From: MirceaKitsune Date: Sun, 17 Apr 2011 13:29:20 +0000 (+0300) Subject: Move the netradiant and fteqcc sources X-Git-Url: http://de.git.xonotic.org/?p=voretournament%2Fvoretournament.git;a=commitdiff_plain;h=65bc0125990fdbce3dd3232d61f1554cb7e317cb Move the netradiant and fteqcc sources --- diff --git a/misc/mediasource/extra/fteqcc-src/LICENSE b/misc/mediasource/extra/fteqcc-src/LICENSE deleted file mode 100644 index 2f3289af..00000000 --- a/misc/mediasource/extra/fteqcc-src/LICENSE +++ /dev/null @@ -1,87 +0,0 @@ -GNU GENERAL PUBLIC LICENSE -Version 2, June 1991 - -Copyright (C) 1989, 1991 Free Software Foundation, Inc. -59 Temple Place - Suite 330, Boston, MA 02111-1307, USA - -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. -Preamble -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. - -To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. - -For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. - -We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. - -Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. - -Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. - -The precise terms and conditions for copying, distribution and modification follow. - -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. - -1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - -a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. - -b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. - -c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: - -a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, - -b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, - -c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) -The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. -If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. - -4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. - -6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. - -7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. - -10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - -END OF TERMS AND CONDITIONS diff --git a/misc/mediasource/extra/fteqcc-src/Makefile b/misc/mediasource/extra/fteqcc-src/Makefile deleted file mode 100644 index 40a721c6..00000000 --- a/misc/mediasource/extra/fteqcc-src/Makefile +++ /dev/null @@ -1,89 +0,0 @@ -COMMON_OBJS=comprout.o hash.o qcc_cmdlib.o qcd_main.o -QCC_OBJS=qccmain.o qcc_pr_comp.o qcc_pr_lex.o -VM_OBJS=pr_exec.o pr_edict.o pr_multi.o initlib.o qcdecomp.o -GTKGUI_OBJS=qcc_gtk.o qccguistuff.o -WIN32GUI_OBJS=qccgui.o qccguistuff.o -TUI_OBJS=qcctui.o -LIB_OBJS= - -CC=gcc -Wall - -all: qcc - -USEGUI_CFLAGS= -# set to -DUSEGUI when compiling the GUI -BASE_CFLAGS=-ggdb $(USEGUI_CFLAGS) - -BASE_LDFLAGS=-s -# set to "" for debugging - -DO_CC=$(CC) $(BASE_CFLAGS) -o $@ -c $< $(CFLAGS) - -lib: - -R_win_nocyg: $(QCC_OBJS) $(COMMON_OBJS) $(WIN32GUI_OBJS) - $(CC) $(BASE_CFLAGS) -o fteqcc.exe -O3 $(BASE_LDFLAGS) $(QCC_OBJS) $(COMMON_OBJS) $(WIN32GUI_OBJS) -mno-cygwin -mwindows -lcomctl32 -R_nocyg: $(QCC_OBJS) $(COMMON_OBJS) $(WIN32GUI_OBJS) - $(CC) $(BASE_CFLAGS) -o fteqcc.exe -O3 $(BASE_LDFLAGS) $(QCC_OBJS) $(COMMON_OBJS) $(WIN32GUI_OBJS) -mno-cygwin -lcomctl32 -R_win: $(QCC_OBJS) $(COMMON_OBJS) $(WIN32GUI_OBJS) - $(CC) $(BASE_CFLAGS) -o fteqcc.exe -O3 $(BASE_LDFLAGS) $(QCC_OBJS) $(COMMON_OBJS) $(WIN32GUI_OBJS) -mwindows -lcomctl32 - -win_nocyg: - $(MAKE) USEGUI_CFLAGS="-DUSEGUI -DQCCONLY" R_win_nocyg -nocyg: - $(MAKE) USEGUI_CFLAGS="-DUSEGUI -DQCCONLY" R_nocyg -win: - $(MAKE) USEGUI_CFLAGS="-DUSEGUI -DQCCONLY" R_win - -R_qcc: $(QCC_OBJS) $(COMMON_OBJS) $(TUI_OBJS) - $(CC) $(BASE_CFLAGS) -o fteqcc.bin -O3 $(BASE_LDFLAGS) $(QCC_OBJS) $(TUI_OBJS) $(COMMON_OBJS) -qcc: - $(MAKE) USEGUI_CFLAGS="" R_qcc - -qccmain.o: qccmain.c qcc.h - $(DO_CC) - -qcc_cmdlib.o: qcc_cmdlib.c qcc.h - $(DO_CC) - -qcc_pr_comp.o: qcc_pr_comp.c qcc.h - $(DO_CC) - -qcc_pr_lex.o: qcc_pr_lex.c qcc.h - $(DO_CC) - -comprout.o: comprout.c qcc.h - $(DO_CC) - -hash.o: hash.c qcc.h - $(DO_CC) - -qcd_main.o: qcd_main.c qcc.h - $(DO_CC) - -qccguistuff.o: qccguistuff.c qcc.h - $(DO_CC) - -qcc_gtk.o: qcc_gtk.c qcc.h - $(DO_CC) `pkg-config --cflags gtk+-2.0` - -R_gtkgui: $(QCC_OBJS) $(COMMON_OBJS) $(GTKGUI_OBJS) - $(CC) $(BASE_CFLAGS) $(USEGUI_CFLAGS) -o fteqccgui.bin -O3 $(GTKGUI_OBJS) $(QCC_OBJS) $(COMMON_OBJS) `pkg-config --libs gtk+-2.0` -gtkgui: - $(MAKE) USEGUI_CFLAGS="-DUSEGUI -DQCCONLY" R_gtkgui - -clean: - $(RM) fteqcc.bin fteqcc.exe $(QCC_OBJS) $(COMMON_OBJS) $(VM_OBJS) $(GTKGUI_OBJS) $(WIN32GUI_OBJS) $(TUI_OBJS) - -qcvm.so: $(QCC_OBJS) $(VM_OBJS) $(COMMON_OBJS) - $(CC) $(BASE_CFLAGS) -o $@ -O3 $(BASE_LDFLAGS) $(QCC_OBJS) $(VM_OBJS) $(COMMON_OBJS) -shared - - -test.o: test.c - $(DO_CC) - -testapp.bin: qcvm.so test.o - $(CC) $(BASE_CFLAGS) -o testapp.bin -O3 $(BASE_LDFLAGS) qcvm.so test.o - -regressiontest: testapp.bin - ./testapp.bin regression.dat -srcfile regression.src diff --git a/misc/mediasource/extra/fteqcc-src/cmdlib.h b/misc/mediasource/extra/fteqcc-src/cmdlib.h deleted file mode 100644 index 768d899a..00000000 --- a/misc/mediasource/extra/fteqcc-src/cmdlib.h +++ /dev/null @@ -1,93 +0,0 @@ -// cmdlib.h - -#ifndef __CMDLIB__ -#define __CMDLIB__ - -#include "progsint.h" - -/*#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef NeXT -#include -#endif -*/ - -// the dec offsetof macro doesn't work very well... -#define myoffsetof(type,identifier) ((size_t)&((type *)NULL)->identifier) - - -// set these before calling CheckParm -extern int myargc; -extern char **myargv; - -//char *strupr (char *in); -//char *strlower (char *in); -int QCC_filelength (int handle); -int QCC_tell (int handle); - -int QC_strcasecmp (const char *s1, const char *s2); - -#ifdef _MSC_VER -#define QC_vsnprintf _vsnprintf -#else -#define QC_vsnprintf vsnprintf -#endif - -#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) - #ifndef LIKEPRINTF - #define LIKEPRINTF(x) __attribute__((format(printf,x,x+1))) - #endif -#endif -#ifndef LIKEPRINTF -#define LIKEPRINTF(x) -#endif - -double I_FloatTime (void); - -void VARGS QCC_Error (int errortype, const char *error, ...) LIKEPRINTF(2); -int CheckParm (char *check); - - -int SafeOpenWrite (char *filename, int maxsize); -int SafeOpenRead (char *filename); -void SafeRead (int handle, void *buffer, long count); -void SafeWrite (int handle, void *buffer, long count); -void SafeClose(int handle); -int SafeSeek(int hand, int ofs, int mode); -void *SafeMalloc (long size); - - -long QCC_LoadFile (char *filename, void **bufferptr); -void QCC_SaveFile (char *filename, void *buffer, long count); - -void DefaultExtension (char *path, char *extension); -void DefaultPath (char *path, char *basepath); -void StripFilename (char *path); -void StripExtension (char *path); - -void ExtractFilePath (char *path, char *dest); -void ExtractFileBase (char *path, char *dest); -void ExtractFileExtension (char *path, char *dest); - -long ParseNum (char *str); - - -char *QCC_COM_Parse (char *data); -char *QCC_COM_Parse2 (char *data); - -extern char qcc_token[1024]; -extern int qcc_eof; - - - -#endif diff --git a/misc/mediasource/extra/fteqcc-src/comprout.c b/misc/mediasource/extra/fteqcc-src/comprout.c deleted file mode 100644 index a2a7a3bd..00000000 --- a/misc/mediasource/extra/fteqcc-src/comprout.c +++ /dev/null @@ -1,252 +0,0 @@ -//compile routines - -#include "qcc.h" -#undef progfuncs - -char errorfile[128]; -int errorline; - -progfuncs_t *qccprogfuncs; - -#include - -extern int qcc_compileactive; -jmp_buf qcccompileerror; -char qcc_gamedir[128]; -void QCC_PR_ResetErrorScope(void); - - - -#ifdef MINIMAL - -#else - -int qccalloced; -int qcchunksize; -char *qcchunk; -void *qccHunkAlloc(size_t mem) -{ - mem = (mem + 7)&~7; - - qccalloced+=mem; - if (qccalloced > qcchunksize) - QCC_Error(ERR_INTERNAL, "Compile hunk was filled"); - - memset(qcchunk+qccalloced-mem, 0, mem); - return qcchunk+qccalloced-mem; -} -void qccClearHunk(void) -{ - if (qcchunk) - { - free(qcchunk); - qcchunk=NULL; - } -} -int qccpersisthunk; -void PostCompile(void) -{ - if (!qccpersisthunk) - qccClearHunk(); - - if (asmfile) - { - fclose(asmfile); - asmfile = NULL; - } -} -pbool PreCompile(void) -{ - QCC_PR_ResetErrorScope(); - - qccClearHunk(); - strcpy(qcc_gamedir, ""); - qcchunk = malloc(qcchunksize=128*1024*1024); - while(!qcchunk && qcchunksize > 8*1024*1024) - { - qcchunksize /= 2; - qcchunk = malloc(qcchunksize); - } - qccalloced=0; - - return !!qcchunk; -} - -void QCC_main (int argc, char **argv); -void QCC_ContinueCompile(void); -void QCC_FinishCompile(void); - -int comp_nump;char **comp_parms; -//void Editor(char *fname, int line, int numparms, char **compileparms); -pbool CompileParams(progfuncs_t *progfuncs, int doall, int nump, char **parms) -{ - comp_nump = nump; - comp_parms = parms; - *errorfile = '\0'; - qccprogfuncs = progfuncs; - if (setjmp(qcccompileerror)) - { - PostCompile(); - if (*errorfile) - { - if (!externs->useeditor) - printf("Error in %s on line %i\n", errorfile, errorline); - else - externs->useeditor(progfuncs, errorfile, errorline, nump, parms); - } - return false; - } - - if (!PreCompile()) - return false; - QCC_main(nump, parms); - - while(qcc_compileactive) - QCC_ContinueCompile(); - - PostCompile(); - - return true; -} -int Comp_Begin(progfuncs_t *progfuncs, int nump, char **parms) -{ - comp_nump = nump; - comp_parms = parms; - qccprogfuncs = progfuncs; - *errorfile = '\0'; - if (setjmp(qcccompileerror)) - { - PostCompile(); - if (*errorfile) - externs->useeditor(progfuncs, errorfile, errorline, nump, parms); - return false; - } - - if (!PreCompile()) - return false; - QCC_main(nump, parms); - - return true; -} -int Comp_Continue(progfuncs_t *progfuncs) -{ - qccprogfuncs = progfuncs; - if (setjmp(qcccompileerror)) - { - PostCompile(); - if (*errorfile && externs->useeditor) - externs->useeditor(progfuncs, errorfile, errorline, comp_nump, comp_parms); - return false; - } - - if (qcc_compileactive) - QCC_ContinueCompile(); - else - { - PostCompile(); - - if (*errorfile && externs->useeditor) - externs->useeditor(progfuncs, errorfile, errorline, comp_nump, comp_parms); - - return false; - } - - return true; -} -#endif -pbool CompileFile(progfuncs_t *progfuncs, char *filename) -{ -#ifdef MINIMAL - return false; -#else - char srcfile[32]; - char newname[32]; - static char *p[5]; - int parms; - char *s, *s2; - - p[0] = NULL; - parms = 1; - - strcpy(newname, filename); - s = newname; - if (strchr(s+1, '/')) - { - while(1) - { - s2 = strchr(s+1, '/'); - if (!s2) - { - *s = '\0'; - break; - } - s = s2; - } - p[parms] = "-src"; - p[parms+1] = newname; - parms+=2; - - strcpy(srcfile, s+1); - srcfile[strlen(srcfile)-4] = '\0'; - strcat(srcfile, ".src"); - - if (externs->FileSize(qcva("%s/%s", newname, srcfile))>0) - { - p[parms] = "-srcfile"; - p[parms+1] = srcfile; - parms+=2; - } - } - else - { - p[parms] = "-srcfile"; - p[parms+1] = newname; - newname[strlen(newname)-4] = '\0'; - strcat(newname, ".src"); - parms+=2; - } -// p[2][strlen(p[2])-4] = '\0'; -// strcat(p[2], "/"); - - while (!CompileParams(progfuncs, true, parms, p)) - { - return false; - } - return true; -#endif -} - -int QC_strncasecmp(const char *s1, const char *s2, int n) -{ - int c1, c2; - - while (1) - { - 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 - } - if (!c1) - return 0; // strings are equal - } - - return -1; -} - -void editbadfile(char *fname, int line) -{ - strcpy(errorfile, fname); - errorline = line; -} - diff --git a/misc/mediasource/extra/fteqcc-src/execloop.h b/misc/mediasource/extra/fteqcc-src/execloop.h deleted file mode 100644 index 365c93a4..00000000 --- a/misc/mediasource/extra/fteqcc-src/execloop.h +++ /dev/null @@ -1,1141 +0,0 @@ -//qc execution code. -//we have two conditions. -//one allows us to debug and trace through our code, the other doesn't. - -//hopefully, the compiler will do a great job at optimising this code for us, where required. -//if it dosn't, then bum. - -//the general overhead should be reduced significantly, and I would be supprised if it did run slower. - -//run away loops are checked for ONLY on gotos and function calls. This might give a poorer check, but it will run faster overall. - -//Appears to work fine. - -#if INTSIZE == 16 -#define cont cont16 -#define reeval reeval16 -#define st st16 -#define pr_statements pr_statements16 -#define fakeop fakeop16 -#define dstatement_t dstatement16_t -#define sofs signed short -#define uofs unsigned short -#elif INTSIZE == 32 -#define cont cont32 -#define reeval reeval32 -#define st st32 -#define pr_statements pr_statements32 -#define fakeop fakeop32 -#define dstatement_t dstatement32_t -#define sofs signed int -#define uofs unsigned int -#elif INTSIZE == 24 -#error INTSIZE should be set to 32. -#else -#error Bad cont size -#endif - -#define ENGINEPOINTER(p) ((char*)(p) - progfuncs->stringtable) -#define QCPOINTER(p) (eval_t *)(p->_int+progfuncs->stringtable) -#define QCPOINTERM(p) (eval_t *)((p)+progfuncs->stringtable) - -//rely upon just st -{ -#ifdef DEBUGABLE -cont: //last statement may have been a breakpoint - s = st-pr_statements; - s+=1; - s=ShowStep(progfuncs, s); - st = pr_statements + s; - -reeval: -#else - st++; -#endif - - switch (st->op) - { - case OP_ADD_F: - OPC->_float = OPA->_float + OPB->_float; - break; - case OP_ADD_V: - OPC->_vector[0] = OPA->_vector[0] + OPB->_vector[0]; - OPC->_vector[1] = OPA->_vector[1] + OPB->_vector[1]; - OPC->_vector[2] = OPA->_vector[2] + OPB->_vector[2]; - break; - - case OP_SUB_F: - OPC->_float = OPA->_float - OPB->_float; - break; - case OP_SUB_V: - OPC->_vector[0] = OPA->_vector[0] - OPB->_vector[0]; - OPC->_vector[1] = OPA->_vector[1] - OPB->_vector[1]; - OPC->_vector[2] = OPA->_vector[2] - OPB->_vector[2]; - break; - - case OP_MUL_F: - OPC->_float = OPA->_float * OPB->_float; - break; - case OP_MUL_V: - OPC->_float = OPA->_vector[0]*OPB->_vector[0] - + OPA->_vector[1]*OPB->_vector[1] - + OPA->_vector[2]*OPB->_vector[2]; - break; - case OP_MUL_FV: - OPC->_vector[0] = OPA->_float * OPB->_vector[0]; - OPC->_vector[1] = OPA->_float * OPB->_vector[1]; - OPC->_vector[2] = OPA->_float * OPB->_vector[2]; - break; - case OP_MUL_VF: - OPC->_vector[0] = OPB->_float * OPA->_vector[0]; - OPC->_vector[1] = OPB->_float * OPA->_vector[1]; - OPC->_vector[2] = OPB->_float * OPA->_vector[2]; - break; - - case OP_DIV_F: - OPC->_float = OPA->_float / OPB->_float; - break; - case OP_DIV_VF: - OPC->_vector[0] = OPB->_float / OPA->_vector[0]; - OPC->_vector[1] = OPB->_float / OPA->_vector[1]; - OPC->_vector[2] = OPB->_float / OPA->_vector[2]; - break; - - case OP_BITAND: - OPC->_float = (float)((int)OPA->_float & (int)OPB->_float); - break; - - case OP_BITOR: - OPC->_float = (float)((int)OPA->_float | (int)OPB->_float); - break; - - - case OP_GE: - OPC->_float = (float)(OPA->_float >= OPB->_float); - break; - case OP_GE_I: - OPC->_int = (int)(OPA->_int >= OPB->_int); - break; - case OP_GE_IF: - OPC->_float = (float)(OPA->_int >= OPB->_float); - break; - case OP_GE_FI: - OPC->_float = (float)(OPA->_float >= OPB->_int); - break; - - case OP_LE: - OPC->_float = (float)(OPA->_float <= OPB->_float); - break; - case OP_LE_I: - OPC->_int = (int)(OPA->_int <= OPB->_int); - break; - case OP_LE_IF: - OPC->_float = (float)(OPA->_int <= OPB->_float); - break; - case OP_LE_FI: - OPC->_float = (float)(OPA->_float <= OPB->_int); - break; - - case OP_GT: - OPC->_float = (float)(OPA->_float > OPB->_float); - break; - case OP_GT_I: - OPC->_int = (int)(OPA->_int > OPB->_int); - break; - case OP_GT_IF: - OPC->_float = (float)(OPA->_int > OPB->_float); - break; - case OP_GT_FI: - OPC->_float = (float)(OPA->_float > OPB->_int); - break; - - case OP_LT: - OPC->_float = (float)(OPA->_float < OPB->_float); - break; - case OP_LT_I: - OPC->_int = (int)(OPA->_int < OPB->_int); - break; - case OP_LT_IF: - OPC->_float = (float)(OPA->_int < OPB->_float); - break; - case OP_LT_FI: - OPC->_float = (float)(OPA->_float < OPB->_int); - break; - - case OP_AND: - OPC->_float = (float)(OPA->_float && OPB->_float); - break; - case OP_OR: - OPC->_float = (float)(OPA->_float || OPB->_float); - break; - - case OP_NOT_F: - OPC->_float = (float)(!OPA->_float); - break; - case OP_NOT_V: - OPC->_float = (float)(!OPA->_vector[0] && !OPA->_vector[1] && !OPA->_vector[2]); - break; - case OP_NOT_S: - OPC->_float = (float)(!(OPA->string) || !*PR_StringToNative(progfuncs, OPA->string)); - break; - case OP_NOT_FNC: - OPC->_float = (float)(!(OPA->function & ~0xff000000)); - break; - case OP_NOT_ENT: - OPC->_float = (float)(PROG_TO_EDICT(progfuncs, OPA->edict) == (edictrun_t *)sv_edicts); - break; - - case OP_EQ_F: - OPC->_float = (float)(OPA->_float == OPB->_float); - break; - case OP_EQ_IF: - OPC->_float = (float)(OPA->_int == OPB->_float); - break; - case OP_EQ_FI: - OPC->_float = (float)(OPA->_float == OPB->_int); - break; - - - case OP_EQ_V: - OPC->_float = (float)((OPA->_vector[0] == OPB->_vector[0]) && - (OPA->_vector[1] == OPB->_vector[1]) && - (OPA->_vector[2] == OPB->_vector[2])); - break; - case OP_EQ_S: - if (OPA->string==OPB->string) - OPC->_float = true; - else if (!OPA->string) - { - if (!OPB->string || !*PR_StringToNative(progfuncs, OPB->string)) - OPC->_float = true; - else - OPC->_float = false; - } - else if (!OPB->string) - { - if (!OPA->string || !*PR_StringToNative(progfuncs, OPA->string)) - OPC->_float = true; - else - OPC->_float = false; - } - else - OPC->_float = (float)(!strcmp(PR_StringToNative(progfuncs, OPA->string),PR_StringToNative(progfuncs, OPB->string))); - break; - case OP_EQ_E: - OPC->_float = (float)(OPA->_int == OPB->_int); - break; - case OP_EQ_FNC: - OPC->_float = (float)(OPA->function == OPB->function); - break; - - - case OP_NE_F: - OPC->_float = (float)(OPA->_float != OPB->_float); - break; - case OP_NE_V: - OPC->_float = (float)((OPA->_vector[0] != OPB->_vector[0]) || - (OPA->_vector[1] != OPB->_vector[1]) || - (OPA->_vector[2] != OPB->_vector[2])); - break; - case OP_NE_S: - if (OPA->string==OPB->string) - OPC->_float = false; - else if (!OPA->string) - { - if (!OPB->string || !*(PR_StringToNative(progfuncs, OPB->string))) - OPC->_float = false; - else - OPC->_float = true; - } - else if (!OPB->string) - { - if (!OPA->string || !*PR_StringToNative(progfuncs, OPA->string)) - OPC->_float = false; - else - OPC->_float = true; - } - else - OPC->_float = (float)(strcmp(PR_StringToNative(progfuncs, OPA->string),PR_StringToNative(progfuncs, OPB->string))); - break; - case OP_NE_E: - OPC->_float = (float)(OPA->_int != OPB->_int); - break; - case OP_NE_FNC: - OPC->_float = (float)(OPA->function != OPB->function); - break; - -//================== - case OP_STORE_IF: - OPB->_float = (float)OPA->_int; - break; - case OP_STORE_FI: - OPB->_int = (int)OPA->_float; - break; - - case OP_STORE_F: - case OP_STORE_ENT: - case OP_STORE_FLD: // integers - case OP_STORE_S: - case OP_STORE_I: - case OP_STORE_FNC: // pointers - case OP_STORE_P: - OPB->_int = OPA->_int; - break; - case OP_STORE_V: - OPB->_vector[0] = OPA->_vector[0]; - OPB->_vector[1] = OPA->_vector[1]; - OPB->_vector[2] = OPA->_vector[2]; - break; - - //store a value to a pointer - case OP_STOREP_IF: - if ((unsigned int)OPB->_int >= addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", progfuncs->stringtable + pr_xfunction->s_name); - } - ptr = QCPOINTER(OPB); - ptr->_float = (float)OPA->_int; - break; - case OP_STOREP_FI: - if ((unsigned int)OPB->_int >= addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", progfuncs->stringtable + pr_xfunction->s_name); - } - ptr = QCPOINTER(OPB); - ptr->_int = (int)OPA->_float; - break; - case OP_STOREP_I: - if ((unsigned int)OPB->_int >= addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", progfuncs->stringtable + pr_xfunction->s_name); - } - ptr = QCPOINTER(OPB); - ptr->_int = OPA->_int; - break; - case OP_STOREP_F: - case OP_STOREP_ENT: - case OP_STOREP_FLD: // integers - case OP_STOREP_S: - case OP_STOREP_FNC: // pointers - if ((unsigned int)OPB->_int >= addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", progfuncs->stringtable + pr_xfunction->s_name); - } - ptr = QCPOINTER(OPB); - ptr->_int = OPA->_int; - break; - case OP_STOREP_V: - if ((unsigned int)OPB->_int >= addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", progfuncs->stringtable + pr_xfunction->s_name); - } - ptr = QCPOINTER(OPB); - ptr->_vector[0] = OPA->_vector[0]; - ptr->_vector[1] = OPA->_vector[1]; - ptr->_vector[2] = OPA->_vector[2]; - break; - - case OP_STOREP_C: //store character in a string - if ((unsigned int)OPB->_int >= addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", progfuncs->stringtable + pr_xfunction->s_name); - } - ptr = QCPOINTER(OPB); - *(unsigned char *)ptr = (char)OPA->_float; - break; - - case OP_MULSTORE_F: // f *= f - OPB->_float *= OPA->_float; - break; - case OP_MULSTORE_V: // v *= f - OPB->_vector[0] *= OPA->_float; - OPB->_vector[1] *= OPA->_float; - OPB->_vector[2] *= OPA->_float; - break; - case OP_MULSTOREP_F: // e.f *= f - if ((unsigned int)OPB->_int >= addressableused) - { - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "bad pointer write in %s", progfuncs->stringtable + pr_xfunction->s_name); - } - ptr = QCPOINTER(OPB); - OPC->_float = (ptr->_float *= OPA->_float); - break; - case OP_MULSTOREP_V: // e.v *= f - ptr = QCPOINTER(OPB); - OPC->_vector[0] = (ptr->_vector[0] *= OPA->_float); - OPC->_vector[0] = (ptr->_vector[1] *= OPA->_float); - OPC->_vector[0] = (ptr->_vector[2] *= OPA->_float); - break; - - case OP_DIVSTORE_F: // f /= f - OPB->_float /= OPA->_float; - break; - case OP_DIVSTOREP_F: // e.f /= f - ptr = QCPOINTER(OPB); - OPC->_float = (ptr->_float /= OPA->_float); - break; - - case OP_ADDSTORE_F: // f += f - OPB->_float += OPA->_float; - break; - case OP_ADDSTORE_V: // v += v - OPB->_vector[0] += OPA->_vector[0]; - OPB->_vector[1] += OPA->_vector[1]; - OPB->_vector[2] += OPA->_vector[2]; - break; - case OP_ADDSTOREP_F: // e.f += f - ptr = QCPOINTER(OPB); - OPC->_float = (ptr->_float += OPA->_float); - break; - case OP_ADDSTOREP_V: // e.v += v - ptr = QCPOINTER(OPB); - OPC->_vector[0] = (ptr->_vector[0] += OPA->_vector[0]); - OPC->_vector[1] = (ptr->_vector[1] += OPA->_vector[1]); - OPC->_vector[2] = (ptr->_vector[2] += OPA->_vector[2]); - break; - - case OP_SUBSTORE_F: // f -= f - OPB->_float -= OPA->_float; - break; - case OP_SUBSTORE_V: // v -= v - OPB->_vector[0] -= OPA->_vector[0]; - OPB->_vector[1] -= OPA->_vector[1]; - OPB->_vector[2] -= OPA->_vector[2]; - break; - case OP_SUBSTOREP_F: // e.f -= f - ptr = QCPOINTER(OPB); - OPC->_float = (ptr->_float -= OPA->_float); - break; - case OP_SUBSTOREP_V: // e.v -= v - ptr = QCPOINTER(OPB); - OPC->_vector[0] = (ptr->_vector[0] -= OPA->_vector[0]); - OPC->_vector[1] = (ptr->_vector[1] -= OPA->_vector[1]); - OPC->_vector[2] = (ptr->_vector[2] -= OPA->_vector[2]); - break; - - - //get a pointer to a field var - case OP_ADDRESS: - if ((unsigned)OPA->edict >= (unsigned)maxedicts) - { -#ifndef DEBUGABLE - pr_trace++; - printf("OP_ADDRESS references invalid entity in %s", progfuncs->stringtable + pr_xfunction->s_name); - st--; - goto cont; -#else - PR_RunError (progfuncs, "OP_ADDRESS references invalid entity in %s", PR_StringToNative(progfuncs, pr_xfunction->s_name)); -#endif - } - ed = PROG_TO_EDICT(progfuncs, OPA->edict); -#ifdef PARANOID - NUM_FOR_EDICT(ed); // make sure it's in range -#endif - if (!ed || ed->readonly) - { - pr_xstatement = st-pr_statements; -#ifndef DEBUGABLE - //boot it over to the debugger - pr_trace++; - printf("assignment to read-only entity in %s", progfuncs->stringtable + pr_xfunction->s_name); - st--; - goto cont; -#else - { - ddef16_t *d16; - fdef_t *f; - d16 = ED_GlobalAtOfs16(progfuncs, st->a); - f = ED_FieldAtOfs(progfuncs, OPB->_int + progfuncs->fieldadjust); - PR_RunError (progfuncs, "assignment to read-only entity in %s (%s.%s)", PR_StringToNative(progfuncs, pr_xfunction->s_name), PR_StringToNative(progfuncs, d16->s_name), f?f->name:NULL); - } -#endif - } - -//Whilst the next block would technically be correct, we don't use it as it breaks too many quake mods. -// if (ed->isfree) -// { -// pr_xstatement = st-pr_statements; -// PR_RunError (progfuncs, "assignment to free entitiy in %s", progfuncs->stringtable + pr_xfunction->s_name); -// } - OPC->_int = ENGINEPOINTER((((int *)edvars(ed)) + OPB->_int + progfuncs->fieldadjust)); - break; - - //load a field to a value - case OP_LOAD_I: - case OP_LOAD_F: - case OP_LOAD_FLD: - case OP_LOAD_ENT: - case OP_LOAD_S: - case OP_LOAD_FNC: - if ((unsigned)OPA->edict >= (unsigned)maxedicts) - PR_RunError (progfuncs, "OP_LOAD references invalid entity in %s", progfuncs->stringtable + pr_xfunction->s_name); - ed = PROG_TO_EDICT(progfuncs, OPA->edict); -#ifdef PARANOID - NUM_FOR_EDICT(ed); // make sure it's in range -#endif - ptr = (eval_t *)(((int *)edvars(ed)) + OPB->_int + progfuncs->fieldadjust); - OPC->_int = ptr->_int; - break; - - case OP_LOAD_V: - if ((unsigned)OPA->edict >= (unsigned)maxedicts) - PR_RunError (progfuncs, "OP_LOAD_V references invalid entity in %s", progfuncs->stringtable + pr_xfunction->s_name); - ed = PROG_TO_EDICT(progfuncs, OPA->edict); -#ifdef PARANOID - NUM_FOR_EDICT(ed); // make sure it's in range -#endif - ptr = (eval_t *)(((int *)edvars(ed)) + OPB->_int + progfuncs->fieldadjust); - OPC->_vector[0] = ptr->_vector[0]; - OPC->_vector[1] = ptr->_vector[1]; - OPC->_vector[2] = ptr->_vector[2]; - break; - -//================== - - case OP_IFNOT_S: - RUNAWAYCHECK(); - if (!OPA->string || !PR_StringToNative(progfuncs, OPA->string)) - st += (sofs)st->b - 1; // offset the s++ - break; - - case OP_IFNOT_F: - RUNAWAYCHECK(); - if (!OPA->_float) - st += (sofs)st->b - 1; // offset the s++ - break; - - case OP_IFNOT: - RUNAWAYCHECK(); - if (!OPA->_int) - st += (sofs)st->b - 1; // offset the s++ - break; - - case OP_IF_S: - RUNAWAYCHECK(); - if (OPA->string && PR_StringToNative(progfuncs, OPA->string)) - st += (sofs)st->b - 1; // offset the s++ - break; - - case OP_IF_F: - RUNAWAYCHECK(); - if (OPA->_int) - st += (sofs)st->b - 1; // offset the s++ - break; - - case OP_IF: - RUNAWAYCHECK(); - if (OPA->_int) - st += (sofs)st->b - 1; // offset the s++ - break; - - case OP_GOTO: - RUNAWAYCHECK(); - st += (sofs)st->a - 1; // offset the s++ - break; - - case OP_CALL8H: - case OP_CALL7H: - case OP_CALL6H: - case OP_CALL5H: - case OP_CALL4H: - case OP_CALL3H: - case OP_CALL2H: - G_VECTOR(OFS_PARM1)[0] = OPC->_vector[0]; - G_VECTOR(OFS_PARM1)[1] = OPC->_vector[1]; - G_VECTOR(OFS_PARM1)[2] = OPC->_vector[2]; - case OP_CALL1H: - G_VECTOR(OFS_PARM0)[0] = OPB->_vector[0]; - G_VECTOR(OFS_PARM0)[1] = OPB->_vector[1]; - G_VECTOR(OFS_PARM0)[2] = OPB->_vector[2]; - - case OP_CALL8: - case OP_CALL7: - case OP_CALL6: - case OP_CALL5: - case OP_CALL4: - case OP_CALL3: - case OP_CALL2: - case OP_CALL1: - case OP_CALL0: - RUNAWAYCHECK(); - pr_xstatement = st-pr_statements; - - - if (st->op > OP_CALL8) - pr_argc = st->op - (OP_CALL1H-1); - else - pr_argc = st->op - OP_CALL0; - fnum = OPA->function; - if ((fnum & ~0xff000000)==0) - { - pr_trace++; - printf("NULL function from qc (%s).\n", progfuncs->stringtable + pr_xfunction->s_name); -#ifndef DEBUGABLE - goto cont; -#endif - break; - } -/* -{ - static char buffer[1024*1024*8]; - int size = sizeof buffer; - progfuncs->save_ents(progfuncs, buffer, &size, 0); -}*/ - - - p=pr_typecurrent; -//about to switch. needs caching. - - //if it's an external call, switch now (before any function pointers are used) - PR_MoveParms(progfuncs, (fnum & 0xff000000)>>24, p); - PR_SwitchProgs(progfuncs, (fnum & 0xff000000)>>24); - - newf = &pr_functions[fnum & ~0xff000000]; - - if (newf->first_statement < 0) - { // negative statements are built in functions - -if (pr_typecurrent != 0) -{ - PR_MoveParms(progfuncs, 0, pr_typecurrent); - PR_SwitchProgs(progfuncs, 0); -} - i = -newf->first_statement; -// p = pr_typecurrent; - progfuncs->lastcalledbuiltinnumber = i; - if (i < externs->numglobalbuiltins) - { - prinst->numtempstringsstack = prinst->numtempstrings; - (*externs->globalbuiltins[i]) (progfuncs, (struct globalvars_s *)current_progstate->globals); - if (prinst->continuestatement!=-1) - { - st=&pr_statements[prinst->continuestatement]; - prinst->continuestatement=-1; - break; - } - } - else - { - i -= externs->numglobalbuiltins; - if (i >= current_progstate->numbuiltins) - { -// if (newf->first_statement == -0x7fffffff) -// ((builtin_t)newf->profile) (progfuncs, (struct globalvars_s *)current_progstate->globals); -// else - PR_RunError (progfuncs, "Bad builtin call number - %i", -newf->first_statement); - } - else - current_progstate->builtins [i] (progfuncs, (struct globalvars_s *)current_progstate->globals); - } - PR_MoveParms(progfuncs, p, pr_typecurrent); -// memcpy(&pr_progstate[p].globals[OFS_RETURN], ¤t_progstate->globals[OFS_RETURN], sizeof(vec3_t)); - PR_SwitchProgs(progfuncs, (progsnum_t)p); - -//#ifndef DEBUGABLE //decide weather non debugger wants to start debugging. - s = st-pr_statements; - goto restart; -//#endif -// break; - } -// PR_MoveParms((OPA->function & 0xff000000)>>24, pr_typecurrent); -// PR_SwitchProgs((OPA->function & 0xff000000)>>24); - s = PR_EnterFunction (progfuncs, newf, p); - st = &pr_statements[s]; - - goto restart; -// break; - - case OP_DONE: - case OP_RETURN: - - RUNAWAYCHECK(); - - pr_globals[OFS_RETURN] = pr_globals[st->a]; - pr_globals[OFS_RETURN+1] = pr_globals[st->a+1]; - pr_globals[OFS_RETURN+2] = pr_globals[st->a+2]; -/* -{ - static char buffer[1024*1024*8]; - int size = sizeof buffer; - progfuncs->save_ents(progfuncs, buffer, &size, 0); -} -*/ - s = PR_LeaveFunction (progfuncs); - st = &pr_statements[s]; - if (pr_depth == prinst->exitdepth) - { - return; // all done - } - goto restart; -// break; - - case OP_STATE: - externs->stateop(progfuncs, OPA->_float, OPB->function); - break; - - case OP_ADD_I: - OPC->_int = OPA->_int + OPB->_int; - break; - case OP_ADD_FI: - OPC->_float = OPA->_float + (float)OPB->_int; - break; - case OP_ADD_IF: - OPC->_float = (float)OPA->_int + OPB->_float; - break; - - case OP_SUB_I: - OPC->_int = OPA->_int - OPB->_int; - break; - case OP_SUB_FI: - OPC->_float = OPA->_float - (float)OPB->_int; - break; - case OP_SUB_IF: - OPC->_float = (float)OPA->_int - OPB->_float; - break; - - case OP_CONV_ITOF: - OPC->_float = (float)OPA->_int; - break; - case OP_CONV_FTOI: - OPC->_int = (int)OPA->_float; - break; - - case OP_CP_ITOF: - ptr = (eval_t *)(((qbyte *)sv_edicts) + OPA->_int); - OPC->_float = (float)ptr->_int; - break; - - case OP_CP_FTOI: - ptr = (eval_t *)(((qbyte *)sv_edicts) + OPA->_int); - OPC->_int = (int)ptr->_float; - break; - - case OP_BITAND_I: - OPC->_int = (OPA->_int & OPB->_int); - break; - - case OP_BITOR_I: - OPC->_int = (OPA->_int | OPB->_int); - break; - - case OP_MUL_I: - OPC->_int = OPA->_int * OPB->_int; - break; - case OP_DIV_I: - if (OPB->_int == 0) //no division by zero allowed... - OPC->_int = 0; - else - OPC->_int = OPA->_int / OPB->_int; - break; - case OP_EQ_I: - OPC->_int = (OPA->_int == OPB->_int); - break; - case OP_NE_I: - OPC->_int = (OPA->_int != OPB->_int); - break; - - - //array/structure reading/riting. - case OP_GLOBALADDRESS: - OPC->_int = ENGINEPOINTER(&OPA->_int + OPB->_int); - break; - case OP_POINTER_ADD: //pointer to 32 bit (remember to *3 for vectors) - OPC->_int = OPA->_int + OPB->_int*4; - break; - - case OP_LOADA_I: - case OP_LOADA_F: - case OP_LOADA_FLD: - case OP_LOADA_ENT: - case OP_LOADA_S: - case OP_LOADA_FNC: - ptr = (eval_t *)(&OPA->_int + OPB->_int); - OPC->_int = ptr->_int; - break; - - case OP_LOADA_V: - ptr = (eval_t *)(&OPA->_int + OPB->_int); - OPC->_vector[0] = ptr->_vector[0]; - OPC->_vector[1] = ptr->_vector[1]; - OPC->_vector[2] = ptr->_vector[2]; - break; - - - - case OP_ADD_SF: //(char*)c = (char*)a + (float)b - OPC->_int = OPA->_int + (int)OPB->_float; - break; - case OP_SUB_S: //(float)c = (char*)a - (char*)b - OPC->_int = OPA->_int - OPB->_int; - break; - case OP_LOADP_C: //load character from a string - ptr = QCPOINTERM(OPA->_int + (int)OPB->_float); - OPC->_float = *(unsigned char *)ptr; - break; - case OP_LOADP_I: - case OP_LOADP_F: - case OP_LOADP_FLD: - case OP_LOADP_ENT: - case OP_LOADP_S: - case OP_LOADP_FNC: - ptr = QCPOINTERM(OPA->_int + OPB->_int); - OPC->_int = ptr->_int; - break; - - case OP_LOADP_V: - ptr = QCPOINTERM(OPA->_int + OPB->_int); - OPC->_vector[0] = ptr->_vector[0]; - OPC->_vector[1] = ptr->_vector[1]; - OPC->_vector[2] = ptr->_vector[2]; - break; - - case OP_XOR_I: - OPC->_int = OPA->_int ^ OPB->_int; - break; - case OP_RSHIFT_I: - OPC->_int = OPA->_int >> OPB->_int; - break; - case OP_LSHIFT_I: - OPC->_int = OPA->_int << OPB->_int; - break; - - - case OP_FETCH_GBL_F: - case OP_FETCH_GBL_S: - case OP_FETCH_GBL_E: - case OP_FETCH_GBL_FNC: - i = (int)OPB->_float; - if(i < 0 || i > ((eval_t *)&glob[st->a-1])->_int) - { - PR_RunError(progfuncs, "array index out of bounds: %s[%d]", PR_GlobalStringNoContents(progfuncs, st->a), i); - } - t = (eval_t *)&pr_globals[(uofs)st->a + i]; - OPC->_int = t->_int; - break; - case OP_FETCH_GBL_V: - i = (int)OPB->_float; - if(i < 0 || i > ((eval_t *)&glob[st->a-1])->_int) - { - PR_RunError(progfuncs, "array index out of bounds: %s[%d]", PR_GlobalStringNoContents(progfuncs, st->a), i); - } - t = (eval_t *)&pr_globals[(uofs)st->a - +((int)OPB->_float)*3]; - OPC->_vector[0] = t->_vector[0]; - OPC->_vector[1] = t->_vector[1]; - OPC->_vector[2] = t->_vector[2]; - break; - - case OP_CSTATE: - externs->cstateop(progfuncs, OPA->_float, OPB->_float, fnum); - break; - - case OP_CWSTATE: - externs->cwstateop(progfuncs, OPA->_float, OPB->_float, fnum); - break; - - case OP_THINKTIME: - externs->thinktimeop(progfuncs, (struct edict_s *)PROG_TO_EDICT(progfuncs, OPA->edict), OPB->_float); - break; - - - case OP_BITSET: // b (+) a - OPB->_float = (float)((int)OPB->_float | (int)OPA->_float); - break; - case OP_BITSETP: // .b (+) a - ptr = QCPOINTER(OPB); - ptr->_float = (float)((int)ptr->_float | (int)OPA->_float); - break; - case OP_BITCLR: // b (-) a - OPB->_float = (float)((int)OPB->_float & ~((int)OPA->_float)); - break; - case OP_BITCLRP: // .b (-) a - ptr = QCPOINTER(OPB); - ptr->_float = (float)((int)ptr->_float & ~((int)OPA->_float)); - break; - - case OP_RAND0: - G_FLOAT(OFS_RETURN) = (rand()&0x7fff)/((float)0x7fff); - break; - case OP_RAND1: - G_FLOAT(OFS_RETURN) = (rand()&0x7fff)/((float)0x7fff)*OPA->_float; - break; - case OP_RAND2: - if(OPA->_float < OPB->_float) - { - G_FLOAT(OFS_RETURN) = OPA->_float+((rand()&0x7fff)/((float)0x7fff) - *(OPB->_float-OPA->_float)); - } - else - { - G_FLOAT(OFS_RETURN) = OPB->_float+((rand()&0x7fff)/((float)0x7fff) - *(OPA->_float-OPB->_float)); - } - break; - case OP_RANDV0: - G_FLOAT(OFS_RETURN+0) = (rand()&0x7fff)/((float)0x7fff); - G_FLOAT(OFS_RETURN+1) = (rand()&0x7fff)/((float)0x7fff); - G_FLOAT(OFS_RETURN+2) = (rand()&0x7fff)/((float)0x7fff); - break; - case OP_RANDV1: - G_FLOAT(OFS_RETURN+0) = (rand()&0x7fff)/((float)0x7fff)*OPA->_vector[0]; - G_FLOAT(OFS_RETURN+1) = (rand()&0x7fff)/((float)0x7fff)*OPA->_vector[1]; - G_FLOAT(OFS_RETURN+2) = (rand()&0x7fff)/((float)0x7fff)*OPA->_vector[2]; - break; - case OP_RANDV2: - for(i = 0; i < 3; i++) - { - if(OPA->_vector[i] < OPB->_vector[i]) - { - G_FLOAT(OFS_RETURN+i) = OPA->_vector[i]+((rand()&0x7fff)/((float)0x7fff) - *(OPB->_vector[i]-OPA->_vector[i])); - } - else - { - G_FLOAT(OFS_RETURN+i) = OPB->_vector[i]+(rand()*(1.0f/RAND_MAX) - *(OPA->_vector[i]-OPB->_vector[i])); - } - } - break; - - - case OP_SWITCH_F: - case OP_SWITCH_V: - case OP_SWITCH_S: - case OP_SWITCH_E: - case OP_SWITCH_FNC: - swtch = OPA; - swtchtype = st->op; - RUNAWAYCHECK(); - st += (sofs)st->b - 1; // offset the st++ - break; - case OP_CASE: - switch(swtchtype) - { - case OP_SWITCH_F: - if (swtch->_float == OPA->_float) - { - RUNAWAYCHECK(); - st += (sofs)st->b-1; // -1 to offset the s++ - } - break; - case OP_SWITCH_E: - case OP_SWITCH_FNC: - if (swtch->_int == OPA->_int) - { - RUNAWAYCHECK(); - st += (sofs)st->b-1; // -1 to offset the s++ - } - break; - case OP_SWITCH_S: - if (swtch->_int == OPA->_int) - { - RUNAWAYCHECK(); - st += (sofs)st->b-1; // -1 to offset the s++ - } - if ((!swtch->_int && PR_StringToNative(progfuncs, OPA->string)) || (!OPA->_int && PR_StringToNative(progfuncs, swtch->string))) //one is null (cannot be not both). - break; - if (!strcmp(PR_StringToNative(progfuncs, swtch->string), PR_StringToNative(progfuncs, OPA->string))) - { - RUNAWAYCHECK(); - st += (sofs)st->b-1; // -1 to offset the s++ - } - break; - case OP_SWITCH_V: - if (swtch->_vector[0] == OPA->_vector[0] && swtch->_vector[1] == OPA->_vector[1] && swtch->_vector[2] == OPA->_vector[2]) - { - RUNAWAYCHECK(); - st += (sofs)st->b-1; // -1 to offset the s++ - } - break; - default: - PR_RunError (progfuncs, "OP_CASE with bad/missing OP_SWITCH %i", swtchtype); - break; - } - break; - case OP_CASERANGE: - switch(swtchtype) - { - case OP_SWITCH_F: - if (swtch->_float >= OPA->_float && swtch->_float <= OPB->_float) - { - RUNAWAYCHECK(); - st += (sofs)st->c-1; // -1 to offset the s++ - } - break; - default: - PR_RunError (progfuncs, "OP_CASERANGE with bad/missing OP_SWITCH %i", swtchtype); - } - break; - - - - - - - - - - case OP_BITAND_IF: - OPC->_int = (OPA->_int & (int)OPB->_float); - break; - case OP_BITOR_IF: - OPC->_int = (OPA->_int | (int)OPB->_float); - break; - case OP_BITAND_FI: - OPC->_int = ((int)OPA->_float & OPB->_int); - break; - case OP_BITOR_FI: - OPC->_int = ((int)OPA->_float | OPB->_int); - break; - - case OP_MUL_IF: - OPC->_float = (OPA->_int * OPB->_float); - break; - case OP_MUL_FI: - OPC->_float = (OPA->_float * OPB->_int); - break; - - case OP_MUL_VI: - OPC->_vector[0] = OPA->_vector[0] * OPB->_int; - OPC->_vector[1] = OPA->_vector[0] * OPB->_int; - OPC->_vector[2] = OPA->_vector[0] * OPB->_int; - break; - case OP_MUL_IV: - OPC->_vector[0] = OPB->_int * OPA->_vector[0]; - OPC->_vector[1] = OPB->_int * OPA->_vector[1]; - OPC->_vector[2] = OPB->_int * OPA->_vector[2]; - break; - - case OP_DIV_IF: - OPC->_float = (OPA->_int / OPB->_float); - break; - case OP_DIV_FI: - OPC->_float = (OPA->_float / OPB->_int); - break; - - case OP_AND_I: - OPC->_int = (OPA->_int && OPB->_int); - break; - case OP_OR_I: - OPC->_int = (OPA->_int || OPB->_int); - break; - - case OP_AND_IF: - OPC->_int = (OPA->_int && OPB->_float); - break; - case OP_OR_IF: - OPC->_int = (OPA->_int || OPB->_float); - break; - - case OP_AND_FI: - OPC->_int = (OPA->_float && OPB->_int); - break; - case OP_OR_FI: - OPC->_int = (OPA->_float || OPB->_int); - break; - - case OP_NOT_I: - OPC->_int = !OPA->_int; - break; - - case OP_NE_IF: - OPC->_int = (OPA->_int != OPB->_float); - break; - case OP_NE_FI: - OPC->_int = (OPA->_float != OPB->_int); - break; - - case OP_GSTOREP_I: - case OP_GSTOREP_F: - case OP_GSTOREP_ENT: - case OP_GSTOREP_FLD: // integers - case OP_GSTOREP_S: - case OP_GSTOREP_FNC: // pointers - case OP_GSTOREP_V: - case OP_GADDRESS: - case OP_GLOAD_I: - case OP_GLOAD_F: - case OP_GLOAD_FLD: - case OP_GLOAD_ENT: - case OP_GLOAD_S: - case OP_GLOAD_FNC: - pr_xstatement = st-pr_statements; - PR_RunError(progfuncs, "Extra opcode not implemented\n"); - break; - - case OP_BOUNDCHECK: - if ((unsigned int)OPA->_int < (unsigned int)st->c || (unsigned int)OPA->_int >= (unsigned int)st->b) - { - pr_xstatement = st-pr_statements; - PR_RunError(progfuncs, "Progs boundcheck failed. Value is %i.", OPA->_int); - } - break; -/* case OP_PUSH: - OPC->_int = ENGINEPOINTER(&localstack[localstack_used+pr_spushed]); - pr_spushed += OPA->_int; - if (pr_spushed + localstack_used >= LOCALSTACK_SIZE) - { - pr_spushed = 0; - pr_xstatement = st-pr_statements; - PR_RunError(progfuncs, "Progs pushed too much"); - } - break; - case OP_POP: - pr_spushed -= OPA->_int; - if (pr_spushed < 0) - { - pr_spushed = 0; - pr_xstatement = st-pr_statements; - PR_RunError(progfuncs, "Progs poped more than it pushed"); - } - break; -*/ - default: - if (st->op & 0x8000) //break point! - { - pr_xstatement = s = st-pr_statements; - - printf("Break point hit in %s.\n", pr_xfunction->s_name+progfuncs->stringtable); - if (pr_trace<1) - pr_trace=1; //this is what it's for - - s = ShowStep(progfuncs, s); - st = &pr_statements[s]; //let the user move execution - pr_xstatement = s = st-pr_statements; - -#if 0 //fakeop stuff - not practical, the rest of the code is more optimised, st needs to point at the correct statement - memcpy(&fakeop, st, sizeof(dstatement_t)); //don't hit the new statement as a break point, cos it's probably the same one. - fakeop.op &= ~0x8000; - st = &fakeop; //a little remapping... -#else - st->op &= ~0x8000; //just remove the breakpoint and go around again, but this time in the debugger. -#endif - - goto reeval; //reexecute - } - pr_xstatement = st-pr_statements; - PR_RunError (progfuncs, "Bad opcode %i", st->op); - } -} - - -#undef cont -#undef reeval -#undef st -#undef pr_statements -#undef fakeop -#undef dstatement_t -#undef sofs -#undef uofs - -#undef ENGINEPOINTER -#undef QCPOINTER -#undef QCPOINTERM - diff --git a/misc/mediasource/extra/fteqcc-src/gui.h b/misc/mediasource/extra/fteqcc-src/gui.h deleted file mode 100644 index 66ad9c56..00000000 --- a/misc/mediasource/extra/fteqcc-src/gui.h +++ /dev/null @@ -1,21 +0,0 @@ -void GoToDefinition(char *name); -void EditFile(char *name, int line); - -void GUI_SetDefaultOpts(void); -int GUI_BuildParms(char *args, char **argv); - -unsigned char *QCC_ReadFile (char *fname, void *buffer, int len); -int QCC_FileSize (char *fname); -pbool QCC_WriteFile (char *name, void *data, int len); -void GUI_DialogPrint(char *title, char *text); - -extern char parameters[16384]; - -extern char progssrcname[256]; -extern char progssrcdir[256]; - -extern pbool fl_hexen2; -extern pbool fl_autohighlight; -extern pbool fl_compileonstart; -extern pbool fl_showall; -extern pbool fl_log; diff --git a/misc/mediasource/extra/fteqcc-src/hash.c b/misc/mediasource/extra/fteqcc-src/hash.c deleted file mode 100644 index 2b7b9120..00000000 --- a/misc/mediasource/extra/fteqcc-src/hash.c +++ /dev/null @@ -1,272 +0,0 @@ -#include "hash.h" -#include -#include - -#ifndef _WIN32 -#ifndef stricmp -#define stricmp strcasecmp -#endif -#endif - -// hash init assumes we get clean memory -void Hash_InitTable(hashtable_t *table, int numbucks, void *mem) -{ - table->numbuckets = numbucks; - table->bucket = (bucket_t **)mem; -} - -int Hash_Key(const char *name, int modulus) -{ //fixme: optimize. - unsigned int key; - for (key=0;*name; name++) - key += ((key<<3) + (key>>28) + *name); - - return (int)(key%modulus); -} -int Hash_KeyInsensative(const char *name, int modulus) -{ //fixme: optimize. - unsigned int key; - for (key=0;*name; name++) - { - if (*name >= 'A' && *name <= 'Z') - key += ((key<<3) + (key>>28) + (*name-'A'+'a')); - else - key += ((key<<3) + (key>>28) + *name); - } - - return (int)(key%modulus); -} - -void *Hash_Get(hashtable_t *table, const char *name) -{ - int bucknum = Hash_Key(name, table->numbuckets); - bucket_t *buck; - - buck = table->bucket[bucknum]; - - while(buck) - { - if (!STRCMP(name, buck->key.string)) - return buck->data; - - buck = buck->next; - } - return NULL; -} -void *Hash_GetInsensative(hashtable_t *table, const char *name) -{ - int bucknum = Hash_KeyInsensative(name, table->numbuckets); - bucket_t *buck; - - buck = table->bucket[bucknum]; - - while(buck) - { - if (!stricmp(name, buck->key.string)) - return buck->data; - - buck = buck->next; - } - return NULL; -} -void *Hash_GetKey(hashtable_t *table, int key) -{ - int bucknum = key%table->numbuckets; - bucket_t *buck; - - buck = table->bucket[bucknum]; - - while(buck) - { - if (buck->key.value == key) - return buck->data; - - buck = buck->next; - } - return NULL; -} -void *Hash_GetNext(hashtable_t *table, char *name, void *old) -{ - int bucknum = Hash_Key(name, table->numbuckets); - bucket_t *buck; - - buck = table->bucket[bucknum]; - - while(buck) - { - if (!STRCMP(name, buck->key.string)) - { - if (buck->data == old) //found the old one - break; - } - - buck = buck->next; - } - if (!buck) - return NULL; - - buck = buck->next;//don't return old - while(buck) - { - if (!STRCMP(name, buck->key.string)) - return buck->data; - - buck = buck->next; - } - return NULL; -} -void *Hash_GetNextInsensative(hashtable_t *table, char *name, void *old) -{ - int bucknum = Hash_KeyInsensative(name, table->numbuckets); - bucket_t *buck; - - buck = table->bucket[bucknum]; - - while(buck) - { - if (!STRCMP(name, buck->key.string)) - { - if (buck->data == old) //found the old one - break; - } - - buck = buck->next; - } - if (!buck) - return NULL; - - buck = buck->next;//don't return old - while(buck) - { - if (!STRCMP(name, buck->key.string)) - return buck->data; - - buck = buck->next; - } - return NULL; -} - - -void *Hash_Add(hashtable_t *table, char *name, void *data, bucket_t *buck) -{ - int bucknum = Hash_Key(name, table->numbuckets); - - buck->data = data; - buck->key.string = name; - buck->next = table->bucket[bucknum]; - table->bucket[bucknum] = buck; - - return buck; -} -void *Hash_AddInsensative(hashtable_t *table, char *name, void *data, bucket_t *buck) -{ - int bucknum = Hash_KeyInsensative(name, table->numbuckets); - - buck->data = data; - buck->key.string = name; - buck->next = table->bucket[bucknum]; - table->bucket[bucknum] = buck; - - return buck; -} -void *Hash_AddKey(hashtable_t *table, int key, void *data, bucket_t *buck) -{ - int bucknum = key%table->numbuckets; - - buck->data = data; - buck->key.value = key; - buck->next = table->bucket[bucknum]; - table->bucket[bucknum] = buck; - - return buck; -} - -void Hash_Remove(hashtable_t *table, char *name) -{ - int bucknum = Hash_Key(name, table->numbuckets); - bucket_t *buck; - - buck = table->bucket[bucknum]; - if(!buck) - return; - - if (!STRCMP(name, buck->key.string)) - { - table->bucket[bucknum] = buck->next; - return; - } - - - while(buck->next) - { - if (!STRCMP(name, buck->next->key.string)) - { - buck->next = buck->next->next; - return; - } - - buck = buck->next; - } - return; -} - -void Hash_RemoveData(hashtable_t *table, char *name, void *data) -{ - int bucknum = Hash_Key(name, table->numbuckets); - bucket_t *buck; - - buck = table->bucket[bucknum]; - if(!buck) - return; - - if (buck->data == data) - if (!STRCMP(name, buck->key.string)) - { - table->bucket[bucknum] = buck->next; - return; - } - - - while(buck->next) - { - if (buck->next->data == data) - if (!STRCMP(name, buck->next->key.string)) - { - buck->next = buck->next->next; - return; - } - - buck = buck->next; - } - return; -} - - -void Hash_RemoveKey(hashtable_t *table, int key) -{ - int bucknum = key%table->numbuckets; - bucket_t *buck; - - buck = table->bucket[bucknum]; - if(!buck) - return; - - if (buck->key.value == key) - { - table->bucket[bucknum] = buck->next; - return; - } - - - while(buck->next) - { - if (buck->next->key.value == key) - { - buck->next = buck->next->next; - return; - } - - buck = buck->next; - } - return; -} diff --git a/misc/mediasource/extra/fteqcc-src/hash.h b/misc/mediasource/extra/fteqcc-src/hash.h deleted file mode 100644 index 778e67a5..00000000 --- a/misc/mediasource/extra/fteqcc-src/hash.h +++ /dev/null @@ -1,38 +0,0 @@ -//============================= -//David's hash tables -//string based. - -#ifndef HASH_H__ -#define HASH_H__ - -#define Hash_BytesForBuckets(b) (sizeof(bucket_t)*b) - -#define STRCMP(s1,s2) (((*s1)!=(*s2)) || strcmp(s1+1,s2+1)) //saves about 2-6 out of 120 - expansion of idea from fastqcc -typedef struct bucket_s { - void *data; - union { - const char *string; - int value; - } key; - struct bucket_s *next; -} bucket_t; -typedef struct hashtable_s { - int numbuckets; - bucket_t **bucket; -} hashtable_t; - -void Hash_InitTable(hashtable_t *table, int numbucks, void *mem); //mem must be 0 filled. (memset(mem, 0, size)) -int Hash_Key(const char *name, int modulus); -void *Hash_Get(hashtable_t *table, const char *name); -void *Hash_GetInsensative(hashtable_t *table, const char *name); -void *Hash_GetKey(hashtable_t *table, int key); -void *Hash_GetNext(hashtable_t *table, char *name, void *old); -void *Hash_GetNextInsensative(hashtable_t *table, char *name, void *old); -void *Hash_Add(hashtable_t *table, char *name, void *data, bucket_t *buck); -void *Hash_AddInsensative(hashtable_t *table, char *name, void *data, bucket_t *buck); -void Hash_Remove(hashtable_t *table, char *name); -void Hash_RemoveData(hashtable_t *table, char *name, void *data); -void Hash_RemoveKey(hashtable_t *table, int key); -void *Hash_AddKey(hashtable_t *table, int key, void *data, bucket_t *buck); - -#endif diff --git a/misc/mediasource/extra/fteqcc-src/initlib.c b/misc/mediasource/extra/fteqcc-src/initlib.c deleted file mode 100644 index 1ca5728b..00000000 --- a/misc/mediasource/extra/fteqcc-src/initlib.c +++ /dev/null @@ -1,834 +0,0 @@ -#define PROGSUSED -#include "progsint.h" -#include - -typedef struct prmemb_s { - struct prmemb_s *prev; - int level; -} prmemb_t; -void *PRHunkAlloc(progfuncs_t *progfuncs, int ammount) -{ - prmemb_t *mem; - ammount = sizeof(prmemb_t)+((ammount + 3)&~3); - mem = memalloc(ammount); - memset(mem, 0, ammount); - mem->prev = memb; - if (!memb) - mem->level = 1; - else - mem->level = ((prmemb_t *)memb)->level+1; - memb = mem; - - return ((char *)mem)+sizeof(prmemb_t); -} - -int PRHunkMark(progfuncs_t *progfuncs) -{ - return ((prmemb_t *)memb)->level; -} -void PRHunkFree(progfuncs_t *progfuncs, int mark) -{ - prmemb_t *omem; - while(memb) - { - if (memb->level <= mark) - return; - - omem = memb; - memb = memb->prev; - memfree(omem); - } - return; -} - -//for 64bit systems. :) -//addressable memory is memory available to the vm itself for writing. -//once allocated, it cannot be freed for the lifetime of the VM. -void *PRAddressableAlloc(progfuncs_t *progfuncs, int ammount) -{ - ammount = (ammount + 4)&~3; //round up to 4 - if (addressableused + ammount > addressablesize) - Sys_Error("Not enough addressable memory for progs VM"); - - addressableused += ammount; - -#ifdef _WIN32 - if (!VirtualAlloc (addressablehunk, addressableused, MEM_COMMIT, PAGE_READWRITE)) - Sys_Error("VirtualAlloc failed. Blame windows."); -#endif - - return &addressablehunk[addressableused-ammount]; -} - -void PRAddressableFlush(progfuncs_t *progfuncs, int totalammount) -{ - addressableused = 0; - if (totalammount < 0) //flush - { - totalammount = addressablesize; -// return; - } - - if (addressablehunk) -#ifdef _WIN32 - VirtualFree(addressablehunk, 0, MEM_RELEASE); //doesn't this look complicated? :p - addressablehunk = VirtualAlloc (NULL, totalammount, MEM_RESERVE, PAGE_NOACCESS); -#else - free(addressablehunk); - addressablehunk = malloc(totalammount); //linux will allocate-on-use anyway, which is handy. -// memset(addressablehunk, 0xff, totalammount); -#endif - if (!addressablehunk) - Sys_Error("Out of memory\n"); - addressablesize = totalammount; -} - -int PR_InitEnts(progfuncs_t *progfuncs, int max_ents) -{ - maxedicts = max_ents; - - sv_num_edicts = 0; - - max_fields_size = fields_size; - - prinst->edicttable = PRHunkAlloc(progfuncs, maxedicts*sizeof(struct edicts_s *)); - sv_edicts = PRHunkAlloc(progfuncs, externs->edictsize); - prinst->edicttable[0] = sv_edicts; - ((edictrun_t*)prinst->edicttable[0])->fields = PRAddressableAlloc(progfuncs, max_fields_size); - QC_ClearEdict(progfuncs, sv_edicts); - sv_num_edicts = 1; - - if (externs->entspawn) - externs->entspawn((struct edict_s *)sv_edicts, false); - - return max_fields_size; -} -edictrun_t tempedict; //used as a safty buffer -float tempedictfields[2048]; - -void PR_Configure (progfuncs_t *progfuncs, int addressable_size, int max_progs) //can be used to wipe all memory -{ - unsigned int i; - edictrun_t *e; - -// int a; -#ifdef QCJIT - prinst->usejit = true; -#endif - - max_fields_size=0; - fields_size = 0; - progfuncs->stringtable = 0; - QC_StartShares(progfuncs); - QC_InitShares(progfuncs); - - for ( i=1 ; iedicttable[i]); - prinst->edicttable[i] = NULL; -// e->entnum = i; - if (e) - memfree(e); - } - - PRHunkFree(progfuncs, 0); //clear mem - our hunk may not be a real hunk. - if (addressable_size<0) - addressable_size = 8*1024*1024; - PRAddressableFlush(progfuncs, addressable_size); - - pr_progstate = PRHunkAlloc(progfuncs, sizeof(progstate_t) * max_progs); - -/* for(a = 0; a < max_progs; a++) - { - pr_progstate[a].progs = NULL; - } -*/ - - maxprogs = max_progs; - pr_typecurrent=-1; - - prinst->reorganisefields = false; - - maxedicts = 1; - prinst->edicttable = &sv_edicts; - sv_num_edicts = 1; //set up a safty buffer so things won't go horribly wrong too often - sv_edicts=(struct edict_s *)&tempedict; - tempedict.readonly = true; - tempedict.fields = tempedictfields; - tempedict.isfree = false; -} - - - -struct globalvars_s *PR_globals (progfuncs_t *progfuncs, progsnum_t pnum) -{ - if (pnum < 0) - { - if (!current_progstate) - return NULL; //err.. you've not loaded one yet. - return (struct globalvars_s *)current_progstate->globals; - } - return (struct globalvars_s *)pr_progstate[pnum].globals; -} - -struct entvars_s *PR_entvars (progfuncs_t *progfuncs, struct edict_s *ed) -{ - if (((edictrun_t *)ed)->isfree) - return NULL; - - return (struct entvars_s *)edvars(ed); -} - -int PR_GetFuncArgCount(progfuncs_t *progfuncs, func_t func) -{ - unsigned int pnum; - unsigned int fnum; - dfunction_t *f; - - pnum = (func & 0xff000000)>>24; - fnum = (func & 0x00ffffff); - - if (pnum >= (unsigned)maxprogs || !pr_progstate[pnum].functions) - return -1; - else if (fnum >= pr_progstate[pnum].progs->numfunctions) - return -1; - else - { - f = pr_progstate[pnum].functions + fnum; - return f->numparms; - } -} - -func_t PR_FindFunc(progfuncs_t *progfuncs, char *funcname, progsnum_t pnum) -{ - dfunction_t *f=NULL; - if (pnum == PR_ANY) - { - for (pnum = 0; (unsigned)pnum < maxprogs; pnum++) - { - if (!pr_progstate[pnum].progs) - continue; - f = ED_FindFunction(progfuncs, funcname, &pnum, pnum); - if (f) - break; - } - } - else if (pnum == PR_ANYBACK) //run backwards - { - for (pnum = maxprogs-1; pnum >= 0; pnum--) - { - if (!pr_progstate[pnum].progs) - continue; - f = ED_FindFunction(progfuncs, funcname, &pnum, pnum); - if (f) - break; - } - } - else - f = ED_FindFunction(progfuncs, funcname, &pnum, pnum); - if (!f) - return 0; - - { - ddef16_t *var16; - ddef32_t *var32; - switch(pr_progstate[pnum].intsize) - { - case 24: - case 16: - var16 = ED_FindTypeGlobalFromProgs16(progfuncs, funcname, pnum, ev_function); //we must make sure we actually have a function def - 'light' is defined as a field before it is defined as a function. - if (!var16) - return (f - pr_progstate[pnum].functions) | (pnum << 24); - return *(int *)&pr_progstate[pnum].globals[var16->ofs]; - case 32: - var32 = ED_FindTypeGlobalFromProgs32(progfuncs, funcname, pnum, ev_function); //we must make sure we actually have a function def - 'light' is defined as a field before it is defined as a function. - if (!var32) - return (f - pr_progstate[pnum].functions) | (pnum << 24); - return *(int *)&pr_progstate[pnum].globals[var32->ofs]; - } - Sys_Error("Error with def size (PR_FindFunc)"); - } - return 0; -} - -eval_t *PR_FindGlobal(progfuncs_t *progfuncs, char *globname, progsnum_t pnum) -{ - unsigned int i; - ddef16_t *var16; - ddef32_t *var32; - if (pnum == PR_CURRENT) - pnum = pr_typecurrent; - if (pnum == PR_ANY) - { - eval_t *ev; - for (i = 0; i < maxprogs; i++) - { - if (!pr_progstate[i].progs) - continue; - ev = PR_FindGlobal(progfuncs, globname, i); - if (ev) - return ev; - } - return NULL; - } - if (pnum < 0 || (unsigned)pnum >= maxprogs || !pr_progstate[pnum].progs) - return NULL; - switch(pr_progstate[pnum].intsize) - { - case 16: - case 24: - if (!(var16 = ED_FindGlobalFromProgs16(progfuncs, globname, pnum))) - return NULL; - - return (eval_t *)&pr_progstate[pnum].globals[var16->ofs]; - case 32: - if (!(var32 = ED_FindGlobalFromProgs32(progfuncs, globname, pnum))) - return NULL; - - return (eval_t *)&pr_progstate[pnum].globals[var32->ofs]; - } - Sys_Error("Error with def size (PR_FindGlobal)"); - return NULL; -} - -void SetGlobalEdict(progfuncs_t *progfuncs, struct edict_s *ed, int ofs) -{ - ((int*)pr_globals)[ofs] = EDICT_TO_PROG(progfuncs, ed); -} - -char *PR_VarString (progfuncs_t *progfuncs, int first) -{ - int i; - static char out[1024]; - char *s; - - out[0] = 0; - for (i=first ; istringtable; - strcat (out, s); - -//#ifdef PARANOID - if (strlen(out)+1 >= sizeof(out)) - Sys_Error("VarString (builtin call ending with strings) exceeded maximum string length of %i chars", sizeof(out)); -//#endif - } - } - return out; -} - -int PR_QueryField (progfuncs_t *progfuncs, unsigned int fieldoffset, etype_t *type, char **name, evalc_t *fieldcache) -{ - fdef_t *var; - var = ED_FieldAtOfs(progfuncs, fieldoffset); - if (!var) - return false; - - if (type) - *type = var->type & ~(DEF_SAVEGLOBAL|DEF_SHARED); - if (name) - *name = var->name; - if (fieldcache) - { - fieldcache->ofs32 = var; - fieldcache->varname = var->name; - } - - return true; -} - -eval_t *GetEdictFieldValue(progfuncs_t *progfuncs, struct edict_s *ed, char *name, evalc_t *cache) -{ - fdef_t *var; - if (!cache) - { - var = ED_FindField(progfuncs, name); - if (!var) - return NULL; - return (eval_t *) &(((int*)(((edictrun_t*)ed)->fields))[var->ofs]); - } - if (!cache->varname) - { - cache->varname = name; - var = ED_FindField(progfuncs, name); - if (!var) - { - cache->ofs32 = NULL; - return NULL; - } - cache->ofs32 = var; - cache->varname = var->name; - if (!ed) - return (void*)~0; //something not null - return (eval_t *) &(((int*)(((edictrun_t*)ed)->fields))[var->ofs]); - } - if (cache->ofs32 == NULL) - return NULL; - return (eval_t *) &(((int*)(((edictrun_t*)ed)->fields))[cache->ofs32->ofs]); -} - -struct edict_s *ProgsToEdict (progfuncs_t *progfuncs, int progs) -{ - if ((unsigned)progs >= (unsigned)maxedicts) - { - printf("Bad entity index %i\n", progs); - progs = 0; - } - return (struct edict_s *)PROG_TO_EDICT(progfuncs, progs); -} -int EdictToProgs (progfuncs_t *progfuncs, struct edict_s *ed) -{ - return EDICT_TO_PROG(progfuncs, ed); -} - -string_t PR_StringToProgs (progfuncs_t *progfuncs, char *str) -{ - char **ntable; - int i, free=-1; - - if (!str) - return 0; - -// if (str-progfuncs->stringtable < progfuncs->stringtablesize) -// return str - progfuncs->stringtable; - - for (i = prinst->numallocedstrings-1; i >= 0; i--) - { - if (prinst->allocedstrings[i] == str) - return (string_t)((unsigned int)i | 0x80000000); - if (!prinst->allocedstrings[i]) - free = i; - } - - if (free != -1) - { - i = free; - prinst->allocedstrings[i] = str; - return (string_t)((unsigned int)i | 0x80000000); - } - - prinst->maxallocedstrings += 1024; - ntable = memalloc(sizeof(char*) * prinst->maxallocedstrings); - memcpy(ntable, prinst->allocedstrings, sizeof(char*) * prinst->numallocedstrings); - memset(ntable + prinst->numallocedstrings, 0, sizeof(char*) * (prinst->maxallocedstrings - prinst->numallocedstrings)); - prinst->numallocedstrings = prinst->maxallocedstrings; - if (prinst->allocedstrings) - memfree(prinst->allocedstrings); - prinst->allocedstrings = ntable; - - for (i = prinst->numallocedstrings-1; i >= 0; i--) - { - if (!prinst->allocedstrings[i]) - { - prinst->allocedstrings[i] = str; - return (string_t)((unsigned int)i | 0x80000000); - } - } - - return 0; -} - -char *PR_RemoveProgsString (progfuncs_t *progfuncs, string_t str) -{ - char *ret; - - //input string is expected to be an allocated string - //if its a temp, or a constant, just return NULL. - if ((unsigned int)str & 0xc0000000) - { - if ((unsigned int)str & 0x80000000) - { - int i = str & ~0x80000000; - if (i >= prinst->numallocedstrings) - { - pr_trace = 1; - return NULL; - } - if (prinst->allocedstrings[i]) - { - ret = prinst->allocedstrings[i]; - prinst->allocedstrings[i] = NULL; //remove it - return ret; - } - else - { - pr_trace = 1; - return NULL; //urm, was freed... - } - } - } - pr_trace = 1; - return NULL; -} - -char *PR_StringToNative (progfuncs_t *progfuncs, string_t str) -{ - if ((unsigned int)str & 0xc0000000) - { - if ((unsigned int)str & 0x80000000) - { - int i = str & ~0x80000000; - if (i >= prinst->numallocedstrings) - { - pr_trace = 1; - return ""; - } - if (prinst->allocedstrings[i]) - return prinst->allocedstrings[i]; - else - { - pr_trace = 1; - return ""; //urm, was freed... - } - } - if ((unsigned int)str & 0x40000000) - { - int i = str & ~0x40000000; - if (i >= prinst->numtempstrings) - { - pr_trace = 1; - return ""; - } - return prinst->tempstrings[i]; - } - } - - if (str >= progfuncs->stringtablesize) - { - pr_trace = 1; - return ""; - } - return progfuncs->stringtable + str; -} - - -string_t PR_AllocTempString (progfuncs_t *progfuncs, char *str) -{ - char **ntable; - int newmax; - int i; - - if (!str) - return 0; - - if (prinst->numtempstrings == prinst->maxtempstrings) - { - newmax = prinst->maxtempstrings += 1024; - prinst->maxtempstrings += 1024; - ntable = memalloc(sizeof(char*) * newmax); - memcpy(ntable, prinst->tempstrings, sizeof(char*) * prinst->numtempstrings); - prinst->maxtempstrings = newmax; - if (prinst->tempstrings) - memfree(prinst->tempstrings); - prinst->tempstrings = ntable; - } - - i = prinst->numtempstrings; - if (i == 0x10000000) - return 0; - - prinst->numtempstrings++; - - prinst->tempstrings[i] = memalloc(strlen(str)+1); - strcpy(prinst->tempstrings[i], str); - - return (string_t)((unsigned int)i | 0x40000000); -} - -void PR_FreeTemps (progfuncs_t *progfuncs, int depth) -{ - int i; - if (depth > prinst->numtempstrings) - { - Sys_Error("QC Temp stack inverted\n"); - return; - } - for (i = depth; i < prinst->numtempstrings; i++) - { - memfree(prinst->tempstrings[i]); - } - - prinst->numtempstrings = depth; -} - - -struct qcthread_s *PR_ForkStack (progfuncs_t *progfuncs); -void PR_ResumeThread (progfuncs_t *progfuncs, struct qcthread_s *thread); -void PR_AbortStack (progfuncs_t *progfuncs); - - -void RegisterBuiltin(progfuncs_t *progfncs, char *name, builtin_t func); - -progfuncs_t deffuncs = { - PROGSTRUCT_VERSION, - PR_Configure, - PR_LoadProgs, - PR_InitEnts, - PR_ExecuteProgram, - PR_SwitchProgs, - PR_globals, - PR_entvars, - PR_RunError, - ED_Print, - ED_Alloc, - ED_Free, - - EDICT_NUM, - NUM_FOR_EDICT, - - - SetGlobalEdict, - - PR_VarString, - - NULL, - PR_FindFunc, -#ifdef MINIMAL - NULL, - NULL, -#else - Comp_Begin, - Comp_Continue, -#endif - - filefromprogs, - NULL,//filefromnewprogs, - - SaveEnts, - LoadEnts, - - SaveEnt, - RestoreEnt, - - PR_FindGlobal, - ED_NewString, - (void*)PRHunkAlloc, - - GetEdictFieldValue, - ProgsToEdict, - EdictToProgs, - - EvaluateDebugString, - - NULL, - PR_StackTrace, - - PR_ToggleBreakpoint, - 0, - NULL, -#ifdef MINIMAL - NULL, -#else - Decompile, -#endif - NULL, - NULL, - RegisterBuiltin, - - 0, - 0, - - PR_ForkStack, - PR_ResumeThread, - PR_AbortStack, - - 0, - - QC_RegisterFieldVar, - - 0, - 0, - - PR_AllocTempString, - - PR_StringToProgs, - PR_StringToNative, - 0, - PR_QueryField, - QC_ClearEdict -}; -#undef printf - -//defs incase following structure is not passed. -struct edict_s *safesv_edicts; -int safesv_num_edicts; -double safetime=0; - -progexterns_t defexterns = { - PROGSTRUCT_VERSION, - - NULL, //char *(*ReadFile) (char *fname, void *buffer, int len); - NULL, //int (*FileSize) (char *fname); //-1 if file does not exist - NULL, //bool (*WriteFile) (char *name, void *data, int len); - printf, //void (*printf) (char *, ...); - (void*)exit, //void (*Sys_Error) (char *, ...); - NULL, //void (*Abort) (char *, ...); - sizeof(edictrun_t), //int edictsize; //size of edict_t - - NULL, //void (*entspawn) (struct edict_s *ent); //ent has been spawned, but may not have all the extra variables (that may need to be set) set - NULL, //bool (*entcanfree) (struct edict_s *ent); //return true to stop ent from being freed - NULL, //void (*stateop) (float var, func_t func); - NULL, - NULL, - NULL, - - //used when loading a game - NULL, //builtin_t *(*builtinsfor) (int num); //must return a pointer to the builtins that were used before the state was saved. - NULL, //void (*loadcompleate) (int edictsize); //notification to reset any pointers. - - (void*)malloc, //void *(*memalloc) (int size); //small string allocation malloced and freed randomly by the executor. (use memalloc if you want) - free, //void (*memfree) (void * mem); - - - NULL, //builtin_t *globalbuiltins; //these are available to all progs - 0, //int numglobalbuiltins; - - PR_NOCOMPILE, - - &safetime, //double *gametime; - - &safesv_edicts, //struct edict_s **sv_edicts; - &safesv_num_edicts, //int *sv_num_edicts; - - NULL, //int (*useeditor) (char *filename, int line, int nump, char **parms); -}; - -//progfuncs_t *progfuncs = NULL; -#undef memfree -#undef prinst -#undef extensionbuiltin -#undef field -#undef shares -#undef sv_num_edicts - - -#ifdef QCLIBDLL_EXPORTS -__declspec(dllexport) -#endif -void CloseProgs(progfuncs_t *inst) -{ -// extensionbuiltin_t *eb; - void (VARGS *f) (void *); - - unsigned int i; - edictrun_t *e; - - f = inst->parms->memfree; - - for ( i=1 ; imaxedicts; i++) - { - e = (edictrun_t *)(inst->prinst->edicttable[i]); - inst->prinst->edicttable[i] = NULL; - if (e) - { -// e->entnum = i; - f(e); - } - } - - PRHunkFree(inst, 0); - -#ifdef _WIN32 - VirtualFree(inst->addressablehunk, 0, MEM_RELEASE); //doesn't this look complicated? :p -#else - free(inst->addressablehunk); -#endif - -/* - while(inst->prinst->extensionbuiltin) - { - eb = inst->prinst->extensionbuiltin->prev; - f(inst->prinst->extensionbuiltin); - inst->prinst->extensionbuiltin = eb; - } -*/ - if (inst->prinst->field) - f(inst->prinst->field); - if (inst->prinst->shares) - f(inst->prinst->shares); //free memory - f(inst->prinst); - f(inst); -} - -void RegisterBuiltin(progfuncs_t *progfuncs, char *name, builtin_t func) -{ -/* - extensionbuiltin_t *eb; - eb = memalloc(sizeof(extensionbuiltin_t)); - eb->prev = progfuncs->prinst->extensionbuiltin; - progfuncs->prinst->extensionbuiltin = eb; - eb->name = name; - eb->func = func; -*/ -} - -#ifndef WIN32 -#define QCLIBINT //don't use dllspecifications -#endif - -#if defined(QCLIBDLL_EXPORTS) -__declspec(dllexport) -#endif -progfuncs_t * InitProgs(progexterns_t *ext) -{ - progfuncs_t *funcs; - - if (!ext) - ext = &defexterns; - else - { - int i; - if (ext->progsversion > PROGSTRUCT_VERSION) - return NULL; - - for (i=0;imemalloc(sizeof(progfuncs_t)); - memcpy(funcs, &deffuncs, sizeof(progfuncs_t)); - - funcs->prinst = ext->memalloc(sizeof(prinst_t)); - memset(funcs->prinst,0, sizeof(prinst_t)); - - funcs->pr_trace = &funcs->prinst->pr_trace; - funcs->progstate = &funcs->pr_progstate; - funcs->callargc = &funcs->pr_argc; - - funcs->parms = ext; - - SetEndian(); - - return funcs; -} - - - - - - - - - - - - - - - - -#ifdef QCC -void main (int argc, char **argv) -{ - progexterns_t ext; - - progfuncs_t *funcs; - funcs = InitProgs(&ext); - if (funcs->PR_StartCompile(argc, argv)) - while(funcs->PR_ContinueCompile()); -} -#endif diff --git a/misc/mediasource/extra/fteqcc-src/pr_comp.h b/misc/mediasource/extra/fteqcc-src/pr_comp.h deleted file mode 100644 index 13b93bce..00000000 --- a/misc/mediasource/extra/fteqcc-src/pr_comp.h +++ /dev/null @@ -1,540 +0,0 @@ -// this file is shared by the execution and compiler - -/*i'm part way through making this work -I've given up now that I can't work out a way to load pointers. -Setting them should be fine. -*/ -#ifndef __PR_COMP_H__ -#define __PR_COMP_H__ - - -/*this distinction is made as the execution uses c pointers while compiler uses pointers from the start of the string table of the current progs*/ -#ifdef COMPILER -typedef int QCC_string_t; -#else -//typedef char *string_t; -#endif - -//typedef enum {ev_void, ev_string, ev_float, ev_vector, ev_entity, ev_field, ev_function, ev_pointer, ev_integer, ev_struct, ev_union} etype_t; -// 0 1 2 3 4 5 6 7 8 9 10 - -#define OFS_NULL 0 -#define OFS_RETURN 1 -#define OFS_PARM0 4 // leave 3 ofs for each parm to hold vectors -#define OFS_PARM1 7 -#define OFS_PARM2 10 -#define OFS_PARM3 13 -#define OFS_PARM4 16 -#define OFS_PARM5 19 -#define OFS_PARM6 22 -#define OFS_PARM7 25 -#define RESERVED_OFS 28 - - -enum { - OP_DONE, //0 - OP_MUL_F, - OP_MUL_V, - OP_MUL_FV, - OP_MUL_VF, - OP_DIV_F, - OP_ADD_F, - OP_ADD_V, - OP_SUB_F, - OP_SUB_V, - - OP_EQ_F, //10 - OP_EQ_V, - OP_EQ_S, - OP_EQ_E, - OP_EQ_FNC, - - OP_NE_F, - OP_NE_V, - OP_NE_S, - OP_NE_E, - OP_NE_FNC, - - OP_LE, //20 - OP_GE, - OP_LT, - OP_GT, - - OP_LOAD_F, - OP_LOAD_V, - OP_LOAD_S, - OP_LOAD_ENT, - OP_LOAD_FLD, - OP_LOAD_FNC, - - OP_ADDRESS, //30 - - OP_STORE_F, - OP_STORE_V, - OP_STORE_S, - OP_STORE_ENT, - OP_STORE_FLD, - OP_STORE_FNC, - - OP_STOREP_F, - OP_STOREP_V, - OP_STOREP_S, - OP_STOREP_ENT, //40 - OP_STOREP_FLD, - OP_STOREP_FNC, - - OP_RETURN, - OP_NOT_F, - OP_NOT_V, - OP_NOT_S, - OP_NOT_ENT, - OP_NOT_FNC, - OP_IF, - OP_IFNOT, //50 - OP_CALL0, //careful... hexen2 and q1 have different calling conventions - OP_CALL1, //remap hexen2 calls to OP_CALL2H - OP_CALL2, - OP_CALL3, - OP_CALL4, - OP_CALL5, - OP_CALL6, - OP_CALL7, - OP_CALL8, - OP_STATE, //60 - OP_GOTO, - OP_AND, - OP_OR, - - OP_BITAND, - OP_BITOR, - - - //these following ones are Hexen 2 constants. - - OP_MULSTORE_F, - OP_MULSTORE_V, - OP_MULSTOREP_F, - OP_MULSTOREP_V, - - OP_DIVSTORE_F, //70 - OP_DIVSTOREP_F, - - OP_ADDSTORE_F, - OP_ADDSTORE_V, - OP_ADDSTOREP_F, - OP_ADDSTOREP_V, - - OP_SUBSTORE_F, - OP_SUBSTORE_V, - OP_SUBSTOREP_F, - OP_SUBSTOREP_V, - - OP_FETCH_GBL_F, //80 - OP_FETCH_GBL_V, - OP_FETCH_GBL_S, - OP_FETCH_GBL_E, - OP_FETCH_GBL_FNC, - - OP_CSTATE, - OP_CWSTATE, - - OP_THINKTIME, - - OP_BITSET, - OP_BITSETP, - OP_BITCLR, //90 - OP_BITCLRP, - - OP_RAND0, - OP_RAND1, - OP_RAND2, - OP_RANDV0, - OP_RANDV1, - OP_RANDV2, - - OP_SWITCH_F, - OP_SWITCH_V, - OP_SWITCH_S, //100 - OP_SWITCH_E, - OP_SWITCH_FNC, - - OP_CASE, - OP_CASERANGE, - - - - - - //the rest are added - //mostly they are various different ways of adding two vars with conversions. - - OP_CALL1H, - OP_CALL2H, - OP_CALL3H, - OP_CALL4H, - OP_CALL5H, - OP_CALL6H, //110 - OP_CALL7H, - OP_CALL8H, - - - OP_STORE_I, - OP_STORE_IF, - OP_STORE_FI, - - OP_ADD_I, - OP_ADD_FI, - OP_ADD_IF, //110 - - OP_SUB_I, - OP_SUB_FI, - OP_SUB_IF, - - OP_CONV_ITOF, - OP_CONV_FTOI, - OP_CP_ITOF, - OP_CP_FTOI, - OP_LOAD_I, - OP_STOREP_I, - OP_STOREP_IF, //120 - OP_STOREP_FI, - - OP_BITAND_I, - OP_BITOR_I, - - OP_MUL_I, - OP_DIV_I, - OP_EQ_I, - OP_NE_I, - - OP_IFNOT_S, - OP_IF_S, - - OP_NOT_I, //130 - - OP_DIV_VF, - - OP_XOR_I, - OP_RSHIFT_I, - OP_LSHIFT_I, - - OP_GLOBALADDRESS, - OP_POINTER_ADD, //32 bit pointers - - OP_LOADA_F, - OP_LOADA_V, - OP_LOADA_S, - OP_LOADA_ENT, //140 - OP_LOADA_FLD, - OP_LOADA_FNC, - OP_LOADA_I, - - OP_STORE_P, //152... erm.. wait... - OP_LOAD_P, - - OP_LOADP_F, - OP_LOADP_V, - OP_LOADP_S, - OP_LOADP_ENT, - OP_LOADP_FLD, //150 - OP_LOADP_FNC, - OP_LOADP_I, - - OP_LE_I, - OP_GE_I, - OP_LT_I, - OP_GT_I, - - OP_LE_IF, - OP_GE_IF, - OP_LT_IF, - OP_GT_IF, //160 - - OP_LE_FI, - OP_GE_FI, - OP_LT_FI, - OP_GT_FI, - - OP_EQ_IF, - OP_EQ_FI, - - //------------------------------------- - //string manipulation. - OP_ADD_SF, //(char*)c = (char*)a + (float)b - OP_SUB_S, //(float)c = (char*)a - (char*)b - OP_STOREP_C,//(float)c = *(char*)b = (float)a - OP_LOADP_C, //(float)c = *(char*) //170 - //------------------------------------- - - - OP_MUL_IF, - OP_MUL_FI, - OP_MUL_VI, - OP_MUL_IV, - OP_DIV_IF, - OP_DIV_FI, - OP_BITAND_IF, - OP_BITOR_IF, - OP_BITAND_FI, - OP_BITOR_FI, //180 - OP_AND_I, - OP_OR_I, - OP_AND_IF, - OP_OR_IF, - OP_AND_FI, - OP_OR_FI, - OP_NE_IF, - OP_NE_FI, - -//erm... FTEQCC doesn't make use of these... These are for DP. - OP_GSTOREP_I, - OP_GSTOREP_F, //190 - OP_GSTOREP_ENT, - OP_GSTOREP_FLD, // integers - OP_GSTOREP_S, - OP_GSTOREP_FNC, // pointers - OP_GSTOREP_V, - OP_GADDRESS, - OP_GLOAD_I, - OP_GLOAD_F, - OP_GLOAD_FLD, - OP_GLOAD_ENT, //200 - OP_GLOAD_S, - OP_GLOAD_FNC, - OP_BOUNDCHECK, - -//back to ones that we do use. - OP_STOREP_P, - OP_PUSH, //push 4octets onto the local-stack (which is ALWAYS poped on function return). Returns a pointer. - OP_POP, //pop those ones that were pushed (don't over do it). Needs assembler. - - OP_SWITCH_I,//hmm. - OP_GLOAD_V, - - OP_IF_F, - OP_IFNOT_F, - - OP_NUMREALOPS, - - /* - These ops are emulated out, always, and are only present in the compiler. - */ - - OP_BITSET_I, - OP_BITSETP_I, - - OP_MULSTORE_I, - OP_DIVSTORE_I, - OP_ADDSTORE_I, - OP_SUBSTORE_I, - OP_MULSTOREP_I, - OP_DIVSTOREP_I, - OP_ADDSTOREP_I, - OP_SUBSTOREP_I, - - OP_MULSTORE_IF, - OP_MULSTOREP_IF, - OP_DIVSTORE_IF, - OP_DIVSTOREP_IF, - OP_ADDSTORE_IF, - OP_ADDSTOREP_IF, - OP_SUBSTORE_IF, - OP_SUBSTOREP_IF, - - OP_MULSTORE_FI, - OP_MULSTOREP_FI, - OP_DIVSTORE_FI, - OP_DIVSTOREP_FI, - OP_ADDSTORE_FI, - OP_ADDSTOREP_FI, - OP_SUBSTORE_FI, - OP_SUBSTOREP_FI, - - OP_NUMOPS -}; - - -#ifndef COMPILER -typedef struct statement16_s -{ - unsigned short op; - unsigned short a,b,c; -} dstatement16_t; -typedef struct statement32_s -{ - unsigned int op; - unsigned int a,b,c; -} dstatement32_t; -#else -typedef struct QCC_statement16_s -{ - unsigned short op; - unsigned short a,b,c; -} QCC_dstatement16_t; -typedef struct QCC_statement32_s -{ - unsigned int op; - unsigned int a,b,c; -} QCC_dstatement32_t; -#define QCC_dstatement_t QCC_dstatement32_t -#endif - -//these should be the same except the string type -#ifndef COMPILER -typedef struct ddef16_s -{ - unsigned short type; // if DEF_SAVEGLOBAL bit is set - // the variable needs to be saved in savegames - unsigned short ofs; - string_t s_name; -} ddef16_t; - -typedef struct ddef32_s -{ - unsigned int type; // if DEF_SAVEGLOBAL bit is set - // the variable needs to be saved in savegames - unsigned int ofs; - string_t s_name; -} ddef32_t; - -typedef struct fdef_s -{ - unsigned int type; // if DEF_SAVEGLOBAL bit is set - // the variable needs to be saved in savegames - unsigned int ofs; - unsigned int progsofs; //used at loading time, so maching field offsets (unions/members) are positioned at the same runtime offset. - char * name; -} fdef_t; - -typedef void *ddefXX_t; -#else -typedef struct QCC_ddef16_s -{ - unsigned short type; // if DEF_SAVEGLOBAL bit is set - // the variable needs to be saved in savegames - unsigned short ofs; - QCC_string_t s_name; -} QCC_ddef16_t; - -typedef struct QCC_ddef32_s -{ - unsigned int type; // if DEF_SAVEGLOBAL bit is set - // the variable needs to be saved in savegames - unsigned int ofs; - QCC_string_t s_name; -} QCC_ddef32_t; - -#define QCC_ddef_t QCC_ddef32_t -#endif - -#define DEF_SAVEGLOBAL (1<<15) -#define DEF_SHARED (1<<14) - -#define MAX_PARMS 8 - -#ifndef COMPILER -typedef struct -{ - int first_statement; // negative numbers are builtins - int parm_start; - int locals; // total ints of parms + locals - - int profile; // runtime - - string_t s_name; - string_t s_file; // source file defined in - - int numparms; - qbyte parm_size[MAX_PARMS]; -} dfunction_t; -#else -typedef struct -{ - unsigned int first_statement; // negative numbers are builtins - unsigned int parm_start; - int locals; // total ints of parms + locals - - int profile; // runtime - - QCC_string_t s_name; - QCC_string_t s_file; // source file defined in - - int numparms; - qbyte parm_size[MAX_PARMS]; -} QCC_dfunction_t; -#endif - - -#define PROG_VERSION 6 -#define PROG_KKQWSVVERSION 7 -#define PROG_EXTENDEDVERSION 7 -#define PROG_SECONDARYVERSION16 (*(int*)"1FTE" ^ *(int*)"PROG") //something unlikly and still meaningful (to me) -#define PROG_SECONDARYVERSION32 (*(int*)"1FTE" ^ *(int*)"32B ") //something unlikly and still meaningful (to me) -typedef struct -{ - int version; - int crc; // check of header file - - unsigned int ofs_statements; //comp 1 - unsigned int numstatements; // statement 0 is an error - - unsigned int ofs_globaldefs; //comp 2 - unsigned int numglobaldefs; - - unsigned int ofs_fielddefs; //comp 4 - unsigned int numfielddefs; - - unsigned int ofs_functions; //comp 8 - unsigned int numfunctions; // function 0 is an empty - - unsigned int ofs_strings; //comp 16 - unsigned int numstrings; // first string is a null string - - unsigned int ofs_globals; //comp 32 - unsigned int numglobals; - - unsigned int entityfields; - - //debug / version 7 extensions - unsigned int ofsfiles; //non list format. no comp - unsigned int ofslinenums; //numstatements big //comp 64 - unsigned int ofsbodylessfuncs; //no comp - unsigned int numbodylessfuncs; - - unsigned int ofs_types; //comp 128 - unsigned int numtypes; - unsigned int blockscompressed; - - int secondaryversion; //Constant - to say that any version 7 progs are actually ours, not someone else's alterations. -} dprograms_t; -#define standard_dprograms_t_size ((int)&((dprograms_t*)NULL)->ofsfiles) - -#endif - - - - - -typedef struct { - char filename[128]; - int size; - int compsize; - int compmethod; - int ofs; -} includeddatafile_t; - - - - -typedef struct typeinfo_s -{ - etype_t type; - - int next; - int aux_type; - int num_parms; - - int ofs; //inside a structure. - int size; - char *name; -} typeinfo_t; diff --git a/misc/mediasource/extra/fteqcc-src/pr_edict.c b/misc/mediasource/extra/fteqcc-src/pr_edict.c deleted file mode 100644 index d6c21199..00000000 --- a/misc/mediasource/extra/fteqcc-src/pr_edict.c +++ /dev/null @@ -1,3118 +0,0 @@ - - -#define PROGSUSED -struct edict_s; -#include "progsint.h" -//#include "crc.h" - -/*int maxedicts; - -evalc_t spawnflagscache; -*/ - -#ifdef _WIN32 -//this is windows all files are written with this endian standard. we do this to try to get a little more speed. -#define NOENDIAN -#endif - - -vec3_t vec3_origin; - -//edictrun_t *sv_edicts; -//int sv_num_edicts; - -//int pr_edict_size; // in bytes -//int pr_max_edict_size; - -//unsigned short pr_crc; - -fdef_t *ED_FieldAtOfs (progfuncs_t *progfuncs, unsigned int ofs); -pbool ED_ParseEpair (progfuncs_t *progfuncs, void *base, ddefXX_t *key, char *s, int bits); - - - -/* -#define MAX_FIELD_LEN 64 -#define GEFV_CACHESIZE 5 - -typedef struct { - ddef_t *pcache; - char field[MAX_FIELD_LEN]; -} gefv_cache; - -static gefv_cache gefvCache[GEFV_CACHESIZE] = {{NULL, ""}, {NULL, ""}}; -*/ - -/* -================= -QC_ClearEdict - -Sets everything to NULL -================= -*/ -void QC_ClearEdict (progfuncs_t *progfuncs, struct edict_s *ed) -{ - edictrun_t *e = (edictrun_t *)ed; - int num = e->entnum; - memset (e->fields, 0, fields_size); - e->isfree = false; - e->entnum = num; -} - -edictrun_t *ED_AllocIntoTable (progfuncs_t *progfuncs, int num) -{ - edictrun_t *e; - - prinst->edicttable[num] = *(struct edict_s **)&e = (void*)memalloc(externs->edictsize); - memset(e, 0, externs->edictsize); - e->fields = PRAddressableAlloc(progfuncs, fields_size); - e->entnum = num; - QC_ClearEdict(progfuncs, (struct edict_s*)e); - - return e; -} - -/* -================= -ED_Alloc - -Either finds a free edict, or allocates a new one. -Try to avoid reusing an entity that was recently freed, because it -can cause the client to think the entity morphed into something else -instead of being removed and recreated, which can cause interpolated -angles and bad trails. -================= -*/ -struct edict_s *ED_Alloc (progfuncs_t *progfuncs) -{ - unsigned int i; - edictrun_t *e; - - for ( i=0 ; iisfree && ( e->freetime < 2 || *externs->gametime - e->freetime > 0.5 ) )) - { - if (!e) - e = ED_AllocIntoTable(progfuncs, i); - else - QC_ClearEdict (progfuncs, (struct edict_s*)e); - - if (externs->entspawn) - externs->entspawn((struct edict_s *) e, false); - return (struct edict_s *)e; - } - } - - if (i >= maxedicts-1) //try again, but use timed out ents. - { - for ( i=0 ; iisfree)) - { - if (!e) - e = ED_AllocIntoTable(progfuncs, i); - else - QC_ClearEdict (progfuncs, (struct edict_s*)e); - - if (externs->entspawn) - externs->entspawn((struct edict_s *) e, false); - return (struct edict_s *)e; - } - } - - if (i >= maxedicts-2) - { - printf("Running out of edicts\n"); - pr_trace = 1; //trip the debugger whilst it's still valid - } - if (i >= maxedicts-1) - { - int size; - char *buf; - buf = progfuncs->save_ents(progfuncs, NULL, &size, 0); - progfuncs->parms->WriteFile("edalloc.dump", buf, size); - Sys_Error ("ED_Alloc: no free edicts"); - } - } - - sv_num_edicts++; - e = (edictrun_t*)EDICT_NUM(progfuncs, i); - - if (!e) - e = ED_AllocIntoTable(progfuncs, i); - else - QC_ClearEdict (progfuncs, (struct edict_s*)e); - - if (externs->entspawn) - externs->entspawn((struct edict_s *) e, false); - - return (struct edict_s *)e; -} - -/* -================= -ED_Free - -Marks the edict as free -FIXME: walk all entities and NULL out references to this entity -================= -*/ -void ED_Free (progfuncs_t *progfuncs, struct edict_s *ed) -{ - edictrun_t *e = (edictrun_t *)ed; -// SV_UnlinkEdict (ed); // unlink from world bsp - - if (e->isfree) //this happens on start.bsp where an onlyregistered trigger killtargets itself (when all of this sort die after 1 trigger anyway). - { - if (pr_depth) - printf("Tried to free free entity within %s\n", pr_xfunction->s_name+progfuncs->stringtable); - else - printf("Engine tried to free free entity\n"); -// if (developer.value == 1) -// pr_trace = true; - return; - } - - if (externs->entcanfree) - if (!externs->entcanfree(ed)) //can stop an ent from being freed. - return; - - e->isfree = true; - e->freetime = (float)*externs->gametime; - -/* - ed->v.model = 0; - ed->v.takedamage = 0; - ed->v.modelindex = 0; - ed->v.colormap = 0; - ed->v.skin = 0; - ed->v.frame = 0; - VectorCopy (vec3_origin, ed->v.origin); - VectorCopy (vec3_origin, ed->v.angles); - ed->v.nextthink = -1; - ed->v.solid = 0; -*/ -} - -//=========================================================================== - -/* -============ -ED_GlobalAtOfs -============ -*/ -ddef16_t *ED_GlobalAtOfs16 (progfuncs_t *progfuncs, int ofs) -{ - ddef16_t *def; - unsigned int i; - - for (i=0 ; inumglobaldefs ; i++) - { - def = &pr_globaldefs16[i]; - if (def->ofs == ofs) - return def; - } - return NULL; -} -ddef32_t *ED_GlobalAtOfs32 (progfuncs_t *progfuncs, unsigned int ofs) -{ - ddef32_t *def; - unsigned int i; - - for (i=0 ; inumglobaldefs ; i++) - { - def = &pr_globaldefs32[i]; - if (def->ofs == ofs) - return def; - } - return NULL; -} - -/* -============ -ED_FieldAtOfs -============ -*/ -fdef_t *ED_FieldAtOfs (progfuncs_t *progfuncs, unsigned int ofs) -{ -// ddef_t *def; - unsigned int i; - - for (i=0 ; inumglobaldefs ; i++) - { - def = &pr_globaldefs16[i]; - if (!strcmp(def->s_name+progfuncs->stringtable,name) ) - return def; - } - return NULL; -} -ddef32_t *ED_FindGlobal32 (progfuncs_t *progfuncs, char *name) -{ - ddef32_t *def; - unsigned int i; - - for (i=1 ; inumglobaldefs ; i++) - { - def = &pr_globaldefs32[i]; - if (!strcmp(def->s_name+progfuncs->stringtable,name) ) - return def; - } - return NULL; -} - -unsigned int ED_FindGlobalOfs (progfuncs_t *progfuncs, char *name) -{ - ddef16_t *d16; - ddef32_t *d32; - switch(current_progstate->intsize) - { - case 24: - case 16: - d16 = ED_FindGlobal16(progfuncs, name); - return d16?d16->ofs:0; - case 32: - d32 = ED_FindGlobal32(progfuncs, name); - return d32?d32->ofs:0; - } - Sys_Error("ED_FindGlobalOfs - bad intsize"); - return 0; -} - -ddef16_t *ED_FindGlobalFromProgs16 (progfuncs_t *progfuncs, char *name, progsnum_t prnum) -{ - ddef16_t *def; - unsigned int i; - - for (i=1 ; inumglobaldefs ; i++) - { - def = &pr_progstate[prnum].globaldefs16[i]; - if (!strcmp(def->s_name+progfuncs->stringtable,name) ) - return def; - } - return NULL; -} -ddef32_t *ED_FindGlobalFromProgs32 (progfuncs_t *progfuncs, char *name, progsnum_t prnum) -{ - ddef32_t *def; - unsigned int i; - - for (i=1 ; inumglobaldefs ; i++) - { - def = &pr_progstate[prnum].globaldefs32[i]; - if (!strcmp(def->s_name+progfuncs->stringtable,name) ) - return def; - } - return NULL; -} - -ddef16_t *ED_FindTypeGlobalFromProgs16 (progfuncs_t *progfuncs, char *name, progsnum_t prnum, int type) -{ - ddef16_t *def; - unsigned int i; - - for (i=1 ; inumglobaldefs ; i++) - { - def = &pr_progstate[prnum].globaldefs16[i]; - if (!strcmp(def->s_name+progfuncs->stringtable,name) ) - { - if (pr_progstate[prnum].types) - { - if (pr_progstate[prnum].types[def->type&~DEF_SAVEGLOBAL].type != type) - continue; - } - else if ((def->type&(~DEF_SAVEGLOBAL)) != type) - continue; - return def; - } - } - return NULL; -} - - -ddef32_t *ED_FindTypeGlobalFromProgs32 (progfuncs_t *progfuncs, char *name, progsnum_t prnum, int type) -{ - ddef32_t *def; - unsigned int i; - - for (i=1 ; inumglobaldefs ; i++) - { - def = &pr_progstate[prnum].globaldefs32[i]; - if (!strcmp(def->s_name+progfuncs->stringtable,name) ) - { - if (pr_progstate[prnum].types) - { - if (pr_progstate[prnum].types[def->type&~DEF_SAVEGLOBAL].type != type) - continue; - } - else if ((def->type&(~DEF_SAVEGLOBAL)) != (unsigned)type) - continue; - return def; - } - } - return NULL; -} - -unsigned int *ED_FindGlobalOfsFromProgs (progfuncs_t *progfuncs, char *name, progsnum_t prnum, int type) -{ - ddef16_t *def16; - ddef32_t *def32; - static unsigned int pos; - switch(pr_progstate[prnum].intsize) - { - case 16: - case 24: - def16 = ED_FindTypeGlobalFromProgs16(progfuncs, name, prnum, type); - if (!def16) - return NULL; - pos = def16->ofs; - return &pos; - case 32: - def32 = ED_FindTypeGlobalFromProgs32(progfuncs, name, prnum, type); - if (!def32) - return NULL; - return &def32->ofs; - } - Sys_Error("ED_FindGlobalOfsFromProgs - bad intsize"); - return 0; -} - -/* -============ -ED_FindFunction -============ -*/ -dfunction_t *ED_FindFunction (progfuncs_t *progfuncs, char *name, progsnum_t *prnum, progsnum_t fromprogs) -{ - dfunction_t *func; - unsigned int i; - char *sep; - - progsnum_t pnum; - - if (prnum) - { - sep = strchr(name, ':'); - if (sep) - { - pnum = atoi(name); - name = sep+1; - } - else - { - if (fromprogs>=0) - pnum = fromprogs; - else - pnum = pr_typecurrent; - } - *prnum = pnum; - } - else - pnum = pr_typecurrent; - - if ((unsigned)pnum > (unsigned)maxprogs) - { - printf("Progsnum %i out of bounds\n", pnum); - return NULL; - } - - if (!pr_progstate[pnum].progs) - return NULL; - - for (i=1 ; inumfunctions ; i++) - { - func = &pr_progstate[pnum].functions[i]; - if (!strcmp(func->s_name+progfuncs->stringtable,name) ) - return func; - } - return NULL; -} - -/* -============ -PR_ValueString - -Returns a string describing *data in a type specific manner -============= -*/ -char *PR_ValueString (progfuncs_t *progfuncs, etype_t type, eval_t *val) -{ - static char line[256]; - fdef_t *fielddef; - dfunction_t *f; - -#ifdef DEF_SAVEGLOBAL - type &= ~DEF_SAVEGLOBAL; -#endif - - if (pr_types) - type = pr_types[type].type; - - switch (type) - { - case ev_struct: - sprintf (line, "struct"); - break; - case ev_union: - sprintf (line, "union"); - break; - case ev_string: - sprintf (line, "%s", PR_StringToNative(progfuncs, val->string)); - break; - case ev_entity: - sprintf (line, "entity %i", NUM_FOR_EDICT(progfuncs, (struct edict_s *)PROG_TO_EDICT(progfuncs, val->edict)) ); - break; - case ev_function: - if (!val->function) - sprintf (line, "NULL function"); - else - { - if ((val->function & 0xff000000)>>24 >= (unsigned)maxprogs || !pr_progstate[(val->function & 0xff000000)>>24].functions) - sprintf (line, "Bad function"); - else - { - f = pr_progstate[(val->function & 0xff000000)>>24].functions + (val->function & ~0xff000000); - sprintf (line, "%i:%s()", (val->function & 0xff000000)>>24, f->s_name+progfuncs->stringtable); - } - } - break; - case ev_field: - fielddef = ED_FieldAtOfs (progfuncs, val->_int ); - if (!fielddef) - sprintf (line, ".??? (%i)", val->_int); - else - sprintf (line, ".%s (%i)", fielddef->name, val->_int); - break; - case ev_void: - sprintf (line, "void type"); - break; - case ev_float: - sprintf (line, "%5.1f", val->_float); - break; - case ev_integer: - sprintf (line, "%i", val->_int); - break; - case ev_vector: - sprintf (line, "'%5.1f %5.1f %5.1f'", val->_vector[0], val->_vector[1], val->_vector[2]); - break; - case ev_pointer: - sprintf (line, "pointer"); - { -// int entnum; -// int valofs; - if (val->_int == 0) - { - sprintf (line, "NULL pointer"); - break; - } - //FIXME: :/ - sprintf(line, "UNKNOWN"); -// entnum = ((qbyte *)val->edict - (qbyte *)sv_edicts) / pr_edict_size; -// valofs = (int *)val->edict - (int *)edvars(EDICT_NUM(progfuncs, entnum)); -// fielddef = ED_FieldAtOfs (progfuncs, valofs ); -// if (!fielddef) -// sprintf(line, "ent%i.%s", entnum, "UNKNOWN"); -// else -// sprintf(line, "ent%i.%s", entnum, fielddef->s_name); - } - break; - default: - sprintf (line, "bad type %i", type); - break; - } - - return line; -} - -/* -============ -PR_UglyValueString - -Returns a string describing *data in a type specific manner -Easier to parse than PR_ValueString -============= -*/ -char *PR_UglyValueString (progfuncs_t *progfuncs, etype_t type, eval_t *val) -{ - static char line[256]; - fdef_t *fielddef; - dfunction_t *f; - int i, j; - -#ifdef DEF_SAVEGLOBAL - type &= ~DEF_SAVEGLOBAL; -#endif - - if (pr_types) - type = pr_types[type].type; - - switch (type) - { - case ev_struct: - sprintf (line, "structures cannot yet be saved"); - break; - case ev_union: - sprintf (line, "unions cannot yet be saved"); - break; - case ev_string: - { - char *outs = line; - int outb = sizeof(line)-2; - char *ins = PR_StringToNative(progfuncs, val->string); - //markup the output string. - while(*ins && outb > 0) - { - switch(*ins) - { - case '\n': - *outs++ = '\\'; - *outs++ = 'n'; - ins++; - outb-=2; - break; - case '\"': - *outs++ = '\\'; - *outs++ = '"'; - ins++; - outb-=2; - break; - case '\\': - *outs++ = '\\'; - *outs++ = '\\'; - ins++; - outb-=2; - break; - default: - *outs++ = *ins++; - outb--; - break; - } - } - *outs = 0; - } - break; - case ev_entity: - sprintf (line, "%i", val->_int); - break; - case ev_function: - i = (val->function & 0xff000000)>>24; //progs number - if ((unsigned)i >= maxprogs || !pr_progstate[(unsigned)i].progs) - sprintf (line, "BAD FUNCTION INDEX: %i", val->function); - else - { - j = (val->function & ~0xff000000); //function number - if ((unsigned)j >= pr_progstate[(unsigned)i].progs->numfunctions) - sprintf(line, "%i:%s", i, "CORRUPT FUNCTION POINTER"); - else - { - f = pr_progstate[(unsigned)i].functions + j; - sprintf (line, "%i:%s", i, f->s_name+progfuncs->stringtable); - } - } - break; - case ev_field: - fielddef = ED_FieldAtOfs (progfuncs, val->_int ); - sprintf (line, "%s", fielddef->name); - break; - case ev_void: - sprintf (line, "void"); - break; - case ev_float: - if (val->_float == (int)val->_float) - sprintf (line, "%i", (int)val->_float); //an attempt to cut down on the number of .000000 vars.. - else - sprintf (line, "%f", val->_float); - break; - case ev_integer: - sprintf (line, "%i", val->_int); - break; - case ev_vector: - if (val->_vector[0] == (int)val->_vector[0] && val->_vector[1] == (int)val->_vector[1] && val->_vector[2] == (int)val->_vector[2]) - sprintf (line, "%i %i %i", (int)val->_vector[0], (int)val->_vector[1], (int)val->_vector[2]); - else - sprintf (line, "%f %f %f", val->_vector[0], val->_vector[1], val->_vector[2]); - break; - default: - sprintf (line, "bad type %i", type); - break; - } - - return line; -} - -//compatible with Q1 (for savegames) -char *PR_UglyOldValueString (progfuncs_t *progfuncs, etype_t type, eval_t *val) -{ - static char line[256]; - fdef_t *fielddef; - dfunction_t *f; - -#ifdef DEF_SAVEGLOBAL - type &= ~DEF_SAVEGLOBAL; -#endif - - if (pr_types) - type = pr_types[type].type; - - switch (type) - { - case ev_struct: - sprintf (line, "structures cannot yet be saved"); - break; - case ev_union: - sprintf (line, "unions cannot yet be saved"); - break; - case ev_string: - sprintf (line, "%s", PR_StringToNative(progfuncs, val->string)); - break; - case ev_entity: - sprintf (line, "%i", NUM_FOR_EDICT(progfuncs, (struct edict_s *)PROG_TO_EDICT(progfuncs, val->edict))); - break; - case ev_function: - f = pr_progstate[(val->function & 0xff000000)>>24].functions + (val->function & ~0xff000000); - sprintf (line, "%s", f->s_name+progfuncs->stringtable); - break; - case ev_field: - fielddef = ED_FieldAtOfs (progfuncs, val->_int ); - sprintf (line, "%s", fielddef->name); - break; - case ev_void: - sprintf (line, "void"); - break; - case ev_float: - if (val->_float == (int)val->_float) - sprintf (line, "%i", (int)val->_float); //an attempt to cut down on the number of .000000 vars.. - else - sprintf (line, "%f", val->_float); - break; - case ev_integer: - sprintf (line, "%i", val->_int); - break; - case ev_vector: - if (val->_vector[0] == (int)val->_vector[0] && val->_vector[1] == (int)val->_vector[1] && val->_vector[2] == (int)val->_vector[2]) - sprintf (line, "%i %i %i", (int)val->_vector[0], (int)val->_vector[1], (int)val->_vector[2]); - else - sprintf (line, "%f %f %f", val->_vector[0], val->_vector[1], val->_vector[2]); - break; - break; - default: - sprintf (line, "bad type %i", type); - break; - } - - return line; -} - -char *PR_TypeString(progfuncs_t *progfuncs, etype_t type) -{ -#ifdef DEF_SAVEGLOBAL - type &= ~DEF_SAVEGLOBAL; -#endif - - if (pr_types) - type = pr_types[type].type; - - switch (type) - { - case ev_struct: - return "struct"; - case ev_union: - return "union"; - case ev_string: - return "string"; - case ev_entity: - return "entity"; - case ev_function: - return "function"; - case ev_field: - return "field"; - case ev_void: - return "void"; - case ev_float: - return "float"; - case ev_vector: - return "vector"; - case ev_integer: - return "integer"; - default: - return "BAD TYPE"; - } -} - -/* -============ -PR_GlobalString - -Returns a string with a description and the contents of a global, -padded to 20 field width -============ -*/ -char *PR_GlobalString (progfuncs_t *progfuncs, int ofs) -{ - char *s; - int i; - ddef16_t *def16; - ddef32_t *def32; - void *val; - static char line[128]; - - switch (current_progstate->intsize) - { - case 16: - case 24: - val = (void *)&pr_globals[ofs]; - def16 = ED_GlobalAtOfs16(progfuncs, ofs); - if (!def16) - sprintf (line,"%i(?""?""?)", ofs); - else - { - s = PR_ValueString (progfuncs, def16->type, val); - sprintf (line,"%i(%s)%s", ofs, def16->s_name+progfuncs->stringtable, s); - } - - i = strlen(line); - for ( ; i<20 ; i++) - strcat (line," "); - strcat (line," "); - return line; - case 32: - val = (void *)&pr_globals[ofs]; - def32 = ED_GlobalAtOfs32(progfuncs, ofs); - if (!def32) - sprintf (line,"%i(?""?""?)", ofs); - else - { - s = PR_ValueString (progfuncs, def32->type, val); - sprintf (line,"%i(%s)%s", ofs, def32->s_name+progfuncs->stringtable, s); - } - - i = strlen(line); - for ( ; i<20 ; i++) - strcat (line," "); - strcat (line," "); - return line; - } - Sys_Error("Bad offset size in PR_GlobalString"); - return ""; -} - -char *PR_GlobalStringNoContents (progfuncs_t *progfuncs, int ofs) -{ - int i; - ddef16_t *def16; - ddef32_t *def32; - static char line[128]; - - switch (current_progstate->intsize) - { - case 16: - case 24: - def16 = ED_GlobalAtOfs16(progfuncs, ofs); - if (!def16) - sprintf (line,"%i(?""?""?)", ofs); - else - sprintf (line,"%i(%s)", ofs, def16->s_name+progfuncs->stringtable); - break; - case 32: - def32 = ED_GlobalAtOfs32(progfuncs, ofs); - if (!def32) - sprintf (line,"%i(?""?""?)", ofs); - else - sprintf (line,"%i(%s)", ofs, def32->s_name+progfuncs->stringtable); - break; - default: - Sys_Error("Bad offset size in PR_GlobalStringNoContents"); - } - - i = strlen(line); - for ( ; i<20 ; i++) - strcat (line," "); - strcat (line," "); - - return line; -} - - -/* -============= -ED_Print - -For debugging -============= -*/ -void ED_Print (progfuncs_t *progfuncs, struct edict_s *ed) -{ - int l; - fdef_t *d; - int *v; - unsigned int i;unsigned int j; - char *name; - int type; - - if (((edictrun_t *)ed)->isfree) - { - printf ("FREE\n"); - return; - } - - printf("\nEDICT %i:\n", NUM_FOR_EDICT(progfuncs, (struct edict_s *)ed)); - for (i=1 ; iname; - l = strlen(name); - if (l >= 2 && name[l-2] == '_') - continue; // skip _x, _y, _z vars - - v = (int *)((char *)edvars(ed) + d->ofs*4); - - // if the value is still all 0, skip the field -#ifdef DEF_SAVEGLOBAL - type = d->type & ~DEF_SAVEGLOBAL; -#else - type = d->type; -#endif - - for (j=0 ; jtype, (eval_t *)v)); - } -} - -void ED_PrintNum (progfuncs_t *progfuncs, int ent) -{ - ED_Print (progfuncs, EDICT_NUM(progfuncs, ent)); -} - -/* -============= -ED_PrintEdicts - -For debugging, prints all the entities in the current server -============= -*/ -void ED_PrintEdicts (progfuncs_t *progfuncs) -{ - unsigned int i; - - printf ("%i entities\n", sv_num_edicts); - for (i=0 ; iisfree) - continue; - active++; -// if (ent->v.solid) -// solid++; -// if (ent->v.model) -// models++; -// if (ent->v.movetype == MOVETYPE_STEP) -// step++; - } - - printf ("num_edicts:%3i\n", sv_num_edicts); - printf ("active :%3i\n", active); -// Con_Printf ("view :%3i\n", models); -// Con_Printf ("touch :%3i\n", solid); -// Con_Printf ("step :%3i\n", step); - -} - - - -//============================================================================ - - -/* -============= -ED_NewString -============= -*/ -char *ED_NewString (progfuncs_t *progfuncs, char *string, int minlength) -{ - char *newc, *new_p; - int i,l; - - minlength++; - - l = strlen(string) + 1; - - newc = PRAddressableAlloc (progfuncs, lofs); - - if (pr_types) - type = pr_types[((ddef16_t*)key)->type & ~DEF_SAVEGLOBAL].type; - else - type = ((ddef16_t*)key)->type & ~DEF_SAVEGLOBAL; - break; - case 32: - d = (void *)((int *)base + ((ddef32_t*)key)->ofs); - - if (pr_types) - type = pr_types[((ddef32_t*)key)->type & ~DEF_SAVEGLOBAL].type; - else - type = ((ddef32_t*)key)->type & ~DEF_SAVEGLOBAL; - break; - default: - Sys_Error("Bad bits in ED_ParseEpair"); - d = 0; - } - - switch (type) - { - case ev_string: - st = PR_StringToProgs(progfuncs, ED_NewString (progfuncs, s, 0)); - *(string_t *)d = st; - break; - - case ev_float: - *(float *)d = (float)atof (s); - break; - - case ev_integer: - *(int *)d = atoi (s); - break; - - case ev_vector: - strcpy (string, s); - v = string; - w = string; - for (i=0 ; i<3 ; i++) - { - while (*v && *v != ' ') - v++; - *v = 0; - ((float *)d)[i] = (float)atof (w); - w = v = v+1; - } - break; - - case ev_entity: - *(int *)d = atoi (s); - break; - - case ev_field: - def = ED_FindField (progfuncs, s); - if (!def) - { - printf ("Can't find field %s\n", s); - return false; - } - *(int *)d = def->ofs; - break; - - case ev_function: - if (s[1]==':'&&s[2]=='\0') - { - *(func_t *)d = 0; - return true; - } - func = ED_FindFunction (progfuncs, s, &i, -1); - if (!func) - { - printf ("Can't find function %s\n", s); - return false; - } - *(func_t *)d = (func - pr_progstate[i].functions) | (i<<24); - break; - - default: - break; - } - return true; -} - -/* -==================== -ED_ParseEdict - -Parses an edict out of the given string, returning the new position -ed should be a properly initialized empty edict. -Used for initial level load and for savegames. -==================== -*/ -#if 1 -char *ED_ParseEdict (progfuncs_t *progfuncs, char *data, edictrun_t *ent) -{ - fdef_t *key; - pbool init; - char keyname[256]; - int n; - -// eval_t *val; - - init = false; - -// clear it -// if (ent != (edictrun_t *)sv_edicts) // hack -// memset (ent+1, 0, pr_edict_size - sizeof(edictrun_t)); - -// go through all the dictionary pairs - while (1) - { - // parse key - data = QCC_COM_Parse (data); - if (qcc_token[0] == '}') - break; - if (!data) - { - printf ("ED_ParseEntity: EOF without closing brace\n"); - return NULL; - } - - strncpy (keyname, qcc_token, sizeof(keyname)-1); - keyname[sizeof(keyname)-1] = 0; - - // another hack to fix heynames with trailing spaces - n = strlen(keyname); - while (n && keyname[n-1] == ' ') - { - keyname[n-1] = 0; - n--; - } - - // parse value - data = QCC_COM_Parse (data); - if (!data) - { - printf ("ED_ParseEntity: EOF without closing brace\n"); - return NULL; - } - - if (qcc_token[0] == '}') - { - printf ("ED_ParseEntity: closing brace without data\n"); - return NULL; - } - - init = true; - -// keynames with a leading underscore are used for utility comments, -// and are immediately discarded by quake - if (keyname[0] == '_') - continue; - - key = ED_FindField (progfuncs, keyname); - if (!key) - { - if (!strcmp(keyname, "angle")) //Quake anglehack - we've got to leave it in cos it doesn't work for quake otherwise, and this is a QuakeC lib! - { - if ((key = ED_FindField (progfuncs, "angles"))) - { - sprintf (qcc_token, "0 %f 0", atof(qcc_token)); //change it from yaw to 3d angle - goto cont; - } - } - if (!strcmp(keyname, "light")) //Quake lighthack - allows a field name and a classname to go by the same thing in the level editor - if ((key = ED_FindField (progfuncs, "light_lev"))) - goto cont; - printf ("'%s' is not a field\n", keyname); - continue; - } - -cont: - if (!ED_ParseEpair (progfuncs, ent->fields, (ddefXX_t*)key, qcc_token, 32)) - { - continue; -// Sys_Error ("ED_ParseEdict: parse error on entities"); - } - } - - if (!init) - ent->isfree = true; - - return data; -} -#endif - -/* -================ -ED_LoadFromFile - -The entities are directly placed in the array, rather than allocated with -ED_Alloc, because otherwise an error loading the map would have entity -number references out of order. - -Creates a server's entity / program execution context by -parsing textual entity definitions out of an ent file. - -Used for both fresh maps and savegame loads. A fresh map would also need -to call ED_CallSpawnFunctions () to let the objects initialize themselves. -================ -*/ - -char *ED_WriteGlobals(progfuncs_t *progfuncs, char *buffer) //switch first. -{ -#define AddS(str) strcpy(buffer, str);buffer+=strlen(str); - int *v; - ddef32_t *def32; - ddef16_t *def16; - unsigned int i; - unsigned int j; - char *name; - int type; - int curprogs = pr_typecurrent; - int len; - switch(current_progstate->intsize) - { - case 16: - case 24: - for (i=0 ; inumglobaldefs ; i++) - { - def16 = &pr_globaldefs16[i]; - name = def16->s_name + progfuncs->stringtable; - len = strlen(name); - if (!*name) - continue; - if (name[len-2] == '_' && (name[len-1] == 'x' || name[len-1] == 'y' || name[len-1] == 'z')) - continue; // skip _x, _y, _z vars (vector components, which are saved as one vector not 3 floats) - - type = def16->type; - -#ifdef DEF_SAVEGLOBAL - if ( !(def16->type & DEF_SAVEGLOBAL) ) - continue; - type &= ~DEF_SAVEGLOBAL; -#endif - if (current_progstate->types) - type = current_progstate->types[type].type; - if (type == ev_function) - { - v = (int *)¤t_progstate->globals[def16->ofs]; - if ((v[0]&0xff000000)>>24 == (unsigned)curprogs) //same progs - { - if (!progfuncs->stringtable[current_progstate->functions[v[0]&0x00ffffff].s_name]) - continue; - else if (!strcmp(current_progstate->functions[v[0]&0x00ffffff].s_name+ progfuncs->stringtable, name)) //names match. Assume function is at initial value. - continue; - } - - if (curprogs!=0) - if ((v[0]&0xff000000)>>24 == 0) - if (!ED_FindFunction(progfuncs, name, NULL, curprogs)) //defined as extern - { - if (!progfuncs->stringtable[pr_progstate[0].functions[v[0]&0x00ffffff].s_name]) - continue; - else if (!strcmp(pr_progstate[0].functions[v[0]&0x00ffffff].s_name + progfuncs->stringtable, name)) //same name. - continue; - } - - //else function has been redirected externally. - goto add16; - } - else if (type != ev_string //anything other than these is not saved - && type != ev_float - && type != ev_integer - && type != ev_entity - && type != ev_vector) - continue; - - v = (int *)¤t_progstate->globals[def16->ofs]; - - // make sure the value is not null, where there's no point in saving - for (j=0 ; jtype&~DEF_SAVEGLOBAL, (eval_t *)v))); - } - break; - case 32: - for (i=0 ; inumglobaldefs ; i++) - { - def32 = &pr_globaldefs32[i]; - name = def32->s_name + progfuncs->stringtable; - if (name[strlen(name)-2] == '_') - continue; // skip _x, _y, _z vars (vector components, which are saved as one vector not 3 floats) - - type = def32->type; - -#ifdef DEF_SAVEGLOBAL - if ( !(def32->type & DEF_SAVEGLOBAL) ) - continue; - type &= ~DEF_SAVEGLOBAL; -#endif - if (current_progstate->types) - type = current_progstate->types[type].type; - if (type == ev_function) - { - v = (int *)¤t_progstate->globals[def32->ofs]; - if ((v[0]&0xff000000)>>24 == (unsigned)curprogs) //same progs - if (!strcmp(current_progstate->functions[v[0]&0x00ffffff].s_name+ progfuncs->stringtable, name)) //names match. Assume function is at initial value. - continue; - - if (curprogs!=0) - if ((v[0]&0xff000000)>>24 == 0) - if (!ED_FindFunction(progfuncs, name, NULL, curprogs)) //defined as extern - if (!strcmp(pr_progstate[0].functions[v[0]&0x00ffffff].s_name+ progfuncs->stringtable, name)) //same name. - continue; - - //else function has been redirected externally. - goto add32; - } - else if (type != ev_string //anything other than these is not saved - && type != ev_float - && type != ev_integer - && type != ev_entity - && type != ev_vector) - continue; - - v = (int *)¤t_progstate->globals[def32->ofs]; - - // make sure the value is not null, where there's no point in saving - for (j=0 ; jtype&~DEF_SAVEGLOBAL, (eval_t *)v))); - } - break; - default: - Sys_Error("Bad number of bits in SaveEnts"); - } - - return buffer; -} - -char *ED_WriteEdict(progfuncs_t *progfuncs, edictrun_t *ed, char *buffer, pbool q1compatible) -{ - fdef_t *d; - - int *v; - unsigned int i;unsigned int j; - char *name; - int type; - int len; - - for (i=0 ; iname; - len = strlen(name); - if (len>4 && (name[len-2] == '_' && (name[len-1] == 'x' || name[len-1] == 'y' || name[len-1] == 'z'))) - continue; // skip _x, _y, _z vars - - v = (int *)((char*)ed->fields + d->ofs*4); - - // if the value is still all 0, skip the field -#ifdef DEF_SAVEGLOBAL - type = d->type & ~DEF_SAVEGLOBAL; -#else - type = d->type; -#endif - - for (j=0 ; jtype, (eval_t *)v))); - } - - return buffer; -#undef AddS -} - -char *SaveCallStack (progfuncs_t *progfuncs, char *s) -{ -#define AddS(str) strcpy(s, str);s+=strlen(str); - char buffer[8192]; - dfunction_t *f; - int i; - int progs; - - int arg; - int *globalbase; - - progs = -1; - - if (pr_depth == 0) - { - AddS ("\n"); - return s; - } - - globalbase = (int *)pr_globals + pr_xfunction->parm_start + pr_xfunction->locals; - - pr_stack[pr_depth].f = pr_xfunction; - for (i=pr_depth ; i>0 ; i--) - { - f = pr_stack[i].f; - - if (!f) - { - AddS ("\n"); - } - else - { - if (pr_stack[i].progsnum != progs) - { - progs = pr_stack[i].progsnum; - - sprintf(buffer, "//%i %s\n", progs, pr_progstate[progs].filename); - AddS (buffer); - } - if (!f->s_file) - sprintf(buffer, "\t\"%i:%s\"\n", progs, f->s_name+progfuncs->stringtable); - else - sprintf(buffer, "\t\"%i:%s\" //%s\n", progs, f->s_name+progfuncs->stringtable, f->s_file+progfuncs->stringtable); - AddS (buffer); - - AddS ("\t{\n"); - for (arg = 0; arg < f->locals; arg++) - { - ddef16_t *local; - local = ED_GlobalAtOfs16(progfuncs, f->parm_start+arg); - if (!local) - sprintf(buffer, "\t\tofs%i %i // %f\n", f->parm_start+arg, *(int *)(globalbase - f->locals+arg), *(float *)(globalbase - f->locals+arg) ); - else - { - if (local->type == ev_entity) - { - sprintf(buffer, "\t\t\"%s\" \"entity %i\"\n", local->s_name+progfuncs->stringtable, ((eval_t*)(globalbase - f->locals+arg))->edict); - } - else - sprintf(buffer, "\t\t\"%s\"\t\"%s\"\n", local->s_name+progfuncs->stringtable, PR_ValueString(progfuncs, local->type, (eval_t*)(globalbase - f->locals+arg))); - - if (local->type == ev_vector) - arg+=2; - } - AddS (buffer); - } - AddS ("\t}\n"); - - if (i == pr_depth) - globalbase = localstack + localstack_used - f->locals; - else - globalbase -= f->locals; - } - } - return s; -#undef AddS -} - -//there are two ways of saving everything. -//0 is to save just the entities. -//1 is to save the entites, and all the progs info so that all the variables are saved off, and it can be reloaded to exactly how it was (provided no files or data has been changed outside, like the progs.dat for example) -char *SaveEnts(progfuncs_t *progfuncs, char *mem, int *len, int alldata) -{ -#define AddS(str) strcpy(s, str);s+=strlen(str); - char *s, *os; - unsigned int a; - int oldprogs; - - if (mem) - { - os = s = mem; - } - else - os = s = memalloc(5*1024*1024); - - if (alldata == 2) - { //special Q1 savegame compatability mode. - //engine will need to store references to progs type and will need to preload the progs and inti the ents itself before loading. - - //Make sure there is only 1 progs loaded. - for (a = 1; a < maxprogs; a++) - { - if (pr_progstate[a].progs) - break; - } - if (!pr_progstate[0].progs || a != maxprogs) //the state of the progs wasn't Q1 compatible. - { - memfree(os); - return NULL; - } - - //write the globals - AddS ("{\n"); - - oldprogs = pr_typecurrent; - PR_SwitchProgs(progfuncs, 0); - - s = ED_WriteGlobals(progfuncs, s); - - PR_SwitchProgs(progfuncs, oldprogs); - - AddS ("}\n"); - - - //write the ents - for (a = 0; a < sv_num_edicts; a++) - { - edictrun_t *ed = (edictrun_t *)EDICT_NUM(progfuncs, a); - - AddS ("{\n"); - - if (!ed->isfree) - s = ED_WriteEdict(progfuncs, ed, s, true); - - AddS ("}\n"); - } - - *len = s - os; - return os; - } - - if (alldata) - { - AddS("general {\n"); - AddS(qcva("\"maxprogs\" \"%i\"\n", maxprogs)); -// AddS(qcva("\"maxentities\" \"%i\"\n", maxedicts)); -// AddS(qcva("\"mem\" \"%i\"\n", hunksize)); -// AddS(qcva("\"crc\" \"%i\"\n", header_crc)); - AddS(qcva("\"numentities\" \"%i\"\n", sv_num_edicts)); - AddS("}\n"); - - oldprogs = pr_typecurrent; - - for (a = 0; a < maxprogs; a++) - { - if (!pr_progstate[a].progs) - continue; - PR_SwitchProgs(progfuncs, a); - { - AddS (qcva("progs %i {\n", a)); - AddS (qcva("\"filename\" \"%s\"\n", pr_progstate[a].filename)); - AddS (qcva("\"crc\" \"%i\"\n", pr_progs->crc)); - AddS (qcva("\"numbuiltins\" \"%i\"\n", current_progstate->numbuiltins)); - AddS ("}\n"); - } - } - - if (alldata == 3) - { - //include callstack - AddS("stacktrace {\n"); - s = SaveCallStack(progfuncs, s); - AddS("}\n"); - } - - for (a = 0; a < maxprogs; a++) //I would mix, but external functions rely on other progs being loaded - { - if (!pr_progstate[a].progs) - continue; - - AddS (qcva("globals %i {\n", a)); - - PR_SwitchProgs(progfuncs, a); - - s = ED_WriteGlobals(progfuncs, s); - - AddS ("}\n"); - } - PR_SwitchProgs(progfuncs, oldprogs); - } - for (a = 0; a < sv_num_edicts; a++) - { - edictrun_t *ed = (edictrun_t *)EDICT_NUM(progfuncs, a); - - if (ed->isfree) - continue; - - AddS (qcva("entity %i{\n", a)); - - s = ED_WriteEdict(progfuncs, ed, s, false); - - AddS ("}\n"); - } - - *len = s - os; - return os; - -#undef AddS -} - -int header_crc; - -//if 'general' block is found, this is a compleate state, otherwise, we should spawn entities like -int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags) -{ - eval_t *fulldata; //this is part of FTE_FULLSPAWNDATA - char *datastart; - - eval_t *var; - - char filename[128]; - int num; - int numbuiltins; - edictrun_t *ed=NULL; - ddef16_t *d16; - ddef32_t *d32; - func_t CheckSpawn=0; - - extern edictrun_t tempedict; - - int crc = 1; - int entsize = 0; - int numents = 0; - - pbool resethunk=0; - pbool isloadgame; - if (!strncmp(file, "loadgame", 8)) - { - isloadgame = true; - numents = -1; - file+=8; - fulldata = NULL; - } - else - { - isloadgame = false; - - if (pr_typecurrent>=0) - num = ED_FindGlobalOfs(progfuncs, "__fullspawndata"); - else - num = 0; - if (num) - fulldata = (eval_t *)((int *)pr_globals + num); - else - fulldata = NULL; - } - - while(1) - { - datastart = file; - file = QCC_COM_Parse(file); - if (file == NULL) - break; //finished reading file - else if (!strcmp(qcc_token, "entity")) - { - if (entsize == 0 && resethunk) //edicts have not yet been initialized, and this is a compleate load (memsize has been set) - { - entsize = PR_InitEnts(progfuncs, maxedicts); -// sv_num_edicts = numents; - - for (num = 0; num < numents; num++) - { - ed = (edictrun_t *)EDICT_NUM(progfuncs, num); - - if (!ed) - { - ed = ED_AllocIntoTable(progfuncs, num); - ed->isfree = true; - if (externs->entspawn) - externs->entspawn((struct edict_s *) ed, true); - } - } - } - - file = QCC_COM_Parse(file); - num = atoi(qcc_token); - file = QCC_COM_Parse(file); - if (qcc_token[0] != '{') - Sys_Error("Progs loading found %s, not '{'", qcc_token); - if (!resethunk) - ed = (edictrun_t *)ED_Alloc(progfuncs); - else - { - ed = (edictrun_t *)EDICT_NUM(progfuncs, num); - - if (!ed) - { - Sys_Error("Edict was not allocated\n"); - ed = ED_AllocIntoTable(progfuncs, num); - } - } - ed->isfree = false; - if (externs->entspawn) - externs->entspawn((struct edict_s *) ed, true); - file = ED_ParseEdict(progfuncs, file, ed); - - if (killonspawnflags) - { - var = GetEdictFieldValue (progfuncs, (struct edict_s *)&ed, "spawnflags", &spawnflagscache); - if (var) - { - if ((int)var->_float & (int)killonspawnflags) - { - ed->isfree = true; - continue; - } - } - } - - if (!resethunk) - { - dfunction_t *f; - if ((var = GetEdictFieldValue (progfuncs, (struct edict_s *)ed, "classname", NULL))) - { - f = ED_FindFunction(progfuncs, var->string + progfuncs->stringtable, NULL, -1); - if (f) - { - var = (eval_t *)((int *)pr_globals + ED_FindGlobalOfs(progfuncs, "self")); - var->edict = EDICT_TO_PROG(progfuncs, ed); - PR_ExecuteProgram(progfuncs, f-pr_functions); - } - } - } - } - else if (!strcmp(qcc_token, "progs")) - { - file = QCC_COM_Parse(file); - num = atoi(qcc_token); - file = QCC_COM_Parse(file); - if (qcc_token[0] != '{') - Sys_Error("Progs loading found %s, not '{'", qcc_token); - - - filename[0] = '\0'; - header_crc = 0; - numbuiltins = 0; - - while(1) - { - file = QCC_COM_Parse(file); //read the key - if (!file) - Sys_Error("EOF in progs block"); - - if (!strcmp("filename", qcc_token)) //check key get and save values - {file = QCC_COM_Parse(file); strcpy(filename, qcc_token);} - else if (!strcmp("crc", qcc_token)) - {file = QCC_COM_Parse(file); header_crc = atoi(qcc_token);} - else if (!strcmp("numbuiltins", qcc_token)) - {file = QCC_COM_Parse(file); numbuiltins = atoi(qcc_token);} - else if (qcc_token[0] == '}') //end of block - break; - else - Sys_Error("Bad key \"%s\" in progs block", qcc_token); - } - - PR_ReallyLoadProgs(progfuncs, filename, header_crc, &pr_progstate[num], true); - if (!externs->builtinsfor) - { - // Sys_Error("Couldn't reset the builtin functions"); - current_progstate->builtins = NULL; //these are specific, we assume the global ones were set via pr_configure - current_progstate->numbuiltins = 0; - } - else - { - current_progstate->builtins = externs->builtinsfor(num, header_crc); - current_progstate->numbuiltins = numbuiltins; - } - } - else if (!strcmp(qcc_token, "globals")) - { - if (entsize == 0 && resethunk) //by the time we parse some globals, we MUST have loaded all progs - { - entsize = PR_InitEnts(progfuncs, maxedicts); -// sv_num_edicts = numents; - - for (num = 0; num < numents; num++) - { - ed = (edictrun_t *)EDICT_NUM(progfuncs, num); - - if (!ed) - { - ed = ED_AllocIntoTable(progfuncs, num); - ed->isfree = true; - } - - if (externs->entspawn) - externs->entspawn((struct edict_s *) ed, true); - } - } - - file = QCC_COM_Parse(file); - num = atoi(qcc_token); - - file = QCC_COM_Parse(file); - if (qcc_token[0] != '{') - Sys_Error("Globals loading found \'%s\', not '{'", qcc_token); - - PR_SwitchProgs(progfuncs, num); - while (1) - { - file = QCC_COM_Parse(file); - if (qcc_token[0] == '}') - break; - else if (!qcc_token[0] || !file) - Sys_Error("EOF when parsing global values"); - - switch(current_progstate->intsize) - { - case 16: - case 24: - if (!(d16 = ED_FindGlobal16(progfuncs, qcc_token))) - { - file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); - } - else - { - file = QCC_COM_Parse(file); - ED_ParseEpair(progfuncs, pr_globals, (ddefXX_t*)d16, qcc_token, 16); - } - break; - case 32: - if (!(d32 = ED_FindGlobal32(progfuncs, qcc_token))) - { - file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); - } - else - { - file = QCC_COM_Parse(file); - ED_ParseEpair(progfuncs, pr_globals, (ddefXX_t*)d32, qcc_token, 32); - } - break; - default: - Sys_Error("Bad intsize in LoadEnts"); - } - } - -// file = QCC_COM_Parse(file); -// if (com_token[0] != '}') -// Sys_Error("Progs loading found %s, not '}'", qcc_token); - } - else if (!strcmp(qcc_token, "general")) - { - QC_StartShares(progfuncs); -// QC_InitShares(); //forget stuff -// pr_edict_size = 0; - max_fields_size=0; - - file = QCC_COM_Parse(file); - if (qcc_token[0] != '{') - Sys_Error("Progs loading found %s, not '{'", qcc_token); - - while(1) - { - file = QCC_COM_Parse(file); //read the key - if (!file) - Sys_Error("EOF in general block"); - - if (!strcmp("maxprogs", qcc_token)) //check key get and save values - {file = QCC_COM_Parse(file); maxprogs = atoi(qcc_token);} -// else if (!strcmp("maxentities", com_token)) -// {file = QCC_COM_Parse(file); maxedicts = atoi(qcc_token);} -// else if (!strcmp("mem", com_token)) -// {file = QCC_COM_Parse(file); memsize = atoi(qcc_token);} -// else if (!strcmp("crc", com_token)) -// {file = QCC_COM_Parse(file); crc = atoi(qcc_token);} - else if (!strcmp("numentities", qcc_token)) - {file = QCC_COM_Parse(file); numents = atoi(qcc_token);} - else if (qcc_token[0] == '}') //end of block - break; - else - Sys_Error("Bad key \"%s\" in general block", qcc_token); - } - - PRAddressableFlush(progfuncs, -1); - resethunk=true; - - pr_progstate = PRHunkAlloc(progfuncs, sizeof(progstate_t) * maxprogs); - pr_typecurrent=0; - - sv_num_edicts = 1; //set up a safty buffer so things won't go horribly wrong too often - sv_edicts=(struct edict_s *)&tempedict; - prinst->edicttable = &sv_edicts; - - - sv_num_edicts = numents; //should be fine - -// PR_Configure(crc, NULL, memsize, maxedicts, maxprogs); - } - else if (!strcmp(qcc_token, "{")) - { - if (isloadgame) - { - if (numents == -1) //globals - { - while (1) - { - file = QCC_COM_Parse(file); - if (qcc_token[0] == '}') - break; - else if (!qcc_token[0] || !file) - Sys_Error("EOF when parsing global values"); - - switch(current_progstate->intsize) - { - case 16: - case 24: - if (!(d16 = ED_FindGlobal16(progfuncs, qcc_token))) - { - file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); - } - else - { - file = QCC_COM_Parse(file); - ED_ParseEpair(progfuncs, pr_globals, (ddefXX_t*)d16, qcc_token, 16); - } - break; - case 32: - if (!(d32 = ED_FindGlobal32(progfuncs, qcc_token))) - { - file = QCC_COM_Parse(file); - printf("global value %s not found", qcc_token); - } - else - { - file = QCC_COM_Parse(file); - ED_ParseEpair(progfuncs, pr_globals, (ddefXX_t*)d32, qcc_token, 32); - } - break; - default: - Sys_Error("Bad intsize in LoadEnts"); - } - } - } - else - { - ed = (edictrun_t *)EDICT_NUM(progfuncs, numents); - if (!ed) - ed = ED_AllocIntoTable(progfuncs, numents); - - if (externs->entspawn) - externs->entspawn((struct edict_s *) ed, true); - - sv_num_edicts = numents; - ed->isfree = false; - file = ED_ParseEdict (progfuncs, file, ed); - } - numents++; - continue; - } - - if (entsize == 0 && resethunk) //edicts have not yet been initialized, and this is a compleate load (memsize has been set) - { - entsize = PR_InitEnts(progfuncs, maxedicts); -// sv_num_edicts = numents; - - for (num = 0; num < numents; num++) - { - ed = (edictrun_t *)EDICT_NUM(progfuncs, num); - - if (!ed) - { - ed = ED_AllocIntoTable(progfuncs, num); - ed->isfree = true; - } - } - } - - if (!ed) //first entity - ed = (edictrun_t *)EDICT_NUM(progfuncs, 0); - else - ed = (edictrun_t *)ED_Alloc(progfuncs); - ed->isfree = false; - if (externs->entspawn) - externs->entspawn((struct edict_s *) ed, true); - file = ED_ParseEdict(progfuncs, file, ed); - - if (killonspawnflags) - { - var = GetEdictFieldValue (progfuncs, (struct edict_s *)ed, "spawnflags", &spawnflagscache); - if (var) - { - if ((int)var->_float & (int)killonspawnflags) - { - ed->isfree = true; - ed->freetime = 0; - continue; - } - } - } - - if (!resethunk) - { - char *eclassname; - func_t f; - if (!CheckSpawn) - CheckSpawn = PR_FindFunc(progfuncs, "CheckSpawn", -2); - - var = GetEdictFieldValue (progfuncs, (struct edict_s *)ed, "classname", NULL); - if (!var || !var->string || !*PR_StringToNative(progfuncs, var->string)) - { - printf("No classname\n"); - ED_Free(progfuncs, (struct edict_s *)ed); - } - else - { - eval_t *selfvar; - - //added by request of Mercury. - if (fulldata) //this is a vital part of HL map support!!! - { //essentually, it passes the ent's spawn info to the ent. - char *nl; //otherwise it sees only the named fields of - char *spawndata;//a standard quake ent. - spawndata = PRHunkAlloc(progfuncs, file - datastart +1); - strncpy(spawndata, datastart, file - datastart); - spawndata[file - datastart] = '\0'; - for (nl = spawndata; *nl; nl++) - if (*nl == '\n') - *nl = '\t'; - fulldata->string = PR_StringToProgs(progfuncs, spawndata); - } - - selfvar = (eval_t *)((int *)pr_globals + ED_FindGlobalOfs(progfuncs, "self")); - selfvar->edict = EDICT_TO_PROG(progfuncs, ed); - - //DP_SV_SPAWNFUNC_PREFIX support - eclassname = PR_StringToNative(progfuncs, var->string); -#ifdef _WIN32 - _snprintf(filename, sizeof(filename), "spawnfunc_%s", eclassname); - filename[sizeof(filename)-1] = 0; -#else - snprintf(filename, sizeof(filename), "spawnfunc_%s", eclassname); -#endif - f = PR_FindFunc(progfuncs, filename, PR_ANYBACK); - if (!f) - f = PR_FindFunc(progfuncs, eclassname, PR_ANYBACK); - if (f) - { - if (CheckSpawn) - { - G_INT(OFS_PARM0) = f; - PR_ExecuteProgram(progfuncs, CheckSpawn); - //call the spawn func or remove. - } - else - PR_ExecuteProgram(progfuncs, f); - } - else if (CheckSpawn) - { - G_INT(OFS_PARM0) = 0; - PR_ExecuteProgram(progfuncs, CheckSpawn); - //the mod is responsible for freeing unrecognised ents. - } - else - { - printf("Couldn't find spawn function %s\n", PR_StringToNative(progfuncs, var->string)); - ED_Free(progfuncs, (struct edict_s *)ed); - } - } - } - } - else - Sys_Error("Command %s not recognised", qcc_token); - } - if (resethunk) - { - header_crc = crc; - if (externs->loadcompleate) - externs->loadcompleate(entsize); - - sv_num_edicts = numents; - } - - if (resethunk) - { - return entsize; - } - else - return max_fields_size; -} - -#define AddS(str) strcpy(s, str);s+=strlen(str); - -char *SaveEnt (progfuncs_t *progfuncs, char *buf, int *size, struct edict_s *ed) -{ - fdef_t *d; - int *v; - unsigned int i;unsigned int j; - char *name; - int type; - - char *s = buf; - -// if (ed->free) -// continue; - - AddS ("{\n"); - - - for (i=0 ; iname; - len = strlen(name); // should we skip vars with no name? - if (len > 2 && name[len-2] == '_') - continue; // skip _x, _y, _z vars - - v = (int*)((edictrun_t*)ed)->fields + d->ofs; - - // if the value is still all 0, skip the field - type = d->type & ~DEF_SAVEGLOBAL; - for (j=0 ; jtype, (eval_t *)v))); - } - - AddS ("}\n"); - - *size = s - buf; - - return buf; -} -struct edict_s *RestoreEnt (progfuncs_t *progfuncs, char *buf, int *size, struct edict_s *ed) -{ - edictrun_t *ent; - char *start = buf; - - buf = QCC_COM_Parse(buf); //read the key - if (!buf || !*qcc_token) - return NULL; - - if (strcmp(qcc_token, "{")) - Sys_Error("Restore Ent with no opening brace"); - - if (!ed) - ent = (edictrun_t *)ED_Alloc(progfuncs); - else - ent = (edictrun_t *)ed; - ent->isfree = false; - - if (externs->entspawn) - externs->entspawn((struct edict_s *) ent, false); - - buf = ED_ParseEdict(progfuncs, buf, ent); - - *size = buf - start; - - return (struct edict_s *)ent; -} - -#define Host_Error Sys_Error - -//return true if pr_progs needs recompiling (source files have changed) -pbool PR_TestRecompile(progfuncs_t *progfuncs) -{ - int newsize; - int num, found=0, lost=0, changed=0; - includeddatafile_t *s; - if (!pr_progs->ofsfiles) - return false; - - num = *(int*)((char *)pr_progs + pr_progs->ofsfiles); - s = (includeddatafile_t *)((char *)pr_progs + pr_progs->ofsfiles+4); - while(num>0) - { - newsize = externs->FileSize(s->filename); - if (newsize == -1) //ignore now missing files. - the referencer must have changed... - lost++; - else if (s->size != newsize) //file - changed++; - else - found++; - - s++; - num--; - } - if (lost > found+changed) - return false; - if (changed) - return true; - return false; -} -/* -#ifdef _DEBUG -//this is for debugging. -//I'm using this to detect incorrect string types while converting 32bit string pointers with bias to bound indexes. -void PR_TestForWierdness(progfuncs_t *progfuncs) -{ - unsigned int i; - int e; - edictrun_t *ed; - for (i = 0; i < pr_progs->numglobaldefs; i++) - { - if ((pr_globaldefs16[i].type&~(DEF_SHARED|DEF_SAVEGLOBAL)) == ev_string) - { - if (G_INT(pr_globaldefs16[i].ofs) < 0 || G_INT(pr_globaldefs16[i].ofs) >= addressableused) - printf("String type irregularity on \"%s\" \"%s\"\n", pr_globaldefs16[i].s_name+progfuncs->stringtable, G_INT(pr_globaldefs16[i].ofs)+progfuncs->stringtable); - } - } - - for (i = 0; i < numfields; i++) - { - if ((field[i].type&~(DEF_SHARED|DEF_SAVEGLOBAL)) == ev_string) - { - for (e = 0; e < sv_num_edicts; e++) - { - ed = (edictrun_t*)EDICT_NUM(progfuncs, e); - if (ed->isfree) - continue; - if (((int *)ed->fields)[field[i].ofs] < 0 || ((int *)ed->fields)[field[i].ofs] >= addressableused) - printf("String type irregularity \"%s\" \"%s\"\n", field[i].name, ((int *)ed->fields)[field[i].ofs]+progfuncs->stringtable); - } - } - } -} -#endif -*/ -char *decode(int complen, int len, int method, char *info, char *buffer); -/* -=============== -PR_LoadProgs -=============== -*/ -int PR_ReallyLoadProgs (progfuncs_t *progfuncs, char *filename, int headercrc, progstate_t *progstate, pbool complain) -{ - unsigned int i, type; -// extensionbuiltin_t *eb; -// float fl; - int len; -// int num; -// dfunction_t *f, *f2; - ddef16_t *d16; - ddef32_t *d32; - int *d2; - eval_t *eval; - char *s; - int progstype; - int trysleft = 2; -// bool qfhack = false; - pbool isfriked = false; //all imediate values were stripped, which causes problems with strings. - pbool hexencalling = false; //hexen style calling convention. The opcodes themselves are used as part of passing the arguments; - ddef16_t *gd16, *fld16; - float *glob; - dfunction_t *fnc; - dstatement16_t *st16; - - int hmark=0xffffffff; - - int reorg = prinst->reorganisefields || numfields; - - int stringadjust; - - current_progstate = progstate; - - strcpy(current_progstate->filename, filename); - - -// flush the non-C variable lookup cache -// for (i=0 ; iautocompile == PR_COMPILEALWAYS) //always compile before loading - { - printf("Forcing compile of progs %s\n", filename); - if (!CompileFile(progfuncs, filename)) - return false; - } - -// CRC_Init (&pr_crc); - -retry: - if ((len=externs->FileSize(filename))<=0) - { - if (externs->autocompile == PR_COMPILENEXIST || externs->autocompile == PR_COMPILECHANGED) //compile if file is not found (if 2, we have already tried, so don't bother) - { - if (hmark==0xffffffff) //first try - { - printf("couldn't open progs %s. Attempting to compile.\n", filename); - CompileFile(progfuncs, filename); - } - if ((len=externs->FileSize(filename))<0) - { - printf("Couldn't find or compile file %s\n", filename); - return false; - } - } - else if (externs->autocompile == PR_COMPILEIGNORE) - return false; - else - { - printf("Couldn't find file %s\n", filename); - return false; - } - } - - hmark = PRHunkMark(progfuncs); - pr_progs = PRHunkAlloc(progfuncs, len+1); - if (!externs->ReadFile(filename, pr_progs, len+1)) - { - if (!complain) - return false; - printf("Failed to open %s", filename); - return false; - } - -// for (i=0 ; iversion == PROG_VERSION) - { -// printf("Opening standard progs file \"%s\"\n", filename); - current_progstate->intsize = 16; - } - else if (pr_progs->version == PROG_EXTENDEDVERSION) - { -#ifndef NOENDIAN - for (i = standard_dprograms_t_size/sizeof(int); i < sizeof(dprograms_t)/sizeof(int); i++) - ((int *)pr_progs)[i] = PRLittleLong ( ((int *)pr_progs)[i] ); -#endif - if (pr_progs->secondaryversion == PROG_SECONDARYVERSION16) - { -// printf("Opening 16bit fte progs file \"%s\"\n", filename); - current_progstate->intsize = 16; - } - else if (pr_progs->secondaryversion == PROG_SECONDARYVERSION32) - { -// printf("Opening 32bit fte progs file \"%s\"\n", filename); - current_progstate->intsize = 32; - } - else - { -// printf("Opening KK7 progs file \"%s\"\n", filename); - current_progstate->intsize = 24; //KK progs. Yuck. Disabling saving would be a VERY good idea. - pr_progs->version = PROG_VERSION; //not fte. - } -/* else - { - printf ("Progs extensions are not compatible\nTry recompiling with the FTE compiler\n"); - HunkFree(hmark); - pr_progs=NULL; - return false; - } -*/ } - else - { - printf ("%s has wrong version number (%i should be %i)\n", filename, pr_progs->version, PROG_VERSION); - PRHunkFree(progfuncs, hmark); - pr_progs=NULL; - return false; - } - -//progs contains enough info for use to recompile it. - if (trysleft && (externs->autocompile == PR_COMPILECHANGED || externs->autocompile == PR_COMPILEEXISTANDCHANGED) && pr_progs->version == PROG_EXTENDEDVERSION) - { - if (PR_TestRecompile(progfuncs)) - { - printf("Source file has changed\nRecompiling.\n"); - if (CompileFile(progfuncs, filename)) - { - PRHunkFree(progfuncs, hmark); - pr_progs=NULL; - - trysleft--; - goto retry; - } - } - } - if (!trysleft) //the progs exists, let's just be happy about it. - printf("Progs is out of date and uncompilable\n"); - - if (headercrc != -1 && headercrc != 0) - if (pr_progs->crc != headercrc && pr_progs->crc != 0) //This shouldn't affect us. However, it does adjust expectations and usage of builtins. - { -// printf ("%s system vars have been modified, progdefs.h is out of date\n", filename); - PRHunkFree(progfuncs, hmark); - pr_progs=NULL; - return false; - } - - if (pr_progs->version == PROG_EXTENDEDVERSION && pr_progs->blockscompressed && !QC_decodeMethodSupported(2)) - { - printf ("%s uses compression\n", filename); - PRHunkFree(progfuncs, hmark); - pr_progs=NULL; - return false; - } - - fnc = pr_functions = (dfunction_t *)((qbyte *)pr_progs + pr_progs->ofs_functions); - pr_strings = ((char *)pr_progs + pr_progs->ofs_strings); - current_progstate->globaldefs = *(void**)&gd16 = (void *)((qbyte *)pr_progs + pr_progs->ofs_globaldefs); - current_progstate->fielddefs = *(void**)&fld16 = (void *)((qbyte *)pr_progs + pr_progs->ofs_fielddefs); - current_progstate->statements = (void *)((qbyte *)pr_progs + pr_progs->ofs_statements); - - glob = pr_globals = (void *)((qbyte *)pr_progs + pr_progs->ofs_globals); - - pr_linenums=NULL; - pr_types=NULL; - if (pr_progs->version == PROG_EXTENDEDVERSION) - { - if (pr_progs->ofslinenums) - pr_linenums = (int *)((qbyte *)pr_progs + pr_progs->ofslinenums); - if (pr_progs->ofs_types) - pr_types = (typeinfo_t *)((qbyte *)pr_progs + pr_progs->ofs_types); - - //start decompressing stuff... - if (pr_progs->blockscompressed & 1) //statements - { - switch(current_progstate->intsize) - { - case 16: - len=sizeof(dstatement16_t)*pr_progs->numstatements; - break; - case 32: - len=sizeof(dstatement32_t)*pr_progs->numstatements; - break; - default: - Sys_Error("Bad intsize"); - } - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_statements16), len, 2, (char *)(((int *)pr_statements16)+1), s); - - current_progstate->statements = (dstatement16_t *)s; - } - if (pr_progs->blockscompressed & 2) //global defs - { - switch(current_progstate->intsize) - { - case 16: - len=sizeof(ddef16_t)*pr_progs->numglobaldefs; - break; - case 32: - len=sizeof(ddef32_t)*pr_progs->numglobaldefs; - break; - default: - Sys_Error("Bad intsize"); - } - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_globaldefs16), len, 2, (char *)(((int *)pr_globaldefs16)+1), s); - - gd16 = *(ddef16_t**)¤t_progstate->globaldefs = (ddef16_t *)s; - } - if (pr_progs->blockscompressed & 4) //fields - { - switch(current_progstate->intsize) - { - case 16: - len=sizeof(ddef16_t)*pr_progs->numglobaldefs; - break; - case 32: - len=sizeof(ddef32_t)*pr_progs->numglobaldefs; - break; - default: - Sys_Error("Bad intsize"); - } - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_fielddefs16), len, 2, (char *)(((int *)pr_fielddefs16)+1), s); - - *(ddef16_t**)¤t_progstate->fielddefs = (ddef16_t *)s; - } - if (pr_progs->blockscompressed & 8) //functions - { - len=sizeof(dfunction_t)*pr_progs->numfunctions; - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_functions), len, 2, (char *)(((int *)pr_functions)+1), s); - - fnc = pr_functions = (dfunction_t *)s; - } - if (pr_progs->blockscompressed & 16) //string table - { - len=sizeof(char)*pr_progs->numstrings; - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_strings), len, 2, (char *)(((int *)pr_strings)+1), s); - - pr_strings = (char *)s; - } - if (pr_progs->blockscompressed & 32) //globals - { - len=sizeof(float)*pr_progs->numglobals; - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_globals), len, 2, (char *)(((int *)pr_globals)+1), s); - - glob = pr_globals = (float *)s; - } - if (pr_linenums && pr_progs->blockscompressed & 64) //line numbers - { - len=sizeof(int)*pr_progs->numstatements; - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_linenums), len, 2, (char *)(((int *)pr_linenums)+1), s); - - pr_linenums = (int *)s; - } - if (pr_types && pr_progs->blockscompressed & 128) //types - { - len=sizeof(typeinfo_t)*pr_progs->numtypes; - s = PRHunkAlloc(progfuncs, len); - QC_decode(progfuncs, PRLittleLong(*(int *)pr_types), len, 2, (char *)(((int *)pr_types)+1), s); - - pr_types = (typeinfo_t *)s; - } - } - - len=sizeof(char)*pr_progs->numstrings; - s = PRAddressableAlloc(progfuncs, len); - memcpy(s, pr_strings, len); - pr_strings = (char *)s; - - len=sizeof(float)*pr_progs->numglobals; - s = PRAddressableAlloc(progfuncs, len); - memcpy(s, pr_globals, len); - glob = pr_globals = (float *)s; - - if (progfuncs->stringtable) - stringadjust = pr_strings - progfuncs->stringtable; - else - stringadjust = 0; - - if (!pr_linenums) - { - unsigned int lnotype = *(unsigned int*)"LNOF"; - unsigned int version = 1; - int ohm; - unsigned int *file; - char lnoname[128]; - ohm = PRHunkMark(progfuncs); - - strcpy(lnoname, filename); - StripExtension(lnoname); - strcat(lnoname, ".lno"); - if ((len=externs->FileSize(lnoname))>0) - { - file = PRHunkAlloc(progfuncs, len+1); - if (externs->ReadFile(lnoname, file, len+1)) - { - if ( file[0] != lnotype - || file[1] != version - || file[2] != pr_progs->numglobaldefs - || file[3] != pr_progs->numglobals - || file[4] != pr_progs->numfielddefs - || file[5] != pr_progs->numstatements - ) - { - PRHunkFree(progfuncs, ohm); //whoops: old progs or incompatible - } - else - pr_linenums = file + 6; - } - } - } - - pr_functions = fnc; -// pr_strings = ((char *)pr_progs + pr_progs->ofs_strings); - gd16 = *(ddef16_t**)¤t_progstate->globaldefs = (ddef16_t *)((qbyte *)pr_progs + pr_progs->ofs_globaldefs); - fld16 = (ddef16_t *)((qbyte *)pr_progs + pr_progs->ofs_fielddefs); -// pr_statements16 = (dstatement16_t *)((qbyte *)pr_progs + pr_progs->ofs_statements); - pr_globals = glob; - st16 = pr_statements16; -#undef pr_globals -#undef pr_globaldefs16 -#undef pr_functions -#undef pr_statements16 -#undef pr_fielddefs16 - - - current_progstate->edict_size = pr_progs->entityfields * 4 + externs->edictsize; - -// byte swap the lumps - for (i=0 ; inumfunctions; i++) - { -#ifndef NOENDIAN - fnc[i].first_statement = PRLittleLong (fnc[i].first_statement); - fnc[i].parm_start = PRLittleLong (fnc[i].parm_start); - fnc[i].s_name = (string_t)PRLittleLong ((long)fnc[i].s_name); - fnc[i].s_file = (string_t)PRLittleLong ((long)fnc[i].s_file); - fnc[i].numparms = PRLittleLong (fnc[i].numparms); - fnc[i].locals = PRLittleLong (fnc[i].locals); -#endif -/* if (!strncmp(fnc[i].s_name+pr_strings, "ext_", 4)) - { - for (eb = extensionbuiltin; eb; eb = eb->prev) - { - if (*eb->name == '_') - { - if (!strncmp(fnc[i].s_name+pr_strings+4, eb->name+1, strlen(eb->name+1))) - { - fnc[i].first_statement = -0x7fffffff; - *(void**)&fnc[i].profile = (void*)eb->func; - break; - } - } - else if (!strcmp(fnc[i].s_name+4, eb->name)) - { - fnc[i].first_statement = -0x7fffffff; - *(void**)&fnc[i].profile = (void*)eb->func; - break; - } - } - } -*/ - fnc[i].s_name += stringadjust; - fnc[i].s_file += stringadjust; - } - - //actual global values -#ifndef NOENDIAN - for (i=0 ; inumglobals ; i++) - ((int *)glob)[i] = PRLittleLong (((int *)glob)[i]); -#endif - - if (pr_types) - { - for (i=0 ; inumtypes ; i++) - { -#ifndef NOENDIAN - pr_types[i].type = PRLittleLong(current_progstate->types[i].type); - pr_types[i].next = PRLittleLong(current_progstate->types[i].next); - pr_types[i].aux_type = PRLittleLong(current_progstate->types[i].aux_type); - pr_types[i].num_parms = PRLittleLong(current_progstate->types[i].num_parms); - pr_types[i].ofs = PRLittleLong(current_progstate->types[i].ofs); - pr_types[i].size = PRLittleLong(current_progstate->types[i].size); - pr_types[i].name = (char *)PRLittleLong((long)current_progstate->types[i].name); -#endif - pr_types[i].name += stringadjust; - } - } - - if (reorg) - reorg = (headercrc != -1); - - QC_FlushProgsOffsets(progfuncs); - switch(current_progstate->intsize) - { - case 24: - case 16: - //byteswap the globals and fix name offsets - for (i=0 ; inumglobaldefs ; i++) - { -#ifndef NOENDIAN - gd16[i].type = PRLittleShort (gd16[i].type); - gd16[i].ofs = PRLittleShort (gd16[i].ofs); - gd16[i].s_name = (string_t)PRLittleLong ((long)gd16[i].s_name); -#endif - gd16[i].s_name += stringadjust; - } - - //byteswap fields and fix name offets. Also register the fields (which will result in some offset adjustments in the globals segment). - for (i=0 ; inumfielddefs ; i++) - { -#ifndef NOENDIAN - fld16[i].type = PRLittleShort (fld16[i].type); - fld16[i].ofs = PRLittleShort (fld16[i].ofs); - fld16[i].s_name = (string_t)PRLittleLong ((long)fld16[i].s_name); -#endif - if (reorg) - { - if (pr_types) - type = pr_types[fld16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type; - else - type = fld16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - - if (progfuncs->fieldadjust && !pr_typecurrent) //we need to make sure all fields appear in their original place. - QC_RegisterFieldVar(progfuncs, type, fld16[i].s_name+pr_strings, 4*(fld16[i].ofs+progfuncs->fieldadjust), -1); - else if (type == ev_vector) //emit vector vars early, so their fields cannot be alocated before the vector itself. (useful against scramblers) - { - QC_RegisterFieldVar(progfuncs, type, fld16[i].s_name+pr_strings, -1, fld16[i].ofs); - } - } - else - { - fdef_t *nf; - if (numfields+1>maxfields) - { - i = maxfields; - maxfields += 32; - nf = memalloc(sizeof(fdef_t) * maxfields); - memcpy(nf, field, sizeof(fdef_t) * i); - memfree(field); - field = nf; - } - nf = &field[numfields]; - nf->name = fld16[i].s_name+pr_strings; - nf->type = fld16[i].type; - nf->progsofs = fld16[i].ofs; - nf->ofs = fld16[i].ofs; - - if (fields_size < (nf->ofs+type_size[nf->type])*4) - fields_size = (nf->ofs+type_size[nf->type])*4; - - numfields++; - } - fld16[i].s_name += stringadjust; - } - if (reorg && !(progfuncs->fieldadjust && !pr_typecurrent)) - for (i=0 ; inumfielddefs ; i++) - { - if (pr_types) - type = pr_types[fld16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type; - else - type = fld16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - if (type != ev_vector) - QC_RegisterFieldVar(progfuncs, type, fld16[i].s_name+pr_strings-stringadjust, -1, fld16[i].ofs); - } - - break; - case 32: - for (i=0 ; inumglobaldefs ; i++) - { -#ifndef NOENDIAN - pr_globaldefs32[i].type = PRLittleLong (pr_globaldefs32[i].type); - pr_globaldefs32[i].ofs = PRLittleLong (pr_globaldefs32[i].ofs); - pr_globaldefs32[i].s_name = (string_t)PRLittleLong ((long)pr_globaldefs32[i].s_name); -#endif - pr_globaldefs32[i].s_name += stringadjust; - } - - for (i=0 ; inumfielddefs ; i++) - { - #ifndef NOENDIAN - pr_fielddefs32[i].type = PRLittleLong (pr_fielddefs32[i].type); - pr_fielddefs32[i].ofs = PRLittleLong (pr_fielddefs32[i].ofs); - pr_fielddefs32[i].s_name = (string_t)PRLittleLong ((long)pr_fielddefs32[i].s_name); - #endif - - if (reorg) - { - if (pr_types) - type = pr_types[pr_fielddefs32[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type; - else - type = pr_fielddefs32[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - if (progfuncs->fieldadjust && !pr_typecurrent) //we need to make sure all fields appear in their original place. - QC_RegisterFieldVar(progfuncs, type, fld16[i].s_name+pr_strings, 4*(fld16[i].ofs+progfuncs->fieldadjust), -1); - else if (type == ev_vector) - QC_RegisterFieldVar(progfuncs, type, pr_fielddefs32[i].s_name+pr_strings, -1, pr_fielddefs32[i].ofs); - } - pr_fielddefs32[i].s_name += stringadjust; - } - if (reorg && !(progfuncs->fieldadjust && !pr_typecurrent)) - for (i=0 ; inumfielddefs ; i++) - { - if (pr_types) - type = pr_types[pr_fielddefs32[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type; - else - type = pr_fielddefs32[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - if (type != ev_vector) - QC_RegisterFieldVar(progfuncs, type, pr_fielddefs32[i].s_name+pr_strings-stringadjust, -1, pr_fielddefs32[i].ofs); - } - break; - default: - Sys_Error("Bad int size"); - } - -//ifstring fixes arn't performed anymore. -//the following switch just fixes endian and hexen2 calling conventions (by using different opcodes). - switch(current_progstate->intsize) - { - case 16: - for (i=0 ; inumstatements ; i++) - { -#ifndef NOENDIAN - st16[i].op = PRLittleShort(st16[i].op); - st16[i].a = PRLittleShort(st16[i].a); - st16[i].b = PRLittleShort(st16[i].b); - st16[i].c = PRLittleShort(st16[i].c); -#endif - if (st16[i].op >= OP_CALL1 && st16[i].op <= OP_CALL8) - { - if (st16[i].b) - hexencalling = true; - - } - } - if (hexencalling) - { - for (i=0 ; inumstatements ; i++) - { - if (st16[i].op >= OP_CALL1 && st16[i].op <= OP_CALL8) - st16[i].op += OP_CALL1H - OP_CALL1; - } - } - break; - - case 24: //24 sucks. Guess why. - for (i=0 ; inumstatements ; i++) - { -#ifndef NOENDIAN - pr_statements32[i].op = PRLittleLong(pr_statements32[i].op); - pr_statements32[i].a = PRLittleLong(pr_statements32[i].a); - pr_statements32[i].b = PRLittleLong(pr_statements32[i].b); - pr_statements32[i].c = PRLittleLong(pr_statements32[i].c); -#endif - if (pr_statements32[i].op >= OP_CALL1 && pr_statements32[i].op <= OP_CALL8) - { - if (pr_statements32[i].b) - hexencalling = true; - - } - } - if (hexencalling) - { - for (i=0 ; inumstatements ; i++) - { - if (pr_statements32[i].op >= OP_CALL1 && pr_statements32[i].op <= OP_CALL8) - pr_statements32[i].op += OP_CALL1H - OP_CALL1; - } - } - break; - case 32: - for (i=0 ; inumstatements ; i++) - { -#ifndef NOENDIAN - pr_statements32[i].op = PRLittleLong(pr_statements32[i].op); - pr_statements32[i].a = PRLittleLong(pr_statements32[i].a); - pr_statements32[i].b = PRLittleLong(pr_statements32[i].b); - pr_statements32[i].c = PRLittleLong(pr_statements32[i].c); -#endif - if (pr_statements32[i].op >= OP_CALL1 && pr_statements32[i].op <= OP_CALL8) - { - if (pr_statements32[i].b) - hexencalling = true; - - } - } - if (hexencalling) - { - for (i=0 ; inumstatements ; i++) - { - if (pr_statements32[i].op >= OP_CALL1 && pr_statements32[i].op <= OP_CALL8) - pr_statements32[i].op += OP_CALL1H - OP_CALL1; - } - } - break; - } - - - if (headercrc == -1) - { - isfriked = true; - if (current_progstate->intsize != 16) - Sys_Error("Decompiling a bigprogs"); - return true; - } - - progstype = current_progstate-pr_progstate; - -// QC_StartShares(progfuncs); - - isfriked = true; - if (!pr_typecurrent) //progs 0 always acts as string stripped. - isfriked = -1; //partly to avoid some bad progs. - -// len = 0; - switch(current_progstate->intsize) - { - case 24: - case 16: - for (i=0 ; inumglobaldefs ; i++) - { - if (pr_types) - type = pr_types[gd16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type; - else - type = gd16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - - if (gd16[i].type & DEF_SHARED) - { - gd16[i].type &= ~DEF_SHARED; - if (pr_types) - QC_AddSharedVar(progfuncs, gd16[i].ofs, pr_types[gd16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].size); - else - QC_AddSharedVar(progfuncs, gd16[i].ofs, type_size[type]); - } - switch(type) - { - case ev_field: - if (reorg) - QC_AddSharedFieldVar(progfuncs, i, pr_strings - stringadjust); - break; - case ev_string: - if (((unsigned int *)glob)[gd16[i].ofs]>=progstate->progs->numstrings) - printf("Insane value\n"); - else if (isfriked != -1) - { - if (pr_strings[((int *)glob)[gd16[i].ofs]]) //quakec uses string tables. 0 must remain null, or 'if (s)' can break. - { - ((int *)glob)[gd16[i].ofs] += stringadjust; - isfriked = false; - } - else - ((int *)glob)[gd16[i].ofs] = 0; - } - break; - case ev_function: - if (((int *)glob)[gd16[i].ofs]) //don't change null funcs - { -// if (fnc[((int *)glob)[gd16[i].ofs]].first_statement>=0) //this is a hack. Make all builtins switch to the main progs first. Allows builtin funcs to cache vars from just the main progs. - ((int *)glob)[gd16[i].ofs] |= progstype << 24; - } - break; - } - } - break; - case 32: - for (i=0 ; inumglobaldefs ; i++) - { - if (pr_types) - type = pr_types[pr_globaldefs32[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type; - else - type = pr_globaldefs32[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - - if (pr_globaldefs32[i].type & DEF_SHARED) - { - pr_globaldefs32[i].type &= ~DEF_SHARED; - if (pr_types) - QC_AddSharedVar(progfuncs, pr_globaldefs32[i].ofs, pr_types[pr_globaldefs32[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].size); - else - QC_AddSharedVar(progfuncs, pr_globaldefs32[i].ofs, type_size[type]); - } - switch(type) - { - case ev_field: - QC_AddSharedFieldVar(progfuncs, i, pr_strings - stringadjust); - break; - case ev_string: - if (pr_strings[((int *)glob)[pr_globaldefs32[i].ofs]]) //quakec uses string tables. 0 must remain null, or 'if (s)' can break. - { - ((int *)glob)[pr_globaldefs32[i].ofs] += stringadjust; - isfriked = false; - } - break; - case ev_function: - if (((int *)glob)[pr_globaldefs32[i].ofs]) //don't change null funcs - ((int *)glob)[pr_globaldefs32[i].ofs] |= progstype << 24; - break; - } - } - - if (pr_progs->version == PROG_EXTENDEDVERSION && pr_progs->numbodylessfuncs) - { - s = &((char *)pr_progs)[pr_progs->ofsbodylessfuncs]; - for (i = 0; i < pr_progs->numbodylessfuncs; i++) - { - d32 = ED_FindGlobal32(progfuncs, s); - d2 = ED_FindGlobalOfsFromProgs(progfuncs, s, 0, ev_function); - if (!d2) - Sys_Error("Runtime-linked function %s was not found in existing progs", s); - if (!d32) - Sys_Error("Couldn't find def for \"%s\"", s); - ((int *)glob)[d32->ofs] = (*(func_t *)&pr_progstate[0].globals[*d2]); - - s+=strlen(s)+1; - } - } - break; - default: - Sys_Error("Bad int size"); - } - - if ((isfriked && pr_typecurrent)) //friked progs only allow one file. - { - printf("You are trying to load a string-stripped progs as an addon.\nThis behaviour is not supported. Try removing some optimizations."); - PRHunkFree(progfuncs, hmark); - pr_progs=NULL; - return false; - } - - pr_strings+=stringadjust; - if (!progfuncs->stringtable) - progfuncs->stringtable = pr_strings; - - if (progfuncs->stringtablesize + progfuncs->stringtable < pr_strings + pr_progs->numstrings) - progfuncs->stringtablesize = (pr_strings + pr_progs->numstrings) - progfuncs->stringtable; - - eval = PR_FindGlobal(progfuncs, "thisprogs", progstype); - if (eval) - eval->prog = progstype; - - switch(current_progstate->intsize) - { - case 16: - if (pr_progs->version == PROG_EXTENDEDVERSION && pr_progs->numbodylessfuncs) - { - s = &((char *)pr_progs)[pr_progs->ofsbodylessfuncs]; - for (i = 0; i < pr_progs->numbodylessfuncs; i++) - { - d16 = ED_FindGlobal16(progfuncs, s); - if (!d16) - { - printf("Progs requires \"%s\" the external function \"%s\", but the definition was stripped", filename, s); - PRHunkFree(progfuncs, hmark); - pr_progs=NULL; - return false; - } - - ((int *)glob)[d16->ofs] = PR_FindFunc(progfuncs, s, PR_ANY); - if (!((int *)glob)[d16->ofs]) - printf("Warning: Runtime-linked function %s was not found in primary progs (loading %s)", s, filename); - /* - d2 = ED_FindGlobalOfsFromProgs(progfuncs, s, 0, ev_function); - if (!d2) - Sys_Error("Runtime-linked function %s was not found in primary progs (loading %s)", s, filename); - ((int *)glob)[d16->ofs] = (*(func_t *)&pr_progstate[0].globals[*d2]); - */ - s+=strlen(s)+1; - } - } - break; - case 24: - break; //cannot happen anyway. - case 32: - if (pr_progs->version == PROG_EXTENDEDVERSION && pr_progs->numbodylessfuncs) - { - s = &((char *)pr_progs)[pr_progs->ofsbodylessfuncs]; - for (i = 0; i < pr_progs->numbodylessfuncs; i++) - { - d32 = ED_FindGlobal32(progfuncs, s); - d2 = ED_FindGlobalOfsFromProgs(progfuncs, s, 0, ev_function); - if (!d2) - printf("Warning: Runtime-linked function %s was not found in existing progs", s); - if (!d32) - { - printf("Couldn't find def for \"%s\"", s); - PRHunkFree(progfuncs, hmark); - pr_progs=NULL; - return false; - } - ((int *)glob)[d32->ofs] = (*(func_t *)&pr_progstate[0].globals[*d2]); - - s+=strlen(s)+1; - } - } - break; - } - - eval = PR_FindGlobal(progfuncs, "__ext__fasttrackarrays", PR_CURRENT); - if (eval) //we support these opcodes - eval->_float = true; - - return true; -} - - - -struct edict_s *EDICT_NUM(progfuncs_t *progfuncs, unsigned int n) -{ - if (n >= maxedicts) - Sys_Error ("QCLIB: EDICT_NUM: bad number %i", n); - - return prinst->edicttable[n]; -} - -unsigned int NUM_FOR_EDICT(progfuncs_t *progfuncs, struct edict_s *e) -{ - edictrun_t *er = (edictrun_t*)e; - if (er->entnum >= maxedicts) - Sys_Error ("QCLIB: NUM_FOR_EDICT: bad pointer (%p)", e); - return er->entnum; -} diff --git a/misc/mediasource/extra/fteqcc-src/pr_exec.c b/misc/mediasource/extra/fteqcc-src/pr_exec.c deleted file mode 100644 index bdd2af95..00000000 --- a/misc/mediasource/extra/fteqcc-src/pr_exec.c +++ /dev/null @@ -1,1199 +0,0 @@ -#define PROGSUSED -#include "progsint.h" -//#include "editor.h" - -#define HunkAlloc BADGDFG sdfhhsf FHS - - -#define Host_Error Sys_Error - - -//============================================================================= - -/* -================= -PR_PrintStatement -================= -*/ -/* -void PR_PrintStatement (progfuncs_t *progfuncs, dstatement16_t *s) -{ - int i; -printf("PR_PrintStatement is unsupported\n"); -return; - if ( (unsigned)s->op < OP_NUMOPS) - { - printf ("%s ", pr_opcodes[s->op].name); - i = strlen(pr_opcodes[s->op].name); - for ( ; i<10 ; i++) - printf (" "); - } - - if (s->op == OP_IF || s->op == OP_IFNOT) - printf ("%sbranch %i",PR_GlobalString(progfuncs, s->a),s->b); - else if (s->op == OP_GOTO) - { - printf ("branch %i",s->a); - } - else if ( (unsigned)(s->op - OP_STORE_F) < 6) - { - printf ("%s",PR_GlobalString(progfuncs, s->a)); - printf ("%s", PR_GlobalStringNoContents(progfuncs, s->b)); - } - else - { - if (s->a) - printf ("%s",PR_GlobalString(progfuncs, s->a)); - if (s->b) - printf ("%s",PR_GlobalString(progfuncs, s->b)); - if (s->c) - printf ("%s", PR_GlobalStringNoContents(progfuncs, s->c)); - } - printf ("\n"); -} -*/ - -/* -============ -PR_StackTrace -============ -*/ -char *QC_ucase(char *str) -{ - static char s[1024]; - strcpy(s, str); - str = s; - - while(*str) - { - if (*str >= 'a' && *str <= 'z') - *str = *str - 'a' + 'A'; - str++; - } - return s; -} - -void PR_StackTrace (progfuncs_t *progfuncs) -{ - dfunction_t *f; - int i; - int progs; - -#ifdef STACKTRACE - int arg; - int *globalbase; -#endif - progs = -1; - - if (pr_depth == 0) - { - printf ("\n"); - return; - } - -#ifdef STACKTRACE - globalbase = (int *)pr_globals + pr_xfunction->parm_start - pr_xfunction->locals; -#endif - - pr_stack[pr_depth].f = pr_xfunction; - pr_stack[pr_depth].s = pr_xstatement; - for (i=pr_depth ; i>0 ; i--) - { - f = pr_stack[i].f; - - if (!f) - { - printf ("\n"); - } - else - { - if (pr_stack[i].progsnum != progs) - { - progs = pr_stack[i].progsnum; - - printf ("<%s>\n", pr_progstate[progs].filename); - } - if (!f->s_file) - printf ("stripped : %s\n", f->s_name+progfuncs->stringtable); - else - { - if (pr_progstate[progs].linenums) - printf ("%12s %i : %s\n", f->s_file+progfuncs->stringtable, pr_progstate[progs].linenums[pr_stack[i].s], f->s_name+progfuncs->stringtable); - else - printf ("%12s : %s\n", f->s_file+progfuncs->stringtable, f->s_name+progfuncs->stringtable); - } - -#ifdef STACKTRACE - - for (arg = 0; arg < f->locals; arg++) - { - ddef16_t *local; - local = ED_GlobalAtOfs16(progfuncs, f->parm_start+arg); - if (!local) - { - printf(" ofs %i: %f : %i\n", f->parm_start+arg, *(float *)(globalbase - f->locals+arg), *(int *)(globalbase - f->locals+arg) ); - } - else - { - printf(" %s: %s\n", local->s_name+progfuncs->stringtable, PR_ValueString(progfuncs, local->type, (eval_t*)(globalbase - f->locals+arg))); - if (local->type == ev_vector) - arg+=2; - } - } - - if (i == pr_depth) - globalbase = localstack + localstack_used; - else - globalbase -= f->locals; -#endif - } - } -} - -/* -============ -PR_Profile_f - -============ -*/ -/* -void PR_Profile_f (void) -{ - dfunction_t *f, *best; - int max; - int num; - unsigned int i; - - num = 0; - do - { - max = 0; - best = NULL; - for (i=0 ; inumfunctions ; i++) - { - f = &pr_functions[i]; - if (f->profile > max && f->first_statement >=0) - { - max = f->profile; - best = f; - } - } - if (best) - { - if (num < 10) - printf ("%7i %s\n", best->profile, best->s_name); - num++; - best->profile = 0; - } - } while (best); -} -*/ - - -/* -============ -PR_RunError - -Aborts the currently executing function -============ -*/ -void VARGS PR_RunError (progfuncs_t *progfuncs, char *error, ...) -{ - va_list argptr; - char string[1024]; - - va_start (argptr,error); - Q_vsnprintf (string,sizeof(string)-1, error,argptr); - va_end (argptr); - -// { -// void SV_EndRedirect (void); -// SV_EndRedirect(); -// } - -// PR_PrintStatement (pr_statements + pr_xstatement); - PR_StackTrace (progfuncs); - printf ("\n"); - -//editbadfile(pr_strings + pr_xfunction->s_file, -1); - -// pr_depth = 0; // dump the stack so host_error can shutdown functions -// prinst->exitdepth = 0; - - Abort ("%s", string); -} - -/* -============================================================================ -PR_ExecuteProgram - -The interpretation main loop -============================================================================ -*/ - -/* -==================== -PR_EnterFunction - -Returns the new program statement counter -==================== -*/ -void PR_AbortStack (progfuncs_t *progfuncs); -int PR_EnterFunction (progfuncs_t *progfuncs, dfunction_t *f, int progsnum) -{ - int i, j, c, o; - - pr_stack[pr_depth].s = pr_xstatement; - pr_stack[pr_depth].f = pr_xfunction; - pr_stack[pr_depth].progsnum = progsnum; - pr_stack[pr_depth].pushed = pr_spushed; - pr_depth++; - if (pr_depth == MAX_STACK_DEPTH) - { - pr_depth--; - PR_StackTrace (progfuncs); - - printf ("stack overflow on call to %s\n", progfuncs->stringtable+f->s_name); - - //comment this out if you want the progs to try to continue anyway (could cause infinate loops) - PR_AbortStack(progfuncs); - Abort("Stack Overflow in %s\n", progfuncs->stringtable+f->s_name); - return pr_xstatement; - } - - localstack_used += pr_spushed; //make sure the call doesn't hurt pushed pointers - -// save off any locals that the new function steps on (to a side place, fromwhere they are restored on exit) - c = f->locals; - if (localstack_used + c > LOCALSTACK_SIZE) - { - localstack_used -= pr_spushed; - pr_depth--; - PR_RunError (progfuncs, "PR_ExecuteProgram: locals stack overflow\n"); - } - - for (i=0 ; i < c ; i++) - localstack[localstack_used+i] = ((int *)pr_globals)[f->parm_start + i]; - localstack_used += c; - -// copy parameters (set initial values) - o = f->parm_start; - for (i=0 ; inumparms ; i++) - { - for (j=0 ; jparm_size[i] ; j++) - { - ((int *)pr_globals)[o] = ((int *)pr_globals)[OFS_PARM0+i*3+j]; - o++; - } - } - - pr_xfunction = f; - return f->first_statement - 1; // offset the s++ -} - -/* -==================== -PR_LeaveFunction -==================== -*/ -int PR_LeaveFunction (progfuncs_t *progfuncs) -{ - int i, c; - - if (pr_depth <= 0) - Sys_Error ("prog stack underflow"); - -// restore locals from the stack - c = pr_xfunction->locals; - localstack_used -= c; - if (localstack_used < 0) - PR_RunError (progfuncs, "PR_ExecuteProgram: locals stack underflow\n"); - - for (i=0 ; i < c ; i++) - ((int *)pr_globals)[pr_xfunction->parm_start + i] = localstack[localstack_used+i]; - -// up stack - pr_depth--; - PR_MoveParms(progfuncs, pr_stack[pr_depth].progsnum, pr_typecurrent); - PR_SwitchProgs(progfuncs, pr_stack[pr_depth].progsnum); - pr_xfunction = pr_stack[pr_depth].f; - pr_spushed = pr_stack[pr_depth].pushed; - - localstack_used -= pr_spushed; - return pr_stack[pr_depth].s; -} - -ddef32_t *ED_FindLocalOrGlobal(progfuncs_t *progfuncs, char *name, eval_t **val) -{ - static ddef32_t def; - ddef32_t *def32; - ddef16_t *def16; - int i; - - switch (pr_progstate[pr_typecurrent].intsize) - { - case 16: - case 24: - //this gets parms fine, but not locals - if (pr_xfunction) - for (i = 0; i < pr_xfunction->numparms; i++) - { - def16 = ED_GlobalAtOfs16(progfuncs, pr_xfunction->parm_start+i); - if (!def16) - continue; - if (!strcmp(def16->s_name+progfuncs->stringtable, name)) - { - *val = (eval_t *)&pr_progstate[pr_typecurrent].globals[pr_xfunction->parm_start+i]; - - //we need something like this for functions that are not the top layer - // *val = (eval_t *)&localstack[localstack_used-pr_xfunction->numparms*4]; - def.ofs = def16->ofs; - def.s_name = def16->s_name; - def.type = def16->type; - return &def; - } - } - def16 = ED_FindGlobal16(progfuncs, name); - if (!def16) - return NULL; - def.ofs = def16->ofs; - def.type = def16->type; - def.s_name = def16->s_name; - def32 = &def; - break; - case 32: - //this gets parms fine, but not locals - if (pr_xfunction) - for (i = 0; i < pr_xfunction->numparms; i++) - { - def32 = ED_GlobalAtOfs32(progfuncs, pr_xfunction->parm_start+i); - if (!def32) - continue; - if (!strcmp(def32->s_name+progfuncs->stringtable, name)) - { - *val = (eval_t *)&pr_progstate[pr_typecurrent].globals[pr_xfunction->parm_start+i]; - - //we need something like this for functions that are not the top layer - // *val = (eval_t *)&localstack[localstack_used-pr_xfunction->numparms*4]; - return def32; - } - } - def32 = ED_FindGlobal32(progfuncs, name); - if (!def32) - return NULL; - break; - default: - Sys_Error("Bad int size in ED_FindLocalOrGlobal"); - def32 = NULL; - } - - *val = (eval_t *)&pr_progstate[pr_typecurrent].globals[def32->ofs]; - return &def; -} - -char *COM_TrimString(char *str) -{ - int i; - static char buffer[256]; - while (*str <= ' ' && *str>'\0') - str++; - - for (i = 0; i < 255; i++) - { - if (*str <= ' ') - break; - buffer[i] = *str++; - } - buffer[i] = '\0'; - return buffer; -} - -char *EvaluateDebugString(progfuncs_t *progfuncs, char *key) -{ - static char buf[256]; - char *c, *c2; - ddef32_t *def; - fdef_t *fdef; - eval_t *val; - char *assignment; - int type; - ddef32_t fakedef; - eval_t fakeval; - - assignment = strchr(key, '='); - if (assignment) - *assignment = '\0'; - - c = strchr(key, '.'); - if (c) *c = '\0'; - def = ED_FindLocalOrGlobal(progfuncs, key, &val); - if (!def) - { - if (atoi(key)) - { - def = &fakedef; - def->ofs = 0; - def->type = ev_entity; - val = &fakeval; - val->edict = atoi(key); - } - } - if (c) *c = '.'; - if (!def) - { - return "(Bad string)"; - } - type = def->type; - - //go through ent vars - c = strchr(key, '.'); - while(c) - { - c2 = c+1; - c = strchr(c2, '.'); - type = type &~DEF_SAVEGLOBAL; - if (current_progstate->types) - type = current_progstate->types[type].type; - if (type != ev_entity) - return "'.' without entity"; - if (c)*c = '\0'; - fdef = ED_FindField(progfuncs, COM_TrimString(c2)); - if (c)*c = '.'; - if (!fdef) - return "(Bad string)"; - val = (eval_t *) (((char *)PROG_TO_EDICT(progfuncs, val->_int)->fields) + fdef->ofs*4); - type = fdef->type; - } - - if (assignment) - { - assignment++; - switch (type&~DEF_SAVEGLOBAL) - { - case ev_string: - *(string_t *)val = PR_StringToProgs(progfuncs, ED_NewString (progfuncs, assignment, 0)); - break; - - case ev_float: - *(float *)val = (float)atof (assignment); - break; - - case ev_integer: - *(int *)val = atoi (assignment); - break; - -/* case ev_vector: - strcpy (string, assignment); - v = string; - w = string; - for (i=0 ; i<3 ; i++) - { - while (*v && *v != ' ') - v++; - *v = 0; - ((float *)d)[i] = (float)atof (w); - w = v = v+1; - } - break; -*/ - case ev_entity: - *(int *)val = EDICT_TO_PROG(progfuncs, EDICT_NUM(progfuncs, atoi (assignment))); - break; - - case ev_field: - fdef = ED_FindField (progfuncs, assignment); - if (!fdef) - { - int l,nl = strlen(assignment); - strcpy(buf, "Can't find field "); - l = strlen(buf); - if (nl > sizeof(buf)-l-2) - nl = sizeof(buf)-l-2; - memcpy(buf+l, assignment, nl); - assignment[l+nl+0] = '\n'; - assignment[l+nl+1] = 0; - return buf; - } - *(int *)val = G_INT(fdef->ofs); - break; - - case ev_function: - { - dfunction_t *func; - int i; - int progsnum = -1; - char *s = assignment; - if (s[0] && s[1] == ':') - { - progsnum = atoi(s); - s+=2; - } - else if (s[0] && s[1] && s[2] == ':') - { - progsnum = atoi(s); - s+=3; - } - - func = ED_FindFunction (progfuncs, s, &i, progsnum); - if (!func) - { - int l,nl = strlen(s); - - assignment[-1] = '='; - - strcpy(buf, "Can't find field "); - l = strlen(buf); - if (nl > sizeof(buf)-l-2) - nl = sizeof(buf)-l-2; - memcpy(buf+l, assignment, nl); - assignment[l+nl+0] = '\n'; - assignment[l+nl+1] = 0; - return buf; - } - *(func_t *)val = (func - pr_progstate[i].functions) | (i<<24); - } - break; - - default: - break; - - } - assignment[-1] = '='; - } - strcpy(buf, PR_ValueString(progfuncs, type, val)); - - return buf; -} - -int debugstatement; -//int EditorHighlightLine(window_t *wnd, int line); -void SetExecutionToLine(progfuncs_t *progfuncs, int linenum) -{ - int pn = pr_typecurrent; - int snum; - dfunction_t *f = pr_xfunction; - - switch(current_progstate->intsize) - { - case 16: - for (snum = f->first_statement; pr_progstate[pn].linenums[snum] < linenum; snum++) - { - if (pr_statements16[snum].op == OP_DONE) - return; - } - break; - case 24: - case 32: - for (snum = f->first_statement; pr_progstate[pn].linenums[snum] < linenum; snum++) - { - if (pr_statements32[snum].op == OP_DONE) - return; - } - break; - default: - Sys_Error("Bad intsize"); - snum = 0; - } - debugstatement = snum; -// EditorHighlightLine(editwnd, pr_progstate[pn].linenums[snum]); -} - -//0 clear. 1 set, 2 toggle, 3 check -int PR_ToggleBreakpoint(progfuncs_t *progfuncs, char *filename, int linenum, int flag) //write alternate route to work by function name. -{ - int ret=0; - unsigned int fl; - unsigned int i; - int pn = pr_typecurrent; - dfunction_t *f; - int op; - - for (pn = 0; (unsigned)pn < maxprogs; pn++) - { - if (!pr_progstate || !pr_progstate[pn].progs) - continue; - - if (linenum) //linenum is set means to set the breakpoint on a file and line - { - if (!pr_progstate[pn].linenums) - continue; - - for (f = pr_progstate[pn].functions, fl = 0; fl < pr_progstate[pn].progs->numfunctions; f++, fl++) - { - if (!stricmp(f->s_file+progfuncs->stringtable, filename)) - { - for (i = f->first_statement; ; i++) - { - if (pr_progstate[pn].linenums[i] >= linenum) - { - fl = pr_progstate[pn].linenums[i]; - for (; ; i++) - { - if ((unsigned int)pr_progstate[pn].linenums[i] > fl) - break; - - switch(pr_progstate[pn].intsize) - { - case 16: - op = ((dstatement16_t*)pr_progstate[pn].statements + i)->op; - break; - case 24: - case 32: - op = ((dstatement32_t*)pr_progstate[pn].statements + i)->op; - break; - default: - Sys_Error("Bad intsize"); - op = 0; - } - switch (flag) - { - default: - if (op & 0x8000) - { - op &= ~0x8000; - ret = false; - flag = 0; - } - else - { - op |= 0x8000; - ret = true; - flag = 1; - } - break; - case 0: - op &= ~0x8000; - ret = false; - break; - case 1: - op |= 0x8000; - ret = true; - break; - case 3: - if (op & 0x8000) - return true; - } - switch(pr_progstate[pn].intsize) - { - case 16: - ((dstatement16_t*)pr_progstate[pn].statements + i)->op = op; - break; - case 24: - case 32: - ((dstatement32_t*)pr_progstate[pn].statements + i)->op = op; - break; - default: - Sys_Error("Bad intsize"); - op = 0; - } - } - goto cont; - } - } - } - } - } - else //set the breakpoint on the first statement of the function specified. - { - for (f = pr_progstate[pn].functions, fl = 0; fl < pr_progstate[pn].progs->numfunctions; f++, fl++) - { - if (!strcmp(f->s_name+progfuncs->stringtable, filename)) - { - i = f->first_statement; - switch(pr_progstate[pn].intsize) - { - case 16: - op = ((dstatement16_t*)pr_progstate[pn].statements + i)->op; - break; - case 24: - case 32: - op = ((dstatement32_t*)pr_progstate[pn].statements + i)->op; - break; - default: - Sys_Error("Bad intsize"); - } - switch (flag) - { - default: - if (op & 0x8000) - { - op &= ~0x8000; - ret = false; - flag = 0; - } - else - { - op |= 0x8000; - ret = true; - flag = 1; - } - break; - case 0: - op &= ~0x8000; - ret = false; - break; - case 1: - op |= 0x8000; - ret = true; - break; - case 3: - if (op & 0x8000) - return true; - } - switch(pr_progstate[pn].intsize) - { - case 16: - ((dstatement16_t*)pr_progstate[pn].statements + i)->op = op; - break; - case 24: - case 32: - ((dstatement32_t*)pr_progstate[pn].statements + i)->op = op; - break; - default: - Sys_Error("Bad intsize"); - } - break; - } - } - } -cont: - continue; - } - - return ret; -} - -int ShowStep(progfuncs_t *progfuncs, int statement) -{ -// return statement; -// texture realcursortex; -static int lastline = 0; -static char *lastfile = 0; - - int pn = pr_typecurrent; - int i; - dfunction_t *f = pr_xfunction; - - if (f && pr_progstate[pn].linenums && externs->useeditor) - { - if (lastline == pr_progstate[pn].linenums[statement] && lastfile == f->s_file+progfuncs->stringtable) - return statement; //no info/same line as last time - - lastline = pr_progstate[pn].linenums[statement]; - lastfile = f->s_file+progfuncs->stringtable; - - lastline = externs->useeditor(progfuncs, lastfile, lastline, 0, NULL); - - if (pr_progstate[pn].linenums[statement] != lastline) - { - for (i = f->first_statement; ; i++) - { - if (lastline == pr_progstate[pn].linenums[i]) - { - return i; - } - else if (lastline <= pr_progstate[pn].linenums[i]) - { - return statement; - } - } - } - } - else if (f) //annoying. - { - if (*(f->s_file+progfuncs->stringtable)) //if we can't get the filename, then it was stripped, and debugging it like this is useless - if (externs->useeditor) - externs->useeditor(progfuncs, f->s_file+progfuncs->stringtable, -1, 0, NULL); - return statement; - } - - - return statement; -} - -//DMW: all pointer functions are modified to be absoloute pointers from NULL not sv_edicts -/* -==================== -PR_ExecuteProgram -==================== -*/ -void PR_ExecuteCode (progfuncs_t *progfuncs, int s) -{ - eval_t *t, *swtch=NULL; - - int swtchtype; - dstatement16_t *st16; - dstatement32_t *st32; - dfunction_t *newf; - int runaway; - int i; - int p; - edictrun_t *ed; - eval_t *ptr; - - float *glob; - - int fnum; - - prinst->continuestatement = -1; -#ifdef QCJIT - if (prinst->usejit) - { - PR_EnterJIT(progfuncs, s); - return; - } -#endif - fnum = pr_xfunction - pr_functions; - - runaway = 100000000; - -#define PRBOUNDSCHECK -#define RUNAWAYCHECK() \ - if (!--runaway) \ - { \ - pr_xstatement = st-pr_statements; \ - PR_StackTrace(progfuncs); \ - printf ("runaway loop error"); \ - while(pr_depth > prinst->exitdepth) \ - PR_LeaveFunction(progfuncs); \ - pr_spushed = 0; \ - return; \ - } - -#define OPA ((eval_t *)&glob[st->a]) -#define OPB ((eval_t *)&glob[st->b]) -#define OPC ((eval_t *)&glob[st->c]) - -restart: //jumped to when the progs might have changed. - glob = pr_globals; - switch (current_progstate->intsize) - { - case 16: -#define INTSIZE 16 - st16 = &pr_statements16[s]; - while (pr_trace) - { - #define DEBUGABLE - #ifdef SEPARATEINCLUDES - #include "execloop16d.h" - #else - #include "execloop.h" - #endif - #undef DEBUGABLE - } - - while(1) - { - #include "execloop.h" - } -#undef INTSIZE - Sys_Error("PR_ExecuteProgram - should be unreachable"); - break; - case 24: - case 32: -#define INTSIZE 32 - st32 = &pr_statements32[s]; - while (pr_trace) - { - #define DEBUGABLE - #ifdef SEPARATEINCLUDES - #include "execloop32d.h" - #else - #include "execloop.h" - #endif - #undef DEBUGABLE - } - - while(1) - { - #ifdef SEPARATEINCLUDES - #include "execloop32.h" - #else - #include "execloop.h" - #endif - } -#undef INTSIZE - Sys_Error("PR_ExecuteProgram - should be unreachable"); - break; - default: - Sys_Error("PR_ExecuteProgram - bad intsize"); - } -} - - -void PR_ExecuteProgram (progfuncs_t *progfuncs, func_t fnum) -{ - dfunction_t *f; - int i; - unsigned int initial_progs; - int oldexitdepth; - - int s; - - int tempdepth; - - unsigned int newprogs = (fnum & 0xff000000)>>24; - - initial_progs = pr_typecurrent; - if (newprogs != initial_progs) - { - if (newprogs >= maxprogs || !&pr_progstate[newprogs].globals) //can happen with hexen2... - { - printf("PR_ExecuteProgram: tried branching into invalid progs\n"); - return; - } - PR_MoveParms(progfuncs, newprogs, pr_typecurrent); - PR_SwitchProgs(progfuncs, newprogs); - } - - if (!(fnum & ~0xff000000) || (signed)(fnum & ~0xff000000) >= pr_progs->numfunctions) - { -// if (pr_global_struct->self) -// ED_Print (PROG_TO_EDICT(pr_global_struct->self)); - printf("PR_ExecuteProgram: NULL function from exe\n"); -// Host_Error ("PR_ExecuteProgram: NULL function from exe"); - -// PR_MoveParms(0, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); - return; - } - - oldexitdepth = prinst->exitdepth; - - f = &pr_functions[fnum & ~0xff000000]; - - if (f->first_statement < 0) - { // negative statements are built in functions - i = -f->first_statement; - - if (i < externs->numglobalbuiltins) - (*externs->globalbuiltins[i]) (progfuncs, (struct globalvars_s *)current_progstate->globals); - else - { - i -= externs->numglobalbuiltins; - if (i > current_progstate->numbuiltins) - { - printf ("Bad builtin call number %i (from exe)\n", -f->first_statement); - // PR_MoveParms(p, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); - return; - } - current_progstate->builtins [i] (progfuncs, (struct globalvars_s *)current_progstate->globals); - } - PR_MoveParms(progfuncs, initial_progs, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); - return; - } - - if (pr_trace) - pr_trace--; - -// make a stack frame - prinst->exitdepth = pr_depth; - - - s = PR_EnterFunction (progfuncs, f, initial_progs); - - tempdepth = prinst->numtempstringsstack; - PR_ExecuteCode(progfuncs, s); - - - PR_MoveParms(progfuncs, initial_progs, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); - - PR_FreeTemps(progfuncs, tempdepth); - prinst->numtempstringsstack = tempdepth; - - prinst->exitdepth = oldexitdepth; -} - - - - - - -typedef struct { - int fnum; - int progsnum; - int statement; -} qcthreadstack_t; -typedef struct qcthread_s { - int fstackdepth; - qcthreadstack_t fstack[MAX_STACK_DEPTH]; - int lstackused; - int lstack[LOCALSTACK_SIZE]; - int xstatement; - int xfunction; - progsnum_t xprogs; -} qcthread_t; - -struct qcthread_s *PR_ForkStack(progfuncs_t *progfuncs) -{ //QC code can call builtins that call qc code. - //to get around the problems of restoring the builtins we simply don't save the thread over the builtin. - int i, l; - int ed = prinst->exitdepth; - int localsoffset, baselocalsoffset; - qcthread_t *thread = memalloc(sizeof(qcthread_t)); - dfunction_t *f; - - //copy out the functions stack. - for (i = 0,localsoffset=0; i < ed; i++) - { - if (i+1 == pr_depth) - f = pr_xfunction; - else - f = pr_stack[i+1].f; - localsoffset += f->locals; //this is where it crashes - } - baselocalsoffset = localsoffset; - for (i = ed; i < pr_depth; i++) - { - thread->fstack[i-ed].fnum = pr_stack[i].f - pr_progstate[pr_stack[i].progsnum].functions; - thread->fstack[i-ed].progsnum = pr_stack[i].progsnum; - thread->fstack[i-ed].statement = pr_stack[i].s; - - if (i+1 == pr_depth) - f = pr_xfunction; - else - f = pr_stack[i+1].f; - localsoffset += f->locals; - } - thread->fstackdepth = pr_depth - ed; - - for (i = pr_depth - 1; i >= ed ; i--) - { - if (i+1 == pr_depth) - f = pr_xfunction; - else - f = pr_stack[i+1].f; - localsoffset -= f->locals; - for (l = 0; l < f->locals; l++) - { - thread->lstack[localsoffset-baselocalsoffset + l ] = ((int *)pr_globals)[f->parm_start + l]; - ((int *)pr_globals)[f->parm_start + l] = localstack[localsoffset+l]; //copy the old value into the globals (so the older functions have the correct locals. - } - } - - for (i = ed; i < pr_depth ; i++) //we need to get the locals back to how they were. - { - if (i+1 == pr_depth) - f = pr_xfunction; - else - f = pr_stack[i+1].f; - - for (l = 0; l < f->locals; l++) - { - ((int *)pr_globals)[f->parm_start + l] = thread->lstack[localsoffset-baselocalsoffset + l]; - } - localsoffset += f->locals; - } - thread->lstackused = localsoffset - baselocalsoffset; - - thread->xstatement = pr_xstatement; - thread->xfunction = pr_xfunction - pr_progstate[pr_typecurrent].functions; - thread->xprogs = pr_typecurrent; - - return thread; -} - -void PR_ResumeThread (progfuncs_t *progfuncs, struct qcthread_s *thread) -{ - dfunction_t *f, *oldf; - int i,l,ls; - progsnum_t initial_progs; - int oldexitdepth; - - int s; - int tempdepth; - - progsnum_t prnum = thread->xprogs; - int fnum = thread->xfunction; - - if (localstack_used + thread->lstackused > LOCALSTACK_SIZE) - PR_RunError(progfuncs, "Too many locals on resumtion of QC thread\n"); - - if (pr_depth + thread->fstackdepth > MAX_STACK_DEPTH) - PR_RunError(progfuncs, "Too large stack on resumtion of QC thread\n"); - - - //do progs switching stuff as appropriate. (fteqw only) - initial_progs = pr_typecurrent; - PR_MoveParms(progfuncs, prnum, pr_typecurrent); - PR_SwitchProgs(progfuncs, prnum); - - - oldexitdepth = prinst->exitdepth; - prinst->exitdepth = pr_depth; - - ls = 0; - //add on the callstack. - for (i = 0; i < thread->fstackdepth; i++) - { - if (pr_depth == prinst->exitdepth) - { - pr_stack[pr_depth].f = pr_xfunction; - pr_stack[pr_depth].s = pr_xstatement; - pr_stack[pr_depth].progsnum = initial_progs; - } - else - { - pr_stack[pr_depth].progsnum = thread->fstack[i].progsnum; - pr_stack[pr_depth].f = pr_progstate[thread->fstack[i].progsnum].functions + thread->fstack[i].fnum; - pr_stack[pr_depth].s = thread->fstack[i].statement; - } - - if (i+1 == thread->fstackdepth) - f = &pr_functions[fnum]; - else - f = pr_progstate[thread->fstack[i+1].progsnum].functions + thread->fstack[i+1].fnum; - for (l = 0; l < f->locals; l++) - { - localstack[localstack_used++] = ((int *)pr_globals)[f->parm_start + l]; - ((int *)pr_globals)[f->parm_start + l] = thread->lstack[ls++]; - } - - pr_depth++; - } - - if (ls != thread->lstackused) - PR_RunError(progfuncs, "Thread stores incorrect locals count\n"); - - - f = &pr_functions[fnum]; - -// thread->lstackused -= f->locals; //the current function is the odd one out. - - //add on the locals stack - memcpy(localstack+localstack_used, thread->lstack, sizeof(int)*thread->lstackused); - localstack_used += thread->lstackused; - - //bung the locals of the current function on the stack. -// for (i=0 ; i < f->locals ; i++) -// ((int *)pr_globals)[f->parm_start + i] = 0xff00ff00;//thread->lstack[thread->lstackused+i]; - - -// PR_EnterFunction (progfuncs, f, initial_progs); - oldf = pr_xfunction; - pr_xfunction = f; - s = thread->xstatement; - - tempdepth = prinst->numtempstringsstack; - PR_ExecuteCode(progfuncs, s); - - - PR_MoveParms(progfuncs, initial_progs, pr_typecurrent); - PR_SwitchProgs(progfuncs, initial_progs); - PR_FreeTemps(progfuncs, tempdepth); - prinst->numtempstringsstack = tempdepth; - - prinst->exitdepth = oldexitdepth; - pr_xfunction = oldf; -} - -void PR_AbortStack (progfuncs_t *progfuncs) -{ - while(pr_depth > prinst->exitdepth+1) - PR_LeaveFunction(progfuncs); - prinst->continuestatement = 0; -} - diff --git a/misc/mediasource/extra/fteqcc-src/pr_multi.c b/misc/mediasource/extra/fteqcc-src/pr_multi.c deleted file mode 100644 index 5a1ade75..00000000 --- a/misc/mediasource/extra/fteqcc-src/pr_multi.c +++ /dev/null @@ -1,427 +0,0 @@ -#define PROGSUSED -#include "progsint.h" - -#define HunkAlloc BADGDFG sdfhhsf FHS - -void PR_SetBuiltins(int type); -/* -progstate_t *pr_progstate; -progsnum_t pr_typecurrent; -int maxprogs; - -progstate_t *current_progstate; -int numshares; - -sharedvar_t *shares; //shared globals, not including parms -int maxshares; -*/ - -pbool PR_SwitchProgs(progfuncs_t *progfuncs, progsnum_t type) -{ - if ((unsigned)type >= maxprogs) - PR_RunError(progfuncs, "QCLIB: Bad prog type - %i", type); -// Sys_Error("Bad prog type - %i", type); - - if (pr_progstate[(unsigned)type].progs == NULL) //we havn't loaded it yet, for some reason - return false; - - current_progstate = &pr_progstate[(unsigned)type]; - - pr_typecurrent = type; - - return true; -} - -void PR_MoveParms(progfuncs_t *progfuncs, progsnum_t progs1, progsnum_t progs2) //from 2 to 1 -{ - unsigned int a; - progstate_t *p1; - progstate_t *p2; - - if (progs1 == progs2) - return; //don't bother coping variables to themselves... - - p1 = &pr_progstate[(int)progs1]; - p2 = &pr_progstate[(int)progs2]; - - if ((unsigned)progs1 >= maxprogs || !p1->globals) - Sys_Error("QCLIB: Bad prog type - %i", progs1); - if ((unsigned)progs2 >= maxprogs || !p2->globals) - Sys_Error("QCLIB: Bad prog type - %i", progs2); - - //copy parms. - for (a = 0; a < MAX_PARMS;a++) - { - *(int *)&p1->globals[OFS_PARM0+3*a ] = *(int *)&p2->globals[OFS_PARM0+3*a ]; - *(int *)&p1->globals[OFS_PARM0+3*a+1] = *(int *)&p2->globals[OFS_PARM0+3*a+1]; - *(int *)&p1->globals[OFS_PARM0+3*a+2] = *(int *)&p2->globals[OFS_PARM0+3*a+2]; - } - p1->globals[OFS_RETURN] = p2->globals[OFS_RETURN]; - p1->globals[OFS_RETURN+1] = p2->globals[OFS_RETURN+1]; - p1->globals[OFS_RETURN+2] = p2->globals[OFS_RETURN+2]; - - //move the vars defined as shared. - for (a = 0; a < numshares; a++)//fixme: make offset per progs - { - memmove(&((int *)p1->globals)[shares[a].varofs], &((int *)p2->globals)[shares[a].varofs], shares[a].size*4); -/* ((int *)p1->globals)[shares[a].varofs] = ((int *)p2->globals)[shares[a].varofs]; - if (shares[a].size > 1) - { - ((int *)p1->globals)[shares[a].varofs+1] = ((int *)p2->globals)[shares[a].varofs+1]; - if (shares[a].size > 2) - ((int *)p1->globals)[shares[a].varofs+2] = ((int *)p2->globals)[shares[a].varofs+2]; - } -*/ - } -} - -progsnum_t PR_LoadProgs(progfuncs_t *progfuncs, char *s, int headercrc, builtin_t *builtins, int numbuiltins) -{ - unsigned int a; - progsnum_t oldtype; - oldtype = pr_typecurrent; - for (a = 0; a < maxprogs; a++) - { - if (pr_progstate[a].progs == NULL) - { - pr_typecurrent = a; - current_progstate = &pr_progstate[a]; - if (PR_ReallyLoadProgs(progfuncs, s, headercrc, &pr_progstate[a], false)) //try and load it - { - current_progstate->builtins = builtins; - current_progstate->numbuiltins = numbuiltins; - -#ifdef QCJIT - if (prinst->usejit) - prinst->usejit = PR_GenerateJit(progfuncs); -#endif - if (oldtype>=0) - PR_SwitchProgs(progfuncs, oldtype); - return a; //we could load it. Yay! - } - if (oldtype!=-1) - PR_SwitchProgs(progfuncs, oldtype); - return -1; // loading failed. - } - } - PR_SwitchProgs(progfuncs, oldtype); - return -1; -} - -void PR_ShiftParms(progfuncs_t *progfuncs, int amount) -{ - int a; - for (a = 0; a < MAX_PARMS - amount;a++) - *(int *)&pr_globals[OFS_PARM0+3*a] = *(int *)&pr_globals[OFS_PARM0+3*(amount+a)]; -} - -//forget a progs -void PR_Clear(progfuncs_t *progfuncs) -{ - unsigned int a; - for (a = 0; a < maxprogs; a++) - { - pr_progstate[a].progs = NULL; - } -} - - - -void QC_StartShares(progfuncs_t *progfuncs) -{ - numshares = 0; - maxshares = 32; - if (shares) - memfree(shares); - shares = memalloc(sizeof(sharedvar_t)*maxshares); -} -void QC_AddSharedVar(progfuncs_t *progfuncs, int start, int size) //fixme: make offset per progs and optional -{ - int ofs; - unsigned int a; - - if (numshares >= maxshares) - { - void *buf; - buf = shares; - maxshares += 16; - shares = memalloc(sizeof(sharedvar_t)*maxshares); - - memcpy(shares, buf, sizeof(sharedvar_t)*numshares); - - memfree(buf); - } - ofs = start; - for (a = 0; a < numshares; a++) - { - if (shares[a].varofs+shares[a].size == ofs) - { - shares[a].size += size; //expand size. - return; - } - if (shares[a].varofs == start) - return; - } - - - shares[numshares].varofs = start; - shares[numshares].size = size; - numshares++; -} - - -//void ShowWatch(void); - -void QC_InitShares(progfuncs_t *progfuncs) -{ -// ShowWatch(); - if (!field) //don't make it so we will just need to remalloc everything - { - maxfields = 64; - field = memalloc(sizeof(fdef_t) * maxfields); - } - - numfields = 0; - progfuncs->fieldadjust = 0; -} - -void QC_FlushProgsOffsets(progfuncs_t *progfuncs) -{ //sets the fields up for loading a new progs. - //fields are matched by name to other progs - //not by offset - unsigned int i; - for (i = 0; i < numfields; i++) - field[i].progsofs = -1; -} - - -//called if a global is defined as a field -//returns offset. - -//vectors must be added before any of their corresponding _x/y/z vars -//in this way, even screwed up progs work. - -//requestedpos is the offset the engine WILL put it at. -//origionaloffs is used to track matching field offsets. fields with the same progs offset overlap - -//note: we probably suffer from progs with renamed system globals. -int QC_RegisterFieldVar(progfuncs_t *progfuncs, unsigned int type, char *name, int engineofs, int progsofs) -{ -// progstate_t *p; -// int pnum; - unsigned int i; - int namelen; - int ofs; - - int fnum; - - if (!name) //engine can use this to offset all progs fields - { //which fixes constant field offsets (some ktpro arrays) - progfuncs->fieldadjust = fields_size/4; - return 0; - } - - - prinst->reorganisefields = true; - - //look for an existing match - for (i = 0; i < numfields; i++) - { - if (!strcmp(name, field[i].name)) - { - if (field[i].type != type) - { - printf("Field type mismatch on \"%s\"\n", name); - continue; - } - if (!progfuncs->fieldadjust && engineofs>=0) - if ((unsigned)engineofs/4 != field[i].ofs) - Sys_Error("Field %s at wrong offset", name); - - if (field[i].progsofs == -1) - field[i].progsofs = progsofs; -// printf("Dupfield %s %i -> %i\n", name, field[i].progsofs,field[i].ofs); - return field[i].ofs-progfuncs->fieldadjust; //got a match - } - } - - if (numfields+1>maxfields) - { - fdef_t *nf; - i = maxfields; - maxfields += 32; - nf = memalloc(sizeof(fdef_t) * maxfields); - memcpy(nf, field, sizeof(fdef_t) * i); - memfree(field); - field = nf; - } - - //try to add a new one - fnum = numfields; - numfields++; - field[fnum].name = name; - if (type == ev_vector) - { - char *n; - namelen = strlen(name)+5; - - n=PRHunkAlloc(progfuncs, namelen); - sprintf(n, "%s_x", name); - ofs = QC_RegisterFieldVar(progfuncs, ev_float, n, engineofs, progsofs); - field[fnum].ofs = ofs+progfuncs->fieldadjust; - - n=PRHunkAlloc(progfuncs, namelen); - sprintf(n, "%s_y", name); - QC_RegisterFieldVar(progfuncs, ev_float, n, (engineofs==-1)?-1:(engineofs+4), (progsofs==-1)?-1:progsofs+1); - - n=PRHunkAlloc(progfuncs, namelen); - sprintf(n, "%s_z", name); - QC_RegisterFieldVar(progfuncs, ev_float, n, (engineofs==-1)?-1:(engineofs+8), (progsofs==-1)?-1:progsofs+2); - } - else if (engineofs >= 0) - { //the engine is setting up a list of required field indexes. - - //paranoid checking of the offset. - /* for (i = 0; i < numfields-1; i++) - { - if (field[i].ofs == ((unsigned)engineofs)/4) - { - if (type == ev_float && field[i].type == ev_vector) //check names - { - if (strncmp(field[i].name, name, strlen(field[i].name))) - Sys_Error("Duplicated offset"); - } - else - Sys_Error("Duplicated offset"); - } - }*/ - if (engineofs&3) - Sys_Error("field %s is %i&3", name, engineofs); - field[fnum].ofs = ofs = engineofs/4; - } - else - { //we just found a new fieldname inside a progs - field[fnum].ofs = ofs = fields_size/4; //add on the end - - //if the progs field offset matches annother offset in the same progs, make it match up with the earlier one. - if (progsofs>=0) - { - for (i = 0; i < numfields-1; i++) - { - if (field[i].progsofs == (unsigned)progsofs) - { -// printf("found union field %s %i -> %i\n", field[i].name, field[i].progsofs, field[i].ofs); - field[fnum].ofs = ofs = field[i].ofs; - break; - } - } - } - } -// if (type != ev_vector) - if (fields_size < (ofs+type_size[type])*4) - fields_size = (ofs+type_size[type])*4; - - if (max_fields_size && fields_size > max_fields_size) - Sys_Error("Allocated too many additional fields after ents were inited."); - field[fnum].type = type; - - field[fnum].progsofs = progsofs; - -// printf("Field %s %i -> %i\n", name, field[fnum].progsofs,field[fnum].ofs); - - //we've finished setting the structure - return ofs - progfuncs->fieldadjust; -} - - -//called if a global is defined as a field -void QC_AddSharedFieldVar(progfuncs_t *progfuncs, int num, char *stringtable) -{ -// progstate_t *p; -// int pnum; - unsigned int i, o; - - char *s; - - //look for an existing match not needed, cos we look a little later too. - /* - for (i = 0; i < numfields; i++) - { - if (!strcmp(pr_globaldefs[num].s_name, field[i].s_name)) - { - //really we should look for a field def - - *(int *)&pr_globals[pr_globaldefs[num].ofs] = field[i].ofs; //got a match - - return; - } - } - */ - - switch(current_progstate->intsize) - { - case 24: - case 16: - for (i=1 ; inumfielddefs; i++) - { - if (!strcmp(pr_fielddefs16[i].s_name+stringtable, pr_globaldefs16[num].s_name+stringtable)) - { -// int old = *(int *)&pr_globals[pr_globaldefs16[num].ofs]; - *(int *)&pr_globals[pr_globaldefs16[num].ofs] = QC_RegisterFieldVar(progfuncs, pr_fielddefs16[i].type, pr_globaldefs16[num].s_name+stringtable, -1, *(int *)&pr_globals[pr_globaldefs16[num].ofs]); - -// printf("Field %s %i -> %i\n", pr_globaldefs16[num].s_name+stringtable, old, *(int *)&pr_globals[pr_globaldefs16[num].ofs]); - return; - } - } - - s = pr_globaldefs16[num].s_name+stringtable; - - for (i = 0; i < numfields; i++) - { - o = field[i].progsofs; - if (o == *(unsigned int *)&pr_globals[pr_globaldefs16[num].ofs]) - { -// int old = *(int *)&pr_globals[pr_globaldefs16[num].ofs]; - *(int *)&pr_globals[pr_globaldefs16[num].ofs] = field[i].ofs-progfuncs->fieldadjust; -// printf("Field %s %i -> %i\n", pr_globaldefs16[num].s_name+stringtable, old, *(int *)&pr_globals[pr_globaldefs16[num].ofs]); - return; - } - } - - //oh well, must be a parameter. -// if (*(int *)&pr_globals[pr_globaldefs16[num].ofs]) -// Sys_Error("QCLIB: Global field var with no matching field \"%s\", from offset %i", pr_globaldefs16[num].s_name+stringtable, *(int *)&pr_globals[pr_globaldefs16[num].ofs]); - return; - case 32: - for (i=1 ; inumfielddefs; i++) - { - if (!strcmp(pr_fielddefs32[i].s_name+stringtable, pr_globaldefs32[num].s_name+stringtable)) - { - *(int *)&pr_globals[pr_globaldefs32[num].ofs] = QC_RegisterFieldVar(progfuncs, pr_fielddefs32[i].type, pr_globaldefs32[num].s_name+stringtable, -1, *(int *)&pr_globals[pr_globaldefs32[num].ofs]); - return; - } - } - - s = pr_globaldefs32[num].s_name+stringtable; - - for (i = 0; i < numfields; i++) - { - o = field[i].progsofs; - if (o == *(unsigned int *)&pr_globals[pr_globaldefs32[num].ofs]) - { - *(int *)&pr_globals[pr_globaldefs32[num].ofs] = field[i].ofs-progfuncs->fieldadjust; - return; - } - } - - //oh well, must be a parameter. - if (*(int *)&pr_globals[pr_globaldefs32[num].ofs]) - Sys_Error("QCLIB: Global field var with no matching field \"%s\", from offset %i", pr_globaldefs32[num].s_name+stringtable, *(int *)&pr_globals[pr_globaldefs32[num].ofs]); - return; - default: - Sys_Error("Bad bits"); - break; - } - Sys_Error("Should be unreachable"); -} - diff --git a/misc/mediasource/extra/fteqcc-src/pr_x86.c b/misc/mediasource/extra/fteqcc-src/pr_x86.c deleted file mode 100644 index 4ebfdda2..00000000 --- a/misc/mediasource/extra/fteqcc-src/pr_x86.c +++ /dev/null @@ -1,1087 +0,0 @@ -/* -when I say JIT, I mean load time, not execution time. - -notes: - qc jump offsets are all constants. we have no variable offset jumps (other than function calls/returns) - field remapping... fields are in place, and cannot be adjusted. if a field is not set to 0, its assumed to be a constant. - -optimisations: - none at the moment... - instructions need to be chained. stuff that writes to C should be cacheable, etc. maybe we don't even need to do the write to C - it should also be possible to fold in eq+ifnot, so none of this silly storeing of floats in equality tests - - eax - tmp - ebx - prinst->edicttable - ecx - tmp - edx - tmp - esi - - edi - tmp (because its preserved by subfunctions - ebp - - - to use gas to provide binary opcodes: - vim -N blob.s && as blob.s && objdump.exe -d a.out -*/ - -#define PROGSUSED -#include "progsint.h" - -#ifdef QCJIT - -static float ta, tb, nullfloat=0; - -unsigned int *statementjumps; //[MAX_STATEMENTS*2] -unsigned char **statementoffsets; //[MAX_STATEMENTS] -unsigned int numjumps; -unsigned char *code; -unsigned int codesize; -unsigned int jitstatements; - -void EmitByte(unsigned char byte) -{ - code[codesize++] = byte; -} -void Emit4Byte(unsigned int value) -{ - code[codesize++] = (value>> 0)&0xff; - code[codesize++] = (value>> 8)&0xff; - code[codesize++] = (value>>16)&0xff; - code[codesize++] = (value>>24)&0xff; -} -void EmitAdr(void *value) -{ - Emit4Byte((unsigned int)value); -} -void EmitFloat(float value) -{ - union {float f; unsigned int i;} u; - u.f = value; - Emit4Byte(u.i); -} -void Emit2Byte(unsigned short value) -{ - code[codesize++] = (value>> 0)&0xff; - code[codesize++] = (value>> 8)&0xff; -} - -void EmitFOffset(void *func, int bias) -{ - union {void *f; unsigned int i;} u; - u.f = func; - u.i -= (unsigned int)&code[codesize+bias]; - Emit4Byte(u.i); -} - -void Emit4ByteJump(int statementnum, int offset) -{ - statementjumps[numjumps++] = codesize; - statementjumps[numjumps++] = statementnum; - statementjumps[numjumps++] = offset; - - //the offset is filled in later - codesize += 4; -} - -void FixupJumps(void) -{ - unsigned int j; - unsigned char *codesrc; - unsigned char *codedst; - unsigned int offset; - - unsigned int v; - - for (j = 0; j < numjumps;) - { - v = statementjumps[j++]; - codesrc = &code[v]; - - v = statementjumps[j++]; - codedst = statementoffsets[v]; - - v = statementjumps[j++]; - offset = (int)(codedst - (codesrc-v)); //3rd term because the jump is relative to the instruction start, not the instruction's offset - - codesrc[0] = (offset>> 0)&0xff; - codesrc[1] = (offset>> 8)&0xff; - codesrc[2] = (offset>>16)&0xff; - codesrc[3] = (offset>>24)&0xff; - } -} - -int PR_LeaveFunction (progfuncs_t *progfuncs); -int PR_EnterFunction (progfuncs_t *progfuncs, dfunction_t *f, int progsnum); - -pbool PR_GenerateJit(progfuncs_t *progfuncs) -{ - unsigned int i; - dstatement16_t *op = (dstatement16_t*)current_progstate->statements; - unsigned int numstatements = current_progstate->progs->numstatements; - int *glob = (int*)current_progstate->globals; - - if (current_progstate->numbuiltins) - return false; - - jitstatements = numstatements; - - statementjumps = malloc(numstatements*12); - statementoffsets = malloc(numstatements*4); - code = malloc(numstatements*500); - - numjumps = 0; - codesize = 0; - - - - for (i = 0; i < numstatements; i++) - { - statementoffsets[i] = &code[codesize]; - switch(op[i].op) - { - //jumps - case OP_IF: - //integer compare - //if a, goto b - - //cmpl $0,glob[A] - EmitByte(0x83);EmitByte(0x3d);EmitAdr(glob + op[i].a);EmitByte(0x0); - //jnz B - EmitByte(0x0f);EmitByte(0x85);Emit4ByteJump(i + (signed short)op[i].b, -4); - break; - - case OP_IFNOT: - //integer compare - //if !a, goto b - - //cmpl $0,glob[A] - EmitByte(0x83);EmitByte(0x3d);EmitAdr(glob + op[i].a);EmitByte(0x0); - //jz B - EmitByte(0x0f);EmitByte(0x84);Emit4ByteJump(i + (signed short)op[i].b, -4); - break; - - case OP_GOTO: - EmitByte(0xE9);Emit4ByteJump(i + (signed short)op[i].a, -4); - break; - - //function returns - case OP_DONE: - case OP_RETURN: - //done and return are the same - - //part 1: store A into OFS_RETURN - - if (!op[i].a) - { - //assumption: anything that returns address 0 is a void or zero return. - //thus clear eax and copy that to the return vector. - EmitByte(0x31);EmitByte(0xc0); - EmitByte(0xa3);EmitAdr(glob + OFS_RETURN+0); - EmitByte(0xa3);EmitAdr(glob + OFS_RETURN+1); - EmitByte(0xa3);EmitAdr(glob + OFS_RETURN+2); - } - else - { - //movl glob[A+0],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a+0); - //movl glob[A+0],edx - EmitByte(0x8b);EmitByte(0x0d);EmitAdr(glob + op[i].a+1); - //movl glob[A+0],ecx - EmitByte(0x8b);EmitByte(0x15);EmitAdr(glob + op[i].a+2); - //movl eax, glob[OFS_RET+0] - EmitByte(0xa3);EmitAdr(glob + OFS_RETURN+0); - //movl edx, glob[OFS_RET+0] - EmitByte(0x89);EmitByte(0x15);EmitAdr(glob + OFS_RETURN+1); - //movl ecx, glob[OFS_RET+0] - EmitByte(0x89);EmitByte(0x15);EmitAdr(glob + OFS_RETURN+2); - } - - //call leavefunction to get the return address - -// pushl progfuncs - EmitByte(0x68);EmitAdr(progfuncs); -// call PR_LeaveFunction - EmitByte(0xe8);EmitFOffset(PR_LeaveFunction, 4); -// add $4,%esp - EmitByte(0x83);EmitByte(0xc4);EmitByte(0x04); -// movl pr_depth,%edx - EmitByte(0x8b);EmitByte(0x15);EmitAdr(&pr_depth); -// cmp prinst->exitdepth,%edx - EmitByte(0x3b);EmitByte(0x15);EmitAdr(&prinst->exitdepth); -// je returntoc - EmitByte(0x74);EmitByte(0x09); -// mov statementoffsets[%eax*4],%eax - EmitByte(0x8b);EmitByte(0x04);EmitByte(0x85);EmitAdr(statementoffsets+1); -// jmp eax - EmitByte(0xff);EmitByte(0xe0); -// returntoc: -// ret - EmitByte(0xc3); - break; - - //function calls - case OP_CALL0: - case OP_CALL1: - case OP_CALL2: - case OP_CALL3: - case OP_CALL4: - case OP_CALL5: - case OP_CALL6: - case OP_CALL7: - case OP_CALL8: - //save the state in place the rest of the engine can cope with - //movl $i, pr_xstatement - EmitByte(0xc7);EmitByte(0x05);EmitAdr(&pr_xstatement);Emit4Byte(i); - //movl $(op[i].op-OP_CALL0), pr_argc - EmitByte(0xc7);EmitByte(0x05);EmitAdr(&pr_argc);Emit4Byte(op[i].op-OP_CALL0); - - //figure out who we're calling, and what that involves - //%eax = glob[A] - EmitByte(0xa1); EmitAdr(glob + op[i].a); - //eax is now the func num - - //mov %eax,%ecx - EmitByte(0x89); EmitByte(0xc1); - //shr $24,%ecx - EmitByte(0xc1); EmitByte(0xe9); EmitByte(0x18); - //ecx is now the progs num for the new func - - //cmp %ecx,pr_typecurrent - EmitByte(0x39); EmitByte(0x0d); EmitAdr(&pr_typecurrent); - //je sameprogs - EmitByte(0x74); EmitByte(0x3); - { - //can't handle switching progs - - //FIXME: recurse though PR_ExecuteProgram - //push eax - //push progfuncs - //call PR_ExecuteProgram - //add $8,%esp - //remember to change the je above - - //err... exit depth? no idea - EmitByte(0xcd);EmitByte(op[i].op); //int $X - - - //ret - EmitByte(0xc3); - } - //sameprogs: - - //andl $0x00ffffff, %eax - EmitByte(0x25);Emit4Byte(0x00ffffff); - - //mov $sizeof(dfunction_t),%edx - EmitByte(0xba);Emit4Byte(sizeof(dfunction_t)); - //mul %edx - EmitByte(0xf7); EmitByte(0xe2); - //add pr_functions,%eax - EmitByte(0x05); EmitAdr(pr_functions); - - //eax is now the dfunction_t to be called - //edx is clobbered. - - //mov (%eax),%edx - EmitByte(0x8b);EmitByte(0x10); - //edx is now the first statement number - //cmp $0,%edx - EmitByte(0x83);EmitByte(0xfa);EmitByte(0x00); - //jl isabuiltin - EmitByte(0x7c);EmitByte(22); - - { - //push %ecx - EmitByte(0x51); - //push %eax - EmitByte(0x50); - //pushl progfuncs - EmitByte(0x68);EmitAdr(progfuncs); - //call PR_EnterFunction - EmitByte(0xe8);EmitFOffset(PR_EnterFunction, 4); - //sub $12,%esp - EmitByte(0x83);EmitByte(0xc4);EmitByte(0xc); - //eax is now the next statement number (first of the new function, usually equal to ecx, but not always) - - //jmp statementoffsets[%eax*4] - EmitByte(0xff);EmitByte(0x24);EmitByte(0x85);EmitAdr(statementoffsets+1); - } - //isabuiltin: - - - //push current_progstate->globals - EmitByte(0x68);EmitAdr(current_progstate->globals); - //push progfuncs - EmitByte(0x68);EmitAdr(progfuncs); - //neg %edx - EmitByte(0xf7);EmitByte(0xda); - //call externs->globalbuiltins[%edx,4] -//FIXME: make sure this dereferences - EmitByte(0xff);EmitByte(0x14);EmitByte(0x95);EmitAdr(externs->globalbuiltins); - //add $8,%esp - EmitByte(0x83);EmitByte(0xc4);EmitByte(0x8); - - //but that builtin might have been Abort() - - //mov prinst->continuestatement,%eax - EmitByte(0xa1);EmitAdr(&prinst->continuestatement); - //eax is now prinst->continuestatement - - //cmp $-1,%eax - EmitByte(0x83);EmitByte(0xf8);EmitByte(0xff); - //je donebuiltincall - EmitByte(0x74);EmitByte(10+8); - { -EmitByte(0xcc); - //jmp statementoffsets[%eax*4] - EmitByte(0xff);EmitByte(0x24);EmitByte(0x85);EmitAdr(statementoffsets+1); - - //mov $-1,prinst->continuestatement - EmitByte(0xc7);EmitByte(0x05);EmitAdr(&prinst->continuestatement+1);Emit4Byte((unsigned int)-1); - } - //donebuiltincall: - break; - - case OP_MUL_F: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a); - //fmuls glob[B] - EmitByte(0xd8);EmitByte(0x0d);EmitAdr(glob + op[i].b); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c); - break; - case OP_DIV_F: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a); - //fdivs glob[B] - EmitByte(0xd8);EmitByte(0x35);EmitAdr(glob + op[i].b); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c); - break; - case OP_ADD_F: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a); - //fadds glob[B] - EmitByte(0xd8);EmitByte(0x05);EmitAdr(glob + op[i].b); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c); - break; - case OP_SUB_F: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a); - //fsubs glob[B] - EmitByte(0xd8);EmitByte(0x25);EmitAdr(glob + op[i].b); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c); - break; - - case OP_NOT_F: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a); - //fldz - EmitByte(0xd9);EmitByte(0xee); - //fnstsw %ax - EmitByte(0xdf);EmitByte(0xe0); - //testb 0x40,%ah - EmitByte(0xf6);EmitByte(0xc4);EmitByte(0x40); - //je noteq - EmitByte(0x74);EmitByte(0x0c); - //movl 1.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05);EmitAdr(glob + op[i].c);EmitFloat(0.0f); - //jmp end - EmitByte(0xeb);EmitByte(0x0a); - //noteq: - //movl 0.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05);EmitAdr(glob + op[i].c);EmitFloat(1.0f); - //end: - break; - - case OP_STORE_F: - case OP_STORE_S: - case OP_STORE_ENT: - case OP_STORE_FLD: - case OP_STORE_FNC: - //movl glob[A],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a); - //movl eax,glob[B] - EmitByte(0xa3);EmitAdr(glob + op[i].b); - break; - - case OP_STORE_V: - //movl glob[A+0],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a+0); - //movl glob[A+1],edx - EmitByte(0x8b);EmitByte(0x0d);EmitAdr(glob + op[i].a+1); - //movl glob[A+2],ecx - EmitByte(0x8b);EmitByte(0x15);EmitAdr(glob + op[i].a+2); - - //movl eax, glob[B+0] - EmitByte(0xa3);EmitAdr(glob + op[i].b+0); - //movl edx, glob[B+1] - EmitByte(0x89);EmitByte(0x15);EmitAdr(glob + op[i].b+1); - //movl ecx, glob[B+2] - EmitByte(0x89);EmitByte(0x15);EmitAdr(glob + op[i].b+2); - break; - - case OP_LOAD_F: - case OP_LOAD_S: - case OP_LOAD_ENT: - case OP_LOAD_FLD: - case OP_LOAD_FNC: - case OP_LOAD_V: - //a is the ent number, b is the field - //c is the dest - - //movl glob[A+0],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a); - //mov glob[B],ecx - EmitByte(0x8b); EmitByte(0x0d);EmitAdr(glob + op[i].b); - //FIXME: bound eax (ent number) - //FIXME: bound ecx (field index) - //mov (ebx,eax,4).%eax - EmitByte(0x8b); EmitByte(0x04); EmitByte(0x83); - //eax is now an edictrun_t - //mov fields(,%eax,4),%edx - EmitByte(0x8b);EmitByte(0x50);EmitByte((int)&((edictrun_t*)NULL)->fields); - //edx is now the field array for that ent - - //mov fieldajust(%edx,%ecx,4),%eax //offset = progfuncs->fieldadjust - EmitByte(0x8b); EmitByte(0x84); EmitByte(0x8a); Emit4Byte(progfuncs->fieldadjust*4); - //mov edx,glob[C] - EmitByte(0xa3);EmitAdr(glob + op[i].c); - - if (op[i].op == OP_LOAD_V) - { - //mov fieldajust+4(%edx,%ecx,4),%eax //offset = progfuncs->fieldadjust - EmitByte(0x8b); EmitByte(0x84); EmitByte(0x8a); Emit4Byte(4+progfuncs->fieldadjust*4); - //mov edx,glob[C+1] - EmitByte(0xa3);EmitAdr(glob + op[i].c+1); - - //mov fieldajust+8(%edx,%ecx,4),%eax //offset = progfuncs->fieldadjust - EmitByte(0x8b); EmitByte(0x84); EmitByte(0x8a); Emit4Byte(4+progfuncs->fieldadjust*4); - //mov edx,glob[C+1] - EmitByte(0xa3);EmitAdr(glob + op[i].c+2); - } - break; - - case OP_ADDRESS: - //a is the ent number, b is the field - //c is the dest - - //movl glob[A+0],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a); - //mov glob[B],ecx - EmitByte(0x8b); EmitByte(0x0d);EmitAdr(glob + op[i].b); - //FIXME: bound eax (ent number) - //FIXME: bound ecx (field index) - //mov (ebx,eax,4).%eax - EmitByte(0x8b); EmitByte(0x04); EmitByte(0x83); - //eax is now an edictrun_t - //mov fields(,%eax,4),%edx - EmitByte(0x8b);EmitByte(0x50);EmitByte((int)&((edictrun_t*)NULL)->fields); - //edx is now the field array for that ent - //mov fieldajust(%edx,%ecx,4),%eax //offset = progfuncs->fieldadjust - //EmitByte(0x8d); EmitByte(0x84); EmitByte(0x8a); EmitByte(progfuncs->fieldadjust*4); - EmitByte(0x8d); EmitByte(0x84); EmitByte(0x8a); Emit4Byte(progfuncs->fieldadjust*4); - //mov edx,glob[C] - EmitByte(0xa3);EmitAdr(glob + op[i].c); - break; - - case OP_STOREP_F: - case OP_STOREP_S: - case OP_STOREP_ENT: - case OP_STOREP_FLD: - case OP_STOREP_FNC: - //movl glob[A],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a); - //mov glob[B],ecx - EmitByte(0x8b); EmitByte(0x0d);EmitAdr(glob + op[i].b); - //mov %eax,(%ecx) - EmitByte(0x89);EmitByte(0x01); - break; - - case OP_STOREP_V: - //mov glob[B],ecx - EmitByte(0x8b); EmitByte(0x0d);EmitAdr(glob + op[i].b); - //movl glob[A],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a+0); - //mov %eax,0(%ecx) - EmitByte(0x89);EmitByte(0x01); - //movl glob[A],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a+0); - //mov %eax,4(%ecx) - EmitByte(0x89);EmitByte(0x41);EmitByte(0x04); - //movl glob[A],eax - EmitByte(0xa1);EmitAdr(glob + op[i].a+0); - //mov %eax,8(%ecx) - EmitByte(0x89);EmitByte(0x41);EmitByte(0x08); - break; - - case OP_EQ_E: - case OP_EQ_FNC: - //integer equality - //movl glob[A],%eax - EmitByte(0xa1);EmitAdr(glob + op[i].a); - //cmp glob[B],%eax - EmitByte(0x3b); EmitByte(0x0f); EmitAdr(glob + op[i].b); - //je 12 - EmitByte(0x74);EmitByte(0x0c); - //mov 0.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05); EmitAdr(glob + op[i].a);EmitFloat(0.0f); - //jmp 10 - EmitByte(0xeb);EmitByte(0x0a); - //mov 1.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05); EmitAdr(glob + op[i].a);EmitFloat(1.0f); - break; - - case OP_NE_E: - case OP_NE_FNC: - //integer equality - //movl glob[A],%eax - EmitByte(0xa1);EmitAdr(glob + op[i].a); - //cmp glob[B],%eax - EmitByte(0x3b); EmitByte(0x0f); EmitAdr(glob + op[i].b); - //je 12 - EmitByte(0x74);EmitByte(0x0c); - //mov 0.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05); EmitAdr(glob + op[i].a);EmitFloat(1.0f); - //jmp 10 - EmitByte(0xeb);EmitByte(0x0a); - //mov 1.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05); EmitAdr(glob + op[i].a);EmitFloat(0.0f); - break; - - case OP_NOT_ENT: - case OP_NOT_FNC: - //cmp glob[B],%eax - EmitByte(0x8c); EmitByte(0x3d); EmitAdr(glob + op[i].a);EmitByte(0x00); - //je 12 - EmitByte(0x74);EmitByte(0x0c); - //mov 0.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05); EmitAdr(glob + op[i].a);EmitFloat(0.0f); - //jmp 10 - EmitByte(0xeb);EmitByte(0x0a); - //mov 1.0f,glob[C] - EmitByte(0xc7);EmitByte(0x05); EmitAdr(glob + op[i].c);EmitFloat(1.0f); - break; - - case OP_BITOR: //floats... - //flds glob[A] - EmitByte(0xd9); EmitByte(0x05);EmitAdr(glob + op[i].a); - //flds glob[B] - EmitByte(0xd9); EmitByte(0x05);EmitAdr(glob + op[i].b); - //fistp tb - EmitByte(0xdf); EmitByte(0x1d);EmitAdr(&tb); - //fistp ta - EmitByte(0xdf); EmitByte(0x1d);EmitAdr(&ta); - //mov ta,%eax - EmitByte(0xa1); EmitAdr(&ta); - //and tb,%eax - EmitByte(0x09); EmitByte(0x05);EmitAdr(&tb); - //fild tb - EmitByte(0xdf); EmitByte(0x05);EmitAdr(&tb); - //fstps glob[C] - EmitByte(0xd9); EmitByte(0x1d);EmitAdr(glob + op[i].c); - break; - - case OP_BITAND: - //flds glob[A] - EmitByte(0xd9); EmitByte(0x05);EmitAdr(glob + op[i].a); - //flds glob[B] - EmitByte(0xd9); EmitByte(0x05);EmitAdr(glob + op[i].b); - //fistp tb - EmitByte(0xdf); EmitByte(0x1d);EmitAdr(&tb); - //fistp ta - EmitByte(0xdf); EmitByte(0x1d);EmitAdr(&ta); - //mov ta,%eax - EmitByte(0xa1); EmitAdr(&ta); - //and tb,%eax - EmitByte(0x21); EmitByte(0x05);EmitAdr(&tb); - //fild tb - EmitByte(0xdf); EmitByte(0x05);EmitAdr(&tb); - //fstps glob[C] - EmitByte(0xd9); EmitByte(0x1d);EmitAdr(glob + op[i].c); - break; - - case OP_AND: - //test floats properly, so we don't get confused with -0.0 - - //flds glob[A] - EmitByte(0xd9); EmitByte(0x05); EmitAdr(glob + op[i].a); - //fcomps nullfloat - EmitByte(0xd8); EmitByte(0x1d); EmitAdr(&nullfloat); - //fnstsw %ax - EmitByte(0xdf); EmitByte(0xe0); - //test $0x40,%ah - EmitByte(0xf6); EmitByte(0xc4);EmitByte(0x40); - //je onefalse - EmitByte(0x75); EmitByte(0x1f); - - //flds glob[B] - EmitByte(0xd9); EmitByte(0x05); EmitAdr(glob + op[i].b); - //fcomps nullfloat - EmitByte(0xd8); EmitByte(0x1d); EmitAdr(&nullfloat); - //fnstsw %ax - EmitByte(0xdf); EmitByte(0xe0); - //test $0x40,%ah - EmitByte(0xf6); EmitByte(0xc4);EmitByte(0x40); - //jne onefalse - EmitByte(0x75); EmitByte(0x0c); - - //mov float0,glob[C] - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(1.0f); - //jmp done - EmitByte(0xeb); EmitByte(0x0a); - - //onefalse: - //mov float1,glob[C] - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(0.0f); - //done: - break; - case OP_OR: - //test floats properly, so we don't get confused with -0.0 - - //flds glob[A] - EmitByte(0xd9); EmitByte(0x05); EmitAdr(glob + op[i].a); - //fcomps nullfloat - EmitByte(0xd8); EmitByte(0x1d); EmitAdr(&nullfloat); - //fnstsw %ax - EmitByte(0xdf); EmitByte(0xe0); - //test $0x40,%ah - EmitByte(0xf6); EmitByte(0xc4);EmitByte(0x40); - //je onetrue - EmitByte(0x74); EmitByte(0x1f); - - //flds glob[B] - EmitByte(0xd9); EmitByte(0x05); EmitAdr(glob + op[i].b); - //fcomps nullfloat - EmitByte(0xd8); EmitByte(0x1d); EmitAdr(&nullfloat); - //fnstsw %ax - EmitByte(0xdf); EmitByte(0xe0); - //test $0x40,%ah - EmitByte(0xf6); EmitByte(0xc4);EmitByte(0x40); - //je onetrue - EmitByte(0x74); EmitByte(0x0c); - - //mov float0,glob[C] - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(0.0f); - //jmp done - EmitByte(0xeb); EmitByte(0x0a); - - //onetrue: - //mov float1,glob[C] - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(1.0f); - //done: - break; - - case OP_EQ_S: - case OP_NE_S: - //put a in ecx - //put b in edi - //mov a,%ecx - EmitByte(0x8b); EmitByte(0x0d); EmitAdr(glob + op[i].a); - //mov b,%edi - EmitByte(0x8b); EmitByte(0x3d); EmitAdr(glob + op[i].b); - - //early out if they're equal - //cmp %ecx,%edi - EmitByte(0x39); EmitByte(0xd1); - //je _true - EmitByte(0x74); EmitByte(0x68); - - //if a is 0, check if b is "" - //jecxz ais0 - EmitByte(0xe3); EmitByte(0x1a); - - //if b is 0, check if a is "" - //cmp $0,%edi - EmitByte(0x83); EmitByte(0xff); EmitByte(0x00); - //jne bnot0 - EmitByte(0x75); EmitByte(0x2a); - { - //push a - EmitByte(0x51); - //push progfuncs - EmitByte(0x68); EmitAdr(progfuncs); - //call PR_StringToNative - EmitByte(0xe8); EmitFOffset(PR_StringToNative,4); - //add $8,%esp - EmitByte(0x83); EmitByte(0xc4); EmitByte(0x08); - //cmpb $0,(%eax) - EmitByte(0x80); EmitByte(0x38); EmitByte(0x00); - //je _true - EmitByte(0x74); EmitByte(0x4b); - //jmp _false - EmitByte(0xeb); EmitByte(0x3d); - - //ais0: - { - //push edi - EmitByte(0x57); - //push progfuncs - EmitByte(0x68); EmitAdr(progfuncs); - //call PR_StringToNative - EmitByte(0xe8); EmitFOffset(PR_StringToNative,4); - //add $8,%esp - EmitByte(0x83); EmitByte(0xc4); EmitByte(0x08); - //cmpb $0,(%eax) - EmitByte(0x80); EmitByte(0x38); EmitByte(0x00); - //je _true - EmitByte(0x74); EmitByte(0x36); - //jmp _false - EmitByte(0xeb); EmitByte(0x28); - } - } - //bnot0: - - //push ecx - EmitByte(0x51); - //push progfuncs - EmitByte(0x68); EmitAdr(progfuncs); - //call PR_StringToNative - EmitByte(0xe8); EmitFOffset(PR_StringToNative,4); - //push %eax - EmitByte(0x50); - - //push %edi - EmitByte(0x57); - //push progfuncs - EmitByte(0x68); EmitAdr(progfuncs); - //call PR_StringToNative - EmitByte(0xe8); EmitFOffset(PR_StringToNative,4); - //add $8,%esp - EmitByte(0x83); EmitByte(0xc4); EmitByte(0x08); - - - //push %eax - EmitByte(0x50); - //call strcmp - EmitByte(0xe8); EmitFOffset(strcmp,4); - //add $16,%esp - EmitByte(0x83); EmitByte(0xc4); EmitByte(0x10); - //cmp $0,%eax - EmitByte(0x83); EmitByte(0xf8); EmitByte(0x00); - //je _true - EmitByte(0x74); EmitByte(0x0c); -//_false: - //mov 0.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat((op[i].op == OP_NE_S)?1.0f:0.0f); - //jmp done - EmitByte(0xeb); EmitByte(0x0a); -//_true: - //mov 1.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat((op[i].op == OP_NE_S)?0.0f:1.0f); -//_done: - break; - - case OP_NOT_S: - //mov A,%eax - EmitByte(0xa1);EmitAdr(glob + op[i].a); - //cmp $0,%eax - EmitByte(0x83); EmitByte(0xf8); EmitByte(0x00); - //je _true - EmitByte(0x74); EmitByte(0x1f); - //push %eax - EmitByte(0x50); - //push progfuncs - EmitByte(0x68); EmitAdr(progfuncs); - //call PR_StringToNative - EmitByte(0xe8); EmitFOffset(PR_StringToNative,4); - //add $8,%esp - EmitByte(0x83); EmitByte(0xc4); EmitByte(0x08); - //cmpb $0,(%eax) - EmitByte(0x80); EmitByte(0x38); EmitByte(0x00); - //je _true - EmitByte(0x74); EmitByte(0x0c); -//_false: - //mov 0.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(0.0f); - //jmp done - EmitByte(0xeb); EmitByte(0x0a); -//_true: - //mov 1.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(1.0f); -//_done: - break; - - case OP_ADD_V: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+0); - //fadds glob[B] - EmitByte(0xd8);EmitByte(0x05);EmitAdr(glob + op[i].b+0); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+0); - - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+1); - //fadds glob[B] - EmitByte(0xd8);EmitByte(0x05);EmitAdr(glob + op[i].b+1); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+1); - - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+2); - //fadds glob[B] - EmitByte(0xd8);EmitByte(0x05);EmitAdr(glob + op[i].b+2); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+2); - break; - case OP_SUB_V: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+0); - //fsubs glob[B] - EmitByte(0xd8);EmitByte(0x25);EmitAdr(glob + op[i].b+0); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+0); - - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+1); - //fsubs glob[B] - EmitByte(0xd8);EmitByte(0x25);EmitAdr(glob + op[i].b+1); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+1); - - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+2); - //fsubs glob[B] - EmitByte(0xd8);EmitByte(0x25);EmitAdr(glob + op[i].b+2); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+2); - break; - - case OP_MUL_V: - //this is actually a dotproduct - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+0); - //fmuls glob[B] - EmitByte(0xd8);EmitByte(0x0d);EmitAdr(glob + op[i].b+0); - - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+1); - //fmuls glob[B] - EmitByte(0xd8);EmitByte(0x0d);EmitAdr(glob + op[i].b+1); - - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+2); - //fmuls glob[B] - EmitByte(0xd8);EmitByte(0x0d);EmitAdr(glob + op[i].b+2); - - //faddp - EmitByte(0xde);EmitByte(0xc1); - //faddp - EmitByte(0xde);EmitByte(0xc1); - - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c); - break; - - case OP_EQ_F: - case OP_NE_F: - case OP_LE: - case OP_GE: - case OP_LT: - case OP_GT: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a); - //flds glob[B] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].b); - //fcomip %st(1),%st - EmitByte(0xdf);EmitByte(0xe9); - //fstp %st(0) (aka: pop) - EmitByte(0xdd);EmitByte(0xd8); - - //jcc _true - if (op[i].op == OP_LE) - EmitByte(0x7e); //jle - else if (op[i].op == OP_GE) - EmitByte(0x7d); //jge - else if (op[i].op == OP_LT) - EmitByte(0x7c); //jl - else if (op[i].op == OP_GT) - EmitByte(0x7f); //jg - else if (op[i].op == OP_NE_F) - EmitByte(0x75); //jne - else - EmitByte(0x74); //je - EmitByte(0x0c); -//_false: - //mov 0.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(0.0f); - //jmp done - EmitByte(0xeb); EmitByte(0x0a); -//_true: - //mov 1.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(1.0f); -//_done: - break; - - case OP_MUL_FV: - case OP_MUL_VF: - // - { - int v; - int f; - if (op[i].op == OP_MUL_FV) - { - f = op[i].a; - v = op[i].b; - } - else - { - v = op[i].a; - f = op[i].b; - } - - //flds glob[F] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + f); - - //flds glob[V0] - EmitByte(0xd8);EmitByte(0x0d);EmitAdr(glob + v+0); - //fmul st(1) - EmitByte(0xd8);EmitByte(0xc9); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+0); - - //flds glob[V0] - EmitByte(0xd8);EmitByte(0x0d);EmitAdr(glob + v+1); - //fmul st(1) - EmitByte(0xd8);EmitByte(0xc9); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+1); - - //flds glob[V0] - EmitByte(0xd8);EmitByte(0x0d);EmitAdr(glob + v+2); - //fmul st(1) - EmitByte(0xd8);EmitByte(0xc9); - //fstps glob[C] - EmitByte(0xd9);EmitByte(0x1d);EmitAdr(glob + op[i].c+2); - - //fstp %st(0) (aka: pop) - EmitByte(0xdd);EmitByte(0xd8); - } - break; - - case OP_STATE: - //externs->stateop(progfuncs, OPA->_float, OPB->function); - //push b - EmitByte(0xff);EmitByte(0x35);EmitAdr(glob + op[i].b); - //push a - EmitByte(0xff);EmitByte(0x35);EmitAdr(glob + op[i].a); - //push $progfuncs - EmitByte(0x68); EmitAdr(progfuncs); - //call externs->stateop - EmitByte(0xe8); EmitFOffset(externs->stateop, 4); - //add $12,%esp - EmitByte(0x83); EmitByte(0xc4); EmitByte(0x0c); - break; -#if 0 - case OP_NOT_V: - //flds 0 - //flds glob[A+0] - //fcomip %st(1),%st - //jne _true - //flds glob[A+1] - //fcomip %st(1),%st - //jne _true - //flds glob[A+1] - //fcomip %st(1),%st - //jne _true - //mov 1,C - //jmp done - //_true: - //mov 0,C - //done: - break; - - case OP_EQ_V: - //flds glob[A] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].a+0); - //flds glob[B] - EmitByte(0xd9);EmitByte(0x05);EmitAdr(glob + op[i].b+0); - //fcomip %st(1),%st - EmitByte(0xdf);EmitByte(0xe9); - //fstp %st(0) (aka: pop) - EmitByte(0xdd);EmitByte(0xd8); - - //jncc _true - if (op[i].op == OP_NE_V) - EmitByte(0x74); //je - else - EmitByte(0x75); //jne - EmitByte(0x0c); -//_false0: - //mov 0.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(1.0f); - //jmp done - EmitByte(0xeb); EmitByte(0x0a); - - -//_true: - //mov 1.0f,c - EmitByte(0xc7); EmitByte(0x05); EmitAdr(glob + op[i].c); EmitFloat(0.0f); -//_done: - break; - - - case OP_EQ_V: - EmitByte(0xcd);EmitByte(op[i].op); - printf("QCJIT: instruction %i is not implemented\n", op[i].op); - break; - - case OP_NE_V: - EmitByte(0xcd);EmitByte(op[i].op); - printf("QCJIT: instruction %i is not implemented\n", op[i].op); - break; - - case OP_NOT_V: - EmitByte(0xcd);EmitByte(op[i].op); - printf("QCJIT: instruction %i is not implemented\n", op[i].op); - break; -#endif - default: - printf("QCJIT: Extended instruction set %i is not supported, not using jit.\n", op[i].op); - - - free(statementjumps); //[MAX_STATEMENTS] - free(statementoffsets); //[MAX_STATEMENTS] - free(code); - statementoffsets = NULL; - return false; - } - } - - FixupJumps(); - -#ifdef _WIN32 - { - DWORD old; - - //this memory is on the heap. - //this means that we must maintain read/write protection, or libc will crash us - VirtualProtect(code, codesize, PAGE_EXECUTE_READWRITE, &old); - } -#endif - -// externs->WriteFile("jit.x86", code, codesize); - - return true; -} - -void PR_EnterJIT(progfuncs_t *progfuncs, int statement) -{ -#ifdef __GNUC__ - //call, it clobbers pretty much everything. - asm("call *%0" :: "r"(statementoffsets[statement+1]),"b"(prinst->edicttable):"cc","memory","eax","ecx","edx"); -#elif defined(_MSC_VER) - void *entry = statementoffsets[statement+1]; - void *edicttable = prinst->edicttable; - __asm { - pushad - mov eax,entry - mov ebx,edicttable - call eax - popad - } -#else - #error "Sorry, no idea how to enter assembler safely for your compiler" -#endif -} -#endif diff --git a/misc/mediasource/extra/fteqcc-src/progsint.h b/misc/mediasource/extra/fteqcc-src/progsint.h deleted file mode 100644 index 39c316e5..00000000 --- a/misc/mediasource/extra/fteqcc-src/progsint.h +++ /dev/null @@ -1,477 +0,0 @@ -#ifdef _WIN32 - - #ifndef AVAIL_ZLIB - #ifdef _MSC_VER - //#define AVAIL_ZLIB - #endif - #endif - - #include - - enum{false, true}; -#else - #include - #include - - #include - #include - #include - #include - - #ifndef __declspec - #define __declspec(mode) - #endif - - typedef enum{false, true} boolean; -//#define _inline inline -#endif -typedef unsigned char qbyte; -#include - -#if defined(_M_IX86) || defined(__i386__) -//#define QCJIT -#endif - -#define DLL_PROG -#ifndef PROGSUSED -#define PROGSUSED -#endif - -extern int maxedicts; -extern int maxprogs; -extern int hunksize; - -#include "progtype.h" -#include "progslib.h" - -//extern progfuncs_t *progfuncs; - -#define prinst progfuncs->prinst -#define externs progfuncs->parms - -#include "pr_comp.h" - -#include "qcd.h" - -typedef struct -{ - int targetflags; //weather we need to mark the progs as a newer version - char *name; - char *opname; - int priority; - enum {ASSOC_LEFT, ASSOC_RIGHT, ASSOC_RIGHT_RESULT} associative; - struct QCC_type_s **type_a, **type_b, **type_c; -} QCC_opcode_t; -extern QCC_opcode_t pr_opcodes[]; // sized by initialization - - - - -#ifdef _MSC_VER -#define Q_vsnprintf _vsnprintf -#else -#define Q_vsnprintf vsnprintf -#endif - - -#define sv_num_edicts (*externs->sv_num_edicts) -#define sv_edicts (*externs->sv_edicts) - -#define printf externs->printf -#define Sys_Error externs->Sys_Error -#define Abort externs->Abort - -#define memalloc externs->memalloc -#define memfree externs->memfree - -int PRHunkMark(progfuncs_t *progfuncs); -void PRHunkFree(progfuncs_t *progfuncs, int mark); -void *PRHunkAlloc(progfuncs_t *progfuncs, int size); -void *PRAddressableAlloc(progfuncs_t *progfuncs, int ammount); - -#ifdef printf -#undef LIKEPRINTF -#define LIKEPRINTF(x) -#endif - -//void *HunkAlloc (int size); -char *VARGS qcva (char *text, ...) LIKEPRINTF(1); -void QC_InitShares(progfuncs_t *progfuncs); -void QC_StartShares(progfuncs_t *progfuncs); -void QC_AddSharedVar(progfuncs_t *progfuncs, int num, int type); -void QC_AddSharedFieldVar(progfuncs_t *progfuncs, int num, char *stringtable); -int QC_RegisterFieldVar(progfuncs_t *progfuncs, unsigned int type, char *name, int requestedpos, int originalofs); -pbool Decompile(progfuncs_t *progfuncs, char *fname); -int PR_ToggleBreakpoint(progfuncs_t *progfuncs, char *filename, int linenum, int flag); -void StripExtension (char *path); - - -#define edvars(ed) (((edictrun_t*)ed)->fields) //pointer to the field vars, given an edict - - -void SetEndian(void); -extern short (*PRBigShort) (short l); -extern short (*PRLittleShort) (short l); -extern int (*PRBigLong) (int l); -extern int (*PRLittleLong) (int l); -extern float (*PRBigFloat) (float l); -extern float (*PRLittleFloat) (float l); - - - -/* -#ifndef COMPILER -typedef union eval_s -{ - string_t string; - float _float; - float vector[3]; - func_t function; - int _int; - int edict; - progsnum_t prog; //so it can easily be changed -} eval_t; -#endif -*/ - -typedef struct edictrun_s -{ - pbool isfree; - - float freetime; // realtime when the object was freed - unsigned int entnum; - pbool readonly; //causes error when QC tries writing to it. (quake's world entity) - void *fields; - -// other fields from progs come immediately after -} edictrun_t; - - -int Comp_Begin(progfuncs_t *progfuncs, int nump, char **parms); -int Comp_Continue(progfuncs_t *progfuncs); - -char *EvaluateDebugString(progfuncs_t *progfuncs, char *key); -char *SaveEnts(progfuncs_t *progfuncs, char *mem, int *size, int mode); -int LoadEnts(progfuncs_t *progfuncs, char *file, float killonspawnflags); -char *SaveEnt (progfuncs_t *progfuncs, char *buf, int *size, struct edict_s *ed); -struct edict_s *RestoreEnt (progfuncs_t *progfuncs, char *buf, int *size, struct edict_s *ed); -char *PF_VarString (int first); -void PR_StackTrace (progfuncs_t *progfuncs); - -extern int noextensions; - -#ifndef COMPILER -typedef struct progstate_s -{ - dprograms_t *progs; - dfunction_t *functions; - char *strings; - union { - ddefXX_t *globaldefs; - ddef16_t *globaldefs16; - ddef32_t *globaldefs32; - }; - union { - ddefXX_t *fielddefs; - ddef16_t *fielddefs16; - ddef32_t *fielddefs32; - }; - void *statements; -// void *global_struct; - float *globals; // same as pr_global_struct - - typeinfo_t *types; - - int edict_size; // in bytes - - char filename[128]; - - builtin_t *builtins; - int numbuiltins; - - int *linenums; //debug versions only - - int intsize; //16 for standard (more limiting) versions -} progstate_t; - -typedef struct extensionbuiltin_s { - char *name; - builtin_t func; - struct extensionbuiltin_s *prev; -} extensionbuiltin_t; - -//============================================================================ - - -#define pr_progs current_progstate->progs -#define pr_functions current_progstate->functions -#define pr_strings current_progstate->strings -#define pr_globaldefs16 ((ddef16_t*)current_progstate->globaldefs) -#define pr_globaldefs32 ((ddef32_t*)current_progstate->globaldefs) -#define pr_fielddefs16 ((ddef16_t*)current_progstate->fielddefs) -#define pr_fielddefs32 ((ddef32_t*)current_progstate->fielddefs) -#define pr_statements16 ((dstatement16_t*)current_progstate->statements) -#define pr_statements32 ((dstatement32_t*)current_progstate->statements) -//#define pr_global_struct current_progstate->global_struct -#define pr_globals current_progstate->globals -#define pr_linenums current_progstate->linenums -#define pr_types current_progstate->types - - - -//============================================================================ - -void PR_Init (void); - -void PR_ExecuteProgram (progfuncs_t *progfuncs, func_t fnum); -int PR_LoadProgs(progfuncs_t *progfncs, char *s, int headercrc, builtin_t *builtins, int numbuiltins); -int PR_ReallyLoadProgs (progfuncs_t *progfuncs, char *filename, int headercrc, progstate_t *progstate, pbool complain); - -void *PRHunkAlloc(progfuncs_t *progfuncs, int ammount); - -void PR_Profile_f (void); - -struct edict_s *ED_Alloc (progfuncs_t *progfuncs); -void ED_Free (progfuncs_t *progfuncs, struct edict_s *ed); - -char *ED_NewString (progfuncs_t *progfuncs, char *string, int minlength); -// returns a copy of the string allocated from the server's string heap - -void ED_Print (progfuncs_t *progfuncs, struct edict_s *ed); -//void ED_Write (FILE *f, edictrun_t *ed); -char *ED_ParseEdict (progfuncs_t *progfuncs, char *data, edictrun_t *ent); - -//void ED_WriteGlobals (FILE *f); -void ED_ParseGlobals (char *data); - -//void ED_LoadFromFile (char *data); - -//define EDICT_NUM(n) ((edict_t *)(sv.edicts+ (n)*pr_edict_size)) -//define NUM_FOR_EDICT(e) (((byte *)(e) - sv.edicts)/pr_edict_size) - -struct edict_s *EDICT_NUM(progfuncs_t *progfuncs, unsigned int n); -unsigned int NUM_FOR_EDICT(progfuncs_t *progfuncs, struct edict_s *e); - -//#define NEXT_EDICT(e) ((edictrun_t *)( (byte *)e + pr_edict_size)) - -#define EDICT_TO_PROG(pf, e) (((edictrun_t*)e)->entnum) -#define PROG_TO_EDICT(pf, e) ((struct edictrun_s *)prinst->edicttable[e]) - -//============================================================================ - -#define G_FLOAT(o) (pr_globals[o]) -#define G_FLOAT2(o) (pr_globals[OFS_PARM0 + o*3]) -#define G_INT(o) (*(int *)&pr_globals[o]) -#define G_EDICT(o) ((edict_t *)((qbyte *)sv_edicts+ *(int *)&pr_globals[o])) -#define G_EDICTNUM(o) NUM_FOR_EDICT(G_EDICT(o)) -#define G_VECTOR(o) (&pr_globals[o]) -#define G_STRING(o) (*(string_t *)&pr_globals[o]) -#define G_STRING2(o) ((char*)*(string_t *)&pr_globals[o]) -#define GQ_STRING(o) (*(QCC_string_t *)&pr_globals[o]) -#define GQ_STRING2(o) ((char*)*(QCC_string_t *)&pr_globals[o]) -#define G_FUNCTION(o) (*(func_t *)&pr_globals[o]) -#define G_PROG(o) (*(progsnum_t *)&pr_globals[o]) //simply so it's nice and easy to change... - -#define RETURN_EDICT(e) (((int *)pr_globals)[OFS_RETURN] = EDICT_TO_PROG(e)) - -#define E_FLOAT(e,o) (((float*)&e->v)[o]) -#define E_INT(e,o) (*(int *)&((float*)&e->v)[o]) -#define E_VECTOR(e,o) (&((float*)&e->v)[o]) -#define E_STRING(e,o) (*(string_t *)&((float*)(e+1))[o]) - -const extern unsigned int type_size[]; - - -extern unsigned short pr_crc; - -void VARGS PR_RunError (progfuncs_t *progfuncs, char *error, ...) LIKEPRINTF(2); - -void ED_PrintEdicts (progfuncs_t *progfuncs); -void ED_PrintNum (progfuncs_t *progfuncs, int ent); - - -pbool PR_SwitchProgs(progfuncs_t *progfuncs, progsnum_t type); -void PR_MoveParms(progfuncs_t *progfuncs, progsnum_t progs1, progsnum_t progs2); - - - - -eval_t *GetEdictFieldValue(progfuncs_t *progfuncs, struct edict_s *ed, char *name, evalc_t *cache); - -#endif - - - - -#ifndef COMPILER - -//this is windows - all files are written with this endian standard -//optimisation -//leave undefined if in doubt over os. -#ifdef _WIN32 -#define NOENDIAN -#endif - - -typedef struct { - int varofs; - int size; -} sharedvar_t; -typedef struct -{ - int s; - dfunction_t *f; - int progsnum; - int pushed; -} prstack_t; - - - -//pr_multi.c -void PR_SetBuiltins(int type); - -#define var(type, name) type name -#define vars(type, name, size) type name[size] - -typedef struct prinst_s { -#ifdef QCJIT - pbool usejit; -#endif - char **tempstrings; - int maxtempstrings; - int numtempstrings; - int numtempstringsstack; - - char **allocedstrings; - int maxallocedstrings; - int numallocedstrings; - -var(progstate_t *, pr_progstate); -#define pr_progstate prinst->pr_progstate - -var(progsnum_t, pr_typecurrent); -#define pr_typecurrent prinst->pr_typecurrent -var(unsigned int, maxprogs); -#define maxprogs prinst->maxprogs - -var(progstate_t *,current_progstate); -#define current_progstate prinst->current_progstate - -var(unsigned int, numshares); -#define numshares prinst->numshares -var(sharedvar_t *,shares); //shared globals, not including parms -#define shares prinst->shares -var(unsigned int, maxshares); -#define maxshares prinst->maxshares - -var(struct prmemb_s *, memblocks); -#define memb prinst->memblocks - -var(unsigned int, maxfields); -#define maxfields prinst->maxfields -var(unsigned int, numfields); -#define numfields prinst->numfields -var(fdef_t*, field); //biggest size -#define field prinst->field - -int reorganisefields; - - -//pr_exec.c -#define MAX_STACK_DEPTH 64 -vars(prstack_t, pr_stack, MAX_STACK_DEPTH); -#define pr_stack prinst->pr_stack -var(int, pr_depth); -#define pr_depth prinst->pr_depth -var(int, spushed); -#define pr_spushed prinst->spushed - -#define LOCALSTACK_SIZE 4096 -vars(int, localstack, LOCALSTACK_SIZE); -#define localstack prinst->localstack -var(int, localstack_used); -#define localstack_used prinst->localstack_used - -var(int, continuestatement); -var(int, exitdepth); - -var(int, pr_trace); -#define pr_trace prinst->pr_trace -var(dfunction_t *, pr_xfunction); -#define pr_xfunction prinst->pr_xfunction -var(int, pr_xstatement); -#define pr_xstatement prinst->pr_xstatement - -var(int, pr_argc); -#define pr_argc prinst->pr_argc - -//pr_edict.c - -var(unsigned int, maxedicts); -#define maxedicts prinst->maxedicts - -var(evalc_t, spawnflagscache); -#define spawnflagscache prinst->spawnflagscache - - - - -var(unsigned int, fields_size); // in bytes -#define fields_size prinst->fields_size -var(unsigned int, max_fields_size); -#define max_fields_size prinst->max_fields_size - - -//initlib.c -var(char *, addressablehunk); -#define addressablehunk prinst->addressablehunk -var(unsigned int, addressableused); -#define addressableused prinst->addressableused -var(unsigned int, addressablesize); -#define addressablesize prinst->addressablesize - - -//var(extensionbuiltin_t *, extensionbuiltin); -//#define extensionbuiltin prinst->extensionbuiltin - - struct edict_s **edicttable; -} prinst_t; -extern vec3_t vec3_origin; - -eval_t *PR_FindGlobal(progfuncs_t *prfuncs, char *globname, progsnum_t pnum); -ddef16_t *ED_FindTypeGlobalFromProgs16 (progfuncs_t *progfuncs, char *name, progsnum_t prnum, int type); -ddef32_t *ED_FindTypeGlobalFromProgs32 (progfuncs_t *progfuncs, char *name, progsnum_t prnum, int type); -ddef16_t *ED_FindGlobalFromProgs16 (progfuncs_t *progfuncs, char *name, progsnum_t prnum); -ddef32_t *ED_FindGlobalFromProgs32 (progfuncs_t *progfuncs, char *name, progsnum_t prnum); -fdef_t *ED_FindField (progfuncs_t *progfuncs, char *name); -fdef_t *ED_FieldAtOfs (progfuncs_t *progfuncs, unsigned int ofs); -dfunction_t *ED_FindFunction (progfuncs_t *progfuncs, char *name, progsnum_t *pnum, progsnum_t fromprogs); -func_t PR_FindFunc(progfuncs_t *progfncs, char *funcname, progsnum_t pnum); -void PR_Configure (progfuncs_t *progfncs, int addressable_size, int max_progs); -int PR_InitEnts(progfuncs_t *progfncs, int maxents); -char *PR_ValueString (progfuncs_t *progfuncs, etype_t type, eval_t *val); -void QC_ClearEdict (progfuncs_t *progfuncs, struct edict_s *ed); -void PRAddressableFlush(progfuncs_t *progfuncs, int totalammount); -void QC_FlushProgsOffsets(progfuncs_t *progfuncs); - -ddef16_t *ED_GlobalAtOfs16 (progfuncs_t *progfuncs, int ofs); -ddef16_t *ED_FindGlobal16 (progfuncs_t *progfuncs, char *name); -ddef32_t *ED_FindGlobal32 (progfuncs_t *progfuncs, char *name); -ddef32_t *ED_GlobalAtOfs32 (progfuncs_t *progfuncs, unsigned int ofs); - -string_t PR_StringToProgs (progfuncs_t *inst, char *str); -char *PR_StringToNative (progfuncs_t *inst, string_t str); - -void PR_FreeTemps (progfuncs_t *progfuncs, int depth); - -char *PR_GlobalString (progfuncs_t *progfuncs, int ofs); -char *PR_GlobalStringNoContents (progfuncs_t *progfuncs, int ofs); - -pbool CompileFile(progfuncs_t *progfuncs, char *filename); - -pbool PR_GenerateJit(progfuncs_t *progfuncs); -void PR_EnterJIT(progfuncs_t *progfuncs, int statement); - -char *QCC_COM_Parse (char *data); -extern char qcc_token[1024]; -#endif diff --git a/misc/mediasource/extra/fteqcc-src/progslib.h b/misc/mediasource/extra/fteqcc-src/progslib.h deleted file mode 100644 index f3f4488a..00000000 --- a/misc/mediasource/extra/fteqcc-src/progslib.h +++ /dev/null @@ -1,321 +0,0 @@ - -#ifndef PROGSLIB_H -#define PROGSLIB_H -/*#define true 1 -#define false 0 - -#define PITCH 0 -#define YAW 1 -#define ROLL 2 - -typedef char bool; -//typedef float vec3_t[3]; -typedef int progsnum_t; -typedef int func_t; -#ifndef COMPILER -typedef char *string_t; -#endif -//typedef struct globalvars_s globalvars_t; -//typedef struct edict_s edict_t; -#define globalvars_t void -#define edict_t void -*/ - -#ifdef _MSC_VER - #define VARGS __cdecl -#endif -#if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) - #define LIKEPRINTF(x) __attribute__((format(printf,x,x+1))) -#endif -#ifndef LIKEPRINTF - #define LIKEPRINTF(x) -#endif -#ifndef VARGS - #define VARGS -#endif - - -struct edict_s; -struct entvars_s; -struct globalvars_s; -struct qcthread_s; -typedef struct progfuncs_s progfuncs_t; -typedef void (*builtin_t) (progfuncs_t *prinst, struct globalvars_s *gvars); - -//used by progs engine. All nulls is reset. -typedef struct { - char *varname; - struct fdef_s *ofs32; - - int spare[2]; -} evalc_t; -#define sizeofevalc sizeof(evalc_t) -typedef enum {ev_void, ev_string, ev_float, ev_vector, ev_entity, ev_field, ev_function, ev_pointer, ev_integer, ev_variant, ev_struct, ev_union} etype_t; - -//the number of pointers to variables (as opposed to functions - those are fine) in these structures is excessive. -//Many of the functions are also obsolete. -struct progfuncs_s { - int progsversion; //PROGSTRUCT_VERSION - - - void (*Configure) (progfuncs_t *prinst, int addressablesize, int max_progs); //configure buffers and memory. Used to reset and must be called first. Flushes a running VM. - progsnum_t (*LoadProgs) (progfuncs_t *prinst, char *s, int headercrc, builtin_t *builtins, int numbuiltins); //load a progs - int (*InitEnts) (progfuncs_t *prinst, int max_ents); //returns size of edicts for use with nextedict macro - void (*ExecuteProgram) (progfuncs_t *prinst, func_t fnum); //start execution - pbool (*SwitchProgs) (progfuncs_t *prinst, progsnum_t num); //switch to a different progs - this should be obsolete. - struct globalvars_s *(*globals) (progfuncs_t *prinst, progsnum_t num); //get the globals of a progs - struct entvars_s *(*entvars) (progfuncs_t *prinst, struct edict_s *ent); //return a pointer to the entvars of an ent. can be achieved via the edict_t structure instead, so obsolete. - - void (VARGS *RunError) (progfuncs_t *prinst, char *msg, ...) LIKEPRINTF(2); //builtins call this to say there was a problem - void (*PrintEdict) (progfuncs_t *prinst, struct edict_s *ed); //get a listing of all vars on an edict (sent back via 'print') - - struct edict_s *(*EntAlloc) (progfuncs_t *prinst); - void (*EntFree) (progfuncs_t *prinst, struct edict_s *ed); - - struct edict_s *(*EDICT_NUM) (progfuncs_t *prinst, unsigned int n); //get the nth edict - unsigned int (*NUM_FOR_EDICT) (progfuncs_t *prinst, struct edict_s *e); //so you can find out what that 'n' will be - - void (*SetGlobalEdict) (progfuncs_t *prinst, struct edict_s *ed, int ofs); //set a global to an edict (partially obsolete) - - char *(*VarString) (progfuncs_t *prinst, int first); //returns a string made up of multiple arguments - - struct progstate_s **progstate; //internal to the library. - - func_t (*FindFunction) (progfuncs_t *prinst, char *funcname, progsnum_t num); - - int (*StartCompile) (progfuncs_t *prinst, int argv, char **argc); //1 if can compile, 0 if failed to compile - int (*ContinueCompile) (progfuncs_t *prinst); //2 if finished, 1 if more to go, 0 if failed - - char *(*filefromprogs) (progfuncs_t *prinst, progsnum_t prnum, char *fname, int *size, char *buffer); //reveals encoded/added files from already loaded progs - char *(*filefromnewprogs) (progfuncs_t *prinst, char *prname, char *fname, int *size, char *buffer); //reveals encoded/added files from a progs on the disk somewhere - - char *(*save_ents) (progfuncs_t *prinst, char *buf, int *size, int mode); //dump the entire progs info into one big self allocated string - int (*load_ents) (progfuncs_t *prinst, char *s, float killonspawnflags); //restore the entire progs state (or just add some more ents) (returns edicts ize) - - char *(*saveent) (progfuncs_t *prinst, char *buf, int *size, struct edict_s *ed); //will save just one entities vars - struct edict_s *(*restoreent) (progfuncs_t *prinst, char *buf, int *size, struct edict_s *ed); //will restore the entity that had it's values saved (can use NULL for ed) - - union eval_s *(*FindGlobal) (progfuncs_t *prinst, char *name, progsnum_t num); //find a pointer to the globals value - char *(*AddString) (progfuncs_t *prinst, char *val, int minlength); //dump a string into the progs memory (for setting globals and whatnot) - void *(*Tempmem) (progfuncs_t *prinst, int ammount, char *whatfor); //grab some mem for as long as the progs stays loaded - - union eval_s *(*GetEdictFieldValue) (progfuncs_t *prinst, struct edict_s *ent, char *name, evalc_t *s); //get an entityvar (cache it) and return the possible values - struct edict_s *(*ProgsToEdict) (progfuncs_t *prinst, int progs); //edicts are stored as ints and need to be adjusted - int (*EdictToProgs) (progfuncs_t *prinst, struct edict_s *ed); //edicts are stored as ints and need to be adjusted - - char *(*EvaluateDebugString) (progfuncs_t *prinst, char *key); //evaluate a string and return it's value (according to current progs) (expands edict vars) - - int *pr_trace; //start calling the editor for each line executed - - void (*StackTrace) (progfuncs_t *prinst); - - int (*ToggleBreak) (progfuncs_t *prinst, char *filename, int linenum, int mode); - - int numprogs; - - struct progexterns_s *parms; //these are the initial parms, they may be changed - - pbool (*Decompile) (progfuncs_t *prinst, char *fname); - - - struct prinst_s *prinst; //internal variables. Leave alone. - - int *callargc; //number of args of built-in call - void (*RegisterBuiltin) (progfuncs_t *prinst, char *, builtin_t); - - char *stringtable; //qc strings are all relative. add to a qc string. this is required for support of frikqcc progs that strip string immediates. - int fieldadjust; //FrikQCC style arrays can cause problems due to field remapping. This causes us to leave gaps but offsets identical. - - struct qcthread_s *(*Fork) (progfuncs_t *prinst); //returns a pointer to a thread which can be resumed via RunThread. - void (*RunThread) (progfuncs_t *prinst, struct qcthread_s *thread); - void (*AbortStack) (progfuncs_t *prinst); //annigilates the current stack, positioning on a return statement. It is expected that this is only used via a builtin! - - int lastcalledbuiltinnumber; //useful with non-implemented opcodes. - - int (*RegisterFieldVar) (progfuncs_t *prinst, unsigned int type, char *name, int requestedpos, int originalofs); - - char *tempstringbase; //for engine's use. Store your base tempstring pointer here. - int tempstringnum; //for engine's use. - - string_t (*TempString) (progfuncs_t *prinst, char *str); - - string_t (*StringToProgs) (progfuncs_t *prinst, char *str); - char *(*StringToNative) (progfuncs_t *prinst, string_t str); - int stringtablesize; - - int (*QueryField) (progfuncs_t *prinst, unsigned int fieldoffset, etype_t *type, char **name, evalc_t *fieldcache); //find info on a field definition at an offset - - void (*EntClear) (progfuncs_t *progfuncs, struct edict_s *e); -}; - -typedef struct progexterns_s { - int progsversion; //PROGSTRUCT_VERSION - - unsigned char *(*ReadFile) (char *fname, void *buffer, int len); - int (*FileSize) (char *fname); //-1 if file does not exist - pbool (*WriteFile) (char *name, void *data, int len); - int (VARGS *printf) (const char *, ...) LIKEPRINTF(1); - void (VARGS *Sys_Error) (const char *, ...) LIKEPRINTF(1); - void (VARGS *Abort) (char *, ...) LIKEPRINTF(1); - int edictsize; //size of edict_t - - void (*entspawn) (struct edict_s *ent, int loading); //ent has been spawned, but may not have all the extra variables (that may need to be set) set - pbool (*entcanfree) (struct edict_s *ent); //return true to stop ent from being freed - void (*stateop) (progfuncs_t *prinst, float var, func_t func); //what to do on qc's state opcode. - void (*cstateop) (progfuncs_t *prinst, float vara, float varb, func_t currentfunc); //a hexen2 opcode. - void (*cwstateop) (progfuncs_t *prinst, float vara, float varb, func_t currentfunc); //a hexen2 opcode. - void (*thinktimeop) (progfuncs_t *prinst, struct edict_s *ent, float varb); //a hexen2 opcode. - - - //used when loading a game - builtin_t *(*builtinsfor) (int num, int headercrc); //must return a pointer to the builtins that were used before the state was saved. - void (*loadcompleate) (int edictsize); //notification to reset any pointers. - - void *(VARGS *memalloc) (int size); //small string allocation malloced and freed randomly by the executor. (use malloc if you want) - void (VARGS *memfree) (void * mem); - - - builtin_t *globalbuiltins; //these are available to all progs - int numglobalbuiltins; - - enum {PR_NOCOMPILE, PR_COMPILENEXIST, PR_COMPILEEXISTANDCHANGED, PR_COMPILECHANGED, PR_COMPILEALWAYS, PR_COMPILEIGNORE} autocompile; - - double *gametime; //used to prevent the vm from reusing an entity faster than 2 secs. - - struct edict_s **sv_edicts; //pointer to the engine's reference to world. - unsigned int *sv_num_edicts; //pointer to the engine's edict count. - - int (*useeditor) (progfuncs_t *prinst, char *filename, int line, int nump, char **parms); //called on syntax errors or step-by-step debugging. -} progparms_t, progexterns_t; - -//FIXMEs -void QC_AddSharedVar(progfuncs_t *progfuncs, int start, int size); -void QC_AddSharedFieldVar(progfuncs_t *progfuncs, int num, char *relstringtable); -void ED_Print(progfuncs_t *progfuncs, struct edict_s *ed); -char *PR_RemoveProgsString(progfuncs_t *progfuncs, string_t str); -int PR_GetFuncArgCount(progfuncs_t *progfuncs, func_t func); - -#if defined(QCLIBDLL_EXPORTS) -__declspec(dllexport) -#endif -progfuncs_t * InitProgs(progparms_t *ext); -#if defined(QCLIBDLL_EXPORTS) -__declspec(dllexport) -#endif -void CloseProgs(progfuncs_t *inst); - -#ifndef COMPILER -typedef union eval_s -{ - string_t string; - float _float; - float _vector[3]; - func_t function; - int _int; - int edict; - progsnum_t prog; //so it can easily be changed -} eval_t; -#endif - -#define PR_CURRENT -1 -#define PR_ANY -2 //not always valid. Use for finding funcs -#define PR_ANYBACK -3 -#define PROGSTRUCT_VERSION 2 - - -#ifndef DLL_PROG -#define PR_Configure(pf, memsize, max_progs) (*pf->Configure) (pf, memsize, max_progs) -#define PR_LoadProgs(pf, s, headercrc, builtins, numb) (*pf->LoadProgs) (pf, s, headercrc, builtins, numb) -#define PR_InitEnts(pf, maxents) (*pf->InitEnts) (pf, maxents) -#define PR_ExecuteProgram(pf, fnum) (*pf->ExecuteProgram) (pf, fnum) -#define PR_SwitchProgs(pf, num) (*pf->SwitchProgs) (pf, num) -#define PR_globals(pf, num) (*pf->globals) (pf, num) -#define PR_entvars(pf, ent) (*pf->entvars) (pf, ent) - -#define PR_RegisterFieldVar(pf,type,name,reqofs,qcofs) (*pf->RegisterFieldVar) (pf,type,name,reqofs,qcofs) - -#define ED_Alloc(pf) (*pf->EntAlloc) (pf) -#define ED_Free(pf, ed) (*pf->EntFree) (pf, ed) -#define ED_Clear(pf, ed) (*pf->EntClear) (pf, ed) - -#define PR_LoadEnts(pf, s, kf) (*pf->load_ents) (pf, s, kf) -#define PR_SaveEnts(pf, buf, size, mode) (*pf->save_ents) (pf, buf, size, mode) - -#define EDICT_NUM(pf, num) (*pf->EDICT_NUM) (pf, num) -#define NUM_FOR_EDICT(pf, e) (*pf->NUM_FOR_EDICT) (pf, e) -#define SetGlobalEdict(pf, ed, ofs) (*pf->SetGlobalEdict) (pf, ed, ofs) -#define PR_VarString(pf,first) (*pf->VarString) (pf,first) - -#define PR_StartCompile(pf,argc,argv) (*pf->StartCompile) (pf,argc,argv) -#define PR_ContinueCompile(pf) (*pf->ContinueCompile) (pf) - -#define PR_StackTrace(pf) (*pf->StackTrace) (pf) -#define PR_AbortStack(pf) (*pf->AbortStack) (pf) - -#define PR_RunError(pf,str) (*pf->RunError) (pf,str) - -#define PR_PrintEdict(pf,ed) (*pf->PrintEdict) (pf, ed) - -#define PR_FindFunction(pf, name, num) (*pf->FindFunction) (pf, name, num) -#define PR_FindGlobal(pf, name, progs) (*pf->FindGlobal) (pf, name, progs) -#define PR_AddString(pf, ed, len) (*pf->AddString) (pf, ed, len) -#define PR_Alloc(pf,size) (*pf->Tempmem) (pf, size) - -#define PROG_TO_EDICT(pf, ed) (*pf->ProgsToEdict) (pf, ed) -#define EDICT_TO_PROG(pf, ed) (*pf->EdictToProgs) (pf, (struct edict_s*)ed) - -#define PR_RegisterBuiltin(pf, name, func) (*pf->RegisterBuiltin) (pf, name, func) - -#define PR_GetString(pf,s) (*pf->StringToNative) (pf, s) -#define PR_GetStringOfs(pf,o) (*pf->StringToNative) (pf, G_INT(o)) -#define PR_SetString(pf, s) (*pf->StringToProgs) (pf, s) - -#define NEXT_EDICT(pf,o) EDICT_NUM(pf, NUM_FOR_EDICT(pf, o)+1) -#define RETURN_EDICT(pf, e) (((int *)pr_globals)[OFS_RETURN] = EDICT_TO_PROG(pf, e)) - - -//builtin funcs (which operate on globals) -//To use these outside of builtins, you will likly have to use the 'globals' method. -#define G_FLOAT(o) (((float *)pr_globals)[o]) -#define G_FLOAT2(o) (((float *)pr_globals)[OFS_PARM0 + o*3]) -#define G_INT(o) (((int *)pr_globals)[o]) -#define G_EDICT(pf, o) PROG_TO_EDICT(pf, G_INT(o)) //((edict_t *)((char *) sv.edicts+ *(int *)&((float *)pr_globals)[o])) -#define G_EDICTNUM(pf, o) NUM_FOR_EDICT(pf, G_EDICT(pf, o)) -#define G_VECTOR(o) (&((float *)pr_globals)[o]) -#define G_FUNCTION(o) (*(func_t *)&((float *)pr_globals)[o]) - -/* -#define PR_GetString(p,s) (s?s + p->stringtable:"") -#define PR_GetStringOfs(p,o) (G_INT(o)?G_INT(o) + p->stringtable:"") -#define PR_SetStringOfs(p,o,s) (G_INT(o) = s - p->stringtable) -*/ -//#define PR_SetString(p, s) ((s&&*s)?(s - p->stringtable):0) -#define PR_NewString(p, s, l) PR_SetString(p, PR_AddString(p, s, l)) -/**/ - -#define ev_prog ev_integer - -#define E_STRING(o) (char *)(((int *)((char *)ed) + progparms.edictsize)[o]) - -//#define pr_global_struct pr_globals - -#endif - - -#define OFS_NULL 0 -#define OFS_RETURN 1 -#define OFS_PARM0 4 // leave 3 ofs for each parm to hold vectors -#define OFS_PARM1 7 -#define OFS_PARM2 10 -#define OFS_PARM3 13 -#define OFS_PARM4 16 -#define OFS_PARM5 19 -#define OFS_PARM6 22 -#define OFS_PARM7 25 -#define RESERVED_OFS 28 - - -#undef edict_t -#undef globalvars_t - -#endif //PROGSLIB_H diff --git a/misc/mediasource/extra/fteqcc-src/progtype.h b/misc/mediasource/extra/fteqcc-src/progtype.h deleted file mode 100644 index ab120154..00000000 --- a/misc/mediasource/extra/fteqcc-src/progtype.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef QCLIB_PROGTYPE_H -#define QCLIB_PROGTYPE_H - -#ifndef DLL_PROG - -#else -typedef float vec_t; -typedef vec_t vec3_t[3]; -#endif - -#ifndef t_bool -#define t_bool -typedef int pbool; - -#else -#define t_bool -#endif -typedef int progsnum_t; -typedef int func_t; -typedef int string_t; - -#endif /* QCLIB_PROGTYPE_H */ - diff --git a/misc/mediasource/extra/fteqcc-src/qcc.dsp b/misc/mediasource/extra/fteqcc-src/qcc.dsp deleted file mode 100644 index f5af89c8..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcc.dsp +++ /dev/null @@ -1,256 +0,0 @@ -# Microsoft Developer Studio Project File - Name="qcc" - Package Owner=<4> -# Microsoft Developer Studio Generated Build File, Format Version 6.00 -# ** DO NOT EDIT ** - -# TARGTYPE "Win32 (x86) Console Application" 0x0103 - -CFG=qcc - Win32 GUIDebug -!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 "qcc.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 "qcc.mak" CFG="qcc - Win32 GUIDebug" -!MESSAGE -!MESSAGE Possible choices for configuration are: -!MESSAGE -!MESSAGE "qcc - Win32 Release" (based on "Win32 (x86) Console Application") -!MESSAGE "qcc - Win32 Debug" (based on "Win32 (x86) Console Application") -!MESSAGE "qcc - Win32 GUIDebug" (based on "Win32 (x86) Console Application") -!MESSAGE "qcc - Win32 GUIRelease" (based on "Win32 (x86) Console Application") -!MESSAGE - -# Begin Project -# PROP AllowPerConfigDependencies 0 -# PROP Scc_ProjName "" -# PROP Scc_LocalPath "" -CPP=cl.exe -RSC=rc.exe - -!IF "$(CFG)" == "qcc - 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 "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "QCCONLY" /YX /FD /c -# ADD BASE RSC /l 0x809 /d "NDEBUG" -# ADD RSC /l 0x809 /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 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 ../libs/zlib.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 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 /out:"../../fteqcc.exe" - -!ELSEIF "$(CFG)" == "qcc - 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 "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "QCCONLY" /FR /YX /FD /GZ /c -# ADD BASE RSC /l 0x809 /d "_DEBUG" -# ADD RSC /l 0x809 /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 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 ..\libs\zlib.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 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 /out:"../../fteqcc_dbg.exe" /pdbtype:sept - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIDebug" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 1 -# PROP BASE Output_Dir "qcc___Win32_GUIDebug" -# PROP BASE Intermediate_Dir "qcc___Win32_GUIDebug" -# PROP BASE Ignore_Export_Lib 0 -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 1 -# PROP Output_Dir "qcc___Win32_GUIDebug" -# PROP Intermediate_Dir "qcc___Win32_GUIDebug" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "QCCONLY" /FR /YX /FD /GZ /c -# ADD CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS" /D "QCCONLY" /FR /YX /FD /GZ /c -# ADD BASE RSC /l 0x809 /d "_DEBUG" -# ADD RSC /l 0x809 /d "_DEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 ..\libs\zlib.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 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 /out:"../../../fteqcc.exe" /pdbtype:sept -# ADD LINK32 ..\libs\zlib.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 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib comdlg32.lib /nologo /subsystem:windows /debug /machine:I386 /out:"..\..\fteqcc.exe" /pdbtype:sept -# SUBTRACT LINK32 /pdb:none - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIRelease" - -# PROP BASE Use_MFC 0 -# PROP BASE Use_Debug_Libraries 0 -# PROP BASE Output_Dir "qcc___Win32_GUIRelease0" -# PROP BASE Intermediate_Dir "qcc___Win32_GUIRelease0" -# PROP BASE Ignore_Export_Lib 0 -# PROP BASE Target_Dir "" -# PROP Use_MFC 0 -# PROP Use_Debug_Libraries 0 -# PROP Output_Dir "qcc___Win32_GUIRelease0" -# PROP Intermediate_Dir "qcc___Win32_GUIRelease0" -# PROP Ignore_Export_Lib 0 -# PROP Target_Dir "" -# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "QCCONLY" /YX /FD /c -# ADD CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D "QCCONLY" /FR /YX /FD /c -# ADD BASE RSC /l 0x809 /d "NDEBUG" -# ADD RSC /l 0x809 /d "NDEBUG" -BSC32=bscmake.exe -# ADD BASE BSC32 /nologo -# ADD BSC32 /nologo -LINK32=link.exe -# ADD BASE LINK32 ../libs/zlib.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 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 /out:"../../../fteqcc.exe" -# ADD LINK32 ../libs/zlib.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 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib comctl32.lib /nologo /subsystem:windows /machine:I386 /out:"../../fteqccgui.exe" -# SUBTRACT LINK32 /pdb:none - -!ENDIF - -# Begin Target - -# Name "qcc - Win32 Release" -# Name "qcc - Win32 Debug" -# Name "qcc - Win32 GUIDebug" -# Name "qcc - Win32 GUIRelease" -# Begin Group "Source Files" - -# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat" -# Begin Source File - -SOURCE=.\Comprout.c -# End Source File -# Begin Source File - -SOURCE=.\hash.c -# End Source File -# Begin Source File - -SOURCE=.\qcc_cmdlib.c -# End Source File -# Begin Source File - -SOURCE=.\qcc_gtk.c -# PROP Exclude_From_Build 1 -# End Source File -# Begin Source File - -SOURCE=.\qcc_pr_comp.c -# End Source File -# Begin Source File - -SOURCE=.\qcc_pr_lex.c -# End Source File -# Begin Source File - -SOURCE=.\qccgui.c - -!IF "$(CFG)" == "qcc - Win32 Release" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "qcc - Win32 Debug" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIDebug" - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIRelease" - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\qccguistuff.c - -!IF "$(CFG)" == "qcc - Win32 Release" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "qcc - Win32 Debug" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIDebug" - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIRelease" - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\QccMain.c -# End Source File -# Begin Source File - -SOURCE=.\qcctui.c - -!IF "$(CFG)" == "qcc - Win32 Release" - -!ELSEIF "$(CFG)" == "qcc - Win32 Debug" - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIDebug" - -# PROP Exclude_From_Build 1 - -!ELSEIF "$(CFG)" == "qcc - Win32 GUIRelease" - -# PROP Exclude_From_Build 1 - -!ENDIF - -# End Source File -# Begin Source File - -SOURCE=.\qcd_main.c -# End Source File -# End Group -# Begin Group "Header Files" - -# PROP Default_Filter "h;hpp;hxx;hm;inl" -# Begin Source File - -SOURCE=.\gui.h -# End Source File -# Begin Source File - -SOURCE=.\pr_comp.h -# End Source File -# Begin Source File - -SOURCE=.\qcc.h -# End Source File -# End Group -# Begin Group "Resource Files" - -# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe" -# End Group -# End Target -# End Project diff --git a/misc/mediasource/extra/fteqcc-src/qcc.h b/misc/mediasource/extra/fteqcc-src/qcc.h deleted file mode 100644 index e71ad165..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcc.h +++ /dev/null @@ -1,906 +0,0 @@ -#define COMPILER -#define PROGSUSED - -//#define COMMONINLINES -//#define inline _inline - -#include "cmdlib.h" -#include -/* -#include -#include - - -#include "pr_comp.h" -*/ - -//this is for testing -#define WRITEASM - -#ifdef __MINGW32_VERSION -#define MINGW -#endif - -#define progfuncs qccprogfuncs -extern progfuncs_t *qccprogfuncs; - -#ifndef _WIN32 -#define stricmp strcasecmp -#define strnicmp strncasecmp -#endif - -void *qccHunkAlloc(size_t mem); -void qccClearHunk(void); - -extern short (*PRBigShort) (short l); -extern short (*PRLittleShort) (short l); -extern int (*PRBigLong) (int l); -extern int (*PRLittleLong) (int l); -extern float (*PRBigFloat) (float l); -extern float (*PRLittleFloat) (float l); - - -#define MAX_ERRORS 10 - -#define MAX_NAME 64 // chars long - -extern unsigned int MAX_REGS; - -extern int MAX_STRINGS; -extern int MAX_GLOBALS; -extern int MAX_FIELDS; -extern int MAX_STATEMENTS; -extern int MAX_FUNCTIONS; - -#define MAX_SOUNDS 1024 //convert to int? -#define MAX_TEXTURES 1024 //convert to int? -#define MAX_MODELS 1024 //convert to int? -#define MAX_FILES 1024 //convert to int? -#define MAX_DATA_PATH 64 - -extern int MAX_CONSTANTS; -#define MAXCONSTANTLENGTH 64 -#define MAXCONSTANTVALUELENGTH 1024 -#define MAXCONSTANTPARAMLENGTH 32 -#define MAXCONSTANTPARAMS 32 - -typedef enum {QCF_STANDARD, QCF_HEXEN2, QCF_DARKPLACES, QCF_FTE, QCF_FTEDEBUG, QCF_KK7} qcc_targetformat_t; -extern qcc_targetformat_t qcc_targetformat; - - -/* - -TODO: - -"stopped at 10 errors" - -other pointer types for models and clients? - -compact string heap? - -always initialize all variables to something safe - -the def->type->type arrangement is really silly. - -return type checking - -parm count type checking - -immediate overflow checking - -pass the first two parms in call->b and call->c - -*/ - -/* - -comments --------- -// comments discard text until the end of line -/ * * / comments discard all enclosed text (spaced out on this line because this documentation is in a regular C comment block, and typing them in normally causes a parse error) - -code structure --------------- -A definition is: - [ = ] {, [ = ] }; - - -types ------ -simple types: void, float, vector, string, or entity - float width, height; - string name; - entity self, other; - -vector types: - vector org; // also creates org_x, org_y, and org_z float defs - - -A function type is specified as: simpletype ( type name {,type name} ) -The names are ignored except when the function is initialized. - void() think; - entity() FindTarget; - void(vector destination, float speed, void() callback) SUB_CalcMove; - void(...) dprint; // variable argument builtin - -A field type is specified as: .type - .vector origin; - .string netname; - .void() think, touch, use; - - -names ------ -Names are a maximum of 64 characters, must begin with A-Z,a-z, or _, and can continue with those characters or 0-9. - -There are two levels of scoping: global, and function. The parameter list of a function and any vars declared inside a function with the "local" statement are only visible within that function, - - -immediates ----------- -Float immediates must begin with 0-9 or minus sign. .5 is illegal. - -A parsing ambiguity is present with negative constants. "a-5" will be parsed as "a", then "-5", causing an error. Seperate the - from the digits with a space "a - 5" to get the proper behavior. - 12 - 1.6 - 0.5 - -100 - -Vector immediates are three float immediates enclosed in single quotes. - '0 0 0' - '20.5 -10 0.00001' - -String immediates are characters enclosed in double quotes. The string cannot contain explicit newlines, but the escape character \n can embed one. The \" escape can be used to include a quote in the string. - "maps/jrwiz1.bsp" - "sound/nin/pain.wav" - "ouch!\n" - -Code immediates are statements enclosed in {} braces. -statement: - { } - ; - local [ = ] {, [ = ] }; - return ; - if ( ) [ else ]; - while ( ) ; - do while ( ); - ( ); - -expression: - combiations of names and these operators with standard C precedence: - "&&", "||", "<=", ">=","==", "!=", "!", "*", "/", "-", "+", "=", ".", "<", ">", "&", "|" - Parenthesis can be used to alter order of operation. - The & and | operations perform integral bit ops on floats - -A built in function immediate is a number sign followed by an integer. - #1 - #12 - - -compilation ------------ -Source files are processed sequentially without dumping any state, so if a defs file is the first one processed, the definitions will be available to all other files. - -The language is strongly typed and there are no casts. - -Anything that is initialized is assumed to be constant, and will have immediates folded into it. If you change the value, your program will malfunction. All uninitialized globals will be saved to savegame files. - -Functions cannot have more than eight parameters. - -Error recovery during compilation is minimal. It will skip to the next global definition, so you will never see more than one error at a time in a given function. All compilation aborts after ten error messages. - -Names can be defined multiple times until they are defined with an initialization, allowing functions to be prototyped before their definition. - -void() MyFunction; // the prototype - -void() MyFunction = // the initialization -{ - dprint ("we're here\n"); -}; - - -entities and fields -------------------- - - -execution ---------- -Code execution is initiated by C code in quake from two main places: the timed think routines for periodic control, and the touch function when two objects impact each other. - -There are three global variables that are set before beginning code execution: - entity world; // the server's world object, which holds all global - // state for the server, like the deathmatch flags - // and the body ques. - entity self; // the entity the function is executing for - entity other; // the other object in an impact, not used for thinks - float time; // the current game time. Note that because the - // entities in the world are simulated sequentially, - // time is NOT strictly increasing. An impact late - // in one entity's time slice may set time higher - // than the think function of the next entity. - // The difference is limited to 0.1 seconds. -Execution is also caused by a few uncommon events, like the addition of a new client to an existing server. - -There is a runnaway counter that stops a program if 100000 statements are executed, assuming it is in an infinite loop. - -It is acceptable to change the system set global variables. This is usually done to pose as another entity by changing self and calling a function. - -The interpretation is fairly efficient, but it is still over an order of magnitude slower than compiled C code. All time consuming operations should be made into built in functions. - -A profile counter is kept for each function, and incremented for each interpreted instruction inside that function. The "profile" console command in Quake will dump out the top 10 functions, then clear all the counters. The "profile all" command will dump sorted stats for every function that has been executed. - - -afunc ( 4, bfunc(1,2,3)); -will fail because there is a shared parameter marshaling area, which will cause the 1 from bfunc to overwrite the 4 already placed in parm0. When a function is called, it copies the parms from the globals into it's privately scoped variables, so there is no collision when calling another function. - -total = factorial(3) + factorial(4); -Will fail because the return value from functions is held in a single global area. If this really gets on your nerves, tell me and I can work around it at a slight performance and space penalty by allocating a new register for the function call and copying it out. - - -built in functions ------------------- -void(string text) dprint; -Prints the string to the server console. - -void(entity client, string text) cprint; -Prints a message to a specific client. - -void(string text) bprint; -Broadcast prints a message to all clients on the current server. - -entity() spawn; -Returns a totally empty entity. You can manually set everything up, or just set the origin and call one of the existing entity setup functions. - -entity(entity start, .string field, string match) find; -Searches the server entity list beginning at start, looking for an entity that has entity.field = match. To start at the beginning of the list, pass world. World is returned when the end of the list is reached. - - - - -gotchas -------- - -The && and || operators DO NOT EARLY OUT like C! - -Don't confuse single quoted vectors with double quoted strings - -The function declaration syntax takes a little getting used to. - -Don't forget the ; after the trailing brace of a function initialization. - -Don't forget the "local" before defining local variables. - -There are no ++ / -- operators, or operate/assign operators. - -*/ - - -#if 1 -#include "hash.h" -extern hashtable_t compconstantstable; -extern hashtable_t globalstable, localstable; -#endif - -#ifdef WRITEASM -FILE *asmfile; -#endif -//============================================================================= - -// offsets are always multiplied by 4 before using -typedef unsigned int gofs_t; // offset in global data block -typedef struct QCC_function_s QCC_function_t; - -#define MAX_PARMS 8 - -typedef struct QCC_type_s -{ - etype_t type; - - struct QCC_type_s *parentclass; //type_entity... - struct QCC_type_s *next; -// function types are more complex - struct QCC_type_s *aux_type; // return type or field type - struct QCC_type_s *param; - int num_parms; // -1 = variable args -// struct QCC_type_s *parm_types[MAX_PARMS]; // only [num_parms] allocated - - unsigned int ofs; //inside a structure. - unsigned int size; - char *name; -} QCC_type_t; -int typecmp(QCC_type_t *a, QCC_type_t *b); - -typedef struct temp_s { - gofs_t ofs; - struct QCC_def_s *scope; -#ifdef WRITEASM - struct QCC_def_s *lastfunc; -#endif - struct temp_s *next; - pbool used; - unsigned int size; -} temp_t; - -//not written -typedef struct QCC_def_s -{ - QCC_type_t *type; - char *name; - struct QCC_def_s *next; - struct QCC_def_s *nextlocal; //provides a chain of local variables for the opt_locals_marshalling optimisation. - gofs_t ofs; - struct QCC_def_s *scope; // function the var was defined in, or NULL - int initialized; // 1 when a declaration included "= immediate" - int constant; // 1 says we can use the value over and over again - - int references; - int timescalled; //part of the opt_stripfunctions optimisation. - - int s_file; - int s_line; - - int arraysize; - pbool shared; - pbool saved; - pbool isstatic; - - temp_t *temp; -} QCC_def_t; - -//============================================================================ - -// pr_loc.h -- program local defs - - -//============================================================================= -extern char QCC_copyright[1024]; -extern char QCC_Packname[5][128]; -extern int QCC_packid; - -typedef union QCC_eval_s -{ - QCC_string_t string; - float _float; - float vector[3]; - func_t function; - int _int; - union QCC_eval_s *ptr; -} QCC_eval_t; - -const extern unsigned int type_size[]; -//extern QCC_def_t *def_for_type[9]; - -extern QCC_type_t *type_void, *type_string, *type_float, *type_vector, *type_entity, *type_field, *type_function, *type_pointer, *type_integer, *type_variant, *type_floatfield; - -struct QCC_function_s -{ - int builtin; // if non 0, call an internal function - int code; // first statement - char *file; // source file with definition - int file_line; - struct QCC_def_s *def; - unsigned int parm_ofs[MAX_PARMS]; // always contiguous, right? -}; - - -// -// output generated by prog parsing -// -typedef struct -{ - char *memory; - int max_memory; - int current_memory; - QCC_type_t *types; - - QCC_def_t def_head; // unused head of linked list - QCC_def_t *def_tail; // add new defs after this and move it - QCC_def_t *localvars; // chain of variables which need to be pushed and stuff. - - int size_fields; -} QCC_pr_info_t; - -extern QCC_pr_info_t pr; - - -typedef struct -{ - char name[MAXCONSTANTLENGTH]; - char value[MAXCONSTANTVALUELENGTH]; - char params[MAXCONSTANTPARAMS][MAXCONSTANTPARAMLENGTH]; - int numparams; - pbool used; - pbool inside; - - int namelen; -} CompilerConstant_t; -extern CompilerConstant_t *CompilerConstant; - -//============================================================================ - -extern pbool pr_dumpasm; - -//extern QCC_def_t **pr_global_defs; // to find def for a global variable - -typedef enum { -tt_eof, // end of file reached -tt_name, // an alphanumeric name token -tt_punct, // code punctuation -tt_immediate, // string, float, vector -} token_type_t; - -extern char pr_token[8192]; -extern token_type_t pr_token_type; -extern QCC_type_t *pr_immediate_type; -extern QCC_eval_t pr_immediate; - -extern pbool keyword_asm; -extern pbool keyword_break; -extern pbool keyword_case; -extern pbool keyword_class; -extern pbool keyword_const; -extern pbool keyword_continue; -extern pbool keyword_default; -extern pbool keyword_do; -extern pbool keyword_entity; -extern pbool keyword_float; -extern pbool keyword_for; -extern pbool keyword_goto; -extern pbool keyword_int; -extern pbool keyword_integer; -extern pbool keyword_state; -extern pbool keyword_string; -extern pbool keyword_struct; -extern pbool keyword_switch; -extern pbool keyword_thinktime; -extern pbool keyword_var; -extern pbool keyword_vector; -extern pbool keyword_union; -extern pbool keyword_enum; //kinda like in c, but typedef not supported. -extern pbool keyword_enumflags; //like enum, but doubles instead of adds 1. -extern pbool keyword_typedef; //fixme -extern pbool keyword_extern; //function is external, don't error or warn if the body was not found -extern pbool keyword_shared; //mark global to be copied over when progs changes (part of FTE_MULTIPROGS) -extern pbool keyword_noref; //nowhere else references this, don't strip it. -extern pbool keyword_nosave; //don't write the def to the output. -extern pbool keyword_union; //you surly know what a union is! - - -extern pbool keywords_coexist; -extern pbool output_parms; -extern pbool autoprototype; -extern pbool pr_subscopedlocals; -extern pbool flag_ifstring; -extern pbool flag_iffloat; -extern pbool flag_acc; -extern pbool flag_caseinsensative; -extern pbool flag_laxcasts; -extern pbool flag_hashonly; -extern pbool flag_fasttrackarrays; -extern pbool flag_assume_integer; -extern pbool flag_msvcstyle; - -extern pbool opt_overlaptemps; -extern pbool opt_shortenifnots; -extern pbool opt_noduplicatestrings; -extern pbool opt_constantarithmatic; -extern pbool opt_nonvec_parms; -extern pbool opt_constant_names; -extern pbool opt_precache_file; -extern pbool opt_filenames; -extern pbool opt_assignments; -extern pbool opt_unreferenced; -extern pbool opt_function_names; -extern pbool opt_locals; -extern pbool opt_dupconstdefs; -extern pbool opt_constant_names_strings; -extern pbool opt_return_only; -extern pbool opt_compound_jumps; -//extern pbool opt_comexprremoval; -extern pbool opt_stripfunctions; -extern pbool opt_locals_marshalling; -extern pbool opt_logicops; -extern pbool opt_vectorcalls; - -extern int optres_shortenifnots; -extern int optres_overlaptemps; -extern int optres_noduplicatestrings; -extern int optres_constantarithmatic; -extern int optres_nonvec_parms; -extern int optres_constant_names; -extern int optres_precache_file; -extern int optres_filenames; -extern int optres_assignments; -extern int optres_unreferenced; -extern int optres_function_names; -extern int optres_locals; -extern int optres_dupconstdefs; -extern int optres_constant_names_strings; -extern int optres_return_only; -extern int optres_compound_jumps; -//extern int optres_comexprremoval; -extern int optres_stripfunctions; -extern int optres_locals_marshalling; -extern int optres_logicops; - -pbool CompileParams(progfuncs_t *progfuncs, int doall, int nump, char **parms); - -void QCC_PR_PrintStatement (QCC_dstatement_t *s); - -void QCC_PR_Lex (void); -// reads the next token into pr_token and classifies its type - -QCC_type_t *QCC_PR_NewType (char *name, int basictype); -QCC_type_t *QCC_PR_ParseType (int newtype); extern pbool type_inlinefunction; -QCC_type_t *QCC_TypeForName(char *name); -QCC_type_t *QCC_PR_ParseFunctionType (int newtype, QCC_type_t *returntype); -QCC_type_t *QCC_PR_ParseFunctionTypeReacc (int newtype, QCC_type_t *returntype); -char *QCC_PR_ParseName (void); -CompilerConstant_t *QCC_PR_DefineName(char *name); - -void QCC_RemapOffsets(unsigned int firststatement, unsigned int laststatement, unsigned int min, unsigned int max, unsigned int newmin); - -#ifndef COMMONINLINES -pbool QCC_PR_CheckToken (char *string); -pbool QCC_PR_CheckName (char *string); -void QCC_PR_Expect (char *string); -pbool QCC_PR_CheckKeyword(int keywordenabled, char *string); -#endif -void VARGS QCC_PR_ParseError (int errortype, char *error, ...); -void VARGS QCC_PR_ParseWarning (int warningtype, char *error, ...); -void VARGS QCC_PR_Warning (int type, char *file, int line, char *error, ...); -void QCC_PR_ParsePrintDef (int warningtype, QCC_def_t *def); -void VARGS QCC_PR_ParseErrorPrintDef (int errortype, QCC_def_t *def, char *error, ...); - -int QCC_WarningForName(char *name); - -//QccMain.c must be changed if this is changed. -enum { - WARN_DEBUGGING, - WARN_ERROR, - WARN_NOTREFERENCED, - WARN_NOTREFERENCEDCONST, - WARN_CONFLICTINGRETURNS, - WARN_TOOFEWPARAMS, - WARN_TOOMANYPARAMS, - WARN_UNEXPECTEDPUNCT, - WARN_ASSIGNMENTTOCONSTANT, - WARN_ASSIGNMENTTOCONSTANTFUNC, - WARN_MISSINGRETURNVALUE, - WARN_WRONGRETURNTYPE, - WARN_CORRECTEDRETURNTYPE, - WARN_POINTLESSSTATEMENT, - WARN_MISSINGRETURN, - WARN_DUPLICATEDEFINITION, - WARN_UNDEFNOTDEFINED, - WARN_PRECOMPILERMESSAGE, - WARN_TOOMANYPARAMETERSFORFUNC, - WARN_STRINGTOOLONG, - WARN_BADTARGET, - WARN_BADPRAGMA, - WARN_HANGINGSLASHR, - WARN_NOTDEFINED, - WARN_NOTCONSTANT, - WARN_SWITCHTYPEMISMATCH, - WARN_CONFLICTINGUNIONMEMBER, - WARN_KEYWORDDISABLED, - WARN_ENUMFLAGS_NOTINTEGER, - WARN_ENUMFLAGS_NOTBINARY, - WARN_CASEINSENSATIVEFRAMEMACRO, - WARN_DUPLICATELABEL, - WARN_DUPLICATEMACRO, - WARN_ASSIGNMENTINCONDITIONAL, - WARN_MACROINSTRING, - WARN_BADPARAMS, - WARN_IMPLICITCONVERSION, - WARN_FIXEDRETURNVALUECONFLICT, - WARN_EXTRAPRECACHE, - WARN_NOTPRECACHED, - WARN_DEADCODE, - WARN_UNREACHABLECODE, - WARN_NOTSTANDARDBEHAVIOUR, - WARN_INEFFICIENTPLUSPLUS, - WARN_DUPLICATEPRECOMPILER, - WARN_IDENTICALPRECOMPILER, - WARN_FTE_SPECIFIC, //extension that only FTEQCC will have a clue about. - WARN_EXTENSION_USED, //extension that frikqcc also understands - WARN_IFSTRING_USED, - WARN_LAXCAST, //some errors become this with a compiler flag - WARN_UNDESIRABLECONVENTION, - WARN_SAMENAMEASGLOBAL, - WARN_CONSTANTCOMPARISON, - WARN_UNSAFEFUNCTIONRETURNTYPE, - - ERR_PARSEERRORS, //caused by qcc_pr_parseerror being called. - - //these are definatly my fault... - ERR_INTERNAL, - ERR_TOOCOMPLEX, - ERR_BADOPCODE, - ERR_TOOMANYSTATEMENTS, - ERR_TOOMANYSTRINGS, - ERR_BADTARGETSWITCH, - ERR_TOOMANYTYPES, - ERR_TOOMANYPAKFILES, - ERR_PRECOMPILERCONSTANTTOOLONG, - ERR_MACROTOOMANYPARMS, - ERR_CONSTANTTOOLONG, - ERR_TOOMANYFRAMEMACROS, - - //limitations, some are imposed by compiler, some arn't. - ERR_TOOMANYGLOBALS, - ERR_TOOMANYGOTOS, - ERR_TOOMANYBREAKS, - ERR_TOOMANYCONTINUES, - ERR_TOOMANYCASES, - ERR_TOOMANYLABELS, - ERR_TOOMANYOPENFILES, - ERR_TOOMANYPARAMETERSVARARGS, - ERR_TOOMANYTOTALPARAMETERS, - - //these are probably yours, or qcc being fussy. - ERR_BADEXTENSION, - ERR_BADIMMEDIATETYPE, - ERR_NOOUTPUT, - ERR_NOTAFUNCTION, - ERR_FUNCTIONWITHVARGS, - ERR_BADHEX, - ERR_UNKNOWNPUCTUATION, - ERR_EXPECTED, - ERR_NOTANAME, - ERR_NAMETOOLONG, - ERR_NOFUNC, - ERR_COULDNTOPENFILE, - ERR_NOTFUNCTIONTYPE, - ERR_TOOFEWPARAMS, - ERR_TOOMANYPARAMS, - ERR_CONSTANTNOTDEFINED, - ERR_BADFRAMEMACRO, - ERR_TYPEMISMATCH, - ERR_TYPEMISMATCHREDEC, - ERR_TYPEMISMATCHPARM, - ERR_TYPEMISMATCHARRAYSIZE, - ERR_UNEXPECTEDPUNCTUATION, - ERR_NOTACONSTANT, - ERR_REDECLARATION, - ERR_INITIALISEDLOCALFUNCTION, - ERR_NOTDEFINED, - ERR_ARRAYNEEDSSIZE, - ERR_ARRAYNEEDSBRACES, - ERR_TOOMANYINITIALISERS, - ERR_TYPEINVALIDINSTRUCT, - ERR_NOSHAREDLOCALS, - ERR_TYPEWITHNONAME, - ERR_BADARRAYSIZE, - ERR_NONAME, - ERR_SHAREDINITIALISED, - ERR_UNKNOWNVALUE, - ERR_BADARRAYINDEXTYPE, - ERR_NOVALIDOPCODES, - ERR_MEMBERNOTVALID, - ERR_BADPLUSPLUSOPERATOR, - ERR_BADNOTTYPE, - ERR_BADTYPECAST, - ERR_MULTIPLEDEFAULTS, - ERR_CASENOTIMMEDIATE, - ERR_BADSWITCHTYPE, - ERR_BADLABELNAME, - ERR_NOLABEL, - ERR_THINKTIMETYPEMISMATCH, - ERR_STATETYPEMISMATCH, - ERR_BADBUILTINIMMEDIATE, - ERR_PARAMWITHNONAME, - ERR_BADPARAMORDER, - ERR_ILLEGALCONTINUES, - ERR_ILLEGALBREAKS, - ERR_ILLEGALCASES, - ERR_NOTANUMBER, - ERR_WRONGSUBTYPE, - ERR_EOF, - ERR_NOPRECOMPILERIF, - ERR_NOENDIF, - ERR_HASHERROR, - ERR_NOTATYPE, - ERR_TOOMANYPACKFILES, - ERR_INVALIDVECTORIMMEDIATE, - ERR_INVALIDSTRINGIMMEDIATE, - ERR_BADCHARACTERCODE, - ERR_BADPARMS, - ERR_WERROR, - - WARN_MAX -}; - -#define FLAG_KILLSDEBUGGERS 1 -#define FLAG_ASDEFAULT 2 -#define FLAG_SETINGUI 4 -#define FLAG_HIDDENINGUI 8 -#define FLAG_MIDCOMPILE 16 //option can be changed mid-compile with the special pragma -typedef struct { - pbool *enabled; - char *abbrev; - int optimisationlevel; - int flags; //1: kills debuggers. 2: applied as default. - char *fullname; - char *description; - void *guiinfo; -} optimisations_t; -extern optimisations_t optimisations[]; - -typedef struct { - pbool *enabled; - int flags; //2 applied as default - char *abbrev; - char *fullname; - char *description; - void *guiinfo; -} compiler_flag_t; -extern compiler_flag_t compiler_flag[]; - -extern pbool qccwarningdisabled[WARN_MAX]; - -extern jmp_buf pr_parse_abort; // longjump with this on parse error -extern int pr_source_line; -extern char *pr_file_p; - -void *QCC_PR_Malloc (int size); - - -#define OFS_NULL 0 -#define OFS_RETURN 1 -#define OFS_PARM0 4 // leave 3 ofs for each parm to hold vectors -#define OFS_PARM1 7 -#define OFS_PARM2 10 -#define OFS_PARM3 13 -#define OFS_PARM4 16 -#define RESERVED_OFS 28 - - -extern QCC_def_t *pr_scope; -extern int pr_error_count, pr_warning_count; - -void QCC_PR_NewLine (pbool incomment); -QCC_def_t *QCC_PR_GetDef (QCC_type_t *type, char *name, QCC_def_t *scope, pbool allocate, int arraysize, pbool saved); - -void QCC_PR_PrintDefs (void); - -void QCC_PR_SkipToSemicolon (void); - -#define MAX_EXTRA_PARMS 128 -#ifdef MAX_EXTRA_PARMS -extern char pr_parm_names[MAX_PARMS+MAX_EXTRA_PARMS][MAX_NAME]; -extern QCC_def_t *extra_parms[MAX_EXTRA_PARMS]; -#else -extern char pr_parm_names[MAX_PARMS][MAX_NAME]; -#endif -extern pbool pr_trace; - -#define G_FLOAT(o) (qcc_pr_globals[o]) -#define G_INT(o) (*(int *)&qcc_pr_globals[o]) -#define G_VECTOR(o) (&qcc_pr_globals[o]) -#define G_STRING(o) (strings + *(QCC_string_t *)&qcc_pr_globals[o]) -#define G_FUNCTION(o) (*(func_t *)&qcc_pr_globals[o]) - -char *QCC_PR_ValueString (etype_t type, void *val); - -void QCC_PR_ClearGrabMacros (void); - -pbool QCC_PR_CompileFile (char *string, char *filename); -void QCC_PR_ResetErrorScope(void); - -extern pbool pr_dumpasm; - -extern QCC_string_t s_file; // filename for function definition - -extern QCC_def_t def_ret, def_parms[MAX_PARMS]; - -void QCC_PR_EmitArrayGetFunction(QCC_def_t *scope, char *arrayname); -void QCC_PR_EmitArraySetFunction(QCC_def_t *scope, char *arrayname); -void QCC_PR_EmitClassFromFunction(QCC_def_t *scope, char *tname); - -//============================================================================= - -extern char pr_immediate_string[8192]; - -extern float *qcc_pr_globals; -extern unsigned int numpr_globals; - -extern char *strings; -extern int strofs; - -extern QCC_dstatement_t *statements; -extern int numstatements; -extern int *statement_linenums; - -extern QCC_dfunction_t *functions; -extern int numfunctions; - -extern QCC_ddef_t *qcc_globals; -extern int numglobaldefs; - -extern QCC_def_t *activetemps; - -extern QCC_ddef_t *fields; -extern int numfielddefs; - -extern QCC_type_t *qcc_typeinfo; -extern int numtypeinfos; -extern int maxtypeinfos; - -extern int ForcedCRC; -extern pbool defaultstatic; - -extern int *qcc_tempofs; -extern int max_temps; -//extern int qcc_functioncalled; //unuse temps if this is true - don't want to reuse the same space. - -extern int tempsstart; -extern int numtemps; - -typedef char PATHSTRING[MAX_DATA_PATH]; - -PATHSTRING *precache_sounds; -int *precache_sounds_block; -int *precache_sounds_used; -int numsounds; - -PATHSTRING *precache_textures; -int *precache_textures_block; -int numtextures; - -PATHSTRING *precache_models; -int *precache_models_block; -int *precache_models_used; -int nummodels; - -PATHSTRING *precache_files; -int *precache_files_block; -int numfiles; - -int QCC_CopyString (char *str); - - - - -typedef struct qcc_cachedsourcefile_s { - char filename[128]; - int size; - char *file; - enum{FT_CODE, FT_DATA} type; //quakec source file or not. - struct qcc_cachedsourcefile_s *next; -} qcc_cachedsourcefile_t; -extern qcc_cachedsourcefile_t *qcc_sourcefile; - - - - - -#ifdef COMMONINLINES -static bool inline QCC_PR_CheckToken (char *string) -{ - if (pr_token_type != tt_punct) - return false; - - if (STRCMP (string, pr_token)) - return false; - - QCC_PR_Lex (); - return true; -} - -static void inline QCC_PR_Expect (char *string) -{ - if (strcmp (string, pr_token)) - QCC_PR_ParseError ("expected %s, found %s",string, pr_token); - QCC_PR_Lex (); -} -#endif - -void editbadfile(char *fname, int line); -char *TypeName(QCC_type_t *type); -void QCC_PR_IncludeChunk (char *data, pbool duplicate, char *filename); -void QCC_PR_IncludeChunkEx(char *data, pbool duplicate, char *filename, CompilerConstant_t *cnst); -pbool QCC_PR_UnInclude(void); -extern void *(*pHash_Get)(hashtable_t *table, char *name); -extern void *(*pHash_GetNext)(hashtable_t *table, char *name, void *old); -extern void *(*pHash_Add)(hashtable_t *table, char *name, void *data, bucket_t *); diff --git a/misc/mediasource/extra/fteqcc-src/qcc_cmdlib.c b/misc/mediasource/extra/fteqcc-src/qcc_cmdlib.c deleted file mode 100644 index 8d0f874a..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcc_cmdlib.c +++ /dev/null @@ -1,918 +0,0 @@ -// cmdlib.c - -#include "qcc.h" -#include -//#include - -#define PATHSEPERATOR '/' - -#ifndef QCC -extern jmp_buf qcccompileerror; -#endif - -// set these before calling CheckParm -int myargc; -char **myargv; - -char qcc_token[1024]; -int qcc_eof; - -const unsigned int type_size[12] = {1, //void - sizeof(string_t)/4, //string - 1, //float - 3, //vector - 1, //entity - 1, //field - sizeof(func_t)/4,//function - 1, //pointer (its an int index) - 1, //integer - 1, //fixme: how big should a variant be? - 0, //ev_struct. variable sized. - 0 //ev_union. variable sized. - }; - -/* -============================================================================ - - BYTE ORDER FUNCTIONS - -============================================================================ -*/ -short (*PRBigShort) (short l); -short (*PRLittleShort) (short l); -int (*PRBigLong) (int l); -int (*PRLittleLong) (int l); -float (*PRBigFloat) (float l); -float (*PRLittleFloat) (float l); - - -short QCC_SwapShort (short l) -{ - qbyte b1,b2; - - b1 = l&255; - b2 = (l>>8)&255; - - return (b1<<8) + b2; -} - -short QCC_Short (short l) -{ - return l; -} - - -int QCC_SwapLong (int l) -{ - qbyte b1,b2,b3,b4; - - b1 = (qbyte)l; - b2 = (qbyte)(l>>8); - b3 = (qbyte)(l>>16); - b4 = (qbyte)(l>>24); - - return ((int)b1<<24) + ((int)b2<<16) + ((int)b3<<8) + b4; -} - -int QCC_Long (int l) -{ - return l; -} - - -float QCC_SwapFloat (float l) -{ - union {qbyte 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 QCC_Float (float l) -{ - return l; -} - -void SetEndian(void) -{ - union {qbyte b[2]; unsigned short s;} ed; - ed.s = 255; - if (ed.b[0] == 255) - { - PRBigShort = QCC_SwapShort; - PRLittleShort = QCC_Short; - PRBigLong = QCC_SwapLong; - PRLittleLong = QCC_Long; - PRBigFloat = QCC_SwapFloat; - PRLittleFloat = QCC_Float; - } - else - { - PRBigShort = QCC_Short; - PRLittleShort = QCC_SwapShort; - PRBigLong = QCC_Long; - PRLittleLong = QCC_SwapLong; - PRBigFloat = QCC_Float; - PRLittleFloat = QCC_SwapFloat; - } -} - - - -#ifndef MINIMAL -/* -================ -I_FloatTime -================ -*/ -/* -double I_FloatTime (void) -{ - 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; -} - - */ - - -#ifdef QCC -int QC_strncasecmp (const char *s1, const char *s2, int n) -{ - int c1, c2; - - while (1) - { - 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 - } - if (!c1) - return 0; // strings are equal -// s1++; -// s2++; - } - - return -1; -} - -int QC_strcasecmp (const char *s1, const char *s2) -{ - return QC_strncasecmp(s1, s2, 0x7fffffff); -} - -#else -int QC_strncasecmp(const char *s1, const char *s2, int n); -int QC_strcasecmp (const char *s1, const char *s2) -{ - return QC_strncasecmp(s1, s2, 0x7fffffff); -} - -#endif - - - -#endif //minimal -/* -============== -COM_Parse - -Parse a token out of a string -============== -*/ -char *QCC_COM_Parse (char *data) -{ - int c; - int len; - - len = 0; - qcc_token[0] = 0; - - if (!data) - return NULL; - -// skip whitespace -skipwhite: - while ( (c = *data) <= ' ') - { - if (c == 0) - { - qcc_eof = true; - return NULL; // end of file; - } - data++; - } - -// skip // comments - if (c=='/' && data[1] == '/') - { - while (*data && *data != '\n') - data++; - goto skipwhite; - } - - // skip /* comments - if (c=='/' && data[1] == '*') - { - while (data[1] && (data[0] != '*' || data[1] != '/')) - data++; - data+=2; - goto skipwhite; - } - - -// handle quoted strings specially - if (c == '\"') - { - data++; - do - { - c = *data++; - if (c=='\\' && *data == '\"') - c = *data++; //allow C-style string escapes - else if (c=='\\' && *data == '\\') - c = *data++; // \ is now a special character so it needs to be marked up using itself - else if (c=='\\' && *data == 'n') - { // and do new lines while we're at it. - c = '\n'; - data++; - } - else if (c=='\"') - { - qcc_token[len] = 0; - return data; - } - else if (c=='\0'||c=='\n') - { - qcc_token[len] = 0; - return data; - } - qcc_token[len] = c; - len++; - } while (1); - } - -// parse single characters - if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':' || c==',') - { - qcc_token[len] = c; - len++; - qcc_token[len] = 0; - return data+1; - } - -// parse a regular word - do - { - qcc_token[len] = c; - data++; - len++; - c = *data; - if (c=='{' || c=='}'|| c==')'|| c=='(' || c=='\'' || c==':' || c=='\"' || c==',') - break; - } while (c>32); - - qcc_token[len] = 0; - return data; -} - -//more C tokens... -char *QCC_COM_Parse2 (char *data) -{ - int c; - int len; - - len = 0; - qcc_token[0] = 0; - - if (!data) - return NULL; - -// skip whitespace -skipwhite: - while ( (c = *data) <= ' ') - { - if (c == 0) - { - qcc_eof = true; - 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=='\\' && *data == '\"') - c = *data++; //allow C-style string escapes - else if (c=='\\' && *data == '\\') - c = *data++; // \ is now a special character so it needs to be marked up using itself - else if (c=='\\' && *data == 'n') - { // and do new lines while we're at it. - c = '\n'; - data++; - } - else if (c=='\"'||c=='\0') - qcc_token[len] = c; - len++; - } while (1); - } - -// parse numbers - if (c >= '0' && c <= '9') - { - if (c == '0' && data[1] == 'x') - { //parse hex - qcc_token[0] = '0'; - c='x'; - len=1; - data++; - for(;;) - { //parse regular number - qcc_token[len] = c; - data++; - len++; - c = *data; - if ((c<'0'|| c>'9') && (c<'a'||c>'f') && (c<'A'||c>'F') && c != '.') - break; - } - - } - else - { - for(;;) - { //parse regular number - qcc_token[len] = c; - data++; - len++; - c = *data; - if ((c<'0'|| c>'9') && c != '.') - break; - } - } - - qcc_token[len] = 0; - return data; - } -// parse words - else if ((c>= 'a' && c <= 'z') || (c>= 'A' && c <= 'Z') || c == '_') - { - do - { - qcc_token[len] = c; - data++; - len++; - c = *data; - } while ((c>= 'a' && c <= 'z') || (c>= 'A' && c <= 'Z') || c == '_'); - - qcc_token[len] = 0; - return data; - } - else - { - qcc_token[len] = c; - len++; - qcc_token[len] = 0; - return data+1; - } -} - -char *VARGS qcva (char *text, ...) -{ - va_list argptr; - static char msg[2048]; - - va_start (argptr,text); - QC_vsnprintf (msg,sizeof(msg)-1, text,argptr); - va_end (argptr); - - return msg; -} - - -#ifndef MINIMAL - -char *QC_strupr (char *start) -{ - char *in; - in = start; - while (*in) - { - *in = toupper(*in); - in++; - } - return start; -} - -char *QC_strlower (char *start) -{ - char *in; - in = start; - while (*in) - { - *in = tolower(*in); - in++; - } - return start; -} - - -/* -============================================================================= - - MISC FUNCTIONS - -============================================================================= -*/ - -/* -================= -Error - -For abnormal program terminations -================= -*/ -void VARGS QCC_Error (int errortype, const char *error, ...) -{ - extern int numsourcefiles; - va_list argptr; - char msg[2048]; - - va_start (argptr,error); - QC_vsnprintf (msg,sizeof(msg)-1, error,argptr); - va_end (argptr); - - printf ("\n************ ERROR ************\n%s\n", msg); - - - editbadfile(strings+s_file, pr_source_line); - - numsourcefiles = 0; - -#ifndef QCC - longjmp(qcccompileerror, 1); -#else - print ("Press any key\n"); - getch(); -#endif - exit (1); -} - - -/* -================= -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 QCC_CheckParm (char *check) -{ - int i; - - for (i = 1;i 0 && path[length] != PATHSEPERATOR) - length--; - path[length] = 0; -} - -/* -==================== -Extract file parts -==================== -*/ -void ExtractFilePath (char *path, char *dest) -{ - char *src; - - src = path + strlen(path) - 1; - -// -// back up until a \ or the start -// - while (src != path && *(src-1) != PATHSEPERATOR) - src--; - - memcpy (dest, path, src-path); - dest[src-path] = 0; -} - -void ExtractFileBase (char *path, char *dest) -{ - char *src; - - src = path + strlen(path) - 1; - -// -// back up until a \ or the start -// - while (src != path && *(src-1) != PATHSEPERATOR) - src--; - - while (*src && *src != '.') - { - *dest++ = *src++; - } - *dest = 0; -} - -void ExtractFileExtension (char *path, char *dest) -{ - 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 -============== -*/ -long ParseHex (char *hex) -{ - char *str; - long 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 - QCC_Error (ERR_BADHEX, "Bad hex number: %s",hex); - str++; - } - - return num; -} - - -long ParseNum (char *str) -{ - if (str[0] == '$') - return ParseHex (str+1); - if (str[0] == '0' && str[1] == 'x') - return ParseHex (str+2); - return atol (str); -} - - - - - - - - -//buffer size and max size are different. buffer is bigger. - -#define MAXQCCFILES 3 -struct { - char name[64]; - char *buff; -// int buffismalloc; - int buffsize; - int ofs; - int maxofs; -} qccfile[MAXQCCFILES]; -int SafeOpenWrite (char *filename, int maxsize) -{ - int i; - for (i = 0; i < MAXQCCFILES; i++) - { - if (!qccfile[i].buff) - { - strcpy(qccfile[i].name, filename); - qccfile[i].buffsize = maxsize; - qccfile[i].maxofs = 0; - qccfile[i].ofs = 0; -// if (maxsize > 8192) -// qccfile[i].buffismalloc = 1; -// else -// qccfile[i].buffismalloc = 0; -// if (qccfile[i].buffismalloc) - qccfile[i].buff = malloc(qccfile[i].buffsize); -// else -// qccfile[i].buff = memalloc(qccfile[i].buffsize); - return i; - } - } - QCC_Error(ERR_TOOMANYOPENFILES, "Too many open files on file %s", filename); - return -1; -} - -void ResizeBuf(int hand, int newsize) -{ -// int wasmal = qccfile[hand].buffismalloc; - char *nb; - - if (qccfile[hand].buffsize >= newsize) - return; //already big enough - -// if (newsize > 8192) -// { -// qccfile[hand].buffismalloc = true; - nb = malloc(newsize); -// } -// else -// { -// qccfile[hand].buffismalloc = false; -// nb = memalloc(newsize); -// } - - memcpy(nb, qccfile[hand].buff, qccfile[hand].maxofs); -// if (wasmal) - free(qccfile[hand].buff); -// else -// memfree(qccfile[hand].buff); - qccfile[hand].buff = nb; - qccfile[hand].buffsize = newsize; -} -void SafeWrite(int hand, void *buf, long count) -{ - if (qccfile[hand].ofs +count >= qccfile[hand].buffsize) - ResizeBuf(hand, qccfile[hand].ofs + count+(64*1024)); - - memcpy(&qccfile[hand].buff[qccfile[hand].ofs], buf, count); - qccfile[hand].ofs+=count; - if (qccfile[hand].ofs > qccfile[hand].maxofs) - qccfile[hand].maxofs = qccfile[hand].ofs; -} -int SafeSeek(int hand, int ofs, int mode) -{ - if (mode == SEEK_CUR) - return qccfile[hand].ofs; - else - { - ResizeBuf(hand, ofs+1024); - qccfile[hand].ofs = ofs; - if (qccfile[hand].ofs > qccfile[hand].maxofs) - qccfile[hand].maxofs = qccfile[hand].ofs; - return 0; - } -} -void SafeClose(int hand) -{ - externs->WriteFile(qccfile[hand].name, qccfile[hand].buff, qccfile[hand].maxofs); -// if (qccfile[hand].buffismalloc) - free(qccfile[hand].buff); -// else -// memfree(qccfile[hand].buff); - qccfile[hand].buff = NULL; -} - -qcc_cachedsourcefile_t *qcc_sourcefile; -long QCC_LoadFile (char *filename, void **bufferptr) -{ - char *mem; - int len; - len = externs->FileSize(filename); - if (len < 0) - { - QCC_Error(ERR_COULDNTOPENFILE, "Couldn't open file %s", filename); -// if (!Abort) - return -1; -// Abort("failed to find file %s", filename); - } - mem = qccHunkAlloc(sizeof(qcc_cachedsourcefile_t) + len+2); - - ((qcc_cachedsourcefile_t*)mem)->next = qcc_sourcefile; - qcc_sourcefile = (qcc_cachedsourcefile_t*)mem; - qcc_sourcefile->size = len; - mem += sizeof(qcc_cachedsourcefile_t); - strcpy(qcc_sourcefile->filename, filename); - qcc_sourcefile->file = mem; - qcc_sourcefile->type = FT_CODE; - - externs->ReadFile(filename, mem, len+2); - mem[len] = '\n'; - mem[len+1] = '\0'; - *bufferptr=mem; - - return len; -} -void QCC_AddFile (char *filename) -{ - char *mem; - int len; - len = externs->FileSize(filename); - if (len < 0) - Abort("failed to find file %s", filename); - mem = qccHunkAlloc(sizeof(qcc_cachedsourcefile_t) + len+1); - - ((qcc_cachedsourcefile_t*)mem)->next = qcc_sourcefile; - qcc_sourcefile = (qcc_cachedsourcefile_t*)mem; - qcc_sourcefile->size = len; - mem += sizeof(qcc_cachedsourcefile_t); - strcpy(qcc_sourcefile->filename, filename); - qcc_sourcefile->file = mem; - qcc_sourcefile->type = FT_DATA; - - externs->ReadFile(filename, mem, len+1); - mem[len] = '\0'; -} -void *FS_ReadToMem(char *filename, void *mem, int *len) -{ - if (!mem) - { - *len = externs->FileSize(filename); - mem = memalloc(*len); - } - return externs->ReadFile(filename, mem, *len); -} - -void FS_CloseFromMem(void *mem) -{ - memfree(mem); -} - - -#endif - -void StripExtension (char *path) -{ - int length; - - length = strlen(path)-1; - while (length > 0 && path[length] != '.') - { - length--; - if (path[length] == '/') - return; // no extension - } - if (length) - path[length] = 0; -} diff --git a/misc/mediasource/extra/fteqcc-src/qcc_pr_comp.c b/misc/mediasource/extra/fteqcc-src/qcc_pr_comp.c deleted file mode 100644 index e37d4ff2..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcc_pr_comp.c +++ /dev/null @@ -1,9829 +0,0 @@ -#ifndef MINIMAL - -#include "qcc.h" -void QCC_PR_ParseAsm(void); - -#define MEMBERFIELDNAME "__m%s" - -#define STRCMP(s1,s2) (((*s1)!=(*s2)) || strcmp(s1+1,s2+1)) //saves about 2-6 out of 120 - expansion of idea from fastqcc -#define STRNCMP(s1,s2,l) (((*s1)!=(*s2)) || strncmp(s1+1,s2+1,l)) //pathetic saving here. - -extern char *compilingfile; - -int conditional; - -extern int dotranslate; -extern int dotranslate_count; - -//standard qcc keywords -#define keyword_do 1 -#define keyword_return 1 -#define keyword_if 1 -#define keyword_else 1 -#define keyword_local 1 -#define keyword_while 1 - -//extended keywords. -pbool keyword_asm; -pbool keyword_break; -pbool keyword_case; -pbool keyword_class; -pbool keyword_const; //fixme -pbool keyword_continue; -pbool keyword_default; -pbool keyword_entity; //for skipping the local -pbool keyword_float; //for skipping the local -pbool keyword_for; -pbool keyword_goto; -pbool keyword_int; //for skipping the local -pbool keyword_integer; //for skipping the local -pbool keyword_state; -pbool keyword_string; //for skipping the local -pbool keyword_struct; -pbool keyword_switch; -pbool keyword_thinktime; -pbool keyword_var; //allow it to be initialised and set around the place. -pbool keyword_vector; //for skipping the local - - -pbool keyword_enum; //kinda like in c, but typedef not supported. -pbool keyword_enumflags; //like enum, but doubles instead of adds 1. -pbool keyword_typedef; //fixme -#define keyword_codesys flag_acc //reacc needs this (forces the resultant crc) -#define keyword_function flag_acc //reacc needs this (reacc has this on all functions, wierd eh?) -#define keyword_objdata flag_acc //reacc needs this (following defs are fields rather than globals, use var to disable) -#define keyword_object flag_acc //reacc needs this (an entity) -#define keyword_pfunc flag_acc //reacc needs this (pointer to function) -#define keyword_system flag_acc //reacc needs this (potatos) -#define keyword_real flag_acc //reacc needs this (a float) -#define keyword_exit flag_acc //emits an OP_DONE opcode. -#define keyword_external flag_acc //reacc needs this (a builtin) -pbool keyword_extern; //function is external, don't error or warn if the body was not found -pbool keyword_shared; //mark global to be copied over when progs changes (part of FTE_MULTIPROGS) -pbool keyword_noref; //nowhere else references this, don't strip it. -pbool keyword_nosave; //don't write the def to the output. -pbool keyword_union; //you surly know what a union is! - -#define keyword_not 1 //hexenc support needs this, and fteqcc can optimise without it, but it adds an extra token after the if, so it can cause no namespace conflicts - -pbool keywords_coexist; //don't disable a keyword simply because a var was made with the same name. -pbool output_parms; //emit some PARMX fields. confuses decompilers. -pbool autoprototype; //take two passes over the source code. First time round doesn't enter and functions or initialise variables. -pbool pr_subscopedlocals; //causes locals to be valid ONLY within their statement block. (they simply can't be referenced by name outside of it) -pbool flag_ifstring; //makes if (blah) equivelent to if (blah != "") which resolves some issues in multiprogs situations. -pbool flag_iffloat; //use an op_if_f instruction instead of op_if so if(-0) evaluates to false. -pbool flag_acc; //reacc like behaviour of src files (finds *.qc in start dir and compiles all in alphabetical order) -pbool flag_caseinsensative; //symbols will be matched to an insensative case if the specified case doesn't exist. This should b usable for any mod -pbool flag_laxcasts; //Allow lax casting. This'll produce loadsa warnings of course. But allows compilation of certain dodgy code. -pbool flag_hashonly; //Allows use of only #constant for precompiler constants, allows certain preqcc using mods to compile -pbool flag_fasttrackarrays; //Faster arrays, dynamically detected, activated only in supporting engines. -pbool flag_msvcstyle; //MSVC style warnings, so msvc's ide works properly -pbool flag_assume_integer; //5 - is that an integer or a float? qcc says float. but we support int too, so maybe we want that instead? - -pbool opt_overlaptemps; //reduce numpr_globals by reuse of temps. When they are not needed they are freed for reuse. The way this is implemented is better than frikqcc's. (This is the single most important optimisation) -pbool opt_assignments; //STORE_F isn't used if an operation wrote to a temp. -pbool opt_shortenifnots; //if(!var) is made an IF rather than NOT IFNOT -pbool opt_noduplicatestrings; //brute force string check. time consuming but more effective than the equivelent in frikqcc. -pbool opt_constantarithmatic; //3*5 appears as 15 instead of the extra statement. -pbool opt_nonvec_parms; //store_f instead of store_v on function calls, where possible. -pbool opt_constant_names; //take out the defs and name strings of constants. -pbool opt_constant_names_strings;//removes the defs of strings too. plays havok with multiprogs. -pbool opt_precache_file; //remove the call, the parameters, everything. -pbool opt_filenames; //strip filenames. hinders older decompilers. -pbool opt_unreferenced; //strip defs that are not referenced. -pbool opt_function_names; //strip out the names of builtin functions. -pbool opt_locals; //strip out the names of locals and immediates. -pbool opt_dupconstdefs; //float X = 5; and float Y = 5; occupy the same global with this. -pbool opt_return_only; //RETURN; DONE; at the end of a function strips out the done statement if there is no way to get to it. -pbool opt_compound_jumps; //jumps to jump statements jump to the final point. -pbool opt_stripfunctions; //if a functions is only ever called directly or by exe, don't emit the def. -pbool opt_locals_marshalling; //make the local vars of all functions occupy the same globals. -pbool opt_logicops; //don't make conditions enter functions if the return value will be discarded due to a previous value. (C style if statements) -pbool opt_vectorcalls; //vectors can be packed into 3 floats, which can yield lower numpr_globals, but cost two more statements per call (only works for q1 calling conventions). -pbool opt_simplifiedifs; //if (f != 0) -> if (f). if (f == 0) -> ifnot (f) -//bool opt_comexprremoval; - -//these are the results of the opt_. The values are printed out when compilation is compleate, showing effectivness. -int optres_shortenifnots; -int optres_assignments; -int optres_overlaptemps; -int optres_noduplicatestrings; -int optres_constantarithmatic; -int optres_nonvec_parms; -int optres_constant_names; -int optres_constant_names_strings; -int optres_precache_file; -int optres_filenames; -int optres_unreferenced; -int optres_function_names; -int optres_locals; -int optres_dupconstdefs; -int optres_return_only; -int optres_compound_jumps; -//int optres_comexprremoval; -int optres_stripfunctions; -int optres_locals_marshalling; -int optres_logicops; - -int optres_test1; -int optres_test2; - -void *(*pHash_Get)(hashtable_t *table, char *name); -void *(*pHash_GetNext)(hashtable_t *table, char *name, void *old); -void *(*pHash_Add)(hashtable_t *table, char *name, void *data, bucket_t *); - -QCC_def_t *QCC_PR_DummyDef(QCC_type_t *type, char *name, QCC_def_t *scope, int arraysize, unsigned int ofs, int referable, pbool saved); -QCC_type_t *QCC_PR_NewType (char *name, int basictype); -QCC_type_t *QCC_PR_FindType (QCC_type_t *type); -QCC_type_t *QCC_PR_PointerType (QCC_type_t *pointsto); -QCC_type_t *QCC_PR_FieldType (QCC_type_t *pointsto); - -void QCC_PR_ParseState (void); -pbool simplestore; -pbool expandedemptymacro; - -QCC_pr_info_t pr; -//QCC_def_t **pr_global_defs/*[MAX_REGS]*/; // to find def for a global variable - -//keeps track of how many funcs are called while parsing a statement -//int qcc_functioncalled; - -//======================================== - -QCC_def_t *pr_scope; // the function being parsed, or NULL -QCC_type_t *pr_classtype; -pbool pr_dumpasm; -QCC_string_t s_file, s_file2; // filename for function definition - -unsigned int locals_start; // for tracking local variables vs temps -unsigned int locals_end; // for tracking local variables vs temps - -jmp_buf pr_parse_abort; // longjump with this on parse error - -void QCC_PR_ParseDefs (char *classname); - -pbool qcc_usefulstatement; - -int max_breaks; -int max_continues; -int max_cases; -int num_continues; -int num_breaks; -int num_cases; -int *pr_breaks; -int *pr_continues; -int *pr_cases; -QCC_def_t **pr_casesdef; -QCC_def_t **pr_casesdef2; - -typedef struct { - int statementno; - int lineno; - char name[256]; -} gotooperator_t; - -int max_labels; -int max_gotos; -gotooperator_t *pr_labels; -gotooperator_t *pr_gotos; -int num_gotos; -int num_labels; - -QCC_def_t *extra_parms[MAX_EXTRA_PARMS]; - -#define ASSOC_RIGHT_RESULT ASSOC_RIGHT - -//======================================== - -//FIXME: modifiy list so most common GROUPS are first -//use look up table for value of first char and sort by first char and most common...? - -//if true, effectivly {b=a; return a;} -QCC_opcode_t pr_opcodes[] = -{ - {6, "", "DONE", -1, ASSOC_LEFT, &type_void, &type_void, &type_void}, - - {6, "*", "MUL_F", 3, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "*", "MUL_V", 3, ASSOC_LEFT, &type_vector, &type_vector, &type_float}, - {6, "*", "MUL_FV", 3, ASSOC_LEFT, &type_float, &type_vector, &type_vector}, - {6, "*", "MUL_VF", 3, ASSOC_LEFT, &type_vector, &type_float, &type_vector}, - - {6, "/", "DIV_F", 3, ASSOC_LEFT, &type_float, &type_float, &type_float}, - - {6, "+", "ADD_F", 4, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "+", "ADD_V", 4, ASSOC_LEFT, &type_vector, &type_vector, &type_vector}, - - {6, "-", "SUB_F", 4, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "-", "SUB_V", 4, ASSOC_LEFT, &type_vector, &type_vector, &type_vector}, - - {6, "==", "EQ_F", 5, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "==", "EQ_V", 5, ASSOC_LEFT, &type_vector, &type_vector, &type_float}, - {6, "==", "EQ_S", 5, ASSOC_LEFT, &type_string, &type_string, &type_float}, - {6, "==", "EQ_E", 5, ASSOC_LEFT, &type_entity, &type_entity, &type_float}, - {6, "==", "EQ_FNC", 5, ASSOC_LEFT, &type_function, &type_function, &type_float}, - - {6, "!=", "NE_F", 5, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "!=", "NE_V", 5, ASSOC_LEFT, &type_vector, &type_vector, &type_float}, - {6, "!=", "NE_S", 5, ASSOC_LEFT, &type_string, &type_string, &type_float}, - {6, "!=", "NE_E", 5, ASSOC_LEFT, &type_entity, &type_entity, &type_float}, - {6, "!=", "NE_FNC", 5, ASSOC_LEFT, &type_function, &type_function, &type_float}, - - {6, "<=", "LE", 5, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, ">=", "GE", 5, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "<", "LT", 5, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, ">", "GT", 5, ASSOC_LEFT, &type_float, &type_float, &type_float}, - - {6, ".", "INDIRECT_F", 1, ASSOC_LEFT, &type_entity, &type_field, &type_float}, - {6, ".", "INDIRECT_V", 1, ASSOC_LEFT, &type_entity, &type_field, &type_vector}, - {6, ".", "INDIRECT_S", 1, ASSOC_LEFT, &type_entity, &type_field, &type_string}, - {6, ".", "INDIRECT_E", 1, ASSOC_LEFT, &type_entity, &type_field, &type_entity}, - {6, ".", "INDIRECT_FI", 1, ASSOC_LEFT, &type_entity, &type_field, &type_field}, - {6, ".", "INDIRECT_FU", 1, ASSOC_LEFT, &type_entity, &type_field, &type_function}, - - {6, ".", "ADDRESS", 1, ASSOC_LEFT, &type_entity, &type_field, &type_pointer}, - - {6, "=", "STORE_F", 6, ASSOC_RIGHT, &type_float, &type_float, &type_float}, - {6, "=", "STORE_V", 6, ASSOC_RIGHT, &type_vector, &type_vector, &type_vector}, - {6, "=", "STORE_S", 6, ASSOC_RIGHT, &type_string, &type_string, &type_string}, - {6, "=", "STORE_ENT", 6, ASSOC_RIGHT, &type_entity, &type_entity, &type_entity}, - {6, "=", "STORE_FLD", 6, ASSOC_RIGHT, &type_field, &type_field, &type_field}, - {6, "=", "STORE_FNC", 6, ASSOC_RIGHT, &type_function, &type_function, &type_function}, - - {6, "=", "STOREP_F", 6, ASSOC_RIGHT, &type_pointer, &type_float, &type_float}, - {6, "=", "STOREP_V", 6, ASSOC_RIGHT, &type_pointer, &type_vector, &type_vector}, - {6, "=", "STOREP_S", 6, ASSOC_RIGHT, &type_pointer, &type_string, &type_string}, - {6, "=", "STOREP_ENT", 6, ASSOC_RIGHT, &type_pointer, &type_entity, &type_entity}, - {6, "=", "STOREP_FLD", 6, ASSOC_RIGHT, &type_pointer, &type_field, &type_field}, - {6, "=", "STOREP_FNC", 6, ASSOC_RIGHT, &type_pointer, &type_function, &type_function}, - - {6, "", "RETURN", -1, ASSOC_LEFT, &type_float, &type_void, &type_void}, - - {6, "!", "NOT_F", -1, ASSOC_LEFT, &type_float, &type_void, &type_float}, - {6, "!", "NOT_V", -1, ASSOC_LEFT, &type_vector, &type_void, &type_float}, - {6, "!", "NOT_S", -1, ASSOC_LEFT, &type_vector, &type_void, &type_float}, - {6, "!", "NOT_ENT", -1, ASSOC_LEFT, &type_entity, &type_void, &type_float}, - {6, "!", "NOT_FNC", -1, ASSOC_LEFT, &type_function, &type_void, &type_float}, - - {6, "", "IF", -1, ASSOC_RIGHT, &type_float, NULL, &type_void}, - {6, "", "IFNOT", -1, ASSOC_RIGHT, &type_float, NULL, &type_void}, - -// calls returns REG_RETURN - {6, "", "CALL0", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL1", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL2", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL3", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL4", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL5", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL6", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL7", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - {6, "", "CALL8", -1, ASSOC_LEFT, &type_function, &type_void, &type_void}, - - {6, "", "STATE", -1, ASSOC_LEFT, &type_float, &type_float, &type_void}, - - {6, "", "GOTO", -1, ASSOC_RIGHT, NULL, &type_void, &type_void}, - - {6, "&&", "AND", 7, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "||", "OR", 7, ASSOC_LEFT, &type_float, &type_float, &type_float}, - - {6, "&", "BITAND", 3, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {6, "|", "BITOR", 3, ASSOC_LEFT, &type_float, &type_float, &type_float}, - - //version 6 are in normal progs. - - - -//these are hexen2 - {7, "*=", "MULSTORE_F", 6, ASSOC_RIGHT_RESULT, &type_float, &type_float, &type_float}, - {7, "*=", "MULSTORE_V", 6, ASSOC_RIGHT_RESULT, &type_vector, &type_float, &type_vector}, - {7, "*=", "MULSTOREP_F", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_float}, - {7, "*=", "MULSTOREP_V", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_vector}, - - {7, "/=", "DIVSTORE_F", 6, ASSOC_RIGHT_RESULT, &type_float, &type_float, &type_float}, - {7, "/=", "DIVSTOREP_F", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_float}, - - {7, "+=", "ADDSTORE_F", 6, ASSOC_RIGHT_RESULT, &type_float, &type_float, &type_float}, - {7, "+=", "ADDSTORE_V", 6, ASSOC_RIGHT_RESULT, &type_vector, &type_vector, &type_vector}, - {7, "+=", "ADDSTOREP_F", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_float}, - {7, "+=", "ADDSTOREP_V", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_vector, &type_vector}, - - {7, "-=", "SUBSTORE_F", 6, ASSOC_RIGHT_RESULT, &type_float, &type_float, &type_float}, - {7, "-=", "SUBSTORE_V", 6, ASSOC_RIGHT_RESULT, &type_vector, &type_vector, &type_vector}, - {7, "-=", "SUBSTOREP_F", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_float}, - {7, "-=", "SUBSTOREP_V", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_vector, &type_vector}, - - {7, "", "FETCH_GBL_F", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {7, "", "FETCH_GBL_V", -1, ASSOC_LEFT, &type_vector, &type_float, &type_vector}, - {7, "", "FETCH_GBL_S", -1, ASSOC_LEFT, &type_string, &type_float, &type_string}, - {7, "", "FETCH_GBL_E", -1, ASSOC_LEFT, &type_entity, &type_float, &type_entity}, - {7, "", "FETCH_GBL_FNC", -1, ASSOC_LEFT, &type_function, &type_float, &type_function}, - - {7, "", "CSTATE", -1, ASSOC_LEFT, &type_float, &type_float, &type_void}, - - {7, "", "CWSTATE", -1, ASSOC_LEFT, &type_float, &type_float, &type_void}, - - {7, "", "THINKTIME", -1, ASSOC_LEFT, &type_entity, &type_float, &type_void}, - - {7, "|=", "BITSET_F", 6, ASSOC_RIGHT, &type_float, &type_float, &type_float}, - {7, "|=", "BITSETP_F", 6, ASSOC_RIGHT, &type_pointer, &type_float, &type_float}, - {7, "&~=", "BITCLR_F", 6, ASSOC_RIGHT, &type_float, &type_float, &type_float}, - {7, "&~=", "BITCLRP_F", 6, ASSOC_RIGHT, &type_pointer, &type_float, &type_float}, - - {7, "", "RAND0", -1, ASSOC_LEFT, &type_void, &type_void, &type_float}, - {7, "", "RAND1", -1, ASSOC_LEFT, &type_float, &type_void, &type_float}, - {7, "", "RAND2", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - {7, "", "RANDV0", -1, ASSOC_LEFT, &type_void, &type_void, &type_vector}, - {7, "", "RANDV1", -1, ASSOC_LEFT, &type_vector, &type_void, &type_vector}, - {7, "", "RANDV2", -1, ASSOC_LEFT, &type_vector, &type_vector, &type_vector}, - - {7, "", "SWITCH_F", -1, ASSOC_LEFT, &type_void, NULL, &type_void}, - {7, "", "SWITCH_V", -1, ASSOC_LEFT, &type_void, NULL, &type_void}, - {7, "", "SWITCH_S", -1, ASSOC_LEFT, &type_void, NULL, &type_void}, - {7, "", "SWITCH_E", -1, ASSOC_LEFT, &type_void, NULL, &type_void}, - {7, "", "SWITCH_FNC", -1, ASSOC_LEFT, &type_void, NULL, &type_void}, - - {7, "", "CASE", -1, ASSOC_LEFT, &type_void, NULL, &type_void}, - {7, "", "CASERANGE", -1, ASSOC_LEFT, &type_void, &type_void, NULL}, - - -//Later are additions by DMW. - - {7, "", "CALL1H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_void}, - {7, "", "CALL2H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_vector}, - {7, "", "CALL3H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_vector}, - {7, "", "CALL4H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_vector}, - {7, "", "CALL5H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_vector}, - {7, "", "CALL6H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_vector}, - {7, "", "CALL7H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_vector}, - {7, "", "CALL8H", -1, ASSOC_LEFT, &type_function, &type_vector, &type_vector}, - - {7, "=", "STORE_I", 6, ASSOC_RIGHT, &type_integer, &type_integer, &type_integer}, - {7, "=", "STORE_IF", 6, ASSOC_RIGHT, &type_integer, &type_float, &type_integer}, - {7, "=", "STORE_FI", 6, ASSOC_RIGHT, &type_float, &type_integer, &type_float}, - - {7, "+", "ADD_I", 4, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "+", "ADD_FI", 4, ASSOC_LEFT, &type_float, &type_integer, &type_float}, - {7, "+", "ADD_IF", 4, ASSOC_LEFT, &type_integer, &type_float, &type_float}, - - {7, "-", "SUB_I", 4, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "-", "SUB_FI", 4, ASSOC_LEFT, &type_float, &type_integer, &type_float}, - {7, "-", "SUB_IF", 4, ASSOC_LEFT, &type_integer, &type_float, &type_float}, - - {7, "", "C_ITOF", -1, ASSOC_LEFT, &type_integer, &type_void, &type_float}, - {7, "", "C_FTOI", -1, ASSOC_LEFT, &type_float, &type_void, &type_integer}, - {7, "", "CP_ITOF", -1, ASSOC_LEFT, &type_pointer, &type_integer, &type_float}, - {7, "", "CP_FTOI", -1, ASSOC_LEFT, &type_pointer, &type_float, &type_integer}, - - {7, ".", "INDIRECT", 1, ASSOC_LEFT, &type_entity, &type_field, &type_integer}, - {7, "=", "STOREP_I", 6, ASSOC_RIGHT, &type_pointer, &type_integer, &type_integer}, - {7, "=", "STOREP_IF", 6, ASSOC_RIGHT, &type_pointer, &type_float, &type_integer}, - {7, "=", "STOREP_FI", 6, ASSOC_RIGHT, &type_pointer, &type_integer, &type_float}, - - {7, "&", "BITAND_I", 3, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "|", "BITOR_I", 3, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - - {7, "*", "MUL_I", 3, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "/", "DIV_I", 3, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "==", "EQ_I", 5, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "!=", "NE_I", 5, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - - {7, "", "IFNOTS", -1, ASSOC_RIGHT, &type_string, NULL, &type_void}, - {7, "", "IFS", -1, ASSOC_RIGHT, &type_string, NULL, &type_void}, - - {7, "!", "NOT_I", -1, ASSOC_LEFT, &type_integer, &type_void, &type_integer}, - - {7, "/", "DIV_VF", 3, ASSOC_LEFT, &type_vector, &type_float, &type_float}, - - {7, "^", "XOR_I", 3, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, ">>", "RSHIFT_I", 3, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "<<", "LSHIFT_I", 3, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - - //var, offset return - {7, "", "GET_POINTER", -1, ASSOC_LEFT, &type_float, &type_integer, &type_pointer}, - {7, "", "ARRAY_OFS", -1, ASSOC_LEFT, &type_pointer, &type_integer, &type_pointer}, - - {7, "=", "LOADA_F", 6, ASSOC_LEFT, &type_float, &type_integer, &type_float}, - {7, "=", "LOADA_V", 6, ASSOC_LEFT, &type_vector, &type_integer, &type_vector}, - {7, "=", "LOADA_S", 6, ASSOC_LEFT, &type_string, &type_integer, &type_string}, - {7, "=", "LOADA_ENT", 6, ASSOC_LEFT, &type_entity, &type_integer, &type_entity}, - {7, "=", "LOADA_FLD", 6, ASSOC_LEFT, &type_field, &type_integer, &type_field}, - {7, "=", "LOADA_FNC", 6, ASSOC_LEFT, &type_function, &type_integer, &type_function}, - {7, "=", "LOADA_I", 6, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - - {7, "=", "STORE_P", 6, ASSOC_RIGHT, &type_pointer, &type_pointer, &type_void}, - {7, ".", "INDIRECT_P", 1, ASSOC_LEFT, &type_entity, &type_field, &type_pointer}, - - {7, "=", "LOADP_F", 6, ASSOC_LEFT, &type_pointer, &type_integer, &type_float}, - {7, "=", "LOADP_V", 6, ASSOC_LEFT, &type_pointer, &type_integer, &type_vector}, - {7, "=", "LOADP_S", 6, ASSOC_LEFT, &type_pointer, &type_integer, &type_string}, - {7, "=", "LOADP_ENT", 6, ASSOC_LEFT, &type_pointer, &type_integer, &type_entity}, - {7, "=", "LOADP_FLD", 6, ASSOC_LEFT, &type_pointer, &type_integer, &type_field}, - {7, "=", "LOADP_FNC", 6, ASSOC_LEFT, &type_pointer, &type_integer, &type_function}, - {7, "=", "LOADP_I", 6, ASSOC_LEFT, &type_pointer, &type_integer, &type_integer}, - - - {7, "<=", "LE_I", 5, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, ">=", "GE_I", 5, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, "<", "LT_I", 5, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - {7, ">", "GT_I", 5, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, - - {7, "<=", "LE_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, - {7, ">=", "GE_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, - {7, "<", "LT_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, - {7, ">", "GT_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, - - {7, "<=", "LE_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_integer}, - {7, ">=", "GE_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_integer}, - {7, "<", "LT_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_integer}, - {7, ">", "GT_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_integer}, - - {7, "==", "EQ_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, - {7, "==", "EQ_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_float}, - - //------------------------------------- - //string manipulation. - {7, "+", "ADD_SF", 4, ASSOC_LEFT, &type_string, &type_float, &type_string}, - {7, "-", "SUB_S", 4, ASSOC_LEFT, &type_string, &type_string, &type_float}, - {7, "", "STOREP_C", 1, ASSOC_RIGHT, &type_string, &type_float, &type_float}, - {7, "", "LOADP_C", 1, ASSOC_LEFT, &type_string, &type_void, &type_float}, - //------------------------------------- - - - -{7, "*", "MUL_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, -{7, "*", "MUL_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_float}, -{7, "*", "MUL_VI", 5, ASSOC_LEFT, &type_vector, &type_integer, &type_vector}, -{7, "*", "MUL_IV", 5, ASSOC_LEFT, &type_integer, &type_vector, &type_vector}, - -{7, "/", "DIV_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, -{7, "/", "DIV_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_float}, - -{7, "&", "BITAND_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, -{7, "|", "BITOR_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, -{7, "&", "BITAND_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_float}, -{7, "|", "BITOR_FI", 5, ASSOC_LEFT, &type_float, &type_integer, &type_float}, - -{7, "&&", "AND_I", 7, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, -{7, "||", "OR_I", 7, ASSOC_LEFT, &type_integer, &type_integer, &type_integer}, -{7, "&&", "AND_IF", 7, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, -{7, "||", "OR_IF", 7, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, -{7, "&&", "AND_FI", 7, ASSOC_LEFT, &type_float, &type_integer, &type_integer}, -{7, "||", "OR_FI", 7, ASSOC_LEFT, &type_float, &type_integer, &type_integer}, -{7, "!=", "NE_IF", 5, ASSOC_LEFT, &type_integer, &type_float, &type_integer}, -{7, "!=", "NE_FI", 5, ASSOC_LEFT, &type_float, &type_float, &type_integer}, - - - - - - -{7, "<>", "GSTOREP_I", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GSTOREP_F", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GSTOREP_ENT", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GSTOREP_FLD", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GSTOREP_S", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GSTOREP_FNC", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GSTOREP_V", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - -{7, "<>", "GADDRESS", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - -{7, "<>", "GLOAD_I", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GLOAD_F", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GLOAD_FLD", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GLOAD_ENT", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GLOAD_S", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, -{7, "<>", "GLOAD_FNC", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - -{7, "<>", "BOUNDCHECK", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - -{7, "=", "STOREP_P", 6, ASSOC_RIGHT, &type_pointer, &type_pointer, &type_void}, -{7, "", "PUSH", -1, ASSOC_RIGHT, &type_float, &type_void, &type_pointer}, -{7, "", "POP", -1, ASSOC_RIGHT, &type_float, &type_void, &type_void}, - -{7, "", "SWITCH_I", -1, ASSOC_LEFT, &type_void, NULL, &type_void}, -{7, "<>", "GLOAD_S", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - -{6, "", "IF_F", -1, ASSOC_RIGHT, &type_float, NULL, &type_void}, -{6, "","IFNOT_F", -1, ASSOC_RIGHT, &type_float, NULL, &type_void}, - -/* emulated ops begin here */ - {7, "<>", "OP_EMULATED", -1, ASSOC_LEFT, &type_float, &type_float, &type_float}, - - - {7, "|=", "BITSET_I", 6, ASSOC_RIGHT, &type_integer, &type_integer, &type_integer}, - {7, "|=", "BITSETP_I", 6, ASSOC_RIGHT, &type_pointer, &type_integer, &type_integer}, - - - {7, "*=", "MULSTORE_I", 6, ASSOC_RIGHT_RESULT, &type_integer, &type_integer, &type_integer}, - {7, "/=", "DIVSTORE_I", 6, ASSOC_RIGHT_RESULT, &type_integer, &type_integer, &type_integer}, - {7, "+=", "ADDSTORE_I", 6, ASSOC_RIGHT_RESULT, &type_integer, &type_integer, &type_integer}, - {7, "-=", "SUBSTORE_I", 6, ASSOC_RIGHT_RESULT, &type_integer, &type_integer, &type_integer}, - - {7, "*=", "MULSTOREP_I", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_integer}, - {7, "/=", "DIVSTOREP_I", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_integer}, - {7, "+=", "ADDSTOREP_I", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_integer}, - {7, "-=", "SUBSTOREP_I", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_integer}, - - {7, "*=", "OP_MULSTORE_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - {7, "*=", "OP_MULSTOREP_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - {7, "/=", "OP_DIVSTORE_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - {7, "/=", "OP_DIVSTOREP_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - {7, "+=", "OP_ADDSTORE_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - {7, "+=", "OP_ADDSTOREP_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - {7, "-=", "OP_SUBSTORE_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - {7, "-=", "OP_SUBSTOREP_IF", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_float, &type_integer}, - - {7, "*=", "OP_MULSTORE_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - {7, "*=", "OP_MULSTOREP_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - {7, "/=", "OP_DIVSTORE_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - {7, "/=", "OP_DIVSTOREP_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - {7, "+=", "OP_ADDSTORE_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - {7, "+=", "OP_ADDSTOREP_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - {7, "-=", "OP_SUBSTORE_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - {7, "-=", "OP_SUBSTOREP_FI", 6, ASSOC_RIGHT_RESULT, &type_pointer, &type_integer, &type_float}, - - {0, NULL} -}; - - -pbool OpAssignsToC(unsigned int op) -{ - // calls, switches and cases DON'T - if(pr_opcodes[op].type_c == &type_void) - return false; - if(op >= OP_SWITCH_F && op <= OP_CALL8H) - return false; - if(op >= OP_RAND0 && op <= OP_RANDV2) - return false; - // they use a and b, but have 3 types - // safety - if(op >= OP_BITSET && op <= OP_BITCLRP) - return false; - /*if(op >= OP_STORE_I && op <= OP_STORE_FI) - return false; <- add STOREP_*?*/ - if(op == OP_STOREP_C || op == OP_LOADP_C) - return false; - if(op >= OP_MULSTORE_F && op <= OP_SUBSTOREP_V) - return false; - return true; -} -pbool OpAssignsToB(unsigned int op) -{ - if(op >= OP_BITSET && op <= OP_BITCLRP) - return true; - if(op >= OP_STORE_I && op <= OP_STORE_FI) - return true; - if(op == OP_STOREP_C || op == OP_LOADP_C) - return true; - if(op >= OP_MULSTORE_F && op <= OP_SUBSTOREP_V) - return true; - if(op >= OP_STORE_F && op <= OP_STOREP_FNC) - return true; - return false; -} -/*pbool OpAssignedTo(QCC_def_t *v, unsigned int op) -{ - if(OpAssignsToC(op)) - { - } - else if(OpAssignsToB(op)) - { - } - return false; -} -*/ -#undef ASSOC_RIGHT_RESULT - -#define TOP_PRIORITY 7 -#define UNARY_PRIORITY 1 -#define NOT_PRIORITY 5 -//conditional and/or -#define CONDITION_PRIORITY 7 - - -//this system cuts out 10/120 -//these evaluate as top first. -QCC_opcode_t *opcodeprioritized[TOP_PRIORITY+1][128] = -{ - { //don't use -/* &pr_opcodes[OP_DONE], - &pr_opcodes[OP_RETURN], - - &pr_opcodes[OP_NOT_F], - &pr_opcodes[OP_NOT_V], - &pr_opcodes[OP_NOT_S], - &pr_opcodes[OP_NOT_ENT], - &pr_opcodes[OP_NOT_FNC], - - &pr_opcodes[OP_IF], - &pr_opcodes[OP_IFNOT], - &pr_opcodes[OP_CALL0], - &pr_opcodes[OP_CALL1], - &pr_opcodes[OP_CALL2], - &pr_opcodes[OP_CALL3], - &pr_opcodes[OP_CALL4], - &pr_opcodes[OP_CALL5], - &pr_opcodes[OP_CALL6], - &pr_opcodes[OP_CALL7], - &pr_opcodes[OP_CALL8], - &pr_opcodes[OP_STATE], - &pr_opcodes[OP_GOTO], - - &pr_opcodes[OP_IFNOTS], - &pr_opcodes[OP_IFS], - - &pr_opcodes[OP_NOT_I], -*/ NULL - }, { //1 - - &pr_opcodes[OP_LOAD_F], - &pr_opcodes[OP_LOAD_V], - &pr_opcodes[OP_LOAD_S], - &pr_opcodes[OP_LOAD_ENT], - &pr_opcodes[OP_LOAD_FLD], - &pr_opcodes[OP_LOAD_FNC], - &pr_opcodes[OP_LOAD_I], - &pr_opcodes[OP_LOAD_P], - &pr_opcodes[OP_ADDRESS], - NULL - }, { //2 -/* //conversion. don't use - &pr_opcodes[OP_C_ITOF], - &pr_opcodes[OP_C_FTOI], - &pr_opcodes[OP_CP_ITOF], - &pr_opcodes[OP_CP_FTOI], -*/ NULL - }, { //3 - &pr_opcodes[OP_MUL_F], - &pr_opcodes[OP_MUL_V], - &pr_opcodes[OP_MUL_FV], - &pr_opcodes[OP_MUL_VF], - &pr_opcodes[OP_MUL_I], - - &pr_opcodes[OP_DIV_F], - &pr_opcodes[OP_DIV_I], - &pr_opcodes[OP_DIV_VF], - - &pr_opcodes[OP_BITAND], - &pr_opcodes[OP_BITAND_I], - &pr_opcodes[OP_BITAND_IF], - &pr_opcodes[OP_BITAND_FI], - - &pr_opcodes[OP_BITOR], - &pr_opcodes[OP_BITOR_I], - &pr_opcodes[OP_BITOR_IF], - &pr_opcodes[OP_BITOR_FI], - - &pr_opcodes[OP_XOR_I], - &pr_opcodes[OP_RSHIFT_I], - &pr_opcodes[OP_LSHIFT_I], - - NULL - }, { //4 - - &pr_opcodes[OP_ADD_F], - &pr_opcodes[OP_ADD_V], - &pr_opcodes[OP_ADD_I], - &pr_opcodes[OP_ADD_FI], - &pr_opcodes[OP_ADD_IF], - &pr_opcodes[OP_ADD_SF], - - &pr_opcodes[OP_SUB_F], - &pr_opcodes[OP_SUB_V], - &pr_opcodes[OP_SUB_I], - &pr_opcodes[OP_SUB_FI], - &pr_opcodes[OP_SUB_IF], - &pr_opcodes[OP_SUB_S], - NULL - }, { //5 - - &pr_opcodes[OP_EQ_F], - &pr_opcodes[OP_EQ_V], - &pr_opcodes[OP_EQ_S], - &pr_opcodes[OP_EQ_E], - &pr_opcodes[OP_EQ_FNC], - &pr_opcodes[OP_EQ_I], - &pr_opcodes[OP_EQ_IF], - &pr_opcodes[OP_EQ_FI], - - &pr_opcodes[OP_NE_F], - &pr_opcodes[OP_NE_V], - &pr_opcodes[OP_NE_S], - &pr_opcodes[OP_NE_E], - &pr_opcodes[OP_NE_FNC], - &pr_opcodes[OP_NE_I], - &pr_opcodes[OP_NE_IF], - &pr_opcodes[OP_NE_FI], - - &pr_opcodes[OP_LE], - &pr_opcodes[OP_LE_I], - &pr_opcodes[OP_LE_IF], - &pr_opcodes[OP_LE_FI], - &pr_opcodes[OP_GE], - &pr_opcodes[OP_GE_I], - &pr_opcodes[OP_GE_IF], - &pr_opcodes[OP_GE_FI], - &pr_opcodes[OP_LT], - &pr_opcodes[OP_LT_I], - &pr_opcodes[OP_LT_IF], - &pr_opcodes[OP_LT_FI], - &pr_opcodes[OP_GT], - &pr_opcodes[OP_GT_I], - &pr_opcodes[OP_GT_IF], - &pr_opcodes[OP_GT_FI], - - NULL - }, { //6 - &pr_opcodes[OP_STORE_F], - &pr_opcodes[OP_STORE_V], - &pr_opcodes[OP_STORE_S], - &pr_opcodes[OP_STORE_ENT], - &pr_opcodes[OP_STORE_FLD], - &pr_opcodes[OP_STORE_FNC], - &pr_opcodes[OP_STORE_I], - &pr_opcodes[OP_STORE_IF], - &pr_opcodes[OP_STORE_FI], - &pr_opcodes[OP_STORE_P], - - &pr_opcodes[OP_STOREP_F], - &pr_opcodes[OP_STOREP_V], - &pr_opcodes[OP_STOREP_S], - &pr_opcodes[OP_STOREP_ENT], - &pr_opcodes[OP_STOREP_FLD], - &pr_opcodes[OP_STOREP_FNC], - &pr_opcodes[OP_STOREP_I], - &pr_opcodes[OP_STOREP_IF], - &pr_opcodes[OP_STOREP_FI], - &pr_opcodes[OP_STOREP_P], - - &pr_opcodes[OP_DIVSTORE_F], - &pr_opcodes[OP_DIVSTORE_I], - &pr_opcodes[OP_DIVSTORE_FI], - &pr_opcodes[OP_DIVSTORE_IF], - &pr_opcodes[OP_DIVSTOREP_F], - &pr_opcodes[OP_DIVSTOREP_I], - &pr_opcodes[OP_DIVSTOREP_IF], - &pr_opcodes[OP_DIVSTOREP_FI], - &pr_opcodes[OP_MULSTORE_F], - &pr_opcodes[OP_MULSTORE_V], - &pr_opcodes[OP_MULSTORE_I], - &pr_opcodes[OP_MULSTORE_IF], - &pr_opcodes[OP_MULSTORE_FI], - &pr_opcodes[OP_MULSTOREP_F], - &pr_opcodes[OP_MULSTOREP_V], - &pr_opcodes[OP_MULSTOREP_I], - &pr_opcodes[OP_MULSTOREP_IF], - &pr_opcodes[OP_MULSTOREP_FI], - &pr_opcodes[OP_ADDSTORE_F], - &pr_opcodes[OP_ADDSTORE_V], - &pr_opcodes[OP_ADDSTORE_I], - &pr_opcodes[OP_ADDSTORE_IF], - &pr_opcodes[OP_ADDSTORE_FI], - &pr_opcodes[OP_ADDSTOREP_F], - &pr_opcodes[OP_ADDSTOREP_V], - &pr_opcodes[OP_ADDSTOREP_I], - &pr_opcodes[OP_ADDSTOREP_IF], - &pr_opcodes[OP_ADDSTOREP_FI], - &pr_opcodes[OP_SUBSTORE_F], - &pr_opcodes[OP_SUBSTORE_V], - &pr_opcodes[OP_SUBSTORE_I], - &pr_opcodes[OP_SUBSTORE_IF], - &pr_opcodes[OP_SUBSTORE_FI], - &pr_opcodes[OP_SUBSTOREP_F], - &pr_opcodes[OP_SUBSTOREP_V], - &pr_opcodes[OP_SUBSTOREP_I], - &pr_opcodes[OP_SUBSTOREP_IF], - &pr_opcodes[OP_SUBSTOREP_FI], - - &pr_opcodes[OP_BITSET], - &pr_opcodes[OP_BITSET_I], -// &pr_opcodes[OP_BITSET_IF], -// &pr_opcodes[OP_BITSET_FI], - &pr_opcodes[OP_BITSETP], - &pr_opcodes[OP_BITSETP_I], -// &pr_opcodes[OP_BITSETP_IF], -// &pr_opcodes[OP_BITSETP_FI], - &pr_opcodes[OP_BITCLR], - &pr_opcodes[OP_BITCLRP], - - NULL - }, { //7 - &pr_opcodes[OP_AND], - &pr_opcodes[OP_AND_I], - &pr_opcodes[OP_AND_IF], - &pr_opcodes[OP_AND_FI], - &pr_opcodes[OP_OR], - &pr_opcodes[OP_OR_I], - &pr_opcodes[OP_OR_IF], - &pr_opcodes[OP_OR_FI], - NULL - } -}; - -pbool QCC_OPCodeValid(QCC_opcode_t *op) -{ - int num; - num = op - pr_opcodes; - - switch(qcc_targetformat) - { - case QCF_STANDARD: - case QCF_KK7: - if (num < OP_MULSTORE_F) - return true; - return false; - case QCF_HEXEN2: - if (num >= OP_SWITCH_V && num <= OP_SWITCH_FNC) //these were assigned numbers but were never actually implemtented in standard h2. - return false; -// if (num >= OP_MULSTORE_F && num <= OP_SUBSTOREP_V) -// return false; - if (num <= OP_CALL8H) //CALLXH are fixed up. This is to provide more dynamic switching...?? - return true; - return false; - case QCF_FTE: - case QCF_FTEDEBUG: - //no emulated opcodes - if (num >= OP_NUMREALOPS) - return false; - return true; - case QCF_DARKPLACES: - //all id opcodes. - if (num < OP_MULSTORE_F) - return true; - - //no emulated opcodes - if (num >= OP_NUMREALOPS) - return false; - - //extended opcodes. - //DPFIXME: this is a list of the extended opcodes. I was conservative regarding supported ones. - // at the time of writing, these are the ones that look like they'll work just fine in Blub\0's patch. - // the ones that looked too permissive with bounds checks, or would give false positives are disabled. - // if the DP guys want I can change them as desired. - switch(num) - { - //maths and conditionals (simple opcodes that read from specific globals and write to a global) - case OP_ADD_I: - case OP_ADD_IF: - case OP_ADD_FI: - case OP_SUB_I: - case OP_SUB_IF: - case OP_SUB_FI: - case OP_MUL_I: - case OP_MUL_IF: - case OP_MUL_FI: - case OP_MUL_VI: - case OP_DIV_VF: - case OP_DIV_I: - case OP_DIV_IF: - case OP_DIV_FI: - case OP_BITAND_I: - case OP_BITOR_I: - case OP_BITAND_IF: - case OP_BITOR_IF: - case OP_BITAND_FI: - case OP_BITOR_FI: - case OP_GE_I: - case OP_LE_I: - case OP_GT_I: - case OP_LT_I: - case OP_AND_I: - case OP_OR_I: - case OP_GE_IF: - case OP_LE_IF: - case OP_GT_IF: - case OP_LT_IF: - case OP_AND_IF: - case OP_OR_IF: - case OP_GE_FI: - case OP_LE_FI: - case OP_GT_FI: - case OP_LT_FI: - case OP_AND_FI: - case OP_OR_FI: - case OP_NOT_I: - case OP_EQ_I: - case OP_EQ_IF: - case OP_EQ_FI: - case OP_NE_I: - case OP_NE_IF: - case OP_NE_FI: - return true; - - //stores into a pointer (generated from 'ent.field=XXX') - case OP_STOREP_I: //no worse than the other OP_STOREP_X functions - case OP_STOREP_P: - //reads from an entity field - case OP_LOAD_I: //no worse than the other OP_LOAD_X functions. - case OP_LOAD_P: - return true; - - //stores into the globals array. - //they can change any global dynamically, but thats no security risk. - //fteqcc will not automatically generate these. - //fteqw does not support them either. - case OP_GSTOREP_I: - case OP_GSTOREP_F: - case OP_GSTOREP_ENT: - case OP_GSTOREP_FLD: - case OP_GSTOREP_S: - case OP_GSTOREP_FNC: - case OP_GSTOREP_V: - return true; - - //this opcode looks weird - case OP_GADDRESS://floatc = globals[inta + floatb] (fte does not support) - return true; - - //fteqcc will not automatically generate these - //fteqw does not support them either, for that matter. - case OP_GLOAD_I://c = globals[inta] - case OP_GLOAD_F://note: fte does not support these - case OP_GLOAD_FLD: - case OP_GLOAD_ENT: - case OP_GLOAD_S: - case OP_GLOAD_FNC: - return true; - case OP_GLOAD_V: - return false; //DPFIXME: this is commented out in the patch I was given a link to... because the opcode wasn't defined. - - //these are reportedly functional. - case OP_CALL8H: - case OP_CALL7H: - case OP_CALL6H: - case OP_CALL5H: - case OP_CALL4H: - case OP_CALL3H: - case OP_CALL2H: - case OP_CALL1H: - return true; - - case OP_RAND0: - case OP_RAND1: - case OP_RAND2: - case OP_RANDV0: - case OP_RANDV1: - case OP_RANDV2: - return true; - - case OP_BITSET: // b |= a - case OP_BITCLR: // b &= ~a - case OP_BITSETP: // *b |= a - case OP_BITCLRP: // *b &= ~a - return false; //FIXME: I do not fully follow the controversy over these. - - case OP_SWITCH_F: - case OP_SWITCH_V: - case OP_SWITCH_S: - case OP_SWITCH_E: - case OP_SWITCH_FNC: - case OP_CASE: - case OP_CASERANGE: - return true; - - //assuming the pointers here are fine, the return values are a little strange. - //but its fine - case OP_ADDSTORE_F: - case OP_ADDSTORE_V: - case OP_ADDSTOREP_F: // e.f += f - case OP_ADDSTOREP_V: // e.v += v - case OP_SUBSTORE_F: - case OP_SUBSTORE_V: - case OP_SUBSTOREP_F: // e.f += f - case OP_SUBSTOREP_V: // e.v += v - return true; - - case OP_LOADA_I: - case OP_LOADA_F: - case OP_LOADA_FLD: - case OP_LOADA_ENT: - case OP_LOADA_S: - case OP_LOADA_FNC: - case OP_LOADA_V: - return false; //DPFIXME: DP does not bounds check these properly. I won't generate them. - - case OP_CONV_ITOF: - case OP_CONV_FTOI: - return true; //these look fine. - - case OP_STOREP_C: // store a char in a string - return false; //DPFIXME: dp's bounds check may give false positives with expected uses. - - case OP_MULSTORE_F: - case OP_MULSTORE_V: - case OP_MULSTOREP_F: - case OP_MULSTOREP_V: // e.v *= f - case OP_DIVSTORE_F: - case OP_DIVSTOREP_F: - case OP_STORE_IF: - case OP_STORE_FI: - case OP_STORE_P: - case OP_STOREP_IF: // store a value to a pointer - case OP_STOREP_FI: - case OP_IFNOT_S: - case OP_IF_S: - return true; - - case OP_IFNOT_F: //added, but not in dp yet - case OP_IF_F: - return false; - - case OP_CP_ITOF: - case OP_CP_FTOI: - return false; //DPFIXME: These are not bounds checked at all. - case OP_GLOBALADDRESS: - return true; //DPFIXME: DP will reject these pointers if they are ever used. - case OP_POINTER_ADD: - return true; //just maths. - - case OP_ADD_SF: //(char*)c = (char*)a + (float)b - case OP_SUB_S: //(float)c = (char*)a - (char*)b - return true; - case OP_LOADP_C: //load character from a string - return false; //DPFIXME: DP looks like it'll reject these or wrongly allow. - - case OP_LOADP_I: - case OP_LOADP_F: - case OP_LOADP_FLD: - case OP_LOADP_ENT: - case OP_LOADP_S: - case OP_LOADP_FNC: - case OP_LOADP_V: - return true; - - case OP_XOR_I: - case OP_RSHIFT_I: - case OP_LSHIFT_I: - return true; - - case OP_FETCH_GBL_F: - case OP_FETCH_GBL_S: - case OP_FETCH_GBL_E: - case OP_FETCH_GBL_FNC: - case OP_FETCH_GBL_V: - return false; //DPFIXME: DP will not bounds check this properly, it is too permissive. - case OP_CSTATE: - case OP_CWSTATE: - return false; //DP does not support this hexenc opcode. - case OP_THINKTIME: - return true; //but it does support this one. - - default: //anything I forgot to mention is new. - return false; - } - } - return false; -} - -#define EXPR_WARN_ABOVE_1 2 -#define EXPR_DISALLOW_COMMA 4 -QCC_def_t *QCC_PR_Expression (int priority, int exprflags); -int QCC_AStatementJumpsTo(int targ, int first, int last); -pbool QCC_StatementIsAJump(int stnum, int notifdest); - -temp_t *functemps; //floats/strings/funcs/ents... - -//=========================================================================== - - -/* -============ -PR_Statement - -Emits a primitive statement, returning the var it places it's value in -============ -*/ -QCC_def_t *QCC_PR_Statement ( QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_b, QCC_dstatement_t **outstatement); -static int QCC_ShouldConvert(QCC_def_t *var, etype_t wanted) -{ - if (var->type->type == ev_integer && wanted == ev_function) - return 0; - if (var->type->type == ev_pointer && var->type->aux_type) - { - if (var->type->aux_type->type == ev_float && wanted == ev_integer) - return OP_CP_FTOI; - - if (var->type->aux_type->type == ev_integer && wanted == ev_float) - return OP_CP_ITOF; - } - else - { - if (var->type->type == ev_float && wanted == ev_integer) - return OP_CONV_FTOI; - - if (var->type->type == ev_integer && wanted == ev_float) - return OP_CONV_ITOF; - } - - return -1; -} -QCC_def_t *QCC_SupplyConversion(QCC_def_t *var, etype_t wanted) -{ - int o; - - if (pr_classtype && var->type->type == ev_field && wanted != ev_field) - { - if (pr_classtype) - { //load self.var into a temp - QCC_def_t *self; - self = QCC_PR_GetDef(type_entity, "self", NULL, true, 1, false); - switch(wanted) - { - case ev_float: - return QCC_PR_Statement(pr_opcodes+OP_LOAD_F, self, var, NULL); - case ev_string: - return QCC_PR_Statement(pr_opcodes+OP_LOAD_S, self, var, NULL); - case ev_function: - return QCC_PR_Statement(pr_opcodes+OP_LOAD_FNC, self, var, NULL); - case ev_vector: - return QCC_PR_Statement(pr_opcodes+OP_LOAD_V, self, var, NULL); - case ev_entity: - return QCC_PR_Statement(pr_opcodes+OP_LOAD_ENT, self, var, NULL); - default: - QCC_Error(ERR_INTERNAL, "Inexplicit field load failed, try explicit"); - } - } - } - - o = QCC_ShouldConvert(var, wanted); - - if (o <= 0) //no conversion - return var; - - - return QCC_PR_Statement(&pr_opcodes[o], var, NULL, NULL); //conversion return value -} -QCC_def_t *QCC_MakeStringDef(char *value); -QCC_def_t *QCC_MakeFloatDef(float value); -QCC_def_t *QCC_MakeIntDef(int value); -QCC_def_t *QCC_MakeVectorDef(float a, float b, float c); - -typedef struct freeoffset_s { - struct freeoffset_s *next; - gofs_t ofs; - unsigned int size; -} freeoffset_t; - -freeoffset_t *freeofs; - -//assistant functions. This can safly be bipassed with the old method for more complex things. -gofs_t QCC_GetFreeOffsetSpace(unsigned int size) -{ - int ofs; - if (opt_locals_marshalling) - { - freeoffset_t *fofs, *prev; - for (fofs = freeofs, prev = NULL; fofs; fofs=fofs->next) - { - if (fofs->size == size) - { - if (prev) - prev->next = fofs->next; - else - freeofs = fofs->next; - - return fofs->ofs; - } - prev = fofs; - } - for (fofs = freeofs, prev = NULL; fofs; fofs=fofs->next) - { - if (fofs->size > size) - { - fofs->size -= size; - fofs->ofs += size; - - return fofs->ofs-size; - } - prev = fofs; - } - } - - ofs = numpr_globals; - numpr_globals+=size; - - if (numpr_globals >= MAX_REGS) - { - if (!opt_overlaptemps || !opt_locals_marshalling) - QCC_Error(ERR_TOOMANYGLOBALS, "numpr_globals exceeded MAX_REGS - you'll need to use more optimisations"); - else - QCC_Error(ERR_TOOMANYGLOBALS, "numpr_globals exceeded MAX_REGS"); - } - - return ofs; -} - -void QCC_FreeOffset(gofs_t ofs, unsigned int size) -{ - freeoffset_t *fofs; - if (ofs+size == numpr_globals) - { //fixme: is this a bug? - numpr_globals -= size; - return; - } - - for (fofs = freeofs; fofs; fofs=fofs->next) - { - //fixme: if this means the last block becomes free, free them all. - if (fofs->ofs == ofs + size) - { - fofs->ofs -= size; - fofs->size += size; - return; - } - if (fofs->ofs+fofs->size == ofs) - { - fofs->size += size; - return; - } - } - - fofs = qccHunkAlloc(sizeof(freeoffset_t)); - fofs->next = freeofs; - fofs->ofs = ofs; - fofs->size = size; - - freeofs = fofs; - return; -} - -static QCC_def_t *QCC_GetTemp(QCC_type_t *type) -{ -//#define CRAZYTEMPOPTS //not worth it. saves 2 temps with hexen2 (without even touching numpr_globals) - QCC_def_t *var_c; - temp_t *t; -#ifdef CRAZYTEMPOPTS - temp_t *best = NULL; -#endif - - var_c = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - memset (var_c, 0, sizeof(QCC_def_t)); - var_c->type = type; - var_c->name = "temp"; - - if (opt_overlaptemps) //don't exceed. This lets us allocate a huge block, and still be able to compile smegging big funcs. - { - for (t = functemps; t; t = t->next) - { - if (!t->used && t->size == type->size) - { -#ifdef CRAZYTEMPOPTS - best = t; - if (t->scope == pr_scope) -#endif - break; - } - } -#ifdef CRAZYTEMPOPTS - t = best; -#endif - if (t && t->scope && t->scope != pr_scope) - QCC_Error(ERR_INTERNAL, "Internal error temp has scope not equal to current scope"); - - if (!t) - { - //allocate a new one - t = qccHunkAlloc(sizeof(temp_t)); - t->size = type->size; - t->next = functemps; - functemps = t; - - t->ofs = QCC_GetFreeOffsetSpace(t->size); - - numtemps+=t->size; - } - else - optres_overlaptemps+=t->size; - //use a previous one. - var_c->ofs = t->ofs; - var_c->temp = t; - t->lastfunc = pr_scope; - } - else if (opt_locals_marshalling) - { - //allocate a new one - t = qccHunkAlloc(sizeof(temp_t)); - t->size = type->size; - - t->next = functemps; - functemps = t; - - t->ofs = QCC_GetFreeOffsetSpace(t->size); - - numtemps+=t->size; - - var_c->ofs = t->ofs; - var_c->temp = t; - t->lastfunc = pr_scope; - } - else - { - // we're not going to reallocate any temps so allocate permanently - var_c->ofs = QCC_GetFreeOffsetSpace(type->size); - numtemps+=type->size; - } - - var_c->s_file = s_file; - var_c->s_line = pr_source_line; - - if (var_c->temp) - var_c->temp->used = true; - - return var_c; -} - -//nothing else references this temp. -static void QCC_FreeTemp(QCC_def_t *t) -{ - if (t && t->temp) - t->temp->used = false; -} - -static void QCC_UnFreeTemp(QCC_def_t *t) -{ - if (t->temp) - t->temp->used = true; -} - -//We've just parsed a statement. -//We can gaurentee that any used temps are now not used. -#ifdef _DEBUG -static void QCC_FreeTemps(void) -{ - temp_t *t; - - if (def_ret.temp && def_ret.temp->used) - { - QCC_PR_ParseWarning(WARN_DEBUGGING, "Return value still in use in %s", pr_scope->name); - def_ret.temp->used = false; - } - - t = functemps; - while(t) - { - if (t->used && !pr_error_count) //don't print this after an error jump out. - { - QCC_PR_ParseWarning(WARN_DEBUGGING, "Temp was used in %s", pr_scope->name); - t->used = false; - } - t = t->next; - } -} -#else -#define QCC_FreeTemps() -#endif - -//temps that are still in use over a function call can be considered dodgy. -//we need to remap these to locally defined temps, on return from the function so we know we got them all. -static void QCC_LockActiveTemps(void) -{ - temp_t *t; - - t = functemps; - while(t) - { - if (t->used) - t->scope = pr_scope; - t = t->next; - } -} - -static void QCC_LockTemp(QCC_def_t *d) -{ - if (d->temp && d->temp->used) - d->temp->scope = pr_scope; -} - -static void QCC_RemapLockedTemp(temp_t *t, int firststatement, int laststatement) -{ -#ifdef WRITEASM - char buffer[128]; -#endif - - QCC_def_t *def; - int newofs; - QCC_dstatement_t *st; - int i; - - newofs = 0; - for (i = firststatement, st = &statements[i]; i < laststatement; i++, st++) - { - if (pr_opcodes[st->op].type_a && st->a == t->ofs) - { - if (!newofs) - { - newofs = QCC_GetFreeOffsetSpace(t->size); - numtemps+=t->size; - - def = QCC_PR_DummyDef(type_float, NULL, pr_scope, t->size, newofs, false, false); - def->nextlocal = pr.localvars; - def->constant = false; -#ifdef WRITEASM - sprintf(buffer, "locked_%i", t->ofs); - def->name = qccHunkAlloc(strlen(buffer)+1); - strcpy(def->name, buffer); -#endif - pr.localvars = def; - } - st->a = newofs; - } - if (pr_opcodes[st->op].type_b && st->b == t->ofs) - { - if (!newofs) - { - newofs = QCC_GetFreeOffsetSpace(t->size); - numtemps+=t->size; - - def = QCC_PR_DummyDef(type_float, NULL, pr_scope, t->size, newofs, false, false); - def->nextlocal = pr.localvars; - def->constant = false; -#ifdef WRITEASM - sprintf(buffer, "locked_%i", t->ofs); - def->name = qccHunkAlloc(strlen(buffer)+1); - strcpy(def->name, buffer); -#endif - pr.localvars = def; - } - st->b = newofs; - } - if (pr_opcodes[st->op].type_c && st->c == t->ofs) - { - if (!newofs) - { - newofs = QCC_GetFreeOffsetSpace(t->size); - numtemps+=t->size; - - def = QCC_PR_DummyDef(type_float, NULL, pr_scope, t->size, newofs, false, false); - def->nextlocal = pr.localvars; - def->constant = false; -#ifdef WRITEASM - sprintf(buffer, "locked_%i", t->ofs); - def->name = qccHunkAlloc(strlen(buffer)+1); - strcpy(def->name, buffer); -#endif - pr.localvars = def; - } - st->c = newofs; - } - } -} - -static void QCC_RemapLockedTemps(int firststatement, int laststatement) -{ - temp_t *t; - - t = functemps; - while(t) - { - if (t->scope || opt_locals_marshalling) - { - QCC_RemapLockedTemp(t, firststatement, laststatement); - t->scope = NULL; - t->lastfunc = NULL; - } - t = t->next; - } -} - -static void QCC_fprintfLocals(FILE *f, gofs_t paramstart, gofs_t paramend) -{ - QCC_def_t *var; - temp_t *t; - int i; - - for (var = pr.localvars; var; var = var->nextlocal) - { - if (var->ofs >= paramstart && var->ofs < paramend) - continue; - fprintf(f, "local %s %s;\n", TypeName(var->type), var->name); - } - - for (t = functemps, i = 0; t; t = t->next, i++) - { - if (t->lastfunc == pr_scope) - { - fprintf(f, "local %s temp_%i;\n", (t->size == 1)?"float":"vector", i); - } - } -} - -#ifdef WRITEASM -void QCC_WriteAsmFunction(QCC_def_t *sc, unsigned int firststatement, gofs_t firstparm); -static const char *QCC_VarAtOffset(unsigned int ofs, unsigned int size) -{ - static char message[1024]; - QCC_def_t *var; - //check the temps - temp_t *t; - int i; - - for (t = functemps, i = 0; t; t = t->next, i++) - { - if (ofs >= t->ofs && ofs < t->ofs + t->size) - { - if (size < t->size) - sprintf(message, "temp_%i_%c", i, 'x' + (ofs-t->ofs)%3); - else - sprintf(message, "temp_%i", i); - return message; - } - } - - for (var = pr.localvars; var; var = var->nextlocal) - { - if (var->scope && var->scope != pr_scope) - continue; //this should be an error - if (ofs >= var->ofs && ofs < var->ofs + var->type->size) - { - if (*var->name) - { - if (!STRCMP(var->name, "IMMEDIATE")) //continue, don't get bogged down by multiple bits of code - continue; - if (size < var->type->size) - sprintf(message, "%s_%c", var->name, 'x' + (ofs-var->ofs)%3); - else - sprintf(message, "%s", var->name); - return message; - } - } - } - - for (var = pr.def_head.next; var; var = var->next) - { - if (var->scope && var->scope != pr_scope) - continue; - - if (ofs >= var->ofs && ofs < var->ofs + var->type->size) - { - if (*var->name) - { - if (!STRCMP(var->name, "IMMEDIATE")) - { - switch(var->type->type) - { - case ev_string: - sprintf(message, "\"%.1020s\"", &strings[((int *)qcc_pr_globals)[var->ofs]]); - return message; - case ev_integer: - sprintf(message, "%i", ((int *)qcc_pr_globals)[var->ofs]); - return message; - case ev_float: - sprintf(message, "%f", qcc_pr_globals[var->ofs]); - return message; - case ev_vector: - sprintf(message, "'%f %f %f'", qcc_pr_globals[var->ofs], qcc_pr_globals[var->ofs+1], qcc_pr_globals[var->ofs+2]); - return message; - default: - sprintf(message, "IMMEDIATE"); - return message; - } - } - if (size < var->type->size) - sprintf(message, "%s_%c", var->name, 'x' + (ofs-var->ofs)%3); - else - sprintf(message, "%s", var->name); - return message; - } - } - } - - if (size >= 3) - { - if (ofs >= OFS_RETURN && ofs < OFS_PARM0) - sprintf(message, "return"); - else if (ofs >= OFS_PARM0 && ofs < RESERVED_OFS) - sprintf(message, "parm%i", (ofs-OFS_PARM0)/3); - else - sprintf(message, "offset_%i", ofs); - } - else - { - if (ofs >= OFS_RETURN && ofs < OFS_PARM0) - sprintf(message, "return_%c", 'x' + ofs-OFS_RETURN); - else if (ofs >= OFS_PARM0 && ofs < RESERVED_OFS) - sprintf(message, "parm%i_%c", (ofs-OFS_PARM0)/3, 'x' + (ofs-OFS_PARM0)%3); - else - sprintf(message, "offset_%i", ofs); - } - return message; -} -#endif - -QCC_def_t *QCC_PR_Statement ( QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_b, QCC_dstatement_t **outstatement) -{ - QCC_dstatement_t *statement; - QCC_def_t *var_c=NULL, *temp=NULL; - - if (outstatement == (QCC_dstatement_t **)0xffffffff) - outstatement = NULL; - else if (op->priority != -1) - { - if (op->associative!=ASSOC_LEFT) - { - if (op->type_a == &type_pointer) - var_b = QCC_SupplyConversion(var_b, (*op->type_b)->type); - else - var_b = QCC_SupplyConversion(var_b, (*op->type_a)->type); - } - else - { - if (var_a) - var_a = QCC_SupplyConversion(var_a, (*op->type_a)->type); - if (var_b) - var_b = QCC_SupplyConversion(var_b, (*op->type_b)->type); -// if (op->type_a == &def_pointer) -// var_a = QCC_SupplyConversion(var_a, (*op->type_b)->type); -// else -// var_a = QCC_SupplyConversion(var_a, (*op->type_a)->type); -// } -// //can't convert the left componant of an assignment operation -// if (var_b && var_b->type && var_b->type != op->type_b->type) -// var_b = QCC_SupplyConversion(var_b, op->type_b->type->type); - } - } - - if (var_a) - { - var_a->references++; - QCC_FreeTemp(var_a); - } - if (var_b) - { - var_b->references++; - QCC_FreeTemp(var_b); - } - - if (keyword_class && var_a && var_b) - { - if (var_a->type->type == ev_entity && var_b->type->type == ev_entity) - if (var_a->type != var_b->type) - if (strcmp(var_a->type->name, var_b->type->name)) - QCC_PR_ParseWarning(0, "Implicit cast from '%s' to '%s'", var_a->type->name, var_b->type->name); - } - - //maths operators - if (opt_constantarithmatic) - { - if (var_a && var_a->constant) - { - if (var_b && var_b->constant) - { - //both are constants - switch (op - pr_opcodes) //improve some of the maths. - { - case OP_BITOR: - optres_constantarithmatic++; - return QCC_MakeFloatDef((float)((int)G_FLOAT(var_a->ofs) | (int)G_FLOAT(var_b->ofs))); - case OP_BITAND: - optres_constantarithmatic++; - return QCC_MakeFloatDef((float)((int)G_FLOAT(var_a->ofs) & (int)G_FLOAT(var_b->ofs))); - case OP_MUL_F: - optres_constantarithmatic++; - return QCC_MakeFloatDef(G_FLOAT(var_a->ofs) * G_FLOAT(var_b->ofs)); - case OP_DIV_F: - optres_constantarithmatic++; - return QCC_MakeFloatDef(G_FLOAT(var_a->ofs) / G_FLOAT(var_b->ofs)); - case OP_ADD_F: - optres_constantarithmatic++; - return QCC_MakeFloatDef(G_FLOAT(var_a->ofs) + G_FLOAT(var_b->ofs)); - case OP_SUB_F: - optres_constantarithmatic++; - return QCC_MakeFloatDef(G_FLOAT(var_a->ofs) - G_FLOAT(var_b->ofs)); - - case OP_BITOR_I: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) | G_INT(var_b->ofs)); - case OP_BITAND_I: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) & G_INT(var_b->ofs)); - case OP_MUL_I: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) * G_INT(var_b->ofs)); - case OP_DIV_I: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) / G_INT(var_b->ofs)); - case OP_ADD_I: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) + G_INT(var_b->ofs)); - case OP_SUB_I: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) - G_INT(var_b->ofs)); - - case OP_AND: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) && G_INT(var_b->ofs)); - case OP_OR: - optres_constantarithmatic++; - return QCC_MakeIntDef(G_INT(var_a->ofs) || G_INT(var_b->ofs)); - case OP_MUL_V: //mul_f is actually a dot-product - optres_constantarithmatic++; - return QCC_MakeFloatDef( G_FLOAT(var_a->ofs) * G_FLOAT(var_b->ofs+0) + - G_FLOAT(var_a->ofs) * G_FLOAT(var_b->ofs+1) + - G_FLOAT(var_a->ofs) * G_FLOAT(var_b->ofs+2)); - case OP_MUL_FV: - optres_constantarithmatic++; - return QCC_MakeVectorDef( G_FLOAT(var_a->ofs) * G_FLOAT(var_b->ofs+0), - G_FLOAT(var_a->ofs) * G_FLOAT(var_b->ofs+1), - G_FLOAT(var_a->ofs) * G_FLOAT(var_b->ofs+2)); - case OP_MUL_VF: - optres_constantarithmatic++; - return QCC_MakeVectorDef( G_FLOAT(var_a->ofs+0) * G_FLOAT(var_b->ofs), - G_FLOAT(var_a->ofs+1) * G_FLOAT(var_b->ofs), - G_FLOAT(var_a->ofs+2) * G_FLOAT(var_b->ofs)); - case OP_ADD_V: - optres_constantarithmatic++; - return QCC_MakeVectorDef( G_FLOAT(var_a->ofs+0) + G_FLOAT(var_b->ofs+0), - G_FLOAT(var_a->ofs+1) + G_FLOAT(var_b->ofs+1), - G_FLOAT(var_a->ofs+2) + G_FLOAT(var_b->ofs+2)); - case OP_SUB_V: - optres_constantarithmatic++; - return QCC_MakeVectorDef( G_FLOAT(var_a->ofs+0) - G_FLOAT(var_b->ofs+0), - G_FLOAT(var_a->ofs+1) - G_FLOAT(var_b->ofs+1), - G_FLOAT(var_a->ofs+2) - G_FLOAT(var_b->ofs+2)); - } - } - else - { - //a is const, b is not - switch (op - pr_opcodes) - { - case OP_BITOR: - case OP_OR: - case OP_ADD_F: - if (G_FLOAT(var_a->ofs) == 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_b); - return var_b; - } - break; - case OP_MUL_F: - if (G_FLOAT(var_a->ofs) == 1) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_b); - return var_b; - } - break; - case OP_BITAND: - case OP_AND: - if (G_FLOAT(var_a->ofs) != 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_b); - return var_b; - } - break; - - case OP_BITOR_I: - case OP_OR_I: - case OP_ADD_I: - if (G_INT(var_a->ofs) == 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_b); - return var_b; - } - break; - case OP_MUL_I: - if (G_INT(var_a->ofs) == 1) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_b); - return var_b; - } - break; - case OP_BITAND_I: - case OP_AND_I: - if (G_INT(var_a->ofs) != 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_b); - return var_b; - } - break; - } - } - } - else if (var_b && var_b->constant) - { - //b is const, a is not - switch (op - pr_opcodes) - { - case OP_BITOR: - case OP_OR: - case OP_SUB_F: - case OP_ADD_F: - if (G_FLOAT(var_b->ofs) == 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_a); - return var_a; - } - break; - case OP_DIV_F: - case OP_MUL_F: - if (G_FLOAT(var_b->ofs) == 1) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_a); - return var_a; - } - break; - //no bitand_f, I don't trust the casts - case OP_AND: - if (G_FLOAT(var_b->ofs) != 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_a); - return var_a; - } - break; - - case OP_BITOR_I: - case OP_OR_I: - case OP_SUB_I: - case OP_ADD_I: - if (G_INT(var_b->ofs) == 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_a); - return var_a; - } - break; - case OP_DIV_I: - case OP_MUL_I: - if (G_INT(var_b->ofs) == 1) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_a); - return var_a; - } - break; - case OP_BITAND_I: - if (G_INT(var_b->ofs) == 0xffffffff) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_a); - return var_a; - } - case OP_AND_I: - if (G_INT(var_b->ofs) != 0) - { - optres_constantarithmatic++; - QCC_UnFreeTemp(var_a); - return var_a; - } - break; - } - } - } - - switch (op - pr_opcodes) - { - case OP_AND: - if (var_a->ofs == var_b->ofs) - QCC_PR_ParseWarning(WARN_CONSTANTCOMPARISON, "Parameter offsets for && are the same"); - if (var_a->constant || var_b->constant) - QCC_PR_ParseWarning(WARN_CONSTANTCOMPARISON, "Result of comparison is constant"); - break; - case OP_OR: - if (var_a->ofs == var_b->ofs) - QCC_PR_ParseWarning(WARN_CONSTANTCOMPARISON, "Parameters for || are the same"); - if (var_a->constant || var_b->constant) - QCC_PR_ParseWarning(WARN_CONSTANTCOMPARISON, "Result of comparison is constant"); - break; - case OP_EQ_F: - case OP_EQ_S: - case OP_EQ_E: - case OP_EQ_FNC: -// if (opt_shortenifnots) -// if (var_b->constant && ((int*)qcc_pr_globals)[var_b->ofs]==0) // (a == 0) becomes (!a) -// op = &pr_opcodes[(op - pr_opcodes) - OP_EQ_F + OP_NOT_F]; - case OP_EQ_V: - - case OP_NE_F: - case OP_NE_V: - case OP_NE_S: - case OP_NE_E: - case OP_NE_FNC: - - case OP_LE: - case OP_GE: - case OP_LT: - case OP_GT: - if ((var_a->constant && var_b->constant && !var_a->temp && !var_b->temp) || var_a->ofs == var_b->ofs) - QCC_PR_ParseWarning(WARN_CONSTANTCOMPARISON, "Result of comparison is constant"); - break; - case OP_IF_S: - case OP_IFNOT_S: - case OP_IF_F: - case OP_IFNOT_F: - case OP_IF: - case OP_IFNOT: -// if (var_a->type->type == ev_function && !var_a->temp) -// QCC_PR_ParseWarning(WARN_CONSTANTCOMPARISON, "Result of comparison is constant"); - if (var_a->constant && !var_a->temp) - QCC_PR_ParseWarning(WARN_CONSTANTCOMPARISON, "Result of comparison is constant"); - break; - default: - break; - } - - if (numstatements) - { //optimise based on last statement. - if (op - pr_opcodes == OP_IFNOT) - { - if (opt_shortenifnots && var_a && (statements[numstatements-1].op == OP_NOT_F || statements[numstatements-1].op == OP_NOT_FNC || statements[numstatements-1].op == OP_NOT_ENT)) - { - if (statements[numstatements-1].c == var_a->ofs) - { - static QCC_def_t nvara; - if (statements[numstatements-1].op == OP_NOT_F) - op = &pr_opcodes[OP_IF_F]; - else - op = &pr_opcodes[OP_IF]; - numstatements--; - QCC_FreeTemp(var_a); - memcpy(&nvara, var_a, sizeof(nvara)); - nvara.ofs = statements[numstatements].a; - var_a = &nvara; - - optres_shortenifnots++; - } - } - } - else if (op - pr_opcodes == OP_IFNOT_F) - { - if (opt_shortenifnots && var_a && statements[numstatements-1].op == OP_NOT_F) - { - if (statements[numstatements-1].c == var_a->ofs) - { - static QCC_def_t nvara; - op = &pr_opcodes[OP_IF_F]; - numstatements--; - QCC_FreeTemp(var_a); - memcpy(&nvara, var_a, sizeof(nvara)); - nvara.ofs = statements[numstatements].a; - var_a = &nvara; - - optres_shortenifnots++; - } - } - } - else if (op - pr_opcodes == OP_IFNOT_S) - { - if (opt_shortenifnots && var_a && statements[numstatements-1].op == OP_NOT_S) - { - if (statements[numstatements-1].c == var_a->ofs) - { - static QCC_def_t nvara; - op = &pr_opcodes[OP_IF_S]; - numstatements--; - QCC_FreeTemp(var_a); - memcpy(&nvara, var_a, sizeof(nvara)); - nvara.ofs = statements[numstatements].a; - var_a = &nvara; - - optres_shortenifnots++; - } - } - } - else if (((unsigned) ((op - pr_opcodes) - OP_STORE_F) < 6) || (op-pr_opcodes) == OP_STORE_P) - { - // remove assignments if what should be assigned is the 3rd operand of the previous statement? - // don't if it's a call, callH, switch or case - // && var_a->ofs >RESERVED_OFS) - if (OpAssignsToC(statements[numstatements-1].op) && - opt_assignments && var_a && var_a->ofs == statements[numstatements-1].c) - { - if (var_a->type->type == var_b->type->type) - { - if (var_a->temp) - { - statement = &statements[numstatements-1]; - statement->c = var_b->ofs; - - if (var_a->type->type != var_b->type->type) - QCC_PR_ParseWarning(0, "store type mismatch"); - var_b->references++; - var_a->references--; - QCC_FreeTemp(var_a); - optres_assignments++; - - simplestore=true; - - QCC_UnFreeTemp(var_b); - return var_b; - } - } - } - } - } - simplestore=false; - - statement = &statements[numstatements]; - numstatements++; - - if (!QCC_OPCodeValid(op)) - { - switch(op - pr_opcodes) - { - case OP_IF_S: - var_c = QCC_PR_GetDef(type_string, "string_null", NULL, true, 1, false); - numstatements--; - var_a = QCC_PR_Statement(&pr_opcodes[OP_NE_S], var_a, var_c, NULL); - statement = &statements[numstatements]; - numstatements++; - - QCC_FreeTemp(var_a); - op = &pr_opcodes[OP_IF]; - break; - - case OP_IFNOT_S: - var_c = QCC_PR_GetDef(type_string, "string_null", NULL, true, 1, false); - numstatements--; - var_a = QCC_PR_Statement(&pr_opcodes[OP_NE_S], var_a, var_c, NULL); - statement = &statements[numstatements]; - numstatements++; - - QCC_FreeTemp(var_a); - op = &pr_opcodes[OP_IFNOT]; - break; - - case OP_IF_F: - var_c = QCC_MakeFloatDef(0); - numstatements--; - var_a = QCC_PR_Statement(&pr_opcodes[OP_NE_F], var_a, var_c, NULL); - statement = &statements[numstatements]; - numstatements++; - - QCC_FreeTemp(var_a); - op = &pr_opcodes[OP_IF]; - break; - - case OP_IFNOT_F: - var_c = QCC_MakeFloatDef(0); - numstatements--; - var_a = QCC_PR_Statement(&pr_opcodes[OP_NE_F], var_a, var_c, NULL); - statement = &statements[numstatements]; - numstatements++; - - QCC_FreeTemp(var_a); - op = &pr_opcodes[OP_IFNOT]; - break; - - case OP_ADDSTORE_F: - op = &pr_opcodes[OP_ADD_F]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_ADDSTORE_FI: - op = &pr_opcodes[OP_ADD_FI]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_ADDSTORE_IF: - op = &pr_opcodes[OP_ADD_IF]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_SUBSTORE_F: - op = &pr_opcodes[OP_SUB_F]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_SUBSTORE_FI: - op = &pr_opcodes[OP_SUB_FI]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_SUBSTORE_IF: - op = &pr_opcodes[OP_SUB_IF]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_DIVSTORE_F: - op = &pr_opcodes[OP_DIV_F]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_DIVSTORE_FI: - op = &pr_opcodes[OP_DIV_FI]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_DIVSTORE_IF: - op = &pr_opcodes[OP_DIV_IF]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_MULSTORE_F: - op = &pr_opcodes[OP_MUL_F]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_MULSTORE_IF: - op = &pr_opcodes[OP_MUL_IF]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_MULSTORE_FI: - op = &pr_opcodes[OP_MUL_FI]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_ADDSTORE_V: - op = &pr_opcodes[OP_ADD_V]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_SUBSTORE_V: - op = &pr_opcodes[OP_SUB_V]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_MULSTORE_V: - op = &pr_opcodes[OP_MUL_VF]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_BITSET_I: - op = &pr_opcodes[OP_BITOR_I]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - case OP_BITSET: - op = &pr_opcodes[OP_BITOR]; - var_c = var_b; - var_b = var_a; - var_a = var_c; - var_c = var_a; - break; - - case OP_BITCLR: - //b = var, a = bit field. - - QCC_UnFreeTemp(var_a); - QCC_UnFreeTemp(var_b); - - numstatements--; - var_c = QCC_PR_Statement(&pr_opcodes[OP_BITAND], var_b, var_a, NULL); - QCC_FreeTemp(var_c); - statement = &statements[numstatements]; - numstatements++; - - QCC_FreeTemp(var_a); - QCC_FreeTemp(var_b); - - op = &pr_opcodes[OP_SUB_F]; - var_a = var_b; - var_b = var_c; - var_c = var_a; - break; - - case OP_SUBSTOREP_FI: - case OP_SUBSTOREP_IF: - case OP_ADDSTOREP_FI: - case OP_ADDSTOREP_IF: - case OP_MULSTOREP_FI: - case OP_MULSTOREP_IF: - case OP_DIVSTOREP_FI: - case OP_DIVSTOREP_IF: - - - case OP_SUBSTOREP_F: - case OP_ADDSTOREP_F: - case OP_MULSTOREP_F: - case OP_DIVSTOREP_F: - case OP_BITSETP: - case OP_BITSETP_I: - case OP_BITCLRP: -// QCC_PR_ParseWarning(0, "XSTOREP_F emulation is still experimental"); - QCC_UnFreeTemp(var_a); - QCC_UnFreeTemp(var_b); - //don't chain these... this expansion is not the same. - { - int st; - int need_lock = false; - for (st = numstatements-2; st>=0; st--) - { - if (statements[st].op == OP_ADDRESS) - if (statements[st].c == var_b->ofs) - break; - - if (statements[st].op >= OP_CALL0 && statements[st].op <= OP_CALL8 || statements[st].op >= OP_CALL1H && statements[st].op <= OP_CALL8H) - need_lock = true; - - //printf("%s\n", pr_opcodes[statements[st].op].opname); - - if (statements[st].c == var_b->ofs) - QCC_PR_ParseWarning(0, "Temp-reuse may have broken your %s", op->name); - } - if (st < 0) - QCC_PR_ParseError(ERR_INTERNAL, "XSTOREP_F: pointer was not generated from previous statement"); - var_c = QCC_GetTemp(*op->type_c); - if(need_lock) - QCC_LockTemp(var_c); // this will cause the temp to be remapped by QCC_RemapLockedTemps - - statement_linenums[statement-statements] = statement_linenums[st]; - statement->op = OP_ADDRESS; - statement->a = statements[st].a; - statement->b = statements[st].b; - statement->c = statements[st].c; - - statement_linenums[st] = pr_source_line; - statements[st].op = OP_LOAD_F; - statements[st].a = statements[st].a; - statements[st].b = statements[st].b; - statements[st].c = var_c->ofs; - } - - statement = &statements[numstatements]; - numstatements++; - - statement_linenums[statement-statements] = pr_source_line; - switch(op - pr_opcodes) - { - case OP_SUBSTOREP_F: - statement->op = OP_SUB_F; - break; - case OP_SUBSTOREP_IF: - statement->op = OP_SUB_IF; - break; - case OP_SUBSTOREP_FI: - statement->op = OP_SUB_FI; - break; - case OP_ADDSTOREP_IF: - statement->op = OP_ADD_IF; - break; - case OP_ADDSTOREP_FI: - statement->op = OP_ADD_FI; - break; - case OP_MULSTOREP_IF: - statement->op = OP_MUL_IF; - break; - case OP_MULSTOREP_FI: - statement->op = OP_MUL_FI; - break; - case OP_DIVSTOREP_IF: - statement->op = OP_DIV_IF; - break; - case OP_DIVSTOREP_FI: - statement->op = OP_DIV_FI; - break; - case OP_ADDSTOREP_F: - statement->op = OP_ADD_F; - break; - case OP_MULSTOREP_F: - statement->op = OP_MUL_F; - break; - case OP_DIVSTOREP_F: - statement->op = OP_DIV_F; - break; - case OP_BITSETP: - statement->op = OP_BITOR; - break; - case OP_BITSETP_I: - statement->op = OP_BITOR_I; - break; - case OP_BITCLRP: - //float pointer float - temp = QCC_GetTemp(type_float); - statement->op = OP_BITAND; - statement->a = var_c ? var_c->ofs : 0; - statement->b = var_a ? var_a->ofs : 0; - statement->c = temp->ofs; - - statement = &statements[numstatements]; - numstatements++; - - statement_linenums[statement-statements] = pr_source_line; - statement->op = OP_SUB_F; - - //t = c & i - //c = c - t - break; - default: //no way will this be hit... - QCC_PR_ParseError(ERR_INTERNAL, "opcode invalid 3 times %i", op - pr_opcodes); - } - if (op - pr_opcodes == OP_BITCLRP) - { - statement->a = var_c ? var_c->ofs : 0; - statement->b = temp ? temp->ofs : 0; - statement->c = var_c->ofs; - QCC_FreeTemp(temp); - var_b = var_b; //this is the ptr. - QCC_FreeTemp(var_a); - var_a = var_c; //this is the value. - } - else - { - statement->a = var_c ? var_c->ofs : 0; - statement->b = var_a ? var_a->ofs : 0; - statement->c = var_c->ofs; - var_b = var_b; //this is the ptr. - QCC_FreeTemp(var_a); - var_a = var_c; //this is the value. - } - - op = &pr_opcodes[OP_STOREP_F]; - QCC_FreeTemp(var_c); - - var_c = NULL; - QCC_FreeTemp(var_b); - - statement = &statements[numstatements]; - numstatements++; - break; - - case OP_MULSTOREP_V: - case OP_SUBSTOREP_V: - case OP_ADDSTOREP_V: -// QCC_PR_ParseWarning(0, "XSTOREP_V emulation is still experimental"); - QCC_UnFreeTemp(var_a); - QCC_UnFreeTemp(var_b); - //don't chain these... this expansion is not the same. - { - int st; - int need_lock = false; - for (st = numstatements-2; st>=0; st--) - { - if (statements[st].op == OP_ADDRESS) - if (statements[st].c == var_b->ofs) - break; - - if (statements[st].op >= OP_CALL0 && statements[st].op <= OP_CALL8 || statements[st].op >= OP_CALL1H && statements[st].op <= OP_CALL8H) - need_lock = true; - - if (statements[st].c == var_b->ofs) - QCC_PR_ParseWarning(0, "Temp-reuse may have broken your %s", op->name); - } - if (st < 0) - QCC_PR_ParseError(ERR_INTERNAL, "XSTOREP_V couldn't find pointer generation"); - var_c = QCC_GetTemp(*op->type_c); - if(need_lock) - QCC_LockTemp(var_c); // this will cause the temp to be remapped by QCC_RemapLockedTemps - - statement_linenums[statement-statements] = statement_linenums[st]; - statement->op = OP_ADDRESS; - statement->a = statements[st].a; - statement->b = statements[st].b; - statement->c = statements[st].c; - - statement_linenums[st] = pr_source_line; - statements[st].op = OP_LOAD_V; - statements[st].a = statements[st].a; - statements[st].b = statements[st].b; - statements[st].c = var_c->ofs; - } - - statement = &statements[numstatements]; - numstatements++; - - statement_linenums[statement-statements] = pr_source_line; - switch(op - pr_opcodes) - { - case OP_SUBSTOREP_V: - statement->op = OP_SUB_V; - break; - case OP_ADDSTOREP_V: - statement->op = OP_ADD_V; - break; - case OP_MULSTOREP_V: - statement->op = OP_MUL_VF; - break; - default: //no way will this be hit... - QCC_PR_ParseError(ERR_INTERNAL, "opcode invalid 3 times %i", op - pr_opcodes); - } - statement->a = var_a ? var_a->ofs : 0; - statement->b = var_c ? var_c->ofs : 0; - QCC_FreeTemp(var_c); - var_c = QCC_GetTemp(*op->type_c); - statement->c = var_c ? var_c->ofs : 0; - - var_b = var_b; //this is the ptr. - QCC_FreeTemp(var_a); - var_a = var_c; //this is the value. - op = &pr_opcodes[OP_STOREP_V]; - - - - - QCC_FreeTemp(var_c); - var_c = NULL; - QCC_FreeTemp(var_b); - - statement = &statements[numstatements]; - numstatements++; - break; - default: - QCC_PR_ParseError(ERR_BADEXTENSION, "Opcode \"%s|%s\" not valid for target", op->name, op->opname); - break; - } - } - - if (outstatement) - *outstatement = statement; - - statement_linenums[statement-statements] = pr_source_line; - statement->op = op - pr_opcodes; - statement->a = var_a ? var_a->ofs : 0; - statement->b = var_b ? var_b->ofs : 0; - if (var_c != NULL) - { - statement->c = var_c->ofs; - } - else if (op->type_c == &type_void || op->associative==ASSOC_RIGHT || op->type_c == NULL) - { - var_c = NULL; - statement->c = 0; // ifs, gotos, and assignments - // don't need vars allocated - } - else - { // allocate result space - var_c = QCC_GetTemp(*op->type_c); - statement->c = var_c->ofs; - if (op->type_b == &type_field) - { - var_c->name = var_b->name; - var_c->s_file = var_b->s_file; - var_c->s_line = var_b->s_line; - } - } - - if ((op - pr_opcodes >= OP_LOAD_F && op - pr_opcodes <= OP_LOAD_FNC) || - op - pr_opcodes == OP_LOAD_I) - { - if (var_b->constant == 2) - var_c->constant = true; - } - - if (!var_c) - { - if (var_a) - QCC_UnFreeTemp(var_a); - return var_a; - } - return var_c; -} - -/* -============ -QCC_PR_SimpleStatement - -Emits a primitive statement, returning the var it places it's value in -============ -*/ -QCC_dstatement_t *QCC_PR_SimpleStatement( int op, int var_a, int var_b, int var_c, int force) -{ - QCC_dstatement_t *statement; - - if (!force && !QCC_OPCodeValid(pr_opcodes+op)) - { - QCC_PR_ParseError(ERR_BADEXTENSION, "Opcode \"%s|%s\" not valid for target\n", pr_opcodes[op].name, pr_opcodes[op].opname); - } - - statement_linenums[numstatements] = pr_source_line; - statement = &statements[numstatements]; - - numstatements++; - statement->op = op; - statement->a = var_a; - statement->b = var_b; - statement->c = var_c; - return statement; -} - -void QCC_PR_Statement3 ( QCC_opcode_t *op, QCC_def_t *var_a, QCC_def_t *var_b, QCC_def_t *var_c, int force) -{ - QCC_dstatement_t *statement; - - if (!force && !QCC_OPCodeValid(op)) - { -// outputversion = op->extension; -// if (noextensions) - QCC_PR_ParseError(ERR_BADEXTENSION, "Opcode \"%s|%s\" not valid for target\n", op->name, op->opname); - } - - statement = &statements[numstatements]; - numstatements++; - - statement_linenums[statement-statements] = pr_source_line; - statement->op = op - pr_opcodes; - statement->a = var_a ? var_a->ofs : 0; - statement->b = var_b ? var_b->ofs : 0; - statement->c = var_c ? var_c->ofs : 0; -} - -/* -============ -PR_ParseImmediate - -Looks for a preexisting constant -============ -*/ -QCC_def_t *QCC_PR_ParseImmediate (void) -{ - QCC_def_t *cn; - - if (pr_immediate_type == type_float) - { - cn = QCC_MakeFloatDef(pr_immediate._float); - QCC_PR_Lex (); - return cn; - } - if (pr_immediate_type == type_integer) - { - cn = QCC_MakeIntDef(pr_immediate._int); - QCC_PR_Lex (); - return cn; - } - - if (pr_immediate_type == type_string) - { - cn = QCC_MakeStringDef(pr_immediate_string); - QCC_PR_Lex (); - return cn; - } - -// check for a constant with the same value - for (cn=pr.def_head.next ; cn ; cn=cn->next) //FIXME - hashtable. - { - if (!cn->initialized) - continue; - if (!cn->constant) - continue; - if (cn->type != pr_immediate_type) - continue; - if (pr_immediate_type == type_string) - { - if (!STRCMP(G_STRING(cn->ofs), pr_immediate_string) ) - { - QCC_PR_Lex (); - return cn; - } - } - else if (pr_immediate_type == type_float) - { - if ( G_FLOAT(cn->ofs) == pr_immediate._float ) - { - QCC_PR_Lex (); - return cn; - } - } - else if (pr_immediate_type == type_integer) - { - if ( G_INT(cn->ofs) == pr_immediate._int ) - { - QCC_PR_Lex (); - return cn; - } - } - else if (pr_immediate_type == type_vector) - { - if ( ( G_FLOAT(cn->ofs) == pr_immediate.vector[0] ) - && ( G_FLOAT(cn->ofs+1) == pr_immediate.vector[1] ) - && ( G_FLOAT(cn->ofs+2) == pr_immediate.vector[2] ) ) - { - QCC_PR_Lex (); - return cn; - } - } - else - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "weird immediate type"); - } - -// allocate a new one - cn = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - cn->next = NULL; - pr.def_tail->next = cn; - pr.def_tail = cn; - - cn->type = pr_immediate_type; - cn->name = "IMMEDIATE"; - cn->constant = true; - cn->initialized = 1; - cn->scope = NULL; // always share immediates - -// copy the immediate to the global area - cn->ofs = QCC_GetFreeOffsetSpace(type_size[pr_immediate_type->type]); - - if (pr_immediate_type == type_string) - pr_immediate.string = QCC_CopyString (pr_immediate_string); - - memcpy (qcc_pr_globals + cn->ofs, &pr_immediate, 4*type_size[pr_immediate_type->type]); - - QCC_PR_Lex (); - - return cn; -} - - -void QCC_PrecacheSound (QCC_def_t *e, int ch) -{ - char *n; - int i; - - if (e->type->type != ev_string) - return; - - if (!e->ofs || e->temp || !e->constant) - return; - n = G_STRING(e->ofs); - if (!*n) - return; - for (i=0 ; i= '1' && ch <= '9') - precache_sounds_block[i] = ch - '0'; - else - precache_sounds_block[i] = 1; - numsounds++; -} - -void QCC_PrecacheModel (QCC_def_t *e, int ch) -{ - char *n; - int i; - - if (e->type->type != ev_string) - return; - - if (!e->ofs || e->temp || !e->constant) - return; - n = G_STRING(e->ofs); - if (!*n) - return; - for (i=0 ; i= '1' && ch <= '9') - precache_models_block[i] = ch - '0'; - else - precache_models_block[i] = 1; - } - return; - } - if (nummodels == MAX_MODELS) - return; -// QCC_Error ("PrecacheModels: nummodels == MAX_MODELS"); - strcpy (precache_models[i], n); - if (ch >= '1' && ch <= '9') - precache_models_block[i] = ch - '0'; - else - precache_models_block[i] = 1; - nummodels++; -} - -void QCC_SetModel (QCC_def_t *e) -{ - char *n; - int i; - - if (e->type->type != ev_string) - return; - - if (!e->ofs || e->temp || !e->constant) - return; - n = G_STRING(e->ofs); - if (!*n) - return; - for (i=0 ; itype->type != ev_string) - return; - - if (!e->ofs || e->temp || !e->constant) - return; - n = G_STRING(e->ofs); - if (!*n) - return; - for (i=0 ; i= '1' && ch <= '9') - precache_textures_block[i] = ch - '0'; - else - precache_textures_block[i] = 1; - numtextures++; -} - -void QCC_PrecacheFile (QCC_def_t *e, int ch) -{ - char *n; - int i; - - if (e->type->type != ev_string) - return; - - if (!e->ofs || e->temp || !e->constant) - return; - n = G_STRING(e->ofs); - if (!*n) - return; - for (i=0 ; i= '1' && ch <= '9') - precache_files_block[i] = ch - '0'; - else - precache_files_block[i] = 1; - numfiles++; -} - -void QCC_PrecacheFileOptimised (char *n, int ch) -{ - int i; - - for (i=0 ; i= '1' && ch <= '9') - precache_files_block[i] = ch - '0'; - else - precache_files_block[i] = 1; - numfiles++; -} - -QCC_def_t *QCC_PR_GenerateFunctionCall (QCC_def_t *func, QCC_def_t *arglist[], int argcount) //warning, the func could have no name set if it's a field call. -{ - QCC_def_t *d, *oldret, *oself; - int i; - QCC_type_t *t; - int extraparms=false; - int np; - int laststatement = numstatements; - - int callconvention; - QCC_dstatement_t *st; - - - func->timescalled++; - - if (QCC_OPCodeValid(&pr_opcodes[OP_CALL1H])) - callconvention = OP_CALL1H; //FTE extended - else - callconvention = OP_CALL1; //standard - - t = func->type; - - if (t->type == ev_variant) - { - t->aux_type = type_variant; - } - - if (t->type != ev_function && t->type != ev_variant) - { - QCC_PR_ParseErrorPrintDef (ERR_NOTAFUNCTION, func, "not a function"); - } - -// copy the arguments to the global parameter variables - if (t->type == ev_variant) - { - extraparms = true; - np = 0; - } - else if (t->num_parms < 0) - { - extraparms = true; - np = (t->num_parms * -1) - 1; - } - else - np = t->num_parms; - - if (strchr(func->name, ':') && laststatement && statements[laststatement-1].op == OP_LOAD_FNC && statements[laststatement-1].c == func->ofs) - { //we're entering OO code with a different self. - //eg: other.touch(self) - - //FIXME: problems could occur with hexen2 calling conventions when parm0/1 is 'self' - //thiscall. copy the right ent into 'self' (if it's not the same offset) - d = QCC_PR_GetDef(type_entity, "self", NULL, true, 1, false); - if (statements[laststatement-1].a != d->ofs) - { - oself = QCC_GetTemp(type_entity); - //oself = self - QCC_PR_SimpleStatement(OP_STORE_ENT, d->ofs, oself->ofs, 0, false); - //self = other - QCC_PR_SimpleStatement(OP_STORE_ENT, statements[laststatement-1].a, d->ofs, 0, false); - - //if the args refered to self, update them to refer to oself instead - //(as self is now set to 'other') - for (i = 0; i < argcount; i++) - { - if (arglist[i]->ofs == d->ofs) - { - arglist[i] = oself; - } - } - } - else - { - //it was self.func() anyway - oself = NULL; - d = NULL; - } - } - else - { //regular func call - oself = NULL; - d = NULL; - } - -// write the arguments (except for first two if hexenc) - for (i = 0; i < argcount; i++) - { - if (i>=MAX_PARMS) - d = extra_parms[i - MAX_PARMS]; - else - d = &def_parms[i]; - - if (callconvention == OP_CALL1H) - if (i < 2) - { - //first two args are passed in the call opcode, so don't need to be copied - arglist[i]->references++; - d->references++; - QCC_FreeTemp(arglist[i]); - continue; - } - - if (arglist[i]->type->size>1 || !opt_nonvec_parms) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STORE_V], arglist[i], d, (QCC_dstatement_t **)0xffffffff)); - else - { - d->type = arglist[i]->type; - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STORE_F], arglist[i], d, (QCC_dstatement_t **)0xffffffff)); - optres_nonvec_parms++; - } - } - - //if the return value was in use, save it off now, so that it doesn't get clobbered - if (def_ret.temp->used) - { - oldret = QCC_GetTemp(def_ret.type); - if (def_ret.type->size == 3) - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_V], &def_ret, oldret, NULL)); - else - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], &def_ret, oldret, NULL)); - QCC_UnFreeTemp(oldret); - QCC_UnFreeTemp(&def_ret); - QCC_PR_ParseWarning(WARN_FIXEDRETURNVALUECONFLICT, "Return value conflict - output is inefficient"); - } - else - oldret = NULL; - - //we dont need to lock the local containing the function index because its thrown away after the call anyway - //(if a function is called in the argument list then it'll be locked as part of that call) - QCC_FreeTemp(func); - QCC_LockActiveTemps(); //any temps before are likly to be used with the return value. - QCC_UnFreeTemp(func); - - //generate the call - if (argcount>MAX_PARMS) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[callconvention-1+MAX_PARMS], func, 0, (QCC_dstatement_t **)&st)); - else if (argcount) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[callconvention-1+argcount], func, 0, (QCC_dstatement_t **)&st)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_CALL0], func, 0, (QCC_dstatement_t **)&st)); - - if (callconvention == OP_CALL1H) - { - if (argcount) - { - st->b = arglist[0]->ofs; -// QCC_FreeTemp(param[0]); - if (argcount>1) - { - st->c = arglist[1]->ofs; -// QCC_FreeTemp(param[1]); - } - } - } - - //restore the class owner - if (oself) - QCC_PR_SimpleStatement(OP_STORE_ENT, oself->ofs, d->ofs, 0, false); - - for(; argcount; argcount--) - { - QCC_FreeTemp(arglist[argcount-1]); - } - - if (oldret) - { - // Make sure our def_ret backup temp wasn't freed above - QCC_UnFreeTemp(oldret); //this bug fix was brought to you by Blub, the character \ and the number 0. - - - //if we preserved the ofs_ret global, restore it here - if (t->type == ev_variant) - { - d = QCC_GetTemp(type_variant); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_F, &def_ret, d, NULL)); - } - else - { - d = QCC_GetTemp(t->aux_type); - if (t->aux_type->size == 3) - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_V, &def_ret, d, NULL)); - else - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_F, &def_ret, d, NULL)); - } - if (def_ret.type->size == 3) - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_V, oldret, &def_ret, NULL)); - else - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_F, oldret, &def_ret, NULL)); - QCC_FreeTemp(oldret); - QCC_UnFreeTemp(&def_ret); - QCC_UnFreeTemp(d); - - return d; - } - - if (t->type == ev_variant) - def_ret.type = type_variant; - else - def_ret.type = t->aux_type; - if (def_ret.temp->used) - QCC_PR_ParseWarning(WARN_FIXEDRETURNVALUECONFLICT, "Return value conflict - output is inefficient"); - def_ret.temp->used = true; - - return &def_ret; -} - -/* -============ -PR_ParseFunctionCall -============ -*/ -QCC_def_t *QCC_PR_ParseFunctionCall (QCC_def_t *func) //warning, the func could have no name set if it's a field call. -{ - QCC_def_t *e, *d, *old, *oself, *out; - int arg; - QCC_type_t *t, *p; - int extraparms=false; - int np; - int laststatement = numstatements; - - int callconvention; - - QCC_def_t *param[MAX_PARMS+MAX_EXTRA_PARMS]; - - func->timescalled++; - - if (QCC_OPCodeValid(&pr_opcodes[OP_CALL1H])) - callconvention = OP_CALL1H; //FTE extended - else - callconvention = OP_CALL1; //standard - - t = func->type; - - if (t->type == ev_variant) - { - t->aux_type = type_variant; - } - - if (t->type != ev_function && t->type != ev_variant) - { - QCC_PR_ParseErrorPrintDef (ERR_NOTAFUNCTION, func, "not a function"); - } - - if (!t->num_parms&&t->type != ev_variant) //intrinsics. These base functions have variable arguments. I would check for (...) args too, but that might be used for extended builtin functionality. (this code wouldn't compile otherwise) - { - if (!strcmp(func->name, "random")) - { - old = NULL; - func->references++; - if (!QCC_PR_CheckToken(")")) - { - e = QCC_PR_Expression (TOP_PRIORITY, EXPR_DISALLOW_COMMA); - if (e->type->type != ev_float) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHPARM, func, "type mismatch on parm %i", 1); - if (!QCC_PR_CheckToken(")")) - { - QCC_PR_Expect(","); - d = QCC_PR_Expression (TOP_PRIORITY, EXPR_DISALLOW_COMMA); - if (d->type->type != ev_float) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHPARM, func, "type mismatch on parm %i", 2); - QCC_PR_Expect(")"); - } - else - d = NULL; - } - else - { - e = NULL; - d = NULL; - } - - if (QCC_OPCodeValid(&pr_opcodes[OP_RAND0])) - { - if(def_ret.temp->used) - out = QCC_GetTemp(type_float); - else - out = &def_ret; - - if (e) - { - if (d) - QCC_PR_SimpleStatement(OP_RAND2, e->ofs, d->ofs, out->ofs, false); - else - QCC_PR_SimpleStatement(OP_RAND1, e->ofs, 0, out->ofs, false); - } - else - QCC_PR_SimpleStatement(OP_RAND0, 0, 0, out->ofs, false); - } - else - { - if (def_ret.temp->used) - { - old = QCC_GetTemp(def_ret.type); - if (def_ret.type->size == 3) - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_V], &def_ret, old, NULL)); - else - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], &def_ret, old, NULL)); - QCC_UnFreeTemp(old); - QCC_UnFreeTemp(&def_ret); - QCC_PR_ParseWarning(WARN_FIXEDRETURNVALUECONFLICT, "Return value conflict - output is inefficient"); - } - else - old = NULL; - - if (e) - { - if (d) - { - QCC_dstatement_t *st; - QCC_def_t *t; - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - - if ((!d->constant || !e->constant) && G_FLOAT(d->ofs) >= G_FLOAT(d->ofs)) - { - t = QCC_PR_Statement(&pr_opcodes[OP_GT], d, e, NULL); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_IFNOT], t, 0, &st)); - st->b = 3; - - t = QCC_PR_Statement(&pr_opcodes[OP_SUB_F], d, e, NULL); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, e->ofs, OFS_RETURN, false); - - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_GOTO], 0, 0, &st)); - st->a = 3; - } - - t = QCC_PR_Statement(&pr_opcodes[OP_SUB_F], e, d, NULL); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, d->ofs, OFS_RETURN, false); - } - else - { - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, e->ofs, OFS_RETURN, false); - } - } - else - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - } - - if (e) - { - QCC_FreeTemp(e); - e->references++; - } - if (d) - { - d->references++; - QCC_FreeTemp(d); - } - - if (old) - { - d = QCC_GetTemp(type_float); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_F, &def_ret, d, NULL)); - if (def_ret.type->size == 3) - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_V, old, &def_ret, NULL)); - else - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_F, old, &def_ret, NULL)); - QCC_FreeTemp(old); - QCC_UnFreeTemp(d); - QCC_UnFreeTemp(&def_ret); - - return d; - } - - if (def_ret.temp->used) - QCC_PR_ParseWarning(0, "Return value conflict - output is likly to be invalid"); - def_ret.temp->used = true; - def_ret.type = type_float; - return &def_ret; - - } - if (!strcmp(func->name, "randomv")) - { - out = NULL; - func->references++; - if (!QCC_PR_CheckToken(")")) - { - e = QCC_PR_Expression (TOP_PRIORITY, EXPR_DISALLOW_COMMA); - if (e->type->type != ev_vector) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHPARM, func, "type mismatch on parm %i", 1); - if (!QCC_PR_CheckToken(")")) - { - QCC_PR_Expect(","); - d = QCC_PR_Expression (TOP_PRIORITY, EXPR_DISALLOW_COMMA); - if (d->type->type != ev_vector) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHPARM, func, "type mismatch on parm %i", 2); - QCC_PR_Expect(")"); - } - else - d = NULL; - } - else - { - e = NULL; - d = NULL; - } - - if (QCC_OPCodeValid(&pr_opcodes[OP_RANDV0])) - { - if(def_ret.temp->used) - out = QCC_GetTemp(type_vector); - else - out = &def_ret; - - if (e) - { - if (d) - QCC_PR_SimpleStatement(OP_RANDV2, e->ofs, d->ofs, out->ofs, false); - else - QCC_PR_SimpleStatement(OP_RANDV1, e->ofs, 0, out->ofs, false); - } - else - QCC_PR_SimpleStatement(OP_RANDV0, 0, 0, out->ofs, false); - } - else - { - if (def_ret.temp->used) - { - old = QCC_GetTemp(def_ret.type); - if (def_ret.type->size == 3) - QCC_PR_Statement(&pr_opcodes[OP_STORE_V], &def_ret, old, NULL); - else - QCC_PR_Statement(&pr_opcodes[OP_STORE_F], &def_ret, old, NULL); - QCC_UnFreeTemp(old); - QCC_UnFreeTemp(&def_ret); - QCC_PR_ParseWarning(WARN_FIXEDRETURNVALUECONFLICT, "Return value conflict - output is inefficient"); - } - else - old = NULL; - - if (e) - { - if (d) - { - QCC_def_t *t; - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - - if ((!d->constant || !e->constant) && G_FLOAT(d->ofs) >= G_FLOAT(d->ofs)) - { - t = QCC_GetTemp(type_float); - QCC_PR_SimpleStatement(OP_GT, d->ofs+2, e->ofs+2, t->ofs, false); - QCC_PR_SimpleStatement(OP_IFNOT, t->ofs, 3, 0, false); - - QCC_PR_SimpleStatement(OP_SUB_F, d->ofs+2, e->ofs+2, t->ofs, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN+2, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, e->ofs+2, OFS_RETURN+2, false); - - QCC_PR_SimpleStatement(OP_GOTO, 3, 0, 0, false); - } - - t = QCC_GetTemp(type_float); - QCC_PR_SimpleStatement(OP_SUB_F, d->ofs+2, e->ofs+2, t->ofs, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN+2, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, d->ofs+2, OFS_RETURN+2, false); - - - - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - - if ((!d->constant || !e->constant) && G_FLOAT(d->ofs) >= G_FLOAT(d->ofs)) - { - t = QCC_GetTemp(type_float); - QCC_PR_SimpleStatement(OP_GT, d->ofs+1, e->ofs+1, t->ofs, false); - QCC_PR_SimpleStatement(OP_IFNOT, t->ofs, 3, 0, false); - - QCC_PR_SimpleStatement(OP_SUB_F, d->ofs+1, e->ofs+1, t->ofs, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN+1, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, e->ofs+1, OFS_RETURN+1, false); - - QCC_PR_SimpleStatement(OP_GOTO, 3, 0, 0, false); - } - - t = QCC_GetTemp(type_float); - QCC_PR_SimpleStatement(OP_SUB_F, d->ofs+1, e->ofs+1, t->ofs, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN+1, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, d->ofs+1, OFS_RETURN+1, false); - - - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - - if ((!d->constant || !e->constant) && G_FLOAT(d->ofs) >= G_FLOAT(d->ofs)) - { - t = QCC_GetTemp(type_float); - QCC_PR_SimpleStatement(OP_GT, d->ofs, e->ofs, t->ofs, false); - QCC_PR_SimpleStatement(OP_IFNOT, t->ofs, 3, 0, false); - - QCC_PR_SimpleStatement(OP_SUB_F, d->ofs, e->ofs, t->ofs, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, e->ofs, OFS_RETURN, false); - - QCC_PR_SimpleStatement(OP_GOTO, 3, 0, 0, false); - } - - t = QCC_GetTemp(type_float); - QCC_PR_SimpleStatement(OP_SUB_F, d->ofs, e->ofs, t->ofs, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, t->ofs, OFS_RETURN, false); - QCC_FreeTemp(t); - QCC_PR_SimpleStatement(OP_ADD_F, OFS_RETURN, d->ofs, OFS_RETURN, false); - } - else - { - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, e->ofs, OFS_RETURN+2, false); - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, e->ofs, OFS_RETURN+1, false); - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - QCC_PR_SimpleStatement(OP_MUL_F, OFS_RETURN, e->ofs, OFS_RETURN, false); - } - } - else - { - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - QCC_PR_SimpleStatement(OP_STORE_F, OFS_RETURN, OFS_RETURN+2, 0, false); - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - QCC_PR_SimpleStatement(OP_STORE_F, OFS_RETURN, OFS_RETURN+1, 0, false); - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - } - } - - - if (e) - { - QCC_FreeTemp(e); - e->references++; - } - if (d) - { - d->references++; - QCC_FreeTemp(d); - } - - if (old) - { - d = QCC_GetTemp(type_vector); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_V, &def_ret, d, NULL)); - if (def_ret.type->size == 3) - { - QCC_PR_Statement(pr_opcodes+OP_STORE_V, old, &def_ret, NULL); - } - else - { - QCC_PR_Statement(pr_opcodes+OP_STORE_F, old, &def_ret, NULL); - } - QCC_FreeTemp(old); - QCC_UnFreeTemp(d); - QCC_UnFreeTemp(&def_ret); - - return d; - } - - if (def_ret.temp->used) - QCC_PR_ParseWarning(0, "Return value conflict - output is likly to be invalid"); - def_ret.temp->used = true; - def_ret.type = type_vector; - return &def_ret; - } - else if (!strcmp(func->name, "spawn")) - { - QCC_type_t *rettype; - if (QCC_PR_CheckToken(")")) - { - rettype = type_entity; - } - else - { - rettype = QCC_TypeForName(QCC_PR_ParseName()); - if (!rettype || rettype->type != ev_entity) - QCC_PR_ParseError(ERR_NOTANAME, "Spawn operator with undefined class"); - - QCC_PR_Expect(")"); - } - - - if (def_ret.temp->used) - { - old = QCC_GetTemp(def_ret.type); - if (def_ret.type->size == 3) - QCC_PR_Statement(&pr_opcodes[OP_STORE_V], &def_ret, old, NULL); - else - QCC_PR_Statement(&pr_opcodes[OP_STORE_F], &def_ret, old, NULL); - QCC_UnFreeTemp(old); - QCC_UnFreeTemp(&def_ret); - QCC_PR_ParseWarning(WARN_FIXEDRETURNVALUECONFLICT, "Return value conflict - output is inefficient"); - } - else - old = NULL; - /* - if (def_ret.temp->used) - QCC_PR_ParseWarning(0, "Return value conflict - output is likly to be invalid"); - def_ret.temp->used = true; - */ - - if (rettype != type_entity) - { - char genfunc[2048]; - sprintf(genfunc, "Class*%s", rettype->name); - func = QCC_PR_GetDef(type_function, genfunc, NULL, true, 1, false); - func->references++; - } - QCC_PR_SimpleStatement(OP_CALL0, func->ofs, 0, 0, false); - - if (old) - { - d = QCC_GetTemp(rettype); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_ENT, &def_ret, d, NULL)); - if (def_ret.type->size == 3) - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_V, old, &def_ret, NULL)); - else - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_STORE_F, old, &def_ret, NULL)); - QCC_FreeTemp(old); - QCC_UnFreeTemp(d); - QCC_UnFreeTemp(&def_ret); - - return d; - } - - def_ret.type = rettype; - return &def_ret; - } - else if (!strcmp(func->name, "entnum") && !QCC_PR_CheckToken(")")) - { - //t = (a/%1) / (nextent(world)/%1) - //a/%1 does a (int)entity to float conversion type thing - func->initialized = 1; - - e = QCC_PR_Expression(TOP_PRIORITY, EXPR_DISALLOW_COMMA); - QCC_PR_Expect(")"); - e = QCC_PR_Statement(&pr_opcodes[OP_DIV_F], e, QCC_MakeIntDef(1), (QCC_dstatement_t **)0xffffffff); - - d = QCC_PR_GetDef(NULL, "nextent", NULL, false, 0, false); - if (!d) - QCC_PR_ParseError(0, "the nextent builtin is not defined"); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], e, &def_parms[0], (QCC_dstatement_t **)0xffffffff)); - d = QCC_PR_Statement(&pr_opcodes[OP_CALL0], d, NULL, NULL); - d = QCC_PR_Statement(&pr_opcodes[OP_DIV_F], d, QCC_MakeIntDef(1), (QCC_dstatement_t **)0xffffffff); - - e = QCC_PR_Statement(&pr_opcodes[OP_DIV_F], e, d, (QCC_dstatement_t **)0xffffffff); - - return e; - } - else if (!strcmp(func->name, "_") && !QCC_PR_CheckToken(")")) - { - // return string as is, but set the dotranslate flag - ++dotranslate; - e = QCC_PR_Expression(TOP_PRIORITY, EXPR_DISALLOW_COMMA); - --dotranslate; - QCC_PR_Expect(")"); - return e; - } - } //so it's not an intrinsic. - - if (opt_precache_file) //should we strip out all precache_file calls? - { - if (!strncmp(func->name,"precache_file", 13)) - { - if (pr_token_type == tt_immediate && pr_immediate_type->type == ev_string) - { - optres_precache_file += strlen(pr_immediate_string); - QCC_PR_Lex(); - QCC_PR_Expect(")"); - QCC_PrecacheFileOptimised (pr_immediate_string, func->name[13]); - def_ret.type = type_void; - return &def_ret; - } - } - } - -// copy the arguments to the global parameter variables - arg = 0; - if (t->type == ev_variant) - { - extraparms = true; - np = 0; - } - else if (t->num_parms < 0) - { - extraparms = true; - np = (t->num_parms * -1) - 1; - } - else - np = t->num_parms; - - //any temps referenced to build the parameters don't need to be locked. - if (!QCC_PR_CheckToken(")")) - { - p = t->param; - do - { - if (extraparms && arg >= MAX_PARMS) - QCC_PR_ParseErrorPrintDef (ERR_TOOMANYPARAMETERSVARARGS, func, "More than %i parameters on varargs function", MAX_PARMS); - else if (arg >= MAX_PARMS+MAX_EXTRA_PARMS) - QCC_PR_ParseErrorPrintDef (ERR_TOOMANYTOTALPARAMETERS, func, "More than %i parameters", MAX_PARMS+MAX_EXTRA_PARMS); - if (!extraparms && arg >= t->num_parms) - { - QCC_PR_ParseWarning (WARN_TOOMANYPARAMETERSFORFUNC, "too many parameters"); - QCC_PR_ParsePrintDef(WARN_TOOMANYPARAMETERSFORFUNC, func); - } - - - //with vectorcalls, we store the vector into the args as individual floats - //this allows better reuse of vector constants. - //copy it into the offset now, because we can. - if (opt_vectorcalls && pr_token_type == tt_immediate && pr_immediate_type == type_vector && arg < MAX_PARMS && !def_parms[arg].temp->used) - { - e = &def_parms[arg]; - - e->ofs = OFS_PARM0+0; - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STORE_F], QCC_MakeFloatDef(pr_immediate.vector[0]), e, (QCC_dstatement_t **)0xffffffff)); - e->ofs = OFS_PARM0+1; - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STORE_F], QCC_MakeFloatDef(pr_immediate.vector[1]), e, (QCC_dstatement_t **)0xffffffff)); - e->ofs = OFS_PARM0+2; - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STORE_F], QCC_MakeFloatDef(pr_immediate.vector[2]), e, (QCC_dstatement_t **)0xffffffff)); - e->ofs = OFS_PARM0; - - QCC_PR_Lex(); - } - else - e = QCC_PR_Expression (TOP_PRIORITY, EXPR_DISALLOW_COMMA); - - if (arg == 0 && func->name) - { - // save information for model and sound caching - if (!strncmp(func->name,"precache_", 9)) - { - if (!strncmp(func->name+9,"sound", 5)) - QCC_PrecacheSound (e, func->name[14]); - else if (!strncmp(func->name+9,"model", 5)) - QCC_PrecacheModel (e, func->name[14]); - else if (!strncmp(func->name+9,"texture", 7)) - QCC_PrecacheTexture (e, func->name[16]); - else if (!strncmp(func->name+9,"file", 4)) - QCC_PrecacheFile (e, func->name[13]); - } - } - - if (arg>=MAX_PARMS) - { - if (!extra_parms[arg - MAX_PARMS]) - { - d = (QCC_def_t *) qccHunkAlloc (sizeof(QCC_def_t)); - d->name = "extra parm"; - d->ofs = QCC_GetFreeOffsetSpace (3); - extra_parms[arg - MAX_PARMS] = d; - } - d = extra_parms[arg - MAX_PARMS]; - } - else - d = &def_parms[arg]; - - if (pr_classtype && e->type->type == ev_field && p->type != ev_field) - { //convert. - oself = QCC_PR_GetDef(type_entity, "self", NULL, true, 1, false); - switch(e->type->aux_type->type) - { - case ev_string: - e = QCC_PR_Statement(pr_opcodes+OP_LOAD_S, oself, e, NULL); - break; - case ev_integer: - e = QCC_PR_Statement(pr_opcodes+OP_LOAD_I, oself, e, NULL); - break; - case ev_float: - e = QCC_PR_Statement(pr_opcodes+OP_LOAD_F, oself, e, NULL); - break; - case ev_function: - e = QCC_PR_Statement(pr_opcodes+OP_LOAD_FNC, oself, e, NULL); - break; - case ev_vector: - e = QCC_PR_Statement(pr_opcodes+OP_LOAD_V, oself, e, NULL); - break; - case ev_entity: - e = QCC_PR_Statement(pr_opcodes+OP_LOAD_ENT, oself, e, NULL); - break; - default: - QCC_Error(ERR_INTERNAL, "Bad member type. Try forced expansion"); - } - } - - if (p) - { - if (typecmp(e->type, p)) - /*if (e->type->type != ev_integer && p->type != ev_function) - if (e->type->type != ev_function && p->type != ev_integer) - if ( e->type->type != p->type )*/ - { - if (p->type == ev_integer && e->type->type == ev_float) //convert float -> int... is this a constant? - e = QCC_PR_Statement(pr_opcodes+OP_CONV_FTOI, e, NULL, NULL); - else if (p->type == ev_float && e->type->type == ev_integer) //convert float -> int... is this a constant? - e = QCC_PR_Statement(pr_opcodes+OP_CONV_ITOF, e, NULL, NULL); - else if (p->type == ev_function && e->type->type == ev_integer && e->constant && !((int*)qcc_pr_globals)[e->ofs]) - { //you're allowed to use int 0 to pass a null function pointer - //this is basically because __NULL__ is defined as ~0 (int 0) - } - else if (p->type != ev_variant) //can cast to variant whatever happens - { - if (flag_laxcasts || (p->type == ev_function && e->type->type == ev_function)) - { - QCC_PR_ParseWarning(WARN_LAXCAST, "type mismatch on parm %i - (%s should be %s)", arg+1, TypeName(e->type), TypeName(p)); - QCC_PR_ParsePrintDef(WARN_LAXCAST, func); - } - else - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHPARM, func, "type mismatch on parm %i - (%s should be %s)", arg+1, TypeName(e->type), TypeName(p)); - } - } - - d->type = p; - - p=p->next; - } - // a vector copy will copy everything - else - d->type = type_void; - - if (arg == 1 && !STRCMP(func->name, "setmodel")) - { - QCC_SetModel(e); - } - - param[arg] = e; -/* if (e->type->size>1) - QCC_PR_Statement (&pr_opcodes[OP_STORE_V], e, d, (QCC_dstatement_t **)0xffffffff); - else - QCC_PR_Statement (&pr_opcodes[OP_STORE_F], e, d, (QCC_dstatement_t **)0xffffffff); - */ - arg++; - } while (QCC_PR_CheckToken (",")); - - if (t->num_parms != -1 && arg < np) - QCC_PR_ParseWarning (WARN_TOOFEWPARAMS, "too few parameters on call to %s", func->name); - QCC_PR_Expect (")"); - } - else if (np) - { - QCC_PR_ParseWarning (WARN_TOOFEWPARAMS, "%s: Too few parameters", func->name); - QCC_PR_ParsePrintDef (WARN_TOOFEWPARAMS, func); - } - - return QCC_PR_GenerateFunctionCall(func, param, arg); -} - -int constchecks; -int varchecks; -int typechecks; -QCC_def_t *QCC_MakeIntDef(int value) -{ - QCC_def_t *cn; - -// check for a constant with the same value - for (cn=pr.def_head.next ; cn ; cn=cn->next) - { - varchecks++; - if (!cn->initialized) - continue; - if (!cn->constant) - continue; - constchecks++; - if (cn->type != type_integer) - continue; - typechecks++; - - if ( G_INT(cn->ofs) == value ) - { - return cn; - } - } - -// allocate a new one - cn = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - cn->next = NULL; - pr.def_tail->next = cn; - pr.def_tail = cn; - - cn->type = type_integer; - cn->name = "IMMEDIATE"; - cn->constant = true; - cn->initialized = 1; - cn->scope = NULL; // always share immediates - cn->arraysize = 1; - -// copy the immediate to the global area - cn->ofs = QCC_GetFreeOffsetSpace (type_size[type_integer->type]); - - G_INT(cn->ofs) = value; - - - return cn; -} - -QCC_def_t *QCC_MakeVectorDef(float a, float b, float c) -{ - QCC_def_t *cn; - -// check for a constant with the same value - for (cn=pr.def_head.next ; cn ; cn=cn->next) - { - varchecks++; - if (!cn->initialized) - continue; - if (!cn->constant) - continue; - constchecks++; - if (cn->type != type_vector) - continue; - typechecks++; - - if ( G_FLOAT(cn->ofs+0) == a && - G_FLOAT(cn->ofs+1) == b && - G_FLOAT(cn->ofs+2) == c) - { - return cn; - } - } - -// allocate a new one - cn = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - cn->next = NULL; - pr.def_tail->next = cn; - pr.def_tail = cn; - - cn->type = type_vector; - cn->name = "IMMEDIATE"; - cn->constant = true; - cn->initialized = 1; - cn->scope = NULL; // always share immediates - cn->arraysize = 1; - -// copy the immediate to the global area - cn->ofs = QCC_GetFreeOffsetSpace (type_size[type_vector->type]); - - G_FLOAT(cn->ofs+0) = a; - G_FLOAT(cn->ofs+1) = b; - G_FLOAT(cn->ofs+2) = c; - - return cn; -} - -hashtable_t floatconstdefstable; -QCC_def_t *QCC_MakeFloatDef(float value) -{ - QCC_def_t *cn; - - union { - float f; - int i; - } fi; - - fi.f = value; - - cn = Hash_GetKey(&floatconstdefstable, fi.i); - if (cn) - return cn; - -// allocate a new one - cn = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - cn->next = NULL; - pr.def_tail->next = cn; - pr.def_tail = cn; - - cn->s_file = s_file; - cn->s_line = pr_source_line; - cn->type = type_float; - cn->name = "IMMEDIATE"; - cn->constant = true; - cn->initialized = 1; - cn->scope = NULL; // always share immediates - cn->arraysize = 1; - -// copy the immediate to the global area - cn->ofs = QCC_GetFreeOffsetSpace (type_size[type_integer->type]); - - Hash_AddKey(&floatconstdefstable, fi.i, cn, qccHunkAlloc(sizeof(bucket_t))); - - G_FLOAT(cn->ofs) = value; - - - return cn; -} - -extern hashtable_t stringconstdefstable; -extern hashtable_t stringconstdefstable_dotranslate; -QCC_def_t *QCC_MakeStringDef(char *value) -{ - QCC_def_t *cn; - int string; - hashtable_t *tbl = dotranslate ? &stringconstdefstable_dotranslate : &stringconstdefstable; - char buf[64]; - - cn = pHash_Get(tbl, value); - if (cn) - return cn; - -// allocate a new one - cn = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - cn->next = NULL; - pr.def_tail->next = cn; - pr.def_tail = cn; - - cn->type = type_string; - if(dotranslate > 0) - { - sprintf(buf, "dotranslate_%d", ++dotranslate_count); - cn->name = strdup(buf); - } - else - cn->name = "IMMEDIATE"; - cn->constant = true; - cn->initialized = 1; - cn->scope = NULL; // always share immediates - cn->arraysize = 1; - -// copy the immediate to the global area - cn->ofs = QCC_GetFreeOffsetSpace (type_size[type_integer->type]); - - string = QCC_CopyString (value); - - pHash_Add(tbl, strings+string, cn, qccHunkAlloc(sizeof(bucket_t))); - - G_INT(cn->ofs) = string; - - - return cn; -} - -QCC_type_t *QCC_PR_NewType (char *name, int basictype); -QCC_type_t *QCC_PointerTypeTo(QCC_type_t *type) -{ - QCC_type_t *newtype; - newtype = QCC_PR_NewType("POINTER TYPE", ev_pointer); - newtype->aux_type = type; - return newtype; -} - -int basictypefield[ev_union+1]; -char *basictypenames[] = { - "void", - "string", - "float", - "vector", - "entity", - "field", - "function", - "pointer", - "integer", - "struct", - "union" -}; - -QCC_def_t *QCC_MemberInParentClass(char *name, QCC_type_t *clas) -{ //if a member exists, return the member field (rather than mapped-to field) - QCC_type_t *mt; - QCC_def_t *def; - int p, np; - char membername[2048]; - - if (!clas) - { - def = QCC_PR_GetDef(NULL, name, NULL, 0, 0, false); - if (def && def->type->type == ev_field) //the member existed as a normal entity field. - return def; - return NULL; - } - - np = clas->num_parms; - for (p = 0, mt = clas->param; p < np; p++, mt = mt->next) - { - if (strcmp(mt->name, name)) - continue; - - //the parent has it. - - sprintf(membername, "%s::"MEMBERFIELDNAME, clas->name, mt->name); - def = QCC_PR_GetDef(NULL, membername, NULL, false, 0, false); - return def; - } - - return QCC_MemberInParentClass(name, clas->parentclass); -} - -//create fields for the types, instanciate the members to the fields. -//we retouch the parents each time to guarentee polymorphism works. -//FIXME: virtual methods will not work properly. Need to trace down to see if a parent already defined it -void QCC_PR_EmitFieldsForMembers(QCC_type_t *clas) -{ -//we created fields for each class when we defined the actual classes. -//we need to go through each member and match it to the offset of it's parent class, if overloaded, or create a new field if not.. - -//basictypefield is cleared before we do this -//we emit the parent's fields first (every time), thus ensuring that we don't reuse parent fields on a child class. - - char membername[2048]; - int p, np, a; - unsigned int o; - QCC_type_t *mt, *ft; - QCC_def_t *f, *m; - if (clas->parentclass != type_entity) //parents MUST have all their fields set or inheritance would go crazy. - QCC_PR_EmitFieldsForMembers(clas->parentclass); - - np = clas->num_parms; - mt = clas->param; - for (p = 0; p < np; p++, mt = mt->next) - { - sprintf(membername, "%s::"MEMBERFIELDNAME, clas->name, mt->name); - m = QCC_PR_GetDef(NULL, membername, NULL, false, 0, false); - - f = QCC_MemberInParentClass(mt->name, clas->parentclass); - if (f) - { - if (m->arraysize>1) - QCC_Error(ERR_INTERNAL, "FTEQCC does not support overloaded arrays of members"); - a=0; - for (o = 0; o < m->type->size; o++) - ((int *)qcc_pr_globals)[o+a*mt->size+m->ofs] = ((int *)qcc_pr_globals)[o+f->ofs]; - continue; - } - - for (a = 0; a < m->arraysize; a++) - { - //we need the type in here so saved games can still work without saving ints as floats. (would be evil) - ft = QCC_PR_NewType(basictypenames[mt->type], ev_field); - ft->aux_type = QCC_PR_NewType(basictypenames[mt->type], mt->type); - ft->aux_type->aux_type = type_void; - ft->size = ft->aux_type->size; - ft = QCC_PR_FindType(ft); - sprintf(membername, "__f_%s_%i", ft->name, ++basictypefield[mt->type]); - f = QCC_PR_GetDef(ft, membername, NULL, true, 1, true); - - for (o = 0; o < m->type->size; o++) - ((int *)qcc_pr_globals)[o+a*mt->size+m->ofs] = ((int *)qcc_pr_globals)[o+f->ofs]; - - f->references++; - } - } -} - -void QCC_PR_EmitClassFunctionTable(QCC_type_t *clas, QCC_type_t *childclas, QCC_def_t *ed, QCC_def_t **constructor) -{ //go through clas, do the virtual thing only if the child class does not override. - - char membername[2048]; - QCC_type_t *type; - QCC_type_t *oc; - int p; - - QCC_def_t *point, *member; - QCC_def_t *virt; - - if (clas->parentclass) - QCC_PR_EmitClassFunctionTable(clas->parentclass, childclas, ed, constructor); - - type = clas->param; - for (p = 0; p < clas->num_parms; p++, type = type->next) - { - for (oc = childclas; oc != clas; oc = oc->parentclass) - { - sprintf(membername, "%s::"MEMBERFIELDNAME, oc->name, type->name); - if (QCC_PR_GetDef(NULL, membername, NULL, false, 0, false)) - break; //a child class overrides. - } - if (oc != clas) - continue; - - if (type->type == ev_function) //FIXME: inheritance will not install all the member functions. - { - sprintf(membername, "%s::"MEMBERFIELDNAME, clas->name, type->name); - member = QCC_PR_GetDef(NULL, membername, NULL, false, 1, false); - if (!member) - { - QCC_PR_Warning(0, NULL, 0, "Member function %s was not defined", membername); - continue; - } - if (!strcmp(type->name, clas->name)) - { - *constructor = member; - } - point = QCC_PR_Statement(&pr_opcodes[OP_ADDRESS], ed, member, NULL); - sprintf(membername, "%s::%s", clas->name, type->name); - virt = QCC_PR_GetDef(type, membername, NULL, false, 1, false); - QCC_PR_Statement(&pr_opcodes[OP_STOREP_FNC], virt, point, NULL); - } - } -} - -//take all functions in the type, and parent types, and make sure the links all work properly. -void QCC_PR_EmitClassFromFunction(QCC_def_t *scope, char *tname) -{ - QCC_type_t *basetype; - - QCC_dfunction_t *df; - - QCC_def_t *virt; - QCC_def_t *ed, *oself, *self; - QCC_def_t *constructor = NULL; - -// int func; - - basetype = QCC_TypeForName(tname); - if (!basetype) - QCC_PR_ParseError(ERR_INTERNAL, "Type %s was not defined...", tname); - - - pr_scope = NULL; - memset(basictypefield, 0, sizeof(basictypefield)); - QCC_PR_EmitFieldsForMembers(basetype); - - - - - pr_scope = scope; - - df = &functions[numfunctions]; - numfunctions++; - - df->s_file = 0; - df->s_name = 0; - df->first_statement = numstatements; - df->parm_size[0] = 1; - df->numparms = 0; - df->parm_start = numpr_globals; - - G_FUNCTION(scope->ofs) = df - functions; - - //locals here... - ed = QCC_PR_GetDef(type_entity, "ent", pr_scope, true, 1, false); - - virt = QCC_PR_GetDef(type_function, "spawn", NULL, false, 0, false); - if (!virt) - QCC_Error(ERR_INTERNAL, "spawn function was not defined\n"); - QCC_PR_SimpleStatement(OP_CALL0, virt->ofs, 0, 0, false); //calling convention doesn't come into it. - - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_ENT], &def_ret, ed, NULL)); - - ed->references = 1; //there may be no functions. - - - QCC_PR_EmitClassFunctionTable(basetype, basetype, ed, &constructor); - - if (constructor) - { //self = ent; - self = QCC_PR_GetDef(type_entity, "self", NULL, false, 0, false); - oself = QCC_PR_GetDef(type_entity, "oself", scope, true, 1, false); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_ENT], self, oself, NULL)); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_ENT], ed, self, NULL)); //return to our old self. boom boom. - QCC_PR_SimpleStatement(OP_CALL0, constructor->ofs, 0, 0, false); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_ENT], oself, self, NULL)); - } - - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_RETURN], ed, NULL, NULL)); //apparently we do actually have to return something. *sigh*... - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_DONE], NULL, NULL, NULL)); - - - - QCC_WriteAsmFunction(scope, df->first_statement, df->parm_start); - pr.localvars = NULL; - - - locals_end = numpr_globals + basetype->size; - df->locals = locals_end - df->parm_start; -} -/* -============ -PR_ParseValue - -Returns the global ofs for the current token -============ -*/ -QCC_def_t *QCC_PR_ParseValue (QCC_type_t *assumeclass, pbool allowarrayassign) -{ - QCC_def_t *ao=NULL; //arrayoffset - QCC_def_t *d, *nd, *od; - char *name; - QCC_dstatement_t *st; - int i; - static QCC_def_t intrinsic = { - NULL, // QCC_type_t *type; - NULL, // char *name; - NULL, // struct QCC_def_s *next; - NULL, // struct QCC_def_s *nextlocal; //provides a chain of local variables for the opt_locals_marshalling optimisation. - 0, // gofs_t ofs; - NULL, // struct QCC_def_s *scope; // function the var was defined in, or NULL - 1, // int initialized; // 1 when a declaration included "= immediate" - 1, // int constant; // 1 says we can use the value over and over again - 1, // int references; - 0, // int timescalled; //part of the opt_stripfunctions optimisation. - 0, // int s_file; - 0, // int s_line; - 0, // int arraysize; - 0, // pbool shared; - 0, // pbool saved; - 0, // pbool isstatic; - NULL // temp_t *temp; - }; - - char membername[2048]; - -// if the token is an immediate, allocate a constant for it - if (pr_token_type == tt_immediate) - return QCC_PR_ParseImmediate (); - - if (QCC_PR_CheckToken("[")) //reacc support - { //looks like a funky vector. :) - vec3_t v; - pr_immediate_type = type_vector; - v[0] = pr_immediate._float; - QCC_PR_Lex(); - v[1] = pr_immediate._float; - QCC_PR_Lex(); - v[2] = pr_immediate._float; - pr_immediate.vector[0] = v[0]; - pr_immediate.vector[1] = v[1]; - pr_immediate.vector[2] = v[2]; - pr_immediate_type = type_vector; - d = QCC_PR_ParseImmediate(); - QCC_PR_Expect("]"); - return d; - } - name = QCC_PR_ParseName (); - - if (assumeclass && assumeclass->parentclass) // 'testvar' becomes 'self::testvar' - { //try getting a member. - QCC_type_t *type; - type = assumeclass; - d = NULL; - while(type != type_entity && type) - { - sprintf(membername, "%s::"MEMBERFIELDNAME, type->name, name); - od = d = QCC_PR_GetDef (NULL, membername, pr_scope, false, 0, false); - if (d) - break; - - type = type->parentclass; - } - if (!d) - od = d = QCC_PR_GetDef (NULL, name, pr_scope, false, 0, false); - } - else - -// look through the defs - od = d = QCC_PR_GetDef (NULL, name, pr_scope, false, 0, false); - - if (!d) - { - if ( (!strcmp(name, "random" )) || - (!strcmp(name, "randomv")) || - (!strcmp(name, "entnum")) || - (!strcmp(name, "_")) ) //intrinsics, any old function with no args will do. - { - intrinsic.name = name; - intrinsic.type = type_function; // can't put that in the static var - od = d = &intrinsic; - } - else if (keyword_class && !strcmp(name, "this")) - { - if (!pr_classtype) - QCC_PR_ParseError(ERR_NOTANAME, "Cannot use 'this' outside of an OO function\n"); - od = QCC_PR_GetDef(NULL, "self", NULL, true, 1, false); - od = d = QCC_PR_DummyDef(pr_classtype, "this", pr_scope, 1, od->ofs, true, false); - } - else if (keyword_class && !strcmp(name, "super")) - { - if (!pr_classtype) - QCC_PR_ParseError(ERR_NOTANAME, "Cannot use 'super' outside of an OO function\n"); - od = QCC_PR_GetDef(NULL, "self", NULL, true, 1, false); - od = d = QCC_PR_DummyDef(pr_classtype, "super", pr_scope, 1, od->ofs, true, false); - } - else - { - od = d = QCC_PR_GetDef (type_variant, name, pr_scope, true, 1, false); - if (!d) - QCC_PR_ParseError (ERR_UNKNOWNVALUE, "Unknown value \"%s\"", name); - else - { - QCC_PR_ParseWarning (ERR_UNKNOWNVALUE, "Unknown value \"%s\".", name); - } - } - } - -reloop: - - -//FIXME: Make this work with double arrays/2nd level structures. -//Should they just jump back to here? - if (QCC_PR_CheckToken("[")) - { - QCC_type_t *newtype; - if (ao) - { - numstatements--; //remove the last statement - - nd = QCC_PR_Expression (TOP_PRIORITY, 0); - QCC_PR_Expect("]"); - - if (d->type->size != 1) //we need to multiply it to find the offset. - { - if (ao->type->type == ev_integer) - nd = QCC_PR_Statement(&pr_opcodes[OP_MUL_I], nd, QCC_MakeIntDef(d->type->size), NULL); //get add part - else if (ao->type->type == ev_float) - nd = QCC_PR_Statement(&pr_opcodes[OP_MUL_F], nd, QCC_MakeFloatDef((float)d->type->size), NULL); //get add part - else - { - QCC_PR_ParseError(ERR_BADARRAYINDEXTYPE, "Array offset is not of integer or float type"); - nd = NULL; - } - } - - if (nd->type->type == ao->type->type) - { - if (ao->type->type == ev_integer) - ao = QCC_PR_Statement(&pr_opcodes[OP_ADD_I], ao, nd, NULL); //get add part - else if (ao->type->type == ev_float) - ao = QCC_PR_Statement(&pr_opcodes[OP_ADD_F], ao, nd, NULL); //get add part - else - { - QCC_PR_ParseError(ERR_BADARRAYINDEXTYPE, "Array offset is not of integer or float type"); - nd = NULL; - } - } - else - { - if (nd->type->type == ev_float) - nd = QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], nd, 0, NULL); - ao = QCC_PR_Statement(&pr_opcodes[OP_ADD_I], ao, nd, NULL); //get add part - } - - newtype = d->type; - d = od; - } - else - { - ao = QCC_PR_Expression (TOP_PRIORITY, 0); - QCC_PR_Expect("]"); - - if (QCC_OPCodeValid(&pr_opcodes[OP_LOADA_F]) && d->type->size != 1) //we need to multiply it to find the offset. - { - if (ao->type->type == ev_integer) - ao = QCC_PR_Statement(&pr_opcodes[OP_MUL_I], ao, QCC_MakeIntDef(d->type->size), NULL); //get add part - else if (ao->type->type == ev_float) - ao = QCC_PR_Statement(&pr_opcodes[OP_MUL_F], ao, QCC_MakeFloatDef((float)d->type->size), NULL); //get add part - else - { - nd = NULL; - QCC_PR_ParseError(ERR_BADARRAYINDEXTYPE, "Array offset is not of integer or float type"); - } - } - - newtype = d->type; - } - if (ao->type->type == ev_integer) - { - switch(newtype->type) - { - case ev_float: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_F], d, ao, NULL); //get pointer to precise def. - break; - case ev_string: - if (d->arraysize <= 1) - { - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_C], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_ITOF], ao, 0, NULL), NULL); //get pointer to precise def. - newtype = nd->type;//don't be fooled - } - else - { - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_S], d, ao, NULL); //get pointer to precise def. - } - break; - case ev_vector: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_V], d, ao, NULL); //get pointer to precise def. - break; - case ev_entity: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_ENT], d, ao, NULL); //get pointer to precise def. - break; - case ev_field: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_FLD], d, ao, NULL); //get pointer to precise def. - break; - case ev_function: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_FNC], d, ao, NULL); //get pointer to precise def. - nd->type = d->type; - break; - case ev_pointer: - if (ao->constant && !G_INT(ao->ofs)) - ao->ofs = 0; - if (d->arraysize>1) //use the array - { - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, ao, NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - } - else - { //dereference the pointer. - switch(newtype->aux_type->type) - { - case ev_pointer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_I], d, ao, NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - case ev_float: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_F], d, ao, NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - case ev_vector: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_V], d, ao, NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - case ev_integer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_I], d, ao, NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - default: - QCC_PR_ParseError(ERR_NOVALIDOPCODES, "No op available. Try assembler"); - nd = NULL; - break; - } - } - break; - case ev_integer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, ao, NULL); //get pointer to precise def. - break; - case ev_struct: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, ao, NULL); //get pointer to precise def. - nd->type = d->type; - break; - default: - QCC_PR_ParseError(ERR_NOVALIDOPCODES, "No op available. Try assembler"); - nd = NULL; - break; - } - d=nd; - } - else if (ao->type->type == ev_float) - { - if (qcc_targetformat == QCF_HEXEN2) - { //hexen2 style retrieval, mixed with q1 style assignments... - if (QCC_PR_CheckToken("=")) //(hideous concept) - { - QCC_def_t *funcretr; - QCC_def_t *args[2]; - if (d->scope) - QCC_PR_ParseError(0, "Scoped array without specific engine support"); - - funcretr = QCC_PR_GetDef(type_function, qcva("ArraySet*%s", d->name), NULL, true, 1, false); - nd = QCC_PR_Expression(TOP_PRIORITY, 0); - if (nd->type->type != d->type->type) - QCC_PR_ParseErrorPrintDef(ERR_TYPEMISMATCH, d, "Type Mismatch on array assignment"); - - args[0] = ao; - args[1] = nd; - return QCC_PR_GenerateFunctionCall(funcretr, args, 2); - } - - switch(newtype->type) - { - case ev_float: - nd = QCC_PR_Statement(&pr_opcodes[OP_FETCH_GBL_F], d, ao, &st); //get pointer to precise def. - st->a = d->ofs; - break; - case ev_vector: - nd = QCC_PR_Statement(&pr_opcodes[OP_FETCH_GBL_V], d, ao, &st); //get pointer to precise def. - st->a = d->ofs; - break; - case ev_string: - nd = QCC_PR_Statement(&pr_opcodes[OP_FETCH_GBL_S], d, ao, &st); //get pointer to precise def. - st->a = d->ofs; - break; - case ev_entity: - nd = QCC_PR_Statement(&pr_opcodes[OP_FETCH_GBL_E], d, ao, &st); //get pointer to precise def. - st->a = d->ofs; - break; - case ev_function: - nd = QCC_PR_Statement(&pr_opcodes[OP_FETCH_GBL_FNC], d, ao, &st); //get pointer to precise def. - st->a = d->ofs; - break; - default: - QCC_PR_ParseError(ERR_NOVALIDOPCODES, "No op available. Try assembler"); - nd = NULL; - break; - } - QCC_FreeTemp(d); - QCC_FreeTemp(ao); - - d=nd; - d->type = newtype; - return d; - } - else - { - if (!QCC_OPCodeValid(&pr_opcodes[OP_LOADA_F])) //q1 compatible. - { //you didn't see this, okay? - QCC_def_t *funcretr; - if (d->scope) - QCC_PR_ParseError(0, "Scoped array without specific engine support"); - - if (allowarrayassign && QCC_PR_CheckToken("=")) - { - QCC_def_t *args[2]; - - funcretr = QCC_PR_GetDef(type_function, qcva("ArraySet*%s", d->name), NULL, true, 1, false); - - nd = QCC_PR_Expression(TOP_PRIORITY, 0); - if (nd->type->type != d->type->type) - QCC_PR_ParseErrorPrintDef(ERR_TYPEMISMATCH, d, "Type Mismatch on array assignment"); - - args[0] = ao; - args[1] = nd; - qcc_usefulstatement=true; - nd = QCC_PR_GenerateFunctionCall(funcretr, args, 2); - nd->type = d->type->aux_type; - } - else - { - QCC_def_t *args[1]; - - def_parms[0].type = type_float; - funcretr = QCC_PR_GetDef(type_function, qcva("ArrayGet*%s", d->name), NULL, true, 1, false); - - args[0] = ao; - nd = QCC_PR_GenerateFunctionCall(funcretr, args, 1); - nd->type = d->type->aux_type; - } - } - else - { - switch(newtype->type) - { - case ev_pointer: - if (d->arraysize>1) //use the array - { - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - } - else - { //dereference the pointer. - switch(newtype->aux_type->type) - { - case ev_pointer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_I], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - case ev_float: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_F], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - case ev_vector: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_V], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - case ev_integer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_I], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - nd->type = d->type->aux_type; - break; - default: - QCC_PR_ParseError(ERR_NOVALIDOPCODES, "No op available. Try assembler"); - nd = NULL; - break; - } - } - break; - - case ev_float: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_F], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - break; - case ev_string: - if (d->arraysize <= 1) - { - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_C], d, ao, NULL); //get pointer to precise def. - newtype = nd->type;//don't be fooled - } - else - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_S], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - break; - case ev_vector: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_V], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - break; - case ev_entity: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_ENT], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - break; - case ev_field: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_FLD], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - break; - case ev_function: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_FNC], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - nd->type = d->type; - break; - case ev_integer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - break; - - case ev_struct: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], ao, 0, NULL), NULL); //get pointer to precise def. - nd->type = d->type; - break; - default: - QCC_PR_ParseError(ERR_NOVALIDOPCODES, "No op available. Try assembler"); - nd = NULL; - break; - } - } - } - d=nd; - } - else - QCC_PR_ParseError(ERR_BADARRAYINDEXTYPE, "Array offset is not of integer or float type"); - - d->type = newtype; - goto reloop; - } - - - i = d->type->type; - if (i == ev_pointer) - { - int j; - QCC_type_t *type; - if (QCC_PR_CheckToken(".") || QCC_PR_CheckToken("->")) - { - for (i = d->type->num_parms, type = d->type+1; i; i--, type++) - { - if (QCC_PR_CheckName(type->name)) - { - //give result - if (ao) - { - numstatements--; //remove the last statement - d = od; - - nd = QCC_MakeIntDef(type->ofs); - ao = QCC_PR_Statement(&pr_opcodes[OP_ADD_I], ao, nd, NULL); //get add part - - //so that we may offset it and readd it. - } - else - ao = QCC_MakeIntDef(type->ofs); - switch (type->type) - { - case ev_float: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_F], d, ao, NULL); //get pointer to precise def. - break; - case ev_string: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_S], d, ao, NULL); //get pointer to precise def. - break; - case ev_vector: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_V], d, ao, NULL); //get pointer to precise def. - break; - case ev_entity: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_ENT], d, ao, NULL); //get pointer to precise def. - break; - case ev_field: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_FLD], d, ao, NULL); //get pointer to precise def. - break; - case ev_function: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_FNC], d, ao, NULL); //get pointer to precise def. - nd->type = type; - break; - case ev_integer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_I], d, ao, NULL); //get pointer to precise def. - break; - -// case ev_struct: - //no suitable op. -// nd = QCC_PR_Statement(&pr_opcodes[OP_LOADP_I], d, ao, NULL); //get pointer to precise def. -// nd->type = type; -// break; - default: - QCC_PR_ParseError(ERR_NOVALIDOPCODES, "No op available. Try assembler"); - nd = NULL; - break; - } - - d=nd; - break; - } - if (type->num_parms) - { - for (j = type->num_parms; j;j--) - type++; - } - } - if (!i) - QCC_PR_ParseError (ERR_MEMBERNOTVALID, "\"%s\" is not a member of \"%s\"", pr_token, od->type->name); - - goto reloop; - } - } - else if (i == ev_struct || i == ev_union) - { - int j; - QCC_type_t *type; - if (QCC_PR_CheckToken(".") || QCC_PR_CheckToken("->")) - { - for (i = d->type->num_parms, type = d->type+1; i; i--, type++) - { - if (QCC_PR_CheckName(type->name)) - { - //give result - if (ao) - { - numstatements--; //remove the last statement - d = od; - - nd = QCC_MakeIntDef(type->ofs); - ao = QCC_PR_Statement(&pr_opcodes[OP_ADD_I], ao, nd, NULL); //get add part - - //so that we may offset it and readd it. - } - else - ao = QCC_MakeIntDef(type->ofs); - switch (type->type) - { - case ev_float: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_F], d, ao, NULL); //get pointer to precise def. - break; - case ev_string: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_S], d, ao, NULL); //get pointer to precise def. - break; - case ev_vector: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_V], d, ao, NULL); //get pointer to precise def. - break; - case ev_entity: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_ENT], d, ao, NULL); //get pointer to precise def. - break; - case ev_field: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_FLD], d, ao, NULL); //get pointer to precise def. - break; - case ev_function: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_FNC], d, ao, NULL); //get pointer to precise def. - nd->type = type; - break; - case ev_integer: - nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, ao, NULL); //get pointer to precise def. - break; - -// case ev_struct: - //no suitable op. -// nd = QCC_PR_Statement(&pr_opcodes[OP_LOADA_I], d, ao, NULL); //get pointer to precise def. -// nd->type = type; -// break; - default: - QCC_PR_ParseError(ERR_NOVALIDOPCODES, "No op available. Try assembler"); - nd = NULL; - break; - } - - d=nd; - break; - } - if (type->num_parms) - { - for (j = type->num_parms; j;j--) - type++; - } - } - if (!i) - QCC_PR_ParseError (ERR_MEMBERNOTVALID, "\"%s\" is not a member of \"%s\"", pr_token, od->type->name); - - goto reloop; - } - } - -/* if (d->type->type == ev_pointer) - { //expand now, not in function call/maths parsing - switch(d->type->aux_type->type) - { - case ev_string: - d = QCC_PR_Statement(&pr_opcodes[OP_LOADP_S], d, NULL, NULL); - break; - case ev_float: - d = QCC_PR_Statement(&pr_opcodes[OP_LOADP_F], d, NULL, NULL); - break; - } - } -*/ - if (!keyword_class) - return d; - - if (d->type->parentclass||d->type->type == ev_entity) //class - { - if (QCC_PR_CheckToken(".") || QCC_PR_CheckToken("->")) - { - QCC_def_t *field; - if (QCC_PR_CheckToken("(")) - { - field = QCC_PR_Expression(TOP_PRIORITY, 0); - QCC_PR_Expect(")"); - } - else - field = QCC_PR_ParseValue(d->type, false); - if (field->type->type == ev_field) - { - if (!field->type->aux_type) - { - QCC_PR_ParseWarning(ERR_INTERNAL, "Field with null aux_type"); - return QCC_PR_Statement(&pr_opcodes[OP_LOAD_FLD], d, field, NULL); - } - else - { - switch(field->type->aux_type->type) - { - default: - QCC_PR_ParseError(ERR_INTERNAL, "Bad field type"); - return d; - case ev_integer: - return QCC_PR_Statement(&pr_opcodes[OP_LOAD_I], d, field, NULL); - case ev_field: - d = QCC_PR_Statement(&pr_opcodes[OP_LOAD_FLD], d, field, NULL); - nd = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - memset (nd, 0, sizeof(QCC_def_t)); - nd->type = field->type->aux_type; - nd->ofs = d->ofs; - nd->temp = d->temp; - nd->constant = false; - nd->name = d->name; - return nd; - case ev_float: - return QCC_PR_Statement(&pr_opcodes[OP_LOAD_F], d, field, NULL); - case ev_string: - return QCC_PR_Statement(&pr_opcodes[OP_LOAD_S], d, field, NULL); - case ev_vector: - return QCC_PR_Statement(&pr_opcodes[OP_LOAD_V], d, field, NULL); - case ev_function: - { //complicated for a typecast - d = QCC_PR_Statement(&pr_opcodes[OP_LOAD_FNC], d, field, NULL); - nd = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - memset (nd, 0, sizeof(QCC_def_t)); - nd->type = field->type->aux_type; - nd->ofs = d->ofs; - nd->temp = d->temp; - nd->constant = false; - nd->name = d->name; - return nd; - - } - case ev_entity: - return QCC_PR_Statement(&pr_opcodes[OP_LOAD_ENT], d, field, NULL); - } - } - } - else - QCC_PR_IncludeChunk(".", false, NULL); - } - } - - return d; -} - - -/* -============ -PR_Term -============ -*/ -QCC_def_t *QCC_PR_Term (void) -{ - QCC_def_t *e, *e2; - etype_t t; - if (pr_token_type == tt_punct) //a little extra speed... - { - if (QCC_PR_CheckToken("++")) - { - qcc_usefulstatement=true; - e = QCC_PR_Term (); - if (e->constant) - QCC_PR_ParseWarning(WARN_ASSIGNMENTTOCONSTANT, "Assignment to constant %s", e->name); - if (e->temp) - QCC_PR_ParseWarning(WARN_ASSIGNMENTTOCONSTANT, "Hey! That's a temp! ++ operators cannot work on temps!"); - switch (e->type->type) - { - case ev_integer: - QCC_PR_Statement3(&pr_opcodes[OP_ADD_I], e, QCC_MakeIntDef(1), e, false); - break; - case ev_float: - QCC_PR_Statement3(&pr_opcodes[OP_ADD_F], e, QCC_MakeFloatDef(1), e, false); - break; - default: - QCC_PR_ParseError(ERR_BADPLUSPLUSOPERATOR, "++ operator on unsupported type"); - break; - } - return e; - } - else if (QCC_PR_CheckToken("--")) - { - qcc_usefulstatement=true; - e = QCC_PR_Term (); - if (e->constant) - QCC_PR_ParseWarning(WARN_ASSIGNMENTTOCONSTANT, "Assignment to constant %s", e->name); - if (e->temp) - QCC_PR_ParseWarning(WARN_ASSIGNMENTTOCONSTANT, "Hey! That's a temp! -- operators cannot work on temps!"); - switch (e->type->type) - { - case ev_integer: - QCC_PR_Statement3(&pr_opcodes[OP_SUB_I], e, QCC_MakeIntDef(1), e, false); - break; - case ev_float: - QCC_PR_Statement3(&pr_opcodes[OP_SUB_F], e, QCC_MakeFloatDef(1), e, false); - break; - default: - QCC_PR_ParseError(ERR_BADPLUSPLUSOPERATOR, "-- operator on unsupported type"); - break; - } - return e; - } - - if (QCC_PR_CheckToken ("!")) - { - e = QCC_PR_Expression (NOT_PRIORITY, EXPR_DISALLOW_COMMA|EXPR_WARN_ABOVE_1); - t = e->type->type; - if (t == ev_float) - e2 = QCC_PR_Statement (&pr_opcodes[OP_NOT_F], e, 0, NULL); - else if (t == ev_string) - e2 = QCC_PR_Statement (&pr_opcodes[OP_NOT_S], e, 0, NULL); - else if (t == ev_entity) - e2 = QCC_PR_Statement (&pr_opcodes[OP_NOT_ENT], e, 0, NULL); - else if (t == ev_vector) - e2 = QCC_PR_Statement (&pr_opcodes[OP_NOT_V], e, 0, NULL); - else if (t == ev_function) - e2 = QCC_PR_Statement (&pr_opcodes[OP_NOT_FNC], e, 0, NULL); - else if (t == ev_integer) - e2 = QCC_PR_Statement (&pr_opcodes[OP_NOT_FNC], e, 0, NULL); //functions are integer values too. - else if (t == ev_pointer) - e2 = QCC_PR_Statement (&pr_opcodes[OP_NOT_FNC], e, 0, NULL); //Pointers are too. - else - { - e2 = NULL; // shut up compiler warning; - QCC_PR_ParseError (ERR_BADNOTTYPE, "type mismatch for !"); - } - return e2; - } - - else if (QCC_PR_CheckToken ("&")) - { - int st = numstatements; - e = QCC_PR_Expression (UNARY_PRIORITY, 0); - t = e->type->type; - - if (st != numstatements) - //woo, something like ent.field? - { - if ((unsigned)(statements[numstatements-1].op - OP_LOAD_F) < 6 || statements[numstatements-1].op == OP_LOAD_I || statements[numstatements-1].op == OP_LOAD_P) - { - statements[numstatements-1].op = OP_ADDRESS; - e->type = QCC_PR_PointerType(e->type); - return e; - } - else //this is a restriction that could be lifted, I just want to make sure that I got all the bits first. - { - QCC_PR_ParseError (ERR_BADNOTTYPE, "type mismatch for '&' Must be singular expression or field reference"); - return e; - } - } -// QCC_PR_ParseWarning(0, "debug: &global"); - - if (!QCC_OPCodeValid(&pr_opcodes[OP_GLOBALADDRESS])) - QCC_PR_ParseError (ERR_BADEXTENSION, "Cannot use addressof operator ('&') on a global. Please use the FTE target."); - - e2 = QCC_PR_Statement (&pr_opcodes[OP_GLOBALADDRESS], e, 0, NULL); - e2->type = QCC_PR_PointerType(e->type); - return e2; - } - else if (QCC_PR_CheckToken ("*")) - { - e = QCC_PR_Expression (UNARY_PRIORITY, 0); - t = e->type->type; - - if (t != ev_pointer) - QCC_PR_ParseError (ERR_BADNOTTYPE, "type mismatch for *"); - - switch(e->type->aux_type->type) - { - case ev_float: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_F], e, 0, NULL); - break; - case ev_string: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_S], e, 0, NULL); - break; - case ev_vector: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_V], e, 0, NULL); - break; - case ev_entity: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_ENT], e, 0, NULL); - break; - case ev_field: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_FLD], e, 0, NULL); - break; - case ev_function: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_FLD], e, 0, NULL); - break; - case ev_integer: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_I], e, 0, NULL); - break; - case ev_pointer: - e2 = QCC_PR_Statement (&pr_opcodes[OP_LOADP_I], e, 0, NULL); - break; - - default: - QCC_PR_ParseError (ERR_BADNOTTYPE, "type mismatch for * (unrecognised type)"); - e2 = NULL; - break; - } - - e2->type = e->type->aux_type; - return e2; - } - else if (QCC_PR_CheckToken ("-")) - { - e = QCC_PR_Expression (UNARY_PRIORITY, 0); - - switch(e->type->type) - { - case ev_float: - e2 = QCC_PR_Statement (&pr_opcodes[OP_SUB_F], QCC_MakeFloatDef(0), e, NULL); - break; - case ev_vector: - e2 = QCC_PR_Statement (&pr_opcodes[OP_SUB_V], QCC_MakeVectorDef(0, 0, 0), e, NULL); - break; - case ev_integer: - e2 = QCC_PR_Statement (&pr_opcodes[OP_SUB_I], QCC_MakeIntDef(0), e, NULL); - break; - default: - QCC_PR_ParseError (ERR_BADNOTTYPE, "type mismatch for -"); - e2 = NULL; - break; - } - return e2; - } - else if (QCC_PR_CheckToken ("+")) - { - e = QCC_PR_Expression (UNARY_PRIORITY, 0); - - switch(e->type->type) - { - case ev_float: - e2 = e; - break; - case ev_vector: - e2 = e; - break; - case ev_integer: - e2 = e; - break; - default: - QCC_PR_ParseError (ERR_BADNOTTYPE, "type mismatch for +"); - e2 = NULL; - break; - } - return e2; - } - - if (QCC_PR_CheckToken ("(")) - { - if (QCC_PR_CheckKeyword(keyword_float, "float")) //check for type casts - { - QCC_PR_Expect (")"); - e = QCC_PR_Term(); - if (e->type->type == ev_float) - return e; - else if (e->type->type == ev_integer) - return QCC_PR_Statement (&pr_opcodes[OP_CONV_ITOF], e, 0, NULL); - else if (e->type->type == ev_function) - return e; - // else - // QCC_PR_ParseError ("invalid typecast"); - - QCC_PR_ParseWarning (0, "Not all vars make sence as floats"); - - e2 = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - memset (e2, 0, sizeof(QCC_def_t)); - e2->type = type_float; - e2->ofs = e->ofs; - e2->constant = true; - e2->temp = e->temp; - return e2; - } - else if (QCC_PR_CheckKeyword(keyword_class, "class")) - { - QCC_type_t *classtype = QCC_TypeForName(QCC_PR_ParseName()); - if (!classtype) - QCC_PR_ParseError(ERR_NOTANAME, "Class not defined for cast"); - - QCC_PR_Expect (")"); - e = QCC_PR_Term(); - e2 = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - memset (e2, 0, sizeof(QCC_def_t)); - e2->type = classtype; - e2->ofs = e->ofs; - e2->constant = true; - e2->temp = e->temp; - return e2; - } - else if (QCC_PR_CheckKeyword(keyword_integer, "integer")) //check for type casts - { - QCC_PR_Expect (")"); - e = QCC_PR_Term(); - if (e->type->type == ev_integer) - return e; - else if (e->type->type == ev_float) - return QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], e, 0, NULL); - else - QCC_PR_ParseError (ERR_BADTYPECAST, "invalid typecast"); - } - else if (QCC_PR_CheckKeyword(keyword_int, "int")) //check for type casts - { - QCC_PR_Expect (")"); - e = QCC_PR_Term(); - if (e->type->type == ev_integer) - return e; - else if (e->type->type == ev_float) - return QCC_PR_Statement (&pr_opcodes[OP_CONV_FTOI], e, 0, NULL); - else - QCC_PR_ParseError (ERR_BADTYPECAST, "invalid typecast"); - } - else - { - pbool oldcond = conditional; - conditional = conditional?2:0; - e = QCC_PR_Expression (TOP_PRIORITY, 0); - QCC_PR_Expect (")"); - conditional = oldcond; - } - return e; - } - } - return QCC_PR_ParseValue (pr_classtype, true); -} - - -int QCC_canConv(QCC_def_t *from, etype_t to) -{ - if (from->type->type == to) - return 0; - - if (from->type->type == ev_vector && to == ev_float) - return 4; - - if (pr_classtype) - { - if (from->type->type == ev_field) - { - if (from->type->aux_type->type == to) - return 1; - } - } - -/* if (from->type->type == ev_pointer && from->type->aux_type->type == to) - return 1; - - if (QCC_ShouldConvert(from, to)>=0) - return 1; -*/ - if (from->type->type == ev_integer && to == ev_function) - return 1; - - return -100; -} -/* -============== -PR_Expression -============== -*/ - -QCC_def_t *QCC_PR_Expression (int priority, int exprflags) -{ - QCC_dstatement32_t *st; - QCC_opcode_t *op, *oldop; - - QCC_opcode_t *bestop; - int numconversions, c; - - int opnum; - - QCC_def_t *e, *e2; - etype_t type_a, type_b, type_c; - - if (priority == 0) - return QCC_PR_Term (); - - e = QCC_PR_Expression (priority-1, exprflags); - - while (1) - { - if (priority == 1) - { - if (QCC_PR_CheckToken ("(") ) - { - qcc_usefulstatement=true; - e = QCC_PR_ParseFunctionCall (e); - } - if (QCC_PR_CheckToken ("?")) - { - QCC_dstatement32_t *fromj, *elsej; - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_IFNOT], e, NULL, &fromj)); - e = QCC_PR_Expression(TOP_PRIORITY, 0); - e2 = QCC_GetTemp(e->type); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[(e2->type->size>=3)?OP_STORE_V:OP_STORE_F], e, e2, NULL)); - //e2 can be stomped upon until its reused anyway - QCC_UnFreeTemp(e2); - - QCC_PR_Expect(":"); - QCC_PR_Statement(&pr_opcodes[OP_GOTO], NULL, NULL, &elsej); - fromj->b = &statements[numstatements] - fromj; - e = QCC_PR_Expression(TOP_PRIORITY, 0); - - if (typecmp(e->type, e2->type) != 0) - QCC_PR_ParseError(0, "Ternary operator with mismatching types\n"); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[(e2->type->size>=3)?OP_STORE_V:OP_STORE_F], e, e2, NULL)); - QCC_UnFreeTemp(e2); - - elsej->a = &statements[numstatements] - elsej; - return e2; - } - } - - opnum=0; - - if (pr_token_type == tt_immediate) - { - if (pr_immediate_type->type == ev_float) - if (pr_immediate._float < 0) //hehehe... was a minus all along... - { - QCC_PR_IncludeChunk(pr_token, true, NULL); - strcpy(pr_token, "+");//two negatives would make a positive. - pr_token_type = tt_punct; - } - } - - if (pr_token_type != tt_punct) - { - QCC_PR_ParseWarning(WARN_UNEXPECTEDPUNCT, "Expected punctuation"); - } - - //go straight for the correct priority. - for (op = opcodeprioritized[priority][opnum]; op; op = opcodeprioritized[priority][++opnum]) -// for (op=pr_opcodes ; op->name ; op++) - { -// if (op->priority != priority) -// continue; - if (!QCC_PR_CheckToken (op->name)) - continue; - st = NULL; - if ( op->associative!=ASSOC_LEFT ) - { - // if last statement is an indirect, change it to an address of - if (!simplestore && ((unsigned)(statements[numstatements-1].op - OP_LOAD_F) < 6 || statements[numstatements-1].op == OP_LOAD_I || statements[numstatements-1].op == OP_LOAD_P) && statements[numstatements-1].c == e->ofs) - { - qcc_usefulstatement=true; - statements[numstatements-1].op = OP_ADDRESS; - type_pointer->aux_type->type = e->type->type; - e->type = type_pointer; - } - //if last statement retrieved a value, switch it to retrieve a usable pointer. - if ( !simplestore && (unsigned)(statements[numstatements-1].op - OP_LOADA_F) < 7)// || statements[numstatements-1].op == OP_LOADA_C) - { - statements[numstatements-1].op = OP_GLOBALADDRESS; - type_pointer->aux_type->type = e->type->type; - e->type = type_pointer; - } - if ( !simplestore && (unsigned)(statements[numstatements-1].op - OP_LOADP_F) < 7 && statements[numstatements-1].c == e->ofs) - { - if (!statements[numstatements-1].b) - { - //if the loadp has no offset, remove the instruction and convert the dest of this instruction directly to the pointer's load address - //this kills the add 0. - e->ofs = statements[numstatements-1].a; - numstatements--; - - if (e->type->type != ev_pointer) - { - type_pointer->aux_type->type = e->type->type; - e->type = type_pointer; - } - } - else - { - statements[numstatements-1].op = OP_ADD_I; - if (e->type->type != ev_pointer) - { - type_pointer->aux_type->type = e->type->type; - e->type = type_pointer; - } - } - } - if ( !simplestore && statements[numstatements-1].op == OP_LOADP_C && e->ofs == statements[numstatements-1].c) - { - statements[numstatements-1].op = OP_ADD_SF; - e->type = type_string; - - //now we want to make sure that string = float can't work without it being a dereferenced pointer. (we don't want to allow storep_c without dereferece) - e2 = QCC_PR_Expression (priority, exprflags); - if (e2->type->type == ev_float) - op = &pr_opcodes[OP_STOREP_C]; - } - else - e2 = QCC_PR_Expression (priority, exprflags); - } - else - { - if (op->priority == 7 && opt_logicops) - { - optres_logicops++; - st = &statements[numstatements]; - if (*op->name == '&') //statement 3 because we don't want to optimise this into if from not ifnot - QCC_PR_Statement3(&pr_opcodes[OP_IFNOT], e, NULL, NULL, false); - else - QCC_PR_Statement3(&pr_opcodes[OP_IF], e, NULL, NULL, false); - } - - e2 = QCC_PR_Expression (priority-1, exprflags); - } - - // type check - type_a = e->type->type; - type_b = e2->type->type; - -// if (type_a == ev_pointer && type_b == ev_pointer) -// QCC_PR_ParseWarning(0, "Debug: pointer op pointer"); - - if (op->name[0] == '.')// field access gets type from field - { - if (e2->type->aux_type) - type_c = e2->type->aux_type->type; - else - type_c = -1; // not a field - } - else - type_c = ev_void; - - oldop = op; - bestop = NULL; - numconversions = 32767; - while (op) - { - if (!(type_c != ev_void && type_c != (*op->type_c)->type)) - { - if (!STRCMP (op->name , oldop->name)) //matches - { - //return values are never converted - what to? - // if (type_c != ev_void && type_c != op->type_c->type->type) - // { - // op++; - // continue; - // } - - if (op->associative!=ASSOC_LEFT) - {//assignment - if (op->type_a == &type_pointer) //ent var - { - if (e->type->type != ev_pointer) - c = -200; //don't cast to a pointer. - else if ((*op->type_c)->type == ev_void && op->type_b == &type_pointer && e2->type->type == ev_pointer) - c = 0; //generic pointer... fixme: is this safe? make sure both sides are equivelent - else if (e->type->aux_type->type != (*op->type_b)->type) //if e isn't a pointer to a type_b - c = -200; //don't let the conversion work - else - c = QCC_canConv(e2, (*op->type_c)->type); - } - else - { - c=QCC_canConv(e2, (*op->type_b)->type); - if (type_a != (*op->type_a)->type) //in this case, a is the final assigned value - c = -300; //don't use this op, as we must not change var b's type - } - } - else - { - if (op->type_a == &type_pointer) //ent var - { - if (e2->type->type != ev_pointer || e2->type->aux_type->type != (*op->type_b)->type) //if e isn't a pointer to a type_b - c = -200; //don't let the conversion work - else - c = 0; - } - else - { - c=QCC_canConv(e, (*op->type_a)->type); - c+=QCC_canConv(e2, (*op->type_b)->type); - } - } - - if (c>=0 && c < numconversions) - { - bestop = op; - numconversions=c; - if (c == 0)//can't get less conversions than 0... - break; - } - } - else - break; - } - op = opcodeprioritized[priority][++opnum]; - } - if (bestop == NULL) - { - if (oldop->priority == CONDITION_PRIORITY) - op = oldop; - else - { - if (flag_laxcasts) - { - op = oldop; - QCC_PR_ParseWarning(WARN_LAXCAST, "type mismatch for %s (%s and %s)", oldop->name, e->type->name, e2->type->name); - } - else - QCC_PR_ParseError (ERR_TYPEMISMATCH, "type mismatch for %s (%s and %s)", oldop->name, e->type->name, e2->type->name); - } - } - else - { - if (numconversions>3) - QCC_PR_ParseWarning(WARN_IMPLICITCONVERSION, "Implicit conversion"); - op = bestop; - } - -// if (type_a == ev_pointer && type_b != e->type->aux_type->type) -// QCC_PR_ParseError ("type mismatch for %s", op->name); - - if (st) - st->b = &statements[numstatements] - st; - - - if (op->associative!=ASSOC_LEFT) - { - qcc_usefulstatement = true; - if (e->constant || e->ofs < OFS_PARM0) - { - if (e->type->type == ev_function) - { - QCC_PR_ParseWarning(WARN_ASSIGNMENTTOCONSTANTFUNC, "Assignment to function %s", e->name); - QCC_PR_ParsePrintDef(WARN_ASSIGNMENTTOCONSTANTFUNC, e); - } - else - { - QCC_PR_ParseWarning(WARN_ASSIGNMENTTOCONSTANT, "Assignment to constant %s", e->name); - QCC_PR_ParsePrintDef(WARN_ASSIGNMENTTOCONSTANT, e); - } -#ifndef QCC - editbadfile(strings+s_file, pr_source_line); -#endif - } - if (conditional&1) - QCC_PR_ParseWarning(WARN_ASSIGNMENTINCONDITIONAL, "Assignment in conditional"); - - e = QCC_PR_Statement (op, e2, e, NULL); - } - else - e = QCC_PR_Statement (op, e, e2, NULL); - - if (type_c != ev_void/* && type_c != ev_string*/) // field access gets type from field - e->type = e2->type->aux_type; - - if (priority > 1 && exprflags & EXPR_WARN_ABOVE_1) - QCC_PR_ParseWarning(0, "You may wish to add brackets after that ! operator"); - - break; - } - if (!op) - { - if (e == NULL) - QCC_PR_ParseError(ERR_INTERNAL, "e == null"); - - - if (!STRCMP(pr_token, "++")) - { - //if the last statement was an ent.float (or something) - if (((unsigned)(statements[numstatements-1].op - OP_LOAD_F) < 6 || statements[numstatements-1].op == OP_LOAD_I) && statements[numstatements-1].c == e->ofs) - { //we have our load. - QCC_def_t *e3; -//the only inefficiency here is with an extra temp (we can't reuse the original) -//this is not a problem, as the optimise temps or locals marshalling can clean these up for us - qcc_usefulstatement=true; -//load -//add to temp -//store temp to offset -//return original loaded (which is not at the same offset as the pointer we store to) - e2 = QCC_GetTemp(type_float); - e3 = QCC_GetTemp(type_pointer); - QCC_PR_SimpleStatement(OP_ADDRESS, statements[numstatements-1].a, statements[numstatements-1].b, e3->ofs, false); - if (e->type->type == ev_float) - { - QCC_PR_Statement3(&pr_opcodes[OP_ADD_F], e, QCC_MakeFloatDef(1), e2, false); - QCC_PR_Statement3(&pr_opcodes[OP_STOREP_F], e2, e3, NULL, false); - } - else if (e->type->type == ev_integer) - { - QCC_PR_Statement3(&pr_opcodes[OP_ADD_I], e, QCC_MakeIntDef(1), e2, false); - QCC_PR_Statement3(&pr_opcodes[OP_STOREP_I], e2, e3, NULL, false); - } - else - { - QCC_PR_ParseError(ERR_PARSEERRORS, "-- suffix operator results in nonstandard behaviour. Use -=1 or prefix form instead"); - QCC_PR_IncludeChunk("-=1", false, NULL); - } - QCC_FreeTemp(e2); - QCC_FreeTemp(e3); - } - else if (e->type->type == ev_float) - { -//copy to temp -//add to original -//return temp (which == original) - QCC_PR_ParseWarning(WARN_INEFFICIENTPLUSPLUS, "++ suffix operator results in inefficient behaviour. Use +=1 or prefix form instead"); - qcc_usefulstatement=true; - - e2 = QCC_GetTemp(type_float); - QCC_PR_Statement3(&pr_opcodes[OP_STORE_F], e, e2, NULL, false); - QCC_PR_Statement3(&pr_opcodes[OP_ADD_F], e, QCC_MakeFloatDef(1), e, false); - QCC_FreeTemp(e); - e = e2; - } - else if (e->type->type == ev_integer) - { - QCC_PR_ParseWarning(WARN_INEFFICIENTPLUSPLUS, "++ suffix operator results in inefficient behaviour. Use +=1 or prefix form instead"); - qcc_usefulstatement=true; - - e2 = QCC_GetTemp(type_integer); - QCC_PR_Statement3(&pr_opcodes[OP_STORE_I], e, e2, NULL, false); - QCC_PR_Statement3(&pr_opcodes[OP_ADD_I], e, QCC_MakeIntDef(1), e, false); - QCC_FreeTemp(e); - e = e2; - } - else - { - QCC_PR_ParseWarning(WARN_NOTSTANDARDBEHAVIOUR, "++ suffix operator results in nonstandard behaviour. Use +=1 or prefix form instead"); - QCC_PR_IncludeChunk("+=1", false, NULL); - } - QCC_PR_Lex(); - } - else if (!STRCMP(pr_token, "--")) - { - if (((unsigned)(statements[numstatements-1].op - OP_LOAD_F) < 6 || statements[numstatements-1].op == OP_LOAD_I) && statements[numstatements-1].c == e->ofs) - { //we have our load. - QCC_def_t *e3; -//load -//add to temp -//store temp to offset -//return original loaded (which is not at the same offset as the pointer we store to) - e2 = QCC_GetTemp(type_float); - e3 = QCC_GetTemp(type_pointer); - QCC_PR_SimpleStatement(OP_ADDRESS, statements[numstatements-1].a, statements[numstatements-1].b, e3->ofs, false); - if (e->type->type == ev_float) - { - QCC_PR_Statement3(&pr_opcodes[OP_SUB_F], e, QCC_MakeFloatDef(1), e2, false); - QCC_PR_Statement3(&pr_opcodes[OP_STOREP_F], e2, e3, NULL, false); - } - else if (e->type->type == ev_integer) - { - QCC_PR_Statement3(&pr_opcodes[OP_SUB_I], e, QCC_MakeIntDef(1), e2, false); - QCC_PR_Statement3(&pr_opcodes[OP_STOREP_I], e2, e3, NULL, false); - } - else - { - QCC_PR_ParseError(ERR_PARSEERRORS, "-- suffix operator results in nonstandard behaviour. Use -=1 or prefix form instead"); - QCC_PR_IncludeChunk("-=1", false, NULL); - } - QCC_FreeTemp(e2); - QCC_FreeTemp(e3); - } - else if (e->type->type == ev_float) - { - QCC_PR_ParseWarning(WARN_INEFFICIENTPLUSPLUS, "-- suffix operator results in inefficient behaviour. Use -=1 or prefix form instead"); - qcc_usefulstatement=true; - - e2 = QCC_GetTemp(type_float); - QCC_PR_Statement3(&pr_opcodes[OP_STORE_F], e, e2, NULL, false); - QCC_PR_Statement3(&pr_opcodes[OP_SUB_F], e, QCC_MakeFloatDef(1), e, false); - QCC_FreeTemp(e); - e = e2; - } - else if (e->type->type == ev_integer) - { - QCC_PR_ParseWarning(WARN_INEFFICIENTPLUSPLUS, "-- suffix operator results in inefficient behaviour. Use -=1 or prefix form instead"); - qcc_usefulstatement=true; - - e2 = QCC_GetTemp(type_integer); - QCC_PR_Statement3(&pr_opcodes[OP_STORE_I], e, e2, NULL, false); - QCC_PR_Statement3(&pr_opcodes[OP_SUB_I], e, QCC_MakeIntDef(1), e, false); - QCC_FreeTemp(e); - e = e2; - } - else - { - QCC_PR_ParseWarning(WARN_NOTSTANDARDBEHAVIOUR, "-- suffix operator results in nonstandard behaviour. Use -=1 or prefix form instead"); - QCC_PR_IncludeChunk("-=1", false, NULL); - } - QCC_PR_Lex(); - } - break; // next token isn't at this priority level - } - } - if (e == NULL) - QCC_PR_ParseError(ERR_INTERNAL, "e == null"); - - if (!(exprflags&EXPR_DISALLOW_COMMA) && priority == TOP_PRIORITY && QCC_PR_CheckToken (",")) - { - QCC_FreeTemp(e); - return QCC_PR_Expression(TOP_PRIORITY, exprflags); - } - - return e; -} - -void QCC_PR_GotoStatement (QCC_dstatement_t *patch2, char *labelname) -{ - if (num_gotos >= max_gotos) - { - max_gotos += 8; - pr_gotos = realloc(pr_gotos, sizeof(*pr_gotos)*max_gotos); - } - - strncpy(pr_gotos[num_gotos].name, labelname, sizeof(pr_gotos[num_gotos].name) -1); - pr_gotos[num_gotos].lineno = pr_source_line; - pr_gotos[num_gotos].statementno = patch2 - statements; - - num_gotos++; -} - -pbool QCC_PR_StatementBlocksMatch(QCC_dstatement_t *p1, int p1count, QCC_dstatement_t *p2, int p2count) -{ - if (p1count != p2count) - return false; - - while(p1count>0) - { - if (p1->op != p2->op) - return false; - if (p1->a != p2->a) - return false; - if (p1->b != p2->b) - return false; - if (p1->c != p2->c) - return false; - p1++; - p2++; - p1count--; - } - - return true; -} - -/* -============ -PR_ParseStatement - -============ -*/ -void QCC_PR_ParseStatement (void) -{ - int continues; - int breaks; - int cases; - int i; - QCC_def_t *e, *e2; - QCC_dstatement_t *patch1, *patch2, *patch3; - int statementstart = pr_source_line; - - if (QCC_PR_CheckToken ("{")) - { - e = pr.localvars; - while (!QCC_PR_CheckToken("}")) - QCC_PR_ParseStatement (); - - if (pr_subscopedlocals) - { - for (e2 = pr.localvars; e2 != e; e2 = e2->nextlocal) - { - Hash_RemoveData(&localstable, e2->name, e2); - } - } - return; - } - - if (QCC_PR_CheckKeyword(keyword_return, "return")) - { - /*if (pr_classtype) - { - e = QCC_PR_GetDef(NULL, "__oself", pr_scope, false, 0); - e2 = QCC_PR_GetDef(NULL, "self", NULL, false, 0); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_ENT], e, QCC_PR_DummyDef(pr_classtype, "self", pr_scope, 1, e2->ofs, false), NULL)); - }*/ - - if (QCC_PR_CheckToken (";")) - { - if (pr_scope->type->aux_type->type != ev_void) - QCC_PR_ParseWarning(WARN_MISSINGRETURNVALUE, "\'%s\' should return %s", pr_scope->name, pr_scope->type->aux_type->name); - if (opt_return_only) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_DONE], 0, 0, NULL)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_RETURN], 0, 0, NULL)); - return; - } - e = QCC_PR_Expression (TOP_PRIORITY, 0); - e2 = QCC_SupplyConversion(e, pr_scope->type->aux_type->type); - if (e != e2) - { - QCC_PR_ParseWarning(WARN_CORRECTEDRETURNTYPE, "\'%s\' returned %s, expected %s, conversion supplied", pr_scope->name, e->type->name, pr_scope->type->aux_type->name); - e = e2; - } - QCC_PR_Expect (";"); - if (pr_scope->type->aux_type->type != e->type->type) - QCC_PR_ParseWarning(WARN_WRONGRETURNTYPE, "\'%s\' returned %s, expected %s", pr_scope->name, e->type->name, pr_scope->type->aux_type->name); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_RETURN], e, 0, NULL)); - return; - } - if (QCC_PR_CheckKeyword(keyword_exit, "exit")) - { - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_DONE], 0, 0, NULL)); - QCC_PR_Expect (";"); - return; - } - - if (QCC_PR_CheckKeyword(keyword_while, "while")) - { - continues = num_continues; - breaks = num_breaks; - - QCC_PR_Expect ("("); - patch2 = &statements[numstatements]; - conditional = 1; - e = QCC_PR_Expression (TOP_PRIORITY, 0); - conditional = 0; - if (((e->constant && !e->temp) || !STRCMP(e->name, "IMMEDIATE")) && opt_compound_jumps) - { - optres_compound_jumps++; - if (!G_INT(e->ofs)) - { - QCC_PR_ParseWarning(0, "while(0)?"); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, &patch1)); - } - else - { - patch1 = NULL; - } - } - else - { - if (e->constant && !e->temp) - { - if (!G_FLOAT(e->ofs)) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, &patch1)); - else - patch1 = NULL; - } - else if (!typecmp( e->type, type_string) && flag_ifstring) //special case, as strings are now pointers, not offsets from string table - { - QCC_PR_ParseWarning(WARN_IFSTRING_USED, "while(string) can result in bizzare behaviour"); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT_S], e, 0, &patch1)); - } - else if (!typecmp( e->type, type_float) && (flag_iffloat||QCC_OPCodeValid(&pr_opcodes[OP_IFNOT_F]))) //special case, as negative 0 is also zero - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT_F], e, 0, &patch1)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT], e, 0, &patch1)); - } - QCC_PR_Expect (")"); //after the line number is noted.. - QCC_PR_ParseStatement (); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], NULL, 0, &patch3)); - patch3->a = patch2 - patch3; - if (patch1) - { - if (patch1->op == OP_GOTO) - patch1->a = &statements[numstatements] - patch1; - else - patch1->b = &statements[numstatements] - patch1; - } - - if (breaks != num_breaks) - { - for(i = breaks; i < num_breaks; i++) - { - patch1 = &statements[pr_breaks[i]]; - statements[pr_breaks[i]].a = &statements[numstatements] - patch1; //jump to after the return-to-top goto - } - num_breaks = breaks; - } - if (continues != num_continues) - { - for(i = continues; i < num_continues; i++) - { - patch1 = &statements[pr_continues[i]]; - statements[pr_continues[i]].a = patch2 - patch1; //jump back to top - } - num_continues = continues; - } - return; - } - if (QCC_PR_CheckKeyword(keyword_for, "for")) - { - int old_numstatements; - int numtemp, i; - - int linenum[32]; - QCC_dstatement_t temp[sizeof(linenum)/sizeof(linenum[0])]; - - continues = num_continues; - breaks = num_breaks; - - QCC_PR_Expect("("); - if (!QCC_PR_CheckToken(";")) - { - QCC_FreeTemp(QCC_PR_Expression(TOP_PRIORITY, 0)); - QCC_PR_Expect(";"); - } - - patch2 = &statements[numstatements]; - if (!QCC_PR_CheckToken(";")) - { - conditional = 1; - e = QCC_PR_Expression(TOP_PRIORITY, 0); - conditional = 0; - QCC_PR_Expect(";"); - } - else - e = NULL; - - if (!QCC_PR_CheckToken(")")) - { - old_numstatements = numstatements; - QCC_FreeTemp(QCC_PR_Expression(TOP_PRIORITY, 0)); - - numtemp = numstatements - old_numstatements; - if (numtemp > sizeof(linenum)/sizeof(linenum[0])) - QCC_PR_ParseError(ERR_TOOCOMPLEX, "Update expression too large"); - numstatements = old_numstatements; - for (i = 0 ; i < numtemp ; i++) - { - linenum[i] = statement_linenums[numstatements + i]; - temp[i] = statements[numstatements + i]; - } - - QCC_PR_Expect(")"); - } - else - numtemp = 0; - - if (e) - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_IFNOT], e, 0, &patch1)); - else - patch1 = NULL; - if (!QCC_PR_CheckToken(";")) - QCC_PR_ParseStatement(); //don't give the hanging ';' warning. - patch3 = &statements[numstatements]; - for (i = 0 ; i < numtemp ; i++) - { - statement_linenums[numstatements] = linenum[i]; - statements[numstatements++] = temp[i]; - } - QCC_PR_SimpleStatement(OP_GOTO, patch2 - &statements[numstatements], 0, 0, false); - if (patch1) - patch1->b = &statements[numstatements] - patch1; - - if (breaks != num_breaks) - { - for(i = breaks; i < num_breaks; i++) - { - patch1 = &statements[pr_breaks[i]]; - statements[pr_breaks[i]].a = &statements[numstatements] - patch1; - } - num_breaks = breaks; - } - if (continues != num_continues) - { - for(i = continues; i < num_continues; i++) - { - patch1 = &statements[pr_continues[i]]; - statements[pr_continues[i]].a = patch3 - patch1; - } - num_continues = continues; - } - - return; - } - if (QCC_PR_CheckKeyword(keyword_do, "do")) - { - continues = num_continues; - breaks = num_breaks; - - patch1 = &statements[numstatements]; - QCC_PR_ParseStatement (); - QCC_PR_Expect ("while"); - QCC_PR_Expect ("("); - conditional = 1; - e = QCC_PR_Expression (TOP_PRIORITY, 0); - conditional = 0; - - if (e->constant && !e->temp) - { - if (G_FLOAT(e->ofs)) - { - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], NULL, 0, &patch2)); - patch2->a = patch1 - patch2; - } - } - else - { - if (!typecmp( e->type, type_string) && flag_ifstring) - { - QCC_PR_ParseWarning(WARN_IFSTRING_USED, "do {} while(string) can result in bizzare behaviour"); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF_S], e, NULL, &patch2)); - } - else if (!typecmp( e->type, type_float) && (flag_iffloat||QCC_OPCodeValid(&pr_opcodes[OP_IFNOT_F]))) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF_F], e, NULL, &patch2)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF], e, NULL, &patch2)); - - patch2->b = patch1 - patch2; - } - - QCC_PR_Expect (")"); - QCC_PR_Expect (";"); - - if (breaks != num_breaks) - { - for(i = breaks; i < num_breaks; i++) - { - patch2 = &statements[pr_breaks[i]]; - statements[pr_breaks[i]].a = &statements[numstatements] - patch2; - } - num_breaks = breaks; - } - if (continues != num_continues) - { - for(i = continues; i < num_continues; i++) - { - patch2 = &statements[pr_continues[i]]; - statements[pr_continues[i]].a = patch1 - patch2; - } - num_continues = continues; - } - - return; - } - - if (QCC_PR_CheckKeyword(keyword_local, "local")) - { - QCC_type_t *functionsclasstype = pr_classtype; -// if (locals_end != numpr_globals) //is this breaking because of locals? -// QCC_PR_ParseWarning("local vars after temp vars\n"); - QCC_PR_ParseDefs (NULL); - pr_classtype = functionsclasstype; - locals_end = numpr_globals; - return; - } - - if (pr_token_type == tt_name) - if ((keyword_var && !STRCMP ("var", pr_token)) || - (keyword_string && !STRCMP ("string", pr_token)) || - (keyword_float && !STRCMP ("float", pr_token)) || - (keyword_entity && !STRCMP ("entity", pr_token)) || - (keyword_vector && !STRCMP ("vector", pr_token)) || - (keyword_integer && !STRCMP ("integer", pr_token)) || - (keyword_int && !STRCMP ("int", pr_token)) || - (keyword_class && !STRCMP ("class", pr_token)) || - (keyword_const && !STRCMP ("const", pr_token))) - { -// if (locals_end != numpr_globals) //is this breaking because of locals? -// QCC_PR_ParseWarning("local vars after temp vars\n"); - QCC_PR_ParseDefs (NULL); - locals_end = numpr_globals; - return; - } - - if (QCC_PR_CheckKeyword(keyword_state, "state")) - { - QCC_PR_Expect("["); - QCC_PR_ParseState(); - QCC_PR_Expect(";"); - return; - } - if (QCC_PR_CheckToken("#")) - { - char *name; - float frame = pr_immediate._float; - QCC_PR_Lex(); - name = QCC_PR_ParseName(); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STATE], QCC_MakeFloatDef(frame), QCC_PR_GetDef(type_function, name, NULL, false, 0, false), NULL)); - QCC_PR_Expect(";"); - return; - } - - if (QCC_PR_CheckKeyword(keyword_if, "if")) - { - pbool negate = QCC_PR_CheckKeyword(keyword_not, "not"); - - QCC_PR_Expect ("("); - conditional = 1; - e = QCC_PR_Expression (TOP_PRIORITY, 0); - conditional = 0; - -// negate = negate != 0; - - if (negate) - { - if (!typecmp( e->type, type_string) && flag_ifstring) - { - QCC_PR_ParseWarning(WARN_IFSTRING_USED, "if not(string) can result in bizzare behaviour"); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF_S], e, 0, &patch1)); - } - else if (!typecmp( e->type, type_float) && (flag_iffloat||QCC_OPCodeValid(&pr_opcodes[OP_IFNOT_F]))) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF_F], e, 0, &patch1)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF], e, 0, &patch1)); - } - else - { - if (!typecmp( e->type, type_string) && flag_ifstring) - { - QCC_PR_ParseWarning(WARN_IFSTRING_USED, "if (string) can result in bizzare behaviour"); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT_S], e, 0, &patch1)); - } - else if (!typecmp( e->type, type_float) && (flag_iffloat||QCC_OPCodeValid(&pr_opcodes[OP_IFNOT_F]))) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT_F], e, 0, &patch1)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT], e, 0, &patch1)); - } - - QCC_PR_Expect (")"); //close bracket is after we save the statement to mem (so debugger does not show the if statement as being on the line after - - QCC_PR_ParseStatement (); - - if (QCC_PR_CheckKeyword (keyword_else, "else")) - { - int lastwasreturn; - lastwasreturn = statements[numstatements-1].op == OP_RETURN || statements[numstatements-1].op == OP_DONE || - statements[numstatements-1].op == OP_GOTO; - - //the last statement of the if was a return, so we don't need the goto at the end - if (lastwasreturn && opt_compound_jumps && !QCC_AStatementJumpsTo(numstatements, patch1-statements, numstatements)) - { -// QCC_PR_ParseWarning(0, "optimised the else"); - optres_compound_jumps++; - patch1->b = &statements[numstatements] - patch1; - QCC_PR_ParseStatement (); - } - else - { -// QCC_PR_ParseWarning(0, "using the else"); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, &patch2)); - patch1->b = &statements[numstatements] - patch1; - QCC_PR_ParseStatement (); - patch2->a = &statements[numstatements] - patch2; - - if (QCC_PR_StatementBlocksMatch(patch1+1, patch2-patch1, patch2+1, &statements[numstatements] - patch2)) - QCC_PR_ParseWarning(0, "Two identical blocks each side of an else"); - } - } - else - patch1->b = &statements[numstatements] - patch1; - - return; - } - if (QCC_PR_CheckKeyword(keyword_switch, "switch")) - { - int op; - int hcstyle; - int defaultcase = -1; - temp_t *et; - int oldst; - QCC_type_t *switchtype; - - breaks = num_breaks; - cases = num_cases; - - - QCC_PR_Expect ("("); - - conditional = 1; - e = QCC_PR_Expression (TOP_PRIORITY, 0); - conditional = 0; - - if (e == &def_ret) - { //copy it out, so our hack just below doesn't crash us -/* if (e->type->type == ev_vector) - e = QCC_PR_Statement(pr_opcodes+OP_STORE_V, e, QCC_GetTemp(type_vector), NULL); - else - e = QCC_PR_Statement(pr_opcodes+OP_STORE_F, e, QCC_GetTemp(type_float), NULL); - - if (e == &def_ret) //this shouldn't be happening - QCC_Error(ERR_INTERNAL, "internal error: switch: e == &def_ret"); -*/ - et = NULL; - } - else - { - et = e->temp; - e->temp = NULL; //so noone frees it until we finish this loop - } - - //expands - - //switch (CONDITION) - //{ - //case 1: - // break; - //case 2: - //default: - // break; - //} - - //to - - // x = CONDITION, goto start - // l1: - // goto end - // l2: - // def: - // goto end - // goto end P1 - // start: - // if (x == 1) goto l1; - // if (x == 2) goto l2; - // goto def - // end: - - //x is emitted in an opcode, stored as a register that we cannot access later. - //it should be possible to nest these. - - switchtype = e->type; - switch(switchtype->type) - { - case ev_float: - op = OP_SWITCH_F; - break; - case ev_entity: //whu??? - op = OP_SWITCH_E; - break; - case ev_vector: - op = OP_SWITCH_V; - break; - case ev_string: - op = OP_SWITCH_S; - break; - case ev_function: - op = OP_SWITCH_FNC; - break; - default: //err hmm. - op = 0; - break; - } - - if (op) - hcstyle = QCC_OPCodeValid(&pr_opcodes[op]); - else - hcstyle = false; - - - if (hcstyle) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[op], e, 0, &patch1)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], e, 0, &patch1)); - - QCC_PR_Expect (")"); //close bracket is after we save the statement to mem (so debugger does not show the if statement as being on the line after - - oldst = numstatements; - QCC_PR_ParseStatement (); - - //this is so that a missing goto at the end of your switch doesn't end up in the jumptable again - if (oldst == numstatements || !QCC_StatementIsAJump(numstatements-1, numstatements-1)) - { - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, &patch2)); //the P1 statement/the theyforgotthebreak statement. -// QCC_PR_ParseWarning(0, "emitted goto"); - } - else - { - patch2 = NULL; -// QCC_PR_ParseWarning(0, "No goto"); - } - - if (hcstyle) - patch1->b = &statements[numstatements] - patch1; //the goto start part - else - patch1->a = &statements[numstatements] - patch1; //the goto start part - - if (e == &def_ret) - e->type = switchtype; //set it back to the type it was actually meant to be. - - for (i = cases; i < num_cases; i++) - { - if (!pr_casesdef[i]) - { - if (defaultcase >= 0) - QCC_PR_ParseError(ERR_MULTIPLEDEFAULTS, "Duplicated default case"); - defaultcase = i; - } - else - { - if (pr_casesdef[i]->type->type != e->type->type) - { - if (e->type->type == ev_integer && pr_casesdef[i]->type->type == ev_float) - pr_casesdef[i] = QCC_MakeIntDef((int)qcc_pr_globals[pr_casesdef[i]->ofs]); - else - QCC_PR_ParseWarning(WARN_SWITCHTYPEMISMATCH, "switch case type mismatch"); - } - if (pr_casesdef2[i]) - { - if (pr_casesdef2[i]->type->type != e->type->type) - { - if (e->type->type == ev_integer && pr_casesdef[i]->type->type == ev_float) - pr_casesdef2[i] = QCC_MakeIntDef((int)qcc_pr_globals[pr_casesdef2[i]->ofs]); - else - QCC_PR_ParseWarning(WARN_SWITCHTYPEMISMATCH, "switch caserange type mismatch"); - } - - if (hcstyle) - { - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_CASERANGE], pr_casesdef[i], pr_casesdef2[i], &patch3)); - patch3->c = &statements[pr_cases[i]] - patch3; - } - else - { - QCC_def_t *e3; - - if (e->type->type == ev_float) - { - e2 = QCC_PR_Statement (&pr_opcodes[OP_GE], e, pr_casesdef[i], NULL); - e3 = QCC_PR_Statement (&pr_opcodes[OP_LE], e, pr_casesdef2[i], NULL); - e2 = QCC_PR_Statement (&pr_opcodes[OP_AND], e2, e3, NULL); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF], e2, 0, &patch3)); - patch3->b = &statements[pr_cases[i]] - patch3; - } - else if (e->type->type == ev_integer) - { - e2 = QCC_PR_Statement (&pr_opcodes[OP_GE_I], e, pr_casesdef[i], NULL); - e3 = QCC_PR_Statement (&pr_opcodes[OP_LE_I], e, pr_casesdef2[i], NULL); - e2 = QCC_PR_Statement (&pr_opcodes[OP_AND], e2, e3, NULL); - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF], e2, 0, &patch3)); - patch3->b = &statements[pr_cases[i]] - patch3; - } - else - QCC_PR_ParseWarning(WARN_SWITCHTYPEMISMATCH, "switch caserange MUST be a float or integer"); - } - } - else - { - if (hcstyle) - { - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_CASE], pr_casesdef[i], 0, &patch3)); - patch3->b = &statements[pr_cases[i]] - patch3; - } - else - { - if (!pr_casesdef[i]->constant || G_INT(pr_casesdef[i]->ofs)) - { - switch(e->type->type) - { - case ev_float: - e2 = QCC_PR_Statement (&pr_opcodes[OP_EQ_F], e, pr_casesdef[i], NULL); - break; - case ev_entity: //whu??? - e2 = QCC_PR_Statement (&pr_opcodes[OP_EQ_E], e, pr_casesdef[i], &patch1); - break; - case ev_vector: - e2 = QCC_PR_Statement (&pr_opcodes[OP_EQ_V], e, pr_casesdef[i], &patch1); - break; - case ev_string: - e2 = QCC_PR_Statement (&pr_opcodes[OP_EQ_S], e, pr_casesdef[i], &patch1); - break; - case ev_function: - e2 = QCC_PR_Statement (&pr_opcodes[OP_EQ_FNC], e, pr_casesdef[i], &patch1); - break; - case ev_field: - e2 = QCC_PR_Statement (&pr_opcodes[OP_EQ_FNC], e, pr_casesdef[i], &patch1); - break; - case ev_integer: - e2 = QCC_PR_Statement (&pr_opcodes[OP_EQ_I], e, pr_casesdef[i], &patch1); - break; - default: - QCC_PR_ParseError(ERR_BADSWITCHTYPE, "Bad switch type"); - e2 = NULL; - break; - } - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IF], e2, 0, &patch3)); - } - else - { - if (e->type->type == ev_string) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT_S], e, 0, &patch3)); - else if (e->type->type == ev_float) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT_F], e, 0, &patch3)); - else - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_IFNOT], e, 0, &patch3)); - } - patch3->b = &statements[pr_cases[i]] - patch3; - } - } - } - } - if (defaultcase>=0) - { - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, &patch3)); - patch3->a = &statements[pr_cases[defaultcase]] - patch3; - } - - num_cases = cases; - - - patch3 = &statements[numstatements]; - if (patch2) - patch2->a = patch3 - patch2; //set P1 jump - - if (breaks != num_breaks) - { - for(i = breaks; i < num_breaks; i++) - { - patch2 = &statements[pr_breaks[i]]; - patch2->a = patch3 - patch2; - } - num_breaks = breaks; - } - - if (et) - { - e->temp = et; - QCC_FreeTemp(e); - } - return; - } - - if (QCC_PR_CheckKeyword(keyword_asm, "asm")) - { - if (QCC_PR_CheckToken("{")) - { - while (!QCC_PR_CheckToken("}")) - QCC_PR_ParseAsm (); - } - else - QCC_PR_ParseAsm (); - return; - } - - if (QCC_PR_CheckToken(":")) - { - if (pr_token_type != tt_name) - { - QCC_PR_ParseError(ERR_BADLABELNAME, "invalid label name \"%s\"", pr_token); - return; - } - - for (i = 0; i < num_labels; i++) - if (!STRNCMP(pr_labels[i].name, pr_token, sizeof(pr_labels[num_labels].name) -1)) - { - QCC_PR_ParseWarning(WARN_DUPLICATELABEL, "Duplicate label %s", pr_token); - QCC_PR_Lex(); - return; - } - - if (num_labels >= max_labels) - { - max_labels += 8; - pr_labels = realloc(pr_labels, sizeof(*pr_labels)*max_labels); - } - - strncpy(pr_labels[num_labels].name, pr_token, sizeof(pr_labels[num_labels].name) -1); - pr_labels[num_labels].lineno = pr_source_line; - pr_labels[num_labels].statementno = numstatements; - - num_labels++; - -// QCC_PR_ParseWarning("Gotos are evil"); - QCC_PR_Lex(); - return; - } - if (QCC_PR_CheckKeyword(keyword_goto, "goto")) - { - if (pr_token_type != tt_name) - { - QCC_PR_ParseError(ERR_NOLABEL, "invalid label name \"%s\"", pr_token); - return; - } - - QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, &patch2); - - QCC_PR_GotoStatement (patch2, pr_token); - -// QCC_PR_ParseWarning("Gotos are evil"); - QCC_PR_Lex(); - QCC_PR_Expect(";"); - return; - } - - if (QCC_PR_CheckKeyword(keyword_break, "break")) - { - if (!STRCMP ("(", pr_token)) - { //make sure it wasn't a call to the break function. - QCC_PR_IncludeChunk("break(", true, NULL); - QCC_PR_Lex(); //so it sees the break. - } - else - { - if (num_breaks >= max_breaks) - { - max_breaks += 8; - pr_breaks = realloc(pr_breaks, sizeof(*pr_breaks)*max_breaks); - } - pr_breaks[num_breaks] = numstatements; - QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, NULL); - num_breaks++; - QCC_PR_Expect(";"); - return; - } - } - if (QCC_PR_CheckKeyword(keyword_continue, "continue")) - { - if (num_continues >= max_continues) - { - max_continues += 8; - pr_continues = realloc(pr_continues, sizeof(*pr_continues)*max_continues); - } - pr_continues[num_continues] = numstatements; - QCC_PR_Statement (&pr_opcodes[OP_GOTO], 0, 0, NULL); - num_continues++; - QCC_PR_Expect(";"); - return; - } - if (QCC_PR_CheckKeyword(keyword_case, "case")) - { - if (num_cases >= max_cases) - { - max_cases += 8; - pr_cases = realloc(pr_cases, sizeof(*pr_cases)*max_cases); - pr_casesdef = realloc(pr_casesdef, sizeof(*pr_casesdef)*max_cases); - pr_casesdef2 = realloc(pr_casesdef2, sizeof(*pr_casesdef2)*max_cases); - } - pr_cases[num_cases] = numstatements; - pr_casesdef[num_cases] = QCC_PR_Expression (TOP_PRIORITY, EXPR_DISALLOW_COMMA); - if (QCC_PR_CheckToken("..")) - { - pr_casesdef2[num_cases] = QCC_PR_Expression (TOP_PRIORITY, EXPR_DISALLOW_COMMA); - if (pr_casesdef[num_cases]->constant && pr_casesdef2[num_cases]->constant && - !pr_casesdef[num_cases]->temp && !pr_casesdef2[num_cases]->temp) - if (G_FLOAT(pr_casesdef[num_cases]->ofs) >= G_FLOAT(pr_casesdef2[num_cases]->ofs)) - QCC_PR_ParseError(ERR_CASENOTIMMEDIATE, "Caserange statement uses backwards range\n"); - } - else - pr_casesdef2[num_cases] = NULL; - - if (numstatements != pr_cases[num_cases]) - QCC_PR_ParseError(ERR_CASENOTIMMEDIATE, "Case statements may not use formulas\n"); - num_cases++; - QCC_PR_Expect(":"); - return; - } - if (QCC_PR_CheckKeyword(keyword_default, "default")) - { - if (num_cases >= max_cases) - { - max_cases += 8; - pr_cases = realloc(pr_cases, sizeof(*pr_cases)*max_cases); - pr_casesdef = realloc(pr_casesdef, sizeof(*pr_casesdef)*max_cases); - pr_casesdef2 = realloc(pr_casesdef2, sizeof(*pr_casesdef2)*max_cases); - } - pr_cases[num_cases] = numstatements; - pr_casesdef[num_cases] = NULL; - pr_casesdef2[num_cases] = NULL; - num_cases++; - QCC_PR_Expect(":"); - return; - } - - if (QCC_PR_CheckKeyword(keyword_thinktime, "thinktime")) - { - QCC_def_t *nextthink; - QCC_def_t *time; - e = QCC_PR_Expression (TOP_PRIORITY, 0); - QCC_PR_Expect(":"); - e2 = QCC_PR_Expression (TOP_PRIORITY, 0); - if (e->type->type != ev_entity || e2->type->type != ev_float) - QCC_PR_ParseError(ERR_THINKTIMETYPEMISMATCH, "thinktime type mismatch"); - - if (QCC_OPCodeValid(&pr_opcodes[OP_THINKTIME])) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_THINKTIME], e, e2, NULL)); - else - { - nextthink = QCC_PR_GetDef(NULL, "nextthink", NULL, false, 0, false); - if (!nextthink) - QCC_PR_ParseError (ERR_UNKNOWNVALUE, "Unknown value \"%s\"", "nextthink"); - time = QCC_PR_GetDef(type_float, "time", NULL, false, 0, false); - if (!time) - QCC_PR_ParseError (ERR_UNKNOWNVALUE, "Unknown value \"%s\"", "time"); - nextthink = QCC_PR_Statement(&pr_opcodes[OP_ADDRESS], e, nextthink, NULL); - time = QCC_PR_Statement(&pr_opcodes[OP_ADD_F], time, e2, NULL); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STOREP_F], time, nextthink, NULL)); - } - QCC_PR_Expect(";"); - return; - } - if (QCC_PR_CheckToken(";")) - { - int osl = pr_source_line; - pr_source_line = statementstart; - if (!expandedemptymacro) - QCC_PR_ParseWarning(WARN_POINTLESSSTATEMENT, "Hanging ';'"); - pr_source_line = osl; - return; - } - -// qcc_functioncalled=0; - - qcc_usefulstatement = false; - e = QCC_PR_Expression (TOP_PRIORITY, 0); - expandedemptymacro = false; - QCC_PR_Expect (";"); - - if (e->type->type != ev_void && !qcc_usefulstatement) - { - int osl = pr_source_line; - pr_source_line = statementstart; - QCC_PR_ParseWarning(WARN_POINTLESSSTATEMENT, "Effectless statement"); - pr_source_line = osl; - } - - QCC_FreeTemp(e); - -// qcc_functioncalled=false; -} - - -/* -============== -PR_ParseState - -States are special functions made for convenience. They automatically -set frame, nextthink (implicitly), and think (allowing forward definitions). - -// void() name = [framenum, nextthink] {code} -// expands to: -// function void name () -// { -// self.frame=framenum; -// self.nextthink = time + 0.1; -// self.think = nextthink -// -// }; -============== -*/ -void QCC_PR_ParseState (void) -{ - char *name; - QCC_def_t *s1, *def, *sc = pr_scope; - char f; - - f = *pr_token; - if (QCC_PR_CheckToken("++") || QCC_PR_CheckToken("--")) - { - s1 = QCC_PR_ParseImmediate (); - QCC_PR_Expect(".."); - def = QCC_PR_ParseImmediate (); - QCC_PR_Expect ("]"); - - if (s1->type->type != ev_float || def->type->type != ev_float) - QCC_PR_ParseError(ERR_STATETYPEMISMATCH, "state type mismatch"); - - - if (QCC_OPCodeValid(&pr_opcodes[OP_CSTATE])) - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_CSTATE], s1, def, NULL)); - else - { - QCC_def_t *t1, *t2; - QCC_def_t *framef, *frame; - QCC_def_t *self; - QCC_def_t *cycle_wrapped; - temp_t *ftemp; - - self = QCC_PR_GetDef(type_entity, "self", NULL, false, 0, false); - framef = QCC_PR_GetDef(NULL, "frame", NULL, false, 0, false); - cycle_wrapped = QCC_PR_GetDef(type_float, "cycle_wrapped", NULL, false, 0, false); - - frame = QCC_PR_Statement(&pr_opcodes[OP_LOAD_F], self, framef, NULL); - if (cycle_wrapped) - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], QCC_MakeFloatDef(0), cycle_wrapped, NULL)); - QCC_UnFreeTemp(frame); - - //make sure the frame is within the bounds given. - ftemp = frame->temp; - frame->temp = NULL; - t1 = QCC_PR_Statement(&pr_opcodes[OP_LT], frame, s1, NULL); - t2 = QCC_PR_Statement(&pr_opcodes[OP_GT], frame, def, NULL); - t1 = QCC_PR_Statement(&pr_opcodes[OP_OR], t1, t2, NULL); - QCC_PR_SimpleStatement(OP_IFNOT, t1->ofs, 2, 0, false); - QCC_FreeTemp(t1); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], s1, frame, NULL)); - QCC_PR_SimpleStatement(OP_GOTO, t1->ofs, 13, 0, false); - - t1 = QCC_PR_Statement(&pr_opcodes[OP_GE], def, s1, NULL); - QCC_PR_SimpleStatement(OP_IFNOT, t1->ofs, 7, 0, false); - QCC_FreeTemp(t1); //this block is the 'it's in a forwards direction' - QCC_PR_SimpleStatement(OP_ADD_F, frame->ofs, QCC_MakeFloatDef(1)->ofs, frame->ofs, false); - t1 = QCC_PR_Statement(&pr_opcodes[OP_GT], frame, def, NULL); - QCC_PR_SimpleStatement(OP_IFNOT, t1->ofs,2, 0, false); - QCC_FreeTemp(t1); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], s1, frame, NULL)); - QCC_UnFreeTemp(frame); - if (cycle_wrapped) - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], QCC_MakeFloatDef(1), cycle_wrapped, NULL)); - - QCC_PR_SimpleStatement(OP_GOTO, 6, 0, 0, false); - //reverse animation. - QCC_PR_SimpleStatement(OP_SUB_F, frame->ofs, QCC_MakeFloatDef(1)->ofs, frame->ofs, false); - t1 = QCC_PR_Statement(&pr_opcodes[OP_LT], frame, s1, NULL); - QCC_PR_SimpleStatement(OP_IFNOT, t1->ofs,2, 0, false); - QCC_FreeTemp(t1); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], def, frame, NULL)); - QCC_UnFreeTemp(frame); - if (cycle_wrapped) - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], QCC_MakeFloatDef(1), cycle_wrapped, NULL)); - - //self.frame = frame happens with the normal state opcode. - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STATE], frame, pr_scope, NULL)); - - frame->temp = ftemp; - QCC_FreeTemp(frame); - } - return; - } - - if (pr_token_type != tt_immediate || pr_immediate_type != type_float) - QCC_PR_ParseError (ERR_STATETYPEMISMATCH, "state frame must be a number"); - s1 = QCC_PR_ParseImmediate (); - - QCC_PR_CheckToken (","); - - name = QCC_PR_ParseName (); - pr_scope = NULL; - def = QCC_PR_GetDef (type_function, name, NULL, true, 1, false); - pr_scope = sc; - - QCC_PR_Expect ("]"); - - QCC_FreeTemp(QCC_PR_Statement (&pr_opcodes[OP_STATE], s1, def, NULL)); -} - -void QCC_PR_ParseAsm(void) -{ - QCC_dstatement_t *patch1; - int op, p; - QCC_def_t *a, *b, *c; - - if (QCC_PR_CheckKeyword(keyword_local, "local")) - { - QCC_PR_ParseDefs (NULL); - locals_end = numpr_globals; - return; - } - - for (op = 0; op < OP_NUMOPS; op++) - { - if (!STRCMP(pr_token, pr_opcodes[op].opname)) - { - QCC_PR_Lex(); - if (pr_opcodes[op].priority==-1 && pr_opcodes[op].associative!=ASSOC_LEFT) - { - if (pr_opcodes[op].type_a==NULL) - { - patch1 = &statements[numstatements]; - - QCC_PR_Statement3(&pr_opcodes[op], NULL, NULL, NULL, true); - - if (pr_token_type == tt_name) - { - QCC_PR_GotoStatement(patch1, QCC_PR_ParseName()); - } - else - { - p = (int)pr_immediate._float; - patch1->a = (int)p; - } - - QCC_PR_Lex(); - } - else if (pr_opcodes[op].type_b==NULL) - { - patch1 = &statements[numstatements]; - - a = QCC_PR_ParseValue(pr_classtype, false); - QCC_PR_Statement3(&pr_opcodes[op], a, NULL, NULL, true); - - if (pr_token_type == tt_name) - { - QCC_PR_GotoStatement(patch1, QCC_PR_ParseName()); - } - else - { - p = (int)pr_immediate._float; - patch1->b = (int)p; - } - - QCC_PR_Lex(); - } - else - { - patch1 = &statements[numstatements]; - - a = QCC_PR_ParseValue(pr_classtype, false); - b = QCC_PR_ParseValue(pr_classtype, false); - QCC_PR_Statement3(&pr_opcodes[op], a, b, NULL, true); - - if (pr_token_type == tt_name) - { - QCC_PR_GotoStatement(patch1, QCC_PR_ParseName()); - } - else - { - p = (int)pr_immediate._float; - patch1->c = (int)p; - } - - QCC_PR_Lex(); - } - } - else - { - if (pr_opcodes[op].type_a != &type_void) - a = QCC_PR_ParseValue(pr_classtype, false); - else - a=NULL; - if (pr_opcodes[op].type_b != &type_void) - b = QCC_PR_ParseValue(pr_classtype, false); - else - b=NULL; - if (pr_opcodes[op].associative==ASSOC_LEFT && pr_opcodes[op].type_c != &type_void) - c = QCC_PR_ParseValue(pr_classtype, false); - else - c=NULL; - - QCC_PR_Statement3(&pr_opcodes[op], a, b, c, true); - } - - QCC_PR_Expect(";"); - return; - } - } - QCC_PR_ParseError(ERR_BADOPCODE, "Bad op code name %s", pr_token); -} - -pbool QCC_FuncJumpsTo(int first, int last, int statement) -{ - int st; - for (st = first; st < last; st++) - { - if (pr_opcodes[statements[st].op].type_a == NULL) - { - if (st + (signed)statements[st].a == statement) - { - if (st != first) - { - if (statements[st-1].op == OP_RETURN) - continue; - if (statements[st-1].op == OP_DONE) - continue; - return true; - } - } - } - if (pr_opcodes[statements[st].op].type_b == NULL) - { - if (st + (signed)statements[st].b == statement) - { - if (st != first) - { - if (statements[st-1].op == OP_RETURN) - continue; - if (statements[st-1].op == OP_DONE) - continue; - return true; - } - } - } - if (pr_opcodes[statements[st].op].type_c == NULL) - { - if (st + (signed)statements[st].c == statement) - { - if (st != first) - { - if (statements[st-1].op == OP_RETURN) - continue; - if (statements[st-1].op == OP_DONE) - continue; - return true; - } - } - } - } - return false; -} - -pbool QCC_FuncJumpsToRange(int first, int last, int firstr, int lastr) -{ - int st; - for (st = first; st < last; st++) - { - if (pr_opcodes[statements[st].op].type_a == NULL) - { - if (st + (signed)statements[st].a >= firstr && st + (signed)statements[st].a <= lastr) - { - if (st != first) - { - if (statements[st-1].op == OP_RETURN) - continue; - if (statements[st-1].op == OP_DONE) - continue; - return true; - } - } - } - if (pr_opcodes[statements[st].op].type_b == NULL) - { - if (st + (signed)statements[st].b >= firstr && st + (signed)statements[st].b <= lastr) - { - if (st != first) - { - if (statements[st-1].op == OP_RETURN) - continue; - if (statements[st-1].op == OP_DONE) - continue; - return true; - } - } - } - if (pr_opcodes[statements[st].op].type_c == NULL) - { - if (st + (signed)statements[st].c >= firstr && st + (signed)statements[st].c <= lastr) - { - if (st != first) - { - if (statements[st-1].op == OP_RETURN) - continue; - if (statements[st-1].op == OP_DONE) - continue; - return true; - } - } - } - } - return false; -} - -#if 0 -void QCC_CompoundJumps(int first, int last) -{ - //jumps to jumps are reordered so they become jumps to the final target. - int statement; - int st; - for (st = first; st < last; st++) - { - if (pr_opcodes[statements[st].op].type_a == NULL) - { - statement = st + (signed)statements[st].a; - if (statements[statement].op == OP_RETURN || statements[statement].op == OP_DONE) - { //goto leads to return. Copy the command out to remove the goto. - statements[st].op = statements[statement].op; - statements[st].a = statements[statement].a; - statements[st].b = statements[statement].b; - statements[st].c = statements[statement].c; - optres_compound_jumps++; - } - while (statements[statement].op == OP_GOTO) - { - statements[st].a = statement+statements[statement].a - st; - statement = st + (signed)statements[st].a; - optres_compound_jumps++; - } - } - if (pr_opcodes[statements[st].op].type_b == NULL) - { - statement = st + (signed)statements[st].b; - while (statements[statement].op == OP_GOTO) - { - statements[st].b = statement+statements[statement].a - st; - statement = st + (signed)statements[st].b; - optres_compound_jumps++; - } - } - if (pr_opcodes[statements[st].op].type_c == NULL) - { - statement = st + (signed)statements[st].c; - while (statements[statement].op == OP_GOTO) - { - statements[st].c = statement+statements[statement].a - st; - statement = st + (signed)statements[st].c; - optres_compound_jumps++; - } - } - } -} -#else -void QCC_CompoundJumps(int first, int last) -{ - //jumps to jumps are reordered so they become jumps to the final target. - int statement; - int st; - int infloop; - for (st = first; st < last; st++) - { - if (pr_opcodes[statements[st].op].type_a == NULL) - { - statement = st + (signed)statements[st].a; - if (statements[statement].op == OP_RETURN || statements[statement].op == OP_DONE) - { //goto leads to return. Copy the command out to remove the goto. - statements[st].op = statements[statement].op; - statements[st].a = statements[statement].a; - statements[st].b = statements[statement].b; - statements[st].c = statements[statement].c; - optres_compound_jumps++; - } - infloop = 1000; - while (statements[statement].op == OP_GOTO) - { - if (!infloop--) - { - QCC_PR_ParseWarning(0, "Infinate loop detected"); - break; - } - statements[st].a = (statement+statements[statement].a - st); - statement = st + (signed)statements[st].a; - optres_compound_jumps++; - } - } - if (pr_opcodes[statements[st].op].type_b == NULL) - { - statement = st + (signed)statements[st].b; - infloop = 1000; - while (statements[statement].op == OP_GOTO) - { - if (!infloop--) - { - QCC_PR_ParseWarning(0, "Infinate loop detected"); - break; - } - statements[st].b = (statement+statements[statement].a - st); - statement = st + (signed)statements[st].b; - optres_compound_jumps++; - } - } - if (pr_opcodes[statements[st].op].type_c == NULL) - { - statement = st + (signed)statements[st].c; - infloop = 1000; - while (statements[statement].op == OP_GOTO) - { - if (!infloop--) - { - QCC_PR_ParseWarning(0, "Infinate loop detected"); - break; - } - statements[st].c = (statement+statements[statement].a - st); - statement = st + (signed)statements[st].c; - optres_compound_jumps++; - } - } - } -} -#endif - -void QCC_CheckForDeadAndMissingReturns(int first, int last, int rettype) -{ - int st, st2; - - if (statements[last-1].op == OP_DONE) - last--; //don't want the done - - if (rettype != ev_void) - if (statements[last-1].op != OP_RETURN) - { - if (statements[last-1].op != OP_GOTO || (signed)statements[last-1].a > 0) - { - QCC_PR_ParseWarning(WARN_MISSINGRETURN, "%s: not all control paths return a value", pr_scope->name ); - return; - } - } - - for (st = first; st < last; st++) - { - if (statements[st].op == OP_RETURN || statements[st].op == OP_GOTO) - { - st++; - if (st == last) - continue; //erm... end of function doesn't count as unreachable. - - if (!opt_compound_jumps) - { //we can ignore single statements like these without compound jumps (compound jumps correctly removes all). - if (statements[st].op == OP_GOTO) //inefficient compiler, we can ignore this. - continue; - if (statements[st].op == OP_DONE) //inefficient compiler, we can ignore this. - continue; - if (statements[st].op == OP_RETURN) //inefficient compiler, we can ignore this. - continue; - } - - //make sure something goes to just after this return. - for (st2 = first; st2 < last; st2++) - { - if (pr_opcodes[statements[st2].op].type_a == NULL) - { - if (st2 + (signed)statements[st2].a == st) - break; - } - if (pr_opcodes[statements[st2].op].type_b == NULL) - { - if (st2 + (signed)statements[st2].b == st) - break; - } - if (pr_opcodes[statements[st2].op].type_c == NULL) - { - if (st2 + (signed)statements[st2].c == st) - break; - } - } - if (st2 == last) - { - QCC_PR_ParseWarning(WARN_UNREACHABLECODE, "%s: contains unreachable code", pr_scope->name ); - } - continue; - } - if (rettype != ev_void) - { - if (pr_opcodes[statements[st].op].type_a == NULL) - { - if (st + (signed)statements[st].a == last) - { - QCC_PR_ParseWarning(WARN_MISSINGRETURN, "%s: not all control paths return a value", pr_scope->name ); - return; - } - } - if (pr_opcodes[statements[st].op].type_b == NULL) - { - if (st + (signed)statements[st].b == last) - { - QCC_PR_ParseWarning(WARN_MISSINGRETURN, "%s: not all control paths return a value", pr_scope->name ); - return; - } - } - if (pr_opcodes[statements[st].op].type_c == NULL) - { - if (st + (signed)statements[st].c == last) - { - QCC_PR_ParseWarning(WARN_MISSINGRETURN, "%s: not all control paths return a value", pr_scope->name ); - return; - } - } - } - } -} - -pbool QCC_StatementIsAJump(int stnum, int notifdest) //only the unconditionals. -{ - if (statements[stnum].op == OP_RETURN) - return true; - if (statements[stnum].op == OP_DONE) - return true; - if (statements[stnum].op == OP_GOTO) - if ((int)statements[stnum].a != notifdest) - return true; - return false; -} - -int QCC_AStatementJumpsTo(int targ, int first, int last) -{ - int st; - for (st = first; st < last; st++) - { - if (pr_opcodes[statements[st].op].type_a == NULL) - { - if (st + (signed)statements[st].a == targ && statements[st].a) - { - return true; - } - } - if (pr_opcodes[statements[st].op].type_b == NULL) - { - if (st + (signed)statements[st].b == targ) - { - return true; - } - } - if (pr_opcodes[statements[st].op].type_c == NULL) - { - if (st + (signed)statements[st].c == targ) - { - return true; - } - } - } - - for (st = 0; st < num_labels; st++) //assume it's used. - { - if (pr_labels[st].statementno == targ) - return true; - } - - - return false; -} -/* -//goes through statements, if it sees a matching statement earlier, it'll strim out the current. -void QCC_CommonSubExpressionRemoval(int first, int last) -{ - int cur; //the current - int prev; //the earlier statement - for (cur = last-1; cur >= first; cur--) - { - if (pr_opcodes[statements[cur].op].priority == -1) - continue; - for (prev = cur-1; prev >= first; prev--) - { - if (statements[prev].op >= OP_CALL0 && statements[prev].op <= OP_CALL8) - { - optres_test1++; - break; - } - if (statements[prev].op >= OP_CALL1H && statements[prev].op <= OP_CALL8H) - { - optres_test1++; - break; - } - if (pr_opcodes[statements[prev].op].right_associative) - { //make sure no changes to var_a occur. - if (statements[prev].b == statements[cur].a) - { - optres_test2++; - break; - } - if (statements[prev].b == statements[cur].b && !pr_opcodes[statements[cur].op].right_associative) - { - optres_test2++; - break; - } - } - else - { - if (statements[prev].c == statements[cur].a) - { - optres_test2++; - break; - } - if (statements[prev].c == statements[cur].b && !pr_opcodes[statements[cur].op].right_associative) - { - optres_test2++; - break; - } - } - - if (statements[prev].op == statements[cur].op) - if (statements[prev].a == statements[cur].a) - if (statements[prev].b == statements[cur].b) - if (statements[prev].c == statements[cur].c) - { - if (!QCC_FuncJumpsToRange(first, last, prev, cur)) - { - statements[cur].op = OP_STORE_F; - statements[cur].a = 28; - statements[cur].b = 28; - optres_comexprremoval++; - } - else - optres_test1++; - break; - } - } - } -} -*/ - -void QCC_RemapOffsets(unsigned int firststatement, unsigned int laststatement, unsigned int min, unsigned int max, unsigned int newmin) -{ - QCC_dstatement_t *st; - unsigned int i; - - for (i = firststatement, st = &statements[i]; i < laststatement; i++, st++) - { - if (pr_opcodes[st->op].type_a && st->a >= min && st->a < max) - st->a = st->a - min + newmin; - if (pr_opcodes[st->op].type_b && st->b >= min && st->b < max) - st->b = st->b - min + newmin; - if (pr_opcodes[st->op].type_c && st->c >= min && st->c < max) - st->c = st->c - min + newmin; - } -} - -void QCC_Marshal_Locals(int first, int laststatement) -{ - QCC_def_t *local; - unsigned int newofs; - -// if (!opt_overlaptemps) //clear these after each function. we arn't overlapping them so why do we need to keep track of them? -// { -// temp_t *t; -// for (t = functemps; t; t = t->next) -// QCC_FreeOffset(t->ofs, t->size); -// functemps = NULL; -// } - - if (!pr.localvars) //nothing to marshal - { - locals_start = numpr_globals; - locals_end = numpr_globals; - return; - } - - if (!opt_locals_marshalling) - { - pr.localvars = NULL; - return; - } - - //initial backwards bounds. - locals_start = MAX_REGS; - locals_end = 0; - - newofs = MAX_REGS; //this is a handy place to put it. :) - - //the params need to be in the order that they were allocated - //so we allocate in a backwards order. - for (local = pr.localvars; local; local = local->nextlocal) - { - if (local->constant) - continue; - - newofs += local->type->size*local->arraysize; - if (local->arraysize>1) - newofs++; - } - - locals_start = MAX_REGS; - locals_end = newofs; - - - optres_locals_marshalling+=newofs-MAX_REGS; - - for (local = pr.localvars; local; local = local->nextlocal) - { - if (local->constant) - continue; - - if (((int*)qcc_pr_globals)[local->ofs]) - QCC_PR_ParseError(ERR_INTERNAL, "Marshall of a set value"); - - newofs -= local->type->size*local->arraysize; - if (local->arraysize>1) - newofs--; - - QCC_RemapOffsets(first, laststatement, local->ofs, local->ofs+local->type->size*local->arraysize, newofs); - QCC_FreeOffset(local->ofs, local->type->size*local->arraysize); - - local->ofs = newofs; - } - - - pr.localvars = NULL; -} - -#ifdef WRITEASM -void QCC_WriteAsmFunction(QCC_def_t *sc, unsigned int firststatement, gofs_t firstparm) -{ - unsigned int i; - unsigned int p; - gofs_t o; - QCC_type_t *type; - QCC_def_t *param; - - if (!asmfile) - return; - - type = sc->type; - fprintf(asmfile, "%s(", TypeName(type->aux_type)); - p = type->num_parms; - for (o = firstparm, i = 0, type = type->param; i < p; i++, type = type->next) - { - if (i) - fprintf(asmfile, ", "); - - for (param = pr.localvars; param; param = param->nextlocal) - { - if (param->ofs == o) - break; - } - if (param) - fprintf(asmfile, "%s %s", TypeName(type), param->name); - else - fprintf(asmfile, "%s", TypeName(type)); - - o += type->size; - } - - fprintf(asmfile, ") %s = asm\n{\n", sc->name); - - QCC_fprintfLocals(asmfile, firstparm, o); - - for (i = firststatement; i < (unsigned int)numstatements; i++) - { - fprintf(asmfile, "\t%s", pr_opcodes[statements[i].op].opname); - if (pr_opcodes[statements[i].op].type_a != &type_void) - { - if (strlen(pr_opcodes[statements[i].op].opname)<6) - fprintf(asmfile, "\t"); - if (pr_opcodes[statements[i].op].type_a) - fprintf(asmfile, "\t%s", QCC_VarAtOffset(statements[i].a, (*pr_opcodes[statements[i].op].type_a)->size)); - else - fprintf(asmfile, "\t%i", statements[i].a); - if (pr_opcodes[statements[i].op].type_b != &type_void) - { - if (pr_opcodes[statements[i].op].type_b) - fprintf(asmfile, ",\t%s", QCC_VarAtOffset(statements[i].b, (*pr_opcodes[statements[i].op].type_b)->size)); - else - fprintf(asmfile, ",\t%i", statements[i].b); - if (pr_opcodes[statements[i].op].type_c != &type_void && pr_opcodes[statements[i].op].associative==ASSOC_LEFT) - { - if (pr_opcodes[statements[i].op].type_c) - fprintf(asmfile, ",\t%s", QCC_VarAtOffset(statements[i].c, (*pr_opcodes[statements[i].op].type_c)->size)); - else - fprintf(asmfile, ",\t%i", statements[i].c); - } - } - else - { - if (pr_opcodes[statements[i].op].type_c != &type_void) - { - if (pr_opcodes[statements[i].op].type_c) - fprintf(asmfile, ",\t%s", QCC_VarAtOffset(statements[i].c, (*pr_opcodes[statements[i].op].type_c)->size)); - else - fprintf(asmfile, ",\t%i", statements[i].c); - } - } - } - fprintf(asmfile, ";\n"); - } - - fprintf(asmfile, "}\n\n"); -} -#endif - -/* -============ -PR_ParseImmediateStatements - -Parse a function body -============ -*/ -QCC_function_t *QCC_PR_ParseImmediateStatements (QCC_type_t *type) -{ - int i; - QCC_function_t *f; - QCC_def_t *defs[MAX_PARMS+MAX_EXTRA_PARMS], *e2; - - QCC_type_t *parm; - pbool needsdone=false; - freeoffset_t *oldfofs; - - conditional = 0; - - expandedemptymacro = false; - - - f = (void *)qccHunkAlloc (sizeof(QCC_function_t)); - -// -// check for builtin function definition #1, #2, etc -// -// hexenC has void name() : 2; - if (QCC_PR_CheckToken ("#") || QCC_PR_CheckToken (":")) - { - int binum = 0; - if (pr_token_type == tt_immediate - && pr_immediate_type == type_float - && pr_immediate._float == (int)pr_immediate._float) - binum = (int)pr_immediate._float; - else if (pr_token_type == tt_immediate && pr_immediate_type == type_integer) - binum = pr_immediate._int; - else - QCC_PR_ParseError (ERR_BADBUILTINIMMEDIATE, "Bad builtin immediate"); - f->builtin = binum; - QCC_PR_Lex (); - - locals_start = locals_end = OFS_PARM0; //hmm... - return f; - } - if (QCC_PR_CheckKeyword(keyword_external, "external")) - { //reacc style builtin - if (pr_token_type != tt_immediate - || pr_immediate_type != type_float - || pr_immediate._float != (int)pr_immediate._float) - QCC_PR_ParseError (ERR_BADBUILTINIMMEDIATE, "Bad builtin immediate"); - f->builtin = (int)-pr_immediate._float; - QCC_PR_Lex (); - QCC_PR_Expect(";"); - - locals_start = locals_end = OFS_PARM0; //hmm... - return f; - } - - if (type->num_parms < 0) - QCC_PR_ParseError (ERR_FUNCTIONWITHVARGS, "QC function with variable arguments and function body"); - - f->builtin = 0; -// -// define the parms -// - - locals_start = locals_end = numpr_globals; - - oldfofs = freeofs; - freeofs = NULL; - - parm = type->param; - for (i=0 ; inum_parms ; i++) - { - if (!*pr_parm_names[i]) - QCC_PR_ParseError(ERR_PARAMWITHNONAME, "Parameter is not named"); - defs[i] = QCC_PR_GetDef (parm, pr_parm_names[i], pr_scope, true, 1, false); - - defs[i]->references++; - if (i < MAX_PARMS) - { - f->parm_ofs[i] = defs[i]->ofs; - if (i > 0 && f->parm_ofs[i] < f->parm_ofs[i-1]) - QCC_Error (ERR_BADPARAMORDER, "bad parm order"); - if (i > 0 && f->parm_ofs[i] != f->parm_ofs[i-1]+defs[i-1]->type->size) - QCC_Error (ERR_BADPARAMORDER, "parms not packed"); - } - parm = parm->next; - } - - if (type->num_parms) - locals_start = locals_end = defs[0]->ofs; - - freeofs = oldfofs; - - f->code = numstatements; - - if (type->num_parms > MAX_PARMS) - { - for (i = MAX_PARMS; i < type->num_parms; i++) - { - if (!extra_parms[i - MAX_PARMS]) - { - e2 = (QCC_def_t *) qccHunkAlloc (sizeof(QCC_def_t)); - e2->name = "extra parm"; - e2->ofs = QCC_GetFreeOffsetSpace(3); - extra_parms[i - MAX_PARMS] = e2; - } - extra_parms[i - MAX_PARMS]->type = defs[i]->type; - if (defs[i]->type->type != ev_vector) - QCC_PR_Statement (&pr_opcodes[OP_STORE_F], extra_parms[i - MAX_PARMS], defs[i], NULL); - else - QCC_PR_Statement (&pr_opcodes[OP_STORE_V], extra_parms[i - MAX_PARMS], defs[i], NULL); - } - } - - QCC_RemapLockedTemps(-1, -1); - - /*if (pr_classtype) - { - QCC_def_t *e, *e2; - e = QCC_PR_GetDef(pr_classtype, "__oself", pr_scope, true, 1); - e2 = QCC_PR_GetDef(type_entity, "self", NULL, true, 1); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_ENT], QCC_PR_DummyDef(pr_classtype, "self", pr_scope, 1, e2->ofs, false), e, NULL)); - }*/ - -// -// check for a state opcode -// - if (QCC_PR_CheckToken ("[")) - QCC_PR_ParseState (); - - if (QCC_PR_CheckKeyword (keyword_asm, "asm")) - { - QCC_PR_Expect ("{"); - while (!QCC_PR_CheckToken("}")) - QCC_PR_ParseAsm (); - } - else - { - if (QCC_PR_CheckKeyword (keyword_var, "var")) //reacc support - { //parse lots of locals - char *name; - do { - name = QCC_PR_ParseName(); - QCC_PR_Expect(":"); - e2 = QCC_PR_GetDef(QCC_PR_ParseType(false), name, pr_scope, true, 1, false); - QCC_PR_Expect(";"); - } while(!QCC_PR_CheckToken("{")); - } - else - QCC_PR_Expect ("{"); -// -// parse regular statements -// - while (!QCC_PR_CheckToken("}")) - { - QCC_PR_ParseStatement (); - QCC_FreeTemps(); - } - } - QCC_FreeTemps(); - - // this is cheap -// if (type->aux_type->type) -// if (statements[numstatements - 1].op != OP_RETURN) -// QCC_PR_ParseWarning(WARN_MISSINGRETURN, "%s: not all control paths return a value", pr_scope->name ); - - if (f->code == numstatements) - needsdone = true; - else if (statements[numstatements - 1].op != OP_RETURN && statements[numstatements - 1].op != OP_DONE) - needsdone = true; - - if (num_gotos) - { - int j; - for (i = 0; i < num_gotos; i++) - { - for (j = 0; j < num_labels; j++) - { - if (!strcmp(pr_gotos[i].name, pr_labels[j].name)) - { - if (!pr_opcodes[statements[pr_gotos[i].statementno].op].type_a) - statements[pr_gotos[i].statementno].a += pr_labels[j].statementno - pr_gotos[i].statementno; - else if (!pr_opcodes[statements[pr_gotos[i].statementno].op].type_b) - statements[pr_gotos[i].statementno].b += pr_labels[j].statementno - pr_gotos[i].statementno; - else - statements[pr_gotos[i].statementno].c += pr_labels[j].statementno - pr_gotos[i].statementno; - break; - } - } - if (j == num_labels) - { - num_gotos = 0; - QCC_PR_ParseError(ERR_NOLABEL, "Goto statement with no matching label \"%s\"", pr_gotos[i].name); - } - } - num_gotos = 0; - } - - if (opt_return_only && !needsdone) - needsdone = QCC_FuncJumpsTo(f->code, numstatements, numstatements); - - // emit an end of statements opcode - if (!opt_return_only || needsdone) - { - /*if (pr_classtype) - { - QCC_def_t *e, *e2; - e = QCC_PR_GetDef(NULL, "__oself", pr_scope, false, 0); - e2 = QCC_PR_GetDef(NULL, "self", NULL, false, 0); - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_ENT], e, QCC_PR_DummyDef(pr_classtype, "self", pr_scope, 1, e2->ofs, false), NULL)); - }*/ - - QCC_PR_Statement (pr_opcodes, 0,0, NULL); - } - else - optres_return_only++; - - QCC_CheckForDeadAndMissingReturns(f->code, numstatements, type->aux_type->type); - - if (opt_compound_jumps) - QCC_CompoundJumps(f->code, numstatements); -// if (opt_comexprremoval) -// QCC_CommonSubExpressionRemoval(f->code, numstatements); - - - QCC_RemapLockedTemps(f->code, numstatements); - locals_end = numpr_globals; - - QCC_WriteAsmFunction(pr_scope, f->code, locals_start); - - QCC_Marshal_Locals(f->code, numstatements); - - if (num_labels) - num_labels = 0; - - - if (num_continues) - { - num_continues=0; - QCC_PR_ParseError(ERR_ILLEGALCONTINUES, "%s: function contains illegal continues", pr_scope->name); - } - if (num_breaks) - { - num_breaks=0; - QCC_PR_ParseError(ERR_ILLEGALBREAKS, "%s: function contains illegal breaks", pr_scope->name); - } - if (num_cases) - { - num_cases = 0; - QCC_PR_ParseError(ERR_ILLEGALCASES, "%s: function contains illegal cases", pr_scope->name); - } - - return f; -} - -void QCC_PR_ArrayRecurseDivideRegular(QCC_def_t *array, QCC_def_t *index, int min, int max) -{ - QCC_dstatement_t *st; - QCC_def_t *eq; - if (min == max || min+1 == max) - { - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef(min+0.5f), NULL); - QCC_UnFreeTemp(index); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - st->b = 2; - QCC_PR_Statement(pr_opcodes+OP_RETURN, 0, 0, &st); - st->a = array->ofs + min*array->type->size; - } - else - { - int mid = min + (max-min)/2; - - if (max-min>4) - { - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef(mid+0.5f), NULL); - QCC_UnFreeTemp(index); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - } - else - st = NULL; - QCC_PR_ArrayRecurseDivideRegular(array, index, min, mid); - if (st) - st->b = numstatements - (st-statements); - QCC_PR_ArrayRecurseDivideRegular(array, index, mid, max); - } -} - -//the idea here is that we return a vector, the caller then figures out the extra 3rd. -//This is useful when we have a load of indexes. -void QCC_PR_ArrayRecurseDivideUsingVectors(QCC_def_t *array, QCC_def_t *index, int min, int max) -{ - QCC_dstatement_t *st; - QCC_def_t *eq; - if (min == max || min+1 == max) - { - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef(min+0.5f), NULL); - QCC_UnFreeTemp(index); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - st->b = 2; - QCC_PR_Statement(pr_opcodes+OP_RETURN, 0, 0, &st); - st->a = array->ofs + min*3; - } - else - { - int mid = min + (max-min)/2; - - if (max-min>4) - { - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef(mid+0.5f), NULL); - QCC_UnFreeTemp(index); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - } - else - st = NULL; - QCC_PR_ArrayRecurseDivideUsingVectors(array, index, min, mid); - if (st) - st->b = numstatements - (st-statements); - QCC_PR_ArrayRecurseDivideUsingVectors(array, index, mid, max); - } -} - -//returns a vector overlapping the result needed. -QCC_def_t *QCC_PR_EmitArrayGetVector(QCC_def_t *array) -{ - QCC_dfunction_t *df; - QCC_def_t *temp, *index, *func; - - func = QCC_PR_GetDef(type_function, qcva("ArrayGetVec*%s", array->name), NULL, true, 1, false); - - pr_scope = func; - - df = &functions[numfunctions]; - numfunctions++; - - df->s_file = 0; - df->s_name = QCC_CopyString(func->name); - df->first_statement = numstatements; - df->parm_size[0] = 1; - df->numparms = 1; - df->parm_start = numpr_globals; - index = QCC_PR_GetDef(type_float, "index___", func, true, 1, false); - index->references++; - temp = QCC_PR_GetDef(type_float, "div3___", func, true, 1, false); - locals_end = numpr_globals; - df->locals = locals_end - df->parm_start; - QCC_PR_Statement3(pr_opcodes+OP_DIV_F, index, QCC_MakeFloatDef(3), temp, false); - QCC_PR_Statement3(pr_opcodes+OP_BITAND, temp, temp, temp, false);//round down to int - - QCC_PR_ArrayRecurseDivideUsingVectors(array, temp, 0, (array->arraysize+2)/3); //round up - - QCC_PR_Statement(pr_opcodes+OP_RETURN, QCC_MakeFloatDef(0), 0, NULL); //err... we didn't find it, give up. - QCC_PR_Statement(pr_opcodes+OP_DONE, 0, 0, NULL); //err... we didn't find it, give up. - - G_FUNCTION(func->ofs) = df - functions; - func->initialized = 1; - return func; -} - -void QCC_PR_EmitArrayGetFunction(QCC_def_t *scope, char *arrayname) -{ - QCC_def_t *vectortrick; - QCC_dfunction_t *df; - QCC_def_t *def, *index; - - QCC_dstatement_t *st; - QCC_def_t *eq; - - QCC_def_t *fasttrackpossible; - - if (flag_fasttrackarrays) - fasttrackpossible = QCC_PR_GetDef(type_float, "__ext__fasttrackarrays", NULL, true, 1, false); - else - fasttrackpossible = NULL; - - def = QCC_PR_GetDef(NULL, arrayname, NULL, false, 0, false); - - if (def->arraysize >= 15 && def->type->size == 1) - { - vectortrick = QCC_PR_EmitArrayGetVector(def); - } - else - vectortrick = NULL; - - pr_scope = scope; - - df = &functions[numfunctions]; - numfunctions++; - - df->s_file = 0; - df->s_name = QCC_CopyString(scope->name); - df->first_statement = numstatements; - df->parm_size[0] = 1; - df->numparms = 1; - df->parm_start = numpr_globals; - index = QCC_PR_GetDef(type_float, "indexg___", def, true, 1, false); - - G_FUNCTION(scope->ofs) = df - functions; - - if (fasttrackpossible) - { - QCC_PR_Statement(pr_opcodes+OP_IFNOT, fasttrackpossible, NULL, &st); - //fetch_gbl takes: (float size, variant array[]), float index, variant pos - //note that the array size is coded into the globals, one index before the array. - - if (def->type->size >= 3) - QCC_PR_Statement3(&pr_opcodes[OP_FETCH_GBL_V], def, index, &def_ret, true); - else - QCC_PR_Statement3(&pr_opcodes[OP_FETCH_GBL_F], def, index, &def_ret, true); - - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_RETURN], &def_ret, NULL, NULL)); - - //finish the jump - st->b = &statements[numstatements] - st; - } - - if (vectortrick) - { - QCC_def_t *div3, *intdiv3, *ret; - - //okay, we've got a function to retrieve the var as part of a vector. - //we need to work out which part, x/y/z that it's stored in. - //0,1,2 = i - ((int)i/3 *) 3; - - div3 = QCC_PR_GetDef(type_float, "div3___", def, true, 1, false); - intdiv3 = QCC_PR_GetDef(type_float, "intdiv3___", def, true, 1, false); - - eq = QCC_PR_Statement(pr_opcodes+OP_GE, index, QCC_MakeFloatDef((float)def->arraysize), NULL); //escape clause - should call some sort of error function instead.. that'd rule! - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - st->b = 2; - QCC_PR_Statement(pr_opcodes+OP_RETURN, QCC_MakeFloatDef(0), 0, &st); - - div3->references++; - QCC_PR_Statement3(pr_opcodes+OP_BITAND, index, index, index, false); - QCC_PR_Statement3(pr_opcodes+OP_DIV_F, index, QCC_MakeFloatDef(3), div3, false); - QCC_PR_Statement3(pr_opcodes+OP_BITAND, div3, div3, intdiv3, false); - - QCC_PR_Statement3(pr_opcodes+OP_STORE_F, index, &def_parms[0], NULL, false); - QCC_PR_Statement3(pr_opcodes+OP_CALL1, vectortrick, NULL, NULL, false); - vectortrick->references++; - ret = QCC_PR_GetDef(type_vector, "vec__", pr_scope, true, 1, false); - ret->references+=4; - QCC_PR_Statement3(pr_opcodes+OP_STORE_V, &def_ret, ret, NULL, false); - QCC_FreeTemp(&def_ret); - - div3 = QCC_PR_Statement(pr_opcodes+OP_MUL_F, intdiv3, QCC_MakeFloatDef(3), NULL); - QCC_PR_Statement3(pr_opcodes+OP_SUB_F, index, div3, index, false); - QCC_FreeTemp(div3); - - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef(0+0.5f), NULL); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - st->b = 2; - QCC_PR_Statement(pr_opcodes+OP_RETURN, 0, 0, &st); - st->a = ret->ofs + 0; - - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef(1+0.5f), NULL); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - st->b = 2; - QCC_PR_Statement(pr_opcodes+OP_RETURN, 0, 0, &st); - st->a = ret->ofs + 1; - - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef(2+0.5), NULL); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - st->b = 2; - QCC_PR_Statement(pr_opcodes+OP_RETURN, 0, 0, &st); - st->a = ret->ofs + 2; - QCC_FreeTemp(ret); - QCC_FreeTemp(index); - } - else - { - QCC_PR_Statement3(pr_opcodes+OP_BITAND, index, index, index, false); - QCC_PR_ArrayRecurseDivideRegular(def, index, 0, def->arraysize); - } - - QCC_PR_Statement(pr_opcodes+OP_RETURN, QCC_MakeFloatDef(0), 0, NULL); - - QCC_PR_Statement(pr_opcodes+OP_DONE, 0, 0, NULL); - - locals_end = numpr_globals; - df->locals = locals_end - df->parm_start; - - - QCC_WriteAsmFunction(pr_scope, df->first_statement, df->parm_start); - - QCC_FreeTemps(); -} - -void QCC_PR_ArraySetRecurseDivide(QCC_def_t *array, QCC_def_t *index, QCC_def_t *value, int min, int max) -{ - QCC_dstatement_t *st; - QCC_def_t *eq; - if (min == max || min+1 == max) - { - eq = QCC_PR_Statement(pr_opcodes+OP_EQ_F, index, QCC_MakeFloatDef((float)min), NULL); - QCC_UnFreeTemp(index); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - st->b = 3; - if (array->type->size == 3) - QCC_PR_Statement(pr_opcodes+OP_STORE_V, value, array, &st); - else - QCC_PR_Statement(pr_opcodes+OP_STORE_F, value, array, &st); - st->b = array->ofs + min*array->type->size; - QCC_PR_Statement(pr_opcodes+OP_RETURN, 0, 0, &st); - } - else - { - int mid = min + (max-min)/2; - - if (max-min>4) - { - eq = QCC_PR_Statement(pr_opcodes+OP_LT, index, QCC_MakeFloatDef((float)mid), NULL); - QCC_UnFreeTemp(index); - QCC_FreeTemp(QCC_PR_Statement(pr_opcodes+OP_IFNOT, eq, 0, &st)); - } - else - st = NULL; - QCC_PR_ArraySetRecurseDivide(array, index, value, min, mid); - if (st) - st->b = numstatements - (st-statements); - QCC_PR_ArraySetRecurseDivide(array, index, value, mid, max); - } -} - -void QCC_PR_EmitArraySetFunction(QCC_def_t *scope, char *arrayname) -{ - QCC_dfunction_t *df; - QCC_def_t *def, *index, *value; - - QCC_def_t *fasttrackpossible; - - if (flag_fasttrackarrays) - fasttrackpossible = QCC_PR_GetDef(type_float, "__ext__fasttrackarrays", NULL, true, 1, false); - else - fasttrackpossible = NULL; - - def = QCC_PR_GetDef(NULL, arrayname, NULL, false, 0, false); - pr_scope = scope; - - df = &functions[numfunctions]; - numfunctions++; - - df->s_file = 0; - df->s_name = QCC_CopyString(scope->name); - df->first_statement = numstatements; - df->parm_size[0] = 1; - df->parm_size[1] = def->type->size; - df->numparms = 2; - df->parm_start = numpr_globals; - index = QCC_PR_GetDef(type_float, "indexs___", def, true, 1, false); - value = QCC_PR_GetDef(def->type, "value___", def, true, 1, false); - locals_end = numpr_globals; - df->locals = locals_end - df->parm_start; - - G_FUNCTION(scope->ofs) = df - functions; - - if (fasttrackpossible) - { - QCC_dstatement_t *st; - - QCC_PR_Statement(pr_opcodes+OP_IFNOT, fasttrackpossible, NULL, &st); - //note that the array size is coded into the globals, one index before the array. - - QCC_PR_Statement3(&pr_opcodes[OP_CONV_FTOI], index, NULL, index, true); //address stuff is integer based, but standard qc (which this accelerates in supported engines) only supports floats - QCC_PR_SimpleStatement (OP_BOUNDCHECK, index->ofs, ((int*)qcc_pr_globals)[def->ofs-1]+1, 0, true);//annoy the programmer. :p - if (def->type->size != 1)//shift it upwards for larger types - QCC_PR_Statement3(&pr_opcodes[OP_MUL_I], index, QCC_MakeIntDef(def->type->size), index, true); - QCC_PR_Statement3(&pr_opcodes[OP_GLOBALADDRESS], def, index, index, true); //comes with built in add - if (def->type->size >= 3) - QCC_PR_Statement3(&pr_opcodes[OP_STOREP_V], value, index, NULL, true); //*b = a - else - QCC_PR_Statement3(&pr_opcodes[OP_STOREP_F], value, index, NULL, true); - QCC_PR_Statement(&pr_opcodes[OP_RETURN], value, NULL, NULL); - - //finish the jump - st->b = &statements[numstatements] - st; - } - - QCC_PR_Statement3(pr_opcodes+OP_BITAND, index, index, index, false); - QCC_PR_ArraySetRecurseDivide(def, index, value, 0, def->arraysize); - - QCC_PR_Statement(pr_opcodes+OP_DONE, 0, 0, NULL); - - - - QCC_WriteAsmFunction(pr_scope, df->first_statement, df->parm_start); - - QCC_FreeTemps(); -} - -//register a def, and all of it's sub parts. -//only the main def is of use to the compiler. -//the subparts are emitted to the compiler and allow correct saving/loading -//be careful with fields, this doesn't allocated space, so will it allocate fields. It only creates defs at specified offsets. -QCC_def_t *QCC_PR_DummyDef(QCC_type_t *type, char *name, QCC_def_t *scope, int arraysize, unsigned int ofs, int referable, pbool saved) -{ - char array[64]; - char newname[256]; - int a; - QCC_def_t *def, *first=NULL; - -#define KEYWORD(x) if (!STRCMP(name, #x) && keyword_##x) {if (keyword_##x)QCC_PR_ParseWarning(WARN_KEYWORDDISABLED, "\""#x"\" keyword used as variable name%s", keywords_coexist?" - coexisting":" - disabling");keyword_##x=keywords_coexist;} - if (name) - { - KEYWORD(var); - KEYWORD(thinktime); - KEYWORD(for); - KEYWORD(switch); - KEYWORD(case); - KEYWORD(default); - KEYWORD(goto); - if (type->type != ev_function) - KEYWORD(break); - KEYWORD(continue); - KEYWORD(state); - KEYWORD(string); - if (qcc_targetformat != QCF_HEXEN2) - KEYWORD(float); //hmm... hexen2 requires this... - KEYWORD(entity); - KEYWORD(vector); - KEYWORD(const); - KEYWORD(asm); - } - - for (a = 0; a < arraysize; a++) - { - if (a == 0) - *array = '\0'; - else - sprintf(array, "[%i]", a); - - if (name) - sprintf(newname, "%s%s", name, array); - else - *newname = *""; - - // allocate a new def - def = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - memset (def, 0, sizeof(*def)); - def->next = NULL; - def->arraysize = arraysize; - if (name) - { - pr.def_tail->next = def; - pr.def_tail = def; - } - - if (a > 0) - def->references++; - - def->s_line = pr_source_line; - def->s_file = s_file; - - def->name = (void *)qccHunkAlloc (strlen(newname)+1); - strcpy (def->name, newname); - def->type = type; - - def->scope = scope; - def->saved = saved; - - // if (arraysize>1) - def->constant = true; - - if (ofs + type->size*a >= MAX_REGS) - QCC_Error(ERR_TOOMANYGLOBALS, "MAX_REGS is too small"); - def->ofs = ofs + type->size*a; - if (!first) - first = def; - -// printf("Emited %s\n", newname); - - if (type->type == ev_struct) - { - int partnum; - QCC_type_t *parttype; - parttype = type->param; - for (partnum = 0; partnum < type->num_parms; partnum++) - { - switch (parttype->type) - { - case ev_vector: - sprintf(newname, "%s%s.%s", name, array, parttype->name); - QCC_PR_DummyDef(parttype, newname, scope, 1, ofs + type->size*a + parttype->ofs, false, saved); - - sprintf(newname, "%s%s.%s_x", name, array, parttype->name); - QCC_PR_DummyDef(type_float, newname, scope, 1, ofs + type->size*a + parttype->ofs, false, false); - sprintf(newname, "%s%s.%s_y", name, array, parttype->name); - QCC_PR_DummyDef(type_float, newname, scope, 1, ofs + type->size*a + parttype->ofs+1, false, false); - sprintf(newname, "%s%s.%s_z", name, array, parttype->name); - QCC_PR_DummyDef(type_float, newname, scope, 1, ofs + type->size*a + parttype->ofs+2, false, false); - break; - - case ev_float: - case ev_string: - case ev_entity: - case ev_field: - case ev_pointer: - case ev_integer: - case ev_struct: - case ev_union: - case ev_variant: //for lack of any better alternative - sprintf(newname, "%s%s.%s", name, array, parttype->name); - QCC_PR_DummyDef(parttype, newname, scope, 1, ofs + type->size*a + parttype->ofs, false, saved); - break; - - case ev_function: - sprintf(newname, "%s%s.%s", name, array, parttype->name); - QCC_PR_DummyDef(parttype, newname, scope, 1, ofs + type->size*a +parttype->ofs, false, saved)->initialized = true; - break; - case ev_void: - break; - } - parttype=parttype->next; - } - } - else if (type->type == ev_vector) - { //do the vector thing. - sprintf(newname, "%s%s_x", name, array); - QCC_PR_DummyDef(type_float, newname, scope, 1, ofs + type->size*a+0, referable, false); - sprintf(newname, "%s%s_y", name, array); - QCC_PR_DummyDef(type_float, newname, scope, 1, ofs + type->size*a+1, referable, false); - sprintf(newname, "%s%s_z", name, array); - QCC_PR_DummyDef(type_float, newname, scope, 1, ofs + type->size*a+2, referable, false); - } - else if (type->type == ev_field) - { - if (type->aux_type->type == ev_vector) - { - //do the vector thing. - sprintf(newname, "%s%s_x", name, array); - QCC_PR_DummyDef(type_floatfield, newname, scope, 1, ofs + type->size*a+0, referable, false); - sprintf(newname, "%s%s_y", name, array); - QCC_PR_DummyDef(type_floatfield, newname, scope, 1, ofs + type->size*a+1, referable, false); - sprintf(newname, "%s%s_z", name, array); - QCC_PR_DummyDef(type_floatfield, newname, scope, 1, ofs + type->size*a+2, referable, false); - } - } - } - - if (referable) - { - if (!pHash_Get(&globalstable, "end_sys_fields")) - first->references++; //anything above needs to be left in, and so warning about not using it is just going to pee people off. - if (arraysize <= 1) - first->constant = false; - if (scope) - pHash_Add(&localstable, first->name, first, qccHunkAlloc(sizeof(bucket_t))); - else - pHash_Add(&globalstable, first->name, first, qccHunkAlloc(sizeof(bucket_t))); - - if (!scope && asmfile) - fprintf(asmfile, "%s %s;\n", TypeName(first->type), first->name); - } - - return first; -} - -/* -============ -PR_GetDef - -If type is NULL, it will match any type -If allocate is true, a new def will be allocated if it can't be found -============ -*/ - -QCC_def_t *QCC_PR_GetDef (QCC_type_t *type, char *name, QCC_def_t *scope, pbool allocate, int arraysize, pbool saved) -{ - int ofs; - QCC_def_t *def; -// char element[MAX_NAME]; - unsigned int i; - QCC_def_t *foundstatic = NULL; - - if (scope) - { - def = Hash_Get(&localstable, name); - - while(def) - { - if ( def->scope && def->scope != scope) - { - def = Hash_GetNext(&localstable, name, def); - continue; // in a different function - } - - if (type && typecmp(def->type, type)) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHREDEC, def, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); - if (def->arraysize != arraysize && arraysize) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHARRAYSIZE, def, "Array sizes for redecleration of %s do not match",name); - if (allocate && scope) - { - QCC_PR_ParseWarning (WARN_DUPLICATEDEFINITION, "%s duplicate definition ignored", name); - QCC_PR_ParsePrintDef(WARN_DUPLICATEDEFINITION, def); -// if (!scope) -// QCC_PR_ParsePrintDef(def); - } - return def; - } - } - - - def = Hash_Get(&globalstable, name); - - while(def) - { - if ( def->scope && def->scope != scope) - { - def = Hash_GetNext(&globalstable, name, def); - continue; // in a different function - } - - if (def->isstatic && def->s_file != s_file) - { //warn? or would that be pointless? - foundstatic = def; - def = Hash_GetNext(&globalstable, name, def); - continue; // in a different function - } - - if (type && typecmp(def->type, type)) - { - if (!pr_scope) - QCC_PR_ParseErrorPrintDef (ERR_TYPEMISMATCHREDEC, def, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); - } - if (def->arraysize != arraysize && arraysize) - QCC_PR_ParseErrorPrintDef(ERR_TYPEMISMATCHARRAYSIZE, def, "Array sizes for redecleration of %s do not match",name); - if (allocate && scope) - { - if (pr_scope) - { //warn? or would that be pointless? - def = Hash_GetNext(&globalstable, name, def); - continue; // in a different function - } - - QCC_PR_ParseWarning (WARN_DUPLICATEDEFINITION, "%s duplicate definition ignored", name); - QCC_PR_ParsePrintDef(WARN_DUPLICATEDEFINITION, def); -// if (!scope) -// QCC_PR_ParsePrintDef(def); - } - return def; - } - - if (pHash_Get != &Hash_Get && !allocate) //do we want to try case insensative too? - { - if (scope) - { - def = pHash_Get(&localstable, name); - - while(def) - { - if ( def->scope && def->scope != scope) - { - def = pHash_GetNext(&localstable, name, def); - continue; // in a different function - } - - if (type && typecmp(def->type, type)) - QCC_PR_ParseError (ERR_TYPEMISMATCHREDEC, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); - if (def->arraysize != arraysize && arraysize) - QCC_PR_ParseError (ERR_TYPEMISMATCHARRAYSIZE, "Array sizes for redecleration of %s do not match",name); - if (allocate && scope) - { - QCC_PR_ParseWarning (WARN_DUPLICATEDEFINITION, "%s duplicate definition ignored", name); - QCC_PR_ParsePrintDef(WARN_DUPLICATEDEFINITION, def); - // if (!scope) - // QCC_PR_ParsePrintDef(def); - } - return def; - } - } - - - def = pHash_Get(&globalstable, name); - - while(def) - { - if ( def->scope && def->scope != scope) - { - def = pHash_GetNext(&globalstable, name, def); - continue; // in a different function - } - - if (def->isstatic && def->s_file != s_file) - { //warn? or would that be pointless? - foundstatic = def; - def = Hash_GetNext(&globalstable, name, def); - continue; // in a different function - } - - if (type && typecmp(def->type, type)) - { - if (!pr_scope) - QCC_PR_ParseError (ERR_TYPEMISMATCHREDEC, "Type mismatch on redeclaration of %s. %s, should be %s",name, TypeName(type), TypeName(def->type)); - } - if (def->arraysize != arraysize && arraysize) - QCC_PR_ParseError (ERR_TYPEMISMATCHARRAYSIZE, "Array sizes for redecleration of %s do not match",name); - if (allocate && scope) - { - if (pr_scope) - { //warn? or would that be pointless? - def = pHash_GetNext(&globalstable, name, def); - continue; // in a different function - } - - QCC_PR_ParseWarning (WARN_DUPLICATEDEFINITION, "%s duplicate definition ignored", name); - QCC_PR_ParsePrintDef(WARN_DUPLICATEDEFINITION, def); - // if (!scope) - // QCC_PR_ParsePrintDef(def); - } - return def; - } - } - - if (foundstatic && !allocate) - { - QCC_PR_ParseWarning (WARN_DUPLICATEDEFINITION, "%s defined static", name); - QCC_PR_ParsePrintDef(WARN_DUPLICATEDEFINITION, foundstatic); - } - - if (!allocate) - return NULL; - - if (arraysize < 1) - { - QCC_PR_ParseError (ERR_ARRAYNEEDSSIZE, "First declaration of array %s with no size",name); - } - - if (scope) - { - if (QCC_PR_GetDef(type, name, NULL, false, arraysize, false)) - QCC_PR_ParseWarning(WARN_SAMENAMEASGLOBAL, "Local \"%s\" defined with name of a global", name); - } - - ofs = numpr_globals; - if (arraysize > 1) - { //write the array size - ofs = QCC_GetFreeOffsetSpace(1 + (type->size * arraysize)); - - ((int *)qcc_pr_globals)[ofs] = arraysize-1; //An array needs the size written first. This is a hexen2 opcode thing. - ofs++; - } - else - ofs = QCC_GetFreeOffsetSpace(type->size * arraysize); - - def = QCC_PR_DummyDef(type, name, scope, arraysize, ofs, true, saved); - - //fix up fields. - if (type->type == ev_field && allocate != 2) - { - for (i = 0; i < type->size*arraysize; i++) //make arrays of fields work. - *(int *)&qcc_pr_globals[def->ofs+i] = pr.size_fields+i; - - pr.size_fields += i; - } - - if (scope) - { - def->nextlocal = pr.localvars; - pr.localvars = def; - } - - return def; -} - -QCC_def_t *QCC_PR_DummyFieldDef(QCC_type_t *type, char *name, QCC_def_t *scope, int arraysize, unsigned int *fieldofs, pbool saved) -{ - char array[64]; - char newname[256]; - int a, parms; - QCC_def_t *def, *first=NULL; - unsigned int maxfield, startfield; - QCC_type_t *ftype; - pbool isunion; - startfield = *fieldofs; - maxfield = startfield; - - for (a = 0; a < arraysize; a++) - { - if (a == 0) - *array = '\0'; - else - sprintf(array, "[%i]", a); - - if (*name) - { - sprintf(newname, "%s%s", name, array); - - // allocate a new def - def = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - memset (def, 0, sizeof(*def)); - def->next = NULL; - def->arraysize = arraysize; - - pr.def_tail->next = def; - pr.def_tail = def; - - def->s_line = pr_source_line; - def->s_file = s_file; - - def->name = (void *)qccHunkAlloc (strlen(newname)+1); - strcpy (def->name, newname); - def->type = type; - - def->scope = scope; - - def->ofs = QCC_GetFreeOffsetSpace(1); - ((int *)qcc_pr_globals)[def->ofs] = *fieldofs; - *fieldofs++; - if (!first) - first = def; - } - else - { - def=NULL; - } - -// printf("Emited %s\n", newname); - - if ((type)->type == ev_struct||(type)->type == ev_union) - { - int partnum; - QCC_type_t *parttype; - if (def) - def->references++; - parttype = (type)->param; - isunion = ((type)->type == ev_union); - for (partnum = 0, parms = (type)->num_parms; partnum < parms; partnum++) - { - switch (parttype->type) - { - case ev_union: - case ev_struct: - if (*name) - sprintf(newname, "%s%s.%s", name, array, parttype->name); - else - sprintf(newname, "%s%s", parttype->name, array); - def = QCC_PR_DummyFieldDef(parttype, newname, scope, 1, fieldofs, saved); - break; - case ev_float: - case ev_string: - case ev_vector: - case ev_entity: - case ev_field: - case ev_pointer: - case ev_integer: - case ev_variant: - if (*name) - sprintf(newname, "%s%s.%s", name, array, parttype->name); - else - sprintf(newname, "%s%s", parttype->name, array); - ftype = QCC_PR_NewType("FIELD TYPE", ev_field); - ftype->aux_type = parttype; - if (parttype->type == ev_vector) - ftype->size = parttype->size; //vector fields create a _y and _z too, so we need this still. - def = QCC_PR_GetDef(NULL, newname, scope, false, 1, saved); - if (!def) - { - def = QCC_PR_GetDef(ftype, newname, scope, true, 1, saved); - } - else - { - QCC_PR_ParseWarning(WARN_CONFLICTINGUNIONMEMBER, "conflicting offsets for union/struct expansion of %s. Ignoring new def.", newname); - QCC_PR_ParsePrintDef(WARN_CONFLICTINGUNIONMEMBER, def); - } - break; - - case ev_function: - if (*name) - sprintf(newname, "%s%s.%s", name, array, parttype->name); - else - sprintf(newname, "%s%s", parttype->name, array); - ftype = QCC_PR_NewType("FIELD TYPE", ev_field); - ftype->aux_type = parttype; - def = QCC_PR_GetDef(ftype, newname, scope, true, 1, saved); - def->initialized = true; - ((int *)qcc_pr_globals)[def->ofs] = *fieldofs; - *fieldofs += parttype->size; - break; - case ev_void: - break; - } - if (*fieldofs > maxfield) - maxfield = *fieldofs; - if (isunion) - *fieldofs = startfield; - - type = parttype; - parttype=parttype->next; - } - } - } - - *fieldofs = maxfield; //final size of the union. - return first; -} - - - -void QCC_PR_ExpandUnionToFields(QCC_type_t *type, int *fields) -{ - QCC_type_t *pass = type->aux_type; - QCC_PR_DummyFieldDef(pass, "", pr_scope, 1, fields, true); -} - -int accglobalsblock; //0 = error, 1 = var, 2 = function, 3 = objdata -/* -================ -PR_ParseDefs - -Called at the outer layer and when a local statement is hit -================ -*/ -void QCC_PR_ParseDefs (char *classname) -{ - char *name; - QCC_type_t *type, *parm; - QCC_def_t *def, *d; - QCC_function_t *f; - QCC_dfunction_t *df; - int i; - extern pbool defaultstatic; - pbool shared=false; - pbool isstatic=defaultstatic; - pbool externfnc=false; - pbool isconstant = false; - pbool isvar = false; - pbool noref = false; - pbool nosave = false; - pbool allocatenew = true; - pbool inlinefunction = false; - int ispointer; - gofs_t oldglobals; - int arraysize; - - if (QCC_PR_CheckKeyword(keyword_enum, "enum")) - { - if (QCC_PR_CheckKeyword(keyword_integer, "integer") || QCC_PR_CheckKeyword(keyword_int, "int")) - { - int iv = 0; - QCC_PR_Expect("{"); - i = 0; - d = NULL; - while(1) - { - name = QCC_PR_ParseName(); - if (QCC_PR_CheckToken("=")) - { - if (pr_token_type != tt_immediate && pr_immediate_type->type != ev_integer) - { - def = QCC_PR_GetDef(NULL, QCC_PR_ParseName(), NULL, false, 0, false); - if (def) - { - if (!def->constant) - QCC_PR_ParseError(ERR_NOTANUMBER, "enum - %s is not a constant", def->name); - else - iv = G_INT(def->ofs); - } - else - QCC_PR_ParseError(ERR_NOTANUMBER, "enum - not a number"); - } - else - { - iv = pr_immediate._int; - QCC_PR_Lex(); - } - } - def = QCC_MakeIntDef(iv); - pHash_Add(&globalstable, name, def, qccHunkAlloc(sizeof(bucket_t))); - iv++; - - if (QCC_PR_CheckToken("}")) - break; - QCC_PR_Expect(","); - } - } - else - { - float fv = 0; - QCC_PR_CheckKeyword(keyword_float, "float"); - QCC_PR_Expect("{"); - i = 0; - d = NULL; - while(1) - { - name = QCC_PR_ParseName(); - if (QCC_PR_CheckToken("=")) - { - if (pr_token_type != tt_immediate && pr_immediate_type->type != ev_float) - { - def = QCC_PR_GetDef(NULL, QCC_PR_ParseName(), NULL, false, 0, false); - if (def) - { - if (!def->constant) - QCC_PR_ParseError(ERR_NOTANUMBER, "enum - %s is not a constant", def->name); - else - fv = G_FLOAT(def->ofs); - } - else - QCC_PR_ParseError(ERR_NOTANUMBER, "enum - not a number"); - } - else - { - fv = pr_immediate._float; - QCC_PR_Lex(); - } - } - def = QCC_MakeFloatDef(fv); - pHash_Add(&globalstable, name, def, qccHunkAlloc(sizeof(bucket_t))); - fv++; - - if (QCC_PR_CheckToken("}")) - break; - QCC_PR_Expect(","); - } - } - QCC_PR_Expect(";"); - return; - } - - if (QCC_PR_CheckKeyword(keyword_enumflags, "enumflags")) - { - int bits; - - if (QCC_PR_CheckKeyword(keyword_integer, "integer") || QCC_PR_CheckKeyword(keyword_int, "int")) - { - int iv = 1; - QCC_PR_Expect("{"); - i = 0; - d = NULL; - while(1) - { - name = QCC_PR_ParseName(); - if (QCC_PR_CheckToken("=")) - { - if (pr_token_type != tt_immediate && pr_immediate_type->type != ev_integer) - { - def = QCC_PR_GetDef(NULL, QCC_PR_ParseName(), NULL, false, 0, false); - if (def) - { - if (!def->constant) - QCC_PR_ParseError(ERR_NOTANUMBER, "enumflags - %s is not a constant", def->name); - else - iv = G_INT(def->ofs); - } - else - QCC_PR_ParseError(ERR_NOTANUMBER, "enumflags - not a number"); - } - else - { - iv = pr_immediate._int; - QCC_PR_Lex(); - } - } - - bits = 0; - i = (int)iv; - if (i != iv) - QCC_PR_ParseWarning(WARN_ENUMFLAGS_NOTINTEGER, "enumflags - %f not an integer", iv); - else - { - while(i) - { - if (((i>>1)<<1) != i) - bits++; - i>>=1; - } - if (bits != 1) - QCC_PR_ParseWarning(WARN_ENUMFLAGS_NOTBINARY, "enumflags - value %i not a single bit", (int)iv); - } - - def = QCC_MakeIntDef(iv); - pHash_Add(&globalstable, name, def, qccHunkAlloc(sizeof(bucket_t))); - - iv*=2; - - if (QCC_PR_CheckToken("}")) - break; - QCC_PR_Expect(","); - } - } - else - { - float fv = 1; - QCC_PR_CheckKeyword(keyword_float, "float"); - - QCC_PR_Expect("{"); - i = 0; - d = NULL; - while(1) - { - name = QCC_PR_ParseName(); - if (QCC_PR_CheckToken("=")) - { - if (pr_token_type != tt_immediate && pr_immediate_type->type != ev_float) - { - def = QCC_PR_GetDef(NULL, QCC_PR_ParseName(), NULL, false, 0, false); - if (def) - { - if (!def->constant) - QCC_PR_ParseError(ERR_NOTANUMBER, "enumflags - %s is not a constant", def->name); - else - fv = G_FLOAT(def->ofs); - } - else - QCC_PR_ParseError(ERR_NOTANUMBER, "enumflags - not a number"); - } - else - { - fv = pr_immediate._float; - QCC_PR_Lex(); - } - } - - bits = 0; - i = (int)fv; - if (i != fv) - QCC_PR_ParseWarning(WARN_ENUMFLAGS_NOTINTEGER, "enumflags - %f not an integer", fv); - else - { - while(i) - { - if (((i>>1)<<1) != i) - bits++; - i>>=1; - } - if (bits != 1) - QCC_PR_ParseWarning(WARN_ENUMFLAGS_NOTBINARY, "enumflags - value %i not a single bit", (int)fv); - } - - def = QCC_MakeFloatDef(fv); - pHash_Add(&globalstable, name, def, qccHunkAlloc(sizeof(bucket_t))); - - fv*=2; - - if (QCC_PR_CheckToken("}")) - break; - QCC_PR_Expect(","); - } - } - QCC_PR_Expect(";"); - return; - } - - if (QCC_PR_CheckKeyword (keyword_typedef, "typedef")) - { - type = QCC_PR_ParseType(true); - if (!type) - { - QCC_PR_ParseError(ERR_NOTANAME, "typedef found unexpected tokens"); - } - type->name = QCC_CopyString(pr_token)+strings; - QCC_PR_Lex(); - QCC_PR_Expect(";"); - return; - } - - if (flag_acc) - { - char *oldp; - if (QCC_PR_CheckKeyword (keyword_codesys, "CodeSys")) //reacc support. - { - if (ForcedCRC) - QCC_PR_ParseError(ERR_BADEXTENSION, "progs crc was already specified - only one is allowed"); - ForcedCRC = (int)pr_immediate._float; - QCC_PR_Lex(); - QCC_PR_Expect(";"); - return; - } - - oldp = pr_file_p; - if (QCC_PR_CheckKeyword (keyword_var, "var")) //reacc support. - { - if (accglobalsblock == 3) - { - if (!QCC_PR_GetDef(type_void, "end_sys_fields", NULL, false, 0, false)) - QCC_PR_GetDef(type_void, "end_sys_fields", NULL, true, 1, false); - } - - QCC_PR_ParseName(); - if (QCC_PR_CheckToken(":")) - accglobalsblock = 1; - pr_file_p = oldp; - QCC_PR_Lex(); - } - - if (QCC_PR_CheckKeyword (keyword_function, "function")) //reacc support. - { - accglobalsblock = 2; - } - if (QCC_PR_CheckKeyword (keyword_objdata, "objdata")) //reacc support. - { - if (accglobalsblock == 3) - { - if (!QCC_PR_GetDef(type_void, "end_sys_fields", NULL, false, 0, false)) - QCC_PR_GetDef(type_void, "end_sys_fields", NULL, true, 1, false); - } - else - if (!QCC_PR_GetDef(type_void, "end_sys_globals", NULL, false, 0, false)) - QCC_PR_GetDef(type_void, "end_sys_globals", NULL, true, 1, false); - accglobalsblock = 3; - } - } - - if (!pr_scope) - switch(accglobalsblock)//reacc support. - { - case 1: - { - char *oldp = pr_file_p; - name = QCC_PR_ParseName(); - if (!QCC_PR_CheckToken(":")) //nope, it wasn't! - { - QCC_PR_IncludeChunk(name, true, NULL); - QCC_PR_Lex(); - QCC_PR_UnInclude(); - pr_file_p = oldp; - break; - } - if (QCC_PR_CheckKeyword(keyword_object, "object")) - QCC_PR_GetDef(type_entity, name, NULL, true, 1, true); - else if (QCC_PR_CheckKeyword(keyword_string, "string")) - QCC_PR_GetDef(type_string, name, NULL, true, 1, true); - else if (QCC_PR_CheckKeyword(keyword_real, "real")) - { - def = QCC_PR_GetDef(type_float, name, NULL, true, 1, true); - if (QCC_PR_CheckToken("=")) - { - G_FLOAT(def->ofs) = pr_immediate._float; - QCC_PR_Lex(); - } - } - else if (QCC_PR_CheckKeyword(keyword_vector, "vector")) - { - def = QCC_PR_GetDef(type_vector, name, NULL, true, 1, true); - if (QCC_PR_CheckToken("=")) - { - QCC_PR_Expect("["); - G_FLOAT(def->ofs+0) = pr_immediate._float; - QCC_PR_Lex(); - G_FLOAT(def->ofs+1) = pr_immediate._float; - QCC_PR_Lex(); - G_FLOAT(def->ofs+2) = pr_immediate._float; - QCC_PR_Lex(); - QCC_PR_Expect("]"); - } - } - else if (QCC_PR_CheckKeyword(keyword_pfunc, "pfunc")) - QCC_PR_GetDef(type_function, name, NULL, true, 1, true); - else - QCC_PR_ParseError(ERR_BADNOTTYPE, "Bad type\n"); - QCC_PR_Expect (";"); - - if (QCC_PR_CheckKeyword (keyword_system, "system")) - QCC_PR_Expect (";"); - return; - } - case 2: - name = QCC_PR_ParseName(); - QCC_PR_GetDef(type_function, name, NULL, true, 1, true); - QCC_PR_CheckToken (";"); - return; - case 3: - { - char *oldp = pr_file_p; - name = QCC_PR_ParseName(); - if (!QCC_PR_CheckToken(":")) //nope, it wasn't! - { - QCC_PR_IncludeChunk(name, true, NULL); - QCC_PR_Lex(); - QCC_PR_UnInclude(); - pr_file_p = oldp; - break; - } - if (QCC_PR_CheckKeyword(keyword_object, "object")) - QCC_PR_GetDef(QCC_PR_FieldType(type_entity), name, NULL, true, 1, true); - else if (QCC_PR_CheckKeyword(keyword_string, "string")) - QCC_PR_GetDef(QCC_PR_FieldType(type_string), name, NULL, true, 1, true); - else if (QCC_PR_CheckKeyword(keyword_real, "real")) - QCC_PR_GetDef(QCC_PR_FieldType(type_float), name, NULL, true, 1, true); - else if (QCC_PR_CheckKeyword(keyword_vector, "vector")) - QCC_PR_GetDef(QCC_PR_FieldType(type_vector), name, NULL, true, 1, true); - else if (QCC_PR_CheckKeyword(keyword_pfunc, "pfunc")) - QCC_PR_GetDef(QCC_PR_FieldType(type_function), name, NULL, true, 1, true); - else - QCC_PR_ParseError(ERR_BADNOTTYPE, "Bad type\n"); - QCC_PR_Expect (";"); - return; - } - } - - while(1) - { - if (QCC_PR_CheckKeyword(keyword_extern, "extern")) - externfnc=true; - else if (QCC_PR_CheckKeyword(keyword_shared, "shared")) - { - shared=true; - if (pr_scope) - QCC_PR_ParseError (ERR_NOSHAREDLOCALS, "Cannot have shared locals"); - } - else if (QCC_PR_CheckKeyword(keyword_const, "const")) - isconstant = true; - else if (QCC_PR_CheckKeyword(keyword_var, "var")) - isvar = true; - else if (!pr_scope && QCC_PR_CheckKeyword(keyword_var, "static")) - isstatic = true; - else if (!pr_scope && QCC_PR_CheckKeyword(keyword_var, "nonstatic")) - isstatic = false; - else if (QCC_PR_CheckKeyword(keyword_noref, "noref")) - noref=true; - else if (QCC_PR_CheckKeyword(keyword_nosave, "nosave")) - nosave = true; - else - break; - } - - type = QCC_PR_ParseType (false); - if (type == NULL) //ignore - return; - - inlinefunction = type_inlinefunction; - - if (externfnc && type->type != ev_function) - { - printf ("Only functions may be defined as external (yet)\n"); - externfnc=false; - } - - if (!pr_scope && QCC_PR_CheckKeyword(keyword_function, "function")) //reacc support. - { - name = QCC_PR_ParseName (); - QCC_PR_Expect("("); - type = QCC_PR_ParseFunctionTypeReacc(false, type); - QCC_PR_Expect(";"); - if (!stricmp(name, "null")) - printf("null!\n"); - def = QCC_PR_GetDef (type, name, NULL, true, 1, false); - - if (autoprototype) - { //ignore the code and stuff - - if (QCC_PR_CheckKeyword(keyword_external, "external")) - { //builtin - QCC_PR_Lex(); - QCC_PR_Expect(";"); - } - else - { - int blev = 1; - - while (!QCC_PR_CheckToken("{")) //skip over the locals. - { - if (pr_token_type == tt_eof) - { - QCC_PR_ParseError(0, "Unexpected EOF"); - break; - } - QCC_PR_Lex(); - } - - //balance out the { and } - while(blev) - { - if (pr_token_type == tt_eof) - break; - if (QCC_PR_CheckToken("{")) - blev++; - else if (QCC_PR_CheckToken("}")) - blev--; - else - QCC_PR_Lex(); //ignore it. - } - } - return; - } - - def->references++; - - pr_scope = def; - f = QCC_PR_ParseImmediateStatements (type); - pr_scope = NULL; - def->initialized = 1; - def->isstatic = isstatic; - G_FUNCTION(def->ofs) = numfunctions; - f->def = def; -// if (pr_dumpasm) -// PR_PrintFunction (def); - -// fill in the dfunction - df = &functions[numfunctions]; - numfunctions++; - if (f->builtin) - df->first_statement = -f->builtin; - else - df->first_statement = f->code; - - if (f->builtin && opt_function_names) - optres_function_names += strlen(f->def->name); - else - df->s_name = QCC_CopyString (f->def->name); - df->s_file = s_file2; - df->numparms = f->def->type->num_parms; - df->locals = locals_end - locals_start; - df->parm_start = locals_start; - for (i=0,parm = type->param ; inumparms ; i++, parm = parm->next) - { - df->parm_size[i] = parm->size; - } - - return; - } - -// if (pr_scope && (type->type == ev_field) ) -// QCC_PR_ParseError ("Fields must be global"); - - do - { - if (QCC_PR_CheckToken ("*")) - { - ispointer = 1; - while(QCC_PR_CheckToken ("*")) - ispointer++; - name = QCC_PR_ParseName (); - } - else if (QCC_PR_CheckToken (";")) - { - if (type->type == ev_field && (type->aux_type->type == ev_union || type->aux_type->type == ev_struct)) - { - QCC_PR_ExpandUnionToFields(type, &pr.size_fields); - return; - } -// if (type->type == ev_union) -// { -// return; -// } - QCC_PR_ParseError (ERR_TYPEWITHNONAME, "type with no name"); - name = NULL; - ispointer = false; - } - else - { - name = QCC_PR_ParseName (); - ispointer = false; - } - - if (QCC_PR_CheckToken("::") && !classname) - { - classname = name; - name = QCC_PR_ParseName(); - } - -//check for an array - - if ( QCC_PR_CheckToken ("[") ) - { - char *oldprfile = pr_file_p; - arraysize = 0; - if (QCC_PR_CheckToken("]")) - { - QCC_PR_Expect("="); - QCC_PR_Expect("{"); - QCC_PR_Lex(); - arraysize++; - while(1) - { - if(pr_token_type == tt_eof) - break; - if (QCC_PR_CheckToken(",")) - arraysize++; - if (QCC_PR_CheckToken("}")) - break; - QCC_PR_Lex(); - } - pr_file_p = oldprfile; - QCC_PR_Lex(); - } - else - { - def = QCC_PR_Expression(TOP_PRIORITY, 0); - if (!def->constant) - QCC_PR_ParseError(ERR_BADARRAYSIZE, "Array size is not a constant value"); - else if (def->type->type == ev_integer) - arraysize = G_INT(def->ofs); - else if (def->type->type == ev_float) - { - arraysize = (int)G_FLOAT(def->ofs); - if ((float)arraysize != G_FLOAT(def->ofs)) - QCC_PR_ParseError(ERR_BADARRAYSIZE, "Array size is not a constant value"); - } - else - QCC_PR_ParseError(ERR_BADARRAYSIZE, "Array size must be of int value"); -/* if(pr_token_type == tt_name) - { - def = QCC_PR_GetDef(NULL, QCC_PR_ParseName(), pr_scope, false, 0); - if (def && def->arraysize==1) - { - if (def->type->type == ev_integer) - arraysize = G_INT(def->ofs); - else if (def->type->type == ev_float && (float)(int)G_FLOAT(def->ofs) == G_FLOAT(def->ofs)) - arraysize = (int)G_FLOAT(def->ofs); - } - } - else if (pr_token_type == tt_immediate) - { - arraysize = atoi (pr_token); - QCC_PR_Lex(); - } -*/ QCC_PR_Expect("]"); - } - - if (arraysize < 1) - { - QCC_PR_ParseError (ERR_BADARRAYSIZE, "Definition of array (%s) size is not of a numerical value", name); - arraysize=0; //grrr... - } - } - else - arraysize = 1; - - if (QCC_PR_CheckToken("(")) - { - if (inlinefunction) - QCC_PR_ParseWarning(WARN_UNSAFEFUNCTIONRETURNTYPE, "Function returning function. Is this what you meant? (suggestion: use typedefs)"); - inlinefunction = false; - type = QCC_PR_ParseFunctionType(false, type); - } - - if (classname) - { - char *membername = name; - name = qccHunkAlloc(strlen(classname) + strlen(name) + 3); - sprintf(name, "%s::"MEMBERFIELDNAME, classname, membername); - if (!QCC_PR_GetDef(NULL, name, NULL, false, 0, false)) - QCC_PR_ParseError(ERR_NOTANAME, "%s %s is not a member of class %s\n", TypeName(type), membername, classname); - sprintf(name, "%s::%s", classname, membername); - - pr_classtype = QCC_TypeForName(classname); - if (!pr_classtype || !pr_classtype->parentclass) - QCC_PR_ParseError(ERR_NOTANAME, "%s is not a class\n", classname); - } - else - pr_classtype = NULL; - - oldglobals = numpr_globals; - - if (ispointer) - { - parm = type; - while(ispointer) - { - ispointer--; - parm = QCC_PointerTypeTo(parm); - } - - def = QCC_PR_GetDef (parm, name, pr_scope, allocatenew, arraysize, !nosave); - } - else - def = QCC_PR_GetDef (type, name, pr_scope, allocatenew, arraysize, !nosave); - - if (!def) - QCC_PR_ParseError(ERR_NOTANAME, "%s is not part of class %s", name, classname); - - if (noref) - def->references++; - - if (!def->initialized && shared) //shared count as initiialised - { - def->shared = shared; - def->initialized = true; - } - if (externfnc) - def->initialized = 2; - - if (isstatic) - { - if (def->s_file == s_file) - def->isstatic = isstatic; - else //if (type->type != ev_function && defaultstatic) //functions don't quite consitiute a definition - QCC_PR_ParseErrorPrintDef (ERR_REDECLARATION, def, "can't redefine non-static as static"); - } - -// check for an initialization - if (type->type == ev_function && (pr_scope)) - { - if ( QCC_PR_CheckToken ("=") ) - { - QCC_PR_ParseError (ERR_INITIALISEDLOCALFUNCTION, "local functions may not be initialised"); - } - - arraysize = def->arraysize; - d = def; //apply to ALL elements - while(arraysize--) - { - d->initialized = 1; //fake function - G_FUNCTION(d->ofs) = 0; - d = d->next; - } - - continue; - } - - if (type->type == ev_field && QCC_PR_CheckName ("alias")) - { - QCC_PR_ParseError(ERR_INTERNAL, "FTEQCC does not support this variant of decompiled hexenc\nPlease obtain the original version released by Raven Software instead."); - name = QCC_PR_ParseName(); - } - else if ( QCC_PR_CheckToken ("=") || ((type->type == ev_function) && (pr_token[0] == '{' || pr_token[0] == '[' || pr_token[0] == ':'))) //this is an initialisation (or a function) - { - if (def->shared) - QCC_PR_ParseError (ERR_SHAREDINITIALISED, "shared values may not be assigned an initial value", name); - if (def->initialized == 1) - { - if (def->type->type == ev_function) - { - i = G_FUNCTION(def->ofs); - df = &functions[i]; - QCC_PR_ParseErrorPrintDef (ERR_REDECLARATION, def, "%s redeclared, prev instance is in %s", name, strings+df->s_file); - } - else - QCC_PR_ParseErrorPrintDef(ERR_REDECLARATION, def, "%s redeclared", name); - } - - if (autoprototype) - { //ignore the code and stuff - if (QCC_PR_CheckToken("[")) - { - while (!QCC_PR_CheckToken("]")) - { - if (pr_token_type == tt_eof) - break; - QCC_PR_Lex(); - } - } - if (QCC_PR_CheckToken("{")) - { - int blev = 1; - //balance out the { and } - while(blev) - { - if (pr_token_type == tt_eof) - break; - if (QCC_PR_CheckToken("{")) - blev++; - else if (QCC_PR_CheckToken("}")) - blev--; - else - QCC_PR_Lex(); //ignore it. - } - } - else - { - QCC_PR_CheckToken("#"); - QCC_PR_Lex(); - } - continue; - } - -#pragma message("this is experimental") - if (pr_scope) - { - d = QCC_PR_Expression(TOP_PRIORITY, EXPR_DISALLOW_COMMA); - if (d->constant) - { - for (i = 0; i < d->type->size; i++) - G_INT(def->ofs+i) = G_INT(d->ofs+i); - def->constant = !isvar; - def->initialized = 1; - continue; - } - else if (def->type->size >= 3) - { - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_V], d, def, NULL)); - def->constant = false; - def->initialized = false; - continue; - } - else - { - QCC_FreeTemp(QCC_PR_Statement(&pr_opcodes[OP_STORE_F], d, def, NULL)); - def->constant = false; - def->initialized = false; - continue; - } - } - else - if (pr_token_type == tt_name && strcmp(pr_token, "_")) - { - unsigned int i; - - if (def->arraysize>1) - QCC_PR_ParseError(ERR_ARRAYNEEDSBRACES, "Array initialisation requires curly braces"); - - d = QCC_PR_GetDef(NULL, pr_token, pr_scope, false, 0, false); - if (!d) - QCC_PR_ParseError(ERR_NOTDEFINED, "%s was not defined\n", pr_token); - if (typecmp(def->type, d->type)) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s", name); - - - for (i = 0; i < d->type->size; i++) - G_INT(def->ofs) = G_INT(d->ofs); - QCC_PR_Lex(); - - if (type->type == ev_function) - { - def->initialized = 1; - def->constant = !isvar; - } - continue; - } - - else if (type->type == ev_function) - { - if (isvar) - def->constant = false; - else - def->constant = true; - if (QCC_PR_CheckImmediate("0")) - { - def->constant = 0; - def->initialized = 1; //fake function - G_FUNCTION(def->ofs) = 0; - continue; - } - - if (!def->constant && arraysize==1) - { - def->constant = 0; - def->initialized = 1; //fake function - - name = QCC_PR_ParseName (); - d = QCC_PR_GetDef (NULL, name, pr_scope, false, 0, false); - if (!d) - QCC_PR_ParseError(ERR_NOTDEFINED, "%s was not previously defined", name); - G_FUNCTION(def->ofs+i) = G_FUNCTION(d->ofs); - continue; - } - - if (arraysize>1) - { - int i; - def->initialized = 1; //fake function - QCC_PR_Expect ("{"); - i = 0; - do - { - if (pr_token_type == tt_immediate && ( - (pr_immediate_type == type_integer && pr_immediate._int == 0) || - (pr_immediate_type == type_float && pr_immediate._float == 0))) - { - QCC_PR_Lex(); - G_FUNCTION(def->ofs+i) = 0; - } - else - { - name = QCC_PR_ParseName (); - - d = QCC_PR_GetDef (NULL, name, pr_scope, false, 0, false); - if (!d) - QCC_PR_ParseError(ERR_NOTDEFINED, "%s was not defined", name); - else - { - if (!d->initialized) - QCC_PR_ParseWarning(WARN_NOTDEFINED, "initialisation of function arrays must be placed after the body of all functions used (%s)", name); - G_FUNCTION(def->ofs+i) = G_FUNCTION(d->ofs); - } - } - - i++; - } while(QCC_PR_CheckToken(",")); - - arraysize = def->arraysize; - d = def; //apply to ALL elements - while(arraysize--) - { - d->initialized = 1; //fake function - d = d->next; - } - - QCC_PR_Expect("}"); - if (i > def->arraysize) - QCC_PR_ParseError(ERR_TOOMANYINITIALISERS, "Too many initializers"); - continue; - } - if (!def->constant) - QCC_PR_ParseError(0, "Initialised functions must be constant"); - - def->references++; - pr_scope = def; - f = QCC_PR_ParseImmediateStatements (type); - pr_scope = NULL; - def->initialized = 1; - G_FUNCTION(def->ofs) = numfunctions; - f->def = def; -// if (pr_dumpasm) -// PR_PrintFunction (def); - - // fill in the dfunction - df = &functions[numfunctions]; - numfunctions++; - if (f->builtin) - df->first_statement = -f->builtin; - else - df->first_statement = f->code; - - if (f->builtin && opt_function_names) - optres_function_names += strlen(f->def->name); - else - df->s_name = QCC_CopyString (f->def->name); - df->s_file = s_file2; - df->numparms = f->def->type->num_parms; - df->locals = locals_end - locals_start; - df->parm_start = locals_start; - for (i=0,parm = type->param ; inumparms ; i++, parm = parm->next) - { - df->parm_size[i] = parm->size; - } - - continue; - } - - else if (type->type == ev_struct) - { - int arraypart, partnum; - QCC_type_t *parttype; - def->initialized = 1; - if (isvar) - def->constant = true; - else - def->constant = false; -// if (constant) -// QCC_PR_ParseError("const used on a struct isn't useful"); - - //FIXME: should do this recursivly - QCC_PR_Expect("{"); - for (arraypart = 0; arraypart < arraysize; arraypart++) - { - parttype = type->param; - QCC_PR_Expect("{"); - for (partnum = 0; partnum < type->num_parms; partnum++) - { - switch (parttype->type) - { - case ev_float: - case ev_integer: - case ev_vector: - if (pr_token_type == tt_punct) - { - if (QCC_PR_CheckToken("{")) - { - QCC_PR_Expect("}"); - } - else - QCC_PR_ParseError(ERR_UNEXPECTEDPUNCTUATION, "Unexpected punctuation"); - - } - else if (pr_token_type == tt_immediate) - { - if (pr_immediate_type->type == ev_float && parttype->type == ev_integer) - G_INT(def->ofs + arraypart*type->size + parttype->ofs) = (int)pr_immediate._float; - else if (pr_immediate_type->type != parttype->type) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate subtype for %s.%s", def->name, parttype->name); - else - memcpy (qcc_pr_globals + def->ofs + arraypart*type->size + parttype->ofs, &pr_immediate, 4*type_size[pr_immediate_type->type]); - } - else if (pr_token_type == tt_name) - { - d = QCC_PR_GetDef(NULL, pr_token, pr_scope, false, 0, false); - if (!d) - QCC_PR_ParseError(ERR_NOTDEFINED, "%s was not defined\n", pr_token); - else if (d->type->type != parttype->type) - QCC_PR_ParseError (ERR_WRONGSUBTYPE, "wrong subtype for %s.%s", def->name, parttype->name); - else if (!d->constant) - QCC_PR_ParseError(ERR_NOTACONSTANT, "%s isn't a constant\n", pr_token); - - memcpy (qcc_pr_globals + def->ofs + arraypart*type->size + parttype->ofs, qcc_pr_globals + d->ofs, 4*d->type->size); - } - else - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate subtype for %s.%s", def->name, parttype->name); - QCC_PR_Lex (); - - break; - case ev_string: - if (pr_token_type == tt_punct) - { - if (QCC_PR_CheckToken("{")) - { - unsigned int i; - for (i = 0; i < parttype->size; i++) - { -/* //the executor defines strings as true c strings, but reads in index from string table. - //structures can hide these strings. - d = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - d->next = NULL; - pr.def_tail->next = d; - pr.def_tail = d; - - d->type = parttype; - d->name = "STRUCTIMMEDIATE"; - d->constant = constant; - d->initialized = 1; - d->scope = NULL; - - d->ofs = def->ofs+arraypart*type->size+parttype->ofs+i; -*/ - G_INT(def->ofs+arraypart*type->size+parttype->ofs+i) = QCC_CopyString(pr_immediate_string); - QCC_PR_Lex (); - - if (!QCC_PR_CheckToken(",")) - { - i++; - break; - } - } - for (; i < parttype->size; i++) - { -/* //the executor defines strings as true c strings, but reads in index from string table. - //structures can hide these strings. - d = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - d->next = NULL; - pr.def_tail->next = d; - pr.def_tail = d; - - d->type = parttype; - d->name = "STRUCTIMMEDIATE"; - d->constant = constant; - d->initialized = 1; - d->scope = NULL; - - d->ofs = def->ofs+arraypart*type->size+parttype->ofs+i; -*/ - G_INT(def->ofs+arraypart*type->size+parttype->ofs+i) = 0; - } - QCC_PR_Expect("}"); - } - else - QCC_PR_ParseError(ERR_UNEXPECTEDPUNCTUATION, "Unexpected punctuation"); - } - else - { -/* //the executor defines strings as true c strings, but reads in index from string table. - //structures can hide these strings. - d = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - d->next = NULL; - pr.def_tail->next = d; - pr.def_tail = d; - - d->type = parttype; - d->name = "STRUCTIMMEDIATE"; - d->constant = constant; - d->initialized = 1; - d->scope = NULL; - - d->ofs = def->ofs+arraypart*type->size+parttype->ofs; -*/ - G_INT(def->ofs+arraypart*type->size+parttype->ofs) = QCC_CopyString(pr_immediate_string); - QCC_PR_Lex (); - } - break; - case ev_function: - if (pr_token_type == tt_immediate) - { - if (pr_immediate._int != 0) - QCC_PR_ParseError(ERR_NOTFUNCTIONTYPE, "Expected function name or NULL"); - G_FUNCTION(def->ofs+arraypart*type->size+parttype->ofs) = 0; - QCC_PR_Lex(); - } - else - { - name = QCC_PR_ParseName (); - - d = QCC_PR_GetDef (NULL, name, pr_scope, false, 0, false); - if (!d) - QCC_PR_ParseError(ERR_NOTDEFINED, "%s was not defined\n", name); - else - G_FUNCTION(def->ofs+arraypart*type->size+parttype->ofs) = G_FUNCTION(d->ofs); - } - break; - default: - QCC_PR_ParseError(ERR_TYPEINVALIDINSTRUCT, "type %i not valid in a struct", parttype->type); - QCC_PR_Lex(); - break; - } - if (!QCC_PR_CheckToken(",")) - break; - - parttype=parttype->next; - } - QCC_PR_Expect("}"); - if (!QCC_PR_CheckToken(",")) - break; - } - QCC_PR_Expect("}"); - continue; - } - - else if (type->type == ev_integer) //handle these differently, because they may need conversions - { - if (isvar) - def->constant = false; - else - def->constant = true; - - def->initialized = 1; - memcpy (qcc_pr_globals + def->ofs, &pr_immediate, 4*type_size[pr_immediate_type->type]); - QCC_PR_Lex (); - - if (pr_immediate_type->type == ev_float) - G_INT(def->ofs) = (int)pr_immediate._float; - else if (pr_immediate_type->type != ev_integer) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s", name); - - continue; - } - else if (type->type == ev_string) - { - int dotranslate = 0; - char buf[64]; - if (!strcmp(pr_token, "_")) - { - dotranslate = 1; - QCC_PR_Lex(); - } - if(dotranslate) - QCC_PR_Expect("("); - - if (arraysize>=1 && QCC_PR_CheckToken("{")) - { - int i; - for (i = 0; i < arraysize; i++) - { - int dotranslate2; - - //the executor defines strings as true c strings, but reads in index from string table. - //structures can hide these strings. - if (i != 0) //not for the first entry - already a string def for that - { - d = (void *)qccHunkAlloc (sizeof(QCC_def_t)); - d->next = NULL; - pr.def_tail->next = d; - pr.def_tail = d; - - d->name = "IMMEDIATE"; - d->type = type_string; - if (isvar) - d->constant = false; - else - d->constant = true; - d->initialized = 1; - d->scope = NULL; - - d->ofs = def->ofs+i; - if (d->ofs >= MAX_REGS) - QCC_Error(ERR_TOOMANYGLOBALS, "MAX_REGS is too small"); - } - - if (!strcmp(pr_token, "_")) - { - dotranslate2 = 1; - QCC_PR_Lex(); - } - if(dotranslate2) - QCC_PR_Expect("("); - - if(dotranslate || dotranslate2) - { - sprintf(buf, "dotranslate_%d", ++dotranslate_count); - d->name = strdup(buf); - } - - (((int *)qcc_pr_globals)[def->ofs+i]) = QCC_CopyString(pr_immediate_string); - QCC_PR_Lex (); - - if(dotranslate2) - QCC_PR_Expect(")"); - - if (!QCC_PR_CheckToken(",")) - break; - } - QCC_PR_Expect("}"); - } - else if (arraysize<=1) - { - if (isvar) - def->constant = false; - else - def->constant = true; - def->initialized = 1; - (((int *)qcc_pr_globals)[def->ofs]) = QCC_CopyString(pr_immediate_string); - QCC_PR_Lex (); - - if(dotranslate) - { - sprintf(buf, "dotranslate_%d", ++dotranslate_count); - def->name = strdup(buf); - } - - if (pr_immediate_type->type == ev_float) - G_INT(def->ofs) = (int)pr_immediate._float; - else if (pr_immediate_type->type != ev_string) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s", name); - } - else - QCC_PR_ParseError(ERR_ARRAYNEEDSBRACES, "Array initialisation requires curly brasces"); - - if(dotranslate) - QCC_PR_Expect(")"); - continue; - } - else if (type->type == ev_float) - { - if (arraysize>=1 && QCC_PR_CheckToken("{")) - { - int i; - for (i = 0; i < arraysize; i++) - { - if (pr_immediate_type->type != ev_float) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s", name); - (((float *)qcc_pr_globals)[def->ofs+i]) = pr_immediate._float; - QCC_PR_Lex (); - - if (!QCC_PR_CheckToken(",")) - break; - } - QCC_PR_Expect("}"); - - continue; - } - else if (arraysize<=1) - { - if (isvar) - def->constant = false; - else - def->constant = true; - - def->initialized = 1; - - if (pr_immediate_type->type != ev_float) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s", name); - - if (def->constant && opt_dupconstdefs) - { - if (def->ofs == oldglobals) - { - if (Hash_GetKey(&floatconstdefstable, *(int*)&pr_immediate._float)) - optres_dupconstdefs++; - QCC_FreeOffset(def->ofs, def->type->size); - d = QCC_MakeFloatDef(pr_immediate._float); - d->references++; - def->ofs = d->ofs; - QCC_PR_Lex(); - continue; - } - } - - (((float *)qcc_pr_globals)[def->ofs]) = pr_immediate._float; - QCC_PR_Lex (); - - continue; - } - else - QCC_PR_ParseError(ERR_ARRAYNEEDSBRACES, "Array initialisation requires curly brasces"); - } - else if (type->type == ev_vector) - { - if (arraysize>=1 && QCC_PR_CheckToken("{")) - { - int i; - for (i = 0; i < arraysize; i++) - { - if (pr_immediate_type->type != ev_vector) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s", name); - (((float *)qcc_pr_globals)[def->ofs+i*3+0]) = pr_immediate.vector[0]; - (((float *)qcc_pr_globals)[def->ofs+i*3+1]) = pr_immediate.vector[1]; - (((float *)qcc_pr_globals)[def->ofs+i*3+2]) = pr_immediate.vector[2]; - QCC_PR_Lex (); - - if (!QCC_PR_CheckToken(",")) - break; - } - QCC_PR_Expect("}"); - - continue; - } - else if (arraysize<=1) - { - if (isvar) - def->constant = false; - else - def->constant = true; - def->initialized = 1; - - if (pr_immediate_type->type != ev_vector) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s", name); - (((float *)qcc_pr_globals)[def->ofs+0]) = pr_immediate.vector[0]; - (((float *)qcc_pr_globals)[def->ofs+1]) = pr_immediate.vector[1]; - (((float *)qcc_pr_globals)[def->ofs+2]) = pr_immediate.vector[2]; - QCC_PR_Lex (); - - continue; - } - else - QCC_PR_ParseError(ERR_ARRAYNEEDSBRACES, "Array initialisation requires curly brasces"); - } - else if (pr_token_type == tt_name) - { -// if (pr_scope)//create a new instance, emit a copy op -// { -// QCC_PR_ParseError ("name defined for local : %s", name); -// } -// else - { - d = QCC_PR_GetDef (NULL, pr_token, pr_scope, false, 0, false); - if (!d) - QCC_PR_ParseError (ERR_NOTDEFINED, "initialisation name not defined : %s", pr_token); - if (!d->constant) - { - QCC_PR_ParseWarning (WARN_NOTCONSTANT, "initialisation name not a constant : %s", pr_token); - QCC_PR_ParsePrintDef(WARN_NOTCONSTANT, d); - } - memcpy (def, d, sizeof(*d)); - def->name = name; - def->initialized = true; - } - } - else if (pr_token_type != tt_immediate) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "not an immediate for %s - %s", name, pr_token); - else if (pr_immediate_type->type != type->type) - QCC_PR_ParseError (ERR_BADIMMEDIATETYPE, "wrong immediate type for %s - %s", name, pr_token); - else - memcpy (qcc_pr_globals + def->ofs, &pr_immediate, 4*type_size[pr_immediate_type->type]); - - if (isvar) - def->constant = false; - else - def->constant = true; - def->initialized = true; - QCC_PR_Lex (); - } - else - { - if (type->type == ev_function && isvar) - { - isconstant = !isvar; - def->initialized = 1; - } - - if (isconstant && type->type == ev_field) - def->constant = 2; //special flag on fields, 2, makes the pointer obtained from them also constant. - else - def->constant = isconstant; - } - - - } while (QCC_PR_CheckToken (",")); - - if (type->type == ev_function) - QCC_PR_CheckToken (";"); - else - { - if (!QCC_PR_CheckToken (";")) - QCC_PR_ParseWarning(WARN_UNDESIRABLECONVENTION, "Missing semicolon at end of definition"); - } -} - -/* -============ -PR_CompileFile - -compiles the 0 terminated text, adding defintions to the pr structure -============ -*/ -pbool QCC_PR_CompileFile (char *string, char *filename) -{ - jmp_buf oldjb; - if (!pr.memory) - QCC_Error (ERR_INTERNAL, "PR_CompileFile: Didn't clear"); - - QCC_PR_ClearGrabMacros (); // clear the frame macros - - compilingfile = filename; - - if (opt_filenames) - { - optres_filenames += strlen(filename); - pr_file_p = qccHunkAlloc(strlen(filename)+1); - strcpy(pr_file_p, filename); - s_file = pr_file_p - strings; - s_file2 = 0; - } - else - { - s_file = s_file2 = QCC_CopyString (filename); - } - pr_file_p = string; - - pr_source_line = 0; - - memcpy(&oldjb, &pr_parse_abort, sizeof(oldjb)); - - if( setjmp( pr_parse_abort ) ) { - // dont count it as error - } else { - //clock up the first line - QCC_PR_NewLine (false); - - QCC_PR_Lex (); // read first token - } - - while (pr_token_type != tt_eof) - { - if (setjmp(pr_parse_abort)) - { - if (++pr_error_count > MAX_ERRORS) - { - memcpy(&pr_parse_abort, &oldjb, sizeof(oldjb)); - return false; - } - num_continues = 0; - num_breaks = 0; - num_cases = 0; - QCC_PR_SkipToSemicolon (); - if (pr_token_type == tt_eof) - { - memcpy(&pr_parse_abort, &oldjb, sizeof(oldjb)); - return false; - } - } - - pr_scope = NULL; // outside all functions - - QCC_PR_ParseDefs (NULL); - } - memcpy(&pr_parse_abort, &oldjb, sizeof(oldjb)); - - return (pr_error_count == 0); -} - -pbool QCC_Include(char *filename) -{ - char *newfile; - char fname[512]; - char *opr_file_p; - QCC_string_t os_file, os_file2; - int opr_source_line; - char *ocompilingfile; - struct qcc_includechunk_s *oldcurrentchunk; - extern struct qcc_includechunk_s *currentchunk; - - ocompilingfile = compilingfile; - os_file = s_file; - os_file2 = s_file2; - opr_source_line = pr_source_line; - opr_file_p = pr_file_p; - oldcurrentchunk = currentchunk; - - strcpy(fname, filename); - QCC_LoadFile(fname, (void*)&newfile); - currentchunk = NULL; - pr_file_p = newfile; - QCC_PR_CompileFile(newfile, fname); - currentchunk = oldcurrentchunk; - - compilingfile = ocompilingfile; - s_file = os_file; - s_file2 = os_file2; - pr_source_line = opr_source_line; - pr_file_p = opr_file_p; - -// QCC_PR_IncludeChunk(newfile, false, fname); - - return true; -} - -#endif diff --git a/misc/mediasource/extra/fteqcc-src/qcc_pr_lex.c b/misc/mediasource/extra/fteqcc-src/qcc_pr_lex.c deleted file mode 100644 index 286da96f..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcc_pr_lex.c +++ /dev/null @@ -1,3542 +0,0 @@ -#ifndef MINIMAL - -#include "qcc.h" -#ifdef QCC -#define print printf -#endif -#include "time.h" - -#define MEMBERFIELDNAME "__m%s" - -#define STRCMP(s1,s2) (((*s1)!=(*s2)) || strcmp(s1+1,s2+1)) //saves about 2-6 out of 120 - expansion of idea from fastqcc - -void QCC_PR_ConditionCompilation(void); -pbool QCC_PR_UndefineName(char *name); -char *QCC_PR_CheakCompConstString(char *def); -CompilerConstant_t *QCC_PR_CheckCompConstDefined(char *def); -pbool QCC_Include(char *filename); - -char *compilingfile; - -int pr_source_line; - -char *pr_file_p; -char *pr_line_start; // start of current source line - -int pr_bracelevel; - -char pr_token[8192]; -token_type_t pr_token_type; -QCC_type_t *pr_immediate_type; -QCC_eval_t pr_immediate; - -char pr_immediate_string[8192]; - -int pr_error_count; -int pr_warning_count; - - -CompilerConstant_t *CompilerConstant; -int numCompilerConstants; -extern pbool expandedemptymacro; - - - -char *pr_punctuation[] = -// longer symbols must be before a shorter partial match -{"&&", "||", "<=", ">=","==", "!=", "/=", "*=", "+=", "-=", "(+)", "(-)", "|=", "&~=", "++", "--", "->", "::", ";", ",", "!", "*", "/", "(", ")", "-", "+", "=", "[", "]", "{", "}", "...", "..", ".", "<<", "<", ">>", ">" , "?", "#" , "@", "&" , "|", "^", ":", NULL}; - -char *pr_punctuationremap[] = //a nice bit of evilness. -//(+) -> |= -//-> -> . -//(-) -> &~= -{"&&", "||", "<=", ">=","==", "!=", "/=", "*=", "+=", "-=", "|=", "&~=", "|=", "&~=", "++", "--", ".", "::", ";", ",", "!", "*", "/", "(", ")", "-", "+", "=", "[", "]", "{", "}", "...", "..", ".", "<<", "<", ">>", ">" , "?", "#" , "@", "&" , "|", "^", ":", NULL}; - -// simple types. function types are dynamically allocated -QCC_type_t *type_void;// = {ev_void/*, &def_void*/}; -QCC_type_t *type_string;// = {ev_string/*, &def_string*/}; -QCC_type_t *type_float;// = {ev_float/*, &def_float*/}; -QCC_type_t *type_vector;// = {ev_vector/*, &def_vector*/}; -QCC_type_t *type_entity;// = {ev_entity/*, &def_entity*/}; -QCC_type_t *type_field;// = {ev_field/*, &def_field*/}; -QCC_type_t *type_function;// = {ev_function/*, &def_function*/,NULL,&type_void}; -// type_function is a void() function used for state defs -QCC_type_t *type_pointer;// = {ev_pointer/*, &def_pointer*/}; -QCC_type_t *type_integer;// = {ev_integer/*, &def_integer*/}; -QCC_type_t *type_variant;// = {ev_integer/*, &def_integer*/}; - -QCC_type_t *type_floatfield;// = {ev_field/*, &def_field*/, NULL, &type_float}; - -/*QCC_def_t def_void = {type_void, "temp"}; -QCC_def_t def_string = {type_string, "temp"}; -QCC_def_t def_float = {type_float, "temp"}; -QCC_def_t def_vector = {type_vector, "temp"}; -QCC_def_t def_entity = {type_entity, "temp"}; -QCC_def_t def_field = {type_field, "temp"}; -QCC_def_t def_function = {type_function, "temp"}; -QCC_def_t def_pointer = {type_pointer, "temp"}; -QCC_def_t def_integer = {type_integer, "temp"}; -*/ -QCC_def_t def_ret, def_parms[MAX_PARMS]; - -//QCC_def_t *def_for_type[9] = {&def_void, &def_string, &def_float, &def_vector, &def_entity, &def_field, &def_function, &def_pointer, &def_integer}; - -void QCC_PR_LexWhitespace (void); - - - - -//for compiler constants and file includes. - -typedef struct qcc_includechunk_s { - struct qcc_includechunk_s *prev; - char *filename; - char *currentdatapoint; - int currentlinenumber; - CompilerConstant_t *cnst; -} qcc_includechunk_t; -qcc_includechunk_t *currentchunk; -void QCC_PR_IncludeChunkEx (char *data, pbool duplicate, char *filename, CompilerConstant_t *cnst) -{ - qcc_includechunk_t *chunk = qccHunkAlloc(sizeof(qcc_includechunk_t)); - chunk->prev = currentchunk; - currentchunk = chunk; - - chunk->currentdatapoint = pr_file_p; - chunk->currentlinenumber = pr_source_line; - chunk->cnst = cnst; - if( cnst ) - { - cnst->inside++; - } - - if (duplicate) - { - pr_file_p = qccHunkAlloc(strlen(data)+1); - strcpy(pr_file_p, data); - } - else - pr_file_p = data; -} -void QCC_PR_IncludeChunk (char *data, pbool duplicate, char *filename) -{ - QCC_PR_IncludeChunkEx(data, duplicate, filename, NULL); -} - -pbool QCC_PR_UnInclude(void) -{ - if (!currentchunk) - return false; - - if( currentchunk->cnst ) - currentchunk->cnst->inside--; - - pr_file_p = currentchunk->currentdatapoint; - pr_source_line = currentchunk->currentlinenumber; - - currentchunk = currentchunk->prev; - - return true; -} - - -/* -============== -PR_PrintNextLine -============== -*/ -void QCC_PR_PrintNextLine (void) -{ - char *t; - - printf ("%3i:",pr_source_line); - for (t=pr_line_start ; *t && *t != '\n' ; t++) - printf ("%c",*t); - printf ("\n"); -} - -extern char qccmsourcedir[]; -//also meant to include it. -void QCC_FindBestInclude(char *newfile, char *currentfile, char *rootpath) -{ - char fullname[10248]; - char *stripfrom; - int doubledots; - - char *end = fullname; - - if (!*newfile) - return; - - doubledots = 0; - while(!strncmp(newfile, "../", 3) || !strncmp(newfile, "..\\", 3)) - { - newfile+=3; - doubledots++; - } - - currentfile += strlen(rootpath); //could this be bad? - - for(stripfrom = currentfile+strlen(currentfile)-1; stripfrom>currentfile; stripfrom--) - { - if (*stripfrom == '/' || *stripfrom == '\\') - { - if (doubledots>0) - doubledots--; - else - { - stripfrom++; - break; - } - } - } - strcpy(end, rootpath); end = end+strlen(end); - if (*fullname && end[-1] != '/') - { - strcpy(end, "/"); - end = end+strlen(end); - } - strncpy(end, currentfile, stripfrom - currentfile); end += stripfrom - currentfile; *end = '\0'; - strcpy(end, newfile); - - QCC_Include(fullname); -} - -pbool defaultstatic; -int ForcedCRC; -int QCC_PR_LexInteger (void); -void QCC_AddFile (char *filename); -void QCC_PR_LexString (void); -pbool QCC_PR_SimpleGetToken (void); - -int ParsePrecompilerIf(void) -{ - CompilerConstant_t *c; - int eval; - char *start = pr_file_p; - if (!QCC_PR_SimpleGetToken()) - { - if (*pr_file_p == '(') - { - eval = ParsePrecompilerIf(); - while (*pr_file_p == ' ' || *pr_file_p == '\t') - pr_file_p++; - if (*pr_file_p != ')') - QCC_PR_ParseError(ERR_EXPECTED, "unclosed bracket condition\n"); - } - else - QCC_PR_ParseError(ERR_EXPECTED, "expected bracket or constant\n"); - } - else if (!strcmp(pr_token, "defined")) - { - while (*pr_file_p == ' ' || *pr_file_p == '\t') - pr_file_p++; - if (*pr_file_p != '(') - QCC_PR_ParseError(ERR_EXPECTED, "no opening bracket after defined\n"); - else - { - pr_file_p++; - - QCC_PR_SimpleGetToken(); - eval = !!QCC_PR_CheckCompConstDefined(pr_token); - - while (*pr_file_p == ' ' || *pr_file_p == '\t') - pr_file_p++; - if (*pr_file_p != ')') - QCC_PR_ParseError(ERR_EXPECTED, "unclosed defined condition\n"); - pr_file_p++; - } - } - else - { - c = QCC_PR_CheckCompConstDefined(pr_token); - if (!c) - eval = atoi(pr_token); - else - eval = atoi(c->value); - } - - QCC_PR_SimpleGetToken(); - if (!strcmp(pr_token, "||")) - eval = ParsePrecompilerIf()||eval; - else if (!strcmp(pr_token, "&&")) - eval = ParsePrecompilerIf()&&eval; - else if (!strcmp(pr_token, "<=")) - eval = eval <= ParsePrecompilerIf(); - else if (!strcmp(pr_token, ">=")) - eval = eval >= ParsePrecompilerIf(); - else if (!strcmp(pr_token, "<")) - eval = eval < ParsePrecompilerIf(); - else if (!strcmp(pr_token, ">")) - eval = eval > ParsePrecompilerIf(); - else if (!strcmp(pr_token, "!=")) - eval = eval != ParsePrecompilerIf(); - - return eval; -} -/* -============== -QCC_PR_Precompiler -============== - -Runs precompiler stage -*/ -pbool QCC_PR_Precompiler(void) -{ - char msg[1024]; - int ifmode; - int a; - static int ifs = 0; - int level; //#if level - pbool eval = false; - - if (*pr_file_p == '#') - { - char *directive; - for (directive = pr_file_p+1; *directive; directive++) //so # define works - { - if (*directive == '\r' || *directive == '\n') - QCC_PR_ParseError(ERR_UNKNOWNPUCTUATION, "Hanging # with no directive\n"); - if (*directive > ' ') - break; - } - if (!strncmp(directive, "define", 6)) - { - pr_file_p = directive; - QCC_PR_ConditionCompilation(); - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - else if (!strncmp(directive, "undef", 5)) - { - pr_file_p = directive+5; - while(*pr_file_p <= ' ') - pr_file_p++; - - QCC_PR_SimpleGetToken (); - QCC_PR_UndefineName(pr_token); - - // QCC_PR_ConditionCompilation(); - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - else if (!strncmp(directive, "if", 2)) - { - int originalline = pr_source_line; - pr_file_p = directive+2; - if (!strncmp(pr_file_p, "def ", 4)) - { - ifmode = 0; - pr_file_p+=4; - } - else if (!strncmp(pr_file_p, "ndef ", 5)) - { - ifmode = 1; - pr_file_p+=5; - } - else - { - ifmode = 2; - pr_file_p+=0; - //QCC_PR_ParseError("bad \"#if\" type"); - } - - if (ifmode == 2) - { - eval = ParsePrecompilerIf(); - - if(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - QCC_PR_ParseError (ERR_NOENDIF, "junk on the end of #if line"); - } - } - else - { - QCC_PR_SimpleGetToken (); - - // if (!STRCMP(pr_token, "COOP_MODE")) - // eval = false; - if (QCC_PR_CheckCompConstDefined(pr_token)) - eval = true; - - if (ifmode == 1) - eval = eval?false:true; - } - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - level = 1; - - if (eval) - ifs+=1; - else - { - while (1) - { - while(*pr_file_p && (*pr_file_p==' ' || *pr_file_p == '\t')) - pr_file_p++; - - if (!*pr_file_p) - { - pr_source_line = originalline; - QCC_PR_ParseError (ERR_NOENDIF, "#if with no endif"); - } - - if (*pr_file_p == '#') - { - pr_file_p++; - while(*pr_file_p==' ' || *pr_file_p == '\t') - pr_file_p++; - if (!strncmp(pr_file_p, "endif", 5)) - level--; - if (!strncmp(pr_file_p, "if", 2)) - level++; - if (!strncmp(pr_file_p, "else", 4) && level == 1) - { - ifs+=1; - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - break; - } - } - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - if (level <= 0) - break; - pr_file_p++; //next line - pr_source_line++; - } - } - } - else if (!strncmp(directive, "else", 4)) - { - int originalline = pr_source_line; - - ifs -= 1; - level = 1; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - while (1) - { - while(*pr_file_p && (*pr_file_p==' ' || *pr_file_p == '\t')) - pr_file_p++; - - if (!*pr_file_p) - { - pr_source_line = originalline; - QCC_PR_ParseError(ERR_NOENDIF, "#if with no endif"); - } - - if (*pr_file_p == '#') - { - pr_file_p++; - while(*pr_file_p==' ' || *pr_file_p == '\t') - pr_file_p++; - - if (!strncmp(pr_file_p, "endif", 5)) - level--; - if (!strncmp(pr_file_p, "if", 2)) - level++; - if (!strncmp(pr_file_p, "else", 4) && level == 1) - { - ifs+=1; - break; - } - } - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - if (level <= 0) - break; - pr_file_p++; //go off the end - pr_source_line++; - } - } - else if (!strncmp(directive, "endif", 5)) - { - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - if (ifs <= 0) - QCC_PR_ParseError(ERR_NOPRECOMPILERIF, "unmatched #endif"); - else - ifs-=1; - } - else if (!strncmp(directive, "eof", 3)) - { - pr_file_p = NULL; - return true; - } - else if (!strncmp(directive, "error", 5)) - { - pr_file_p = directive+5; - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line, yes, I KNOW we are going to register an error, and not properly leave this function tree, but... - { - pr_file_p++; - } - - QCC_PR_ParseError(ERR_HASHERROR, "#Error: %s", msg); - } - else if (!strncmp(directive, "warning", 7)) - { - pr_file_p = directive+7; - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - - QCC_PR_ParseWarning(WARN_PRECOMPILERMESSAGE, "#warning: %s", msg); - } - else if (!strncmp(directive, "message", 7)) - { - pr_file_p = directive+7; - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - - printf("#message: %s\n", msg); - } - else if (!strncmp(directive, "copyright", 9)) - { - pr_file_p = directive+9; - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - - if (strlen(msg) >= sizeof(QCC_copyright)) - QCC_PR_ParseWarning(WARN_STRINGTOOLONG, "Copyright message is too long\n"); - strncpy(QCC_copyright, msg, sizeof(QCC_copyright)-1); - } - else if (!strncmp(directive, "pack", 4)) - { - ifmode = 0; - pr_file_p=directive+4; - if (!strncmp(pr_file_p, "id", 2)) - pr_file_p+=3; - else - { - ifmode = QCC_PR_LexInteger(); - if (ifmode == 0) - ifmode = 1; - pr_file_p++; - } - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - - if (ifmode == 0) - QCC_packid = atoi(msg); - else if (ifmode <= 5) - strcpy(QCC_Packname[ifmode-1], msg); - else - QCC_PR_ParseError(ERR_TOOMANYPACKFILES, "No more than 5 packs are allowed"); - } - else if (!strncmp(directive, "forcecrc", 8)) - { - pr_file_p=directive+8; - - ForcedCRC = QCC_PR_LexInteger(); - - pr_file_p++; - - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - else if (!strncmp(directive, "includelist", 11)) - { - pr_file_p=directive+11; - - while(*pr_file_p <= ' ') - pr_file_p++; - - while(1) - { - QCC_PR_LexWhitespace(); - if (!QCC_PR_SimpleGetToken()) - { - if (!*pr_file_p) - QCC_Error(ERR_EOF, "eof in includelist"); - else - { - pr_file_p++; - pr_source_line++; - } - continue; - } - if (!strcmp(pr_token, "#endlist")) - break; - - QCC_FindBestInclude(pr_token, compilingfile, qccmsourcedir); - - if (*pr_file_p == '\r') - pr_file_p++; - - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - else if (!strncmp(directive, "include", 7)) - { - char sm; - - pr_file_p=directive+7; - - while(*pr_file_p <= ' ') - pr_file_p++; - - msg[0] = '\0'; - if (*pr_file_p == '\"') - sm = '\"'; - else if (*pr_file_p == '<') - sm = '>'; - else - { - QCC_PR_ParseError(0, "Not a string literal (on a #include)"); - sm = 0; - } - pr_file_p++; - a=0; - while(*pr_file_p != sm) - { - if (*pr_file_p == '\n') - { - QCC_PR_ParseError(0, "#include continued over line boundy\n"); - break; - } - msg[a++] = *pr_file_p; - pr_file_p++; - } - msg[a] = 0; - - QCC_FindBestInclude(msg, compilingfile, qccmsourcedir); - - pr_file_p++; - - while(*pr_file_p != '\n' && *pr_file_p != '\0' && *pr_file_p <= ' ') - pr_file_p++; - - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - else if (!strncmp(directive, "datafile", 8)) - { - pr_file_p=directive+8; - - while(*pr_file_p <= ' ') - pr_file_p++; - - QCC_PR_LexString(); - printf("Including datafile: %s\n", pr_token); - QCC_AddFile(pr_token); - - pr_file_p++; - - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - else if (!strncmp(directive, "output", 6)) - { - extern char destfile[1024]; - pr_file_p=directive+6; - - while(*pr_file_p <= ' ') - pr_file_p++; - - QCC_PR_LexString(); - strcpy(destfile, pr_token); - printf("Outputfile: %s\n", destfile); - - pr_file_p++; - - for (a = 0; a < 1023 && pr_file_p[a] != '\n' && pr_file_p[a] != '\0'; a++) - msg[a] = pr_file_p[a]; - - msg[a-1] = '\0'; - - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - { - pr_file_p++; - } - } - else if (!strncmp(directive, "pragma", 6)) - { - pr_file_p=directive+6; - while(*pr_file_p <= ' ') - pr_file_p++; - - qcc_token[0] = '\0'; - for(a = 0; *pr_file_p != '\n' && *pr_file_p != '\0'; pr_file_p++) //read on until the end of the line - { - if ((*pr_file_p == ' ' || *pr_file_p == '\t'|| *pr_file_p == '(') && !*qcc_token) - { - msg[a] = '\0'; - strcpy(qcc_token, msg); - a=0; - continue; - } - msg[a++] = *pr_file_p; - } - - msg[a] = '\0'; - { - char *end; - for (end = msg + a-1; end>=msg && *end <= ' '; end--) - *end = '\0'; - } - - if (!*qcc_token) - { - strcpy(qcc_token, msg); - msg[0] = '\0'; - } - - { - char *end; - for (end = msg + a-1; end>=msg && *end <= ' '; end--) - *end = '\0'; - } - - if (!QC_strcasecmp(qcc_token, "DONT_COMPILE_THIS_FILE")) - { - while (*pr_file_p) - { - while(*pr_file_p != '\n' && *pr_file_p != '\0') //read on until the end of the line - pr_file_p++; - - if (*pr_file_p == '\n') - { - pr_file_p++; - QCC_PR_NewLine(false); - } - } - } - else if (!QC_strcasecmp(qcc_token, "COPYRIGHT")) - { - if (strlen(msg) >= sizeof(QCC_copyright)) - QCC_PR_ParseWarning(WARN_STRINGTOOLONG, "Copyright message is too long\n"); - strncpy(QCC_copyright, msg, sizeof(QCC_copyright)-1); - } - else if (!strncmp(qcc_token, "compress", 8)) - { - extern pbool compressoutput; - compressoutput = atoi(msg); - } - else if (!strncmp(qcc_token, "forcecrc", 8)) - { - ForcedCRC = atoi(msg); - } - else if (!strncmp(qcc_token, "defaultstatic", 13)) - { - defaultstatic = atoi(msg); - } - else if (!strncmp(qcc_token, "sourcefile", 10)) - { - #define MAXSOURCEFILESLIST 8 - extern char sourcefileslist[MAXSOURCEFILESLIST][1024]; - extern int currentsourcefile; - extern int numsourcefiles; - - int i; - - QCC_COM_Parse(msg); - - for (i = 0; i < numsourcefiles; i++) - { - if (!strcmp(sourcefileslist[i], qcc_token)) - break; - } - if (i == numsourcefiles) - strcpy(sourcefileslist[numsourcefiles++], qcc_token); - } - else if (!QC_strcasecmp(qcc_token, "TARGET")) - { - if (qcc_targetformat == QCF_HEXEN2 && numstatements) - QCC_PR_ParseWarning(WARN_BADTARGET, "Cannot switch from hexen2 target \'%s\'. Ignored.", msg); - else if (!QC_strcasecmp(msg, "H2") || !QC_strcasecmp(msg, "HEXEN2")) - { - if (numstatements) - QCC_PR_ParseWarning(WARN_BADTARGET, "Cannot switch from hexen2 target \'%s\'. Ignored.", msg); - else - qcc_targetformat = QCF_HEXEN2; - } - else if (!QC_strcasecmp(msg, "KK7")) - qcc_targetformat = QCF_KK7; - else if (!QC_strcasecmp(msg, "DP") || !QC_strcasecmp(msg, "DARKPLACES")) - qcc_targetformat = QCF_DARKPLACES; - else if (!QC_strcasecmp(msg, "FTEDEBUG")) - qcc_targetformat = QCF_FTEDEBUG; - else if (!QC_strcasecmp(msg, "FTE")) - qcc_targetformat = QCF_FTE; - else if (!QC_strcasecmp(msg, "STANDARD") || !QC_strcasecmp(msg, "ID")) - qcc_targetformat = QCF_STANDARD; - else if (!QC_strcasecmp(msg, "DEBUG")) - qcc_targetformat = QCF_FTEDEBUG; - else - QCC_PR_ParseWarning(WARN_BADTARGET, "Unknown target \'%s\'. Ignored.", msg); - } - else if (!QC_strcasecmp(qcc_token, "PROGS_SRC")) - { //doesn't make sence, but silenced if you are switching between using a certain precompiler app used with CuTF. - } - else if (!QC_strcasecmp(qcc_token, "PROGS_DAT")) - { //doesn't make sence, but silenced if you are switching between using a certain precompiler app used with CuTF. - extern char destfile[1024]; -#ifndef QCCONLY - extern char qccmfilename[1024]; - int p; - char *s, *s2; -#endif - QCC_COM_Parse(msg); - -#ifndef QCCONLY - p=0; - s2 = qcc_token; - if (!strncmp(s2, "./", 2)) - s2+=2; - else - { - while(!strncmp(s2, "../", 3)) - { - s2+=3; - p++; - } - } - strcpy(qccmfilename, qccmsourcedir); - for (s=qccmfilename+strlen(qccmfilename);p && s>=qccmfilename; s--) - { - if (*s == '/' || *s == '\\') - { - *(s+1) = '\0'; - p--; - } - } - sprintf(destfile, "%s", s2); - - while (p>0) - { - memmove(destfile+3, destfile, strlen(destfile)+1); - destfile[0] = '.'; - destfile[1] = '.'; - destfile[2] = '/'; - p--; - } -#else - - strcpy(destfile, qcc_token); -#endif - printf("Outputfile: %s\n", destfile); - } - else if (!QC_strcasecmp(qcc_token, "keyword") || !QC_strcasecmp(qcc_token, "flag")) - { - char *s; - int st; - s = QCC_COM_Parse(msg); - if (!QC_strcasecmp(qcc_token, "enable") || !QC_strcasecmp(qcc_token, "on")) - st = 1; - else if (!QC_strcasecmp(qcc_token, "disable") || !QC_strcasecmp(qcc_token, "off")) - st = 0; - else - { - QCC_PR_ParseWarning(WARN_BADPRAGMA, "compiler flag state not recognised"); - st = -1; - } - if (st < 0) - QCC_PR_ParseWarning(WARN_BADPRAGMA, "warning id not recognised"); - else - { - int f; - s = QCC_COM_Parse(s); - - for (f = 0; compiler_flag[f].enabled; f++) - { - if (!QC_strcasecmp(compiler_flag[f].abbrev, qcc_token)) - { - if (compiler_flag[f].flags & FLAG_MIDCOMPILE) - *compiler_flag[f].enabled = st; - else - QCC_PR_ParseWarning(WARN_BADPRAGMA, "Cannot enable/disable keyword/flag via a pragma"); - break; - } - } - if (!compiler_flag[f].enabled) - QCC_PR_ParseWarning(WARN_BADPRAGMA, "keyword/flag not recognised"); - - } - } - else if (!QC_strcasecmp(qcc_token, "warning")) - { - int st; - char *s; - s = QCC_COM_Parse(msg); - if (!stricmp(qcc_token, "enable") || !stricmp(qcc_token, "on")) - st = 0; - else if (!stricmp(qcc_token, "disable") || !stricmp(qcc_token, "off")) - st = 1; - else if (!stricmp(qcc_token, "toggle")) - st = 2; - else - { - QCC_PR_ParseWarning(WARN_BADPRAGMA, "warning state not recognised"); - st = -1; - } - if (st>=0) - { - int wn; - s = QCC_COM_Parse(s); - wn = QCC_WarningForName(qcc_token); - if (wn < 0) - QCC_PR_ParseWarning(WARN_BADPRAGMA, "warning id not recognised"); - else - { - if (st == 2) //toggle - qccwarningdisabled[wn] = true - qccwarningdisabled[wn]; - else - qccwarningdisabled[wn] = st; - } - } - } - else - QCC_PR_ParseWarning(WARN_BADPRAGMA, "Unknown pragma \'%s\'", qcc_token); - } - return true; - } - - return false; -} - -/* -============== -PR_NewLine - -Call at start of file and when *pr_file_p == '\n' -============== -*/ -void QCC_PR_NewLine (pbool incomment) -{ - pr_source_line++; - pr_line_start = pr_file_p; - while(*pr_file_p==' ' || *pr_file_p == '\t') - pr_file_p++; - if (incomment) //no constants if in a comment. - { - } - else if (QCC_PR_Precompiler()) - { - } - -// if (pr_dumpasm) -// PR_PrintNextLine (); -} - -/* -============== -PR_LexString - -Parses a quoted string -============== -*/ -#if 0 -void QCC_PR_LexString (void) -{ - int c; - int len; - char tmpbuf[2048]; - - char *text; - char *oldf; - int oldline; - - bool fromfile = true; - - len = 0; - - text = pr_file_p; - do - { - QCC_COM_Parse(text); -// print("Next token is \"%s\"\n", com_token); - if (*text == '\"') - { - text++; - if (fromfile) pr_file_p++; - } - do - { - c = *text++; - if (fromfile) pr_file_p++; - if (!c) - QCC_PR_ParseError ("EOF inside quote"); - if (c=='\n') - QCC_PR_ParseError ("newline inside quote"); - if (c=='\\') - { // escape char - c = *text++; - if (fromfile) pr_file_p++; - if (!c) - QCC_PR_ParseError ("EOF inside quote"); - if (c == 'n') - c = '\n'; - else if (c == '"') - c = '"'; - else if (c == '\\') - c = '\\'; - else - QCC_PR_ParseError ("Unknown escape char"); - } - else if (c=='\"') - { - if (fromfile) pr_file_p++; - break; - } - tmpbuf[len] = c; - len++; - } while (1); - tmpbuf[len] = 0; -// if (fromfile) pr_file_p++; - - pr_immediate_type=NULL; - oldline=pr_source_line; - oldf=pr_file_p; - QCC_PR_Lex(); - if (pr_immediate_type == &type_string) - { -// print("Appending \"%s\" to \"%s\"\n", pr_immediate_string, tmpbuf); - strcat(tmpbuf, pr_immediate_string); - len+=strlen(pr_immediate_string); - } - else - { - pr_source_line = oldline; - pr_file_p = oldf-1; - QCC_PR_LexWhitespace(); - if (*pr_file_p != '\"') //annother string - break; - } - - QCC_PR_LexWhitespace(); - text = pr_file_p; - - } while (1); - - strcpy(pr_token, tmpbuf); - pr_token_type = tt_immediate; - pr_immediate_type = &type_string; - strcpy (pr_immediate_string, pr_token); - -// print("Found \"%s\"\n", pr_immediate_string); -} -#else -void QCC_PR_LexString (void) -{ - int c; - int len; - char *end, *cnst; - - int texttype=0; - - len = 0; - pr_file_p++; - do - { - c = *pr_file_p++; - if (!c) - QCC_PR_ParseError (ERR_EOF, "EOF inside quote"); - if (c=='\n') - QCC_PR_ParseError (ERR_INVALIDSTRINGIMMEDIATE, "newline inside quote"); - if (c=='\\') - { // escape char - c = *pr_file_p++; - if (!c) - QCC_PR_ParseError (ERR_EOF, "EOF inside quote"); - if (c == 'n') - c = '\n'; - else if (c == 'r') - c = '\r'; - else if (c == '"') - c = '"'; - else if (c == 't') - c = '\t'; - else if (c == 'a') - c = '\a'; - else if (c == 'v') - c = '\v'; - else if (c == 'f') - c = '\f'; - else if (c == 's' || c == 'b') - { - texttype ^= 128; - continue; - } - else if (c == '[') - c = 16; - else if (c == ']') - c = 17; - else if (c == '{') - { - int d; - c = 0; - while ((d = *pr_file_p++) != '}') - { - c = c * 10 + d - '0'; - if (d < '0' || d > '9' || c > 255) - QCC_PR_ParseError(ERR_BADCHARACTERCODE, "Bad character code"); - } - } - else if (c == '<') - c = 29; - else if (c == '-') - c = 30; - else if (c == '>') - c = 31; - else if (c == 'x' || c == 'X') - { - int d; - c = 0; - - d = (unsigned char)*pr_file_p++; - if (d >= '0' && d <= '9') - c += d - '0'; - else if (d >= 'A' && d <= 'F') - c += d - 'A' + 10; - else if (d >= 'a' && d <= 'f') - c += d - 'a' + 10; - else - QCC_PR_ParseError(ERR_BADCHARACTERCODE, "Bad character code"); - - c *= 16; - - d = (unsigned char)*pr_file_p++; - if (d >= '0' && d <= '9') - c += d - '0'; - else if (d >= 'A' && d <= 'F') - c += d - 'A' + 10; - else if (d >= 'a' && d <= 'f') - c += d - 'a' + 10; - else - QCC_PR_ParseError(ERR_BADCHARACTERCODE, "Bad character code"); - } - else if (c == '\\') - c = '\\'; - else if (c == '\'') - c = '\''; - else if (c >= '0' && c <= '9') - c = 18 + c - '0'; - else if (c == '\r') - { //sigh - c = *pr_file_p++; - if (c != '\n') - QCC_PR_ParseWarning(WARN_HANGINGSLASHR, "Hanging \\\\\r"); - pr_source_line++; - } - else if (c == '\n') - { //sigh - pr_source_line++; - } - else - QCC_PR_ParseError (ERR_INVALIDSTRINGIMMEDIATE, "Unknown escape char %c", c); - } - else if (c=='\"') - { - if (len >= sizeof(pr_immediate_string)-1) - QCC_Error(ERR_INVALIDSTRINGIMMEDIATE, "String length exceeds %i", sizeof(pr_immediate_string)-1); - - while(*pr_file_p && *pr_file_p <= ' ') - { - if (*pr_file_p == '\n') - { - pr_file_p++; - QCC_PR_NewLine(false); - } - else - pr_file_p++; - } - if (*pr_file_p == '\"') //have annother go - { - pr_file_p++; - continue; - } - pr_token[len] = 0; - pr_token_type = tt_immediate; - pr_immediate_type = type_string; - strcpy (pr_immediate_string, pr_token); - return; - } - else if (c == '#') - { - for (end = pr_file_p; ; end++) - { - if (*end <= ' ') - break; - - if (*end == ')' - || *end == '(' - || *end == '+' - || *end == '-' - || *end == '*' - || *end == '/' - || *end == '\\' - || *end == '|' - || *end == '&' - || *end == '=' - || *end == '^' - || *end == '~' - || *end == '[' - || *end == ']' - || *end == '\"' - || *end == '{' - || *end == '}' - || *end == ';' - || *end == ':' - || *end == ',' - || *end == '.' - || *end == '#') - break; - } - - c = *end; - *end = '\0'; - cnst = QCC_PR_CheakCompConstString(pr_file_p); - if (cnst==pr_file_p) - cnst=NULL; - *end = c; - c = '#'; //undo - if (cnst) - { - QCC_PR_ParseWarning(WARN_MACROINSTRING, "Macro expansion in string"); - - if (len+strlen(cnst) >= sizeof(pr_token)-1) - QCC_Error(ERR_INVALIDSTRINGIMMEDIATE, "String length exceeds %i", sizeof(pr_token)-1); - - strcpy(pr_token+len, cnst); - len+=strlen(cnst); - pr_file_p = end; - continue; - } - } - else if (c == 0x7C && flag_acc) //reacc support... reacc is strange. - c = '\n'; - else - c |= texttype; - - pr_token[len] = c; - len++; - if (len >= sizeof(pr_token)-1) - QCC_Error(ERR_INVALIDSTRINGIMMEDIATE, "String length exceeds %i", sizeof(pr_token)-1); - } while (1); -} -#endif - -/* -============== -PR_LexNumber -============== -*/ -int QCC_PR_LexInteger (void) -{ - int c; - int len; - - len = 0; - c = *pr_file_p; - if (pr_file_p[0] == '0' && pr_file_p[1] == 'x') - { - pr_token[0] = '0'; - pr_token[1] = 'x'; - len = 2; - c = *(pr_file_p+=2); - } - do - { - pr_token[len] = c; - len++; - pr_file_p++; - c = *pr_file_p; - } while ((c >= '0' && c<= '9') || c == '.' || (c>='a' && c <= 'f')); - pr_token[len] = 0; - return atoi (pr_token); -} - -void QCC_PR_LexNumber (void) -{ - int tokenlen = 0; - int num=0; - int base=0; - int c; - int sign=1; - if (*pr_file_p == '-') - { - sign=-1; - pr_file_p++; - - pr_token[tokenlen++] = '-'; - } - if (pr_file_p[0] == '0' && pr_file_p[1] == 'x') - { - pr_file_p+=2; - base = 16; - - pr_token[tokenlen++] = '0'; - pr_token[tokenlen++] = 'x'; - } - - pr_immediate_type = NULL; - //assume base 10 if not stated - if (!base) - base = 10; - - while((c = *pr_file_p)) - { - if (c >= '0' && c <= '9') - { - pr_token[tokenlen++] = c; - num*=base; - num += c-'0'; - } - else if (c >= 'a' && c <= 'f' && base > 10) - { - pr_token[tokenlen++] = c; - num*=base; - num += c -'a'+10; - } - else if (c >= 'A' && c <= 'F' && base > 10) - { - pr_token[tokenlen++] = c; - num*=base; - num += c -'A'+10; - } - else if (c == '.') - { - pr_token[tokenlen++] = c; - pr_file_p++; - pr_immediate_type = type_float; - while(1) - { - c = *pr_file_p; - if (c >= '0' && c <= '9') - { - pr_token[tokenlen++] = c; - } - else if (c == 'f') - { - pr_file_p++; - break; - } - else - { - break; - } - pr_file_p++; - } - pr_token[tokenlen++] = 0; - pr_immediate._float = (float)atof(pr_token); - return; - } - else if (c == 'i') - { - pr_token[tokenlen++] = c; - pr_token[tokenlen++] = 0; - pr_file_p++; - pr_immediate_type = type_integer; - pr_immediate._int = num*sign; - return; - } - else - break; - pr_file_p++; - } - pr_token[tokenlen++] = 0; - - if (!pr_immediate_type) - { - if (flag_assume_integer) - pr_immediate_type = type_integer; - else - pr_immediate_type = type_float; - } - - if (pr_immediate_type == type_integer) - { - pr_immediate_type = type_integer; - pr_immediate._int = num*sign; - } - else - { - pr_immediate_type = type_float; - // at this point, we know there's no . in it, so the NaN bug shouldn't happen - // and we cannot use atof on tokens like 0xabc, so use num*sign, it SHOULD be safe - //pr_immediate._float = atof(pr_token); - pr_immediate._float = (float)(num*sign); - } -} - - -float QCC_PR_LexFloat (void) -{ - int c; - int len; - - len = 0; - c = *pr_file_p; - do - { - pr_token[len] = c; - len++; - pr_file_p++; - c = *pr_file_p; - } while ((c >= '0' && c<= '9') || (c == '.'&&pr_file_p[1]!='.')); //only allow a . if the next isn't too... - pr_token[len] = 0; - return (float)atof (pr_token); -} - -/* -============== -PR_LexVector - -Parses a single quoted vector -============== -*/ -void QCC_PR_LexVector (void) -{ - int i; - - pr_file_p++; - - if (*pr_file_p == '\\') - {//extended character constant - pr_token_type = tt_immediate; - pr_immediate_type = type_float; - pr_file_p++; - switch(*pr_file_p) - { - case 'n': - pr_immediate._float = '\n'; - break; - case 'r': - pr_immediate._float = '\r'; - break; - case 't': - pr_immediate._float = '\t'; - break; - case '\'': - pr_immediate._float = '\''; - break; - case '\"': - pr_immediate._float = '\"'; - break; - case '\\': - pr_immediate._float = '\\'; - break; - default: - QCC_PR_ParseError (ERR_INVALIDVECTORIMMEDIATE, "Bad character constant"); - } - if (*pr_file_p != '\'') - QCC_PR_ParseError (ERR_INVALIDVECTORIMMEDIATE, "Bad character constant"); - pr_file_p++; - return; - } - if (pr_file_p[1] == '\'') - {//character constant - pr_token_type = tt_immediate; - pr_immediate_type = type_float; - pr_immediate._float = pr_file_p[0]; - pr_file_p+=2; - return; - } - pr_token_type = tt_immediate; - pr_immediate_type = type_vector; - QCC_PR_LexWhitespace (); - for (i=0 ; i<3 ; i++) - { - pr_immediate.vector[i] = QCC_PR_LexFloat (); - QCC_PR_LexWhitespace (); - - if (*pr_file_p == '\'' && i == 1) - { - if (i < 2) - QCC_PR_ParseWarning (WARN_FTE_SPECIFIC, "Bad vector"); - - for (i++ ; i<3 ; i++) - pr_immediate.vector[i] = 0; - break; - } - } - if (*pr_file_p != '\'') - QCC_PR_ParseError (ERR_INVALIDVECTORIMMEDIATE, "Bad vector"); - pr_file_p++; -} - -/* -============== -PR_LexName - -Parses an identifier -============== -*/ -void QCC_PR_LexName (void) -{ - int c; - int len; - - len = 0; - c = *pr_file_p; - do - { - pr_token[len] = c; - len++; - pr_file_p++; - c = *pr_file_p; - } while ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' - || (c >= '0' && c <= '9')); - - pr_token[len] = 0; - pr_token_type = tt_name; -} - -/* -============== -PR_LexPunctuation -============== -*/ -void QCC_PR_LexPunctuation (void) -{ - int i; - int len; - char *p; - - pr_token_type = tt_punct; - - for (i=0 ; (p = pr_punctuation[i]) != NULL ; i++) - { - len = strlen(p); - if (!strncmp(p, pr_file_p, len) ) - { - strcpy (pr_token, pr_punctuationremap[i]); - if (p[0] == '{') - pr_bracelevel++; - else if (p[0] == '}') - pr_bracelevel--; - pr_file_p += len; - return; - } - } - - QCC_PR_ParseError (ERR_UNKNOWNPUCTUATION, "Unknown punctuation"); -} - - -/* -============== -PR_LexWhitespace -============== -*/ -void QCC_PR_LexWhitespace (void) -{ - int c; - - while (1) - { - // skip whitespace - while ( (c = *pr_file_p) <= ' ') - { - if (c=='\n') - { - pr_file_p++; - QCC_PR_NewLine (false); - if (!pr_file_p) - return; - } - else - { - if (c == 0) - return; // end of file - pr_file_p++; - } - } - - // skip // comments - if (c=='/' && pr_file_p[1] == '/') - { - while (*pr_file_p && *pr_file_p != '\n') - pr_file_p++; - - if (*pr_file_p == '\n') - pr_file_p++; //don't break on eof. - QCC_PR_NewLine(false); - continue; - } - - // skip /* */ comments - if (c=='/' && pr_file_p[1] == '*') - { - pr_file_p+=2; - do - { - if (pr_file_p[0]=='\n') - { - QCC_PR_NewLine(true); - } - if (pr_file_p[1] == 0) - { - pr_file_p++; - return; - } - pr_file_p++; - } while (pr_file_p[0] != '*' || pr_file_p[1] != '/'); - pr_file_p+=2; - continue; - } - - break; // a real character has been found - } -} - -//============================================================================ - -#define MAX_FRAMES 8192 -char pr_framemodelname[64]; -char pr_framemacros[MAX_FRAMES][64]; -int pr_framemacrovalue[MAX_FRAMES]; -int pr_nummacros, pr_oldmacros; -int pr_macrovalue; -int pr_savedmacro; - -void QCC_PR_ClearGrabMacros (void) -{ - pr_oldmacros = pr_nummacros; -// pr_nummacros = 0; - pr_macrovalue = 0; - pr_savedmacro = -1; -} - -int QCC_PR_FindMacro (char *name) -{ - int i; - - for (i=pr_nummacros-1 ; i>=0 ; i--) - { - if (!STRCMP (name, pr_framemacros[i])) - { - return pr_framemacrovalue[i]; - } - } - for (i=pr_nummacros-1 ; i>=0 ; i--) - { - if (!stricmp (name, pr_framemacros[i])) - { - QCC_PR_ParseWarning(WARN_CASEINSENSATIVEFRAMEMACRO, "Case insensative frame macro"); - return pr_framemacrovalue[i]; - } - } - return -1; -} - -void QCC_PR_ExpandMacro(void) -{ - int i = QCC_PR_FindMacro(pr_token); - - if (i < 0) - QCC_PR_ParseError (ERR_BADFRAMEMACRO, "Unknown frame macro $%s", pr_token); - - sprintf (pr_token,"%d", i); - pr_token_type = tt_immediate; - pr_immediate_type = type_float; - pr_immediate._float = (float)i; -} - -// just parses text, returning false if an eol is reached -pbool QCC_PR_SimpleGetToken (void) -{ - int c; - int i; - - pr_token[0] = 0; - -// skip whitespace - while ( (c = *pr_file_p) <= ' ') - { - if (c=='\n' || c == 0) - return false; - pr_file_p++; - } - if (pr_file_p[0] == '/') - { - if (pr_file_p[1] == '/') - { //comment alert - while(*pr_file_p && *pr_file_p != '\n') - pr_file_p++; - return false; - } - if (pr_file_p[1] == '*') - return false; - } - - i = 0; - while ( (c = *pr_file_p) > ' ' && c != ',' && c != ';' && c != ')' && c != '(' && c != ']') - { - pr_token[i] = c; - i++; - pr_file_p++; - } - pr_token[i] = 0; - return i!=0; -} - -pbool QCC_PR_LexMacroName(void) -{ - int c; - int i; - - pr_token[0] = 0; - -// skip whitespace - while ( (c = *pr_file_p) <= ' ') - { - if (c=='\n' || c == 0) - return false; - pr_file_p++; - } - if (pr_file_p[0] == '/') - { - if (pr_file_p[1] == '/') - { //comment alert - while(*pr_file_p && *pr_file_p != '\n') - pr_file_p++; - return false; - } - if (pr_file_p[1] == '*') - return false; - } - - i = 0; - while ( (c = *pr_file_p) > ' ' && c != '\n' && c != ',' && c != ';' && c != ')' && c != '(' && c != ']' && !(pr_file_p[0] == '.' && pr_file_p[1] == '.')) - { - pr_token[i] = c; - i++; - pr_file_p++; - } - pr_token[i] = 0; - return i!=0; -} - -void QCC_PR_MacroFrame(char *name, int value) -{ - int i; - for (i=pr_nummacros-1 ; i>=0 ; i--) - { - if (!STRCMP (name, pr_framemacros[i])) - { - pr_framemacrovalue[i] = value; - if (i>=pr_oldmacros) - QCC_PR_ParseWarning(WARN_DUPLICATEMACRO, "Duplicate macro defined (%s)", pr_token); - //else it's from an old file, and shouldn't be mentioned. - return; - } - } - - if (strlen(name)+1 > sizeof(pr_framemacros[0])) - QCC_PR_ParseWarning(ERR_TOOMANYFRAMEMACROS, "Name for frame macro %s is too long", name); - else - { - strcpy (pr_framemacros[pr_nummacros], name); - pr_framemacrovalue[pr_nummacros] = value; - pr_nummacros++; - if (pr_nummacros >= MAX_FRAMES) - QCC_PR_ParseError(ERR_TOOMANYFRAMEMACROS, "Too many frame macros defined"); - } -} - -void QCC_PR_ParseFrame (void) -{ - while (QCC_PR_LexMacroName ()) - { - QCC_PR_MacroFrame(pr_token, pr_macrovalue++); - } -} - -/* -============== -PR_LexGrab - -Deals with counting sequence numbers and replacing frame macros -============== -*/ -void QCC_PR_LexGrab (void) -{ - pr_file_p++; // skip the $ -// if (!QCC_PR_SimpleGetToken ()) -// QCC_PR_ParseError ("hanging $"); - if (*pr_file_p <= ' ') - QCC_PR_ParseError (ERR_BADFRAMEMACRO, "hanging $"); - QCC_PR_LexMacroName(); - if (!*pr_token) - QCC_PR_ParseError (ERR_BADFRAMEMACRO, "hanging $"); - -// check for $frame - if (!STRCMP (pr_token, "frame") || !STRCMP (pr_token, "framesave")) - { - QCC_PR_ParseFrame (); - QCC_PR_Lex (); - } -// ignore other known $commands - just for model/spritegen - else if (!STRCMP (pr_token, "cd") - || !STRCMP (pr_token, "origin") - || !STRCMP (pr_token, "base") - || !STRCMP (pr_token, "flags") - || !STRCMP (pr_token, "scale") - || !STRCMP (pr_token, "skin") ) - { // skip to end of line - while (QCC_PR_LexMacroName ()) - ; - QCC_PR_Lex (); - } - else if (!STRCMP (pr_token, "flush")) - { - QCC_PR_ClearGrabMacros(); - while (QCC_PR_LexMacroName ()) - ; - QCC_PR_Lex (); - } - else if (!STRCMP (pr_token, "framevalue")) - { - QCC_PR_LexMacroName (); - pr_macrovalue = atoi(pr_token); - - QCC_PR_Lex (); - } - else if (!STRCMP (pr_token, "framerestore")) - { - QCC_PR_LexMacroName (); - QCC_PR_ExpandMacro(); - pr_macrovalue = (int)pr_immediate._float; - - QCC_PR_Lex (); - } - else if (!STRCMP (pr_token, "modelname")) - { - int i; - QCC_PR_LexMacroName (); - - if (*pr_framemodelname) - QCC_PR_MacroFrame(pr_framemodelname, pr_macrovalue); - - strncpy(pr_framemodelname, pr_token, sizeof(pr_framemodelname)-1); - pr_framemodelname[sizeof(pr_framemodelname)-1] = '\0'; - - i = QCC_PR_FindMacro(pr_framemodelname); - if (i) - pr_macrovalue = i; - else - i = 0; - - QCC_PR_Lex (); - } -// look for a frame name macro - else - QCC_PR_ExpandMacro (); -} - -//=========================== -//compiler constants - dmw - -pbool QCC_PR_UndefineName(char *name) -{ -// int a; - CompilerConstant_t *c; - c = pHash_Get(&compconstantstable, name); - if (!c) - { - QCC_PR_ParseWarning(WARN_UNDEFNOTDEFINED, "Precompiler constant %s was not defined", name); - return false; - } - - Hash_Remove(&compconstantstable, name); - return true; - /* - a = c-CompilerConstant; -// for (a = 0; a < numCompilerConstants; a++) - { -// if (!STRCMP(name, CompilerConstant[a].name)) - { - memmove(&CompilerConstant[a], &CompilerConstant[a+1], sizeof(CompilerConstant_t) * (numCompilerConstants-a)); - numCompilerConstants--; - - - - - if (!STRCMP(name, "OP_NODUP")) - qccop_noduplicatestrings = false; - - if (!STRCMP(name, "OP_COMP_ALL")) //group - { - QCC_PR_UndefineName("OP_COMP_STATEMENTS"); - QCC_PR_UndefineName("OP_COMP_DEFS"); - QCC_PR_UndefineName("OP_COMP_FIELDS"); - QCC_PR_UndefineName("OP_COMP_FUNCTIONS"); - QCC_PR_UndefineName("OP_COMP_STRINGS"); - QCC_PR_UndefineName("OP_COMP_GLOBALS"); - QCC_PR_UndefineName("OP_COMP_LINES"); - QCC_PR_UndefineName("OP_COMP_TYPES"); - } - - return true; - } - } -// return false; -*/ -} - -CompilerConstant_t *QCC_PR_DefineName(char *name) -{ - int i; - CompilerConstant_t *cnst; - -// if (numCompilerConstants >= MAX_CONSTANTS) -// QCC_PR_ParseError("Too many compiler constants - %i >= %i", numCompilerConstants, MAX_CONSTANTS); - - if (strlen(name) >= MAXCONSTANTLENGTH || !*name) - QCC_PR_ParseError(ERR_CONSTANTTOOLONG, "Compiler constant name length is too long or short"); - - cnst = pHash_Get(&compconstantstable, name); - if (cnst ) - { - QCC_PR_ParseWarning(WARN_DUPLICATEDEFINITION, "Duplicate definition for Precompiler constant %s", name); - Hash_Remove(&compconstantstable, name); - } - - cnst = qccHunkAlloc(sizeof(CompilerConstant_t)); - - cnst->used = false; - cnst->numparams = 0; - strcpy(cnst->name, name); - cnst->namelen = strlen(name); - *cnst->value = '\0'; - for (i = 0; i < MAXCONSTANTPARAMS; i++) - cnst->params[i][0] = '\0'; - - pHash_Add(&compconstantstable, cnst->name, cnst, qccHunkAlloc(sizeof(bucket_t))); - - if (!STRCMP(name, "OP_NODUP")) - opt_noduplicatestrings = true; - - - if (!STRCMP(name, "OP_TIME")) //group - optimize for a fast compiler - { - QCC_PR_UndefineName("OP_SIZE"); - QCC_PR_UndefineName("OP_SPEED"); - - QCC_PR_UndefineName("OP_NODUP"); - QCC_PR_UndefineName("OP_COMP_ALL"); - } - - if (!STRCMP(name, "OP_SPEED")) //group - optimize run speed - { - QCC_PR_UndefineName("OP_SIZE"); - QCC_PR_UndefineName("OP_TIME"); - -// QCC_PR_UndefineName("OP_NODUP"); - QCC_PR_UndefineName("OP_COMP_ALL"); - } - - if (!STRCMP(name, "OP_SIZE")) //group - produce small output. - { - QCC_PR_UndefineName("OP_SPEED"); - QCC_PR_UndefineName("OP_TIME"); - - QCC_PR_DefineName("OP_NODUP"); - QCC_PR_DefineName("OP_COMP_ALL"); - } - - if (!STRCMP(name, "OP_COMP_ALL")) //group - compress the output - { - QCC_PR_DefineName("OP_COMP_STATEMENTS"); - QCC_PR_DefineName("OP_COMP_DEFS"); - QCC_PR_DefineName("OP_COMP_FIELDS"); - QCC_PR_DefineName("OP_COMP_FUNCTIONS"); - QCC_PR_DefineName("OP_COMP_STRINGS"); - QCC_PR_DefineName("OP_COMP_GLOBALS"); - QCC_PR_DefineName("OP_COMP_LINES"); - QCC_PR_DefineName("OP_COMP_TYPES"); - } - - - - return cnst; -} - -void QCC_PR_Undefine(void) -{ - QCC_PR_SimpleGetToken (); - - QCC_PR_UndefineName(pr_token); -// QCC_PR_ParseError("%s was not defined.", pr_token); -} - -void QCC_PR_ConditionCompilation(void) -{ - char *oldval; - char *d; - char *s; - int quote=false; - CompilerConstant_t *cnst; - - QCC_PR_SimpleGetToken (); - - if (!QCC_PR_SimpleGetToken ()) - QCC_PR_ParseError(ERR_NONAME, "No name defined for compiler constant"); - - cnst = pHash_Get(&compconstantstable, pr_token); - if (cnst) - { - oldval = cnst->value; - Hash_Remove(&compconstantstable, pr_token); - } - else - oldval = NULL; - - cnst = QCC_PR_DefineName(pr_token); - - if (*pr_file_p == '(') - { - s = pr_file_p+1; - while(*pr_file_p++) - { - if (*pr_file_p == ',') - { - if (cnst->numparams >= MAXCONSTANTPARAMS) - QCC_PR_ParseError(ERR_MACROTOOMANYPARMS, "May not have more than %i parameters to a macro", MAXCONSTANTPARAMS); - strncpy(cnst->params[cnst->numparams], s, pr_file_p-s); - cnst->params[cnst->numparams][pr_file_p-s] = '\0'; - cnst->numparams++; - pr_file_p++; - s = pr_file_p; - } - if (*pr_file_p == ')') - { - if (cnst->numparams >= MAXCONSTANTPARAMS) - QCC_PR_ParseError(ERR_MACROTOOMANYPARMS, "May not have more than %i parameters to a macro", MAXCONSTANTPARAMS); - strncpy(cnst->params[cnst->numparams], s, pr_file_p-s); - cnst->params[cnst->numparams][pr_file_p-s] = '\0'; - cnst->numparams++; - pr_file_p++; - break; - } - } - } - else cnst->numparams = -1; - - s = pr_file_p; - d = cnst->value; - while(*s == ' ' || *s == '\t') - s++; - while(1) - { - if( *s == '\\' ) - { - // read over a newline if necessary - if( s[1] == '\n' || s[1] == '\r' ) - { - s++; - QCC_PR_NewLine(false); - *d++ = *s++; - if( s[-1] == '\r' && s[0] == '\n' ) - { - *d++ = *s++; - } - } - } - else if(*s == '\r' || *s == '\n' || *s == '\0') - { - break; - } - - if (!quote && s[0]=='/'&&(s[1]=='/'||s[1]=='*')) - break; - if (*s == '\"') - quote=!quote; - - *d = *s; - d++; - s++; - } - *d = '\0'; - d--; - while(*d<= ' ' && d >= cnst->value) - *d-- = '\0'; - if (strlen(cnst->value) >= sizeof(cnst->value)) //this is too late. - QCC_PR_ParseError(ERR_CONSTANTTOOLONG, "Macro %s too long (%i not %i)", cnst->name, strlen(cnst->value), sizeof(cnst->value)); - - if (oldval) - { //we always warn if it was already defined - //we use different warning codes so that -Wno-mundane can be used to ignore identical redefinitions. - if (strcmp(oldval, cnst->value)) - QCC_PR_ParseWarning(WARN_DUPLICATEPRECOMPILER, "Alternate precompiler definition of %s", pr_token); - else - QCC_PR_ParseWarning(WARN_IDENTICALPRECOMPILER, "Identical precompiler definition of %s", pr_token); - } - - pr_file_p = s; -} - -int QCC_PR_CheakCompConst(void) -{ - char *oldpr_file_p = pr_file_p; - int whitestart; - - CompilerConstant_t *c; - - char *end; - for (end = pr_file_p; ; end++) - { - if (*end <= ' ') - break; - - if (*end == ')' - || *end == '(' - || *end == '+' - || *end == '-' - || *end == '*' - || *end == '/' - || *end == '|' - || *end == '&' - || *end == '=' - || *end == '^' - || *end == '~' - || *end == '[' - || *end == ']' - || *end == '\"' - || *end == '{' - || *end == '}' - || *end == ';' - || *end == ':' - || *end == ',' - || *end == '.' - || *end == '#') - break; - } - strncpy(pr_token, pr_file_p, end-pr_file_p); - pr_token[end-pr_file_p]='\0'; - -// printf("%s\n", pr_token); - c = pHash_Get(&compconstantstable, pr_token); - - if (c && !c->inside) - { - pr_file_p = oldpr_file_p+strlen(c->name); - while(*pr_file_p == ' ' || *pr_file_p == '\t') - pr_file_p++; - if (c->numparams>=0) - { - if (*pr_file_p == '(') - { - int p; - char *start; - char buffer[1024]; - char *paramoffset[MAXCONSTANTPARAMS+1]; - int param=0; - int plevel=0; - - pr_file_p++; - while(*pr_file_p == ' ' || *pr_file_p == '\t') - pr_file_p++; - start = pr_file_p; - while(1) - { - // handle strings correctly by ignoring them - if (*pr_file_p == '\"') - { - do { - pr_file_p++; - } while( (pr_file_p[-1] == '\\' || pr_file_p[0] != '\"') && *pr_file_p && *pr_file_p != '\n' ); - } - if (*pr_file_p == '(') - plevel++; - else if (!plevel && (*pr_file_p == ',' || *pr_file_p == ')')) - { - paramoffset[param++] = start; - start = pr_file_p+1; - if (*pr_file_p == ')') - { - *pr_file_p = '\0'; - pr_file_p++; - break; - } - *pr_file_p = '\0'; - pr_file_p++; - while(*pr_file_p == ' ' || *pr_file_p == '\t') - { - pr_file_p++; - start++; - } - // move back by one char because we move forward by one at the end of the loop - pr_file_p--; - if (param == MAXCONSTANTPARAMS) - QCC_PR_ParseError(ERR_TOOMANYPARAMS, "Too many parameters in macro call"); - } else if (*pr_file_p == ')' ) - plevel--; - else if(*pr_file_p == '\n') - QCC_PR_NewLine(false); - - // see that *pr_file_p = '\0' up there? Must ++ BEFORE checking for !*pr_file_p - pr_file_p++; - if (!*pr_file_p) - QCC_PR_ParseError(ERR_EOF, "EOF on macro call"); - } - if (param < c->numparams) - QCC_PR_ParseError(ERR_TOOFEWPARAMS, "Not enough macro parameters"); - paramoffset[param] = start; - - *buffer = '\0'; - - oldpr_file_p = pr_file_p; - pr_file_p = c->value; - for(;;) - { - whitestart = p = strlen(buffer); - while(*pr_file_p <= ' ') //copy across whitespace - { - if (!*pr_file_p) - break; - buffer[p++] = *pr_file_p++; - } - buffer[p] = 0; - - if(*pr_file_p == '\"') - { - do - { - buffer[p++] = *pr_file_p; - ++pr_file_p; - } while( (pr_file_p[-1] == '\\' || pr_file_p[0] != '\"') && *pr_file_p && *pr_file_p != '\n' ); - buffer[p++] = *pr_file_p; // copy the end-quote too - buffer[p] = 0; - ++pr_file_p; // and skip it - continue; - } - else if (*pr_file_p == '#') //if you ask for #a##b you will be shot. use #a #b instead, or chain macros. - { - if (pr_file_p[1] == '#') - { //concatinate (srip out whitespace) - buffer[whitestart] = '\0'; - pr_file_p+=2; - } - else - { //stringify - pr_file_p++; - pr_file_p = QCC_COM_Parse2(pr_file_p); - if (!pr_file_p) - break; - - for (p = 0; p < param; p++) - { - if (!STRCMP(qcc_token, c->params[p])) - { - strcat(buffer, "\""); - strcat(buffer, paramoffset[p]); - strcat(buffer, "\""); - break; - } - } - if (p == param) - { - strcat(buffer, "#"); - strcat(buffer, qcc_token); - //QCC_PR_ParseWarning(0, "Stringification ignored"); - } - continue; //already did this one - } - } - - pr_file_p = QCC_COM_Parse2(pr_file_p); - if (!pr_file_p) - break; - - for (p = 0; p < param; p++) - { - if (!STRCMP(qcc_token, c->params[p])) - { - strcat(buffer, paramoffset[p]); - break; - } - } - if (p == param) - strcat(buffer, qcc_token); - } - - for (p = 0; p < param-1; p++) - paramoffset[p][strlen(paramoffset[p])] = ','; - paramoffset[p][strlen(paramoffset[p])] = ')'; - - pr_file_p = oldpr_file_p; - if (!*buffer) - expandedemptymacro = true; - QCC_PR_IncludeChunkEx(buffer, true, NULL, c); - } - else - QCC_PR_ParseError(ERR_TOOFEWPARAMS, "Macro without opening brace"); - } - else - { - if (!*c->value) - expandedemptymacro = true; - QCC_PR_IncludeChunkEx(c->value, false, NULL, c); - } - - QCC_PR_Lex(); - return true; - } - - if (!strncmp(pr_file_p, "__TIME__", 8)) - { - static char retbuf[128]; - - time_t long_time; - time( &long_time ); - strftime( retbuf, sizeof(retbuf), - "\"%H:%M\"", localtime( &long_time )); - - pr_file_p = retbuf; - QCC_PR_Lex(); //translate the macro's value - pr_file_p = oldpr_file_p+8; - - return true; - } - if (!strncmp(pr_file_p, "__DATE__", 8)) - { - static char retbuf[128]; - - time_t long_time; - time( &long_time ); - strftime( retbuf, sizeof(retbuf), - "\"%a %d %b %Y\"", localtime( &long_time )); - - pr_file_p = retbuf; - QCC_PR_Lex(); //translate the macro's value - pr_file_p = oldpr_file_p+8; - - return true; - } - if (!strncmp(pr_file_p, "__FILE__", 8)) - { - static char retbuf[256]; - sprintf(retbuf, "\"%s\"", strings + s_file); - pr_file_p = retbuf; - QCC_PR_Lex(); //translate the macro's value - pr_file_p = oldpr_file_p+8; - - return true; - } - if (!strncmp(pr_file_p, "__LINE__", 8)) - { - static char retbuf[256]; - sprintf(retbuf, "\"%i\"", pr_source_line); - pr_file_p = retbuf; - QCC_PR_Lex(); //translate the macro's value - pr_file_p = oldpr_file_p+8; - return true; - } - if (!strncmp(pr_file_p, "__FUNC__", 8)) - { - static char retbuf[256]; - sprintf(retbuf, "\"%s\"",pr_scope->name); - pr_file_p = retbuf; - QCC_PR_Lex(); //translate the macro's value - pr_file_p = oldpr_file_p+8; - return true; - } - if (!strncmp(pr_file_p, "__NULL__", 8)) - { - static char retbuf[256]; - sprintf(retbuf, "0i"); - pr_file_p = retbuf; - QCC_PR_Lex(); //translate the macro's value - pr_file_p = oldpr_file_p+8; - return true; - } - return false; -} - -char *QCC_PR_CheakCompConstString(char *def) -{ - char *s; - - CompilerConstant_t *c; - - c = pHash_Get(&compconstantstable, def); - - if (c) - { - s = QCC_PR_CheakCompConstString(c->value); - return s; - } - return def; -} - -CompilerConstant_t *QCC_PR_CheckCompConstDefined(char *def) -{ - CompilerConstant_t *c = pHash_Get(&compconstantstable, def); - return c; - /*int a; - for (a = 0; a < numCompilerConstants; a++) - { - if (!strncmp(def, CompilerConstant[a].name, CompilerConstant[a].namelen+1)) - return &CompilerConstant[a]; - } - return NULL; - */ -} - -//============================================================================ - -/* -============== -PR_Lex - -Sets pr_token, pr_token_type, and possibly pr_immediate and pr_immediate_type -============== -*/ -void QCC_PR_Lex (void) -{ - int c; - - pr_token[0] = 0; - - if (!pr_file_p) - { - if (QCC_PR_UnInclude()) - { - QCC_PR_Lex(); - return; - } - pr_token_type = tt_eof; - return; - } - - QCC_PR_LexWhitespace (); - - if (!pr_file_p) - { - if (QCC_PR_UnInclude()) - { - QCC_PR_Lex(); - return; - } - pr_token_type = tt_eof; - return; - } - - c = *pr_file_p; - - if (!c) - { - if (QCC_PR_UnInclude()) - { - QCC_PR_Lex(); - return; - } - pr_token_type = tt_eof; - return; - } - -// handle quoted strings as a unit - if (c == '\"') - { - QCC_PR_LexString (); - return; - } - -// handle quoted vectors as a unit - if (c == '\'') - { - QCC_PR_LexVector (); - return; - } - -// if the first character is a valid identifier, parse until a non-id -// character is reached - if ( c == '~' || c == '%') //let's see which one we make into an operator first... possibly both... - { - QCC_PR_ParseWarning(0, "~ or %% prefixes to denote integers are deprecated. Please use a postfix of 'i'"); - pr_file_p++; - pr_token_type = tt_immediate; - pr_immediate_type = type_integer; - pr_immediate._int = QCC_PR_LexInteger (); - return; - } - if ( c == '0' && pr_file_p[1] == 'x') - { - pr_token_type = tt_immediate; - QCC_PR_LexNumber(); - return; - } - if ( (c == '.'&&pr_file_p[1] >='0' && pr_file_p[1] <= '9') || (c >= '0' && c <= '9') || ( c=='-' && pr_file_p[1]>='0' && pr_file_p[1] <='9') ) - { - pr_token_type = tt_immediate; - QCC_PR_LexNumber (); - return; - } - - if (c == '#' && !(pr_file_p[1]=='-' || (pr_file_p[1]>='0' && pr_file_p[1] <='9'))) //hash and not number - { - pr_file_p++; - if (!QCC_PR_CheakCompConst()) - { - if (!QCC_PR_SimpleGetToken()) - strcpy(pr_token, "unknown"); - QCC_PR_ParseError(ERR_CONSTANTNOTDEFINED, "Explicit precompiler usage when not defined %s", pr_token); - } - else - if (pr_token_type == tt_eof) - QCC_PR_Lex(); - - return; - } - - if ( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' ) - { - if (flag_hashonly || !QCC_PR_CheakCompConst()) //look for a macro. - QCC_PR_LexName (); - else - if (pr_token_type == tt_eof) - { - if (QCC_PR_UnInclude()) - { - QCC_PR_Lex(); - return; - } - pr_token_type = tt_eof; - } - return; - } - - if (c == '$') - { - QCC_PR_LexGrab (); - return; - } - -// parse symbol strings until a non-symbol is found - QCC_PR_LexPunctuation (); -} - -//============================================================================= - - -void QCC_PR_ParsePrintDef (int type, QCC_def_t *def) -{ - if (qccwarningdisabled[type]) - return; - if (def->s_file) - { - if (flag_msvcstyle) - printf ("%s(%i) : %s is defined here\n", strings + def->s_file, def->s_line, def->name); - else - printf ("%s:%i: %s is defined here\n", strings + def->s_file, def->s_line, def->name); - } -} -void *errorscope; -void QCC_PR_PrintScope (void) -{ - if (pr_scope) - { - if (errorscope != pr_scope) - printf ("in function %s (line %i),\n", pr_scope->name, pr_scope->s_line); - errorscope = pr_scope; - } - else - { - if (errorscope) - printf ("at global scope,\n"); - errorscope = NULL; - } -} -void QCC_PR_ResetErrorScope(void) -{ - errorscope = NULL; -} -/* -============ -PR_ParseError - -Aborts the current file load -============ -*/ -#ifndef QCC -void editbadfile(char *file, int line); -#endif -void VARGS QCC_PR_ParseError (int errortype, char *error, ...) -{ - va_list argptr; - char string[1024]; - - va_start (argptr,error); - QC_vsnprintf (string,sizeof(string)-1, error,argptr); - va_end (argptr); - -#ifndef QCC - editbadfile(strings+s_file, pr_source_line); -#endif - - QCC_PR_PrintScope(); - if (flag_msvcstyle) - printf ("%s(%i) : error: %s\n", strings + s_file, pr_source_line, string); - else - printf ("%s:%i: error: %s\n", strings + s_file, pr_source_line, string); - - longjmp (pr_parse_abort, 1); -} -void VARGS QCC_PR_ParseErrorPrintDef (int errortype, QCC_def_t *def, char *error, ...) -{ - va_list argptr; - char string[1024]; - - va_start (argptr,error); - QC_vsnprintf (string,sizeof(string)-1, error,argptr); - va_end (argptr); - -#ifndef QCC - editbadfile(strings+s_file, pr_source_line); -#endif - QCC_PR_PrintScope(); - if (flag_msvcstyle) - printf ("%s(%i) : error: %s\n", strings + s_file, pr_source_line, string); - else - printf ("%s:%i: error: %s\n", strings + s_file, pr_source_line, string); - - QCC_PR_ParsePrintDef(WARN_ERROR, def); - - longjmp (pr_parse_abort, 1); -} -void VARGS QCC_PR_ParseWarning (int type, char *error, ...) -{ - va_list argptr; - char string[1024]; - - if (type < ERR_PARSEERRORS && qccwarningdisabled[type]) - return; - - va_start (argptr,error); - QC_vsnprintf (string,sizeof(string)-1, error,argptr); - va_end (argptr); - - QCC_PR_PrintScope(); - if (type >= ERR_PARSEERRORS) - { - if (flag_msvcstyle) - printf ("%s(%i) : error: %s\n", strings + s_file, pr_source_line, string); - else - printf ("%s:%i: error: %s\n", strings + s_file, pr_source_line, string); - pr_error_count++; - } - else - { - if (flag_msvcstyle) - printf ("%s(%i) : warning: %s\n", strings + s_file, pr_source_line, string); - else - printf ("%s:%i: warning: %s\n", strings + s_file, pr_source_line, string); - pr_warning_count++; - } -} - -void VARGS QCC_PR_Warning (int type, char *file, int line, char *error, ...) -{ - va_list argptr; - char string[1024]; - - if (qccwarningdisabled[type]) - return; - - va_start (argptr,error); - QC_vsnprintf (string,sizeof(string)-1, error,argptr); - va_end (argptr); - - QCC_PR_PrintScope(); - if (file) - { - if (flag_msvcstyle) - printf ("%s(%i) : warning: %s\n", file, line, string); - else - printf ("%s:%i: warning: %s\n", file, line, string); - } - else - printf ("warning: %s\n", string); - pr_warning_count++; -} - - -/* -============= -PR_Expect - -Issues an error if the current token isn't equal to string -Gets the next token -============= -*/ -#ifndef COMMONINLINES -void QCC_PR_Expect (char *string) -{ - if (STRCMP (string, pr_token)) - QCC_PR_ParseError (ERR_EXPECTED, "expected %s, found %s",string, pr_token); - QCC_PR_Lex (); -} -#endif - - -/* -============= -PR_Check - -Returns true and gets the next token if the current token equals string -Returns false and does nothing otherwise -============= -*/ -#ifndef COMMONINLINES -pbool QCC_PR_CheckToken (char *string) -{ - if (pr_token_type != tt_punct) - return false; - - if (STRCMP (string, pr_token)) - return false; - - QCC_PR_Lex (); - return true; -} - -pbool QCC_PR_CheckImmediate (char *string) -{ - if (pr_token_type != tt_immediate) - return false; - - if (STRCMP (string, pr_token)) - return false; - - QCC_PR_Lex (); - return true; -} - -pbool QCC_PR_CheckName(char *string) -{ - if (pr_token_type != tt_name) - return false; - if (flag_caseinsensative) - { - if (stricmp (string, pr_token)) - return false; - } - else - { - if (STRCMP(string, pr_token)) - return false; - } - QCC_PR_Lex (); - return true; -} - -pbool QCC_PR_CheckKeyword(int keywordenabled, char *string) -{ - if (!keywordenabled) - return false; - if (flag_caseinsensative) - { - if (stricmp (string, pr_token)) - return false; - } - else - { - if (STRCMP(string, pr_token)) - return false; - } - QCC_PR_Lex (); - return true; -} -#endif - - -/* -============ -PR_ParseName - -Checks to see if the current token is a valid name -============ -*/ -char *QCC_PR_ParseName (void) -{ - static char ident[MAX_NAME]; - char *ret; - - if (pr_token_type != tt_name) - QCC_PR_ParseError (ERR_NOTANAME, "\"%s\" - not a name", pr_token); - if (strlen(pr_token) >= MAX_NAME-1) - QCC_PR_ParseError (ERR_NAMETOOLONG, "name too long"); - strcpy (ident, pr_token); - QCC_PR_Lex (); - - ret = qccHunkAlloc(strlen(ident)+1); - strcpy(ret, ident); - return ret; -// return ident; -} - -/* -============ -PR_FindType - -Returns a preexisting complex type that matches the parm, or allocates -a new one and copies it out. -============ -*/ - -//0 if same -QCC_type_t *QCC_PR_NewType (char *name, int basictype); -int typecmp(QCC_type_t *a, QCC_type_t *b) -{ - if (a == b) - return 0; - if (!a || !b) - return 1; //different (^ and not both null) - - if (a->type != b->type) - return 1; - if (a->num_parms != b->num_parms) - return 1; - - if (a->size != b->size) - return 1; -// if (STRCMP(a->name, b->name)) //This isn't 100% clean. -// return 1; - - if (typecmp(a->aux_type, b->aux_type)) - return 1; - - if (a->param || b->param) - { - a = a->param; - b = b->param; - - while(a || b) - { - if (typecmp(a, b)) - return 1; - - a=a->next; - b=b->next; - } - } - - return 0; -} - -QCC_type_t *QCC_PR_DuplicateType(QCC_type_t *in) -{ - QCC_type_t *out, *op, *ip; - if (!in) - return NULL; - - out = QCC_PR_NewType(in->name, in->type); - out->aux_type = QCC_PR_DuplicateType(in->aux_type); - out->param = QCC_PR_DuplicateType(in->param); - ip = in->param; - op = NULL; - while(ip) - { - if (!op) - out->param = op = QCC_PR_DuplicateType(ip); - else - op = (op->next = QCC_PR_DuplicateType(ip)); - ip = ip->next; - } - out->size = in->size; - out->num_parms = in->num_parms; - out->ofs = in->ofs; - out->name = in->name; - out->parentclass = in->parentclass; - - return out; -} - -char *TypeName(QCC_type_t *type) -{ - static char buffer[2][512]; - static int op; - char *ret; - - - op++; - ret = buffer[op&1]; - if (type->type == ev_field) - { - type = type->aux_type; - *ret++ = '.'; - } - *ret = 0; - - if (type->type == ev_function) - { - strcat(ret, type->aux_type->name); - strcat(ret, " ("); - type = type->param; - while(type) - { - strcat(ret, type->name); - type = type->next; - - if (type) - strcat(ret, ", "); - } - strcat(ret, ")"); - } - else if (type->type == ev_entity && type->parentclass) - { - ret = buffer[op&1]; - *ret = 0; - strcat(ret, "class "); - strcat(ret, type->name); -/* strcat(ret, " {"); - type = type->param; - while(type) - { - strcat(ret, type->name); - type = type->next; - - if (type) - strcat(ret, ", "); - } - strcat(ret, "}"); -*/ - } - else - strcpy(ret, type->name); - - return buffer[op&1]; -} -//#define typecmp(a, b) (a && ((a)->type==(b)->type) && !STRCMP((a)->name, (b)->name)) - -QCC_type_t *QCC_PR_FindType (QCC_type_t *type) -{ - int t; - for (t = 0; t < numtypeinfos; t++) - { -// check = &qcc_typeinfo[t]; - if (typecmp(&qcc_typeinfo[t], type)) - continue; - - -// c2 = check->next; -// n2 = type->next; -// for (i=0 ; n2&&c2 ; i++) -// { -// if (!typecmp((c2), (n2))) -// break; -// c2=c2->next; -// n2=n2->next; -// } - -// if (n2==NULL&&c2==NULL) - { - return &qcc_typeinfo[t]; - } - } -QCC_Error(ERR_INTERNAL, "Error with type"); - - return type; -} -/* -QCC_type_t *QCC_PR_NextSubType(QCC_type_t *type, QCC_type_t *prev) -{ - int p; - if (!prev) - return type->next; - - for (p = prev->num_parms; p; p--) - prev = QCC_PR_NextSubType(prev, NULL); - if (prev->num_parms) - - switch(prev->type) - { - case ev_function: - - } - - return prev->next; -} -*/ - -QCC_type_t *QCC_TypeForName(char *name) -{ - int i; - - for (i = 0; i < numtypeinfos; i++) - { - if (!STRCMP(qcc_typeinfo[i].name, name)) - { - return &qcc_typeinfo[i]; - } - } - - return NULL; -} - -/* -============ -PR_SkipToSemicolon - -For error recovery, also pops out of nested braces -============ -*/ -void QCC_PR_SkipToSemicolon (void) -{ - do - { - if (!pr_bracelevel && QCC_PR_CheckToken (";")) - return; - QCC_PR_Lex (); - } while (pr_token_type != tt_eof); -} - - -/* -============ -PR_ParseType - -Parses a variable type, including field and functions types -============ -*/ -#ifdef MAX_EXTRA_PARMS -char pr_parm_names[MAX_PARMS+MAX_EXTRA_PARMS][MAX_NAME]; -#else -char pr_parm_names[MAX_PARMS][MAX_NAME]; -#endif - -pbool recursivefunctiontype; - -QCC_type_t *QCC_PR_NewType (char *name, int basictype); -//expects a ( to have already been parsed. -QCC_type_t *QCC_PR_ParseFunctionType (int newtype, QCC_type_t *returntype) -{ - QCC_type_t *ftype, *ptype, *nptype; - char *name; - int definenames = !recursivefunctiontype; - - recursivefunctiontype++; - - ftype = QCC_PR_NewType(type_function->name, ev_function); - - ftype->aux_type = returntype; // return type - ftype->num_parms = 0; - ptype = NULL; - - - if (!QCC_PR_CheckToken (")")) - { - if (QCC_PR_CheckToken ("...")) - ftype->num_parms = -1; // variable args - else - do - { - if (ftype->num_parms>=MAX_PARMS+MAX_EXTRA_PARMS) - QCC_PR_ParseError(ERR_TOOMANYTOTALPARAMETERS, "Too many parameters. Sorry. (limit is %i)\n", MAX_PARMS+MAX_EXTRA_PARMS); - - if (QCC_PR_CheckToken ("...")) - { - ftype->num_parms = (ftype->num_parms * -1) - 1; - break; - } - - nptype = QCC_PR_ParseType(true); - - if (nptype->type == ev_void) - break; - if (!ptype) - { - ptype = nptype; - ftype->param = ptype; - } - else - { - ptype->next = nptype; - ptype = ptype->next; - } -// type->name = "FUNC PARAMETER"; - - - if (STRCMP(pr_token, ",") && STRCMP(pr_token, ")")) - { - name = QCC_PR_ParseName (); - if (definenames) - strcpy (pr_parm_names[ftype->num_parms], name); - } - else if (definenames) - strcpy (pr_parm_names[ftype->num_parms], ""); - ftype->num_parms++; - } while (QCC_PR_CheckToken (",")); - - QCC_PR_Expect (")"); - } - recursivefunctiontype--; - if (newtype) - return ftype; - return QCC_PR_FindType (ftype); -} -QCC_type_t *QCC_PR_ParseFunctionTypeReacc (int newtype, QCC_type_t *returntype) -{ - QCC_type_t *ftype, *ptype, *nptype; - char *name; - char argname[64]; - int definenames = !recursivefunctiontype; - - recursivefunctiontype++; - - ftype = QCC_PR_NewType(type_function->name, ev_function); - - ftype->aux_type = returntype; // return type - ftype->num_parms = 0; - ptype = NULL; - - - if (!QCC_PR_CheckToken (")")) - { - if (QCC_PR_CheckToken ("...")) - ftype->num_parms = -1; // variable args - else - do - { - if (ftype->num_parms>=MAX_PARMS+MAX_EXTRA_PARMS) - QCC_PR_ParseError(ERR_TOOMANYTOTALPARAMETERS, "Too many parameters. Sorry. (limit is %i)\n", MAX_PARMS+MAX_EXTRA_PARMS); - - if (QCC_PR_CheckToken ("...")) - { - ftype->num_parms = (ftype->num_parms * -1) - 1; - break; - } - - if (QCC_PR_CheckName("arg")) - { - sprintf(argname, "arg%i", ftype->num_parms); - name = argname; - nptype = QCC_PR_NewType("Variant", ev_variant); - } - else if (QCC_PR_CheckName("vect")) //this can only be of vector sizes, so... - { - sprintf(argname, "arg%i", ftype->num_parms); - name = argname; - nptype = QCC_PR_NewType("Vector", ev_vector); - } - else - { - name = QCC_PR_ParseName(); - QCC_PR_Expect(":"); - nptype = QCC_PR_ParseType(true); - } - - if (nptype->type == ev_void) - break; - if (!ptype) - { - ptype = nptype; - ftype->param = ptype; - } - else - { - ptype->next = nptype; - ptype = ptype->next; - } -// type->name = "FUNC PARAMETER"; - - if (definenames) - strcpy (pr_parm_names[ftype->num_parms], name); - ftype->num_parms++; - } while (QCC_PR_CheckToken (";")); - - QCC_PR_Expect (")"); - } - recursivefunctiontype--; - if (newtype) - return ftype; - return QCC_PR_FindType (ftype); -} -QCC_type_t *QCC_PR_PointerType (QCC_type_t *pointsto) -{ - QCC_type_t *ptype; - char name[128]; - sprintf(name, "*%s", pointsto->name); - ptype = QCC_PR_NewType(name, ev_pointer); - ptype->aux_type = pointsto; - return QCC_PR_FindType (ptype); -} -QCC_type_t *QCC_PR_FieldType (QCC_type_t *pointsto) -{ - QCC_type_t *ptype; - char name[128]; - sprintf(name, "FIELD TYPE(%s)", pointsto->name); - ptype = QCC_PR_NewType(name, ev_field); - ptype->aux_type = pointsto; - ptype->size = ptype->aux_type->size; - return QCC_PR_FindType (ptype); -} - -pbool type_inlinefunction; -QCC_type_t *QCC_PR_ParseType (int newtype) -{ - QCC_type_t *newparm; - QCC_type_t *newt; - QCC_type_t *type; - char *name; - int i; - - type_inlinefunction = false; //doesn't really matter so long as its not from an inline function type - -// int ofs; - - if (QCC_PR_CheckToken ("..")) //so we don't end up with the user specifying '. .vector blah' (hexen2 added the .. token for array ranges) - { - newt = QCC_PR_NewType("FIELD TYPE", ev_field); - newt->aux_type = QCC_PR_ParseType (false); - - newt->size = newt->aux_type->size; - - newt = QCC_PR_FindType (newt); - - type = QCC_PR_NewType("FIELD TYPE", ev_field); - type->aux_type = newt; - - type->size = type->aux_type->size; - - if (newtype) - return type; - return QCC_PR_FindType (type); - } - if (QCC_PR_CheckToken (".")) - { - newt = QCC_PR_NewType("FIELD TYPE", ev_field); - newt->aux_type = QCC_PR_ParseType (false); - - newt->size = newt->aux_type->size; - - if (newtype) - return newt; - return QCC_PR_FindType (newt); - } - - name = QCC_PR_CheakCompConstString(pr_token); - - if (QCC_PR_CheckKeyword (keyword_class, "class")) - { -// int parms; - QCC_type_t *fieldtype; - char membername[2048]; - char *classname = QCC_PR_ParseName(); - int forwarddeclaration; - - newt = 0; - - /* Don't advance the line number yet */ - forwarddeclaration = pr_token[0] == ';'; - - /* Look to see if this type is already defined */ - for(i=0;inum_parms != 0) - QCC_PR_ParseError(ERR_REDECLARATION, "Redeclaration of class %s", classname); - - if (!newt) - newt = QCC_PR_NewType(classname, ev_entity); - - newt->size=type_entity->size; - - type = NULL; - - if (forwarddeclaration) - { - QCC_PR_CheckToken(";"); - return NULL; - } - - - - if (QCC_PR_CheckToken(":")) - { - char *parentname = QCC_PR_ParseName(); - newt->parentclass = QCC_TypeForName(parentname); - if (!newt->parentclass) - QCC_PR_ParseError(ERR_NOTANAME, "Parent class %s was not defined", parentname); - } - else - newt->parentclass = type_entity; - - - QCC_PR_Expect("{"); - if (QCC_PR_CheckToken(",")) - QCC_PR_ParseError(ERR_NOTANAME, "member missing name"); - while (!QCC_PR_CheckToken("}")) - { -// if (QCC_PR_CheckToken(",")) -// type->next = QCC_PR_NewType(type->name, type->type); -// else - newparm = QCC_PR_ParseType(true); - - if (newparm->type == ev_struct || newparm->type == ev_union) //we wouldn't be able to handle it. - QCC_PR_ParseError(ERR_INTERNAL, "Struct or union in class %s", classname); - - if (!QCC_PR_CheckToken(";")) - { - newparm->name = QCC_CopyString(pr_token)+strings; - QCC_PR_Lex(); - if (QCC_PR_CheckToken("[")) - { - type->next->size*=atoi(pr_token); - QCC_PR_Lex(); - QCC_PR_Expect("]"); - } - QCC_PR_CheckToken(";"); - } - else - newparm->name = QCC_CopyString("")+strings; - - sprintf(membername, "%s::"MEMBERFIELDNAME, classname, newparm->name); - fieldtype = QCC_PR_NewType(newparm->name, ev_field); - fieldtype->aux_type = newparm; - fieldtype->size = newparm->size; - QCC_PR_GetDef(fieldtype, membername, pr_scope, 2, 1, false); - - - newparm->ofs = 0;//newt->size; - newt->num_parms++; - - if (type) - type->next = newparm; - else - newt->param = newparm; - - type = newparm; - } - - - QCC_PR_Expect(";"); - return NULL; - } - if (QCC_PR_CheckKeyword (keyword_struct, "struct")) - { - newt = QCC_PR_NewType("struct", ev_struct); - newt->size=0; - QCC_PR_Expect("{"); - - type = NULL; - if (QCC_PR_CheckToken(",")) - QCC_PR_ParseError(ERR_NOTANAME, "element missing name"); - - newparm = NULL; - while (!QCC_PR_CheckToken("}")) - { - if (QCC_PR_CheckToken(",")) - { - if (!newparm) - QCC_PR_ParseError(ERR_NOTANAME, "element missing type"); - newparm = QCC_PR_NewType(newparm->name, newparm->type); - } - else - newparm = QCC_PR_ParseType(true); - - if (!QCC_PR_CheckToken(";")) - { - newparm->name = QCC_CopyString(pr_token)+strings; - QCC_PR_Lex(); - if (QCC_PR_CheckToken("[")) - { - newparm->size*=atoi(pr_token); - QCC_PR_Lex(); - QCC_PR_Expect("]"); - } - QCC_PR_CheckToken(";"); - } - else - newparm->name = QCC_CopyString("")+strings; - newparm->ofs = newt->size; - newt->size += newparm->size; - newt->num_parms++; - - if (type) - type->next = newparm; - else - newt->param = newparm; - type = newparm; - } - return newt; - } - if (QCC_PR_CheckKeyword (keyword_union, "union")) - { - newt = QCC_PR_NewType("union", ev_union); - newt->size=0; - QCC_PR_Expect("{"); - - type = NULL; - if (QCC_PR_CheckToken(",")) - QCC_PR_ParseError(ERR_NOTANAME, "element missing name"); - newparm = NULL; - while (!QCC_PR_CheckToken("}")) - { - if (QCC_PR_CheckToken(",")) - { - if (!newparm) - QCC_PR_ParseError(ERR_NOTANAME, "element missing type"); - newparm = QCC_PR_NewType(newparm->name, newparm->type); - } - else - newparm = QCC_PR_ParseType(true); - if (QCC_PR_CheckToken(";")) - newparm->name = QCC_CopyString("")+strings; - else - { - newparm->name = QCC_CopyString(pr_token)+strings; - QCC_PR_Lex(); - QCC_PR_Expect(";"); - } - newparm->ofs = 0; - if (newparm->size > newt->size) - newt->size = newparm->size; - newt->num_parms++; - - if (type) - type->next = newparm; - else - newt->param = newparm; - type = newparm; - } - return newt; - } - type = NULL; - for (i = 0; i < numtypeinfos; i++) - { - if (!STRCMP(qcc_typeinfo[i].name, name)) - { - type = &qcc_typeinfo[i]; - break; - } - } - - if (i == numtypeinfos) - { - if (!*name) - return NULL; - if (!stricmp("Void", name)) - type = type_void; - else if (!stricmp("Real", name)) - type = type_float; - else if (!stricmp("Vector", name)) - type = type_vector; - else if (!stricmp("Object", name)) - type = type_entity; - else if (!stricmp("String", name)) - type = type_string; - else if (!stricmp("PFunc", name)) - type = type_function; - else - { - QCC_PR_ParseError (ERR_NOTATYPE, "\"%s\" is not a type", name); - type = type_float; // shut up compiler warning - } - } - QCC_PR_Lex (); - - if (QCC_PR_CheckToken ("(")) //this is followed by parameters. Must be a function. - { - type_inlinefunction = true; - return QCC_PR_ParseFunctionType(newtype, type); - } - else - { - if (newtype) - { - type = QCC_PR_DuplicateType(type); - } - - return type; - } -} - -#endif - - - diff --git a/misc/mediasource/extra/fteqcc-src/qccgui.c b/misc/mediasource/extra/fteqcc-src/qccgui.c deleted file mode 100644 index e6fb7bd0..00000000 --- a/misc/mediasource/extra/fteqcc-src/qccgui.c +++ /dev/null @@ -1,2343 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "qcc.h" -#include "gui.h" - - - - -/* -============== -LoadFile -============== -*/ -unsigned char *QCC_ReadFile (char *fname, void *buffer, int len) -{ - long length; - FILE *f; - f = fopen(fname, "rb"); - if (!f) - return NULL; - length = fread(buffer, 1, len, f); - fclose(f); - - if (length != len) - return NULL; - - return buffer; -} -int QCC_FileSize (char *fname) -{ - long length; - FILE *f; - f = fopen(fname, "rb"); - if (!f) - return -1; - fseek(f, 0, SEEK_END); - length = ftell(f); - fclose(f); - - return length; -} - -pbool QCC_WriteFile (char *name, void *data, int len) -{ - long length; - FILE *f; - f = fopen(name, "wb"); - if (!f) - return false; - length = fwrite(data, 1, len, f); - fclose(f); - - if (length != len) - return false; - - return true; -} - -#undef printf -#undef Sys_Error - -void Sys_Error(const char *text, ...) -{ - va_list argptr; - static char msg[2048]; - - va_start (argptr,text); - QC_vsnprintf (msg,sizeof(msg)-1, text,argptr); - va_end (argptr); - - QCC_Error(ERR_INTERNAL, "%s", msg); -} - - -FILE *logfile; -int logprintf(const char *format, ...) -{ - va_list argptr; - static char string[1024]; - - va_start (argptr, format); -#ifdef _WIN32 - _vsnprintf (string,sizeof(string)-1, format,argptr); -#else - vsnprintf (string,sizeof(string), format,argptr); -#endif - va_end (argptr); - - printf("%s", string); - if (logfile) - fputs(string, logfile); - - return 0; -} - - - - - - - - - - - -#define Edit_Redo(hwndCtl) ((BOOL)(DWORD)SNDMSG((hwndCtl), EM_REDO, 0L, 0L)) - - -#define MAIN_WINDOW_CLASS_NAME "FTEMAINWINDOW" -#define MDI_WINDOW_CLASS_NAME "FTEMDIWINDOW" -#define EDIT_WINDOW_CLASS_NAME "FTEEDITWINDOW" -#define OPTIONS_WINDOW_CLASS_NAME "FTEOPTIONSWINDOW" - -#define EM_GETSCROLLPOS (WM_USER + 221) -#define EM_SETSCROLLPOS (WM_USER + 222) - - - -int GUIprintf(const char *msg, ...); -void GUIPrint(HWND wnd, char *msg); - -char finddef[256]; - -void RunCompiler(char *args); - -HINSTANCE ghInstance; -HMODULE richedit; - -pbool resetprogssrc; //progs.src was changed, reload project info. - - -HWND mainwindow; -HWND mdibox; -HWND outputwindow; -HWND outputbox; -HWND projecttree; -HWND gotodefbox; -HWND gotodefaccept; - -FILE *logfile; - -struct{ - char *text; - HWND hwnd; - int washit; -} buttons[] = { - {"Compile"}, - {"Edit"}, - {"Options"}, - {"Quit"} -}; - -#define ID_COMPILE 0 -#define ID_EDIT 1 -#define ID_OPTIONS 2 -#define ID_QUIT 3 - -#define NUMBUTTONS sizeof(buttons)/sizeof(buttons[0]) - - - -void GUI_DialogPrint(char *title, char *text) -{ - MessageBox(mainwindow, text, title, 0); -} - -HWND CreateAnEditControl(HWND parent) -{ - HWND newc; - - if (!richedit) - richedit = LoadLibrary("RICHED32.DLL"); - - newc=CreateWindowEx(WS_EX_CLIENTEDGE, - richedit?RICHEDIT_CLASS:"EDIT", - "", - WS_CHILD /*| ES_READONLY*/ | WS_VISIBLE | - WS_HSCROLL | WS_VSCROLL | ES_LEFT | ES_WANTRETURN | - ES_MULTILINE | ES_AUTOVSCROLL, - 0, 0, 0, 0, - parent, - NULL, - ghInstance, - NULL); - - if (!newc) - newc=CreateWindowEx(WS_EX_CLIENTEDGE, - richedit?RICHEDIT_CLASS10A:"EDIT", //fall back to the earlier version - "", - WS_CHILD /*| ES_READONLY*/ | WS_VISIBLE | - WS_HSCROLL | WS_VSCROLL | ES_LEFT | ES_WANTRETURN | - ES_MULTILINE | ES_AUTOVSCROLL, - 0, 0, 0, 0, - parent, - NULL, - ghInstance, - NULL); - - if (!newc) - { //you've not got RICHEDIT installed properly, I guess - FreeLibrary(richedit); - richedit = NULL; - newc=CreateWindowEx(WS_EX_CLIENTEDGE, - "EDIT", - "", - WS_CHILD /*| ES_READONLY*/ | WS_VISIBLE | - WS_HSCROLL | WS_VSCROLL | ES_LEFT | ES_WANTRETURN | - ES_MULTILINE | ES_AUTOVSCROLL, - 0, 0, 0, 0, - parent, - NULL, - ghInstance, - NULL); - } - - //go to lucidia console, 10pt - { - CHARFORMAT cf; - memset(&cf, 0, sizeof(cf)); - cf.cbSize = sizeof(cf); - cf.dwMask = CFM_BOLD | CFM_FACE;// | CFM_SIZE; - strcpy(cf.szFaceName, "Lucida Console"); - cf.yHeight = 5; - - SendMessage(newc, EM_SETCHARFORMAT, SCF_ALL, (WPARAM)&cf); - } - - if (richedit) - { - SendMessage(newc, EM_EXLIMITTEXT, 0, 1<<20); - } - - ShowWindow(newc, SW_SHOW); - - return newc; -} - - - - -enum { - IDM_OPENDOCU=32, - IDM_OPENNEW, - IDM_GOTODEF, - IDM_SAVE, - IDM_FIND, - IDM_QUIT, - IDM_UNDO, - IDM_REDO, - IDM_ABOUT, - IDM_HIGHTLIGHT, - IDM_CASCADE, - IDM_TILE_HORIZ, - IDM_TILE_VERT, - - IDI_O_LEVEL0, - IDI_O_LEVEL1, - IDI_O_LEVEL2, - IDI_O_LEVEL3, - IDI_O_DEFAULT, - IDI_O_DEBUG, - IDI_O_CHANGE_PROGS_SRC, - IDI_O_ADDITIONALPARAMETERS, - IDI_O_OPTIMISATION, - IDI_O_COMPILER_FLAG, - IDI_O_USE, - IDI_O_APPLY, - IDI_O_TARGET, - IDI_O_SYNTAX_HIGHLIGHTING, - - IDM_FIRSTCHILD -}; - - -typedef struct editor_s { - char filename[MAX_PATH]; //abs - HWND window; - HWND editpane; - struct editor_s *next; -} editor_t; - -editor_t *editors; - -int EditorSave(editor_t *edit); -void EditFile(char *name, int line); -pbool EditorModified(editor_t *e); -int Rehighlight(editor_t *edit); - -void QueryOpenFile(void) -{ - char filename[MAX_PATH]; - char oldpath[MAX_PATH+10]; - OPENFILENAME ofn; - memset(&ofn, 0, sizeof(ofn)); - ofn.lStructSize = sizeof(ofn); - ofn.hInstance = ghInstance; - ofn.lpstrFile = filename; - ofn.nMaxFile = sizeof(filename)-1; - memset(filename, 0, sizeof(filename)); - GetCurrentDirectory(sizeof(oldpath)-1, oldpath); - if (GetOpenFileName(&ofn)) - EditFile(filename, -1); - SetCurrentDirectory(oldpath); -} - -//IDM_ stuff that needs no active menu -void GenericMenu(WPARAM wParam) -{ - switch(LOWORD(wParam)) - { - case IDM_OPENNEW: - QueryOpenFile(); - break; - - case IDM_ABOUT: - MessageBox(NULL, "FTE QuakeC Compiler\nWritten by Forethough Entertainment.\nBasically that means it was written by Spike.\n\nIt has a few cool features, like a useful IDE.\n\nSupports:\nPrecompiler (with macros)\nArrays\n+= / -= / *= / /= operations.\nSwitch statements\nfor loops\nLots of optimisations.", "About", 0); - break; - - case IDM_CASCADE: - SendMessage(mdibox, WM_MDICASCADE, 0, 0); - break; - case IDM_TILE_HORIZ: - SendMessage(mdibox, WM_MDITILE, MDITILE_HORIZONTAL, 0); - break; - case IDM_TILE_VERT: - SendMessage(mdibox, WM_MDITILE, MDITILE_VERTICAL, 0); - break; - } -} - -void EditorMenu(editor_t *editor, WPARAM wParam) -{ - switch(LOWORD(wParam)) - { - case IDM_OPENDOCU: - { - char buffer[1024]; - int total; - total = SendMessage(editor->editpane, EM_GETSELTEXT, (WPARAM)sizeof(buffer)-1, (LPARAM)buffer); - buffer[total]='\0'; - if (!total) - { - MessageBox(NULL, "There is no name currently selected.", "Whoops", 0); - break; - } - else - EditFile(buffer, -1); - } - break; - case IDM_SAVE: - EditorSave(editor); - break; - case IDM_GOTODEF: - { - char buffer[1024]; - int total; - total = SendMessage(editor->editpane, EM_GETSELTEXT, (WPARAM)sizeof(buffer)-1, (LPARAM)buffer); - buffer[total]='\0'; - if (!total) - { - MessageBox(NULL, "There is no name currently selected.", "Whoops", 0); - break; - } - else - GoToDefinition(buffer); - } - break; - case IDM_HIGHTLIGHT: - Rehighlight(editor); - break; - - case IDM_UNDO: - Edit_Undo(editor->editpane); - break; - case IDM_REDO: - Edit_Redo(editor->editpane); - break; - - default: - GenericMenu(wParam); - break; - } -} - -static LONG CALLBACK EditorWndProc(HWND hWnd,UINT message, - WPARAM wParam,LPARAM lParam) -{ - RECT rect; - HDC hdc; - PAINTSTRUCT ps; - - editor_t *editor; - for (editor = editors; editor; editor = editor->next) - { - if (editor->window == hWnd) - break; - if (editor->window == NULL) - break; //we're actually creating it now. - } - if (!editor) - goto gdefault; - - switch (message) - { - case WM_CLOSE: - case WM_QUIT: - if (EditorModified(editor)) - { - switch (MessageBox(hWnd, "Would you like to save?", editor->filename, MB_YESNOCANCEL)) - { - case IDCANCEL: - return false; - case IDYES: - if (!EditorSave(editor)) - return false; - case IDNO: - default: - break; - } - } - goto gdefault; - case WM_DESTROY: - { - editor_t *e; - if (editor == editors) - { - editors = editor->next; - free(editor); - return 0; - } - for (e = editors; e; e = e->next) - { - if (e->next == editor) - { - e->next = editor->next; - free(editor); - return 0; - } - } - MessageBox(0, "Couldn't destroy file reference", "WARNING", 0); - } - goto gdefault; - case WM_CREATE: - editor->editpane = CreateAnEditControl(hWnd); - /* - editor->editpane=CreateWindowEx(WS_EX_CLIENTEDGE, - richedit?RICHEDIT_CLASS:"EDIT", - "", - WS_CHILD | WS_VISIBLE | - WS_HSCROLL | WS_VSCROLL | ES_LEFT | ES_WANTRETURN | - ES_MULTILINE | ES_AUTOVSCROLL, - 0, 0, 0, 0, - hWnd, - NULL, - ghInstance, - NULL); -*/ - if (richedit) - { - SendMessage(editor->editpane, EM_EXLIMITTEXT, 0, 1<<31); - - SendMessage(editor->editpane, EM_SETUNDOLIMIT, 256, 256); - } - goto gdefault; - case WM_SIZE: - GetClientRect(hWnd, &rect); - SetWindowPos(editor->editpane, NULL, 0, 0, rect.right-rect.left, rect.bottom-rect.top, 0); - goto gdefault; - case WM_PAINT: - hdc=BeginPaint(hWnd,(LPPAINTSTRUCT)&ps); - - EndPaint(hWnd,(LPPAINTSTRUCT)&ps); - return TRUE; - break; - case WM_COMMAND: - if (mdibox) - goto gdefault; - EditorMenu(editor, wParam); - break; - case WM_NOTIFY: - { - NMHDR *nmhdr; - SELCHANGE *sel; - char message[2048]; - nmhdr = (NMHDR *)lParam; - switch(nmhdr->code) - { - case EN_SELCHANGE: - sel = (SELCHANGE *)nmhdr; - sprintf(message, "%s:%i - FTEQCC Editor", editor->filename, 1+Edit_LineFromChar(editor->editpane, sel->chrg.cpMin)); - SetWindowText(editor->window, message); - break; - } - } - default: - gdefault: - if (mdibox) - return DefMDIChildProc(hWnd,message,wParam,lParam); - else - return DefWindowProc(hWnd,message,wParam,lParam); - } - return 0; -} - -#if 1 -static DWORD lastcolour; -int GUIEmitText(HWND wnd, int start, char *text, int len) -{ - int c, cr; - DWORD colour; - CHARFORMAT cf; - - if (!len) - return start; - - c = text[len]; - text[len] = '\0'; - Edit_SetSel(wnd,start,start); - Edit_ReplaceSel(wnd,text); - - if (!strcmp(text, "void")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "float")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "vector")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "entity")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "local")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "string")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "struct")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "class")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "union")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "const")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "var")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "nosave")) - colour = RGB(0, 0, 255); - - else if (!strcmp(text, "goto")) - colour = RGB(255, 0, 0); - else if (!strcmp(text, "thinktime")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "if")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "else")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "switch")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "case")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "default")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "break")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "continue")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "do")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "while")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "for")) - colour = RGB(0, 0, 255); - else if (!strcmp(text, "return")) - colour = RGB(0, 0, 255); - - else if (!strcmp(text, "self")) - colour = RGB(0, 0, 127); - else if (!strcmp(text, "this")) - colour = RGB(0, 0, 127); - else if (!strcmp(text, "other")) - colour = RGB(0, 0, 127); - else if (!strcmp(text, "world")) - colour = RGB(0, 0, 127); - else if (!strcmp(text, "time")) - colour = RGB(0, 0, 127); - - - else if (!strcmp(text, "#define")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#ifdef")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#ifndef")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#else")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#endif")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#undef")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#pragma")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#includelist")) - colour = RGB(0, 128, 255); - else if (!strcmp(text, "#endlist")) - colour = RGB(0, 128, 255); - - - else if (*text == '\"') - colour = RGB(128, 0, 0); - - else if (!strncmp(text, "//", 2)) - colour = RGB(0, 127, 0); - else if (!strncmp(text, "/*", 2)) - colour = RGB(0, 127, 0); - else - colour = RGB(0, 0, 0); - - text[len] = c; - - cr = 0; - for (c = 0; c < len; c++) - if (text[c] == '\r') - cr++; - if (cr) - len-=cr; - - if (colour == lastcolour) - return start+len; - - lastcolour = colour; - - Edit_SetSel(wnd,start,start+len); - memset(&cf, 0, sizeof(cf)); - cf.cbSize = sizeof(cf); - cf.dwMask = CFM_COLOR; - cf.crTextColor = colour; - SendMessage(wnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf); - Edit_SetSel(wnd,start+len,start+len); - - return start + len; -} -void GUIFormattingPrint(HWND wnd, char *msg) -{ - int len=Edit_GetTextLength(wnd); - char *start; - CHARRANGE chrg; - lastcolour = RGB(0,0,0); - SendMessage(wnd, WM_SETREDRAW, false, 0); - chrg.cpMin = chrg.cpMax = 0; - SendMessage(wnd, EM_EXSETSEL, 0, (LPARAM) &chrg); - - for(start = msg;;) - { - if (!*msg) - break; - else if (*msg == '/' && msg[1] == '/') - { - len = GUIEmitText(wnd, len, start, msg - start); - start = msg; - - msg+=2; - while(*msg && *msg != '\n' && *msg != '\r') - msg++; - } - else if (*msg == '/' && msg[1] == '*') - { - len = GUIEmitText(wnd, len, start, msg - start); - start = msg; - msg+=2; - while(*msg) - { - if (msg[0] == '*' && msg[1] == '/') - { - msg+=2; - break; - } - msg++; - } - } - else if (*msg == '#' || *msg == '_' || (*msg >= 'A' && *msg <= 'Z') || (*msg >= 'a' && *msg <= 'z')) - { - len = GUIEmitText(wnd, len, start, msg - start); - start = msg; - msg++; - while (*msg == '_' || (*msg >= 'A' && *msg <= 'Z') || (*msg >= 'a' && *msg <= 'z' || *msg >= '0' && *msg <= '9')) - msg++; - } - else if (*msg == '\"') - { - len = GUIEmitText(wnd, len, start, msg - start); - start = msg; - msg++; - while(*msg) - { - if (*msg == '\\') - msg++; - else if (*msg == '\"') - { - msg++; - break; - } - - msg++; - } - } -/* else if (*msg <= ' ') - { - while (*msg <= ' ' && *msg) - msg++; - }*/ - else - { - msg++; - continue; - } - - len = GUIEmitText(wnd, len, start, msg - start); - start = msg; - } - len = GUIEmitText(wnd, len, start, msg - start); - start = msg; - SendMessage(wnd, WM_SETREDRAW, true, 0); -} - -int Rehighlight(editor_t *edit) -{ - int len; - char *file; - - CHARRANGE chrg; - POINT scrollpos; - - SendMessage(edit->editpane, EM_SETEVENTMASK, 0, 0); - - SendMessage(edit->editpane, EM_GETSCROLLPOS, 0, (LPARAM)&scrollpos); - SendMessage(edit->editpane, EM_EXGETSEL, 0, (LPARAM) &chrg); - - len = Edit_GetTextLength(edit->editpane); - file = malloc(len+1); - if (!file) - { - MessageBox(NULL, "Save failed - not enough mem", "Error", 0); - return false; - } - Edit_GetText(edit->editpane, file, len); - file[len] = '\0'; - - SetWindowText(edit->editpane,""); - -// GUIPrint(edit->editpane, file); - GUIFormattingPrint(edit->editpane, file); - free(file); - -// Edit_SetSel(edit->editpane, Edit_LineIndex(neweditor->editpane, 0), Edit_LineIndex(neweditor->editpane, 0)); - - InvalidateRect(edit->editpane, NULL, true); - InvalidateRect(edit->window, NULL, true); - - SendMessage(edit->editpane, EM_SETEVENTMASK, 0, ENM_SELCHANGE); - - SendMessage(edit->editpane, EM_SETSCROLLPOS, 0, (LPARAM)&scrollpos); - SendMessage(edit->editpane, EM_EXSETSEL, 0, (LPARAM) &chrg); - - UpdateWindow(edit->editpane); - RedrawWindow(edit->window, NULL, NULL, 0); - - return true; -} -#else -static void chunkcolour(HWND pane, int start, int end, DWORD colour) -{ - CHARFORMAT cf; - if (colour == RGB(0,0,0)) - return; //don't need to - Edit_SetSel(pane,start,end); - memset(&cf, 0, sizeof(cf)); - cf.cbSize = sizeof(cf); - cf.dwMask = CFM_COLOR; - cf.crTextColor = colour; - SendMessage(pane, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf); -} -void GUIFormattingPrint(HWND wnd, char *msg) -{ -} -int Rehighlight(editor_t *edit) -{ - char *file; - int c, last, len; - DWORD color; - CHARRANGE chrg; - POINT scrollpos; - - //Dsiable redraws - SendMessage(edit->editpane, WM_SETREDRAW, false, 0); - - //Don't notify us for a bit.. - SendMessage(edit->editpane, EM_SETEVENTMASK, 0, 0); - - //get state so we can restore scroll positions and things. - SendMessage(edit->editpane, EM_GETSCROLLPOS, 0, (LPARAM)&scrollpos); - SendMessage(edit->editpane, EM_EXGETSEL, 0, (LPARAM) &chrg); - - - len = Edit_GetTextLength(edit->editpane); - file = malloc(len+1); - if (!file) - { - MessageBox(NULL, "Highlight failed - not enough mem", "Error", 0); - return false; - } - Edit_GetText(edit->editpane, file, len); - file[len] = '\0'; - SetWindowText(edit->editpane,file); //this is so that we guarentee that the \rs or whatever that windows insists on inserting don't get in the way - - color = RGB(0,0,0); - for (last = 0, c = 0; c < len; c++) - { - if (file[c] == '/' && file[c+1] == '/') //do special syntax - { - chunkcolour(edit->editpane, last, c, color); - last = c; - - while(file[c] != '\n') - c++; - color = RGB(0, 127, 0); - } - else - { - chunkcolour(edit->editpane, last, c, color); - last = c; - - while(file[c] >= 'a' && file[c] <= 'z' || file[c] >= 'A' && file[c] <= 'Z' || file[c] == '_') - c++; - - color = RGB(rand(), rand(), rand()); - } - } - - free(file); - - //reenable drawing - SendMessage(edit->editpane, WM_SETREDRAW, true, 0); -} -#endif - -void EditFile(char *name, int line) -{ - char title[1024]; - int flen; - char *file; - editor_t *neweditor; - WNDCLASS wndclass; - HMENU menu, menufile, menuhelp, menunavig; - - for (neweditor = editors; neweditor; neweditor = neweditor->next) - { - if (neweditor->window && !strcmp(neweditor->filename, name)) - { - if (line >= 0) - { - Edit_SetSel(neweditor->editpane, Edit_LineIndex(neweditor->editpane, line), Edit_LineIndex(neweditor->editpane, line+1)); - Edit_ScrollCaret(neweditor->editpane); - } - if (mdibox) - SendMessage(mdibox, WM_MDIACTIVATE, (WPARAM)neweditor->window, 0); - SetFocus(neweditor->window); - SetFocus(neweditor->editpane); - return; - } - } - - flen = QCC_FileSize(name); - if (flen == -1) - { - MessageBox(NULL, "File not found.", "Error", 0); - return; - } - - neweditor = malloc(sizeof(editor_t)); - if (!neweditor) - { - MessageBox(NULL, "Low memory", "Error", 0); - return; - } - - neweditor->next = editors; - editors = neweditor; - - strncpy(neweditor->filename, name, sizeof(neweditor->filename)-1); - - if (!mdibox) - { - menu = CreateMenu(); - menufile = CreateMenu(); - menuhelp = CreateMenu(); - menunavig = CreateMenu(); - AppendMenu(menu, MF_POPUP, (UINT)menufile, "&File"); - AppendMenu(menu, MF_POPUP, (UINT)menunavig, "&Navigation"); - AppendMenu(menu, MF_POPUP, (UINT)menuhelp, "&Help"); - AppendMenu(menufile, 0, IDM_OPENNEW, "Open &new file "); - AppendMenu(menufile, 0, IDM_SAVE, "&Save "); - // AppendMenu(menufile, 0, IDM_FIND, "&Find"); - AppendMenu(menufile, 0, IDM_UNDO, "&Undo Ctrl+Z"); - AppendMenu(menufile, 0, IDM_REDO, "&Redo Ctrl+Y"); - AppendMenu(menunavig, 0, IDM_GOTODEF, "Go to definition"); - AppendMenu(menunavig, 0, IDM_OPENDOCU, "Open selected file"); - AppendMenu(menuhelp, 0, IDM_ABOUT, "About"); - AppendMenu(menu, 0, IDM_HIGHTLIGHT, "H&ighlight"); - } - - - - wndclass.style = 0; - wndclass.lpfnWndProc = (WNDPROC)EditorWndProc; - wndclass.cbClsExtra = 0; - wndclass.cbWndExtra = 0; - wndclass.hInstance = ghInstance; - wndclass.hIcon = 0; - wndclass.hCursor = LoadCursor (NULL,IDC_ARROW); - wndclass.hbrBackground = (void *)COLOR_WINDOW; - wndclass.lpszMenuName = 0; - wndclass.lpszClassName = EDIT_WINDOW_CLASS_NAME; - RegisterClass(&wndclass); - - neweditor->window = NULL; - if (mdibox) - { - MDICREATESTRUCT mcs; - - sprintf(title, "%s", name); - - mcs.szClass = EDIT_WINDOW_CLASS_NAME; - mcs.szTitle = name; - mcs.hOwner = ghInstance; - mcs.x = mcs.cx = CW_USEDEFAULT; - mcs.y = mcs.cy = CW_USEDEFAULT; - mcs.style = WS_OVERLAPPEDWINDOW; - mcs.lParam = 0; - - neweditor->window = (HWND) SendMessage (mdibox, WM_MDICREATE, 0, - (LONG) (LPMDICREATESTRUCT) &mcs); - } - else - { - sprintf(title, "%s - FTEEditor", name); - - neweditor->window=CreateWindow(EDIT_WINDOW_CLASS_NAME, title, WS_OVERLAPPEDWINDOW, - 0, 0, 640, 480, NULL, NULL, ghInstance, NULL); - } - - if (!mdibox) - SetMenu(neweditor->window, menu); - - if (!neweditor->window) - { - MessageBox(NULL, "Failed to create editor window", "Error", 0); - return; - } - - flen = QCC_FileSize(name); - file = malloc(flen+1); - QCC_ReadFile(name, file, flen); - file[flen] = 0; - - SendMessage(neweditor->editpane, EM_SETEVENTMASK, 0, 0); - - if (!fl_autohighlight) - { - GUIPrint(neweditor->editpane, file); - } - else - { - GUIFormattingPrint(neweditor->editpane, file); - } - - SendMessage(neweditor->editpane, EM_SETEVENTMASK, 0, ENM_SELCHANGE); - - if (line >= 0) - Edit_SetSel(neweditor->editpane, Edit_LineIndex(neweditor->editpane, line), Edit_LineIndex(neweditor->editpane, line+1)); - else - Edit_SetSel(neweditor->editpane, Edit_LineIndex(neweditor->editpane, 0), Edit_LineIndex(neweditor->editpane, 0)); - - Edit_ScrollCaret(neweditor->editpane); - - ShowWindow(neweditor->window, SW_SHOW); - SetFocus(mainwindow); - SetFocus(neweditor->window); - SetFocus(neweditor->editpane); -} - -int EditorSave(editor_t *edit) -{ - int len; - char *file; - len = Edit_GetTextLength(edit->editpane); - file = malloc(len+1); - if (!file) - { - MessageBox(NULL, "Save failed - not enough mem", "Error", 0); - return false; - } - Edit_GetText(edit->editpane, file, len); - if (!QCC_WriteFile(edit->filename, file, len)) - { - MessageBox(NULL, "Save failed\nCheck path and ReadOnly flags", "Failure", 0); - return false; - } - free(file); - - return true; -} -void EditorsRun(void) -{ -} - - -char *GUIReadFile(char *fname, void *buffer, int blen) -{ - editor_t *e; - for (e = editors; e; e = e->next) - { - if (e->window && !strcmp(e->filename, fname)) - { - int elen = Edit_GetTextLength(e->editpane); - Edit_GetText(e->editpane, buffer, blen); - return buffer; - } - } - - return QCC_ReadFile(fname, buffer, blen); -} - -int GUIFileSize(char *fname) -{ - editor_t *e; - for (e = editors; e; e = e->next) - { - if (e->window && !strcmp(e->filename, fname)) - { - int len = Edit_GetTextLength(e->editpane); - return len; - } - } - return QCC_FileSize(fname); -} - -pbool EditorModified(editor_t *e) -{ - char *buffer; - int elen, flen; - elen = Edit_GetTextLength(e->editpane); - flen = QCC_FileSize(e->filename); - - if (elen != flen) - return true; - - buffer = malloc(elen+flen); - Edit_GetText(e->editpane, buffer, elen); - QCC_ReadFile(e->filename, buffer+elen, flen); - if (memcmp(buffer, buffer+elen, elen)) - { - free(buffer); - return true; - } - free(buffer); - - return false; -} - - - - - - - - - - - - - -HWND optionsmenu; -HWND hexen2item; -HWND nokeywords_coexistitem; -HWND autoprototype_item; -HWND autohighlight_item; -HWND extraparmsitem; -static LONG CALLBACK OptionsWndProc(HWND hWnd,UINT message, - WPARAM wParam,LPARAM lParam) -{ - int i; - switch (message) - { - case WM_DESTROY: - optionsmenu = NULL; - break; - - case WM_COMMAND: - switch(wParam) - { - case IDI_O_USE: - case IDI_O_APPLY: - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_HIDDENINGUI) - continue; - - if (Button_GetCheck(optimisations[i].guiinfo)) - optimisations[i].flags |= FLAG_SETINGUI; - else - optimisations[i].flags &= ~FLAG_SETINGUI; - } - fl_hexen2 = Button_GetCheck(hexen2item); - for (i = 0; compiler_flag[i].enabled; i++) - { - if (compiler_flag[i].flags & FLAG_HIDDENINGUI) - continue; - if (Button_GetCheck(compiler_flag[i].guiinfo)) - compiler_flag[i].flags |= FLAG_SETINGUI; - else - compiler_flag[i].flags &= ~FLAG_SETINGUI; - } - fl_autohighlight = Button_GetCheck(autohighlight_item); - Edit_GetText(extraparmsitem, parameters, sizeof(parameters)-1); - - if (wParam == IDI_O_USE) - buttons[ID_COMPILE].washit = true; - break; - case IDI_O_CHANGE_PROGS_SRC: - { - char *s, *s2; - char filename[MAX_PATH]; - char oldpath[MAX_PATH+10]; - OPENFILENAME ofn; - memset(&ofn, 0, sizeof(ofn)); - ofn.lStructSize = sizeof(ofn); - ofn.hInstance = ghInstance; - ofn.lpstrFile = filename; - ofn.lpstrTitle = "Please find progs.src"; - ofn.nMaxFile = sizeof(filename)-1; - ofn.lpstrFilter = "QuakeC source\0*.src\0All files\0*.*\0"; - memset(filename, 0, sizeof(filename)); - GetCurrentDirectory(sizeof(oldpath)-1, oldpath); - ofn.lpstrInitialDir = oldpath; - if (GetOpenFileName(&ofn)) - { - strcpy(progssrcdir, filename); - for(s = progssrcdir; s; s = s2) - { - s2 = strchr(s+1, '\\'); - if (!s2) - break; - s = s2; - } - if (s) - { - *s = '\0'; - strcpy(progssrcname, s+1); - } - else - strcpy(progssrcname, filename); - - SetCurrentDirectory(progssrcdir); - *progssrcdir = '\0'; - } - resetprogssrc = true; - } - break; - case IDI_O_LEVEL0: - case IDI_O_LEVEL1: - case IDI_O_LEVEL2: - case IDI_O_LEVEL3: - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_HIDDENINGUI) - continue; - - if (optimisations[i].optimisationlevel<=(int)wParam-IDI_O_LEVEL0) - Button_SetCheck(optimisations[i].guiinfo, 1); - else - Button_SetCheck(optimisations[i].guiinfo, 0); - } - break; - case IDI_O_DEBUG: - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_HIDDENINGUI) - continue; - - if (optimisations[i].flags&FLAG_KILLSDEBUGGERS) - Button_SetCheck(optimisations[i].guiinfo, 0); - } - break; - case IDI_O_DEFAULT: - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_HIDDENINGUI) - continue; - - if (optimisations[i].flags & FLAG_ASDEFAULT) - Button_SetCheck(optimisations[i].guiinfo, 1); - else - Button_SetCheck(optimisations[i].guiinfo, 0); - } - break; - } - break; - case WM_HELP: - { - HELPINFO *hi; - hi = (HELPINFO *)lParam; - switch(hi->iCtrlId) - { - case IDI_O_DEFAULT: - MessageBox(hWnd, "Sets the default optimisations", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_DEBUG: - MessageBox(hWnd, "Clears all optimisations which can make your progs harder to debug", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_LEVEL0: - case IDI_O_LEVEL1: - case IDI_O_LEVEL2: - case IDI_O_LEVEL3: - MessageBox(hWnd, "Sets a specific optimisation level", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_CHANGE_PROGS_SRC: - MessageBox(hWnd, "Use this button to change your root source file.\nNote that fteqcc compiles sourcefiles from editors first, rather than saving. This means that changes are saved ONLY when you save them, but means that switching project mid-compile can result in problems.", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_ADDITIONALPARAMETERS: - MessageBox(hWnd, "Type in additional commandline parameters here. Use -Dname to define a named precompiler constant before compiling.", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_APPLY: - MessageBox(hWnd, "Apply changes shown, but do not recompile yet.", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_USE: - MessageBox(hWnd, "Apply changes shown here and recompile.", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_OPTIMISATION: - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].guiinfo == hi->hItemHandle) - { - MessageBox(hWnd, optimisations[i].description, "Help", MB_OK|MB_ICONINFORMATION); - break; - } - } - break; - case IDI_O_COMPILER_FLAG: - for (i = 0; compiler_flag[i].enabled; i++) - { - if (compiler_flag[i].guiinfo == hi->hItemHandle) - { - MessageBox(hWnd, compiler_flag[i].description, "Help", MB_OK|MB_ICONINFORMATION); - break; - } - } - break; - case IDI_O_TARGET: - MessageBox(hWnd, "Click here to compile a hexen2 compatible progs. Note that this uses the -Thexen2. There are other targets available.", "Help", MB_OK|MB_ICONINFORMATION); - break; - case IDI_O_SYNTAX_HIGHLIGHTING: - MessageBox(hWnd, "Should syntax be highlighted automatically when a file is opened?", "Help", MB_OK|MB_ICONINFORMATION); - break; - } - } - break; - default: - return DefWindowProc(hWnd,message,wParam,lParam); - } - return 0; -} -void OptionsDialog(void) -{ - HWND subsection; - RECT r; - WNDCLASS wndclass; - HWND wnd; - int i; - int flagcolums=1; - - int x; - int y; - int my; - int height; - int num; - int cflagsshown; - - if (optionsmenu) - { - BringWindowToTop(optionsmenu); - return; - } - - - memset(&wndclass, 0, sizeof(wndclass)); - wndclass.style = 0; - wndclass.lpfnWndProc = (WNDPROC)OptionsWndProc; - wndclass.cbClsExtra = 0; - wndclass.cbWndExtra = 0; - wndclass.hInstance = ghInstance; - wndclass.hIcon = 0; - wndclass.hCursor = LoadCursor (NULL,IDC_ARROW); - wndclass.hbrBackground = (void *)COLOR_WINDOW; - wndclass.lpszMenuName = 0; - wndclass.lpszClassName = OPTIONS_WINDOW_CLASS_NAME; - RegisterClass(&wndclass); - - height = 0; - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_HIDDENINGUI) - continue; - - height++; - } - - cflagsshown = 2; - for (i = 0; compiler_flag[i].enabled; i++) - { - if (compiler_flag[i].flags & FLAG_HIDDENINGUI) - continue; - - cflagsshown++; - } - - height = (height-1)/2; - - while (cflagsshown > ((480-(88+40))/16)*(flagcolums)) - flagcolums++; - - if (height < (cflagsshown+flagcolums-1)/flagcolums) - height = (cflagsshown+flagcolums-1)/flagcolums; - - r.right = 408 + flagcolums*168; - if (r.right < 640) - r.right = 640; - - height *= 16; - - height += 88+40; - - r.left = GetSystemMetrics(SM_CXSCREEN)/2-320; - r.top = GetSystemMetrics(SM_CYSCREEN)/2-240; - r.bottom = r.top + height; - r.right += r.left; - - - - AdjustWindowRectEx (&r, WS_CAPTION|WS_SYSMENU, FALSE, 0); - - optionsmenu=CreateWindowEx(WS_EX_CONTEXTHELP, OPTIONS_WINDOW_CLASS_NAME, "Options - FTE QuakeC compiler", WS_CAPTION|WS_SYSMENU, - r.left, r.top, r.right-r.left, r.bottom-r.top, NULL, NULL, ghInstance, NULL); - - subsection = CreateWindow("BUTTON", "Optimisations", WS_CHILD|WS_VISIBLE|BS_GROUPBOX, - 0, 0, 400, height-48, optionsmenu, NULL, ghInstance, NULL); - - num = 0; - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_HIDDENINGUI) - { - optimisations[i].guiinfo = NULL; - continue; - } - - optimisations[i].guiinfo = wnd = CreateWindow("BUTTON",optimisations[i].fullname, - WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, - 8+200*(num&1),16+16*(num/2),200-16,16, - subsection, - (HMENU)IDI_O_OPTIMISATION, - ghInstance, - NULL); - - if (optimisations[i].flags&FLAG_SETINGUI) - Button_SetCheck(wnd, 1); - else - Button_SetCheck(wnd, 0); - - num++; - } - - CreateWindow("BUTTON","O0", - WS_CHILD | WS_VISIBLE, - 8,height-88,64,32, - optionsmenu, - (HMENU)IDI_O_LEVEL0, - ghInstance, - NULL); - CreateWindow("BUTTON","O1", - WS_CHILD | WS_VISIBLE, - 8+64,height-88,64,32, - optionsmenu, - (HMENU)IDI_O_LEVEL1, - ghInstance, - NULL); - CreateWindow("BUTTON","O2", - WS_CHILD | WS_VISIBLE, - 8+64*2,height-88,64,32, - optionsmenu, - (HMENU)IDI_O_LEVEL2, - ghInstance, - NULL); - CreateWindow("BUTTON","O3", - WS_CHILD | WS_VISIBLE, - 8+64*3,height-88,64,32, - optionsmenu, - (HMENU)IDI_O_LEVEL3, - ghInstance, - NULL); - CreateWindow("BUTTON","Debug", - WS_CHILD | WS_VISIBLE, - 8+64*4,height-88,64,32, - optionsmenu, - (HMENU)IDI_O_DEBUG, - ghInstance, - NULL); - CreateWindow("BUTTON","Default", - WS_CHILD | WS_VISIBLE, - 8+64*5,height-88,64,32, - optionsmenu, - (HMENU)IDI_O_DEFAULT, - ghInstance, - NULL); - CreateWindow("BUTTON","Apply", - WS_CHILD | WS_VISIBLE, - 8,height-40,64,32, - optionsmenu, - (HMENU)IDI_O_APPLY, - ghInstance, - NULL); - CreateWindow("BUTTON","Use", - WS_CHILD | WS_VISIBLE, - 8+64,height-40,64,32, - optionsmenu, - (HMENU)IDI_O_USE, - ghInstance, - NULL); - CreateWindow("BUTTON","progs.src", - WS_CHILD | WS_VISIBLE, - 8+64*2,height-40,64,32, - optionsmenu, - (HMENU)IDI_O_CHANGE_PROGS_SRC, - ghInstance, - NULL); - - - - y=4; - hexen2item = wnd = CreateWindow("BUTTON","HexenC", - WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, - 408,y,200-16,16, - optionsmenu, - (HMENU)IDI_O_TARGET, - ghInstance, - NULL); - y+=16; - if (fl_hexen2) - Button_SetCheck(wnd, 1); - else - Button_SetCheck(wnd, 0); - - autohighlight_item = wnd = CreateWindow("BUTTON","Syntax Highlighting", - WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, - 408,y,200-16,16, - optionsmenu, - (HMENU)IDI_O_SYNTAX_HIGHLIGHTING, - ghInstance, - NULL); - y+=16; - if (fl_autohighlight) - Button_SetCheck(wnd, 1); - else - Button_SetCheck(wnd, 0); - - x = 408; - my = y; - for (i = 0; compiler_flag[i].enabled; i++) - { - if (compiler_flag[i].flags & FLAG_HIDDENINGUI) - { - compiler_flag[i].guiinfo = NULL; - continue; - } - - if (y > height-(88+40)) - { - y = 4; - x += 168; - } - - compiler_flag[i].guiinfo = wnd = CreateWindow("BUTTON",compiler_flag[i].fullname, - WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, - x,y,168,16, - optionsmenu, - (HMENU)IDI_O_COMPILER_FLAG, - ghInstance, - NULL); - y+=16; - - if (my < y) - my = y; - - if (compiler_flag[i].flags & FLAG_SETINGUI) - Button_SetCheck(wnd, 1); - else - Button_SetCheck(wnd, 0); - } - - CreateWindow("STATIC","Extra Parameters:", - WS_CHILD | WS_VISIBLE, - 408,my,200-16,16, - optionsmenu, - (HMENU)0, - ghInstance, - NULL); - my+=16; - extraparmsitem = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT",parameters, - WS_CHILD | WS_VISIBLE|ES_LEFT | ES_WANTRETURN | - ES_MULTILINE | ES_AUTOVSCROLL, - 408,my,r.right-r.left - 408 - 8,height-my-4, - optionsmenu, - (HMENU)IDI_O_ADDITIONALPARAMETERS, - ghInstance, - NULL); - - ShowWindow(optionsmenu, SW_SHOWDEFAULT); -} - - - - - - - - - - - -#undef printf - - - -static LONG CALLBACK MainWndProc(HWND hWnd,UINT message, - WPARAM wParam,LPARAM lParam) -{ - int width; - int i; - RECT rect; - HDC hdc; - PAINTSTRUCT ps; - switch (message) - { - case WM_CREATE: - { - CLIENTCREATESTRUCT ccs; - - HMENU rootmenu, windowmenu, m; - rootmenu = CreateMenu(); - - AppendMenu(rootmenu, MF_POPUP, (UINT)(m = CreateMenu()), "&File"); - AppendMenu(m, 0, IDM_OPENNEW, "Open &new file "); - AppendMenu(m, 0, IDM_SAVE, "&Save "); - // AppendMenu(m, 0, IDM_FIND, "&Find"); - AppendMenu(m, 0, IDM_UNDO, "&Undo Ctrl+Z"); - AppendMenu(m, 0, IDM_REDO, "&Redo Ctrl+Y"); - AppendMenu(rootmenu, MF_POPUP, (UINT)(m = CreateMenu()), "&Navigation"); - AppendMenu(m, 0, IDM_GOTODEF, "Go to definition"); - AppendMenu(m, 0, IDM_OPENDOCU, "Open selected file"); - AppendMenu(rootmenu, MF_POPUP, (UINT)(m = windowmenu = CreateMenu()), "&Window"); - AppendMenu(m, 0, IDM_CASCADE, "&Cascade"); - AppendMenu(m, 0, IDM_TILE_HORIZ, "Tile &Horizontally"); - AppendMenu(m, 0, IDM_TILE_VERT, "Tile &Vertically"); - AppendMenu(rootmenu, MF_POPUP, (UINT)(m = CreateMenu()), "&Help"); - AppendMenu(m, 0, IDM_ABOUT, "About"); - - SetMenu(hWnd, rootmenu); - - // Retrieve the handle to the window menu and assign the - // first child window identifier. - - memset(&ccs, 0, sizeof(ccs)); - ccs.hWindowMenu = windowmenu; - ccs.idFirstChild = IDM_FIRSTCHILD; - - // Create the MDI client window. - - mdibox = CreateWindow( "MDICLIENT", (LPCTSTR) NULL, - WS_CHILD | WS_CLIPCHILDREN | WS_VSCROLL | WS_HSCROLL, - 0, 0, 320, 200, hWnd, (HMENU) 0xCAC, ghInstance, (LPSTR) &ccs); - ShowWindow(mdibox, SW_SHOW); - - projecttree = CreateWindow(WC_TREEVIEW, (LPCTSTR) NULL, - WS_CHILD | WS_CLIPCHILDREN | WS_VSCROLL | WS_HSCROLL - | TVS_HASBUTTONS |TVS_LINESATROOT|TVS_HASLINES, - 0, 0, 320, 200, hWnd, (HMENU) 0xCAC, ghInstance, (LPSTR) &ccs); - ShowWindow(projecttree, SW_SHOW); - - if (projecttree) - { - gotodefbox = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", (LPCTSTR) NULL, - WS_CHILD | WS_CLIPCHILDREN, - 0, 0, 320, 200, hWnd, (HMENU) 0xCAC, ghInstance, (LPSTR) NULL); - ShowWindow(gotodefbox, SW_SHOW); - - gotodefaccept = CreateWindowEx(WS_EX_CLIENTEDGE, "BUTTON", "GO", - WS_CHILD | WS_CLIPCHILDREN | BS_DEFPUSHBUTTON, - 0, 0, 320, 200, hWnd, (HMENU) 0x4404, ghInstance, (LPSTR) NULL); - ShowWindow(gotodefaccept, SW_SHOW); - } - } - break; - - case WM_DESTROY: - mainwindow = NULL; - break; - - case WM_SIZE: - GetClientRect(mainwindow, &rect); - if (projecttree) - { - SetWindowPos(projecttree, NULL, 0, 0, 192, rect.bottom-rect.top - 34 - 24, 0); - - SetWindowPos(gotodefbox, NULL, 0, rect.bottom-rect.top - 33 - 24, 160, 24, 0); - SetWindowPos(gotodefaccept, NULL, 160, rect.bottom-rect.top - 33 - 24, 32, 24, 0); - SetWindowPos(mdibox?mdibox:outputbox, NULL, 192, 0, rect.right-rect.left-192, rect.bottom-rect.top - 32, 0); - } - else - SetWindowPos(mdibox?mdibox:outputbox, NULL, 0, 0, rect.right-rect.left, rect.bottom-rect.top - 32, 0); - width = (rect.right-rect.left); - width/=NUMBUTTONS; - for (i = 0; i < NUMBUTTONS; i++) - { - SetWindowPos(buttons[i].hwnd, NULL, width*i, rect.bottom-rect.top - 32, width, 32, 0); - } - break; - case WM_PAINT: - hdc=BeginPaint(hWnd,(LPPAINTSTRUCT)&ps); - - EndPaint(hWnd,(LPPAINTSTRUCT)&ps); - return TRUE; - break; - case WM_COMMAND: - if (wParam == 0x4404) - { - GetWindowText(gotodefbox, finddef, sizeof(finddef)-1); - return true; - } - if (LOWORD(wParam)>0 && LOWORD(wParam) <= NUMBUTTONS) - { - if (LOWORD(wParam)) - buttons[LOWORD(wParam)-1].washit = 1; - break; - } - if (LOWORD(wParam) < IDM_FIRSTCHILD) - { - HWND ew; - editor_t *editor; - - ew = (HWND)SendMessage(mdibox, WM_MDIGETACTIVE, 0, 0); - - for (editor = editors; editor; editor = editor->next) - { - if (editor->window == ew) - break; - } - if (editor) - EditorMenu(editor, wParam); - else - GenericMenu(wParam); - break; - } - break; - case WM_NOTIFY: - if (lParam) - { - NMHDR *nm; - HANDLE item; - TVITEM i; - char filename[256]; - char itemtext[256]; - int oldlen; - int newlen; - nm = (NMHDR*)lParam; - if (nm->hwndFrom == projecttree) - { - switch(nm->code) - { - case NM_DBLCLK: - item = TreeView_GetSelection(projecttree); - i.hItem = item; - i.mask = TVIF_TEXT; - i.pszText = itemtext; - i.cchTextMax = sizeof(itemtext)-1; - if (!TreeView_GetItem(projecttree, &i)) - return 0; - strcpy(filename, i.pszText); - while(item) - { - item = TreeView_GetParent(projecttree, item); - i.hItem = item; - if (!TreeView_GetItem(projecttree, &i)) - break; - if (!TreeView_GetParent(projecttree, item)) - break; - - oldlen = strlen(filename); - newlen = strlen(i.pszText); - memmove(filename+newlen+1, filename, oldlen+1); - filename[newlen] = '/'; - strncpy(filename, i.pszText, newlen); - } - EditFile(filename, -1); - break; - } - } - } - default: - if (mdibox) - return DefFrameProc(hWnd,mdibox,message,wParam,lParam); - else - return DefWindowProc(hWnd,message,wParam,lParam); - } - return 0; -} - -static LONG CALLBACK OutputWindowProc(HWND hWnd,UINT message, - WPARAM wParam,LPARAM lParam) -{ - RECT rect; - switch (message) - { - case WM_DESTROY: - outputwindow = NULL; - outputbox = NULL; - break; - case WM_CREATE: - outputbox = CreateAnEditControl(hWnd); - case WM_SIZE: - GetClientRect(hWnd, &rect); - SetWindowPos(outputbox, NULL, 0, 0, rect.right-rect.left, rect.bottom-rect.top, 0); - - default: - return DefMDIChildProc(hWnd,message,wParam,lParam); - } - return 0; -} - -void GUIPrint(HWND wnd, char *msg) -{ - MSG wmsg; - int len; - static int writing; - - if (writing) - return; - if (!mainwindow) - { - printf("%s", msg); - return; - } - writing=true; - len=Edit_GetTextLength(wnd); -/* if ((unsigned)len>(32767-strlen(msg))) - Edit_SetSel(wnd,0,len); - else*/ - Edit_SetSel(wnd,len,len); - Edit_ReplaceSel(wnd,msg); - - while (PeekMessage (&wmsg, NULL, 0, 0, PM_NOREMOVE)) - { - if (!GetMessage (&wmsg, NULL, 0, 0)) - break; - TranslateMessage (&wmsg); - DispatchMessage (&wmsg); - } - writing=false; -} -int GUIEmitOutputText(HWND wnd, int start, char *text, int len, DWORD colour) -{ - int c, cr; - CHARFORMAT cf; - - if (!len) - return start; - - c = text[len]; - text[len] = '\0'; - Edit_SetSel(wnd,start,start); - Edit_ReplaceSel(wnd,text); - - text[len] = c; - - cr = 0; - for (c = 0; c < len; c++) - if (text[c] == '\r') - cr++; - if (cr) - len-=cr; - - Edit_SetSel(wnd,start,start+len); - memset(&cf, 0, sizeof(cf)); - cf.cbSize = sizeof(cf); - cf.dwMask = CFM_COLOR; - cf.crTextColor = colour; - SendMessage(wnd, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf); - Edit_SetSel(wnd,start+len,start+len); - - return start + len; -} -int outlen; -int GUIprintf(const char *msg, ...) -{ - va_list argptr; - char buf[1024]; - char rn[3] = "\n"; - char *st, *s; - int args; - MSG wmsg; - - DWORD col; - - va_start (argptr,msg); - args = QC_vsnprintf (buf,sizeof(buf)-1, msg,argptr); - va_end (argptr); - - printf("%s", buf); - if (logfile) - fprintf(logfile, "%s", buf); - - if (!*buf) - { - SetWindowText(outputbox,""); - outlen = 0; - return 0; - } - - if (strstr(buf, "warning: ")) - col = RGB(128, 128, 0); - else if (strstr(buf, "error: ")) - col = RGB(255, 0, 0); - else - col = RGB(0, 0, 0); - - s = st = buf; - while(*s) - { - if (*s == '\n') - { - *s = '\0'; - if (*st) - outlen = GUIEmitOutputText(outputbox, outlen, st, strlen(st), col); - outlen = GUIEmitOutputText(outputbox, outlen, rn, 1, col); - st = s+1; - } - - s++; - } - if (*st) - outlen = GUIEmitOutputText(outputbox, outlen, st, strlen(st), col); - - while (PeekMessage (&wmsg, NULL, 0, 0, PM_NOREMOVE)) - { - if (!GetMessage (&wmsg, NULL, 0, 0)) - break; - TranslateMessage (&wmsg); - DispatchMessage (&wmsg); - } -/* - s = st = buf; - while(*s) - { - if (*s == '\n') - { - *s = '\0'; - if (*st) - GUIPrint(outputbox, st); - GUIPrint(outputbox, "\r\n"); - st = s+1; - } - - s++; - } - if (*st) - GUIPrint(outputbox, st); -*/ - return args; -} - -#undef Sys_Error - -void Sys_Error(const char *text, ...); -void RunCompiler(char *args) -{ - char *argv[64]; - int argc; - progexterns_t ext; - progfuncs_t funcs; - - memset(&funcs, 0, sizeof(funcs)); - funcs.parms = &ext; - memset(&ext, 0, sizeof(ext)); - funcs.parms->ReadFile = GUIReadFile; - funcs.parms->FileSize = GUIFileSize; - funcs.parms->WriteFile = QCC_WriteFile; - funcs.parms->printf = GUIprintf; - funcs.parms->Sys_Error = Sys_Error; - GUIprintf(""); - - if (logfile) - fclose(logfile); - if (fl_log) - logfile = fopen("fteqcc.log", "wb"); - else - logfile = NULL; - - argc = GUI_BuildParms(args, argv); - - CompileParams(&funcs, true, argc, argv); - - if (logfile) - fclose(logfile); -} - - -void CreateOutputWindow(void) -{ - WNDCLASS wndclass; - MDICREATESTRUCT mcs; - - if (!mdibox) //should already be created - return; - - if (!outputwindow) - { - wndclass.style = 0; - wndclass.lpfnWndProc = (WNDPROC)OutputWindowProc; - wndclass.cbClsExtra = 0; - wndclass.cbWndExtra = 0; - wndclass.hInstance = ghInstance; - wndclass.hIcon = 0; - wndclass.hCursor = LoadCursor (NULL,IDC_ARROW); - wndclass.hbrBackground = (void *)COLOR_WINDOW; - wndclass.lpszMenuName = 0; - wndclass.lpszClassName = MAIN_WINDOW_CLASS_NAME; - RegisterClass(&wndclass); - - - - mcs.szClass = MAIN_WINDOW_CLASS_NAME; - mcs.szTitle = "Compiler output"; - mcs.hOwner = ghInstance; - mcs.x = mcs.cx = CW_USEDEFAULT; - mcs.y = mcs.cy = CW_USEDEFAULT; - mcs.style = WS_OVERLAPPEDWINDOW; - mcs.lParam = 0; - - outputwindow = (HWND) SendMessage (mdibox, WM_MDICREATE, 0, - (LONG) (LPMDICREATESTRUCT) &mcs); - - ShowWindow(outputwindow, SW_SHOW); - } - - //bring it to the front. - SendMessage(mdibox, WM_MDIACTIVATE, (WPARAM)outputwindow, 0); -} - -//progssrcname should already have been set. -void SetProgsSrc(void) -{ - FILE *f; - - HANDLE rootitem, pi; - TVINSERTSTRUCT item; - TV_ITEM parent; - char parentstring[256]; - memset(&item, 0, sizeof(item)); - memset(&parent, 0, sizeof(parent)); - - if (projecttree) - { - int size; - char *buffer; - char *slash; - - f = fopen (progssrcname, "rb"); - if (!f) - return; - fseek(f, 0, SEEK_END); - size = ftell(f); - fseek(f, 0, SEEK_SET); - buffer = malloc(size+1); - if (!buffer) - { - fclose(f); - return; - } - buffer[size] = '\0'; - fread(buffer, 1, size, f); - fclose(f); - - pr_file_p = QCC_COM_Parse(buffer); - if (*qcc_token == '#') - { - free(buffer); //aaaahhh! newstyle! - return; - } - - pr_file_p = QCC_COM_Parse(pr_file_p); //we dont care about the produced progs.dat - - - item.hParent = TVI_ROOT; - item.hInsertAfter = TVI_SORT; - item.item.pszText = progssrcname; - item.item.mask = TVIF_TEXT; - rootitem = (HANDLE)SendMessage(projecttree,TVM_INSERTITEM,0,(LPARAM)&item); - while(pr_file_p) - { - pi = item.hParent = rootitem; - item.item.pszText = qcc_token; - while(slash = strchr(item.item.pszText, '/')) - { - *slash = '\0'; - item.hParent = TreeView_GetChild(projecttree, item.hParent); - do - { - parent.hItem = item.hParent; - parent.mask = TVIF_TEXT; - parent.pszText = parentstring; - parent.cchTextMax = sizeof(parentstring)-1; - if (TreeView_GetItem(projecttree, &parent)) - { - if (!stricmp(parent.pszText, item.item.pszText)) - break; - } - } while(item.hParent=TreeView_GetNextSibling(projecttree, item.hParent)); - if (!item.hParent) - { //add a directory. - item.hParent = pi; - pi = (HANDLE)SendMessage(projecttree,TVM_INSERTITEM,0,(LPARAM)&item); - item.hParent = pi; - } - else pi = item.hParent; - - item.item.pszText = slash+1; - } - SendMessage(projecttree,TVM_INSERTITEM,0,(LPARAM)&item); - pr_file_p = QCC_COM_Parse(pr_file_p); - } - - free(buffer); - } -} - -int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) -{ - unsigned int i; - WNDCLASS wndclass; - ghInstance= hInstance; - - GUI_SetDefaultOpts(); - - if(strstr(lpCmdLine, "-stdout")) - { - GUI_ParseCommandLine(lpCmdLine); - RunCompiler(lpCmdLine); - return 0; - } - - if (!*lpCmdLine) - { - int len; - FILE *f; - char *s; - - f = fopen("fteqcc.cfg", "rb"); - if (f) - { - fseek(f, 0, SEEK_END); - len = ftell(f); - fseek(f, 0, SEEK_SET); - lpCmdLine = malloc(len+1); - fread(lpCmdLine, 1, len, f); - lpCmdLine[len] = '\0'; - fclose(f); - - while(s = strchr(lpCmdLine, '\r')) - *s = ' '; - while(s = strchr(lpCmdLine, '\n')) - *s = ' '; - } - } - - GUI_ParseCommandLine(lpCmdLine); - - GUI_RevealOptions(); - - if (/*!fl_acc &&*/ !*progssrcname) - { - strcpy(progssrcname, "preprogs.src"); - if (QCC_FileSize(progssrcname)==-1) - strcpy(progssrcname, "progs.src"); - if (QCC_FileSize(progssrcname)==-1) - { - char *s, *s2; - char filename[MAX_PATH]; - char oldpath[MAX_PATH+10]; - OPENFILENAME ofn; - memset(&ofn, 0, sizeof(ofn)); - ofn.lStructSize = sizeof(ofn); - ofn.hInstance = ghInstance; - ofn.lpstrFile = filename; - ofn.lpstrTitle = "Please find progs.src"; - ofn.nMaxFile = sizeof(filename)-1; - ofn.lpstrFilter = "QuakeC source\0*.src\0All files\0*.*\0"; - memset(filename, 0, sizeof(filename)); - GetCurrentDirectory(sizeof(oldpath)-1, oldpath); - ofn.lpstrInitialDir = oldpath; - if (GetOpenFileName(&ofn)) - { - strcpy(progssrcdir, filename); - for(s = progssrcdir; s; s = s2) - { - s2 = strchr(s+1, '\\'); - if (!s2) - break; - s = s2; - } - if (s) - { - *s = '\0'; - strcpy(progssrcname, s+1); - } - else - strcpy(progssrcname, filename); - } - else - { - MessageBox(NULL, "You didn't select a file", "Error", 0); - return 0; - } - SetCurrentDirectory(progssrcdir); - *progssrcdir = '\0'; - } - } - - resetprogssrc = true; - - wndclass.style = 0; - wndclass.lpfnWndProc = (WNDPROC)MainWndProc; - wndclass.cbClsExtra = 0; - wndclass.cbWndExtra = 0; - wndclass.hInstance = ghInstance; - wndclass.hIcon = 0; - wndclass.hCursor = LoadCursor (NULL,IDC_ARROW); - wndclass.hbrBackground = (void *)COLOR_WINDOW; - wndclass.lpszMenuName = 0; - wndclass.lpszClassName = MDI_WINDOW_CLASS_NAME; - RegisterClass(&wndclass); - - mainwindow=CreateWindow(MDI_WINDOW_CLASS_NAME, "FTE QuakeC compiler", WS_OVERLAPPEDWINDOW, - 0, 0, 640, 480, NULL, NULL, ghInstance, NULL); - - if (mdibox) - { - SetWindowText(mainwindow, "FTE QuakeC Development Suite"); - } - - if (!mainwindow) - { - MessageBox(NULL, "Failed to create main window", "Error", 0); - return 0; - } - - InitCommonControls(); -/* - outputbox=CreateWindowEx(WS_EX_CLIENTEDGE, - "EDIT", - "", - WS_CHILD | ES_READONLY | WS_VISIBLE | - WS_VSCROLL | ES_LEFT | ES_WANTRETURN | - ES_MULTILINE | ES_AUTOVSCROLL, - 0, 0, 0, 0, - mainwindow, - NULL, - ghInstance, - NULL); -*/ - - if (!mdibox) - outputbox = CreateAnEditControl(mainwindow); - - for (i = 0; i < NUMBUTTONS; i++) - { - buttons[i].hwnd = CreateWindowEx(WS_EX_CLIENTEDGE, - "BUTTON", - buttons[i].text, - WS_CHILD | WS_VISIBLE, - 0, 0, 5, 5, - mainwindow, - (HMENU)(i+1), - ghInstance, - NULL); - } - - ShowWindow(mainwindow, SW_SHOWDEFAULT); - - if (fl_compileonstart) - { - CreateOutputWindow(); - RunCompiler(lpCmdLine); - } - else - { - if (mdibox) - { - buttons[ID_EDIT].washit = true; - } - else - { - GUIprintf("Welcome to FTE QCC\n"); - GUIprintf("Source file: "); - GUIprintf(progssrcname); - GUIprintf("\n"); - - RunCompiler("-?"); - } - } - - while(mainwindow || editors) - { - MSG msg; - - if (resetprogssrc) - { //this here, with the compiler below, means that we don't run recursivly. - resetprogssrc = false; - SetProgsSrc(); - } - - EditorsRun(); - - while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) - { - if (!GetMessage (&msg, NULL, 0, 0)) - break; - if (!mdibox || !TranslateMDISysAccel(mdibox, &msg)) - { - TranslateMessage (&msg); - DispatchMessage (&msg); - } - } - - if (mainwindow) - { - i = Edit_GetSel(outputbox); - if ((i>>16) != (i&0xffff) && i != -1) //some text is selected. - { - int bytes; - char line[1024]; - char *colon1, *colon2 = NULL; - - int l1; - int l2; - - l1 = Edit_LineFromChar(outputbox, i&0xffff); - l2 = Edit_LineFromChar(outputbox, (i>>16)&0xffff); - if (l1 == l2) - { - bytes = Edit_GetLine(outputbox, Edit_LineFromChar(outputbox, i&0xffff), line, sizeof(line)-1); - line[bytes] = 0; - - for (colon1 = line+strlen(line)-1; *colon1 <= ' ' && colon1>=line; colon1--) - *colon1 = '\0'; - if (!strncmp(line, "warning: ", 9)) - memmove(line, line+9, sizeof(line)); - colon1=line; - do - { - colon1 = strchr(colon1+1, ':'); - } while (colon1 && colon1[1] == '\\'); - - if (colon1) - { - colon2 = strchr(colon1+1, ':'); - while (colon2 && colon2[1] == '\\') - { - colon2 = strchr(colon2+1, ':'); - } - if (colon2) - { - *colon1 = '\0'; - *colon2 = '\0'; - EditFile(line, atoi(colon1+1)-1); - } - else if (!strncmp(line, "Source file: ", 13)) - EditFile(line+13, -1); - else if (!strncmp(line, "Including: ", 11)) - EditFile(line+11, -1); - } - else if (!strncmp(line, "compiling ", 10)) - EditFile(line+10, -1); - else if (!strncmp(line, "prototyping ", 12)) - EditFile(line+12, -1); - Edit_SetSel(outputbox, i&0xffff, i&0xffff); //deselect it. - } - } - - if (buttons[ID_COMPILE].washit) - { - CreateOutputWindow(); - RunCompiler(parameters); - - buttons[ID_COMPILE].washit = false; - } - if (buttons[ID_EDIT].washit) - { - buttons[ID_EDIT].washit = false; - EditFile(progssrcname, -1); - } - if (buttons[ID_OPTIONS].washit) - { - buttons[ID_OPTIONS].washit = false; - OptionsDialog(); - } - if (buttons[ID_QUIT].washit) - { - buttons[ID_QUIT].washit = false; - DestroyWindow(mainwindow); - } - } - - if (*finddef) - { - GoToDefinition(finddef); - *finddef = '\0'; - } - - Sleep(10); - } - - return 0; -} diff --git a/misc/mediasource/extra/fteqcc-src/qccguistuff.c b/misc/mediasource/extra/fteqcc-src/qccguistuff.c deleted file mode 100644 index b9555312..00000000 --- a/misc/mediasource/extra/fteqcc-src/qccguistuff.c +++ /dev/null @@ -1,325 +0,0 @@ -#include "qcc.h" -#include "gui.h" - -//common gui things - -pbool fl_hexen2; -pbool fl_autohighlight; -pbool fl_compileonstart; -pbool fl_showall; -pbool fl_log; - -char parameters[16384]; -char progssrcname[256]; -char progssrcdir[256]; - -int qccpersisthunk = 1; -void GoToDefinition(char *name) -{ - QCC_def_t *def; - QCC_dfunction_t *fnc; - - char *strip; //trim whitespace (for convieniance). - while (*name <= ' ' && *name) - name++; - for (strip = name + strlen(name)-1; *strip; strip++) - { - if (*strip <= ' ') - *strip = '\0'; - else //got some part of a word - break; - } - - if (!globalstable.numbuckets) - { - GUI_DialogPrint("Not found", "You need to compile first."); - return; - } - - - def = QCC_PR_GetDef(NULL, name, NULL, false, 0, false); - - if (def) - { - if (def->type->type == ev_function && def->constant) - { - fnc = &functions[((int *)qcc_pr_globals)[def->ofs]]; - if (fnc->first_statement>=0 && fnc->s_file) - { - EditFile(fnc->s_file+strings, statement_linenums[fnc->first_statement]); - return; - } - } - if (!def->s_file) - GUI_DialogPrint("Not found", "Global definition of var was not specified."); - else - EditFile(def->s_file+strings, def->s_line-1); - } - else - GUI_DialogPrint("Not found", "Global instance of var was not found."); -} - - - - -//this function takes the windows specified commandline and strips out all the options menu items. -void GUI_ParseCommandLine(char *args) -{ - int paramlen=0; - int l, p; - char *next; - while(*args) - { - while (*args <= ' ' && *args) - args++; - - for (next = args; *next>' '; next++) - ; - - strncpy(parameters+paramlen, args, next-args); - parameters[paramlen+next-args] = '\0'; - l = strlen(parameters+paramlen)+1; - - if (!strnicmp(parameters+paramlen, "-O", 2) || !strnicmp(parameters+paramlen, "/O", 2)) - { //strip out all -O - if (parameters[paramlen+2]) - { - if (parameters[paramlen+2] >= '0' && parameters[paramlen+2] <= '3') - { - p = parameters[paramlen+2]-'0'; - for (l = 0; optimisations[l].enabled; l++) - { - if (optimisations[l].optimisationlevel<=p) - optimisations[l].flags |= FLAG_SETINGUI; - else - optimisations[l].flags &= ~FLAG_SETINGUI; - } - } - else if (!strncmp(parameters+paramlen+2, "no-", 3)) - { - if (parameters[paramlen+5]) - { - for (p = 0; optimisations[p].enabled; p++) - if ((*optimisations[p].abbrev && !strcmp(parameters+paramlen+5, optimisations[p].abbrev)) || !strcmp(parameters+paramlen+5, optimisations[p].fullname)) - { - optimisations[p].flags &= ~FLAG_SETINGUI; - break; - } - - if (!optimisations[p].enabled) - { - parameters[paramlen+next-args] = ' '; - paramlen += l; - } - } - } - else - { - for (p = 0; optimisations[p].enabled; p++) - if ((*optimisations[p].abbrev && !strcmp(parameters+paramlen+2, optimisations[p].abbrev)) || !strcmp(parameters+paramlen+2, optimisations[p].fullname)) - { - optimisations[p].flags |= FLAG_SETINGUI; - break; - } - - if (!optimisations[p].enabled) - { - parameters[paramlen+next-args] = ' '; - paramlen += l; - } - } - } - } -/* - else if (!strnicmp(parameters+paramlen, "-Fno-kce", 8) || !strnicmp(parameters+paramlen, "/Fno-kce", 8)) //keywords stuph - { - fl_nokeywords_coexist = true; - } - else if (!strnicmp(parameters+paramlen, "-Fkce", 5) || !strnicmp(parameters+paramlen, "/Fkce", 5)) - { - fl_nokeywords_coexist = false; - } - else if (!strnicmp(parameters+paramlen, "-Facc", 5) || !strnicmp(parameters+paramlen, "/Facc", 5)) - { - fl_acc = true; - } - else if (!strnicmp(parameters+paramlen, "-autoproto", 10) || !strnicmp(parameters+paramlen, "/autoproto", 10)) - { - fl_autoprototype = true; - } -*/ - else if (!strnicmp(parameters+paramlen, "-showall", 8) || !strnicmp(parameters+paramlen, "/showall", 8)) - { - fl_showall = true; - } - else if (!strnicmp(parameters+paramlen, "-ah", 3) || !strnicmp(parameters+paramlen, "/ah", 3)) - { - fl_autohighlight = true; - } - else if (!strnicmp(parameters+paramlen, "-ac", 3) || !strnicmp(parameters+paramlen, "/ac", 3)) - { - fl_compileonstart = true; - } - else if (!strnicmp(parameters+paramlen, "-log", 4) || !strnicmp(parameters+paramlen, "/log", 4)) - { - fl_log = true; - } - else if (!strnicmp(parameters+paramlen, "-srcfile", 8) || !strnicmp(parameters+paramlen, "/srcfile", 8)) - { - while (*next == ' ') - next++; - - l = 0; - while (*next != ' ' && *next) - progssrcname[l++] = *next++; - progssrcname[l] = 0; - } - else if (!strnicmp(parameters+paramlen, "-T", 2) || !strnicmp(parameters+paramlen, "/T", 2)) //the target - { - if (!strnicmp(parameters+paramlen+2, "h2", 2)) - { - fl_hexen2 = true; - } - else - { - fl_hexen2 = false; - parameters[paramlen+next-args] = ' '; - paramlen += l; - } - } - else - { - parameters[paramlen+next-args] = ' '; - paramlen += l; - } - - args=next; - } - if (paramlen) - parameters[paramlen-1] = '\0'; - else - *parameters = '\0'; -} - -void GUI_SetDefaultOpts(void) -{ - int i; - for (i = 0; compiler_flag[i].enabled; i++) //enabled is a pointer - { - if (compiler_flag[i].flags & FLAG_ASDEFAULT) - compiler_flag[i].flags |= FLAG_SETINGUI; - else - compiler_flag[i].flags &= ~FLAG_SETINGUI; - } - for (i = 0; optimisations[i].enabled; i++) //enabled is a pointer - { - if (optimisations[i].flags & FLAG_ASDEFAULT) - optimisations[i].flags |= FLAG_SETINGUI; - else - optimisations[i].flags &= ~FLAG_SETINGUI; - } -} - -void GUI_RevealOptions(void) -{ - int i; - for (i = 0; compiler_flag[i].enabled; i++) //enabled is a pointer - { - if (fl_showall && compiler_flag[i].flags & FLAG_HIDDENINGUI) - compiler_flag[i].flags &= ~FLAG_HIDDENINGUI; - } - for (i = 0; optimisations[i].enabled; i++) //enabled is a pointer - { - if (fl_showall && optimisations[i].flags & FLAG_HIDDENINGUI) - optimisations[i].flags &= ~FLAG_HIDDENINGUI; - - if (optimisations[i].flags & FLAG_HIDDENINGUI) //hidden optimisations are disabled as default - optimisations[i].optimisationlevel = 4; - } -} - - - - -int GUI_BuildParms(char *args, char **argv) -{ - static char param[2048]; - int paramlen = 0; - int argc; - char *next; - int i; - - - argc = 1; - argv[0] = "fteqcc"; - - while(*args) - { - while (*args <= ' '&& *args) - args++; - - for (next = args; *next>' '; next++) - ; - strncpy(param+paramlen, args, next-args); - param[paramlen+next-args] = '\0'; - argv[argc++] = param+paramlen; - paramlen += strlen(param+paramlen)+1; - - args=next; - } - - if (fl_hexen2) - { - strcpy(param+paramlen, "-Th2"); - argv[argc++] = param+paramlen; - paramlen += strlen(param+paramlen)+1; - } - - for (i = 0; optimisations[i].enabled; i++) //enabled is a pointer - { - if (optimisations[i].flags & FLAG_SETINGUI) - sprintf(param+paramlen, "-O%s", optimisations[i].abbrev); - else - sprintf(param+paramlen, "-Ono-%s", optimisations[i].abbrev); - argv[argc++] = param+paramlen; - paramlen += strlen(param+paramlen)+1; - } - - for (i = 0; compiler_flag[i].enabled; i++) //enabled is a pointer - { - if (compiler_flag[i].flags & FLAG_SETINGUI) - sprintf(param+paramlen, "-F%s", compiler_flag[i].abbrev); - else - sprintf(param+paramlen, "-Fno-%s", compiler_flag[i].abbrev); - argv[argc++] = param+paramlen; - paramlen += strlen(param+paramlen)+1; - } - - -/* while(*args) - { - while (*args <= ' '&& *args) - args++; - - for (next = args; *next>' '; next++) - ; - strncpy(param+paramlen, args, next-args); - param[paramlen+next-args] = '\0'; - argv[argc++] = param+paramlen; - paramlen += strlen(param+paramlen)+1; - args=next; - }*/ - - if (*progssrcname) - { - argv[argc++] = "-srcfile"; - argv[argc++] = progssrcname; - } - if (*progssrcdir) - { - argv[argc++] = "-src"; - argv[argc++] = progssrcdir; - } - - return argc; -} diff --git a/misc/mediasource/extra/fteqcc-src/qccmain.c b/misc/mediasource/extra/fteqcc-src/qccmain.c deleted file mode 100644 index a410ab08..00000000 --- a/misc/mediasource/extra/fteqcc-src/qccmain.c +++ /dev/null @@ -1,3478 +0,0 @@ -#ifndef MINIMAL - -#define PROGSUSED -#include "qcc.h" -int mkdir(const char *path); - -char QCC_copyright[1024]; -int QCC_packid; -char QCC_Packname[5][128]; - -extern QCC_def_t *functemps; //floats/strings/funcs/ents... - -extern int optres_test1; -extern int optres_test2; - -int writeasm; -static pbool pr_werror; -pbool verbose; - - -pbool QCC_PR_SimpleGetToken (void); -void QCC_PR_LexWhitespace (void); - -void *FS_ReadToMem(char *fname, void *membuf, int *len); -void FS_CloseFromMem(void *mem); - -struct qcc_includechunk_s *currentchunk; - -unsigned int MAX_REGS; - -int MAX_STRINGS; -int MAX_GLOBALS; -int MAX_FIELDS; -int MAX_STATEMENTS; -int MAX_FUNCTIONS; -int MAX_CONSTANTS; -int max_temps; - -int *qcc_tempofs; -int tempsstart; -int numtemps; - -#define MAXSOURCEFILESLIST 8 -char sourcefileslist[MAXSOURCEFILESLIST][1024]; -int currentsourcefile; -int numsourcefiles; - -void QCC_PR_ResetErrorScope(void); - -pbool compressoutput; - -pbool newstylesource; -char destfile[1024]; - -float *qcc_pr_globals; -unsigned int numpr_globals; - -char *strings; -int strofs; - -QCC_dstatement_t *statements; -int numstatements; -int *statement_linenums; - -QCC_dfunction_t *functions; -int numfunctions; - -QCC_ddef_t *qcc_globals; -int numglobaldefs; - -QCC_ddef_t *fields; -int numfielddefs; - -//typedef char PATHSTRING[MAX_DATA_PATH]; - -PATHSTRING *precache_sounds; -int *precache_sounds_block; -int numsounds; - -PATHSTRING *precache_textures; -int *precache_textures_block; -int numtextures; - -PATHSTRING *precache_models; -int *precache_models_block; -int nummodels; - -PATHSTRING *precache_files; -int *precache_files_block; -int numfiles; - -extern int numCompilerConstants; -hashtable_t compconstantstable; -hashtable_t globalstable; -hashtable_t localstable; -hashtable_t floatconstdefstable; -hashtable_t stringconstdefstable; -hashtable_t stringconstdefstable_dotranslate; -int dotranslate; -int dotranslate_count; - -pbool qccwarningdisabled[WARN_MAX]; - -qcc_targetformat_t qcc_targetformat; - -pbool bodylessfuncs; - -QCC_type_t *qcc_typeinfo; -int numtypeinfos; -int maxtypeinfos; - - -struct { - char *name; - int index; -} warningnames[] = -{ - {"Q302", WARN_NOTREFERENCED}, -// {"", WARN_NOTREFERENCEDCONST}, -// {"", WARN_CONFLICTINGRETURNS}, - {"Q105", WARN_TOOFEWPARAMS}, - {"Q101", WARN_TOOMANYPARAMS}, -// {"", WARN_UNEXPECTEDPUNCT}, - {"Q106", WARN_ASSIGNMENTTOCONSTANT}, - {"Q203", WARN_MISSINGRETURNVALUE}, - {"Q204", WARN_WRONGRETURNTYPE}, - {"Q205", WARN_POINTLESSSTATEMENT}, - {"Q206", WARN_MISSINGRETURN}, - {"Q207", WARN_DUPLICATEDEFINITION}, - {"Q100", WARN_PRECOMPILERMESSAGE}, -// {"", WARN_STRINGTOOLONG}, -// {"", WARN_BADTARGET}, - {"Q120", WARN_BADPRAGMA}, -// {"", WARN_HANGINGSLASHR}, -// {"", WARN_NOTDEFINED}, -// {"", WARN_SWITCHTYPEMISMATCH}, -// {"", WARN_CONFLICTINGUNIONMEMBER}, -// {"", WARN_KEYWORDDISABLED}, -// {"", WARN_ENUMFLAGS_NOTINTEGER}, -// {"", WARN_ENUMFLAGS_NOTBINARY}, -// {"", WARN_CASEINSENSATIVEFRAMEMACRO}, - {"Q111", WARN_DUPLICATELABEL}, - {"Q201", WARN_ASSIGNMENTINCONDITIONAL}, - {"F300", WARN_DEADCODE}, - {NULL} -}; - -int QCC_WarningForName(char *name) -{ - int i; - for (i = 0; warningnames[i].name; i++) - { - if (!stricmp(name, warningnames[i].name)) - return warningnames[i].index; - } - return -1; -} - -optimisations_t optimisations[] = -{ - //level 0 = no optimisations - //level 1 = size optimisations - //level 2 = speed optimisations - //level 3 = dodgy optimisations. - //level 4 = experimental... - - {&opt_assignments, "t", 1, FLAG_ASDEFAULT, "assignments", "c = a*b is performed in one operation rather than two, and can cause older decompilers to fail."}, - {&opt_shortenifnots, "i", 1, FLAG_ASDEFAULT, "shortenifs", "if (!a) was traditionally compiled in two statements. This optimisation does it in one, but can cause some decompilers to get confused."}, - {&opt_nonvec_parms, "p", 1, FLAG_ASDEFAULT, "nonvec_parms", "In the original qcc, function parameters were specified as a vector store even for floats. This fixes that."}, - {&opt_constant_names, "c", 2, FLAG_KILLSDEBUGGERS, "constant_names", "This optimisation strips out the names of constants (but not strings) from your progs, resulting in smaller files. It makes decompilers leave out names or fabricate numerical ones."}, - {&opt_constant_names_strings, "cs", 3, FLAG_KILLSDEBUGGERS, "constant_names_strings", "This optimisation strips out the names of string constants from your progs. However, this can break addons, so don't use it in those cases."}, - {&opt_dupconstdefs, "d", 1, FLAG_ASDEFAULT, "dupconstdefs", "This will merge definitions of constants which are the same value. Pay extra attention to assignment to constant warnings."}, - {&opt_noduplicatestrings, "s", 1, 0, "noduplicatestrings", "This will compact the string table that is stored in the progs. It will be considerably smaller with this."}, - {&opt_locals, "l", 1, FLAG_KILLSDEBUGGERS, "locals", "Strips out local names and definitions. This makes it REALLY hard to decompile"}, - {&opt_function_names, "n", 1, FLAG_KILLSDEBUGGERS, "function_names", "This strips out the names of functions which are never called. Doesn't make much of an impact though."}, - {&opt_filenames, "f", 1, FLAG_KILLSDEBUGGERS, "filenames", "This strips out the filenames of the progs. This can confuse the really old decompilers, but is nothing to the more recent ones."}, - {&opt_unreferenced, "u", 1, FLAG_ASDEFAULT, "unreferenced", "Removes the entries of unreferenced variables. Doesn't make a difference in well maintained code."}, - {&opt_overlaptemps, "r", 1, FLAG_ASDEFAULT, "overlaptemps", "Optimises the pr_globals count by overlapping temporaries. In QC, every multiplication, division or operation in general produces a temporary variable. This optimisation prevents excess, and in the case of Hexen2's gamecode, reduces the count by 50k. This is the most important optimisation, ever."}, - {&opt_constantarithmatic, "a", 1, FLAG_ASDEFAULT, "constantarithmatic", "5*6 actually emits an operation into the progs. This prevents that happening, effectivly making the compiler see 30"}, - {&opt_precache_file, "pf", 2, 0, "precache_file", "Strip out stuff wasted used in function calls and strings to the precache_file builtin (which is actually a stub in quake)."}, - {&opt_return_only, "ro", 3, FLAG_KILLSDEBUGGERS, "return_only", "Functions ending in a return statement do not need a done statement at the end of the function. This can confuse some decompilers, making functions appear larger than they were."}, - {&opt_compound_jumps, "cj", 3, FLAG_KILLSDEBUGGERS, "compound_jumps", "This optimisation plays an effect mostly with nested if/else statements, instead of jumping to an unconditional jump statement, it'll jump to the final destination instead. This will bewilder decompilers."}, -// {&opt_comexprremoval, "cer", 4, 0, "expression_removal", "Eliminate common sub-expressions"}, //this would be too hard... - {&opt_stripfunctions, "sf", 3, 0, "strip_functions", "Strips out the 'defs' of functions that were only ever called directly. This does not affect saved games."}, - {&opt_locals_marshalling, "lm", 4, FLAG_KILLSDEBUGGERS, "locals_marshalling", "Store all locals in one section of the pr_globals. Vastly reducing it. This effectivly does the job of overlaptemps. It's been noticed as buggy by a few, however, and the curcumstances where it causes problems are not yet known."}, - {&opt_vectorcalls, "vc", 4, FLAG_KILLSDEBUGGERS, "vectorcalls", "Where a function is called with just a vector, this causes the function call to store three floats instead of one vector. This can save a good number of pr_globals where those vectors contain many duplicate coordinates but do not match entirly."}, - {NULL} -}; - -#define defaultkeyword FLAG_HIDDENINGUI|FLAG_ASDEFAULT|FLAG_MIDCOMPILE -#define nondefaultkeyword FLAG_HIDDENINGUI|0|FLAG_MIDCOMPILE -//global to store useage to, flags, codename, human-readable name, help text -compiler_flag_t compiler_flag[] = { - //keywords - {&keyword_asm, defaultkeyword, "asm", "Keyword: asm", "Disables the 'asm' keyword. Use the writeasm flag to see an example of the asm."}, - {&keyword_break, defaultkeyword, "break", "Keyword: break", "Disables the 'break' keyword."}, - {&keyword_case, defaultkeyword, "case", "Keyword: case", "Disables the 'case' keyword."}, - {&keyword_class, defaultkeyword, "class", "Keyword: class", "Disables the 'class' keyword."}, - {&keyword_const, defaultkeyword, "const", "Keyword: const", "Disables the 'const' keyword."}, - {&keyword_continue, defaultkeyword, "continue", "Keyword: continue", "Disables the 'continue' keyword."}, - {&keyword_default, defaultkeyword, "default", "Keyword: default", "Disables the 'default' keyword."}, - {&keyword_entity, defaultkeyword, "entity", "Keyword: entity", "Disables the 'entity' keyword."}, - {&keyword_enum, defaultkeyword, "enum", "Keyword: enum", "Disables the 'enum' keyword."}, //kinda like in c, but typedef not supported. - {&keyword_enumflags, defaultkeyword, "enumflags", "Keyword: enumflags", "Disables the 'enumflags' keyword."}, //like enum, but doubles instead of adds 1. - {&keyword_extern, defaultkeyword, "extern", "Keyword: extern", "Disables the 'extern' keyword. Use only on functions inside addons."}, //function is external, don't error or warn if the body was not found - {&keyword_float, defaultkeyword, "float", "Keyword: float", "Disables the 'float' keyword. (Disables the float keyword without 'local' preceeding it)"}, - {&keyword_for, defaultkeyword, "for", "Keyword: for", "Disables the 'for' keyword. Syntax: for(assignment; while; increment) {codeblock;}"}, - {&keyword_goto, defaultkeyword, "goto", "Keyword: goto", "Disables the 'goto' keyword."}, - {&keyword_int, defaultkeyword, "int", "Keyword: int", "Disables the 'int' keyword."}, - {&keyword_integer, defaultkeyword, "integer", "Keyword: integer", "Disables the 'integer' keyword."}, - {&keyword_noref, defaultkeyword, "noref", "Keyword: noref", "Disables the 'noref' keyword."}, //nowhere else references this, don't strip it. - {&keyword_nosave, defaultkeyword, "nosave", "Keyword: nosave", "Disables the 'nosave' keyword."}, //don't write the def to the output. - {&keyword_shared, defaultkeyword, "shared", "Keyword: shared", "Disables the 'shared' keyword."}, //mark global to be copied over when progs changes (part of FTE_MULTIPROGS) - {&keyword_state, nondefaultkeyword,"state", "Keyword: state", "Disables the 'state' keyword."}, - {&keyword_string, defaultkeyword, "string", "Keyword: string", "Disables the 'string' keyword."}, - {&keyword_struct, defaultkeyword, "struct", "Keyword: struct", "Disables the 'struct' keyword."}, - {&keyword_switch, defaultkeyword, "switch", "Keyword: switch", "Disables the 'switch' keyword."}, - {&keyword_thinktime, nondefaultkeyword,"thinktime", "Keyword: thinktime", "Disables the 'thinktime' keyword which is used in HexenC"}, - {&keyword_typedef, defaultkeyword, "typedef", "Keyword: typedef", "Disables the 'typedef' keyword."}, //fixme - {&keyword_union, defaultkeyword, "union", "Keyword: union", "Disables the 'union' keyword."}, //you surly know what a union is! - {&keyword_var, defaultkeyword, "var", "Keyword: var", "Disables the 'var' keyword."}, - {&keyword_vector, defaultkeyword, "vector", "Keyword: vector", "Disables the 'vector' keyword."}, - - - //options - {&keywords_coexist, FLAG_ASDEFAULT, "kce", "Keywords Coexist", "If you want keywords to NOT be disabled when they a variable by the same name is defined, check here."}, - {&output_parms, 0, "parms", "Define offset parms", "if PARM0 PARM1 etc should be defined by the compiler. These are useful if you make use of the asm keyword for function calls, or you wish to create your own variable arguments. This is an easy way to break decompilers."}, //controls weather to define PARMx for the parms (note - this can screw over some decompilers) - {&autoprototype, 0, "autoproto", "Automatic Prototyping","Causes compilation to take two passes instead of one. The first pass, only the definitions are read. The second pass actually compiles your code. This means you never have to remember to prototype functions again."}, //so you no longer need to prototype functions and things in advance. - {&writeasm, 0, "wasm", "Dump Assembler", "Writes out a qc.asm which contains all your functions but in assembler. This is a great way to look for bugs in fteqcc, but can also be used to see exactly what your functions turn into, and thus how to optimise statements better."}, //spit out a qc.asm file, containing an assembler dump of the ENTIRE progs. (Doesn't include initialisation of constants) - {&flag_ifstring, FLAG_MIDCOMPILE,"ifstring", "if(string) fix", "Causes if(string) to behave identically to if(string!="") This is most useful with addons of course, but also has adverse effects with FRIK_FILE's fgets, where it becomes impossible to determin the end of the file. In such a case, you can still use asm {IF string 2;RETURN} to detect eof and leave the function."}, //correction for if(string) no-ifstring to get the standard behaviour. - {&flag_iffloat, FLAG_MIDCOMPILE,"iffloat","if(-0.0) fix","Fixes certain floating point logic."}, - {&flag_acc, 0, "acc", "Reacc support", "Reacc is a pascall like compiler. It was released before the Quake source was released. This flag has a few effects. It sorts all qc files in the current directory into alphabetical order to compile them. It also allows Reacc global/field distinctions, as well as allows ¦ as EOF. Whilst case insensativity and lax type checking are supported by reacc, they are seperate compiler flags in fteqcc."}, //reacc like behaviour of src files. - {&flag_caseinsensative, 0, "caseinsens", "Case insensativity", "Causes fteqcc to become case insensative whilst compiling names. It's generally not advised to use this as it compiles a little more slowly and provides little benefit. However, it is required for full reacc support."}, //symbols will be matched to an insensative case if the specified case doesn't exist. This should b usable for any mod - {&flag_laxcasts, FLAG_MIDCOMPILE,"lax", "Lax type checks", "Disables many errors (generating warnings instead) when function calls or operations refer to two normally incompatible types. This is required for reacc support, and can also allow certain (evil) mods to compile that were originally written for frikqcc."}, //Allow lax casting. This'll produce loadsa warnings of course. But allows compilation of certain dodgy code. - {&flag_hashonly, FLAG_MIDCOMPILE,"hashonly", "Hash-only constants", "Allows use of only #constant for precompiler constants, allows certain preqcc using mods to compile"}, - {&opt_logicops, FLAG_MIDCOMPILE,"lo", "Logic ops", "This changes the behaviour of your code. It generates additional if operations to early-out in if statements. With this flag, the line if (0 && somefunction()) will never call the function. It can thus be considered an optimisation. However, due to the change of behaviour, it is not considered so by fteqcc. Note that due to inprecisions with floats, this flag can cause runaway loop errors within the player walk and run functions (without iffloat also enabled). This code is advised:\nplayer_stand1:\n if (self.velocity_x || self.velocity_y)\nplayer_run\n if (!(self.velocity_x || self.velocity_y))"}, - {&flag_msvcstyle, FLAG_MIDCOMPILE,"msvcstyle", "MSVC-style errors", "Generates warning and error messages in a format that msvc understands, to facilitate ide integration."}, - {&flag_fasttrackarrays, FLAG_MIDCOMPILE|FLAG_ASDEFAULT,"fastarrays","fast arrays where possible", "Generates extra instructions inside array handling functions to detect engine and use extension opcodes only in supporting engines.\nAdds a global which is set by the engine if the engine supports the extra opcodes. Note that this applies to all arrays or none."}, - {&flag_assume_integer, FLAG_MIDCOMPILE,"assumeint", "Assume Integers", "Numerical constants are assumed to be integers, instead of floats."}, - {&pr_subscopedlocals, FLAG_MIDCOMPILE,"subscope", "Subscoped locals", "Allow locals to only be valid in the block they are defined in (like in C)."}, - {NULL} -}; - -struct { - qcc_targetformat_t target; - char *name; -} targets[] = { - {QCF_STANDARD, "standard"}, - {QCF_STANDARD, "q1"}, - {QCF_STANDARD, "quakec"}, - {QCF_HEXEN2, "hexen2"}, - {QCF_HEXEN2, "h2"}, - {QCF_KK7, "kkqwsv"}, - {QCF_KK7, "kk7"}, - {QCF_KK7, "bigprogs"}, - {QCF_KK7, "version7"}, - {QCF_KK7, "kkqwsv"}, - {QCF_FTE, "fte"}, - {QCF_DARKPLACES,"darkplaces"}, - {QCF_DARKPLACES,"dp"}, - {0, NULL} -}; - -/* -================= -BspModels - -Runs qbsp and light on all of the models with a .bsp extension -================= -*/ -int QCC_CheckParm (char *check); - -void QCC_BspModels (void) -{ - int p; - char *gamedir; - int i; - char *m; - char cmd[1024]; - char name[256]; - - p = QCC_CheckParm ("-bspmodels"); - if (!p) - return; - if (p == myargc-1) - QCC_Error (ERR_BADPARMS, "-bspmodels must preceed a game directory"); - gamedir = myargv[p+1]; - - for (i=0 ; istrings ; s--) - if (!strcmp(s, str)) - return s-strings; - - old = strofs; - strcpy (strings+strofs, str); - strofs += strlen(str)+1; - return old; -} - -void QCC_PrintStrings (void) -{ - int i, l, j; - - for (i=0 ; is_file, strings + d->s_name, d->first_statement, d->parm_start); - for (j=0 ; jnumparms ; j++) - printf ("%i ",d->parm_size[j]); - printf (")\n"); - } -}*/ - -void QCC_PrintFields (void) -{ - int i; - QCC_ddef_t *d; - - for (i=0 ; iofs, d->type, strings + d->s_name); - } -} - -void QCC_PrintGlobals (void) -{ - int i; - QCC_ddef_t *d; - - for (i=0 ; iofs, d->type, strings + d->s_name); - } -} - -int encode(int len, int method, char *in, int handle); -int WriteSourceFiles(int h, dprograms_t *progs, pbool sourceaswell) -{ - includeddatafile_t *idf; - qcc_cachedsourcefile_t *f; - int num=0; - int ofs; - - /* - for (f = qcc_sourcefile; f ; f=f->next) - { - if (f->type == FT_CODE && !sourceaswell) - continue; - - SafeWrite(h, f->filename, strlen(f->filename)+1); - i = PRLittleLong(f->size); - SafeWrite(h, &i, sizeof(int)); - - i = PRLittleLong(encrpytmode); - SafeWrite(h, &i, sizeof(int)); - - if (encrpytmode) - for (i = 0; i < f->size; i++) - f->file[i] ^= 0xA5; - - SafeWrite(h, f->file, f->size); - }*/ - - for (f = qcc_sourcefile,num=0; f ; f=f->next) - { - if (f->type == FT_CODE && !sourceaswell) - continue; - - num++; - } - if (!num) - return 0; - idf = qccHunkAlloc(sizeof(includeddatafile_t)*num); - for (f = qcc_sourcefile,num=0; f ; f=f->next) - { - if (f->type == FT_CODE && !sourceaswell) - continue; - - strcpy(idf[num].filename, f->filename); - idf[num].size = f->size; -#ifdef AVAIL_ZLIB - idf[num].compmethod = 2; -#else - idf[num].compmethod = 1; -#endif - idf[num].ofs = SafeSeek(h, 0, SEEK_CUR); - idf[num].compsize = QC_encode(progfuncs, f->size, idf[num].compmethod, f->file, h); - num++; - } - - ofs = SafeSeek(h, 0, SEEK_CUR); - SafeWrite(h, &num, sizeof(int)); - SafeWrite(h, idf, sizeof(includeddatafile_t)*num); - - qcc_sourcefile = NULL; - - return ofs; -} - -void QCC_InitData (void) -{ - static char parmname[12][MAX_PARMS]; - static temp_t ret_temp; - int i; - - qcc_sourcefile = NULL; - - numstatements = 1; - strofs = 1; - numfunctions = 1; - numglobaldefs = 1; - numfielddefs = 1; - - memset(&ret_temp, 0, sizeof(ret_temp)); - - def_ret.ofs = OFS_RETURN; - def_ret.name = "return"; - def_ret.temp = &ret_temp; - def_ret.constant = false; - def_ret.type = NULL; - ret_temp.ofs = def_ret.ofs; - ret_temp.scope = NULL; - ret_temp.size = 3; - ret_temp.next = NULL; - for (i=0 ; inext) - { - if (d->type->type == ev_function && !d->scope)// function parms are ok - { - if (d->initialized != 1 && d->references>0) - { - SafeWrite(handle, d->name, strlen(d->name)+1); - ret++; - } - } - } - - return ret; -} - -//marshalled locals remaps all the functions to use the range MAX_REGS onwards for the offset to their locals. -//this function remaps all the locals back into the function. -void QCC_UnmarshalLocals(void) -{ - QCC_def_t *def; - unsigned int ofs; - unsigned int maxo; - int i; - - ofs = numpr_globals; - maxo = ofs; - - for (def = pr.def_head.next ; def ; def = def->next) - { - if (def->ofs >= MAX_REGS) //unmap defs. - { - def->ofs = def->ofs + ofs - MAX_REGS; - if (maxo < def->ofs) - maxo = def->ofs; - } - } - - for (i = 0; i < numfunctions; i++) - { - if (functions[i].parm_start == MAX_REGS) - functions[i].parm_start = ofs; - } - - QCC_RemapOffsets(0, numstatements, MAX_REGS, MAX_REGS + maxo-numpr_globals + 3, ofs); - - numpr_globals = maxo+3; - if (numpr_globals > MAX_REGS) - QCC_Error(ERR_TOOMANYGLOBALS, "Too many globals are in use to unmarshal all locals"); - - if (maxo-ofs) - printf("Total of %i marshalled globals\n", maxo-ofs); -} - -CompilerConstant_t *QCC_PR_CheckCompConstDefined(char *def); -pbool QCC_WriteData (int crc) -{ - char element[MAX_NAME]; - QCC_def_t *def, *comp_x, *comp_y, *comp_z; - QCC_ddef_t *dd; - dprograms_t progs; - int h; - int i, len; - pbool debugtarget = false; - pbool types = false; - int outputsize = 16; - - if (numstatements==1 && numfunctions==1 && numglobaldefs==1 && numfielddefs==1) - { - printf("nothing to write\n"); - return false; - } - - progs.blockscompressed=0; - - if (numstatements > MAX_STATEMENTS) - QCC_Error(ERR_TOOMANYSTATEMENTS, "Too many statements - %i\nAdd \"MAX_STATEMENTS\" \"%i\" to qcc.cfg", numstatements, (numstatements+32768)&~32767); - - if (strofs > MAX_STRINGS) - QCC_Error(ERR_TOOMANYSTRINGS, "Too many strings - %i\nAdd \"MAX_STRINGS\" \"%i\" to qcc.cfg", strofs, (strofs+32768)&~32767); - - QCC_UnmarshalLocals(); - - switch (qcc_targetformat) - { - case QCF_HEXEN2: - case QCF_STANDARD: - if (bodylessfuncs) - printf("Warning: There are some functions without bodies.\n"); - - if (numpr_globals > 65530 ) - { - printf("Forcing target to FTE32 due to numpr_globals\n"); - outputsize = 32; - } - else if (qcc_targetformat == QCF_HEXEN2) - { - printf("Progs execution requires a Hexen2 compatible engine\n"); - break; - } - else - { - if (numpr_globals >= 32768) //not much of a different format. Rewrite output to get it working on original executors? - printf("An enhanced executor will be required (FTE/QF/KK)\n"); - else - printf("Progs should run on any Quake executor\n"); - break; - } - //intentional - qcc_targetformat = QCF_FTE; - case QCF_FTEDEBUG: - case QCF_FTE: - case QCF_DARKPLACES: - if (qcc_targetformat == QCF_FTEDEBUG) - debugtarget = true; - - if (numpr_globals > 65530) - { - printf("Using 32 bit target due to numpr_globals\n"); - outputsize = 32; - } - - if (qcc_targetformat == QCF_DARKPLACES) - compressoutput = 0; - - - //compression of blocks? - if (compressoutput) progs.blockscompressed |=1; //statements - if (compressoutput) progs.blockscompressed |=2; //defs - if (compressoutput) progs.blockscompressed |=4; //fields - if (compressoutput) progs.blockscompressed |=8; //functions - if (compressoutput) progs.blockscompressed |=16; //strings - if (compressoutput) progs.blockscompressed |=32; //globals - if (compressoutput) progs.blockscompressed |=64; //line numbers - if (compressoutput) progs.blockscompressed |=128; //types - //include a type block? - types = debugtarget;//!!QCC_PR_CheckCompConstDefined("TYPES"); //useful for debugging and saving (maybe, anyway...). - - if (verbose) - { - if (qcc_targetformat == QCF_DARKPLACES) - printf("DarkPlaces or FTE will be required\n"); - else - printf("An FTE executor will be required\n"); - } - break; - case QCF_KK7: - if (bodylessfuncs) - printf("Warning: There are some functions without bodies.\n"); - if (numpr_globals > 65530) - printf("Warning: Saving is not supported. Ensure all engine read fields and globals are defined early on.\n"); - - printf("A KK compatible executor will be required (FTE/KK)\n"); - break; - } - - //part of how compilation works. This def is always present, and never used. - def = QCC_PR_GetDef(NULL, "end_sys_globals", NULL, false, 0, false); - if (def) - def->references++; - - def = QCC_PR_GetDef(NULL, "end_sys_fields", NULL, false, 0, false); - if (def) - def->references++; - - for (def = pr.def_head.next ; def ; def = def->next) - { - if (def->type->type == ev_vector || (def->type->type == ev_field && def->type->aux_type->type == ev_vector)) - { //do the references, so we don't get loadsa not referenced VEC_HULL_MINS_x - sprintf(element, "%s_x", def->name); - comp_x = QCC_PR_GetDef(NULL, element, def->scope, false, 0, false); - sprintf(element, "%s_y", def->name); - comp_y = QCC_PR_GetDef(NULL, element, def->scope, false, 0, false); - sprintf(element, "%s_z", def->name); - comp_z = QCC_PR_GetDef(NULL, element, def->scope, false, 0, false); - - h = def->references; - if (comp_x && comp_y && comp_z) - { - h += comp_x->references; - h += comp_y->references; - h += comp_z->references; - - if (!def->references) - if (!comp_x->references || !comp_y->references || !comp_z->references) //one of these vars is useless... - h=0; - - def->references = h; - - - if (!h) - h = 1; - if (comp_x) - comp_x->references = h; - if (comp_y) - comp_y->references = h; - if (comp_z) - comp_z->references = h; - } - } - if (def->references<=0) - { - if (def->constant) - QCC_PR_Warning(WARN_NOTREFERENCEDCONST, strings + def->s_file, def->s_line, "%s no references", def->name); - else - QCC_PR_Warning(WARN_NOTREFERENCED, strings + def->s_file, def->s_line, "%s no references", def->name); - - if (opt_unreferenced && def->type->type != ev_field) - { - optres_unreferenced++; - continue; - } - } - - if (def->type->type == ev_function) - { - if (opt_function_names && functions[G_FUNCTION(def->ofs)].first_statement<0) - { - optres_function_names++; - def->name = ""; - } - if (!def->timescalled) - { - if (def->references<=1) - QCC_PR_Warning(WARN_DEADCODE, strings + def->s_file, def->s_line, "%s is never directly called or referenced (spawn function or dead code)", def->name); -// else -// QCC_PR_Warning(WARN_DEADCODE, strings + def->s_file, def->s_line, "%s is never directly called", def->name); - } - if (opt_stripfunctions && def->timescalled >= def->references-1) //make sure it's not copied into a different var. - { //if it ever does self.think then it could be needed for saves. - optres_stripfunctions++; //if it's only ever called explicitly, the engine doesn't need to know. - continue; - } - -// df = &functions[numfunctions]; -// numfunctions++; - - } - else if (def->type->type == ev_field)// && !def->constant) - { - dd = &fields[numfielddefs]; - numfielddefs++; - dd->type = def->type->aux_type->type; - dd->s_name = QCC_CopyString (def->name); - dd->ofs = G_INT(def->ofs); - } - else if ((def->scope||def->constant) && (def->type->type != ev_string || opt_constant_names_strings)) - { - if (opt_constant_names) - { - if (def->type->type == ev_string) - optres_constant_names_strings += strlen(def->name); - else - optres_constant_names += strlen(def->name); - continue; - } - } - -// if (!def->saved && def->type->type != ev_string) -// continue; - dd = &qcc_globals[numglobaldefs]; - numglobaldefs++; - - if (types) - dd->type = def->type-qcc_typeinfo; - else - dd->type = def->type->type; -#ifdef DEF_SAVEGLOBAL - if ( def->saved && ((!def->initialized || def->type->type == ev_function) -// && def->type->type != ev_function - && def->type->type != ev_field - && def->scope == NULL)) - { - dd->type |= DEF_SAVEGLOBAL; - } -#endif - if (def->shared) - dd->type |= DEF_SHARED; - - if (opt_locals && (def->scope || !strcmp(def->name, "IMMEDIATE"))) - { - dd->s_name = 0; - optres_locals += strlen(def->name); - } - else - dd->s_name = QCC_CopyString (def->name); - dd->ofs = def->ofs; - } - - for (i = 0; i < numglobaldefs; i++) - { - dd = &qcc_globals[i]; - if (!(dd->type & DEF_SAVEGLOBAL)) //only warn about saved ones. - continue; - - for (h = 0; h < numglobaldefs; h++) - { - if (i == h) - continue; - if (dd->ofs == qcc_globals[h].ofs) - { - if (dd->type != qcc_globals[h].type) - { - if (dd->type != ev_vector && qcc_globals[h].type != ev_float) - QCC_PR_Warning(0, NULL, 0, "Mismatched union global types (%s and %s)", strings+dd->s_name, strings+qcc_globals[h].s_name); - } - //remove the saveglobal flag on the duplicate globals. - qcc_globals[h].type &= ~DEF_SAVEGLOBAL; - } - } - } - for (i = 1; i < numfielddefs; i++) - { - dd = &fields[i]; - - if (dd->type == ev_vector) //just ignore vectors. - continue; - - for (h = 1; h < numfielddefs; h++) - { - if (i == h) - continue; - if (dd->ofs == fields[h].ofs) - { - if (dd->type != fields[h].type) - { - if (fields[h].type != ev_vector) - { - QCC_PR_Warning(0, NULL, 0, "Mismatched union field types (%s and %s)", strings+dd->s_name, strings+fields[h].s_name); - } - } - } - } - } - - if (numglobaldefs > MAX_GLOBALS) - QCC_Error(ERR_TOOMANYGLOBALS, "Too many globals - %i\nAdd \"MAX_GLOBALS\" \"%i\" to qcc.cfg", numglobaldefs, (numglobaldefs+32768)&~32767); - - - for (i = 0; i < nummodels; i++) - { - if (!precache_models_used[i]) - QCC_PR_Warning(WARN_EXTRAPRECACHE, NULL, 0, "Model %s was precached but not directly used", precache_models[i]); - else if (!precache_models_block[i]) - QCC_PR_Warning(WARN_NOTPRECACHED, NULL, 0, "Model %s was used but not precached", precache_models[i]); - } -//PrintStrings (); -//PrintFunctions (); -//PrintFields (); -//PrintGlobals (); -strofs = (strofs+3)&~3; - - if (verbose) - { - printf ("%6i strofs (of %i)\n", strofs, MAX_STRINGS); - printf ("%6i numstatements (of %i)\n", numstatements, MAX_STATEMENTS); - printf ("%6i numfunctions (of %i)\n", numfunctions, MAX_FUNCTIONS); - printf ("%6i numglobaldefs (of %i)\n", numglobaldefs, MAX_GLOBALS); - printf ("%6i numfielddefs (%i unique) (of %i)\n", numfielddefs, pr.size_fields, MAX_FIELDS); - printf ("%6i numpr_globals (of %i)\n", numpr_globals, MAX_REGS); - } - - if (!*destfile) - strcpy(destfile, "progs.dat"); - if (verbose) - printf("Writing %s\n", destfile); - h = SafeOpenWrite (destfile, 2*1024*1024); - SafeWrite (h, &progs, sizeof(progs)); - SafeWrite (h, "\r\n\r\n", 4); - SafeWrite (h, QCC_copyright, strlen(QCC_copyright)+1); - SafeWrite (h, "\r\n\r\n", 4); - while(SafeSeek (h, 0, SEEK_CUR) & 3)//this is a lame way to do it - { - SafeWrite (h, "\0", 1); - } - - progs.ofs_strings = SafeSeek (h, 0, SEEK_CUR); - progs.numstrings = strofs; - - if (progs.blockscompressed&16) - { - SafeWrite (h, &len, sizeof(int)); //save for later - len = QC_encode(progfuncs, strofs*sizeof(char), 2, (char *)strings, h); //write - i = SafeSeek (h, 0, SEEK_CUR); - SafeSeek(h, progs.ofs_strings, SEEK_SET);//seek back - len = PRLittleLong(len); - SafeWrite (h, &len, sizeof(int)); //write size. - SafeSeek(h, i, SEEK_SET); - } - else - SafeWrite (h, strings, strofs); - - progs.ofs_statements = SafeSeek (h, 0, SEEK_CUR); - progs.numstatements = numstatements; - - if (qcc_targetformat == QCF_HEXEN2) - { - for (i=0 ; i= OP_CALL1 && statements[i].op <= OP_CALL8) - QCC_Error(ERR_BADTARGETSWITCH, "Target switching produced incompatible instructions"); - else if (statements[i].op >= OP_CALL1H && statements[i].op <= OP_CALL8H) - statements[i].op = statements[i].op - OP_CALL1H + OP_CALL1; - } - } - - for (i=0 ; iMAX_PARMS)?MAX_PARMS:functions[i].numparms); - functions[i].locals = PRLittleLong (functions[i].locals); - } - - if (progs.blockscompressed&8) - { - SafeWrite (h, &len, sizeof(int)); //save for later - len = QC_encode(progfuncs, numfunctions*sizeof(QCC_dfunction_t), 2, (char *)functions, h); //write - i = SafeSeek (h, 0, SEEK_CUR); - SafeSeek(h, progs.ofs_functions, SEEK_SET);//seek back - len = PRLittleLong(len); - SafeWrite (h, &len, sizeof(int)); //write size. - SafeSeek(h, i, SEEK_SET); - } - else - SafeWrite (h, functions, numfunctions*sizeof(QCC_dfunction_t)); - - switch(outputsize) - { - case 32: - progs.ofs_globaldefs = SafeSeek (h, 0, SEEK_CUR); - progs.numglobaldefs = numglobaldefs; - for (i=0 ; i 60) - { - *s++ = '.'; - *s++ = '.'; - *s++ = '.'; - break; - } - } - *s++ = '"'; - *s++ = 0; - return buf; -} - - - -QCC_def_t *QCC_PR_DefForFieldOfs (gofs_t ofs) -{ - QCC_def_t *d; - - for (d=pr.def_head.next ; d ; d=d->next) - { - if (d->type->type != ev_field) - continue; - if (*((unsigned int *)&qcc_pr_globals[d->ofs]) == ofs) - return d; - } - QCC_Error (ERR_NOTDEFINED, "PR_DefForFieldOfs: couldn't find %i",ofs); - return NULL; -} - -/* -============ -PR_ValueString - -Returns a string describing *data in a type specific manner -============= -*/ -char *QCC_PR_ValueString (etype_t type, void *val) -{ - static char line[256]; - QCC_def_t *def; - QCC_dfunction_t *f; - - switch (type) - { - case ev_string: - sprintf (line, "%s", QCC_PR_String(strings + *(int *)val)); - break; - case ev_entity: - sprintf (line, "entity %i", *(int *)val); - break; - case ev_function: - f = functions + *(int *)val; - if (!f) - sprintf (line, "undefined function"); - else - sprintf (line, "%s()", strings + f->s_name); - break; - case ev_field: - def = QCC_PR_DefForFieldOfs ( *(int *)val ); - sprintf (line, ".%s", def->name); - break; - case ev_void: - sprintf (line, "void"); - break; - case ev_float: - sprintf (line, "%5.1f", *(float *)val); - break; - case ev_integer: - sprintf (line, "%i", *(int *)val); - break; - case ev_vector: - sprintf (line, "'%5.1f %5.1f %5.1f'", ((float *)val)[0], ((float *)val)[1], ((float *)val)[2]); - break; - case ev_pointer: - sprintf (line, "pointer"); - break; - default: - sprintf (line, "bad type %i", type); - break; - } - - return line; -} - -/* -============ -PR_GlobalString - -Returns a string with a description and the contents of a global, -padded to 20 field width -============ -*/ -/*char *QCC_PR_GlobalStringNoContents (gofs_t ofs) -{ - int i; - QCC_def_t *def; - void *val; - static char line[128]; - - val = (void *)&qcc_pr_globals[ofs]; - def = pr_global_defs[ofs]; - if (!def) -// Error ("PR_GlobalString: no def for %i", ofs); - sprintf (line,"%i(?""?""?)", ofs); - else - sprintf (line,"%i(%s)", ofs, def->name); - - i = strlen(line); - for ( ; i<16 ; i++) - strcat (line," "); - strcat (line," "); - - return line; -} - -char *QCC_PR_GlobalString (gofs_t ofs) -{ - char *s; - int i; - QCC_def_t *def; - void *val; - static char line[128]; - - val = (void *)&qcc_pr_globals[ofs]; - def = pr_global_defs[ofs]; - if (!def) - return QCC_PR_GlobalStringNoContents(ofs); - if (def->initialized && def->type->type != ev_function) - { - s = QCC_PR_ValueString (def->type->type, &qcc_pr_globals[ofs]); - sprintf (line,"%i(%s)", ofs, s); - } - else - sprintf (line,"%i(%s)", ofs, def->name); - - i = strlen(line); - for ( ; i<16 ; i++) - strcat (line," "); - strcat (line," "); - - return line; -}*/ - -/* -============ -PR_PrintOfs -============ -*/ -/*void QCC_PR_PrintOfs (gofs_t ofs) -{ - printf ("%s\n",QCC_PR_GlobalString(ofs)); -}*/ - -/* -================= -PR_PrintStatement -================= -*/ -/*void QCC_PR_PrintStatement (QCC_dstatement_t *s) -{ - int i; - - printf ("%4i : %4i : %s ", (int)(s - statements), statement_linenums[s-statements], pr_opcodes[s->op].opname); - i = strlen(pr_opcodes[s->op].opname); - for ( ; i<10 ; i++) - printf (" "); - - if (s->op == OP_IF || s->op == OP_IFNOT) - printf ("%sbranch %i",QCC_PR_GlobalString(s->a),s->b); - else if (s->op == OP_GOTO) - { - printf ("branch %i",s->a); - } - else if ( (unsigned)(s->op - OP_STORE_F) < 6) - { - printf ("%s",QCC_PR_GlobalString(s->a)); - printf ("%s", QCC_PR_GlobalStringNoContents(s->b)); - } - else - { - if (s->a) - printf ("%s",QCC_PR_GlobalString(s->a)); - if (s->b) - printf ("%s",QCC_PR_GlobalString(s->b)); - if (s->c) - printf ("%s", QCC_PR_GlobalStringNoContents(s->c)); - } - printf ("\n"); -}*/ - - -/* -============ -PR_PrintDefs -============ -*/ -/*void QCC_PR_PrintDefs (void) -{ - QCC_def_t *d; - - for (d=pr.def_head.next ; d ; d=d->next) - QCC_PR_PrintOfs (d->ofs); -}*/ - -QCC_type_t *QCC_PR_NewType (char *name, int basictype) -{ - if (numtypeinfos>= maxtypeinfos) - QCC_Error(ERR_TOOMANYTYPES, "Too many types"); - memset(&qcc_typeinfo[numtypeinfos], 0, sizeof(QCC_type_t)); - qcc_typeinfo[numtypeinfos].type = basictype; - qcc_typeinfo[numtypeinfos].name = name; - qcc_typeinfo[numtypeinfos].num_parms = 0; - qcc_typeinfo[numtypeinfos].param = NULL; - qcc_typeinfo[numtypeinfos].size = type_size[basictype]; - - - numtypeinfos++; - - return &qcc_typeinfo[numtypeinfos-1]; -} - -/* -============== -PR_BeginCompilation - -called before compiling a batch of files, clears the pr struct -============== -*/ -void QCC_PR_BeginCompilation (void *memory, int memsize) -{ - extern int recursivefunctiontype; - extern struct freeoffset_s *freeofs; - int i; - char name[16]; - - pr.memory = memory; - pr.max_memory = memsize; - - pr.def_tail = &pr.def_head; - - QCC_PR_ResetErrorScope(); - pr_scope = NULL; - -/* numpr_globals = RESERVED_OFS; - - for (i=0 ; iaux_type = type_float; - type_pointer->aux_type = QCC_PR_NewType("pointeraux", ev_float); - - type_function->aux_type = type_void; - - //type_field->aux_type = type_float; - - if (keyword_integer) - type_integer = QCC_PR_NewType("integer", ev_integer); - if (keyword_int) - type_integer = QCC_PR_NewType("int", ev_integer); - - - - if (output_parms) - { //this tends to confuse the brains out of decompilers. :) - numpr_globals = 1; - QCC_PR_GetDef(type_vector, "RETURN", NULL, true, 1, false)->references++; - for (i = 0; i < MAX_PARMS; i++) - { - sprintf(name, "PARM%i", i); - QCC_PR_GetDef(type_vector, name, NULL, true, 1, false)->references++; - } - } - else - { - numpr_globals = RESERVED_OFS; -// for (i=0 ; inext = NULL; - pr_error_count = 0; - pr_warning_count = 0; - recursivefunctiontype = 0; - - freeofs = NULL; -} - -/* -============== -PR_FinishCompilation - -called after all files are compiled to check for errors -Returns false if errors were detected. -============== -*/ -int QCC_PR_FinishCompilation (void) -{ - QCC_def_t *d; - int errors; - - errors = false; - -// check to make sure all functions prototyped have code - for (d=pr.def_head.next ; d ; d=d->next) - { - if (d->type->type == ev_function && !d->scope)// function parms are ok - { -// f = G_FUNCTION(d->ofs); -// if (!f || (!f->code && !f->builtin) ) - if (d->initialized==0) - { - if (!strncmp(d->name, "ArrayGet*", 9)) - { - QCC_PR_EmitArrayGetFunction(d, d->name+9); - pr_scope = NULL; - } - else if (!strncmp(d->name, "ArraySet*", 9)) - { - QCC_PR_EmitArraySetFunction(d, d->name+9); - pr_scope = NULL; - } - else if (!strncmp(d->name, "Class*", 6)) - { - QCC_PR_EmitClassFromFunction(d, d->name+6); - pr_scope = NULL; - } - else - { - QCC_PR_ParseErrorPrintDef(ERR_NOFUNC, d, "function %s was not defined",d->name); - bodylessfuncs = true; - errors = true; - } -// errors = true; - } - else if (d->initialized==2) - bodylessfuncs = true; - } - } - pr_scope = NULL; - - return !errors; -} - -//============================================================================= - -// 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 QCC_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 QCC_CRC_Init(unsigned short *crcvalue) -{ - *crcvalue = CRC_INIT_VALUE; -} - -void QCC_CRC_ProcessByte(unsigned short *crcvalue, qbyte data) -{ - *crcvalue = (*crcvalue << 8) ^ QCC_crctable[(*crcvalue >> 8) ^ data]; -} - -unsigned short QCC_CRC_Value(unsigned short crcvalue) -{ - return crcvalue ^ CRC_XOR_VALUE; -} -//============================================================================= - - -/* -============ -PR_WriteProgdefs - -Writes the global and entity structures out -Returns a crc of the header, to be stored in the progs file for comparison -at load time. -============ -*/ -/* -char *Sva(char *msg, ...) -{ - va_list l; - static char buf[1024]; - - va_start(l, msg); - QC_vsnprintf (buf,sizeof(buf)-1, msg, l); - va_end(l); - - return buf; -} -*/ - -#define PROGDEFS_MAX_SIZE 16384 -//write (to file buf) and add to the crc -static void Add(char *p, unsigned short *crc, char *file) -{ - char *s; - int i = strlen(file); - if (i + strlen(p)+1 >= PROGDEFS_MAX_SIZE) - return; - for(s=p;*s;s++,i++) - { - QCC_CRC_ProcessByte(crc, *s); - file[i] = *s; - } - file[i]='\0'; -} -#define ADD(p) Add(p, &crc, file) -//#define ADD(p) {char *s;int i = strlen(p);for(s=p;*s;s++,i++){QCC_CRC_ProcessByte(&crc, *s);file[i] = *s;}file[i]='\0';} - -static void Add3(char *p, unsigned short *crc, char *file) -{ - char *s; - for(s=p;*s;s++) - QCC_CRC_ProcessByte(crc, *s); -} -#define ADD3(p) Add3(p, &crc, file) - -unsigned short QCC_PR_WriteProgdefs (char *filename) -{ -#define ADD2(p) strncat(file, p, PROGDEFS_MAX_SIZE-1 - strlen(file)) //no crc (later changes) - char file[PROGDEFS_MAX_SIZE]; - QCC_def_t *d; - int f; - unsigned short crc; -// int c; - - file[0] = '\0'; - - QCC_CRC_Init (&crc); - -// print global vars until the first field is defined - - //ADD: crc and dump - //ADD2: dump but don't crc - //ADD3: crc but don't dump - - ADD("\n/* "); - if (qcc_targetformat == QCF_HEXEN2) - ADD3("generated by hcc, do not modify"); - else - ADD3("file generated by qcc, do not modify"); - ADD2("File generated by FTEQCC, relevent for engine modding only, the generated crc must be the same as your engine expects."); - ADD(" */\n\ntypedef struct"); - ADD2(" globalvars_s"); - ADD(qcva("\n{")); - ADD2("\tint pad;\n" - "\tint ofs_return[3];\n" //makes it easier with the get globals func - "\tint ofs_parm0[3];\n" - "\tint ofs_parm1[3];\n" - "\tint ofs_parm2[3];\n" - "\tint ofs_parm3[3];\n" - "\tint ofs_parm4[3];\n" - "\tint ofs_parm5[3];\n" - "\tint ofs_parm6[3];\n" - "\tint ofs_parm7[3];\n"); - ADD3(qcva("\tint\tpad[%i];\n", RESERVED_OFS)); - for (d=pr.def_head.next ; d ; d=d->next) - { - if (!strcmp (d->name, "end_sys_globals")) - break; - if (d->ofstype->type) - { - case ev_float: - ADD(qcva("\tfloat\t%s;\n",d->name)); - break; - case ev_vector: - ADD(qcva("\tvec3_t\t%s;\n",d->name)); - d=d->next->next->next; // skip the elements - break; - case ev_string: - ADD(qcva("\tstring_t\t%s;\n",d->name)); - break; - case ev_function: - ADD(qcva("\tfunc_t\t%s;\n",d->name)); - break; - case ev_entity: - ADD(qcva("\tint\t%s;\n",d->name)); - break; - case ev_integer: - ADD(qcva("\tint\t%s;\n",d->name)); - break; - default: - ADD(qcva("\tint\t%s;\n",d->name)); - break; - } - } - ADD("} globalvars_t;\n\n"); - -// print all fields - ADD("typedef struct"); - ADD2(" entvars_s"); - ADD("\n{\n"); - for (d=pr.def_head.next ; d ; d=d->next) - { - if (!strcmp (d->name, "end_sys_fields")) - break; - - if (d->type->type != ev_field) - continue; - - switch (d->type->aux_type->type) - { - case ev_float: - ADD(qcva("\tfloat\t%s;\n",d->name)); - break; - case ev_vector: - ADD(qcva("\tvec3_t\t%s;\n",d->name)); - d=d->next->next->next; // skip the elements - break; - case ev_string: - ADD(qcva("\tstring_t\t%s;\n",d->name)); - break; - case ev_function: - ADD(qcva("\tfunc_t\t%s;\n",d->name)); - break; - case ev_entity: - ADD(qcva("\tint\t%s;\n",d->name)); - break; - case ev_integer: - ADD(qcva("\tint\t%s;\n",d->name)); - break; - default: - ADD(qcva("\tint\t%s;\n",d->name)); - break; - } - } - ADD("} entvars_t;\n\n"); - - ///temp - ADD2("//with this the crc isn't needed for fields.\n#ifdef FIELDSSTRUCT\nstruct fieldvars_s {\n\tint ofs;\n\tint type;\n\tchar *name;\n} fieldvars[] = {\n"); - f=0; - for (d=pr.def_head.next ; d ; d=d->next) - { - if (!strcmp (d->name, "end_sys_fields")) - break; - - if (d->type->type != ev_field) - continue; - if (f) - ADD2(",\n"); - ADD2(qcva("\t{%i,\t%i,\t\"%s\"}",G_INT(d->ofs), d->type->aux_type->type, d->name)); - f = 1; - } - ADD2("\n};\n#endif\n\n"); - //end temp - - ADD2(qcva("#define PROGHEADER_CRC %i\n", crc)); - - if (QCC_CheckParm("-progdefs")) - { - printf ("writing %s\n", filename); - f = SafeOpenWrite(filename, 16384); - SafeWrite(f, file, strlen(file)); - SafeClose(f); - } - - - if (ForcedCRC) - crc = ForcedCRC; - - switch (crc) - { - case 12923: //#pragma sourcefile usage - break; - case 54730: - if (verbose) - printf("Recognised progs as QuakeWorld\n"); - break; - case 5927: - if (verbose) - printf("Recognised progs as NetQuake server gamecode\n"); - break; - - case 26940: - if (verbose) - printf("Recognised progs as Quake pre-release...\n"); - break; - - case 38488: - if (verbose) - printf("Recognised progs as original Hexen2\n"); - break; - case 26905: - if (verbose) - printf("Recognised progs as Hexen2 Mission Pack\n"); - break; - case 14046: - if (verbose) - printf("Recognised progs as Hexen2 (demo)\n"); - break; - - case 22390: //EXT_CSQC_1 - if (verbose) - printf("Recognised progs as an EXT_CSQC_1 module\n"); - break; - case 17105: - case 32199: //outdated ext_csqc - printf("Recognised progs as outdated CSQC module\n"); - break; - case 52195: - printf("Recognised progs as outdated CSQC module\n"); - break; - case 10020: - if (verbose) - printf("Recognised progs as a DP/FTE Menu module\n"); - break; - - case 32401: - printf("Warning: please update your tenebrae system defs.\n"); - break; - default: - printf("Warning: progs CRC not recognised from quake nor clones\n"); - break; - } - - - return crc; -} - - -/*void QCC_PrintFunction (char *name) -{ - int i; - QCC_dstatement_t *ds; - QCC_dfunction_t *df; - - for (i=0 ; ifirst_statement; - while (1) - { - QCC_PR_PrintStatement (ds); - if (!ds->op) - break; - ds++; - } -}*/ -/* -void QCC_PrintOfs(unsigned int ofs) -{ - int i; - bool printfunc; - QCC_dstatement_t *ds; - QCC_dfunction_t *df; - - for (i=0 ; ifirst_statement; - printfunc = false; - while (1) - { - if (!ds->op) - break; - if (ds->a == ofs || ds->b == ofs || ds->c == ofs) - { - QCC_PR_PrintStatement (ds); - printfunc = true; - } - ds++; - } - if (printfunc) - { - QCC_PrintFunction(strings + functions[i].s_name); - printf(" \n \n"); - } - } - -} -*/ -/* -============================================================================== - -DIRECTORY COPYING / PACKFILE CREATION - -============================================================================== -*/ - -typedef struct -{ - char name[56]; - int filepos, filelen; -} packfile_t; - -typedef struct -{ - char id[4]; - int dirofs; - int dirlen; -} packheader_t; - -packfile_t pfiles[4096], *pf; -int packhandle; -int packbytes; - - -/* -============ -CreatePath -============ -*/ -void QCC_CreatePath (char *path) -{ - /* - char *ofs; - - for (ofs = path+1 ; *ofs ; ofs++) - { - if (*ofs == '/') - { // create the directory - *ofs = 0; -#ifdef QCC - mkdir(path); -#else - QCC_mkdir (path); -#endif - *ofs = '/'; - } - } - */ -} - - -/* -=========== -PackFile - -Copy a file into the pak file -=========== -*/ -void QCC_PackFile (char *src, char *name) -{ - int remaining; -#if 1 - char *f; -#else - int in; - int count; - char buf[4096]; -#endif - - - if ( (qbyte *)pf - (qbyte *)pfiles > sizeof(pfiles) ) - QCC_Error (ERR_TOOMANYPAKFILES, "Too many files in pak file"); - -#if 1 - f = FS_ReadToMem(src, NULL, &remaining); - if (!f) - { - printf ("%64s : %7s\n", name, ""); -// QCC_Error("Failed to open file %s", src); - return; - } - - pf->filepos = PRLittleLong (SafeSeek (packhandle, 0, SEEK_CUR)); - pf->filelen = PRLittleLong (remaining); - strcpy (pf->name, name); - printf ("%64s : %7i\n", pf->name, remaining); - - packbytes += remaining; - - SafeWrite (packhandle, f, remaining); - - FS_CloseFromMem(f); -#else - in = SafeOpenRead (src); - remaining = filelength (in); - - pf->filepos = PRLittleLong (lseek (packhandle, 0, SEEK_CUR)); - pf->filelen = PRLittleLong (remaining); - strcpy (pf->name, name); - printf ("%64s : %7i\n", pf->name, remaining); - - packbytes += remaining; - - while (remaining) - { - if (remaining < sizeof(buf)) - count = remaining; - else - count = sizeof(buf); - SafeRead (in, buf, count); - SafeWrite (packhandle, buf, count); - remaining -= count; - } - - close (in); -#endif - pf++; -} - - -/* -=========== -CopyFile - -Copies a file, creating any directories needed -=========== -*/ -void QCC_CopyFile (char *src, char *dest) -{ - /* - int in, out; - int remaining, count; - char buf[4096]; - - print ("%s to %s\n", src, dest); - - in = SafeOpenRead (src); - remaining = filelength (in); - - QCC_CreatePath (dest); - out = SafeOpenWrite (dest, remaining+10); - - while (remaining) - { - if (remaining < sizeof(buf)) - count = remaining; - else - count = sizeof(buf); - SafeRead (in, buf, count); - SafeWrite (out, buf, count); - remaining -= count; - } - - close (in); - SafeClose (out); - */ -} - - -/* -=========== -CopyFiles -=========== -*/ - -void _QCC_CopyFiles (int blocknum, int copytype, char *srcdir, char *destdir) -{ - int i; - int dirlen; - unsigned short crc; - packheader_t header; - char name[1024]; - char srcfile[1024], destfile[1024]; - - packbytes = 0; - - if (copytype == 2) - { - pf = pfiles; - packhandle = SafeOpenWrite (destdir, 1024*1024); - SafeWrite (packhandle, &header, sizeof(header)); - } - - for (i=0 ; i 0) - printf ("%3i unique precache_sounds\n", numsounds); - if (nummodels > 0) - printf ("%3i unique precache_models\n", nummodels); - if (numtextures > 0) - printf ("%3i unique precache_textures\n", numtextures); - if (numfiles > 0) - printf ("%3i unique precache_files\n", numfiles); - } - - p = QCC_CheckParm ("-copy"); - if (p && p < myargc-2) - { // create a new directory tree - - strcpy (srcdir, myargv[p+1]); - strcpy (destdir, myargv[p+2]); - if (srcdir[strlen(srcdir)-1] != '/') - strcat (srcdir, "/"); - if (destdir[strlen(destdir)-1] != '/') - strcat (destdir, "/"); - - _QCC_CopyFiles(0, 1, srcdir, destdir); - return; - } - - for ( p = 0; p < 5; p++) - { - s = QCC_Packname[p]; - if (!*s) - continue; - strcpy(destdir, s); - strcpy(srcdir, ""); - _QCC_CopyFiles(p+1, 2, srcdir, destdir); - } - return; - /* - - blocknum = 1; - p = QCC_CheckParm ("-pak2"); - if (p && p = sizeof(cnst->value)) - QCC_Error(ERR_PRECOMPILERCONSTANTTOOLONG, "Compiler constant value is too long\n"); - strncpy(cnst->value, val, sizeof(cnst->value)-1); - cnst->value[sizeof(cnst->value)-1] = '\0'; - } - } - - //optimisations. - else if ( !strnicmp(myargv[i], "-O", 2) || !strnicmp(myargv[i], "/O", 2) ) - { - p = 0; - if (myargv[i][2] >= '0' && myargv[i][2] <= '3') - { - } - else if (!strnicmp(myargv[i]+2, "no-", 3)) - { - if (myargv[i][5]) - { - for (p = 0; optimisations[p].enabled; p++) - { - if ((*optimisations[p].abbrev && !stricmp(myargv[i]+5, optimisations[p].abbrev)) || !stricmp(myargv[i]+5, optimisations[p].fullname)) - { - *optimisations[p].enabled = false; - break; - } - } - } - } - else - { - if (myargv[i][2]) - for (p = 0; optimisations[p].enabled; p++) - if ((*optimisations[p].abbrev && !stricmp(myargv[i]+2, optimisations[p].abbrev)) || !stricmp(myargv[i]+2, optimisations[p].fullname)) - { - *optimisations[p].enabled = true; - break; - } - } - if (!optimisations[p].enabled) - QCC_PR_Warning(0, NULL, WARN_BADPARAMS, "Unrecognised optimisation parameter (%s)", myargv[i]); - } - - else if ( !strnicmp(myargv[i], "-K", 2) || !strnicmp(myargv[i], "/K", 2) ) - { - p = 0; - if (!strnicmp(myargv[i]+2, "no-", 3)) - { - for (p = 0; compiler_flag[p].enabled; p++) - if (!stricmp(myargv[i]+5, compiler_flag[p].abbrev)) - { - *compiler_flag[p].enabled = false; - break; - } - } - else - { - for (p = 0; compiler_flag[p].enabled; p++) - if (!stricmp(myargv[i]+2, compiler_flag[p].abbrev)) - { - *compiler_flag[p].enabled = true; - break; - } - } - - if (!compiler_flag[p].enabled) - QCC_PR_Warning(0, NULL, WARN_BADPARAMS, "Unrecognised keyword parameter (%s)", myargv[i]); - } - else if ( !strnicmp(myargv[i], "-F", 2) || !strnicmp(myargv[i], "/F", 2) ) - { - p = 0; - if (!strnicmp(myargv[i]+2, "no-", 3)) - { - for (p = 0; compiler_flag[p].enabled; p++) - if (!stricmp(myargv[i]+5, compiler_flag[p].abbrev)) - { - *compiler_flag[p].enabled = false; - break; - } - } - else - { - for (p = 0; compiler_flag[p].enabled; p++) - if (!stricmp(myargv[i]+2, compiler_flag[p].abbrev)) - { - *compiler_flag[p].enabled = true; - break; - } - } - - if (!compiler_flag[p].enabled) - QCC_PR_Warning(0, NULL, WARN_BADPARAMS, "Unrecognised flag parameter (%s)", myargv[i]); - } - - - else if ( !strncmp(myargv[i], "-T", 2) || !strncmp(myargv[i], "/T", 2) ) - { - p = 0; - for (p = 0; targets[p].name; p++) - if (!stricmp(myargv[i]+2, targets[p].name)) - { - qcc_targetformat = targets[p].target; - break; - } - - if (!targets[p].name) - QCC_PR_Warning(0, NULL, WARN_BADPARAMS, "Unrecognised target parameter (%s)", myargv[i]); - } - - else if ( !strnicmp(myargv[i], "-W", 2) || !strnicmp(myargv[i], "/W", 2) ) - { - if (!stricmp(myargv[i]+2, "all")) - memset(qccwarningdisabled, 0, sizeof(qccwarningdisabled)); - else if (!stricmp(myargv[i]+2, "none")) - memset(qccwarningdisabled, 1, sizeof(qccwarningdisabled)); - else if(!stricmp(myargv[i]+2, "error")) - pr_werror = true; - else if (!stricmp(myargv[i]+2, "no-mundane")) - { //disable mundane performance/efficiency/blah warnings that don't affect code. - qccwarningdisabled[WARN_SAMENAMEASGLOBAL] = true; - qccwarningdisabled[WARN_DUPLICATEDEFINITION] = true; - qccwarningdisabled[WARN_CONSTANTCOMPARISON] = true; - qccwarningdisabled[WARN_ASSIGNMENTINCONDITIONAL] = true; - qccwarningdisabled[WARN_DEADCODE] = true; - qccwarningdisabled[WARN_NOTREFERENCEDCONST] = true; - qccwarningdisabled[WARN_NOTREFERENCED] = true; - qccwarningdisabled[WARN_POINTLESSSTATEMENT] = true; - qccwarningdisabled[WARN_ASSIGNMENTTOCONSTANTFUNC] = true; - qccwarningdisabled[WARN_BADPRAGMA] = true; //C specs say that these should be ignored. We're close enough to C that I consider that a valid statement. - qccwarningdisabled[WARN_IDENTICALPRECOMPILER] = true; - qccwarningdisabled[WARN_UNDEFNOTDEFINED] = true; - qccwarningdisabled[WARN_FIXEDRETURNVALUECONFLICT] = true; - qccwarningdisabled[WARN_EXTRAPRECACHE] = true; - qccwarningdisabled[WARN_CORRECTEDRETURNTYPE] = true; - } - else - { - p = 0; - if (!strnicmp(myargv[i]+2, "no-", 3)) - { - for (p = 0; warningnames[p].name; p++) - if (!strcmp(myargv[i]+5, warningnames[p].name)) - { - qccwarningdisabled[warningnames[p].index] = true; - break; - } - } - else - { - for (p = 0; warningnames[p].name; p++) - if (!stricmp(myargv[i]+2, warningnames[p].name)) - { - qccwarningdisabled[warningnames[p].index] = false; - break; - } - } - - if (!warningnames[p].name) - QCC_PR_Warning(0, NULL, WARN_BADPARAMS, "Unrecognised warning parameter (%s)", myargv[i]); - } - } - } -} - -/* -============ -main -============ -*/ - -char *qccmsrc; -char *qccmsrc2; -char qccmfilename[1024]; -char qccmprogsdat[1024]; -char qccmsourcedir[1024]; - -void QCC_FinishCompile(void); - - -void SetEndian(void); - - - -void QCC_SetDefaultProperties (void) -{ - int level; - int i; - - Hash_InitTable(&compconstantstable, MAX_CONSTANTS, qccHunkAlloc(Hash_BytesForBuckets(MAX_CONSTANTS))); - - ForcedCRC = 0; - defaultstatic = 0; - - QCC_PR_DefineName("FTEQCC"); - - if (QCC_CheckParm("/Oz")) - { - qcc_targetformat = QCF_FTE; - QCC_PR_DefineName("OP_COMP_STATEMENTS"); - QCC_PR_DefineName("OP_COMP_DEFS"); - QCC_PR_DefineName("OP_COMP_FIELDS"); - QCC_PR_DefineName("OP_COMP_FUNCTIONS"); - QCC_PR_DefineName("OP_COMP_STRINGS"); - QCC_PR_DefineName("OP_COMP_GLOBALS"); - QCC_PR_DefineName("OP_COMP_LINES"); - QCC_PR_DefineName("OP_COMP_TYPES"); - } - - if (QCC_CheckParm("/O0") || QCC_CheckParm("-O0")) - level = 0; - else if (QCC_CheckParm("/O1") || QCC_CheckParm("-O1")) - level = 1; - else if (QCC_CheckParm("/O2") || QCC_CheckParm("-O2")) - level = 2; - else if (QCC_CheckParm("/O3") || QCC_CheckParm("-O3")) - level = 3; - else - level = -1; - - if (level == -1) - { - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_ASDEFAULT) - *optimisations[i].enabled = true; - else - *optimisations[i].enabled = false; - } - } - else - { - for (i = 0; optimisations[i].enabled; i++) - { - if (level >= optimisations[i].optimisationlevel) - *optimisations[i].enabled = true; - else - *optimisations[i].enabled = false; - } - } - - if (QCC_CheckParm ("-h2")) - qcc_targetformat = QCF_HEXEN2; - else if (QCC_CheckParm ("-fte")) - qcc_targetformat = QCF_FTE; - else if (QCC_CheckParm ("-dp")) - qcc_targetformat = QCF_DARKPLACES; - else - qcc_targetformat = QCF_STANDARD; - - - //enable all warnings - memset(qccwarningdisabled, 0, sizeof(qccwarningdisabled)); - - //play with default warnings. - qccwarningdisabled[WARN_NOTREFERENCEDCONST] = true; - qccwarningdisabled[WARN_MACROINSTRING] = true; -// qccwarningdisabled[WARN_ASSIGNMENTTOCONSTANT] = true; - qccwarningdisabled[WARN_FIXEDRETURNVALUECONFLICT] = true; - qccwarningdisabled[WARN_EXTRAPRECACHE] = true; - qccwarningdisabled[WARN_DEADCODE] = true; - qccwarningdisabled[WARN_INEFFICIENTPLUSPLUS] = true; - qccwarningdisabled[WARN_FTE_SPECIFIC] = true; - qccwarningdisabled[WARN_EXTENSION_USED] = true; - qccwarningdisabled[WARN_IFSTRING_USED] = true; - - - - if (QCC_CheckParm("-nowarn") || QCC_CheckParm("-Wnone")) - memset(qccwarningdisabled, 1, sizeof(qccwarningdisabled)); - if (QCC_CheckParm("-Wall")) - memset(qccwarningdisabled, 0, sizeof(qccwarningdisabled)); - - if (QCC_CheckParm("-h2")) - qccwarningdisabled[WARN_CASEINSENSATIVEFRAMEMACRO] = true; - - //Check the command line - QCC_PR_CommandLinePrecompilerOptions(); - - - if (qcc_targetformat == QCF_HEXEN2) //force on the thinktime keyword if hexen2 progs. - keyword_thinktime = true; - - if (QCC_CheckParm("/Debug")) //disable any debug optimisations - { - for (i = 0; optimisations[i].enabled; i++) - { - if (optimisations[i].flags & FLAG_KILLSDEBUGGERS) - *optimisations[i].enabled = false; - } - } -} - -//builds a list of files, pretends that they came from a progs.src -int QCC_FindQCFiles() -{ -#ifdef _WIN32 - WIN32_FIND_DATA fd; - HANDLE h; -#endif - - int numfiles = 0, i, j; - char *filelist[256], *temp; - - - qccmsrc = qccHunkAlloc(8192); - strcat(qccmsrc, "progs.dat\n");//"#pragma PROGS_DAT progs.dat\n"); - -#ifdef _WIN32 - h = FindFirstFile("*.qc", &fd); - if (h == INVALID_HANDLE_VALUE) - return 0; - - do - { - filelist[numfiles] = qccHunkAlloc (strlen(fd.cFileName)+1); - strcpy(filelist[numfiles], fd.cFileName); - numfiles++; - } while(FindNextFile(h, &fd)!=0); - FindClose(h); -#else - printf("-Facc is not supported on this platform. Please make a progs.src file instead\n"); -#endif - - //Sort alphabetically. - //bubble. :( - - for (i = 0; i < numfiles-1; i++) - { - for (j = i+1; j < numfiles; j++) - { - if (stricmp(filelist[i], filelist[j]) > 0) - { - temp = filelist[j]; - filelist[j] = filelist[i]; - filelist[i] = temp; - } - } - } - for (i = 0; i < numfiles; i++) - { - strcat(qccmsrc, filelist[i]); - strcat(qccmsrc, "\n"); -// strcat(qccmsrc, "#include \""); -// strcat(qccmsrc, filelist[i]); -// strcat(qccmsrc, "\"\n"); - } - - return numfiles; -} - -int qcc_compileactive = false; -extern int accglobalsblock; -char *originalqccmsrc; //for autoprototype. -void QCC_main (int argc, char **argv) //as part of the quake engine -{ - extern int pr_bracelevel; - - int p; - -#ifndef QCCONLY - char destfile2[1024], *s2; -#endif - char *s; - - SetEndian(); - - myargc = argc; - myargv = argv; - - qcc_compileactive = true; - - pHash_Get = &Hash_Get; - pHash_GetNext = &Hash_GetNext; - pHash_Add = &Hash_Add; - - MAX_REGS = 65536; - MAX_STRINGS = 1000000; - MAX_GLOBALS = 32768; - MAX_FIELDS = 2048; - MAX_STATEMENTS = 0x80000; - MAX_FUNCTIONS = 16384; - maxtypeinfos = 16384; - MAX_CONSTANTS = 2048; - - compressoutput = 0; - - p = externs->FileSize("qcc.cfg"); - if (p < 0) - p = externs->FileSize("src/qcc.cfg"); - if (p>0) - { - s = qccHunkAlloc(p+1); - s = externs->ReadFile("qcc.cfg", s, p); - - while(1) - { - s = QCC_COM_Parse(s); - if (!strcmp(qcc_token, "MAX_REGS")) - { - s = QCC_COM_Parse(s); - MAX_REGS = atoi(qcc_token); - } else if (!strcmp(qcc_token, "MAX_STRINGS")) { - s = QCC_COM_Parse(s); - MAX_STRINGS = atoi(qcc_token); - } else if (!strcmp(qcc_token, "MAX_GLOBALS")) { - s = QCC_COM_Parse(s); - MAX_GLOBALS = atoi(qcc_token); - } else if (!strcmp(qcc_token, "MAX_FIELDS")) { - s = QCC_COM_Parse(s); - MAX_FIELDS = atoi(qcc_token); - } else if (!strcmp(qcc_token, "MAX_STATEMENTS")) { - s = QCC_COM_Parse(s); - MAX_STATEMENTS = atoi(qcc_token); - } else if (!strcmp(qcc_token, "MAX_FUNCTIONS")) { - s = QCC_COM_Parse(s); - MAX_FUNCTIONS = atoi(qcc_token); - } else if (!strcmp(qcc_token, "MAX_TYPES")) { - s = QCC_COM_Parse(s); - maxtypeinfos = atoi(qcc_token); - } else if (!strcmp(qcc_token, "MAX_TEMPS")) { - s = QCC_COM_Parse(s); - max_temps = atoi(qcc_token); - } else if (!strcmp(qcc_token, "CONSTANTS")) { - s = QCC_COM_Parse(s); - MAX_CONSTANTS = atoi(qcc_token); - } - else if (!s) - break; - else - printf("Bad token in qcc.cfg file\n"); - } - } - /* don't try to be clever - else if (p < 0) - { - s = qccHunkAlloc(8192); - sprintf(s, "MAX_REGS\t%i\r\nMAX_STRINGS\t%i\r\nMAX_GLOBALS\t%i\r\nMAX_FIELDS\t%i\r\nMAX_STATEMENTS\t%i\r\nMAX_FUNCTIONS\t%i\r\nMAX_TYPES\t%i\r\n", - MAX_REGS, MAX_STRINGS, MAX_GLOBALS, MAX_FIELDS, MAX_STATEMENTS, MAX_FUNCTIONS, maxtypeinfos); - externs->WriteFile("qcc.cfg", s, strlen(s)); - } - */ - - strcpy(QCC_copyright, "This file was created with ForeThought's modified QuakeC compiler\nThanks to ID Software"); - for (p = 0; p < 5; p++) - strcpy(QCC_Packname[p], ""); - - for (p = 0; compiler_flag[p].enabled; p++) - { - *compiler_flag[p].enabled = compiler_flag[p].flags & FLAG_ASDEFAULT; - } - pr_werror = false; - - QCC_SetDefaultProperties(); - - optres_shortenifnots = 0; - optres_overlaptemps = 0; - optres_noduplicatestrings = 0; - optres_constantarithmatic = 0; - optres_nonvec_parms = 0; - optres_constant_names = 0; - optres_constant_names_strings = 0; - optres_precache_file = 0; - optres_filenames = 0; - optres_assignments = 0; - optres_unreferenced = 0; - optres_function_names = 0; - optres_locals = 0; - optres_dupconstdefs = 0; - optres_return_only = 0; - optres_compound_jumps = 0; -// optres_comexprremoval = 0; - optres_stripfunctions = 0; - optres_locals_marshalling = 0; - optres_logicops = 0; - - optres_test1 = 0; - optres_test2 = 0; - - accglobalsblock = 0; - - - numtemps = 0; - - functemps=NULL; - - strings = (void *)qccHunkAlloc(sizeof(char) * MAX_STRINGS); - strofs = 1; - - statements = (void *)qccHunkAlloc(sizeof(QCC_dstatement_t) * MAX_STATEMENTS); - numstatements = 0; - statement_linenums = (void *)qccHunkAlloc(sizeof(int) * MAX_STATEMENTS); - - functions = (void *)qccHunkAlloc(sizeof(QCC_dfunction_t) * MAX_FUNCTIONS); - numfunctions=0; - - pr_bracelevel = 0; - - qcc_pr_globals = (void *)qccHunkAlloc(sizeof(float) * MAX_REGS); - numpr_globals=0; - - Hash_InitTable(&globalstable, MAX_REGS, qccHunkAlloc(Hash_BytesForBuckets(MAX_REGS))); - Hash_InitTable(&localstable, MAX_REGS, qccHunkAlloc(Hash_BytesForBuckets(MAX_REGS))); - Hash_InitTable(&floatconstdefstable, MAX_REGS+1, qccHunkAlloc(Hash_BytesForBuckets(MAX_REGS+1))); - Hash_InitTable(&stringconstdefstable, MAX_REGS, qccHunkAlloc(Hash_BytesForBuckets(MAX_REGS))); - Hash_InitTable(&stringconstdefstable_dotranslate, MAX_REGS, qccHunkAlloc(Hash_BytesForBuckets(MAX_REGS))); - dotranslate=0; - dotranslate_count=0; - -// pr_global_defs = (QCC_def_t **)qccHunkAlloc(sizeof(QCC_def_t *) * MAX_REGS); - - qcc_globals = (void *)qccHunkAlloc(sizeof(QCC_ddef_t) * MAX_GLOBALS); - numglobaldefs=0; - - fields = (void *)qccHunkAlloc(sizeof(QCC_ddef_t) * MAX_FIELDS); - numfielddefs=0; - -memset(pr_immediate_string, 0, sizeof(pr_immediate_string)); - - precache_sounds = (void *)qccHunkAlloc(sizeof(char)*MAX_DATA_PATH*MAX_SOUNDS); - precache_sounds_block = (void *)qccHunkAlloc(sizeof(int)*MAX_SOUNDS); - precache_sounds_used = (void *)qccHunkAlloc(sizeof(int)*MAX_SOUNDS); - numsounds=0; - - precache_textures = (void *)qccHunkAlloc(sizeof(char)*MAX_DATA_PATH*MAX_TEXTURES); - precache_textures_block = (void *)qccHunkAlloc(sizeof(int)*MAX_TEXTURES); - numtextures=0; - - precache_models = (void *)qccHunkAlloc(sizeof(char)*MAX_DATA_PATH*MAX_MODELS); - precache_models_block = (void *)qccHunkAlloc(sizeof(int)*MAX_MODELS); - precache_models_used = (void *)qccHunkAlloc(sizeof(int)*MAX_MODELS); - nummodels=0; - - precache_files = (void *)qccHunkAlloc(sizeof(char)*MAX_DATA_PATH*MAX_FILES); - precache_files_block = (void *)qccHunkAlloc(sizeof(int)*MAX_FILES); - numfiles = 0; - - qcc_typeinfo = (void *)qccHunkAlloc(sizeof(QCC_type_t)*maxtypeinfos); - numtypeinfos = 0; - - qcc_tempofs = qccHunkAlloc(sizeof(int) * max_temps); - tempsstart = 0; - - bodylessfuncs=0; - - memset(&pr, 0, sizeof(pr)); -#ifdef MAX_EXTRA_PARMS - memset(&extra_parms, 0, sizeof(extra_parms)); -#endif - - if ( QCC_CheckParm ("/?") || QCC_CheckParm ("?") || QCC_CheckParm ("-?") || QCC_CheckParm ("-help") || QCC_CheckParm ("--help")) - { - printf ("qcc looks for progs.src in the current directory.\n"); - printf ("to look in a different directory: qcc -src \n"); -// printf ("to build a clean data tree: qcc -copy \n"); -// printf ("to build a clean pak file: qcc -pak \n"); -// printf ("to bsp all bmodels: qcc -bspmodels \n"); - printf ("-Fwasm causes FTEQCC to dump all asm to qc.asm\n"); - printf ("-O0 to disable optimisations\n"); - printf ("-O1 to optimise for size\n"); - printf ("-O2 to optimise more - some behaviours may change\n"); - printf ("-O3 to optimise lots - experimental or non-future-proof\n"); - printf ("-Oname to enable an optimisation\n"); - printf ("-Ono-name to disable optimisations\n"); - printf ("-Kkeyword to activate keyword\n"); - printf ("-Kno-keyword to disable keyword\n"); - printf ("-Wall to give a stupid number of warnings\n"); - printf ("-Ttarget to set a output format\n"); - printf ("-Fautoproto to enable automatic prototyping\n"); - printf ("-Fsubscope to enable subscopes\n"); - - qcc_compileactive = false; - return; - } - - if (flag_caseinsensative) - { - printf("Compiling without case sensativity\n"); - pHash_Get = &Hash_GetInsensative; - pHash_GetNext = &Hash_GetNextInsensative; - pHash_Add = &Hash_AddInsensative; - } - - - if (opt_locals_marshalling) - printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\nLocals marshalling might be buggy. Use with caution\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); - - p = QCC_CheckParm ("-src"); - if (p && p < argc-1 ) - { - strcpy (qccmsourcedir, argv[p+1]); - strcat (qccmsourcedir, "/"); - printf ("Source directory: %s\n", qccmsourcedir); - } - else - *qccmsourcedir = '\0'; - - QCC_InitData (); - - QCC_PR_BeginCompilation ((void *)qccHunkAlloc (0x100000), 0x100000); - - if (flag_acc) - { - if (!QCC_FindQCFiles()) - QCC_Error (ERR_COULDNTOPENFILE, "Couldn't open file for asm output."); - } - else - { - if (!numsourcefiles) - { - p = QCC_CheckParm ("-qc"); - if (!p || p >= argc-1 || argv[p+1][0] == '-') - p = QCC_CheckParm ("-srcfile"); - if (p && p < argc-1 ) - sprintf (qccmprogsdat, "%s%s", qccmsourcedir, argv[p+1]); - else - { //look for a preprogs.src... :o) - sprintf (qccmprogsdat, "%spreprogs.src", qccmsourcedir); - if (externs->FileSize(qccmprogsdat) <= 0) - sprintf (qccmprogsdat, "%sprogs.src", qccmsourcedir); - } - - numsourcefiles = 0; - strcpy(sourcefileslist[numsourcefiles++], qccmprogsdat); - currentsourcefile = 0; - } - else if (currentsourcefile == numsourcefiles) - { - //no more. - qcc_compileactive = false; - numsourcefiles = 0; - currentsourcefile = 0; - return; - } - - if (currentsourcefile) - printf("-------------------------------------\n"); - - strcpy(qccmprogsdat, sourcefileslist[currentsourcefile++]); - - printf ("Source file: %s\n", qccmprogsdat); - - if (QCC_LoadFile (qccmprogsdat, (void *)&qccmsrc) == -1) - { - return; - } - } - -#ifdef WRITEASM - if (writeasm) - { - asmfile = fopen("qc.asm", "wb"); - if (!asmfile) - QCC_Error (ERR_INTERNAL, "Couldn't open file for asm output."); - } -#endif - - newstylesource = false; - while(*qccmsrc && *qccmsrc < ' ') - qccmsrc++; - pr_file_p = QCC_COM_Parse(qccmsrc); - - if (QCC_CheckParm ("-qc")) - { - strcpy(destfile, qccmprogsdat); - StripExtension(destfile); - strcat(destfile, ".qco"); - - p = QCC_CheckParm ("-o"); - if (!p || p >= argc-1 || argv[p+1][0] == '-') - if (p && p < argc-1 ) - sprintf (destfile, "%s%s", qccmsourcedir, argv[p+1]); - goto newstyle; - } - - if (*qcc_token == '#') - { - void StartNewStyleCompile(void); -newstyle: - newstylesource = true; - StartNewStyleCompile(); - return; - } - - pr_file_p = qccmsrc; - QCC_PR_LexWhitespace(); - qccmsrc = pr_file_p; - - s = qccmsrc; - pr_file_p = qccmsrc; - QCC_PR_SimpleGetToken (); - strcpy(qcc_token, pr_token); - qccmsrc = pr_file_p; - - if (!qccmsrc) - QCC_Error (ERR_NOOUTPUT, "No destination filename. qcc -help for info."); - strcpy (destfile, qcc_token); - -#ifndef QCCONLY - p=0; - s2 = strcpy(destfile2, destfile); - if (!strncmp(s2, "./", 2)) - s2+=2; - else - { - while(!strncmp(s2, "../", 3)) - { - s2+=3; - p++; - } - } - strcpy(qccmfilename, qccmsourcedir); - for (s=qccmfilename+strlen(qccmfilename);p && s>=qccmfilename; s--) - { - if (*s == '/' || *s == '\\') - { - *(s+1) = '\0'; - p--; - } - } - sprintf(destfile, "%s", s2); - - while (p>0) - { - memmove(destfile+3, destfile, strlen(destfile)+1); - destfile[0] = '.'; - destfile[1] = '.'; - destfile[2] = '/'; - p--; - } -#endif - - printf ("outputfile: %s\n", destfile); - - pr_dumpasm = false; - - currentchunk = NULL; - - originalqccmsrc = qccmsrc; -} - -void new_QCC_ContinueCompile(void); -//called between exe frames - won't loose net connection (is the theory)... -void QCC_ContinueCompile(void) -{ - char *s, *s2; - currentchunk = NULL; - if (!qcc_compileactive) - //HEY! - return; - - if (newstylesource) - { - new_QCC_ContinueCompile(); - return; - } - - qccmsrc = QCC_COM_Parse(qccmsrc); - if (!qccmsrc) - { - if (autoprototype) - { - qccmsrc = originalqccmsrc; - QCC_SetDefaultProperties(); - autoprototype = false; - return; - } - QCC_FinishCompile(); - - PostCompile(); - if (!PreCompile()) - return; - QCC_main(myargc, myargv); - return; - } - s = qcc_token; - - strcpy (qccmfilename, qccmsourcedir); - while(1) - { - if (!strncmp(s, "..\\", 3)) - { - s2 = qccmfilename + strlen(qccmfilename)-2; - while (s2>=qccmfilename) - { - if (*s2 == '/' || *s2 == '\\') - { - s2[1] = '\0'; - break; - } - s2--; - } - s+=3; - continue; - } - if (!strncmp(s, ".\\", 2)) - { - s+=2; - continue; - } - - break; - } - strcat (qccmfilename, s); - if (autoprototype) - printf ("prototyping %s\n", qccmfilename); - else - { - printf ("compiling %s\n", qccmfilename); - } - QCC_LoadFile (qccmfilename, (void *)&qccmsrc2); - - if (!QCC_PR_CompileFile (qccmsrc2, qccmfilename) ) - QCC_Error (ERR_PARSEERRORS, "Errors have occured\n"); -} -void QCC_FinishCompile(void) -{ - pbool donesomething; - int crc; -// int p; - currentchunk = NULL; - - if (setjmp(pr_parse_abort)) - QCC_Error(ERR_INTERNAL, ""); - - if (!QCC_PR_FinishCompilation ()) - { - QCC_Error (ERR_PARSEERRORS, "compilation errors"); - } - -/* p = QCC_CheckParm ("-asm"); - if (p) - { - for (p++ ; p MAX_ERRORS) - return; - if (setjmp(pr_parse_abort)) - return; - - QCC_PR_SkipToSemicolon (); - if (pr_token_type == tt_eof) - return; - } - - - QCC_PR_ClearGrabMacros (); // clear the frame macros - - compilingfile = qccmprogsdat; - - pr_file_p = qccmsrc; - s_file = s_file2 = QCC_CopyString (compilingfile); - - pr_source_line = 0; - - QCC_PR_NewLine (false); - - QCC_PR_Lex (); // read first token -} -void new_QCC_ContinueCompile(void) -{ - if (setjmp(pr_parse_abort)) - { -// if (pr_error_count != 0) - { - QCC_Error (ERR_PARSEERRORS, "Errors have occured"); - return; - } - QCC_PR_SkipToSemicolon (); - if (pr_token_type == tt_eof) - return; - } - - if (pr_token_type == tt_eof) - { - if (pr_error_count) - QCC_Error (ERR_PARSEERRORS, "Errors have occured"); - QCC_FinishCompile(); - - PostCompile(); - if (!PreCompile()) - return; - QCC_main(myargc, myargv); - return; - } - - pr_scope = NULL; // outside all functions - - QCC_PR_ParseDefs (NULL); -} - -/*void new_QCC_ContinueCompile(void) -{ - char *s, *s2; - if (!qcc_compileactive) - //HEY! - return; - -// compile all the files - - qccmsrc = QCC_COM_Parse(qccmsrc); - if (!qccmsrc) - { - QCC_FinishCompile(); - return; - } - s = qcc_token; - - strcpy (qccmfilename, qccmsourcedir); - while(1) - { - if (!strncmp(s, "..\\", 3)) - { - s2 = qccmfilename + strlen(qccmfilename)-2; - while (s2>=qccmfilename) - { - if (*s2 == '/' || *s2 == '\\') - { - s2[1] = '\0'; - break; - } - s2--; - } - s+=3; - continue; - } - if (!strncmp(s, ".\\", 2)) - { - s+=2; - continue; - } - - break; - } -// strcat (qccmfilename, s); -// printf ("compiling %s\n", qccmfilename); -// QCC_LoadFile (qccmfilename, (void *)&qccmsrc2); - -// if (!new_QCC_PR_CompileFile (qccmsrc2, qccmfilename) ) -// QCC_Error ("Errors have occured\n"); - - - { - - if (!pr.memory) - QCC_Error ("PR_CompileFile: Didn't clear"); - - QCC_PR_ClearGrabMacros (); // clear the frame macros - - compilingfile = filename; - - pr_file_p = qccmsrc2; - s_file = QCC_CopyString (filename); - - pr_source_line = 0; - - QCC_PR_NewLine (); - - QCC_PR_Lex (); // read first token - - while (pr_token_type != tt_eof) - { - if (setjmp(pr_parse_abort)) - { - if (++pr_error_count > MAX_ERRORS) - return false; - QCC_PR_SkipToSemicolon (); - if (pr_token_type == tt_eof) - return false; - } - - pr_scope = NULL; // outside all functions - - QCC_PR_ParseDefs (); - } - } - return (pr_error_count == 0); - -}*/ - - -#endif diff --git a/misc/mediasource/extra/fteqcc-src/qcctui.c b/misc/mediasource/extra/fteqcc-src/qcctui.c deleted file mode 100644 index 7f33e913..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcctui.c +++ /dev/null @@ -1,117 +0,0 @@ -#include "qcc.h" - -#include -#include - -/* -============== -LoadFile -============== -*/ -unsigned char *QCC_ReadFile (char *fname, void *buffer, int len) -{ - long length; - FILE *f; - f = fopen(fname, "rb"); - if (!f) - return NULL; - length = fread(buffer, 1, len, f); - fclose(f); - - if (length != len) - return NULL; - - return buffer; -} -int QCC_FileSize (char *fname) -{ - long length; - FILE *f; - f = fopen(fname, "rb"); - if (!f) - return -1; - fseek(f, 0, SEEK_END); - length = ftell(f); - fclose(f); - - return length; -} - -pbool QCC_WriteFile (char *name, void *data, int len) -{ - long length; - FILE *f; - f = fopen(name, "wb"); - if (!f) - return false; - length = fwrite(data, 1, len, f); - fclose(f); - - if (length != len) - return false; - - return true; -} - -#undef printf -#undef Sys_Error - -void Sys_Error(const char *text, ...) -{ - va_list argptr; - static char msg[2048]; - - va_start (argptr,text); - QC_vsnprintf (msg,sizeof(msg)-1, text,argptr); - va_end (argptr); - - QCC_Error(ERR_INTERNAL, "%s", msg); -} - - -FILE *logfile; -int logprintf(const char *format, ...) -{ - va_list argptr; - static char string[1024]; - - va_start (argptr, format); -#ifdef _WIN32 - _vsnprintf (string,sizeof(string)-1, format,argptr); -#else - vsnprintf (string,sizeof(string), format,argptr); -#endif - va_end (argptr); - - printf("%s", string); - if (logfile) - fputs(string, logfile); - - return 0; -} - -int main (int argc, char **argv) -{ - int sucess; - progexterns_t ext; - progfuncs_t funcs; - progfuncs = &funcs; - memset(&funcs, 0, sizeof(funcs)); - funcs.parms = &ext; - memset(&ext, 0, sizeof(progexterns_t)); - funcs.parms->ReadFile = QCC_ReadFile; - funcs.parms->FileSize = QCC_FileSize; - funcs.parms->WriteFile = QCC_WriteFile; - funcs.parms->printf = logprintf; - funcs.parms->Sys_Error = Sys_Error; - logfile = fopen("fteqcc.log", "wt"); - sucess = CompileParams(&funcs, true, argc, argv); - qccClearHunk(); - if (logfile) - fclose(logfile); - -#ifdef _WIN32 -// fgetc(stdin); //wait for keypress -#endif - return !sucess; -} diff --git a/misc/mediasource/extra/fteqcc-src/qcd.h b/misc/mediasource/extra/fteqcc-src/qcd.h deleted file mode 100644 index fd7817eb..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcd.h +++ /dev/null @@ -1,7 +0,0 @@ -pbool QC_decodeMethodSupported(int method); -char *QC_decode(progfuncs_t *progfuncs, int complen, int len, int method, char *info, char *buffer); -int QC_encode(progfuncs_t *progfuncs, int len, int method, char *in, int handle); - -char *filefromprogs(progfuncs_t *progfuncs, progsnum_t prnum, char *fname, int *size, char *buffer); -char *filefromnewprogs(progfuncs_t *progfuncs, char *prname, char *fname, int *size, char *buffer);//fixme - remove parm 1 - diff --git a/misc/mediasource/extra/fteqcc-src/qcd_main.c b/misc/mediasource/extra/fteqcc-src/qcd_main.c deleted file mode 100644 index f98e5336..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcd_main.c +++ /dev/null @@ -1,228 +0,0 @@ -#include "progsint.h" -//#include "qcc.h" - -//#define AVAIL_ZLIB - -#ifdef AVAIL_ZLIB -#ifdef _WIN32 -#define ZEXPORT VARGS -#include "../libs/zlib.h" - -# pragma comment (lib, "../libs/zlib.lib") -#else -#include -#endif -#endif - -pbool QC_decodeMethodSupported(int method) -{ - if (method == 0) - return true; - if (method == 1) - return true; - if (method == 2) - { -#ifdef AVAIL_ZLIB - return false; -#endif - } - return false; -} - -char *QC_decode(progfuncs_t *progfuncs, int complen, int len, int method, char *info, char *buffer) -{ - int i; - if (method == 0) //copy - { - if (complen != len) Sys_Error("lengths do not match"); - memcpy(buffer, info, len); - } - else if (method == 1) //xor encryption - { - if (complen != len) Sys_Error("lengths do not match"); - for (i = 0; i < len; i++) - buffer[i] = info[i] ^ 0xA5; - } - else if (method == 2) //compression (ZLIB) - { -#ifdef AVAIL_ZLIB - z_stream strm = { - info, - complen, - 0, - - buffer, - len, - 0, - - NULL, - NULL, - - NULL, - NULL, - NULL, - - Z_BINARY, - 0, - 0 - }; - - inflateInit(&strm); - if (Z_STREAM_END != inflate(&strm, Z_FINISH)) //decompress it in one go. - Sys_Error("Failed block decompression\n"); - inflateEnd(&strm); -#endif - } - //add your decryption/decompression routine here. - else - Sys_Error("Bad file encryption routine\n"); - - - return buffer; -} - -#ifndef MINIMAL -void SafeWrite(int hand, void *buf, long count); -int SafeSeek(int hand, int ofs, int mode); -//we are allowed to trash our input here. -int QC_encode(progfuncs_t *progfuncs, int len, int method, char *in, int handle) -{ - int i; - if (method == 0) //copy - { - SafeWrite(handle, in, len); - return len; - } - else if (method == 1) //xor encryption - { - for (i = 0; i < len; i++) - in[i] = in[i] ^ 0xA5; - SafeWrite(handle, in, len); - return len; - } - else if (method == 2) //compression (ZLIB) - { -#ifdef AVAIL_ZLIB - char out[8192]; - - z_stream strm = { - in, - len, - 0, - - out, - sizeof(out), - 0, - - NULL, - NULL, - - NULL, - NULL, - NULL, - - Z_BINARY, - 0, - 0 - }; - i=0; - - deflateInit(&strm, Z_BEST_COMPRESSION); - while(deflate(&strm, Z_FINISH) == Z_OK) - { - SafeWrite(handle, out, sizeof(out) - strm.avail_out); //compress in chunks of 8192. Saves having to allocate a huge-mega-big buffer - i+=sizeof(out) - strm.avail_out; - strm.next_out = out; - strm.avail_out = sizeof(out); - } - SafeWrite(handle, out, sizeof(out) - strm.avail_out); - i+=sizeof(out) - strm.avail_out; - deflateEnd(&strm); - return i; -#endif - Sys_Error("ZLIB compression not supported in this build"); - return 0; - } - //add your compression/decryption routine here. - else - { - Sys_Error("Wierd method"); - return 0; - } -} -#endif - -char *filefromprogs(progfuncs_t *progfuncs, progsnum_t prnum, char *fname, int *size, char *buffer) -{ - int num; - includeddatafile_t *s; - if (!pr_progstate[prnum].progs) - return NULL; - if (pr_progstate[prnum].progs->version != PROG_EXTENDEDVERSION) - return NULL; - if (!pr_progstate[prnum].progs->secondaryversion != PROG_SECONDARYVERSION16 && - !pr_progstate[prnum].progs->secondaryversion != PROG_SECONDARYVERSION32) - return NULL; - - num = *(int*)((char *)pr_progstate[prnum].progs + pr_progstate[prnum].progs->ofsfiles); - s = (includeddatafile_t *)((char *)pr_progstate[prnum].progs + pr_progstate[prnum].progs->ofsfiles+4); - while(num>0) - { - if (!strcmp(s->filename, fname)) - { - if (size) - *size = s->size; - if (!buffer) - return (char *)0xffffffff; - return QC_decode(progfuncs, s->compsize, s->size, s->compmethod, (char *)pr_progstate[prnum].progs+s->ofs, buffer); - } - - s++; - num--; - } - - if (size) - *size = 0; - return NULL; -} - -/* -char *filefromnewprogs(progfuncs_t *progfuncs, char *prname, char *fname, int *size, char *buffer) -{ - int num; - includeddatafile_t *s; - progstate_t progs; - if (!PR_ReallyLoadProgs(progfuncs, prname, -1, &progs, false)) - { - if (size) - *size = 0; - return NULL; - } - - if (progs.progs->version < PROG_EXTENDEDVERSION) - return NULL; - if (!progs.progs->ofsfiles) - return NULL; - - num = *(int*)((char *)progs.progs + progs.progs->ofsfiles); - s = (includeddatafile_t *)((char *)progs.progs + progs.progs->ofsfiles+4); - while(num>0) - { - if (!strcmp(s->filename, fname)) - { - if (size) - *size = s->size; - if (!buffer) - return (char *)0xffffffff; - return QC_decode(progfuncs, s->compsize, s->size, s->compmethod, (char *)progs.progs+s->ofs, buffer); - } - - s++; - num--; - } - - if (size) - *size = 0; - return NULL; -} -*/ diff --git a/misc/mediasource/extra/fteqcc-src/qcdecomp.c b/misc/mediasource/extra/fteqcc-src/qcdecomp.c deleted file mode 100644 index d1fcabf5..00000000 --- a/misc/mediasource/extra/fteqcc-src/qcdecomp.c +++ /dev/null @@ -1,986 +0,0 @@ -#ifndef MINIMAL - -#include "progsint.h" -#include "setjmp.h" - -#define MAX_PARMS 8 - -typedef struct QCC_type_s -{ - etype_t type; - - struct QCC_type_s *next; -// function types are more complex - struct QCC_type_s *aux_type; // return type or field type - int num_parms; // -1 = variable args -// struct QCC_type_s *parm_types[MAX_PARMS]; // only [num_parms] allocated - - int ofs; //inside a structure. - int size; - char *name; - -} QCC_type_t; - - -extern QCC_type_t *qcc_typeinfo; -extern int numtypeinfos; -extern int maxtypeinfos; -extern QCC_type_t *type_void;// = {ev_void/*, &def_void*/}; -extern QCC_type_t *type_string;// = {ev_string/*, &def_string*/}; -extern QCC_type_t *type_float;// = {ev_float/*, &def_float*/}; -extern QCC_type_t *type_vector;// = {ev_vector/*, &def_vector*/}; -extern QCC_type_t *type_entity;// = {ev_entity/*, &def_entity*/}; -extern QCC_type_t *type_field;// = {ev_field/*, &def_field*/}; -extern QCC_type_t *type_function;// = {ev_function/*, &def_function*/,NULL,&type_void}; -// type_function is a void() function used for state defs -extern QCC_type_t *type_pointer;// = {ev_pointer/*, &def_pointer*/}; -extern QCC_type_t *type_integer;// = {ev_integer/*, &def_integer*/}; - -extern QCC_type_t *type_floatfield;// = {ev_field/*, &def_field*/, NULL, &type_float}; -QCC_type_t *QCC_PR_NewType (char *name, int basictype); - - -jmp_buf decompilestatementfailure; - -#if 0 -pbool Decompile(progfuncs_t *progfuncs, char *fname) -{ - return false; -} -#else - -QCC_type_t **ofstype; -qbyte *ofsflags; - -int SafeOpenWrite (char *filename, int maxsize); -void SafeWrite(int hand, void *buf, long count); -int SafeSeek(int hand, int ofs, int mode); -void SafeClose(int hand); -void VARGS writes(int hand, char *msg, ...) -{ - va_list va; - char buf[4192]; - - va_start(va, msg); - Q_vsnprintf (buf,sizeof(buf)-1, msg, va); - va_end(va); - - SafeWrite(hand, buf, strlen(buf)); -}; - -char *PR_UglyValueString (etype_t type, eval_t *val); -ddef16_t *ED_GlobalAtOfs16 (progfuncs_t *progfuncs, int ofs); -char *VarAtOfs(progfuncs_t *progfuncs, int ofs) -{ - static char buf [4192]; - ddef16_t *def; - int typen; - - if (ofsflags[ofs]&8) - def = ED_GlobalAtOfs16(progfuncs, ofs); - else - def = NULL; - if (!def) - { - if (ofsflags[ofs]&3) - { - if (ofstype[ofs]) - sprintf(buf, "_v_%s_%i", ofstype[ofs]->name, ofs); - else - sprintf(buf, "_v_%i", ofs); - } - else - { - if (ofstype[ofs]) - { - typen = ofstype[ofs]->type; - goto evaluateimmediate; - } - else - sprintf(buf, "_c_%i", ofs); - } - return buf; - } - if (!def->s_name[progfuncs->stringtable] || !strcmp(progfuncs->stringtable+def->s_name, "IMMEDIATE")) - { - if (current_progstate->types) - typen = current_progstate->types[def->type & ~DEF_SHARED].type; - else - typen = def->type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - -evaluateimmediate: -// return PR_UglyValueString(def->type, (eval_t *)¤t_progstate->globals[def->ofs]); - switch(typen) - { - case ev_float: - sprintf(buf, "%f", G_FLOAT(ofs)); - return buf; - case ev_vector: - sprintf(buf, "\'%f %f %f\'", G_FLOAT(ofs), G_FLOAT(ofs+1), G_FLOAT(ofs+2)); - return buf; - case ev_string: - { - char *s, *s2; - s = buf; - *s++ = '\"'; - s2 = pr_strings+G_INT(ofs); - - - if (s2) - while(*s2) - { - if (*s2 == '\n') - { - *s++ = '\\'; - *s++ = 'n'; - s2++; - } - else if (*s2 == '\"') - { - *s++ = '\\'; - *s++ = '\"'; - s2++; - } - else if (*s2 == '\t') - { - *s++ = '\\'; - *s++ = 't'; - s2++; - } - else - *s++=*s2++; - } - *s++ = '\"'; - *s++ = '\0'; - } - return buf; - case ev_pointer: - sprintf(buf, "_c_pointer_%i", ofs); - return buf; - default: - sprintf(buf, "_c_%i", ofs); - return buf; - } - } - return def->s_name+progfuncs->stringtable; -} - - -int file; - -int ImmediateReadLater(progfuncs_t *progfuncs, progstate_t *progs, unsigned int ofs, int firstst) -{ - dstatement16_t *st; - if (ofsflags[ofs] & 8) - return false; //this is a global/local/pramater, not a temp - if (!(ofsflags[ofs] & 3)) - return false; //this is a constant. - for (st = &((dstatement16_t*)progs->statements)[firstst]; ; st++,firstst++) - { //if written, return false, if read, return true. - if (st->op >= OP_CALL0 && st->op <= OP_CALL8) - { - if (ofs == OFS_RETURN) - return false; - if (ofs < OFS_PARM0 + 3*((unsigned int)st->op - OP_CALL0)) - return true; - } - else if (pr_opcodes[st->op].associative == ASSOC_RIGHT) - { - if (ofs == st->b) - return false; - if (ofs == st->a) - return true; - } - else - { - if (st->a == ofs) - return true; - if (st->b == ofs) - return true; - if (st->c == ofs) - return false; - } - - if (st->op == OP_DONE || st->op == OP_RETURN) //we missed our chance. (return/done ends any code coherancy). - return false; - } - return false; -} -int ProductReadLater(progfuncs_t *progfuncs, progstate_t *progs, int stnum) -{ - dstatement16_t *st; - st = &((dstatement16_t*)progs->statements)[stnum]; - if (pr_opcodes[st->op].priority == -1) - { - if (st->op >= OP_CALL0 && st->op <= OP_CALL7) - return ImmediateReadLater(progfuncs, progs, OFS_RETURN, stnum+1); - return false;//these don't have products... - } - - if (pr_opcodes[st->op].associative == ASSOC_RIGHT) - return ImmediateReadLater(progfuncs, progs, st->b, stnum+1); - else - return ImmediateReadLater(progfuncs, progs, st->c, stnum+1); -} - -void WriteStatementProducingOfs(progfuncs_t *progfuncs, progstate_t *progs, int lastnum, int firstpossible, int ofs) //recursive, works backwards -{ - int i; - dstatement16_t *st; - ddef16_t *def; - if (ofs == 0) - longjmp(decompilestatementfailure, 1); - for (; lastnum >= firstpossible; lastnum--) - { - st = &((dstatement16_t*)progs->statements)[lastnum]; - if (st->op >= OP_CALL0 && st->op < OP_CALL7) - { - if (ofs != OFS_RETURN) - continue; - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, st->a); - writes(file, "("); - for (i = 0; i < st->op - OP_CALL0; i++) - { - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, OFS_PARM0 + i*3); - if (i != st->op - OP_CALL0-1) - writes(file, ", "); - } - writes(file, ")"); - return; - } - else if (pr_opcodes[st->op].associative == ASSOC_RIGHT) - { - if (st->b != ofs) - continue; - if (!ImmediateReadLater(progfuncs, progs, st->b, lastnum+1)) - { - writes(file, "("); - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, st->b); - writes(file, " "); - writes(file, pr_opcodes[st->op].name); - writes(file, " "); - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, st->a); - writes(file, ")"); - return; - } - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, st->a); - return; - } - else - { - if (st->c != ofs) - continue; - - if (!ImmediateReadLater(progfuncs, progs, st->c, lastnum+1)) - { - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, st->c); - writes(file, " = "); - } - writes(file, "("); - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, st->a); - - if (!strcmp(pr_opcodes[st->op].name, ".")) - writes(file, pr_opcodes[st->op].name); //extra spaces around .s are ugly. - else - { - writes(file, " "); - writes(file, pr_opcodes[st->op].name); - writes(file, " "); - } - WriteStatementProducingOfs(progfuncs, progs, lastnum-1, firstpossible, st->b); - writes(file, ")"); - return; - } - } - - def = ED_GlobalAtOfs16(progfuncs, ofs); - if (def) - { - if (!strcmp(def->s_name+progfuncs->stringtable, "IMMEDIATE")) - writes(file, "%s", VarAtOfs(progfuncs, ofs)); - else - writes(file, "%s", progfuncs->stringtable+def->s_name); - } - else - writes(file, "%s", VarAtOfs(progfuncs, ofs)); -// longjmp(decompilestatementfailure, 1); -} - -int WriteStatement(progfuncs_t *progfuncs, progstate_t *progs, int stnum, int firstpossible) -{ - int count, skip; - dstatement16_t *st; - st = &((dstatement16_t*)progs->statements)[stnum]; - switch(st->op) - { - case OP_IFNOT: - count = (signed short)st->b; - writes(file, "if ("); - WriteStatementProducingOfs(progfuncs, progs, stnum, firstpossible, st->a); - writes(file, ")\r\n"); - writes(file, "{\r\n"); - firstpossible = stnum+1; - count--; - stnum++; - while(count) - { - if (ProductReadLater(progfuncs, progs, stnum)) - { - count--; - stnum++; - continue; - } - skip = WriteStatement(progfuncs, progs, stnum, firstpossible); - count-=skip; - stnum+=skip; - } - writes(file, "}\r\n"); - st = &((dstatement16_t*)progs->statements)[stnum]; - if (st->op == OP_GOTO) - { - count = (signed short)st->b; - count--; - stnum++; - - writes(file, "else\r\n"); - writes(file, "{\r\n"); - while(count) - { - if (ProductReadLater(progfuncs, progs, stnum)) - { - count--; - stnum++; - continue; - } - skip = WriteStatement(progfuncs, progs, stnum, firstpossible); - count-=skip; - stnum+=skip; - } - writes(file, "}\r\n"); - } - break; - case OP_IF: - longjmp(decompilestatementfailure, 1); - break; - case OP_GOTO: - longjmp(decompilestatementfailure, 1); - break; - case OP_RETURN: - case OP_DONE: - if (st->a) - WriteStatementProducingOfs(progfuncs, progs, stnum-1, firstpossible, st->a); - break; - case OP_CALL0: - case OP_CALL1: - case OP_CALL2: - case OP_CALL3: - case OP_CALL4: - case OP_CALL5: - case OP_CALL6: - case OP_CALL7: - WriteStatementProducingOfs(progfuncs, progs, stnum, firstpossible, OFS_RETURN); - writes(file, ";\r\n"); - break; - default: - if (pr_opcodes[st->op].associative == ASSOC_RIGHT) - WriteStatementProducingOfs(progfuncs, progs, stnum, firstpossible, st->b); - else - WriteStatementProducingOfs(progfuncs, progs, stnum, firstpossible, st->c); - writes(file, ";\r\n"); - break; - } - - return 1; -} - -void WriteAsmStatements(progfuncs_t *progfuncs, progstate_t *progs, int num, int f, char *functionname) -{ - int stn = progs->functions[num].first_statement; - QCC_opcode_t *op; - dstatement16_t *st = NULL; - eval_t *v; - - ddef16_t *def; - int ofs,i; - - int fileofs; - - if (!functionname && stn<0) - { - //we wrote this one... - return; - } - - if (stn>=0) - { - for (stn = progs->functions[num].first_statement; stn < (signed int)pr_progs->numstatements; stn++) - { - st = &((dstatement16_t*)progs->statements)[stn]; - if (st->op == OP_DONE || st->op == OP_RETURN) - { - if (!st->a) - writes(f, "void("); - else if (ofstype[st->a]) - { - writes(f, "%s", ofstype[st->a]->name); - writes(f, "("); - } - else - writes(f, "function("); - break; - } - } - st=NULL; - stn = progs->functions[num].first_statement; - } - else - writes(f, "function("); - for (ofs = progs->functions[num].parm_start, i = 0; i < progs->functions[num].numparms; i++, ofs+=progs->functions[num].parm_size[i]) - { - ofsflags[ofs] |= 4; - - def = ED_GlobalAtOfs16(progfuncs, ofs); - if (def && stn>=0) - { - if (st) - writes(f, ", "); - st = (void *)0xffff; - - if (!def->s_name[progfuncs->stringtable]) - { - char mem[64]; - sprintf(mem, "_p_%i", def->ofs); - def->s_name = (char*)malloc(strlen(mem)+1)-progfuncs->stringtable; - strcpy(def->s_name+progfuncs->stringtable, mem); - } - - if (current_progstate->types) - writes(f, "%s %s", current_progstate->types[def->type&~(DEF_SHARED|DEF_SAVEGLOBAL)].name, def->s_name); - else - switch(def->type&~(DEF_SHARED|DEF_SAVEGLOBAL)) - { - case ev_string: - writes(f, "%s %s", "string", progfuncs->stringtable+def->s_name); - break; - case ev_float: - writes(f, "%s %s", "float", progfuncs->stringtable+def->s_name); - break; - case ev_entity: - writes(f, "%s %s", "entity", progfuncs->stringtable+def->s_name); - break; - case ev_vector: - writes(f, "%s %s", "vector", progfuncs->stringtable+def->s_name); - break; - default: - writes(f, "%s %s", "randomtype", progfuncs->stringtable+def->s_name); - break; - } - } - } - for (ofs = progs->functions[num].parm_start+progs->functions[num].numparms, i = progs->functions[num].numparms; i < progs->functions[num].locals; i++, ofs+=1) - ofsflags[ofs] |= 4; - - if (!progfuncs->stringtable[progs->functions[num].s_name]) - { - char mem[64]; - if (!functionname) - { - sprintf(mem, "_bi_%i", num); - progs->functions[num].s_name = (char*)malloc(strlen(mem)+1)-progfuncs->stringtable; - strcpy(progs->functions[num].s_name+progfuncs->stringtable, mem); - } - else - { - progs->functions[num].s_name = (char*)malloc(strlen(functionname)+1)-progfuncs->stringtable; - strcpy(progs->functions[num].s_name+progfuncs->stringtable, functionname); - } - } - - writes(f, ") %s", progfuncs->stringtable+progs->functions[num].s_name); - - if (stn < 0) - { - stn*=-1; - writes(f, " = #%i;\r\n", stn); -/* - for (ofs = progs->functions[num].parm_start, i = 0; i < progs->functions[num].numparms; i++, ofs+=progs->functions[num].parm_size[i]) - { - def = ED_GlobalAtOfs16(progfuncs, ofs); - if (def) - { - def->ofs = 0xffff; - - if (progs->types) - { - if (progs->types[def->type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type == ev_vector) - { - def = ED_GlobalAtOfs16(progfuncs, ofs); - def->ofs = 0xffff; - def = ED_GlobalAtOfs16(progfuncs, ofs+1); - def->ofs = 0xffff; - def = ED_GlobalAtOfs16(progfuncs, ofs+2); - def->ofs = 0xffff; - } - } - else if ((def->type & (~(DEF_SHARED|DEF_SAVEGLOBAL))) == ev_vector) - { - def = ED_GlobalAtOfs16(progfuncs, ofs); - def->ofs = 0xffff; - def = ED_GlobalAtOfs16(progfuncs, ofs+1); - def->ofs = 0xffff; - def = ED_GlobalAtOfs16(progfuncs, ofs+2); - def->ofs = 0xffff; - } - } - } - */ - return; - } - - if (functionname) //parsing defs - { - writes(f, ";\r\n"); - return; - } - - fileofs = SafeSeek(f, 0, SEEK_CUR); - if (setjmp(decompilestatementfailure)) - { - writes(f, "*/\r\n"); - // SafeSeek(f, fileofs, SEEK_SET); - writes(f, " = asm {\r\n"); - - stn = progs->functions[num].first_statement; - for (ofs = progs->functions[num].parm_start+progs->functions[num].numparms, i = progs->functions[num].numparms; i < progs->functions[num].locals; i++, ofs+=1) - { - def = ED_GlobalAtOfs16(progfuncs, ofs); - if (def) - { - v = (eval_t *)&((int *)progs->globals)[def->ofs]; - if (current_progstate->types) - writes(f, "\tlocal %s %s;\r\n", current_progstate->types[def->type&~(DEF_SHARED|DEF_SAVEGLOBAL)].name, def->s_name); - else - { - if (!progfuncs->stringtable[def->s_name]) - { - char mem[64]; - sprintf(mem, "_l_%i", def->ofs); - def->s_name = (char*)malloc(strlen(mem)+1)-progfuncs->stringtable; - strcpy(def->s_name+progfuncs->stringtable, mem); - } - - switch(def->type&~(DEF_SHARED|DEF_SAVEGLOBAL)) - { - case ev_string: - writes(f, "\tlocal %s %s;\r\n", "string", progfuncs->stringtable+def->s_name); - break; - case ev_float: - writes(f, "\tlocal %s %s;\r\n", "float", progfuncs->stringtable+def->s_name); - break; - case ev_entity: - writes(f, "\tlocal %s %s;\r\n", "entity", progfuncs->stringtable+def->s_name); - break; - case ev_vector: - if (v->_vector[0] || v->_vector[1] || v->_vector[2]) - writes(f, "\tlocal vector %s = '%f %f %f';\r\n", progfuncs->stringtable+def->s_name, v->_vector[0], v->_vector[1], v->_vector[2]); - else - writes(f, "\tlocal %s %s;\r\n", "vector", progfuncs->stringtable+def->s_name); - ofs+=2; //skip floats; - break; - default: - writes(f, "\tlocal %s %s;\r\n", "randomtype", progfuncs->stringtable+def->s_name); - break; - } - } - } - } - - while(1) - { - st = &((dstatement16_t*)progs->statements)[stn]; - if (!st->op) //end of function statement! - break; - op = &pr_opcodes[st->op]; - writes(f, "\t%s", op->opname); - - if (op->priority==-1&&op->associative==ASSOC_RIGHT) //last param is a goto - { - if (op->type_b == &type_void) - { - if (st->a) - writes(f, " %i", (signed short)st->a); - } - else if (op->type_c == &type_void) - { - if (st->a) - writes(f, " %s", VarAtOfs(progfuncs, st->a)); - if (st->b) - writes(f, " %i", (signed short)st->b); - } - else - { - if (st->a) - writes(f, " %s", VarAtOfs(progfuncs, st->a)); - if (st->b) - writes(f, " %s", VarAtOfs(progfuncs, st->b)); - if (st->c) //rightness means it uses a as c - writes(f, " %i", (signed short)st->c); - } - } - else - { - if (st->a) - { - if (op->type_a == NULL) - writes(f, " %i", (signed short)st->a); - else - writes(f, " %s", VarAtOfs(progfuncs, st->a)); - } - if (st->b) - { - if (op->type_b == NULL) - writes(f, " %i", (signed short)st->b); - else - writes(f, " %s", VarAtOfs(progfuncs, st->b)); - } - if (st->c && op->associative != ASSOC_RIGHT) //rightness means it uses a as c - { - if (op->type_c == NULL) - writes(f, " %i", (signed short)st->c); - else - writes(f, " %s", VarAtOfs(progfuncs, st->c)); - } - } - - writes(f, ";\r\n"); - - stn++; - } - } - else - { - if (!strcmp(progfuncs->stringtable+progs->functions[num].s_name, "SUB_Remove")) - file = 0; - file = f; - - writes(f, "/*\r\n"); - - writes(f, " =\r\n{\r\n"); - - for (ofs = progs->functions[num].parm_start+progs->functions[num].numparms, i = progs->functions[num].numparms; i < progs->functions[num].locals; i++, ofs+=1) - { - def = ED_GlobalAtOfs16(progfuncs, ofs); - if (def) - { - v = (eval_t *)&((int *)progs->globals)[def->ofs]; - if (current_progstate->types) - writes(f, "\tlocal %s %s;\r\n", current_progstate->types[def->type&~(DEF_SHARED|DEF_SAVEGLOBAL)].name, def->s_name); - else - { - if (!def->s_name[progfuncs->stringtable]) - { - char mem[64]; - sprintf(mem, "_l_%i", def->ofs); - def->s_name = (char*)malloc(strlen(mem)+1)-progfuncs->stringtable; - strcpy(def->s_name+progfuncs->stringtable, mem); - } - - switch(def->type&~(DEF_SHARED|DEF_SAVEGLOBAL)) - { - case ev_string: - writes(f, "\tlocal %s %s;\r\n", "string", progfuncs->stringtable+def->s_name); - break; - case ev_float: - writes(f, "\tlocal %s %s;\r\n", "float", progfuncs->stringtable+def->s_name); - break; - case ev_entity: - writes(f, "\tlocal %s %s;\r\n", "entity", progfuncs->stringtable+def->s_name); - break; - case ev_vector: - if (v->_vector[0] || v->_vector[1] || v->_vector[2]) - writes(f, "\tlocal vector %s = '%f %f %f';\r\n", def->s_name, v->_vector[0], v->_vector[1], v->_vector[2]); - else - writes(f, "\tlocal %s %s;\r\n", "vector",progfuncs->stringtable+def->s_name); - ofs+=2; //skip floats; - break; - default: - writes(f, "\tlocal %s %s;\r\n", "randomtype", progfuncs->stringtable+def->s_name); - break; - } - } - } - } - - - for (stn = progs->functions[num].first_statement; stn < (signed int)pr_progs->numstatements; stn++) - { - if (ProductReadLater(progfuncs, progs, stn)) - continue; - - st = &((dstatement16_t*)progs->statements)[stn]; - if (!st->op) - break; - WriteStatement(progfuncs, progs, stn, progs->functions[num].first_statement); - } - - longjmp(decompilestatementfailure, 1); - } - writes(f, "};\r\n"); -} - -void FigureOutTypes(progfuncs_t *progfuncs) -{ - ddef16_t *def; - QCC_opcode_t *op; - unsigned int i,p; - dstatement16_t *st; - - int parmofs[8]; - - ofstype = realloc(ofstype, sizeof(*ofstype)*65535); - ofsflags = realloc(ofsflags, sizeof(*ofsflags)*65535); - - maxtypeinfos=256; - qcc_typeinfo = (void *)realloc(qcc_typeinfo, sizeof(QCC_type_t)*maxtypeinfos); - numtypeinfos = 0; - - memset(ofstype, 0, sizeof(*ofstype)*65535); - memset(ofsflags, 0, sizeof(*ofsflags)*65535); - - type_void = QCC_PR_NewType("void", ev_void); - type_string = QCC_PR_NewType("string", ev_string); - type_float = QCC_PR_NewType("float", ev_float); - type_vector = QCC_PR_NewType("vector", ev_vector); - type_entity = QCC_PR_NewType("entity", ev_entity); - type_field = QCC_PR_NewType("field", ev_field); - type_function = QCC_PR_NewType("function", ev_function); - type_pointer = QCC_PR_NewType("pointer", ev_pointer); - type_integer = QCC_PR_NewType("integer", ev_integer); - -// type_variant = QCC_PR_NewType("__variant", ev_variant); - - type_floatfield = QCC_PR_NewType("fieldfloat", ev_field); - type_floatfield->aux_type = type_float; - type_pointer->aux_type = QCC_PR_NewType("pointeraux", ev_float); - - type_function->aux_type = type_void; - - for (i = 0,st = pr_statements16; i < pr_progs->numstatements; i++,st++) - { - op = &pr_opcodes[st->op]; - if (st->op >= OP_CALL1 && st->op <= OP_CALL8) - { - for (p = 0; p < (unsigned int)st->op-OP_CALL0; p++) - { - ofstype[parmofs[p]] = ofstype[OFS_PARM0+p*3]; - } - } - else if (op->associative == ASSOC_RIGHT) - { //assignment - ofsflags[st->b] |= 1; - if (st->b >= OFS_PARM0 && st->b < RESERVED_OFS) - parmofs[(st->b-OFS_PARM0)/3] = st->a; - -// if (st->op != OP_STORE_F || st->b>RESERVED_OFS) //optimising compilers fix the OP_STORE_V, it's the storef that becomes meaningless (this is the only time that we need this sort of info anyway) - { - if (op->type_c && op->type_c != &type_void) - ofstype[st->a] = *op->type_c; - if (op->type_b && op->type_b != &type_void) - ofstype[st->b] = *op->type_b; - } - } - else if (op->type_c) - { - ofsflags[st->c] |= 2; - - if (st->c >= OFS_PARM0 && st->b < RESERVED_OFS) //too complicated - parmofs[(st->b-OFS_PARM0)/3] = 0; - -// if (st->op != OP_STORE_F || st->b>RESERVED_OFS) //optimising compilers fix the OP_STORE_V, it's the storef that becomes meaningless (this is the only time that we need this sort of info anyway) - { - if (op->type_a && op->type_a != &type_void) - ofstype[st->a] = *op->type_a; - if (op->type_b && op->type_b != &type_void) - ofstype[st->b] = *op->type_b; - if (op->type_c && op->type_c != &type_void) - ofstype[st->c] = *op->type_c; - } - } - } - - - for (i=0 ; inumglobaldefs ; i++) - { - def = &pr_globaldefs16[i]; - ofsflags[def->ofs] |= 8; - switch(def->type) - { - case ev_float: - ofstype[def->ofs] = type_float; - break; - case ev_string: - ofstype[def->ofs] = type_string; - break; - case ev_vector: - ofstype[def->ofs] = type_vector; - break; - default: - break; - } - } -} - -pbool Decompile(progfuncs_t *progfuncs, char *fname) -{ - extern progfuncs_t *qccprogfuncs; - unsigned int i; - unsigned int fld=0; - eval_t *v; -// char *filename; - int f, type; - - progstate_t progs, *op; - - qccprogfuncs = progfuncs; - op=current_progstate; - - if (!PR_ReallyLoadProgs(progfuncs, fname, -1, &progs, false)) - { - return false; - } - - f=SafeOpenWrite("qcdtest/defs.qc", 1024*512); - - writes(f, "//Decompiled code can contain little type info.\r\n#define NOWARNINGS\r\n"); - - FigureOutTypes(progfuncs); - - for (i = 1; i < progs.progs->numglobaldefs; i++) - { - if (!strcmp(progfuncs->stringtable+pr_globaldefs16[i].s_name, "IMMEDIATE")) - continue; - - if (ofsflags[pr_globaldefs16[i].ofs] & 4) - continue; //this is a local. - - if (current_progstate->types) - type = progs.types[pr_globaldefs16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL)].type; - else - type = pr_globaldefs16[i].type & ~(DEF_SHARED|DEF_SAVEGLOBAL); - v = (eval_t *)&((int *)progs.globals)[pr_globaldefs16[i].ofs]; - - if (!progfuncs->stringtable[pr_globaldefs16[i].s_name]) - { - char mem[64]; - if (ofsflags[pr_globaldefs16[i].ofs] & 3) - { - ofsflags[pr_globaldefs16[i].ofs] &= ~8; - continue; //this is a constant... - } - - sprintf(mem, "_g_%i", pr_globaldefs16[i].ofs); - pr_globaldefs16[i].s_name = (char*)malloc(strlen(mem)+1)-progfuncs->stringtable; - strcpy(pr_globaldefs16[i].s_name+progfuncs->stringtable, mem); - } - - switch(type) - { - case ev_void: - writes(f, "void %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - case ev_string: - if (v->string && *(pr_strings+v->_int)) - writes(f, "string %s = \"%s\";\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name, pr_strings+v->_int); - else - writes(f, "string %s;\r\n", pr_globaldefs16[i].s_name); - break; - case ev_float: - if (v->_float) - writes(f, "float %s = %f;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name, v->_float); - else - writes(f, "float %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - case ev_vector: - if (v->_vector[0] || v->_vector[1] || v->_vector[2]) - writes(f, "vector %s = '%f %f %f';\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name, v->_vector[0], v->_vector[1], v->_vector[2]); - else - writes(f, "vector %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - i+=3;//skip the floats - break; - case ev_entity: - writes(f, "entity %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - case ev_field: -//wierd - fld++; - if (!v->_int) - writes(f, "var "); - switch(pr_fielddefs16[fld].type) - { - case ev_string: - writes(f, ".string %s;", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - - case ev_float: - writes(f, ".float %s;", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - - case ev_vector: - writes(f, ".float %s;", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - - case ev_entity: - writes(f, ".float %s;", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - - case ev_function: - writes(f, ".void() %s;", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - - default: - writes(f, "field %s;", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - } - if (v->_int) - writes(f, "/* %i */", v->_int); - writes(f, "\r\n"); - break; - - case ev_function: -//wierd - WriteAsmStatements(progfuncs, &progs, ((int *)progs.globals)[pr_globaldefs16[i].ofs], f, pr_globaldefs16[i].s_name+progfuncs->stringtable); - break; - - case ev_pointer: - writes(f, "pointer %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - case ev_integer: - writes(f, "integer %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - - case ev_union: - writes(f, "union %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - case ev_struct: - writes(f, "struct %s;\r\n", progfuncs->stringtable+pr_globaldefs16[i].s_name); - break; - default: - break; - - } - } - - for (i = 0; i < progs.progs->numfunctions; i++) - { - WriteAsmStatements(progfuncs, &progs, i, f, NULL); - } - - SafeClose(f); - - current_progstate=op; - - return true; -} -#endif - -#endif diff --git a/misc/mediasource/extra/fteqcc-src/readme.txt b/misc/mediasource/extra/fteqcc-src/readme.txt deleted file mode 100644 index a254729a..00000000 --- a/misc/mediasource/extra/fteqcc-src/readme.txt +++ /dev/null @@ -1,50 +0,0 @@ -Readme for the FTE QCLib - -This library is a library for running QuakeC gamecode. It does not provide any builtins itself. - -Features: - * Multiple library instances, enabling server qc, client qc, and menu qc. There is no maximum instance limit other than memory. - - * Addons, for running multiple progs in any individual instance. - - * Field reassignment, allowing a single engine to support multiple subtly different QC APIs. Also makes additional fields easier. - - * Step-by-step debugging. Requires a text editor of some form, however. A printout of the current line is also useful of course. - - * 64bit support. All strings, globals, and fields are allocated in a consecutive addressable section of memory. This also allows pointers and secure access (not implemented yet, but should be relativly easy bar builtins, which are your responsability). - - * Multiple 'threads'. The library allows a builtin to make a duplicate of the current execution state, or to wipe the current state. This allows sleep commands and fork commands. How handy. - - * Integrated QC compiler. FTEQCC comes as part of qclib. By setting up an interface with a specific value, you can cause it to always run, or run only if it detects a source change. - - * Support for different sorts of progs. Namly Hexen2's, kkqwsv's bigprogs, and FTE's extended format with extra opcodes and possibly fully 32bit offsets. The use of kkqwsv's progs is not recommended - this might be removed at some point. - - - - -Quirks: - * don't use multiple instances of fteqcc at the same time. Compilation will fail. - * 64bit support requires all strings to be allocated by qclib itself, achivable via a method call. Compatability requires a certain ammount of caution. - * a fair number of methods are obsolete. - * An overuse of pointers in the API. There are some macros which you can use to hide some of the dereferences. - * kkqwsv progs are not reliable. Do not try saving the game. Avoid letting your users know of support. - - * Builtin structures are different from original quake. You'll need to convert the arguments to qclib style. This change was required for both multiple instances as well as addon support. It should be straightforward enough. - * Entity fields are accessed via a pointer from the edict_t structure. This was required to place entity fields within the 64bit accessable section. Changing a . to a -> is not a major issue though. However, there are a lot. do a find and replace of ->v. to ->v-> - * FTE's entities are numbers not pointers. This fact is not made into a big feature as it's kinda incompatable with standard quake. Please do not use numbers directly to refer to ents but instead use the EDICT_TO_PROGS macro which will give protection. This is consistant with standard quake. - - -Basic usage: - * refer to test.c for a sample on how to set up the library. - * refer to progslib.h for the things that I've forgotten to mention. - * Call the InitProgs function to get a handle to the instance. It takes a parameter which should be set up with some fields. You'll require ReadFile, FileSize, Abort and printf for basic execution. - * Call the configure function to say how much memory to use, and how many progs/addons to support. - * Load your progs via LoadProgs. Use a crc of 0 to use any. Otherwise progs will be rejected if it doesn't match. Give it a list of progs-specific builtins too. :) - * Before calling the spawn builtin, call the InitEnts method. It's parameter stating how many maximum entities to spawn. Using a really large quantity is not much of an issue, as they are allocated as required. - * Before calling InitEnts, you can tell the VM which fields your engine uses (state all basic ones or none). This will place the entity fields in the same order as your engine expects for entvars_t. - * Obtain pointers to globals, or just use the globals structure directly. - * Call the ExecuteProgram method to start execution. - * Call the FindFunction method to find a function to run in the first place. - * Call the 'globals' method to retrieve a pointer to the globals (you should always use PR_CURRENT here). Set the parameters with the G_INT/G_FLOAT macros and friends. Use OFS_PARM0 - OFS_PARM7 to set params before calling or read inside a builtin. Use OFS_RETURN to read the return value. These macros are hard coded to use a 'pr_globals' symbol, so avoid renaming builtin parameter names. - * Ask me on IRC when it all starts keeling over. - * These are the C files that form qclib: pr_edict.c pr_exec.c pr_multi.c initlib.c qcc_pr_comp.c qcc_pr_lex.c qccmain.c qcc_cmdlib.c comprout.c hash.c qcd_main.c qcdecomp.c diff --git a/misc/mediasource/extra/fteqcc-src/test.c b/misc/mediasource/extra/fteqcc-src/test.c deleted file mode 100644 index 8875d2eb..00000000 --- a/misc/mediasource/extra/fteqcc-src/test.c +++ /dev/null @@ -1,221 +0,0 @@ -//This is basically a sample program. -//It deomnstrates the code required to get qclib up and running. -//This code does not demonstrate entities, however. -//It does demonstrate the built in qc compiler, and does demonstrate a globals-only progs interface. -//It also demonstrates basic builtin(s). - - - -#include "progtype.h" -#include "progslib.h" - -#include -#include -#include -#include - - - - -//builtins and builtin management. -void PF_prints (progfuncs_t *prinst, struct globalvars_s *gvars) -{ - char *s; - s = prinst->VarString(prinst, 0); - - printf("%s", s); -} - -void PF_printv (progfuncs_t *prinst, struct globalvars_s *pr_globals) -{ - printf("%f %f %f\n", G_FLOAT(OFS_PARM0+0), G_FLOAT(OFS_PARM0+1), G_FLOAT(OFS_PARM0+2)); -} - -void PF_printf (progfuncs_t *prinst, struct globalvars_s *pr_globals) -{ - printf("%f\n", G_FLOAT(OFS_PARM0)); -} - - -void PF_bad (progfuncs_t *prinst, struct globalvars_s *gvars) -{ - printf("bad builtin\n"); -} - -builtin_t builtins[] = { - PF_bad, - PF_prints, - PF_printv, - PF_printf -}; - - - - -//Called when the qc library has some sort of serious error. -void Sys_Abort(char *s, ...) -{ //quake handles this with a longjmp. - va_list ap; - va_start(ap, s); - vprintf(s, ap); - va_end(ap); - exit(1); -} -//Called when the library has something to say. -//Kinda required for the compiler... -//Not really that useful for the normal vm. -int Sys_Printf(char *s, ...) -{ //look up quake's va function to find out how to deal with variable arguments properly. - return printf("%s", s); -} - -#include -//copy file into buffer. note that the buffer will have been sized to fit the file (obtained via FileSize) -unsigned char *Sys_ReadFile (char *fname, void *buffer, int buflen) -{ - int len; - FILE *f; - if (!strncmp(fname, "src/", 4)) - fname+=4; //skip the src part - f = fopen(fname, "rb"); - if (!f) - return NULL; - fseek(f, 0, SEEK_END); - len = ftell(f); - if (buflen < len) - return NULL; - fseek(f, 0, SEEK_SET); - fread(buffer, 1, len, f); - fclose(f); - return buffer; -} -//Finds the size of a file. -int Sys_FileSize (char *fname) -{ - int len; - FILE *f; - if (!strncmp(fname, "src/", 4)) - fname+=4; //skip the src part - f = fopen(fname, "rb"); - if (!f) - return -1; - fseek(f, 0, SEEK_END); - len = ftell(f); - fclose(f); - return len; -} -//Writes a file. -pbool Sys_WriteFile (char *fname, void *data, int len) -{ - FILE *f; - f = fopen(fname, "wb"); - if (!f) - return 0; - fwrite(data, 1, len, f); - fclose(f); - return 1; -} - -void runtest(char *progsname) -{ - progfuncs_t *pf; - func_t func; - progsnum_t pn; - - progparms_t ext; - memset(&ext, 0, sizeof(ext)); - - ext.progsversion = PROGSTRUCT_VERSION; - ext.ReadFile = Sys_ReadFile; - ext.FileSize= Sys_FileSize; - ext.Abort = Sys_Abort; - ext.printf = printf; - - ext.numglobalbuiltins = sizeof(builtins)/sizeof(builtins[0]); - ext.globalbuiltins = builtins; - - pf = InitProgs(&ext); - pf->Configure(pf, 1024*1024, 1); //memory quantity of 1mb. Maximum progs loadable into the instance of 1 -//If you support multiple progs types, you should tell the VM the offsets here, via RegisterFieldVar - pn = pf->LoadProgs(pf, progsname, 0, NULL, 0); //load the progs, don't care about the crc, and use those builtins. - if (pn < 0) - printf("test: Failed to load progs \"%s\"\n", progsname); - else - { -//allocate qc-acessable strings here for 64bit cpus. (allocate via AddString, tempstringbase is a holding area not used by the actual vm) -//you can call functions before InitEnts if you want. it's not really advised for anything except naming additional progs. This sample only allows one max. - - pf->InitEnts(pf, 10); //Now we know how many fields required, we can say how many maximum ents we want to allow. 10 in this case. This can be huge without too many problems. - -//now it's safe to ED_Alloc. - - func = pf->FindFunction(pf, "main", PR_ANY); //find the function 'main' in the first progs that has it. - if (!func) - printf("Couldn't find function\n"); - else - pf->ExecuteProgram(pf, func); //call the function - } - CloseProgs(pf); -} - - -//Run a compiler and nothing else. -//Note that this could be done with an autocompile of PR_COMPILEALWAYS. -void compile(int argc, char **argv) -{ - progfuncs_t *pf; - - progparms_t ext; - - if (0) - { - char *testsrcfile = //newstyle progs.src must start with a #. - //it's newstyle to avoid using multiple source files. - "#pragma PROGS_DAT \"testprogs.dat\"\r\n" - "//INTERMEDIATE FILE - EDIT TEST.C INSTEAD\r\n" - "\r\n" - "void(...) print = #1;\r\n" - "void() main =\r\n" - "{\r\n" - " print(\"hello world\\n\");\r\n" - "};\r\n"; - - //so that the file exists. We could insert it via the callbacks instead - Sys_WriteFile("progs.src", testsrcfile, strlen(testsrcfile)); - } - - memset(&ext, 0, sizeof(ext)); - ext.progsversion = PROGSTRUCT_VERSION; - ext.ReadFile = Sys_ReadFile; - ext.FileSize= Sys_FileSize; - ext.WriteFile= Sys_WriteFile; - ext.Abort = Sys_Abort; - ext.printf = printf; - - pf = InitProgs(&ext); - if (pf->StartCompile) - { - if (pf->StartCompile(pf, argc, argv)) - { - while(pf->ContinueCompile(pf) == 1) - ; - } - } - else - printf("no compiler in this qcvm build\n"); - CloseProgs(pf); -} - -int main(int argc, char **argv) -{ - if (argc < 2) - { - printf("Invalid arguments!\nPlease run as, for example:\n%s testprogs.dat -srcfile progs.src\nThe first argument is the name of the progs.dat to run, the remaining arguments are the qcc args to use", argv[0]); - return 0; - } - - compile(argc-1, argv+1); - runtest(argv[1]); - - return 0; -} diff --git a/misc/mediasource/extra/netradiant-src/.gitattributes b/misc/mediasource/extra/netradiant-src/.gitattributes deleted file mode 100644 index ec3bfe3d..00000000 --- a/misc/mediasource/extra/netradiant-src/.gitattributes +++ /dev/null @@ -1,222 +0,0 @@ -* -crlf - -*.0 -diff -crlf -*.1 crlf=input -*.3 crlf=input -*.7z -diff -crlf -*.ac crlf=input -*.a -diff -crlf -*.afm crlf=input -*.aft crlf=input -*.ai -diff -crlf -*.aliases crlf=input -all crlf=input -*.am crlf=input -*.animinfo crlf=input -*.aps -diff -crlf -*.asc -diff -crlf -*.ase -crlf -*.bat -crlf -*.bgs crlf=input -*.blend1 -diff -crlf -*.blend -diff -crlf -blind_id -diff -crlf -*.bmp -diff -crlf -branch-manager crlf=input -*.brand crlf=input -BSDmakefile crlf=input -bsp2ent crlf=input -*.bsp -diff -crlf -*.cache -diff -crlf -*.cbp -crlf -*.cbp -diff -crlf -*.c crlf=input -*.cfg crlf=input -*.cg crlf=input -ChangeLog crlf=input -CHANGES crlf=input -cjpeg -diff -crlf -COMPILING crlf=input -compress-texture crlf=input -*.conf crlf=input -CONTRIBUTORS crlf=input -COPYING crlf=input -*.cpp crlf=input -create crlf=input -*.cron crlf=input -*.css crlf=input -*.cvswrappers crlf=input -*.d0pk -diff -crlf -*.db -diff -crlf -*.default crlf=input -*.def crlf=input -*.dem -diff -crlf -*.dev -crlf -dir -diff -crlf -djpeg -diff -crlf -*.dll -diff -crlf -DOCS -diff -crlf -*.dot crlf=input -DoxyConfig crlf=input -doxyfile crlf=input -Doxyfile crlf=input -*.doxygen crlf=input -*.dpm -diff -crlf -*.dsp -crlf -*.dsw -crlf -*.dtd crlf=input -*.dylib -diff -crlf -empty -diff -crlf -*.EncoderPlugin crlf=input -*.flac -diff -crlf -*.form crlf=input -*.framegroups crlf=input -*.game crlf=input -*.gdb crlf=input -gendox crlf=input -gendoxfunctions crlf=input -genDoxyfile crlf=input -*.gif -diff -crlf -*.gitattributes crlf=input -git-branch-manager crlf=input -git-filter-index crlf=input -git-filter-repository crlf=input -*.gitignore crlf=input -git-pk3-import crlf=input -git-pk3-merge crlf=input -git-pullall crlf=input -git-recurse crlf=input -git-split-repository crlf=input -git-svn-checkout crlf=input -git-svn-update crlf=input -git-update-octopus crlf=input -*.glp crlf=input -*.glsl crlf=input -GPL crlf=input -*.hardwired crlf=input -*.h crlf=input -*.hs crlf=input -*.html crlf=input -*.html-part crlf=input -*.icns -diff -crlf -*.ico -diff -crlf -*.idl crlf=input -*.idsoftware crlf=input -*.inc crlf=input -*.in crlf=input -*.info-1 -diff -crlf -*.info-2 -diff -crlf -*.info -diff -crlf -*.inl crlf=input -*.instantaction crlf=input -*.iqm -diff -crlf -*.java crlf=input -*.jhm crlf=input -*.jnlp crlf=input -jpegtran -diff -crlf -*.jpg -diff -crlf -*.jsmooth crlf=input -*.la crlf=input -LGPL crlf=input -LICENSE crlf=input -*.lmp -diff -crlf -*.loaders crlf=input -*.lso -diff -crlf -*.m4 crlf=input -makefile crlf=input -Makefile crlf=input -makespr32 crlf=input -*.map -crlf filter=mapclean -*.mapinfo crlf=input -*.m crlf=input -*.md3 -diff -crlf -*.md5anim -crlf -*.md5mesh -crlf -*.mdl -diff -crlf -*.med crlf=input -*.mf crlf=input -*.mid -diff -crlf -*.mk crlf=input -*.mkdir -diff -crlf -*.mmpz -diff -crlf -*.modules crlf=input -*.nib -crlf -*.obj -crlf -OFFSETS -diff -crlf -*.ogg -diff -crlf -*.options crlf=input -pangorc crlf=input -*.patch crlf=input -*.patchsets crlf=input -*.pc crlf=input -*.pcx -diff -crlf -*.pfb -diff -crlf -*.pfm -diff -crlf -*.pk3 -diff -crlf -PkgInfo crlf=input -*.pl crlf=input -*.plist crlf=input -*.pm crlf=input -*.png -diff -crlf -POSITIONS -diff -crlf -*.proj -crlf -*.properties crlf=input -*.psd -diff -crlf -*.py crlf=input -*.q3map1 crlf=input -*.qc crlf=input -*.qdt crlf=input -*.qh crlf=input -*.rb crlf=input -*.rc2 crlf=input -*.rc -crlf -rdjpgcom -diff -crlf -*.readme crlf=input -README crlf=input -*.rtlights -diff -crlf -SCHEMA crlf=input -*.scm crlf=input -sdl-config crlf=input -SDL -diff -crlf -*.shader crlf=input -*.sh crlf=input -*.skin crlf=input -*.sln -crlf -*.sounds crlf=input -*.sp2 -diff -crlf -*.spr32 -diff -crlf -*.spr -diff -crlf -*.src crlf=input -*.strings crlf=input -strip crlf=input -*.svg -diff -crlf -*.TAB -diff -crlf -*.tga -diff -crlf -TMAP -diff -crlf -todo crlf=input -TODO crlf=input -*.ttf -diff -crlf -*.TTF -diff -crlf -*.txt crlf=input -update-shaderlists crlf=input -*.vbs -crlf -*.vcproj -crlf -versionbuilder crlf=input -*.wav -diff -crlf -*.waypoints -diff -crlf -w crlf=input -*.width crlf=input -*.workspace -crlf -wrjpgcom -diff -crlf -*.xcf -diff -crlf -*.xlink crlf=input -*.xml crlf=input -xonotic-map-compiler-autobuild crlf=input -xonotic-map-compiler crlf=input -xonotic-map-screenshot crlf=input -xonotic-osx-agl crlf=input -xonotic-osx-sdl crlf=input -*.xpm crlf=input -*.zip -diff -crlf -zipdiff crlf=input -*.zym -diff -crlf diff --git a/misc/mediasource/extra/netradiant-src/.patchsets b/misc/mediasource/extra/netradiant-src/.patchsets deleted file mode 100644 index cebd1b56..00000000 --- a/misc/mediasource/extra/netradiant-src/.patchsets +++ /dev/null @@ -1,3 +0,0 @@ -master = https://zerowing.idsoftware.com/svn/radiant/GtkRadiant/branches/1.5 -revisions_applied = 1-327 - diff --git a/misc/mediasource/extra/netradiant-src/COMPILING b/misc/mediasource/extra/netradiant-src/COMPILING deleted file mode 100644 index 3c847ee1..00000000 --- a/misc/mediasource/extra/netradiant-src/COMPILING +++ /dev/null @@ -1,89 +0,0 @@ - -developer documentation for NetRadiant -====================================== - -(NOTE: outdated stuff has been ROT13ed) - -getting the source -================== - -The latest source is available from the git repository. - git://git.icculus.org/divverent/netradiant.git - -The git client can be obtained from the Subversion site. - http://git-scm.org - -To get a copy of the source using the commandline git client: - Change the current directory to the desired location for the source. - git clone git://git.icculus.org/divverent/netradiant.git - cd netradiant - - - -Linux(using X-windows) -====================== - -environment: -- gcc >= version 3.1 (preferably) -- GNU make -- svn >= 1.1 (some build steps use svn) - -dependencies: -- gtk+ >= 2.4.0 (requires glib, atk, pango, iconv, etc) -- gtkglext >= 1.0.0 (requires opengl) -- libxml2 >= 2.0.0 -- zlib >= 1.2.0 (for archivezip module) -- libpng >= 1.2.0 (for imagepng module) - -build: -run 'make' - -run: -Execute 'install/radiant.x86' - -OSX(using X-windows) -==================== - -environment: -- OS X 10.5 or 10.6 -- Xcode developer tools installed (OSX DVD) -- X11 (from the OS X DVD) -- MacPorts or fink installed -- the following packages installed: - Macports: - gtkglext pkgconfig glib2-devel libxml2 gtk2 pango atk gettext wget - Fink: - gtkglext1 pkgconfig glib2-dev libxml2 gtk+2 gtk+2-dev pango1-xft2-ft219-dev atk1 gettext-dev wget - -build: -run 'make' - -run: -Switch into the install folder, and run NetRadiant.app - -Win32 (2000, XP, Vista or Windows 7) -================== - -environment: -- MinGW (http://www.mingw.org/wiki/Getting_Started) - Install this to c:\mingw, and select the components C compiler, C++ compiler - and MSYS Basic System -- Start the MSYS shell once, then exit it -- Prepackaged Radiant dependencies (Gtk and other stuff): - http://www.icculus.org/netradiant/files/netradiant-dependencies-mingw32-20101211-7z.exe - Extract this one to - c:\mingw\msys\1.0\home\username - (if you do this with 7zip, keep the "netradiant-dependencies-mingw32" folder - name of the contents) -- now download the source from the MSYS shell, if you don't already have it: - ~/netradiant-dependencies-mingw32/util/bin/git clone git://git.icculus.org/divverent/netradiant.git - -build: -- Start the MSYS shell -- Switch to the directory with NetRadiant source -- make MAKEFILE_CONF=mingw-Makefile.conf - -run: -- in the "install" directory, double click netradiant.exe -- if you get a DLL not found error, copy the DLL from either c:\mingw\bin or - from c:\mingw\msys\1.0\bin to the "install" directory diff --git a/misc/mediasource/extra/netradiant-src/CONTRIBUTORS b/misc/mediasource/extra/netradiant-src/CONTRIBUTORS deleted file mode 100644 index 664e339d..00000000 --- a/misc/mediasource/extra/netradiant-src/CONTRIBUTORS +++ /dev/null @@ -1,94 +0,0 @@ -GtkRadiant CONTRIBUTORS and CREDITS -last update: 28/02/2007 -======================= - -GtkRadiant 1.5 development: -------- -Thomas "namespace" Nitschke spam@codecreator.net -Stefan "Shaderman" Greven -"Topsun" -SmallPileofGibs spog@planetquake.com -"Tr3b" - -Small contributions and improvements for 1.5 --------- -Eric "eb" Barth - -Loki ----- -Leonardo Zide leo@lokigames.com -Mike Phillips (Loki QA) -Bernd Kreimeier (overall coordination) - -QER.com -------- -TTimo timo@idsoftware.com -^Fishman (Pablo Zurita) fish@gamedesign.net -RR2DO2 rr2do2@q3f.com -SmallPileofGibs spog@planetquake.com - -Curry plugin ------------- -Mike "mickey" Jackman -Tim "Maj" Rennie - -PrtView plugin, various bug fixes and q3map guru ------------------------------------------------- -Geoffrey DeWan - -Gensurf plugin --------------- -David Hyde - -PicoModel ---------- -seaw0lf with assist by ydnar - -Q3Map2 ------- -Randy 'ydnar' Reddig - -Updated shader files, textures, entities.def, keyboard shortcut list -overall testing and feedback ----------------------------- -Jean-Francois "Eutectic" Groleau - -Improvements and bug fixing ---------------------------- -Jan Paul "MrElusive" van Waveren -Robert Duffy -Forest "LordHavoc" Wroncy-Hale -Nurail -AcidDeath -Chronos -Michael Schlueter -Jamie Wilkinson -Robert "Tr3B" Beckebans - -Web ---- -Dave "Bargle" Koenig -Jason "Wolfen" Spencer -Shawn "EvilTypeGuy" Walker - -Thanks to John Hutton, AstroCreep and W2k for web help - -FAQ ---- -Equim and Wex - - -Testing/Feedback ---- -Black_Dog, d0nkey, Fjoggis, Jago, jetscreamer, gibbie, Godmil, Gom Jabbar, -Mindlink, mslaf, necros, Promit, Ravo, RPG, scampie, sock, sponge, thiste, -voodoochopsticks, Zwiffle - - -Misc ----- -Thanks to everyone on the beta mailing list and -irc.telefragged.com #qeradiant for testing and feedback. -Updated icons by AstroCreep! -Bitch-slapping by RaYGunn! -Last minute bugs by SPoG! (SPoG--) diff --git a/misc/mediasource/extra/netradiant-src/ChangeLog b/misc/mediasource/extra/netradiant-src/ChangeLog deleted file mode 100644 index 40bd4d0a..00000000 --- a/misc/mediasource/extra/netradiant-src/ChangeLog +++ /dev/null @@ -1,279 +0,0 @@ -2009-04-26 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: minimap generation for Nexuiz - * q3map2: better progress indicators - -2009-04-23 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: misc_model spawnflag 64 turns off normal smoothing - * q3map2: improved output of vis - -2009-04-21 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: more MAX_MAP_VISIBILITY - -2009-04-15 Rudolf Polzer divVerent(at)alientrap.org - * radiant: new toolbar bitmaps by sev - -2009-04-13 Rudolf Polzer divVerent(at)alientrap.org - * all: fix some MSVC compile errors - -2009-04-10 Rudolf Polzer divVerent(at)alientrap.org - * all: add WarsowPack - * q3map2: add alias _shadeangle to _smoothnormals - * q3map2: fix crash in reading RBSP files - -2009-04-09 Rudolf Polzer divVerent(at)alientrap.org - * radiant: fix font size handling - -2009-04-08 Rudolf Polzer divVerent(at)alientrap.org - * radiant: force disable composition on Vista (should fix "white 3D window" issues) - -2009-04-05 Rudolf Polzer divVerent(at)alientrap.org - * radiant: fix ViewSide command (no longer does the same as ViewTop) - * q3map2: generate origin brushes when decompiling - * q3map2: allow more portals per leaf, to help with -bsp -deep - -2009-04-04 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: -bsp -deep also including detail brushes into the BSP tree at lowest priority, should give higher fps while increasing compile time and BSP size - * q3map2: fix crash when decompiling to .map - -2009-04-03 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: -vis -mergeportals speeding up vis a lot, while not making vis much worse - -2009-04-02 Rudolf Polzer divVerent(at)alientrap.org - * radiant: portable radiant: when a subdir "settings" exists where radiant.exe resides, config is stored there so you can take it with you on a USB stick - -2009-04-01 Rudolf Polzer divVerent(at)alientrap.org - * all: compile fix on Win64 - -2009-03-31 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: merged feature -bsp -altsplit (27), alternate way to weight BSP splits, should give higher fps in original Q3 engine (needs testing) - * q3map2: also compare shaders when comparing surfaces for sorting (27) - * q3map2: misc_model spawnflag 32 copies vertex alpha from color, for terrain blending on models (27) - -2009-03-29 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: _ls key shorthand for _lighmapscale (VorteX) - * q3map2: -samplescale switch (VorteX) - * q3map2: in dq and prophecy games, func_wall casts shadows by default (VorteX) - * q3map2: some more prints (VorteX) - * q3map2: q3map_floodlight shader keyword (VorteX) - * q3map2: more MAX_TW_VERTS (VorteX) - * q3map2: _patchMeta 1 entity keyword (VorteX) - * q3map2: q3map_deprecateShader shader keyword (VorteX) - * q3map2: tangentspace deluxemaps (-deluxemode 1) (VorteX) - * q3map2: _smoothnormals entity key to easier set shadeangle (VorteX) - * q3map2: -keeplights switch in -light (VorteX) - * q3map2: spawnflag 32 on light: unnormalized color (VorteX) - * q3map2: spawnflag 64 on light: distance falloff (VorteX) - * q3map2: option -gridscale, -gridambientscale (VorteX) - -2009-03-27 Rudolf Polzer divVerent(at)alientrap.org - * radiant: fix a crash on "regroup entities" - -2009-03-25 Rudolf Polzer divVerent(at)alientrap.org - * radiant: editable keyboard shortcuts - -2009-03-23 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: avoid a crash if a surface is huge - -2009-03-20 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: command line option -celshader - * q3map2: let Q_mkdir create all parent directories too - * q3map2: fix some crashes - -2009-03-16 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: command line option -fs_homebase - -2009-03-13 Rudolf Polzer divVerent(at)alientrap.org - * all: support objs without material groups - -2009-03-11 Rudolf Polzer divVerent(at)alientrap.org - * radiant: detect being installed inside Q2World - -2009-03-08 Rudolf Polzer divVerent(at)alientrap.org - * radiant: indicate the direction of the clip plane in the 2D view - -2009-03-11 Rudolf Polzer divVerent(at)alientrap.org - * radiant: detect being installed inside Nexuiz - -2009-03-09 Rudolf Polzer divVerent(at)alientrap.org - * radiant: OS X compile fixes - -2009-03-04 Rudolf Polzer divVerent(at)alientrap.org - * radiant: -global-Key Value and -gamename.game-Key Value options to set - config settings from the command line - -2009-02-25 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: fix two bugs in tjunction fixing - * q3map2: -lightmapdir option - * q3map2: eliminate MAX_MAP_PLANES limit - -2009-02-23 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: -scale -tex ("no texture lock while scaling") - -2009-02-15 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: non-uniform -scale x y z - -2009-02-10 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: remove LOTS of limits - -2009-02-08 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: put the command line parameters into a worldspawn key - _q3map2_cmdline; currently not yet supported for -onlyents - -2009-02-07 Rudolf Polzer divVerent(at)alientrap.org - * radiant: use gtk default font instead of defined ones for linux/windows - which could happen to be not installed (merged from uforadiant) - -2009-02-06 Rudolf Polzer divVerent(at)alientrap.org - * radiant: OS X icon by airscout - -2009-01-15 Rudolf Polzer divVerent(at)alientrap.org - * all: more fixes for OS X - -2009-01-14 Rudolf Polzer divVerent(at)alientrap.org - * radiant: use %f format for angles, prevents weird looking angles - -2009-01-09 Rudolf Polzer divVerent(at)alientrap.org - * all: lots of fixes for compiling on OS X - -2009-01-07 Rudolf Polzer divVerent(at)alientrap.org - * radiant: handle ALL key binds properly using GDK methods - -2009-01-03 Rudolf Polzer divVerent(at)alientrap.org - * radiant: fix the translation of entities used by mirroring or scaling - -2009-01-02 Rudolf Polzer divVerent(at)alientrap.org - * radiant: command "regroup entities", allows moving brushes in/out of - entities - -2009-01-01 Rudolf Polzer divVerent(at)alientrap.org - * radiant: "clone selection" no longer changes targetnames by default. - Hold shift while pressing space to do change them as before. - * all: handle "origin" keys for brush entities (more consistency, should - break no maps) - -2008-12-10 Rudolf Polzer divVerent(at)alientrap.org - * radiant: properly handle the [ and ] keys on german layout - * q3map2: fix dotProduct2scale to match the documentation - -2008-11-28 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: -dirty: don't treat skybox surfaces as solid for dirtmapping; - prevents Quake 2-ish "dark near skybox" effect. - -2008-11-21 Rudolf Polzer divVerent(at)alientrap.org - * radiant: applied win32 font and build fix by ingar - -2008-11-20 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: extend some more limits but just by a bit this time to not - let memory usage rise too high - * radiant: fix finding the .mtl file for .obj models - -2008-11-18 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: get rid of the MAX_MAP_DRAW_VERTS limit (the array already was - dynamic anyway); allows creating BSPs of over 400 MB in size ;) - -2008-11-10 Rudolf Polzer divVerent(at)alientrap.org - * radiant: draw targeting arrows also for target2, etc. keys even in Q3 - map mode; this is good for Nexuiz which now supports target, target2, - target3 and target4. - -2008-11-07 Rudolf Polzer divVerent(at)alientrap.org - * radiant: fix buffer overruns because of using the realpath function - with an insufficient buffer; there might be more of these in the code - base - -2008-10-27 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: -convert -format ase -shadersasbitmap convert mode that writes - the shader names in the *BITMAP field in the .ase. That way, the .ase - files work without changing as mapobjects. - -2008-10-12 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: fix the deluxemap contribution from ambient lighting. minLight - is still broken with deluxemapping. If you must use minLight, combine it - with 1/2 or 1/4 of its amount in ambient. - -2008-09-30 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: fix deluxemap when lit from the wrong side as good as possible - by ignoring the deluxemap contribution. Now the invariant "deluxemap - vector points away from the surface" should hold. Avoids sudden black - spots when deluxemapping. - -2008-09-26 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: turn the Urban Terror vis nudge and triangle check into options - -extravisnudge and -trianglecheck, as they break some Nexuiz maps. - Evaluate the usefulness of these options later. - * q3map2: make sure the intermediate .bsp when bouncing always is loadable - into the game (by unparsing the entities, so if gridsize got modified, - that change gets written too) - -2008-09-23 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: print a warning if the specified samplesize cannot be used with - the current lightmap size - -2008-09-22 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: add dotProduct2scale alphamod - * q3map2: add -minsamplesize command line option to override lightmapscale - specified in map files - -2008-09-19 Rudolf Polzer divVerent(at)alientrap.org - * radiant: add a "Strafe Mode" option - * radiant: ctrl-tab now focuses all XYZ views in the three-part view (as - that is what the user is likely to want there) - * radiant: make rotate/scale dialogs non-modal - -2008-09-18 Rudolf Polzer divVerent(at)alientrap.org - * radiant: handle missing anisotropy extension; fixes display bug on - Windows XP software renderer - * radiant: make logging kick in earlier - * radiant: add svn release to the version number - -2008-09-15 Rudolf Polzer divVerent(at)alientrap.org - * all: added a Makefile to build GtkRadiant; this replaces scons and - python install.py - * all: got rid of libmhash dependency, using mdfour.c from DarkPlaces - instead - * q2data: remove RSA security copyrighted md4.c, using mdfour.c from DP - instead as a drop-in replacement - * all: get rid of version.h and aboutmsg.h, instead set the version in the - Makefile - * all: support cross compiling using mingw32 - -2008-09-13 Rudolf Polzer divVerent(at)alientrap.org - * q3map2: update to ZeroRadiant's q3map2 - * q3map2: added lightmap exposure feature: -exposure 4.2 (Urban Terror) - * q3map2: check whether a lightmap sample is actually in the triangle - (Urban Terror) - * q3map2: nudge light sample origin by 1qu away from planes (Urban Terror) - * q3map2: floodlight: usage is "_floodlight" "red green blue distance - intensity", default "240 240 255 1024 128"; works somewhat similar to - dirtmapping (Urban Terror); uses a switch -lowquality - * q3map2: added -debugnormals feature (Urban Terror) - * q3map2: fix -convert -format map decompiling (note: outputs map in - "Alternate Texture Projection" format); no longer messes up texcoords - * q3map2: added -game nexuiz to use good default paths for Nexuiz - * q3map2: added -game quakelive to enable in-game adverts - * q3map2: fix incorrect plane snapping often causing holes in terrain - * q3map2: spawnflags on misc_model: 8 extrudes with original normals, 16 - extrudes with up/down normals (terrain), default: extrudes with axial - normals (like before) - * q3map2: fix obvious (and reported, and patch sent in) bug when importing - models when the normals were pointing in a 45 degrees direction - * q3map2: when importing models, allow "surfaceparms structural". This - also turns off any plane snapping, as it is intended for caulk brushes - inside a model - * q3map2: added parameters -ne to set normal epsilon, and -de to set - distance epsilon (to customize plane snapping) - * q3map2: fix q3map_lightRGB (Urban Terror) - * q3map2: add a build script to cross compile q3map2 to Win32 - * radiant: when displaying normals on a model, scale them to 8 unit size - on the output (so "modelscale" can be used without LOTS of lines on the - screen) - * radiant: also support "killtarget" as target key for drawing the - targeting lines - * radiant: "expand selection to whole entities" now also selects the - entity ITSELF; result: Ctrl-Alt-E Space makes a NEW entity now, instead of - just duplicating the brush (old behaviour caused bugs in maps with copied - func_ladders) - * picomodel: support .obj format as exported by Blender, with a .mtl file - defining the shader names for each material; to export using Blender, - enable "Materials" and "Material Groups" in the .obj export dialog - * all: bump version to 1.5.0-div0 diff --git a/misc/mediasource/extra/netradiant-src/ChangeLog.idsoftware b/misc/mediasource/extra/netradiant-src/ChangeLog.idsoftware deleted file mode 100644 index 47deae20..00000000 --- a/misc/mediasource/extra/netradiant-src/ChangeLog.idsoftware +++ /dev/null @@ -1,8216 +0,0 @@ -This is the changelog for developers, != changelog for the end user -that we distribute with the binaries. (see changelog) - -28/06/2007 (dunkfordyce@gmail.com) -- fixed mnemonics for MRU list -- fixed find functionality -- added option to always use caulk texture for new brushes -- fixed(?) a small bug in install.py that was trying to copy msvc files on linux - -28/06/2007 -- Added material-support to brushexport-plugin (Shaderman) - -26/04/2007 -- Disabled auto-search for texbrowser and entityinspector even when the option - is turned on in the gtkrc - -26/04/2007 -- Fixed q3map2 lightbounce bug (by Unknown) - -26/04/2007 -- Fixed another texcompression bug - -25/04/2007 -- Fixed texcompression beeing disabled after each restart -- Fixed gtk-searchpopup in treeviews - -15/04/2007 -namespace -- Fixed brushexport2 output float-format (Shaderman) - -27/03/2007 -namespace -- Fix: Added missing xml-writer pop-calls -- Ported mapxml plugin to Doom3 -- mapxml now exports brushes with its vertices - -19/03/2007 -namespace -- Fix: Selection is now deleted when creating a patch out of it (aumüller / namespace) - -08/03/2007 -namespace -- Win32 compile fix (woekele) - -07/03/2007 -namespace -- Updated UFA:Plugin (mattn2) - -04/03/2007 -namespace -- Reverted Q3 translucency fix since it randomly made brushes - fully transparent in Doom3 mode. - -04/03/2007 -namespace -- Final update for installerfiles (Shaderman / namespace) -- Removed installer.py validation checks since they are incompatible with Vista -- Updated msiquery module to python 2.5 -- Added msiquery module for python 2.5 - -03/03/2007 -namespace -(THIS IS A TRANSITIONAL REVISION, DO NOT USE, WAIT FOR UPDATED DEPS) -- Fixed weird msvcrt bugs caused by dbghelp.dll -- Activated new radiant icon on Linux (Topsun) -- First update for installerfiles (Shaderman) -- New MODT for q3map2 :) -- tiny changes - -28/02/2007 -namespace -- Radiant is now Vista compatible (Aero must be disabled) -- Updated all radiant dependencies (gtk is now 2-2.10) - New dependency packages can be found here -http://zerowing.idsoftware.com/files/radiant/developer/1.5/gtkradiant-1.5-dependencies-1.0.zip - or here -http://www.codecreator.net/radiant/gtkradiant-1.5-dependencies-1.0.zip -- Removed Win32 filechooser - - Fixes crashes caused by utf-8 encoded filenames - - Fixes Vista "SaveAs"-Bug -- Converted all projects to Visual Studio 2005 -- Codefixes for vc2k5 compiler -- Removed old unused projectfiles for Visual Studio 6 -- Simplified dependency filestructure -- Simplified install.py -- Updated CONTRIBUTORS list - -26/01/2007 -namespace -- SnapPlane reenabled by namespace because of multiple reports of - q3map2-crashes which were triggered by this patch. - -24/01/2007 -namespace -- Added Undo/Redo-Toolbarbuttons (Shaderman) -- Fixed Bug #1078 (sogined) - -18/01/2007 -namespace -- Weird shiftvalues are now hidden to the user, shiftvalues will - stay in ]-shader_size;shader_size[ range for display. - For the sake of floatingpoint precision, it would be nice - to keep the internal values in that range too, but thats "nice to have". -- Fixed missing librarypaths in ufoai-plugin - -18/01/2007 -LordHavoc -- disabled SnapPlane because it slightly corrupts collision brushes from - embedded model triangles - -17/01/2007 -namespace -- Fixed "jumping" texcoords when switching to a shader with different size -- (Todo) Toolbar: add button for refresh-models. (Shaderman) -- Aniso fix (Shaderman) -- Translucency fix (Shaderman) - -05/01/2007 -namespace -- UFO:Alien Invasion Plugin (mattn2) -- Fix: Filtering models in ET doesn't filter misc_gamemodels (Shaderman) - -25/12/2006 -namespace - - Brushplugin Version 2.0, supports multiple collapse modes and a materialignore list (namespace) - - Camera movement speed changes. Increase speed = SHIFT+KP_PLUS, decrease speed = SHIFT+KP_MINUS. - New option to link the strafe speed to camera movement speed (default: linked). (Shaderman) - - Fixed bug in sample plugin (Shaderman) - - Merry Christmas - -17/12/2006 -namespace - - Radiant warzow-support (Topsun + Warzow-Mappers) - -15/12/2006 -namespace - - Inverted bevel can be used with end caps (Topsun) - - Removed needless .pdb files from win32 installer (Topsun) - - Fixed .ase picomodel loader to load shaders again (Shaderman) - - Removed translucent brushes fix because of wrong rendering behaviour on Linux - - New cool(!) radiant icon by eb - -13/12/2006 -namespace -- Added tremoulus-support to q3map2 - -08/12/2006 -namespace -- Entity names are now drawn for group entities in Doom3 and Quake 3 mode (namespace) -- Fixed translucent brushes becoming invisible when selected (Shaderman) - -06/11/2006 -namespace -- (TODO) Texture sizes sometimes vary wildly. New texture browser option: View -> Fixed Size. - Code parts taken from DarkRadiant. (Shaderman) -- Added new texture browser option: View -> Hide Image Missing. (Shaderman) -- Fixed new D3 lights don't have a light_radius key. (Shaderman) -- Fixed hotkey collision (paste to camera/view menu). New View shortcut = ALT+W. (Shaderman) -- Fixed .wad MMB 3d view texture selection bug. (Shaderman) - -04/11/2006 -namespace -- Added warzow-support to q3map2 - -12/10/2006 -namespace -- Updated help menu web links (removed map-center.com, added ETB documentation) (Shaderman) -- Added check for existing worldspawn if a new one should be added with the entity menu (Shaderman) -- Fixed Entity -> Ungroup (Topsun) -- Fixed hotkey collision ALT+M (filter botclip/Modify menu). New Modify shortcut = ALT+O (Shaderman) -- Updated Window Layout images (Shaderman) -- Fixed (TODO) XYWindow: save show-workzone option (Shaderman) -- Fixed (TODO) Toolbar: add shortcut to tooltips for toolbar buttons (Shaderman) -- Fixed (TODO) GUI: detachable submenus (Shaderman) - -09/10/2006 -namespace -- Added option to toggle the camera window stats on/off (Shaderman) - (view --> show --> show stats) - - -08/10/2006 -namespace -- Fix for bug 1106 - .wad files don't get listed in the textures menu (Shaderman) - (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1106) -- Added initial support for Prey (Shaderman) -- Fixed entity inspector sliders to always show (Shaderman) -- Added NOTES subsection to the entity inspector listing .def "editor_usage*" values (Shaderman) - -07/10/2006 -namespace -- Added "select inside" and "select touching" - Both functions now work with multiple selectionbrushes, allowing complex - selection operations. -- Added entries for the selectionfunctions in "Edit" and the main toolbar. - -06/10/2006 -namespace -- Changed ETB not to show any texture if a tag search doesn't match anything (Shaderman) -- Added View -> Filter -> "Invert filters/Reset filters" function (Shaderman) -- Fixed (TODO) Textures: remove "shaders only" option for doom3 (Shaderman) -- Fixed show shaders / shader only / shader info for doom3 and .wad file games (Shaderman) - -03/10/2006 -namespace -- Fix for Bug 1113 (Topsun) - (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1113) - -03/10/2006 -namespace -- Changed ETB tag toolbar to a notebook with tag/texture pages (Shaderman) -- Added a context menu (add/delete/rename tag) to the ETB tag tree view (Shaderman) -- Added new win32 installer HOWTO (Shaderman/Topsun) - -01/10/2006 -namespace -- Added missing xml files for win32 installer - -30/09/2006 -namespace -- Fixed Etb saving custom tags to global tagfile (Shaderman/namespace) -- Fixed postbuild step for brushexport, shaderplug and sunplug (Shaderman) -- Added installersupport for new files and plugins (Shaderman) - -30/09/2006 -namespace -- Added LocalLcPath to plugin interface -- Added enhanced Texturebrowser (ETB) by Shaderman -- Added shaderplug by Shaderman, accompanies the ETB -- Added xmltagging lib by Shaderman, accompanies the ETB -- Added new icons for ETB, Console, Entityinspector and Lighteditor -- Fixed minor warning in Sunplug Project -- Fixed PATH_MAX namecollision in ptrview plugin on Linux -- Final fix for 64 bit patch.h issue - - - -12/09/2006 -namespace -- Fixed 64 Bit issue in patch.h, see http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1109 - for details - -11/09/2006 -namespace -- Fixed unnecessary warnings, see http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1108 - for details - -11/09/2006 -namespace -- Added sunplug (Mapcoordinator-plugin for ET) by Topsun - ET only: setting mapcoordsmins and mapcoordsmaxs in the worldspawn - Tester: Shaderman -- Added brushexport Plugin by namespace - Exports selected brushes as wavefront object. - Tester: Shaderman - -11/09/2006 -namespace -- Fixed compile error on x86_64, see http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1105 - for details. - -09/09/2996 -namespace -- Added strafing for the camerawindow while holding ctrl -- Additional forward movement can be enabled by pressing shift during strafe - -22/08/2006 -SPoG -- Added VFS support for locating the archive a file was loaded from. -- Changed Doom3 entity definition parser to gracefully handle parse errors. -- Fixed crash when loading entity definitions in quake4 1.3 point release. - -13/08/2006 -SPoG -- Disabled 'detail' content flag checkbox in quake2 Surface Inspector. - -22/07/2006 -SPoG -- Fixed doom3 func_static with model not appearing to move when dragged. -- Changed ASE model loader to parse material names the same way as DoomEdit. -- Fixed title of wait-dialog when loading a model. -- Fixed doom3 func_static with blank 'model' key being invisible. -- Changed doom3 func_static model creation to replace selected models. -- Added support for loading both .ent and .def files at the same time. - -09/07/2006 -Shaderman -- Updated win32 libxml2 package to 2.6.24. -namespace -- Ported win32 stack-backtrace to use new DebugHelp API. -- Added stack-backtrace functionality for Linux/OSX. - -11/06/2006 -SPoG -- Fixed arbitrary rotation X and Y axes appearing to be transposed. - -04/06/2006 -SPoG -- Fixed crash when deleting items from Build menu. - -03/06/2006 -SPoG -- Changed doom3 entity creation to add model key for brush-entities. -- Fixed crash in Save Region. -- Fixed detail brushes being turned structural when texture is set. - -29/05/2006 -SPoG -- Changed default doom3 light_radius to be taken from the entity-definition. -- Fixed error when entering and exiting camera freemove with LMB pressed. - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1090 - -13/05/2006 -LordHavoc -- Added -fPIC for Linux builds to support x86_64. -- Removed static-linked libstdc++ hack for non-final builds. -- Removed gcc explicit linking hack for non-final builds. -- Added workaround for gcc static-member-pointer-as-template-argument bug. -- Fixed bobtoolz linux compile errors. -- Added Nexuiz and Darkplaces support. -SPoG -- Changed 'inconsistent vertex count' assert to be non-fatal. -- Changed 'failed to remove accelerator' assert to be non-fatal. -- Fixed crash due to broken module dependencies. -- Fixed default settings for Build Monitoring. -- Fixed nudge-selection when using the drag tool mode. -- Added support for patches in texture-painting tool. - -30/04/2006 -SPoG -- Fixed memory leak in signals library. -- Ported bobtoolz to use new module APIs. - -01/04/2006 -SPoG -- Added key-observer interface to entity module API. -- Rewrote callback library to add support for return-values. -- Added minimal API to support bobtoolz plugin. -- Refactored brush for-each functions to take Functor instead of Visitor. -- Added signals library. - -31/03/2006 -SPoG -- Changed doom3 light creation to use size of selected brushes. - -20/03/2006 -SPoG -- Fixed crash when resetting preferences after startup failure. -- Fixed crash on next-leak-spot with build-monitoring enabled. -- Fixed doom3/quake4 blended-decal rendering when toggling lighting mode. -- Fixed fit-texture with rotated texture transforms. - -20/03/2006 -SPoG -- Changed Copy/Paste to work on face textures if any faces are selected. -- Fixed GTK_WIDGET_REALIZED assert when selecting entities (linux). - -28/02/2006 -namespace, SPoG -- Added drag-resizing for doom3/quake4 light_radius boxes. - -25/02/2006 -SPoG -- Fixed objects sometimes dissappearing when at high zoom level in Ortho views. - -24/02/2006 -SPoG -- Added GPL text to win32 installer. -- Fixed gtk wimp theme not working after using gtkthemeselector. - -21/02/2006 -namespace -- Added command to toggle lighting/textured modes, shortcut F3. - -20/02/2006 -SPoG -- Fixed crash when disabling lighting for a second time. - -19/02/2006 -SPoG -- Fixed crash when loading invalid ASE models. - -11/02/2006 -SPoG -- Added install.py script. -- Updated COMPILING instructions. -- Fixed transparency rendering on quake3 shaders. -- Fixed hint/caulk filtering for Jedi Academy shaders. - -04/02/2006 -SPoG -- Added Radiant Manual shortcut to win32 installation. -- Added 'use alternative texture projection' option to prefs. -- Fixed caching bug causing import-map to not reload modified maps. -- Added blended-decal rendering for doom3 and quake4. - -30/01/2006 -SPoG -- Added expand-selection-to-entities with default shortcut ctrl+alt+e. -- Fixed crash in gtk file-chooser with some versions of GTK+. - -29/01/2006 -SPoG -- Changed create-group-entity to re-select brushes after creation. - -26/01/2006 -SPoG -- Changed far-clip-plane setting to increase exponentially with distance. -- Fixed selected entities moving when drag-resizing brushes. -- Changed patches to be selectable from the back in wireframe views. -- Speed improvements for transform-selection code. - -25/01/2006 -SPoG -- Added default-texture-scale option to preferences. -- Added default-grid-spacing option to preferences. - -23/01/2006 -Shamus -- Fixed editing of doom3/quake4 faces with negative texture scale factors. - -22/01/2006 -SPoG -- Fixed shortcut for toggle-far-clip. -- Fixed broken link in 1.5 user docs. - -10/01/2006 -SPoG -- Changed script parser to ignore comments that start in the middle of tokens. -- Added support for editor_int/editor_string keys in doom3 entity definitions. -- Changed doom3/quake4 .mtr and .guide searching to look in subfolders. -- Added experimental support for doom3/quake4 projected lights. - -20/12/2005 -SPoG -- Added support for quake4 .guide material templates. -- Fixed GCC4 compile errors with anonymous enums. -- Added light_radius and light_center GUI to doom3 entity inspector. - -10/12/2005 -SPoG -- Added support for loading and saving Quake4 map format. -- Added support for built-in shader images such as _noFalloff. -- Added experimental code to render projected lights. -- Added support for loading quake4 entity definitions. -- Fixed picomodel bug loading .lwo files with texture names >64 in length. - -22/10/2005 -SPoG -- Fixed minor memory leak in zip-archive reader. - -21/10/2005 -SPoG -- Fixed model rotation using free-rotation tool. -- Fixed behaviour of angle/rotation keys for Doom3 entities. -- Added entity angle-editing for entities that display a model. -- Stopped size-info being drawn if selection has zero size. -- Added support for 'angle' key on doom3 entities. - -20/10/2005 -SPoG -- Fixed minor one-time memory leak in build-shader-list. -- Added functional free-scale tool. -- Improved precision preservation for free-rotation and free-scale tools. -- Fixed misc_model rotation using free-rotation tool. - -09/10/2005 -SPoG -- Added entity angle-editing using rotate-tool or rotation toolbar buttons. -- Fixed start-on-primary-monitor (win32). -- Fixed camera-view freelook when window is on secondary monitor (win32). - -05/10/2005 -paxed -- Added texture-lock toolbar button. -SPoG -- Added stack-trace output to all debug popup messages (win32). -- Fixed vertex/edge selection behaviour on undoing brush edits. -- Changed doom3 light centre rendering to use a point instead of a box. -- Changed map and shader parsers to gracefully handle bad data. - -24/09/2005 -SPoG -- Fixed crash when importing a file after deleting the world entity. -- Changed copy/paste/import to select world brushes instead of world entity. -- Added win32-specific stack-trace logging support. - -31/08/2005 -SPoG -- Fixed clipper removing brushes on incorrect side of clip-plane when flipped. - -21/08/2005 -SPoG -- Optimised light-dragging. -- Changed connect-entities to not break existing connections where possible. - -24/07/2005 -SPoG -- Fixed q3 entity definition for item_health_small. - -02/07/2005 -SPoG -- Fixed build menu becoming empty if editing of default menu is cancelled. - -01/07/2005 -SPoG -- Fixed snap-planes-to-integer preference not being saved. - -26/06/2005 -SPoG -- Changed doom3 light_radius box to draw flat-shaded translucent in camera view. -- Fixed progress window not being shown when loading maps. -- Refactored shortcut handling to make focussed widgets override global shortcuts. - Allows using ctrl+c to copy console text, undo/redo without main-window focus. - -23/06/2005 -SPoG -- Fixed crash when handling assert/error before gtk_init. -- Changed Help menu to display only the help menu relevant to the current game. - -21/06/2005 -SPoG -- Fixed double-maps-directory when using non-native file open dialog on win32. -- Changed find/replace-textures window to update when selecting textures with MMB. -- Fixed handling of non-UTF-8 wad-names in textures menu. - -20/06/2005 -SPoG -- Changed home-path prefix to be optional on linux/osx for q1/q2. -- Changed OpenGL module to work correctly with GL_VERSION 2.0.0. -- Fixed spawnflags in Enemy Territory entity definitions. -- Added missing Enemy Territory entity types. - -19/06/2005 -SPoG -- Changed clipper-point selection/rendering to behave the same at all zoom levels. -- Changed clipper-point selection to always pick the closest point to the cursor. -- Fixed clipper colour not being updated until after restarting. -- Fixed QE tool not deselecting edges when left-clicking on a vertex without shift. -- Fixed grid rendering with grid settings other than 8-unit. -- Fixed textures menu always behaving as if show-shaderlist-only is enabled. - -18/06/2005 -SPoG -- Added saving of camera render mode preference. -- Changed default camera render mode to Textured for Doom3. -- Changed default texture render mode to Trilinear. - -17/06/2005 -SPoG -- Ported Team Arena entity definitions to xml format. -- Added xml q3 entity-definitions to win32 and linux setups. - -14/06/2005 -SPoG -- Fixed QE-tool component-drag selecting components of unselected brushes. - -13/06/2005 -SPoG -- Changed clipper mode and component-editing modes to be mutually exclusive. -- Changed camera A/Z/D/C keys to obey "discrete movement" checkbox. -- Added support for up/down movement in freelook mode. -- Fixed clipper-tool-uses-caulk option. -- Added prompt for engine path at startup if not found. - -12/06/2005 -SPoG -- Added entity-inspector GUI support for func_button/func_door direction attribute. -- Added angle/model/sound GUI to entity-inspector for old-style entity-definitions. -- Added clipper-plane rendering using stippled back-face-culled polygon. -- Fixed entity-inspector failing to handle non-ascii characters in entity keys. - -11/06/2005 -SPoG -- Fixed entity-inspector window position changing while hidden. - -09/06/2005 -SPoG -- Fixed region-set-selected for model entities. - -08/06/2005 -SPoG -- Added option to enable or disable snapping brush planes to integer on map load/save. -- Added 0.125 grid. -- Changed grid rendering to always show major/minor grid colours whatever the zoom level. -- Increased maximum zoom level for XY views. - -06/06/2005 -SPoG -- Added 'File > Refresh models' - reloads models that have changed outside Radiant. - -05/06/2005 -SPoG -- Fixed model files not being closed after being read. -- Fixed build menu dialog not saving changes to build commands. -- Changed build menu to save xml only if changed by user. -- Fixed CSG-merge. -- Reduced CSG-merge tolerance for misaligned brushes. -Michael Kluskens -- Updated STVEF default build menu to version 2 format. -- Updated STVEF game configuration file and removed synapse.config. - -02/04/2005 -SPoG -- Changed HashTable insert/remove operations to not invalidate iterators. -- Changed ReferenceCache realise/unrealise to take advantage of new HashTable behaviour. -- Refactored containers to use std::swap. -- Refactored bitfield.h. -Tr3B -- Fixed endianness for .lwo loading on linux. -- Extended q3map2 mathlib functionality. - -28/03/2005 -SPoG -- Specialised filters list for doom3 entity/material types. -- Added ASE-loader support for shader names specified as a bitmap absolute-path. -- Fixed monitored-compile debug-feedback display. -- Added TGA-loader support for vertical and horizontal flipping. -- Enabled auto-generation of smooth normals for all LWO models. - -27/03/2005 -Tr3B -- Fixed map-xml module. -- Added support for qer_trans keyword in doom3 materials. - -08/03/2005 -SPoG -- Added GUI updates during map load and engine-path/game-dir changes. -- Fixed main window being hidden behind another application on closing a floating window. - -07/03/2005 -SPoG -- Fixed crash when selecting the root node in the entity-list window. -- Fixed detail flag saving for quake3 map format. - -06/03/2005 -SPoG -- Optimised type-casts for scene-graph type system. -- Disabled substitution of 'unspecified' for entity key values that match the default. -- Refactored module-system api - added globalModuleServer(). -- Fixed rotation origin for doom3 func_static models. - -05/03/2005 -SPoG -- Added support for doom3 model-entity 'skin' key. -- Added noshadows/nospecular/nodiffuse/falloff doom3 light keys to entity-inspector. - -04/03/2005 -SPoG -- Added camera move up/down one floor. -- Added support for 'unspecified' contents/flags/value for Quake2 brush faces. - -26/02/2005 -SPoG -- Added auto-complete for shader attributes in entity inspector. -- Added support for doom3-material heightmap to normalmap conversion. - -22/02/2005 -SPoG -- Fixed missing prefix attribute in quake game configuration file. -- Added auto-completion for find/replace-textures texture-name entries. -- Removed redundant buttons and options in find/replace-textures window. - -21/02/2005 -SPoG -- Added auto-completion for surface-inspector texture-name entry. - -20/02/2005 -SPoG -- Fixed failure to load shaders containing '.' such as Heretic II model skins. -- Removed unused legacy cmdlib functions. -- Added support for fractional repeat values to brush-fit-texture. - -19/02/2005 -SPoG -- Changed entity-connect-selected to use the parent entity of a selected brush. -- Added q2map and bspc to installation packages. -Jamie Wilkinson -- Fixed path to q2map in quake2 build-menu. - -13/02/2005 -SPoG -- Fixed crash in 'Misc > Find Brush' when searching for a non-existent brush. - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1059 -- Limited the maximum number of sides of a prefab brush-cone to 32. - -11/02/2005 -SPoG -- Changed display of angled box-entities to show un-rotated bounding boxes. - -10/02/2005 -SPoG -- Disabled rotation of light entities for games other than Doom 3. - -09/02/2005 -David Constanzo -- Fixed episode flag names on Quake item_sigil and func_episodegate entities. - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1056 -- Added detailed description of Quake item_sigil and func_episodegate entities. -SPoG -- Fixed position of light-entity names. -- Fixed q3map2 feedback xml streams containing non-UTF-8 text. -- Optimised Locale<->UTF-8 text conversion. - -08/02/2005 -SPoG -- Fixed selecting a texture not resetting the current selected texture-projection. -- Added handling of OpenGL drivers that don't implement all reported extensions. - -07/02/2005 -SPoG -- Added support for multi-byte UTF-8 characters in xml content (not markup). -- Added UTF-8 support in entity-inspector, prefs dialog, recent-files menu, console. -- Fixed potentially misaligned objects. - -05/02/2005 -SPoG -- Added rendering of entity names for non-group entities. -- Removed context-dependent opengl calls before opengl context is created. - -04/02/2005 -SPoG -- Fixed crash when printing extended-ascii text in the console. -- Added conversion of extended-ascii text to utf8 for gtk text-buffer widgets. - -03/02/2005 -David Constanzo -- Fixed typo in Quake entity-definitions. -SPoG -- Fixed undo of brush-set-structural and brush-make-structural. -- Refactored image-loader module api. -- Added full support for Quake II and Heretic II surface-flags in surface-inspector. -- Fixed crash in patch-inspector for games other than doom3. - -01/02/2005 -SPoG -- Changed shader-list and entity-definition searching to also search base-dir. - -29/01/2005 -SPoG -- Fixed title of floating entities/console/textures window. -- Fixed destruction of floating windows on shutdown. -- Added shortcut handling when entity-inspector/texture-browser are active. -David Constanzo -- Fixed crash while auto-saving snapshots. - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1049 - -28/01/2005 -SPoG -- Added rendering of fixed S/T tesselation on doom3 patches. -- Changed creation of doom3 func_static entities to prompt for a model. -- Fixed zero-sized primitives being rendered for culled entity-connection-lines. - -25/01/2005 -SPoG -- Added support for setting fixed S/T tesselation on doom3 patches. -- Changed patch inspector to be completely non-modal. - -24/01/2005 -SPoG -- Added support for rotating lights using the rotation tool. - -23/01/2005 -SPoG -- Fixed crash on startup with texture-subsets enabled. - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=1045 -- Added support for doom3 lights combined with brushes and patches. -- Added support for doom3 light_origin on lights. -- Added support for doom3 light_rotation and rotation key on lights. - -22/01/2005 -SPoG -- Fixed crash when accessing links from help menu. -- Fixed broken links in help menu. -- Added game-specific docs to win32 setup. -- Changed q3 connect-entities to preserve existing targetname key. -- Changed q3 connect-entities to generate targetname key based on target classname. - -21/01/2005 -SPoG -- Moved information in synapse.config into .game files. -- Added api versioning for module-system. - -20/01/2005 -SPoG -- Fixed keys/values for brush entities not being editable unless parent is selected. -- Fixed brush-entities not being deleted when the last child brush is deleted. -- Fixed scenarios where worldspawn is not the first entity in the map. - -19/01/2005 -SPoG -- Fixed numerical instability in brush winding-generation. - -16/01/2005 -SPoG -- Added Jedi Academy support to linux installer. -- Fixed main-window jumping to front during autosave. -- Fixed saving of empty brushes. -Jame Wilkinson -- Fixed build errors when compiling for big-endian target. - -15/01/2005 -SPoG -- Fixed launching q3map2 from build-menu on linux/osx. -- Added version checking of generated config files. -- Fixed key-up events being missed while holding ctrl/shift/alt. -- Fixed texture-compression support. -Jago -- Changed q1 trigger_relay and trigger_counter to be point entities. - -11/01/2005 -SPoG -- Changed brush-save to not write non-contributing faces. -- Fixed rendering artifacts on outlines of selected box-entities. - -10/01/2005 -SPoG -- Added patch-cap-cylinder. - -09/01/2005 -SPoG -- Fixed texture-browser scroll-to-selected-texture. -- Added brush face texture painting. - -08/01/2005 -SPoG -- Fixed ungroup-selected-entities. -- Added 'Entity' menu. -- Removed items unrelated to entity-creation from xy-window right-click menu. -- Fixed minor memory leaks in core. -- Removed code that ignores empty alpha-channel in tga loader. -- Fixed memory leak in model module. -- Fixed memory leaks in picomodel library: ase and lwo loaders. -- Changed default tool to 'QE' tool. - -04/01/2005 -SPoG -- Changed start-on-primary-screen default to 'true' with multiple screens. -- Added enter/escape as shortcuts for OK/Cancel buttons on modal dialogs. -- Disabled mouse-chase scrolling in XY window when drag-selecting. -- Fixed xlink I/O warnings on linux. -- Removed light-creation 'intensity' dialog in doom3 config. -- Changed the default vertical size of the shortcut-list window to 400. -- Fixed patch-creation with zero-sized workzone. -- Fixed crash when rendering doom3 light_radius box. - -03/01/2005 -SPoG -- Added arbfp1/arbvp1 vertex/fragment program lighting support. -- Fixed colour-selection dialog not going away after OK/Cancel. -- Fixed tangent/bitangent calculation on degenerate patches. -- Added resizing of patches with QE tool. - -02/01/2005 -SPoG -- Added stippled hidden-line rendering for rotate/translate manipulators. -- Refactored high-level camera/orthographic rendering functions. -- Fixed failure to load models with back-slashes in path. -- Improved peformance of doom3 lighting with large models. - -01/01/2005 -SPoG -- Changed entity renderering to draw connections for culled entities. -- Fixed runtime errors on shutdown after cycling between lighting/textured. -- Fixed 'Cancel' button in modal dialogs behaving like 'OK' button. -- Changed 'clip' brush filtering to use shader parameters instead of names. -- Added rendering of origin-point for selected model entities. -- Fixed doom3 light-interaction updates for model entities. - -31/12/2004 -SPoG -- Removed menu-splitting functionality. -- Refactored entity-class menu construction. -- Replaced const_reference with ConstReference. -- Renamed string_t to CopiedString. -- Changed code using Str::Format and Str::operator+= to use StringOutputStream. -- Refactored shortcut command parsing code. -- Changed light entity rendering to show light_radius box only in doom3 config. -- Added 2x overbrightening for doom3 lighting preview. - -16/12/2004 -SPoG -- Changed default doom3 light_radius to 300. -- Fixed initial value of doom3 light_center. -- Reduced frequency of gui updates during map load. - -13/12/2004 -SPoG -- Fixed crash in monitored-compile feedback dialog. - -12/12/2004 -SPoG -- Added visualisation of halflife texture-projection format. -- Added texture-lock for halflife texture-projection format. -- Changed brush-texture-lock default to enabled for doom3 and halflife. - -11/12/2004 -SPoG -- Refactored script-tokeniser. -- Fixed doom3 lighting on ATI cards. -- Added support for list attributes in entity definitions. -- Added utf8-normalisation on text printed to console. -- Fixed missing default_build_menu.xml in halflife game config. - -10/12/2004 -SPoG -- Fixed missing commas in entity-inspector comments. -- Added support for default values in entity-definitions. - -09/12/2004 -SPoG -- Enabled doom3 realtime lighting preview. - -05/12/2004 -SPoG -- Fixed gcc compile warnings in patch.cpp. -- Added q1 and q2 support to linux installer. - -02/12/2004 -SPoG -- Added highlighting of entity-list nodes that have selected descendants. - -29/11/2004 -SPoG -- Fixed xy-window failing to update after map-load. - -28/11/2004 -SPoG -- Fixed error on shutdown when game-select dialog is disabled. -- Added surface/light-interaction debugging mode. -- Added per-plane light-culling for brush faces. -- Added support for bump shaders using 'blend' layer keyword. -- Added support for light-shaders. -- Fixed edge/border clamping on light-attenuation textures. -- Added 'Lighting' camera render-mode for doom3 config. - -25/11/2004 -SPoG -- Fixed right-click-menu on linux. - -13/11/2004 -SPoG -- Changed light-entity to draw radii only when selected. - -07/11/2004 -SPoG -- Fixed shortcuts for creating n-sided brush-prisms. - -19/10/2003 -SPoG -- Fixed user-customisable shortcuts support. - -16/10/2003 -SPoG -- Added restore-main-window call when a modal-dialog dialog-box is shown. - -13/10/2003 -Jamie Wilkinson -- Fixed SConstruct cpu detection on Power Macintosh. -- Added more verbose warning settings for gcc builds. -SPoG -- Changed buffered-text-input-stream API to not use magic EOF value. - -06/10/2004 -Jamie Wilkinson -- Fixed debug-break on non-x86 platforms. - -05/10/2004 -SPoG -- Fixed new doom3 entities not being given unique names. - -02/10/2004 -SPoG -- Fixed autosave causing the main-window to jump to the front. -- Fixed window-title when changing view direction in floating-windows layout. -- Added status information to wait dialogs. -- Changed map-save to overwrite/refresh files modified/deleted outside radiant. -- Changed component selection in QE tool to treat near-equal points as one. -- Added texture browser window to View menu. -- Changed white overlay in camera-window to draw hidden lines in 75% grey. -- Reduced point-size for vertex/edge/face handles by 2/3. - -25/09/2004 -SPoG -- Added component-editing for curves on doom3 entities. -- Added normalisation of translation for texture-lock on doom3 brushes. -- Added update of surface inspector for texdef changes caused by texture-lock. -- Changed floating-windows layout to centre all ortho views on center-xy-views. -- Stopped autosave from saving unmodified maps after first-time load. -Shamus -- Textool improvements. - -21/09/2004 -Michael Schlueter -- Changed file-chooser dialogs to use GtkFileChooser. - -20/09/2004 -SPoG -- Added basic rendering for 'curve_CatmullRomSpline' on doom3 entities. - -19/09/2004 -SPoG -- Added basic rendering for 'curve_Nurbs' on doom3 entities. - -18/09/2004 -SPoG -- Added doom3 entity-definition editor_usage* key support. -- Added doom3 entity-definition editor_* key info to entity-inspector comments. -- Added specialised attribute-entry in entity-inspector for boolean attributes. -- Fixed crash in find-brush when entering the index of a fixed-size entity. -- Added support for rendering doom3 'targetN' -> 'name' entity connections. -- Changed connect-entities to use 'targetN' and 'name' keys on doom3 entities. -- Improved handling of brushes with near-duplicate planes. -- Fixed crash in snap-to-grid on brushes with non-contributing faces. - -17/09/2004 -Michael Schlueter -- Fixed gcc build errors. -SPoG -- Fixed stability problems with doom3 brush-entities. - -16/09/2004 -SPoG -- Added automatic renaming of entity target/name keys for paste and import-map. - -13/09/2004 -SPoG -- Fixed rotation/mirror toolbar buttons using wrong axes in certain situations. -- Fixed incorrect filter settings display in filters menu. -- Added automatic renaming of entity target/name keys when cloned. -- Fixed quake2 support. - -12/09/2004 -SPoG -- Added shortcut support for all menu commands and toolbar buttons. -- Fixed patch shader-name saving for doom3 patches created by user. - -10/09/2004 -SPoG -- Fixed patch-cap-endcap and patch-cap-reverse-endcap. - -09/09/2004 -SPoG -- Fixed status-bar labels showing 'Label' at startup. -- Fixed textures-menu grouping bug. -- Fixed mirroring on brushes with doom3 plane-defs. - -08/09/2004 -SPoG -- Changed patch-cap-selected to prompt for cap type only once. -- Fixed infinite-loop in patch-cap-selected. -- Changed autosave to only save if the map has changed since the last autosave. -- Changed "file exists, overwrite?" to go back to the file-chooser if 'no' is selected. - -07/09/2004 -Michael Schlueter -- Removed unused source files - qsysprintf, gtkfilesel. -- Changed linux exectuable-path resolution to use '/proc/self/exe'. -- Changed 'file exists, overwrite?' prompt to default to 'no'. - -06/09/2004 -SPoG -- Fixed crash when handling duplicate shader definitions. -- Fixed crash on startup after changing game-type (sp/mp). -- Changed compute-axis-base to be more stable in degenerate cases. -Michael Schlueter -- Cleaned up loki_path stuff. -Shamus -- Added textool rotation manipulator. - -01/09/2004 -Michael Schlueter -- Changed linux installer to copy *.game files from game-packs instead of generating them. - -29/08/2004 -SPoG -- Moved doom3 shader parsing into a separate function. -- Fixed saving of visibility of yz-side and xz-front in floating-windows layout. -- Added inheritance of doom3 entityDef 'editor_* *' keys. -- Added support for doom3 entityDef 'editor_* *' keys other than 'editor_var'. -- Changed entity-inspector attributes panel to be scrollable. -- Changed shaders module to load *.mtr for doom3 instead of using shaderlist. -- Improved doom3 material parsing. -- Fixed crash loading maps containing patches with large numbers of control points. -- Changed face-selection in camera view to use polygon test. -- Changed face-selection-mode rendering in camera view to cull back-faces. -- Changed shaders module to use diffusemap on doom3 shaders with no qer_editorimage. - -28/08/2004 -SPoG -- Fixed undefined-behaviour bug causing a crash with gcc optimisation. -- Fixed opengl extension support on linux. -- Added support for half-life .fgd entity-definitions. -- Fixed loading of half-life maps with texture-names containing '{'. - -26/08/2004 -SPoG -- Updated win32 install to use gtk+-2.4.7 and gtk-wimp-0.6.2. -- Removed 'unknown model type: ""' and 'Texture load failed: ""' errors. -- Changed pivot-point calculation to use entity-origin for fixed-size entities. -- Fixed errors drawing selection-rectangle in floating-windows layout. -- Fixed shortcuts becoming disabled in floating-windows layout. -- Removed snap-to-integer on entity angle/angles/scale keys. -- Fixed dragging of doom3 brush-entities. -Michael Schlueter -- Fixed gcc compiler error and warnings. -- linux installer fixes. - -25/08/2004 -Michael Schlueter -- Changed linux build system to copy '$GAME.game/*' for installer. -- Changed linux installer to use 1.5's module set. -- Removed optimisation from linux build to fix optimiser-related crash. -- Added Doom3 support to linux installer. -SPoG -- Changed texdef export to not snap shift/rotate to integer. - -17/08/2004 -SPoG -- Fixed texture-browser height update bug. -- Changed texture-browser to show only the texture-set selected from the menu. -- Fixed bug loading quake maps. - -16/08/2004 -SPoG -- Fixed shortcuts for shift/rotate/scale-texture on patches. -- Fixed patch-inspector rows/cols combos not being cleared between selections. -- Changed entity/brush counts to use counters instead of polling every second. -- Changed archivewad module to check lump types and ignore non-miptex files. -- Added support for worldcraft/hammer half-life map format. - -15/08/2004 -SPoG -- Added doom3 md5mesh loader. -- Added support for doom3 entityDef 'model' key. -- Changed textures-menu to show/load only shaders in the form 'textures//*'. -- Fixed texture-browser height calculation bug. -- Added support for doom3 entityDef 'editor_var *' key. -- Fixed support for patchDef3 subdivision settings. - -14/08/2004 -Chronos -- Added doom3 light_radius and light_center rendering. -SPoG -- Disabled default-shaders for doom3. -- Added one-click dragging of vertices/edges/faces on brushes and patches. -- Fixed detail flag being lost on brush-clone or save-as. - -12/08/2004 -SPoG -- Fixed workzone being invalidated when a brush is deleted. -- Fixed pivot updates when switching from translate-tool to rotate-tool. -- Fixed crash in misc_model. -- Changed file_dialog to show '*.*' when pattern is not specified. -- Added undo support for patch-inspector XYZUV tweaking. -- Removed 'Apply'/'Done' buttons from patch-inspector. - -11/08/2004 -redfella -- Converted RTCW entities.def to xml format. -SPoG -- Added support for "name" key for doom3 entities. - -10/08/2004 -SPoG -- Added support for loading text files from VFS archives. - -09/08/2004 -SPoG -- Changed .map writer to always use decimal notation for floats. -- Added filtering of monster_clip/full_clip/player_clip. -- Added support for inheritance in doom3 entity-definitions. -- Fixed doom3 patchDef2 material-name import/export. - -06/08/2004 -SPoG -- Doom3 support: - - Map load/save. - - Materials parsing. - - entityDef parsing. - - Fixed brush-primitives texturing bug. - - Added texture-lock for brush-primitives texturing on all transforms. - - Added support for model/rotation/origin keys on func_ entities. -- Added DDS image module. - -03/08/2004 -SPoG -- Fixed copy/paste copying all brushes of an entity when only one is selected. -- Fixed discrete-camera-movement shortcuts becoming disabled after using freemove-camera. - -27/07/2004 -Shallow -- Converted ET entities.def to xml format. - -26/07/2004 -SPoG -- Fixed SI when not in face-selection mode. -- Changed patch-create-prefab to use current workzone. -- Changed engine attribute to be optional in game-description. - -24/07/2004 -SPoG -- Changed module server to support wildcard modules. -- Cleaned up docs/developer, added README. -- Removed old TODO. - -23/07/2004 -Shamus -- Initial version of textool. -MindLink -- Fixed const bug for vs.net 2005 compiler. - -22/07/2004 -SPoG -- Fixed copy/paste and export-selected failing to export stuff. - -19/07/2004 -SPoG -- Updated win32 setup scripts for q1 entity definitions. - -18/07/2004 -SPoG -- Updated win32 setup scripts. -- Fixed bug loading 8-bit bmp with <256 palette entries. -- Added support for loading textures from arbitrary locations. -- Changed shaders module to load notex/shadernotex from bitmaps/ in .bmp format. -- Fixed bugs in brush-primitives texdef code. - -17/07/2004 -SPoG -- Added STV:EF support to win32 installer. -- Moved hardcoded game-specific configuration stuff into .game files. - -16/07/2004 -SPoG -- Fixed crash bug in brush edge/vertex/face selection. - -15/07/2004 -SPoG -- Moved .def files from //scripts/ to ///. -- Changed entity inspector UI to be driven by entities xml. - -14/07/2004 -SPoG -- Fixed map load/save in brusb-primitives mode. -- Added files required to run in brush-primitives mode. -- Added support for changing engine-path while a map is loaded. - - -11/07/2004 -SPoG -- Changed entity inspector to support custom UI for each entity-class. - -10/07/2004 -SPoG -- Added support for experimental xml version of .def format. -- Rewrote token parser. -- Rewrote .def parser. -- Fixed failure to read show-workzone preference. -- Refactored quake3 entities module. - -03/07/2004 -SPoG -- Changed QE-style Drag tool to move as well as resize. -- Fixed shortcuts becoming disabled. -- Fixed loading file types with upper-case extensions. - -30/06/2004 -AcidDeath -- Added support for plugin submenus. - -27/06/2004 -SPoG -- Added build-menu-command editing. -- Fixed texture-object reshuffle caused by changing gamma. -- Refactored vfs/shaders/renderstates/eclass/texturemenu unrealise/realise systems. - -26/06/2004 -SPoG -- Added printf-formatting support to output streams. -- Added error/warning printing to xml parser. -- Changed build-menu xml format to allow easier editing. -- Added sample plugin. - -25/06/2004 -SPoG -- Changed paste and import-map to select pasted/imported entities and world brushes. - -24/06/2004 -SPoG -- Changed create-entity API to use eclass instead of classname. -- Changed nodes with unknown entity types to use a group-entity if the node has children. - -18/06/2004 -SPoG -- Changed image-loaders interface to use a file object instead of VFS. -- Changed model-loader interface to support in-place model reloading. -- Changed picomodel-loader module to support configuration of suppported model types in synapse.config. -- PicoModel: added support for loading models from an abstract input stream. - -14/06/2004 -SPoG -- Refactored texture browser. -- Removed GLWindow. -- Fixed mousewheel movement in camera window. - -13/06/2004 -SPoG -- Added load-entire-wad from textures menu in Quake/HL mode. -- Fixed bug with writing negative integers to .map format. -- Fixed texture-browser hide-unused to show only in-use shaders. -- Fixed texture-browser scrollbar positioning and origin-clamping. -- Fixed prompting to save unchanged new maps. -- Changed unsaved-changes message box default to "Yes, save" instead of "OK, don't save". -- Changed all message boxes to appear centrally. -- Removed minimize/maximize buttons from all message boxes. - -12/06/2004 -SPoG -- Disabled shortcut keys during drags. -- Fixed window updates for edge/vertex multi-selection. -- Added apply/cancel on enter/escape for texture-browser filter entry. -- Changed undo system to use explicit start/finish pair to specify undoable operations. -- Changed undo system to print undoable command after command completion instead of before. -- Added printing of movement parameters for translate/rotate manipulator drags. -- Changed brush-subtract to not delete the selection after subtracting. -- Fixed texture browser to not display textures if only in-use by nodes in the undo-queue. -- Fixed another workzone-update performance issue causing area-selection to be slow. -- Added code to brush build-B-Rep to handle duplicate edges. - -10/06/2004 -SPoG -- Added lazy evaluation of local->world transforms and world-space AABBs. -- Added shortcut key for translate mode, default 'W'. -- Added toolbar buttons for edge/face/vertex modes. -- Changed Escape shortcut to deselect-components if components are selected. - -02/06/2004 -SPoG -- Fixed performance bug with workzone updates not being lazily evaluated. -- Fixed brush edge-graph bug by removing degenerate winding edges. - -01/06/2004 -SPoG -- Added mode information to status bar. -- Added console feedback describing undoable commands executed. -- Fixed assertion failures on updating degenerate edge/vertex selections. -- Fixed detail brushes turning structural when clipped. - -31/05/2004 -SPoG -- Added support for more than one edge/vertex selected per brush. - -29/05/2004 -SPoG -- Refactored groupdialog - decoupled notebook from console/textures/entity pages. -- Fixed crash in patch tesselator. -- Fixed floating windows startup crash. -- Fixed null texture name for patches. - -28/05/2004 -SPoG -- Hide arrows on translate manipulator when obscured by square part. -- Workaround for main window not being brought to front when a floating window is closed. -- Fixed rendering of selected components of degenerate brush faces. -- Fixed double typedef in picomodel. -- Fixed bug in allocator stuff. -- Fixed up clipper tool button state. -- Added workzone updates when selection bounds change. -- Fixed transient setting on floating inspector windows. - -27/05/2004 -Tr3b -- Fixed gcc build errors. -SPoG -- Fixed crash bug in game selection dialog. - -26/05/2004 -SPoG -- Cleaned up project settings. -- Changed autosave/snapshots to only save modified maps. -- Refactored build menu. - -23/05/2004 -SPoG -- Fixed minor picomodel ase loader smoothing-groups bug. - -19/05/2004 -SPoG -- Allocator system improvements, fixed warnings - -18/05/2004 -SPoG -- PicoModel: added support for per-vertex smoothing-group, used in generation of normals. -- PicoModel ASE loader: added support for per-face 'MESH_SMOOTHING' id. -- PicoModel: changed normal generation code to create smooth normals across texcoord/colour discontinuities. -- Fixed cosmetic menu bug. -- Fixed file handle leak in tga loader. -- Added experimental allocator system. - -15/05/2004 -Tr3b -- Fixed gcc build errors. - -11/05/2004 -SPoG -- Fixed version.h custom build step on win32 -- Refactored preferences dialog to eliminate dependencies on other modules. -- Redesigned preferences dialog ui layout. - -06/05/2004 -SPoG -- Refactored texture browser. - -05/05/2004 -SPoG -- Upgraded win32 gtk2 version to 2.4.1. -- Migrated from GtkCombo to GtkComboBox. -- Texture browser improvements. -- Fixed malloc/free mismatch bug. - -05/05/2004 -SPoG -- Refactored surface inspector and texture browser. - -02/05/2004 -Nurail -- Added imageq2 module with support for quake2 and heretic2 texture formats: wal, m8, m32. - -30/04/2004 -SPoG -- Changed texture window not to auto-scroll when selecting faces. -- Changed surface inspector to apply shader seperately from shift/scale/rotate. -- Changed selected face tracking to use separate selection list. - -26/04/2004 -SPoG -- Added per-file change tracking - only modified (unsaved) files are saved by SaveMap(). - -18/04/2004 -SPoG -- Fixed texture-increment-matches-grid. -- Changed selecting a texture to only change the shader on the selected brushes. -- Changed 'Axial' button in surface inspector to reset the texdef for selected brushes/faces. -- Removed MAX_TEXTUREDIRS limit. - -11/04/2004 -SPoG -- OS library module added to wrap calls to rename/unlink/access/stat. -- OpenGL-view selection tests constrained to current window. -- Cleaned up OpenURL. -- Added jk2 and sof2 support to win32 installer. - -09/04/2004 -TTimo -- update the OSX setup / .info generation code - -08/04/2004 -SPoG -- Added integer quantisation for brush edge/vertex drags to fix FP-drift on planes. -TTimo -- fix for scons 0.95 -- re-enable Python >= 2.1 version check -- OSX 10.3: remove obsolete dlsym_auto_underscore (bug #920) -- OSX: disable q2 tools build (broken thread code) - -07/04/2004 -SPoG -- Moved profile.cpp into a separate static library. - -06/04/2004 -SPoG -- Refactored preferences to be more modular. -- Fixed preferences being corrupted if a crash occurs during preference saving. -- Refactored window position saving. -- Fixed bug in radio button creation in preferences dialog. - -24/03/2004 -SPoG -- Changed surface inspector to unfocus after pressing escape or return, to enable shortcuts. -- Added refresh of surface inspector for shift/scale/rotate-texdef shortcuts. -- Fixed bug causing some operations to be applied twice. - -21/03/2004 -SPoG -- Added depth-test and normalisation for translate-manipulator rendering. -- Added basic clipper-preview rendering. - -18/03/2004 -SPoG -- Added maya-style arrow-heads to translate manipulator. -- Changed square part of translate manipulator to be viewplane-oriented. -- Changed square part of translate manipulator to take priority for selection. - -15/03/2004 -SPoG -- Added recalculation of pivot-point when grid size changes. -- Changed win32 SHGetFolderPath to link with shfolder.lib instead of shell32.lib. -- Fixed failure to recover brushes from an invalid state. - -14/03/2004 -SPoG -- Improved event handling to make manipulator-dragging smoother in complex scenes. -- Refactored camera window camera-movement handling. - -06/03/2004 -SPoG -- Fixed vertex/edge undo failing to update selected-vertex position. - -29/02/2004 -SPoG -- Re-enabled next-xy-view in floating windows mode. -- Reinstated light-radius rendering. -- Added Wolfenstein support to win32 setup. - -24/02/2004 -SPoG -- Changed create-brush-prism to use correct dimension for prism radius. -- Changed freelook selection to use window-centre position. - -22/02/2004 -SPoG -- Optimised undo for adding/removing scenegraph nodes. -- Changed entity-list view to sort the tree by name. - -18/02/2004 -SPoG -- Moved default shaderlist to ///default_shaderlist.txt -- Moved user shaderlist to ////shaderlist.txt - -11/02/2004 -SPoG -- Refactored clipboard copy/paste code to allow re-use. - -10/02/2004 -SPoG -- Fixed false-positive-intersection bug in CSG subtract algorithm. - -07/02/2004 -SPoG -- SceneGraph: Refactored per-instance functionality. -- Fixed intermittent culling bug caused by bad bounding boxes. -- Fixed missing ToggleCubicClip shortcut. -- Removed modal buttons from Surface Inspector. -- Changed Surface Inspector keys: - - Escape: revert not-yet-committed values to previous state. - - Enter: commit not-yet-committed values immediatly. -- Changed Surface Inspector to update when selection changes. - -31/01/2004 -SPoG -- Cleaned up functional.h template usage with typedefs. -- Fixed autosave path. -- Added q1 component to installer. -- Added radiant_manual component to installer. -- Added q3-example-maps package to installer. - -29/01/2004 -SPoG -- Added error reporting for module system initialisation failure. -- Added MSI package creation tools in setup/win32. - note: requires MSI SDK binaries in http://zerowing.idsoftware.com/radiant-files/msi/msitools.zip -- Added initial version of scripts to build basic win32 setup. - -26/01/2004 -SPoG -- Added storing EnginePath for each game in local.pref. -- Added EnginePath editing to prefs dialog. -- Added vfs shutdown/init when gamename changes. -- Added vfs shutdown/init when enginepath changes. - -25/01/2004 -SPoG -- Fixed filtering updates. -- Moved default bsp menu to //default_build_menu.xml -- Moved user bsp menu to ///build_menu.xml -- Moved synapse.config to //synapse.config -- Moved game-specific .xlink files to //*.xlink - -25/01/2004 -SPoG -- Redesigned filter system: - - Filtered status updated when filterable attributes change. - - Supports per-brush-face filtering. -- Removed long-dead project-settings stuff: - - Moved gamemode and gamename storage into local.pref temporarily. - - Moved bsp commands over to a new format, disabled gui editing for now. - -20/01/2004 -SPoG -- Changed win32 Application Data path lookup to use win32 API instead of getenv. - -14/01/2004 -SPoG -- Fixed main menu mnemonics. -- Fixed crash on exit after viewing pointfile. - -13/01/2004 -SPoG -- Fixed not always resetting -component-mode when selection is cleared. - -11/01/2004 -Tr3B -- Added parse/write support for BrushDef3 and PatchDef3. - Requires editing synapse.config to enable. -SPoG -- Rearranged menus: - File = new/open/import/export - Edit = manipulate scene hierarchy and selection - View = toggle entityinspector/entitylist/surfaceinspector/camera/xy - edit camera/xy parameters - filters/hideshow/region - Modify = transform scene elements - Build = bsp menu -- Fixed Brush-Primitives support: - Requires editing synapse.config to enable. - Supports load/save of BP mapfiles, and editing BP texdefs in surface inspector - (Not yet possible to convert between formats). - -15/12/2003 -SPoG -- Changed user-prefs to be stored in user-profile directory on win32. - -14/12/2003 -SPoG -- Fixed entitylist window visibility tracking. -- Implemented find/replace-shader for patches. -- Changed get-texture-from-selected to update find/replace-shader dialog. -- Implemented reparent-selected for more than one selected node. -- Added checks to stop assignment of invalid texture names. -- Fixed uninitialised texture-compression setting. -- Fixed bsp menu. - -------- spog_branch merged to trunk - -10/12/2003 -SPoG -- Ported imagehl module. -- Ported imagepng module. - -03/12/2003 -SPoG -- Changed brush winding generation to use use double precision planes. -- Fixed tracking of modifier key state. - -29/11/2003 -SPoG -- Replaced mathlib with c++ vector/matrix library. -- Added expression-templates for common vector/matrix operations. - -21/11/2003 -SPoG -- Refactored component-selection stuff. -- Ported m4x4_t library to c++ Matrix4. - -16/11/2003 -SPoG -- Changed shortcuts.ini to be written automatically. -- Moved more prefs into specific modules. -- Changed c++ NULL usage to 0 for maximum portability. - -11/11/2003 -SPoG -- #include cleanup. -- Added debug output/assert for module initialisation. - -09/11/2003 -SPoG -- Refactored status bar stuff. -- Refactored window updates to use closures. -- General cleanup and refactoring. - -08/11/2003 -SPoG -- Increased priority of window redraw events. -- Ported model module to new module system. - -07/11/2003 -SPoG -- Refactored window updates. - -05/11/2003 -SPoG -- Changed menubar/toolbars to be non-detachable. -- Fixed empty-undos created when left-clicking in XY window. -- Refactored camera modelview/projection matrix updates. -- Moved application-specific code out of mainframe.cpp. -- Reinstated brush/entity count in statusbar. - -04/11/2003 -SPoG -- Reinstated instant status-bar updates. - -30/10/2003 -SPoG -- Fixed crosshair cursor in clipper mode. - -29/10/2003 -SPoG -- Changed camera to maintain valid projection/modelview matrices. -- Moved manipulator-transform update from frustum class to selection system. -- Removed frame-rate dependency in 3d-window freelook. - -27/10/2003 -SPoG -- Smoothed out xy-window mouse-chasing. -- Changed mouse-chasing to occur 16 pixels inside the window edges. -- Changed xy-window to maintain valid projection/modelview matrices. -- Fixed invalid workzone generated when deselecting with no selection. - -26/10/2003 -SPoG -- Ported changes from trunk between rev 3818 and rev 4036. - -25/10/2003 -SPoG -- Refactored xy-window mouse event handling. - -22/10/2003 -SPoG -- Fixed freelook focus-out event. -- Changed selection mouse event handling to use modifiers on button-release. - -21/10/2003 -SPoG -- Refactored all mouse event handling for camera window. -- Changed menus/toolbars/accelerators to use anonymous closures. - -20/10/2003 -SPoG -- Fixed get-pointer-in-screen-coordinates on win32. -- Changed patch prefs to use preference-system module. -- Fixed selection of side-on faces. -- Changed brush rendering to avoid glPushClientAttrib - workaround for ATI driver issue. - -19/10/2003 -SPoG -- Changed VFS directory initialisation to occur after module initialisation. -- Changed load-preferences to occur after module initialisation. -- Added preference-system module. -- Changed undo prefs to use preference-system module. -- Restored splash screen with non-intrusive behaviour. -- Cleaned up main-toolbar creation. -- Fixed floating windows behaviour when main window is minimised. -- Changed shader-list parsing to use new script tokeniser. -- Changed deprecated code using GtkPixmap to use GtkImage. -- Removed bitmap-loading from core. -- Removed pc-speaker beep on map-save. - -17/10/2003 -SPoG -- Fixed crash when trying to undo on an empty undo queue. -- Refactored gtkdlgs, using helper functions to create common widgets. -- Changed Dialog class to use std::list for data. - -13/10/2003 -SPoG -- Refactored entity inspector. -- Removed miscellaneous unused functions. -- Refactored qe3 header. -- Moved texture-window preferences into texwindow.cpp. - -12/10/2003 -SPoG -- Moved layout-mode dependant code into main-frame creation. -- Replaced prefs system with new import/export system. -- Fixed gcc3.3 build errors. - -11/10/2003 -SPoG -- Moved unnecessary methods from MainFrame into free functions. -- Removed unsupported toolbar buttons and menu items. -- Changed misc->gamma to not require restart. -- Fixed unmaximised window-size when loading main window maximised. -- Fixed saving of rotate increment preference. - -10/10/2003 -SPoG -- Fixed keyboard shortcuts intercepting input to texture-subsets text-entry. - -09/10/2003 -SPoG -- Fixed gcc3 build errors, compiled and tested on linux. - -08/10/2003 -SPoG -- Fixed brush snap-to-grid creating huge coordinate values. -- Fixed minor bug in selection menu. - -07/10/2003 -SPoG -- Cleaned up MainFrame. -- Added quantisation of plane pts when dragging. -- Fixed create-empty-brush bug. - -06/10/2003 -SPoG -- Moved control of camera keyboard-accelerators into camera window module. - -05/10/2003 -SPoG -- Separated keyboard-accelerators from menu items, using functors. -- Completed factoring out HandleCommand. - -04/10/2003 -SPoG -- Changed 4-way-split mode to automatically reposition separators when window size changes. -- Fixed gtk error in floating-entity/textures/console window. -- Fixed position of console horizontal pane separator. - -03/10/2003 -SPoG -- Work-in-progress factoring out HandleCommand. - -02/10/2003 -SPoG -- Fixed pink icons on main window on win32. -- Replaced g_bIgnoreCommands with signal block/unblock. -- Refactored MainFrame startup. - -01/10/2003 -SPoG -- Fixed entity-window redraw on selection change. -- Moved control over VFS init/shutdown to module system. -- Fixed failure to release translucency render-states. -- Added support for realise/unrealise of all opengl texture objects. -- Refactored startup/shutdown logic. - Changed quit commands to do nothing but call gtk_main_quit(). - Added code after gtk_main() to destroy stuff. -- Changed 25ms timeout-handler to an idle-handler for window updates. - (reduces redraw-request response time on fast machines) -- Moved gl-shutdown control to glwidget. - Textures are realised/unrealised when the shared context is created/destroyed. -- Fixed lack of a valid gl context when unrealising gl textures. - -30/09/2003 -SPoG -- Added support for translucent entity rendering. - -29/09/2003 -SPoG -- Changed all global modules to use GlobalModule helper templates. -- Ported qgl.c to c++. -- Changed win32 project to dynamic-link with opengl32.lib. - -28/09/2003 -SPoG -- Added new experimental xml preference import/export system. -- Refactored dialog base class: - Moved common dialog-element-creation code into helper functions. - Changed UpdateData to use per-element callback functions. -- Refactored preferences dialog. - -26/09/2003 -SPoG -- Reversed winding order for circle primitives. - -25/09/2003 -SPoG -- Fixed slow selection response in large maps. - -21/09/2003 -SPoG -- Added sharing of global modules within a client. -- Added quake map module and wal image module. -- Ported mip image module and hlw image module. -- Cleaned up imagehl module. -- Fixed crash in pcx image module. -- Rewrote md3 model module. -- Ported mdl, md2 and mdc model modules. -- Added filtering of q1/q2 clip brushes. -- Added ati-crash-workaround rendering path. -- Upgraded to gtk+-2.2.4 on win32: - Fixed capslock affecting shortcut-keys. -- Upgraded to gtkglext-1.0.4 on win32. -- Fixed copy/paste. -- Added shortcut-key support to entity treeview. - -17/09/2003 -SPoG -- Fixed failure to call vfsFreeFile on an empty buffer. -- Fixed calling convention for dlls in new module system. -- Changed map.cpp to support maps without a worldspawn entity. -- Fixed crash on attempting to clone a map root. -- Added filter-update calls after loading or cloning stuff. -- Fixed reference cache failing to save a file. - -16/09/2003 -SPoG -- Refactored client-side module system code for direct module access. -- Changed shaders, vfs, model, brush, patch and entity module interfaces - to use abstract base class. -- Removed unused functions from shaders and vfs interfaces. - -15/09/2003 -SPoG -- Removed synapse dependencies for win32 makefiles. -- Added find-first-module-of-type helper function. - -14/09/2003 -SPoG -- Added new lightweight module system: - Initialises each module the first time it is requested. - Does not allow configurations with cyclic runtime dependencies. - Provides templates for simple type-safe client-side implementation. - Requires no client-side linkage. -- Split radiant API into multiple APIs: - core, textures, scenegraph, selection, renderstate, filters, filetypes. -- Ported radiant, core, mapq3, mapxml, md3model, entity, shaders, image, - vfspk3, archivewad, archivepak, archivezip to new module system. - -11/09/2003 -SPoG -- Removed edge and vertex integer-snapping during selection. - -10/09/2003 -SPoG -- Replaced map in referencecache.cpp with a hashtable. -- Changed ReferenceCache interface to take a path string, - which can be either absolute or relative. - -08/09/2003 -SPoG -- Cleaned up qertypes.h - split into multiple files. -- Moved texdef stuff into itexdef.h. -- Fixed shutdown destruction order bug. - -07/09/2003 -SPoG -- Refactored texwindow.cpp. - Moved texture management code into textures.cpp. - Added textures api. - Replaced globals from texwindow.h with accessor functions. -- Cleaned up shaders module. - Removed color-shader stuff. - Rewrote shader-activation logic to use textures API. - Removed appshaders API. -- Refactored shutdown logic. - Moved non-mainframe shutdown stuff into Radiant_Shutdown(). - Added deferred render-state realisation. -- Fixed failure to create gl contexts in 16-bit mode for latest nvidia drivers. -- Changed hashtable template to use traits parameter - for case-insensitive hasher and keyequal functions. -- Removed unused functions from qerplugin API. - -02/09/2003 -SPoG -- Refactored code to remove global-object accesses: - Passing global objects as parameters to functions. -- Refactored texwindow. -- Moved synapse server out of pluginmanager. - Changed pluginmanager to handle nothing but IPlugin stuff. - -01/09/2003 -SPoG -- Refactored scenelib.h, split into multiple files. -- Refactored #includes related to scenelib.h. -- Refactored preferences for xywindow and camwindow. -- Refactored references to g_pParentWnd in xywindow and camwindow. - -30/08/2003 -SPoG -- Ported changes from trunk since 17/08/2003. -- Ported all changes from bug800-spog_branch (vfs rewrite and q1 support). - -29/08/2003 -SPoG -- Refactored component-selection stuff. -- Fixed selection-tracking bug in patches. - -28/08/2003 -SPoG -- Added support for line-strips to Selectors. -- Fixed selection for entity treeview. -- Refactored external-resource loading. - -20/08/2003 -SPoG -- Fixed snap-to-grid in edge and vertex modes. -- Added a default model to use when a model load fails. - -19/08/2003 -SPoG -- Changed snap-to-grid to vastly reduce the possibility of creating an invalid plane. - -17/08/2003 -SPoG -- Ported changes from trunk since 01/08/2003. - -12/08/2003 -SPoG -- Changed entity key/value tracking to only track keys already added to the entity. -- Fixed bug causing undo system to track scene changes during a queue-flush operation. - -12/08/2003 -SPoG -- Fixed bug in project settings bsp-commands display. -- Fixed empty undos being created by rotation buttons. -- Fixed rotation pivot for rotation buttons. - -09/08/2003 -SPoG -- Added property svn:eol-style=native to all text files. -- Added property evn:eol-style=CRLF to all dsp and dsw files. -- Partially ported bobtoolz to use new spog_branch module APIs. -- Removed Sys_UpdateScene. -- Added Map_Name() for access to currentmap variable. -- Added initial drag-n-drop support for graph tree-model. - -01/08/2003 -SPoG -- Fixed uninitialised refcount in entity key class. -- Fixed memory leak in shader parsing. -- Added reference-counting holder for worldspawn node. -- Moved string class and utilities into a new header in libs dir. -- Fixed external-file-resource cache to use case-insensitive name compare on win32. -- Fixed shaders to use case-insensitive name compare. -- Fixed shader module to display SHADER_NOT_FOUND when appropriate. -- Changed the default texture name to "NULL" instead of SHADER_NOT_FOUND. -- Changed move-into-entity to perform parent-selection-to-last-selected-node. -- Added a new implementation of GtkTreeModel operating directly on the scenegraph. -- Fixed disable-screen-updates to queue update requests instead of ignoring them. -- Merged from trunk (tag head-cvs2svn-2). - -22/07/2003 -SPoG -- Changed scale/flip-selection to use the manipulator as a pivot point. -- Added OnShutdown callback for CSynapseClient, used in entity module. -- Fixed console updates when loading maps/models. - -20/07/2003 -SPoG -- Added renderer support for qer_alphatest and qer_cull. -- Merged 'picomodule' module into 'model' module. -- Added rendering of area-selection rectangle. - -19/07/2003 -SPoG -- Merged from trunk. - -18/07/2003 -SPoG -- Disabled deleting classname key in entity inspector window. -- Cleaned up some stuff in selection system. -- Added basic versions of std::mem_fun and std::bind1st to function-object library. - -10/07/2003 -SPoG -- Implemented connect-entities. - -09/07/2003 -SPoG -- Completed local-space rotation manipulator. -- Fixed cloning objects within a misc_model subgraph. -- Fixed crash bug in loading certain models. - -06/07/2003 -SPoG -- Added function-object library header, similar to boost::function. -- Changed undo system to improve performance. -- Refactored entity inspector implementation. - -22/06/2003 -SPoG -- Refactored selection observing stuff. -- Changed shader parsing to use new tokeniser. -- Changed implementation of entities to use generic container. -- Refactored entity wrapper system. -- Fixed undo on delete/reset entity keys. - -21/06/2003 -SPoG -- Added rendering of target/targetname connection lines. -- Moved entity and eclass stuff out of qertypes.h into ientity and ieclass. -- Refactored entity_t to hide it behind Entity interface. -- Removed global project settings entity. -- Cleaned up bsp-command editing in project settings dialog. - -17/06/2003 -SPoG -- Fixed back-face-culling for selections by working in screen-space. - -16/06/2003 -SPoG -- Added workaround for nvidia driver opengl vertex arrays bug. - -15/06/2003 -SPoG -- Refactored Patch implementation. -- Refactored scene graph system to allow multiple graph instances. - -13/06/2003 -SPoG -- Added snap-selected-components-to-grid for faces edges and vertices. - -11/06/2003 -SPoG -- Improved normal-quantisation code. - -10/06/2003 -SPoG -- Changed renderer vertex types to be struct instead of typedef'd array. -- Added experimental quantisation of normals. - -05/06/2003 -SPoG -- Fixed intermittent crash in face-fit-texture. -- Changed patch rendering to display components only in vertex mode. - -02/06/2003 -SPoG -- Added nameable interface for scene graph nodes. -- Fixed undo for set-detail and set-structural. -- Added rendering of arrow for angled entities. - -01/06/2003 -SPoG -- Fixed handling of invalid planes during brush b-rep build. -- Refactored brush copy-construction/assignment. -- Fixed lack of rebuild after removing empty faces. -- Added lightjunior entity display. -- Fixed display of spawnflags/info for selected entity. -- Fixed update of entity window on setting spawnflags. -- Fixed botclip filtering. -- Fixed uninitialised alpha channel on jpg images by ignoring alpha. - -31/05/2003 -SPoG -- Cleaned up undo calls in brush and patch implementation. -- Changed brush implementation to defer rebuilds until needed. -- Fixed undo for find/replace shader. -- Refactored brush implementation, removed empty-face list. -- Fixed crash on loading unrecognised entities containing brushes. -- Fixed crashes in renderer caused by state-stack underflow. -- Fixed handling of invalid and duplicate planes during brush editing. -- Fixed failure to save brush faces during save-as. -- Refactored brush data members. - -28/05/2003 -SPoG -- Fixed crash on selecting stuff from entity list window. - -27/05/2003 -SPoG -- Fixed window title after save-as. - -22/05/2003 -SPoG -- Refactored selection system interface slightly. -- Removed old brushwrapper stuff. -- Fixed clipper-split-selection to keep both parts selected. - -21/05/2003 -SPoG -- Added select-faces-by-shader. -- Fixed find/replace-shader. - -19/05/2003 -SPoG -- Fixed rotation on misc_model. - -13/05/2003 -SPoG -- Fixed lack of undo on create-n-sided-brush. - -29/04/2003 -SPoG -- Fixed per-face find/replace and per-face nudge rotation. - -25/04/2003 -SPoG -- Fixed find-brush. -- Changed rotation buttons to use perfect precision for 90-degree rotations. - -24/04/2003 -SPoG -- Added find-dir-for-relative-filename and find-dir-for-absolute-filename to vfs. -- Changed resource manager to handle per-mod resources using vfs. -- Changed resource manager to allow resources with absolute paths. -- Fixed selection-test behaving like an ellipse instead of a rectangle. - -23/04/2003 -SPoG -- Changed selection test to choose closest-to-cursor over closest-to-camera. - -22/04/2003 -SPoG -- Fixed reference counting on shaders loaded from a texture directory. -- Fixed show-in-use and show-all shaders. -- Fixed undo for patch-set-shader. -- Changed shaders module to use STL map container instead of CShaderArray. -- Fixed SelectAllOfType for entities and patches. -- Cleaned up unused functions in shaders API. -- Decoupled selecting a texture in texture window from applying a texture to selection. - -21/04/2003 -SPoG -- Fixed memory leaks in image loaders, texdef_t, csg subtract, picomodel module. -- Fixed uninitialised memory references in renderer, texdef_t, eclass loader, undo system. -- Refactored tga loader. -- Cleaned up image module, enabled pcx and bmp loaders. - -17/04/2003 -SPoG -- Fixed shift-texture on selected brush faces. -- Changed brush b-rep algorithm to have higher tolerance for similar planes. -- Changed brush b-rep algorithm to always produce a valid connectivity graph. -- Added setting/getting shader for patches. - -16/04/2003 -SPoG -- Fixed tracking of in-use shaders (though undo queue still keeps shader references). -- Changed brush faces to store state in undo-system cleanly. -- Fixed flush & reload shaders and sleep/wake. -- Ensured that shaders are never leaked. -- Fixed bool conversion warnings. - -15/04/2003 -SPoG -- Added clamping of planepts on export to nearest 65536th of 1 unit. -- Changed m4x4 rotation functions to use double-precision for angles in radians. -- Changed m4x4 quaternion rotation to use double-precision internally. -- Changed float printing to use %g instead of %f (strips trailing zeros). - -13/04/2003 -SPoG -- Fixed brush import failing to update bounding boxes. - -11/04/2003 -SPoG -- Refactored Brush class into Brush, BrushInstance and BrushNode. -- Fixed various flaws stopping brush b-rep algorithm from being 100% reliable. - -02/04/2003 -SPoG -- Changed manipulator to move to position of selected brush components. - -01/04/2003 -SPoG -- Fixed xml parser failing to resolve predefined entities. - -31/03/2003 -SPoG -- Fixed asserts in brush manipulation when creating invalid brushes. -- Removed automatic update of current texdef. -- Added Get Texture and Set Texture to textures menu. - -29/03/2003 -SPoG -- Fixed array template failing to free zero-sized allocations. -- Changed clipper mode to behave as a component-editing-mode. -- Removed right-click-to-drop-clip-point - use X and leftclick instead. - -28/03/2003 -SPoG -- Changed scene graph to sort objects in ascending order of creation time. - -27/03/2003 -SPoG -- Fixed bug in clone-selection causing only first selected brush to be cloned. -- Optimised select-all for brush/patch components. -- Changed edge/face/vertex toggles to toggle correctly. - -26/03/2003 -SPoG -- Removed win32/x dependencies from gl interface. -- Removed win32/glib dependencies from core interface. -- Replaced void* in gtk helper functions with forward-declared GtkWidget. -- Changed gtk helper functions to return enumerated values instead of win32 IDOK. -- Removed WINAPI macro for __stdcall from all interfaces. -- Removed unnecessary dependencies from core stdafx/qe3 header. - -25/03/2003 -SPoG -- Changed class-level render states to be static for Brush and Patch. -- Refactored brush implementation - breaking it up into smaller parts. -- Added refcounted ptr template to track refcounts. -- Fixed refcount bug introduced by new clone-selection. -- Fixed warnings in brush implementation. -- Cleaned up plugin interface header inclusion. - -24/03/2003 -SPoG -- Fixed crash on building unbounded brushes in release build. -- Changed assertion failures to be non-fatal in release build. -- Moved OS-specific gl headers into separate files. -- Moved app-shaders interface into a separate file. -- Cleaned up dependencies for brush implementation. - -23/03/2003 -SPoG -- Added per-instance selection of patch vertices. -- Fixed per-instance vertex selection rendering on multiple instances. -- Refactored patch/brush render code. -- Changed manipulator transforms to convert to local space before applying. -- Fixed selection test for picomodule meshes. -- Fixed selection test winding order for triangles. -- Fixed update of window title on new-map and load-map. -- Changed selection to work with exactly side-on faces. -- Refactored instance implementation to reduce code bloat. -- Fixed map export always exporting root. - -21/03/2003 -SPoG -- Fixed external resource tracking to preserve uppercase characters in names. -- Changed clone-selection to not use global copy/paste. - -20/03/2003 -SPoG -- Changed map-save to save all saveable files that the map references. - -16/03/2003 -SPoG -- Moved hashtable and hashfunc into libs. -- Cleaned up renderer interface and selection interface. -- Refactored frustum testing class. - -12/03/2003 -SPoG -- Moved winding-specific stuff from brush obj to winding obj. -- Refactored filter subsystem to remove dependency on entity/brush/patch. - -07/03/2003 -SPoG -- Fixed crash when clicking cancel from patch cap-dialog. -- Changed selection tests to ignore back-facing faces. - -05/03/2003 -SPoG -- Fixed failure to release cloned scene graph nodes. -- Fixed selection manager failing to release render states. -- Fixed eclass system failing to release render states. - -04/03/2003 -SPoG -- Fixed writing-past-end of vertex arrays in brush rendering. -- Fixed releasing data stored in undo system when deleting undoables. -- Fixed crash in misc_model when model fails to load. -- Fixed undo for clone/rotate/flip/nudge/set-texture operations. -- Cleaned up surface dialog. - -01/03/2003 -SPoG -- Changed clipper split-selection to keep result selected. -- Cleaned up and finalised picomodule, adding to cvs. - -28/02/2003 -SPoG -- Cleaned up entity list window. -- Fixed crash on freeing a map while entity list node is selected. -- Fixed crash on clone/copy of externally referenced brushes. -- Added multiple-selection support to entity list. -- Added updating entity list selection display on selection changes. - -26/02/2003 -SPoG -- Added stl_warnings include. -- Fixed tracking of map-modified-since-last-saved. - -24/02/2003 -SPoG -- Fixed missing map-release when map-load fails. -- Changed map-rename (save-as) to flush undo queue. -- Fixed bug in exporting selections. - -23/02/2003 -SPoG -- Fixed redo on changing misc_model "model" key. - -22/02/2003 -SPoG -- Changed undo interface to factor out global undo system. - -21/02/2003 -SPoG -- Started cleaning up Map subsystem. - -20/02/2003 -SPoG -- Added 'clone subgraph' feature to core, using direct xml import/export. -- Added 'save' feature to reference cache. -- Added scope timer object. -- Changed scene graph interface to allow setting scene root. -- Changed core to use reference cache to track current map. -- Removed mapmodel module. -- Fixed relative paths for loading maps as misc_model. - -19/02/2003 -SPoG -- Changed model/map modules to register their file types on load. -- Added map module manager to support unlimited map loader modules. - -18/02/2003 -SPoG -- Changed vertex buffer template to support resizing. -- Changed vertex buffer search algorithm to iterate instead of recurse. - -17/02/2003 -SPoG -- Fixed sorting bug with render-states. -- Fixed colour state when disabling gl_color_array. -- Fixed unterminated loop in scenegraph traversal. -- Fixed freeing project entity twice on shutdown (infinite loop). -- Fixed failing to destroy the scene graph on exit (oops). - -07/02/2003 -SPoG -- Added updating current texdef when a face is selected. -- Fixed crash when creating a brush with duplicate planes. - -06/02/2003 -SPoG -- Fixed various issues with 'save region'. -- Changed default current texdef to use game-specific scale. -- Changed brush creation to use current texdef. -- Changed clipper to use current texdef. -- Fixed bug in selection counting for patch control points. - -05/02/2003 -SPoG -- Fixed reversed solid-selection-outline preference. -- Finished factoring out face_t. -- Added script token writer interface for map export. -- Changed map export interface to use script token writer. - -04/02/2003 -SPoG -- Added depth-buffer-write enable/disable feature to renderer. -- Changed Pointfile class to use renderer. -- Continued factoring out face_t. - -03/02/2003 -SPoG -- Fixed temporary objects leaving dangling references in the undo system. -- Changed import-map to not modify existing selection. - -02/02/2003 -SPoG -- Fixed frustum culling for transformed nodes. -- Fixed hide/filter/region to work independently. -- Added highlighting of selected brush faces in component mode. -- Fixed bug detecting thin area-selection if dragged down or left. -- Renamed brush_type to Brush. -- Renamed face_type to Face. -- Started factoring out face_t. - -01/02/2003 -SPoG -- Improved edge and vertex manipulation. -- Removed unnecessary graph traversals for rendering/selection. - -31/01/2003 -SPoG -- Merged changes since last merge from merge-1_2_10-post to spog_branch. -- Merged changes since last merge from HEAD to spog_branch. -- Tagged HEAD after merging as 'merge-spog_branch-post'. -- Added walker to merge sibling worldspawns. -- Merged changes to Construct for PPC from trunk. -- Fixed over-enthusiastic worldspawn merging. -- Fixed misc_model "angle" key setting pitch instead of yaw. -- Fixed entity set-key-value changing scene-graph topology. - -30/01/2003 -SPoG -- Added subgraph traversal feature to scenegraph traversal. - -29/01/2003 -SPoG -- Changed scene graph implementation to allow nested traversals. - -28/01/2003 -SPoG -- Fixed angles key order for misc_model. - -27/01/2003 -SPoG -- Fixed typo causing set-texture-of-selection to behave incorrectly. - -26/01/2003 -SPoG -- Replaced all tabs with spaces in CHANGES. -- Fixed entity bounds updates for 'light'. -- Fixed code that doesn't conform to c++ standard as enforced by gcc. - -24/01/2003 -SPoG -- Added missing file: icharstream.h. -- Fixed bug with synchronisation of brush-face instance data. -- Added .map format import/export interfaces. -- Removed last remnants of IBrush. -- Removed IPatch. -- Moved walkers defined in in mainframe.cpp to appropriate places. - -23/01/2003 -SPoG -- Changed scenegraph traversals to use a compiled graph. - -20/01/2003 -SPoG -- Changed selection interface to hide per-instance data. -- Added streaming tokeniser for .map format. -- Changed mapq3 module to use streaming tokeniser. -- Added xml stream interface for input and output. -- Added xml stream parser based on libxml2 SAX. -- Changed mapxml module to use xml stream input. -- Changed brush and patch to use xml stream input. -- Added xml stream writer. -- Changed mapxml module to use stream output. -- Changed brush and patch to use xml stream output. - - -16/01/2003 -SPoG -- Disabled pivot updates while selection is being manipulated. -- Changed pivot calculation to use instanced world-bounding-box. -- Fixed crash bug in PositionView. - -14/01/2003 -SPoG -- Merged with branch merge-1_2_10-post at tag spog_merge_merge-1_2_10-post -- Removed 10k+ lines of unused #if 0 code. -- Removed unused declarations in qe3.h. -- Removed brush and face types from qertypes.h. -- Removed plugin API stuff dependant on brush type. -- Added per-instance selection for brush faces. - -08/01/2003 -SPoG -- Added selection counters for primitive/component modes. -- Added face-drag mode (default shortcut key = F). -- Added face-centre-point rendering/selection/editing. - -07/01/2003 -SPoG -- Changed selection to work per-instance. - -06/01/2003 -SPoG -- Changed selector interface to allow per-entity selection tests. - -06/12/2002 -SPoG -- Added selection-test and selector objects to clean up selection system. -- Unified key modifiers for selection in both primitive and component modes. -- Added mapmodel module to load .map and .xmap as misc_model. - -02/12/2002 -SPoG -- Added debug rendering of a selection test. -- Fixed bugs in triangle/line clipper, making selection work properly. -- Refactored selection system interface. -- Added undo for texture nudge. -- Fixed minor render-state bug. - -29/11/2002 -SPoG -- Optimised wireframe drawing of brushes with back-face culling. -- Optimised brush-winding generation. -- Changed winding generation to be more robust with large world extents. -- Fixed crashes with unbounded-face and degenerate-edge cases. - -20/11/2002 -SPoG -- Completed rotation manipulator. -- Added translation manipulator for the default editing mode. -- Changed XY mouse-chaser speed to depend on distance mouse moved outside window. - -15/11/2002 -SPoG -- Added initial version of maya-style manipulators - rotation manipulator. - -07/11/2002 -SPoG -- Fixed false asserts in Brush ConstructPrefab. -- Undo system optimisation - uses binary-sorted container to speed up finding already-added objects. -- Fixed crash when transforming objects which don't support edit_interface. -- Fixed clone command to nudge the selection after cloning. -- Fixed clipper to remove brushes that are completely behind the clip plane. - -06/11/2002 -SPoG -- Brushes: cleaned up per-face operations to use face visitor pattern. -- Fixed setting brush face texdef, with fully functioning undo on individual brush faces. - -04/11/2002 -SPoG -- Refactored renderer to two objects, camera and XY renderer - XY uses entity shaders. -- Experimental pivot object.. work-in-progress. -- Modified scene-graph instance-caching to maintain multiple instances within nodes. -- Fixed undo bug, deleting a void* doesn't call the destructor. -- Rewrote filters system to work with scene graph system. -- Cleaned up quake entity module to provide same functionality as before. -- Refactored render-state cache to use generic hashtable and reference-cache templates. - -19/10/2002 -SPoG - spog_branch - experimental - work-in-progress -- added scene graph library: defines interfaces, generic graph node types, - re-usable systems for traversals, traversal paths, node containers, - multiple-instance caching of world-space-transforms/bounding-volumes/visibility. -- added scene graph traversals to replace all traversals of 'active_brushes', - 'selected_brushes', 'filtered_brushes' and 'entities' linked-lists. -- added view module: view-volume-culling system acting on the scene graph, - uses scene heirarchy to minimise culling tests per frame. -- added opengl-state module: sorts opengl-state objects (shaders) to minimise - opengl state changes during rendering. -- added renderer module: culls objects outside the view volume, - gathers non-culled renderable objects from the scene graph, - keeps track of state during traversal, adds renderable objects to correct opengl-state. -- added selection module: sets view volume to the selection box/ray, culls - objects outside the view volume, gathers non-culled selectable objects - from the scene graph (entity/primitive/component), - selects gathered objects (select/toggle/cycle) or moves things if already-selected. -- added patch module: encapsulates a patch as a scene graph node, - optimised patch tesselation. -- added brush module: encapsulates a brush as a scene graph node, - adapts multiple-brush operations to use the scene graph. -- adapted entity module: encapsulates an entity as a scene graph node/subtree, - shares common code between different visualised entity types. -- adapted model module: encapsulates a model as a scene graph node/subtree. -- added undo module: completely new compact infinite-undo-system, - operates on undoable objects, uses minimal-state data to store objects, - uses refcounting to undo "deleted" objects. - -TODO: cleanup: many simple things are still broken or not functioning in the right way.. -see !\todo items in the code (not all are documented yet though). -Selection module probably needs refactoring some more - perhaps split off the move-already-selected stuff. -The dependencies are still pretty bad.. need to refactor stdafx.h/qertypes.h. -Some of the above modules are not really modules, they're static-linked to the core, but could easily be dynamic-linked. -The interfaces to brushes and entities still expose brush_t and entity_t for backwards-compatibility. -NOTE: some todos are #if 0 because their functionality is (or will be) replaced by the new systems. - ------- branch point - spog_branch - -30/08/2003 -SPoG -- Ported changes from trunk. - -17/08/2003 -SPoG -- Ported changes from trunk. -- Added quake pack to win32 setup scripts. -- Fixed crash in RunBsp. - -17/05/2003 -SPoG -- Renamed stream interfaces with C and I prefix. -- Shoehorned bytestream into idatastream. -- Moved member classes out of IArchive, replaced with member typedefs. -- Renamed filesystem, path, dynamic string, file input stream with C and I prefix. -- Documented filesystem, path, dynamic string, file input stream. -- Cleaned up game-specific encapsulation classes a little. - -16/05/2003 -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=815 - found out about string_t that slept through my reviews - -Updated list of broken stuff on this branch: - -- include/bytestream.h: remove this file, extend idatastream.h header -from the code conventions: - include/ directory: - This directory is holding the API header files for the synapse modules (plus a few build control and version related headers) - All headers that describe synapse APIs should start with an i: ishader.h igl.h - - The few files in include/ that don't start with a lowercase i are specific files for build control and configuration. - Regular developement never creates non i-prefixed files in include/ - -the merge with IDataStream goes like this (note the corrected class names): -class IInputStream -class IOutputStream - -class IDataStream : public IInputStream, IOutputStream - -class ISeekableStream -class ISeekableInputStream : public IInputStream, public ISeekableStream -class ISeekableOutputStream : public IOutputStream, public ISeekableStream - -typedef unsigned int size_type; goes away, use size_t - -- include/iarchive.h - -renamed VisitorFunc to IArchiveVisitor -move it out of IArchive class (keep it in iarchive.h though) -from code conventions: - Don't declare classes inside classes. Makes the code harder to read and isn't useful to anything. - -- remove libs/bytestreamutils.h -put that functionality into the IStream stuff / idatastream.h stuff -anything you retrieve from an IStream should be endian-correct - -- libs/filestream.h -I'd rather see a header without embedded code, and a .cpp file for it - -- libs/fs_filesystem.h libs/fs_path.h -those totally lack documentation about what they are doing -same as above. way too much embedded code. makes things harder to maintain. implement in a .cpp -and as usual, name the classes correctly, C and I prefixes - -- gamespecific_t: rename correctly to CGameSpecific -I like the idea of gathering all hardocded game-specific behaviours inside one same class. -But is it really the topic of bug800? - -- gamespecific_executable_t: rename correctly to CGameSpecificExecutable -shouldn't this be merged with CGameSpecific? - -12/05/2003 -SPoG -- Fixed win32 build error (win32 has no ). -- Added dir_good() check to handle failure of dir_open() in posix DIR wrapper. -- Renamed dynamic_string_t and path_t to DynamicString and UnixPath respectively. -- Removed unnecessary use of 'inline' and 'virtual' keywords in class definitions (bad habit). -- Documented archive interface. - -09/05/2003 -TTimo -- some easy fixes to get it to startup on Linux -- tagging the current source as bug800-spog, preparing rollback - - -SPoG -- Added an implementation of IArchive to do OS filesystem access. -- Changed vfspk3 to use above implementation for OS filesystem access. -- Added const qualifiers to vfsGetFullPath and everything dependant on it. -- Changed vfsGetFileList to use "*" to indicate all-files instead of a NULL pointer. -- Extended IArchive interface to allow for extra filesystem functionality. - Added method to check if a file exists quickly. - Added method to traverse the filesystem with control on start-dir and depth of recursion. -- Defined implementation requirements for IArchive. - An archive contains a heirarchy of directories and files, and may contain empty directories. - An archive can be traversed in directory order. - Directories can be distinguished from files during a traversal. - Directory paths will always end with a separator. - File entries can be opened as an IArchiveFile. - IArchiveFile provides a simple non-seekable input stream which can only be read forwards. - Any number of files may be opened and read from an archive simultaneously. - An archive may be released while one or more files are still open, the files will remain valid until released. -- Changed archivepak, archivezip and archivewad to implement all IArchive requirements. -- Factored common code from archive implementations out into new lib/headers: - fs_filesystem.h: a templated filesystem container, with iterators and efficient traversal. - fs_path.h: a dynamic filesystem path object, with separator checking and efficient memory management. - ibytestream.h: abstract interfaces for input byte streams. - bytestream.h: utilities operating on abstract input byte streams. - filestream.h: a c++ wrapper for stdc FILE object, implementing a seekable input stream. -- Added a new pkzip-reader implementation, designed to be orthogonal to the compression library used. -- Added a zlib input stream object, which decompresses data from an abstract byte stream on the fly. -- Removed archivezip code copy/pasted/hacked from zlib and unzip.c, replaced by pkzip-reader and zlib input stream. -- Changed vfsLoadFile to return 0 for a zero-sized file, only returning -1 if it failed to load the file. -- Removed halflife-specific disabling of shader-loading, thereby allowing common-hydra.shader to work. -- Added archivezip, archivewad and archivepak to win32 setup scripts. -- Updated win32 setup scripts for halflife media. -- Updated cons scripts for archivezip, archivewad and archivepak. -- Added printing of warnings when vfs functions are given invalid input paths. - - --------- branchpoint: "bug800-spog_branch" - - -30/08/2003 -SPoG -- Ported changes from trunk since branch point. - -11/08/2003 -SPoG -- Split qe3.h up into multiple headers. -- Cleaned up use of win32 symbols: - WINAPI macro for module functions removed. - GUID for module interfaces replaced by string. - boolean replaced by bool. - MB_OK etc gui defines replaced by enumerations. -- Removed plugin stuff deprecated by synapse from qerplugin.h. -- Cleaned up use of glib symbols: - guint32, gdouble, gboolean typedefs removed from non-glib-dependent code. - TRUE/FALSE replaced by c++ bool true/false. -- Removed all "extern" function declarations. -- Removed dependency on MainFrame from preferences.h. -- Moved synapse server and pluginmanager instances to pluginmanager.cpp. -- Split pluginmanager.cpp into three parts: - Radiant's synapse client stuff in plugin.cpp. - Implementation of brush/entity/patch-handles stuff in pluginapi.cpp. - Synapse server init/shutdown in pluginmanager.cpp. -- Added forward-declarations to avoid including other headers. -- Replaced CString usage with Str; -- Removed unused brush-scripts stuff. -- Cleaned up patch-vertex-area-selection logic. -- Removed very old code chunks that were commented or #if 0. -- Replaced project-entity with a dedicated key/value string map. - ----- branch point - spog-cleanup - -06/12/2003 -SCDS_ReyalP -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=930 - shortcuts to change texture window scale - -02/12/2003 -SCDS_ReyalP -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=913 - fix for single monitor window positioning save -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=924 - fixes to CenterXYView shortcut, correctly bound to Shift+Control+Tab now -TTimo -- add a 'q3map2' command line to win32_install.py, factorize and remove win32_install_q3map2.py - --- linux 1.3.14 test build 1 - -29/11/2003 -TTimo -- heretic2 has no q2map. linux setup tries to install and breaks - removed faulty setup line -- cleaned more Linux setup fuckage caused by q2/her2 - a tip: rm -rf build install before building and testing a new setup - -28/11/2003 -ydnar -- full SCC purge of the vs.net project files (for real this time) -- added seperate Q3Map2 build targets -- added seperate Q3Map2 post-build Python script -- _skybox entity support -- _skybox and _decal in entities.def (Q3) - --- win32 1.3.14 test build 1 - -28/11/2003 -djbob -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=899 - bobtoolz update (icon functionality is in menu too) -djbob & TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=842 - migration of the win32 build system to vs.net/VC7 - new libxml and libpng packages are required: - http://zerowing.idsoftware.com/libxml/ - http://zerowing.idsoftware.com/libpng/ - updated win32_install.py for new names and paths -TTimo -- assraped the vcproj with sed to remove Scc entries -SCDS_ReyalP -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=88 - 2D background image plugin -TTimo -- putting together win32 setup updates for 1.3.14 - msvcr70.dll goes in core directory - bkgrnd2d plugin content - changed file paths (libxml/libpng) - .xlink for new JA content - -27/11/2003 -TTimo -- using a central scons.signatures file for checksums -- version bump to 1.3.14 -- a libxml-related build bug in qe3.cpp on Debian sid -- it looks like Sid no longer has inflate_mask exported from /usr/lib/libz.so - switched the mask to be defined in our source - this may be a problem on other distros, and on holy box (Woody) -SCDS_ReyalP -- bug 921 and 922, Z floating window fixes -- bug 926, hullcaulk, hintskip, subtlehint -EvilTypeGuy -- bug 505 - select all faces with a given texture - -19/11/2003 -ydnar -- clipper tool plane points default to 1st selected patch mesh - -17/11/2003 -TTimo -- upgraded server to subversion 0.33 - --- released 1.3.13 - -10/11/2003 -SCDS_reyalP -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=917 - floating windows startup crash - -09/11/2003 -TTimo -- fix M4_GAME_ET ( OSX setup ) -AstroCreep -- cleaned up JA shader scripts - -01/11/2003 -ydnar -- Merged ASE submaterial/subobject code from BirdDawg -- Made Q2/Heretic2 tools not use precompiled headers to eliminate Win32 compilation errors -- Added glColor4ubv() support to the GL function table -- Changed PicoModel rendering to use glColor4ubv() instead of 4 divides and pass-by-value glColor4f() -- Fixed bug 900 by setting alpha to 255 explicitly in image module, rather than 3 input components, - which was borking Q3Map2 jpeg loading, and thus compiles - -24/10/2003 -TTimo -- bump to 1.3.13 -Anders -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=826 -new osx patch, fixes strip bug in setup. merging setup patches to a single file -SCDS_reyalP -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=900 -Some jpegs get garbaged alpha channel - -22/10/2003 --- merge https://zerowing.idsoftware.com:666/radiant/GtkRadiant/branches/Release-1.3.12/ - 19/10/2003 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=826 - scons BUILD=info to generate a tarball and it's .info - - 18/10/2003 - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=888 - patch for 16 bit RGBA support in glwidget - - -- released 1.3.12 Linux - - 14/10/2003 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=879 - fixed hellish dlclose issue only occuring with holy builds - - -- released 1.3.12 win32 --- end merge -Arnout -- added epsilon testing to hashtable compares to eliminate almost-identical vertices -- pico surfaces now use the normals from LWO vertices - -21/10/2003 -Arnout -- added hashtable for faster vertex matching during LWO surface generation -- model rendering now uses DrawElements and will use vertex colours in wireframe/flats shade mode - -20/10/2003 -Arnout -- added LWO support to picomodel. - shader names are derived from surface name - only geometry from layer 0 is used -- added support for 'vertical flipped' TGAs - -19/10/2003 -Arnout -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=893 - fixed starton primary monitor - fixed mouse pointer setting on win32 to properly translate gdk's offset coordinate system in windows' one - --- released 1.3.12 win32 - -11/10/2003 -Spog -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=865 - fix texture subsets -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=889 - misc update, missing JA system textures -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=824 - fixed .pref file trashing -Nurail -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=881 - BSP monitoring disabled by default in Q2 - -09/10/2003 -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=883 - more JA pack: shaders and mapextras.pk3 textures -- fix Q2 win32_install.py to put the tools at the right spot -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=878 - correctly support PNG images with an alpha channel -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=885 - fix console to refresh during a texture directory load -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=739 - fix weird Shift + Control + Z causing a Redo in non-floating window mode - -07/10/2003 -Nurail & TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=872 - Q2 tools, added -fs_basepath. Need corresponding setup and .proj updates -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=875 - fixed broken surface properties in Q2 surface plugin -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=872 - more fixes, build paths in scons, take out INSTALL config on command line (not functional + not need) - added Q2 tools back to Linux setup -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=197 - using "*" as the shaders minor in surface plugin -- updated makeself copy to the latest from icculus.org cvs -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=574 - sprite plugins, tweak to make it functional for all games -- updated Q2 tools .dsp -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=876 - more Jedi Academy setup work and content - moving imagepng.dll module to the core, as now both Sof2 and JA need it - sample maps reorg, new siege_hoth_sample.map -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=874 - a lot more models - using a dynamic File Group in IS to cope with that -- Q2 IS setup fix, was not properly putting stuff in baseq2/ - IS setup: tweak to Q2 tools stuff - -06/10/2003 -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=872 - Q2 setup needs to be cleaned up and unified between win32 and Linux - using INSTALL_Q2 and TOOLS_Q2 in SCons script to install the Q2 tools - fixed the setup build dependencies to reference the Q2 tools targets - moved the Q2 specific modules imagewad and vfspak to q2/modules - -05/10/2003 -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=871 - updating the gtk2 version to 2.2.4 - adding an SVN module with the Gtk2 developer package: checkout gtk2-win32 - updating IS to the new files - sed'ing the .dsp to replace src-gtk2 by gtk2-win32 -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=609 - Q2 tools: comment out dupe strupr on win32 - update IS setup to missing Q2 stuff ( vfspak and tools ) -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=866 - Fixed Camera inspector window not refreshing. Was a missing top level gtk_widget_show call - -03/10/2003 -Nurail -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=609 - quake2 tools build scripts - Linux setup updates - Q2 game pack in Linux setup -TTimo -- scan through all URL links in game.xlink to update them -- added JA links (Raven and MapCenter forums) - -30/09/2003 -TTimo -- update all synapse.config, win32 .dsw and install_win32.py for new surface module -- Jedi Academy and Quake II game packs in IS setups -- hardcoded hacks in editor core for JA, copied over from JKII -- bug #867, disable sleep by default -- q3map2 bug fix - -Nurail -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=862 - Q2's 'no patch' stuff - -29/09/2003 -TTimo -- OSX: fixup setup.xml.in - --- merge bug856 back into trunk -16/09/2003 -Nurail -- new patch + win32 stuff for surface module -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=804 - refactored the XML synapse.config handling: - better detection of invalid XML file - less code, factorized to CSynapseClient::ConfigXML -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=828 - fixing bobtoolz 'shaders' major loading issues - added '*' minor. to be used with lots of caution. only if the given major will have a single API such as 'shaders' - also, map module was missing a VFS entry in non-HL configs. that's bad karma, using a minor "*" instead - NOTE: on a lot of modules we could be using a '*' entry instead of having lines in synapse.config -- took out obsolete md3model - -15/09/2003 -Nurail -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=856 - quake2 surface module - -07/09/2003 -Nurail & TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=856 - a surface inspector module to customize per-game API - removing DO_SURFACEPLUGIN define (enabled implicitely) - removing bSurfacePropertiesPlugin (true implicitely) - remove SI_SetActiveInRadiant, it's always on by default - why was USE_UNDOTABLE_DEFINE taken out? - put back in - removed DBG_PLUGIN define and related code, that stuff is from way back and no longer relevant - cleanup QERApp_FreeShaders in shader module from DO_SURFACEPLUGIN stuff - the WINAPI stuff in interfaces is not needed, that's an old remnant. Cleaned up --- end merge bug856 back into trunk - -19/09/2003 -Justin Blur -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=785 - fix ~/.radiant permission bug -Nurail & TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=849 - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=851 - win32 updates for the new modules and install_win32.py - -16/09/2003 -Nurail & Hydra -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=848 - q2 map format minor - -08/09/2003 -Tr3B -- imagepng.so / PNG format support in Linux - NOTE: atm no official supported Linux game by GtkR uses this - -07/09/2003 -Nurail -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=851 - imagewal.so module / wal image format -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=840 - md2 support in picomodel - -06/09/2003 -Nurail & TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=848 - renaming mapq3.so to map.so - added hooks for Q2 map format load/save to single map module (minor mapq2) -Nurail -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=849 - vfspak port to synapse and updates - -04/09/2003 -SPoG -- Fixed crash in RunBsp caused by passing an invalid pointer to printf. -- Changed console to wrap long lines instead of using horizontal scrollbar. - -30/08/2003 -Anders & TTimo -- OSX setup, new patch to make scons SETUP=1 produce a .run -- don't put bspc Linux binary in the setup - -30/08/2003 -Anders & TTimo -- OSX setup, new patch to make scons SETUP=1 produce a .run -- don't put bspc Linux binary in the setup - -26/08/2003 -Anders -- more scons OSX, start on setup stuff - -25/08/2003 -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=855 - make 'move into worldspawn' work again -Anders Gudmundson & TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=826 - OSX scons build system - -24/08/2003 -ydnar -- Removed "test.cpp" from radiant.dsp (merge artifact?) -- Added ddslib to radiant.dsw -- Correctly set lib deps for q3map2.dsp for ddslib -- [bug 852] Increased buffers from 260 bytes on Win32 to 4096 bytes - -TTimo -- bump to ver 1.3.12 -- EnsurePythonVersion broke in 0.91 (commented out) - -David Hogue -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=844 - q3data Linux. q3data can read .ase and turn them into .md3 - -23/08/2003 -ydnar -- Added ddslib to repository, based on nvidia sample code, cleaned up a bit - straight C, loads DXT1, DXT3 and DXT5 format DDS textures. - -22/08/2003 -TTimo -- https://zerowing.idsoftware.com:666/viewsvn/ -- Arnout's commit email script - try #2 - the commit script doesn't handle viewsvn root remaps (radiant instead of radiant.svn) - adding a prefix to the report - -04/08/2003 -TTimo -- conversion from CVS to Subversion: -repository convert completed (with revml) -module repositories glued together in a single one -hooking email commit scripts and backup scripts -- Python >= 2.1 required instead of 2.2 - -01/08/2003 -SPoG -- Changed gl widget to request maximum available depth buffer precision. -- Changed all uses of deprecated GtkCList and GtkCTree to use GtkTreeView/Model. -- Fixed directory handle leakage in synapse module search. -- Fixed dir_dialog always returning NULL for Textures -> Load Directory. - -23/07/2003 -SPoG -- Ported focus_out_event handlers in gensurf to gtk2 signals system. -- Fixed failure to load models for entities other than misc_model. -- Fixed crash in model module shutdown caused by mismatched resource capture/release. - -22/07/2003 -TTimo -- fix q3map2 .dsp for correct glib-2.0 includes (common/vfs.c) -- camera plugin installs to core now (RTCW and ET) -- fixups to the merged setup stuff -- patched cvsreport to provide explicit diff for some files #2 -- fix to work with scons 0.90 / added LIBPREFIX ('lib') where needed - https://sourceforge.net/tracker/?func=detail&atid=398971&aid=766975&group_id=30337 -SPoG -- Fixed crash in cmdlib ExtractFileBase when source filename is an empty string. - -20/07/2003 -TTimo -- SCons scripts for the ported plugins: bobtoolz, camera, prtview, gensurf -- ET Linux setup script + new plugins -- q3map2.x86 is installed and wrapped through a q3map2 script (libstdc++ LD_LIBRARY_PATH) -- update ChangeLog and credits -- put back the GTKRAD_DIR in .fgl - -19/07/2003 -SPoG -- Tagged trunk before merge as bug537-merge-3. -- Tagged branch port_gtk2_20030307 as gtk2-merge-final. -- Merged changes since tag bug537-merge-2 into trunk. -- Removed gtk dependency from plugin toolbar interface. -- Ported prtview, bobtoolz and gensurf to gtk2. - -18/07/2003 -Anders Gud -- OSX build fix - -16/07/2003 -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=814 - merging ET support code into to trunk -- cvsreport 0.3.0 - http://www.nongnu.org/cvsreport/ - rolling out this ver since old cvsreport setup broke -- fixup to build on Linux (including fixing plugin builds) - --- release-1_3_8-ET - -02/07/2003 -TTimo -- new setup build, with patches and updates from SD -- local fixing of bobtoolz dependency against libcmd, and itoolbar.h gtk header bustage - -19/06/2003 -TTimo -- missing plugins. add them to .dsw for default build, add them to IS setup: - camera, gensurf, bobtoolz, prtview -- fixup bobtoolz code for VC6. for(int i=0 causing duplicate definition errors -- removed pk3man from IS (we no longer distribute/maintain it) - TODO: cvs remove the IS files for it -- re-enabled plugins in build by default, disabled curry and textool - TODO: following error when bring up About box of bobtoolz: - BobToolz::ERROR->Failed To Load Exclusion List: C:\Program Files\GtkRadiant-ET-1.3\plugins\bobtoolz.dllbt\bt-el2.txt - -18/06/2003 -TTimo -- add ET game pack. from Arnout's full dump of editor source + game pack data - trunk tagged at ET-tag for this -- Dlg_SdAskCorePath: - szDir = "C:\\Program Files\\GtkRadiant-ET-1.<>"; - -09/06/2003 -ydnar -- Added Q3Map2 keys/entities to Quake 3 entities.def -- Removed obsolete vlight keys from Quake 3 entities.def -- Added MD5 functionality to mathlib, from: - http://sourceforge.net/projects/libmd5-rfc/ - -------- merged changes since tag bug537-merge-2 from branch port_gtk2_20030307 to trunk - -TTimo -- try checkin on branch see if cvsreport 0.3.0 will verbose it - -08/07/2003 -SPoG -- Fixed recent-files list for file names containing underscores. - -07/07/2003 -SPoG -- Fixed crash and file-type bugs in gtk file-dialog. -TTimo -- converted the setup code from perl to python -- added copy over of libgcc_s and libstdc++, and LD_LIBRARY_PATH in the wrapper script - -06/07/2003 -SPoG -- Changed console popup menu to include cut/copy/paste as well as clear. - -05/07/2003 -SPoG -- Fixed the way surface-inspector dialog responds to escape key. - -04/07/2003 -TTimo -- linux building / SCons - 0.90 is broken, use 0.14 for now. added version check - adding scons SETUP=1 option to spawn setup build - enable back vfswad in scons - TODO: grab Conscript-setup, convert it to python in build_setup function - -02/07/2003 -TTimo -- building a win32 setup, using -gtk2 suffix (game packs in Radiant-1.3-gtk2 and core in GtkRadiant-1.3-gtk2) -SPoG -- Ported vfswad to gtk2. -- Fixed memory leak in vfspk3 directory search. -- Added vfswad to win32_install.py. - -09/06/2003 -TTimo -- tagging setup/ as gtk2_setup_rollback - rolling back trunk setup code to the branch to build an experimental release -- merge trunk to branch: --- tagged HEAD with bug537-merge-2 --- merge HEAD between bug537 and bug537-merge-2 into the branch -- - 31/05/2003 - TTimo - - grab back vfswad code that I forgot in bug 800 rollback - - add prtview back to the project, fix it to build (#817) - - 27/05/2003 - djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=817 - prtview fixes, upgrade to synapse - - -- release-1_3_8 --- end merge HEAD between bug537 and bug537-merge-2 into the branch -- -- freshly merged in vfswad is broken -- freshly merged in prtview is broken -- q3radiant.dsp -> GtkRadiant.dsp, outputs GtkRadiant.exe -- removed vc5 dsps -SPoG -- Updated win32 setup stuff to use gtk2 dlls. -- Modified setup.pl to run correctly (tested on cygwin perl 5.6). - -08/06/2003 -TTimo -- Linux: - check gcc 3.x, better ldd check - add gcc version to about message - kill old cons stuff -- added q3map2.x86 scons build -- header conflict libs/cmdlib.h tools/quake3/common/cmdlib.h - grepped through q3map2 source to change #include "cmdlib.h" to common/cmdlib.h -- killed more cons files remnants -SPoG -- Improved error reporting for win32 setup system. -- Fixed errors reported when running setup scripts. -- Fixed scale of xor selection rectangle in XY window. - -07/06/2003 -SPoG -- Fixed X Window System error when entering freelook on *nix. - -06/06/2003 -SPoG -- Fixed copy/paste on *nix. -- Changed copy/paste on *nix to use GtkClipboard api. -- Changed copy/paste on win32 to be non-window-specific. -- Further cleaned up MainFrame::Create. -- Changed freelook to use gdk_window_get_origin instead of gdk_window_get_root_origin to place the cursor. - -05/06/2003 -SPoG -- Fixed grey statusbar in 4-way-split mode. -- Redirected gtk messages before creating main window. -- Removed unused XYFriend hack from camwindow. - -04/06/2003 -TTimo -- win32_install.py settings loaded/saved from site.conf - -02/06/2003 -TTimo -- fixed python running with no output. Make sure VC6 finds native Python before any cygwin Python - look at the Directories settings in Tools > Options to either kill the c:\cygwin\bin path, or have Python path first -- renamed dupe files to avoid header collision and general confusion between entity and model -- added win32_install.py to perform post-build install (need to load the configuration paths from a non-cvs stored site.conf file) - -01/06/2003 -TTimo -- bind gen.dsp to makeversion.py -- added a run_python.bat to check for python presence and execute - -27/05/2003 -TTimo -- write makeversion.py module - hook it up to SCons build - cleaner, easier to use -- comment out vfswad build lines. source is still not in tree (bug 800 aftermath I think) - -18/05/2003 -SPoG -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=537 - Changed Sys_FPrintf_VA to immediately process console events during map load. - Changed startup to create main window after QE_Init(). - Fixed loading last map on startup. - Fixed crash on exit. - Fixed colour dialog. -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=537 - have to delay merging back to trunk. - have a behaviour problem between debug and release builds. - while debug is fine, release is screwed (see bug item) - --- tagged HEAD with bug537 --- merge HEAD between merge-gtk2-20030413 and bug537 into the branch ----- - 11/05/2003 - Dan Olofson & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=812 - workaround for ATI drivers bug (polygon backfaces) - use Preferences > 2D Display/rendering > ATI cards with broken drivers - Riant - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=806 - updated synapse.config for SoF2 png - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=805 - dir_dialog is broken - is only used in prefab path prompt - - -- release-1_3_7 - - 14/04/2003 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=801 - moved "ignoring sprite for entity.." to be a _DEBUG only thing - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=802 - fixed models not drawing on win32. was a setup bug - - OSX setup build updates - added dependency against libpng3-shlibs - - added openurl.sh to open urls on *nix (with setup updates) - Riant - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=803 - RTCW - default_project.proj in setup - - 13/04/2003 - Michael Schlueter & EvilTypeGuy - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=684 - imagepng building under Linux - Riant & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=797 - fixed texture compression support - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=799 - regen project file from template on version upgrade - updated all default_project.proj to have "version" "1" - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=798 - missing modules/bitmaps/model_reload_entity.bmp from Linux setup --- end merge HEAD between merge-gtk2-20030413 and bug537 into the branch ----- - -17/05/2003 -TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=537 - http://www.qeradiant.com/wikifaq/index.php?Gtk2%20build%20notes - went through the new dll dependencies, listed required files preparing for a single zip package - updated all the project files to rely on src-gtk2/ - -13/04/2003 -SPoG -- Tagged HEAD with 'merge-gtk2-20030413' and merged HEAD --> port_gtk2_20030307. - -12/04/2003 -SPoG -- Added gtk-2.x libraries to win32 setup. -- Changed win32 setup to use 'dynamic' file-groups, making it possible to add files without - modifying installshield scripts. -- Modified win32/setup.pl to copy setup data to dynamic file-group directories. - -30/03/2003 -TTimo -- added scons scripts. the scons engine is included in the tree. you just need to have python - have ldd -r safe check on .so - TODO: - - make sure it's gcc3 - - check OSX - - add q3map2 build - -29/03/2003 -TTimo -- tracked and fixed the startup bomb on Debian sid: - `pkg-config gtk+-2.0 --libs` - -Wl,--export-dynamic -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgdk_pixbuf-2.0 -lm -lpangoxft-1.0 -lpangox-1.0 -lpango-1.0 -lgobject-2.0 -lgmodule-2.0 -ldl -lglib-2.0 - http://www.gnu.org/manual/ld-2.9.1/html_chapter/ld_2.html#SEC3 - --export-dynamic - When creating a dynamically linked executable, add all symbols to the dynamic symbol table. - The dynamic symbol table is the set of symbols which are visible from dynamic objects at run time. - If you do not use this option, the dynamic symbol table will normally contain only those symbols - which are referenced by some dynamic object mentioned in the link. If you use dlopen to load - a dynamic object which needs to refer back to the symbols defined by the program, rather than - some other dynamic object, then you will probably need to use this option when linking the program - itself. - this causes symbol confusion, shaders.so's g_ShaderTable suddenly resolves to the core's g_ShaderTable - one is a 'shaders' API, the other an 'appshaders' .. everything gets badly mixed up - added a check in the cons script, using `pkg-config gtk+-2.0 --libs-only-L` `pkg-config gtk+-2.0 --libs-only-l` - (same for gtkglext) - -28/03/2003 -TTimo -- propagate jpeg compile fix from bug750 branch -- use PKG_CONFIG_PATH when building radiant/ (alternate gtkglext-1.0) -- on OSX, you need gtk+2-dev package, and pkgconfig, atk1 - build gtkglext from source http://gtkglext.sourceforge.net - -17/03/2003 -TTimo -- updated the build system to glib2/gtk2/gtkglext - atm it compiles and starts on my dev box (Debian Sid) - but doesn't reach end of initialization, hangs on - q = (qtexture_t*)g_hash_table_lookup (g_ShadersTable.m_pfnQTexmap (), stdName); - in shaders.cpp QERApp_Try_Texture_ForName - need to have the gtk2 dev packages, and libgtkglext1-dev - -12/03/2003 -SPoG -- Replaced alpha-blended area-selection rect with XOR rect. -- Fixed YX/XZ/YZ toggle in floating windows layout. -- Cleaned up xor rectangle code. - -11/03/2003 -SPoG -- Fixed console scroll-to-last-text-inserted. -- Fixed console error/warning colours. -- Refactored or removed WIN32-specific gtk-related stuff. -- Removed win32 SetCapture/ReleaseCapture on GLWindow. -- Removed win32 gtk_main_iteration calls in glwindow mousemoved. -- Cleaned up start-on-primary-monitor stuff. -- Changed main window to use standard save/load window position/size. -- Replaced deprecated gtk_widget_set_uposition with gtk_window_move. -- Removed win32/X gl functions from igl. -- TODO: replace/remove deprecated gtk_widget_usize. - -10/03/2003 -SPoG -- Changed fonts in win32 rc file to 8pt tahoma. -- Fixed flat-grey gui in Regular layout mode. -- Changed main-window save/restore maximized to use gtk API. -- Fixed button_press_event handling on console/entity/entitylist windows. - -09/03/2003 -SPoG -- Fixed crash on shutdown after changing floating-z-window preference. -- Removed win32_realize_floating hack. -- Refactored MainFrame::Create to make it more readable. -- Fixed key_press_event handlers for entity/surface/patch dialogs. -- Fixed delete_event handlers for dialogs derived from Dialog class. - -08/03/2003 -SPoG -- Fixed viewport for entity window comment text. -- Fixed x-shrinking for entity window comment text. -- Fixed menu underscore shortcut hack in MRU list. -- Changed groupdialog to connect switch_page signal after creating all pages. -- Changed gl widget to use gtkglext/pango to create fonts. -- Cleaned up gtkglext glwidget implementation. -- Reduced border size on toolbar widgets. -- Replaced font with font_name in win32 rc file. -- Added viewports for all scrolled text boxes. -- Fixed entities/textures/console window title update when page is changed. -- Fixed floating windows not being transient to main window (don't want them on taskbar). - -07/03/2003 -SPoG -- Created a new branch for the port to gtk 2.x. -- Fixed menu underscore shortcuts to use gtk_label_new_with_mnemonic. -- Fixed global keyboard shortcuts by using mainframe_keypress. -- Fixed use of deprecated gtk_color_selection_get_color. -- Removed use of deprecated gtk_paned_set_gutter_size. -- Replaced deprecated gtk_widget_draw with gtk_widget_queue_draw. -- Replaced deprecated gtk_object_get/set_data with g_object_get/set_data. -- Replaced deprecated gdk functions with 2.x equivalents. - - ------ branch port_gtk2_20030307 ------ - - -13/04/2003 -Michael Schlueter & EvilTypeGuy -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=684 - imagepng building under Linux -Riant & TTimo -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=797 - broken texture compression support - - - -31/01/2003 -SPoG -- bug #752 - Construct fix for ppc, patch applied. - -26/01/2003 -TTimo -- bug #750 - revamp of the setup stuff on Linux - (under way, see bug for progress - feel free to help!) -- reworked the cons scripts, setup is hooked in to cons now - also, added gcc version select on command line, using Cons_gcc.pm utility - -22/01/2003 -TTimo -- merged merge-1_2_10-post back to trunk - - -=============================================================== --- merging release-1_2_9 -> merge-post-1_2_10 into trunk - trunk before merge is tagged pre-merge-1_2_10 -=============================================================== - -22/01/2003 -TTimo -- finished up the TODO items, turned into bug items or dropped them. branch is ready to move back in to trunk - -18/01/2003 -TTimo -- fixed ID_SELECTION_MERGE - -17/01/2003 -TTimo -- fixups - FlushReloadSelectedToolbarButton -> CFlushReloadSelected - incorrect naming: RadiantToolbarModuleManager -> CRadiantToolbarModuleManager - ToolbarButton -> IToolbarButton, and C* implementations - http://www.qeradiant.com/wikifaq/admin.php?Code%20Conventions - -14/01/2003 -ydnar -- Minor Cons fix for OS X (bug 729) - -13/01/2003 -ydnar -- GtkRadiant now builds on OS X, Linux, and Win32 out of the same tree -- OSX build uses gtkfileselect-linux now, as the Darwin version was broken/old - fixme: change this to use OS X open dialog box or something? -- Minor fixes to a few files to fix gcc warnings -- Model module now builds on OS X and Linux, using Synapse properly -- PicoModel change to invert T coordinate on ASE models -- Q3Map2 change to export ASE models with T coordinate flipped -- Misc Q3Map2 changes - -09/01/2003 -ydnar -- Updated Construct with Darwin/OS X ld flags for 4MB stack size -- Misc Q3Map2 updates (2.3.35-dev) - -05/01/2003 -ydnar -- "angles" key now properly ordered, to work with current mathlib - (also changed in Q3Map2) - -31/12/2002 -ydnar -- PicoModel: Minor fix to MDC loader (naming/define) -- Q3Map2: 2.3.34-pre-1 updates -- MapXML dsp unix->dos newlines - -29/12/2002 -SPoG -- Merged q3map2-texturing prefs key. -- Merged vfs check for gamemode project key. - -27/12/2002 -TTimo -- fix GetTickCount stuff -- added q3map2 cons script -- fixed Linux build - -23/12/2002 -SPoG -- Added model cache API, moved model cache implementation from entity module to core. -- Added file-type registry API, replaced core file-type manager with registry. -- Changed model module to register supported file types with core registry. -- Removed or #ifdef'd non-functional code from model module. -- Added support for misc_gamemodel and model_static to entity module. -- Cleaned up entity module's on-epair-changed API. -- Moved light-entity-specific code to a seperate file in entity module. -- Cleaned up file dialog interface - specify file-type-lists with a string. - -22/12/2002 -SPoG -- Ported camera plugin to synapse, adding support for camera and ui APIs. - -20/12/2002 -SPoG -- Fixed default prefs setting for selected-brushes-camera, gridmajor-alt and gridminor-alt. -- Merged CEntityEclassModel::Draw in entity module. -- Ported imagepng module to synapse. -- Fixed warning for CamDragMultiSelect preference bool used as int. - -19/12/2002 -SPoG -- Fixed white-textures bug caused by texture compression preferences. -- Ported light-radius rendering to 1.3 entity module. - -18/12/2002 -SPoG -- Merged win32 project files, with the exception of camera plugin. -- Ported model module to synapse API. -- Redesigned toolbar API to remove gtk-dependency from toolbar plugins. -- Refactored window-position preference save/load. - -17/12/2002 -TTimo -- kick doxygen generation for branch merge-1_2_10-post - -15/12/2002 -TTimo -- having the linux version compile and start again. took out numerous elements while merging, built a list of TODO stuff - the main thing to do being to bring the win32 build back up too, then to go through TODO list and fix stuff - until the win32 version runs too, I check this in to a seperate branch merge-1_2_10-post -- There is quite a massive update in mainframe.cpp switch case for all events. - Looks like it's just a reordering of stuff, but it looks bad in the diffs. -- added m_MapReg pattern - -- At some point, I'm thinking that forcing correct TAB/SPACE conversion on the server end would be a good thing to have. - Nazisticly forcing the formatting sounds like the only viable solution. - - 11/12/2002 - RR2DO2 - - #418, mdc load and display (RTCW) - - #597, CenterCamera shortcut - Use Ctrl+Shift+TAB to center the views onto the current camera location - - #714, bitmap loading fixes and speedups - - #715, fixed Alt+Shift cycle/drill select to work with brush-based entities - EvilTypeGuy - - #718, fix compilation warnings - Riant - - #707, fixed HM mode in STV:EF - - 10/12/2002 - EvilTypeGuy - - Fix gcc3 compilation warning - EvilTypeGuy and X-Man - - Fix OpenURL so browser launching works on XDarwin (Mac) systems. - - 8/12/2002 - RR2DO2 - - #710, AssignSound pattern - - #711, SoF2 model_static drawing - - #713, sync 2d and 3d rendering of models - - #238, apply 0..1 T range when Fitting a patch (instead of 0..-1 previously) - - #633, Add ability to change default color in 3D window Misc > Colors > Camera background - ydnar - - Q3Map 2.3.33 (see changes.q3map2.txt) - - Quake 3 + TA common.shader updates (q3map_terrain, hint) - - 3/12/2002 - TTimo - - merging Stable-1_2-Apple into Stable-1_2 - - why INSTALL.TXT? re-used INSTALL, updated to point to wiki - - why the -machinedump test against i386-redhat-linux? removed - - using $is_darwin flag instead of $gcc_machine tests in the build scripts: - gotta leave some room for a Linux ppc build, and darwin x86 - exporting it for use in sub scripts - - the addition of ccache support broke some Apple SConstruct patches to $ENV{PATH}, fixing - merged version is compiling fine on Debian Sid - checking in on a branch, need to validate win32 build and OSX build before applying in Stable-1_2 - - -- release-1_2_11 - - 30/11/2002 - TTimo - - added seaw0lf to credits - - ydnar's changelog.q3map2, added to global.xlink and Linux setup - - 1.2.11 version tag - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=699 - updated IS setup for q3map_terrain keyword - also fixed details in STVEF media - Arnout - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=569 - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=698 - fixed drill select, Ctrl bug in vertex mode, and updated changelog.txt - - 29/11/2002 - TTimo - - 1.2.11-rc1 - - update changelog credits links for release - - update linux setup, putting EULA and new README instructions - - 28/11/2002 - ydnar - - Removed redundant 'p' from "developers" - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=637 - fixed - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=694 - fixed - - Updated to Q3Map 2.3.32 - - Added epsilon to texture plane choose code to eliminate numerical - inconsistencies on brush faces slanted at 45 degree angles (bug 637) - - Fixed bug in lightmap export after lighting when map contains 0 BSP lightmaps - - Adjusted some light tracing constants to fix certain brush/patch seam shadows - - Tinkered with skylight code again - - Fixed bug where lightgrid would be black if level was compiled with -nogrid - - Fixed -approx code to work in floating-point space, using _minlight - - Fixed bug where vertex light code was using invalid pvs data to create - light list for surface, leading to incorrect vertex lighting - - Fixed related bug in anti-light-leak code that was causing brush faces to go - black (bug 694) - - New: _minlight sets _minvertexlight and (new) _mingridlight automatically - - New: _mingridlight key to set minimum grid lighting - - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=637 - added preference setting in Preferences > BSP monitoring - added an item on the wiki - - 27/11/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=662 - picomodel-based model.dll module (new model.dll, removed md3module.dll) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=664 - media/setup updates for q3map2 support - added modified quakev3.qe4, bumped internal version to 4 for all games - SOF2 and JKII were forcing BSP monitoring off because of sof2map, now only printing a warning - added -rename to SOF2 BSP phase - Q3 & RTCW new templates are working - haven't tested the STVEF & SOF2 versions - updated IS setup scripts to make sure quakev3.qe4 is updated in nightly release - (not needed on Linux, we will be doing a full release) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=662 - updated win32 setup to provide right model.dll stuff - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=621 - typo was causing memory error - - RR2DO2 & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=662 - more model fixes, fixed the Linux build to build model.so - added search path to modules/ for bitmaps - model reload, patch and bitmap - - 26/11/2002 - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=569 - area select - Alt+Shift for area select (complete tall) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=621 - broken undo creating ghost undo entities (and trashes memory) - partly fixes the issue, it's a memory error still - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=659 - updates to RTCW camera plugin - works in 4 view mode - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=663 - more fixes to plugin API - - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=638 - libpng in the core DLLs instead of SoF2 (for q3map2 dependencies) - putting q3map2 binary with the Core Binaries - - 25/11/2002 - TTimo - - added ccache support to cons build system - http://ccache.samba.org/ - - 21/11/2002 - ydnar - - minor bugfix to PicoModel ASE material loader - - Q3Map2 updated to 2.3.31 (Splash Damage) - - Stitching the edges of lightmaps on patches that wrap around (cyls and cones) - so the seam is no longer visible - - The -patchmeta switch works better now, the patches are still stored in the - BSP for collision, but are pre-tesselated into nonplanar meta surfaces for - more efficient rendering - - Better, more uniform lightmap sample position finding on patch meshes - - Moved q3map_tcMod and q3map_alphaMod processing to the final phase - - New: q3map_skylight AMOUNT ITERATIONS to replace surfacelight on sky surfaces - for much faster and more uniform sky illumination - - Fixed bug in PicoModel ASE material parsing code - - Fixed a few seam/lightmap precision/projection errors - - Increased MAX_SHADER FILES to 1024 and fixed overrun error when more than that - number of shaders was listed in shaderlist.txt - - Increased a few compiler maximums for larger maps - - New: -np N switch on BSP phase, works like -shadeangle, in that it forces all - planar shaders to be nonplanar with the shading angle specified - - New: -nohint switch on BSP phase, omits hint brushes from compile for testing - - New: -debugaxis switch on light mode. Colors lightmaps based on their lightmap - axis (which direction the lightmap was projected on) - - New: -debugorigin switch on light mode. Colors lightmaps based on the luxel - origin relative to the raw lightmap's bounding box - - New: -debugcluster switch on light mode. Colors lightmaps based on the pvs - cluster the luxel falls into - - New: -convert switch to convert BSP to ASE file (experimental) - - New: q3map_lightmapmergable directive to allow terrain to be mapped onto a - single lightmap page for seamless terrain shadows - - 18/11/2002 - TTimo - - fixed pk3man build system to work with new cons layout - - fixing linux setup system to work with new cons layout - Linux 1.2.11 will be a full setup, much easier that way - - update makeself to the latest (and best) version - - add q3map2 to Linux setup. goes in core (g_strAppPath) - NOTE: has a dynamic dependency to libpng - - pk3man still has issues with the zlib code that's been thrown in it - unresolved which I don't have time to look at - since we plan to drop pk3man in 1.3, dropping it now is just as good - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=644 - detect GOTY install from registry and use it as default path - - 13/11/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=639 - reworked to have the UI in game settings dialog - (this is strictly win32 thing, if that broke Linux build, then fix the typos) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=630 - mouse AngleSpeed setting was getting clobbered. fixed and upped the max values - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=623 - applied a fix, rolls back the values when the compression formats are not supported - fix ain't very clean, if we have to deal with extensions some more, we need to deal with the settings persistance better - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=624 - updated the setup code for town_*.shader (both in full setup and update) - updated files in WolfPack - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=672 - using a QE4_VERSION define, added a message if there's a project template with wrong version - - 12/11/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=671 - guard junk.txt path between " " - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=663 - fix to CommitBrushHandleToEntity stuff - - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=660 - previously you could select patch control points when patch selected + vertex edit (V) in 2D view. Works in camera view now - - 12/11/2002 - TTimo - - nudging zerowing to trigger Stable-1_2-Apple doxygen generation - http://zerowing.idsoftware.com/doxygen/ - - 11/11/2002 - TTimo - - http://ttimo.net/web/anjuta - modified the .prj to work with the cons patches (linked dirs) - still way experimental - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=651 - fixing linking for radiant.x86 - - 10/11/2002 - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=669 - patch inspector bug - fixed - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=663 - fucked up change in the plugin API caused breakage of several plugins - still have to fix bobtoolz http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=665 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=661 - Undolevels not set properly - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=660 - drag selection to the camwindow for patches in controlpoint edit mode - (not sure about the actual shortcuts, Ctrl+Alt on my current Linux setup) - - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=657 - mark map modified on editing entity keys - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=651 - added the correct link and ldflags statements to have static linking everywhere - didn't check gcc 3 build, check correct static on Debian Sid and holy box - has a $staticstdcxx in Construct to toggle On/Off if needed - - 09/11/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=651 - reworking the cons building. support for gcc2 and gcc3 - cons -- gcc= - read gcc version and configure accordingly - changed _NO_STLPORT to Q_NO_STLPORT - independant BASE_CFLAGS and BASE_CXXFLAGS - correcting usage of CC/CXX for c/cpp source and linking - fixed missing -lz in vfspk3.so - changed the way we build curry.so, works from the GtkRadiant tree now - (NOTE: gcc 3.2 build of curry.so spews quite a few warnings) - tweaked the way we do -fno-rtti -fno-exception - - 04/11/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=638 - .qe4 version 4, udpated q3's .qe4 template, update setup to put q3map2 in the right place - bumped version to 1.2.11-test for test setups - - 03/11/2002 - ydnar - - fixed bug in jpeg loading code (4 components instead of 3 for RGB images, mh) - - updated PicoModel to 0.8.8 and Q3Map2 sundry fixes (2.3.29): - - Merged with latest CVS, fixed minor issues with matrix order - - Fixed minor Sys_FPrintf/Sys_Printf substitution typo in Q3Map2 - - Expanded debug colors to 12 for debugging surface meshes - - PicoModel: fixed ASE loader to support > 1 texture coordinate per-vertex, - so more models supported correctly, also loading vertex normals - - PicoModel: md3 shader names are now cleaned. Suffixes (such as .tga or .jpg) - are stripped, and \ path separators are changed to / - - New: Add :q3map to the end of any shader name, and it will be interpreted as - the named shader minus :q3map. Example: - textures/shaderlab/concrete:q3map -> textures/shaderlab/concrete - One potential use is the -approx feature to collapse lightmapped surfaces - into vertexlit surfaces, saving lightmap space/memory - - New: q3map_clipModel -- does what you think it does, sort of. This code ix - really experimental, and should *only* be used on large models such as terrain - (not small decorative models). This code will be evolving. Note: the shader's - surfaceparms are inherited by the magic clip brush, so if you have nonsolid - in your model's shader that uses q3map_clipModel, then the brush will also - be nonsolid - - 03/11/2002 - TTimo - - cleaning up some cons stuff, checking that the setup building process is still good on Linux - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=622 - updated Linux setup to put the bitmap - - 02/11/2002 - ydnar - - PicoModel: replaced stricmp with _pico_stricmp - - 02/11/2002 - ydnar - - PicoModel: added obj.c and ms3d.c, removed wfobj.c - - 02/11/2002 - ydnar - seaw0lf - - Updated Q3Map2 to 2.3.29 sources - 2.3.29 - - Merged with latest CVS, fixed minor issues with matrix order - 2.3.28 - - Bug 654 (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=654): - Fixed problem where brush faces, drawsurfaces, and surfaceparms weren't living - together in perfect harmony (terrain surfaceparms now inherited by brushes) - - Nodraw fog works now, albeit when you're underneath, surfaces above don't get - fogged properly. Could be good for foggy water where you want the above-water - portions to only be occluded by the water surface - - Bug 656 (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=656): - Number of lightgrid points displayed (byte size is currently out of proportion - due to internal storage format) when Q3Map is called with the -info switch - - Fixed wack surface merging bug where code would attempt to merge triangles not - adjacent to the current set, causing bad lightmap projections on nonplanar - surfaces - - Fixed tiny 1-character bug in 2d lightmap texture allocator where adjacent - luxels were being checked for occlusion rather than the actual source luxel - 2.3.27 - - Fixed minor bug in scriplib bugfix where the last character in a file wasn't - being read. - - Fixed bug where 0-area or bogus triangles were causing crash in MapRawLightmap - if they used a shader with a normalmap (thanks ShadowSpawn) - - Fixed bug where lightmaps were getting hosed levelwide on a prerelease version - of 2.3.27 - - Fixed bug where lightmaps were getting knackered on models and certain patches - - Merged latest PicoModel version from seaw0lf, adding support for ASE and WF OBJ - models (preliminary) - - Increased MAX_MAP_PLANES to 0x40000 (~256k) - 2.3.26 - - Now using GtkRadiant's libpng and zlib config (linked as DLLs) - - Fixed bug in script parser where repeat calls to GetToken() were causing - memory corruption - - Fixed SOF2 -rename bug - - When using -game sof2 or -game jk2, the -flares argument is implied - - Added -noflares argument to disable the above behavior - - Added support for flares on entities. Use one of the following keys: - "_flare" "1" -- use default flare (different for each game) - "_flareshader" "path/to/flareshader" -- use a specific flare shader - Note: This only matters in SOF2/JK2 now. Make a light targetted (a spotlight) - to get it to aim the correct direction, otherwise it defaults to pointing - downward. You cannot have omnidirectional flares - - Lightgrid size is automatically increased to accomodate large maps. The - MAX_MAP_LIGHTGRID error will never happen again - - Update PicoModel to 0.8.7 sources - - ASE support - - Alias|Wavefront OBJ support - - .remap shader remapping suport - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=655 - handle grayscale jpegs gracefully - - mathlib: fixed VectorClear(), got rid of braces - - scriplib: fixed double-free memory corruption bug - - radiant: added new color scheme to emulate Lightwave/Maya/3DS Max - - 02/11/2002 - TTimo - - too many issues with build system reading system's libjpeg.h instead of libs/libjpeg.h - renamed libs/libjpeg.h to libs/radiant_libjpeg.h, updated sources - - 29/10/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=639 - running from a network share - saving prefs per-user - - 27/10/2002 - TTimo - - merged in some more m4x4 code for q3map2 - - fixed unresolved code in picomodel (strlwr / strnicmp) - - reworked the tools building to build both q3map and q3map2 without trouble - - 25/10/2002 - ydnar - - q3map2 and picomodel source, initial checkin to Stable-1_2 branch (does not compile yet, tweaking to be done) - - 23/10/2002 - TTimo - - camera.dll goes into $(RTCWRADIANTDIR)/plugins instead of $(RTCWRADIANTDIR)/modules - fixed up camera compile (exports) - added camera bitmap (plugin toolbar) - - 21/10/2002 - TTimo - - quickfix to the build (typo) - - changed dynamic linking on Linux to look for libGL.so.1 by default - fixes "all textures are blank" Linux bug with NVidia cards - (you still have to have a working NVidia GL installation though, xlibmesa-dev on Debian screws things up) - - checked in modified q3 .qe4 with q3map2 menu (see bug #638) - - 09/10/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=622 - reworked the plugin toolbar to rely on interface instead of straight exports - cleaned up the botclip monsterclip Brush_Draw filtering, added proper selection filtering (Brush_Ray) - merged bug-622 back into Stable-1_2, bug-622 branch is dead now - - 06/09/2002 - James Monroe - RR2DO2 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=619 - light globes, applying patch by RR2DO2 built from the initial light globe code - - note to self: indent -kr -nut -st -ts2 -i2 - - RR2DO2 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=622 - massive patch update from SD's GtkRadiant - - camera plugin: new bitmap - fixed Linux install path for camera plugin to wolf/plugins - - fixed various warnings in camera build gcc / Linux - - fixed pref crash if plugin toolbar disabled - - fixed Gtk-WARNING on bad cast in AddPlugInToolbarItem - - renamed the new select to 'Use paint-select in camera view:' in prefs - (camera paint-select, should be our default name for this) - - NEW: you can 'paint select' in the camera view: 'camera paint-select' - press shift and move the mouse over the camera view to paint over brushes you want to select - configurable in prefs to enable / use Shift key, or use 'classic mode' ctrl+alt - - NEW: light radius drawing - Added in-editor light envelope drawing. Outer circle is max envelope, - inner fullbright radius. Optional classic mode emulates the similar drawing - from Rituals and Ravens tools (not q3map correct, easier for the level designer - to understand/legacy). - - NOTE: 'angles' is q3map2 only - NOTE: could manipulate angles directly from the views (2d and 3d with some handles) - - NOTE TO SELF: - hey guys .. just a quick question if you don't mind .. I'm trying to track a Gtk-WARNING .. is there a way to make those apps cause a break to track them easily ? - just run your app with --g-fatal-warnings - - TODO: add new bitmap to win32 & linux setups - TODO: don't use exports for the plugin toolbar, use entry functions - do something like CPlugIn::InitBSPFrontendPlugin - TODO: botclip is broken with the new Brush_Ray code - - initial ChangeLog for the patch: - - 28-09-2002 - Arnout - + Added 'angles' support for models (misc_model/misc_gamemodel). - + Prevented pivot drawing of model from scaling and rotating. - + Cleaned up the dropdown boxes in the preferences a bit (all use - tables now, so not multiline). - + Added 'Classic Key Setup' option to camera paint select configuration, this - drag-selects with ctrl+alt instead of shift. - + Changed XYWnd::PositionView to position on the center of the - selection, not on the mins. - - 27-09-2002 - Arnout - + Added in-editor light envelope drawing. Outer circle is max envelope, - inner fullbright radius. Optional classic mode emulates the similar drawing - from Rituals and Ravens tools (not q3map correct, easier for the level designer - to understand/legacy). - - 26-09-2002 - Arnout - + Upped MAX_TEXTUREDIRS to 256 (from 128). - - 25-09-2002 - Arnout - + Fixed patches not being drawn in XY window with colour of parent - entity. - + Made paste to camera snap destination spot snap to grid. - - 18-09-2002 - Arnout - + Changed Select_Reselect to be much faster. - - 12-09-2002 - Arnout - + Fixed curve point drag-selection area not showing properly in XY - views. - + Fixed size info breaking over 9999.9 units. - + Fixed AllocateSelectedPatchHandles not setting patchesmode to - ESelectedPatches. - + Changed the horizontal and vertical tc shift spin control to have a - limit of 8192. - + Moved SPoG's implementation of redisperse cols to a seperate function - and reinstated the old code. - + Added 'Paste to Camera', shortcut Alt+V, which pastes the contents of - the clipboard to the current camera origin. - + Added centerview functionality to 4 window mode. Ctrl+tab will focus - on the selection, or if non existant, on the camera. - - 11-09-2002 - Arnout - + Made sure settings set in savedinfo.bin get initialized to their - proper defaults. - + Added botclip filter (filters *botclip* and *monsterclip*). - - 10-09-2002 - Arnout - + Removed .reg from normal map saving, can only save as region - using 'Save region'. - + Added outline style cycling (j) cycle between z buffered outlines and - selected colour rendering. - + Added colour dialog to pick the colour of selected surfaces in the - camwindow. - + Third coordinate for clip points now gets set to the center of the - selection. - + Changed arbitrary rotation dialog to accept negative angles as well. - + Changed texture alignment dialog to accept values up to 2 decimal - points. - + Fixed entity inspector to say 'Textures:' in the window title. - NOTE: still broke in floating window mode - + Changed entity inspector so that tab doesn't clear the epair value - field anymore, so it retains the value while jumping to it. - + Disabling camera paint-select now returns selection behaviour for groups to - the old behaviour as well (shift+click selects whole group). - + Changed load_plugin_bitmap to load bitmaps from g_strAppPath if - g_strGameToolsPath fails. - + Added plugin toolbar and api. - + Fixed m_pfnCommitBrushHandleToEntity, wasn't creating brushes - properly (well, not at all really). - - Older changes: - Arnout - + Added misc_gamemodel drawing. - + Ported camera paint-select over from 1.3. - + Fixed statusbar display of text (removed a bunch of \n's). - + Added area selection in 3d view for patches. - - 30/09/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=556 - quickfix crash bug - - 27/09/2002 - TTimo - - more CORERADIANTDIR cleanup (q3data) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=602 - added cascading to the entity submenu (doesn't cascade the main menu, only the sub ones, NPC_* for instance) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=556 - with clip and caulk filtered out, won't be selected anymore in camera view (i.e. selecting invisible faces) - added SF_CAMERA to the flags in the selection process - cleanup up various ugly syntaxes in the selection code: - don't ever do if (flags == SF_SINGLEFACE) on a bitmask and assert that the other flags will always be NULL - don't do arithmetic on bitmasks: - if ( (flags & SF_ENTITIES_FIRST) && t.brush == NULL) - return Test_Ray (origin, dir, flags - SF_ENTITIES_FIRST); - is WRONG - using flags & ~SF_ENTITIES_FIRST is the appropriate way - - 23/09/2002 - Riant - - new IS scripts to go with recent media updates - Riant & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=615 - reworked the fix to use "caulk_shader" in .game - updated IS .rul script to generate special values for Sof2 and JKII - - 21/09/2002 - Riant - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=595 - more texture compression, dialog and settings - Michael Schlueter - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=592 - fixes to the Linux build system, exclusive q3 or wolf working now - - 22/08/2002 - EvilTypeGuy - - Fix @*$&)@)$$ memory leak of my own doing, yes it's really been in there this long. - This should help memory usage drastically, especially when flushing & reloading - the same sets of textures, GtkRadiant's memory usage no longer becomes heinous. - - 14/08/2002 - EvilTypeGuy - - Fix build on some linux boxen by including qertypes.h for proper boolean type declaration - - -- release-1_2_10 - - 16/08/2002 - TTimo - - STVEF media update finalized (some .def) - - 1_2 Core Update for shader manual update - - in JKII, typo with nar_shader? replaced by nar_shaddar, with proper support in update too - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=530 - Q3/TA media update with cleaned up shaders - - validated the update content by a diff between 1.2.9 + 1.2.10-update and 1.2.10 full - - added a DO_NIGHTLY_BOOL to setup.rul AND a warning during setup about update content for games that are not installed - - built 1.2.10-sof2, SoF2 full install - - 15/08/2002 - Michael Schlueter - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=590 - added the option to build a Linux setup with the debug binaries - - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=530 - cleaned up shaders, done nightly setup update on Linux - updated Linux nightly for 1.2 to use /usr/local/games/GtkRadiant-1.2 as default base - - using version 1.2.10-update. Full Sof2 setup will be 1.2.10-sof2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=426 - don't straffe when using Ctrl+Shift(+Alt) - - camera.so RTCW plugin in Linux setup - - quickfix to non-initialized var in camera code - - awfull piece of work that had been completely left out, nightly elements for JK2 and STVEF - added JKII media update and STVEF media update (for the DIR_GAME elements) - JKII nightly is finalized - - 14/08/2002 - TTimo - - fixed a missing file - - Linux build quickfix - - fixed silly rendering bug - - added pref to force texture compression off (hey why would you do that??) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=466 - fixed MAX_POINTS_ON_WINDING overflow in q3map (and relevant code to handle in radiant) - - 13/08/2002 - TTimo - - cleared up notexture (dead code) - - cleaned up QERApp_LoadTextureRGBA gamma table init - - having a shot at 1.3 texture compression - sees the extension, binds the texture with the currect setting - but rendering is fucked .. someone explain? - - 08/7/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=586 - search and destroy Q3Radiant -> Radiant - - 07/7/2002 - SCDS_reyalP - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=526 - wolf_entities.def update - - riant - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=548 - STV:EF updates - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=541 - SOF2 updates - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=584 - JKII updates - - 06/7/2002 - Riant - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=541 - Sof2 patches and IS setup - TTimo - - game pack prompt asking about STVEF, fixed - - mp_examples was leaked and non lighted, fixed - - imagepng.dll goes into Sof2 install / modules, and not in DIR_CORE - - libpng12.dll needs installed only with Sof2 pack (added 'SOF2 Pogram DLL') - default texture scale is 0.125 - - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=582 - nomipmap -> nomipmaps in shader manual - - removed libs/pak, this was still being linked in to Radiant, but not used at all - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=580 - .PK3 are recognized along .pk3 files (strcmp ->strcasecmp) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=386 - added the RTCW camera plugin to IS setup - - Michael Schlueter - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=581 - GL warning fix - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=567 - GL font display fixes (mostly Linux) - applied the changes with some tweaking - - 31/6/2002 - TTimo - - compiling the camera plugin on Linux: - move the GUID and other misc compatibility definitions to include/misc_def.h - GetTickCount being used in camera.so, this is from radiant/missing.cpp (unresolved) - -> use QGetTickCount instead (in main function table) - - 30/6/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=530 - cleaned the .shader from 'light 1' statements - updated the IS script for the updated .shader - - 17/6/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=541 - Sof2 support, PNG format - wrote imagepng module, dynamic dependencies to zlib and libpng - changes in the core: - some hardcoded to "sof2.game" for png interface loading and extensions - in GetTextureExtension, killed outdated support for texture plugins - if ! "sof2.game", png is not loaded, support disabled - http://zerowing.idsoftware.com/libpng/ - correctly configured for VC build (post build steps and dependencies) - is required on win32 to build imagepng - - added m_pfnGetGameFileName to the main function table (was needed for png stuff) - - cleaned up the QERApp_LoadTextureRGBA path - using (unsigned char* pPixels, int nWidth, int nHeight) - cleaning up internal access path - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=386 - camera plugin for RTCW - TTimo: wrote the .dsp, post build steps etc. - IMPORTANT: you need to have RTCWRADIANTDIR env variable pointing to the RTCW Radiant files - (default C:\Program Files\Return To Castle Wolfenstein\Radiant) - - - 12/6/2002 - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=299 - MP/SP pk3 filtering in VFS - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=386 - .camera support: splines library, camera plugin - TTimo: portability fixups, cons build, guarding pragma, __cdecl BOOL - virtual functions but non-virtual destructor - declaration with no type - int idCameraFOV::start - control reaches end of non-void, making it void - enumeration not handled in switch - no _MAX_PATH, the portable one is PATH_MAX - implicit declaration of int _fullpath - for(int i = 0; .. - struct _IO_FILE has no member named '_bufsiz' - stricmp -> Q_stricmp - attempt at implementation in .h file (InitIglToQgl) - camera stuff still vastly broken (particularly on Linux), need to check in because of new fixes incoming - djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=17 - quick fix to spawnflags getting corrupted when multiple entities selected - (doesn't completely solve the problems we have with spawnflags yet though) - -=============================================================== -END -- merging release-1_2_9 -> merge-post-1_2_10 into trunk - END -=============================================================== - -12/12/2002 - Hydra - - #197, HL support update - -11/12/2002 - TTimo - - added cmdlib dependency to mapq3.so (fixes unresolved) - -25/10/2002 - Hydra - - vfsGetFullPath() can now (optionally) search PK3/WAD files - - Half-life map loading is now un-borked (my original patch worked - but some conditional code in the patch was incorrectly applied. - That, coupled with the missing vfsFileExists and vfsFindFile replacements) - - A patch to imagehl/lbmlib.cpp/LoadIDSP() was missed out, causing all sprite - models to be reverse-rendered (due to an inverted alphamask) - - Renamed HydraToolz to HydraToolz-HL as it's half-life specific - changed project files and renamed all appropriate files and directories - (for the merge, just delete contrib/hydratoolz and apply the diff) - - - Comments on previous notes: - - - TODO: need to rationalize where the modules are placed and identify HL specific modules - (this affects the build system / post build step too) - imagehl and spritemodel are halflife specific and can be placed in - either $coreradiantdir/modules or $hlradiantdir/modules - I've updated the .dsp files so that they are copied to $coreradiantdir/modules - spritemodel can actually be used for other engines, not just HL so it makes sense - to keep it in $coreradiantdir/modules - hydratoolz is a half-life specific plugin and must go in $hlradiantdir/modules as it - is NOT to be used for any other engines. I've also updated the "about text" to - reflect this. - -14/08/2002 - EvilTypeGuy - - fix build process for textool plugin on some Linux boxen by including qertypes.h - -11/06/2002 - TTimo - - spritemodels in build system - - applying HL setup patch (att 270, bug 197) - - the templating went one filename seperator too far, causing all *.fgl to be modified .. - fixed so that we only have the relevant changes - - modules added to main Executable Files, TODO for later will need to identify what is HL specific - - .game generation: don't want enginename yet, gamename is ok - - updated HL .game generation for eclass_singleload and no_patch - - update hydratoolz location in setup - - update maphl in synapse.config - -07/06/2002 - TTimo - - realized that \func doesn't work in doxygen, should be \fn (updated everywhere) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=197 - applying the HL patch (see original list of changes below) - - ugly eclass API changes - eclassfgd/plugin.cpp.rej, eclass API changes involved, a bunch of .rej - SupportsMultiple tries to send configuration information from the eclass format file module to the eclass manager - dropping it, using a proper configuration node instead (eclass_singleload) - - added "no_patch" prop to disable patch support - the patch toolbar prompts are only present in prefs if there is patch support - otherwise everything is force-disabled - - PFN_VFSFINDFILE PFN_VFSFILEEXISTS: - one of the problems we have is that the 'manager' code and file format code are in the same module - (i.e. vfspk3 / vfswad: two formats, but the manager part is pretty much the same) - vfsFindFile(relative filename): - this worked by searching through the list of loaded pk3/wad files for the file - then trying to search through the search directories - - wasn't properly documented about what it does / how is the search performed - - not consistent with existing code, duplicate of vfsGetFullPath for the most part - can't be added to the VFS API as-is, it would confuse the interface - - usage of vfsFindFile in the code doesn't justify the way it proceeds for search - foxing it, replacing by calls to vfsGetFullPath - vfsFileExists(relative filename): - returns wether a file exist, can be flagged to search in pk3/wad or straight filesystem - - this is a duplicate / particular case of vfsGetFileCount - foxing it too, we need to extend and update vfsGetFileCount instead - - mapq3: the changes completely fucked q3 map parsing - need reorganization. same module provides parsing for all .map based formats - we use wrappers around the actual calls and globals in the module to select formats - MAPVERSION_Q2 and MAPVERSION_Q1 don't need to be there yet, they are not supported - MAPVERSION_HL means WC >= 2.2 - (when introduced, MAPVERSION_Q2 would be Q2 or qer+hl plugin (same)) - MAPVERSION_HL uses "maphl" minor name (instead of mapq2) - cleaned up the Q3 read/write code that got broken - cleaned up various commenting/hack that deal with Q2!=HL format .. we'll see about Q2 when we actually do it - bad cut and paste from cmdlib code, using actual dependency to cmdlib instead (see below for some cmdlib updates) - - took out all SafeRead SafeWrite code from cmdlib, removed annoying cmdlib dependency to Error function - all file access go through VFS module, the cmdlib 07/06/2002 15:47file code was way old - - radiant/points.cpp pointfile code changes (that's used only for non-monitored compiling now) - - applied patch 267 (hydratoolz fixes) - - commented out some bworldcraft flagged stuff in mapq3/parse.cpp - - updated the .dsw .dsp to compile and copy HL stuff - - TODO: need to rationalize where the modules are placed and identify HL specific modules - - TODO: seems to be a synapse crash when unloading plugins (hydratools) - (looks like I didn't look at the plugin unload code yet actually) - - TODO: make sure HL setup puts eclass_singleload="1" and no_patch="1" - - TODO: WATCHBSP_KEY and TEXTURE_KEY hardcoded for HL need cleanup - - TODO: imagehl duplicates some image functionality - imagehl is supposed to be only for HL-specific image formats - it 'adds' the required formats to the stuff that image makes available for everyone already - - TODO: HL doesn't have a BSP menu! - - TODO: rename mapq3/ into map/, the map module handles all .map formats - - TODO: it's likely that we only need a vfs/ module instead of vfspk3/ and vfspak/ - think about it, see if we really act on this (or do we need to abstract the manager and some file format modules) - - TODO: HL synapse.config needs to use maphl - - TODO: wtf is enginename="quake2" in hl.game - - TODO: I don't have a sample HL map to play with, so I didn't test the changes against - -05/06/2002 - TTimo - - fixups to make 1.3 start (Q3 mode) - - turned off C++ exception support in the modules/plugins, as we don't use it - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=543 - exit properly if missing chunks in synapse.config, don't crash - - Hydra - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=558 - fix for version check in release build - - ====================================================================================== - -- http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=197 - HL support patch - ====================================================================================== - 04/6/2002 - Hydra - - Patched in some CVS changes and fixed a little issue with the - new entity file loader code. - - 28/5/2002 - Hydra - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=544 - Selected Entity Bounding Box obscured by brushes fix. - - Moved the "wad" keypair creation code from the Map module into - a new plugin called HydraToolz, this means that wad keypair is - done manually by the user, as in fact it should be. (as the - order of the wads is actually important). - - Fixed a problem with the wads in the wad list being re-ordered. - - 27/5/2002 - Hydra - - Created an inital implementation of a sprite model plugin. - According to the powers that be, it seems creating a model - plugin is hackish. - It works ok, but there is no way to attach models (sprites if you will) - to non-fixedsize entities (like func_bombtarget) - Also, I can't get the alpha map stuff right so I had to invert the alpha - mask in the spr loader so that 0xff = not drawn pixel. - - 17/5/2002 - Hydra - - "Wad" keypairs are now used when loading a map and speeds up map loading - significantly. This sorts out quite a few issues that could otherwise occur. - - Map loader now uses textures from wads listed in the the "wad" keypair first. - - Added a texture name mapping cache system to the .map loader - this significantly improves load times of maps that don't store texture - names along with paths (e.g. "mytexture" not "mytextures/mytexture".) - - Added vfsFileExists() to the vfs table (for above) and added it to - vfspk3 and vfswad - - Map loading and saving times are printed to the console. - - Wad file names from the "wad" key pair are logged to the console when - a map is loaded - - The user is informed if the textures loaded were not found in the - wad files in the "wad" keypair. - - The user is informed if the textures was not found in any wad file at all - (Q2/HL only, the shader module still gives you similar information for other - games when a shader activation fails) - - - 8/5/2002 - Hydra - - Added basic support in mapq3 for reading maps saved by Worldcraft 2.2+ - in .map format (It uses [ ]'s round some of the texture co-ordinates) - TODO: do we need to be able to save a map in this format too ? - - Added support for loading ZHLT style point files (*.lin) - - Added wad filename information when loading textures. - (This helps take the ambiguity out of which wad files textures come from, - so that we can correctly setup the worldspawn "wads" e-pair manually.) - Note: This will be removed when the "wads" worldspawn key is built by radiant. - - added vfsFindFile() to vfs table. - - VFSWAD: vfsLoadFile() no longer ignores paths when loading textures - (this was by design, but the design has changed for the better) - - When loading a Quake2 map file, vfsFindFile() is used to find the actual path of - the shader/texture being loaded. - This fixes all the weird issues that crop up when we were able to use non - wad-relative texture names () and wad-relative(/). - (such as having an image loaded twice in memory.) - We also now get the correct shader name in the suface inspector too. - Note: not sure if this code should stay in the map parser, or wether it should - be moved to where shaders are first initialised. - Note: maybe this needs to be when a halflife map is loaded, not specifically a - quake2 map file. - - added EClass_SupportsMultiple to the EClass loader API. - Note: this is poop. FGD files can be additive but radiant makes it so they can't be. - This function would not be needed if the eclass loader itself took care of the init, - rather then the manager taking care of the init. Also note that if the loader were - to take care of the init then FGD files *CAN* be additive, as it's not down to the - format of the FGD files. However, it'll do for the moment because all the supplied - FGD files that come with halflife and it's mods are meant to be used one at a time. - - removed support for having an additional (not external) eclass loader. - Just ifdef'd for now, grep for USEADDITIONALECLASSLOADER. - We never mix entity definition formats and synapse.config allows us to just have the - right one and also there is no mechanism for setting g_bHaveEClassExt anymore. - - Texture subset on by default for halflife. - - default texture scale is now set to 1 instead of 0.5 for halflife. - (needs to be 1 for q1/q2 too) - - patch toolbar disabled by default for halflife and it's also disabled - in the preferences so it can't be turned back on) - (needs to be 1 for q1/q2 too) - - bsp monitoring disabled by default for halflife - - When you drop a light entity the epair "_light" is used instead of "light" (halflife specific) - - removed -fs_game additions to the map compiler commands; ZHLT doesn't support it. - - saving of contents/flags/values in q2 format maps disabled (ZHLT doesn't like em !#?!) - TODO: re-enable for Q2 (but not halflife) format maps when we can - can figure out what game/engine combo we're using from within a module - - configured mapq3 to have dynamic VFS API too - - Added halflife shaderlist.txt parsing back in, it's actually useful - afterall (for editor shaders). - ====================================================================================== - -- end HL support patch - ====================================================================================== - -01/06/2002 - TTimo - - merging 1.2.7 -> 1.2.9 changes into 1.3, merge notes: - - the win32 .dsp are a bit different, using the $(CORERADIANTDIR) post build commands now - - merged in the JKII/STVEF hardcoded chunks, should probably check that everything is still fine on that end - was setting the "dir" epair in project files intead of "gamename" like all other games? - (which should really be "fs_game" anyway, I wonder who decided to call it "gamename") - - rebuilt a setup. we have a problem with RADIANT_MAJOR RADIANT_MINOR it seems - TODO: setup needs to use GtkRadiant-1. as basename in start menu, and base for installation - C:\Program Files\GtkRadiant-1.3 and C:\quake3\Radiant-1.3 etc. for the game packs - TODO: add HL setup chunks! - -=============================================================== --- merging release-1_2_7 -> release-1_2_9 into 1.3 -=============================================================== -28/5/2002 - TTimo - - final fixes for Linux 1.2.9 setup - -27/5/2002 - TTimo - - bug 521, q3 entities.def trigger_hurt fix - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=542 - default texture scale is configured in .game - defaults to 0.5 (q3/wolf) if nothing specified, under the prop "default_scale" - removed the item from the prefs dialog too - updated the nightly setup to put the proper param in JKII .game - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=509 - changing texture window scale changes selected brushes texture - re-selecting the previous texture can be done, but is a bit tedious to write - made sure we deselect before re-init of the tex window view - - fixed linux setup code bug. won't be any update, only a full release on linux - -26/5/2002 - TTimo - - parallel cons working at last! was a problem with the targets list ('Default' command) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=515 - using the eclass extents for the box if model can't be found - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=435 - changed the submenu cascading params to avoid the overlap (we fit less stuff now obviously) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=540 - that sigchld handler is only used on Linux to report the run times - since we are rewriting the whole BSP code stuff, we can drop this for now - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=538 - removed that prompt and display - - we build radiant.x86 in cons scripts, updated the setup code - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=526 - updated the setup script to install new wolf_entities.def - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=302 - added q3map2 URL to global.xlink, updated Linux setup - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=465 - printing q3map version info through the net stream - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=539 - fixed various media, some related code, and Linux setup - - fixed watchbsp.cpp "jk2.game", was breaking game spawn for wolf (needed else if) - - SCDS_reyalP - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=504 - fixed bobtoolz vis viewer to work with RTCW (BSP version) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=526 - update of the Wolf entities file - -25/5/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=164 - corruption on exit, tried to look some more. Cleaned up some source, need looking at Gtk code closer - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=536 - cleaned up SHADER_NOT_FOUND SHADER_NOTEX internals some more - added a clean error exit in case this happens, fixed a crash that would happen anyway (Patch_LODMatchAll) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394 - cleanup/sanitize of the pattern filtering code, it was ugly. did some doxygen documentation - fixed part of the print XY code, more broken stuff showed up, dropping it - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=503 - region compiling was indeed fucked, spog b0rkage - fixed so that it works again - denying compile with camera out of the region - reworked SelectBrush to deal with regioning and select the right brushes - -24/5/2002 - TTimo - - Linux build fix - -23/5/2002 - Riant & TTimo - - STVEF patch and setup scripts - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516 - moved error handling code to it's own file radiant/error.cpp - compiled with UNICODE define (that's why I had to isolate), and process the error string - so that Gtk can print it (that's only relevant to win32) - -22/5/2002 - TTimo - - quickfix, cleanup of the console verbosity - -11/5/2002 - TTimo - - final IS script updates for JKII game pack, version 1.2.8-jk2 - - fixed a bad karma #ifdef _DEBUG chunk in Texture_NextPos (causing crash of release build) - - added web url support in .xlink files (strstr on http://) - -10/5/2002 - TTimo - - cleaned the build step copy from $(QUAKE3RADIANTDIR) to $(CORERADIANTDIR) - - system shaders auto-load: display 'system' in the prefs - - force BSP monitoring off in jk2 mode - - cleaned up web update check, added HL (3) and Jedi Knight II (number 4) (on the web database too) - - updated IS setup script for mapextras.pk3 - Riant - - system shaders auto-load in prefs - Raven - - mapextras.pk3 as replacement for system.pk3 (system editor textures) - -8/5/2002 - Riant - - game pack and patches for JKII support - TTimo - - .game additions to specify .shader path (shaderlist and shader scripts) - NOTE: if we ever use q3map for JKII compiles, that would need to be propagated - - reworked the shaderlist to list all the included shaders - - built a system.pk3 pack for textures/system/ and textures/radiant/ (misses a few pieces still) - - MP / SP mapping mode toggle, SP ignores mp_*.def MP ignores sp_*.def - - fs_basepath does not get added during BSP command expansion for JKII mode - - more verbose on script location and junk.txt location when monitored compile is disabled - (the BSP compilation WANTS to be rewritten, it's getting VERY URGENT) - - JKII game back IS setup lands - -7/5/2002 - TTimo - - using radiant.x86 as Linux target (instead of radiant, didn't fit with the setup procedure) - - bumped version tag - - TODO: bug #453 code needs backported from 1.3 - -6/5/2002 - TTimo - - fixed typo in plugins/mapq3/write.cpp Map_Write - g_count_entities = 0; instead of g_count_brushes - - more fixes which showed up while merging this with 1.3 - --- release-1_2_7 ----------- tagged and Stable-1_2 merging into trunk - -02/5/2002 - Gef - - added filtering on unselect for newly created brushes/entities (bugzilla: #374) - SPoG - - added undo for pasted/cloned brushes - -============================================================ --- end release-1_2_7 -> release-1_2_9 merge -============================================================ - -15/05/2002 - TTimo - - rewrote the ref count code cleanly, added some elements to design and todo - - wrote the core shutdown code of synapse, 1.3 exits cleanly without crashing (well, in most cases it seems) - -10/05/2002 - TTimo - - began writing proper unloading and shutdown of synapse (see libs/synapse/docs/unload.txt) - design doc started, non active modules are unloaded after startup - need win32 implementation of ReleaseSO - - quickfix on win32 (ReleaseSO) - -07/05/2002 - SPoG - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=512 - - cleaned up strHomeMaps and strFSBasePath stuff - prompts for maps, models, sounds etc are fs_game-dependant - - =========================================================================== - -- merging Stable-1_2 between Stable-1_2-tag and release_1_2_7 into trunk - merge ChangeLog - ============================================================================= - 07/05/2002 - - using RADIANT_MAJOR_VERSION and RADIANT_MINOR_VERSION for the version info, this was conflicting with synapse - - - m_strHomeMaps - http://zerowing.idsoftware.com/viewcvs/viewcvs.cgi/GtkRadiant/include/qertypes.h.diff?r1=1.27&r2=1.28&only_with_tag=MAIN - http://zerowing.idsoftware.com/archives/gtkradiant/2002-February/002170.html - posted on the ML, bringing it back in from 1.2 - - setup scripts: - easily merged, as the 1.3 scripts have not been touched mostly - - qe3.cpp conflict: - 1.2 tweaks stuff in the QE_*Project* functions - 1.3 has them mostly commented out - applying manually where relevant - the project settings stuff is very different, and the changes can't be applied as is - given the fixes I had to do in 1.2, I'd expect the current 1.3 version to be fairly broken - a complete kill and rewrite of the prefs/project stuff might be our option anyway - http://zerowing.idsoftware.com/archives/gtkradiant/2002-May/003038.html - qe3.cpp QE_InitVFS conflict: - 1.3 has some changes when creating the files in a new userprefix (ex. ~/.q3a/baseq3/scripts /maps /maps/prefabs etc.) - merged by hand, probably needs to be checked - qe3.cpp OpenDialog SaveAsDialog conflict: - commented out in 1.3, getting rid of it completely - - preferences.cpp conflict: - 1.2 adds CUSTOMSHADEREDITOR_KEY pref - 1.3 uses a completely different syntax for prefs - preferences.cpp conflict: - prefab path pref changes conflict with 1.3 pref syntax - applying changes manually to 1.3 codebase - - pmesh.cpp conflict: - 1.2 adds pref to group / not group patch thickening - 1.3 changes the way we manipulate entities around that code - merged manually, would be worth checking that the thicken pref works - - pluginmanager.cpp conflicts: synapse completely changes that part - on relevant 1.2 thing is the removal of pfnRadiant_Free - - map.cpp Map_ImportEntities conflict - 1.3 has bug 453 map conversion promt that was not backported to 1.2 (caused merge to conflict a bit) - usin 1.3 code and checking 1.2 changes manually - - using radiant.x86 as Linux target (instead of radiant, didn't fit with the setup procedure) - - 06/05/2002 - not merging in .dsw .dsp - an eclass.cpp fixed moved to eclass_def.cpp - mainframe.cpp is always a bitch to merge, sent several mail comments to list about conflicts that arose - MainFrame::OnFileSaveas needed some updates that were not in the diff (correct default prompt) - (same for MainFrame::OnFileSaveregion) - MainFrame::OnFileNewproject conflicts a bit, changes have been made in 1.2 and 1.3 - changes in 1.2 seem more crucial, using the 1.2 version, and patched the 1.3 manually over it - (might need to be checked, bug #506) - - TODO: need to check for parasite g_free that I added back from the file dialog - - propagated ChangeLog from Stable-1_2 - ============================================================================= - 02/5/2002 - Gef - - added filtering on unselect for newly created brushes/entities (bugzilla: #374) - SPoG - - added undo for pasted/cloned brushes - TTimo - - shift+left click to open shader editor no longer selects the texture on the way - (this was unstable, pCurrentShader could become NULL somehow) - - editpad bindings were completely broken - attempts to make it work again failed - taking it out - changed the prefs, on win32 you select between internal shader editor or win32 .shader binding - we have lost the ability to jump to a given line, if someone has a good solution for line jumping, let me know - - one more fix to the MAJOR / MINOR safe checks stuff - - bug #500: oooogly, I removed a line which I should not have :) - - 01/5/2002 - TTimo - - "Save selected.." load/save in fs_game sensitive directory too - - removed a bunch of unused/broken project settings items - removed most of them actually .. project settings are .. ahem - - added an optional 'go to url' button in gtk_MessageBox - - 30/4/2002 - Gef - - fixed lod drawing of selected patches when patches are filtered - - 29/4/2002 - TTimo - - bugzilla #467 - make patch inspector deny space textures - make mapq3 write code drop space textures - - bugzilla #132 - removed remotebasepath and texturepath - rewrote the Textures > Load Directory (which was kinda relying on texturepath) - - bugzilla #355 - uploading editpad zip to qeradiant.com misc/ in files section, replacing the win32 message about editpad - added editpad quote in qer.com totd - - fixing the map load/save dialogs to work correctly with mod settings on win32 (was done on Linux and still broken on win32) - - - 26/4/2002 - Gef - - fixed patches losing their shader if outside region when calling flush/reload - (bugzilla: #492) - - blocked textures with spaces from loading in Texture_ShowDirectory with a warning - (bugzilla: #467) - - fixed a dud shader (liquids.shader -> textures/liquids/ripplewater2_back) didn't have - the textures/liquids prefix - - 25/4/2002 - Gef - - fixed a broken image link in the shader manual (bugzilla: #486) - - changed prtview to use ~/.radiant//prtview.ini instead of - ~/.q3a/radiant/prtview.ini on linux - - fixed prtview loading/saving config (bugzilla: #424) - TTimo - - removed QERApp_RadiantFree from the function table - we can malloc and free across modules configured correctly for the CRT (Common Runtime DLLs) - cleaned up related broken malloc / free strategy in the plugins (vfsLoadFile uglyness) - - added main build date and version to curry / pk3man / prtview - - 23/4/2002 - SmallPileOfGibs - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=229 - flush and reload was affecting texturing of selected brushes - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=489 - File > Check for update menu item, jumps to the website and checks for update - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=431 - win32 part, RADIANT_MAJOR RADIANT_MINOR written out by setup - - more stuff on File > New Project and common mod setup issues (not finished yet) - - 22/4/2002 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=431 - reworking a bit the installer stuff - wrote the version checking - needs testing on win32 (RADIANT_MAJOR and RADIANT_MINOR are required in the install now) - - 21/4/2002 - TTimo - - trying more seriously to get a new nightly out - updating the ChangeLog for current 1.2.7 from this file - cleanups, browsing through the bugs to close/update/fix - - http://zerowing.idsoftware.com/bugzilla/showattachment.cgi?attach_id=197 - I kinda fixed that myself already, going through the diff and applying the missing stuff - creating the prefabs/ dir in QE_InitVFS - - added a line about the games dialog / auto-select at startup in the dialog frame - - 15/4/2002 - TTimo - - cleaning some old commented out map load code - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=477 - on Linux: - - strHomeMaps was init without taking care of m_strFSGame - - SaveAsDialog was not using strHomeMaps - NOTE: should strHomeMaps be spcific to Linux, or we will do better if we unify - need similar checks on win32 - - 13/4/2002 - TTimo - - kicking the source to generate new doxygen on zerowing - - 09/4/2002 - Gef - - setting the sel_mode accordingly when (i)nverting selection, verts were being drawn when - they shouldn't have been - - 05/4/2002 - Gef - - fix File/New Project for mods so it doesn't fail if the dir exists (bugzilla: #459) - - add Linux-isms for New Projects & read/write permissions... - note: for a total conversion, basepath needs to be manually set - - prevent opening multiple internal shader editor dialogs - - added preference for using a custom shader editor - - set horizontal scrollbar to be automatic instead of never for entity keyval list (bugzilla: #4) - - added a call to Select_Reselect() in XYWnd->OnViewEntity() to make sure its modifying the - current selection (bugzilla: #436) - - fixed entity dialog passing events through to main window (bugzilla: #454) return values - were backwards - - patching in the .pfb extension adding stuff (bugzilla: #259) - - fixed thickened patches not being grouped (bugzilla: #226). this was supposed to be happening - anyway, the entity create code was called before the patches were selected - - 02/4/2002 - EvilTypeGuy - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=457 - add entity #X and brush #X comments back to saved .map files - - 24/3/2002 - Hydra & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=444 - only show empty alpha channel warning if the tga texture is actually 32 bit - (24 bit would always have empty alpha, the warning was useless in this case) - - 19/3/2002 - Gef - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=217 - - Set show value to true for angle and movement velocity sliders in preferences - - Increased the maximum value of angle velocity from 6 to 100 - - 18/3/2002 - SPoG - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=419 - fixed File->Save with region active acts the same as File->SaveRegion for ents - - - end merge - ============================================================================= - -16/4/2002 - SPoG - - fixed MDC_XYZ_SCALE value - -12/4/2002 - SPoG - - fixed win32 compile error - vc6 being nitpicky - - fixed refcount init on CSynapseAPIManager - - cleaned up md3model win32 project file - -9/4/2002 - Gef - - added nudging for selected brush and patch vertices (bugzilla: #240) - - added selected brush vertex highlighting - - sorted all the ID_'s in HandleCommand alphabetically to make it easier to track things down - - setting the sel_mode accordingly when (i)nverting selection, verts were being drawn when - they shouldn't have been - -5/4/2002 - EvilTypeGuy & djbob - - patched in djbob's grid minor/major color settings for gridsize < 1 - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=24 - -1/4/2002 - TTimo - - configured md3model to have dynamic VFS API too - - cleaned up texwindow.cpp texture extension loop - - updated current HL media with hl's synapse.config - http://zerowing.idsoftware.com/stuff/HL-media-0401.zip - - checking in new synapse.config for Q3/RTCW - - fixed win32 project files, removed hltoggle.h - - bumped version to 1.3.3 - -31/3/2002 - TTimo - - XML runtime configuration of synapse - uses a synapse.config in the gametools path, we can add a line in the .game to specify the file later on - - various cleanups and removal of dead code - - Linux build system: sanitized CFLAGS, libxml, STLPort and glib include path all in the toplevel Construct file - - removed the 'cons -- halflife' option, the binaries are unified again - - cleaned up image loading - - -29/3/2002 - TTimo - - patching in Hydra's code for Half-Life, builds and runs on Linux, need to quickfix on win32 now - - build system on Linux: some things are still hardcoded into the core, you need a different core - for Q3/RTCW or HL for now. do ./cons -- halflife to build HL mode (build trees are seperate) - - there is no media / install procedure yet, but a zip with what you may need for install is available: - http://zerowing.idsoftware.com/stuff/HL-media-0329.zip - - cvs added all the new files - - patched various things from the patches, don't have a precise list - cleaned up the interface requests, isolated HL specific between TMP_HALFLIFE defines - removed 'tga' from imagehl, two modules providing the same API has unexpected results - - TODO: the image loading is the main problem right now. We should not have any place that scans the - extensions, this is done internally to the image load manager? texwindow.cpp does enumeration of the - minors too .. but that may be legal in this case. - - TODO: synapse config at runtime through XML (rather big piece) - - - fixing build on win32 - bad coding practices: 'for (GSList *choicelst = ..' - added a quick hack include/hltoggle.h for easy switch q3/rtcw or hl compile - (remaining hardcoded stuff is temporary) - - -28/3/2002 - Gef - - added linux pthreads support to tools - - removed old terrain.c and lightv.c from q3map2 Conscript - -27/3/2002 - Gef - - updated cons for q3map 2 - - minor q3map2 fixes for linux compile errors/warnings - - minor warning fix in map.cpp - SPoG - - changed entity_addtolist to add entities to end of list instead of beginning - - added eclass_forname to eclassmanager interface - - fixed setting eclass before model-update for entities loaded from map - - fixed setting bounding box for models after model-update - ydnar - q3map2 - - fixed crash on -connect and other gremlins related to argument processing - - removed flag that prevented Castle's maps from compiling - - -27/3/2002 - - Hydra - - Important Changes: - - - Added VFSWAD modules for extracting textures from WAD files. - - Added ImageHL for loading textures contained in WAD files - - Updated shaders source code so that you can produce ShadersHL.dll - (single minor using #ifdefs) - - MapQ3 source updated so that it can load and save q2 format maps - provides a multiple minors. - - Added EClassFGD for loading FGD definition files - (I documented this code quite well, if you're interested...) - - Added support for iconsprite() settings in the FGD loader, we set - eclass_t->skinpath with the name of the sprite - TODO: write a sprite model plugin. - - Fixes: - - - Fixed incorrect line numbers being reported when script files had // comments in them - - Removed EClass_Create from the EClass manager _EClassManagerTable - - Replaced all occurences of "textures/radiant/notex" in shaders.cpp with a define. - - Fixed a crash in shaders.cpp when there was no default texture. - - Fixed a possible issue with g_bCancel_Map_LoadFile - - Added a crash fix for uninitialised patchMesh_t->pSymbiot - - Core Changes Required for HalfLife Support: - - - Set MAX_FLAGS to 16 to support Halflife's extra spawnflags, adjusted - entity inspector to display the new spawnflags, updated FGD loader - to load them correctly (previously it only loaded the ones with values <8) - (Done without breaking the old Q2 code that was commented out) - - Added GetTokenExtra to the _ScripLibTable - - Kludged texwindow.cpp to allow loading extension other than "tga" and "jpg" - TODO: ttimo, we need something in synapse to help with this. - - Plugin manager requests different API's depending on .game file used. - TODO: this needs to be done on a PER GAME basis, not PER .GAME FILE. - - Shaderlist.txt is not parsed on startup if hl.game is used. - TODO: this needs to be done on a PER ENGINE basis, not PER GAME. - - Cosmetic Changes: - - - Changed MAPQ3's minor_name from "map" to "mapq3" (also adds "mapq2" as a minor) - - Changed XMAP's minor_name from "xmap" to "mapxml" - - Changed VFS's minor_name from "quake3" to "pk3", more inline with VFSWAD now. - - Changed file/Load to file/Import on the menus - - When a shader (Q3/HL) is not found a message is displayed in the console - (only once for each shader that is not found). This is so the user can - quickly get a list of missing textures/shaders. - -26/3/2002 - ydnar - - initial q3map 2.0 source import - new tools/quake3/q3map2 directory - common/qfiles.h and common/surfaceflags.h modified - affects q3map 1.x too, bumped MAX_MAP_BRUSHSIDES to 0x40000 - will need to write the build scripts and compile on Linux too - SPoG - - Re-added dialog prompting user to convert/change-mode/abort when map BP mode - conflicts with project settings - - large entity/models update - +++ include/ientity.h 25 Mar 2002 11:37:54 -0000 - entity module - - interface cleanup - - common #defines for easy transition - +++ include/igl.h 25 Mar 2002 11:37:55 -0000 - opengl module - - Vertex Arrays support - +++ include/imodel.h 25 Mar 2002 11:37:57 -0000 - model module - - interface cleanup - +++ libs/mathlib.h 25 Mar 2002 11:37:59 -0000 - vector macros - cleanup - m4x4 - - documentation of matrix layout - - interface for utility functions for axis-angle and quaternion rotations - - interface for new utilities for specifically transforming points/normals - aabb - - interface for faster aabb-ray test without finding intersection point - - interface for utility to calculate an aabb to contain a transformed aabb - +++ libs/mathlib/bbox.c 25 Mar 2002 11:38:01 -0000 - - cleanup of use of qboolean - - implementation of fast aabb-ray-test - - implementation of aabb-for-transformed-aabb - +++ libs/mathlib/m4x4.c 25 Mar 2002 11:38:02 -0000 - - implementation of utility for rotation matrix from axis-angle/quaternion - - cleanup of implementation of matrix multiplication functions (optimise for in-order array traversal) - - implementation of new utilities for specifically transforming points/normals - +++ libs/mathlib/ray.c 25 Mar 2002 11:38:02 -0000 - - replace use of m4x4_transform_vec3 with new point/normal specific utils - +++ plugins/mapq3/plugin.cpp 25 Mar 2002 11:38:06 -0000 - - rename g_EntityTable using #define in ientity.h - +++ plugins/mapq3/plugin.h 25 Mar 2002 11:38:06 -0000 - - rename g_EntityTable using #define in ientity.h - +++ plugins/mapxml/xmlparse.cpp 25 Mar 2002 11:38:06 -0000 - - buffer-safe dtd path construction (without using string class, in case of unknown bugs) - +++ plugins/md3model/Conscript 25 Mar 2002 11:38:06 -0000 - - remove entity-module files from md3model conscript - +++ plugins/md3model/md3model.cpp 25 Mar 2002 11:38:07 -0000 - - implementation of generic quake-style-model class CModel - - implementation of CModel-derived md3/mdc classes - +++ plugins/md3model/md3model.dsp 25 Mar 2002 11:38:08 -0000 - - remove entity-module files from md3model dsp - +++ plugins/md3model/md3model.h 25 Mar 2002 11:38:08 -0000 - - interface for generic quake-style-model class CModel - - interface for CModel-derived md3/mdc classes - +++ plugins/md3model/md3surface.cpp 25 Mar 2002 11:38:09 -0000 - - implementation of generic quake-style-model class CSurface - - implementation of CSurface-derived md3/md2/mdl/mdc classes - +++ plugins/md3model/md3surface.h 25 Mar 2002 11:38:09 -0000 - - interface for generic quake-style-model class CSurface - - interface for CSurface-derived md3/md2/mdl/mdc classes - +++ plugins/md3model/plugin.cpp 25 Mar 2002 11:38:10 -0000 - - provide support to synapse for loading md3/mdc/mdl/md2 models, and mdl images - +++ plugins/md3model/plugin.h 25 Mar 2002 11:38:10 -0000 - - interface for loading md3/mdc/mdl/md2 models, and mdl images - +++ radiant/brush.cpp 25 Mar 2002 11:38:18 -0000 - - #ifdef remove Group/Brush-Patch-Epair related stuff - - const correctness for ValueForKey interface const change - - add bounding-box update for models in Brush_Build - - remove old brush parsing/writing stuff - - remove old eclass-model loading/displaying stuff - - enable vertex arrays on light drawing - - moved brush is-selected? utility to brush.cpp - +++ radiant/brush.h 25 Mar 2002 11:38:18 -0000 - - comment out interface for old brush parse/write stuff - - comment out interface for brush epair stuff - +++ radiant/brush_primit.cpp 25 Mar 2002 11:38:20 -0000 - - remove old brush-primitives parsing/writing stuff - +++ radiant/camwindow.cpp 25 Mar 2002 11:38:23 -0000 - - moved brush-bbox update for models to brush.cpp:Brush_Build - - bugfix for material colour setting when drawing models - +++ radiant/eclass.cpp 25 Mar 2002 11:38:24 -0000 - - removed old eclass-model checking/loading stuff - - added const checking for Eclass_ForName interface - +++ radiant/entity.cpp 25 Mar 2002 11:38:26 -0000 - - REMOVE THIS FILE - +++ radiant/entity.h 25 Mar 2002 11:38:26 -0000 - - REMOVE THIS FILE - +++ radiant/groupdialog.cpp 25 Mar 2002 11:38:29 -0000 - - change entity creation to not use Entity_Create (function was removed) - - commented groups stuff - +++ radiant/gtkdlgs.cpp 25 Mar 2002 11:38:36 -0000 - - const correctness for ValueForKey - +++ radiant/gtkmisc.cpp 25 Mar 2002 11:38:39 -0000 - - added filetype patterns for mdc/mdl/md2 - +++ radiant/main.cpp 25 Mar 2002 11:38:41 -0000 - - const correctness fixes - +++ radiant/mainframe.cpp 25 Mar 2002 11:38:59 -0000 - - change selection -> merge entity and selection -> separate from entity to go through mainframe class - - implementation of mainframe functions for selection -> merge entity and selection -> separate from entity - - made entity grouping and detail/structural settings undoable - - commented out old groups stuff - +++ radiant/mainframe.h 25 Mar 2002 11:39:01 -0000 - - interface for mainframe functions for selection -> merge entity and selection -> separate from entity - +++ radiant/map.cpp 25 Mar 2002 11:39:04 -0000 - - const correctness fixes - +++ radiant/pluginmanager.cpp 25 Mar 2002 11:39:08 -0000 - - removed model table - - stopped requesting model table from synapse - - request undo table from synapse - - commented out support for IEpairs stuff - NOTE: to be integrated with entity module - - fill interface table for opengl vertex array support - - fill interface table for undo - +++ radiant/pmesh.cpp 25 Mar 2002 11:39:18 -0000 - - cleanup patch cap and patch thicken to create entities using entity module interface (without Entity_Create) - - removed old patch parse/write stuff - - #ifdef'd out patch epair/groups stuff - +++ radiant/qe3.cpp 25 Mar 2002 11:39:21 -0000 - - const fixes - - buffer-safe dtd path construction (without using string class, in case of unknown bugs) - +++ radiant/qe3.h 25 Mar 2002 11:39:24 -0000 - - don't include entity.h, include ientity.h and forward-declare entity-table instead - - include imodel.h but don't forward declare model-table - - include iundo.h and forward-declare undo table - - comment out interface to old patch parse/write stuff - - comment out interface to old brush parse/write stuff - - comment out iepairs header include.. NOTE: to be integrated with entity module/interface - - include eclass interface (we don't have an eclass.h) - - declare interface for CreateEntityFromName (generic useful func) - - declare target/targetname utils interface (we don't have a targetname.h) - +++ radiant/select.cpp 25 Mar 2002 11:39:27 -0000 - - cleanup implementation of entity selection-grouping/ungrouping utlities - +++ radiant/select.h 25 Mar 2002 11:39:27 -0000 - - cleanup interface for entity selection-grouping/ungrouping utlities - +++ radiant/undo.cpp 25 Mar 2002 11:39:29 -0000 - - removed workaround for wierd entity_clone behaviour (changed in entity module) - - avoid using Entity_FreeEpairs (not exposed by entity module) - +++ radiant/xywindow.cpp 25 Mar 2002 11:39:35 -0000 - - const fixes - - cleanup implementation of CreateEntityFromName to be a usful generic utiliy function - - enable vertex arrays in XY_Draw - - enable undo for right-click dropping entities in XY window - TTimo - - various fixes to make the above compile on Linux, checkin to cvs - - fixing some win32 build stuff - - Hydra - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=434 - fixed setSpecialLoad in .def code - -19/3/2002 - Gef - - Modified the fix for LoadImage to be more consistent with other code - - Applied Hydra's fix for empty alpha channel warnings & cleaned up indentations (tabs) in lbmlib.cpp - also added output of the tga type when a tga file fails to load - - Reverted my over complex fix (read; mess) for strtok_r to use strtok instead of manual tokenising - -17/3/2002 - Gef - - Fixed LoadImage API list not being incremented while trying to find image minors, result was - infinite loop when loading images that weren't of the first type (tga) - - Fixed cloning giving dtd errors. mapxml/xmlparse.cpp:ParseXMLStream() was using - g_FuncTable.m_pfnGetQERPath() as the dtds path... disabled validation until spog can check - that my fix is the right solution - - Added simple formatting to xmap file output so that each node has a new line for readability - -13/3/2002 - TTimo - - introduced API List managers - we deal with two types of APIManager now, the ones that matching all minors for a given major - and the ones that require a fixed list of minors - - converted the image loaders to go through a API list manager - - fixed various things in synapse (introduced more bugs?) - - fixed plugins, realized it was still broken - -12/3/2002 - Hydra & TTimo - - EClass_Create in the EClass manager _EClassManagerTable - - removed InitFromText from _EClassTable - -8/3/2002 - TTimo - - some commented out code cleanups - - added eclassfgd/ fgd.so module skeleton - loaded up in radiant core as an optional entity format - added eclass manager code to deal with the new format if present - this still loads .def, the actual .fgd code needs to be written now - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=433 - added a g_strDTDPath global - disabled DTD validation, broken on win32 - - Str copy constructor (const Str &) working correctly with a __strDup - -7/3/2002 - TTimo - - added verbosity in file accesses for CXMLPropertyBag - - more fixes to project lookup - - dropping dtds/ prefix, this is installation dependent - - removed ipluginentities.h, the plugin entities stuff was disabled long time ago already - - cleaned up some old commented out stuff - - proof of concept synapse builtin module: new class CSynapseClientBuiltin allows to have - modules builtin to the application (i.e. statically linked) - adding - include/ieclass.h (eclass loader API) - radiant/eclass_def.cpp (.def class loader, builtin) - radiant/eclass_def.h (.def loade, API public to the core) - - NOTE: radiant/eclass_def.cpp needs to be added to the win32 projects - - quickfix to project file loading ("/scripts/") - - introduced an EClass manager, hooked up the .def builtin module through it - (not yet possible to push new entity format modules, but .def reading is already fully synapsed) - -6/3/2002 - Gef - - Fixed a segfault when getting mUserPathPrefix in CGameDescription::CGameDescription() - - added preferences check for fixing target/name collisions - - fixed a logical error on my part, where setting g_qeglobals.m_strHomeGame in - CGameDescription constructor results in a value from the last file parsed. Moved it - to a more appropriate location, where it gets a value from the selected .game file. - SPoG - - changed g_strGameToolsPath to g_strAppPath in GetQERPath API - - fixed mapq3.dtd - - enabled DTD validation of xmap files - - added mapq3.dtd to setup scripts (not tested) - TTimo - - added OnActivated() to synapse clients, override to put some init code - - fixing default project path lookup and user project increment (again) - - fix to linux setup, no trailing slash in basegame items - (wolf.game and q3.game) - - removed old plugin/modules code, leaving only the synapse implementation - recoded image loading and Map_Import/Map_Export - still some temporary solutions and cleanup work to be done - removed plugin.cpp from the tree / build system - -5/3/2002 - SPoG - - TODO: add default project for wolf to WolfPack CVS module - - changed xml project file load to search for DTD "dtds/project.dtd" under radiant path - - fixed crash in mapq3 on trying to read uninitialised token ptr - - changed .map to be default map format for now - - changed runbsp to not hardcode -fs_basepath - - added -fs_basepath to quake3 default project - - added project.dtd to setup scripts and swapped quakev2.qe4 for default_project.proj (not tested) - -4/3/2002 - TTimo - - merged synapse2 branch back into trunk, checked Linux and win32 builds ok - - updated the .dsp to work with new libxml2 2.4.16 - - fixed broken enginepath guessing, and broken project path rotation / saving - -28/2/2002 - Gef - - Added extra checks for target/targetname collisions - - Find Brush dialog title correction (bugzilla #393) - -26/2/2002 - Gef - - Added Entity_Connect() to entity.cpp to avoid duplicating code - - Fixed target/targetname collisions - entities being cross-linked when copied - Bugzilla #385 : http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=385 - -16/2/2002 - Gef - - cleaned up the kyro gl_point workaround stuff - - taught ClipPoint's (clips & path points) how to draw themselves - -8/2/2002 - Gef - - Added mapxml.so to linux setup - - strip debug symbols option in setup - - removed g_qeglobals.m_strHomeMaps, writing it to project instead - fixes a bunch of re-broken path issues. Also uses fs_game now. - - Minor grid colour in QER Black & Green theme - - Save window's pos/size for all view types in MainFrame::OnDestroy - ---------------------------- on branch synapse2 -4/3/2002 - - modules don't show up in plugins menu, added a dump in console before entering interactive mode - - added compile time def for synapse verbosity - -3/3/2002 - - finished converting all the modules to synapse, disabled old ResolveInterface call - -24/2/2002 - - hooked TexTool into Radiant plugin menu through synapse - - added iplugin.h which I had forgotten earlier - - ported synapse code to compile and run on win32 - -19/2/2002 - - SYN_REQUIRE_ANY / multiple API manager code - can load multiple interfaces based on a matching pattern - converted TexTool to load that way - -18/2/2002 - - added iplugin.h with basic interface for plugins - -13/2/2002 - - synapse on modules currently disabled, - the basics of the code are working fine, need to look at multiple interfaces matches before going further - - started converting shaders, requires conversion of a lot more others - - image converted to synapse - - no longer using GUID in synapse, all done through *_MAJOR strings - HOWTO: convert a module to synapse: - configure it to link against synapse static lib - (+include path to STLPort required) - add #include "synapse.h" to the plugin header - declare the : public CSynapseClient in plugin header - implement it (listing provides and requires, implement the request code) - -12/2/2002 - - vfspk3 converted to synapse - -11/2/2002 - TODO: get rid of all WINAPI crap - - debugged the API dependencies solver to actually work - - added newer cons at the head of the tree - -10/2/2002 - TTimo - - added the basic code for solving API dependencies and requesting the various tables - - more diagnostic printing code fixes - - version checkings - - some more design work (libs/synapse/doc) - -9/2/2002 - TTimo - - some changes to the files layout, cleanup of the diagnostics printing - (stuff's mostly broken right now) - - reworked the complete Sys_Printf stuff to rely on va_list implementation - - include/isynapse.h declared useless and foxed without mercy - - added include/irefcount.h - -8/2/2002 - TTimo - - adding an experimental Anjuta project file to play around with - -7/2/2002 - TTimo - - various fixes to build on linux, listed a bunch of current issues - - fixing terrademo.map to remove broken mapobj~1 -> mapobjects - -- synapse2 branch -- - - propagate the code from old synapse branch to a new branch out of 1.3 tree - (builds and runs on linux, that's about it for now) - ---------------------------- end branch synapse2 - -7/2/2002 - djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=354 - moved all the preferences code to XML - -6/2/2002 - SPoG - - checked all paths conform to: unix dir separators + trailing separator - - changed file dialogs for load/save of maps to default to "mapspath" - - removed OpenDialog and SaveAsDialog, use file_dialog instead - - removed FileSystem paths stored in QEGlobals_t.. replaced by CGameDescription - - removed dependence on EnginePath from preferences, replaced by CGameDescription - - removed hardcoded g_get_home_dir calls for file dialogs - - added validation of project settings entry paths before they are set - -5/2/2002 - EvilTypeGuy - - moved filters.cpp related function declarations to filters.h - and added #include "filters.h" to brush.cpp, csg.cpp, main.cpp, - mainframe.cpp, map.cpp, select.cpp as not all files include - qe3.h and qe3.h is a rather monolithic header this seems to be - a cleaner solution per SPoG's suggestion...Fixes compilation. - - Gef - - contrib/plugins BOOL cleanup (uses qboolean now) fixes X header conflict - - cons update for mapxml - - SaveAsDialog() changed to match path's used in OpenDialog() - - removed radiant/xy.h - moved contents to qe3.h (FilterBrush declaration) - -4/2/2002 - SPoG - - changed QE_LoadProject and QE_SaveProject to load/save xml project file format - - changed request dialog for project files to loop until a valid file is found - - fixed memleaks in CGameDescription constructor for xmlGetProp - - added converting gametoolspath unix format when parsed from game file - - - fixed m4x4 lib to use column-major order (more compatible with opengl) - - added divergence parameter to ray-point intersection test - (now easier to select distant points in perspective views) - - cleaned up modelview/projection matrix manipulations in 2d/3d view - - cleaned up map modules / interface source files a bit - - - added ability to specify map module version when importing/exporting map - - cleaned up file dialog code, returned filename is static and in unix format - - save-as dialogs force a file extension depending on filetype selected - - added filetype manager to support registering custom file types - - fixed loading and cleaning engine path from radiant.ini correctly - -3/2/2002 - EvilTypeGuy - - fixed win32 compilation (userpathprefix is Linux specific) - - ETG & Powzer - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=308 - added preference to allow 'paint drag-select' brushes/faces in 3d camera view - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=389 - added preference to strafe camera foward/back in 3d view while freelook is active - - ETG & RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=388 - patch adds ability to strafe up/down/left right while freelook is active - -1/2/2002 - TTimo - - bumped to 1.3.1-nightly - --- 1.2 stable branch branched here - - Gef & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=372 - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=376 - appplied the patch, corrected the mapspath expansion stuff - TTimo - - linux nightly setup code - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=384 - hacked a corrective action in the nightly setup - - SPoG - - fixed creating region brushes that fill the entire grid for Save Region - -31/1/2002 - - Micheal Schlueter - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=375 - syntax fix to q3map path_init.c - - Gef - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=279 - patch 185 == 186 - tweaking to config stuff in linux setup - patch 187 - Ensures the games directory exists before trying to create a file there - patch 177 - Adds *.cf files & uses them. I think I have all the files in the right places now... maybe - (some additional fixes on top by me) - - ETG - quick fix to shader prefs load - -29/1/2002 - - EvilTypeGuy - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=345 - more detachable menus fixes - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=334 - fixes 'load shaders at startup' preference - - SPoG - - fixed misc_model "modelscale" and "modelscale_vec" support - - TTimo - - upgraded setup scripts to support nightly build - - last minute fix to the modelscale and modelscale_vec code (md3 module) - - ydnar - q3map 1.2.4-y2 - - New features: - - -nopatchfix argument. This disables lightmap patch fixes and makes a map suitable for lighting with -vlight. - - Degenerate patches are treated like broken brushes. They are ignored, warned about, and selected in Radiant if you ran with the -connect option (or from the BSP menu). This was what was causing the "0 valued axis" error some people were experiencing. - - New entity keys: - - "_lightmapscale" key for brush entities (worldspawn, func_*). This lets a mapper scale the lightmap samplesize per-entity. For large constructions, 2.0 or 3.0 is a fine value, and keeps BSP size down and compile times low. For those areas you want to have high-detail shadows, make a func_group and use a value of 0.25 or so. It will scale the samplesize value for the surface's shader (default 16) or the -samplesize argument. - - "modelscale" and "modelscale_vec" keys for misc_models (1.0 = default). This was for proper RTCW support and is available for Quake 3 maps as well. Lets you scale up map models in the world, getting around the MD3 size limitation. The next build of GtkRadiant has SPoG's code to support this in-editor so you can see what effect a scale has. - - Flare surfaces are now supressed from the BSP. They serve no purpose other than add to the vert & surfacecount in a BSP. These surfaces were created silently when a shader has "light 1" or "q3map_flareshader X." Use the new -flares switch when BSPing your map to have them emitted. - - Changes: - - GtkRadiant 1.2.4-nightly version increment. - - Full WolfSDK style lighting enabled with -game wolf, including lightJuniors. This includes linear lights by default (no angle attenuation) and support for the additional RTCW "fade" and "angle" keys, and spawnflag changes, including q3map_nondynamic on light entities. This may require maps being constructed for RTCW with the current toolset to change their light entities. Sorry. :) Note, Wolf-style lighting only works with -light, and not -vlight. - - Vertex light stitching now uses a near-ambient light check for dark vertexes as opposed to lower-than-average fixups. This preserves some shadow detail better while getting the buried verts lit properly. Comments encouraged. - - Surfaces' samplesize are now stored in the BSP. This change makes BSPs generated from this version incompatible with all other q3maps. The upside is that -samplesize N is no longer necessary on the -light or -vlight stage. This feature is necessary to support the "_lightmapscale" key. - - Additional PVS optimizations in lighting. - - Fixes: - - Will compile for RTCW properly (1.2.1-y12 didn't). - - No more sparklies where fog meets brush faces. They're split properly now. - - Crash bug in vlight fixed. - - Vertex light fixups/stitching is considerably faster. - - Vertex light fixups ONLY stitch faces with lightmaps. For pointlight surfaces you're on your own. - - Better snapping logic when merging nearly-coincident vertexes on complex brush windings. - - Bug where the .prt file had some bogus or nearly-borked portals. They're cleaned up like everything else now. - - A few stupid bugs in path initialization. Should work better. Also includes TTimo's fixes to my code so it would work properly on Linux. - - RR2DO2's PCX loading patch for alphamaps. This bug was manifesting itself in the form of offset or incorrect samples being used on terrain entities. - - A ton of other minor little fixes here and there. - -28/1/2002 - - TTimo - - win32 fixes - - 1.2.4-nightly - - djbob - - EClass_ForName fix if malformed name - ----- 1.2.3 linux released - - TTimo - - fixed BSP version depending on game mode in q3map - (home dir guessing is still fucked, have to fix before release) - - fixed q3map init_path.c home path bug on init - - Gef - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=369 - more fixes to texture paths in gensurf - -27/1/2002 - TTimo - - switching to v3 project file, forcing reload of template if non-v3 - need to distribute quakev3.qe4 in setups now (done for linux setup, will have to in win32) - - renamed Main to main in q3map init paths - - fixes the ~/. inits and init order in q3map - - added m_pfnPathForPluginName to the main function table, returns the directory a plugin is running from - used in bobtoolz / curry / pk3man to find various files - see also todo: http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=368 - - some fixes to textures loading paths in curry - - linux setup copying correct content for curry (pk3 in wolf media) and bobtoolz (bt/ in plugins/) - - building 1.2.2 setups - - Gef - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=362 - gensurf fix - - djbob - - bobtoolz update - - Hydra - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=361 - fixes a bug with the texture menu loading, now we see the non-shaderlist directories too - -26/1/2002 - Gef - Michael Schlueter - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=279 - applied several patches (to setup code and to the setup scripts) - modified makesdk.pl to update with more content - added an "enginepath" attribute to the game file, reworked the handling in editor - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=347 - took out the refresh command from the plugin menu - - more linux fixes: - bringing all the plugins to compile again on linux - polishing the setup code (all the right files in the right places) - - for linux release, bumping ver to 1.2.2 - win32 will have a 1.2.3-nightly after that - - added correct init of ~/.q3a or ~/.wolf - *nix systems have a 'prefix' attribute in the .game file to specify - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=359 - identified the mod compiling problems - applying back the old fs_basepath fs_game code to the BSP generation - - ydnar- TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=351 - cleaner path init code - it doesn't init for ~/.q3a and ~/.wolf paths yet - -25/1/2002 - SPoG - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=352 - using the wrong matrix stack for XY_Draw caused stack overflow error - - texture_mode was set to an invalid enum in wireframe/flatshade mode - - changed plugin API to expect gamedir-relative texturenames - - fixed gensurf to create faces/patches with gamedir-relative textures - -24/1/2002 - SPoG - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=322 - added modelscale key check to misc_model entity in md3/entity module - added angle key check to eclassmodel class in md3/entity module - fixed bugs in BP writing and reading in map module - TTimo (commited as SPoG) - - fixing permissions on cvsreport and doxygen stuff, upgraded dot - -23/1/2002 - SPoG - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=336 - plugin API bugfix - fixes textures on stuff created by plugins - ----- 1.2.1 was released here - -22/1/2002 - Gef - - linux build fixes - SCDS_reyalP - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=325 - wrong file packaged in setup - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=327 - fix to PCX loading - SPoG - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=298 - cut & paste bugfix - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=332 - update origin key on entities - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=333 - made fixedsize entities not scalable - -21/1/2002 - TTimo - - scanning in g_strAppPath/modules/ and plugins/ prior to g_strGameToolsPath - using the main path to put general plugins and modules - - fixed bobtoolz bug, init of epairs table was relying on wrong params - - fixed curry to compile again on 1.2 - - fixed pk3man to compile again on 1.2 - - updated IS setup: - installing the plugins with the core - installing the common modules in the core - - Compiling manual, more IS stuff, .xlink etc. - - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=315 - patches for improved multimonitor support (with some associated pref items) - - ydnar - - more q3map: http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=324 - - radiosity fixes (proper handling of ambient light) - - polygonoffset fixes - - lightmaps on patches work better (normal calcs adjusted, planar patches are - box projected like brush sides) - - double vfs init in bsp stage removed (this needs to be tested on Linux) - - lighting is faster again - - a couple crash bugs resolved - - other tasty nibbles - -20/1/2002 - EvilTypeGuy - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=313 - detachable menus set as preference (in layout) - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=255 - path prompt - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=307 - patch dialog names - ETG & RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=306 - fix 'Natural' texturing crash - ETG & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=291 - found out the problem, Wolf SP spawn works now - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=144 - fixed more problems with model loading vfsExtractRelativePath - prolly broke the linux build, just a matter of putting a bunch of #idfdef - - fixed an additionnal .pid lock situation, cleaning the global prefs on game .pid lock - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=301 - fixed md3 tris test selection bug - djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=219 - fixed bobtoolz for 1.2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=318 - filter structural - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=305 - filter in viewmenu for lightgrid brushes (ydnar's q3map) - fixes image lib loading bugs - Hydra - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=298 - copy/clone deselects the copied stuff - added a pref to deselect or not, and to nudge pasted stuff or not - -19/1/2002 - djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=311 - IEpair wrapper to access project entity from plugins - RR2DO2 - - missing IncRef in CShaderArray::AddSingle - TTimo - - game.xlink files in gametools path, is scanned to build items in the Help menu - (and the associated code) - -18/1/2002 - Gef / Michael Schlueter / TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=279 - patches 133 and 138 applied, new setup code - -14/1/2002 - TTimo - - adding djbob write access for bobtoolz - -13/1/2002 - ydnar - - q3map code updates 1.2.1-y8 - new lightgrid surface flag feature - lightgrid shader and editor image for Wolf and Q3/TA: in the common .pk3 and in all common.shader - cvs remove setup/data/baseq3/common-q3r.pk3 (unused, we use common-spog.pk3) - TTimo - - updating setup to use mapq3 module instead of map (both Wolf and Q3 game packs) - (also checked the lightgrid option) - - fixed setup.pl bug for template gen from WorkDir/ - - correct spawning between SP and MP mapping mode - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297 - .pid check, console logging and prefs cleanup - Wolfen - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=294 - checked in updates to the manual links page and setup instructions - (i.e. new prefs dialog) - -12/1/2002 - Gef & Michael Schlueter - - bugs #295 and #279, new patches applied - EvilTypeGuy & djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=220 - patch selection crash - EvilTypeGuy - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=260 - Dense and Very Dense Cylinders have wrong number of rows - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=292 - latching patch toolbar settings - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=144 - win32 long/short pathname bugs reappearing, switching back to short paths for project settings - - removed obsolete radiant/vfs.cpp radiant/vfs.h - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=291 - using new .qe4 for Wolf, fixed stuff editor side (long path names and engine spawn) - SCDS_reyalP - - http://zerowing.idsoftware.com/bugzilla/showattachment.cgi?attach_id=118 - realloc bug in terrain - -11/1/2002 - SPoG - - unpatched bug #239, unintended duplication of brushes, patch #96 - Note: bug #239 now unresolved - EvilTypeGuy - - bug #295 fixes for compile under Linux - -10/1/2002 - SPoG - - fixed CEntityEclassModel referencing eclass after eclass has been deleted - SPoG - map-module branch - - new map module, provides current functionality, using new map interface - - cleaned up merging/creating of entity array used by map module - - implemented MemStream::printf(const char,...) - can't print strings larger than 1024 currently - - changed copy/paste to use the map module, via abstraction of FileStream/MemStream as DataStream - - fixed Save Region and Save Selected - - new xml map module "mapxml" - - cleaned up map.cpp - -6/1/2002 - TTimo - - removed m_bPak from pref dialogs (it was dead code) - -5/1/2002 - RR2DO2 - - q3map terrain blending fix for >5 layers - EvilTypeGuy - - fs_homepath patch on linux - Gef - - bug #279, linux setup, patch #102 - - bug #239, unintended duplication of brushes, patch #96 - TTimo - - added Wolf specific project settings dialog: - correct fs_game selection and combo names - added multiplayer / single player mapping mode selection - -4/1/2002 - TTimo - - adding -game wolf switch to q3map (-game quake3 works too, but it's the default anyway) - using different bsp version and different fs_basegame on wolf - - updated the setup/win32/setup.pl script to generate from a config file instead of hardcoded - (added corresponding q3.cf wolf.cf and all.cf config files) - - added a default Start Menu shortcut name (RR2DO2 special) - - diffing against Id's internal SOS source and merging in new stuff: - - bumped MAX_SURFACE_INFO to 4096 in shaders.c - - new terrain code (Jim Dose) - ParseTerrain() addition in terrain.c - Creates a mapDrawSurface_t from the terrain text - - VL_SurfaceRadiosity and VL_SurfaceRadiosity - MrElusive's vlight radiosity code - - speedups to vis.c and visflow.c (MrElusive) - -3/1/2002 - TTimo - - merge gameselect branch back into trunk - the IS setup scripts have been updated for the new paths layout - developement environment needs to be updated to copy binaries to the right places for debug - it is recommended to run a 1.2.1 setup on win32 prior to compile and install debug bins - - updated the setup to be more templated for inclusion/non inclusion of game packs on demand - - - propagating recent fixes to Alpha into the trunk - based on diffing between Merge-1_1_1 and Merge-1_1_2: - ===================================================================== - 13/11/2001 - djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=244 - reverted again the shader manual and tcMod docs - - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=214 - patched aselib.c, was calling strstr badly (relative path extraction) - - 12/11/2001 - djbob - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=241 - applied patch, will release in next nightly - - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=254 - patch for safe_malloc - - TTimo - - fixing STLPort config checks and XML config (CHAR -> xmlChar) - - added safe_malloc_info and safe_malloc in the common/ dir - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=179 - added XML stream version checking between Radiant and q3map - ======================================================================== - also, manual merge of docs/manual and setup media - this merge work is related to bug #280 too: - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=280 - - ydnar - - new q3map, radiosity and bug fixes, code merged in with the trunk version - (TODO: add more detailed changes log) - - EvilTypeGuy - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=274 - broken auto caulking fix - - EvilTypeGyu & LordHavoc - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=207 - (two new files, project settings updated) - -2/1/2002 - TTimo - branch gameselect - - copying over the linux setup binaries (setup, uninstall, setup.gtk) - from Alpha branch. Those have the ability to prompt destination path - per component. - Gef - branch gameselect - - patch 101 for bug 279 - .game files generation by the setup, makesdk.sh and postinstall.sh fixups - -1/1/2002 - Gef - branch gameselect - - linux source fix http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=279 - (we use PATH_MAX as the cross platform define instead of MAX_PATH which only works on win32) - - TTimo - branch gameselect - - cleanup and homogeneisation of the paths for prefs storage - m_global_rc_path: - win32: g_strAppPath - linux: ~/.radiant// - m_rc_path: - win32: g_strGameToolsPath - linux: ~/.radiant// - so that global.pref goes in ~/.radiant//global.pref - and radiant.ini ~/.radiant///radiant.ini - -27/12/2001 - TTimo - branch gameselect - - global prefs file (global.pref), XML based in core directory - stores game selection setting - stores autoload setting - - dropping 'gameid' from .game file, gonna use a 'gamefile' in global prefs instead - (and the .game file name .. thks Gef) - - TODO: radiant.log stuff in global prefs? - -21/12/2001 - TTimo - branch gameselect - - more Wolf setup tweaking for an experimental build release: - quakev2.qe4 project template file - using a 'gameid' attribute in the game file to select hardcoded features in the editor binary - 'basegame' node for lookup of the default project file - 'engine' node for engine path - - added experimental Wolf game pack to IS - - added setup/win32/HOWTO with extensive information about the procedure to - add new game packs - - reading the 'name' attribute in the game node for game selection dialog - - TODO: pid files to make safe startup? - The .pid stuff should be happening after game selection, since it covers game-specific - preference settings. - - TODO: console logging pref should be a global pref, goes with game autoload? - -17/12/2001 - TTimo - branch gameselect - - updating the setup script for experimental 1.2.0 setup: - - merged some of the docs back into trunk (Radiant manual, some TA docs) - will need to perform a complete diffing between Alpha and trunk about docs/manual at some point - merged bitmaps from Alpha too - - added the Q3 modules (image, map, md3model, shaders, vfspk3) to Q3 game pack in setup - - generating per-game config file q3.game in OnMoved (IS setup) - will need equivalent with linux setup of course - - various other generic fixes to the setup code - - - multiple games support, list of changes, and TODO: - NOTE: this is on a 'gameselect' branch for now - Doxygen documentation should be at http://zerowing.idsoftware.com/doxygen - for this branch too. - - The installation procedure has changed. The win32 installer is partly ready, linux installer - will need to be modified too. The editor binary and the Gtk DLLs are installed in a common - location, i.e. 'C:\Program Files\GtkRadiant' typically. The game specific binaries and modules - go in the same location as usual, for instance 'C:\Program Files\Quake III Arena\GtkRadiant\' - (and also 'C:\Program Files\Quake III Arena\GtkRadiant\modules' 'C:\<..>\plugins') - - The environment variables used by the build system (VC6 project files) have been adapted: - $(QUAKE3RADIANTDIR) is still used - $(CORERADIANTDIR) is used for the main editor location - - When editor starts, it looks for games/*.game under g_strAppPath and prompts the user for a game - Once game is selected, parameters are used for regular startup. - You need to write your own q3.game for now, it will be generated by the setup procedure - my C:\Program Files\GtkRadiant\games\q3.game looks like that: - - - - - - given that, the editor does a complete startup, and the basics are here for multiple games - - - precise changes: - - g_strToolsPath renamed to g_strGameToolsPath - most of former g_strAppPath uses g_strGameToolsPath - the name change was also meant for homogeneity with DIR_GAMETOOLS_* variables we use in the setups - g_strAppPath still used, points to the main installation path - - added the game selection code in CPrefsDlg::Init - using several classes and a dialog box, parsing XML files - - - TODO: - - the console 'Radiant.log' doesn't catch the game selection stuff as it is now - initialize it to the main install, without the game setting - (console logging is a debugging tool anyway, no reason it should go to the proper game folder - each time) - - the 'preferences reset/cleanup' code is probably broken, specially when used with the .pid checking - since we check for .pid even before we know where the GameTools path is - - on linux, we need to sanitize the ~/.q3a dir usage. Switch to ~/.radiant, use the version tag - to maintain things independant, and use the game name to isolate per-game settings? - ~/.radiant/1.2.0-nightly/quake3/radiant.ini (.pid, .log) - ~/.radiant/1.2.0-nightly/wolf/.. - - also, when looking for those files (.ini mostly), win32 stores them in a main installation, and - linux has them in ~/.radiant/.. (which is the read/write area). This should be homogenized? - Maybe by adding a 'Main' to the readonly path and a new variable with 'RW', pointing to 'Main' on - win32 and to ~/.radiant on linux - -11/12/2001 - TTimo - - replaced setup/win32/setup.sh by setup/win32/setup.pl - same functionality level + abiliy to generate back a template from a work version - - major rework on the IS scripts, basics of multiple games support installer - clean seperation between editor core and game pack - design doc and analysis of custom setup generation, setup script UI requierements - see setup/win32/TODO for more details - -10/12/2001 - TTimo - - new generation of InstallShield setup - using a template/ directory instead of a .zip file - requires rewrite of the processing script - allows easier maintenance of the IS script - -23/11/2001 - TTimo - - yet another update to cvsreport script, - catch the branch and forward the info to user commands too - able to build doxygen for several branches selectively now: - http://zerowing.idsoftware.com/doxygen - -22/11/2001 - TTimo - - new cvsreport script, should send explicit diff of the CHANGES file now - -03/12/2001 - TTimo - md3-module branch - - validated the fixes and the build on linux, ready to merge in trunk - SPoG - md3-module branch - - changed function naming conventions in mathlib for m4x4, ray, bbox, to be consistent - - fixed bug in m4x4_invert - -29/11/2001 - TTimo - md3-module branch - - flagged all new mathlib functions that need a name change or an argument order change - also added various \todo to point out inconsistencies - -28/11/2001 - TTimo - md3-module branch - - updated linux build - - fixed CEntityMiscModel and CEntityEclassModel destructors - (any destructor should be virtual) - -27/11/2001 - Spog - md3-module branch - - stopped texturewindow showing shaders without the "textures/" path - - made md3 module functionally identical to current radiant md3 code - -22/11/2001 - TTimo - md3-module branch - - fixes to the core for linux build - - model.so module builds on linux - - added plugins/md3model/doc/md3-design.txt - - several doxy-friendly \todo chunks about the module model - - Spog - md3-module branch - - fixed aabb_add_aabb() algorithm wasn't very reliable - - added VectorMid, VectorNegative and CrossProduct macros to mathlib - - added bbox_intersect_plane() - -21/11/2001 - Spog & TTimo - md3-module branch - - initial code from Spog following a preparatory design work - merging in as new 'md3-module' branch - geomlib code merged into mathlib - some reorganisation of the source layout and cleanup (more stuff in imodel.h, less in qertypes.h) - - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=261 - fix applied - -20/23/11/2001 - TTimo - - yet another update to cvsreport script, - catch the branch and forward the info to user commands too - able to build doxygen for several branches selectively now: - http://zerowing.idsoftware.com/doxygen - -22/11/2001 - TTimo - - new cvsreport script, should send explicit diff of the CHANGES file now - -11/2001 - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=253 - additional fixes - TTimo - - renamed tools/quake3/common/threads.h to qthreads.h - avoids a collision with system headers - -19/11/2001 - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=251 - Fixed "Move into worldspawn" deleting entities with only one brush - Fixed Brush_Move using texture lock on fixedsize entity brushes - Fixed Textures > Texture Lock > Rotations toggle checkbox - -16/11/2001 - Gef - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=247 - applied patch 77, using a notebook layout for preferences dialog - also patched in some preferences saving that had been forgotten - (such as invert mouse in freelook) - - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=253 - patch 84 + additional modifs, bug still open - -15/11/2001 - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=252 - rewritten rendering pipeline for cam window - fixes some hacks, improves speed, - makes rendering modes more consistent with each other - -07/11/2001 - TTimo - - more IMAP interface, adding a blind data void *pData to entity_t - more info about it and why it's done is in map.cpp, should be a small base for next additions to the editor - -31/10/2001 - TTimo - - using IDataStream in map module, moved back some of the module code into the trunk - -30/10/2001 - Gef - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=245 - applied patch 76 - - TTimo - - renaming istream.h to idatastream.h, this had nasty conflicts with OS includes - already had to IStream -> IDataStream some time ago anyway - -27/10/2001 - TTimo - - updated cvsreport, testing new ver - - added a static version of texdef (no memory alloc on the texture name) - unused for now, was just experimental - Gef - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=245 - applied patch 75 - -26/01/2001 - TTimo - - various updates: - new GtkSDK precompiled binaries - updated libxml2 package (to 2.4.3) - updated STLPort (to 4.5) - now compiling with STLPort and threading (since we are using threading throughout the app) - - exposing the data stream API to the modules, renamed some stuff on the way - need to update the map module to use it now - - cleanup on qtexture_t definition - guarding and disabling chunks of the surface plugin code behind DO_SURFACEPLUGIN - (see earlier patch on plugin entities) - -25/01/2001 - Hydra - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=202 - applied patch commenting out plugin entities code - might come back in 1.2 under another implementation - the code is still there, only commented out for now - -17/01/2001 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=93 - checking in doxygen content, setting up generation on zerowing - auto generation on zerowing upon a commit: - http://zerowing.idsoftware.com/doxygen - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=231 - checked in the patch - - switching to a new cvs commit script - -14/10/2001 - TTimo - - libs/mathlib library - unifies mathlib code squattered all over the tree - mainly a merge of tools math code and radiant/mathlib.cpp - C implementation, using an extern "C" construct for use from C++ - need to check on linux, win32 builds ok - extracted qboolean code into libs/bytebool.h on the way - -11/10/2001 - TTimo - merged TmpMerge-1_1_1 branch back in the trunk, the update process from Alpha 1.1.1 is done - - TTimo - branch TmpMerge-1_1_1 - looking through all remaining .rej files and applying the failed patches accordingly - bobtoolz is broken, but it's not due to the merge - the plugin API is different and some things need updated - (disabled bobtoolz build in contrib/Construct for now) - same for gensurf - same for prtview - same for textool - setup: replaced the existing stuff with 1.1.1 code - fixed various things for win32 build, checked correct CRT lib config - -10/10/2001 - TTimo - branch TmpMerge-1_1_1 - building modules, going through all the .rej - merging radiant/missing.h and modules/shaders/missing.h into a single one, moving to libs/ - exposing BuildShaderList PreloadShaders in _QERAppShadersTable - have to review all the remaining .rej to finalize the merge now - -04/10/2001 - TTimo - branch TmpMerge-1_1_1 - using this branch as temporary location for merge process - copied over new binary files. mostly .dsp (prolly broken) - and setup/linux/setup.data stuff - -25/08/2001 - TTimo - map module successfully loaded and saved q3dm1, the saved file was then loaded back into 1.1-TA without problems - rebuilt and checked on win32 - merged IMap back in trunk, fixed some memory conflicts on win32 - Took me a lot more time than I would have liked to, but there's a script tied to the CVS server now, which will post on this list a diff of the docs/developer/CHANGES file whenever it gets updated. This will probably be very handy for me since I'll only have to put update information in the CHANGES file instead of having to post on the list too. - The script is likely to be a bit laggy, or miss some features (for instance I'd like to extract the branch name .. anyone know how I can get the branch name (Alpha/IMap/HEAD) from the version number? - PS: I can email this script to anyone who would like to have a look - -22/08/2001 - TTimo - did more work on map module, one big chunk of work left: the core should broadcast interface requests to plugins - when it doesn't know how to do it by itself.. - Gef - new doxygen patch, generates output from core (libs/ include/ and radiant/) - -21/08/2001 - TTimo - removed Makefile, use cons damnit! - -18/08/2001 - Gef - automated documentation via doxygen, new scripts and content - -18/08/2001 - EvilTypeGuy - patch for CHAR to xmlChar conversion (xml2 consistency) - -09/08/2001 - TTimo - the map module starts to look like something, cleaned up the interface stuff - started moving the actual code out in the module and removing it from the core - lots of issues raised on the way, some structures to export, and the macro scheme to access API functions more easily - it compiles right now, but won't run because it's missing a lot of things .. the process simply happens to be "under way" - -04/08/2001 - TTimo - patched more path code, to look for stuff in "bitmaps/" and "modules/" instead of "tools/bitmaps" and "tools/modules" - modified the Construct files accordingly - merged in radiant/ishaders.cpp diff into plugins/shaders/shaders.cpp (PreloadShaders) - merged in radiant/lbmlib.cpp diff into plugins/images/lbmlib.cpp (Sys_FPrintf) - checked the .rej and patched a few remaining things - NOTE - the diffs are space/tab sensisitive, and we used the "beautify source" a bunch of times, so it's a bit fucked now - next time, generate the diffs not space sensitive.. - TODO - map loading is fucked, "textures/" prefix issue? - -27/07/2001 - TTimo - merging recent changes from Alpha branch into the Trunk - this could not be done with a regular cvs merge because we already did a cvs merge of Alpha into trunk some time ago - manually built a diff between the current Alpha (now tagged Merge-1_1-TA_1-nightly) - and the Alpha we had right after the former cvs merge: -r Alpha -D 2000-05-28 - binary files ignored in the diff, only going for source stuff - built with diff -Nru Reference/ Current/ - then patch -p1 < patchfile - next, started rebuilding: - big manual updates were in vfs.cpp and texwindow.cpp - cleaned up some VFS stuff .. it had an absurd QERAppFileSystem / QERPlugFileSystem scheme - TODO: - the ISSetup has not been copied over from Alpha - OK check the Construct files - OK radiant/ishaders.cpp no longer exists .. apply the patch on the shader module - OK radiant/lbmlib.cpp no longer exists .. in the image code? - OK look at the *.rej files - -03/10/2001 - TTimo - - adding a pref to select patches by BBox, fixes - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=212 - -02/10/2001 - TTimo - - reverting Spog patch 67 to bug #209, starting from scratch - applied again, with HasModel returning NULL safe checks - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=211 - fixed overlays drawing (XY and Cam) - -01/10/2001 - TTimo - - building and distributing q3data (.ase -> .md3 conversion utility) - updated q3data to show main GtkRadiant version information and build date - - generating a new GUID per-setup - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=206 - Gef - - updated credits.html and links.htm, look much better - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=200 - - update Z-checker view on camera up and down - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=199 - Spog - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=209 - Fixed QERApp_ReloadShaders.. PreloadShaders needs a BuildShaderList call - Fixed Flush & Reload Shaders for md3 models - -25/09/2001 - Gef / djbob - - several patches to the key handling code, for linux specific issues and sticky keys - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=191 - TTimo - - fixing q3map bug, not processing the argv correctly - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=192 - - fixed ToggleCubicClip shortcut Ctrl+\ (win32 Gtk source patch) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=15 - -18/09/2001 - RR2DO2 - - discreet movement for camera (prefs setting) - fixes texture window bug - latching view layout changes until restart - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23 - djbob - - added back "view > show > show angles" in view filters - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=188 - -15/09/2001 - G_Dewan - - fixed problems with q3map when not using -connect - SPoG - - fixed q3map texture projection for brushes belonging to entities with local origin - - added SafeOpenRead() check, terminating map->bsp stage if .map file cannot be read - -13/09/2001 - RR2DO2 - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=181 - fixing key handling bug (key pressed with repetition was not properly catched) - TTimo - - added new Radiant manual elements (GtkRad section) to the win32 full setup - - reverting version to nightly, going back to nightly / RC delayed - - patched linux setup, now prompting for component path only if at least - one of the options is checked. Still need to handle Cancel in dialog though. - -12/09/2001 - TTimo - - more fixes to linux script, copy plugins right now - -10/09/2001 - TTimo - - patched contrib plugins, using seperate build scheme - - fixed textool issues, compiles again - -09/09/2001 - TTimo - - sub-menu cascading - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=178 - - udpated the Q3Radiant manual with some new GtkRadiant stuff - - updated the FAQ with 1.1.1 known issues - Gef - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=174 - applied all the patches - -07/09/2001 - SPoG - - fixed qer_editorimages outside "textures/" being ignored - - stopped q3map_lightimage being used to set shader image dimensions - - changed bsp menu to remove "bsp_", changed menu text in default .qe4 - - fixed patch LOD update - now always occurs on both cam/xy draw - - djbob - - dynamic DEpair class strings in bobtoolz - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=171 - - decrease VESF verbosity - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=169 - - TTimo - - fixed Gtk keyboard bug Ctrl + [ and ] - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=15 - -06/09/2001 - TTimo - - merged FullSetup branch into the trunk, we have basic functionality - for a full linux setup (components prompting for path) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=158 - - Gef - - CapDialog source cleanup patch (got rid of the namespace) - - RR2DO2 - - more camera fixes, wheel mouse and texture drag drop - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23 - - additionnal patch to optimize camera refreshes - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23 - - djbob - - remember last key/pair in entity dialog for easy "apply again" - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=18 - - re-enabled texture name edit on PI - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=18 - -04/09/2001 - djbob - - left pane on status bar - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=166 - - RR2DO2 - - cam window cursor fix - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23 - - TTimo (FullSetup branch) - patched setupdb and setup to allow for path prompt in install - modified the setup script scheme to go towards a solution similar to what - we do under win32 (build a full and nightly build) - the binaries in setup.data/ (setup and setup.gtk) still need to be updated - with proper binaries built from setup and setupdb cvs source - -03/09/2001 - TTimo - - wheel mouse in texture window on win32 (with a pref setting for increment) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=160 - - not saving prefs while exit on sleep - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=157 - - fixed select all of type (changed behaviour to something that makes more sense?) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=79 - - Gef - - final tweaks to wheel mouse scrolling (locks texwin scrolling and scrollbar update) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=160 - - prevent multiple color selection dialog for light entity - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=165 - - djbob & TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=137 - window positions - applied patch to store SI and PI positions - storing entity info and map info positions - reworked the overall position load/save scheme - added an enum for the view style, makes things more readable - -02/09/2001 - TTimo - - added/cleanup ToggleFreeMode to camwindow.cpp .. stopped working on cam stuff since RR2DO2 has another patch in preparation - Gef - - patched Conscript to accept 'cons -- release' on the command line to performa a release build - djbob - - added patch splitting to bobtoolz - - fix to patch control points bug in camera - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=159 - - handling of NWUV errors in q3map - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=147 - RR2DO2 - - new patch for camera control - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23 - -01/09/2001 - SPoG - - Fixed .wal texture support, searches for .wal extension if .tga and .jpg fail - NOTE: requires a "pics/colormap.pcx" file to obtain a palette from - - Added variable default texture scale in preferences (ini key: TextureDefaultScale) - -01/09/2001 - djbob - - fixed surface inspector "fit" bug - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=161 - - single face deselection on a selected brush - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=153 - -31/08/2001 - TTimo - - Moved *.def files to scripts/ in win32 setup - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=116 - - Applied patch for background position on widgets (win32) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=108 - - Checked C runtime lib configs - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=135 - - updating docs (add to CVS, update setups etc.) - added TA teams manual to the full setup - uploaded on web site - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=97 - - changed versioning to 1.1.1-nightly, next release will be 1.1.1 - (the -TA part was removed, since we now support ALL mods) - - removed AFX_MANAGE_STATE calls, this is old MFC related code for win32 - - moved texdef_t::name to private, added const char * GetName() - (doesn't fix explosion on exit for win32 debug builds though) - - fixed DoTextEdit / EditPad b0rkage (due to recent Q_Exec changes) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=134 - - added targetShaderName documentation to shader manual - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=102 - - added "notta" and "notq3a" documentation to the TA Mapping manual - - fixed entities.def on shootable doors and buttons - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=101 - - djbob - - added MAX_POINT_ON_WINDING error handling - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=129 - - bobtoolz update - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=123 - - RR2DO2 - - noclip-type camera movement - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=23 - -30/08/2001 - TTimo - - Fixed CHANGES commit script bug - - Fixed -onlyents bug in q3map / origin brushes - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=92 - - added mouse wheel to the texture window - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=81 - SPoG - - Fixed texture rotation not updating correctly on patches - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=136 - - Fixed long delay on toggling cubic clip by removing call to Map_BuildBrushData() - - Added note in entities.def for default worldspawn _color value - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=105 - - Added IncRef and DecRef to Patch_FindReplaceTexture() - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=95 - - Fixed misc_model updating on changing model key or with invalid model - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=138 - -30/08/2001 - SPoG - - Added negative vertical scale on SET and FIT in patch/surface inspector - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=65 - -27/08/2001 - Gef - - running makeversion.sh from Conscript - - a bunch of patches to cleanup compile warnings on linux - - added VectorSnap on float grid - - IWindowListener modified to pass float values for X Y in click messages - TTimo - - fixed crash when adding a misc_model if Gtk dialog is on - djbob - - md3 filtering for misc_model dialog - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=76 - -26/08/2001 - Gef - fixed http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=152 - Kyro II GL drivers bug - fixed http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=150 - using a scrolling textbox for GL extensions in the about list - fixed http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=150 - func_group toggle in cap dialog - - TTimo - fixed running BSP commands on linux - fixed http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=133 - VFS init on linux - -around 15/08/2001 - TTimo - quakecon fixes: switched to long filenames in project and misc_model dialogs, - removed all occurences of win32 conversion to old 8.3 filenames - NOTE: this might raise some bugs and issues, but it's the way to go for the future, - already fixes more issues than it creates - -03/08/2001 - djbob - fixed Radiant hijacks win32 copy/paste - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=36 - ---- merged Alpha into Trunk, see Merge-1_1-TA-nightly tag - -25/07/2001 - TTimo - fixed project dialog to behave right - proper .def scanning - fixed shader loading with VFS and mod stuff - added a local to texwindow.cpp GSList *l_shaderfiles - holds the names of the active .shader files - modified q3map to read "fs_basepath" and "fs_game" - TODO: - .def files in the media need to move to /scripts/ - rename entities-TA.def to entities-ta.def - -24/07/2001 - TTimo - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=116 - updated cmdlib's Q_Exec to be more widely used through Radiant (during watchbsp.cpp cleanup) - patching in MarsMattel's code for mod support, and started fixing: - added m_strFSBasePath m_strFSMain m_strFSGame to g_qeglobals to match Q3's filesystem - reworked the project file dialog - changed the way we load and initialize eclass and shaders to work with mod code - updated VFS initialisation code, cleaner and better console output - the "game" key in the project file is no longer relevant, only "dir" is - (if "dir" is not present, then no mod support, vanilla Q3) - changed the loading of the .def files to scan in scripts/, you might need to move your entites.def to use - TODO: - cleanup .. (search where "basepath" is used for instance) - using fs_game when calling q3map - fixing project dialog to behave right - shader loading using VFS functions (seems to work again but I'm not sure) - win32 ver. might be slightly broken - .def scanning, don't scan ALL .def - -23/07/2001 - TTimo - added version and build info to the log file + current timestamp - -22/07/2001 - SPoG - fixed selection of misc_model when viewed as a bounding box - -20/07/2001 - TTimo - cons script for q3map building - added general GtkRadiant versioning (version.h) to q3map - nightly setup on linux: - using the right install path (with GtkRadiant's version name) - cleaned up options to only the stuff relevant to nightly - fixed Radiant and core binaries path in setup - added some template processing of setup.xml (similar to what is being done on win32) - -19/07/2001 - TTimo - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=112 - applied ^Fishman's path - inclusion of version.h and aboutmsg.h moved to qe3.h - changed base path location process (in most cases it will prompt) - fixed the path construction to initialize according to the new layout - -16/07/2001 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=115 - fixed wake up crash on linux - -12/07/2001 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=117 - fixed - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=120 - fixed installer bug on win98, was a problem with cygwin config - -11/07/2001 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=64 - cleanup and fixed - -06/07/2001 - TTimo - - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=100 - can't locate the "textures: in use" problem, has been fixed already? - now selecting the right entity in the list, had to go around an inifinite recursion problem - (i.e. selection message in the entity class list causes UpdateSel recursion) - -04/07/2001 - TTimo - - added botclip to missionpack/common.shader - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=114 - -01/07/2001 - TTimo - - backported cons scripts to Alpha branch. Type 'cons' at the head to build - regular makefiles should soon be outdated.. - -30/06/2001 - TTimo - - updated the IS script (Gtk changes and and BACK problem) - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=68 - - bunch of fixed to make it build on win32 against new STLPort - http://zerowing.idsoftware.com/STLPort/ - using an STLPort configured locally in GtkRadiant (with stl_config.h, new file) - -29/06/2001 - TTimo - - fixed GDI leak affecting text widgets, specially the console and the entity inspector - -18/06/2001 - TTimo - - more win32 project file cleanup, removing libs/libxml2 from the tree - - importing back "gtkr_list.h" from 1.2, made Alpha branch STLport compliant too - http://www.qeradiant.com/faq/fom-serve/cache/174.html - -30/05/2001 - TTimo - - added libxml2 as an external dependency. libxml2 should be installed as a seperate - directory on win32. dynamic linking now instead of static previously. - - cleaned up q3map win32 project file, removed opengl dependency - (the drawflag command line is inoperant now .. I don't think it was used anyway?) - -26/07/2001 - TTimo - - checking in Gef's doxygen files - -14/06/2001 - TTimo - - added .dsp for map module on win32 - - fixed several issues with module loading, stability of the debug and release builds - http://www.qeradiant.com/faq/index.cgi?file=197 - -12/06/2001 - TTimo - - got rid of of SysMsg thing, using SysPrintf and SysFPrintf now - - got rid of InfoMsg functions (can't remember what it was) - - changed the m_pfnError in the plugin API to match Radiant's (void)(char *, ...) - - changed Warning to Sys_Warning, as #define to Sys_FPrintf(SYS_WRN, - -11/06/2001 - TTimo - - new map module, in plugins/map, required for execution (linux Makefiles written, win32 needs to be) - this is using the imap.h interface - - added Sys_ functions to the main table (Sys_BeginWait Sys_EndWait) - - got rid of AFX_MANAGE_STATE macros .. those are crappy MFC remnants - - reverted Spog's changes to the console logging switches to their original behaviour - - removed m_fVersion from the func table .. we use the size of the table to do the checks - XMLmap merge from 31/11/2000: - - started moving the map loading code into a module - -08/06/2001 - TTimo - - updates to the plugin loading code, verbose a bit more, and more interesting information - -05/06/2001 - TTimo - - some fixes to vfspk3 string code, using the proper str implementation - http://www.qeradiant.com/faq/index.cgi?file=175 - - added and tweaked various cons build files, Radiant 1.2 core and required Q3 modules are building now - - fixes to image module - -04/06/2001 - TTimo - - started using cons for the linux (*NIX) build system - see http://www.dsmit.com/cons/ - - SPoG - - Fixed drawing too much coordinate text in XY window - - Changed grid line drawing in XY window to be more consistent - - Fixed clipper-tool-uses-caulk to only apply common/caulk to solid opaque brushes - (shaders.dll now parses some new surfaceparms) - - Changed shader parsing to pass over layer information in shaders, - rather than parsing and ignoring it all - - Changed misc_model selection to ignore back-facing triangles - - Added axes to show the grid origin in XY window - - Changed misc_model rendering and selection to minimise the number of extra - transformation calculations - - Fixed texture directory listing to allocate and free memory correctly using vfs - - Added qglDeleteTextures() to plugin GL API - fixes crash - - Fixed image.dll to correctly allocate and free memory for jpgs - - Moved modules to /modules from /plugins, updated win32 project files. - (linux/mac makefiles will need to be updated) - - Changed console logging toggle in main() to automatically disable logging after any successful startup - - Changed console logging to only activate when a Release build finds a .pid file - - Changed "found .pid" and "logging console output" messageboxes to give a clearer message - - Added vfsFreeFile - which is kinda redundant if we use g_free and g_malloc for everything - -31/05/2001 - TTimo - - cleanup of the win32 project file and C++ options.\ - Turned off exception handling, changed some code generation options and fixed - some threaded/non-threaded linking problems - - STL in GtkRadiant or a plugin must now use STLPort - a custom configured version of STLPort is available at http://zerowing.idsoftware.com/STLPort - still need to write some guidelines about it - bascially, we are using STL: iostreams disabled, no namespace, no threading, no exceptions - -30/05/2001 - TTimo - - removed libxml2 from tree, use a seperate libxml2/ directory next to GtkRadiant/ for win32 - libxml2 will be distributed seperately as an archive based on official release (same as win32 Gtk SDK) - (check on zerowing for the latest archive) - libxml2 is now used as dynamic shared object on win32, makes sense since many module will rely on it - - cleaned q3map, removed GL dependencies - - updated Debug and Release builds on win32, it compiles and runs now - -28/05/2001 - Spog - - moved vfsExtractRelativePath and vfsGetFullPath to vfs.cpp in vfspk3, - added vfsExtractRelativePath and vfsGetFullPath to IFileSystem. Copied BuildShortPathName() from qe3.cpp to vfs.cpp as a Temp fix. - - Changed Error() calls in bmp.cpp as a Temp fix, they relied on definition of Error in qe3.cpp. Should probably use Error() from cmdlib instead. - - Fixed unresolved external in jpgload.obj - merged bufsize argument into jpeg_stdio_src from Alpha branch... assuming Alpha is the newer version. - - Changed GtkWidget* to void* in image.cpp.. this could be cleaned up more.. i only did enough to make it compile. - - Added jpeg.cpp to msvc project for image.dll.. changed declaraction of LoadJPG() in image.cpp to an extern... is this correct? - - TODO: update vfs.cpp, vfspak.cpp and vfs.h in plugins/vfspak - - fixed unresolved external load_pixmap() - merged load_pixmap declaration from Alpha branch into gtkmisc.cpp - - moved vfsBasePromptPath() to qe3.cpp as a Temp fix - not currently required in vfs module, but it will be in future. - - two calls to free() in texwindow.cpp freeing memory allocated by vfs module, causing debug assert errors - changed them to g_free() - - TODO: Delete vfs.cpp and vfs.h from /radiant - TTimo - - additional fixes after Spog's merge (linux version), removed messaging.cpp messaging.h (name changed to ui.h ui.cpp) - updated linux makefile accordingly - - merge of Alpha version into trunk (massive amount of changes and merges, not detailed) - -25/05/2001 - TTimo (Alpha branch) - - merged the recent MacOS branch back into Alpha - this makes a potential source codebase for a MacOS release - -24/05/2001 - TTimo (Alpha branch) - - patching Spog's recent changes to fix linux build - using DBL_MAX and FLT_MAX from for float and double max - -23/05/2001 - TTimo (Alpha branch) - - testing Spog's write access - - SPoG (Alpha branch) - - Added variable LOD for PatchMeshes based on curvature - - Added LOD-matching to eliminate gaps between patches with mismatched LOD - - Fixed texture shift/scale on LOD'd PatchMeshes - - Added opengl lighting (three infinite light sources) - - Added dynamically calculating vertex normals for PatchMeshes, for gl lighting - - Added decoding/transforming md3 vertex normals for gl lighting - - Changed camera drawing routine to minimise gl state changes - - Removed Patch_InsertDelete() - not functional - - Added CV lattice to selected patches - - Added Per-polygon patch selection - - Added Per-polygon misc_model selection - - Changed default "patch subdivisions" to 4 - - Rewrote camwindow drawing to only change opengl state within the camwnd's member functions - fixes all rendering modes to be more consistent, speeds up rendering - ---------- GtkRadiant 1.1-TA win32 and linux release ---------- - -13/05/2001 - - Spog (patched in TTimo) (Alpha branch) - - Fixed "Fix entity-target/targetname collisions" to use next available tN if tN, else use next available name_N - - Changed patch point selection to pick already-selected points in preference over non-selected - - Changed RemoveCols and RemoveRows to not extrapolate unless a col/row is selected - -11/05/2001 - TTimo (Alpha branch) - - final fix pass to the generated version and about message tags - - improved texture adjustment code (shift+arrows shortcuts) - - texture adjustment commands now affect the texture relatively to their current orientation - they will move along their texture axis, and not along world axis - the texture adjustment commands are now interpreted to be more intuitive: - Radiant will match the up/down/right/left translation messages to the face that is affected - depending on the way the camera is looking at the face, the right move commands will be used - - changes start in Select_ShiftTexture, using new ShiftTextureRelative_Camera - - ShiftTextureRelative_Camera uses several new functions: - - // get the two relative texture axes for the current texturing - BrushPrimit_GetRelativeAxes(f, vecS, vecT); - - MatchViewAxes does the matching between up/down/left/right commands and world directions: - // vec defines a direction in geometric space and P an origin point - // the user is interacting from the camera view - // (for example with texture adjustment shortcuts) - // and intuitively if he hits left / right / up / down - // what happens in geometric space should match the left/right/up/down move in camera space - // axis = 0: vec is along left/right - // axis = 1: vec is along up/down - // sgn = +1: same directions - // sgn = -1: opposite directions - // Implementation: - // typical use case is giving a face center and a normalized vector - // 1) compute start and endpoint, project them in camera view, get the direction - // depending on the situation, we might bump into precision issues with that - // 2) possible to compute the projected direction independently? - // this solution would be better but right now I don't see how to do it.. - void CamWnd::MatchViewAxes(const vec3_t P, const vec3_t vec, int &axis, float &sgn) - - // shift a texture (texture adjustments) along it's current texture axes - // x and y are geometric values, which we must compute as ST increments - // this depends on the texture size and the pixel/texel ratio - void ShiftTextureRelative_BrushPrimit( face_t *f, float x, float y) - - those functions are using various new utility functions: - - // GL matrix product - void GLMatMul(vec_t M[4][4], vec_t A[4], vec_t B[4]); - - // project a 3D point onto the camera space - // we use the GL viewing matrixes - // this is the implementation of a glu function (I realized that afterwards): gluProject - void CamWnd::ProjectCamera(const vec3_t A, vec_t B[2]) - - - UI abstraction layer (interfaces for Gtk MFC and Q3 UI) - -09/05/2001 - Maj (Alpha branch) - - new splash screen - - Spog (patched in by TTimo) (Alpha branch) - - patcing in changes: - - moving void VectorSnap(vec3_t point, int snap); to mathlib - - NOTE: STL dependency removed .. leaving this comment - this will rely on M$ implementation of STL on win32 and the libstdc++ for linux - it should work fine for basic stuff - but M$ implementation doesn't follow the standards when it comes to advanced stuff - it is probably better to leave the STL header in local files and not go towards including it directly from qe3.h - - Spog's Changelog: - - rushing this a bit.. make sure you check it doesn't remove anything you - changed. This only contains changes within /radiant .. i'm pretty sure I didn't - change anything else, but i'll check again. Patch below. - - Fixed ctrl+G SnapToGrid, now never creates degenerate face-planes - Fixed setting an origin for multiple brushes to use origin point of fixedsize - entities - Fixed mirroring and rotation of fixedsize entities including misc_model - Fixed undo/redo on multiple entities to link brushes to entities correctly - Fixed "view > entities as.." menu to display correct default setting - Fixed "view > entities as.." toolbar button to show menu - Changed selection-area of edge/vertex control handles to stay constant when - zoomed - Fixed undo on ctrl+G SnapToGrid - Fixed Selection Invert to set bSelected correctly on patches - Fixed XY-window Z selection origin to be g_MaxWorldCoord - Changed RotateIcon to draw same size at all zoom levels - - Fixed origin drift on saving misc_model with null md3Class - Fixed creation of cap for 'Bevel' type patches - Fixed inverted cap being created for 'Endcap' type patches - Fixed inverting patches on mirror operations - Added snap-selected-to-grid affects only the patch points selected - Cleaned up Select_ApplyMatrix and Select_SnapToGrid - Added drawing of brush planepts in debug build - Fixed texture quality slider adjustment - Removed redundant menu items curve > cap > inverted bevel/inverted endcap - Fixed texture scrolling not working when scrollbar is disabled - Fixed textures with odd dimensions being skewed with texture quality less than - max - Changed Patch Inspector Horizontal/Vertical increment to use pixel values - (default 8) - Changed Patch Inspector Horizontal increment to subtract from S values but not - T values - Changed Patch Inspector Stretch spinner to do something useful - Changed Patch Inspector Stretch default amount to 0.5 - Changed Arbitrary Rotation dialog to reset rotation spinner values to 0 on Apply - !! stops output in console window !! - Added sending q3map output - to /temp/junk.txt to bsp commands, in win32 only - Fixed Patch_Naturalize to calculate T values backwards, correcting texture - vertical flip - Changed patch row/column Insert/Remove to interpolate/extrapolate from existing - curves - Fixed point selection on patches when new points are added - Fixed redundant edge/vertex handles being created for patch brushes and - fixedsize brushes - Fixed refusal to activate brush vertex-drag mode if any patches are selected - Partly fixed Undo picking up patch point drags when no points are selected - Fixed behaviour of vertex selection on patches - Fixed patch point colours in textured mode in cam window - Changed patch point selection to update selection pool on each selection click - -06/05/2001 - TTimo (Alpha branch) - - more setup script changes, will rely on version information - various other fixes in the script file - -02/05/2001 - TTimo (Alpha branch) - - added makeversion.sh to the root, will generate version and date files before compilation - version.h and date.h - - cleanup and fixes to the linux setup scripts - - Spog (CVS add and config by TTimo) (Alpha branch) - - win32 setup script, run setup/setup.sh from cygwin to create a working directory for the setup - -01/05/2001 - TTimo (Alpha branch) - - fixes to linux version from previous set of patches - -19/04/2001 - Hydra (patched in TTimo) (Alpha branch) - http://fenris.lokigames.com/show_bug.cgi?id=3458 : - - *.pfb filter - - SpoG (patched in TTimo) (Alpha branch) - - updated setup data: entities.def common.shader(Q3) and common-spog.pk3 - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=25 : - - Patches: Curve > matrix > redisperse > rows/columns - I changed this function to treat a patch as multiple 3by3 sections when doing - redispersal of control points. The effect is that green patch points are never - moved. I also removed the call to Patch_Naturalize, so the texture coordinates - are not changed (user can hit ctrl+n to naturalize afterwards if desired). - - rewrote the patch_captexture function to be more reliable - - Fixed YZ view drawing and selection being mirrored on plane X=0 - - Fixed X and Z rotation direction to be clockwise as shown on the toolbar button - icons - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=8 : - - Fixed: Removed orientation-switching hack to fix 2pt-clip orientation problems, - originally stemming from ass-backwards representation of grid axes. Fixed - clipper to generate 3rd clip point correctly for each axis instead. - - Fixed: Stopped clipper-caulker from NOT applying caulk if the first face of a - brush was "common/caulk". - - TTimo (Alpha branch) - - removed some unused code in the Gtk file dialog, hopefully stabilizing it - -02/04/2001 - TTimo (Alpha branch) - - changed the regular/BP conversion prompt - -01/04/2001 - Spog (patched in by TTimo) (Alpha branch) - - Fixed view > show coordinates now affects Z window - - Fixed minimum/maximum world coordinates now -65536/65536 - - Fixed view > show blocks now only draws vertical lines if not XY view - - Added variable blocksize (gtkr only displays 1024 < blocksize < 65536) - - Changed XY/Z window grid drawing to use floats internally - - Fixed broken XY window grid drawing for higher zoom levels - - Changed camera and Z-checker icons to stay the same size when zoom level changes - -24/03/2001 - Spog (patched in by TTimo) (Alpha branch) - - added filters.cpp to the VC6 Makefile. Linux build needs updating - - Changed Filter system to use brush-flags updated only on actions that affect filtering - - Changed Filter system to allow further extension and future customisation - - Changed show/hide to use brush filter flags - - Changed Find/Replace textures to only rebuild brushes that changed. - - Changed View > Filter menu shortcuts and behaviour - - Fixed various minor spelling errors - - TTimo (Alpha branch) - - Fixed the 'Clean' command in preferences, used to remove only Radiant.ini and not SavedInfo.bin - -06/03/2001 - TTimo (Alpha branch) - - better parse error information: added the line number of the error in (hopefully) all cases - -30/02/2001 - TTimo (Alpha branch) - - texture locking in BP mode for axis flipping and axis rotation (toolbar buttons) (Id bugfix request) - - fixed undo in BP mode - - MatchToken error message in q3map improved with the script name - -27/02/2001 - TTimo (Alpha branch) - - switched linux makefiles to xml2-config instead of xml-config - latest version of libxml2 is using xml2-config instead of xml-config now - -26/02/2001 - TTimo (Alpha branch) - - fixed a loki_initpath misbehaviour, was overriding the path to the binary with RADIANT_DATA if defined - -21/02/2001 - - Added setup data and a script to build linux setups to the cvs - TTimo (Alpha branch) - - various printf -> Sys_Printf - - added vslick/ directory for Visual Slickedit 6.0 on win32 <- THIS IDE RULES - -20/02/2001 - - Removed "Show Paths" option, already in the filter menu - -19/02/2001 - - Fixed the Enter key handling on the surface inspector (suggested by Spog) - - Fixed skewed textures with lower texture quality - - Changed the order the include directories are searched under Linux - -15/02/2001 - - Moved the Show Cluster Portals option to the Filter menu - - Fixed the rotate and scale toolbar buttons being incorrectly checked - - Fixed arbitrary rotation bug (#3073) - -14/02/2001 - - Fixed CreateFont memory leak on glwidget - -12/02/2001 - TTimo (Alpha branch) - - fixed save as prefab stuff (right dialog name and overwrite prompt) - -10/02/2001 - TTimo (Alpha branch) - - was crashing on win32 boxes where HOME env var was not defined (loading bookmarks) - -09/02/2001 - TTimo (Alpha branch) - - change some code in the file dialog to use g_malloc g_free instead of new - for win32 file dialog and malloc for Gtk file dialog. (all of this trying to get rid of - some of the crashes) - -07/02/2001 - - Fixed Load command initial path - - Fixed some toolbar buttons not being correctly initialized - ------------? - -06/02/2001 - (Alpha branch) - - Fixed pk3man file dialog errors - - New RC uploaded - - Changed conflicting shortcuts: FilterModels = Shift+M, FilterTriggers = Ctrl+Shift+T - TTimo (Alpha branch) - - fix to hide/show, still selecting hidden brushes - -05/02/2001 - (Alpha branch) - - Fixed compile errors (use stat, not _stat) - - Removed --nofonts option - -04/02/2001 - TTimo (Alpha branch) - - fenris #2866, added a pref to turn on/off name conflicts resolution, rewrote the whole algorithm - - fenris #2823, fixed patch and brush dragging in 0.25 0.5 grids (it's an ugly hack btw) - - fixed the black squares at end of line in Gtk text boxes - RR2DO2 (Alpha branch) - - fix to the "entitypath" fixup in QE_CheckProject. might not compile on linux yet (use of _stat?) - -03/02/2001 - TTimo (Alpha branch) - - fenris #2867, limiting the amount of "spawnflags" "0" appearing in entities. This bug has work left to do, - there are some oddities in the entity inspector behavior described. - -02/02/2001 - (Alpha branch) - - Fixed sleep mode not restoring windows correctly - - Fixed some minimize/restore issues on floating views mode - TTimo (Alpha branch) - - fixed more gtkfilesel stuff. pattern filtering works for both Gtk dialogs - and win32 native. Also checked on linux that it compiles. Renamed gtkfilesel.h - to gtkfilesel-linux.h for consistency. - -31/01/2001 - (Alpha branch) - - New file selection widget with filtering, masks and all other shit we need - TTimo (Alpha branch) - - changed some gtkfilesel API and fixed some bugs on pattern filtering, need to reboot on linux and fix some more - -30/01/2001 - (Alpha branch) - - Added an option to keep the Z and XY views on the same window in floating views mode - - Did some cleanup - TTimo (Alpha branch) - - removed the 3 layers in terrain entities limitation, increase version tag to patchlevel 3 - sent for testing to AstroCreep, bug is still there - - fixed one more thing with RC file (get it in the right dir) - - worked on file dialog and pattern filtering, still issues left - -29/01/2001 - Jonas (patched in by TTimo) (Alpha branch) - - Using RC file to tweak the font size on win32, looks much nicer now! - - Fixed fenris #2773: esc key behaviour when group window has focus / dependant on view modes - -28/01/2001 - TTimo (Alpha branch) - - Finished fenris #2810 (Snap T to grid), it was a bitch - - Fixed fenris #2769: raise the brush max size (it was already big, now it's just not sane) - - Fixed fenris #2965: eclass (entities) loading code broken, needs to be checked on linux build before closing - -27/01/2001 - TTimo (Alpha branch) - - Fixed vertex edit prefs broken - - more fixes in Gtk libs - - Fixed clipping + brush primitives bug (#2644) - - Fixed clip caulk related issues (#2912) - - Added Snap T to grid back (#2810) <- still need to test and validate it, I'm too tired tonight - -25/01/2001 - TTimo (Alpha branch) - - New Gtk file selection dialog seems stabilized, built a Gtk SDK for the new Gtk libs. - -24/01/2001 - (Alpha branch) - - Fixed elapsed time displayed by q3map - - Fixed Radiant loading some TGA files upside down - TTimo (Alpha branch) - - more work done on the file selector. Added a win32 pref to select between regular win32 file dialog and Gtk one. - The advanced file selector is still not stabilized on win32. I am thinking about letting go and sticking to the regular one. - -23/01/2001 - (Alpha branch) - - Fixed q3map not finding md3 files under missionpack/ - - Prompt to save changes when choosing a recent file - - Fixed window title when choosing File/Load Map - - Don't show hidden brushes in the Z window - -22/01/2001 - (Alpha branch) - - More File Dialog fixes - -21/01/2001 - TTimo (Alpha branch) - - version first version of the advanced file selector on win32 - seems to work nicely, but crashes when you actually load something .. needs debugging! - - leo (Alpha branch) - - Set correct initial directory for the File/Load command - -17/01/2001 - (Alpha branch) - - Fixed q3map is crash if a .shader file is referenced in shaderlist and not found - - TTimo (Alpha branch) - - fixed some license headers on gtkfilesel.c, started looking into porting gtkfilesel.c to win32 - -16/01/2001 - raistlin - - the tree is opened whoooo! - - TTimo (Alpha branch) - - replaced the old Id header by the newer version (BIG update, to trunk and Alpha) - - switched str.h to BSP - - added LGPL license to the sample dll - -15/01/2001 - (Alpha branch) - - Added camera window toggle option to all views mode - - TTimo - for trunk and Alpha: - - renamed TOOL_SOURCE_EULA to LICENSE_ID - - renamed CONTRIBUTOR to CONTRIBUTOR_AGREEMENT - - added CONTRIBUTORS and LICENSE - -14/01/2001 - (Alpha branch) - - plugin SDK is back in setup/ moved the sample dll to be in plugins/, need to rewrite the SDK scripts - - built a lightweight plugin SDK with cygwin makefile for the sample plugin - -12/01/2001 - (Alpha branch) - - Set map modified flag when deleting a brush - - Minimize all windows when the main window is minimized in floating views mode - -11/01/2001 - (Alpha branch) - - Cleaned up the View/Show submenu - - Fixed texture menu splitting - - Fixed major grid lines on 128 and 256 grids - - Load only a single .def file if specified in the project settings - - Fixed q3map Makefile - - TTimo - (Alpha branch) - - Removed plugins/shaders from Alpha branch - - got rid of common2/ and code, moved qfiles.h and surfaceflags.h into common/ - - put the licensing headers in all source files (forgot some? byte me) - -10/01/2001 - leo (Alpha branch) - - Added new filter system based on FAKK2 Radiant - - TTimo - - fixed whatever could be fixed to make it compile with the new directory layout - (Alpha branch) - - project files update - -09/01/2001 - (Alpha branch) - - Added undo for patch redisperse rows and patch redisperse cols commands - - Fixed Show Z Outline menu item - -30/11/2000 - TTimo - - removed content flags and value from qtexture_t, these have moved to the IShader - (NOTE: qtexture_t != texdef_t, texdef_t still using flags value and content) - - - Rewrote the linux plugins Makefiles - -29/11/2000 - - Improved the way modules are loaded - - Added new parameter to QERPlug_RequestInterface - - finished VC6 project files conversion for new directory structure - - fixed shader blending on terrain maps bug - -08/01/2001 - - Updated Makefiles for the new directory structure - - Fixed View/Show/Entities menu not being checked correctly - - Fixed "Invert Selection" command selecting hidden brushes - - Fixed "Select All of Type" command not working correctly after the Enitity Window is closed - - Fixed grid being drawn even when it's the same color of the background - - Fixed "Toggle Size Paint" not turning off - -05/01/2001 - - Fixed autosave interval being calculated wrong - - Fixed autosave path under Linux - - Fixed q3map crash when trying to load missing pcx files - - Fixed q3map not finding .bmp files for the terrain alpha map - -04/01/2001 - - Fixed GL stack underflow when loading a misc_model - -03/01/2001 - - Fixed patches remaining half-selected after "Region set selected" (#2748) - - Fixed Surface Inspector spin buttons rate (#2776) - - Fixed some shortcuts not appearing on menu items (#2786) - - -================================================================================ - 1.1-TA beta -================================================================================ - -02/01/2001 - - Fixed memory problem if a file without extension is entered in the file save dialog. - - Fixed double slashes "//" on filenames when saving a map - - Fixed pk3man plugin not finding the toolbar bitmaps - - Fixed double clicks being considered 2 mouse clicks - - RR2DO2 (applied by TTimo) - - Clusterportal filtering ('View > Show > Show clusterportal' toggle) - -01/01/2001 - TTimo - - updated Web/ with new stuff, web site ready for release - - fixed a crash with multiple edge dragging on win32 (was caused by compiler optimizations, - this one was a major pain) - -31/12/2000 - - fixed the file open/save dialogs initial directory - - RR2DO2 (applied by TTimo) - - bug fix in the terrain loading speedup - - TTimo - - tried to lookup the Z window minimum width problem, added #define DBG_WINDOWPOS code to investigate - -30/12/2000 - RR2DO2 (applied by TTimo) - - fix to CSG Merge in the menu drop down (menu was there, command not hooked) - - some message formatting fixes - - TTimo - - rudimentary pattern matching in file selection, affects the plugin API too - - fixed silly bug in the "clipper uses caulk" code - - major speedup to the loading code on terrain entities - (in mpterra2, from 113s to 4s for the main terrain entity) - - patched back the file open/save dialogs initial directory to override in TA mode - - fixed Patch output crash in the plugin API - - fixed BP conversion in the brush output of the plugin API - - minkey (applied by TTimo) - - fix to the m_pfnLoadFile code to use VFS - -29/12/2000 - - Remember main window position in floating views mode - - Fixed wake up when running the engine in floating views mode under win32 - - TTimo - - various fixes and debug hooks for PJ bug reports - -28/12/2000 - - Fixed VFS initialization order - - Removed texture menu splitting option from preferences (now it's automatic) - - TTimo - - built an initial setup, updated the changelog file for 1.1-TA-beta - -27/12/2000 - - Fixed Q3Map output window being too wide on some errors - - Added VFS to q3map - - TTimo - - replace a printf in q3map by Sys_Printf (!), which is what should actually be used - - added a set of functions to vfs to help with file dialogs, building relative files etc. - - reworked the file dialogs so they default in the right location (open/save as/md3 loading/sound loading) - - fixed shader editor to work with the right path - -26/12/2000 - TTimo - - put the converted HTML manuals (Radiant, shaders and model) in the tree (and the win32 setup) - - added the new Terrain and Team Arena mapping manuals (added to the setups too) - - leo - - Copy and paste across different instances of Radiant - - Fixed wait cursor when copying - - Print engine command line to the console - - Fix glib warnings when running the engine - - Fixed shader files being loaded twice - - Texture menu now automatically breaks when it reaches the maximum screen height - -24/12/2000 - - Fixed q3map to compile with the new LoadJPGBuf parameter - - TTimo - - added TA paths to the BSP commands and running engine - - fixed a bug if running with monitoring disabled (generating the .bat was borked) - - changed the -moddir implementation to a global switch in q3map (same as -connect) - - moddirparam as a global variable in cmdlib, added a TA_HACK in there - - changed the SetQDirFromPath to stick to "baseq3/" when using -moddir - TODO: check standalone files - -23/12/2000 - TTimo - - fixed some sleep/wake code (crashes and wakeup problems on models) - - vfsInitDirectory for TA directory (needs to be checked on linux) - - changed my mind on entities.def, if TA is enabled, load entities-TA.def on top of regular entities.def - - mickey (applied by TTimo) - - some memory overrun fixes - -22/12/2000 - - Fixed plugin Makefiles to not use private/ - - RR2DO2 (applied by leo) - - Fixed SetTallBrush undo - - Added bug report link to help menu - -21/12/2000 - - Daily Linux compilation fixes - - Fixed q3map to read .pk3 files from the directory set by -moddir - - Fixed vfs not listing all files correctly - - Fixed libjpeg crashing on some jpeg files - - Load .def files depending on the current game - -20/12/2000 - - Applied Mickey's patch to fix win32 window position save/load. - - removed missing _msize call - - TTimo - - cleaned up more g_malloc g_free problems, cleaned a INPUT_BUF_SIZE problem in jpeglib - -19/12/2000 - - More manual updates - - Fixed bugs comparing file extensions - - Added VFS to the Alpha branch - - TTimo - - moved game selection to the project settings - - got leo's vfs fixes, started changing the memory allocation scheme to glib - - moved 'free' calls to g_free with a #define in cmdlib, Radiant seems to run nicely again - - removed calls to _msize .. those were causing heap debug assertion failures - - upped more stuff - -18/12/2000 - - Added popup menus with the list of active textures to the find texture dialog - - Fixed some menu checkbuttons - - Changed max number of shader files parsed by q3map to 128 - - Updated manual images - -17/12/2000 - - Fixed bug with the texture window scrollbar range - - Mickey (patched in by TTimo) - - fix to the floating windows mode, don't send windows to the desktop when raising something else (#2659) - - TTimo - - finalized the merge and move into worldspawn commands by adding the undo stuff - - fixed the clamping problems when flipping or mirroring patches - - added 0.5 and 0.25 grids - - added undo to Select_CompleteTall Select_PartialTall and Select_Inside - - added on-the-fly conversion between regular brush coordinates and brush primitives texturing in the plugin API - -15/12/2000 - - Fixed crash on Shift-A (Select all of type) - - Save the state of the toolbar buttons - - Remember the state of the Show Patch Bounding Box button - - Double clicking on an entity on the Entity View tree selects the entity - - Sort the list columns of the map info dialog - - Fixed a bug that would allow multiple Entity View dialogs - - Mickey (patched in by TTimo) - - saving position and size of the entity window between runs and during usage - - TTimo - - two new commands in the drop down menu: - "move into worldspawn" will move selected brushes to worldspawn and eventually delete entities which end up with no brushes - "merge brushes" will merge brushes into an entity (from worldspawn or from another entity) - - added cleaned HTML version of the editor manual in the tree - -14/12/2000 - - When pressing a letter key in the entity window list, scroll to the entity starting with the key pressed - - Fixed backspace not working on the texture subset entry - - Added version check when loading savedinfo.bin - - TTimo - - started implementing Select_Merge and Select_Seperate for workflow improvement on terrain maps - -13/12/2000 - - Finished GtkGenSurf - - RR2DO2 (merged in by TTimo) - - patch to q3map, added option -custinfoparams for custom surface flags (still need documentation) - - TTimo - - zoom out and grid drawing taylored to the world size - -12/12/2000 - TTimo - - quick win32 update to gensurf - - fixed #2610 (MAX_NETMESSAGE) .. needed a consistent rewrite of the way we parse the stream - -11/12/2000 - - Fixed linux compiler errors from recent changes - Not fixed today but I forgot to add those to the Alpha changelog - - Fixed multiple Map Info dialogs bug - - Fixed texture window not scrolling to the top when a new directory is loaded - - Fixed GL Windows grab pointer bug - - Fixed crash after map compilation if the map leaked - - Fixed q3map crash if MAX_SHADER_FILES is reached - -28/11/2000 - - Fixed sleep mode restoring hidden windows (win32) - - Fixed find/replace textures dialog layout and keep it always on top of the main window - - Replaced malloc/free calls with g_malloc/g_free to avoid the win32 limitation - -27/11/2000 - - Removed glu.h dependencies - - Added new file selection dialog - - Removed g_PrefsDlg.m_bDisableAlphaChannel (always FALSE) - - Added shortcuts for sleep and simple patch mesh - - Fixed crash after sleep mode (no GL context current) - -24/11/2000 - - Rewrote the jpeg functions of the image plugin - - Replaced some MFC classes with glib - - More shader plugin fixes - - Fixed bug with select all entities command - - TTimo - - fixed q3map to handle the new LoadJPGBuff length parameter - -22/11/2000 - - Fixed crash in Error() if there's no current GL context - - Fixes to the shaders plugin - - TTimo - - created VC6 project file for image module - - modified the m_pfnError in qerplugin.h to use (char *, ...) construct - -21/11/2000 - - Ensured that the plugins are loaded in the correct order - - Added Sys_FPrintf and Sys_Printf to the plugin interfaces - - Some VC++ fixes - - TTimo - - more fixes to the world size - - modified moduleentry_t so it compiles on win32. need to update the code in all modules probably - - other minor fixes and updates to get everything building on win32 - -20/11/2000 - - Moved image loading code to a plugin - - Fixed some bugs in the shader plugin - - Now using glGenTextures to set texture ids - -19/11/2000 - TTimo - - shader code removed from Radiant core, relies on shader module - - added ctrl-alt-LBUTTON = multiple brush select without selecting whole entities (from TA update) - - added an XML testing proggy in DevDocs/ - -18/11/2000 - TTimo - - shader module is compiling - - reworked the way we deal with required interfaces, - automated the interface request process and added code to check the required modules have been found - -17/11/2000 - - Q1 VFS plugin - - Changes to the VFS API to detect the format supported by a plugin - - Added checks to PluginManager to load the correct VFS plugin - - TTimo - - made a mess with XML MAX_NETMESSAGE error, still not fixed - - merged q3map 1.0r (TA update from Id) into the tree - important files modified: surfaceflags.h qfiles.h - -08/12/2000 - TTimo (shit I'm 24 now) - - added gtk gensurf, VC6 project files are up to date, linux Makefile not checked - - fix some WINAPI stuff on above code - - add idata.h for raw access to editor data - - new _QERAppShaderTable for shader module -> editor functions - - added new entries in various tables (GL, parser etc.) - - shader module is well under way - -16/11/2000 - - Added a color selection dialog function to the plugin API - - Added profile read/write functions to the plugin API - - TTimo - - MAX_NETMESSAGE bug: patched q3map so it sends in several messages if the problem occurs - still need to update Radiant to recognize XML nodes split into several messages (using an input buffer) - - added a test map for MAX_NETMESSAGE: sput.map - - project file for vfspk3and win32 patching - -15/11/2000 - - More plugin cleanup - - Added IsEqualGUID() to qerplugin.h - - TTimo - - merged Alpha back in (didn't try to merge this CHANGES file) - - backported some stuff from the trunk to here, the Sys_Printf, gtk_MessageBox and profile stuff - - created VC project file for gtk-based gensurf plugin - -14/11/2000 - - Fixed DumpUnreferencedShaders() - - TTimo - - added QE_CheckProjectEntity to check paths are following the right conventions - -13/11/2000 - - Fixed bugs in the vfs plugin - - Added support to vfs plugins in Radiant - - TTimo - - updated project file to libxml2-2.2.8, use libxml2 as the directory name for whatever version.. - NOTE: libxml2-2.2.8 needs some patching to compile right.. - -12/11/2000 - TTimo - - all Radiant functions that might be exported in interfaces need to use the WINAPI calling convention - modified the GTK functions code accordingly - - started writing the shaders module - -10/11/2000 - - Added new GTK functions to the plugin API - - Added 'parent' parameter to MessageBox, file_dialog and dir_dialog - - Fixed Help commands (Linux) - -09/11/2000 - - Fixed bug in the Z wnd code - - Fixed copy text from the console (win32) - - TTimo - - moved the libxml library out of the tree, updated the VC6 project files accordingly - -08/11/2000 - - ZWnd always on top (view #2, win32) - - TTimo - - added Escape key to hide the entity inspector - - S and Shift+S now act as toggles on the inspectors - -07/11/2000 - - Added ungroup command to right click menu - - Fixed message box accelerator bug - - Fixed GL error on win32 startup - - TTimo - - additions to the BSP interface - - fixed DestroyCursor error - - clipper caulks faces (and prefs checkbox) - -06/11/2000 - - Cleaned PrtView and TexTool plugins - - Fixed bug in texture menu names (#2506) - - Added splitters to Entity dialog - - TTimo - - started clipper caulk implementation - - fix to the pointfile not drawing in 2D views - - MAX_BUILD_SIDES in q3map debug stream - -05/11/2000 - - Merged Alpha branch with the trunk - - TTimo - - more plugin interface for Q3Build, and plugin SDK additions - - merged q3map Realloc back into Alpha branch - -04/11/2000 - - Fixed crash during startup if Zwnd was hidden in views #2 and #3 - - Fixed ToggleConsole command - - Fixed ToggleEntity and ToggleTexture commands in view #2 - - Fixed plugin Makefiles - - Removed -rdynamic from Radiant link options (crashes pk3man plugin) - -03/11/2000 - TTimo - - directory reorganisation for the plugin SDK, added an interface/ directory - -02/11/2000 - - Save ZWnd state in views #2 and #3 - - Entity dlg always on top (linux) - - Fixed shortcuts.ini parsing bug - - Fixed editpad crash if editpad not present (win32) - - Fixed bugs in the internal shader editor - - Fixed widget_show if window moved after gtk_widget_set_uposition - -================================================================================ - 1.1 beta -================================================================================ - -31/10/2000 - - Continue loading if glXGetProcAddressARB is not present (Utah-GLX fix) - - Fix BSP commands not working if a map is not in "mapspath" (linux) - -30/10/2000 - - fixed the Region commands, "Region > Set brush" is working - Region uses the camera as spawn point. - - Fixed view/show menu initialization - - Fixed warning when starting view #2 - - Fixed z wnd in view #3 - - Fixed win32 sleep mode crashes on views #2 and #3 - - Added "Restart" message when changing texture quality in the preferences - - Cleanup: removed radbsp.cpp (unused) and unzip.cpp (already in pak.a) - -29/10/2000 - - Fixed SIGCHLD handler - - Built 1.1b setups - -28/10/2000 - - Fixed q3map bug visbytes > MAX_MAP_VISIBILITY - - Fixed clipper display bug - - TTimo - - updated quakev2.qe4 with -vlight options - - added checks in q3map to prevent crashing on allocating a winding too big - will stop with an error now. - - added the corresponding editor support for debug messages if MAX_POINTS_ON_WINDING is exceeded - - G_Dewan - - improved q3map, reducing minimal memory footprint by about 45Mb - -27/10/2000 - - Fixed crash in BSP debug window - - Reorganized the preferences dialog - - Fixed q3map Makefile - - Fixed +/- bug in win32 (Gtk patch) - - Fixed Alt shortcuts bug in win32 (Gtk patch) - - Fixed q3map crash when visbytes > MAX_MAP_VISIBILITY - - TTimo - - improved snapshots behaviour, doesn't snapshot non-modified maps - -26/10/2000 - - Fixed patch inspector not showing after it has been closed - - Added 'Reset' button to entity dialog - -25/10/2000 - - Fixed more grid issues - - Fixed load window position bug (saved pos greater than screen resolution) - - Fixed selection nudge bug - - Improved entity windows layout - - Fixed GL font not being recreated when exiting sleep mode - - TTimo - - cleaned m_nTextureTweak and m_bSnapTToGrid - - improved the CycleCapTexturePatch command, now cycles across the 3 planes only - and works on multiple patches at once - -24/10/2000 - - Added an overwrite prompt when saving files - - Fixed 128 and 256 grid display - - Commented-out grouping code (not functional yet) - -23/10/2000 - - Fixed q3map to load jpgs under Linux - - Fixed wake-up crash when floating windows were closed (#2423) - -21/10/2000 - - More q3map and radiant Makefile fixes - - Remember size/position of the entities dialog - -20/10/2000 - - Redirect Gdk warnings - - Draw border around active XY wnd - - Moved some scripts to the Makefile - - Added shift+rclick to zoom in/out - - Removed minimize/maximize buttons for z wnd in floating mode under win32 - - TTimo - - Two new entries in View > Show: Show Outline and Show Axes - Show Outline turns on/off colored outline of the current view - Show Axes turns on/off display of a small axis base in the 2D view - - fix q3map Makefile to use external libxml2 source - - G_DEWAN - - Fix to bogus noshader error message in q3map - -19/10/2000 - - Added new console functions that support colors - - Revised linux makefile for debug/release builds - - Redirect Gtk warnings to the console - - TTimo - - reorganized the entity inspector window, layout depends on the number of flags to get - more space in the comment window. - -18/10/2000 - - Fixed add/remove bsp items in project settings dialog - - Did some cleanup (removed #define WIN32_CONSOLE) - - Fixed console not working in view #3 - - Fixed warning when exiting in views #2 #3 - - TTimo - - fix to entity inspector comment window for the eclass_t on win32 (removed the white squares) - -17/10/2000 - - Fixed texwindow not scrolling when last texture is large - - Added LOD for patches - - Fixed prefab path & user ini in preferences dialog - -13/10/2000 - TTimo (XML branch) - - basic architecture for XML feedback is functional - see radiant/feedback.cpp radiant/watchbsp.cpp q3tools/common2/inout.c - merging back in alpha - -04/10/2000 - TTimo (XML branch) - - sax interface is in Radiant, need to add a state machine and proper processing - -04/10/2000 - TTimo (XML branch) - - experimental use of SAX interface to parse the stream on the server side, see q3tools/q3map/NetTest - -03/10/2000 - TTimo (XML branch) - - adding libxml2 in the repository, based on libxml2-2.2.4 with project files and stuff to build on win32 - -31/09/2000 - TTimo (XML branch) - - new common2/ dir, output system rewritten through Sys_Printf - - experimental use of libxml - -28/09/2000 - TTimo (Inspector branch) - - shift+arrows matches the increments from the surface inspector - - button 'Match Grid' in the SI to set the increment according to current grid - -25/09/2000 - TTimo (Inspector branch) - - fixed crappy bug in SavedInfo.bin upgrade (when the struct sizes don't match) - - surface inspector has inc step dialog boxes (+saved in prefs) - - face selection is always on (was something weird from the prefs) - - undo works better with the surface inspector - -25/09/2000 - - Added ARB_Multitexture support - -21/09/2000 - - Fixed preferences dialog warning - - Added new grid sizes - -20/09/2000 - - Fixed small bugs reported from Fenris - -17/09/2000 - TTimo - - fixed a bug with template project loading / path to the engine safecheck (a weird hidden one) - G_Dewan & TTimo - - fixes to the process spawning (Q_Exec in cmdlib) + appropriate warning and error messages - Fishman - - antialiased drawing in 2D views - -14/09/2000 - TTimo - - radiant.log commandlist.txt and radiant.pid are create in g_strAppPath on win32 and g_strTempPath on linux - - moved the splash screen after the .pid code - - I suspect a bug in the .pid removal, added a check and message box - - help works again on win32, spawning Word with the Q3Rad_Manual.doc (temporary solution of course) - - surface inspector: removed all Q2 related stuff, fixed horizontal shift, reorganized the widgets layout - hooked the widgets to apply the changes on the fly (the inspectors need a good chunk of work) - - fixed a radiant.pid bug - - added icon to MSVC6 project (with some help) - - G_Dewan - - fix to BSP menu order getting mixed up - - fix to the file dialog - -11/09/2000 - - Added splash screen - -25/08/2000 TTimo - - launch sleep mode before running game - - fixed Map_Snapshot bug - - going to sleep works on view n2, raising is still screwed (contexts) - -24/08/2000 TTimo - - fixed some sleep mode stuff - - fixed map snapshot bug - -21/08/2000 - - fixed stuff to build on linux - - Merged in q3map 1.0p - -18/08/2000 - - Removed "High Color Textures" option (always on) - - Removed "Status Point Size" option - -17/08/2000 - - Fixed win32 console issues - -16/08/2000 - - added g_strTempPath - - restore maximized window state - - fixed logo.bmp - -15/08/2000 TTimo - - fixed keyboard shortcuts - - fixed engine path in prefs (must use the file dialog to change) - - fixed a bug related to engine path and project templates - -15/08/2000 - - Removed QE4 update model option (always on) - - Removed Buggy ICD option (always off) - - Reorganized the preferences dialog to take a bit less space - -14/08/2000 TTimo - - using profile.cpp code to read shortcut keys files - - moved DevDocs/changelog.txt to data/changelog.txt - (data/ should be used for user-side stuff and DevDocs/ for developpers) - - added data/quickstart.txt with a beginning of info about the main differences - between Q3Radiant 202 and GtkRadiant. to be used as a doc later. - -13/08/2000 TTimo - - added DevDocs/WIN32SETUP and DevDocs/changelog.txt - changelog.txt is end user changes - WIN32SETUP the TODO list for install specific stuff - - wrapped a first version of the win32 installers (full and patch) - -11/08/2000 TTimo - - quickfix to put undo/redo back in - - added DevDocs/WIN32SETUP, describes what I'm up to with the setup of win32 version - -10/08/2000 TTimo - - added back the window position saving code that was in earlier tree - NOTE: would have rather have it done in prefs than hooked in mainframe_delete and MainFrame::Create - (would have been cleaner IMO) - NOTE: IT'S STILL BROKEN .. I ADDED THE CODE BUT I MUST BE MISSING SOMETHING - NOTE: it doesn't remember the maximized state. It should. - -08/08/2000 TTimo - - fixed win32 build for GLWidget code, added WINAPI calling convention on all exported stuff - - fixed TexTool to compile under win32 - -07/08/2000 TTimo - - fixed some crash with the new jpeg lib - - fixed console logging behaviour (was always turned on at startup) - - added console logging checkbutton in prefs - -07/08/2000 - - Merged the GLWidget branch - - Merged 202 patches - - Fixed "clean" button in the preferences dialog - - Added pid startup detection - - Updated plugin interface with GLWidget functions - - Updated TexTool plugin - -04/08/2000 - - Added "errno" string to the Error() message box - - More 202 patches - -03/08/2000 - - Merged changes from MFC Radiant 202 - - Fixed the win32 GLWidget stuff - -02/08/2000 - - new OpenGL widget to keep all platform specific code in only one file - -01/08/2000 - - Added code to restore the windows when coming out of sleep mode - - Rewrote the TexTool plugin - -31/07/2000 TTimo - - added vc6 projects for PrtView - - tested PrtView and Radiant against latest binary release of Gtk (works great) - - Leo: - - Updated VC5 projects - - Fixed plugin loading under win32 - - Updated PrtView to compile under win32 - - Radiant is now iconified when going in sleep mode - -30/07/2000 TTimo - - prefs dialog for BSP monitoring - - Added data/ directory with entities.def and quakev2.qe4 - - stabilized syntax of v2 project file, same project file for both platforms - - added DevDocs/WIN32BETA with a list of stuff to do before going on public beta on win32 - - added DevDocs/d2u .. handy script to remove linefeeds from DOS files - - added radiant/radiant.proj, project file for source navigator (SN rules) - - Leo: - - Fixed the logfile crash when ~/.q3a/radiant doesn't exist (fenris #1953) - -28/07/2000 TTimo - - Fix to the win32 console to use window's default font - - Added File > Sleep for experimentation - NOTE: we need to keep Radiant minimized when going into sleep mode - -28/07/2000 - - Finished the win32 console replacement - - Fixed bug 1952 (map loading segfault) - - Added a Makefile to the libs dir - -26/07/2000 - - Added PrtView plugin - - Added qvm target to source/Makefile - - Another release candidate sent to QA - -18/07/2000 - - Fixed the slow updates issue in the win32 version - - Added 3 new variables to fix the paths issue - -17/07/2000 - - Fixed the plugin search directory (broken with the changes to g_strAppPath) - -14/07/2000 - - Increased the timer speed in MainFrame::RoutineProcessing - - Added code to release and recreate the contexts to the win32 version - - Fixed the mouse capture under win32 - -13/07/2000 - - Fixed the new path and bsp problems - - Sent new version to QA for testing/release - -12/07/2000 - - Added "tools/" back to g_strAppPath under linux - -11/07/2000 - - Added code to release and the recreate the GL contexts (linux) - -10/07/2000 - - Changed directory structure - -09/07/2000 - - Added CS_OWNDC for win32 with a GDK hack - -07/07/2000 - - Fixed "white textures" bug (gluBuild2DMipmaps bug) - -03/07/2000 -TTimo: - main.cpp l386, removed tools/ appending to g_strAppPath, g_strAppPath is expected to point to the app.. (hope it doesn't break anything) - -02/07/2000 - - Added precompiled headers for faster win32 builds - -01/07/2000 - - Finally got q3asm/lcc working - -26/06/2000 - - 201 patches - - Added screenshot option - - Added an error message if X is running in 8 bits - -23/06/2000 - - Updated with build 200 source - -13/06/2000 - - Remove --noshare option - - Added --nofonts option to workaround a bug using glXUseXFonts in XFree 4.0 - -04/06/2000 - - Fixed bug with the Ctrl-X accelerator for the File/Exit menu - -02/06/2000 - - Converting the TexTool plugin - -30/05/2000 - - Changes to the plugin loading code - -28/05/2000 - - Files with an underscore character are now correctly parsed in the MRU menu - -25/05/2000 - - Fixed _exit bugs - - Fixed bug in CMapStringToString::SetAt - - Fixed copy/paste/clone bug - -24/05/2000 - - Finished applying the 199 patches - - Fixed a bug in CShaderArray::SortShaders() that was calling the wrong version of InsertAt() - - Added numbers to the MRU menu items - -23/05/2000 - - Fixed the floating point bug in gluBuild2DMipmaps - - Fixed the time display after a bsp command is executed - - Applied several patches from the 199 version - - The console is now visible by default - -21/05/2000 - - Added a replacement for gluBuild2DMipmaps - -20/05/2000 - - Fixed the repeating textures bug when playing a map, "brush_primit" must be set to "1". - - Fixed the bug about no current GL context when exiting in computers with 3dfx cards. - - Textures in the directory pointed by "texturepath" are now loaded correctly in Radiant. - - Fixed bug in q3map where it would require a shaderlist.txt file in ~/.q3a/baseq3/scripts. - -19/05/2000 - - Fixed a bug in the multiple directories hack in libs/pakstuff.cc - - Finished the filter in the texture window - - The wait cursor is now correctly set in the XY window - - Added replacements for gluPerspective and gluLookAt - - Textures can now be stored in 2 places: - * The path pointed by "texturepath" (defaults to ~/.q3a/baseq3/textures, - but can be changed in the project settings) - * The base texture path (/baseq3/textures) - - Radiant and the q3map tool now looks for shaders in ~/.q3a/baseq3/shaderlist.txt - and /baseq3/scripts/shaderlist.txt - -18/05/2000 - - Plugin menu fixes - - Created a simple text editor to edit the shaders (instead of calling an external program) - - Copy and paste now work - - Fixed some bugs with the MRU menu - - Some menu items are now enabled/disabled correctly in MainFrame::RoutineProcessing () - - Added a new command line option (--cdpath) to set the CD-ROM path - - Fixed some bugs in the entity window, now it's possible to add/edit/remove properties - - New directory paths: - * maps now default to ~/.q3a/baseq3/maps - * autosave files are saved in ~/.q3a/baseq3/maps - * .pk3 files can be in ~/.q3a/baseq3, /baseq3 and in the CD-ROM - -17/05/2000 - - Fixed bug deselecting a brush after the surface dialog is open - - hide cursor when right-dragging XYWnd - - files saved to /tmp are now saved in ~/.q3a/radiant - - Disabled undo - - Fixed a bug in FillTextureMenu - - User can now correctly change the accelerators at run-time - - Accelerators are read from ~/.q3a/radiant/radiant.ini - -16/05/2000 - - Finished the patch inspector - - Finished the texture toolbar - - more small bug fixes - -11/05/2000 - - Finished the GroupDlg stuff - - Added support to read pak files from the Quake3 CD-ROM - - moved /tmp/paklog.txt to ~/.q3a/radiant/paklog - - added functions to replace GetKeyState and SetCursorPos - - fixed the command key handlers for the mainwindow diff --git a/misc/mediasource/extra/netradiant-src/DoxyConfig b/misc/mediasource/extra/netradiant-src/DoxyConfig deleted file mode 100644 index b9c0619d..00000000 --- a/misc/mediasource/extra/netradiant-src/DoxyConfig +++ /dev/null @@ -1,47 +0,0 @@ -# Included Doxygen Config file -#--------------------------------------------------------------------------- -# Project name & version number -#--------------------------------------------------------------------------- -PROJECT_NAME = -PROJECT_NUMBER = - -#--------------------------------------------------------------------------- -# Where to put the output -# Note: The images dir should be next to the created html dir within the -# output dir. -# eg; -# [Current Dir] -# L__[OUTPUT_DIRECTORY] -# L__[html] -# L__[images] -#--------------------------------------------------------------------------- -OUTPUT_DIRECTORY = ../GtkRadiant-doxygen - -#--------------------------------------------------------------------------- -# Where to read the sources -# you can add more than one source... -# INPUT = radiant/ \ -# tools/quake3/q3map \ -# tools/quake3/q3data -# -# Recursive is set on, so setting it to ./ (current dir) would read source -# files recursively from the current dir down. (which would take a while) -# -# eg: To document just include, if the current directory is ../GtkRadiant/ -# then... -#--------------------------------------------------------------------------- -INPUT = radiant/ - -#--------------------------------------------------------------------------- -# Misc settings -# TAB_SIZE - sets the indenting for the inline source and the source -# browser -# INCLUDE_PATH - will include documentation for included files from other -# packages. You can specify more than one path the same as -# shown in the INPUT example Leave it blank if you don't want -# this. -# PERL_PATH - path to the perl executable -# -#--------------------------------------------------------------------------- -PERL_PATH = /usr/bin/perl - diff --git a/misc/mediasource/extra/netradiant-src/Doxyfile b/misc/mediasource/extra/netradiant-src/Doxyfile deleted file mode 100644 index b87c164f..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxyfile +++ /dev/null @@ -1,1117 +0,0 @@ -# Doxyfile 1.3.6 - -# This file describes the settings to be used by the documentation system -# doxygen (www.doxygen.org) for a project -# -# All text after a hash (#) is considered a comment and will be ignored -# The format is: -# TAG = value [value, ...] -# For lists items can also be appended using: -# TAG += value [value, ...] -# Values that contain spaces should be placed between quotes (" ") - -#--------------------------------------------------------------------------- -# Project related configuration options -#--------------------------------------------------------------------------- - -# The PROJECT_NAME tag is a single word (or a sequence of words surrounded -# by quotes) that should identify the project. - -PROJECT_NAME = GtkRadiant - -# The PROJECT_NUMBER tag can be used to enter a project or revision number. -# This could be handy for archiving the generated documentation or -# if some version control system is used. - -PROJECT_NUMBER = 1.5.0 - -# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) -# base path where the generated documentation will be put. -# If a relative path is entered, it will be relative to the location -# where doxygen was started. If left blank the current directory will be used. - -OUTPUT_DIRECTORY = doxygen-out - -# The OUTPUT_LANGUAGE tag is used to specify the language in which all -# documentation generated by doxygen is written. Doxygen will use this -# information to generate all constant output in the proper language. -# The default language is English, other supported languages are: -# Brazilian, Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, -# Finnish, French, German, Greek, Hungarian, Italian, Japanese, Japanese-en -# (Japanese with English messages), Korean, Korean-en, Norwegian, Polish, Portuguese, -# Romanian, Russian, Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. - -OUTPUT_LANGUAGE = English - -# This tag can be used to specify the encoding used in the generated output. -# The encoding is not always determined by the language that is chosen, -# but also whether or not the output is meant for Windows or non-Windows users. -# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES -# forces the Windows encoding (this is the default for the Windows binary), -# whereas setting the tag to NO uses a Unix-style encoding (the default for -# all platforms other than Windows). - -USE_WINDOWS_ENCODING = YES - -# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will -# include brief member descriptions after the members that are listed in -# the file and class documentation (similar to JavaDoc). -# Set to NO to disable this. - -BRIEF_MEMBER_DESC = YES - -# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend -# the brief description of a member or function before the detailed description. -# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the -# brief descriptions will be completely suppressed. - -REPEAT_BRIEF = YES - -# This tag implements a quasi-intelligent brief description abbreviator -# that is used to form the text in various listings. Each string -# in this list, if found as the leading text of the brief description, will be -# stripped from the text and the result after processing the whole list, is used -# as the annotated text. Otherwise, the brief description is used as-is. If left -# blank, the following values are used ("$name" is automatically replaced with the -# name of the entity): "The $name class" "The $name widget" "The $name file" -# "is" "provides" "specifies" "contains" "represents" "a" "an" "the" - -ABBREVIATE_BRIEF = - -# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then -# Doxygen will generate a detailed section even if there is only a brief -# description. - -ALWAYS_DETAILED_SEC = NO - -# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all inherited -# members of a class in the documentation of that class as if those members were -# ordinary class members. Constructors, destructors and assignment operators of -# the base classes will not be shown. - -INLINE_INHERITED_MEMB = NO - -# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full -# path before files name in the file list and in the header files. If set -# to NO the shortest path that makes the file name unique will be used. - -FULL_PATH_NAMES = NO - -# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag -# can be used to strip a user-defined part of the path. Stripping is -# only done if one of the specified strings matches the left-hand part of -# the path. It is allowed to use relative paths in the argument list. -# If left blank the directory from which doxygen is run is used as the -# path to strip. - -STRIP_FROM_PATH = - -# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter -# (but less readable) file names. This can be useful is your file systems -# doesn't support long names like on DOS, Mac, or CD-ROM. - -SHORT_NAMES = NO - -# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen -# will interpret the first line (until the first dot) of a JavaDoc-style -# comment as the brief description. If set to NO, the JavaDoc -# comments will behave just like the Qt-style comments (thus requiring an -# explicit @brief command for a brief description. - -JAVADOC_AUTOBRIEF = NO - -# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen -# treat a multi-line C++ special comment block (i.e. a block of //! or /// -# comments) as a brief description. This used to be the default behaviour. -# The new default is to treat a multi-line C++ comment block as a detailed -# description. Set this tag to YES if you prefer the old behaviour instead. - -MULTILINE_CPP_IS_BRIEF = NO - -# If the DETAILS_AT_TOP tag is set to YES then Doxygen -# will output the detailed description near the top, like JavaDoc. -# If set to NO, the detailed description appears after the member -# documentation. - -DETAILS_AT_TOP = NO - -# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented -# member inherits the documentation from any documented member that it -# re-implements. - -INHERIT_DOCS = YES - -# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC -# tag is set to YES, then doxygen will reuse the documentation of the first -# member in the group (if any) for the other members of the group. By default -# all members of a group must be documented explicitly. - -DISTRIBUTE_GROUP_DOC = NO - -# The TAB_SIZE tag can be used to set the number of spaces in a tab. -# Doxygen uses this value to replace tabs by spaces in code fragments. - -TAB_SIZE = 2 - -# This tag can be used to specify a number of aliases that acts -# as commands in the documentation. An alias has the form "name=value". -# For example adding "sideeffect=\par Side Effects:\n" will allow you to -# put the command \sideeffect (or @sideeffect) in the documentation, which -# will result in a user-defined paragraph with heading "Side Effects:". -# You can put \n's in the value part of an alias to insert newlines. - -ALIASES = - -# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources -# only. Doxygen will then generate output that is more tailored for C. -# For instance, some of the names that are used will be different. The list -# of all members will be omitted, etc. - -OPTIMIZE_OUTPUT_FOR_C = NO - -# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java sources -# only. Doxygen will then generate output that is more tailored for Java. -# For instance, namespaces will be presented as packages, qualified scopes -# will look different, etc. - -OPTIMIZE_OUTPUT_JAVA = NO - -# Set the SUBGROUPING tag to YES (the default) to allow class member groups of -# the same type (for instance a group of public functions) to be put as a -# subgroup of that type (e.g. under the Public Functions section). Set it to -# NO to prevent subgrouping. Alternatively, this can be done per class using -# the \nosubgrouping command. - -SUBGROUPING = YES - -#--------------------------------------------------------------------------- -# Build related configuration options -#--------------------------------------------------------------------------- - -# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in -# documentation are documented, even if no documentation was available. -# Private class members and static file members will be hidden unless -# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES - -EXTRACT_ALL = NO - -# If the EXTRACT_PRIVATE tag is set to YES all private members of a class -# will be included in the documentation. - -EXTRACT_PRIVATE = NO - -# If the EXTRACT_STATIC tag is set to YES all static members of a file -# will be included in the documentation. - -EXTRACT_STATIC = YES - -# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) -# defined locally in source files will be included in the documentation. -# If set to NO only classes defined in header files are included. - -EXTRACT_LOCAL_CLASSES = YES - -# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all -# undocumented members of documented classes, files or namespaces. -# If set to NO (the default) these members will be included in the -# various overviews, but no documentation section is generated. -# This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_MEMBERS = NO - -# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all -# undocumented classes that are normally visible in the class hierarchy. -# If set to NO (the default) these classes will be included in the various -# overviews. This option has no effect if EXTRACT_ALL is enabled. - -HIDE_UNDOC_CLASSES = NO - -# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all -# friend (class|struct|union) declarations. -# If set to NO (the default) these declarations will be included in the -# documentation. - -HIDE_FRIEND_COMPOUNDS = NO - -# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any -# documentation blocks found inside the body of a function. -# If set to NO (the default) these blocks will be appended to the -# function's detailed documentation block. - -HIDE_IN_BODY_DOCS = NO - -# The INTERNAL_DOCS tag determines if documentation -# that is typed after a \internal command is included. If the tag is set -# to NO (the default) then the documentation will be excluded. -# Set it to YES to include the internal documentation. - -INTERNAL_DOCS = NO - -# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate -# file names in lower-case letters. If set to YES upper-case letters are also -# allowed. This is useful if you have classes or files whose names only differ -# in case and if your file system supports case sensitive file names. Windows -# users are advised to set this option to NO. - -CASE_SENSE_NAMES = YES - -# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen -# will show members with their full class and namespace scopes in the -# documentation. If set to YES the scope will be hidden. - -HIDE_SCOPE_NAMES = NO - -# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen -# will put a list of the files that are included by a file in the documentation -# of that file. - -SHOW_INCLUDE_FILES = YES - -# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] -# is inserted in the documentation for inline members. - -INLINE_INFO = YES - -# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen -# will sort the (detailed) documentation of file and class members -# alphabetically by member name. If set to NO the members will appear in -# declaration order. - -SORT_MEMBER_DOCS = YES - -# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the -# brief documentation of file, namespace and class members alphabetically -# by member name. If set to NO (the default) the members will appear in -# declaration order. - -SORT_BRIEF_DOCS = NO - -# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be -# sorted by fully-qualified names, including namespaces. If set to -# NO (the default), the class list will be sorted only by class name, -# not including the namespace part. -# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. -# Note: This option applies only to the class list, not to the -# alphabetical list. - -SORT_BY_SCOPE_NAME = NO - -# The GENERATE_TODOLIST tag can be used to enable (YES) or -# disable (NO) the todo list. This list is created by putting \todo -# commands in the documentation. - -GENERATE_TODOLIST = YES - -# The GENERATE_TESTLIST tag can be used to enable (YES) or -# disable (NO) the test list. This list is created by putting \test -# commands in the documentation. - -GENERATE_TESTLIST = YES - -# The GENERATE_BUGLIST tag can be used to enable (YES) or -# disable (NO) the bug list. This list is created by putting \bug -# commands in the documentation. - -GENERATE_BUGLIST = YES - -# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or -# disable (NO) the deprecated list. This list is created by putting -# \deprecated commands in the documentation. - -GENERATE_DEPRECATEDLIST= YES - -# The ENABLED_SECTIONS tag can be used to enable conditional -# documentation sections, marked by \if sectionname ... \endif. - -ENABLED_SECTIONS = - -# The MAX_INITIALIZER_LINES tag determines the maximum number of lines -# the initial value of a variable or define consists of for it to appear in -# the documentation. If the initializer consists of more lines than specified -# here it will be hidden. Use a value of 0 to hide initializers completely. -# The appearance of the initializer of individual variables and defines in the -# documentation can be controlled using \showinitializer or \hideinitializer -# command in the documentation regardless of this setting. - -MAX_INITIALIZER_LINES = 30 - -# Set the SHOW_USED_FILES tag to NO to disable the list of files generated -# at the bottom of the documentation of classes and structs. If set to YES the -# list will mention the files that were used to generate the documentation. - -SHOW_USED_FILES = YES - -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- - -# The QUIET tag can be used to turn on/off the messages that are generated -# by doxygen. Possible values are YES and NO. If left blank NO is used. - -QUIET = NO - -# The WARNINGS tag can be used to turn on/off the warning messages that are -# generated by doxygen. Possible values are YES and NO. If left blank -# NO is used. - -WARNINGS = YES - -# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings -# for undocumented members. If EXTRACT_ALL is set to YES then this flag will -# automatically be disabled. - -WARN_IF_UNDOCUMENTED = NO - -# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for -# potential errors in the documentation, such as not documenting some -# parameters in a documented function, or documenting parameters that -# don't exist or using markup commands wrongly. - -WARN_IF_DOC_ERROR = YES - -# The WARN_FORMAT tag determines the format of the warning messages that -# doxygen can produce. The string should contain the $file, $line, and $text -# tags, which will be replaced by the file and line number from which the -# warning originated and the warning text. - -WARN_FORMAT = "$file:$line: $text" - -# The WARN_LOGFILE tag can be used to specify a file to which warning -# and error messages should be written. If left blank the output is written -# to stderr. - -WARN_LOGFILE = - -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- - -# The INPUT tag can be used to specify the files and/or directories that contain -# documented source files. You may enter file names like "myfile.cpp" or -# directories like "/usr/src/myproject". Separate the files or directories -# with spaces. - -INPUT = radiant/ plugins/ libs/ include/ - -# If the value of the INPUT tag contains directories, you can use the -# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank the following patterns are tested: -# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx *.hpp -# *.h++ *.idl *.odl *.cs *.php *.php3 *.inc - -FILE_PATTERNS = - -# The RECURSIVE tag can be used to turn specify whether or not subdirectories -# should be searched for input files as well. Possible values are YES and NO. -# If left blank NO is used. - -RECURSIVE = YES - -# The EXCLUDE tag can be used to specify files and/or directories that should -# excluded from the INPUT source files. This way you can easily exclude a -# subdirectory from a directory tree whose root is specified with the INPUT tag. - -EXCLUDE = - -# The EXCLUDE_SYMLINKS tag can be used select whether or not files or directories -# that are symbolic links (a Unix filesystem feature) are excluded from the input. - -EXCLUDE_SYMLINKS = NO - -# If the value of the INPUT tag contains directories, you can use the -# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude -# certain files from those directories. - -EXCLUDE_PATTERNS = */.svn/* - -# The EXAMPLE_PATH tag can be used to specify one or more files or -# directories that contain example code fragments that are included (see -# the \include command). - -EXAMPLE_PATH = radiant/ plugins/ libs/ include/ - -# If the value of the EXAMPLE_PATH tag contains directories, you can use the -# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp -# and *.h) to filter out the source-files in the directories. If left -# blank all files are included. - -EXAMPLE_PATTERNS = - -# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be -# searched for input files to be used with the \include or \dontinclude -# commands irrespective of the value of the RECURSIVE tag. -# Possible values are YES and NO. If left blank NO is used. - -EXAMPLE_RECURSIVE = NO - -# The IMAGE_PATH tag can be used to specify one or more files or -# directories that contain image that are included in the documentation (see -# the \image command). - -IMAGE_PATH = - -# The INPUT_FILTER tag can be used to specify a program that doxygen should -# invoke to filter for each input file. Doxygen will invoke the filter program -# by executing (via popen()) the command , where -# is the value of the INPUT_FILTER tag, and is the name of an -# input file. Doxygen will then use the output that the filter program writes -# to standard output. - -INPUT_FILTER = - -# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using -# INPUT_FILTER) will be used to filter the input files when producing source -# files to browse (i.e. when SOURCE_BROWSER is set to YES). - -FILTER_SOURCE_FILES = NO - -#--------------------------------------------------------------------------- -# configuration options related to source browsing -#--------------------------------------------------------------------------- - -# If the SOURCE_BROWSER tag is set to YES then a list of source files will -# be generated. Documented entities will be cross-referenced with these sources. -# Note: To get rid of all source code in the generated output, make sure also -# VERBATIM_HEADERS is set to NO. - -SOURCE_BROWSER = NO - -# Setting the INLINE_SOURCES tag to YES will include the body -# of functions and classes directly in the documentation. - -INLINE_SOURCES = NO - -# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct -# doxygen to hide any special comment blocks from generated source code -# fragments. Normal C and C++ comments will always remain visible. - -STRIP_CODE_COMMENTS = YES - -# If the REFERENCED_BY_RELATION tag is set to YES (the default) -# then for each documented function all documented -# functions referencing it will be listed. - -REFERENCED_BY_RELATION = YES - -# If the REFERENCES_RELATION tag is set to YES (the default) -# then for each documented function all documented entities -# called/used by that function will be listed. - -REFERENCES_RELATION = YES - -# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen -# will generate a verbatim copy of the header file for each class for -# which an include is specified. Set to NO to disable this. - -VERBATIM_HEADERS = YES - -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- - -# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index -# of all compounds will be generated. Enable this if the project -# contains a lot of classes, structs, unions or interfaces. - -ALPHABETICAL_INDEX = NO - -# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then -# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns -# in which this list will be split (can be a number in the range [1..20]) - -COLS_IN_ALPHA_INDEX = 5 - -# In case all classes in a project start with a common prefix, all -# classes will be put under the same header in the alphabetical index. -# The IGNORE_PREFIX tag can be used to specify one or more prefixes that -# should be ignored while generating the index headers. - -IGNORE_PREFIX = - -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- - -# If the GENERATE_HTML tag is set to YES (the default) Doxygen will -# generate HTML output. - -GENERATE_HTML = YES - -# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `html' will be used as the default path. - -HTML_OUTPUT = html - -# The HTML_FILE_EXTENSION tag can be used to specify the file extension for -# each generated HTML page (for example: .htm,.php,.asp). If it is left blank -# doxygen will generate files with .html extension. - -HTML_FILE_EXTENSION = .html - -# The HTML_HEADER tag can be used to specify a personal HTML header for -# each generated HTML page. If it is left blank doxygen will generate a -# standard header. - -HTML_HEADER = - -# The HTML_FOOTER tag can be used to specify a personal HTML footer for -# each generated HTML page. If it is left blank doxygen will generate a -# standard footer. - -HTML_FOOTER = - -# The HTML_STYLESHEET tag can be used to specify a user-defined cascading -# style sheet that is used by each HTML page. It can be used to -# fine-tune the look of the HTML output. If the tag is left blank doxygen -# will generate a default style sheet. Note that doxygen will try to copy -# the style sheet file to the HTML output directory, so don't put your own -# stylesheet in the HTML output directory as well, or it will be erased! - -HTML_STYLESHEET = - -# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, -# files or namespaces will be aligned in HTML using tables. If set to -# NO a bullet list will be used. - -HTML_ALIGN_MEMBERS = YES - -# If the GENERATE_HTMLHELP tag is set to YES, additional index files -# will be generated that can be used as input for tools like the -# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) -# of the generated HTML documentation. - -GENERATE_HTMLHELP = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can -# be used to specify the file name of the resulting .chm file. You -# can add a path in front of the file if the result should not be -# written to the html output directory. - -CHM_FILE = - -# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can -# be used to specify the location (absolute path including file name) of -# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run -# the HTML help compiler on the generated index.hhp. - -HHC_LOCATION = - -# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag -# controls if a separate .chi index file is generated (YES) or that -# it should be included in the master .chm file (NO). - -GENERATE_CHI = NO - -# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag -# controls whether a binary table of contents is generated (YES) or a -# normal table of contents (NO) in the .chm file. - -BINARY_TOC = NO - -# The TOC_EXPAND flag can be set to YES to add extra items for group members -# to the contents of the HTML help documentation and to the tree view. - -TOC_EXPAND = NO - -# The DISABLE_INDEX tag can be used to turn on/off the condensed index at -# top of each HTML page. The value NO (the default) enables the index and -# the value YES disables it. - -DISABLE_INDEX = NO - -# This tag can be used to set the number of enum values (range [1..20]) -# that doxygen will group on one line in the generated HTML documentation. - -ENUM_VALUES_PER_LINE = 4 - -# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be -# generated containing a tree-like index structure (just like the one that -# is generated for HTML Help). For this to work a browser that supports -# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, -# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are -# probably better off using the HTML help feature. - -GENERATE_TREEVIEW = NO - -# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be -# used to set the initial width (in pixels) of the frame in which the tree -# is shown. - -TREEVIEW_WIDTH = 250 - -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- - -# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will -# generate Latex output. - -GENERATE_LATEX = YES - -# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `latex' will be used as the default path. - -LATEX_OUTPUT = latex - -# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be -# invoked. If left blank `latex' will be used as the default command name. - -LATEX_CMD_NAME = latex - -# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to -# generate index for LaTeX. If left blank `makeindex' will be used as the -# default command name. - -MAKEINDEX_CMD_NAME = makeindex - -# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact -# LaTeX documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_LATEX = NO - -# The PAPER_TYPE tag can be used to set the paper type that is used -# by the printer. Possible values are: a4, a4wide, letter, legal and -# executive. If left blank a4wide will be used. - -PAPER_TYPE = a4wide - -# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX -# packages that should be included in the LaTeX output. - -EXTRA_PACKAGES = - -# The LATEX_HEADER tag can be used to specify a personal LaTeX header for -# the generated latex document. The header should contain everything until -# the first chapter. If it is left blank doxygen will generate a -# standard header. Notice: only use this tag if you know what you are doing! - -LATEX_HEADER = - -# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated -# is prepared for conversion to pdf (using ps2pdf). The pdf file will -# contain links (just like the HTML output) instead of page references -# This makes the output suitable for online browsing using a pdf viewer. - -PDF_HYPERLINKS = NO - -# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of -# plain latex in the generated Makefile. Set this option to YES to get a -# higher quality PDF documentation. - -USE_PDFLATEX = NO - -# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. -# command to the generated LaTeX files. This will instruct LaTeX to keep -# running if errors occur, instead of asking the user for help. -# This option is also used when generating formulas in HTML. - -LATEX_BATCHMODE = NO - -# If LATEX_HIDE_INDICES is set to YES then doxygen will not -# include the index chapters (such as File Index, Compound Index, etc.) -# in the output. - -LATEX_HIDE_INDICES = NO - -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- - -# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output -# The RTF output is optimized for Word 97 and may not look very pretty with -# other RTF readers or editors. - -GENERATE_RTF = NO - -# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `rtf' will be used as the default path. - -RTF_OUTPUT = rtf - -# If the COMPACT_RTF tag is set to YES Doxygen generates more compact -# RTF documents. This may be useful for small projects and may help to -# save some trees in general. - -COMPACT_RTF = NO - -# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated -# will contain hyperlink fields. The RTF file will -# contain links (just like the HTML output) instead of page references. -# This makes the output suitable for online browsing using WORD or other -# programs which support those fields. -# Note: wordpad (write) and others do not support links. - -RTF_HYPERLINKS = NO - -# Load stylesheet definitions from file. Syntax is similar to doxygen's -# config file, i.e. a series of assignments. You only have to provide -# replacements, missing definitions are set to their default value. - -RTF_STYLESHEET_FILE = - -# Set optional variables used in the generation of an rtf document. -# Syntax is similar to doxygen's config file. - -RTF_EXTENSIONS_FILE = - -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- - -# If the GENERATE_MAN tag is set to YES (the default) Doxygen will -# generate man pages - -GENERATE_MAN = NO - -# The MAN_OUTPUT tag is used to specify where the man pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `man' will be used as the default path. - -MAN_OUTPUT = man - -# The MAN_EXTENSION tag determines the extension that is added to -# the generated man pages (default is the subroutine's section .3) - -MAN_EXTENSION = .3 - -# If the MAN_LINKS tag is set to YES and Doxygen generates man output, -# then it will generate one additional man file for each entity -# documented in the real man page(s). These additional files -# only source the real man page, but without them the man command -# would be unable to find the correct page. The default is NO. - -MAN_LINKS = NO - -#--------------------------------------------------------------------------- -# configuration options related to the XML output -#--------------------------------------------------------------------------- - -# If the GENERATE_XML tag is set to YES Doxygen will -# generate an XML file that captures the structure of -# the code including all documentation. - -GENERATE_XML = YES - -# The XML_OUTPUT tag is used to specify where the XML pages will be put. -# If a relative path is entered the value of OUTPUT_DIRECTORY will be -# put in front of it. If left blank `xml' will be used as the default path. - -XML_OUTPUT = doxygen-xml - -# The XML_SCHEMA tag can be used to specify an XML schema, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_SCHEMA = - -# The XML_DTD tag can be used to specify an XML DTD, -# which can be used by a validating XML parser to check the -# syntax of the XML files. - -XML_DTD = - -# If the XML_PROGRAMLISTING tag is set to YES Doxygen will -# dump the program listings (including syntax highlighting -# and cross-referencing information) to the XML output. Note that -# enabling this will significantly increase the size of the XML output. - -XML_PROGRAMLISTING = NO - -#--------------------------------------------------------------------------- -# configuration options for the AutoGen Definitions output -#--------------------------------------------------------------------------- - -# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will -# generate an AutoGen Definitions (see autogen.sf.net) file -# that captures the structure of the code including all -# documentation. Note that this feature is still experimental -# and incomplete at the moment. - -GENERATE_AUTOGEN_DEF = NO - -#--------------------------------------------------------------------------- -# configuration options related to the Perl module output -#--------------------------------------------------------------------------- - -# If the GENERATE_PERLMOD tag is set to YES Doxygen will -# generate a Perl module file that captures the structure of -# the code including all documentation. Note that this -# feature is still experimental and incomplete at the -# moment. - -GENERATE_PERLMOD = NO - -# If the PERLMOD_LATEX tag is set to YES Doxygen will generate -# the necessary Makefile rules, Perl scripts and LaTeX code to be able -# to generate PDF and DVI output from the Perl module output. - -PERLMOD_LATEX = NO - -# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be -# nicely formatted so it can be parsed by a human reader. This is useful -# if you want to understand what is going on. On the other hand, if this -# tag is set to NO the size of the Perl module output will be much smaller -# and Perl will parse it just the same. - -PERLMOD_PRETTY = YES - -# The names of the make variables in the generated doxyrules.make file -# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. -# This is useful so different doxyrules.make files included by the same -# Makefile don't overwrite each other's variables. - -PERLMOD_MAKEVAR_PREFIX = - -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- - -# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will -# evaluate all C-preprocessor directives found in the sources and include -# files. - -ENABLE_PREPROCESSING = YES - -# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro -# names in the source code. If set to NO (the default) only conditional -# compilation will be performed. Macro expansion can be done in a controlled -# way by setting EXPAND_ONLY_PREDEF to YES. - -MACRO_EXPANSION = NO - -# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES -# then the macro expansion is limited to the macros specified with the -# PREDEFINED and EXPAND_AS_PREDEFINED tags. - -EXPAND_ONLY_PREDEF = NO - -# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files -# in the INCLUDE_PATH (see below) will be search if a #include is found. - -SEARCH_INCLUDES = YES - -# The INCLUDE_PATH tag can be used to specify one or more directories that -# contain include files that are not input files but should be processed by -# the preprocessor. - -INCLUDE_PATH = - -# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard -# patterns (like *.h and *.hpp) to filter out the header-files in the -# directories. If left blank, the patterns specified with FILE_PATTERNS will -# be used. - -INCLUDE_FILE_PATTERNS = - -# The PREDEFINED tag can be used to specify one or more macro names that -# are defined before the preprocessor is started (similar to the -D option of -# gcc). The argument of the tag is a list of macros of the form: name -# or name=definition (no spaces). If the definition and the = are -# omitted =1 is assumed. - -PREDEFINED = - -# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then -# this tag can be used to specify a list of macro names that should be expanded. -# The macro definition that is found in the sources will be used. -# Use the PREDEFINED tag if you want to use a different macro definition. - -EXPAND_AS_DEFINED = - -# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then -# doxygen's preprocessor will remove all function-like macros that are alone -# on a line, have an all uppercase name, and do not end with a semicolon. Such -# function macros are typically used for boiler-plate code, and will confuse the -# parser if not removed. - -SKIP_FUNCTION_MACROS = YES - -#--------------------------------------------------------------------------- -# Configuration::additions related to external references -#--------------------------------------------------------------------------- - -# The TAGFILES option can be used to specify one or more tagfiles. -# Optionally an initial location of the external documentation -# can be added for each tagfile. The format of a tag file without -# this location is as follows: -# TAGFILES = file1 file2 ... -# Adding location for the tag files is done as follows: -# TAGFILES = file1=loc1 "file2 = loc2" ... -# where "loc1" and "loc2" can be relative or absolute paths or -# URLs. If a location is present for each tag, the installdox tool -# does not have to be run to correct the links. -# Note that each tag file must have a unique name -# (where the name does NOT include the path) -# If a tag file is not located in the directory in which doxygen -# is run, you must also specify the path to the tagfile here. - -TAGFILES = - -# When a file name is specified after GENERATE_TAGFILE, doxygen will create -# a tag file that is based on the input files it reads. - -GENERATE_TAGFILE = - -# If the ALLEXTERNALS tag is set to YES all external classes will be listed -# in the class index. If set to NO only the inherited external classes -# will be listed. - -ALLEXTERNALS = NO - -# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed -# in the modules index. If set to NO, only the current project's groups will -# be listed. - -EXTERNAL_GROUPS = YES - -# The PERL_PATH should be the absolute path and name of the perl script -# interpreter (i.e. the result of `which perl'). - -PERL_PATH = /usr/bin/perl - -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- - -# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will -# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base or -# super classes. Setting the tag to NO turns the diagrams off. Note that this -# option is superseded by the HAVE_DOT option below. This is only a fallback. It is -# recommended to install and use dot, since it yields more powerful graphs. - -CLASS_DIAGRAMS = YES - -# If set to YES, the inheritance and collaboration graphs will hide -# inheritance and usage relations if the target is undocumented -# or is not a class. - -HIDE_UNDOC_RELATIONS = YES - -# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is -# available from the path. This tool is part of Graphviz, a graph visualization -# toolkit from AT&T and Lucent Bell Labs. The other options in this section -# have no effect if this option is set to NO (the default) - -HAVE_DOT = YES - -# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect inheritance relations. Setting this tag to YES will force the -# the CLASS_DIAGRAMS tag to NO. - -CLASS_GRAPH = YES - -# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen -# will generate a graph for each documented class showing the direct and -# indirect implementation dependencies (inheritance, containment, and -# class references variables) of the class with other documented classes. - -COLLABORATION_GRAPH = YES - -# If the UML_LOOK tag is set to YES doxygen will generate inheritance and -# collaboration diagrams in a style similar to the OMG's Unified Modeling -# Language. - -UML_LOOK = NO - -# If set to YES, the inheritance and collaboration graphs will show the -# relations between templates and their instances. - -TEMPLATE_RELATIONS = YES - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT -# tags are set to YES then doxygen will generate a graph for each documented -# file showing the direct and indirect include dependencies of the file with -# other documented files. - -INCLUDE_GRAPH = YES - -# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and -# HAVE_DOT tags are set to YES then doxygen will generate a graph for each -# documented header file showing the documented files that directly or -# indirectly include this file. - -INCLUDED_BY_GRAPH = YES - -# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will -# generate a call dependency graph for every global function or class method. -# Note that enabling this option will significantly increase the time of a run. -# So in most cases it will be better to enable call graphs for selected -# functions only using the \callgraph command. - -CALL_GRAPH = NO - -# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen -# will graphical hierarchy of all classes instead of a textual one. - -GRAPHICAL_HIERARCHY = YES - -# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images -# generated by dot. Possible values are png, jpg, or gif -# If left blank png will be used. - -DOT_IMAGE_FORMAT = png - -# The tag DOT_PATH can be used to specify the path where the dot tool can be -# found. If left blank, it is assumed the dot tool can be found on the path. - -DOT_PATH = - -# The DOTFILE_DIRS tag can be used to specify one or more directories that -# contain dot files that are included in the documentation (see the -# \dotfile command). - -DOTFILE_DIRS = - -# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width -# (in pixels) of the graphs generated by dot. If a graph becomes larger than -# this value, doxygen will try to truncate the graph, so that it fits within -# the specified constraint. Beware that most browsers cannot cope with very -# large images. - -MAX_DOT_GRAPH_WIDTH = 1024 - -# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height -# (in pixels) of the graphs generated by dot. If a graph becomes larger than -# this value, doxygen will try to truncate the graph, so that it fits within -# the specified constraint. Beware that most browsers cannot cope with very -# large images. - -MAX_DOT_GRAPH_HEIGHT = 1024 - -# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the -# graphs generated by dot. A depth value of 3 means that only nodes reachable -# from the root by following a path via at most 3 edges will be shown. Nodes that -# lay further from the root node will be omitted. Note that setting this option to -# 1 or 2 may greatly reduce the computation time needed for large code bases. Also -# note that a graph may be further truncated if the graph's image dimensions are -# not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH and MAX_DOT_GRAPH_HEIGHT). -# If 0 is used for the depth value (the default), the graph is not depth-constrained. - -MAX_DOT_GRAPH_DEPTH = 0 - -# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will -# generate a legend page explaining the meaning of the various boxes and -# arrows in the dot generated graphs. - -GENERATE_LEGEND = YES - -# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will -# remove the intermediate dot files that are used to generate -# the various graphs. - -DOT_CLEANUP = YES - -#--------------------------------------------------------------------------- -# Configuration::additions related to the search engine -#--------------------------------------------------------------------------- - -# The SEARCHENGINE tag specifies whether or not a search engine should be -# used. If set to NO the values of all tags below this one will be ignored. - -SEARCHENGINE = NO diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/Doxyfile b/misc/mediasource/extra/netradiant-src/Doxygen_files/Doxyfile deleted file mode 100644 index 51bd498a..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/Doxyfile +++ /dev/null @@ -1,159 +0,0 @@ -# Doxyfile 1.2.5-20010304 -#--------------------------------------------------------------------------- -# General configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = -PROJECT_NUMBER = -OUTPUT_DIRECTORY = -OUTPUT_LANGUAGE = English -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_STATIC = YES -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ALWAYS_DETAILED_SEC = YES -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = $(PWD)/ -INTERNAL_DOCS = YES -CLASS_DIAGRAMS = YES -SOURCE_BROWSER = YES -INLINE_SOURCES = YES -STRIP_CODE_COMMENTS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -VERBATIM_HEADERS = YES -SHOW_INCLUDE_FILES = YES -JAVADOC_AUTOBRIEF = YES -INHERIT_DOCS = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -DISTRIBUTE_GROUP_DOC = NO -TAB_SIZE = 2 -ENABLED_SECTIONS = -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -ALIASES = -MAX_INITIALIZER_LINES = 30 -OPTIMIZE_OUTPUT_FOR_C = NO -SHOW_USED_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = YES -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = doxygen.log -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = -FILE_PATTERNS = *.h \ - *.cpp \ - *.c -RECURSIVE = YES -EXCLUDE = -EXCLUDE_PATTERNS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = -IMAGE_PATH = -INPUT_FILTER = -FILTER_SOURCE_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 4 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = -HTML_HEADER = Doxygen_files/doxygen_gtkradiant_head.html -HTML_FOOTER = Doxygen_files/doxygen_gtkradiant_foot.html -HTML_STYLESHEET = Doxygen_files/doxygen_gtkradiant.css -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = NO -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = -MAN_EXTENSION = .3 -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = YES -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = -#--------------------------------------------------------------------------- -# Configuration::addtions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -HAVE_DOT = YES -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -GRAPHICAL_HIERARCHY = YES -DOT_PATH = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::addtions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO -CGI_NAME = search.cgi -CGI_URL = -DOC_URL = -DOC_ABSPATH = -BIN_ABSPATH = /usr/local/bin/ -EXT_DOC_PATHS = - -#--------------------------------------------------------------------------- -# Include file, at the bottom to over-ride anything I missed. -#--------------------------------------------------------------------------- -@INCLUDE = genConf \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxy_mainpage.h b/misc/mediasource/extra/netradiant-src/Doxygen_files/doxy_mainpage.h deleted file mode 100644 index 80fce39b..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxy_mainpage.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -** Doxygen index.html generation file -** -*/ - -/*! \mainpage +project+ Doxygen Index - - \section intro Introduction - - This documentation was generated from NetRadiant source code using Doxygen.
- Generated from source in: +target+ - - \section links Links - General Links
- Doxygen Homepage
- GtkRadiant Homepage
- Zerowing - GtkRadiant Development
- - Local Links
- Doxygen Quick Reference (Local)
- -

- GtkRadiant FAQ Links
- GtkRadiant FAQ
- GtkRadiant FAQ: Open Tasks
- GtkRadiant FAQ: Compiling instructions
- GtkRadiant FAQ: Creating/Submitting patches
- GtkRadiant FAQ: Coding Conventions & Guidelines
-

- - Misc Links
- idsoftware.com
- -

- - * Note: The content on this page was generated from this file. - It is moved into the path when the doxygen documentation is generated, and removed immediately - afterwards. - -

- - This page generated: by +user+ on +machine+
- On +date+ -
-*/ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant.css b/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant.css deleted file mode 100644 index ad85caff..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant.css +++ /dev/null @@ -1,34 +0,0 @@ -body { background-color: black; } -IMG { border-color: #222222; border: 0; } -em { font-size: 11px; font-style: italic; font-weight: normal; color: #888888; } -H1 { text-align: center; font-size: 15px; color: #2222AA; font-family: Geneva, Verdana, Helvetica, Arial, sans-serif; } -H3 { text-align: center; font-size: 18px; color: #2222AA; font-family: Geneva, Verdana, Helvetica, Arial, sans-serif; } -A { text-decoration: none; color: #6666DD; } -A:HOVER { text-decoration: underline; color: #4444FF; } -A:VISITED { text-decoration: none; color: #8888AA; } -A.qindex { text-decoration: none; color: #6666DD; font-size: 11px; } -A.qindex:HOVER { text-decoration: underline; color: #4444FF; font-size: 11px; } -A.qindex:VISITED { text-decoration: none; color: #8888AA; font-size: 11px; } -A.qindexRef { font-size: 11px; } -A.el { text-decoration: none; font-weight: bold; } -A.elRef { font-weight: bold; } -A.code { text-decoration: none; font-weight: normal; color: #6666DD; } -A.code:HOVER { text-decoration: underline; font-weight: normal; color: #4444FF; } -A.code:VISITED { text-decoration: none; font-weight: normal; color: #8888AA; } -A.codeRef { text-decoration: none; font-weight: normal; color: #6666DD; } -A.codeRef:HOVER { text-decoration: underline; font-weight: normal; color: #4444FF; } -A.codeRef:VISITED { text-decoration: none; font-weight: normal; color: #8888AA; } -DL.el { margin-left: 2cm; width: 99%; } -DIV.fragment { background-color: #FFFFFF; width: 99%; } -DIV.ah { background-color: #AAAAAA; width: 99%; margin-bottom: 3; margin-top: 3; } -TD.md { cellpadding: 0; background-color: #DDDDDD; border: 0; width: 99%; color: #222222; } -DIV.groupHeader { margin-left: 16; margin-top: 12; margin-bottom: 6; font-weight: bold; color: #222222; } -DIV.groupText { margin-left: 16; font-style: italic; font-size: smaller; } -FONT.keyword { color: #0080A0; } -FONT.keywordtype { color: #604020; } -FONT.keywordflow { color: #E08000; } -FONT.comment { color: #800000; } -FONT.comment { color: #009900; text-decoration: italic; } -FONT.preprocessor { color: #806020; } -FONT.stringliteral{ color: #002080; } -FONT.charliteral { color: #008080; } diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant_foot.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant_foot.html deleted file mode 100644 index affcb3c3..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant_foot.html +++ /dev/null @@ -1,49 +0,0 @@ - - - - - -

-
- - - - - -
- Documentation generated by : Doxygen $doxygenversion - - - ttimo@idsoftware.com - -
-
- -
-
- -   - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant_head.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant_head.html deleted file mode 100644 index cda29303..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_gtkradiant_head.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - $projectname $projectnumber Doxygen Documentation - - - - - -
-
- - - - - - -
- -
idsoftware
-
- - - - - - - - - - - - -
- - -
 
-

-
- - - - - - - - -
- \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_index.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_index.html deleted file mode 100644 index a9005b7f..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_index.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - Redirecting to Doxygen index - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_reference_foot.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_reference_foot.html deleted file mode 100644 index 1bc7d704..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_reference_foot.html +++ /dev/null @@ -1,46 +0,0 @@ - -

-
- - - - - -
- - Doxygen is: Copyright © 1997-2001 by Dimitri van Heesch. - - - GtkRadiant Doxygen Maintainer: Gef -
-
- -
-
-
 
- - - - - -
- -
-
-
- -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_reference_head.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_reference_head.html deleted file mode 100644 index 4f12e035..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/doxygen_reference_head.html +++ /dev/null @@ -1,38 +0,0 @@ - - - - GtkRadiant - Doxygen Quick Reference - - - - - -
- -
- - - - - - -
- - -
idsoftware
-
- - - - - - - - - - - - -
- - -
&nsbp;
-

- \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/annotated.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/annotated.html deleted file mode 100644 index c827a83c..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/annotated.html +++ /dev/null @@ -1,103 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEPairsClassDocumentationExample Compound List

Here are the classes, structs, unions and interfaces with brief descriptions:
    -
  • IEpair (Virtual class to allow plugin operations on entity pairs) -
- - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- -
-
- -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classIEpair-members.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classIEpair-members.html deleted file mode 100644 index b58775ce..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classIEpair-members.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEpair Member List

This is the complete list of members for IEpair, including all inherited members. - - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classIEpair.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classIEpair.html deleted file mode 100644 index a64a9e94..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classIEpair.html +++ /dev/null @@ -1,414 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEpair Class Reference

Virtual class to allow plugin operations on entity pairs. -More... -

-List of all members. - - - - - - - - - - - - - - - - - -

Public Methods

virtual void IncRef ()=0
 Increment the number of references to this object. More...

virtual void DecRef ()=0
 Decrement the reference count. More...

virtual void GetVectorForKey (char *key, vec3_t vec)=0
 Get a vector from a key. More...

virtual float FloatForKey (char *key)=0
 Get a float from a key. More...

virtual char* ValueForKey (char *key)=0
 Get a string (char *) from a key. More...

virtual void SetKeyValue (char *key, char *value)=0
 Set a key value to char *value. More...

virtual void GetEntityOrigin (vec3_t vec)=0
 Get a vec3_t for the entities origin. More...

virtual void CalculateRotatedBounds (vec3_t mins, vec3_t maxs)=0
 Compute the rotated bounds of the BBox based on "angle" and "angles" keys. More...

-


Detailed Description

-Virtual class to allow plugin operations on entity pairs. -

- -

-

-Todo:
-Write more complete documentation for this class so that it's use is clear
-

-An interface to entity keys and key pairs that allows plugins to; read and write entity keys and key values, get a key value as a vec3_t -

- -

-Definition at line 10 of file iepairs.h.


Member Function Documentation

-

- - - - -
- - - - - - - - - - -
-void IEpair::CalculateRotatedBounds ( - -vec3_t mins, -
-vec3_t maxs ) [pure virtual] -
-
- - - - - -
-   - - -

-Compute the rotated bounds of the BBox based on "angle" and "angles" keys. -

-

-

- - - - -
- - - - - - -
-void IEpair::DecRef ( - -) [pure virtual] -
-
- - - - - -
-   - - -

-Decrement the reference count. -

-

-

- - - - -
- - - - - - -
-float IEpair::FloatForKey ( - -char * key ) [pure virtual] -
-
- - - - - -
-   - - -

-Get a float from a key. -

-

-

- - - - -
- - - - - - -
-void IEpair::GetEntityOrigin ( - -vec3_t vec ) [pure virtual] -
-
- - - - - -
-   - - -

-Get a vec3_t for the entities origin. -

-

-

- - - - -
- - - - - - - - - - -
-void IEpair::GetVectorForKey ( - -char * key, -
-vec3_t vec ) [pure virtual] -
-
- - - - - -
-   - - -

-Get a vector from a key. -

-

-

- - - - -
- - - - - - -
-void IEpair::IncRef ( - -) [pure virtual] -
-
- - - - - -
-   - - -

-Increment the number of references to this object. -

-

-

- - - - -
- - - - - - - - - - -
-void IEpair::SetKeyValue ( - -char * key, -
-char * value ) [pure virtual] -
-
- - - - - -
-   - - -

-Set a key value to char *value. -

-

-Parameters:
- - - -
key -The (char *) containing the keyname
value -The (char *) to set the key value to
-
-

- - - - -
- - - - - - -
-char * IEpair::ValueForKey ( - -char * key ) [pure virtual] -
-
- - - - - -
-   - - -

-Get a string (char *) from a key. -

-

-


The documentation for this class was generated from the following file: - - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classes.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classes.html deleted file mode 100644 index b79308f9..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/classes.html +++ /dev/null @@ -1,103 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEPairsClassDocumentationExample Compound Index

- -
  I  
IEpair   
- - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/doxygen.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/doxygen.gif deleted file mode 100644 index 192c83ce..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/doxygen.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/doxygen_gtkradiant.css b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/doxygen_gtkradiant.css deleted file mode 100644 index 30bf2075..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/doxygen_gtkradiant.css +++ /dev/null @@ -1,35 +0,0 @@ -body { background-color: black; } -IMG { border-color: #222222; border: 1; } -em { font-size: 11px; font-style: italic; font-weight: normal; color: #888888; } -H1 { text-align: center; font-size: 15px; color: #2222AA; font-family: Geneva, Verdana, Helvetica, Arial, sans-serif; } -H3 { text-align: center; font-size: 18px; color: #2222AA; font-family: Geneva, Verdana, Helvetica, Arial, sans-serif; } -A { text-decoration: none; color: #6666DD; } -A:HOVER { text-decoration: underline; color: #4444FF; } -A:VISITED { text-decoration: none; color: #8888AA; } -A.qindex { text-decoration: none; color: #6666DD; font-size: 11px; } -A.qindex:HOVER { text-decoration: underline; color: #4444FF; font-size: 11px; } -A.qindex:VISITED { text-decoration: none; color: #8888AA; font-size: 11px; } -A.qindexRef { font-size: 11px; } -A.el { text-decoration: none; font-weight: bold; } -A.elRef { font-weight: bold; } -A.code { text-decoration: none; font-weight: normal; color: #6666DD; } -A.code:HOVER { text-decoration: underline; font-weight: normal; color: #4444FF; } -A.code:VISITED { text-decoration: none; font-weight: normal; color: #8888AA; } -A.codeRef { text-decoration: none; font-weight: normal; color: #6666DD; } -A.codeRef:HOVER { text-decoration: underline; font-weight: normal; color: #4444FF; } -A.codeRef:VISITED { text-decoration: none; font-weight: normal; color: #8888AA; } -DL.el { margin-left: 2cm; width: 99%; } -DIV.fragment { background-color: #FFFFFF; width: 99%; } -DIV.ah { background-color: #AAAAAA; width: 99%; margin-bottom: 3; margin-top: 3; } -TD.md { cellpadding: 2; background-color: #DDDDDD; border: 1; width: 99%; color: #222222; } -DIV.groupHeader { margin-left: 16; margin-top: 12; margin-bottom: 6; font-weight: bold; color: #222222; } -DIV.groupText { margin-left: 16; font-style: italic; font-size: smaller; } -FONT.keyword { color: #0080A0; } -FONT.keywordtype { color: #604020; } -FONT.keywordflow { color: #E08000; } -FONT.comment { color: #800000; } -FONT.comment { color: #009900; text-decoration: italic; } -FONT.preprocessor { color: #806020; } -FONT.stringliteral{ color: #002080; } -FONT.charliteral { color: #008080; } - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/files.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/files.html deleted file mode 100644 index 9911650f..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/files.html +++ /dev/null @@ -1,102 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEPairsClassDocumentationExample File List

Here is a list of all files with brief descriptions: - - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/functions.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/functions.html deleted file mode 100644 index 12914931..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/functions.html +++ /dev/null @@ -1,110 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEPairsClassDocumentationExample Compound Members

Here is a list of all class members with links to the class documentation for each member: - - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.dot b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.dot deleted file mode 100644 index 3d8a101e..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.dot +++ /dev/null @@ -1,16 +0,0 @@ -digraph inheritance -{ - Node7 [shape="box",label="Inherited",fontsize=10,height=0.2,width=0.4,fontname="doxfont",color="black",style="filled" fontcolor="white"]; - Node8 -> Node7 [dir=back,color="midnightblue",fontsize=10,style="solid",fontname="doxfont"]; - Node8 [shape="box",label="PublicBase",fontsize=10,height=0.2,width=0.4,fontname="doxfont",color="black",URL="$class_publicbase.html"]; - Node9 -> Node8 [dir=back,color="midnightblue",fontsize=10,style="solid",fontname="doxfont"]; - Node9 [shape="box",label="Truncated",fontsize=10,height=0.2,width=0.4,fontname="doxfont",color="red",URL="$class_truncated.html"]; - Node11 -> Node7 [dir=back,color="darkgreen",fontsize=10,style="solid",fontname="doxfont"]; - Node11 [shape="box",label="ProtectedBase",fontsize=10,height=0.2,width=0.4,fontname="doxfont",color="black",URL="$class_protectedbase.html"]; - Node12 -> Node7 [dir=back,color="firebrick4",fontsize=10,style="solid",fontname="doxfont"]; - Node12 [shape="box",label="PrivateBase",fontsize=10,height=0.2,width=0.4,fontname="doxfont",color="black",URL="$class_privatebase.html"]; - Node13 -> Node7 [dir=back,color="midnightblue",fontsize=10,style="solid",fontname="doxfont"]; - Node13 [shape="box",label="Undocumented",fontsize=10,height=0.2,width=0.4,fontname="doxfont",color="grey75"]; - Node14 -> Node7 [dir=back,color="darkorchid3",fontsize=10,style="dashed",label="m_usedClass",fontname="doxfont"]; - Node14 [shape="box",label="Used",fontsize=10,height=0.2,width=0.4,fontname="doxfont",color="black",URL="$class_used.html"]; -} diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.gif deleted file mode 100644 index f4f1a005..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.html deleted file mode 100644 index 2283f3eb..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/graph_legend.html +++ /dev/null @@ -1,141 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

Graph Legend

This page explains how to interpret the graphs that are generated by doxygen. -

- Consider the following example:

/*! Invisible class because of truncation */
-class Invisible { };
-
-/*! Truncated class, inheritance relation is hidden */
-class Truncated : public Invisible { };
-
-/* Class not documented with doxygen comments */
-class Undocumented { };
-
-/*! Class that is inherited using public inheritance */
-class PublicBase : public Truncated { };
-
-/*! Class that is inherited using protected inheritance */
-class ProtectedBase { };
-
-/*! Class that is inherited using private inheritance */
-class PrivateBase { };
-
-/*! Class that is used by the Inherited class */
-class Used { };
-
-/*! Super class that inherits a number of other classes */
-class Inherited : public PublicBase,
-                  protected ProtectedBase,
-                  private PrivateBase,
-                  public Undocumented
-{
-  private:
-    Used *m_usedClass;
-};
If the MAX_DOT_GRAPH_HEIGHT tag in the configuration file is set to 200 this will result in the following graph: -

-

-
- -

- The boxes in the above graph have the following meaning:

    -
  • A filled black box represents the struct or class for which the graph is generated.
  • A box with a black border denotes a documented struct or class.
  • A box with a grey border denotes an undocumented struct or class.
  • A box with a red border denotes a documented struct or class for which not all inheritance/containment relations are shown. A graph is truncated if it does not fit within the specified boundaries.
- The arrows have the following meaning:
    -
  • A dark blue arrow is used to visualize a public inheritance relation between two classes.
  • A dark green arrow is used for protected inheritance.
  • A dark red arrow is used for private inheritance.
  • A purple dashed arrow is used if a class is contained or used by another class. The arrow is labeled with the variable(s) through which the pointed class or struct is accessible.
- - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/index.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/index.html deleted file mode 100644 index b8466f27..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/index.html +++ /dev/null @@ -1,102 +0,0 @@ - - - - IEPairs Class Example Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEPairs Class Example Documentation

-

- - -

-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/pages.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/pages.html deleted file mode 100644 index 0f446d98..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/pages.html +++ /dev/null @@ -1,104 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

IEPairsClassDocumentationExample Related Pages

Here is a list of all related documentation pages: - - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/test_8c-source.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/test_8c-source.html deleted file mode 100644 index c36f5a32..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/test_8c-source.html +++ /dev/null @@ -1,140 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

iepairs.h

Go to the documentation of this file.
00001 //! Virtual class to allow plugin operations on entity pairs
-00002 /*!
-00003   \todo Write more complete documentation for this class so that it's use
-00004   is clear
-00005                         
-00006   An interface to entity keys and key pairs that allows plugins to;
-00007   read and write entity keys and key values, get a key value as a
-00008   vec3_t
-00009 */
-00010 class IEpair
-00011 {
-00012   public:
-00013     //! Increment the number of references to this object
-00014     virtual void IncRef () = 0;
-00015                                 
-00016     //! Decrement the reference count
-00017     virtual void DecRef () = 0;
-00018                                 
-00019     //! Get a vector from a key
-00020     virtual void GetVectorForKey( char* key, vec3_t vec ) = 0;
-00021                                 
-00022     //! Get a float from a key
-00023     virtual float FloatForKey( char *key ) = 0;
-00024                                 
-00025     //! Get a string (char *) from a key
-00026     virtual char* ValueForKey( char *key ) = 0;
-00027                                 
-00028     //! Set a key value to char *value
-00029     /*!
-00030       \param key The (char *) containing the keyname
-00031       \param value The (char *) to set the key value to
-00032     */
-00033     virtual void SetKeyValue( char *key, char *value ) = 0;
-00034                                 
-00035     //! Get a vec3_t for the entities origin
-00036     virtual void GetEntityOrigin( vec3_t vec ) = 0;
-00037                                 
-00038     //! Compute the rotated bounds of the BBox based on "angle" and "angles" keys
-00039     virtual void CalculateRotatedBounds( vec3_t mins, vec3_t maxs ) = 0;
-00040 };
-
- -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/test_8c.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/test_8c.html deleted file mode 100644 index 206bda67..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/test_8c.html +++ /dev/null @@ -1,107 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

iepairs.h File Reference

-

-Go to the source code of this file. - - - -

Compounds

class  IEpair
 Virtual class to allow plugin operations on entity pairs. More...

- - -

-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/todo.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/example/todo.html deleted file mode 100644 index 769aac56..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/example/todo.html +++ /dev/null @@ -1,105 +0,0 @@ - - - - IEPairsClassDocumentationExample Doxygen Documentation - - - - - -
- - - - - - - -
- - -
idsoftware -
- -
- - - - - - - - - - - - - - - - - -
- - - - - -
 
-

- -
-
- - - - - -
-Main Page   Alphabetical List   Compound List   File List   Compound Members   Related Pages  
-

Todo List

- -
-
Class IEpair
Write more complete documentation for this class so that it's use is clear -
- - -
-
- -

-
- - - - - -
- Documentation generated by : Doxygen 1.2.8.1 on 11 Aug 2001 - - - ttimo@idsoftware.com - -
-
- -
-
-
 
- - - - - -
- - - - - - - -
- - - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/genDoxyfile b/misc/mediasource/extra/netradiant-src/Doxygen_files/genDoxyfile deleted file mode 100644 index 330bb570..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/genDoxyfile +++ /dev/null @@ -1,159 +0,0 @@ -# Doxyfile 1.2.5-20010304 -#--------------------------------------------------------------------------- -# General configuration options -#--------------------------------------------------------------------------- -PROJECT_NAME = -PROJECT_NUMBER = -OUTPUT_DIRECTORY = -OUTPUT_LANGUAGE = English -EXTRACT_ALL = YES -EXTRACT_PRIVATE = YES -EXTRACT_STATIC = YES -HIDE_UNDOC_MEMBERS = NO -HIDE_UNDOC_CLASSES = NO -BRIEF_MEMBER_DESC = YES -REPEAT_BRIEF = YES -ALWAYS_DETAILED_SEC = YES -FULL_PATH_NAMES = YES -STRIP_FROM_PATH = $(PWD)/ -INTERNAL_DOCS = YES -CLASS_DIAGRAMS = YES -SOURCE_BROWSER = YES -INLINE_SOURCES = YES -STRIP_CODE_COMMENTS = NO -CASE_SENSE_NAMES = YES -HIDE_SCOPE_NAMES = NO -VERBATIM_HEADERS = YES -SHOW_INCLUDE_FILES = YES -JAVADOC_AUTOBRIEF = YES -INHERIT_DOCS = YES -INLINE_INFO = YES -SORT_MEMBER_DOCS = YES -DISTRIBUTE_GROUP_DOC = NO -TAB_SIZE = 2 -ENABLED_SECTIONS = -GENERATE_TODOLIST = YES -GENERATE_TESTLIST = YES -GENERATE_BUGLIST = YES -ALIASES = -MAX_INITIALIZER_LINES = 30 -OPTIMIZE_OUTPUT_FOR_C = NO -SHOW_USED_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to warning and progress messages -#--------------------------------------------------------------------------- -QUIET = YES -WARNINGS = YES -WARN_IF_UNDOCUMENTED = YES -WARN_FORMAT = "$file:$line: $text" -WARN_LOGFILE = doxygen.log -#--------------------------------------------------------------------------- -# configuration options related to the input files -#--------------------------------------------------------------------------- -INPUT = -FILE_PATTERNS = *.h \ - *.cpp \ - *.c -RECURSIVE = YES -EXCLUDE = -EXCLUDE_PATTERNS = -EXAMPLE_PATH = -EXAMPLE_PATTERNS = -IMAGE_PATH = -INPUT_FILTER = -FILTER_SOURCE_FILES = YES -#--------------------------------------------------------------------------- -# configuration options related to the alphabetical class index -#--------------------------------------------------------------------------- -ALPHABETICAL_INDEX = YES -COLS_IN_ALPHA_INDEX = 4 -IGNORE_PREFIX = -#--------------------------------------------------------------------------- -# configuration options related to the HTML output -#--------------------------------------------------------------------------- -GENERATE_HTML = YES -HTML_OUTPUT = -HTML_HEADER = Doxygen_files/doxygen_gtkradiant_head.html -HTML_FOOTER = Doxygen_files/doxygen_gtkradiant_foot.html -HTML_STYLESHEET = Doxygen_files/doxygen_gtkradiant.css -HTML_ALIGN_MEMBERS = YES -GENERATE_HTMLHELP = NO -GENERATE_CHI = NO -BINARY_TOC = NO -TOC_EXPAND = NO -DISABLE_INDEX = NO -ENUM_VALUES_PER_LINE = 4 -GENERATE_TREEVIEW = NO -TREEVIEW_WIDTH = 250 -#--------------------------------------------------------------------------- -# configuration options related to the LaTeX output -#--------------------------------------------------------------------------- -GENERATE_LATEX = NO -LATEX_OUTPUT = -COMPACT_LATEX = NO -PAPER_TYPE = a4wide -EXTRA_PACKAGES = -LATEX_HEADER = -PDF_HYPERLINKS = NO -USE_PDFLATEX = NO -LATEX_BATCHMODE = NO -#--------------------------------------------------------------------------- -# configuration options related to the RTF output -#--------------------------------------------------------------------------- -GENERATE_RTF = NO -RTF_OUTPUT = -COMPACT_RTF = NO -RTF_HYPERLINKS = NO -RTF_STYLESHEET_FILE = -#--------------------------------------------------------------------------- -# configuration options related to the man page output -#--------------------------------------------------------------------------- -GENERATE_MAN = NO -MAN_OUTPUT = -MAN_EXTENSION = .3 -#--------------------------------------------------------------------------- -# Configuration options related to the preprocessor -#--------------------------------------------------------------------------- -ENABLE_PREPROCESSING = YES -MACRO_EXPANSION = YES -EXPAND_ONLY_PREDEF = NO -SEARCH_INCLUDES = YES -INCLUDE_PATH = -INCLUDE_FILE_PATTERNS = -PREDEFINED = -EXPAND_AS_DEFINED = -#--------------------------------------------------------------------------- -# Configuration::addtions related to external references -#--------------------------------------------------------------------------- -TAGFILES = -GENERATE_TAGFILE = -ALLEXTERNALS = NO -#--------------------------------------------------------------------------- -# Configuration options related to the dot tool -#--------------------------------------------------------------------------- -HAVE_DOT = YES -CLASS_GRAPH = YES -COLLABORATION_GRAPH = YES -INCLUDE_GRAPH = YES -INCLUDED_BY_GRAPH = YES -GRAPHICAL_HIERARCHY = YES -DOT_PATH = -MAX_DOT_GRAPH_WIDTH = 1024 -MAX_DOT_GRAPH_HEIGHT = 1024 -GENERATE_LEGEND = YES -DOT_CLEANUP = YES -#--------------------------------------------------------------------------- -# Configuration::addtions related to the search engine -#--------------------------------------------------------------------------- -SEARCHENGINE = NO -CGI_NAME = search.cgi -CGI_URL = -DOC_URL = -DOC_ABSPATH = -BIN_ABSPATH = /usr/local/bin/ -EXT_DOC_PATHS = - -#--------------------------------------------------------------------------- -# Include file, at the bottom to over-ride anything I missed. -#--------------------------------------------------------------------------- -@INCLUDE = ./Doxygen_files/genConf diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/gendoxfunctions b/misc/mediasource/extra/netradiant-src/Doxygen_files/gendoxfunctions deleted file mode 100644 index b8837be1..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/gendoxfunctions +++ /dev/null @@ -1,421 +0,0 @@ -#!/bin/bash -# Functions for the gendox script -# -# Gef, Aug 2001 - -#------------------------------------------------------------------------ -# Set the doxygen output language from the system locale -#------------------------------------------------------------------------ -get_language() { - if [ -n "$LANG" ] ; then - local LANG=`locale | grep LANG | cut -d= -f2`; - fi - case "$LANG" in - czech) - OUPUTLANGUAGE="Czech"; - ;; - german) - OUPUTLANGUAGE="German"; - ;; - spanish) - OUPUTLANGUAGE="Spanish"; - ;; - finnish) - OUPUTLANGUAGE="Finnish"; - ;; - french) - OUPUTLANGUAGE="French"; - ;; - italian) - OUPUTLANGUAGE="Italian"; - ;; - japanese*) - OUPUTLANGUAGE="Japanese"; - ;; - dutch) - OUPUTLANGUAGE="Dutch"; - ;; - swedish) - OUPUTLANGUAGE="Swedish"; - ;; - *) - OUPUTLANGUAGE="English"; - ;; - esac -} - -#------------------------------------------------------------------------ -# Output usage info & output help -#------------------------------------------------------------------------ -output_usage() { - echo -e "Usage: $0 [] [-o ]"; - return; -} - -output_help() { - output_usage; - echo -e "\nOptions:"; - echo -e " []"; - echo -e " This is an optional parameter that specifies the directory, or multiple"; - echo -e " directories from which to generate the documentation."; - echo -e ""; - echo -e " [-o ]"; - echo -e " An optional parameter that specifies the output directory in which"; - echo -e " to save the generated documentation."; - echo -e ""; - echo -e " -q or --quiet"; - echo -e " Prevents the output of status information" - echo -e "" - echo -e " --help, or -h"; - echo -e " Displays this information"; - echo -e "" - echo -e " -q or --quiet"; - echo -e " Prevents the output of status information" - echo -e "" - echo -e " -k or --kill"; - echo -e " kills running doxygen pids." - echo -e "" - echo -e "* Further information on using this script, can be found in README.doxygen"; - echo -e "* in the current directory."; - -} - -#------------------------------------------------------------------------ -# Set the target to what was passed on the command line -#------------------------------------------------------------------------ -parse_commandline() { - # todo: - # need to add the ability to check for an auto gen'd version - # used for automatically generating new documentation for each commit - # to the cvs server - - # funky bash shell array - declare -a OPTLIST[$#]; - - if [ $OPTCOUNT == 0 ] ; then - # No options on the command line so set the target list to the core - TARGETCOUNT=0; - OUTPUTDIR="../$(basename `pwd`)-doxygen"; - else - # put all the command line options into an array - for f in $COMLINE ; do - OPTLIST[$COUNTER]="$f"; - let COUNTER++; - done - - for (( COUNTER=0 ; $COUNTER < $OPTCOUNT; $[COUNTER++] )) ; do - if [ "${OPTLIST[$COUNTER]}" == "--help" ] ; then - # output usage information - output_help; - RETVAL=1; - return; - elif [ "${OPTLIST[$COUNTER]}" == "-h" ] ; then - # output usage information - output_help; - RETVAL=1; - return; - fi - - case ${OPTLIST[$COUNTER]} in - -q) - QUIETMODE=1; - ;; - --quiet) - QUIETMODE=1; - ;; - -k) - KILLON=1; - ;; - --kill) - KILLON=1; - ;; - -o) - # look for the -o switch, and get the next command line option as the output dir - if [ -z ${OPTLIST[$COUNTER + 1]} ] ; then - [ $QUIETMODE -gt 0 ] || echo -e " ** Output switch used, but no output dir passed..."; - [ $QUIETMODE -gt 0 ] || echo -e " ** Setting default output dir."; - else - let COUNTER++; - OUTPUTDIR=${OPTLIST[$COUNTER]}; - fi - break; - ;; - **) - # If the command line option is anything other that -o then assume it's a target - # Check to make sure the target exists first... - if [ -d ${OPTLIST[$COUNTER]} ] ; then - TARGETLIST[$COUNTER]=${OPTLIST[$COUNTER]}; - else - output_usage; - echo -e " ** Error: Non-existent directory specified as a target.\nExiting."; - RETVAL=1; - return; - fi - let TARGETCOUNT++; - ;; - esac - done - - fi # if [ $OPTCOUNT == 0 ] ; - - if [ $TARGETCOUNT == 0 ] ; then - TARGETCOUNT=4; - TARGETLIST[0]="include"; - TARGETLIST[1]="libs"; - TARGETLIST[2]="radiant"; - TARGETLIST[3]="plugins"; - # Gef: outputdir for default core when no targets are passed on the command line - # TTimo problem still there, if -o used on command line, don't override - if [ -z $OUTPUTDIR ] ; then - OUTPUTDIR="../$(basename `pwd`)-doxygen"; - fi - fi - - # Add trailing slash's to the lines that need them - TARGETSTRING=`echo ${TARGETLIST[*]} | sed -e 's/" "/", "/'` - [ $QUIETMODE -gt 0 ] || echo -ne " -> Set Input to: "; - for (( COUNTER=0; COUNTER < $TARGETCOUNT ; $[COUNTER++] )) ; do - if [ $COUNTER == $[TARGETCOUNT - 1] ] ; then - [ $QUIETMODE -gt 0 ] || echo -ne "${TARGETLIST[$COUNTER]}\n"; - TARGETLIST[$COUNTER]="${TARGETLIST[$COUNTER]}"; - else - [ $QUIETMODE -gt 0 ] || echo -ne "${TARGETLIST[$COUNTER]}, "; - TARGETLIST[$COUNTER]="${TARGETLIST[$COUNTER]} \\"; - fi - done - [ $QUIETMODE -gt 0 ] || echo -e " -> Set Output Dir to: $OUTPUTDIR"; - return; -} - -#------------------------------------------------------------------------ -# Try to extract the version number -# todo: find a better way to determine the version -#------------------------------------------------------------------------ -get_version() { - VERSION=`grep PROJECT_NUMBER $DOXYCONFIG | grep -v \# | cut -d= -f2`; - if [ -z $VERSION ] ; then - if [ -f "./include/version.default" ] ; then # checks that we are in the right dir - VERSION=`cat ./include/version.default`; - else - VERSION="(Unknown)"; - fi - fi - return; -} - -#------------------------------------------------------------------------ -# Create a projectname from the tree name -#------------------------------------------------------------------------ -get_projectname() { - PROJECTNAME=`grep PROJECT_NAME $DOXYCONFIG | grep -v \# | cut -d= -f2`; - if [ -z $PROJECTNAME ] ; then - # PROJECTNAME=`echo $TARGET | sed -e s/[^A-Za-z0-9]/!/ | cut -d! -f1`; - PROJECTNAME="$(basename `pwd`)"; - fi - return; -} - -#------------------------------------------------------------------------ -# function to determine the path to the perl executable -#------------------------------------------------------------------------ -get_perlpath() { - if [ -f "$DOXYCONFIG" ] ; then - PERLPATH=`grep PERL_PATH $DOXYCONFIG | grep = | cut -d= -f2` - fi - - if [ 'basename $PERLPATH &2>/dev/null' != "perl" ] ; then - PERLPATH=`which perl 2>/dev/null | sed -e 's/perl//'`; - elif [ 'basename $PERLPATH &2>/dev/null' != "perl" ] ; then - PERLPATH=""; - fi - return; -} - -#------------------------------------------------------------------------ -# Function to determine the path to the dot executable -#------------------------------------------------------------------------ -get_dotpath() { - if [ -f "$DOXYCONFIG" ] ; then - DOTPATH=`grep DOT_PATH $DOXYCONFIG | grep = | cut -d= -f2` - fi - - if [ -z $DOTPATH ] || [ `basename $DOTPATH 2>/dev/null` != "dot" ] ; then - DOTPATH=`which dot 2>/dev/null`; - fi - - if [ -z $DOTPATH ] || [ `basename $DOTPATH 2>/dev/null` != "dot" ] ; then - DOTPATH=""; - HAVEDOT="No"; - echo -e "** Warning: dot not found."; - [ $QUIETMODE -gt 0 ] || echo -e "** dot is part of the GraphVis package and is used to generate"; - [ $QUIETMODE -gt 0 ] || echo -e "** dependancy/inheritance/include (etc) diagrams."; - [ $QUIETMODE -gt 0 ] || echo -e "** It's suggested that you install the GraphVis package for those"; - [ $QUIETMODE -gt 0 ] || echo -e "** features."; - [ $QUIETMODE -gt 0 ] || echo -e "** GraphVis can be downloaded from www.graphvis.org"; - else - HAVEDOT="Yes"; - DOTPATH=`echo $DOTPATH | sed -e 's/dot//'`; - fi - - return; -} - -#------------------------------------------------------------------------ -# Function to move stuff around -#------------------------------------------------------------------------ -# eg: move the images into the output directory & the reference doc into the -# html directory. -# called after doxygen has finished generating documentation -move_stuff() { - [ $QUIETMODE -gt 0 ] || echo -ne " -> Move stuff.\n"; - if [ ! -d $OUTPUTDIR ] ; then - mkdir $OUTPUTDIR; - fi - - if [ ! -d "$EXTRAS_PATH/images/" ] ; then - [ $QUIETMODE -gt 0 ] || echo -e " - Looking for images."; - [ $QUIETMODE -gt 0 ] || sleep 2; - [ $QUIETMODE -gt 0 ] || echo -e " - I can't find the images..."; - [ $QUIETMODE -gt 0 ] || sleep 1; - [ $QUIETMODE -gt 0 ] || echo -e " - Where did you put the images!?"; - [ $QUIETMODE -gt 0 ] || sleep 2; - [ $QUIETMODE -gt 0 ] || echo -e " - They have to be here somewhere..."; - [ $QUIETMODE -gt 0 ] || sleep 1; - [ $QUIETMODE -gt 0 ] || echo -e " - Looking in /dev/null"; - [ $QUIETMODE -gt 0 ] || sleep 3; - [ $QUIETMODE -gt 0 ] || echo -e " - YOU FOOL, YOU DELETED THE IMAGES!!!"; - [ $QUIETMODE -gt 0 ] || sleep 1; - [ $QUIETMODE -gt 0 ] || echo -e " - I quit!"; - RETVAL=666; - else - if [ ! -d $OUTPUTDIR/images ] ; then - mkdir $OUTPUTDIR/images ; - fi - cp $EXTRAS_PATH/images/* $OUTPUTDIR/images/ ; - RETVAL=0; - fi - return; -} - -#------------------------------------------------------------------------ -# clean_up() removes old versions of the documentation -#------------------------------------------------------------------------ -clean_up() { - if [ -f $OUTPUTDIR/html/index.html ] ; then - [ $QUIETMODE -gt 0 ] || echo -e " -> Trashing old dox."; - rm -f $OUTPUTDIR/html/* - fi - return; -} - -#------------------------------------------------------------------------ -# Create a new genConf & Doxyfile -#------------------------------------------------------------------------ -gen_doxyconfig() { - [ $QUIETMODE -gt 0 ] || echo -e " -> Generating DoxyConfig."; - RETVAL=0; - # first need to make sure there is a Doxyfile here - if [ ! -f $DOXYFILE ] ; then - # what now? (could generate one with 'doxygen -e Doxyfile') but it would be screwed. - echo -e "No Doxyfile here..."; - RETVAL=3; - return; - else - # Create a new doxyfile with the @INCLUDE statement including the generated stuff - echo "`cat $DOXYFILE | grep -v @INCLUDE`" > $NEWDOXYFILE - echo "@INCLUDE = $CONFIG_OUTPUT" >> $NEWDOXYFILE - fi - - # remove the old config file - rm -f $CONFIG_OUTPUT - - # create a new one - touch $CONFIG_OUTPUT - echo "# Generated configuration - Do Not Edit." >> $CONFIG_OUTPUT; - echo "# If you want to modify options, edit DoxyConfig and re-run genconf." >> $CONFIG_OUTPUT; - echo -e "\n" >> $CONFIG_OUTPUT; - echo -e "PROJECT_NAME=$PROJECTNAME" >> $CONFIG_OUTPUT; - echo -e "PROJECT_NUMBER=$VERSION" >> $CONFIG_OUTPUT; - echo -e "PERL_PATH=$PERLPATH" >> $CONFIG_OUTPUT; - echo -e "HAVE_DOT=$HAVEDOT" >> $CONFIG_OUTPUT; - echo -e "DOT_PATH=$DOTPATH" >> $CONFIG_OUTPUT; - echo -e "OUTPUT_LANGUAGE=$OUTPUTLANGUAGE" >> $CONFIG_OUTPUT; - - echo -n "INPUT=" >> $CONFIG_OUTPUT; - for (( COUNTER=0 ; COUNTER < $TARGETCOUNT; $[COUNTER++] )) ; do - # echo -e "${TARGETLIST[$COUNTER]}"; - echo -e "${TARGETLIST[$COUNTER]}" >> $CONFIG_OUTPUT - done - # echo -e "INPUT=$TARGET" >> $CONFIG_OUTPUT; - - echo -e "OUTPUT_DIRECTORY=$OUTPUTDIR" >> $CONFIG_OUTPUT; - echo -e "\n" >> $CONFIG_OUTPUT; - return; -} - -#------------------------------------------------------------------------ -# Build the reference page & index -#------------------------------------------------------------------------ -build_extra_html() { - # file locations - REF_OUT="$OUTPUTDIR/reference/index.html" - INDEX_OUT="$OUTPUTDIR/index.html" - - # Make the output directory if it doesn't exist - if [ ! -d $OUTPUTDIR/reference/ ] ; then - [ $QUIETMODE -gt 0 ] || echo -e " -> Making reference directory"; - mkdir $OUTPUTDIR/reference - fi - - # cat the files together and output the result to each file - [ $QUIETMODE -gt 0 ] || echo -e " -> Building reference document"; - cat $EXTRAS_PATH/doxygen_reference_head.html $EXTRAS_PATH/reference1.html $EXTRAS_PATH/doxygen_reference_foot.html > $REF_OUT; - - if [ ! -d $OUTPUTDIR/example/ ] ; then - [ $QUIETMODE -gt 0 ] || echo -e " -> Making example dir"; - mkdir $OUTPUTDIR/example - fi - [ $QUIETMODE -gt 0 ] || echo -e " -> Moving example docs"; - cp $EXTRAS_PATH/example/* $OUTPUTDIR/example/ - cp $EXTRAS_PATH/doxygen_gtkradiant.css $OUTPUTDIR/example/ - - # Make a redirecting index.html - cat $EXTRAS_PATH/doxygen_index.html > $INDEX_OUT; - return; -} - -#------------------------------------------------------------------------ -# Execute doxygen -#------------------------------------------------------------------------ -run_doxygen() { - # copy doxy_mainpage.h to the target directory - # pipe it through sed to add generation time/date and username - $machine - TEMPLOCATION=`echo $TARGETSTRING | cut -d' ' -f1`; - if [ X"$USERNAME" == "X" ] ; then - USERNAME=`whoami`; - fi - MACHINE=`uname -n`; # `uname -n` or `hostname` ?? - cp $EXTRAS_PATH/doxy_mainpage.h temp.h - cat temp.h | - sed "s/+project+/$PROJECTNAME/" | - sed "s|+target+|$TARGETSTRING|" | - sed "s/+user+/$USERNAME/" | - sed "s/+machine+/$MACHINE/" | - sed "s/+date+/$(date '+%b %d %Y')/" > $TEMPLOCATION/doxy_mainpage.h ; - - rm -f temp.h - - # Start doxygen with the command "doxygen $DOXYFILE" - [ $QUIETMODE -gt 0 ] || echo -e " -> Executing doxygen."; - [ $QUIETMODE -gt 0 ] || echo -e "> doxygen $NEWDOXYFILE"; - doxygen $NEWDOXYFILE - RETVAL=$? - - # remove doxy_mainpage.h from the target directory - rm -f $TEMPLOCATION/doxy_mainpage.h - return; -} - -#------------------------------------------------------------------------ -# End. - diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-left-tile.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-left-tile.gif deleted file mode 100644 index 676dda0a..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-left-tile.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-left.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-left.gif deleted file mode 100644 index e22fcecd..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-left.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-right.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-right.gif deleted file mode 100644 index b9d1f992..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-right.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-tile.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-tile.gif deleted file mode 100644 index f9bfad72..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-lower-tile.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-right-tile.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-right-tile.gif deleted file mode 100644 index 576d7a1a..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-right-tile.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-left.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-left.gif deleted file mode 100644 index e8e433bd..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-left.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-right.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-right.gif deleted file mode 100644 index af29319f..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-right.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-tile.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-tile.gif deleted file mode 100644 index 89e8c660..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/body-upper-tile.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/gtkr_splash.jpg b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/gtkr_splash.jpg deleted file mode 100644 index ebf3a2db..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/gtkr_splash.jpg and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/gtkr_splash_sm.jpg b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/gtkr_splash_sm.jpg deleted file mode 100644 index 2f1f3cc5..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/gtkr_splash_sm.jpg and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/history_id_logo.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/history_id_logo.gif deleted file mode 100644 index 117f9be1..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/history_id_logo.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-right.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-right.gif deleted file mode 100644 index 0cf8a660..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-right.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-tile.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-tile.gif deleted file mode 100644 index 0c6d3b2f..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-tile.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-title.gif b/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-title.gif deleted file mode 100644 index b4460064..00000000 Binary files a/misc/mediasource/extra/netradiant-src/Doxygen_files/images/top-title.gif and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/Doxygen_files/reference1.html b/misc/mediasource/extra/netradiant-src/Doxygen_files/reference1.html deleted file mode 100644 index a6af4625..00000000 --- a/misc/mediasource/extra/netradiant-src/Doxygen_files/reference1.html +++ /dev/null @@ -1,333 +0,0 @@ -
- - -
-NetRadiant Doxygen Documentation - - -

Doxygen Quick Reference

-
-

- -

Index

-
    -
  1. Commenting styles
  2. -
  3. Qt Style C++ Class Example
  4. -
  5. JavaDoc Style C++ Class Example
  6. -
  7. Special Tags
  8. -
  9. Structural Tags
  10. -
-

- -
- -

1. Commenting Styles

-There are two different styles of commenting that doxygen recognises. -

-Qt Style:
- -/*!
- .... text ....
-*/
-
-
-Qt Style Single line
- -//! .... one line of text ....
-
-

- -

-JavaDoc Style:
- -/**
- * .... text ....
- */
-
-
-JavaDoc Style Single line
- -/// .... one line of text ....
-
-

- -

- Doxygen only allows one brief and one detailed description for each declaration/definition. - If there is a brief description before a declaration, and one before the a definition, only - the one before the declaration will be used. If the same situation occurs for a detailed - description the one before the definition is preferred and the one before the declaration will - be ignored.
- A useful method is to have the brief documentation with the declaration in the header file, - and the detailed documentation with the definition in the source file. -

- Note: Standard C/C++ comments are ignored by doxygen, but will be included in the code listing - for that file. -

-

-

top

-
- - -

2. Qt Style C++ Class Example

-

- Here is an example of a C++ class using Qt Style documentation.
- The IEpair class from include/iepairs.h is used here. The html result of using these comments - can be found here.
-

- Note: The resulting html was generated from a single file. If it were generated as part of - the whole documentation, many of the function names and variables would be hyperlinks to - their definitions.
-

-
-//! Virtual class to allow plugin operations on entity pairs
-/*!
-  \todo Write more complete documentation for this class so that it's use
-  is clear
-			
-  An interface to entity keys and key pairs that allows plugins to;
-  read and write entity keys and key values, get a key value as a
-  vec3_t
-*/
-class IEpair
-{
-  public:
-    //! Increment the number of references to this object
-    virtual void IncRef () = 0;
-				
-    //! Decrement the reference count
-    virtual void DecRef () = 0;
-				
-    //! Get a vector from a key
-    virtual void GetVectorForKey( char* key, vec3_t vec ) = 0;
-				
-    //! Get a float from a key
-    virtual float FloatForKey( char *key ) = 0;
-				
-    //! Get a string (char *) from a key
-    virtual char* ValueForKey( char *key ) = 0;
-				
-    //! Set a key value to char *value
-    /*!
-      \param key The (char *) containing the keyname
-      \param value The (char *) to set the key value to
-    */
-    virtual void SetKeyValue( char *key, char *value ) = 0;
-				
-    //! Get a vec3_t for the entities origin
-    virtual void GetEntityOrigin( vec3_t vec ) = 0;
-				
-    //! Compute the rotated bounds of the BBox based on "angle" and "angles" keys
-    virtual void CalculateRotatedBounds( vec3_t mins, vec3_t maxs ) = 0;
-};
-
-

-

-

top

- -

3. JavaDoc Style C++ Class Example

- - The same class documented using JavaDoc Style comments -
-/// Virtual class to allow plugin operations on entity pairs
-/**
-  * @todo Write more complete documentation for this class so that it's use
-  * is clear
-  *	
-  * An interface to entity keys and key pairs that allows plugins to;
-  * read and write entity keys and key values, get a key value as a
-  * vec3_t
-  */
-class IEpair
-{
-  public:
-    /// Increment the number of references to this object
-    virtual void IncRef () = 0;
-				
-    /// Decrement the reference count
-    virtual void DecRef () = 0;
-				
-    /// Get a vector from a key
-    virtual void GetVectorForKey( char* key, vec3_t vec ) = 0;
-				
-    /// Get a float from a key
-    virtual float FloatForKey( char *key ) = 0;
-				
-    /// Get a string (char *) from a key
-    virtual char* ValueForKey( char *key ) = 0;
-				
-    /** Set a key value to char *value
-      * @param key The (char *) containing the keyname
-      * @param value The (char *) to set the key value to
-      */
-    virtual void SetKeyValue( char *key, char *value ) = 0;
-				
-    //! Get a vec3_t for the entities origin
-    virtual void GetEntityOrigin( vec3_t vec ) = 0;
-				
-    //! Compute the rotated bounds of the BBox based on "angle" and "angles" keys
-    virtual void CalculateRotatedBounds( vec3_t mins, vec3_t maxs ) = 0;
-};
-
-

-

top

-
- - -

4. Special Tags

-

- Special tags using the Qt style begin with a " \ ", or using JavaDoc style a " @ " (the two should not be mixed).
-
- Common special tags
-

- - - -
- author - - The author or a list of comma separated authors/contributers -
- see - - A reference to another class, class member, function, etc... -
- param - - A description of a specific function argument or parameter -
- return - - A description of the value returned from a function/method -
- bug - - Starts a paragraph where one or more bugs may be listed. -
- note - - Starts a paragraph where a note may be entered. -
- todo - - Starts a paragraph where a TODO item is described.
- Note: All TODO items are collated into a separate todo list, each linking to each other -
- version - - Starts a paragraph where one or more version strings may be entered. -
- warning - - Starts a paragraph where one or more warning messages may be entered. -
- brief - - A single line comment in place of the //! or /// comment. -
-
-
-

top

-
- -

5. Structural Tags

-

-These are used to document a named object, and are not required to be located near that -object definition or declaration. This allows the documentation for an object to be located -anywhere in the doxygen input files. The exception to this rule however, is that these -documentation blocks cannot be within the body of a function or within C style comment blocks. -All structural commands are preceded by either a " \ " or a " @ ", depending on the -documentation style, and require one or more parameters to specify the name of the object -the description is referring to.
-

-

-An example of the \file structural tag: -

-/*! \file iepairs.h
-    \brief One line documentation for this file
-    \author Author(s)
-    Long description of this file
-*/
-
-

- -Common Structural Tags

-
- - - -
- class - - Documents a class
- eg:
- /*! \class IEpair
- \brief Short description of the IEpair class
-
- Detailed description of the IEpair class
- */
-
-
-
- def - - Describes a #define
- eg:
- /*! \def MAX_VALUE The name of the define
- \brief Description of MAX_VALUE
- */
-
-
-
- file - - Describes a file
- eg:
- /*! \file iepairs.h The name of the file
- \brief Description of the file iepairs.h
-
- Details
- */
-
-
-
- struct - - Documents a struct
- eg:
- /*! \struct BTListList_t the name of the struct
- \brief Description of BTListList_t
-
- Details
- */
-
-
-
- var - - Documents a typedef, variable or enum value
- eg:
- /*! \var typedef unsigned int UINT32
- \brief Short description
- */
-
-
-
- fn - - Documents a function - eg:
- /*! \fn virtual void IEpair::DecRef() = 0;
- \brief Short description of this function
-
- Detailed description of this function
- */
-
- -
-
- -
-

top

-
-
-
diff --git a/misc/mediasource/extra/netradiant-src/GPL b/misc/mediasource/extra/netradiant-src/GPL deleted file mode 100644 index 3912109b..00000000 --- a/misc/mediasource/extra/netradiant-src/GPL +++ /dev/null @@ -1,340 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. diff --git a/misc/mediasource/extra/netradiant-src/LGPL b/misc/mediasource/extra/netradiant-src/LGPL deleted file mode 100644 index 3b204400..00000000 --- a/misc/mediasource/extra/netradiant-src/LGPL +++ /dev/null @@ -1,458 +0,0 @@ - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - - END OF TERMS AND CONDITIONS diff --git a/misc/mediasource/extra/netradiant-src/LICENSE b/misc/mediasource/extra/netradiant-src/LICENSE deleted file mode 100644 index 962a9fb2..00000000 --- a/misc/mediasource/extra/netradiant-src/LICENSE +++ /dev/null @@ -1,36 +0,0 @@ -LICENSE ( last update: Wed Feb 8 17:16:40 CST 2006 ) ------------------------------------------------------ - -There are 3 license types used throughout GtkRadiant source code. - -BSD - modified Berkeley Software Distribution license -( each BSD licensed source file starts with the appropriate header ) -LGPL - GNU Lesser General Public License v2.1 -( see LGPL at the root of the tree ) -GPL - GNU General Public License -( see GPL at the root of the tree ) - -How do I check which license applies to a given part of the source code? - -Each source file in the tree comes with a license header which explains what -license applies. To sum up shortly: - -GPL: ( except some files contributed by Loki Software under BSD license ) -GtkRadiant Core -GtkRadiant Modules -GtkRadiant Libraries -Quake III Tools -Quake II Tools -Background2D Plugin -HydraToolz Plugin - -BSD: -JPEG Library -MD5 Library -DDS Library -PicoModel Library -PrtView Plugin - -LGPL -BobToolz Plugin -GenSurf Plugin diff --git a/misc/mediasource/extra/netradiant-src/Makefile b/misc/mediasource/extra/netradiant-src/Makefile deleted file mode 100644 index b0a1d4a2..00000000 --- a/misc/mediasource/extra/netradiant-src/Makefile +++ /dev/null @@ -1,1081 +0,0 @@ -MAKEFILE_CONF ?= Makefile.conf --include $(MAKEFILE_CONF) - -## CONFIGURATION SETTINGS -# user customizable stuf -# you may override this in Makefile.conf or the environment -BUILD ?= debug -# or: release, or: extradebug, or: profile -OS ?= $(shell uname) -# or: Linux, Win32, Darwin -LDFLAGS ?= -CFLAGS ?= -CXXFLAGS ?= -CPPFLAGS ?= -LIBS ?= -RADIANT_ABOUTMSG ?= Custom build - -# warning: this directory may NOT contain any files other than the ones written by this Makefile! -# NEVER SET THIS TO A SYSTEM WIDE "bin" DIRECTORY! -INSTALLDIR ?= install - -CC ?= gcc -CXX ?= g++ -RANLIB ?= ranlib -AR ?= ar -LDD ?= ldd # nothing on Win32 -OTOOL ?= # only used on OS X -WINDRES ?= windres # only used on Win32 - -PKGCONFIG ?= pkg-config -PKG_CONFIG_PATH ?= - -SH ?= $(SHELL) -ECHO ?= echo -ECHO_NOLF ?= echo -n -CAT ?= cat -MKDIR ?= mkdir -p -CP ?= cp -CP_R ?= $(CP) -r -RM ?= rm -RM_R ?= $(RM) -r -TEE_STDERR ?= | tee /dev/stderr -TR ?= tr -FIND ?= find -DIFF ?= diff -SED ?= sed -GIT ?= git -SVN ?= svn -WGET ?= wget -MV ?= mv -UNZIPPER ?= unzip - -FD_TO_DEVNULL ?= >/dev/null -STDOUT_TO_DEVNULL ?= 1$(FD_TO_DEVNULL) -STDERR_TO_DEVNULL ?= 2$(FD_TO_DEVNULL) -STDERR_TO_STDOUT ?= 2>&1 -TO_DEVNULL ?= $(STDOUT_TO_DEVNULL) $(STDERR_TO_STDOUT) - -CPPFLAGS_GLIB ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) glib-2.0 --cflags $(STDERR_TO_DEVNULL)) -LIBS_GLIB ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) glib-2.0 --libs-only-L $(STDERR_TO_DEVNULL)) \ - $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) glib-2.0 --libs-only-l $(STDERR_TO_DEVNULL)) -CPPFLAGS_XML ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libxml-2.0 --cflags $(STDERR_TO_DEVNULL)) -LIBS_XML ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libxml-2.0 --libs-only-L $(STDERR_TO_DEVNULL)) \ - $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libxml-2.0 --libs-only-l $(STDERR_TO_DEVNULL)) -CPPFLAGS_PNG ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libpng --cflags $(STDERR_TO_DEVNULL)) -LIBS_PNG ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libpng --libs-only-L $(STDERR_TO_DEVNULL)) \ - $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) libpng --libs-only-l $(STDERR_TO_DEVNULL)) -CPPFLAGS_GTK ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtk+-2.0 --cflags $(STDERR_TO_DEVNULL)) -LIBS_GTK ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtk+-2.0 --libs-only-L $(STDERR_TO_DEVNULL)) \ - $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtk+-2.0 --libs-only-l $(STDERR_TO_DEVNULL)) -CPPFLAGS_PANGOFT2 ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) pangoft2 --cflags $(STDERR_TO_DEVNULL)) -LIBS_PANGOFT2 ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) pangoft2 --libs-only-L $(STDERR_TO_DEVNULL)) \ - $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) pangoft2 --libs-only-l $(STDERR_TO_DEVNULL)) -CPPFLAGS_GTKGLEXT ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtkglext-1.0 --cflags $(STDERR_TO_DEVNULL)) -LIBS_GTKGLEXT ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtkglext-1.0 --libs-only-L $(STDERR_TO_DEVNULL)) \ - $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtkglext-1.0 --libs-only-l $(STDERR_TO_DEVNULL)) -CPPFLAGS_GL ?= -LIBS_GL ?= -lGL # -lopengl32 on Win32 -CPPFLAGS_DL ?= -LIBS_DL ?= -ldl # nothing on Win32 -CPPFLAGS_ZLIB ?= -LIBS_ZLIB ?= -lz -DEPEND_ON_MAKEFILE ?= yes -DOWNLOAD_GAMEPACKS ?= yes -# set to no to disable gamepack, set to all to even download undistributable gamepacks - -# Support CHECK_DEPENDENCIES with DOWNLOAD_GAMEPACKS semantics -ifneq ($(CHECK_DEPENDENCIES),) -DEPENDENCIES_CHECK = $(patsubst yes,quiet,$(patsubst no,off,$(CHECK_DEPENDENCIES))) -else -DEPENDENCIES_CHECK ?= quiet -# or: off, verbose -endif - -# these are used on Win32 only -GTKDIR ?= $(shell PKG_CONFIG_PATH=$(PKG_CONFIG_PATH) $(PKGCONFIG) gtk+-2.0 --variable=prefix $(STDERR_TO_DEVNULL)) -WHICHDLL ?= which - -# alias mingw32 OSes -ifeq ($(OS),MINGW32_NT-6.0) - OS = Win32 -endif -ifeq ($(OS),Windows_NT) - OS = Win32 -endif - -CFLAGS_COMMON = -MMD -W -Wall -Wcast-align -Wcast-qual -Wno-unused-parameter -fno-strict-aliasing -CPPFLAGS_COMMON = -LDFLAGS_COMMON = -LIBS_COMMON = -CXXFLAGS_COMMON = -Wno-non-virtual-dtor -Wreorder -fno-exceptions -fno-rtti - -ifeq ($(BUILD),debug) -ifeq ($(findstring $(CFLAGS),-g),) - CFLAGS_COMMON += -g - # only add -g if no -g flag is in $(CFLAGS) -endif -ifeq ($(findstring $(CFLAGS),-O),) - CFLAGS_COMMON += -O - # only add -O if no -O flag is in $(CFLAGS) -endif - CPPFLAGS_COMMON += - LDFLAGS_COMMON += -else - -ifeq ($(BUILD),extradebug) -ifeq ($(findstring $(CFLAGS),-g),) - CFLAGS_COMMON += -g3 - # only add -g3 if no -g flag is in $(CFLAGS) -endif - CPPFLAGS_COMMON += -D_DEBUG - LDFLAGS_COMMON += -else - -ifeq ($(BUILD),profile) -ifeq ($(findstring $(CFLAGS),-g),) - CFLAGS_COMMON += -g - # only add -g if no -g flag is in $(CFLAGS) -endif -ifeq ($(findstring $(CFLAGS),-O),) - CFLAGS_COMMON += -O - # only add -O if no -O flag is in $(CFLAGS) -endif - CFLAGS_COMMON += -pg - CPPFLAGS_COMMON += - LDFLAGS_COMMON += -pg -else - -ifeq ($(BUILD),release) -ifeq ($(findstring $(CFLAGS),-O),) - CFLAGS_COMMON += -O3 - # only add -O3 if no -O flag is in $(CFLAGS) - # to allow overriding the optimizations -endif - CPPFLAGS_COMMON += - LDFLAGS_COMMON += -s -else - -$(error Unsupported build type: $(BUILD)) -endif -endif -endif -endif - -INSTALLDIR_BASE := $(INSTALLDIR) - -ifeq ($(OS),Linux) - CPPFLAGS_COMMON += -DPOSIX -DXWINDOWS - CFLAGS_COMMON += -fPIC - LDFLAGS_DLL = -fPIC -ldl - LIBS_COMMON = -lpthread - EXE ?= x86 - A = a - DLL = so - MWINDOWS = -else - -ifeq ($(OS),Win32) - CPPFLAGS_COMMON += -DWIN32 -D_WIN32 -D_inline=inline - CFLAGS_COMMON += -mms-bitfields - LDFLAGS_DLL = --dll -Wl,--add-stdcall-alias - LIBS_COMMON = -lws2_32 -luser32 -lgdi32 - EXE ?= exe - A = a - DLL = dll - MWINDOWS = -mwindows - - # workaround: we have no "ldd" for Win32, so... - LDD = - # workaround: OpenGL library for Win32 is called opengl32.dll - LIBS_GL = -lopengl32 - # workaround: no -ldl on Win32 - LIBS_DL = -else - -ifeq ($(OS),Darwin) - CPPFLAGS_COMMON += -DPOSIX -DXWINDOWS - CFLAGS_COMMON += -fPIC - CXXFLAGS_COMMON += -fno-exceptions -fno-rtti - CPPFLAGS_COMMON += -I/opt/local/include -I/sw/include -I/usr/X11R6/include - LDFLAGS_COMMON += -L/opt/local/lib -L/sw/lib -L/usr/X11R6/lib - LDFLAGS_DLL += -dynamiclib -ldl - EXE ?= ppc - MACLIBDIR ?= /opt/local/lib - A = a - DLL = dylib - MWINDOWS = - # workaround for weird prints - ECHO_NOLF = /bin/echo -n - - # workaround: http://developer.apple.com/qa/qa2007/qa1567.html - LIBS_GL += -lX11 -dylib_file /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib - LIBS_GTKGLEXT += -lX11 -dylib_file /System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib:/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib - # workaround: we have no "ldd" for OS X, so... - LDD = - OTOOL = otool - - INSTALLDIR := $(INSTALLDIR_BASE)/NetRadiant.app/Contents/MacOS/install -else - -$(error Unsupported build OS: $(OS)) -endif -endif -endif - -# VERSION! -RADIANT_VERSION_NUMBER = 1.5.0 -RADIANT_VERSION = $(RADIANT_VERSION_NUMBER)n -RADIANT_MAJOR_VERSION = 5 -RADIANT_MINOR_VERSION = 0 -Q3MAP_VERSION = 2.5.17n - -# Executable extension -RADIANT_EXECUTABLE := $(EXE) - -GIT_VERSION := $(shell $(GIT) rev-parse --short HEAD $(STDERR_TO_DEVNULL)) -ifneq ($(GIT_VERSION),) - RADIANT_VERSION := $(RADIANT_VERSION)-git-$(GIT_VERSION) - Q3MAP_VERSION := $(Q3MAP_VERSION)-git-$(GIT_VERSION) -endif - -CPPFLAGS += -DRADIANT_VERSION="\"$(RADIANT_VERSION)\"" -DRADIANT_MAJOR_VERSION="\"$(RADIANT_MAJOR_VERSION)\"" -DRADIANT_MINOR_VERSION="\"$(RADIANT_MINOR_VERSION)\"" -DRADIANT_ABOUTMSG="\"$(RADIANT_ABOUTMSG)\"" -DQ3MAP_VERSION="\"$(Q3MAP_VERSION)\"" -DRADIANT_EXECUTABLE="\"$(RADIANT_EXECUTABLE)\"" - -.PHONY: all -all: \ - dependencies-check \ - binaries \ - install-data \ - install-dll \ - -.PHONY: dependencies-check -ifeq ($(findstring $(DEPENDENCIES_CHECK),off),off) -dependencies-check: - @$(ECHO) dependencies checking disabled, good luck... -else -dependencies-check: - @$(ECHO) - @if [ x"$(DEPENDENCIES_CHECK)" = x"verbose" ]; then set -x; exec 3>&2; else exec 3$(FD_TO_DEVNULL); fi; \ - failed=0; \ - checkbinary() \ - { \ - $(ECHO_NOLF) "Checking for $$2 ($$1)... "; \ - $$2 --help >&3 $(STDERR_TO_STDOUT); \ - if [ $$? != 127 ]; then \ - $(ECHO) "found."; \ - else \ - $(ECHO) "not found, please install it or set PATH right!"; \ - $(ECHO) "To see the failed commands, set DEPENDENCIES_CHECK=verbose"; \ - $(ECHO) "To proceed anyway, set DEPENDENCIES_CHECK=off"; \ - failed=1; \ - fi; \ - }; \ - $(ECHO) checking that the build tools exist; \ - checkbinary "bash (or another shell)" "$(SH)"; \ - checkbinary coreutils "$(ECHO)"; \ - checkbinary coreutils "$(ECHO_NOLF)"; \ - checkbinary coreutils "$(CAT)"; \ - checkbinary coreutils "$(MKDIR)"; \ - checkbinary coreutils "$(CP)"; \ - checkbinary coreutils "$(CP_R)"; \ - checkbinary coreutils "$(RM)"; \ - checkbinary coreutils "$(RM_R)"; \ - checkbinary coreutils "$(MV)"; \ - checkbinary coreutils "$(ECHO) test $(TEE_STDERR)"; \ - checkbinary sed "$(SED)"; \ - checkbinary findutils "$(FIND)"; \ - checkbinary diff "$(DIFF)"; \ - checkbinary gcc "$(CC)"; \ - checkbinary g++ "$(CXX)"; \ - checkbinary binutils "$(RANLIB)"; \ - checkbinary binutils "$(AR)"; \ - checkbinary pkg-config "$(PKGCONFIG)"; \ - checkbinary unzip "$(UNZIPPER)"; \ - checkbinary git-core "$(GIT)"; \ - checkbinary subversion "$(SVN)"; \ - checkbinary wget "$(WGET)"; \ - [ "$(OS)" = "Win32" ] && checkbinary mingw32 "$(WINDRES)"; \ - [ -n "$(LDD)" ] && checkbinary libc6 "$(LDD)"; \ - [ -n "$(OTOOL)" ] && checkbinary xcode "$(OTOOL)"; \ - [ "$$failed" = "0" ] && $(ECHO) All required tools have been found! - @$(ECHO) - @if [ x"$(DEPENDENCIES_CHECK)" = x"verbose" ]; then set -x; exec 3>&2; else exec 3$(FD_TO_DEVNULL); fi; \ - failed=0; \ - checkheader() \ - { \ - $(ECHO_NOLF) "Checking for $$2 ($$1)... "; \ - if \ - $(CXX) conftest.cpp $(CFLAGS) $(CXXFLAGS) $(CFLAGS_COMMON) $(CXXFLAGS_COMMON) $(CPPFLAGS) $(CPPFLAGS_COMMON) $$4 -DCONFTEST_HEADER="<$$2>" -DCONFTEST_SYMBOL="$$3" $(TARGET_ARCH) $(LDFLAGS) -c -o conftest.o >&3 $(STDERR_TO_STDOUT); \ - then \ - if \ - $(CXX) conftest.o $(LDFLAGS) $(LDFLAGS_COMMON) $$5 $(LIBS_COMMON) $(LIBS) -o conftest >&3 $(STDERR_TO_STDOUT); \ - then \ - $(RM) conftest conftest.o conftest.d; \ - $(ECHO) "found and links."; \ - else \ - $(RM) conftest.o conftest.d; \ - $(ECHO) "found but does not link, please install it or set PKG_CONFIG_PATH right!"; \ - $(ECHO) "To see the failed commands, set DEPENDENCIES_CHECK=verbose"; \ - $(ECHO) "To proceed anyway, set DEPENDENCIES_CHECK=off"; \ - failed=1; \ - fi; \ - else \ - $(RM) conftest conftest.o conftest.d; \ - $(ECHO) "not found, please install it or set PKG_CONFIG_PATH right!"; \ - $(ECHO) "To see the failed commands, set DEPENDENCIES_CHECK=verbose"; \ - $(ECHO) "To proceed anyway, set DEPENDENCIES_CHECK=off"; \ - failed=1; \ - fi; \ - }; \ - $(ECHO) checking that the dependencies exist; \ - checkheader libglib2.0-dev glib/gutils.h g_path_is_absolute "$(CPPFLAGS_GLIB)" "$(LIBS_GLIB)"; \ - checkheader libxml2-dev libxml/xpath.h xmlXPathInit "$(CPPFLAGS_XML)" "$(LIBS_XML)"; \ - checkheader libpng12-dev png.h png_create_read_struct "$(CPPFLAGS_PNG)" "$(LIBS_PNG)"; \ - checkheader "mesa-common-dev (or another OpenGL library)" GL/gl.h glClear "$(CPPFLAGS_GL)" "$(LIBS_GL)"; \ - checkheader libgtk2.0-dev gtk/gtkdialog.h gtk_dialog_run "$(CPPFLAGS_GTK)" "$(LIBS_GTK)"; \ - checkheader libpango1.0-dev pango/pangoft2.h pango_ft2_font_map_new "$(CPPFLAGS_PANGOFT2)" "$(LIBS_PANGOFT2)"; \ - checkheader libgtkglext1-dev gtk/gtkglwidget.h gtk_widget_get_gl_context "$(CPPFLAGS_GTKGLEXT)" "$(LIBS_GTKGLEXT)"; \ - [ "$(OS)" != "Win32" ] && checkheader libc6-dev dlfcn.h dlopen "$(CPPFLAGS_DL)" "$(LIBS_DL)"; \ - checkheader zlib1g-dev zlib.h zlibVersion "$(CPPFLAGS_ZLIB)" "$(LIBS_ZLIB)"; \ - [ "$$failed" = "0" ] && $(ECHO) All required libraries have been found! - @$(ECHO) -endif - -.PHONY: binaries -binaries: \ - binaries-tools \ - binaries-radiant \ - -.PHONY: binaries-radiant-all -binaries-radiant: \ - binaries-radiant-modules \ - binaries-radiant-plugins \ - binaries-radiant-core \ - -.PHONY: binaries-radiant-modules -binaries-radiant-modules: \ - $(INSTALLDIR)/modules/archivepak.$(DLL) \ - $(INSTALLDIR)/modules/archivewad.$(DLL) \ - $(INSTALLDIR)/modules/archivezip.$(DLL) \ - $(INSTALLDIR)/modules/entity.$(DLL) \ - $(INSTALLDIR)/modules/image.$(DLL) \ - $(INSTALLDIR)/modules/imagehl.$(DLL) \ - $(INSTALLDIR)/modules/imagepng.$(DLL) \ - $(INSTALLDIR)/modules/imageq2.$(DLL) \ - $(INSTALLDIR)/modules/mapq3.$(DLL) \ - $(INSTALLDIR)/modules/mapxml.$(DLL) \ - $(INSTALLDIR)/modules/md3model.$(DLL) \ - $(INSTALLDIR)/modules/model.$(DLL) \ - $(INSTALLDIR)/modules/shaders.$(DLL) \ - $(INSTALLDIR)/modules/vfspk3.$(DLL) \ - -.PHONY: binaries-radiant-plugins -binaries-radiant-plugins: \ - $(INSTALLDIR)/plugins/bobtoolz.$(DLL) \ - $(INSTALLDIR)/plugins/brushexport.$(DLL) \ - $(INSTALLDIR)/plugins/prtview.$(DLL) \ - $(INSTALLDIR)/plugins/shaderplug.$(DLL) \ - $(INSTALLDIR)/plugins/sunplug.$(DLL) \ - $(INSTALLDIR)/plugins/ufoaiplug.$(DLL) \ - -.PHONY: binaries-radiant -binaries-radiant-core: \ - $(INSTALLDIR)/radiant.$(EXE) \ - -.PHONY: binaries-tools -binaries-tools: \ - binaries-tools-quake2 \ - binaries-tools-quake3 \ - -.PHONY: binaries-tools-quake2 -binaries-tools-quake2: \ - binaries-q2map \ - binaries-qdata3 \ - binaries-h2data \ - -.PHONY: binaries-q2map -binaries-q2map: \ - $(INSTALLDIR)/q2map.$(EXE) \ - -.PHONY: binaries-qdata3 -binaries-qdata3: \ - $(INSTALLDIR)/qdata3.$(EXE) \ - -.PHONY: binaries-h2data -binaries-h2data: \ - $(INSTALLDIR)/heretic2/h2data.$(EXE) - -.PHONY: binaries-tools-quake3 -binaries-tools-quake3: \ - binaries-q3data \ - binaries-q3map2 \ - -.PHONY: binaries-q3data -binaries-q3data: \ - $(INSTALLDIR)/q3data.$(EXE) \ - -.PHONY: binaries-q3map2 -binaries-q3map2: \ - $(INSTALLDIR)/q3map2.$(EXE) \ - - -.PHONY: clean -clean: - $(RM_R) $(INSTALLDIR_BASE)/ - $(FIND) . \( -name \*.o -o -name \*.d -o -name \*.$(DLL) -o -name \*.$(A) -o -name \*.$(EXE) \) -exec $(RM) {} \; - $(RM) icons/*.rc - -%.$(EXE): - file=$@; $(MKDIR) $${file%/*} - $(CXX) $^ $(LDFLAGS) $(LDFLAGS_COMMON) $(LDFLAGS_EXTRA) $(LIBS_EXTRA) $(LIBS_COMMON) $(LIBS) -o $@ - [ -z "$(LDD)" ] || [ -z "`$(LDD) -r $@ $(STDERR_TO_STDOUT) $(STDOUT_TO_DEVNULL) $(TEE_STDERR)`" ] || { $(RM) $@; exit 1; } - -%.$(A): - $(AR) rc $@ $^ - $(RANLIB) $@ - -%.$(DLL): - file=$@; $(MKDIR) $${file%/*} - $(CXX) $^ $(LDFLAGS) $(LDFLAGS_COMMON) $(LDFLAGS_EXTRA) $(LDFLAGS_DLL) $(LIBS_EXTRA) $(LIBS_COMMON) $(LIBS) -shared -o $@ - [ -z "$(LDD)" ] || [ -z "`$(LDD) -r $@ $(STDERR_TO_STDOUT) $(STDOUT_TO_DEVNULL) $(TEE_STDERR)`" ] || { $(RM) $@; exit 1; } - -%.rc: %.ico - $(ECHO) '1 ICON "$<"' > $@ - -ifeq ($(OS),Win32) -%.o: %.rc - $(WINDRES) $< $@ -endif - -%.o: %.cpp $(if $(findstring $(DEPEND_ON_MAKEFILE),yes),$(wildcard Makefile*),) - $(CXX) $< $(CFLAGS) $(CXXFLAGS) $(CFLAGS_COMMON) $(CXXFLAGS_COMMON) $(CPPFLAGS_EXTRA) $(CPPFLAGS_COMMON) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ - -%.o: %.c $(if $(findstring $(DEPEND_ON_MAKEFILE),yes),$(wildcard Makefile*),) - $(CC) $< $(CFLAGS) $(CFLAGS_COMMON) $(CPPFLAGS_EXTRA) $(CPPFLAGS_COMMON) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ - - -$(INSTALLDIR)/q3map2.$(EXE): LIBS_EXTRA := $(LIBS_XML) $(LIBS_GLIB) $(LIBS_PNG) $(LIBS_ZLIB) -$(INSTALLDIR)/q3map2.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) $(CPPFLAGS_PNG) -Itools/quake3/common -Ilibs -Iinclude -$(INSTALLDIR)/q3map2.$(EXE): \ - tools/quake3/common/cmdlib.o \ - tools/quake3/common/imagelib.o \ - tools/quake3/common/inout.o \ - tools/quake3/common/md4.o \ - tools/quake3/common/mutex.o \ - tools/quake3/common/polylib.o \ - tools/quake3/common/scriplib.o \ - tools/quake3/common/threads.o \ - tools/quake3/common/unzip.o \ - tools/quake3/common/vfs.o \ - tools/quake3/q3map2/brush.o \ - tools/quake3/q3map2/brush_primit.o \ - tools/quake3/q3map2/bspfile_abstract.o \ - tools/quake3/q3map2/bspfile_ibsp.o \ - tools/quake3/q3map2/bspfile_rbsp.o \ - tools/quake3/q3map2/bsp.o \ - tools/quake3/q3map2/convert_ase.o \ - tools/quake3/q3map2/convert_obj.o \ - tools/quake3/q3map2/convert_map.o \ - tools/quake3/q3map2/decals.o \ - tools/quake3/q3map2/facebsp.o \ - tools/quake3/q3map2/fog.o \ - tools/quake3/q3map2/image.o \ - tools/quake3/q3map2/leakfile.o \ - tools/quake3/q3map2/light_bounce.o \ - tools/quake3/q3map2/lightmaps_ydnar.o \ - tools/quake3/q3map2/light.o \ - tools/quake3/q3map2/light_trace.o \ - tools/quake3/q3map2/light_ydnar.o \ - tools/quake3/q3map2/main.o \ - tools/quake3/q3map2/map.o \ - tools/quake3/q3map2/mesh.o \ - tools/quake3/q3map2/model.o \ - tools/quake3/q3map2/patch.o \ - tools/quake3/q3map2/path_init.o \ - tools/quake3/q3map2/portals.o \ - tools/quake3/q3map2/prtfile.o \ - tools/quake3/q3map2/shaders.o \ - tools/quake3/q3map2/surface_extra.o \ - tools/quake3/q3map2/surface_foliage.o \ - tools/quake3/q3map2/surface_fur.o \ - tools/quake3/q3map2/surface_meta.o \ - tools/quake3/q3map2/surface.o \ - tools/quake3/q3map2/tjunction.o \ - tools/quake3/q3map2/tree.o \ - tools/quake3/q3map2/visflow.o \ - tools/quake3/q3map2/vis.o \ - tools/quake3/q3map2/writebsp.o \ - libddslib.$(A) \ - libjpeg6.$(A) \ - libl_net.$(A) \ - libmathlib.$(A) \ - libpicomodel.$(A) \ - $(if $(findstring $(OS),Win32),icons/q3map2.o,) \ - -libmathlib.$(A): CPPFLAGS_EXTRA := -Ilibs -libmathlib.$(A): \ - libs/mathlib/bbox.o \ - libs/mathlib/line.o \ - libs/mathlib/m4x4.o \ - libs/mathlib/mathlib.o \ - libs/mathlib/ray.o \ - -libl_net.$(A): CPPFLAGS_EXTRA := -Ilibs -libl_net.$(A): \ - libs/l_net/l_net.o \ - $(if $(findstring $(OS),Win32),libs/l_net/l_net_wins.o,libs/l_net/l_net_berkley.o) \ - -libjpeg6.$(A): CPPFLAGS_EXTRA := -Ilibs/jpeg6 -Ilibs -libjpeg6.$(A): \ - libs/jpeg6/jcomapi.o \ - libs/jpeg6/jdapimin.o \ - libs/jpeg6/jdapistd.o \ - libs/jpeg6/jdatasrc.o \ - libs/jpeg6/jdcoefct.o \ - libs/jpeg6/jdcolor.o \ - libs/jpeg6/jddctmgr.o \ - libs/jpeg6/jdhuff.o \ - libs/jpeg6/jdinput.o \ - libs/jpeg6/jdmainct.o \ - libs/jpeg6/jdmarker.o \ - libs/jpeg6/jdmaster.o \ - libs/jpeg6/jdpostct.o \ - libs/jpeg6/jdsample.o \ - libs/jpeg6/jdtrans.o \ - libs/jpeg6/jerror.o \ - libs/jpeg6/jfdctflt.o \ - libs/jpeg6/jidctflt.o \ - libs/jpeg6/jmemmgr.o \ - libs/jpeg6/jmemnobs.o \ - libs/jpeg6/jpgload.o \ - libs/jpeg6/jutils.o \ - -libpicomodel.$(A): CPPFLAGS_EXTRA := -Ilibs -libpicomodel.$(A): \ - libs/picomodel/lwo/clip.o \ - libs/picomodel/lwo/envelope.o \ - libs/picomodel/lwo/list.o \ - libs/picomodel/lwo/lwio.o \ - libs/picomodel/lwo/lwo2.o \ - libs/picomodel/lwo/lwob.o \ - libs/picomodel/lwo/pntspols.o \ - libs/picomodel/lwo/surface.o \ - libs/picomodel/lwo/vecmath.o \ - libs/picomodel/lwo/vmap.o \ - libs/picomodel/picointernal.o \ - libs/picomodel/picomodel.o \ - libs/picomodel/picomodules.o \ - libs/picomodel/pm_3ds.o \ - libs/picomodel/pm_ase.o \ - libs/picomodel/pm_fm.o \ - libs/picomodel/pm_lwo.o \ - libs/picomodel/pm_md2.o \ - libs/picomodel/pm_md3.o \ - libs/picomodel/pm_mdc.o \ - libs/picomodel/pm_ms3d.o \ - libs/picomodel/pm_obj.o \ - libs/picomodel/pm_terrain.o \ - -libddslib.$(A): CPPFLAGS_EXTRA := -Ilibs -libddslib.$(A): \ - libs/ddslib/ddslib.o \ - -$(INSTALLDIR)/q3data.$(EXE): LIBS_EXTRA := $(LIBS_XML) $(LIBS_GLIB) $(LIBS_ZLIB) -$(INSTALLDIR)/q3data.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) $(CPPFLAGS_ZLIB) -Itools/quake3/common -Ilibs -Iinclude -$(INSTALLDIR)/q3data.$(EXE): \ - tools/quake3/common/aselib.o \ - tools/quake3/common/bspfile.o \ - tools/quake3/common/cmdlib.o \ - tools/quake3/common/imagelib.o \ - tools/quake3/common/inout.o \ - tools/quake3/common/md4.o \ - tools/quake3/common/scriplib.o \ - tools/quake3/common/trilib.o \ - tools/quake3/common/unzip.o \ - tools/quake3/common/vfs.o \ - tools/quake3/q3data/3dslib.o \ - tools/quake3/q3data/compress.o \ - tools/quake3/q3data/images.o \ - tools/quake3/q3data/md3lib.o \ - tools/quake3/q3data/models.o \ - tools/quake3/q3data/p3dlib.o \ - tools/quake3/q3data/polyset.o \ - tools/quake3/q3data/q3data.o \ - tools/quake3/q3data/stripper.o \ - tools/quake3/q3data/video.o \ - libl_net.$(A) \ - libmathlib.$(A) \ - $(if $(findstring $(OS),Win32),icons/q3data.o,) \ - -$(INSTALLDIR)/radiant.$(EXE): LDFLAGS_EXTRA := $(MWINDOWS) -$(INSTALLDIR)/radiant.$(EXE): LIBS_EXTRA := $(LIBS_GL) $(LIBS_DL) $(LIBS_XML) $(LIBS_GLIB) $(LIBS_GTK) $(LIBS_GTKGLEXT) $(LIBS_ZLIB) $(LIBS_PANGOFT2) -$(INSTALLDIR)/radiant.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_GL) $(CPPFLAGS_DL) $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) $(CPPFLAGS_GTKGLEXT) $(CPPFLAGS_PANGOFT2) -Ilibs -Iinclude -$(INSTALLDIR)/radiant.$(EXE): \ - radiant/autosave.o \ - radiant/brushmanip.o \ - radiant/brushmodule.o \ - radiant/brushnode.o \ - radiant/brush.o \ - radiant/brush_primit.o \ - radiant/brushtokens.o \ - radiant/brushxml.o \ - radiant/build.o \ - radiant/camwindow.o \ - radiant/clippertool.o \ - radiant/commands.o \ - radiant/console.o \ - radiant/csg.o \ - radiant/dialog.o \ - radiant/eclass_def.o \ - radiant/eclass_doom3.o \ - radiant/eclass_fgd.o \ - radiant/eclass.o \ - radiant/eclass_xml.o \ - radiant/entityinspector.o \ - radiant/entitylist.o \ - radiant/entity.o \ - radiant/environment.o \ - radiant/error.o \ - radiant/feedback.o \ - radiant/filetypes.o \ - radiant/filters.o \ - radiant/findtexturedialog.o \ - radiant/glwidget.o \ - radiant/grid.o \ - radiant/groupdialog.o \ - radiant/gtkdlgs.o \ - radiant/gtkmisc.o \ - radiant/help.o \ - radiant/image.o \ - radiant/mainframe.o \ - radiant/main.o \ - radiant/map.o \ - $(if $(findstring $(OS),Win32),radiant/multimon.o,) \ - radiant/mru.o \ - radiant/nullmodel.o \ - radiant/parse.o \ - radiant/patchdialog.o \ - radiant/patchmanip.o \ - radiant/patchmodule.o \ - radiant/patch.o \ - radiant/pluginapi.o \ - radiant/pluginmanager.o \ - radiant/pluginmenu.o \ - radiant/plugin.o \ - radiant/plugintoolbar.o \ - radiant/points.o \ - radiant/preferencedictionary.o \ - radiant/preferences.o \ - radiant/qe3.o \ - radiant/qgl.o \ - radiant/referencecache.o \ - radiant/renderer.o \ - radiant/renderstate.o \ - radiant/scenegraph.o \ - radiant/selection.o \ - radiant/select.o \ - radiant/server.o \ - radiant/shaders.o \ - radiant/sockets.o \ - radiant/stacktrace.o \ - radiant/surfacedialog.o \ - radiant/texmanip.o \ - radiant/textures.o \ - radiant/texwindow.o \ - radiant/timer.o \ - radiant/treemodel.o \ - radiant/undo.o \ - radiant/url.o \ - radiant/view.o \ - radiant/watchbsp.o \ - radiant/winding.o \ - radiant/windowobservers.o \ - radiant/xmlstuff.o \ - radiant/xywindow.o \ - libcmdlib.$(A) \ - libgtkutil.$(A) \ - libl_net.$(A) \ - libmathlib.$(A) \ - libprofile.$(A) \ - libxmllib.$(A) \ - $(if $(findstring $(OS),Win32),icons/radiant.o,) \ - -libcmdlib.$(A): CPPFLAGS_EXTRA := -Ilibs -libcmdlib.$(A): \ - libs/cmdlib/cmdlib.o \ - -libprofile.$(A): CPPFLAGS_EXTRA := -Ilibs -Iinclude -libprofile.$(A): \ - libs/profile/file.o \ - libs/profile/profile.o \ - -libgtkutil.$(A): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) $(CPPFLAGS_GTKGLEXT) $(CPPFLAGS_PANGOFT2) -Ilibs -Iinclude -libgtkutil.$(A): \ - libs/gtkutil/accelerator.o \ - libs/gtkutil/button.o \ - libs/gtkutil/clipboard.o \ - libs/gtkutil/closure.o \ - libs/gtkutil/container.o \ - libs/gtkutil/cursor.o \ - libs/gtkutil/dialog.o \ - libs/gtkutil/entry.o \ - libs/gtkutil/filechooser.o \ - libs/gtkutil/frame.o \ - libs/gtkutil/glfont.o \ - libs/gtkutil/glwidget.o \ - libs/gtkutil/idledraw.o \ - libs/gtkutil/image.o \ - libs/gtkutil/menu.o \ - libs/gtkutil/messagebox.o \ - libs/gtkutil/nonmodal.o \ - libs/gtkutil/paned.o \ - libs/gtkutil/pointer.o \ - libs/gtkutil/toolbar.o \ - libs/gtkutil/widget.o \ - libs/gtkutil/window.o \ - libs/gtkutil/xorrectangle.o \ - -libxmllib.$(A): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) -Ilibs -Iinclude -libxmllib.$(A): \ - libs/xml/ixml.o \ - libs/xml/xmlelement.o \ - libs/xml/xmlparser.o \ - libs/xml/xmltextags.o \ - libs/xml/xmlwriter.o \ - -$(INSTALLDIR)/modules/archivezip.$(DLL): LIBS_EXTRA := $(LIBS_ZLIB) -$(INSTALLDIR)/modules/archivezip.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_ZLIB) -Ilibs -Iinclude -$(INSTALLDIR)/modules/archivezip.$(DLL): \ - plugins/archivezip/archive.o \ - plugins/archivezip/pkzip.o \ - plugins/archivezip/plugin.o \ - plugins/archivezip/zlibstream.o \ - -$(INSTALLDIR)/modules/archivewad.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/archivewad.$(DLL): \ - plugins/archivewad/archive.o \ - plugins/archivewad/plugin.o \ - plugins/archivewad/wad.o \ - -$(INSTALLDIR)/modules/archivepak.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/archivepak.$(DLL): \ - plugins/archivepak/archive.o \ - plugins/archivepak/pak.o \ - plugins/archivepak/plugin.o \ - -$(INSTALLDIR)/modules/entity.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/entity.$(DLL): \ - plugins/entity/angle.o \ - plugins/entity/angles.o \ - plugins/entity/colour.o \ - plugins/entity/doom3group.o \ - plugins/entity/eclassmodel.o \ - plugins/entity/entity.o \ - plugins/entity/filters.o \ - plugins/entity/generic.o \ - plugins/entity/group.o \ - plugins/entity/light.o \ - plugins/entity/miscmodel.o \ - plugins/entity/model.o \ - plugins/entity/modelskinkey.o \ - plugins/entity/namedentity.o \ - plugins/entity/origin.o \ - plugins/entity/plugin.o \ - plugins/entity/rotation.o \ - plugins/entity/scale.o \ - plugins/entity/skincache.o \ - plugins/entity/targetable.o \ - -$(INSTALLDIR)/modules/image.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/image.$(DLL): \ - plugins/image/bmp.o \ - plugins/image/dds.o \ - plugins/image/image.o \ - plugins/image/jpeg.o \ - plugins/image/pcx.o \ - plugins/image/tga.o \ - libddslib.$(A) \ - libjpeg6.$(A) \ - -$(INSTALLDIR)/modules/imageq2.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/imageq2.$(DLL): \ - plugins/imageq2/imageq2.o \ - plugins/imageq2/wal32.o \ - plugins/imageq2/wal.o \ - -$(INSTALLDIR)/modules/imagehl.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/imagehl.$(DLL): \ - plugins/imagehl/hlw.o \ - plugins/imagehl/imagehl.o \ - plugins/imagehl/mip.o \ - plugins/imagehl/sprite.o \ - -$(INSTALLDIR)/modules/imagepng.$(DLL): LIBS_EXTRA := $(LIBS_PNG) -$(INSTALLDIR)/modules/imagepng.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_PNG) -Ilibs -Iinclude -$(INSTALLDIR)/modules/imagepng.$(DLL): \ - plugins/imagepng/plugin.o \ - -$(INSTALLDIR)/modules/mapq3.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/mapq3.$(DLL): \ - plugins/mapq3/parse.o \ - plugins/mapq3/plugin.o \ - plugins/mapq3/write.o \ - -$(INSTALLDIR)/modules/mapxml.$(DLL): LIBS_EXTRA := $(LIBS_XML) $(LIBS_GLIB) -$(INSTALLDIR)/modules/mapxml.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) $(CPPFLAGS_GLIB) -Ilibs -Iinclude -$(INSTALLDIR)/modules/mapxml.$(DLL): \ - plugins/mapxml/plugin.o \ - plugins/mapxml/xmlparse.o \ - plugins/mapxml/xmlwrite.o \ - -$(INSTALLDIR)/modules/md3model.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/md3model.$(DLL): \ - plugins/md3model/md2.o \ - plugins/md3model/md3.o \ - plugins/md3model/md5.o \ - plugins/md3model/mdc.o \ - plugins/md3model/mdlimage.o \ - plugins/md3model/mdl.o \ - plugins/md3model/plugin.o \ - -$(INSTALLDIR)/modules/model.$(DLL): CPPFLAGS_EXTRA := -Ilibs -Iinclude -$(INSTALLDIR)/modules/model.$(DLL): \ - plugins/model/model.o \ - plugins/model/plugin.o \ - libpicomodel.$(A) \ - -$(INSTALLDIR)/modules/shaders.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) -$(INSTALLDIR)/modules/shaders.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) -Ilibs -Iinclude -$(INSTALLDIR)/modules/shaders.$(DLL): \ - plugins/shaders/plugin.o \ - plugins/shaders/shaders.o \ - -$(INSTALLDIR)/modules/vfspk3.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) -$(INSTALLDIR)/modules/vfspk3.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) -Ilibs -Iinclude -$(INSTALLDIR)/modules/vfspk3.$(DLL): \ - plugins/vfspk3/archive.o \ - plugins/vfspk3/vfs.o \ - plugins/vfspk3/vfspk3.o \ - -$(INSTALLDIR)/plugins/bobtoolz.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK) -$(INSTALLDIR)/plugins/bobtoolz.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude -$(INSTALLDIR)/plugins/bobtoolz.$(DLL): \ - contrib/bobtoolz/bobToolz-GTK.o \ - contrib/bobtoolz/bsploader.o \ - contrib/bobtoolz/cportals.o \ - contrib/bobtoolz/DBobView.o \ - contrib/bobtoolz/DBrush.o \ - contrib/bobtoolz/DEntity.o \ - contrib/bobtoolz/DEPair.o \ - contrib/bobtoolz/dialogs/dialogs-gtk.o \ - contrib/bobtoolz/DMap.o \ - contrib/bobtoolz/DPatch.o \ - contrib/bobtoolz/DPlane.o \ - contrib/bobtoolz/DPoint.o \ - contrib/bobtoolz/DShape.o \ - contrib/bobtoolz/DTrainDrawer.o \ - contrib/bobtoolz/DTreePlanter.o \ - contrib/bobtoolz/DVisDrawer.o \ - contrib/bobtoolz/DWinding.o \ - contrib/bobtoolz/funchandlers-GTK.o \ - contrib/bobtoolz/lists.o \ - contrib/bobtoolz/misc.o \ - contrib/bobtoolz/ScriptParser.o \ - contrib/bobtoolz/shapes.o \ - contrib/bobtoolz/visfind.o \ - libcmdlib.$(A) \ - libmathlib.$(A) \ - libprofile.$(A) \ - -$(INSTALLDIR)/plugins/brushexport.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK) -$(INSTALLDIR)/plugins/brushexport.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude -$(INSTALLDIR)/plugins/brushexport.$(DLL): \ - contrib/brushexport/callbacks.o \ - contrib/brushexport/export.o \ - contrib/brushexport/interface.o \ - contrib/brushexport/plugin.o \ - contrib/brushexport/support.o \ - -$(INSTALLDIR)/plugins/prtview.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK) -$(INSTALLDIR)/plugins/prtview.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude -$(INSTALLDIR)/plugins/prtview.$(DLL): \ - contrib/prtview/AboutDialog.o \ - contrib/prtview/ConfigDialog.o \ - contrib/prtview/LoadPortalFileDialog.o \ - contrib/prtview/portals.o \ - contrib/prtview/prtview.o \ - libprofile.$(A) \ - -$(INSTALLDIR)/plugins/shaderplug.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK) $(LIBS_XML) -$(INSTALLDIR)/plugins/shaderplug.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) $(CPPFLAGS_XML) -Ilibs -Iinclude -$(INSTALLDIR)/plugins/shaderplug.$(DLL): \ - contrib/shaderplug/shaderplug.o \ - libxmllib.$(A) \ - -$(INSTALLDIR)/plugins/sunplug.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK) -$(INSTALLDIR)/plugins/sunplug.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude -$(INSTALLDIR)/plugins/sunplug.$(DLL): \ - contrib/sunplug/sunplug.o \ - -$(INSTALLDIR)/qdata3.$(EXE): LIBS_EXTRA := $(LIBS_XML) -$(INSTALLDIR)/qdata3.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) -Itools/quake2/common -Ilibs -Iinclude -$(INSTALLDIR)/qdata3.$(EXE): \ - tools/quake2/common/bspfile.o \ - tools/quake2/common/cmdlib.o \ - tools/quake2/common/inout.o \ - tools/quake2/common/l3dslib.o \ - tools/quake2/common/lbmlib.o \ - tools/quake2/common/mathlib.o \ - tools/quake2/common/md4.o \ - tools/quake2/common/path_init.o \ - tools/quake2/common/polylib.o \ - tools/quake2/common/scriplib.o \ - tools/quake2/common/threads.o \ - tools/quake2/common/trilib.o \ - tools/quake2/qdata/images.o \ - tools/quake2/qdata/models.o \ - tools/quake2/qdata/qdata.o \ - tools/quake2/qdata/sprites.o \ - tools/quake2/qdata/tables.o \ - tools/quake2/qdata/video.o \ - libl_net.$(A) \ - $(if $(findstring $(OS),Win32),icons/qdata3.o,) \ - -$(INSTALLDIR)/q2map.$(EXE): LIBS_EXTRA := $(LIBS_XML) -$(INSTALLDIR)/q2map.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) -Itools/quake2/common -Ilibs -Iinclude -$(INSTALLDIR)/q2map.$(EXE): \ - tools/quake2/common/bspfile.o \ - tools/quake2/common/cmdlib.o \ - tools/quake2/common/inout.o \ - tools/quake2/common/l3dslib.o \ - tools/quake2/common/lbmlib.o \ - tools/quake2/common/mathlib.o \ - tools/quake2/common/md4.o \ - tools/quake2/common/path_init.o \ - tools/quake2/common/polylib.o \ - tools/quake2/common/scriplib.o \ - tools/quake2/common/threads.o \ - tools/quake2/common/trilib.o \ - tools/quake2/q2map/brushbsp.o \ - tools/quake2/q2map/csg.o \ - tools/quake2/q2map/faces.o \ - tools/quake2/q2map/flow.o \ - tools/quake2/q2map/glfile.o \ - tools/quake2/q2map/leakfile.o \ - tools/quake2/q2map/lightmap.o \ - tools/quake2/q2map/main.o \ - tools/quake2/q2map/map.o \ - tools/quake2/q2map/nodraw.o \ - tools/quake2/q2map/patches.o \ - tools/quake2/q2map/portals.o \ - tools/quake2/q2map/prtfile.o \ - tools/quake2/q2map/qbsp.o \ - tools/quake2/q2map/qrad.o \ - tools/quake2/q2map/qvis.o \ - tools/quake2/q2map/textures.o \ - tools/quake2/q2map/trace.o \ - tools/quake2/q2map/tree.o \ - tools/quake2/q2map/writebsp.o \ - libl_net.$(A) \ - $(if $(findstring $(OS),Win32),icons/q2map.o,) \ - -$(INSTALLDIR)/plugins/ufoaiplug.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK) -$(INSTALLDIR)/plugins/ufoaiplug.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude -$(INSTALLDIR)/plugins/ufoaiplug.$(DLL): \ - contrib/ufoaiplug/ufoai_filters.o \ - contrib/ufoaiplug/ufoai_gtk.o \ - contrib/ufoaiplug/ufoai_level.o \ - contrib/ufoaiplug/ufoai.o \ - -$(INSTALLDIR)/plugins/bkgrnd2d.$(DLL): LIBS_EXTRA := $(LIBS_GLIB) $(LIBS_GTK) -$(INSTALLDIR)/plugins/bkgrnd2d.$(DLL): CPPFLAGS_EXTRA := $(CPPFLAGS_GLIB) $(CPPFLAGS_GTK) -Ilibs -Iinclude -$(INSTALLDIR)/plugins/bkgrnd2d.$(DLL): \ - contrib/bkgrnd2d/bkgrnd2d.o \ - contrib/bkgrnd2d/dialog.o \ - contrib/bkgrnd2d/plugin.o \ - -$(INSTALLDIR)/heretic2/h2data.$(EXE): LIBS_EXTRA := $(LIBS_XML) -$(INSTALLDIR)/heretic2/h2data.$(EXE): CPPFLAGS_EXTRA := $(CPPFLAGS_XML) -Itools/quake2/qdata_heretic2/common -Itools/quake2/qdata_heretic2/qcommon -Itools/quake2/qdata_heretic2 -Itools/quake2/common -Ilibs -Iinclude -$(INSTALLDIR)/heretic2/h2data.$(EXE): \ - tools/quake2/qdata_heretic2/common/bspfile.o \ - tools/quake2/qdata_heretic2/common/cmdlib.o \ - tools/quake2/qdata_heretic2/common/inout.o \ - tools/quake2/qdata_heretic2/common/l3dslib.o \ - tools/quake2/qdata_heretic2/common/lbmlib.o \ - tools/quake2/qdata_heretic2/common/mathlib.o \ - tools/quake2/qdata_heretic2/common/md4.o \ - tools/quake2/qdata_heretic2/common/path_init.o \ - tools/quake2/qdata_heretic2/common/qfiles.o \ - tools/quake2/qdata_heretic2/common/scriplib.o \ - tools/quake2/qdata_heretic2/common/threads.o \ - tools/quake2/qdata_heretic2/common/token.o \ - tools/quake2/qdata_heretic2/common/trilib.o \ - tools/quake2/qdata_heretic2/qcommon/reference.o \ - tools/quake2/qdata_heretic2/qcommon/resourcemanager.o \ - tools/quake2/qdata_heretic2/qcommon/skeletons.o \ - tools/quake2/qdata_heretic2/animcomp.o \ - tools/quake2/qdata_heretic2/book.o \ - tools/quake2/qdata_heretic2/fmodels.o \ - tools/quake2/qdata_heretic2/images.o \ - tools/quake2/qdata_heretic2/jointed.o \ - tools/quake2/qdata_heretic2/models.o \ - tools/quake2/qdata_heretic2/pics.o \ - tools/quake2/qdata_heretic2/qdata.o \ - tools/quake2/qdata_heretic2/qd_skeletons.o \ - tools/quake2/qdata_heretic2/sprites.o \ - tools/quake2/qdata_heretic2/svdcmp.o \ - tools/quake2/qdata_heretic2/tables.o \ - tools/quake2/qdata_heretic2/tmix.o \ - tools/quake2/qdata_heretic2/video.o \ - libl_net.$(A) \ - $(if $(findstring $(OS),Win32),icons/h2data.o,) \ - -.PHONY: install-data -install-data: binaries - $(MKDIR) $(INSTALLDIR)/games - $(FIND) $(INSTALLDIR_BASE)/ -name .svn -exec $(RM_R) {} \; -prune - [ "$(OS)" != "Darwin" ] || $(CP_R) setup/data/osx/NetRadiant.app/* $(INSTALLDIR_BASE)/NetRadiant.app/ - DOWNLOAD_GAMEPACKS="$(DOWNLOAD_GAMEPACKS)" GIT="$(GIT)" SVN="$(SVN)" WGET="$(WGET)" RM_R="$(RM_R)" MV="$(MV)" UNZIPPER="$(UNZIPPER)" ECHO="$(ECHO)" SH="$(SH)" CP="$(CP)" CP_R="$(CP_R)" $(SH) install-gamepacks.sh "$(INSTALLDIR)" - $(ECHO) $(RADIANT_MINOR_VERSION) > $(INSTALLDIR)/RADIANT_MINOR - $(ECHO) $(RADIANT_MAJOR_VERSION) > $(INSTALLDIR)/RADIANT_MAJOR - $(CP_R) setup/data/tools/* $(INSTALLDIR)/ - $(MKDIR) $(INSTALLDIR)/docs - $(CP_R) docs/* $(INSTALLDIR)/docs/ - $(FIND) $(INSTALLDIR_BASE)/ -name .svn -exec $(RM_R) {} \; -prune - -.PHONY: install-dll -ifeq ($(OS),Win32) -install-dll: binaries - MKDIR="$(MKDIR)" CP="$(CP)" CAT="$(CAT)" GTKDIR="$(GTKDIR)" WHICHDLL="$(WHICHDLL)" INSTALLDIR="$(INSTALLDIR)" $(SH) install-dlls.sh -else -ifeq ($(OS),Darwin) -install-dll: binaries - EXE="$(EXE)" MACLIBDIR="$(MACLIBDIR)" CP="$(CP)" OTOOL="$(OTOOL)" INSTALLDIR="$(INSTALLDIR)" $(SH) install-dylibs.sh -else -install-dll: binaries - @$(ECHO) No DLL inclusion implemented for this target. -endif -endif - -# release building... NOT for general users -# these may use tools not in the list that is checked by the build system -release-src: BUILD_DATE := $(shell date +%Y%m%d) -release-src: INSTALLDIR := netradiant-$(RADIANT_VERSION_NUMBER)-$(BUILD_DATE) -release-src: - $(GIT) archive --format=tar --prefix=$(INSTALLDIR)/ HEAD | bzip2 > ../$(INSTALLDIR).tar.bz2 - -release-win32: BUILD_DATE := $(shell date +%Y%m%d) -release-win32: INSTALLDIR := netradiant-$(RADIANT_VERSION_NUMBER)-$(BUILD_DATE) -release-win32: - $(MAKE) all INSTALLDIR=$(INSTALLDIR) MAKEFILE_CONF=cross-Makefile.conf RADIANT_ABOUTMSG="Official release build" BUILD=release - 7za a -sfx../../../../../../../../../../$(HOME)/7z.sfx ../$(INSTALLDIR)-win32-7z.exe $(INSTALLDIR)/ - chmod 644 ../$(INSTALLDIR)-win32-7z.exe # 7zip is evil - $(MAKE) clean INSTALLDIR=$(INSTALLDIR) MAKEFILE_CONF=cross-Makefile.conf RADIANT_ABOUTMSG="Official release build" BUILD=release - -release-all: - $(GIT) clean -xdf - $(MAKE) release-src - $(MAKE) release-win32 - -# load dependency files --include $(shell find . -name \*.d) diff --git a/misc/mediasource/extra/netradiant-src/Makefile.conf b/misc/mediasource/extra/netradiant-src/Makefile.conf deleted file mode 100644 index 95d54970..00000000 --- a/misc/mediasource/extra/netradiant-src/Makefile.conf +++ /dev/null @@ -1,17 +0,0 @@ -# empty Makefile.conf template - -## OS X: -# BUILD=debug -# RADIANT_ABOUTMSG=Custom build -# EXE=ub - -## Fink -## (-arch ppc can combined with -arch 386, I read somewhere. However does work fine like this on OSX 10.6) -# LDFLAGS=-arch i386 -# CFLAGS=-arch i386 -# TARGET_ARCH=-arch i386 -# MACLIBDIR=/sw/lib - -## On some versions of OSX you may get compile errors regarding glTexImage1D, uncomment this to fix it -#MACVERSION ?= 16 -#CPPFLAGS_COMMON += -DMACVERSION="$(MACVERSION)" diff --git a/misc/mediasource/extra/netradiant-src/README.doxygen b/misc/mediasource/extra/netradiant-src/README.doxygen deleted file mode 100644 index f3847f67..00000000 --- a/misc/mediasource/extra/netradiant-src/README.doxygen +++ /dev/null @@ -1,51 +0,0 @@ - Documentation for generating doxygen documentation ---------------------------------------------------------- - -1. Options for gendox -More up-to-date command line options are available via -the command ./gendox --help - -usage: "sh gendox [ ] [ -o ]" - or "./gendox [ ] [ -o ]" - - - The directory, or directories to generate the - documentation from. - --o - Specifies the output directory which - should follow the -o switch - --q --quiet - Stops the script from outputing status information, - other than errors. - --k --kill - Kills other running doxygen pids. - -eg: ./gendox include/ -o ../Documentation - -* This will produce documentation for the include files, -and output to the directory specified one level above the -current directory. - -The target can be the current directory "./" in which case -doxygen will generate documentation for all subdirectories -of the current directory recursively. - -The default output directory is currently ... -> ../GtkRadiant-doxygen - -* If the script is called without any target directories -it will generate documentation for the core of radiant... -include/ libs/ radiant/ and plugins/ - -If there are specific options that you'd like to customise, -the DoxyConfig file is used to generate the file from which -doxygen gets its settings from. So any changes that need -to be made should be made to this file. - - -Gef :] -(gefdavis@dingoblue.net.au) ---------------------------------------------------------- diff --git a/misc/mediasource/extra/netradiant-src/TODO b/misc/mediasource/extra/netradiant-src/TODO deleted file mode 100644 index 60573df1..00000000 --- a/misc/mediasource/extra/netradiant-src/TODO +++ /dev/null @@ -1,149 +0,0 @@ -[-z-]: make rotate dialog non-modal - - - -BUGS - -MSI: installer bug with new folders? : create custom dir, click New Folder icon, type "FOLDER\" - gets stuck -GTK2: gtk2 crashes when trying to use bitmap fonts such as MS Sans Serif http://bugzilla.gnome.org/show_bug.cgi?id=142579 -GTK2: alt+tab while mouse button is held down: see http://bugzilla.gnome.org/show_bug.cgi?id=145156 -UI: changing resolution in floating-windows mode can screw up window positions. -HalfLife: half-life maps saved in q1 map format are not supported - currently have to convert them to hammer map format using hammer editor. And vice versa. -Entity: creating a new entity with all the brushes of another entity selected results in the latter entity having no brushes. -SConscript: build fails if SETUP=1 -SConscript: svn.py fails if not using C locale - set LC_ALL? -GUI: can't use arrow keys to navigate in camera view when capslock is enabled -GUI: screensaver causes: gdkgc-win32.c: line 905 (gdk_win32_hdc_get): assertion failed: (win32_gc->hdc == NULL) - - -FEATURES - -- paint-select or equivalent (e.g. area-selection with occlusion) -- select-complete-tall or equivalent (e.g. subtract-from-selection modifier key) -- texture pane names are often illegible, becuase 1. they are long and overlap each other and 2. they overlap the outline rectangles around the images themselves. - - -Build: document build-menu xml format. -The build menu in GtkRadiant 1.5 is entirely customisable - you can make it run qbsp3/qvis3/arghrad or any tool you want. Use 'Build > Customize...' to edit the menu. - -Menu commands are the shell commands that Radiant will execute when you choose the menu item. You can add as many commands as you want to a single menu item, and they will be executed in sequence. The commands contain variables, specified using []. The values of variables will be substituted when the command is executed. - -For example: -
[q2map] -bsp "[MapFile]"
-becomes: -
"C:\Program Files\GtkRadiant 1.5.0\q2map" -fs_basepath "c:\quake2" -bsp "c:\quake2\baseq2\maps\blah.map"
-This uses the predefined variable 'MapFile' and the custom variable 'q2map'. 'q2map' is defined in the XML file, and 'MapFile' is the full path to your map. -The 'MapFile' variable is enclosed in quotes, because the path to your map may contain spaces. -At the moment you can only create custom variables by editing the XML file. A custom variable for arghrad would look something like this: -
"[RadiantPath]arghrad"
-This variable could then be used in a command like this: -
[arghrad] "[MapFile]"
- -Entity: option to filter non-world entities (e.g. not func_group or func_static) -Rotate Tool: if more than one object is selected, with different local orientations, use parent-space rotation pivot instead of local-space -Brush: MMB+ctrl to paint texture on whole brush/patch. -Camera: add alternative highlighting styles (used to be J). -Doom3: filter func_splinemovers -Entity: draw arrowheads to show direction of connection-lines. -? MMB to select a texture should also apply that texture to all selected faces. -Mouse: support 2-button mouse. -Grid: background colour should be different when the smallest grid is invisible due to being zoomed out. -Brush: option to disable dots on selected faces when not in face mode. -Entity: draw direction arrow for func_door and func_button angle. -Build Menu: support for editing variables. -Shaders: handle doom3 materials with multiple bumpmaps stage - use first stage, ignore later stages. -Brush: warn when a brush is dragged into a configuration with <0 volume -Textures: add option to give new brushes a specific texture instead of the last selected. -? QE-tool: click anywhere on xy view to drag entity instead of requiring clicking directly on entity. -UserDocs: how to use multi-vertex selection - replaces vertex-edit-splits-faces option: -UserDocs: how to use parent-selection: - Parent-selection works like Maya: it allows you to 'reparent' brushes - onto other entities than the one they're currently part of. To use it, - select some brushes, select an entity, Edit -> Parent. -Textures: add anisotropic filtering. -Preferences: allow preference settings to be shared across games. -Preferences: add colour 'theme' files using prefs format. -Preferences: sensible default size for prefs window. -Doom3: add model browser. -Doom3: s_diversity light key. -HalfLife: enable HL-mode on linux/osx. -Renderer: doom3 'parallel' and 'spot' light support. -Entity: add mouse-editing for doom3 light_center key -Shaders: add support for texture transforms. -Shaders: add support for 'addnormals' keyword - e.g. models/mapobjects/healthgui/healthguidirty -TGA Loader: check that true-colour images with palettes are properly handled. -Module System: reinstate 'refresh' feature. -Surface Inspector: add button for 'axial' projection for doom3. -Build: fix hardcoded engine-launch commands - use similar system to build-menu command description. -Filters: use q2/heretic2 content flags to filter brushes. -? Surface Inspector: allow material names not relative to 'textures/' for doom3 -Module System: add versioning for module-system api. -svn: remove install/ dir, create it during build process on win32 -Editing: add option to choose the default startup tool mode. -Renderer: lighting for doom3 materials without bumpmaps (e.g. mcity/mchangar2) -Renderer: realtime doom3 materials preview -Renderer: realtime doom3 shadows preview -Linux: Provide .tar.gz of example-map data for et/wolf. -Textures Window: add inner dark outline to distinguish 'is-shader' outline from white textures. -HalfLife2: add HL2 map load/save. -Selection: add move-pivot mode to allow rotation/scale around a custom pivot-point. -Selection: add rotate increment for rotate manipulator. -Selection: visibly distinguish between entity and brush selections -Selection: need 'add to selection' and 'subtract from selection' modifiers -Selection: Finish scale manipulator. -FaceCopy/PasteTexture: Make face-copy/paste-texture shortcuts customisable. -Manual: add documentation about search paths for .ent/.def/.fgd, shaders etc for each game. -Halflife: add support for cstrike fgd. -HalfLife: disable patches -HalfLife: add HL .mdl model loader. -HalfLife: add HL .spr support. -HalfLife: support fgd 'flags' attributes. -Model: add support for doom3 md5anim format -Model: support doom3 ragdolls -VFS: add ability to browse VFS from file-open dialogs. -Installer: enable q3 brush-primitives map support. -Installer: add editor manual to linux installer -Map: add conversion between map formats -Map: add conversion between entity definition formats -Build: add build-menu dmap support (doom3) -Entity: optionally draw target connection lines thicker than one pixel. -Entity: add specialised attribute-entry in entity-inspector for integer/real/color attribute types. -Patch: add cap-texture, fit-texture and natural-texture toolbar buttons -Patch: draw patches in wireframe from the back, make patches selectable from the back -Patch: add option for convert-selection-to-new-brush/patch -Patch: fix bobtoolz merge-patches feature -Patch: fix insert/remove rows/cols indicated by current selected patch vertices. -Autosave/Snapshots: Add support for multi-file maps. -Quake2: Q2 hint transparency support -Shortcuts: make shortcut list editable within radiant. -Shortcuts: convert shortcuts.ini to xml. -Shortcuts: warn when duplicate shortcuts are registered -Shortcuts: rename commands in order to group shortcuts list better. -upgrade to new API for SymGetModuleInfo - required for compiling with Visual Studio 8.0 -Doom3: lights should stay in place while resizing - - -LOW priority features - -Selection: Add shear manipulator? -Textures Window: Improve texture-manipulation and texture-browsing tools. -Undo: make selections undoable? -Win32 Installer: Automatically upgrade existing installation. -General: refactor game-specific hacks to be parameterised by .game file -Patch: Overlays, Bend Mode, Thicken. -Brush: Add brush-specific plugin API. -Entity: Draw light style numbers. -... Entity: Show models with model2 key. -Entity: Interpret _remap* key (_MindLink_). -Entity: Support _origin _angles _scale on groups. -Selection: Add Primitive-mode shortcut key/button. -Selection: Customisable manipulator size - +/- to change the size of the translate/rotate tool. -Selection: Add optional screen-relative control for constrained rotations. -Clipper: Change selection/manipulation to be consistent with other component editing. -Filtering: Either deselect filtered nodes, or render filtered nodes that are selected. -Filtering: Add customisable filter presets to set/unset multiple filters at once. -Texdef: Make texdef formats abstract, add conversion between texdef formats (use generic affine-texture-matrix format for conversions). -Textures Window: Precise display of texture size when selecting. (tooltip, possibly) -Status: 'Size of brush' display on status bar. -Colours: maya scheme default? -Quake: add support for adjusting gamma on quake palette? diff --git a/misc/mediasource/extra/netradiant-src/branch-manager b/misc/mediasource/extra/netradiant-src/branch-manager deleted file mode 100644 index 2fd5a8fd..00000000 --- a/misc/mediasource/extra/netradiant-src/branch-manager +++ /dev/null @@ -1,344 +0,0 @@ -#!/usr/bin/perl - -use strict; -use warnings; - -sub OutputOf($@) -{ - my ($cmd, @args) = @_; - $cmd =~ s/#(\d)/"\$ARG$1"/g; - $ENV{"ARG$_"} = $args[$_-1] - for 1..@args; - - open my $fh, '-|', $cmd - or die "popen $cmd: $!"; - - $ENV{"ARG$_"} = '' - for 1..@args; - - undef local $/; - my $ret = <$fh>; - close $fh; - - return $ret; -} - -my %conf = -( - master => '', - revisions_applied => '' -); -my @revisions_applied = (); # array of [first, last] ranges - -sub LoadSettings() -{ - open my $fh, '<', ".patchsets" - or return; - while(<$fh>) - { - chomp; - /^([^=]*?)\s*=\s*(.*?)$/s - or next; - die "Invalid config item: $1 (allowed: @{[sort keys %conf]})" - if not exists $conf{$1}; - $conf{$1} = $2; - } - - @revisions_applied = map { /^(\d+)-(\d+)$/s or die "Invalid revision spec $_"; [$1, $2]; } split /,/, $conf{revisions_applied}; -} - -sub WriteSettings() -{ - $conf{revisions_applied} = join ',', map { "$_->[0]-$_->[1]" } @revisions_applied; - - open my $fh, '>', ".patchsets" - or die "writing settings: $!"; - for(sort keys %conf) - { - print $fh "$_ = $conf{$_}\n"; - } -} - -sub AddPatch($$) -{ - my ($first, $last) = @_; - die "Invalid range" if $first > $last; - - my @rev = sort { $a->[0] <=> $b->[0] } (@revisions_applied, [$first, $last]); - - my $i = 0; - while($i < @rev - 1) - { - my $a = $rev[$i][0]; - my $b = $rev[$i][1]; - my $c = $rev[$i+1][0]; - my $d = $rev[$i+1][1]; - - if($b >= $c) - { - die "overlapping patch: $a-$b overlaps $c-$d"; - } - if($b == $c - 1) - { - splice @rev, $i, 2, [$a, $d]; - next; - } - ++$i; - } - - @revisions_applied = @rev; -} - -sub RemovePatch($$) -{ - my ($first, $last) = @_; - die "Invalid range" if $first > $last; - - my @rev = sort { $a->[0] <=> $b->[0] } (@revisions_applied); - - my $i = 0; - while($i < @rev) - { - my $a = $rev[$i][0]; - my $b = $rev[$i][1]; - - if($first >= $a && $last <= $b) - { - # this is the range - my @replacement; - - if($first == $a && $last == $b) - { - @replacement = (); - } - elsif($first == $a) - { - @replacement = ([$last + 1, $b]); - } - elsif($last == $b) - { - @replacement = ([$a, $first - 1]); - } - else - { - @replacement = ([$a, $first - 1], [$last + 1, $b]); - } - splice @rev, $i, 1, @replacement; - @revisions_applied = @rev; - return; - } - } - - die "could not remove range: not in set"; -} - -sub GetUnappliedRanges($) -{ - my ($lastrev) = @_; - my @unapplied = (); - - my $cur = 0; - for(@revisions_applied) - { - my ($a, $b) = @$_; - if($a - 1 >= $cur + 1) - { - push @unapplied, [$cur + 1, $a - 1]; - } - $cur = $b; - } - if($lastrev >= $cur + 1) - { - push @unapplied, [$cur + 1, $lastrev]; - } - return @unapplied; -} - -sub GetMasterRev() -{ - my $svninfo = OutputOf 'svn info #1', $conf{master}; - $svninfo =~ /^Last Changed Rev: (\d+)$/m - or die "could not get svn info"; - return $1; -} - -sub GetLog($$) -{ - my ($first, $last) = @_; - my $log = OutputOf 'svn log -r#1:#2 #3', $first, $last, $conf{master}; - $log =~ s/^-*$//gm; - $log =~ s/\n+/\n/gs; - $log =~ s/^\n//s; - $log =~ s/\n$//s; - return $log; -} - -sub GetDiff($$) -{ - my ($first, $last) = @_; - return OutputOf 'svn diff -r#1:#2 #3', $first-1, $last, $conf{master}; -} - -my ($cmd, @args) = @ARGV; -$cmd = 'help' if not defined $cmd; - -if($cmd eq 'info') -{ - LoadSettings(); - for(@revisions_applied) - { - my ($a, $b) = @$_; - print "Applied: $a to $b\n"; - } - for(GetUnappliedRanges(GetMasterRev())) - { - my ($a, $b) = @$_; - print "Unapplied: $a to $b\n"; - } -} -elsif($cmd eq 'unmerged-diff') -{ - LoadSettings(); - my @autoadd = (); - for(GetUnappliedRanges(GetMasterRev())) - { - my ($a, $b) = @$_; - my $log = GetLog $a, $b; - if($log eq '') - { - push @autoadd, [$a, $b]; - next; - } - $log =~ s/^/ /gm; - print "Unapplied: $a to $b\n"; - print "$log\n"; - print GetDiff $a, $b; - print "\n"; - } - for(@autoadd) - { - my ($a, $b) = @$_; - print "Autofilled revision hole $a to $b\n"; - AddPatch $a, $b; - } - WriteSettings() if @autoadd; -} -elsif($cmd eq 'unmerged') -{ - LoadSettings(); - my @autoadd = (); - for(GetUnappliedRanges(GetMasterRev())) - { - my ($a, $b) = @$_; - my $log = GetLog $a, $b; - if($log eq '') - { - push @autoadd, [$a, $b]; - next; - } - $log =~ s/^/ /gm; - print "Unapplied: $a to $b\n"; - print "$log\n\n"; - } - for(@autoadd) - { - my ($a, $b) = @$_; - print "Autofilled revision hole $a to $b\n"; - AddPatch $a, $b; - } - WriteSettings() if @autoadd; -} -elsif($cmd eq 'merge') -{ - my ($first, $last, $force) = @args; - die "Usage: $0 merge first last [--force]" - if not defined $first; - $last = $first if not defined $last; - - die "Usage: $0 merge first last" - if "$first$last" =~ /[^0-9]/; - - die "There is an uncommitted merge" - if -f '.commitmsg' and $force ne '--force'; - - LoadSettings(); - AddPatch $first, $last; - - print OutputOf 'svn merge -r#1:#2 #3', ($first - 1), $last, $conf{master}; - print "You may also want to run $0 unmerged to fill possible revision holes\n"; - print "Make sure there are no conflicts, then run $0 commit\n"; - print "To abort, use $0 revert\n"; - - open my $fh, '>>', '.commitmsg' - or die "open .commitmsg"; - print $fh GetLog $first, $last; - print $fh "\n"; - close $fh; - - WriteSettings(); -} -elsif($cmd eq 'undo') -{ - my ($first, $last, $force) = @args; - die "Usage: $0 undo first last" - if not defined $first; - $last = $first if not defined $last; - - die "Usage: $0 merge first last" - if "$first$last" =~ /[^0-9]/; - - die "There is an uncommitted merge" - if -f '.commitmsg' and $force ne '--force'; - - LoadSettings(); - RemovePatch $first, $last; - - print OutputOf 'svn merge -r#2:#1 #3', ($first - 1), $last, $conf{master}; - print "Make sure there are no conflicts, then run $0 commit\n"; - print "To abort, use $0 revert\n"; - - open my $fh, '>>', '.commitmsg' - or die "open .commitmsg"; - print $fh "undo the following merge:\n", GetLog $first, $last; - close $fh; - - WriteSettings(); -} -elsif($cmd eq 'commit') -{ - system 'vim .commitmsg'; - print "Hit Enter if OK to commit, Ctrl-C otherwise...\n"; - my $ok = ; - if(!system 'svn commit -F .commitmsg') - { - unlink '.commitmsg'; - } -} -elsif($cmd eq 'revert') -{ - if(!system 'svn revert -R .') - { - unlink '.commitmsg'; - } -} -elsif($cmd eq 'init') -{ - my ($master, $rev) = @args; - $conf{master} = $master; - @revisions_applied = [1, $rev]; - WriteSettings(); -} -else -{ - print <texture_number); - g_free(m_tex); - m_tex = NULL; - } -} - -void CBackgroundImage::Render() -{ - if (!m_bActive || !Valid()) - return; - g_QglTable.m_pfn_qglPushAttrib(GL_ALL_ATTRIB_BITS); - - g_QglTable.m_pfn_qglEnable(GL_TEXTURE_2D); - g_QglTable.m_pfn_qglEnable(GL_BLEND); - g_QglTable.m_pfn_qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - g_QglTable.m_pfn_qglTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - g_QglTable.m_pfn_qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - g_QglTable.m_pfn_qglTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - - g_QglTable.m_pfn_qglPolygonMode(GL_FRONT,GL_FILL); - // TODO, just so we can tell if we end up going the wrong way - // g_QglTable.m_pfn_qglPolygonMode(GL_BACK,GL_LINE); - // TODO any other state we should not assume ? - - g_QglTable.m_pfn_qglBindTexture(GL_TEXTURE_2D, m_tex->texture_number); - g_QglTable.m_pfn_qglBegin(GL_QUADS); - - g_QglTable.m_pfn_qglColor4f(1.0,1.0,1.0,m_alpha); - g_QglTable.m_pfn_qglTexCoord2f(0.0,1.0); - g_QglTable.m_pfn_qglVertex2f(m_xmin,m_ymin); - - g_QglTable.m_pfn_qglTexCoord2f(1.0,1.0); - g_QglTable.m_pfn_qglVertex2f(m_xmax,m_ymin); - - g_QglTable.m_pfn_qglTexCoord2f(1.0,0.0); - g_QglTable.m_pfn_qglVertex2f(m_xmax,m_ymax); - - g_QglTable.m_pfn_qglTexCoord2f(0.0,0.0); - g_QglTable.m_pfn_qglVertex2f(m_xmin,m_ymax); - - g_QglTable.m_pfn_qglEnd(); - g_QglTable.m_pfn_qglBindTexture(GL_TEXTURE_2D, 0); - - g_QglTable.m_pfn_qglPopAttrib(); -} - -bool CBackgroundImage::Load(const char *filename) -{ - qtexture_t *newtex; - - unsigned char *image = NULL; // gets allocated with what ? g_malloc - int width = 0, height = 0; - - g_FuncTable.m_pfnLoadImage(filename,&image,&width,&height); - - if(!image) { - Syn_Printf(MSG_WARN "load %s failed\n",filename); - return false; - } - -// just in case we want to build for an old version -// http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=900 -#ifdef BKGRND2D_JPG_WORKAROUND - if ( strlen(filename) > 4 && !strcmp(".jpg",filename + strlen(filename) - 4)) { - Syn_Printf(MSG_PREFIX ".jpg workaround, clearing alpha channel\n"); - int size = width*height*4; - int i; - for (i = 3; i < size; i+=4) { - image[i] = 255; - } - } -#endif - - //TODO bug for stored texture size - //TODO whose gl context are we in, anyway ? - newtex = g_FuncTable.m_pfnLoadTextureRGBA(image,width,height); - - g_free(image); - - if(!newtex) { - Syn_Printf(MSG_WARN "image to texture failed\n"); - return false; - } - - Cleanup(); - m_tex = newtex; - - g_FuncTable.m_pfnSysUpdateWindows(W_XY); - - return true; -} - -bool CBackgroundImage::SetExtentsMM() -{ - entity_s *worldentity; - const char *val; - int xmin = 0, ymin = 0, xmax = 0, ymax = 0; - - worldentity = (entity_s *)g_FuncTable.m_pfnGetEntityHandle(0); - if(!worldentity) { - Syn_Printf(MSG_WARN "SetExtentsMM worldspawn not found\n"); - return false; - } - //TODO val is not NULL even if key does not exist - val = g_EntityTable.m_pfnValueForKey(worldentity,"mapcoordsmins"); - if(!val || !val[0]) { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmins not found\n"); - return false; - } -// we could be more robust -// note contortions due to splashs strange idea of min and max - if(sscanf(val, "%d %d",&xmin,&ymax) != 2) - { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmins malformed\n"); - return false; - } - - val = g_EntityTable.m_pfnValueForKey(worldentity,"mapcoordsmaxs"); - if(!val || !val[0]) { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmaxs not found\n"); - return false; - } - if(sscanf(val, "%d %d",&xmax,&ymin) != 2) - { - Syn_Printf(MSG_WARN "SetExtentsMM mapcoordsmaxs malformed\n"); - return false; - } - //might do sanity check before we commit - m_xmin = (float)xmin; - m_ymin = (float)ymin; - m_xmax = (float)xmax; - m_ymax = (float)ymax; - - g_FuncTable.m_pfnSysUpdateWindows(W_XY); - return true; -} - -// TODO, this should just be exported from core -// ripped directly from radiant/select.cpp:Select_GetBounds -// -static bool get_selection_bounds (vec3_t mins, vec3_t maxs) -{ - brush_t *b; - int i; - brush_t *selected_brushes = g_DataTable.m_pfnSelectedBrushes(); - //TODO should never happen - if(!selected_brushes) { - Sys_Printf (MSG_PREFIX "selected_brushes = NULL\n"); - return false; - } - // this should mean no selection - if(selected_brushes == selected_brushes->next) { - Sys_Printf (MSG_PREFIX "nothing selected\n"); - - return false; - } - - for (i=0 ; i<3 ; i++) - { - mins[i] = 99999; - maxs[i] = -99999; - } - - for (b=selected_brushes->next ; b != selected_brushes ; b=b->next) - { - if (b->owner->eclass->fixedsize) - { - for (i=0 ; i<3 ; i++) - { - if (b->owner->origin[i] < mins[i]) - mins[i] = b->owner->origin[i]; - if (b->owner->origin[i] > maxs[i]) - maxs[i] = b->owner->origin[i]; - } - } - else - { - for (i=0 ; i<3 ; i++) - { - if (b->mins[i] < mins[i]) - mins[i] = b->mins[i]; - if (b->maxs[i] > maxs[i]) - maxs[i] = b->maxs[i]; - } - } - } - return true; -} - -bool CBackgroundImage::SetExtentsSel() -{ - vec3_t mins,maxs; - - if(!get_selection_bounds(mins,maxs)) - return false; - - if(((int)mins[m_ix] == (int)maxs[m_ix]) || - ((int)mins[m_iy] == (int)maxs[m_iy])) { - Syn_Printf(MSG_PREFIX "tiny selection\n"); - return false; - } - - m_xmin = mins[m_ix]; - m_ymin = mins[m_iy]; - m_xmax = maxs[m_ix]; - m_ymax = maxs[m_iy]; - - g_FuncTable.m_pfnSysUpdateWindows(W_XY); - - return true; -} - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/bkgrnd2d.def b/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/bkgrnd2d.def deleted file mode 100644 index fa90fdb1..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/bkgrnd2d.def +++ /dev/null @@ -1,8 +0,0 @@ -; bkgrnd2d.def : Declares the module parameters for the DLL. - -LIBRARY "BKGRND2D" -DESCRIPTION 'BKGRND2D Windows Dynamic Link Library' - -EXPORTS - ; Explicit exports can go here - Synapse_EnumerateInterfaces @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/bkgrnd2d.h b/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/bkgrnd2d.h deleted file mode 100644 index 3874cb19..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/bkgrnd2d.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright (C) 2003 Reed Mideke. - -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 -*/ - -// -// bkgrnd2d Plugin -// -// Code by reyalP aka Reed Mideke -// -// Based on spritemodel source code by hydra -// - -#include "plugin.h" - -class CBackgroundImage { -private: - qtexture_t *m_tex; - VIEWTYPE m_vt; - -// which components of a vec3_t correspond to x and y in the image - unsigned m_ix,m_iy; - -public: - CBackgroundImage(VIEWTYPE vt); -// ~CBackgroundImage(); - - float m_alpha; // vertex alpha - bool m_bActive; - -// x and y axis are in relation to the screen, not world, making rendering -// the same for each view type. Whoever sets them is responsible for -// shuffling. -// units are world units. -// TODO should be private - float m_xmin,m_ymin,m_xmax,m_ymax; - -// load file, create new tex, cleanup old tex, set new tex - bool Load(const char *filename); - void Cleanup(); // free texture, free tex, set make tex NULL - bool SetExtentsMM(); // set extents by ET mapcoordsmaxs/mapcoordsmins - bool SetExtentsSel(); // set extents by selection - void Render(); - bool Valid() { return (m_tex && (m_xmin != m_xmax) && (m_ymin != m_ymax)); } -}; - -class CBackgroundRender : public IGL2DWindow { -public: - - CBackgroundRender(); - virtual ~CBackgroundRender(); - -protected: - int refCount; - -public: - - // IGL2DWindow IGL3DWindow interface - void IncRef() { refCount++; } - void DecRef() { refCount--; if (refCount <= 0) delete this; } - void Draw2D( VIEWTYPE vt ); - void Register(); -}; - -extern CBackgroundImage backgroundXY,backgroundXZ,backgroundYZ; -extern CBackgroundRender render; - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/dialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/dialog.cpp deleted file mode 100644 index 8d9a8455..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/dialog.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* -Copyright (C) 2003 Reed Mideke. - -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 -*/ - -// -// bkgrnd2d Plugin dialog -// -// Code by reyalP aka Reed Mideke -// -// Based on various other plugins -// - -#include - -#include "bkgrnd2d.h" -#include "dialog.h" - -// spaces to make label nice and big -#define NO_FILE_MSG " (no file loaded) " - -static GtkWidget *pDialogWnd; -static GtkWidget *pNotebook; -static GtkTooltips *pTooltips; - -class CBackgroundDialogPage -{ -private: - GtkWidget *m_pWidget; - GtkWidget *m_pTabLabel; - GtkWidget *m_pFileLabel; - GtkWidget *m_pPosLabel; - VIEWTYPE m_vt; - bool m_bValidFile; - -public: - CBackgroundImage *m_pImage; - CBackgroundDialogPage( VIEWTYPE vt ); - void Append(GtkWidget *notebook); - void Browse(); - void Reload(); - void SetPosLabel(); -// ~BackgroundDialogPage(); -}; - - -// dialog page callbacks -static void browse_callback( GtkWidget *widget, gpointer data ) -{ - ((CBackgroundDialogPage *)data)->Browse(); -} - -static void reload_callback( GtkWidget *widget, gpointer data ) -{ - ((CBackgroundDialogPage *)data)->Reload(); -} - -static void size_sel_callback( GtkWidget *widget, gpointer data ) -{ - CBackgroundDialogPage *pPage = (CBackgroundDialogPage *)data; - if (pPage->m_pImage->SetExtentsSel()) - pPage->SetPosLabel(); -} - -static void size_mm_callback( GtkWidget *widget, gpointer data ) -{ - CBackgroundDialogPage *pPage = (CBackgroundDialogPage *)data; - if(pPage->m_pImage->SetExtentsMM()) - pPage->SetPosLabel(); -} - -static void alpha_adjust_callback( GtkWidget *widget, gpointer data ) -{ - CBackgroundDialogPage *pPage = (CBackgroundDialogPage *)data; - pPage->m_pImage->m_alpha = (float)gtk_range_get_value (GTK_RANGE(widget)); - g_FuncTable.m_pfnSysUpdateWindows(W_XY); -} - -void CBackgroundDialogPage::Reload() -{ - if(m_bValidFile) - m_pImage->Load(gtk_label_get_text(GTK_LABEL(m_pFileLabel))); -} - -void CBackgroundDialogPage::Browse() -{ - char browsedir[PATH_MAX]; - const char *ct; - const char *newfile; - char *t; - - //TODO GetMapName saves the map. eeep! - //also with no map, returns unnamed.map, otherwise returns full path -// Syn_Printf(MSG_PREFIX "GetMapName() %s\n", -// g_FuncTable.m_pfnGetMapName()); - - ct = g_FuncTable.m_pfnReadProjectKey("basepath"); - // TODO shouldn't need this stuff - if(!ct || !strlen(ct)) { - Syn_Printf(MSG_PREFIX "basepath = NULL or empty\n"); - return; - } - Syn_Printf(MSG_PREFIX "basepath: %s\n",ct); - if(strlen(ct) >= PATH_MAX) { - Syn_Printf(MSG_PREFIX "base game dir too long\n"); - return; - } - - strcpy(browsedir,ct); - // make sure we have a trailing / - if(browsedir[strlen(browsedir) - 1] != '/') - strcat(browsedir,"/"); - - //if we dont have a file yet, don't try to use it for default dir - if(m_bValidFile) { - // filename should always be a nice clean unix style relative path - ct = gtk_label_get_text(GTK_LABEL(m_pFileLabel)); - strcat(browsedir,ct); - Syn_Printf(MSG_PREFIX "full path: %s\n",browsedir); - - // lop off the file part - t = browsedir + strlen(browsedir) - 1; - while (t != browsedir && *t != '/') - t--; - *t = 0; - } - Syn_Printf(MSG_PREFIX "browse directory %s\n",browsedir); - -//does NOT need freeing contrary to include/qerplugin.h comments -//TODO bug/patch for comments -//TODO patern gets fucked up sometimes if empty -//http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=915 - newfile = g_FuncTable.m_pfnFileDialog(pDialogWnd,TRUE, - "Load Background Image",browsedir,FILETYPE_KEY); - if(!newfile) { - Syn_Printf(MSG_PREFIX "newfile = NULL\n"); - return; - } - Syn_Printf(MSG_PREFIX "newfile: %s\n",newfile); - newfile = g_FileSystemTable.m_pfnExtractRelativePath(newfile); - - if(!newfile) { - Syn_Printf(MSG_PREFIX "newfile = NULL\n"); - return; - } - Syn_Printf(MSG_PREFIX "newfile: %s\n",newfile); - - if(m_pImage->Load(newfile)) { - m_bValidFile = true; - gtk_label_set_text(GTK_LABEL(m_pFileLabel),newfile); - } -} - -void CBackgroundDialogPage::SetPosLabel() -{ - char s[64]; - // TODO no snprintf ? - sprintf(s, "Size/Position (%d,%d) (%d,%d)",(int)(m_pImage->m_xmin), - (int)(m_pImage->m_ymin),(int)(m_pImage->m_xmax),(int)(m_pImage->m_ymax)); - gtk_label_set_text(GTK_LABEL(m_pPosLabel),s); -} - -CBackgroundDialogPage::CBackgroundDialogPage(VIEWTYPE vt ) -{ - GtkWidget *frame; - GtkWidget *hbox; - GtkWidget *w; - - m_vt = vt; - - m_bValidFile = false; - - switch(m_vt) - { - case XY: - m_pTabLabel = gtk_label_new("X/Y"); - m_pImage = &backgroundXY; - break; - case XZ: - m_pTabLabel = gtk_label_new("X/Z"); - m_pImage = &backgroundXZ; - break; - case YZ: - m_pTabLabel = gtk_label_new("Y/Z"); - m_pImage = &backgroundYZ; - break; - } -// A vbox to hold everything - m_pWidget = gtk_vbox_new(FALSE,0); -// Frame for file row - frame = gtk_frame_new("File"); - gtk_box_pack_start (GTK_BOX (m_pWidget),frame, FALSE, FALSE, 2); - -// hbox for first row - hbox = gtk_hbox_new(FALSE,5); - gtk_container_set_border_width(GTK_CONTAINER (hbox),4); - gtk_container_add (GTK_CONTAINER (frame), hbox); - -// label to display filename - m_pFileLabel = gtk_label_new(NO_FILE_MSG); - gtk_label_set_selectable(GTK_LABEL(m_pFileLabel),TRUE); -//TODO set min size ? done with spaces right now - gtk_box_pack_start (GTK_BOX (hbox),m_pFileLabel, TRUE, TRUE, 5); - - gtk_widget_show (m_pFileLabel); - - w = gtk_button_new_with_label ("Browse..."); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (browse_callback), - (gpointer)this); - gtk_box_pack_start (GTK_BOX (hbox),w, FALSE, FALSE, 5); - gtk_tooltips_set_tip (pTooltips, w, "Select a file", NULL); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Reload"); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (reload_callback), - (gpointer)this); - // TODO disable until we have file - // gtk_widget_set_sensitive(w,FALSE); - gtk_tooltips_set_tip (pTooltips, w, "Reload current file", NULL); - gtk_box_pack_start (GTK_BOX (hbox),w, FALSE, FALSE, 5); - gtk_widget_show (w); - - gtk_widget_show (hbox); - gtk_widget_show (frame); - -// second row (rendering options) - frame = gtk_frame_new("Rendering"); - gtk_box_pack_start (GTK_BOX (m_pWidget),frame, FALSE, FALSE, 2); - - hbox = gtk_hbox_new(FALSE,5); - gtk_container_set_border_width(GTK_CONTAINER (hbox),4); - gtk_container_add (GTK_CONTAINER (frame), hbox); - - w = gtk_label_new("Vertex alpha:"); - gtk_box_pack_start (GTK_BOX (hbox),w, FALSE, FALSE, 5); - gtk_widget_show (w); - - w = gtk_hscale_new_with_range(0.0,1.0,0.01); - gtk_range_set_value(GTK_RANGE(w),0.5); - gtk_scale_set_value_pos(GTK_SCALE(w),GTK_POS_LEFT); - g_signal_connect (G_OBJECT (w), "value-changed", - G_CALLBACK (alpha_adjust_callback), (gpointer)this); - gtk_box_pack_start (GTK_BOX (hbox),w, TRUE, TRUE, 5); - gtk_tooltips_set_tip (pTooltips, w, "Set image transparancy", NULL); - gtk_widget_show (w); - - gtk_widget_show (hbox); - gtk_widget_show (frame); -// Third row (size and position) - frame = gtk_frame_new("Size/Position (undefined)"); - m_pPosLabel = gtk_frame_get_label_widget (GTK_FRAME(frame)); - gtk_box_pack_start ( GTK_BOX (m_pWidget), frame, FALSE, FALSE, 2); - - hbox = gtk_hbox_new(FALSE,5); - gtk_container_add (GTK_CONTAINER (frame), hbox); - gtk_container_set_border_width(GTK_CONTAINER (hbox),4); - - w = gtk_button_new_with_label ("from selection"); - gtk_box_pack_start (GTK_BOX (hbox),w, TRUE, FALSE, 5); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (size_sel_callback), - (gpointer)this); - gtk_tooltips_set_tip (pTooltips, w, "Set the size of the image to the bounding rectangle of all selected brushes and entities", NULL); - gtk_widget_show (w); - - if(m_vt == XY) { - w = gtk_button_new_with_label ("from map mins/maxs"); - gtk_box_pack_start ( GTK_BOX (hbox),w, TRUE, FALSE, 2); - g_signal_connect (G_OBJECT (w), "clicked", G_CALLBACK (size_mm_callback), - (gpointer)this); - gtk_tooltips_set_tip (pTooltips, w, "Set the size of the image using the mapcoordsmins and mapcoordsmaxs keys of the worldspawn entity", NULL); - gtk_widget_show (w); - } - - gtk_widget_show (hbox); - gtk_widget_show (frame); - - gtk_widget_show ( m_pWidget ); -} - -void CBackgroundDialogPage::Append(GtkWidget *notebook) -{ - gtk_notebook_append_page( GTK_NOTEBOOK(notebook), m_pWidget, m_pTabLabel); -} - -// dialog global callbacks -/* -static gint expose_callback( GtkWidget *widget, gpointer data ) -{ - return FALSE; -} -*/ - -static void response_callback( GtkWidget *widget, gint response, gpointer data ) -{ - if( response == GTK_RESPONSE_CLOSE ) - gtk_widget_hide( pDialogWnd ); -} - -static gint close_callback( GtkWidget *widget, gpointer data ) -{ - gtk_widget_hide( pDialogWnd ); - return TRUE; -} - -void InitBackgroundDialog() -{ - CBackgroundDialogPage *pPage; - - pDialogWnd = gtk_dialog_new_with_buttons ("Background Images", - GTK_WINDOW(g_pMainWidget), - (GtkDialogFlags)(GTK_DIALOG_DESTROY_WITH_PARENT), - // TODO dialog with no buttons - // GTK_STOCK_CLOSE, - // GTK_RESPONSE_CLOSE, - NULL); - gtk_signal_connect( GTK_OBJECT (pDialogWnd), "delete_event", - GTK_SIGNAL_FUNC( close_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (pDialogWnd), "response", - GTK_SIGNAL_FUNC( response_callback ), NULL ); -// gtk_signal_connect( GTK_OBJECT (pDialogWnd), "expose_event", GTK_SIGNAL_FUNC( ci_expose ), NULL ); - - pTooltips = gtk_tooltips_new(); - - pNotebook = gtk_notebook_new(); - pPage = new CBackgroundDialogPage(XY); - pPage->Append(pNotebook); - pPage = new CBackgroundDialogPage(XZ); - pPage->Append(pNotebook); - pPage = new CBackgroundDialogPage(YZ); - pPage->Append(pNotebook); - - gtk_box_pack_start (GTK_BOX (GTK_DIALOG(pDialogWnd)->vbox), pNotebook, TRUE, TRUE, 0); - - gtk_widget_show ( pNotebook ); - - gtk_widget_realize( pDialogWnd ); -} - -void ShowBackgroundDialog() -{ - gtk_window_present( GTK_WINDOW(pDialogWnd) ); -} - -void ShowBackgroundDialogPG(int page) -{ - gtk_notebook_set_current_page(GTK_NOTEBOOK(pNotebook),page); - ShowBackgroundDialog(); -} - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/dialog.h b/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/dialog.h deleted file mode 100644 index 03af2078..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/dialog.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright (C) 2003 Reed Mideke. - -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 -*/ - -// -// bkgrnd2d Plugin dialog box -// -// Code by reyalP aka Reed Mideke -// -// - -#ifndef _BKGRND2D_DIALOG_H_ -#define _BKGRND2D_DIALOG_H_ - -void InitBackgroundDialog(); -void ShowBackgroundDialog(); -void ShowBackgroundDialogPG(int page); - -#endif // _BKGRND2D_DIALOG_H_ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/plugin.cpp b/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/plugin.cpp deleted file mode 100644 index a37882c5..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/plugin.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* -Copyright (C) 2003 Reed Mideke. - -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 -*/ - -// -// 2d background Plugin -// -// Code by reyalP aka Reed Mideke -// -// Based on -// - -/* - Overview - ======== - This little plugin allows you to display an image in the background of the - gtkradiant XY window. - - Version History - =============== - - v0.1 - - Initial version. - v0.2 - - three views, dialog box, toolbar - v0.25 - - tooltips, follow gtkradiant coding conventions - - Why ? - ----- - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=88 - - - How ? - ----- - - textures 'n widgets 'n stuff. -*/ - -//#include "plugin.h" -//TODO we just poke the objects directly -#include "bkgrnd2d.h" -#include "dialog.h" - -#define CMD_SEP "-" -#define CMD_CONFIG "Configure..." -#define CMD_ABOUT "About..." -// ============================================================================= -// Globals - -// function tables -_QERFuncTable_1 g_FuncTable; -_QERQglTable g_QglTable; -_QERFileSystemTable g_FileSystemTable; -_QEREntityTable g_EntityTable; -_QERAppDataTable g_DataTable; - -// for the file load dialog -void *g_pMainWidget; - -// ============================================================================= -// plugin implementation - -static const char *PLUGIN_NAME = "2d window background plugin"; - -//backwards for some reason -static const char *PLUGIN_COMMANDS = CMD_ABOUT ";" - CMD_SEP ";" - CMD_CONFIG - ; - -static const char *PLUGIN_ABOUT = "2d window background v0.25\n\n" - "By reyalP (hellsownpuppy@yahoo.com)"; - - - - -void DoBkgrndToggleXY(); -void DoBkgrndToggleXZ(); -void DoBkgrndToggleYZ(); - -#define NUM_TOOLBAR_BUTTONS 4 -struct toolbar_button_info_s -{ - const char *image; - const char *text; - const char *tip; - void (*func)(); - IToolbarButton::EType type; -}; - -struct toolbar_button_info_s toolbar_buttons[NUM_TOOLBAR_BUTTONS] = -{ - { - "bkgrnd2d_xy_toggle.bmp", - "xy background", - "Toggle xy background image", - DoBkgrndToggleXY, - IToolbarButton::eToggleButton - }, - { - "bkgrnd2d_xz_toggle.bmp", - "xz background", - "Toggle xz background image", - DoBkgrndToggleXZ, - IToolbarButton::eToggleButton - }, - { - "bkgrnd2d_yz_toggle.bmp", - "yz background", - "Toggle yz background image", - DoBkgrndToggleYZ, - IToolbarButton::eToggleButton - }, - { - "bkgrnd2d_conf.bmp", - "Configure", - "Configure background images", - ShowBackgroundDialog, - IToolbarButton::eButton - }, -}; - -class Bkgrnd2dButton : public IToolbarButton -{ -public: - const toolbar_button_info_s *bi; - virtual const char* getImage() const - { - return bi->image; - } - virtual const char* getText() const - { - return bi->text; - } - virtual const char* getTooltip() const - { - return bi->tip; - } - virtual void activate() const - { - bi->func(); - return ; - } - virtual EType getType() const - { - return bi->type; - } -}; - -Bkgrnd2dButton g_bkgrnd2dbuttons[NUM_TOOLBAR_BUTTONS]; - -unsigned int ToolbarButtonCount() -{ - return NUM_TOOLBAR_BUTTONS; -} - -const IToolbarButton* GetToolbarButton(unsigned int index) -{ - g_bkgrnd2dbuttons[index].bi = &toolbar_buttons[index]; - return &g_bkgrnd2dbuttons[index]; -} - -extern "C" const char* QERPlug_Init (void *hApp, void* pMainWidget) -{ - g_pMainWidget = pMainWidget; - - InitBackgroundDialog(); - render.Register(); - -//TODO is it right ? is it wrong ? it works -//TODO figure out supported image types - GetFileTypeRegistry()->addType(FILETYPE_KEY, filetype_t("all files", "*.*")); - GetFileTypeRegistry()->addType(FILETYPE_KEY, filetype_t("jpeg files", "*.jpg")); - GetFileTypeRegistry()->addType(FILETYPE_KEY, filetype_t("targa files", "*.tga")); - return (char *) PLUGIN_NAME; -} - -extern "C" const char* QERPlug_GetName () -{ - return (char *) PLUGIN_NAME; -} - -extern "C" const char* QERPlug_GetCommandList () -{ - return (char *) PLUGIN_COMMANDS; -} - -extern "C" void QERPlug_Dispatch (const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - Sys_Printf (MSG_PREFIX "Command \"%s\"\n",p); - if(!strcmp(p, CMD_ABOUT)) { - g_FuncTable.m_pfnMessageBox(NULL, PLUGIN_ABOUT, "About", MB_OK, NULL); - } - else if(!strcmp(p,CMD_CONFIG)) { - ShowBackgroundDialog(); - } -} - -//TODO these three suck -void DoBkgrndToggleXY() -{ - Sys_Printf (MSG_PREFIX "DoBkgrndToggleXY\n"); - // always toggle, since the buttons do - backgroundXY.m_bActive = (backgroundXY.m_bActive) ? false:true; - // if we don't have image or extents, and we activated, - // bring up the dialog with the corresponding page - // would be better to hide or grey out button, but we can't - if(backgroundXY.m_bActive && !backgroundXY.Valid()) - ShowBackgroundDialogPG(0); - else - g_FuncTable.m_pfnSysUpdateWindows(W_XY); -} - -void DoBkgrndToggleXZ() -{ - Sys_Printf (MSG_PREFIX "DoBkgrndToggleXZ\n"); - backgroundXZ.m_bActive = (backgroundXZ.m_bActive) ? false:true; - if(backgroundXZ.m_bActive && !backgroundXZ.Valid()) - ShowBackgroundDialogPG(1); - else - g_FuncTable.m_pfnSysUpdateWindows(W_XY); -} - -void DoBkgrndToggleYZ() -{ - Sys_Printf (MSG_PREFIX "DoBkgrndToggleYZ\n"); - backgroundYZ.m_bActive = (backgroundYZ.m_bActive) ? false:true; - if(backgroundYZ.m_bActive && !backgroundYZ.Valid()) - ShowBackgroundDialogPG(2); - else - g_FuncTable.m_pfnSysUpdateWindows(W_XY); -} - -// ============================================================================= -// SYNAPSE - -CSynapseServer* g_pSynapseServer = NULL; -CSynapseClientBkgrnd2d g_SynapseClient; - -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(TOOLBAR_MAJOR, BKGRND2D_MINOR, sizeof(_QERPlugToolbarTable)); - g_SynapseClient.AddAPI(PLUGIN_MAJOR, BKGRND2D_MINOR, sizeof( _QERPluginTable ) ); - - g_SynapseClient.AddAPI( RADIANT_MAJOR, NULL, sizeof( g_FuncTable ), SYN_REQUIRE, &g_FuncTable ); - g_SynapseClient.AddAPI( QGL_MAJOR, NULL, sizeof( g_QglTable ), SYN_REQUIRE, &g_QglTable ); -// TODO is this the right way to ask for 'whichever VFS we have loaded' ? Seems to work -// for misc filename functions - g_SynapseClient.AddAPI( VFS_MAJOR, "*", sizeof( g_FileSystemTable ), SYN_REQUIRE, &g_FileSystemTable ); -// get worldspawn - g_SynapseClient.AddAPI( ENTITY_MAJOR, NULL, sizeof( g_EntityTable ), SYN_REQUIRE, &g_EntityTable ); -// selected brushes - g_SynapseClient.AddAPI( DATA_MAJOR, NULL, sizeof( g_DataTable ), SYN_REQUIRE, &g_DataTable ); - - return &g_SynapseClient; -} - -bool CSynapseClientBkgrnd2d::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable* pTable= static_cast<_QERPluginTable*>(pAPI->mpTable); - - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - if (!strcmp(pAPI->major_name, TOOLBAR_MAJOR)) - { - _QERPlugToolbarTable* pTable= static_cast<_QERPlugToolbarTable*>(pAPI->mpTable); - - pTable->m_pfnToolbarButtonCount = &ToolbarButtonCount; - pTable->m_pfnGetToolbarButton = &GetToolbarButton; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; -} - -#include "version.h" - -const char* CSynapseClientBkgrnd2d::GetInfo() -{ - return "2d Background plugin built " __DATE__ " " RADIANT_VERSION; -} - -const char* CSynapseClientBkgrnd2d::GetName() -{ - return "bkgrnd2d"; -} - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/plugin.h b/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/plugin.h deleted file mode 100644 index 30b0ca7d..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/plugin.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright (C) 2003 Reed Mideke. - -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 -*/ - -// -// bkgrnd2d Plugin -// -// Code by reyalP aka Reed Mideke -// -// Based on spritemodel source code by hydra -// - -#ifndef _PLUGIN_H_ -#define _PLUGIN_H_ - -/*! -\todo need general notice about lib purpose etc. -and the external dependencies (such as GLib, STL, mathlib etc.) -*/ - -#include -// for CPtrArray for idata.h -#include "missing.h" - -#include "synapse.h" -#include "iplugin.h" -#include "itoolbar.h" -#define USE_QERTABLE_DEFINE -#include "qerplugin.h" -#include "igl.h" -#include "ifilesystem.h" -#include "ientity.h" -#include "idata.h" - -// verbose messages -#define BKGRND2D_DEBUG - -extern _QERFuncTable_1 g_FuncTable; -extern _QERQglTable g_QglTable; -extern _QERFileSystemTable g_FileSystemTable; -extern _QEREntityTable g_EntityTable; -extern _QERAppDataTable g_DataTable; -extern void *g_pMainWidget; - -extern CSynapseServer* g_pSynapseServer; - -class CSynapseClientBkgrnd2d : public CSynapseClient -{ -public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - const char* GetName(); - - CSynapseClientBkgrnd2d() { } - virtual ~CSynapseClientBkgrnd2d() { } -}; -#define MSG_PREFIX "bkgrnd2d: " -#define MSG_WARN "bkgrnd2d WARNING: " -#define BKGRND2D_MINOR "bkgrnd2d" -#define FILETYPE_KEY "bkgrnd2d" - -#endif // _PLUGIN_H_ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/readme_bkgrnd2d-b0.25.txt b/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/readme_bkgrnd2d-b0.25.txt deleted file mode 100644 index c1e401c7..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bkgrnd2d/readme_bkgrnd2d-b0.25.txt +++ /dev/null @@ -1,131 +0,0 @@ -November 25 2003 -bkgrnd2d v 0.25 beta for radiant 1.3.13 -by SCDS_reyalP (email hellsownpuppy@yahoo.com) - -WARNING: -This is an beta release. It is provided with absolutely NO WARRANTY. -If it turns your data to mush and melts your CPU, don't blame me. - -Overview: -This little plugin allows you to display an image in the the gtkradiant 2d -windows. This is useful for layout sketches, maps made from -existing plans, building geometry based on photgraphs, viewing terrain -alphamaps in relation to your terrain, and so on. - -Installation: -extract the .dll and bitmaps into your gtkradiant/plugins directory, and -restart radiant. Be sure to use directory names, to ensure the bitmaps go -in your plugins/bitmaps directory. - -Uninstallation: -Close radiant, delete the bkgrnd2d.dll from the plugins directory, and -delete the bkgrnd2*.bmp files from the plugins/bitmaps directory. - -User Interface: -- The plugin adds 4 buttons to the radiant plugin toolbar. The first 3 - toggle the display of a background image in the specified view. The fourth - brings up a configuration dialog. The configuration dialog can also be - opened from the plugins menu. - -- If an image has not been loaded, or it's display size and location have - not been set, pushing one of the toggle buttons will bring up the dialog - with the corresponding page selected. - -- The configuration dialog is non-modal, meaning that you can leave it open - while you work in radiant. If it gets lost behind another window, clicking - on the configuration button will bring it to the forground. - -Usage: -- bring up the configuration dialog. - -- Choose the "Browse..." button. This will prompt you for an image file. - The file *MUST* be inside your basegame directory (baseq3, main, etmain or - whatever your chosen game uses). The image must be in a format supported by - the game in use. For q3 based games this is truecolor .jpg, .tga and - sometimes .png. For q2 this is .wal - -- Use one of the following methods to set the size (in game units) that the - file is displayed. - 1) select 1 or more brushes or entities and choose "from selection" - This will use the total dimensions off all selected brushes and entities - to size the image. - 2) For the X/Y view only, choose 'Size to min/max keys' This will look in - the worldspawn entity for the keys mapcoordsmins and mapcoordsmaxs (also - used for ET tracemap generation and command map sizing) and use those - dimensions to size the image. - -- Use the toggle buttons to show or hide the loaded images. The buttons will - press or unpress whenever you click them, but an image will only be - displayed once you have successfully loaded a file and set its size/postion. - -- Set the opacity of the image using the slider in the configuration dialog. - -- If any of these commands do not produce the expected results, there may be - an information in the radiant console. Please include this when reporting - bugs. - - -Notes and limitations: -- This plugin is compiled for GtkRadiant 1.3.13. It may or may not work with - later versions. It will *NOT* work with version 1.3.12 and below. If you - build from source (see below) you can build it for other versions. - -- As mentioned above, the image *MUST* be inside your basegame directory, or - another directory in which radiant looks for game files. - -- To prevent the image from being distorted, you should size it to the - original images aspect ratio. mapcoordsmaxs/mapcoordsmins and command maps - should always be square. - -- If you want a specific pixel to world unit relationship, you must arrange - that yourself. - -- On load, the image is converted to a texture whose dimensions are powers - of 2. If the original image dimensions are not powers of 2, some detail will - be lost due to resampling. If it is too large to fit on a single texture, - resolution is reduced. - -- radiants gamma and mipmap options are applied to the image. - -- If the image has an alpha channel, it will be included in the blending - process. 0 is transparent, 255 is opaque. .tga images are recommended if - you want to have an alpha channel. - -- since the plugin will only use true color files, you cannot use a terrain - indexmap (aka alphamap) or heightmap directly. You can of course, save a - copy of your indexmap in a 32 bit format. - -- There is no unload command. - -- You put the plugin in a game specific plugin directory, rather than the - radiant plugin directory. - -- You cannot set the image size with sub-unit precision. - -- Only win32 binaries are included. The source is available from: - http://www.cyberonic.net/~gdevault/rfm/mapstuff/bkgrnd2d-b0.25-src.zip - If you want to use it on another platform you will need a buildable gtkradiant - source tree to build it. For any non-windows platform you will also have to - figure out the compile options. I suggest ripping those off from some other - plugin. - -TODO: -- make file selection paterns match supported filetypes -- large images without downsampling -- bitmap and pcx support for indexmaps -- automatic size from indexmapped entities -- render under the grid instead of blending -- mac/*nix support -- remember/save/restore settings -- texture options independant of radiant prefs -- clean up icky code - -Changes from 0.1 -- all 2d views supported -- new ui -- file selection patterns, default directory improved - -Changes from 0.2 -- tooltips in dialog -- various code cleanup - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/CPortals.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/CPortals.h deleted file mode 100644 index 71f399b7..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/CPortals.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -class CBspPoint { -public: - float p[3]; -}; - -class CBspPortal { -public: - CBspPortal(); - ~CBspPortal(); - - unsigned point_count; - CBspPoint *point; - bool Build(char *def, unsigned int pointCnt, bool bInverse); -}; - - -class CBspNode { -public: - CBspPortal *portal; - unsigned int portal_count; - - bool AddPortal(char* def, unsigned int pointCnt, bool bInverse); - unsigned int portal_next; - CBspNode(); - ~CBspNode(); -}; - - -#define NAME_MAX 255 - -class CPortals { -public: - - CPortals(); - ~CPortals(); - - void Load(); // use filename in fn - void Purge(); - - char fn[NAME_MAX]; - CBspNode *node; - - unsigned int node_count; -}; diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBobView.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBobView.cpp deleted file mode 100644 index aef76088..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBobView.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// BobView.cpp: implementation of the DBobView class. -// -////////////////////////////////////////////////////////////////////// - -#include "DBobView.h" -//#include "misc.h" -#include "funchandlers.h" - -#include - -#include "iglrender.h" -#include "qerplugin.h" -#include "str.h" -#include "math/matrix.h" - -#include "DEntity.h" -#include "DEPair.h" -#include "misc.h" -#include "dialogs/dialogs-gtk.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DBobView::DBobView() -{ - nPathCount = 0; - - path = NULL; - - boundingShow = BOUNDS_APEX; - - constructShaders(); - GlobalShaderCache().attachRenderable(*this); -} - -DBobView::~DBobView() -{ - GlobalShaderCache().detachRenderable(*this); - destroyShaders(); - - if(path) - delete[] path; - - g_PathView = NULL; -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// - -void DBobView::render(RenderStateFlags state) const -{ - glBegin(GL_LINE_STRIP); - - for(int i = 0; i < nPathCount; i++) - glVertex3fv(path[i]); - - glEnd(); -} - -const char* DBobView_state_line = "$bobtoolz/bobview/line"; -const char* DBobView_state_box = "$bobtoolz/bobview/box"; - -void DBobView::constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_BLEND|RENDER_LINESMOOTH; - state.m_sort = OpenGLState::eSortOpaque; - state.m_linewidth = 1; - state.m_colour[0] = 1; - state.m_colour[1] = 0; - state.m_colour[2] = 0; - state.m_colour[3] = 1; - GlobalOpenGLStateLibrary().insert(DBobView_state_line, state); - - state.m_colour[0] = 0.25f; - state.m_colour[1] = 0.75f; - state.m_colour[2] = 0.75f; - state.m_colour[3] = 1; - GlobalOpenGLStateLibrary().insert(DBobView_state_box, state); - - m_shader_line = GlobalShaderCache().capture(DBobView_state_line); - m_shader_box = GlobalShaderCache().capture(DBobView_state_box); -} - -void DBobView::destroyShaders() -{ - GlobalOpenGLStateLibrary().erase(DBobView_state_line); - GlobalOpenGLStateLibrary().erase(DBobView_state_box); - GlobalShaderCache().release(DBobView_state_line); - GlobalShaderCache().release(DBobView_state_box); -} - -Matrix4 g_transform_box1 = matrix4_translation_for_vec3(Vector3(16.0f, 16.0f, 28.0f)); -Matrix4 g_transform_box2 = matrix4_translation_for_vec3(Vector3(-16.0f, 16.0f, 28.0f)); -Matrix4 g_transform_box3 = matrix4_translation_for_vec3(Vector3(16.0f, -16.0f, -28.0f)); -Matrix4 g_transform_box4 = matrix4_translation_for_vec3(Vector3(-16.0f, -16.0f, -28.0f)); - -void DBobView::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!path) - return; - - renderer.SetState(m_shader_line, Renderer::eWireframeOnly); - renderer.SetState(m_shader_line, Renderer::eFullMaterials); - renderer.addRenderable(*this, g_matrix4_identity); - - if(m_bShowExtra) - { - renderer.SetState(m_shader_box, Renderer::eWireframeOnly); - renderer.SetState(m_shader_box, Renderer::eFullMaterials); - renderer.addRenderable(*this, g_transform_box1); - renderer.addRenderable(*this, g_transform_box2); - renderer.addRenderable(*this, g_transform_box3); - renderer.addRenderable(*this, g_transform_box4); - } -} -void DBobView::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - renderSolid(renderer, volume); -} - -void DBobView::SetPath(vec3_t *pPath) -{ - if(path) - delete[] path; - - path = pPath; -} - -#define LOCAL_GRAVITY -800.0f - -bool DBobView::CalculateTrajectory(vec3_t start, vec3_t apex, float multiplier, int points, float varGravity) -{ - if(apex[2] <= start[2]) - { - SetPath(NULL); - return false; - } - // ----think q3a actually would allow these - //scrub that, coz the plugin wont :] - - vec3_t dist, speed; - VectorSubtract(apex, start, dist); - - vec_t speed_z = (float)sqrt(-2*LOCAL_GRAVITY*dist[2]); - float flight_time = -speed_z/LOCAL_GRAVITY; - - - VectorScale(dist, 1/flight_time, speed); - speed[2] = speed_z; - -// Sys_Printf("Speed: (%.4f %.4f %.4f)\n", speed[0], speed[1], speed[2]); - - vec3_t* pPath = new vec3_t[points]; - - float interval = multiplier*flight_time/points; - for(int i = 0; i < points; i++) - { - float ltime = interval*i; - - VectorScale(speed, ltime, pPath[i]); - VectorAdd(pPath[i], start, pPath[i]); - - // could do this all with vectors - // vGrav = {0, 0, -800.0f} - // VectorScale(vGrav, 0.5f*ltime*ltime, vAdd); - // VectorScale(speed, ltime, pPath[i]); - // _VectorAdd(pPath[i], start, pPath[i]) - // _VectorAdd(pPath[i], vAdd, pPath[i]) - - pPath[i][2] = start[2] + (speed_z*ltime) + (varGravity*0.5f*ltime*ltime); - } - - SetPath(pPath); - return true; -} - -void DBobView::Begin(const char* trigger, const char *target, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra) -{ - strcpy(entTrigger, trigger); - strcpy(entTarget, target); - - fMultiplier = multiplier; - fVarGravity = varGravity; - nPathCount = points; - m_bShowExtra = bShowExtra; - - if(!UpdatePath()) - { - globalErrorStream() << "Initialization Failure in DBobView::Begin"; - delete this; - } - globalOutputStream() << "Initialization of Path Plotter succeeded."; -} - -bool DBobView::UpdatePath() -{ - vec3_t start, apex; - - if(GetEntityCentre(entTrigger, start)) - { - if(GetEntityCentre(entTarget, apex)) - { - CalculateTrajectory(start, apex, fMultiplier, nPathCount, fVarGravity); - return true; - } - } - return false; -} - -void DBobView_setEntity(Entity& entity, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra) -{ - DEntity trigger; - trigger.LoadEPairList(&entity); - - DEPair* trigger_ep = trigger.FindEPairByKey("targetname"); - - if(trigger_ep) - { - if(!strcmp(trigger.m_Classname, "trigger_push")) - { - DEPair* target_ep = trigger.FindEPairByKey("target"); - if(target_ep) - { - const scene::Path* entTarget = FindEntityFromTargetname(target_ep->value); - if(entTarget) - { - if(g_PathView) - delete g_PathView; - g_PathView = new DBobView; - - Entity* target = Node_getEntity(entTarget->top()); - if(target != 0) - { - if(!bNoUpdate) - { - g_PathView->trigger = &entity; - entity.attach(*g_PathView); - g_PathView->target = target; - target->attach(*g_PathView); - } - g_PathView->Begin(trigger_ep->value, target_ep->value, multiplier, points, varGravity, bNoUpdate, bShowExtra); - } - else - globalErrorStream() << "bobToolz PathPlotter: trigger_push ARGH\n"; - } - else - globalErrorStream() << "bobToolz PathPlotter: trigger_push target could not be found..\n"; - } - else - globalErrorStream() << "bobToolz PathPlotter: trigger_push has no target..\n"; - } - else - globalErrorStream() << "bobToolz PathPlotter: You must select a 'trigger_push' entity..\n"; - } - else - globalErrorStream() << "bobToolz PathPlotter: Entity must have a targetname.\n"; - return; -} \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBobView.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBobView.h deleted file mode 100644 index 6869e6bd..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBobView.h +++ /dev/null @@ -1,106 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DBobView.h: interface for the DBobView class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_BOBVIEW_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_BOBVIEW_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ - -#include "ientity.h" -#include "irender.h" -#include "renderable.h" -#include "mathlib.h" - -class DListener; -class Shader; - -#define BOUNDS_ALL 0 -#define BOUNDS_APEX 1 - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -class DBobView : public Renderable, public OpenGLRenderable, public Entity::Observer -{ - Shader* m_shader_line; - Shader* m_shader_box; -public: - DBobView(); - virtual ~DBobView(); - -protected: - vec3_t* path; -public: - bool m_bShowExtra; - int boundingShow; - DListener* eyes; - float fVarGravity; - float fMultiplier; - int nPathCount; - - Entity* trigger; - Entity* target; - - bool UpdatePath(); - char entTarget[256]; - char entTrigger[256]; - void Begin(const char*, const char*, float, int, float, bool, bool); - bool CalculateTrajectory(vec3_t, vec3_t, float, int, float); - - void SetPath(vec3_t* pPath); - - void render(RenderStateFlags state) const; - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; - - void constructShaders(); - void destroyShaders(); - - void valueChanged(const char* value) - { - UpdatePath(); - } - typedef MemberCaller1 ValueChangedCaller; - void insert(const char* key, EntityKeyValue& value) - { - value.attach(ValueChangedCaller(*this)); - } - void erase(const char* key, EntityKeyValue& value) - { - value.detach(ValueChangedCaller(*this)); - } - void clear() - { - if(trigger != 0) - { - trigger->detach(*this); - target->detach(*this); - trigger = 0; - target = 0; - } - } -}; - -class Entity; -void DBobView_setEntity(Entity& entity, float multiplier, int points, float varGravity, bool bNoUpdate, bool bShowExtra); - -#endif // !defined(AFX_BOBVIEW_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBrush.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBrush.cpp deleted file mode 100644 index 96c884d2..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBrush.cpp +++ /dev/null @@ -1,861 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DBrush.cpp: implementation of the DBrush class. -// -////////////////////////////////////////////////////////////////////// - -#include "DBrush.h" - -#ifdef WIN32 -#pragma warning(disable : 4786) -#endif - -#include -#include "str.h" - -#include "DPoint.h" -#include "DPlane.h" -#include "DEPair.h" -#include "DPatch.h" -#include "DEntity.h" -#include "DWinding.h" - -#include "dialogs/dialogs-gtk.h" - -#include "misc.h" - -#include "iundo.h" - -#include "generic/referencecounted.h" - -#include "scenelib.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DBrush::DBrush(int ID) -{ - m_nBrushID = ID; - bBoundsBuilt = false; - QER_entity = NULL; - QER_brush = NULL; -} - -DBrush::~DBrush() -{ - ClearFaces(); - ClearPoints(); -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// - -DPlane* DBrush::AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData) -{ -#ifdef _DEBUG -// Sys_Printf("(%f %f %f) (%f %f %f) (%f %f %f)\n", va[0], va[1], va[2], vb[0], vb[1], vb[2], vc[0], vc[1], vc[2]); -#endif - bBoundsBuilt = false; - DPlane* newFace = new DPlane(va, vb, vc, texData); - faceList.push_back(newFace); - - return newFace; -} - -int DBrush::BuildPoints() -{ - ClearPoints(); - - if(faceList.size() <= 3) // if less than 3 faces, there can be no points - return 0; // with only 3 faces u can't have a bounded soild - - for(std::list::const_iterator p1=faceList.begin(); p1!=faceList.end(); p1++) - { - std::list::const_iterator p2=p1; - for(p2++; p2!=faceList.end(); p2++) - { - std::list::const_iterator p3=p2; - for(p3++; p3!=faceList.end(); p3++) - { - vec3_t pnt; - if((*p1)->PlaneIntersection(*p2, *p3, pnt)) - { - int pos = PointPosition(pnt); - - if(pos == POINT_IN_BRUSH) - { // ???? shouldn't happen here - globalErrorStream() << "ERROR:: Build Brush Points: Point IN brush!!!\n"; - } - else if(pos == POINT_ON_BRUSH) - { // normal point - if(!HasPoint(pnt)) - AddPoint(pnt); -/* else - Sys_Printf("Duplicate Point Found, pyramids ahoy!!!!!\n");*/ - // point lies on more that 3 planes - } - - // otherwise point is removed due to another plane.. - - // Sys_Printf("(%f, %f, %f)\n", pnt[0], pnt[1], pnt[2]); - } - } - } - } - -#ifdef _DEBUG -// Sys_Printf("%i points on brush\n", pointList.size()); -#endif - - return static_cast(pointList.size()); -} - -void DBrush_addFace(DBrush& brush, const _QERFaceData& faceData) -{ - brush.AddFace(vector3_to_array(faceData.m_p0), vector3_to_array(faceData.m_p1), vector3_to_array(faceData.m_p2), 0); -} -typedef ReferenceCaller1 DBrushAddFaceCaller; - -void DBrush_addFaceTextured(DBrush& brush, const _QERFaceData& faceData) -{ - brush.AddFace(vector3_to_array(faceData.m_p0), vector3_to_array(faceData.m_p1), vector3_to_array(faceData.m_p2), &faceData); -} -typedef ReferenceCaller1 DBrushAddFaceTexturedCaller; - -void DBrush::LoadFromBrush(scene::Instance& brush, bool textured) -{ - ClearFaces(); - ClearPoints(); - - GlobalBrushCreator().Brush_forEachFace(brush.path().top(), textured ? BrushFaceDataCallback(DBrushAddFaceTexturedCaller(*this)) : BrushFaceDataCallback(DBrushAddFaceCaller(*this))); - - QER_entity = brush.path().parent().get_pointer(); - QER_brush = brush.path().top().get_pointer(); -} - -int DBrush::PointPosition(vec3_t pnt) -{ - int state = POINT_IN_BRUSH; // if nothing happens point is inside brush - - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) - { - float dist = (*chkPlane)->DistanceToPoint(pnt); - - if(dist > MAX_ROUND_ERROR) - return POINT_OUT_BRUSH; // if point is in front of plane, it CANT be in the brush - else if(fabs(dist) < MAX_ROUND_ERROR) - state = POINT_ON_BRUSH; // if point is ON plane point is either ON the brush - // or outside it, it can no longer be in it - } - - return state; -} - -void DBrush::ClearPoints() -{ - for(std::list::const_iterator deadPoint=pointList.begin(); deadPoint!=pointList.end(); deadPoint++) { - delete *deadPoint; - } - pointList.clear(); -} - -void DBrush::ClearFaces() -{ - bBoundsBuilt = false; - for(std::list::const_iterator deadPlane=faceList.begin(); deadPlane!=faceList.end(); deadPlane++) - { - delete *deadPlane; - } - faceList.clear(); -} - -void DBrush::AddPoint(vec3_t pnt) -{ - DPoint* newPoint = new DPoint; - VectorCopy(pnt, newPoint->_pnt); - pointList.push_back(newPoint); -} - -bool DBrush::HasPoint(vec3_t pnt) -{ - for(std::list::const_iterator chkPoint=pointList.begin(); chkPoint!=pointList.end(); chkPoint++) - { - if(**chkPoint == pnt) - return true; - } - - return false; -} - -int DBrush::RemoveRedundantPlanes() -{ - int cnt = 0; - std::list::iterator chkPlane; - - // find duplicate planes - std::list::iterator p1=faceList.begin(); - - while( p1!=faceList.end() ) - { - std::list::iterator p2 = p1; - - for(p2++; p2!=faceList.end(); p2++) - { - if(**p1 == **p2) - { - if(!strcmp((*p1)->m_shader.c_str(), "textures/common/caulk")) - { - delete *p1; - p1 = faceList.erase(p1); // duplicate plane - } - else - { - delete *p2; - p2 = faceList.erase(p2); // duplicate plane - } - - cnt++; - break; - } - } - - if( p2 == faceList.end() ) - p1++; - } - - //+djbob kill planes with bad normal, they are more of a nuisance than losing a brush - chkPlane=faceList.begin(); - while( chkPlane!=faceList.end() ) - { - if(VectorLength((*chkPlane)->normal) == 0) // plane has bad normal - { - delete *chkPlane; - chkPlane = faceList.erase(chkPlane); - cnt++; - } else { - chkPlane++; - } - } - //-djbob - - if(pointList.size() == 0) // if points may not have been built, build them -/* if(BuildPoints() == 0) // just let the planes die if they are all bad - return cnt;*/ - BuildPoints(); - - chkPlane=faceList.begin(); - while(chkPlane != faceList.end()) - { - if((*chkPlane)->IsRedundant(pointList)) // checks that plane "0wnz" :), 3 or more points - { - delete *chkPlane; - chkPlane = faceList.erase(chkPlane); - cnt++; - } - else - chkPlane++; - } - - return cnt; -} - -bool DBrush::GetBounds(vec3_t min, vec3_t max) -{ - BuildBounds(); - - if(!bBoundsBuilt) - return false; - - VectorCopy(bbox_min, min); - VectorCopy(bbox_max, max); - - return true; -} - -bool DBrush::BBoxCollision(DBrush* chkBrush) -{ - vec3_t min1, min2; - vec3_t max1, max2; - - GetBounds(min1, max1); - chkBrush->GetBounds(min2, max2); - - if(min1[0] >= max2[0]) - return false; - if(min1[1] >= max2[1]) - return false; - if(min1[2] >= max2[2]) - return false; - - if(max1[0] <= min2[0]) - return false; - if(max1[1] <= min2[1]) - return false; - if(max1[2] <= min2[2]) - return false; - - return true; -} - -DPlane* DBrush::HasPlane(DPlane* chkPlane) -{ - for(std::list::const_iterator brushPlane=faceList.begin(); brushPlane!=faceList.end(); brushPlane++) - { - if(**brushPlane == *chkPlane) - return *brushPlane; - } - return NULL; -} - -bool DBrush::IsCutByPlane(DPlane *cuttingPlane) -{ - bool isInFront; - - if(pointList.size() == 0) - if(BuildPoints() == 0) - return false; - - std::list::const_iterator chkPnt = pointList.begin(); - - if(chkPnt == pointList.end()) - return false; - - float dist = cuttingPlane->DistanceToPoint((*chkPnt)->_pnt); - - if(dist > MAX_ROUND_ERROR) - isInFront = false; - else if(dist < MAX_ROUND_ERROR) - isInFront = true; - else - return true; - - for(chkPnt++=pointList.begin(); chkPnt!=pointList.end(); chkPnt++) - { - dist = cuttingPlane->DistanceToPoint((*chkPnt)->_pnt); - - if(dist > MAX_ROUND_ERROR) - { - if(isInFront) - return true; - } - else if(dist < MAX_ROUND_ERROR) - { - if(!isInFront) - return true; - } - else - return true; - } - - return false; -} - - -scene::Node* DBrush::BuildInRadiant(bool allowDestruction, int* changeCnt, scene::Node* entity) -{ - if(allowDestruction) - { - bool kill = true; - - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) - { - if((*chkPlane)->m_bChkOk) - { - kill = false; - break; - } - } - if(kill) - return NULL; - } - - //+djbob: fixed bug when brush had no faces "phantom brush" in radiant. - if(faceList.size() < 4) - { - globalErrorStream() << "Possible Phantom Brush Found, will not rebuild\n"; - return NULL; - } - //-djbob - - NodeSmartReference node(GlobalBrushCreator().createBrush()); - - for(std::list::const_iterator buildPlane=faceList.begin(); buildPlane!=faceList.end(); buildPlane++) { - if((*buildPlane)->AddToBrush(node) && changeCnt) { - (*changeCnt)++; - } - } - - if(entity) { - Node_getTraversable(*entity)->insert(node); - } else { - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(node); - } - - QER_entity = entity; - QER_brush = node.get_pointer(); - - return node.get_pointer(); -} - -void DBrush::CutByPlane(DPlane *cutPlane, DBrush **newBrush1, DBrush **newBrush2) -{ - if(!IsCutByPlane(cutPlane)) - { - *newBrush1 = NULL; - *newBrush2 = NULL; - return; - } - - DBrush* b1 = new DBrush; - DBrush* b2 = new DBrush; - - for(std::list::const_iterator parsePlane=faceList.begin(); parsePlane!=faceList.end(); parsePlane++) - { - b1->AddFace((*parsePlane)->points[0], (*parsePlane)->points[1], (*parsePlane)->points[2], NULL); - b2->AddFace((*parsePlane)->points[0], (*parsePlane)->points[1], (*parsePlane)->points[2], NULL); - } - - b1->AddFace(cutPlane->points[0], cutPlane->points[1], cutPlane->points[2], NULL); - b2->AddFace(cutPlane->points[2], cutPlane->points[1], cutPlane->points[0], NULL); - - b1->RemoveRedundantPlanes(); - b2->RemoveRedundantPlanes(); - - *newBrush1 = b1; - *newBrush2 = b2; -} - -bool DBrush::IntersectsWith(DBrush *chkBrush) -{ - if(pointList.size() == 0) - if(BuildPoints() == 0) - return false; // invalid brush!!!! - - if(chkBrush->pointList.size() == 0) - if(chkBrush->BuildPoints() == 0) - return false; // invalid brush!!!! - - if(!BBoxCollision(chkBrush)) - return false; - - std::list::const_iterator iplPlane; - - for( iplPlane=faceList.begin(); iplPlane!=faceList.end(); iplPlane++) - { - - bool allInFront = true; - for(std::list::const_iterator iPoint=chkBrush->pointList.begin(); iPoint!=chkBrush->pointList.end(); iPoint++) - { - if((*iplPlane)->DistanceToPoint((*iPoint)->_pnt) < -MAX_ROUND_ERROR) - { - allInFront = false; - break; - } - } - if(allInFront) - return false; - } - - for( iplPlane=chkBrush->faceList.begin(); iplPlane!=chkBrush->faceList.end(); iplPlane++) - { - bool allInFront = true; - for(std::list::const_iterator iPoint=pointList.begin(); iPoint!=pointList.end(); iPoint++) - { - if((*iplPlane)->DistanceToPoint((*iPoint)->_pnt) < -MAX_ROUND_ERROR) - { - allInFront = false; - break; - } - } - if(allInFront) - return false; - } - - return true; -} - -bool DBrush::IntersectsWith(DPlane* p1, DPlane* p2, vec3_t v) { - vec3_t vDown = { 0, 0, -1 }; - - std::list::const_iterator iplPlane; - for( iplPlane = faceList.begin(); iplPlane != faceList.end(); iplPlane++) { - DPlane* p = (*iplPlane); - - vec_t d = DotProduct( p->normal, vDown ); - if( d >= 0 ) { - continue; - } - if(p->PlaneIntersection(p1, p2, v)) { - if(PointPosition( v ) != POINT_OUT_BRUSH) { - return true; - } - } - } - - return false; -} - -void DBrush::BuildBounds() -{ - if(!bBoundsBuilt) - { - if(pointList.size() == 0) // if points may not have been built, build them - if(BuildPoints() == 0) - return; - - std::list::const_iterator first = pointList.begin(); - VectorCopy((*first)->_pnt, bbox_min); - VectorCopy((*first)->_pnt, bbox_max); - - std::list::const_iterator point=pointList.begin(); - for( point++; point!=pointList.end(); point++) - { - if((*point)->_pnt[0] > bbox_max[0]) - bbox_max[0] = (*point)->_pnt[0]; - if((*point)->_pnt[1] > bbox_max[1]) - bbox_max[1] = (*point)->_pnt[1]; - if((*point)->_pnt[2] > bbox_max[2]) - bbox_max[2] = (*point)->_pnt[2]; - - if((*point)->_pnt[0] < bbox_min[0]) - bbox_min[0] = (*point)->_pnt[0]; - if((*point)->_pnt[1] < bbox_min[1]) - bbox_min[1] = (*point)->_pnt[1]; - if((*point)->_pnt[2] < bbox_min[2]) - bbox_min[2] = (*point)->_pnt[2]; - } - - bBoundsBuilt = true; - } -} - -bool DBrush::BBoxTouch(DBrush *chkBrush) -{ - vec3_t min1, min2; - vec3_t max1, max2; - - GetBounds(min1, max1); - chkBrush->GetBounds(min2, max2); - - if((min1[0] - max2[0]) > MAX_ROUND_ERROR) - return false; - if((min1[1] - max2[1]) > MAX_ROUND_ERROR) - return false; - if((min1[2] - max2[2]) > MAX_ROUND_ERROR) - return false; - - if((min2[0] - max1[0]) > MAX_ROUND_ERROR) - return false; - if((min2[1] - max1[1]) > MAX_ROUND_ERROR) - return false; - if((min2[2] - max1[2]) > MAX_ROUND_ERROR) - return false; - - int cnt = 0; - - if((min2[0] - max1[0]) == 0) - cnt++; - - if((min2[1] - max1[1]) == 0) - cnt++; - - if((min2[2] - max1[2]) == 0) - cnt++; - - if((min1[0] - max2[0]) == 0) - cnt++; - - if((min1[1] - max2[1]) == 0) - cnt++; - - if((min1[2] - max2[2]) == 0) - cnt++; - - if(cnt > 1) - return false; - - return true; -} - -void DBrush::ResetChecks(std::list* exclusionList) -{ - for(std::list::const_iterator resetPlane=faceList.begin(); resetPlane!=faceList.end(); resetPlane++) - { - bool set = false; - - if(exclusionList) - { - for(std::list::iterator eTexture = exclusionList->begin(); eTexture != exclusionList->end(); eTexture++) - { - if(strstr((*resetPlane)->m_shader.c_str(), eTexture->GetBuffer())) - { - set = true; - break; - } - } - } - - (*resetPlane)->m_bChkOk = set; - } -} - -DPlane* DBrush::HasPlaneInverted(DPlane *chkPlane) -{ - for(std::list::const_iterator brushPlane=faceList.begin(); brushPlane!=faceList.end(); brushPlane++) - { - if(**brushPlane != *chkPlane) - { - if(fabs((*brushPlane)->_d + chkPlane->_d) < 0.1) - return (*brushPlane); - } - } - return NULL; -} - -bool DBrush::HasTexture(const char *textureName) -{ - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) - { - if(strstr((*chkPlane)->m_shader.c_str(), textureName)) - return true; - - } - return false; -} - -bool DBrush::IsDetail() -{ - for(std::list::const_iterator chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) - { - if((*chkPlane)->texInfo.contents & FACE_DETAIL) - return true; - - } - return false; -} - -void DBrush::BuildFromWinding(DWinding *w) -{ - if(w->numpoints < 3) - { - globalErrorStream() << "Winding has invalid number of points"; - return; - } - - DPlane* wPlane = w->WindingPlane(); - - DWinding* w2; - w2 = w->CopyWinding(); - int i; - for(i = 0; i < w2->numpoints; i++) - VectorAdd(w2->p[i], wPlane->normal, w2->p[i]); - - AddFace(w2->p[0], w2->p[1], w2->p[2], NULL); - AddFace(w->p[2], w->p[1], w->p[0], NULL); - - for(i = 0; i < w->numpoints-1; i++) - AddFace(w2->p[i], w->p[i], w->p[i+1], NULL); - AddFace(w2->p[w->numpoints-1], w->p[w->numpoints-1], w->p[0], NULL); - - delete wPlane; - delete w2; -} - -void DBrush::SaveToFile(FILE *pFile) -{ - fprintf(pFile, "{\n"); - - for(std::list::const_iterator pp=faceList.begin(); pp!=faceList.end(); pp++) - { - char buffer[512]; - - sprintf(buffer, "( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) ( %.0f %.0f %.0f ) %s %.0f %.0f %f %f %.0f 0 0 0\n", - (*pp)->points[0][0], (*pp)->points[0][1], (*pp)->points[0][2], - (*pp)->points[1][0], (*pp)->points[1][1], (*pp)->points[1][2], - (*pp)->points[2][0], (*pp)->points[2][1], (*pp)->points[2][2], - (*pp)->m_shader.c_str(), - (*pp)->texInfo.m_texdef.shift[0], (*pp)->texInfo.m_texdef.shift[1], - (*pp)->texInfo.m_texdef.scale[0], (*pp)->texInfo.m_texdef.scale[0], - (*pp)->texInfo.m_texdef.rotate); - - fprintf(pFile, buffer); - } - - fprintf(pFile, "}\n"); -} - -void DBrush::Rotate(vec3_t vOrigin, vec3_t vRotation) -{ - for(std::list::const_iterator rotPlane=faceList.begin(); rotPlane!=faceList.end(); rotPlane++) - { - for(int i = 0; i < 3; i++) - VectorRotate((*rotPlane)->points[i], vRotation, vOrigin); - - (*rotPlane)->Rebuild(); - } -} - -void DBrush::RotateAboutCentre(vec3_t vRotation) -{ - vec3_t min, max, centre; - GetBounds(min, max); - VectorAdd(min, max, centre); - VectorScale(centre, 0.5f, centre); - - Rotate(centre, vRotation); -} - -bool DBrush::ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation) -{ - if(textureName) - { - bool changed = false; - for(std::list::const_iterator resetPlane=faceList.begin(); resetPlane!=faceList.end(); resetPlane++) - { - if(!strcmp((*resetPlane)->m_shader.c_str(), textureName)) - { - if(bResetTextureName) - (*resetPlane)->m_shader = newTextureName; - - if(bResetScale[0]) - (*resetPlane)->texInfo.m_texdef.scale[0] = fScale[0]; - if(bResetScale[1]) - (*resetPlane)->texInfo.m_texdef.scale[1] = fScale[1]; - - if(bResetShift[0]) - (*resetPlane)->texInfo.m_texdef.shift[0] = fShift[0]; - if(bResetShift[1]) - (*resetPlane)->texInfo.m_texdef.shift[1] = fShift[1]; - - if(bResetRotation) - (*resetPlane)->texInfo.m_texdef.rotate = (float)rotation; - - changed = true; - } - } - return changed; // no point rebuilding unless we need to, only slows things down - } - else - { - for(std::list::const_iterator resetPlane=faceList.begin(); resetPlane!=faceList.end(); resetPlane++) - { - if(bResetTextureName) - (*resetPlane)->m_shader = newTextureName; - - if(bResetScale[0]) - (*resetPlane)->texInfo.m_texdef.scale[0] = fScale[0]; - if(bResetScale[1]) - (*resetPlane)->texInfo.m_texdef.scale[1] = fScale[1]; - - if(bResetShift[0]) - (*resetPlane)->texInfo.m_texdef.shift[0] = fShift[0]; - if(bResetShift[1]) - (*resetPlane)->texInfo.m_texdef.shift[1] = fShift[1]; - - if(bResetRotation) - (*resetPlane)->texInfo.m_texdef.rotate = (float)rotation; - } - return true; - } -} - -bool DBrush::operator ==(DBrush* other) -{ - std::list::const_iterator chkPlane; - - for(chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) - { - if(!other->HasPlane((*chkPlane))) - return false; - } - - for(chkPlane=faceList.begin(); chkPlane!=faceList.end(); chkPlane++) - { - if(!HasPlane((*chkPlane))) - return false; - } - - return true; -} - -DPlane* DBrush::AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const char *textureName, bool bDetail) -{ - bBoundsBuilt = false; - DPlane* newFace = new DPlane(va, vb, vc, textureName, bDetail); - faceList.push_back(newFace); - - return newFace; -} - -DPlane* DBrush::FindPlaneWithClosestNormal( vec_t* normal ) { - vec_t bestDot = -2; - DPlane* bestDotPlane = NULL; - std::list::const_iterator chkPlane; - for( chkPlane = faceList.begin(); chkPlane != faceList.end(); chkPlane++ ) { - DPlane* pPlane = (*chkPlane); - - vec_t dot = DotProduct( pPlane->normal, normal ); - if( dot > bestDot ) { - bestDot = dot; - bestDotPlane = pPlane; - } - } - - return bestDotPlane; -} - -int DBrush::FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ) { - int numpnts = 0; - - if(!maxpnts) { - return 0; - } - - BuildPoints(); - - for( std::list::const_iterator points = pointList.begin(); points != pointList.end(); points++ ) { - DPoint* point = (*points); - - if( fabs(plane->DistanceToPoint( point->_pnt )) < MAX_ROUND_ERROR ) { - pnts[numpnts] = point; - numpnts++; - - if(numpnts >= maxpnts) { - return numpnts; - } - - } - } - - return numpnts; -} - -void DBrush::RemovePlane( DPlane* plane ) { - bBoundsBuilt = false; - for( std::list::const_iterator deadPlane = faceList.begin(); deadPlane != faceList.end(); deadPlane++ ) { - if(*deadPlane == plane) { - delete *deadPlane; - faceList.remove( plane ); - } - } -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBrush.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBrush.h deleted file mode 100644 index 112f2294..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DBrush.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DBrush.h: interface for the DBrush class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DBRUSH_H__35B2C522_F0A7_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_DBRUSH_H__35B2C522_F0A7_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include -#include -#include "mathlib.h" -#include "str.h" - -class DPlane; -class DWinding; -class DPoint; -class _QERFaceData; - -namespace scene -{ - class Node; - class Instance; -} - -#define POINT_IN_BRUSH 0 -#define POINT_ON_BRUSH 1 -#define POINT_OUT_BRUSH 2 - -class DBrush -{ -public: - DPlane* AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail); - void SaveToFile(FILE* pFile); - - void Rotate(vec3_t vOrigin, vec3_t vRotation); - void RotateAboutCentre(vec3_t vRotation); - - DPlane* HasPlaneInverted(DPlane* chkPlane); - DPlane* HasPlane(DPlane* chkPlane); - DPlane* AddFace(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData); - - bool ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation); - bool IsDetail(); - bool HasTexture(const char* textureName); - bool IntersectsWith(DBrush *chkBrush); - bool IntersectsWith(DPlane* p1, DPlane* p2, vec3_t v); - bool IsCutByPlane(DPlane* cuttingPlane); - bool GetBounds(vec3_t min, vec3_t max); - bool HasPoint(vec3_t pnt); - bool BBoxCollision(DBrush* chkBrush); - bool BBoxTouch(DBrush* chkBrush); - - int BuildPoints(); - void BuildBounds(); - void BuildFromWinding(DWinding* w); - scene::Node* BuildInRadiant(bool allowDestruction, int* changeCnt, scene::Node* entity = NULL); - - void ResetChecks(std::list* exclusionList); - - void ClearFaces(); - void ClearPoints(); - - int RemoveRedundantPlanes( void ); - void RemovePlane( DPlane* plane ); - int PointPosition(vec3_t pnt); - - - void CutByPlane(DPlane* cutPlane, DBrush** newBrush1, DBrush** newBrush2); - - void LoadFromBrush(scene::Instance& brush, bool textured); - void AddPoint(vec3_t pnt); - - DPlane* FindPlaneWithClosestNormal( vec_t* normal ); - int FindPointsForPlane( DPlane* plane, DPoint** pnts, int maxpnts ); - - DBrush(int ID = -1); - virtual ~DBrush(); - - bool operator== (DBrush* other); - -// members - scene::Node* QER_entity; - scene::Node* QER_brush; - std::list faceList; - std::list pointList; - int m_nBrushID; - vec3_t bbox_min, bbox_max; - bool bBoundsBuilt; -}; - -//typedef CList DBrushList; - -#endif // !defined(AFX_DBRUSH_H__35B2C522_F0A7_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEPair.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEPair.cpp deleted file mode 100644 index 72dda4b3..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEPair.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DEPair.cpp: implementation of the DEPair class. -// -////////////////////////////////////////////////////////////////////// - -#include "DEPair.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DEPair::DEPair() -{ - -} - -DEPair::~DEPair() -{ - -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// - -void DEPair::Build(const char *pKey, const char *pValue) -{ - key = pKey; - value = pValue; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEPair.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEPair.h deleted file mode 100644 index fac4c334..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEPair.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DEPair.h: interface for the DEPair class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DEPAIR_H__35B2C521_F0A7_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_DEPAIR_H__35B2C521_F0A7_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "str.h" - -class DEPair -{ -public: - DEPair(); - virtual ~DEPair(); - - void Build(const char* pKey, const char* pValue); - - Str key; - Str value; -}; - -//typedef CList DEPairList; - -#endif // !defined(AFX_DEPAIR_H__35B2C521_F0A7_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEntity.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEntity.cpp deleted file mode 100644 index f03b489e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEntity.cpp +++ /dev/null @@ -1,716 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DEntity.cpp: implementation of the DEntity class. -// -////////////////////////////////////////////////////////////////////// - -#include "DEntity.h" - -#ifdef WIN32 -#pragma warning(disable : 4786) -#endif - -#include -#include "str.h" - -#include "DPoint.h" -#include "DPlane.h" -#include "DBrush.h" -#include "DEPair.h" -#include "DPatch.h" - -#include "dialogs/dialogs-gtk.h" -#include "misc.h" -#include "CPortals.h" - -#include "iundo.h" -#include "ientity.h" -#include "ieclass.h" - -#include "generic/referencecounted.h" - -#include -#include -#include -#include - -#include "scenelib.h" - - -const char* brushEntityList[] = { - "worldspawn", - "trigger_always", - "trigger_hurt", - "trigger_multiple", - "trigger_push", - "trigger_teleport", - "func_bobbing", - "func_button", - "func_door", - "func_group", - "func_pendulum", - "func_plat", - "func_rotating", - "func_static", - "func_timer", - "func_train", - 0 -}; - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DEntity::DEntity(const char *classname, int ID) -{ - SetClassname(classname); - m_nID = ID; - QER_Entity = NULL; -} - -DEntity::~DEntity() -{ - ClearPatches(); - ClearBrushes(); - ClearEPairs(); -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// - -void DEntity::ClearBrushes() -{ - for(std::list::const_iterator deadBrush=brushList.begin(); deadBrush!=brushList.end(); deadBrush++) - { - delete *deadBrush; - } - brushList.clear(); -} - -void DEntity::ClearPatches() -{ - for(std::list::const_iterator deadPatch=patchList.begin(); deadPatch!=patchList.end(); deadPatch++) - { - delete *deadPatch; - } - patchList.clear(); -} - -DPatch* DEntity::NewPatch() -{ - DPatch* newPatch = new DPatch; - - patchList.push_back(newPatch); - - return newPatch; -} - -DBrush* DEntity::NewBrush(int ID) -{ - DBrush* newBrush = new DBrush(ID); - - brushList.push_back(newBrush); - - return newBrush; -} - -char* getNextBracket(char* s) -{ - char* p = s; - while(*p) - { - p++; - if(*p == '(') - break; - } - - return p; -} - -bool DEntity::LoadFromPrt(char *filename) -{ - CPortals portals; - strcpy(portals.fn, filename); - portals.Load(); - - if(portals.node_count == 0) - return false; - - ClearBrushes(); - ClearEPairs(); - - bool build = false; - for(unsigned int i = 0; i < portals.node_count; i++) - { - build = false; - DBrush* brush = NewBrush(); - - for(unsigned int j = 0; j < portals.node[i].portal_count; j++) - { - for(unsigned int k = 0; k < portals.node[i].portal[j].point_count-2; k++) - { - vec3_t v1, v2, normal, n; - VectorSubtract(portals.node[i].portal[j].point[k+2].p, portals.node[i].portal[j].point[k+1].p, v1); - VectorSubtract(portals.node[i].portal[j].point[k].p, portals.node[i].portal[j].point[k+1].p, v2); - CrossProduct(v1, v2, n); - VectorNormalize(n, v2); - - if(k == 0) - { - VectorCopy(v2, normal); - } - else - { - VectorSubtract(v2, normal, v1); - if(VectorLength(v1) > 0.01) - { - build = true; - break; - } - } - } - - if(!build) - brush->AddFace(portals.node[i].portal[j].point[2].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[0].p, "textures/common/caulk", false); - else - brush->AddFace(portals.node[i].portal[j].point[0].p, portals.node[i].portal[j].point[1].p, portals.node[i].portal[j].point[2].p, "textures/common/caulk", false); - } - if(build) - brush->BuildInRadiant(false, NULL); - } - - return true; -} - -DPlane* DEntity::AddFaceToBrush(vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID) -{ - DBrush* buildBrush = GetBrushForID(ID); - return buildBrush->AddFace(va, vb, vc, faceData); - // slow, dont use much -} - -DBrush* DEntity::GetBrushForID(int ID) -{ - DBrush* buildBrush = NULL; - - for(std::list::const_iterator chkBrush=brushList.begin(); chkBrush!=brushList.end(); chkBrush++) - { - if((*chkBrush)->m_nBrushID == ID) - { - buildBrush = (*chkBrush); - break; - } - } - - if(!buildBrush) - buildBrush = NewBrush(ID); - - return buildBrush; -} - -template -class BrushSelectedVisitor : public SelectionSystem::Visitor -{ - const Functor& m_functor; -public: - BrushSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - if(Node_isBrush(instance.path().top())) - { - m_functor(instance); - } - } -}; - -template -inline const Functor& Scene_forEachSelectedBrush(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(BrushSelectedVisitor(functor)); - return functor; -} - -void DEntity_loadBrush(DEntity& entity, scene::Instance& brush) -{ - DBrush* loadBrush = entity.NewBrush(static_cast(entity.brushList.size())); - loadBrush->LoadFromBrush(brush, true); -} -typedef ReferenceCaller1 DEntityLoadBrushCaller; - -void DEntity::LoadSelectedBrushes() -{ - ClearBrushes(); - ClearEPairs(); - - Scene_forEachSelectedBrush(DEntityLoadBrushCaller(*this)); -} - -template -class PatchSelectedVisitor : public SelectionSystem::Visitor -{ - const Functor& m_functor; -public: - PatchSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - if(Node_isPatch(instance.path().top())) - { - m_functor(instance); - } - } -}; - -template -inline const Functor& Scene_forEachSelectedPatch(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(PatchSelectedVisitor(functor)); - return functor; -} - -void DEntity_loadPatch(DEntity& entity, scene::Instance& patch) -{ - DPatch* loadPatch = entity.NewPatch(); - loadPatch->LoadFromPatch(patch); -} -typedef ReferenceCaller1 DEntityLoadPatchCaller; - -void DEntity::LoadSelectedPatches() -{ - ClearPatches(); - ClearEPairs(); - - Scene_forEachSelectedPatch(DEntityLoadPatchCaller(*this)); -} - -bool* DEntity::BuildIntersectList() -{ - int max = GetIDMax(); - if(max == 0) - return NULL; - - bool* pbIntList = new bool[max]; - memset(pbIntList, 0, sizeof(bool)*(max)); - - for(std::list::const_iterator pB1=brushList.begin(); pB1!=brushList.end(); pB1++) - { - std::list::const_iterator pB2=pB1; - for(pB2++; pB2!=brushList.end(); pB2++) - { - if((*pB1)->IntersectsWith((*pB2))) - { - pbIntList[(*pB1)->m_nBrushID] = true; - pbIntList[(*pB2)->m_nBrushID] = true; - } - } - } - - return pbIntList; -} - -bool* DEntity::BuildDuplicateList() -{ - int max = GetIDMax(); - if(max == 0) - return NULL; - - bool* pbDupList = new bool[max]; - memset(pbDupList, 0, sizeof(bool)*(max)); - - for(std::list::const_iterator pB1=brushList.begin(); pB1!=brushList.end(); pB1++) - { - std::list::const_iterator pB2=pB1; - for(pB2++; pB2!=brushList.end(); pB2++) - { - if(**pB1 == *pB2) - { - pbDupList[(*pB1)->m_nBrushID] = true; - pbDupList[(*pB2)->m_nBrushID] = true; - } - } - } - - return pbDupList; -} - -void DEntity::SelectBrushes(bool *selectList) -{ - if(selectList == NULL) - return; - - GlobalSelectionSystem().setSelectedAll(false); - - scene::Path path(NodeReference(GlobalSceneGraph().root())); - path.push(NodeReference(*QER_Entity)); - - for(std::list::const_iterator pBrush=brushList.begin(); pBrush!=brushList.end(); pBrush++) - { - if(selectList[(*pBrush)->m_nBrushID]) - { - path.push(NodeReference(*(*pBrush)->QER_brush)); - Instance_getSelectable(*GlobalSceneGraph().find(path))->setSelected(true); - path.pop(); - } - } -} - -bool DEntity::LoadFromEntity(scene::Node& ent, bool bLoadPatches) { - ClearPatches(); - ClearBrushes(); - ClearEPairs(); - - QER_Entity = &ent; - - LoadEPairList(Node_getEntity(ent)); - - bool keep = false; - int i; - for(i = 0; brushEntityList[i]; i++) - { - if(string_equal_nocase(brushEntityList[i], m_Classname)) - { - keep = true; - break; - } - } - - if(!keep) - return false; - - if(Node_getTraversable(ent)) - { - class load_brushes_t : public scene::Traversable::Walker - { - DEntity* m_entity; - mutable int m_count; - public: - load_brushes_t(DEntity* entity) - : m_entity(entity), m_count(0) - { - } - bool pre(scene::Node& node) const - { - scene::Path path(NodeReference(GlobalSceneGraph().root())); - path.push(NodeReference(*m_entity->QER_Entity)); - path.push(NodeReference(node)); - scene::Instance* instance = GlobalSceneGraph().find(path); - ASSERT_MESSAGE(instance != 0, ""); - - if(Node_isPatch(node)) - { - DPatch* loadPatch = m_entity->NewPatch(); - loadPatch->LoadFromPatch(*instance); - } - else if(Node_isBrush(node)) - { - DBrush* loadBrush = m_entity->NewBrush(m_count++); - loadBrush->LoadFromBrush(*instance, true); - } - return false; - } - } load_brushes(this); - - Node_getTraversable(ent)->traverse(load_brushes); - } - - return true; -} - -void DEntity::RemoveNonCheckBrushes(std::list* exclusionList, bool useDetail) -{ - std::list::iterator chkBrush=brushList.begin(); - - while( chkBrush!=brushList.end() ) - { - if(!useDetail) - { - if((*chkBrush)->IsDetail()) - { - delete *chkBrush; - chkBrush = brushList.erase(chkBrush); - continue; - } - } - - std::list::iterator eTexture; - - for( eTexture=exclusionList->begin(); eTexture!=exclusionList->end(); eTexture++ ) - { - if((*chkBrush)->HasTexture((*eTexture).GetBuffer())) - { - delete *chkBrush; - chkBrush = brushList.erase(chkBrush); - break; - } - } - - if( eTexture == exclusionList->end() ) - chkBrush++; - } -} - -void DEntity::ResetChecks(std::list* exclusionList) -{ - for(std::list::const_iterator resetBrush=brushList.begin(); resetBrush!=brushList.end(); resetBrush++) - { - (*resetBrush)->ResetChecks(exclusionList); - } -} - -int DEntity::FixBrushes() -{ - int count = 0; - - for(std::list::const_iterator fixBrush=brushList.begin(); fixBrush!=brushList.end(); fixBrush++) - { - count += (*fixBrush)->RemoveRedundantPlanes(); - } - - return count; -} - -void DEntity::BuildInRadiant(bool allowDestruction) -{ - bool makeEntity = strcmp(m_Classname, "worldspawn") ? true : false; - - if(makeEntity) - { - NodeSmartReference node(GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert(m_Classname.GetBuffer(), !brushList.empty() || !patchList.empty()))); - - for(std::list::const_iterator buildEPair=epairList.begin(); buildEPair!=epairList.end(); buildEPair++) - { - Node_getEntity(node)->setKeyValue((*buildEPair)->key, (*buildEPair)->value); - } - - Node_getTraversable(GlobalSceneGraph().root())->insert(node); - - for(std::list::const_iterator buildBrush=brushList.begin(); buildBrush!=brushList.end(); buildBrush++) - (*buildBrush)->BuildInRadiant(allowDestruction, NULL, node.get_pointer()); - - for(std::list::const_iterator buildPatch=patchList.begin(); buildPatch!=patchList.end(); buildPatch++) - (*buildPatch)->BuildInRadiant(node.get_pointer()); - - QER_Entity = node.get_pointer(); - } - else - { - for(std::list::const_iterator buildBrush=brushList.begin(); buildBrush!=brushList.end(); buildBrush++) - (*buildBrush)->BuildInRadiant(allowDestruction, NULL); - - for(std::list::const_iterator buildPatch=patchList.begin(); buildPatch!=patchList.end(); buildPatch++) - (*buildPatch)->BuildInRadiant(); - } -} - - - -int DEntity::GetIDMax( void ) { - int max = -1; - for(std::list::const_iterator cntBrush=brushList.begin(); cntBrush!=brushList.end(); cntBrush++) { - if((*cntBrush)->m_nBrushID > max) - max = (*cntBrush)->m_nBrushID; - } - return max+1; -} - -void DEntity::SetClassname( const char *classname ) { - m_Classname = classname; -} - -void DEntity::SaveToFile(FILE *pFile) -{ - fprintf(pFile, "{\n"); - - fprintf(pFile, "\"classname\" \"%s\"\n", (const char *)m_Classname); - - for(std::list::const_iterator ep=epairList.begin(); ep!=epairList.end(); ep++) - { - fprintf(pFile, "\"%s\" \"%s\"\n", (const char *)(*ep)->key, (const char *)(*ep)->value); - } - - for(std::list::const_iterator bp=brushList.begin(); bp!=brushList.end(); bp++) - { - (*bp)->SaveToFile(pFile); - } - - fprintf(pFile, "}\n"); -} - -void DEntity::ClearEPairs() -{ - for(std::list::const_iterator deadEPair=epairList.begin(); deadEPair!=epairList.end(); deadEPair++) - { - delete (*deadEPair); - } - epairList.clear(); -} - -void DEntity::AddEPair(const char *key, const char *value) { - DEPair* newEPair; - newEPair = FindEPairByKey( key ); - if(!newEPair) { - newEPair = new DEPair; - newEPair->Build(key, value); - epairList.push_back(newEPair); - } else { - newEPair->Build(key, value); - } -} - -void DEntity::LoadEPairList(Entity *epl) -{ - class load_epairs_t : public Entity::Visitor - { - DEntity* m_entity; - public: - load_epairs_t(DEntity* entity) - : m_entity(entity) - { - } - void visit(const char* key, const char* value) - { - if(strcmp(key, "classname") == 0) - m_entity->SetClassname(value); - else - m_entity->AddEPair(key, value); - } - - } load_epairs(this); - - epl->forEachKeyValue(load_epairs); -} - -bool DEntity::ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild) -{ - bool reset = false; - - for(std::list::const_iterator resetBrush=brushList.begin(); resetBrush!=brushList.end(); resetBrush++) - { - bool tmp = (*resetBrush)->ResetTextures(textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation); - - if(tmp) - { - reset = true; - if(rebuild) - { - Node_getTraversable(*(*resetBrush)->QER_entity)->erase(*(*resetBrush)->QER_brush); - (*resetBrush)->BuildInRadiant(false, NULL, (*resetBrush)->QER_entity); - } - } - } - - if(bResetTextureName) - { - for(std::list::const_iterator resetPatch=patchList.begin(); resetPatch!=patchList.end(); resetPatch++) - { - bool tmp = (*resetPatch)->ResetTextures(textureName, newTextureName); - - if(tmp) - { - reset = true; - if(rebuild) - { - Node_getTraversable(*(*resetPatch)->QER_entity)->erase(*(*resetPatch)->QER_brush); - (*resetPatch)->BuildInRadiant((*resetPatch)->QER_entity); - } - } - } - } - - return reset; -} - -DEPair* DEntity::FindEPairByKey(const char* keyname) -{ - for(std::list::const_iterator ep=epairList.begin(); ep!=epairList.end(); ep++) - { - char* c = (*ep)->key; - if(!strcmp(c, keyname)) - return *ep; - } - return NULL; -} - -void DEntity::RemoveFromRadiant() -{ - Node_getTraversable(GlobalSceneGraph().root())->erase(*QER_Entity); - - QER_Entity = NULL; -} - -void DEntity::SpawnString(const char* key, const char* defaultstring, const char** out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { - *out = pEP->value; - } else { - *out = defaultstring; - } -} - -void DEntity::SpawnInt(const char* key, const char* defaultstring, int* out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { - *out = atoi(pEP->value); - } else { - *out = atoi(defaultstring); - } -} - -void DEntity::SpawnFloat(const char* key, const char* defaultstring, float* out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { - *out = static_cast(atof(pEP->value)); - } else { - *out = static_cast(atof(defaultstring)); - } -} - -void DEntity::SpawnVector(const char* key, const char* defaultstring, vec_t* out) -{ - DEPair* pEP = FindEPairByKey(key); - if(pEP) { - sscanf(pEP->value, "%f %f %f", &out[0], &out[1], &out[2]); - } else { - sscanf(defaultstring, "%f %f %f", &out[0], &out[1], &out[2]); - } -} - -int DEntity::GetBrushCount( void ) { - return static_cast(brushList.size()); -} - -DBrush* DEntity::FindBrushByPointer( scene::Node& brush ) { - for(std::list::const_iterator listBrush = brushList.begin(); listBrush != brushList.end(); listBrush++) { - DBrush* pBrush = (*listBrush); - if(pBrush->QER_brush == &brush) { - return pBrush; - } - } - return NULL; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEntity.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEntity.h deleted file mode 100644 index 5baa3d3d..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DEntity.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DEntity.h: interface for the DEntity class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include -#include "str.h" -#include "mathlib.h" - -class DEPair; -class DBrush; -class DPlane; -class DPatch; -class Entity; - -namespace scene -{ - class Node; -} -class _QERFaceData; - -class DEntity -{ -public: - void RemoveFromRadiant(); - scene::Node* QER_Entity; - int m_nID; - -// Constrcution/Destruction - DEntity(const char* classname = "worldspawn", int ID = -1); // sets classname - virtual ~DEntity(); -// --------------------------------------------- - -// epair functions........ - void LoadEPairList(Entity* epl); - void AddEPair(const char* key, const char* value); - void ClearEPairs(); - DEPair* FindEPairByKey(const char* keyname); -// --------------------------------------------- - -// random functions........ - bool ResetTextures(const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation, bool rebuild); - void SaveToFile(FILE* pFile); - void SetClassname(const char* classname); - int GetIDMax(); - - void BuildInRadiant(bool allowDestruction); - void ResetChecks(std::list* exclusionList); - void RemoveNonCheckBrushes(std::list* exclusionList, bool useDetail); - - DPlane* AddFaceToBrush(vec3_t va, vec3_t vb, vec3_t vc, _QERFaceData* faceData, int ID); // slow, try not to use much - int GetBrushCount( void ); - DBrush* FindBrushByPointer( scene::Node& brush ); -// --------------------------------------------- - - -// bool list functions - void SelectBrushes(bool* selectList); - bool* BuildDuplicateList(); - bool* BuildIntersectList(); -// --------------------------------------------- - - -// brush operations - void ClearBrushes(); // clears brush list and frees memory for brushes - - DBrush* GetBrushForID(int ID); - DBrush* NewBrush(int ID = -1); -// --------------------------------------------- - -// patch operations - void ClearPatches(); - - DPatch* NewPatch(); -// --------------------------------------------- - -// vars - std::list epairList; - std::list brushList; - // new patches, wahey!!! - std::list patchList; - Str m_Classname; -// --------------------------------------------- - - - int FixBrushes(); - - bool LoadFromEntity(scene::Node& ent, bool bLoadPatches = false); - void LoadSelectedBrushes(); - void LoadSelectedPatches(); - - bool LoadFromPrt(char* filename); -// --------------------------------------------- - void SpawnString(const char* key, const char* defaultstring, const char** out); - void SpawnInt(const char* key, const char* defaultstring, int* out); - void SpawnFloat(const char* key, const char* defaultstring, float* out); - void SpawnVector(const char* key, const char* defaultstring, vec_t* out); -}; - -#endif // !defined(AFX_DENTITY_H__35B2C523_F0A7_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DMap.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DMap.cpp deleted file mode 100644 index 18e43188..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DMap.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DMap.cpp: implementation of the DMap class. -// -////////////////////////////////////////////////////////////////////// - -#include "DMap.h" - -#include "str.h" -#include - -#include "DPoint.h" -#include "DPlane.h" -#include "DBrush.h" -#include "DEPair.h" -#include "DPatch.h" -#include "DEntity.h" - -#include "iundo.h" - -#include "generic/referencecounted.h" - -#include -#include -#include -#include - -#include "scenelib.h" - - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DMap::DMap() -{ - m_nNextEntity = 1; - AddEntity("worldspawn", 0); -} - -DMap::~DMap() -{ - ClearEntities(); -} - -DEntity* DMap::AddEntity(char *classname, int ID) -{ - DEntity* newEntity; - if(ID == -1) - newEntity = new DEntity(classname, m_nNextEntity++); - else - newEntity = new DEntity(classname, ID); - - entityList.push_back(newEntity); - - return newEntity; -} - -void DMap::ClearEntities() -{ - m_nNextEntity = 1; - - for(std::list::const_iterator deadEntity=entityList.begin(); deadEntity!=entityList.end(); deadEntity++) - delete *deadEntity; - - entityList.clear(); -} - -DEntity* DMap::GetEntityForID(int ID) -{ - DEntity* findEntity = NULL; - - for(std::list::const_iterator chkEntity=entityList.begin(); chkEntity!=entityList.end(); chkEntity++) - { - if((*chkEntity)->m_nID == ID) - { - findEntity = (*chkEntity); - break; - } - } - - if(!findEntity) - findEntity = AddEntity("worldspawn", ID); - - return findEntity; -} - - -DEntity* DMap::GetWorldSpawn() -{ - return GetEntityForID(0); -} - -void DMap::BuildInRadiant(bool bAllowDestruction) -{ - for(std::list::const_iterator buildEntity=entityList.begin(); buildEntity!=entityList.end(); buildEntity++) - (*buildEntity)->BuildInRadiant(bAllowDestruction); -} - -void DMap::LoadAll(bool bLoadPatches) -{ - ClearEntities(); - - GlobalSelectionSystem().setSelectedAll(false); - - class load_entities_t : public scene::Traversable::Walker - { - DMap* m_map; - bool m_bLoadPatches; - public: - load_entities_t(DMap* map, bool bLoadPatches) - : m_map(map), m_bLoadPatches(bLoadPatches) - { - } - bool pre(scene::Node& node) const - { - if(Node_isEntity(node)) - { - DEntity* loadEntity = m_map->AddEntity("", 0); - loadEntity->LoadFromEntity(node, m_bLoadPatches); - } - return false; - } - } load_entities(this, bLoadPatches); - - Node_getTraversable(GlobalSceneGraph().root())->traverse(load_entities); -} - -int DMap::FixBrushes() -{ - int count = 0; - for(std::list::const_iterator fixEntity=entityList.begin(); fixEntity!=entityList.end(); fixEntity++) - { - count += (*fixEntity)->FixBrushes(); - } - - return count; -} - -void DMap::ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, - int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation) -{ - for(std::list::const_iterator texEntity=entityList.begin(); texEntity!=entityList.end(); texEntity++) - { - if(string_equal_nocase("worldspawn", (*texEntity)->m_Classname)) - (*texEntity)->ResetTextures(textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation, true); - else - { - if((*texEntity)->ResetTextures( textureName, fScale, fShift, rotation, newTextureName, - bResetTextureName, bResetScale, bResetShift, bResetRotation, false)) - RebuildEntity(*texEntity); - } - } -} - -void DMap::RebuildEntity(DEntity *ent) -{ - ent->RemoveFromRadiant(); - ent->BuildInRadiant(false); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DMap.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DMap.h deleted file mode 100644 index 018dbc0f..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DMap.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DMap.h: interface for the DMap class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_) -#define AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include - -class DEntity; - -class DMap -{ -public: - static void RebuildEntity(DEntity* ent); - - void ResetTextures( const char* textureName, float fScale[2], float fShift[2], int rotation, const char* newTextureName, int bResetTextureName, int bResetScale[2], int bResetShift[2], int bResetRotation); - void LoadAll(bool bLoadPatches = false); - void BuildInRadiant(bool bAllowDestruction); - int m_nNextEntity; - DEntity* GetWorldSpawn(); - void ClearEntities(); - - DEntity* GetEntityForID(int ID); - DEntity* AddEntity(char* classname = "worldspawn", int ID = -1); - - std::list entityList; - - DMap(); - virtual ~DMap(); - - int FixBrushes(); -}; - -#endif // !defined(AFX_DMAP_H__ACAE597A_D26D_49AD_AA69_EDE743DB54FA__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPatch.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPatch.cpp deleted file mode 100644 index 10dbb4bb..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPatch.cpp +++ /dev/null @@ -1,573 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DPatch.cpp: implementation of the DPatch class. -// -////////////////////////////////////////////////////////////////////// - -#include "DPatch.h" - -#include -#include "str.h" -#include "scenelib.h" - -#include "ipatch.h" - -#include "misc.h" -#include "./dialogs/dialogs-gtk.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -// Added patch merging, wahey! - -// -// problem is, you cant put patches into entities as yet :( -// - -DPatch::DPatch() -{ - width = MIN_PATCH_WIDTH; - height = MIN_PATCH_HEIGHT; - QER_entity = NULL; - QER_brush = NULL; -} - -DPatch::~DPatch() -{ - -} - -void DPatch::SetTexture(const char *textureName) -{ - strcpy(texture, textureName); -} - -void CopyDrawVert(const drawVert_t* in, drawVert_t* out) -{ - out->lightmap[0] = in->lightmap[0]; - out->lightmap[1] = in->lightmap[1]; - out->st[0] = in->st[0]; - out->st[1] = in->st[1]; - VectorCopy(in->normal, out->normal); - VectorCopy(in->xyz, out->xyz); -} - -void DPatch::BuildInRadiant(scene::Node* entity) -{ - NodeSmartReference patch(GlobalPatchCreator().createPatch()); - - scene::Node& parent = entity != 0 ? *entity : GlobalRadiant().getMapWorldEntity(); - Node_getTraversable(parent)->insert(patch); - - GlobalPatchCreator().Patch_setShader(patch, texture); - GlobalPatchCreator().Patch_resize(patch, height, width); - PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints(patch); - for(int x = 0; x < height; x++) - { - for(int y = 0; y < width; y++) - { - PatchControl& p = matrix(y, x); - p.m_vertex[0] = points[x][y].xyz[0]; - p.m_vertex[1] = points[x][y].xyz[1]; - p.m_vertex[2] = points[x][y].xyz[2]; - p.m_texcoord[0] = points[x][y].st[0]; - p.m_texcoord[1] = points[x][y].st[1]; - } - } - GlobalPatchCreator().Patch_controlPointsChanged(patch); - - QER_entity = entity; - QER_brush = patch.get_pointer(); - - -#if 0 - int nIndex = g_FuncTable.m_pfnCreatePatchHandle(); - //$ FIXME: m_pfnGetPatchHandle - patchMesh_t* pm = g_FuncTable.m_pfnGetPatchData(nIndex); - - b->patchBrush = true; - b->pPatch = Patch_Alloc(); - b->pPatch->setDims(width,height); - - for(int x = 0; x < width; x++) - for(int y = 0; y < height; y++) - CopyDrawVert(&points[x][y], &pm->ctrl[x][y]); - -/* if(entity) - { -// strcpy(pm->d_texture->name, texture); - - brush_t* brush = (brush_t*)g_FuncTable.m_pfnCreateBrushHandle(); - brush->patchBrush = true; - brush->pPatch = pm; - - pm->pSymbiot = brush; - pm->bSelected = false; - pm->bOverlay = false; // bleh, f*cks up, just have to wait for a proper function - pm->bDirty = true; // or get my own patch out.... - pm->nListID = -1; - - g_FuncTable.m_pfnCommitBrushHandleToEntity(brush, entity); - } - else*/ // patch to entity just plain dont work atm - - if(entity) - g_FuncTable.m_pfnCommitPatchHandleToEntity(nIndex, pm, texture, entity); - else - g_FuncTable.m_pfnCommitPatchHandleToMap(nIndex, pm, texture); - - QER_brush = pm->pSymbiot; -#endif -} - -void DPatch::LoadFromPatch(scene::Instance& patch) -{ - QER_entity = patch.path().parent().get_pointer(); - QER_brush = patch.path().top().get_pointer(); - - PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints(patch.path().top()); - - width = static_cast(matrix.x()); - height = static_cast(matrix.y()); - - for(int x = 0; x < height; x++) - { - for(int y = 0; y < width; y++) - { - PatchControl& p = matrix(y, x); - points[x][y].xyz[0] = p.m_vertex[0]; - points[x][y].xyz[1] = p.m_vertex[1]; - points[x][y].xyz[2] = p.m_vertex[2]; - points[x][y].st[0] = p.m_texcoord[0]; - points[x][y].st[1] = p.m_texcoord[1]; - } - } - SetTexture(GlobalPatchCreator().Patch_getShader(patch.path().top())); - -#if 0 - SetTexture(brush->pPatch->GetShader()); - - width = brush->pPatch->getWidth(); - height = brush->pPatch->getHeight(); - - for(int x = 0; x < height; x++) - { - for(int y = 0; y < width; y++) - { - float *p = brush->pPatch->ctrlAt(ROW,x,y); - p[0] = points[x][y].xyz[0]; - p[1] = points[x][y].xyz[1]; - p[2] = points[x][y].xyz[2]; - p[3] = points[x][y].st[0]; - p[4] = points[x][y].st[1]; - } - } -#endif -} - -bool DPatch::ResetTextures(const char *oldTextureName, const char *newTextureName) -{ - if( !oldTextureName || !strcmp(texture, oldTextureName)) - { - strcpy(texture, newTextureName); - return true; - } - - return false; -} - -void Build1dArray(vec3_t* array, drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT], - int startX, int startY, int number, bool horizontal, bool inverse) -{ - int x = startX, y = startY, i, step; - - if(inverse) - step = -1; - else - step = 1; - - for(i = 0; i < number; i++) - { - VectorCopy(points[x][y].xyz, array[i]); - - if(horizontal) - x+=step; - else - y+=step; - } -} - -void Print1dArray(vec3_t* array, int size) -{ - for(int i = 0; i < size; i++) - globalOutputStream() << "(" << array[i][0] << " " << array[i][1] << " " << array[i][2] << ")\t"; - globalOutputStream() << "\n"; -} - -bool Compare1dArrays(vec3_t* a1, vec3_t* a2, int size) -{ - int i; - bool equal = true; - - for(i = 0; i < size; i++) - { - if(!VectorCompare(a1[i], a2[size-i-1])) - { - equal = false; - break; - } - } - return equal; -} - -patch_merge_t DPatch::IsMergable(DPatch *other) -{ - int i, j; - vec3_t p1Array[4][MAX_PATCH_HEIGHT]; - vec3_t p2Array[4][MAX_PATCH_HEIGHT]; - - int p1ArraySizes[4]; - int p2ArraySizes[4]; - - patch_merge_t merge_info; - - Build1dArray(p1Array[0], this->points, 0, 0, this->width, true, false); - Build1dArray(p1Array[1], this->points, this->width-1, 0, this->height, false, false); - Build1dArray(p1Array[2], this->points, this->width-1, this->height-1, this->width, true, true); - Build1dArray(p1Array[3], this->points, 0, this->height-1, this->height, false, true); - - Build1dArray(p2Array[0], other->points, 0, 0, other->width, true, false); - Build1dArray(p2Array[1], other->points, other->width-1, 0, other->height, false, false); - Build1dArray(p2Array[2], other->points, other->width-1, other->height-1, other->width, true, true); - Build1dArray(p2Array[3], other->points, 0, other->height-1, other->height, false, true); - - p1ArraySizes[0] = this->width; - p1ArraySizes[1] = this->height; - p1ArraySizes[2] = this->width; - p1ArraySizes[3] = this->height; - - p2ArraySizes[0] = other->width; - p2ArraySizes[1] = other->height; - p2ArraySizes[2] = other->width; - p2ArraySizes[3] = other->height; - - for(i = 0; i < 4; i++) - { - for(j = 0; j < 4; j++) - { - if(p1ArraySizes[i] == p2ArraySizes[j]) - { - if(Compare1dArrays(p1Array[i], p2Array[j], p1ArraySizes[i])) - { - merge_info.pos1 = i; - merge_info.pos2 = j; - merge_info.mergable = true; - return merge_info; - } - } - } - } - - merge_info.mergable = false; - return merge_info; -} - -DPatch* DPatch::MergePatches(patch_merge_t merge_info, DPatch *p1, DPatch *p2) -{ - while(merge_info.pos1 != 2) - { - p1->Transpose(); - merge_info.pos1--; - if(merge_info.pos1 < 0) - merge_info.pos1 += 4; - } - - while(merge_info.pos2 != 0) - { - p2->Transpose(); - merge_info.pos2--; - if(merge_info.pos2 < 0) - merge_info.pos2 += 3; - } - // - - int newHeight = p1->height + p2->height - 1; - if(newHeight > MAX_PATCH_HEIGHT) - return false; -/* int newWidth = p1->width + p2->width - 1; - if(newWidth > MAX_PATCH_WIDTH) - return NULL; -*/ - DPatch* newPatch = new DPatch(); - //switched.. - newPatch->height = newHeight; - newPatch->width = p1->width; - newPatch->SetTexture(p1->texture); - - for(int y = 0; y < p1->height; y++) - for(int x = 0; x < p1->width; x++) - newPatch->points[x][y] = p1->points[x][y]; - - for(int y = 1; y < p2->height; y++) - for(int x = 0; x < p2->width; x++) - newPatch->points[x][(y + p1->height - 1)] = p2->points[x][y]; - -// newPatch->Invert(); - return newPatch; -} - -void DPatch::Invert() -{ - int i, j; - - for(i = 0 ; i < width ; i++ ) - { - for(j = 0; j < height / 2; j++) - { - std::swap(points[i][height - 1- j], points[i][j]); - } - } -} - -void DPatch::Transpose() -{ - int i, j, w; - - if ( width > height ) - { - for ( i = 0 ; i < height ; i++ ) - { - for ( j = i + 1 ; j < width ; j++ ) - { - if ( j < height ) - { - // swap the value - std::swap(points[j][i], points[i][j]); - } - else - { - // just copy - points[i][j] = points[j][i]; - } - } - } - } - else - { - for ( i = 0 ; i < width ; i++ ) - { - for ( j = i + 1 ; j < height ; j++ ) - { - if ( j < width ) - { - // swap the value - std::swap(points[i][j], points[j][i]); - } - else - { - // just copy - points[j][i] = points[i][j]; - } - } - } - } - - w = width; - width = height; - height = w; - - Invert(); -} - -std::list DPatch::SplitRows() -{ - std::list patchList; - int i; - int x, y; - - if(height >= 5) - { - for(i = 0; i < (height-1)/2; i++) - { - DPatch p; - - p.width = width; - p.height = 3; - p.SetTexture(texture); - for(x = 0; x < 3; x++) - { - for(y = 0; y < p.width; y++) - { - p.points[x][y] = points[(i*2)+x][y]; - } - } - patchList.push_back(p); - } - } else { - //This returns exactly what comes in.. I don't know better :/ - //If nothing is returned, the Patch in Radiant is just deleted - I suppose for evil follow up erros. - DPatch p; - - p.height = height; - p.width = width; - p.SetTexture(texture); - - for(x = 0; x < p.height; x++) - { - for(y = 0; y < p.width; y++) - { - p.points[x][y] = points[x][y]; - } - } - patchList.push_back(p); - } - return patchList; -} - -std::list DPatch::SplitCols() -{ - std::list patchList; - int i; - int x, y; - - if(width >= 5) - { - for(i = 0; i < (width-1)/2; i++) - { - DPatch p; - - p.width = 3; - p.height = height; - p.SetTexture(texture); - - for(x = 0; x < p.height; x++) - { - for(y = 0; y < 3; y++) - { - p.points[x][y] = points[x][(i*2)+y]; - } - } - patchList.push_back(p); - } - } else - { - //This returns exactly what comes in.. I don't know better :/ - //If nothing is returned, the Patch in Radiant is just deleted - I suppose for evil follow up erros. - DPatch p; - - p.height = height; - p.width = width; - p.SetTexture(texture); - - for(x = 0; x < p.height; x++) - { - for(y = 0; y < p.width; y++) - { - p.points[x][y] = points[x][y]; - } - } - patchList.push_back(p); - } - return patchList; -} - -std::list DPatch::Split() -{ - std::list patchList; - int i; - int x, y; - - if(width >= 5) - { - for(i = 0; i < (width-1)/2; i++) - { - DPatch p; - - p.width = 3; - p.height = height; - p.SetTexture(texture); - - for(x = 0; x < p.height; x++) - { - for(y = 0; y < 3; y++) - { - p.points[x][y] = points[x][(i*2)+y]; - } - } - patchList.push_back(p); - } - std::list patchList2; - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) - { - std::list patchList3 = (*patches).SplitRows(); - for(std::list::iterator patches2 = patchList3.begin(); patches2 != patchList3.end(); patches2++) - patchList2.push_front(*patches2); - } - return patchList2; - - } else if(height >= 5) - { - for(i = 0; i < (height-1)/2; i++) - { - DPatch p; - - p.width = width; - p.height = 3; - p.SetTexture(texture); - for(x = 0; x < 3; x++) - { - for(y = 0; y < p.width; y++) - { - p.points[x][y] = points[(i*2)+x][y]; - } - } - patchList.push_back(p); - } - std::list patchList2; - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) - { - std::list patchList3 = (*patches).SplitCols(); - for(std::list::iterator patches2 = patchList3.begin(); patches2 != patchList3.end(); patches2++) - patchList2.push_front(*patches2); - } - return patchList2; - - } else - { - //This returns exactly what comes in.. I don't know better :/ - //If nothing is returned, the Patch in Radiant is just deleted - I suppose for evil follow up erros. - DPatch p; - - p.height = height; - p.width = width; - p.SetTexture(texture); - - for(x = 0; x < p.height; x++) - { - for(y = 0; y < p.width; y++) - { - p.points[x][y] = points[x][y]; - } - } - patchList.push_back(p); - } - return patchList; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPatch.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPatch.h deleted file mode 100644 index 5a956f92..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPatch.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DPatch.h: interface for the DPatch class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DPATCH_H__26C6B083_CE5B_420B_836B_1DDA733C04CE__INCLUDED_) -#define AFX_DPATCH_H__26C6B083_CE5B_420B_836B_1DDA733C04CE__INCLUDED_ - -#include - -typedef struct -{ - bool mergable; - int pos1; - int pos2; -} patch_merge_t; - -typedef struct { - float xyz[3]; - float st[2]; - float normal[3]; - float lightmap[2]; -} drawVert_t; - -namespace scene -{ - class Node; - class Instance; -} - -#define MAX_PATCH_WIDTH 32 -#define MAX_PATCH_HEIGHT 32 -#define MIN_PATCH_WIDTH 3 -#define MIN_PATCH_HEIGHT 3 - -class DPatch -{ -public: - std::list SplitRows(); - std::list SplitCols(); - std::list Split(); - void Transpose(); - void Invert(); - DPatch* MergePatches(patch_merge_t merge_info, DPatch* p1, DPatch* p2); - patch_merge_t IsMergable(DPatch* other); - bool ResetTextures(const char *oldTextureName, const char *newTextureName); - scene::Node* QER_entity; - scene::Node* QER_brush; - void LoadFromPatch(scene::Instance& patch); - void BuildInRadiant(scene::Node* entity = NULL); - void SetTexture(const char* textureName); - char texture[256]; - int width, height; - drawVert_t points[MAX_PATCH_WIDTH][MAX_PATCH_HEIGHT]; - DPatch(); - virtual ~DPatch(); - -}; - -#endif // !defined(AFX_DPATCH_H__26C6B083_CE5B_420B_836B_1DDA733C04CE__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPlane.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPlane.cpp deleted file mode 100644 index c16db749..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPlane.cpp +++ /dev/null @@ -1,268 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DPlane.cpp: implementation of the DPlane class. -// -////////////////////////////////////////////////////////////////////// - -#include "DPlane.h" - -#include - -#include "DPoint.h" -#include "DWinding.h" - -#include "str.h" -#include "misc.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DPlane::DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData) -{ - MakeNormal( va, vb, vc, normal ); - if(VectorNormalize(normal, normal) == 0) // normalizes and returns length - globalErrorStream() << "DPlane::DPlane: Bad Normal.\n"; - - _d = (normal[0]*va[0]) + (normal[1]*va[1]) + (normal[2]*va[2]); - - VectorCopy(va, points[0]); - VectorCopy(vb, points[1]); - VectorCopy(vc, points[2]); - - m_bChkOk = true; - - if(texData) - memcpy(&texInfo, texData, sizeof(_QERFaceData)); - else - FillDefaultTexture(&texInfo, points[0], points[1], points[2], "textures/common/caulk"); -} - -DPlane::~DPlane() -{ - -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// - -vec_t DPlane::DistanceToPoint(vec3_t pnt) -{ - vec3_t tmp; - VectorSubtract(pnt, points[0], tmp); - return DotProduct(tmp, normal); -} - -bool DPlane::PlaneIntersection(DPlane *pl1, DPlane *pl2, vec3_t out) -{ - float a1, a2, a3; - float b1, b2, b3; - float c1, c2, c3; - - a1 = normal[0]; a2 = normal[1]; a3 = normal[2]; - b1 = pl1->normal[0]; b2 = pl1->normal[1]; b3 = pl1->normal[2]; - c1 = pl2->normal[0]; c2 = pl2->normal[1]; c3 = pl2->normal[2]; - - float d = Determinant3x3(a1, a2, a3, b1, b2, b3, c1, c2, c3); - - if(d == 0) - return false; - - float v1 = _d; - float v2 = pl1->_d; - float v3 = pl2->_d; - - float d1 = Determinant3x3(v1, a2, a3, v2, b2, b3, v3, c2, c3); - float d2 = Determinant3x3(a1, v1, a3, b1, v2, b3, c1, v3, c3); - float d3 = Determinant3x3(a1, a2, v1, b1, b2, v2, c1, c2, v3); - - out[0] = d1/d; - out[1] = d2/d; - out[2] = d3/d; - - return true; -} - -bool DPlane::IsRedundant(std::list& pointList) -{ - int cnt = 0; - - //std::list::const_iterator point=pointList.begin(); - for(std::list::const_iterator point=pointList.begin(); point!=pointList.end(); point++) - { - if(fabs(DistanceToPoint((*point)->_pnt)) < MAX_ROUND_ERROR) - cnt++; - - if(cnt == 3) - return false; - } - return true; -} - -bool DPlane::operator == (DPlane& other) -{ - vec3_t chk; - VectorSubtract(other.normal, normal, chk); - if(fabs(VectorLength(chk)) > MAX_ROUND_ERROR) - return false; - - if(fabs(other._d - _d) > MAX_ROUND_ERROR) - return false; - - return true; -} - -bool DPlane::operator != (DPlane& other) -{ - vec3_t chk; - VectorAdd(other.normal, normal, chk); - if(fabs(VectorLength(chk)) > MAX_ROUND_ERROR) - return false; - - return true; -} - -DWinding* DPlane::BaseWindingForPlane() -{ - int i, x; - vec_t max, v; - vec3_t org, vright, vup; - -// find the major axis - - max = -131072; - x = -1; - for (i=0 ; i<3; i++) - { - v = (float)fabs(normal[i]); - if (v > max) - { - x = i; - max = v; - } - } - if (x==-1) - globalOutputStream() << "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, _d, org); - - CrossProduct (vup, normal, vright); - - VectorScale (vup, 131072, vup); - VectorScale (vright, 131072, vright); - -// project a really big axis aligned box onto the plane - DWinding* w = new DWinding; - 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]); - - return w; -} - -void DPlane::Rebuild() -{ - vec3_t v1, v2; - VectorSubtract(points[0], points[1], v1); - VectorSubtract(points[2], points[1], v2); - CrossProduct(v1, v2, normal); - - if(VectorNormalize(normal, normal) == 0) // normalizes and returns length - globalErrorStream() << "DPlane::Rebuild: Bad Normal.\n"; - - _d = (normal[0]*points[0][0]) + (normal[1]*points[0][1]) + (normal[2]*points[0][2]); - - VectorCopy(points[0], texInfo.m_p0); - VectorCopy(points[1], texInfo.m_p1); - VectorCopy(points[2], texInfo.m_p2); -} - -bool DPlane::AddToBrush(scene::Node& brush) -{ - bool changed = false; - if(!(m_bChkOk || !strcmp(m_shader.c_str(), "textures/common/caulk"))) - { - m_shader = "textures/common/caulk"; - changed = true; - } - - _QERFaceData faceData; - faceData.m_p0 = vector3_from_array(points[0]); - faceData.m_p1 = vector3_from_array(points[1]); - faceData.m_p2 = vector3_from_array(points[2]); - faceData.m_texdef = texInfo.m_texdef; - faceData.m_shader = m_shader.c_str(); - GlobalBrushCreator().Brush_addFace(brush, faceData); - - return changed; -} - -void DPlane::ScaleTexture() -{ } - -DPlane::DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail) -{ - vec3_t v1, v2; - VectorSubtract(va, vb, v1); - VectorSubtract(vc, vb, v2); - CrossProduct(v1, v2, normal); - - if(VectorNormalize(normal, normal) == 0) // normalizes and returns length - globalErrorStream() << "DPlane::DPlane: Bad Normal.\n"; - - _d = (normal[0]*va[0]) + (normal[1]*va[1]) + (normal[2]*va[2]); - - VectorCopy(va, points[0]); - VectorCopy(vb, points[1]); - VectorCopy(vc, points[2]); - - m_bChkOk = true; - - FillDefaultTexture(&texInfo, points[0], points[1], points[2], textureName); - if(bDetail) - texInfo.contents |= FACE_DETAIL; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPlane.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPlane.h deleted file mode 100644 index 68db6ed9..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPlane.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DPlane.h: interface for the DPlane class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DPLANE_H__FC37C021_F0A1_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_DPLANE_H__FC37C021_F0A1_11D4_ACF7_004095A18133__INCLUDED_ - -#include -#include "ibrush.h" -#include "string/string.h" -#include "mathlib.h" - -class Brush; -class DPoint; - -#define FACE_DETAIL 0x8000000 - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -class DWinding; - -class DPlane -{ -public: - DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const char* textureName, bool bDetail); - void ScaleTexture(); - DWinding* BaseWindingForPlane(); - - void Rebuild(); - - bool AddToBrush(scene::Node& brush); - bool operator != (DPlane& other); - bool operator == (DPlane& other); - - bool IsRedundant(std::list& pointList); - bool PlaneIntersection(DPlane* pl1, DPlane* pl2, vec3_t out);; - - vec_t DistanceToPoint(vec3_t pnt); - - DPlane(const vec3_t va, const vec3_t vb, const vec3_t vc, const _QERFaceData* texData); - DPlane() { } - virtual ~DPlane(); - - bool m_bChkOk; - _QERFaceData texInfo; - CopiedString m_shader; - vec3_t points[3]; // djbob:do we really need these any more? - vec3_t normal; - float _d; -}; - -//typedef CList DPlaneList; -#endif // !defined(AFX_DPLANE_H__FC37C021_F0A1_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPoint.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPoint.cpp deleted file mode 100644 index b0b60153..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPoint.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DPoint.cpp: implementation of the DPoint class. -// -////////////////////////////////////////////////////////////////////// - -#include "DPoint.h" -#include "misc.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DPoint::DPoint() -{ - -} - -DPoint::~DPoint() -{ - -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// - -bool DPoint::operator ==(vec3_t other) -{ - vec3_t test; - VectorSubtract(other, _pnt, test); - if(fabs(VectorLength(test)) > MAX_ROUND_ERROR) - return false; - return true; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPoint.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPoint.h deleted file mode 100644 index 12137341..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DPoint.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DPoint.h: interface for the DPoint class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DPOINT_H__FC37C022_F0A1_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_DPOINT_H__FC37C022_F0A1_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "mathlib.h" - -class DPoint -{ -public: - DPoint(); - virtual ~DPoint(); - - bool operator ==(vec3_t other); - - vec3_t _pnt; - unsigned char m_uData; -}; - -//typedef CList DPointList; - -#endif // !defined(AFX_DPOINT_H__FC37C022_F0A1_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DShape.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DShape.cpp deleted file mode 100644 index 9201d29c..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DShape.cpp +++ /dev/null @@ -1,469 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DShape.cpp: implementation of the DShape class. -// -////////////////////////////////////////////////////////////////////// - -#include "DShape.h" - -#include -#include -#include "str.h" - -#include "DPoint.h" -#include "DPlane.h" -#include "DBrush.h" -#include "DEPair.h" -#include "DPatch.h" -#include "DEntity.h" - -//#include "dialogs-gtk.h" - -#include "misc.h" -#include "shapes.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -bool bFacesAll[6] = {true, true, true, true, true, true}; - -DShape::DShape() -{ - m_nNextBrush = 0; -} - -DShape::~DShape() -{ - -} - -void DShape::BuildRegularPrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop) -{ - vec3_t vc[MAX_POLYGON_FACES+2], vd[MAX_POLYGON_FACES+2]; - - vec3_t radius; - vec3_t origin; - - VectorSubtract(max, min, radius); - VectorScale(radius, 0.5f, radius); - // calc 3d radius and origin - VectorAdd(max, min, origin); - VectorScale(origin, 0.5f, origin); - - float phase = 0.0f; - - if(bAlignTop) - { - phase = -(Q_PI/nSides); - VectorScale(radius, static_cast(1.0 / cos(phase)), radius); - } - - //----- Build Polygon Vertices ----- - - int i; - for(i = 0; i < nSides; i++) - { - VectorCopy(origin, vc[i]); - VectorCopy(origin, vd[i]); - - vc[i][2] = min[2]; - vd[i][2] = max[2]; - - vc[i][0] += radius[0] * sinf( ( 2 * Q_PI * i / nSides ) + phase ); - vc[i][1] += radius[1] * cosf( ( 2 * Q_PI * i / nSides ) + phase ); - - vd[i][0] = vc[i][0]; - vd[i][1] = vc[i][1]; - } - - VectorCopy(vc[0], vc[nSides]); - VectorCopy(vd[0], vd[nSides]); - VectorCopy(vc[1], vc[nSides+1]); - VectorCopy(vd[1], vd[nSides+1]); - - //---------------------------------- - - DBrush* pB = m_Container.GetWorldSpawn()->NewBrush(m_nNextBrush++); - - for(i = 1; i <= nSides; i++) - pB->AddFace(vc[i-1], vc[i], vd[i], GetCurrentTexture(), false); - - pB->AddFace(vc[2], vc[1], vc[0], "textures/common/caulk", false); - pB->AddFace(vd[0], vd[1], vd[2], "textures/common/caulk", false); -} - -void DShape::Commit() -{ - m_Container.GetWorldSpawn()->FixBrushes(); - m_Container.BuildInRadiant(true); -} - -void DShape::BuildInversePrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop) -{ - vec3_t va[MAX_POLYGON_FACES+1], vb[MAX_POLYGON_FACES+1]; - vec3_t radius; - vec3_t origin; - - VectorSubtract(max, min, radius); - VectorScale(radius, 0.5f, radius); - // calc 3d radius and origin - VectorAdd(max, min, origin); - VectorScale(origin, 0.5f, origin); - - float phase = 0.0f; - - if(bAlignTop) - { - phase = -(Q_PI/nSides); - VectorScale(radius, static_cast(1.0 / cos(phase)), radius); - } - - //----- Build Polygon Vertices ----- - - int i; - for(i = 0; i < nSides; i++) - { - VectorCopy(origin, va[i]); - VectorCopy(origin, vb[i]); - - va[i][2] = min[2]; - vb[i][2] = max[2]; - - va[i][0] += radius[0] * sinf( ( 2 * Q_PI * i / nSides ) + phase ); - va[i][1] += radius[1] * cosf( ( 2 * Q_PI * i / nSides ) + phase ); - - vb[i][0] = va[i][0]; - vb[i][1] = va[i][1]; - } - - VectorCopy(va[0], va[nSides]); - VectorCopy(vb[0], vb[nSides]); - - //---------------------------------- - - for(i = 1; i <= nSides; i++) - { - DBrush* pB = GetBoundingCube(min, max, "textures/common/caulk"); - - vec3_t top, bottom; - VectorCopy(va[i-1], top); - VectorCopy(va[i], bottom); - - if(va[i-1][1] > va[i][1]) - { - top[0] += 5; - bottom[0] += 5; - } - else // flip direction of plane on crossover - { - top[0] -= 5; - bottom[0] -= 5; - } - - if(top[1] != bottom[1]) // internal line is flat already if true - { - pB->AddFace(va[i-1], top, vb[i-1], "textures/common/caulk", false); - pB->AddFace(va[i], vb[i], bottom, "textures/common/caulk", false); - } // add cut-off planes - - pB->AddFace(va[i-1], vb[i-1], vb[i], GetCurrentTexture(), false); - // add internal polygon plane - } -} - -void DShape::BuildBorderedPrism(vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop) -{ - vec3_t va[MAX_POLYGON_FACES+2], vb[MAX_POLYGON_FACES+2]; - vec3_t vc[MAX_POLYGON_FACES+2], vd[MAX_POLYGON_FACES+2]; - - vec3_t radius; - vec3_t origin; - - VectorSubtract(max, min, radius); - VectorScale(radius, 0.5f, radius); - // calc 3d radius and origin - VectorAdd(max, min, origin); - VectorScale(origin, 0.5f, origin); - - if(nBorder >= Min(radius[0], radius[1])) - { -// DoMessageBox("Border is too large", "Error", MB_OK); - return; - } - - float phase = 0.0f; - - if(bAlignTop) - { - phase = -(Q_PI/nSides); - VectorScale(radius, static_cast(1.0 / cos(phase)), radius); - } - - //----- Build Polygon Vertices ----- - - int i; - for(i = 0; i < nSides; i++) - { - VectorCopy(origin, va[i]); - VectorCopy(origin, vb[i]); - VectorCopy(origin, vc[i]); - VectorCopy(origin, vd[i]); - - va[i][2] = min[2]; - vb[i][2] = max[2]; - - va[i][0] += (radius[0] - nBorder) * sinf( ( 2 * Q_PI * i / nSides ) + phase ); - va[i][1] += (radius[1] - nBorder) * cosf( ( 2 * Q_PI * i / nSides ) + phase ); - - vb[i][0] = va[i][0]; - vb[i][1] = va[i][1]; - - - - vc[i][2] = min[2]; - vd[i][2] = max[2]; - - vc[i][0] += radius[0] * sinf( ( 2 * Q_PI * i / nSides ) + phase ); - vc[i][1] += radius[1] * cosf( ( 2 * Q_PI * i / nSides ) + phase ); - - vd[i][0] = vc[i][0]; - vd[i][1] = vc[i][1]; - } - - VectorCopy(va[0], va[nSides]); - VectorCopy(vb[0], vb[nSides]); - VectorCopy(va[1], va[nSides+1]); - VectorCopy(vb[1], vb[nSides+1]); - - VectorCopy(vc[0], vc[nSides]); - VectorCopy(vd[0], vd[nSides]); - VectorCopy(vc[1], vc[nSides+1]); - VectorCopy(vd[1], vd[nSides+1]); - - //---------------------------------- - - for(i = 1; i <= nSides; i++) - { - DBrush* pB = GetBoundingCube(min, max, "textures/common/caulk"); - - pB->AddFace(origin, vc[i-1], vd[i-1], "textures/common/caulk", false); - pB->AddFace(origin, vd[i], vc[i], "textures/common/caulk", false); - - pB->AddFace(vc[i-1], vc[i], vd[i], GetCurrentTexture(), false); - pB->AddFace(vb[i], va[i], va[i-1], GetCurrentTexture(), false); - } -} - -DBrush* DShape::GetBoundingCube_Ext(vec3_t min, vec3_t max, const char *textureName, bool* bUseFaces, bool detail) -{ - DBrush* pB = new DBrush; - //----- Build Outer Bounds --------- - - vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - - v2[0] = max[0]; - v3[1] = max[1]; - - v6[0] = min[0]; - v7[1] = min[1]; - - //---------------------------------- - - //----- Add Six Cube Faces --------- - - if(bUseFaces[0]) - pB->AddFace(v1, v2, v3, textureName, detail); - if(bUseFaces[1]) - pB->AddFace(v1, v3, v6, textureName, detail); - if(bUseFaces[2]) - pB->AddFace(v1, v7, v2, textureName, detail); - - if(bUseFaces[3]) - pB->AddFace(v5, v6, v3, textureName, detail); - if(bUseFaces[4]) - pB->AddFace(v5, v2, v7, textureName, detail); - if(bUseFaces[5]) - pB->AddFace(v5, v7, v6, textureName, detail); - - //---------------------------------- - - return pB; -} - -DBrush* DShape::GetBoundingCube(vec3_t min, vec3_t max, const char *textureName, DEntity* ent, bool* bUseFaces) -{ - DBrush* pB; - if(ent == NULL) - pB = m_Container.GetWorldSpawn()->NewBrush(m_nNextBrush++); - else - pB = ent->NewBrush(m_nNextBrush++); - - //----- Build Outer Bounds --------- - - vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - - v2[0] = max[0]; - v3[1] = max[1]; - - v6[0] = min[0]; - v7[1] = min[1]; - - //---------------------------------- - - //----- Add Six Cube Faces --------- - - if(bUseFaces[0]) - pB->AddFace(v1, v2, v3, textureName, false); - if(bUseFaces[1]) - pB->AddFace(v1, v3, v6, textureName, false); - if(bUseFaces[2]) - pB->AddFace(v1, v7, v2, textureName, false); - - if(bUseFaces[3]) - pB->AddFace(v5, v6, v3, textureName, false); - if(bUseFaces[4]) - pB->AddFace(v5, v2, v7, textureName, false); - if(bUseFaces[5]) - pB->AddFace(v5, v7, v6, textureName, false); - - //---------------------------------- - - return pB; -} - -bool DShape::BuildPit(vec3_t min, vec3_t max) -{ - if((max[2] - min[2]) < 196) - return false; - - srand(time(NULL)); - - vec3_t centre; - VectorAdd(min, max, centre); - VectorScale(centre, 0.5f, centre); - - char buffer[256]; - - int team = (rand()%10000)+5000; - -// ************* SPEAKER *************** - sprintf(buffer, "t%i_1", team); - -// trigger for speaker - vec3_t triggerVoiceBtm; - VectorCopy(min, triggerVoiceBtm); - triggerVoiceBtm[2] = max[2] - 16; - - DEntity* triggerVoice = m_Container.AddEntity("trigger_multiple"); - GetBoundingCube(triggerVoiceBtm, max, "textures/common/trigger", triggerVoice); - triggerVoice->AddEPair("target", buffer); -//-------------------- - -// target for speaker - vec3_t voiceOrigin; - VectorCopy(centre, voiceOrigin); - voiceOrigin[2] = max[2]+16; - - - DEntity* targetVoice = m_Container.AddEntity("target_speaker"); - targetVoice->AddEPair("targetname", buffer); - - sprintf(buffer, "%f %f %f", voiceOrigin[0], voiceOrigin[1], voiceOrigin[2]); - targetVoice->AddEPair("origin", buffer); - targetVoice->AddEPair("spawnflags", "8"); - targetVoice->AddEPair("noise", "*falling1.wav"); -//-------------------- - -// *********** END SPEAKER ************* - -// ********* POWERUP REMOVAL *********** - sprintf(buffer, "t%i_2", team); - -// trigger for powerup removal - vec3_t triggerPwrRmvTop, triggerPwrRmvBtm; - VectorCopy(min, triggerPwrRmvBtm); - VectorCopy(max, triggerPwrRmvTop); - - triggerPwrRmvTop[2] = triggerVoiceBtm[2] - 64; - triggerPwrRmvBtm[2] = triggerPwrRmvTop[2] - 16; - - DEntity* triggerPwrRmv = m_Container.AddEntity("trigger_multiple"); - GetBoundingCube(triggerPwrRmvBtm, triggerPwrRmvTop, "textures/common/trigger", triggerPwrRmv); - triggerPwrRmv->AddEPair("target", buffer); -//-------------------- - -// target for powerup removal - vec3_t pwrRmvOrigin; - VectorCopy(centre, pwrRmvOrigin); - pwrRmvOrigin[2] = triggerPwrRmvTop[2]+16; - - DEntity* targetPwrRmv = m_Container.AddEntity("target_remove_powerups"); - targetPwrRmv->AddEPair("targetname", buffer); - - sprintf(buffer, "%f %f %f", pwrRmvOrigin[0], pwrRmvOrigin[1], pwrRmvOrigin[2]); - targetPwrRmv->AddEPair("origin", buffer); -//-------------------- - -// ****** END POWERUP REMOVAL ******** - -// ********* DAMAGE *********** - -// trigger for damage - vec3_t triggerDmgTop, triggerDmgBtm; - VectorCopy(min, triggerDmgBtm); - VectorCopy(max, triggerDmgTop); - - triggerDmgBtm[2] = min[2] + 64; - triggerDmgTop[2] = triggerDmgBtm[2] + 16; - - DEntity* triggerDmg = m_Container.AddEntity("trigger_hurt"); - GetBoundingCube(triggerDmgBtm, triggerDmgTop, "textures/common/trigger", triggerDmg); - triggerDmg->AddEPair("dmg", "9999"); - triggerDmg->AddEPair("spawnflags", "12"); -//-------------------- - -// ****** END DAMAGE ******** - -// ********* NODROP *********** - - vec3_t nodropTop; - VectorCopy(max, nodropTop); - - nodropTop[2] = min[2] + 64; - - GetBoundingCube(min, nodropTop, "textures/common/nodrop"); - -// ****** END NODROP ******** - - return true; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DShape.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DShape.h deleted file mode 100644 index 3c4ed75e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DShape.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DShape.h: interface for the DShape class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_) -#define AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "mathlib.h" -#include "DMap.h" -class DBrush; -class DEntity; - -// defines for polygon stuff -#define MAX_POLYGON_FACES 128 - -extern bool bFacesAll[]; - -class DShape -{ -public: - bool BuildPit(vec3_t min, vec3_t max); - void BuildBorderedPrism(vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop); - void BuildInversePrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop); - void BuildRegularPrism(vec3_t min, vec3_t max, int nSides, bool bAlignTop); - - int m_nNextBrush; - static DBrush* GetBoundingCube_Ext(vec3_t min, vec3_t max, const char* textureName, bool* bUseFaces = bFacesAll, bool detail = false); - - DShape(); - virtual ~DShape(); - - void Commit(); -private: - DBrush* GetBoundingCube(vec3_t min, vec3_t max, const char* textureName, DEntity* ent = NULL, bool* bUseFaces = bFacesAll); - - DMap m_Container; -}; - -#endif // !defined(AFX_DSHAPE_H__0B30B302_9D21_4C2D_836A_61F3C8D4244D__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTrainDrawer.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTrainDrawer.cpp deleted file mode 100644 index 92b2333a..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTrainDrawer.cpp +++ /dev/null @@ -1,339 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "DTrainDrawer.h" - -#include -#include "str.h" - -#include "DPoint.h" -#include "DPlane.h" -#include "DBrush.h" -#include "DEPair.h" -#include "DPatch.h" -#include "DEntity.h" - -#include "misc.h" -#include "funchandlers.h" - -#include "iglrender.h" -#include "ientity.h" -#include "math/matrix.h" - -#include "dialogs/dialogs-gtk.h" - -DTrainDrawer::DTrainDrawer() { - m_bDisplay = false; - - BuildPaths(); - constructShaders(); - GlobalShaderCache().attachRenderable(*this); -} - -DTrainDrawer::~DTrainDrawer(void) { - GlobalShaderCache().detachRenderable(*this); - destroyShaders(); - - ClearPoints(); - ClearSplines(); -} - -void DTrainDrawer::ClearSplines() { - for(std::list::const_iterator deadSpline = m_splineList.begin(); deadSpline != m_splineList.end(); deadSpline++) { - (*deadSpline)->m_pointList.clear(); - (*deadSpline)->m_vertexList.clear(); - delete (*deadSpline); - } - - m_splineList.clear(); -} - -void DTrainDrawer::ClearPoints() { - for(std::list::const_iterator deadPoint = m_pointList.begin(); deadPoint != m_pointList.end(); deadPoint++) { - delete *deadPoint; - } - - m_pointList.clear(); -} - -void CalculateSpline_r(vec3_t* v, int count, vec3_t out, float tension) { - vec3_t dist; - - if(count < 2) { - return; - } - - if(count == 2) { - VectorSubtract( v[1], v[0], dist ); - VectorMA(v[0], tension, dist, out); - return; - } - - vec3_t* v2 = new vec3_t[count-1]; - - for( int i = 0; i < count-1; i++ ) { - VectorSubtract( v[i+1], v[i], dist ); - VectorMA(v[i], tension, dist, v2[i]); - } - - CalculateSpline_r( v2, count-1, out, tension); - - delete[] v2; -} - -void DTrainDrawer::render(RenderStateFlags state) const -{ - for(std::list::const_iterator sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - splinePoint_t* pSP = (*sp); - - glBegin(GL_LINE_STRIP); - for(std::list::const_iterator v = pSP->m_vertexList.begin(); v != pSP->m_vertexList.end(); v++) { - glVertex3fv((*v)._pnt); - } - glEnd(); - - } -} - -const char* DTrainDrawer_state_wireframe = "$bobtoolz/traindrawer/wireframe"; -const char* DTrainDrawer_state_solid = "$bobtoolz/traindrawer/solid"; - -void DTrainDrawer::constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_BLEND; - state.m_sort = OpenGLState::eSortOverlayFirst; - state.m_linewidth = 1; - state.m_colour[0] = 1; - state.m_colour[1] = 0; - state.m_colour[2] = 0; - state.m_colour[3] = 1; - state.m_linewidth = 1; - GlobalOpenGLStateLibrary().insert(DTrainDrawer_state_wireframe, state); - - state.m_colour[0] = 1; - state.m_colour[1] = 1; - state.m_colour[2] = 1; - state.m_colour[3] = 1; - state.m_linewidth = 2; - GlobalOpenGLStateLibrary().insert(DTrainDrawer_state_solid, state); - - m_shader_wireframe = GlobalShaderCache().capture(DTrainDrawer_state_wireframe); - m_shader_solid = GlobalShaderCache().capture(DTrainDrawer_state_solid); -} - -void DTrainDrawer::destroyShaders() -{ - GlobalOpenGLStateLibrary().erase(DTrainDrawer_state_wireframe); - GlobalOpenGLStateLibrary().erase(DTrainDrawer_state_solid); - GlobalShaderCache().release(DTrainDrawer_state_wireframe); - GlobalShaderCache().release(DTrainDrawer_state_solid); -} - - -void DTrainDrawer::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!m_bDisplay) { - return; - } - - renderer.SetState(m_shader_wireframe, Renderer::eWireframeOnly); - renderer.SetState(m_shader_solid, Renderer::eFullMaterials); - renderer.addRenderable(*this, g_matrix4_identity); -} -void DTrainDrawer::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - renderSolid(renderer, volume); -} - -void AddSplineControl(const char* control, splinePoint_t* pSP) { - controlPoint_t cp; - strncpy(cp.strName, control, 64); - - pSP->m_pointList.push_front(cp); -} - -class EntityBuildPaths -{ - mutable DEntity e; - DTrainDrawer& drawer; -public: - EntityBuildPaths(DTrainDrawer& drawer) : drawer(drawer) - { - } - void operator()(scene::Instance& instance) const - { - e.ClearEPairs(); - e.LoadEPairList(Node_getEntity(instance.path().top())); - - const char* classname = e.m_Classname.GetBuffer(); - const char* target; - const char* control; - const char* targetname; - vec3_t vOrigin; - - e.SpawnString("targetname", NULL, &targetname); - e.SpawnVector("origin", "0 0 0", vOrigin); - - if(!strcmp(classname, "info_train_spline_main")) { - if(!targetname) { - globalOutputStream() << "info_train_spline_main with no targetname"; - return; - } - - e.SpawnString("target", NULL, &target); - - if(!target) { - drawer.AddControlPoint( targetname, vOrigin ); - } else { - splinePoint_t* pSP = drawer.AddSplinePoint( targetname, target, vOrigin ); - - e.SpawnString("control", NULL, &control); - - if(control) { - AddSplineControl( control, pSP ); - - for(int j = 2;; j++) { - char buffer[16]; - sprintf(buffer, "control%i", j); - - e.SpawnString(buffer, NULL, &control); - if(!control) { - break; - } - - AddSplineControl( control, pSP ); - } - } - } - } else if(!strcmp(classname, "info_train_spline_control")) { - if(!targetname) { - globalOutputStream() << "info_train_spline_control with no targetname"; - return; - } - - drawer.AddControlPoint( targetname, vOrigin ); - } - } -}; - -void DTrainDrawer::BuildPaths() { - Scene_forEachEntity(EntityBuildPaths(*this)); - - std::list::const_iterator sp; - for(sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - splinePoint_t* pSP = (*sp); - - controlPoint_t* pTarget = FindControlPoint( pSP->strTarget ); - - if(!pTarget) { - globalOutputStream() << "couldn't find target " << pSP->strTarget; - return; -// continue; - } - - pSP->pTarget = pTarget; - - - for(std::list::iterator cp = pSP->m_pointList.begin(); cp != pSP->m_pointList.end(); cp++) { - controlPoint_t* pControl = FindControlPoint( (*cp).strName ); - if(!pControl) { - globalOutputStream() << "couldn't find control " << (*cp).strName; - return; - } - - VectorCopy(pControl->vOrigin, (*cp).vOrigin); - } - } - - m_bDisplay = true; - - for(sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - splinePoint_t* pSP = (*sp); - DPoint out; - - if(!pSP->pTarget) { - continue; - } - - std::size_t count = pSP->m_pointList.size() + 2; - vec3_t* v = new vec3_t[count]; - - VectorCopy(pSP->point.vOrigin, v[0]); - - int i = 1; - for(std::list::reverse_iterator cp = pSP->m_pointList.rbegin(); cp != pSP->m_pointList.rend(); cp++) { - VectorCopy((*cp).vOrigin, v[i]); - i++; - } - VectorCopy(pSP->pTarget->vOrigin, v[i]); - - for (float tension = 0.0f; tension <= 1.f; tension += 0.01f) { - CalculateSpline_r(v, static_cast(count), out._pnt, tension); - pSP->m_vertexList.push_front(out); - } - - delete[] v; - - VectorCopy(pSP->pTarget->vOrigin, out._pnt); - pSP->m_vertexList.push_front(out); - } - - SceneChangeNotify(); -} - -void DTrainDrawer::AddControlPoint(const char* name, vec_t* origin) -{ - controlPoint_t* pCP = new controlPoint_t; - - strncpy(pCP->strName, name, 64); - VectorCopy( origin, pCP->vOrigin ); - - m_pointList.push_back( pCP ); -} - -splinePoint_t* DTrainDrawer::AddSplinePoint(const char* name, const char* target, vec_t* origin) -{ - splinePoint_t* pSP = new splinePoint_t; - - strncpy(pSP->point.strName, name, 64); - strncpy(pSP->strTarget, target, 64); - VectorCopy( origin, pSP->point.vOrigin ); - m_splineList.push_back( pSP ); - - return pSP; -} - -controlPoint_t* DTrainDrawer::FindControlPoint(const char* name) -{ - for(std::list::const_iterator cp = m_pointList.begin(); cp != m_pointList.end(); cp++) { - if(!strcmp(name, (*cp)->strName)) { - return (*cp); - } - } - - for(std::list::const_iterator sp = m_splineList.begin(); sp != m_splineList.end(); sp++) { - if(!strcmp(name, (*sp)->point.strName)) { - return &((*sp)->point); - } - } - - return NULL; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTrainDrawer.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTrainDrawer.h deleted file mode 100644 index 9d8903ee..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTrainDrawer.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DTrainDrawer.h: interface for the DTrainDrawer class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 - -#pragma once -#endif // _MSC_VER > 1000 - -#include -#include "mathlib.h" - -#include "irender.h" -#include "renderable.h" - -class DPoint; -class Shader; - -typedef struct { - char strName[64]; - - vec3_t vOrigin; -} controlPoint_t; - -typedef struct { - controlPoint_t point; - - char strControl[64]; - char strTarget[64]; - - std::list m_pointList; - std::list m_vertexList; - - controlPoint_t* pTarget; -} splinePoint_t; - -class DTrainDrawer : public Renderable, public OpenGLRenderable -{ -private: - std::list m_splineList; - std::list m_pointList; - - bool m_bDisplay; - Shader* m_shader_wireframe; - Shader* m_shader_solid; -public: - - DTrainDrawer(); - virtual ~DTrainDrawer(void); - - void render(RenderStateFlags state) const; - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; - - void constructShaders(); - void destroyShaders(); - - void ClearSplines(); - void ClearPoints(); - void BuildPaths(); - void AddControlPoint(const char* name, vec_t* origin); - splinePoint_t* AddSplinePoint(const char* name, const char* target, vec_t* origin); - controlPoint_t* FindControlPoint(const char* name); -}; - -#endif // !defined(AFX_TRAINDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTreePlanter.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTreePlanter.cpp deleted file mode 100644 index 6ad221be..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTreePlanter.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "DTreePlanter.h" - -#include -#include "str.h" - -#include "DPoint.h" -#include "DPlane.h" -#include "DBrush.h" -#include "DEPair.h" -#include "DPatch.h" -#include "DEntity.h" - -#include "ScriptParser.h" -#include "misc.h" -#include "scenelib.h" - - - -#include "funchandlers.h" - -SignalHandlerResult DTreePlanter::mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) -{ - if(button != c_buttonLeft) - { - return SIGNAL_CONTINUE_EMISSION; - } - VIEWTYPE vt = GlobalRadiant().XYWindow_getViewType(); - - switch(vt) { - case XY: - break; - case YZ: - case XZ: - default: - return SIGNAL_CONTINUE_EMISSION; - } - - Vector3 pt, vhit; - - pt = vector3_snapped(GlobalRadiant().XYWindow_windowToWorld(position), GlobalRadiant().getGridSize()); - - if(FindDropPoint(vector3_to_array(pt), vector3_to_array(vhit))) { - vhit[2] += m_offset; - - char buffer[128]; - DEntity e(m_entType); - - sprintf(buffer, "%i %i %i", (int)vhit[0], (int)vhit[1], (int)vhit[2]); - e.AddEPair("origin", buffer); - - if(m_autoLink) { - - const scene::Path* pLastEntity = NULL; - const scene::Path* pThisEntity = NULL; - - int entpos; - for(int i = 0; i < 256; i++) { - sprintf(buffer, m_linkName, i); - pThisEntity = FindEntityFromTargetname( buffer ); - - if(pThisEntity) { - entpos = i; - pLastEntity = pThisEntity; - } - } - - if(!pLastEntity) { - sprintf(buffer, m_linkName, 0); - } else { - sprintf(buffer, m_linkName, entpos + 1); - } - - e.AddEPair( "targetname", buffer ); - - if(pLastEntity) { - DEntity e2; - e2.LoadFromEntity(pLastEntity->top(), true); - e2.AddEPair("target", buffer); - e2.RemoveFromRadiant(); - e2.BuildInRadiant(false); - } - - } - - if(m_setAngles) { - int angleYaw = (rand() % (m_maxYaw - m_minYaw + 1)) + m_minYaw; - int anglePitch = (rand() % (m_maxPitch - m_minPitch + 1)) + m_minPitch; - - sprintf(buffer, "%i %i 0", anglePitch, angleYaw); - e.AddEPair("angles", buffer); - } - - if(m_numModels) { - int treetype = rand() % m_numModels; - e.AddEPair("model", m_trees[treetype].name); - } - - if(m_useScale) { - float scale = (((rand()%1000)*0.001f) * (m_maxScale - m_minScale)) + m_minScale; - - sprintf(buffer, "%f", scale ); - e.AddEPair("modelscale", buffer); - } - - e.BuildInRadiant( false ); - } - - if(m_autoLink) { - DoTrainPathPlot(); - } - - return SIGNAL_STOP_EMISSION; -} - -bool DTreePlanter::FindDropPoint(vec3_t in, vec3_t out) { - DPlane p1; - DPlane p2; - - vec3_t vUp = { 0, 0, 1 }; - vec3_t vForward = { 0, 1, 0 }; - vec3_t vLeft = { 1, 0, 0 }; - - in[2] = 65535; - - VectorCopy(in, p1.points[0]); - VectorCopy(in, p1.points[1]); - VectorCopy(in, p1.points[2]); - VectorMA(p1.points[1], 20, vUp, p1.points[1]); - VectorMA(p1.points[1], 20, vLeft, p1.points[2]); - - VectorCopy(in, p2.points[0]); - VectorCopy(in, p2.points[1]); - VectorCopy(in, p2.points[2]); - VectorMA(p1.points[1], 20, vUp, p2.points[1]); - VectorMA(p1.points[1], 20, vForward, p2.points[2]); - - p1.Rebuild(); - p2.Rebuild(); - - bool found = false; - vec3_t temp; - vec_t dist; - int cnt = m_world.GetIDMax(); - for(int i = 0; i < cnt; i++) { - DBrush* pBrush = m_world.GetBrushForID( i ); - - if(pBrush->IntersectsWith( &p1, &p2, temp )) { - vec3_t diff; - vec_t tempdist; - VectorSubtract(in, temp, diff); - tempdist = VectorLength( diff ); - if(!found || (tempdist < dist)) { - dist = tempdist; - VectorCopy( temp, out ); - found = true; - } - } - } - - return found; -} - -class TreePlanterDropEntityIfSelected -{ - mutable DEntity ent; - DTreePlanter& planter; -public: - TreePlanterDropEntityIfSelected(DTreePlanter& planter) : planter(planter) - { - } - void operator()(scene::Instance& instance) const - { - if(!instance.isSelected()) - { - return; - } - ent.LoadFromEntity(instance.path().top()); - - DEPair* pEpair = ent.FindEPairByKey("origin"); - if(!pEpair) { - return; - } - - vec3_t vec, out; - sscanf( pEpair->value.GetBuffer(), "%f %f %f", &vec[0], &vec[1], &vec[2]); - - planter.FindDropPoint( vec, out ); - - char buffer[256]; - sprintf( buffer, "%f %f %f", out[0], out[1], out[2] ); - ent.AddEPair( "origin", buffer ); - ent.RemoveFromRadiant(); - ent.BuildInRadiant(false); - } -}; - -void DTreePlanter::DropEntsToGround( void ) { - Scene_forEachEntity(TreePlanterDropEntityIfSelected(*this)); -} - -void DTreePlanter::MakeChain( int linkNum, const char* linkName ) { - char buffer[256]; - int i; - for(i = 0; i < linkNum; i++) { - DEntity e("info_train_spline_main"); - - sprintf( buffer, "%s_pt%i", linkName, i ); - e.AddEPair( "targetname", buffer ); - - sprintf( buffer, "0 %i 0", i * 64 ); - e.AddEPair( "origin", buffer ); - - if(i != m_linkNum-1) { - sprintf( buffer, "%s_pt%i", linkName, i+1 ); - e.AddEPair( "target", buffer ); - - sprintf( buffer, "%s_ctl%i", linkName, i ); - e.AddEPair( "control", buffer ); - } - e.BuildInRadiant( false ); - } - - for(i = 0; i < linkNum-1; i++) { - DEntity e("info_train_spline_control"); - - sprintf( buffer, "%s_ctl%i", linkName, i ); - e.AddEPair( "targetname", buffer ); - - sprintf( buffer, "0 %i 0", (i * 64) + 32); - e.AddEPair( "origin", buffer ); - - e.BuildInRadiant( false ); - } -} - -void DTreePlanter::SelectChain( void ) { -/* char buffer[256]; - - for(int i = 0; i < m_linkNum; i++) { - DEntity e("info_train_spline_main"); - - sprintf( buffer, "%s_pt%i", m_linkName, i ); - e.AddEPair( "targetname", buffer ); - - sprintf( buffer, "0 %i 0", i * 64 ); - e.AddEPair( "origin", buffer ); - - if(i != m_linkNum-1) { - sprintf( buffer, "%s_pt%i", m_linkName, i+1 ); - e.AddEPair( "target", buffer ); - - sprintf( buffer, "%s_ctl%i", m_linkName, i ); - e.AddEPair( "control", buffer ); - } - - e.BuildInRadiant( false ); - } - - for(int i = 0; i < m_linkNum-1; i++) { - DEntity e("info_train_spline_control"); - - sprintf( buffer, "%s_ctl%i", m_linkName, i ); - e.AddEPair( "targetname", buffer ); - - sprintf( buffer, "0 %i 0", (i * 64) + 32); - e.AddEPair( "origin", buffer ); - - e.BuildInRadiant( false ); - }*/ -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTreePlanter.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTreePlanter.h deleted file mode 100644 index fec8910f..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DTreePlanter.h +++ /dev/null @@ -1,211 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef __DTREE_H__ -#define __DTREE_H__ - -#include "qerplugin.h" -#include "signal/isignal.h" -#include "string/string.h" - -#include "DEntity.h" -#include "ScriptParser.h" -#include "mathlib.h" -#include "misc.h" - -#define MAX_QPATH 64 - -typedef struct treeModel_s { - char name[MAX_QPATH]; -} treeModel_t; - -#define MAX_TP_MODELS 256 - -class DTreePlanter { - MouseEventHandlerId m_mouseDown; - SignalHandlerId m_destroyed; -public: - SignalHandlerResult mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers); - typedef Member3 MouseDownCaller; - void destroyed() - { - m_mouseDown = MouseEventHandlerId(); - m_destroyed = SignalHandlerId(); - } - typedef Member DestroyedCaller; - - DTreePlanter() { - m_numModels = 0; - m_offset = 0; - m_maxPitch = 0; - m_minPitch = 0; - m_maxYaw = 0; - m_minYaw = 0; - m_setAngles = false; - m_useScale = false; - m_autoLink = false; - m_linkNum = 0; - - m_world.LoadSelectedBrushes(); - - char buffer[256]; - GetFilename( buffer, "bt/tp_ent.txt" ); - - FILE* file = fopen( buffer, "rb" ); - if(file) { - fseek( file, 0, SEEK_END ); - int len = ftell( file ); - fseek( file, 0, SEEK_SET ); - - if(len) { - char* buf = new char[len+1]; - buf[len] = '\0'; - // parser will do the cleanup, dont delete. - - fread( buf, len, 1, file ); - - CScriptParser parser; - parser.SetScript( buf ); - - ReadConfig( &parser ); - } - - fclose( file ); - } - - m_mouseDown = GlobalRadiant().XYWindowMouseDown_connect(makeSignalHandler3(MouseDownCaller(), *this)); - m_destroyed = GlobalRadiant().XYWindowDestroyed_connect(makeSignalHandler(DestroyedCaller(), *this)); - } - - virtual ~DTreePlanter() - { - if(!m_mouseDown.isNull()) - { - GlobalRadiant().XYWindowMouseDown_disconnect(m_mouseDown); - } - if(!m_destroyed.isNull()) - { - GlobalRadiant().XYWindowDestroyed_disconnect(m_destroyed); - } - } - -#define MT(t) string_equal_nocase( pToken, t ) -#define GT pToken = pScriptParser->GetToken( true ) -#define CT if(!*pToken) { return; } - - void ReadConfig( CScriptParser* pScriptParser ) { - const char* GT; - CT; - - do { - GT; - if(*pToken == '}') { - break; - } - - if(MT("model")) { - if(m_numModels >= MAX_TP_MODELS) { - return; - } - - GT; CT; - - strncpy( m_trees[m_numModels++].name, pToken, MAX_QPATH ); - } else if(MT("link")) { - GT; CT; - - strncpy( m_linkName, pToken, MAX_QPATH ); - - m_autoLink = true; - } else if(MT("entity")) { - GT; CT; - - strncpy( m_entType, pToken, MAX_QPATH ); - } else if(MT("offset")) { - GT; CT; - - m_offset = atoi(pToken); - } else if(MT("pitch")) { - GT; CT; - - m_minPitch = atoi(pToken); - - GT; CT; - - m_maxPitch = atoi(pToken); - - m_setAngles = true; - } else if(MT("yaw")) { - GT; CT; - - m_minYaw = atoi(pToken); - - GT; CT; - - m_maxYaw = atoi(pToken); - - m_setAngles = true; - } else if(MT("scale")) { - GT; CT; - - m_minScale = static_cast(atof(pToken)); - - GT; CT; - - m_maxScale = static_cast(atof(pToken)); - - m_useScale = true; - } else if(MT("numlinks")) { - GT; CT; - - m_linkNum = atoi( pToken ); - } - } while( true ); - } - - bool FindDropPoint(vec3_t in, vec3_t out); - void DropEntsToGround( void ); - void MakeChain( int linkNum, const char* linkName ); - void SelectChain( void ); - -private: - DEntity m_world; - - treeModel_t m_trees[MAX_TP_MODELS]; - - int m_numModels; - int m_offset; - int m_maxPitch; - int m_minPitch; - int m_maxYaw; - int m_minYaw; - - char m_entType[MAX_QPATH]; - char m_linkName[MAX_QPATH]; - int m_linkNum; - - float m_minScale; - float m_maxScale; - - bool m_useScale; - bool m_setAngles; - bool m_autoLink; -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DVisDrawer.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DVisDrawer.cpp deleted file mode 100644 index 0a936941..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DVisDrawer.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// BobView.cpp: implementation of the DVisDrawer class. -// -////////////////////////////////////////////////////////////////////// - -#include "DVisDrawer.h" - -#include "iglrender.h" -#include "math/matrix.h" - -#include -#include "str.h" - -#include "DPoint.h" -#include "DWinding.h" - -#include "misc.h" -#include "funchandlers.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DVisDrawer::DVisDrawer() -{ - m_list = NULL; - - constructShaders(); - GlobalShaderCache().attachRenderable(*this); -} - -DVisDrawer::~DVisDrawer() -{ - GlobalShaderCache().detachRenderable(*this); - destroyShaders(); - - g_VisView = NULL; -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// -const char* g_state_solid = "$bobtoolz/visdrawer/solid"; -const char* g_state_wireframe = "$bobtoolz/visdrawer/wireframe"; - -void DVisDrawer::constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_COLOURCHANGE; - state.m_linewidth = 1; - - GlobalOpenGLStateLibrary().insert(g_state_wireframe, state); - - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_FILL|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_COLOURCHANGE|RENDER_SMOOTH|RENDER_DEPTHWRITE; - - GlobalOpenGLStateLibrary().insert(g_state_solid, state); - - m_shader_solid = GlobalShaderCache().capture(g_state_solid); - m_shader_wireframe = GlobalShaderCache().capture(g_state_wireframe); -} - -void DVisDrawer::destroyShaders() -{ - GlobalShaderCache().release(g_state_solid); - GlobalShaderCache().release(g_state_wireframe); - GlobalOpenGLStateLibrary().erase(g_state_solid); - GlobalOpenGLStateLibrary().erase(g_state_wireframe); -} - -void DVisDrawer::render(RenderStateFlags state) const -{ - //bleh - std::list::const_iterator l=m_list->begin(); - - for(; l != m_list->end(); l++) - { - DWinding* w = *l; - - glColor4f(w->clr[0], w->clr[1], w->clr[2], 0.5f); - - glBegin(GL_POLYGON); - for(int i = 0; i < w->numpoints; i++) { - glVertex3f((w->p[i])[0], (w->p[i])[1], (w->p[i])[2]); - } - glEnd(); - } -} - -void DVisDrawer::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - if(!m_list) - return; - - renderer.SetState(m_shader_wireframe, Renderer::eWireframeOnly); - - renderer.addRenderable(*this, g_matrix4_identity); -} - -void DVisDrawer::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!m_list) - return; - - renderer.SetState(m_shader_solid, Renderer::eWireframeOnly); - renderer.SetState(m_shader_solid, Renderer::eFullMaterials); - - renderer.addRenderable(*this, g_matrix4_identity); -} - -void DVisDrawer::SetList(std::list *pointList) -{ - if(m_list) - ClearPoints(); - - m_list = pointList; -} - -void DVisDrawer::ClearPoints() -{ - std::list::const_iterator deadPoint=m_list->begin(); - for(; deadPoint!=m_list->end(); deadPoint++) - delete *deadPoint; - m_list->clear(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DVisDrawer.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DVisDrawer.h deleted file mode 100644 index 83a80cb1..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DVisDrawer.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DBobView.h: interface for the DBobView class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_VISDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_VISDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 - -#pragma once -#endif // _MSC_VER > 1000 - -#include -#include "renderable.h" -#include "irender.h" - -#include "DWinding.h" - -class DVisDrawer : public Renderable, public OpenGLRenderable -{ - Shader* m_shader_solid; - Shader* m_shader_wireframe; -public: - DVisDrawer(); - virtual ~DVisDrawer(); - -protected: - std::list* m_list; - int refCount; -public: - void ClearPoints(); - void SetList(std::list* pointList); - - void render(RenderStateFlags state) const; - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; - - void constructShaders(); - void destroyShaders(); - -}; - -#endif // !defined(AFX_VISDRAWER_H__6E36062A_EF0B_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DWinding.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DWinding.cpp deleted file mode 100644 index 2068f3f8..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DWinding.cpp +++ /dev/null @@ -1,485 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DWinding.cpp: implementation of the DWinding class. -// -////////////////////////////////////////////////////////////////////// - -#include "DWinding.h" - -#include - -#include "DPoint.h" -#include "DPlane.h" - -////////////////////////////////////////////////////////////////////// -// Construction/Destruction -////////////////////////////////////////////////////////////////////// - -DWinding::DWinding() -{ - numpoints = 0; - p = NULL; -} - -DWinding::~DWinding() -{ - if(p) - delete[] p; -} - -////////////////////////////////////////////////////////////////////// -// Implementation -////////////////////////////////////////////////////////////////////// - -#define BOGUS_RANGE 4096 - -void DWinding::AllocWinding(int points) -{ - numpoints = points; - if(p) - delete[] p; - p = new vec3_t[points]; -} - -vec_t DWinding::WindingArea() -{ - vec3_t d1, d2, cross; - vec_t total; - - total = 0; - for (int i = 2; i < numpoints ; i++) - { - VectorSubtract (p[i-1], p[0], d1); - VectorSubtract (p[i], p[0], d2); - - CrossProduct (d1, d2, cross); - - total += 0.5f * VectorLength ( cross ); - } - - return total; -} - -void DWinding::RemoveColinearPoints() -{ - vec3_t p2[MAX_POINTS_ON_WINDING]; - - int nump = 0; - for (int i = 0; i < numpoints; i++) - { - int j = (i+1)%numpoints; - int k = (i+numpoints-1)%numpoints; - - vec3_t v1, v2; - VectorSubtract (p[j], p[i], v1); - VectorSubtract (p[i], p[k], v2); - VectorNormalize(v1, v1); - VectorNormalize(v2, v2); - - if (DotProduct(v1, v2) < 0.999) - { - VectorCopy (p[i], p2[nump]); - nump++; - } - } - - if (nump == numpoints) - return; - - AllocWinding(nump); - memcpy (p, p2, nump*sizeof(vec3_t)); -} - -DPlane* DWinding::WindingPlane() -{ - DPlane* newPlane = new DPlane(p[0], p[1], p[2], NULL); - return newPlane; -} - -void DWinding::WindingBounds(vec3_t mins, vec3_t maxs) -{ - if(numpoints == 0) - return; - - VectorCopy(mins, p[0]); - VectorCopy(maxs, p[0]); - - for (int i = 1; i < numpoints ;i++) - { - for (int j = 0; j < 3; j++) - { - vec_t v = p[i][j]; - if (v < mins[j]) - mins[j] = v; - if (v > maxs[j]) - maxs[j] = v; - } - } -} - -void DWinding::WindingCentre(vec3_t centre) -{ - VectorCopy (vec3_origin, centre); - for (int i = 0; i < numpoints; i++) - VectorAdd (p[i], centre, centre); - - float scale = 1.0f/numpoints; - VectorScale (centre, scale, centre); -} - - -DWinding* DWinding::CopyWinding() -{ - DWinding* c = new DWinding; - c->AllocWinding(numpoints); - memcpy (c->p, p, numpoints*sizeof(vec3_t)); - return c; -} - - -int DWinding::WindingOnPlaneSide(vec3_t normal, vec_t dist) -{ - bool front = false; - bool back = false; - - for (int i = 0; i < numpoints; i++) - { - vec_t d = DotProduct (p[i], normal) - dist; - if (d < -ON_EPSILON) - { - if (front) - return SIDE_CROSS; - back = true; - continue; - } - if (d > ON_EPSILON) - { - if (back) - return SIDE_CROSS; - front = true; - continue; - } - } - - if (back) - return SIDE_BACK; - if (front) - return SIDE_FRONT; - return SIDE_ON; -} - -void DWinding::CheckWinding() -{ - vec_t *p1, *p2; - vec_t edgedist; - vec3_t dir, edgenormal; - - if (numpoints < 3) - globalOutputStream() << "CheckWinding: " << numpoints << " points\n"; - - vec_t area = WindingArea(); - if (area < 1) - globalOutputStream() << "CheckWinding: " << area << " area\n"; - - DPlane* wPlane = WindingPlane (); - int i; - for (i = 0; i < numpoints; i++) - { - p1 = p[i]; - - int j; - for (j = 0; j < 3; j++) - if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE) - globalOutputStream() << "CheckFace: BOGUS_RANGE: " << p1[j] << "\n"; - - j = i + 1 == numpoints ? 0 : i + 1; - - // check the point is on the face plane - vec_t d = DotProduct (p1, wPlane->normal) - wPlane->_d; - if (d < -ON_EPSILON || d > ON_EPSILON) - globalOutputStream() << "CheckWinding: point off plane\n"; - - // check the edge isnt degenerate - p2 = p[j]; - VectorSubtract (p2, p1, dir); - - if (VectorLength (dir) < ON_EPSILON) - globalOutputStream() << "CheckWinding: degenerate edge\n"; - - CrossProduct (wPlane->normal, dir, edgenormal); - VectorNormalize (edgenormal, edgenormal); - edgedist = DotProduct (p1, edgenormal); - - // all other points must be on front side - for (j = 0 ; j < numpoints ; j++) - { - if (j == i) - continue; - - d = DotProduct (p[j], edgenormal); - if (d > (edgedist + ON_EPSILON)) - globalOutputStream() << "CheckWinding: non-convex\n"; - } - } - - delete wPlane; -} - -DWinding* DWinding::ReverseWinding() -{ - DWinding* c = new DWinding; - c->AllocWinding(numpoints); - - for (int i = 0; i < numpoints ; i++) - VectorCopy (p[numpoints-1-i], c->p[i]); - - return c; -} - -bool DWinding::ChopWindingInPlace(DPlane* chopPlane, vec_t epsilon) -{ - vec_t dists[MAX_POINTS_ON_WINDING+4]; - int sides[MAX_POINTS_ON_WINDING+4]; - int counts[3]; - vec_t *p1, *p2; - vec3_t mid; - - counts[0] = counts[1] = counts[2] = 0; - -// determine sides for each point - int i; - for (i = 0; i < numpoints; i++) - { - vec_t dot = DotProduct (p[i], chopPlane->normal); - dot -= chopPlane->_d; - 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]) - { - delete this; - return false; - } - - if (!counts[1]) - return true; - - int maxpts = numpoints+4; // cant use counts[0]+2 because - // of fp grouping errors - - DWinding* f = new DWinding; - f->AllocWinding(maxpts); - f->numpoints = 0; - - for (i = 0; i < numpoints; i++) - { - p1 = 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 = p[(i+1)%numpoints]; - - vec_t dot = dists[i] / (dists[i]-dists[i+1]); - for (int j = 0; j < 3; j++) - { - if (chopPlane->normal[j] == 1) - mid[j] = chopPlane->_d; - else if (chopPlane->normal[j] == -1) - mid[j] = -chopPlane->_d; - else - mid[j] = p1[j] + dot*(p2[j]-p1[j]); - } - - VectorCopy (mid, f->p[f->numpoints]); - f->numpoints++; - } - - if (f->numpoints > maxpts) - globalOutputStream() << "ClipWinding: points exceeded estimate\n"; - if (f->numpoints > MAX_POINTS_ON_WINDING) - globalOutputStream() << "ClipWinding: MAX_POINTS_ON_WINDING\n"; - - delete[] p; - p = f->p; - f->p = NULL; - delete f; - return true; -} - -void DWinding::ClipWindingEpsilon(DPlane* chopPlane, vec_t epsilon, DWinding **front, DWinding **back) -{ - vec_t dists[MAX_POINTS_ON_WINDING+4]; - int sides[MAX_POINTS_ON_WINDING+4]; - int counts[3]; - vec_t *p1, *p2; - vec3_t mid; - - counts[0] = counts[1] = counts[2] = 0; - -// determine sides for each point - int i; - for (i = 0; i < numpoints; i++) - { - vec_t dot = -chopPlane->DistanceToPoint(p[i]); - 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(); - return; - } - if (!counts[1]) - { - *front = CopyWinding(); - return; - } - - int maxpts = numpoints+4; // cant use counts[0]+2 because - // of fp grouping errors - - DWinding* f = new DWinding; - DWinding* b = new DWinding; - - f->AllocWinding(maxpts); - f->numpoints = 0; - - b->AllocWinding(maxpts); - b->numpoints = 0; - - *front = f; - *back = b; - - for (i = 0; i < numpoints ; i++) - { - p1 = 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 = p[(i+1)%numpoints]; - - vec_t dot = dists[i] / (dists[i]-dists[i+1]); - for (int j = 0; j < 3; j++) - { - if (chopPlane->normal[j] == 1) - mid[j] = chopPlane->_d; - else if (chopPlane->normal[j] == -1) - mid[j] = -chopPlane->_d; - 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) - globalOutputStream() << "ClipWinding: points exceeded estimate\n"; - if (f->numpoints > MAX_POINTS_ON_WINDING || b->numpoints > MAX_POINTS_ON_WINDING) - globalOutputStream() << "ClipWinding: MAX_POINTS_ON_WINDING\n"; -} - -bool DWinding::ChopWinding(DPlane* chopPlane) -{ - DWinding *f, *b; - - ClipWindingEpsilon (chopPlane, (float)ON_EPSILON, &f, &b); - - if (b) - delete (b); - - - if(!f) - { - delete this; - return false; - } - - delete[] p; - p = f->p; - f->p = NULL; - numpoints = f->numpoints; - delete f; - - return true; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DWinding.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DWinding.h deleted file mode 100644 index 52846aab..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/DWinding.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DWinding.h: interface for the DWinding class. -// -////////////////////////////////////////////////////////////////////// - -#if !defined(AFX_DWINDING_H__35B2C524_F0A7_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_DWINDING_H__35B2C524_F0A7_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 - -#include "mathlib.h" - -class DPlane; - -class DWinding -{ -public: - DWinding(); - virtual ~DWinding(); - - void AllocWinding(int points); - - bool ChopWinding(DPlane* chopPlane); - bool ChopWindingInPlace(DPlane* chopPlane, vec_t ON_EPSILON); - void ClipWindingEpsilon(DPlane* chopPlane, vec_t epsilon, DWinding** front, DWinding** back); - - void CheckWinding(); - void WindingCentre(vec3_t centre); - void WindingBounds(vec3_t mins, vec3_t maxs); - void RemoveColinearPoints(); - - DWinding* ReverseWinding(); - DWinding* CopyWinding(); - DPlane* WindingPlane(); - - int WindingOnPlaneSide(vec3_t normal, vec_t dist); - - vec_t WindingArea(); - -// members - int numpoints; - vec3_t* p; - vec3_t clr; -}; - -#define MAX_POINTS_ON_WINDING 64 - -#define ON_EPSILON 0.01 - -#endif // !defined(AFX_DWINDING_H__35B2C524_F0A7_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ScriptParser.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ScriptParser.cpp deleted file mode 100644 index 826613e4..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ScriptParser.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ScriptParser.h" -#include - -CScriptParser::CScriptParser(void): - m_pScript(NULL), - m_pScriptSection(NULL), - m_pLastScriptSection(NULL), - m_pToken(NULL) { - ClearBuffer(); -} - -CScriptParser::~CScriptParser(void) { - ClearBuffer(); -} - -void CScriptParser::ClearBuffer(void) { - if(m_pScript) { - delete[] m_pScript; - m_pScript = NULL; - } - if(m_pToken) { - delete[] m_pToken; - m_pToken = NULL; - } - m_pScriptSection = NULL; - m_pLastScriptSection = NULL; - memset(m_breakChars, 0, sizeof(m_breakChars)); -} - -const char* CScriptParser::MakeToken(const char* pToken) { - if(m_pToken) { - delete[] m_pToken; - m_pToken = NULL; - } - - if(!pToken) { - pToken = ""; - } - - int len = static_cast(strlen(pToken)); - - m_pToken = new char[len + 1]; - m_pToken[len] = '\0'; - strcpy(m_pToken, pToken); - - return m_pToken; -} - -#define MAX_TOKEN_STRING 1024 -// Should NEVER return NULL -const char* CScriptParser::GetToken(bool bAllowLinebreaks) { - int c = 0, len; - char token[MAX_TOKEN_STRING]; - bool bNewLines = false; - - m_pLastScriptSection = m_pScriptSection; - - len = 0; - *token = '\0'; - - if(!m_pScript || !m_pScriptSection) { - return MakeToken(token); - } - - while ( true ) { - SkipWhitespace( &bNewLines ); - if ( !*m_pScriptSection ) { - return MakeToken(token); - } - if ( bNewLines && !bAllowLinebreaks ) { - return MakeToken(token); - } - - c = *m_pScriptSection; - - if ( c == '/' && m_pScriptSection[1] == '/' ) { // C style comments - m_pScriptSection += 2; - while (*m_pScriptSection && *m_pScriptSection != '\n') { - m_pScriptSection++; - } - } else if ( c=='/' && m_pScriptSection[1] == '*' ) { // C++ style comments - m_pScriptSection += 2; - while ( *m_pScriptSection && ( *m_pScriptSection != '*' || m_pScriptSection[1] != '/' ) ) { - m_pScriptSection++; - } - if ( *m_pScriptSection ) { - m_pScriptSection += 2; - } - } else { - break; - } - } - - if (c == '\"') { - m_pScriptSection++; - while ( true ) { - c = *m_pScriptSection++; - if (c=='\"' || !c) { - token[len] = 0; - return MakeToken(token); - } - if (len < MAX_TOKEN_STRING) { - token[len] = c; - len++; - } - } - } - - do { - if(len > 0 && IsBreakChar(*m_pScriptSection)) { - break; - } - - if (len < MAX_TOKEN_STRING) { - token[len] = c; - len++; - } - m_pScriptSection++; - - if(IsBreakChar(c)) { - break; - } - - c = *m_pScriptSection; - } while (c > 32); - - if (len == MAX_TOKEN_STRING) { - len = 0; - } - token[len] = 0; - - return MakeToken(token); -} - -void CScriptParser::SkipWhitespace(bool* pbNewLines) { - int c; - - if(!m_pScript || !m_pScriptSection) { - return; - } - - while( (c = *m_pScriptSection) <= ' ') { - if( !c ) { - return; - } - if( c == '\n' ) { - *pbNewLines = true; - } - m_pScriptSection++; - } -} - -void CScriptParser::SkipBracedSection(void) { - const char *token; - int depth; - - depth = 0; - do { - token = GetToken( true ); - if( token[1] == 0 ) { - if( *token == '{' ) { - depth++; - } else if( *token == '}' ) { - depth--; - } - } - } while( depth && *m_pScriptSection ); -} - -void CScriptParser::SkipRestOfLine(void) { - char *p; - int c; - - p = m_pScriptSection; - while ( (c = *p++) != 0 ) { - if ( c == '\n' ) { - break; - } - } - m_pScriptSection = p; -} - -void CScriptParser::UndoGetToken(void) { - if(!m_pLastScriptSection) { - return; - } - m_pScriptSection = m_pLastScriptSection; - m_pLastScriptSection = NULL; -} - -void CScriptParser::ResetParseSession(void) { - if(!m_pScript) { - return; - } - - m_pScriptSection = m_pScript; - m_pLastScriptSection = NULL; -} - -char* CScriptParser::GetBufferCopy(void) { - if(!m_pScript) { - return NULL; - } - - int len = static_cast(strlen(m_pScript)); - char* pBuffer = new char[len + 1]; - strcpy(pBuffer, m_pScript); - return pBuffer; -} - -int CScriptParser::GetTokenOffset(void) { - if(!m_pScript || !m_pScriptSection) { - return 0; - } - - return static_cast(m_pScriptSection - m_pScript); -} - -void CScriptParser::LoadScript(const char* pScript) { - ClearBuffer(); - - int len = static_cast(strlen(pScript)); - if(len <= 0) { - return; - } - - m_pScript = new char[len + 1]; - m_pScript[len] = '\0'; - - strcpy(m_pScript, pScript); - m_pScriptSection = m_pScript; -} - -void CScriptParser::AddBreakChar(char c) { - for(int i = 0; i < SP_MAX_BREAKCHARS; i++) { - if(!m_breakChars[i]) { - m_breakChars[i] = c; - return; - } - } - - // TODO: Error: max break chars hit -} - -bool CScriptParser::IsBreakChar(char c) { - for(int i = 0; i < SP_MAX_BREAKCHARS; i++) { - if(!m_breakChars[i]) { - return false; - } - if(m_breakChars[i] == c) { - return true; - } - } - return false; -} - -void CScriptParser::SetScript(char* pScript) { - ClearBuffer(); - - int len = static_cast(strlen(pScript)); - if(len <= 0) { - return; - } - - m_pScript = pScript; - m_pScriptSection = m_pScript; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ScriptParser.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ScriptParser.h deleted file mode 100644 index 27eb6df7..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ScriptParser.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#ifndef _SCRIPTPARSER_H_ -#define _SCRIPTPARSER_H_ - -//#include "interfaces/IScriptParser.h" - -#define SP_MAX_BREAKCHARS 16 - -class CScriptParser //: public IScriptParser -{ -public: - CScriptParser(void); - ~CScriptParser(void); -private: - char m_breakChars[SP_MAX_BREAKCHARS]; - char* m_pScript; - char* m_pScriptSection; - char* m_pLastScriptSection; - char* m_pToken; - - void SkipWhitespace(bool* pbNewLines); - void ClearBuffer(void); - const char* MakeToken(const char* pToken); - bool IsBreakChar(char c); -public: - const char* GetToken(bool bAllowLinebreaks); - void SkipBracedSection(void); - void SkipRestOfLine(void); - void UndoGetToken(void); - void ResetParseSession(void); - - char* GetBufferCopy(void); - int GetTokenOffset(void); - - void LoadScript(const char* pScript); - void SetScript(char* pScript); - - void AddBreakChar(char c); -private: -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/StdAfx.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/StdAfx.cpp deleted file mode 100644 index 1a02f66b..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/StdAfx.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// stdafx.cpp : source file that includes just the standard includes -// plugin.pch will be the pre-compiled header -// stdafx.obj will contain the pre-compiled type information - -#include "StdAfx.h" - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/StdAfx.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/StdAfx.h deleted file mode 100644 index b8897f39..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/StdAfx.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef __STDAFX_BOBTOOLZ__ -#define __STDAFX_BOBTOOLZ__ - - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_caulk.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_caulk.bmp deleted file mode 100644 index 52239503..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_caulk.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_cleanup.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_cleanup.bmp deleted file mode 100644 index 33cc9490..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_cleanup.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_dropent.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_dropent.bmp deleted file mode 100644 index 2fcdcba3..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_dropent.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_merge.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_merge.bmp deleted file mode 100644 index cc5e272c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_merge.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_poly.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_poly.bmp deleted file mode 100644 index ed720e90..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_poly.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_split.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_split.bmp deleted file mode 100644 index fbb1571c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_split.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_trainpathplot.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_trainpathplot.bmp deleted file mode 100644 index 66537dc1..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_trainpathplot.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_treeplanter.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_treeplanter.bmp deleted file mode 100644 index 08f55f3c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_treeplanter.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_turnedge.bmp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_turnedge.bmp deleted file mode 100644 index b72cb2aa..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bitmaps/bobtoolz_turnedge.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz-GTK.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz-GTK.cpp deleted file mode 100644 index 78f4a5b3..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz-GTK.cpp +++ /dev/null @@ -1,356 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - - -#include "str.h" -#include "qerplugin.h" -#include "mathlib.h" -#include "string/string.h" -#include "itoolbar.h" - -#include "funchandlers.h" -#include "DBobView.h" -#include "DVisDrawer.h" -#include "DTrainDrawer.h" -#include "DTreePlanter.h" - -#include "dialogs/dialogs-gtk.h" -#include "../../libs/cmdlib.h" - -void BobToolz_construct() -{ -} - -void BobToolz_destroy() -{ - if(g_PathView) { - delete g_PathView; - g_PathView = NULL; - } - if(g_VisView) { - delete g_VisView; - g_VisView = NULL; - } - if(g_TrainView) { - delete g_TrainView; - g_TrainView = NULL; - } - if(g_TreePlanter) { - delete g_TreePlanter; - g_TreePlanter = NULL; - } -} - -// plugin name -char* PLUGIN_NAME = "bobToolz"; - -// commands in the menu -static char* PLUGIN_COMMANDS = "About...,-,Reset Textures...,PitOMatic,-,Vis Viewer,Brush Cleanup,Polygon Builder,Caulk Selection,-,Tree Planter,Drop Entity,Plot Splines,-,Merge Patches,Split patches,Split patches cols,Split patches rows,Turn edge"; - -// globals -GtkWidget *g_pRadiantWnd = NULL; - -static const char *PLUGIN_ABOUT = "bobToolz for SDRadiant\n" - "by digibob (digibob@splashdamage.com)\n" - "http://www.splashdamage.com\n\n" - "Additional Contributors:\n" - "MarsMattel, RR2DO2\n"; - -extern "C" const char* QERPlug_Init( void* hApp, void* pMainWidget ) { - g_pRadiantWnd = (GtkWidget*)pMainWidget; - - return "bobToolz for GTKradiant"; -} - -extern "C" const char* QERPlug_GetName() { - return PLUGIN_NAME; -} - -extern "C" const char* QERPlug_GetCommandList() { - return PLUGIN_COMMANDS; -} - -extern "C" void QERPlug_Dispatch (const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) { - LoadLists(); - - if( string_equal_nocase( p, "brush cleanup" ) ) { - DoFixBrushes(); - } else if( string_equal_nocase( p, "polygon builder" ) ) { - DoPolygonsTB(); - } else if( string_equal_nocase( p, "caulk selection" ) ) { - DoCaulkSelection(); - } else if( string_equal_nocase( p, "tree planter" ) ) { - DoTreePlanter(); - } else if( string_equal_nocase( p, "plot splines" ) ) { - DoTrainPathPlot(); - } else if( string_equal_nocase( p, "drop entity" ) ) { - DoDropEnts(); - } else if( string_equal_nocase( p, "merge patches" ) ) { - DoMergePatches(); - } else if( string_equal_nocase( p, "split patches" ) ) { - DoSplitPatch(); - } else if( string_equal_nocase( p, "split patches rows" ) ) { - DoSplitPatchRows(); - } else if( string_equal_nocase( p, "split patches cols" ) ) { - DoSplitPatchCols(); - } else if( string_equal_nocase( p, "turn edge" ) ) { - DoFlipTerrain(); - } else if( string_equal_nocase(p, "reset textures...") ) { - DoResetTextures(); - } else if( string_equal_nocase(p, "pitomatic") ) { - DoPitBuilder(); - } else if( string_equal_nocase(p, "vis viewer") ) { - DoVisAnalyse(); - } else if( string_equal_nocase(p, "stair builder...") ) { - DoBuildStairs(); - } else if( string_equal_nocase(p, "door builder...") ) { - DoBuildDoors(); - } else if( string_equal_nocase(p, "intersect...") ) { - DoIntersect(); - } else if( string_equal_nocase(p, "make chain...") ) { - DoMakeChain(); - } else if( string_equal_nocase(p, "path plotter...") ) { - DoPathPlotter(); - } else if( string_equal_nocase(p, "about...") ) { - DoMessageBox(PLUGIN_ABOUT, "About", eMB_OK); - } -} - -const char* QERPlug_GetCommandTitleList() -{ - return ""; -} - - -#define NUM_TOOLBARBUTTONS 14 - -std::size_t ToolbarButtonCount( void ) { - return NUM_TOOLBARBUTTONS; -} - -class CBobtoolzToolbarButton : public IToolbarButton -{ -public: - virtual const char* getImage() const - { - switch( mIndex ) { - case 0: return "bobtoolz_cleanup.bmp"; - case 1: return "bobtoolz_poly.bmp"; - case 2: return "bobtoolz_caulk.bmp"; - case 3: return ""; - case 4: return "bobtoolz_treeplanter.bmp"; - case 5: return "bobtoolz_trainpathplot.bmp"; - case 6: return "bobtoolz_dropent.bmp"; - case 7: return ""; - case 8: return "bobtoolz_merge.bmp"; - case 9: return "bobtoolz_split.bmp"; - case 10: return "bobtoolz_splitrow.bmp"; - case 11: return "bobtoolz_splitcol.bmp"; - case 12: return ""; - case 13: return "bobtoolz_turnedge.bmp"; - } - return NULL; - } - virtual EType getType() const - { - switch( mIndex ) { - case 3: return eSpace; - case 4: return eToggleButton; - case 7: return eSpace; - case 12: return eSpace; - default: return eButton; - } - } - virtual const char* getText() const - { - switch( mIndex ) { - case 0: return "Cleanup"; - case 1: return "Polygons"; - case 2: return "Caulk"; - case 4: return "Tree Planter"; - case 5: return "Plot Splines"; - case 6: return "Drop Entity"; - case 8: return "Merge 2 Patches"; - case 9: return "Split Patch"; - case 10: return "Split Patch Rows"; - case 11: return "Split Patch Columns"; - case 13: return "Flip Terrain"; - } - return NULL; - } - virtual const char* getTooltip() const - { - switch( mIndex ) { - case 0: return "Brush Cleanup"; - case 1: return "Polygons"; - case 2: return "Caulk selection"; - case 4: return "Tree Planter"; - case 5: return "Plot Splines"; - case 6: return "Drop Entity"; - case 8: return "Merge 2 Patches"; - case 9: return "Split Patch"; - case 10: return "Split Patch Rows"; - case 11: return "Split Patch Columns"; - case 13: return "Flip Terrain (Turn Edge)"; - } - return NULL; - } - - virtual void activate() const - { - LoadLists(); - - switch( mIndex ) { - case 0: DoFixBrushes(); break; - case 1: DoPolygonsTB(); break; - case 2: DoCaulkSelection(); break; - case 4: DoTreePlanter(); break; - case 5: DoTrainPathPlot(); break; - case 6: DoDropEnts(); break; - case 8: DoMergePatches(); break; - case 9: DoSplitPatch(); break; - case 10: DoSplitPatchRows(); break; - case 11: DoSplitPatchCols(); break; - case 13: DoFlipTerrain(); break; - } - } - - std::size_t mIndex; -}; - -CBobtoolzToolbarButton g_bobtoolzToolbarButtons[NUM_TOOLBARBUTTONS]; - -const IToolbarButton* GetToolbarButton(std::size_t index) -{ - g_bobtoolzToolbarButtons[index].mIndex = index; - return &g_bobtoolzToolbarButtons[index]; -} - - -#include "modulesystem/singletonmodule.h" - -#include "iscenegraph.h" -#include "irender.h" -#include "iundo.h" -#include "ishaders.h" -#include "ipatch.h" -#include "ibrush.h" -#include "ientity.h" -#include "ieclass.h" -#include "iglrender.h" -#include "iplugin.h" - -class BobToolzPluginDependencies : - public GlobalRadiantModuleRef, - public GlobalUndoModuleRef, - public GlobalSceneGraphModuleRef, - public GlobalSelectionModuleRef, - public GlobalEntityModuleRef, - public GlobalEntityClassManagerModuleRef, - public GlobalShadersModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalBrushModuleRef, - public GlobalPatchModuleRef, - public GlobalOpenGLModuleRef, - public GlobalOpenGLStateLibraryModuleRef -{ -public: - BobToolzPluginDependencies() : - GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities")), - GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")), - GlobalBrushModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("brushtypes")), - GlobalPatchModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("patchtypes")), - GlobalEntityClassManagerModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclass")) - { - } -}; - -class BobToolzPluginModule : public TypeSystemRef -{ - _QERPluginTable m_plugin; -public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "bobToolz"); - - BobToolzPluginModule() - { - m_plugin.m_pfnQERPlug_Init = QERPlug_Init; - m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; - m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - - BobToolz_construct(); - } - ~BobToolzPluginModule() - { - BobToolz_destroy(); - } - _QERPluginTable* getTable() - { - return &m_plugin; - } -}; - -typedef SingletonModule SingletonBobToolzPluginModule; - -SingletonBobToolzPluginModule g_BobToolzPluginModule; - - -class BobToolzToolbarDependencies : - public ModuleRef<_QERPluginTable> -{ -public: - BobToolzToolbarDependencies() : - ModuleRef<_QERPluginTable>("bobToolz") - { - } -}; - -class BobToolzToolbarModule : public TypeSystemRef -{ - _QERPlugToolbarTable m_table; -public: - typedef _QERPlugToolbarTable Type; - STRING_CONSTANT(Name, "bobToolz"); - - BobToolzToolbarModule() - { - m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; - m_table.m_pfnGetToolbarButton = GetToolbarButton; - } - _QERPlugToolbarTable* getTable() - { - return &m_table; - } -}; - -typedef SingletonModule SingletonBobToolzToolbarModule; - -SingletonBobToolzToolbarModule g_BobToolzToolbarModule; - - -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - - g_BobToolzPluginModule.selfRegister(); - g_BobToolzToolbarModule.selfRegister(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.def b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.def deleted file mode 100644 index 74f9189b..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.def +++ /dev/null @@ -1,8 +0,0 @@ -; plugin.def : Declares the module parameters for the DLL. - -LIBRARY "bobToolz" -; DESCRIPTION 'bobToolz Windows Dynamic Link Library' - -EXPORTS - ; Explicit exports can go here - Radiant_RegisterModules @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.h deleted file mode 100644 index 6101e877..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// plugin.h : main header file for the PLUGIN DLL -// - -#if !defined(AFX_PLUGIN_H__3BA55F6A_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_) -#define AFX_PLUGIN_H__3BA55F6A_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_ - -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 - -#ifndef __AFXWIN_H__ - #error include 'StdAfx.h' before including this file for PCH -#endif - -#include "resource.h" // main symbols - -///////////////////////////////////////////////////////////////////////////// -// CPluginApp -// See plugin.cpp for the implementation of this class -// - -class CPluginApp : public CWinApp -{ -public: - CPluginApp(); - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CPluginApp) - //}}AFX_VIRTUAL - - //{{AFX_MSG(CPluginApp) - // NOTE - the ClassWizard will add and remove member functions here. - // DO NOT EDIT what you see in these blocks of generated code ! - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - - -///////////////////////////////////////////////////////////////////////////// - -//{{AFX_INSERT_LOCATION}} -// Microsoft Developer Studio will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_PLUGIN_H__3BA55F6A_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.rc b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.rc deleted file mode 100644 index 4abed936..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobToolz.rc +++ /dev/null @@ -1,533 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "resource.h" -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,1,1,0 - PRODUCTVERSION 2,0,0,0 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "080904b0" - BEGIN - VALUE "Comments", "by djbob :P and MarsMattel ~:]\0" - VALUE "CompanyName", "bobCo\0" - VALUE "FileDescription", "All your plugins are belong to us\0" - VALUE "FileVersion", "1, 1, 1, 0\0" - VALUE "InternalName", "bobToolz\0" - VALUE "LegalCopyright", "Copyright (C) y2k\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "bobToolz.DLL\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "\0" - VALUE "ProductVersion", "2, 0, 0, 0\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x809, 1200 - END -END - -#endif // !_MAC - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// Neutral (Sys. Default) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEUSD) -#ifdef _WIN32 -LANGUAGE LANG_NEUTRAL, SUBLANG_SYS_DEFAULT -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_ABOUT DIALOG DISCARDABLE 0, 0, 361, 118 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "About" -FONT 8, "Arial" -BEGIN - DEFPUSHBUTTON "OK",IDOK,305,100,50,14 - CTEXT "BobToolz - Q3radiant version by djbob &&&& Mars Mattel", - IDC_STATIC,5,5,350,14,SS_CENTERIMAGE - CTEXT "Latest Version Can Be Found At http://djbob.fortefide.com", - IDC_STATIC,5,20,350,15,SS_CENTERIMAGE - LTEXT "Random bobToolz comments:",IDC_STATIC,5,35,355,10 - CTEXT "Texture Alignments Are Irrelevant, You Will Be Caulked\n-QPSiren\nCaulk Me Baby One More Time\n-TTimo\nWe're Up The Creek Without A Penguin\n-Mars Mattel", - IDC_STATIC,5,45,355,50 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_ABOUT, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 354 - TOPMARGIN, 7 - BOTTOMMARGIN, 111 - END -END -#endif // APSTUDIO_INVOKED - -#endif // Neutral (Sys. Default) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.K.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_STAIR_DIALOG DIALOG DISCARDABLE 0, 0, 246, 118 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Stair Designer" -FONT 8, "Arial" -BEGIN - DEFPUSHBUTTON "OK",IDOK,189,83,50,12 - PUSHBUTTON "Cancel",IDCANCEL,189,99,50,12 - EDITTEXT IDC_EDIT1,5,5,86,12,ES_AUTOHSCROLL - LTEXT "Stair Height",IDC_STATIC,95,5,42,15,SS_CENTERIMAGE - GROUPBOX "Direction",IDC_STATIC,7,26,85,64 - CONTROL "North",IDC_DIR_N_RADIO,"Button",BS_AUTORADIOBUTTON | - WS_GROUP,14,38,33,10 - CONTROL "South",IDC_DIR_S_RADIO,"Button",BS_AUTORADIOBUTTON,14, - 50,35,10 - CONTROL "East",IDC_DIR_E_RADIO,"Button",BS_AUTORADIOBUTTON,14,62, - 30,10 - CONTROL "West",IDC_DIR_W_RADIO,"Button",BS_AUTORADIOBUTTON,14,74, - 33,10 - GROUPBOX "Style",IDC_STATIC,97,26,82,49 - CONTROL "Original",IDC_STYLE_ORIG_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_GROUP,105,35,39,10 - CONTROL "Bob's Style",IDC_STYLE_BOB_RADIO,"Button", - BS_AUTORADIOBUTTON,105,47,51,10 - CONTROL "Corner",IDC_STYLE_CORNER_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_DISABLED,105,59,51,10 - EDITTEXT IDC_RISER_EDIT,7,99,85,12,ES_AUTOHSCROLL - LTEXT "Riser Texture",IDC_STATIC,95,100,60,11,SS_CENTERIMAGE - CONTROL "Use Detail Brushes",IDC_DETAIL_CHK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,100,80,75,10 -END - -IDD_POLYGON_DIALOG DIALOG DISCARDABLE 0, 0, 271, 68 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Polygon Builder" -FONT 8, "Arial" -BEGIN - PUSHBUTTON "OK",IDOK,150,50,50,14 - PUSHBUTTON "Cancel",IDCANCEL,215,50,50,14 - EDITTEXT IDC_EDIT1,7,7,76,13,ES_AUTOHSCROLL - LTEXT "Number Of Sides",IDC_STATIC,85,7,60,13,SS_CENTERIMAGE - CONTROL "Inverse Polygon",IDC_INVERSE_CHK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,149,21,75,10 - CONTROL "Use Border",IDC_BORDER_CHK,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,149,7,66,10 - EDITTEXT IDC_BORDER_EDIT,7,28,76,13,ES_AUTOHSCROLL - LTEXT "Border Size",IDC_STATIC,86,28,60,13,SS_CENTERIMAGE - CONTROL "Align Top Edge",IDC_ALIGN_CHK,"Button",BS_AUTOCHECKBOX | - WS_TABSTOP,149,35,75,10 -END - -IDD_DOOR_DIALOG DIALOG DISCARDABLE 0, 0, 327, 119 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Door Builder" -FONT 8, "Arial" -BEGIN - DEFPUSHBUTTON "OK",IDOK,270,7,50,14 - PUSHBUTTON "Cancel",IDCANCEL,270,24,50,14 - EDITTEXT IDC_FBTEXTURE_EDIT,7,7,125,14,ES_AUTOHSCROLL - LTEXT "Door Front/Back Texture",IDC_STATIC,137,7,86,14, - SS_CENTERIMAGE - EDITTEXT IDC_TRIMTEXTURE_EDIT,7,26,125,14,ES_AUTOHSCROLL - LTEXT "Door Trim Texture",IDC_STATIC,137,26,86,14, - SS_CENTERIMAGE - CONTROL "Scale Main Texture Horizontally",IDC_TEXSCALE1_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,46,115,10 - CONTROL "Scale Main Texture Vertically",IDC_TEXSCALE2_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,60,107,10 - CONTROL "Scale Trim Texture Horizontally",IDC_TEXSCALE3_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,136,46,113,10 - CONTROL "Scale Trim Texture Vertically",IDC_TEXSCALE4_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,136,60,105,10 - COMBOBOX IDC_MAINTEX_COMBO,7,76,126,30,CBS_DROPDOWN | CBS_SORT | - WS_VSCROLL | WS_TABSTOP - COMBOBOX IDC_TRIMTEX_COMBO,7,99,126,30,CBS_DROPDOWN | CBS_SORT | - WS_VSCROLL | WS_TABSTOP - PUSHBUTTON "Set As Main Texture",IDC_SET_MAINTEX_BTN,139,76,82,14 - PUSHBUTTON "Set As Trim Texture",IDC_SET_TRIMTEX_BTN,139,98,82,14 - GROUPBOX "Orientation",IDC_DIR_GROUP,225,72,95,40 - CONTROL "North - South",IDC_DIR_NS_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_GROUP,230,82,85,10 - CONTROL "East - West",IDC_DIR_EW_RADIO,"Button", - BS_AUTORADIOBUTTON,230,97,85,10 -END - -IDD_INTERSECT_DIALOG DIALOG DISCARDABLE 0, 0, 245, 58 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Intersecting Brush Finder" -FONT 8, "Arial" -BEGIN - DEFPUSHBUTTON "OK",IDOK,130,40,50,14 - PUSHBUTTON "Cancel",IDCANCEL,185,40,50,14 - CONTROL "Include Detail Brushes",IDC_DETAIL_INCLUDE_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,130,10,111,10 - GROUPBOX "Brush Options",IDC_STATIC,10,5,111,45 - CONTROL "Use Whole Map",IDC_WHOLEMAP_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_GROUP,15,15,95,10 - CONTROL "Use Selected Brushes",IDC_SELECTED_RADIO,"Button", - BS_AUTORADIOBUTTON,15,30,95,10 - CONTROL "Only Select Duplicate Brushes",IDC_DUPLICATEONLY_CHECK, - "Button",BS_AUTOCHECKBOX | WS_TABSTOP,130,25,113,10 -END - -IDD_INTERSECT_INFO_DIALOG DIALOG DISCARDABLE 0, 0, 187, 33 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Progress1",IDC_PROGRESS1,"msctls_progress32",PBS_SMOOTH, - 5,15,175,10 - CTEXT "Brush Loading",IDC_STATIC,5,5,175,10,SS_CENTERIMAGE -END - -IDD_BRUSHCHECKER_DIALOG DIALOG DISCARDABLE 0, 0, 182, 38 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Progress1",IDC_PROGRESS1,"msctls_progress32",PBS_SMOOTH, - 5,21,172,10 - CTEXT "Checking Brushes",IDC_STATIC,5,5,170,15,SS_CENTERIMAGE -END - -IDD_AUTOCAULK_DIALOG DIALOG DISCARDABLE 0, 0, 187, 52 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE -FONT 8, "MS Sans Serif" -BEGIN - CONTROL "Progress1",IDC_PROGRESS1,"msctls_progress32",PBS_SMOOTH, - 5,15,175,10 - CTEXT "Loading Portal Data",IDC_STATIC,5,5,175,10, - SS_CENTERIMAGE - CONTROL "Progress1",IDC_PROGRESS2,"msctls_progress32",PBS_SMOOTH, - 5,35,175,10 - CTEXT "Auto Caulking",IDC_STATIC,5,25,175,10,SS_CENTERIMAGE -END - -IDD_AUTOCAULKSTART_DIALOG DIALOG DISCARDABLE 0, 0, 237, 83 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Auto Caulk" -FONT 8, "Arial" -BEGIN - DEFPUSHBUTTON "OK",IDOK,125,10,50,14 - PUSHBUTTON "Cancel",IDCANCEL,180,10,50,14 - CONTROL "Destroy Invisible Brushes",IDC_KILLBRUSHES_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,125,50,95,10 - LTEXT "",IDC_WARNING1_STATIC,5,65,223,11,NOT WS_GROUP - GROUPBOX "Static",IDC_STATIC,5,5,115,57 - CONTROL "Autocaulk",IDC_AC_NORMAL_RADIO,"Button", - BS_AUTORADIOBUTTON | WS_GROUP,10,15,48,10 - CONTROL "Build Mini Prt",IDC_AC_BUILD_MINI_PRT_RADIO,"Button", - BS_AUTORADIOBUTTON,10,30,56,10 - CONTROL "Autocaulk+ (Detail Brushes)",IDC_AC_SUPER_RADIO,"Button", - BS_AUTORADIOBUTTON,10,45,106,10 -END - -IDD_TEXTURE_RESET_DIALOG DIALOG DISCARDABLE 0, 0, 272, 107 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Texture Reset" -FONT 8, "Arial" -BEGIN - DEFPUSHBUTTON "OK",IDOK,160,85,50,14 - PUSHBUTTON "Cancel",IDCANCEL,215,85,50,14 - EDITTEXT IDC_RESET_TEXTURE_EDIT,5,5,118,14,ES_AUTOHSCROLL - EDITTEXT IDC_SCL_VERT_EDIT,85,45,40,14,ES_AUTOHSCROLL - EDITTEXT IDC_SCL_HOR_EDIT,85,65,40,14,ES_AUTOHSCROLL - EDITTEXT IDC_ROTATION_EDIT,85,85,40,14,ES_AUTOHSCROLL - EDITTEXT IDC_SHFT_VER_EDIT,225,45,40,14,ES_AUTOHSCROLL - EDITTEXT IDC_SHFT_HOR_EDIT,225,65,40,14,ES_AUTOHSCROLL - RTEXT "Scale::Vertical",IDC_STATIC,5,45,75,15,SS_CENTERIMAGE - RTEXT "Scale::Horizontal",IDC_STATIC,5,65,75,15,SS_CENTERIMAGE - RTEXT "Rotation",IDC_STATIC,5,85,75,15,SS_CENTERIMAGE - RTEXT "Shift::Horizontal",IDC_STATIC,160,65,60,15, - SS_CENTERIMAGE - RTEXT "Shift::Vertical",IDC_STATIC,160,45,60,15,SS_CENTERIMAGE - LTEXT "Texture To Reset",IDC_STATIC,128,5,62,15,SS_CENTERIMAGE - CONTROL "Reset All Textures",IDC_ALLTEXTURES_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,195,5,75,15 - EDITTEXT IDC_RESET_NEW_TEXTURE_EDIT,5,25,118,14,ES_AUTOHSCROLL - LTEXT "New Texture Name",IDC_STATIC,128,25,62,15, - SS_CENTERIMAGE - CONTROL "Reset Texture Only",IDC_ONLYTEXTURE_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,195,25,75,15 -END - -IDD_PATHPLOTTER_DIALOG DIALOG DISCARDABLE 0, 0, 172, 113 -STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Path Plotter" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "Enable",IDYES,5,92,50,14 - PUSHBUTTON "Cancel",IDCANCEL,115,92,50,14 - PUSHBUTTON "Disable",IDNO,60,92,50,14 - EDITTEXT IDC_POINTCOUNT_EDIT,5,5,80,14,ES_AUTOHSCROLL - EDITTEXT IDC_MULTIPLIER_EDIT,5,25,80,14,ES_AUTOHSCROLL - EDITTEXT IDC_GRAVITY_EDIT,5,45,80,14,ES_AUTOHSCROLL - LTEXT "Number Of Points",IDC_STATIC,90,5,60,15,SS_CENTERIMAGE - CONTROL "No Dynamic Update",IDC_NOUPDATE_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,7,65,80,10 - LTEXT "Multiplier",IDC_STATIC,90,25,60,15,SS_CENTERIMAGE - LTEXT "Gravity",IDC_STATIC,90,45,60,15,SS_CENTERIMAGE - CONTROL "Show Bounding Lines",IDC_SHOWEXTRA_CHECK,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,7,79,85,10 -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_STAIR_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 239 - TOPMARGIN, 7 - BOTTOMMARGIN, 111 - END - - IDD_POLYGON_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 264 - TOPMARGIN, 7 - BOTTOMMARGIN, 61 - END - - IDD_DOOR_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 320 - TOPMARGIN, 7 - BOTTOMMARGIN, 112 - END - - IDD_INTERSECT_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 238 - TOPMARGIN, 7 - BOTTOMMARGIN, 51 - END - - IDD_INTERSECT_INFO_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 180 - TOPMARGIN, 7 - BOTTOMMARGIN, 25 - END - - IDD_BRUSHCHECKER_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 175 - TOPMARGIN, 7 - BOTTOMMARGIN, 31 - END - - IDD_AUTOCAULK_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 180 - TOPMARGIN, 7 - BOTTOMMARGIN, 45 - END - - IDD_AUTOCAULKSTART_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 230 - TOPMARGIN, 7 - BOTTOMMARGIN, 76 - END - - IDD_TEXTURE_RESET_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 265 - TOPMARGIN, 7 - BOTTOMMARGIN, 100 - END - - IDD_PATHPLOTTER_DIALOG, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 165 - TOPMARGIN, 7 - BOTTOMMARGIN, 106 - END -END -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog Info -// - -IDD_DOOR_DIALOG DLGINIT -BEGIN - IDC_MAINTEX_COMBO, 0x403, 25, 0 -0x6162, 0x6573, 0x645f, 0x6f6f, 0x2f72, 0x6873, 0x6e69, 0x6d79, 0x7465, -0x6c61, 0x6f64, 0x726f, "\000" - IDC_MAINTEX_COMBO, 0x403, 33, 0 -0x6162, 0x6573, 0x645f, 0x6f6f, 0x2f72, 0x6873, 0x6e69, 0x6d79, 0x7465, -0x6c61, 0x6f64, 0x726f, 0x6f5f, 0x7475, 0x6973, 0x6564, "\000" - IDC_MAINTEX_COMBO, 0x403, 36, 0 -0x6162, 0x6573, 0x645f, 0x6f6f, 0x2f72, 0x6873, 0x6e69, 0x6d79, 0x7465, -0x6c61, 0x6f64, 0x726f, 0x6f5f, 0x7475, 0x6973, 0x6564, 0x6133, 0x0032, - - IDC_MAINTEX_COMBO, 0x403, 24, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x625f, 0x6572, 0x0064, - IDC_MAINTEX_COMBO, 0x403, 31, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x625f, 0x6572, 0x3264, 0x735f, 0x6968, 0x796e, "\000" - IDC_MAINTEX_COMBO, 0x403, 32, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x655f, 0x6c62, 0x6575, 0x5f32, 0x6873, 0x6e69, 0x0079, - IDC_MAINTEX_COMBO, 0x403, 33, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x695f, 0x6f5f, 0x6e72, 0x7461, 0x3565, 0x665f, 0x6e69, "\000" - IDC_MAINTEX_COMBO, 0x403, 21, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x6a5f, "\000" - IDC_MAINTEX_COMBO, 0x403, 22, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x6a5f, 0x0033, - IDC_MAINTEX_COMBO, 0x403, 22, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x6a5f, 0x0034, - IDC_MAINTEX_COMBO, 0x403, 23, 0 -0x6f67, 0x6874, 0x6369, 0x645f, 0x6f6f, 0x2f72, 0x6f64, 0x726f, 0x3230, -0x6b5f, 0x6232, "\000" - IDC_TRIMTEX_COMBO, 0x403, 26, 0 -0x6162, 0x6573, 0x735f, 0x7075, 0x6f70, 0x7472, 0x732f, 0x7075, 0x6f70, -0x7472, 0x7231, 0x7375, 0x0074, - IDC_TRIMTEX_COMBO, 0x403, 27, 0 -0x6162, 0x6573, 0x735f, 0x7075, 0x6f70, 0x7472, 0x732f, 0x7075, 0x6f70, -0x7472, 0x7331, 0x6968, 0x796e, "\000" - IDC_TRIMTEX_COMBO, 0x403, 26, 0 -0x6162, 0x6573, 0x735f, 0x7075, 0x6f70, 0x7472, 0x732f, 0x7075, 0x6f70, -0x7472, 0x7232, 0x7375, 0x0074, - IDC_TRIMTEX_COMBO, 0x403, 22, 0 -0x6162, 0x6573, 0x735f, 0x7075, 0x6f70, 0x7472, 0x772f, 0x6c70, 0x7461, -0x5f31, 0x0031, - IDC_TRIMTEX_COMBO, 0x403, 22, 0 -0x6162, 0x6573, 0x735f, 0x7075, 0x6f70, 0x7472, 0x702f, 0x616c, 0x6574, -0x5f32, 0x0035, - 0 -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""resource.h""\r\n" - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.K.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobtoolz-gtk.rc b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobtoolz-gtk.rc deleted file mode 100644 index 1d401e10..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bobtoolz-gtk.rc +++ /dev/null @@ -1,109 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource-gtk.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.K.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource-gtk.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,1,1,0 - PRODUCTVERSION 2,0,0,0 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "080904b0" - BEGIN - VALUE "Comments", "by djbob :P and MarsMattel ~:)\0" - VALUE "CompanyName", "bobCo\0" - VALUE "FileDescription", "All your plugins are belong to us\0" - VALUE "FileVersion", "1, 1, 1, 0\0" - VALUE "InternalName", "bobToolz GTK\0" - VALUE "LegalCopyright", "Copyright © 2001\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "bobToolz.dll\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "bobCo bobToolz\0" - VALUE "ProductVersion", "2, 0, 0, 0\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x809, 1200 - END -END - -#endif // !_MAC - -#endif // English (U.K.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bsploader.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bsploader.cpp deleted file mode 100644 index 287c5fff..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bsploader.cpp +++ /dev/null @@ -1,263 +0,0 @@ -#include "bsploader.h" -#include "dialogs/dialogs-gtk.h" -#include "cmdlib.h" - -int numnodes; -int numplanes; -int numleafs; -int numleafsurfaces; -int numVisBytes; -int numDrawVerts; -int numDrawSurfaces; -int numbrushes; -int numbrushsides; -int numleafbrushes; - -byte *visBytes = NULL; -dnode_t *dnodes = NULL; -dplane_t *dplanes = NULL; -dleaf_t *dleafs = NULL; -qdrawVert_t *drawVerts = NULL; -dsurface_t *drawSurfaces = NULL; -int *dleafsurfaces = NULL; -dbrush_t *dbrushes = NULL; -dbrushside_t *dbrushsides = NULL; -int *dleafbrushes = NULL; - -#define BSP_IDENT (('P'<<24)+('S'<<16)+('B'<<8)+'I') -#define Q3_BSP_VERSION 46 -#define WOLF_BSP_VERSION 47 - -/* -================ -FileLength -================ -*/ -int 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; -} - -/* -============== -LoadFile -============== -*/ -bool LoadFile( const char *filename, byte **bufferptr) -{ - FILE *f; - int length; - byte *buffer; - - f = fopen(filename, "rb"); - if(!f) - return false; - - length = FileLength (f); - buffer = new byte[length+1]; - buffer[length] = 0; - fread(buffer, 1, length, f); - fclose (f); - - *bufferptr = buffer; - return true; -} - -int LittleLong (int l) -{ -#if defined(__BIG_ENDIAN__) - std::reverse(reinterpret_cast(&l), reinterpret_cast(&l) + sizeof(int)); -#endif - return l; -} - -float LittleFloat (float l) -{ -#if defined(__BIG_ENDIAN__) - std::reverse(reinterpret_cast(&l), reinterpret_cast(&l) + sizeof(float)); -#endif - return l; -} - -/* -============= -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 ); -// } -} - -/* -============= -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; - - *dest = new byte[length]; - memcpy( *dest, (byte *)header + ofs, length ); - - return length / size; -} - -/* -============= -LoadBSPFile -============= -*/ -bool LoadBSPFile( const char *filename ) { - dheader_t *header; - - // load the file header - if(!LoadFile (filename, (byte **)&header)) - return false; - - // swap the header - SwapBlock( (int *)header, sizeof(*header) ); - - if ( header->ident != BSP_IDENT ) { - DoMessageBox( "Cant find a valid IBSP file", "Error", eMB_OK); - return false; - } - if ( (header->version != Q3_BSP_VERSION) && - (header->version != WOLF_BSP_VERSION) ) { - DoMessageBox( "File is incorrect version", "Error", eMB_OK); - return false; - } - - numbrushsides = CopyLump( header, LUMP_BRUSHES, (void**)&dbrushsides, sizeof(dbrushside_t) ); - numbrushes = CopyLump( header, LUMP_BRUSHES, (void**)&dbrushes, sizeof(dbrush_t) ); - numplanes = CopyLump( header, LUMP_PLANES, (void**)&dplanes, sizeof(dplane_t) ); - numleafs = CopyLump( header, LUMP_LEAFS, (void**)&dleafs, sizeof(dleaf_t) ); - numnodes = CopyLump( header, LUMP_NODES, (void**)&dnodes, sizeof(dnode_t) ); - numDrawVerts = CopyLump( header, LUMP_DRAWVERTS, (void**)&drawVerts, sizeof(qdrawVert_t) ); - numDrawSurfaces = CopyLump( header, LUMP_SURFACES, (void**)&drawSurfaces, sizeof(dsurface_t) ); - numleafsurfaces = CopyLump( header, LUMP_LEAFSURFACES, (void**)&dleafsurfaces, sizeof(int) ); - numVisBytes = CopyLump( header, LUMP_VISIBILITY, (void**)&visBytes, 1 ); - numleafbrushes = CopyLump( header, LUMP_LEAFBRUSHES, (void**)&dleafbrushes, sizeof(int) ); - - delete header; // everything has been copied out - - // swap everything - SwapBSPFile(); - - return true; -} - -void FreeBSPData() -{ - if(visBytes) - delete visBytes; - if(dnodes) - delete dnodes; - if(dplanes) - delete dplanes; - if(dleafs) - delete dleafs; - if(drawVerts) - delete drawVerts; - if(drawSurfaces) - delete drawSurfaces; - if(dleafsurfaces) - delete dleafsurfaces; - if(dleafbrushes) - delete dleafbrushes; - if(dbrushes) - delete dbrushes; - if(dbrushsides) - delete dbrushsides; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bsploader.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bsploader.h deleted file mode 100644 index 3cea233b..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bsploader.h +++ /dev/null @@ -1,137 +0,0 @@ - -#include "mathlib.h" - -#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 fileofs, filelen; -} lump_t; - -typedef struct { - int ident; - int version; - - lump_t lumps[HEADER_LUMPS]; -} dheader_t; - -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 { - vec3_t xyz; - float st[2]; - float lightmap[2]; - vec3_t normal; - byte color[4]; -} qdrawVert_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; - -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 enum { - MST_BAD, - MST_PLANAR, - MST_PATCH, - MST_TRIANGLE_SOUP, - MST_FLARE -} mapSurfaceType_t; - -#define MAX_MAP_VISIBILITY 0x200000 -#define MAX_MAP_NODES 0x20000 -#define MAX_MAP_PLANES 0x20000 -#define MAX_MAP_LEAFS 0x20000 - -extern int numVisBytes; -extern int numleafs; -extern int numplanes; -extern int numnodes; -extern int numDrawVerts; -extern int numDrawSurfaces; -extern int numleafsurfaces; -extern int numbrushes; -extern int numbrushsides; -extern int numleafbrushes; - -extern dnode_t *dnodes; -extern dplane_t *dplanes; -extern dleaf_t *dleafs; -extern byte *visBytes; -extern qdrawVert_t *drawVerts; -extern dsurface_t *drawSurfaces; -extern int *dleafsurfaces; -extern dbrush_t *dbrushes; -extern dbrushside_t *dbrushsides; -extern int *dleafbrushes; - -bool LoadBSPFile( const char *filename ); -void FreeBSPData(); diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/bt-el1.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/bt-el1.txt deleted file mode 100644 index f6485f94..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/bt-el1.txt +++ /dev/null @@ -1,17 +0,0 @@ -common/areaportal -common/clip -common/clusterportal -common/cushion -common/donotenter -common/full_clip -common/hint -common/missileclip -common/nodraw -common/nodrawnonsolid -common/nodrop -common/noimpact -common/origin -common/trigger -common/weapclip -liquid -fog \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/bt-el2.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/bt-el2.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/ctf-blue.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/ctf-blue.txt deleted file mode 100644 index 5a5f6ca3..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/ctf-blue.txt +++ /dev/null @@ -1,61 +0,0 @@ -base_light/light1blue_2000 -base_light/light1blue_5000 -ctf/blue_telep -ctf/ctf_blueflag -ctf/ctf_tower_bluefin_shiny -gothic_door/door02_eblue2_shiny -gothic_light/ironcrossltblue_10000 -gothic_light/ironcrossltblue_2000 -gothic_light/ironcrossltblue_20000 -gothic_light/ironcrossltblue_3000 -gothic_light/ironcrossltblue_30000 -gothic_light/ironcrossltblue_4000 -gothic_light/ironcrossltblue_5000 -sfx/beam_blue -sfx/flameanim_blue -sfx/flameanim_blue_nolight -sfx/flameanim_blue_pj -sfx/mkc_fog_ctfblue -sfx/xbluefog -base_wall2/blue_metal -base_wall2/jumppad_blue_kc -base_wall2/blue_line -base_wall2/double_line_blue -base_wall2/blue_arrow_small -base_wall2/blue_circle -base_wall2/bluearrows -base_wall2/blue_solid -ctf2/blueteam01 -ctf2/blueteam02 -ctf2/xblueteam01 -ctf2/blue_banner02 -proto2/blueflag -proto2/blueob -proto2/marbledoor_blue -proto2/concrete_bluenfx -proto2/bluelight_on -proto2/bsbluelight_on -proto2/rsbluelight_off -proto2/bsbluelight_off -proto2/rsbluelight_on -proto2/bluetrim01 -proto2/blue_zot -proto2/blue_zot2 -proto2/bluea_dcl -proto2/concrete_blue -proto2/teamwerkz_blue1 -proto2/blueflare2 -proto2/blueflare -sfx2/flameanim_blue_lowlite -sfx2/blue_jumpad05 -sfx2/blue_launchpad -sfx2/blue_jumpad -sfx2/blue_jumpad2 -sfx2/blue_jumpad3 -sfx2/bluegoal2 -tim/blue_flagbase -team_icon/the fallen_blue -team_icon/intruders_blue -team_icon/crusaders_blue -team_icon/pagans_blue -team_icon/stroggs_blue \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/ctf-red.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/ctf-red.txt deleted file mode 100644 index 8dec85e7..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/ctf-red.txt +++ /dev/null @@ -1,61 +0,0 @@ -base_light/light1red_2000 -base_light/light1red_5000 -ctf/red_telep -ctf/ctf_redflag -ctf/ctf_tower_redfin_shiny -gothic_door/door02_bred2_shiny -gothic_light/ironcrossltred_10000 -gothic_light/ironcrossltred_2000 -gothic_light/ironcrossltred_20000 -gothic_light/ironcrossltred_3000 -gothic_light/ironcrossltred_30000 -gothic_light/ironcrossltred_4000 -gothic_light/ironcrossltred_5000 -sfx/beam_red -sfx/flameanim_red -sfx/flameanim_red_nolight -sfx/flameanim_red_pj -sfx/mkc_fog_ctfred -sfx/xredfog -base_wall2/red_metal -base_wall2/jumppad_red_kc -base_wall2/red_line -base_wall2/double_line_red -base_wall2/red_arrow_small -base_wall2/red_circle -base_wall2/redarrows -base_wall2/red_solid -ctf2/redteam01 -ctf2/redteam02 -ctf2/xredteam01x -ctf2/red_banner02 -proto2/redflag -proto2/redob -proto2/marbledoor_red -proto2/concrete_rednfx -proto2/redlight_on -proto2/bsredlight_on -proto2/rsredlight_off -proto2/bsredlight_off -proto2/rsredlight_on -proto2/redtrim01 -proto2/red_zot -proto2/red_zot2 -proto2/reda_dcl -proto2/concrete_red -proto2/teamwerkz_red1 -proto2/redflare2 -proto2/redflare -sfx2/flameanim_red_lowlite -sfx2/red_jumpad05 -sfx2/red_launchpad -sfx2/red_jumpad -sfx2/red_jumpad2 -sfx2/red_jumpad3 -sfx2/redgoal2 -tim/red_flagbase -team_icon/the fallen_red -team_icon/intruders_red -team_icon/crusaders_red -team_icon/pagans_red -team_icon/stroggs_red \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/door-tex-trim.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/door-tex-trim.txt deleted file mode 100644 index d52ef76f..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/door-tex-trim.txt +++ /dev/null @@ -1,5 +0,0 @@ -base_support/support1rust -base_support/support1shiny -base_support/support2rust -base_support/wplat1_1 -base_support/plate2_5 \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/door-tex.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/door-tex.txt deleted file mode 100644 index 69629989..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/door-tex.txt +++ /dev/null @@ -1,10 +0,0 @@ -base_door/shinymetaldoor -base_door/shinymetaldoor_outside -gothic_door/door02_bred -gothic_door/door02_bred2_shiny -gothic_door/door02_eblue2_shiny -gothic_door/door02_i_ornate5_fin -gothic_door/door02_j -gothic_door/door02_j3 -gothic_door/door02_j4 -gothic_door/door02_k2b \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/tp_ent.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/tp_ent.txt deleted file mode 100644 index f0645b34..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/bt/tp_ent.txt +++ /dev/null @@ -1,14 +0,0 @@ -{ - "entity" "misc_model" - - "offset" "-16" - - "model" "models/mapobjects/trees_sd/tree_a.md3" - "model" "models/mapobjects/trees_sd/tree_b.md3" - "model" "models/mapobjects/trees_sd/tree_c.md3" - "model" "models/mapobjects/trees_sd/tree_d.md3" - - "pitch" "-5" "5" - "yaw" "0" "360" - "scale" "1" "1.3" -} \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/cportals.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/cportals.cpp deleted file mode 100644 index 5048eef0..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/cportals.cpp +++ /dev/null @@ -1,343 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "CPortals.h" - -#include -#include - -#include "misc.h" - -#define LINE_BUF 1000 -#define MSG_PREFIX "bobToolz plugin: " - -// these classes are far less of a mess than my code was, -// thanq to G.DeWan 4 the prtview source on which it was based - -CBspPortal::CBspPortal() -{ - memset(this, 0, sizeof(CBspPortal)); -} - -CBspPortal::~CBspPortal() -{ - delete[] point; -} - -void ClampFloat(float* p) -{ - double i; - double frac = modf(*p, &i); - - if(!frac) - return; - - if(fabs(*p - ceil(*p)) < MAX_ROUND_ERROR) - *p = static_cast(ceil(*p)); - - if(fabs(*p - floor(*p)) < MAX_ROUND_ERROR) - *p = static_cast(floor(*p)); -} - -bool CBspPortal::Build(char *def, unsigned int pointCnt, bool bInverse) -{ - char *c = def; - unsigned int n; - - point_count = pointCnt; - - if(point_count < 3) - return false; - - point = new CBspPoint[point_count]; - - for(n = 0; n < point_count; n++) - { - for(; *c != 0 && *c != '('; c++); - - if(*c == 0) - return false; - - c++; - - int x; - if(bInverse) - x = point_count - n - 1; - else - x = n; - - sscanf(c, "%f %f %f", &point[x].p[0], &point[x].p[1], &point[x].p[2]); - - ClampFloat(&point[x].p[0]); - ClampFloat(&point[x].p[1]); - ClampFloat(&point[x].p[2]); - } - - return true; -} - -CPortals::CPortals() -{ - memset(this, 0, sizeof(CPortals)); -} - -CPortals::~CPortals() -{ - Purge(); -} - -void CPortals::Purge() -{ - if(node) - delete[] node; - node = NULL; - node_count = 0; -} - -void CPortals::Load() -{ - char buf[LINE_BUF+1]; - - memset(buf, 0, LINE_BUF + 1); - - Purge(); - - globalOutputStream() << MSG_PREFIX "Loading portal file " << fn << ".\n"; - - FILE *in; - - in = fopen(fn, "rt"); - - if(in == NULL) - { - globalOutputStream() << " ERROR - could not open file.\n"; - - return; - } - - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - if(strncmp("PRT1", buf, 4) != 0) - { - fclose(in); - - globalOutputStream() << " ERROR - File header indicates wrong file type (should be \"PRT1\").\n"; - - return; - } - - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - sscanf(buf, "%u", &node_count); - - if(node_count > 0xFFFF) - { - fclose(in); - - node_count = 0; - - globalOutputStream() << " ERROR - Extreme number of nodes, aborting.\n"; - - return; - } - - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - node_count = 0; - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - unsigned int p_count; - sscanf(buf, "%u", &p_count); - - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - node_count = 0; - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - unsigned int p_count2; - sscanf(buf, "%u", &p_count2); - - node = new CBspNode[node_count]; - - unsigned int i; - for(i = 0; i < p_count; i++) - { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - node_count = 0; - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - unsigned int dummy, node1, node2; - sscanf(buf, "%u %u %u", &dummy, &node1, &node2); - - node[node1].portal_count++; - node[node2].portal_count++; - } - - for(i = 0; i < p_count2; i++) - { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - node_count = 0; - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - unsigned int dummy, node1; - sscanf(buf, "%u %u", &dummy, &node1); - - node[node1].portal_count++; - } - - for(i = 0; i < node_count; i++) - node[i].portal = new CBspPortal[node[i].portal_count]; - - fclose(in); - - in = fopen(fn, "rt"); - - fgets(buf, LINE_BUF, in); - fgets(buf, LINE_BUF, in); - fgets(buf, LINE_BUF, in); - fgets(buf, LINE_BUF, in); - - unsigned int n; - for(n = 0; n < p_count; n++) - { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - Purge(); - - globalOutputStream() << " ERROR - Could not find information for portal number " << n + 1 << " of " << p_count << ".\n"; - - return; - } - - unsigned int pCount, node1, node2; - sscanf(buf, "%u %u %u", &pCount, &node1, &node2); - - if(!node[node1].AddPortal(buf, pCount, false)) - { - fclose(in); - - Purge(); - - globalOutputStream() << " ERROR - Information for portal number " << n + 1 << " of " << p_count << " is not formatted correctly.\n"; - - return; - } - - if(!node[node2].AddPortal(buf, pCount, true)) - { - fclose(in); - - Purge(); - - globalOutputStream() << " ERROR - Information for portal number " << n + 1 << " of " << p_count << " is not formatted correctly.\n"; - - return; - } - } - - for(n = 0; n < p_count2; n++) - { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - Purge(); - - globalOutputStream() << " ERROR - Could not find information for portal number " << n + 1 << " of " << p_count << ".\n"; - - return; - } - - unsigned int pCount, node1; - sscanf(buf, "%u %u", &pCount, &node1); - - if(!node[node1].AddPortal(buf, pCount, false)) - { - fclose(in); - - Purge(); - - globalOutputStream() << " ERROR - Information for portal number " << n + 1 << " of " << p_count << " is not formatted correctly.\n"; - - return; - } - } - - fclose(in); -} - -CBspNode::CBspNode() -{ - portal = NULL; - portal_count = 0; - portal_next = 0; -} - -CBspNode::~CBspNode() -{ - if(portal != NULL) - delete[] portal; -} - -bool CBspNode::AddPortal(char *def, unsigned int pointCnt, bool bInverse) -{ - return portal[portal_next++].Build(def, pointCnt, bInverse); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfToolz-GTK.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfToolz-GTK.cpp deleted file mode 100644 index fe0e1d95..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfToolz-GTK.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "StdAfx.h" - -#include "funchandlers.h" -#include "misc.h" - -#include "dialogs/dialogs-gtk.h" - -// Radiant function table -_QERFuncTable_1 g_FuncTable; -_QERAppBSPFrontendTable g_BSPTable; // for map name - -BOOL g_bBSPInitDone = FALSE; - -// plugin name -static const char *PLUGIN_NAME = "ctfToolz"; - -// commands in the menu -static const char *PLUGIN_COMMANDS = "About...,Colour Changer...,Swap Light Colours,Change Angles 180,Swap Spawn Points"; - -// globals -GtkWidget *g_pRadiantWnd=NULL; - -static const char *PLUGIN_ABOUT = "ctfToolz for NetRadiant\n" - "by djbob\n" - "http://www.planetquake.com/toolz\n\n"; - -extern "C" LPVOID WINAPI QERPlug_GetFuncTable() -{ - return &g_FuncTable; -} - -extern "C" LPCSTR WINAPI QERPlug_Init(HMODULE hApp, GtkWidget* pMainWidget) -{ - g_pRadiantWnd = pMainWidget; - memset(&g_FuncTable, 0, sizeof(_QERFuncTable_1)); - g_FuncTable.m_fVersion = QER_PLUG_VERSION; - g_FuncTable.m_nSize = sizeof(_QERFuncTable_1); - - return "ctfToolz for GTKradiant"; -} - -extern "C" LPCSTR WINAPI QERPlug_GetName() -{ - return (char*)PLUGIN_NAME; -} - -extern "C" LPCSTR WINAPI QERPlug_GetCommandList() -{ - return (char*)PLUGIN_COMMANDS; -} - -extern "C" void WINAPI QERPlug_Dispatch (LPCSTR p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - LoadLists(); - - if (!g_bBSPInitDone) - { - g_BSPTable.m_nSize = sizeof(_QERAppBSPFrontendTable); - if ( g_FuncTable.m_pfnRequestInterface( QERAppBSPFrontendTable_GUID, static_cast(&g_BSPTable) ) ) - g_bBSPInitDone = TRUE; - else - { - Sys_ERROR("_QERAppBSPFrontendTable interface request failed\n"); - return; - } - } - - if(!strcmp(p, "About...")) - DoMessageBox(PLUGIN_ABOUT, "About", IDOK); - else if(!strcmp(p, "Colour Changer...")) - DoCTFColourChanger(); - else if(!strcmp(p, "Swap Light Colours")) - DoSwapLights(); - else if(!strcmp(p, "Change Angles 180")) - DoChangeAngles(); - else if(!strcmp(p, "Swap Spawn Points")) - DoSwapSpawns(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfresource_gtk.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfresource_gtk.h deleted file mode 100644 index 3f706a04..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfresource_gtk.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by ctfresource_gtk.rc -// - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfresource_gtk.rc b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfresource_gtk.rc deleted file mode 100644 index d3dc2f77..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctfresource_gtk.rc +++ /dev/null @@ -1,109 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "ctfresource_gtk.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.K.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENG) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_UK -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "ctfresource_gtk.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,0 - PRODUCTVERSION 1,0,0,0 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "080904b0" - BEGIN - VALUE "Comments", "\0" - VALUE "CompanyName", "bobCo\0" - VALUE "FileDescription", "All your plugins are belong to us\0" - VALUE "FileVersion", "1, 0, 0, 0\0" - VALUE "InternalName", "ctftoolz\0" - VALUE "LegalCopyright", "Copyright © 2001\0" - VALUE "LegalTrademarks", "\0" - VALUE "OriginalFilename", "ctftoolz.dll\0" - VALUE "PrivateBuild", "\0" - VALUE "ProductName", "bobCo ctftoolz\0" - VALUE "ProductVersion", "1, 0, 0, 0\0" - VALUE "SpecialBuild", "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x809, 1200 - END -END - -#endif // !_MAC - -#endif // English (U.K.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctftoolz.def b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctftoolz.def deleted file mode 100644 index 2c063edd..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/ctftoolz.def +++ /dev/null @@ -1,12 +0,0 @@ -; plugin.def : Declares the module parameters for the DLL. - -LIBRARY "ctfToolz" -DESCRIPTION 'ctfToolz Windows Dynamic Link Library' - -EXPORTS - ; Explicit exports can go here - QERPlug_Init @1 - QERPlug_GetName @2 - QERPlug_GetCommandList @3 - QERPlug_Dispatch @4 - QERPlug_GetFuncTable @5 diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AboutDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AboutDialog.cpp deleted file mode 100644 index e5d37038..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AboutDialog.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// AboutDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "AboutDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -//static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CAboutDialog dialog - - -CAboutDialog::CAboutDialog(CWnd* pParent /*=NULL*/) - : CDialog(CAboutDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CAboutDialog) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void CAboutDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CAboutDialog) - // NOTE: the ClassWizard will add DDX and DDV calls here - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CAboutDialog, CDialog) - //{{AFX_MSG_MAP(CAboutDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CAboutDialog message handlers - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AboutDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AboutDialog.h deleted file mode 100644 index 54cfd017..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AboutDialog.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_ABOUTDIALOG_H__3BA55F71_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_) -#define AFX_ABOUTDIALOG_H__3BA55F71_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_ - -#if _MSC_VER >= 1000 -#pragma once -#endif // _MSC_VER >= 1000 -// AboutDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CAboutDialog dialog - -class CAboutDialog : public CDialog -{ -// Construction -public: - CAboutDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CAboutDialog) - enum { IDD = IDD_ABOUT }; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAboutDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CAboutDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Developer Studio will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_ABOUTDIALOG_H__3BA55F71_1D27_11D3_BC7B_F7EFD9765E37__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp deleted file mode 100644 index fd46b7fb..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkDialog.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// AutoCaulkDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "../bobtoolz.h" -#include "AutoCaulkDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CAutoCaulkDialog dialog - - -CAutoCaulkDialog::CAutoCaulkDialog(CWnd* pParent /*=NULL*/) - : CDialog(CAutoCaulkDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CAutoCaulkDialog) - // NOTE: the ClassWizard will add member initialization here - //}}AFX_DATA_INIT -} - - -void CAutoCaulkDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CAutoCaulkDialog) - DDX_Control(pDX, IDC_PROGRESS2, m_prog2); - DDX_Control(pDX, IDC_PROGRESS1, m_prog1); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CAutoCaulkDialog, CDialog) - //{{AFX_MSG_MAP(CAutoCaulkDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CAutoCaulkDialog message handlers diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkDialog.h deleted file mode 100644 index a8740275..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkDialog.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_AUTOCAULKDIALOG_H__C2783D61_DDEB_11D4_ACF6_004095A18133__INCLUDED_) -#define AFX_AUTOCAULKDIALOG_H__C2783D61_DDEB_11D4_ACF6_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// AutoCaulkDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CAutoCaulkDialog dialog - -class CAutoCaulkDialog : public CDialog -{ -// Construction -public: - CAutoCaulkDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CAutoCaulkDialog) - enum { IDD = IDD_AUTOCAULK_DIALOG }; - CProgressCtrl m_prog2; - CProgressCtrl m_prog1; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAutoCaulkDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CAutoCaulkDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_AUTOCAULKDIALOG_H__C2783D61_DDEB_11D4_ACF6_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.cpp deleted file mode 100644 index 857df71a..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// AutoCaulkStartDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "../bobtoolz.h" -#include "AutoCaulkStartDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CAutoCaulkStartDialog dialog - - -CAutoCaulkStartDialog::CAutoCaulkStartDialog(CWnd* pParent /*=NULL*/) - : CDialog(CAutoCaulkStartDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CAutoCaulkStartDialog) - m_bAllowDestruction = FALSE; - m_Warning1 = _T(""); - m_nMode = 0; - //}}AFX_DATA_INIT -} - - -void CAutoCaulkStartDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CAutoCaulkStartDialog) - DDX_Check(pDX, IDC_KILLBRUSHES_CHECK, m_bAllowDestruction); - DDX_Text(pDX, IDC_WARNING1_STATIC, m_Warning1); - DDX_Radio(pDX, IDC_AC_NORMAL_RADIO, m_nMode); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CAutoCaulkStartDialog, CDialog) - //{{AFX_MSG_MAP(CAutoCaulkStartDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CAutoCaulkStartDialog message handlers diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h deleted file mode 100644 index 9311c51c..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/AutoCaulkStartDialog.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_AUTOCAULKSTARTDIALOG_H__F3DE2E81_E73E_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_AUTOCAULKSTARTDIALOG_H__F3DE2E81_E73E_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// AutoCaulkStartDialog.h : header file -// - -#define MODE_AC_NORMAL 0 -#define MODE_AC_BUILD_MINI_PRT 1 -#define MODE_AC_SUPER 2 - -///////////////////////////////////////////////////////////////////////////// -// CAutoCaulkStartDialog dialog - -class CAutoCaulkStartDialog : public CDialog -{ -// Construction -public: - CAutoCaulkStartDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CAutoCaulkStartDialog) - enum { IDD = IDD_AUTOCAULKSTART_DIALOG }; - BOOL m_bAllowDestruction; - CString m_Warning1; - int m_nMode; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CAutoCaulkStartDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CAutoCaulkStartDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_AUTOCAULKSTARTDIALOG_H__F3DE2E81_E73E_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/BrushCheckDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/BrushCheckDialog.h deleted file mode 100644 index 2ccf8e8f..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/BrushCheckDialog.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_BRUSHCHECKDIALOG_H__4BF2C701_D9EF_11D4_ACF6_004095A18133__INCLUDED_) -#define AFX_BRUSHCHECKDIALOG_H__4BF2C701_D9EF_11D4_ACF6_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// BrushCheckDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CBrushCheckDialog dialog - -class CBrushCheckDialog : public CDialog -{ -// Construction -public: - CBrushCheckDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CBrushCheckDialog) - enum { IDD = IDD_BRUSHCHECKER_DIALOG }; - CProgressCtrl m_prog1; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CBrushCheckDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CBrushCheckDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_BRUSHCHECKDIALOG_H__4BF2C701_D9EF_11D4_ACF6_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/DoorDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/DoorDialog.cpp deleted file mode 100644 index 2a1829d5..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/DoorDialog.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// DoorDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "DoorDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CDoorDialog dialog - - -CDoorDialog::CDoorDialog(CWnd* pParent /*=NULL*/) - : CDialog(CDoorDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CDoorDialog) - m_fbTextureName = _T(""); - m_bSclMainHor = TRUE; - m_bSclMainVert = TRUE; - m_bSclTrimHor = TRUE; - m_bSclTrimVert = FALSE; - m_trimTextureName = _T(""); - m_trimTexSetBox = _T(""); - m_mainTexSetBox = _T(""); - m_doorDirection = -1; - //}}AFX_DATA_INIT -} - - -void CDoorDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CDoorDialog) - DDX_Text(pDX, IDC_FBTEXTURE_EDIT, m_fbTextureName); - DDX_Check(pDX, IDC_TEXSCALE1_CHECK, m_bSclMainHor); - DDX_Check(pDX, IDC_TEXSCALE2_CHECK, m_bSclMainVert); - DDX_Check(pDX, IDC_TEXSCALE3_CHECK, m_bSclTrimHor); - DDX_Check(pDX, IDC_TEXSCALE4_CHECK, m_bSclTrimVert); - DDX_Text(pDX, IDC_TRIMTEXTURE_EDIT, m_trimTextureName); - DDX_CBString(pDX, IDC_TRIMTEX_COMBO, m_trimTexSetBox); - DDX_CBString(pDX, IDC_MAINTEX_COMBO, m_mainTexSetBox); - DDX_Radio(pDX, IDC_DIR_NS_RADIO, m_doorDirection); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CDoorDialog, CDialog) - //{{AFX_MSG_MAP(CDoorDialog) - ON_BN_CLICKED(IDC_SET_MAINTEX_BTN, OnSetMaintexBtn) - ON_BN_CLICKED(IDC_SET_TRIMTEX_BTN, OnSetTrimtexBtn) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CDoorDialog message handlers - -void CDoorDialog::OnSetMaintexBtn() -{ - UpdateData(TRUE); - m_fbTextureName = m_mainTexSetBox; - UpdateData(FALSE); -} - -void CDoorDialog::OnSetTrimtexBtn() -{ - UpdateData(TRUE); - m_trimTextureName = m_trimTexSetBox; - UpdateData(FALSE); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/DoorDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/DoorDialog.h deleted file mode 100644 index 4d312cb9..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/DoorDialog.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_DOORDIALOG_H__F36CBE01_D2C4_11D4_AE97_004095A18133__INCLUDED_) -#define AFX_DOORDIALOG_H__F36CBE01_D2C4_11D4_AE97_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// DoorDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CDoorDialog dialog - -class CDoorDialog : public CDialog -{ -// Construction -public: - CDoorDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CDoorDialog) - enum { IDD = IDD_DOOR_DIALOG }; - CString m_fbTextureName; - BOOL m_bSclMainHor; - BOOL m_bSclMainVert; - BOOL m_bSclTrimHor; - BOOL m_bSclTrimVert; - CString m_trimTextureName; - CString m_trimTexSetBox; - CString m_mainTexSetBox; - int m_doorDirection; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CDoorDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CDoorDialog) - afx_msg void OnSetMaintexBtn(); - afx_msg void OnSetTrimtexBtn(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_DOORDIALOG_H__F36CBE01_D2C4_11D4_AE97_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectDialog.cpp deleted file mode 100644 index 63a42d02..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectDialog.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// IntersectDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "IntersectDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CIntersectDialog dialog - - -CIntersectDialog::CIntersectDialog(CWnd* pParent /*=NULL*/) - : CDialog(CIntersectDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CIntersectDialog) - m_nBrushOptions = 1; - m_bUseDetail = FALSE; - m_bDuplicateOnly = FALSE; - //}}AFX_DATA_INIT -} - - -void CIntersectDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CIntersectDialog) - DDX_Radio(pDX, IDC_WHOLEMAP_RADIO, m_nBrushOptions); - DDX_Check(pDX, IDC_DETAIL_INCLUDE_CHECK, m_bUseDetail); - DDX_Check(pDX, IDC_DUPLICATEONLY_CHECK, m_bDuplicateOnly); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CIntersectDialog, CDialog) - //{{AFX_MSG_MAP(CIntersectDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CIntersectDialog message handlers diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectDialog.h deleted file mode 100644 index d1190a6f..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectDialog.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_INTERSECTDIALOG_H__03507C01_D3B3_11D4_AE97_004095A18133__INCLUDED_) -#define AFX_INTERSECTDIALOG_H__03507C01_D3B3_11D4_AE97_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// IntersectDialog.h : header file -// - -#define BRUSH_OPT_WHOLE_MAP 0 -#define BRUSH_OPT_SELECTED 1 - -///////////////////////////////////////////////////////////////////////////// -// CIntersectDialog dialog - -class CIntersectDialog : public CDialog -{ -// Construction -public: - CIntersectDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CIntersectDialog) - enum { IDD = IDD_INTERSECT_DIALOG }; - int m_nBrushOptions; - BOOL m_bUseDetail; - BOOL m_bDuplicateOnly; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CIntersectDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CIntersectDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_INTERSECTDIALOG_H__03507C01_D3B3_11D4_AE97_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectInfoDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectInfoDialog.cpp deleted file mode 100644 index f7684a9e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectInfoDialog.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// IntersectInfoDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "../bobtoolz.h" -#include "IntersectInfoDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CIntersectInfoDialog dialog - - -CIntersectInfoDialog::CIntersectInfoDialog(CWnd* pParent /*=NULL*/) - : CDialog(CIntersectInfoDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CIntersectInfoDialog) - //}}AFX_DATA_INIT -} - - -void CIntersectInfoDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CIntersectInfoDialog) - DDX_Control(pDX, IDC_PROGRESS1, m_prog1); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CIntersectInfoDialog, CDialog) - //{{AFX_MSG_MAP(CIntersectInfoDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CIntersectInfoDialog message handlers diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectInfoDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectInfoDialog.h deleted file mode 100644 index 51a4bf75..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/IntersectInfoDialog.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_INTERSECTINFODIALOG_H__62CDC8CD_D9D2_11D4_ACF6_004095A18133__INCLUDED_) -#define AFX_INTERSECTINFODIALOG_H__62CDC8CD_D9D2_11D4_ACF6_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// IntersectInfoDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CIntersectInfoDialog dialog - -class CIntersectInfoDialog : public CDialog -{ -// Construction -public: - CIntersectInfoDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CIntersectInfoDialog) - enum { IDD = IDD_INTERSECT_INFO_DIALOG }; - CProgressCtrl m_prog1; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CIntersectInfoDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CIntersectInfoDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_INTERSECTINFODIALOG_H__62CDC8CD_D9D2_11D4_ACF6_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/PolygonDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/PolygonDialog.cpp deleted file mode 100644 index f0a38d6e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/PolygonDialog.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// PolygonDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "PolygonDialog.h" -#include "../shapes.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CPolygonDialog dialog - - -CPolygonDialog::CPolygonDialog(CWnd* pParent /*=NULL*/) - : CDialog(CPolygonDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CPolygonDialog) - m_nSideCount = 3; - m_bInverse = FALSE; - m_bBorder = FALSE; - m_nBorderSize = 8; - m_bAlignTop = FALSE; - //}}AFX_DATA_INIT -} - -void CPolygonDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CPolygonDialog) - DDX_Text(pDX, IDC_EDIT1, m_nSideCount); - DDV_MinMaxUInt(pDX, m_nSideCount, 3, MAX_POLYGON_FACES); - DDX_Check(pDX, IDC_INVERSE_CHK, m_bInverse); - DDX_Check(pDX, IDC_BORDER_CHK, m_bBorder); - DDX_Text(pDX, IDC_BORDER_EDIT, m_nBorderSize); - DDV_MinMaxUInt(pDX, m_nBorderSize, 1, 1024); - DDX_Check(pDX, IDC_ALIGN_CHK, m_bAlignTop); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CPolygonDialog, CDialog) - //{{AFX_MSG_MAP(CPolygonDialog) - ON_BN_CLICKED(IDC_BORDER_CHK, OnBorderChkClicked) - ON_BN_CLICKED(IDC_INVERSE_CHK, OnInverseChkClickrd) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CPolygonDialog message handlers - -BOOL CPolygonDialog::OnInitDialog() -{ - CDialog::OnInitDialog(); - - EnableBordered(!GetChkBool(IDC_INVERSE_CHK)); - EnableBorderEdit(!GetChkBool(IDC_INVERSE_CHK) && GetChkBool(IDC_BORDER_CHK)); - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void CPolygonDialog::EnableBordered(BOOL bEnable) -{ - CWnd* dtlChk = GetDlgItem(IDC_BORDER_CHK); - if(dtlChk) - dtlChk->EnableWindow(bEnable); -} - -void CPolygonDialog::EnableBorderEdit(BOOL bEnable) -{ - CWnd* dtlChk = GetDlgItem(IDC_BORDER_EDIT); - if(dtlChk) - dtlChk->EnableWindow(bEnable); -} - -void CPolygonDialog::OnBorderChkClicked() -{ - EnableBorderEdit(!GetChkBool(IDC_INVERSE_CHK) && GetChkBool(IDC_BORDER_CHK)); -} - -void CPolygonDialog::OnInverseChkClickrd() -{ - EnableBordered(!GetChkBool(IDC_INVERSE_CHK)); - EnableBorderEdit(!GetChkBool(IDC_INVERSE_CHK) && GetChkBool(IDC_BORDER_CHK)); -} - -BOOL CPolygonDialog::GetChkBool(int nID) -{ - CButton* btn = (CButton*)GetDlgItem(nID); - if(btn) - return btn->GetCheck(); - return FALSE; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/PolygonDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/PolygonDialog.h deleted file mode 100644 index afe5cb87..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/PolygonDialog.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_POLYGONDIALOG_H__EF7FE400_628A_11D1_B66D_004095A18133__INCLUDED_) -#define AFX_POLYGONDIALOG_H__EF7FE400_628A_11D1_B66D_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// PolygonDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CPolygonDialog dialog - -class CPolygonDialog : public CDialog -{ -// Construction -public: - BOOL GetChkBool(int nID); - void EnableBorderEdit(BOOL bEnable); - void EnableBordered(BOOL bEnable); - CPolygonDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CPolygonDialog) - enum { IDD = IDD_POLYGON_DIALOG }; - UINT m_nSideCount; - BOOL m_bInverse; - BOOL m_bBorder; - UINT m_nBorderSize; - BOOL m_bAlignTop; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CPolygonDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CPolygonDialog) - virtual BOOL OnInitDialog(); - afx_msg void OnBorderChkClicked(); - afx_msg void OnInverseChkClickrd(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_POLYGONDIALOG_H__EF7FE400_628A_11D1_B66D_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/StairDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/StairDialog.cpp deleted file mode 100644 index 4e7feba3..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/StairDialog.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// StairDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "StairDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CStairDialog dialog - - -CStairDialog::CStairDialog(CWnd* pParent /*=NULL*/) - : CDialog(CStairDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CStairDialog) - m_nStairHeight = 8; - m_StairDir = 0; - m_StairStyle = 0; - m_riserTexture = _T(""); - m_bDetail = TRUE; - //}}AFX_DATA_INIT -} - -void CStairDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CStairDialog) - DDX_Text(pDX, IDC_EDIT1, m_nStairHeight); - DDV_MinMaxUInt(pDX, m_nStairHeight, 1, 256); - DDX_Radio(pDX, IDC_DIR_N_RADIO, m_StairDir); - DDX_Radio(pDX, IDC_STYLE_ORIG_RADIO, m_StairStyle); - DDX_Text(pDX, IDC_RISER_EDIT, m_riserTexture); - DDV_MaxChars(pDX, m_riserTexture, 256); - DDX_Check(pDX, IDC_DETAIL_CHK, m_bDetail); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CStairDialog, CDialog) - //{{AFX_MSG_MAP(CStairDialog) - ON_BN_CLICKED(IDC_STYLE_BOB_RADIO, OnStyleBobClicked) - ON_BN_CLICKED(IDC_STYLE_ORIG_RADIO, OnStyleOrigClicked) - ON_BN_CLICKED(IDC_STYLE_CORNER_RADIO, OnStyleCornerClicked) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CStairDialog message handlers - -void CStairDialog::OnStyleBobClicked() -{ - EnableDetail(TRUE); -} - -void CStairDialog::OnStyleOrigClicked() -{ - EnableDetail(FALSE); -} - -void CStairDialog::EnableDetail(BOOL bEnable) -{ - CWnd* dtlChk = GetDlgItem(IDC_DETAIL_CHK); - if(dtlChk) - dtlChk->EnableWindow(bEnable); -} - - -BOOL CStairDialog::OnInitDialog() -{ - CDialog::OnInitDialog(); - - EnableDetail(m_StairStyle == 1); - - return TRUE; // return TRUE unless you set the focus to a control - // EXCEPTION: OCX Property Pages should return FALSE -} - -void CStairDialog::OnStyleCornerClicked() -{ - EnableDetail(FALSE); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/StairDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/StairDialog.h deleted file mode 100644 index 0bcdc0ec..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/StairDialog.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_STAIRDIALOG_H__942FFF20_5F9E_11D1_B66D_004095A18133__INCLUDED_) -#define AFX_STAIRDIALOG_H__942FFF20_5F9E_11D1_B66D_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// StairDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CStairDialog dialog - -class CStairDialog : public CDialog -{ -// Construction -public: - CStairDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CStairDialog) - enum { IDD = IDD_STAIR_DIALOG }; - UINT m_nStairHeight; - int m_StairDir; - int m_StairStyle; - CString m_riserTexture; - BOOL m_bDetail; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CStairDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CStairDialog) - afx_msg void OnStyleBobClicked(); - afx_msg void OnStyleOrigClicked(); - virtual BOOL OnInitDialog(); - afx_msg void OnStyleCornerClicked(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -private: - void EnableDetail(BOOL bEnable); -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_STAIRDIALOG_H__942FFF20_5F9E_11D1_B66D_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/TextureResetDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/TextureResetDialog.cpp deleted file mode 100644 index 77ebc766..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/TextureResetDialog.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// TextureResetDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "../bobtoolz.h" -#include "TextureResetDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CTextureResetDialog dialog - - -CTextureResetDialog::CTextureResetDialog(CWnd* pParent /*=NULL*/) - : CDialog(CTextureResetDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CTextureResetDialog) - m_bAllTextures = FALSE; - m_TextureName = _T(""); - m_nRotation = 0; - m_fScaleHorizontal = 0.5f; - m_fScaleVertical = 0.5f; - m_nShiftHorizontal = 0; - m_nShiftVertical = 0; - m_bOnlyTexture = FALSE; - m_NewTextureName = _T(""); - //}}AFX_DATA_INIT -} - - -void CTextureResetDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CTextureResetDialog) - DDX_Check(pDX, IDC_ALLTEXTURES_CHECK, m_bAllTextures); - DDX_Text(pDX, IDC_RESET_TEXTURE_EDIT, m_TextureName); - DDV_MaxChars(pDX, m_TextureName, 256); - DDX_Text(pDX, IDC_ROTATION_EDIT, m_nRotation); - DDV_MinMaxInt(pDX, m_nRotation, 0, 360); - DDX_Text(pDX, IDC_SCL_HOR_EDIT, m_fScaleHorizontal); - DDX_Text(pDX, IDC_SCL_VERT_EDIT, m_fScaleVertical); - DDX_Text(pDX, IDC_SHFT_HOR_EDIT, m_nShiftHorizontal); - DDX_Text(pDX, IDC_SHFT_VER_EDIT, m_nShiftVertical); - DDX_Check(pDX, IDC_ONLYTEXTURE_CHECK, m_bOnlyTexture); - DDX_Text(pDX, IDC_RESET_NEW_TEXTURE_EDIT, m_NewTextureName); - DDV_MaxChars(pDX, m_NewTextureName, 256); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CTextureResetDialog, CDialog) - //{{AFX_MSG_MAP(CTextureResetDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CTextureResetDialog message handlers diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/TextureResetDialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/TextureResetDialog.h deleted file mode 100644 index 6f041611..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/TextureResetDialog.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_TEXTURERESETDIALOG_H__42D665C1_ED84_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_TEXTURERESETDIALOG_H__42D665C1_ED84_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// TextureResetDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CTextureResetDialog dialog - -class CTextureResetDialog : public CDialog -{ -// Construction -public: - CTextureResetDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CTextureResetDialog) - enum { IDD = IDD_TEXTURE_RESET_DIALOG }; - BOOL m_bAllTextures; - CString m_TextureName; - int m_nRotation; - float m_fScaleHorizontal; - float m_fScaleVertical; - int m_nShiftHorizontal; - int m_nShiftVertical; - BOOL m_bOnlyTexture; - CString m_NewTextureName; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CTextureResetDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CTextureResetDialog) - // NOTE: the ClassWizard will add member functions here - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_TEXTURERESETDIALOG_H__42D665C1_ED84_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/brushcheckdialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/brushcheckdialog.cpp deleted file mode 100644 index 06fe6c9b..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/brushcheckdialog.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// BrushCheckDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "../bobtoolz.h" -#include "BrushCheckDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CBrushCheckDialog dialog - - -CBrushCheckDialog::CBrushCheckDialog(CWnd* pParent /*=NULL*/) - : CDialog(CBrushCheckDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CBrushCheckDialog) - //}}AFX_DATA_INIT -} - - -void CBrushCheckDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CBrushCheckDialog) - DDX_Control(pDX, IDC_PROGRESS1, m_prog1); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CBrushCheckDialog, CDialog) - //{{AFX_MSG_MAP(CBrushCheckDialog) - // NOTE: the ClassWizard will add message map macros here - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CBrushCheckDialog message handlers diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/dialogs-gtk.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/dialogs-gtk.cpp deleted file mode 100644 index 927c7887..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/dialogs-gtk.cpp +++ /dev/null @@ -1,2018 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "dialogs-gtk.h" -#include "../funchandlers.h" - -#include "str.h" -#include -#include -#include "gtkutil/pointer.h" - -#include "../lists.h" -#include "../misc.h" - - -/*-------------------------------- - Callback Functions ----------------------------------*/ - -typedef struct { - GtkWidget *cbTexChange; - GtkWidget *editTexOld, *editTexNew; - - GtkWidget *cbScaleHor, *cbScaleVert; - GtkWidget *editScaleHor, *editScaleVert; - - GtkWidget *cbShiftHor, *cbShiftVert; - GtkWidget *editShiftHor, *editShiftVert; - - GtkWidget *cbRotation; - GtkWidget *editRotation; -}dlg_texReset_t; - -dlg_texReset_t dlgTexReset; - -void Update_TextureReseter(); - -static void dialog_button_callback_texreset_update (GtkWidget *widget, gpointer data) -{ - Update_TextureReseter(); -} - -void Update_TextureReseter() -{ - gboolean check; - - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbTexChange )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editTexNew), check); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editTexOld), check); - - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleHor )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editScaleHor), check); - - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleVert )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editScaleVert), check); - - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftHor )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editShiftHor), check); - - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftVert )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editShiftVert), check); - - check = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbRotation )); - gtk_entry_set_editable (GTK_ENTRY (dlgTexReset.editRotation), check); -} - -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop; - EMessageBoxReturn *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (EMessageBoxReturn*)g_object_get_data (G_OBJECT (parent), "ret"); - - *loop = 0; - *ret = (EMessageBoxReturn)gpointer_to_int(data); -} - -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; - - return TRUE; -} - -static void dialog_button_callback_settex (GtkWidget *widget, gpointer data) -{ - TwinWidget* tw = (TwinWidget*)data; - - GtkEntry* entry = GTK_ENTRY( tw->one ); - GtkCombo* combo = GTK_COMBO( tw->two ); - - const gchar* tex = gtk_entry_get_text(GTK_ENTRY( combo->entry )); - gtk_entry_set_text( entry, tex); -} - -/*-------------------------------- - Data validation Routines ----------------------------------*/ - -bool ValidateTextFloat(const char* pData, char* error_title, float* value) -{ - if(pData) - { - float testNum = (float)atof(pData); - - if((testNum == 0.0f) && strcmp(pData, "0")) - { - DoMessageBox("Please Enter A Floating Point Number", error_title, eMB_OK); - return FALSE; - } - else - { - *value = testNum; - return TRUE; - } - } - - DoMessageBox("Please Enter A Floating Point Number", error_title, eMB_OK); - return FALSE; -} - -bool ValidateTextFloatRange(const char* pData, float min, float max, char* error_title, float* value) -{ - char error_buffer[256]; - sprintf(error_buffer, "Please Enter A Floating Point Number Between %.3f and %.3f", min, max); - - if(pData) - { - float testNum = (float)atof(pData); - - if((testNum < min) || (testNum > max)) - { - DoMessageBox(error_buffer, error_title, eMB_OK); - return FALSE; - } - else - { - *value = testNum; - return TRUE; - } - } - - DoMessageBox(error_buffer, error_title, eMB_OK); - return FALSE; -} - -bool ValidateTextIntRange(const char* pData, int min, int max, char* error_title, int* value) -{ - char error_buffer[256]; - sprintf(error_buffer, "Please Enter An Integer Between %i and %i", min, max); - - if(pData) - { - int testNum = atoi(pData); - - if((testNum < min) || (testNum > max)) - { - DoMessageBox(error_buffer, error_title, eMB_OK); - return FALSE; - } - else - { - *value = testNum; - return TRUE; - } - } - - DoMessageBox(error_buffer, error_title, eMB_OK); - return FALSE; -} - -bool ValidateTextInt(const char* pData, char* error_title, int* value) -{ - if(pData) - { - int testNum = atoi(pData); - - if((testNum == 0) && strcmp(pData, "0")) - { - DoMessageBox("Please Enter An Integer", error_title, eMB_OK); - return FALSE; - } - else - { - *value = testNum; - return TRUE; - } - } - - DoMessageBox("Please Enter An Integer", error_title, eMB_OK); - return FALSE; -} - -/*-------------------------------- - Modal Dialog Boxes ----------------------------------*/ - -/* - - Major clean up of variable names etc required, excluding Mars's ones, - which are nicely done :) - -*/ - -EMessageBoxReturn DoMessageBox (const char* lpText, const char* lpCaption, EMessageBoxType type) -{ - GtkWidget *window, *w, *vbox, *hbox; - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_signal_connect (GTK_OBJECT (window), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_window_set_title (GTK_WINDOW (window), lpCaption); - gtk_container_border_width (GTK_CONTAINER (window), 10); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - w = gtk_label_new (lpText); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - if (type == eMB_OK) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - ret = eIDOK; - } - else if (type == eMB_OKCANCEL) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - } - else if (type == eMB_YESNOCANCEL) - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDNO)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - } - else /* if (mode == MB_YESNO) */ - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDNO)); - gtk_widget_show (w); - ret = eIDNO; - } - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -EMessageBoxReturn DoIntersectBox (IntersectRS* rs) -{ - GtkWidget *window, *w, *vbox, *hbox; - GtkWidget *radio1, *radio2; - GtkWidget *check1, *check2; - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Intersect"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - // ---- vbox ---- - - - radio1 = gtk_radio_button_new_with_label(NULL, "Use Whole Map"); - gtk_box_pack_start (GTK_BOX (vbox), radio1, FALSE, FALSE, 2); - gtk_widget_show (radio1); - - radio2 = gtk_radio_button_new_with_label(((GtkRadioButton*)radio1)->group, "Use Selected Brushes"); - gtk_box_pack_start (GTK_BOX (vbox), radio2, FALSE, FALSE, 2); - gtk_widget_show (radio2); - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - check1 = gtk_check_button_new_with_label("Include Detail Brushes"); - gtk_box_pack_start (GTK_BOX (vbox), check1, FALSE, FALSE, 0); - gtk_widget_show (check1); - - check2 = gtk_check_button_new_with_label("Select Duplicate Brushes Only"); - gtk_box_pack_start (GTK_BOX (vbox), check2, FALSE, FALSE, 0); - gtk_widget_show (check2); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- ok/cancel buttons - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // ---- /hbox ---- - - // ---- /vbox ---- - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - if(gtk_toggle_button_get_active((GtkToggleButton*)radio1)) - rs->nBrushOptions = BRUSH_OPT_WHOLE_MAP; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radio2)) - rs->nBrushOptions = BRUSH_OPT_SELECTED; - - rs->bUseDetail = gtk_toggle_button_get_active((GtkToggleButton*)check1) ? true : false; - rs->bDuplicateOnly = gtk_toggle_button_get_active((GtkToggleButton*)check2) ? true : false; - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -EMessageBoxReturn DoPolygonBox (PolygonRS* rs) -{ - GtkWidget *window, *w, *vbox, *hbox, *vbox2, *hbox2; - - GtkWidget *check1, *check2, *check3; - GtkWidget *text1, *text2; - - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Polygon Builder"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - // ---- vbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - - vbox2 = gtk_vbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (hbox), vbox2, FALSE, FALSE, 2); - gtk_widget_show (vbox2); - - // ---- vbox2 ---- - - hbox2 = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox2), hbox2, FALSE, FALSE, 2); - gtk_widget_show (hbox2); - - // ---- hbox2 ---- - - text1 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text1, "3"); - gtk_box_pack_start (GTK_BOX (hbox2), text1, FALSE, FALSE, 2); - gtk_widget_show (text1); - - w = gtk_label_new ("Number Of Sides"); - gtk_box_pack_start (GTK_BOX (hbox2), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox2 ---- - - hbox2 = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox2), hbox2, FALSE, FALSE, 2); - gtk_widget_show (hbox2); - - // ---- hbox2 ---- - - text2 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text2, "8"); - gtk_box_pack_start (GTK_BOX (hbox2), text2, FALSE, FALSE, 2); - gtk_widget_show (text2); - - w = gtk_label_new ("Border Width"); - gtk_box_pack_start (GTK_BOX (hbox2), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox2 ---- - - // ---- /vbox2 ---- - - - - vbox2 = gtk_vbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (hbox), vbox2, FALSE, FALSE, 2); - gtk_widget_show (vbox2); - - // ---- vbox2 ---- - - check1 = gtk_check_button_new_with_label("Use Border"); - gtk_box_pack_start (GTK_BOX (vbox2), check1, FALSE, FALSE, 0); - gtk_widget_show (check1); - - - check2 = gtk_check_button_new_with_label("Inverse Polygon"); - gtk_box_pack_start (GTK_BOX (vbox2), check2, FALSE, FALSE, 0); - gtk_widget_show (check2); - - - check3 = gtk_check_button_new_with_label("Align Top Edge"); - gtk_box_pack_start (GTK_BOX (vbox2), check3, FALSE, FALSE, 0); - gtk_widget_show (check3); - - // ---- /vbox2 ---- - - // ---- /hbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // ---- /hbox ---- - - // ---- /vbox ---- - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) - { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if(ret == eIDOK) - { - rs->bUseBorder = gtk_toggle_button_get_active((GtkToggleButton*)check1) ? true : false; - rs->bInverse = gtk_toggle_button_get_active((GtkToggleButton*)check2) ? true : false; - rs->bAlignTop = gtk_toggle_button_get_active((GtkToggleButton*)check3) ? true : false; - - if(!ValidateTextIntRange(gtk_entry_get_text((GtkEntry*)text1), 3, 32, "Number Of Sides", &rs->nSides)) - dialogError = TRUE; - - if(rs->bUseBorder) - { - if(!ValidateTextIntRange(gtk_entry_get_text((GtkEntry*)text2), 8, 256, "Border Width", &rs->nBorderWidth)) - dialogError = TRUE; - } - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -// mars -// for stair builder stuck as close as i could to the MFC version -// obviously feel free to change it at will :) -EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs) -{ - // i made widgets for just about everything ... i think that's what i need to do dunno tho - GtkWidget *window, *w, *vbox, *hbox; - GtkWidget *textStairHeight, *textRiserTex, *textMainTex; - GtkWidget *radioNorth, *radioSouth, *radioEast, *radioWest; // i'm guessing we can't just abuse 'w' for these if we're getting a value - GtkWidget *radioOldStyle, *radioBobStyle, *radioCornerStyle; - GtkWidget *checkUseDetail; - GSList *radioDirection, *radioStyle; - EMessageBoxReturn ret; - int loop = 1; - - char *text = "Please set a value in the boxes below and press 'OK' to build the stairs"; - - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title( GTK_WINDOW( window ), "Stair Builder" ); - - gtk_container_border_width( GTK_CONTAINER( window ), 10 ); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - // new vbox - vbox = gtk_vbox_new( FALSE, 10 ); - gtk_container_add( GTK_CONTAINER( window ), vbox ); - gtk_widget_show( vbox ); - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_container_add( GTK_CONTAINER( vbox ), hbox ); - gtk_widget_show( hbox ); - - // dunno if you want this text or not ... - w = gtk_label_new( text ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); // not entirely sure on all the parameters / what they do ... - gtk_widget_show( w ); - - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // ------------------------- // indenting == good way of keeping track of lines :) - - // new hbox - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textStairHeight = gtk_entry_new_with_max_length( 256 ); - gtk_box_pack_start( GTK_BOX( hbox ), textStairHeight, FALSE, FALSE, 1 ); - gtk_widget_show( textStairHeight ); - - w = gtk_label_new( "Stair Height" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); - gtk_widget_show( w ); - - // ------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Direction:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 5 ); - gtk_widget_show( w ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - // radio buttons confuse me ... - // but this _looks_ right - - // djbob: actually it looks very nice :), slightly better than the way i did it - // edit: actually it doesn't work :P, you must pass the last radio item each time, ugh - - radioNorth = gtk_radio_button_new_with_label( NULL, "North" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioNorth, FALSE, FALSE, 3 ); - gtk_widget_show( radioNorth ); - - radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioNorth ) ); - - radioSouth = gtk_radio_button_new_with_label( radioDirection, "South" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioSouth, FALSE, FALSE, 2 ); - gtk_widget_show( radioSouth ); - - radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioSouth ) ); - - radioEast = gtk_radio_button_new_with_label( radioDirection, "East" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioEast, FALSE, FALSE, 1 ); - gtk_widget_show( radioEast ); - - radioDirection = gtk_radio_button_group( GTK_RADIO_BUTTON( radioEast ) ); - - radioWest = gtk_radio_button_new_with_label( radioDirection, "West" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioWest, FALSE, FALSE, 0 ); - gtk_widget_show( radioWest ); - - // --------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Style:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 5 ); - gtk_widget_show( w ); - - // --------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - radioOldStyle = gtk_radio_button_new_with_label( NULL, "Original" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioOldStyle, FALSE, FALSE, 0 ); - gtk_widget_show( radioOldStyle ); - - radioStyle = gtk_radio_button_group( GTK_RADIO_BUTTON( radioOldStyle ) ); - - radioBobStyle = gtk_radio_button_new_with_label( radioStyle, "Bob's Style" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioBobStyle, FALSE, FALSE, 0 ); - gtk_widget_show( radioBobStyle ); - - radioStyle = gtk_radio_button_group( GTK_RADIO_BUTTON( radioBobStyle ) ); - - radioCornerStyle = gtk_radio_button_new_with_label( radioStyle, "Corner Style" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioCornerStyle, FALSE, FALSE, 0 ); - gtk_widget_show( radioCornerStyle ); - - // err, the q3r has an if or something so you need bob style checked before this - // is "ungreyed out" but you'll need to do that, as i suck :) - - // djbob: er.... yeah um, im not at all sure how i'm gonna sort this - // djbob: think we need some button callback functions or smuffin - // FIXME: actually get around to doing what i suggested!!!! - - checkUseDetail = gtk_check_button_new_with_label( "Use Detail Brushes" ); - gtk_box_pack_start( GTK_BOX( hbox ), checkUseDetail, FALSE, FALSE, 0 ); - gtk_widget_show( checkUseDetail ); - - // --------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textMainTex = gtk_entry_new_with_max_length( 512 ); - gtk_entry_set_text(GTK_ENTRY(textMainTex), rs->mainTexture); - gtk_box_pack_start( GTK_BOX( hbox ), textMainTex, FALSE, FALSE, 0 ); - gtk_widget_show( textMainTex ); - - w = gtk_label_new( "Main Texture" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); - gtk_widget_show( w ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textRiserTex = gtk_entry_new_with_max_length( 512 ); - gtk_box_pack_start( GTK_BOX( hbox ), textRiserTex, FALSE, FALSE, 0 ); - gtk_widget_show( textRiserTex ); - - w = gtk_label_new( "Riser Texture" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); - gtk_widget_show( w ); - - // -------------------------- // - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label( "OK" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Cancel" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); - gtk_widget_show( w ); - - ret = eIDCANCEL; - -// +djbob: need our "little" modal loop mars :P - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) - { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if(ret == eIDOK) - { - rs->bUseDetail = gtk_toggle_button_get_active((GtkToggleButton*)checkUseDetail) ? true : false; - - strcpy(rs->riserTexture, gtk_entry_get_text((GtkEntry*)textRiserTex)); - strcpy(rs->mainTexture, gtk_entry_get_text((GtkEntry*)textMainTex)); - - if(gtk_toggle_button_get_active((GtkToggleButton*)radioNorth)) - rs->direction = MOVE_NORTH; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioSouth)) - rs->direction = MOVE_SOUTH; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioEast)) - rs->direction = MOVE_EAST; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioWest)) - rs->direction = MOVE_WEST; - - if(!ValidateTextInt(gtk_entry_get_text((GtkEntry*)textStairHeight), "Stair Height", &rs->stairHeight)) - dialogError = TRUE; - - if(gtk_toggle_button_get_active((GtkToggleButton*)radioOldStyle)) - rs->style = STYLE_ORIGINAL; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioBobStyle)) - rs->style = STYLE_BOB; - else if(gtk_toggle_button_get_active((GtkToggleButton*)radioCornerStyle)) - rs->style = STYLE_CORNER; - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -// -djbob - - // there we go, all done ... on my end at least, not bad for a night's work -} - -EMessageBoxReturn DoDoorsBox(DoorRS* rs) -{ - GtkWidget *window, *hbox, *vbox, *w; - GtkWidget *textFrontBackTex, *textTrimTex; - GtkWidget *checkScaleMainH, *checkScaleMainV, *checkScaleTrimH, *checkScaleTrimV; - GtkWidget *comboMain, *comboTrim; - GtkWidget *buttonSetMain, *buttonSetTrim; - GtkWidget *radioNS, *radioEW; - GSList *radioOrientation; - TwinWidget tw1, tw2; - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title( GTK_WINDOW( window ), "Door Builder" ); - - gtk_container_border_width( GTK_CONTAINER( window ), 10 ); - - g_object_set_data( G_OBJECT( window ), "loop", &loop ); - g_object_set_data( G_OBJECT( window ), "ret", &ret ); - - gtk_widget_realize (window); - - char buffer[256]; - GList *listMainTextures = NULL; - GList *listTrimTextures = NULL; - LoadGList(GetFilename(buffer, "plugins/bt/door-tex.txt"), &listMainTextures); - LoadGList(GetFilename(buffer, "plugins/bt/door-tex-trim.txt"), &listTrimTextures); - - vbox = gtk_vbox_new( FALSE, 10 ); - gtk_container_add( GTK_CONTAINER( window ), vbox ); - gtk_widget_show( vbox ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textFrontBackTex = gtk_entry_new_with_max_length( 512 ); - gtk_entry_set_text( GTK_ENTRY( textFrontBackTex ), rs->mainTexture); - gtk_box_pack_start( GTK_BOX( hbox ), textFrontBackTex, FALSE, FALSE, 0 ); - gtk_widget_show( textFrontBackTex ); - - w = gtk_label_new( "Door Front/Back Texture" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // ------------------------ // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textTrimTex = gtk_entry_new_with_max_length( 512 ); - gtk_box_pack_start( GTK_BOX( hbox ), textTrimTex, FALSE, FALSE, 0 ); - gtk_widget_show( textTrimTex ); - - w = gtk_label_new( "Door Trim Texture" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // ----------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - // sp: horizontally ???? - // djbob: yes mars, u can spell :] - checkScaleMainH = gtk_check_button_new_with_label( "Scale Main Texture Horizontally" ); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON( checkScaleMainH ), TRUE); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleMainH, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleMainH ); - - checkScaleTrimH = gtk_check_button_new_with_label( "Scale Trim Texture Horizontally" ); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON( checkScaleTrimH ), TRUE); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleTrimH, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleTrimH ); - - // ---------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - checkScaleMainV = gtk_check_button_new_with_label( "Scale Main Texture Vertically" ); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON( checkScaleMainV ), TRUE); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleMainV, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleMainV ); - - checkScaleTrimV = gtk_check_button_new_with_label( "Scale Trim Texture Vertically" ); - gtk_box_pack_start( GTK_BOX( hbox ), checkScaleTrimV, FALSE, FALSE, 0 ); - gtk_widget_show( checkScaleTrimV ); - - // --------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - // djbob: lists added - - comboMain = gtk_combo_new(); - gtk_box_pack_start( GTK_BOX( hbox ), comboMain, FALSE, FALSE, 0 ); - gtk_combo_set_popdown_strings( GTK_COMBO( comboMain ), listMainTextures ); - gtk_combo_set_use_arrows( GTK_COMBO( comboMain ), 1 ); - gtk_widget_show( comboMain ); - - tw1.one = textFrontBackTex; - tw1.two = comboMain; - - buttonSetMain = gtk_button_new_with_label( "Set As Main Texture" ); - gtk_signal_connect( GTK_OBJECT( buttonSetMain ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback_settex ), &tw1 ); - gtk_box_pack_start( GTK_BOX( hbox ), buttonSetMain, FALSE, FALSE, 0 ); - gtk_widget_show( buttonSetMain ); - - // ------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - comboTrim = gtk_combo_new(); - gtk_box_pack_start( GTK_BOX( hbox ), comboTrim, FALSE, FALSE, 0 ); - gtk_combo_set_popdown_strings( GTK_COMBO( comboTrim ), listTrimTextures ); - gtk_combo_set_use_arrows( GTK_COMBO( comboMain ), 1 ); - gtk_widget_show( comboTrim ); - - tw2.one = textTrimTex; - tw2.two = comboTrim; - - buttonSetTrim = gtk_button_new_with_label( "Set As Trim Texture" ); - gtk_signal_connect( GTK_OBJECT( buttonSetTrim ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback_settex ), &tw2 ); - gtk_box_pack_start( GTK_BOX( hbox ), buttonSetTrim, FALSE, FALSE, 0 ); - gtk_widget_show( buttonSetTrim ); - - // ------------------ // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Orientation" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // argh more radio buttons! - radioNS = gtk_radio_button_new_with_label( NULL, "North - South" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioNS, FALSE, FALSE, 0 ); - gtk_widget_show( radioNS ); - - radioOrientation = gtk_radio_button_group( GTK_RADIO_BUTTON( radioNS ) ); - - radioEW = gtk_radio_button_new_with_label( radioOrientation, "East - West" ); - gtk_box_pack_start( GTK_BOX( hbox ), radioEW, FALSE, FALSE, 0 ); - gtk_widget_show( radioEW ); - - // ----------------- // - - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // ----------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label( "OK" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Cancel" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); - gtk_widget_show( w ); - ret = eIDCANCEL; - - // ----------------- // - -//+djbob - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - strcpy(rs->mainTexture, gtk_entry_get_text( GTK_ENTRY( textFrontBackTex ) )); - strcpy(rs->trimTexture, gtk_entry_get_text( GTK_ENTRY( textTrimTex ) )); - - rs->bScaleMainH = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleMainH)) ? true : false; - rs->bScaleMainV = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleMainV)) ? true : false; - rs->bScaleTrimH = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleTrimH)) ? true : false; - rs->bScaleTrimV = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(checkScaleTrimV)) ? true : false; - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioNS))) - rs->nOrientation = DIRECTION_NS; - else if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radioEW))) - rs->nOrientation = DIRECTION_EW; - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -//-djbob -} - -EMessageBoxReturn DoPathPlotterBox(PathPlotterRS* rs) -{ - GtkWidget *window, *w, *vbox, *hbox; - - GtkWidget *text1, *text2, *text3; - GtkWidget *check1, *check2; - - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Texture Reset"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - // ---- vbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - text1 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text1, "25"); - gtk_box_pack_start (GTK_BOX (hbox), text1, FALSE, FALSE, 2); - gtk_widget_show (text1); - - w = gtk_label_new ("Number Of Points"); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - text2 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text2, "3"); - gtk_box_pack_start (GTK_BOX (hbox), text2, FALSE, FALSE, 2); - gtk_widget_show (text2); - - w = gtk_label_new ("Multipler"); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox ---- - - w = gtk_label_new ("Path Distance = dist(start -> apex) * multiplier"); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 0); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - text3 = gtk_entry_new_with_max_length(256); - gtk_entry_set_text((GtkEntry*)text3, "-800"); - gtk_box_pack_start (GTK_BOX (hbox), text3, FALSE, FALSE, 2); - gtk_widget_show (text3); - - w = gtk_label_new ("Gravity"); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox ---- - - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - check1 = gtk_check_button_new_with_label( "No Dynamic Update" ); - gtk_box_pack_start( GTK_BOX( vbox ), check1, FALSE, FALSE, 0 ); - gtk_widget_show( check1 ); - - check2 = gtk_check_button_new_with_label( "Show Bounding Lines" ); - gtk_box_pack_start( GTK_BOX( vbox ), check2, FALSE, FALSE, 0 ); - gtk_widget_show( check2 ); - - // ---- /vbox ---- - - - // ----------------- // - - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // ----------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label( "Enable" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDYES ) ); - gtk_widget_show( w ); - - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - - w = gtk_button_new_with_label( "Disable" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDNO ) ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Cancel" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); - gtk_widget_show( w ); - - ret = eIDCANCEL; - - // ----------------- // - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) - { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if(ret == eIDYES) - { - if(!ValidateTextIntRange(gtk_entry_get_text(GTK_ENTRY(text1)), 1, 200, "Number Of Points", &rs->nPoints)) - dialogError = TRUE; - - if(!ValidateTextFloatRange(gtk_entry_get_text(GTK_ENTRY(text2)), 1.0f, 10.0f, "Multiplier", &rs->fMultiplier)) - dialogError = TRUE; - - if(!ValidateTextFloatRange(gtk_entry_get_text(GTK_ENTRY(text3)), -10000.0f, -1.0f, "Gravity", &rs->fGravity)) - dialogError = TRUE; - - rs->bNoUpdate = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check1)) ? true : false; - rs->bShowExtra = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(check2)) ? true : false; - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -EMessageBoxReturn DoCTFColourChangeBox () -{ - GtkWidget *window, *w, *vbox, *hbox; - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "CTF Colour Changer"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - // ---- vbox ---- - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, TRUE, TRUE, 0 ); - gtk_widget_show( hbox ); - - // ---- hbox ---- ok/cancel buttons - - w = gtk_button_new_with_label ("Red->Blue"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Blue->Red"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // ---- /hbox ---- - - // ---- /vbox ---- - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -EMessageBoxReturn DoResetTextureBox (ResetTextureRS* rs) -{ - Str texSelected; - - GtkWidget *window, *w, *vbox, *hbox, *frame, *table; - - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Texture Reset"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - // ---- vbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - texSelected = "Currently Selected Texture: "; - texSelected += GetCurrentTexture(); - - w = gtk_label_new (texSelected); - gtk_box_pack_start (GTK_BOX (hbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - // ---- /hbox ---- - - frame = gtk_frame_new ("Reset Texture Names"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - dlgTexReset.cbTexChange = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbTexChange), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbTexChange); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbTexChange, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("Old Name: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editTexOld = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editTexOld), rs->textureName); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editTexOld, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editTexOld); - - w = gtk_label_new ("New Name: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editTexNew = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editTexNew), rs->textureName); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editTexNew, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editTexNew); - - // ---- /frame ---- - - frame = gtk_frame_new ("Reset Scales"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - dlgTexReset.cbScaleHor = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbScaleHor), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbScaleHor); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbScaleHor, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Horizontal Scale: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editScaleHor = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editScaleHor), "0.5"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editScaleHor, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editScaleHor); - - - dlgTexReset.cbScaleVert = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbScaleVert), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbScaleVert); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbScaleVert, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Vertical Scale: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editScaleVert = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editScaleVert), "0.5"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editScaleVert, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editScaleVert); - - // ---- /frame ---- - - frame = gtk_frame_new ("Reset Shift"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - dlgTexReset.cbShiftHor = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbShiftHor), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbShiftHor); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbShiftHor, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Horizontal Shift: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editShiftHor = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editShiftHor), "0"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editShiftHor, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editShiftHor); - - - dlgTexReset.cbShiftVert = gtk_check_button_new_with_label("Enabled"); - gtk_signal_connect (GTK_OBJECT (dlgTexReset.cbShiftVert), "toggled", GTK_SIGNAL_FUNC (dialog_button_callback_texreset_update), NULL); - gtk_widget_show (dlgTexReset.cbShiftVert); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbShiftVert, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Vertical Shift: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editShiftVert = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editShiftVert), "0"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editShiftVert, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editShiftVert); - - // ---- /frame ---- - - frame = gtk_frame_new ("Reset Rotation"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (1, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - dlgTexReset.cbRotation = gtk_check_button_new_with_label("Enabled"); - gtk_widget_show (dlgTexReset.cbRotation); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.cbRotation, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - w = gtk_label_new ("New Rotation Value: "); - gtk_table_attach (GTK_TABLE (table), w, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - dlgTexReset.editRotation = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(dlgTexReset.editRotation), "0"); - gtk_table_attach (GTK_TABLE (table), dlgTexReset.editRotation, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (dlgTexReset.editRotation); - - // ---- /frame ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - w = gtk_button_new_with_label ("Use Selected Brushes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Use All Brushes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDYES)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // ---- /hbox ---- - - // ---- /vbox ---- - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - Update_TextureReseter(); - - bool dialogError = TRUE; - while (dialogError) - { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if(ret != eIDCANCEL) - { - rs->bResetRotation = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbRotation )); - if(rs->bResetRotation) - if(!ValidateTextInt(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editRotation)), "Rotation", &rs->rotation)) - dialogError = TRUE; - - rs->bResetScale[0] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleHor )); - if(rs->bResetScale[0]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editScaleHor)), "Horizontal Scale", &rs->fScale[0])) - dialogError = TRUE; - - rs->bResetScale[1] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbScaleVert )); - if(rs->bResetScale[1]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editScaleVert)), "Vertical Scale", &rs->fScale[1])) - dialogError = TRUE; - - rs->bResetShift[0] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftHor )); - if(rs->bResetShift[0]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editShiftHor)), "Horizontal Shift", &rs->fShift[0])) - dialogError = TRUE; - - rs->bResetShift[1] = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbShiftVert )); - if(rs->bResetShift[1]) - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(dlgTexReset.editShiftVert)), "Vertical Shift", &rs->fShift[1])) - dialogError = TRUE; - - rs->bResetTextureName = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON( dlgTexReset.cbTexChange )); - if(rs->bResetTextureName) - { - strcpy(rs->textureName, gtk_entry_get_text(GTK_ENTRY( dlgTexReset.editTexOld ))); - strcpy(rs->newTextureName, gtk_entry_get_text(GTK_ENTRY( dlgTexReset.editTexNew ))); - } - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -EMessageBoxReturn DoTrainThingBox (TrainThingRS* rs) -{ - Str texSelected; - - GtkWidget *window, *w, *vbox, *hbox, *frame, *table; - - GtkWidget *radiusX, *radiusY; - GtkWidget *angleStart, *angleEnd; - GtkWidget *heightStart, *heightEnd; - GtkWidget *numPoints; - - EMessageBoxReturn ret; - int loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title (GTK_WINDOW (window), "Train Thing"); - gtk_container_border_width (GTK_CONTAINER (window), 10); - - gtk_object_set_data (GTK_OBJECT (window), "loop", &loop); - gtk_object_set_data (GTK_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - // ---- vbox ---- - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- /hbox ---- - - frame = gtk_frame_new ("Radii"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - w = gtk_label_new ("X: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - radiusX = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(radiusX), "100"); - gtk_table_attach (GTK_TABLE (table), radiusX, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (radiusX); - - - - w = gtk_label_new ("Y: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - radiusY = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(radiusY), "100"); - gtk_table_attach (GTK_TABLE (table), radiusY, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (radiusY); - - - - frame = gtk_frame_new ("Angles"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - w = gtk_label_new ("Start: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - angleStart = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(angleStart), "0"); - gtk_table_attach (GTK_TABLE (table), angleStart, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (angleStart); - - - - w = gtk_label_new ("End: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - angleEnd = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(angleEnd), "90"); - gtk_table_attach (GTK_TABLE (table), angleEnd, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (angleEnd); - - - frame = gtk_frame_new ("Height"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - w = gtk_label_new ("Start: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - heightStart = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(heightStart), "0"); - gtk_table_attach (GTK_TABLE (table), heightStart, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (heightStart); - - - - w = gtk_label_new ("End: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - heightEnd = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(heightEnd), "0"); - gtk_table_attach (GTK_TABLE (table), heightEnd, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (heightEnd); - - - - frame = gtk_frame_new ("Points"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (2, 3, TRUE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - - // ---- frame ---- - - w = gtk_label_new ("Number: "); - gtk_table_attach (GTK_TABLE (table), w, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (w); - - numPoints = gtk_entry_new_with_max_length(256); - gtk_entry_set_text(GTK_ENTRY(numPoints), "0"); - gtk_table_attach (GTK_TABLE (table), numPoints, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_show (numPoints); - - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - // ---- hbox ---- - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // ---- /hbox ---- - - - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) - { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if(ret != eIDCANCEL) - { - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(radiusX)), "Radius (X)", &rs->fRadiusX)) - dialogError = TRUE; - - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(radiusY)), "Radius (Y)", &rs->fRadiusY)) - dialogError = TRUE; - - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(angleStart)), "Angle (Start)", &rs->fStartAngle)) - dialogError = TRUE; - - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(angleEnd)), "Angle (End)", &rs->fEndAngle)) - dialogError = TRUE; - - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(heightStart)), "Height (Start)", &rs->fStartHeight)) - dialogError = TRUE; - - if(!ValidateTextFloat(gtk_entry_get_text(GTK_ENTRY(heightEnd)), "Height (End)", &rs->fEndHeight)) - dialogError = TRUE; - - if(!ValidateTextInt(gtk_entry_get_text(GTK_ENTRY(numPoints)), "Num Points", &rs->iNumPoints)) - dialogError = TRUE; - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} -// ailmanki -// add a simple input for the MakeChain thing.. -EMessageBoxReturn DoMakeChainBox(MakeChainRS* rs) -{ - GtkWidget *window, *w, *vbox, *hbox; - GtkWidget *textlinkNum, *textlinkName; - EMessageBoxReturn ret; - int loop = 1; - - char *text = "Please set a value in the boxes below and press 'OK' to make a chain"; - - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - - gtk_signal_connect (GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - - gtk_window_set_title( GTK_WINDOW( window ), "Make Chain" ); - - gtk_container_border_width( GTK_CONTAINER( window ), 10 ); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - // new vbox - vbox = gtk_vbox_new( FALSE, 10 ); - gtk_container_add( GTK_CONTAINER( window ), vbox ); - gtk_widget_show( vbox ); - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_container_add( GTK_CONTAINER( vbox ), hbox ); - gtk_widget_show( hbox ); - - // dunno if you want this text or not ... - w = gtk_label_new( text ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - w = gtk_hseparator_new(); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // ------------------------- // - - // new hbox - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textlinkNum = gtk_entry_new_with_max_length( 256 ); - gtk_box_pack_start( GTK_BOX( hbox ), textlinkNum, FALSE, FALSE, 1 ); - gtk_widget_show( textlinkNum ); - - w = gtk_label_new( "Number of elements in chain" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); - gtk_widget_show( w ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 10 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - textlinkName = gtk_entry_new_with_max_length( 256 ); - gtk_box_pack_start( GTK_BOX( hbox ), textlinkName, FALSE, FALSE, 0 ); - gtk_widget_show( textlinkName ); - - w = gtk_label_new( "Basename for chain's targetnames." ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 1 ); - gtk_widget_show( w ); - - - w = gtk_button_new_with_label( "OK" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDOK ) ); - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Cancel" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( dialog_button_callback ), GINT_TO_POINTER( eIDCANCEL ) ); - gtk_widget_show( w ); - - ret = eIDCANCEL; - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) - { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if(ret == eIDOK) - { - strcpy(rs->linkName, gtk_entry_get_text((GtkEntry*)textlinkName)); - if(!ValidateTextInt(gtk_entry_get_text((GtkEntry*)textlinkNum), "Elements", &rs->linkNum)) - dialogError = TRUE; - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/dialogs-gtk.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/dialogs-gtk.h deleted file mode 100644 index 0ad1c6b5..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/dialogs-gtk.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(INCLUDED_DIALOGS_GTK_H) -#define INCLUDED_DIALOGS_GTK_H - -#include "qerplugin.h" - -struct BuildStairsRS{ - char mainTexture[256]; - char riserTexture[256]; - int direction; - int style; - int stairHeight; - bool bUseDetail; -}; - -struct ResetTextureRS { - int bResetTextureName; - char textureName[256]; - char newTextureName[256]; - - int bResetScale[2]; - float fScale[2]; - - int bResetShift[2]; - float fShift[2]; - - int bResetRotation; - int rotation; -}; - -struct TrainThingRS { - float fRadiusX, fRadiusY; - float fStartAngle, fEndAngle; - int iNumPoints; - float fStartHeight, fEndHeight; -}; - -struct IntersectRS{ - int nBrushOptions; - bool bUseDetail; - bool bDuplicateOnly; -}; - -struct PolygonRS{ - bool bUseBorder; - bool bInverse; - bool bAlignTop; - int nSides; - int nBorderWidth; -}; - -struct DoorRS{ - char mainTexture[256]; - char trimTexture[256]; - bool bScaleMainH; - bool bScaleMainV; - bool bScaleTrimH; - bool bScaleTrimV; - int nOrientation; -}; - -struct PathPlotterRS{ - int nPoints; - float fMultiplier; - float fGravity; - bool bNoUpdate; - bool bShowExtra; -}; - -struct MakeChainRS{ - char linkName[256]; - int linkNum; -}; - -typedef struct _GtkWidget GtkWidget; - -struct TwinWidget{ - GtkWidget* one; - GtkWidget* two; -}; - -EMessageBoxReturn DoMessageBox(const char* lpText, const char* lpCaption, EMessageBoxType type); -EMessageBoxReturn DoIntersectBox(IntersectRS* rs); -EMessageBoxReturn DoPolygonBox(PolygonRS* rs); -EMessageBoxReturn DoResetTextureBox (ResetTextureRS* rs); -EMessageBoxReturn DoBuildStairsBox(BuildStairsRS* rs); -EMessageBoxReturn DoDoorsBox(DoorRS* rs); -EMessageBoxReturn DoPathPlotterBox(PathPlotterRS* rs); -EMessageBoxReturn DoCTFColourChangeBox(); -EMessageBoxReturn DoTrainThingBox (TrainThingRS* rs); -EMessageBoxReturn DoMakeChainBox(MakeChainRS* rs); -//GtkWidget* GetProgressWindow(char* title, GtkProgressBar* feedback); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/pathplotterdialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/pathplotterdialog.cpp deleted file mode 100644 index ae638529..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/pathplotterdialog.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// PathPlotterDialog.cpp : implementation file -// - -#include "../StdAfx.h" -#include "../bobtoolz.h" -#include "PathPlotterDialog.h" - -#ifdef _DEBUG -#define new DEBUG_NEW -#undef THIS_FILE -static char THIS_FILE[] = __FILE__; -#endif - -///////////////////////////////////////////////////////////////////////////// -// CPathPlotterDialog dialog - - -CPathPlotterDialog::CPathPlotterDialog(CWnd* pParent /*=NULL*/) - : CDialog(CPathPlotterDialog::IDD, pParent) -{ - //{{AFX_DATA_INIT(CPathPlotterDialog) - m_fGravity = -800.0f; - m_fMultiplier = 3.0f; - m_bNoUpdate = FALSE; - m_nPoints = 25; - m_bShowExtra = FALSE; - //}}AFX_DATA_INIT -} - - -void CPathPlotterDialog::DoDataExchange(CDataExchange* pDX) -{ - CDialog::DoDataExchange(pDX); - //{{AFX_DATA_MAP(CPathPlotterDialog) - DDX_Text(pDX, IDC_GRAVITY_EDIT, m_fGravity); - DDV_MinMaxFloat(pDX, m_fGravity, -10000.f, -1.f); - DDX_Text(pDX, IDC_MULTIPLIER_EDIT, m_fMultiplier); - DDV_MinMaxFloat(pDX, m_fMultiplier, 1.f, 10.f); - DDX_Check(pDX, IDC_NOUPDATE_CHECK, m_bNoUpdate); - DDX_Text(pDX, IDC_POINTCOUNT_EDIT, m_nPoints); - DDV_MinMaxInt(pDX, m_nPoints, 1, 1000); - DDX_Check(pDX, IDC_SHOWEXTRA_CHECK, m_bShowExtra); - //}}AFX_DATA_MAP -} - - -BEGIN_MESSAGE_MAP(CPathPlotterDialog, CDialog) - //{{AFX_MSG_MAP(CPathPlotterDialog) - ON_BN_CLICKED(IDYES, OnYes) - ON_BN_CLICKED(IDNO, OnNo) - //}}AFX_MSG_MAP -END_MESSAGE_MAP() - -///////////////////////////////////////////////////////////////////////////// -// CPathPlotterDialog message handlers - -void CPathPlotterDialog::OnYes() -{ - if(UpdateData()) - EndModalLoop(IDYES); -} - -void CPathPlotterDialog::OnNo() -{ - EndModalLoop(IDNO); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/pathplotterdialog.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/pathplotterdialog.h deleted file mode 100644 index 6edd8987..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/dialogs/pathplotterdialog.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(AFX_PATHPLOTTERDIALOG_H__A0516221_F19B_11D4_ACF7_004095A18133__INCLUDED_) -#define AFX_PATHPLOTTERDIALOG_H__A0516221_F19B_11D4_ACF7_004095A18133__INCLUDED_ - -#if _MSC_VER > 1000 -#pragma once -#endif // _MSC_VER > 1000 -// PathPlotterDialog.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CPathPlotterDialog dialog - -class CPathPlotterDialog : public CDialog -{ -// Construction -public: - CPathPlotterDialog(CWnd* pParent = NULL); // standard constructor - -// Dialog Data - //{{AFX_DATA(CPathPlotterDialog) - enum { IDD = IDD_PATHPLOTTER_DIALOG }; - float m_fGravity; - float m_fMultiplier; - BOOL m_bNoUpdate; - int m_nPoints; - BOOL m_bShowExtra; - //}}AFX_DATA - - -// Overrides - // ClassWizard generated virtual function overrides - //{{AFX_VIRTUAL(CPathPlotterDialog) - protected: - virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support - //}}AFX_VIRTUAL - -// Implementation -protected: - - // Generated message map functions - //{{AFX_MSG(CPathPlotterDialog) - afx_msg void OnYes(); - afx_msg void OnNo(); - //}}AFX_MSG - DECLARE_MESSAGE_MAP() -}; - -//{{AFX_INSERT_LOCATION}} -// Microsoft Visual C++ will insert additional declarations immediately before the previous line. - -#endif // !defined(AFX_PATHPLOTTERDIALOG_H__A0516221_F19B_11D4_ACF7_004095A18133__INCLUDED_) diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers-GTK.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers-GTK.cpp deleted file mode 100644 index 8f26d714..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers-GTK.cpp +++ /dev/null @@ -1,890 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "funchandlers.h" - -#ifdef WIN32 -#pragma warning(disable : 4786) -#endif - -#include "dialogs/dialogs-gtk.h" - -#include -#include "str.h" - -#include "DPoint.h" -#include "DPlane.h" -#include "DBrush.h" -#include "DEPair.h" -#include "DPatch.h" -#include "DEntity.h" -#include "DShape.h" -#include "DBobView.h" -#include "DVisDrawer.h" -#include "DTrainDrawer.h" - -#include "misc.h" -#include "ScriptParser.h" -#include "DTreePlanter.h" - -#include "shapes.h" -#include "lists.h" -#include "visfind.h" - -#include "iundo.h" - -#include -#include -#include -#include - -#include "scenelib.h" - -// for autocaulk -std::list exclusionList; // whole brush exclusion -std::list exclusionList_Face; // single face exclusion - -bool el1Loaded = false; -bool el2Loaded = false; -bool clrLst1Loaded = false; -bool clrLst2Loaded = false; - -DBobView* g_PathView = NULL; -DVisDrawer* g_VisView = NULL; -DTrainDrawer* g_TrainView = NULL; -DTreePlanter* g_TreePlanter = NULL; -// ------------- - -//========================// -// Helper Functions // -//========================// - -void LoadLists() -{ - char buffer[256]; - - if(!el1Loaded) - el1Loaded = LoadExclusionList(GetFilename(buffer, "bt/bt-el1.txt"), &exclusionList); - if(!el2Loaded) - el2Loaded = LoadExclusionList(GetFilename(buffer, "bt/bt-el2.txt"), &exclusionList_Face); -} - - -//========================// -// Main Functions // -//========================// - -void DoIntersect() -{ - UndoableCommand undo("bobToolz.intersect"); - IntersectRS rs; - - if(DoIntersectBox(&rs) == eIDCANCEL) - return; - - if(rs.nBrushOptions == BRUSH_OPT_SELECTED) - { - if( GlobalSelectionSystem().countSelected() < 2 ) - { - //DoMessageBox("Invalid number of brushes selected, choose at least 2", "Error", eMB_OK); - globalErrorStream() << "bobToolz Intersect: Invalid number of brushes selected, choose at least 2.\n"; - return; - } - } - - DEntity world; - switch(rs.nBrushOptions) - { - case BRUSH_OPT_SELECTED: - { - - world.LoadFromEntity(GlobalRadiant().getMapWorldEntity(), false); - world.LoadSelectedBrushes(); - break; - } - case BRUSH_OPT_WHOLE_MAP: - { - world.LoadFromEntity(GlobalRadiant().getMapWorldEntity(), false); - break; - } - } - world.RemoveNonCheckBrushes(&exclusionList, rs.bUseDetail); - - bool* pbSelectList; - if(rs.bDuplicateOnly) - pbSelectList = world.BuildDuplicateList(); - else - pbSelectList = world.BuildIntersectList(); - - world.SelectBrushes(pbSelectList); - int brushCount = GlobalSelectionSystem().countSelected(); - globalOutputStream() << "bobToolz Intersect: " << brushCount << " intersecting brushes found.\n"; - delete[] pbSelectList; -} - -void DoPolygonsTB() -{ - DoPolygons(); -} - -void DoPolygons() -{ - UndoableCommand undo("bobToolz.polygons"); - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz Polygons: Invalid number of brushes selected, choose 1 only.\n"; - return; - } - - PolygonRS rs; - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - if( !Node_isBrush(instance.path().top()) ) { - //DoMessageBox("No brush selected, select ONLY one brush", "Error", eMB_OK); - globalErrorStream() << "bobToolz Polygons: No brush selected, select ONLY one brush.\n"; - return; - } - // ask user for type, size, etc.... - if(DoPolygonBox(&rs) == eIDOK) - { - DShape poly; - - vec3_t vMin, vMax; - - { - - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); - - Path_deleteTop(instance.path()); - } - - if(rs.bInverse) - poly.BuildInversePrism(vMin, vMax, rs.nSides, rs.bAlignTop); - else - { - if(rs.bUseBorder) - poly.BuildBorderedPrism(vMin, vMax, rs.nSides, rs.nBorderWidth, rs.bAlignTop); - else - poly.BuildRegularPrism(vMin, vMax, rs.nSides, rs.bAlignTop); - - } - - poly.Commit(); - } -} - -void DoFixBrushes() -{ - UndoableCommand undo("bobToolz.fixBrushes"); - DMap world; - world.LoadAll(); - - int count = world.FixBrushes(); - - globalOutputStream() << "bobToolz FixBrushes: " << count << " invalid/duplicate planes removed.\n"; -} - -void DoResetTextures() -{ - UndoableCommand undo("bobToolz.resetTextures"); - static ResetTextureRS rs; - - const char* texName; - if(1/*g_SelectedFaceTable.m_pfnGetSelectedFaceCount() != 1*/) - { - texName = NULL; - } - else - { - texName = GetCurrentTexture(); - strcpy(rs.textureName, GetCurrentTexture()); - } - - EMessageBoxReturn ret; - if((ret = DoResetTextureBox(&rs)) == eIDCANCEL) - return; - - if(rs.bResetTextureName) - texName = rs.textureName; - - if(ret == eIDOK) - { - DEntity world; - world.LoadSelectedBrushes(); - world.ResetTextures(texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, - rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation, true); - } - else - { - DMap world; - world.LoadAll(true); - world.ResetTextures(texName, rs.fScale, rs.fShift, rs.rotation, rs.newTextureName, - rs.bResetTextureName, rs.bResetScale, rs.bResetShift, rs.bResetRotation); - } -} - -void DoBuildStairs() -{ - UndoableCommand undo("bobToolz.buildStairs"); - BuildStairsRS rs; - - strcpy(rs.mainTexture, GetCurrentTexture()); - - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz BuildStairs: Invalid number of brushes selected, choose 1 only.\n"; - return; - } - - // ask user for type, size, etc.... - if(DoBuildStairsBox(&rs) == eIDOK) - { - vec3_t vMin, vMax; - - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); - } - - // calc brush size - vec3_t size; - VectorSubtract(vMax, vMin, size); - - if(((int)size[2] % rs.stairHeight) != 0) - { - // stairs must fit evenly into brush - //DoMessageBox("Invalid stair height\nHeight of block must be divisable by stair height", "Error", eMB_OK); - globalErrorStream() << "bobToolz BuildStairs: Invalid stair height. Height of block must be divisable by stair height.\n"; - } - else - { - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - Path_deleteTop(instance.path()); - } - - // Get Step Count - int numSteps = (int)size[2] / rs.stairHeight; - - if(rs.style == STYLE_CORNER) - { - BuildCornerStairs(vMin, vMax, numSteps, rs.mainTexture, rs.riserTexture); - } - else - { - - // Get Step Dimensions - float stairHeight = (float)rs.stairHeight; - float stairWidth; - if((rs.direction == MOVE_EAST) || (rs.direction == MOVE_WEST)) - stairWidth = (size[0])/numSteps; - else - stairWidth = (size[1])/numSteps; - - - // Build Base For Stair (bob's style) - if(rs.style == STYLE_BOB) - Build_Wedge(rs.direction, vMin, vMax, true); - - - // Set First Step Starting Position - vMax[2] = vMin[2] + stairHeight; - SetInitialStairPos(rs.direction, vMin, vMax, stairWidth); - - - // Build The Steps - for(int i = 0; i < numSteps; i++) - { - if(rs.style == STYLE_BOB) - Build_StairStep_Wedge(rs.direction, vMin, vMax, rs.mainTexture, rs.riserTexture, rs.bUseDetail); - else if(rs.style == STYLE_ORIGINAL) - Build_StairStep(vMin, vMax, rs.mainTexture, rs.riserTexture, rs.direction); - - // get step into next position - MoveBlock(rs.direction, vMin, vMax, stairWidth); - vMax[2] += stairHeight; - if(rs.style == STYLE_BOB) - vMin[2] += stairHeight; // wedge bottom must be raised - } - } - } - } -} - -void DoBuildDoors() -{ - UndoableCommand undo("bobToolz.buildDoors"); - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz BuildDoors: Invalid number of brushes selected, choose 1 only.\n"; - return; - } - - DoorRS rs; - strcpy(rs.mainTexture, GetCurrentTexture()); - - if(DoDoorsBox(&rs) == eIDOK) - { - vec3_t vMin, vMax; - - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); - Path_deleteTop(instance.path()); - } - - BuildDoorsX2(vMin, vMax, - rs.bScaleMainH, rs.bScaleMainV, - rs.bScaleTrimH, rs.bScaleTrimV, - rs.mainTexture, rs.trimTexture, - rs.nOrientation); // shapes.cpp - } -} - -void DoPathPlotter() -{ - UndoableCommand undo("bobToolz.pathPlotter"); - PathPlotterRS rs; - EMessageBoxReturn ret = DoPathPlotterBox(&rs); - if(ret == eIDCANCEL) - return; - if(ret == eIDNO) - { - if(g_PathView) - delete g_PathView; - return; - } - - // ensure we have something selected - /* - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); - globalOutputStream() << "bobToolz PathPlotter: Invalid number of entities selected, choose 1 trigger_push entity only.\n"; - return; - } - */ - Entity* entity = Node_getEntity(GlobalSelectionSystem().ultimateSelected().path().top()); - if(entity != 0) - { - DBobView_setEntity(*entity, rs.fMultiplier, rs.nPoints, rs.fGravity, rs.bNoUpdate, rs.bShowExtra); - } - else globalErrorStream() << "bobToolz PathPlotter: No trigger_push entitity selected, select 1 only (Use list to select it).\n"; - return; -} - -void DoPitBuilder() -{ - UndoableCommand undo("bobToolz.pitBuilder"); - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of brushes selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz PitBuilder: Invalid number of brushes selected, choose 1 only.\n"; - return; - } - - vec3_t vMin, vMax; - - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - //seems it does this also with a patch with valid dimensions.. but probably better to enforce a brush. - if( !Node_isBrush(instance.path().top()) ) { - //DoMessageBox("No brush selected, select ONLY one brush", "Error", eMB_OK); - globalErrorStream() << "bobToolz PitBuilder: No brush selected, select ONLY 1 brush.\n"; - return; - } - - VectorSubtract(instance.worldAABB().origin, instance.worldAABB().extents, vMin); - VectorAdd(instance.worldAABB().origin, instance.worldAABB().extents, vMax); - - DShape pit; - - if(pit.BuildPit(vMin, vMax)) - { - pit.Commit(); - Path_deleteTop(instance.path()); - } - else - { - //DoMessageBox("Failed To Make Pit\nTry Making The Brush Bigger", "Error", eMB_OK); - globalErrorStream() << "bobToolz PitBuilder: Failed to make Pit, try making the brush bigger.\n"; - } -} - -void DoMergePatches() -{ - UndoableCommand undo("bobToolz.mergePatches"); - patch_merge_t merge_info; - DPatch mrgPatches[2]; - int i; - - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 2 ) - { - globalErrorStream() << "bobToolz MergePatches: Invalid number of patches selected, choose 2 only.\n"; - //DoMessageBox("Invalid number of patches selected, choose 2 only", "Error", eMB_OK); - return; - } - - scene::Instance* patches[2]; - patches[0] = &GlobalSelectionSystem().ultimateSelected(); - patches[1] = &GlobalSelectionSystem().penultimateSelected(); - - for (i = 0; i < 2; i++) - { - if (!Node_isPatch(patches[i]->path().top())) - { - //DoMessageBox("No patches selected, select ONLY patches", "Error", eMB_OK); - globalErrorStream() << "bobToolz MergePatches: Invalid number of patches selected, choose ONLY 2 patches.\n"; - return; - } - - mrgPatches[i].LoadFromPatch(*patches[i]); - } - - /* mrgPatches[0].Transpose(); - mrgPatches[0].RemoveFromRadiant(); - mrgPatches[0].BuildInRadiant();*/ - - merge_info = mrgPatches[0].IsMergable(&mrgPatches[1]); - - if (merge_info.mergable) - { - globalOutputStream() << merge_info.pos1 << " " << merge_info.pos2; - //Message removed, No tools give feedback on success. - //globalOutputStream() << "bobToolz MergePatches: Patches Mergable.\n"; - DPatch* newPatch = mrgPatches[0].MergePatches(merge_info, &mrgPatches[0], &mrgPatches[1]); - - /* mrgPatches[0].RemoveFromRadiant(); - mrgPatches[0].BuildInRadiant(); - - mrgPatches[1].RemoveFromRadiant(); - mrgPatches[1].BuildInRadiant(); - - - delete newPatch;*/ - - if (!newPatch) - { - } else - { - Path_deleteTop(patches[0]->path()); - Path_deleteTop(patches[1]->path()); - - newPatch->BuildInRadiant(); - delete newPatch; - } - } - else - { - globalErrorStream() << "bobToolz.mergePatch: The selected patches are not mergable.\n"; - - } -} - -void DoSplitPatch() { - UndoableCommand undo("bobToolz.splitPatch"); - - DPatch patch; - - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of patches selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz SplitPatch: Invalid number of patches selected, choose only 1 patch.\n"; - return; - } - - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - - if( !Node_isPatch(instance.path().top()) ) { - //DoMessageBox("No patch selected, select ONLY one patch", "Error", eMB_OK); - globalErrorStream() << "bobToolz SplitPatch: No patch selected, select ONLY 1 patch.\n"; - return; - } - - patch.LoadFromPatch(instance); - - std::list patchList = patch.Split(); - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) { - (*patches).BuildInRadiant(); - } - - Path_deleteTop(instance.path()); -} - -void DoSplitPatchCols() { - UndoableCommand undo("bobToolz.splitPatchCols"); - - DPatch patch; - - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of patches selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz SplitPatchCols: Invalid number of patches selected, choose 1 only.\n"; - return; - } - - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - - if( !Node_isPatch(instance.path().top()) ) { - //DoMessageBox("No patch selected, select ONLY one patch", "Error", eMB_OK); - globalErrorStream() << "bobToolz SplitPatchCols: No patch selected, select ONLY 1 patch.\n"; - return; - } - - patch.LoadFromPatch(instance); - - std::list patchList = patch.SplitCols(); - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) { - (*patches).BuildInRadiant(); - } - - Path_deleteTop(instance.path()); -} - -void DoSplitPatchRows() { - UndoableCommand undo("bobToolz.splitPatchRows"); - - DPatch patch; - - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of patches selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz SplitPatchRows: Invalid number of patches selected, choose 1 only.\n"; - return; - } - - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - - if( !Node_isPatch(instance.path().top()) ) { - //DoMessageBox("No patch selected, select ONLY one patch", "Error", eMB_OK); - globalErrorStream() << "bobToolz SplitPatchRows: No patch selected, select ONLY 1 patch.\n"; - return; - } - - patch.LoadFromPatch(instance); - - std::list patchList = patch.SplitRows(); - for(std::list::iterator patches = patchList.begin(); patches != patchList.end(); patches++) { - (*patches).BuildInRadiant(); - } - - Path_deleteTop(instance.path()); -} - -void DoVisAnalyse() -{ - char filename[1024]; - - if( GlobalSelectionSystem().countSelected() == 0 ) - { - globalErrorStream() << "bobToolz VisAnalyse: Invalid number of objects selected, choose 1 only.\n"; - if(g_VisView) - { - delete g_VisView; - return; - } - } - - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 1 ) - { - //DoMessageBox("Invalid number of objects selected, choose 1 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz VisAnalyse: Invalid number of objects selected, choose 1 only.\n"; - return; - } - - scene::Instance& brush = GlobalSelectionSystem().ultimateSelected(); - //ensure we have a brush selected - if( !Node_isBrush(brush.path().top()) ) { - //DoMessageBox("No brush selected, select ONLY one brush", "Error", eMB_OK); - globalErrorStream() << "bobToolz VisAnalyse: No brush selected, select ONLY 1 brush.\n"; - return; - } - DBrush orgBrush; - orgBrush.LoadFromBrush(brush, false); - - orgBrush.BuildBounds(); - vec3_t origin; - origin[0] = (orgBrush.bbox_max[0] + orgBrush.bbox_min[0])/2.f; - origin[1] = (orgBrush.bbox_max[1] + orgBrush.bbox_min[1])/2.f; - origin[2] = (orgBrush.bbox_max[2] + orgBrush.bbox_min[2])/2.f; - - - const char* rad_filename = GlobalRadiant().getMapName(); - if(!rad_filename) - { - //DoMessageBox("An ERROR occurred while trying\n to get the map filename", "Error", eMB_OK); - globalErrorStream() << "bobToolz VisAnalyse: An ERROR occurred while trying to get the map filename.\n"; - return; - } - - strcpy(filename, rad_filename); - - char* ext = strrchr(filename, '.')+1; - strcpy(ext, "bsp");// rename the extension - - std::list *pointList = BuildTrace(filename, origin); - - if(!g_VisView) - { - g_VisView = new DVisDrawer; - } - - g_VisView->SetList(pointList); -} - -void DoTrainPathPlot() { - if(g_TrainView) { - delete g_TrainView; - g_TrainView = NULL; - } - - g_TrainView = new DTrainDrawer(); -} - -void DoCaulkSelection() { - UndoableCommand undo("bobToolz.caulkSelection"); - DEntity world; - - float fScale[2] = { 0.5f, 0.5f }; - float fShift[2] = { 0.0f, 0.0f }; - - int bResetScale[2] = { false, false }; - int bResetShift[2] = { false, false }; - - world.LoadSelectedBrushes(); - world.LoadSelectedPatches(); - world.ResetTextures( NULL, fScale, fShift, 0, "textures/common/caulk", true, bResetScale, bResetShift, false, true ); -} - -void DoTreePlanter() { - UndoableCommand undo("bobToolz.treePlanter"); - if(g_TreePlanter) { - delete g_TreePlanter; - g_TreePlanter = NULL; - return; - } - - g_TreePlanter = new DTreePlanter(); -} - -void DoDropEnts() { - UndoableCommand undo("bobToolz.dropEntities"); - if(g_TreePlanter) { - g_TreePlanter->DropEntsToGround(); - } -} - -void DoMakeChain() { - MakeChainRS rs; - if(DoMakeChainBox(&rs) == eIDOK) - { - if ( rs.linkNum > 1001 ) { - globalErrorStream() << "bobToolz MakeChain: " << rs.linkNum << " to many Elemets, limited to 1000.\n"; - return; - } - UndoableCommand undo("bobToolz.makeChain"); - DTreePlanter pl; - pl.MakeChain(rs.linkNum,rs.linkName); - } -} - -typedef DPoint* pntTripple[3]; - -bool bFacesNoTop[6] = {true, true, true, true, true, false}; - -void DoFlipTerrain() { - UndoableCommand undo("bobToolz.flipTerrain"); - vec3_t vUp = { 0.f, 0.f, 1.f }; - int i; - - // ensure we have something selected - if( GlobalSelectionSystem().countSelected() != 2 ) - { - //DoMessageBox("Invalid number of objects selected, choose 2 only", "Error", eMB_OK); - globalErrorStream() << "bobToolz FlipTerrain: Invalid number of objects selected, choose 2 only.\n"; - return; - } - - scene::Instance* brushes[2]; - brushes[0] = &GlobalSelectionSystem().ultimateSelected(); - brushes[1] = &GlobalSelectionSystem().penultimateSelected(); - //ensure we have only Brushes selected. - for (i = 0; i < 2; i++) - { - if( !Node_isBrush(brushes[i]->path().top()) ) { - //DoMessageBox("No brushes selected, select ONLY brushes", "Error", eMB_OK); - globalErrorStream() << "bobToolz FlipTerrain: No brushes selected, select ONLY 2 brushes.\n"; - return; - } - } - DBrush Brushes[2]; - DPlane* Planes[2]; - pntTripple Points[2]; - for( i = 0; i < 2; i++ ) { - Brushes[i].LoadFromBrush( *brushes[i], false ); - if(!(Planes[i] = Brushes[i].FindPlaneWithClosestNormal( vUp )) || Brushes[i].FindPointsForPlane( Planes[i], Points[i], 3 ) != 3) { - //DoMessageBox("Error", "Error", eMB_OK); - globalErrorStream() << "bobToolz FlipTerrain: ERROR (FindPlaneWithClosestNormal/FindPointsForPlane).\n"; - return; - } - } - - vec3_t mins1, mins2, maxs1, maxs2; - Brushes[0].GetBounds( mins1, maxs1 ); - Brushes[1].GetBounds( mins2, maxs2 ); - - - - int dontmatch[2] = { -1, -1 }; - bool found = false; - for( i = 0; i < 3; i++ ) { - for( int j = 0; j < 3 && !found; j++ ) { - if(VectorCompare( (Points[0])[i]->_pnt, (Points[1])[j]->_pnt )) { - found = true; - break; - } - } - if(!found) { - dontmatch[0] = i; - break; - } - found = false; - } - if(dontmatch[0] == -1) { - //DoMessageBox("Error", "Error", eMB_OK); - globalErrorStream() << "bobToolz FlipTerrain: ERROR (dontmatch[0]).\n"; - return; - } - - for( i = 0; i < 3; i++ ) { - for( int j = 0; j < 3 && !found; j++ ) { - if(VectorCompare( (Points[1])[i]->_pnt, (Points[0])[j]->_pnt )) { - found = true; - break; - } - } - if(!found) { - dontmatch[1] = i; - break; - } - found = false; - } - if(dontmatch[1] == -1) { - //DoMessageBox("Error", "Error", eMB_OK); - globalErrorStream() << "bobToolz FlipTerrain: ERROR (dontmatch[1]).\n"; - return; - } - - vec3_t plnpnts1[3]; - vec3_t plnpnts2[3]; - vec3_t plnpntsshr[3]; - - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpnts1[0] ); - for( i = 0; i < 3; i++ ) { - if( dontmatch[0] != i ) { - VectorCopy( (Points[0])[i]->_pnt, plnpnts1[1] ); - break; - } - } - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpnts1[2] ); - - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpnts2[0] ); - for( i = 0; i < 3; i++ ) { - if( dontmatch[1] != i && !VectorCompare( (Points[1])[i]->_pnt, plnpnts1[1] )) { - VectorCopy( (Points[1])[i]->_pnt, plnpnts2[1] ); - break; - } - } - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpnts2[2] ); - - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpntsshr[0] ); - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpntsshr[1] ); - if( (Points[1])[dontmatch[1]]->_pnt[2] < (Points[0])[dontmatch[0]]->_pnt[2] ) { - VectorCopy( (Points[1])[dontmatch[1]]->_pnt, plnpntsshr[2] ); - } else { - VectorCopy( (Points[0])[dontmatch[0]]->_pnt, plnpntsshr[2] ); - } - plnpntsshr[2][2] -= 16; - - for( i = 0; i < 3; i++ ) { - if( mins2[i] < mins1[i] ) { - mins1[i] = mins2[i]; - } - if( maxs2[i] > maxs1[i] ) { - maxs1[i] = maxs2[i]; - } - } - - DBrush* newBrushes[2]; - newBrushes[0] = DShape::GetBoundingCube_Ext( mins1, maxs1, "textures/common/caulk", bFacesAll, true); - newBrushes[1] = DShape::GetBoundingCube_Ext( mins1, maxs1, "textures/common/caulk", bFacesAll, true); - - vec3_t normal; - MakeNormal( plnpnts1[0], plnpnts1[1], plnpnts1[2], normal ); - if( normal[2] >= 0 ) { - newBrushes[0]->AddFace( plnpnts1[0], plnpnts1[1], plnpnts1[2], "textures/common/terrain", true ); - } else { - newBrushes[0]->AddFace( plnpnts1[2], plnpnts1[1], plnpnts1[0], "textures/common/terrain", true ); - } - - MakeNormal( plnpnts2[0], plnpnts2[1], plnpnts2[2], normal ); - if( normal[2] >= 0 ) { - newBrushes[1]->AddFace( plnpnts2[0], plnpnts2[1], plnpnts2[2], "textures/common/terrain", true ); - } else { - newBrushes[1]->AddFace( plnpnts2[2], plnpnts2[1], plnpnts2[0], "textures/common/terrain", true ); - } - - vec3_t vec; - MakeNormal( plnpntsshr[0], plnpntsshr[1], plnpntsshr[2], normal ); - - VectorSubtract( plnpnts1[2], plnpnts1[1], vec ); - if( DotProduct( vec, normal ) >= 0 ) { - newBrushes[0]->AddFace( plnpntsshr[0], plnpntsshr[1], plnpntsshr[2], "textures/common/caulk", true ); - } else { - newBrushes[0]->AddFace( plnpntsshr[2], plnpntsshr[1], plnpntsshr[0], "textures/common/caulk", true ); - } - - VectorSubtract( plnpnts2[2], plnpnts2[1], vec ); - if( DotProduct( vec, normal ) >= 0 ) { - newBrushes[1]->AddFace( plnpntsshr[0], plnpntsshr[1], plnpntsshr[2], "textures/common/caulk", true ); - } else { - newBrushes[1]->AddFace( plnpntsshr[2], plnpntsshr[1], plnpntsshr[0], "textures/common/caulk", true ); - } - - for( i = 0; i < 2; i++ ) { - newBrushes[i]->RemoveRedundantPlanes(); - newBrushes[i]->BuildInRadiant( false, NULL, brushes[i]->path().parent().get_pointer() ); - Path_deleteTop(brushes[i]->path()); - delete newBrushes[i]; - } - -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers-ctf-GTK.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers-ctf-GTK.cpp deleted file mode 100644 index b01fc7cb..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers-ctf-GTK.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "StdAfx.h" - -#include "dialogs/dialogs-gtk.h" - -#include "DEntity.h" -#include "DMap.h" - -#include "misc.h" -#include "lists.h" -#include "funchandlers.h" - -// for ctf texture changer -list clrList_Blue; -list clrList_Red; - -BOOL clrLst1Loaded = FALSE; -BOOL clrLst2Loaded = FALSE; - -// ------------- - -//========================// -// Helper Functions // -//========================// - -void LoadLists() -{ - char buffer[256]; - - if(!clrLst1Loaded) - { - clrLst1Loaded = LoadExclusionList(GetFilename(buffer, "plugins/bt/ctf-blue.txt"), &clrList_Blue); - LoadExclusionList(GetFilename(buffer, "plugins/bt/blue.txt"), &clrList_Blue); - } - if(!clrLst2Loaded) - { - clrLst2Loaded = LoadExclusionList(GetFilename(buffer, "plugins/bt/ctf-red.txt"), &clrList_Red); - LoadExclusionList(GetFilename(buffer, "plugins/bt/red.txt"), &clrList_Red); - } -} - - -//========================// -// Main Functions // -//========================// - -void DoCTFColourChanger() -{ - if(!clrLst1Loaded || !clrLst2Loaded) - { - DoMessageBox("CTF texture lists not found, this function will terminate.", "Error", MB_OK); - return; - } - - int ret = DoCTFColourChangeBox(); - if(ret == IDCANCEL) - return; - - int cnt = Min(clrList_Blue.size(), clrList_Red.size()); - - list::const_iterator Texture_change; - list::const_iterator Texture_new; - - float fDummy[2]; - - int eCnt = g_FuncTable.m_pfnGetEntityCount(); - - DMap world; - world.LoadAll(TRUE); - - if(ret == IDYES) - { - Texture_change = clrList_Blue.begin(); - Texture_new = clrList_Red.begin(); - } - else - { - Texture_change = clrList_Red.begin(); - Texture_new = clrList_Blue.begin(); - } - - for(int i = 0; i < cnt; i++) - { - world.ResetTextures((*Texture_change).c_str(), fDummy, fDummy, 0, (*Texture_new).c_str(), TRUE); - - Texture_change++; - Texture_new++; - } -} - -void DoSwapLights() -{ -/* DMap world; - world.LoadAll(); - - for(list::const_iterator loopEnt = world.entityList.begin(); loopEnt != world.entityList.end(); loopEnt++) - { - DEntity* e = (*loopEnt); - DEPair* epLightColour = e->FindEPairByKey("_color"); - if(epLightColour) - { - float r, g, b; - sscanf(epLightColour->value, "%f %f %f", &r, &g, &b); - sprintf(epLightColour->value, "%f %f %f", b, g, r); - DMap::RebuildEntity(e); - } - }*/ - - int cnt = g_FuncTable.m_pfnGetEntityCount(); - - for(int i = 0; i < cnt; i++) - { - void* ent = g_FuncTable.m_pfnGetEntityHandle(i); - - for(epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList(ent); epList; epList= epList->next) - { - if(!stricmp("_color", epList->key)) - { - float r, g, b; - sscanf(epList->value, "%f %f %f", &r, &g, &b); - sprintf(epList->value, "%f %f %f", b, g, r); - } - } - } -} - -void DoChangeAngles() -{ - int cnt = g_FuncTable.m_pfnGetEntityCount(); - - for(int i = 0; i < cnt; i++) - { - void* ent = g_FuncTable.m_pfnGetEntityHandle(i); - - for(epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList(ent); epList; epList= epList->next) - { - if(!stricmp("angle", epList->key)) - { - float angle; - sscanf(epList->value, "%f", &angle); - angle += 180; - while(angle > 360) - angle -= 360; - - sprintf(epList->value, "%f", angle); - } - } - } -} - -void DoSwapSpawns() -{ - int cnt = g_FuncTable.m_pfnGetEntityCount(); - - for(int i = 0; i < cnt; i++) - { - void* ent = g_FuncTable.m_pfnGetEntityHandle(i); - - for(epair_t* epList = *g_FuncTable.m_pfnGetEntityKeyValList(ent); epList; epList= epList->next) - { - if(!stricmp("classname", epList->key)) - { - if(!strcmp(epList->value, "team_CTF_redplayer")) - sprintf(epList->value, "team_CTF_blueplayer"); - else if(!strcmp(epList->value, "team_CTF_blueplayer")) - sprintf(epList->value, "team_CTF_redplayer"); - - if(!strcmp(epList->value, "team_CTF_redspawn")) - sprintf(epList->value, "team_CTF_bluespawn"); - else if(!strcmp(epList->value, "team_CTF_bluespawn")) - sprintf(epList->value, "team_CTF_redspawn"); - - if(!strcmp(epList->value, "team_CTF_redflag")) - sprintf(epList->value, "team_CTF_blueflag"); - else if(!strcmp(epList->value, "team_CTF_blueflag")) - sprintf(epList->value, "team_CTF_redflag") - ; - if(!strcmp(epList->value, "team_redobelisk")) - sprintf(epList->value, "team_blueobelisk"); - else if(!strcmp(epList->value, "team_blueobelisk")) - sprintf(epList->value, "team_redobelisk"); - } - } - } -} - -/*void test() -{ - DMap world; - world.LoadAll(); - - for(list::const_iterator ents = world.entityList.begin(); ents != world.entityList.end(); ents++) - { - (*ents)->RemoveFromRadiant(); - } -}*/ diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers.cpp deleted file mode 100644 index a429b78d..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers.cpp +++ /dev/null @@ -1,505 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "StdAfx.h" - -#include "funchandlers.h" - -#include "IntersectDialog.h" -#include "PolygonDialog.h" -#include "StairDialog.h" -#include "DoorDialog.h" -#include "IntersectInfoDialog.h" -#include "BrushCheckDialog.h" -#include "AutoCaulkDialog.h" -#include "AutoCaulkStartDialog.h" -#include "TextureResetDialog.h" -#include "pathplotterdialog.h" - -#include "DEntity.h" -#include "shapes.h" -#include "lists.h" -#include "misc.h" -#include "DShape.h" - -// for autocaulk -std::list exclusionList; // whole brush exclusion -std::list exclusionList_Face; // single face exclusion - -BOOL el1Loaded; -BOOL el2Loaded; - -DBobView* g_PathView = NULL; -// ------------- - -/************************ - Global Variables -************************/ - -CPolygonDialog polygonDlg; -CIntersectDialog intrDlg; -CStairDialog stairDlg; -CDoorDialog doorDlg; -CAutoCaulkStartDialog autocaulkDlg; -CTextureResetDialog texRstDlg; -CPathPlotterDialog ppDlg; - -/************************ - --Main Functions-- -************************/ - -void LoadLists() -{ - char buffer[256]; - - if(!el1Loaded) - el1Loaded = LoadExclusionList(GetFilename(buffer, "bt\\bt-el1.txt"), &exclusionList); - if(!el2Loaded) - el2Loaded = LoadExclusionList(GetFilename(buffer, "bt\\bt-el2.txt"), &exclusionList); -} - -void PolygonBuilder(vec3_t vMin, vec3_t vMax) -{ - // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; - } - - // tell Radiant we want to access the selected brushes - g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - - // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); - // cant release until we delete the brush, if we do... - - // ask user for type, size, etc.... - if(polygonDlg.DoModal() == IDOK) - { - DShape poly; - - g_FuncTable.m_pfnDeleteBrushHandle(brush); - - if(polygonDlg.m_bInverse) - poly.BuildInversePrism(vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_bAlignTop); - else - { - if(polygonDlg.m_bBorder) - poly.BuildBorderedPrism(vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_nBorderSize, polygonDlg.m_bAlignTop); - else - poly.BuildRegularPrism(vMin, vMax, polygonDlg.m_nSideCount, polygonDlg.m_bAlignTop); - } - - poly.Commit(); - } - - - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); -} - - -void IntersectionFinder() -{ - if(intrDlg.DoModal() == IDCANCEL) - return; - - if(intrDlg.m_nBrushOptions == BRUSH_OPT_SELECTED) - { - // ensure we have enough brushes selected - if( g_FuncTable.m_pfnSelectedBrushCount() < 2 ) - { - MessageBox(NULL, "Invalid number of brushes selected, choose at least 2", "Error", MB_OK); - return; - } - } - - CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); - intrInfoDlg->Create(IDD_INTERSECT_INFO_DIALOG); - - DEntity world; - - switch(intrDlg.m_nBrushOptions) - { - case BRUSH_OPT_SELECTED: - { - world.LoadSelectedBrushes(&intrInfoDlg->m_prog1); - break; - } - case BRUSH_OPT_WHOLE_MAP: - { - world.LoadFromEntity(0, &intrInfoDlg->m_prog1); - break; - } - } - - world.RemoveNonCheckBrushes(&exclusionList, intrDlg.m_bUseDetail); - BOOL* pbSelectList; - if(intrDlg.m_bDuplicateOnly) - pbSelectList = world.BuildDuplicateList(); - else - pbSelectList = world.BuildIntersectList(); - - world.SelectBrushes(pbSelectList); - - intrInfoDlg->DestroyWindow(); - delete[] pbSelectList; -} - -void StairBuilder(vec3_t vMin, vec3_t vMax) -{ - // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; - } - - // tell Radiant we want to access the selected brushes - g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - - // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); - // cant release until we delete the brush, if we do... - - - // ask user for type, size, etc.... - if(stairDlg.DoModal() == IDOK) - { - - // calc brush size - vec3_t size; - _VectorSubtract(vMax, vMin, size); - - - if(((int)size[2] % stairDlg.m_nStairHeight) != 0) - { - // stairs must fit evenly into brush - MessageBox(NULL, "Invalid stair height\nHeight of block must be divisable by stair height", "Error", MB_OK); - } - else - { - - // Remove Size Brush - g_FuncTable.m_pfnDeleteBrushHandle(brush); - - - // Get Step Count, Direction of Stairs, Stair Style - int numSteps = (int)size[2] / stairDlg.m_nStairHeight; - int direction = stairDlg.m_StairDir; - int style = stairDlg.m_StairStyle; - - if(stairDlg.m_StairStyle == STYLE_CORNER) - { - BuildCornerStairs(vMin, vMax, numSteps, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture); - } - else - { - // Get Step Dimensions - float stairHeight = (float)stairDlg.m_nStairHeight; - float stairWidth; - if((direction == MOVE_EAST) || (direction == MOVE_WEST)) - stairWidth = (size[0])/numSteps; - else - stairWidth = (size[1])/numSteps; - - - // Build Base For Stair (bob's style) - if(style == STYLE_BOB) - Build_Wedge(direction, vMin, vMax, TRUE); - - - // Set First Step Starting Position - vMax[2] = vMin[2] + stairHeight; - SetInitialStairPos(direction, vMin, vMax, stairWidth); - - - // Build The Steps - for(int i = 0; i < numSteps; i++) - { - if(style == STYLE_BOB) - Build_StairStep_Wedge(direction, vMin, vMax, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture, stairDlg.m_bDetail); - else if(style == STYLE_ORIGINAL) - Build_StairStep(vMin, vMax, "textures/common/caulk", (LPCTSTR)stairDlg.m_riserTexture, direction); - - // get step into next position - MoveBlock(direction, vMin, vMax, stairWidth); - vMax[2] += stairHeight; - if(style == STYLE_BOB) - vMin[2] += stairHeight; // wedge bottom must be raised - } - } - } - } - - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); -} - -void DoorBuilder(vec3_t vMin, vec3_t vMax) -{ - // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; - } - - // tell Radiant we want to access the selected brushes - g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - - // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); - // cant release until we delete the brush, if we do... - - - - strcpy(doorDlg.m_fbTextureName.GetBuffer(256), g_FuncTable.m_pfnGetCurrentTexture()); - - if(doorDlg.DoModal() == IDOK) - { - g_FuncTable.m_pfnDeleteBrushHandle(brush); - - BuildDoorsX2(vMin, vMax, - doorDlg.m_bSclMainHor, doorDlg.m_bSclMainVert, - doorDlg.m_bSclTrimHor, doorDlg.m_bSclTrimVert, - (LPCTSTR)doorDlg.m_fbTextureName, - (LPCTSTR)doorDlg.m_trimTextureName, - doorDlg.m_doorDirection); - } - - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); -} - -void FixBrushes() -{ - DEntity world; - - CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); - intrInfoDlg->Create(IDD_INTERSECT_INFO_DIALOG); - - world.LoadFromEntity(0, &intrInfoDlg->m_prog1); - - intrInfoDlg->DestroyWindow(); - - CBrushCheckDialog* chkDlg = new CBrushCheckDialog(); - chkDlg->Create(IDD_BRUSHCHECKER_DIALOG); - - int count = world.FixBrushes(TRUE, &chkDlg->m_prog1); - - chkDlg->DestroyWindow(); - - Sys_Printf("%i invalid/duplicate planes removed\n", count); -} - -void AutoCaulk() -{ - UndoableCommand undo("bobToolz.autoCaulk"); - - if(!el1Loaded) - autocaulkDlg.m_Warning1 = "WARNING: Brush exclusion list not found\n, ALL BRUSHES WILL BE USED"; - - if(autocaulkDlg.DoModal() == IDCANCEL) - return; - - if(autocaulkDlg.m_nMode == MODE_AC_BUILD_MINI_PRT) - { - BuildMiniPrt(&exclusionList); - return; - } - - CAutoCaulkDialog* acDlg = new CAutoCaulkDialog; - acDlg->Create(IDD_AUTOCAULK_DIALOG); - - char filename[1204]; - - if(autocaulkDlg.m_nMode == MODE_AC_NORMAL) - { - char* rad_filename = g_BSPTable.m_pfnGetMapName(); - if(!rad_filename) - { - MessageBox(NULL, "An Error Occurred While Trying To Get The Map Filename", "Error", MB_OK); - acDlg->DestroyWindow(); - return; - } - - strcpy(filename, rad_filename); - - char* ext = strrchr(filename, '.')+1; - strcpy(ext, "prt");// rename the extension - } - else - { - IEpair* pEp = g_EpairTable.m_pfnIEpairForProjectKeys(); - char *pn = pEp->ValueForKey("mapspath"); - pEp->DecRef(); - - strcpy( filename, pn ); - strcat( filename, "/ac_prt.prt" ); - } - - DEntity portals; - if(!portals.LoadFromPrt(filename, &acDlg->m_prog1)) - { - MessageBox(NULL, "Failed To Load Portal File", "Error", MB_OK); - acDlg->DestroyWindow(); - return; - } - // load portal file - - CIntersectInfoDialog* intrInfoDlg = new CIntersectInfoDialog(); - intrInfoDlg->Create(IDD_INTERSECT_INFO_DIALOG); - - DEntity world; - - world.LoadFromEntity(0, &intrInfoDlg->m_prog1); - intrInfoDlg->DestroyWindow(); - - if(autocaulkDlg.m_nMode == MODE_AC_NORMAL) - world.RemoveNonCheckBrushes(&exclusionList, FALSE); - else - world.RemoveNonCheckBrushes(&exclusionList, TRUE); - - world.ResetChecks(&exclusionList_Face); - - int caulkedCount = 0; - int killCnt = world.AutoCaulk(&portals, autocaulkDlg.m_bAllowDestruction, &caulkedCount, &acDlg->m_prog2); - - if(autocaulkDlg.m_bAllowDestruction) - Sys_Printf("%i unrequired brush(es) killed\n", killCnt); - Sys_Printf("%i face(s) caulked\n", caulkedCount); - - acDlg->DestroyWindow(); -} - -void ResetTextures() -{ - texRstDlg.m_TextureName = GetCurrentTexture(); - texRstDlg.m_NewTextureName = GetCurrentTexture(); - - if(texRstDlg.DoModal() == IDCANCEL) - return; - - float fScale[2]; - float fShift[2]; - fScale[1] = texRstDlg.m_fScaleVertical; - fScale[0] = texRstDlg.m_fScaleHorizontal; - - fShift[1] = (float)texRstDlg.m_nShiftVertical; - fShift[0] = (float)texRstDlg.m_nShiftHorizontal; - - DEntity world; - world.LoadFromEntity(0, NULL); - - if(texRstDlg.m_bAllTextures) - world.ResetTextures(NULL, fScale, fShift, texRstDlg.m_nRotation, texRstDlg.m_NewTextureName, texRstDlg.m_bOnlyTexture); - else - world.ResetTextures(texRstDlg.m_TextureName, fScale, fShift, texRstDlg.m_nRotation, texRstDlg.m_NewTextureName, texRstDlg.m_bOnlyTexture); -} - -void PathPlotter() -{ - int ret = ppDlg.DoModal(); - if(ret == IDCANCEL) - return; - if(ret == IDNO) - { - if(g_PathView) - delete g_PathView; - - return; - } - - if( g_FuncTable.m_pfnSelectedBrushCount() != 1) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; - } - - // tell Radiant we want to access the selected brushes - g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - - // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); - // cant release until we delete the brush, if we do... - - DEntity world; - world.LoadEPairList(*g_FuncTable.m_pfnGetEntityKeyValList(brush->owner)); - - DEPair* trigger_ep = world.FindEPairByKey("targetname"); - - if(trigger_ep) - { - if(!strcmp(world.m_Classname, "trigger_push")) - { - DEPair* target_ep = world.FindEPairByKey("target"); - if(target_ep) - { - entity_s* entTarget = FindEntityFromTargetname(target_ep->value); - if(entTarget) - { - if(g_PathView) - delete g_PathView; - g_PathView = new DBobView; - - g_PathView->Begin(trigger_ep->value, target_ep->value, ppDlg.m_fMultiplier, ppDlg.m_nPoints, ppDlg.m_fGravity, ppDlg.m_bNoUpdate, ppDlg.m_bShowExtra); - } - else - MessageBox(NULL, "trigger_push target could not be found.", "Error", MB_OK); - } - else - MessageBox(NULL, "trigger_push has no target.", "Error", MB_OK); - } - else - MessageBox(NULL, "You must select a 'trigger_push' entity.", "Error", MB_OK); - } - else - MessageBox(NULL, "Entity must have a targetname", "Error", MB_OK); - - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); -} - -void PitBuilder(vec3_t vMin, vec3_t vMax) -{ - // ensure we have something selected - if( g_FuncTable.m_pfnSelectedBrushCount() != 1 ) - { - MessageBox(NULL, "Invalid number of brushes selected, chose 1 only", "Error", MB_OK); - return; - } - - // tell Radiant we want to access the selected brushes - g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - - // get handle to size definition brush - brush_t *brush = (brush_t*)g_FuncTable.m_pfnGetSelectedBrushHandle(0); - // cant release until we delete the brush, if we do... - - DShape pit; - - if(pit.BuildPit(vMin, vMax)) - { - pit.Commit(); - - g_FuncTable.m_pfnDeleteBrushHandle(brush); - } - else - MessageBox(NULL, "Failed To Make Pit\nTry Making The Brush Bigger", "Error", MB_OK); - - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers.h deleted file mode 100644 index 3f4202ff..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/funchandlers.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -class DBobView; -class DVisDrawer; -class DTrainDrawer; -class DTreePlanter; - -extern DBobView* g_PathView; -extern DVisDrawer* g_VisView; -extern DTrainDrawer* g_TrainView; -extern DTreePlanter* g_TreePlanter; - -// intersect stuff -#define BRUSH_OPT_WHOLE_MAP 0 -#define BRUSH_OPT_SELECTED 1 - -// defines for stairs -#define MOVE_NORTH 0 -#define MOVE_SOUTH 1 -#define MOVE_EAST 2 -#define MOVE_WEST 3 - -#define STYLE_ORIGINAL 0 -#define STYLE_BOB 1 -#define STYLE_CORNER 2 - -// defines for doors -#define DIRECTION_NS 0 -#define DIRECTION_EW 1 - -// help -void LoadLists(); - - -// djbob -void DoIntersect(); -void DoPolygonsTB(); -void DoPolygons(); -void DoFixBrushes(); -void DoResetTextures(); -void DoBuildStairs(); -void DoBuildDoors(); -void DoPathPlotter(); -void DoPitBuilder(); -void DoCTFColourChanger(); -void DoMergePatches(); -void DoSplitPatch(); -void DoSplitPatchRows(); -void DoSplitPatchCols(); -void DoVisAnalyse(); -void DoTrainThing(); -void DoTrainPathPlot(); -void DoCaulkSelection(); -void DoTreePlanter(); -void DoDropEnts(); -void DoMakeChain(); -void DoFlipTerrain(); diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/lists.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/lists.cpp deleted file mode 100644 index 9823b051..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/lists.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "lists.h" - -#ifdef WIN32 -#pragma warning(disable : 4786) -#endif - -#include - -#include "misc.h" - -bool LoadExclusionList(char* filename, std::list* exclusionList) -{ - FILE* eFile = fopen(filename, "r"); - if(eFile) - { - char buffer[256]; - int cnt = 0; - while(!feof(eFile)) - { - memset(buffer, 0, 256); - fscanf(eFile, "%s\n", buffer); - - if(strlen(buffer) > 0) - exclusionList->push_back(buffer); - else - cnt++; - } - - fclose(eFile); - - return TRUE; - } - - globalErrorStream() << "Failed To Load Exclusion List: " << filename << "\n"; - return FALSE; -} - -bool LoadGList(char* filename, GList** loadlist) -{ - FILE* eFile = fopen(filename, "r"); - if(eFile) - { - char buffer[256]; - int cnt = 0; - while(!feof(eFile)) - { - memset(buffer, 0, 256); - fscanf(eFile, "%s\n", buffer); - - if(strlen(buffer) > 0) - { - char* buffer2 = new char[strlen(buffer) + 1]; - strcpy(buffer2, buffer); - *loadlist = g_list_append(*loadlist, buffer2); - } - else - cnt++; - } - - fclose(eFile); - - return TRUE; - } - - globalErrorStream() << "Failed To Load GList: " << filename << "\n"; - return FALSE; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/lists.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/lists.h deleted file mode 100644 index c4ccf77e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/lists.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include "str.h" -typedef struct _GList GList; - -bool LoadExclusionList(char* filename, std::list* exclusionList); -bool LoadGList(char* filename, GList** loadlist); diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/misc.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/misc.cpp deleted file mode 100644 index 5d926986..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/misc.cpp +++ /dev/null @@ -1,406 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "misc.h" - -#include -#include "str.h" - -#include "DPoint.h" -#include "DPlane.h" -#include "DBrush.h" -#include "DEPair.h" -#include "DPatch.h" -#include "DEntity.h" - -#include "funchandlers.h" - -#ifdef __linux__ -#include -#include -#endif - -#include "iundo.h" -#include "ientity.h" -#include "iscenegraph.h" -#include "qerplugin.h" - -#include -#include -#include -#include - -#include "scenelib.h" - -/*========================== - Global Vars -==========================*/ - -//HANDLE bsp_process; -char g_CurrentTexture[256] = ""; - -//============================================================= -//============================================================= - -void ReadCurrentTexture() -{ - const char* textureName = GlobalRadiant().TextureBrowser_getSelectedShader(); - strcpy(g_CurrentTexture, textureName); -} - -const char* GetCurrentTexture() -{ - ReadCurrentTexture(); - return g_CurrentTexture; -} - -void MoveBlock(int dir, vec3_t min, vec3_t max, float dist) -{ - switch(dir) - { - case MOVE_EAST: - { - min[0]+=dist; - max[0]+=dist; - break; - } - case MOVE_WEST: - { - min[0]-=dist; - max[0]-=dist; - break; - } - case MOVE_NORTH: - { - min[1]+=dist; - max[1]+=dist; - break; - } - case MOVE_SOUTH: - { - min[1]-=dist; - max[1]-=dist; - break; - } - } -} - -void SetInitialStairPos(int dir, vec3_t min, vec3_t max, float width) -{ - switch(dir) - { - case MOVE_EAST: - { - max[0] = min[0] + width; - break; - } - case MOVE_WEST: - { - min[0] = max[0] - width; - break; - } - case MOVE_NORTH: - { - max[1] = min[1] + width; - break; - } - case MOVE_SOUTH: - { - min[1] = max[1] - width; - break; - } - } -} - -char* TranslateString (char *buf) -{ - static char buf2[32768]; - - std::size_t l = strlen(buf); - char* out = buf2; - for (int i=0 ; i - -bool Q_Exec( const char *pCmd, bool bCreateConsole ) -{ - // G_DeWan: Don't know if this is needed for linux version - - PROCESS_INFORMATION pi; - STARTUPINFO si = {0}; // Initialize all members to zero - si.cb = sizeof(STARTUPINFO); // Set byte count - DWORD dwCreationFlags; - - if (bCreateConsole) - dwCreationFlags = CREATE_NEW_CONSOLE | NORMAL_PRIORITY_CLASS; - else - dwCreationFlags = DETACHED_PROCESS | NORMAL_PRIORITY_CLASS; - - for(; *pCmd == ' '; pCmd++); - - if(!CreateProcess(NULL, (char *)pCmd, NULL, NULL, false, dwCreationFlags, NULL, NULL, &si, &pi)) - return false; - - return true; -} -#endif - -void StartBSP() -{ - char exename[256]; - GetFilename(exename, "q3map"); - UnixToDosPath(exename); // do we want this done in linux version? - - char mapname[256]; - const char *pn = GlobalRadiant().getMapsPath(); - - strcpy( mapname, pn ); - strcat( mapname, "/ac_prt.map" ); - UnixToDosPath(mapname); - - char command[1024]; - sprintf(command, "%s -nowater -fulldetail %s", exename, mapname); - - Q_Exec( command, true ); -} - -class EntityWriteMiniPrt -{ - mutable DEntity world; - FILE* pFile; - std::list* exclusionList; -public: - EntityWriteMiniPrt(FILE* pFile, std::list* exclusionList) - : pFile(pFile), exclusionList(exclusionList) - { - } - void operator()(scene::Instance& instance) const - { - const char* classname = Node_getEntity(instance.path().top())->getKeyValue("classname"); - - if(!strcmp(classname, "worldspawn")) - { - world.LoadFromEntity(instance.path().top(), false); - world.RemoveNonCheckBrushes(exclusionList, true); - world.SaveToFile(pFile); - } - else if(strstr(classname, "info_")) - { - world.ClearBrushes(); - world.ClearEPairs(); - world.LoadEPairList(Node_getEntity(instance.path().top())); - world.SaveToFile(pFile); - } - } -}; - -void BuildMiniPrt(std::list* exclusionList) -{ - // yes, we could just use -fulldetail option, but, as SPOG said - // it'd be faster without all the hint, donotenter etc textures and - // doors, etc - - - - char buffer[128]; - const char *pn = GlobalRadiant().getMapsPath(); - - strcpy( buffer, pn ); - strcat( buffer, "/ac_prt.map" ); - FILE* pFile = fopen(buffer, "w"); - - // ahem, thx rr2 - if(!pFile) - return; - - Scene_forEachEntity(EntityWriteMiniPrt(pFile, exclusionList)); - - fclose(pFile); - - StartBSP(); -} - -class EntityFindByTargetName -{ - const char* targetname; -public: - mutable const scene::Path* result; - EntityFindByTargetName(const char* targetname) - : targetname(targetname), result(0) - { - } - void operator()(scene::Instance& instance) const - { - if(result == 0) - { - const char* value = Node_getEntity(instance.path().top())->getKeyValue("targetname"); - - if(!strcmp(value, targetname)) - { - result = &instance.path(); - } - } - } -}; - -const scene::Path* FindEntityFromTargetname(const char* targetname) -{ - return Scene_forEachEntity(EntityFindByTargetName(targetname)).result; -} - -void FillDefaultTexture(_QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc, const char* texture) -{ - faceData->m_texdef.rotate = 0; - faceData->m_texdef.scale[0] = 0.5; - faceData->m_texdef.scale[1] = 0.5; - faceData->m_texdef.shift[0] = 0; - faceData->m_texdef.shift[1] = 0; - faceData->contents = 0; - faceData->flags = 0; - faceData->value = 0; - if(*texture) - faceData->m_shader = texture; - else - faceData->m_shader = "textures/common/caulk"; - VectorCopy(va, faceData->m_p0); - VectorCopy(vb, faceData->m_p1); - VectorCopy(vc, faceData->m_p2); -} - -float Determinant3x3(float a1, float a2, float a3, - float b1, float b2, float b3, - float c1, float c2, float c3) -{ - return a1*(b2*c3-b3*c2) - a2*(b1*c3-b3*c1) + a3*(b1*c2-b2*c1); -} - -bool GetEntityCentre(const char* entity, vec3_t centre) -{ - const scene::Path* ent = FindEntityFromTargetname(entity); - if(!ent) - return false; - - scene::Instance& instance = *GlobalSceneGraph().find(*ent); - VectorCopy(instance.worldAABB().origin, centre); - - return true; -} - -vec_t Min(vec_t a, vec_t b) -{ - if(a < b) - return a; - return b; -} - -void MakeNormal( const vec_t* va, const vec_t* vb, const vec_t* vc, vec_t* out ) { - vec3_t v1, v2; - VectorSubtract(va, vb, v1); - VectorSubtract(vc, vb, v2); - CrossProduct(v1, v2, out); -} - -char* GetFilename(char* buffer, const char* filename) { - strcpy(buffer, GlobalRadiant().getAppPath()); - strcat(buffer, "plugins/"); - strcat(buffer, filename); - return buffer; -} - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/misc.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/misc.h deleted file mode 100644 index 61faee5d..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/misc.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(INCLUDED_MISC_H) -#define INCLUDED_MISC_H - -#include "mathlib.h" -#include -#include "str.h" -#include "iscenegraph.h" - -#define MAX_ROUND_ERROR 0.05 - -vec_t Min(vec_t a, vec_t b); - -// reads current texture into global, returns pointer to it -const char* GetCurrentTexture(); - -class _QERFaceData; -void FillDefaultTexture(_QERFaceData* faceData, vec3_t va, vec3_t vb, vec3_t vc, const char* texture); - -void BuildMiniPrt(std::list* exclusionList); - -void MoveBlock(int dir, vec3_t min, vec3_t max, float dist); -void SetInitialStairPos(int dir, vec3_t min, vec3_t max, float width); - -const scene::Path* FindEntityFromTargetname(const char* targetname); - -char* UnixToDosPath(char* path); - -char* GetFilename(char* buffer, const char* filename); -char* GetGameFilename(char* buffer, const char* filename); - -float Determinant3x3(float a1, float a2, float a3, - float b1, float b2, float b3, - float c1, float c2, float c3); - -bool GetEntityCentre(const char* entity, vec3_t centre); -void MakeNormal( const vec_t* va, const vec_t* vb, const vec_t* vc, vec_t* out ); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/res/plugin.rc2 b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/res/plugin.rc2 deleted file mode 100644 index 2704dbfa..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/res/plugin.rc2 +++ /dev/null @@ -1,13 +0,0 @@ -// -// SOUNDTEST.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/resource-gtk.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/resource-gtk.h deleted file mode 100644 index 9297877f..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/resource-gtk.h +++ /dev/null @@ -1,15 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by bobtoolz-gtk.rc -// - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/resource.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/resource.h deleted file mode 100644 index 2c7f97ed..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/resource.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by bobToolz.rc -// -#define IDD_PATHPLOTTER_DIALOG 101 -#define IDD_ABOUT 129 -#define IDD_STAIR_DIALOG 130 -#define IDD_POLYGON_DIALOG 131 -#define IDB_BT_BITMAP 137 -#define IDI_ICON1 139 -#define IDD_POLYGON_BRD_DIALOG 141 -#define IDD_DOOR_DIALOG 141 -#define IDD_INTERSECT_DIALOG 143 -#define IDD_INTERSECT_INFO_DIALOG 144 -#define IDD_BRUSHCHECKER_DIALOG 146 -#define IDD_AUTOCAULK_DIALOG 147 -#define IDD_AUTOCAULKSTART_DIALOG 148 -#define IDD_TEXTURE_RESET_DIALOG 149 -#define IDC_EDIT1 1000 -#define IDC_DIR_N_RADIO 1001 -#define IDC_TRIMTEXTURE_EDIT 1001 -#define IDC_SCL_VERT_EDIT 1001 -#define IDC_DIR_S_RADIO 1002 -#define IDC_SCL_HOR_EDIT 1002 -#define IDC_POINTCOUNT_EDIT 1002 -#define IDC_DIR_E_RADIO 1003 -#define IDC_ROTATION_EDIT 1003 -#define IDC_MULTIPLIER_EDIT 1003 -#define IDC_DIR_W_RADIO 1004 -#define IDC_SHFT_VER_EDIT 1004 -#define IDC_GRAVITY_EDIT 1004 -#define IDC_STYLE_ORIG_RADIO 1005 -#define IDC_SHFT_HOR_EDIT 1005 -#define IDC_NOUPDATE_CHECK 1005 -#define IDC_STYLE_BOB_RADIO 1006 -#define IDC_SHOWEXTRA_CHECK 1006 -#define IDC_STYLE_CORNER_RADIO 1007 -#define IDC_RISER_EDIT 1011 -#define IDC_FLAT_EDIT 1012 -#define IDC_MAX_WALL_WIDTH 1013 -#define IDC_MIN_WALL_WIDTH 1014 -#define IDC_DETAIL_CHK 1014 -#define IDC_MAX_CLIFF_HEIGHT 1015 -#define IDC_INVERSE_CHK 1015 -#define IDC_MIN_CLIFF_HEIGHT 1016 -#define IDC_BORDER_CHK 1016 -#define IDC_ALIGN_CHK 1017 -#define IDC_BORDER_EDIT 1018 -#define IDC_MAX_CNR_SIZE 1019 -#define IDC_MIN_CNR_SIZE 1020 -#define IDC_FBTEXTURE_EDIT 1020 -#define IDC_GRID_SNAP 1021 -#define IDC_TEXSCALE1_CHECK 1021 -#define IDC_MAX_WALL_BREADTH 1022 -#define IDC_TEXSCALE2_CHECK 1022 -#define IDC_MIN_WALL_BREADTH 1023 -#define IDC_MAINTEX_COMBO 1023 -#define IDC_TEXSCALE3_CHECK 1024 -#define IDC_TEXSCALE4_CHECK 1025 -#define IDC_TRIMTEX_COMBO 1026 -#define IDC_SET_MAINTEX_BTN 1027 -#define IDC_SET_TRIMTEX_BTN 1028 -#define IDC_WHOLEMAP_CHECK 1030 -#define IDC_DETAIL_INCLUDE_CHECK 1031 -#define IDC_SKIPBOUNDS_CHECK 1032 -#define IDC_SKIPSIMPLE_CHECK 1033 -#define IDC_SKIPACCURATE_CHECK 1034 -#define IDC_PROGRESS1 1035 -#define IDC_INTR_PROG1 1035 -#define IDC_DIR_NS_RADIO 1036 -#define IDC_PROGRESS2 1036 -#define IDC_DIR_EW_RADIO 1037 -#define IDC_DIR_GROUP 1038 -#define IDC_WHOLEMAP_RADIO 1040 -#define IDC_SELECTED_RADIO 1041 -#define IDC_KILLBRUSHES_CHECK 1041 -#define IDC_WARNING1_STATIC 1042 -#define IDC_AC_NORMAL_RADIO 1043 -#define IDC_AC_BUILD_MINI_PRT_RADIO 1044 -#define IDC_AC_SUPER_RADIO 1045 -#define IDC_RESET_TEXTURE_EDIT 1046 -#define IDC_RESET_NEW_TEXTURE_EDIT 1047 -#define IDC_ONLYTEXTURE_CHECK 1048 -#define IDC_ALLTEXTURES_CHECK 1049 -#define IDC_DUPLICATEONLY_CHECK 1050 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1007 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/shapes.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/shapes.cpp deleted file mode 100644 index e38dd495..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/shapes.cpp +++ /dev/null @@ -1,697 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#include "shapes.h" - -#include - -#include "DPoint.h" -#include "DPlane.h" - -#include "str.h" -#include "misc.h" -#include "funchandlers.h" - -#include "iundo.h" -#include "ishaders.h" -#include "ientity.h" -#include "ieclass.h" -#include "ipatch.h" -#include "qerplugin.h" - -#include -#include -#include -#include -#include - -#include "scenelib.h" -#include "texturelib.h" - -//#include "dialogs-gtk.h" - -/************************ - Cube Diagram -************************/ - -/* - - 7 ----- 5 - /| /| - / | / | - / | / | - 4 ----- 6 | - | 2|_|___|8 - | / | / - | / | / ----> WEST, definitely - |/ | / - 1|_____|/3 - -*/ - -/************************ - Global Variables -************************/ - -vec3_t g_Origin = {0.0f, 0.0f, 0.0f}; - -extern bool bFacesAll[]; - -/************************ - Helper Functions -************************/ - -float Deg2Rad(float angle) -{ - return (float)(angle*Q_PI/180); -} - -void AddFaceWithTexture(scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, const char* texture, bool detail) -{ - _QERFaceData faceData; - FillDefaultTexture(&faceData, va, vb, vc, texture); - if(detail) - faceData.contents |= FACE_DETAIL; - GlobalBrushCreator().Brush_addFace(brush, faceData); -} - -void AddFaceWithTextureScaled(scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, - const char* texture, bool bVertScale, bool bHorScale, - float minX, float minY, float maxX, float maxY) -{ - qtexture_t* pqtTexInfo; - - // TTimo: there used to be a call to pfnHasShader here - // this was not necessary. In Radiant everything is shader. - // If a texture doesn't have a shader script, a default shader object is used. - // The IShader object was leaking also - // collect texture info: sizes, etc - IShader* i = GlobalShaderSystem().getShaderForName(texture); - pqtTexInfo = i->getTexture(); // shader width/height doesn't come out properly - - if(pqtTexInfo) - { - float scale[2] = {0.5f, 0.5f}; - float shift[2] = {0, 0}; - - if(bHorScale) - { - float width = maxX - minX; - - scale[0] = width/pqtTexInfo->width; - shift[0] = -(float)((int)maxX%(int)width)/scale[0]; - } - - if(bVertScale) - { - float height = maxY - minY; - - scale[1] = height/pqtTexInfo->height; - shift[1] = (float)((int)minY%(int)height)/scale[1]; - } - - _QERFaceData addFace; - FillDefaultTexture(&addFace, va, vb, vc, texture); - addFace.m_texdef.scale[0] = scale[0]; - addFace.m_texdef.scale[1] = scale[1]; - addFace.m_texdef.shift[0] = shift[0]; - addFace.m_texdef.shift[1] = shift[1]; - - GlobalBrushCreator().Brush_addFace(brush, addFace); - } - else - { - // shouldn't even get here, as default missing texture should be returned if - // texture doesn't exist, but just in case - AddFaceWithTexture(brush, va, vb, vc, texture, false); - globalErrorStream() << "BobToolz::Invalid Texture Name-> " << texture; - } - // the IShader is not kept referenced, DecRef it - i->DecRef(); -} - -/************************ - --Main Functions-- -************************/ - -void Build_Wedge(int dir, vec3_t min, vec3_t max, bool bUp) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); - - vec3_t v1, v2, v3, v5, v6, v7, v8; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - VectorCopy(max, v8); - - v2[0] = max[0]; - v3[1] = max[1]; - - v6[0] = min[0]; - v7[1] = min[1]; - v8[2] = min[2]; - - if(bUp) - { - - if(dir != MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", false); - - if(dir != MOVE_WEST) - AddFaceWithTexture(newBrush, v7, v5, v8, "textures/common/caulk", false); - - if(dir != MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", false); - - if(dir != MOVE_SOUTH) - AddFaceWithTexture(newBrush, v3, v8, v6, "textures/common/caulk", false); - - AddFaceWithTexture(newBrush, v1, v2, v3, "textures/common/caulk", false); - - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v5, "textures/common/caulk", false); - - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v2, v6, v8, "textures/common/caulk", false); - - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v6, v5, "textures/common/caulk", false); - - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v7, v3, v8, "textures/common/caulk", false); - } - else - { - if(dir != MOVE_WEST) - AddFaceWithTexture(newBrush, v7, v5, v8, "textures/common/caulk", false); - - if(dir != MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", false); - - if(dir != MOVE_NORTH) - AddFaceWithTexture(newBrush, v3, v8, v6, "textures/common/caulk", false); - - if(dir != MOVE_SOUTH) - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", false); - - - AddFaceWithTexture(newBrush, v6, v5, v7, "textures/common/caulk", false); - - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v1, v5, v3, "textures/common/caulk", false); - - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v2, v8, v6, "textures/common/caulk", false); - - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v5, v6, "textures/common/caulk", false); - - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v7, v8, v3, "textures/common/caulk", false); - } - - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(newBrush); -} - -//----------------------------------------------------------------------------------- -//----------------------------------------------------------------------------------- - -void Build_StairStep_Wedge(int dir, vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, bool detail) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); - - //----- Build Outer Bounds --------- - - vec3_t v1, v2, v3, v5, v6, v7, v8; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - VectorCopy(max, v8); - - v2[0] = max[0]; - v3[1] = max[1]; - - v6[0] = min[0]; - v7[1] = min[1]; - - v8[2] = min[2]; - //v8 needed this time, becoz of sloping faces (2-4-6-8) - - //---------------------------------- - - AddFaceWithTexture(newBrush, v6, v5, v7, mainTexture, detail); - - if(dir != MOVE_EAST) - { - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v5, v2, v7, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v5, v2, v7, "textures/common/caulk", detail); - } - - if(dir != MOVE_WEST) - { - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", detail); - } - - if(dir != MOVE_NORTH) - { - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v3, v5, v6, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v3, v5, v6, "textures/common/caulk", detail); - } - - if(dir != MOVE_SOUTH) - { - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v7, v2, riserTexture, detail); - else - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", detail); - } - - - if(dir == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v5, v3, "textures/common/caulk", detail); - - if(dir == MOVE_WEST) - AddFaceWithTexture(newBrush, v2, v8, v6, "textures/common/caulk", detail); - - if(dir == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v5, v6, "textures/common/caulk", detail); - - if(dir == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v7, v8, v3, "textures/common/caulk", detail); - - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(newBrush); -} - -//----------------------------------------------------------------------------------- -//----------------------------------------------------------------------------------- - -// internal use only, to get a box without finishing construction -scene::Node& Build_Get_BoundingCube_Selective(vec3_t min, vec3_t max, char* texture, bool* useFaces) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); - - //----- Build Outer Bounds --------- - - vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - - v2[0] = max[0]; - v3[1] = max[1]; - - v6[0] = min[0]; - v7[1] = min[1]; - - //---------------------------------- - - //----- Add Six Cube Faces --------- - - if(useFaces[0]) - AddFaceWithTexture(newBrush, v1, v2, v3, texture, false); - if(useFaces[1]) - AddFaceWithTexture(newBrush, v1, v3, v6, texture, false); - if(useFaces[2]) - AddFaceWithTexture(newBrush, v1, v7, v2, texture, false); - - if(useFaces[3]) - AddFaceWithTexture(newBrush, v5, v6, v3, texture, false); - if(useFaces[4]) - AddFaceWithTexture(newBrush, v5, v2, v7, texture, false); - if(useFaces[5]) - AddFaceWithTexture(newBrush, v5, v7, v6, texture, false); - - //---------------------------------- - - return newBrush; -} - -scene::Node& Build_Get_BoundingCube(vec3_t min, vec3_t max, char* texture) -{ - return Build_Get_BoundingCube_Selective(min, max, texture, bFacesAll); -} - -//----------------------------------------------------------------------------------- -//----------------------------------------------------------------------------------- - -void Build_StairStep(vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, int direction) -{ - NodeSmartReference newBrush(GlobalBrushCreator().createBrush()); - - //----- Build Outer Bounds --------- - - vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - - v2[0] = max[0]; - v3[1] = max[1]; - - v6[0] = min[0]; - v7[1] = min[1]; - - //---------------------------------- - - AddFaceWithTexture(newBrush, v6, v5, v7, mainTexture, false); - // top gets current texture - - - if(direction == MOVE_EAST) - AddFaceWithTexture(newBrush, v1, v3, v6, riserTexture, false); - else - AddFaceWithTexture(newBrush, v1, v3, v6, "textures/common/caulk", false); - // west facing side, etc... - - - if(direction == MOVE_NORTH) - AddFaceWithTexture(newBrush, v1, v7, v2, riserTexture, false); - else - AddFaceWithTexture(newBrush, v1, v7, v2, "textures/common/caulk", false); - - if(direction == MOVE_SOUTH) - AddFaceWithTexture(newBrush, v3, v5, v6, riserTexture, false); - else - AddFaceWithTexture(newBrush, v3, v5, v6, "textures/common/caulk", false); - - if(direction == MOVE_WEST) - AddFaceWithTexture(newBrush, v7, v5, v2, riserTexture, false); - else - AddFaceWithTexture(newBrush, v7, v5, v2, "textures/common/caulk", false); - - - AddFaceWithTexture(newBrush, v1, v2, v3, "textures/common/caulk", false); - // base is caulked - - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(newBrush); - // finish brush -} - -//----------------------------------------------------------------------------------- -//----------------------------------------------------------------------------------- - -void BuildDoorsX2(vec3_t min, vec3_t max, - bool bSclMainHor, bool bSclMainVert, - bool bSclTrimHor, bool bSclTrimVert, - const char* mainTexture, const char* trimTexture, - int direction) -{ - int xy; - if(direction == 0) - xy = 0; - else - xy = 1; - - //----- Build Outer Bounds --------- - - vec3_t v1, v2, v3, v5, v6, v7, ve_1, ve_2, ve_3; - VectorCopy(min, v1); - VectorCopy(min, v2); - VectorCopy(min, v3); - VectorCopy(max, v5); - VectorCopy(max, v6); - VectorCopy(max, v7); - - v2[0] = max[0]; - v3[1] = max[1]; - - v6[0] = min[0]; - v7[1] = min[1]; - - float width = (max[xy] - min[xy])/2; - - if(direction == 0) - { - VectorCopy(v1, ve_1); - VectorCopy(v3, ve_2); - VectorCopy(v6, ve_3); - } - else - { - VectorCopy(v7, ve_1); - VectorCopy(v1, ve_2); - VectorCopy(v2, ve_3); - } - - ve_1[xy] += width; - ve_2[xy] += width; - ve_3[xy] += width; - - //---------------------------------- - - NodeSmartReference newBrush1(GlobalBrushCreator().createBrush()); - NodeSmartReference newBrush2(GlobalBrushCreator().createBrush()); - - AddFaceWithTexture(newBrush1, v1, v2, v3, "textures/common/caulk", false); - AddFaceWithTexture(newBrush1, v5, v7, v6, "textures/common/caulk", false); - - AddFaceWithTexture(newBrush2, v1, v2, v3, "textures/common/caulk", false); - AddFaceWithTexture(newBrush2, v5, v7, v6, "textures/common/caulk", false); - - if(direction == 0) - { - AddFaceWithTexture(newBrush1, v1, v3, v6, "textures/common/caulk", false); - AddFaceWithTexture(newBrush2, v5, v2, v7, "textures/common/caulk", false); - } - else - { - AddFaceWithTexture(newBrush1, v1, v7, v2, "textures/common/caulk", false); - AddFaceWithTexture(newBrush2, v5, v6, v3, "textures/common/caulk", false); - } - - if(direction == 0) - { - AddFaceWithTextureScaled(newBrush1, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, - min[0], min[2], max[0], max[2]); - AddFaceWithTextureScaled(newBrush1, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, - max[0], min[2], min[0], max[2]); - - - AddFaceWithTextureScaled(newBrush2, v1, v7, v2, mainTexture, bSclMainVert, bSclMainHor, - min[0], min[2], max[0], max[2]); - AddFaceWithTextureScaled(newBrush2, v5, v6, v3, mainTexture, bSclMainVert, bSclMainHor, - max[0], min[2], min[0], max[2]); // flip max/min to reverse tex dir - - - - AddFaceWithTextureScaled(newBrush1, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, - min[1], min[2], max[1], max[2]); - - AddFaceWithTextureScaled(newBrush2, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, - max[1], min[2], min[1], max[2]); - } - else - { - AddFaceWithTextureScaled(newBrush1, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, - min[1], min[2], max[1], max[2]); - AddFaceWithTextureScaled(newBrush1, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, - max[1], min[2], min[1], max[2]); - - - AddFaceWithTextureScaled(newBrush2, v1, v3, v6, mainTexture, bSclMainVert, bSclMainHor, - min[1], min[2], max[1], max[2]); - AddFaceWithTextureScaled(newBrush2, v5, v2, v7, mainTexture, bSclMainVert, bSclMainHor, - max[1], min[2], min[1], max[2]); // flip max/min to reverse tex dir - - - AddFaceWithTextureScaled(newBrush1, ve_1, ve_2, ve_3, trimTexture, bSclTrimVert, bSclTrimHor, - min[0], min[2], max[0], max[2]); - - AddFaceWithTextureScaled(newBrush2, ve_3, ve_2, ve_1, trimTexture, bSclTrimVert, bSclTrimHor, - max[0], min[2], min[0], max[2]); - } - - //---------------------------------- - - - EntityClass* doorClass = GlobalEntityClassManager().findOrInsert("func_door", true); - NodeSmartReference pEDoor1(GlobalEntityCreator().createEntity(doorClass)); - NodeSmartReference pEDoor2(GlobalEntityCreator().createEntity(doorClass)); - - if(direction == 0) - { - Node_getEntity(pEDoor1)->setKeyValue("angle", "180"); - Node_getEntity(pEDoor2)->setKeyValue("angle", "360"); - } - else - { - Node_getEntity(pEDoor1)->setKeyValue("angle", "270"); - Node_getEntity(pEDoor2)->setKeyValue("angle", "90"); - } - - srand((unsigned)time(NULL)); - - char teamname[256]; - sprintf(teamname, "t%i", rand()); - Node_getEntity(pEDoor1)->setKeyValue("team", teamname); - Node_getEntity(pEDoor2)->setKeyValue("team", teamname); - - Node_getTraversable(pEDoor1)->insert(newBrush1); - Node_getTraversable(pEDoor2)->insert(newBrush2); - - Node_getTraversable(GlobalSceneGraph().root())->insert(pEDoor1); - Node_getTraversable(GlobalSceneGraph().root())->insert(pEDoor2); - -// ResetCurrentTexture(); -} - -//----------------------------------------------------------------------------------- -//----------------------------------------------------------------------------------- - -void MakeBevel(vec3_t vMin, vec3_t vMax) -{ - NodeSmartReference patch(GlobalPatchCreator().createPatch()); - GlobalPatchCreator().Patch_resize(patch, 3, 3); - GlobalPatchCreator().Patch_setShader(patch, "textures/common/caulk"); - PatchControlMatrix matrix = GlobalPatchCreator().Patch_getControlPoints(patch); - vec3_t x_3, y_3, z_3; - x_3[0] = vMin[0]; x_3[1] = vMin[0]; x_3[2] = vMax[0]; - y_3[0] = vMin[1]; y_3[1] = vMax[1]; y_3[2] = vMax[1]; - z_3[0] = vMin[2]; z_3[1] = (vMax[2] + vMin[2])/2; z_3[2] = vMax[2]; - /* - x_3[0] = 0; x_3[1] = 0; x_3[2] = 64; - y_3[0] = 0; y_3[1] = 64; y_3[2] = 64; - z_3[0] = 0; z_3[1] = 32; z_3[2] = 64;*/ - for(int i = 0; i < 3; i++) - { - for(int j = 0; j < 3; j++) - { - PatchControl& p = matrix(i, j); - p.m_vertex[0] = x_3[i]; - p.m_vertex[1] = y_3[i]; - p.m_vertex[2] = z_3[j]; - } - } - //does invert the matrix, else the patch face is on wrong side. - for(int i = 0 ; i < 3 ; i++ ) - { - for(int j = 0; j < 1; j++) - { - PatchControl& p = matrix(i,2- j); - PatchControl& q = matrix(i, j); - std::swap(p.m_vertex, q.m_vertex); - //std::swap(p.m_texcoord, q.m_texcoord); - } - } - GlobalPatchCreator().Patch_controlPointsChanged(patch); - //TODO - the patch has textures weird, patchmanip.h has all function it needs.. lots of duplicate code.. - //NaturalTexture(patch); - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(patch); -} - -void BuildCornerStairs(vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTexture, const char* riserTex) -{ - vec3_t* topPoints = new vec3_t[nSteps+1]; - vec3_t* botPoints = new vec3_t[nSteps+1]; - - //bool bFacesUse[6] = {true, true, false, true, false, false}; - - vec3_t centre; - VectorCopy(vMin, centre); - centre[0] = vMax[0]; - - int height = (int)(vMax[2] - vMin[2]) / nSteps; - - vec3_t vTop, vBot; - VectorCopy(vMax, vTop); - VectorCopy(vMin, vBot); - vTop[2] = vMin[2] + height; - - int i; - for(i = 0; i <= nSteps; i++) - { - VectorCopy(centre, topPoints[i]); - VectorCopy(centre, botPoints[i]); - - topPoints[i][2] = vMax[2]; - botPoints[i][2] = vMin[2]; - - topPoints[i][0] -= 10 * sinf( Q_PI * i / ( 2 * nSteps ) ); - topPoints[i][1] += 10 * cosf( Q_PI * i / ( 2 * nSteps ) ); - - botPoints[i][0] = topPoints[i][0]; - botPoints[i][1] = topPoints[i][1]; - } - - vec3_t tp[3]; - for(int j = 0; j < 3; j++) - VectorCopy(topPoints[j], tp[j]); - - for(i = 0; i < nSteps; i++) - { - NodeSmartReference brush(GlobalBrushCreator().createBrush()); - vec3_t v1, v2, v3, v5, v6, v7; - VectorCopy(vBot, v1); - VectorCopy(vBot, v2); - VectorCopy(vBot, v3); - VectorCopy(vTop, v5); - VectorCopy(vTop, v6); - VectorCopy(vTop, v7); - - v2[0] = vTop[0]; - v3[1] = vTop[1]; - - v6[0] = vBot[0]; - v7[1] = vBot[1]; - - AddFaceWithTexture(brush, v1, v2, v3, "textures/common/caulk", false); - AddFaceWithTexture(brush, v1, v3, v6, "textures/common/caulk", false); - AddFaceWithTexture(brush, v5, v6, v3, "textures/common/caulk", false); - - for(int j = 0; j < 3; j++) - tp[j][2] = vTop[2]; - - AddFaceWithTexture(brush, tp[2], tp[1], tp[0], mainTexture, false); - - AddFaceWithTexture(brush, centre, botPoints[i+1], topPoints[i+1], "textures/common/caulk", false); - AddFaceWithTexture(brush, centre, topPoints[i], botPoints[i], riserTex, false); - - Node_getTraversable(GlobalRadiant().getMapWorldEntity())->insert(brush); - - vTop[2] += height; - vBot[2] += height; - } - - delete[] topPoints; - delete[] botPoints; - - vMin[2] += height; - vMax[2] += height; - MakeBevel(vMin, vMax); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/shapes.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/shapes.h deleted file mode 100644 index 0fa92659..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/shapes.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -BobToolz plugin for GtkRadiant -Copyright (C) 2001 Gordon Biggans - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// TODO: implement all this stuff via DBrush class. started with DShape -// TODO: Auto Face Scaling, no need to pass parms, calculated via brush. - -// Q3MAP stuff -#define FACE_DETAIL 0x8000000 - -// defines for polygon stuff -#define MAX_POLYGON_FACES 128 - -namespace scene -{ - class Node; -} - -#include "mathlib.h" - -// generic (detail added 12/01/01, for AC+) -void AddFaceWithTexture(scene::Node& brush, vec3_t va, vec3_t vb, vec3_t vc, const char* texture, bool detail); - -// ------------- -// ---caulked--- -// ------------- -void Build_Wedge(int dir, vec3_t min, vec3_t max, bool bUp); - -// -------------- -// ---textured--- -// -------------- -void BuildDoorsX2(vec3_t min, vec3_t max, bool bSclMainHor, bool bSclMainVert, bool bSclTrimHor, bool bSclTrimVert, const char* mainTexture, const char* trimTexture, int direction); -void Build_StairStep(vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, int direction); -void Build_StairStep_Wedge(int dir, vec3_t min, vec3_t max, const char* mainTexture, const char* riserTexture, bool detail); -void BuildCornerStairs(vec3_t vMin, vec3_t vMax, int nSteps, const char* mainTexture, const char* riserTex); -// stairs stuff. - -//void Build_Prism_Border(vec3_t min, vec3_t max, int nSides, int nBorder, bool bAlignTop = FALSE); //moved to DShape -//void Build_Prism_Ordinary(vec3_t min, vec3_t max, int nSides, bool bAlignTop = FALSE); //moved to DShape -//void Build_Prism_Efficient(vec3_t min, vec3_t max, int nSides, bool bAlignTop = FALSE); //moved to DShape -// polygon stuff. diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/txt/changelog.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/txt/changelog.txt deleted file mode 100644 index 777dc775..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/txt/changelog.txt +++ /dev/null @@ -1,96 +0,0 @@ -BobToolz Changelog: -[=================] - -Changes in v1110 (GTK): -[=====================] - -djbob - -Added: -(16.05.01) - Impemented a little feature that highligths the q3map bug that is causing problems for autocaulk, (see readme) -(01.04.01) - Added DPatch class to implement patches, however radiant does not (currently) support adding patches to an entity via a plugin, so, its actually redundant atm, i was adding this to fix the patches being removed from entities probelm with dealing with entities outside of the worldspawn. - -Changes: -(02.04.01) - EPair keys and values can now be 128 characters long, not 64, happy now hydra? - Texture reseter works on patches now too. - -Removed: -(29.03.01) - Removed CTF colour changer, it is now in the ctftoolz. - -Fixed: -(02.04.01) - Worldspawn brushes are rebuilt per brush, rather than per entity in texture reseter. -(03.04.01) - Worldspawn brushes are rebuilt per brush, rather than per entity in brush cleanup. - -Changes in v1100 (GTK): -[=====================] - -djbob - -Added: -(24.03.01) - Added CTF colour changer for worldspawn+func_group. - -Changes: -(25.03.01) - Brought some functions over to using DMap class, allowing them to run on multiple entities, patches are still a no-no atm. - This includes: - - a) brush cleanup, will now fix problems on brushes that are not in the worldspawn, and rebuild the entitiy afterwards. - b) texture reseter will change textures on all brushes now, not just those in the worldspawn. - c) CTF colour changer will also work on brushes outside of the worldspawn entity. - -This introduces one prolem, patches in entities will no longer be part of the new entity, sorry for any trouble this causes, i will fix it soon hopefully. - -Fixes: -(25.03.01) - Fixed bug in DMap class that prevented it destroying brushes... thus enabling the class to work!!!! - -Changes in v1090 (GTK): -[=====================] - -djbob - -Added: -(22.03.01) - Added PitOMatic Function. - -Changes in v1080b (GTK): -[======================] - -djbob - -Fixes: - Removed some previously unnoticed porting introduced bugs. - -Added: - Polygon stuff now passes through my internal validation routines, no more phantom brushes will be made, or squiffy planes. - -Changes in v1080 (GTK): -[=====================] - -djbob - -Fixes: -(05.03.01) - Fixed line removed by rr2 in autocaulk. - Fixed Autocaulk not working with maps larger than the old grid. - -Added: -(04.03.01) - Added Changelog. - Added ability to align polygons so that top edge will be flat. (Request By Casey) -(05.03.01) - Added ability to change main texture for stairs. - -rr2do2 - -Changes: -(??.??.01) - Removed all traces of MFC from GTK version, the evil that it is ;] - diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/txt/readme.txt b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/txt/readme.txt deleted file mode 100644 index 5c0feddb..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/txt/readme.txt +++ /dev/null @@ -1,77 +0,0 @@ -BobToolz GTK: v1100 -[=================] - -Date: -[===] -16.05.01 - -The multipurpose Quake3 Mappers Tool -[==================================] - -Author: djbob -Other work: q3terra, ctftoolz, EECA mod - -eMail: gbiggans@uglab.eee.strath.ac.uk (NO SPAM thank u very much :P) - -www: www.planetquake.com/toolz - www.planetquake.com/eeca - -IRC: #freepq irc.fdf.net - #qeradiant irc.telefragged.com - -Files Contained In This Package: -[==============================] - -Readme.txt --- This file. -Changelog.txt --- Version information. -bobToolz.dll --- The plugin itsself. -bt/*.txt --- A few text files required by the plugin. - - -What's a boy to do? -[=================] - -Put The plugin in your GTKRadiant plugins folder: -e.g. mine: c:\gamez\quake3\GTKRadiant\plugins - -Run Radiant, and select the toolz from the dropdown plugin menu. - -Help is available in the form of a manual on my site. - - - -For the new q3map bug highlighting feature, run autocaulk-build mini prt, then run autocaulk. -identify an area which has been caulked incorrectly, then reopen the map, select the q3map bug highlight option, and wait. -once the selected brushes appear, u have 2 choices, - -a) press i and remove all the original brushes, or -b) keep going with both sets (slower, but more useful) - -navigate to the problem region, you should find that the set of inverse brushes that has been built is missing a brush -at the problem area, i suppose the next problem is finding out why :] - -this function is mainly provided for other coders to show the problem, and is probably of little use to anyone else, -but u never know. - - -Coming Soon: -[==========] -Region area saving. perhaps, if i get the time to finish it. - - -Testing, Feedback & Ideas: -[========================] - - Akuma, Casey, Cartman2K, maverik, rayden, nephilim_goth and god knows who else. - Thx to you all. - -Thanx: -[====] - - ttimo, da man :] - spog, for his often baffling advice.... and questions.... - Thx to rr2do2, for his linux conversion, and removing the "evil" (his words :]) MFC code. - Thx to RKone, for improving my q3w sig. - Azr for giving me ops in #qeradiant, k3wl :] - Everyone at the Quake3World Forums, I think of you all as my little worshippers :P - id Software, of course. \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/visfind.cpp b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/visfind.cpp deleted file mode 100644 index e5b890b1..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/visfind.cpp +++ /dev/null @@ -1,247 +0,0 @@ -// Requries parts of the q3 tools source to compile -// Date: Oct 5, 2001 -// Written by: Brad Whitehead (whiteheb@gamerstv.net) - -#include "visfind.h" -#include "dialogs/dialogs-gtk.h" -#include "DWinding.h" -#include "bsploader.h" - -#include - -typedef struct { - int portalclusters; - int leafbytes; //leafbytes = ((portalclusters+63)&~63)>>3; -} vis_header; - -// added because int shift = 32; i = 0xFFFFFFFF >> shift; -// then i = 0xFFFFFFFF, when it should = 0 -const unsigned long bitmasks[33] = -{ - 0x00000000, - 0x00000001, 0x00000003, 0x00000007, 0x0000000F, - 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, - 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, - 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, - 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, - 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, - 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, - 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF -}; - -int bsp_leafnumfororigin(vec3_t origin) -{ - dnode_t *node; - dplane_t *plane; - float d; - - // TODO: check if origin is in the map?? - - node = dnodes; - while (true) - { - plane = &dplanes[node->planeNum]; - d = DotProduct (origin, plane->normal) - plane->dist; - if ( d >= 0 ) - if ( node->children[0] < 0 ) - return -(node->children[0]+1); - else - node = &dnodes[node->children[0]]; - else - if ( node->children[1] < 0 ) - return -(node->children[1]+1); - else - node = &dnodes[node->children[1]]; - } - return 0; -} - -int bsp_leafnumforcluster(int cluster) -{ - dleaf_t *l; - int i; - - for ( i = 0, l = dleafs; i < numleafs; i++, l++ ) - if ( l->cluster == cluster ) return(i); - return(0); -} - -// leaf1 = origin leaf -// leaf2 = leaf to test for -/*int bsp_InPVS(int cluster1, int cluster2) -{ - vis_header *vheader; - byte *visdata; - - vheader = (vis_header *) visBytes; - visdata = visBytes + VIS_HEADER_SIZE; - - return( *( visdata + ( cluster1 * vheader->leafbytes ) + (cluster2 / 8) ) & ( 1 << ( cluster2 % 8 ) ) ); -}*/ - -void bsp_setbitvectorlength( byte *v, int length_bits, int length_vector ) -{ - int i; - - i = length_bits/8; - - *(v+i) = (byte) bitmasks[length_bits % 8]; - - memset((v+i+1), 0, length_vector-i-1); -} - - -void bsp_bitvectorsubtract(byte *first, byte *second, byte *out, int length) -{ - - int i; - - for ( i = 0; i < length; i++ ) - *(out+i) = *(first+i) & ~(*(second+i)); -} - -int bsp_countclusters(byte *bitvector, int length) -{ - int i, j, c; - - c = 0; - for ( i = 0; i < length; i++ ) - for ( j = 0; j < 8; j++ ) - if ( (*(bitvector+i) & (1 << j)) ) c++; - return(c); -} - -int bsp_countclusters_mask(byte *bitvector, byte *maskvector, int length) -{ - int i, j, c; - - c = 0; - for ( i = 0; i < length; i++ ) - for ( j = 0; j < 8; j++ ) - if ( (*(bitvector+i) & (1 << j)) && (*(maskvector+i) & (1 << j)) ) c++; - return(c); -} - -void AddCluster(std::list *pointlist, dleaf_t *cl, bool* repeatlist, vec3_t clr) -{ - DWinding* w; - - int* leafsurf = &dleafsurfaces[cl->firstLeafSurface]; - for(int k = 0; k < cl->numLeafSurfaces; k++, leafsurf++) - { - if(repeatlist[*leafsurf]) - continue; - - dsurface_t* surf = &drawSurfaces[*leafsurf]; - if(surf->surfaceType != MST_PLANAR) - continue; - - qdrawVert_t* vert = &drawVerts[surf->firstVert]; - if(surf->firstVert + surf->numVerts > numDrawVerts) - DoMessageBox("Warning", "Warning", eMB_OK); - - w = new DWinding(); - w->AllocWinding(surf->numVerts); - - for (int l = 0; l < surf->numVerts; l++, vert++) - { - (w->p[l])[0] = vert->xyz[0]; - (w->p[l])[1] = vert->xyz[1]; - (w->p[l])[2] = vert->xyz[2]; - - w->clr[0] = clr[0]; - w->clr[1] = clr[1]; - w->clr[2] = clr[2]; - } - pointlist->push_back(w); - - repeatlist[*leafsurf] = true; - } -} - -/* -============= -CreateTrace -============= -*/ -std::list *CreateTrace( dleaf_t *leaf, int c, vis_header *header, byte *visdata, byte *seen ) -{ - byte *vis; - int i, j, clusterNum; - std::list *pointlist = new std::list; - bool* repeatlist = new bool[numDrawSurfaces]; - dleaf_t *cl; - - vec3_t clrRnd[5] = { - {0.f, 0.f, 1.f}, - {0.f, 1.f, 1.f}, - {1.f, 0.f, 0.f}, - {1.f, 0.f, 1.f}, - {1.f, 1.f, 0.f}, - }; - - vec3_t clrGreen = {0.f, 1.f, 0.f}; - - memset(repeatlist, 0, sizeof(bool)*numDrawSurfaces); - - vis = visdata + ( c * header->leafbytes ); - - clusterNum = 0; - - AddCluster(pointlist, &(dleafs[bsp_leafnumforcluster( c )]), repeatlist, clrGreen); - - for ( i = 0; i < header->leafbytes; i++ ) - { - for ( j = 0; j < 8; j++ ) - { - cl = &(dleafs[bsp_leafnumforcluster( clusterNum )]); - - if ( ( *(vis + i) & (1 << j) ) && (*(seen+i) & (1 << j)) && (leaf->area == cl->area)) - AddCluster(pointlist, cl, repeatlist, clrRnd[rand()%5]); - clusterNum++; - } - } - - delete repeatlist; - - return pointlist; -} - -/* -============= -TraceCluster - -setup for CreateTrace -============= -*/ -std::list *TraceCluster (int leafnum) -{ - byte seen[(MAX_MAP_LEAFS/8) + 1]; - vis_header *vheader; - byte *visdata; - dleaf_t *leaf; - - vheader = (vis_header *) visBytes; - visdata = visBytes + sizeof(vis_header); - - memset(seen, 0xFF, sizeof(seen)); - bsp_setbitvectorlength(seen, vheader->portalclusters, sizeof(seen)); - - leaf = &(dleafs[leafnum]); - - return CreateTrace(leaf, leaf->cluster, vheader, visdata, seen); -} - -std::list* BuildTrace(char* filename, vec3_t v_origin) -{ - if(!LoadBSPFile(filename)) - return NULL; - - int leafnum = bsp_leafnumfororigin(v_origin); - - std::list *pointlist = TraceCluster(leafnum); - - FreeBSPData(); - - return pointlist; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/visfind.h b/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/visfind.h deleted file mode 100644 index 3476d864..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/bobtoolz/visfind.h +++ /dev/null @@ -1,7 +0,0 @@ - -#include -#include "mathlib.h" - -class DWinding; - -std::list *BuildTrace(char* filename, vec3_t v_origin); diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/brushexport.def b/misc/mediasource/extra/netradiant-src/contrib/brushexport/brushexport.def deleted file mode 100644 index 21740167..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/brushexport.def +++ /dev/null @@ -1,7 +0,0 @@ -; brushexport.def : Declares the module parameters for the DLL. - -LIBRARY "BRUSHEXPORT" - -EXPORTS - ; Explicit exports can go here - Radiant_RegisterModules @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/callbacks.cpp b/misc/mediasource/extra/netradiant-src/contrib/brushexport/callbacks.cpp deleted file mode 100644 index 0aea73da..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/callbacks.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include -#include -#include - -#include "qerplugin.h" -#include "debugging/debugging.h" -#include "support.h" -#include "export.h" - -// stuff from interface.cpp -void DestroyWindow(); - - -namespace callbacks { - -void OnDestroy(GtkWidget* w, gpointer data) -{ - DestroyWindow(); -} - -void OnExportClicked(GtkButton* button, gpointer user_data) -{ - GtkWidget* window = lookup_widget(GTK_WIDGET(button), "w_plugplug2"); - ASSERT_NOTNULL(window); - const char* cpath = GlobalRadiant().m_pfnFileDialog(window, false, "Save as Obj", 0, 0, false, false, true); - if(!cpath) - return; - - std::string path(cpath); - - // get ignore list from ui - std::set ignore; - - GtkTreeView* view = GTK_TREE_VIEW(lookup_widget(GTK_WIDGET(button), "t_materialist")); - GtkListStore* list = GTK_LIST_STORE(gtk_tree_view_get_model(view)); - - GtkTreeIter iter; - gboolean valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(list), &iter); - while(valid) - { - gchar* data; - gtk_tree_model_get(GTK_TREE_MODEL(list), &iter, 0, &data, -1); - globalOutputStream() << data << "\n"; - ignore.insert(std::string(data)); - g_free(data); - valid = gtk_tree_model_iter_next (GTK_TREE_MODEL(list), &iter); - } - - for(std::set::iterator it(ignore.begin()); it != ignore.end(); ++it) - globalOutputStream() << it->c_str() << "\n"; - - // collapse mode - collapsemode mode = COLLAPSE_NONE; - - GtkWidget* radio = lookup_widget(GTK_WIDGET(button), "r_collapse"); - ASSERT_NOTNULL(radio); - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radio))) - mode = COLLAPSE_ALL; - else - { - radio = lookup_widget(GTK_WIDGET(button), "r_collapsebymaterial"); - ASSERT_NOTNULL(radio); - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radio))) - mode = COLLAPSE_BY_MATERIAL; - else - { - radio = lookup_widget(GTK_WIDGET(button), "r_nocollapse"); - ASSERT_NOTNULL(radio); - ASSERT_NOTNULL(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(radio))); - mode = COLLAPSE_NONE; - } - } - - // export materials? - GtkWidget* toggle = lookup_widget(GTK_WIDGET(button), "t_exportmaterials"); - ASSERT_NOTNULL(toggle); - - bool exportmat = FALSE; - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle))) - exportmat = TRUE; - - // limit material names? - toggle = lookup_widget(GTK_WIDGET(button), "t_limitmatnames"); - ASSERT_NOTNULL(toggle); - - bool limitMatNames = FALSE; - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle)) && exportmat) - limitMatNames = TRUE; - - // create objects instead of groups? - toggle = lookup_widget(GTK_WIDGET(button), "t_objects"); - ASSERT_NOTNULL(toggle); - - bool objects = FALSE; - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggle)) && exportmat) - objects = TRUE; - - // export - ExportSelection(ignore, mode, exportmat, path, limitMatNames, objects); -} - -void OnAddMaterial(GtkButton* button, gpointer user_data) -{ - GtkEntry* edit = GTK_ENTRY(lookup_widget(GTK_WIDGET(button), "ed_materialname")); - ASSERT_NOTNULL(edit); - - const gchar* name = gtk_entry_get_text(edit); - if(g_utf8_strlen(name, -1) > 0) - { - GtkListStore* list = GTK_LIST_STORE(gtk_tree_view_get_model(GTK_TREE_VIEW(lookup_widget(GTK_WIDGET(button), "t_materialist")))); - GtkTreeIter iter; - gtk_list_store_append(list, &iter); - gtk_list_store_set(list, &iter, 0, name, -1); - gtk_entry_set_text(edit, ""); - } -} - -void OnRemoveMaterial(GtkButton* button, gpointer user_data) -{ - GtkTreeView* view = GTK_TREE_VIEW(lookup_widget(GTK_WIDGET(button), "t_materialist")); - GtkListStore* list = GTK_LIST_STORE(gtk_tree_view_get_model(view)); - GtkTreeSelection* sel = gtk_tree_view_get_selection(view); - - GtkTreeIter iter; - if(gtk_tree_selection_get_selected(sel, 0, &iter)) - gtk_list_store_remove(list, &iter); -} - -void OnExportMatClicked(GtkButton* button, gpointer user_data) -{ - GtkWidget* toggleLimit = lookup_widget(GTK_WIDGET(button), "t_limitmatnames"); - GtkWidget* toggleObject = lookup_widget(GTK_WIDGET(button), "t_objects"); - - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) - { - gtk_widget_set_sensitive(GTK_WIDGET(toggleLimit), TRUE); - gtk_widget_set_sensitive(GTK_WIDGET(toggleObject), TRUE); - } else { - gtk_widget_set_sensitive(GTK_WIDGET(toggleLimit), FALSE); - gtk_widget_set_sensitive(GTK_WIDGET(toggleObject), FALSE); - } -} - -}// callbacks diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/callbacks.h b/misc/mediasource/extra/netradiant-src/contrib/brushexport/callbacks.h deleted file mode 100644 index 9bf95684..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/callbacks.h +++ /dev/null @@ -1,12 +0,0 @@ -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkButton GtkButton; - -namespace callbacks { - -void OnDestroy(GtkWidget*, gpointer); -void OnExportClicked(GtkButton*, gpointer); -void OnAddMaterial(GtkButton*, gpointer); -void OnRemoveMaterial(GtkButton*, gpointer); -void OnExportMatClicked(GtkButton* button, gpointer); - -}// callbacks diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/export.cpp b/misc/mediasource/extra/netradiant-src/contrib/brushexport/export.cpp deleted file mode 100644 index 0407432e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/export.cpp +++ /dev/null @@ -1,376 +0,0 @@ -#include "export.h" -#include "debugging/debugging.h" -#include "ibrush.h" -#include "iscenegraph.h" -#include "iselection.h" -#include "stream/stringstream.h" -#include "stream/textfilestream.h" - -#include - -// this is very evil, but right now there is no better way -#include "../../radiant/brush.h" - -// for limNames -#define MAX_MATERIAL_NAME 20 - -/* - Abstract baseclass for modelexporters - the class collects all the data which then gets - exported through the WriteToFile method. -*/ -class ExportData -{ -public: - ExportData(const std::set& ignorelist, collapsemode mode, bool limNames, bool objs); - virtual ~ExportData(void); - - virtual void BeginBrush(Brush& b); - virtual void AddBrushFace(Face& f); - virtual void EndBrush(void); - - virtual bool WriteToFile(const std::string& path, collapsemode mode) const = 0; - -protected: - - // a group of faces - class group - { - public: - std::string name; - std::list faces; - }; - - std::list groups; - -private: - - // "textures/common/caulk" -> "caulk" - void GetShaderNameFromShaderPath(const char* path, std::string& name); - - group* current; - collapsemode mode; - const std::set& ignorelist; -}; - -ExportData::ExportData(const std::set& _ignorelist, collapsemode _mode, bool _limNames, bool _objs) - : mode(_mode), - ignorelist(_ignorelist) -{ - current = 0; - - // in this mode, we need just one group - if(mode == COLLAPSE_ALL) - { - groups.push_back(group()); - current = &groups.back(); - current->name = "all"; - } -} - -ExportData::~ExportData(void) -{ - -} - -void ExportData::BeginBrush(Brush& b) -{ - // create a new group for each brush - if(mode == COLLAPSE_NONE) - { - groups.push_back(group()); - current = &groups.back(); - - StringOutputStream str(256); - str << "Brush" << (const unsigned int)groups.size(); - current->name = str.c_str(); - } -} - -void ExportData::EndBrush(void) -{ - // all faces of this brush were on the ignorelist, discard the emptygroup - if(mode == COLLAPSE_NONE) - { - ASSERT_NOTNULL(current); - if(current->faces.empty()) - { - groups.pop_back(); - current = 0; - } - } -} - -void ExportData::AddBrushFace(Face& f) -{ - std::string shadername; - GetShaderNameFromShaderPath(f.GetShader(), shadername); - - // ignore faces from ignore list - if(ignorelist.find(shadername) != ignorelist.end()) - return; - - if(mode == COLLAPSE_BY_MATERIAL) - { - // find a group for this material - current = 0; - const std::list::iterator end(groups.end()); - for(std::list::iterator it(groups.begin()); it != end; ++it) - { - if(it->name == shadername) - current = &(*it); - } - - // no group found, create one - if(!current) - { - groups.push_back(group()); - current = &groups.back(); - current->name = shadername; - } - } - - ASSERT_NOTNULL(current); - - // add face to current group - current->faces.push_back(&f); - -#ifdef _DEBUG - globalOutputStream() << "Added Face to group " << current->name.c_str() << "\n"; -#endif -} - -void ExportData::GetShaderNameFromShaderPath(const char* path, std::string& name) -{ - std::string tmp(path); - - size_t last_slash = tmp.find_last_of("/"); - - if(last_slash != std::string::npos && last_slash == (tmp.length() - 1)) - name = path; - else - name = tmp.substr(last_slash + 1, tmp.length() - last_slash); - -#ifdef _DEBUG - globalOutputStream() << "Last: " << (const unsigned int) last_slash << " " << "length: " << (const unsigned int)tmp.length() << "Name: " << name.c_str() << "\n"; -#endif -} - -/* - Exporter writing facedata as wavefront object -*/ -class ExportDataAsWavefront : public ExportData -{ -private: - bool expmat; - bool limNames; - bool objs; - -public: - ExportDataAsWavefront(const std::set& _ignorelist, collapsemode _mode, bool _expmat, bool _limNames, bool _objs) - : ExportData(_ignorelist, _mode, _limNames, _objs) - { - expmat = _expmat; - limNames = _limNames; - objs = _objs; - } - - bool WriteToFile(const std::string& path, collapsemode mode) const; -}; - -bool ExportDataAsWavefront::WriteToFile(const std::string& path, collapsemode mode) const -{ - std::string objFile = path.substr(0, path.length() -4) + ".obj"; - std::string mtlFile = path.substr(0, path.length() -4) + ".mtl"; - - std::set materials; - - TextFileOutputStream out(objFile.c_str()); - - if(out.failed()) - { - globalErrorStream() << "Unable to open file\n"; - return false; - } - - out << "# Wavefront Objectfile exported with radiants brushexport plugin 3.0 by Thomas 'namespace' Nitschke, spam@codecreator.net\n\n"; - - if(expmat) - { - size_t last = mtlFile.find_last_of("//"); - std::string mtllib = mtlFile.substr(last + 1, mtlFile.size() - last).c_str(); - out << "mtllib " << mtllib.c_str() << "\n"; - } - - unsigned int vertex_count = 0; - - const std::list::const_iterator gend(groups.end()); - for(std::list::const_iterator git(groups.begin()); git != gend; ++git) - { - typedef std::multimap bm; - bm brushMaterials; - typedef std::pair String_Pair; - - const std::list::const_iterator end(git->faces.end()); - - // submesh starts here - if(objs) - { - out << "\no "; - } else { - out << "\ng "; - } - out << git->name.c_str() << "\n"; - - // material - if(expmat && mode == COLLAPSE_ALL) - { - out << "usemtl material" << "\n\n"; - materials.insert("material"); - } - - for(std::list::const_iterator it(git->faces.begin()); it != end; ++it) - { - const Winding& w((*it)->getWinding()); - - // vertices - for(size_t i = 0; i < w.numpoints; ++i) - out << "v " << FloatFormat(w[i].vertex.x(), 1, 6) << " " << FloatFormat(w[i].vertex.z(), 1, 6) << " " << FloatFormat(w[i].vertex.y(), 1, 6) << "\n"; - } - out << "\n"; - - for(std::list::const_iterator it(git->faces.begin()); it != end; ++it) - { - const Winding& w((*it)->getWinding()); - - // texcoords - for(size_t i = 0; i < w.numpoints; ++i) - out << "vt " << FloatFormat(w[i].texcoord.x(), 1, 6) << " " << FloatFormat(w[i].texcoord.y(), 1, 6) << "\n"; - } - - for(std::list::const_iterator it(git->faces.begin()); it != end; ++it) - { - const Winding& w((*it)->getWinding()); - - // faces - StringOutputStream faceLine(256); - faceLine << "\nf"; - for(size_t i = 0; i < w.numpoints; ++i, ++vertex_count) - { - faceLine << " " << vertex_count+1 << "/" << vertex_count+1; - } - - if(mode != COLLAPSE_ALL) - { - materials.insert((*it)->getShader().getShader()); - brushMaterials.insert(String_Pair((*it)->getShader().getShader(), faceLine.c_str())); - } else { - out << faceLine.c_str(); - } - } - - if(mode != COLLAPSE_ALL) - { - std::string lastMat; - std::string mat; - std::string faces; - - for(bm::iterator iter = brushMaterials.begin(); iter != brushMaterials.end(); iter++) - { - mat = (*iter).first.c_str(); - faces = (*iter).second.c_str(); - - if(mat != lastMat) - { - if(limNames && mat.size() > MAX_MATERIAL_NAME) - { - out << "\nusemtl " << mat.substr(mat.size() - MAX_MATERIAL_NAME, mat.size()).c_str(); - } else { - out << "\nusemtl " << mat.c_str(); - } - } - - out << faces.c_str(); - lastMat = mat; - } - } - - out << "\n"; - } - - if(expmat) - { - TextFileOutputStream outMtl(mtlFile.c_str()); - if(outMtl.failed()) - { - globalErrorStream() << "Unable to open material file\n"; - return false; - } - - outMtl << "# Wavefront material file exported with NetRadiants brushexport plugin.\n"; - outMtl << "# Material Count: " << (const Unsigned)materials.size() << "\n\n"; - for(std::set::const_iterator it(materials.begin()); it != materials.end(); ++it) - { - if(limNames && it->size() > MAX_MATERIAL_NAME) - { - outMtl << "newmtl " << it->substr(it->size() - MAX_MATERIAL_NAME, it->size()).c_str() << "\n"; - } else { - outMtl << "newmtl " << it->c_str() << "\n"; - } - } - } - - return true; -} - - -class ForEachFace : public BrushVisitor -{ -public: - ForEachFace(ExportData& _exporter) - : exporter(_exporter) - {} - - void visit(Face& face) const - { - exporter.AddBrushFace(face); - } - -private: - ExportData& exporter; -}; - -class ForEachSelected : public SelectionSystem::Visitor -{ -public: - ForEachSelected(ExportData& _exporter) - : exporter(_exporter) - {} - - void visit(scene::Instance& instance) const - { - BrushInstance* bptr = InstanceTypeCast::cast(instance); - if(bptr) - { - Brush& brush(bptr->getBrush()); - - exporter.BeginBrush(brush); - ForEachFace face_vis(exporter); - brush.forEachFace(face_vis); - exporter.EndBrush(); - } - } - -private: - ExportData& exporter; -}; - -bool ExportSelection(const std::set& ignorelist, collapsemode m, bool exmat, const std::string& path, bool limNames, bool objs) -{ - ExportDataAsWavefront exporter(ignorelist, m, exmat, limNames, objs); - - ForEachSelected vis(exporter); - GlobalSelectionSystem().foreachSelected(vis); - - return exporter.WriteToFile(path, m); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/export.h b/misc/mediasource/extra/netradiant-src/contrib/brushexport/export.h deleted file mode 100644 index 3482bbed..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/export.h +++ /dev/null @@ -1,15 +0,0 @@ -#ifndef EXPORT_H -#define EXPORT_H -#include -#include - -enum collapsemode -{ - COLLAPSE_ALL, - COLLAPSE_BY_MATERIAL, - COLLAPSE_NONE -}; - -bool ExportSelection(const std::set& ignorelist, collapsemode m, bool exmat, const std::string& path, bool limitMatNames, bool objects); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/interface.cpp b/misc/mediasource/extra/netradiant-src/contrib/brushexport/interface.cpp deleted file mode 100644 index 6525e201..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/interface.cpp +++ /dev/null @@ -1,241 +0,0 @@ -#include -#include - -#include "debugging/debugging.h" -#include "callbacks.h" -#include "support.h" - -#define GLADE_HOOKUP_OBJECT(component,widget,name) \ - g_object_set_data_full (G_OBJECT (component), name, \ - gtk_widget_ref (widget), (GDestroyNotify) gtk_widget_unref) - -#define GLADE_HOOKUP_OBJECT_NO_REF(component,widget,name) \ - g_object_set_data (G_OBJECT (component), name, widget) - -// created by glade -GtkWidget* -create_w_plugplug2 (void) -{ - GtkWidget *w_plugplug2; - GtkWidget *vbox1; - GtkWidget *hbox2; - GtkWidget *vbox4; - GtkWidget *r_collapse; - GSList *r_collapse_group = NULL; - GtkWidget *r_collapsebymaterial; - GtkWidget *r_nocollapse; - GtkWidget *vbox3; - GtkWidget *b_export; - GtkWidget *b_close; - GtkWidget *vbox2; - GtkWidget *label1; - GtkWidget *scrolledwindow1; - GtkWidget *t_materialist; - GtkWidget *ed_materialname; - GtkWidget *hbox1; - GtkWidget *b_addmaterial; - GtkWidget *b_removematerial; - GtkWidget *t_exportmaterials; - GtkWidget *t_limitmatnames; - GtkWidget *t_objects; - GtkTooltips *tooltips; - - tooltips = gtk_tooltips_new(); - - w_plugplug2 = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_widget_set_name (w_plugplug2, "w_plugplug2"); - gtk_window_set_title (GTK_WINDOW (w_plugplug2), "BrushExport-Plugin 3.0 by namespace"); - gtk_window_set_position (GTK_WINDOW (w_plugplug2), GTK_WIN_POS_CENTER); - gtk_window_set_destroy_with_parent (GTK_WINDOW (w_plugplug2), TRUE); - - vbox1 = gtk_vbox_new (FALSE, 0); - gtk_widget_set_name (vbox1, "vbox1"); - gtk_widget_show (vbox1); - gtk_container_add (GTK_CONTAINER (w_plugplug2), vbox1); - gtk_container_set_border_width (GTK_CONTAINER (vbox1), 5); - - hbox2 = gtk_hbox_new (TRUE, 5); - gtk_widget_set_name (hbox2, "hbox2"); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox1), hbox2, FALSE, FALSE, 0); - gtk_container_set_border_width (GTK_CONTAINER (hbox2), 5); - - vbox4 = gtk_vbox_new (TRUE, 0); - gtk_widget_set_name (vbox4, "vbox4"); - gtk_widget_show (vbox4); - gtk_box_pack_start (GTK_BOX (hbox2), vbox4, TRUE, FALSE, 0); - - r_collapse = gtk_radio_button_new_with_mnemonic (NULL, "Collapse mesh"); - gtk_widget_set_name (r_collapse, "r_collapse"); - gtk_tooltips_set_tip (GTK_TOOLTIPS(tooltips), r_collapse, "Collapse all brushes into a single group", "Collapse all brushes into a single group"); - gtk_widget_show (r_collapse); - gtk_box_pack_start (GTK_BOX (vbox4), r_collapse, FALSE, FALSE, 0); - gtk_radio_button_set_group (GTK_RADIO_BUTTON (r_collapse), r_collapse_group); - r_collapse_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (r_collapse)); - - r_collapsebymaterial = gtk_radio_button_new_with_mnemonic (NULL, "Collapse by material"); - gtk_widget_set_name (r_collapsebymaterial, "r_collapsebymaterial"); - gtk_tooltips_set_tip (GTK_TOOLTIPS(tooltips), r_collapsebymaterial, "Collapse into groups by material", "Collapse into groups by material"); - gtk_widget_show (r_collapsebymaterial); - gtk_box_pack_start (GTK_BOX (vbox4), r_collapsebymaterial, FALSE, FALSE, 0); - gtk_radio_button_set_group (GTK_RADIO_BUTTON (r_collapsebymaterial), r_collapse_group); - r_collapse_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (r_collapsebymaterial)); - - r_nocollapse = gtk_radio_button_new_with_mnemonic (NULL, "Don't collapse"); - gtk_widget_set_name (r_nocollapse, "r_nocollapse"); - gtk_tooltips_set_tip (GTK_TOOLTIPS(tooltips), r_nocollapse, "Every brush is stored in its own group", "Every brush is stored in its own group"); - gtk_widget_show (r_nocollapse); - gtk_box_pack_start (GTK_BOX (vbox4), r_nocollapse, FALSE, FALSE, 0); - gtk_radio_button_set_group (GTK_RADIO_BUTTON (r_nocollapse), r_collapse_group); - r_collapse_group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (r_nocollapse)); - - vbox3 = gtk_vbox_new (FALSE, 0); - gtk_widget_set_name (vbox3, "vbox3"); - gtk_widget_show (vbox3); - gtk_box_pack_start (GTK_BOX (hbox2), vbox3, FALSE, FALSE, 0); - - b_export = gtk_button_new_from_stock ("gtk-save"); - gtk_widget_set_name (b_export, "b_export"); - gtk_widget_show (b_export); - gtk_box_pack_start (GTK_BOX (vbox3), b_export, TRUE, FALSE, 0); - gtk_container_set_border_width (GTK_CONTAINER (b_export), 5); - - b_close = gtk_button_new_from_stock ("gtk-cancel"); - gtk_widget_set_name (b_close, "b_close"); - gtk_widget_show (b_close); - gtk_box_pack_start (GTK_BOX (vbox3), b_close, TRUE, FALSE, 0); - gtk_container_set_border_width (GTK_CONTAINER (b_close), 5); - - vbox2 = gtk_vbox_new (FALSE, 5); - gtk_widget_set_name (vbox2, "vbox2"); - gtk_widget_show (vbox2); - gtk_box_pack_start (GTK_BOX (vbox1), vbox2, TRUE, TRUE, 0); - gtk_container_set_border_width (GTK_CONTAINER (vbox2), 2); - - label1 = gtk_label_new ("Ignored materials:"); - gtk_widget_set_name (label1, "label1"); - gtk_widget_show (label1); - gtk_box_pack_start (GTK_BOX (vbox2), label1, FALSE, FALSE, 0); - - scrolledwindow1 = gtk_scrolled_window_new (NULL, NULL); - gtk_widget_set_name (scrolledwindow1, "scrolledwindow1"); - gtk_widget_show (scrolledwindow1); - gtk_box_pack_start (GTK_BOX (vbox2), scrolledwindow1, TRUE, TRUE, 0); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow1), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledwindow1), GTK_SHADOW_IN); - - t_materialist = gtk_tree_view_new (); - gtk_widget_set_name (t_materialist, "t_materialist"); - gtk_widget_show (t_materialist); - gtk_container_add (GTK_CONTAINER (scrolledwindow1), t_materialist); - gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (t_materialist), FALSE); - gtk_tree_view_set_enable_search (GTK_TREE_VIEW (t_materialist), FALSE); - - ed_materialname = gtk_entry_new (); - gtk_widget_set_name (ed_materialname, "ed_materialname"); - gtk_widget_show (ed_materialname); - gtk_box_pack_start (GTK_BOX (vbox2), ed_materialname, FALSE, FALSE, 0); - - hbox1 = gtk_hbox_new (TRUE, 0); - gtk_widget_set_name (hbox1, "hbox1"); - gtk_widget_show (hbox1); - gtk_box_pack_start (GTK_BOX (vbox2), hbox1, FALSE, FALSE, 0); - - b_addmaterial = gtk_button_new_from_stock ("gtk-add"); - gtk_widget_set_name (b_addmaterial, "b_addmaterial"); - gtk_widget_show (b_addmaterial); - gtk_box_pack_start (GTK_BOX (hbox1), b_addmaterial, FALSE, FALSE, 0); - - b_removematerial = gtk_button_new_from_stock ("gtk-remove"); - gtk_widget_set_name (b_removematerial, "b_removematerial"); - gtk_widget_show (b_removematerial); - gtk_box_pack_start (GTK_BOX (hbox1), b_removematerial, FALSE, FALSE, 0); - - t_limitmatnames = gtk_check_button_new_with_mnemonic ("Use short material names (max. 20 chars)"); - gtk_widget_set_name (t_limitmatnames, "t_limitmatnames"); - gtk_widget_show (t_limitmatnames); - gtk_box_pack_end (GTK_BOX (vbox2), t_limitmatnames, FALSE, FALSE, 0); - - t_objects = gtk_check_button_new_with_mnemonic ("Create (o)bjects instead of (g)roups"); - gtk_widget_set_name (t_objects, "t_objects"); - gtk_widget_show (t_objects); - gtk_box_pack_end (GTK_BOX (vbox2), t_objects, FALSE, FALSE, 0); - - t_exportmaterials = gtk_check_button_new_with_mnemonic ("Create material information (.mtl file)"); - gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(t_exportmaterials), true); - gtk_widget_set_name (t_exportmaterials, "t_exportmaterials"); - gtk_widget_show (t_exportmaterials); - gtk_box_pack_end (GTK_BOX (vbox2), t_exportmaterials, FALSE, FALSE, 10); - - using namespace callbacks; - g_signal_connect(G_OBJECT(w_plugplug2), "destroy", G_CALLBACK(OnDestroy), NULL); - g_signal_connect_swapped(G_OBJECT(b_close), "clicked", G_CALLBACK (OnDestroy), NULL); - - g_signal_connect ((gpointer) b_export, "clicked", G_CALLBACK (OnExportClicked), NULL); - g_signal_connect ((gpointer) b_addmaterial, "clicked", G_CALLBACK (OnAddMaterial), NULL); - g_signal_connect ((gpointer) b_removematerial, "clicked", G_CALLBACK (OnRemoveMaterial), NULL); - g_signal_connect ((gpointer) t_exportmaterials, "clicked", G_CALLBACK (OnExportMatClicked), NULL); - - /* Store pointers to all widgets, for use by lookup_widget(). */ - GLADE_HOOKUP_OBJECT_NO_REF (w_plugplug2, w_plugplug2, "w_plugplug2"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox1, "vbox1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, hbox2, "hbox2"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox4, "vbox4"); - GLADE_HOOKUP_OBJECT (w_plugplug2, r_collapse, "r_collapse"); - GLADE_HOOKUP_OBJECT (w_plugplug2, r_collapsebymaterial, "r_collapsebymaterial"); - GLADE_HOOKUP_OBJECT (w_plugplug2, r_nocollapse, "r_nocollapse"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox3, "vbox3"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_export, "b_export"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_close, "b_close"); - GLADE_HOOKUP_OBJECT (w_plugplug2, vbox2, "vbox2"); - GLADE_HOOKUP_OBJECT (w_plugplug2, label1, "label1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, scrolledwindow1, "scrolledwindow1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_materialist, "t_materialist"); - GLADE_HOOKUP_OBJECT (w_plugplug2, ed_materialname, "ed_materialname"); - GLADE_HOOKUP_OBJECT (w_plugplug2, hbox1, "hbox1"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_addmaterial, "b_addmaterial"); - GLADE_HOOKUP_OBJECT (w_plugplug2, b_removematerial, "b_removematerial"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_exportmaterials, "t_exportmaterials"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_limitmatnames, "t_limitmatnames"); - GLADE_HOOKUP_OBJECT (w_plugplug2, t_objects, "t_objects"); - - return w_plugplug2; -} - -// global main window, is 0 when not created -GtkWidget* g_brushexp_window = 0; - -// spawn plugin window (and make sure it got destroyed first or never created) -void CreateWindow(void) -{ - ASSERT_NOTNULL(!g_brushexp_window); - - GtkWidget* wnd = create_w_plugplug2(); - - // column & renderer - GtkTreeViewColumn* col = gtk_tree_view_column_new(); - gtk_tree_view_column_set_title(col, "materials"); - gtk_tree_view_append_column(GTK_TREE_VIEW(lookup_widget(wnd, "t_materialist")), col); - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(lookup_widget(wnd, "t_materialist")), -1, "", renderer, "text", 0, NULL); - - // list store - GtkListStore* ignorelist = gtk_list_store_new(1, G_TYPE_STRING); - gtk_tree_view_set_model(GTK_TREE_VIEW(lookup_widget(wnd, "t_materialist")), GTK_TREE_MODEL(ignorelist)); - g_object_unref(ignorelist); - - gtk_widget_show_all(wnd); - g_brushexp_window = wnd; -} - -void DestroyWindow(void) -{ - ASSERT_NOTNULL(g_brushexp_window); - gtk_widget_destroy(g_brushexp_window); - g_brushexp_window = 0; -} - -bool IsWindowOpen(void) -{ - return g_brushexp_window != 0; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/plugin.cpp b/misc/mediasource/extra/netradiant-src/contrib/brushexport/plugin.cpp deleted file mode 100644 index 3b3fab09..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/plugin.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* -Copyright (C) 2006, Thomas Nitschke. -All Rights Reserved. - -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 "plugin.h" - -#include "iplugin.h" -#include "qerplugin.h" - -#include -#include - -#include "debugging/debugging.h" -#include "string/string.h" -#include "modulesystem/singletonmodule.h" -#include "stream/textfilestream.h" -#include "stream/stringstream.h" -#include "gtkutil/messagebox.h" -#include "gtkutil/filechooser.h" - -#include "ibrush.h" -#include "iscenegraph.h" -#include "iselection.h" -#include "ifilesystem.h" -#include "ifiletypes.h" - -#include "support.h" - -#include "typesystem.h" - -void CreateWindow (void); -void DestroyWindow(void); -bool IsWindowOpen(void); - -namespace BrushExport -{ - GtkWindow* g_mainwnd; - - const char* init(void* hApp, void* pMainWidget) - { - g_mainwnd = (GtkWindow*)pMainWidget; - ASSERT_NOTNULL(g_mainwnd); - return ""; - } - const char* getName() - { - return "Brush export Plugin"; - } - const char* getCommandList() - { - return "Export selected as Wavefront Object;About"; - } - const char* getCommandTitleList() - { - return ""; - } - - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) - { - if(string_equal(command, "About")) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_mainwnd), "Brushexport plugin v 2.0 by namespace (www.codecreator.net)\n" - "Enjoy!\n\nSend feedback to spam@codecreator.net", "About me...", - eMB_OK, - eMB_ICONDEFAULT); - } - else if(string_equal(command, "Export selected as Wavefront Object")) - { - if(IsWindowOpen()) - DestroyWindow(); - CreateWindow(); - } - } -} - -class BrushExportDependencies : - public GlobalRadiantModuleRef, - public GlobalFiletypesModuleRef, - public GlobalBrushModuleRef, - public GlobalFileSystemModuleRef, - public GlobalSceneGraphModuleRef, - public GlobalSelectionModuleRef -{ -public: - BrushExportDependencies(void) - : GlobalBrushModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("brushtypes")) - {} -}; - -class BrushExportModule : public TypeSystemRef -{ - _QERPluginTable m_plugin; -public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "brushexport2"); - - BrushExportModule() - { - m_plugin.m_pfnQERPlug_Init = &BrushExport::init; - m_plugin.m_pfnQERPlug_GetName = &BrushExport::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &BrushExport::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &BrushExport::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &BrushExport::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } -}; - -typedef SingletonModule SingletonBrushExportModule; -SingletonBrushExportModule g_BrushExportModule; - -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - g_BrushExportModule.selfRegister(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/plugin.h b/misc/mediasource/extra/netradiant-src/contrib/brushexport/plugin.h deleted file mode 100644 index da0faa13..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/plugin.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2006, Thomas Nitschke. -All Rights Reserved. - -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(INCLUDED_BRUSH_EXPORT_H) -#define INCLUDED_BRUSH_EXPORT_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/support.cpp b/misc/mediasource/extra/netradiant-src/contrib/brushexport/support.cpp deleted file mode 100644 index 2835b112..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/support.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include - -#include "support.h" - -GtkWidget* -lookup_widget (GtkWidget *widget, - const gchar *widget_name) -{ - GtkWidget *parent, *found_widget; - - for (;;) - { - if (GTK_IS_MENU (widget)) - parent = gtk_menu_get_attach_widget (GTK_MENU (widget)); - else - parent = widget->parent; - if (!parent) - parent = (GtkWidget*) g_object_get_data (G_OBJECT (widget), "GladeParentKey"); - if (parent == NULL) - break; - widget = parent; - } - - found_widget = (GtkWidget*) g_object_get_data (G_OBJECT (widget), - widget_name); - if (!found_widget) - g_warning ("Widget not found: %s", widget_name); - return found_widget; -} - - diff --git a/misc/mediasource/extra/netradiant-src/contrib/brushexport/support.h b/misc/mediasource/extra/netradiant-src/contrib/brushexport/support.h deleted file mode 100644 index 628885a5..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/brushexport/support.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * DO NOT EDIT THIS FILE - it is generated by Glade. - */ - -#ifdef HAVE_CONFIG_H -# include -#endif - -#include - -/* - * Public Functions. - */ - -/* - * This function returns a widget in a component created by Glade. - * Call it with the toplevel widget in the component (i.e. a window/dialog), - * or alternatively any widget in the component, and the name of the widget - * you want returned. - */ -GtkWidget* lookup_widget (GtkWidget *widget, - const gchar *widget_name); - - diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/bitmaps/camera_insp.bmp b/misc/mediasource/extra/netradiant-src/contrib/camera/bitmaps/camera_insp.bmp deleted file mode 100644 index 1286716e..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/camera/bitmaps/camera_insp.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/camera.cpp b/misc/mediasource/extra/netradiant-src/contrib/camera/camera.cpp deleted file mode 100644 index 488e6549..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/camera.cpp +++ /dev/null @@ -1,290 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#include "camera.h" - -// Render view -CRenderer *Renderer = NULL; - -// Interaction -CListener *Listener = NULL; - -// plugin name -static const char *PLUGIN_NAME = "Camera"; - -// commands in the menu -static const char *PLUGIN_COMMANDS = "About...,-,Load Camera...,-,Preview Camera,-,Camera Inspector...,-,New Spline Camera,New Interpolated Camera,New Fixed Camera"; - -// globals -GtkWidget *g_pRadiantWnd = NULL; -GtkWidget *g_pCameraInspectorWnd = NULL; -CCamera *firstCam = NULL; // double linked list -CCamera *firstFreeCam = NULL; // single linked list -CCamera *currentCam = NULL; // single item -bool g_bEditOn = false; -int g_iEditMode = 0; // 0: editting points 1: adding points -int g_iActiveTarget = -1; -int g_iPreviewRunning = 0; // 0: no preview 1: start preview 2: preview in progress - -static const char *PLUGIN_ABOUT = "Camera v1.0 for NetRadiant\n" - "by Arnout van Meer (rr2do2@splashdamage.com)\n\n" - "This product contains software technology\n" - "from id Software, Inc. ('id Technology').\n" - "id Technology (c) 2001, 2002 id Software, Inc."; - - -#include "iplugin.h" - -const char* QERPlug_Init(void* hApp, void* pMainWidget) -{ - g_pRadiantWnd = (GtkWidget*)pMainWidget; - - // initialize cams - for( int i = 0; i < MAX_CAMERAS; i++ ) { - if( i == 0 ) { - firstFreeCam = new CCamera( i ); - firstCam = firstFreeCam; - } else { - firstCam->SetNext( new CCamera( i ) ); - firstCam = firstCam->GetNext(); - } - } - firstCam = NULL; - - if( !Renderer ) - { - Renderer = new CRenderer; - } - - if( g_pCameraInspectorWnd == NULL ) - g_pCameraInspectorWnd = CreateCameraInspectorDialog(); - - GetFileTypeRegistry()->addType("camera", "", filetype_t("Camera file", "*.camera")); - - return "Camera for NetRadiant"; -} - -const char* QERPlug_GetName() -{ - return PLUGIN_NAME; -} - -const char* QERPlug_GetCommandList() -{ - return PLUGIN_COMMANDS; -} - -void QERPlug_Dispatch (const char* p, float* vMin, float* vMax, bool bSingleBrush) -{ - if( !strcmp( p, "New Fixed Camera" ) ) - DoNewFixedCamera(); - else if( !strcmp( p, "New Interpolated Camera" ) ) - DoNewInterpolatedCamera(); - else if( !strcmp( p, "New Spline Camera" ) ) - DoNewSplineCamera(); - else if( !strcmp( p, "Camera Inspector..." ) ) - DoCameraInspector(); - else if( !strcmp( p, "Preview Camera" ) ) - DoPreviewCamera(); - else if( !strcmp( p, "Load Camera..." ) ) - DoLoadCamera(); - else if( !strcmp( p, "About..." ) ) - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, PLUGIN_ABOUT, "About", eMB_OK ); -} - - -// toolbar - -#include "itoolbar.h" - -unsigned int ToolbarButtonCount() -{ - return 1; -} - -class CameraInspectorButton : public IToolbarButton -{ -public: - virtual const char* getImage() const - { - return "camera_insp.bmp"; - } - virtual const char* getText() const - { - return "Inspector"; - } - virtual const char* getTooltip() const - { - return "Camera Inspector"; - } - virtual void activate() const - { - DoCameraInspector(); - } - virtual EType getType() const - { - return eButton; - } -}; - -CameraInspectorButton g_camerainspectorbutton; - -const IToolbarButton* GetToolbarButton(unsigned int index) -{ - return &g_camerainspectorbutton; -} - - -_QERFuncTable_1 g_FuncTable; -_QERQglTable g_QglTable; -_QERUITable g_UITable; -_QERCameraTable g_CameraTable; - -// ============================================================================= -// SYNAPSE - -#include "synapse.h" - -class CameraSynapseClient : public CSynapseClient -{ -public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - - CameraSynapseClient() { } - virtual ~CameraSynapseClient() { } -}; - -CSynapseServer* g_pSynapseServer = NULL; -CameraSynapseClient g_SynapseClient; - -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(TOOLBAR_MAJOR, "camera", sizeof(_QERPlugToolbarTable)); - g_SynapseClient.AddAPI(PLUGIN_MAJOR, "camera", sizeof(_QERPluginTable)); - - g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(_QERFuncTable_1), SYN_REQUIRE, &g_FuncTable); - g_SynapseClient.AddAPI(UI_MAJOR, NULL, sizeof(_QERUITable), SYN_REQUIRE, &g_UITable); - g_SynapseClient.AddAPI(QGL_MAJOR, NULL, sizeof(_QERQglTable), SYN_REQUIRE, &g_QglTable); - g_SynapseClient.AddAPI(CAMERA_MAJOR, NULL, sizeof(_QERCameraTable), SYN_REQUIRE, &g_CameraTable); - - return &g_SynapseClient; -} - -bool CameraSynapseClient::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, TOOLBAR_MAJOR)) - { - _QERPlugToolbarTable* pTable= static_cast<_QERPlugToolbarTable*>(pAPI->mpTable); - - pTable->m_pfnToolbarButtonCount = &ToolbarButtonCount; - pTable->m_pfnGetToolbarButton = &GetToolbarButton; - return true; - } - else if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable* pTable= static_cast<_QERPluginTable*>(pAPI->mpTable); - - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; -} - -#include "version.h" - -const char* CameraSynapseClient::GetInfo() -{ - return "Camera plugin v1.0 - Arnout van Meer - built " __DATE__ " " RADIANT_VERSION; -} - - - -// -// CCamera -// -CCamera *AllocCam() { - if( !firstFreeCam ) - return( NULL ); - - CCamera *cam = firstFreeCam; - firstFreeCam = firstFreeCam->GetNext(); - cam->Init(); - if( firstCam ) { - cam->SetNext( firstCam ); - firstCam->SetPrev( cam ); - } - firstCam = cam; - - return( cam ); -} - -void FreeCam( CCamera *cam ) { - if( cam->GetPrev() ) { - if( cam->GetNext() ) { - cam->GetPrev()->SetNext( cam->GetNext() ); - cam->GetNext()->SetPrev( cam->GetPrev() ); - } else { - cam->GetPrev()->SetNext( NULL ); - } - } else if( cam->GetNext() ) { - cam->GetNext()->SetPrev( NULL ); - firstCam = cam->GetNext(); - } else { - firstCam = NULL; - } - - cam->GetCam()->clear(); - cam->Init(); - - if( firstFreeCam ) { - cam->SetNext( firstFreeCam ); - } - firstFreeCam = cam; -} - -void SetCurrentCam( CCamera *cam ) { - currentCam = cam; -} - -CCamera *GetCurrentCam() { - return( currentCam ); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/camera.def b/misc/mediasource/extra/netradiant-src/contrib/camera/camera.def deleted file mode 100644 index 6a597438..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/camera.def +++ /dev/null @@ -1,8 +0,0 @@ -; camera.def : Declares the module parameters for the DLL. - -LIBRARY "CAMERA" -DESCRIPTION 'CAMERA Windows Dynamic Link Library' - -EXPORTS - ; Explicit exports can go here - Synapse_EnumerateInterfaces @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/camera.h b/misc/mediasource/extra/netradiant-src/contrib/camera/camera.h deleted file mode 100644 index 4c7f6cb2..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/camera.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#ifndef _CAMERA_H_ -#define _CAMERA_H_ - -typedef unsigned char byte; - -#include "mathlib.h" -#include -#include "qertypes.h" -#include - -#define USE_QERTABLE_DEFINE -#include "iscenegraph.h" -#include "qerplugin.h" - -#define USE_QGLTABLE_DEFINE -#include "igl.h" -extern _QERQglTable __QGLTABLENAME; - -#include "iui.h" -#include "icamera.h" - -#include "bytebool.h" - -class CCamera; -#include - -#include "str.h" - - -#include "misc.h" -#include "dialogs.h" -#include "funchandlers.h" -#include "renderer.h" -#include "listener.h" - -extern _QERFuncTable_1 g_FuncTable; -extern _QERQglTable g_QglTable; -extern _QERUITable g_UITable; -extern _QERCameraTable g_CameraTable; - -extern CRenderer *Renderer; -extern CListener *Listener; - -// splinelib -#define CAMERA_PLUGIN -#define DotProduct(a,b) ((a)[0]*(b)[0]+(a)[1]*(b)[1]+(a)[2]*(b)[2]) - -#include "splines/splines.h" - -// this needs to match splines.cpp -#define MAX_CAMERAS 64 -extern idCameraDef camera[MAX_CAMERAS]; - -extern "C" qboolean loadCamera(int camNum, const char *name); - -#ifndef PATH_MAX -#define PATH_MAX 260 -#endif - -// -// CCamera -// - -class CCamera { -public: - CCamera( int i ) { - cam = &camera[i]; - camnum = i; - Init(); - } - ~CCamera(); - - void Init() { - next = prev = NULL; - fileName[0] = '\0'; - hasbeensaved = 0; - } - - idCameraDef *GetCam() { - return( cam ); - } - int GetCamNum() { - return( camnum ); - } - - char *GetFileName() { - return( fileName ); - } - void SetFileName( const char *name, bool save ) { - strcpy( fileName, name ); - if( save ) - hasbeensaved = 1; - } - - CCamera *GetNext() { - return( next ); - } - - CCamera *GetPrev() { - return( prev ); - } - - void SetNext( CCamera *camera ) { - next = camera; - } - void SetPrev( CCamera *camera ) { - prev = camera; - } - - int HasBeenSaved() { - return( hasbeensaved ); - } - void HasBeenModified() { - if( hasbeensaved ) - hasbeensaved = 2; - } - -protected: - idCameraDef *cam; - int camnum; - CCamera *next, *prev; - char fileName[PATH_MAX]; - int hasbeensaved; // 0:never saved 1:saved 2:saved, but modified -}; - -CCamera *AllocCam(); -void FreeCam( CCamera *cam ); -void SetCurrentCam( CCamera *cam ); -CCamera *GetCurrentCam(); - -// globals -extern GtkWidget *g_pRadiantWnd; -extern GtkWidget *g_pCameraInspectorWnd; -extern CCamera *firstCam; -extern bool g_bEditOn; -extern int g_iEditMode; -extern int g_iActiveTarget; -extern int g_iPreviewRunning; -extern CCamera *g_pCurrentEditCam; - -#endif // _CAMERA_H_ diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs.cpp b/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs.cpp deleted file mode 100644 index 40df284e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs.cpp +++ /dev/null @@ -1,1356 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#include "camera.h" - -static GSList *g_pEditTypeRadio = NULL; -static GtkWidget *g_pEditModeEditRadioButton = NULL; -GtkWidget *g_pEditModeAddRadioButton = NULL; -static GtkWidget *g_pSecondsEntry = NULL; -static GtkWidget *g_pEventsList = NULL; -static GtkLabel *g_pCurrentTime = NULL; -static GtkLabel *g_pTotalTime = NULL; -static GtkAdjustment *g_pTimeLine = NULL; -static GtkWidget *g_pTrackCamera = NULL; -static GtkWidget *g_pCamName = NULL; -static char *g_cNull = '\0'; - -static gint ci_editmode_edit( GtkWidget *widget, gpointer data ) -{ - g_iEditMode = 0; - - return TRUE; -} - -static gint ci_editmode_add( GtkWidget *widget, gpointer data ) -{ - g_iEditMode = 1; - - return TRUE; -} - -/*static gint ci_delete_selected( GtkWidget *widget, gpointer data ) -{ - return TRUE; -} - -static gint ci_select_all( GtkWidget *widget, gpointer data ) -{ - return TRUE; -}*/ - -static gint ci_new( GtkWidget *widget, gpointer data ) -{ - GtkWidget *window, *w, *vbox, *vbox2, *hbox, *frame; //, *name; - GtkWidget *fixed, *interpolated, *spline; - EMessageBoxReturn ret; - int loop = 1; - GSList *targetTypeRadio = NULL; -// char buf[128]; - - // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "New Camera" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - // fill the window - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show( vbox ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - frame = gtk_frame_new( "Type" ); - gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); - gtk_widget_show( frame ); - - vbox2 = gtk_vbox_new( FALSE, 5 ); - gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); - gtk_container_set_border_width( GTK_CONTAINER (vbox2), 5 ); - gtk_widget_show( vbox2 ); - - // -------------------------- // - - fixed = gtk_radio_button_new_with_label( targetTypeRadio, "Fixed" ); - gtk_box_pack_start( GTK_BOX( vbox2 ), fixed, FALSE, FALSE, 3 ); - gtk_widget_show( fixed ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( fixed ) ); - - interpolated = gtk_radio_button_new_with_label( targetTypeRadio, "Interpolated" ); - gtk_box_pack_start( GTK_BOX( vbox2 ), interpolated, FALSE, FALSE, 3 ); - gtk_widget_show( interpolated ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( interpolated ) ); - - spline = gtk_radio_button_new_with_label( targetTypeRadio, "Spline" ); - gtk_box_pack_start( GTK_BOX( vbox2 ), spline, FALSE, FALSE, 3 ); - gtk_widget_show( spline ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( spline ) ); - - // -------------------------- // - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); - - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // -------------------------- // - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if( ret == eIDOK ) { - if( gtk_toggle_button_get_active( (GtkToggleButton*)fixed ) ) - DoNewFixedCamera(); - else if( gtk_toggle_button_get_active( (GtkToggleButton*)interpolated ) ) - DoNewInterpolatedCamera(); - else if( gtk_toggle_button_get_active( (GtkToggleButton*)spline ) ) - DoNewSplineCamera(); - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return TRUE; -} - -static gint ci_load( GtkWidget *widget, gpointer data ) -{ - DoLoadCamera(); - - return TRUE; -} - -static gint ci_save( GtkWidget *widget, gpointer data ) -{ - DoSaveCamera(); - - return TRUE; -} - -static gint ci_unload( GtkWidget *widget, gpointer data ) -{ - DoUnloadCamera(); - - return TRUE; -} - -static gint ci_apply( GtkWidget *widget, gpointer data ) -{ - if( GetCurrentCam() ) { - const char *str; - char buf[128]; - bool build = false; - - str = gtk_entry_get_text( GTK_ENTRY(g_pCamName) ); - - if( str ) { - GetCurrentCam()->GetCam()->setName( str ); - build = true; - } - - str = gtk_entry_get_text( GTK_ENTRY(g_pSecondsEntry) ); - - if( str ) { - GetCurrentCam()->GetCam()->setBaseTime( atof( str ) ); - build = true; - } - - if( build ) { - GetCurrentCam()->GetCam()->buildCamera(); - } - - sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getBaseTime() ); - gtk_entry_set_text( GTK_ENTRY(g_pSecondsEntry), buf ); - - sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getTotalTime() ); - gtk_label_set_text( g_pCurrentTime, "0.00" ); - gtk_label_set_text( g_pTotalTime, buf ); - - gtk_adjustment_set_value( g_pTimeLine, 0.f ); - g_pTimeLine->upper = GetCurrentCam()->GetCam()->getTotalTime() * 1000; - - GetCurrentCam()->HasBeenModified(); - } - - return TRUE; -} - -static gint ci_preview( GtkWidget *widget, gpointer data ) -{ - if( GetCurrentCam() ) { - g_iPreviewRunning = 1; - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } - - return TRUE; -} - -static gint ci_expose( GtkWidget *widget, gpointer data ) -{ - // start edit mode - DoStartEdit( GetCurrentCam() ); - - return FALSE; -} - -static gint ci_close( GtkWidget *widget, gpointer data ) -{ - gtk_widget_hide( g_pCameraInspectorWnd ); - - // exit edit mode - DoStopEdit(); - - return TRUE; -} - -static GtkWidget *g_pPathListCombo = NULL; -static GtkLabel *g_pPathType = NULL; - -static void RefreshPathListCombo( void ) -{ - if( !g_pPathListCombo ) - return; - - GList *combo_list = (GList*)NULL; - - if( GetCurrentCam() ) { - combo_list = g_list_append( combo_list, (void *)GetCurrentCam()->GetCam()->getPositionObj()->getName() ); - for( int i = 0; i < GetCurrentCam()->GetCam()->numTargets(); i++ ) { - combo_list = g_list_append( combo_list, (void *)GetCurrentCam()->GetCam()->getActiveTarget( i )->getName() ); - } - } else { - // add one empty string make gtk be quiet - combo_list = g_list_append( combo_list, (gpointer)g_cNull ); - } - - gtk_combo_set_popdown_strings( GTK_COMBO( g_pPathListCombo ), combo_list ); - g_list_free( combo_list ); -} - -static gint ci_pathlist_changed( GtkWidget *widget, gpointer data ) -{ - const char *str = gtk_entry_get_text( GTK_ENTRY(widget) ); - - if( !str || !GetCurrentCam() ) - return TRUE; - - int i; - for( i = 0; i < GetCurrentCam()->GetCam()->numTargets(); i++ ) { - if( !strcmp( str, GetCurrentCam()->GetCam()->getActiveTarget( i )->getName() ) ) - break; - } - - if( i >= 0 && i < GetCurrentCam()->GetCam()->numTargets() ) { - GetCurrentCam()->GetCam()->setActiveTarget( i ); - - g_iActiveTarget = i; - if( g_pPathType ) - gtk_label_set_text( g_pPathType, GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->typeStr() ); - } else { - g_iActiveTarget = -1; - if( g_pPathType ) - gtk_label_set_text( g_pPathType, GetCurrentCam()->GetCam()->getPositionObj()->typeStr() ); - } - - // start edit mode - if( g_pCameraInspectorWnd && GTK_WIDGET_VISIBLE( g_pCameraInspectorWnd ) ) - DoStartEdit( GetCurrentCam() ); - - return TRUE; -} - -static void RefreshEventList( void ) -{ - int i; - char buf[128]; - - // Clear events list - gtk_clist_freeze( GTK_CLIST(g_pEventsList) ); - gtk_clist_clear( GTK_CLIST(g_pEventsList) ); - - if( GetCurrentCam() ) { - // Fill events list - for( i = 0; i < GetCurrentCam()->GetCam()->numEvents(); i++ ) { - char rowbuf[3][128], *row[3]; - // FIXME: sort by time? - sprintf( rowbuf[0], "%li", GetCurrentCam()->GetCam()->getEvent(i)->getTime() ); row[0] = rowbuf[0]; - strncpy( rowbuf[1], GetCurrentCam()->GetCam()->getEvent(i)->typeStr(), sizeof(rowbuf[0]) ); row[1] = rowbuf[1]; - strncpy( rowbuf[2], GetCurrentCam()->GetCam()->getEvent(i)->getParam(), sizeof(rowbuf[1]) ); row[2] = rowbuf[2]; - gtk_clist_append( GTK_CLIST(g_pEventsList), row ); - } - - // Total duration might have changed - sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getTotalTime() ); - gtk_label_set_text( g_pCurrentTime, "0.00" ); - gtk_label_set_text( g_pTotalTime, buf ); - - gtk_adjustment_set_value( g_pTimeLine, 0.f ); - g_pTimeLine->upper = ( GetCurrentCam()->GetCam()->getTotalTime() * 1000 ); - } - - gtk_clist_thaw( GTK_CLIST(g_pEventsList) ); -} - -static gint ci_rename( GtkWidget *widget, gpointer data ) -{ - GtkWidget *window, *w, *vbox, *hbox, *name; - EMessageBoxReturn ret; - int loop = 1; - - if( !GetCurrentCam() ) - return TRUE; - - // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Rename Path" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize ( window ); - - // fill the window - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show( vbox ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Name:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - name = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), name, FALSE, FALSE, 0 ); - gtk_widget_show( name ); - - if( g_iActiveTarget < 0 ) - gtk_entry_set_text( GTK_ENTRY(name), GetCurrentCam()->GetCam()->getPositionObj()->getName() ); - else - gtk_entry_set_text( GTK_ENTRY(name), GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->getName() ); - - // -------------------------- // - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); - - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // -------------------------- // - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if( ret == eIDOK ) { - const char *str = gtk_entry_get_text( GTK_ENTRY(name) ); - - if( str && str[0] ) { - // Update the path - if( g_iActiveTarget < 0 ) - GetCurrentCam()->GetCam()->getPositionObj()->setName( str ); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->setName( str ); - - GetCurrentCam()->GetCam()->buildCamera(); - - // Rebuild the listbox - RefreshPathListCombo(); - } else { - dialogError = TRUE; - } - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return TRUE; -} - -static gint ci_add_target( GtkWidget *widget, gpointer data ) -{ - GtkWidget *window, *w, *vbox, *vbox2, *hbox, *frame, *name; - GtkWidget *fixed, *interpolated, *spline; - EMessageBoxReturn ret; - int loop = 1; - GSList *targetTypeRadio = NULL; - char buf[128]; - - if( !GetCurrentCam() ) - return TRUE; - - // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Add Target" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - // fill the window - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show( vbox ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Name:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - name = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), name, TRUE, TRUE, 0 ); - gtk_widget_show( name ); - - sprintf( buf, "target%i", GetCurrentCam()->GetCam()->numTargets() + 1 ); - gtk_entry_set_text( GTK_ENTRY(name), buf ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - frame = gtk_frame_new( "Type" ); - gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); - gtk_widget_show( frame ); - - vbox2 = gtk_vbox_new( FALSE, 5 ); - gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); - gtk_container_set_border_width( GTK_CONTAINER (vbox2), 5 ); - gtk_widget_show( vbox2 ); - - // -------------------------- // - - fixed = gtk_radio_button_new_with_label( targetTypeRadio, "Fixed" ); - gtk_box_pack_start( GTK_BOX( vbox2 ), fixed, FALSE, FALSE, 3 ); - gtk_widget_show( fixed ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( fixed ) ); - - interpolated = gtk_radio_button_new_with_label( targetTypeRadio, "Interpolated" ); - gtk_box_pack_start( GTK_BOX( vbox2 ), interpolated, FALSE, FALSE, 3 ); - gtk_widget_show( interpolated ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( interpolated ) ); - - spline = gtk_radio_button_new_with_label( targetTypeRadio, "Spline" ); - gtk_box_pack_start( GTK_BOX( vbox2 ), spline, FALSE, FALSE, 3 ); - gtk_widget_show( spline ); - targetTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( spline ) ); - - // -------------------------- // - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); - - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // -------------------------- // - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if( ret == eIDOK ) { - const char *str = gtk_entry_get_text( GTK_ENTRY(name) ); - - if( str && str[0] ) { - int type; - GList *li; - - if( gtk_toggle_button_get_active( (GtkToggleButton*)fixed ) ) - type = 0; - else if( gtk_toggle_button_get_active( (GtkToggleButton*)interpolated ) ) - type = 1; - else if( gtk_toggle_button_get_active( (GtkToggleButton*)spline ) ) - type = 2; - - // Add the target - GetCurrentCam()->GetCam()->addTarget( str, static_cast(type) ); - - // Rebuild the listbox - RefreshPathListCombo(); - - // Select the last item in the listbox - li = g_list_last( GTK_LIST(GTK_COMBO(g_pPathListCombo)->list)->children ); - gtk_list_select_child( GTK_LIST(GTK_COMBO(g_pPathListCombo)->list), GTK_WIDGET (li->data) ); - - // If this was the first one, refresh the event list - if( GetCurrentCam()->GetCam()->numTargets() == 1 ) { - RefreshEventList(); - } - - // Go to editmode Add - gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(g_pEditModeAddRadioButton), TRUE ); - - } else { - dialogError = TRUE; - } - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return TRUE; -} - -static GtkWidget *g_pCamListCombo = NULL; -static GtkLabel *g_pCamType = NULL; - -void RefreshCamListCombo( void ) -{ - if( !g_pCamListCombo ) - return; - - GList *combo_list = (GList*)NULL; - CCamera *combo_cam = firstCam; - if( combo_cam ) { - while( combo_cam ) { - //combo_list = g_list_append( combo_list, (void *)combo_cam->GetCam()->getName() ); - //if( combo_cam->HasBeenSaved() ) { - combo_list = g_list_append( combo_list, (void *)combo_cam->GetFileName() ); - /*} else { - char buf[128]; - sprintf( buf, "Unsaved Camera %i", combo_cam->GetCamNum() ); - combo_list = g_list_append( combo_list, (void *)buf ); - - //combo_list = g_list_append( combo_list, (void *)combo_cam->GetCam()->getName() ); // FIXME: this requires camera.dll to create unique names for new cams - }*/ - combo_cam = combo_cam->GetNext(); - } - }else { - // add one empty string make gtk be quiet - combo_list = g_list_append( combo_list, (gpointer)g_cNull ); - } - gtk_combo_set_popdown_strings( GTK_COMBO( g_pCamListCombo ), combo_list ); - g_list_free( combo_list ); - - // select our current entry in the list - if( GetCurrentCam() ) { - // stop editing on the current cam - //GetCurrentCam()->GetCam()->stopEdit(); // FIXME: this crashed on creating new cameras, why is it here? - - GList *li = GTK_LIST( GTK_COMBO(g_pCamListCombo)->list)->children; - combo_cam = firstCam; - while( li && combo_cam ) { - if( combo_cam == GetCurrentCam() ) { - gtk_list_select_child( GTK_LIST( GTK_COMBO(g_pCamListCombo)->list ), GTK_WIDGET( li->data ) ); - break; - } - li = li->next; - combo_cam = combo_cam->GetNext(); - } - } - - RefreshPathListCombo(); -} - -static gint ci_camlist_changed( GtkWidget *widget, gpointer data ) -{ - const char *str = gtk_entry_get_text( GTK_ENTRY(widget) ); - - CCamera *combo_cam = firstCam; - while( str && combo_cam ) { - //if( !strcmp( str, combo_cam->GetCam()->getName() ) ) - //if( combo_cam->HasBeenSaved() ) { - if( !strcmp( str, combo_cam->GetFileName() ) ) - break; - /*} else { - char buf[128]; - sprintf( buf, "Unsaved Camera %i", combo_cam->GetCamNum() ); - if( !strcmp( str, buf ) ) - //if( !strcmp( str, combo_cam->GetCam()->getName() ) ) - break; - }*/ - - combo_cam = combo_cam->GetNext(); - } - - SetCurrentCam( combo_cam ); - - if( g_pCamType ) { - if( GetCurrentCam() ) { - // Fill in our widgets fields for this camera - char buf[128]; - - // Set Name - gtk_entry_set_text( GTK_ENTRY(g_pCamName), GetCurrentCam()->GetCam()->getName() ); - - // Set type - gtk_label_set_text( g_pCamType, GetCurrentCam()->GetCam()->getPositionObj()->typeStr() ); - - // Set duration - sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getBaseTime() ); - gtk_entry_set_text( GTK_ENTRY(g_pSecondsEntry), buf ); - - sprintf( buf, "%.2f", GetCurrentCam()->GetCam()->getTotalTime() ); - gtk_label_set_text( g_pCurrentTime, "0.00" ); - gtk_label_set_text( g_pTotalTime, buf ); - - gtk_adjustment_set_value( g_pTimeLine, 0.f ); - g_pTimeLine->upper = GetCurrentCam()->GetCam()->getTotalTime() * 1000; - } else { - // Set Name - gtk_entry_set_text( GTK_ENTRY(g_pCamName), "" ); - - // Set type - gtk_label_set_text( g_pCamType, "" ); - - // Set duration - gtk_entry_set_text( GTK_ENTRY(g_pSecondsEntry), "30.00" ); - - gtk_label_set_text( g_pCurrentTime, "0.00" ); - gtk_label_set_text( g_pTotalTime, "30.00" ); - - gtk_adjustment_set_value( g_pTimeLine, 0.f ); - g_pTimeLine->upper = 30000; - } - - // Refresh event list - RefreshEventList(); - } - - RefreshPathListCombo(); - - // start edit mode - g_iActiveTarget = -1; - if( g_pCameraInspectorWnd && GTK_WIDGET_VISIBLE( g_pCameraInspectorWnd ) ) - DoStartEdit( GetCurrentCam() ); - - return TRUE; -} - -enum camEventType { - 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 -}; - -// { requires parameters, enabled } -const bool camEventFlags[][2] = { - { false, false }, - { false, true }, - { false, false }, - { false, false }, - { true, true }, - { false, false }, - { true, true }, - { false, false }, - { false, false }, - { false, true }, - { true, true }, - { true, true }, - { true, true }, - { false, true }, -}; - -const char *camEventStr[] = { - "n/a", - "Wait", - "Target wait", - "Speed", - "Change Target ", - "Snap Target", - "FOV ", - "Run Script", - "Trigger", - "Stop", - "Change to Camera (or ", - "Fade Out ", - "Fade In ", - "Feather" -}; - -static gint ci_add( GtkWidget *widget, gpointer data ) -{ - GtkWidget *window, *w, *vbox, *vbox2, *hbox, *frame, *parameters; - GtkWidget *eventWidget[EVENT_COUNT]; - EMessageBoxReturn ret; - int i, loop = 1; - GSList *eventTypeRadio = NULL; -// char buf[128]; - - if( !GetCurrentCam() ) - return TRUE; - - // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Add Event" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( dialog_delete_callback ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pCameraInspectorWnd ) ); - - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - - gtk_widget_realize (window); - - // fill the window - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show( vbox ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - frame = gtk_frame_new( "Type" ); - gtk_box_pack_start( GTK_BOX( hbox ), frame, TRUE, TRUE, 0 ); - gtk_widget_show( frame ); - - vbox2 = gtk_vbox_new( FALSE, 5 ); - gtk_container_add( GTK_CONTAINER( frame ), vbox2 ); - gtk_container_set_border_width( GTK_CONTAINER (vbox2), 5 ); - gtk_widget_show( vbox2 ); - - // -------------------------- // - - for( i = 1; i < EVENT_COUNT; i++ ) { - eventWidget[i] = gtk_radio_button_new_with_label( eventTypeRadio, camEventStr[i] ); - gtk_box_pack_start( GTK_BOX( vbox2 ), eventWidget[i], FALSE, FALSE, 3 ); - gtk_widget_show( eventWidget[i] ); - eventTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( eventWidget[i] ) ); - if( camEventFlags[i][1] == false ) - gtk_widget_set_sensitive (eventWidget[i], FALSE); - } - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Parameters:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - parameters = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), parameters, TRUE, TRUE, 0 ); - gtk_widget_show( parameters ); - - // -------------------------- // - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDOK)); - gtk_widget_show (w); - - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (eIDCANCEL)); - gtk_widget_show (w); - ret = eIDCANCEL; - - // -------------------------- // - - gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER); - gtk_widget_show (window); - gtk_grab_add (window); - - bool dialogError = TRUE; - while (dialogError) { - loop = 1; - while (loop) - gtk_main_iteration (); - - dialogError = FALSE; - - if( ret == eIDOK ) { - const char *str = gtk_entry_get_text( GTK_ENTRY(parameters) ); - - if( !camEventFlags[i][0] || ( str && str[0] ) ) { - int type = 0; -// GList *li; - - for( type = 1; type < EVENT_COUNT; type++ ) { - if( gtk_toggle_button_get_active( (GtkToggleButton*)eventWidget[type] ) ) - break; - } - - // Add the event - GetCurrentCam()->GetCam()->addEvent( static_cast(type), str, (long)(g_pTimeLine->value) ); - - // Refresh event list - RefreshEventList(); - } else { - dialogError = TRUE; - } - } - } - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return TRUE; -} - -static gint ci_del( GtkWidget *widget, gpointer data ) -{ - // TODO: add support to splines lib - if( GetCurrentCam() && GTK_CLIST(g_pEventsList)->focus_row >= 0 ) { - GetCurrentCam()->GetCam()->removeEvent( GTK_CLIST(g_pEventsList)->focus_row ); - // Refresh event list - RefreshEventList(); - } - - return TRUE; -} - -static gint ci_timeline_changed( GtkAdjustment *adjustment ) -{ - char buf[128]; - - sprintf( buf, "%.2f", adjustment->value / 1000.f ); - gtk_label_set_text( g_pCurrentTime, buf ); - - // FIXME: this will never work completely perfect. Startcamera calls buildcamera, which sets all events to 'nottriggered'. - // So if you have a wait at the end of the path, this will go to nontriggered immediately when you go over it and the camera - // will have no idea where on the track it should be. - if( GetCurrentCam() && gtk_toggle_button_get_active( GTK_TOGGLE_BUTTON(g_pTrackCamera) ) ) { - float fov; - vec3_t origin = { 0.0f, 0.0f, 0.0f }, dir = { 0.0f, 0.0f, 0.0f}, angles; - - GetCurrentCam()->GetCam()->startCamera( 0 ); - - GetCurrentCam()->GetCam()->getCameraInfo( (long)(adjustment->value), &origin[0], &dir[0], &fov ); - VectorSet( angles, asin (dir[2])*180/3.14159, atan2 (dir[1], dir[0])*180/3.14159, 0 ); - g_CameraTable.m_pfnSetCamera( origin, angles ); - } - - return TRUE; -} - -GtkWidget *CreateCameraInspectorDialog( void ) -{ - GtkWidget *window, *w, *vbox, *hbox, *table, *frame; - - // create the window - window = gtk_window_new( GTK_WINDOW_TOPLEVEL ); - gtk_window_set_title( GTK_WINDOW (window), "Camera Inspector" ); - gtk_signal_connect( GTK_OBJECT (window), "delete_event", GTK_SIGNAL_FUNC( ci_close ), NULL ); - gtk_signal_connect( GTK_OBJECT (window), "expose_event", GTK_SIGNAL_FUNC( ci_expose ), NULL ); - // gtk_signal_connect( GTK_OBJECT (window), "destroy", GTK_SIGNAL_FUNC( gtk_widget_destroy ), NULL ); - gtk_window_set_transient_for( GTK_WINDOW( window ), GTK_WINDOW( g_pRadiantWnd ) ); - - // don't use show, as you don't want to have it displayed on startup ;-) - gtk_widget_realize( window ); - - // fill the window - - // the table - // -------------------------- // - - table = gtk_table_new( 3, 2, FALSE ); - gtk_widget_show( table ); - gtk_container_add( GTK_CONTAINER( window ), table ); - gtk_container_set_border_width( GTK_CONTAINER( table ), 5 ); - gtk_table_set_row_spacings( GTK_TABLE( table ), 5 ); - gtk_table_set_col_spacings( GTK_TABLE( table ), 5 ); - - // the properties column - // -------------------------- // - - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "File:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - g_pCamListCombo = gtk_combo_new(); - gtk_box_pack_start (GTK_BOX( hbox ), g_pCamListCombo, TRUE, TRUE, 0); - gtk_widget_show( g_pCamListCombo ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Name:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - g_pCamName = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), g_pCamName, FALSE, FALSE, 0 ); - gtk_widget_show( g_pCamName ); - - w = gtk_label_new( "Type: " ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - w = gtk_label_new( "" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - g_pCamType = GTK_LABEL( w ); - - RefreshCamListCombo(); - - gtk_entry_set_editable( GTK_ENTRY( GTK_COMBO(g_pCamListCombo)->entry ), FALSE ); - gtk_signal_connect( GTK_OBJECT(GTK_COMBO(g_pCamListCombo)->entry), "changed", GTK_SIGNAL_FUNC( ci_camlist_changed ), NULL ); - - // -------------------------- // - - frame = gtk_frame_new( "Path and Target editing" ); - gtk_widget_show( frame ); - gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); - - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add( GTK_CONTAINER( frame ), vbox ); - gtk_container_set_border_width( GTK_CONTAINER (vbox), 5 ); - gtk_widget_show( vbox ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Edit:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - g_pPathListCombo = gtk_combo_new(); - gtk_box_pack_start (GTK_BOX( hbox ), g_pPathListCombo, TRUE, TRUE, 0); - gtk_widget_show( g_pPathListCombo ); - - RefreshPathListCombo(); - - gtk_entry_set_editable( GTK_ENTRY( GTK_COMBO(g_pPathListCombo)->entry ), FALSE ); - gtk_signal_connect( GTK_OBJECT(GTK_COMBO(g_pPathListCombo)->entry), "changed", GTK_SIGNAL_FUNC( ci_pathlist_changed ), NULL ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - g_pEditModeEditRadioButton = gtk_radio_button_new_with_label( g_pEditTypeRadio, "Edit Points" ); - gtk_box_pack_start( GTK_BOX( hbox ), g_pEditModeEditRadioButton, FALSE, FALSE, 3 ); - gtk_widget_show( g_pEditModeEditRadioButton ); - g_pEditTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( g_pEditModeEditRadioButton ) ); - - gtk_signal_connect( GTK_OBJECT( g_pEditModeEditRadioButton ), "clicked", GTK_SIGNAL_FUNC( ci_editmode_edit ), NULL ); - - g_pEditModeAddRadioButton = gtk_radio_button_new_with_label( g_pEditTypeRadio, "Add Points" ); - gtk_box_pack_start( GTK_BOX( hbox ), g_pEditModeAddRadioButton, FALSE, FALSE, 3 ); - gtk_widget_show( g_pEditModeAddRadioButton ); - g_pEditTypeRadio = gtk_radio_button_group( GTK_RADIO_BUTTON( g_pEditModeAddRadioButton ) ); - - gtk_signal_connect( GTK_OBJECT( g_pEditModeAddRadioButton ), "clicked", GTK_SIGNAL_FUNC( ci_editmode_add ), NULL ); - - // see if we should use a different default - if( g_iEditMode == 1 ) { - // Go to editmode Add - gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(g_pEditModeAddRadioButton), TRUE ); - } - - w = gtk_label_new( "Type: " ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - w = gtk_label_new( "" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - g_pPathType = GTK_LABEL( w ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label( "Rename..." ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_rename ), NULL ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Add Target..." ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_add_target ), NULL ); - gtk_widget_show( w ); - - // not available in splines library - /*w = gtk_button_new_with_label( "Delete Selected" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_delete_selected ), NULL ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Select All" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, TRUE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_select_all ), NULL ); - gtk_widget_show( w );*/ - - // -------------------------- // - - frame = gtk_frame_new( "Time" ); - gtk_widget_show( frame ); - gtk_table_attach( GTK_TABLE( table ), frame, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); - - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_container_add( GTK_CONTAINER( frame ), vbox ); - gtk_container_set_border_width( GTK_CONTAINER (vbox), 5 ); - gtk_widget_show( vbox ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Length (seconds):" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - g_pSecondsEntry = gtk_entry_new(); - gtk_box_pack_start( GTK_BOX( hbox ), g_pSecondsEntry, FALSE, FALSE, 0 ); - gtk_widget_show( g_pSecondsEntry ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Current Time: " ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - w = gtk_label_new( "0.00" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - g_pCurrentTime = GTK_LABEL( w ); - - w = gtk_label_new( " of " ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - w = gtk_label_new( "0.00" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - g_pTotalTime = GTK_LABEL( w ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - g_pTimeLine = GTK_ADJUSTMENT( gtk_adjustment_new( 0, 0, 30000, 100, 250, 0 ) ); - gtk_signal_connect( GTK_OBJECT(g_pTimeLine), "value_changed", GTK_SIGNAL_FUNC( ci_timeline_changed ), NULL ); - w = gtk_hscale_new( g_pTimeLine ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_widget_show( w ); - gtk_scale_set_draw_value( GTK_SCALE( w ), FALSE ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - g_pTrackCamera = gtk_check_button_new_with_label( "Track Camera" ); - gtk_box_pack_start( GTK_BOX( hbox ), g_pTrackCamera, FALSE, FALSE, 0 ); - gtk_widget_show( g_pTrackCamera ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_label_new( "Events:" ); - gtk_box_pack_start( GTK_BOX( hbox ), w, FALSE, FALSE, 0 ); - gtk_widget_show( w ); - - // -------------------------- // - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, FALSE, FALSE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_scrolled_window_new( NULL, NULL ); - gtk_widget_set_usize( w, 0, 150 ); - gtk_scrolled_window_set_policy( GTK_SCROLLED_WINDOW( w ), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC ); - gtk_box_pack_start( GTK_BOX( hbox ), w, TRUE, TRUE, 0 ); - gtk_widget_show( w ); - - g_pEventsList = gtk_clist_new( 3 ); - gtk_container_add( GTK_CONTAINER(w), g_pEventsList); - //gtk_signal_connect( GTK_OBJECT(g_pEventsList), "select_row", GTK_SIGNAL_FUNC (proplist_select_row), NULL); - gtk_clist_set_selection_mode( GTK_CLIST(g_pEventsList), GTK_SELECTION_BROWSE ); - gtk_clist_column_titles_hide( GTK_CLIST(g_pEventsList) ); - gtk_clist_set_column_auto_resize( GTK_CLIST(g_pEventsList), 0, TRUE ); - gtk_clist_set_column_auto_resize( GTK_CLIST(g_pEventsList), 1, TRUE ); - gtk_clist_set_column_auto_resize( GTK_CLIST(g_pEventsList), 2, TRUE ); - gtk_widget_show( g_pEventsList ); - - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( hbox ), vbox, FALSE, FALSE, 0 ); - gtk_widget_show( vbox ); - - w = gtk_button_new_with_label( "Add..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_add ), NULL ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Del" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_del ), NULL ); - gtk_widget_show( w ); - - // -------------------------- // - - /*/ - | - | - | - */ - - // the buttons column - // -------------------------- // - - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); - - w = gtk_button_new_with_label( "New..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_new ), NULL ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Load..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_load ), NULL ); - gtk_widget_show( w ); - - // -------------------------- // - - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); - - w = gtk_button_new_with_label( "Save..." ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_save ), NULL ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Unload" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_unload ), NULL ); - gtk_widget_show( w ); - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, TRUE, TRUE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label( "Apply" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_apply ), NULL ); - gtk_widget_show( w ); - - w = gtk_button_new_with_label( "Preview" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_preview ), NULL ); - gtk_widget_show( w ); - - // -------------------------- // - - vbox = gtk_vbox_new( FALSE, 5 ); - gtk_widget_show( vbox ); - gtk_table_attach( GTK_TABLE( table ), vbox, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0 ); - - hbox = gtk_hbox_new( FALSE, 5 ); - gtk_box_pack_start( GTK_BOX( vbox ), hbox, TRUE, TRUE, 0 ); - gtk_widget_show( hbox ); - - w = gtk_button_new_with_label( "Close" ); - gtk_box_pack_start( GTK_BOX( vbox ), w, FALSE, FALSE, 0); - gtk_signal_connect( GTK_OBJECT( w ), "clicked", GTK_SIGNAL_FUNC( ci_close ), NULL ); - GTK_WIDGET_SET_FLAGS( w, GTK_CAN_DEFAULT ); - gtk_widget_grab_default( w ); - gtk_widget_show( w ); - - // -------------------------- // - - return window; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs.h b/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs.h deleted file mode 100644 index 4df27eae..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -struct TwinWidget { - GtkWidget* one; - GtkWidget* two; -}; - -void dialog_button_callback (GtkWidget *widget, gpointer data); -gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data); -//void dialog_button_callback_settex (GtkWidget *widget, gpointer data); - -void RefreshCamListCombo( void ); -GtkWidget *CreateCameraInspectorDialog( void ); diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs_common.cpp b/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs_common.cpp deleted file mode 100644 index 43a4e70e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/dialogs_common.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#include "camera.h" - -void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); - - *loop = 0; - *ret = gpointer_to_int (data); -} - -gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; - - return TRUE; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/funchandlers.cpp b/misc/mediasource/extra/netradiant-src/contrib/camera/funchandlers.cpp deleted file mode 100644 index 2e9d17bb..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/funchandlers.cpp +++ /dev/null @@ -1,271 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#include "camera.h" - -extern GtkWidget *g_pEditModeAddRadioButton; - -char* Q_realpath(const char *path, char *resolved_path, size_t size) -{ -#if defined(POSIX) - return realpath(path, resolved_path); -#elif defined(WIN32) - return _fullpath(resolved_path, path, size); -#else -#error "unsupported platform" -#endif -} - -static void DoNewCamera( idCameraPosition::positionType type ) -{ - CCamera *cam = AllocCam(); - - if( cam ) { - char buf[128]; - sprintf( buf, "camera%i", cam->GetCamNum() ); - - cam->GetCam()->startNewCamera( type ); - cam->GetCam()->setName( buf ); - cam->GetCam()->buildCamera(); - - sprintf( buf, "Unsaved Camera %i", cam->GetCamNum() ); - cam->SetFileName( buf, false ); - - SetCurrentCam( cam ); - RefreshCamListCombo(); - - // Go to editmode Add - gtk_toggle_button_set_active( GTK_TOGGLE_BUTTON(g_pEditModeAddRadioButton), TRUE ); - - // Show the camera inspector - DoCameraInspector(); - - // Start edit mode (if not initiated by DoCameraInspector) - if( !g_bEditOn ) - DoStartEdit( GetCurrentCam() ); - } else { - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "No free cameras available.", "Create Camera Error", eMB_OK ); - } -} - -void DoNewFixedCamera() -{ - DoNewCamera( idCameraPosition::FIXED ); -} - -void DoNewInterpolatedCamera() -{ - DoNewCamera( idCameraPosition::INTERPOLATED ); -} - -void DoNewSplineCamera() -{ - DoNewCamera( idCameraPosition::SPLINE ); -} - -void DoCameraInspector() -{ - gtk_widget_show( g_pCameraInspectorWnd ); -} - -void DoPreviewCamera() -{ - if( GetCurrentCam() ) { - g_iPreviewRunning = 1; - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } -} - -void DoLoadCamera() -{ - char basepath[PATH_MAX]; - - if( firstCam && firstCam->HasBeenSaved() ) - ExtractFilePath( firstCam->GetFileName(), basepath ); - else - strcpy( basepath, g_FuncTable.m_pfnGetGamePath() ); - - const gchar *filename = g_FuncTable.m_pfnFileDialog( (GtkWidget *)g_pRadiantWnd, TRUE, "Open Camera File", basepath, "camera"); - - if( filename ) - { - CCamera *cam = AllocCam(); - char fullpathtofile[PATH_MAX]; - - if( cam ) { - Q_realpath(filename, fullpathtofile, PATH_MAX); - - // see if this camera file was already loaded - CCamera *checkCam = firstCam->GetNext(); // not the first one as we just allocated it - while( checkCam ) { - if( !strcmp( fullpathtofile, checkCam->GetFileName() ) ) { - char error[PATH_MAX+64]; - FreeCam( cam ); - sprintf( error, "Camera file \'%s\' is already loaded", fullpathtofile ); - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Load error", eMB_OK ); - //g_free( filename ); - return; - } - checkCam = checkCam->GetNext(); - } - - if( loadCamera( cam->GetCamNum(), fullpathtofile ) ) { - cam->GetCam()->buildCamera(); - cam->SetFileName( filename, true ); - SetCurrentCam( cam ); - RefreshCamListCombo(); - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } else { - char error[PATH_MAX+64]; - FreeCam( cam ); - sprintf( error, "An error occured during the loading of \'%s\'", fullpathtofile ); - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Load error", eMB_OK ); - } - - //g_free( filename ); - } else { - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "No free camera slots available", "Load error", eMB_OK ); - } - } -} - -void DoSaveCamera() { - char basepath[PATH_MAX]; - - if( !GetCurrentCam() ) - return; - - if( GetCurrentCam()->GetFileName()[0] ) - ExtractFilePath( GetCurrentCam()->GetFileName(), basepath ); - else - strcpy( basepath, g_FuncTable.m_pfnGetGamePath() ); - - const gchar *filename = g_FuncTable.m_pfnFileDialog( g_pRadiantWnd, FALSE, "Save Camera File", basepath, "camera"); - - if( filename ) { - char fullpathtofile[PATH_MAX + 8]; - - Q_realpath(filename, fullpathtofile, PATH_MAX); - - // File dialog from windows (and maybe the gtk one from radiant) doesn't handle default extensions properly. - // Add extension and check again if file exists - if( strcmp( fullpathtofile + (strlen(fullpathtofile) - 7), ".camera" ) ) { - strcat( fullpathtofile, ".camera" ); - - if( FileExists( fullpathtofile ) ) { - if( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, "File already exists.\nOverwrite?", "Save Camera File", eMB_YESNO ) == eIDNO ) - return; - } - } - - // see if this camera file was already loaded - CCamera *checkCam = firstCam; - while( checkCam ) { - if( checkCam == GetCurrentCam() ) { - checkCam = checkCam->GetNext(); - if( !checkCam ) // we only have one camera file opened so no need to check further - break; - } else if( !strcmp( fullpathtofile, checkCam->GetFileName() ) ) { - char error[PATH_MAX+64]; - sprintf( error, "Camera file \'%s\' is currently loaded by NetRadiant.\nPlease select a different filename.", fullpathtofile ); - g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, error, "Save error", eMB_OK ); - return; - } - checkCam = checkCam->GetNext(); - } - - // FIXME: check for existing directory - - GetCurrentCam()->GetCam()->save( fullpathtofile ); - GetCurrentCam()->SetFileName( fullpathtofile, true ); - RefreshCamListCombo(); - } -} - -void DoUnloadCamera() { - if( !GetCurrentCam() ) - return; - - if( !GetCurrentCam()->HasBeenSaved() ) { - char buf[PATH_MAX+64]; - sprintf( buf, "Do you want to save the changes for camera '%s'?", GetCurrentCam()->GetCam()->getName() ); - if( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, buf, "Warning", eMB_YESNO ) == eIDYES ) - DoSaveCamera(); - } else if( GetCurrentCam()->HasBeenSaved() == 2 ) { - char buf[PATH_MAX+64]; - sprintf( buf, "Do you want to save the changes made to camera file '%s'?", GetCurrentCam()->GetFileName() ); - if( g_FuncTable.m_pfnMessageBox( (GtkWidget *)g_pRadiantWnd, buf, "Warning", eMB_YESNO ) == eIDYES ) - DoSaveCamera(); - } - - if( g_pCurrentEditCam ) { - DoStopEdit(); - g_pCurrentEditCam = NULL; - } - - FreeCam( GetCurrentCam() ); - SetCurrentCam( NULL ); - RefreshCamListCombo(); -} - -CCamera *g_pCurrentEditCam = NULL; - -void DoStartEdit( CCamera *cam ) { - if( g_pCurrentEditCam ) { - DoStopEdit(); - g_pCurrentEditCam = NULL; - } - - if( cam ) { - g_bEditOn = true; - - if( !Listener ) - Listener = new CListener; - - cam->GetCam()->startEdit( g_iActiveTarget < 0 ? true : false ); - - g_pCurrentEditCam = cam; - - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } -} - -void DoStopEdit( void ) { - g_bEditOn = false; - - if( Listener ) { - delete Listener; - Listener = NULL; - } - - if( g_pCurrentEditCam ) { - // stop editing on the current cam - g_pCurrentEditCam->GetCam()->stopEdit(); - g_pCurrentEditCam = NULL; - - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/funchandlers.h b/misc/mediasource/extra/netradiant-src/contrib/camera/funchandlers.h deleted file mode 100644 index 0c97f610..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/funchandlers.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -void DoNewFixedCamera(); -void DoNewInterpolatedCamera(); -void DoNewSplineCamera(); -void DoCameraInspector(); -void DoPreviewCamera(); -void DoLoadCamera(); -void DoSaveCamera(); -void DoUnloadCamera(); -void DoStartEdit( CCamera *cam ); -void DoStopEdit( void ); - diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/listener.cpp b/misc/mediasource/extra/netradiant-src/contrib/camera/listener.cpp deleted file mode 100644 index f3169b8d..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/listener.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#include "camera.h" - -CListener::CListener() -{ - refCount = 1; - - m_bHooked = FALSE; - - m_bLeftMBPressed = m_bRightMBPressed = m_bMiddleMBPressed = false; - - oldValid = false; - - Register(); -} - -CListener::~CListener() -{ - UnRegister(); -} - -void CListener::Register() -{ - g_UITable.m_pfnHookWindow( this ); - g_pXYWndWrapper = g_UITable.m_pfnGetXYWndWrapper(); - m_bHooked = TRUE; -} - -void CListener::UnRegister() -{ - if(m_bHooked) - { - g_UITable.m_pfnUnHookWindow( this ); - g_pXYWndWrapper= NULL; - m_bHooked = FALSE; - } -} - -bool CListener::OnMouseMove( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - if( m_bLeftMBPressed && oldValid && g_iEditMode == 0 ) { - vec3_t click, delta; - - g_pXYWndWrapper->SnapToGrid( (int)x, (int)y, click ); - - switch( m_vt ) { - case XY: - VectorSet( delta, click[0] - old_x, click[1] - old_y, 0 ); - old_x = click[0]; old_y = click[1]; - break; - case XZ: - VectorSet( delta, click[0] - old_x, 0, click[2] - old_y ); - old_x = click[0]; old_y = click[2]; - break; - case YZ: - VectorSet( delta, 0, click[1] - old_x, click[2] - old_y ); - old_x = click[1]; old_y = click[2]; - break; - } - - if( g_iActiveTarget < 0 ) - GetCurrentCam()->GetCam()->getPositionObj()->updateSelection( delta[0], delta[1], delta[2] ); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->updateSelection( delta[0], delta[1], delta[2] ); - - GetCurrentCam()->HasBeenModified(); - - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - - return true; - } - - return false; -} - -bool CListener::OnLButtonDown( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - m_bLeftMBPressed = true; - oldValid = true; - - vec3_t org, delta; - - g_pXYWndWrapper->SnapToGrid( (int)x, (int)y, org ); - - switch( m_vt ) { - case XY: - old_x = org[0]; old_y = org[1]; org[2] = 64*1024; - VectorSet( delta, 0, 0, -1 ); - break; - case XZ: - old_x = org[0]; old_y = org[2]; org[1] = 64*1024; - VectorSet( delta, 0, -1, 0 ); - break; - case YZ: - old_x = org[1]; old_y = org[2]; org[0] = 64*1024; - VectorSet( delta, -1, 0, 0 ); - break; - } - - if( g_iEditMode == 0 ) { - if( g_iActiveTarget < 0 ) - GetCurrentCam()->GetCam()->getPositionObj()->selectPointByRay( org[0], org[1], org[2], delta[0], delta[1], delta[2], true ); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->selectPointByRay( org[0], org[1], org[2], delta[0], delta[1], delta[2], true ); - } else if( g_iEditMode == 1 ) { - idVec3 *lastcoord; - idCameraPosition *camera; - - if( g_iActiveTarget < 0 ) { - camera = GetCurrentCam()->GetCam()->getPositionObj(); - } else { - camera = GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget); - } - - if( camera->numPoints() ) { - lastcoord = camera->getPoint( camera->numPoints() -1 ); - switch( m_vt ) { - case XY: - camera->addPoint( org[0], org[1], lastcoord->z ); - break; - case XZ: - camera->addPoint( org[0], lastcoord->y, org[2] ); - break; - case YZ: - camera->addPoint( lastcoord->x, org[1], org[2] ); - break; - } - } else { - switch( m_vt ) { - case XY: - camera->addPoint( org[0], org[1], 0 ); - break; - case XZ: - camera->addPoint( org[0], 0, org[2] ); - break; - case YZ: - camera->addPoint( 0, org[1], org[2] ); - break; - } - } - - GetCurrentCam()->HasBeenModified(); - } - - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - - return true; - - //return false; -} - -bool CListener::OnLButtonUp( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - m_bLeftMBPressed = false; - oldValid = false; - - if( g_iEditMode == 0 ) { - if( g_iActiveTarget < 0 ) - GetCurrentCam()->GetCam()->getPositionObj()->deselectAll(); - else - GetCurrentCam()->GetCam()->getActiveTarget(g_iActiveTarget)->deselectAll(); - - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } - - return false; -} - -bool CListener::OnRButtonDown( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - m_bRightMBPressed = true; - - return false; -} - -bool CListener::OnRButtonUp( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - m_bRightMBPressed = false; - - return false; -} - -bool CListener::OnMButtonDown( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - m_bMiddleMBPressed = true; - - return false; -} - -bool CListener::OnMButtonUp( unsigned int nFlags, double x, double y ) -{ - SetViewType( g_pXYWndWrapper->GetViewType() ); - - m_bMiddleMBPressed = false; - - return false; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/listener.h b/misc/mediasource/extra/netradiant-src/contrib/camera/listener.h deleted file mode 100644 index 72bf1fdb..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/listener.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -class CListener : public IWindowListener -{ -public: - bool OnMouseMove(guint32 nFlags, gdouble x, gdouble y); - bool OnLButtonDown(guint32 nFlags, gdouble x, gdouble y); - bool OnMButtonDown(guint32 nFlags, gdouble x, gdouble y); - bool OnRButtonDown(guint32 nFlags, gdouble x, gdouble y); - bool OnLButtonUp(guint32 nFlags, gdouble x, gdouble y); - bool OnMButtonUp(guint32 nFlags, gdouble x, gdouble y); - bool OnRButtonUp(guint32 nFlags, gdouble x, gdouble y); - bool OnKeyPressed(char *s) { return false; } - bool Paint() { return true; } - void Close() { } - - void UnRegister(); - void Register(); - CListener(); - virtual ~CListener(); - - void IncRef() { refCount++; } - void DecRef() { refCount--; if (refCount <= 0) delete this; } - - void SetViewType( VIEWTYPE vt ) { if( m_vt != vt ) oldValid = false; m_vt = vt; } - -private: - IXYWndWrapper *g_pXYWndWrapper; - - bool m_bHooked; - int refCount; - VIEWTYPE m_vt; - - // mouse button status - bool m_bLeftMBPressed, m_bRightMBPressed, m_bMiddleMBPressed; - - // old mouse coordinates - bool oldValid; - gdouble old_x, old_y; -}; diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/misc.cpp b/misc/mediasource/extra/netradiant-src/contrib/camera/misc.cpp deleted file mode 100644 index 49148248..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/misc.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#include "camera.h" - -void Sys_ERROR( char* text, ... ) -{ - va_list argptr; - char buf[32768]; - - va_start (argptr,text); - vsprintf (buf, text,argptr); - va_end (argptr); - - Sys_Printf("Camera::ERROR->%s", buf); -} - -char* UnixToDosPath( char* path ) -{ -#ifndef WIN32 - return path; -#else - for(char* p = path; *p; p++) - { - if(*p == '/') - *p = '\\'; - } - return path; -#endif -} - -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; -} - -const char* ExtractFilename( const char* path ) -{ - char* p = strrchr(path, '/'); - if(!p) - { - p = strrchr(path, '\\'); - - if(!p) - return path; - } - return ++p; -} - -int Q_stricmp (const char *s1, const char *s2) { - return string_equal_nocase( s1, s2 ); -} - -/* -============== -FileExists -============== -*/ -bool FileExists (const char *filename) -{ - FILE *f; - - f = fopen( filename, "r" ); - if( !f ) - return false; - fclose( f ); - return true; -} - -// -// command buffer -// empty wrappers, don't really use them here -// -void Cbuf_AddText( const char *text ) {}; -void Cbuf_Execute (void) {}; - -// -// Common -// - -void CDECL Com_Error( int level, const char *error, ... ) -{ - va_list argptr; - char buf[32768]; - - va_start (argptr,error); - vsprintf (buf, error,argptr); - va_end (argptr); - - Sys_Printf("Camera::ERROR->%s", buf); -} - -void CDECL Com_Printf( const char* msg, ... ) -{ - va_list argptr; - char buf[32768]; - - va_start (argptr,msg); - vsprintf (buf, msg,argptr); - va_end (argptr); - - Sys_Printf("Camera::%s", buf); -} - -void CDECL Com_DPrintf( const char* msg, ... ) -{ -#ifdef _DEBUG - va_list argptr; - char buf[32768]; - - va_start (argptr,msg); - vsprintf (buf, msg,argptr); - va_end (argptr); - - Sys_Printf("Camera::%s", buf); -#endif -} - -void *Com_Allocate( int bytes ) { - return( malloc( bytes ) ); -} - -void Com_Dealloc( void *ptr ) { - free( ptr ); -} - -// -// Filesystem -// - -#ifdef WIN32 - #pragma warning(disable : 4311) - #pragma warning(disable : 4312) -#endif - -int FS_Read( void *buffer, int len, fileHandle_t f ) { - return fread( buffer, len, 1, (FILE *)f ); -} - -int FS_Write( const void *buffer, int len, fileHandle_t h ) { - return fwrite( buffer, len, 1, (FILE *)h ); -} - -int FS_ReadFile( const char *qpath, void **buffer ) { - fileHandle_t h; - byte* buf; - int len; - - buf = NULL; - - len = FS_FOpenFileRead( qpath, &h, qfalse ); - - if( h == 0 ) { - if ( buffer ) { - *buffer = NULL; - } - - return -1; - } - - buf = (byte *)Com_Allocate( len + 1 ); - - *buffer = buf; - - FS_Read (buf, len, h); - - buf[len] = 0; - FS_FCloseFile( h ); - - return len; -} - -void FS_FreeFile( void *buffer ) { - Com_Dealloc( buffer ); -} - -int FS_FOpenFileRead( const char *filename, fileHandle_t *file, bool uniqueFILE ) { - FILE *fh; - long len; - - fh = fopen( filename, "rb" ); - *file = *(fileHandle_t *)&fh; - - if( file ) - { - fseek (fh, 0, SEEK_END); - len = ftell (fh); - rewind (fh); - return len; - } - else - return -1; -} - -fileHandle_t FS_FOpenFileWrite( const char *filename ) { - FILE *fh; - fileHandle_t f; - - memset( &f, 0, sizeof(f) ); - - fh = fopen( filename, "wb" ); - - f = (fileHandle_t)fh; - return f; -} - -void FS_FCloseFile( fileHandle_t f ) { - fclose( (FILE *)f ); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/misc.h b/misc/mediasource/extra/netradiant-src/contrib/camera/misc.h deleted file mode 100644 index 913b7c4a..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/misc.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -void Sys_ERROR( char* text, ... ); -char* UnixToDosPath( char* path ); -void ExtractFilePath( const char *path, char *dest ); -const char* ExtractFilename( const char* path ); -bool FileExists (const char *filename); -int Q_stricmp (const char *s1, const char *s2); - -typedef int fileHandle_t; - -extern "C" { -// command buffer -void Cbuf_AddText( const char *text ); -void Cbuf_Execute (void); - -// common -#ifndef CDECL -#ifdef WIN32 - #define CDECL __cdecl -#else - #define CDECL -#endif -#endif - -void CDECL Com_Error( int level, const char *error, ... ); -void CDECL Com_Printf( const char *msg, ... ); -void CDECL Com_DPrintf( const char *msg, ... ); -void *Com_Allocate( int bytes ); -void Com_Dealloc( void *ptr ); - -// filesystem -int FS_Read( void *buffer, int len, fileHandle_t f ); -int FS_Write( const void *buffer, int len, fileHandle_t h ); -int FS_ReadFile( const char *qpath, void **buffer ); -void FS_FreeFile( void *buffer ); -int FS_FOpenFileRead( const char *filename, fileHandle_t *file, bool uniqueFILE ); -fileHandle_t FS_FOpenFileWrite( const char *filename ); -void FS_FCloseFile( fileHandle_t f ); -} - -// vectors -#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 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];} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/renderer.cpp b/misc/mediasource/extra/netradiant-src/contrib/camera/renderer.cpp deleted file mode 100644 index 08e6664e..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/renderer.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -#include "camera.h" - -CRenderer::CRenderer() { - - refCount = 1; - - m_bHooked = FALSE; - - Register(); - Initialize(); -} - -CRenderer::~CRenderer() { - if( m_bHooked ) - UnRegister(); -} - -void CRenderer::Register() { - g_QglTable.m_pfnHookGL2DWindow( this ); - g_QglTable.m_pfnHookGL3DWindow( this ); - m_bHooked = TRUE; -} - -void CRenderer::UnRegister() { - if( g_QglTable.m_nSize ) { - g_QglTable.m_pfnUnHookGL2DWindow( this ); - g_QglTable.m_pfnUnHookGL3DWindow( this ); - } - m_bHooked = FALSE; -} - -void CRenderer::Initialize() { - -} - -void CRenderer::Draw2D( VIEWTYPE vt ) { - - g_QglTable.m_pfn_qglPushAttrib(GL_ALL_ATTRIB_BITS); - g_QglTable.m_pfn_qglPushMatrix(); - - switch(vt) - { - case XY: - break; - case XZ: - g_QglTable.m_pfn_qglRotatef(270.0f, 1.0f, 0.0f, 0.0f); - break; - case YZ: - g_QglTable.m_pfn_qglRotatef(270.0f, 1.0f, 0.0f, 0.0f); - g_QglTable.m_pfn_qglRotatef(270.0f, 0.0f, 0.0f, 1.0f); - break; - } - - CCamera *cam = firstCam; - while( cam ) { - cam->GetCam()->draw( ((Listener && cam == g_pCurrentEditCam) ? true : false) ); - cam = cam->GetNext(); - } - - g_QglTable.m_pfn_qglPopMatrix(); - g_QglTable.m_pfn_qglPopAttrib(); -} - -void CRenderer::Draw3D() { - // FIXME: really need a mainloop callback from the editor core - static long start; - static float cycle; - static long msecs; - static long current; - - if( g_iPreviewRunning ) { - if( g_iPreviewRunning == 1 ) { - start = Q_QGetTickCount(); - GetCurrentCam()->GetCam()->startCamera( start ); - cycle = GetCurrentCam()->GetCam()->getTotalTime(); - msecs = (long)(cycle * 1000); - current = start; - g_iPreviewRunning = 2; - } - - if( current < start + msecs ) { - float fov; - vec3_t origin = {0.0f, 0.0f, 0.0f}, dir = {0.0f, 0.0f, 0.0f}, angles; - - GetCurrentCam()->GetCam()->getCameraInfo( current, &origin[0], &dir[0], &fov ); - VectorSet( angles, asin (dir[2])*180/3.14159, atan2 (dir[1], dir[0])*180/3.14159, 0 ); - g_CameraTable.m_pfnSetCamera( origin, angles ); - current = Q_QGetTickCount(); - } else { - g_iPreviewRunning = 0; - GetCurrentCam()->GetCam()->setRunning( false ); - g_FuncTable.m_pfnSysUpdateWindows( W_XY_OVERLAY | W_CAMERA ); - } - } - - g_QglTable.m_pfn_qglPushAttrib(GL_ALL_ATTRIB_BITS); - - CCamera *cam = firstCam; - while( cam ) { - cam->GetCam()->draw( ((Listener && cam == g_pCurrentEditCam) ? true : false) ); - cam = cam->GetNext(); - } - - if( g_iPreviewRunning ) { - int x, y, width, height, i; - float degInRad; - - g_CameraTable.m_pfnGetCamWindowExtents( &x, &y, &width, &height ); - - // setup orthographic projection mode - g_QglTable.m_pfn_qglMatrixMode(GL_PROJECTION); - g_QglTable.m_pfn_qglLoadIdentity(); - g_QglTable.m_pfn_qglDisable( GL_DEPTH_TEST ); - g_QglTable.m_pfn_qglOrtho( 0, (float)width, 0, (float)height, -100, 100 ); - g_QglTable.m_pfn_qglMatrixMode( GL_MODELVIEW ); - - g_QglTable.m_pfn_qglLoadIdentity(); - g_QglTable.m_pfn_qglColor3f( 1.f, 1.f, 1.f ); - g_QglTable.m_pfn_qglBegin( GL_LINE_LOOP ); - g_QglTable.m_pfn_qglVertex2f( 10, 10 ); - g_QglTable.m_pfn_qglVertex2f( 40, 10 ); - g_QglTable.m_pfn_qglVertex2f( 40, 25 ); - g_QglTable.m_pfn_qglVertex2f( 10, 25 ); - g_QglTable.m_pfn_qglEnd(); - - g_QglTable.m_pfn_qglBegin( GL_LINE_LOOP ); - for( i = 0; i < 360; i += 60 ) { - degInRad = i * (3.14159265358979323846/180.f); - g_QglTable.m_pfn_qglVertex2f( 18 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); - } - g_QglTable.m_pfn_qglEnd(); - - degInRad = (360-((current - start) % 360)) * (3.14159265358979323846/180.f); - g_QglTable.m_pfn_qglBegin( GL_LINES ); - g_QglTable.m_pfn_qglVertex2f( 18, 18 ); - g_QglTable.m_pfn_qglVertex2f( 18 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); - g_QglTable.m_pfn_qglVertex2f( 32, 18 ); - g_QglTable.m_pfn_qglVertex2f( 32 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); - g_QglTable.m_pfn_qglEnd(); - - g_QglTable.m_pfn_qglBegin( GL_LINE_LOOP ); - for( i = 0; i < 360; i += 60 ) { - degInRad = i * (3.14159265358979323846/180.f); - g_QglTable.m_pfn_qglVertex2f( 32 + cos(degInRad) * 5, 18 + sin(degInRad) * 5 ); - } - g_QglTable.m_pfn_qglEnd(); - - g_QglTable.m_pfn_qglBegin( GL_LINES ); - g_QglTable.m_pfn_qglVertex2f( 40, 22 ); - g_QglTable.m_pfn_qglVertex2f( 52, 31 ); - g_QglTable.m_pfn_qglVertex2f( 40, 13 ); - g_QglTable.m_pfn_qglVertex2f( 52, 4 ); - g_QglTable.m_pfn_qglEnd(); - } - - g_QglTable.m_pfn_qglPopAttrib(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/camera/renderer.h b/misc/mediasource/extra/netradiant-src/contrib/camera/renderer.h deleted file mode 100644 index c73d84d4..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/camera/renderer.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -Camera plugin for GtkRadiant -Copyright (C) 2002 Splash Damage Ltd. -*/ - -class CRenderer : public IGL2DWindow, public IGL3DWindow { -public: - CRenderer(); - virtual ~CRenderer(); - -protected: - int refCount; - -public: - void Register(); - void UnRegister(); - void Initialize(); - void Draw2D( VIEWTYPE vt ); - void Draw3D(); - - void IncRef() { refCount++; } - void DecRef() { refCount--; if (refCount <= 0) delete this; } - - bool m_bHooked; -}; diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/CHANGES b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/CHANGES deleted file mode 100644 index 51510b6c..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/CHANGES +++ /dev/null @@ -1,73 +0,0 @@ -05/14/2001 - ^Fishman -=============== -bitmap.cpp -Added Hydra's snap to grid code. -=============== -dec.cpp -Modified to support the new max size for the maps(Q3 1.27). -=============== -face.cpp -Modified to support the new max size for the maps(Q3 1.27). -=============== -font.cpp -Changed the fonts color to green, part of the new theme. -=============== -gendlgs.cpp -Added a label and textbox for the snap to grid feature. -Added a checkbox for adding terrain key to func_group. -Added a checkbox for antialiased lines in the preview window. -Modified a textbox to support the new max size for the maps(Q3 1.27). -Modified the About dialog. -=============== -genmap.cpp -Modified to support the new max size for the maps(Q3 1.27). -Added code for adding terrain key to func_group. -=============== -gensurf.cpp -Added code to save the settings of the antialiasing checkbox status and the terrain key checkbox status. -Modified version number. -=============== -view.cpp -Modified code for the new Green/Black theme. -Added code to antialiase lines in the preview window - -12/18/2000 - MrHyde -=============== -bitmap.cpp -Corrected a substitution error that would prevent code from reading a selected bitmap on the first pass, and possibly leave the bitmap file open. -Checks to ensure that main window has been created before updating the preview (which might be done if a bitmap filename was saved to ini file). Previous failure to do this resulted in Radiant console error messages. -=============== -gendlgs.cpp -One tooltip was goofed up ("preview" instead of "main_preview"), resulting in "invalid cast from (NULL) pointer to GtkObject" in Radiant console. -Tooltips - oops. Use wave_radios[] rather than string constants. -Moved check for game type from SetDlgValues to GenSurfInit in gensurf.cpp. Since the game type presumably won't change while GenSurf is active this only needs to be checked once (and if it IS possible to change the game while GenSurf is active then quite a bit more needs to be changed). -Worked around strange bug in SetDlgValues. In release dll (not debug), the 2nd pass through the set_sensitive loop for game_radios crashed. Since the state of those radio buttons won't ever change during a single session, the state is only set once now. Sure would like to know what's going on there, though. -=============== -view.cpp -Elevation and azimuth labels are right-justified. - -TODO: -Check out Fix Points on Voodoo2 again. Previous attempt caused entire preview to be redrawn when moving mouse (GL_SCISSOR_TEST failed?) - -12/17/2000 - MrHyde -- tooltips -- reformatted the source to use spaces instead of tabs -- fixes to update mechanism in bitmap tab - -12/13/2000 - MrHyde -=============== -gendlgs.cpp -In ReadDlgValues, reads wavelength, amplitude, and roughness text boxes (previously ignored). -In create_main_dialog, set a "focus_out_event" for the above and added a "value_changed" for RandomSeed. -In main_go, added call to WriteIni -=============== -gensurf.cpp -Set gszIni to "plugins/gensurf.ini" to get past assert error -ported WriteIni -=============== -view.cpp -In DrawPreview, changed 2 occurrences of GL_LINE_LOOP to GL_LINE_STRIP for patches diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/bitmap.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/bitmap.cpp deleted file mode 100644 index 038d93a2..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/bitmap.cpp +++ /dev/null @@ -1,434 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include -#include "gensurf.h" - -void GenerateBitmapMapping () -{ - double value; - double C0, C1; - double x, y; - int i, j; - int O00,O01,O10,O11; - int r0, r1, c0, c1; - int color; - unsigned char *colors; - - if (!gbmp.colors) - return; - - colors = gbmp.colors; - - for (j=0; j<=NV; j++) - { - y = (double)(j*(gbmp.height-1))/(double)NV; - r0 = (int)floor(y); - r1 = (int)ceil(y); - for (i=0; i<=NH; i++) - { - x = (double)(i*(gbmp.width-1))/(double)NH; - c0 = (int)floor(x); - c1 = (int)ceil(x); - O00 = r0*gbmp.width + c0; - O01 = r0*gbmp.width + c1; - O10 = r1*gbmp.width + c0; - O11 = r1*gbmp.width + c1; - C0 = (double)colors[O00] + (double)(colors[O01]-colors[O00])*(x-(double)c0); - C1 = (double)colors[O10] + (double)(colors[O11]-colors[O10])*(x-(double)c0); - color = (int)(C0 + (C1-C0)*(y-r0)); - - value = CalculateSnapValue(gbmp.black_value + color*((gbmp.white_value-gbmp.black_value)/255.)); - - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[1] = value; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[0] = value; - break; - default: - xyz[i][j].p[2] = value; - } - } - } -} - -static unsigned char* OpenBitmapFile () -{ -#define INVALID_FORMAT do{\ - fprintf(stderr,"%s:%d: Error file '%s' is malformed.\n",__FILE__,__LINE__,gbmp.name);\ - fclose(fp);\ - return NULL;\ -}while(0); - - int32_t bmWidth; - int32_t bmHeight; - uint16_t bmPlanes; - uint16_t bmBitsPixel; - uint8_t m1,m2; - uint32_t sizeimage; - int16_t res1,res2; - int32_t filesize, pixoff; - int32_t bmisize, compression; - int32_t xscale, yscale; - int32_t colors, impcol; - uint32_t m_bytesRead = 0; - unsigned char *image; - FILE *fp; - - fp = fopen (gbmp.name, "rb"); - if (fp == NULL) - { - fprintf(stderr,"Error: Invalid filename '%s'\n",gbmp.name); - return NULL; - } - - long rc; - rc = fread(&m1, 1, 1, fp); - m_bytesRead++; - if (rc == -1) - INVALID_FORMAT; - - rc = fread(&m2, 1, 1, fp); - m_bytesRead++; - if ((m1 != 'B') || (m2 != 'M')) - INVALID_FORMAT; - - rc = fread((uint32_t*)&(filesize),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(res1),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(res2),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(pixoff),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(bmisize),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t *)&(bmWidth),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(bmHeight),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(bmPlanes),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint16_t*)&(bmBitsPixel),2,1,fp); m_bytesRead+=2; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(compression),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(sizeimage),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(xscale),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(yscale),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(colors),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - rc = fread((uint32_t*)&(impcol),4,1,fp); m_bytesRead+=4; - if (rc != 1) INVALID_FORMAT; - - if (bmBitsPixel != 8) - { - g_FuncTable.m_pfnMessageBox (g_pWnd, "This is not an 8-bit image. GenSurf can't use it.", - "Bitmap", eMB_OK, eMB_ICONWARNING); - fclose(fp); - return NULL; - } - - if (colors == 0) - colors = 1 << bmBitsPixel; - - if (bmBitsPixel != 24) - { - int i; - for (i = 0; i < colors; i++) - { - unsigned char r ,g, b, dummy; - - rc = fread(&b, 1, 1, fp); - m_bytesRead++; - if (rc!=1) - { - INVALID_FORMAT; - } - - rc = fread(&g, 1, 1, fp); - m_bytesRead++; - if (rc!=1) - { - INVALID_FORMAT; - } - - rc = fread(&r, 1, 1, fp); - m_bytesRead++; - if (rc != 1) - { - INVALID_FORMAT; - } - - rc = fread(&dummy, 1, 1, fp); - m_bytesRead++; - if (rc != 1) - { - INVALID_FORMAT; - } - } - } - - if ((long)m_bytesRead > pixoff) - { - INVALID_FORMAT; - } - - while ((long)m_bytesRead < pixoff) - { - char dummy; - fread(&dummy,1,1,fp); - m_bytesRead++; - } - - int w = bmWidth; - int h = bmHeight; - - // set the output params - image = (unsigned char*)malloc(w*h); - - if (image != NULL) - { - unsigned char* outbuf = image; - long row = 0; - long rowOffset = 0; - - if (compression == 0) // BI_RGB - { - for (row = 0; row < bmHeight; row++) - { - // which row are we working on? - rowOffset = (long unsigned)row*w; - - { - // pixels are packed as 1 , 4 or 8 bit vals. need to unpack them - int bit_count = 0; - unsigned long mask = (1 << bmBitsPixel) - 1; - unsigned char inbyte = 0; - - for (int col=0;col> bit_count) & mask; - - // lookup the color from the colormap - stuff it in our buffer - // swap red and blue - *(outbuf + rowOffset + col) = pix; - } - - // read DWORD padding - while ((m_bytesRead-pixoff)&3) - { - char dummy; - if (fread(&dummy,1,1,fp)!=1) - { - free(image); - INVALID_FORMAT; - } - m_bytesRead++; - } - } - } - } - else // compression != 0 - { - int i, x = 0; - unsigned char c, c1 = 0, *pp; - row = 0; - pp = outbuf; - - if (bmBitsPixel == 8) - { - while (row < bmHeight) - { - c = getc(fp); - - if (c) - { - // encoded mode - c1 = getc(fp); - for (i = 0; i < c; x++, i++) - { - *pp = c1; pp++; - } - } - else - { - // c==0x00, escape codes - c = getc(fp); - - if (c == 0x00) // end of line - { - row++; - x = 0; - pp = outbuf + row*bmWidth; - } - else if (c == 0x01) - break; // end of pic - else if (c == 0x02) // delta - { - c = getc(fp); - x += c; - c = getc(fp); - row += c; - pp = outbuf + x + row*bmWidth; - } - else // absolute mode - { - for (i = 0; i < c; x++, i++) - { - c1 = getc(fp); - *pp = c1; pp++; - } - - if (c & 1) - getc(fp); // odd length run: read an extra pad byte - } - } - } - } - else if (bmBitsPixel == 4) - { - while (row < bmHeight) - { - c = getc(fp); - - if (c) - { - // encoded mode - c1 = getc(fp); - for (i = 0; i < c; x++, i++) - { - *pp = (i&1) ? (c1 & 0x0f) : ((c1>>4)&0x0f); pp++; - } - } - else - { - // c==0x00, escape codes - c = getc(fp); - - if (c == 0x00) // end of line - { - row++; - x = 0; - pp = outbuf + bmHeight*bmWidth; - } - else if (c == 0x01) - break; // end of pic - else if (c == 0x02) // delta - { - c = getc(fp); - x += c; - c = getc(fp); - row += c; - pp = outbuf + x + row*bmWidth; - } - else // absolute mode - { - for (i = 0; i < c; x++, i++) - { - if ((i&1) == 0) - c1 = getc(fp); - *pp = (i&1) ? (c1 & 0x0f) : ((c1>>4)&0x0f); pp++; - } - - if (((c&3) == 1) || ((c&3) == 2)) - getc(fp); // odd length run: read an extra pad byte - } - } - } - } - } - } - fclose(fp); - - gbmp.width = w; - gbmp.height = h; - if(gbmp.colors) - free(gbmp.colors); - gbmp.colors = image; - return image; - - -} - -bool OpenBitmap () -{ - - OpenBitmapFile (); - - if (!gbmp.colors) - { - char Text[256]; - - sprintf (Text, "Error opening %s", gbmp.name); - g_FuncTable.m_pfnMessageBox (g_pWnd, Text, "Bitmap", eMB_OK, eMB_ICONWARNING); - strcpy (gbmp.name, ""); - } - - if (g_pWnd) - { - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")), gbmp.name); - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_reload")), - strlen (gbmp.name) ? TRUE : FALSE); - - UpdatePreview (true); - } - - return (gbmp.colors != NULL); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/dec.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/dec.cpp deleted file mode 100644 index cc9083de..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/dec.cpp +++ /dev/null @@ -1,1327 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#define SINGLE -#ifdef SINGLE -#define REAL float -#else /* not SINGLE */ -#define REAL double -#endif /* not SINGLE */ - -#include -#include -#include -#include "gensurf.h" -#include "triangle.h" - -typedef struct -{ - float error; - int node; -} TRITABLE; - -double dh, dv; -int NVP1; - -#define Absolute(a) ((a) >= 0.0 ? (a) : -(a)) - -void MakeDecimatedMap(int *NumNodes, int *NumTris, NODE **pNode, TRI **pTri) -{ - int compare(TRITABLE *, TRITABLE *); - int Bisect(NODE *, int, int, int); - void CalcAngles(NODE *, int *, float *); - void EdgeOnSide(int *, int *, int *); - int tricall(int, NODE *, int *, TRI **, TRI **, const char *); - int CheckBorders(int *,int,NODE *,int *,TRI **); - - float biggesterror; - int i, j, N; - int j0, j1, j2; - int NumNodesToSave; - int NumNodesUsed; - NODE *Node; - TRI *Tri; - TRITABLE *TriTable; - - if(Decimate <= 0) return; - /* - ghCursorCurrent = LoadCursor(NULL,IDC_WAIT); - SetCursor(ghCursorCurrent); - */ - dh = (Hur-Hll)/NH; - dv = (Vur-Vll)/NV; - NVP1 = NV+1; - - NumNodes[0] = (NH+1)*(NVP1); - *pNode = (NODE *) malloc(NumNodes[0] * sizeof(NODE)); - Node = *pNode; - memset(Node,0,NumNodes[0]*sizeof(NODE)); - - // Copy [NH][NV] vertex array to our working node array - for(i=0,N=0; i<=NH; i++) - { - for(j=0; j<=NV; j++, N++) - { - Node[N].p[0] = (float)xyz[i][j].p[0]; - Node[N].p[1] = (float)xyz[i][j].p[1]; - Node[N].p[2] = (float)xyz[i][j].p[2]; - Node[N].fixed = xyz[i][j].fixed; - } - } - // Start things off with the corner values - Node[ 0].used = 1; - Node[NV].used = 1; - Node[NH*NVP1].used = 1; - Node[NH*NVP1+NV].used = 1; - NumNodesUsed = 4; - tricall(NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY"); - Tri = *pTri; - - // Which coordinates are we triangulating on? - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - j0 = 1; - j1 = 0; - j2 = 2; - break; - case PLANE_YZ0: - case PLANE_YZ1: - j0 = 0; - j1 = 1; - j2 = 2; - break; - default: - j0 = 2; - j1 = 0; - j2 = 1; - } - - // TriTable stores the largest error in a triangle and the node where that - // error occurs - TriTable = (TRITABLE *) malloc(NH*NV*2 * sizeof(TRITABLE)); - NumNodesToSave = min(NumNodes[0], (int)(0.01*(100-Decimate)*(NumNodes[0]-NumNodesUsed)+NumNodesUsed)); - - while(NumNodesUsed < NumNodesToSave) - { - for(i=0; i TriTable[Node[i].tri].error) - { - TriTable[Node[i].tri].error = (float)(Absolute(Node[i].error)); - TriTable[Node[i].tri].node = i; - } - } - qsort( (void *)TriTable, (size_t)(NumTris[0]), sizeof(TRITABLE), (int (*)(const void *, const void *))compare ); - for(i=0; i 0.5*biggesterror; i++) - { - if(Node[TriTable[i].node].used) continue; // shouldn't happen - NumNodesUsed++; - Node[TriTable[i].node].used++; - } - free(Tri); - tricall(NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY"); - Tri = *pTri; - // Sliver-check along borders. Since borders are often linear, the errors - // along borders will often be zero, so no new points will be added. This - // tends to produce long, thin brushes. For all border triangles, check - // that minimum angle isn't less than SLIVER_ANGLE. If it is, add another - // vertex. - while(CheckBorders(&NumNodesUsed,NumNodes[0],Node,NumTris,pTri) > 0) - { - } - Tri = *pTri; - } - } - free(TriTable); - // One last time (because we're pessimistic), check border triangles -// CheckBorders(&NumNodesUsed,NumNodes[0],Node,NumTris,pTri); -// Tri = *pTri; - - // Check that all fixed points are exact. If not, add them to the mix. - // First check to see if we have any fixed points that aren't already used. - for(i=0, N=0; i 0.5) - { - NumNodesUsed++; - Node[i].used++; - free(Tri); - tricall(NumNodes[0], Node, NumTris, NULL, pTri, "cnzBNPY"); - Tri = *pTri; - } - } - } - - // Swap node orders for surfaces facing down, north or west so that - // they are counterclockwise when facing the surface - - if((Plane == PLANE_XY1) || (Plane == PLANE_XZ0) || (Plane == PLANE_YZ1) ) - { - for(i=0; i= R) && (v[1] >= R) ) - { - edge[0] = 0; - border[0] = 1; - } - if( (v[1] >= R) && (v[2] >= R) ) - { - edge[0] = 1; - border[0] = 1; - } - if( (v[2] >= R) && (v[0] >= R) ) - { - edge[0] = 2; - border[0] = 1; - } - - if(border[0] >= 0) - { - k0 = edge[0]; - k1 = (k0+1) % 3; - N = Absolute(v[k0] - v[k1]); - Ndv = (float)(N*dv); - } - if( ((v[0] % NVP1) == 0) && ((v[1] % NVP1) == 0) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[0] - v[1])*dh)) return; - edge[0] = 0; - border[0] = 2; - return; - } - if( ((v[1] % NVP1) == 0) && ((v[2] % NVP1) == 0) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[1] - v[2])*dh)) return; - edge[0] = 1; - border[0] = 2; - return; - } - if( ((v[2] % NVP1) == 0) && ((v[0] % NVP1) == 0) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[2] - v[0])*dh)) return; - edge[0] = 2; - border[0] = 2; - return; - } - - if( ((v[0] % NVP1) == NV) && ((v[1] % NVP1) == NV) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[0] - v[1])*dh)) return; - edge[0] = 0; - border[0] = 3; - return; - } - if( ((v[1] % NVP1) == NV) && ((v[2] % NVP1) == NV) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[1] - v[2])*dh)) return; - edge[0] = 1; - border[0] = 3; - return; - } - if( ((v[2] % NVP1) == NV) && ((v[0] % NVP1) == NV) ) - { - if(border[0] >= 0) - if( Ndv > (Absolute(v[2] - v[0])*dh)) return; - edge[0] = 2; - border[0] = 3; - return; - } - return; -} - -void CalcAngles(NODE *node, int *v, float *angle) -{ - int i, j, k; - vec l; - vec x0, x1, x2, y0, y1, y2; - vec2 vv[3]; - vec dot; - - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - i = 0; - j = 2; - break; - case PLANE_YZ0: - case PLANE_YZ1: - i = 1; - j = 2; - break; - default: - i = 0; - j = 1; - } - x0 = node[v[0]].p[i]; - x1 = node[v[1]].p[i]; - x2 = node[v[2]].p[i]; - y0 = node[v[0]].p[j]; - y1 = node[v[1]].p[j]; - y2 = node[v[2]].p[j]; - - vv[0][0] = x1-x0; - vv[0][1] = y1-y0; - vv[1][0] = x2-x1; - vv[1][1] = y2-y1; - vv[2][0] = x0-x2; - vv[2][1] = y0-y2; - - for(k=0; k<3; k++) - { - l = (vec)(sqrt( vv[k][0]*vv[k][0] + vv[k][1]*vv[k][1] )); - if(l > 0.) - { - vv[k][0] /= l; - vv[k][1] /= l; - } - } - - dot = -(vv[0][0]*vv[2][0] + vv[0][1]*vv[2][1]); - angle[0] = (float)(acos(dot)); - dot = -(vv[1][0]*vv[0][0] + vv[1][1]*vv[0][1]); - angle[1] = (float)(acos(dot)); - dot = -(vv[2][0]*vv[1][0] + vv[2][1]*vv[1][1]); - angle[2] = (float)(acos(dot)); -} -//================================================================= -int Bisect(NODE *node, int border, int j0, int j1) -{ - int k; - - switch(border) - { - case 0: - k = (j0+j1)/2; - break; - case 1: - k = (j0+j1)/2; - break; - case 2: - k = (int)((j0+j1)/(2*NVP1)) * NVP1; - break; - case 3: - k = (int)((j0+j1+2)/(2*NVP1)) * NVP1 - 1; - break; - } - return( ((k != j0) && (k != j1)) ? k : 0 ); -} -//================================================================= -int compare(TRITABLE *t1, TRITABLE *t2) -{ - if(t1->error > t2->error) return -1; - if(t1->error < t2->error) return 1; - return 0; -} - -void MakeBrushes(int NumTris, NODE *Node, TRI *Tri,bool surf, - int offset,char *texture0, char *texture1, char *texture2) -{ - extern double backface; - BRUSH brush; - int contents; - int i, j; - float Steep; - vec3_t PlaneNormal,SurfNormal; - bool CheckAngle; - vec3_t t[2]; - - // if texture2 is identical to texture0, there's no need to - // check surface angle - if(!g_strcasecmp(texture0,texture2) || !strlen(texture2)) - CheckAngle = FALSE; - else - { - CheckAngle = TRUE; - Steep = (float)cos((double)SlantAngle/57.2957795); - switch(Plane) - { - case PLANE_XY0: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_XY1: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]=-1.;break; - case PLANE_XZ0: PlaneNormal[0]= 0.;PlaneNormal[1]= 1.;PlaneNormal[2]= 1.;break; - case PLANE_XZ1: PlaneNormal[0]= 0.;PlaneNormal[1]=-1.;PlaneNormal[2]= 1.;break; - case PLANE_YZ0: PlaneNormal[0]= 1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_YZ1: PlaneNormal[0]=-1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - } - } - - contents = 0; - if(surf) - { - if(UseDetail) contents += CONTENTS_DETAIL; - if(UseLadder) contents += CONTENTS_LADDER; - } - - OpenFuncGroup(); - for(i=0; i= max(Node[q[0]].p[j1],Node[q[2]].p[j1])) continue; - if(Tri[k].min[j2] >= max(Node[q[0]].p[j2],Node[q[2]].p[j2])) continue; - if(Tri[k].max[j1] <= min(Node[q[0]].p[j1],Node[q[2]].p[j1])) continue; - if(Tri[k].max[j2] <= min(Node[q[0]].p[j2],Node[q[2]].p[j2])) continue; - - for(h0=0; h0<4 && OK; h0++) - { - h1 = (h0+1)%4; - for(t=0; t<3 && OK; t++) - { - s[t] = side(Node[q[h0]].p[j1],Node[q[h0]].p[j2], - Node[q[h1]].p[j1],Node[q[h1]].p[j2], - Node[Tri[k].v[t]].p[j1],Node[Tri[k].v[t]].p[j2]); - } - if((s[1] > 0 || s[2] > 0) && s[0] < 0) OK=0; - if((s[2] > 0 || s[0] > 0) && s[1] < 0) OK=0; - if((s[0] > 0 || s[1] > 0) && s[2] < 0) OK=0; - } - } - if(!OK) continue; - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - // front - brush.face[0].v[0][0] = Node[q[2]].p[0]; - brush.face[0].v[0][1] = (float)front; - brush.face[0].v[0][2] = Node[q[2]].p[2]; - - brush.face[0].v[1][0] = Node[q[1]].p[0]; - brush.face[0].v[1][1] = (float)front; - brush.face[0].v[1][2] = Node[q[1]].p[2]; - - brush.face[0].v[2][0] = Node[q[0]].p[0]; - brush.face[0].v[2][1] = (float)front; - brush.face[0].v[2][2] = Node[q[0]].p[2]; - - // back - brush.face[1].v[0][0] = Node[q[0]].p[0]; - brush.face[1].v[0][1] = (float)backface; - brush.face[1].v[0][2] = Node[q[0]].p[2]; - - brush.face[1].v[1][0] = Node[q[1]].p[0]; - brush.face[1].v[1][1] = (float)backface; - brush.face[1].v[1][2] = Node[q[1]].p[2]; - - brush.face[1].v[2][0] = Node[q[2]].p[0]; - brush.face[1].v[2][1] = (float)backface; - brush.face[1].v[2][2] = Node[q[2]].p[2]; - - for(k0=0; k0= 0) - { - if(!Node[j].used) // Shouldn't be used, but... - { - NumNodesUsed[0]++; - Node[j].used++; - } - } - } - } - if(NumNodesUsed[0] > N) - { - free(*pTri); - tricall(NumNodes, Node, NumTris, NULL, pTri, "cnzBNPY"); - Tri = *pTri; - } - return (NumNodesUsed[0] - N); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/face.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/face.cpp deleted file mode 100644 index b1e6c6e8..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/face.cpp +++ /dev/null @@ -1,452 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include "gensurf.h" - -#define MAX_FACES 128 // Maximum number of faces on a brush -#define MAX_POINTS_ON_WINDING 64 -#define SIDE_FRONT 0 -#define SIDE_ON 2 -#define SIDE_BACK 1 -#define SIDE_CROSS -2 - -//vec3 vec3_origin = {0,0,0}; - -void PlaneFromPoints (float *p0, float *p1, float *p2, PLANE *plane) -{ - vec3 t1, t2; - vec length; - - VectorSubtract (p0, p1, t1); - VectorSubtract (p2, p1, t2); - plane->normal[0] = t1[1]*t2[2] - t1[2]*t2[1]; - plane->normal[1] = t1[2]*t2[0] - t1[0]*t2[2]; - plane->normal[2] = t1[0]*t2[1] - t1[1]*t2[0]; - - length = (vec)(sqrt(plane->normal[0]*plane->normal[0] + - plane->normal[1]*plane->normal[1] + - plane->normal[2]*plane->normal[2] )); - if (length == 0) - { - VectorClear(plane->normal); - } - else - { - plane->normal[0] /= length; - plane->normal[1] /= length; - plane->normal[2] /= length; - } - plane->dist = DotProduct (p0, plane->normal); -} -/* -void VectorMA (vec3 va, vec scale, vec3 vb, vec3 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 v1, vec3 v2, vec3 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]; -} -*/ -/* -============= -AllocWinding -============= -*/ -MY_WINDING *AllocWinding (int points) -{ - MY_WINDING *w; - int s; - - s = sizeof(vec)*3*points + sizeof(int); - w = (MY_WINDING*)malloc (s); - memset (w, 0, s); - return w; -} -/* -vec VectorNormalize (vec3 in, vec3 out) -{ - vec length, ilength; - - length = (vec)(sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2])); - if (length == 0) - { - VectorClear (out); - return 0; - } - - ilength = (vec)1.0/length; - out[0] = in[0]*ilength; - out[1] = in[1]*ilength; - out[2] = in[2]*ilength; - - return length; -} -*/ - -/* -================= -BaseWindingForPlane -================= -*/ -MY_WINDING *BaseWindingForPlane (vec3 normal, vec dist) -{ - int i, x; - vec max, v; - vec3 org, vright, vup; - MY_WINDING *w; - -// find the major axis - - max = -BOGUS_RANGE; - x = -1; - for (i=0 ; i<3; i++) - { - v = (vec)(fabs(normal[i])); - if (v > max) - { - x = i; - max = v; - } - } - if (x==-1) x = 2; - - 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, 65536, vup); - VectorScale (vright, 65536, 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; -} - -void FreeWinding (MY_WINDING *w) -{ - if (*(unsigned *)w == 0xdeaddead) -// Error ("FreeWinding: freed a freed winding"); - return; - *(unsigned *)w = 0xdeaddead; - - free (w); -} - -/* -============= -ChopWindingInPlace -============= -*/ -void ChopWindingInPlace (MY_WINDING **inout, vec3 normal, vec dist, vec epsilon) -{ - MY_WINDING *in; - vec dists[MAX_POINTS_ON_WINDING+4]; - int sides[MAX_POINTS_ON_WINDING+4]; - int counts[3]; - static vec dot; // VC 4.2 optimizer bug if not static - int i, j; - vec *p1, *p2; - vec3 mid; - MY_WINDING *f; - int maxpts; - - in = *inout; - counts[0] = counts[1] = counts[2] = 0; - -// determine sides for each point - for (i=0 ; inumpoints ; 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 ; inumpoints ; 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; -} - -void UseFaceBounds() -{ - LPVOID vp; - float Dot, BestDot; - float planepts[3][3]; - int BestFace; - int i, j; - int NumFaces; - vec3 SurfNormal; - vec3 vmin,vmax; - PLANE plane[MAX_FACES*2]; - PLANE pface; - MY_WINDING *w; - - switch(Plane) - { - case PLANE_XY1: - SurfNormal[0] = 0.0; - SurfNormal[1] = 0.0; - SurfNormal[2] =-1.0; - break; - case PLANE_XZ0: - SurfNormal[0] = 0.0; - SurfNormal[1] = 1.0; - SurfNormal[2] = 0.0; - break; - case PLANE_XZ1: - SurfNormal[0] = 0.0; - SurfNormal[1] =-1.0; - SurfNormal[2] = 0.0; - break; - case PLANE_YZ0: - SurfNormal[0] = 1.0; - SurfNormal[1] = 0.0; - SurfNormal[2] = 0.0; - break; - case PLANE_YZ1: - SurfNormal[0] =-1.0; - SurfNormal[1] = 0.0; - SurfNormal[2] = 0.0; - break; - default: - SurfNormal[0] = 0.0; - SurfNormal[1] = 0.0; - SurfNormal[2] = 1.0; - } - -#if 0 - i = g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - vp = g_FuncTable.m_pfnGetSelectedBrushHandle(0); - NumFaces = g_FuncTable.m_pfnGetFaceCount(vp); - - BestFace = -1; - BestDot = 0.0; - - for(i=0; im_v1[0]; - planepts[0][1] = QERFaceData->m_v1[1]; - planepts[0][2] = QERFaceData->m_v1[2]; - planepts[1][0] = QERFaceData->m_v2[0]; - planepts[1][1] = QERFaceData->m_v2[1]; - planepts[1][2] = QERFaceData->m_v2[2]; - planepts[2][0] = QERFaceData->m_v3[0]; - planepts[2][1] = QERFaceData->m_v3[1]; - planepts[2][2] = QERFaceData->m_v3[2]; - - PlaneFromPoints (planepts[0], planepts[1], planepts[2], &plane[2*i]); - VectorSubtract (vec3_origin, plane[2*i].normal, plane[2*i+1].normal); - plane[2*i+1].dist = -plane[2*i].dist; - - Dot = DotProduct(plane[2*i].normal,SurfNormal); - if(Dot > BestDot) - { - BestDot = Dot; - BestFace = i; - if(strlen(QERFaceData->m_TextureName)) - strcpy(Texture[Game][0],QERFaceData->m_TextureName); - } - } - for(i=0; im_TextureName)) - { - if(strcmp(Texture[Game][0],QERFaceData->m_TextureName)) - strcpy(Texture[Game][1],QERFaceData->m_TextureName); - } - } - - - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); - - w = BaseWindingForPlane (plane[BestFace*2].normal, plane[BestFace*2].dist); - - for (i=0 ; ip[0][0]; - vmin[1] = vmax[1] = w->p[0][1]; - vmin[2] = vmax[2] = w->p[0][2]; - for(j=1; jnumpoints; j++) - { - vmin[0] = min(vmin[0],w->p[j][0]); - vmin[1] = min(vmin[1],w->p[j][1]); - vmin[2] = min(vmin[2],w->p[j][2]); - vmax[0] = max(vmax[0],w->p[j][0]); - vmax[1] = max(vmax[1],w->p[j][1]); - vmax[2] = max(vmax[2],w->p[j][2]); - } - - FreeWinding(w); - - VectorCopy(plane[BestFace*2].normal,pface.normal); - pface.dist = plane[BestFace*2].dist; - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - if(pface.normal[1] == 0.) return; - Hll = vmin[0]; - Hur = vmax[0]; - Vll = vmin[2]; - Vur = vmax[2]; - Z00 = (pface.dist - pface.normal[0]*Hll - pface.normal[2]*Vll)/pface.normal[1]; - Z01 = (pface.dist - pface.normal[0]*Hll - pface.normal[2]*Vur)/pface.normal[1]; - Z10 = (pface.dist - pface.normal[0]*Hur - pface.normal[2]*Vll)/pface.normal[1]; - Z11 = (pface.dist - pface.normal[0]*Hur - pface.normal[2]*Vur)/pface.normal[1]; - break; - case PLANE_YZ0: - case PLANE_YZ1: - if(pface.normal[0] == 0.) return; - Hll = vmin[1]; - Hur = vmax[1]; - Vll = vmin[2]; - Vur = vmax[2]; - Z00 = (pface.dist - pface.normal[1]*Hll - pface.normal[2]*Vll)/pface.normal[0]; - Z01 = (pface.dist - pface.normal[1]*Hll - pface.normal[2]*Vur)/pface.normal[0]; - Z10 = (pface.dist - pface.normal[1]*Hur - pface.normal[2]*Vll)/pface.normal[0]; - Z11 = (pface.dist - pface.normal[1]*Hur - pface.normal[2]*Vur)/pface.normal[0]; - break; - default: - if(pface.normal[2] == 0.) return; - Hll = vmin[0]; - Hur = vmax[0]; - Vll = vmin[1]; - Vur = vmax[1]; - Z00 = (pface.dist - pface.normal[0]*Hll - pface.normal[1]*Vll)/pface.normal[2]; - Z01 = (pface.dist - pface.normal[0]*Hll - pface.normal[1]*Vur)/pface.normal[2]; - Z10 = (pface.dist - pface.normal[0]*Hur - pface.normal[1]*Vll)/pface.normal[2]; - Z11 = (pface.dist - pface.normal[0]*Hur - pface.normal[1]*Vur)/pface.normal[2]; - } -#endif -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/font.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/font.cpp deleted file mode 100644 index c31741d4..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/font.cpp +++ /dev/null @@ -1,270 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// -// Texture Font -// -// Taken from LeoCAD (www.leocad.org) and used in GtkGenSurf -// with permission from the author. -// -// Leonardo Zide (leo@lokigames.com) -// - -#include -#include "gensurf.h" - -static const unsigned char data[2048] = { - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 207, 255, 255, 159, 255, 31, 255, 231, 159, 153, 63, 255, 255, 255, 255, - 255, 207, 255, 255, 159, 255, 207, 255, 231, 159, 153, 63, 255, 255, 255, 255, - 255, 207, 255, 255, 159, 255, 207, 255, 231, 255, 159, 63, 255, 255, 255, 255, - 7, 78, 252, 240, 145, 135, 3, 71, 38, 158, 153, 51, 19, 227, 196, 255, - 243, 140, 121, 230, 140, 51, 207, 51, 198, 156, 153, 57, 99, 204, 152, 255, - 255, 204, 51, 111, 158, 121, 206, 121, 230, 153, 153, 60, 115, 206, 60, 255, - 31, 204, 51, 127, 158, 121, 206, 121, 230, 153, 25, 62, 115, 206, 60, 255, - 199, 204, 51, 127, 158, 1, 206, 121, 230, 153, 25, 62, 115, 206, 60, 255, - 243, 204, 51, 127, 158, 249, 207, 121, 230, 153, 153, 60, 115, 206, 60, 255, - 243, 204, 51, 111, 158, 249, 207, 121, 230, 153, 153, 57, 115, 206, 60, 255, - 243, 140, 121, 230, 140, 115, 206, 51, 230, 153, 153, 51, 115, 206, 60, 255, - 7, 73, 252, 240, 145, 7, 207, 71, 230, 153, 153, 39, 115, 206, 60, 255, - 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 249, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 249, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 57, 255, 255, 249, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 131, 255, 255, 252, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 227, 255, - 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 201, 255, - 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, 255, 255, 255, 255, 156, 255, - 15, 79, 252, 200, 196, 96, 32, 79, 62, 252, 15, 15, 159, 192, 156, 255, - 103, 142, 121, 198, 112, 206, 57, 79, 62, 60, 15, 15, 159, 207, 156, 255, - 243, 204, 51, 207, 120, 254, 57, 207, 156, 57, 103, 102, 206, 231, 156, 255, - 243, 204, 51, 207, 124, 252, 57, 207, 156, 25, 230, 112, 206, 231, 156, 255, - 243, 204, 51, 207, 252, 224, 57, 207, 156, 25, 230, 121, 206, 243, 156, 255, - 243, 204, 51, 207, 252, 199, 57, 207, 201, 211, 242, 240, 228, 249, 156, 255, - 243, 204, 51, 207, 252, 207, 57, 207, 201, 195, 112, 230, 228, 249, 156, 255, - 103, 142, 121, 198, 124, 206, 121, 198, 227, 231, 57, 207, 241, 252, 201, 255, - 15, 79, 252, 200, 252, 224, 227, 200, 227, 231, 57, 207, 241, 192, 227, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 249, 255, 255, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 255, - 255, 207, 255, 207, 255, 255, 255, 255, 255, 255, 255, 127, 254, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 159, 15, 30, 252, 57, 224, 225, 128, 131, 7, 255, 254, 128, 127, 240, 255, - 135, 231, 204, 249, 57, 255, 252, 159, 57, 115, 126, 252, 60, 63, 231, 255, - 159, 247, 236, 249, 56, 127, 254, 159, 57, 115, 126, 252, 124, 158, 207, 255, - 159, 255, 252, 249, 56, 127, 254, 207, 57, 115, 62, 249, 124, 158, 207, 255, - 159, 255, 252, 121, 56, 112, 254, 207, 57, 115, 62, 249, 60, 207, 255, 255, - 159, 127, 62, 60, 57, 103, 224, 231, 131, 115, 158, 243, 128, 207, 255, 255, - 159, 63, 255, 57, 249, 103, 206, 231, 57, 7, 158, 243, 60, 207, 255, 255, - 159, 159, 255, 153, 249, 103, 206, 231, 57, 127, 206, 231, 124, 206, 255, 255, - 159, 207, 255, 25, 240, 103, 206, 243, 57, 127, 14, 224, 124, 158, 207, 255, - 159, 231, 239, 249, 185, 103, 206, 243, 57, 127, 230, 207, 124, 158, 207, 255, - 159, 231, 207, 249, 57, 103, 206, 243, 57, 63, 231, 207, 60, 63, 231, 255, - 159, 7, 28, 252, 121, 240, 224, 243, 131, 135, 231, 207, 128, 127, 240, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 7, 126, 128, 3, 124, 240, 249, 156, 63, 231, 57, 255, 252, 57, 159, 255, - 231, 124, 254, 243, 63, 231, 249, 156, 63, 231, 60, 255, 252, 57, 159, 255, - 231, 121, 254, 243, 159, 207, 249, 156, 63, 103, 62, 255, 248, 56, 158, 255, - 231, 121, 254, 243, 159, 207, 249, 156, 63, 39, 63, 255, 248, 56, 156, 255, - 231, 115, 254, 243, 207, 255, 249, 156, 63, 135, 63, 255, 112, 56, 152, 255, - 231, 115, 192, 3, 206, 255, 1, 156, 63, 199, 63, 255, 112, 56, 153, 255, - 231, 115, 254, 243, 207, 193, 249, 156, 63, 135, 63, 255, 36, 57, 147, 255, - 231, 115, 254, 243, 207, 207, 249, 156, 63, 39, 63, 255, 36, 57, 131, 255, - 231, 121, 254, 243, 159, 207, 249, 156, 57, 103, 62, 255, 140, 57, 135, 255, - 231, 121, 254, 243, 159, 199, 249, 156, 57, 231, 60, 255, 140, 57, 143, 255, - 231, 124, 254, 243, 63, 199, 249, 156, 147, 231, 57, 255, 220, 57, 159, 255, - 7, 126, 128, 243, 127, 208, 249, 156, 199, 231, 51, 192, 220, 57, 159, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 63, 252, 128, 63, 252, 128, 63, 28, 128, 249, 204, 79, 254, 39, 63, 255, - 159, 249, 60, 159, 249, 60, 159, 249, 249, 249, 204, 79, 158, 39, 63, 255, - 207, 243, 124, 206, 243, 124, 206, 243, 249, 249, 156, 103, 158, 103, 158, 255, - 207, 243, 124, 206, 243, 124, 206, 255, 249, 249, 156, 231, 156, 243, 204, 255, - 231, 231, 124, 230, 231, 124, 158, 255, 249, 249, 156, 231, 12, 243, 225, 255, - 231, 231, 60, 231, 231, 60, 63, 252, 249, 249, 60, 243, 12, 243, 243, 255, - 231, 231, 128, 231, 231, 128, 255, 249, 249, 249, 60, 243, 105, 249, 243, 255, - 231, 231, 252, 103, 230, 60, 255, 243, 249, 249, 124, 251, 97, 248, 225, 255, - 207, 243, 252, 207, 240, 124, 254, 243, 249, 249, 124, 248, 97, 248, 204, 255, - 207, 243, 252, 207, 241, 124, 206, 243, 249, 249, 124, 248, 243, 124, 158, 255, - 159, 249, 252, 159, 241, 124, 158, 249, 249, 115, 254, 252, 243, 60, 63, 255, - 63, 252, 252, 63, 228, 252, 60, 252, 249, 7, 255, 252, 243, 60, 63, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 243, 19, 192, 255, 252, 255, 255, 127, 14, 127, 248, 15, 252, 247, 227, 231, - 243, 243, 207, 255, 252, 255, 153, 127, 102, 62, 243, 227, 241, 193, 201, 243, - 231, 249, 231, 255, 252, 255, 60, 127, 242, 156, 231, 249, 231, 148, 201, 249, - 207, 252, 243, 255, 204, 124, 126, 126, 254, 156, 231, 57, 230, 148, 201, 252, - 207, 252, 243, 255, 204, 60, 255, 60, 255, 156, 231, 156, 204, 244, 99, 254, - 31, 254, 249, 255, 252, 159, 255, 57, 127, 158, 231, 204, 204, 244, 63, 255, - 31, 254, 252, 255, 252, 207, 255, 51, 63, 159, 231, 204, 204, 193, 159, 255, - 63, 127, 254, 255, 252, 159, 255, 57, 159, 207, 207, 204, 204, 151, 207, 248, - 63, 127, 254, 255, 252, 63, 255, 156, 159, 159, 231, 204, 228, 151, 103, 242, - 63, 63, 255, 255, 255, 127, 126, 158, 255, 159, 231, 25, 241, 148, 115, 242, - 63, 159, 127, 230, 204, 252, 60, 159, 159, 159, 231, 249, 255, 148, 121, 242, - 63, 31, 64, 230, 204, 252, 153, 159, 159, 159, 231, 227, 255, 193, 252, 248, - 255, 255, 63, 255, 231, 255, 255, 255, 255, 159, 231, 15, 252, 247, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 243, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 127, 248, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 63, 254, 255, 195, 255, 255, 255, 255, 3, 252, 147, 255, 255, 255, 255, 255, - 159, 252, 255, 153, 255, 255, 255, 255, 243, 252, 147, 255, 255, 255, 255, 255, - 159, 252, 255, 153, 255, 243, 255, 255, 243, 252, 147, 255, 255, 255, 255, 255, - 159, 252, 204, 60, 255, 243, 255, 255, 243, 252, 0, 255, 255, 255, 255, 255, - 63, 254, 204, 60, 255, 243, 128, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 63, 254, 225, 60, 255, 243, 255, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 31, 126, 128, 60, 127, 128, 255, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 159, 228, 225, 60, 193, 243, 128, 255, 243, 252, 201, 255, 255, 255, 255, 255, - 207, 240, 204, 60, 255, 243, 255, 255, 243, 124, 128, 255, 255, 255, 255, 255, - 207, 249, 204, 60, 255, 243, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, - 207, 240, 255, 60, 255, 243, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, - 31, 242, 255, 60, 255, 255, 255, 255, 243, 252, 228, 255, 255, 255, 255, 255, - 255, 255, 255, 60, 255, 255, 255, 255, 243, 252, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 153, 255, 255, 255, 0, 242, 252, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 153, 255, 255, 255, 255, 243, 252, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 195, 255, 255, 255, 255, 3, 252, 255, 255, 255, 255, 255, 255 -}; - -typedef struct -{ - unsigned char width; - float left, right, top, bottom; -} LC_TXFVERT; - -static LC_TXFVERT glyphs[93]; -static GLuint texture; - -void texfont_init () -{ - if (texture != 0) - return; - - int i, j, x, y; - float inv = 1.0f/128; - const char *charlines[16] = { - "abcdefghijklmn", "opqrstuvwxyz0", "123456789ABC", "DEFGHIJKLMN", - "OPQRSTUVWX", "YZ,.!;:<>/?{}@$%", "&*()-+=_[] #" }; - unsigned char lefts[7][17] = { - { 1, 11, 21, 30, 40, 50, 56, 66, 76, 80, 84, 93, 97, 111, 121 }, - { 1, 11, 21, 31, 38, 47, 53, 63, 72, 86, 94, 103, 111, 120 }, - { 1, 10, 19, 28, 37, 46, 55, 64, 73, 82, 94, 106, 118, }, - { 1, 13, 24, 34, 47, 59, 64, 73, 84, 94, 108, 120 }, - { 1, 14, 25, 38, 50, 61, 71, 83, 94, 109, 120 }, - { 1, 12, 22, 26, 30, 35, 39, 43, 52, 61, 65, 75, 81, 87, 103, 112, 125 }, - { 3, 14, 23, 28, 33, 38, 47, 56, 65, 70, 75, 79, 88 } }; - // tops = 1 20 39 58 77 96 112 (+16) - memset(glyphs, 0, sizeof(glyphs)); - - // ASCII 32-125 - for (i = 32; i < 126; i++) - for (x = 0; x < 7; x++) - for (y = 0; charlines[x][y]; y++) - if (charlines[x][y] == i) - { - glyphs[i-32].width = lefts[x][y+1] - lefts[x][y]; - glyphs[i-32].left = (float)lefts[x][y]*inv; - glyphs[i-32].right = (float)(lefts[x][y+1])*inv; - - if (x != 6) - glyphs[i-32].top = (float)(1 + 19*x); - else - glyphs[i-32].top = 112; - glyphs[i-32].bottom = glyphs[i-32].top + 16; - glyphs[i-32].top *= inv; - glyphs[i-32].bottom *= inv; - } - - g_GLTable.m_pfn_qglGenTextures (1, &texture); - g_GLTable.m_pfn_qglBindTexture (GL_TEXTURE_2D, texture); - g_GLTable.m_pfn_qglDisable (GL_TEXTURE_GEN_S); - g_GLTable.m_pfn_qglDisable (GL_TEXTURE_GEN_T); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - g_GLTable.m_pfn_qglTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - // g_GLTable.m_pfn_qglPixelStorei (GL_UNPACK_ALIGNMENT, 1); - - unsigned char *buf = (unsigned char*)malloc (128*128); - memset (buf, 255, 128*128); - - for (i = 0; i < 2048; i++) - for (j = 0; j < 8; j++) - if ((data[i] & (1 << j)) != 0) - buf[i*8+j] = 0; - - g_GLTable.m_pfn_qglTexImage2D (GL_TEXTURE_2D, 0, GL_INTENSITY4, 128, 128, 0, - GL_LUMINANCE, GL_UNSIGNED_BYTE, buf); - free (buf); -} - -void texfont_write (const char *text, int l, int t) -{ - if (texture == 0) - return; - - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglBindTexture (GL_TEXTURE_2D, texture); - g_GLTable.m_pfn_qglEnable (GL_TEXTURE_2D); - // g_GLTable.m_pfn_qglTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - g_GLTable.m_pfn_qglAlphaFunc (GL_GREATER, 0.0625); - g_GLTable.m_pfn_qglEnable (GL_ALPHA_TEST); - - g_GLTable.m_pfn_qglBegin (GL_QUADS); - for (const char* p = text; *p; p++) - { - if (*p < 32 || *p > 125) - continue; - if (glyphs[*p-32].width == 0) - continue; - - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].left, glyphs[*p-32].top); - g_GLTable.m_pfn_qglVertex2i (l, t); - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].left, glyphs[*p-32].bottom); - g_GLTable.m_pfn_qglVertex2i (l, t-16); - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].right, glyphs[*p-32].bottom); - g_GLTable.m_pfn_qglVertex2i (l + glyphs[*p-32].width, t-16); - g_GLTable.m_pfn_qglTexCoord2f (glyphs[*p-32].right, glyphs[*p-32].top); - g_GLTable.m_pfn_qglVertex2i (l + glyphs[*p-32].width, t); - l += glyphs[*p-32].width; - } - g_GLTable.m_pfn_qglEnd (); - - g_GLTable.m_pfn_qglDisable (GL_ALPHA_TEST); - g_GLTable.m_pfn_qglDisable (GL_TEXTURE_2D); - g_GLTable.m_pfn_qglBindTexture (GL_TEXTURE_2D, 0); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gendlgs.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gendlgs.cpp deleted file mode 100644 index dcda98a8..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gendlgs.cpp +++ /dev/null @@ -1,2359 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include -#include -#include -#include "gensurf.h" - -#define GENERAL_TAB 0 -#define EXTENTS_TAB 1 -#define BITMAP_TAB 2 -#define FIXPOINTS_TAB 3 -#define TEXTURE_TAB 4 -//#define BUFF_SIZE 32768 - -#define ENABLE_WIDGET(name,enable) \ - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), (name))), (enable)) -#define CHECK_WIDGET(name,check) \ - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), name)), check) - -static GtkWidget *game_radios[NUMGAMES]; -static GtkWidget *wave_radios[5]; -static GtkWidget *plane_radios[6]; -static guint current_tab; -static int OldPreview; -static int WasDetail; -static GtkTooltips *tooltips; -static int FirstPassComplete = 0; - -void About (GtkWidget *parent) -{ -/* - char *icon_xpm[] = { -"32 32 4 1", -" c None", -". c #000000", -"+ c #FFFFFF", -"@ c #838183", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................", -"...............++...............", -".............++++++.............", -"............++@+++@+............", -"..........+++..++..+++..........", -"........++.+.++..++.+.@+........", -".......+..+..+.++.+..+..++......", -".....++..++.+..++..+.++..++.....", -"...++..++...+.+..+.++..++..++...", -"..++.+.++....++..++....++.+..+..", -".+.+..+..++....++....++..++.+.+.", -"..+++....+.++++++++++.+....+++..", -"....++.@@+++++.++.++++@++.++....", -"......+++++++......++@+++++.....", -".......+++.+.++..++.+..++.......", -".........++..+.++.+..++.........", -"...........++..++..++...........", -".............++..+.+............", -"..............+..+@.............", -"...............@@...............", -"................................", -"................................", -"................................", -"................................", -"................................", -"................................" -}; -*/ - // leo: I'm too lazy to create a nice about box - // ^Fishman - I am lazy too :P. - g_FuncTable.m_pfnMessageBox (parent, "GtkGenSurf 1.05\n\n" - "Original version\n" - "David Hyde (rascal@vicksburg.com)\n\n" - "Porting\n" - "Leonardo Zide (leo@lokigames.com)\n\n" - "Enhancements\n" - "Pablo Zurita (pablo@qeradiant.com)\n" - "Hydra (hydra@hydras-world.com)", - "About GtkGenSurf", eMB_OK); -} - -// ============================================================================= -// main dialog - -static void SetupControls () -{ - switch (current_tab) - { - case GENERAL_TAB: - break; - - case EXTENTS_TAB: - if (Game != QUAKE3) - { - gtk_widget_hide (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "use_patches"))); - ENABLE_WIDGET ("use_patches", FALSE); - } - else - { - gtk_widget_show (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "use_patches"))); - ENABLE_WIDGET ("use_patches", TRUE); - } - - if (Game == QUAKE3 && UsePatches != 0) - { - ENABLE_WIDGET ("decimate", FALSE); - } - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "snap_text")), "Snap to grid:"); // ^Fishman - Snap to grid. - break; - - case BITMAP_TAB: - if (WaveType != WAVE_BITMAP) - { - ENABLE_WIDGET ("bmp_file", FALSE); - ENABLE_WIDGET ("bmp_file_browse", FALSE); - ENABLE_WIDGET ("bmp_black", FALSE); - ENABLE_WIDGET ("bmp_white", FALSE); - ENABLE_WIDGET ("bmp_text1", FALSE); - ENABLE_WIDGET ("bmp_text2", FALSE); - ENABLE_WIDGET ("bmp_text3", FALSE); - ENABLE_WIDGET ("bmp_reload", FALSE); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "bmp_note")), - "These options are disabled unless \"From Bitmap\"\n" - "is selected as the Waveform on the General tab."); - } - else - { - ENABLE_WIDGET ("bmp_file", TRUE); - ENABLE_WIDGET ("bmp_file_browse", TRUE); - ENABLE_WIDGET ("bmp_black", TRUE); - ENABLE_WIDGET ("bmp_white", TRUE); - ENABLE_WIDGET ("bmp_text1", TRUE); - ENABLE_WIDGET ("bmp_text2", TRUE); - ENABLE_WIDGET ("bmp_text3", TRUE); - ENABLE_WIDGET ("bmp_reload", strlen(gbmp.name) != 0); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "bmp_note")), - "GenSurf works only with 8-bit bitmaps. Color indices are\n" - "mapped to values for each vertex. Generally, gray scale\n" - "images are stored with black as color 0, white as color 255."); - } - break; - - case FIXPOINTS_TAB: - ENABLE_WIDGET ("fix_value", (NumVerticesSelected != 0)); - ENABLE_WIDGET ("fix_value_text", (NumVerticesSelected != 0)); - ENABLE_WIDGET ("fix_free", (NumVerticesSelected != 0)); - ENABLE_WIDGET ("fix_range", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - ENABLE_WIDGET ("fix_range_text", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - ENABLE_WIDGET ("fix_rate", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - ENABLE_WIDGET ("fix_rate_text", ((NumVerticesSelected != 0) && (WaveType != WAVE_ROUGH_ONLY))); - break; - - case TEXTURE_TAB: - ENABLE_WIDGET ("texture2", (UsePatches == 0)); - ENABLE_WIDGET ("texture3", (UsePatches == 0)); - ENABLE_WIDGET ("tex_slant", (UsePatches == 0)); - ENABLE_WIDGET ("detail", (UsePatches == 0)); - if (Game != QUAKE3 ) - { - ENABLE_WIDGET ("terrain_ent", FALSE); // ^Fishman - Adds terrain key to func_group. - ENABLE_WIDGET ("hint", (UsePatches == 0)); - } - break; - } - - switch (WaveType) - { - case WAVE_HCYLINDER: - case WAVE_VCYLINDER: - ENABLE_WIDGET ("amplitude", TRUE); - ENABLE_WIDGET ("wavelength", TRUE); - ENABLE_WIDGET ("z00", TRUE); - ENABLE_WIDGET ("z01", TRUE); - ENABLE_WIDGET ("z10", TRUE); - ENABLE_WIDGET ("z11", TRUE); - ENABLE_WIDGET ("linearborder", TRUE); - ENABLE_WIDGET ("go", TRUE); - break; - case WAVE_BITMAP: - ENABLE_WIDGET ("amplitude", FALSE); - ENABLE_WIDGET ("wavelength", FALSE); - ENABLE_WIDGET ("z00", FALSE); - ENABLE_WIDGET ("z01", FALSE); - ENABLE_WIDGET ("z10", FALSE); - ENABLE_WIDGET ("z11", FALSE); - ENABLE_WIDGET ("linearborder", FALSE); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - break; - case WAVE_ROUGH_ONLY: - ENABLE_WIDGET ("amplitude", FALSE); - ENABLE_WIDGET ("wavelength", FALSE); - ENABLE_WIDGET ("z00", TRUE); - ENABLE_WIDGET ("z01", TRUE); - ENABLE_WIDGET ("z10", TRUE); - ENABLE_WIDGET ("z11", TRUE); - ENABLE_WIDGET ("linearborder", TRUE); - ENABLE_WIDGET ("go", TRUE); - break; - default: - ENABLE_WIDGET ("amplitude", TRUE); - ENABLE_WIDGET ("wavelength", TRUE); - ENABLE_WIDGET ("z00", TRUE); - ENABLE_WIDGET ("z01", TRUE); - ENABLE_WIDGET ("z10", TRUE); - ENABLE_WIDGET ("z11", TRUE); - ENABLE_WIDGET ("linearborder", TRUE); - ENABLE_WIDGET ("go", TRUE); - } - - switch (Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmin_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmax_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmin_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmax_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nh_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nv_text")), "Z:"); - break; - case PLANE_YZ0: - case PLANE_YZ1: - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmin_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmax_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmin_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmax_text")), "Z:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nh_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nv_text")), "Z:"); - break; - default: - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmin_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "hmax_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmin_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "vmax_text")), "Y:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nh_text")), "X:"); - gtk_label_set_text (GTK_LABEL (g_object_get_data (G_OBJECT (g_pWnd), "nv_text")), "Y:"); - break; - } -} - -// SetDlgValues fills in text boxes and initializes other input controls -static void SetDlgValues (int tab) -{ - char Text[256]; - char RForm[16] = "%.5g"; - int i; - - switch (tab) - { - case GENERAL_TAB: - // Hell if I know why, but in the release build the 2nd pass thru the - // set_sensitive loop for game_radios crashes. No need to do this more - // than once anyhow. - if (!FirstPassComplete) - { - for (i = 0; i < NUMGAMES; i++) - gtk_widget_set_sensitive (game_radios[i], (i == Game ? TRUE : FALSE)); - for (i = 0; i < 6; i++) - gtk_widget_set_sensitive (plane_radios[i], (i == Plane ? TRUE : FALSE)); - } - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (game_radios[Game]), TRUE); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (plane_radios[Plane]), TRUE); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (wave_radios[WaveType]), TRUE); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "random")), - RandomSeed); - sprintf (Text, RForm, WaveLength); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "wavelength")), Text); - sprintf (Text, RForm, Amplitude); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "amplitude")), Text); - sprintf (Text, RForm, Roughness); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "roughness")), Text); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data - (G_OBJECT (g_pWnd), "main_antialiasing")), Antialiasing); - break; - - case EXTENTS_TAB: - sprintf (Text,RForm,Hll); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "hmin")), Text); - sprintf (Text,RForm,Vll); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "vmin")), Text); - sprintf (Text,RForm,Hur); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "hmax")), Text); - sprintf (Text,RForm,Vur); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "vmax")), Text); - sprintf (Text,RForm,Z00); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z00")), Text); - sprintf (Text,RForm,Z01); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z01")), Text); - sprintf (Text,RForm,Z10); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z10")), Text); - sprintf (Text,RForm,Z11); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "z11")), Text); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nh")), NH); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nv")), NV); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "sp")), SP); // ^Fishman - Snap to grid. - - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data - (G_OBJECT (g_pWnd), "linearborder")), FixBorders); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data - (G_OBJECT (g_pWnd), "use_patches")), UsePatches); - gtk_adjustment_set_value (GTK_ADJUSTMENT (g_object_get_data (G_OBJECT (g_pWnd), "decimate_adj")), - Decimate); - - if (Game == QUAKE3 && UsePatches) - { - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "decimate")), FALSE); - - if (NH % 2) - { - NH++; - if (NH > MAX_ROWS) NH -= 2; - SetDlgValues (current_tab); - } - - if (NV % 2) - { - NV++; - if (NV > MAX_ROWS) NV -= 2; - SetDlgValues (current_tab); - } - if (NH % 2 ) NH++; - if (NH < 2 ) NH = 2; - if (NH > MAX_ROWS) NH = MAX_ROWS; - if (NV % 2 ) NV++; - if (NV < 2 ) NV = 2; - if (NV > MAX_ROWS) NV = MAX_ROWS; - - gpointer spin = g_object_get_data (G_OBJECT (g_pWnd), "nh"); - GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 2; - gtk_adjustment_changed (adj); - spin = g_object_get_data (G_OBJECT (g_pWnd), "nv"); - adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 2; - gtk_adjustment_changed (adj); - } - else - { - gtk_widget_set_sensitive (GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "decimate")), TRUE); - - gpointer spin = g_object_get_data (G_OBJECT (g_pWnd), "nh"); - GtkAdjustment *adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 1; - gtk_adjustment_changed (adj); - spin = g_object_get_data (G_OBJECT (g_pWnd), "nv"); - adj = gtk_spin_button_get_adjustment (GTK_SPIN_BUTTON (spin)); - adj->lower = 1; - gtk_adjustment_changed (adj); - } - - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nh")), NH); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "nv")), NV); - - break; - - case BITMAP_TAB: - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")), gbmp.name); - sprintf(Text,"%g",gbmp.black_value); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_black")), Text); - sprintf(Text,"%g",gbmp.white_value); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_white")), Text); - break; - - case FIXPOINTS_TAB: - break; - - case TEXTURE_TAB: - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texture1")), Texture[Game][0]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texture2")), Texture[Game][1]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texture3")), Texture[Game][2]); - gtk_spin_button_set_value (GTK_SPIN_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "tex_slant")), - SlantAngle); - sprintf(Text,RForm,TexOffset[0]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texoffsetx")), Text); - sprintf(Text,RForm,TexOffset[1]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texoffsety")), Text); - sprintf(Text,RForm,TexScale[0]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texscalex")), Text); - sprintf(Text,RForm,TexScale[1]); - gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "texscaley")), Text); - CHECK_WIDGET ("detail", UseDetail); - - if (Game==QUAKE3) - { - ENABLE_WIDGET ("hint", FALSE); - AddHints=0; - } - else - ENABLE_WIDGET ("hint", TRUE); - CHECK_WIDGET ("hint", AddHints); - - /* - if (Game==SIN) - { - // ArghRad doesn't currently support SiN - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use sin file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Sin:"); - } - */ - - if(Game==QUAKE3) - { - /* - // ArghRad sun is inapplicable (so far) - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - // No ladders in Q3 - EnableWindow(GetDlgItem(hwndDisplay,DLG_LADDER), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_LADDER), SW_HIDE); - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use pk3 file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"PK3:"); - */ - } - -/*trix if(Game==HERETIC2) - { - // ArghRad doesn't currently support Heretic2 - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use pak file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Pak:"); - } */ - /* - if(Game==HALFLIFE) - { - // A bunch of controls aren't applicable to HL - EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE_BROWSE), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE2_BROWSE),0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE3_BROWSE),0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_DETAIL), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_LADDER), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE_BROWSE), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE2_BROWSE),SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_TEXTURE3_BROWSE),SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_DETAIL), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_LADDER), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use wad file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Wad:"); - SetDlgItemText(hwndDisplay,DLG_HINT,"Hint brushes"); - } - - if(Game==GENESIS3D) - { - // No Q2-type compilers support Genesis3D (including ArghRad) - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), 0); - EnableWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), 0); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_TEXT), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2), SW_HIDE); - ShowWindow(GetDlgItem(hwndDisplay,DLG_ARGHRAD2_SPIN), SW_HIDE); - - SetDlgItemText(hwndDisplay,DLG_TEX_USEPAK,"Use sin file"); - SetDlgItemText(hwndDisplay,DLG_TEX_PAK_TEXT,"Sin:"); - } - */ - break; - } - SetupControls (); -} - -static void ReadDlgValues (int tab) -{ - // char Text[256]; - // int i; - - switch (tab) - { - case GENERAL_TAB: - gpointer spin; - Roughness = atof ( gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "roughness")))); - WaveLength = atof ( gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "wavelength")))); - Amplitude = atof ( gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "amplitude")))); - spin = g_object_get_data (G_OBJECT (g_pWnd), "random"); - RandomSeed = gtk_spin_button_get_value_as_int (GTK_SPIN_BUTTON (spin)); - break; - - case EXTENTS_TAB: - SP = atoi (gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "sp")))); - NH = atoi (gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "nh")))); - NV = atoi (gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "nv")))); - - if (Game == QUAKE3 && UsePatches != 0) - { - if (NH % 2 ) NH++; - if (NH < 2 ) NH = 2; - if (NH > MAX_ROWS) NH = MAX_ROWS; - if (NV % 2 ) NV++; - if (NV < 2 ) NV = 2; - if (NV > MAX_ROWS) NV = MAX_ROWS; - } - break; - -#if 0 - case BITMAP_TAB: - - if (WaveType == WAVE_BITMAP) - { - GetDlgItemText(hwnd,DLG_BMP_FILE,gbmp.name,sizeof(gbmp.name)); - CheckValidDIB(hwnd); - GetDlgItemText(hwnd,DLG_BMP_BLACK,Text,sizeof(Text)); - gbmp.black_value = atof(Text); - GetDlgItemText(hwnd,DLG_BMP_WHITE,Text,sizeof(Text)); - gbmp.white_value = atof(Text); - UpdatePreview(TRUE); - } - break; - - case FIXPOINTS_TAB: - GetDlgItemText(hwnd,DLG_FIX_VALUE,Text,sizeof(Text)); - temp.fixed_value = atoi(Text); - GetDlgItemText(hwnd,DLG_FIX_RANGE,Text,sizeof(Text)); - temp.range = atoi(Text); - GetDlgItemText(hwnd,DLG_FIX_RATE, Text,sizeof(Text)); - temp.rate = atof(Text); - for(k=0; k MAX_ROWS) - { - sprintf (Text, "The number of divisions must be > 0 and no greater than %d.", MAX_ROWS); - g_FuncTable.m_pfnMessageBox (g_pWnd, Text, "GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (NV < 1 || NV > MAX_ROWS) - { - sprintf (Text, "The number of divisions must be > 0 and no greater than %d.", MAX_ROWS); - g_FuncTable.m_pfnMessageBox (g_pWnd, Text, "GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (Hll >= Hur) - { - g_FuncTable.m_pfnMessageBox (g_pWnd, "The \"lower-left\" values must be less than " - "the corresponding \"upper-right\" values in " - "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (Vll >= Vur) - { - g_FuncTable.m_pfnMessageBox (g_pWnd,"The \"lower-left\" values must be less than " - "the corresponding \"upper-right\" values in " - "the \"Extent\" box.","GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - - if (!strlen (Texture[Game][0])) - { - g_FuncTable.m_pfnMessageBox (g_pWnd, "You must supply a texture name.", "GenSurf", eMB_OK, eMB_ICONWARNING); - gtk_notebook_set_page (GTK_NOTEBOOK (notebook), EXTENTS_TAB); - return; - } - -/* if (Decimate>0 && GimpHints!=0) - { - MessageBox(hwnd,"You've elected to use a decimated grid and gimp's non-detail hint brushes. " - "This combination usually produces bizarre visual errors in the game, " - "so GenSurf has turned off the hint brush option.", - "GenSurf",eMB_ICONWARNING); - GimpHints = 0; - } */ - - gtk_widget_hide (g_pWnd); - if (g_pWndPreview) - gtk_widget_hide (g_pWndPreview); - - GenerateMap(); - WriteIniFile(gszIni); -} - -// ============================================================================= -// general tab callbacks - -static void general_game (GtkToggleButton *widget, gpointer data) -{ - if (gtk_toggle_button_get_active (widget)) - { - Game = GPOINTER_TO_INT (data); - UpdatePreview (TRUE); - } -} - -static void general_plane (GtkToggleButton *widget, gpointer data) -{ - if (gtk_toggle_button_get_active (widget)) - { - Plane = GPOINTER_TO_INT (data); - SetupControls (); - UpdatePreview (TRUE); - } -} - -static void general_wave (GtkToggleButton *widget, gpointer data) -{ - if (gtk_toggle_button_get_active (widget)) - { - WaveType = GPOINTER_TO_INT (data); - SetupControls (); - UpdatePreview (TRUE); - } -} - -static void general_random (GtkAdjustment *adj, gpointer data) -{ - int nPos = (int)adj->value; - - if (RandomSeed != nPos) - { - RandomSeed = nPos; - UpdatePreview (true); - } -} - -// ============================================================================= -// extents tab callbacks - -static void extents_linearborder (GtkToggleButton *check, gpointer data) -{ - FixBorders = gtk_toggle_button_get_active (check); - UpdatePreview (true); -} - -static void extents_use_patches (GtkToggleButton *check, gpointer data) -{ - if (Game != QUAKE3) - return; - - UsePatches = gtk_toggle_button_get_active (check); - SetDlgValues (current_tab); - SetupControls (); - UpdatePreview (true); -} - -static void extents_nhnv_spin (GtkAdjustment *adj, int *data) -{ - int nPos = (int)adj->value; - - if (*data != nPos) - { - if (Game==QUAKE3 && UsePatches && (nPos % 2)) - { - if (*data < nPos) - *data += 2; - else - *data -= 2; - gtk_adjustment_set_value (adj, *data); - } - else - *data = nPos; - UpdatePreview (true); - } -} - -static void extents_decimate (GtkAdjustment *adj, gpointer data) -{ - int nPos = (int)adj->value; - - Decimate = nPos; - UpdatePreview (true); -} - -// Hydra : snap to grid begin -/*static void extents_snaptogrid (GtkAdjustment *adj, gpointer data) -{ - int nPos = (int)adj->value; - - SnapToGrid = nPos; - UpdatePreview (true); -}*/ - -// ^Fishman - Modified version of Hydra's snap to grid code. -static void extents_snaptogrid_spin (GtkAdjustment *adj, int *data) -{ - int nPos = (int)adj->value; - SnapToGrid = nPos; - UpdatePreview (true); -} - -// ============================================================================= -// bitmap tab callbacks - -static gint bitmap_file_entryfocusout(GtkWidget* widget, GdkEventFocus* event, gpointer data) -{ - char filename[NAME_MAX]; - - strcpy (filename, gtk_entry_get_text (GTK_ENTRY(widget))); - if(strcmp (filename,gbmp.name)) - { - strcpy (gbmp.name,filename); - if (strlen(gbmp.name) ) - OpenBitmap (); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - } - return FALSE; -} - -static void bitmap_browse (GtkWidget *widget, gpointer data) -{ - const char *filename; - char *ptr; - - filename = g_FuncTable.m_pfnFileDialog (g_pWnd, TRUE, "Bitmap File", gbmp.defpath); - - if (filename != NULL) - { - strcpy (gbmp.name, filename); - - ptr = strrchr (filename, G_DIR_SEPARATOR); - if (ptr != NULL) - { - *(ptr+1) = '\0'; - strcpy (gbmp.defpath, filename); - } - - OpenBitmap (); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - } -} - -static void bitmap_reload (GtkWidget *widget, gpointer data) -{ - strcpy (gbmp.name, gtk_entry_get_text (GTK_ENTRY (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")))); - if(strlen (gbmp.name) ) - { - OpenBitmap (); - ENABLE_WIDGET ("go", (gbmp.colors != NULL ? TRUE : FALSE)); - } - else - ENABLE_WIDGET ("go", FALSE ); -} - -// ============================================================================= -// fix points tab callbacks - -static gint fix_value_entryfocusout (GtkWidget* widget, GdkEventFocus *event, gpointer data) -{ - int i = atoi (gtk_entry_get_text (GTK_ENTRY(widget))), k; - char Text[32]; - - if (i < -65536 || i > 65536) - { - gdk_beep (); - g_FuncTable.m_pfnMessageBox (g_pWnd, "The value must be between -65536 and 65536, inclusive.", - "GenSurf", eMB_OK, eMB_ICONWARNING); - sprintf (Text, "%d", (int)xyz[Vertex[0].i][Vertex[0].j].fixed_value); - gtk_entry_set_text (GTK_ENTRY(widget), Text); - gtk_window_set_focus (GTK_WINDOW (gtk_widget_get_toplevel (widget)), widget); - } - else if (i != xyz[Vertex[0].i][Vertex[0].j].fixed_value) - { - for(k=0; kvalue; - - if (xyz[Vertex[0].i][Vertex[0].j].fixed_value != i) - { - for(k=0; k(data)); - return FALSE; -} - -// ============================================================================= -// create tooltips - -void create_tooltips () -{ - tooltips = gtk_tooltips_new (); - - // Main - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "go")), - "Accept all input and generate a surface in Q3Radiant", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "open")), - "Open a previously saved GenSurf settings file.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "save")), - "Save all settings to a file.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "defaults")), - "Restore default values from DEFAULTS.SRF. If this file does not exist, GenSurf " - "initializes all input parameters to reasonable values. You can create your own " - "default surface by setting all parameters to your liking, then saving a settings " - "file as DEFAULTS.SRF with the Save As button.", - ""); - - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "main_preview")), - "View a wire-frame representation of the surface", - ""); - - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "main_antialiasing")), - "The lines in the preview window are antialiased for better quality", - ""); - - // General tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[0]), - "Builds a surface with alternating hills and valleys. Uses the general form Z=cos(X) " - "x sin(Y)", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[1]), - "Builds a surface with ridges parallel to the vertical axis.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[2]), - "Builds a surface with ridges parallel to the horizontal axis.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[3]), - "Builds a map from a bitmap image representing a contour plot. Click the \"Bitmap\" " - "tab to select the image. GenSurf only supports 256-color (8 bit) " - "bitmaps. GenSurf will work with any 256-color bitmap, but gray scale bitmaps are a bit " - "more intuitive.", - "" ); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (wave_radios[4]), - "Builds a random surface using the Plasma Cloud technique. Variance is controlled " - "by the Roughness input. To build a surface with completely random values not " - "dependent on neighboring vertices, use one of the other waveforms with 0 amplitude.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "wavelength")), - "Enter the wavelength (distance between crests). NOTE: Wavelengths equal to the grid " - "size or 2 times the grid size will result in 0 amplitudes. For best results, the " - "wavelength value should be at least 4 times the grid size (extents divided by the " - "number of divisions", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "amplitude")), - "Enter the height of hills/ridges.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "roughness")), - "Enter the roughness value (noise) for the surface. For fractal surfaces, this value " - "is used as a variance in the fractal calculations.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "random")), - "Seed value for the pseudo-random number generator.", - ""); - // Extents tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "hmin")), - "Minimum horizontal coordinate of the surface, i.e. X for a surface parallel to " - "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "hmax")), - "Maximum horizontal coordinate of the surface, i.e. X for a surface parallel to " - "the XY or XZ planes, Y for a surface parallel to the YZ plane. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "vmin")), - "Minimum vertical coordinate of the surface, i.e. Y for a surface parallel to " - "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "vmax")), - "Maximum vertical coordinate of the surface, i.e. Y for a surface parallel to " - "the XY plane, Z for a surface parallel to the XZ or YZ planes. For best results, " - "the extents (maximum-minimum values) in a given direction should be evenly " - "divisible by the number of divisions in that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "nh")), - "Number of divisions in the horizontal direction. For best results, the extents " - "in a given direction should be evenly divisible by the number of divisions in " - "that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "nv")), - "Number of divisions in the vertical direction. For best results, the extents " - "in a given direction should be evenly divisible by the number of divisions in " - "that direction.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "use_patches")), - "Produce one or more curved patches in the shape of your selected surface rather " - "than producing solid brushes. Depending on the size of your surface (and the " - "user's graphic detail settings, which you cannot control), curved surfaces will " - "be represented in the game by a very large number of polygons. Read the warnings " - "concerning curved surfaces on the GenSurf web page before using this feature.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "decimate")), - "Use the slider to control the number of vertices discarded by GenSurf. For many " - "surfaces, you can produce roughly the same shape surface with a high decimation " - "value. This will generally result in a map with lower polygon counts (and better " - "in-game performance). However, this feature should NOT be used for large terrain " - "surfaces in Q3", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z00")), - "Enter the height of the surface at the lower left corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z01")), - "Enter the height of the surface at the upper left corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z10")), - "Enter the height of the surface at the lower right corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "z11")), - "Enter the height of the surface at the upper right corner. This value will likely " - "be modified unless \"Linear Borders\" is checked.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "linearborder")), - "Restrict the edges of the surface to a straight line. This will help match up " - "brush edges if you drop this surface into another map.", - ""); - // Bitmap tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file")), - "Type the name of an 8-bit bitmap image file, or click Browse to select an image " - "from a list of those available on your system.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_file_browse")), - "Select a bitmap image file from a list of those available on your system.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_reload")), - "Reload the selected bitmap file after making changes in an external image editor.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_black")), - "Enter the value corresponding to color index 0 in the bitmap file. For gray scale " - "images, color 0 is normally black.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "bmp_white")), - "Enter the value corresponding to color index 255 in the bitmap file. For gray scale " - "images, color 255 is normally white.", - ""); - // Fixpoints tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_value")), - "Enter a value for the selected vertex. This value will not be adjusted when applying " - "a waveform or roughness to the surface. Unlock this vertex (so that it will be " - "adjusted normally) by clicking \"Free\". This vertex will influence vertices within " - "the \"Range affected\" of this vertex.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_range")), - "Enter the range away from the selected vertex that other vertices will be affected. " - "Use 0 if you don't want other vertices to be influenced by the currently selected " - "one. Note: this box is disabled if you've chosen the fractal generator, as it uses " - "a completely different method for determining values.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_rate")), - "Enter a rate of change for the surface affected by the fixed value. 0 gives a smooth " - "sinusoidal curve, values less than 0 give progressively sharper spikes, and values " - "greater than 0 take on a square shape. Values less than -30 or greater than 30 are " - "set to -30 and 30, respectively. Note that this entry will have no effect unless " - "you also specify a \"range affected\".", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_free")), - "Click this to free (unlock the value of) the currently selected vertex.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "fix_freeall")), - "Click this to free (unlock the values of) all vertices.", - ""); - // Texture tab - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "texture1")), - "Enter the name of the texture or shader used for the surface faces.", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "texture2")), - "Enter the name of the texture or shader used for faces other than the surface. Under " - "normal circumstances this should be \"common/caulk\"", - ""); - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "texture3")), - "Enter the name of the texture or shader used for \"steep\" surface faces, where \"steep\" " - "is the angle specified below. If this entry is left blank or if the \"steep\" angle is 0, " - "all surface faces will use the texture specified by \"Surface\".", - ""); - - gtk_tooltips_set_tip(GTK_TOOLTIPS (tooltips), - GTK_WIDGET (g_object_get_data (G_OBJECT (g_pWnd), "detail")), - "Check this box to use the detail content property on the generated brushes. Compile " - "times will be considerably shorter if the detail property is used, though the surface " - "will not block visibility at all. If you use the detail property, you should make sure " - "that \"common/caulk\" is used for the non-surface faces, or the polygon count will be " - "much higher than necessary.", - ""); -} - -// ============================================================================= -// create main dialog - -GtkWidget* create_main_dialog () -{ - GtkWidget *dlg, *vbox, *hbox, *hbox2, *button, *notebook, *frame, *table, *table2; - GtkWidget *check, *spin, *radio, *label, *entry, *scale; - GtkObject *adj; - GSList *group; - int i; - const char *games[] = { "Quake 2", "Half-Life", "SiN", "Heretic 2", "Kingpin", "Genesis3D", "Quake 3 Arena" }; - const char *waveforms[] = { "Alternating hill/valley", "Cylindrical left-to-right", "Cylindrical top-to-bottom", - "From bitmap", "Fractal" }; - const char *orientations[] = { "Ground surface", "Ceiling", "Wall facing 0", "Wall facing 90", - "Wall facing 180","Wall facing 270" }; - - g_pWnd = dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), gszCaption); - g_signal_connect (G_OBJECT (dlg), "delete_event", G_CALLBACK (main_close), NULL); - // g_signal_connect (G_OBJECT (dlg), "destroy", G_CALLBACK (gtk_widget_destroy), NULL); - gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (g_pRadiantWnd)); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_container_add (GTK_CONTAINER (dlg), hbox); - gtk_container_set_border_width (GTK_CONTAINER (hbox), 5); - - notebook = gtk_notebook_new (); - gtk_widget_show (notebook); - gtk_box_pack_start (GTK_BOX (hbox), notebook, TRUE, TRUE, 0); - g_signal_connect (G_OBJECT (notebook), "switch_page", - G_CALLBACK (switch_page), NULL); - gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP); - g_object_set_data (G_OBJECT (dlg), "notebook", notebook); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("General"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), table, label); - - frame = gtk_frame_new ("Game"); - gtk_widget_show (frame); - gtk_table_attach (GTK_TABLE (table), frame, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - vbox = gtk_vbox_new (TRUE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (frame), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - for (i = 0, group = NULL; i < NUMGAMES; i++) - { - radio = gtk_radio_button_new_with_label (group, games[i]); - gtk_widget_show (radio); - gtk_box_pack_start (GTK_BOX (vbox), radio, TRUE, TRUE, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (radio)); - game_radios[i] = radio; - g_signal_connect (G_OBJECT (radio), "toggled", G_CALLBACK (general_game), GINT_TO_POINTER (i)); - } - - frame = gtk_frame_new ("Waveform"); - gtk_widget_show (frame); - gtk_table_attach (GTK_TABLE (table), frame, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - vbox = gtk_vbox_new (TRUE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (frame), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - for (i = 0, group = NULL; i < 5; i++) - { - radio = gtk_radio_button_new_with_label (group, waveforms[i]); - gtk_widget_show (radio); - gtk_box_pack_start (GTK_BOX (vbox), radio, TRUE, TRUE, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (radio)); - wave_radios[i] = radio; - g_signal_connect (G_OBJECT (radio), "toggled", G_CALLBACK (general_wave), GINT_TO_POINTER (i)); - } - - frame = gtk_frame_new ("Orientation"); - gtk_widget_show (frame); - gtk_table_attach (GTK_TABLE (table), frame, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - vbox = gtk_vbox_new (TRUE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (frame), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - for (i = 0, group = NULL; i < 6; i++) - { - radio = gtk_radio_button_new_with_label (group, orientations[i]); - gtk_widget_show (radio); - gtk_box_pack_start (GTK_BOX (vbox), radio, TRUE, TRUE, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (radio)); - plane_radios[i] = radio; - g_signal_connect (G_OBJECT (radio), "toggled", G_CALLBACK (general_plane), GINT_TO_POINTER (i)); - } - - table2 = gtk_table_new (4, 2, FALSE); - gtk_widget_show (table2); - gtk_table_set_row_spacings (GTK_TABLE (table2), 5); - gtk_table_set_col_spacings (GTK_TABLE (table2), 5); - gtk_table_attach (GTK_TABLE (table), table2, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - label = gtk_label_new ("Wavelength:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Max. amplitude:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Roughness:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Random seed:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table2), label, 0, 1, 3, 4, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table2), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "wavelength", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &WaveLength); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table2), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "amplitude", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Amplitude); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table2), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "roughness", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Roughness); - - adj = gtk_adjustment_new (1, 1, 32767, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (general_random), NULL); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table2), spin, 1, 2, 3, 4, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "random", spin); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Extents"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, TRUE, 0); - - frame = gtk_frame_new ("Extents"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (hbox2), frame, TRUE, TRUE, 0); - - table = gtk_table_new (3, 4, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("X:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "hmin_text", label); - - label = gtk_label_new ("X:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "hmax_text", label); - - label = gtk_label_new ("Y:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "vmin_text", label); - - label = gtk_label_new ("Y:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "vmax_text", label); - - label = gtk_label_new ("Lower-left"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Upper-right"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 3, 4, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "hmin", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Hll); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "hmax", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Hur); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "vmin", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Vll); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "vmax", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Vur); - - frame = gtk_frame_new ("Divisions"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (hbox2), frame, TRUE, TRUE, 0); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("X:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "nh_text", label); - - label = gtk_label_new ("Y:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "nv_text", label); - - adj = gtk_adjustment_new (8, 1, MAX_ROWS, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_nhnv_spin), &NH); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table), spin, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "nh", spin); - - adj = gtk_adjustment_new (8, 1, MAX_ROWS, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_nhnv_spin), &NV); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table), spin, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "nv", spin); - - check = gtk_check_button_new_with_label ("Use Bezier patches"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "use_patches", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (extents_use_patches), NULL); - - // ^Fishman - Snap to grid, replaced scroll bar with a texbox. - label = gtk_label_new ("Snap to grid:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - gtk_object_set_data (GTK_OBJECT (dlg), "snap_text", label); - - adj = gtk_adjustment_new (8, 0, 256, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_snaptogrid_spin), &SP); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_box_pack_start (GTK_BOX (vbox), spin, FALSE, TRUE, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "sp", spin); - // ^Fishman - End of Snap to grid code. - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, TRUE, 10); - - label = gtk_label_new ("Decimate:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, TRUE, 0); - - adj = gtk_adjustment_new (0, 0, 110, 1, 10, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (extents_decimate), NULL); - g_object_set_data (G_OBJECT (dlg), "decimate_adj", adj); - scale = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (scale); - gtk_box_pack_start (GTK_BOX (hbox2), scale, TRUE, TRUE, 0); - gtk_scale_set_value_pos (GTK_SCALE (scale), GTK_POS_RIGHT); - gtk_scale_set_digits (GTK_SCALE (scale), 0); - g_object_set_data (G_OBJECT (dlg), "decimate", scale); - - frame = gtk_frame_new ("Corner values"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, TRUE, 0); - - table = gtk_table_new (3, 4, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Upper-left:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Lower-left:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Upper-right:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Lower-right:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z01", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z01); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z00", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z00); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z11", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z11); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "z10", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &Z10); - - check = gtk_check_button_new_with_label ("Linear borders"); - gtk_widget_show (check); - gtk_table_attach (GTK_TABLE (table), check, 0, 4, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "linearborder", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (extents_linearborder), NULL); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Bitmap"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); - - label = gtk_label_new (""); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_note", label); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Filename:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_text1", label); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_file", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (bitmap_file_entryfocusout), NULL); - - hbox2 = gtk_hbox_new (TRUE, 5); - gtk_widget_show (hbox2); - gtk_table_attach (GTK_TABLE (table), hbox2, 1, 2, 1, 2, - (GtkAttachOptions) (0), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - button = gtk_button_new_with_label ("Browse..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (hbox2), button, FALSE, FALSE, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_file_browse", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (bitmap_browse), NULL); - - button = gtk_button_new_with_label ("Reload"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (hbox2), button, FALSE, FALSE, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_reload", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (bitmap_reload), NULL); - - table = gtk_table_new (2, 2, TRUE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Map color 0 to:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL|GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_text2", label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - label = gtk_label_new ("Map color 255 to:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL|GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - g_object_set_data (G_OBJECT (dlg), "bmp_text3", label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_table_attach (GTK_TABLE (table), hbox2, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_box_pack_start (GTK_BOX (hbox2), entry, FALSE, FALSE, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_black", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &gbmp.black_value); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_table_attach (GTK_TABLE (table), hbox2, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_box_pack_start (GTK_BOX (hbox2), entry, FALSE, FALSE, 0); - gtk_widget_set_usize (entry, 50, -2); - g_object_set_data (G_OBJECT (dlg), "bmp_white", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (doublevariable_entryfocusout), &gbmp.white_value); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Fix Points"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); - - label = gtk_label_new ("Click on a vertex in the lower half of the preview window,\n" - "then use the arrow keys or text box to assign a value.\n" - "Use Ctrl+Click to select multiple vertices/toggle a\n" - "selection. Use Shift+Click to select a range of vertices.\n\n" - "Click \"Free\" to unlock a vertex. Vertices within \"Range\n" - "affected\" will be influenced by this vertex."); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - - table = gtk_table_new (3, 3, FALSE); - gtk_widget_show (table); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Value:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - g_object_set_data (G_OBJECT (dlg), "fix_value_text", label); - - label = gtk_label_new ("Range affected:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - g_object_set_data (G_OBJECT (dlg), "fix_range_text", label); - - label = gtk_label_new ("Rate of change:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - g_object_set_data (G_OBJECT (dlg), "fix_rate_text", label); - - adj = gtk_adjustment_new (0, -65536, 65536, 1, 16, 0); - g_signal_connect (G_OBJECT (adj), "value_changed", G_CALLBACK (fix_value_changed), NULL); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_table_attach (GTK_TABLE (table), spin, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_EXPAND), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_value", spin); - g_signal_connect (G_OBJECT (spin), "focus_out_event", G_CALLBACK (fix_value_entryfocusout), NULL); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_range", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (fix_range_entryfocusout), NULL); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_rate", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK (fix_rate_entryfocusout), NULL); - - button = gtk_button_new_with_label ("Free"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_free", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (fix_free), NULL); - - button = gtk_button_new_with_label ("Free All"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_EXPAND), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "fix_freeall", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (fix_freeall), NULL); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_widget_show (vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - label = gtk_label_new ("Texture"); - gtk_widget_show (label); - gtk_notebook_append_page (GTK_NOTEBOOK (notebook), vbox, label); - - // ^Fishman - Modified to add more labels and textboxes. - table = gtk_table_new (5, 2, FALSE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Surface:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - - label = gtk_label_new ("Other:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - - label = gtk_label_new ("Steep:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texture1", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK(texture_entryfocusout), GINT_TO_POINTER (0)); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texture2", entry); - g_signal_connect (G_OBJECT (entry), "focus_out_event", G_CALLBACK(texture_entryfocusout), GINT_TO_POINTER (1)); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texture3", entry); - - hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_box_pack_start (GTK_BOX (vbox), hbox2, FALSE, TRUE, 0); - - label = gtk_label_new ("\"Steep\" angle:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, TRUE, 0); - - adj = gtk_adjustment_new (60, 0, 90, 1, 10, 0); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_box_pack_start (GTK_BOX (hbox2), spin, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "tex_slant", spin); - - table = gtk_table_new (2, 4, TRUE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Offset "); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - label = gtk_label_new ("Scale "); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 2, 4, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texoffsetx", entry); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texoffsety", entry); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texscalex", entry); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - gtk_widget_set_usize (entry, 60, -2); - g_object_set_data (G_OBJECT (dlg), "texscaley", entry); - - - - check = gtk_check_button_new_with_label ("Use detail brushes"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "detail", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (texture_detail), NULL); - - check = gtk_check_button_new_with_label ("Detail hint brushes"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "hint", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (texture_hint), NULL); - - // ^Fishman - Add terrain key to func_group. - check = gtk_check_button_new_with_label ("Add terrain key"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "terrain_ent", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (texture_terrainent), NULL); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, TRUE, 0); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - gtk_widget_set_usize (button, 60, -2); - g_object_set_data (G_OBJECT (dlg), "go", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_go), NULL); - - label = gtk_label_new ("Settings:"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, TRUE, 0); - - button = gtk_button_new_with_label ("Open..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "open", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_open), NULL); - - button = gtk_button_new_with_label ("Save as..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "save", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_save), NULL); - - button = gtk_button_new_with_label ("Defaults"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "defaults", button); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_defaults), NULL); - - button = gtk_button_new_with_label ("About..."); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (main_about), NULL); - - check = gtk_check_button_new_with_label ("Preview"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (main_preview), NULL); - g_object_set_data (G_OBJECT (dlg), "main_preview", check); - - // ^Fishman - Antializing for the preview window. - check = gtk_check_button_new_with_label ("Antialised lines"); - gtk_widget_show (check); - gtk_box_pack_start (GTK_BOX (vbox), check, FALSE, TRUE, 0); - g_object_set_data (G_OBJECT (dlg), "main_antialiasing", check); - g_signal_connect (G_OBJECT (check), "toggled", G_CALLBACK (main_antialiasing), NULL); - - for (i = 0; i < 5; i++) - SetDlgValues (i); - - CreateViewWindow (); - - create_tooltips(); - - FirstPassComplete = 1; - - return dlg; -} - - -#if 0 - -HWND hwndDisplay = (HWND)NULL; -HWND ghwndTab = (HWND)NULL; -int iTab=0; -Rect rcTab; -FILE *ftex; - -char GenSurfURL[40] = {"http://tarot.telefragged.com/gensurf"}; -char GenSurfBoard[40]={"http://tarot.telefragged.com/board"}; - -/* -* AboutDlgProc - processes messages for the about dialog. -*/ - -qboolean CALLBACK AboutDlgProc( HWND hwnd, unsigned msg, UINT wparam, LONG lparam ) -{ - char szText[256]; - DRAWITEMSTRUCT *dis; - HDC hdc; - HPEN hpen; - HWND hwndURL; - Rect rc; - SIZE size; - - lparam = lparam; /* turn off warning */ - - switch( msg ) { - case WM_INITDIALOG: - strcpy(szText,"About " ); - strcat(szText,gszCaption); - SetWindowText(hwnd,gszCaption); - SetDlgItemText(hwnd,DLG_ABOUT_APP,szText); - /* Application icon: */ - SendDlgItemMessage( hwnd, DLG_ABOUT_ICON, - STM_SETICON, (WPARAM)(HICON)LoadIcon(ghInst,"GENSURF"), - (LPARAM) NULL); - - hwndURL = GetDlgItem(hwnd,DLG_ABOUT_URL); - hdc = GetDC(hwndURL); - GetTextExtentPoint(hdc,GenSurfURL,strlen(GenSurfURL),&size); - ReleaseDC(hwndURL,hdc); - GetWindowRect(hwndURL,&rc); - SetWindowPos(hwndURL,(HWND)NULL,0,0,size.cx,size.cy+2, - SWP_NOMOVE | SWP_NOZORDER); - - hwndURL = GetDlgItem(hwnd,DLG_ABOUT_BOARD); - hdc = GetDC(hwndURL); - GetTextExtentPoint(hdc,GenSurfBoard,strlen(GenSurfBoard),&size); - ReleaseDC(hwndURL,hdc); - GetWindowRect(hwndURL,&rc); - SetWindowPos(hwndURL,(HWND)NULL,0,0,size.cx,size.cy+2, - SWP_NOMOVE | SWP_NOZORDER); - - return TRUE; - - case WM_COMMAND: - switch(LOWORD(wparam)) - { - case DLG_ABOUT_URL: - HTTP(GenSurfURL); - break; - case DLG_ABOUT_BOARD: - HTTP(GenSurfBoard); - break; - case IDOK: - EndDialog(hwnd,1); - return TRUE; - } - break; - - case WM_DRAWITEM: - if(wparam == DLG_ABOUT_URL) - { - dis = (LPDRAWITEMSTRUCT)lparam; - SetTextColor(dis->hDC,RGB(0,0,255)); - TextOut(dis->hDC,0,0,GenSurfURL,strlen(GenSurfURL)); - GetWindowRect(dis->hwndItem,&rc); - GetTextExtentPoint(dis->hDC,GenSurfURL,strlen(GenSurfURL),&size); - hpen = CreatePen(PS_SOLID,0,RGB(0,0,255)); - SelectObject(dis->hDC,hpen); - MoveToEx(dis->hDC,0,size.cy,NULL); - LineTo(dis->hDC,size.cx,size.cy); - SelectObject(dis->hDC,GetStockObject(BLACK_PEN)); - DeleteObject(hpen); - } - else if(wparam==DLG_ABOUT_BOARD) - { - dis = (LPDRAWITEMSTRUCT)lparam; - SetTextColor(dis->hDC,RGB(0,0,255)); - TextOut(dis->hDC,0,0,GenSurfBoard,strlen(GenSurfBoard)); - GetWindowRect(dis->hwndItem,&rc); - GetTextExtentPoint(dis->hDC,GenSurfBoard,strlen(GenSurfBoard),&size); - hpen = CreatePen(PS_SOLID,0,RGB(0,0,255)); - SelectObject(dis->hDC,hpen); - MoveToEx(dis->hDC,0,size.cy,NULL); - LineTo(dis->hDC,size.cx,size.cy); - SelectObject(dis->hDC,GetStockObject(BLACK_PEN)); - DeleteObject(hpen); - } - break; - - case WM_CLOSE: - EndDialog(hwnd,1); - return TRUE; - - default: - return FALSE; - } - return FALSE; - -} /* AboutDlgProc */ - -void About() -{ - if( DialogBox( ghInst,"About", ghwnd_main, (DLGPROC)AboutDlgProc ) < 0) - { - char Text[256]; - sprintf(Text,"In About(), GetLastError()=0x%08x",GetLastError()); - MessageBox(ghwnd_main,Text,"GenSurf",eMB_ICONWARNING); - } -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gendlgs.h b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gendlgs.h deleted file mode 100644 index dd954678..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gendlgs.h +++ /dev/null @@ -1,151 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#define DLG_PLANE_XY0 100 -#define DLG_PLANE_XY1 101 -#define DLG_PLANE_YZ0 102 -#define DLG_PLANE_XZ0 103 -#define DLG_PLANE_YZ1 104 -#define DLG_PLANE_XZ1 105 -#define DLG_WAVE_01 106 -#define DLG_WAVE_02 107 -#define DLG_WAVE_03 108 -#define DLG_WAVE_04 109 -#define DLG_WAVE_05 110 -#define DLG_WAVE_06 111 -#define DLG_LAMBDA 112 -#define DLG_LAMBDA_TEXT 113 -#define DLG_AMP 114 -#define DLG_AMP_TEXT 115 -#define DLG_ROUGH 116 -#define DLG_ROUGH_TEXT 117 -#define DLG_LINEARBORDER 118 -#define DLG_FILE 119 -#define DLG_FILE_BROWSE 120 -#define DLG_PREVIEW 121 -#define DLG_GO 122 -#define DLG_ABOUT 123 -#define DLG_NH_TEXT 124 -#define DLG_NH 125 -#define DLG_NH_SPIN 126 -#define DLG_NV_TEXT 127 -#define DLG_NV 128 -#define DLG_NV_SPIN 129 -#define DLG_HMIN_TEXT 130 -#define DLG_HMIN 131 -#define DLG_HMAX_TEXT 132 -#define DLG_HMAX 133 -#define DLG_VMIN_TEXT 134 -#define DLG_VMIN 135 -#define DLG_VMAX_TEXT 136 -#define DLG_VMAX 137 -#define DLG_Z00_TEXT 138 -#define DLG_Z00 139 -#define DLG_Z01_TEXT 140 -#define DLG_Z01 141 -#define DLG_Z10_TEXT 142 -#define DLG_Z10 143 -#define DLG_Z11_TEXT 144 -#define DLG_Z11 145 -#define DLG_TEXTURE 146 -#define DLG_SKYBOX 147 -#define DLG_AUTOOVERWRITE 148 -#define DLG_DETAIL 149 -#define DLG_ARGHRAD2 150 -#define DLG_ARGHRAD2_SPIN 151 -#define DLG_APPEND 152 -#define DLG_REFRESH 153 -#define DLG_TEXOFFSETX 154 -#define DLG_TEXOFFSETY 155 -#define DLG_TEXSCALEX 156 -#define DLG_TEXSCALEY 157 -#define DLG_FIXPOINTS 158 -#define DLG_TEXTURE_BROWSE 159 -#define DLG_AZIMUTH 162 -#define DLG_AZIMUTH_SPIN 163 -#define DLG_ELEVATION 164 -#define DLG_ELEVATION_SPIN 165 -#define DLG_RANDOMSEED 166 -#define DLG_RANDOMSEED_SPIN 167 -#define DLG_BITMAP 168 -#define DLG_SAVE 169 -#define DLG_OPEN 170 -#define DLG_TAB 171 -#define DLG_TEXTURE2 172 -#define DLG_TEXTURE2_BROWSE 173 -#define DLG_LADDER 174 -#define DLG_ARGHRAD2_TEXT 175 -#define DLG_FILE_TEXT 176 -#define DLG_DECIMATE 177 -#define DLG_DECIMATE_TEXT 178 -#define DLG_HIDEBACKFACES 179 -#define DLG_DEFAULTS 180 -#define DLG_ABOUT_APP 200 -#define DLG_ABOUT_ICON 201 -#define DLG_BMP_FILE 202 -#define DLG_BMP_FILE_BROWSE 203 -#define DLG_BMP_BLACK 204 -#define DLG_BMP_WHITE 205 -#define DLG_BMP_TEXT1 206 -#define DLG_BMP_TEXT2 207 -#define DLG_BMP_TEXT3 208 -#define DLG_BMP_NOTE 209 -#define DLG_BMP_RELOAD 210 -#define DLG_ABOUT_URL 211 -#define DLG_ABOUT_BOARD 212 -#define DLG_FIX_FREE 300 -#define DLG_FIX_FREEALL 301 -#define DLG_FIX_VALUE_TEXT 302 -#define DLG_FIX_VALUE 303 -#define DLG_FIX_VALUE_SPIN 304 -#define DLG_FIX_DONE 305 -#define DLG_FIX_RANGE_TEXT 306 -#define DLG_FIX_RANGE 307 -#define DLG_FIX_NOTE 308 -#define DLG_FIX_RATE_TEXT 309 -#define DLG_FIX_RATE 310 -#define DLG_USE_PATCHES 311 -#define DLG_DECIMATE_LABEL 312 -#define DLG_HINT 350 -#define DLG_GAME_00 400 -#define DLG_GAME_01 401 -#define DLG_GAME_02 402 -#define DLG_GAME_03 403 -#define DLG_GAME_04 404 -#define DLG_GAME_05 405 -#define DLG_GAME_06 406 -#define DLG_GAME_07 407 -#define DLG_GAME_08 408 -#define DLG_GAME_09 409 -#define DLG_TEX_USEPAK 420 -#define DLG_TEX_PAK_TEXT 421 -#define DLG_TEX_PAKFILE 422 -#define DLG_TEX_PAK_BROWSE 423 -#define DLG_TEX_LIST1 424 -#define DLG_TEX_LIST2 425 -#define DLG_TEX_LIST3 426 -#define DLG_TEXTURE3 427 -#define DLG_TEXTURE3_BROWSE 428 -#define DLG_TEX_SLANT_TEXT 429 -#define DLG_TEX_SLANT 430 -#define DLG_TEX_SLANT_SPIN 431 -#define DLG_EXCEL_FUNC 500 -#define DLG_EXCEL_FUNC_TEXT 501 -#define DLG_PREVIEW_ANTIALIASING 502 // ^Fishman - Antializing for the preview window. -#define DLG_SNAP_TO_GRID 503 // Hydra : snap to grid diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/genmap.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/genmap.cpp deleted file mode 100644 index 6e9c95dc..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/genmap.cpp +++ /dev/null @@ -1,2040 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include -#include "gensurf.h" - -double xmin,xmax,ymin,ymax,zmin,zmax; -double backface; -extern double dh, dv; -FILE *fmap; -XYZ xyz[MAX_ROWS+1][MAX_ROWS+1]; -int contents; -int surface[3]; - -#include "iundo.h" - -#include "refcounted_ptr.h" - -#include -#include -#include -#include - -#include "scenelib.h" - -scene::Node* h_func_group; -scene::Node* h_worldspawn; - - -//============================================================= -// Hydra : snap-to-grid begin -double CalculateSnapValue(double value) -{ - long snapvalue; - - // simple uncomplicated snapping, rounding both UP and DOWN to the nearest - // grid unit. - if (SnapToGrid >0) - { - snapvalue = (int)value / SnapToGrid; - if ((long)value % SnapToGrid < (SnapToGrid / 2)) // Snap Downwards if less than halfway between to grid units - value = snapvalue * SnapToGrid; - else // Snap Upwards if more than halfway between to grid units - value = (snapvalue+1) * SnapToGrid; - } - return value; -} -// Hydra : snap-to-grid end - -//============================================================= -bool ValidSurface() -{ - if(WaveType == WAVE_BITMAP && !gbmp.colors) return FALSE; - if(NH < 1) return FALSE; - if(NH > MAX_ROWS) return FALSE; - if(NV < 1) return FALSE; - if(NV > MAX_ROWS) return FALSE; - if(Hll >= Hur) return FALSE; - if(Vll >= Vur) return FALSE; - return TRUE; -} - -//============================================================= -int MapPatches() -{ - int NH_remain; - int NV_remain; - int NH_patch; - int NV_patch; - int BrushNum = 0; - int i, j, k1, k2, k3; - int i0, j0, ii; - char szOops[128]; - - dh = (Hur-Hll)/NH; - dv = (Vur-Vll)/NV; - - // Generate control points in pp array to give desired values currently - // in p array. - switch(Plane) - { - case PLANE_XY0: - case PLANE_XY1: - k1 = 0; - k2 = 1; - k3 = 2; - break; - case PLANE_XZ0: - case PLANE_XZ1: - k1 = 0; - k2 = 2; - k3 = 1; - break; - case PLANE_YZ0: - case PLANE_YZ1: - k1 = 1; - k2 = 2; - k3 = 0; - break; - } - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].pp[k1] = xyz[i][j].p[k1]; - xyz[i][j].pp[k2] = xyz[i][j].p[k2]; - } - } - for(i=0; i<=NH; i+=2) - { - for(j=0; j<=NV; j+=2) - xyz[i][j].pp[k3] = xyz[i][j].p[k3]; - } - for(i=1; i 1) - { - if(( (NH_remain-1) % 14) == 0) - NH_patch = 15; - else if(( (NH_remain-1) % 12) == 0) - NH_patch = 13; - else if(( (NH_remain-1) % 10) == 0) - NH_patch = 11; - else if(( (NH_remain-1) % 8) == 0) - NH_patch = 9; - else if(( (NH_remain-1) % 6) == 0) - NH_patch = 7; - else if(( (NH_remain-1) % 4) == 0) - NH_patch = 5; - else if(( (NH_remain-1) % 2) == 0) - NH_patch = 3; - else if(NH_remain > 16) - NH_patch = 7; - else if(NH_remain > 4) - NH_patch = 5; - else - NH_patch = 3; - while( NH_patch > 3 && (NH_patch-1)*dh > 512 ) - NH_patch -= 2; - NH_remain -= (NH_patch-1); - if(NH_remain < 0) - { - sprintf(szOops,"Oops... screwed up with NH=%d",NH); - g_FuncTable.m_pfnMessageBox(NULL,szOops,"Uh oh"); - } - NV_remain = NV+1; - j0 = 0; - while(NV_remain > 1) - { - if(( (NV_remain-1) % 14) == 0) - NV_patch = 15; - else if(( (NV_remain-1) % 12) == 0) - NV_patch = 13; - else if(( (NV_remain-1) % 10) == 0) - NV_patch = 11; - else if(( (NV_remain-1) % 8) == 0) - NV_patch = 9; - else if(( (NV_remain-1) % 6) == 0) - NV_patch = 7; - else if(( (NV_remain-1) % 4) == 0) - NV_patch = 5; - else if(( (NV_remain-1) % 2) == 0) - NV_patch = 3; - else if(NV_remain > 16) - NV_patch = 7; - else if(NV_remain > 4) - NV_patch = 5; - else - NV_patch = 3; - while( NV_patch > 3 && (NV_patch-1)*dh > 512 ) - NV_patch -= 2; - NV_remain -= (NV_patch-1); - if(NV_remain < 0) - { - sprintf(szOops,"Oops... screwed up with NV=%d",NV); - g_FuncTable.m_pfnMessageBox(NULL,szOops,"Uh oh"); - } - - scene::Node* patch = MakePatch(); -#if 0 - b->pPatch->setDims(NH_patch, NV_patch); - for(i=0; ipPatch->ctrlAt(COL,i,j)[0] = (float)xyz[ii][j0+j].pp[0]; - b->pPatch->ctrlAt(COL,i,j)[1] = (float)xyz[ii][j0+j].pp[1]; - b->pPatch->ctrlAt(COL,i,j)[2] = (float)xyz[ii][j0+j].pp[2]; - b->pPatch->ctrlAt(COL,i,j)[3] = (float)i; - b->pPatch->ctrlAt(COL,i,j)[4] = (float)j; - } - } - b->pPatch->UpdateCachedData(); -#endif - BrushNum++; - j0 += NV_patch-1; - } - i0 += NH_patch-1; - } - return BrushNum; -} - -//============================================================= -void MapBrushes() -{ - char hint[128]; - char skip[128]; - char sidetext[64]; - char surftext[64]; - char surftext2[64]; - char surft[64]; - float Steep; - vec3_t PlaneNormal,SurfNormal; - vec3_t t[2]; - int i, j, k; - int surf; - bool CheckAngle; - BRUSH brush; - XYZ v[8]; - - strcpy(surftext,Texture[Game][0]); - strcpy(sidetext,(strlen(Texture[Game][1]) ? Texture[Game][1] : Texture[Game][0])); - strcpy(surftext2,(strlen(Texture[Game][2]) ? Texture[Game][2] : Texture[Game][0])); - - // if surftext2 is identical to surftext, there's no need to - // check surface angle - if(!g_strcasecmp(surftext,surftext2)) - CheckAngle = FALSE; - else - { - CheckAngle = TRUE; - Steep = (float)cos((double)SlantAngle/57.2957795); - switch(Plane) - { - case PLANE_XY0: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_XY1: PlaneNormal[0]= 0.;PlaneNormal[1]= 0.;PlaneNormal[2]=-1.;break; - case PLANE_XZ0: PlaneNormal[0]= 0.;PlaneNormal[1]= 1.;PlaneNormal[2]= 1.;break; - case PLANE_XZ1: PlaneNormal[0]= 0.;PlaneNormal[1]=-1.;PlaneNormal[2]= 1.;break; - case PLANE_YZ0: PlaneNormal[0]= 1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - case PLANE_YZ1: PlaneNormal[0]=-1.;PlaneNormal[1]= 0.;PlaneNormal[2]= 1.;break; - } - } - - OpenFuncGroup(); - - for(i=0; i 0 && (Game != QUAKE3 || UsePatches==0) ) - { - MapOut(gNumNodes,gNumTris,gNode,gTri); - /* - ghCursorCurrent = ghCursorDefault; - SetCursor(ghCursorCurrent); - */ - return; - } - - contents = 0; - // HL doesn't have detail property - if((Game != HALFLIFE) && UseDetail) contents += CONTENTS_DETAIL; - // HL and Q3 don't have ladder property - if((Game != HALFLIFE && Game != QUAKE3) && UseLadder) contents += CONTENTS_LADDER; - // Genesis requires solid property to be set explicitly - if(Game == GENESIS3D) contents |= CONTENTS_SOLID; - // Heretic 2 uses different sounds (in surface props) for different texture types - if(Game == HERETIC2) - { - surface[0] = GetDefSurfaceProps(Texture[Game][0]); - surface[1] = GetDefSurfaceProps(Texture[Game][1]); - surface[2] = GetDefSurfaceProps(Texture[Game][2]); - } - else - { - surface[0] = 0; - surface[1] = 0; - surface[2] = 0; - } - if(Game!=QUAKE3 || UsePatches == 0) - MapBrushes(); - - /* - ghCursorCurrent = ghCursorDefault; - SetCursor(ghCursorCurrent); - */ -} - -//============================================================= -void GenerateXYZ() -{ - extern void MakeDecimatedMap(int *, int *, NODE **, TRI **); - double zl, zu; - double wh, wv; - int NHalfcycles; - double a,v,h,ha,va; - double delta, dr, rate; - double range, maxrange; - double r; - int i, j, k, N; - int i0, i1, j0, j1; - int ii, jj; - -// FILE *f; -// char CSV[64]; - - if(!ValidSurface()) return; - - srand(1); - srand(RandomSeed); - - dh = (Hur-Hll)/NH; - dv = (Vur-Vll)/NV; - - // H & V - for(i=0; i<=NH; i++) - { - for(j=0;j<=NV;j++) - { - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[0] = Hll + i*dh; - xyz[i][j].p[2] = Vll + j*dv; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[1] = Hll + i*dh; - xyz[i][j].p[2] = Vll + j*dv; - break; - default: - xyz[i][j].p[0] = Hll + i*dh; - xyz[i][j].p[1] = Vll + j*dv; - } - } - } - - if(WaveType == WAVE_BITMAP) - GenerateBitmapMapping(); - /* - else if(WaveType == WAVE_FORMULA) - DoFormula(); - */ - else - { - // Initialize Z values using bilinear interpolation - for(i=0; i<=NH; i++) - { - zl = Z00 + i*(Z10 - Z00)/NH; - zu = Z01 + i*(Z11 - Z01)/NH; - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - for(j=0; j<=NV; j++) - xyz[i][j].p[1] = zl + j*(zu-zl)/NV; - break; - case PLANE_YZ0: - case PLANE_YZ1: - for(j=0; j<=NV; j++) - xyz[i][j].p[0] = zl + j*(zu-zl)/NV; - break; - default: - for(j=0; j<=NV; j++) - xyz[i][j].p[2] = zl + j*(zu-zl)/NV; - } - } - } - - switch(WaveType) - { - case WAVE_COS_SIN: - if(FixBorders) - { - NHalfcycles = (int)((Hur-Hll)/(WaveLength/2.)); - NHalfcycles = max(NHalfcycles,1); - wh = 2.*(Hur-Hll)/NHalfcycles; - NHalfcycles = (int)((Vur-Vll)/(WaveLength/2.)); - wv = 2.*(Vur-Vll)/NHalfcycles; - NHalfcycles = max(NHalfcycles,1); - i0 = 1; - i1 = NH-1; - j0 = 1; - j1 = NV-1; - } - else - { - wh = WaveLength; - wv = WaveLength; - i0 = 0; - i1 = NH; - j0 = 0; - j1 = NV; - } - - for(i=i0; i<=i1; i++) - { - h = Hll + i*dh; - ha = ((h-Hll)/wh)*2.*PI - PI/2.; - for(j=j0; j<=j1; j++) - { - v = Vll + j*dv; - va = ((v-Vll)/wv)*2.*PI; - a = Amplitude * cos( ha ) * sin( va ); - switch(Plane) - { - case PLANE_XY1: - xyz[i][j].p[2] -= a; - break; - case PLANE_XZ0: - xyz[i][j].p[1] += a; - break; - case PLANE_XZ1: - xyz[i][j].p[1] -= a; - break; - case PLANE_YZ0: - xyz[i][j].p[0] += a; - break; - case PLANE_YZ1: - xyz[i][j].p[0] -= a; - break; - default: - xyz[i][j].p[2] += a; - } - } - } - break; - case WAVE_HCYLINDER: - for(i=0; i<=NH; i++) - { - h = Hll + i*dh; - ha = ((h-Hll)/WaveLength)*2.*PI - PI/2.; - for(j=0; j<=NV; j++) - { - a = Amplitude * cos( ha ); - switch(Plane) - { - case PLANE_XY1: - xyz[i][j].p[2] -= a; - break; - case PLANE_XZ0: - xyz[i][j].p[1] += a; - break; - case PLANE_XZ1: - xyz[i][j].p[1] -= a; - break; - case PLANE_YZ0: - xyz[i][j].p[0] += a; - break; - case PLANE_YZ1: - xyz[i][j].p[0] -= a; - break; - default: - xyz[i][j].p[2] += a; - } - } - } - break; - case WAVE_VCYLINDER: - for(i=0; i<=NH; i++) - { - h = Hll + i*dh; - for(j=0; j<=NV; j++) - { - v = Vll + j*dv; - va = ((v-Vll)/WaveLength)*2.*PI; - a = Amplitude * sin( va ); - switch(Plane) - { - case PLANE_XY1: - xyz[i][j].p[2] -= a; - break; - case PLANE_XZ0: - xyz[i][j].p[1] += a; - break; - case PLANE_XZ1: - xyz[i][j].p[1] -= a; - break; - case PLANE_YZ0: - xyz[i][j].p[0] += a; - break; - case PLANE_YZ1: - xyz[i][j].p[0] -= a; - break; - default: - xyz[i][j].p[2] += a; - } - } - } - break; - case WAVE_ROUGH_ONLY: - PlasmaCloud(); - break; - } - - if(WaveType != WAVE_ROUGH_ONLY) - { - // Fixed values - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - { - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[1] = xyz[i][j].fixed_value; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[0] = xyz[i][j].fixed_value; - break; - default: - xyz[i][j].p[2] = xyz[i][j].fixed_value; - } - - if(xyz[i][j].range > 0) - { - maxrange = pow(xyz[i][j].range,2); // so we don't have to do sqrt's - i0 = i - (int)( floor(xyz[i][j].range/dh - 0.5) + 1 ); - i1 = i + i - i0; - j0 = j - (int)( floor(xyz[i][j].range/dv - 0.5) + 1 ); - j1 = j + j - j0; - if(FixBorders) - { - i0 = max(i0,1); - i1 = min(i1,NH-1); - j0 = max(j0,1); - j1 = min(j1,NV-1); - } - else - { - i0 = max(i0,0); - i1 = min(i1,NH); - j0 = max(j0,0); - j1 = min(j1,NV); - } - for(ii=i0; ii<=i1; ii++) - { - for(jj=j0; jj<=j1; jj++) - { - if(ii==i && jj==j) continue; - range = pow( dh*(i-ii), 2) + pow( dv*(j-jj), 2); - if(range > maxrange) continue; - dr = sqrt(range/maxrange); - rate = max(-30.,min(xyz[i][j].rate,30.)); - if(rate < -1.) - { - delta = pow((1.-dr),-rate+1.); - } - else if(rate < 0.) - { - delta = (1+rate)*0.5*(cos(dr*PI)+1.0) - - rate*pow((1.-dr),2); - } - else if(rate == 0.) - { - delta = 0.5*(cos(dr*PI)+1.0); - } - else if(rate <= 1.) - { - delta = (1.-rate)*0.5*(cos(dr*PI)+1.0) + - rate*(1.-pow(dr,2)); - } - else - { - delta = 1.-pow(dr,rate+1); - } - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[ii][jj].p[1] += (xyz[i][j].p[1] - xyz[ii][jj].p[1])*delta; - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[ii][jj].p[0] += (xyz[i][j].p[0] - xyz[ii][jj].p[0])*delta; - break; - default: - xyz[ii][jj].p[2] += (xyz[i][j].p[2] - xyz[ii][jj].p[2])*delta; - } - } - } - } - } - } - } - } - - if((Roughness > 0.) && (WaveType != WAVE_ROUGH_ONLY) ) - { - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(CanEdit(i,j) && !xyz[i][j].fixed) - { - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xyz[i][j].p[1] += -Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX); - break; - case PLANE_YZ0: - case PLANE_YZ1: - xyz[i][j].p[0] += -Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX); - break; - default: - xyz[i][j].p[2] += -Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX); - } - } - else - r = rand(); // We still get a random number, so that fixing points - // doesn't change the sequence. - - } - } - } - - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - for(k=0; k<3; k++) - { - xyz[i][j].p[k] = Nearest(xyz[i][j].p[k],2.0); - } - } - } - - // Find minima and maxima - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - xmin = Hll; - xmax = Hur; - zmin = Vll; - zmax = Vur; - ymin = xyz[0][0].p[1]; - ymax = ymin; - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - ymin = min(ymin,xyz[i][j].p[1]); - ymax = max(ymax,xyz[i][j].p[1]); - } - } - break; - case PLANE_YZ0: - case PLANE_YZ1: - ymin = Hll; - ymax = Hur; - zmin = Vll; - zmax = Vur; - xmin = xyz[0][0].p[0]; - xmax = ymin; - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xmin = min(xmin,xyz[i][j].p[0]); - xmax = max(xmax,xyz[i][j].p[0]); - } - } - break; - break; - default: - xmin = Hll; - xmax = Hur; - ymin = Vll; - ymax = Vur; - zmin = xyz[0][0].p[2]; - zmax = zmin; - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - zmin = min(zmin,xyz[i][j].p[2]); - zmax = max(zmax,xyz[i][j].p[2]); - } - } - } - - xmin = Nearest(xmin,2.); - xmax = Nearest(xmax,2.); - ymin = Nearest(ymin,2.); - ymax = Nearest(ymax,2.); - zmin = Nearest(zmin,2.); - zmax = Nearest(zmax,2.); - - switch(Plane) - { - case PLANE_XY1: - backface = AtLeast(zmax+32.,32.); - break; - case PLANE_XZ0: - backface = NoMoreThan(ymin-32.,32.); - break; - case PLANE_XZ1: - backface = AtLeast(ymax+32.,32.); - break; - case PLANE_YZ0: - backface = NoMoreThan(xmin-32.,32.); - break; - case PLANE_YZ1: - backface = AtLeast(xmax+32.,32.); - break; - default: - backface = NoMoreThan(zmin-32.,32.); - } - - if(gNode) - { - free(gNode); - free(gTri); - gNode = (NODE *)NULL; - gTri = (TRI *)NULL; - } - if(Decimate > 0 && (Game != QUAKE3 || UsePatches==0) ) - { - MakeDecimatedMap(&gNumNodes,&gNumTris,&gNode,&gTri); - } - else - { - gNumNodes = (NH+1)*(NV+1); - gNumTris = NH*NV*2; - gNode = (NODE *) malloc(gNumNodes * sizeof(NODE)); - gTri = (TRI *) malloc(gNumTris * sizeof(TRI)); - - for(i=0,N=0; i<=NH; i++) - { - for(j=0; j<=NV; j++, N++) - { - gNode[N].used = 1; - gNode[N].p[0] = (float)xyz[i][j].p[0]; - gNode[N].p[1] = (float)xyz[i][j].p[1]; - gNode[N].p[2] = (float)xyz[i][j].p[2]; - } - } - - for(i=0; i 0) - { - for(i=0; i x) xx -= dx; - return xx; -} -//============================================================= -double AtLeast(double x, double dx) -{ - double xx; - - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - if(xx < x) xx += dx; - return xx; -} -//============================================================= -double LessThan(double x,double dx) -{ - double xx; - - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - if(xx >= x) xx -= dx; - return xx; -} -//============================================================= -double MoreThan(double x,double dx) -{ - double xx; - - xx = (double)(floor(x/dx - 0.5)+1.)*dx; - while(xx <= x) - xx += dx; - return xx; -} -//============================================================= -void SubdividePlasma(int i0,int j0,int i1,int j1) -{ - int i, j; - double z1, z2; - double r; // NOTE: This is used to keep the random number sequence the same - // when we fix a point. If we did NOT do this, then simply - // fixing a point at its current value would change the entire - // surface. - - i = (i0+i1)/2; - j = (j0+j1)/2; - if(i1 > i0+1) - { - if(!xyz[i][j0].done) - { - xyz[i][j0].pp[2] = xyz[i0][j0].pp[2] + - (xyz[i1][j0].pp[2] - xyz[i0][j0].pp[2])*(double)(i-i0)/(double)(i1-i0) + - ((double)(i-i0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i][j0].done = 1; - } - else - r = rand(); - if((j1 > j0) && (!xyz[i][j1].done) ) - { - xyz[i][j1].pp[2] = xyz[i0][j1].pp[2] + - (xyz[i1][j1].pp[2] - xyz[i0][j1].pp[2])*(double)(i-i0)/(double)(i1-i0) + - ((double)(i-i0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i][j1].done = 1; - } - else - r = rand(); - } - if(j1 > j0 + 1) - { - if(!xyz[i0][j].done) - { - xyz[i0][j].pp[2] = xyz[i0][j0].pp[2] + - (xyz[i0][j1].pp[2] - xyz[i0][j0].pp[2])*(double)(j-j0)/(double)(j1-j0) + - ((double)(j-j0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i0][j].done = 1; - } - else - r = rand(); - if((i1 > i0) && (!xyz[i1][j].done)) - { - xyz[i1][j].pp[2] = xyz[i1][j0].pp[2] + - (xyz[i1][j1].pp[2] - xyz[i1][j0].pp[2])*(double)(j-j0)/(double)(j1-j0) + - ((double)(j-j0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i1][j].done = 1; - } - else - r = rand(); - } - if((i1 > i0+1) && (j1 > j0+1)) - { - if(!xyz[i][j].done) - { - z1 = xyz[i0][j].pp[2] + - (xyz[i1][j].pp[2] - xyz[i0][j].pp[2])*(double)(i-i0)/(double)(i1-i0); - z2 = xyz[i][j0].pp[2] + - (xyz[i][j1].pp[2] - xyz[i][j0].pp[2])*(double)(j-j0)/(double)(j1-j0); - xyz[i][j].pp[2] = (z1+z2)/2. + - ((double)(i-i0))*(-Roughness/2. + Roughness*((double)rand()/(double)RAND_MAX)); - xyz[i][j].done = 1; - } - else - r = rand(); - } - if(i > i0+1 || j > j0+1) - SubdividePlasma(i0,j0,i,j); - if(i1 > i+1 || j > j0+1) - SubdividePlasma(i,j0,i1,j); - if(i > i0+1 || j1 > j0+1) - SubdividePlasma(i0,j,i,j1); - if(i1 > i+1 || j1 > j0+1) - SubdividePlasma(i,j,i1,j1); -} -//================================================================================== -void PlasmaCloud() -{ - int i, j; - /* use pp[2] values until done to avoid messing with a bunch of - switch statements */ - - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(FixedPoint(i,j)) - xyz[i][j].done = 1; - else - xyz[i][j].done = 0; - } - } - - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - xyz[i][j].pp[2] = xyz[i][j].fixed_value; - else - xyz[i][j].pp[2] = xyz[i][j].p[1]; - } - } - break; - case PLANE_YZ0: - case PLANE_YZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - xyz[i][j].pp[2] = xyz[i][j].fixed_value; - else - xyz[i][j].pp[2] = xyz[i][j].p[0]; - } - } - break; - default: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - xyz[i][j].pp[2] = xyz[i][j].fixed_value; - else - xyz[i][j].pp[2] = xyz[i][j].p[2]; - } - } - break; - } - SubdividePlasma(0,0,NH,NV); - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].p[1] = xyz[i][j].pp[2]; - } - } - break; - case PLANE_YZ0: - case PLANE_YZ1: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].p[0] = xyz[i][j].pp[2]; - } - } - break; - default: - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - xyz[i][j].p[2] = xyz[i][j].pp[2]; - } - } - break; - } -} -//=========================================================================== -bool FixedPoint(int i, int j) -{ - if(xyz[i][j].fixed) return TRUE; - return !CanEdit(i,j); -} -//=========================================================================== -bool CanEdit(int i, int j) -{ - if(FixBorders && ( (WaveType==WAVE_COS_SIN) || (WaveType==WAVE_ROUGH_ONLY) ) ) - { - if(i== 0) return FALSE; - if(i==NH) return FALSE; - if(j== 0) return FALSE; - if(j==NV) return FALSE; - } - if(i== 0 && j== 0) return FALSE; - if(i==NH && j== 0) return FALSE; - if(i== 0 && j==NV) return FALSE; - if(i==NH && j==NV) return FALSE; - return TRUE; -} -/*============================================================================ - TriangleFromPoint - Determines which triangle in the gTri array bounds the input point. Doesn't - do anything special with border points. -*/ -int TriangleFromPoint(double x, double y) -{ - int j, tri; - - if(!gTri) return -1; - - for(j=0, tri=-1; jp[0],2.); - v[0][1] = (vec)Nearest(xyz->p[1],2.); - v[0][2] = (vec)Nearest(xyz->p[2],2.); -} - -//============================================================= -scene::Node* MakePatch(void) -{ - scene::Node* patch = Patch_AllocNode(); -#if 0 - patch->m_patch->SetShader(Texture[Game][0]); -#endif - Node_getTraversable(h_worldspawn)->insert(patch); - return patch; -} - -//============================================================= -void MakeBrush(BRUSH *brush) -{ - NodePtr node(Brush_AllocNode()); - -#if 0 - for(int i=0; iNumFaces; i++) - { - _QERFaceData QERFaceData; - if(!strncmp(brush->face[i].texture, "textures/", 9)) - strcpy(QERFaceData.m_TextureName,brush->face[i].texture); - else - { - strcpy(QERFaceData.m_TextureName,"textures/"); - strcpy(QERFaceData.m_TextureName+9,brush->face[i].texture); - } - QERFaceData.m_nContents = brush->face[i].Contents; - QERFaceData.m_nFlags = brush->face[i].Surface; - QERFaceData.m_nValue = brush->face[i].Value; - QERFaceData.m_fShift[0] = brush->face[i].Shift[0]; - QERFaceData.m_fShift[1] = brush->face[i].Shift[1]; - QERFaceData.m_fRotate = brush->face[i].Rotate; - QERFaceData.m_fScale[0] = brush->face[i].Scale[0]; - QERFaceData.m_fScale[1] = brush->face[i].Scale[1]; - QERFaceData.m_v1[0] = brush->face[i].v[0][0]; - QERFaceData.m_v1[1] = brush->face[i].v[0][1]; - QERFaceData.m_v1[2] = brush->face[i].v[0][2]; - QERFaceData.m_v2[0] = brush->face[i].v[1][0]; - QERFaceData.m_v2[1] = brush->face[i].v[1][1]; - QERFaceData.m_v2[2] = brush->face[i].v[1][2]; - QERFaceData.m_v3[0] = brush->face[i].v[2][0]; - QERFaceData.m_v3[1] = brush->face[i].v[2][1]; - QERFaceData.m_v3[2] = brush->face[i].v[2][2]; - QERFaceData.m_bBPrimit = false; - (g_FuncTable.m_pfnAddFaceData)(vp,&QERFaceData); - } -#endif - - Node_getTraversable(h_func_group)->insert(node); -} -//============================================================= -void OpenFuncGroup() -{ - h_func_group = GlobalEntityCreator().createEntity("func_group"); - h_func_group->IncRef(); - if(AddTerrainKey) - h_func_group->m_entity->setkeyvalue("terrain", "1"); -} -//============================================================= -void CloseFuncGroup() -{ - h_func_group->DecRef(); - if (g_FuncTable.m_pfnSysUpdateWindows != NULL) - g_FuncTable.m_pfnSysUpdateWindows (W_ALL); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gensurf.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gensurf.cpp deleted file mode 100644 index 3c3107aa..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/gensurf.cpp +++ /dev/null @@ -1,469 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include -/* -#include -#include -#include -*/ -#include "gensurf.h" - -char gszAppDir[NAME_MAX]; -char gszCaption[64]; -char gszIni[NAME_MAX]; -char gszHelpFile[NAME_MAX]; -char gszMapFile[NAME_MAX]; -char gszVersion[64]; -double Amplitude; -double Roughness; -double TexOffset[2]; -double TexScale[2]; -double WaveLength; -double Hll, Hur, Vll, Vur; -double Z00, Z01, Z10, Z11; -ELEMENT Vertex[(MAX_ROWS+1)*(MAX_ROWS+1)]; -int AddHints; -int ArghRad2; -int AutoOverwrite; -int Decimate=0; -int SnapToGrid=0; // 0, or the grid size to snap to. // Hydra : snap to grid -int FileAppend=0; -int FixBorders; -int HideBackFaces=0; -int NH, NV; -int NumVerticesSelected; -int Plane; -int Preview; -int RandomSeed=1; -int Skybox; -int UseDetail; -int UseLadder; -int VertexMode=0; -int WaveType; -int gNumNodes=0; -int gNumTris=0; -int vid_x, vid_y; -int view_x, view_y; -int view_cx, view_cy; -int UsePatches; -int SlantAngle; -int GimpHints; -int Antialiasing; // ^Fishman - Antializing for the preview window. -int AddTerrainKey; // ^Fishman - Add terrain key to func_group. -int SP; // ^Fishman - Snap to grid. - -GtkWidget *g_pWnd; // ghwnd; -GtkWidget *g_pRadiantWnd; // ghwnd_main; -/*HWND ghwndAngles; -*/GtkWidget *g_pWndPreview; -GtkWidget *g_pPreviewWidget; -MYBITMAP gbmp; -NODE *gNode=(NODE *)NULL; -TRI *gTri=(TRI *)NULL; - -int Game; -bounding_box PlayerBox[NUMGAMES] = { {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Quake2 - {{-16., 16.}, {-16., 16.}, {-36., 36.}}, // Half-Life - {{-16., 16.}, {-16., 16.}, {-32., 32.}}, // SiN - {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // Heretic2 (guess) - {{-16., 16.}, {-16., 16.}, {-24., 32.}}, // KingPin (guess) - {{-30., 30.}, {-30., 30.}, {-10.,160.}}, // Genesis3D (no idea) - {{-16., 16.}, {-16., 16.}, {-24., 32.}}}; // Quake3 (not sure) -//char gszOutputDir[NUMGAMES][NAME_MAX]; -//char gszTextureDir[NUMGAMES][NAME_MAX]; -char Texture[NUMGAMES][3][64]; -//char pakfile[NUMGAMES][NAME_MAX]; -//char lastpakfile[NUMGAMES][NAME_MAX]; -//int UsePak[NUMGAMES]; -//char GameDir[NUMGAMES][NAME_MAX]; - -char GameName[NUMGAMES][16] = {"Quake2", "Half-Life", "SiN", "Heretic2", "Kingpin", "Genesis3D", "Quake3" }; - - -bool GenSurfInit () -{ - strcpy (gszVersion, "1.05"); - strcpy (gszCaption, "GtkGenSurf"); - if (strlen (gszVersion)) - { - strcat (gszCaption, " v"); - strcat (gszCaption, gszVersion); - } - - strcpy (gszIni, g_FuncTable.m_pfnProfileGetDirectory ()); - strcat (gszIni, "gensurf.ini"); - -/*if (g_FuncTable.m_pfnReadProjectKey != NULL) - { - char *basepath; - - basepath = g_FuncTable.m_pfnReadProjectKey("basepath"); - if (basepath) - { - g_strdown (basepath); - if (strstr(basepath,"baseq3")) - Game = QUAKE3; - else if (strstr (basepath,"baseq2")) - Game = QUAKE2; - else // Gotta have a game, might as well be Quake3 - Game = QUAKE3; - } - else - Game = QUAKE3; - } - else */ - Game = QUAKE3; - - - if (g_pWnd == NULL) - g_pWnd = create_main_dialog (); - - ReadIniFile (gszIni); - - return true; -} - -// Reads default values - -#define OPTS_SECTION "Options" - -void ReadIniFile (const char *file) -{ - char *Text; - float x1,x2,x3,x4; - int i; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "Amplitude", ""); - if (strlen (Text)) - Amplitude = atof (Text); - else - Amplitude = 128; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "Roughness", ""); - if (strlen (Text)) - Roughness = atof (Text); - else - Roughness = 16; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "WaveLength", ""); - if (strlen (Text)) - WaveLength = atof (Text); - else - WaveLength = 1024; - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "Extents", ""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f,%f,%f",&x1,&x2,&x3,&x4); - Hll = x1; - Vll = x2; - Hur = x3; - Vur = x4; - } - else - { - Hll = -512; - Vll = -512; - Hur = 512; - Vur = 512; - } - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "CornerValues", ""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f,%f,%f",&x1,&x2,&x3,&x4); - Z00 = x1; - Z01 = x2; - Z10 = x3; - Z11 = x4; - } - else - { - Z00 = 0.; - Z01 = 0.; - Z10 = 0.; - Z11 = 0.; - } - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION, "TextureOffset", ""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f",&x1,&x2); - TexOffset[0] = x1; - TexOffset[1] = x2; - } - else - { - TexOffset[0] = 0.; - TexOffset[1] = 0.; - } - - Text = g_FuncTable.m_pfnProfileLoadString (file, OPTS_SECTION,"TextureScale",""); - if (strlen (Text)) - { - sscanf(Text,"%f,%f",&x1,&x2); - TexScale[0] = x1; - TexScale[1] = x2; - if(TexScale[0] == 0.) TexScale[0] = 1.0; - if(TexScale[1] == 0.) TexScale[1] = 1.0; - } - else - { - TexScale[0] = 1.; - TexScale[1] = 1.; - } - - NH = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"NH",8); - NH = max(1,min(NH,MAX_ROWS)); - NV = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"NV",8); - NV = max(1,min(NV,MAX_ROWS)); - -// Decimate = GetPrivateProfileInt(OPTS_SECTION,"Decimate",0,file); -// Decimate = max(0,min(Decimate,100)); - - AddHints = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"AddHints",0); - ArghRad2 = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"ArghRad2",0); - AutoOverwrite = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"AutoOverwrite",0); - FixBorders = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"FixBorders",1); - HideBackFaces = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"HideBackFaces",0); - Plane = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Plane",0); - Preview = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Preview", 0); - Antialiasing = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Antialiasing",0); // ^Fishman - Antializing for the preview window. - RandomSeed = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"RandomSeed",1); - Skybox = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"Skybox",0); - UseDetail = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"UseDetail",0); - AddTerrainKey = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"AddTerrainKey",0); // ^Fishman - Add terrain key to func_group. - UseLadder = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"UseLadder",0); - WaveType = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"WaveType",0); - vid_x = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"vid_x", 0); - vid_y = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"vid_y", 0); - view_x = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_x",0); - view_y = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_y",0); - view_cx = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_cx",0); - view_cy = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"view_cy",0); - - UsePatches = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"UsePatches",0); - - SlantAngle = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"SlantAngle",60); - GimpHints = g_FuncTable.m_pfnProfileLoadInt (file, OPTS_SECTION,"GimpHints",0); - - for(i=0; i -#include "qertypes.h" -#include - -#include "mathlib.h" -#include "iscenegraph.h" -#define USE_QERTABLE_DEFINE -#include "qerplugin.h" -extern _QERFuncTable_1 g_FuncTable; - -#include "irender.h" -#include "iselection.h" - -#define USE_ENTITYTABLE_DEFINE -#include "ientity.h" -extern _QEREntityTable __ENTITYTABLENAME; - -#define USE_PATCHTABLE_DEFINE -#include "ipatch.h" -extern _QERPatchTable __PATCHTABLENAME; - -#define USE_BRUSHTABLE_DEFINE -#include "ibrush.h" -extern _QERBrushTable __BRUSHTABLENAME; - -#include "igl.h" -#include "ientity.h" - -#include - -#include "iui_gtk.h" - -#include "gendlgs.h" - - -#define PLUGIN -#define Q3RADIANT - -//#if defined(__linux__) || defined(__APPLE__) -#if 1 -#include -#else -template -inline T min (T x, T y) { return (x < y) ? x : y; } -template -inline T max (T x, T y) { return (x > y) ? x : y; } -#endif - -typedef struct { long x, y; } Point; -typedef struct { long left, top, right, bottom; } Rect; - -#define NAME_MAX 255 - -typedef void* LPVOID; -typedef char* LPSTR; - -//#endif -inline bool PtInRect (Rect *rc, Point pt) -{ - if (pt.x < rc->left) return false; - if (pt.x > rc->right) return false; - if (pt.y < rc->bottom) return false; - if (pt.y > rc->top) return false; - return true; -} - -#define NUMGAMES 7 - -#define CONTENTS_SOLID 0x00000001 -#define CONTENTS_DETAIL 0x08000000 // brushes to be added after vis leafs -#define CONTENTS_LADDER 0x20000000 -#define SURF_HINT 0x100 // make a primary bsp splitter -#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes -#define HINT_OFFSET 96 - -#define PI 3.14159265358979224 -#define RadiansToDegrees(a) (floor(a*57.2957795 - 0.5)+1.) -#define DegreesToRadians(a) (a/57.2957795) - -#define BOGUS_RANGE 65536 -/* -#define DotProduct(x,y) (x[0]*y[0]+x[1]*y[1]+x[2]*y[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 VectorClear(x) {x[0] = x[1] = x[2] = 0;} -#define VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];} -#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[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 XYZVectorSubtract(a,b,c) {c[0]=(float)a[0]-(float)b[0];c[1]=(float)a[1]-(float)b[1];c[2]=(float)a[2]-(float)b[2];} -#define side(u1,v1,u2,v2,u3,v3) (v3-v1)*(u2-u1) - (u3-u1)*(v2-v1) - -#define QUAKE2 0 -#define HALFLIFE 1 -#define SIN 2 -#define HERETIC2 3 -#define KINGPIN 4 -#define GENESIS3D 5 -#define QUAKE3 6 - -#define MAX_FACES_PER_BRUSH 6 -#define SLIVER_ANGLE DegreesToRadians(20) -#define MAX_NODES (MAX_ROWS+1)*(MAX_ROWS+1) -#define MAX_TRIS (MAX_ROWS)*(MAX_ROWS) - -typedef float vec; -typedef vec vec3[3]; -typedef vec vec2[2]; - -typedef struct -{ - vec3 v[3]; - char texture[64]; - float Shift[2]; - float Rotate; - float Scale[2]; - int Contents; - int Surface; - int Value; -} FACE; - -typedef struct -{ - vec3 normal; - vec dist; -} PLANE; - -typedef struct -{ - int numpoints; - vec3 p[4]; // variable sized -} MY_WINDING; - -typedef struct -{ - int Number; - int NumFaces; - FACE face[MAX_FACES_PER_BRUSH]; -} BRUSH; - -typedef struct tagXYZ -{ - int fixed; - int done; - double p[3]; - double pp[3]; // these used only for general 3D projection (not isometric) - double fixed_value; - double range; - double rate; -} XYZ; - -// Q2 PAK file structures -typedef struct -{ - char id[4]; // Should be 'PACK' - int dstart; // Offest in the file to the directory - int dsize; // Size in bytes of the directory, same as num_items*64 -} pak_header_t; - -typedef struct -{ - char name[56]; // The name of the item, normal C string - int start; // Offset in .pak file to start of item - int size; // Size of item in bytes -} pak_item_t; - -// SiN .SIN structures -#define SINPAKHEADER (('K'<<24)+('A'<<16)+('P'<<8)+'S') -#define MAX_PAK_FILENAME_LENGTH 120 - -typedef struct -{ - char name[MAX_PAK_FILENAME_LENGTH]; - int filepos, filelen; -} dpackfile_t; - -typedef struct -{ - int ident; // == IDPAKHEADER - int dirofs; - int dirlen; -} dpackheader_t; - -// Half-Life WAD file structures -typedef struct -{ - char identification[4]; // should be WAD2 or 2DAW - int numlumps; - int infotableofs; -} wadinfo_t; - -typedef struct -{ - int filepos; - int disksize; - int size; // uncompressed - char type; - char compression; - char pad1, pad2; - char name[16]; // must be null terminated -} lumpinfo_t; - -typedef struct -{ - int signature; - short version; - short bitflag; - short compression_method; - short modfiletime; - short modfiledate; - int crc; - int compressed_size; - int uncompressed_size; - short filename_size; - short extra_size; -} zipheader_t; - -typedef struct -{ - double x[2]; - double y[2]; - double z[2]; -} bounding_box; - -typedef struct -{ - float p[3]; - int used; - int tri; - float error; - int fixed; -} NODE; - -typedef struct -{ - int v[3]; - int n[3]; // indices of neighboring triangles - PLANE plane; - int flag; - float min[3]; - float max[3]; -} TRI; - -//--------------- bitmap.c ----------------------------- -bool OpenBitmap (); -double CalculateSnapValue(double value); -void GenerateBitmapMapping (); -//--------------- face.c ------------------------------- -void PlaneFromPoints (float *, float *, float *, PLANE *); -//void CrossProduct (vec3 v1, vec3 v2, vec3 cross); -//vec VectorNormalize (vec3 in, vec3 out); -//--------------- gendlg.c ----------------------------- -GtkWidget* create_main_dialog (); -void About (GtkWidget *parent); -//--------------- genmap.c ----------------------------- -double AtLeast(double,double); -bool CanEdit(int, int); -void CloseFuncGroup(); -bool FixedPoint(int,int); -void GenerateMap(); -void GenerateXYZ(); -double LessThan(double,double); -void MakeBrush(BRUSH *); -double MoreThan(double,double); -double Nearest(double,double); -double NoMoreThan(double,double); -void OpenFuncGroup(); -void PlasmaCloud(); -int PlayerStartZ(double,double); -void SubdividePlasma(int,int,int,int); -bool ValidSurface(); -void XYZtoV(XYZ *, vec3 *); -scene::Node* MakePatch(void); - -//---------------- gensurf.c --------------------------- -bool GenSurfInit (); -void ReadIniFile (const char *); -void WriteIniFile (const char *); -void OpenSetup (GtkWidget*,int); -void SaveSetup (GtkWidget*); -//---------------- heretic.c --------------------------- -int GetDefSurfaceProps(char *); -//---------------- view.c ------------------------------ -void CreateViewWindow (); -void DrawGrid(Rect); -void DrawPreview(Rect); -void evaluate(); -void GetScaleFactor(Rect); -void project(XYZ *); -void Scale(Rect,XYZ,Point *); -void ShowPreview (); -void UpdatePreview (bool); - -//---------------- plugin.c ----------------------------- -void UseFaceBounds(); - -extern _QERFuncTable_1 g_FuncTable; -extern _QERQglTable g_GLTable; -extern _QERUIGtkTable g_UIGtkTable; -extern _QEREntityTable g_EntityTable; -//#define MAX_ROWS 64 -#define MAX_ROWS 128 - -#define PLANE_XY0 0 -#define PLANE_XY1 1 -#define PLANE_YZ0 2 -#define PLANE_XZ0 3 -#define PLANE_YZ1 4 -#define PLANE_XZ1 5 - -#define WAVE_COS_SIN 0 -#define WAVE_HCYLINDER 1 -#define WAVE_VCYLINDER 2 -#define WAVE_BITMAP 3 -#define WAVE_ROUGH_ONLY 4 -#define WAVE_FORMULA 5 -#define WAVE_FIRST WAVE_COS_SIN -#define WAVE_LAST WAVE_FORMULA -#define DLG_WAVE_LAST DLG_WAVE_01+WAVE_LAST-WAVE_FIRST - -#define MSG_VERTEX_SELECTED WM_USER+1 - -typedef struct tagMYBITMAP -{ - char name[NAME_MAX]; - char defpath[NAME_MAX]; - double black_value; - double white_value; - int width, height; - unsigned char* colors; -} MYBITMAP; - -typedef struct tagELEMENT { - int i; - int j; -} ELEMENT; - -extern char gszAppDir[NAME_MAX]; -extern char gszCaption[64]; -extern char gszHelpFile[NAME_MAX]; -extern char gszIni[NAME_MAX]; -extern char gszMapFile[NAME_MAX]; -extern char gszVersion[64]; -extern double Amplitude; -extern double Roughness; -extern double TexOffset[2]; -extern double TexScale[2]; -extern double WaveLength; -extern double Hll, Hur, Vll, Vur; -extern double Z00, Z01, Z10, Z11; -extern double yaw, pitch, roll; -extern ELEMENT Vertex[(MAX_ROWS+1)*(MAX_ROWS+1)]; -extern int AddHints; -extern int ArghRad2; -extern int AutoOverwrite; -extern int Decimate; -extern int FileAppend; -extern int FixBorders; -extern int HideBackFaces; -extern int NH, NV; -extern int NumVerticesSelected; -extern int Plane; -extern int Preview; -extern int RandomSeed; -extern int Skybox; -extern int UseDetail; -extern int UseLadder; -extern int VertexMode; -extern int vid_x, vid_y; -extern int WaveType; -extern int gNumNodes; -extern int gNumTris; -extern int view_x, view_y; -extern int view_cx, view_cy; -extern int UsePatches; -extern int SlantAngle; -extern int GimpHints; -extern int Antialiasing; // ^Fishman - Antializing for the preview window. -extern int AddTerrainKey; // ^Fishman - Add terrain key to func_group. -extern int SnapToGrid; // Hydra : snap to grid -extern int SP; // ^Fishman - Snap to grid. - - -/*extern HCURSOR ghCursorCurrent; -extern HCURSOR ghCursorDefault; -extern HCURSOR ghCursorVertex; -extern HINSTANCE ghInst;*/ -extern GtkWidget *g_pRadiantWnd; -extern GtkWidget *g_pWnd; -/*extern HWND ghwndAngles; -extern HWND ghwndFix; -*/extern GtkWidget *g_pWndPreview; -extern GtkWidget *g_pPreviewWidget; -extern MYBITMAP gbmp; -extern NODE *gNode; -extern TRI *gTri; -extern XYZ xyz[MAX_ROWS+1][MAX_ROWS+1]; - -extern int Game; -extern bounding_box PlayerBox[NUMGAMES]; -//extern char gszOutputDir[NUMGAMES][NAME_MAX]; -extern char Texture[NUMGAMES][3][64]; -//extern char gszTextureDir[NUMGAMES][NAME_MAX]; -extern char GameName[NUMGAMES][16]; -//extern char pakfile[NUMGAMES][NAME_MAX]; -//extern char lastpakfile[NUMGAMES][NAME_MAX]; -//extern int UsePak[NUMGAMES]; -//extern char GameDir[NUMGAMES][NAME_MAX]; -//extern char ExcelFunc[1024]; - -#endif // _GENSURF_H_ diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/heretic.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/heretic.cpp deleted file mode 100644 index 4fb19a23..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/heretic.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include -#include "gensurf.h" - -// Heretic 2 - specific routines - -typedef struct palette_s -{ - guint8 r,g,b; -} palette_t; - -#define MIP_VERSION 2 -#define PAL_SIZE 256 -#define MIPLEVELS 16 - -typedef struct miptex_s -{ - int version; - char name[32]; - unsigned width[MIPLEVELS], height[MIPLEVELS]; - unsigned offsets[MIPLEVELS]; // four mip maps stored - char animname[32]; // next frame in animation chain - palette_t palette[PAL_SIZE]; - int flags; - int contents; - int value; -} miptex_t; - -//============================================================= -int GetDefSurfaceProps(char *Tex) -{ - return 0; // leo: only used for Heretic 2, fix later - /* - char path[NAME_MAX]; - char *p; - int flags; - miptex_t *mt; - FILE *f; - int length; - int pos; - - if(Game != HERETIC2) return 0; - if(!strlen(Tex)) return 0; - - mt = NULL; - flags = 0; - if(UsePak[Game]) - { - FILE *fpak; - pak_header_t pakheader; - pak_item_t pakitem; - int i; - int num; - int numitems; - - if (NULL != (fpak = fopen(pakfile[Game], "rb"))) - { - sprintf(path,"textures/%s.m8",Tex); - g_strdown(path); - num=fread(&pakheader,1,sizeof(pak_header_t),fpak); - if((size_t)num < sizeof(pak_header_t)) - { - fclose(fpak); - return 0; - } - if(strncmp(pakheader.id,"PACK",4)) - { - fclose(fpak); - return 0; - } - numitems = pakheader.dsize/sizeof(pak_item_t); - fseek(fpak,pakheader.dstart,SEEK_SET); - for(i=0; iflags; - free(mt); - } - } - } - fclose(fpak); - } - } - else - { - // Assume .map will be output to gamedir/maps, then back up - // to the gamedir and append /textures. Ugly but it should work - strcpy(path,gszMapFile); - g_strdown(path); - p = strstr(path,"maps"); - if(!p) return 0; - p[0] = '\0'; - strcat(path,"textures/"); - strcat(path,Tex); - strcat(path,".m8"); - f = fopen (path, "rb"); - if (!f) - flags = 0; - else - { - pos = ftell (f); - fseek (f, 0, SEEK_END); - length = ftell (f); - fseek (f, pos, SEEK_SET); - if((mt = (miptex_t*)malloc(length+1))==NULL) - flags = 0; - else - { - ((char *)mt)[length] = 0; - fread(mt, 1, length, f); - fclose (f); - flags = mt->flags; - free(mt); - } - } - } - return flags; - */ -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/plugin.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/plugin.cpp deleted file mode 100644 index 18e12091..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/plugin.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "gensurf.h" - -// Global plugin FuncTable -_QERFuncTable_1 g_FuncTable; -_QERQglTable g_GLTable; -_QERUIGtkTable g_UIGtkTable; -_QEREntityTable __ENTITYTABLENAME; -_QERBrushTable __BRUSHTABLENAME; -_QERPatchTable __PATCHTABLENAME; -bool SingleBrushSelected; -bool g_bInitDone; - -#include "iplugin.h" - -const char* QERPlug_Init(void* hApp, void* pMainWidget) -{ - g_pRadiantWnd = (GtkWidget*)pMainWidget; - - return "GenSurf for Q3Radiant"; -} - -const char* QERPlug_GetName () -{ - return "GtkGenSurf"; -} - -const char* QERPlug_GetCommandList () -{ - return "Wall facing 270...;Wall facing 180...;Wall facing 90...;Wall facing 0...;" - "Ceiling...;Ground surface...;-;About..."; -} - -// vMin/vMax provide the bounds of the selection, they are zero if there is no selection -// if there is a selection, bSingleBrush will be true if a single brush is selected -// if so, typical plugin behaviour (such as primitive creation) would use the bounds as -// a rule to create the primitive, then delete the selection -void QERPlug_Dispatch (const char *p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - bool Generate = false; - - if (!g_bInitDone) - { - if (GenSurfInit ()) - g_bInitDone = true; - } - - if (!strcmp (p, "Ground surface...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XY0; - if (SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[1]; - Hur = vMax[0]; - Vur = vMax[1]; - Z00 = Z01 = Z10 = Z11 = vMax[2]; - } - Generate = true; - } - else if (!strcmp (p, "Ceiling...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XY1; - if(SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[1]; - Hur = vMax[0]; - Vur = vMax[1]; - Z00 = Z01 = Z10 = Z11 = vMin[2]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 0...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_YZ0; - if (SingleBrushSelected) - { - Hll = vMin[1]; - Vll = vMin[2]; - Hur = vMax[1]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMax[0]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 90...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XZ0; - if (SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[2]; - Hur = vMax[0]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMax[1]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 180...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_YZ1; - if (SingleBrushSelected) - { - Hll = vMin[1]; - Vll = vMin[2]; - Hur = vMax[1]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMin[0]; - } - Generate = true; - } - else if (!strcmp (p, "Wall facing 270...")) - { - SingleBrushSelected = bSingleBrush; - Plane = PLANE_XZ1; - if (SingleBrushSelected) - { - Hll = vMin[0]; - Vll = vMin[2]; - Hur = vMax[0]; - Vur = vMax[2]; - Z00 = Z01 = Z10 = Z11 = vMin[1]; - } - Generate = true; - } - else if (!strcmp(p,"About...")) - About (g_pRadiantWnd); - - if (Generate) - { - if (SingleBrushSelected) - UseFaceBounds (); - - gtk_widget_show (g_pWnd); - } -} - -// ============================================================================= -// SYNAPSE - -#include "synapse.h" - -class GenSurfSynapseClient : public CSynapseClient -{ -public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - - GenSurfSynapseClient() { } - virtual ~GenSurfSynapseClient() { } -}; - -CSynapseServer* g_pSynapseServer = NULL; -GenSurfSynapseClient g_SynapseClient; - -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(PLUGIN_MAJOR, "gtkgensurf", sizeof(_QERPluginTable)); - - g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(_QERFuncTable_1), SYN_REQUIRE, &g_FuncTable); - g_SynapseClient.AddAPI(UIGTK_MAJOR, NULL, sizeof(_QERUIGtkTable), SYN_REQUIRE, &g_UIGtkTable); - g_SynapseClient.AddAPI(QGL_MAJOR, NULL, sizeof(_QERQglTable), SYN_REQUIRE, &g_GLTable); - g_SynapseClient.AddAPI(ENTITY_MAJOR, NULL, sizeof(_QEREntityTable), SYN_REQUIRE, &g_EntityTable); - - return &g_SynapseClient; -} - -bool GenSurfSynapseClient::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable* pTable= static_cast<_QERPluginTable*>(pAPI->mpTable); - - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; -} - -#include "version.h" - -const char* GenSurfSynapseClient::GetInfo() -{ - return "GtkGenSurf - built " __DATE__ " " RADIANT_VERSION; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/triangle.c b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/triangle.c deleted file mode 100644 index 1e155cac..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/triangle.c +++ /dev/null @@ -1,13236 +0,0 @@ -#define ANSI_DECLARATORS -/*****************************************************************************/ -/* */ -/* 888888888 ,o, / 888 */ -/* 888 88o88o " o8888o 88o8888o o88888o 888 o88888o */ -/* 888 888 888 88b 888 888 888 888 888 d888 88b */ -/* 888 888 888 o88^o888 888 888 "88888" 888 8888oo888 */ -/* 888 888 888 C888 888 888 888 / 888 q888 */ -/* 888 888 888 "88o^888 888 888 Cb 888 "88oooo" */ -/* "8oo8D */ -/* */ -/* A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator. */ -/* (triangle.c) */ -/* */ -/* Version 1.3 */ -/* July 19, 1996 */ -/* */ -/* Copyright 1996 */ -/* Jonathan Richard Shewchuk */ -/* School of Computer Science */ -/* Carnegie Mellon University */ -/* 5000 Forbes Avenue */ -/* Pittsburgh, Pennsylvania 15213-3891 */ -/* jrs@cs.cmu.edu */ -/* */ -/* This program may be freely redistributed under the condition that the */ -/* copyright notices (including this entire header and the copyright */ -/* notice printed when the `-h' switch is selected) are not removed, and */ -/* no compensation is received. Private, research, and institutional */ -/* use is free. You may distribute modified versions of this code UNDER */ -/* THE CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE TO IT IN THE */ -/* SAME FILE REMAIN UNDER COPYRIGHT OF THE ORIGINAL AUTHOR, BOTH SOURCE */ -/* AND OBJECT CODE ARE MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR */ -/* NOTICE IS GIVEN OF THE MODIFICATIONS. Distribution of this code as */ -/* part of a commercial system is permissible ONLY BY DIRECT ARRANGEMENT */ -/* WITH THE AUTHOR. (If you are not directly supplying this code to a */ -/* customer, and you are instead telling them how they can obtain it for */ -/* free, then you are not required to make any arrangement with me.) */ -/* */ -/* Hypertext instructions for Triangle are available on the Web at */ -/* */ -/* http://www.cs.cmu.edu/~quake/triangle.html */ -/* */ -/* Some of the references listed below are marked [*]. These are available */ -/* for downloading from the Web page */ -/* */ -/* http://www.cs.cmu.edu/~quake/triangle.research.html */ -/* */ -/* A paper discussing some aspects of Triangle is available. See Jonathan */ -/* Richard Shewchuk, "Triangle: Engineering a 2D Quality Mesh Generator */ -/* and Delaunay Triangulator," First Workshop on Applied Computational */ -/* Geometry, ACM, May 1996. [*] */ -/* */ -/* Triangle was created as part of the Archimedes project in the School of */ -/* Computer Science at Carnegie Mellon University. Archimedes is a */ -/* system for compiling parallel finite element solvers. For further */ -/* information, see Anja Feldmann, Omar Ghattas, John R. Gilbert, Gary L. */ -/* Miller, David R. O'Hallaron, Eric J. Schwabe, Jonathan R. Shewchuk, */ -/* and Shang-Hua Teng, "Automated Parallel Solution of Unstructured PDE */ -/* Problems." To appear in Communications of the ACM, we hope. */ -/* */ -/* The quality mesh generation algorithm is due to Jim Ruppert, "A */ -/* Delaunay Refinement Algorithm for Quality 2-Dimensional Mesh */ -/* Generation," Journal of Algorithms 18(3):548-585, May 1995. [*] */ -/* */ -/* My implementation of the divide-and-conquer and incremental Delaunay */ -/* triangulation algorithms follows closely the presentation of Guibas */ -/* and Stolfi, even though I use a triangle-based data structure instead */ -/* of their quad-edge data structure. (In fact, I originally implemented */ -/* Triangle using the quad-edge data structure, but switching to a */ -/* triangle-based data structure sped Triangle by a factor of two.) The */ -/* mesh manipulation primitives and the two aforementioned Delaunay */ -/* triangulation algorithms are described by Leonidas J. Guibas and Jorge */ -/* Stolfi, "Primitives for the Manipulation of General Subdivisions and */ -/* the Computation of Voronoi Diagrams," ACM Transactions on Graphics */ -/* 4(2):74-123, April 1985. */ -/* */ -/* Their O(n log n) divide-and-conquer algorithm is adapted from Der-Tsai */ -/* Lee and Bruce J. Schachter, "Two Algorithms for Constructing the */ -/* Delaunay Triangulation," International Journal of Computer and */ -/* Information Science 9(3):219-242, 1980. The idea to improve the */ -/* divide-and-conquer algorithm by alternating between vertical and */ -/* horizontal cuts was introduced by Rex A. Dwyer, "A Faster Divide-and- */ -/* Conquer Algorithm for Constructing Delaunay Triangulations," */ -/* Algorithmica 2(2):137-151, 1987. */ -/* */ -/* The incremental insertion algorithm was first proposed by C. L. Lawson, */ -/* "Software for C1 Surface Interpolation," in Mathematical Software III, */ -/* John R. Rice, editor, Academic Press, New York, pp. 161-194, 1977. */ -/* For point location, I use the algorithm of Ernst P. Mucke, Isaac */ -/* Saias, and Binhai Zhu, "Fast Randomized Point Location Without */ -/* Preprocessing in Two- and Three-dimensional Delaunay Triangulations," */ -/* Proceedings of the Twelfth Annual Symposium on Computational Geometry, */ -/* ACM, May 1996. [*] If I were to randomize the order of point */ -/* insertion (I currently don't bother), their result combined with the */ -/* result of Leonidas J. Guibas, Donald E. Knuth, and Micha Sharir, */ -/* "Randomized Incremental Construction of Delaunay and Voronoi */ -/* Diagrams," Algorithmica 7(4):381-413, 1992, would yield an expected */ -/* O(n^{4/3}) bound on running time. */ -/* */ -/* The O(n log n) sweepline Delaunay triangulation algorithm is taken from */ -/* Steven Fortune, "A Sweepline Algorithm for Voronoi Diagrams", */ -/* Algorithmica 2(2):153-174, 1987. A random sample of edges on the */ -/* boundary of the triangulation are maintained in a splay tree for the */ -/* purpose of point location. Splay trees are described by Daniel */ -/* Dominic Sleator and Robert Endre Tarjan, "Self-Adjusting Binary Search */ -/* Trees," Journal of the ACM 32(3):652-686, July 1985. */ -/* */ -/* The algorithms for exact computation of the signs of determinants are */ -/* described in Jonathan Richard Shewchuk, "Adaptive Precision Floating- */ -/* Point Arithmetic and Fast Robust Geometric Predicates," Technical */ -/* Report CMU-CS-96-140, School of Computer Science, Carnegie Mellon */ -/* University, Pittsburgh, Pennsylvania, May 1996. [*] (Submitted to */ -/* Discrete & Computational Geometry.) An abbreviated version appears as */ -/* Jonathan Richard Shewchuk, "Robust Adaptive Floating-Point Geometric */ -/* Predicates," Proceedings of the Twelfth Annual Symposium on Computa- */ -/* tional Geometry, ACM, May 1996. [*] Many of the ideas for my exact */ -/* arithmetic routines originate with Douglas M. Priest, "Algorithms for */ -/* Arbitrary Precision Floating Point Arithmetic," Tenth Symposium on */ -/* Computer Arithmetic, 132-143, IEEE Computer Society Press, 1991. [*] */ -/* Many of the ideas for the correct evaluation of the signs of */ -/* determinants are taken from Steven Fortune and Christopher J. Van Wyk, */ -/* "Efficient Exact Arithmetic for Computational Geometry," Proceedings */ -/* of the Ninth Annual Symposium on Computational Geometry, ACM, */ -/* pp. 163-172, May 1993, and from Steven Fortune, "Numerical Stability */ -/* of Algorithms for 2D Delaunay Triangulations," International Journal */ -/* of Computational Geometry & Applications 5(1-2):193-213, March-June */ -/* 1995. */ -/* */ -/* For definitions of and results involving Delaunay triangulations, */ -/* constrained and conforming versions thereof, and other aspects of */ -/* triangular mesh generation, see the excellent survey by Marshall Bern */ -/* and David Eppstein, "Mesh Generation and Optimal Triangulation," in */ -/* Computing and Euclidean Geometry, Ding-Zhu Du and Frank Hwang, */ -/* editors, World Scientific, Singapore, pp. 23-90, 1992. */ -/* */ -/* The time for incrementally adding PSLG (planar straight line graph) */ -/* segments to create a constrained Delaunay triangulation is probably */ -/* O(n^2) per segment in the worst case and O(n) per edge in the common */ -/* case, where n is the number of triangles that intersect the segment */ -/* before it is inserted. This doesn't count point location, which can */ -/* be much more expensive. (This note does not apply to conforming */ -/* Delaunay triangulations, for which a different method is used to */ -/* insert segments.) */ -/* */ -/* The time for adding segments to a conforming Delaunay triangulation is */ -/* not clear, but does not depend upon n alone. In some cases, very */ -/* small features (like a point lying next to a segment) can cause a */ -/* single segment to be split an arbitrary number of times. Of course, */ -/* floating-point precision is a practical barrier to how much this can */ -/* happen. */ -/* */ -/* The time for deleting a point from a Delaunay triangulation is O(n^2) in */ -/* the worst case and O(n) in the common case, where n is the degree of */ -/* the point being deleted. I could improve this to expected O(n) time */ -/* by "inserting" the neighboring vertices in random order, but n is */ -/* usually quite small, so it's not worth the bother. (The O(n) time */ -/* for random insertion follows from L. Paul Chew, "Building Voronoi */ -/* Diagrams for Convex Polygons in Linear Expected Time," Technical */ -/* Report PCS-TR90-147, Department of Mathematics and Computer Science, */ -/* Dartmouth College, 1990. */ -/* */ -/* Ruppert's Delaunay refinement algorithm typically generates triangles */ -/* at a linear rate (constant time per triangle) after the initial */ -/* triangulation is formed. There may be pathological cases where more */ -/* time is required, but these never arise in practice. */ -/* */ -/* The segment intersection formulae are straightforward. If you want to */ -/* see them derived, see Franklin Antonio. "Faster Line Segment */ -/* Intersection." In Graphics Gems III (David Kirk, editor), pp. 199- */ -/* 202. Academic Press, Boston, 1992. */ -/* */ -/* If you make any improvements to this code, please please please let me */ -/* know, so that I may obtain the improvements. Even if you don't change */ -/* the code, I'd still love to hear what it's being used for. */ -/* */ -/* Disclaimer: Neither I nor Carnegie Mellon warrant this code in any way */ -/* whatsoever. This code is provided "as-is". Use at your own risk. */ -/* */ -/*****************************************************************************/ - -/* For single precision (which will save some memory and reduce paging), */ -/* define the symbol SINGLE by using the -DSINGLE compiler switch or by */ -/* writing "#define SINGLE" below. */ -/* */ -/* For double precision (which will allow you to refine meshes to a smaller */ -/* edge length), leave SINGLE undefined. */ -/* */ -/* Double precision uses more memory, but improves the resolution of the */ -/* meshes you can generate with Triangle. It also reduces the likelihood */ -/* of a floating exception due to overflow. Finally, it is much faster */ -/* than single precision on 64-bit architectures like the DEC Alpha. I */ -/* recommend double precision unless you want to generate a mesh for which */ -/* you do not have enough memory. */ - -#define SINGLE - -#ifdef SINGLE -#define REAL float -#else /* not SINGLE */ -#define REAL double -#endif /* not SINGLE */ - -/* If yours is not a Unix system, define the NO_TIMER compiler switch to */ -/* remove the Unix-specific timing code. */ - -#define NO_TIMER - -/* To insert lots of self-checks for internal errors, define the SELF_CHECK */ -/* symbol. This will slow down the program significantly. It is best to */ -/* define the symbol using the -DSELF_CHECK compiler switch, but you could */ -/* write "#define SELF_CHECK" below. If you are modifying this code, I */ -/* recommend you turn self-checks on. */ - -/* #define SELF_CHECK */ - -/* To compile Triangle as a callable object library (triangle.o), define the */ -/* TRILIBRARY symbol. Read the file triangle.h for details on how to call */ -/* the procedure triangulate() that results. */ - -#define TRILIBRARY - -/* It is possible to generate a smaller version of Triangle using one or */ -/* both of the following symbols. Define the REDUCED symbol to eliminate */ -/* all features that are primarily of research interest; specifically, the */ -/* -i, -F, -s, and -C switches. Define the CDT_ONLY symbol to eliminate */ -/* all meshing algorithms above and beyond constrained Delaunay */ -/* triangulation; specifically, the -r, -q, -a, -S, and -s switches. */ -/* These reductions are most likely to be useful when generating an object */ -/* library (triangle.o) by defining the TRILIBRARY symbol. */ - -#define REDUCED -#define CDT_ONLY - -/* On some machines, the exact arithmetic routines might be defeated by the */ -/* use of internal extended precision floating-point registers. Sometimes */ -/* this problem can be fixed by defining certain values to be volatile, */ -/* thus forcing them to be stored to memory and rounded off. This isn't */ -/* a great solution, though, as it slows Triangle down. */ -/* */ -/* To try this out, write "#define INEXACT volatile" below. Normally, */ -/* however, INEXACT should be defined to be nothing. ("#define INEXACT".) */ - -#define INEXACT /* Nothing */ -/* #define INEXACT volatile */ - -/* Maximum number of characters in a file name (including the null). */ - -#define FILENAMESIZE 512 - -/* Maximum number of characters in a line read from a file (including the */ -/* null). */ - -#define INPUTLINESIZE 512 - -/* For efficiency, a variety of data structures are allocated in bulk. The */ -/* following constants determine how many of each structure is allocated */ -/* at once. */ - -#define TRIPERBLOCK 4092 /* Number of triangles allocated at once. */ -#define SHELLEPERBLOCK 508 /* Number of shell edges allocated at once. */ -#define POINTPERBLOCK 4092 /* Number of points allocated at once. */ -#define VIRUSPERBLOCK 1020 /* Number of virus triangles allocated at once. */ -/* Number of encroached segments allocated at once. */ -#define BADSEGMENTPERBLOCK 252 -/* Number of skinny triangles allocated at once. */ -#define BADTRIPERBLOCK 4092 -/* Number of splay tree nodes allocated at once. */ -#define SPLAYNODEPERBLOCK 508 - -/* The point marker DEADPOINT is an arbitrary number chosen large enough to */ -/* (hopefully) not conflict with user boundary markers. Make sure that it */ -/* is small enough to fit into your machine's integer size. */ - -#define DEADPOINT -1073741824 - -/* The next line is used to outsmart some very stupid compilers. If your */ -/* compiler is smarter, feel free to replace the "int" with "void". */ -/* Not that it matters. */ - -#define VOID int - -/* Two constants for algorithms based on random sampling. Both constants */ -/* have been chosen empirically to optimize their respective algorithms. */ - -/* Used for the point location scheme of Mucke, Saias, and Zhu, to decide */ -/* how large a random sample of triangles to inspect. */ -#define SAMPLEFACTOR 11 -/* Used in Fortune's sweepline Delaunay algorithm to determine what fraction */ -/* of boundary edges should be maintained in the splay tree for point */ -/* location on the front. */ -#define SAMPLERATE 10 - -/* A number that speaks for itself, every kissable digit. */ - -#define PI 3.141592653589793238462643383279502884197169399375105820974944592308 - -/* Another fave. */ - -#define SQUAREROOTTWO 1.4142135623730950488016887242096980785696718753769480732 - -/* And here's one for those of you who are intimidated by math. */ - -#define ONETHIRD 0.333333333333333333333333333333333333333333333333333333333333 - -#include -#include -#include -#ifndef NO_TIMER -#include -#endif /* NO_TIMER */ -#ifdef TRILIBRARY -#include "triangle.h" -#endif /* TRILIBRARY */ - -/* The following obscenity seems to be necessary to ensure that this program */ -/* will port to Dec Alphas running OSF/1, because their stdio.h file commits */ -/* the unpardonable sin of including stdlib.h. Hence, malloc(), free(), and */ -/* exit() may or may not already be defined at this point. I declare these */ -/* functions explicitly because some non-ANSI C compilers lack stdlib.h. */ - -#ifndef _STDLIB_H_ -extern void *malloc(); -extern void free(); -extern void exit(); -extern double strtod(); -extern long strtol(); -#endif /* _STDLIB_H_ */ - -/* A few forward declarations. */ - -void poolrestart(); -#ifndef TRILIBRARY -char *readline(); -char *findfield(); -#endif /* not TRILIBRARY */ - -/* Labels that signify whether a record consists primarily of pointers or of */ -/* floating-point words. Used to make decisions about data alignment. */ - -enum wordtype {POINTER, FLOATINGPOINT}; - -/* Labels that signify the result of point location. The result of a */ -/* search indicates that the point falls in the interior of a triangle, on */ -/* an edge, on a vertex, or outside the mesh. */ - -enum locateresult {INTRIANGLE, ONEDGE, ONVERTEX, OUTSIDE}; - -/* Labels that signify the result of site insertion. The result indicates */ -/* that the point was inserted with complete success, was inserted but */ -/* encroaches on a segment, was not inserted because it lies on a segment, */ -/* or was not inserted because another point occupies the same location. */ - -enum insertsiteresult {SUCCESSFULPOINT, ENCROACHINGPOINT, VIOLATINGPOINT, - DUPLICATEPOINT}; - -/* Labels that signify the result of direction finding. The result */ -/* indicates that a segment connecting the two query points falls within */ -/* the direction triangle, along the left edge of the direction triangle, */ -/* or along the right edge of the direction triangle. */ - -enum finddirectionresult {WITHIN, LEFTCOLLINEAR, RIGHTCOLLINEAR}; - -/* Labels that signify the result of the circumcenter computation routine. */ -/* The return value indicates which edge of the triangle is shortest. */ - -enum circumcenterresult {OPPOSITEORG, OPPOSITEDEST, OPPOSITEAPEX}; - -/*****************************************************************************/ -/* */ -/* The basic mesh data structures */ -/* */ -/* There are three: points, triangles, and shell edges (abbreviated */ -/* `shelle'). These three data structures, linked by pointers, comprise */ -/* the mesh. A point simply represents a point in space and its properties.*/ -/* A triangle is a triangle. A shell edge is a special data structure used */ -/* to represent impenetrable segments in the mesh (including the outer */ -/* boundary, boundaries of holes, and internal boundaries separating two */ -/* triangulated regions). Shell edges represent boundaries defined by the */ -/* user that triangles may not lie across. */ -/* */ -/* A triangle consists of a list of three vertices, a list of three */ -/* adjoining triangles, a list of three adjoining shell edges (when shell */ -/* edges are used), an arbitrary number of optional user-defined floating- */ -/* point attributes, and an optional area constraint. The latter is an */ -/* upper bound on the permissible area of each triangle in a region, used */ -/* for mesh refinement. */ -/* */ -/* For a triangle on a boundary of the mesh, some or all of the neighboring */ -/* triangles may not be present. For a triangle in the interior of the */ -/* mesh, often no neighboring shell edges are present. Such absent */ -/* triangles and shell edges are never represented by NULL pointers; they */ -/* are represented by two special records: `dummytri', the triangle that */ -/* fills "outer space", and `dummysh', the omnipresent shell edge. */ -/* `dummytri' and `dummysh' are used for several reasons; for instance, */ -/* they can be dereferenced and their contents examined without causing the */ -/* memory protection exception that would occur if NULL were dereferenced. */ -/* */ -/* However, it is important to understand that a triangle includes other */ -/* information as well. The pointers to adjoining vertices, triangles, and */ -/* shell edges are ordered in a way that indicates their geometric relation */ -/* to each other. Furthermore, each of these pointers contains orientation */ -/* information. Each pointer to an adjoining triangle indicates which face */ -/* of that triangle is contacted. Similarly, each pointer to an adjoining */ -/* shell edge indicates which side of that shell edge is contacted, and how */ -/* the shell edge is oriented relative to the triangle. */ -/* */ -/* Shell edges are found abutting edges of triangles; either sandwiched */ -/* between two triangles, or resting against one triangle on an exterior */ -/* boundary or hole boundary. */ -/* */ -/* A shell edge consists of a list of two vertices, a list of two */ -/* adjoining shell edges, and a list of two adjoining triangles. One of */ -/* the two adjoining triangles may not be present (though there should */ -/* always be one), and neighboring shell edges might not be present. */ -/* Shell edges also store a user-defined integer "boundary marker". */ -/* Typically, this integer is used to indicate what sort of boundary */ -/* conditions are to be applied at that location in a finite element */ -/* simulation. */ -/* */ -/* Like triangles, shell edges maintain information about the relative */ -/* orientation of neighboring objects. */ -/* */ -/* Points are relatively simple. A point is a list of floating point */ -/* numbers, starting with the x, and y coordinates, followed by an */ -/* arbitrary number of optional user-defined floating-point attributes, */ -/* followed by an integer boundary marker. During the segment insertion */ -/* phase, there is also a pointer from each point to a triangle that may */ -/* contain it. Each pointer is not always correct, but when one is, it */ -/* speeds up segment insertion. These pointers are assigned values once */ -/* at the beginning of the segment insertion phase, and are not used or */ -/* updated at any other time. Edge swapping during segment insertion will */ -/* render some of them incorrect. Hence, don't rely upon them for */ -/* anything. For the most part, points do not have any information about */ -/* what triangles or shell edges they are linked to. */ -/* */ -/*****************************************************************************/ - -/*****************************************************************************/ -/* */ -/* Handles */ -/* */ -/* The oriented triangle (`triedge') and oriented shell edge (`edge') data */ -/* structures defined below do not themselves store any part of the mesh. */ -/* The mesh itself is made of `triangle's, `shelle's, and `point's. */ -/* */ -/* Oriented triangles and oriented shell edges will usually be referred to */ -/* as "handles". A handle is essentially a pointer into the mesh; it */ -/* allows you to "hold" one particular part of the mesh. Handles are used */ -/* to specify the regions in which one is traversing and modifying the mesh.*/ -/* A single `triangle' may be held by many handles, or none at all. (The */ -/* latter case is not a memory leak, because the triangle is still */ -/* connected to other triangles in the mesh.) */ -/* */ -/* A `triedge' is a handle that holds a triangle. It holds a specific side */ -/* of the triangle. An `edge' is a handle that holds a shell edge. It */ -/* holds either the left or right side of the edge. */ -/* */ -/* Navigation about the mesh is accomplished through a set of mesh */ -/* manipulation primitives, further below. Many of these primitives take */ -/* a handle and produce a new handle that holds the mesh near the first */ -/* handle. Other primitives take two handles and glue the corresponding */ -/* parts of the mesh together. The exact position of the handles is */ -/* important. For instance, when two triangles are glued together by the */ -/* bond() primitive, they are glued by the sides on which the handles lie. */ -/* */ -/* Because points have no information about which triangles they are */ -/* attached to, I commonly represent a point by use of a handle whose */ -/* origin is the point. A single handle can simultaneously represent a */ -/* triangle, an edge, and a point. */ -/* */ -/*****************************************************************************/ - -/* The triangle data structure. Each triangle contains three pointers to */ -/* adjoining triangles, plus three pointers to vertex points, plus three */ -/* pointers to shell edges (defined below; these pointers are usually */ -/* `dummysh'). It may or may not also contain user-defined attributes */ -/* and/or a floating-point "area constraint". It may also contain extra */ -/* pointers for nodes, when the user asks for high-order elements. */ -/* Because the size and structure of a `triangle' is not decided until */ -/* runtime, I haven't simply defined the type `triangle' to be a struct. */ - -typedef REAL **triangle; /* Really: typedef triangle *triangle */ - -/* An oriented triangle: includes a pointer to a triangle and orientation. */ -/* The orientation denotes an edge of the triangle. Hence, there are */ -/* three possible orientations. By convention, each edge is always */ -/* directed to point counterclockwise about the corresponding triangle. */ - -struct triedge { - triangle *tri; - int orient; /* Ranges from 0 to 2. */ -}; - -/* The shell data structure. Each shell edge contains two pointers to */ -/* adjoining shell edges, plus two pointers to vertex points, plus two */ -/* pointers to adjoining triangles, plus one shell marker. */ - -typedef REAL **shelle; /* Really: typedef shelle *shelle */ - -/* An oriented shell edge: includes a pointer to a shell edge and an */ -/* orientation. The orientation denotes a side of the edge. Hence, there */ -/* are two possible orientations. By convention, the edge is always */ -/* directed so that the "side" denoted is the right side of the edge. */ - -struct edge { - shelle *sh; - int shorient; /* Ranges from 0 to 1. */ -}; - -/* The point data structure. Each point is actually an array of REALs. */ -/* The number of REALs is unknown until runtime. An integer boundary */ -/* marker, and sometimes a pointer to a triangle, is appended after the */ -/* REALs. */ - -typedef REAL *point; - -/* A queue used to store encroached segments. Each segment's vertices are */ -/* stored so that one can check whether a segment is still the same. */ - -struct badsegment { - struct edge encsegment; /* An encroached segment. */ - point segorg, segdest; /* The two vertices. */ - struct badsegment *nextsegment; /* Pointer to next encroached segment. */ -}; - -/* A queue used to store bad triangles. The key is the square of the cosine */ -/* of the smallest angle of the triangle. Each triangle's vertices are */ -/* stored so that one can check whether a triangle is still the same. */ - -struct badface { - struct triedge badfacetri; /* A bad triangle. */ - REAL key; /* cos^2 of smallest (apical) angle. */ - point faceorg, facedest, faceapex; /* The three vertices. */ - struct badface *nextface; /* Pointer to next bad triangle. */ -}; - -/* A node in a heap used to store events for the sweepline Delaunay */ -/* algorithm. Nodes do not point directly to their parents or children in */ -/* the heap. Instead, each node knows its position in the heap, and can */ -/* look up its parent and children in a separate array. The `eventptr' */ -/* points either to a `point' or to a triangle (in encoded format, so that */ -/* an orientation is included). In the latter case, the origin of the */ -/* oriented triangle is the apex of a "circle event" of the sweepline */ -/* algorithm. To distinguish site events from circle events, all circle */ -/* events are given an invalid (smaller than `xmin') x-coordinate `xkey'. */ - -struct event { - REAL xkey, ykey; /* Coordinates of the event. */ - VOID *eventptr; /* Can be a point or the location of a circle event. */ - int heapposition; /* Marks this event's position in the heap. */ -}; - -/* A node in the splay tree. Each node holds an oriented ghost triangle */ -/* that represents a boundary edge of the growing triangulation. When a */ -/* circle event covers two boundary edges with a triangle, so that they */ -/* are no longer boundary edges, those edges are not immediately deleted */ -/* from the tree; rather, they are lazily deleted when they are next */ -/* encountered. (Since only a random sample of boundary edges are kept */ -/* in the tree, lazy deletion is faster.) `keydest' is used to verify */ -/* that a triangle is still the same as when it entered the splay tree; if */ -/* it has been rotated (due to a circle event), it no longer represents a */ -/* boundary edge and should be deleted. */ - -struct splaynode { - struct triedge keyedge; /* Lprev of an edge on the front. */ - point keydest; /* Used to verify that splay node is still live. */ - struct splaynode *lchild, *rchild; /* Children in splay tree. */ -}; - -/* A type used to allocate memory. firstblock is the first block of items. */ -/* nowblock is the block from which items are currently being allocated. */ -/* nextitem points to the next slab of free memory for an item. */ -/* deaditemstack is the head of a linked list (stack) of deallocated items */ -/* that can be recycled. unallocateditems is the number of items that */ -/* remain to be allocated from nowblock. */ -/* */ -/* Traversal is the process of walking through the entire list of items, and */ -/* is separate from allocation. Note that a traversal will visit items on */ -/* the "deaditemstack" stack as well as live items. pathblock points to */ -/* the block currently being traversed. pathitem points to the next item */ -/* to be traversed. pathitemsleft is the number of items that remain to */ -/* be traversed in pathblock. */ -/* */ -/* itemwordtype is set to POINTER or FLOATINGPOINT, and is used to suggest */ -/* what sort of word the record is primarily made up of. alignbytes */ -/* determines how new records should be aligned in memory. itembytes and */ -/* itemwords are the length of a record in bytes (after rounding up) and */ -/* words. itemsperblock is the number of items allocated at once in a */ -/* single block. items is the number of currently allocated items. */ -/* maxitems is the maximum number of items that have been allocated at */ -/* once; it is the current number of items plus the number of records kept */ -/* on deaditemstack. */ - -struct memorypool { - VOID **firstblock, **nowblock; - VOID *nextitem; - VOID *deaditemstack; - VOID **pathblock; - VOID *pathitem; - enum wordtype itemwordtype; - int alignbytes; - int itembytes, itemwords; - int itemsperblock; - long items, maxitems; - int unallocateditems; - int pathitemsleft; -}; - -/* Variables used to allocate memory for triangles, shell edges, points, */ -/* viri (triangles being eaten), bad (encroached) segments, bad (skinny */ -/* or too large) triangles, and splay tree nodes. */ - -static struct memorypool triangles; -static struct memorypool shelles; -static struct memorypool points; -static struct memorypool viri; -static struct memorypool badsegments; -static struct memorypool badtriangles; -static struct memorypool splaynodes; - -/* Variables that maintain the bad triangle queues. The tails are pointers */ -/* to the pointers that have to be filled in to enqueue an item. */ - -static struct badface *queuefront[64]; -static struct badface **queuetail[64]; - -static REAL xmin, xmax, ymin, ymax; /* x and y bounds. */ -static REAL xminextreme; /* Nonexistent x value used as a flag in sweepline. */ -static int inpoints; /* Number of input points. */ -static int inelements; /* Number of input triangles. */ -static int insegments; /* Number of input segments. */ -static int holes; /* Number of input holes. */ -static int regions; /* Number of input regions. */ -static long edges; /* Number of output edges. */ -static int mesh_dim; /* Dimension (ought to be 2). */ -static int nextras; /* Number of attributes per point. */ -static int eextras; /* Number of attributes per triangle. */ -static long hullsize; /* Number of edges of convex hull. */ -static int triwords; /* Total words per triangle. */ -static int shwords; /* Total words per shell edge. */ -static int pointmarkindex; /* Index to find boundary marker of a point. */ -static int point2triindex; /* Index to find a triangle adjacent to a point. */ -static int highorderindex; /* Index to find extra nodes for high-order elements. */ -static int elemattribindex; /* Index to find attributes of a triangle. */ -static int areaboundindex; /* Index to find area bound of a triangle. */ -static int checksegments; /* Are there segments in the triangulation yet? */ -static int readnodefile; /* Has a .node file been read? */ -static long samples; /* Number of random samples for point location. */ -static unsigned long randomseed; /* Current random number seed. */ - -static REAL splitter; /* Used to split REAL factors for exact multiplication. */ -static REAL epsilon; /* Floating-point machine epsilon. */ -static REAL resulterrbound; -static REAL ccwerrboundA, ccwerrboundB, ccwerrboundC; -static REAL iccerrboundA, iccerrboundB, iccerrboundC; - -static long incirclecount; /* Number of incircle tests performed. */ -static long counterclockcount; /* Number of counterclockwise tests performed. */ -static long hyperbolacount; /* Number of right-of-hyperbola tests performed. */ -static long circumcentercount; /* Number of circumcenter calculations performed. */ -static long circletopcount; /* Number of circle top calculations performed. */ - -/* Switches for the triangulator. */ -/* poly: -p switch. refine: -r switch. */ -/* quality: -q switch. */ -/* minangle: minimum angle bound, specified after -q switch. */ -/* goodangle: cosine squared of minangle. */ -/* vararea: -a switch without number. */ -/* fixedarea: -a switch with number. */ -/* maxarea: maximum area bound, specified after -a switch. */ -/* regionattrib: -A switch. convex: -c switch. */ -/* firstnumber: inverse of -z switch. All items are numbered starting */ -/* from firstnumber. */ -/* edgesout: -e switch. voronoi: -v switch. */ -/* neighbors: -n switch. geomview: -g switch. */ -/* nobound: -B switch. nopolywritten: -P switch. */ -/* nonodewritten: -N switch. noelewritten: -E switch. */ -/* noiterationnum: -I switch. noholes: -O switch. */ -/* noexact: -X switch. */ -/* order: element order, specified after -o switch. */ -/* nobisect: count of how often -Y switch is selected. */ -/* steiner: maximum number of Steiner points, specified after -S switch. */ -/* steinerleft: number of Steiner points not yet used. */ -/* incremental: -i switch. sweepline: -F switch. */ -/* dwyer: inverse of -l switch. */ -/* splitseg: -s switch. */ -/* docheck: -C switch. */ -/* quiet: -Q switch. verbose: count of how often -V switch is selected. */ -/* useshelles: -p, -r, -q, or -c switch; determines whether shell edges */ -/* are used at all. */ -/* */ -/* Read the instructions to find out the meaning of these switches. */ - -static int poly, refine, quality, vararea, fixedarea, regionattrib, convex; -static int firstnumber; -static int edgesout, voronoi, neighbors, geomview; -static int nobound, nopolywritten, nonodewritten, noelewritten, noiterationnum; -static int noholes, noexact; -static int incremental, sweepline, dwyer; -static int splitseg; -static int docheck; -static int quiet, verbose; -static int useshelles; -static int order; -static int nobisect; -static int steiner, steinerleft; -static REAL minangle, goodangle; -static REAL maxarea; - -/* Variables for file names. */ - -#ifndef TRILIBRARY -char innodefilename[FILENAMESIZE]; -char inelefilename[FILENAMESIZE]; -char inpolyfilename[FILENAMESIZE]; -char areafilename[FILENAMESIZE]; -char outnodefilename[FILENAMESIZE]; -char outelefilename[FILENAMESIZE]; -char outpolyfilename[FILENAMESIZE]; -char edgefilename[FILENAMESIZE]; -char vnodefilename[FILENAMESIZE]; -char vedgefilename[FILENAMESIZE]; -char neighborfilename[FILENAMESIZE]; -char offfilename[FILENAMESIZE]; -#endif /* not TRILIBRARY */ - -/* Triangular bounding box points. */ - -static point infpoint1, infpoint2, infpoint3; - -/* Pointer to the `triangle' that occupies all of "outer space". */ - -static triangle *dummytri; -static triangle *dummytribase; /* Keep base address so we can free() it later. */ - -/* Pointer to the omnipresent shell edge. Referenced by any triangle or */ -/* shell edge that isn't really connected to a shell edge at that */ -/* location. */ - -static shelle *dummysh; -static shelle *dummyshbase; /* Keep base address so we can free() it later. */ - -/* Pointer to a recently visited triangle. Improves point location if */ -/* proximate points are inserted sequentially. */ - -static struct triedge recenttri; - -/*****************************************************************************/ -/* */ -/* Mesh manipulation primitives. Each triangle contains three pointers to */ -/* other triangles, with orientations. Each pointer points not to the */ -/* first byte of a triangle, but to one of the first three bytes of a */ -/* triangle. It is necessary to extract both the triangle itself and the */ -/* orientation. To save memory, I keep both pieces of information in one */ -/* pointer. To make this possible, I assume that all triangles are aligned */ -/* to four-byte boundaries. The `decode' routine below decodes a pointer, */ -/* extracting an orientation (in the range 0 to 2) and a pointer to the */ -/* beginning of a triangle. The `encode' routine compresses a pointer to a */ -/* triangle and an orientation into a single pointer. My assumptions that */ -/* triangles are four-byte-aligned and that the `unsigned long' type is */ -/* long enough to hold a pointer are two of the few kludges in this program.*/ -/* */ -/* Shell edges are manipulated similarly. A pointer to a shell edge */ -/* carries both an address and an orientation in the range 0 to 1. */ -/* */ -/* The other primitives take an oriented triangle or oriented shell edge, */ -/* and return an oriented triangle or oriented shell edge or point; or they */ -/* change the connections in the data structure. */ -/* */ -/*****************************************************************************/ - -/********* Mesh manipulation primitives begin here *********/ -/** **/ -/** **/ - -/* Fast lookup arrays to speed some of the mesh manipulation primitives. */ - -int plus1mod3[3] = {1, 2, 0}; -int minus1mod3[3] = {2, 0, 1}; - -/********* Primitives for triangles *********/ -/* */ -/* */ - -/* decode() converts a pointer to an oriented triangle. The orientation is */ -/* extracted from the two least significant bits of the pointer. */ - -#define decode(ptr, triedge) \ - (triedge).orient = (int) ((unsigned long) (ptr) & (unsigned long) 3l); \ - (triedge).tri = (triangle *) \ - ((unsigned long) (ptr) ^ (unsigned long) (triedge).orient) - -/* encode() compresses an oriented triangle into a single pointer. It */ -/* relies on the assumption that all triangles are aligned to four-byte */ -/* boundaries, so the two least significant bits of (triedge).tri are zero.*/ - -#define encode(triedge) \ - (triangle) ((unsigned long) (triedge).tri | (unsigned long) (triedge).orient) - -/* The following edge manipulation primitives are all described by Guibas */ -/* and Stolfi. However, they use an edge-based data structure, whereas I */ -/* am using a triangle-based data structure. */ - -/* sym() finds the abutting triangle, on the same edge. Note that the */ -/* edge direction is necessarily reversed, because triangle/edge handles */ -/* are always directed counterclockwise around the triangle. */ - -#define sym(triedge1, triedge2) \ - ptr = (triedge1).tri[(triedge1).orient]; \ - decode(ptr, triedge2); - -#define symself(triedge) \ - ptr = (triedge).tri[(triedge).orient]; \ - decode(ptr, triedge); - -/* lnext() finds the next edge (counterclockwise) of a triangle. */ - -#define lnext(triedge1, triedge2) \ - (triedge2).tri = (triedge1).tri; \ - (triedge2).orient = plus1mod3[(triedge1).orient] - -#define lnextself(triedge) \ - (triedge).orient = plus1mod3[(triedge).orient] - -/* lprev() finds the previous edge (clockwise) of a triangle. */ - -#define lprev(triedge1, triedge2) \ - (triedge2).tri = (triedge1).tri; \ - (triedge2).orient = minus1mod3[(triedge1).orient] - -#define lprevself(triedge) \ - (triedge).orient = minus1mod3[(triedge).orient] - -/* onext() spins counterclockwise around a point; that is, it finds the next */ -/* edge with the same origin in the counterclockwise direction. This edge */ -/* will be part of a different triangle. */ - -#define onext(triedge1, triedge2) \ - lprev(triedge1, triedge2); \ - symself(triedge2); - -#define onextself(triedge) \ - lprevself(triedge); \ - symself(triedge); - -/* oprev() spins clockwise around a point; that is, it finds the next edge */ -/* with the same origin in the clockwise direction. This edge will be */ -/* part of a different triangle. */ - -#define oprev(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lnextself(triedge2); - -#define oprevself(triedge) \ - symself(triedge); \ - lnextself(triedge); - -/* dnext() spins counterclockwise around a point; that is, it finds the next */ -/* edge with the same destination in the counterclockwise direction. This */ -/* edge will be part of a different triangle. */ - -#define dnext(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lprevself(triedge2); - -#define dnextself(triedge) \ - symself(triedge); \ - lprevself(triedge); - -/* dprev() spins clockwise around a point; that is, it finds the next edge */ -/* with the same destination in the clockwise direction. This edge will */ -/* be part of a different triangle. */ - -#define dprev(triedge1, triedge2) \ - lnext(triedge1, triedge2); \ - symself(triedge2); - -#define dprevself(triedge) \ - lnextself(triedge); \ - symself(triedge); - -/* rnext() moves one edge counterclockwise about the adjacent triangle. */ -/* (It's best understood by reading Guibas and Stolfi. It involves */ -/* changing triangles twice.) */ - -#define rnext(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lnextself(triedge2); \ - symself(triedge2); - -#define rnextself(triedge) \ - symself(triedge); \ - lnextself(triedge); \ - symself(triedge); - -/* rnext() moves one edge clockwise about the adjacent triangle. */ -/* (It's best understood by reading Guibas and Stolfi. It involves */ -/* changing triangles twice.) */ - -#define rprev(triedge1, triedge2) \ - sym(triedge1, triedge2); \ - lprevself(triedge2); \ - symself(triedge2); - -#define rprevself(triedge) \ - symself(triedge); \ - lprevself(triedge); \ - symself(triedge); - -/* These primitives determine or set the origin, destination, or apex of a */ -/* triangle. */ - -#define org(triedge, pointptr) \ - pointptr = (point) (triedge).tri[plus1mod3[(triedge).orient] + 3] - -#define dest(triedge, pointptr) \ - pointptr = (point) (triedge).tri[minus1mod3[(triedge).orient] + 3] - -#define apex(triedge, pointptr) \ - pointptr = (point) (triedge).tri[(triedge).orient + 3] - -#define setorg(triedge, pointptr) \ - (triedge).tri[plus1mod3[(triedge).orient] + 3] = (triangle) pointptr - -#define setdest(triedge, pointptr) \ - (triedge).tri[minus1mod3[(triedge).orient] + 3] = (triangle) pointptr - -#define setapex(triedge, pointptr) \ - (triedge).tri[(triedge).orient + 3] = (triangle) pointptr - -#define setvertices2null(triedge) \ - (triedge).tri[3] = (triangle) NULL; \ - (triedge).tri[4] = (triangle) NULL; \ - (triedge).tri[5] = (triangle) NULL; - -/* Bond two triangles together. */ - -#define bond(triedge1, triedge2) \ - (triedge1).tri[(triedge1).orient] = encode(triedge2); \ - (triedge2).tri[(triedge2).orient] = encode(triedge1) - -/* Dissolve a bond (from one side). Note that the other triangle will still */ -/* think it's connected to this triangle. Usually, however, the other */ -/* triangle is being deleted entirely, or bonded to another triangle, so */ -/* it doesn't matter. */ - -#define dissolve(triedge) \ - (triedge).tri[(triedge).orient] = (triangle) dummytri - -/* Copy a triangle/edge handle. */ - -#define triedgecopy(triedge1, triedge2) \ - (triedge2).tri = (triedge1).tri; \ - (triedge2).orient = (triedge1).orient - -/* Test for equality of triangle/edge handles. */ - -#define triedgeequal(triedge1, triedge2) \ - (((triedge1).tri == (triedge2).tri) && \ - ((triedge1).orient == (triedge2).orient)) - -/* Primitives to infect or cure a triangle with the virus. These rely on */ -/* the assumption that all shell edges are aligned to four-byte boundaries.*/ - -#define infect(triedge) \ - (triedge).tri[6] = (triangle) \ - ((unsigned long) (triedge).tri[6] | (unsigned long) 2l) - -#define uninfect(triedge) \ - (triedge).tri[6] = (triangle) \ - ((unsigned long) (triedge).tri[6] & ~ (unsigned long) 2l) - -/* Test a triangle for viral infection. */ - -#define infected(triedge) \ - (((unsigned long) (triedge).tri[6] & (unsigned long) 2l) != 0) - -/* Check or set a triangle's attributes. */ - -#define elemattribute(triedge, attnum) \ - ((REAL *) (triedge).tri)[elemattribindex + (attnum)] - -#define setelemattribute(triedge, attnum, value) \ - ((REAL *) (triedge).tri)[elemattribindex + (attnum)] = (REAL)value - -/* Check or set a triangle's maximum area bound. */ - -#define areabound(triedge) ((REAL *) (triedge).tri)[areaboundindex] - -#define setareabound(triedge, value) \ - ((REAL *) (triedge).tri)[areaboundindex] = (REAL)value - -/********* Primitives for shell edges *********/ -/* */ -/* */ - -/* sdecode() converts a pointer to an oriented shell edge. The orientation */ -/* is extracted from the least significant bit of the pointer. The two */ -/* least significant bits (one for orientation, one for viral infection) */ -/* are masked out to produce the real pointer. */ - -#define sdecode(sptr, edge) \ - (edge).shorient = (int) ((unsigned long) (sptr) & (unsigned long) 1l); \ - (edge).sh = (shelle *) \ - ((unsigned long) (sptr) & ~ (unsigned long) 3l) - -/* sencode() compresses an oriented shell edge into a single pointer. It */ -/* relies on the assumption that all shell edges are aligned to two-byte */ -/* boundaries, so the least significant bit of (edge).sh is zero. */ - -#define sencode(edge) \ - (shelle) ((unsigned long) (edge).sh | (unsigned long) (edge).shorient) - -/* ssym() toggles the orientation of a shell edge. */ - -#define ssym(edge1, edge2) \ - (edge2).sh = (edge1).sh; \ - (edge2).shorient = 1 - (edge1).shorient - -#define ssymself(edge) \ - (edge).shorient = 1 - (edge).shorient - -/* spivot() finds the other shell edge (from the same segment) that shares */ -/* the same origin. */ - -#define spivot(edge1, edge2) \ - sptr = (edge1).sh[(edge1).shorient]; \ - sdecode(sptr, edge2) - -#define spivotself(edge) \ - sptr = (edge).sh[(edge).shorient]; \ - sdecode(sptr, edge) - -/* snext() finds the next shell edge (from the same segment) in sequence; */ -/* one whose origin is the input shell edge's destination. */ - -#define snext(edge1, edge2) \ - sptr = (edge1).sh[1 - (edge1).shorient]; \ - sdecode(sptr, edge2) - -#define snextself(edge) \ - sptr = (edge).sh[1 - (edge).shorient]; \ - sdecode(sptr, edge) - -/* These primitives determine or set the origin or destination of a shell */ -/* edge. */ - -#define sorg(edge, pointptr) \ - pointptr = (point) (edge).sh[2 + (edge).shorient] - -#define sdest(edge, pointptr) \ - pointptr = (point) (edge).sh[3 - (edge).shorient] - -#define setsorg(edge, pointptr) \ - (edge).sh[2 + (edge).shorient] = (shelle) pointptr - -#define setsdest(edge, pointptr) \ - (edge).sh[3 - (edge).shorient] = (shelle) pointptr - -/* These primitives read or set a shell marker. Shell markers are used to */ -/* hold user boundary information. */ - -#define mark(edge) (* (int *) ((edge).sh + 6)) - -#define setmark(edge, value) \ - * (int *) ((edge).sh + 6) = value - -/* Bond two shell edges together. */ - -#define sbond(edge1, edge2) \ - (edge1).sh[(edge1).shorient] = sencode(edge2); \ - (edge2).sh[(edge2).shorient] = sencode(edge1) - -/* Dissolve a shell edge bond (from one side). Note that the other shell */ -/* edge will still think it's connected to this shell edge. */ - -#define sdissolve(edge) \ - (edge).sh[(edge).shorient] = (shelle) dummysh - -/* Copy a shell edge. */ - -#define shellecopy(edge1, edge2) \ - (edge2).sh = (edge1).sh; \ - (edge2).shorient = (edge1).shorient - -/* Test for equality of shell edges. */ - -#define shelleequal(edge1, edge2) \ - (((edge1).sh == (edge2).sh) && \ - ((edge1).shorient == (edge2).shorient)) - -/********* Primitives for interacting triangles and shell edges *********/ -/* */ -/* */ - -/* tspivot() finds a shell edge abutting a triangle. */ - -#define tspivot(triedge, edge) \ - sptr = (shelle) (triedge).tri[6 + (triedge).orient]; \ - sdecode(sptr, edge) - -/* stpivot() finds a triangle abutting a shell edge. It requires that the */ -/* variable `ptr' of type `triangle' be defined. */ - -#define stpivot(edge, triedge) \ - ptr = (triangle) (edge).sh[4 + (edge).shorient]; \ - decode(ptr, triedge) - -/* Bond a triangle to a shell edge. */ - -#define tsbond(triedge, edge) \ - (triedge).tri[6 + (triedge).orient] = (triangle) sencode(edge); \ - (edge).sh[4 + (edge).shorient] = (shelle) encode(triedge) - -/* Dissolve a bond (from the triangle side). */ - -#define tsdissolve(triedge) \ - (triedge).tri[6 + (triedge).orient] = (triangle) dummysh - -/* Dissolve a bond (from the shell edge side). */ - -#define stdissolve(edge) \ - (edge).sh[4 + (edge).shorient] = (shelle) dummytri - -/********* Primitives for points *********/ -/* */ -/* */ - -#define pointmark(pt) ((int *) (pt))[pointmarkindex] - -#define setpointmark(pt, value) \ - ((int *) (pt))[pointmarkindex] = value - -#define point2tri(pt) ((triangle *) (pt))[point2triindex] - -#define setpoint2tri(pt, value) \ - ((triangle *) (pt))[point2triindex] = value - -/** **/ -/** **/ -/********* Mesh manipulation primitives end here *********/ - -/********* User interaction routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* syntax() Print list of command line switches. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -void syntax() -{ -#ifdef CDT_ONLY -#ifdef REDUCED - printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n"); -#else /* not REDUCED */ - printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n"); -#endif /* not REDUCED */ -#else /* not CDT_ONLY */ -#ifdef REDUCED - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n"); -#else /* not REDUCED */ - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n"); -#endif /* not REDUCED */ -#endif /* not CDT_ONLY */ - - printf(" -p Triangulates a Planar Straight Line Graph (.poly file).\n"); -#ifndef CDT_ONLY - printf(" -r Refines a previously generated mesh.\n"); - printf( - " -q Quality mesh generation. A minimum angle may be specified.\n"); - printf(" -a Applies a maximum triangle area constraint.\n"); -#endif /* not CDT_ONLY */ - printf( - " -A Applies attributes to identify elements in certain regions.\n"); - printf(" -c Encloses the convex hull with segments.\n"); - printf(" -e Generates an edge list.\n"); - printf(" -v Generates a Voronoi diagram.\n"); - printf(" -n Generates a list of triangle neighbors.\n"); - printf(" -g Generates an .off file for Geomview.\n"); - printf(" -B Suppresses output of boundary information.\n"); - printf(" -P Suppresses output of .poly file.\n"); - printf(" -N Suppresses output of .node file.\n"); - printf(" -E Suppresses output of .ele file.\n"); - printf(" -I Suppresses mesh iteration numbers.\n"); - printf(" -O Ignores holes in .poly file.\n"); - printf(" -X Suppresses use of exact arithmetic.\n"); - printf(" -z Numbers all items starting from zero (rather than one).\n"); - printf(" -o2 Generates second-order subparametric elements.\n"); -#ifndef CDT_ONLY - printf(" -Y Suppresses boundary segment splitting.\n"); - printf(" -S Specifies maximum number of added Steiner points.\n"); -#endif /* not CDT_ONLY */ -#ifndef REDUCED - printf(" -i Uses incremental method, rather than divide-and-conquer.\n"); - printf(" -F Uses Fortune's sweepline algorithm, rather than d-and-c.\n"); -#endif /* not REDUCED */ - printf(" -l Uses vertical cuts only, rather than alternating cuts.\n"); -#ifndef REDUCED -#ifndef CDT_ONLY - printf( - " -s Force segments into mesh by splitting (instead of using CDT).\n"); -#endif /* not CDT_ONLY */ - printf(" -C Check consistency of final mesh.\n"); -#endif /* not REDUCED */ - printf(" -Q Quiet: No terminal output except errors.\n"); - printf(" -V Verbose: Detailed information on what I'm doing.\n"); - printf(" -h Help: Detailed instructions for Triangle.\n"); - exit(0); -} - -#endif /* not TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* info() Print out complete instructions. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -void info() -{ - printf("Triangle\n"); - printf( -"A Two-Dimensional Quality Mesh Generator and Delaunay Triangulator.\n"); - printf("Version 1.3\n\n"); - printf( -"Copyright 1996 Jonathan Richard Shewchuk (bugs/comments to jrs@cs.cmu.edu)\n" -); - printf("School of Computer Science / Carnegie Mellon University\n"); - printf("5000 Forbes Avenue / Pittsburgh, Pennsylvania 15213-3891\n"); - printf( -"Created as part of the Archimedes project (tools for parallel FEM).\n"); - printf( -"Supported in part by NSF Grant CMS-9318163 and an NSERC 1967 Scholarship.\n"); - printf("There is no warranty whatsoever. Use at your own risk.\n"); -#ifdef SINGLE - printf("This executable is compiled for single precision arithmetic.\n\n\n"); -#else /* not SINGLE */ - printf("This executable is compiled for double precision arithmetic.\n\n\n"); -#endif /* not SINGLE */ - printf( -"Triangle generates exact Delaunay triangulations, constrained Delaunay\n"); - printf( -"triangulations, and quality conforming Delaunay triangulations. The latter\n" -); - printf( -"can be generated with no small angles, and are thus suitable for finite\n"); - printf( -"element analysis. If no command line switches are specified, your .node\n"); - printf( -"input file will be read, and the Delaunay triangulation will be returned in\n" -); - printf(".node and .ele output files. The command syntax is:\n\n"); -#ifdef CDT_ONLY -#ifdef REDUCED - printf("triangle [-pAcevngBPNEIOXzo_lQVh] input_file\n\n"); -#else /* not REDUCED */ - printf("triangle [-pAcevngBPNEIOXzo_iFlCQVh] input_file\n\n"); -#endif /* not REDUCED */ -#else /* not CDT_ONLY */ -#ifdef REDUCED - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__lQVh] input_file\n\n"); -#else /* not REDUCED */ - printf("triangle [-prq__a__AcevngBPNEIOXzo_YS__iFlsCQVh] input_file\n\n"); -#endif /* not REDUCED */ -#endif /* not CDT_ONLY */ - printf( -"Underscores indicate that numbers may optionally follow certain switches;\n"); - printf( -"do not leave any space between a switch and its numeric parameter.\n"); - printf( -"input_file must be a file with extension .node, or extension .poly if the\n"); - printf( -"-p switch is used. If -r is used, you must supply .node and .ele files,\n"); - printf( -"and possibly a .poly file and .area file as well. The formats of these\n"); - printf("files are described below.\n\n"); - printf("Command Line Switches:\n\n"); - printf( -" -p Reads a Planar Straight Line Graph (.poly file), which can specify\n" -); - printf( -" points, segments, holes, and regional attributes and area\n"); - printf( -" constraints. Will generate a constrained Delaunay triangulation\n"); - printf( -" fitting the input; or, if -s, -q, or -a is used, a conforming\n"); - printf( -" Delaunay triangulation. If -p is not used, Triangle reads a .node\n" -); - printf(" file by default.\n"); - printf( -" -r Refines a previously generated mesh. The mesh is read from a .node\n" -); - printf( -" file and an .ele file. If -p is also used, a .poly file is read\n"); - printf( -" and used to constrain edges in the mesh. Further details on\n"); - printf(" refinement are given below.\n"); - printf( -" -q Quality mesh generation by Jim Ruppert's Delaunay refinement\n"); - printf( -" algorithm. Adds points to the mesh to ensure that no angles\n"); - printf( -" smaller than 20 degrees occur. An alternative minimum angle may be\n" -); - printf( -" specified after the `q'. If the minimum angle is 20.7 degrees or\n"); - printf( -" smaller, the triangulation algorithm is theoretically guaranteed to\n" -); - printf( -" terminate (assuming infinite precision arithmetic - Triangle may\n"); - printf( -" fail to terminate if you run out of precision). In practice, the\n"); - printf( -" algorithm often succeeds for minimum angles up to 33.8 degrees.\n"); - printf( -" For highly refined meshes, however, it may be necessary to reduce\n"); - printf( -" the minimum angle to well below 20 to avoid problems associated\n"); - printf( -" with insufficient floating-point precision. The specified angle\n"); - printf(" may include a decimal point.\n"); - printf( -" -a Imposes a maximum triangle area. If a number follows the `a', no\n"); - printf( -" triangle will be generated whose area is larger than that number.\n"); - printf( -" If no number is specified, an .area file (if -r is used) or .poly\n"); - printf( -" file (if -r is not used) specifies a number of maximum area\n"); - printf( -" constraints. An .area file contains a separate area constraint for\n" -); - printf( -" each triangle, and is useful for refining a finite element mesh\n"); - printf( -" based on a posteriori error estimates. A .poly file can optionally\n" -); - printf( -" contain an area constraint for each segment-bounded region, thereby\n" -); - printf( -" enforcing triangle densities in a first triangulation. You can\n"); - printf( -" impose both a fixed area constraint and a varying area constraint\n"); - printf( -" by invoking the -a switch twice, once with and once without a\n"); - printf( -" number following. Each area specified may include a decimal point.\n" -); - printf( -" -A Assigns an additional attribute to each triangle that identifies\n"); - printf( -" what segment-bounded region each triangle belongs to. Attributes\n"); - printf( -" are assigned to regions by the .poly file. If a region is not\n"); - printf( -" explicitly marked by the .poly file, triangles in that region are\n"); - printf( -" assigned an attribute of zero. The -A switch has an effect only\n"); - printf(" when the -p switch is used and the -r switch is not.\n"); - printf( -" -c Creates segments on the convex hull of the triangulation. If you\n"); - printf( -" are triangulating a point set, this switch causes a .poly file to\n"); - printf( -" be written, containing all edges in the convex hull. (By default,\n" -); - printf( -" a .poly file is written only if a .poly file is read.) If you are\n" -); - printf( -" triangulating a PSLG, this switch specifies that the interior of\n"); - printf( -" the convex hull of the PSLG should be triangulated. If you do not\n" -); - printf( -" use this switch when triangulating a PSLG, it is assumed that you\n"); - printf( -" have identified the region to be triangulated by surrounding it\n"); - printf( -" with segments of the input PSLG. Beware: if you are not careful,\n" -); - printf( -" this switch can cause the introduction of an extremely thin angle\n"); - printf( -" between a PSLG segment and a convex hull segment, which can cause\n"); - printf( -" overrefinement or failure if Triangle runs out of precision. If\n"); - printf( -" you are refining a mesh, the -c switch works differently; it\n"); - printf( -" generates the set of boundary edges of the mesh, rather than the\n"); - printf(" convex hull.\n"); - printf( -" -e Outputs (to an .edge file) a list of edges of the triangulation.\n"); - printf( -" -v Outputs the Voronoi diagram associated with the triangulation.\n"); - printf(" Does not attempt to detect degeneracies.\n"); - printf( -" -n Outputs (to a .neigh file) a list of triangles neighboring each\n"); - printf(" triangle.\n"); - printf( -" -g Outputs the mesh to an Object File Format (.off) file, suitable for\n" -); - printf(" viewing with the Geometry Center's Geomview package.\n"); - printf( -" -B No boundary markers in the output .node, .poly, and .edge output\n"); - printf( -" files. See the detailed discussion of boundary markers below.\n"); - printf( -" -P No output .poly file. Saves disk space, but you lose the ability\n"); - printf( -" to impose segment constraints on later refinements of the mesh.\n"); - printf(" -N No output .node file.\n"); - printf(" -E No output .ele file.\n"); - printf( -" -I No iteration numbers. Suppresses the output of .node and .poly\n"); - printf( -" files, so your input files won't be overwritten. (If your input is\n" -); - printf( -" a .poly file only, a .node file will be written.) Cannot be used\n"); - printf( -" with the -r switch, because that would overwrite your input .ele\n"); - printf( -" file. Shouldn't be used with the -s, -q, or -a switch if you are\n"); - printf( -" using a .node file for input, because no .node file will be\n"); - printf(" written, so there will be no record of any added points.\n"); - printf(" -O No holes. Ignores the holes in the .poly file.\n"); - printf( -" -X No exact arithmetic. Normally, Triangle uses exact floating-point\n" -); - printf( -" arithmetic for certain tests if it thinks the inexact tests are not\n" -); - printf( -" accurate enough. Exact arithmetic ensures the robustness of the\n"); - printf( -" triangulation algorithms, despite floating-point roundoff error.\n"); - printf( -" Disabling exact arithmetic with the -X switch will cause a small\n"); - printf( -" improvement in speed and create the possibility (albeit small) that\n" -); - printf( -" Triangle will fail to produce a valid mesh. Not recommended.\n"); - printf( -" -z Numbers all items starting from zero (rather than one). Note that\n" -); - printf( -" this switch is normally overrided by the value used to number the\n"); - printf( -" first point of the input .node or .poly file. However, this switch\n" -); - printf(" is useful when calling Triangle from another program.\n"); - printf( -" -o2 Generates second-order subparametric elements with six nodes each.\n" -); - printf( -" -Y No new points on the boundary. This switch is useful when the mesh\n" -); - printf( -" boundary must be preserved so that it conforms to some adjacent\n"); - printf( -" mesh. Be forewarned that you will probably sacrifice some of the\n"); - printf( -" quality of the mesh; Triangle will try, but the resulting mesh may\n" -); - printf( -" contain triangles of poor aspect ratio. Works well if all the\n"); - printf( -" boundary points are closely spaced. Specify this switch twice\n"); - printf( -" (`-YY') to prevent all segment splitting, including internal\n"); - printf(" boundaries.\n"); - printf( -" -S Specifies the maximum number of Steiner points (points that are not\n" -); - printf( -" in the input, but are added to meet the constraints of minimum\n"); - printf( -" angle and maximum area). The default is to allow an unlimited\n"); - printf( -" number. If you specify this switch with no number after it,\n"); - printf( -" the limit is set to zero. Triangle always adds points at segment\n"); - printf( -" intersections, even if it needs to use more points than the limit\n"); - printf( -" you set. When Triangle inserts segments by splitting (-s), it\n"); - printf( -" always adds enough points to ensure that all the segments appear in\n" -); - printf( -" the triangulation, again ignoring the limit. Be forewarned that\n"); - printf( -" the -S switch may result in a conforming triangulation that is not\n" -); - printf( -" truly Delaunay, because Triangle may be forced to stop adding\n"); - printf( -" points when the mesh is in a state where a segment is non-Delaunay\n" -); - printf( -" and needs to be split. If so, Triangle will print a warning.\n"); - printf( -" -i Uses an incremental rather than divide-and-conquer algorithm to\n"); - printf( -" form a Delaunay triangulation. Try it if the divide-and-conquer\n"); - printf(" algorithm fails.\n"); - printf( -" -F Uses Steven Fortune's sweepline algorithm to form a Delaunay\n"); - printf( -" triangulation. Warning: does not use exact arithmetic for all\n"); - printf(" calculations. An exact result is not guaranteed.\n"); - printf( -" -l Uses only vertical cuts in the divide-and-conquer algorithm. By\n"); - printf( -" default, Triangle uses alternating vertical and horizontal cuts,\n"); - printf( -" which usually improve the speed except with point sets that are\n"); - printf( -" small or short and wide. This switch is primarily of theoretical\n"); - printf(" interest.\n"); - printf( -" -s Specifies that segments should be forced into the triangulation by\n" -); - printf( -" recursively splitting them at their midpoints, rather than by\n"); - printf( -" generating a constrained Delaunay triangulation. Segment splitting\n" -); - printf( -" is true to Ruppert's original algorithm, but can create needlessly\n" -); - printf(" small triangles near external small features.\n"); - printf( -" -C Check the consistency of the final mesh. Uses exact arithmetic for\n" -); - printf( -" checking, even if the -X switch is used. Useful if you suspect\n"); - printf(" Triangle is buggy.\n"); - printf( -" -Q Quiet: Suppresses all explanation of what Triangle is doing, unless\n" -); - printf(" an error occurs.\n"); - printf( -" -V Verbose: Gives detailed information about what Triangle is doing.\n"); - printf( -" Add more `V's for increasing amount of detail. `-V' gives\n"); - printf( -" information on algorithmic progress and more detailed statistics.\n"); - printf( -" `-VV' gives point-by-point details, and will print so much that\n"); - printf( -" Triangle will run much more slowly. `-VVV' gives information only\n" -); - printf(" a debugger could love.\n"); - printf(" -h Help: Displays these instructions.\n"); - printf("\n"); - printf("Definitions:\n"); - printf("\n"); - printf( -" A Delaunay triangulation of a point set is a triangulation whose vertices\n" -); - printf( -" are the point set, having the property that no point in the point set\n"); - printf( -" falls in the interior of the circumcircle (circle that passes through all\n" -); - printf(" three vertices) of any triangle in the triangulation.\n\n"); - printf( -" A Voronoi diagram of a point set is a subdivision of the plane into\n"); - printf( -" polygonal regions (some of which may be infinite), where each region is\n"); - printf( -" the set of points in the plane that are closer to some input point than\n"); - printf( -" to any other input point. (The Voronoi diagram is the geometric dual of\n" -); - printf(" the Delaunay triangulation.)\n\n"); - printf( -" A Planar Straight Line Graph (PSLG) is a collection of points and\n"); - printf( -" segments. Segments are simply edges, whose endpoints are points in the\n"); - printf( -" PSLG. The file format for PSLGs (.poly files) is described below.\n"); - printf("\n"); - printf( -" A constrained Delaunay triangulation of a PSLG is similar to a Delaunay\n"); - printf( -" triangulation, but each PSLG segment is present as a single edge in the\n"); - printf( -" triangulation. (A constrained Delaunay triangulation is not truly a\n"); - printf(" Delaunay triangulation.)\n\n"); - printf( -" A conforming Delaunay triangulation of a PSLG is a true Delaunay\n"); - printf( -" triangulation in which each PSLG segment may have been subdivided into\n"); - printf( -" several edges by the insertion of additional points. These inserted\n"); - printf( -" points are necessary to allow the segments to exist in the mesh while\n"); - printf(" maintaining the Delaunay property.\n\n"); - printf("File Formats:\n\n"); - printf( -" All files may contain comments prefixed by the character '#'. Points,\n"); - printf( -" triangles, edges, holes, and maximum area constraints must be numbered\n"); - printf( -" consecutively, starting from either 1 or 0. Whichever you choose, all\n"); - printf( -" input files must be consistent; if the nodes are numbered from 1, so must\n" -); - printf( -" be all other objects. Triangle automatically detects your choice while\n"); - printf( -" reading the .node (or .poly) file. (When calling Triangle from another\n"); - printf( -" program, use the -z switch if you wish to number objects from zero.)\n"); - printf(" Examples of these file formats are given below.\n\n"); - printf(" .node files:\n"); - printf( -" First line: <# of points> <# of attributes>\n"); - printf( -" <# of boundary markers (0 or 1)>\n" -); - printf( -" Remaining lines: [attributes] [boundary marker]\n"); - printf("\n"); - printf( -" The attributes, which are typically floating-point values of physical\n"); - printf( -" quantities (such as mass or conductivity) associated with the nodes of\n" -); - printf( -" a finite element mesh, are copied unchanged to the output mesh. If -s,\n" -); - printf( -" -q, or -a is selected, each new Steiner point added to the mesh will\n"); - printf(" have attributes assigned to it by linear interpolation.\n\n"); - printf( -" If the fourth entry of the first line is `1', the last column of the\n"); - printf( -" remainder of the file is assumed to contain boundary markers. Boundary\n" -); - printf( -" markers are used to identify boundary points and points resting on PSLG\n" -); - printf( -" segments; a complete description appears in a section below. The .node\n" -); - printf( -" file produced by Triangle will contain boundary markers in the last\n"); - printf(" column unless they are suppressed by the -B switch.\n\n"); - printf(" .ele files:\n"); - printf( -" First line: <# of triangles> <# of attributes>\n"); - printf( -" Remaining lines: ... [attributes]\n" -); - printf("\n"); - printf( -" Points are indices into the corresponding .node file. The first three\n" -); - printf( -" points are the corners, and are listed in counterclockwise order around\n" -); - printf( -" each triangle. (The remaining points, if any, depend on the type of\n"); - printf( -" finite element used.) The attributes are just like those of .node\n"); - printf( -" files. Because there is no simple mapping from input to output\n"); - printf( -" triangles, an attempt is made to interpolate attributes, which may\n"); - printf( -" result in a good deal of diffusion of attributes among nearby triangles\n" -); - printf( -" as the triangulation is refined. Diffusion does not occur across\n"); - printf( -" segments, so attributes used to identify segment-bounded regions remain\n" -); - printf( -" intact. In output .ele files, all triangles have three points each\n"); - printf( -" unless the -o2 switch is used, in which case they have six, and the\n"); - printf( -" fourth, fifth, and sixth points lie on the midpoints of the edges\n"); - printf(" opposite the first, second, and third corners.\n\n"); - printf(" .poly files:\n"); - printf( -" First line: <# of points> <# of attributes>\n"); - printf( -" <# of boundary markers (0 or 1)>\n" -); - printf( -" Following lines: [attributes] [boundary marker]\n"); - printf(" One line: <# of segments> <# of boundary markers (0 or 1)>\n"); - printf( -" Following lines: [boundary marker]\n"); - printf(" One line: <# of holes>\n"); - printf(" Following lines: \n"); - printf( -" Optional line: <# of regional attributes and/or area constraints>\n"); - printf( -" Optional following lines: \n"); - printf("\n"); - printf( -" A .poly file represents a PSLG, as well as some additional information.\n" -); - printf( -" The first section lists all the points, and is identical to the format\n" -); - printf( -" of .node files. <# of points> may be set to zero to indicate that the\n" -); - printf( -" points are listed in a separate .node file; .poly files produced by\n"); - printf( -" Triangle always have this format. This has the advantage that a point\n" -); - printf( -" set may easily be triangulated with or without segments. (The same\n"); - printf( -" effect can be achieved, albeit using more disk space, by making a copy\n" -); - printf( -" of the .poly file with the extension .node; all sections of the file\n"); - printf(" but the first are ignored.)\n\n"); - printf( -" The second section lists the segments. Segments are edges whose\n"); - printf( -" presence in the triangulation is enforced. Each segment is specified\n"); - printf( -" by listing the indices of its two endpoints. This means that you must\n" -); - printf( -" include its endpoints in the point list. If -s, -q, and -a are not\n"); - printf( -" selected, Triangle will produce a constrained Delaunay triangulation,\n"); - printf( -" in which each segment appears as a single edge in the triangulation.\n"); - printf( -" If -q or -a is selected, Triangle will produce a conforming Delaunay\n"); - printf( -" triangulation, in which segments may be subdivided into smaller edges.\n" -); - printf(" Each segment, like each point, may have a boundary marker.\n\n"); - printf( -" The third section lists holes (and concavities, if -c is selected) in\n"); - printf( -" the triangulation. Holes are specified by identifying a point inside\n"); - printf( -" each hole. After the triangulation is formed, Triangle creates holes\n"); - printf( -" by eating triangles, spreading out from each hole point until its\n"); - printf( -" progress is blocked by PSLG segments; you must be careful to enclose\n"); - printf( -" each hole in segments, or your whole triangulation may be eaten away.\n"); - printf( -" If the two triangles abutting a segment are eaten, the segment itself\n"); - printf( -" is also eaten. Do not place a hole directly on a segment; if you do,\n"); - printf(" Triangle will choose one side of the segment arbitrarily.\n\n"); - printf( -" The optional fourth section lists regional attributes (to be assigned\n"); - printf( -" to all triangles in a region) and regional constraints on the maximum\n"); - printf( -" triangle area. Triangle will read this section only if the -A switch\n"); - printf( -" is used or the -a switch is used without a number following it, and the\n" -); - printf( -" -r switch is not used. Regional attributes and area constraints are\n"); - printf( -" propagated in the same manner as holes; you specify a point for each\n"); - printf( -" attribute and/or constraint, and the attribute and/or constraint will\n"); - printf( -" affect the whole region (bounded by segments) containing the point. If\n" -); - printf( -" two values are written on a line after the x and y coordinate, the\n"); - printf( -" former is assumed to be a regional attribute (but will only be applied\n" -); - printf( -" if the -A switch is selected), and the latter is assumed to be a\n"); - printf( -" regional area constraint (but will only be applied if the -a switch is\n" -); - printf( -" selected). You may also specify just one value after the coordinates,\n" -); - printf( -" which can serve as both an attribute and an area constraint, depending\n" -); - printf( -" on the choice of switches. If you are using the -A and -a switches\n"); - printf( -" simultaneously and wish to assign an attribute to some region without\n"); - printf(" imposing an area constraint, use a negative maximum area.\n\n"); - printf( -" When a triangulation is created from a .poly file, you must either\n"); - printf( -" enclose the entire region to be triangulated in PSLG segments, or\n"); - printf( -" use the -c switch, which encloses the convex hull of the input point\n"); - printf( -" set. If you do not use the -c switch, Triangle will eat all triangles\n" -); - printf( -" on the outer boundary that are not protected by segments; if you are\n"); - printf( -" not careful, your whole triangulation may be eaten away. If you do\n"); - printf( -" use the -c switch, you can still produce concavities by appropriate\n"); - printf(" placement of holes just inside the convex hull.\n\n"); - printf( -" An ideal PSLG has no intersecting segments, nor any points that lie\n"); - printf( -" upon segments (except, of course, the endpoints of each segment.) You\n" -); - printf( -" aren't required to make your .poly files ideal, but you should be aware\n" -); - printf( -" of what can go wrong. Segment intersections are relatively safe -\n"); - printf( -" Triangle will calculate the intersection points for you and add them to\n" -); - printf( -" the triangulation - as long as your machine's floating-point precision\n" -); - printf( -" doesn't become a problem. You are tempting the fates if you have three\n" -); - printf( -" segments that cross at the same location, and expect Triangle to figure\n" -); - printf( -" out where the intersection point is. Thanks to floating-point roundoff\n" -); - printf( -" error, Triangle will probably decide that the three segments intersect\n" -); - printf( -" at three different points, and you will find a minuscule triangle in\n"); - printf( -" your output - unless Triangle tries to refine the tiny triangle, uses\n"); - printf( -" up the last bit of machine precision, and fails to terminate at all.\n"); - printf( -" You're better off putting the intersection point in the input files,\n"); - printf( -" and manually breaking up each segment into two. Similarly, if you\n"); - printf( -" place a point at the middle of a segment, and hope that Triangle will\n"); - printf( -" break up the segment at that point, you might get lucky. On the other\n" -); - printf( -" hand, Triangle might decide that the point doesn't lie precisely on the\n" -); - printf( -" line, and you'll have a needle-sharp triangle in your output - or a lot\n" -); - printf(" of tiny triangles if you're generating a quality mesh.\n\n"); - printf( -" When Triangle reads a .poly file, it also writes a .poly file, which\n"); - printf( -" includes all edges that are part of input segments. If the -c switch\n"); - printf( -" is used, the output .poly file will also include all of the edges on\n"); - printf( -" the convex hull. Hence, the output .poly file is useful for finding\n"); - printf( -" edges associated with input segments and setting boundary conditions in\n" -); - printf( -" finite element simulations. More importantly, you will need it if you\n" -); - printf( -" plan to refine the output mesh, and don't want segments to be missing\n"); - printf(" in later triangulations.\n\n"); - printf(" .area files:\n"); - printf(" First line: <# of triangles>\n"); - printf(" Following lines: \n\n"); - printf( -" An .area file associates with each triangle a maximum area that is used\n" -); - printf( -" for mesh refinement. As with other file formats, every triangle must\n"); - printf( -" be represented, and they must be numbered consecutively. A triangle\n"); - printf( -" may be left unconstrained by assigning it a negative maximum area.\n"); - printf("\n"); - printf(" .edge files:\n"); - printf(" First line: <# of edges> <# of boundary markers (0 or 1)>\n"); - printf( -" Following lines: [boundary marker]\n"); - printf("\n"); - printf( -" Endpoints are indices into the corresponding .node file. Triangle can\n" -); - printf( -" produce .edge files (use the -e switch), but cannot read them. The\n"); - printf( -" optional column of boundary markers is suppressed by the -B switch.\n"); - printf("\n"); - printf( -" In Voronoi diagrams, one also finds a special kind of edge that is an\n"); - printf( -" infinite ray with only one endpoint. For these edges, a different\n"); - printf(" format is used:\n\n"); - printf(" -1 \n\n"); - printf( -" The `direction' is a floating-point vector that indicates the direction\n" -); - printf(" of the infinite ray.\n\n"); - printf(" .neigh files:\n"); - printf( -" First line: <# of triangles> <# of neighbors per triangle (always 3)>\n" -); - printf( -" Following lines: \n"); - printf("\n"); - printf( -" Neighbors are indices into the corresponding .ele file. An index of -1\n" -); - printf( -" indicates a mesh boundary, and therefore no neighbor. Triangle can\n"); - printf( -" produce .neigh files (use the -n switch), but cannot read them.\n"); - printf("\n"); - printf( -" The first neighbor of triangle i is opposite the first corner of\n"); - printf(" triangle i, and so on.\n\n"); - printf("Boundary Markers:\n\n"); - printf( -" Boundary markers are tags used mainly to identify which output points and\n" -); - printf( -" edges are associated with which PSLG segment, and to identify which\n"); - printf( -" points and edges occur on a boundary of the triangulation. A common use\n" -); - printf( -" is to determine where boundary conditions should be applied to a finite\n"); - printf( -" element mesh. You can prevent boundary markers from being written into\n"); - printf(" files produced by Triangle by using the -B switch.\n\n"); - printf( -" The boundary marker associated with each segment in an output .poly file\n" -); - printf(" or edge in an output .edge file is chosen as follows:\n"); - printf( -" - If an output edge is part or all of a PSLG segment with a nonzero\n"); - printf( -" boundary marker, then the edge is assigned the same marker.\n"); - printf( -" - Otherwise, if the edge occurs on a boundary of the triangulation\n"); - printf( -" (including boundaries of holes), then the edge is assigned the marker\n" -); - printf(" one (1).\n"); - printf(" - Otherwise, the edge is assigned the marker zero (0).\n"); - printf( -" The boundary marker associated with each point in an output .node file is\n" -); - printf(" chosen as follows:\n"); - printf( -" - If a point is assigned a nonzero boundary marker in the input file,\n"); - printf( -" then it is assigned the same marker in the output .node file.\n"); - printf( -" - Otherwise, if the point lies on a PSLG segment (including the\n"); - printf( -" segment's endpoints) with a nonzero boundary marker, then the point\n"); - printf( -" is assigned the same marker. If the point lies on several such\n"); - printf(" segments, one of the markers is chosen arbitrarily.\n"); - printf( -" - Otherwise, if the point occurs on a boundary of the triangulation,\n"); - printf(" then the point is assigned the marker one (1).\n"); - printf(" - Otherwise, the point is assigned the marker zero (0).\n"); - printf("\n"); - printf( -" If you want Triangle to determine for you which points and edges are on\n"); - printf( -" the boundary, assign them the boundary marker zero (or use no markers at\n" -); - printf( -" all) in your input files. Alternatively, you can mark some of them and\n"); - printf(" leave others marked zero, allowing Triangle to label them.\n\n"); - printf("Triangulation Iteration Numbers:\n\n"); - printf( -" Because Triangle can read and refine its own triangulations, input\n"); - printf( -" and output files have iteration numbers. For instance, Triangle might\n"); - printf( -" read the files mesh.3.node, mesh.3.ele, and mesh.3.poly, refine the\n"); - printf( -" triangulation, and output the files mesh.4.node, mesh.4.ele, and\n"); - printf(" mesh.4.poly. Files with no iteration number are treated as if\n"); - printf( -" their iteration number is zero; hence, Triangle might read the file\n"); - printf( -" points.node, triangulate it, and produce the files points.1.node and\n"); - printf(" points.1.ele.\n\n"); - printf( -" Iteration numbers allow you to create a sequence of successively finer\n"); - printf( -" meshes suitable for multigrid methods. They also allow you to produce a\n" -); - printf( -" sequence of meshes using error estimate-driven mesh refinement.\n"); - printf("\n"); - printf( -" If you're not using refinement or quality meshing, and you don't like\n"); - printf( -" iteration numbers, use the -I switch to disable them. This switch will\n"); - printf( -" also disable output of .node and .poly files to prevent your input files\n" -); - printf( -" from being overwritten. (If the input is a .poly file that contains its\n" -); - printf(" own points, a .node file will be written.)\n\n"); - printf("Examples of How to Use Triangle:\n\n"); - printf( -" `triangle dots' will read points from dots.node, and write their Delaunay\n" -); - printf( -" triangulation to dots.1.node and dots.1.ele. (dots.1.node will be\n"); - printf( -" identical to dots.node.) `triangle -I dots' writes the triangulation to\n" -); - printf( -" dots.ele instead. (No additional .node file is needed, so none is\n"); - printf(" written.)\n\n"); - printf( -" `triangle -pe object.1' will read a PSLG from object.1.poly (and possibly\n" -); - printf( -" object.1.node, if the points are omitted from object.1.poly) and write\n"); - printf(" their constrained Delaunay triangulation to object.2.node and\n"); - printf( -" object.2.ele. The segments will be copied to object.2.poly, and all\n"); - printf(" edges will be written to object.2.edge.\n\n"); - printf( -" `triangle -pq31.5a.1 object' will read a PSLG from object.poly (and\n"); - printf( -" possibly object.node), generate a mesh whose angles are all greater than\n" -); - printf( -" 31.5 degrees and whose triangles all have area smaller than 0.1, and\n"); - printf( -" write the mesh to object.1.node and object.1.ele. Each segment may have\n" -); - printf( -" been broken up into multiple edges; the resulting constrained edges are\n"); - printf(" written to object.1.poly.\n\n"); - printf( -" Here is a sample file `box.poly' describing a square with a square hole:\n" -); - printf("\n"); - printf( -" # A box with eight points in 2D, no attributes, one boundary marker.\n"); - printf(" 8 2 0 1\n"); - printf(" # Outer box has these vertices:\n"); - printf(" 1 0 0 0\n"); - printf(" 2 0 3 0\n"); - printf(" 3 3 0 0\n"); - printf(" 4 3 3 33 # A special marker for this point.\n"); - printf(" # Inner square has these vertices:\n"); - printf(" 5 1 1 0\n"); - printf(" 6 1 2 0\n"); - printf(" 7 2 1 0\n"); - printf(" 8 2 2 0\n"); - printf(" # Five segments with boundary markers.\n"); - printf(" 5 1\n"); - printf(" 1 1 2 5 # Left side of outer box.\n"); - printf(" 2 5 7 0 # Segments 2 through 5 enclose the hole.\n"); - printf(" 3 7 8 0\n"); - printf(" 4 8 6 10\n"); - printf(" 5 6 5 0\n"); - printf(" # One hole in the middle of the inner square.\n"); - printf(" 1\n"); - printf(" 1 1.5 1.5\n\n"); - printf( -" Note that some segments are missing from the outer square, so one must\n"); - printf( -" use the `-c' switch. After `triangle -pqc box.poly', here is the output\n" -); - printf( -" file `box.1.node', with twelve points. The last four points were added\n"); - printf( -" to meet the angle constraint. Points 1, 2, and 9 have markers from\n"); - printf( -" segment 1. Points 6 and 8 have markers from segment 4. All the other\n"); - printf( -" points but 4 have been marked to indicate that they lie on a boundary.\n"); - printf("\n"); - printf(" 12 2 0 1\n"); - printf(" 1 0 0 5\n"); - printf(" 2 0 3 5\n"); - printf(" 3 3 0 1\n"); - printf(" 4 3 3 33\n"); - printf(" 5 1 1 1\n"); - printf(" 6 1 2 10\n"); - printf(" 7 2 1 1\n"); - printf(" 8 2 2 10\n"); - printf(" 9 0 1.5 5\n"); - printf(" 10 1.5 0 1\n"); - printf(" 11 3 1.5 1\n"); - printf(" 12 1.5 3 1\n"); - printf(" # Generated by triangle -pqc box.poly\n\n"); - printf(" Here is the output file `box.1.ele', with twelve triangles.\n\n"); - printf(" 12 3 0\n"); - printf(" 1 5 6 9\n"); - printf(" 2 10 3 7\n"); - printf(" 3 6 8 12\n"); - printf(" 4 9 1 5\n"); - printf(" 5 6 2 9\n"); - printf(" 6 7 3 11\n"); - printf(" 7 11 4 8\n"); - printf(" 8 7 5 10\n"); - printf(" 9 12 2 6\n"); - printf(" 10 8 7 11\n"); - printf(" 11 5 1 10\n"); - printf(" 12 8 4 12\n"); - printf(" # Generated by triangle -pqc box.poly\n\n"); - printf( -" Here is the output file `box.1.poly'. Note that segments have been added\n" -); - printf( -" to represent the convex hull, and some segments have been split by newly\n" -); - printf( -" added points. Note also that <# of points> is set to zero to indicate\n"); - printf(" that the points should be read from the .node file.\n\n"); - printf(" 0 2 0 1\n"); - printf(" 12 1\n"); - printf(" 1 1 9 5\n"); - printf(" 2 5 7 1\n"); - printf(" 3 8 7 1\n"); - printf(" 4 6 8 10\n"); - printf(" 5 5 6 1\n"); - printf(" 6 3 10 1\n"); - printf(" 7 4 11 1\n"); - printf(" 8 2 12 1\n"); - printf(" 9 9 2 5\n"); - printf(" 10 10 1 1\n"); - printf(" 11 11 3 1\n"); - printf(" 12 12 4 1\n"); - printf(" 1\n"); - printf(" 1 1.5 1.5\n"); - printf(" # Generated by triangle -pqc box.poly\n\n"); - printf("Refinement and Area Constraints:\n\n"); - printf( -" The -r switch causes a mesh (.node and .ele files) to be read and\n"); - printf( -" refined. If the -p switch is also used, a .poly file is read and used to\n" -); - printf( -" specify edges that are constrained and cannot be eliminated (although\n"); - printf( -" they can be divided into smaller edges) by the refinement process.\n"); - printf("\n"); - printf( -" When you refine a mesh, you generally want to impose tighter quality\n"); - printf( -" constraints. One way to accomplish this is to use -q with a larger\n"); - printf( -" angle, or -a followed by a smaller area than you used to generate the\n"); - printf( -" mesh you are refining. Another way to do this is to create an .area\n"); - printf( -" file, which specifies a maximum area for each triangle, and use the -a\n"); - printf( -" switch (without a number following). Each triangle's area constraint is\n" -); - printf( -" applied to that triangle. Area constraints tend to diffuse as the mesh\n"); - printf( -" is refined, so if there are large variations in area constraint between\n"); - printf(" adjacent triangles, you may not get the results you want.\n\n"); - printf( -" If you are refining a mesh composed of linear (three-node) elements, the\n" -); - printf( -" output mesh will contain all the nodes present in the input mesh, in the\n" -); - printf( -" same order, with new nodes added at the end of the .node file. However,\n" -); - printf( -" there is no guarantee that each output element is contained in a single\n"); - printf( -" input element. Often, output elements will overlap two input elements,\n"); - printf( -" and input edges are not present in the output mesh. Hence, a sequence of\n" -); - printf( -" refined meshes will form a hierarchy of nodes, but not a hierarchy of\n"); - printf( -" elements. If you a refining a mesh of higher-order elements, the\n"); - printf( -" hierarchical property applies only to the nodes at the corners of an\n"); - printf(" element; other nodes may not be present in the refined mesh.\n\n"); - printf( -" It is important to understand that maximum area constraints in .poly\n"); - printf( -" files are handled differently from those in .area files. A maximum area\n" -); - printf( -" in a .poly file applies to the whole (segment-bounded) region in which a\n" -); - printf( -" point falls, whereas a maximum area in an .area file applies to only one\n" -); - printf( -" triangle. Area constraints in .poly files are used only when a mesh is\n"); - printf( -" first generated, whereas area constraints in .area files are used only to\n" -); - printf( -" refine an existing mesh, and are typically based on a posteriori error\n"); - printf( -" estimates resulting from a finite element simulation on that mesh.\n"); - printf("\n"); - printf( -" `triangle -rq25 object.1' will read object.1.node and object.1.ele, then\n" -); - printf( -" refine the triangulation to enforce a 25 degree minimum angle, and then\n"); - printf( -" write the refined triangulation to object.2.node and object.2.ele.\n"); - printf("\n"); - printf( -" `triangle -rpaa6.2 z.3' will read z.3.node, z.3.ele, z.3.poly, and\n"); - printf( -" z.3.area. After reconstructing the mesh and its segments, Triangle will\n" -); - printf( -" refine the mesh so that no triangle has area greater than 6.2, and\n"); - printf( -" furthermore the triangles satisfy the maximum area constraints in\n"); - printf( -" z.3.area. The output is written to z.4.node, z.4.ele, and z.4.poly.\n"); - printf("\n"); - printf( -" The sequence `triangle -qa1 x', `triangle -rqa.3 x.1', `triangle -rqa.1\n"); - printf( -" x.2' creates a sequence of successively finer meshes x.1, x.2, and x.3,\n"); - printf(" suitable for multigrid.\n\n"); - printf("Convex Hulls and Mesh Boundaries:\n\n"); - printf( -" If the input is a point set (rather than a PSLG), Triangle produces its\n"); - printf( -" convex hull as a by-product in the output .poly file if you use the -c\n"); - printf( -" switch. There are faster algorithms for finding a two-dimensional convex\n" -); - printf( -" hull than triangulation, of course, but this one comes for free. If the\n" -); - printf( -" input is an unconstrained mesh (you are using the -r switch but not the\n"); - printf( -" -p switch), Triangle produces a list of its boundary edges (including\n"); - printf(" hole boundaries) as a by-product if you use the -c switch.\n\n"); - printf("Voronoi Diagrams:\n\n"); - printf( -" The -v switch produces a Voronoi diagram, in files suffixed .v.node and\n"); - printf( -" .v.edge. For example, `triangle -v points' will read points.node,\n"); - printf( -" produce its Delaunay triangulation in points.1.node and points.1.ele,\n"); - printf( -" and produce its Voronoi diagram in points.1.v.node and points.1.v.edge.\n"); - printf( -" The .v.node file contains a list of all Voronoi vertices, and the .v.edge\n" -); - printf( -" file contains a list of all Voronoi edges, some of which may be infinite\n" -); - printf( -" rays. (The choice of filenames makes it easy to run the set of Voronoi\n"); - printf(" vertices through Triangle, if so desired.)\n\n"); - printf( -" This implementation does not use exact arithmetic to compute the Voronoi\n" -); - printf( -" vertices, and does not check whether neighboring vertices are identical.\n" -); - printf( -" Be forewarned that if the Delaunay triangulation is degenerate or\n"); - printf( -" near-degenerate, the Voronoi diagram may have duplicate points, crossing\n" -); - printf( -" edges, or infinite rays whose direction vector is zero. Also, if you\n"); - printf( -" generate a constrained (as opposed to conforming) Delaunay triangulation,\n" -); - printf( -" or if the triangulation has holes, the corresponding Voronoi diagram is\n"); - printf(" likely to have crossing edges and unlikely to make sense.\n\n"); - printf("Mesh Topology:\n\n"); - printf( -" You may wish to know which triangles are adjacent to a certain Delaunay\n"); - printf( -" edge in an .edge file, which Voronoi regions are adjacent to a certain\n"); - printf( -" Voronoi edge in a .v.edge file, or which Voronoi regions are adjacent to\n" -); - printf( -" each other. All of this information can be found by cross-referencing\n"); - printf( -" output files with the recollection that the Delaunay triangulation and\n"); - printf(" the Voronoi diagrams are planar duals.\n\n"); - printf( -" Specifically, edge i of an .edge file is the dual of Voronoi edge i of\n"); - printf( -" the corresponding .v.edge file, and is rotated 90 degrees counterclock-\n"); - printf( -" wise from the Voronoi edge. Triangle j of an .ele file is the dual of\n"); - printf( -" vertex j of the corresponding .v.node file; and Voronoi region k is the\n"); - printf(" dual of point k of the corresponding .node file.\n\n"); - printf( -" Hence, to find the triangles adjacent to a Delaunay edge, look at the\n"); - printf( -" vertices of the corresponding Voronoi edge; their dual triangles are on\n"); - printf( -" the left and right of the Delaunay edge, respectively. To find the\n"); - printf( -" Voronoi regions adjacent to a Voronoi edge, look at the endpoints of the\n" -); - printf( -" corresponding Delaunay edge; their dual regions are on the right and left\n" -); - printf( -" of the Voronoi edge, respectively. To find which Voronoi regions are\n"); - printf(" adjacent to each other, just read the list of Delaunay edges.\n"); - printf("\n"); - printf("Statistics:\n"); - printf("\n"); - printf( -" After generating a mesh, Triangle prints a count of the number of points,\n" -); - printf( -" triangles, edges, boundary edges, and segments in the output mesh. If\n"); - printf( -" you've forgotten the statistics for an existing mesh, the -rNEP switches\n" -); - printf( -" (or -rpNEP if you've got a .poly file for the existing mesh) will\n"); - printf(" regenerate these statistics without writing any output.\n\n"); - printf( -" The -V switch produces extended statistics, including a rough estimate\n"); - printf( -" of memory use and a histogram of triangle aspect ratios and angles in the\n" -); - printf(" mesh.\n\n"); - printf("Exact Arithmetic:\n\n"); - printf( -" Triangle uses adaptive exact arithmetic to perform what computational\n"); - printf( -" geometers call the `orientation' and `incircle' tests. If the floating-\n" -); - printf( -" point arithmetic of your machine conforms to the IEEE 754 standard (as\n"); - printf( -" most workstations do), and does not use extended precision internal\n"); - printf( -" registers, then your output is guaranteed to be an absolutely true\n"); - printf(" Delaunay or conforming Delaunay triangulation, roundoff error\n"); - printf( -" notwithstanding. The word `adaptive' implies that these arithmetic\n"); - printf( -" routines compute the result only to the precision necessary to guarantee\n" -); - printf( -" correctness, so they are usually nearly as fast as their approximate\n"); - printf( -" counterparts. The exact tests can be disabled with the -X switch. On\n"); - printf( -" most inputs, this switch will reduce the computation time by about eight\n" -); - printf( -" percent - it's not worth the risk. There are rare difficult inputs\n"); - printf( -" (having many collinear and cocircular points), however, for which the\n"); - printf( -" difference could be a factor of two. These are precisely the inputs most\n" -); - printf(" likely to cause errors if you use the -X switch.\n\n"); - printf( -" Unfortunately, these routines don't solve every numerical problem. Exact\n" -); - printf( -" arithmetic is not used to compute the positions of points, because the\n"); - printf( -" bit complexity of point coordinates would grow without bound. Hence,\n"); - printf( -" segment intersections aren't computed exactly; in very unusual cases,\n"); - printf( -" roundoff error in computing an intersection point might actually lead to\n" -); - printf( -" an inverted triangle and an invalid triangulation. (This is one reason\n"); - printf( -" to compute your own intersection points in your .poly files.) Similarly,\n" -); - printf( -" exact arithmetic is not used to compute the vertices of the Voronoi\n"); - printf(" diagram.\n\n"); - printf( -" Underflow and overflow can also cause difficulties; the exact arithmetic\n" -); - printf( -" routines do not ameliorate out-of-bounds exponents, which can arise\n"); - printf( -" during the orientation and incircle tests. As a rule of thumb, you\n"); - printf( -" should ensure that your input values are within a range such that their\n"); - printf( -" third powers can be taken without underflow or overflow. Underflow can\n"); - printf( -" silently prevent the tests from being performed exactly, while overflow\n"); - printf(" will typically cause a floating exception.\n\n"); - printf("Calling Triangle from Another Program:\n\n"); - printf(" Read the file triangle.h for details.\n\n"); - printf("Troubleshooting:\n\n"); - printf(" Please read this section before mailing me bugs.\n\n"); - printf(" `My output mesh has no triangles!'\n\n"); - printf( -" If you're using a PSLG, you've probably failed to specify a proper set\n" -); - printf( -" of bounding segments, or forgotten to use the -c switch. Or you may\n"); - printf( -" have placed a hole badly. To test these possibilities, try again with\n" -); - printf( -" the -c and -O switches. Alternatively, all your input points may be\n"); - printf( -" collinear, in which case you can hardly expect to triangulate them.\n"); - printf("\n"); - printf(" `Triangle doesn't terminate, or just crashes.'\n"); - printf("\n"); - printf( -" Bad things can happen when triangles get so small that the distance\n"); - printf( -" between their vertices isn't much larger than the precision of your\n"); - printf( -" machine's arithmetic. If you've compiled Triangle for single-precision\n" -); - printf( -" arithmetic, you might do better by recompiling it for double-precision.\n" -); - printf( -" Then again, you might just have to settle for more lenient constraints\n" -); - printf( -" on the minimum angle and the maximum area than you had planned.\n"); - printf("\n"); - printf( -" You can minimize precision problems by ensuring that the origin lies\n"); - printf( -" inside your point set, or even inside the densest part of your\n"); - printf( -" mesh. On the other hand, if you're triangulating an object whose x\n"); - printf( -" coordinates all fall between 6247133 and 6247134, you're not leaving\n"); - printf(" much floating-point precision for Triangle to work with.\n\n"); - printf( -" Precision problems can occur covertly if the input PSLG contains two\n"); - printf( -" segments that meet (or intersect) at a very small angle, or if such an\n" -); - printf( -" angle is introduced by the -c switch, which may occur if a point lies\n"); - printf( -" ever-so-slightly inside the convex hull, and is connected by a PSLG\n"); - printf( -" segment to a point on the convex hull. If you don't realize that a\n"); - printf( -" small angle is being formed, you might never discover why Triangle is\n"); - printf( -" crashing. To check for this possibility, use the -S switch (with an\n"); - printf( -" appropriate limit on the number of Steiner points, found by trial-and-\n" -); - printf( -" error) to stop Triangle early, and view the output .poly file with\n"); - printf( -" Show Me (described below). Look carefully for small angles between\n"); - printf( -" segments; zoom in closely, as such segments might look like a single\n"); - printf(" segment from a distance.\n\n"); - printf( -" If some of the input values are too large, Triangle may suffer a\n"); - printf( -" floating exception due to overflow when attempting to perform an\n"); - printf( -" orientation or incircle test. (Read the section on exact arithmetic\n"); - printf( -" above.) Again, I recommend compiling Triangle for double (rather\n"); - printf(" than single) precision arithmetic.\n\n"); - printf( -" `The numbering of the output points doesn't match the input points.'\n"); - printf("\n"); - printf( -" You may have eaten some of your input points with a hole, or by placing\n" -); - printf(" them outside the area enclosed by segments.\n\n"); - printf( -" `Triangle executes without incident, but when I look at the resulting\n"); - printf( -" mesh, it has overlapping triangles or other geometric inconsistencies.'\n"); - printf("\n"); - printf( -" If you select the -X switch, Triangle's divide-and-conquer Delaunay\n"); - printf( -" triangulation algorithm occasionally makes mistakes due to floating-\n"); - printf( -" point roundoff error. Although these errors are rare, don't use the -X\n" -); - printf(" switch. If you still have problems, please report the bug.\n"); - printf("\n"); - printf( -" Strange things can happen if you've taken liberties with your PSLG. Do\n"); - printf( -" you have a point lying in the middle of a segment? Triangle sometimes\n"); - printf( -" copes poorly with that sort of thing. Do you want to lay out a collinear\n" -); - printf( -" row of evenly spaced, segment-connected points? Have you simply defined\n" -); - printf( -" one long segment connecting the leftmost point to the rightmost point,\n"); - printf( -" and a bunch of points lying along it? This method occasionally works,\n"); - printf( -" especially with horizontal and vertical lines, but often it doesn't, and\n" -); - printf( -" you'll have to connect each adjacent pair of points with a separate\n"); - printf(" segment. If you don't like it, tough.\n\n"); - printf( -" Furthermore, if you have segments that intersect other than at their\n"); - printf( -" endpoints, try not to let the intersections fall extremely close to PSLG\n" -); - printf(" points or each other.\n\n"); - printf( -" If you have problems refining a triangulation not produced by Triangle:\n"); - printf( -" Are you sure the triangulation is geometrically valid? Is it formatted\n"); - printf( -" correctly for Triangle? Are the triangles all listed so the first three\n" -); - printf(" points are their corners in counterclockwise order?\n\n"); - printf("Show Me:\n\n"); - printf( -" Triangle comes with a separate program named `Show Me', whose primary\n"); - printf( -" purpose is to draw meshes on your screen or in PostScript. Its secondary\n" -); - printf( -" purpose is to check the validity of your input files, and do so more\n"); - printf( -" thoroughly than Triangle does. Show Me requires that you have the X\n"); - printf( -" Windows system. If you didn't receive Show Me with Triangle, complain to\n" -); - printf(" whomever you obtained Triangle from, then send me mail.\n\n"); - printf("Triangle on the Web:\n\n"); - printf( -" To see an illustrated, updated version of these instructions, check out\n"); - printf("\n"); - printf(" http://www.cs.cmu.edu/~quake/triangle.html\n"); - printf("\n"); - printf("A Brief Plea:\n"); - printf("\n"); - printf( -" If you use Triangle, and especially if you use it to accomplish real\n"); - printf( -" work, I would like very much to hear from you. A short letter or email\n"); - printf( -" (to jrs@cs.cmu.edu) describing how you use Triangle will mean a lot to\n"); - printf( -" me. The more people I know are using this program, the more easily I can\n" -); - printf( -" justify spending time on improvements and on the three-dimensional\n"); - printf( -" successor to Triangle, which in turn will benefit you. Also, I can put\n"); - printf( -" you on a list to receive email whenever a new version of Triangle is\n"); - printf(" available.\n\n"); - printf( -" If you use a mesh generated by Triangle in a publication, please include\n" -); - printf(" an acknowledgment as well.\n\n"); - printf("Research credit:\n\n"); - printf( -" Of course, I can take credit for only a fraction of the ideas that made\n"); - printf( -" this mesh generator possible. Triangle owes its existence to the efforts\n" -); - printf( -" of many fine computational geometers and other researchers, including\n"); - printf( -" Marshall Bern, L. Paul Chew, Boris Delaunay, Rex A. Dwyer, David\n"); - printf( -" Eppstein, Steven Fortune, Leonidas J. Guibas, Donald E. Knuth, C. L.\n"); - printf( -" Lawson, Der-Tsai Lee, Ernst P. Mucke, Douglas M. Priest, Jim Ruppert,\n"); - printf( -" Isaac Saias, Bruce J. Schachter, Micha Sharir, Jorge Stolfi, Christopher\n" -); - printf( -" J. Van Wyk, David F. Watson, and Binhai Zhu. See the comments at the\n"); - printf(" beginning of the source code for references.\n\n"); - exit(0); -} - -#endif /* not TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* internalerror() Ask the user to send me the defective product. Exit. */ -/* */ -/*****************************************************************************/ - -void internalerror() -{ - printf(" Please report this bug to jrs@cs.cmu.edu\n"); - printf(" Include the message above, your input data set, and the exact\n"); - printf(" command line you used to run Triangle.\n"); - exit(1); -} - -/*****************************************************************************/ -/* */ -/* parsecommandline() Read the command line, identify switches, and set */ -/* up options and file names. */ -/* */ -/* The effects of this routine are felt entirely through global variables. */ -/* */ -/*****************************************************************************/ - -void parsecommandline(argc, argv) -int argc; -char **argv; -{ -#ifdef TRILIBRARY -#define STARTINDEX 0 -#else /* not TRILIBRARY */ -#define STARTINDEX 1 - int increment; - int meshnumber; -#endif /* not TRILIBRARY */ - int i, j; -#ifndef CDT_ONLY - int k; - char workstring[FILENAMESIZE]; -#endif - - poly = refine = quality = vararea = fixedarea = regionattrib = convex = 0; - firstnumber = 1; - edgesout = voronoi = neighbors = geomview = 0; - nobound = nopolywritten = nonodewritten = noelewritten = noiterationnum = 0; - noholes = noexact = 0; - incremental = sweepline = 0; - dwyer = 1; - splitseg = 0; - docheck = 0; - nobisect = 0; - steiner = -1; - order = 1; - minangle = 0.0; - maxarea = -1.0; - quiet = verbose = 0; -#ifndef TRILIBRARY - innodefilename[0] = '\0'; -#endif /* not TRILIBRARY */ - - for (i = STARTINDEX; i < argc; i++) { -#ifndef TRILIBRARY - if (argv[i][0] == '-') { -#endif /* not TRILIBRARY */ - for (j = STARTINDEX; argv[i][j] != '\0'; j++) { - if (argv[i][j] == 'p') { - poly = 1; - } -#ifndef CDT_ONLY - if (argv[i][j] == 'r') { - refine = 1; - } - if (argv[i][j] == 'q') { - quality = 1; - if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - k = 0; - while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - j++; - workstring[k] = argv[i][j]; - k++; - } - workstring[k] = '\0'; - minangle = (REAL) strtod(workstring, (char **) NULL); - } else { - minangle = 20.0; - } - } - if (argv[i][j] == 'a') { - quality = 1; - if (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - fixedarea = 1; - k = 0; - while (((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) || - (argv[i][j + 1] == '.')) { - j++; - workstring[k] = argv[i][j]; - k++; - } - workstring[k] = '\0'; - maxarea = (REAL) strtod(workstring, (char **) NULL); - if (maxarea <= 0.0) { - printf("Error: Maximum area must be greater than zero.\n"); - exit(1); - } - } else { - vararea = 1; - } - } -#endif /* not CDT_ONLY */ - if (argv[i][j] == 'A') { - regionattrib = 1; - } - if (argv[i][j] == 'c') { - convex = 1; - } - if (argv[i][j] == 'z') { - firstnumber = 0; - } - if (argv[i][j] == 'e') { - edgesout = 1; - } - if (argv[i][j] == 'v') { - voronoi = 1; - } - if (argv[i][j] == 'n') { - neighbors = 1; - } - if (argv[i][j] == 'g') { - geomview = 1; - } - if (argv[i][j] == 'B') { - nobound = 1; - } - if (argv[i][j] == 'P') { - nopolywritten = 1; - } - if (argv[i][j] == 'N') { - nonodewritten = 1; - } - if (argv[i][j] == 'E') { - noelewritten = 1; - } -#ifndef TRILIBRARY - if (argv[i][j] == 'I') { - noiterationnum = 1; - } -#endif /* not TRILIBRARY */ - if (argv[i][j] == 'O') { - noholes = 1; - } - if (argv[i][j] == 'X') { - noexact = 1; - } - if (argv[i][j] == 'o') { - if (argv[i][j + 1] == '2') { - j++; - order = 2; - } - } -#ifndef CDT_ONLY - if (argv[i][j] == 'Y') { - nobisect++; - } - if (argv[i][j] == 'S') { - steiner = 0; - while ((argv[i][j + 1] >= '0') && (argv[i][j + 1] <= '9')) { - j++; - steiner = steiner * 10 + (int) (argv[i][j] - '0'); - } - } -#endif /* not CDT_ONLY */ -#ifndef REDUCED - if (argv[i][j] == 'i') { - incremental = 1; - } - if (argv[i][j] == 'F') { - sweepline = 1; - } -#endif /* not REDUCED */ - if (argv[i][j] == 'l') { - dwyer = 0; - } -#ifndef REDUCED -#ifndef CDT_ONLY - if (argv[i][j] == 's') { - splitseg = 1; - } -#endif /* not CDT_ONLY */ - if (argv[i][j] == 'C') { - docheck = 1; - } -#endif /* not REDUCED */ - if (argv[i][j] == 'Q') { - quiet = 1; - } - if (argv[i][j] == 'V') { - verbose++; - } -#ifndef TRILIBRARY - if ((argv[i][j] == 'h') || (argv[i][j] == 'H') || - (argv[i][j] == '?')) { - info(); - } -#endif /* not TRILIBRARY */ - } -#ifndef TRILIBRARY - } else { - strncpy(innodefilename, argv[i], FILENAMESIZE - 1); - innodefilename[FILENAMESIZE - 1] = '\0'; - } -#endif /* not TRILIBRARY */ - } -#ifndef TRILIBRARY - if (innodefilename[0] == '\0') { - syntax(); - } - if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".node")) { - innodefilename[strlen(innodefilename) - 5] = '\0'; - } - if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".poly")) { - innodefilename[strlen(innodefilename) - 5] = '\0'; - poly = 1; - } -#ifndef CDT_ONLY - if (!strcmp(&innodefilename[strlen(innodefilename) - 4], ".ele")) { - innodefilename[strlen(innodefilename) - 4] = '\0'; - refine = 1; - } - if (!strcmp(&innodefilename[strlen(innodefilename) - 5], ".area")) { - innodefilename[strlen(innodefilename) - 5] = '\0'; - refine = 1; - quality = 1; - vararea = 1; - } -#endif /* not CDT_ONLY */ -#endif /* not TRILIBRARY */ - steinerleft = steiner; - useshelles = poly || refine || quality || convex; - goodangle = (REAL)cos(minangle * PI / 180.0); - goodangle *= goodangle; - if (refine && noiterationnum) { - printf( - "Error: You cannot use the -I switch when refining a triangulation.\n"); - exit(1); - } - /* Be careful not to allocate space for element area constraints that */ - /* will never be assigned any value (other than the default -1.0). */ - if (!refine && !poly) { - vararea = 0; - } - /* Be careful not to add an extra attribute to each element unless the */ - /* input supports it (PSLG in, but not refining a preexisting mesh). */ - if (refine || !poly) { - regionattrib = 0; - } - -#ifndef TRILIBRARY - strcpy(inpolyfilename, innodefilename); - strcpy(inelefilename, innodefilename); - strcpy(areafilename, innodefilename); - increment = 0; - strcpy(workstring, innodefilename); - j = 1; - while (workstring[j] != '\0') { - if ((workstring[j] == '.') && (workstring[j + 1] != '\0')) { - increment = j + 1; - } - j++; - } - meshnumber = 0; - if (increment > 0) { - j = increment; - do { - if ((workstring[j] >= '0') && (workstring[j] <= '9')) { - meshnumber = meshnumber * 10 + (int) (workstring[j] - '0'); - } else { - increment = 0; - } - j++; - } while (workstring[j] != '\0'); - } - if (noiterationnum) { - strcpy(outnodefilename, innodefilename); - strcpy(outelefilename, innodefilename); - strcpy(edgefilename, innodefilename); - strcpy(vnodefilename, innodefilename); - strcpy(vedgefilename, innodefilename); - strcpy(neighborfilename, innodefilename); - strcpy(offfilename, innodefilename); - strcat(outnodefilename, ".node"); - strcat(outelefilename, ".ele"); - strcat(edgefilename, ".edge"); - strcat(vnodefilename, ".v.node"); - strcat(vedgefilename, ".v.edge"); - strcat(neighborfilename, ".neigh"); - strcat(offfilename, ".off"); - } else if (increment == 0) { - strcpy(outnodefilename, innodefilename); - strcpy(outpolyfilename, innodefilename); - strcpy(outelefilename, innodefilename); - strcpy(edgefilename, innodefilename); - strcpy(vnodefilename, innodefilename); - strcpy(vedgefilename, innodefilename); - strcpy(neighborfilename, innodefilename); - strcpy(offfilename, innodefilename); - strcat(outnodefilename, ".1.node"); - strcat(outpolyfilename, ".1.poly"); - strcat(outelefilename, ".1.ele"); - strcat(edgefilename, ".1.edge"); - strcat(vnodefilename, ".1.v.node"); - strcat(vedgefilename, ".1.v.edge"); - strcat(neighborfilename, ".1.neigh"); - strcat(offfilename, ".1.off"); - } else { - workstring[increment] = '%'; - workstring[increment + 1] = 'd'; - workstring[increment + 2] = '\0'; - sprintf(outnodefilename, workstring, meshnumber + 1); - strcpy(outpolyfilename, outnodefilename); - strcpy(outelefilename, outnodefilename); - strcpy(edgefilename, outnodefilename); - strcpy(vnodefilename, outnodefilename); - strcpy(vedgefilename, outnodefilename); - strcpy(neighborfilename, outnodefilename); - strcpy(offfilename, outnodefilename); - strcat(outnodefilename, ".node"); - strcat(outpolyfilename, ".poly"); - strcat(outelefilename, ".ele"); - strcat(edgefilename, ".edge"); - strcat(vnodefilename, ".v.node"); - strcat(vedgefilename, ".v.edge"); - strcat(neighborfilename, ".neigh"); - strcat(offfilename, ".off"); - } - strcat(innodefilename, ".node"); - strcat(inpolyfilename, ".poly"); - strcat(inelefilename, ".ele"); - strcat(areafilename, ".area"); -#endif /* not TRILIBRARY */ -} - -/** **/ -/** **/ -/********* User interaction routines begin here *********/ - -/********* Debugging routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* printtriangle() Print out the details of a triangle/edge handle. */ -/* */ -/* I originally wrote this procedure to simplify debugging; it can be */ -/* called directly from the debugger, and presents information about a */ -/* triangle/edge handle in digestible form. It's also used when the */ -/* highest level of verbosity (`-VVV') is specified. */ -/* */ -/*****************************************************************************/ - -void printtriangle(t) -struct triedge *t; -{ - struct triedge printtri; - struct edge printsh; - point printpoint; - - printf("triangle x%lx with orientation %d:\n", (unsigned long) t->tri, - t->orient); - decode(t->tri[0], printtri); - if (printtri.tri == dummytri) { - printf(" [0] = Outer space\n"); - } else { - printf(" [0] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - decode(t->tri[1], printtri); - if (printtri.tri == dummytri) { - printf(" [1] = Outer space\n"); - } else { - printf(" [1] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - decode(t->tri[2], printtri); - if (printtri.tri == dummytri) { - printf(" [2] = Outer space\n"); - } else { - printf(" [2] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - org(*t, printpoint); - if (printpoint == (point) NULL) - printf(" Origin[%d] = NULL\n", (t->orient + 1) % 3 + 3); - else - printf(" Origin[%d] = x%lx (%.12g, %.12g)\n", - (t->orient + 1) % 3 + 3, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - dest(*t, printpoint); - if (printpoint == (point) NULL) - printf(" Dest [%d] = NULL\n", (t->orient + 2) % 3 + 3); - else - printf(" Dest [%d] = x%lx (%.12g, %.12g)\n", - (t->orient + 2) % 3 + 3, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - apex(*t, printpoint); - if (printpoint == (point) NULL) - printf(" Apex [%d] = NULL\n", t->orient + 3); - else - printf(" Apex [%d] = x%lx (%.12g, %.12g)\n", - t->orient + 3, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - if (useshelles) { - sdecode(t->tri[6], printsh); - if (printsh.sh != dummysh) { - printf(" [6] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sdecode(t->tri[7], printsh); - if (printsh.sh != dummysh) { - printf(" [7] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sdecode(t->tri[8], printsh); - if (printsh.sh != dummysh) { - printf(" [8] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - } - if (vararea) { - printf(" Area constraint: %.4g\n", areabound(*t)); - } -} - -/*****************************************************************************/ -/* */ -/* printshelle() Print out the details of a shell edge handle. */ -/* */ -/* I originally wrote this procedure to simplify debugging; it can be */ -/* called directly from the debugger, and presents information about a */ -/* shell edge handle in digestible form. It's also used when the highest */ -/* level of verbosity (`-VVV') is specified. */ -/* */ -/*****************************************************************************/ - -void printshelle(s) -struct edge *s; -{ - struct edge printsh; - struct triedge printtri; - point printpoint; - - printf("shell edge x%lx with orientation %d and mark %d:\n", - (unsigned long) s->sh, s->shorient, mark(*s)); - sdecode(s->sh[0], printsh); - if (printsh.sh == dummysh) { - printf(" [0] = No shell\n"); - } else { - printf(" [0] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sdecode(s->sh[1], printsh); - if (printsh.sh == dummysh) { - printf(" [1] = No shell\n"); - } else { - printf(" [1] = x%lx %d\n", (unsigned long) printsh.sh, - printsh.shorient); - } - sorg(*s, printpoint); - if (printpoint == (point) NULL) - printf(" Origin[%d] = NULL\n", 2 + s->shorient); - else - printf(" Origin[%d] = x%lx (%.12g, %.12g)\n", - 2 + s->shorient, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - sdest(*s, printpoint); - if (printpoint == (point) NULL) - printf(" Dest [%d] = NULL\n", 3 - s->shorient); - else - printf(" Dest [%d] = x%lx (%.12g, %.12g)\n", - 3 - s->shorient, (unsigned long) printpoint, - printpoint[0], printpoint[1]); - decode(s->sh[4], printtri); - if (printtri.tri == dummytri) { - printf(" [4] = Outer space\n"); - } else { - printf(" [4] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } - decode(s->sh[5], printtri); - if (printtri.tri == dummytri) { - printf(" [5] = Outer space\n"); - } else { - printf(" [5] = x%lx %d\n", (unsigned long) printtri.tri, - printtri.orient); - } -} - -/** **/ -/** **/ -/********* Debugging routines end here *********/ - -/********* Memory management routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* poolinit() Initialize a pool of memory for allocation of items. */ -/* */ -/* This routine initializes the machinery for allocating items. A `pool' */ -/* is created whose records have size at least `bytecount'. Items will be */ -/* allocated in `itemcount'-item blocks. Each item is assumed to be a */ -/* collection of words, and either pointers or floating-point values are */ -/* assumed to be the "primary" word type. (The "primary" word type is used */ -/* to determine alignment of items.) If `alignment' isn't zero, all items */ -/* will be `alignment'-byte aligned in memory. `alignment' must be either */ -/* a multiple or a factor of the primary word size; powers of two are safe. */ -/* `alignment' is normally used to create a few unused bits at the bottom */ -/* of each item's pointer, in which information may be stored. */ -/* */ -/* Don't change this routine unless you understand it. */ -/* */ -/*****************************************************************************/ - -void poolinit(pool, bytecount, itemcount, wtype, alignment) -struct memorypool *pool; -int bytecount; -int itemcount; -enum wordtype wtype; -int alignment; -{ - int wordsize; - - /* Initialize values in the pool. */ - pool->itemwordtype = wtype; - wordsize = (pool->itemwordtype == POINTER) ? sizeof(VOID *) : sizeof(REAL); - /* Find the proper alignment, which must be at least as large as: */ - /* - The parameter `alignment'. */ - /* - The primary word type, to avoid unaligned accesses. */ - /* - sizeof(VOID *), so the stack of dead items can be maintained */ - /* without unaligned accesses. */ - if (alignment > wordsize) { - pool->alignbytes = alignment; - } else { - pool->alignbytes = wordsize; - } - if (sizeof(VOID *) > pool->alignbytes) { - pool->alignbytes = sizeof(VOID *); - } - pool->itemwords = ((bytecount + pool->alignbytes - 1) / pool->alignbytes) - * (pool->alignbytes / wordsize); - pool->itembytes = pool->itemwords * wordsize; - pool->itemsperblock = itemcount; - - /* Allocate a block of items. Space for `itemsperblock' items and one */ - /* pointer (to point to the next block) are allocated, as well as space */ - /* to ensure alignment of the items. */ - pool->firstblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes - + sizeof(VOID *) + pool->alignbytes); - if (pool->firstblock == (VOID **) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Set the next block pointer to NULL. */ - *(pool->firstblock) = (VOID *) NULL; - poolrestart(pool); -} - -/*****************************************************************************/ -/* */ -/* poolrestart() Deallocate all items in a pool. */ -/* */ -/* The pool is returned to its starting state, except that no memory is */ -/* freed to the operating system. Rather, the previously allocated blocks */ -/* are ready to be reused. */ -/* */ -/*****************************************************************************/ - -void poolrestart(pool) -struct memorypool *pool; -{ - unsigned long alignptr; - - pool->items = 0; - pool->maxitems = 0; - - /* Set the currently active block. */ - pool->nowblock = pool->firstblock; - /* Find the first item in the pool. Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->nowblock + 1); - /* Align the item on an `alignbytes'-byte boundary. */ - pool->nextitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* There are lots of unallocated items left in this block. */ - pool->unallocateditems = pool->itemsperblock; - /* The stack of deallocated items is empty. */ - pool->deaditemstack = (VOID *) NULL; -} - -/*****************************************************************************/ -/* */ -/* pooldeinit() Free to the operating system all memory taken by a pool. */ -/* */ -/*****************************************************************************/ - -void pooldeinit(pool) -struct memorypool *pool; -{ - while (pool->firstblock != (VOID **) NULL) { - pool->nowblock = (VOID **) *(pool->firstblock); - free(pool->firstblock); - pool->firstblock = pool->nowblock; - } -} - -/*****************************************************************************/ -/* */ -/* poolalloc() Allocate space for an item. */ -/* */ -/*****************************************************************************/ - -VOID *poolalloc(pool) -struct memorypool *pool; -{ - VOID *newitem; - VOID **newblock; - unsigned long alignptr; - - /* First check the linked list of dead items. If the list is not */ - /* empty, allocate an item from the list rather than a fresh one. */ - if (pool->deaditemstack != (VOID *) NULL) { - newitem = pool->deaditemstack; /* Take first item in list. */ - pool->deaditemstack = * (VOID **) pool->deaditemstack; - } else { - /* Check if there are any free items left in the current block. */ - if (pool->unallocateditems == 0) { - /* Check if another block must be allocated. */ - if (*(pool->nowblock) == (VOID *) NULL) { - /* Allocate a new block of items, pointed to by the previous block. */ - newblock = (VOID **) malloc(pool->itemsperblock * pool->itembytes - + sizeof(VOID *) + pool->alignbytes); - if (newblock == (VOID **) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - *(pool->nowblock) = (VOID *) newblock; - /* The next block pointer is NULL. */ - *newblock = (VOID *) NULL; - } - /* Move to the new block. */ - pool->nowblock = (VOID **) *(pool->nowblock); - /* Find the first item in the block. */ - /* Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->nowblock + 1); - /* Align the item on an `alignbytes'-byte boundary. */ - pool->nextitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* There are lots of unallocated items left in this block. */ - pool->unallocateditems = pool->itemsperblock; - } - /* Allocate a new item. */ - newitem = pool->nextitem; - /* Advance `nextitem' pointer to next free item in block. */ - if (pool->itemwordtype == POINTER) { - pool->nextitem = (VOID *) ((VOID **) pool->nextitem + pool->itemwords); - } else { - pool->nextitem = (VOID *) ((REAL *) pool->nextitem + pool->itemwords); - } - pool->unallocateditems--; - pool->maxitems++; - } - pool->items++; - return newitem; -} - -/*****************************************************************************/ -/* */ -/* pooldealloc() Deallocate space for an item. */ -/* */ -/* The deallocated space is stored in a queue for later reuse. */ -/* */ -/*****************************************************************************/ - -void pooldealloc(pool, dyingitem) -struct memorypool *pool; -VOID *dyingitem; -{ - /* Push freshly killed item onto stack. */ - *((VOID **) dyingitem) = pool->deaditemstack; - pool->deaditemstack = dyingitem; - pool->items--; -} - -/*****************************************************************************/ -/* */ -/* traversalinit() Prepare to traverse the entire list of items. */ -/* */ -/* This routine is used in conjunction with traverse(). */ -/* */ -/*****************************************************************************/ - -void traversalinit(pool) -struct memorypool *pool; -{ - unsigned long alignptr; - - /* Begin the traversal in the first block. */ - pool->pathblock = pool->firstblock; - /* Find the first item in the block. Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->pathblock + 1); - /* Align with item on an `alignbytes'-byte boundary. */ - pool->pathitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* Set the number of items left in the current block. */ - pool->pathitemsleft = pool->itemsperblock; -} - -/*****************************************************************************/ -/* */ -/* traverse() Find the next item in the list. */ -/* */ -/* This routine is used in conjunction with traversalinit(). Be forewarned */ -/* that this routine successively returns all items in the list, including */ -/* deallocated ones on the deaditemqueue. It's up to you to figure out */ -/* which ones are actually dead. Why? I don't want to allocate extra */ -/* space just to demarcate dead items. It can usually be done more */ -/* space-efficiently by a routine that knows something about the structure */ -/* of the item. */ -/* */ -/*****************************************************************************/ - -VOID *traverse(pool) -struct memorypool *pool; -{ - VOID *newitem; - unsigned long alignptr; - - /* Stop upon exhausting the list of items. */ - if (pool->pathitem == pool->nextitem) { - return (VOID *) NULL; - } - /* Check whether any untraversed items remain in the current block. */ - if (pool->pathitemsleft == 0) { - /* Find the next block. */ - pool->pathblock = (VOID **) *(pool->pathblock); - /* Find the first item in the block. Increment by the size of (VOID *). */ - alignptr = (unsigned long) (pool->pathblock + 1); - /* Align with item on an `alignbytes'-byte boundary. */ - pool->pathitem = (VOID *) - (alignptr + (unsigned long) pool->alignbytes - - (alignptr % (unsigned long) pool->alignbytes)); - /* Set the number of items left in the current block. */ - pool->pathitemsleft = pool->itemsperblock; - } - newitem = pool->pathitem; - /* Find the next item in the block. */ - if (pool->itemwordtype == POINTER) { - pool->pathitem = (VOID *) ((VOID **) pool->pathitem + pool->itemwords); - } else { - pool->pathitem = (VOID *) ((REAL *) pool->pathitem + pool->itemwords); - } - pool->pathitemsleft--; - return newitem; -} - -/*****************************************************************************/ -/* */ -/* dummyinit() Initialize the triangle that fills "outer space" and the */ -/* omnipresent shell edge. */ -/* */ -/* The triangle that fills "outer space", called `dummytri', is pointed to */ -/* by every triangle and shell edge on a boundary (be it outer or inner) of */ -/* the triangulation. Also, `dummytri' points to one of the triangles on */ -/* the convex hull (until the holes and concavities are carved), making it */ -/* possible to find a starting triangle for point location. */ -/* */ -/* The omnipresent shell edge, `dummysh', is pointed to by every triangle */ -/* or shell edge that doesn't have a full complement of real shell edges */ -/* to point to. */ -/* */ -/*****************************************************************************/ - -void dummyinit(trianglewords, shellewords) -int trianglewords; -int shellewords; -{ - unsigned long alignptr; - - /* `triwords' and `shwords' are used by the mesh manipulation primitives */ - /* to extract orientations of triangles and shell edges from pointers. */ - triwords = trianglewords; /* Initialize `triwords' once and for all. */ - shwords = shellewords; /* Initialize `shwords' once and for all. */ - - /* Set up `dummytri', the `triangle' that occupies "outer space". */ - dummytribase = (triangle *) malloc(triwords * sizeof(triangle) - + triangles.alignbytes); - if (dummytribase == (triangle *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Align `dummytri' on a `triangles.alignbytes'-byte boundary. */ - alignptr = (unsigned long) dummytribase; - dummytri = (triangle *) - (alignptr + (unsigned long) triangles.alignbytes - - (alignptr % (unsigned long) triangles.alignbytes)); - /* Initialize the three adjoining triangles to be "outer space". These */ - /* will eventually be changed by various bonding operations, but their */ - /* values don't really matter, as long as they can legally be */ - /* dereferenced. */ - dummytri[0] = (triangle) dummytri; - dummytri[1] = (triangle) dummytri; - dummytri[2] = (triangle) dummytri; - /* Three NULL vertex points. */ - dummytri[3] = (triangle) NULL; - dummytri[4] = (triangle) NULL; - dummytri[5] = (triangle) NULL; - - if (useshelles) { - /* Set up `dummysh', the omnipresent "shell edge" pointed to by any */ - /* triangle side or shell edge end that isn't attached to a real shell */ - /* edge. */ - dummyshbase = (shelle *) malloc(shwords * sizeof(shelle) - + shelles.alignbytes); - if (dummyshbase == (shelle *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Align `dummysh' on a `shelles.alignbytes'-byte boundary. */ - alignptr = (unsigned long) dummyshbase; - dummysh = (shelle *) - (alignptr + (unsigned long) shelles.alignbytes - - (alignptr % (unsigned long) shelles.alignbytes)); - /* Initialize the two adjoining shell edges to be the omnipresent shell */ - /* edge. These will eventually be changed by various bonding */ - /* operations, but their values don't really matter, as long as they */ - /* can legally be dereferenced. */ - dummysh[0] = (shelle) dummysh; - dummysh[1] = (shelle) dummysh; - /* Two NULL vertex points. */ - dummysh[2] = (shelle) NULL; - dummysh[3] = (shelle) NULL; - /* Initialize the two adjoining triangles to be "outer space". */ - dummysh[4] = (shelle) dummytri; - dummysh[5] = (shelle) dummytri; - /* Set the boundary marker to zero. */ - * (int *) (dummysh + 6) = 0; - - /* Initialize the three adjoining shell edges of `dummytri' to be */ - /* the omnipresent shell edge. */ - dummytri[6] = (triangle) dummysh; - dummytri[7] = (triangle) dummysh; - dummytri[8] = (triangle) dummysh; - } -} - -/*****************************************************************************/ -/* */ -/* initializepointpool() Calculate the size of the point data structure */ -/* and initialize its memory pool. */ -/* */ -/* This routine also computes the `pointmarkindex' and `point2triindex' */ -/* indices used to find values within each point. */ -/* */ -/*****************************************************************************/ - -void initializepointpool() -{ - int pointsize; - - /* The index within each point at which the boundary marker is found. */ - /* Ensure the point marker is aligned to a sizeof(int)-byte address. */ - pointmarkindex = ((mesh_dim + nextras) * sizeof(REAL) + sizeof(int) - 1) - / sizeof(int); - pointsize = (pointmarkindex + 1) * sizeof(int); - if (poly) { - /* The index within each point at which a triangle pointer is found. */ - /* Ensure the pointer is aligned to a sizeof(triangle)-byte address. */ - point2triindex = (pointsize + sizeof(triangle) - 1) / sizeof(triangle); - pointsize = (point2triindex + 1) * sizeof(triangle); - } - /* Initialize the pool of points. */ - poolinit(&points, pointsize, POINTPERBLOCK, - (sizeof(REAL) >= sizeof(triangle)) ? FLOATINGPOINT : POINTER, 0); -} - -/*****************************************************************************/ -/* */ -/* initializetrisegpools() Calculate the sizes of the triangle and shell */ -/* edge data structures and initialize their */ -/* memory pools. */ -/* */ -/* This routine also computes the `highorderindex', `elemattribindex', and */ -/* `areaboundindex' indices used to find values within each triangle. */ -/* */ -/*****************************************************************************/ - -void initializetrisegpools() -{ - int trisize; - - /* The index within each triangle at which the extra nodes (above three) */ - /* associated with high order elements are found. There are three */ - /* pointers to other triangles, three pointers to corners, and possibly */ - /* three pointers to shell edges before the extra nodes. */ - highorderindex = 6 + (useshelles * 3); - /* The number of bytes occupied by a triangle. */ - trisize = ((order + 1) * (order + 2) / 2 + (highorderindex - 3)) * - sizeof(triangle); - /* The index within each triangle at which its attributes are found, */ - /* where the index is measured in REALs. */ - elemattribindex = (trisize + sizeof(REAL) - 1) / sizeof(REAL); - /* The index within each triangle at which the maximum area constraint */ - /* is found, where the index is measured in REALs. Note that if the */ - /* `regionattrib' flag is set, an additional attribute will be added. */ - areaboundindex = elemattribindex + eextras + regionattrib; - /* If triangle attributes or an area bound are needed, increase the number */ - /* of bytes occupied by a triangle. */ - if (vararea) { - trisize = (areaboundindex + 1) * sizeof(REAL); - } else if (eextras + regionattrib > 0) { - trisize = areaboundindex * sizeof(REAL); - } - /* If a Voronoi diagram or triangle neighbor graph is requested, make */ - /* sure there's room to store an integer index in each triangle. This */ - /* integer index can occupy the same space as the shell edges or */ - /* attributes or area constraint or extra nodes. */ - if ((voronoi || neighbors) && - (trisize < 6 * sizeof(triangle) + sizeof(int))) { - trisize = 6 * sizeof(triangle) + sizeof(int); - } - /* Having determined the memory size of a triangle, initialize the pool. */ - poolinit(&triangles, trisize, TRIPERBLOCK, POINTER, 4); - - if (useshelles) { - /* Initialize the pool of shell edges. */ - poolinit(&shelles, 6 * sizeof(triangle) + sizeof(int), SHELLEPERBLOCK, - POINTER, 4); - - /* Initialize the "outer space" triangle and omnipresent shell edge. */ - dummyinit(triangles.itemwords, shelles.itemwords); - } else { - /* Initialize the "outer space" triangle. */ - dummyinit(triangles.itemwords, 0); - } -} - -/*****************************************************************************/ -/* */ -/* triangledealloc() Deallocate space for a triangle, marking it dead. */ -/* */ -/*****************************************************************************/ - -void triangledealloc(dyingtriangle) -triangle *dyingtriangle; -{ - /* Set triangle's vertices to NULL. This makes it possible to */ - /* detect dead triangles when traversing the list of all triangles. */ - dyingtriangle[3] = (triangle) NULL; - dyingtriangle[4] = (triangle) NULL; - dyingtriangle[5] = (triangle) NULL; - pooldealloc(&triangles, (VOID *) dyingtriangle); -} - -/*****************************************************************************/ -/* */ -/* triangletraverse() Traverse the triangles, skipping dead ones. */ -/* */ -/*****************************************************************************/ - -triangle *triangletraverse() -{ - triangle *newtriangle; - - do { - newtriangle = (triangle *) traverse(&triangles); - if (newtriangle == (triangle *) NULL) { - return (triangle *) NULL; - } - } while (newtriangle[3] == (triangle) NULL); /* Skip dead ones. */ - return newtriangle; -} - -/*****************************************************************************/ -/* */ -/* shelledealloc() Deallocate space for a shell edge, marking it dead. */ -/* */ -/*****************************************************************************/ - -void shelledealloc(dyingshelle) -shelle *dyingshelle; -{ - /* Set shell edge's vertices to NULL. This makes it possible to */ - /* detect dead shells when traversing the list of all shells. */ - dyingshelle[2] = (shelle) NULL; - dyingshelle[3] = (shelle) NULL; - pooldealloc(&shelles, (VOID *) dyingshelle); -} - -/*****************************************************************************/ -/* */ -/* shelletraverse() Traverse the shell edges, skipping dead ones. */ -/* */ -/*****************************************************************************/ - -shelle *shelletraverse() -{ - shelle *newshelle; - - do { - newshelle = (shelle *) traverse(&shelles); - if (newshelle == (shelle *) NULL) { - return (shelle *) NULL; - } - } while (newshelle[2] == (shelle) NULL); /* Skip dead ones. */ - return newshelle; -} - -/*****************************************************************************/ -/* */ -/* pointdealloc() Deallocate space for a point, marking it dead. */ -/* */ -/*****************************************************************************/ - -void pointdealloc(dyingpoint) -point dyingpoint; -{ - /* Mark the point as dead. This makes it possible to detect dead points */ - /* when traversing the list of all points. */ - setpointmark(dyingpoint, DEADPOINT); - pooldealloc(&points, (VOID *) dyingpoint); -} - -/*****************************************************************************/ -/* */ -/* pointtraverse() Traverse the points, skipping dead ones. */ -/* */ -/*****************************************************************************/ - -point pointtraverse() -{ - point newpoint; - - do { - newpoint = (point) traverse(&points); - if (newpoint == (point) NULL) { - return (point) NULL; - } - } while (pointmark(newpoint) == DEADPOINT); /* Skip dead ones. */ - return newpoint; -} - -/*****************************************************************************/ -/* */ -/* badsegmentdealloc() Deallocate space for a bad segment, marking it */ -/* dead. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void badsegmentdealloc(dyingseg) -struct edge *dyingseg; -{ - /* Set segment's orientation to -1. This makes it possible to */ - /* detect dead segments when traversing the list of all segments. */ - dyingseg->shorient = -1; - pooldealloc(&badsegments, (VOID *) dyingseg); -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* badsegmenttraverse() Traverse the bad segments, skipping dead ones. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -struct edge *badsegmenttraverse() -{ - struct edge *newseg; - - do { - newseg = (struct edge *) traverse(&badsegments); - if (newseg == (struct edge *) NULL) { - return (struct edge *) NULL; - } - } while (newseg->shorient == -1); /* Skip dead ones. */ - return newseg; -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* getpoint() Get a specific point, by number, from the list. */ -/* */ -/* The first point is number 'firstnumber'. */ -/* */ -/* Note that this takes O(n) time (with a small constant, if POINTPERBLOCK */ -/* is large). I don't care to take the trouble to make it work in constant */ -/* time. */ -/* */ -/*****************************************************************************/ - -point getpoint(number) -int number; -{ - VOID **getblock; - point foundpoint; - unsigned long alignptr; - int current; - - getblock = points.firstblock; - current = firstnumber; - /* Find the right block. */ - while (current + points.itemsperblock <= number) { - getblock = (VOID **) *getblock; - current += points.itemsperblock; - } - /* Now find the right point. */ - alignptr = (unsigned long) (getblock + 1); - foundpoint = (point) (alignptr + (unsigned long) points.alignbytes - - (alignptr % (unsigned long) points.alignbytes)); - while (current < number) { - foundpoint += points.itemwords; - current++; - } - return foundpoint; -} - -/*****************************************************************************/ -/* */ -/* triangledeinit() Free all remaining allocated memory. */ -/* */ -/*****************************************************************************/ - -void triangledeinit() -{ - pooldeinit(&triangles); - free(dummytribase); - if (useshelles) { - pooldeinit(&shelles); - free(dummyshbase); - } - pooldeinit(&points); -#ifndef CDT_ONLY - if (quality) { - pooldeinit(&badsegments); - if ((minangle > 0.0) || vararea || fixedarea) { - pooldeinit(&badtriangles); - } - } -#endif /* not CDT_ONLY */ -} - -/** **/ -/** **/ -/********* Memory management routines end here *********/ - -/********* Constructors begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* maketriangle() Create a new triangle with orientation zero. */ -/* */ -/*****************************************************************************/ - -void maketriangle(newtriedge) -struct triedge *newtriedge; -{ - int i; - - newtriedge->tri = (triangle *) poolalloc(&triangles); - /* Initialize the three adjoining triangles to be "outer space". */ - newtriedge->tri[0] = (triangle) dummytri; - newtriedge->tri[1] = (triangle) dummytri; - newtriedge->tri[2] = (triangle) dummytri; - /* Three NULL vertex points. */ - newtriedge->tri[3] = (triangle) NULL; - newtriedge->tri[4] = (triangle) NULL; - newtriedge->tri[5] = (triangle) NULL; - /* Initialize the three adjoining shell edges to be the omnipresent */ - /* shell edge. */ - if (useshelles) { - newtriedge->tri[6] = (triangle) dummysh; - newtriedge->tri[7] = (triangle) dummysh; - newtriedge->tri[8] = (triangle) dummysh; - } - for (i = 0; i < eextras; i++) { - setelemattribute(*newtriedge, i, 0.0); - } - if (vararea) { - setareabound(*newtriedge, -1.0); - } - - newtriedge->orient = 0; -} - -/*****************************************************************************/ -/* */ -/* makeshelle() Create a new shell edge with orientation zero. */ -/* */ -/*****************************************************************************/ - -void makeshelle(newedge) -struct edge *newedge; -{ - newedge->sh = (shelle *) poolalloc(&shelles); - /* Initialize the two adjoining shell edges to be the omnipresent */ - /* shell edge. */ - newedge->sh[0] = (shelle) dummysh; - newedge->sh[1] = (shelle) dummysh; - /* Two NULL vertex points. */ - newedge->sh[2] = (shelle) NULL; - newedge->sh[3] = (shelle) NULL; - /* Initialize the two adjoining triangles to be "outer space". */ - newedge->sh[4] = (shelle) dummytri; - newedge->sh[5] = (shelle) dummytri; - /* Set the boundary marker to zero. */ - setmark(*newedge, 0); - - newedge->shorient = 0; -} - -/** **/ -/** **/ -/********* Constructors end here *********/ - -/********* Determinant evaluation routines begin here *********/ -/** **/ -/** **/ - -/* The adaptive exact arithmetic geometric predicates implemented herein are */ -/* described in detail in my Technical Report CMU-CS-96-140. The complete */ -/* reference is given in the header. */ - -/* Which of the following two methods of finding the absolute values is */ -/* fastest is compiler-dependent. A few compilers can inline and optimize */ -/* the fabs() call; but most will incur the overhead of a function call, */ -/* which is disastrously slow. A faster way on IEEE machines might be to */ -/* mask the appropriate bit, but that's difficult to do in C. */ - -#define Absolute(a) ((a) >= 0.0 ? (a) : -(a)) -/* #define Absolute(a) fabs(a) */ - -/* Many of the operations are broken up into two pieces, a main part that */ -/* performs an approximate operation, and a "tail" that computes the */ -/* roundoff error of that operation. */ -/* */ -/* The operations Fast_Two_Sum(), Fast_Two_Diff(), Two_Sum(), Two_Diff(), */ -/* Split(), and Two_Product() are all implemented as described in the */ -/* reference. Each of these macros requires certain variables to be */ -/* defined in the calling routine. The variables `bvirt', `c', `abig', */ -/* `_i', `_j', `_k', `_l', `_m', and `_n' are declared `INEXACT' because */ -/* they store the result of an operation that may incur roundoff error. */ -/* The input parameter `x' (or the highest numbered `x_' parameter) must */ -/* also be declared `INEXACT'. */ - -#define Fast_Two_Sum_Tail(a, b, x, y) \ - bvirt = x - a; \ - y = b - bvirt - -#define Fast_Two_Sum(a, b, x, y) \ - x = (REAL) (a + b); \ - Fast_Two_Sum_Tail(a, b, x, y) - -#define Two_Sum_Tail(a, b, x, y) \ - bvirt = (REAL) (x - a); \ - avirt = x - bvirt; \ - bround = b - bvirt; \ - around = a - avirt; \ - y = around + bround - -#define Two_Sum(a, b, x, y) \ - x = (REAL) (a + b); \ - Two_Sum_Tail(a, b, x, y) - -#define Two_Diff_Tail(a, b, x, y) \ - bvirt = (REAL) (a - x); \ - avirt = x + bvirt; \ - bround = bvirt - b; \ - around = a - avirt; \ - y = around + bround - -#define Two_Diff(a, b, x, y) \ - x = (REAL) (a - b); \ - Two_Diff_Tail(a, b, x, y) - -#define Split(a, ahi, alo) \ - c = (REAL) (splitter * a); \ - abig = (REAL) (c - a); \ - ahi = (REAL)(c - abig); \ - alo = (REAL)(a - ahi) - -#define Two_Product_Tail(a, b, x, y) \ - Split(a, ahi, alo); \ - Split(b, bhi, blo); \ - err1 = x - (ahi * bhi); \ - err2 = err1 - (alo * bhi); \ - err3 = err2 - (ahi * blo); \ - y = (alo * blo) - err3 - -#define Two_Product(a, b, x, y) \ - x = (REAL) (a * b); \ - Two_Product_Tail(a, b, x, y) - -/* Two_Product_Presplit() is Two_Product() where one of the inputs has */ -/* already been split. Avoids redundant splitting. */ - -#define Two_Product_Presplit(a, b, bhi, blo, x, y) \ - x = (REAL) (a * b); \ - Split(a, ahi, alo); \ - err1 = x - (ahi * bhi); \ - err2 = err1 - (alo * bhi); \ - err3 = err2 - (ahi * blo); \ - y = (alo * blo) - err3 - -/* Square() can be done more quickly than Two_Product(). */ - -#define Square_Tail(a, x, y) \ - Split(a, ahi, alo); \ - err1 = x - (ahi * ahi); \ - err3 = err1 - ((ahi + ahi) * alo); \ - y = (alo * alo) - err3 - -#define Square(a, x, y) \ - x = (REAL) (a * a); \ - Square_Tail(a, x, y) - -/* Macros for summing expansions of various fixed lengths. These are all */ -/* unrolled versions of Expansion_Sum(). */ - -#define Two_One_Sum(a1, a0, b, x2, x1, x0) \ - Two_Sum(a0, b , _i, x0); \ - Two_Sum(a1, _i, x2, x1) - -#define Two_One_Diff(a1, a0, b, x2, x1, x0) \ - Two_Diff(a0, b , _i, x0); \ - Two_Sum( a1, _i, x2, x1) - -#define Two_Two_Sum(a1, a0, b1, b0, x3, x2, x1, x0) \ - Two_One_Sum(a1, a0, b0, _j, _0, x0); \ - Two_One_Sum(_j, _0, b1, x3, x2, x1) - -#define Two_Two_Diff(a1, a0, b1, b0, x3, x2, x1, x0) \ - Two_One_Diff(a1, a0, b0, _j, _0, x0); \ - Two_One_Diff(_j, _0, b1, x3, x2, x1) - -/*****************************************************************************/ -/* */ -/* exactinit() Initialize the variables used for exact arithmetic. */ -/* */ -/* `epsilon' is the largest power of two such that 1.0 + epsilon = 1.0 in */ -/* floating-point arithmetic. `epsilon' bounds the relative roundoff */ -/* error. It is used for floating-point error analysis. */ -/* */ -/* `splitter' is used to split floating-point numbers into two half- */ -/* length significands for exact multiplication. */ -/* */ -/* I imagine that a highly optimizing compiler might be too smart for its */ -/* own good, and somehow cause this routine to fail, if it pretends that */ -/* floating-point arithmetic is too much like real arithmetic. */ -/* */ -/* Don't change this routine unless you fully understand it. */ -/* */ -/*****************************************************************************/ - -void exactinit() -{ - REAL half; - REAL check, lastcheck; - int every_other; - - every_other = 1; - half = 0.5; - epsilon = 1.0; - splitter = 1.0; - check = 1.0; - /* Repeatedly divide `epsilon' by two until it is too small to add to */ - /* one without causing roundoff. (Also check if the sum is equal to */ - /* the previous sum, for machines that round up instead of using exact */ - /* rounding. Not that these routines will work on such machines anyway. */ - do { - lastcheck = check; - epsilon *= half; - if (every_other) { - splitter *= 2.0; - } - every_other = !every_other; - check = (REAL)(1.0 + epsilon); - } while ((check != 1.0) && (check != lastcheck)); - splitter += 1.0; - if (verbose > 1) { - printf("Floating point roundoff is of magnitude %.17g\n", epsilon); - printf("Floating point splitter is %.17g\n", splitter); - } - /* Error bounds for orientation and incircle tests. */ - resulterrbound = (REAL)((3.0 + 8.0 * epsilon) * epsilon); - ccwerrboundA = (REAL)((3.0 + 16.0 * epsilon) * epsilon); - ccwerrboundB = (REAL)((2.0 + 12.0 * epsilon) * epsilon); - ccwerrboundC = (REAL)((9.0 + 64.0 * epsilon) * epsilon * epsilon); - iccerrboundA = (REAL)((10.0 + 96.0 * epsilon) * epsilon); - iccerrboundB = (REAL)((4.0 + 48.0 * epsilon) * epsilon); - iccerrboundC = (REAL)((44.0 + 576.0 * epsilon) * epsilon * epsilon); -} - -/*****************************************************************************/ -/* */ -/* fast_expansion_sum_zeroelim() Sum two expansions, eliminating zero */ -/* components from the output expansion. */ -/* */ -/* Sets h = e + f. See my Robust Predicates paper for details. */ -/* */ -/* If round-to-even is used (as with IEEE 754), maintains the strongly */ -/* nonoverlapping property. (That is, if e is strongly nonoverlapping, h */ -/* will be also.) Does NOT maintain the nonoverlapping or nonadjacent */ -/* properties. */ -/* */ -/*****************************************************************************/ - -int fast_expansion_sum_zeroelim(elen, e, flen, f, h) /* h cannot be e or f. */ -int elen; -REAL *e; -int flen; -REAL *f; -REAL *h; -{ - REAL Q; - INEXACT REAL Qnew; - INEXACT REAL hh; - INEXACT REAL bvirt; - REAL avirt, bround, around; - int eindex, findex, hindex; - REAL enow, fnow; - - enow = e[0]; - fnow = f[0]; - eindex = findex = 0; - if ((fnow > enow) == (fnow > -enow)) { - Q = enow; - enow = e[++eindex]; - } else { - Q = fnow; - fnow = f[++findex]; - } - hindex = 0; - if ((eindex < elen) && (findex < flen)) { - if ((fnow > enow) == (fnow > -enow)) { - Fast_Two_Sum(enow, Q, Qnew, hh); - enow = e[++eindex]; - } else { - Fast_Two_Sum(fnow, Q, Qnew, hh); - fnow = f[++findex]; - } - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - while ((eindex < elen) && (findex < flen)) { - if ((fnow > enow) == (fnow > -enow)) { - Two_Sum(Q, enow, Qnew, hh); - enow = e[++eindex]; - } else { - Two_Sum(Q, fnow, Qnew, hh); - fnow = f[++findex]; - } - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - } - } - while (eindex < elen) { - Two_Sum(Q, enow, Qnew, hh); - enow = e[++eindex]; - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - } - while (findex < flen) { - Two_Sum(Q, fnow, Qnew, hh); - fnow = f[++findex]; - Q = Qnew; - if (hh != 0.0) { - h[hindex++] = hh; - } - } - if ((Q != 0.0) || (hindex == 0)) { - h[hindex++] = Q; - } - return hindex; -} - -/*****************************************************************************/ -/* */ -/* scale_expansion_zeroelim() Multiply an expansion by a scalar, */ -/* eliminating zero components from the */ -/* output expansion. */ -/* */ -/* Sets h = be. See my Robust Predicates paper for details. */ -/* */ -/* Maintains the nonoverlapping property. If round-to-even is used (as */ -/* with IEEE 754), maintains the strongly nonoverlapping and nonadjacent */ -/* properties as well. (That is, if e has one of these properties, so */ -/* will h.) */ -/* */ -/*****************************************************************************/ - -int scale_expansion_zeroelim(elen, e, b, h) /* e and h cannot be the same. */ -int elen; -REAL *e; -REAL b; -REAL *h; -{ - INEXACT REAL Q, sum; - REAL hh; - INEXACT REAL product1; - REAL product0; - int eindex, hindex; - REAL enow; - INEXACT REAL bvirt; - REAL avirt, bround, around; - INEXACT REAL c; - INEXACT REAL abig; - REAL ahi, alo, bhi, blo; - REAL err1, err2, err3; - - Split(b, bhi, blo); - Two_Product_Presplit(e[0], b, bhi, blo, Q, hh); - hindex = 0; - if (hh != 0) { - h[hindex++] = hh; - } - for (eindex = 1; eindex < elen; eindex++) { - enow = e[eindex]; - Two_Product_Presplit(enow, b, bhi, blo, product1, product0); - Two_Sum(Q, product0, sum, hh); - if (hh != 0) { - h[hindex++] = hh; - } - Fast_Two_Sum(product1, sum, Q, hh); - if (hh != 0) { - h[hindex++] = hh; - } - } - if ((Q != 0.0) || (hindex == 0)) { - h[hindex++] = Q; - } - return hindex; -} - -/*****************************************************************************/ -/* */ -/* estimate() Produce a one-word estimate of an expansion's value. */ -/* */ -/* See my Robust Predicates paper for details. */ -/* */ -/*****************************************************************************/ - -REAL estimate(elen, e) -int elen; -REAL *e; -{ - REAL Q; - int eindex; - - Q = e[0]; - for (eindex = 1; eindex < elen; eindex++) { - Q += e[eindex]; - } - return Q; -} - -/*****************************************************************************/ -/* */ -/* counterclockwise() Return a positive value if the points pa, pb, and */ -/* pc occur in counterclockwise order; a negative */ -/* value if they occur in clockwise order; and zero */ -/* if they are collinear. The result is also a rough */ -/* approximation of twice the signed area of the */ -/* triangle defined by the three points. */ -/* */ -/* Uses exact arithmetic if necessary to ensure a correct answer. The */ -/* result returned is the determinant of a matrix. This determinant is */ -/* computed adaptively, in the sense that exact arithmetic is used only to */ -/* the degree it is needed to ensure that the returned value has the */ -/* correct sign. Hence, this function is usually quite fast, but will run */ -/* more slowly when the input points are collinear or nearly so. */ -/* */ -/* See my Robust Predicates paper for details. */ -/* */ -/*****************************************************************************/ - -REAL counterclockwiseadapt(pa, pb, pc, detsum) -point pa; -point pb; -point pc; -REAL detsum; -{ - INEXACT REAL acx, acy, bcx, bcy; - REAL acxtail, acytail, bcxtail, bcytail; - INEXACT REAL detleft, detright; - REAL detlefttail, detrighttail; - REAL det, errbound; - REAL B[4], C1[8], C2[12], D[16]; - INEXACT REAL B3; - int C1length, C2length, Dlength; - REAL u[4]; - INEXACT REAL u3; - INEXACT REAL s1, t1; - REAL s0, t0; - - INEXACT REAL bvirt; - REAL avirt, bround, around; - INEXACT REAL c; - INEXACT REAL abig; - REAL ahi, alo, bhi, blo; - REAL err1, err2, err3; - INEXACT REAL _i, _j; - REAL _0; - - acx = (REAL) (pa[0] - pc[0]); - bcx = (REAL) (pb[0] - pc[0]); - acy = (REAL) (pa[1] - pc[1]); - bcy = (REAL) (pb[1] - pc[1]); - - Two_Product(acx, bcy, detleft, detlefttail); - Two_Product(acy, bcx, detright, detrighttail); - - Two_Two_Diff(detleft, detlefttail, detright, detrighttail, - B3, B[2], B[1], B[0]); - B[3] = B3; - - det = estimate(4, B); - errbound = (REAL)(ccwerrboundB * detsum); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - Two_Diff_Tail(pa[0], pc[0], acx, acxtail); - Two_Diff_Tail(pb[0], pc[0], bcx, bcxtail); - Two_Diff_Tail(pa[1], pc[1], acy, acytail); - Two_Diff_Tail(pb[1], pc[1], bcy, bcytail); - - if ((acxtail == 0.0) && (acytail == 0.0) - && (bcxtail == 0.0) && (bcytail == 0.0)) { - return det; - } - - errbound = (REAL)(ccwerrboundC * detsum + resulterrbound * Absolute(det)); - det += (acx * bcytail + bcy * acxtail) - - (acy * bcxtail + bcx * acytail); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - Two_Product(acxtail, bcy, s1, s0); - Two_Product(acytail, bcx, t1, t0); - Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]); - u[3] = u3; - C1length = fast_expansion_sum_zeroelim(4, B, 4, u, C1); - - Two_Product(acx, bcytail, s1, s0); - Two_Product(acy, bcxtail, t1, t0); - Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]); - u[3] = u3; - C2length = fast_expansion_sum_zeroelim(C1length, C1, 4, u, C2); - - Two_Product(acxtail, bcytail, s1, s0); - Two_Product(acytail, bcxtail, t1, t0); - Two_Two_Diff(s1, s0, t1, t0, u3, u[2], u[1], u[0]); - u[3] = u3; - Dlength = fast_expansion_sum_zeroelim(C2length, C2, 4, u, D); - - return(D[Dlength - 1]); -} - -REAL counterclockwise(pa, pb, pc) -point pa; -point pb; -point pc; -{ - REAL detleft, detright, det; - REAL detsum, errbound; - - counterclockcount++; - - detleft = (pa[0] - pc[0]) * (pb[1] - pc[1]); - detright = (pa[1] - pc[1]) * (pb[0] - pc[0]); - det = detleft - detright; - - if (noexact) { - return det; - } - - if (detleft > 0.0) { - if (detright <= 0.0) { - return det; - } else { - detsum = detleft + detright; - } - } else if (detleft < 0.0) { - if (detright >= 0.0) { - return det; - } else { - detsum = -detleft - detright; - } - } else { - return det; - } - - errbound = ccwerrboundA * detsum; - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - return counterclockwiseadapt(pa, pb, pc, detsum); -} - -/*****************************************************************************/ -/* */ -/* incircle() Return a positive value if the point pd lies inside the */ -/* circle passing through pa, pb, and pc; a negative value if */ -/* it lies outside; and zero if the four points are cocircular.*/ -/* The points pa, pb, and pc must be in counterclockwise */ -/* order, or the sign of the result will be reversed. */ -/* */ -/* Uses exact arithmetic if necessary to ensure a correct answer. The */ -/* result returned is the determinant of a matrix. This determinant is */ -/* computed adaptively, in the sense that exact arithmetic is used only to */ -/* the degree it is needed to ensure that the returned value has the */ -/* correct sign. Hence, this function is usually quite fast, but will run */ -/* more slowly when the input points are cocircular or nearly so. */ -/* */ -/* See my Robust Predicates paper for details. */ -/* */ -/*****************************************************************************/ - -REAL incircleadapt(pa, pb, pc, pd, permanent) -point pa; -point pb; -point pc; -point pd; -REAL permanent; -{ - INEXACT REAL adx, bdx, cdx, ady, bdy, cdy; - REAL det, errbound; - - INEXACT REAL bdxcdy1, cdxbdy1, cdxady1, adxcdy1, adxbdy1, bdxady1; - REAL bdxcdy0, cdxbdy0, cdxady0, adxcdy0, adxbdy0, bdxady0; - REAL bc[4], ca[4], ab[4]; - INEXACT REAL bc3, ca3, ab3; - REAL axbc[8], axxbc[16], aybc[8], ayybc[16], adet[32]; - int axbclen, axxbclen, aybclen, ayybclen, alen; - REAL bxca[8], bxxca[16], byca[8], byyca[16], bdet[32]; - int bxcalen, bxxcalen, bycalen, byycalen, blen; - REAL cxab[8], cxxab[16], cyab[8], cyyab[16], cdet[32]; - int cxablen, cxxablen, cyablen, cyyablen, clen; - REAL abdet[64]; - int ablen; - REAL fin1[1152], fin2[1152]; - REAL *finnow, *finother, *finswap; - int finlength; - - REAL adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail; - INEXACT REAL adxadx1, adyady1, bdxbdx1, bdybdy1, cdxcdx1, cdycdy1; - REAL adxadx0, adyady0, bdxbdx0, bdybdy0, cdxcdx0, cdycdy0; - REAL aa[4], bb[4], cc[4]; - INEXACT REAL aa3, bb3, cc3; - INEXACT REAL ti1, tj1; - REAL ti0, tj0; - REAL u[4], v[4]; - INEXACT REAL u3, v3; - REAL temp8[8], temp16a[16], temp16b[16], temp16c[16]; - REAL temp32a[32], temp32b[32], temp48[48], temp64[64]; - int temp8len, temp16alen, temp16blen, temp16clen; - int temp32alen, temp32blen, temp48len, temp64len; - REAL axtbb[8], axtcc[8], aytbb[8], aytcc[8]; - int axtbblen, axtcclen, aytbblen, aytcclen; - REAL bxtaa[8], bxtcc[8], bytaa[8], bytcc[8]; - int bxtaalen, bxtcclen, bytaalen, bytcclen; - REAL cxtaa[8], cxtbb[8], cytaa[8], cytbb[8]; - int cxtaalen, cxtbblen, cytaalen, cytbblen; - REAL axtbc[8], aytbc[8], bxtca[8], bytca[8], cxtab[8], cytab[8]; - int axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen; - REAL axtbct[16], aytbct[16], bxtcat[16], bytcat[16], cxtabt[16], cytabt[16]; - int axtbctlen, aytbctlen, bxtcatlen, bytcatlen, cxtabtlen, cytabtlen; - REAL axtbctt[8], aytbctt[8], bxtcatt[8]; - REAL bytcatt[8], cxtabtt[8], cytabtt[8]; - int axtbcttlen, aytbcttlen, bxtcattlen, bytcattlen, cxtabttlen, cytabttlen; - REAL abt[8], bct[8], cat[8]; - int abtlen, bctlen, catlen; - REAL abtt[4], bctt[4], catt[4]; - int abttlen, bcttlen, cattlen; - INEXACT REAL abtt3, bctt3, catt3; - REAL negate; - - INEXACT REAL bvirt; - REAL avirt, bround, around; - INEXACT REAL c; - INEXACT REAL abig; - REAL ahi, alo, bhi, blo; - REAL err1, err2, err3; - INEXACT REAL _i, _j; - REAL _0; - - adx = (REAL) (pa[0] - pd[0]); - bdx = (REAL) (pb[0] - pd[0]); - cdx = (REAL) (pc[0] - pd[0]); - ady = (REAL) (pa[1] - pd[1]); - bdy = (REAL) (pb[1] - pd[1]); - cdy = (REAL) (pc[1] - pd[1]); - - Two_Product(bdx, cdy, bdxcdy1, bdxcdy0); - Two_Product(cdx, bdy, cdxbdy1, cdxbdy0); - Two_Two_Diff(bdxcdy1, bdxcdy0, cdxbdy1, cdxbdy0, bc3, bc[2], bc[1], bc[0]); - bc[3] = bc3; - axbclen = scale_expansion_zeroelim(4, bc, adx, axbc); - axxbclen = scale_expansion_zeroelim(axbclen, axbc, adx, axxbc); - aybclen = scale_expansion_zeroelim(4, bc, ady, aybc); - ayybclen = scale_expansion_zeroelim(aybclen, aybc, ady, ayybc); - alen = fast_expansion_sum_zeroelim(axxbclen, axxbc, ayybclen, ayybc, adet); - - Two_Product(cdx, ady, cdxady1, cdxady0); - Two_Product(adx, cdy, adxcdy1, adxcdy0); - Two_Two_Diff(cdxady1, cdxady0, adxcdy1, adxcdy0, ca3, ca[2], ca[1], ca[0]); - ca[3] = ca3; - bxcalen = scale_expansion_zeroelim(4, ca, bdx, bxca); - bxxcalen = scale_expansion_zeroelim(bxcalen, bxca, bdx, bxxca); - bycalen = scale_expansion_zeroelim(4, ca, bdy, byca); - byycalen = scale_expansion_zeroelim(bycalen, byca, bdy, byyca); - blen = fast_expansion_sum_zeroelim(bxxcalen, bxxca, byycalen, byyca, bdet); - - Two_Product(adx, bdy, adxbdy1, adxbdy0); - Two_Product(bdx, ady, bdxady1, bdxady0); - Two_Two_Diff(adxbdy1, adxbdy0, bdxady1, bdxady0, ab3, ab[2], ab[1], ab[0]); - ab[3] = ab3; - cxablen = scale_expansion_zeroelim(4, ab, cdx, cxab); - cxxablen = scale_expansion_zeroelim(cxablen, cxab, cdx, cxxab); - cyablen = scale_expansion_zeroelim(4, ab, cdy, cyab); - cyyablen = scale_expansion_zeroelim(cyablen, cyab, cdy, cyyab); - clen = fast_expansion_sum_zeroelim(cxxablen, cxxab, cyyablen, cyyab, cdet); - - ablen = fast_expansion_sum_zeroelim(alen, adet, blen, bdet, abdet); - finlength = fast_expansion_sum_zeroelim(ablen, abdet, clen, cdet, fin1); - - det = estimate(finlength, fin1); - errbound = (REAL)(iccerrboundB * permanent); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - Two_Diff_Tail(pa[0], pd[0], adx, adxtail); - Two_Diff_Tail(pa[1], pd[1], ady, adytail); - Two_Diff_Tail(pb[0], pd[0], bdx, bdxtail); - Two_Diff_Tail(pb[1], pd[1], bdy, bdytail); - Two_Diff_Tail(pc[0], pd[0], cdx, cdxtail); - Two_Diff_Tail(pc[1], pd[1], cdy, cdytail); - if ((adxtail == 0.0) && (bdxtail == 0.0) && (cdxtail == 0.0) - && (adytail == 0.0) && (bdytail == 0.0) && (cdytail == 0.0)) { - return det; - } - - errbound = (REAL)(iccerrboundC * permanent + resulterrbound * Absolute(det)); - det += (REAL)(((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - - (bdy * cdxtail + cdx * bdytail)) - + 2.0 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) - + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - - (cdy * adxtail + adx * cdytail)) - + 2.0 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) - + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - - (ady * bdxtail + bdx * adytail)) - + 2.0 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx))); - if ((det >= errbound) || (-det >= errbound)) { - return det; - } - - finnow = fin1; - finother = fin2; - - if ((bdxtail != 0.0) || (bdytail != 0.0) - || (cdxtail != 0.0) || (cdytail != 0.0)) { - Square(adx, adxadx1, adxadx0); - Square(ady, adyady1, adyady0); - Two_Two_Sum(adxadx1, adxadx0, adyady1, adyady0, aa3, aa[2], aa[1], aa[0]); - aa[3] = aa3; - } - if ((cdxtail != 0.0) || (cdytail != 0.0) - || (adxtail != 0.0) || (adytail != 0.0)) { - Square(bdx, bdxbdx1, bdxbdx0); - Square(bdy, bdybdy1, bdybdy0); - Two_Two_Sum(bdxbdx1, bdxbdx0, bdybdy1, bdybdy0, bb3, bb[2], bb[1], bb[0]); - bb[3] = bb3; - } - if ((adxtail != 0.0) || (adytail != 0.0) - || (bdxtail != 0.0) || (bdytail != 0.0)) { - Square(cdx, cdxcdx1, cdxcdx0); - Square(cdy, cdycdy1, cdycdy0); - Two_Two_Sum(cdxcdx1, cdxcdx0, cdycdy1, cdycdy0, cc3, cc[2], cc[1], cc[0]); - cc[3] = cc3; - } - - if (adxtail != 0.0) { - axtbclen = scale_expansion_zeroelim(4, bc, adxtail, axtbc); - temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, 2.0 * adx, - temp16a); - - axtcclen = scale_expansion_zeroelim(4, cc, adxtail, axtcc); - temp16blen = scale_expansion_zeroelim(axtcclen, axtcc, bdy, temp16b); - - axtbblen = scale_expansion_zeroelim(4, bb, adxtail, axtbb); - temp16clen = scale_expansion_zeroelim(axtbblen, axtbb, -cdy, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (adytail != 0.0) { - aytbclen = scale_expansion_zeroelim(4, bc, adytail, aytbc); - temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, 2.0 * ady, - temp16a); - - aytbblen = scale_expansion_zeroelim(4, bb, adytail, aytbb); - temp16blen = scale_expansion_zeroelim(aytbblen, aytbb, cdx, temp16b); - - aytcclen = scale_expansion_zeroelim(4, cc, adytail, aytcc); - temp16clen = scale_expansion_zeroelim(aytcclen, aytcc, -bdx, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdxtail != 0.0) { - bxtcalen = scale_expansion_zeroelim(4, ca, bdxtail, bxtca); - temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, 2.0 * bdx, - temp16a); - - bxtaalen = scale_expansion_zeroelim(4, aa, bdxtail, bxtaa); - temp16blen = scale_expansion_zeroelim(bxtaalen, bxtaa, cdy, temp16b); - - bxtcclen = scale_expansion_zeroelim(4, cc, bdxtail, bxtcc); - temp16clen = scale_expansion_zeroelim(bxtcclen, bxtcc, -ady, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdytail != 0.0) { - bytcalen = scale_expansion_zeroelim(4, ca, bdytail, bytca); - temp16alen = scale_expansion_zeroelim(bytcalen, bytca, 2.0 * bdy, - temp16a); - - bytcclen = scale_expansion_zeroelim(4, cc, bdytail, bytcc); - temp16blen = scale_expansion_zeroelim(bytcclen, bytcc, adx, temp16b); - - bytaalen = scale_expansion_zeroelim(4, aa, bdytail, bytaa); - temp16clen = scale_expansion_zeroelim(bytaalen, bytaa, -cdx, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdxtail != 0.0) { - cxtablen = scale_expansion_zeroelim(4, ab, cdxtail, cxtab); - temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, 2.0 * cdx, - temp16a); - - cxtbblen = scale_expansion_zeroelim(4, bb, cdxtail, cxtbb); - temp16blen = scale_expansion_zeroelim(cxtbblen, cxtbb, ady, temp16b); - - cxtaalen = scale_expansion_zeroelim(4, aa, cdxtail, cxtaa); - temp16clen = scale_expansion_zeroelim(cxtaalen, cxtaa, -bdy, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdytail != 0.0) { - cytablen = scale_expansion_zeroelim(4, ab, cdytail, cytab); - temp16alen = scale_expansion_zeroelim(cytablen, cytab, 2.0 * cdy, - temp16a); - - cytaalen = scale_expansion_zeroelim(4, aa, cdytail, cytaa); - temp16blen = scale_expansion_zeroelim(cytaalen, cytaa, bdx, temp16b); - - cytbblen = scale_expansion_zeroelim(4, bb, cdytail, cytbb); - temp16clen = scale_expansion_zeroelim(cytbblen, cytbb, -adx, temp16c); - - temp32alen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16clen, temp16c, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - if ((adxtail != 0.0) || (adytail != 0.0)) { - if ((bdxtail != 0.0) || (bdytail != 0.0) - || (cdxtail != 0.0) || (cdytail != 0.0)) { - Two_Product(bdxtail, cdy, ti1, ti0); - Two_Product(bdx, cdytail, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]); - u[3] = u3; - negate = -bdy; - Two_Product(cdxtail, negate, ti1, ti0); - negate = -bdytail; - Two_Product(cdx, negate, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]); - v[3] = v3; - bctlen = fast_expansion_sum_zeroelim(4, u, 4, v, bct); - - Two_Product(bdxtail, cdytail, ti1, ti0); - Two_Product(cdxtail, bdytail, tj1, tj0); - Two_Two_Diff(ti1, ti0, tj1, tj0, bctt3, bctt[2], bctt[1], bctt[0]); - bctt[3] = bctt3; - bcttlen = 4; - } else { - bct[0] = 0.0; - bctlen = 1; - bctt[0] = 0.0; - bcttlen = 1; - } - - if (adxtail != 0.0) { - temp16alen = scale_expansion_zeroelim(axtbclen, axtbc, adxtail, temp16a); - axtbctlen = scale_expansion_zeroelim(bctlen, bct, adxtail, axtbct); - temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, 2.0 * adx, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - if (bdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, cc, adxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, bb, -adxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - temp32alen = scale_expansion_zeroelim(axtbctlen, axtbct, adxtail, - temp32a); - axtbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adxtail, axtbctt); - temp16alen = scale_expansion_zeroelim(axtbcttlen, axtbctt, 2.0 * adx, - temp16a); - temp16blen = scale_expansion_zeroelim(axtbcttlen, axtbctt, adxtail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (adytail != 0.0) { - temp16alen = scale_expansion_zeroelim(aytbclen, aytbc, adytail, temp16a); - aytbctlen = scale_expansion_zeroelim(bctlen, bct, adytail, aytbct); - temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, 2.0 * ady, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - - - temp32alen = scale_expansion_zeroelim(aytbctlen, aytbct, adytail, - temp32a); - aytbcttlen = scale_expansion_zeroelim(bcttlen, bctt, adytail, aytbctt); - temp16alen = scale_expansion_zeroelim(aytbcttlen, aytbctt, 2.0 * ady, - temp16a); - temp16blen = scale_expansion_zeroelim(aytbcttlen, aytbctt, adytail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - } - if ((bdxtail != 0.0) || (bdytail != 0.0)) { - if ((cdxtail != 0.0) || (cdytail != 0.0) - || (adxtail != 0.0) || (adytail != 0.0)) { - Two_Product(cdxtail, ady, ti1, ti0); - Two_Product(cdx, adytail, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]); - u[3] = u3; - negate = -cdy; - Two_Product(adxtail, negate, ti1, ti0); - negate = -cdytail; - Two_Product(adx, negate, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]); - v[3] = v3; - catlen = fast_expansion_sum_zeroelim(4, u, 4, v, cat); - - Two_Product(cdxtail, adytail, ti1, ti0); - Two_Product(adxtail, cdytail, tj1, tj0); - Two_Two_Diff(ti1, ti0, tj1, tj0, catt3, catt[2], catt[1], catt[0]); - catt[3] = catt3; - cattlen = 4; - } else { - cat[0] = 0.0; - catlen = 1; - catt[0] = 0.0; - cattlen = 1; - } - - if (bdxtail != 0.0) { - temp16alen = scale_expansion_zeroelim(bxtcalen, bxtca, bdxtail, temp16a); - bxtcatlen = scale_expansion_zeroelim(catlen, cat, bdxtail, bxtcat); - temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, 2.0 * bdx, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - if (cdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, aa, bdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, cdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (adytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, cc, -bdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - temp32alen = scale_expansion_zeroelim(bxtcatlen, bxtcat, bdxtail, - temp32a); - bxtcattlen = scale_expansion_zeroelim(cattlen, catt, bdxtail, bxtcatt); - temp16alen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, 2.0 * bdx, - temp16a); - temp16blen = scale_expansion_zeroelim(bxtcattlen, bxtcatt, bdxtail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdytail != 0.0) { - temp16alen = scale_expansion_zeroelim(bytcalen, bytca, bdytail, temp16a); - bytcatlen = scale_expansion_zeroelim(catlen, cat, bdytail, bytcat); - temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, 2.0 * bdy, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - - - temp32alen = scale_expansion_zeroelim(bytcatlen, bytcat, bdytail, - temp32a); - bytcattlen = scale_expansion_zeroelim(cattlen, catt, bdytail, bytcatt); - temp16alen = scale_expansion_zeroelim(bytcattlen, bytcatt, 2.0 * bdy, - temp16a); - temp16blen = scale_expansion_zeroelim(bytcattlen, bytcatt, bdytail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - } - if ((cdxtail != 0.0) || (cdytail != 0.0)) { - if ((adxtail != 0.0) || (adytail != 0.0) - || (bdxtail != 0.0) || (bdytail != 0.0)) { - Two_Product(adxtail, bdy, ti1, ti0); - Two_Product(adx, bdytail, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, u3, u[2], u[1], u[0]); - u[3] = u3; - negate = -ady; - Two_Product(bdxtail, negate, ti1, ti0); - negate = -adytail; - Two_Product(bdx, negate, tj1, tj0); - Two_Two_Sum(ti1, ti0, tj1, tj0, v3, v[2], v[1], v[0]); - v[3] = v3; - abtlen = fast_expansion_sum_zeroelim(4, u, 4, v, abt); - - Two_Product(adxtail, bdytail, ti1, ti0); - Two_Product(bdxtail, adytail, tj1, tj0); - Two_Two_Diff(ti1, ti0, tj1, tj0, abtt3, abtt[2], abtt[1], abtt[0]); - abtt[3] = abtt3; - abttlen = 4; - } else { - abt[0] = 0.0; - abtlen = 1; - abtt[0] = 0.0; - abttlen = 1; - } - - if (cdxtail != 0.0) { - temp16alen = scale_expansion_zeroelim(cxtablen, cxtab, cdxtail, temp16a); - cxtabtlen = scale_expansion_zeroelim(abtlen, abt, cdxtail, cxtabt); - temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, 2.0 * cdx, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - if (adytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, bb, cdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, adytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (bdytail != 0.0) { - temp8len = scale_expansion_zeroelim(4, aa, -cdxtail, temp8); - temp16alen = scale_expansion_zeroelim(temp8len, temp8, bdytail, - temp16a); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp16alen, - temp16a, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - - temp32alen = scale_expansion_zeroelim(cxtabtlen, cxtabt, cdxtail, - temp32a); - cxtabttlen = scale_expansion_zeroelim(abttlen, abtt, cdxtail, cxtabtt); - temp16alen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, 2.0 * cdx, - temp16a); - temp16blen = scale_expansion_zeroelim(cxtabttlen, cxtabtt, cdxtail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - if (cdytail != 0.0) { - temp16alen = scale_expansion_zeroelim(cytablen, cytab, cdytail, temp16a); - cytabtlen = scale_expansion_zeroelim(abtlen, abt, cdytail, cytabt); - temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, 2.0 * cdy, - temp32a); - temp48len = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp32alen, temp32a, temp48); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp48len, - temp48, finother); - finswap = finnow; finnow = finother; finother = finswap; - - - temp32alen = scale_expansion_zeroelim(cytabtlen, cytabt, cdytail, - temp32a); - cytabttlen = scale_expansion_zeroelim(abttlen, abtt, cdytail, cytabtt); - temp16alen = scale_expansion_zeroelim(cytabttlen, cytabtt, 2.0 * cdy, - temp16a); - temp16blen = scale_expansion_zeroelim(cytabttlen, cytabtt, cdytail, - temp16b); - temp32blen = fast_expansion_sum_zeroelim(temp16alen, temp16a, - temp16blen, temp16b, temp32b); - temp64len = fast_expansion_sum_zeroelim(temp32alen, temp32a, - temp32blen, temp32b, temp64); - finlength = fast_expansion_sum_zeroelim(finlength, finnow, temp64len, - temp64, finother); - finswap = finnow; finnow = finother; finother = finswap; - } - } - - return finnow[finlength - 1]; -} - -REAL incircle(pa, pb, pc, pd) -point pa; -point pb; -point pc; -point pd; -{ - REAL adx, bdx, cdx, ady, bdy, cdy; - REAL bdxcdy, cdxbdy, cdxady, adxcdy, adxbdy, bdxady; - REAL alift, blift, clift; - REAL det; - REAL permanent, errbound; - - incirclecount++; - - adx = pa[0] - pd[0]; - bdx = pb[0] - pd[0]; - cdx = pc[0] - pd[0]; - ady = pa[1] - pd[1]; - bdy = pb[1] - pd[1]; - cdy = pc[1] - pd[1]; - - bdxcdy = bdx * cdy; - cdxbdy = cdx * bdy; - alift = adx * adx + ady * ady; - - cdxady = cdx * ady; - adxcdy = adx * cdy; - blift = bdx * bdx + bdy * bdy; - - adxbdy = adx * bdy; - bdxady = bdx * ady; - clift = cdx * cdx + cdy * cdy; - - det = alift * (bdxcdy - cdxbdy) - + blift * (cdxady - adxcdy) - + clift * (adxbdy - bdxady); - - if (noexact) { - return det; - } - - permanent = (Absolute(bdxcdy) + Absolute(cdxbdy)) * alift - + (Absolute(cdxady) + Absolute(adxcdy)) * blift - + (Absolute(adxbdy) + Absolute(bdxady)) * clift; - errbound = iccerrboundA * permanent; - if ((det > errbound) || (-det > errbound)) { - return det; - } - - return incircleadapt(pa, pb, pc, pd, permanent); -} - -/** **/ -/** **/ -/********* Determinant evaluation routines end here *********/ - -/*****************************************************************************/ -/* */ -/* triangleinit() Initialize some variables. */ -/* */ -/*****************************************************************************/ - -void triangleinit() -{ - points.maxitems = triangles.maxitems = shelles.maxitems = viri.maxitems = - badsegments.maxitems = badtriangles.maxitems = splaynodes.maxitems = 0l; - points.itembytes = triangles.itembytes = shelles.itembytes = viri.itembytes = - badsegments.itembytes = badtriangles.itembytes = splaynodes.itembytes = 0; - recenttri.tri = (triangle *) NULL; /* No triangle has been visited yet. */ - samples = 1; /* Point location should take at least one sample. */ - checksegments = 0; /* There are no segments in the triangulation yet. */ - incirclecount = counterclockcount = hyperbolacount = 0; - circumcentercount = circletopcount = 0; - randomseed = 1; - - exactinit(); /* Initialize exact arithmetic constants. */ -} - -/*****************************************************************************/ -/* */ -/* randomnation() Generate a random number between 0 and `choices' - 1. */ -/* */ -/* This is a simple linear congruential random number generator. Hence, it */ -/* is a bad random number generator, but good enough for most randomized */ -/* geometric algorithms. */ -/* */ -/*****************************************************************************/ - -unsigned long randomnation(choices) -unsigned int choices; -{ - randomseed = (randomseed * 1366l + 150889l) % 714025l; - return randomseed / (714025l / choices + 1); -} - -/********* Mesh quality testing routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* checkmesh() Test the mesh for topological consistency. */ -/* */ -/*****************************************************************************/ - -#ifndef REDUCED - -void checkmesh() -{ - struct triedge triangleloop; - struct triedge oppotri, oppooppotri; - point triorg, tridest, triapex; - point oppoorg, oppodest; - int horrors; - int saveexact; - triangle ptr; /* Temporary variable used by sym(). */ - - /* Temporarily turn on exact arithmetic if it's off. */ - saveexact = noexact; - noexact = 0; - if (!quiet) { - printf(" Checking consistency of mesh...\n"); - } - horrors = 0; - /* Run through the list of triangles, checking each one. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* Check all three edges of the triangle. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - org(triangleloop, triorg); - dest(triangleloop, tridest); - if (triangleloop.orient == 0) { /* Only test for inversion once. */ - /* Test if the triangle is flat or inverted. */ - apex(triangleloop, triapex); - if (counterclockwise(triorg, tridest, triapex) <= 0.0) { - printf(" !! !! Inverted "); - printtriangle(&triangleloop); - horrors++; - } - } - /* Find the neighboring triangle on this edge. */ - sym(triangleloop, oppotri); - if (oppotri.tri != dummytri) { - /* Check that the triangle's neighbor knows it's a neighbor. */ - sym(oppotri, oppooppotri); - if ((triangleloop.tri != oppooppotri.tri) - || (triangleloop.orient != oppooppotri.orient)) { - printf(" !! !! Asymmetric triangle-triangle bond:\n"); - if (triangleloop.tri == oppooppotri.tri) { - printf(" (Right triangle, wrong orientation)\n"); - } - printf(" First "); - printtriangle(&triangleloop); - printf(" Second (nonreciprocating) "); - printtriangle(&oppotri); - horrors++; - } - /* Check that both triangles agree on the identities */ - /* of their shared vertices. */ - org(oppotri, oppoorg); - dest(oppotri, oppodest); - if ((triorg != oppodest) || (tridest != oppoorg)) { - printf(" !! !! Mismatched edge coordinates between two triangles:\n" - ); - printf(" First mismatched "); - printtriangle(&triangleloop); - printf(" Second mismatched "); - printtriangle(&oppotri); - horrors++; - } - } - } - triangleloop.tri = triangletraverse(); - } - if (horrors == 0) { - if (!quiet) { - printf(" In my studied opinion, the mesh appears to be consistent.\n"); - } - } else if (horrors == 1) { - printf(" !! !! !! !! Precisely one festering wound discovered.\n"); - } else { - printf(" !! !! !! !! %d abominations witnessed.\n", horrors); - } - /* Restore the status of exact arithmetic. */ - noexact = saveexact; -} - -#endif /* not REDUCED */ - -/*****************************************************************************/ -/* */ -/* checkdelaunay() Ensure that the mesh is (constrained) Delaunay. */ -/* */ -/*****************************************************************************/ - -#ifndef REDUCED - -void checkdelaunay() -{ - struct triedge triangleloop; - struct triedge oppotri; - struct edge opposhelle; - point triorg, tridest, triapex; - point oppoapex; - int shouldbedelaunay; - int horrors; - int saveexact; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - /* Temporarily turn on exact arithmetic if it's off. */ - saveexact = noexact; - noexact = 0; - if (!quiet) { - printf(" Checking Delaunay property of mesh...\n"); - } - horrors = 0; - /* Run through the list of triangles, checking each one. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* Check all three edges of the triangle. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - org(triangleloop, triorg); - dest(triangleloop, tridest); - apex(triangleloop, triapex); - sym(triangleloop, oppotri); - apex(oppotri, oppoapex); - /* Only test that the edge is locally Delaunay if there is an */ - /* adjoining triangle whose pointer is larger (to ensure that */ - /* each pair isn't tested twice). */ - shouldbedelaunay = (oppotri.tri != dummytri) - && (triapex != (point) NULL) && (oppoapex != (point) NULL) - && (triangleloop.tri < oppotri.tri); - if (checksegments && shouldbedelaunay) { - /* If a shell edge separates the triangles, then the edge is */ - /* constrained, so no local Delaunay test should be done. */ - tspivot(triangleloop, opposhelle); - if (opposhelle.sh != dummysh){ - shouldbedelaunay = 0; - } - } - if (shouldbedelaunay) { - if (incircle(triorg, tridest, triapex, oppoapex) > 0.0) { - printf(" !! !! Non-Delaunay pair of triangles:\n"); - printf(" First non-Delaunay "); - printtriangle(&triangleloop); - printf(" Second non-Delaunay "); - printtriangle(&oppotri); - horrors++; - } - } - } - triangleloop.tri = triangletraverse(); - } - if (horrors == 0) { - if (!quiet) { - printf( - " By virtue of my perceptive intelligence, I declare the mesh Delaunay.\n"); - } - } else if (horrors == 1) { - printf( - " !! !! !! !! Precisely one terrifying transgression identified.\n"); - } else { - printf(" !! !! !! !! %d obscenities viewed with horror.\n", horrors); - } - /* Restore the status of exact arithmetic. */ - noexact = saveexact; -} - -#endif /* not REDUCED */ - -/*****************************************************************************/ -/* */ -/* enqueuebadtri() Add a bad triangle to the end of a queue. */ -/* */ -/* The queue is actually a set of 64 queues. I use multiple queues to give */ -/* priority to smaller angles. I originally implemented a heap, but the */ -/* queues are (to my surprise) much faster. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void enqueuebadtri(instri, angle, insapex, insorg, insdest) -struct triedge *instri; -REAL angle; -point insapex; -point insorg; -point insdest; -{ - struct badface *newface; - int queuenumber; - - if (verbose > 2) { - printf(" Queueing bad triangle:\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", insorg[0], - insorg[1], insdest[0], insdest[1], insapex[0], insapex[1]); - } - /* Allocate space for the bad triangle. */ - newface = (struct badface *) poolalloc(&badtriangles); - triedgecopy(*instri, newface->badfacetri); - newface->key = angle; - newface->faceapex = insapex; - newface->faceorg = insorg; - newface->facedest = insdest; - newface->nextface = (struct badface *) NULL; - /* Determine the appropriate queue to put the bad triangle into. */ - if (angle > 0.6) { - queuenumber = (int) (160.0 * (angle - 0.6)); - if (queuenumber > 63) { - queuenumber = 63; - } - } else { - /* It's not a bad angle; put the triangle in the lowest-priority queue. */ - queuenumber = 0; - } - /* Add the triangle to the end of a queue. */ - *queuetail[queuenumber] = newface; - /* Maintain a pointer to the NULL pointer at the end of the queue. */ - queuetail[queuenumber] = &newface->nextface; -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* dequeuebadtri() Remove a triangle from the front of the queue. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -struct badface *dequeuebadtri() -{ - struct badface *result; - int queuenumber; - - /* Look for a nonempty queue. */ - for (queuenumber = 63; queuenumber >= 0; queuenumber--) { - result = queuefront[queuenumber]; - if (result != (struct badface *) NULL) { - /* Remove the triangle from the queue. */ - queuefront[queuenumber] = result->nextface; - /* Maintain a pointer to the NULL pointer at the end of the queue. */ - if (queuefront[queuenumber] == (struct badface *) NULL) { - queuetail[queuenumber] = &queuefront[queuenumber]; - } - return result; - } - } - return (struct badface *) NULL; -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* checkedge4encroach() Check a segment to see if it is encroached; add */ -/* it to the list if it is. */ -/* */ -/* An encroached segment is an unflippable edge that has a point in its */ -/* diametral circle (that is, it faces an angle greater than 90 degrees). */ -/* This definition is due to Ruppert. */ -/* */ -/* Returns a nonzero value if the edge is encroached. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -int checkedge4encroach(testedge) -struct edge *testedge; -{ - struct triedge neighbortri; - struct edge testsym; - struct edge *badedge; - int addtolist; - int sides; - point eorg, edest, eapex; - triangle ptr; /* Temporary variable used by stpivot(). */ - - addtolist = 0; - sides = 0; - - sorg(*testedge, eorg); - sdest(*testedge, edest); - /* Check one neighbor of the shell edge. */ - stpivot(*testedge, neighbortri); - /* Does the neighbor exist, or is this a boundary edge? */ - if (neighbortri.tri != dummytri) { - sides++; - /* Find a vertex opposite this edge. */ - apex(neighbortri, eapex); - /* Check whether the vertex is inside the diametral circle of the */ - /* shell edge. Pythagoras' Theorem is used to check whether the */ - /* angle at the vertex is greater than 90 degrees. */ - if (eapex[0] * (eorg[0] + edest[0]) + eapex[1] * (eorg[1] + edest[1]) > - eapex[0] * eapex[0] + eorg[0] * edest[0] + - eapex[1] * eapex[1] + eorg[1] * edest[1]) { - addtolist = 1; - } - } - /* Check the other neighbor of the shell edge. */ - ssym(*testedge, testsym); - stpivot(testsym, neighbortri); - /* Does the neighbor exist, or is this a boundary edge? */ - if (neighbortri.tri != dummytri) { - sides++; - /* Find the other vertex opposite this edge. */ - apex(neighbortri, eapex); - /* Check whether the vertex is inside the diametral circle of the */ - /* shell edge. Pythagoras' Theorem is used to check whether the */ - /* angle at the vertex is greater than 90 degrees. */ - if (eapex[0] * (eorg[0] + edest[0]) + - eapex[1] * (eorg[1] + edest[1]) > - eapex[0] * eapex[0] + eorg[0] * edest[0] + - eapex[1] * eapex[1] + eorg[1] * edest[1]) { - addtolist += 2; - } - } - - if (addtolist && (!nobisect || ((nobisect == 1) && (sides == 2)))) { - if (verbose > 2) { - printf(" Queueing encroached segment (%.12g, %.12g) (%.12g, %.12g).\n", - eorg[0], eorg[1], edest[0], edest[1]); - } - /* Add the shell edge to the list of encroached segments. */ - /* Be sure to get the orientation right. */ - badedge = (struct edge *) poolalloc(&badsegments); - if (addtolist == 1) { - shellecopy(*testedge, *badedge); - } else { - shellecopy(testsym, *badedge); - } - } - return addtolist; -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* testtriangle() Test a face for quality measures. */ -/* */ -/* Tests a triangle to see if it satisfies the minimum angle condition and */ -/* the maximum area condition. Triangles that aren't up to spec are added */ -/* to the bad triangle queue. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void testtriangle(testtri) -struct triedge *testtri; -{ - struct triedge sametesttri; - struct edge edge1, edge2; - point torg, tdest, tapex; - point anglevertex; - REAL dxod, dyod, dxda, dyda, dxao, dyao; - REAL dxod2, dyod2, dxda2, dyda2, dxao2, dyao2; - REAL apexlen, orglen, destlen; - REAL angle; - REAL area; - shelle sptr; /* Temporary variable used by tspivot(). */ - - org(*testtri, torg); - dest(*testtri, tdest); - apex(*testtri, tapex); - dxod = torg[0] - tdest[0]; - dyod = torg[1] - tdest[1]; - dxda = tdest[0] - tapex[0]; - dyda = tdest[1] - tapex[1]; - dxao = tapex[0] - torg[0]; - dyao = tapex[1] - torg[1]; - dxod2 = dxod * dxod; - dyod2 = dyod * dyod; - dxda2 = dxda * dxda; - dyda2 = dyda * dyda; - dxao2 = dxao * dxao; - dyao2 = dyao * dyao; - /* Find the lengths of the triangle's three edges. */ - apexlen = dxod2 + dyod2; - orglen = dxda2 + dyda2; - destlen = dxao2 + dyao2; - if ((apexlen < orglen) && (apexlen < destlen)) { - /* The edge opposite the apex is shortest. */ - /* Find the square of the cosine of the angle at the apex. */ - angle = dxda * dxao + dyda * dyao; - angle = angle * angle / (orglen * destlen); - anglevertex = tapex; - lnext(*testtri, sametesttri); - tspivot(sametesttri, edge1); - lnextself(sametesttri); - tspivot(sametesttri, edge2); - } else if (orglen < destlen) { - /* The edge opposite the origin is shortest. */ - /* Find the square of the cosine of the angle at the origin. */ - angle = dxod * dxao + dyod * dyao; - angle = angle * angle / (apexlen * destlen); - anglevertex = torg; - tspivot(*testtri, edge1); - lprev(*testtri, sametesttri); - tspivot(sametesttri, edge2); - } else { - /* The edge opposite the destination is shortest. */ - /* Find the square of the cosine of the angle at the destination. */ - angle = dxod * dxda + dyod * dyda; - angle = angle * angle / (apexlen * orglen); - anglevertex = tdest; - tspivot(*testtri, edge1); - lnext(*testtri, sametesttri); - tspivot(sametesttri, edge2); - } - /* Check if both edges that form the angle are segments. */ - if ((edge1.sh != dummysh) && (edge2.sh != dummysh)) { - /* The angle is a segment intersection. */ - if ((angle > 0.9924) && !quiet) { /* Roughly 5 degrees. */ - if (angle > 1.0) { - /* Beware of a floating exception in acos(). */ - angle = 1.0; - } - /* Find the actual angle in degrees, for printing. */ - angle = acos(sqrt(angle)) * (180.0 / PI); - printf( - "Warning: Small angle (%.4g degrees) between segments at point\n", - angle); - printf(" (%.12g, %.12g)\n", anglevertex[0], anglevertex[1]); - } - /* Don't add this bad triangle to the list; there's nothing that */ - /* can be done about a small angle between two segments. */ - angle = 0.0; - } - /* Check whether the angle is smaller than permitted. */ - if (angle > goodangle) { - /* Add this triangle to the list of bad triangles. */ - enqueuebadtri(testtri, angle, tapex, torg, tdest); - return; - } - if (vararea || fixedarea) { - /* Check whether the area is larger than permitted. */ - area = 0.5 * (dxod * dyda - dyod * dxda); - if (fixedarea && (area > maxarea)) { - /* Add this triangle to the list of bad triangles. */ - enqueuebadtri(testtri, angle, tapex, torg, tdest); - } else if (vararea) { - /* Nonpositive area constraints are treated as unconstrained. */ - if ((area > areabound(*testtri)) && (areabound(*testtri) > 0.0)) { - /* Add this triangle to the list of bad triangles. */ - enqueuebadtri(testtri, angle, tapex, torg, tdest); - } - } - } -} - -#endif /* not CDT_ONLY */ - -/** **/ -/** **/ -/********* Mesh quality testing routines end here *********/ - -/********* Point location routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* makepointmap() Construct a mapping from points to triangles to improve */ -/* the speed of point location for segment insertion. */ -/* */ -/* Traverses all the triangles, and provides each corner of each triangle */ -/* with a pointer to that triangle. Of course, pointers will be */ -/* overwritten by other pointers because (almost) each point is a corner */ -/* of several triangles, but in the end every point will point to some */ -/* triangle that contains it. */ -/* */ -/*****************************************************************************/ - -void makepointmap() -{ - struct triedge triangleloop; - point triorg; - - if (verbose) { - printf(" Constructing mapping from points to triangles.\n"); - } - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* Check all three points of the triangle. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - org(triangleloop, triorg); - setpoint2tri(triorg, encode(triangleloop)); - } - triangleloop.tri = triangletraverse(); - } -} - -/*****************************************************************************/ -/* */ -/* preciselocate() Find a triangle or edge containing a given point. */ -/* */ -/* Begins its search from `searchtri'. It is important that `searchtri' */ -/* be a handle with the property that `searchpoint' is strictly to the left */ -/* of the edge denoted by `searchtri', or is collinear with that edge and */ -/* does not intersect that edge. (In particular, `searchpoint' should not */ -/* be the origin or destination of that edge.) */ -/* */ -/* These conditions are imposed because preciselocate() is normally used in */ -/* one of two situations: */ -/* */ -/* (1) To try to find the location to insert a new point. Normally, we */ -/* know an edge that the point is strictly to the left of. In the */ -/* incremental Delaunay algorithm, that edge is a bounding box edge. */ -/* In Ruppert's Delaunay refinement algorithm for quality meshing, */ -/* that edge is the shortest edge of the triangle whose circumcenter */ -/* is being inserted. */ -/* */ -/* (2) To try to find an existing point. In this case, any edge on the */ -/* convex hull is a good starting edge. The possibility that the */ -/* vertex one seeks is an endpoint of the starting edge must be */ -/* screened out before preciselocate() is called. */ -/* */ -/* On completion, `searchtri' is a triangle that contains `searchpoint'. */ -/* */ -/* This implementation differs from that given by Guibas and Stolfi. It */ -/* walks from triangle to triangle, crossing an edge only if `searchpoint' */ -/* is on the other side of the line containing that edge. After entering */ -/* a triangle, there are two edges by which one can leave that triangle. */ -/* If both edges are valid (`searchpoint' is on the other side of both */ -/* edges), one of the two is chosen by drawing a line perpendicular to */ -/* the entry edge (whose endpoints are `forg' and `fdest') passing through */ -/* `fapex'. Depending on which side of this perpendicular `searchpoint' */ -/* falls on, an exit edge is chosen. */ -/* */ -/* This implementation is empirically faster than the Guibas and Stolfi */ -/* point location routine (which I originally used), which tends to spiral */ -/* in toward its target. */ -/* */ -/* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */ -/* is a handle whose origin is the existing vertex. */ -/* */ -/* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */ -/* handle whose primary edge is the edge on which the point lies. */ -/* */ -/* Returns INTRIANGLE if the point lies strictly within a triangle. */ -/* `searchtri' is a handle on the triangle that contains the point. */ -/* */ -/* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */ -/* handle whose primary edge the point is to the right of. This might */ -/* occur when the circumcenter of a triangle falls just slightly outside */ -/* the mesh due to floating-point roundoff error. It also occurs when */ -/* seeking a hole or region point that a foolish user has placed outside */ -/* the mesh. */ -/* */ -/* WARNING: This routine is designed for convex triangulations, and will */ -/* not generally work after the holes and concavities have been carved. */ -/* However, it can still be used to find the circumcenter of a triangle, as */ -/* long as the search is begun from the triangle in question. */ -/* */ -/*****************************************************************************/ - -enum locateresult preciselocate(searchpoint, searchtri) -point searchpoint; -struct triedge *searchtri; -{ - struct triedge backtracktri; - point forg, fdest, fapex; - point swappoint; - REAL orgorient, destorient; - int moveleft; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose > 2) { - printf(" Searching for point (%.12g, %.12g).\n", - searchpoint[0], searchpoint[1]); - } - /* Where are we? */ - org(*searchtri, forg); - dest(*searchtri, fdest); - apex(*searchtri, fapex); - while (1) { - if (verbose > 2) { - printf(" At (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - forg[0], forg[1], fdest[0], fdest[1], fapex[0], fapex[1]); - } - /* Check whether the apex is the point we seek. */ - if ((fapex[0] == searchpoint[0]) && (fapex[1] == searchpoint[1])) { - lprevself(*searchtri); - return ONVERTEX; - } - /* Does the point lie on the other side of the line defined by the */ - /* triangle edge opposite the triangle's destination? */ - destorient = counterclockwise(forg, fapex, searchpoint); - /* Does the point lie on the other side of the line defined by the */ - /* triangle edge opposite the triangle's origin? */ - orgorient = counterclockwise(fapex, fdest, searchpoint); - if (destorient > 0.0) { - if (orgorient > 0.0) { - /* Move left if the inner product of (fapex - searchpoint) and */ - /* (fdest - forg) is positive. This is equivalent to drawing */ - /* a line perpendicular to the line (forg, fdest) passing */ - /* through `fapex', and determining which side of this line */ - /* `searchpoint' falls on. */ - moveleft = (fapex[0] - searchpoint[0]) * (fdest[0] - forg[0]) + - (fapex[1] - searchpoint[1]) * (fdest[1] - forg[1]) > 0.0; - } else { - moveleft = 1; - } - } else { - if (orgorient > 0.0) { - moveleft = 0; - } else { - /* The point we seek must be on the boundary of or inside this */ - /* triangle. */ - if (destorient == 0.0) { - lprevself(*searchtri); - return ONEDGE; - } - if (orgorient == 0.0) { - lnextself(*searchtri); - return ONEDGE; - } - return INTRIANGLE; - } - } - - /* Move to another triangle. Leave a trace `backtracktri' in case */ - /* floating-point roundoff or some such bogey causes us to walk */ - /* off a boundary of the triangulation. We can just bounce off */ - /* the boundary as if it were an elastic band. */ - if (moveleft) { - lprev(*searchtri, backtracktri); - fdest = fapex; - } else { - lnext(*searchtri, backtracktri); - forg = fapex; - } - sym(backtracktri, *searchtri); - - /* Check for walking off the edge. */ - if (searchtri->tri == dummytri) { - /* Turn around. */ - triedgecopy(backtracktri, *searchtri); - swappoint = forg; - forg = fdest; - fdest = swappoint; - apex(*searchtri, fapex); - /* Check if the point really is beyond the triangulation boundary. */ - destorient = counterclockwise(forg, fapex, searchpoint); - orgorient = counterclockwise(fapex, fdest, searchpoint); - if ((orgorient < 0.0) && (destorient < 0.0)) { - return OUTSIDE; - } - } else { - apex(*searchtri, fapex); - } - } -} - -/*****************************************************************************/ -/* */ -/* locate() Find a triangle or edge containing a given point. */ -/* */ -/* Searching begins from one of: the input `searchtri', a recently */ -/* encountered triangle `recenttri', or from a triangle chosen from a */ -/* random sample. The choice is made by determining which triangle's */ -/* origin is closest to the point we are searcing for. Normally, */ -/* `searchtri' should be a handle on the convex hull of the triangulation. */ -/* */ -/* Details on the random sampling method can be found in the Mucke, Saias, */ -/* and Zhu paper cited in the header of this code. */ -/* */ -/* On completion, `searchtri' is a triangle that contains `searchpoint'. */ -/* */ -/* Returns ONVERTEX if the point lies on an existing vertex. `searchtri' */ -/* is a handle whose origin is the existing vertex. */ -/* */ -/* Returns ONEDGE if the point lies on a mesh edge. `searchtri' is a */ -/* handle whose primary edge is the edge on which the point lies. */ -/* */ -/* Returns INTRIANGLE if the point lies strictly within a triangle. */ -/* `searchtri' is a handle on the triangle that contains the point. */ -/* */ -/* Returns OUTSIDE if the point lies outside the mesh. `searchtri' is a */ -/* handle whose primary edge the point is to the right of. This might */ -/* occur when the circumcenter of a triangle falls just slightly outside */ -/* the mesh due to floating-point roundoff error. It also occurs when */ -/* seeking a hole or region point that a foolish user has placed outside */ -/* the mesh. */ -/* */ -/* WARNING: This routine is designed for convex triangulations, and will */ -/* not generally work after the holes and concavities have been carved. */ -/* */ -/*****************************************************************************/ - -enum locateresult locate(searchpoint, searchtri) -point searchpoint; -struct triedge *searchtri; -{ - VOID **sampleblock; - triangle *firsttri; - struct triedge sampletri; - point torg, tdest; - unsigned long alignptr; - REAL searchdist, dist; - REAL ahead; - long sampleblocks, samplesperblock, samplenum; - long triblocks; - long i, j; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose > 2) { - printf(" Randomly sampling for a triangle near point (%.12g, %.12g).\n", - searchpoint[0], searchpoint[1]); - } - /* Record the distance from the suggested starting triangle to the */ - /* point we seek. */ - org(*searchtri, torg); - searchdist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) - + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]); - if (verbose > 2) { - printf(" Boundary triangle has origin (%.12g, %.12g).\n", - torg[0], torg[1]); - } - - /* If a recently encountered triangle has been recorded and has not been */ - /* deallocated, test it as a good starting point. */ - if (recenttri.tri != (triangle *) NULL) { - if (recenttri.tri[3] != (triangle) NULL) { - org(recenttri, torg); - if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) { - triedgecopy(recenttri, *searchtri); - return ONVERTEX; - } - dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) - + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]); - if (dist < searchdist) { - triedgecopy(recenttri, *searchtri); - searchdist = dist; - if (verbose > 2) { - printf(" Choosing recent triangle with origin (%.12g, %.12g).\n", - torg[0], torg[1]); - } - } - } - } - - /* The number of random samples taken is proportional to the cube root of */ - /* the number of triangles in the mesh. The next bit of code assumes */ - /* that the number of triangles increases monotonically. */ - while (SAMPLEFACTOR * samples * samples * samples < triangles.items) { - samples++; - } - triblocks = (triangles.maxitems + TRIPERBLOCK - 1) / TRIPERBLOCK; - samplesperblock = 1 + (samples / triblocks); - sampleblocks = samples / samplesperblock; - sampleblock = triangles.firstblock; - sampletri.orient = 0; - for (i = 0; i < sampleblocks; i++) { - alignptr = (unsigned long) (sampleblock + 1); - firsttri = (triangle *) (alignptr + (unsigned long) triangles.alignbytes - - (alignptr % (unsigned long) triangles.alignbytes)); - for (j = 0; j < samplesperblock; j++) { - if (i == triblocks - 1) { - samplenum = randomnation((int) - (triangles.maxitems - (i * TRIPERBLOCK))); - } else { - samplenum = randomnation(TRIPERBLOCK); - } - sampletri.tri = (triangle *) - (firsttri + (samplenum * triangles.itemwords)); - if (sampletri.tri[3] != (triangle) NULL) { - org(sampletri, torg); - dist = (searchpoint[0] - torg[0]) * (searchpoint[0] - torg[0]) - + (searchpoint[1] - torg[1]) * (searchpoint[1] - torg[1]); - if (dist < searchdist) { - triedgecopy(sampletri, *searchtri); - searchdist = dist; - if (verbose > 2) { - printf(" Choosing triangle with origin (%.12g, %.12g).\n", - torg[0], torg[1]); - } - } - } - } - sampleblock = (VOID **) *sampleblock; - } - /* Where are we? */ - org(*searchtri, torg); - dest(*searchtri, tdest); - /* Check the starting triangle's vertices. */ - if ((torg[0] == searchpoint[0]) && (torg[1] == searchpoint[1])) { - return ONVERTEX; - } - if ((tdest[0] == searchpoint[0]) && (tdest[1] == searchpoint[1])) { - lnextself(*searchtri); - return ONVERTEX; - } - /* Orient `searchtri' to fit the preconditions of calling preciselocate(). */ - ahead = counterclockwise(torg, tdest, searchpoint); - if (ahead < 0.0) { - /* Turn around so that `searchpoint' is to the left of the */ - /* edge specified by `searchtri'. */ - symself(*searchtri); - } else if (ahead == 0.0) { - /* Check if `searchpoint' is between `torg' and `tdest'. */ - if (((torg[0] < searchpoint[0]) == (searchpoint[0] < tdest[0])) - && ((torg[1] < searchpoint[1]) == (searchpoint[1] < tdest[1]))) { - return ONEDGE; - } - } - return preciselocate(searchpoint, searchtri); -} - -/** **/ -/** **/ -/********* Point location routines end here *********/ - -/********* Mesh transformation routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* insertshelle() Create a new shell edge and insert it between two */ -/* triangles. */ -/* */ -/* The new shell edge is inserted at the edge described by the handle */ -/* `tri'. Its vertices are properly initialized. The marker `shellemark' */ -/* is applied to the shell edge and, if appropriate, its vertices. */ -/* */ -/*****************************************************************************/ - -void insertshelle(tri, shellemark) -struct triedge *tri; /* Edge at which to insert the new shell edge. */ -int shellemark; /* Marker for the new shell edge. */ -{ - struct triedge oppotri; - struct edge newshelle; - point triorg, tridest; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - /* Mark points if possible. */ - org(*tri, triorg); - dest(*tri, tridest); - if (pointmark(triorg) == 0) { - setpointmark(triorg, shellemark); - } - if (pointmark(tridest) == 0) { - setpointmark(tridest, shellemark); - } - /* Check if there's already a shell edge here. */ - tspivot(*tri, newshelle); - if (newshelle.sh == dummysh) { - /* Make new shell edge and initialize its vertices. */ - makeshelle(&newshelle); - setsorg(newshelle, tridest); - setsdest(newshelle, triorg); - /* Bond new shell edge to the two triangles it is sandwiched between. */ - /* Note that the facing triangle `oppotri' might be equal to */ - /* `dummytri' (outer space), but the new shell edge is bonded to it */ - /* all the same. */ - tsbond(*tri, newshelle); - sym(*tri, oppotri); - ssymself(newshelle); - tsbond(oppotri, newshelle); - setmark(newshelle, shellemark); - if (verbose > 2) { - printf(" Inserting new "); - printshelle(&newshelle); - } - } else { - if (mark(newshelle) == 0) { - setmark(newshelle, shellemark); - } - } -} - -/*****************************************************************************/ -/* */ -/* Terminology */ -/* */ -/* A "local transformation" replaces a small set of triangles with another */ -/* set of triangles. This may or may not involve inserting or deleting a */ -/* point. */ -/* */ -/* The term "casing" is used to describe the set of triangles that are */ -/* attached to the triangles being transformed, but are not transformed */ -/* themselves. Think of the casing as a fixed hollow structure inside */ -/* which all the action happens. A "casing" is only defined relative to */ -/* a single transformation; each occurrence of a transformation will */ -/* involve a different casing. */ -/* */ -/* A "shell" is similar to a "casing". The term "shell" describes the set */ -/* of shell edges (if any) that are attached to the triangles being */ -/* transformed. However, I sometimes use "shell" to refer to a single */ -/* shell edge, so don't get confused. */ -/* */ -/*****************************************************************************/ - -/*****************************************************************************/ -/* */ -/* flip() Transform two triangles to two different triangles by flipping */ -/* an edge within a quadrilateral. */ -/* */ -/* Imagine the original triangles, abc and bad, oriented so that the */ -/* shared edge ab lies in a horizontal plane, with the point b on the left */ -/* and the point a on the right. The point c lies below the edge, and the */ -/* point d lies above the edge. The `flipedge' handle holds the edge ab */ -/* of triangle abc, and is directed left, from vertex a to vertex b. */ -/* */ -/* The triangles abc and bad are deleted and replaced by the triangles cdb */ -/* and dca. The triangles that represent abc and bad are NOT deallocated; */ -/* they are reused for dca and cdb, respectively. Hence, any handles that */ -/* may have held the original triangles are still valid, although not */ -/* directed as they were before. */ -/* */ -/* Upon completion of this routine, the `flipedge' handle holds the edge */ -/* dc of triangle dca, and is directed down, from vertex d to vertex c. */ -/* (Hence, the two triangles have rotated counterclockwise.) */ -/* */ -/* WARNING: This transformation is geometrically valid only if the */ -/* quadrilateral adbc is convex. Furthermore, this transformation is */ -/* valid only if there is not a shell edge between the triangles abc and */ -/* bad. This routine does not check either of these preconditions, and */ -/* it is the responsibility of the calling routine to ensure that they are */ -/* met. If they are not, the streets shall be filled with wailing and */ -/* gnashing of teeth. */ -/* */ -/*****************************************************************************/ - -void flip(flipedge) -struct triedge *flipedge; /* Handle for the triangle abc. */ -{ - struct triedge botleft, botright; - struct triedge topleft, topright; - struct triedge top; - struct triedge botlcasing, botrcasing; - struct triedge toplcasing, toprcasing; - struct edge botlshelle, botrshelle; - struct edge toplshelle, toprshelle; - point leftpoint, rightpoint, botpoint; - point farpoint; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - /* Identify the vertices of the quadrilateral. */ - org(*flipedge, rightpoint); - dest(*flipedge, leftpoint); - apex(*flipedge, botpoint); - sym(*flipedge, top); -#ifdef SELF_CHECK - if (top.tri == dummytri) { - printf("Internal error in flip(): Attempt to flip on boundary.\n"); - lnextself(*flipedge); - return; - } - if (checksegments) { - tspivot(*flipedge, toplshelle); - if (toplshelle.sh != dummysh) { - printf("Internal error in flip(): Attempt to flip a segment.\n"); - lnextself(*flipedge); - return; - } - } -#endif /* SELF_CHECK */ - apex(top, farpoint); - - /* Identify the casing of the quadrilateral. */ - lprev(top, topleft); - sym(topleft, toplcasing); - lnext(top, topright); - sym(topright, toprcasing); - lnext(*flipedge, botleft); - sym(botleft, botlcasing); - lprev(*flipedge, botright); - sym(botright, botrcasing); - /* Rotate the quadrilateral one-quarter turn counterclockwise. */ - bond(topleft, botlcasing); - bond(botleft, botrcasing); - bond(botright, toprcasing); - bond(topright, toplcasing); - - if (checksegments) { - /* Check for shell edges and rebond them to the quadrilateral. */ - tspivot(topleft, toplshelle); - tspivot(botleft, botlshelle); - tspivot(botright, botrshelle); - tspivot(topright, toprshelle); - if (toplshelle.sh == dummysh) { - tsdissolve(topright); - } else { - tsbond(topright, toplshelle); - } - if (botlshelle.sh == dummysh) { - tsdissolve(topleft); - } else { - tsbond(topleft, botlshelle); - } - if (botrshelle.sh == dummysh) { - tsdissolve(botleft); - } else { - tsbond(botleft, botrshelle); - } - if (toprshelle.sh == dummysh) { - tsdissolve(botright); - } else { - tsbond(botright, toprshelle); - } - } - - /* New point assignments for the rotated quadrilateral. */ - setorg(*flipedge, farpoint); - setdest(*flipedge, botpoint); - setapex(*flipedge, rightpoint); - setorg(top, botpoint); - setdest(top, farpoint); - setapex(top, leftpoint); - if (verbose > 2) { - printf(" Edge flip results in left "); - lnextself(topleft); - printtriangle(&topleft); - printf(" and right "); - printtriangle(flipedge); - } -} - -/*****************************************************************************/ -/* */ -/* insertsite() Insert a vertex into a Delaunay triangulation, */ -/* performing flips as necessary to maintain the Delaunay */ -/* property. */ -/* */ -/* The point `insertpoint' is located. If `searchtri.tri' is not NULL, */ -/* the search for the containing triangle begins from `searchtri'. If */ -/* `searchtri.tri' is NULL, a full point location procedure is called. */ -/* If `insertpoint' is found inside a triangle, the triangle is split into */ -/* three; if `insertpoint' lies on an edge, the edge is split in two, */ -/* thereby splitting the two adjacent triangles into four. Edge flips are */ -/* used to restore the Delaunay property. If `insertpoint' lies on an */ -/* existing vertex, no action is taken, and the value DUPLICATEPOINT is */ -/* returned. On return, `searchtri' is set to a handle whose origin is the */ -/* existing vertex. */ -/* */ -/* Normally, the parameter `splitedge' is set to NULL, implying that no */ -/* segment should be split. In this case, if `insertpoint' is found to */ -/* lie on a segment, no action is taken, and the value VIOLATINGPOINT is */ -/* returned. On return, `searchtri' is set to a handle whose primary edge */ -/* is the violated segment. */ -/* */ -/* If the calling routine wishes to split a segment by inserting a point in */ -/* it, the parameter `splitedge' should be that segment. In this case, */ -/* `searchtri' MUST be the triangle handle reached by pivoting from that */ -/* segment; no point location is done. */ -/* */ -/* `segmentflaws' and `triflaws' are flags that indicate whether or not */ -/* there should be checks for the creation of encroached segments or bad */ -/* quality faces. If a newly inserted point encroaches upon segments, */ -/* these segments are added to the list of segments to be split if */ -/* `segmentflaws' is set. If bad triangles are created, these are added */ -/* to the queue if `triflaws' is set. */ -/* */ -/* If a duplicate point or violated segment does not prevent the point */ -/* from being inserted, the return value will be ENCROACHINGPOINT if the */ -/* point encroaches upon a segment (and checking is enabled), or */ -/* SUCCESSFULPOINT otherwise. In either case, `searchtri' is set to a */ -/* handle whose origin is the newly inserted vertex. */ -/* */ -/* insertsite() does not use flip() for reasons of speed; some */ -/* information can be reused from edge flip to edge flip, like the */ -/* locations of shell edges. */ -/* */ -/*****************************************************************************/ - -enum insertsiteresult insertsite(insertpoint, searchtri, splitedge, - segmentflaws, triflaws) -point insertpoint; -struct triedge *searchtri; -struct edge *splitedge; -int segmentflaws; -int triflaws; -{ - struct triedge horiz; - struct triedge top; - struct triedge botleft, botright; - struct triedge topleft, topright; - struct triedge newbotleft, newbotright; - struct triedge newtopright; - struct triedge botlcasing, botrcasing; - struct triedge toplcasing, toprcasing; - struct triedge testtri; - struct edge botlshelle, botrshelle; - struct edge toplshelle, toprshelle; - struct edge brokenshelle; - struct edge checkshelle; - struct edge rightedge; - struct edge newedge; - struct edge *encroached; - point first; - point leftpoint, rightpoint, botpoint, toppoint, farpoint; - REAL attrib; - REAL area; - enum insertsiteresult success; - enum locateresult intersect; - int doflip; - int mirrorflag; - int i; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by spivot() and tspivot(). */ - - if (verbose > 1) { - printf(" Inserting (%.12g, %.12g).\n", insertpoint[0], insertpoint[1]); - } - if (splitedge == (struct edge *) NULL) { - /* Find the location of the point to be inserted. Check if a good */ - /* starting triangle has already been provided by the caller. */ - if (searchtri->tri == (triangle *) NULL) { - /* Find a boundary triangle. */ - horiz.tri = dummytri; - horiz.orient = 0; - symself(horiz); - /* Search for a triangle containing `insertpoint'. */ - intersect = locate(insertpoint, &horiz); - } else { - /* Start searching from the triangle provided by the caller. */ - triedgecopy(*searchtri, horiz); - intersect = preciselocate(insertpoint, &horiz); - } - } else { - /* The calling routine provides the edge in which the point is inserted. */ - triedgecopy(*searchtri, horiz); - intersect = ONEDGE; - } - if (intersect == ONVERTEX) { - /* There's already a vertex there. Return in `searchtri' a triangle */ - /* whose origin is the existing vertex. */ - triedgecopy(horiz, *searchtri); - triedgecopy(horiz, recenttri); - return DUPLICATEPOINT; - } - if ((intersect == ONEDGE) || (intersect == OUTSIDE)) { - /* The vertex falls on an edge or boundary. */ - if (checksegments && (splitedge == (struct edge *) NULL)) { - /* Check whether the vertex falls on a shell edge. */ - tspivot(horiz, brokenshelle); - if (brokenshelle.sh != dummysh) { - /* The vertex falls on a shell edge. */ - if (segmentflaws) { - if (nobisect == 0) { - /* Add the shell edge to the list of encroached segments. */ - encroached = (struct edge *) poolalloc(&badsegments); - shellecopy(brokenshelle, *encroached); - } else if ((nobisect == 1) && (intersect == ONEDGE)) { - /* This segment may be split only if it is an internal boundary. */ - sym(horiz, testtri); - if (testtri.tri != dummytri) { - /* Add the shell edge to the list of encroached segments. */ - encroached = (struct edge *) poolalloc(&badsegments); - shellecopy(brokenshelle, *encroached); - } - } - } - /* Return a handle whose primary edge contains the point, */ - /* which has not been inserted. */ - triedgecopy(horiz, *searchtri); - triedgecopy(horiz, recenttri); - return VIOLATINGPOINT; - } - } - /* Insert the point on an edge, dividing one triangle into two (if */ - /* the edge lies on a boundary) or two triangles into four. */ - lprev(horiz, botright); - sym(botright, botrcasing); - sym(horiz, topright); - /* Is there a second triangle? (Or does this edge lie on a boundary?) */ - mirrorflag = topright.tri != dummytri; - if (mirrorflag) { - lnextself(topright); - sym(topright, toprcasing); - maketriangle(&newtopright); - } else { - /* Splitting the boundary edge increases the number of boundary edges. */ - hullsize++; - } - maketriangle(&newbotright); - - /* Set the vertices of changed and new triangles. */ - org(horiz, rightpoint); - dest(horiz, leftpoint); - apex(horiz, botpoint); - setorg(newbotright, botpoint); - setdest(newbotright, rightpoint); - setapex(newbotright, insertpoint); - setorg(horiz, insertpoint); - for (i = 0; i < eextras; i++) { - /* Set the element attributes of a new triangle. */ - setelemattribute(newbotright, i, elemattribute(botright, i)); - } - if (vararea) { - /* Set the area constraint of a new triangle. */ - setareabound(newbotright, areabound(botright)); - } - if (mirrorflag) { - dest(topright, toppoint); - setorg(newtopright, rightpoint); - setdest(newtopright, toppoint); - setapex(newtopright, insertpoint); - setorg(topright, insertpoint); - for (i = 0; i < eextras; i++) { - /* Set the element attributes of another new triangle. */ - setelemattribute(newtopright, i, elemattribute(topright, i)); - } - if (vararea) { - /* Set the area constraint of another new triangle. */ - setareabound(newtopright, areabound(topright)); - } - } - - /* There may be shell edges that need to be bonded */ - /* to the new triangle(s). */ - if (checksegments) { - tspivot(botright, botrshelle); - if (botrshelle.sh != dummysh) { - tsdissolve(botright); - tsbond(newbotright, botrshelle); - } - if (mirrorflag) { - tspivot(topright, toprshelle); - if (toprshelle.sh != dummysh) { - tsdissolve(topright); - tsbond(newtopright, toprshelle); - } - } - } - - /* Bond the new triangle(s) to the surrounding triangles. */ - bond(newbotright, botrcasing); - lprevself(newbotright); - bond(newbotright, botright); - lprevself(newbotright); - if (mirrorflag) { - bond(newtopright, toprcasing); - lnextself(newtopright); - bond(newtopright, topright); - lnextself(newtopright); - bond(newtopright, newbotright); - } - - if (splitedge != (struct edge *) NULL) { - /* Split the shell edge into two. */ - setsdest(*splitedge, insertpoint); - ssymself(*splitedge); - spivot(*splitedge, rightedge); - insertshelle(&newbotright, mark(*splitedge)); - tspivot(newbotright, newedge); - sbond(*splitedge, newedge); - ssymself(newedge); - sbond(newedge, rightedge); - ssymself(*splitedge); - } - -#ifdef SELF_CHECK - if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to edge point insertion (bottom).\n"); - } - if (mirrorflag) { - if (counterclockwise(leftpoint, rightpoint, toppoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to edge point insertion (top).\n"); - } - if (counterclockwise(rightpoint, toppoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge point insertion (top right).\n" - ); - } - if (counterclockwise(toppoint, leftpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge point insertion (top left).\n" - ); - } - } - if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge point insertion (bottom left).\n" - ); - } - if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf( - " Clockwise triangle after edge point insertion (bottom right).\n"); - } -#endif /* SELF_CHECK */ - if (verbose > 2) { - printf(" Updating bottom left "); - printtriangle(&botright); - if (mirrorflag) { - printf(" Updating top left "); - printtriangle(&topright); - printf(" Creating top right "); - printtriangle(&newtopright); - } - printf(" Creating bottom right "); - printtriangle(&newbotright); - } - - /* Position `horiz' on the first edge to check for */ - /* the Delaunay property. */ - lnextself(horiz); - } else { - /* Insert the point in a triangle, splitting it into three. */ - lnext(horiz, botleft); - lprev(horiz, botright); - sym(botleft, botlcasing); - sym(botright, botrcasing); - maketriangle(&newbotleft); - maketriangle(&newbotright); - - /* Set the vertices of changed and new triangles. */ - org(horiz, rightpoint); - dest(horiz, leftpoint); - apex(horiz, botpoint); - setorg(newbotleft, leftpoint); - setdest(newbotleft, botpoint); - setapex(newbotleft, insertpoint); - setorg(newbotright, botpoint); - setdest(newbotright, rightpoint); - setapex(newbotright, insertpoint); - setapex(horiz, insertpoint); - for (i = 0; i < eextras; i++) { - /* Set the element attributes of the new triangles. */ - attrib = elemattribute(horiz, i); - setelemattribute(newbotleft, i, attrib); - setelemattribute(newbotright, i, attrib); - } - if (vararea) { - /* Set the area constraint of the new triangles. */ - area = areabound(horiz); - setareabound(newbotleft, area); - setareabound(newbotright, area); - } - - /* There may be shell edges that need to be bonded */ - /* to the new triangles. */ - if (checksegments) { - tspivot(botleft, botlshelle); - if (botlshelle.sh != dummysh) { - tsdissolve(botleft); - tsbond(newbotleft, botlshelle); - } - tspivot(botright, botrshelle); - if (botrshelle.sh != dummysh) { - tsdissolve(botright); - tsbond(newbotright, botrshelle); - } - } - - /* Bond the new triangles to the surrounding triangles. */ - bond(newbotleft, botlcasing); - bond(newbotright, botrcasing); - lnextself(newbotleft); - lprevself(newbotright); - bond(newbotleft, newbotright); - lnextself(newbotleft); - bond(botleft, newbotleft); - lprevself(newbotright); - bond(botright, newbotright); - -#ifdef SELF_CHECK - if (counterclockwise(rightpoint, leftpoint, botpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to point insertion.\n"); - } - if (counterclockwise(rightpoint, leftpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after point insertion (top).\n"); - } - if (counterclockwise(leftpoint, botpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after point insertion (left).\n"); - } - if (counterclockwise(botpoint, rightpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after point insertion (right).\n"); - } -#endif /* SELF_CHECK */ - if (verbose > 2) { - printf(" Updating top "); - printtriangle(&horiz); - printf(" Creating left "); - printtriangle(&newbotleft); - printf(" Creating right "); - printtriangle(&newbotright); - } - } - - /* The insertion is successful by default, unless an encroached */ - /* edge is found. */ - success = SUCCESSFULPOINT; - /* Circle around the newly inserted vertex, checking each edge opposite */ - /* it for the Delaunay property. Non-Delaunay edges are flipped. */ - /* `horiz' is always the edge being checked. `first' marks where to */ - /* stop circling. */ - org(horiz, first); - rightpoint = first; - dest(horiz, leftpoint); - /* Circle until finished. */ - while (1) { - /* By default, the edge will be flipped. */ - doflip = 1; - if (checksegments) { - /* Check for a segment, which cannot be flipped. */ - tspivot(horiz, checkshelle); - if (checkshelle.sh != dummysh) { - /* The edge is a segment and cannot be flipped. */ - doflip = 0; -#ifndef CDT_ONLY - if (segmentflaws) { - /* Does the new point encroach upon this segment? */ - if (checkedge4encroach(&checkshelle)) { - success = ENCROACHINGPOINT; - } - } -#endif /* not CDT_ONLY */ - } - } - if (doflip) { - /* Check if the edge is a boundary edge. */ - sym(horiz, top); - if (top.tri == dummytri) { - /* The edge is a boundary edge and cannot be flipped. */ - doflip = 0; - } else { - /* Find the point on the other side of the edge. */ - apex(top, farpoint); - /* In the incremental Delaunay triangulation algorithm, any of */ - /* `leftpoint', `rightpoint', and `farpoint' could be vertices */ - /* of the triangular bounding box. These vertices must be */ - /* treated as if they are infinitely distant, even though their */ - /* "coordinates" are not. */ - if ((leftpoint == infpoint1) || (leftpoint == infpoint2) - || (leftpoint == infpoint3)) { - /* `leftpoint' is infinitely distant. Check the convexity of */ - /* the boundary of the triangulation. 'farpoint' might be */ - /* infinite as well, but trust me, this same condition */ - /* should be applied. */ - doflip = counterclockwise(insertpoint, rightpoint, farpoint) > 0.0; - } else if ((rightpoint == infpoint1) || (rightpoint == infpoint2) - || (rightpoint == infpoint3)) { - /* `rightpoint' is infinitely distant. Check the convexity of */ - /* the boundary of the triangulation. 'farpoint' might be */ - /* infinite as well, but trust me, this same condition */ - /* should be applied. */ - doflip = counterclockwise(farpoint, leftpoint, insertpoint) > 0.0; - } else if ((farpoint == infpoint1) || (farpoint == infpoint2) - || (farpoint == infpoint3)) { - /* `farpoint' is infinitely distant and cannot be inside */ - /* the circumcircle of the triangle `horiz'. */ - doflip = 0; - } else { - /* Test whether the edge is locally Delaunay. */ - doflip = incircle(leftpoint, insertpoint, rightpoint, farpoint) - > 0.0; - } - if (doflip) { - /* We made it! Flip the edge `horiz' by rotating its containing */ - /* quadrilateral (the two triangles adjacent to `horiz'). */ - /* Identify the casing of the quadrilateral. */ - lprev(top, topleft); - sym(topleft, toplcasing); - lnext(top, topright); - sym(topright, toprcasing); - lnext(horiz, botleft); - sym(botleft, botlcasing); - lprev(horiz, botright); - sym(botright, botrcasing); - /* Rotate the quadrilateral one-quarter turn counterclockwise. */ - bond(topleft, botlcasing); - bond(botleft, botrcasing); - bond(botright, toprcasing); - bond(topright, toplcasing); - if (checksegments) { - /* Check for shell edges and rebond them to the quadrilateral. */ - tspivot(topleft, toplshelle); - tspivot(botleft, botlshelle); - tspivot(botright, botrshelle); - tspivot(topright, toprshelle); - if (toplshelle.sh == dummysh) { - tsdissolve(topright); - } else { - tsbond(topright, toplshelle); - } - if (botlshelle.sh == dummysh) { - tsdissolve(topleft); - } else { - tsbond(topleft, botlshelle); - } - if (botrshelle.sh == dummysh) { - tsdissolve(botleft); - } else { - tsbond(botleft, botrshelle); - } - if (toprshelle.sh == dummysh) { - tsdissolve(botright); - } else { - tsbond(botright, toprshelle); - } - } - /* New point assignments for the rotated quadrilateral. */ - setorg(horiz, farpoint); - setdest(horiz, insertpoint); - setapex(horiz, rightpoint); - setorg(top, insertpoint); - setdest(top, farpoint); - setapex(top, leftpoint); - for (i = 0; i < eextras; i++) { - /* Take the average of the two triangles' attributes. */ - attrib = (REAL)(0.5 * (elemattribute(top, i) + elemattribute(horiz, i))); - setelemattribute(top, i, attrib); - setelemattribute(horiz, i, attrib); - } - if (vararea) { - if ((areabound(top) <= 0.0) || (areabound(horiz) <= 0.0)) { - area = -1.0; - } else { - /* Take the average of the two triangles' area constraints. */ - /* This prevents small area constraints from migrating a */ - /* long, long way from their original location due to flips. */ - area = (REAL)(0.5 * (areabound(top) + areabound(horiz))); - } - setareabound(top, area); - setareabound(horiz, area); - } -#ifdef SELF_CHECK - if (insertpoint != (point) NULL) { - if (counterclockwise(leftpoint, insertpoint, rightpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to edge flip (bottom).\n"); - } - /* The following test has been removed because constrainededge() */ - /* sometimes generates inverted triangles that insertsite() */ - /* removes. */ -/* - if (counterclockwise(rightpoint, farpoint, leftpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle prior to edge flip (top).\n"); - } -*/ - if (counterclockwise(farpoint, leftpoint, insertpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge flip (left).\n"); - } - if (counterclockwise(insertpoint, rightpoint, farpoint) < 0.0) { - printf("Internal error in insertsite():\n"); - printf(" Clockwise triangle after edge flip (right).\n"); - } - } -#endif /* SELF_CHECK */ - if (verbose > 2) { - printf(" Edge flip results in left "); - lnextself(topleft); - printtriangle(&topleft); - printf(" and right "); - printtriangle(&horiz); - } - /* On the next iterations, consider the two edges that were */ - /* exposed (this is, are now visible to the newly inserted */ - /* point) by the edge flip. */ - lprevself(horiz); - leftpoint = farpoint; - } - } - } - if (!doflip) { - /* The handle `horiz' is accepted as locally Delaunay. */ -#ifndef CDT_ONLY - if (triflaws) { - /* Check the triangle `horiz' for quality. */ - testtriangle(&horiz); - } -#endif /* not CDT_ONLY */ - /* Look for the next edge around the newly inserted point. */ - lnextself(horiz); - sym(horiz, testtri); - /* Check for finishing a complete revolution about the new point, or */ - /* falling off the edge of the triangulation. The latter will */ - /* happen when a point is inserted at a boundary. */ - if ((leftpoint == first) || (testtri.tri == dummytri)) { - /* We're done. Return a triangle whose origin is the new point. */ - lnext(horiz, *searchtri); - lnext(horiz, recenttri); - return success; - } - /* Finish finding the next edge around the newly inserted point. */ - lnext(testtri, horiz); - rightpoint = leftpoint; - dest(horiz, leftpoint); - } - } -} - -/*****************************************************************************/ -/* */ -/* triangulatepolygon() Find the Delaunay triangulation of a polygon that */ -/* has a certain "nice" shape. This includes the */ -/* polygons that result from deletion of a point or */ -/* insertion of a segment. */ -/* */ -/* This is a conceptually difficult routine. The starting assumption is */ -/* that we have a polygon with n sides. n - 1 of these sides are currently */ -/* represented as edges in the mesh. One side, called the "base", need not */ -/* be. */ -/* */ -/* Inside the polygon is a structure I call a "fan", consisting of n - 1 */ -/* triangles that share a common origin. For each of these triangles, the */ -/* edge opposite the origin is one of the sides of the polygon. The */ -/* primary edge of each triangle is the edge directed from the origin to */ -/* the destination; note that this is not the same edge that is a side of */ -/* the polygon. `firstedge' is the primary edge of the first triangle. */ -/* From there, the triangles follow in counterclockwise order about the */ -/* polygon, until `lastedge', the primary edge of the last triangle. */ -/* `firstedge' and `lastedge' are probably connected to other triangles */ -/* beyond the extremes of the fan, but their identity is not important, as */ -/* long as the fan remains connected to them. */ -/* */ -/* Imagine the polygon oriented so that its base is at the bottom. This */ -/* puts `firstedge' on the far right, and `lastedge' on the far left. */ -/* The right vertex of the base is the destination of `firstedge', and the */ -/* left vertex of the base is the apex of `lastedge'. */ -/* */ -/* The challenge now is to find the right sequence of edge flips to */ -/* transform the fan into a Delaunay triangulation of the polygon. Each */ -/* edge flip effectively removes one triangle from the fan, committing it */ -/* to the polygon. The resulting polygon has one fewer edge. If `doflip' */ -/* is set, the final flip will be performed, resulting in a fan of one */ -/* (useless?) triangle. If `doflip' is not set, the final flip is not */ -/* performed, resulting in a fan of two triangles, and an unfinished */ -/* triangular polygon that is not yet filled out with a single triangle. */ -/* On completion of the routine, `lastedge' is the last remaining triangle, */ -/* or the leftmost of the last two. */ -/* */ -/* Although the flips are performed in the order described above, the */ -/* decisions about what flips to perform are made in precisely the reverse */ -/* order. The recursive triangulatepolygon() procedure makes a decision, */ -/* uses up to two recursive calls to triangulate the "subproblems" */ -/* (polygons with fewer edges), and then performs an edge flip. */ -/* */ -/* The "decision" it makes is which vertex of the polygon should be */ -/* connected to the base. This decision is made by testing every possible */ -/* vertex. Once the best vertex is found, the two edges that connect this */ -/* vertex to the base become the bases for two smaller polygons. These */ -/* are triangulated recursively. Unfortunately, this approach can take */ -/* O(n^2) time not only in the worst case, but in many common cases. It's */ -/* rarely a big deal for point deletion, where n is rarely larger than ten, */ -/* but it could be a big deal for segment insertion, especially if there's */ -/* a lot of long segments that each cut many triangles. I ought to code */ -/* a faster algorithm some time. */ -/* */ -/* The `edgecount' parameter is the number of sides of the polygon, */ -/* including its base. `triflaws' is a flag that determines whether the */ -/* new triangles should be tested for quality, and enqueued if they are */ -/* bad. */ -/* */ -/*****************************************************************************/ - -void triangulatepolygon(firstedge, lastedge, edgecount, doflip, triflaws) -struct triedge *firstedge; -struct triedge *lastedge; -int edgecount; -int doflip; -int triflaws; -{ - struct triedge testtri; - struct triedge besttri; - struct triedge tempedge; - point leftbasepoint, rightbasepoint; - point testpoint; - point bestpoint; - int bestnumber; - int i; - triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ - - /* Identify the base vertices. */ - apex(*lastedge, leftbasepoint); - dest(*firstedge, rightbasepoint); - if (verbose > 2) { - printf(" Triangulating interior polygon at edge\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g)\n", leftbasepoint[0], - leftbasepoint[1], rightbasepoint[0], rightbasepoint[1]); - } - /* Find the best vertex to connect the base to. */ - onext(*firstedge, besttri); - dest(besttri, bestpoint); - triedgecopy(besttri, testtri); - bestnumber = 1; - for (i = 2; i <= edgecount - 2; i++) { - onextself(testtri); - dest(testtri, testpoint); - /* Is this a better vertex? */ - if (incircle(leftbasepoint, rightbasepoint, bestpoint, testpoint) > 0.0) { - triedgecopy(testtri, besttri); - bestpoint = testpoint; - bestnumber = i; - } - } - if (verbose > 2) { - printf(" Connecting edge to (%.12g, %.12g)\n", bestpoint[0], - bestpoint[1]); - } - if (bestnumber > 1) { - /* Recursively triangulate the smaller polygon on the right. */ - oprev(besttri, tempedge); - triangulatepolygon(firstedge, &tempedge, bestnumber + 1, 1, triflaws); - } - if (bestnumber < edgecount - 2) { - /* Recursively triangulate the smaller polygon on the left. */ - sym(besttri, tempedge); - triangulatepolygon(&besttri, lastedge, edgecount - bestnumber, 1, - triflaws); - /* Find `besttri' again; it may have been lost to edge flips. */ - sym(tempedge, besttri); - } - if (doflip) { - /* Do one final edge flip. */ - flip(&besttri); -#ifndef CDT_ONLY - if (triflaws) { - /* Check the quality of the newly committed triangle. */ - sym(besttri, testtri); - testtriangle(&testtri); - } -#endif /* not CDT_ONLY */ - } - /* Return the base triangle. */ - triedgecopy(besttri, *lastedge); -} - -/*****************************************************************************/ -/* */ -/* deletesite() Delete a vertex from a Delaunay triangulation, ensuring */ -/* that the triangulation remains Delaunay. */ -/* */ -/* The origin of `deltri' is deleted. The union of the triangles adjacent */ -/* to this point is a polygon, for which the Delaunay triangulation is */ -/* found. Two triangles are removed from the mesh. */ -/* */ -/* Only interior points that do not lie on segments (shell edges) or */ -/* boundaries may be deleted. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void deletesite(deltri) -struct triedge *deltri; -{ - struct triedge countingtri; - struct triedge firstedge, lastedge; - struct triedge deltriright; - struct triedge lefttri, righttri; - struct triedge leftcasing, rightcasing; - struct edge leftshelle, rightshelle; - point delpoint; - point neworg; - int edgecount; - triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - org(*deltri, delpoint); - if (verbose > 1) { - printf(" Deleting (%.12g, %.12g).\n", delpoint[0], delpoint[1]); - } - pointdealloc(delpoint); - - /* Count the degree of the point being deleted. */ - onext(*deltri, countingtri); - edgecount = 1; - while (!triedgeequal(*deltri, countingtri)) { -#ifdef SELF_CHECK - if (countingtri.tri == dummytri) { - printf("Internal error in deletesite():\n"); - printf(" Attempt to delete boundary point.\n"); - internalerror(); - } -#endif /* SELF_CHECK */ - edgecount++; - onextself(countingtri); - } - -#ifdef SELF_CHECK - if (edgecount < 3) { - printf("Internal error in deletesite():\n Point has degree %d.\n", - edgecount); - internalerror(); - } -#endif /* SELF_CHECK */ - if (edgecount > 3) { - /* Triangulate the polygon defined by the union of all triangles */ - /* adjacent to the point being deleted. Check the quality of */ - /* the resulting triangles. */ - onext(*deltri, firstedge); - oprev(*deltri, lastedge); - triangulatepolygon(&firstedge, &lastedge, edgecount, 0, !nobisect); - } - /* Splice out two triangles. */ - lprev(*deltri, deltriright); - dnext(*deltri, lefttri); - sym(lefttri, leftcasing); - oprev(deltriright, righttri); - sym(righttri, rightcasing); - bond(*deltri, leftcasing); - bond(deltriright, rightcasing); - tspivot(lefttri, leftshelle); - if (leftshelle.sh != dummysh) { - tsbond(*deltri, leftshelle); - } - tspivot(righttri, rightshelle); - if (rightshelle.sh != dummysh) { - tsbond(deltriright, rightshelle); - } - - /* Set the new origin of `deltri' and check its quality. */ - org(lefttri, neworg); - setorg(*deltri, neworg); - if (!nobisect) { - testtriangle(deltri); - } - - /* Delete the two spliced-out triangles. */ - triangledealloc(lefttri.tri); - triangledealloc(righttri.tri); -} - -#endif /* not CDT_ONLY */ - -/** **/ -/** **/ -/********* Mesh transformation routines end here *********/ - -/********* Divide-and-conquer Delaunay triangulation begins here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* The divide-and-conquer bounding box */ -/* */ -/* I originally implemented the divide-and-conquer and incremental Delaunay */ -/* triangulations using the edge-based data structure presented by Guibas */ -/* and Stolfi. Switching to a triangle-based data structure doubled the */ -/* speed. However, I had to think of a few extra tricks to maintain the */ -/* elegance of the original algorithms. */ -/* */ -/* The "bounding box" used by my variant of the divide-and-conquer */ -/* algorithm uses one triangle for each edge of the convex hull of the */ -/* triangulation. These bounding triangles all share a common apical */ -/* vertex, which is represented by NULL and which represents nothing. */ -/* The bounding triangles are linked in a circular fan about this NULL */ -/* vertex, and the edges on the convex hull of the triangulation appear */ -/* opposite the NULL vertex. You might find it easiest to imagine that */ -/* the NULL vertex is a point in 3D space behind the center of the */ -/* triangulation, and that the bounding triangles form a sort of cone. */ -/* */ -/* This bounding box makes it easy to represent degenerate cases. For */ -/* instance, the triangulation of two vertices is a single edge. This edge */ -/* is represented by two bounding box triangles, one on each "side" of the */ -/* edge. These triangles are also linked together in a fan about the NULL */ -/* vertex. */ -/* */ -/* The bounding box also makes it easy to traverse the convex hull, as the */ -/* divide-and-conquer algorithm needs to do. */ -/* */ -/*****************************************************************************/ - -/*****************************************************************************/ -/* */ -/* pointsort() Sort an array of points by x-coordinate, using the */ -/* y-coordinate as a secondary key. */ -/* */ -/* Uses quicksort. Randomized O(n log n) time. No, I did not make any of */ -/* the usual quicksort mistakes. */ -/* */ -/*****************************************************************************/ - -void pointsort(sortarray, arraysize) -point *sortarray; -int arraysize; -{ - int left, right; - int pivot; - REAL pivotx, pivoty; - point temp; - - if (arraysize == 2) { - /* Recursive base case. */ - if ((sortarray[0][0] > sortarray[1][0]) || - ((sortarray[0][0] == sortarray[1][0]) && - (sortarray[0][1] > sortarray[1][1]))) { - temp = sortarray[1]; - sortarray[1] = sortarray[0]; - sortarray[0] = temp; - } - return; - } - /* Choose a random pivot to split the array. */ - pivot = (int) randomnation(arraysize); - pivotx = sortarray[pivot][0]; - pivoty = sortarray[pivot][1]; - /* Split the array. */ - left = -1; - right = arraysize; - while (left < right) { - /* Search for a point whose x-coordinate is too large for the left. */ - do { - left++; - } while ((left <= right) && ((sortarray[left][0] < pivotx) || - ((sortarray[left][0] == pivotx) && - (sortarray[left][1] < pivoty)))); - /* Search for a point whose x-coordinate is too small for the right. */ - do { - right--; - } while ((left <= right) && ((sortarray[right][0] > pivotx) || - ((sortarray[right][0] == pivotx) && - (sortarray[right][1] > pivoty)))); - if (left < right) { - /* Swap the left and right points. */ - temp = sortarray[left]; - sortarray[left] = sortarray[right]; - sortarray[right] = temp; - } - } - if (left > 1) { - /* Recursively sort the left subset. */ - pointsort(sortarray, left); - } - if (right < arraysize - 2) { - /* Recursively sort the right subset. */ - pointsort(&sortarray[right + 1], arraysize - right - 1); - } -} - -/*****************************************************************************/ -/* */ -/* pointmedian() An order statistic algorithm, almost. Shuffles an array */ -/* of points so that the first `median' points occur */ -/* lexicographically before the remaining points. */ -/* */ -/* Uses the x-coordinate as the primary key if axis == 0; the y-coordinate */ -/* if axis == 1. Very similar to the pointsort() procedure, but runs in */ -/* randomized linear time. */ -/* */ -/*****************************************************************************/ - -void pointmedian(sortarray, arraysize, median, axis) -point *sortarray; -int arraysize; -int median; -int axis; -{ - int left, right; - int pivot; - REAL pivot1, pivot2; - point temp; - - if (arraysize == 2) { - /* Recursive base case. */ - if ((sortarray[0][axis] > sortarray[1][axis]) || - ((sortarray[0][axis] == sortarray[1][axis]) && - (sortarray[0][1 - axis] > sortarray[1][1 - axis]))) { - temp = sortarray[1]; - sortarray[1] = sortarray[0]; - sortarray[0] = temp; - } - return; - } - /* Choose a random pivot to split the array. */ - pivot = (int) randomnation(arraysize); - pivot1 = sortarray[pivot][axis]; - pivot2 = sortarray[pivot][1 - axis]; - /* Split the array. */ - left = -1; - right = arraysize; - while (left < right) { - /* Search for a point whose x-coordinate is too large for the left. */ - do { - left++; - } while ((left <= right) && ((sortarray[left][axis] < pivot1) || - ((sortarray[left][axis] == pivot1) && - (sortarray[left][1 - axis] < pivot2)))); - /* Search for a point whose x-coordinate is too small for the right. */ - do { - right--; - } while ((left <= right) && ((sortarray[right][axis] > pivot1) || - ((sortarray[right][axis] == pivot1) && - (sortarray[right][1 - axis] > pivot2)))); - if (left < right) { - /* Swap the left and right points. */ - temp = sortarray[left]; - sortarray[left] = sortarray[right]; - sortarray[right] = temp; - } - } - /* Unlike in pointsort(), at most one of the following */ - /* conditionals is true. */ - if (left > median) { - /* Recursively shuffle the left subset. */ - pointmedian(sortarray, left, median, axis); - } - if (right < median - 1) { - /* Recursively shuffle the right subset. */ - pointmedian(&sortarray[right + 1], arraysize - right - 1, - median - right - 1, axis); - } -} - -/*****************************************************************************/ -/* */ -/* alternateaxes() Sorts the points as appropriate for the divide-and- */ -/* conquer algorithm with alternating cuts. */ -/* */ -/* Partitions by x-coordinate if axis == 0; by y-coordinate if axis == 1. */ -/* For the base case, subsets containing only two or three points are */ -/* always sorted by x-coordinate. */ -/* */ -/*****************************************************************************/ - -void alternateaxes(sortarray, arraysize, axis) -point *sortarray; -int arraysize; -int axis; -{ - int divider; - - divider = arraysize >> 1; - if (arraysize <= 3) { - /* Recursive base case: subsets of two or three points will be */ - /* handled specially, and should always be sorted by x-coordinate. */ - axis = 0; - } - /* Partition with a horizontal or vertical cut. */ - pointmedian(sortarray, arraysize, divider, axis); - /* Recursively partition the subsets with a cross cut. */ - if (arraysize - divider >= 2) { - if (divider >= 2) { - alternateaxes(sortarray, divider, 1 - axis); - } - alternateaxes(&sortarray[divider], arraysize - divider, 1 - axis); - } -} - -/*****************************************************************************/ -/* */ -/* mergehulls() Merge two adjacent Delaunay triangulations into a */ -/* single Delaunay triangulation. */ -/* */ -/* This is similar to the algorithm given by Guibas and Stolfi, but uses */ -/* a triangle-based, rather than edge-based, data structure. */ -/* */ -/* The algorithm walks up the gap between the two triangulations, knitting */ -/* them together. As they are merged, some of their bounding triangles */ -/* are converted into real triangles of the triangulation. The procedure */ -/* pulls each hull's bounding triangles apart, then knits them together */ -/* like the teeth of two gears. The Delaunay property determines, at each */ -/* step, whether the next "tooth" is a bounding triangle of the left hull */ -/* or the right. When a bounding triangle becomes real, its apex is */ -/* changed from NULL to a real point. */ -/* */ -/* Only two new triangles need to be allocated. These become new bounding */ -/* triangles at the top and bottom of the seam. They are used to connect */ -/* the remaining bounding triangles (those that have not been converted */ -/* into real triangles) into a single fan. */ -/* */ -/* On entry, `farleft' and `innerleft' are bounding triangles of the left */ -/* triangulation. The origin of `farleft' is the leftmost vertex, and */ -/* the destination of `innerleft' is the rightmost vertex of the */ -/* triangulation. Similarly, `innerright' and `farright' are bounding */ -/* triangles of the right triangulation. The origin of `innerright' and */ -/* destination of `farright' are the leftmost and rightmost vertices. */ -/* */ -/* On completion, the origin of `farleft' is the leftmost vertex of the */ -/* merged triangulation, and the destination of `farright' is the rightmost */ -/* vertex. */ -/* */ -/*****************************************************************************/ - -void mergehulls(farleft, innerleft, innerright, farright, axis) -struct triedge *farleft; -struct triedge *innerleft; -struct triedge *innerright; -struct triedge *farright; -int axis; -{ - struct triedge leftcand, rightcand; - struct triedge baseedge; - struct triedge nextedge; - struct triedge sidecasing, topcasing, outercasing; - struct triedge checkedge; - point innerleftdest; - point innerrightorg; - point innerleftapex, innerrightapex; - point farleftpt, farrightpt; - point farleftapex, farrightapex; - point lowerleft, lowerright; - point upperleft, upperright; - point nextapex; - point checkvertex; - int changemade; - int badedge; - int leftfinished, rightfinished; - triangle ptr; /* Temporary variable used by sym(). */ - - dest(*innerleft, innerleftdest); - apex(*innerleft, innerleftapex); - org(*innerright, innerrightorg); - apex(*innerright, innerrightapex); - /* Special treatment for horizontal cuts. */ - if (dwyer && (axis == 1)) { - org(*farleft, farleftpt); - apex(*farleft, farleftapex); - dest(*farright, farrightpt); - apex(*farright, farrightapex); - /* The pointers to the extremal points are shifted to point to the */ - /* topmost and bottommost point of each hull, rather than the */ - /* leftmost and rightmost points. */ - while (farleftapex[1] < farleftpt[1]) { - lnextself(*farleft); - symself(*farleft); - farleftpt = farleftapex; - apex(*farleft, farleftapex); - } - sym(*innerleft, checkedge); - apex(checkedge, checkvertex); - while (checkvertex[1] > innerleftdest[1]) { - lnext(checkedge, *innerleft); - innerleftapex = innerleftdest; - innerleftdest = checkvertex; - sym(*innerleft, checkedge); - apex(checkedge, checkvertex); - } - while (innerrightapex[1] < innerrightorg[1]) { - lnextself(*innerright); - symself(*innerright); - innerrightorg = innerrightapex; - apex(*innerright, innerrightapex); - } - sym(*farright, checkedge); - apex(checkedge, checkvertex); - while (checkvertex[1] > farrightpt[1]) { - lnext(checkedge, *farright); - farrightapex = farrightpt; - farrightpt = checkvertex; - sym(*farright, checkedge); - apex(checkedge, checkvertex); - } - } - /* Find a line tangent to and below both hulls. */ - do { - changemade = 0; - /* Make innerleftdest the "bottommost" point of the left hull. */ - if (counterclockwise(innerleftdest, innerleftapex, innerrightorg) > 0.0) { - lprevself(*innerleft); - symself(*innerleft); - innerleftdest = innerleftapex; - apex(*innerleft, innerleftapex); - changemade = 1; - } - /* Make innerrightorg the "bottommost" point of the right hull. */ - if (counterclockwise(innerrightapex, innerrightorg, innerleftdest) > 0.0) { - lnextself(*innerright); - symself(*innerright); - innerrightorg = innerrightapex; - apex(*innerright, innerrightapex); - changemade = 1; - } - } while (changemade); - /* Find the two candidates to be the next "gear tooth". */ - sym(*innerleft, leftcand); - sym(*innerright, rightcand); - /* Create the bottom new bounding triangle. */ - maketriangle(&baseedge); - /* Connect it to the bounding boxes of the left and right triangulations. */ - bond(baseedge, *innerleft); - lnextself(baseedge); - bond(baseedge, *innerright); - lnextself(baseedge); - setorg(baseedge, innerrightorg); - setdest(baseedge, innerleftdest); - /* Apex is intentionally left NULL. */ - if (verbose > 2) { - printf(" Creating base bounding "); - printtriangle(&baseedge); - } - /* Fix the extreme triangles if necessary. */ - org(*farleft, farleftpt); - if (innerleftdest == farleftpt) { - lnext(baseedge, *farleft); - } - dest(*farright, farrightpt); - if (innerrightorg == farrightpt) { - lprev(baseedge, *farright); - } - /* The vertices of the current knitting edge. */ - lowerleft = innerleftdest; - lowerright = innerrightorg; - /* The candidate vertices for knitting. */ - apex(leftcand, upperleft); - apex(rightcand, upperright); - /* Walk up the gap between the two triangulations, knitting them together. */ - while (1) { - /* Have we reached the top? (This isn't quite the right question, */ - /* because even though the left triangulation might seem finished now, */ - /* moving up on the right triangulation might reveal a new point of */ - /* the left triangulation. And vice-versa.) */ - leftfinished = counterclockwise(upperleft, lowerleft, lowerright) <= 0.0; - rightfinished = counterclockwise(upperright, lowerleft, lowerright) <= 0.0; - if (leftfinished && rightfinished) { - /* Create the top new bounding triangle. */ - maketriangle(&nextedge); - setorg(nextedge, lowerleft); - setdest(nextedge, lowerright); - /* Apex is intentionally left NULL. */ - /* Connect it to the bounding boxes of the two triangulations. */ - bond(nextedge, baseedge); - lnextself(nextedge); - bond(nextedge, rightcand); - lnextself(nextedge); - bond(nextedge, leftcand); - if (verbose > 2) { - printf(" Creating top bounding "); - printtriangle(&baseedge); - } - /* Special treatment for horizontal cuts. */ - if (dwyer && (axis == 1)) { - org(*farleft, farleftpt); - apex(*farleft, farleftapex); - dest(*farright, farrightpt); - apex(*farright, farrightapex); - sym(*farleft, checkedge); - apex(checkedge, checkvertex); - /* The pointers to the extremal points are restored to the leftmost */ - /* and rightmost points (rather than topmost and bottommost). */ - while (checkvertex[0] < farleftpt[0]) { - lprev(checkedge, *farleft); - farleftapex = farleftpt; - farleftpt = checkvertex; - sym(*farleft, checkedge); - apex(checkedge, checkvertex); - } - while (farrightapex[0] > farrightpt[0]) { - lprevself(*farright); - symself(*farright); - farrightpt = farrightapex; - apex(*farright, farrightapex); - } - } - return; - } - /* Consider eliminating edges from the left triangulation. */ - if (!leftfinished) { - /* What vertex would be exposed if an edge were deleted? */ - lprev(leftcand, nextedge); - symself(nextedge); - apex(nextedge, nextapex); - /* If nextapex is NULL, then no vertex would be exposed; the */ - /* triangulation would have been eaten right through. */ - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperleft, nextapex) > 0.0; - while (badedge) { - /* Eliminate the edge with an edge flip. As a result, the */ - /* left triangulation will have one more boundary triangle. */ - lnextself(nextedge); - sym(nextedge, topcasing); - lnextself(nextedge); - sym(nextedge, sidecasing); - bond(nextedge, topcasing); - bond(leftcand, sidecasing); - lnextself(leftcand); - sym(leftcand, outercasing); - lprevself(nextedge); - bond(nextedge, outercasing); - /* Correct the vertices to reflect the edge flip. */ - setorg(leftcand, lowerleft); - setdest(leftcand, NULL); - setapex(leftcand, nextapex); - setorg(nextedge, NULL); - setdest(nextedge, upperleft); - setapex(nextedge, nextapex); - /* Consider the newly exposed vertex. */ - upperleft = nextapex; - /* What vertex would be exposed if another edge were deleted? */ - triedgecopy(sidecasing, nextedge); - apex(nextedge, nextapex); - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperleft, nextapex) - > 0.0; - } else { - /* Avoid eating right through the triangulation. */ - badedge = 0; - } - } - } - } - /* Consider eliminating edges from the right triangulation. */ - if (!rightfinished) { - /* What vertex would be exposed if an edge were deleted? */ - lnext(rightcand, nextedge); - symself(nextedge); - apex(nextedge, nextapex); - /* If nextapex is NULL, then no vertex would be exposed; the */ - /* triangulation would have been eaten right through. */ - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperright, nextapex) > 0.0; - while (badedge) { - /* Eliminate the edge with an edge flip. As a result, the */ - /* right triangulation will have one more boundary triangle. */ - lprevself(nextedge); - sym(nextedge, topcasing); - lprevself(nextedge); - sym(nextedge, sidecasing); - bond(nextedge, topcasing); - bond(rightcand, sidecasing); - lprevself(rightcand); - sym(rightcand, outercasing); - lnextself(nextedge); - bond(nextedge, outercasing); - /* Correct the vertices to reflect the edge flip. */ - setorg(rightcand, NULL); - setdest(rightcand, lowerright); - setapex(rightcand, nextapex); - setorg(nextedge, upperright); - setdest(nextedge, NULL); - setapex(nextedge, nextapex); - /* Consider the newly exposed vertex. */ - upperright = nextapex; - /* What vertex would be exposed if another edge were deleted? */ - triedgecopy(sidecasing, nextedge); - apex(nextedge, nextapex); - if (nextapex != (point) NULL) { - /* Check whether the edge is Delaunay. */ - badedge = incircle(lowerleft, lowerright, upperright, nextapex) - > 0.0; - } else { - /* Avoid eating right through the triangulation. */ - badedge = 0; - } - } - } - } - if (leftfinished || (!rightfinished && - (incircle(upperleft, lowerleft, lowerright, upperright) > 0.0))) { - /* Knit the triangulations, adding an edge from `lowerleft' */ - /* to `upperright'. */ - bond(baseedge, rightcand); - lprev(rightcand, baseedge); - setdest(baseedge, lowerleft); - lowerright = upperright; - sym(baseedge, rightcand); - apex(rightcand, upperright); - } else { - /* Knit the triangulations, adding an edge from `upperleft' */ - /* to `lowerright'. */ - bond(baseedge, leftcand); - lnext(leftcand, baseedge); - setorg(baseedge, lowerright); - lowerleft = upperleft; - sym(baseedge, leftcand); - apex(leftcand, upperleft); - } - if (verbose > 2) { - printf(" Connecting "); - printtriangle(&baseedge); - } - } -} - -/*****************************************************************************/ -/* */ -/* divconqrecurse() Recursively form a Delaunay triangulation by the */ -/* divide-and-conquer method. */ -/* */ -/* Recursively breaks down the problem into smaller pieces, which are */ -/* knitted together by mergehulls(). The base cases (problems of two or */ -/* three points) are handled specially here. */ -/* */ -/* On completion, `farleft' and `farright' are bounding triangles such that */ -/* the origin of `farleft' is the leftmost vertex (breaking ties by */ -/* choosing the highest leftmost vertex), and the destination of */ -/* `farright' is the rightmost vertex (breaking ties by choosing the */ -/* lowest rightmost vertex). */ -/* */ -/*****************************************************************************/ - -void divconqrecurse(sortarray, vertices, axis, farleft, farright) -point *sortarray; -int vertices; -int axis; -struct triedge *farleft; -struct triedge *farright; -{ - struct triedge midtri, tri1, tri2, tri3; - struct triedge innerleft, innerright; - REAL area; - int divider; - - if (verbose > 2) { - printf(" Triangulating %d points.\n", vertices); - } - if (vertices == 2) { - /* The triangulation of two vertices is an edge. An edge is */ - /* represented by two bounding triangles. */ - maketriangle(farleft); - setorg(*farleft, sortarray[0]); - setdest(*farleft, sortarray[1]); - /* The apex is intentionally left NULL. */ - maketriangle(farright); - setorg(*farright, sortarray[1]); - setdest(*farright, sortarray[0]); - /* The apex is intentionally left NULL. */ - bond(*farleft, *farright); - lprevself(*farleft); - lnextself(*farright); - bond(*farleft, *farright); - lprevself(*farleft); - lnextself(*farright); - bond(*farleft, *farright); - if (verbose > 2) { - printf(" Creating "); - printtriangle(farleft); - printf(" Creating "); - printtriangle(farright); - } - /* Ensure that the origin of `farleft' is sortarray[0]. */ - lprev(*farright, *farleft); - return; - } else if (vertices == 3) { - /* The triangulation of three vertices is either a triangle (with */ - /* three bounding triangles) or two edges (with four bounding */ - /* triangles). In either case, four triangles are created. */ - maketriangle(&midtri); - maketriangle(&tri1); - maketriangle(&tri2); - maketriangle(&tri3); - area = counterclockwise(sortarray[0], sortarray[1], sortarray[2]); - if (area == 0.0) { - /* Three collinear points; the triangulation is two edges. */ - setorg(midtri, sortarray[0]); - setdest(midtri, sortarray[1]); - setorg(tri1, sortarray[1]); - setdest(tri1, sortarray[0]); - setorg(tri2, sortarray[2]); - setdest(tri2, sortarray[1]); - setorg(tri3, sortarray[1]); - setdest(tri3, sortarray[2]); - /* All apices are intentionally left NULL. */ - bond(midtri, tri1); - bond(tri2, tri3); - lnextself(midtri); - lprevself(tri1); - lnextself(tri2); - lprevself(tri3); - bond(midtri, tri3); - bond(tri1, tri2); - lnextself(midtri); - lprevself(tri1); - lnextself(tri2); - lprevself(tri3); - bond(midtri, tri1); - bond(tri2, tri3); - /* Ensure that the origin of `farleft' is sortarray[0]. */ - triedgecopy(tri1, *farleft); - /* Ensure that the destination of `farright' is sortarray[2]. */ - triedgecopy(tri2, *farright); - } else { - /* The three points are not collinear; the triangulation is one */ - /* triangle, namely `midtri'. */ - setorg(midtri, sortarray[0]); - setdest(tri1, sortarray[0]); - setorg(tri3, sortarray[0]); - /* Apices of tri1, tri2, and tri3 are left NULL. */ - if (area > 0.0) { - /* The vertices are in counterclockwise order. */ - setdest(midtri, sortarray[1]); - setorg(tri1, sortarray[1]); - setdest(tri2, sortarray[1]); - setapex(midtri, sortarray[2]); - setorg(tri2, sortarray[2]); - setdest(tri3, sortarray[2]); - } else { - /* The vertices are in clockwise order. */ - setdest(midtri, sortarray[2]); - setorg(tri1, sortarray[2]); - setdest(tri2, sortarray[2]); - setapex(midtri, sortarray[1]); - setorg(tri2, sortarray[1]); - setdest(tri3, sortarray[1]); - } - /* The topology does not depend on how the vertices are ordered. */ - bond(midtri, tri1); - lnextself(midtri); - bond(midtri, tri2); - lnextself(midtri); - bond(midtri, tri3); - lprevself(tri1); - lnextself(tri2); - bond(tri1, tri2); - lprevself(tri1); - lprevself(tri3); - bond(tri1, tri3); - lnextself(tri2); - lprevself(tri3); - bond(tri2, tri3); - /* Ensure that the origin of `farleft' is sortarray[0]. */ - triedgecopy(tri1, *farleft); - /* Ensure that the destination of `farright' is sortarray[2]. */ - if (area > 0.0) { - triedgecopy(tri2, *farright); - } else { - lnext(*farleft, *farright); - } - } - if (verbose > 2) { - printf(" Creating "); - printtriangle(&midtri); - printf(" Creating "); - printtriangle(&tri1); - printf(" Creating "); - printtriangle(&tri2); - printf(" Creating "); - printtriangle(&tri3); - } - return; - } else { - /* Split the vertices in half. */ - divider = vertices >> 1; - /* Recursively triangulate each half. */ - divconqrecurse(sortarray, divider, 1 - axis, farleft, &innerleft); - divconqrecurse(&sortarray[divider], vertices - divider, 1 - axis, - &innerright, farright); - if (verbose > 1) { - printf(" Joining triangulations with %d and %d vertices.\n", divider, - vertices - divider); - } - /* Merge the two triangulations into one. */ - mergehulls(farleft, &innerleft, &innerright, farright, axis); - } -} - -long removeghosts(startghost) -struct triedge *startghost; -{ - struct triedge searchedge; - struct triedge dissolveedge; - struct triedge deadtri; - point markorg; - long hullsize; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose) { - printf(" Removing ghost triangles.\n"); - } - /* Find an edge on the convex hull to start point location from. */ - lprev(*startghost, searchedge); - symself(searchedge); - dummytri[0] = encode(searchedge); - /* Remove the bounding box and count the convex hull edges. */ - triedgecopy(*startghost, dissolveedge); - hullsize = 0; - do { - hullsize++; - lnext(dissolveedge, deadtri); - lprevself(dissolveedge); - symself(dissolveedge); - /* If no PSLG is involved, set the boundary markers of all the points */ - /* on the convex hull. If a PSLG is used, this step is done later. */ - if (!poly) { - /* Watch out for the case where all the input points are collinear. */ - if (dissolveedge.tri != dummytri) { - org(dissolveedge, markorg); - if (pointmark(markorg) == 0) { - setpointmark(markorg, 1); - } - } - } - /* Remove a bounding triangle from a convex hull triangle. */ - dissolve(dissolveedge); - /* Find the next bounding triangle. */ - sym(deadtri, dissolveedge); - /* Delete the bounding triangle. */ - triangledealloc(deadtri.tri); - } while (!triedgeequal(dissolveedge, *startghost)); - return hullsize; -} - -/*****************************************************************************/ -/* */ -/* divconqdelaunay() Form a Delaunay triangulation by the divide-and- */ -/* conquer method. */ -/* */ -/* Sorts the points, calls a recursive procedure to triangulate them, and */ -/* removes the bounding box, setting boundary markers as appropriate. */ -/* */ -/*****************************************************************************/ - -long divconqdelaunay() -{ - point *sortarray; - struct triedge hullleft, hullright; - int divider; - int i, j; - - /* Allocate an array of pointers to points for sorting. */ - sortarray = (point *) malloc(inpoints * sizeof(point)); - if (sortarray == (point *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - traversalinit(&points); - for (i = 0; i < inpoints; i++) { - sortarray[i] = pointtraverse(); - } - if (verbose) { - printf(" Sorting points.\n"); - } - /* Sort the points. */ - pointsort(sortarray, inpoints); - /* Discard duplicate points, which can really mess up the algorithm. */ - i = 0; - for (j = 1; j < inpoints; j++) { - if ((sortarray[i][0] == sortarray[j][0]) - && (sortarray[i][1] == sortarray[j][1])) { - if (!quiet) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - sortarray[j][0], sortarray[j][1]); - } -/* Commented out - would eliminate point from output .node file, but causes - a failure if some segment has this point as an endpoint. - setpointmark(sortarray[j], DEADPOINT); -*/ - } else { - i++; - sortarray[i] = sortarray[j]; - } - } - i++; - if (dwyer) { - /* Re-sort the array of points to accommodate alternating cuts. */ - divider = i >> 1; - if (i - divider >= 2) { - if (divider >= 2) { - alternateaxes(sortarray, divider, 1); - } - alternateaxes(&sortarray[divider], i - divider, 1); - } - } - if (verbose) { - printf(" Forming triangulation.\n"); - } - /* Form the Delaunay triangulation. */ - divconqrecurse(sortarray, i, 0, &hullleft, &hullright); - free(sortarray); - - return removeghosts(&hullleft); -} - -/** **/ -/** **/ -/********* Divide-and-conquer Delaunay triangulation ends here *********/ - -/********* Incremental Delaunay triangulation begins here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* boundingbox() Form an "infinite" bounding triangle to insert points */ -/* into. */ -/* */ -/* The points at "infinity" are assigned finite coordinates, which are used */ -/* by the point location routines, but (mostly) ignored by the Delaunay */ -/* edge flip routines. */ -/* */ -/*****************************************************************************/ - -#ifndef REDUCED - -void boundingbox() -{ - struct triedge inftri; /* Handle for the triangular bounding box. */ - REAL width; - - if (verbose) { - printf(" Creating triangular bounding box.\n"); - } - /* Find the width (or height, whichever is larger) of the triangulation. */ - width = xmax - xmin; - if (ymax - ymin > width) { - width = ymax - ymin; - } - if (width == 0.0) { - width = 1.0; - } - /* Create the vertices of the bounding box. */ - infpoint1 = (point) malloc(points.itembytes); - infpoint2 = (point) malloc(points.itembytes); - infpoint3 = (point) malloc(points.itembytes); - if ((infpoint1 == (point) NULL) || (infpoint2 == (point) NULL) - || (infpoint3 == (point) NULL)) { - printf("Error: Out of memory.\n"); - exit(1); - } - infpoint1[0] = xmin - 50.0 * width; - infpoint1[1] = ymin - 40.0 * width; - infpoint2[0] = xmax + 50.0 * width; - infpoint2[1] = ymin - 40.0 * width; - infpoint3[0] = 0.5 * (xmin + xmax); - infpoint3[1] = ymax + 60.0 * width; - - /* Create the bounding box. */ - maketriangle(&inftri); - setorg(inftri, infpoint1); - setdest(inftri, infpoint2); - setapex(inftri, infpoint3); - /* Link dummytri to the bounding box so we can always find an */ - /* edge to begin searching (point location) from. */ - dummytri[0] = (triangle) inftri.tri; - if (verbose > 2) { - printf(" Creating "); - printtriangle(&inftri); - } -} - -#endif /* not REDUCED */ - -/*****************************************************************************/ -/* */ -/* removebox() Remove the "infinite" bounding triangle, setting boundary */ -/* markers as appropriate. */ -/* */ -/* The triangular bounding box has three boundary triangles (one for each */ -/* side of the bounding box), and a bunch of triangles fanning out from */ -/* the three bounding box vertices (one triangle for each edge of the */ -/* convex hull of the inner mesh). This routine removes these triangles. */ -/* */ -/*****************************************************************************/ - -#ifndef REDUCED - -long removebox() -{ - struct triedge deadtri; - struct triedge searchedge; - struct triedge checkedge; - struct triedge nextedge, finaledge, dissolveedge; - point markorg; - long hullsize; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose) { - printf(" Removing triangular bounding box.\n"); - } - /* Find a boundary triangle. */ - nextedge.tri = dummytri; - nextedge.orient = 0; - symself(nextedge); - /* Mark a place to stop. */ - lprev(nextedge, finaledge); - lnextself(nextedge); - symself(nextedge); - /* Find a triangle (on the boundary of the point set) that isn't */ - /* a bounding box triangle. */ - lprev(nextedge, searchedge); - symself(searchedge); - /* Check whether nextedge is another boundary triangle */ - /* adjacent to the first one. */ - lnext(nextedge, checkedge); - symself(checkedge); - if (checkedge.tri == dummytri) { - /* Go on to the next triangle. There are only three boundary */ - /* triangles, and this next triangle cannot be the third one, */ - /* so it's safe to stop here. */ - lprevself(searchedge); - symself(searchedge); - } - /* Find a new boundary edge to search from, as the current search */ - /* edge lies on a bounding box triangle and will be deleted. */ - dummytri[0] = encode(searchedge); - hullsize = -2l; - while (!triedgeequal(nextedge, finaledge)) { - hullsize++; - lprev(nextedge, dissolveedge); - symself(dissolveedge); - /* If not using a PSLG, the vertices should be marked now. */ - /* (If using a PSLG, markhull() will do the job.) */ - if (!poly) { - /* Be careful! One must check for the case where all the input */ - /* points are collinear, and thus all the triangles are part of */ - /* the bounding box. Otherwise, the setpointmark() call below */ - /* will cause a bad pointer reference. */ - if (dissolveedge.tri != dummytri) { - org(dissolveedge, markorg); - if (pointmark(markorg) == 0) { - setpointmark(markorg, 1); - } - } - } - /* Disconnect the bounding box triangle from the mesh triangle. */ - dissolve(dissolveedge); - lnext(nextedge, deadtri); - sym(deadtri, nextedge); - /* Get rid of the bounding box triangle. */ - triangledealloc(deadtri.tri); - /* Do we need to turn the corner? */ - if (nextedge.tri == dummytri) { - /* Turn the corner. */ - triedgecopy(dissolveedge, nextedge); - } - } - triangledealloc(finaledge.tri); - - free(infpoint1); /* Deallocate the bounding box vertices. */ - free(infpoint2); - free(infpoint3); - - return hullsize; -} - -#endif /* not REDUCED */ - -/*****************************************************************************/ -/* */ -/* incrementaldelaunay() Form a Delaunay triangulation by incrementally */ -/* adding vertices. */ -/* */ -/*****************************************************************************/ - -#ifndef REDUCED - -long incrementaldelaunay() -{ - struct triedge starttri; - point pointloop; - int i; - - /* Create a triangular bounding box. */ - boundingbox(); - if (verbose) { - printf(" Incrementally inserting points.\n"); - } - traversalinit(&points); - pointloop = pointtraverse(); - i = 1; - while (pointloop != (point) NULL) { - /* Find a boundary triangle to search from. */ - starttri.tri = (triangle *) NULL; - if (insertsite(pointloop, &starttri, (struct edge *) NULL, 0, 0) == - DUPLICATEPOINT) { - if (!quiet) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - pointloop[0], pointloop[1]); - } -/* Commented out - would eliminate point from output .node file. - setpointmark(pointloop, DEADPOINT); -*/ - } - pointloop = pointtraverse(); - i++; - } - /* Remove the bounding box. */ - return removebox(); -} - -#endif /* not REDUCED */ - -/** **/ -/** **/ -/********* Incremental Delaunay triangulation ends here *********/ - -/********* Sweepline Delaunay triangulation begins here *********/ -/** **/ -/** **/ - -#ifndef REDUCED - -void eventheapinsert(heap, heapsize, newevent) -struct event **heap; -int heapsize; -struct event *newevent; -{ - REAL eventx, eventy; - int eventnum; - int parent; - int notdone; - - eventx = newevent->xkey; - eventy = newevent->ykey; - eventnum = heapsize; - notdone = eventnum > 0; - while (notdone) { - parent = (eventnum - 1) >> 1; - if ((heap[parent]->ykey < eventy) || - ((heap[parent]->ykey == eventy) - && (heap[parent]->xkey <= eventx))) { - notdone = 0; - } else { - heap[eventnum] = heap[parent]; - heap[eventnum]->heapposition = eventnum; - - eventnum = parent; - notdone = eventnum > 0; - } - } - heap[eventnum] = newevent; - newevent->heapposition = eventnum; -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -void eventheapify(heap, heapsize, eventnum) -struct event **heap; -int heapsize; -int eventnum; -{ - struct event *thisevent; - REAL eventx, eventy; - int leftchild, rightchild; - int smallest; - int notdone; - - thisevent = heap[eventnum]; - eventx = thisevent->xkey; - eventy = thisevent->ykey; - leftchild = 2 * eventnum + 1; - notdone = leftchild < heapsize; - while (notdone) { - if ((heap[leftchild]->ykey < eventy) || - ((heap[leftchild]->ykey == eventy) - && (heap[leftchild]->xkey < eventx))) { - smallest = leftchild; - } else { - smallest = eventnum; - } - rightchild = leftchild + 1; - if (rightchild < heapsize) { - if ((heap[rightchild]->ykey < heap[smallest]->ykey) || - ((heap[rightchild]->ykey == heap[smallest]->ykey) - && (heap[rightchild]->xkey < heap[smallest]->xkey))) { - smallest = rightchild; - } - } - if (smallest == eventnum) { - notdone = 0; - } else { - heap[eventnum] = heap[smallest]; - heap[eventnum]->heapposition = eventnum; - heap[smallest] = thisevent; - thisevent->heapposition = smallest; - - eventnum = smallest; - leftchild = 2 * eventnum + 1; - notdone = leftchild < heapsize; - } - } -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -void eventheapdelete(heap, heapsize, eventnum) -struct event **heap; -int heapsize; -int eventnum; -{ - struct event *moveevent; - REAL eventx, eventy; - int parent; - int notdone; - - moveevent = heap[heapsize - 1]; - if (eventnum > 0) { - eventx = moveevent->xkey; - eventy = moveevent->ykey; - do { - parent = (eventnum - 1) >> 1; - if ((heap[parent]->ykey < eventy) || - ((heap[parent]->ykey == eventy) - && (heap[parent]->xkey <= eventx))) { - notdone = 0; - } else { - heap[eventnum] = heap[parent]; - heap[eventnum]->heapposition = eventnum; - - eventnum = parent; - notdone = eventnum > 0; - } - } while (notdone); - } - heap[eventnum] = moveevent; - moveevent->heapposition = eventnum; - eventheapify(heap, heapsize - 1, eventnum); -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -void createeventheap(eventheap, events, freeevents) -struct event ***eventheap; -struct event **events; -struct event **freeevents; -{ - point thispoint; - int maxevents; - int i; - - maxevents = (3 * inpoints) / 2; - *eventheap = (struct event **) malloc(maxevents * sizeof(struct event *)); - if (*eventheap == (struct event **) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - *events = (struct event *) malloc(maxevents * sizeof(struct event)); - if (*events == (struct event *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - traversalinit(&points); - for (i = 0; i < inpoints; i++) { - thispoint = pointtraverse(); - (*events)[i].eventptr = (VOID *) thispoint; - (*events)[i].xkey = thispoint[0]; - (*events)[i].ykey = thispoint[1]; - eventheapinsert(*eventheap, i, *events + i); - } - *freeevents = (struct event *) NULL; - for (i = maxevents - 1; i >= inpoints; i--) { - (*events)[i].eventptr = (VOID *) *freeevents; - *freeevents = *events + i; - } -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -int rightofhyperbola(fronttri, newsite) -struct triedge *fronttri; -point newsite; -{ - point leftpoint, rightpoint; - REAL dxa, dya, dxb, dyb; - - hyperbolacount++; - - dest(*fronttri, leftpoint); - apex(*fronttri, rightpoint); - if ((leftpoint[1] < rightpoint[1]) - || ((leftpoint[1] == rightpoint[1]) && (leftpoint[0] < rightpoint[0]))) { - if (newsite[0] >= rightpoint[0]) { - return 1; - } - } else { - if (newsite[0] <= leftpoint[0]) { - return 0; - } - } - dxa = leftpoint[0] - newsite[0]; - dya = leftpoint[1] - newsite[1]; - dxb = rightpoint[0] - newsite[0]; - dyb = rightpoint[1] - newsite[1]; - return dya * (dxb * dxb + dyb * dyb) > dyb * (dxa * dxa + dya * dya); -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -REAL circletop(pa, pb, pc, ccwabc) -point pa; -point pb; -point pc; -REAL ccwabc; -{ - REAL xac, yac, xbc, ybc, xab, yab; - REAL aclen2, bclen2, ablen2; - - circletopcount++; - - xac = pa[0] - pc[0]; - yac = pa[1] - pc[1]; - xbc = pb[0] - pc[0]; - ybc = pb[1] - pc[1]; - xab = pa[0] - pb[0]; - yab = pa[1] - pb[1]; - aclen2 = xac * xac + yac * yac; - bclen2 = xbc * xbc + ybc * ybc; - ablen2 = xab * xab + yab * yab; - return pc[1] + (xac * bclen2 - xbc * aclen2 + sqrt(aclen2 * bclen2 * ablen2)) - / (2.0 * ccwabc); -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -void check4deadevent(checktri, freeevents, eventheap, heapsize) -struct triedge *checktri; -struct event **freeevents; -struct event **eventheap; -int *heapsize; -{ - struct event *deadevent; - point eventpoint; - int eventnum; - - org(*checktri, eventpoint); - if (eventpoint != (point) NULL) { - deadevent = (struct event *) eventpoint; - eventnum = deadevent->heapposition; - deadevent->eventptr = (VOID *) *freeevents; - *freeevents = deadevent; - eventheapdelete(eventheap, *heapsize, eventnum); - (*heapsize)--; - setorg(*checktri, NULL); - } -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -struct splaynode *splay(splaytree, searchpoint, searchtri) -struct splaynode *splaytree; -point searchpoint; -struct triedge *searchtri; -{ - struct splaynode *child, *grandchild; - struct splaynode *lefttree, *righttree; - struct splaynode *leftright; - point checkpoint; - int rightofroot, rightofchild; - - if (splaytree == (struct splaynode *) NULL) { - return (struct splaynode *) NULL; - } - dest(splaytree->keyedge, checkpoint); - if (checkpoint == splaytree->keydest) { - rightofroot = rightofhyperbola(&splaytree->keyedge, searchpoint); - if (rightofroot) { - triedgecopy(splaytree->keyedge, *searchtri); - child = splaytree->rchild; - } else { - child = splaytree->lchild; - } - if (child == (struct splaynode *) NULL) { - return splaytree; - } - dest(child->keyedge, checkpoint); - if (checkpoint != child->keydest) { - child = splay(child, searchpoint, searchtri); - if (child == (struct splaynode *) NULL) { - if (rightofroot) { - splaytree->rchild = (struct splaynode *) NULL; - } else { - splaytree->lchild = (struct splaynode *) NULL; - } - return splaytree; - } - } - rightofchild = rightofhyperbola(&child->keyedge, searchpoint); - if (rightofchild) { - triedgecopy(child->keyedge, *searchtri); - grandchild = splay(child->rchild, searchpoint, searchtri); - child->rchild = grandchild; - } else { - grandchild = splay(child->lchild, searchpoint, searchtri); - child->lchild = grandchild; - } - if (grandchild == (struct splaynode *) NULL) { - if (rightofroot) { - splaytree->rchild = child->lchild; - child->lchild = splaytree; - } else { - splaytree->lchild = child->rchild; - child->rchild = splaytree; - } - return child; - } - if (rightofchild) { - if (rightofroot) { - splaytree->rchild = child->lchild; - child->lchild = splaytree; - } else { - splaytree->lchild = grandchild->rchild; - grandchild->rchild = splaytree; - } - child->rchild = grandchild->lchild; - grandchild->lchild = child; - } else { - if (rightofroot) { - splaytree->rchild = grandchild->lchild; - grandchild->lchild = splaytree; - } else { - splaytree->lchild = child->rchild; - child->rchild = splaytree; - } - child->lchild = grandchild->rchild; - grandchild->rchild = child; - } - return grandchild; - } else { - lefttree = splay(splaytree->lchild, searchpoint, searchtri); - righttree = splay(splaytree->rchild, searchpoint, searchtri); - - pooldealloc(&splaynodes, (VOID *) splaytree); - if (lefttree == (struct splaynode *) NULL) { - return righttree; - } else if (righttree == (struct splaynode *) NULL) { - return lefttree; - } else if (lefttree->rchild == (struct splaynode *) NULL) { - lefttree->rchild = righttree->lchild; - righttree->lchild = lefttree; - return righttree; - } else if (righttree->lchild == (struct splaynode *) NULL) { - righttree->lchild = lefttree->rchild; - lefttree->rchild = righttree; - return lefttree; - } else { -/* printf("Holy Toledo!!!\n"); */ - leftright = lefttree->rchild; - while (leftright->rchild != (struct splaynode *) NULL) { - leftright = leftright->rchild; - } - leftright->rchild = righttree; - return lefttree; - } - } -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -struct splaynode *splayinsert(splayroot, newkey, searchpoint) -struct splaynode *splayroot; -struct triedge *newkey; -point searchpoint; -{ - struct splaynode *newsplaynode; - - newsplaynode = (struct splaynode *) poolalloc(&splaynodes); - triedgecopy(*newkey, newsplaynode->keyedge); - dest(*newkey, newsplaynode->keydest); - if (splayroot == (struct splaynode *) NULL) { - newsplaynode->lchild = (struct splaynode *) NULL; - newsplaynode->rchild = (struct splaynode *) NULL; - } else if (rightofhyperbola(&splayroot->keyedge, searchpoint)) { - newsplaynode->lchild = splayroot; - newsplaynode->rchild = splayroot->rchild; - splayroot->rchild = (struct splaynode *) NULL; - } else { - newsplaynode->lchild = splayroot->lchild; - newsplaynode->rchild = splayroot; - splayroot->lchild = (struct splaynode *) NULL; - } - return newsplaynode; -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -struct splaynode *circletopinsert(splayroot, newkey, pa, pb, pc, topy) -struct splaynode *splayroot; -struct triedge *newkey; -point pa; -point pb; -point pc; -REAL topy; -{ - REAL ccwabc; - REAL xac, yac, xbc, ybc; - REAL aclen2, bclen2; - REAL searchpoint[2]; - struct triedge dummytri; - - ccwabc = counterclockwise(pa, pb, pc); - xac = pa[0] - pc[0]; - yac = pa[1] - pc[1]; - xbc = pb[0] - pc[0]; - ybc = pb[1] - pc[1]; - aclen2 = xac * xac + yac * yac; - bclen2 = xbc * xbc + ybc * ybc; - searchpoint[0] = pc[0] - (yac * bclen2 - ybc * aclen2) / (2.0 * ccwabc); - searchpoint[1] = topy; - return splayinsert(splay(splayroot, (point) searchpoint, &dummytri), newkey, - (point) searchpoint); -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -struct splaynode *frontlocate(splayroot, bottommost, searchpoint, searchtri, - farright) -struct splaynode *splayroot; -struct triedge *bottommost; -point searchpoint; -struct triedge *searchtri; -int *farright; -{ - int farrightflag; - triangle ptr; /* Temporary variable used by onext(). */ - - triedgecopy(*bottommost, *searchtri); - splayroot = splay(splayroot, searchpoint, searchtri); - - farrightflag = 0; - while (!farrightflag && rightofhyperbola(searchtri, searchpoint)) { - onextself(*searchtri); - farrightflag = triedgeequal(*searchtri, *bottommost); - } - *farright = farrightflag; - return splayroot; -} - -#endif /* not REDUCED */ - -#ifndef REDUCED - -long sweeplinedelaunay() -{ - struct event **eventheap; - struct event *events; - struct event *freeevents; - struct event *nextevent; - struct event *newevent; - struct splaynode *splayroot; - struct triedge bottommost; - struct triedge searchtri; - struct triedge fliptri; - struct triedge lefttri, righttri, farlefttri, farrighttri; - struct triedge inserttri; - point firstpoint, secondpoint; - point nextpoint, lastpoint; - point connectpoint; - point leftpoint, midpoint, rightpoint; - REAL lefttest, righttest; - int heapsize; - int check4events, farrightflag; - triangle ptr; /* Temporary variable used by sym(), onext(), and oprev(). */ - - poolinit(&splaynodes, sizeof(struct splaynode), SPLAYNODEPERBLOCK, POINTER, - 0); - splayroot = (struct splaynode *) NULL; - - if (verbose) { - printf(" Placing points in event heap.\n"); - } - createeventheap(&eventheap, &events, &freeevents); - heapsize = inpoints; - - if (verbose) { - printf(" Forming triangulation.\n"); - } - maketriangle(&lefttri); - maketriangle(&righttri); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, righttri); - firstpoint = (point) eventheap[0]->eventptr; - eventheap[0]->eventptr = (VOID *) freeevents; - freeevents = eventheap[0]; - eventheapdelete(eventheap, heapsize, 0); - heapsize--; - do { - if (heapsize == 0) { - printf("Error: Input points are all identical.\n"); - exit(1); - } - secondpoint = (point) eventheap[0]->eventptr; - eventheap[0]->eventptr = (VOID *) freeevents; - freeevents = eventheap[0]; - eventheapdelete(eventheap, heapsize, 0); - heapsize--; - if ((firstpoint[0] == secondpoint[0]) - && (firstpoint[1] == secondpoint[1])) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - secondpoint[0], secondpoint[1]); -/* Commented out - would eliminate point from output .node file. - setpointmark(secondpoint, DEADPOINT); -*/ - } - } while ((firstpoint[0] == secondpoint[0]) - && (firstpoint[1] == secondpoint[1])); - setorg(lefttri, firstpoint); - setdest(lefttri, secondpoint); - setorg(righttri, secondpoint); - setdest(righttri, firstpoint); - lprev(lefttri, bottommost); - lastpoint = secondpoint; - while (heapsize > 0) { - nextevent = eventheap[0]; - eventheapdelete(eventheap, heapsize, 0); - heapsize--; - check4events = 1; - if (nextevent->xkey < xmin) { - decode(nextevent->eventptr, fliptri); - oprev(fliptri, farlefttri); - check4deadevent(&farlefttri, &freeevents, eventheap, &heapsize); - onext(fliptri, farrighttri); - check4deadevent(&farrighttri, &freeevents, eventheap, &heapsize); - - if (triedgeequal(farlefttri, bottommost)) { - lprev(fliptri, bottommost); - } - flip(&fliptri); - setapex(fliptri, NULL); - lprev(fliptri, lefttri); - lnext(fliptri, righttri); - sym(lefttri, farlefttri); - - if (randomnation(SAMPLERATE) == 0) { - symself(fliptri); - dest(fliptri, leftpoint); - apex(fliptri, midpoint); - org(fliptri, rightpoint); - splayroot = circletopinsert(splayroot, &lefttri, leftpoint, midpoint, - rightpoint, nextevent->ykey); - } - } else { - nextpoint = (point) nextevent->eventptr; - if ((nextpoint[0] == lastpoint[0]) && (nextpoint[1] == lastpoint[1])) { - printf( -"Warning: A duplicate point at (%.12g, %.12g) appeared and was ignored.\n", - nextpoint[0], nextpoint[1]); -/* Commented out - would eliminate point from output .node file. - setpointmark(nextpoint, DEADPOINT); -*/ - check4events = 0; - } else { - lastpoint = nextpoint; - - splayroot = frontlocate(splayroot, &bottommost, nextpoint, &searchtri, - &farrightflag); -/* - triedgecopy(bottommost, searchtri); - farrightflag = 0; - while (!farrightflag && rightofhyperbola(&searchtri, nextpoint)) { - onextself(searchtri); - farrightflag = triedgeequal(searchtri, bottommost); - } -*/ - - check4deadevent(&searchtri, &freeevents, eventheap, &heapsize); - - triedgecopy(searchtri, farrighttri); - sym(searchtri, farlefttri); - maketriangle(&lefttri); - maketriangle(&righttri); - dest(farrighttri, connectpoint); - setorg(lefttri, connectpoint); - setdest(lefttri, nextpoint); - setorg(righttri, nextpoint); - setdest(righttri, connectpoint); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, righttri); - lnextself(lefttri); - lprevself(righttri); - bond(lefttri, farlefttri); - bond(righttri, farrighttri); - if (!farrightflag && triedgeequal(farrighttri, bottommost)) { - triedgecopy(lefttri, bottommost); - } - - if (randomnation(SAMPLERATE) == 0) { - splayroot = splayinsert(splayroot, &lefttri, nextpoint); - } else if (randomnation(SAMPLERATE) == 0) { - lnext(righttri, inserttri); - splayroot = splayinsert(splayroot, &inserttri, nextpoint); - } - } - } - nextevent->eventptr = (VOID *) freeevents; - freeevents = nextevent; - - if (check4events) { - apex(farlefttri, leftpoint); - dest(lefttri, midpoint); - apex(lefttri, rightpoint); - lefttest = counterclockwise(leftpoint, midpoint, rightpoint); - if (lefttest > 0.0) { - newevent = freeevents; - freeevents = (struct event *) freeevents->eventptr; - newevent->xkey = xminextreme; - newevent->ykey = circletop(leftpoint, midpoint, rightpoint, - lefttest); - newevent->eventptr = (VOID *) encode(lefttri); - eventheapinsert(eventheap, heapsize, newevent); - heapsize++; - setorg(lefttri, newevent); - } - apex(righttri, leftpoint); - org(righttri, midpoint); - apex(farrighttri, rightpoint); - righttest = counterclockwise(leftpoint, midpoint, rightpoint); - if (righttest > 0.0) { - newevent = freeevents; - freeevents = (struct event *) freeevents->eventptr; - newevent->xkey = xminextreme; - newevent->ykey = circletop(leftpoint, midpoint, rightpoint, - righttest); - newevent->eventptr = (VOID *) encode(farrighttri); - eventheapinsert(eventheap, heapsize, newevent); - heapsize++; - setorg(farrighttri, newevent); - } - } - } - - pooldeinit(&splaynodes); - lprevself(bottommost); - return removeghosts(&bottommost); -} - -#endif /* not REDUCED */ - -/** **/ -/** **/ -/********* Sweepline Delaunay triangulation ends here *********/ - -/********* General mesh construction routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* delaunay() Form a Delaunay triangulation. */ -/* */ -/*****************************************************************************/ - -long delaunay() -{ - eextras = 0; - initializetrisegpools(); - -#ifdef REDUCED - if (!quiet) { - printf( - "Constructing Delaunay triangulation by divide-and-conquer method.\n"); - } - return divconqdelaunay(); -#else /* not REDUCED */ - if (!quiet) { - printf("Constructing Delaunay triangulation "); - if (incremental) { - printf("by incremental method.\n"); - } else if (sweepline) { - printf("by sweepline method.\n"); - } else { - printf("by divide-and-conquer method.\n"); - } - } - if (incremental) { - return incrementaldelaunay(); - } else if (sweepline) { - return sweeplinedelaunay(); - } else { - return divconqdelaunay(); - } -#endif /* not REDUCED */ -} - -/*****************************************************************************/ -/* */ -/* reconstruct() Reconstruct a triangulation from its .ele (and possibly */ -/* .poly) file. Used when the -r switch is used. */ -/* */ -/* Reads an .ele file and reconstructs the original mesh. If the -p switch */ -/* is used, this procedure will also read a .poly file and reconstruct the */ -/* shell edges of the original mesh. If the -a switch is used, this */ -/* procedure will also read an .area file and set a maximum area constraint */ -/* on each triangle. */ -/* */ -/* Points that are not corners of triangles, such as nodes on edges of */ -/* subparametric elements, are discarded. */ -/* */ -/* This routine finds the adjacencies between triangles (and shell edges) */ -/* by forming one stack of triangles for each vertex. Each triangle is on */ -/* three different stacks simultaneously. Each triangle's shell edge */ -/* pointers are used to link the items in each stack. This memory-saving */ -/* feature makes the code harder to read. The most important thing to keep */ -/* in mind is that each triangle is removed from a stack precisely when */ -/* the corresponding pointer is adjusted to refer to a shell edge rather */ -/* than the next triangle of the stack. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -#ifdef TRILIBRARY - -int reconstruct(trianglelist, triangleattriblist, trianglearealist, elements, - corners, attribs, segmentlist, segmentmarkerlist, - numberofsegments) -int *trianglelist; -REAL *triangleattriblist; -REAL *trianglearealist; -int elements; -int corners; -int attribs; -int *segmentlist; -int *segmentmarkerlist; -int numberofsegments; - -#else /* not TRILIBRARY */ - -long reconstruct(elefilename, areafilename, polyfilename, polyfile) -char *elefilename; -char *areafilename; -char *polyfilename; -FILE *polyfile; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - int pointindex; - int attribindex; -#else /* not TRILIBRARY */ - FILE *elefile; - FILE *areafile; - char inputline[INPUTLINESIZE]; - char *stringptr; - int areaelements; -#endif /* not TRILIBRARY */ - struct triedge triangleloop; - struct triedge triangleleft; - struct triedge checktri; - struct triedge checkleft; - struct triedge checkneighbor; - struct edge shelleloop; - triangle *vertexarray; - triangle *prevlink; - triangle nexttri; - point tdest, tapex; - point checkdest, checkapex; - point shorg; - point killpoint; - REAL area; - int corner[3]; - int end[2]; - int killpointindex; - int incorners; - int segmentmarkers; - int boundmarker; - int aroundpoint; - long hullsize; - int notfound; - int elementnumber, segmentnumber; - int i, j; - triangle ptr; /* Temporary variable used by sym(). */ - -#ifdef TRILIBRARY - inelements = elements; - incorners = corners; - if (incorners < 3) { - printf("Error: Triangles must have at least 3 points.\n"); - exit(1); - } - eextras = attribs; -#else /* not TRILIBRARY */ - /* Read the triangles from an .ele file. */ - if (!quiet) { - printf("Opening %s.\n", elefilename); - } - elefile = fopen(elefilename, "r"); - if (elefile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", elefilename); - exit(1); - } - /* Read number of triangles, number of points per triangle, and */ - /* number of triangle attributes from .ele file. */ - stringptr = readline(inputline, elefile, elefilename); - inelements = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - incorners = 3; - } else { - incorners = (int) strtol (stringptr, &stringptr, 0); - if (incorners < 3) { - printf("Error: Triangles in %s must have at least 3 points.\n", - elefilename); - exit(1); - } - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - eextras = 0; - } else { - eextras = (int) strtol (stringptr, &stringptr, 0); - } -#endif /* not TRILIBRARY */ - - initializetrisegpools(); - - /* Create the triangles. */ - for (elementnumber = 1; elementnumber <= inelements; elementnumber++) { - maketriangle(&triangleloop); - /* Mark the triangle as living. */ - triangleloop.tri[3] = (triangle) triangleloop.tri; - } - - if (poly) { -#ifdef TRILIBRARY - insegments = numberofsegments; - segmentmarkers = segmentmarkerlist != (int *) NULL; -#else /* not TRILIBRARY */ - /* Read number of segments and number of segment */ - /* boundary markers from .poly file. */ - stringptr = readline(inputline, polyfile, inpolyfilename); - insegments = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - segmentmarkers = 0; - } else { - segmentmarkers = (int) strtol (stringptr, &stringptr, 0); - } -#endif /* not TRILIBRARY */ - - /* Create the shell edges. */ - for (segmentnumber = 1; segmentnumber <= insegments; segmentnumber++) { - makeshelle(&shelleloop); - /* Mark the shell edge as living. */ - shelleloop.sh[2] = (shelle) shelleloop.sh; - } - } - -#ifdef TRILIBRARY - pointindex = 0; - attribindex = 0; -#else /* not TRILIBRARY */ - if (vararea) { - /* Open an .area file, check for consistency with the .ele file. */ - if (!quiet) { - printf("Opening %s.\n", areafilename); - } - areafile = fopen(areafilename, "r"); - if (areafile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", areafilename); - exit(1); - } - stringptr = readline(inputline, areafile, areafilename); - areaelements = (int) strtol (stringptr, &stringptr, 0); - if (areaelements != inelements) { - printf("Error: %s and %s disagree on number of triangles.\n", - elefilename, areafilename); - exit(1); - } - } -#endif /* not TRILIBRARY */ - - if (!quiet) { - printf("Reconstructing mesh.\n"); - } - /* Allocate a temporary array that maps each point to some adjacent */ - /* triangle. I took care to allocate all the permanent memory for */ - /* triangles and shell edges first. */ - vertexarray = (triangle *) malloc(points.items * sizeof(triangle)); - if (vertexarray == (triangle *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - /* Each point is initially unrepresented. */ - for (i = 0; i < points.items; i++) { - vertexarray[i] = (triangle) dummytri; - } - - if (verbose) { - printf(" Assembling triangles.\n"); - } - /* Read the triangles from the .ele file, and link */ - /* together those that share an edge. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { -#ifdef TRILIBRARY - /* Copy the triangle's three corners. */ - for (j = 0; j < 3; j++) { - corner[j] = trianglelist[pointindex++]; - if ((corner[j] < firstnumber) || (corner[j] >= firstnumber + inpoints)) { - printf("Error: Triangle %d has an invalid vertex index.\n", - elementnumber); - exit(1); - } - } -#else /* not TRILIBRARY */ - /* Read triangle number and the triangle's three corners. */ - stringptr = readline(inputline, elefile, elefilename); - for (j = 0; j < 3; j++) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Triangle %d is missing point %d in %s.\n", - elementnumber, j + 1, elefilename); - exit(1); - } else { - corner[j] = (int) strtol (stringptr, &stringptr, 0); - if ((corner[j] < firstnumber) || - (corner[j] >= firstnumber + inpoints)) { - printf("Error: Triangle %d has an invalid vertex index.\n", - elementnumber); - exit(1); - } - } - } -#endif /* not TRILIBRARY */ - - /* Find out about (and throw away) extra nodes. */ - for (j = 3; j < incorners; j++) { -#ifdef TRILIBRARY - killpointindex = trianglelist[pointindex++]; -#else /* not TRILIBRARY */ - stringptr = findfield(stringptr); - if (*stringptr != '\0') { - killpointindex = (int) strtol (stringptr, &stringptr, 0); -#endif /* not TRILIBRARY */ - if ((killpointindex >= firstnumber) && - (killpointindex < firstnumber + inpoints)) { - /* Delete the non-corner point if it's not already deleted. */ - killpoint = getpoint(killpointindex); - if (pointmark(killpoint) != DEADPOINT) { - pointdealloc(killpoint); - } - } -#ifndef TRILIBRARY - } -#endif /* not TRILIBRARY */ - } - - /* Read the triangle's attributes. */ - for (j = 0; j < eextras; j++) { -#ifdef TRILIBRARY - setelemattribute(triangleloop, j, triangleattriblist[attribindex++]); -#else /* not TRILIBRARY */ - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - setelemattribute(triangleloop, j, 0); - } else { - setelemattribute(triangleloop, j, - (REAL) strtod (stringptr, &stringptr)); - } -#endif /* not TRILIBRARY */ - } - - if (vararea) { -#ifdef TRILIBRARY - area = trianglearealist[elementnumber - firstnumber]; -#else /* not TRILIBRARY */ - /* Read an area constraint from the .area file. */ - stringptr = readline(inputline, areafile, areafilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - area = -1.0; /* No constraint on this triangle. */ - } else { - area = (REAL) strtod(stringptr, &stringptr); - } -#endif /* not TRILIBRARY */ - setareabound(triangleloop, area); - } - - /* Set the triangle's vertices. */ - triangleloop.orient = 0; - setorg(triangleloop, getpoint(corner[0])); - setdest(triangleloop, getpoint(corner[1])); - setapex(triangleloop, getpoint(corner[2])); - /* Try linking the triangle to others that share these vertices. */ - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - /* Take the number for the origin of triangleloop. */ - aroundpoint = corner[triangleloop.orient]; - /* Look for other triangles having this vertex. */ - nexttri = vertexarray[aroundpoint - firstnumber]; - /* Link the current triangle to the next one in the stack. */ - triangleloop.tri[6 + triangleloop.orient] = nexttri; - /* Push the current triangle onto the stack. */ - vertexarray[aroundpoint - firstnumber] = encode(triangleloop); - decode(nexttri, checktri); - if (checktri.tri != dummytri) { - dest(triangleloop, tdest); - apex(triangleloop, tapex); - /* Look for other triangles that share an edge. */ - do { - dest(checktri, checkdest); - apex(checktri, checkapex); - if (tapex == checkdest) { - /* The two triangles share an edge; bond them together. */ - lprev(triangleloop, triangleleft); - bond(triangleleft, checktri); - } - if (tdest == checkapex) { - /* The two triangles share an edge; bond them together. */ - lprev(checktri, checkleft); - bond(triangleloop, checkleft); - } - /* Find the next triangle in the stack. */ - nexttri = checktri.tri[6 + checktri.orient]; - decode(nexttri, checktri); - } while (checktri.tri != dummytri); - } - } - triangleloop.tri = triangletraverse(); - elementnumber++; - } - -#ifdef TRILIBRARY - pointindex = 0; -#else /* not TRILIBRARY */ - fclose(elefile); - if (vararea) { - fclose(areafile); - } -#endif /* not TRILIBRARY */ - - hullsize = 0; /* Prepare to count the boundary edges. */ - if (poly) { - if (verbose) { - printf(" Marking segments in triangulation.\n"); - } - /* Read the segments from the .poly file, and link them */ - /* to their neighboring triangles. */ - boundmarker = 0; - traversalinit(&shelles); - shelleloop.sh = shelletraverse(); - segmentnumber = firstnumber; - while (shelleloop.sh != (shelle *) NULL) { -#ifdef TRILIBRARY - end[0] = segmentlist[pointindex++]; - end[1] = segmentlist[pointindex++]; - if (segmentmarkers) { - boundmarker = segmentmarkerlist[segmentnumber - firstnumber]; - } -#else /* not TRILIBRARY */ - /* Read the endpoints of each segment, and possibly a boundary marker. */ - stringptr = readline(inputline, polyfile, inpolyfilename); - /* Skip the first (segment number) field. */ - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d has no endpoints in %s.\n", segmentnumber, - polyfilename); - exit(1); - } else { - end[0] = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d is missing its second endpoint in %s.\n", - segmentnumber, polyfilename); - exit(1); - } else { - end[1] = (int) strtol (stringptr, &stringptr, 0); - } - if (segmentmarkers) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - boundmarker = 0; - } else { - boundmarker = (int) strtol (stringptr, &stringptr, 0); - } - } -#endif /* not TRILIBRARY */ - for (j = 0; j < 2; j++) { - if ((end[j] < firstnumber) || (end[j] >= firstnumber + inpoints)) { - printf("Error: Segment %d has an invalid vertex index.\n", - segmentnumber); - exit(1); - } - } - - /* set the shell edge's vertices. */ - shelleloop.shorient = 0; - setsorg(shelleloop, getpoint(end[0])); - setsdest(shelleloop, getpoint(end[1])); - setmark(shelleloop, boundmarker); - /* Try linking the shell edge to triangles that share these vertices. */ - for (shelleloop.shorient = 0; shelleloop.shorient < 2; - shelleloop.shorient++) { - /* Take the number for the destination of shelleloop. */ - aroundpoint = end[1 - shelleloop.shorient]; - /* Look for triangles having this vertex. */ - prevlink = &vertexarray[aroundpoint - firstnumber]; - nexttri = vertexarray[aroundpoint - firstnumber]; - decode(nexttri, checktri); - sorg(shelleloop, shorg); - notfound = 1; - /* Look for triangles having this edge. Note that I'm only */ - /* comparing each triangle's destination with the shell edge; */ - /* each triangle's apex is handled through a different vertex. */ - /* Because each triangle appears on three vertices' lists, each */ - /* occurrence of a triangle on a list can (and does) represent */ - /* an edge. In this way, most edges are represented twice, and */ - /* every triangle-segment bond is represented once. */ - while (notfound && (checktri.tri != dummytri)) { - dest(checktri, checkdest); - if (shorg == checkdest) { - /* We have a match. Remove this triangle from the list. */ - *prevlink = checktri.tri[6 + checktri.orient]; - /* Bond the shell edge to the triangle. */ - tsbond(checktri, shelleloop); - /* Check if this is a boundary edge. */ - sym(checktri, checkneighbor); - if (checkneighbor.tri == dummytri) { - /* The next line doesn't insert a shell edge (because there's */ - /* already one there), but it sets the boundary markers of */ - /* the existing shell edge and its vertices. */ - insertshelle(&checktri, 1); - hullsize++; - } - notfound = 0; - } - /* Find the next triangle in the stack. */ - prevlink = &checktri.tri[6 + checktri.orient]; - nexttri = checktri.tri[6 + checktri.orient]; - decode(nexttri, checktri); - } - } - shelleloop.sh = shelletraverse(); - segmentnumber++; - } - } - - /* Mark the remaining edges as not being attached to any shell edge. */ - /* Also, count the (yet uncounted) boundary edges. */ - for (i = 0; i < points.items; i++) { - /* Search the stack of triangles adjacent to a point. */ - nexttri = vertexarray[i]; - decode(nexttri, checktri); - while (checktri.tri != dummytri) { - /* Find the next triangle in the stack before this */ - /* information gets overwritten. */ - nexttri = checktri.tri[6 + checktri.orient]; - /* No adjacent shell edge. (This overwrites the stack info.) */ - tsdissolve(checktri); - sym(checktri, checkneighbor); - if (checkneighbor.tri == dummytri) { - insertshelle(&checktri, 1); - hullsize++; - } - decode(nexttri, checktri); - } - } - - free(vertexarray); - return hullsize; -} - -#endif /* not CDT_ONLY */ - -/** **/ -/** **/ -/********* General mesh construction routines end here *********/ - -/********* Segment (shell edge) insertion begins here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* finddirection() Find the first triangle on the path from one point */ -/* to another. */ -/* */ -/* Finds the triangle that intersects a line segment drawn from the */ -/* origin of `searchtri' to the point `endpoint', and returns the result */ -/* in `searchtri'. The origin of `searchtri' does not change, even though */ -/* the triangle returned may differ from the one passed in. This routine */ -/* is used to find the direction to move in to get from one point to */ -/* another. */ -/* */ -/* The return value notes whether the destination or apex of the found */ -/* triangle is collinear with the two points in question. */ -/* */ -/*****************************************************************************/ - -enum finddirectionresult finddirection(searchtri, endpoint) -struct triedge *searchtri; -point endpoint; -{ - struct triedge checktri; - point startpoint; - point leftpoint, rightpoint; - REAL leftccw, rightccw; - int leftflag, rightflag; - triangle ptr; /* Temporary variable used by onext() and oprev(). */ - - org(*searchtri, startpoint); - dest(*searchtri, rightpoint); - apex(*searchtri, leftpoint); - /* Is `endpoint' to the left? */ - leftccw = counterclockwise(endpoint, startpoint, leftpoint); - leftflag = leftccw > 0.0; - /* Is `endpoint' to the right? */ - rightccw = counterclockwise(startpoint, endpoint, rightpoint); - rightflag = rightccw > 0.0; - if (leftflag && rightflag) { - /* `searchtri' faces directly away from `endpoint'. We could go */ - /* left or right. Ask whether it's a triangle or a boundary */ - /* on the left. */ - onext(*searchtri, checktri); - if (checktri.tri == dummytri) { - leftflag = 0; - } else { - rightflag = 0; - } - } - while (leftflag) { - /* Turn left until satisfied. */ - onextself(*searchtri); - if (searchtri->tri == dummytri) { - printf("Internal error in finddirection(): Unable to find a\n"); - printf(" triangle leading from (%.12g, %.12g) to", startpoint[0], - startpoint[1]); - printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]); - internalerror(); - } - apex(*searchtri, leftpoint); - rightccw = leftccw; - leftccw = counterclockwise(endpoint, startpoint, leftpoint); - leftflag = leftccw > 0.0; - } - while (rightflag) { - /* Turn right until satisfied. */ - oprevself(*searchtri); - if (searchtri->tri == dummytri) { - printf("Internal error in finddirection(): Unable to find a\n"); - printf(" triangle leading from (%.12g, %.12g) to", startpoint[0], - startpoint[1]); - printf(" (%.12g, %.12g).\n", endpoint[0], endpoint[1]); - internalerror(); - } - dest(*searchtri, rightpoint); - leftccw = rightccw; - rightccw = counterclockwise(startpoint, endpoint, rightpoint); - rightflag = rightccw > 0.0; - } - if (leftccw == 0.0) { - return LEFTCOLLINEAR; - } else if (rightccw == 0.0) { - return RIGHTCOLLINEAR; - } else { - return WITHIN; - } -} - -/*****************************************************************************/ -/* */ -/* segmentintersection() Find the intersection of an existing segment */ -/* and a segment that is being inserted. Insert */ -/* a point at the intersection, splitting an */ -/* existing shell edge. */ -/* */ -/* The segment being inserted connects the apex of splittri to endpoint2. */ -/* splitshelle is the shell edge being split, and MUST be opposite */ -/* splittri. Hence, the edge being split connects the origin and */ -/* destination of splittri. */ -/* */ -/* On completion, splittri is a handle having the newly inserted */ -/* intersection point as its origin, and endpoint1 as its destination. */ -/* */ -/*****************************************************************************/ - -void segmentintersection(splittri, splitshelle, endpoint2) -struct triedge *splittri; -struct edge *splitshelle; -point endpoint2; -{ - point endpoint1; - point torg, tdest; - point leftpoint, rightpoint; - point newpoint; - enum insertsiteresult success; - enum finddirectionresult collinear; - REAL ex, ey; - REAL tx, ty; - REAL etx, ety; - REAL split, denom; - int i; - triangle ptr; /* Temporary variable used by onext(). */ - - /* Find the other three segment endpoints. */ - apex(*splittri, endpoint1); - org(*splittri, torg); - dest(*splittri, tdest); - /* Segment intersection formulae; see the Antonio reference. */ - tx = tdest[0] - torg[0]; - ty = tdest[1] - torg[1]; - ex = endpoint2[0] - endpoint1[0]; - ey = endpoint2[1] - endpoint1[1]; - etx = torg[0] - endpoint2[0]; - ety = torg[1] - endpoint2[1]; - denom = ty * ex - tx * ey; - if (denom == 0.0) { - printf("Internal error in segmentintersection():"); - printf(" Attempt to find intersection of parallel segments.\n"); - internalerror(); - } - split = (ey * etx - ex * ety) / denom; - /* Create the new point. */ - newpoint = (point) poolalloc(&points); - /* Interpolate its coordinate and attributes. */ - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = torg[i] + split * (tdest[i] - torg[i]); - } - setpointmark(newpoint, mark(*splitshelle)); - if (verbose > 1) { - printf( - " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n", - torg[0], torg[1], tdest[0], tdest[1], newpoint[0], newpoint[1]); - } - /* Insert the intersection point. This should always succeed. */ - success = insertsite(newpoint, splittri, splitshelle, 0, 0); - if (success != SUCCESSFULPOINT) { - printf("Internal error in segmentintersection():\n"); - printf(" Failure to split a segment.\n"); - internalerror(); - } - if (steinerleft > 0) { - steinerleft--; - } - /* Inserting the point may have caused edge flips. We wish to rediscover */ - /* the edge connecting endpoint1 to the new intersection point. */ - collinear = finddirection(splittri, endpoint1); - dest(*splittri, rightpoint); - apex(*splittri, leftpoint); - if ((leftpoint[0] == endpoint1[0]) && (leftpoint[1] == endpoint1[1])) { - onextself(*splittri); - } else if ((rightpoint[0] != endpoint1[0]) || - (rightpoint[1] != endpoint1[1])) { - printf("Internal error in segmentintersection():\n"); - printf(" Topological inconsistency after splitting a segment.\n"); - internalerror(); - } - /* `splittri' should have destination endpoint1. */ -} - -/*****************************************************************************/ -/* */ -/* scoutsegment() Scout the first triangle on the path from one endpoint */ -/* to another, and check for completion (reaching the */ -/* second endpoint), a collinear point, and the */ -/* intersection of two segments. */ -/* */ -/* Returns one if the entire segment is successfully inserted, and zero if */ -/* the job must be finished by conformingedge() or constrainededge(). */ -/* */ -/* If the first triangle on the path has the second endpoint as its */ -/* destination or apex, a shell edge is inserted and the job is done. */ -/* */ -/* If the first triangle on the path has a destination or apex that lies on */ -/* the segment, a shell edge is inserted connecting the first endpoint to */ -/* the collinear point, and the search is continued from the collinear */ -/* point. */ -/* */ -/* If the first triangle on the path has a shell edge opposite its origin, */ -/* then there is a segment that intersects the segment being inserted. */ -/* Their intersection point is inserted, splitting the shell edge. */ -/* */ -/* Otherwise, return zero. */ -/* */ -/*****************************************************************************/ - -int scoutsegment(searchtri, endpoint2, newmark) -struct triedge *searchtri; -point endpoint2; -int newmark; -{ - struct triedge crosstri; - struct edge crossedge; - point leftpoint, rightpoint; - point endpoint1; - enum finddirectionresult collinear; - shelle sptr; /* Temporary variable used by tspivot(). */ - - collinear = finddirection(searchtri, endpoint2); - dest(*searchtri, rightpoint); - apex(*searchtri, leftpoint); - if (((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) || - ((rightpoint[0] == endpoint2[0]) && (rightpoint[1] == endpoint2[1]))) { - /* The segment is already an edge in the mesh. */ - if ((leftpoint[0] == endpoint2[0]) && (leftpoint[1] == endpoint2[1])) { - lprevself(*searchtri); - } - /* Insert a shell edge, if there isn't already one there. */ - insertshelle(searchtri, newmark); - return 1; - } else if (collinear == LEFTCOLLINEAR) { - /* We've collided with a point between the segment's endpoints. */ - /* Make the collinear point be the triangle's origin. */ - lprevself(*searchtri); - insertshelle(searchtri, newmark); - /* Insert the remainder of the segment. */ - return scoutsegment(searchtri, endpoint2, newmark); - } else if (collinear == RIGHTCOLLINEAR) { - /* We've collided with a point between the segment's endpoints. */ - insertshelle(searchtri, newmark); - /* Make the collinear point be the triangle's origin. */ - lnextself(*searchtri); - /* Insert the remainder of the segment. */ - return scoutsegment(searchtri, endpoint2, newmark); - } else { - lnext(*searchtri, crosstri); - tspivot(crosstri, crossedge); - /* Check for a crossing segment. */ - if (crossedge.sh == dummysh) { - return 0; - } else { - org(*searchtri, endpoint1); - /* Insert a point at the intersection. */ - segmentintersection(&crosstri, &crossedge, endpoint2); - triedgecopy(crosstri, *searchtri); - insertshelle(searchtri, newmark); - /* Insert the remainder of the segment. */ - return scoutsegment(searchtri, endpoint2, newmark); - } - } -} - -/*****************************************************************************/ -/* */ -/* conformingedge() Force a segment into a conforming Delaunay */ -/* triangulation by inserting a point at its midpoint, */ -/* and recursively forcing in the two half-segments if */ -/* necessary. */ -/* */ -/* Generates a sequence of edges connecting `endpoint1' to `endpoint2'. */ -/* `newmark' is the boundary marker of the segment, assigned to each new */ -/* splitting point and shell edge. */ -/* */ -/* Note that conformingedge() does not always maintain the conforming */ -/* Delaunay property. Once inserted, segments are locked into place; */ -/* points inserted later (to force other segments in) may render these */ -/* fixed segments non-Delaunay. The conforming Delaunay property will be */ -/* restored by enforcequality() by splitting encroached segments. */ -/* */ -/*****************************************************************************/ - -#ifndef REDUCED -#ifndef CDT_ONLY - -void conformingedge(endpoint1, endpoint2, newmark) -point endpoint1; -point endpoint2; -int newmark; -{ - struct triedge searchtri1, searchtri2; - struct edge brokenshelle; - point newpoint; - point midpoint1, midpoint2; - enum insertsiteresult success; - int result1, result2; - int i; - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose > 2) { - printf("Forcing segment into triangulation by recursive splitting:\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g)\n", endpoint1[0], endpoint1[1], - endpoint2[0], endpoint2[1]); - } - /* Create a new point to insert in the middle of the segment. */ - newpoint = (point) poolalloc(&points); - /* Interpolate coordinates and attributes. */ - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = 0.5 * (endpoint1[i] + endpoint2[i]); - } - setpointmark(newpoint, newmark); - /* Find a boundary triangle to search from. */ - searchtri1.tri = (triangle *) NULL; - /* Attempt to insert the new point. */ - success = insertsite(newpoint, &searchtri1, (struct edge *) NULL, 0, 0); - if (success == DUPLICATEPOINT) { - if (verbose > 2) { - printf(" Segment intersects existing point (%.12g, %.12g).\n", - newpoint[0], newpoint[1]); - } - /* Use the point that's already there. */ - pointdealloc(newpoint); - org(searchtri1, newpoint); - } else { - if (success == VIOLATINGPOINT) { - if (verbose > 2) { - printf(" Two segments intersect at (%.12g, %.12g).\n", - newpoint[0], newpoint[1]); - } - /* By fluke, we've landed right on another segment. Split it. */ - tspivot(searchtri1, brokenshelle); - success = insertsite(newpoint, &searchtri1, &brokenshelle, 0, 0); - if (success != SUCCESSFULPOINT) { - printf("Internal error in conformingedge():\n"); - printf(" Failure to split a segment.\n"); - internalerror(); - } - } - /* The point has been inserted successfully. */ - if (steinerleft > 0) { - steinerleft--; - } - } - triedgecopy(searchtri1, searchtri2); - result1 = scoutsegment(&searchtri1, endpoint1, newmark); - result2 = scoutsegment(&searchtri2, endpoint2, newmark); - if (!result1) { - /* The origin of searchtri1 may have changed if a collision with an */ - /* intervening vertex on the segment occurred. */ - org(searchtri1, midpoint1); - conformingedge(midpoint1, endpoint1, newmark); - } - if (!result2) { - /* The origin of searchtri2 may have changed if a collision with an */ - /* intervening vertex on the segment occurred. */ - org(searchtri2, midpoint2); - conformingedge(midpoint2, endpoint2, newmark); - } -} - -#endif /* not CDT_ONLY */ -#endif /* not REDUCED */ - -/*****************************************************************************/ -/* */ -/* delaunayfixup() Enforce the Delaunay condition at an edge, fanning out */ -/* recursively from an existing point. Pay special */ -/* attention to stacking inverted triangles. */ -/* */ -/* This is a support routine for inserting segments into a constrained */ -/* Delaunay triangulation. */ -/* */ -/* The origin of fixuptri is treated as if it has just been inserted, and */ -/* the local Delaunay condition needs to be enforced. It is only enforced */ -/* in one sector, however, that being the angular range defined by */ -/* fixuptri. */ -/* */ -/* This routine also needs to make decisions regarding the "stacking" of */ -/* triangles. (Read the description of constrainededge() below before */ -/* reading on here, so you understand the algorithm.) If the position of */ -/* the new point (the origin of fixuptri) indicates that the vertex before */ -/* it on the polygon is a reflex vertex, then "stack" the triangle by */ -/* doing nothing. (fixuptri is an inverted triangle, which is how stacked */ -/* triangles are identified.) */ -/* */ -/* Otherwise, check whether the vertex before that was a reflex vertex. */ -/* If so, perform an edge flip, thereby eliminating an inverted triangle */ -/* (popping it off the stack). The edge flip may result in the creation */ -/* of a new inverted triangle, depending on whether or not the new vertex */ -/* is visible to the vertex three edges behind on the polygon. */ -/* */ -/* If neither of the two vertices behind the new vertex are reflex */ -/* vertices, fixuptri and fartri, the triangle opposite it, are not */ -/* inverted; hence, ensure that the edge between them is locally Delaunay. */ -/* */ -/* `leftside' indicates whether or not fixuptri is to the left of the */ -/* segment being inserted. (Imagine that the segment is pointing up from */ -/* endpoint1 to endpoint2.) */ -/* */ -/*****************************************************************************/ - -void delaunayfixup(fixuptri, leftside) -struct triedge *fixuptri; -int leftside; -{ - struct triedge neartri; - struct triedge fartri; - struct edge faredge; - point nearpoint, leftpoint, rightpoint, farpoint; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - lnext(*fixuptri, neartri); - sym(neartri, fartri); - /* Check if the edge opposite the origin of fixuptri can be flipped. */ - if (fartri.tri == dummytri) { - return; - } - tspivot(neartri, faredge); - if (faredge.sh != dummysh) { - return; - } - /* Find all the relevant vertices. */ - apex(neartri, nearpoint); - org(neartri, leftpoint); - dest(neartri, rightpoint); - apex(fartri, farpoint); - /* Check whether the previous polygon vertex is a reflex vertex. */ - if (leftside) { - if (counterclockwise(nearpoint, leftpoint, farpoint) <= 0.0) { - /* leftpoint is a reflex vertex too. Nothing can */ - /* be done until a convex section is found. */ - return; - } - } else { - if (counterclockwise(farpoint, rightpoint, nearpoint) <= 0.0) { - /* rightpoint is a reflex vertex too. Nothing can */ - /* be done until a convex section is found. */ - return; - } - } - if (counterclockwise(rightpoint, leftpoint, farpoint) > 0.0) { - /* fartri is not an inverted triangle, and farpoint is not a reflex */ - /* vertex. As there are no reflex vertices, fixuptri isn't an */ - /* inverted triangle, either. Hence, test the edge between the */ - /* triangles to ensure it is locally Delaunay. */ - if (incircle(leftpoint, farpoint, rightpoint, nearpoint) <= 0.0) { - return; - } - /* Not locally Delaunay; go on to an edge flip. */ - } /* else fartri is inverted; remove it from the stack by flipping. */ - flip(&neartri); - lprevself(*fixuptri); /* Restore the origin of fixuptri after the flip. */ - /* Recursively process the two triangles that result from the flip. */ - delaunayfixup(fixuptri, leftside); - delaunayfixup(&fartri, leftside); -} - -/*****************************************************************************/ -/* */ -/* constrainededge() Force a segment into a constrained Delaunay */ -/* triangulation by deleting the triangles it */ -/* intersects, and triangulating the polygons that */ -/* form on each side of it. */ -/* */ -/* Generates a single edge connecting `endpoint1' to `endpoint2'. The */ -/* triangle `starttri' has `endpoint1' as its origin. `newmark' is the */ -/* boundary marker of the segment. */ -/* */ -/* To insert a segment, every triangle whose interior intersects the */ -/* segment is deleted. The union of these deleted triangles is a polygon */ -/* (which is not necessarily monotone, but is close enough), which is */ -/* divided into two polygons by the new segment. This routine's task is */ -/* to generate the Delaunay triangulation of these two polygons. */ -/* */ -/* You might think of this routine's behavior as a two-step process. The */ -/* first step is to walk from endpoint1 to endpoint2, flipping each edge */ -/* encountered. This step creates a fan of edges connected to endpoint1, */ -/* including the desired edge to endpoint2. The second step enforces the */ -/* Delaunay condition on each side of the segment in an incremental manner: */ -/* proceeding along the polygon from endpoint1 to endpoint2 (this is done */ -/* independently on each side of the segment), each vertex is "enforced" */ -/* as if it had just been inserted, but affecting only the previous */ -/* vertices. The result is the same as if the vertices had been inserted */ -/* in the order they appear on the polygon, so the result is Delaunay. */ -/* */ -/* In truth, constrainededge() interleaves these two steps. The procedure */ -/* walks from endpoint1 to endpoint2, and each time an edge is encountered */ -/* and flipped, the newly exposed vertex (at the far end of the flipped */ -/* edge) is "enforced" upon the previously flipped edges, usually affecting */ -/* only one side of the polygon (depending upon which side of the segment */ -/* the vertex falls on). */ -/* */ -/* The algorithm is complicated by the need to handle polygons that are not */ -/* convex. Although the polygon is not necessarily monotone, it can be */ -/* triangulated in a manner similar to the stack-based algorithms for */ -/* monotone polygons. For each reflex vertex (local concavity) of the */ -/* polygon, there will be an inverted triangle formed by one of the edge */ -/* flips. (An inverted triangle is one with negative area - that is, its */ -/* vertices are arranged in clockwise order - and is best thought of as a */ -/* wrinkle in the fabric of the mesh.) Each inverted triangle can be */ -/* thought of as a reflex vertex pushed on the stack, waiting to be fixed */ -/* later. */ -/* */ -/* A reflex vertex is popped from the stack when a vertex is inserted that */ -/* is visible to the reflex vertex. (However, if the vertex behind the */ -/* reflex vertex is not visible to the reflex vertex, a new inverted */ -/* triangle will take its place on the stack.) These details are handled */ -/* by the delaunayfixup() routine above. */ -/* */ -/*****************************************************************************/ - -void constrainededge(starttri, endpoint2, newmark) -struct triedge *starttri; -point endpoint2; -int newmark; -{ - struct triedge fixuptri, fixuptri2; - struct edge fixupedge; - point endpoint1; - point farpoint; - REAL area; - int collision; - int done; - triangle ptr; /* Temporary variable used by sym() and oprev(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - org(*starttri, endpoint1); - lnext(*starttri, fixuptri); - flip(&fixuptri); - /* `collision' indicates whether we have found a point directly */ - /* between endpoint1 and endpoint2. */ - collision = 0; - done = 0; - do { - org(fixuptri, farpoint); - /* `farpoint' is the extreme point of the polygon we are "digging" */ - /* to get from endpoint1 to endpoint2. */ - if ((farpoint[0] == endpoint2[0]) && (farpoint[1] == endpoint2[1])) { - oprev(fixuptri, fixuptri2); - /* Enforce the Delaunay condition around endpoint2. */ - delaunayfixup(&fixuptri, 0); - delaunayfixup(&fixuptri2, 1); - done = 1; - } else { - /* Check whether farpoint is to the left or right of the segment */ - /* being inserted, to decide which edge of fixuptri to dig */ - /* through next. */ - area = counterclockwise(endpoint1, endpoint2, farpoint); - if (area == 0.0) { - /* We've collided with a point between endpoint1 and endpoint2. */ - collision = 1; - oprev(fixuptri, fixuptri2); - /* Enforce the Delaunay condition around farpoint. */ - delaunayfixup(&fixuptri, 0); - delaunayfixup(&fixuptri2, 1); - done = 1; - } else { - if (area > 0.0) { /* farpoint is to the left of the segment. */ - oprev(fixuptri, fixuptri2); - /* Enforce the Delaunay condition around farpoint, on the */ - /* left side of the segment only. */ - delaunayfixup(&fixuptri2, 1); - /* Flip the edge that crosses the segment. After the edge is */ - /* flipped, one of its endpoints is the fan vertex, and the */ - /* destination of fixuptri is the fan vertex. */ - lprevself(fixuptri); - } else { /* farpoint is to the right of the segment. */ - delaunayfixup(&fixuptri, 0); - /* Flip the edge that crosses the segment. After the edge is */ - /* flipped, one of its endpoints is the fan vertex, and the */ - /* destination of fixuptri is the fan vertex. */ - oprevself(fixuptri); - } - /* Check for two intersecting segments. */ - tspivot(fixuptri, fixupedge); - if (fixupedge.sh == dummysh) { - flip(&fixuptri); /* May create an inverted triangle on the left. */ - } else { - /* We've collided with a segment between endpoint1 and endpoint2. */ - collision = 1; - /* Insert a point at the intersection. */ - segmentintersection(&fixuptri, &fixupedge, endpoint2); - done = 1; - } - } - } - } while (!done); - /* Insert a shell edge to make the segment permanent. */ - insertshelle(&fixuptri, newmark); - /* If there was a collision with an interceding vertex, install another */ - /* segment connecting that vertex with endpoint2. */ - if (collision) { - /* Insert the remainder of the segment. */ - if (!scoutsegment(&fixuptri, endpoint2, newmark)) { - constrainededge(&fixuptri, endpoint2, newmark); - } - } -} - -/*****************************************************************************/ -/* */ -/* insertsegment() Insert a PSLG segment into a triangulation. */ -/* */ -/*****************************************************************************/ - -void insertsegment(endpoint1, endpoint2, newmark) -point endpoint1; -point endpoint2; -int newmark; -{ - struct triedge searchtri1, searchtri2; - triangle encodedtri; - point checkpoint; - triangle ptr; /* Temporary variable used by sym(). */ - - if (verbose > 1) { - printf(" Connecting (%.12g, %.12g) to (%.12g, %.12g).\n", - endpoint1[0], endpoint1[1], endpoint2[0], endpoint2[1]); - } - - /* Find a triangle whose origin is the segment's first endpoint. */ - checkpoint = (point) NULL; - encodedtri = point2tri(endpoint1); - if (encodedtri != (triangle) NULL) { - decode(encodedtri, searchtri1); - org(searchtri1, checkpoint); - } - if (checkpoint != endpoint1) { - /* Find a boundary triangle to search from. */ - searchtri1.tri = dummytri; - searchtri1.orient = 0; - symself(searchtri1); - /* Search for the segment's first endpoint by point location. */ - if (locate(endpoint1, &searchtri1) != ONVERTEX) { - printf( - "Internal error in insertsegment(): Unable to locate PSLG point\n"); - printf(" (%.12g, %.12g) in triangulation.\n", - endpoint1[0], endpoint1[1]); - internalerror(); - } - } - /* Remember this triangle to improve subsequent point location. */ - triedgecopy(searchtri1, recenttri); - /* Scout the beginnings of a path from the first endpoint */ - /* toward the second. */ - if (scoutsegment(&searchtri1, endpoint2, newmark)) { - /* The segment was easily inserted. */ - return; - } - /* The first endpoint may have changed if a collision with an intervening */ - /* vertex on the segment occurred. */ - org(searchtri1, endpoint1); - - /* Find a triangle whose origin is the segment's second endpoint. */ - checkpoint = (point) NULL; - encodedtri = point2tri(endpoint2); - if (encodedtri != (triangle) NULL) { - decode(encodedtri, searchtri2); - org(searchtri2, checkpoint); - } - if (checkpoint != endpoint2) { - /* Find a boundary triangle to search from. */ - searchtri2.tri = dummytri; - searchtri2.orient = 0; - symself(searchtri2); - /* Search for the segment's second endpoint by point location. */ - if (locate(endpoint2, &searchtri2) != ONVERTEX) { - printf( - "Internal error in insertsegment(): Unable to locate PSLG point\n"); - printf(" (%.12g, %.12g) in triangulation.\n", - endpoint2[0], endpoint2[1]); - internalerror(); - } - } - /* Remember this triangle to improve subsequent point location. */ - triedgecopy(searchtri2, recenttri); - /* Scout the beginnings of a path from the second endpoint */ - /* toward the first. */ - if (scoutsegment(&searchtri2, endpoint1, newmark)) { - /* The segment was easily inserted. */ - return; - } - /* The second endpoint may have changed if a collision with an intervening */ - /* vertex on the segment occurred. */ - org(searchtri2, endpoint2); - -#ifndef REDUCED -#ifndef CDT_ONLY - if (splitseg) { - /* Insert vertices to force the segment into the triangulation. */ - conformingedge(endpoint1, endpoint2, newmark); - } else { -#endif /* not CDT_ONLY */ -#endif /* not REDUCED */ - /* Insert the segment directly into the triangulation. */ - constrainededge(&searchtri1, endpoint2, newmark); -#ifndef REDUCED -#ifndef CDT_ONLY - } -#endif /* not CDT_ONLY */ -#endif /* not REDUCED */ -} - -/*****************************************************************************/ -/* */ -/* markhull() Cover the convex hull of a triangulation with shell edges. */ -/* */ -/*****************************************************************************/ - -void markhull() -{ - struct triedge hulltri; - struct triedge nexttri; - struct triedge starttri; - triangle ptr; /* Temporary variable used by sym() and oprev(). */ - - /* Find a triangle handle on the hull. */ - hulltri.tri = dummytri; - hulltri.orient = 0; - symself(hulltri); - /* Remember where we started so we know when to stop. */ - triedgecopy(hulltri, starttri); - /* Go once counterclockwise around the convex hull. */ - do { - /* Create a shell edge if there isn't already one here. */ - insertshelle(&hulltri, 1); - /* To find the next hull edge, go clockwise around the next vertex. */ - lnextself(hulltri); - oprev(hulltri, nexttri); - while (nexttri.tri != dummytri) { - triedgecopy(nexttri, hulltri); - oprev(hulltri, nexttri); - } - } while (!triedgeequal(hulltri, starttri)); -} - -/*****************************************************************************/ -/* */ -/* formskeleton() Create the shell edges of a triangulation, including */ -/* PSLG edges and edges on the convex hull. */ -/* */ -/* The PSLG edges are read from a .poly file. The return value is the */ -/* number of segments in the file. */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -int formskeleton(segmentlist, segmentmarkerlist, numberofsegments) -int *segmentlist; -int *segmentmarkerlist; -int numberofsegments; - -#else /* not TRILIBRARY */ - -int formskeleton(polyfile, polyfilename) -FILE *polyfile; -char *polyfilename; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - char polyfilename[6]; - int index; -#else /* not TRILIBRARY */ - char inputline[INPUTLINESIZE]; - char *stringptr; -#endif /* not TRILIBRARY */ - point endpoint1, endpoint2; - int segments; - int segmentmarkers; - int end1, end2; - int boundmarker; - int i; - - if (poly) { - if (!quiet) { - printf("Inserting segments into Delaunay triangulation.\n"); - } -#ifdef TRILIBRARY - strcpy(polyfilename, "input"); - segments = numberofsegments; - segmentmarkers = segmentmarkerlist != (int *) NULL; - index = 0; -#else /* not TRILIBRARY */ - /* Read the segments from a .poly file. */ - /* Read number of segments and number of boundary markers. */ - stringptr = readline(inputline, polyfile, polyfilename); - segments = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - segmentmarkers = 0; - } else { - segmentmarkers = (int) strtol (stringptr, &stringptr, 0); - } -#endif /* not TRILIBRARY */ - /* If segments are to be inserted, compute a mapping */ - /* from points to triangles. */ - if (segments > 0) { - if (verbose) { - printf(" Inserting PSLG segments.\n"); - } - makepointmap(); - } - - boundmarker = 0; - /* Read and insert the segments. */ - for (i = 1; i <= segments; i++) { -#ifdef TRILIBRARY - end1 = segmentlist[index++]; - end2 = segmentlist[index++]; - if (segmentmarkers) { - boundmarker = segmentmarkerlist[i - 1]; - } -#else /* not TRILIBRARY */ - stringptr = readline(inputline, polyfile, inpolyfilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d has no endpoints in %s.\n", i, - polyfilename); - exit(1); - } else { - end1 = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Segment %d is missing its second endpoint in %s.\n", i, - polyfilename); - exit(1); - } else { - end2 = (int) strtol (stringptr, &stringptr, 0); - } - if (segmentmarkers) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - boundmarker = 0; - } else { - boundmarker = (int) strtol (stringptr, &stringptr, 0); - } - } -#endif /* not TRILIBRARY */ - if ((end1 < firstnumber) || (end1 >= firstnumber + inpoints)) { - if (!quiet) { - printf("Warning: Invalid first endpoint of segment %d in %s.\n", i, - polyfilename); - } - } else if ((end2 < firstnumber) || (end2 >= firstnumber + inpoints)) { - if (!quiet) { - printf("Warning: Invalid second endpoint of segment %d in %s.\n", i, - polyfilename); - } - } else { - endpoint1 = getpoint(end1); - endpoint2 = getpoint(end2); - if ((endpoint1[0] == endpoint2[0]) && (endpoint1[1] == endpoint2[1])) { - if (!quiet) { - printf("Warning: Endpoints of segment %d are coincident in %s.\n", - i, polyfilename); - } - } else { - insertsegment(endpoint1, endpoint2, boundmarker); - } - } - } - } else { - segments = 0; - } - if (convex || !poly) { - /* Enclose the convex hull with shell edges. */ - if (verbose) { - printf(" Enclosing convex hull with segments.\n"); - } - markhull(); - } - return segments; -} - -/** **/ -/** **/ -/********* Segment (shell edge) insertion ends here *********/ - -/********* Carving out holes and concavities begins here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* infecthull() Virally infect all of the triangles of the convex hull */ -/* that are not protected by shell edges. Where there are */ -/* shell edges, set boundary markers as appropriate. */ -/* */ -/*****************************************************************************/ - -void infecthull() -{ - struct triedge hulltri; - struct triedge nexttri; - struct triedge starttri; - struct edge hulledge; - triangle **deadtri; - point horg, hdest; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose) { - printf(" Marking concavities (external triangles) for elimination.\n"); - } - /* Find a triangle handle on the hull. */ - hulltri.tri = dummytri; - hulltri.orient = 0; - symself(hulltri); - /* Remember where we started so we know when to stop. */ - triedgecopy(hulltri, starttri); - /* Go once counterclockwise around the convex hull. */ - do { - /* Ignore triangles that are already infected. */ - if (!infected(hulltri)) { - /* Is the triangle protected by a shell edge? */ - tspivot(hulltri, hulledge); - if (hulledge.sh == dummysh) { - /* The triangle is not protected; infect it. */ - infect(hulltri); - deadtri = (triangle **) poolalloc(&viri); - *deadtri = hulltri.tri; - } else { - /* The triangle is protected; set boundary markers if appropriate. */ - if (mark(hulledge) == 0) { - setmark(hulledge, 1); - org(hulltri, horg); - dest(hulltri, hdest); - if (pointmark(horg) == 0) { - setpointmark(horg, 1); - } - if (pointmark(hdest) == 0) { - setpointmark(hdest, 1); - } - } - } - } - /* To find the next hull edge, go clockwise around the next vertex. */ - lnextself(hulltri); - oprev(hulltri, nexttri); - while (nexttri.tri != dummytri) { - triedgecopy(nexttri, hulltri); - oprev(hulltri, nexttri); - } - } while (!triedgeequal(hulltri, starttri)); -} - -/*****************************************************************************/ -/* */ -/* plague() Spread the virus from all infected triangles to any neighbors */ -/* not protected by shell edges. Delete all infected triangles. */ -/* */ -/* This is the procedure that actually creates holes and concavities. */ -/* */ -/* This procedure operates in two phases. The first phase identifies all */ -/* the triangles that will die, and marks them as infected. They are */ -/* marked to ensure that each triangle is added to the virus pool only */ -/* once, so the procedure will terminate. */ -/* */ -/* The second phase actually eliminates the infected triangles. It also */ -/* eliminates orphaned points. */ -/* */ -/*****************************************************************************/ - -void plague() -{ - struct triedge testtri; - struct triedge neighbor; - triangle **virusloop; - triangle **deadtri; - struct edge neighborshelle; - point testpoint; - point norg, ndest; - point deadorg, deaddest, deadapex; - int killorg; - triangle ptr; /* Temporary variable used by sym() and onext(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose) { - printf(" Marking neighbors of marked triangles.\n"); - } - /* Loop through all the infected triangles, spreading the virus to */ - /* their neighbors, then to their neighbors' neighbors. */ - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - /* A triangle is marked as infected by messing with one of its shell */ - /* edges, setting it to an illegal value. Hence, we have to */ - /* temporarily uninfect this triangle so that we can examine its */ - /* adjacent shell edges. */ - uninfect(testtri); - if (verbose > 2) { - /* Assign the triangle an orientation for convenience in */ - /* checking its points. */ - testtri.orient = 0; - org(testtri, deadorg); - dest(testtri, deaddest); - apex(testtri, deadapex); - printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - deadorg[0], deadorg[1], deaddest[0], deaddest[1], - deadapex[0], deadapex[1]); - } - /* Check each of the triangle's three neighbors. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - /* Find the neighbor. */ - sym(testtri, neighbor); - /* Check for a shell between the triangle and its neighbor. */ - tspivot(testtri, neighborshelle); - /* Check if the neighbor is nonexistent or already infected. */ - if ((neighbor.tri == dummytri) || infected(neighbor)) { - if (neighborshelle.sh != dummysh) { - /* There is a shell edge separating the triangle from its */ - /* neighbor, but both triangles are dying, so the shell */ - /* edge dies too. */ - shelledealloc(neighborshelle.sh); - if (neighbor.tri != dummytri) { - /* Make sure the shell edge doesn't get deallocated again */ - /* later when the infected neighbor is visited. */ - uninfect(neighbor); - tsdissolve(neighbor); - infect(neighbor); - } - } - } else { /* The neighbor exists and is not infected. */ - if (neighborshelle.sh == dummysh) { - /* There is no shell edge protecting the neighbor, so */ - /* the neighbor becomes infected. */ - if (verbose > 2) { - org(neighbor, deadorg); - dest(neighbor, deaddest); - apex(neighbor, deadapex); - printf( - " Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - deadorg[0], deadorg[1], deaddest[0], deaddest[1], - deadapex[0], deadapex[1]); - } - infect(neighbor); - /* Ensure that the neighbor's neighbors will be infected. */ - deadtri = (triangle **) poolalloc(&viri); - *deadtri = neighbor.tri; - } else { /* The neighbor is protected by a shell edge. */ - /* Remove this triangle from the shell edge. */ - stdissolve(neighborshelle); - /* The shell edge becomes a boundary. Set markers accordingly. */ - if (mark(neighborshelle) == 0) { - setmark(neighborshelle, 1); - } - org(neighbor, norg); - dest(neighbor, ndest); - if (pointmark(norg) == 0) { - setpointmark(norg, 1); - } - if (pointmark(ndest) == 0) { - setpointmark(ndest, 1); - } - } - } - } - /* Remark the triangle as infected, so it doesn't get added to the */ - /* virus pool again. */ - infect(testtri); - virusloop = (triangle **) traverse(&viri); - } - - if (verbose) { - printf(" Deleting marked triangles.\n"); - } - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - - /* Check each of the three corners of the triangle for elimination. */ - /* This is done by walking around each point, checking if it is */ - /* still connected to at least one live triangle. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - org(testtri, testpoint); - /* Check if the point has already been tested. */ - if (testpoint != (point) NULL) { - killorg = 1; - /* Mark the corner of the triangle as having been tested. */ - setorg(testtri, NULL); - /* Walk counterclockwise about the point. */ - onext(testtri, neighbor); - /* Stop upon reaching a boundary or the starting triangle. */ - while ((neighbor.tri != dummytri) - && (!triedgeequal(neighbor, testtri))) { - if (infected(neighbor)) { - /* Mark the corner of this triangle as having been tested. */ - setorg(neighbor, NULL); - } else { - /* A live triangle. The point survives. */ - killorg = 0; - } - /* Walk counterclockwise about the point. */ - onextself(neighbor); - } - /* If we reached a boundary, we must walk clockwise as well. */ - if (neighbor.tri == dummytri) { - /* Walk clockwise about the point. */ - oprev(testtri, neighbor); - /* Stop upon reaching a boundary. */ - while (neighbor.tri != dummytri) { - if (infected(neighbor)) { - /* Mark the corner of this triangle as having been tested. */ - setorg(neighbor, NULL); - } else { - /* A live triangle. The point survives. */ - killorg = 0; - } - /* Walk clockwise about the point. */ - oprevself(neighbor); - } - } - if (killorg) { - if (verbose > 1) { - printf(" Deleting point (%.12g, %.12g)\n", - testpoint[0], testpoint[1]); - } - pointdealloc(testpoint); - } - } - } - - /* Record changes in the number of boundary edges, and disconnect */ - /* dead triangles from their neighbors. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - sym(testtri, neighbor); - if (neighbor.tri == dummytri) { - /* There is no neighboring triangle on this edge, so this edge */ - /* is a boundary edge. This triangle is being deleted, so this */ - /* boundary edge is deleted. */ - hullsize--; - } else { - /* Disconnect the triangle from its neighbor. */ - dissolve(neighbor); - /* There is a neighboring triangle on this edge, so this edge */ - /* becomes a boundary edge when this triangle is deleted. */ - hullsize++; - } - } - /* Return the dead triangle to the pool of triangles. */ - triangledealloc(testtri.tri); - virusloop = (triangle **) traverse(&viri); - } - /* Empty the virus pool. */ - poolrestart(&viri); -} - -/*****************************************************************************/ -/* */ -/* regionplague() Spread regional attributes and/or area constraints */ -/* (from a .poly file) throughout the mesh. */ -/* */ -/* This procedure operates in two phases. The first phase spreads an */ -/* attribute and/or an area constraint through a (segment-bounded) region. */ -/* The triangles are marked to ensure that each triangle is added to the */ -/* virus pool only once, so the procedure will terminate. */ -/* */ -/* The second phase uninfects all infected triangles, returning them to */ -/* normal. */ -/* */ -/*****************************************************************************/ - -void regionplague(attribute, area) -REAL attribute; -REAL area; -{ - struct triedge testtri; - struct triedge neighbor; - triangle **virusloop; - triangle **regiontri; - struct edge neighborshelle; - point regionorg, regiondest, regionapex; - triangle ptr; /* Temporary variable used by sym() and onext(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (verbose > 1) { - printf(" Marking neighbors of marked triangles.\n"); - } - /* Loop through all the infected triangles, spreading the attribute */ - /* and/or area constraint to their neighbors, then to their neighbors' */ - /* neighbors. */ - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - /* A triangle is marked as infected by messing with one of its shell */ - /* edges, setting it to an illegal value. Hence, we have to */ - /* temporarily uninfect this triangle so that we can examine its */ - /* adjacent shell edges. */ - uninfect(testtri); - if (regionattrib) { - /* Set an attribute. */ - setelemattribute(testtri, eextras, attribute); - } - if (vararea) { - /* Set an area constraint. */ - setareabound(testtri, area); - } - if (verbose > 2) { - /* Assign the triangle an orientation for convenience in */ - /* checking its points. */ - testtri.orient = 0; - org(testtri, regionorg); - dest(testtri, regiondest); - apex(testtri, regionapex); - printf(" Checking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - regionorg[0], regionorg[1], regiondest[0], regiondest[1], - regionapex[0], regionapex[1]); - } - /* Check each of the triangle's three neighbors. */ - for (testtri.orient = 0; testtri.orient < 3; testtri.orient++) { - /* Find the neighbor. */ - sym(testtri, neighbor); - /* Check for a shell between the triangle and its neighbor. */ - tspivot(testtri, neighborshelle); - /* Make sure the neighbor exists, is not already infected, and */ - /* isn't protected by a shell edge. */ - if ((neighbor.tri != dummytri) && !infected(neighbor) - && (neighborshelle.sh == dummysh)) { - if (verbose > 2) { - org(neighbor, regionorg); - dest(neighbor, regiondest); - apex(neighbor, regionapex); - printf(" Marking (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - regionorg[0], regionorg[1], regiondest[0], regiondest[1], - regionapex[0], regionapex[1]); - } - /* Infect the neighbor. */ - infect(neighbor); - /* Ensure that the neighbor's neighbors will be infected. */ - regiontri = (triangle **) poolalloc(&viri); - *regiontri = neighbor.tri; - } - } - /* Remark the triangle as infected, so it doesn't get added to the */ - /* virus pool again. */ - infect(testtri); - virusloop = (triangle **) traverse(&viri); - } - - /* Uninfect all triangles. */ - if (verbose > 1) { - printf(" Unmarking marked triangles.\n"); - } - traversalinit(&viri); - virusloop = (triangle **) traverse(&viri); - while (virusloop != (triangle **) NULL) { - testtri.tri = *virusloop; - uninfect(testtri); - virusloop = (triangle **) traverse(&viri); - } - /* Empty the virus pool. */ - poolrestart(&viri); -} - -/*****************************************************************************/ -/* */ -/* carveholes() Find the holes and infect them. Find the area */ -/* constraints and infect them. Infect the convex hull. */ -/* Spread the infection and kill triangles. Spread the */ -/* area constraints. */ -/* */ -/* This routine mainly calls other routines to carry out all these */ -/* functions. */ -/* */ -/*****************************************************************************/ - -void carveholes(holelist, holes, regionlist, regions) -REAL *holelist; -int holes; -REAL *regionlist; -int regions; -{ - struct triedge searchtri; - struct triedge triangleloop; - struct triedge *regiontris; - triangle **holetri; - triangle **regiontri; - point searchorg, searchdest; - enum locateresult intersect; - int i; - triangle ptr; /* Temporary variable used by sym(). */ - - if (!(quiet || (noholes && convex))) { - printf("Removing unwanted triangles.\n"); - if (verbose && (holes > 0)) { - printf(" Marking holes for elimination.\n"); - } - } - - if (regions > 0) { - /* Allocate storage for the triangles in which region points fall. */ - regiontris = (struct triedge *) malloc(regions * sizeof(struct triedge)); - if (regiontris == (struct triedge *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - - if (((holes > 0) && !noholes) || !convex || (regions > 0)) { - /* Initialize a pool of viri to be used for holes, concavities, */ - /* regional attributes, and/or regional area constraints. */ - poolinit(&viri, sizeof(triangle *), VIRUSPERBLOCK, POINTER, 0); - } - - if (!convex) { - /* Mark as infected any unprotected triangles on the boundary. */ - /* This is one way by which concavities are created. */ - infecthull(); - } - - if ((holes > 0) && !noholes) { - /* Infect each triangle in which a hole lies. */ - for (i = 0; i < 2 * holes; i += 2) { - /* Ignore holes that aren't within the bounds of the mesh. */ - if ((holelist[i] >= xmin) && (holelist[i] <= xmax) - && (holelist[i + 1] >= ymin) && (holelist[i + 1] <= ymax)) { - /* Start searching from some triangle on the outer boundary. */ - searchtri.tri = dummytri; - searchtri.orient = 0; - symself(searchtri); - /* Ensure that the hole is to the left of this boundary edge; */ - /* otherwise, locate() will falsely report that the hole */ - /* falls within the starting triangle. */ - org(searchtri, searchorg); - dest(searchtri, searchdest); - if (counterclockwise(searchorg, searchdest, &holelist[i]) > 0.0) { - /* Find a triangle that contains the hole. */ - intersect = locate(&holelist[i], &searchtri); - if ((intersect != OUTSIDE) && (!infected(searchtri))) { - /* Infect the triangle. This is done by marking the triangle */ - /* as infect and including the triangle in the virus pool. */ - infect(searchtri); - holetri = (triangle **) poolalloc(&viri); - *holetri = searchtri.tri; - } - } - } - } - } - - /* Now, we have to find all the regions BEFORE we carve the holes, because */ - /* locate() won't work when the triangulation is no longer convex. */ - /* (Incidentally, this is the reason why regional attributes and area */ - /* constraints can't be used when refining a preexisting mesh, which */ - /* might not be convex; they can only be used with a freshly */ - /* triangulated PSLG.) */ - if (regions > 0) { - /* Find the starting triangle for each region. */ - for (i = 0; i < regions; i++) { - regiontris[i].tri = dummytri; - /* Ignore region points that aren't within the bounds of the mesh. */ - if ((regionlist[4 * i] >= xmin) && (regionlist[4 * i] <= xmax) && - (regionlist[4 * i + 1] >= ymin) && (regionlist[4 * i + 1] <= ymax)) { - /* Start searching from some triangle on the outer boundary. */ - searchtri.tri = dummytri; - searchtri.orient = 0; - symself(searchtri); - /* Ensure that the region point is to the left of this boundary */ - /* edge; otherwise, locate() will falsely report that the */ - /* region point falls within the starting triangle. */ - org(searchtri, searchorg); - dest(searchtri, searchdest); - if (counterclockwise(searchorg, searchdest, ®ionlist[4 * i]) > - 0.0) { - /* Find a triangle that contains the region point. */ - intersect = locate(®ionlist[4 * i], &searchtri); - if ((intersect != OUTSIDE) && (!infected(searchtri))) { - /* Record the triangle for processing after the */ - /* holes have been carved. */ - triedgecopy(searchtri, regiontris[i]); - } - } - } - } - } - - if (viri.items > 0) { - /* Carve the holes and concavities. */ - plague(); - } - /* The virus pool should be empty now. */ - - if (regions > 0) { - if (!quiet) { - if (regionattrib) { - if (vararea) { - printf("Spreading regional attributes and area constraints.\n"); - } else { - printf("Spreading regional attributes.\n"); - } - } else { - printf("Spreading regional area constraints.\n"); - } - } - if (regionattrib && !refine) { - /* Assign every triangle a regional attribute of zero. */ - traversalinit(&triangles); - triangleloop.orient = 0; - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - setelemattribute(triangleloop, eextras, 0.0); - triangleloop.tri = triangletraverse(); - } - } - for (i = 0; i < regions; i++) { - if (regiontris[i].tri != dummytri) { - /* Make sure the triangle under consideration still exists. */ - /* It may have been eaten by the virus. */ - if (regiontris[i].tri[3] != (triangle) NULL) { - /* Put one triangle in the virus pool. */ - infect(regiontris[i]); - regiontri = (triangle **) poolalloc(&viri); - *regiontri = regiontris[i].tri; - /* Apply one region's attribute and/or area constraint. */ - regionplague(regionlist[4 * i + 2], regionlist[4 * i + 3]); - /* The virus pool should be empty now. */ - } - } - } - if (regionattrib && !refine) { - /* Note the fact that each triangle has an additional attribute. */ - eextras++; - } - } - - /* Free up memory. */ - if (((holes > 0) && !noholes) || !convex || (regions > 0)) { - pooldeinit(&viri); - } - if (regions > 0) { - free(regiontris); - } -} - -/** **/ -/** **/ -/********* Carving out holes and concavities ends here *********/ - -/********* Mesh quality maintenance begins here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* tallyencs() Traverse the entire list of shell edges, check each edge */ -/* to see if it is encroached. If so, add it to the list. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void tallyencs() -{ - struct edge edgeloop; - int dummy; - - traversalinit(&shelles); - edgeloop.shorient = 0; - edgeloop.sh = shelletraverse(); - while (edgeloop.sh != (shelle *) NULL) { - /* If the segment is encroached, add it to the list. */ - dummy = checkedge4encroach(&edgeloop); - edgeloop.sh = shelletraverse(); - } -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* precisionerror() Print an error message for precision problems. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void precisionerror() -{ - printf("Try increasing the area criterion and/or reducing the minimum\n"); - printf(" allowable angle so that tiny triangles are not created.\n"); -#ifdef SINGLE - printf("Alternatively, try recompiling me with double precision\n"); - printf(" arithmetic (by removing \"#define SINGLE\" from the\n"); - printf(" source file or \"-DSINGLE\" from the makefile).\n"); -#endif /* SINGLE */ -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* repairencs() Find and repair all the encroached segments. */ -/* */ -/* Encroached segments are repaired by splitting them by inserting a point */ -/* at or near their centers. */ -/* */ -/* `flaws' is a flag that specifies whether one should take note of new */ -/* encroached segments and bad triangles that result from inserting points */ -/* to repair existing encroached segments. */ -/* */ -/* When a segment is split, the two resulting subsegments are always */ -/* tested to see if they are encroached upon, regardless of the value */ -/* of `flaws'. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void repairencs(flaws) -int flaws; -{ - struct triedge enctri; - struct triedge testtri; - struct edge *encloop; - struct edge testsh; - point eorg, edest; - point newpoint; - enum insertsiteresult success; - REAL segmentlength, nearestpoweroftwo; - REAL split; - int acuteorg, acutedest; - int dummy; - int i; - triangle ptr; /* Temporary variable used by stpivot(). */ - shelle sptr; /* Temporary variable used by snext(). */ - - while ((badsegments.items > 0) && (steinerleft != 0)) { - traversalinit(&badsegments); - encloop = badsegmenttraverse(); - while ((encloop != (struct edge *) NULL) && (steinerleft != 0)) { - /* To decide where to split a segment, we need to know if the */ - /* segment shares an endpoint with an adjacent segment. */ - /* The concern is that, if we simply split every encroached */ - /* segment in its center, two adjacent segments with a small */ - /* angle between them might lead to an infinite loop; each */ - /* point added to split one segment will encroach upon the */ - /* other segment, which must then be split with a point that */ - /* will encroach upon the first segment, and so on forever. */ - /* To avoid this, imagine a set of concentric circles, whose */ - /* radii are powers of two, about each segment endpoint. */ - /* These concentric circles determine where the segment is */ - /* split. (If both endpoints are shared with adjacent */ - /* segments, split the segment in the middle, and apply the */ - /* concentric shells for later splittings.) */ - - /* Is the origin shared with another segment? */ - stpivot(*encloop, enctri); - lnext(enctri, testtri); - tspivot(testtri, testsh); - acuteorg = testsh.sh != dummysh; - /* Is the destination shared with another segment? */ - lnextself(testtri); - tspivot(testtri, testsh); - acutedest = testsh.sh != dummysh; - /* Now, check the other side of the segment, if there's a triangle */ - /* there. */ - sym(enctri, testtri); - if (testtri.tri != dummytri) { - /* Is the destination shared with another segment? */ - lnextself(testtri); - tspivot(testtri, testsh); - acutedest = acutedest || (testsh.sh != dummysh); - /* Is the origin shared with another segment? */ - lnextself(testtri); - tspivot(testtri, testsh); - acuteorg = acuteorg || (testsh.sh != dummysh); - } - - sorg(*encloop, eorg); - sdest(*encloop, edest); - /* Use the concentric circles if exactly one endpoint is shared */ - /* with another adjacent segment. */ - if (acuteorg ^ acutedest) { - segmentlength = sqrt((edest[0] - eorg[0]) * (edest[0] - eorg[0]) - + (edest[1] - eorg[1]) * (edest[1] - eorg[1])); - /* Find the power of two nearest the segment's length. */ - nearestpoweroftwo = 1.0; - while (segmentlength > SQUAREROOTTWO * nearestpoweroftwo) { - nearestpoweroftwo *= 2.0; - } - while (segmentlength < (0.5 * SQUAREROOTTWO) * nearestpoweroftwo) { - nearestpoweroftwo *= 0.5; - } - /* Where do we split the segment? */ - split = 0.5 * nearestpoweroftwo / segmentlength; - if (acutedest) { - split = 1.0 - split; - } - } else { - /* If we're not worried about adjacent segments, split */ - /* this segment in the middle. */ - split = 0.5; - } - - /* Create the new point. */ - newpoint = (point) poolalloc(&points); - /* Interpolate its coordinate and attributes. */ - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = (1.0 - split) * eorg[i] + split * edest[i]; - } - setpointmark(newpoint, mark(*encloop)); - if (verbose > 1) { - printf( - " Splitting edge (%.12g, %.12g) (%.12g, %.12g) at (%.12g, %.12g).\n", - eorg[0], eorg[1], edest[0], edest[1], newpoint[0], newpoint[1]); - } - /* Check whether the new point lies on an endpoint. */ - if (((newpoint[0] == eorg[0]) && (newpoint[1] == eorg[1])) - || ((newpoint[0] == edest[0]) && (newpoint[1] == edest[1]))) { - printf("Error: Ran out of precision at (%.12g, %.12g).\n", - newpoint[0], newpoint[1]); - printf("I attempted to split a segment to a smaller size than can\n"); - printf(" be accommodated by the finite precision of floating point\n" - ); - printf(" arithmetic.\n"); - precisionerror(); - exit(1); - } - /* Insert the splitting point. This should always succeed. */ - success = insertsite(newpoint, &enctri, encloop, flaws, flaws); - if ((success != SUCCESSFULPOINT) && (success != ENCROACHINGPOINT)) { - printf("Internal error in repairencs():\n"); - printf(" Failure to split a segment.\n"); - internalerror(); - } - if (steinerleft > 0) { - steinerleft--; - } - /* Check the two new subsegments to see if they're encroached. */ - dummy = checkedge4encroach(encloop); - snextself(*encloop); - dummy = checkedge4encroach(encloop); - - badsegmentdealloc(encloop); - encloop = badsegmenttraverse(); - } - } -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* tallyfaces() Test every triangle in the mesh for quality measures. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void tallyfaces() -{ - struct triedge triangleloop; - - if (verbose) { - printf(" Making a list of bad triangles.\n"); - } - traversalinit(&triangles); - triangleloop.orient = 0; - triangleloop.tri = triangletraverse(); - while (triangleloop.tri != (triangle *) NULL) { - /* If the triangle is bad, enqueue it. */ - testtriangle(&triangleloop); - triangleloop.tri = triangletraverse(); - } -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* findcircumcenter() Find the circumcenter of a triangle. */ -/* */ -/* The result is returned both in terms of x-y coordinates and xi-eta */ -/* coordinates. The xi-eta coordinate system is defined in terms of the */ -/* triangle: the origin of the triangle is the origin of the coordinate */ -/* system; the destination of the triangle is one unit along the xi axis; */ -/* and the apex of the triangle is one unit along the eta axis. */ -/* */ -/* The return value indicates which edge of the triangle is shortest. */ -/* */ -/*****************************************************************************/ - -enum circumcenterresult findcircumcenter(torg, tdest, tapex, circumcenter, - xi, eta) -point torg; -point tdest; -point tapex; -point circumcenter; -REAL *xi; -REAL *eta; -{ - REAL xdo, ydo, xao, yao, xad, yad; - REAL dodist, aodist, addist; - REAL denominator; - REAL dx, dy; - - circumcentercount++; - - /* Compute the circumcenter of the triangle. */ - xdo = tdest[0] - torg[0]; - ydo = tdest[1] - torg[1]; - xao = tapex[0] - torg[0]; - yao = tapex[1] - torg[1]; - dodist = xdo * xdo + ydo * ydo; - aodist = xao * xao + yao * yao; - if (noexact) { - denominator = (REAL)(0.5 / (xdo * yao - xao * ydo)); - } else { - /* Use the counterclockwise() routine to ensure a positive (and */ - /* reasonably accurate) result, avoiding any possibility of */ - /* division by zero. */ - denominator = (REAL)(0.5 / counterclockwise(tdest, tapex, torg)); - /* Don't count the above as an orientation test. */ - counterclockcount--; - } - circumcenter[0] = torg[0] - (ydo * aodist - yao * dodist) * denominator; - circumcenter[1] = torg[1] + (xdo * aodist - xao * dodist) * denominator; - - /* To interpolate point attributes for the new point inserted at */ - /* the circumcenter, define a coordinate system with a xi-axis, */ - /* directed from the triangle's origin to its destination, and */ - /* an eta-axis, directed from its origin to its apex. */ - /* Calculate the xi and eta coordinates of the circumcenter. */ - dx = circumcenter[0] - torg[0]; - dy = circumcenter[1] - torg[1]; - *xi = (REAL)((dx * yao - xao * dy) * (2.0 * denominator)); - *eta = (REAL)((xdo * dy - dx * ydo) * (2.0 * denominator)); - - xad = tapex[0] - tdest[0]; - yad = tapex[1] - tdest[1]; - addist = xad * xad + yad * yad; - if ((addist < dodist) && (addist < aodist)) { - return OPPOSITEORG; - } else if (dodist < aodist) { - return OPPOSITEAPEX; - } else { - return OPPOSITEDEST; - } -} - -/*****************************************************************************/ -/* */ -/* splittriangle() Inserts a point at the circumcenter of a triangle. */ -/* Deletes the newly inserted point if it encroaches upon */ -/* a segment. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void splittriangle(badtri) -struct badface *badtri; -{ - point borg, bdest, bapex; - point newpoint; - REAL xi, eta; - enum insertsiteresult success; - enum circumcenterresult shortedge; - int errorflag; - int i; - - org(badtri->badfacetri, borg); - dest(badtri->badfacetri, bdest); - apex(badtri->badfacetri, bapex); - /* Make sure that this triangle is still the same triangle it was */ - /* when it was tested and determined to be of bad quality. */ - /* Subsequent transformations may have made it a different triangle. */ - if ((borg == badtri->faceorg) && (bdest == badtri->facedest) && - (bapex == badtri->faceapex)) { - if (verbose > 1) { - printf(" Splitting this triangle at its circumcenter:\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", borg[0], - borg[1], bdest[0], bdest[1], bapex[0], bapex[1]); - } - errorflag = 0; - /* Create a new point at the triangle's circumcenter. */ - newpoint = (point) poolalloc(&points); - shortedge = findcircumcenter(borg, bdest, bapex, newpoint, &xi, &eta); - /* Check whether the new point lies on a triangle vertex. */ - if (((newpoint[0] == borg[0]) && (newpoint[1] == borg[1])) - || ((newpoint[0] == bdest[0]) && (newpoint[1] == bdest[1])) - || ((newpoint[0] == bapex[0]) && (newpoint[1] == bapex[1]))) { - if (!quiet) { - printf("Warning: New point (%.12g, %.12g) falls on existing vertex.\n" - , newpoint[0], newpoint[1]); - errorflag = 1; - } - pointdealloc(newpoint); - } else { - for (i = 2; i < 2 + nextras; i++) { - /* Interpolate the point attributes at the circumcenter. */ - newpoint[i] = borg[i] + xi * (bdest[i] - borg[i]) - + eta * (bapex[i] - borg[i]); - } - /* The new point must be in the interior, and have a marker of zero. */ - setpointmark(newpoint, 0); - /* Ensure that the handle `badtri->badfacetri' represents the shortest */ - /* edge of the triangle. This ensures that the circumcenter must */ - /* fall to the left of this edge, so point location will work. */ - if (shortedge == OPPOSITEORG) { - lnextself(badtri->badfacetri); - } else if (shortedge == OPPOSITEDEST) { - lprevself(badtri->badfacetri); - } - /* Insert the circumcenter, searching from the edge of the triangle, */ - /* and maintain the Delaunay property of the triangulation. */ - success = insertsite(newpoint, &(badtri->badfacetri), - (struct edge *) NULL, 1, 1); - if (success == SUCCESSFULPOINT) { - if (steinerleft > 0) { - steinerleft--; - } - } else if (success == ENCROACHINGPOINT) { - /* If the newly inserted point encroaches upon a segment, delete it. */ - deletesite(&(badtri->badfacetri)); - } else if (success == VIOLATINGPOINT) { - /* Failed to insert the new point, but some segment was */ - /* marked as being encroached. */ - pointdealloc(newpoint); - } else { /* success == DUPLICATEPOINT */ - /* Failed to insert the new point because a vertex is already there. */ - if (!quiet) { - printf( - "Warning: New point (%.12g, %.12g) falls on existing vertex.\n" - , newpoint[0], newpoint[1]); - errorflag = 1; - } - pointdealloc(newpoint); - } - } - if (errorflag) { - if (verbose) { - printf(" The new point is at the circumcenter of triangle\n"); - printf(" (%.12g, %.12g) (%.12g, %.12g) (%.12g, %.12g)\n", - borg[0], borg[1], bdest[0], bdest[1], bapex[0], bapex[1]); - } - printf("This probably means that I am trying to refine triangles\n"); - printf(" to a smaller size than can be accommodated by the finite\n"); - printf(" precision of floating point arithmetic. (You can be\n"); - printf(" sure of this if I fail to terminate.)\n"); - precisionerror(); - } - } - /* Return the bad triangle to the pool. */ - pooldealloc(&badtriangles, (VOID *) badtri); -} - -#endif /* not CDT_ONLY */ - -/*****************************************************************************/ -/* */ -/* enforcequality() Remove all the encroached edges and bad triangles */ -/* from the triangulation. */ -/* */ -/*****************************************************************************/ - -#ifndef CDT_ONLY - -void enforcequality() -{ - int i; - - if (!quiet) { - printf("Adding Steiner points to enforce quality.\n"); - } - /* Initialize the pool of encroached segments. */ - poolinit(&badsegments, sizeof(struct edge), BADSEGMENTPERBLOCK, POINTER, 0); - if (verbose) { - printf(" Looking for encroached segments.\n"); - } - /* Test all segments to see if they're encroached. */ - tallyencs(); - if (verbose && (badsegments.items > 0)) { - printf(" Splitting encroached segments.\n"); - } - /* Note that steinerleft == -1 if an unlimited number */ - /* of Steiner points is allowed. */ - while ((badsegments.items > 0) && (steinerleft != 0)) { - /* Fix the segments without noting newly encroached segments or */ - /* bad triangles. The reason we don't want to note newly */ - /* encroached segments is because some encroached segments are */ - /* likely to be noted multiple times, and would then be blindly */ - /* split multiple times. I should fix that some time. */ - repairencs(0); - /* Now, find all the segments that became encroached while adding */ - /* points to split encroached segments. */ - tallyencs(); - } - /* At this point, if we haven't run out of Steiner points, the */ - /* triangulation should be (conforming) Delaunay. */ - - /* Next, we worry about enforcing triangle quality. */ - if ((minangle > 0.0) || vararea || fixedarea) { - /* Initialize the pool of bad triangles. */ - poolinit(&badtriangles, sizeof(struct badface), BADTRIPERBLOCK, POINTER, - 0); - /* Initialize the queues of bad triangles. */ - for (i = 0; i < 64; i++) { - queuefront[i] = (struct badface *) NULL; - queuetail[i] = &queuefront[i]; - } - /* Test all triangles to see if they're bad. */ - tallyfaces(); - if (verbose) { - printf(" Splitting bad triangles.\n"); - } - while ((badtriangles.items > 0) && (steinerleft != 0)) { - /* Fix one bad triangle by inserting a point at its circumcenter. */ - splittriangle(dequeuebadtri()); - /* Fix any encroached segments that may have resulted. Record */ - /* any new bad triangles or encroached segments that result. */ - if (badsegments.items > 0) { - repairencs(1); - } - } - } - /* At this point, if we haven't run out of Steiner points, the */ - /* triangulation should be (conforming) Delaunay and have no */ - /* low-quality triangles. */ - - /* Might we have run out of Steiner points too soon? */ - if (!quiet && (badsegments.items > 0) && (steinerleft == 0)) { - printf("\nWarning: I ran out of Steiner points, but the mesh has\n"); - if (badsegments.items == 1) { - printf(" an encroached segment, and therefore might not be truly\n"); - } else { - printf(" %ld encroached segments, and therefore might not be truly\n", - badsegments.items); - } - printf(" Delaunay. If the Delaunay property is important to you,\n"); - printf(" try increasing the number of Steiner points (controlled by\n"); - printf(" the -S switch) slightly and try again.\n\n"); - } -} - -#endif /* not CDT_ONLY */ - -/** **/ -/** **/ -/********* Mesh quality maintenance ends here *********/ - -/*****************************************************************************/ -/* */ -/* highorder() Create extra nodes for quadratic subparametric elements. */ -/* */ -/*****************************************************************************/ - -void highorder() -{ - struct triedge triangleloop, trisym; - struct edge checkmark; - point newpoint; - point torg, tdest; - int i; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - - if (!quiet) { - printf("Adding vertices for second-order triangles.\n"); - } - /* The following line ensures that dead items in the pool of nodes */ - /* cannot be allocated for the extra nodes associated with high */ - /* order elements. This ensures that the primary nodes (at the */ - /* corners of elements) will occur earlier in the output files, and */ - /* have lower indices, than the extra nodes. */ - points.deaditemstack = (VOID *) NULL; - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - /* To loop over the set of edges, loop over all triangles, and look at */ - /* the three edges of each triangle. If there isn't another triangle */ - /* adjacent to the edge, operate on the edge. If there is another */ - /* adjacent triangle, operate on the edge only if the current triangle */ - /* has a smaller pointer than its neighbor. This way, each edge is */ - /* considered only once. */ - while (triangleloop.tri != (triangle *) NULL) { - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - sym(triangleloop, trisym); - if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) { - org(triangleloop, torg); - dest(triangleloop, tdest); - /* Create a new node in the middle of the edge. Interpolate */ - /* its attributes. */ - newpoint = (point) poolalloc(&points); - for (i = 0; i < 2 + nextras; i++) { - newpoint[i] = (REAL)(0.5 * (torg[i] + tdest[i])); - } - /* Set the new node's marker to zero or one, depending on */ - /* whether it lies on a boundary. */ - setpointmark(newpoint, trisym.tri == dummytri); - if (useshelles) { - tspivot(triangleloop, checkmark); - /* If this edge is a segment, transfer the marker to the new node. */ - if (checkmark.sh != dummysh) { - setpointmark(newpoint, mark(checkmark)); - } - } - if (verbose > 1) { - printf(" Creating (%.12g, %.12g).\n", newpoint[0], newpoint[1]); - } - /* Record the new node in the (one or two) adjacent elements. */ - triangleloop.tri[highorderindex + triangleloop.orient] = - (triangle) newpoint; - if (trisym.tri != dummytri) { - trisym.tri[highorderindex + trisym.orient] = (triangle) newpoint; - } - } - } - triangleloop.tri = triangletraverse(); - } -} - -/********* File I/O routines begin here *********/ -/** **/ -/** **/ - -/*****************************************************************************/ -/* */ -/* readline() Read a nonempty line from a file. */ -/* */ -/* A line is considered "nonempty" if it contains something that looks like */ -/* a number. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -char *readline(string, infile, infilename) -char *string; -FILE *infile; -char *infilename; -{ - char *result; - - /* Search for something that looks like a number. */ - do { - result = fgets(string, INPUTLINESIZE, infile); - if (result == (char *) NULL) { - printf(" Error: Unexpected end of file in %s.\n", infilename); - exit(1); - } - /* Skip anything that doesn't look like a number, a comment, */ - /* or the end of a line. */ - while ((*result != '\0') && (*result != '#') - && (*result != '.') && (*result != '+') && (*result != '-') - && ((*result < '0') || (*result > '9'))) { - result++; - } - /* If it's a comment or end of line, read another line and try again. */ - } while ((*result == '#') || (*result == '\0')); - return result; -} - -#endif /* not TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* findfield() Find the next field of a string. */ -/* */ -/* Jumps past the current field by searching for whitespace, then jumps */ -/* past the whitespace to find the next field. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -char *findfield(string) -char *string; -{ - char *result; - - result = string; - /* Skip the current field. Stop upon reaching whitespace. */ - while ((*result != '\0') && (*result != '#') - && (*result != ' ') && (*result != '\t')) { - result++; - } - /* Now skip the whitespace and anything else that doesn't look like a */ - /* number, a comment, or the end of a line. */ - while ((*result != '\0') && (*result != '#') - && (*result != '.') && (*result != '+') && (*result != '-') - && ((*result < '0') || (*result > '9'))) { - result++; - } - /* Check for a comment (prefixed with `#'). */ - if (*result == '#') { - *result = '\0'; - } - return result; -} - -#endif /* not TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* readnodes() Read the points from a file, which may be a .node or .poly */ -/* file. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -void readnodes(nodefilename, polyfilename, polyfile) -char *nodefilename; -char *polyfilename; -FILE **polyfile; -{ - FILE *infile; - point pointloop; - char inputline[INPUTLINESIZE]; - char *stringptr; - char *infilename; - REAL x, y; - int firstnode; - int nodemarkers; - int currentmarker; - int i, j; - - if (poly) { - /* Read the points from a .poly file. */ - if (!quiet) { - printf("Opening %s.\n", polyfilename); - } - *polyfile = fopen(polyfilename, "r"); - if (*polyfile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", polyfilename); - exit(1); - } - /* Read number of points, number of dimensions, number of point */ - /* attributes, and number of boundary markers. */ - stringptr = readline(inputline, *polyfile, polyfilename); - inpoints = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - mesh_dim = 2; - } else { - mesh_dim = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nextras = 0; - } else { - nextras = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nodemarkers = 0; - } else { - nodemarkers = (int) strtol (stringptr, &stringptr, 0); - } - if (inpoints > 0) { - infile = *polyfile; - infilename = polyfilename; - readnodefile = 0; - } else { - /* If the .poly file claims there are zero points, that means that */ - /* the points should be read from a separate .node file. */ - readnodefile = 1; - infilename = innodefilename; - } - } else { - readnodefile = 1; - infilename = innodefilename; - *polyfile = (FILE *) NULL; - } - - if (readnodefile) { - /* Read the points from a .node file. */ - if (!quiet) { - printf("Opening %s.\n", innodefilename); - } - infile = fopen(innodefilename, "r"); - if (infile == (FILE *) NULL) { - printf(" Error: Cannot access file %s.\n", innodefilename); - exit(1); - } - /* Read number of points, number of dimensions, number of point */ - /* attributes, and number of boundary markers. */ - stringptr = readline(inputline, infile, innodefilename); - inpoints = (int) strtol (stringptr, &stringptr, 0); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - mesh_dim = 2; - } else { - mesh_dim = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nextras = 0; - } else { - nextras = (int) strtol (stringptr, &stringptr, 0); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - nodemarkers = 0; - } else { - nodemarkers = (int) strtol (stringptr, &stringptr, 0); - } - } - - if (inpoints < 3) { - printf("Error: Input must have at least three input points.\n"); - exit(1); - } - if (mesh_dim != 2) { - printf("Error: Triangle only works with two-dimensional meshes.\n"); - exit(1); - } - - initializepointpool(); - - /* Read the points. */ - for (i = 0; i < inpoints; i++) { - pointloop = (point) poolalloc(&points); - stringptr = readline(inputline, infile, infilename); - if (i == 0) { - firstnode = (int) strtol (stringptr, &stringptr, 0); - if ((firstnode == 0) || (firstnode == 1)) { - firstnumber = firstnode; - } - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Point %d has no x coordinate.\n", firstnumber + i); - exit(1); - } - x = (REAL) strtod(stringptr, &stringptr); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Point %d has no y coordinate.\n", firstnumber + i); - exit(1); - } - y = (REAL) strtod(stringptr, &stringptr); - pointloop[0] = x; - pointloop[1] = y; - /* Read the point attributes. */ - for (j = 2; j < 2 + nextras; j++) { - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - pointloop[j] = 0.0; - } else { - pointloop[j] = (REAL) strtod(stringptr, &stringptr); - } - } - if (nodemarkers) { - /* Read a point marker. */ - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - setpointmark(pointloop, 0); - } else { - currentmarker = (int) strtol (stringptr, &stringptr, 0); - setpointmark(pointloop, currentmarker); - } - } else { - /* If no markers are specified in the file, they default to zero. */ - setpointmark(pointloop, 0); - } - /* Determine the smallest and largest x and y coordinates. */ - if (i == 0) { - xmin = xmax = x; - ymin = ymax = y; - } else { - xmin = (x < xmin) ? x : xmin; - xmax = (x > xmax) ? x : xmax; - ymin = (y < ymin) ? y : ymin; - ymax = (y > ymax) ? y : ymax; - } - } - if (readnodefile) { - fclose(infile); - } - - /* Nonexistent x value used as a flag to mark circle events in sweepline */ - /* Delaunay algorithm. */ - xminextreme = 10 * xmin - 9 * xmax; -} - -#endif /* not TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* transfernodes() Read the points from memory. */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -void transfernodes(pointlist, pointattriblist, pointmarkerlist, numberofpoints, - numberofpointattribs) -REAL *pointlist; -REAL *pointattriblist; -int *pointmarkerlist; -int numberofpoints; -int numberofpointattribs; -{ - point pointloop; - REAL x, y; - int i, j; - int coordindex; - int attribindex; - - inpoints = numberofpoints; - mesh_dim = 2; - nextras = numberofpointattribs; - readnodefile = 0; - if (inpoints < 3) { - printf("Error: Input must have at least three input points.\n"); - exit(1); - } - - initializepointpool(); - - /* Read the points. */ - coordindex = 0; - attribindex = 0; - for (i = 0; i < inpoints; i++) { - pointloop = (point) poolalloc(&points); - /* Read the point coordinates. */ - x = pointloop[0] = pointlist[coordindex++]; - y = pointloop[1] = pointlist[coordindex++]; - /* Read the point attributes. */ - for (j = 0; j < numberofpointattribs; j++) { - pointloop[2 + j] = pointattriblist[attribindex++]; - } - if (pointmarkerlist != (int *) NULL) { - /* Read a point marker. */ - setpointmark(pointloop, pointmarkerlist[i]); - } else { - /* If no markers are specified, they default to zero. */ - setpointmark(pointloop, 0); - } - x = pointloop[0]; - y = pointloop[1]; - /* Determine the smallest and largest x and y coordinates. */ - if (i == 0) { - xmin = xmax = x; - ymin = ymax = y; - } else { - xmin = (x < xmin) ? x : xmin; - xmax = (x > xmax) ? x : xmax; - ymin = (y < ymin) ? y : ymin; - ymax = (y > ymax) ? y : ymax; - } - } - - /* Nonexistent x value used as a flag to mark circle events in sweepline */ - /* Delaunay algorithm. */ - xminextreme = 10 * xmin - 9 * xmax; -} - -#endif /* TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* readholes() Read the holes, and possibly regional attributes and area */ -/* constraints, from a .poly file. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -void readholes(polyfile, polyfilename, hlist, holes, rlist, regions) -FILE *polyfile; -char *polyfilename; -REAL **hlist; -int *holes; -REAL **rlist; -int *regions; -{ - REAL *holelist; - REAL *regionlist; - char inputline[INPUTLINESIZE]; - char *stringptr; - int index; - int i; - - /* Read the holes. */ - stringptr = readline(inputline, polyfile, polyfilename); - *holes = (int) strtol (stringptr, &stringptr, 0); - if (*holes > 0) { - holelist = (REAL *) malloc(2 * *holes * sizeof(REAL)); - *hlist = holelist; - if (holelist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - for (i = 0; i < 2 * *holes; i += 2) { - stringptr = readline(inputline, polyfile, polyfilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Hole %d has no x coordinate.\n", - firstnumber + (i >> 1)); - exit(1); - } else { - holelist[i] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Hole %d has no y coordinate.\n", - firstnumber + (i >> 1)); - exit(1); - } else { - holelist[i + 1] = (REAL) strtod(stringptr, &stringptr); - } - } - } else { - *hlist = (REAL *) NULL; - } - -#ifndef CDT_ONLY - if ((regionattrib || vararea) && !refine) { - /* Read the area constraints. */ - stringptr = readline(inputline, polyfile, polyfilename); - *regions = (int) strtol (stringptr, &stringptr, 0); - if (*regions > 0) { - regionlist = (REAL *) malloc(4 * *regions * sizeof(REAL)); - *rlist = regionlist; - if (regionlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - index = 0; - for (i = 0; i < *regions; i++) { - stringptr = readline(inputline, polyfile, polyfilename); - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Region %d has no x coordinate.\n", - firstnumber + i); - exit(1); - } else { - regionlist[index++] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf("Error: Region %d has no y coordinate.\n", - firstnumber + i); - exit(1); - } else { - regionlist[index++] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - printf( - "Error: Region %d has no region attribute or area constraint.\n", - firstnumber + i); - exit(1); - } else { - regionlist[index++] = (REAL) strtod(stringptr, &stringptr); - } - stringptr = findfield(stringptr); - if (*stringptr == '\0') { - regionlist[index] = regionlist[index - 1]; - } else { - regionlist[index] = (REAL) strtod(stringptr, &stringptr); - } - index++; - } - } - } else { - /* Set `*regions' to zero to avoid an accidental free() later. */ - *regions = 0; - *rlist = (REAL *) NULL; - } -#endif /* not CDT_ONLY */ - - fclose(polyfile); -} - -#endif /* not TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* finishfile() Write the command line to the output file so the user */ -/* can remember how the file was generated. Close the file. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -void finishfile(outfile, argc, argv) -FILE *outfile; -int argc; -char **argv; -{ - int i; - - fprintf(outfile, "# Generated by"); - for (i = 0; i < argc; i++) { - fprintf(outfile, " "); - fputs(argv[i], outfile); - } - fprintf(outfile, "\n"); - fclose(outfile); -} - -#endif /* not TRILIBRARY */ - -/*****************************************************************************/ -/* */ -/* writenodes() Number the points and write them to a .node file. */ -/* */ -/* To save memory, the point numbers are written over the shell markers */ -/* after the points are written to a file. */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -void writenodes(pointlist, pointattriblist, pointmarkerlist) -REAL **pointlist; -REAL **pointattriblist; -int **pointmarkerlist; - -#else /* not TRILIBRARY */ - -void writenodes(nodefilename, argc, argv) -char *nodefilename; -int argc; -char **argv; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - REAL *plist; - REAL *palist; - int *pmlist; - int coordindex; - int attribindex; -#else /* not TRILIBRARY */ - FILE *outfile; -#endif /* not TRILIBRARY */ - point pointloop; - int pointnumber; - int i; - -#ifdef TRILIBRARY - if (!quiet) { - printf("Writing points.\n"); - } - /* Allocate memory for output points if necessary. */ - if (*pointlist == (REAL *) NULL) { - *pointlist = (REAL *) malloc(points.items * 2 * sizeof(REAL)); - if (*pointlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output point attributes if necessary. */ - if ((nextras > 0) && (*pointattriblist == (REAL *) NULL)) { - *pointattriblist = (REAL *) malloc(points.items * nextras * sizeof(REAL)); - if (*pointattriblist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output point markers if necessary. */ - if (!nobound && (*pointmarkerlist == (int *) NULL)) { - *pointmarkerlist = (int *) malloc(points.items * sizeof(int)); - if (*pointmarkerlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - plist = *pointlist; - palist = *pointattriblist; - pmlist = *pointmarkerlist; - coordindex = 0; - attribindex = 0; -#else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", nodefilename); - } - outfile = fopen(nodefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", nodefilename); - exit(1); - } - /* Number of points, number of dimensions, number of point attributes, */ - /* and number of boundary markers (zero or one). */ - fprintf(outfile, "%ld %d %d %d\n", points.items, mesh_dim, nextras, - 1 - nobound); -#endif /* not TRILIBRARY */ - - traversalinit(&points); - pointloop = pointtraverse(); - pointnumber = firstnumber; - while (pointloop != (point) NULL) { -#ifdef TRILIBRARY - /* X and y coordinates. */ - plist[coordindex++] = pointloop[0]; - plist[coordindex++] = pointloop[1]; - /* Point attributes. */ - for (i = 0; i < nextras; i++) { - palist[attribindex++] = pointloop[2 + i]; - } - if (!nobound) { - /* Copy the boundary marker. */ - pmlist[pointnumber - firstnumber] = pointmark(pointloop); - } -#else /* not TRILIBRARY */ - /* Point number, x and y coordinates. */ - fprintf(outfile, "%4d %.17g %.17g", pointnumber, pointloop[0], - pointloop[1]); - for (i = 0; i < nextras; i++) { - /* Write an attribute. */ - fprintf(outfile, " %.17g", pointloop[i + 2]); - } - if (nobound) { - fprintf(outfile, "\n"); - } else { - /* Write the boundary marker. */ - fprintf(outfile, " %d\n", pointmark(pointloop)); - } -#endif /* not TRILIBRARY */ - - setpointmark(pointloop, pointnumber); - pointloop = pointtraverse(); - pointnumber++; - } - -#ifndef TRILIBRARY - finishfile(outfile, argc, argv); -#endif /* not TRILIBRARY */ -} - -/*****************************************************************************/ -/* */ -/* numbernodes() Number the points. */ -/* */ -/* Each point is assigned a marker equal to its number. */ -/* */ -/* Used when writenodes() is not called because no .node file is written. */ -/* */ -/*****************************************************************************/ - -void numbernodes() -{ - point pointloop; - int pointnumber; - - traversalinit(&points); - pointloop = pointtraverse(); - pointnumber = firstnumber; - while (pointloop != (point) NULL) { - setpointmark(pointloop, pointnumber); - pointloop = pointtraverse(); - pointnumber++; - } -} - -/*****************************************************************************/ -/* */ -/* writeelements() Write the triangles to an .ele file. */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -void writeelements(trianglelist, triangleattriblist) -int **trianglelist; -REAL **triangleattriblist; - -#else /* not TRILIBRARY */ - -void writeelements(elefilename, argc, argv) -char *elefilename; -int argc; -char **argv; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - int *tlist; - REAL *talist; - int pointindex; - int attribindex; -#else /* not TRILIBRARY */ - FILE *outfile; -#endif /* not TRILIBRARY */ - struct triedge triangleloop; - point p1, p2, p3; - point mid1, mid2, mid3; - int elementnumber; - int i; - -#ifdef TRILIBRARY - if (!quiet) { - printf("Writing triangles.\n"); - } - /* Allocate memory for output triangles if necessary. */ - if (*trianglelist == (int *) NULL) { - *trianglelist = (int *) malloc(triangles.items * - ((order + 1) * (order + 2) / 2) * sizeof(int)); - if (*trianglelist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output triangle attributes if necessary. */ - if ((eextras > 0) && (*triangleattriblist == (REAL *) NULL)) { - *triangleattriblist = (REAL *) malloc(triangles.items * eextras * - sizeof(REAL)); - if (*triangleattriblist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - tlist = *trianglelist; - talist = *triangleattriblist; - pointindex = 0; - attribindex = 0; -#else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", elefilename); - } - outfile = fopen(elefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", elefilename); - exit(1); - } - /* Number of triangles, points per triangle, attributes per triangle. */ - fprintf(outfile, "%ld %d %d\n", triangles.items, - (order + 1) * (order + 2) / 2, eextras); -#endif /* not TRILIBRARY */ - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, p1); - dest(triangleloop, p2); - apex(triangleloop, p3); - if (order == 1) { -#ifdef TRILIBRARY - tlist[pointindex++] = pointmark(p1); - tlist[pointindex++] = pointmark(p2); - tlist[pointindex++] = pointmark(p3); -#else /* not TRILIBRARY */ - /* Triangle number, indices for three points. */ - fprintf(outfile, "%4d %4d %4d %4d", elementnumber, - pointmark(p1), pointmark(p2), pointmark(p3)); -#endif /* not TRILIBRARY */ - } else { - mid1 = (point) triangleloop.tri[highorderindex + 1]; - mid2 = (point) triangleloop.tri[highorderindex + 2]; - mid3 = (point) triangleloop.tri[highorderindex]; -#ifdef TRILIBRARY - tlist[pointindex++] = pointmark(p1); - tlist[pointindex++] = pointmark(p2); - tlist[pointindex++] = pointmark(p3); - tlist[pointindex++] = pointmark(mid1); - tlist[pointindex++] = pointmark(mid2); - tlist[pointindex++] = pointmark(mid3); -#else /* not TRILIBRARY */ - /* Triangle number, indices for six points. */ - fprintf(outfile, "%4d %4d %4d %4d %4d %4d %4d", elementnumber, - pointmark(p1), pointmark(p2), pointmark(p3), pointmark(mid1), - pointmark(mid2), pointmark(mid3)); -#endif /* not TRILIBRARY */ - } - -#ifdef TRILIBRARY - for (i = 0; i < eextras; i++) { - talist[attribindex++] = elemattribute(triangleloop, i); - } -#else /* not TRILIBRARY */ - for (i = 0; i < eextras; i++) { - fprintf(outfile, " %.17g", elemattribute(triangleloop, i)); - } - fprintf(outfile, "\n"); -#endif /* not TRILIBRARY */ - - triangleloop.tri = triangletraverse(); - elementnumber++; - } - -#ifndef TRILIBRARY - finishfile(outfile, argc, argv); -#endif /* not TRILIBRARY */ -} - -/*****************************************************************************/ -/* */ -/* writepoly() Write the segments and holes to a .poly file. */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -void writepoly(segmentlist, segmentmarkerlist) -int **segmentlist; -int **segmentmarkerlist; - -#else /* not TRILIBRARY */ - -void writepoly(polyfilename, holelist, holes, regionlist, regions, argc, argv) -char *polyfilename; -REAL *holelist; -int holes; -REAL *regionlist; -int regions; -int argc; -char **argv; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - int *slist; - int *smlist; - int index; -#else /* not TRILIBRARY */ - FILE *outfile; - int i; -#endif /* not TRILIBRARY */ - struct edge shelleloop; - point endpoint1, endpoint2; - int shellenumber; - -#ifdef TRILIBRARY - if (!quiet) { - printf("Writing segments.\n"); - } - /* Allocate memory for output segments if necessary. */ - if (*segmentlist == (int *) NULL) { - *segmentlist = (int *) malloc(shelles.items * 2 * sizeof(int)); - if (*segmentlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for output segment markers if necessary. */ - if (!nobound && (*segmentmarkerlist == (int *) NULL)) { - *segmentmarkerlist = (int *) malloc(shelles.items * sizeof(int)); - if (*segmentmarkerlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - slist = *segmentlist; - smlist = *segmentmarkerlist; - index = 0; -#else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", polyfilename); - } - outfile = fopen(polyfilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", polyfilename); - exit(1); - } - /* The zero indicates that the points are in a separate .node file. */ - /* Followed by number of dimensions, number of point attributes, */ - /* and number of boundary markers (zero or one). */ - fprintf(outfile, "%d %d %d %d\n", 0, mesh_dim, nextras, 1 - nobound); - /* Number of segments, number of boundary markers (zero or one). */ - fprintf(outfile, "%ld %d\n", shelles.items, 1 - nobound); -#endif /* not TRILIBRARY */ - - traversalinit(&shelles); - shelleloop.sh = shelletraverse(); - shelleloop.shorient = 0; - shellenumber = firstnumber; - while (shelleloop.sh != (shelle *) NULL) { - sorg(shelleloop, endpoint1); - sdest(shelleloop, endpoint2); -#ifdef TRILIBRARY - /* Copy indices of the segment's two endpoints. */ - slist[index++] = pointmark(endpoint1); - slist[index++] = pointmark(endpoint2); - if (!nobound) { - /* Copy the boundary marker. */ - smlist[shellenumber - firstnumber] = mark(shelleloop); - } -#else /* not TRILIBRARY */ - /* Segment number, indices of its two endpoints, and possibly a marker. */ - if (nobound) { - fprintf(outfile, "%4d %4d %4d\n", shellenumber, - pointmark(endpoint1), pointmark(endpoint2)); - } else { - fprintf(outfile, "%4d %4d %4d %4d\n", shellenumber, - pointmark(endpoint1), pointmark(endpoint2), mark(shelleloop)); - } -#endif /* not TRILIBRARY */ - - shelleloop.sh = shelletraverse(); - shellenumber++; - } - -#ifndef TRILIBRARY -#ifndef CDT_ONLY - fprintf(outfile, "%d\n", holes); - if (holes > 0) { - for (i = 0; i < holes; i++) { - /* Hole number, x and y coordinates. */ - fprintf(outfile, "%4d %.17g %.17g\n", firstnumber + i, - holelist[2 * i], holelist[2 * i + 1]); - } - } - if (regions > 0) { - fprintf(outfile, "%d\n", regions); - for (i = 0; i < regions; i++) { - /* Region number, x and y coordinates, attribute, maximum area. */ - fprintf(outfile, "%4d %.17g %.17g %.17g %.17g\n", firstnumber + i, - regionlist[4 * i], regionlist[4 * i + 1], - regionlist[4 * i + 2], regionlist[4 * i + 3]); - } - } -#endif /* not CDT_ONLY */ - - finishfile(outfile, argc, argv); -#endif /* not TRILIBRARY */ -} - -/*****************************************************************************/ -/* */ -/* writeedges() Write the edges to a .edge file. */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -void writeedges(edgelist, edgemarkerlist) -int **edgelist; -int **edgemarkerlist; - -#else /* not TRILIBRARY */ - -void writeedges(edgefilename, argc, argv) -char *edgefilename; -int argc; -char **argv; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - int *elist; - int *emlist; - int index; -#else /* not TRILIBRARY */ - FILE *outfile; -#endif /* not TRILIBRARY */ - struct triedge triangleloop, trisym; - struct edge checkmark; - point p1, p2; - int edgenumber; - triangle ptr; /* Temporary variable used by sym(). */ - shelle sptr; /* Temporary variable used by tspivot(). */ - -#ifdef TRILIBRARY - if (!quiet) { - printf("Writing edges.\n"); - } - /* Allocate memory for edges if necessary. */ - if (*edgelist == (int *) NULL) { - *edgelist = (int *) malloc(edges * 2 * sizeof(int)); - if (*edgelist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for edge markers if necessary. */ - if (!nobound && (*edgemarkerlist == (int *) NULL)) { - *edgemarkerlist = (int *) malloc(edges * sizeof(int)); - if (*edgemarkerlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - elist = *edgelist; - emlist = *edgemarkerlist; - index = 0; -#else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", edgefilename); - } - outfile = fopen(edgefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", edgefilename); - exit(1); - } - /* Number of edges, number of boundary markers (zero or one). */ - fprintf(outfile, "%ld %d\n", edges, 1 - nobound); -#endif /* not TRILIBRARY */ - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - edgenumber = firstnumber; - /* To loop over the set of edges, loop over all triangles, and look at */ - /* the three edges of each triangle. If there isn't another triangle */ - /* adjacent to the edge, operate on the edge. If there is another */ - /* adjacent triangle, operate on the edge only if the current triangle */ - /* has a smaller pointer than its neighbor. This way, each edge is */ - /* considered only once. */ - while (triangleloop.tri != (triangle *) NULL) { - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - sym(triangleloop, trisym); - if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) { - org(triangleloop, p1); - dest(triangleloop, p2); -#ifdef TRILIBRARY - elist[index++] = pointmark(p1); - elist[index++] = pointmark(p2); -#endif /* TRILIBRARY */ - if (nobound) { -#ifndef TRILIBRARY - /* Edge number, indices of two endpoints. */ - fprintf(outfile, "%4d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2)); -#endif /* not TRILIBRARY */ - } else { - /* Edge number, indices of two endpoints, and a boundary marker. */ - /* If there's no shell edge, the boundary marker is zero. */ - if (useshelles) { - tspivot(triangleloop, checkmark); - if (checkmark.sh == dummysh) { -#ifdef TRILIBRARY - emlist[edgenumber - firstnumber] = 0; -#else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2), 0); -#endif /* not TRILIBRARY */ - } else { -#ifdef TRILIBRARY - emlist[edgenumber - firstnumber] = mark(checkmark); -#else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2), mark(checkmark)); -#endif /* not TRILIBRARY */ - } - } else { -#ifdef TRILIBRARY - emlist[edgenumber - firstnumber] = trisym.tri == dummytri; -#else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d %d\n", edgenumber, - pointmark(p1), pointmark(p2), trisym.tri == dummytri); -#endif /* not TRILIBRARY */ - } - } - edgenumber++; - } - } - triangleloop.tri = triangletraverse(); - } - -#ifndef TRILIBRARY - finishfile(outfile, argc, argv); -#endif /* not TRILIBRARY */ -} - -/*****************************************************************************/ -/* */ -/* writevoronoi() Write the Voronoi diagram to a .v.node and .v.edge */ -/* file. */ -/* */ -/* The Voronoi diagram is the geometric dual of the Delaunay triangulation. */ -/* Hence, the Voronoi vertices are listed by traversing the Delaunay */ -/* triangles, and the Voronoi edges are listed by traversing the Delaunay */ -/* edges. */ -/* */ -/* WARNING: In order to assign numbers to the Voronoi vertices, this */ -/* procedure messes up the shell edges or the extra nodes of every */ -/* element. Hence, you should call this procedure last. */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -void writevoronoi(vpointlist, vpointattriblist, vpointmarkerlist, vedgelist, - vedgemarkerlist, vnormlist) -REAL **vpointlist; -REAL **vpointattriblist; -int **vpointmarkerlist; -int **vedgelist; -int **vedgemarkerlist; -REAL **vnormlist; - -#else /* not TRILIBRARY */ - -void writevoronoi(vnodefilename, vedgefilename, argc, argv) -char *vnodefilename; -char *vedgefilename; -int argc; -char **argv; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - REAL *plist; - REAL *palist; - int *elist; - REAL *normlist; - int coordindex; - int attribindex; -#else /* not TRILIBRARY */ - FILE *outfile; -#endif /* not TRILIBRARY */ - struct triedge triangleloop, trisym; - point torg, tdest, tapex; - REAL circumcenter[2]; - REAL xi, eta; - int vnodenumber, vedgenumber; - int p1, p2; - int i; - triangle ptr; /* Temporary variable used by sym(). */ - -#ifdef TRILIBRARY - if (!quiet) { - printf("Writing Voronoi vertices.\n"); - } - /* Allocate memory for Voronoi vertices if necessary. */ - if (*vpointlist == (REAL *) NULL) { - *vpointlist = (REAL *) malloc(triangles.items * 2 * sizeof(REAL)); - if (*vpointlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - /* Allocate memory for Voronoi vertex attributes if necessary. */ - if (*vpointattriblist == (REAL *) NULL) { - *vpointattriblist = (REAL *) malloc(triangles.items * nextras * - sizeof(REAL)); - if (*vpointattriblist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - *vpointmarkerlist = (int *) NULL; - plist = *vpointlist; - palist = *vpointattriblist; - coordindex = 0; - attribindex = 0; -#else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", vnodefilename); - } - outfile = fopen(vnodefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", vnodefilename); - exit(1); - } - /* Number of triangles, two dimensions, number of point attributes, */ - /* zero markers. */ - fprintf(outfile, "%ld %d %d %d\n", triangles.items, 2, nextras, 0); -#endif /* not TRILIBRARY */ - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - vnodenumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, torg); - dest(triangleloop, tdest); - apex(triangleloop, tapex); - findcircumcenter(torg, tdest, tapex, circumcenter, &xi, &eta); -#ifdef TRILIBRARY - /* X and y coordinates. */ - plist[coordindex++] = circumcenter[0]; - plist[coordindex++] = circumcenter[1]; - for (i = 2; i < 2 + nextras; i++) { - /* Interpolate the point attributes at the circumcenter. */ - palist[attribindex++] = torg[i] + xi * (tdest[i] - torg[i]) - + eta * (tapex[i] - torg[i]); - } -#else /* not TRILIBRARY */ - /* Voronoi vertex number, x and y coordinates. */ - fprintf(outfile, "%4d %.17g %.17g", vnodenumber, circumcenter[0], - circumcenter[1]); - for (i = 2; i < 2 + nextras; i++) { - /* Interpolate the point attributes at the circumcenter. */ - fprintf(outfile, " %.17g", torg[i] + xi * (tdest[i] - torg[i]) - + eta * (tapex[i] - torg[i])); - } - fprintf(outfile, "\n"); -#endif /* not TRILIBRARY */ - - * (int *) (triangleloop.tri + 6) = vnodenumber; - triangleloop.tri = triangletraverse(); - vnodenumber++; - } - -#ifndef TRILIBRARY - finishfile(outfile, argc, argv); -#endif /* not TRILIBRARY */ - -#ifdef TRILIBRARY - if (!quiet) { - printf("Writing Voronoi edges.\n"); - } - /* Allocate memory for output Voronoi edges if necessary. */ - if (*vedgelist == (int *) NULL) { - *vedgelist = (int *) malloc(edges * 2 * sizeof(int)); - if (*vedgelist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - *vedgemarkerlist = (int *) NULL; - /* Allocate memory for output Voronoi norms if necessary. */ - if (*vnormlist == (REAL *) NULL) { - *vnormlist = (REAL *) malloc(edges * 2 * sizeof(REAL)); - if (*vnormlist == (REAL *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - elist = *vedgelist; - normlist = *vnormlist; - coordindex = 0; -#else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", vedgefilename); - } - outfile = fopen(vedgefilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", vedgefilename); - exit(1); - } - /* Number of edges, zero boundary markers. */ - fprintf(outfile, "%ld %d\n", edges, 0); -#endif /* not TRILIBRARY */ - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - vedgenumber = firstnumber; - /* To loop over the set of edges, loop over all triangles, and look at */ - /* the three edges of each triangle. If there isn't another triangle */ - /* adjacent to the edge, operate on the edge. If there is another */ - /* adjacent triangle, operate on the edge only if the current triangle */ - /* has a smaller pointer than its neighbor. This way, each edge is */ - /* considered only once. */ - while (triangleloop.tri != (triangle *) NULL) { - for (triangleloop.orient = 0; triangleloop.orient < 3; - triangleloop.orient++) { - sym(triangleloop, trisym); - if ((triangleloop.tri < trisym.tri) || (trisym.tri == dummytri)) { - /* Find the number of this triangle (and Voronoi vertex). */ - p1 = * (int *) (triangleloop.tri + 6); - if (trisym.tri == dummytri) { - org(triangleloop, torg); - dest(triangleloop, tdest); -#ifdef TRILIBRARY - /* Copy an infinite ray. Index of one endpoint, and -1. */ - elist[coordindex] = p1; - normlist[coordindex++] = tdest[1] - torg[1]; - elist[coordindex] = -1; - normlist[coordindex++] = torg[0] - tdest[0]; -#else /* not TRILIBRARY */ - /* Write an infinite ray. Edge number, index of one endpoint, -1, */ - /* and x and y coordinates of a vector representing the */ - /* direction of the ray. */ - fprintf(outfile, "%4d %d %d %.17g %.17g\n", vedgenumber, - p1, -1, tdest[1] - torg[1], torg[0] - tdest[0]); -#endif /* not TRILIBRARY */ - } else { - /* Find the number of the adjacent triangle (and Voronoi vertex). */ - p2 = * (int *) (trisym.tri + 6); - /* Finite edge. Write indices of two endpoints. */ -#ifdef TRILIBRARY - elist[coordindex] = p1; - normlist[coordindex++] = 0.0; - elist[coordindex] = p2; - normlist[coordindex++] = 0.0; -#else /* not TRILIBRARY */ - fprintf(outfile, "%4d %d %d\n", vedgenumber, p1, p2); -#endif /* not TRILIBRARY */ - } - vedgenumber++; - } - } - triangleloop.tri = triangletraverse(); - } - -#ifndef TRILIBRARY - finishfile(outfile, argc, argv); -#endif /* not TRILIBRARY */ -} - -#ifdef TRILIBRARY - -void writeneighbors(neighborlist) -int **neighborlist; - -#else /* not TRILIBRARY */ - -void writeneighbors(neighborfilename, argc, argv) -char *neighborfilename; -int argc; -char **argv; - -#endif /* not TRILIBRARY */ - -{ -#ifdef TRILIBRARY - int *nlist; - int index; -#else /* not TRILIBRARY */ - FILE *outfile; -#endif /* not TRILIBRARY */ - struct triedge triangleloop, trisym; - int elementnumber; - int neighbor1, neighbor2, neighbor3; - triangle ptr; /* Temporary variable used by sym(). */ - -#ifdef TRILIBRARY - if (!quiet) { - printf("Writing neighbors.\n"); - } - /* Allocate memory for neighbors if necessary. */ - if (*neighborlist == (int *) NULL) { - *neighborlist = (int *) malloc(triangles.items * 3 * sizeof(int)); - if (*neighborlist == (int *) NULL) { - printf("Error: Out of memory.\n"); - exit(1); - } - } - nlist = *neighborlist; - index = 0; -#else /* not TRILIBRARY */ - if (!quiet) { - printf("Writing %s.\n", neighborfilename); - } - outfile = fopen(neighborfilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", neighborfilename); - exit(1); - } - /* Number of triangles, three edges per triangle. */ - fprintf(outfile, "%ld %d\n", triangles.items, 3); -#endif /* not TRILIBRARY */ - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - * (int *) (triangleloop.tri + 6) = elementnumber; - triangleloop.tri = triangletraverse(); - elementnumber++; - } - * (int *) (dummytri + 6) = -1; - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - elementnumber = firstnumber; - while (triangleloop.tri != (triangle *) NULL) { - triangleloop.orient = 1; - sym(triangleloop, trisym); - neighbor1 = * (int *) (trisym.tri + 6); - triangleloop.orient = 2; - sym(triangleloop, trisym); - neighbor2 = * (int *) (trisym.tri + 6); - triangleloop.orient = 0; - sym(triangleloop, trisym); - neighbor3 = * (int *) (trisym.tri + 6); -#ifdef TRILIBRARY - nlist[index++] = neighbor1; - nlist[index++] = neighbor2; - nlist[index++] = neighbor3; -#else /* not TRILIBRARY */ - /* Triangle number, neighboring triangle numbers. */ - fprintf(outfile, "%4d %d %d %d\n", elementnumber, - neighbor1, neighbor2, neighbor3); -#endif /* not TRILIBRARY */ - - triangleloop.tri = triangletraverse(); - elementnumber++; - } - -#ifndef TRILIBRARY - finishfile(outfile, argc, argv); -#endif /* TRILIBRARY */ -} - -/*****************************************************************************/ -/* */ -/* writeoff() Write the triangulation to an .off file. */ -/* */ -/* OFF stands for the Object File Format, a format used by the Geometry */ -/* Center's Geomview package. */ -/* */ -/*****************************************************************************/ - -#ifndef TRILIBRARY - -void writeoff(offfilename, argc, argv) -char *offfilename; -int argc; -char **argv; -{ - FILE *outfile; - struct triedge triangleloop; - point pointloop; - point p1, p2, p3; - - if (!quiet) { - printf("Writing %s.\n", offfilename); - } - outfile = fopen(offfilename, "w"); - if (outfile == (FILE *) NULL) { - printf(" Error: Cannot create file %s.\n", offfilename); - exit(1); - } - /* Number of points, triangles, and edges. */ - fprintf(outfile, "OFF\n%ld %ld %ld\n", points.items, triangles.items, - edges); - - /* Write the points. */ - traversalinit(&points); - pointloop = pointtraverse(); - while (pointloop != (point) NULL) { - /* The "0.0" is here because the OFF format uses 3D coordinates. */ - fprintf(outfile, " %.17g %.17g %.17g\n", pointloop[0], - pointloop[1], 0.0); - pointloop = pointtraverse(); - } - - /* Write the triangles. */ - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, p1); - dest(triangleloop, p2); - apex(triangleloop, p3); - /* The "3" means a three-vertex polygon. */ - fprintf(outfile, " 3 %4d %4d %4d\n", pointmark(p1) - 1, - pointmark(p2) - 1, pointmark(p3) - 1); - triangleloop.tri = triangletraverse(); - } - finishfile(outfile, argc, argv); -} - -#endif /* not TRILIBRARY */ - -/** **/ -/** **/ -/********* File I/O routines end here *********/ - -/*****************************************************************************/ -/* */ -/* quality_statistics() Print statistics about the quality of the mesh. */ -/* */ -/*****************************************************************************/ - -void quality_statistics() -{ - struct triedge triangleloop; - point p[3]; - REAL cossquaretable[8]; - REAL ratiotable[16]; - REAL dx[3], dy[3]; - REAL edgelength[3]; - REAL dotproduct; - REAL cossquare; - REAL triarea; - REAL shortest, longest; - REAL trilongest2; - REAL smallestarea, biggestarea; - REAL triminaltitude2; - REAL minaltitude; - REAL triaspect2; - REAL worstaspect; - REAL smallestangle, biggestangle; - REAL radconst, degconst; - int angletable[18]; - int aspecttable[16]; - int aspectindex; - int tendegree; - int acutebiggest; - int i, ii, j, k; - - printf("Mesh quality statistics:\n\n"); - radconst = (REAL)(PI / 18.0); - degconst = (REAL)(180.0 / PI); - for (i = 0; i < 8; i++) { - cossquaretable[i] = (REAL)(cos(radconst * (REAL) (i + 1))); - cossquaretable[i] = cossquaretable[i] * cossquaretable[i]; - } - for (i = 0; i < 18; i++) { - angletable[i] = 0; - } - - ratiotable[0] = 1.5; ratiotable[1] = 2.0; - ratiotable[2] = 2.5; ratiotable[3] = 3.0; - ratiotable[4] = 4.0; ratiotable[5] = 6.0; - ratiotable[6] = 10.0; ratiotable[7] = 15.0; - ratiotable[8] = 25.0; ratiotable[9] = 50.0; - ratiotable[10] = 100.0; ratiotable[11] = 300.0; - ratiotable[12] = 1000.0; ratiotable[13] = 10000.0; - ratiotable[14] = 100000.0; ratiotable[15] = 0.0; - for (i = 0; i < 16; i++) { - aspecttable[i] = 0; - } - - worstaspect = 0.0; - minaltitude = xmax - xmin + ymax - ymin; - minaltitude = minaltitude * minaltitude; - shortest = minaltitude; - longest = 0.0; - smallestarea = minaltitude; - biggestarea = 0.0; - worstaspect = 0.0; - smallestangle = 0.0; - biggestangle = 2.0; - acutebiggest = 1; - - traversalinit(&triangles); - triangleloop.tri = triangletraverse(); - triangleloop.orient = 0; - while (triangleloop.tri != (triangle *) NULL) { - org(triangleloop, p[0]); - dest(triangleloop, p[1]); - apex(triangleloop, p[2]); - trilongest2 = 0.0; - - for (i = 0; i < 3; i++) { - j = plus1mod3[i]; - k = minus1mod3[i]; - dx[i] = p[j][0] - p[k][0]; - dy[i] = p[j][1] - p[k][1]; - edgelength[i] = dx[i] * dx[i] + dy[i] * dy[i]; - if (edgelength[i] > trilongest2) { - trilongest2 = edgelength[i]; - } - if (edgelength[i] > longest) { - longest = edgelength[i]; - } - if (edgelength[i] < shortest) { - shortest = edgelength[i]; - } - } - - triarea = counterclockwise(p[0], p[1], p[2]); - if (triarea < smallestarea) { - smallestarea = triarea; - } - if (triarea > biggestarea) { - biggestarea = triarea; - } - triminaltitude2 = triarea * triarea / trilongest2; - if (triminaltitude2 < minaltitude) { - minaltitude = triminaltitude2; - } - triaspect2 = trilongest2 / triminaltitude2; - if (triaspect2 > worstaspect) { - worstaspect = triaspect2; - } - aspectindex = 0; - while ((triaspect2 > ratiotable[aspectindex] * ratiotable[aspectindex]) - && (aspectindex < 15)) { - aspectindex++; - } - aspecttable[aspectindex]++; - - for (i = 0; i < 3; i++) { - j = plus1mod3[i]; - k = minus1mod3[i]; - dotproduct = dx[j] * dx[k] + dy[j] * dy[k]; - cossquare = dotproduct * dotproduct / (edgelength[j] * edgelength[k]); - tendegree = 8; - for (ii = 7; ii >= 0; ii--) { - if (cossquare > cossquaretable[ii]) { - tendegree = ii; - } - } - if (dotproduct <= 0.0) { - angletable[tendegree]++; - if (cossquare > smallestangle) { - smallestangle = cossquare; - } - if (acutebiggest && (cossquare < biggestangle)) { - biggestangle = cossquare; - } - } else { - angletable[17 - tendegree]++; - if (acutebiggest || (cossquare > biggestangle)) { - biggestangle = cossquare; - acutebiggest = 0; - } - } - } - triangleloop.tri = triangletraverse(); - } - - shortest = (REAL)sqrt(shortest); - longest = (REAL)sqrt(longest); - minaltitude = (REAL)sqrt(minaltitude); - worstaspect = (REAL)sqrt(worstaspect); - smallestarea *= 2.0; - biggestarea *= 2.0; - if (smallestangle >= 1.0) { - smallestangle = 0.0; - } else { - smallestangle = (REAL)(degconst * acos(sqrt(smallestangle))); - } - if (biggestangle >= 1.0) { - biggestangle = 180.0; - } else { - if (acutebiggest) { - biggestangle = (REAL)(degconst * acos(sqrt(biggestangle))); - } else { - biggestangle = (REAL)(180.0 - degconst * acos(sqrt(biggestangle))); - } - } - - printf(" Smallest area: %16.5g | Largest area: %16.5g\n", - smallestarea, biggestarea); - printf(" Shortest edge: %16.5g | Longest edge: %16.5g\n", - shortest, longest); - printf(" Shortest altitude: %12.5g | Largest aspect ratio: %8.5g\n\n", - minaltitude, worstaspect); - printf(" Aspect ratio histogram:\n"); - printf(" 1.1547 - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n", - ratiotable[0], aspecttable[0], ratiotable[7], ratiotable[8], - aspecttable[8]); - for (i = 1; i < 7; i++) { - printf(" %6.6g - %-6.6g : %8d | %6.6g - %-6.6g : %8d\n", - ratiotable[i - 1], ratiotable[i], aspecttable[i], - ratiotable[i + 7], ratiotable[i + 8], aspecttable[i + 8]); - } - printf(" %6.6g - %-6.6g : %8d | %6.6g - : %8d\n", - ratiotable[6], ratiotable[7], aspecttable[7], ratiotable[14], - aspecttable[15]); - printf( -" (Triangle aspect ratio is longest edge divided by shortest altitude)\n\n"); - printf(" Smallest angle: %15.5g | Largest angle: %15.5g\n\n", - smallestangle, biggestangle); - printf(" Angle histogram:\n"); - for (i = 0; i < 9; i++) { - printf(" %3d - %3d degrees: %8d | %3d - %3d degrees: %8d\n", - i * 10, i * 10 + 10, angletable[i], - i * 10 + 90, i * 10 + 100, angletable[i + 9]); - } - printf("\n"); -} - -/*****************************************************************************/ -/* */ -/* statistics() Print all sorts of cool facts. */ -/* */ -/*****************************************************************************/ - -void statistics() -{ - printf("\nStatistics:\n\n"); - printf(" Input points: %d\n", inpoints); - if (refine) { - printf(" Input triangles: %d\n", inelements); - } - if (poly) { - printf(" Input segments: %d\n", insegments); - if (!refine) { - printf(" Input holes: %d\n", holes); - } - } - - printf("\n Mesh points: %ld\n", points.items); - printf(" Mesh triangles: %ld\n", triangles.items); - printf(" Mesh edges: %ld\n", edges); - if (poly || refine) { - printf(" Mesh boundary edges: %ld\n", hullsize); - printf(" Mesh segments: %ld\n\n", shelles.items); - } else { - printf(" Mesh convex hull edges: %ld\n\n", hullsize); - } - if (verbose) { - quality_statistics(); - printf("Memory allocation statistics:\n\n"); - printf(" Maximum number of points: %ld\n", points.maxitems); - printf(" Maximum number of triangles: %ld\n", triangles.maxitems); - if (shelles.maxitems > 0) { - printf(" Maximum number of segments: %ld\n", shelles.maxitems); - } - if (viri.maxitems > 0) { - printf(" Maximum number of viri: %ld\n", viri.maxitems); - } - if (badsegments.maxitems > 0) { - printf(" Maximum number of encroached segments: %ld\n", - badsegments.maxitems); - } - if (badtriangles.maxitems > 0) { - printf(" Maximum number of bad triangles: %ld\n", - badtriangles.maxitems); - } - if (splaynodes.maxitems > 0) { - printf(" Maximum number of splay tree nodes: %ld\n", - splaynodes.maxitems); - } - printf(" Approximate heap memory use (bytes): %ld\n\n", - points.maxitems * points.itembytes - + triangles.maxitems * triangles.itembytes - + shelles.maxitems * shelles.itembytes - + viri.maxitems * viri.itembytes - + badsegments.maxitems * badsegments.itembytes - + badtriangles.maxitems * badtriangles.itembytes - + splaynodes.maxitems * splaynodes.itembytes); - - printf("Algorithmic statistics:\n\n"); - printf(" Number of incircle tests: %ld\n", incirclecount); - printf(" Number of orientation tests: %ld\n", counterclockcount); - if (hyperbolacount > 0) { - printf(" Number of right-of-hyperbola tests: %ld\n", - hyperbolacount); - } - if (circumcentercount > 0) { - printf(" Number of circumcenter computations: %ld\n", - circumcentercount); - } - if (circletopcount > 0) { - printf(" Number of circle top computations: %ld\n", - circletopcount); - } - printf("\n"); - } -} - -/*****************************************************************************/ -/* */ -/* main() or triangulate() Gosh, do everything. */ -/* */ -/* The sequence is roughly as follows. Many of these steps can be skipped, */ -/* depending on the command line switches. */ -/* */ -/* - Initialize constants and parse the command line. */ -/* - Read the points from a file and either */ -/* - triangulate them (no -r), or */ -/* - read an old mesh from files and reconstruct it (-r). */ -/* - Insert the PSLG segments (-p), and possibly segments on the convex */ -/* hull (-c). */ -/* - Read the holes (-p), regional attributes (-pA), and regional area */ -/* constraints (-pa). Carve the holes and concavities, and spread the */ -/* regional attributes and area constraints. */ -/* - Enforce the constraints on minimum angle (-q) and maximum area (-a). */ -/* Also enforce the conforming Delaunay property (-q and -a). */ -/* - Compute the number of edges in the resulting mesh. */ -/* - Promote the mesh's linear triangles to higher order elements (-o). */ -/* - Write the output files and print the statistics. */ -/* - Check the consistency and Delaunay property of the mesh (-C). */ -/* */ -/*****************************************************************************/ - -#ifdef TRILIBRARY - -void triangulate(triswitches, in, out, vorout) -char *triswitches; -struct triangulateio *in; -struct triangulateio *out; -struct triangulateio *vorout; - -#else /* not TRILIBRARY */ - -int main(argc, argv) -int argc; -char **argv; - -#endif /* not TRILIBRARY */ - -{ - REAL *holearray; /* Array of holes. */ - REAL *regionarray; /* Array of regional attributes and area constraints. */ -#ifndef TRILIBRARY - FILE *polyfile; -#endif /* not TRILIBRARY */ -#ifndef NO_TIMER - /* Variables for timing the performance of Triangle. The types are */ - /* defined in sys/time.h. */ - struct timeval tv0, tv1, tv2, tv3, tv4, tv5, tv6; - struct timezone tz; -#endif /* NO_TIMER */ - -#ifndef NO_TIMER - gettimeofday(&tv0, &tz); -#endif /* NO_TIMER */ - - triangleinit(); -#ifdef TRILIBRARY - parsecommandline(1, &triswitches); -#else /* not TRILIBRARY */ - parsecommandline(argc, argv); -#endif /* not TRILIBRARY */ - -#ifdef TRILIBRARY - transfernodes(in->pointlist, in->pointattributelist, in->pointmarkerlist, - in->numberofpoints, in->numberofpointattributes); -#else /* not TRILIBRARY */ - readnodes(innodefilename, inpolyfilename, &polyfile); -#endif /* not TRILIBRARY */ - -#ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv1, &tz); - } -#endif /* NO_TIMER */ - -#ifdef CDT_ONLY - hullsize = delaunay(); /* Triangulate the points. */ -#else /* not CDT_ONLY */ - if (refine) { - /* Read and reconstruct a mesh. */ -#ifdef TRILIBRARY - hullsize = reconstruct(in->trianglelist, in->triangleattributelist, - in->trianglearealist, in->numberoftriangles, - in->numberofcorners, in->numberoftriangleattributes, - in->segmentlist, in->segmentmarkerlist, - in->numberofsegments); -#else /* not TRILIBRARY */ - hullsize = reconstruct(inelefilename, areafilename, inpolyfilename, - polyfile); -#endif /* not TRILIBRARY */ - } else { - hullsize = delaunay(); /* Triangulate the points. */ - } -#endif /* not CDT_ONLY */ - -#ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv2, &tz); - if (refine) { - printf("Mesh reconstruction"); - } else { - printf("Delaunay"); - } - printf(" milliseconds: %ld\n", 1000l * (tv2.tv_sec - tv1.tv_sec) - + (tv2.tv_usec - tv1.tv_usec) / 1000l); - } -#endif /* NO_TIMER */ - - /* Ensure that no point can be mistaken for a triangular bounding */ - /* box point in insertsite(). */ - infpoint1 = (point) NULL; - infpoint2 = (point) NULL; - infpoint3 = (point) NULL; - - if (useshelles) { - checksegments = 1; /* Segments will be introduced next. */ - if (!refine) { - /* Insert PSLG segments and/or convex hull segments. */ -#ifdef TRILIBRARY - insegments = formskeleton(in->segmentlist, in->segmentmarkerlist, - in->numberofsegments); -#else /* not TRILIBRARY */ - insegments = formskeleton(polyfile, inpolyfilename); -#endif /* not TRILIBRARY */ - } - } - -#ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv3, &tz); - if (useshelles && !refine) { - printf("Segment milliseconds: %ld\n", - 1000l * (tv3.tv_sec - tv2.tv_sec) - + (tv3.tv_usec - tv2.tv_usec) / 1000l); - } - } -#endif /* NO_TIMER */ - - if (poly) { -#ifdef TRILIBRARY - holearray = in->holelist; - holes = in->numberofholes; - regionarray = in->regionlist; - regions = in->numberofregions; -#else /* not TRILIBRARY */ - readholes(polyfile, inpolyfilename, &holearray, &holes, - ®ionarray, ®ions); -#endif /* not TRILIBRARY */ - if (!refine) { - /* Carve out holes and concavities. */ - carveholes(holearray, holes, regionarray, regions); - } - } else { - /* Without a PSLG, there can be no holes or regional attributes */ - /* or area constraints. The following are set to zero to avoid */ - /* an accidental free() later. */ - holes = 0; - regions = 0; - } - -#ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv4, &tz); - if (poly && !refine) { - printf("Hole milliseconds: %ld\n", 1000l * (tv4.tv_sec - tv3.tv_sec) - + (tv4.tv_usec - tv3.tv_usec) / 1000l); - } - } -#endif /* NO_TIMER */ - -#ifndef CDT_ONLY - if (quality) { - enforcequality(); /* Enforce angle and area constraints. */ - } -#endif /* not CDT_ONLY */ - -#ifndef NO_TIMER - if (!quiet) { - gettimeofday(&tv5, &tz); -#ifndef CDT_ONLY - if (quality) { - printf("Quality milliseconds: %ld\n", - 1000l * (tv5.tv_sec - tv4.tv_sec) - + (tv5.tv_usec - tv4.tv_usec) / 1000l); - } -#endif /* not CDT_ONLY */ - } -#endif /* NO_TIMER */ - - /* Compute the number of edges. */ - edges = (3l * triangles.items + hullsize) / 2l; - - if (order > 1) { - highorder(); /* Promote elements to higher polynomial order. */ - } - if (!quiet) { - printf("\n"); - } - -#ifdef TRILIBRARY - out->numberofpoints = points.items; - out->numberofpointattributes = nextras; - out->numberoftriangles = triangles.items; - out->numberofcorners = (order + 1) * (order + 2) / 2; - out->numberoftriangleattributes = eextras; - out->numberofedges = edges; - if (useshelles) { - out->numberofsegments = shelles.items; - } else { - out->numberofsegments = hullsize; - } - if (vorout != (struct triangulateio *) NULL) { - vorout->numberofpoints = triangles.items; - vorout->numberofpointattributes = nextras; - vorout->numberofedges = edges; - } -#endif /* TRILIBRARY */ - /* If not using iteration numbers, don't write a .node file if one was */ - /* read, because the original one would be overwritten! */ - if (nonodewritten || (noiterationnum && readnodefile)) { - if (!quiet) { -#ifdef TRILIBRARY - printf("NOT writing points.\n"); -#else /* not TRILIBRARY */ - printf("NOT writing a .node file.\n"); -#endif /* not TRILIBRARY */ - } - numbernodes(); /* We must remember to number the points. */ - } else { -#ifdef TRILIBRARY - writenodes(&out->pointlist, &out->pointattributelist, - &out->pointmarkerlist); -#else /* not TRILIBRARY */ - writenodes(outnodefilename, argc, argv); /* Numbers the points too. */ -#endif /* TRILIBRARY */ - } - if (noelewritten) { - if (!quiet) { -#ifdef TRILIBRARY - printf("NOT writing triangles.\n"); -#else /* not TRILIBRARY */ - printf("NOT writing an .ele file.\n"); -#endif /* not TRILIBRARY */ - } - } else { -#ifdef TRILIBRARY - writeelements(&out->trianglelist, &out->triangleattributelist); -#else /* not TRILIBRARY */ - writeelements(outelefilename, argc, argv); -#endif /* not TRILIBRARY */ - } - /* The -c switch (convex switch) causes a PSLG to be written */ - /* even if none was read. */ - if (poly || convex) { - /* If not using iteration numbers, don't overwrite the .poly file. */ - if (nopolywritten || noiterationnum) { - if (!quiet) { -#ifdef TRILIBRARY - printf("NOT writing segments.\n"); -#else /* not TRILIBRARY */ - printf("NOT writing a .poly file.\n"); -#endif /* not TRILIBRARY */ - } - } else { -#ifdef TRILIBRARY - writepoly(&out->segmentlist, &out->segmentmarkerlist); - out->numberofholes = holes; - out->numberofregions = regions; - if (poly) { - out->holelist = in->holelist; - out->regionlist = in->regionlist; - } else { - out->holelist = (REAL *) NULL; - out->regionlist = (REAL *) NULL; - } -#else /* not TRILIBRARY */ - writepoly(outpolyfilename, holearray, holes, regionarray, regions, - argc, argv); -#endif /* not TRILIBRARY */ - } - } -#ifndef TRILIBRARY -#ifndef CDT_ONLY - if (regions > 0) { - free(regionarray); - } -#endif /* not CDT_ONLY */ - if (holes > 0) { - free(holearray); - } - if (geomview) { - writeoff(offfilename, argc, argv); - } -#endif /* not TRILIBRARY */ - if (edgesout) { -#ifdef TRILIBRARY - writeedges(&out->edgelist, &out->edgemarkerlist); -#else /* not TRILIBRARY */ - writeedges(edgefilename, argc, argv); -#endif /* not TRILIBRARY */ - } - if (voronoi) { -#ifdef TRILIBRARY - writevoronoi(&vorout->pointlist, &vorout->pointattributelist, - &vorout->pointmarkerlist, &vorout->edgelist, - &vorout->edgemarkerlist, &vorout->normlist); -#else /* not TRILIBRARY */ - writevoronoi(vnodefilename, vedgefilename, argc, argv); -#endif /* not TRILIBRARY */ - } - if (neighbors) { -#ifdef TRILIBRARY - writeneighbors(&out->neighborlist); -#else /* not TRILIBRARY */ - writeneighbors(neighborfilename, argc, argv); -#endif /* not TRILIBRARY */ - } - - if (!quiet) { -#ifndef NO_TIMER - gettimeofday(&tv6, &tz); - printf("\nOutput milliseconds: %ld\n", - 1000l * (tv6.tv_sec - tv5.tv_sec) - + (tv6.tv_usec - tv5.tv_usec) / 1000l); - printf("Total running milliseconds: %ld\n", - 1000l * (tv6.tv_sec - tv0.tv_sec) - + (tv6.tv_usec - tv0.tv_usec) / 1000l); -#endif /* NO_TIMER */ - - statistics(); - } - -#ifndef REDUCED - if (docheck) { - checkmesh(); - checkdelaunay(); - } -#endif /* not REDUCED */ - - triangledeinit(); -#ifndef TRILIBRARY - return 0; -#endif /* not TRILIBRARY */ -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/triangle.h b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/triangle.h deleted file mode 100644 index e7d87d01..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/triangle.h +++ /dev/null @@ -1,288 +0,0 @@ -/*****************************************************************************/ -/* */ -/* (triangle.h) */ -/* */ -/* Include file for programs that call Triangle. */ -/* */ -/* Accompanies Triangle Version 1.3 */ -/* July 19, 1996 */ -/* */ -/* Copyright 1996 */ -/* Jonathan Richard Shewchuk */ -/* School of Computer Science */ -/* Carnegie Mellon University */ -/* 5000 Forbes Avenue */ -/* Pittsburgh, Pennsylvania 15213-3891 */ -/* jrs@cs.cmu.edu */ -/* */ -/*****************************************************************************/ - -/*****************************************************************************/ -/* */ -/* How to call Triangle from another program */ -/* */ -/* */ -/* If you haven't read Triangle's instructions (run "triangle -h" to read */ -/* them), you won't understand what follows. */ -/* */ -/* Triangle must be compiled into an object file (triangle.o) with the */ -/* TRILIBRARY symbol defined (preferably by using the -DTRILIBRARY compiler */ -/* switch). The makefile included with Triangle will do this for you if */ -/* you run "make trilibrary". The resulting object file can be called via */ -/* the procedure triangulate(). */ -/* */ -/* If the size of the object file is important to you, you may wish to */ -/* generate a reduced version of triangle.o. The REDUCED symbol gets rid */ -/* of all features that are primarily of research interest. Specifically, */ -/* the -DREDUCED switch eliminates Triangle's -i, -F, -s, and -C switches. */ -/* The CDT_ONLY symbol gets rid of all meshing algorithms above and beyond */ -/* constrained Delaunay triangulation. Specifically, the -DCDT_ONLY switch */ -/* eliminates Triangle's -r, -q, -a, -S, and -s switches. */ -/* */ -/* IMPORTANT: These definitions (TRILIBRARY, REDUCED, CDT_ONLY) must be */ -/* made in the makefile or in triangle.c itself. Putting these definitions */ -/* in this file will not create the desired effect. */ -/* */ -/* */ -/* The calling convention for triangulate() follows. */ -/* */ -/* void triangulate(triswitches, in, out, vorout) */ -/* char *triswitches; */ -/* struct triangulateio *in; */ -/* struct triangulateio *out; */ -/* struct triangulateio *vorout; */ -/* */ -/* `triswitches' is a string containing the command line switches you wish */ -/* to invoke. No initial dash is required. Some suggestions: */ -/* */ -/* - You'll probably find it convenient to use the `z' switch so that */ -/* points (and other items) are numbered from zero. This simplifies */ -/* indexing, because the first item of any type always starts at index */ -/* [0] of the corresponding array, whether that item's number is zero or */ -/* one. */ -/* - You'll probably want to use the `Q' (quiet) switch in your final code, */ -/* but you can take advantage of Triangle's printed output (including the */ -/* `V' switch) while debugging. */ -/* - If you are not using the `q' or `a' switches, then the output points */ -/* will be identical to the input points, except possibly for the */ -/* boundary markers. If you don't need the boundary markers, you should */ -/* use the `N' (no nodes output) switch to save memory. (If you do need */ -/* boundary markers, but need to save memory, a good nasty trick is to */ -/* set out->pointlist equal to in->pointlist before calling triangulate(),*/ -/* so that Triangle overwrites the input points with identical copies.) */ -/* - The `I' (no iteration numbers) and `g' (.off file output) switches */ -/* have no effect when Triangle is compiled with TRILIBRARY defined. */ -/* */ -/* `in', `out', and `vorout' are descriptions of the input, the output, */ -/* and the Voronoi output. If the `v' (Voronoi output) switch is not used, */ -/* `vorout' may be NULL. `in' and `out' may never be NULL. */ -/* */ -/* Certain fields of the input and output structures must be initialized, */ -/* as described below. */ -/* */ -/*****************************************************************************/ - -/*****************************************************************************/ -/* */ -/* The `triangulateio' structure. */ -/* */ -/* Used to pass data into and out of the triangulate() procedure. */ -/* */ -/* */ -/* Arrays are used to store points, triangles, markers, and so forth. In */ -/* all cases, the first item in any array is stored starting at index [0]. */ -/* However, that item is item number `1' unless the `z' switch is used, in */ -/* which case it is item number `0'. Hence, you may find it easier to */ -/* index points (and triangles in the neighbor list) if you use the `z' */ -/* switch. Unless, of course, you're calling Triangle from a Fortran */ -/* program. */ -/* */ -/* Description of fields (except the `numberof' fields, which are obvious): */ -/* */ -/* `pointlist': An array of point coordinates. The first point's x */ -/* coordinate is at index [0] and its y coordinate at index [1], followed */ -/* by the coordinates of the remaining points. Each point occupies two */ -/* REALs. */ -/* `pointattributelist': An array of point attributes. Each point's */ -/* attributes occupy `numberofpointattributes' REALs. */ -/* `pointmarkerlist': An array of point markers; one int per point. */ -/* */ -/* `trianglelist': An array of triangle corners. The first triangle's */ -/* first corner is at index [0], followed by its other two corners in */ -/* counterclockwise order, followed by any other nodes if the triangle */ -/* represents a nonlinear element. Each triangle occupies */ -/* `numberofcorners' ints. */ -/* `triangleattributelist': An array of triangle attributes. Each */ -/* triangle's attributes occupy `numberoftriangleattributes' REALs. */ -/* `trianglearealist': An array of triangle area constraints; one REAL per */ -/* triangle. Input only. */ -/* `neighborlist': An array of triangle neighbors; three ints per */ -/* triangle. Output only. */ -/* */ -/* `segmentlist': An array of segment endpoints. The first segment's */ -/* endpoints are at indices [0] and [1], followed by the remaining */ -/* segments. Two ints per segment. */ -/* `segmentmarkerlist': An array of segment markers; one int per segment. */ -/* */ -/* `holelist': An array of holes. The first hole's x and y coordinates */ -/* are at indices [0] and [1], followed by the remaining holes. Two */ -/* REALs per hole. Input only, although the pointer is copied to the */ -/* output structure for your convenience. */ -/* */ -/* `regionlist': An array of regional attributes and area constraints. */ -/* The first constraint's x and y coordinates are at indices [0] and [1], */ -/* followed by the regional attribute and index [2], followed by the */ -/* maximum area at index [3], followed by the remaining area constraints. */ -/* Four REALs per area constraint. Note that each regional attribute is */ -/* used only if you select the `A' switch, and each area constraint is */ -/* used only if you select the `a' switch (with no number following), but */ -/* omitting one of these switches does not change the memory layout. */ -/* Input only, although the pointer is copied to the output structure for */ -/* your convenience. */ -/* */ -/* `edgelist': An array of edge endpoints. The first edge's endpoints are */ -/* at indices [0] and [1], followed by the remaining edges. Two ints per */ -/* edge. Output only. */ -/* `edgemarkerlist': An array of edge markers; one int per edge. Output */ -/* only. */ -/* `normlist': An array of normal vectors, used for infinite rays in */ -/* Voronoi diagrams. The first normal vector's x and y magnitudes are */ -/* at indices [0] and [1], followed by the remaining vectors. For each */ -/* finite edge in a Voronoi diagram, the normal vector written is the */ -/* zero vector. Two REALs per edge. Output only. */ -/* */ -/* */ -/* Any input fields that Triangle will examine must be initialized. */ -/* Furthermore, for each output array that Triangle will write to, you */ -/* must either provide space by setting the appropriate pointer to point */ -/* to the space you want the data written to, or you must initialize the */ -/* pointer to NULL, which tells Triangle to allocate space for the results. */ -/* The latter option is preferable, because Triangle always knows exactly */ -/* how much space to allocate. The former option is provided mainly for */ -/* people who need to call Triangle from Fortran code, though it also makes */ -/* possible some nasty space-saving tricks, like writing the output to the */ -/* same arrays as the input. */ -/* */ -/* Triangle will not free() any input or output arrays, including those it */ -/* allocates itself; that's up to you. */ -/* */ -/* Here's a guide to help you decide which fields you must initialize */ -/* before you call triangulate(). */ -/* */ -/* `in': */ -/* */ -/* - `pointlist' must always point to a list of points; `numberofpoints' */ -/* and `numberofpointattributes' must be properly set. */ -/* `pointmarkerlist' must either be set to NULL (in which case all */ -/* markers default to zero), or must point to a list of markers. If */ -/* `numberofpointattributes' is not zero, `pointattributelist' must */ -/* point to a list of point attributes. */ -/* - If the `r' switch is used, `trianglelist' must point to a list of */ -/* triangles, and `numberoftriangles', `numberofcorners', and */ -/* `numberoftriangleattributes' must be properly set. If */ -/* `numberoftriangleattributes' is not zero, `triangleattributelist' */ -/* must point to a list of triangle attributes. If the `a' switch is */ -/* used (with no number following), `trianglearealist' must point to a */ -/* list of triangle area constraints. `neighborlist' may be ignored. */ -/* - If the `p' switch is used, `segmentlist' must point to a list of */ -/* segments, `numberofsegments' must be properly set, and */ -/* `segmentmarkerlist' must either be set to NULL (in which case all */ -/* markers default to zero), or must point to a list of markers. */ -/* - If the `p' switch is used without the `r' switch, then */ -/* `numberofholes' and `numberofregions' must be properly set. If */ -/* `numberofholes' is not zero, `holelist' must point to a list of */ -/* holes. If `numberofregions' is not zero, `regionlist' must point to */ -/* a list of region constraints. */ -/* - If the `p' switch is used, `holelist', `numberofholes', */ -/* `regionlist', and `numberofregions' is copied to `out'. (You can */ -/* nonetheless get away with not initializing them if the `r' switch is */ -/* used.) */ -/* - `edgelist', `edgemarkerlist', `normlist', and `numberofedges' may be */ -/* ignored. */ -/* */ -/* `out': */ -/* */ -/* - `pointlist' must be initialized (NULL or pointing to memory) unless */ -/* the `N' switch is used. `pointmarkerlist' must be initialized */ -/* unless the `N' or `B' switch is used. If `N' is not used and */ -/* `in->numberofpointattributes' is not zero, `pointattributelist' must */ -/* be initialized. */ -/* - `trianglelist' must be initialized unless the `E' switch is used. */ -/* `neighborlist' must be initialized if the `n' switch is used. If */ -/* the `E' switch is not used and (`in->numberofelementattributes' is */ -/* not zero or the `A' switch is used), `elementattributelist' must be */ -/* initialized. `trianglearealist' may be ignored. */ -/* - `segmentlist' must be initialized if the `p' or `c' switch is used, */ -/* and the `P' switch is not used. `segmentmarkerlist' must also be */ -/* initialized under these circumstances unless the `B' switch is used. */ -/* - `edgelist' must be initialized if the `e' switch is used. */ -/* `edgemarkerlist' must be initialized if the `e' switch is used and */ -/* the `B' switch is not. */ -/* - `holelist', `regionlist', `normlist', and all scalars may be ignored.*/ -/* */ -/* `vorout' (only needed if `v' switch is used): */ -/* */ -/* - `pointlist' must be initialized. If `in->numberofpointattributes' */ -/* is not zero, `pointattributelist' must be initialized. */ -/* `pointmarkerlist' may be ignored. */ -/* - `edgelist' and `normlist' must both be initialized. */ -/* `edgemarkerlist' may be ignored. */ -/* - Everything else may be ignored. */ -/* */ -/* After a call to triangulate(), the valid fields of `out' and `vorout' */ -/* will depend, in an obvious way, on the choice of switches used. Note */ -/* that when the `p' switch is used, the pointers `holelist' and */ -/* `regionlist' are copied from `in' to `out', but no new space is */ -/* allocated; be careful that you don't free() the same array twice. On */ -/* the other hand, Triangle will never copy the `pointlist' pointer (or any */ -/* others); new space is allocated for `out->pointlist', or if the `N' */ -/* switch is used, `out->pointlist' remains uninitialized. */ -/* */ -/* All of the meaningful `numberof' fields will be properly set; for */ -/* instance, `numberofedges' will represent the number of edges in the */ -/* triangulation whether or not the edges were written. If segments are */ -/* not used, `numberofsegments' will indicate the number of boundary edges. */ -/* */ -/*****************************************************************************/ - -#ifdef __cplusplus -extern "C" { -#endif - -struct triangulateio { - REAL *pointlist; /* In / out */ - REAL *pointattributelist; /* In / out */ - int *pointmarkerlist; /* In / out */ - int numberofpoints; /* In / out */ - int numberofpointattributes; /* In / out */ - - int *trianglelist; /* In / out */ - REAL *triangleattributelist; /* In / out */ - REAL *trianglearealist; /* In only */ - int *neighborlist; /* Out only */ - int numberoftriangles; /* In / out */ - int numberofcorners; /* In / out */ - int numberoftriangleattributes; /* In / out */ - - int *segmentlist; /* In / out */ - int *segmentmarkerlist; /* In / out */ - int numberofsegments; /* In / out */ - - REAL *holelist; /* In / pointer to array copied out */ - int numberofholes; /* In / copied out */ - - REAL *regionlist; /* In / pointer to array copied out */ - int numberofregions; /* In / copied out */ - - int *edgelist; /* Out only */ - int *edgemarkerlist; /* Not used with Voronoi diagram; out only */ - REAL *normlist; /* Used only with Voronoi diagram; out only */ - int numberofedges; /* Out only */ -}; - -void triangulate(char *, struct triangulateio *, struct triangulateio *, - struct triangulateio *); - -#ifdef __cplusplus -} -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/view.cpp b/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/view.cpp deleted file mode 100644 index 88acc4bd..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/gtkgensurf/view.cpp +++ /dev/null @@ -1,1287 +0,0 @@ -/* -GenSurf plugin for GtkRadiant -Copyright (C) 2001 David Hyde, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include -#include -#include -#include "gensurf.h" - -#undef ISOMETRIC - -extern double backface; -extern double dh, dv; -extern double xmin,xmax,ymin,ymax,zmin,zmax; - -double SF, SFG; // Graphics scale factors -double XLo, XHi, YLo, YHi, ZLo, ZHi; -double yaw,roll; -double elevation,azimuth; -int cxChar = 10, cyChar = 16; -int X0, Y0; -int X0G, Y0G; - -static Rect rcCoord; // where X= Y= is drawn -static Rect rcGrid; // rectangle within rcLower that forms the border of the grid, plus - // a 3 pixel slop. -static Rect rcLower; // lower half of window, where plan view is drawn -static Rect rcUpper; // upper half or entire window, where isometric projection is drawn - -void vertex_selected (); -void texfont_init (); -void texfont_write (const char *text, int l, int t); - -#define PEN_GRID { \ - g_GLTable.m_pfn_qglLineWidth (1); \ - g_GLTable.m_pfn_qglColor3f (0, 1, 0); \ - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); } - -#define PEN_RED { \ - g_GLTable.m_pfn_qglLineWidth (2); \ - g_GLTable.m_pfn_qglColor3f (1, 0, 0); \ - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); } - -#define PEN_DASH { \ - g_GLTable.m_pfn_qglLineWidth (1); \ - g_GLTable.m_pfn_qglColor3f (0, 1, 0); \ - g_GLTable.m_pfn_qglLineStipple (1, 0xF0F0); \ - g_GLTable.m_pfn_qglEnable (GL_LINE_STIPPLE); } - -#define DRAW_QUAD(rc,r,g,b) { \ - g_GLTable.m_pfn_qglBegin (GL_QUADS); \ - g_GLTable.m_pfn_qglColor3f (0,1,0); \ - g_GLTable.m_pfn_qglVertex2i (rc.left-1, rc.bottom); \ - g_GLTable.m_pfn_qglVertex2i (rc.right, rc.bottom); \ - g_GLTable.m_pfn_qglVertex2i (rc.right, rc.top+1); \ - g_GLTable.m_pfn_qglVertex2i (rc.left-1, rc.top+1); \ - g_GLTable.m_pfn_qglColor3f (r,g,b); \ - g_GLTable.m_pfn_qglVertex2i (rc.left, rc.bottom+1); \ - g_GLTable.m_pfn_qglVertex2i (rc.right-1, rc.bottom+1); \ - g_GLTable.m_pfn_qglVertex2i (rc.right-1, rc.top); \ - g_GLTable.m_pfn_qglVertex2i (rc.left, rc.top); \ - g_GLTable.m_pfn_qglEnd (); } - - -#ifndef ISOMETRIC -double D=65536.; -double ct[3],st[3]; -double Hhi, Hlo, Vhi, Vlo; -#endif - -#define SUBDIVS 6 - - -void ShowPreview () -{ - if (Preview) - { - if (g_pWndPreview == NULL) - CreateViewWindow (); - gtk_widget_show (g_pWndPreview); - - UpdatePreview (true); - } - else - gtk_widget_hide (g_pWndPreview); -} - -static void draw_preview () -{ - int width = g_pPreviewWidget->allocation.width, height = g_pPreviewWidget->allocation.height; - - g_GLTable.m_pfn_qglClearColor (0, 0, 0, 1); - g_GLTable.m_pfn_qglViewport (0, 0, width, height); - g_GLTable.m_pfn_qglMatrixMode (GL_PROJECTION); - g_GLTable.m_pfn_qglLoadIdentity (); - g_GLTable.m_pfn_qglOrtho (0, width, 0, height, -1, 1); - g_GLTable.m_pfn_qglClear (GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); - - // ^Fishman - Antializing for the preview window. - if (Antialiasing) - { - g_GLTable.m_pfn_qglEnable(GL_BLEND); - g_GLTable.m_pfn_qglBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - g_GLTable.m_pfn_qglEnable(GL_LINE_SMOOTH); - } - else - { - g_GLTable.m_pfn_qglDisable(GL_BLEND); - g_GLTable.m_pfn_qglDisable(GL_LINE_SMOOTH); - } - - texfont_init (); - - if (!ValidSurface ()) - return; - - rcUpper.left = 0; - rcUpper.right = width; - rcUpper.bottom = 0; - rcUpper.top = height; - rcLower.left = 0; - rcLower.right = width; - rcLower.bottom = 0; - rcLower.top = height; - - if (VertexMode) - { - rcUpper.bottom = rcUpper.top/2; - DrawPreview (rcUpper); - g_GLTable.m_pfn_qglBegin (GL_LINES); - g_GLTable.m_pfn_qglVertex2i (rcUpper.left, rcUpper.bottom); - g_GLTable.m_pfn_qglVertex2i (rcUpper.right, rcUpper.bottom); - g_GLTable.m_pfn_qglEnd (); - rcLower.top = rcUpper.bottom-1; - DrawGrid (rcLower); - rcCoord.left = rcLower.left; - rcCoord.right = rcLower.right; - rcCoord.bottom = rcLower.bottom; - rcCoord.top = rcLower.top; - rcCoord.top = rcCoord.bottom+cyChar; - rcCoord.right = rcCoord.left + 15*cxChar; - rcGrid.left = X0G - 3; - rcGrid.bottom = Y0G - 3; - rcGrid.right = X0G + (int)(SFG*(Hur-Hll)) + 3; - rcGrid.top = Y0G + (int)(SFG*(Vur-Vll)) + 3; - } - else - DrawPreview (rcUpper); -} - -static gint expose (GtkWidget *widget, GdkEventExpose *event, gpointer data) -{ - if (event->count > 0) - return TRUE; - - if (!g_UIGtkTable.m_pfn_glwidget_make_current (g_pPreviewWidget)) - { - g_FuncTable.m_pfnSysPrintf ("GtkGenSurf: glMakeCurrent failed\n"); - return TRUE; - } - - draw_preview (); - - g_UIGtkTable.m_pfn_glwidget_swap_buffers (g_pPreviewWidget); - g_GLTable.m_pfn_QE_CheckOpenGLForErrors (); - - return TRUE; -} - -static void button_press (GtkWidget *widget, GdkEventButton *event, gpointer data) -{ - Point pt = { (long)event->x, widget->allocation.height - (long)event->y }; - bool Selected; - double x,y; - int i, j, k, ks; - int i0, i1, j0, j1; - - if ((!VertexMode) || (event->button != 1)) - return; - - if (!PtInRect (&rcGrid,pt)) - { - gdk_beep (); - return; - } - - x = Hll + (pt.x-X0G)/SFG; - y = Vur - (pt.y-Y0G)/SFG; - i = (int)(floor( (x-Hll)/dh - 0.5) + 1); - j = (int)(floor( (y-Vll)/dv - 0.5) + 1); - if (i < 0 || i > NH || j < 0 || j > NV) - { - gdk_beep (); - return; - } - - if(!CanEdit(i,j)) - { - gdk_beep (); - return; - } - - // Control key pressed - add this point, or remove it if already selected - if ((event->state & GDK_CONTROL_MASK) != 0) - { - Selected = FALSE; - if (NumVerticesSelected) - { - for (k=0; kstate & GDK_SHIFT_MASK) != 0) - { - if (NumVerticesSelected) - { - NumVerticesSelected = 1; - i0 = min(Vertex[0].i, i); - i1 = max(Vertex[0].i, i); - j0 = min(Vertex[0].j, j); - j1 = max(Vertex[0].j, j); - for(i=i0; i<=i1; i++) - { - for(j=j0; j<=j1; j++) - { - if(i==0 && j==0 ) continue; - if(i==NH && j==0 ) continue; - if(i==0 && j==NV) continue; - if(i==NH && j==NV) continue; - if(i != Vertex[0].i || j != Vertex[0].j) - { - Vertex[NumVerticesSelected].i = i; - Vertex[NumVerticesSelected].j = j; - NumVerticesSelected++; - } - } - } - } - else - { - Vertex[0].i = i; - Vertex[0].j = j; - NumVerticesSelected = 1; - } - } - else - { - Vertex[0].i = i; - Vertex[0].j = j; - NumVerticesSelected = 1; - } - - vertex_selected (); -} - -static void motion (GtkWidget *widget, GdkEventMotion *event, gpointer data) -{ - Point pt = { (long)event->x, widget->allocation.height - (long)event->y }; - - if (!VertexMode) - return; - - if (!g_UIGtkTable.m_pfn_glwidget_make_current (g_pPreviewWidget)) - { - g_FuncTable.m_pfnSysPrintf ("GtkGenSurf: glMakeCurrent failed\n"); - return; - } - - g_GLTable.m_pfn_qglEnable (GL_SCISSOR_TEST); - g_GLTable.m_pfn_qglScissor (rcCoord.left, rcCoord.bottom, rcCoord.right-rcCoord.left, - rcCoord.top-rcCoord.bottom); - g_GLTable.m_pfn_qglClear (GL_COLOR_BUFFER_BIT); - - if (PtInRect(&rcGrid,pt)) - { - GdkCursor *cursor = gdk_cursor_new (GDK_CROSS); - gdk_window_set_cursor (g_pWndPreview->window, cursor); - gdk_cursor_unref (cursor); - - char Text[32]; - int x, y; - - x = (int)(Hll + (pt.x-X0G)/SFG); - y = (int)(Vur - (pt.y-Y0G)/SFG); - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - sprintf(Text," x=%d, z=%d ",(int)(floor(x-0.5)+1.) ,(int)(floor(y-0.5)+1.) ); - break; - case PLANE_YZ0: - case PLANE_YZ1: - sprintf(Text," y=%d, z=%d ",(int)(floor(x-0.5)+1.) ,(int)(floor(y-0.5)+1.) ); - break; - default: - sprintf(Text," x=%d, y=%d ",(int)(floor(x-0.5)+1.) ,(int)(floor(y-0.5)+1.) ); - } - - texfont_write (Text, rcCoord.left, rcCoord.top); - } - else - { - gdk_window_set_cursor (g_pWndPreview->window, NULL); - } - - g_UIGtkTable.m_pfn_glwidget_swap_buffers (g_pPreviewWidget); - g_GLTable.m_pfn_QE_CheckOpenGLForErrors (); - g_GLTable.m_pfn_qglDisable (GL_SCISSOR_TEST); -} - -static gint preview_close (GtkWidget *widget, gpointer data) -{ - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (g_object_get_data (G_OBJECT (g_pWnd), "main_preview")), FALSE); - return TRUE; -} - -static void preview_focusout (GtkSpinButton *spin, GdkEventFocus *event, double *data) -{ - *data = DegreesToRadians ((double)(gtk_spin_button_get_value_as_int (spin) % 360)); - UpdatePreview (false); -} - -static gint doublevariable_spinfocusout(GtkWidget* widget, GdkEventFocus* event, gpointer data) -{ - preview_focusout(GTK_SPIN_BUTTON(widget), event, reinterpret_cast(data)); - return FALSE; -} - -static void preview_spin (GtkAdjustment *adj, double *data) -{ - *data = DegreesToRadians (adj->value); - UpdatePreview (false); -} - -void CreateViewWindow () -{ - GtkWidget *dlg, *vbox, *hbox, *label, *spin, *frame; - GtkObject *adj; - -#ifndef ISOMETRIC - elevation = PI/6.; - azimuth = PI/6.; -#endif - - g_pWndPreview = dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "GtkGenSurf Preview"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", GTK_SIGNAL_FUNC (preview_close), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (g_pWnd)); - gtk_window_set_default_size (GTK_WINDOW (dlg), 300, 400); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (dlg), vbox); - -#ifndef ISOMETRIC - hbox = gtk_hbox_new (TRUE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 0); - gtk_container_set_border_width (GTK_CONTAINER (hbox), 3); - - label = gtk_label_new ("Elevation"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0); - - adj = gtk_adjustment_new (30, -90, 90, 1, 10, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (preview_spin), &elevation); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_box_pack_start (GTK_BOX (hbox), spin, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (spin), "focus_out_event", G_CALLBACK (doublevariable_spinfocusout), &elevation); - - adj = gtk_adjustment_new (30, 0, 359, 1, 10, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (preview_spin), &azimuth); - spin = gtk_spin_button_new (GTK_ADJUSTMENT (adj), 1, 0); - gtk_widget_show (spin); - gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spin), TRUE); - gtk_box_pack_end (GTK_BOX (hbox), spin, FALSE, TRUE, 0); - - label = gtk_label_new ("Azimuth"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 1, 0.5); - gtk_box_pack_end (GTK_BOX (hbox), label, FALSE, TRUE, 0); - g_signal_connect (G_OBJECT (spin), "focus_out_event", G_CALLBACK (doublevariable_spinfocusout), &azimuth); -#endif - - frame = gtk_frame_new (NULL); - gtk_widget_show (frame); - gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN); - gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); - - g_pPreviewWidget = g_UIGtkTable.m_pfn_glwidget_new (FALSE, NULL); - - gtk_widget_set_events (g_pPreviewWidget, GDK_EXPOSURE_MASK|GDK_BUTTON_PRESS_MASK|GDK_POINTER_MOTION_MASK); - gtk_signal_connect (GTK_OBJECT (g_pPreviewWidget), "expose_event", GTK_SIGNAL_FUNC (expose), NULL); - gtk_signal_connect (GTK_OBJECT (g_pPreviewWidget), "motion_notify_event", GTK_SIGNAL_FUNC (motion), NULL); - gtk_signal_connect (GTK_OBJECT (g_pPreviewWidget), "button_press_event", - GTK_SIGNAL_FUNC (button_press), NULL); - - gtk_widget_show (g_pPreviewWidget); - gtk_container_add (GTK_CONTAINER (frame), g_pPreviewWidget); - - if (Preview) - gtk_widget_show (g_pWndPreview); - - UpdatePreview (true); -} - -//============================================================= -/* DrawPreview */ -void DrawPreview (Rect rc) -{ -#define COSXA 0.8660254037844 -#define SINXA 0.5 -#define COSYA 0.8660254037844 -#define SINYA 0.5 - - double L; - double x,y; - int i, j; - Point pt[8]; - XYZ v[8]; - char axis[3][2] = {"X","Y","Z"}; - -#ifndef ISOMETRIC - evaluate(); -#endif - - XLo = xmin; - XHi = xmax; - YLo = ymin; - YHi = ymax; - ZLo = zmin; - ZHi = zmax; - switch (Plane) - { - case PLANE_XY1: - ZHi = backface; - break; - case PLANE_XZ0: - YLo = backface; - break; - case PLANE_XZ1: - YHi = backface; - break; - case PLANE_YZ0: - XLo = backface; - break; - case PLANE_YZ1: - XHi = backface; - break; - default: - ZLo = backface; - } - - - - GetScaleFactor(rc); - //PEN_GRID - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); - - if (Decimate > 0 && (Game != QUAKE3 || UsePatches==0) ) - { - XYZ *vv; - - vv = (XYZ *) malloc(gNumNodes * sizeof(XYZ)); - for(i=0; i 2) - x = Hll + dh * (int)(NH/2 + 1); - else - x = Hll + dh * (int)(NH/2); - if(NV > 2) - y = Vll + dv * (int)(NV/2 + 1); - else - y = Vll + dv * (int)(NV/2); - } - else - { - if(NH > 1) - x = Hll + dh * (int)(NH/2); - else - x = Hll + dh/2; - if(NV > 1) - y = Vll + dv * (int)(NV/2); - else - y = Vll + dv/2; - } -// x = (Hll+Hur)/2.; -// y = (Vll+Vur)/2.; - v[0].p[0] = x + PlayerBox[Game].x[0]; - v[0].p[1] = y + PlayerBox[Game].y[0]; - v[0].p[2] = PlayerStartZ(x,y) + PlayerBox[Game].z[0] + 8; // add 8 cuz I'm a pessimist - } - v[1].p[0] = v[0].p[0] + PlayerBox[Game].x[1] - PlayerBox[Game].x[0]; - v[1].p[1] = v[0].p[1]; - v[1].p[2] = v[0].p[2]; - v[2].p[0] = v[1].p[0]; - v[2].p[1] = v[1].p[1] + PlayerBox[Game].y[1] - PlayerBox[Game].y[0]; - v[2].p[2] = v[0].p[2]; - v[3].p[0] = v[0].p[0]; - v[3].p[1] = v[2].p[1]; - v[3].p[2] = v[0].p[2]; - VectorCopy(v[0].p,v[4].p); - VectorCopy(v[1].p,v[5].p); - VectorCopy(v[2].p,v[6].p); - VectorCopy(v[3].p,v[7].p); - v[4].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - v[5].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - v[6].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - v[7].p[2] += PlayerBox[Game].z[1] - PlayerBox[Game].z[0]; - for(i=0; i<=7; i++) - { -#ifndef ISOMETRIC - project(&v[i]); -#endif - Scale(rc,v[i],&pt[i]); - } - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[3].x, pt[3].y); - for(i=0; i<=3; i++) - g_GLTable.m_pfn_qglVertex2i (pt[i].x, pt[i].y); - g_GLTable.m_pfn_qglEnd (); - g_GLTable.m_pfn_qglBegin (GL_LINE_STRIP); - g_GLTable.m_pfn_qglVertex2i (pt[7].x, pt[7].y); - for(i=4; i<=7; i++) - g_GLTable.m_pfn_qglVertex2i (pt[i].x, pt[i].y); - g_GLTable.m_pfn_qglEnd (); - g_GLTable.m_pfn_qglBegin (GL_LINES); - for(i=0; i<=3; i++) - { - g_GLTable.m_pfn_qglVertex2i (pt[i].x,pt[i].y); - g_GLTable.m_pfn_qglVertex2i (pt[i+4].x,pt[i+4].y); - } - g_GLTable.m_pfn_qglEnd (); - - g_GLTable.m_pfn_qglLineWidth (1); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); -} -//============================================================= -void DrawGrid(Rect rc) -{ - int i, j, k; - double h,w,x,y; - Point pt[2]; - Rect rcBox; - - w = (double)(rc.right-rc.left+1) - cxChar; - h = (double)(rc.top-rc.bottom+1) - cxChar - cyChar; - - SFG = w/(Hur-Hll); - SFG = min(SFG, h/(Vur-Vll)); - - // Center drawing - X0G = (int)(rc.left + rc.right - (int)(SFG*(Hur-Hll)))/2; - Y0G = (int)(rc.top + rc.bottom + cyChar - (int)(SFG*(Vur-Vll)))/2; - - g_GLTable.m_pfn_qglLineWidth (2); - g_GLTable.m_pfn_qglColor3f (0, 1, 0); - g_GLTable.m_pfn_qglDisable (GL_LINE_STIPPLE); - - pt[0].y = Y0G; - pt[1].y = Y0G + (int)(SFG*(Vur-Vll)); - g_GLTable.m_pfn_qglBegin (GL_LINES); - for(i=0; i<=NH; i++) - { - x = Hll + i * dh; - pt[0].x = X0G + (int)(SFG*(x-Hll)); - g_GLTable.m_pfn_qglVertex2i(pt[0].x, pt[0].y); - g_GLTable.m_pfn_qglVertex2i(pt[0].x, pt[1].y); - } - g_GLTable.m_pfn_qglEnd (); - pt[0].x = X0G; - pt[1].x = X0G + (int)(SFG*(Hur-Hll)); - g_GLTable.m_pfn_qglBegin (GL_LINES); - for(i=0; i<=NV; i++) - { - y = Vll + i * dv; - pt[0].y = Y0G + (int)(SFG*(Vur-y)); - g_GLTable.m_pfn_qglVertex2i (pt[0].x,pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[1].x,pt[0].y); - } - g_GLTable.m_pfn_qglEnd (); - - g_GLTable.m_pfn_qglLineWidth (1); - - // Draw axes - pt[0].x = rc.right - cyChar - cxChar - cyChar/2; - pt[0].y = rc.bottom + cyChar/2; - pt[1].x = pt[0].x + cyChar; - pt[1].y = pt[0].y; - g_GLTable.m_pfn_qglBegin (GL_LINES); - g_GLTable.m_pfn_qglVertex2i (pt[0].x,pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[1].x,pt[1].y); - g_GLTable.m_pfn_qglEnd (); - switch(Plane) - { - case PLANE_YZ0: - case PLANE_YZ1: - texfont_write ("Y", pt[1].x, pt[1].y+cyChar/2); - break; - default: - texfont_write ("X", pt[1].x, pt[1].y+cyChar/2); - } - pt[1].x = pt[0].x; - pt[1].y = pt[0].y + cyChar; - g_GLTable.m_pfn_qglBegin (GL_LINES); - g_GLTable.m_pfn_qglVertex2i (pt[0].x,pt[0].y); - g_GLTable.m_pfn_qglVertex2i (pt[1].x,pt[1].y); - g_GLTable.m_pfn_qglEnd (); - switch(Plane) - { - case PLANE_XY0: - case PLANE_XY1: - texfont_write ("Y", pt[1].x-cyChar/2, pt[1].y+cyChar); - break; - default: - texfont_write ("Z", pt[1].x-cyChar/2, pt[1].y+cyChar); - } - - // Denote fixed points with a 5x5 red rectangle - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - if(xyz[i][j].fixed) - { - x = Hll + i*dh; - y = Vll + j*dv; - rcBox.left = X0G + (int)(SFG*(x-Hll)) - 2; - rcBox.top = Y0G + (int)(SFG*(Vur-y)) + 2; - rcBox.right = rcBox.left + 5; - rcBox.bottom = rcBox.top - 5; - - DRAW_QUAD (rcBox, 1,0,0); - } - } - } - - // Denote currently selected point with a 5x5 green rectangle - if (NumVerticesSelected) - { - for(k=0; kp[0]; - y = v->p[1]; - z = v->p[2]; - - // yaw - xa = ct[0]*x - st[0]*z; - za = st[0]*x + ct[0]*z; - - // roll - x = ct[1]*xa + st[1]*y; - ya = ct[1]*y - st[1]*xa; - - // azimuth - z = ct[2]*za - st[2]*ya; - y = ct[2]*ya + st[2]*za; - - // horizontal and vertical projections: -// v->pp[0] = D*x/z; -// v->pp[1] = D*y/z; - v->pp[0] = -y; - v->pp[1] = x; - v->pp[2] = z; - - // NOTE: if perspective transformation is desired, - // set "persp" to the range from the surface, - // then: - // v->projected_h = -v->projected_h * persp/(v->projected_z-persp); - // v->projected_v = -v->projected_v * persp/(v->projected_z-persp); -} -/*=======================================================================*/ -void evaluate() -{ - int i, j; - XYZ v[4]; - - if(elevation > PI) elevation -= 2.*PI; - roll = elevation * sin(azimuth); - yaw = 1.5*PI + elevation*cos(azimuth); - - // Find angles from midpoint to viewpoint: - st[0] = sin(yaw); - st[1] = sin(roll); - st[2] = sin(azimuth); - ct[0] = cos(yaw); - ct[1] = cos(roll); - ct[2] = cos(azimuth); - - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - project(&xyz[i][j]); - } - } - - Hhi = xyz[0][0].pp[0]; - Hlo = Hhi; - Vhi = xyz[0][0].pp[1]; - Vlo = Vhi; - for(i=0; i<=NH; i++) - { - for(j=0; j<=NV; j++) - { - Hlo = min(Hlo,xyz[i][j].pp[0]); - Hhi = max(Hhi,xyz[i][j].pp[0]); - Vlo = min(Vlo,xyz[i][j].pp[1]); - Vhi = max(Vhi,xyz[i][j].pp[1]); - } - } - - // Include backface in min-max - VectorCopy(xyz[ 0][ 0].p,v[0].p); - VectorCopy(xyz[NH][ 0].p,v[1].p); - VectorCopy(xyz[NH][NV].p,v[2].p); - VectorCopy(xyz[ 0][NV].p,v[3].p); - switch(Plane) - { - case PLANE_XZ0: - case PLANE_XZ1: - v[0].p[1] = backface; - v[1].p[1] = v[0].p[1]; - v[2].p[1] = v[0].p[1]; - v[3].p[1] = v[0].p[1]; - break; - case PLANE_YZ0: - case PLANE_YZ1: - v[0].p[0] = backface; - v[1].p[0] = v[0].p[0]; - v[2].p[0] = v[0].p[0]; - v[3].p[0] = v[0].p[0]; - break; - default: - v[0].p[2] = backface; - v[1].p[2] = v[0].p[2]; - v[2].p[2] = v[0].p[2]; - v[3].p[2] = v[0].p[2]; - } - for(i=0; i<=3; i++) - { - project(&v[i]); - Hlo = min(Hlo,v[i].pp[0]); - Hhi = max(Hhi,v[i].pp[0]); - Vlo = min(Vlo,v[i].pp[1]); - Vhi = max(Vhi,v[i].pp[1]); - } - -} -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/hydratoolz.def b/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/hydratoolz.def deleted file mode 100644 index c48e519a..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/hydratoolz.def +++ /dev/null @@ -1,8 +0,0 @@ -; fgd.def : Declares the module parameters for the DLL. - -LIBRARY "HydraToolz" -DESCRIPTION 'HydraToolz Windows Dynamic Link Library' - -EXPORTS - ; Explicit exports can go here - Synapse_EnumerateInterfaces @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/plugin.cpp b/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/plugin.cpp deleted file mode 100644 index abc57fc3..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/plugin.cpp +++ /dev/null @@ -1,542 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "plugin.h" -#include "version.h" - -/*! \file plugin.cpp - \brief HydraToolz! - - HydraToolz by Dominic Clifton - Hydra (Hydra@Hydras-World.com) - - Overview - ======== - - - Version History - =============== - - v0.1 - 28/May/2002 - - Initial version. - - - ToDo - ==== - - * Code it ? :) - -*/ - -// ============================================================================= -// Globals - -_QERFuncTable_1 g_FuncTable; -_QERFileSystemTable g_FileSystemTable; -_QEREntityTable g_EntityTable; - -// cast to GtkWidget* -void *g_pMainWnd; - -// ============================================================================= -// Ripped from TexTool.cpp - -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)gtk_object_get_data (GTK_OBJECT (parent), "loop"); - ret = (int*)gtk_object_get_data (GTK_OBJECT (parent), "ret"); - - *loop = 0; - *ret = gpointer_to_int (data); -} - -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; - - gtk_widget_hide (widget); - loop = (int*)gtk_object_get_data (GTK_OBJECT (widget), "loop"); - *loop = 0; - - return TRUE; -} - -int DoMessageBox (const char* lpText, const char* lpCaption, guint32 uType) -{ - GtkWidget *window, *w, *vbox, *hbox; - int mode = (uType & MB_TYPEMASK), ret, loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_signal_connect (GTK_OBJECT (window), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_window_set_title (GTK_WINDOW (window), lpCaption); - gtk_container_border_width (GTK_CONTAINER (window), 10); - gtk_object_set_data (GTK_OBJECT (window), "loop", &loop); - gtk_object_set_data (GTK_OBJECT (window), "ret", &ret); - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - w = gtk_label_new (lpText); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - if (mode == MB_OK) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - ret = IDOK; - } - else if (mode == MB_OKCANCEL) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_show (w); - ret = IDCANCEL; - } - else if (mode == MB_YESNOCANCEL) - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_show (w); - ret = IDCANCEL; - } - else /* if (mode == MB_YESNO) */ - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); - gtk_widget_show (w); - ret = IDNO; - } - - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -// End of rip from TexTool.cpp - -// ============================================================================= -// Ripped from cmdlib.cpp - -/* -==================== -Extract file parts -==================== -*/ -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 ExtractFileName (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) - { - *dest++ = *src++; - } - *dest = 0; -} - -void ConvertDOSToUnixName( char *dst, const char *src ) -{ - while ( *src ) - { - if ( *src == '\\' ) - *dst = '/'; - else - *dst = *src; - dst++; src++; - } - *dst = 0; -} - -// End of rip from cmdlib.cpp - -// ============================================================================= -// Actual Plugin Code - -// get the wad name from the shader name (or an actual wadname) and add to a list of wad names making -// sure we don't add duplicates. - -GSList *AddToWadList(GSList *wadlist, const char *shadername, const char *wad) -{ - char tmpstr[QER_MAX_NAMELEN]; - char *wadname; - if (!shadername && !wad) return wadlist; - - if (shadername) - { - if (strcmp(shadername,"color") == 0) - return wadlist; - ExtractFilePath(shadername,tmpstr); - // Sys_Printf("checking: %s\n",shadername); - - int l = strlen(tmpstr) - 1; - - if (tmpstr[l] == '/' || tmpstr[l] == '\\') - tmpstr[l] = 0; - else - { - Sys_Printf("WARNING: Unknown wad file for shader %s\n",shadername); - return wadlist; - } - - ExtractFileName(tmpstr,tmpstr); - - wadname = (char *)malloc(strlen(tmpstr) + 5); - sprintf(wadname,"%s.wad",tmpstr); - } - else - { - wadname=strdup(wad); - } - - for (GSList *l = wadlist; l != NULL ; l = l->next) - { - if (string_equal_nocase((char *)l->data,wadname)) - { - free( wadname ); - return wadlist; - } - } - - Sys_Printf("Adding Wad File to WAD list: %s (reason: ",wadname); - if (shadername) - Sys_Printf("see shader \"%s\")\n", shadername); - else - Sys_Printf("already in WAD key. )\n"); - return ( g_slist_append (wadlist, wadname ) ); -} - -void UpdateWadKeyPair( void ) -{ - int i,nb; - - char wads[2048]; // change to CString usage ? - wads[0] = 0; - char *p1,*p2; - entity_t *pEntity; - epair_t *pEpair; - GSList *wadlist = NULL; - face_t *f; - brush_t *b; - char cleanwadname[QER_MAX_NAMELEN]; - const char *actualwad; - - - pEntity = (entity_t *)g_FuncTable.m_pfnGetEntityHandle(0); // get the worldspawn ent - - Sys_Printf("Searching for in-use wad files...\n"); - for(pEpair = pEntity->epairs; pEpair != NULL; pEpair = pEpair->next) - { - if (string_equal_nocase(pEpair->key,"wad")) - { - strcpy(wads,pEpair->value); - ConvertDOSToUnixName(wads,wads); - - // ok, we got the list of ; delimited wads, now split it into a GSList that contains - // just the wad names themselves. - - p1 = wads; - - do - { - p2 = strchr(p1,';'); - if (p2) - *p2 = 0; // swap the ; with a null terminator - - if (strchr(p1,'/') || strchr(p1,'\\')) - { - ExtractFileName(p1,cleanwadname); - wadlist = AddToWadList (wadlist, NULL, cleanwadname); - } - else - { - wadlist = AddToWadList (wadlist, NULL, p1); - } - if (p2) - p1 = p2+1; // point back to the remainder of the string - else - p1 = NULL; // make it so we exit the loop. - - } while (p1); - - // ok, now we have a list of wads in GSList. - // now we need to add any new wadfiles (with their paths) to this list - // so scan all brushes and see what wads are in use - // FIXME: scan brushes only in the region ? - - break; // we don't need to process any more key/pairs. - } - } - - nb = g_FuncTable.m_pfnAllocateActiveBrushHandles(); - for( i = 0; i < nb; i++ ) - { - b = (brush_t *)g_FuncTable.m_pfnGetActiveBrushHandle(i); - if (b->patchBrush) // patches in halflife ? - { - wadlist = AddToWadList(wadlist, b->pPatch->pShader->getName(),NULL); - } else - { - for (f=b->brush_faces ; f ; f=f->next) - { - wadlist = AddToWadList(wadlist, f->pShader->getName(),NULL); - } - } - } - g_FuncTable.m_pfnReleaseActiveBrushHandles(); - - nb = g_FuncTable.m_pfnAllocateSelectedBrushHandles(); - for( i = 0; i < nb; i++ ) - { - b = (brush_t *)g_FuncTable.m_pfnGetSelectedBrushHandle(i); - if (b->patchBrush) // patches in halflife ? - { - wadlist = AddToWadList(wadlist, b->pPatch->pShader->getName(),NULL); - } else - { - for (f=b->brush_faces ; f ; f=f->next) - { - wadlist = AddToWadList(wadlist, f->pShader->getName(),NULL); - } - } - } - g_FuncTable.m_pfnReleaseSelectedBrushHandles(); - - // Now we have a complete list of wadnames (without paths) so we just have to turn this - // back to a ; delimited list. - - wads[0] = 0; - while (wadlist) - { - if (string_equal_nocase((char *)wadlist->data,"common-hydra.wad")) - { - Sys_Printf("Skipping radiant-supplied wad file %s\n",(char *)wadlist->data); - } - else - { - if (wads[0]) - strcat(wads,";"); - - actualwad = vfsGetFullPath((char *)wadlist->data); - - if (actualwad) - { - strcat(wads, actualwad); - } - else - { - Sys_Printf("WARNING: could not locate wad file %s\n",(char *)wadlist->data); - strcat(wads, (char *)wadlist->data); - } - } - - free (wadlist->data); - wadlist = g_slist_remove (wadlist, wadlist->data); - } - - // store the wad list back in the worldspawn. - if (wads[0]) - { - //free(pEpair->value); - //pEpair->value = strdup(wads); - SetKeyValue(pEntity, "wad", wads); - } - -} - -// ============================================================================= -// PLUGIN INTERFACE STUFF - -// plugin name -const char *PLUGIN_NAME = "Q3 Texture Tools"; - -// commands in the menu -const char *PLUGIN_COMMANDS = "About...;Create/Update WAD keypair"; - -const char *PLUGIN_ABOUT = "HydraToolz for GTKRadiant\n\n" - "By Hydra!"; - -extern "C" void* WINAPI QERPlug_GetFuncTable () -{ - return &g_FuncTable; -} - -const char* QERPlug_Init (void* hApp, void *pWidget) -{ - GtkWidget* pMainWidget = static_cast(pWidget); - - g_pMainWnd = pMainWidget; - memset(&g_FuncTable, 0, sizeof(_QERFuncTable_1)); - g_FuncTable.m_nSize = sizeof(_QERFuncTable_1); - return "HydraToolz for GTKRadiant"; // do we need this ? hmmm -} - -const char* QERPlug_GetName() -{ - return (char*)PLUGIN_NAME; -} - -const char* QERPlug_GetCommandList() -{ - return PLUGIN_COMMANDS; -} - -extern "C" void QERPlug_Dispatch(const char* p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - if(!strcmp(p, "Create/Update WAD keypair")) - UpdateWadKeyPair(); - else if(!strcmp(p, "About...")) - g_FuncTable.m_pfnMessageBox((GtkWidget*)NULL, PLUGIN_ABOUT, "About", eMB_OK); -} - -// ============================================================================= -// SYNAPSE - -CSynapseServer* g_pSynapseServer = NULL; -CSynapseClientHydraToolz g_SynapseClient; - -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(PLUGIN_MAJOR, "HydraToolz", sizeof(_QERPluginTable)); - g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(g_FuncTable), SYN_REQUIRE, &g_FuncTable); - g_SynapseClient.AddAPI(VFS_MAJOR, "wad", sizeof(g_FileSystemTable), SYN_REQUIRE, &g_FileSystemTable); - g_SynapseClient.AddAPI(ENTITY_MAJOR, NULL, sizeof(g_EntityTable), SYN_REQUIRE, &g_EntityTable); - return &g_SynapseClient; -} - -bool CSynapseClientHydraToolz::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable *pTable = static_cast<_QERPluginTable*>(pAPI->mpTable); - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; -} - -const char* CSynapseClientHydraToolz::GetInfo() -{ - return "HydraToolz plugin built " __DATE__ " " RADIANT_VERSION; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/plugin.h b/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/plugin.h deleted file mode 100644 index 70e3ea9b..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/hydratoolz/plugin.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright (C) 1999-2006 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 _PLUGIN_H_ -#define _PLUGIN_H_ - -#include "mathlib.h" -#include -#include "qertypes.h" -#include - -#define USE_QERTABLE_DEFINE -#include "iscenegraph.h" -#include "qerplugin.h" - -#include "ifilesystem.h" -#define USE_ENTITYTABLE_DEFINE -#include "ientity.h" - -#include -#include -#include - -#include "iplugin.h" - -#include -#include "synapse.h" - -class CSynapseClientHydraToolz : public CSynapseClient -{ -public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - - CSynapseClientHydraToolz() { } - virtual ~CSynapseClientHydraToolz() { } -}; - -#endif // _PLUGIN_H_ diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/AboutDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/prtview/AboutDialog.cpp deleted file mode 100644 index 4ac45ab8..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/AboutDialog.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "AboutDialog.h" -#include -#include -#include "version.h" -#include "gtkutil/pointer.h" - -#include "prtview.h" -#include "ConfigDialog.h" - -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); - - *loop = 0; - *ret = gpointer_to_int(data); -} - -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; - - return TRUE; -} - -void DoAboutDlg () -{ - GtkWidget *dlg, *hbox, *vbox, *button, *label; - int loop = 1, ret = IDCANCEL; - - dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "About Portal Viewer"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_widget_show (hbox); - gtk_container_add (GTK_CONTAINER (dlg), hbox); - gtk_container_set_border_width (GTK_CONTAINER (hbox), 10); - - label = gtk_label_new ("Version 1.000\n\n" - "Gtk port by Leonardo Zide\nleo@lokigames.com\n\n" - "Written by Geoffrey DeWan\ngdewan@prairienet.org\n\n" - "Built against NetRadiant " RADIANT_VERSION "\n" - __DATE__ - ); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0); - gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT); - - vbox = gtk_vbox_new (FALSE, 0); - gtk_widget_show (vbox); - gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_widget_set_usize (button, 60, -2); - - gtk_grab_add (dlg); - gtk_widget_show (dlg); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); -} - - -///////////////////////////////////////////////////////////////////////////// -// CAboutDialog message handlers diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/AboutDialog.h b/misc/mediasource/extra/netradiant-src/contrib/prtview/AboutDialog.h deleted file mode 100644 index bf72885f..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/AboutDialog.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(INCLUDED_ABOUTDIALOG_H) -#define INCLUDED_ABOUTDIALOG_H - -void DoAboutDlg (); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/ConfigDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/prtview/ConfigDialog.cpp deleted file mode 100644 index 0b52adad..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/ConfigDialog.cpp +++ /dev/null @@ -1,526 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "ConfigDialog.h" -#include -#include -#include "gtkutil/pointer.h" - -#include "iscenegraph.h" - -#include "prtview.h" -#include "portals.h" - -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); - - *loop = 0; - *ret = gpointer_to_int(data); -} - -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; - - return TRUE; -} - -// ============================================================================= -// Color selection dialog - -static int DoColor (PackedColour *c) -{ - GtkWidget* dlg; - double clr[4]; - int loop = 1, ret = IDCANCEL; - - clr[0] = ((double)GetRValue (*c)) / 255.0; - clr[1] = ((double)GetGValue (*c)) / 255.0; - clr[2] = ((double)GetBValue (*c)) / 255.0; - - dlg = gtk_color_selection_dialog_new ("Choose Color"); - gtk_color_selection_set_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), clr); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_signal_connect (GTK_OBJECT (GTK_COLOR_SELECTION_DIALOG (dlg)->ok_button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_signal_connect (GTK_OBJECT (GTK_COLOR_SELECTION_DIALOG (dlg)->cancel_button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - gtk_widget_show(dlg); - gtk_grab_add(dlg); - - while (loop) - gtk_main_iteration (); - - gtk_color_selection_get_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), clr); - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); - - if (ret == IDOK) - { - *c = RGB (clr[0]*255, clr[1]*255, clr[2]*255); - } - - return ret; -} - -static void Set2DText (GtkWidget* label) -{ - char s[40]; - - sprintf(s, "Line Width = %6.3f", portals.width_2d * 0.5f); - - gtk_label_set_text (GTK_LABEL (label), s); -} - -static void Set3DText (GtkWidget* label) -{ - char s[40]; - - sprintf(s, "Line Width = %6.3f", portals.width_3d * 0.5f); - - gtk_label_set_text (GTK_LABEL (label), s); -} - -static void Set3DTransText (GtkWidget* label) -{ - char s[40]; - - sprintf(s, "Polygon transparency = %d%%", (int)portals.trans_3d); - - gtk_label_set_text (GTK_LABEL (label), s); -} - -static void SetClipText (GtkWidget* label) -{ - char s[40]; - - sprintf(s, "Cubic clip range = %d", (int)portals.clip_range * 64); - - gtk_label_set_text (GTK_LABEL (label), s); -} - -static void OnScroll2d (GtkAdjustment *adj, gpointer data) -{ - portals.width_2d = static_cast(adj->value); - Set2DText (GTK_WIDGET (data)); - - Portals_shadersChanged(); - SceneChangeNotify(); -} - -static void OnScroll3d (GtkAdjustment *adj, gpointer data) -{ - portals.width_3d = static_cast(adj->value); - Set3DText (GTK_WIDGET (data)); - - SceneChangeNotify(); -} - -static void OnScrollTrans (GtkAdjustment *adj, gpointer data) -{ - portals.trans_3d = static_cast(adj->value); - Set3DTransText (GTK_WIDGET (data)); - - SceneChangeNotify(); -} - -static void OnScrollClip (GtkAdjustment *adj, gpointer data) -{ - portals.clip_range = static_cast(adj->value); - SetClipText (GTK_WIDGET (data)); - - SceneChangeNotify(); -} - -static void OnAntiAlias2d (GtkWidget *widget, gpointer data) -{ - portals.aa_2d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; - - Portals_shadersChanged(); - - SceneChangeNotify(); -} - -static void OnConfig2d (GtkWidget *widget, gpointer data) -{ - portals.show_2d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; - - SceneChangeNotify(); -} - -static void OnColor2d (GtkWidget *widget, gpointer data) -{ - if (DoColor (&portals.color_2d) == IDOK) - { - Portals_shadersChanged(); - - SceneChangeNotify(); - } -} - -static void OnConfig3d (GtkWidget *widget, gpointer data) -{ - portals.show_3d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; - - SceneChangeNotify(); -} - - -static void OnAntiAlias3d (GtkWidget *widget, gpointer data) -{ - portals.aa_3d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; - - Portals_shadersChanged(); - SceneChangeNotify(); -} - -static void OnColor3d (GtkWidget *widget, gpointer data) -{ - if (DoColor (&portals.color_3d) == IDOK) - { - Portals_shadersChanged(); - - SceneChangeNotify(); - } -} - -static void OnColorFog (GtkWidget *widget, gpointer data) -{ - if (DoColor (&portals.color_fog) == IDOK) - { - Portals_shadersChanged(); - - SceneChangeNotify(); - } -} - -static void OnFog (GtkWidget *widget, gpointer data) -{ - portals.fog = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; - - Portals_shadersChanged(); - SceneChangeNotify(); -} - -static void OnSelchangeZbuffer (GtkWidget *widget, gpointer data) -{ - portals.zbuffer = gpointer_to_int(data); - - Portals_shadersChanged(); - SceneChangeNotify(); -} - -static void OnPoly (GtkWidget *widget, gpointer data) -{ - portals.polygons = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); - - SceneChangeNotify(); -} - -static void OnLines (GtkWidget *widget, gpointer data) -{ - portals.lines = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)); - - SceneChangeNotify(); -} - -static void OnClip (GtkWidget *widget, gpointer data) -{ - portals.clip = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget)) ? true : false; - - SceneChangeNotify(); -} - -void DoConfigDialog () -{ - GtkWidget *dlg, *hbox, *vbox, *vbox2, *button, *table, *frame; - GtkWidget *lw3slider, *lw3label, *lw2slider, *lw2label, *zlist, *menu, *item; - GtkWidget *aa2check, *aa3check, *depthcheck, *linescheck, *polyscheck; - GtkWidget *transslider, *translabel, *clipslider, *cliplabel; - GtkWidget *show2check, *show3check, *portalcheck; - int loop = 1, ret = IDCANCEL; - GtkObject *adj; - - dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "Portal Viewer Configuration"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (dlg), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - frame = gtk_frame_new ("3D View"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); - - vbox2 = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox2); - gtk_container_add (GTK_CONTAINER (frame), vbox2); - gtk_container_set_border_width (GTK_CONTAINER (vbox2), 5); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, TRUE, 0); - - adj = gtk_adjustment_new (portals.width_3d, 2, 40, 1, 1, 0); - lw3slider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (lw3slider); - gtk_box_pack_start (GTK_BOX (hbox), lw3slider, TRUE, TRUE, 0); - gtk_scale_set_draw_value (GTK_SCALE (lw3slider), FALSE); - - lw3label = gtk_label_new (""); - gtk_widget_show (lw3label); - gtk_box_pack_start (GTK_BOX (hbox), lw3label, FALSE, TRUE, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScroll3d), lw3label); - - table = gtk_table_new (2, 4, FALSE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox2), table, TRUE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - button = gtk_button_new_with_label ("Color"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (OnColor3d), NULL); - - button = gtk_button_new_with_label ("Depth Color"); - gtk_widget_show (button); - gtk_table_attach (GTK_TABLE (table), button, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (OnColorFog), NULL); - - aa3check = gtk_check_button_new_with_label ("Anti-Alias (May not work on some video cards)"); - gtk_widget_show (aa3check); - gtk_table_attach (GTK_TABLE (table), aa3check, 1, 4, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (aa3check), "toggled", GTK_SIGNAL_FUNC (OnAntiAlias3d), NULL); - - depthcheck = gtk_check_button_new_with_label ("Depth Cue"); - gtk_widget_show (depthcheck); - gtk_table_attach (GTK_TABLE (table), depthcheck, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (depthcheck), "toggled", GTK_SIGNAL_FUNC (OnFog), NULL); - - linescheck = gtk_check_button_new_with_label ("Lines"); - gtk_widget_show (linescheck); - gtk_table_attach (GTK_TABLE (table), linescheck, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (linescheck), "toggled", GTK_SIGNAL_FUNC (OnLines), NULL); - - polyscheck = gtk_check_button_new_with_label ("Polygons"); - gtk_widget_show (polyscheck); - gtk_table_attach (GTK_TABLE (table), polyscheck, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_signal_connect (GTK_OBJECT (polyscheck), "toggled", GTK_SIGNAL_FUNC (OnPoly), NULL); - - zlist = gtk_option_menu_new (); - gtk_widget_show (zlist); - gtk_box_pack_start (GTK_BOX (vbox2), zlist, TRUE, FALSE, 0); - - menu = gtk_menu_new (); - gtk_widget_show (menu); - gtk_option_menu_set_menu (GTK_OPTION_MENU (zlist), menu); - - item = gtk_menu_item_new_with_label ("Z-Buffer Test and Write (recommended for solid or no polygons)"); - gtk_widget_show (item); - gtk_signal_connect (GTK_OBJECT (item), "activate", - GTK_SIGNAL_FUNC (OnSelchangeZbuffer), GINT_TO_POINTER (0)); - gtk_menu_append (GTK_MENU (menu), item); - - item = gtk_menu_item_new_with_label ("Z-Buffer Test Only (recommended for transparent polygons)"); - gtk_widget_show (item); - gtk_signal_connect (GTK_OBJECT (item), "activate", - GTK_SIGNAL_FUNC (OnSelchangeZbuffer), GINT_TO_POINTER (1)); - gtk_menu_append (GTK_MENU (menu), item); - - item = gtk_menu_item_new_with_label ("Z-Buffer Off"); - gtk_widget_show (item); - gtk_signal_connect (GTK_OBJECT (item), "activate", - GTK_SIGNAL_FUNC (OnSelchangeZbuffer), GINT_TO_POINTER (2)); - gtk_menu_append (GTK_MENU (menu), item); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_box_pack_start (GTK_BOX (vbox2), table, TRUE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - adj = gtk_adjustment_new (portals.trans_3d, 0, 100, 1, 1, 0); - transslider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (transslider); - gtk_table_attach (GTK_TABLE (table), transslider, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_scale_set_draw_value (GTK_SCALE (transslider), FALSE); - - translabel = gtk_label_new (""); - gtk_widget_show (translabel); - gtk_table_attach (GTK_TABLE (table), translabel, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment (GTK_MISC (translabel), 0.0, 0.0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScrollTrans), translabel); - - adj = gtk_adjustment_new (portals.clip_range, 1, 128, 1, 1, 0); - clipslider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (clipslider); - gtk_table_attach (GTK_TABLE (table), clipslider, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_scale_set_draw_value (GTK_SCALE (clipslider), FALSE); - - cliplabel = gtk_label_new (""); - gtk_widget_show (cliplabel); - gtk_table_attach (GTK_TABLE (table), cliplabel, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment (GTK_MISC (cliplabel), 0.0, 0.0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScrollClip), cliplabel); - - hbox = gtk_hbox_new (TRUE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - show3check = gtk_check_button_new_with_label ("Show"); - gtk_widget_show (show3check); - gtk_box_pack_start (GTK_BOX (hbox), show3check, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (show3check), "toggled", GTK_SIGNAL_FUNC (OnConfig3d), NULL); - - portalcheck = gtk_check_button_new_with_label ("Portal cubic clipper"); - gtk_widget_show (portalcheck); - gtk_box_pack_start (GTK_BOX (hbox), portalcheck, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (portalcheck), "toggled", GTK_SIGNAL_FUNC (OnClip), NULL); - - frame = gtk_frame_new ("2D View"); - gtk_widget_show (frame); - gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); - - vbox2 = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox2); - gtk_container_add (GTK_CONTAINER (frame), vbox2); - gtk_container_set_border_width (GTK_CONTAINER (vbox2), 5); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - adj = gtk_adjustment_new (portals.width_2d, 2, 40, 1, 1, 0); - lw2slider = gtk_hscale_new (GTK_ADJUSTMENT (adj)); - gtk_widget_show (lw2slider); - gtk_box_pack_start (GTK_BOX (hbox), lw2slider, TRUE, TRUE, 0); - gtk_scale_set_draw_value (GTK_SCALE (lw2slider), FALSE); - - lw2label = gtk_label_new (""); - gtk_widget_show (lw2label); - gtk_box_pack_start (GTK_BOX (hbox), lw2label, FALSE, TRUE, 0); - gtk_signal_connect (adj, "value_changed", GTK_SIGNAL_FUNC (OnScroll2d), lw2label); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - button = gtk_button_new_with_label ("Color"); - gtk_widget_show (button); - gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (OnColor2d), NULL); - gtk_widget_set_usize (button, 60, -2); - - aa2check = gtk_check_button_new_with_label ("Anti-Alias (May not work on some video cards)"); - gtk_widget_show (aa2check); - gtk_box_pack_start (GTK_BOX (hbox), aa2check, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (aa2check), "toggled", GTK_SIGNAL_FUNC (OnAntiAlias2d), NULL); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox2), hbox, TRUE, FALSE, 0); - - show2check = gtk_check_button_new_with_label ("Show"); - gtk_widget_show (show2check); - gtk_box_pack_start (GTK_BOX (hbox), show2check, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (show2check), "toggled", GTK_SIGNAL_FUNC (OnConfig2d), NULL); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_widget_set_usize (button, 60, -2); - - // initialize dialog - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (show2check), portals.show_2d); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (aa2check), portals.aa_2d); - Set2DText (lw2label); - - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (show3check), portals.show_3d); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (depthcheck), portals.fog); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (polyscheck), portals.polygons); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (linescheck), portals.lines); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (aa3check), portals.aa_3d); - gtk_option_menu_set_history (GTK_OPTION_MENU (zlist), portals.zbuffer); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (portalcheck), portals.clip); - - Set3DText (lw3label); - Set3DTransText (translabel); - SetClipText (cliplabel); - - gtk_grab_add (dlg); - gtk_widget_show (dlg); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); -} - diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/ConfigDialog.h b/misc/mediasource/extra/netradiant-src/contrib/prtview/ConfigDialog.h deleted file mode 100644 index ef35db06..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/ConfigDialog.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(INCLUDED_CONFIGDIALOG_H) -#define INCLUDED_CONFIGDIALOG_H - -void DoConfigDialog (); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/LoadPortalFileDialog.cpp b/misc/mediasource/extra/netradiant-src/contrib/prtview/LoadPortalFileDialog.cpp deleted file mode 100644 index 03d84397..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/LoadPortalFileDialog.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -// LoadPortalFileDialog.cpp : implementation file -// - -#include "LoadPortalFileDialog.h" - -#include -#include -#include "stream/stringstream.h" -#include "convert.h" -#include "gtkutil/pointer.h" - -#include "qerplugin.h" - -#include "prtview.h" -#include "portals.h" - -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); - - *loop = 0; - *ret = gpointer_to_int(data); -} - -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; - - return TRUE; -} - -static void file_sel_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop; - char **filename; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - filename = (char**)g_object_get_data (G_OBJECT (parent), "filename"); - - *loop = 0; - if (gpointer_to_int(data) == IDOK) - *filename = g_strdup (gtk_file_selection_get_filename (GTK_FILE_SELECTION (parent))); -} - -static void change_clicked (GtkWidget *widget, gpointer data) -{ - GtkWidget* file_sel; - char* filename = NULL; - int loop = 1; - - file_sel = gtk_file_selection_new ("Locate portal (.prt) file"); - gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (file_sel)->ok_button), "clicked", - GTK_SIGNAL_FUNC (file_sel_callback), GINT_TO_POINTER (IDOK)); - gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (file_sel)->cancel_button), "clicked", - GTK_SIGNAL_FUNC (file_sel_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_signal_connect (GTK_OBJECT (file_sel), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_file_selection_hide_fileop_buttons (GTK_FILE_SELECTION (file_sel)); - - g_object_set_data (G_OBJECT (file_sel), "loop", &loop); - g_object_set_data (G_OBJECT (file_sel), "filename", &filename); - gtk_file_selection_set_filename (GTK_FILE_SELECTION (file_sel), portals.fn); - - gtk_grab_add (file_sel); - gtk_widget_show (file_sel); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (file_sel); - gtk_widget_destroy (file_sel); - - if (filename != NULL) - { - strcpy (portals.fn, filename); - gtk_entry_set_text (GTK_ENTRY (data), filename); - g_free (filename); - } -} - -int DoLoadPortalFileDialog () -{ - GtkWidget *dlg, *vbox, *hbox, *button, *entry, *check2d, *check3d; - int loop = 1, ret = IDCANCEL; - - dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_window_set_title (GTK_WINDOW (dlg), "Load .prt"); - gtk_signal_connect (GTK_OBJECT (dlg), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (dlg), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - g_object_set_data (G_OBJECT (dlg), "loop", &loop); - g_object_set_data (G_OBJECT (dlg), "ret", &ret); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add (GTK_CONTAINER (dlg), vbox); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - entry = gtk_entry_new (); - gtk_widget_show (entry); - gtk_entry_set_editable (GTK_ENTRY (entry), FALSE); - gtk_box_pack_start (GTK_BOX (vbox), entry, FALSE, FALSE, 0); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); - - check3d = gtk_check_button_new_with_label ("Show 3D"); - gtk_widget_show (check3d); - gtk_box_pack_start (GTK_BOX (hbox), check3d, FALSE, FALSE, 0); - - check2d = gtk_check_button_new_with_label ("Show 2D"); - gtk_widget_show (check2d); - gtk_box_pack_start (GTK_BOX (hbox), check2d, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("Change"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", GTK_SIGNAL_FUNC (change_clicked), entry); - gtk_widget_set_usize (button, 60, -2); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("Cancel"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_set_usize (button, 60, -2); - - button = gtk_button_new_with_label ("OK"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - gtk_signal_connect (GTK_OBJECT (button), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - gtk_widget_set_usize (button, 60, -2); - - strcpy (portals.fn, GlobalRadiant().getMapName()); - char* fn = strrchr (portals.fn, '.'); - if (fn != NULL) - { - strcpy(fn, ".prt"); - } - - StringOutputStream value(256); - value << portals.fn; - gtk_entry_set_text (GTK_ENTRY (entry), value.c_str()); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (check2d), portals.show_2d); - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (check3d), portals.show_3d); - - gtk_grab_add (dlg); - gtk_widget_show (dlg); - - while (loop) - gtk_main_iteration (); - - if (ret == IDOK) - { - portals.Purge(); - - portals.show_3d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (check3d)) ? true : false; - portals.show_2d = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (check2d)) ? true : false; - } - - gtk_grab_remove (dlg); - gtk_widget_destroy (dlg); - - return ret; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/LoadPortalFileDialog.h b/misc/mediasource/extra/netradiant-src/contrib/prtview/LoadPortalFileDialog.h deleted file mode 100644 index a4a40c6c..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/LoadPortalFileDialog.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(INCLUDED_LOADPORTALFILEDIALOG_H) -#define INCLUDED_LOADPORTALFILEDIALOG_H - -int DoLoadPortalFileDialog (); - -#endif - diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.aps b/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.aps deleted file mode 100644 index d86f0607..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.aps and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.def b/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.def deleted file mode 100644 index 7c18cf88..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.def +++ /dev/null @@ -1,7 +0,0 @@ -; PrtView.def : Declares the module parameters for the DLL. - -LIBRARY "PrtView" - -EXPORTS - ; Explicit exports can go here - Radiant_RegisterModules @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.txt b/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.txt deleted file mode 100644 index 50228e02..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/PrtView.txt +++ /dev/null @@ -1,12 +0,0 @@ -Put PrtView.dll in the Q3Radiant plugins directory. - -This program is pretty self explanitary, but point needs to -be mentioned. In the configuration menu for 3D view options, -the lines and polygons flags are tri-state. In the third state, -the lines or polygons will only be drawn if the have the -hint flag set. Older version of q3map will not set this flag -and the hint shader may have to be modified to set it. As of -this writing, I do not know all the details. - -Geoffrey DeWan -gdewan@prairienet.org \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/portals.cpp b/misc/mediasource/extra/netradiant-src/contrib/prtview/portals.cpp deleted file mode 100644 index d3bef1b6..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/portals.cpp +++ /dev/null @@ -1,652 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "portals.h" -#include -#include -#ifndef __APPLE__ -#include -#endif -#include - -#include "iglrender.h" -#include "cullable.h" - -#include "prtview.h" - -#define LINE_BUF 1000 - -CPortals portals; -CPortalsRender render; - -int compare( const void *arg1, const void *arg2 ) -{ - - if(portals.portal[*((int *)arg1)].dist > portals.portal[*((int *)arg2)].dist) - return -1; - else if(portals.portal[*((int *)arg1)].dist < portals.portal[*((int *)arg2)].dist) - return 1; - - return 0; -} - - -CBspPortal::CBspPortal() -{ - memset(this, 0, sizeof(CBspPortal)); -} - -CBspPortal::~CBspPortal() -{ - delete[] point; - delete[] inner_point; -} - -bool CBspPortal::Build(char *def) -{ - char *c = def; - unsigned int n; - int dummy1, dummy2; - int res_cnt, i; - - if(portals.hint_flags) - { - res_cnt = sscanf(def, "%u %d %d %d", &point_count, &dummy1, &dummy2, (int *)&hint); - } - else - { - sscanf(def, "%u", &point_count); - hint = false; - } - - if(point_count < 3 || (portals.hint_flags && res_cnt < 4)) - return false; - - point = new CBspPoint[point_count]; - inner_point = new CBspPoint[point_count]; - - for(n = 0; n < point_count; n++) - { - for(; *c != 0 && *c != '('; c++); - - if(*c == 0) - return false; - - c++; - - sscanf(c, "%f %f %f", point[n].p, point[n].p+1, point[n].p+2); - - center.p[0] += point[n].p[0]; - center.p[1] += point[n].p[1]; - center.p[2] += point[n].p[2]; - - if(n == 0) - { - for(i = 0; i < 3; i++) - { - min[i] = point[n].p[i]; - max[i] = point[n].p[i]; - } - } - else - { - for(i = 0; i < 3; i++) - { - if(min[i] > point[n].p[i]) - min[i] = point[n].p[i]; - if(max[i] < point[n].p[i]) - max[i] = point[n].p[i]; - } - } - } - - center.p[0] /= (float)point_count; - center.p[1] /= (float)point_count; - center.p[2] /= (float)point_count; - - for(n = 0; n < point_count; n++) - { - inner_point[n].p[0] = (0.01f * center.p[0]) + (0.99f * point[n].p[0]); - inner_point[n].p[1] = (0.01f * center.p[1]) + (0.99f * point[n].p[1]); - inner_point[n].p[2] = (0.01f * center.p[2]) + (0.99f * point[n].p[2]); - } - - fp_color_random[0] = (float)(rand() & 0xff) / 255.0f; - fp_color_random[1] = (float)(rand() & 0xff) / 255.0f; - fp_color_random[2] = (float)(rand() & 0xff) / 255.0f; - fp_color_random[3] = 1.0f; - - return true; -} - -CPortals::CPortals() -{ - memset(this, 0, sizeof(CPortals)); -} - -CPortals::~CPortals() -{ - Purge(); -} - -void CPortals::Purge() -{ - delete[] portal; - delete[] portal_sort; - portal = NULL; - portal_sort = NULL; - portal_count = 0; - - /* - delete[] node; - node = NULL; - node_count = 0; - */ -} - -void CPortals::Load() -{ - char buf[LINE_BUF+1]; - - memset(buf, 0, LINE_BUF + 1); - - Purge(); - - globalOutputStream() << MSG_PREFIX "Loading portal file " << fn << ".\n"; - - FILE *in; - - in = fopen(fn, "rt"); - - if(in == NULL) - { - globalOutputStream() << " ERROR - could not open file.\n"; - - return; - } - - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - if(strncmp("PRT1", buf, 4) != 0) - { - fclose(in); - - globalOutputStream() << " ERROR - File header indicates wrong file type (should be \"PRT1\").\n"; - - return; - } - - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - sscanf(buf, "%u", &node_count); -/* - if(node_count > 0xFFFF) - { - fclose(in); - - node_count = 0; - - globalOutputStream() << " ERROR - Extreme number of nodes, aborting.\n"; - - return; - } - */ - - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - node_count = 0; - - globalOutputStream() << " ERROR - File ended prematurely.\n"; - - return; - } - - sscanf(buf, "%u", &portal_count); - - if(portal_count > 0xFFFF) - { - fclose(in); - - portal_count = 0; - node_count = 0; - - globalOutputStream() << " ERROR - Extreme number of portals, aborting.\n"; - - return; - } - - if(portal_count == 0) - { - fclose(in); - - portal_count = 0; - node_count = 0; - - globalOutputStream() << " ERROR - number of portals equals 0, aborting.\n"; - - return; - } - -// node = new CBspNode[node_count]; - portal = new CBspPortal[portal_count]; - portal_sort = new int[portal_count]; - - unsigned int n; - bool first = true; - unsigned test_vals_1, test_vals_2; - - hint_flags = false; - - for(n = 0; n < portal_count; ) - { - if(!fgets(buf, LINE_BUF, in)) - { - fclose(in); - - Purge(); - - globalOutputStream() << " ERROR - Could not find information for portal number " << n + 1 << " of " << portal_count << ".\n"; - - return; - } - - if(!portal[n].Build(buf)) - { - if(first && sscanf(buf, "%d %d", &test_vals_1, &test_vals_2) == 1) // skip additional counts of later data, not needed - { - // We can count on hint flags being in the file - hint_flags = true; - continue; - } - - first = false; - - fclose(in); - - Purge(); - - globalOutputStream() << " ERROR - Information for portal number " << n + 1 << " of " << portal_count << " is not formatted correctly.\n"; - - return; - } - - n++; - } - - fclose(in); - - globalOutputStream() << " " << node_count << " portals read in.\n"; -} - -#include "math/matrix.h" - -const char* g_state_solid = "$plugins/prtview/solid"; -const char* g_state_solid_outline = "$plugins/prtview/solid_outline"; -const char* g_state_wireframe = "$plugins/prtview/wireframe"; -Shader* g_shader_solid = 0; -Shader* g_shader_solid_outline = 0; -Shader* g_shader_wireframe = 0; - -void Portals_constructShaders() -{ - OpenGLState state; - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortOverlayFirst; - state.m_linewidth = portals.width_2d * 0.5f; - state.m_colour[0] = portals.fp_color_2d[0]; - state.m_colour[1] = portals.fp_color_2d[1]; - state.m_colour[2] = portals.fp_color_2d[2]; - state.m_colour[3] = portals.fp_color_2d[3]; - if(portals.aa_2d) - { - state.m_state |= RENDER_BLEND|RENDER_LINESMOOTH; - } - GlobalOpenGLStateLibrary().insert(g_state_wireframe, state); - - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_FILL|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_COLOURCHANGE|RENDER_SMOOTH; - - if(portals.aa_3d) - { - state.m_state |= RENDER_POLYGONSMOOTH; - } - - switch(portals.zbuffer) - { - case 1: - state.m_state |= RENDER_DEPTHTEST; - break; - case 2: - break; - default: - state.m_state |= RENDER_DEPTHTEST; - state.m_state |= RENDER_DEPTHWRITE; - } - - if(portals.fog) - { - state.m_state |= RENDER_FOG; - - state.m_fog.mode = GL_EXP; - state.m_fog.density = 0.001f; - state.m_fog.start = 10.0f; - state.m_fog.end = 10000.0f; - state.m_fog.index = 0; - state.m_fog.colour[0] = portals.fp_color_fog[0]; - state.m_fog.colour[1] = portals.fp_color_fog[1]; - state.m_fog.colour[2] = portals.fp_color_fog[2]; - state.m_fog.colour[3] = portals.fp_color_fog[3]; - } - - GlobalOpenGLStateLibrary().insert(g_state_solid, state); - - GlobalOpenGLStateLibrary().getDefaultState(state); - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortOverlayFirst; - state.m_linewidth = portals.width_3d * 0.5f; - state.m_colour[0] = portals.fp_color_3d[0]; - state.m_colour[1] = portals.fp_color_3d[1]; - state.m_colour[2] = portals.fp_color_3d[2]; - state.m_colour[3] = portals.fp_color_3d[3]; - - if(portals.aa_3d) - { - state.m_state |= RENDER_LINESMOOTH; - } - - switch(portals.zbuffer) - { - case 1: - state.m_state |= RENDER_DEPTHTEST; - break; - case 2: - break; - default: - state.m_state |= RENDER_DEPTHTEST; - state.m_state |= RENDER_DEPTHWRITE; - } - - if(portals.fog) - { - state.m_state |= RENDER_FOG; - - state.m_fog.mode = GL_EXP; - state.m_fog.density = 0.001f; - state.m_fog.start = 10.0f; - state.m_fog.end = 10000.0f; - state.m_fog.index = 0; - state.m_fog.colour[0] = portals.fp_color_fog[0]; - state.m_fog.colour[1] = portals.fp_color_fog[1]; - state.m_fog.colour[2] = portals.fp_color_fog[2]; - state.m_fog.colour[3] = portals.fp_color_fog[3]; - } - - GlobalOpenGLStateLibrary().insert(g_state_solid_outline, state); - - g_shader_solid = GlobalShaderCache().capture(g_state_solid); - g_shader_solid_outline = GlobalShaderCache().capture(g_state_solid_outline); - g_shader_wireframe = GlobalShaderCache().capture(g_state_wireframe); -} - -void Portals_destroyShaders() -{ - GlobalShaderCache().release(g_state_solid); - GlobalShaderCache().release(g_state_solid_outline); - GlobalShaderCache().release(g_state_wireframe); - GlobalOpenGLStateLibrary().erase(g_state_solid); - GlobalOpenGLStateLibrary().erase(g_state_solid_outline); - GlobalOpenGLStateLibrary().erase(g_state_wireframe); -} - -void Portals_shadersChanged() -{ - Portals_destroyShaders(); - portals.FixColors(); - Portals_constructShaders(); -} - -void CPortals::FixColors() -{ - fp_color_2d[0] = (float)GetRValue(color_2d) / 255.0f; - fp_color_2d[1] = (float)GetGValue(color_2d) / 255.0f; - fp_color_2d[2] = (float)GetBValue(color_2d) / 255.0f; - fp_color_2d[3] = 1.0f; - - fp_color_3d[0] = (float)GetRValue(color_3d) / 255.0f; - fp_color_3d[1] = (float)GetGValue(color_3d) / 255.0f; - fp_color_3d[2] = (float)GetBValue(color_3d) / 255.0f; - fp_color_3d[3] = 1.0f; - - fp_color_fog[0] = 0.0f;//(float)GetRValue(color_fog) / 255.0f; - fp_color_fog[1] = 0.0f;//(float)GetGValue(color_fog) / 255.0f; - fp_color_fog[2] = 0.0f;//(float)GetBValue(color_fog) / 255.0f; - fp_color_fog[3] = 1.0f; -} - -void CPortalsRender::renderWireframe(Renderer& renderer, const VolumeTest& volume) const -{ - if(!portals.show_2d || portals.portal_count < 1) - return; - - renderer.SetState(g_shader_wireframe, Renderer::eWireframeOnly); - - renderer.addRenderable(m_drawWireframe, g_matrix4_identity); -} - -void CPortalsDrawWireframe::render(RenderStateFlags state) const -{ - unsigned int n, p; - - for(n = 0; n < portals.portal_count; n++) - { - glBegin(GL_LINE_LOOP); - - for(p = 0; p < portals.portal[n].point_count; p++) - glVertex3fv(portals.portal[n].point[p].p); - - glEnd(); - } -} - -CubicClipVolume calculateCubicClipVolume(const Matrix4& viewproj) -{ - CubicClipVolume clip; - clip.cam = vector4_projected( - matrix4_transformed_vector4( - matrix4_full_inverse(viewproj), - Vector4(0, 0, -1, 1) - ) - ); - clip.min[0] = clip.cam[0] + (portals.clip_range * 64.0f); - clip.min[1] = clip.cam[1] + (portals.clip_range * 64.0f); - clip.min[2] = clip.cam[2] + (portals.clip_range * 64.0f); - clip.max[0] = clip.cam[0] - (portals.clip_range * 64.0f); - clip.max[1] = clip.cam[1] - (portals.clip_range * 64.0f); - clip.max[2] = clip.cam[2] - (portals.clip_range * 64.0f); - return clip; -} - -void CPortalsRender::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - if(!portals.show_3d || portals.portal_count < 1) - return; - - CubicClipVolume clip = calculateCubicClipVolume(matrix4_multiplied_by_matrix4(volume.GetProjection(), volume.GetModelview())); - - if(portals.polygons) - { - renderer.SetState(g_shader_solid, Renderer::eWireframeOnly); - renderer.SetState(g_shader_solid, Renderer::eFullMaterials); - - m_drawSolid.clip = clip; - renderer.addRenderable(m_drawSolid, g_matrix4_identity); - } - - if(portals.lines) - { - renderer.SetState(g_shader_solid_outline, Renderer::eWireframeOnly); - renderer.SetState(g_shader_solid_outline, Renderer::eFullMaterials); - - m_drawSolidOutline.clip = clip; - renderer.addRenderable(m_drawSolidOutline, g_matrix4_identity); - } -} - -void CPortalsDrawSolid::render(RenderStateFlags state) const -{ - float trans = (100.0f - portals.trans_3d) / 100.0f; - - unsigned int n, p; - - if(portals.zbuffer != 0) - { - float d; - - for(n = 0; n < portals.portal_count; n++) - { - d = (float)clip.cam[0] - portals.portal[n].center.p[0]; - portals.portal[n].dist = d * d; - - d = (float)clip.cam[1] - portals.portal[n].center.p[1]; - portals.portal[n].dist += d * d; - - d = (float)clip.cam[2] - portals.portal[n].center.p[2]; - portals.portal[n].dist += d * d; - - portals.portal_sort[n] = n; - } - - qsort(portals.portal_sort, portals.portal_count, 4, compare); - - for(n = 0; n < portals.portal_count; n++) - { - if(portals.polygons == 2 && !portals.portal[portals.portal_sort[n]].hint) - continue; - - if(portals.clip) - { - if(clip.min[0] < portals.portal[portals.portal_sort[n]].min[0]) - continue; - else if(clip.min[1] < portals.portal[portals.portal_sort[n]].min[1]) - continue; - else if(clip.min[2] < portals.portal[portals.portal_sort[n]].min[2]) - continue; - else if(clip.max[0] > portals.portal[portals.portal_sort[n]].max[0]) - continue; - else if(clip.max[1] > portals.portal[portals.portal_sort[n]].max[1]) - continue; - else if(clip.max[2] > portals.portal[portals.portal_sort[n]].max[2]) - continue; - } - - glColor4f(portals.portal[portals.portal_sort[n]].fp_color_random[0], portals.portal[portals.portal_sort[n]].fp_color_random[1], - portals.portal[portals.portal_sort[n]].fp_color_random[2], trans); - - glBegin(GL_POLYGON); - - for(p = 0; p < portals.portal[portals.portal_sort[n]].point_count; p++) - glVertex3fv(portals.portal[portals.portal_sort[n]].point[p].p); - - glEnd(); - } - } - else - { - for(n = 0; n < portals.portal_count; n++) - { - if(portals.polygons == 2 && !portals.portal[n].hint) - continue; - - if(portals.clip) - { - if(clip.min[0] < portals.portal[n].min[0]) - continue; - else if(clip.min[1] < portals.portal[n].min[1]) - continue; - else if(clip.min[2] < portals.portal[n].min[2]) - continue; - else if(clip.max[0] > portals.portal[n].max[0]) - continue; - else if(clip.max[1] > portals.portal[n].max[1]) - continue; - else if(clip.max[2] > portals.portal[n].max[2]) - continue; - } - - glColor4f(portals.portal[n].fp_color_random[0], portals.portal[n].fp_color_random[1], - portals.portal[n].fp_color_random[2], trans); - - glBegin(GL_POLYGON); - - for(p = 0; p < portals.portal[n].point_count; p++) - glVertex3fv(portals.portal[n].point[p].p); - - glEnd(); - } - } -} - -void CPortalsDrawSolidOutline::render(RenderStateFlags state) const -{ - for(int n = 0; n < portals.portal_count; n++) - { - if(portals.lines == 2 && !portals.portal[n].hint) - continue; - - if(portals.clip) - { - if(clip.min[0] < portals.portal[n].min[0]) - continue; - else if(clip.min[1] < portals.portal[n].min[1]) - continue; - else if(clip.min[2] < portals.portal[n].min[2]) - continue; - else if(clip.max[0] > portals.portal[n].max[0]) - continue; - else if(clip.max[1] > portals.portal[n].max[1]) - continue; - else if(clip.max[2] > portals.portal[n].max[2]) - continue; - } - - glBegin(GL_LINE_LOOP); - - for(int p = 0; p < portals.portal[n].point_count; p++) - glVertex3fv(portals.portal[n].inner_point[p].p); - - glEnd(); - } -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/portals.h b/misc/mediasource/extra/netradiant-src/contrib/prtview/portals.h deleted file mode 100644 index c6bd678d..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/portals.h +++ /dev/null @@ -1,161 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef _PORTALS_H_ -#define _PORTALS_H_ - -#include -#include "irender.h" -#include "renderable.h" -#include "math/vector.h" - - -class CBspPoint { -public: - float p[3]; -}; - -class CBspPortal { -public: - CBspPortal(); - ~CBspPortal(); - -protected: - -public: - CBspPoint center; - unsigned point_count; - CBspPoint *point; - CBspPoint *inner_point; - float fp_color_random[4]; - float min[3]; - float max[3]; - float dist; - bool hint; - - bool Build(char *def); -}; - -#ifdef PATH_MAX -#define PRTVIEW_PATH_MAX PATH_MAX -#else -#define PRTVIEW_PATH_MAX 260 -#endif -typedef guint32 PackedColour; -#define RGB(r, g, b) ((guint32)(((guint8) (r) | ((guint16) (g) << 8))|(((guint32) (guint8) (b)) << 16))) -#define GetRValue(rgb) ((guint8)(rgb)) -#define GetGValue(rgb) ((guint8)(((guint16)(rgb)) >> 8)) -#define GetBValue(rgb) ((guint8)((rgb)>>16)) - - -class CPortals { -public: - - CPortals(); - ~CPortals(); - -protected: - - -public: - - void Load(); // use filename in fn - void Purge(); - - void FixColors(); - - char fn[PRTVIEW_PATH_MAX]; - - int zbuffer; - int polygons; - int lines; - bool show_3d; - bool aa_3d; - bool fog; - PackedColour color_3d; - float width_3d; // in 8'ths - float fp_color_3d[4]; - PackedColour color_fog; - float fp_color_fog[4]; - float trans_3d; - float clip_range; - bool clip; - - bool show_2d; - bool aa_2d; - PackedColour color_2d; - float width_2d; // in 8'ths - float fp_color_2d[4]; - - CBspPortal *portal; - int *portal_sort; - bool hint_flags; -// CBspNode *node; - - unsigned int node_count; - unsigned int portal_count; -}; - -class CubicClipVolume -{ -public: - Vector3 cam, min, max; -}; - -class CPortalsDrawSolid : public OpenGLRenderable -{ -public: - mutable CubicClipVolume clip; - void render(RenderStateFlags state) const; -}; - -class CPortalsDrawSolidOutline : public OpenGLRenderable -{ -public: - mutable CubicClipVolume clip; - void render(RenderStateFlags state) const; -}; - -class CPortalsDrawWireframe : public OpenGLRenderable -{ -public: - void render(RenderStateFlags state) const; -}; - -class CPortalsRender : public Renderable -{ -public: - CPortalsDrawSolid m_drawSolid; - CPortalsDrawSolidOutline m_drawSolidOutline; - CPortalsDrawWireframe m_drawWireframe; - - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const; -}; - -extern CPortals portals; -extern CPortalsRender render; - -void Portals_constructShaders(); -void Portals_destroyShaders(); - -void Portals_shadersChanged(); - - -#endif // _PORTALS_H_ diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/prtview.cpp b/misc/mediasource/extra/netradiant-src/contrib/prtview/prtview.cpp deleted file mode 100644 index c5ed86c9..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/prtview.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - - -#include "prtview.h" -#include -#include - -#include "profile/profile.h" - -#include "qerplugin.h" -#include "iscenegraph.h" -#include "iglrender.h" -#include "iplugin.h" -#include "stream/stringstream.h" - -#include "portals.h" -#include "AboutDialog.h" -#include "ConfigDialog.h" -#include "LoadPortalFileDialog.h" - -#define Q3R_CMD_SPLITTER "-" -#define Q3R_CMD_ABOUT "About Portal Viewer" -#define Q3R_CMD_LOAD "Load .prt file" -#define Q3R_CMD_RELEASE "Unload .prt file" -#define Q3R_CMD_SHOW_3D "Toggle portals (3D)" -#define Q3R_CMD_SHOW_2D "Toggle portals (2D)" -#define Q3R_CMD_OPTIONS "Configure Portal Viewer" - -CopiedString INIfn; - -///////////////////////////////////////////////////////////////////////////// -// CPrtViewApp construction - -#define RENDER_2D "Render2D" -#define WIDTH_2D "Width2D" -#define AA_2D "AntiAlias2D" -#define COLOR_2D "Color2D" - -#define RENDER_3D "Render3D" -#define WIDTH_3D "Width3D" -#define AA_3D "AntiAlias3D" -#define COLOR_3D "Color3D" -#define COLOR_FOG "ColorFog" -#define FOG "Fog" -#define ZBUFFER "ZBuffer" -#define POLYGON "Polygons" -#define LINE "Lines" -#define TRANS_3D "Transparency" -#define CLIP_RANGE "ClipRange" -#define CLIP "Clip" - - -void PrtView_construct() -{ - StringOutputStream tmp(64); - tmp << GlobalRadiant().getSettingsPath() << "prtview.ini"; - INIfn = tmp.c_str(); - - portals.show_2d = INIGetInt(RENDER_2D, FALSE) ? true : false; - portals.aa_2d = INIGetInt(AA_2D, FALSE) ? true : false; - portals.width_2d = (float)INIGetInt(WIDTH_2D, 10); - portals.color_2d = (PackedColour)INIGetInt(COLOR_2D, RGB(0, 0, 255)) & 0xFFFFFF; - - if (portals.width_2d > 40.0f) - portals.width_2d = 40.0f; - else if (portals.width_2d < 2.0f) - portals.width_2d = 2.0f; - - portals.show_3d = INIGetInt(RENDER_3D, TRUE) ? true : false; - - portals.zbuffer = INIGetInt(ZBUFFER, 1); - portals.fog = INIGetInt(FOG, FALSE) ? true : false; - portals.polygons = INIGetInt(POLYGON, TRUE); - portals.lines = INIGetInt(LINE, TRUE); - portals.aa_3d = INIGetInt(AA_3D, FALSE) ? true : false; - portals.width_3d = (float)INIGetInt(WIDTH_3D, 4); - portals.color_3d = (PackedColour)INIGetInt(COLOR_3D, RGB(255, 255, 0)) & 0xFFFFFF; - portals.color_fog = (PackedColour)INIGetInt(COLOR_FOG, RGB(127, 127, 127)) & 0xFFFFFF; - portals.trans_3d = (float)INIGetInt(TRANS_3D, 50); - portals.clip = INIGetInt(CLIP, FALSE) ? true : false; - portals.clip_range = (float)INIGetInt(CLIP_RANGE, 16); - - if (portals.clip_range < 1) - portals.clip_range = 1; - else if (portals.clip_range > 128) - portals.clip_range = 128; - - if (portals.zbuffer < 0) - portals.zbuffer = 0; - else if (portals.zbuffer > 2) - portals.zbuffer = 0; - - if (portals.width_3d > 40.0f) - portals.width_3d = 40.0f; - else if (portals.width_3d < 2.0f) - portals.width_3d = 2.0f; - - if (portals.trans_3d > 100.0f) - portals.trans_3d = 100.0f; - else if (portals.trans_3d < 0.0f) - portals.trans_3d = 0.0f; - - SaveConfig(); - - portals.FixColors(); - - Portals_constructShaders(); - GlobalShaderCache().attachRenderable(render); -} - -void PrtView_destroy() -{ - GlobalShaderCache().detachRenderable(render); - Portals_destroyShaders(); -} - -void SaveConfig () -{ - INISetInt(RENDER_2D, portals.show_2d, "Draw in 2D windows"); - INISetInt(WIDTH_2D, (int)portals.width_2d, "Width of lines in 2D windows (in units of 1/2)"); - INISetInt(COLOR_2D, (int)portals.color_2d, "Color of lines in 2D windows"); - INISetInt(AA_2D, portals.aa_2d, "Draw lines in 2D window anti-aliased"); - - INISetInt(ZBUFFER, portals.zbuffer, "ZBuffer level in 3D window"); - INISetInt(FOG, portals.fog, "Use depth cueing in 3D window"); - INISetInt(POLYGON, portals.polygons, "Render using polygons polygons in 3D window"); - INISetInt(LINE, portals.polygons, "Render using lines in 3D window"); - INISetInt(RENDER_3D, portals.show_3d, "Draw in 3D windows"); - INISetInt(WIDTH_3D, (int)portals.width_3d, "Width of lines in 3D window (in units of 1/2)"); - INISetInt(COLOR_3D, (int)portals.color_3d, "Color of lines/polygons in 3D window"); - INISetInt(COLOR_FOG, (int)portals.color_fog, "Color of distant lines/polygons in 3D window"); - INISetInt(AA_3D, portals.aa_3d, "Draw lines in 3D window anti-aliased"); - INISetInt(TRANS_3D, (int)portals.trans_3d, "Transparency in 3d view (0 = solid, 100 = invisible)"); - INISetInt(CLIP, portals.clip, "Cubic clipper active for portal viewer"); - INISetInt(CLIP_RANGE, (int)portals.clip_range, "Portal viewer cubic clip distance (in units of 64)"); -} - - -#define CONFIG_SECTION "Configuration" - -int INIGetInt(char *key, int def) -{ - char value[1024]; - - if (read_var (INIfn.c_str(), CONFIG_SECTION, key, value)) - return atoi (value); - else - return def; -} - -void INISetInt(char *key, int val, char *comment /* = NULL */) -{ - char s[1000]; - - if(comment) - sprintf(s, "%d ; %s", val, comment); - else - sprintf(s, "%d", val); - save_var (INIfn.c_str(), CONFIG_SECTION, key, s); -} - - -// plugin name -static const char *PLUGIN_NAME = "Portal Viewer"; -// commands in the menu -static const char *PLUGIN_COMMANDS = - Q3R_CMD_ABOUT ";" - Q3R_CMD_SPLITTER ";" - Q3R_CMD_OPTIONS ";" - Q3R_CMD_SPLITTER ";" - Q3R_CMD_SHOW_2D ";" - Q3R_CMD_SHOW_3D ";" - Q3R_CMD_SPLITTER ";" - Q3R_CMD_RELEASE ";" - Q3R_CMD_LOAD; - - - -const char* QERPlug_Init (void *hApp, void* pMainWidget) -{ - return "Portal Viewer for Q3Radiant"; -} - -const char* QERPlug_GetName() -{ - return PLUGIN_NAME; -} - -const char* QERPlug_GetCommandList() -{ - return PLUGIN_COMMANDS; -} - - -const char* QERPlug_GetCommandTitleList() -{ - return ""; -} - - -void QERPlug_Dispatch(const char* p, float* vMin, float* vMax, bool bSingleBrush) -{ - globalOutputStream() << MSG_PREFIX "Command \"" << p << "\"\n"; - - if (!strcmp(p,Q3R_CMD_ABOUT)) - { - DoAboutDlg (); - } - else if (!strcmp(p,Q3R_CMD_LOAD)) - { - if (DoLoadPortalFileDialog () == IDOK) - { - portals.Load(); - SceneChangeNotify(); - } - else - { - globalOutputStream() << MSG_PREFIX "Portal file load aborted.\n"; - } - } - else if (!strcmp(p,Q3R_CMD_RELEASE)) - { - portals.Purge(); - - SceneChangeNotify(); - - globalOutputStream() << MSG_PREFIX "Portals unloaded.\n"; - } - else if (!strcmp(p,Q3R_CMD_SHOW_2D)) - { - portals.show_2d = !portals.show_2d; - - SceneChangeNotify(); - SaveConfig(); - - if(portals.show_2d) - globalOutputStream() << MSG_PREFIX "Portals will be rendered in 2D view.\n"; - else - globalOutputStream() << MSG_PREFIX "Portals will NOT be rendered in 2D view.\n"; - } - else if (!strcmp(p,Q3R_CMD_SHOW_3D)) - { - portals.show_3d = !portals.show_3d; - SaveConfig(); - - SceneChangeNotify(); - - if (portals.show_3d) - globalOutputStream() << MSG_PREFIX "Portals will be rendered in 3D view.\n"; - else - globalOutputStream() << MSG_PREFIX "Portals will NOT be rendered in 3D view.\n"; - } - else if (!strcmp(p,Q3R_CMD_OPTIONS)) - { - DoConfigDialog (); - SaveConfig(); - - SceneChangeNotify(); - } -} - - -#include "modulesystem/singletonmodule.h" - -class PrtViewPluginDependencies : - public GlobalSceneGraphModuleRef, - public GlobalRadiantModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalOpenGLModuleRef, - public GlobalOpenGLStateLibraryModuleRef -{ -}; - -class PrtViewPluginModule -{ - _QERPluginTable m_plugin; -public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "prtview"); - - PrtViewPluginModule() - { - m_plugin.m_pfnQERPlug_Init = QERPlug_Init; - m_plugin.m_pfnQERPlug_GetName = QERPlug_GetName; - m_plugin.m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = QERPlug_GetCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - - PrtView_construct(); - } - ~PrtViewPluginModule() - { - PrtView_destroy(); - } - _QERPluginTable* getTable() - { - return &m_plugin; - } -}; - -typedef SingletonModule SingletonPrtViewPluginModule; - -SingletonPrtViewPluginModule g_PrtViewPluginModule; - - -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - - g_PrtViewPluginModule.selfRegister(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/prtview.h b/misc/mediasource/extra/netradiant-src/contrib/prtview/prtview.h deleted file mode 100644 index 472b028a..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/prtview.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -PrtView plugin for GtkRadiant -Copyright (C) 2001 Geoffrey Dewan, Loki software and qeradiant.com - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#if !defined(INCLUDED_PRTVIEW_H) -#define INCLUDED_PRTVIEW_H - -#define MSG_PREFIX "Portal Viewer plugin: " - -void InitInstance (); -void SaveConfig (); - -int INIGetInt(char *key, int def); -void INISetInt(char *key, int val, char *comment = 0); - -#define IDOK 1 -#define IDCANCEL 2 - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/prtview/res/PrtView.rc2 b/misc/mediasource/extra/netradiant-src/contrib/prtview/res/PrtView.rc2 deleted file mode 100644 index a534b6a2..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/prtview/res/PrtView.rc2 +++ /dev/null @@ -1,13 +0,0 @@ -// -// PRTVIEW.RC2 - resources Microsoft Visual C++ does not edit directly -// - -#ifdef APSTUDIO_INVOKED - #error this file is not editable by Microsoft Visual C++ -#endif //APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// Add manually edited resources here... - -///////////////////////////////////////////////////////////////////////////// diff --git a/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.cpp b/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.cpp deleted file mode 100644 index 6554790b..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.cpp +++ /dev/null @@ -1,263 +0,0 @@ -/* -Copyright (C) 2006, Stefan Greven. -All Rights Reserved. - -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 "shaderplug.h" - -#include "debugging/debugging.h" - -#include -#include -#include "string/string.h" -#include "modulesystem/singletonmodule.h" -#include "stream/stringstream.h" -#include "os/file.h" - -#include - -#include "iplugin.h" -#include "qerplugin.h" -#include "ifilesystem.h" -#include "iarchive.h" -#include "ishaders.h" -#include "iscriplib.h" - -#include "generic/callback.h" - -namespace { -const char SHADERTAG_FILE[] = "shadertags.xml"; -} - -class ShaderPlugPluginDependencies : public GlobalRadiantModuleRef, - public GlobalFileSystemModuleRef, - public GlobalShadersModuleRef -{ -public: - ShaderPlugPluginDependencies() : - GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")) - { - } -}; - -namespace Shaderplug -{ - GtkWindow* g_window; - - std::vector archives; - std::set shaders; - std::set textures; - - XmlTagBuilder TagBuilder; - void CreateTagFile(); - - const char* init(void* hApp, void* pMainWidget) - { - g_window = GTK_WINDOW(pMainWidget); - return ""; - } - const char* getName() - { - return "ShaderPlug"; - } - const char* getCommandList() - { - return "About;Create tag file"; - } - const char* getCommandTitleList() - { - return ""; - } - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) - { - if(string_equal(command, "About")) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), "Shaderplug (1.0)\n\n" - "by Shaderman (shaderman@gmx.net)", - "About", - eMB_OK, - eMB_ICONDEFAULT); - } - if(string_equal(command, "Create tag file")) - { - CreateTagFile(); - } - } - - void loadArchiveFile(const char* filename) - { - archives.push_back(filename); - } - - typedef FreeCaller1 LoadArchiveFileCaller; - - void LoadTextureFile(const char* filename) - { - std::string s_filename = filename; - - char buffer[256]; - strcpy(buffer, "textures/"); - - // append filename without trailing file extension (.tga or .jpg for example) - strncat(buffer, filename, s_filename.length() - 4); - - std::set::iterator iter; - iter = shaders.find(buffer); - - // a shader with this name already exists - if(iter == shaders.end()) - { - textures.insert(buffer); - } - } - - typedef FreeCaller1 LoadTextureFileCaller; - - void GetTextures(char* extension) - { - GlobalFileSystem().forEachFile("textures/", extension, LoadTextureFileCaller(), 0); - } - - void LoadShaderList(const char* filename) - { - if(string_equal_prefix(filename, "textures/")) - { - shaders.insert(filename); - } - } - - typedef FreeCaller1 LoadShaderListCaller; - - void GetAllShaders() - { - GlobalShaderSystem().foreachShaderName(LoadShaderListCaller()); - } - - void GetArchiveList() - { - GlobalFileSystem().forEachArchive(LoadArchiveFileCaller()); - globalOutputStream() << "Shaderplug: " << (const Unsigned)Shaderplug::archives.size() << " archives found.\n"; - } - - void CreateTagFile() - { - const char* shader_type = GlobalRadiant().getGameDescriptionKeyValue("shaders"); - - GetAllShaders(); - globalOutputStream() << "Shaderplug: " << (const Unsigned)shaders.size() << " shaders found.\n"; - - if(string_equal(shader_type, "quake3")) - { - GetTextures("jpg"); - GetTextures("tga"); - GetTextures("png"); - - globalOutputStream() << "Shaderplug: " << (const Unsigned)textures.size() << " textures found.\n"; - } - - if(shaders.size() || textures.size() != 0) - { - globalOutputStream() << "Shaderplug: Creating XML tag file.\n"; - - TagBuilder.CreateXmlDocument(); - - std::set::reverse_iterator r_iter; - - for(r_iter = textures.rbegin(); r_iter != textures.rend(); ++r_iter) - { - TagBuilder.AddShaderNode(const_cast((*r_iter).c_str()), STOCK, TEXTURE); - } - - for(r_iter = shaders.rbegin(); r_iter != shaders.rend(); ++r_iter) - { - TagBuilder.AddShaderNode(const_cast((*r_iter).c_str()), STOCK, SHADER); - } - - // Get the tag file - StringOutputStream tagFileStream(256); - tagFileStream << GlobalRadiant().getLocalRcPath() << SHADERTAG_FILE; - char* tagFile = tagFileStream.c_str(); - - char message[256]; - strcpy(message, "Tag file saved to\n"); - strcat(message, tagFile); - strcat(message, "\nPlease restart Radiant now.\n"); - - if(file_exists(tagFile)) - { - EMessageBoxReturn result = GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), - "WARNING! A tag file already exists! Overwrite it?", "Overwrite tag file?", - eMB_NOYES, - eMB_ICONWARNING); - - if(result == eIDYES) - { - TagBuilder.SaveXmlDoc(tagFile); - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), message, "INFO", eMB_OK, eMB_ICONASTERISK); - } - } else { - TagBuilder.SaveXmlDoc(tagFile); - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), message, "INFO", eMB_OK, eMB_ICONASTERISK); - } - } else { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_window), - "No shaders or textures found. No XML tag file created!\n" - "", - "ERROR", - eMB_OK, - eMB_ICONERROR); - } - } -} // namespace - -class ShaderPluginModule -{ - _QERPluginTable m_plugin; -public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "ShaderPlug"); - - ShaderPluginModule() - { - m_plugin.m_pfnQERPlug_Init = &Shaderplug::init; - m_plugin.m_pfnQERPlug_GetName = &Shaderplug::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &Shaderplug::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &Shaderplug::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &Shaderplug::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } -}; - -typedef SingletonModule SingletonShaderPluginModule; - -SingletonShaderPluginModule g_ShaderPluginModule; - -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - - g_ShaderPluginModule.selfRegister(); -} - - - - diff --git a/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.def b/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.def deleted file mode 100644 index a31ee3b4..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.def +++ /dev/null @@ -1,7 +0,0 @@ -; shaderplug.def : Declares the module parameters for the DLL. - -LIBRARY "SHADERPLUG" - -EXPORTS - ; Explicit exports can go here - Radiant_RegisterModules @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.h b/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.h deleted file mode 100644 index 7ee45fd2..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/shaderplug/shaderplug.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright (C) 2006, Stefan Greven. -All Rights Reserved. - -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(INCLUDED_SHADERPLUG_H) -#define INCLUDED_SHADERPLUG_H - -#include "xml/xmltextags.h" - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.cpp b/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.cpp deleted file mode 100644 index fa005426..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/* -Sunplug plugin for GtkRadiant -Copyright (C) 2004 Topsun -Thanks to SPoG for help! - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#include "sunplug.h" - -#include "debugging/debugging.h" - -#include "iplugin.h" - -#include "string/string.h" -#include "modulesystem/singletonmodule.h" - -#include "iundo.h" // declaration of undo system -#include "ientity.h" // declaration of entity system -#include "iscenegraph.h" // declaration of datastructure of the map - -#include "scenelib.h" // declaration of datastructure of the map -#include "qerplugin.h" // declaration to use other interfaces as a plugin - -#include // to display something with gtk (windows, buttons etc.), the whole package might not be necessary - -void about_plugin_window(); -void MapCoordinator(); - -#ifndef _WIN32 -// linux itoa implementation -char* itoa( int value, char* result, int base ) -{ - // check that the base if valid - if (base < 2 || base > 16) - { - *result = 0; - return result; - } - - char* out = result; - int quotient = value; - - do - { - *out = "0123456789abcdef"[abs(quotient % base)]; - ++out; - - quotient /= base; - } while (quotient); - - // Only apply negative sign for base 10 - if( value < 0 && base == 10) - *out++ = '-'; - - std::reverse(result, out); - - *out = 0; - return result; -} -#endif - -typedef struct _mapcoord_setting_packet { - GtkSpinButton *spinner1, *spinner2, *spinner3, *spinner4; - Entity* worldspawn; -} mapcoord_setting_packet; - -static int map_minX, map_maxX, map_minY, map_maxY; -static int minX, maxX, minY, maxY; -mapcoord_setting_packet msp; - -// ************************** -// ** find entities by class ** from radiant/map.cpp -// ************************** -class EntityFindByClassname : public scene::Graph::Walker -{ - const char* m_name; - Entity*& m_entity; -public: - EntityFindByClassname(const char* name, Entity*& entity) : m_name(name), m_entity(entity) - { - m_entity = 0; - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(m_entity == 0) - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && string_equal(m_name, entity->getKeyValue("classname"))) - { - m_entity = entity; - } - } - return true; - } -}; - -Entity* Scene_FindEntityByClass(const char* name) -{ - Entity* entity; - GlobalSceneGraph().traverse(EntityFindByClassname(name, entity)); - return entity; -} - -// ************************** -// ** GTK callback functions ** -// ************************** - -static gboolean delete_event(GtkWidget *widget, GdkEvent *event, gpointer data) -{ - /* If you return FALSE in the "delete_event" signal handler, - * GTK will emit the "destroy" signal. Returning TRUE means - * you don't want the window to be destroyed. - * This is useful for popping up 'are you sure you want to quit?' - * type dialogs. */ - - return FALSE; -} - -// destroy widget if destroy signal is passed to widget -static void destroy(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(widget); -} - -// function for close button to destroy the toplevel widget -static void close_window(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(gtk_widget_get_toplevel(widget)); -} - -// callback function to assign the optimal mapcoords to the spinboxes -static void input_optimal(GtkWidget *widget, gpointer data) -{ - gtk_spin_button_set_value(msp.spinner1, minX); - gtk_spin_button_set_value(msp.spinner2, maxY); - gtk_spin_button_set_value(msp.spinner3, maxX); - gtk_spin_button_set_value(msp.spinner4, minY); -} - -// Spinner return value function -gint grab_int_value(GtkSpinButton *a_spinner, gpointer user_data) { - return gtk_spin_button_get_value_as_int(a_spinner); -} - -// write the values of the Spinner-Boxes to the worldspawn -static void set_coordinates(GtkWidget *widget, gpointer data) -{ - //Str str_min, str_max; - char buffer[10], str_min[20], str_max[20]; - - itoa(gtk_spin_button_get_value_as_int(msp.spinner1), str_min, 10); - itoa(gtk_spin_button_get_value_as_int(msp.spinner2), buffer, 10); - strcat(str_min, " "); - strcat(str_min, buffer); - msp.worldspawn->setKeyValue("mapcoordsmins", str_min); - - itoa(gtk_spin_button_get_value_as_int(msp.spinner3), str_max, 10); - itoa(gtk_spin_button_get_value_as_int(msp.spinner4), buffer, 10); - strcat(str_max, " "); - strcat(str_max, buffer); - UndoableCommand undo("SunPlug.entitySetMapcoords"); - msp.worldspawn->setKeyValue("mapcoordsmaxs", str_max); - - close_window(widget, NULL); -} - -class SunPlugPluginDependencies : - public GlobalRadiantModuleRef, // basic class for all other module refs - public GlobalUndoModuleRef, // used to say radiant that something has changed and to undo that - public GlobalSceneGraphModuleRef, // necessary to handle data in the mapfile (change, retrieve data) - public GlobalEntityModuleRef // to access and modify the entities -{ -public: - SunPlugPluginDependencies() : - GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities"))//, - { - } -}; - -// ************************* -// ** standard plugin stuff ** -// ************************* -namespace SunPlug -{ - GtkWindow* main_window; - char MenuList[100] = ""; - - const char* init(void* hApp, void* pMainWidget) - { - main_window = GTK_WINDOW(pMainWidget); - return "Initializing SunPlug for GTKRadiant"; - } - const char* getName() - { - return "SunPlug"; // name that is shown in the menue - } - const char* getCommandList() - { - const char about[] = "About..."; - const char etMapCoordinator[] = ";ET-MapCoordinator"; - - strcat(MenuList, about); - if (strncmp(GlobalRadiant().getGameName(), "etmain", 6) == 0) strcat(MenuList, etMapCoordinator); - return (const char*)MenuList; - } - const char* getCommandTitleList() - { - return ""; - } - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) // message processing - { - if(string_equal(command, "About...")) - { - about_plugin_window(); - } - if(string_equal(command, "ET-MapCoordinator")) - { - MapCoordinator(); - } - } -} // namespace - -class SunPlugModule : public TypeSystemRef -{ - _QERPluginTable m_plugin; -public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "SunPlug"); - - SunPlugModule() - { - m_plugin.m_pfnQERPlug_Init = &SunPlug::init; - m_plugin.m_pfnQERPlug_GetName = &SunPlug::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &SunPlug::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &SunPlug::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &SunPlug::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } -}; - -typedef SingletonModule SingletonSunPlugModule; - -SingletonSunPlugModule g_SunPlugModule; - - -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - - g_SunPlugModule.selfRegister(); -} - -// ************ -// ** my stuff ** -// ************ - -// About dialog -void about_plugin_window() -{ - GtkWidget *window, *vbox, *label, *button; - - window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // create a window - gtk_window_set_transient_for(GTK_WINDOW(window), SunPlug::main_window); // make the window to stay in front of the main window - g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL); // connect the delete event - g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL); // connect the destroy event for the window - gtk_window_set_title(GTK_WINDOW(window), "About SunPlug"); // set the title of the window for the window - gtk_window_set_resizable(GTK_WINDOW(window), FALSE); // don't let the user resize the window - gtk_window_set_modal(GTK_WINDOW(window), TRUE); // force the user not to do something with the other windows - gtk_container_set_border_width(GTK_CONTAINER(window), 10); // set the border of the window - - vbox = gtk_vbox_new(FALSE, 10); // create a box to arrange new objects vertically - gtk_container_add(GTK_CONTAINER(window), vbox); // add the box to the window - - label = gtk_label_new("SunPlug v1.0 for NetRadiant 1.5\nby Topsun"); // create a label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // text align left - gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 2); // insert the label in the box - - button = gtk_button_new_with_label("OK"); // create a button with text - g_signal_connect_swapped(G_OBJECT(button), "clicked", G_CALLBACK (gtk_widget_destroy), window); // connect the click event to close the window - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 2); // insert the button in the box - - gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); // center the window on screen - - gtk_widget_show_all(window); // show the window and all subelements -} - -// get the current bounding box and return the optimal coordinates -void GetOptimalCoordinates(AABB *levelBoundingBox) -{ - int half_width, half_heigth, center_x, center_y; - - half_width = levelBoundingBox->extents.x(); - half_heigth = levelBoundingBox->extents.y(); - center_x = levelBoundingBox->origin.x(); - center_y = levelBoundingBox->origin.y(); - - if (half_width > 175 || half_heigth > 175) // the square must be at least 350x350 units - { - // the wider side is the indicator for the square - if (half_width >= half_heigth) - { - minX = center_x - half_width; - maxX = center_x + half_width; - minY = center_y - half_width; - maxY = center_y + half_width; - } else { - minX = center_x - half_heigth; - maxX = center_x + half_heigth; - minY = center_y - half_heigth; - maxY = center_y + half_heigth; - } - } else { - minX = center_x - 175; - maxX = center_x + 175; - minY = center_y - 175; - maxY = center_y + 175; - } -} - -// MapCoordinator dialog window -void MapCoordinator() -{ - GtkWidget *window, *vbox, *table, *label, *spinnerMinX, *spinnerMinY, *spinnerMaxX, *spinnerMaxY, *button; - GtkAdjustment *spinner_adj_MinX, *spinner_adj_MinY, *spinner_adj_MaxX, *spinner_adj_MaxY; - Entity *theWorldspawn = NULL; - const char *buffer; - char line[20]; - - // in any case we need a window to show the user what to do - window = gtk_window_new(GTK_WINDOW_TOPLEVEL); // create the window - gtk_window_set_transient_for(GTK_WINDOW(window), SunPlug::main_window); // make the window to stay in front of the main window - g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL); // connect the delete event for the window - g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL); // connect the destroy event for the window - gtk_window_set_title(GTK_WINDOW(window), "ET-MapCoordinator"); // set the title of the window for the window - gtk_window_set_resizable(GTK_WINDOW(window), FALSE); // don't let the user resize the window - gtk_window_set_modal(GTK_WINDOW(window), TRUE); // force the user not to do something with the other windows - gtk_container_set_border_width(GTK_CONTAINER(window), 10); // set the border of the window - - vbox = gtk_vbox_new(FALSE, 10); // create a box to arrange new objects vertically - gtk_container_add(GTK_CONTAINER(window), vbox); // add the box to the window - - scene::Path path = makeReference(GlobalSceneGraph().root()); // get the path to the root element of the graph - scene::Instance* instance = GlobalSceneGraph().find(path); // find the instance to the given path - AABB levelBoundingBox = instance->worldAABB(); // get the bounding box of the level - - theWorldspawn = Scene_FindEntityByClass("worldspawn"); // find the entity worldspawn - if (theWorldspawn != 0) { // need to have a worldspawn otherwise setting a value crashes the radiant - // next two if's: get the current values of the mapcoords - buffer = theWorldspawn->getKeyValue("mapcoordsmins"); // upper left corner - if (strlen(buffer) > 0) { - strncpy(line, buffer, 19); - map_minX = atoi(strtok(line, " ")); // minimum of x value - map_minY = atoi(strtok(NULL, " ")); // maximum of y value - } else { - map_minX = 0; - map_minY = 0; - } - buffer = theWorldspawn->getKeyValue("mapcoordsmaxs"); // lower right corner - if (strlen(buffer) > 0) { - strncpy(line, buffer, 19); - map_maxX = atoi(strtok(line, " ")); // maximum of x value - map_maxY = atoi(strtok(NULL, " ")); // minimum of y value - } else { - map_maxX = 0; - map_maxY = 0; - } - - globalOutputStream() << "SunPlug: calculating optimal coordinates\n"; // write to console that we are calculating the coordinates - GetOptimalCoordinates(&levelBoundingBox); // calculate optimal mapcoords with the dimensions of the level bounding box - globalOutputStream() << "SunPlug: adviced mapcoordsmins=" << minX << " " << maxY << "\n"; // console info about mapcoordsmins - globalOutputStream() << "SunPlug: adviced mapcoordsmaxs=" << maxX << " " << minY << "\n"; // console info about mapcoordsmaxs - - spinner_adj_MinX = (GtkAdjustment *)gtk_adjustment_new(map_minX, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of minimum x value - spinner_adj_MinY = (GtkAdjustment *)gtk_adjustment_new(map_minY, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of minimum y value - spinner_adj_MaxX = (GtkAdjustment *)gtk_adjustment_new(map_maxX, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of maximum x value - spinner_adj_MaxY = (GtkAdjustment *)gtk_adjustment_new(map_maxY, -65536.0, 65536.0, 1.0, 5.0, 0); // create adjustment for value and range of maximum y value - - button = gtk_button_new_with_label("Get optimal mapcoords"); // create button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(input_optimal), NULL); // connect button with callback function - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 2); // insert button into vbox - - gtk_box_pack_start(GTK_BOX(vbox), gtk_hseparator_new(), FALSE, FALSE, 2); // insert separator into vbox - - table = gtk_table_new(4, 3, TRUE); // create table - gtk_table_set_row_spacings(GTK_TABLE(table), 8); // set row spacings - gtk_table_set_col_spacings(GTK_TABLE(table), 8); // set column spacings - gtk_box_pack_start(GTK_BOX(vbox), table, FALSE, FALSE, 2); // insert table into vbox - - label = gtk_label_new("x"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 1, 2, 0, 1); // insert label into table - - label = gtk_label_new("y"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 2, 3, 0, 1); // insert label into table - - label = gtk_label_new("mapcoordsmins"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 1, 1, 2); // insert label into table - - spinnerMinX = gtk_spin_button_new(spinner_adj_MinX, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMinX, 1, 2, 1, 2); // insert spinbox into table - - spinnerMinY = gtk_spin_button_new(spinner_adj_MinY, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMinY, 2, 3, 1, 2); // insert spinbox into table - - label = gtk_label_new("mapcoordsmaxs"); // create label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // align text to the left side - gtk_table_attach_defaults(GTK_TABLE(table), label, 0, 1, 2, 3); // insert label into table - - spinnerMaxX = gtk_spin_button_new(spinner_adj_MaxX, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMaxX, 1, 2, 2, 3); // insert spinbox into table - - spinnerMaxY = gtk_spin_button_new(spinner_adj_MaxY, 1.0, 0); // create textbox wiht value spin, value and value range - gtk_table_attach_defaults(GTK_TABLE(table), spinnerMaxY, 2, 3, 2, 3); // insert spinbox into table - - // put the references to the spinboxes and the worldspawn into the global exchange - msp.spinner1 = GTK_SPIN_BUTTON(spinnerMinX); - msp.spinner2 = GTK_SPIN_BUTTON(spinnerMinY); - msp.spinner3 = GTK_SPIN_BUTTON(spinnerMaxX); - msp.spinner4 = GTK_SPIN_BUTTON(spinnerMaxY); - msp.worldspawn = theWorldspawn; - - button = gtk_button_new_with_label("Set"); // create button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(set_coordinates), NULL); // connect button with callback function - gtk_table_attach_defaults(GTK_TABLE(table), button, 1, 2, 3, 4); // insert button into table - - button = gtk_button_new_with_label("Cancel"); // create button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(close_window), NULL); // connect button with callback function - gtk_table_attach_defaults(GTK_TABLE(table), button, 2, 3, 3, 4); // insert button into table - } else { - globalOutputStream() << "SunPlug: no worldspawn found!\n"; // output error to console - - label = gtk_label_new("ERROR: No worldspawn was found in the map!\nIn order to use this tool the map must have at least one brush in the worldspawn. "); // create a label - gtk_label_set_justify(GTK_LABEL(label), GTK_JUSTIFY_LEFT); // text align left - gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 2); // insert the label in the box - - button = gtk_button_new_with_label("OK"); // create a button with text - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(close_window), NULL); // connect the click event to close the window - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 2); // insert the button in the box - } - - gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); // center the window - gtk_widget_show_all(window); // show the window and all subelements -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.def b/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.def deleted file mode 100644 index 1f1dfb12..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.def +++ /dev/null @@ -1,7 +0,0 @@ -; sunplug.def : Declares the module parameters for the DLL. - -LIBRARY "SUNPLUG" - -EXPORTS - ; Explicit exports can go here - Radiant_RegisterModules @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.h b/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.h deleted file mode 100644 index fafdc897..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/sunplug/sunplug.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Sunplug plugin for GtkRadiant -Copyright (C) 2004 Topsun -Thanks to SPoG for help! - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ - -#ifndef _PLUGIN_SUNPLUG_ - #define _PLUGIN_SUNPLUG_ - - -#endif // _PLUGIN_SUNPLUG_ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_actorclip.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_actorclip.bmp deleted file mode 100644 index 43bdf933..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_actorclip.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level1.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level1.bmp deleted file mode 100644 index 80a4b299..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level1.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level2.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level2.bmp deleted file mode 100644 index e84e2544..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level2.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level3.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level3.bmp deleted file mode 100644 index 141c3245..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level3.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level4.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level4.bmp deleted file mode 100644 index 3783a803..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level4.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level5.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level5.bmp deleted file mode 100644 index 8f62851c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level5.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level6.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level6.bmp deleted file mode 100644 index 418fdd28..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level6.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level7.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level7.bmp deleted file mode 100644 index d82dab61..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level7.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level8.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level8.bmp deleted file mode 100644 index c3809538..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_level8.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_nodraw.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_nodraw.bmp deleted file mode 100644 index b9948562..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_nodraw.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_stepon.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_stepon.bmp deleted file mode 100644 index 828449ef..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_stepon.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_weaponclip.bmp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_weaponclip.bmp deleted file mode 100644 index fe6b3485..00000000 Binary files a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/bitmaps/ufoai_weaponclip.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.cpp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.cpp deleted file mode 100644 index e371e833..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/* -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 "ufoai.h" -#include "ufoai_level.h" -#include "ufoai_gtk.h" -#include "ufoai_filters.h" - -#include "debugging/debugging.h" - -#include "iplugin.h" - -#include "version.h" - -#include "string/string.h" -#include "modulesystem/singletonmodule.h" - -#include - -#define PLUGIN_VERSION "0.4" - -#include "ifilter.h" -#include "ibrush.h" -#include "iundo.h" // declaration of undo system -#include "ientity.h" // declaration of entity system -#include "iscenegraph.h" // declaration of datastructure of the map -#include "scenelib.h" // declaration of datastructure of the map -#include "qerplugin.h" // declaration to use other interfaces as a plugin -#include "ieclass.h" - -class UFOAIPluginDependencies : - public GlobalRadiantModuleRef, // basic class for all other module refs - public GlobalUndoModuleRef, // used to say radiant that something has changed and to undo that - public GlobalSceneGraphModuleRef, // necessary to handle data in the mapfile (change, retrieve data) - public GlobalEntityModuleRef, // to access and modify the entities - public GlobalEntityClassManagerModuleRef -{ -public: - UFOAIPluginDependencies(void) : - GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities")), - GlobalEntityClassManagerModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclass")) - { - } -}; - -namespace UFOAI -{ - GtkWindow* g_mainwnd; - - const char* init(void* hApp, void* pMainWidget) - { - g_mainwnd = GTK_WINDOW(pMainWidget); - return "Initializing GTKRadiant UFOAI plugin"; - } - const char* getName() - { - return "UFO:AI"; - } - const char* getCommandList() - { - /*GlobalRadiant().getGameName()*/ - return "About;-;Worldspawn reset;Worldspawn;Perform check;-;Level 1;Level 2;Level 3;Level 4;Level 5;Level 6;Level 7;Level 8;-;StepOn;ActorClip;WeaponClip;Nodraw"; - } - const char* getCommandTitleList() - { - return ""; - } - void dispatch(const char* command, float* vMin, float* vMax, bool bSingleBrush) - { - char *message = NULL; - if(string_equal(command, "About")) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_mainwnd), - "UFO:AI Plugin (http://ufoai.sf.net)\nBuild: " __DATE__ "\nRadiant version: " RADIANT_VERSION "\nPlugin version: " PLUGIN_VERSION "\nAuthor: Martin Gerhardy (tlh2000/mattn)\n", "About", - eMB_OK, eMB_ICONDEFAULT); - } - else if(string_equal(command, "Level 1")) - { - filter_level(CONTENTS_LEVEL1); - } - else if(string_equal(command, "Level 2")) - { - filter_level(CONTENTS_LEVEL2); - } - else if(string_equal(command, "Level 3")) - { - filter_level(CONTENTS_LEVEL3); - } - else if(string_equal(command, "Worldspawn")) - { - assign_default_values_to_worldspawn(false, &message); - } - else if(string_equal(command, "Worldspawn reset")) - { - assign_default_values_to_worldspawn(true, &message); - } - else if(string_equal(command, "Perform check")) - { - check_map_values(&message); - } - else if(string_equal(command, "Level 4")) - { - filter_level(CONTENTS_LEVEL4); - } - else if(string_equal(command, "Level 5")) - { - filter_level(CONTENTS_LEVEL5); - } - else if(string_equal(command, "Level 6")) - { - filter_level(CONTENTS_LEVEL6); - } - else if(string_equal(command, "Level 7")) - { - filter_level(CONTENTS_LEVEL7); - } - else if(string_equal(command, "Level 8")) - { - filter_level(CONTENTS_LEVEL8); - } - else if(string_equal(command, "StepOn")) - { - filter_stepon(); - } - else if(string_equal(command, "ActorClip")) - { - filter_actorclip(); - } - else if(string_equal(command, "WeaponClip")) - { - filter_weaponclip(); - } - else if(string_equal(command, "NoDraw")) - { - filter_nodraw(); - } - - if (message != NULL) - { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(g_mainwnd), - message, "Note", - eMB_OK, eMB_ICONDEFAULT); - } - SceneChangeNotify(); - } -} // namespace - - -class UFOAIModule : public TypeSystemRef -{ - _QERPluginTable m_plugin; -public: - typedef _QERPluginTable Type; - STRING_CONSTANT(Name, "UFO:AI"); - - UFOAIModule() - { - m_plugin.m_pfnQERPlug_Init = &UFOAI::init; - m_plugin.m_pfnQERPlug_GetName = &UFOAI::getName; - m_plugin.m_pfnQERPlug_GetCommandList = &UFOAI::getCommandList; - m_plugin.m_pfnQERPlug_GetCommandTitleList = &UFOAI::getCommandTitleList; - m_plugin.m_pfnQERPlug_Dispatch = &UFOAI::dispatch; - } - _QERPluginTable* getTable() - { - return &m_plugin; - } -}; - -typedef SingletonModule SingletonUFOAIModule; - -SingletonUFOAIModule g_UFOAIModule; - - -class UFOAIToolbarDependencies : public ModuleRef<_QERPluginTable> -{ -public: - UFOAIToolbarDependencies() : ModuleRef<_QERPluginTable>("UFO:AI") - { - } -}; - -class UFOAIToolbarModule : public TypeSystemRef -{ - _QERPlugToolbarTable m_table; -public: - typedef _QERPlugToolbarTable Type; - STRING_CONSTANT(Name, "UFO:AI"); - - UFOAIToolbarModule() - { - if (!strcmp(GlobalRadiant().getGameDescriptionKeyValue("name"), "UFO:Alien Invasion")) { - m_table.m_pfnToolbarButtonCount = ToolbarButtonCount; - m_table.m_pfnGetToolbarButton = GetToolbarButton; - } - else - { - m_table.m_pfnToolbarButtonCount = ToolbarNoButtons; - m_table.m_pfnGetToolbarButton = GetToolbarNoButton; - } - } - _QERPlugToolbarTable* getTable() - { - return &m_table; - } -}; - -typedef SingletonModule SingletonUFOAIToolbarModule; - -SingletonUFOAIToolbarModule g_UFOAIToolbarModule; - - -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - - g_UFOAIModule.selfRegister(); - g_UFOAIToolbarModule.selfRegister(); -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.def b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.def deleted file mode 100644 index 03e07507..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.def +++ /dev/null @@ -1,7 +0,0 @@ -; sample.def : Declares the module parameters for the DLL. - -LIBRARY "UFOAI" - -EXPORTS - ; Explicit exports can go here - Radiant_RegisterModules @1 diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.h b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.h deleted file mode 100644 index 7193fa0c..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai.h +++ /dev/null @@ -1,22 +0,0 @@ -/* -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(INCLUDED_UFOAI_H) -#define INCLUDED_UFOAI_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_filters.cpp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_filters.cpp deleted file mode 100644 index 869c4eb8..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_filters.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/* -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 "ufoai_filters.h" - -#include "ibrush.h" -#include "ientity.h" -#include "iscenegraph.h" - -// believe me, i'm sorry -#include "../../radiant/brush.h" - -#include "generic/callback.h" - -#include - -bool actorclip_active = false; -bool stepon_active = false; -bool nodraw_active = false; -bool weaponclip_active = false; -int level_active = 0; - -// TODO: This should be added to ibrush.h -// like already done for Node_getEntity in ientity.h -// FIXME: Doesn't belong here -inline Brush* Node_getBrush(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -void hide_node(scene::Node& node, bool hide) -{ - hide - ? node.enable(scene::Node::eHidden) - : node.disable(scene::Node::eHidden); -} - -typedef std::list entitylist_t; - -class EntityFindByName : public scene::Graph::Walker -{ - const char* m_name; - entitylist_t& m_entitylist; - /* this starts at 1 << level */ - int m_flag; - int m_hide; -public: - EntityFindByName(const char* name, entitylist_t& entitylist, int flag, bool hide) - : m_name(name), m_entitylist(entitylist), m_flag(flag), m_hide(hide) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - int spawnflagsInt; - Entity* entity = Node_getEntity(path.top()); - if (entity != 0) - { - if (string_equal(m_name, entity->getKeyValue("classname"))) - { - const char *spawnflags = entity->getKeyValue("spawnflags"); - globalOutputStream() << "spawnflags for " << m_name << ": " << spawnflags << ".\n"; - - if (!string_empty(spawnflags)) { - spawnflagsInt = atoi(spawnflags); - if (!(spawnflagsInt & m_flag)) - { - hide_node(path.top(), m_hide); // hide/unhide - m_entitylist.push_back(entity); - } - } - else - { - globalOutputStream() << "UFO:AI: Warning: no spawnflags for " << m_name << ".\n"; - } - } - } - return true; - } -}; - -class ForEachFace : public BrushVisitor -{ - Brush &m_brush; -public: - mutable int m_contentFlagsVis; - mutable int m_surfaceFlagsVis; - - ForEachFace(Brush& brush) - : m_brush(brush) - { - m_contentFlagsVis = -1; - m_surfaceFlagsVis = -1; - } - - void visit(Face& face) const - { -#if _DEBUG - if (m_surfaceFlagsVis < 0) - m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; - else if (m_surfaceFlagsVis >= 0 && m_surfaceFlagsVis != face.getShader().m_flags.m_surfaceFlags) - globalOutputStream() << "Faces with different surfaceflags at brush\n"; - if (m_contentFlagsVis < 0) - m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; - else if (m_contentFlagsVis >= 0 && m_contentFlagsVis != face.getShader().m_flags.m_contentFlags) - globalOutputStream() << "Faces with different contentflags at brush\n"; -#else - m_surfaceFlagsVis = face.getShader().m_flags.m_surfaceFlags; - m_contentFlagsVis = face.getShader().m_flags.m_contentFlags; -#endif - } -}; - -typedef std::list brushlist_t; - -class BrushGetLevel : public scene::Graph::Walker -{ - brushlist_t& m_brushlist; - int m_flag; - bool m_content; // if true - use m_contentFlags - otherwise m_surfaceFlags - mutable bool m_notset; - mutable bool m_hide; -public: - BrushGetLevel(brushlist_t& brushlist, int flag, bool content, bool notset, bool hide) - : m_brushlist(brushlist), m_flag(flag), m_content(content), m_notset(notset), m_hide(hide) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Brush* brush = Node_getBrush(path.top()); - if (brush != 0) - { - ForEachFace faces(*brush); - brush->forEachFace(faces); - // contentflags? - if (m_content) - { - // are any flags set? - if (faces.m_contentFlagsVis > 0) - { - // flag should not be set - if (m_notset && (!(faces.m_contentFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } - // check whether flag is set - else if (!m_notset && ((faces.m_contentFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } - } - } - // surfaceflags? - else - { - // are any flags set? - if (faces.m_surfaceFlagsVis > 0) - { - // flag should not be set - if (m_notset && (!(faces.m_surfaceFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } - // check whether flag is set - else if (!m_notset && ((faces.m_surfaceFlagsVis & m_flag))) - { - hide_node(path.top(), m_hide); - m_brushlist.push_back(brush); - } - } - } - - } - return true; - } -}; - -/** - * @brief Activates the level filter for the given level - * @param[in] level Which level to show? - * @todo Entities - */ -void filter_level(int flag) -{ - int level; - brushlist_t brushes; - entitylist_t entities; - - level = (flag >> 8); - - if (level_active) - { - GlobalSceneGraph().traverse(BrushGetLevel(brushes, (level_active << 8), true, true, false)); - GlobalSceneGraph().traverse(EntityFindByName("func_door", entities, level_active, false)); - GlobalSceneGraph().traverse(EntityFindByName("func_breakable", entities, level_active, false)); - GlobalSceneGraph().traverse(EntityFindByName("misc_model", entities, level_active, false)); - GlobalSceneGraph().traverse(EntityFindByName("misc_particle", entities, level_active, false)); - entities.erase(entities.begin(), entities.end()); - brushes.erase(brushes.begin(), brushes.end()); - if (level_active == level) - { - level_active = 0; - // just disabĺe level filter - return; - } - } - level_active = level; - globalOutputStream() << "UFO:AI: level_active: " << level_active << ", flag: " << flag << ".\n"; - - // first all brushes - GlobalSceneGraph().traverse(BrushGetLevel(brushes, flag, true, true, true)); - - // now all entities - GlobalSceneGraph().traverse(EntityFindByName("func_door", entities, level, true)); - GlobalSceneGraph().traverse(EntityFindByName("func_breakable", entities, level, true)); - GlobalSceneGraph().traverse(EntityFindByName("misc_model", entities, level, true)); - GlobalSceneGraph().traverse(EntityFindByName("misc_particle", entities, level, true)); - -#ifdef _DEBUG - if (brushes.empty()) - { - globalOutputStream() << "UFO:AI: No brushes.\n"; - } - else - { - globalOutputStream() << "UFO:AI: Found " << Unsigned(brushes.size()) << " brushes.\n"; - } - - // now let's filter all entities like misc_model, func_breakable and func_door that have the spawnflags set - if (entities.empty()) - { - globalOutputStream() << "UFO:AI: No entities.\n"; - } - else - { - globalOutputStream() << "UFO:AI: Found " << Unsigned(entities.size()) << " entities.\n"; - } -#endif -} - -void filter_stepon (void) -{ - if (stepon_active) { - stepon_active = false; - } else { - stepon_active = true; - } - brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_STEPON, true, false, stepon_active)); - - if (brushes.empty()) - { - globalOutputStream() << "UFO:AI: No brushes.\n"; - } - else - { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " stepon brushes.\n"; - } -} - -void filter_nodraw (void) -{ - if (nodraw_active) { - nodraw_active = false; - } else { - nodraw_active = true; - } - brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, SURF_NODRAW, false, false, nodraw_active)); - -#ifdef _DEBUG - if (brushes.empty()) - { - globalOutputStream() << "UFO:AI: No brushes.\n"; - } - else - { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " nodraw brushes.\n"; - } -#endif -} - -void filter_actorclip (void) -{ - if (actorclip_active) { - actorclip_active = false; - } else { - actorclip_active = true; - } - brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_ACTORCLIP, true, false, actorclip_active)); - -#ifdef _DEBUG - if (brushes.empty()) - { - globalOutputStream() << "UFO:AI: No brushes.\n"; - } - else - { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " actorclip brushes.\n"; - } -#endif -} - -void filter_weaponclip (void) -{ - if (weaponclip_active) { - weaponclip_active = false; - } else { - weaponclip_active = true; - } - brushlist_t brushes; - GlobalSceneGraph().traverse(BrushGetLevel(brushes, CONTENTS_WEAPONCLIP, true, false, weaponclip_active)); - -#ifdef _DEBUG - if (brushes.empty()) - { - globalOutputStream() << "UFO:AI: No brushes.\n"; - } - else - { - globalOutputStream() << "UFO:AI: Hiding " << Unsigned(brushes.size()) << " weaponclip brushes.\n"; - } -#endif -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_filters.h b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_filters.h deleted file mode 100644 index 7d581140..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_filters.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -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(INCLUDED_FILTERS_H) -#define INCLUDED_FILTERS_H - -void filter_level(int flag); -void filter_stepon(void); -void filter_actorclip(void); -void filter_weaponclip(void); -void filter_nodraw(void); - -#define SURF_NODRAW 0x80 - -#define CONTENTS_LEVEL8 0x8000 -#define CONTENTS_LEVEL7 0x4000 -#define CONTENTS_LEVEL6 0x2000 -#define CONTENTS_LEVEL5 0x1000 -#define CONTENTS_LEVEL4 0x0800 -#define CONTENTS_LEVEL3 0x0400 -#define CONTENTS_LEVEL2 0x0200 -#define CONTENTS_LEVEL1 0x0100 -#define CONTENTS_ACTORCLIP 0x10000 -#define CONTENTS_WEAPONCLIP 0x2000000 -#define CONTENTS_STEPON 0x40000000 - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_gtk.cpp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_gtk.cpp deleted file mode 100644 index afadc7ad..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_gtk.cpp +++ /dev/null @@ -1,207 +0,0 @@ -/* -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 "ufoai_gtk.h" -#include "ufoai_filters.h" - -#include "itoolbar.h" -#include "iscenegraph.h" - -#include - -/** - * GTK callback functions - */ - -class UFOAIGtk -{ - GtkWindow* m_gtk_window; -public: - UFOAIGtk(void* gtk_window) : m_gtk_window((GtkWindow*)gtk_window) - { - } -}; - -/** - * @brief If you return FALSE in the "delete_event" signal handler, - * GTK will emit the "destroy" signal. Returning TRUE means - * you don't want the window to be destroyed. - * This is useful for popping up 'are you sure you want to quit?' - * type dialogs. - */ -static gboolean delete_event(GtkWidget *widget, GdkEvent *event, gpointer data) -{ - return FALSE; -} - -/** - * @brief destroy widget if destroy signal is passed to widget - */ -static void destroy(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(widget); -} - -/** - * @brief function for close button to destroy the toplevel widget - */ -static void close_window(GtkWidget *widget, gpointer data) -{ - gtk_widget_destroy(gtk_widget_get_toplevel(widget)); -} - -/* =============================== */ - -#define NUM_TOOLBARBUTTONS 12 - -/** - * @brief - */ -std::size_t ToolbarButtonCount(void) -{ - return NUM_TOOLBARBUTTONS; -} - -/** - * @brief Used if the ufo plugin should not be visible (at least the toolbar stuff) - */ -std::size_t ToolbarNoButtons (void) -{ - return 0; -} - -/** - * @brief - */ -class CUFOAIToolbarButton : public IToolbarButton -{ -public: - virtual const char* getImage() const - { - switch( mIndex ) - { - case 0: return "ufoai_level1.bmp"; - case 1: return "ufoai_level2.bmp"; - case 2: return "ufoai_level3.bmp"; - case 3: return "ufoai_level4.bmp"; - case 4: return "ufoai_level5.bmp"; - case 5: return "ufoai_level6.bmp"; - case 6: return "ufoai_level7.bmp"; - case 7: return "ufoai_level8.bmp"; - case 8: return "ufoai_stepon.bmp"; - case 9: return "ufoai_actorclip.bmp"; - case 10: return "ufoai_weaponclip.bmp"; - case 11: return "ufoai_nodraw.bmp"; - } - return NULL; - } - virtual EType getType() const - { - switch( mIndex ) - { -/* case 3: return eButton;*/ - case 8: return eToggleButton; - case 9: return eToggleButton; - case 10: return eToggleButton; - case 11: return eToggleButton; - default: return eButton; - } - } - virtual const char* getText() const - { - switch( mIndex ) - { - case 0: return "Level 1"; - case 1: return "Level 2"; - case 2: return "Level 3"; - case 3: return "Level 4"; - case 4: return "Level 5"; - case 5: return "Level 6"; - case 6: return "Level 7"; - case 7: return "Level 8"; - case 8: return "Stepon"; - case 9: return "Actorclip"; - case 10: return "Weaponclip"; - case 11: return "Nodraw"; - } - return NULL; - } - virtual const char* getTooltip() const - { - switch( mIndex ) - { - case 0: return "Show only level 1"; - case 1: return "Show only level 2"; - case 2: return "Show only level 3"; - case 3: return "Show only level 4"; - case 4: return "Show only level 5"; - case 5: return "Show only level 6"; - case 6: return "Show only level 7"; - case 7: return "Show only level 8"; - case 8: return "Hide stepon brushes"; - case 9: return "Hide actorclip brushes"; - case 10: return "Hide weaponclip brushes"; - case 11: return "Hide nodraw brushes"; - } - return NULL; - } - - virtual void activate() const - { - switch( mIndex ) - { - case 0: filter_level(CONTENTS_LEVEL1); break; - case 1: filter_level(CONTENTS_LEVEL2); break; - case 2: filter_level(CONTENTS_LEVEL3); break; - case 3: filter_level(CONTENTS_LEVEL4); break; - case 4: filter_level(CONTENTS_LEVEL5); break; - case 5: filter_level(CONTENTS_LEVEL6); break; - case 6: filter_level(CONTENTS_LEVEL7); break; - case 7: filter_level(CONTENTS_LEVEL8); break; - case 8: filter_stepon(); break; - case 9: filter_actorclip(); break; - case 10: filter_weaponclip(); break; - case 11: filter_nodraw(); break; - } - SceneChangeNotify(); - } - - std::size_t mIndex; -}; - -/** - * @brief - */ -CUFOAIToolbarButton g_ufoaiToolbarButtons[NUM_TOOLBARBUTTONS]; - -/** - * @brief - */ -const IToolbarButton* GetToolbarButton(std::size_t index) -{ - g_ufoaiToolbarButtons[index].mIndex = index; - return &g_ufoaiToolbarButtons[index]; -} - -/** - * @brief - */ -const IToolbarButton* GetToolbarNoButton(std::size_t index) -{ - return NULL; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_gtk.h b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_gtk.h deleted file mode 100644 index ef2ae3c3..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_gtk.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -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(INCLUDED_UFOAI_GTK_H) -#define INCLUDED_UFOAI_GTK_H - -#include "itoolbar.h" -#include - -const IToolbarButton* GetToolbarButton(std::size_t index); -const IToolbarButton* GetToolbarNoButton(std::size_t index); -std::size_t ToolbarButtonCount(void); -std::size_t ToolbarNoButtons(void); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_level.cpp b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_level.cpp deleted file mode 100644 index 3a36b258..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_level.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/* -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 "ufoai_level.h" -#include "ufoai_filters.h" - -#include "ibrush.h" -#include "ientity.h" -#include "iscenegraph.h" - -#include "string/string.h" -#include - -class Level; - -/** - * @brief find entities by class - * @note from radiant/map.cpp - */ -class EntityFindByClassname : public scene::Graph::Walker -{ - const char* m_name; - Entity*& m_entity; -public: - EntityFindByClassname(const char* name, Entity*& entity) : m_name(name), m_entity(entity) - { - m_entity = 0; - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(m_entity == 0) - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 && string_equal(m_name, entity->getKeyValue("classname"))) - { - m_entity = entity; - } - } - return true; - } -}; - -/** - * @brief - */ -Entity* Scene_FindEntityByClass(const char* name) -{ - Entity* entity = NULL; - GlobalSceneGraph().traverse(EntityFindByClassname(name, entity)); - return entity; -} - -/** - * @brief finds start positions - */ -class EntityFindFlags : public scene::Graph::Walker -{ - const char *m_classname; - const char *m_flag; - int *m_count; - - public: - EntityFindFlags(const char *classname, const char *flag, int *count) : m_classname(classname), m_flag(flag), m_count(count) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - const char *str; - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 && string_equal(m_classname, entity->getKeyValue("classname"))) - { - str = entity->getKeyValue(m_flag); - if (string_empty(str)) - { - (*m_count)++; - } - } - return true; - } -}; - - -/** - * @brief finds start positions - */ -class EntityFindTeams : public scene::Graph::Walker -{ - const char *m_classname; - int *m_count; - int *m_team; - -public: - EntityFindTeams(const char *classname, int *count, int *team) : m_classname(classname), m_count(count), m_team(team) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - const char *str; - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 && string_equal(m_classname, entity->getKeyValue("classname"))) - { - if (m_count) - (*m_count)++; - // now get the highest teamnum - if (m_team) - { - str = entity->getKeyValue("team"); - if (!string_empty(str)) - { - if (atoi(str) > *m_team) - (*m_team) = atoi(str); - } - } - } - return true; - } -}; - -/** - * @brief - */ -void get_team_count (const char *classname, int *count, int *team) -{ - GlobalSceneGraph().traverse(EntityFindTeams(classname, count, team)); - globalOutputStream() << "UFO:AI: classname: " << classname << ": #" << (*count) << "\n"; -} - -/** - * @brief Some default values to worldspawn like maxlevel and so on - */ -void assign_default_values_to_worldspawn (bool override, char **returnMsg) -{ - static char message[1024]; - Entity* worldspawn; - int teams = 0; - int count = 0; - char str[64]; - - worldspawn = Scene_FindEntityByClass("worldspawn"); - if (!worldspawn) - { - globalOutputStream() << "UFO:AI: Could not find worldspawn.\n"; - *returnMsg = "Could not find worldspawn"; - return; - } - - *message = '\0'; - *str = '\0'; - - if (override || string_empty(worldspawn->getKeyValue("maxlevel"))) - { - // TODO: Get highest brush - a level has 64 units - worldspawn->setKeyValue("maxlevel", "5"); - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Set maxlevel to: %s", worldspawn->getKeyValue("maxlevel")); - } - - if (override || string_empty(worldspawn->getKeyValue("maxteams"))) - { - get_team_count("info_player_start", &count, &teams); - if (teams) - { - snprintf(str, sizeof(str) - 1, "%i", teams); - worldspawn->setKeyValue("maxteams", str); - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Set maxteams to: %s", worldspawn->getKeyValue("maxteams")); - } - if (count < 16) - { - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "You should at least place 16 info_player_start"); - } - } - - // no errors - no warnings - if (!strlen(message)) - return; - - *returnMsg = message; -} - -/** - * @brief - */ -int check_entity_flags (const char *classname, const char *flag) -{ - int count; - - /* init this with 0 every time we browse the tree */ - count = 0; - - GlobalSceneGraph().traverse(EntityFindFlags(classname, flag, &count)); - return count; -} - -/** - * @brief Will check e.g. the map entities for valid values - * @todo: check for maxlevel - */ -void check_map_values (char **returnMsg) -{ - static char message[1024]; - int count = 0; - int teams = 0; - int ent_flags; - Entity* worldspawn; - char str[64]; - - worldspawn = Scene_FindEntityByClass("worldspawn"); - if (!worldspawn) - { - globalOutputStream() << "UFO:AI: Could not find worldspawn.\n"; - *returnMsg = "Could not find worldspawn"; - return; - } - - *message = '\0'; - *str = '\0'; - - // multiplayer start positions - get_team_count("info_player_start", &count, &teams); - if (!count) - strncat(message, "No multiplayer start positions (info_player_start)\n", sizeof(message) - 1); - - // singleplayer map? - count = 0; - get_team_count("info_human_start", &count, NULL); - if (!count) - strncat(message, "No singleplayer start positions (info_human_start)\n", sizeof(message) - 1); - - // singleplayer map? - count = 0; - get_team_count("info_2x2_start", &count, NULL); - if (!count) - strncat(message, "No singleplayer start positions for 2x2 units (info_2x2_start)\n", sizeof(message) - 1); - - // search for civilians - count = 0; - get_team_count("info_civilian_start", &count, NULL); - if (!count) - strncat(message, "No civilian start positions (info_civilian_start)\n", sizeof(message) - 1); - - // check maxlevel - if (string_empty(worldspawn->getKeyValue("maxlevel"))) - strncat(message, "Worldspawn: No maxlevel defined\n", sizeof(message) - 1); - else if (atoi(worldspawn->getKeyValue("maxlevel")) > 8) - { - strncat(message, "Worldspawn: Highest maxlevel is 8\n", sizeof(message) - 1); - worldspawn->setKeyValue("maxlevel", "8"); - } - - ent_flags = check_entity_flags("func_door", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i func_door with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("func_breakable", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i func_breakable with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("misc_sound", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i misc_sound with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("misc_model", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i misc_model with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("misc_particle", "spawnflags"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i misc_particle with no spawnflags\n", ent_flags); - ent_flags = check_entity_flags("info_player_start", "team"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i info_player_start with no team assigned\n!!Teamcount may change after you've fixed this\n", ent_flags); - ent_flags = check_entity_flags("light", "color"); - ent_flags = check_entity_flags("light", "_color"); - if (ent_flags) - snprintf(&message[strlen(message)], sizeof(message) - 1 - strlen(message), "Found %i lights with no color value\n", ent_flags); - - // no errors found - if (!strlen(message)) { - snprintf(message, sizeof(message) - 1, "No errors found - you are ready to compile the map now\n"); - } - - *returnMsg = message; -} diff --git a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_level.h b/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_level.h deleted file mode 100644 index ba75bd45..00000000 --- a/misc/mediasource/extra/netradiant-src/contrib/ufoaiplug/ufoai_level.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -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(INCLUDED_UFOAI_LEVEL_H) -#define INCLUDED_UFOAI_LEVEL_H - -void assign_default_values_to_worldspawn (bool override, char **returnMsg); -void check_map_values (char **returnMsg); -void get_team_count (const char *classname, int *count, int *team); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/cross-Makefile.conf b/misc/mediasource/extra/netradiant-src/cross-Makefile.conf deleted file mode 100644 index 2b44320d..00000000 --- a/misc/mediasource/extra/netradiant-src/cross-Makefile.conf +++ /dev/null @@ -1,9 +0,0 @@ -# Usage: -# copy this file to Makefile.conf -# edit the paths in here - -# how to call the mingw tools -MINGW_EXEC_PREFIX = i586-mingw32msvc- - -# use mingw32 -include mingw-Makefile.inc diff --git a/misc/mediasource/extra/netradiant-src/docs/index.html b/misc/mediasource/extra/netradiant-src/docs/index.html deleted file mode 100644 index 68811708..00000000 --- a/misc/mediasource/extra/netradiant-src/docs/index.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - -

Xonotic Mapping Wiki

- - diff --git a/misc/mediasource/extra/netradiant-src/download-gamepacks.sh b/misc/mediasource/extra/netradiant-src/download-gamepacks.sh deleted file mode 100644 index 2d6c1b78..00000000 --- a/misc/mediasource/extra/netradiant-src/download-gamepacks.sh +++ /dev/null @@ -1,160 +0,0 @@ -#!/bin/sh - -# Usage: -# sh download-gamepack.sh -# LICENSEFILTER=GPL BATCH=1 sh download-gamepack.sh - -: ${GIT:=git} -: ${SVN:=svn} -: ${WGET:=wget} -: ${ECHO:=echo} -: ${MKDIR:=mkdir} -: ${RM_R:=rm -f -r} -: ${MV:=mv} -: ${UNZIPPER:=unzip} - -set -e - -extra_urls() -{ - if [ -f "$1/extra-urls.txt" ]; then - while IFS=" " read -r FILE URL; do - $WGET -O "$1/$FILE" "$URL" - done < "$1/extra-urls.txt" - fi -} - -pack() -{ - pack=$1; shift - license=$1; shift - sourcetype=$1; shift - source=$1; shift - - if [ -d "games/$pack" ]; then - $ECHO "Updating $pack..." - case "$sourcetype" in - svn) - $SVN update "games/$pack" "$@" || true - ;; - zip1) - $RM_R zipdownload - $MKDIR zipdownload - cd zipdownload - $WGET "$source" "$@" || true - $UNZIPPER *.zip || true - cd .. - $RM_R "games/$pack" - $MKDIR "games/$pack" - $MV zipdownload/*/* "games/$pack/" || true - $RM_R zipdownload - ;; - gitdir) - $RM_R "games/$pack" - cd games - $GIT archive --remote="$source" --prefix="$pack/" "$2":"$1" | tar xvf - || true - cd .. - ;; - git) - cd "games/$pack" - $GIT pull || true - cd ../.. - ;; - esac - extra_urls "games/$pack" - return - fi - - $ECHO - $ECHO "Available pack: $pack" - $ECHO " License: $license" - $ECHO " Download via $sourcetype from $source" - $ECHO - case " $PACKFILTER " in - " ") - ;; - *" $pack "*) - ;; - *) - $ECHO "Pack $pack rejected because it is not in PACKFILTER." - return - ;; - esac - case " $LICENSEFILTER " in - " ") - ;; - *" $license "*) - ;; - *) - $ECHO "Pack $pack rejected because its license is not in LICENSEFILTER." - return - ;; - esac - case "$BATCH" in - '') - while :; do - $ECHO "Download this pack? (y/n)" - read -r P - case "$P" in - y*) - break - ;; - n*) - return - ;; - esac - done - ;; - *) - ;; - esac - - $ECHO "Downloading $pack..." - case "$sourcetype" in - svn) - $SVN checkout "$source" "games/$pack" "$@" || true - ;; - zip1) - $RM_R zipdownload - $MKDIR zipdownload - cd zipdownload - $WGET "$source" "$@" || true - $UNZIPPER *.zip || true - cd .. - $MKDIR "games/$pack" - $MV zipdownload/*/* "games/$pack/" || true - $RM_R zipdownload - ;; - gitdir) - cd games - $GIT archive --remote="$source" --prefix="$pack/" "$2":"$1" | tar xvf - || true - cd .. - ;; - git) - cd games - $GIT clone "$source" "$pack" || true - cd .. - ;; - esac - extra_urls "games/$pack" - good=false - for D in "games/$pack"/*.game; do - if [ -d "$D" ]; then - good=true - fi - done - $good || rm -rf "$D" -} - -mkdir -p games -pack DarkPlacesPack GPL svn https://zerowing.idsoftware.com/svn/radiant.gamepacks/DarkPlacesPack/branches/1.5/ -pack NexuizPack GPL gitdir git://git.icculus.org/divverent/nexuiz.git misc/netradiant-NexuizPack master -pack OpenArenaPack unknown zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/OpenArenaPack.zip -pack Q3Pack proprietary svn https://zerowing.idsoftware.com/svn/radiant.gamepacks/Q3Pack/trunk/ -r29 -pack Quake2Pack proprietary zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/Quake2Pack.zip -pack Quake2WorldPack GPL svn svn://jdolan.dyndns.org/quake2world/trunk/gtkradiant -pack QuakePack proprietary zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/QuakePack.zip -pack TremulousPack proprietary zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/TremulousPack.zip -pack UFOAIPack proprietary svn https://zerowing.idsoftware.com/svn/radiant.gamepacks/UFOAIPack/branches/1.5/ -pack WarsowPack GPL svn https://svn.bountysource.com/wswpack/trunk/netradiant/games/WarsowPack/ -pack XonoticPack GPL git git://git.xonotic.org/xonotic/netradiant-xonoticpack.git diff --git a/misc/mediasource/extra/netradiant-src/gen.readme b/misc/mediasource/extra/netradiant-src/gen.readme deleted file mode 100644 index 4b735df4..00000000 --- a/misc/mediasource/extra/netradiant-src/gen.readme +++ /dev/null @@ -1,4 +0,0 @@ -Dummy file for gen.dsp - -gen.dsp is used with MSVC to generate include/version.h and include/aboutmsg.h -you need python installed and configured to make this work diff --git a/misc/mediasource/extra/netradiant-src/gendox b/misc/mediasource/extra/netradiant-src/gendox deleted file mode 100644 index c25663fb..00000000 --- a/misc/mediasource/extra/netradiant-src/gendox +++ /dev/null @@ -1,150 +0,0 @@ -#!/bin/bash -# -# Shell script to make doxygen documentation by specifying a target directory -# on the command line -# -# Gef (gefdavis@dingoblue.net.au) -- August 2001 - -# TODO: -# - Dynamic ChangeLog (page gets updated with each commit) -# - Have the ability to specify server dox or local dox, which will then -# change the content on the main page -# - Incorporate a scaled gtkradiant splash image into the pages - -#------------------------------------------------------------------------ -# Set some variables -#------------------------------------------------------------------------ -# WORKINGDIR=`pwd`; -RETVAL=0; -TARGETSTRING=''; -EXTRAS_PATH="./Doxygen_files"; -CONFIG_OUTPUT="$EXTRAS_PATH/genConf"; -DOXYCONFIG="./DoxyConfig"; -DOXYFILE="$EXTRAS_PATH/Doxyfile"; -NEWDOXYFILE="$EXTRAS_PATH/genDoxyfile"; -declare -a TARGETLIST[$#]; -COUNTER=0; -TARGETCOUNT=0; -QUIETMODE=0; -# added -k command line option to kill running doxygen procs -KILLON=0 - -#------------------------------------------------------------------------ -# load the functions -#------------------------------------------------------------------------ -if [ -f "$EXTRAS_PATH/gendoxfunctions" ] ; then - . $EXTRAS_PATH/gendoxfunctions -else - echo -e "Missing critical files...\n"; - exit 1; -fi - -#------------------------------------------------------------------------ -# parse the command line options -#------------------------------------------------------------------------ -COMLINE="$*"; -OPTCOUNT="$#"; -parse_commandline; -if [ $RETVAL -gt 0 ] ; then - echo -e "Exiting."; - exit $RETVAL; -fi - - -if [ $KILLON -gt 0 ] ; then - PIDOF_DOXYGEN=`pidof -x doxygen` - MYPID=$$ - - if [ -z "$PIDOF_DOXYGEN" ] ; then - [ $QUIETMODE -gt 0 ] || echo -e " * Killing other doxygen pids"; - killall -q -9 doxygen - else - [ $QUIETMODE -gt 0 ] || echo -e " * Killing other doxygen pids"; - kill -9 $PIDOF_DOXYGEN &> /dev/null - fi - - [ $QUIETMODE -gt 0 ] || echo -e " * Cleaning up gendox pids"; - killall -q -9 `pidof -x gendox | sed -e s/$MYPID//` &> /dev/null - -fi - -# If the output dir hasn't been set yet... -#if [ -z "$OUTPUTDIR" ] ; then -# OUTPUTDIR="../$(basename `pwd`)-doxygen"; -#fi - -#------------------------------------------------------------------------ -# execute some functions to determine stuff(c) -# Get the perl path (either from the config file, or find it) -#------------------------------------------------------------------------ -get_perlpath; -if [ X"$PERLPATH" == "X" ] ; then - echo -e "\nError: A working install of perl is needed to use doxygen"; - exit 2; -fi -[ $QUIETMODE -gt 0 ] || echo -e " -> Set PERL_PATH to: $PERLPATH"; - -get_dotpath; -[ $QUIETMODE -gt 0 ] || echo -e " -> Set HAVE_DOT to: $HAVEDOT"; -if [ X"$HAVEDOT" == "XYes" ] ; then - [ $QUIETMODE -gt 0 ] || echo -e " -> Set DOT_PATH to: $DOTPATH"; -fi - -get_language; -[ $QUIETMODE -gt 0 ] || echo -e " -> Set OUTPUT_LANGUAGE to: $OUPUTLANGUAGE"; - -get_projectname; -[ $QUIETMODE -gt 0 ] || echo -e " -> Set PROJECT_NAME to: $PROJECTNAME"; - -get_version; -[ $QUIETMODE -gt 0 ] || echo -e " -> Set PROJECT_NUMBER to: $VERSION"; -#------------------------------------------------------------------------ -# Got everything we need, now write the DoxyConfig file and run doxygen -#------------------------------------------------------------------------ - -# Clean up first -clean_up; - -# Put the images & reference pages in the right place -move_stuff; -if [ $RETVAL -ge 666 ] ; then - exit 666; -fi - -# Generate the config file -gen_doxyconfig; -if [ $RETVAL -gt 0 ] ; then - echo -e "Error: You are missing critical files." - exit RETVAL; -fi - -# build the reference page and the index -build_extra_html; - -# Generate documentation -RETVAL=0; -run_doxygen; -if [ $RETVAL -gt 0 ] ; then - echo -e "Doxygen error: returned $RETVAL"; - echo -e " Check doxygen.log for details"; -elif [ $RETVAL -lt 0 ] ; then - echo -e "Doxygen error: Doxygen returned $RETVAL"; -fi - -# if the log file is empty, remove it -if [ ! -s ./doxygen.log ] ; then - rm -f ./doxygen.log -fi - -#------------------------------------------------------------------------ -# Done. -#------------------------------------------------------------------------ -[ $QUIETMODE -gt 0 ] || echo -e "Finished..."; -[ $QUIETMODE -gt 0 ] || echo -e "Duration: $SECONDS seconds\n"; - -# echo -e "** Removing output while in debug mode **"; -# echo -e "** Output dir: $OUTPUTDIR **\n"; -# rm -rf $OUTPUTDIR - -exit 0; - diff --git a/misc/mediasource/extra/netradiant-src/generic_cpp.py b/misc/mediasource/extra/netradiant-src/generic_cpp.py deleted file mode 100644 index 62d51ed9..00000000 --- a/misc/mediasource/extra/netradiant-src/generic_cpp.py +++ /dev/null @@ -1,40 +0,0 @@ -# Copyright (C) 2001-2006 William Joseph. -# 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 - - -import os -import sys - -def svnAddText(filename): - os.system("svn add " + filename); - os.system("svn ps svn:eol-style native " + filename); - -def createCPPTemplate(filename, name): - file = open(filename, "wt") - file.write("\n") - file.write("#include \"" + name + ".h\"\n") - file.write("\n") - file.close() - -if __name__ == "__main__": - name = sys.argv[1] - location = sys.argv[2] - filename = os.path.join(location, name + ".cpp") - createCPPTemplate(filename, name) - svnAddText(filename) diff --git a/misc/mediasource/extra/netradiant-src/generic_h.py b/misc/mediasource/extra/netradiant-src/generic_h.py deleted file mode 100644 index 9f8b7e98..00000000 --- a/misc/mediasource/extra/netradiant-src/generic_h.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (C) 2001-2006 William Joseph. -# 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 - - -import os -import sys - -def svnAddText(filename): - os.system("svn add " + filename); - os.system("svn ps svn:eol-style native " + filename); - -def createHeaderTemplate(filename, name): - file = open(filename, "wt") - file.write("\n") - file.write("#if !defined(_INCLUDED_" + name.upper() + "_H_)\n") - file.write("#define _INCLUDED_" + name.upper() + "_H_\n") - file.write("\n") - file.write("#endif\n") - -if __name__ == "__main__": - name = sys.argv[1] - location = sys.argv[2] - filename = os.path.join(location, name + ".h") - createHeaderTemplate(filename, name) - svnAddText(filename) diff --git a/misc/mediasource/extra/netradiant-src/generic_module.py b/misc/mediasource/extra/netradiant-src/generic_module.py deleted file mode 100644 index e055e8fa..00000000 --- a/misc/mediasource/extra/netradiant-src/generic_module.py +++ /dev/null @@ -1,59 +0,0 @@ -# Copyright (C) 2001-2006 William Joseph. -# 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 - - -import os -import sys - -def svnAddText(filename): - os.system("svn add " + filename); - os.system("svn ps svn:eol-style native " + filename); - -def createHeaderTemplate(filename, name): - file = open(filename, "wt") - file.write("\n") - file.write("#if !defined(INCLUDED_" + name.upper() + "_H)\n") - file.write("#define INCLUDED_" + name.upper() + "_H\n") - file.write("\n") - file.write("#endif\n") - -def createCPPTemplate(filename, name): - file = open(filename, "wt") - file.write("\n") - file.write("#include \"" + name + ".h\"\n") - file.write("\n") - file.close() - -if __name__ == "__main__": - if not len(sys.argv) == 2: - print "usage: " + sys.argv[0] + " " - - path = sys.argv[1] - name = os.path.split(path)[1]; - - h = os.path.normpath(path + ".h") - print "writing " + h; - createHeaderTemplate(h, name) - svnAddText(h) - - cpp = os.path.normpath(path + ".cpp") - print "writing " + cpp; - createCPPTemplate(cpp, name) - svnAddText(cpp) - diff --git a/misc/mediasource/extra/netradiant-src/icons/h2data.ico b/misc/mediasource/extra/netradiant-src/icons/h2data.ico deleted file mode 100644 index 8f441941..00000000 Binary files a/misc/mediasource/extra/netradiant-src/icons/h2data.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/icons/q2map.ico b/misc/mediasource/extra/netradiant-src/icons/q2map.ico deleted file mode 100644 index 5c508c91..00000000 Binary files a/misc/mediasource/extra/netradiant-src/icons/q2map.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/icons/q3data.ico b/misc/mediasource/extra/netradiant-src/icons/q3data.ico deleted file mode 100644 index 8f441941..00000000 Binary files a/misc/mediasource/extra/netradiant-src/icons/q3data.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/icons/q3map2.ico b/misc/mediasource/extra/netradiant-src/icons/q3map2.ico deleted file mode 100644 index 4fe56fa6..00000000 Binary files a/misc/mediasource/extra/netradiant-src/icons/q3map2.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/icons/qdata3.ico b/misc/mediasource/extra/netradiant-src/icons/qdata3.ico deleted file mode 100644 index 8f441941..00000000 Binary files a/misc/mediasource/extra/netradiant-src/icons/qdata3.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/icons/radiant-src.png b/misc/mediasource/extra/netradiant-src/icons/radiant-src.png deleted file mode 100644 index 720e9857..00000000 Binary files a/misc/mediasource/extra/netradiant-src/icons/radiant-src.png and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/icons/radiant.ico b/misc/mediasource/extra/netradiant-src/icons/radiant.ico deleted file mode 100644 index d377f825..00000000 Binary files a/misc/mediasource/extra/netradiant-src/icons/radiant.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/include/aboutmsg.default b/misc/mediasource/extra/netradiant-src/include/aboutmsg.default deleted file mode 100644 index 0f536453..00000000 --- a/misc/mediasource/extra/netradiant-src/include/aboutmsg.default +++ /dev/null @@ -1 +0,0 @@ -Custom build based on trunk \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/include/aboutmsg.h b/misc/mediasource/extra/netradiant-src/include/aboutmsg.h deleted file mode 100644 index 8b5acc2c..00000000 --- a/misc/mediasource/extra/netradiant-src/include/aboutmsg.h +++ /dev/null @@ -1,4 +0,0 @@ -// Makefile appends preprocessor flags instead now -#ifndef RADIANT_ABOUTMSG -#error no RADIANT_ABOUTMSG defined -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/cullable.cpp b/misc/mediasource/extra/netradiant-src/include/cullable.cpp deleted file mode 100644 index 352ea5d6..00000000 --- a/misc/mediasource/extra/netradiant-src/include/cullable.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "cullable.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/cullable.h b/misc/mediasource/extra/netradiant-src/include/cullable.h deleted file mode 100644 index 8e3c71bc..00000000 --- a/misc/mediasource/extra/netradiant-src/include/cullable.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_CULLABLE_H) -#define INCLUDED_CULLABLE_H - -#include "generic/constant.h" - -template class BasicVector3; -typedef BasicVector3 Vector3; -class Plane3; -class Matrix4; -class AABB; -class Segment; - -template class EnumeratedValue; -struct VolumeIntersection; -typedef EnumeratedValue VolumeIntersectionValue; - -class VolumeTest -{ -public: - - /// \brief Returns true if \p point intersects volume. - virtual bool TestPoint(const Vector3& point) const = 0; - /// \brief Returns true if \p segment intersects volume. - virtual bool TestLine(const Segment& segment) const = 0; - /// \brief Returns true if \p plane faces towards volume. - virtual bool TestPlane(const Plane3& plane) const = 0; - /// \brief Returns true if \p plane transformed by \p localToWorld faces the viewer. - virtual bool TestPlane(const Plane3& plane, const Matrix4& localToWorld) const = 0; - /// \brief Returns the intersection of \p aabb and volume. - virtual VolumeIntersectionValue TestAABB(const AABB& aabb) const = 0; - /// \brief Returns the intersection of \p aabb transformed by \p localToWorld and volume. - virtual VolumeIntersectionValue TestAABB(const AABB& aabb, const Matrix4& localToWorld) const = 0; - - virtual bool fill() const = 0; - - virtual const Matrix4& GetViewport() const = 0; - virtual const Matrix4& GetProjection() const = 0; - virtual const Matrix4& GetModelview() const = 0; -}; - -class Cullable -{ -public: - STRING_CONSTANT(Name, "Cullable"); - - virtual VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const = 0; -}; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/editable.cpp b/misc/mediasource/extra/netradiant-src/include/editable.cpp deleted file mode 100644 index bcd04d8a..00000000 --- a/misc/mediasource/extra/netradiant-src/include/editable.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "editable.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/editable.h b/misc/mediasource/extra/netradiant-src/include/editable.h deleted file mode 100644 index 9e9bac04..00000000 --- a/misc/mediasource/extra/netradiant-src/include/editable.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_EDITABLE_H) -#define INCLUDED_EDITABLE_H - -template class BasicVector3; -typedef BasicVector3 Vector3; -template class BasicVector4; -typedef BasicVector4 Vector4; -class Matrix4; -typedef Vector4 Quaternion; - -#include "scenelib.h" - -class Editable -{ -public: - STRING_CONSTANT(Name, "Editable"); - - virtual const Matrix4& getLocalPivot() const = 0; -}; - -inline Editable* Node_getEditable(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -class Snappable -{ -public: - STRING_CONSTANT(Name, "Snappable"); - - virtual void snapto(float snap) = 0; -}; - -inline Snappable* Node_getSnappable(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iarchive.cpp b/misc/mediasource/extra/netradiant-src/include/iarchive.cpp deleted file mode 100644 index b975bf05..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iarchive.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "iarchive.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iarchive.h b/misc/mediasource/extra/netradiant-src/include/iarchive.h deleted file mode 100644 index b3f21016..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iarchive.h +++ /dev/null @@ -1,162 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IARCHIVE_H) -#define INCLUDED_IARCHIVE_H - -#include -#include "generic/constant.h" - -class InputStream; - -/// \brief A file opened in binary mode. -class ArchiveFile -{ -public: - /// \brief Destroys the file object. - virtual void release() = 0; - /// \brief Returns the size of the file data in bytes. - virtual std::size_t size() const = 0; - /// \brief Returns the path to this file (relative to the filesystem root) - virtual const char* getName() const = 0; - /// \brief Returns the stream associated with this file. - /// Subsequent calls return the same stream. - /// The stream may be read forwards until it is exhausted. - /// The stream remains valid for the lifetime of the file. - virtual InputStream& getInputStream() = 0; -}; - -class TextInputStream; - -/// \brief A file opened in text mode. -class ArchiveTextFile -{ -public: - /// \brief Destroys the file object. - virtual void release() = 0; - /// \brief Returns the stream associated with this file. - /// Subsequent calls return the same stream. - /// The stream may be read forwards until it is exhausted. - /// The stream remains valid for the lifetime of the file. - virtual TextInputStream& getInputStream() = 0; -}; - -class ScopedArchiveFile -{ - ArchiveFile& m_file; -public: - ScopedArchiveFile(ArchiveFile& file) : m_file(file) - { - } - ~ScopedArchiveFile() - { - m_file.release(); - } -}; - -class CustomArchiveVisitor; - -class Archive -{ -public: - - class Visitor - { - public: - virtual void visit(const char* name) = 0; - }; - - typedef CustomArchiveVisitor VisitorFunc; - - enum EMode - { - eFiles = 0x01, - eDirectories = 0x02, - eFilesAndDirectories = 0x03, - }; - - /// \brief Destroys the archive object. - /// Any unreleased file object associated with the archive remains valid. */ - virtual void release() = 0; - /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. - /// Name comparisons are case-insensitive. - virtual ArchiveFile* openFile(const char* name) = 0; - /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. - /// Name comparisons are case-insensitive. - virtual ArchiveTextFile* openTextFile(const char* name) = 0; - /// Returns true if the file identified by \p name can be opened. - /// Name comparisons are case-insensitive. - virtual bool containsFile(const char* name) = 0; - /// \brief Performs a depth-first traversal of the archive tree starting at \p root. - /// Traverses the entire tree if \p root is "". - /// When a file is encountered, calls \c visitor.file passing the file name. - /// When a directory is encountered, calls \c visitor.directory passing the directory name. - /// Skips the directory if \c visitor.directory returned true. - /// Root comparisons are case-insensitive. - /// Names are mixed-case. - virtual void forEachFile(VisitorFunc visitor, const char* root) = 0; -}; - -class CustomArchiveVisitor -{ - Archive::Visitor* m_visitor; - Archive::EMode m_mode; - std::size_t m_depth; -public: - CustomArchiveVisitor(Archive::Visitor& visitor, Archive::EMode mode, std::size_t depth) - : m_visitor(&visitor), m_mode(mode), m_depth(depth) - { - } - void file(const char* name) - { - if((m_mode & Archive::eFiles) != 0) - m_visitor->visit(name); - } - bool directory(const char* name, std::size_t depth) - { - if((m_mode & Archive::eDirectories) != 0) - m_visitor->visit(name); - if(depth == m_depth) - return true; - return false; - } -}; - -typedef Archive* (*PFN_OPENARCHIVE) (const char* name); - -class _QERArchiveTable -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "archive"); - - PFN_OPENARCHIVE m_pfnOpenArchive; -}; - -template -class Modules; -typedef Modules<_QERArchiveTable> ArchiveModules; - -template -class ModulesRef; -typedef ModulesRef<_QERArchiveTable> ArchiveModulesRef; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ibrush.cpp b/misc/mediasource/extra/netradiant-src/include/ibrush.cpp deleted file mode 100644 index 05dc91ef..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ibrush.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "ibrush.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ibrush.h b/misc/mediasource/extra/netradiant-src/include/ibrush.h deleted file mode 100644 index ddc82559..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ibrush.h +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IBRUSH_H) -#define INCLUDED_IBRUSH_H - -#include "generic/constant.h" -#include "generic/callback.h" -#include "generic/vector.h" -#include "itexdef.h" - -namespace scene -{ - class Node; -} - -#if 0 -class IBrushFace -{ -public: - virtual const char* GetShader() const = 0; - virtual void SetShader(const char* name) = 0; - virtual const TextureProjection& GetTexdef() const = 0; - virtual void GetTexdef(TextureProjection& projection) const = 0; - virtual void SetTexdef(const TextureProjection& projection) = 0; - virtual void GetFlags(ContentsFlagsValue& flags) const = 0; - virtual void SetFlags(const ContentsFlagsValue& flags) = 0; - virtual void ShiftTexdef(float s, float t) = 0; - virtual void ScaleTexdef(float s, float t) = 0; - virtual void RotateTexdef(float angle) = 0; - virtual void FitTexture(float s_repeat, float t_repeat) = 0; - virtual bool isDetail() const = 0; - virtual void setDetail(bool detail) = 0; -}; - -class IBrush -{ -public: - STRING_CONSTANT(Name, "IBrush"); - virtual void reserve(std::size_t count) = 0; - virtual void clear() = 0; - virtual void copy(const IBrush& other) = 0; - virtual IBrushFace* addPlane(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection) = 0; - virtual const AABB& localAABB() const = 0; - virtual void removeEmptyFaces() = 0; -}; - -class IBrushFaceInstance -{ -public: - virtual IBrushFace& getFace() = 0; - virtual const IBrushFace& getFace() const = 0; - virtual bool isSelected() const = 0; - virtual void setSelected(SelectionSystem::EComponentMode mode, bool select) const = 0; -}; - -class IBrushInstance -{ -public: - STRING_CONSTANT(Name, "IBrushInstance"); - virtual void forEachFaceInstance(const BrushInstanceVisitor& visitor) = 0; -}; -#endif - -class _QERFaceData -{ -public: - _QERFaceData() : m_shader(""), contents(0), flags(0), value(0) - { - } - Vector3 m_p0; - Vector3 m_p1; - Vector3 m_p2; - texdef_t m_texdef; - const char* m_shader; - int contents; - int flags; - int value; -}; - -typedef Callback1 BrushFaceDataCallback; - -class BrushCreator -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "brush"); - virtual scene::Node& createBrush() = 0; - virtual bool useAlternativeTextureProjection() const = 0; - virtual void Brush_forEachFace(scene::Node& brush, const BrushFaceDataCallback& callback) = 0; - virtual bool Brush_addFace(scene::Node& brush, const _QERFaceData& faceData) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalBrushModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalBrushModuleRef; - -inline BrushCreator& GlobalBrushCreator() -{ - return GlobalBrushModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/icamera.cpp b/misc/mediasource/extra/netradiant-src/include/icamera.cpp deleted file mode 100644 index 436e93a9..00000000 --- a/misc/mediasource/extra/netradiant-src/include/icamera.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "icamera.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/icamera.h b/misc/mediasource/extra/netradiant-src/include/icamera.h deleted file mode 100644 index c98fdc06..00000000 --- a/misc/mediasource/extra/netradiant-src/include/icamera.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -Copyright (C) 1999-2006 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: -// camera interface -// - -#if !defined(INCLUDED_ICAMERA_H) -#define INCLUDED_ICAMERA_H - -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -class Matrix4; - -class CameraView -{ -public: - virtual void setModelview(const Matrix4& modelview) = 0; - virtual void setFieldOfView(float fieldOfView) = 0; -}; - -class CameraModel -{ -public: - STRING_CONSTANT(Name, "CameraModel"); - virtual void setCameraView(CameraView* view, const Callback& disconnect) = 0; -}; - -template class BasicVector3; -typedef BasicVector3 Vector3; - -typedef void (* PFN_GETCAMERA) ( Vector3& origin, Vector3& angles ); -typedef void (* PFN_SETCAMERA) ( const Vector3& origin, const Vector3& angles ); -typedef void (* PFN_GETCAMWINDOWEXTENTS) ( int *x, int *y, int *width, int *height ); - -struct _QERCameraTable -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "camera"); - - PFN_GETCAMERA m_pfnGetCamera; - PFN_SETCAMERA m_pfnSetCamera; - PFN_GETCAMWINDOWEXTENTS m_pfnGetCamWindowExtents; -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/idatastream.cpp b/misc/mediasource/extra/netradiant-src/include/idatastream.cpp deleted file mode 100644 index fff02b57..00000000 --- a/misc/mediasource/extra/netradiant-src/include/idatastream.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "idatastream.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/idatastream.h b/misc/mediasource/extra/netradiant-src/include/idatastream.h deleted file mode 100644 index c5a28a25..00000000 --- a/misc/mediasource/extra/netradiant-src/include/idatastream.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IDATASTREAM_H) -#define INCLUDED_IDATASTREAM_H - -#include - -class StreamBase -{ -public: - typedef std::size_t size_type; - typedef unsigned char byte_type; -}; - -/// \brief A read-only byte-stream. -class InputStream : public StreamBase -{ -public: - /// \brief Attempts to read the next \p length bytes from the stream to \p buffer. - /// Returns the number of bytes actually stored in \p buffer. - virtual size_type read(byte_type* buffer, size_type length) = 0; -}; - -/// \brief A write-only byte-stream. -class OutputStream : public StreamBase -{ -public: - /// \brief Attempts to write \p length bytes to the stream from \p buffer. - /// Returns the number of bytes actually read from \p buffer. - virtual size_type write(const byte_type* buffer, size_type length) = 0; -}; - -class SeekableStream -{ -public: - typedef int offset_type; - typedef std::size_t position_type; - - enum seekdir - { - beg, - cur, - end, - }; - - /// \brief Sets the current \p position of the stream relative to the start. - virtual position_type seek(position_type position) = 0; - /// \brief Sets the current \p position of the stream relative to either the start, end or current position. - virtual position_type seek(offset_type offset, seekdir direction) = 0; - /// \brief Returns the current position of the stream. - virtual position_type tell() const = 0; -}; - -/// \brief A seekable read-only byte-stream. -class SeekableInputStream : public InputStream, public SeekableStream -{ -}; - -/// \brief A seekable write-only byte-stream. -class SeekableOutputStream : public OutputStream, public SeekableStream -{ -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ieclass.cpp b/misc/mediasource/extra/netradiant-src/include/ieclass.cpp deleted file mode 100644 index 461edd53..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ieclass.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "ieclass.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ieclass.h b/misc/mediasource/extra/netradiant-src/include/ieclass.h deleted file mode 100644 index 89b86ca9..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ieclass.h +++ /dev/null @@ -1,118 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/// \file ieclass.h -/// \brief Entity Class definition loader API. - - -#if !defined(INCLUDED_IECLASS_H) -#define INCLUDED_IECLASS_H - -#include "generic/constant.h" - -#define MAX_FLAGS 16 - -// eclass show flags - -#define ECLASS_LIGHT 0x00000001 -#define ECLASS_ANGLE 0x00000002 -#define ECLASS_PATH 0x00000004 -#define ECLASS_MISCMODEL 0x00000008 - -class Shader; - -class EntityClass; -class ListAttributeType; - -class EntityClassCollector -{ -public: - virtual void insert(EntityClass* eclass) = 0; - virtual void insert(const char* name, const ListAttributeType& list) - { - } -}; - -struct EntityClassScanner -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "eclass"); - - void (*scanFile)(EntityClassCollector& collector, const char* filename); - const char* (*getExtension)(); -}; - -#include "modulesystem.h" - -template -class ModuleRef; -typedef ModuleRef EClassModuleRef; - -template -class Modules; -typedef Modules EClassModules; - -template -class ModulesRef; -typedef ModulesRef EClassModulesRef; - - - - - - -class EntityClassVisitor -{ -public: - virtual void visit(EntityClass* eclass) = 0; -}; - -class ModuleObserver; - - -struct EntityClassManager -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "eclassmanager"); - - EntityClass* (*findOrInsert)(const char* name, bool has_brushes); - const ListAttributeType* (*findListType)(const char* name); - void (*forEach)(EntityClassVisitor& visitor); - void (*attach)(ModuleObserver& observer); - void (*detach)(ModuleObserver& observer); - void (*realise)(); - void (*unrealise)(); -}; - -template -class GlobalModule; -typedef GlobalModule GlobalEntityClassManagerModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalEntityClassManagerModuleRef; - -inline EntityClassManager& GlobalEntityClassManager() -{ - return GlobalEntityClassManagerModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ientity.cpp b/misc/mediasource/extra/netradiant-src/include/ientity.cpp deleted file mode 100644 index 0a2eef32..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ientity.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "ientity.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ientity.h b/misc/mediasource/extra/netradiant-src/include/ientity.h deleted file mode 100644 index c74ed7c6..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ientity.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IENTITY_H) -#define INCLUDED_IENTITY_H - -#include "generic/constant.h" - -#include "string/string.h" -#include "scenelib.h" - -class EntityClass; - -typedef Callback1 KeyObserver; - -class EntityKeyValue -{ -public: - virtual const char* c_str() const = 0; - virtual void assign(const char* other) = 0; - virtual void attach(const KeyObserver& observer) = 0; - virtual void detach(const KeyObserver& observer) = 0; -}; - -class Entity -{ -public: - STRING_CONSTANT(Name, "Entity"); - - class Observer - { - public: - virtual void insert(const char* key, EntityKeyValue& value) = 0; - virtual void erase(const char* key, EntityKeyValue& value) = 0; - virtual void clear() { }; - }; - - class Visitor - { - public: - virtual void visit(const char* key, const char* value) = 0; - }; - - virtual const EntityClass& getEntityClass() const = 0; - virtual void forEachKeyValue(Visitor& visitor) const = 0; - virtual void setKeyValue(const char* key, const char* value) = 0; - virtual const char* getKeyValue(const char* key) const = 0; - virtual bool isContainer() const = 0; - virtual void attach(Observer& observer) = 0; - virtual void detach(Observer& observer) = 0; -}; - -class EntityCopyingVisitor : public Entity::Visitor -{ - Entity& m_entity; -public: - EntityCopyingVisitor(Entity& entity) - : m_entity(entity) - { - } - - void visit(const char* key, const char* value) - { - if(!string_equal(key, "classname")) - { - m_entity.setKeyValue(key, value); - } - } -}; - -inline Entity* Node_getEntity(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - - -template -class Stack; -template -class Reference; - -namespace scene -{ - class Node; -} - -typedef Reference NodeReference; - -namespace scene -{ - typedef Stack Path; -} - -class Counter; - -class EntityCreator -{ -public: - INTEGER_CONSTANT(Version, 2); - STRING_CONSTANT(Name, "entity"); - - virtual scene::Node& createEntity(EntityClass* eclass) = 0; - - typedef void (*KeyValueChangedFunc)(); - virtual void setKeyValueChangedFunc(KeyValueChangedFunc func) = 0; - - virtual void setCounter(Counter* counter) = 0; - - virtual void connectEntities(const scene::Path& e1, const scene::Path& e2, int index) = 0; - - virtual void setLightRadii(bool lightRadii) = 0; - virtual bool getLightRadii() = 0; - virtual void setShowNames(bool showNames) = 0; - virtual bool getShowNames() = 0; - virtual void setShowAngles(bool showAngles) = 0; - virtual bool getShowAngles() = 0; - - virtual void printStatistics() const = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalEntityModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalEntityModuleRef; - -inline EntityCreator& GlobalEntityCreator() -{ - return GlobalEntityModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ifilesystem.cpp b/misc/mediasource/extra/netradiant-src/include/ifilesystem.cpp deleted file mode 100644 index d941113c..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ifilesystem.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "ifilesystem.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ifilesystem.h b/misc/mediasource/extra/netradiant-src/include/ifilesystem.h deleted file mode 100644 index ed9e99fd..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ifilesystem.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IFILESYSTEM_H) -#define INCLUDED_IFILESYSTEM_H - -#include -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -typedef Callback1 ArchiveNameCallback; -typedef Callback1 FileNameCallback; - -class ArchiveFile; -class ArchiveTextFile; -class Archive; - -class ModuleObserver; - -typedef struct _GSList GSList; - -/// The Virtual File System. -class VirtualFileSystem -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "VFS"); - - /// \brief Adds a root search \p path. - /// Called before \c initialise. - virtual void initDirectory(const char *path) = 0; - /// \brief Initialises the filesystem. - /// Called after all root search paths have been added. - virtual void initialise() = 0; - /// \brief Shuts down the filesystem. - virtual void shutdown() = 0; - - /// \brief Returns the file identified by \p filename opened in binary mode, or 0 if not found. - /// The caller must \c release() the file returned if it is not 0. - virtual ArchiveFile* openFile(const char* filename) = 0; - /// \brief Returns the file identified by \p filename opened in text mode, or 0 if not found. - /// The caller must \c release() the file returned if it is not 0. - virtual ArchiveTextFile* openTextFile(const char* filename) = 0; - - /// \brief Opens the file identified by \p filename and reads it into \p buffer, or sets *\p buffer to 0 if not found. - /// Returns the size of the buffer allocated, or undefined value if *\p buffer is 0; - /// The caller must free the allocated buffer by calling \c freeFile - /// \deprecated Deprecated - use \c openFile. - virtual std::size_t loadFile(const char *filename, void **buffer) = 0; - /// \brief Frees the buffer returned by \c loadFile. - /// \deprecated Deprecated. - virtual void freeFile(void *p) = 0; - - /// \brief Calls \p callback for each directory under \p basedir. - virtual void forEachDirectory(const char* basedir, const FileNameCallback& callback, std::size_t depth = 1) = 0; - /// \brief Calls \p callback for each file under \p basedir matching \p extension. - /// Use "*" as \p extension to match all file extensions. - virtual void forEachFile(const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth = 1) = 0; - - /// \brief Returns a list containing the relative names of all the directories under \p basedir. - /// The caller must free the returned list by calling \c clearFileDirList; - /// \deprecated Deprecated - use \c forEachDirectory. - virtual GSList* getDirList(const char *basedir) = 0; - /// \brief Returns a list containing the relative names of the files under \p basedir (\p extension can be "*" for all files). - /// The caller must free the returned list by calling \c clearFileDirList. - /// \deprecated Deprecated - use \c forEachFile. - virtual GSList* getFileList(const char *basedir, const char *extension) = 0; - /// \brief Frees the \p list returned from \c getDirList or \c getFileList. - /// \deprecated Deprecated. - virtual void clearFileDirList(GSList **list) = 0; - - /// \brief Returns the absolute filename for a relative \p name, or "" if not found. - virtual const char* findFile(const char* name) = 0; - /// \brief Returns the filesystem root for an absolute \p name, or "" if not found. - /// This can be used to convert an absolute name to a relative name. - virtual const char* findRoot(const char* name) = 0; - - /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the filesystem is initialised or shut down. - virtual void attach(ModuleObserver& observer) = 0; - /// \brief Detach an \p observer previously-attached by calling \c attach. - virtual void detach(ModuleObserver& observer) = 0; - - virtual Archive* getArchive(const char* archiveName, bool pakonly=true) = 0; - virtual void forEachArchive(const ArchiveNameCallback& callback, bool pakonly=true, bool reverse=false) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalFileSystemModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalFileSystemModuleRef; - -inline VirtualFileSystem& GlobalFileSystem() -{ - return GlobalFileSystemModule::getTable(); -} - - -/// \deprecated Use \c openFile. -inline int vfsLoadFile(const char* filename, void** buffer, int index = 0) -{ - return static_cast(GlobalFileSystem().loadFile(filename, buffer)); -}; - -/// \deprecated Deprecated. -inline void vfsFreeFile(void* p) -{ - GlobalFileSystem().freeFile(p); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ifiletypes.cpp b/misc/mediasource/extra/netradiant-src/include/ifiletypes.cpp deleted file mode 100644 index 1d151586..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ifiletypes.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "ifiletypes.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ifiletypes.h b/misc/mediasource/extra/netradiant-src/include/ifiletypes.h deleted file mode 100644 index 0d061d2b..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ifiletypes.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IFILETYPES_H) -#define INCLUDED_IFILETYPES_H - -#include "generic/constant.h" - -class filetype_t -{ -public: - filetype_t() - : name(""), pattern("") - { - } - filetype_t(const char* _name, const char* _pattern, bool _can_load = true, bool _can_import = true, bool _can_save = true) - : name(_name), pattern(_pattern), can_load(_can_load), can_import(_can_import), can_save(_can_save) - { - } - const char* name; - const char* pattern; - bool can_load; - bool can_import; - bool can_save; -}; - - -class IFileTypeList -{ -public: - virtual void addType(const char* moduleName, filetype_t type) = 0; -}; - -class IFileTypeRegistry -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "filetypes"); - - virtual void addType(const char* moduleType, const char* moduleName, filetype_t type) = 0; - virtual void getTypeList(const char* moduleType, IFileTypeList* typelist, bool want_load = false, bool want_import = false, bool want_save = false) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalFiletypesModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalFiletypesModuleRef; - -inline IFileTypeRegistry& GlobalFiletypes() -{ - return GlobalFiletypesModule::getTable(); -} - - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ifilter.cpp b/misc/mediasource/extra/netradiant-src/include/ifilter.cpp deleted file mode 100644 index 1472a935..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ifilter.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "ifilter.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ifilter.h b/misc/mediasource/extra/netradiant-src/include/ifilter.h deleted file mode 100644 index 3da2f1d6..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ifilter.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IFILTER_H) -#define INCLUDED_IFILTER_H - -#include "generic/constant.h" - -enum -{ - EXCLUDE_WORLD = 0x00000001, - EXCLUDE_ENT = 0x00000002, - EXCLUDE_CURVES = 0x00000004, - EXCLUDE_TRANSLUCENT = 0x00000008, - EXCLUDE_LIQUIDS = 0x00000010, - EXCLUDE_CAULK = 0x00000020, - EXCLUDE_CLIP = 0x00000040, - EXCLUDE_PATHS = 0x00000080, - EXCLUDE_LIGHTS = 0x00000100, - EXCLUDE_DETAILS = 0x00000200, - EXCLUDE_HINTSSKIPS = 0x00000400, - EXCLUDE_MODELS = 0x00000800, - EXCLUDE_AREAPORTALS = 0x00001000, - EXCLUDE_TRIGGERS = 0x00002000, - EXCLUDE_CLUSTERPORTALS = 0x00004000, - EXCLUDE_TERRAIN = 0x00008000, - EXCLUDE_LIGHTGRID = 0x00010000, - EXCLUDE_STRUCTURAL = 0x00020000, - EXCLUDE_BOTCLIP = 0x00040000, - EXCLUDE_VISPORTALS = 0x00080000, - EXCLUDE_DECALS = 0x00100000, -}; - -class Filter -{ -public: - virtual void setActive(bool active) = 0; -}; - -class Filterable -{ -public: - virtual void updateFiltered() = 0; -}; - -class FilterSystem -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "filters"); - virtual void addFilter(Filter& filter, int mask) = 0; - virtual void registerFilterable(Filterable& filterable) = 0; - virtual void unregisterFilterable(Filterable& filterable) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalFilterModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalFilterModuleRef; - -inline FilterSystem& GlobalFilterSystem() -{ - return GlobalFilterModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/igl.cpp b/misc/mediasource/extra/netradiant-src/include/igl.cpp deleted file mode 100644 index 170022ee..00000000 --- a/misc/mediasource/extra/netradiant-src/include/igl.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "igl.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/igl.h b/misc/mediasource/extra/netradiant-src/include/igl.h deleted file mode 100644 index 35174967..00000000 --- a/misc/mediasource/extra/netradiant-src/include/igl.h +++ /dev/null @@ -1,2834 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IGL_H) -#define INCLUDED_IGL_H - -#include -#include -#include "generic/constant.h" - -#if defined(WIN32) -#define QGL_DLLEXPORT __stdcall -#else -#define QGL_DLLEXPORT -#endif - -typedef unsigned int GLenum; -typedef unsigned char GLboolean; -typedef unsigned int GLbitfield; -typedef signed char GLbyte; -typedef short GLshort; -typedef int GLint; -typedef int GLsizei; -typedef unsigned char GLubyte; -typedef unsigned short GLushort; -typedef unsigned int GLuint; -typedef float GLfloat; -typedef float GLclampf; -typedef double GLdouble; -typedef double GLclampd; -typedef void GLvoid; - -#if !defined(GL_VERSION_1_1) -#define GL_VERSION_1_1 1 - -#define GL_ZERO 0 -#define GL_ONE 1 -#define GL_TRUE 1 -#define GL_FALSE 0 -#define GL_POINTS 0x0000 -#define GL_LINES 0x0001 -#define GL_LINE_LOOP 0x0002 -#define GL_LINE_STRIP 0x0003 -#define GL_TRIANGLES 0x0004 -#define GL_TRIANGLE_STRIP 0x0005 -#define GL_TRIANGLE_FAN 0x0006 -#define GL_QUADS 0x0007 -#define GL_QUAD_STRIP 0x0008 -#define GL_POLYGON 0x0009 -#define GL_ACCUM 0x0100 -#define GL_LOAD 0x0101 -#define GL_RETURN 0x0102 -#define GL_MULT 0x0103 -#define GL_ADD 0x0104 -#define GL_NEVER 0x0200 -#define GL_LESS 0x0201 -#define GL_EQUAL 0x0202 -#define GL_LEQUAL 0x0203 -#define GL_GREATER 0x0204 -#define GL_NOTEQUAL 0x0205 -#define GL_GEQUAL 0x0206 -#define GL_ALWAYS 0x0207 -#define GL_SRC_COLOR 0x0300 -#define GL_ONE_MINUS_SRC_COLOR 0x0301 -#define GL_SRC_ALPHA 0x0302 -#define GL_ONE_MINUS_SRC_ALPHA 0x0303 -#define GL_DST_ALPHA 0x0304 -#define GL_ONE_MINUS_DST_ALPHA 0x0305 -#define GL_DST_COLOR 0x0306 -#define GL_ONE_MINUS_DST_COLOR 0x0307 -#define GL_SRC_ALPHA_SATURATE 0x0308 -#define GL_BYTE 0x1400 -#define GL_UNSIGNED_BYTE 0x1401 -#define GL_SHORT 0x1402 -#define GL_UNSIGNED_SHORT 0x1403 -#define GL_INT 0x1404 -#define GL_UNSIGNED_INT 0x1405 -#define GL_FLOAT 0x1406 -#define GL_2_BYTES 0x1407 -#define GL_3_BYTES 0x1408 -#define GL_4_BYTES 0x1409 -#define GL_DOUBLE 0x140A -#define GL_NONE 0 -#define GL_FRONT_LEFT 0x0400 -#define GL_FRONT_RIGHT 0x0401 -#define GL_BACK_LEFT 0x0402 -#define GL_BACK_RIGHT 0x0403 -#define GL_FRONT 0x0404 -#define GL_BACK 0x0405 -#define GL_LEFT 0x0406 -#define GL_RIGHT 0x0407 -#define GL_FRONT_AND_BACK 0x0408 -#define GL_AUX0 0x0409 -#define GL_AUX1 0x040A -#define GL_AUX2 0x040B -#define GL_AUX3 0x040C -#define GL_NO_ERROR 0 -#define GL_INVALID_ENUM 0x0500 -#define GL_INVALID_VALUE 0x0501 -#define GL_INVALID_OPERATION 0x0502 -#define GL_STACK_OVERFLOW 0x0503 -#define GL_STACK_UNDERFLOW 0x0504 -#define GL_OUT_OF_MEMORY 0x0505 -#define GL_2D 0x0600 -#define GL_3D 0x0601 -#define GL_3D_COLOR 0x0602 -#define GL_3D_COLOR_TEXTURE 0x0603 -#define GL_4D_COLOR_TEXTURE 0x0604 -#define GL_PASS_THROUGH_TOKEN 0x0700 -#define GL_POINT_TOKEN 0x0701 -#define GL_LINE_TOKEN 0x0702 -#define GL_POLYGON_TOKEN 0x0703 -#define GL_BITMAP_TOKEN 0x0704 -#define GL_DRAW_PIXEL_TOKEN 0x0705 -#define GL_COPY_PIXEL_TOKEN 0x0706 -#define GL_LINE_RESET_TOKEN 0x0707 -#define GL_EXP 0x0800 -#define GL_EXP2 0x0801 -#define GL_CW 0x0900 -#define GL_CCW 0x0901 -#define GL_COEFF 0x0A00 -#define GL_ORDER 0x0A01 -#define GL_DOMAIN 0x0A02 -#define GL_CURRENT_COLOR 0x0B00 -#define GL_CURRENT_INDEX 0x0B01 -#define GL_CURRENT_NORMAL 0x0B02 -#define GL_CURRENT_TEXTURE_COORDS 0x0B03 -#define GL_CURRENT_RASTER_COLOR 0x0B04 -#define GL_CURRENT_RASTER_INDEX 0x0B05 -#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 -#define GL_CURRENT_RASTER_POSITION 0x0B07 -#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 -#define GL_CURRENT_RASTER_DISTANCE 0x0B09 -#define GL_POINT_SMOOTH 0x0B10 -#define GL_POINT_SIZE 0x0B11 -#define GL_POINT_SIZE_RANGE 0x0B12 -#define GL_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_LINE_SMOOTH 0x0B20 -#define GL_LINE_WIDTH 0x0B21 -#define GL_LINE_WIDTH_RANGE 0x0B22 -#define GL_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_LINE_STIPPLE 0x0B24 -#define GL_LINE_STIPPLE_PATTERN 0x0B25 -#define GL_LINE_STIPPLE_REPEAT 0x0B26 -#define GL_LIST_MODE 0x0B30 -#define GL_MAX_LIST_NESTING 0x0B31 -#define GL_LIST_BASE 0x0B32 -#define GL_LIST_INDEX 0x0B33 -#define GL_POLYGON_MODE 0x0B40 -#define GL_POLYGON_SMOOTH 0x0B41 -#define GL_POLYGON_STIPPLE 0x0B42 -#define GL_EDGE_FLAG 0x0B43 -#define GL_CULL_FACE 0x0B44 -#define GL_CULL_FACE_MODE 0x0B45 -#define GL_FRONT_FACE 0x0B46 -#define GL_LIGHTING 0x0B50 -#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 -#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 -#define GL_LIGHT_MODEL_AMBIENT 0x0B53 -#define GL_SHADE_MODEL 0x0B54 -#define GL_COLOR_MATERIAL_FACE 0x0B55 -#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 -#define GL_COLOR_MATERIAL 0x0B57 -#define GL_FOG 0x0B60 -#define GL_FOG_INDEX 0x0B61 -#define GL_FOG_DENSITY 0x0B62 -#define GL_FOG_START 0x0B63 -#define GL_FOG_END 0x0B64 -#define GL_FOG_MODE 0x0B65 -#define GL_FOG_COLOR 0x0B66 -#define GL_DEPTH_RANGE 0x0B70 -#define GL_DEPTH_TEST 0x0B71 -#define GL_DEPTH_WRITEMASK 0x0B72 -#define GL_DEPTH_CLEAR_VALUE 0x0B73 -#define GL_DEPTH_FUNC 0x0B74 -#define GL_ACCUM_CLEAR_VALUE 0x0B80 -#define GL_STENCIL_TEST 0x0B90 -#define GL_STENCIL_CLEAR_VALUE 0x0B91 -#define GL_STENCIL_FUNC 0x0B92 -#define GL_STENCIL_VALUE_MASK 0x0B93 -#define GL_STENCIL_FAIL 0x0B94 -#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 -#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 -#define GL_STENCIL_REF 0x0B97 -#define GL_STENCIL_WRITEMASK 0x0B98 -#define GL_MATRIX_MODE 0x0BA0 -#define GL_NORMALIZE 0x0BA1 -#define GL_VIEWPORT 0x0BA2 -#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 -#define GL_PROJECTION_STACK_DEPTH 0x0BA4 -#define GL_TEXTURE_STACK_DEPTH 0x0BA5 -#define GL_MODELVIEW_MATRIX 0x0BA6 -#define GL_PROJECTION_MATRIX 0x0BA7 -#define GL_TEXTURE_MATRIX 0x0BA8 -#define GL_ATTRIB_STACK_DEPTH 0x0BB0 -#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 -#define GL_ALPHA_TEST 0x0BC0 -#define GL_ALPHA_TEST_FUNC 0x0BC1 -#define GL_ALPHA_TEST_REF 0x0BC2 -#define GL_DITHER 0x0BD0 -#define GL_BLEND_DST 0x0BE0 -#define GL_BLEND_SRC 0x0BE1 -#define GL_BLEND 0x0BE2 -#define GL_LOGIC_OP_MODE 0x0BF0 -#define GL_INDEX_LOGIC_OP 0x0BF1 -#define GL_COLOR_LOGIC_OP 0x0BF2 -#define GL_AUX_BUFFERS 0x0C00 -#define GL_DRAW_BUFFER 0x0C01 -#define GL_READ_BUFFER 0x0C02 -#define GL_SCISSOR_BOX 0x0C10 -#define GL_SCISSOR_TEST 0x0C11 -#define GL_INDEX_CLEAR_VALUE 0x0C20 -#define GL_INDEX_WRITEMASK 0x0C21 -#define GL_COLOR_CLEAR_VALUE 0x0C22 -#define GL_COLOR_WRITEMASK 0x0C23 -#define GL_INDEX_MODE 0x0C30 -#define GL_RGBA_MODE 0x0C31 -#define GL_DOUBLEBUFFER 0x0C32 -#define GL_STEREO 0x0C33 -#define GL_RENDER_MODE 0x0C40 -#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 -#define GL_POINT_SMOOTH_HINT 0x0C51 -#define GL_LINE_SMOOTH_HINT 0x0C52 -#define GL_POLYGON_SMOOTH_HINT 0x0C53 -#define GL_FOG_HINT 0x0C54 -#define GL_TEXTURE_GEN_S 0x0C60 -#define GL_TEXTURE_GEN_T 0x0C61 -#define GL_TEXTURE_GEN_R 0x0C62 -#define GL_TEXTURE_GEN_Q 0x0C63 -#define GL_PIXEL_MAP_I_TO_I 0x0C70 -#define GL_PIXEL_MAP_S_TO_S 0x0C71 -#define GL_PIXEL_MAP_I_TO_R 0x0C72 -#define GL_PIXEL_MAP_I_TO_G 0x0C73 -#define GL_PIXEL_MAP_I_TO_B 0x0C74 -#define GL_PIXEL_MAP_I_TO_A 0x0C75 -#define GL_PIXEL_MAP_R_TO_R 0x0C76 -#define GL_PIXEL_MAP_G_TO_G 0x0C77 -#define GL_PIXEL_MAP_B_TO_B 0x0C78 -#define GL_PIXEL_MAP_A_TO_A 0x0C79 -#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 -#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 -#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 -#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 -#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 -#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 -#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 -#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 -#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 -#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 -#define GL_UNPACK_SWAP_BYTES 0x0CF0 -#define GL_UNPACK_LSB_FIRST 0x0CF1 -#define GL_UNPACK_ROW_LENGTH 0x0CF2 -#define GL_UNPACK_SKIP_ROWS 0x0CF3 -#define GL_UNPACK_SKIP_PIXELS 0x0CF4 -#define GL_UNPACK_ALIGNMENT 0x0CF5 -#define GL_PACK_SWAP_BYTES 0x0D00 -#define GL_PACK_LSB_FIRST 0x0D01 -#define GL_PACK_ROW_LENGTH 0x0D02 -#define GL_PACK_SKIP_ROWS 0x0D03 -#define GL_PACK_SKIP_PIXELS 0x0D04 -#define GL_PACK_ALIGNMENT 0x0D05 -#define GL_MAP_COLOR 0x0D10 -#define GL_MAP_STENCIL 0x0D11 -#define GL_INDEX_SHIFT 0x0D12 -#define GL_INDEX_OFFSET 0x0D13 -#define GL_RED_SCALE 0x0D14 -#define GL_RED_BIAS 0x0D15 -#define GL_ZOOM_X 0x0D16 -#define GL_ZOOM_Y 0x0D17 -#define GL_GREEN_SCALE 0x0D18 -#define GL_GREEN_BIAS 0x0D19 -#define GL_BLUE_SCALE 0x0D1A -#define GL_BLUE_BIAS 0x0D1B -#define GL_ALPHA_SCALE 0x0D1C -#define GL_ALPHA_BIAS 0x0D1D -#define GL_DEPTH_SCALE 0x0D1E -#define GL_DEPTH_BIAS 0x0D1F -#define GL_MAX_EVAL_ORDER 0x0D30 -#define GL_MAX_LIGHTS 0x0D31 -#define GL_MAX_CLIP_PLANES 0x0D32 -#define GL_MAX_TEXTURE_SIZE 0x0D33 -#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 -#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 -#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 -#define GL_MAX_NAME_STACK_DEPTH 0x0D37 -#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 -#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 -#define GL_MAX_VIEWPORT_DIMS 0x0D3A -#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B -#define GL_SUBPIXEL_BITS 0x0D50 -#define GL_INDEX_BITS 0x0D51 -#define GL_RED_BITS 0x0D52 -#define GL_GREEN_BITS 0x0D53 -#define GL_BLUE_BITS 0x0D54 -#define GL_ALPHA_BITS 0x0D55 -#define GL_DEPTH_BITS 0x0D56 -#define GL_STENCIL_BITS 0x0D57 -#define GL_ACCUM_RED_BITS 0x0D58 -#define GL_ACCUM_GREEN_BITS 0x0D59 -#define GL_ACCUM_BLUE_BITS 0x0D5A -#define GL_ACCUM_ALPHA_BITS 0x0D5B -#define GL_NAME_STACK_DEPTH 0x0D70 -#define GL_AUTO_NORMAL 0x0D80 -#define GL_MAP1_COLOR_4 0x0D90 -#define GL_MAP1_INDEX 0x0D91 -#define GL_MAP1_NORMAL 0x0D92 -#define GL_MAP1_TEXTURE_COORD_1 0x0D93 -#define GL_MAP1_TEXTURE_COORD_2 0x0D94 -#define GL_MAP1_TEXTURE_COORD_3 0x0D95 -#define GL_MAP1_TEXTURE_COORD_4 0x0D96 -#define GL_MAP1_VERTEX_3 0x0D97 -#define GL_MAP1_VERTEX_4 0x0D98 -#define GL_MAP2_COLOR_4 0x0DB0 -#define GL_MAP2_INDEX 0x0DB1 -#define GL_MAP2_NORMAL 0x0DB2 -#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 -#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 -#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 -#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 -#define GL_MAP2_VERTEX_3 0x0DB7 -#define GL_MAP2_VERTEX_4 0x0DB8 -#define GL_MAP1_GRID_DOMAIN 0x0DD0 -#define GL_MAP1_GRID_SEGMENTS 0x0DD1 -#define GL_MAP2_GRID_DOMAIN 0x0DD2 -#define GL_MAP2_GRID_SEGMENTS 0x0DD3 -#define GL_TEXTURE_1D 0x0DE0 -#define GL_TEXTURE_2D 0x0DE1 -#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 -#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 -#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 -#define GL_SELECTION_BUFFER_POINTER 0x0DF3 -#define GL_SELECTION_BUFFER_SIZE 0x0DF4 -#define GL_TEXTURE_WIDTH 0x1000 -#define GL_TEXTURE_HEIGHT 0x1001 -#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 -#define GL_TEXTURE_BORDER_COLOR 0x1004 -#define GL_TEXTURE_BORDER 0x1005 -#define GL_DONT_CARE 0x1100 -#define GL_FASTEST 0x1101 -#define GL_NICEST 0x1102 -#define GL_LIGHT0 0x4000 -#define GL_LIGHT1 0x4001 -#define GL_LIGHT2 0x4002 -#define GL_LIGHT3 0x4003 -#define GL_LIGHT4 0x4004 -#define GL_LIGHT5 0x4005 -#define GL_LIGHT6 0x4006 -#define GL_LIGHT7 0x4007 -#define GL_AMBIENT 0x1200 -#define GL_DIFFUSE 0x1201 -#define GL_SPECULAR 0x1202 -#define GL_POSITION 0x1203 -#define GL_SPOT_DIRECTION 0x1204 -#define GL_SPOT_EXPONENT 0x1205 -#define GL_SPOT_CUTOFF 0x1206 -#define GL_CONSTANT_ATTENUATION 0x1207 -#define GL_LINEAR_ATTENUATION 0x1208 -#define GL_QUADRATIC_ATTENUATION 0x1209 -#define GL_COMPILE 0x1300 -#define GL_COMPILE_AND_EXECUTE 0x1301 -#define GL_CLEAR 0x1500 -#define GL_AND 0x1501 -#define GL_AND_REVERSE 0x1502 -#define GL_COPY 0x1503 -#define GL_AND_INVERTED 0x1504 -#define GL_NOOP 0x1505 -#define GL_XOR 0x1506 -#define GL_OR 0x1507 -#define GL_NOR 0x1508 -#define GL_EQUIV 0x1509 -#define GL_INVERT 0x150A -#define GL_OR_REVERSE 0x150B -#define GL_COPY_INVERTED 0x150C -#define GL_OR_INVERTED 0x150D -#define GL_NAND 0x150E -#define GL_SET 0x150F -#define GL_EMISSION 0x1600 -#define GL_SHININESS 0x1601 -#define GL_AMBIENT_AND_DIFFUSE 0x1602 -#define GL_COLOR_INDEXES 0x1603 -#define GL_MODELVIEW 0x1700 -#define GL_PROJECTION 0x1701 -#define GL_TEXTURE 0x1702 -#define GL_COLOR 0x1800 -#define GL_DEPTH 0x1801 -#define GL_STENCIL 0x1802 -#define GL_COLOR_INDEX 0x1900 -#define GL_STENCIL_INDEX 0x1901 -#define GL_DEPTH_COMPONENT 0x1902 -#define GL_RED 0x1903 -#define GL_GREEN 0x1904 -#define GL_BLUE 0x1905 -#define GL_ALPHA 0x1906 -#define GL_RGB 0x1907 -#define GL_RGBA 0x1908 -#define GL_LUMINANCE 0x1909 -#define GL_LUMINANCE_ALPHA 0x190A -#define GL_BITMAP 0x1A00 -#define GL_POINT 0x1B00 -#define GL_LINE 0x1B01 -#define GL_FILL 0x1B02 -#define GL_RENDER 0x1C00 -#define GL_FEEDBACK 0x1C01 -#define GL_SELECT 0x1C02 -#define GL_FLAT 0x1D00 -#define GL_SMOOTH 0x1D01 -#define GL_KEEP 0x1E00 -#define GL_REPLACE 0x1E01 -#define GL_INCR 0x1E02 -#define GL_DECR 0x1E03 -#define GL_VENDOR 0x1F00 -#define GL_RENDERER 0x1F01 -#define GL_VERSION 0x1F02 -#define GL_EXTENSIONS 0x1F03 -#define GL_S 0x2000 -#define GL_T 0x2001 -#define GL_R 0x2002 -#define GL_Q 0x2003 -#define GL_MODULATE 0x2100 -#define GL_DECAL 0x2101 -#define GL_TEXTURE_ENV_MODE 0x2200 -#define GL_TEXTURE_ENV_COLOR 0x2201 -#define GL_TEXTURE_ENV 0x2300 -#define GL_EYE_LINEAR 0x2400 -#define GL_OBJECT_LINEAR 0x2401 -#define GL_SPHERE_MAP 0x2402 -#define GL_TEXTURE_GEN_MODE 0x2500 -#define GL_OBJECT_PLANE 0x2501 -#define GL_EYE_PLANE 0x2502 -#define GL_NEAREST 0x2600 -#define GL_LINEAR 0x2601 -#define GL_NEAREST_MIPMAP_NEAREST 0x2700 -#define GL_LINEAR_MIPMAP_NEAREST 0x2701 -#define GL_NEAREST_MIPMAP_LINEAR 0x2702 -#define GL_LINEAR_MIPMAP_LINEAR 0x2703 -#define GL_TEXTURE_MAG_FILTER 0x2800 -#define GL_TEXTURE_MIN_FILTER 0x2801 -#define GL_TEXTURE_WRAP_S 0x2802 -#define GL_TEXTURE_WRAP_T 0x2803 -#define GL_CLAMP 0x2900 -#define GL_REPEAT 0x2901 -#define GL_CLIP_PLANE0 0x3000 -#define GL_CLIP_PLANE1 0x3001 -#define GL_CLIP_PLANE2 0x3002 -#define GL_CLIP_PLANE3 0x3003 -#define GL_CLIP_PLANE4 0x3004 -#define GL_CLIP_PLANE5 0x3005 -#define GL_CURRENT_BIT 0x00000001 -#define GL_POINT_BIT 0x00000002 -#define GL_LINE_BIT 0x00000004 -#define GL_POLYGON_BIT 0x00000008 -#define GL_POLYGON_STIPPLE_BIT 0x00000010 -#define GL_PIXEL_MODE_BIT 0x00000020 -#define GL_LIGHTING_BIT 0x00000040 -#define GL_FOG_BIT 0x00000080 -#define GL_DEPTH_BUFFER_BIT 0x00000100 -#define GL_ACCUM_BUFFER_BIT 0x00000200 -#define GL_STENCIL_BUFFER_BIT 0x00000400 -#define GL_VIEWPORT_BIT 0x00000800 -#define GL_TRANSFORM_BIT 0x00001000 -#define GL_ENABLE_BIT 0x00002000 -#define GL_COLOR_BUFFER_BIT 0x00004000 -#define GL_HINT_BIT 0x00008000 -#define GL_EVAL_BIT 0x00010000 -#define GL_LIST_BIT 0x00020000 -#define GL_TEXTURE_BIT 0x00040000 -#define GL_SCISSOR_BIT 0x00080000 -#define GL_ALL_ATTRIB_BITS 0x000fffff -#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 -#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 -#define GL_CLIENT_ALL_ATTRIB_BITS 0xffffffff -#define GL_POLYGON_OFFSET_UNITS 0x2A00 -#define GL_POLYGON_OFFSET_POINT 0x2A01 -#define GL_POLYGON_OFFSET_LINE 0x2A02 -#define GL_POLYGON_OFFSET_FILL 0x8037 -#define GL_POLYGON_OFFSET_FACTOR 0x8038 -#define GL_ALPHA4 0x803B -#define GL_ALPHA8 0x803C -#define GL_ALPHA12 0x803D -#define GL_ALPHA16 0x803E -#define GL_LUMINANCE4 0x803F -#define GL_LUMINANCE8 0x8040 -#define GL_LUMINANCE12 0x8041 -#define GL_LUMINANCE16 0x8042 -#define GL_LUMINANCE4_ALPHA4 0x8043 -#define GL_LUMINANCE6_ALPHA2 0x8044 -#define GL_LUMINANCE8_ALPHA8 0x8045 -#define GL_LUMINANCE12_ALPHA4 0x8046 -#define GL_LUMINANCE12_ALPHA12 0x8047 -#define GL_LUMINANCE16_ALPHA16 0x8048 -#define GL_INTENSITY 0x8049 -#define GL_INTENSITY4 0x804A -#define GL_INTENSITY8 0x804B -#define GL_INTENSITY12 0x804C -#define GL_INTENSITY16 0x804D -#define GL_R3_G3_B2 0x2A10 -#define GL_RGB4 0x804F -#define GL_RGB5 0x8050 -#define GL_RGB8 0x8051 -#define GL_RGB10 0x8052 -#define GL_RGB12 0x8053 -#define GL_RGB16 0x8054 -#define GL_RGBA2 0x8055 -#define GL_RGBA4 0x8056 -#define GL_RGB5_A1 0x8057 -#define GL_RGBA8 0x8058 -#define GL_RGB10_A2 0x8059 -#define GL_RGBA12 0x805A -#define GL_RGBA16 0x805B -#define GL_TEXTURE_RED_SIZE 0x805C -#define GL_TEXTURE_GREEN_SIZE 0x805D -#define GL_TEXTURE_BLUE_SIZE 0x805E -#define GL_TEXTURE_ALPHA_SIZE 0x805F -#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 -#define GL_TEXTURE_INTENSITY_SIZE 0x8061 -#define GL_PROXY_TEXTURE_1D 0x8063 -#define GL_PROXY_TEXTURE_2D 0x8064 -#define GL_TEXTURE_PRIORITY 0x8066 -#define GL_TEXTURE_RESIDENT 0x8067 -#define GL_TEXTURE_BINDING_1D 0x8068 -#define GL_TEXTURE_BINDING_2D 0x8069 -#define GL_VERTEX_ARRAY 0x8074 -#define GL_NORMAL_ARRAY 0x8075 -#define GL_COLOR_ARRAY 0x8076 -#define GL_INDEX_ARRAY 0x8077 -#define GL_TEXTURE_COORD_ARRAY 0x8078 -#define GL_EDGE_FLAG_ARRAY 0x8079 -#define GL_VERTEX_ARRAY_SIZE 0x807A -#define GL_VERTEX_ARRAY_TYPE 0x807B -#define GL_VERTEX_ARRAY_STRIDE 0x807C -#define GL_NORMAL_ARRAY_TYPE 0x807E -#define GL_NORMAL_ARRAY_STRIDE 0x807F -#define GL_COLOR_ARRAY_SIZE 0x8081 -#define GL_COLOR_ARRAY_TYPE 0x8082 -#define GL_COLOR_ARRAY_STRIDE 0x8083 -#define GL_INDEX_ARRAY_TYPE 0x8085 -#define GL_INDEX_ARRAY_STRIDE 0x8086 -#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 -#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 -#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A -#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C -#define GL_VERTEX_ARRAY_POINTER 0x808E -#define GL_NORMAL_ARRAY_POINTER 0x808F -#define GL_COLOR_ARRAY_POINTER 0x8090 -#define GL_INDEX_ARRAY_POINTER 0x8091 -#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 -#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 -#define GL_V2F 0x2A20 -#define GL_V3F 0x2A21 -#define GL_C4UB_V2F 0x2A22 -#define GL_C4UB_V3F 0x2A23 -#define GL_C3F_V3F 0x2A24 -#define GL_N3F_V3F 0x2A25 -#define GL_C4F_N3F_V3F 0x2A26 -#define GL_T2F_V3F 0x2A27 -#define GL_T4F_V4F 0x2A28 -#define GL_T2F_C4UB_V3F 0x2A29 -#define GL_T2F_C3F_V3F 0x2A2A -#define GL_T2F_N3F_V3F 0x2A2B -#define GL_T2F_C4F_N3F_V3F 0x2A2C -#define GL_T4F_C4F_N3F_V4F 0x2A2D - -#define glAccum GlobalOpenGL().m_glAccum -#define glAlphaFunc GlobalOpenGL().m_glAlphaFunc -#define glAreTexturesResident GlobalOpenGL().m_glAreTexturesResident -#define glArrayElement GlobalOpenGL().m_glArrayElement -#define glBegin GlobalOpenGL().m_glBegin -#define glBindTexture GlobalOpenGL().m_glBindTexture -#define glBitmap GlobalOpenGL().m_glBitmap -#define glBlendFunc GlobalOpenGL().m_glBlendFunc -#define glCallList GlobalOpenGL().m_glCallList -#define glCallLists GlobalOpenGL().m_glCallLists -#define glClear GlobalOpenGL().m_glClear -#define glClearAccum GlobalOpenGL().m_glClearAccum -#define glClearColor GlobalOpenGL().m_glClearColor -#define glClearDepth GlobalOpenGL().m_glClearDepth -#define glClearIndex GlobalOpenGL().m_glClearIndex -#define glClearStencil GlobalOpenGL().m_glClearStencil -#define glClipPlane GlobalOpenGL().m_glClipPlane -#define glColor3b GlobalOpenGL().m_glColor3b -#define glColor3bv GlobalOpenGL().m_glColor3bv -#define glColor3d GlobalOpenGL().m_glColor3d -#define glColor3dv GlobalOpenGL().m_glColor3dv -#define glColor3f GlobalOpenGL().m_glColor3f -#define glColor3fv GlobalOpenGL().m_glColor3fv -#define glColor3i GlobalOpenGL().m_glColor3i -#define glColor3iv GlobalOpenGL().m_glColor3iv -#define glColor3s GlobalOpenGL().m_glColor3s -#define glColor3sv GlobalOpenGL().m_glColor3sv -#define glColor3ub GlobalOpenGL().m_glColor3ub -#define glColor3ubv GlobalOpenGL().m_glColor3ubv -#define glColor3ui GlobalOpenGL().m_glColor3ui -#define glColor3uiv GlobalOpenGL().m_glColor3uiv -#define glColor3us GlobalOpenGL().m_glColor3us -#define glColor3usv GlobalOpenGL().m_glColor3usv -#define glColor4b GlobalOpenGL().m_glColor4b -#define glColor4bv GlobalOpenGL().m_glColor4bv -#define glColor4d GlobalOpenGL().m_glColor4d -#define glColor4dv GlobalOpenGL().m_glColor4dv -#define glColor4f GlobalOpenGL().m_glColor4f -#define glColor4fv GlobalOpenGL().m_glColor4fv -#define glColor4i GlobalOpenGL().m_glColor4i -#define glColor4iv GlobalOpenGL().m_glColor4iv -#define glColor4s GlobalOpenGL().m_glColor4s -#define glColor4sv GlobalOpenGL().m_glColor4sv -#define glColor4ub GlobalOpenGL().m_glColor4ub -#define glColor4ubv GlobalOpenGL().m_glColor4ubv -#define glColor4ui GlobalOpenGL().m_glColor4ui -#define glColor4uiv GlobalOpenGL().m_glColor4uiv -#define glColor4us GlobalOpenGL().m_glColor4us -#define glColor4usv GlobalOpenGL().m_glColor4usv -#define glColorMask GlobalOpenGL().m_glColorMask -#define glColorMaterial GlobalOpenGL().m_glColorMaterial -#define glColorPointer GlobalOpenGL().m_glColorPointer -#define glCopyPixels GlobalOpenGL().m_glCopyPixels -#define glCopyTexImage1D GlobalOpenGL().m_glCopyTexImage1D -#define glCopyTexImage2D GlobalOpenGL().m_glCopyTexImage2D -#define glCopyTexSubImage1D GlobalOpenGL().m_glCopyTexSubImage1D -#define glCopyTexSubImage2D GlobalOpenGL().m_glCopyTexSubImage2D -#define glCullFace GlobalOpenGL().m_glCullFace -#define glDeleteLists GlobalOpenGL().m_glDeleteLists -#define glDeleteTextures GlobalOpenGL().m_glDeleteTextures -#define glDepthFunc GlobalOpenGL().m_glDepthFunc -#define glDepthMask GlobalOpenGL().m_glDepthMask -#define glDepthRange GlobalOpenGL().m_glDepthRange -#define glDisable GlobalOpenGL().m_glDisable -#define glDisableClientState GlobalOpenGL().m_glDisableClientState -#define glDrawArrays GlobalOpenGL().m_glDrawArrays -#define glDrawBuffer GlobalOpenGL().m_glDrawBuffer -#define glDrawElements GlobalOpenGL().m_glDrawElements -#define glDrawPixels GlobalOpenGL().m_glDrawPixels -#define glEdgeFlag GlobalOpenGL().m_glEdgeFlag -#define glEdgeFlagPointer GlobalOpenGL().m_glEdgeFlagPointer -#define glEdgeFlagv GlobalOpenGL().m_glEdgeFlagv -#define glEnable GlobalOpenGL().m_glEnable -#define glEnableClientState GlobalOpenGL().m_glEnableClientState -#define glEnd GlobalOpenGL().m_glEnd -#define glEndList GlobalOpenGL().m_glEndList -#define glEvalCoord1d GlobalOpenGL().m_glEvalCoord1d -#define glEvalCoord1dv GlobalOpenGL().m_glEvalCoord1dv -#define glEvalCoord1f GlobalOpenGL().m_glEvalCoord1f -#define glEvalCoord1fv GlobalOpenGL().m_glEvalCoord1fv -#define glEvalCoord2d GlobalOpenGL().m_glEvalCoord2d -#define glEvalCoord2dv GlobalOpenGL().m_glEvalCoord2dv -#define glEvalCoord2f GlobalOpenGL().m_glEvalCoord2f -#define glEvalCoord2fv GlobalOpenGL().m_glEvalCoord2fv -#define glEvalMesh1 GlobalOpenGL().m_glEvalMesh1 -#define glEvalMesh2 GlobalOpenGL().m_glEvalMesh2 -#define glEvalPoint1 GlobalOpenGL().m_glEvalPoint1 -#define glEvalPoint2 GlobalOpenGL().m_glEvalPoint2 -#define glFeedbackBuffer GlobalOpenGL().m_glFeedbackBuffer -#define glFinish GlobalOpenGL().m_glFinish -#define glFlush GlobalOpenGL().m_glFlush -#define glFogf GlobalOpenGL().m_glFogf -#define glFogfv GlobalOpenGL().m_glFogfv -#define glFogi GlobalOpenGL().m_glFogi -#define glFogiv GlobalOpenGL().m_glFogiv -#define glFrontFace GlobalOpenGL().m_glFrontFace -#define glFrustum GlobalOpenGL().m_glFrustum -#define glGenLists GlobalOpenGL().m_glGenLists -#define glGenTextures GlobalOpenGL().m_glGenTextures -#define glGetBooleanv GlobalOpenGL().m_glGetBooleanv -#define glGetClipPlane GlobalOpenGL().m_glGetClipPlane -#define glGetDoublev GlobalOpenGL().m_glGetDoublev -#define glGetError GlobalOpenGL().m_glGetError -#define glGetFloatv GlobalOpenGL().m_glGetFloatv -#define glGetIntegerv GlobalOpenGL().m_glGetIntegerv -#define glGetLightfv GlobalOpenGL().m_glGetLightfv -#define glGetLightiv GlobalOpenGL().m_glGetLightiv -#define glGetMapdv GlobalOpenGL().m_glGetMapdv -#define glGetMapfv GlobalOpenGL().m_glGetMapfv -#define glGetMapiv GlobalOpenGL().m_glGetMapiv -#define glGetMaterialfv GlobalOpenGL().m_glGetMaterialfv -#define glGetMaterialiv GlobalOpenGL().m_glGetMaterialiv -#define glGetPixelMapfv GlobalOpenGL().m_glGetPixelMapfv -#define glGetPixelMapuiv GlobalOpenGL().m_glGetPixelMapuiv -#define glGetPixelMapusv GlobalOpenGL().m_glGetPixelMapusv -#define glGetPointerv GlobalOpenGL().m_glGetPointerv -#define glGetPolygonStipple GlobalOpenGL().m_glGetPolygonStipple -#define glGetString GlobalOpenGL().m_glGetString -#define glGetTexEnvfv GlobalOpenGL().m_glGetTexEnvfv -#define glGetTexEnviv GlobalOpenGL().m_glGetTexEnviv -#define glGetTexGendv GlobalOpenGL().m_glGetTexGendv -#define glGetTexGenfv GlobalOpenGL().m_glGetTexGenfv -#define glGetTexGeniv GlobalOpenGL().m_glGetTexGeniv -#define glGetTexImage GlobalOpenGL().m_glGetTexImage -#define glGetTexLevelParameterfv GlobalOpenGL().m_glGetTexLevelParameter -#define glGetTexLevelParameteriv GlobalOpenGL().m_glGetTexLevelParameteriv -#define glGetTexParameterfv GlobalOpenGL().m_glGetTexParameterfv -#define glGetTexParameteriv GlobalOpenGL().m_glGetTexParameteriv -#define glHint GlobalOpenGL().m_glHint -#define glIndexMask GlobalOpenGL().m_glIndexMask -#define glIndexPointer GlobalOpenGL().m_glIndexPointer -#define glIndexd GlobalOpenGL().m_glIndexd -#define glIndexdv GlobalOpenGL().m_glIndexdv -#define glIndexf GlobalOpenGL().m_glIndexf -#define glIndexfv GlobalOpenGL().m_glIndexfv -#define glIndexi GlobalOpenGL().m_glIndexi -#define glIndexiv GlobalOpenGL().m_glIndexiv -#define glIndexs GlobalOpenGL().m_glIndexs -#define glIndexsv GlobalOpenGL().m_glIndexsv -#define glIndexub GlobalOpenGL().m_glIndexub -#define glIndexubv GlobalOpenGL().m_glIndexubv -#define glInitNames GlobalOpenGL().m_glInitNames -#define glInterleavedArrays GlobalOpenGL().m_glInterleavedArrays -#define glIsEnabled GlobalOpenGL().m_glIsEnabled -#define glIsList GlobalOpenGL().m_glIsList -#define glIsTexture GlobalOpenGL().m_glIsTexture -#define glLightModelf GlobalOpenGL().m_glLightModelf -#define glLightModelfv GlobalOpenGL().m_glLightModelfv -#define glLightModeli GlobalOpenGL().m_glLightModeli -#define glLightModeliv GlobalOpenGL().m_glLightModeliv -#define glLightf GlobalOpenGL().m_glLightf -#define glLightfv GlobalOpenGL().m_glLightfv -#define glLighti GlobalOpenGL().m_glLighti -#define glLightiv GlobalOpenGL().m_glLightiv -#define glLineStipple GlobalOpenGL().m_glLineStipple -#define glLineWidth GlobalOpenGL().m_glLineWidth -#define glListBase GlobalOpenGL().m_glListBase -#define glLoadIdentity GlobalOpenGL().m_glLoadIdentity -#define glLoadMatrixd GlobalOpenGL().m_glLoadMatrixd -#define glLoadMatrixf GlobalOpenGL().m_glLoadMatrixf -#define glLoadName GlobalOpenGL().m_glLoadName -#define glLogicOp GlobalOpenGL().m_glLogicOp -#define glMap1d GlobalOpenGL().m_glMap1d -#define glMap1f GlobalOpenGL().m_glMap1f -#define glMap2d GlobalOpenGL().m_glMap2d -#define glMap2f GlobalOpenGL().m_glMap2f -#define glMapGrid1d GlobalOpenGL().m_glMapGrid1d -#define glMapGrid1f GlobalOpenGL().m_glMapGrid1f -#define glMapGrid2d GlobalOpenGL().m_glMapGrid2d -#define glMapGrid2f GlobalOpenGL().m_glMapGrid2f -#define glMaterialf GlobalOpenGL().m_glMaterialf -#define glMaterialfv GlobalOpenGL().m_glMaterialfv -#define glMateriali GlobalOpenGL().m_glMateriali -#define glMaterialiv GlobalOpenGL().m_glMaterialiv -#define glMatrixMode GlobalOpenGL().m_glMatrixMode -#define glMultMatrixd GlobalOpenGL().m_glMultMatrixd -#define glMultMatrixf GlobalOpenGL().m_glMultMatrixf -#define glNewList GlobalOpenGL().m_glNewList -#define glNormal3b GlobalOpenGL().m_glNormal3b -#define glNormal3bv GlobalOpenGL().m_glNormal3bv -#define glNormal3d GlobalOpenGL().m_glNormal3d -#define glNormal3dv GlobalOpenGL().m_glNormal3dv -#define glNormal3f GlobalOpenGL().m_glNormal3f -#define glNormal3fv GlobalOpenGL().m_glNormal3fv -#define glNormal3i GlobalOpenGL().m_glNormal3i -#define glNormal3iv GlobalOpenGL().m_glNormal3iv -#define glNormal3s GlobalOpenGL().m_glNormal3s -#define glNormal3sv GlobalOpenGL().m_glNormal3sv -#define glNormalPointer GlobalOpenGL().m_glNormalPointer -#define glOrtho GlobalOpenGL().m_glOrtho -#define glPassThrough GlobalOpenGL().m_glPassThrough -#define glPixelMapfv GlobalOpenGL().m_glPixelMapfv -#define glPixelMapuiv GlobalOpenGL().m_glPixelMapuiv -#define glPixelMapusv GlobalOpenGL().m_glPixelMapusv -#define glPixelStoref GlobalOpenGL().m_glPixelStoref -#define glPixelStorei GlobalOpenGL().m_glPixelStorei -#define glPixelTransferf GlobalOpenGL().m_glPixelTransferf -#define glPixelTransferi GlobalOpenGL().m_glPixelTransferi -#define glPixelZoom GlobalOpenGL().m_glPixelZoom -#define glPointSize GlobalOpenGL().m_glPointSize -#define glPolygonMode GlobalOpenGL().m_glPolygonMode -#define glPolygonOffset GlobalOpenGL().m_glPolygonOffset -#define glPolygonStipple GlobalOpenGL().m_glPolygonStipple -#define glPopAttrib GlobalOpenGL().m_glPopAttrib -#define glPopClientAttrib GlobalOpenGL().m_glPopClientAttrib -#define glPopMatrix GlobalOpenGL().m_glPopMatrix -#define glPopName GlobalOpenGL().m_glPopName -#define glPrioritizeTextures GlobalOpenGL().m_glPrioritizeTextures -#define glPushAttrib GlobalOpenGL().m_glPushAttrib -#define glPushClientAttrib GlobalOpenGL().m_glPushClientAttrib -#define glPushMatrix GlobalOpenGL().m_glPushMatrix -#define glPushName GlobalOpenGL().m_glPushName -#define glRasterPos2d GlobalOpenGL().m_glRasterPos2d -#define glRasterPos2dv GlobalOpenGL().m_glRasterPos2dv -#define glRasterPos2f GlobalOpenGL().m_glRasterPos2f -#define glRasterPos2fv GlobalOpenGL().m_glRasterPos2fv -#define glRasterPos2i GlobalOpenGL().m_glRasterPos2i -#define glRasterPos2iv GlobalOpenGL().m_glRasterPos2iv -#define glRasterPos2s GlobalOpenGL().m_glRasterPos2s -#define glRasterPos2sv GlobalOpenGL().m_glRasterPos2sv -#define glRasterPos3d GlobalOpenGL().m_glRasterPos3d -#define glRasterPos3dv GlobalOpenGL().m_glRasterPos3dv -#define glRasterPos3f GlobalOpenGL().m_glRasterPos3f -#define glRasterPos3fv GlobalOpenGL().m_glRasterPos3fv -#define glRasterPos3i GlobalOpenGL().m_glRasterPos3i -#define glRasterPos3iv GlobalOpenGL().m_glRasterPos3iv -#define glRasterPos3s GlobalOpenGL().m_glRasterPos3s -#define glRasterPos3sv GlobalOpenGL().m_glRasterPos3sv -#define glRasterPos4d GlobalOpenGL().m_glRasterPos4d -#define glRasterPos4dv GlobalOpenGL().m_glRasterPos4dv -#define glRasterPos4f GlobalOpenGL().m_glRasterPos4f -#define glRasterPos4fv GlobalOpenGL().m_glRasterPos4fv -#define glRasterPos4i GlobalOpenGL().m_glRasterPos4i -#define glRasterPos4iv GlobalOpenGL().m_glRasterPos4iv -#define glRasterPos4s GlobalOpenGL().m_glRasterPos4s -#define glRasterPos4sv GlobalOpenGL().m_glRasterPos4sv -#define glReadBuffer GlobalOpenGL().m_glReadBuffer -#define glReadPixels GlobalOpenGL().m_glReadPixels -#define glRectd GlobalOpenGL().m_glRectd -#define glRectdv GlobalOpenGL().m_glRectdv -#define glRectf GlobalOpenGL().m_glRectf -#define glRectfv GlobalOpenGL().m_glRectfv -#define glRecti GlobalOpenGL().m_glRecti -#define glRectiv GlobalOpenGL().m_glRectiv -#define glRects GlobalOpenGL().m_glRects -#define glRectsv GlobalOpenGL().m_glRectsv -#define glRenderMode GlobalOpenGL().m_glRenderMode -#define glRotated GlobalOpenGL().m_glRotated -#define glRotatef GlobalOpenGL().m_glRotatef -#define glScaled GlobalOpenGL().m_glScaled -#define glScalef GlobalOpenGL().m_glScalef -#define glScissor GlobalOpenGL().m_glScissor -#define glSelectBuffer GlobalOpenGL().m_glSelectBuffer -#define glShadeModel GlobalOpenGL().m_glShadeModel -#define glStencilFunc GlobalOpenGL().m_glStencilFunc -#define glStencilMask GlobalOpenGL().m_glStencilMask -#define glStencilOp GlobalOpenGL().m_glStencilOp -#define glTexCoord1d GlobalOpenGL().m_glTexCoord1d -#define glTexCoord1dv GlobalOpenGL().m_glTexCoord1dv -#define glTexCoord1f GlobalOpenGL().m_glTexCoord1f -#define glTexCoord1fv GlobalOpenGL().m_glTexCoord1fv -#define glTexCoord1i GlobalOpenGL().m_glTexCoord1i -#define glTexCoord1iv GlobalOpenGL().m_glTexCoord1iv -#define glTexCoord1s GlobalOpenGL().m_glTexCoord1s -#define glTexCoord1sv GlobalOpenGL().m_glTexCoord1sv -#define glTexCoord2d GlobalOpenGL().m_glTexCoord2d -#define glTexCoord2dv GlobalOpenGL().m_glTexCoord2dv -#define glTexCoord2f GlobalOpenGL().m_glTexCoord2f -#define glTexCoord2fv GlobalOpenGL().m_glTexCoord2fv -#define glTexCoord2i GlobalOpenGL().m_glTexCoord2i -#define glTexCoord2iv GlobalOpenGL().m_glTexCoord2iv -#define glTexCoord2s GlobalOpenGL().m_glTexCoord2s -#define glTexCoord2sv GlobalOpenGL().m_glTexCoord2sv -#define glTexCoord3d GlobalOpenGL().m_glTexCoord3d -#define glTexCoord3dv GlobalOpenGL().m_glTexCoord3dv -#define glTexCoord3f GlobalOpenGL().m_glTexCoord3f -#define glTexCoord3fv GlobalOpenGL().m_glTexCoord3fv -#define glTexCoord3i GlobalOpenGL().m_glTexCoord3i -#define glTexCoord3iv GlobalOpenGL().m_glTexCoord3iv -#define glTexCoord3s GlobalOpenGL().m_glTexCoord3s -#define glTexCoord3sv GlobalOpenGL().m_glTexCoord3sv -#define glTexCoord4d GlobalOpenGL().m_glTexCoord4d -#define glTexCoord4dv GlobalOpenGL().m_glTexCoord4dv -#define glTexCoord4f GlobalOpenGL().m_glTexCoord4f -#define glTexCoord4fv GlobalOpenGL().m_glTexCoord4fv -#define glTexCoord4i GlobalOpenGL().m_glTexCoord4i -#define glTexCoord4iv GlobalOpenGL().m_glTexCoord4iv -#define glTexCoord4s GlobalOpenGL().m_glTexCoord4s -#define glTexCoord4sv GlobalOpenGL().m_glTexCoord4sv -#define glTexCoordPointer GlobalOpenGL().m_glTexCoordPointer -#define glTexEnvf GlobalOpenGL().m_glTexEnvf -#define glTexEnvfv GlobalOpenGL().m_glTexEnvfv -#define glTexEnvi GlobalOpenGL().m_glTexEnvi -#define glTexEnviv GlobalOpenGL().m_glTexEnviv -#define glTexGend GlobalOpenGL().m_glTexGend -#define glTexGendv GlobalOpenGL().m_glTexGendv -#define glTexGenf GlobalOpenGL().m_glTexGenf -#define glTexGenfv GlobalOpenGL().m_glTexGenfv -#define glTexGeni GlobalOpenGL().m_glTexGeni -#define glTexGeniv GlobalOpenGL().m_glTexGeniv -#define glTexImage1D GlobalOpenGL().m_glTexImage1D -#define glTexImage2D GlobalOpenGL().m_glTexImage2D -#define glTexParameterf GlobalOpenGL().m_glTexParameterf -#define glTexParameterfv GlobalOpenGL().m_glTexParameterfv -#define glTexParameteri GlobalOpenGL().m_glTexParameteri -#define glTexParameteriv GlobalOpenGL().m_glTexParameteriv -#define glTexSubImage1D GlobalOpenGL().m_glTexSubImage1D -#define glTexSubImage2D GlobalOpenGL().m_glTexSubImage2D -#define glTranslated GlobalOpenGL().m_glTranslated -#define glTranslatef GlobalOpenGL().m_glTranslatef -#define glVertex2d GlobalOpenGL().m_glVertex2d -#define glVertex2dv GlobalOpenGL().m_glVertex2dv -#define glVertex2f GlobalOpenGL().m_glVertex2f -#define glVertex2fv GlobalOpenGL().m_glVertex2fv -#define glVertex2i GlobalOpenGL().m_glVertex2i -#define glVertex2iv GlobalOpenGL().m_glVertex2iv -#define glVertex2s GlobalOpenGL().m_glVertex2s -#define glVertex2sv GlobalOpenGL().m_glVertex2sv -#define glVertex3d GlobalOpenGL().m_glVertex3d -#define glVertex3dv GlobalOpenGL().m_glVertex3dv -#define glVertex3f GlobalOpenGL().m_glVertex3f -#define glVertex3fv GlobalOpenGL().m_glVertex3fv -#define glVertex3i GlobalOpenGL().m_glVertex3i -#define glVertex3iv GlobalOpenGL().m_glVertex3iv -#define glVertex3s GlobalOpenGL().m_glVertex3s -#define glVertex3sv GlobalOpenGL().m_glVertex3sv -#define glVertex4d GlobalOpenGL().m_glVertex4d -#define glVertex4dv GlobalOpenGL().m_glVertex4dv -#define glVertex4f GlobalOpenGL().m_glVertex4f -#define glVertex4fv GlobalOpenGL().m_glVertex4fv -#define glVertex4i GlobalOpenGL().m_glVertex4i -#define glVertex4iv GlobalOpenGL().m_glVertex4iv -#define glVertex4s GlobalOpenGL().m_glVertex4s -#define glVertex4sv GlobalOpenGL().m_glVertex4sv -#define glVertexPointer GlobalOpenGL().m_glVertexPointer -#define glViewport GlobalOpenGL().m_glViewport - -#endif - - -#if !defined(GL_EXT_vertex_array) -#define GL_EXT_vertex_array 1 - -#define GL_VERTEX_ARRAY_EXT 0x8074 -#define GL_NORMAL_ARRAY_EXT 0x8075 -#define GL_COLOR_ARRAY_EXT 0x8076 -#define GL_INDEX_ARRAY_EXT 0x8077 -#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078 -#define GL_EDGE_FLAG_ARRAY_EXT 0x8079 -#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A -#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B -#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C -#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D -#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E -#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F -#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080 -#define GL_COLOR_ARRAY_SIZE_EXT 0x8081 -#define GL_COLOR_ARRAY_TYPE_EXT 0x8082 -#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083 -#define GL_COLOR_ARRAY_COUNT_EXT 0x8084 -#define GL_INDEX_ARRAY_TYPE_EXT 0x8085 -#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086 -#define GL_INDEX_ARRAY_COUNT_EXT 0x8087 -#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088 -#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089 -#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A -#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B -#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C -#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D -#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E -#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F -#define GL_COLOR_ARRAY_POINTER_EXT 0x8090 -#define GL_INDEX_ARRAY_POINTER_EXT 0x8091 -#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092 -#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093 -#define GL_DOUBLE_EXT GL_DOUBLE - -#endif - - -#if !defined(GL_EXT_bgra) -#define GL_EXT_bgra 1 - -#define GL_BGR_EXT 0x80E0 -#define GL_BGRA_EXT 0x80E1 - -#endif - - -#if !defined(GL_EXT_paletted_texture) -#define GL_EXT_paletted_texture 1 - -#define GL_COLOR_TABLE_FORMAT_EXT 0x80D8 -#define GL_COLOR_TABLE_WIDTH_EXT 0x80D9 -#define GL_COLOR_TABLE_RED_SIZE_EXT 0x80DA -#define GL_COLOR_TABLE_GREEN_SIZE_EXT 0x80DB -#define GL_COLOR_TABLE_BLUE_SIZE_EXT 0x80DC -#define GL_COLOR_TABLE_ALPHA_SIZE_EXT 0x80DD -#define GL_COLOR_TABLE_LUMINANCE_SIZE_EXT 0x80DE -#define GL_COLOR_TABLE_INTENSITY_SIZE_EXT 0x80DF - -#define GL_COLOR_INDEX1_EXT 0x80E2 -#define GL_COLOR_INDEX2_EXT 0x80E3 -#define GL_COLOR_INDEX4_EXT 0x80E4 -#define GL_COLOR_INDEX8_EXT 0x80E5 -#define GL_COLOR_INDEX12_EXT 0x80E6 -#define GL_COLOR_INDEX16_EXT 0x80E7 - -#define GL_LOGIC_OP GL_INDEX_LOGIC_OP -#define GL_TEXTURE_COMPONENTS GL_TEXTURE_INTERNAL_FORMAT - -#endif - -#if !defined(GL_ARB_multitexture) -#define GL_ARB_multitexture 1 - -#define GL_TEXTURE0_ARB 0x84C0 -#define GL_TEXTURE1_ARB 0x84C1 -#define GL_TEXTURE2_ARB 0x84C2 -#define GL_TEXTURE3_ARB 0x84C3 -#define GL_TEXTURE4_ARB 0x84C4 -#define GL_TEXTURE5_ARB 0x84C5 -#define GL_TEXTURE6_ARB 0x84C6 -#define GL_TEXTURE7_ARB 0x84C7 -#define GL_TEXTURE8_ARB 0x84C8 -#define GL_TEXTURE9_ARB 0x84C9 -#define GL_TEXTURE10_ARB 0x84CA -#define GL_TEXTURE11_ARB 0x84CB -#define GL_TEXTURE12_ARB 0x84CC -#define GL_TEXTURE13_ARB 0x84CD -#define GL_TEXTURE14_ARB 0x84CE -#define GL_TEXTURE15_ARB 0x84CF -#define GL_TEXTURE16_ARB 0x84D0 -#define GL_TEXTURE17_ARB 0x84D1 -#define GL_TEXTURE18_ARB 0x84D2 -#define GL_TEXTURE19_ARB 0x84D3 -#define GL_TEXTURE20_ARB 0x84D4 -#define GL_TEXTURE21_ARB 0x84D5 -#define GL_TEXTURE22_ARB 0x84D6 -#define GL_TEXTURE23_ARB 0x84D7 -#define GL_TEXTURE24_ARB 0x84D8 -#define GL_TEXTURE25_ARB 0x84D9 -#define GL_TEXTURE26_ARB 0x84DA -#define GL_TEXTURE27_ARB 0x84DB -#define GL_TEXTURE28_ARB 0x84DC -#define GL_TEXTURE29_ARB 0x84DD -#define GL_TEXTURE30_ARB 0x84DE -#define GL_TEXTURE31_ARB 0x84DF -#define GL_ACTIVE_TEXTURE_ARB 0x84E0 -#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 -#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 - -#define glActiveTextureARB GlobalOpenGL().m_glActiveTextureARB -#define glClientActiveTextureARB GlobalOpenGL().m_glClientActiveTextureARB -#define glMultiTexCoord1dARB GlobalOpenGL().m_glMultiTexCoord1dARB -#define glMultiTexCoord1dvARB GlobalOpenGL().m_glMultiTexCoord1dvARB -#define glMultiTexCoord1fARB GlobalOpenGL().m_glMultiTexCoord1fARB -#define glMultiTexCoord1fvARB GlobalOpenGL().m_glMultiTexCoord1fvARB -#define glMultiTexCoord1iARB GlobalOpenGL().m_glMultiTexCoord1iARB -#define glMultiTexCoord1ivARB GlobalOpenGL().m_glMultiTexCoord1ivARB -#define glMultiTexCoord1sARB GlobalOpenGL().m_glMultiTexCoord1sARB -#define glMultiTexCoord1svARB GlobalOpenGL().m_glMultiTexCoord1svARB -#define glMultiTexCoord2dARB GlobalOpenGL().m_glMultiTexCoord2dARB -#define glMultiTexCoord2dvARB GlobalOpenGL().m_glMultiTexCoord2dvARB -#define glMultiTexCoord2fARB GlobalOpenGL().m_glMultiTexCoord2fARB -#define glMultiTexCoord2fvARB GlobalOpenGL().m_glMultiTexCoord2fvARB -#define glMultiTexCoord2iARB GlobalOpenGL().m_glMultiTexCoord2iARB -#define glMultiTexCoord2ivARB GlobalOpenGL().m_glMultiTexCoord2ivARB -#define glMultiTexCoord2sARB GlobalOpenGL().m_glMultiTexCoord2sARB -#define glMultiTexCoord2svARB GlobalOpenGL().m_glMultiTexCoord2svARB -#define glMultiTexCoord3dARB GlobalOpenGL().m_glMultiTexCoord3dARB -#define glMultiTexCoord3dvARB GlobalOpenGL().m_glMultiTexCoord3dvARB -#define glMultiTexCoord3fARB GlobalOpenGL().m_glMultiTexCoord3fARB -#define glMultiTexCoord3fvARB GlobalOpenGL().m_glMultiTexCoord3fvARB -#define glMultiTexCoord3iARB GlobalOpenGL().m_glMultiTexCoord3iARB -#define glMultiTexCoord3ivARB GlobalOpenGL().m_glMultiTexCoord3ivARB -#define glMultiTexCoord3sARB GlobalOpenGL().m_glMultiTexCoord3sARB -#define glMultiTexCoord3svARB GlobalOpenGL().m_glMultiTexCoord3svARB -#define glMultiTexCoord4dARB GlobalOpenGL().m_glMultiTexCoord4dARB -#define glMultiTexCoord4dvARB GlobalOpenGL().m_glMultiTexCoord4dvARB -#define glMultiTexCoord4fARB GlobalOpenGL().m_glMultiTexCoord4fARB -#define glMultiTexCoord4fvARB GlobalOpenGL().m_glMultiTexCoord4fvARB -#define glMultiTexCoord4iARB GlobalOpenGL().m_glMultiTexCoord4iARB -#define glMultiTexCoord4ivARB GlobalOpenGL().m_glMultiTexCoord4ivARB -#define glMultiTexCoord4sARB GlobalOpenGL().m_glMultiTexCoord4sARB -#define glMultiTexCoord4svARB GlobalOpenGL().m_glMultiTexCoord4svARB - -#endif - - -// EXT_texture_compression_s3tc -#if !defined(GL_EXT_texture_compression_s3tc) -#define GL_EXT_texture_compression_s3tc 1 - -#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 - -#endif - - -// ARB_texture_compression -#if !defined(GL_ARB_texture_compression) -#define GL_ARB_texture_compression 1 - -#define GL_COMPRESSED_ALPHA_ARB 0x84E9 -#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA -#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB -#define GL_COMPRESSED_INTENSITY_ARB 0x84EC -#define GL_COMPRESSED_RGB_ARB 0x84ED -#define GL_COMPRESSED_RGBA_ARB 0x84EE -#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF -#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 -#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 - -#define glCompressedTexImage3DARB GlobalOpenGL().m_glCompressedTexImage3DARB -#define glCompressedTexImage2DARB GlobalOpenGL().m_glCompressedTexImage2DARB -#define glCompressedTexImage1DARB GlobalOpenGL().m_glCompressedTexImage1DARB -#define glCompressedTexSubImage3DARB GlobalOpenGL().m_glCompressedTexSubImage3DARB -#define glCompressedTexSubImage2DARB GlobalOpenGL().m_glCompressedTexSubImage2DARB -#define glCompressedTexSubImage1DARB GlobalOpenGL().m_glCompressedTexSubImage1DARB -#define glGetCompressedTexImageARB GlobalOpenGL().m_glGetCompressedTexImageARB - -#endif - - -// GL 1.2 - -#if !defined(GL_VERSION_1_2) - -#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 -#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 -#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 -#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 -#define GL_UNSIGNED_BYTE_3_3_2 0x8032 -#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 -#define GL_UNSIGNED_INT_8_8_8_8 0x8035 -#define GL_UNSIGNED_INT_10_10_10_2 0x8036 -#define GL_RESCALE_NORMAL 0x803A -#define GL_TEXTURE_BINDING_3D 0x806A -#define GL_PACK_SKIP_IMAGES 0x806B -#define GL_PACK_IMAGE_HEIGHT 0x806C -#define GL_UNPACK_SKIP_IMAGES 0x806D -#define GL_UNPACK_IMAGE_HEIGHT 0x806E -#define GL_TEXTURE_3D 0x806F -#define GL_PROXY_TEXTURE_3D 0x8070 -#define GL_TEXTURE_DEPTH 0x8071 -#define GL_TEXTURE_WRAP_R 0x8072 -#define GL_MAX_3D_TEXTURE_SIZE 0x8073 -#define GL_BGR 0x80E0 -#define GL_BGRA 0x80E1 -#define GL_MAX_ELEMENTS_VERTICES 0x80E8 -#define GL_MAX_ELEMENTS_INDICES 0x80E9 -#define GL_CLAMP_TO_EDGE 0x812F -#define GL_TEXTURE_MIN_LOD 0x813A -#define GL_TEXTURE_MAX_LOD 0x813B -#define GL_TEXTURE_BASE_LEVEL 0x813C -#define GL_TEXTURE_MAX_LEVEL 0x813D -#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 -#define GL_SINGLE_COLOR 0x81F9 -#define GL_SEPARATE_SPECULAR_COLOR 0x81FA -#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 -#define GL_UNSIGNED_SHORT_5_6_5 0x8363 -#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 -#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 -#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 -#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 -#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 -#define GL_ALIASED_POINT_SIZE_RANGE 0x846D -#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E - -#define glCopyTexSubImage3D GlobalOpenGL().m_glCopyTexSubImage3D -#define glDrawRangeElements GlobalOpenGL().m_glDrawRangeElements -#define glTexImage3D GlobalOpenGL().m_glTexImage3D -#define glTexSubImage3D GlobalOpenGL().m_glTexSubImage3D - -#endif - - -// GL 1.3 - -#if !defined(GL_VERSION_1_3) -#define GL_VERSION_1_3 1 - -#define GL_MULTISAMPLE 0x809D -#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E -#define GL_SAMPLE_ALPHA_TO_ONE 0x809F -#define GL_SAMPLE_COVERAGE 0x80A0 -#define GL_SAMPLE_BUFFERS 0x80A8 -#define GL_SAMPLES 0x80A9 -#define GL_SAMPLE_COVERAGE_VALUE 0x80AA -#define GL_SAMPLE_COVERAGE_INVERT 0x80AB -#define GL_CLAMP_TO_BORDER 0x812D -#define GL_TEXTURE0 0x84C0 -#define GL_TEXTURE1 0x84C1 -#define GL_TEXTURE2 0x84C2 -#define GL_TEXTURE3 0x84C3 -#define GL_TEXTURE4 0x84C4 -#define GL_TEXTURE5 0x84C5 -#define GL_TEXTURE6 0x84C6 -#define GL_TEXTURE7 0x84C7 -#define GL_TEXTURE8 0x84C8 -#define GL_TEXTURE9 0x84C9 -#define GL_TEXTURE10 0x84CA -#define GL_TEXTURE11 0x84CB -#define GL_TEXTURE12 0x84CC -#define GL_TEXTURE13 0x84CD -#define GL_TEXTURE14 0x84CE -#define GL_TEXTURE15 0x84CF -#define GL_TEXTURE16 0x84D0 -#define GL_TEXTURE17 0x84D1 -#define GL_TEXTURE18 0x84D2 -#define GL_TEXTURE19 0x84D3 -#define GL_TEXTURE20 0x84D4 -#define GL_TEXTURE21 0x84D5 -#define GL_TEXTURE22 0x84D6 -#define GL_TEXTURE23 0x84D7 -#define GL_TEXTURE24 0x84D8 -#define GL_TEXTURE25 0x84D9 -#define GL_TEXTURE26 0x84DA -#define GL_TEXTURE27 0x84DB -#define GL_TEXTURE28 0x84DC -#define GL_TEXTURE29 0x84DD -#define GL_TEXTURE30 0x84DE -#define GL_TEXTURE31 0x84DF -#define GL_ACTIVE_TEXTURE 0x84E0 -#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 -#define GL_MAX_TEXTURE_UNITS 0x84E2 -#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 -#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 -#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 -#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 -#define GL_SUBTRACT 0x84E7 -#define GL_COMPRESSED_ALPHA 0x84E9 -#define GL_COMPRESSED_LUMINANCE 0x84EA -#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB -#define GL_COMPRESSED_INTENSITY 0x84EC -#define GL_COMPRESSED_RGB 0x84ED -#define GL_COMPRESSED_RGBA 0x84EE -#define GL_TEXTURE_COMPRESSION_HINT 0x84EF -#define GL_NORMAL_MAP 0x8511 -#define GL_REFLECTION_MAP 0x8512 -#define GL_TEXTURE_CUBE_MAP 0x8513 -#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 -#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 -#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A -#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B -#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C -#define GL_COMBINE 0x8570 -#define GL_COMBINE_RGB 0x8571 -#define GL_COMBINE_ALPHA 0x8572 -#define GL_RGB_SCALE 0x8573 -#define GL_ADD_SIGNED 0x8574 -#define GL_INTERPOLATE 0x8575 -#define GL_CONSTANT 0x8576 -#define GL_PRIMARY_COLOR 0x8577 -#define GL_PREVIOUS 0x8578 -#define GL_SOURCE0_RGB 0x8580 -#define GL_SOURCE1_RGB 0x8581 -#define GL_SOURCE2_RGB 0x8582 -#define GL_SOURCE0_ALPHA 0x8588 -#define GL_SOURCE1_ALPHA 0x8589 -#define GL_SOURCE2_ALPHA 0x858A -#define GL_OPERAND0_RGB 0x8590 -#define GL_OPERAND1_RGB 0x8591 -#define GL_OPERAND2_RGB 0x8592 -#define GL_OPERAND0_ALPHA 0x8598 -#define GL_OPERAND1_ALPHA 0x8599 -#define GL_OPERAND2_ALPHA 0x859A -#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 -#define GL_TEXTURE_COMPRESSED 0x86A1 -#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 -#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 -#define GL_DOT3_RGB 0x86AE -#define GL_DOT3_RGBA 0x86AF -#define GL_MULTISAMPLE_BIT 0x20000000 - -#define glActiveTexture GlobalOpenGL().m_glActiveTexture -#define glClientActiveTexture GlobalOpenGL().m_glClientActiveTexture -#define glCompressedTexImage1D GlobalOpenGL().m_glCompressedTexImage1D -#define glCompressedTexImage2D GlobalOpenGL().m_glCompressedTexImage2D -#define glCompressedTexImage3D GlobalOpenGL().m_glCompressedTexImage3D -#define glCompressedTexSubImage1D GlobalOpenGL().m_glCompressedTexSubImage1D -#define glCompressedTexSubImage2D GlobalOpenGL().m_glCompressedTexSubImage2D -#define glCompressedTexSubImage3D GlobalOpenGL().m_glCompressedTexSubImage3D -#define glGetCompressedTexImage GlobalOpenGL().m_glGetCompressedTexImage -#define glLoadTransposeMatrixd GlobalOpenGL().m_glLoadTransposeMatrixd -#define glLoadTransposeMatrixf GlobalOpenGL().m_glLoadTransposeMatrixf -#define glMultTransposeMatrixd GlobalOpenGL().m_glMultTransposeMatrixd -#define glMultTransposeMatrixf GlobalOpenGL().m_glMultTransposeMatrixf -#define glMultiTexCoord1d GlobalOpenGL().m_glMultiTexCoord1d -#define glMultiTexCoord1dv GlobalOpenGL().m_glMultiTexCoord1dv -#define glMultiTexCoord1f GlobalOpenGL().m_glMultiTexCoord1f -#define glMultiTexCoord1fv GlobalOpenGL().m_glMultiTexCoord1fv -#define glMultiTexCoord1i GlobalOpenGL().m_glMultiTexCoord1i -#define glMultiTexCoord1iv GlobalOpenGL().m_glMultiTexCoord1iv -#define glMultiTexCoord1s GlobalOpenGL().m_glMultiTexCoord1s -#define glMultiTexCoord1sv GlobalOpenGL().m_glMultiTexCoord1sv -#define glMultiTexCoord2d GlobalOpenGL().m_glMultiTexCoord2d -#define glMultiTexCoord2dv GlobalOpenGL().m_glMultiTexCoord2dv -#define glMultiTexCoord2f GlobalOpenGL().m_glMultiTexCoord2f -#define glMultiTexCoord2fv GlobalOpenGL().m_glMultiTexCoord2fv -#define glMultiTexCoord2i GlobalOpenGL().m_glMultiTexCoord2i -#define glMultiTexCoord2iv GlobalOpenGL().m_glMultiTexCoord2iv -#define glMultiTexCoord2s GlobalOpenGL().m_glMultiTexCoord2s -#define glMultiTexCoord2sv GlobalOpenGL().m_glMultiTexCoord2sv -#define glMultiTexCoord3d GlobalOpenGL().m_glMultiTexCoord3d -#define glMultiTexCoord3dv GlobalOpenGL().m_glMultiTexCoord3dv -#define glMultiTexCoord3f GlobalOpenGL().m_glMultiTexCoord3f -#define glMultiTexCoord3fv GlobalOpenGL().m_glMultiTexCoord3fv -#define glMultiTexCoord3i GlobalOpenGL().m_glMultiTexCoord3i -#define glMultiTexCoord3iv GlobalOpenGL().m_glMultiTexCoord3iv -#define glMultiTexCoord3s GlobalOpenGL().m_glMultiTexCoord3s -#define glMultiTexCoord3sv GlobalOpenGL().m_glMultiTexCoord3sv -#define glMultiTexCoord4d GlobalOpenGL().m_glMultiTexCoord4d -#define glMultiTexCoord4dv GlobalOpenGL().m_glMultiTexCoord4dv -#define glMultiTexCoord4f GlobalOpenGL().m_glMultiTexCoord4f -#define glMultiTexCoord4fv GlobalOpenGL().m_glMultiTexCoord4fv -#define glMultiTexCoord4i GlobalOpenGL().m_glMultiTexCoord4i -#define glMultiTexCoord4iv GlobalOpenGL().m_glMultiTexCoord4iv -#define glMultiTexCoord4s GlobalOpenGL().m_glMultiTexCoord4s -#define glMultiTexCoord4sv GlobalOpenGL().m_glMultiTexCoord4sv -#define glSampleCoverage GlobalOpenGL().m_glSampleCoverage - -#endif - - -// GL 1.4 -#if !defined(GL_VERSION_1_4) -#define GL_VERSION_1_4 1 - -#define GL_BLEND_DST_RGB 0x80C8 -#define GL_BLEND_SRC_RGB 0x80C9 -#define GL_BLEND_DST_ALPHA 0x80CA -#define GL_BLEND_SRC_ALPHA 0x80CB -#define GL_POINT_SIZE_MIN 0x8126 -#define GL_POINT_SIZE_MAX 0x8127 -#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 -#define GL_POINT_DISTANCE_ATTENUATION 0x8129 -#define GL_GENERATE_MIPMAP 0x8191 -#define GL_GENERATE_MIPMAP_HINT 0x8192 -#define GL_DEPTH_COMPONENT16 0x81A5 -#define GL_DEPTH_COMPONENT24 0x81A6 -#define GL_DEPTH_COMPONENT32 0x81A7 -#define GL_MIRRORED_REPEAT 0x8370 -#define GL_FOG_COORDINATE_SOURCE 0x8450 -#define GL_FOG_COORDINATE 0x8451 -#define GL_FRAGMENT_DEPTH 0x8452 -#define GL_CURRENT_FOG_COORDINATE 0x8453 -#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 -#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 -#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 -#define GL_FOG_COORDINATE_ARRAY 0x8457 -#define GL_COLOR_SUM 0x8458 -#define GL_CURRENT_SECONDARY_COLOR 0x8459 -#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A -#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B -#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C -#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D -#define GL_SECONDARY_COLOR_ARRAY 0x845E -#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD -#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#define GL_TEXTURE_FILTER_CONTROL 0x8500 -#define GL_TEXTURE_LOD_BIAS 0x8501 -#define GL_INCR_WRAP 0x8507 -#define GL_DECR_WRAP 0x8508 -#define GL_TEXTURE_DEPTH_SIZE 0x884A -#define GL_DEPTH_TEXTURE_MODE 0x884B -#define GL_TEXTURE_COMPARE_MODE 0x884C -#define GL_TEXTURE_COMPARE_FUNC 0x884D -#define GL_COMPARE_R_TO_TEXTURE 0x884E - -#define glBlendColor GlobalOpenGL().m_glBlendColor -#define glBlendEquation GlobalOpenGL().m_glBlendEquation -#define glBlendFuncSeparate GlobalOpenGL().m_glBlendFuncSeparate -#define glFogCoordPointer GlobalOpenGL().m_glFogCoordPointer -#define glFogCoordd GlobalOpenGL().m_glFogCoordd -#define glFogCoorddv GlobalOpenGL().m_glFogCoorddv -#define glFogCoordf GlobalOpenGL().m_glFogCoordf -#define glFogCoordfv GlobalOpenGL().m_glFogCoordfv -#define glMultiDrawArrays GlobalOpenGL().m_glMultiDrawArrays -#define glMultiDrawElements GlobalOpenGL().m_glMultiDrawElements -#define glPointParameterf GlobalOpenGL().m_glPointParameterf -#define glPointParameterfv GlobalOpenGL().m_glPointParameterfv -#define glSecondaryColor3b GlobalOpenGL().m_glSecondaryColor3b -#define glSecondaryColor3bv GlobalOpenGL().m_glSecondaryColor3bv -#define glSecondaryColor3d GlobalOpenGL().m_glSecondaryColor3d -#define glSecondaryColor3dv GlobalOpenGL().m_glSecondaryColor3dv -#define glSecondaryColor3f GlobalOpenGL().m_glSecondaryColor3f -#define glSecondaryColor3fv GlobalOpenGL().m_glSecondaryColor3fv -#define glSecondaryColor3i GlobalOpenGL().m_glSecondaryColor3i -#define glSecondaryColor3iv GlobalOpenGL().m_glSecondaryColor3iv -#define glSecondaryColor3s GlobalOpenGL().m_glSecondaryColor3s -#define glSecondaryColor3sv GlobalOpenGL().m_glSecondaryColor3sv -#define glSecondaryColor3ub GlobalOpenGL().m_glSecondaryColor3ub -#define glSecondaryColor3ubv GlobalOpenGL().m_glSecondaryColor3ubv -#define glSecondaryColor3ui GlobalOpenGL().m_glSecondaryColor3ui -#define glSecondaryColor3uiv GlobalOpenGL().m_glSecondaryColor3uiv -#define glSecondaryColor3us GlobalOpenGL().m_glSecondaryColor3us -#define glSecondaryColor3usv GlobalOpenGL().m_glSecondaryColor3usv -#define glSecondaryColorPointer GlobalOpenGL().m_glSecondaryColorPointer -#define glWindowPos2d GlobalOpenGL().m_glWindowPos2d -#define glWindowPos2dv GlobalOpenGL().m_glWindowPos2dv -#define glWindowPos2f GlobalOpenGL().m_glWindowPos2f -#define glWindowPos2fv GlobalOpenGL().m_glWindowPos2fv -#define glWindowPos2i GlobalOpenGL().m_glWindowPos2i -#define glWindowPos2iv GlobalOpenGL().m_glWindowPos2iv -#define glWindowPos2s GlobalOpenGL().m_glWindowPos2s -#define glWindowPos2sv GlobalOpenGL().m_glWindowPos2sv -#define glWindowPos3d GlobalOpenGL().m_glWindowPos3d -#define glWindowPos3dv GlobalOpenGL().m_glWindowPos3dv -#define glWindowPos3f GlobalOpenGL().m_glWindowPos3f -#define glWindowPos3fv GlobalOpenGL().m_glWindowPos3fv -#define glWindowPos3i GlobalOpenGL().m_glWindowPos3i -#define glWindowPos3iv GlobalOpenGL().m_glWindowPos3iv -#define glWindowPos3s GlobalOpenGL().m_glWindowPos3s -#define glWindowPos3sv GlobalOpenGL().m_glWindowPos3sv - -#endif - - -// GL 1.5 -#if !defined(GL_VERSION_1_5) -#define GL_VERSION_1_5 1 - -#define GL_FOG_COORD GL_FOG_COORDINATE -#define GL_FOG_COORD_ARRAY GL_FOG_COORDINATE_ARRAY -#define GL_SRC0_RGB GL_SOURCE0_RGB -#define GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_POINTER -#define GL_FOG_COORD_SOURCE GL_FOG_COORDINATE_SOURCE -#define GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORDINATE_ARRAY_TYPE -#define GL_SRC1_ALPHA GL_SOURCE1_ALPHA -#define GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE -#define GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_STRIDE -#define GL_SRC0_ALPHA GL_SOURCE0_ALPHA -#define GL_SRC1_RGB GL_SOURCE1_RGB -#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING -#define GL_SRC2_ALPHA GL_SOURCE2_ALPHA -#define GL_SRC2_RGB GL_SOURCE2_RGB -#define GL_BUFFER_SIZE 0x8764 -#define GL_BUFFER_USAGE 0x8765 -#define GL_QUERY_COUNTER_BITS 0x8864 -#define GL_CURRENT_QUERY 0x8865 -#define GL_QUERY_RESULT 0x8866 -#define GL_QUERY_RESULT_AVAILABLE 0x8867 -#define GL_ARRAY_BUFFER 0x8892 -#define GL_ELEMENT_ARRAY_BUFFER 0x8893 -#define GL_ARRAY_BUFFER_BINDING 0x8894 -#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 -#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 -#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 -#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 -#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 -#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A -#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B -#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C -#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D -#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E -#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F -#define GL_READ_ONLY 0x88B8 -#define GL_WRITE_ONLY 0x88B9 -#define GL_READ_WRITE 0x88BA -#define GL_BUFFER_ACCESS 0x88BB -#define GL_BUFFER_MAPPED 0x88BC -#define GL_BUFFER_MAP_POINTER 0x88BD -#define GL_STREAM_DRAW 0x88E0 -#define GL_STREAM_READ 0x88E1 -#define GL_STREAM_COPY 0x88E2 -#define GL_STATIC_DRAW 0x88E4 -#define GL_STATIC_READ 0x88E5 -#define GL_STATIC_COPY 0x88E6 -#define GL_DYNAMIC_DRAW 0x88E8 -#define GL_DYNAMIC_READ 0x88E9 -#define GL_DYNAMIC_COPY 0x88EA -#define GL_SAMPLES_PASSED 0x8914 - -typedef std::ptrdiff_t GLsizeiptr; -typedef std::ptrdiff_t GLintptr; - -#define glBeginQuery GlobalOpenGL().m_glBeginQuery -#define glBindBuffer GlobalOpenGL().m_glBindBuffer -#define glBufferData GlobalOpenGL().m_glBufferData -#define glBufferSubData GlobalOpenGL().m_glBufferSubData -#define glDeleteBuffers GlobalOpenGL().m_glDeleteBuffers -#define glDeleteQueries GlobalOpenGL().m_glDeleteQueries -#define glEndQuery GlobalOpenGL().m_glEndQuery -#define glGenBuffers GlobalOpenGL().m_glGenBuffers -#define glGenQueries GlobalOpenGL().m_glGenQueries -#define glGetBufferParameteriv GlobalOpenGL().m_glGetBufferParameteriv -#define glGetBufferPointerv GlobalOpenGL().m_glGetBufferPointerv -#define glGetBufferSubData GlobalOpenGL().m_glGetBufferSubData -#define glGetQueryObjectiv GlobalOpenGL().m_glGetQueryObjectiv -#define glGetQueryObjectuiv GlobalOpenGL().m_glGetQueryObjectuiv -#define glGetQueryiv GlobalOpenGL().m_glGetQueryiv -#define glIsBuffer GlobalOpenGL().m_glIsBuffer -#define glIsQuery GlobalOpenGL().m_glIsQuery -#define glMapBuffer GlobalOpenGL().m_glMapBuffer -#define glUnmapBuffer GlobalOpenGL().m_glUnmapBuffer - -#endif - - -// GL_ARB_vertex_program -#if !defined(GL_ARB_vertex_program) -#define GL_ARB_vertex_program - -#define GL_VERTEX_PROGRAM_ARB 0x8620 -#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 -#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 -#define GL_COLOR_SUM_ARB 0x8458 -#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 -#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 -#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 -#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 -#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 -#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A -#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 -#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 -#define GL_PROGRAM_LENGTH_ARB 0x8627 -#define GL_PROGRAM_FORMAT_ARB 0x8876 -#define GL_PROGRAM_BINDING_ARB 0x8677 -#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 -#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 -#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 -#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 -#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 -#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 -#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 -#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 -#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 -#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 -#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA -#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB -#define GL_PROGRAM_ATTRIBS_ARB 0x88AC -#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD -#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE -#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF -#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 -#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 -#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 -#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 -#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 -#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 -#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 -#define GL_PROGRAM_STRING_ARB 0x8628 -#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B -#define GL_CURRENT_MATRIX_ARB 0x8641 -#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 -#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 -#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 -#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F -#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E -#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 -#define GL_MATRIX0_ARB 0x88C0 -#define GL_MATRIX1_ARB 0x88C1 -#define GL_MATRIX2_ARB 0x88C2 -#define GL_MATRIX3_ARB 0x88C3 -#define GL_MATRIX4_ARB 0x88C4 -#define GL_MATRIX5_ARB 0x88C5 -#define GL_MATRIX6_ARB 0x88C6 -#define GL_MATRIX7_ARB 0x88C7 -#define GL_MATRIX8_ARB 0x88C8 -#define GL_MATRIX9_ARB 0x88C9 -#define GL_MATRIX10_ARB 0x88CA -#define GL_MATRIX11_ARB 0x88CB -#define GL_MATRIX12_ARB 0x88CC -#define GL_MATRIX13_ARB 0x88CD -#define GL_MATRIX14_ARB 0x88CE -#define GL_MATRIX15_ARB 0x88CF -#define GL_MATRIX16_ARB 0x88D0 -#define GL_MATRIX17_ARB 0x88D1 -#define GL_MATRIX18_ARB 0x88D2 -#define GL_MATRIX19_ARB 0x88D3 -#define GL_MATRIX20_ARB 0x88D4 -#define GL_MATRIX21_ARB 0x88D5 -#define GL_MATRIX22_ARB 0x88D6 -#define GL_MATRIX23_ARB 0x88D7 -#define GL_MATRIX24_ARB 0x88D8 -#define GL_MATRIX25_ARB 0x88D9 -#define GL_MATRIX26_ARB 0x88DA -#define GL_MATRIX27_ARB 0x88DB -#define GL_MATRIX28_ARB 0x88DC -#define GL_MATRIX29_ARB 0x88DD -#define GL_MATRIX30_ARB 0x88DE -#define GL_MATRIX31_ARB 0x88DF - -#define glVertexAttrib1sARB GlobalOpenGL().m_glVertexAttrib1sARB -#define glVertexAttrib1fARB GlobalOpenGL().m_glVertexAttrib1fARB -#define glVertexAttrib1dARB GlobalOpenGL().m_glVertexAttrib1dARB -#define glVertexAttrib2sARB GlobalOpenGL().m_glVertexAttrib2sARB -#define glVertexAttrib2fARB GlobalOpenGL().m_glVertexAttrib2fARB -#define glVertexAttrib2dARB GlobalOpenGL().m_glVertexAttrib2dARB -#define glVertexAttrib3sARB GlobalOpenGL().m_glVertexAttrib3sARB -#define glVertexAttrib3fARB GlobalOpenGL().m_glVertexAttrib3fARB -#define glVertexAttrib3dARB GlobalOpenGL().m_glVertexAttrib3dARB -#define glVertexAttrib4sARB GlobalOpenGL().m_glVertexAttrib4sARB -#define glVertexAttrib4fARB GlobalOpenGL().m_glVertexAttrib4fARB -#define glVertexAttrib4dARB GlobalOpenGL().m_glVertexAttrib4dARB -#define glVertexAttrib4NubARB GlobalOpenGL().m_glVertexAttrib4NubARB -#define glVertexAttrib1svARB GlobalOpenGL().m_glVertexAttrib1svARB -#define glVertexAttrib1fvARB GlobalOpenGL().m_glVertexAttrib1fvARB -#define glVertexAttrib1dvARB GlobalOpenGL().m_glVertexAttrib1dvARB -#define glVertexAttrib2svARB GlobalOpenGL().m_glVertexAttrib2svARB -#define glVertexAttrib2fvARB GlobalOpenGL().m_glVertexAttrib2fvARB -#define glVertexAttrib2dvARB GlobalOpenGL().m_glVertexAttrib2dvARB -#define glVertexAttrib3svARB GlobalOpenGL().m_glVertexAttrib3svARB -#define glVertexAttrib3fvARB GlobalOpenGL().m_glVertexAttrib3fvARB -#define glVertexAttrib3dvARB GlobalOpenGL().m_glVertexAttrib3dvARB -#define glVertexAttrib4bvARB GlobalOpenGL().m_glVertexAttrib4bvARB -#define glVertexAttrib4svARB GlobalOpenGL().m_glVertexAttrib4svARB -#define glVertexAttrib4ivARB GlobalOpenGL().m_glVertexAttrib4ivARB -#define glVertexAttrib4ubvARB GlobalOpenGL().m_glVertexAttrib4ubvARB -#define glVertexAttrib4usvARB GlobalOpenGL().m_glVertexAttrib4usvARB -#define glVertexAttrib4uivARB GlobalOpenGL().m_glVertexAttrib4uivARB -#define glVertexAttrib4fvARB GlobalOpenGL().m_glVertexAttrib4fvARB -#define glVertexAttrib4dvARB GlobalOpenGL().m_glVertexAttrib4dvARB -#define glVertexAttrib4NbvARB GlobalOpenGL().m_glVertexAttrib4NbvARB -#define glVertexAttrib4NsvARB GlobalOpenGL().m_glVertexAttrib4NsvARB -#define glVertexAttrib4NivARB GlobalOpenGL().m_glVertexAttrib4NivARB -#define glVertexAttrib4NubvARB GlobalOpenGL().m_glVertexAttrib4NubvARB -#define glVertexAttrib4NusvARB GlobalOpenGL().m_glVertexAttrib4NusvARB -#define glVertexAttrib4NuivARB GlobalOpenGL().m_glVertexAttrib4NuivARB -#define glVertexAttribPointerARB GlobalOpenGL().m_glVertexAttribPointerARB -#define glEnableVertexAttribArrayARB GlobalOpenGL().m_glEnableVertexAttribArrayARB -#define glDisableVertexAttribArrayARB GlobalOpenGL().m_glDisableVertexAttribArrayARB -#define glProgramStringARB GlobalOpenGL().m_glProgramStringARB -#define glBindProgramARB GlobalOpenGL().m_glBindProgramARB -#define glDeleteProgramsARB GlobalOpenGL().m_glDeleteProgramsARB -#define glGenProgramsARB GlobalOpenGL().m_glGenProgramsARB -#define glProgramEnvParameter4dARB GlobalOpenGL().m_glProgramEnvParameter4dARB -#define glProgramEnvParameter4dvARB GlobalOpenGL().m_glProgramEnvParameter4dvARB -#define glProgramEnvParameter4fARB GlobalOpenGL().m_glProgramEnvParameter4fARB -#define glProgramEnvParameter4fvARB GlobalOpenGL().m_glProgramEnvParameter4fvARB -#define glProgramLocalParameter4dARB GlobalOpenGL().m_glProgramLocalParameter4dARB -#define glProgramLocalParameter4dvARB GlobalOpenGL().m_glProgramLocalParameter4dvARB -#define glProgramLocalParameter4fARB GlobalOpenGL().m_glProgramLocalParameter4fARB -#define glProgramLocalParameter4fvARB GlobalOpenGL().m_glProgramLocalParameter4fvARB -#define glGetProgramEnvParameterdvARB GlobalOpenGL().m_glGetProgramEnvParameterdvARB -#define glGetProgramEnvParameterfvARB GlobalOpenGL().m_glGetProgramEnvParameterfvARB -#define glGetProgramLocalParameterdvARB GlobalOpenGL().m_glGetProgramLocalParameterdvARB -#define glGetProgramLocalParameterfvARB GlobalOpenGL().m_glGetProgramLocalParameterfvARB -#define glGetProgramivARB GlobalOpenGL().m_glGetProgramivARB -#define glGetProgramStringARB GlobalOpenGL().m_glGetProgramStringARB -#define glGetVertexAttribdvARB GlobalOpenGL().m_glGetVertexAttribdvARB -#define glGetVertexAttribfvARB GlobalOpenGL().m_glGetVertexAttribfvARB -#define glGetVertexAttribivARB GlobalOpenGL().m_glGetVertexAttribivARB -#define glGetVertexAttribPointervARB GlobalOpenGL().m_glGetVertexAttribPointervARB -#define glIsProgramARB GlobalOpenGL().m_glIsProgramARB - -#endif - - -// GL_ARB_fragment_program -#if !defined(GL_ARB_fragment_program) -#define GL_ARB_fragment_program 1 - -#define GL_FRAGMENT_PROGRAM_ARB 0x8804 -#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 -#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 -#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 -#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 -#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 -#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A -#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B -#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C -#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D -#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E -#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F -#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 -#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 -#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 - -#endif - - -// GL_ARB_shader_objects -#if !defined(GL_ARB_shader_objects) -#define GL_ARB_shader_objects 1 - -#define GL_PROGRAM_OBJECT_ARB 0x8B40 -#define GL_SHADER_OBJECT_ARB 0x8B48 -#define GL_OBJECT_TYPE_ARB 0x8B4E -#define GL_OBJECT_SUBTYPE_ARB 0x8B4F -#define GL_FLOAT_VEC2_ARB 0x8B50 -#define GL_FLOAT_VEC3_ARB 0x8B51 -#define GL_FLOAT_VEC4_ARB 0x8B52 -#define GL_INT_VEC2_ARB 0x8B53 -#define GL_INT_VEC3_ARB 0x8B54 -#define GL_INT_VEC4_ARB 0x8B55 -#define GL_BOOL_ARB 0x8B56 -#define GL_BOOL_VEC2_ARB 0x8B57 -#define GL_BOOL_VEC3_ARB 0x8B58 -#define GL_BOOL_VEC4_ARB 0x8B59 -#define GL_FLOAT_MAT2_ARB 0x8B5A -#define GL_FLOAT_MAT3_ARB 0x8B5B -#define GL_FLOAT_MAT4_ARB 0x8B5C -#define GL_SAMPLER_1D_ARB 0x8B5D -#define GL_SAMPLER_2D_ARB 0x8B5E -#define GL_SAMPLER_3D_ARB 0x8B5F -#define GL_SAMPLER_CUBE_ARB 0x8B60 -#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 -#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 -#define GL_SAMPLER_2D_RECT_ARB 0x8B63 -#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 -#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 -#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 -#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 -#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 -#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 -#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 -#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 -#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 -#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 - -#define glDeleteObjectARB GlobalOpenGL().m_glDeleteObjectARB -#define glGetHandleARB GlobalOpenGL().m_glGetHandleARB -#define glDetachObjectARB GlobalOpenGL().m_glDetachObjectARB -#define glCreateShaderObjectARB GlobalOpenGL().m_glCreateShaderObjectARB -#define glShaderSourceARB GlobalOpenGL().m_glShaderSourceARB -#define glCompileShaderARB GlobalOpenGL().m_glCompileShaderARB -#define glCreateProgramObjectARB GlobalOpenGL().m_glCreateProgramObjectARB -#define glAttachObjectARB GlobalOpenGL().m_glAttachObjectARB -#define glLinkProgramARB GlobalOpenGL().m_glLinkProgramARB -#define glUseProgramObjectARB GlobalOpenGL().m_glUseProgramObjectARB -#define glValidateProgramARB GlobalOpenGL().m_glValidateProgramARB -#define glUniform1fARB GlobalOpenGL().m_glUniform1fARB -#define glUniform2fARB GlobalOpenGL().m_glUniform2fARB -#define glUniform3fARB GlobalOpenGL().m_glUniform3fARB -#define glUniform4fARB GlobalOpenGL().m_glUniform4fARB -#define glUniform1iARB GlobalOpenGL().m_glUniform1iARB -#define glUniform2iARB GlobalOpenGL().m_glUniform2iARB -#define glUniform3iARB GlobalOpenGL().m_glUniform3iARB -#define glUniform4iARB GlobalOpenGL().m_glUniform4iARB -#define glUniform1fvARB GlobalOpenGL().m_glUniform1fvARB -#define glUniform2fvARB GlobalOpenGL().m_glUniform2fvARB -#define glUniform3fvARB GlobalOpenGL().m_glUniform3fvARB -#define glUniform4fvARB GlobalOpenGL().m_glUniform4fvARB -#define glUniform1ivARB GlobalOpenGL().m_glUniform1ivARB -#define glUniform2ivARB GlobalOpenGL().m_glUniform2ivARB -#define glUniform3ivARB GlobalOpenGL().m_glUniform3ivARB -#define glUniform4ivARB GlobalOpenGL().m_glUniform4ivARB -#define glUniformMatrix2fvARB GlobalOpenGL().m_glUniformMatrix2fvARB -#define glUniformMatrix3fvARB GlobalOpenGL().m_glUniformMatrix3fvARB -#define glUniformMatrix4fvARB GlobalOpenGL().m_glUniformMatrix4fvARB -#define glGetObjectParameterfvARB GlobalOpenGL().m_glGetObjectParameterfvARB -#define glGetObjectParameterivARB GlobalOpenGL().m_glGetObjectParameterivARB -#define glGetInfoLogARB GlobalOpenGL().m_glGetInfoLogARB -#define glGetAttachedObjectsARB GlobalOpenGL().m_glGetAttachedObjectsARB -#define glGetUniformLocationARB GlobalOpenGL().m_glGetUniformLocationARB -#define glGetActiveUniformARB GlobalOpenGL().m_glGetActiveUniformARB -#define glGetUniformfvARB GlobalOpenGL().m_glGetUniformfvARB -#define glGetUniformivARB GlobalOpenGL().m_glGetUniformivARB -#define glGetShaderSourceARB GlobalOpenGL().m_glGetShaderSourceARB - -typedef char GLcharARB; -typedef unsigned int GLhandleARB; - -#endif - -// GL_ARB_vertex_shader -#if !defined(GL_ARB_vertex_shader) -#define GL_ARB_vertex_shader 1 - -#define GL_VERTEX_SHADER_ARB 0x8B31 -#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A -#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B -#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C -#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D -#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 -#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A - -#if 0 -#define glVertexAttrib1fARB GlobalOpenGL().m_glVertexAttrib1fARB -#define glVertexAttrib1sARB GlobalOpenGL().m_glVertexAttrib1sARB -#define glVertexAttrib1dARB GlobalOpenGL().m_glVertexAttrib1dARB -#define glVertexAttrib2fARB GlobalOpenGL().m_glVertexAttrib2fARB -#define glVertexAttrib2sARB GlobalOpenGL().m_glVertexAttrib2sARB -#define glVertexAttrib2dARB GlobalOpenGL().m_glVertexAttrib2dARB -#define glVertexAttrib3fARB GlobalOpenGL().m_glVertexAttrib3fARB -#define glVertexAttrib3sARB GlobalOpenGL().m_glVertexAttrib3sARB -#define glVertexAttrib3dARB GlobalOpenGL().m_glVertexAttrib3dARB -#define glVertexAttrib4fARB GlobalOpenGL().m_glVertexAttrib4fARB -#define glVertexAttrib4sARB GlobalOpenGL().m_glVertexAttrib4sARB -#define glVertexAttrib4dARB GlobalOpenGL().m_glVertexAttrib4dARB -#define glVertexAttrib4NubARB GlobalOpenGL().m_glVertexAttrib4NubARB -#define glVertexAttrib1fvARB GlobalOpenGL().m_glVertexAttrib1fvARB -#define glVertexAttrib1svARB GlobalOpenGL().m_glVertexAttrib1svARB -#define glVertexAttrib1dvARB GlobalOpenGL().m_glVertexAttrib1dvARB -#define glVertexAttrib2fvARB GlobalOpenGL().m_glVertexAttrib2fvARB -#define glVertexAttrib2svARB GlobalOpenGL().m_glVertexAttrib2svARB -#define glVertexAttrib2dvARB GlobalOpenGL().m_glVertexAttrib2dvARB -#define glVertexAttrib3fvARB GlobalOpenGL().m_glVertexAttrib3fvARB -#define glVertexAttrib3svARB GlobalOpenGL().m_glVertexAttrib3svARB -#define glVertexAttrib3dvARB GlobalOpenGL().m_glVertexAttrib3dvARB -#define glVertexAttrib4fvARB GlobalOpenGL().m_glVertexAttrib4fvARB -#define glVertexAttrib4svARB GlobalOpenGL().m_glVertexAttrib4svARB -#define glVertexAttrib4dvARB GlobalOpenGL().m_glVertexAttrib4dvARB -#define glVertexAttrib4ivARB GlobalOpenGL().m_glVertexAttrib4ivARB -#define glVertexAttrib4bvARB GlobalOpenGL().m_glVertexAttrib4bvARB -#define glVertexAttrib4ubvARB GlobalOpenGL().m_glVertexAttrib4ubvARB -#define glVertexAttrib4usvARB GlobalOpenGL().m_glVertexAttrib4usvARB -#define glVertexAttrib4uivARB GlobalOpenGL().m_glVertexAttrib4uivARB -#define glVertexAttrib4NbvARB GlobalOpenGL().m_glVertexAttrib4NbvARB -#define glVertexAttrib4NsvARB GlobalOpenGL().m_glVertexAttrib4NsvARB -#define glVertexAttrib4NivARB GlobalOpenGL().m_glVertexAttrib4NivARB -#define glVertexAttrib4NubvARB GlobalOpenGL().m_glVertexAttrib4NubvARB -#define glVertexAttrib4NusvARB GlobalOpenGL().m_glVertexAttrib4NusvARB -#define glVertexAttrib4NuivARB GlobalOpenGL().m_glVertexAttrib4NuivARB -#define glVertexAttribPointerARB GlobalOpenGL().m_glVertexAttribPointerARB -#define glEnableVertexAttribArrayARB GlobalOpenGL().m_glEnableVertexAttribArrayARB -#define glDisableVertexAttribArrayARB GlobalOpenGL().m_glDisableVertexAttribArrayARB -#endif -#define glBindAttribLocationARB GlobalOpenGL().m_glBindAttribLocationARB -#define glGetActiveAttribARB GlobalOpenGL().m_glGetActiveAttribARB -#define glGetAttribLocationARB GlobalOpenGL().m_glGetAttribLocationARB -#if 0 -#define glGetVertexAttribdvARB GlobalOpenGL().m_glGetVertexAttribdvARB -#define glGetVertexAttribfvARB GlobalOpenGL().m_glGetVertexAttribfvARB -#define glGetVertexAttribivARB GlobalOpenGL().m_glGetVertexAttribivARB -#define glGetVertexAttribPointervARB GlobalOpenGL().m_glGetVertexAttribPointervARB -#endif -#endif - - - -// GL_ARB_fragment_shader -#if !defined(GL_ARB_fragment_shader) -#define GL_ARB_fragment_shader 1 - -#define GL_FRAGMENT_SHADER_ARB 0x8B30 -#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 -#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B - -#endif - - -// GL_ARB_shading_language_100 -#if !defined(GL_ARB_shading_language_100) -#define GL_ARB_shading_language_100 1 - -#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C - -#endif - - -// GL_NV_vertex_program2 -#if !defined(GL_NV_vertex_program) -#define GL_NV_vertex_program 1 - -#define GL_VERTEX_PROGRAM_NV 0x8620 -#define GL_VERTEX_STATE_PROGRAM_NV 0x8621 -#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 -#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 -#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 -#define GL_CURRENT_ATTRIB_NV 0x8626 -#define GL_PROGRAM_LENGTH_NV 0x8627 -#define GL_PROGRAM_STRING_NV 0x8628 -#define GL_MODELVIEW_PROJECTION_NV 0x8629 -#define GL_IDENTITY_NV 0x862A -#define GL_INVERSE_NV 0x862B -#define GL_TRANSPOSE_NV 0x862C -#define GL_INVERSE_TRANSPOSE_NV 0x862D -#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E -#define GL_MAX_TRACK_MATRICES_NV 0x862F -#define GL_MATRIX0_NV 0x8630 -#define GL_MATRIX1_NV 0x8631 -#define GL_MATRIX2_NV 0x8632 -#define GL_MATRIX3_NV 0x8633 -#define GL_MATRIX4_NV 0x8634 -#define GL_MATRIX5_NV 0x8635 -#define GL_MATRIX6_NV 0x8636 -#define GL_MATRIX7_NV 0x8637 -#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 -#define GL_CURRENT_MATRIX_NV 0x8641 -#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 -#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 -#define GL_PROGRAM_PARAMETER_NV 0x8644 -#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 -#define GL_PROGRAM_TARGET_NV 0x8646 -#define GL_PROGRAM_RESIDENT_NV 0x8647 -#define GL_TRACK_MATRIX_NV 0x8648 -#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 -#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A -#define GL_PROGRAM_ERROR_POSITION_NV 0x864B -#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 -#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 -#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 -#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 -#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 -#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 -#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 -#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 -#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 -#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 -#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A -#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B -#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C -#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D -#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E -#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F -#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 -#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 -#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 -#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 -#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 -#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 -#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 -#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 -#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 -#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 -#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A -#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B -#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C -#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D -#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E -#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F -#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 -#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 -#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 -#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 -#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 -#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 -#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 -#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 -#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 -#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 -#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A -#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B -#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C -#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D -#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E -#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F - -#define glAreProgramsResidentNV GlobalOpenGL().m_glAreProgramsResidentNV -#define glBindProgramNV GlobalOpenGL().m_glBindProgramNV -#define glDeleteProgramsNV GlobalOpenGL().m_glDeleteProgramsNV -#define glExecuteProgramNV GlobalOpenGL().m_glExecuteProgramNV -#define glGenProgramsNV GlobalOpenGL().m_glGenProgramsNV -#define glGetProgramParameterdvNV GlobalOpenGL().m_glGetProgramParameterdvNV -#define glGetProgramParameterfvNV GlobalOpenGL().m_glGetProgramParameterfvNV -#define glGetProgramivNV GlobalOpenGL().m_glGetProgramivNV -#define glGetProgramStringNV GlobalOpenGL().m_glGetProgramStringNV -#define glGetTrackMatrixivNV GlobalOpenGL().m_glGetTrackMatrixivNV -#define glGetVertexAttribdvNV GlobalOpenGL().m_glGetVertexAttribdvNV -#define glGetVertexAttribfvNV GlobalOpenGL().m_glGetVertexAttribfvNV -#define glGetVertexAttribivNV GlobalOpenGL().m_glGetVertexAttribivNV -#define glGetVertexAttribPointervNV GlobalOpenGL().m_glGetVertexAttribPointervNV -#define glIsProgramNV GlobalOpenGL().m_glIsProgramNV -#define glLoadProgramNV GlobalOpenGL().m_glLoadProgramNV -#define glProgramParameter4fNV GlobalOpenGL().m_glProgramParameter4fNV -#define glProgramParameter4fvNV GlobalOpenGL().m_glProgramParameter4fvNV -#define glProgramParameters4fvNV GlobalOpenGL().m_glProgramParameters4fvNV -#define glRequestResidentProgramsNV GlobalOpenGL().m_glRequestResidentProgramsNV -#define glTrackMatrixNV GlobalOpenGL().m_glTrackMatrixNV -#define glVertexAttribPointerNV GlobalOpenGL().m_glVertexAttribPointerNV -#define glVertexAttrib1fNV GlobalOpenGL().m_glVertexAttrib1fNV -#define glVertexAttrib1fvNV GlobalOpenGL().m_glVertexAttrib1fvNV -#define glVertexAttrib2fNV GlobalOpenGL().m_glVertexAttrib2fNV -#define glVertexAttrib2fvNV GlobalOpenGL().m_glVertexAttrib2fvNV -#define glVertexAttrib3fNV GlobalOpenGL().m_glVertexAttrib3fNV -#define glVertexAttrib3fvNV GlobalOpenGL().m_glVertexAttrib3fvNV -#define glVertexAttrib4fNV GlobalOpenGL().m_glVertexAttrib4fNV -#define glVertexAttrib4fvNV GlobalOpenGL().m_glVertexAttrib4fvNV -#define glVertexAttribs1fvNV GlobalOpenGL().m_glVertexAttribs1fvNV -#define glVertexAttribs2fvNV GlobalOpenGL().m_glVertexAttribs2fvNV -#define glVertexAttribs3fvNV GlobalOpenGL().m_glVertexAttribs3fvNV -#define glVertexAttribs4fvNV GlobalOpenGL().m_glVertexAttribs4fvNV - -#endif - - -// GL_NV_fragment_program -#if !defined(GL_NV_fragment_program) - -#define GL_NV_fragment_program 1 - -#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868 -#define GL_FRAGMENT_PROGRAM_NV 0x8870 -#define GL_MAX_TEXTURE_COORDS_NV 0x8871 -#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872 -#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873 -#define GL_PROGRAM_ERROR_STRING_NV 0x8874 - -#define glProgramNamedParameter4fNV GlobalOpenGL().m_glProgramNamedParameter4fNV -#define glProgramNamedParameter4fvNV GlobalOpenGL().m_glProgramNamedParameter4fvNV -#define glGetProgramNamedParameterfvNV GlobalOpenGL().m_glGetProgramNamedParameterfvNV - -#endif - -#include "gtkutil/glfont.h" - -/// \brief A module which wraps a runtime-binding of the standard OpenGL functions. -/// Provides convenience functions for querying availabiliy of extensions, rendering text and error-checking. -struct OpenGLBinding -{ - INTEGER_CONSTANT(Version, 2); - STRING_CONSTANT(Name, "qgl"); - - /// \brief OpenGL version, extracted from the GL_VERSION string. - int major_version, minor_version; - - /// \brief Is true if the global shared OpenGL context is valid. - bool contextValid; - - OpenGLBinding() : contextValid(false) - { - } - - /// \brief Asserts that there no OpenGL errors have occurred since the last call to glGetError. - void (*assertNoErrors)(const char *file, int line); - - GLFont *m_font; // MUST be set! - - /// \brief Renders \p string at the current raster-position of the current context. - void drawString(const char* string) const - { - m_font->printString(string); - } - - /// \brief Renders \p character at the current raster-position of the current context. - void drawChar(char character) const - { - char s[2]; - s[0] = character; - s[1] = 0; - drawString(s); - } - - - // GL 1.1 - void (QGL_DLLEXPORT *m_glAccum)(GLenum op, GLfloat value); - void (QGL_DLLEXPORT *m_glAlphaFunc)(GLenum func, GLclampf ref); - GLboolean (QGL_DLLEXPORT *m_glAreTexturesResident)(GLsizei n, const GLuint *textures, GLboolean *residences); - void (QGL_DLLEXPORT *m_glArrayElement)(GLint i); - void (QGL_DLLEXPORT *m_glBegin)(GLenum mode); - void (QGL_DLLEXPORT *m_glBindTexture)(GLenum target, GLuint texture); - void (QGL_DLLEXPORT *m_glBitmap)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); - void (QGL_DLLEXPORT *m_glBlendFunc)(GLenum sfactor, GLenum dfactor); - void (QGL_DLLEXPORT *m_glCallList)(GLuint list); - void (QGL_DLLEXPORT *m_glCallLists)(GLsizei n, GLenum type, const GLvoid *lists); - void (QGL_DLLEXPORT *m_glClear)(GLbitfield mask); - void (QGL_DLLEXPORT *m_glClearAccum)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); - void (QGL_DLLEXPORT *m_glClearColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); - void (QGL_DLLEXPORT *m_glClearDepth)(GLclampd depth); - void (QGL_DLLEXPORT *m_glClearIndex)(GLfloat c); - void (QGL_DLLEXPORT *m_glClearStencil)(GLint s); - void (QGL_DLLEXPORT *m_glClipPlane)(GLenum plane, const GLdouble *equation); - void (QGL_DLLEXPORT *m_glColor3b)(GLbyte red, GLbyte green, GLbyte blue); - void (QGL_DLLEXPORT *m_glColor3bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glColor3d)(GLdouble red, GLdouble green, GLdouble blue); - void (QGL_DLLEXPORT *m_glColor3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glColor3f)(GLfloat red, GLfloat green, GLfloat blue); - void (QGL_DLLEXPORT *m_glColor3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glColor3i)(GLint red, GLint green, GLint blue); - void (QGL_DLLEXPORT *m_glColor3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glColor3s)(GLshort red, GLshort green, GLshort blue); - void (QGL_DLLEXPORT *m_glColor3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glColor3ub)(GLubyte red, GLubyte green, GLubyte blue); - void (QGL_DLLEXPORT *m_glColor3ubv)(const GLubyte *v); - void (QGL_DLLEXPORT *m_glColor3ui)(GLuint red, GLuint green, GLuint blue); - void (QGL_DLLEXPORT *m_glColor3uiv)(const GLuint *v); - void (QGL_DLLEXPORT *m_glColor3us)(GLushort red, GLushort green, GLushort blue); - void (QGL_DLLEXPORT *m_glColor3usv)(const GLushort *v); - void (QGL_DLLEXPORT *m_glColor4b)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); - void (QGL_DLLEXPORT *m_glColor4bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glColor4d)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); - void (QGL_DLLEXPORT *m_glColor4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glColor4f)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); - void (QGL_DLLEXPORT *m_glColor4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glColor4i)(GLint red, GLint green, GLint blue, GLint alpha); - void (QGL_DLLEXPORT *m_glColor4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glColor4s)(GLshort red, GLshort green, GLshort blue, GLshort alpha); - void (QGL_DLLEXPORT *m_glColor4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glColor4ub)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); - void (QGL_DLLEXPORT *m_glColor4ubv)(const GLubyte *v); - void (QGL_DLLEXPORT *m_glColor4ui)(GLuint red, GLuint green, GLuint blue, GLuint alpha); - void (QGL_DLLEXPORT *m_glColor4uiv)(const GLuint *v); - void (QGL_DLLEXPORT *m_glColor4us)(GLushort red, GLushort green, GLushort blue, GLushort alpha); - void (QGL_DLLEXPORT *m_glColor4usv)(const GLushort *v); - void (QGL_DLLEXPORT *m_glColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); - void (QGL_DLLEXPORT *m_glColorMaterial)(GLenum face, GLenum mode); - void (QGL_DLLEXPORT *m_glColorPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glCopyPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); - void (QGL_DLLEXPORT *m_glCopyTexImage1D)(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border); - void (QGL_DLLEXPORT *m_glCopyTexImage2D)(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); - void (QGL_DLLEXPORT *m_glCopyTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); - void (QGL_DLLEXPORT *m_glCopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); - void (QGL_DLLEXPORT *m_glCullFace)(GLenum mode); - void (QGL_DLLEXPORT *m_glDeleteLists)(GLuint list, GLsizei range); - void (QGL_DLLEXPORT *m_glDeleteTextures)(GLsizei n, const GLuint *textures); - void (QGL_DLLEXPORT *m_glDepthFunc)(GLenum func); - void (QGL_DLLEXPORT *m_glDepthMask)(GLboolean flag); - void (QGL_DLLEXPORT *m_glDepthRange)(GLclampd zNear, GLclampd zFar); - void (QGL_DLLEXPORT *m_glDisable)(GLenum cap); - void (QGL_DLLEXPORT *m_glDisableClientState)(GLenum array); - void (QGL_DLLEXPORT *m_glDrawArrays)(GLenum mode, GLint first, GLsizei count); - void (QGL_DLLEXPORT *m_glDrawBuffer)(GLenum mode); - void (QGL_DLLEXPORT *m_glDrawElements)(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices); - void (QGL_DLLEXPORT *m_glDrawPixels)(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glEdgeFlag)(GLboolean flag); - void (QGL_DLLEXPORT *m_glEdgeFlagPointer)(GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glEdgeFlagv)(const GLboolean *flag); - void (QGL_DLLEXPORT *m_glEnable)(GLenum cap); - void (QGL_DLLEXPORT *m_glEnableClientState)(GLenum array); - void (QGL_DLLEXPORT *m_glEnd)(void); - void (QGL_DLLEXPORT *m_glEndList)(void); - void (QGL_DLLEXPORT *m_glEvalCoord1d)(GLdouble u); - void (QGL_DLLEXPORT *m_glEvalCoord1dv)(const GLdouble *u); - void (QGL_DLLEXPORT *m_glEvalCoord1f)(GLfloat u); - void (QGL_DLLEXPORT *m_glEvalCoord1fv)(const GLfloat *u); - void (QGL_DLLEXPORT *m_glEvalCoord2d)(GLdouble u, GLdouble v); - void (QGL_DLLEXPORT *m_glEvalCoord2dv)(const GLdouble *u); - void (QGL_DLLEXPORT *m_glEvalCoord2f)(GLfloat u, GLfloat v); - void (QGL_DLLEXPORT *m_glEvalCoord2fv)(const GLfloat *u); - void (QGL_DLLEXPORT *m_glEvalMesh1)(GLenum mode, GLint i1, GLint i2); - void (QGL_DLLEXPORT *m_glEvalMesh2)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); - void (QGL_DLLEXPORT *m_glEvalPoint1)(GLint i); - void (QGL_DLLEXPORT *m_glEvalPoint2)(GLint i, GLint j); - void (QGL_DLLEXPORT *m_glFeedbackBuffer)(GLsizei size, GLenum type, GLfloat *buffer); - void (QGL_DLLEXPORT *m_glFinish)(void); - void (QGL_DLLEXPORT *m_glFlush)(void); - void (QGL_DLLEXPORT *m_glFogf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glFogfv)(GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glFogi)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glFogiv)(GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glFrontFace)(GLenum mode); - void (QGL_DLLEXPORT *m_glFrustum)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); - GLuint (QGL_DLLEXPORT *m_glGenLists)(GLsizei range); - void (QGL_DLLEXPORT *m_glGenTextures)(GLsizei n, GLuint *textures); - void (QGL_DLLEXPORT *m_glGetBooleanv)(GLenum pname, GLboolean *params); - void (QGL_DLLEXPORT *m_glGetClipPlane)(GLenum plane, GLdouble *equation); - void (QGL_DLLEXPORT *m_glGetDoublev)(GLenum pname, GLdouble *params); - GLenum (QGL_DLLEXPORT *m_glGetError)(void); - void (QGL_DLLEXPORT *m_glGetFloatv)(GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetIntegerv)(GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetLightfv)(GLenum light, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetLightiv)(GLenum light, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetMapdv)(GLenum target, GLenum query, GLdouble *v); - void (QGL_DLLEXPORT *m_glGetMapfv)(GLenum target, GLenum query, GLfloat *v); - void (QGL_DLLEXPORT *m_glGetMapiv)(GLenum target, GLenum query, GLint *v); - void (QGL_DLLEXPORT *m_glGetMaterialfv)(GLenum face, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetMaterialiv)(GLenum face, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetPixelMapfv)(GLenum map, GLfloat *values); - void (QGL_DLLEXPORT *m_glGetPixelMapuiv)(GLenum map, GLuint *values); - void (QGL_DLLEXPORT *m_glGetPixelMapusv)(GLenum map, GLushort *values); - void (QGL_DLLEXPORT *m_glGetPointerv)(GLenum pname, GLvoid* *params); - void (QGL_DLLEXPORT *m_glGetPolygonStipple)(GLubyte *mask); - const GLubyte * (QGL_DLLEXPORT *m_glGetString)(GLenum name); - void (QGL_DLLEXPORT *m_glGetTexEnvfv)(GLenum target, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexEnviv)(GLenum target, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetTexGendv)(GLenum coord, GLenum pname, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetTexGenfv)(GLenum coord, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexGeniv)(GLenum coord, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels); - void (QGL_DLLEXPORT *m_glGetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetTexParameteriv)(GLenum target, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glHint)(GLenum target, GLenum mode); - void (QGL_DLLEXPORT *m_glIndexMask)(GLuint mask); - void (QGL_DLLEXPORT *m_glIndexPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glIndexd)(GLdouble c); - void (QGL_DLLEXPORT *m_glIndexdv)(const GLdouble *c); - void (QGL_DLLEXPORT *m_glIndexf)(GLfloat c); - void (QGL_DLLEXPORT *m_glIndexfv)(const GLfloat *c); - void (QGL_DLLEXPORT *m_glIndexi)(GLint c); - void (QGL_DLLEXPORT *m_glIndexiv)(const GLint *c); - void (QGL_DLLEXPORT *m_glIndexs)(GLshort c); - void (QGL_DLLEXPORT *m_glIndexsv)(const GLshort *c); - void (QGL_DLLEXPORT *m_glIndexub)(GLubyte c); - void (QGL_DLLEXPORT *m_glIndexubv)(const GLubyte *c); - void (QGL_DLLEXPORT *m_glInitNames)(void); - void (QGL_DLLEXPORT *m_glInterleavedArrays)(GLenum format, GLsizei stride, const GLvoid *pointer); - GLboolean (QGL_DLLEXPORT *m_glIsEnabled)(GLenum cap); - GLboolean (QGL_DLLEXPORT *m_glIsList)(GLuint list); - GLboolean (QGL_DLLEXPORT *m_glIsTexture)(GLuint texture); - void (QGL_DLLEXPORT *m_glLightModelf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glLightModelfv)(GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glLightModeli)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glLightModeliv)(GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glLightf)(GLenum light, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glLightfv)(GLenum light, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glLighti)(GLenum light, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glLightiv)(GLenum light, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glLineStipple)(GLint factor, GLushort pattern); - void (QGL_DLLEXPORT *m_glLineWidth)(GLfloat width); - void (QGL_DLLEXPORT *m_glListBase)(GLuint base); - void (QGL_DLLEXPORT *m_glLoadIdentity)(void); - void (QGL_DLLEXPORT *m_glLoadMatrixd)(const GLdouble *m); - void (QGL_DLLEXPORT *m_glLoadMatrixf)(const GLfloat *m); - void (QGL_DLLEXPORT *m_glLoadName)(GLuint name); - void (QGL_DLLEXPORT *m_glLogicOp)(GLenum opcode); - void (QGL_DLLEXPORT *m_glMap1d)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); - void (QGL_DLLEXPORT *m_glMap1f)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); - void (QGL_DLLEXPORT *m_glMap2d)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); - void (QGL_DLLEXPORT *m_glMap2f)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); - void (QGL_DLLEXPORT *m_glMapGrid1d)(GLint un, GLdouble u1, GLdouble u2); - void (QGL_DLLEXPORT *m_glMapGrid1f)(GLint un, GLfloat u1, GLfloat u2); - void (QGL_DLLEXPORT *m_glMapGrid2d)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); - void (QGL_DLLEXPORT *m_glMapGrid2f)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); - void (QGL_DLLEXPORT *m_glMaterialf)(GLenum face, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glMaterialfv)(GLenum face, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glMateriali)(GLenum face, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glMaterialiv)(GLenum face, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glMatrixMode)(GLenum mode); - void (QGL_DLLEXPORT *m_glMultMatrixd)(const GLdouble *m); - void (QGL_DLLEXPORT *m_glMultMatrixf)(const GLfloat *m); - void (QGL_DLLEXPORT *m_glNewList)(GLuint list, GLenum mode); - void (QGL_DLLEXPORT *m_glNormal3b)(GLbyte nx, GLbyte ny, GLbyte nz); - void (QGL_DLLEXPORT *m_glNormal3bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glNormal3d)(GLdouble nx, GLdouble ny, GLdouble nz); - void (QGL_DLLEXPORT *m_glNormal3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glNormal3f)(GLfloat nx, GLfloat ny, GLfloat nz); - void (QGL_DLLEXPORT *m_glNormal3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glNormal3i)(GLint nx, GLint ny, GLint nz); - void (QGL_DLLEXPORT *m_glNormal3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glNormal3s)(GLshort nx, GLshort ny, GLshort nz); - void (QGL_DLLEXPORT *m_glNormal3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glNormalPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glOrtho)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); - void (QGL_DLLEXPORT *m_glPassThrough)(GLfloat token); - void (QGL_DLLEXPORT *m_glPixelMapfv)(GLenum map, GLsizei mapsize, const GLfloat *values); - void (QGL_DLLEXPORT *m_glPixelMapuiv)(GLenum map, GLsizei mapsize, const GLuint *values); - void (QGL_DLLEXPORT *m_glPixelMapusv)(GLenum map, GLsizei mapsize, const GLushort *values); - void (QGL_DLLEXPORT *m_glPixelStoref)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glPixelStorei)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glPixelTransferf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glPixelTransferi)(GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glPixelZoom)(GLfloat xfactor, GLfloat yfactor); - void (QGL_DLLEXPORT *m_glPointSize)(GLfloat size); - void (QGL_DLLEXPORT *m_glPolygonMode)(GLenum face, GLenum mode); - void (QGL_DLLEXPORT *m_glPolygonOffset)(GLfloat factor, GLfloat units); - void (QGL_DLLEXPORT *m_glPolygonStipple)(const GLubyte *mask); - void (QGL_DLLEXPORT *m_glPopAttrib)(void); - void (QGL_DLLEXPORT *m_glPopClientAttrib)(void); - void (QGL_DLLEXPORT *m_glPopMatrix)(void); - void (QGL_DLLEXPORT *m_glPopName)(void); - void (QGL_DLLEXPORT *m_glPrioritizeTextures)(GLsizei n, const GLuint *textures, const GLclampf *priorities); - void (QGL_DLLEXPORT *m_glPushAttrib)(GLbitfield mask); - void (QGL_DLLEXPORT *m_glPushClientAttrib)(GLbitfield mask); - void (QGL_DLLEXPORT *m_glPushMatrix)(void); - void (QGL_DLLEXPORT *m_glPushName)(GLuint name); - void (QGL_DLLEXPORT *m_glRasterPos2d)(GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glRasterPos2dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glRasterPos2f)(GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glRasterPos2fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glRasterPos2i)(GLint x, GLint y); - void (QGL_DLLEXPORT *m_glRasterPos2iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glRasterPos2s)(GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glRasterPos2sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glRasterPos3d)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glRasterPos3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glRasterPos3f)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glRasterPos3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glRasterPos3i)(GLint x, GLint y, GLint z); - void (QGL_DLLEXPORT *m_glRasterPos3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glRasterPos3s)(GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glRasterPos3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glRasterPos4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glRasterPos4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glRasterPos4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glRasterPos4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glRasterPos4i)(GLint x, GLint y, GLint z, GLint w); - void (QGL_DLLEXPORT *m_glRasterPos4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glRasterPos4s)(GLshort x, GLshort y, GLshort z, GLshort w); - void (QGL_DLLEXPORT *m_glRasterPos4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glReadBuffer)(GLenum mode); - void (QGL_DLLEXPORT *m_glReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels); - void (QGL_DLLEXPORT *m_glRectd)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); - void (QGL_DLLEXPORT *m_glRectdv)(const GLdouble *v1, const GLdouble *v2); - void (QGL_DLLEXPORT *m_glRectf)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); - void (QGL_DLLEXPORT *m_glRectfv)(const GLfloat *v1, const GLfloat *v2); - void (QGL_DLLEXPORT *m_glRecti)(GLint x1, GLint y1, GLint x2, GLint y2); - void (QGL_DLLEXPORT *m_glRectiv)(const GLint *v1, const GLint *v2); - void (QGL_DLLEXPORT *m_glRects)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); - void (QGL_DLLEXPORT *m_glRectsv)(const GLshort *v1, const GLshort *v2); - GLint (QGL_DLLEXPORT *m_glRenderMode)(GLenum mode); - void (QGL_DLLEXPORT *m_glRotated)(GLdouble anm_gle, GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glRotatef)(GLfloat anm_gle, GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glScaled)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glScalef)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glScissor)(GLint x, GLint y, GLsizei width, GLsizei height); - void (QGL_DLLEXPORT *m_glSelectBuffer)(GLsizei size, GLuint *buffer); - void (QGL_DLLEXPORT *m_glShadeModel)(GLenum mode); - void (QGL_DLLEXPORT *m_glStencilFunc)(GLenum func, GLint ref, GLuint mask); - void (QGL_DLLEXPORT *m_glStencilMask)(GLuint mask); - void (QGL_DLLEXPORT *m_glStencilOp)(GLenum fail, GLenum zfail, GLenum zpass); - void (QGL_DLLEXPORT *m_glTexCoord1d)(GLdouble s); - void (QGL_DLLEXPORT *m_glTexCoord1dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord1f)(GLfloat s); - void (QGL_DLLEXPORT *m_glTexCoord1fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord1i)(GLint s); - void (QGL_DLLEXPORT *m_glTexCoord1iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord1s)(GLshort s); - void (QGL_DLLEXPORT *m_glTexCoord1sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoord2d)(GLdouble s, GLdouble t); - void (QGL_DLLEXPORT *m_glTexCoord2dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord2f)(GLfloat s, GLfloat t); - void (QGL_DLLEXPORT *m_glTexCoord2fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord2i)(GLint s, GLint t); - void (QGL_DLLEXPORT *m_glTexCoord2iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord2s)(GLshort s, GLshort t); - void (QGL_DLLEXPORT *m_glTexCoord2sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoord3d)(GLdouble s, GLdouble t, GLdouble r); - void (QGL_DLLEXPORT *m_glTexCoord3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord3f)(GLfloat s, GLfloat t, GLfloat r); - void (QGL_DLLEXPORT *m_glTexCoord3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord3i)(GLint s, GLint t, GLint r); - void (QGL_DLLEXPORT *m_glTexCoord3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord3s)(GLshort s, GLshort t, GLshort r); - void (QGL_DLLEXPORT *m_glTexCoord3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoord4d)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); - void (QGL_DLLEXPORT *m_glTexCoord4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glTexCoord4f)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); - void (QGL_DLLEXPORT *m_glTexCoord4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glTexCoord4i)(GLint s, GLint t, GLint r, GLint q); - void (QGL_DLLEXPORT *m_glTexCoord4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glTexCoord4s)(GLshort s, GLshort t, GLshort r, GLshort q); - void (QGL_DLLEXPORT *m_glTexCoord4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glTexCoordPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glTexEnvf)(GLenum target, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glTexEnvfv)(GLenum target, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glTexEnvi)(GLenum target, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glTexEnviv)(GLenum target, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glTexGend)(GLenum coord, GLenum pname, GLdouble param); - void (QGL_DLLEXPORT *m_glTexGendv)(GLenum coord, GLenum pname, const GLdouble *params); - void (QGL_DLLEXPORT *m_glTexGenf)(GLenum coord, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glTexGenfv)(GLenum coord, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glTexGeni)(GLenum coord, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glTexGeniv)(GLenum coord, GLenum pname, const GLint *params); -#if defined(MACVERSION) && MACVERSION > 15 - //Snow Leopard 16, Leopard 15, Tiger 14, Panther 13, ... - void (QGL_DLLEXPORT *m_glTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); -#else - void (QGL_DLLEXPORT *m_glTexImage1D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); -#endif - void (QGL_DLLEXPORT *m_glTexParameterf)(GLenum target, GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glTexParameterfv)(GLenum target, GLenum pname, const GLfloat *params); - void (QGL_DLLEXPORT *m_glTexParameteri)(GLenum target, GLenum pname, GLint param); - void (QGL_DLLEXPORT *m_glTexParameteriv)(GLenum target, GLenum pname, const GLint *params); - void (QGL_DLLEXPORT *m_glTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTranslated)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glTranslatef)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glVertex2d)(GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glVertex2dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertex2f)(GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glVertex2fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertex2i)(GLint x, GLint y); - void (QGL_DLLEXPORT *m_glVertex2iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glVertex2s)(GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glVertex2sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glVertex3d)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glVertex3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertex3f)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glVertex3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertex3i)(GLint x, GLint y, GLint z); - void (QGL_DLLEXPORT *m_glVertex3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glVertex3s)(GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glVertex3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glVertex4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glVertex4dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertex4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glVertex4fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertex4i)(GLint x, GLint y, GLint z, GLint w); - void (QGL_DLLEXPORT *m_glVertex4iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glVertex4s)(GLshort x, GLshort y, GLshort z, GLshort w); - void (QGL_DLLEXPORT *m_glVertex4sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glViewport)(GLint x, GLint y, GLsizei width, GLsizei height); - - // GL_ARB_multitexture - bool support_ARB_multitexture; - bool ARB_multitexture() - { - return support_ARB_multitexture; - } - void (QGL_DLLEXPORT *m_glActiveTextureARB)(GLenum texture); - void (QGL_DLLEXPORT *m_glClientActiveTextureARB)(GLenum texture); - void (QGL_DLLEXPORT *m_glMultiTexCoord1dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1svARB)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord2svARB)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord3svARB)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4dARB)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4dvARB)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4fARB)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4fvARB)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4iARB)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4ivARB)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4sARB)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord4svARB)(GLenum target, const GLshort *v); - - // ARB_texture_compression - bool support_ARB_texture_compression; - bool ARB_texture_compression() - { - return support_ARB_texture_compression; - } - void (QGL_DLLEXPORT *m_glCompressedTexImage3DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexImage2DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexImage1DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage3DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage2DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage1DARB)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid* data); - void (QGL_DLLEXPORT *m_glGetCompressedTexImageARB)(GLenum target, GLint lod, GLvoid* img); - - // EXT_texture_compression_s3tc - bool support_EXT_texture_compression_s3tc; - bool EXT_texture_compression_s3tc() - { - return support_EXT_texture_compression_s3tc; - } - - // GL 1.2 - bool support_GL_1_2; - bool GL_1_2() - { - return support_GL_1_2; - } - void (QGL_DLLEXPORT *m_glCopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); - void (QGL_DLLEXPORT *m_glDrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); - void (QGL_DLLEXPORT *m_glTexImage3D)(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); - void (QGL_DLLEXPORT *m_glTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); - - // GL 1.3 - bool support_GL_1_3; - bool GL_1_3() - { - return support_GL_1_3; - } - void (QGL_DLLEXPORT *m_glActiveTexture)(GLenum texture); - void (QGL_DLLEXPORT *m_glClientActiveTexture)(GLenum texture); - void (QGL_DLLEXPORT *m_glCompressedTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glCompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); - void (QGL_DLLEXPORT *m_glGetCompressedTexImage)(GLenum target, GLint lod, GLvoid *img); - void (QGL_DLLEXPORT *m_glLoadTransposeMatrixd)(const GLdouble m[16]); - void (QGL_DLLEXPORT *m_glLoadTransposeMatrixf)(const GLfloat m[16]); - void (QGL_DLLEXPORT *m_glMultTransposeMatrixd)(const GLdouble m[16]); - void (QGL_DLLEXPORT *m_glMultTransposeMatrixf)(const GLfloat m[16]); - void (QGL_DLLEXPORT *m_glMultiTexCoord1d)(GLenum target, GLdouble s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1f)(GLenum target, GLfloat s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1i)(GLenum target, GLint s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord1s)(GLenum target, GLshort s); - void (QGL_DLLEXPORT *m_glMultiTexCoord1sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2d)(GLenum target, GLdouble s, GLdouble t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2f)(GLenum target, GLfloat s, GLfloat t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2i)(GLenum target, GLint s, GLint t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord2s)(GLenum target, GLshort s, GLshort t); - void (QGL_DLLEXPORT *m_glMultiTexCoord2sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3d)(GLenum target, GLdouble s, GLdouble t, GLdouble r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3f)(GLenum target, GLfloat s, GLfloat t, GLfloat r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3i)(GLenum target, GLint s, GLint t, GLint r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord3s)(GLenum target, GLshort s, GLshort t, GLshort r); - void (QGL_DLLEXPORT *m_glMultiTexCoord3sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4d)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4dv)(GLenum target, const GLdouble *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4f)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4fv)(GLenum target, const GLfloat *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4i)(GLenum target, GLint s, GLint t, GLint r, GLint q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4iv)(GLenum target, const GLint *v); - void (QGL_DLLEXPORT *m_glMultiTexCoord4s)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); - void (QGL_DLLEXPORT *m_glMultiTexCoord4sv)(GLenum target, const GLshort *v); - void (QGL_DLLEXPORT *m_glSampleCoverage)(GLclampf value, GLboolean invert); - - // GL 1.4 - bool support_GL_1_4; - bool GL_1_4() - { - return support_GL_1_4; - } - void (QGL_DLLEXPORT *m_glBlendColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); - void (QGL_DLLEXPORT *m_glBlendEquation)(GLenum mode); - void (QGL_DLLEXPORT *m_glBlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); - void (QGL_DLLEXPORT *m_glFogCoordPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glFogCoordd)(GLdouble coord); - void (QGL_DLLEXPORT *m_glFogCoorddv)(const GLdouble *coord); - void (QGL_DLLEXPORT *m_glFogCoordf)(GLfloat coord); - void (QGL_DLLEXPORT *m_glFogCoordfv)(const GLfloat *coord); - void (QGL_DLLEXPORT *m_glMultiDrawArrays)(GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); - void (QGL_DLLEXPORT *m_glMultiDrawElements)(GLenum mode, GLsizei *count, GLenum type, const GLvoid **indices, GLsizei primcount); - void (QGL_DLLEXPORT *m_glPointParameterf)(GLenum pname, GLfloat param); - void (QGL_DLLEXPORT *m_glPointParameterfv)(GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glSecondaryColor3b)(GLbyte red, GLbyte green, GLbyte blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3bv)(const GLbyte *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3d)(GLdouble red, GLdouble green, GLdouble blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3dv)(const GLdouble *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3f)(GLfloat red, GLfloat green, GLfloat blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3fv)(const GLfloat *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3i)(GLint red, GLint green, GLint blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3iv)(const GLint *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3s)(GLshort red, GLshort green, GLshort blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3sv)(const GLshort *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3ub)(GLubyte red, GLubyte green, GLubyte blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3ubv)(const GLubyte *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3ui)(GLuint red, GLuint green, GLuint blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3uiv)(const GLuint *v); - void (QGL_DLLEXPORT *m_glSecondaryColor3us)(GLushort red, GLushort green, GLushort blue); - void (QGL_DLLEXPORT *m_glSecondaryColor3usv)(const GLushort *v); - void (QGL_DLLEXPORT *m_glSecondaryColorPointer)(GLint size, GLenum type, GLsizei stride, GLvoid *pointer); - void (QGL_DLLEXPORT *m_glWindowPos2d)(GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glWindowPos2dv)(const GLdouble *p); - void (QGL_DLLEXPORT *m_glWindowPos2f)(GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glWindowPos2fv)(const GLfloat *p); - void (QGL_DLLEXPORT *m_glWindowPos2i)(GLint x, GLint y); - void (QGL_DLLEXPORT *m_glWindowPos2iv)(const GLint *p); - void (QGL_DLLEXPORT *m_glWindowPos2s)(GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glWindowPos2sv)(const GLshort *p); - void (QGL_DLLEXPORT *m_glWindowPos3d)(GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glWindowPos3dv)(const GLdouble *p); - void (QGL_DLLEXPORT *m_glWindowPos3f)(GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glWindowPos3fv)(const GLfloat *p); - void (QGL_DLLEXPORT *m_glWindowPos3i)(GLint x, GLint y, GLint z); - void (QGL_DLLEXPORT *m_glWindowPos3iv)(const GLint *p); - void (QGL_DLLEXPORT *m_glWindowPos3s)(GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glWindowPos3sv)(const GLshort *p); - - // GL 1.5 - bool support_GL_1_5; - bool GL_1_5() - { - return support_GL_1_5; - } - void (QGL_DLLEXPORT *m_glBeginQuery)(GLenum target, GLuint id); - void (QGL_DLLEXPORT *m_glBindBuffer)(GLenum target, GLuint buffer); - void (QGL_DLLEXPORT *m_glBufferData)(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage); - void (QGL_DLLEXPORT *m_glBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data); - void (QGL_DLLEXPORT *m_glDeleteBuffers)(GLsizei n, const GLuint* buffers); - void (QGL_DLLEXPORT *m_glDeleteQueries)(GLsizei n, const GLuint* ids); - void (QGL_DLLEXPORT *m_glEndQuery)(GLenum target); - void (QGL_DLLEXPORT *m_glGenBuffers)(GLsizei n, GLuint* buffers); - void (QGL_DLLEXPORT *m_glGenQueries)(GLsizei n, GLuint* ids); - void (QGL_DLLEXPORT *m_glGetBufferParameteriv)(GLenum target, GLenum pname, GLint* params); - void (QGL_DLLEXPORT *m_glGetBufferPointerv)(GLenum target, GLenum pname, GLvoid** params); - void (QGL_DLLEXPORT *m_glGetBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, GLvoid* data); - void (QGL_DLLEXPORT *m_glGetQueryObjectiv)(GLuint id, GLenum pname, GLint* params); - void (QGL_DLLEXPORT *m_glGetQueryObjectuiv)(GLuint id, GLenum pname, GLuint* params); - void (QGL_DLLEXPORT *m_glGetQueryiv)(GLenum target, GLenum pname, GLint params); - GLboolean (QGL_DLLEXPORT *m_glIsBuffer)(GLuint buffer); - GLboolean (QGL_DLLEXPORT *m_glIsQuery)(GLuint id); - GLvoid* (QGL_DLLEXPORT *m_glMapBuffer)(GLenum target, GLenum access); - GLboolean (QGL_DLLEXPORT *m_glUnmapBuffer)(GLenum target); - - // GL_ARB_vertex_program - bool support_ARB_vertex_program; - bool ARB_vertex_program() - { - return support_ARB_vertex_program; - } - void (QGL_DLLEXPORT *m_glVertexAttrib1sARB)(GLuint index, GLshort x); - void (QGL_DLLEXPORT *m_glVertexAttrib1fARB)(GLuint index, GLfloat x); - void (QGL_DLLEXPORT *m_glVertexAttrib1dARB)(GLuint index, GLdouble x); - void (QGL_DLLEXPORT *m_glVertexAttrib2sARB)(GLuint index, GLshort x, GLshort y); - void (QGL_DLLEXPORT *m_glVertexAttrib2fARB)(GLuint index, GLfloat x, GLfloat y); - void (QGL_DLLEXPORT *m_glVertexAttrib2dARB)(GLuint index, GLdouble x, GLdouble y); - void (QGL_DLLEXPORT *m_glVertexAttrib3sARB)(GLuint index, GLshort x, GLshort y, GLshort z); - void (QGL_DLLEXPORT *m_glVertexAttrib3fARB)(GLuint index, GLfloat x, GLfloat y, GLfloat z); - void (QGL_DLLEXPORT *m_glVertexAttrib3dARB)(GLuint index, GLdouble x, GLdouble y, GLdouble z); - void (QGL_DLLEXPORT *m_glVertexAttrib4sARB)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); - void (QGL_DLLEXPORT *m_glVertexAttrib4fARB)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glVertexAttrib4dARB)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubARB)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); - void (QGL_DLLEXPORT *m_glVertexAttrib1svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4bvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4usvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4uivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NbvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NsvARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NusvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NuivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttribPointerARB)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB)(GLuint index); - void (QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB)(GLuint index); - void (QGL_DLLEXPORT *m_glProgramStringARB)(GLenum target, GLenum format, GLsizei len, const GLvoid *string); - void (QGL_DLLEXPORT *m_glBindProgramARB)(GLenum target, GLuint program); - void (QGL_DLLEXPORT *m_glDeleteProgramsARB)(GLsizei n, const GLuint *programs); - void (QGL_DLLEXPORT *m_glGenProgramsARB)(GLsizei n, GLuint *programs); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4dARB)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4dvARB)(GLenum target, GLuint index, const GLdouble *params); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4fARB)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glProgramEnvParameter4fvARB)(GLenum target, GLuint index, const GLfloat *params); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4dARB)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4dvARB)(GLenum target, GLuint index, const GLdouble *params); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4fARB)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); - void (QGL_DLLEXPORT *m_glProgramLocalParameter4fvARB)(GLenum target, GLuint index, const GLfloat *params); - void (QGL_DLLEXPORT *m_glGetProgramEnvParameterdvARB)(GLenum target, GLuint index, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetProgramEnvParameterfvARB)(GLenum target, GLuint index, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetProgramLocalParameterdvARB)(GLenum target, GLuint index, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetProgramLocalParameterfvARB)(GLenum target, GLuint index, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetProgramivARB)(GLenum target, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetProgramStringARB)(GLenum target, GLenum pname, GLvoid *string); - void (QGL_DLLEXPORT *m_glGetVertexAttribdvARB)(GLuint index, GLenum pname, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribfvARB)(GLuint index, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribivARB)(GLuint index, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribPointervARB)(GLuint index, GLenum pname, GLvoid **pointer); - GLboolean (QGL_DLLEXPORT *m_glIsProgramARB)(GLuint program); - - // GL_ARB_fragment_program - bool support_ARB_fragment_program; - bool ARB_fragment_program() - { - return support_ARB_fragment_program; - } - - // GL_ARB_shader_objects - bool support_ARB_shader_objects; - bool ARB_shader_objects() - { - return support_ARB_shader_objects; - } - void (QGL_DLLEXPORT *m_glDeleteObjectARB)(GLhandleARB obj); - GLhandleARB (QGL_DLLEXPORT *m_glGetHandleARB)(GLenum pname); - void (QGL_DLLEXPORT *m_glDetachObjectARB)(GLhandleARB containerObj, GLhandleARB attachedObj); - GLhandleARB (QGL_DLLEXPORT *m_glCreateShaderObjectARB)(GLenum shaderType); - void (QGL_DLLEXPORT *m_glShaderSourceARB)(GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); - void (QGL_DLLEXPORT *m_glCompileShaderARB)(GLhandleARB shaderObj); - GLhandleARB (QGL_DLLEXPORT *m_glCreateProgramObjectARB)(void); - void (QGL_DLLEXPORT *m_glAttachObjectARB)(GLhandleARB containerObj, GLhandleARB obj); - void (QGL_DLLEXPORT *m_glLinkProgramARB)(GLhandleARB programObj); - void (QGL_DLLEXPORT *m_glUseProgramObjectARB)(GLhandleARB programObj); - void (QGL_DLLEXPORT *m_glValidateProgramARB)(GLhandleARB programObj); - void (QGL_DLLEXPORT *m_glUniform1fARB)(GLint location, GLfloat v0); - void (QGL_DLLEXPORT *m_glUniform2fARB)(GLint location, GLfloat v0, GLfloat v1); - void (QGL_DLLEXPORT *m_glUniform3fARB)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); - void (QGL_DLLEXPORT *m_glUniform4fARB)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); - void (QGL_DLLEXPORT *m_glUniform1iARB)(GLint location, GLint v0); - void (QGL_DLLEXPORT *m_glUniform2iARB)(GLint location, GLint v0, GLint v1); - void (QGL_DLLEXPORT *m_glUniform3iARB)(GLint location, GLint v0, GLint v1, GLint v2); - void (QGL_DLLEXPORT *m_glUniform4iARB)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); - void (QGL_DLLEXPORT *m_glUniform1fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform2fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform3fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform4fvARB)(GLint location, GLsizei count, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniform1ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniform2ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniform3ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniform4ivARB)(GLint location, GLsizei count, const GLint *value); - void (QGL_DLLEXPORT *m_glUniformMatrix2fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniformMatrix3fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); - void (QGL_DLLEXPORT *m_glUniformMatrix4fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); - void (QGL_DLLEXPORT *m_glGetObjectParameterfvARB)(GLhandleARB obj, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetObjectParameterivARB)(GLhandleARB obj, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetInfoLogARB)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); - void (QGL_DLLEXPORT *m_glGetAttachedObjectsARB)(GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); - GLint (QGL_DLLEXPORT *m_glGetUniformLocationARB)(GLhandleARB programObj, const GLcharARB *name); - void (QGL_DLLEXPORT *m_glGetActiveUniformARB)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); - void (QGL_DLLEXPORT *m_glGetUniformfvARB)(GLhandleARB programObj, GLint location, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetUniformivARB)(GLhandleARB programObj, GLint location, GLint *params); - void (QGL_DLLEXPORT *m_glGetShaderSourceARB)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); - - // GL_ARB_vertex_shader - bool support_ARB_vertex_shader; - bool ARB_vertex_shader() - { - return support_ARB_vertex_shader; - } -#if 0 - void (QGL_DLLEXPORT *m_glVertexAttrib1fARB)(GLuint index, GLfloat v0); - void (QGL_DLLEXPORT *m_glVertexAttrib1sARB)(GLuint index, GLshort v0); - void (QGL_DLLEXPORT *m_glVertexAttrib1dARB)(GLuint index, GLdouble v0); - void (QGL_DLLEXPORT *m_glVertexAttrib2fARB)(GLuint index, GLfloat v0, GLfloat v1); - void (QGL_DLLEXPORT *m_glVertexAttrib2sARB)(GLuint index, GLshort v0, GLshort v1); - void (QGL_DLLEXPORT *m_glVertexAttrib2dARB)(GLuint index, GLdouble v0, GLdouble v1); - void (QGL_DLLEXPORT *m_glVertexAttrib3fARB)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2); - void (QGL_DLLEXPORT *m_glVertexAttrib3sARB)(GLuint index, GLshort v0, GLshort v1, GLshort v2); - void (QGL_DLLEXPORT *m_glVertexAttrib3dARB)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2); - void (QGL_DLLEXPORT *m_glVertexAttrib4fARB)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); - void (QGL_DLLEXPORT *m_glVertexAttrib4sARB)(GLuint index, GLshort v0, GLshort v1, GLshort v2, GLshort v3); - void (QGL_DLLEXPORT *m_glVertexAttrib4dARB)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubARB)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); - void (QGL_DLLEXPORT *m_glVertexAttrib1fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib1dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib2dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib3dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4fvARB)(GLuint index, const GLfloat *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4svARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4dvARB)(GLuint index, const GLdouble *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4bvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4ubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4usvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4uivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NbvARB)(GLuint index, const GLbyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NsvARB)(GLuint index, const GLshort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NivARB)(GLuint index, const GLint *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NubvARB)(GLuint index, const GLubyte *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NusvARB)(GLuint index, const GLushort *v); - void (QGL_DLLEXPORT *m_glVertexAttrib4NuivARB)(GLuint index, const GLuint *v); - void (QGL_DLLEXPORT *m_glVertexAttribPointerARB)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); - void (QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB)(GLuint index); - void (QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB)(GLuint index); -#endif - void (QGL_DLLEXPORT *m_glBindAttribLocationARB)(GLhandleARB programObj, GLuint index, const GLcharARB *name); - void (QGL_DLLEXPORT *m_glGetActiveAttribARB)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); - GLint (QGL_DLLEXPORT *m_glGetAttribLocationARB)(GLhandleARB programObj, const GLcharARB *name); -#if 0 - void (QGL_DLLEXPORT *m_glGetVertexAttribdvARB)(GLuint index, GLenum pname, GLdouble *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribfvARB)(GLuint index, GLenum pname, GLfloat *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribivARB)(GLuint index, GLenum pname, GLint *params); - void (QGL_DLLEXPORT *m_glGetVertexAttribPointervARB)(GLuint index, GLenum pname, GLvoid **pointer); -#endif - - // ARB_fragment_shader - bool support_ARB_fragment_shader; - bool ARB_fragment_shader() - { - return support_ARB_fragment_shader; - } - - // ARB_shading_language_100 - bool support_ARB_shading_language_100; - bool ARB_shading_language_100() - { - return support_ARB_shading_language_100; - } - - // GL_NV_vertex_program2 - bool support_NV_vertex_program2; - bool NV_vertex_program2() - { - return support_NV_vertex_program2; - } - GLboolean (QGL_DLLEXPORT* m_glAreProgramsResidentNV)(GLsizei, const GLuint *, GLboolean *); - void (QGL_DLLEXPORT* m_glBindProgramNV)(GLenum, GLuint); - void (QGL_DLLEXPORT* m_glDeleteProgramsNV)(GLsizei, const GLuint *); - void (QGL_DLLEXPORT* m_glExecuteProgramNV)(GLenum, GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glGenProgramsNV)(GLsizei, GLuint *); - void (QGL_DLLEXPORT* m_glGetProgramParameterdvNV)(GLenum, GLuint, GLenum, GLdouble *); - void (QGL_DLLEXPORT* m_glGetProgramParameterfvNV)(GLenum, GLuint, GLenum, GLfloat *); - void (QGL_DLLEXPORT* m_glGetProgramivNV)(GLuint, GLenum, GLint *); - void (QGL_DLLEXPORT* m_glGetProgramStringNV)(GLuint, GLenum, GLubyte *); - void (QGL_DLLEXPORT* m_glGetTrackMatrixivNV)(GLenum, GLuint, GLenum, GLint *); - void (QGL_DLLEXPORT* m_glGetVertexAttribdvNV)(GLuint, GLenum, GLdouble *); - void (QGL_DLLEXPORT* m_glGetVertexAttribfvNV)(GLuint, GLenum, GLfloat *); - void (QGL_DLLEXPORT* m_glGetVertexAttribivNV)(GLuint, GLenum, GLint *); - void (QGL_DLLEXPORT* m_glGetVertexAttribPointervNV)(GLuint, GLenum, GLvoid* *); - GLboolean (QGL_DLLEXPORT* m_glIsProgramNV)(GLuint); - void (QGL_DLLEXPORT* m_glLoadProgramNV)(GLenum, GLuint, GLsizei, const GLubyte *); - void (QGL_DLLEXPORT* m_glProgramParameter4fNV)(GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glProgramParameter4fvNV)(GLenum, GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glProgramParameters4fvNV)(GLenum, GLuint, GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glRequestResidentProgramsNV)(GLsizei, const GLuint *); - void (QGL_DLLEXPORT* m_glTrackMatrixNV)(GLenum, GLuint, GLenum, GLenum); - void (QGL_DLLEXPORT* m_glVertexAttribPointerNV)(GLuint, GLint, GLenum, GLsizei, const GLvoid *); - void (QGL_DLLEXPORT* m_glVertexAttrib1fNV)(GLuint, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib1fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttrib2fNV)(GLuint, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib2fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttrib3fNV)(GLuint, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib3fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttrib4fNV)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glVertexAttrib4fvNV)(GLuint, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs1fvNV)(GLuint, GLsizei, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs2fvNV)(GLuint, GLsizei, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs3fvNV)(GLuint, GLsizei, const GLfloat *); - void (QGL_DLLEXPORT* m_glVertexAttribs4fvNV)(GLuint, GLsizei, const GLfloat *); - - // GL_NV_fragment_program - bool support_NV_fragment_program; - bool NV_fragment_program() - { - return support_NV_fragment_program; - } - void (QGL_DLLEXPORT* m_glProgramNamedParameter4fNV)(GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat); - void (QGL_DLLEXPORT* m_glProgramNamedParameter4fvNV)(GLuint, GLsizei, const GLubyte *, const GLfloat *); - void (QGL_DLLEXPORT* m_glGetProgramNamedParameterfvNV)(GLuint, GLsizei, const GLubyte *, GLfloat *); -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalOpenGLModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalOpenGLModuleRef; - -inline OpenGLBinding& GlobalOpenGL() -{ - return GlobalOpenGLModule::getTable(); -} - -#if defined(_DEBUG) -#define GlobalOpenGL_debugAssertNoErrors() GlobalOpenGL().assertNoErrors(__FILE__, __LINE__) -#else -#define GlobalOpenGL_debugAssertNoErrors() -#endif - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iglrender.cpp b/misc/mediasource/extra/netradiant-src/include/iglrender.cpp deleted file mode 100644 index 26d66ae0..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iglrender.cpp +++ /dev/null @@ -1,3 +0,0 @@ - -#include "iglrender.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iglrender.h b/misc/mediasource/extra/netradiant-src/include/iglrender.h deleted file mode 100644 index 76216026..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iglrender.h +++ /dev/null @@ -1,130 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IGLRENDER_H) -#define INCLUDED_IGLRENDER_H - -#include "igl.h" -#include "generic/vector.h" -class AABB; -class Matrix4; - - -class GLProgram -{ -public: - virtual void enable() = 0; - virtual void disable() = 0; - virtual void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) = 0; -}; - -class OpenGLFogState -{ -public: - OpenGLFogState() : mode(GL_EXP), density(0), start(0), end(0), index(0), colour(1, 1, 1, 1) - { - } - GLenum mode; - GLfloat density; - GLfloat start; - GLfloat end; - GLint index; - Vector4 colour; -}; - -//! A collection of opengl state information. -class OpenGLState -{ -public: - enum ESort - { - eSortFirst = 0, - eSortOpaque = 1, - eSortMultiFirst = 2, - eSortMultiLast = 1023, - eSortOverbrighten = 1024, - eSortFullbright = 1025, - eSortHighlight = 1026, - eSortTranslucent = 1027, - eSortOverlayFirst = 1028, - eSortOverlayLast = 2047, - eSortControlFirst = 2048, - eSortControlLast = 3071, - eSortGUI0 = 3072, - eSortGUI1 = 3073, - eSortLast = 4096, - }; - - unsigned int m_state; - std::size_t m_sort; - GLint m_texture; - GLint m_texture1; - GLint m_texture2; - GLint m_texture3; - GLint m_texture4; - GLint m_texture5; - GLint m_texture6; - GLint m_texture7; - Vector4 m_colour; - GLenum m_blend_src, m_blend_dst; - GLenum m_depthfunc; - GLenum m_alphafunc; - GLfloat m_alpharef; - GLfloat m_linewidth; - GLfloat m_pointsize; - GLint m_linestipple_factor; - GLushort m_linestipple_pattern; - OpenGLFogState m_fog; - GLProgram* m_program; - - OpenGLState() : m_program(0) - { - } -}; - -class OpenGLStateLibrary -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "openglshaderlibrary"); - - virtual void getDefaultState(OpenGLState& state) const = 0; - - virtual void insert(const char* name, const OpenGLState& state) = 0; - virtual void erase(const char* name) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalOpenGLStateLibraryModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalOpenGLStateLibraryModuleRef; - -inline OpenGLStateLibrary& GlobalOpenGLStateLibrary() -{ - return GlobalOpenGLStateLibraryModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/igtkgl.cpp b/misc/mediasource/extra/netradiant-src/include/igtkgl.cpp deleted file mode 100644 index 1180d547..00000000 --- a/misc/mediasource/extra/netradiant-src/include/igtkgl.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "igtkgl.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/igtkgl.h b/misc/mediasource/extra/netradiant-src/include/igtkgl.h deleted file mode 100644 index 6a0a631f..00000000 --- a/misc/mediasource/extra/netradiant-src/include/igtkgl.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IGTKGL_H) -#define INCLUDED_IGTKGL_H - -#include "generic/constant.h" - -typedef struct _GtkWidget GtkWidget; -typedef int gint; -typedef gint gboolean; - -struct _QERGtkGLTable -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "gtkgl"); - - GtkWidget* (*glwidget_new)(gboolean zbufffer); - void (*glwidget_swap_buffers)(GtkWidget* widget); - gboolean(*glwidget_make_current)(GtkWidget* widget); - void (*glwidget_destroy_context)(GtkWidget* widget); - void (*glwidget_create_context)(GtkWidget* widget); -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iimage.cpp b/misc/mediasource/extra/netradiant-src/include/iimage.cpp deleted file mode 100644 index a95ab6d3..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iimage.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "iimage.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iimage.h b/misc/mediasource/extra/netradiant-src/include/iimage.h deleted file mode 100644 index f6020bd8..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iimage.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IIMAGE_H) -#define INCLUDED_IIMAGE_H - -#include "generic/constant.h" - -typedef unsigned char byte; - -class Image -{ -public: - virtual void release() = 0; - virtual byte* getRGBAPixels() const = 0; - virtual unsigned int getWidth() const = 0; - virtual unsigned int getHeight() const = 0; - - virtual int getSurfaceFlags() const - { - return 0; - } - virtual int getContentFlags() const - { - return 0; - } - virtual int getValue() const - { - return 0; - } -}; - -class ArchiveFile; - -struct _QERPlugImageTable -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "image"); - - /// Read an image from the file. - /// Returns 0 if the image could not be read. - Image* (*loadImage)(ArchiveFile& file); -}; - -template -class ModuleRef; -typedef ModuleRef<_QERPlugImageTable> ImageModuleRef; - -template -class Modules; -typedef Modules<_QERPlugImageTable> ImageModules; - -template -class ModulesRef; -typedef ModulesRef<_QERPlugImageTable> ImageModulesRef; - -#endif // _IIMAGE_H diff --git a/misc/mediasource/extra/netradiant-src/include/imap.cpp b/misc/mediasource/extra/netradiant-src/include/imap.cpp deleted file mode 100644 index 0b363b5e..00000000 --- a/misc/mediasource/extra/netradiant-src/include/imap.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "imap.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/imap.h b/misc/mediasource/extra/netradiant-src/include/imap.h deleted file mode 100644 index c97a2ff2..00000000 --- a/misc/mediasource/extra/netradiant-src/include/imap.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IMAP_H) -#define INCLUDED_IMAP_H - -#include "generic/constant.h" - -class Tokeniser; -class TokenWriter; - -/// \brief A node whose state can be imported from a token stream. -class MapImporter -{ -public: - STRING_CONSTANT(Name, "MapImporter"); - - virtual bool importTokens(Tokeniser& tokeniser) = 0; -}; - -/// \brief A node whose state can be exported to a token stream. -class MapExporter -{ -public: - STRING_CONSTANT(Name, "MapExporter"); - - virtual void exportTokens(TokenWriter& writer) const = 0; -}; - -#include "iscenegraph.h" - -class EntityCreator; - -class TextInputStream; -class TextOutputStream; - - -typedef void(*GraphTraversalFunc)(scene::Node& root, const scene::Traversable::Walker& walker); - -/// \brief A module that reads and writes a map in a specific format. -class MapFormat -{ -public: - INTEGER_CONSTANT(Version, 2); - STRING_CONSTANT(Name, "map"); - mutable bool wrongFormat; - - /// \brief Read a map graph into \p root from \p outputStream, using \p entityTable to create entities. - virtual void readGraph(scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable) const = 0; - /// \brief Write the map graph obtained by applying \p traverse to \p root into \p outputStream. - virtual void writeGraph(scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream) const = 0; -}; - - -template -class Modules; -typedef Modules MapModules; - -template -class ModulesRef; -typedef ModulesRef MapModulesRef; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/imodel.cpp b/misc/mediasource/extra/netradiant-src/include/imodel.cpp deleted file mode 100644 index 081dccac..00000000 --- a/misc/mediasource/extra/netradiant-src/include/imodel.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "imodel.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/imodel.h b/misc/mediasource/extra/netradiant-src/include/imodel.h deleted file mode 100644 index aa040d63..00000000 --- a/misc/mediasource/extra/netradiant-src/include/imodel.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IMODEL_H) -#define INCLUDED_IMODEL_H - -#include "generic/constant.h" - -namespace scene -{ - class Node; -} - -class ArchiveFile; - -class ModelLoader -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "model"); - virtual scene::Node& loadModel(ArchiveFile& file) = 0; -}; - -template -class Modules; -typedef Modules ModelModules; - -template -class ModulesRef; -typedef ModulesRef ModelModulesRef; - -#endif /* _IMODEL_H_ */ diff --git a/misc/mediasource/extra/netradiant-src/include/ipatch.cpp b/misc/mediasource/extra/netradiant-src/include/ipatch.cpp deleted file mode 100644 index 940a1bed..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ipatch.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "ipatch.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ipatch.h b/misc/mediasource/extra/netradiant-src/include/ipatch.h deleted file mode 100644 index 48ce39b5..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ipatch.h +++ /dev/null @@ -1,292 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IPATCH_H) -#define INCLUDED_IPATCH_H - -#include "generic/constant.h" -#include "generic/vector.h" - -namespace scene -{ - class Node; -} - -template -class ArrayReference -{ - std::size_t m_size; - Element* m_data; -public: - typedef Element value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; - - ArrayReference() - : m_size(0), m_data(0) - { - } - ArrayReference(std::size_t size, Element* data) - : m_size(size), m_data(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; - } -}; - -#if 0 -template -class MatrixIterator -{ - Element* m_position; - - void increment() - { - ++m_position; - } - -public: - typedef std::bidirectional_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; - - MatrixIterator(Element* position) : m_position(position) - { - } - - Element* position() - { - return m_position; - } - - bool operator==(const MatrixIterator& other) const - { - return m_position == other.m_position; - } - bool operator!=(const MatrixIterator& other) const - { - return !operator==(other); - } - MatrixIterator& operator++() - { - increment(); - return *this; - } - MatrixIterator operator++(int) - { - MatrixIterator tmp = *this; - increment(); - return tmp; - } - value_type& operator*() const - { - return m_position->m_value; - } - value_type* operator->() const - { - return &(operator*()); - } -}; -#endif - -template -class Matrix -{ - std::size_t m_x, m_y; - Element* m_data; -public: - typedef Element value_type; - typedef value_type* iterator; - typedef const value_type* const_iterator; - - Matrix() - : m_x(0), m_y(0), m_data(0) - { - } - Matrix(std::size_t x, std::size_t y, Element* data) - : m_x(x), m_y(y), m_data(data) - { - } - - iterator begin() - { - return m_data; - } - const_iterator begin() const - { - return m_data; - } - iterator end() - { - return m_data + size(); - } - const_iterator end() const - { - return m_data + 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& operator()(std::size_t x, std::size_t y) - { -#if defined(_DEBUG) - ASSERT_MESSAGE(x < m_x && y < m_y, "array index out of bounds"); -#endif - return m_data[x * m_y + y]; - } - const value_type& operator()(std::size_t x, std::size_t y) const - { -#if defined(_DEBUG) - ASSERT_MESSAGE(x < m_x && y < m_y, "array index out of bounds"); -#endif - return m_data[x * m_y + y]; - } - value_type* data() - { - return m_data; - } - const value_type* data() const - { - return m_data; - } - std::size_t x() const - { - return m_x; - } - std::size_t y() const - { - return m_y; - } - std::size_t size() const - { - return m_x * m_y; - } - bool empty() const - { - return m_x == 0; - } -}; - -class PatchControl -{ -public: - Vector3 m_vertex; - Vector2 m_texcoord; -}; - -typedef Matrix PatchControlMatrix; - - -class PatchCreator -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "patch"); - virtual scene::Node& createPatch() = 0; - virtual void Patch_undoSave(scene::Node& patch) const = 0; - virtual void Patch_resize(scene::Node& patch, std::size_t width, std::size_t height) const = 0; - virtual PatchControlMatrix Patch_getControlPoints(scene::Node& patch) const = 0; - virtual void Patch_controlPointsChanged(scene::Node& patch) const = 0; - virtual const char* Patch_getShader(scene::Node& patch) const = 0; - virtual void Patch_setShader(scene::Node& patch, const char* shader) const = 0; -}; - -#include "modulesystem.h" - -template -class ModuleRef; -typedef ModuleRef PatchModuleRef; - -template -class GlobalModule; -typedef GlobalModule GlobalPatchModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalPatchModuleRef; - -inline PatchCreator& GlobalPatchCreator() -{ - return GlobalPatchModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iplugin.cpp b/misc/mediasource/extra/netradiant-src/include/iplugin.cpp deleted file mode 100644 index ebfc591f..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iplugin.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "iplugin.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iplugin.h b/misc/mediasource/extra/netradiant-src/include/iplugin.h deleted file mode 100644 index af713a7d..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iplugin.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_IPLUGIN_H) -#define INCLUDED_IPLUGIN_H - -#include "generic/constant.h" - -typedef const char* (* PFN_QERPLUG_INIT) (void* hApp, void* pMainWidget); -typedef const char* (* PFN_QERPLUG_GETNAME)(); -typedef const char* (* PFN_QERPLUG_GETCOMMANDLIST)(); -typedef const char* (* PFN_QERPLUG_GETCOMMANDTITLELIST)(); -typedef void (* PFN_QERPLUG_DISPATCH) (const char* p, float* vMin, float* vMax, bool bSingleBrush); - -struct _QERPluginTable -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "plugin"); - - PFN_QERPLUG_INIT m_pfnQERPlug_Init; - PFN_QERPLUG_GETNAME m_pfnQERPlug_GetName; - PFN_QERPLUG_GETCOMMANDLIST m_pfnQERPlug_GetCommandList; - PFN_QERPLUG_GETCOMMANDTITLELIST m_pfnQERPlug_GetCommandTitleList; - PFN_QERPLUG_DISPATCH m_pfnQERPlug_Dispatch; -}; - -template -class Modules; -typedef Modules<_QERPluginTable> PluginModules; - -template -class ModulesRef; -typedef ModulesRef<_QERPluginTable> PluginModulesRef; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ireference.cpp b/misc/mediasource/extra/netradiant-src/include/ireference.cpp deleted file mode 100644 index 844e95be..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ireference.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "ireference.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ireference.h b/misc/mediasource/extra/netradiant-src/include/ireference.h deleted file mode 100644 index e97df794..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ireference.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IREFERENCE_H) -#define INCLUDED_IREFERENCE_H - -#include "generic/constant.h" - -namespace scene -{ - class Node; -} - -class ModuleObserver; - -class Resource -{ -public: - virtual bool load() = 0; - virtual bool save() = 0; - virtual void flush() = 0; - virtual void refresh() = 0; - virtual scene::Node* getNode() = 0; - virtual void setNode(scene::Node* node) = 0; - virtual void attach(ModuleObserver& observer) = 0; - virtual void detach(ModuleObserver& observer) = 0; - virtual void realise() = 0; - virtual void unrealise() = 0; -}; - -class EntityCreator; - -class ReferenceCache -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "reference"); - - virtual Resource* capture(const char* path) = 0; - virtual void release(const char* path) = 0; - - virtual void setEntityCreator(EntityCreator& entityCreator) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalReferenceModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalReferenceModuleRef; - -inline ReferenceCache& GlobalReferenceCache() -{ - return GlobalReferenceModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/irender.cpp b/misc/mediasource/extra/netradiant-src/include/irender.cpp deleted file mode 100644 index c0fec667..00000000 --- a/misc/mediasource/extra/netradiant-src/include/irender.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "irender.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/irender.h b/misc/mediasource/extra/netradiant-src/include/irender.h deleted file mode 100644 index d9c40b6f..00000000 --- a/misc/mediasource/extra/netradiant-src/include/irender.h +++ /dev/null @@ -1,177 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IRENDER_H) -#define INCLUDED_IRENDER_H - -#include "generic/constant.h" -#include "generic/callbackfwd.h" - - -// Rendering states to sort by. -// Higher bits have the most effect - slowest state changes should be highest. - -const unsigned int RENDER_DEFAULT = 0; -const unsigned int RENDER_LINESTIPPLE = 1 << 0; // glEnable(GL_LINE_STIPPLE) -const unsigned int RENDER_LINESMOOTH = 1 << 1; // glEnable(GL_LINE_SMOOTH) -const unsigned int RENDER_POLYGONSTIPPLE = 1 << 2; // glEnable(GL_POLYGON_STIPPLE) -const unsigned int RENDER_POLYGONSMOOTH = 1 << 3; // glEnable(GL_POLYGON_SMOOTH) -const unsigned int RENDER_ALPHATEST = 1 << 4; // glEnable(GL_ALPHA_TEST) -const unsigned int RENDER_DEPTHTEST = 1 << 5; // glEnable(GL_DEPTH_TEST) -const unsigned int RENDER_DEPTHWRITE = 1 << 6; // glDepthMask(GL_TRUE) -const unsigned int RENDER_COLOURWRITE = 1 << 7; // glColorMask(GL_TRUE; GL_TRUE; GL_TRUE; GL_TRUE) -const unsigned int RENDER_CULLFACE = 1 << 8; // glglEnable(GL_CULL_FACE) -const unsigned int RENDER_SCALED = 1 << 9; // glEnable(GL_NORMALIZE) -const unsigned int RENDER_SMOOTH = 1 << 10; // glShadeModel -const unsigned int RENDER_FOG = 1 << 11; // glEnable(GL_FOG) -const unsigned int RENDER_LIGHTING = 1 << 12; // glEnable(GL_LIGHTING) -const unsigned int RENDER_BLEND = 1 << 13; // glEnable(GL_BLEND) -const unsigned int RENDER_OFFSETLINE = 1 << 14; // glEnable(GL_POLYGON_OFFSET_LINE) -const unsigned int RENDER_FILL = 1 << 15; // glPolygonMode -const unsigned int RENDER_COLOURARRAY = 1 << 16; // glEnableClientState(GL_COLOR_ARRAY) -const unsigned int RENDER_COLOURCHANGE = 1 << 17; // render() is allowed to call glColor*() -const unsigned int RENDER_TEXTURE = 1 << 18; // glEnable(GL_TEXTURE_2D) -const unsigned int RENDER_BUMP = 1 << 19; -const unsigned int RENDER_PROGRAM = 1 << 20; -const unsigned int RENDER_SCREEN = 1 << 21; -const unsigned int RENDER_OVERRIDE = 1 << 22; -typedef unsigned int RenderStateFlags; - - -class AABB; -class Matrix4; - -template class BasicVector3; -typedef BasicVector3 Vector3; - -class Shader; - -class RendererLight -{ -public: - virtual Shader* getShader() const = 0; - virtual const AABB& aabb() const = 0; - virtual bool testAABB(const AABB& other) const = 0; - virtual const Matrix4& rotation() const = 0; - virtual const Vector3& offset() const = 0; - virtual const Vector3& colour() const = 0; - virtual bool isProjected() const = 0; - virtual const Matrix4& projection() const = 0; -}; - -class LightCullable -{ -public: - virtual bool testLight(const RendererLight& light) const = 0; - virtual void insertLight(const RendererLight& light) - { - } - virtual void clearLights() - { - } -}; - -class Renderable; -typedef Callback1 RenderableCallback; - -typedef Callback1 RendererLightCallback; - -class LightList -{ -public: - virtual void evaluateLights() const = 0; - virtual void lightsChanged() const = 0; - virtual void forEachLight(const RendererLightCallback& callback) const = 0; -}; - -const int c_attr_TexCoord0 = 1; -const int c_attr_Tangent = 3; -const int c_attr_Binormal = 4; - -class OpenGLRenderable -{ -public: - virtual void render(RenderStateFlags state) const = 0; -}; - -class Matrix4; -struct qtexture_t; -class ModuleObserver; - -#include "generic/vector.h" - -class Shader -{ -public: - virtual void addRenderable(const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights = 0) = 0; - virtual void incrementUsed() = 0; - virtual void decrementUsed() = 0; - virtual void attach(ModuleObserver& observer) = 0; - virtual void detach(ModuleObserver& observer) = 0; - virtual qtexture_t& getTexture() const = 0; - virtual unsigned int getFlags() const = 0; -}; - -class ShaderCache -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "renderstate"); - - virtual Shader* capture(const char* name) = 0; - virtual void release(const char* name) = 0; - /*! Render all Shader objects. */ - virtual void render(RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer = Vector3(0, 0, 0)) = 0; - - virtual void realise() = 0; - virtual void unrealise() = 0; - - virtual bool lightingSupported() const = 0; - virtual bool useShaderLanguage() const = 0; - - virtual const LightList& attach(LightCullable& cullable) = 0; - virtual void detach(LightCullable& cullable) = 0; - virtual void changed(LightCullable& cullable) = 0; - virtual void attach(RendererLight& light) = 0; - virtual void detach(RendererLight& light) = 0; - virtual void changed(RendererLight& light) = 0; - - virtual void attachRenderable(const Renderable& renderable) = 0; - virtual void detachRenderable(const Renderable& renderable) = 0; - virtual void forEachRenderable(const RenderableCallback& callback) const = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalShaderCacheModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalShaderCacheModuleRef; - -inline ShaderCache& GlobalShaderCache() -{ - return GlobalShaderCacheModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iscenegraph.cpp b/misc/mediasource/extra/netradiant-src/include/iscenegraph.cpp deleted file mode 100644 index 6b7b450e..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iscenegraph.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "iscenegraph.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iscenegraph.h b/misc/mediasource/extra/netradiant-src/include/iscenegraph.h deleted file mode 100644 index 18e50f77..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iscenegraph.h +++ /dev/null @@ -1,221 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (INCLUDED_ISCENEGRAPH_H) -#define INCLUDED_ISCENEGRAPH_H - -#include -#include "generic/constant.h" -#include "signal/signalfwd.h" - -template -class Stack; -template -class Reference; - -namespace scene -{ - class Instance; - const Instance* const nullInstancePointer = 0; - inline const Instance& nullInstance() - { - return *nullInstancePointer; - } - - class Node; - const Node* const nullNodePointer = 0; - inline const Node& nullNode() - { - return *nullNodePointer; - } -} - -typedef Reference NodeReference; - -typedef std::size_t TypeId; - -const TypeId NODETYPEID_MAX = 64; -const TypeId NODETYPEID_NONE = NODETYPEID_MAX; - -const TypeId INSTANCETYPEID_MAX = 64; -const TypeId INSTANCETYPEID_NONE = INSTANCETYPEID_MAX; - -namespace scene -{ - /// \brief A unique key to an instance of a node in the scene-graph. - typedef Stack Path; - - /// \brief A scene-graph - a Directed Acyclic Graph (DAG). - /// - /// - Each node may refer to zero or more 'child' nodes (directed). - /// - A node may never have itself as one of its ancestors (acyclic). - /// - Each node may have more than one 'parent', thus having more than one 'instance' in the graph. - /// - Each instance is uniquely identified by the list of its ancestors plus itself, known as a 'path'. - class Graph - { - public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "scenegraph"); - - class Walker - { - public: - /// \brief Called before traversing the first child-instance of 'instance'. If the return value is false, the children of the current instance are not traversed. - virtual bool pre(const Path& path, Instance& instance) const = 0; - /// \brief Called after traversing the last child-instance of 'instance'. - virtual void post(const Path& path, Instance& instance) const - { - } - }; - - /// \brief Returns the root-node of the graph. - virtual Node& root() = 0; - /// \brief Sets the root-node of the graph to be 'node'. - virtual void insert_root(Node& root) = 0; - /// \brief Clears the root-node of the graph. - virtual void erase_root() = 0; - /// \brief Traverses all nodes in the graph depth-first, starting from the root node. - virtual void traverse(const Walker& walker) = 0; - /// \brief Traverses all nodes in the graph depth-first, starting from 'start'. - virtual void traverse_subgraph(const Walker& walker, const Path& start) = 0; - /// \brief Returns the instance at the location identified by 'path', or 0 if it does not exist. - virtual scene::Instance* find(const Path& path) = 0; - - /// \brief Invokes all scene-changed callbacks. Called when any part of the scene changes the way it will appear when the scene is rendered. - /// \todo Move to a separate class. - virtual void sceneChanged() = 0; - /// \brief Add a \p callback to be invoked when the scene changes. - /// \todo Move to a separate class. - virtual void addSceneChangedCallback(const SignalHandler& handler) = 0; - - /// \brief Invokes all bounds-changed callbacks. Called when the bounds of any instance in the scene change. - /// \todo Move to a separate class. - virtual void boundsChanged() = 0; - /// \brief Add a \p callback to be invoked when the bounds of any instance in the scene change. - virtual SignalHandlerId addBoundsChangedCallback(const SignalHandler& boundsChanged) = 0; - /// \brief Remove a \p callback to be invoked when the bounds of any instance in the scene change. - virtual void removeBoundsChangedCallback(SignalHandlerId id) = 0; - - virtual TypeId getNodeTypeId(const char* name) = 0; - virtual TypeId getInstanceTypeId(const char* name) = 0; - }; - - class Traversable - { - public: - STRING_CONSTANT(Name, "scene::Traversable"); - - class Observer - { - public: - /// \brief Called when a node is added to the container. - virtual void insert(Node& node) = 0; - /// \brief Called when a node is removed from the container. - virtual void erase(Node& node) = 0; - }; - - class Walker - { - public: - /// \brief Called before traversing the first child-node of 'node'. If the return value is false, the children of the current node are not traversed. - virtual bool pre(Node& node) const = 0; - /// \brief Called after traversing the last child-node of 'node'. - virtual void post(Node& node) const - { - } - }; - /// \brief Adds a node to the container. - virtual void insert(Node& node) = 0; - /// \brief Removes a node from the container. - virtual void erase(Node& node) = 0; - /// \brief Traverses the subgraphs rooted at each node in the container, depth-first. - virtual void traverse(const Walker& walker) = 0; - /// \brief Returns true if the container contains no nodes. - virtual bool empty() const = 0; - }; - - class Instantiable - { - public: - STRING_CONSTANT(Name, "scene::Instantiable"); - - class Observer - { - public: - /// \brief Called when an instance is added to the container. - virtual void insert(scene::Instance* instance) = 0; - /// \brief Called when an instance is removed from the container. - virtual void erase(scene::Instance* instance) = 0; - }; - - class Visitor - { - public: - virtual void visit(Instance& instance) const = 0; - }; - - /// \brief Returns a new instance uniquely identified by 'path'. - virtual scene::Instance* create(const scene::Path& path, scene::Instance* parent) = 0; - /// \brief Calls Visitor::visit(instance) for each instance in the container. - virtual void forEachInstance(const Visitor& visitor) = 0; - /// \brief Adds an instance to the container. - virtual void insert(Observer* observer, const Path& path, scene::Instance* instance) = 0; - /// \brief Returns an instance removed from the container. - virtual scene::Instance* erase(Observer* observer, const Path& path) = 0; - }; - - class Cloneable - { - public: - STRING_CONSTANT(Name, "scene::Cloneable"); - - /// \brief Returns a copy of itself. - virtual scene::Node& clone() const = 0; - }; -} - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalSceneGraphModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalSceneGraphModuleRef; - -inline scene::Graph& GlobalSceneGraph() -{ - return GlobalSceneGraphModule::getTable(); -} - -inline void AddSceneChangeCallback(const SignalHandler& handler) -{ - GlobalSceneGraph().addSceneChangedCallback(handler); -} -inline void SceneChangeNotify() -{ - GlobalSceneGraph().sceneChanged(); -} - - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iscriplib.cpp b/misc/mediasource/extra/netradiant-src/include/iscriplib.cpp deleted file mode 100644 index 4de7c3f9..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iscriplib.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "iscriplib.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iscriplib.h b/misc/mediasource/extra/netradiant-src/include/iscriplib.h deleted file mode 100644 index 98d85c27..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iscriplib.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ISCRIPLIB_H) -#define INCLUDED_ISCRIPLIB_H - -/// \file iscriplib.h -/// \brief Token input/output stream module. - -#include -#include "generic/constant.h" - -#define MAXTOKEN 1024 - -class Tokeniser -{ -public: - virtual void release() = 0; - virtual void nextLine() = 0; - virtual const char* getToken() = 0; - virtual void ungetToken() = 0; - virtual std::size_t getLine() const = 0; - virtual std::size_t getColumn() const = 0; -}; - -class TextInputStream; - -class TokenWriter -{ -public: - virtual void release() = 0; - virtual void nextLine() = 0; - virtual void writeToken(const char* token) = 0; - virtual void writeString(const char* string) = 0; - virtual void writeInteger(int i) = 0; - virtual void writeUnsigned(std::size_t i) = 0; - virtual void writeFloat(double f) = 0; -}; - -class TextOutputStream; - -struct _QERScripLibTable -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "scriptlib"); - - Tokeniser& (* m_pfnNewScriptTokeniser)(TextInputStream& istream); - Tokeniser& (* m_pfnNewSimpleTokeniser)(TextInputStream& istream); - TokenWriter& (* m_pfnNewSimpleTokenWriter)(TextOutputStream& ostream); -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule<_QERScripLibTable> GlobalScripLibModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef<_QERScripLibTable> GlobalScripLibModuleRef; - -inline _QERScripLibTable& GlobalScriptLibrary() -{ - return GlobalScripLibModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iselection.cpp b/misc/mediasource/extra/netradiant-src/include/iselection.cpp deleted file mode 100644 index 2438d313..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iselection.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "iselection.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iselection.h b/misc/mediasource/extra/netradiant-src/include/iselection.h deleted file mode 100644 index ec32561e..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iselection.h +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ISELECTION_H) -#define INCLUDED_ISELECTION_H - -#include -#include "generic/constant.h" -#include "generic/callbackfwd.h" -#include "signal/signalfwd.h" - -class Renderer; -class View; - -class Selectable -{ -public: - STRING_CONSTANT(Name, "Selectable"); - - virtual void setSelected(bool select) = 0; - virtual bool isSelected() const = 0; -}; - -namespace scene -{ - class Instance; -}; - -class InstanceSelectionObserver -{ -public: - virtual void onSelectedChanged(scene::Instance& instance) = 0; -}; - -template class BasicVector3; -typedef BasicVector3 Vector3; -template class BasicVector4; -typedef BasicVector4 Vector4; -class Matrix4; -typedef Vector4 Quaternion; - -typedef Callback1 SelectionChangeCallback; -typedef SignalHandler1 SelectionChangeHandler; - -class SelectionSystem -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "selection"); - - enum EMode - { - eEntity, - ePrimitive, - eComponent, - }; - - enum EComponentMode - { - eDefault, - eVertex, - eEdge, - eFace, - }; - - enum EManipulatorMode - { - eTranslate, - eRotate, - eScale, - eDrag, - eClip, - }; - - virtual void SetMode(EMode mode) = 0; - virtual EMode Mode() const = 0; - virtual void SetComponentMode(EComponentMode mode) = 0; - virtual EComponentMode ComponentMode() const = 0; - virtual void SetManipulatorMode(EManipulatorMode mode) = 0; - virtual EManipulatorMode ManipulatorMode() const = 0; - - virtual SelectionChangeCallback getObserver(EMode mode) = 0; - virtual std::size_t countSelected() const = 0; - virtual std::size_t countSelectedComponents() const = 0; - virtual void onSelectedChanged(scene::Instance& instance, const Selectable& selectable) = 0; - virtual void onComponentSelection(scene::Instance& instance, const Selectable& selectable) = 0; - virtual scene::Instance& ultimateSelected() const = 0; - virtual scene::Instance& penultimateSelected() const = 0; - virtual void setSelectedAll(bool selected) = 0; - virtual void setSelectedAllComponents(bool selected) = 0; - - class Visitor - { - public: - virtual void visit(scene::Instance& instance) const = 0; - }; - virtual void foreachSelected(const Visitor& visitor) const = 0; - virtual void foreachSelectedComponent(const Visitor& visitor) const = 0; - - virtual void addSelectionChangeCallback(const SelectionChangeHandler& handler) = 0; - - virtual void NudgeManipulator(const Vector3& nudge, const Vector3& view) = 0; - - virtual void translateSelected(const Vector3& translation) = 0; - virtual void rotateSelected(const Quaternion& rotation) = 0; - virtual void scaleSelected(const Vector3& scaling) = 0; - - virtual void pivotChanged() const = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalSelectionModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalSelectionModuleRef; - -inline SelectionSystem& GlobalSelectionSystem() -{ - return GlobalSelectionModule::getTable(); -} - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/ishaders.cpp b/misc/mediasource/extra/netradiant-src/include/ishaders.cpp deleted file mode 100644 index bf380198..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ishaders.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "ishaders.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/ishaders.h b/misc/mediasource/extra/netradiant-src/include/ishaders.h deleted file mode 100644 index 928dd1de..00000000 --- a/misc/mediasource/extra/netradiant-src/include/ishaders.h +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_ISHADERS_H) -#define INCLUDED_ISHADERS_H - -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -enum -{ - QER_TRANS = 1 << 0, - QER_NOCARVE = 1 << 1, - QER_NODRAW = 1 << 2, - QER_NONSOLID = 1 << 3, - QER_WATER = 1 << 4, - QER_LAVA = 1 << 5, - QER_FOG = 1 << 6, - QER_ALPHATEST = 1 << 7, - QER_CULL = 1 << 8, - QER_AREAPORTAL = 1 << 9, - QER_CLIP = 1 << 10, - QER_BOTCLIP = 1 << 11, -}; - -struct qtexture_t; - -template class BasicVector3; -typedef BasicVector3 Vector3; -typedef Vector3 Colour3; - -typedef unsigned char BlendFactor; -const BlendFactor BLEND_ZERO = 0; -const BlendFactor BLEND_ONE = 1; -const BlendFactor BLEND_SRC_COLOUR = 2; -const BlendFactor BLEND_ONE_MINUS_SRC_COLOUR = 3; -const BlendFactor BLEND_SRC_ALPHA = 4; -const BlendFactor BLEND_ONE_MINUS_SRC_ALPHA = 5; -const BlendFactor BLEND_DST_COLOUR = 6; -const BlendFactor BLEND_ONE_MINUS_DST_COLOUR = 7; -const BlendFactor BLEND_DST_ALPHA = 8; -const BlendFactor BLEND_ONE_MINUS_DST_ALPHA = 9; -const BlendFactor BLEND_SRC_ALPHA_SATURATE = 10; - -class BlendFunc -{ -public: - BlendFunc(BlendFactor src, BlendFactor dst) : m_src(src), m_dst(dst) - { - } - BlendFactor m_src; - BlendFactor m_dst; -}; - -class ShaderLayer -{ -public: - virtual qtexture_t* texture() const = 0; - virtual BlendFunc blendFunc() const = 0; - virtual bool clampToBorder() const = 0; - virtual float alphaTest() const = 0; -}; - -typedef Callback1 ShaderLayerCallback; - - -class IShader -{ -public: - enum EAlphaFunc - { - eAlways, - eEqual, - eLess, - eGreater, - eLEqual, - eGEqual, - }; - enum ECull - { - eCullNone, - eCullBack, - }; - // Increment the number of references to this object - virtual void IncRef() = 0; - // Decrement the reference count - virtual void DecRef() = 0; - // get/set the qtexture_t* Radiant uses to represent this shader object - virtual qtexture_t* getTexture() const = 0; - virtual qtexture_t* getDiffuse() const = 0; - virtual qtexture_t* getBump() const = 0; - virtual qtexture_t* getSpecular() const = 0; - // get shader name - virtual const char* getName() const = 0; - virtual bool IsInUse() const = 0; - virtual void SetInUse(bool bInUse) = 0; - // get the editor flags (QER_NOCARVE QER_TRANS) - virtual int getFlags() const = 0; - // get the transparency value - virtual float getTrans() const = 0; - // test if it's a true shader, or a default shader created to wrap around a texture - virtual bool IsDefault() const = 0; - // get the alphaFunc - virtual void getAlphaFunc(EAlphaFunc *func, float *ref) = 0; - virtual BlendFunc getBlendFunc() const = 0; - // get the cull type - virtual ECull getCull() = 0; - // get shader file name (ie the file where this one is defined) - virtual const char* getShaderFileName() const = 0; - - virtual const ShaderLayer* firstLayer() const = 0; - virtual void forEachLayer(const ShaderLayerCallback& layer) const = 0; - - virtual qtexture_t* lightFalloffImage() const = 0; -}; - -typedef struct _GSList GSList; -typedef Callback1 ShaderNameCallback; - -class ModuleObserver; - -class ShaderSystem -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "shaders"); - // NOTE: shader and texture names used must be full path. - // Shaders usable as textures have prefix equal to getTexturePrefix() - - virtual void realise() = 0; - virtual void unrealise() = 0; - virtual void refresh() = 0; - // activate the shader for a given name and return it - // will return the default shader if name is not found - virtual IShader* getShaderForName(const char* name) = 0; - - virtual void foreachShaderName(const ShaderNameCallback& callback) = 0; - - // iterate over the list of active shaders - virtual void beginActiveShadersIterator() = 0; - virtual bool endActiveShadersIterator() = 0; - virtual IShader* dereferenceActiveShadersIterator() = 0; - virtual void incrementActiveShadersIterator() = 0; - - virtual void setActiveShadersChangedNotify(const Callback& notify) = 0; - - virtual void attach(ModuleObserver& observer) = 0; - virtual void detach(ModuleObserver& observer) = 0; - - virtual void setLightingEnabled(bool enabled) = 0; - - virtual const char* getTexturePrefix() const = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalShadersModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalShadersModuleRef; - -inline ShaderSystem& GlobalShaderSystem() -{ - return GlobalShadersModule::getTable(); -} - - -#define QERApp_Shader_ForName GlobalShaderSystem().getShaderForName -#define QERApp_ActiveShaders_IteratorBegin GlobalShaderSystem().beginActiveShadersIterator -#define QERApp_ActiveShaders_IteratorAtEnd GlobalShaderSystem().endActiveShadersIterator -#define QERApp_ActiveShaders_IteratorCurrent GlobalShaderSystem().dereferenceActiveShadersIterator -#define QERApp_ActiveShaders_IteratorIncrement GlobalShaderSystem().incrementActiveShadersIterator - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/itexdef.cpp b/misc/mediasource/extra/netradiant-src/include/itexdef.cpp deleted file mode 100644 index 1973c960..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itexdef.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "itexdef.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/itexdef.h b/misc/mediasource/extra/netradiant-src/include/itexdef.h deleted file mode 100644 index a299843b..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itexdef.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (INCLUDED_ITEXDEF_H) -#define INCLUDED_ITEXDEF_H - -class texdef_t -{ -public: - float shift[2]; - float rotate; - float scale[2]; - - texdef_t() - { - shift[0] = 0; - shift[1] = 0; - rotate = 0; - scale[0] = 1; - scale[1] = 1; - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/itextstream.cpp b/misc/mediasource/extra/netradiant-src/include/itextstream.cpp deleted file mode 100644 index c93ae35a..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itextstream.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "itextstream.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/itextstream.h b/misc/mediasource/extra/netradiant-src/include/itextstream.h deleted file mode 100644 index 891336e7..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itextstream.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ITEXTSTREAM_H) -#define INCLUDED_ITEXTSTREAM_H - -/// \file -/// \brief Text-stream interfaces. - -#include -#include "generic/static.h" - -/// \brief A read-only character-stream. -class TextInputStream -{ -public: - /// \brief Attempts to read the next \p length characters from the stream to \p buffer. - /// Returns the number of characters actually stored in \p buffer. - virtual std::size_t read(char* buffer, std::size_t length) = 0; -}; - -/// \brief A write-only character-stream. -class TextOutputStream -{ -public: - /// \brief Attempts to write \p length characters to the stream from \p buffer. - /// Returns the number of characters actually read from \p buffer. - virtual std::size_t write(const char* buffer, std::size_t length) = 0; -}; - -/// \brief Calls the overloaded function ostream_write() to perform text formatting specific to the type being written. -/*! Note that ostream_write() is not globally defined - it must be defined once for each type supported.\n -To support writing a custom type MyClass to any kind of text-output-stream with operator<<: -\code -template -TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const MyClass& myClass) -{ - return ostream << myClass.getName() << ' ' << myClass.getText(); -} -\endcode -Expressing this as a template allows it to be used directly with any concrete text-output-stream type, not just the abstract TextOutputStream\n -\n -This overload writes a single character to any text-output-stream - ostream_write(TextOutputStreamType& ostream, char c). -*/ -template -inline TextOutputStream& operator<<(TextOutputStream& ostream, const T& t) -{ - return ostream_write(ostream, t); -} - -class NullOutputStream : public TextOutputStream -{ -public: - std::size_t write(const char*, std::size_t length) - { - return length; - } -}; - -class OutputStreamHolder -{ - NullOutputStream m_nullOutputStream; - TextOutputStream* m_outputStream; -public: - OutputStreamHolder() - : m_outputStream(&m_nullOutputStream) - { - } - void setOutputStream(TextOutputStream& outputStream) - { - m_outputStream = &outputStream; - } - TextOutputStream& getOutputStream() - { - return *m_outputStream; - } -}; - -typedef Static GlobalOutputStream; - -/// \brief Returns the global output stream. Used to display messages to the user. -inline TextOutputStream& globalOutputStream() -{ - return GlobalOutputStream::instance().getOutputStream(); -} - -class ErrorStreamHolder : public OutputStreamHolder {}; -typedef Static GlobalErrorStream; - -/// \brief Returns the global error stream. Used to display error messages to the user. -inline TextOutputStream& globalErrorStream() -{ - return GlobalErrorStream::instance().getOutputStream(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/itextures.cpp b/misc/mediasource/extra/netradiant-src/include/itextures.cpp deleted file mode 100644 index 26e2bf6d..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itextures.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "itextures.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/itextures.h b/misc/mediasource/extra/netradiant-src/include/itextures.h deleted file mode 100644 index 368e7b76..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itextures.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ITEXTURES_H) -#define INCLUDED_ITEXTURES_H - -#include "iimage.h" -#include "generic/constant.h" - -struct qtexture_t; - -class LoadImageCallback -{ - typedef Image* (*LoadFunc)(void* environment, const char* name); -public: - void* m_environment; - LoadFunc m_func; - - LoadImageCallback(void* environment, LoadFunc func) : m_environment(environment), m_func(func) - { - } - Image* loadImage(const char* name) const - { - return m_func(m_environment, name); - } -}; - -inline bool operator==(const LoadImageCallback& self, const LoadImageCallback& other) -{ - return self.m_environment == other.m_environment && self.m_func == other.m_func; -} -inline bool operator<(const LoadImageCallback& self, const LoadImageCallback& other) -{ - return self.m_environment < other.m_environment || - (!(other.m_environment < self.m_environment) && self.m_func < other.m_func); -} - -class TexturesCacheObserver -{ -public: - virtual void unrealise() = 0; - virtual void realise() = 0; -}; - -class TexturesCache -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "textures"); - virtual LoadImageCallback defaultLoader() const = 0; - virtual Image* loadImage(const char* name) = 0; - virtual qtexture_t* capture(const char* name) = 0; - virtual qtexture_t* capture(const LoadImageCallback& load, const char* name) = 0; - virtual void release(qtexture_t* texture) = 0; - virtual void attach(TexturesCacheObserver& observer) = 0; - virtual void detach(TexturesCacheObserver& observer) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalTexturesModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalTexturesModuleRef; - -inline TexturesCache& GlobalTexturesCache() -{ - return GlobalTexturesModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/itoolbar.cpp b/misc/mediasource/extra/netradiant-src/include/itoolbar.cpp deleted file mode 100644 index 2c989b6a..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itoolbar.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "itoolbar.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/itoolbar.h b/misc/mediasource/extra/netradiant-src/include/itoolbar.h deleted file mode 100644 index 350e5a5f..00000000 --- a/misc/mediasource/extra/netradiant-src/include/itoolbar.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_IPLUGTOOLBAR_H) -#define INCLUDED_IPLUGTOOLBAR_H - -#include -#include "generic/constant.h" - -class IToolbarButton -{ -public: - enum EType - { - eSpace, - eButton, - eToggleButton, - eRadioButton, - }; - - virtual const char* getImage() const = 0; - virtual const char* getText() const = 0; - virtual const char* getTooltip() const = 0; - virtual EType getType() const = 0; - virtual void activate() const = 0; -}; - -typedef std::size_t (* PFN_TOOLBARBUTTONCOUNT)(); -typedef const IToolbarButton* (* PFN_GETTOOLBARBUTTON)(std::size_t index); - -struct _QERPlugToolbarTable -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "toolbar"); - - PFN_TOOLBARBUTTONCOUNT m_pfnToolbarButtonCount; - PFN_GETTOOLBARBUTTON m_pfnGetToolbarButton; -}; - -template -class Modules; -typedef Modules<_QERPlugToolbarTable> ToolbarModules; - -template -class ModulesRef; -typedef ModulesRef<_QERPlugToolbarTable> ToolbarModulesRef; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/iundo.cpp b/misc/mediasource/extra/netradiant-src/include/iundo.cpp deleted file mode 100644 index 49b96b03..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iundo.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "iundo.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/iundo.h b/misc/mediasource/extra/netradiant-src/include/iundo.h deleted file mode 100644 index 4dcbad85..00000000 --- a/misc/mediasource/extra/netradiant-src/include/iundo.h +++ /dev/null @@ -1,110 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_IUNDO_H) -#define INCLUDED_IUNDO_H - -/// \file -/// \brief The undo-system interface. Uses the 'memento' pattern. - -#include -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -class UndoMemento -{ -public: - virtual void release() = 0; -}; - -class Undoable -{ -public: - virtual UndoMemento* exportState() const = 0; - virtual void importState(const UndoMemento* state) = 0; -}; - -class UndoObserver -{ -public: - virtual void save(Undoable* undoable) = 0; -}; - -class UndoTracker -{ -public: - virtual void clear() = 0; - virtual void begin() = 0; - virtual void undo() = 0; - virtual void redo() = 0; -}; - -class UndoSystem -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "undo"); - - virtual UndoObserver* observer(Undoable* undoable) = 0; - virtual void release(Undoable* undoable) = 0; - - virtual std::size_t size() const = 0; - virtual void start() = 0; - virtual void finish(const char* command) = 0; - virtual void undo() = 0; - virtual void redo() = 0; - virtual void clear() = 0; - - virtual void trackerAttach(UndoTracker& tracker) = 0; - virtual void trackerDetach(UndoTracker& tracker) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalUndoModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalUndoModuleRef; - -inline UndoSystem& GlobalUndoSystem() -{ - return GlobalUndoModule::getTable(); -} - -class UndoableCommand -{ - const char* m_command; -public: - UndoableCommand(const char* command) : m_command(command) - { - GlobalUndoSystem().start(); - } - ~UndoableCommand() - { - GlobalUndoSystem().finish(m_command); - } -}; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/mapfile.cpp b/misc/mediasource/extra/netradiant-src/include/mapfile.cpp deleted file mode 100644 index 1065f591..00000000 --- a/misc/mediasource/extra/netradiant-src/include/mapfile.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "mapfile.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/mapfile.h b/misc/mediasource/extra/netradiant-src/include/mapfile.h deleted file mode 100644 index e53d79c1..00000000 --- a/misc/mediasource/extra/netradiant-src/include/mapfile.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_MAPFILE_H) -#define INCLUDED_MAPFILE_H - -#include - -#include "iscenegraph.h" -#include "generic/callbackfwd.h" - -const std::size_t MAPFILE_MAX_CHANGES = std::numeric_limits::max(); - -class MapFile -{ -public: - STRING_CONSTANT(Name, "MapFile"); - - virtual void save() = 0; - virtual bool saved() const = 0; - virtual void changed() = 0; - virtual void setChangedCallback(const Callback& changed) = 0; - virtual std::size_t changes() const = 0; -}; - -#include "scenelib.h" - -inline MapFile* Node_getMapFile(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -template -inline MapFile* path_find_mapfile(Iterator first, Iterator last) -{ - Iterator i = last; - for(;;) - { - --i; - - MapFile* map = Node_getMapFile(*i); - if(map != 0) - { - return map; - } - - if(i == first) - { - break; - } - } - ERROR_MESSAGE("failed to find parent mapfile for path"); - return 0; -} - - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/modelskin.cpp b/misc/mediasource/extra/netradiant-src/include/modelskin.cpp deleted file mode 100644 index 6d34f272..00000000 --- a/misc/mediasource/extra/netradiant-src/include/modelskin.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "modelskin.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/modelskin.h b/misc/mediasource/extra/netradiant-src/include/modelskin.h deleted file mode 100644 index c01b5f30..00000000 --- a/misc/mediasource/extra/netradiant-src/include/modelskin.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_MODELSKIN_H) -#define INCLUDED_MODELSKIN_H - -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -class SkinRemap -{ -public: - const char* m_from; - const char* m_to; - SkinRemap(const char* from, const char* to) : m_from(from), m_to(to) - { - } -}; - -typedef Callback1 SkinRemapCallback; -class ModuleObserver; - -class ModelSkin -{ -public: - STRING_CONSTANT(Name, "ModelSkin"); - /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the skin is loaded or unloaded. - virtual void attach(ModuleObserver& observer) = 0; - /// \brief Detach an \p observer previously-attached by calling \c attach. - virtual void detach(ModuleObserver& observer) = 0; - /// \brief Returns true if this skin is currently loaded. - virtual bool realised() const = 0; - /// \brief Returns the shader identifier that \p name remaps to, or "" if not found or not realised. - virtual const char* getRemap(const char* name) const = 0; - /// \brief Calls \p callback for each remap pair. Has no effect if not realised. - virtual void forEachRemap(const SkinRemapCallback& callback) const = 0; -}; - -class SkinnedModel -{ -public: - STRING_CONSTANT(Name, "SkinnedModel"); - /// \brief Instructs the skinned model to update its skin. - virtual void skinChanged() = 0; -}; - -class ModelSkinCache -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "modelskin"); - /// \brief Increments the reference count of and returns a reference to the skin uniquely identified by 'name'. - virtual ModelSkin& capture(const char* name) = 0; - /// \brief Decrements the reference-count of the skin uniquely identified by 'name'. - virtual void release(const char* name) = 0; -}; - - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalModelSkinCacheModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalModelSkinCacheModuleRef; - -inline ModelSkinCache& GlobalModelSkinCache() -{ - return GlobalModelSkinCacheModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/moduleobserver.cpp b/misc/mediasource/extra/netradiant-src/include/moduleobserver.cpp deleted file mode 100644 index fa26f8d9..00000000 --- a/misc/mediasource/extra/netradiant-src/include/moduleobserver.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "moduleobserver.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/moduleobserver.h b/misc/mediasource/extra/netradiant-src/include/moduleobserver.h deleted file mode 100644 index e218b4aa..00000000 --- a/misc/mediasource/extra/netradiant-src/include/moduleobserver.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_MODULEOBSERVER_H) -#define INCLUDED_MODULEOBSERVER_H - -class ModuleObserver -{ -public: - virtual void unrealise() = 0; - virtual void realise() = 0; -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/modulesystem.cpp b/misc/mediasource/extra/netradiant-src/include/modulesystem.cpp deleted file mode 100644 index 6b7a27c9..00000000 --- a/misc/mediasource/extra/netradiant-src/include/modulesystem.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "modulesystem.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/modulesystem.h b/misc/mediasource/extra/netradiant-src/include/modulesystem.h deleted file mode 100644 index 0378cc1d..00000000 --- a/misc/mediasource/extra/netradiant-src/include/modulesystem.h +++ /dev/null @@ -1,265 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_MODULESYSTEM_H) -#define INCLUDED_MODULESYSTEM_H - -#include "generic/static.h" -#include "debugging/debugging.h" - -#if defined(WIN32) -#ifdef MINGW32 -#define RADIANT_DLLEXPORT __declspec(dllexport) -#define RADIANT_DLLIMPORT __declspec(dllimport) -#else -#define RADIANT_DLLEXPORT __stdcall -#define RADIANT_DLLIMPORT __stdcall -#endif -#else -#define RADIANT_DLLEXPORT -#define RADIANT_DLLIMPORT -#endif - - -class Module -{ -public: - virtual void capture() = 0; - virtual void release() = 0; - virtual void* getTable() = 0; -}; - -inline void* Module_getTable(Module& module) -{ - return module.getTable(); -} - -class TextOutputStream; -class DebugMessageHandler; - -class ModuleServer -{ -public: - class Visitor - { - public: - virtual void visit(const char* name, Module& module) const = 0; - }; - - virtual void setError(bool error) = 0; - virtual bool getError() const = 0; - - virtual TextOutputStream& getOutputStream() = 0; - virtual TextOutputStream& getErrorStream() = 0; - virtual DebugMessageHandler& getDebugMessageHandler() = 0; - - virtual void registerModule(const char* type, int version, const char* name, Module& module) = 0; - virtual Module* findModule(const char* type, int version, const char* name) const = 0; - virtual void foreachModule(const char* type, int version, const Visitor& visitor) = 0; -}; - -class ModuleServerHolder -{ - ModuleServer* m_server; -public: - ModuleServerHolder() - : m_server(0) - { - } - void set(ModuleServer& server) - { - m_server = &server; - } - ModuleServer& get() - { - return *m_server; - } -}; - -typedef Static GlobalModuleServer; - -inline ModuleServer& globalModuleServer() -{ - return GlobalModuleServer::instance().get(); -} - - -inline void initialiseModule(ModuleServer& server) -{ - GlobalErrorStream::instance().setOutputStream(server.getErrorStream()); - GlobalOutputStream::instance().setOutputStream(server.getOutputStream()); - GlobalDebugMessageHandler::instance().setHandler(server.getDebugMessageHandler()); - GlobalModuleServer::instance().set(server); -} - - - -template -class Modules -{ -public: - class Visitor - { - public: - virtual void visit(const char* name, const Type& table) const = 0; - }; - - virtual Type* findModule(const char* name) = 0; - virtual void foreachModule(const Visitor& visitor) = 0; -}; - -#include "debugging/debugging.h" - -template -class ModuleRef -{ - Module* m_module; - Type* m_table; -public: - ModuleRef(const char* name) : m_table(0) - { - if(!globalModuleServer().getError()) - { - m_module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); - if(m_module == 0) - { - globalModuleServer().setError(true); - globalErrorStream() << "ModuleRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; - } - else - { - m_module->capture(); - if(!globalModuleServer().getError()) - { - m_table = static_cast(m_module->getTable()); - } - } - } - } - ~ModuleRef() - { - if(m_module != 0) - { - m_module->release(); - } - } - Type* getTable() - { -#if defined(_DEBUG) - ASSERT_MESSAGE(m_table != 0, "ModuleRef::getTable: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " - module-reference used without being initialised"); -#endif - return m_table; - } -}; - -template -class SingletonModuleRef -{ - Module* m_module; - Type* m_table; -public: - - SingletonModuleRef() - : m_module(0), m_table(0) - { - } - - bool initialised() const - { - return m_module != 0; - } - - void initialise(const char* name) - { - m_module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); - if(m_module == 0) - { - globalModuleServer().setError(true); - globalErrorStream() << "SingletonModuleRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; - } - } - - Type* getTable() - { -#if defined(_DEBUG) - ASSERT_MESSAGE(m_table != 0, "SingletonModuleRef::getTable: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " - module-reference used without being initialised"); -#endif - return m_table; - } - void capture() - { - if(initialised()) - { - m_module->capture(); - m_table = static_cast(m_module->getTable()); - } - } - void release() - { - if(initialised()) - { - m_module->release(); - } - } -}; - -template -class GlobalModule -{ - static SingletonModuleRef m_instance; -public: - static SingletonModuleRef& instance() - { - return m_instance; - } - static Type& getTable() - { - return *m_instance.getTable(); - } -}; - -template -SingletonModuleRef GlobalModule::m_instance; - - -template -class GlobalModuleRef -{ -public: - GlobalModuleRef(const char* name = "*") - { - if(!globalModuleServer().getError()) - { - GlobalModule::instance().initialise(name); - } - GlobalModule::instance().capture(); - } - ~GlobalModuleRef() - { - GlobalModule::instance().release(); - } - Type& getTable() - { - return GlobalModule::getTable(); - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/nameable.cpp b/misc/mediasource/extra/netradiant-src/include/nameable.cpp deleted file mode 100644 index f401626c..00000000 --- a/misc/mediasource/extra/netradiant-src/include/nameable.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "nameable.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/nameable.h b/misc/mediasource/extra/netradiant-src/include/nameable.h deleted file mode 100644 index 8e1357a4..00000000 --- a/misc/mediasource/extra/netradiant-src/include/nameable.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_NAMEABLE_H) -#define INCLUDED_NAMEABLE_H - -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -typedef Callback1 NameCallback; - -class Nameable -{ -public: - STRING_CONSTANT(Name, "Nameable"); - - virtual const char* name() const = 0; - virtual void attach(const NameCallback& callback) = 0; - virtual void detach(const NameCallback& callback) = 0; -}; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/namespace.cpp b/misc/mediasource/extra/netradiant-src/include/namespace.cpp deleted file mode 100644 index 2f322fda..00000000 --- a/misc/mediasource/extra/netradiant-src/include/namespace.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "namespace.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/namespace.h b/misc/mediasource/extra/netradiant-src/include/namespace.h deleted file mode 100644 index 30367bfd..00000000 --- a/misc/mediasource/extra/netradiant-src/include/namespace.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_NAMESPACE_H) -#define INCLUDED_NAMESPACE_H - -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -typedef Callback1 NameCallback; -typedef Callback1 NameCallbackCallback; - -class Namespace -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "namespace"); - virtual void attach(const NameCallback& setName, const NameCallbackCallback& attachObserver) = 0; - virtual void detach(const NameCallback& setName, const NameCallbackCallback& detachObserver) = 0; - virtual void makeUnique(const char* name, const NameCallback& setName) const = 0; -}; - -class Namespaced -{ -public: - STRING_CONSTANT(Name, "Namespaced"); - - virtual void setNamespace(Namespace& space) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalNamespaceModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalNamespaceModuleRef; - -inline Namespace& GlobalNamespace() -{ - return GlobalNamespaceModule::getTable(); -} -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/preferencesystem.cpp b/misc/mediasource/extra/netradiant-src/include/preferencesystem.cpp deleted file mode 100644 index a5fecd4d..00000000 --- a/misc/mediasource/extra/netradiant-src/include/preferencesystem.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 0 - -#include "preferencesystem.h" -#include "preferencedictionary.h" - -#include "xml/xmlparser.h" -#include "xml/xmlwriter.h" - - -void LoadPrefs(PreferenceDictionary& preferences, const char* filename) -{ - TextFileInputStream file(filename); - if(!file.failed()) - { - XMLStreamParser parser(file); - XMLPreferenceDictionaryImporter importer(preferences); - parser.exportXML(importer); - } - else - { - // error - } -} - -void SavePrefs(PreferenceDictionary& preferences, const char* filename) -{ - TextFileOutputStream file(filename); - if(!file.failed()) - { - XMLStreamWriter writer(file); - XMLPreferenceDictionaryExporter exporter(preferences, "1"); - exporter.exportXML(writer); - } - else - { - // error - } -} - - -class StringPreference -{ -public: - class Observer - { - public: - virtual void onChanged() = 0; - }; - -private: - CopiedString m_string; - Observer& m_observer; -public: - StringPreference(Observer& observer) - : m_observer(observer) - { - } - void importString(const char* value) - { - m_string = value; - m_observer.onChanged(); - } - typedef MemberCaller1 ImportStringCaller; - void exportString(StringImportCallback& importer) - { - importer(m_string.c_str()); - } - typedef MemberCaller1 ExportStringCaller; -}; - -inline void int_export(int i, StringImportCallback& importer) -{ - char buffer[16]; - sprintf(buffer, "%d", i); - importer(buffer); -} - -inline int int_import(const char* value) -{ - return atoi(value); -} - -class IntPreference -{ -public: - class Observer - { - public: - virtual void onChanged() = 0; - }; - -private: - int m_int; - Observer& m_observer; -public: - - IntPreference(Observer& observer) - : m_observer(observer) - { - } - void importString(const char* value) - { - m_int = int_import(value); - m_observer.onChanged(); - } - typedef MemberCaller1 ImportStringCaller; - void exportString(StringImportCallback& importer) - { - int_export(m_int, importer); - } - typedef MemberCaller1 ExportStringCaller; -}; - -class IntPreferenceImporter -{ - int& m_i; -public: - - IntPreferenceImporter(int& i) - : m_i(i) - { - } - void importString(const char* value) - { - m_i = int_import(value); - } -}; - - -class TestPrefs -{ -public: - TestPrefs() - { - PreferenceDictionary preferences; - - class StringObserver : public StringPreference::Observer - { - public: - void onChanged() - { - int bleh = 0; - } - } string_observer; - StringPreference string1(string_observer); - string1.importString("twenty-three"); - - class IntObserver : public IntPreference::Observer - { - public: - void onChanged() - { - int bleh = 0; - } - - } int_observer; - IntPreference int1(int_observer); - int1.importString("23"); - - preferences.registerPreference("string1", StringPreference::ImportStringCaller(string1), StringPreference::ExportStringCaller(string1)); - preferences.registerPreference("int1", IntPreference::ImportStringCaller(int1), IntPreference::ExportStringCaller(int1)); - - LoadPrefs(preferences, "test.pref"); - SavePrefs(preferences, "test.pref"); - - } -}; - -#if 0 -TestPrefs g_TestPrefs; -#endif - -void readpref(PreferenceDictionary& preferences, int& int_variable) -{ - PreferenceDictionary::iterator i = preferences.find("int_variable"); - IntPreferenceImporter importer(int_variable); - (*i).second.exporter().exportString(importer); -} - -void writepref(PreferenceDictionary& preferences, int& int_variable) -{ - PreferenceDictionary::iterator i = preferences.find("int_variable"); - int_export(int_variable, (*i).second.importer()); -} -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/preferencesystem.h b/misc/mediasource/extra/netradiant-src/include/preferencesystem.h deleted file mode 100644 index f5ebae1d..00000000 --- a/misc/mediasource/extra/netradiant-src/include/preferencesystem.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_PREFERENCESYSTEM_H) -#define INCLUDED_PREFERENCESYSTEM_H - -#include "generic/constant.h" -#include "generic/callbackfwd.h" - -typedef Callback1 StringImportCallback; -typedef Callback1 StringExportCallback; - -class PreferenceSystem -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "preferences"); - - virtual void registerPreference(const char* name, const StringImportCallback& importer, const StringExportCallback& exporter) = 0; -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule GlobalPreferenceSystemModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef GlobalPreferenceSystemModuleRef; - -inline PreferenceSystem& GlobalPreferenceSystem() -{ - return GlobalPreferenceSystemModule::getTable(); -} - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/qerplugin.cpp b/misc/mediasource/extra/netradiant-src/include/qerplugin.cpp deleted file mode 100644 index dd209319..00000000 --- a/misc/mediasource/extra/netradiant-src/include/qerplugin.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qerplugin.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/qerplugin.h b/misc/mediasource/extra/netradiant-src/include/qerplugin.h deleted file mode 100644 index cac311ab..00000000 --- a/misc/mediasource/extra/netradiant-src/include/qerplugin.h +++ /dev/null @@ -1,178 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// QERadiant PlugIns -// -// - -#ifndef __QERPLUGIN_H__ -#define __QERPLUGIN_H__ - -#include "generic/constant.h" - - -// ======================================== -// GTK+ helper functions - -// NOTE: parent can be 0 in all functions but it's best to set them - -// this API does not depend on gtk+ or glib -typedef struct _GtkWidget GtkWidget; - -enum EMessageBoxType -{ - eMB_OK, - eMB_OKCANCEL, - eMB_YESNO, - eMB_YESNOCANCEL, - eMB_NOYES, -}; - -enum EMessageBoxIcon -{ - eMB_ICONDEFAULT, - eMB_ICONERROR, - eMB_ICONWARNING, - eMB_ICONQUESTION, - eMB_ICONASTERISK, -}; - -enum EMessageBoxReturn -{ - eIDOK, - eIDCANCEL, - eIDYES, - eIDNO, -}; - -// simple Message Box, see above for the 'type' flags - -typedef EMessageBoxReturn (* PFN_QERAPP_MESSAGEBOX) (GtkWidget *parent, const char* text, const char* caption/* = "NetRadiant"*/, EMessageBoxType type/* = eMB_OK*/, EMessageBoxIcon icon/* = eMB_ICONDEFAULT*/); - -// file and directory selection functions return null if the user hits cancel -// - 'title' is the dialog title (can be null) -// - 'path' is used to set the initial directory (can be null) -// - 'pattern': the first pattern is for the win32 mode, then comes the Gtk pattern list, see Radiant source for samples -typedef const char* (* PFN_QERAPP_FILEDIALOG) (GtkWidget *parent, bool open, const char* title, const char* path/* = 0*/, const char* pattern/* = 0*/, bool want_load/* = false*/, bool want_import/* = false*/, bool want_save/* = false*/); - -// returns a gchar* string that must be g_free'd by the user -typedef char* (* PFN_QERAPP_DIRDIALOG) (GtkWidget *parent, const char* title/* = "Choose Directory"*/, const char* path/* = 0*/); - -// return true if the user closed the dialog with 'Ok' -// 'color' is used to set the initial value and store the selected value -template class BasicVector3; -typedef BasicVector3 Vector3; -typedef bool (* PFN_QERAPP_COLORDIALOG) (GtkWidget *parent, Vector3& color, - const char* title/* = "Choose Color"*/); - -// load a .bmp file and create a GtkImage widget from it -// NOTE: 'filename' is relative to /plugins/bitmaps/ -typedef struct _GtkImage GtkImage; -typedef GtkImage* (* PFN_QERAPP_NEWIMAGE) (const char* filename); - -// ======================================== - -namespace scene -{ - class Node; -} - -class ModuleObserver; - -#include "signal/signalfwd.h" -#include "windowobserver.h" -#include "generic/vector.h" - -typedef SignalHandler3 MouseEventHandler; -typedef SignalFwd::handler_id_type MouseEventHandlerId; - -enum VIEWTYPE -{ - YZ = 0, - XZ = 1, - XY = 2 -}; - -// the radiant core API -struct _QERFuncTable_1 -{ - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, "radiant"); - - const char* (*getEnginePath)(); - const char* (*getLocalRcPath)(); - const char* (*getGameToolsPath)(); - const char* (*getAppPath)(); - const char* (*getSettingsPath)(); - const char* (*getMapsPath)(); - - const char* (*getGameName)(); - const char* (*getGameMode)(); - - const char* (*getMapName)(); - scene::Node& (*getMapWorldEntity)(); - float (*getGridSize)(); - - const char* (*getGameDescriptionKeyValue)(const char* key); - const char* (*getRequiredGameDescriptionKeyValue)(const char* key); - - void (*attachGameToolsPathObserver)(ModuleObserver& observer); - void (*detachGameToolsPathObserver)(ModuleObserver& observer); - void (*attachEnginePathObserver)(ModuleObserver& observer); - void (*detachEnginePathObserver)(ModuleObserver& observer); - void (*attachGameNameObserver)(ModuleObserver& observer); - void (*detachGameNameObserver)(ModuleObserver& observer); - void (*attachGameModeObserver)(ModuleObserver& observer); - void (*detachGameModeObserver)(ModuleObserver& observer); - - SignalHandlerId (*XYWindowDestroyed_connect)(const SignalHandler& handler); - void (*XYWindowDestroyed_disconnect)(SignalHandlerId id); - MouseEventHandlerId (*XYWindowMouseDown_connect)(const MouseEventHandler& handler); - void (*XYWindowMouseDown_disconnect)(MouseEventHandlerId id); - VIEWTYPE (*XYWindow_getViewType)(); - Vector3 (*XYWindow_windowToWorld)(const WindowVector& position); - const char* (*TextureBrowser_getSelectedShader)(); - - // GTK+ functions - PFN_QERAPP_MESSAGEBOX m_pfnMessageBox; - PFN_QERAPP_FILEDIALOG m_pfnFileDialog; - PFN_QERAPP_DIRDIALOG m_pfnDirDialog; - PFN_QERAPP_COLORDIALOG m_pfnColorDialog; - PFN_QERAPP_NEWIMAGE m_pfnNewImage; - -}; - -#include "modulesystem.h" - -template -class GlobalModule; -typedef GlobalModule<_QERFuncTable_1> GlobalRadiantModule; - -template -class GlobalModuleRef; -typedef GlobalModuleRef<_QERFuncTable_1> GlobalRadiantModuleRef; - -inline _QERFuncTable_1& GlobalRadiant() -{ - return GlobalRadiantModule::getTable(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/renderable.cpp b/misc/mediasource/extra/netradiant-src/include/renderable.cpp deleted file mode 100644 index 9ca3673f..00000000 --- a/misc/mediasource/extra/netradiant-src/include/renderable.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "renderable.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/renderable.h b/misc/mediasource/extra/netradiant-src/include/renderable.h deleted file mode 100644 index de573910..00000000 --- a/misc/mediasource/extra/netradiant-src/include/renderable.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_RENDERABLE_H) -#define INCLUDED_RENDERABLE_H - -#include "generic/constant.h" - -class Shader; -class OpenGLRenderable; -class LightList; -class Matrix4; - -class Renderer -{ -public: - enum EHighlightMode - { - eFace = 1 << 0, - /*! Full highlighting. */ - ePrimitive = 1 << 1, - }; - - enum EStyle - { - eWireframeOnly, - eFullMaterials, - }; - - virtual void PushState() = 0; - virtual void PopState() = 0; - virtual void SetState(Shader* state, EStyle mode) = 0; - virtual const EStyle getStyle() const = 0; - virtual void Highlight(EHighlightMode mode, bool bEnable = true) = 0; - virtual void setLights(const LightList& lights) - { - } - virtual void addRenderable(const OpenGLRenderable& renderable, const Matrix4& world) = 0; -}; - -class VolumeTest; - -class Renderable -{ -public: - STRING_CONSTANT(Name, "Renderable"); - - virtual void renderSolid(Renderer& renderer, const VolumeTest& volume) const = 0; - virtual void renderWireframe(Renderer& renderer, const VolumeTest& volume) const = 0; - virtual void renderComponents(Renderer&, const VolumeTest&) const - { - } - virtual void viewChanged() const - { - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/selectable.cpp b/misc/mediasource/extra/netradiant-src/include/selectable.cpp deleted file mode 100644 index 206bebe4..00000000 --- a/misc/mediasource/extra/netradiant-src/include/selectable.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "selectable.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/selectable.h b/misc/mediasource/extra/netradiant-src/include/selectable.h deleted file mode 100644 index fffcfe29..00000000 --- a/misc/mediasource/extra/netradiant-src/include/selectable.h +++ /dev/null @@ -1,305 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_SELECTABLE_H) -#define INCLUDED_SELECTABLE_H - -#include - -#include "generic/vector.h" -#include "scenelib.h" -#include "generic/callbackfwd.h" - -class SelectionIntersection -{ - float m_depth; - float m_distance; -public: - SelectionIntersection() : m_depth(1), m_distance(2) - { - } - SelectionIntersection(float depth, float distance) : m_depth(depth), m_distance(distance) - { - } - bool operator<(const SelectionIntersection& other) const - { - if(m_distance != other.m_distance) - { - return m_distance < other.m_distance; - } - if(m_depth != other.m_depth) - { - return m_depth < other.m_depth; - } - return false; - } - bool equalEpsilon(const SelectionIntersection& other, float distanceEpsilon, float depthEpsilon) const - { - return float_equal_epsilon(m_distance, other.m_distance, distanceEpsilon) - && float_equal_epsilon(m_depth, other.m_depth, depthEpsilon); - } - float depth() const - { - return m_depth; - } - bool valid() const - { - return depth() < 1; - } -}; - -// returns true if self is closer than other -inline bool SelectionIntersection_closer(const SelectionIntersection& self, const SelectionIntersection& other) -{ - return self < other; -} - -// assigns other to best if other is closer than best -inline void assign_if_closer(SelectionIntersection& best, const SelectionIntersection& other) -{ - if(SelectionIntersection_closer(other, best)) - { - best = other; - } -} - - - - -class VertexPointer -{ - typedef const unsigned char* byte_pointer; -public: - typedef float elem_type; - typedef const elem_type* pointer; - typedef const elem_type& reference; - - class iterator - { - public: - iterator() {} - iterator(byte_pointer vertices, std::size_t stride) - : m_iter(vertices), m_stride(stride) {} - - bool operator==(const iterator& other) const - { - return m_iter == other.m_iter; - } - bool operator!=(const iterator& other) const - { - return !operator==(other); - } - - iterator operator+(std::size_t i) - { - return iterator(m_iter + i * m_stride, m_stride); - } - iterator operator+=(std::size_t i) - { - m_iter += i * m_stride; - return *this; - } - iterator& operator++() - { - m_iter += m_stride; - return *this; - } - iterator operator++(int) - { - iterator tmp = *this; - m_iter += m_stride; - return tmp; - } - reference operator*() const - { - return *reinterpret_cast(m_iter); - } - private: - byte_pointer m_iter; - std::size_t m_stride; - }; - - VertexPointer(pointer vertices, std::size_t stride) - : m_vertices(reinterpret_cast(vertices)), m_stride(stride) {} - - iterator begin() const - { - return iterator(m_vertices, m_stride); - } - - reference operator[](std::size_t i) const - { - return *reinterpret_cast(m_vertices + m_stride*i); - } - -private: - byte_pointer m_vertices; - std::size_t m_stride; -}; - -class IndexPointer -{ -public: - typedef unsigned int index_type; - typedef const index_type* pointer; - - class iterator - { - public: - iterator(pointer iter) : m_iter(iter) {} - - bool operator==(const iterator& other) const - { - return m_iter == other.m_iter; - } - bool operator!=(const iterator& other) const - { - return !operator==(other); - } - - iterator operator+(std::size_t i) - { - return m_iter + i; - } - iterator operator+=(std::size_t i) - { - return m_iter += i; - } - iterator operator++() - { - return ++m_iter; - } - iterator operator++(int) - { - return m_iter++; - } - const index_type& operator*() const - { - return *m_iter; - } - private: - void increment() - { - ++m_iter; - } - pointer m_iter; - }; - - IndexPointer(pointer indices, std::size_t count) - : m_indices(indices), m_finish(indices + count) {} - - iterator begin() const - { - return m_indices; - } - iterator end() const - { - return m_finish; - } - -private: - pointer m_indices; - pointer m_finish; -}; - -template class BasicVector3; -typedef BasicVector3 Vector3; -class Matrix4; -class VolumeTest; - -class SelectionTest -{ -public: - virtual void BeginMesh(const Matrix4& localToWorld, bool twoSided = false) = 0; - virtual const VolumeTest& getVolume() const = 0; - virtual const Vector3& getNear() const = 0; - virtual const Vector3& getFar() const = 0; - virtual void TestPoint(const Vector3& point, SelectionIntersection& best) = 0; - virtual void TestPolygon(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestLineLoop(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestLineStrip(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestLines(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; - virtual void TestTriangles(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; - virtual void TestQuads(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; - virtual void TestQuadStrip(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; -}; - -class Selectable; - -class Selector -{ -public: - virtual void pushSelectable(Selectable& selectable) = 0; - virtual void popSelectable() = 0; - virtual void addIntersection(const SelectionIntersection& intersection) = 0; -}; - -inline void Selector_add(Selector& selector, Selectable& selectable) -{ - selector.pushSelectable(selectable); - selector.addIntersection(SelectionIntersection(0, 0)); - selector.popSelectable(); -} - -inline void Selector_add(Selector& selector, Selectable& selectable, const SelectionIntersection& intersection) -{ - selector.pushSelectable(selectable); - selector.addIntersection(intersection); - selector.popSelectable(); -} - - -class VolumeTest; -class SelectionTestable -{ -public: - STRING_CONSTANT(Name, "SelectionTestable"); - - virtual void testSelect(Selector& selector, SelectionTest& test) = 0; -}; - -inline SelectionTestable* Instance_getSelectionTestable(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); -} - - -class Plane3; -typedef Callback1 PlaneCallback; - -class SelectedPlanes -{ -public: - virtual bool contains(const Plane3& plane) const = 0; -}; - -class PlaneSelectable -{ -public: - STRING_CONSTANT(Name, "PlaneSelectable"); - - virtual void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) = 0; - virtual void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) = 0; -}; - - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/stream_version.h b/misc/mediasource/extra/netradiant-src/include/stream_version.h deleted file mode 100644 index 17ce6339..00000000 --- a/misc/mediasource/extra/netradiant-src/include/stream_version.h +++ /dev/null @@ -1,3 +0,0 @@ -// version defines for q3map stream -#define Q3MAP_STREAM_VERSION "1" - diff --git a/misc/mediasource/extra/netradiant-src/include/version.h b/misc/mediasource/extra/netradiant-src/include/version.h deleted file mode 100644 index 47134512..00000000 --- a/misc/mediasource/extra/netradiant-src/include/version.h +++ /dev/null @@ -1,10 +0,0 @@ -// Makefile appends preprocessor flags instead now -#ifndef RADIANT_VERSION -#error no RADIANT_VERSION defined -#endif -#ifndef RADIANT_MAJOR_VERSION -#error no RADIANT_MAJOR_VERSION defined -#endif -#ifndef RADIANT_MINOR_VERSION -#error no RADIANT_MINOR_VERSION defined -#endif diff --git a/misc/mediasource/extra/netradiant-src/include/warnings.h b/misc/mediasource/extra/netradiant-src/include/warnings.h deleted file mode 100644 index 66415614..00000000 --- a/misc/mediasource/extra/netradiant-src/include/warnings.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (INCLUDED_WARNINGS_H) -#define INCLUDED_WARNINGS_H - -#if _MSC_VER > 1000 && defined(WIN32) -#pragma warning(disable:4355) // 'this' : used in base member initializer list -#pragma warning(disable:4503) // '[symbol]' : decorated name length exceeded, name was truncated -#endif - -#endif - diff --git a/misc/mediasource/extra/netradiant-src/include/windowobserver.cpp b/misc/mediasource/extra/netradiant-src/include/windowobserver.cpp deleted file mode 100644 index 2e59b8c0..00000000 --- a/misc/mediasource/extra/netradiant-src/include/windowobserver.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "windowobserver.h" - diff --git a/misc/mediasource/extra/netradiant-src/include/windowobserver.h b/misc/mediasource/extra/netradiant-src/include/windowobserver.h deleted file mode 100644 index 99fc03da..00000000 --- a/misc/mediasource/extra/netradiant-src/include/windowobserver.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_WINDOWOBSERVER_H) -#define INCLUDED_WINDOWOBSERVER_H - -template class BitFieldValue; -struct ModifierEnumeration; -typedef BitFieldValue ModifierFlags; - -template class EnumeratedValue; -struct ButtonEnumeration; -typedef EnumeratedValue ButtonIdentifier; - - -#include "generic/bitfield.h" - -struct ModifierEnumeration -{ - enum Value - { - SHIFT = 0, - CONTROL = 1, - ALT = 2 - }; -}; - -typedef BitFieldValue ModifierFlags; - -const ModifierFlags c_modifierNone; -const ModifierFlags c_modifierShift(ModifierEnumeration::SHIFT); -const ModifierFlags c_modifierControl(ModifierEnumeration::CONTROL); -const ModifierFlags c_modifierAlt(ModifierEnumeration::ALT); - -#include "generic/enumeration.h" - -struct ButtonEnumeration -{ - enum Value - { - INVALID = 0, - LEFT = 1, - MIDDLE = 3, - RIGHT = 2 - }; -}; - -typedef EnumeratedValue ButtonIdentifier; - -const ButtonIdentifier c_buttonInvalid(ButtonEnumeration::INVALID); -const ButtonIdentifier c_buttonLeft(ButtonEnumeration::LEFT); -const ButtonIdentifier c_buttonMiddle(ButtonEnumeration::MIDDLE); -const ButtonIdentifier c_buttonRight(ButtonEnumeration::RIGHT); - - -template -class BasicVector2; -typedef BasicVector2 Vector2; -typedef Vector2 WindowVector; - -class WindowObserver -{ -public: - virtual void release() = 0; - virtual void onSizeChanged(int width, int height) = 0; - virtual void onMouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) = 0; - virtual void onMouseUp(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) = 0; - virtual void onMouseMotion(const WindowVector& position, ModifierFlags modifiers) = 0; - virtual void onModifierDown(ModifierFlags modifier) = 0; - virtual void onModifierUp(ModifierFlags modifier) = 0; -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/install-dlls.sh b/misc/mediasource/extra/netradiant-src/install-dlls.sh deleted file mode 100644 index f83e3862..00000000 --- a/misc/mediasource/extra/netradiant-src/install-dlls.sh +++ /dev/null @@ -1,193 +0,0 @@ -#!/bin/sh - -set -ex - -: ${WHICHDLL:=which} -: ${GTKDIR:=/gtk} -: ${CP:=cp} -: ${CAT:=cat} -: ${MKDIR:=mkdir -p} -: ${INSTALLDIR:=.} - -for DLL in \ - freetype6.dll \ - intl.dll \ - libatk-1.0-0.dll \ - libcairo-2.dll \ - libexpat-1.dll \ - libfontconfig-1.dll \ - libgdkglext-win32-1.0-0.dll \ - libgdk_pixbuf-2.0-0.dll \ - libgdk-win32-2.0-0.dll \ - libgio-2.0-0.dll \ - libglib-2.0-0.dll \ - libgmodule-2.0-0.dll \ - libgobject-2.0-0.dll \ - libgthread-2.0-0.dll \ - libgtkglext-win32-1.0-0.dll \ - libgtk-win32-2.0-0.dll \ - libpango-1.0-0.dll \ - libpangocairo-1.0-0.dll \ - libpangoft2-1.0-0.dll \ - libpangowin32-1.0-0.dll \ - libpng14-14.dll \ - libxml2-2.dll \ - zlib1.dll \ -; do - $CP "`$WHICHDLL $DLL`" $INSTALLDIR/ -done - -$MKDIR $INSTALLDIR/etc/fonts -$CAT > $INSTALLDIR/etc/fonts/fonts.conf < - - - - - - - - - WINDOWSFONTDIR - - ~/.fonts - - - - - mono - - - monospace - - - - - - - sans serif - - - sans-serif - - - - - - - sans - - - sans-serif - - - - - conf.d - - - - WINDOWSTEMPDIR_FONTCONFIG_CACHE - ~/.fontconfig - - - - - 0x0020 - 0x00A0 - 0x00AD - 0x034F - 0x0600 - 0x0601 - 0x0602 - 0x0603 - 0x06DD - 0x070F - 0x115F - 0x1160 - 0x1680 - 0x17B4 - 0x17B5 - 0x180E - 0x2000 - 0x2001 - 0x2002 - 0x2003 - 0x2004 - 0x2005 - 0x2006 - 0x2007 - 0x2008 - 0x2009 - 0x200A - 0x200B - 0x200C - 0x200D - 0x200E - 0x200F - 0x2028 - 0x2029 - 0x202A - 0x202B - 0x202C - 0x202D - 0x202E - 0x202F - 0x205F - 0x2060 - 0x2061 - 0x2062 - 0x2063 - 0x206A - 0x206B - 0x206C - 0x206D - 0x206E - 0x206F - 0x2800 - 0x3000 - 0x3164 - 0xFEFF - 0xFFA0 - 0xFFF9 - 0xFFFA - 0xFFFB - - - - 30 - - - - -EOF diff --git a/misc/mediasource/extra/netradiant-src/install-dylibs.sh b/misc/mediasource/extra/netradiant-src/install-dylibs.sh deleted file mode 100644 index 798a7d14..00000000 --- a/misc/mediasource/extra/netradiant-src/install-dylibs.sh +++ /dev/null @@ -1,71 +0,0 @@ -#!/bin/sh - -set -ex - -: ${OTOOL:=otool} -: ${CP:=cp} -: ${INSTALLDIR:=.} -: ${EXE:=ppc} -: ${MACLIBDIR:=/sw/lib} -: ${CAT:=cat} - - -finkgetdeps() -{ - otool -L "$1" | grep "$MACLIBDIR" | while read -r LIB STUFF; do - [ -z "${LIB##*:}" ] && continue # first line - [ -f "$INSTALLDIR/${LIB##*/}" ] && continue - cp -vL "$LIB" "$INSTALLDIR" - finkgetdeps "$LIB" - done -} - - -finkgetdeps "$INSTALLDIR/radiant.$EXE" -echo Warning: this only works if only ONE version of gtk-2.0 and pango is installed - -for LIB in "$MACLIBDIR"/gtk-2.0/*/loaders/libpixbufloader-bmp.so; do - LAST=$LIB -done -cp -L "$LAST" "$INSTALLDIR" -finkgetdeps "$LAST" - -for LIB in "$MACLIBDIR"/pango/*/modules/pango-basic-fc.so; do - LAST=$LIB -done -cp -L "$LAST" "$INSTALLDIR" -finkgetdeps "$LAST" - -for LIB in "$MACLIBDIR"/pango/*/modules/pango-basic-x.so; do - LAST=$LIB -done -cp -L "$LAST" "$INSTALLDIR" -finkgetdeps "$LAST" - -cp -L "$MACLIBDIR"/../etc/fonts/fonts.conf "$INSTALLDIR" -cp -L "$MACLIBDIR"/../etc/fonts/fonts.dtd "$INSTALLDIR" -cp -L "$MACLIBDIR"/../etc/gtk-2.0/gdk-pixbuf.loaders "$INSTALLDIR" -cp -L "$MACLIBDIR"/../etc/pango/pangorc "$INSTALLDIR" - -$CAT > "$INSTALLDIR/../netradiant.sh" < -class SingleByteInputStream -{ - typedef typename InputStreamType::byte_type byte_type; - - InputStreamType& m_inputStream; - byte_type m_buffer[SIZE]; - byte_type* m_cur; - byte_type* m_end; - -public: - - SingleByteInputStream(InputStreamType& inputStream) : m_inputStream(inputStream), m_cur(m_buffer + SIZE), m_end(m_cur) - { - } - bool readByte(byte_type& b) - { - if(m_cur == m_end) - { - if(m_end != m_buffer + SIZE) - { - return false; - } - - m_end = m_buffer + m_inputStream.read(m_buffer, SIZE); - 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/misc/mediasource/extra/netradiant-src/libs/bytebool.cpp b/misc/mediasource/extra/netradiant-src/libs/bytebool.cpp deleted file mode 100644 index 036061fe..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/bytebool.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "bytebool.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/bytebool.h b/misc/mediasource/extra/netradiant-src/libs/bytebool.h deleted file mode 100644 index 4009c2dd..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/bytebool.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright (C) 1999-2006 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 __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/misc/mediasource/extra/netradiant-src/libs/bytestreamutils.cpp b/misc/mediasource/extra/netradiant-src/libs/bytestreamutils.cpp deleted file mode 100644 index f9b8ddca..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/bytestreamutils.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "bytestreamutils.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/bytestreamutils.h b/misc/mediasource/extra/netradiant-src/libs/bytestreamutils.h deleted file mode 100644 index aad7d7e4..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/bytestreamutils.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_BYTESTREAMUTILS_H) -#define INCLUDED_BYTESTREAMUTILS_H - -#if defined(__GNUC__) - -#define _ISOC9X_SOURCE 1 -#define _ISOC99_SOURCE 1 - -#define __USE_ISOC9X 1 -#define __USE_ISOC99 1 - -#include - -#endif - -#include - -// if C99 is unavailable, fall back to the types most likely to be the right sizes -#if !defined(int16_t) -typedef signed short int16_t; -#endif -#if !defined(uint16_t) -typedef unsigned short uint16_t; -#endif -#if !defined(int32_t) -typedef signed int int32_t; -#endif -#if !defined(uint32_t) -typedef unsigned int uint32_t; -#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/misc/mediasource/extra/netradiant-src/libs/character.cpp b/misc/mediasource/extra/netradiant-src/libs/character.cpp deleted file mode 100644 index ab8969b6..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/character.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "character.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/character.h b/misc/mediasource/extra/netradiant-src/libs/character.h deleted file mode 100644 index 1e6d3b16..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/character.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/cmdlib.h b/misc/mediasource/extra/netradiant-src/libs/cmdlib.h deleted file mode 100644 index 8961bd2a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/cmdlib.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright (C) 1999-2006 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, bool waitfor); - -// 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/misc/mediasource/extra/netradiant-src/libs/cmdlib/.cvswrappers b/misc/mediasource/extra/netradiant-src/libs/cmdlib/.cvswrappers deleted file mode 100644 index ed97d402..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/cmdlib/.cvswrappers +++ /dev/null @@ -1,3 +0,0 @@ -*.dsp -m 'COPY' -k 'b' -*.dsw -m 'COPY' -k 'b' -*.scc -m 'COPY' -k 'b' diff --git a/misc/mediasource/extra/netradiant-src/libs/cmdlib/cmdlib.cpp b/misc/mediasource/extra/netradiant-src/libs/cmdlib/cmdlib.cpp deleted file mode 100644 index f6ace0fe..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/cmdlib/cmdlib.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright (C) 1999-2006 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" - - -#if defined (POSIX) - -#include -#include -#include - -bool Q_Exec(const char *cmd, char *cmdline, const char *, bool, bool waitfor) -{ - char fullcmd[2048]; - char *pCmd; - pid_t pid; -#ifdef _DEBUG - printf("Q_Exec damnit\n"); -#endif - switch ((pid = fork())) - { - default: - if(waitfor) - waitpid(pid, NULL, 0); - break; - 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; -} - -#elif defined(WIN32) - -#include - -// NOTE TTimo windows is VERY nitpicky about the syntax in CreateProcess -bool Q_Exec(const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole, bool waitfor) -{ - 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 - )) - { - if(waitfor) - WaitForSingleObject(ProcessInformation.hProcess, INFINITE); - return true; - } - return false; -} - -#endif - diff --git a/misc/mediasource/extra/netradiant-src/libs/container/array.cpp b/misc/mediasource/extra/netradiant-src/libs/container/array.cpp deleted file mode 100644 index 378a2e76..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/array.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/container/array.h b/misc/mediasource/extra/netradiant-src/libs/container/array.h deleted file mode 100644 index de444fd8..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/array.h +++ /dev/null @@ -1,197 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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) - { - if(other.size() == size()) - { - std::copy(other.begin(), other.end(), begin()); - } - else - { - 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/misc/mediasource/extra/netradiant-src/libs/container/cache.cpp b/misc/mediasource/extra/netradiant-src/libs/container/cache.cpp deleted file mode 100644 index a704287e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/cache.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "cache.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/container/cache.h b/misc/mediasource/extra/netradiant-src/libs/container/cache.h deleted file mode 100644 index 8c594b88..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/cache.h +++ /dev/null @@ -1,206 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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. -/// \param CreationPolicy Must define 'Cached* construct(const Key&)' and 'void destroy(Cached*)'. The lifetime of the \c Key passed to 'construct' is guaranteed to be longer than the subsequent matched call to 'destroy'. -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) - { -#if 0 - Element& elem = m_map[key]; - if(elem.increment() == 1) - { - elem.set(CreationPolicy::construct(key)); - } - return elem; -#else - iterator i = m_map.insert(key, Element()); - if((*i).value.increment() == 1) - { - (*i).value.set(CreationPolicy::construct((*i).key)); - } - return (*i).value; -#endif - } -#else - value_type& capture(const Key& key) - { - iterator i = m_map.find(key); - if(i == m_map.end()) - { - i = m_map.insert(key, Element()); - (*i).value.set(CreationPolicy::construct((*i).key)); - } - (*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/misc/mediasource/extra/netradiant-src/libs/container/container.cpp b/misc/mediasource/extra/netradiant-src/libs/container/container.cpp deleted file mode 100644 index 627e0c88..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/container.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "container.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/container/container.h b/misc/mediasource/extra/netradiant-src/libs/container/container.h deleted file mode 100644 index b6d75841..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/container.h +++ /dev/null @@ -1,393 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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); - } -} - -template -class ReferencePair -{ - Type* m_first; - Type* m_second; -public: - ReferencePair() : m_first(0), m_second(0) - { - } - void attach(Type& t) - { - ASSERT_MESSAGE(m_first == 0 || m_second == 0, "ReferencePair::insert: pointer already exists"); - if(m_first == 0) - { - m_first = &t; - } - else if(m_second == 0) - { - m_second = &t; - } - } - void detach(Type& t) - { - ASSERT_MESSAGE(m_first == &t || m_second == &t, "ReferencePair::erase: pointer not found"); - if(m_first == &t) - { - m_first = 0; - } - else if(m_second == &t) - { - m_second = 0; - } - } - template - void forEach(const Functor& functor) - { - if(m_second != 0) - { - functor(*m_second); - } - if(m_first != 0) - { - functor(*m_first); - } - } -}; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/container/hashfunc.cpp b/misc/mediasource/extra/netradiant-src/libs/container/hashfunc.cpp deleted file mode 100644 index 20569cd1..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/hashfunc.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "hashfunc.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/container/hashfunc.h b/misc/mediasource/extra/netradiant-src/libs/container/hashfunc.h deleted file mode 100644 index a4ec5fee..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/hashfunc.h +++ /dev/null @@ -1,434 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_CONTAINER_HASHFUNC_H) -#define INCLUDED_CONTAINER_HASHFUNC_H - -#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)); - } -}; - -// lookup2.c -// By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this -// code any way you wish, private, educational, or commercial. It's free. - -#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 RawStringHash -{ - typedef hash_t hash_type; - hash_type operator()(const char* string) const - { - return string_hash(string); - } -}; - -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/misc/mediasource/extra/netradiant-src/libs/container/hashtable.cpp b/misc/mediasource/extra/netradiant-src/libs/container/hashtable.cpp deleted file mode 100644 index e4d02c93..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/hashtable.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/container/hashtable.h b/misc/mediasource/extra/netradiant-src/libs/container/hashtable.h deleted file mode 100644 index 88d672cf..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/hashtable.h +++ /dev/null @@ -1,474 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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() const - { - return static_cast(next); - } - BucketNode* getPrev() const - { - 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*() const - { - return m_node->m_value; - } - value_type* operator->() const - { - 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. - 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) - { - 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/misc/mediasource/extra/netradiant-src/libs/container/stack.cpp b/misc/mediasource/extra/netradiant-src/libs/container/stack.cpp deleted file mode 100644 index 3a7c7ce2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/stack.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "stack.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/container/stack.h b/misc/mediasource/extra/netradiant-src/libs/container/stack.h deleted file mode 100644 index d83674c3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/container/stack.h +++ /dev/null @@ -1,239 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/convert.cpp b/misc/mediasource/extra/netradiant-src/libs/convert.cpp deleted file mode 100644 index 0e73aef7..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/convert.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "convert.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/convert.h b/misc/mediasource/extra/netradiant-src/libs/convert.h deleted file mode 100644 index f7f4f992..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/convert.h +++ /dev/null @@ -1,305 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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.first; p != convert.m_range.last;) - { - 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.first; p != convert.m_range.last; ++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/misc/mediasource/extra/netradiant-src/libs/ddslib.h b/misc/mediasource/extra/netradiant-src/libs/ddslib.h deleted file mode 100644 index 3f5f124c..00000000 --- a/misc/mediasource/extra/netradiant-src/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/misc/mediasource/extra/netradiant-src/libs/ddslib/ddslib.c b/misc/mediasource/extra/netradiant-src/libs/ddslib/ddslib.c deleted file mode 100644 index 424faeea..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/ddslib/ddslib.c +++ /dev/null @@ -1,781 +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*) ((char *) 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*) ((char *) 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*) ((char *) 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/misc/mediasource/extra/netradiant-src/libs/debugging/debugging.cpp b/misc/mediasource/extra/netradiant-src/libs/debugging/debugging.cpp deleted file mode 100644 index 23784950..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/debugging/debugging.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "debugging.h" - -void TEST_ASSERT() -{ - ERROR_MESSAGE("test"); - ASSERT_NOTNULL(0); -} diff --git a/misc/mediasource/extra/netradiant-src/libs/debugging/debugging.h b/misc/mediasource/extra/netradiant-src/libs/debugging/debugging.h deleted file mode 100644 index 4c03e9d7..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/debugging/debugging.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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 STR(x) #x -#define STR2(x) STR(x) -#define FILE_LINE __FILE__ ":" STR2(__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) do{\ -if(!(condition))\ -{\ - globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nassertion failure: " << message << "\n";\ - if(!globalDebugMessageHandler().handleMessage()) { DEBUGGER_BREAKPOINT(); }\ -}} while(0) - -/// \brief Sends a \p message to the current debug-message-handler text-output-stream. -#define ERROR_MESSAGE(message) do{\ -globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nruntime error: " << message << "\n";\ -if(!globalDebugMessageHandler().handleMessage()) { DEBUGGER_BREAKPOINT(); }} while(0) - -#define ASSERT_NOTNULL(ptr) ASSERT_MESSAGE(ptr != 0, "pointer \"" #ptr "\" is null") - -#else - -#define ASSERT_MESSAGE(condition, message) -#define ERROR_MESSAGE(message) -#define ASSERT_NOTNULL(ptr) - -#endif - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/dragplanes.cpp b/misc/mediasource/extra/netradiant-src/libs/dragplanes.cpp deleted file mode 100644 index 9c7e18f8..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/dragplanes.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "dragplanes.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/dragplanes.h b/misc/mediasource/extra/netradiant-src/libs/dragplanes.h deleted file mode 100644 index a8b54dc1..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/dragplanes.h +++ /dev/null @@ -1,259 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_DRAGPLANES_H) -#define INCLUDED_DRAGPLANES_H - -#include "selectable.h" -#include "selectionlib.h" -#include "math/aabb.h" -#include "math/line.h" - -// local must be a pure rotation -inline Vector3 translation_to_local(const Vector3& translation, const Matrix4& local) -{ - return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3(matrix4_transposed(local), translation), - local - ) - ); -} - -// local must be a pure rotation -inline Vector3 translation_from_local(const Vector3& translation, const Matrix4& local) -{ - return matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3(local, translation), - matrix4_transposed(local) - ) - ); -} - -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 - AABB m_bounds; - - 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, const Matrix4& rotation = g_matrix4_identity) - { - Line line(test.getNear(), test.getFar()); - Vector3 corners[8]; - aabb_corners_oriented(aabb, rotation, corners); - - Plane3 planes[6]; - aabb_planes_oriented(aabb, rotation, 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); - selectedPlaneCallback(planes[5]); - //globalOutputStream() << "bottom\n"; - } - - m_bounds = aabb; - } - void selectReversedPlanes(const AABB& aabb, Selector& selector, const SelectedPlanes& selectedPlanes, const Matrix4& rotation = g_matrix4_identity) - { - Plane3 planes[6]; - aabb_planes_oriented(aabb, rotation, 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); - } - } - AABB evaluateResize(const Vector3& translation) const - { - Vector3 min = m_bounds.origin - m_bounds.extents; - Vector3 max = m_bounds.origin + m_bounds.extents; - if(m_bounds.extents[0] != 0) - { - if(m_selectable_right.isSelected()) - { - max[0] += translation[0]; - //globalOutputStream() << "moving right\n"; - } - if(m_selectable_left.isSelected()) - { - min[0] += translation[0]; - //globalOutputStream() << "moving left\n"; - } - } - if(m_bounds.extents[1] != 0) - { - if(m_selectable_front.isSelected()) - { - max[1] += translation[1]; - //globalOutputStream() << "moving front\n"; - } - if(m_selectable_back.isSelected()) - { - min[1] += translation[1]; - //globalOutputStream() << "moving back\n"; - } - } - if(m_bounds.extents[2] != 0) - { - if(m_selectable_top.isSelected()) - { - max[2] += translation[2]; - //globalOutputStream() << "moving top\n"; - } - if(m_selectable_bottom.isSelected()) - { - min[2] += translation[2]; - //globalOutputStream() << "moving bottom\n"; - } - } - - return AABB(vector3_mid(min, max), vector3_scaled(vector3_subtracted(max, min), 0.5)); - } - AABB evaluateResize(const Vector3& translation, const Matrix4& rotation) const - { - AABB aabb(evaluateResize(translation_to_local(translation, rotation))); - aabb.origin = m_bounds.origin + translation_from_local(aabb.origin - m_bounds.origin, rotation); - return aabb; - } - Matrix4 evaluateTransform(const Vector3& translation) const - { - AABB aabb(evaluateResize(translation)); - Vector3 scale( - m_bounds.extents[0] != 0 ? aabb.extents[0] / m_bounds.extents[0] : 1, - m_bounds.extents[1] != 0 ? aabb.extents[1] / m_bounds.extents[1] : 1, - m_bounds.extents[2] != 0 ? aabb.extents[2] / m_bounds.extents[2] : 1 - ); - - Matrix4 matrix(matrix4_translation_for_vec3(aabb.origin - m_bounds.origin)); - matrix4_pivoted_scale_by_vec3(matrix, scale, m_bounds.origin); - - return matrix; - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/eclasslib.cpp b/misc/mediasource/extra/netradiant-src/libs/eclasslib.cpp deleted file mode 100644 index a320bc26..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/eclasslib.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "eclasslib.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/eclasslib.h b/misc/mediasource/extra/netradiant-src/libs/eclasslib.h deleted file mode 100644 index 7bee547b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/eclasslib.h +++ /dev/null @@ -1,341 +0,0 @@ -/* -Copyright (C) 1999-2006 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 (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/misc/mediasource/extra/netradiant-src/libs/entitylib.cpp b/misc/mediasource/extra/netradiant-src/libs/entitylib.cpp deleted file mode 100644 index 385d0f2e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/entitylib.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "entitylib.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/entitylib.h b/misc/mediasource/extra/netradiant-src/libs/entitylib.h deleted file mode 100644 index 667adf72..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/entitylib.h +++ /dev/null @@ -1,756 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (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/pooledstring.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_forward, const Vector3& direction_left, const Vector3& direction_up) -{ - Vector3 endpoint(vector3_added(origin, vector3_scaled(direction_forward, 32.0))); - - Vector3 tip1(vector3_added(vector3_added(endpoint, vector3_scaled(direction_forward, -8.0)), vector3_scaled(direction_up, -4.0))); - Vector3 tip2(vector3_added(tip1, vector3_scaled(direction_up, 8.0))); - Vector3 tip3(vector3_added(vector3_added(endpoint, vector3_scaled(direction_forward, -8.0)), vector3_scaled(direction_left, -4.0))); - Vector3 tip4(vector3_added(tip3, vector3_scaled(direction_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]) -{ - unsigned int indices[26] = { - 0, 1, 1, 2, 2, 3, 3, 0, - 4, 5, 5, 6, 6, 7, 7, 4, - 0, 4, 1, 5, 2, 6, 3, 7, - // 0, 6, 1, 7, 2, 4, 3, 5 // X cross - 1, 7 // diagonal line (connect mins to maxs corner) - }; -#if 1 - glVertexPointer(3, GL_FLOAT, 0, points); - glDrawElements(GL_LINES, sizeof(indices)/sizeof(indices[0]), GL_UNSIGNED_INT, indices); -#else - glBegin(GL_LINES); - for(std::size_t i = 0; i < sizeof(indices)/sizeof(indices[0]); ++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); - } -}; - - -/// \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 : public EntityKeyValue -{ - 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; - - static StringPool& getPool() - { - return Static::instance(); - } -private: - static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; - static Counter* m_counter; - - EntityClass* m_eclass; - - class KeyContext{}; - typedef Static KeyPool; - typedef PooledString Key; - 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()); - } - - Key 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: - bool m_isContainer; - - EntityKeyValues(EntityClass* eclass) : - m_eclass(eclass), - m_undo(m_keyValues, UndoImportCaller(*this)), - m_instanced(false), - m_observerMutex(false), - m_isContainer(!eclass->fixedsize) - { - } - EntityKeyValues(const EntityKeyValues& other) : - Entity(other), - m_eclass(&other.getEntityClass()), - m_undo(m_keyValues, UndoImportCaller(*this)), - m_instanced(false), - m_observerMutex(false), - m_isContainer(other.m_isContainer) - { - 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() - { - for(Observers::iterator i = m_observers.begin(); i != m_observers.end();) - { - // post-increment to allow current element to be removed safely - (*i++)->clear(); - } - 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); - } - - bool isContainer() const - { - return m_isContainer; - } -}; - -/// \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/misc/mediasource/extra/netradiant-src/libs/entityxml.cpp b/misc/mediasource/extra/netradiant-src/libs/entityxml.cpp deleted file mode 100644 index 175c4818..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/entityxml.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "entityxml.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/entityxml.h b/misc/mediasource/extra/netradiant-src/libs/entityxml.h deleted file mode 100644 index 50df739b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/entityxml.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/fs_filesystem.cpp b/misc/mediasource/extra/netradiant-src/libs/fs_filesystem.cpp deleted file mode 100644 index f0820982..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/fs_filesystem.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "fs_filesystem.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/fs_filesystem.h b/misc/mediasource/extra/netradiant-src/libs/fs_filesystem.h deleted file mode 100644 index 0c22a4b3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/fs_filesystem.h +++ /dev/null @@ -1,183 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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(StringRange range) - : m_path(range), 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() : m_file(0) - { - } - 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; - typedef Entry entry_type; - - iterator begin() - { - return m_entries.begin(); - } - iterator end() - { - return m_entries.end(); - } - - /// \brief Returns the file at \p path. - /// Creates all directories below \p path if they do not exist. - /// O(log n) on average. - entry_type& operator[](const Path& path) - { - { - const char* end = path_remove_directory(path.c_str()); - while(end[0] != '\0') - { - Path dir(StringRange(path.c_str(), end)); - m_entries.insert(value_type(dir, Entry(0))); - end = path_remove_directory(end); - } - } - - return m_entries[path]; - } - - /// \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/misc/mediasource/extra/netradiant-src/libs/fs_path.cpp b/misc/mediasource/extra/netradiant-src/libs/fs_path.cpp deleted file mode 100644 index 5cd36406..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/fs_path.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "fs_path.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/fs_path.h b/misc/mediasource/extra/netradiant-src/libs/fs_path.h deleted file mode 100644 index df409ef0..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/fs_path.h +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/generic/arrayrange.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/arrayrange.cpp deleted file mode 100644 index b04ba068..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/arrayrange.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "arrayrange.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/arrayrange.h b/misc/mediasource/extra/netradiant-src/libs/generic/arrayrange.h deleted file mode 100644 index a05489a1..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/arrayrange.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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 first, Iterator last) - : first(first), last(last) - { - } - Iterator first; - Iterator last; -}; - -template -inline ArrayRange makeArrayRange(Element* first, Element* last) -{ - return ArrayRange(first, last); -} - -template -struct ArrayConstRange -{ - typedef const Element* Iterator; - ArrayConstRange(Iterator first, Iterator last) - : first(first), last(last) - { - } - Iterator first; - Iterator last; -}; - -template -inline ArrayConstRange makeArrayRange(const Element* first, const Element* last) -{ - return ArrayConstRange(first, last); -} - -#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))) - -typedef ArrayRange StringRange; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/bitfield.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/bitfield.cpp deleted file mode 100644 index 96d15c9c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/bitfield.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "bitfield.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/bitfield.h b/misc/mediasource/extra/netradiant-src/libs/generic/bitfield.h deleted file mode 100644 index 652f0539..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/bitfield.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/generic/callback.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/callback.cpp deleted file mode 100644 index 2344830a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/callback.cpp +++ /dev/null @@ -1,285 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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 - -namespace -{ - class A1 - { - }; - class A2 - { - }; - class A3 - { - }; - class A4 - { - }; - - class Test - { - public: - void test0() - { - } - typedef Member Test0; - typedef MemberCaller Test0Caller; - void test0const() const - { - } - typedef ConstMember Test0Const; - typedef ConstMemberCaller Test0ConstCaller; - void test1(A1) - { - } - typedef Member1 Test1; - typedef MemberCaller1 Test1Caller; - void test1const(A1) const - { - } - typedef ConstMember1 Test1Const; - typedef ConstMemberCaller1 Test1ConstCaller; - void test2(A1, A2) - { - } - typedef Member2 Test2; - void test2const(A1, A2) const - { - } - typedef ConstMember2 Test2Const; - void test3(A1, A2, A3) - { - } - typedef Member3 Test3; - void test3const(A1, A2, A3) const - { - } - typedef ConstMember3 Test3Const; - }; - - void test0free() - { - } - typedef FreeCaller<&test0free> Test0FreeCaller; - void test1free(A1) - { - } - typedef FreeCaller1 Test1FreeCaller; - void test2free(A1, A2) - { - } - typedef Function2 Test2Free; - void test3free(A1, A2, A3) - { - } - typedef Function3 Test3Free; - - - void test0(Test& test) - { - } - typedef ReferenceCaller Test0Caller; - - void test0const(const Test& test) - { - } - typedef ConstReferenceCaller Test0ConstCaller; - - void test0p(Test* test) - { - } - typedef PointerCaller Test0PCaller; - - void test0constp(const Test* test) - { - } - typedef ConstPointerCaller Test0ConstPCaller; - - void test1(Test& test, A1) - { - } - typedef ReferenceCaller1 Test1Caller; - - void test1const(const Test& test, A1) - { - } - typedef ConstReferenceCaller1 Test1ConstCaller; - - void test1p(Test* test, A1) - { - } - typedef PointerCaller1 Test1PCaller; - - void test1constp(const Test* test, A1) - { - } - typedef ConstPointerCaller1 Test1ConstPCaller; - - void test2(Test& test, A1, A2) - { - } - typedef Function3 Test2; - - void test3(Test& test, A1, A2, A3) - { - } - typedef Function4 Test3; - - void instantiate() - { - Test test; - const Test& testconst = test; - { - Callback a = Test0FreeCaller(); - Callback b = Test::Test0Caller(test); - b = makeCallback0(Test::Test0(), test); - Callback c = Test::Test0ConstCaller(testconst); - c = makeCallback0(Test::Test0Const(), test); - Callback d = Test0Caller(test); - Callback e = Test0ConstCaller(testconst); - Callback f = Test0PCaller(&test); - Callback g = Test0ConstPCaller(&testconst); - a(); - bool u = a != b; - } - { - typedef Callback1 TestCallback1; - TestCallback1 a = Test1FreeCaller(); - TestCallback1 b = Test::Test1Caller(test); - b = makeCallback1(Test::Test1(), test); - TestCallback1 c = Test::Test1ConstCaller(testconst); - c = makeCallback1(Test::Test1Const(), test); - TestCallback1 d = Test1Caller(test); - TestCallback1 e = Test1ConstCaller(testconst); - TestCallback1 f = Test1PCaller(&test); - TestCallback1 g = Test1ConstPCaller(&testconst); - a(A1()); - bool u = a != b; - } - { - typedef Callback2 TestCallback2; - TestCallback2 a = makeStatelessCallback2(Test2Free()); - TestCallback2 b = makeCallback2(Test2(), test); - TestCallback2 c = makeCallback2(Test::Test2(), test); - TestCallback2 d = makeCallback2(Test::Test2Const(), test); - a(A1(), A2()); - bool u = a != b; - } - { - typedef Callback3 TestCallback3; - TestCallback3 a = makeStatelessCallback3(Test3Free()); - TestCallback3 b = makeCallback3(Test3(), test); - TestCallback3 c = makeCallback3(Test::Test3(), test); - TestCallback3 d = makeCallback3(Test::Test3Const(), test); - a(A1(), A2(), A3()); - bool u = a != b; - } - } -} diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/callback.h b/misc/mediasource/extra/netradiant-src/libs/generic/callback.h deleted file mode 100644 index 7141da4a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/callback.h +++ /dev/null @@ -1,670 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GENERIC_CLOSURE_H) -#define INCLUDED_GENERIC_CLOSURE_H - -/// \file -/// \brief Type-safe techniques for binding the first argument of an opaque callback. - -#include -#include "functional.h" -#include "callbackfwd.h" - -template -inline void* convertToOpaque(Type* t) -{ - return t; -} -template -inline void* convertToOpaque(const Type* t) -{ - return const_cast(t); -} -template -inline void* convertToOpaque(Type& t) -{ - return &t; -} -template -inline void* convertToOpaque(const Type& t) -{ - return const_cast(&t); -} - - -template -class ConvertFromOpaque -{ -}; - -template -class ConvertFromOpaque -{ -public: - static Type& apply(void* p) - { - return *static_cast(p); - } -}; - -template -class ConvertFromOpaque -{ -public: - static const Type& apply(void* p) - { - return *static_cast(p); - } -}; - - -template -class ConvertFromOpaque -{ -public: - static Type* apply(void* p) - { - return static_cast(p); - } -}; - -template -class ConvertFromOpaque -{ -public: - static const Type* apply(void* p) - { - return static_cast(p); - } -}; - -template -class BindFirstOpaque -{ - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; -public: - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()() const - { - return Caller::call(firstBound); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment) - { - return Caller::call(ConvertFromOpaque::apply(environment)); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } -}; - -template -class BindFirstOpaque1 -{ - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; -public: - typedef typename Caller::second_argument_type first_argument_type; - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque1(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()(first_argument_type a1) const - { - return Caller::call(firstBound, a1); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment, first_argument_type a1) - { - return Caller::call(ConvertFromOpaque::apply(environment), a1); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } -}; - -template -class BindFirstOpaque2 -{ - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; -public: - typedef typename Caller::second_argument_type first_argument_type; - typedef typename Caller::third_argument_type second_argument_type; - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque2(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()(first_argument_type a1, second_argument_type a2) const - { - return Caller::call(firstBound, a1, a2); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment, first_argument_type a1, second_argument_type a2) - { - return Caller::call(ConvertFromOpaque::apply(environment), a1, a2); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } -}; - -template -class BindFirstOpaque3 -{ - typedef typename Caller::first_argument_type FirstBound; - FirstBound firstBound; -public: - typedef typename Caller::second_argument_type first_argument_type; - typedef typename Caller::third_argument_type second_argument_type; - typedef typename Caller::fourth_argument_type third_argument_type; - typedef typename Caller::result_type result_type; - explicit BindFirstOpaque3(FirstBound firstBound) : firstBound(firstBound) - { - } - result_type operator()(first_argument_type a1, second_argument_type a2, third_argument_type a3) const - { - return Caller::call(firstBound, a1, a2, a3); - } - FirstBound getBound() const - { - return firstBound; - } - static result_type thunk(void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3) - { - return Caller::call(ConvertFromOpaque::apply(environment), a1, a2, a3); - } - void* getEnvironment() const - { - return convertToOpaque(firstBound); - } -}; - -template -class CallbackBase -{ - void* m_environment; - Thunk_ m_thunk; -public: - typedef Thunk_ Thunk; - CallbackBase(void* environment, Thunk function) : m_environment(environment), m_thunk(function) - { - } - void* getEnvironment() const - { - return m_environment; - } - Thunk getThunk() const - { - return m_thunk; - } -}; - -template -inline bool operator==(const CallbackBase& self, const CallbackBase& other) -{ - return self.getEnvironment() == other.getEnvironment() && self.getThunk() == other.getThunk(); -} -template -inline bool operator!=(const CallbackBase& self, const CallbackBase& other) -{ - return !(self == other); -} -template -inline bool operator<(const CallbackBase& self, const CallbackBase& 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. -/// -/// Use with the callback constructors MemberCaller, ConstMemberCaller, ReferenceCaller, ConstReferenceCaller, PointerCaller, ConstPointerCaller and FreeCaller. -template -class Callback0 : public CallbackBase -{ - typedef CallbackBase Base; - static Result nullThunk(void*) - { - } - -public: - typedef Result result_type; - - Callback0() : Base(0, nullThunk) - { - } - template - Callback0(const BindFirstOpaque& caller) : Base(caller.getEnvironment(), BindFirstOpaque::thunk) - { - } - Callback0(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()() const - { - return Base::getThunk()(Base::getEnvironment()); - } -}; - -template -inline Callback0 makeCallback0(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback0(BindFirstOpaque(callee)); -} -template -inline Callback0 makeStatelessCallback0(const Caller& caller) -{ - return makeCallback0(Caller0To1(), 0); -} - -typedef Callback0 Callback; - - - -/// \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 : public CallbackBase -{ - typedef CallbackBase Base; - static Result nullThunk(void*, FirstArgument) - { - } - -public: - typedef FirstArgument first_argument_type; - typedef Result result_type; - - Callback1() : Base(0, nullThunk) - { - } - template - Callback1(const BindFirstOpaque1& caller) : Base(caller.getEnvironment(), BindFirstOpaque1::thunk) - { - } - Callback1(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()(FirstArgument firstArgument) const - { - return Base::getThunk()(Base::getEnvironment(), firstArgument); - } -}; - -template -inline Callback1 makeCallback1(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback1(BindFirstOpaque1(callee)); -} -template -inline Callback1 makeStatelessCallback1(const Caller& caller) -{ - return makeCallback1(Caller1To2(), 0); -} - - -/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and two other arguments. -/// -template -class Callback2 : public CallbackBase -{ - typedef CallbackBase Base; - static Result nullThunk(void*, FirstArgument, SecondArgument) - { - } - -public: - typedef FirstArgument first_argument_type; - typedef SecondArgument second_argument_type; - typedef Result result_type; - - Callback2() : Base(0, nullThunk) - { - } - template - Callback2(const BindFirstOpaque2& caller) : Base(caller.getEnvironment(), BindFirstOpaque2::thunk) - { - } - Callback2(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()(FirstArgument firstArgument, SecondArgument secondArgument) const - { - return Base::getThunk()(Base::getEnvironment(), firstArgument, secondArgument); - } -}; - -template -inline Callback2< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type -> makeCallback2(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback2< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type - >(BindFirstOpaque2(callee)); -} -template -inline Callback2< - typename Caller::first_argument_type, - typename Caller::second_argument_type, - typename Caller::result_type -> makeStatelessCallback2(const Caller& caller) -{ - return makeCallback2(Caller2To3(), 0); -} - - -/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and three other arguments. -/// -template -class Callback3 : public CallbackBase -{ - typedef CallbackBase Base; - static Result nullThunk(void*, FirstArgument, SecondArgument, ThirdArgument) - { - } - -public: - typedef FirstArgument first_argument_type; - typedef SecondArgument second_argument_type; - typedef ThirdArgument third_argument_type; - typedef Result result_type; - - Callback3() : Base(0, nullThunk) - { - } - template - Callback3(const BindFirstOpaque3& caller) : Base(caller.getEnvironment(), BindFirstOpaque3::thunk) - { - } - Callback3(void* environment, typename Base::Thunk function) : Base(environment, function) - { - } - result_type operator()(FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument) const - { - return Base::getThunk()(Base::getEnvironment(), firstArgument, secondArgument, thirdArgument); - } -}; - -template -inline Callback3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::result_type -> makeCallback3(const Caller& caller, typename Caller::first_argument_type callee) -{ - return Callback3< - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::fourth_argument_type, - typename Caller::result_type - >(BindFirstOpaque3(callee)); -} -template -inline Callback3< - typename Caller::first_argument_type, - typename Caller::second_argument_type, - typename Caller::third_argument_type, - typename Caller::result_type -> makeStatelessCallback3(const Caller& caller) -{ - return makeCallback3(Caller3To4(), 0); -} - - -/// \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 : public BindFirstOpaque< Member > -{ -public: - MemberCaller(Environment& environment) : BindFirstOpaque< Member >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque< ConstMember > -{ -public: - ConstMemberCaller(const Environment& environment) : BindFirstOpaque< ConstMember >(environment) - { - } -}; - -/// \brief Forms a Callback from a non-const Environment reference and a const Environment member-function which takes one argument. -template -class MemberCaller1 : public BindFirstOpaque1< Member1 > -{ -public: - MemberCaller1(Environment& environment) : BindFirstOpaque1< Member1 >(environment) - { - } -}; - -/// \brief Forms a Callback from a const Environment reference and a const Environment member-function which takes one argument. -template -class ConstMemberCaller1 : public BindFirstOpaque1< ConstMember1 > -{ -public: - ConstMemberCaller1(const Environment& environment) : BindFirstOpaque1< ConstMember1 >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque< Function1 > -{ -public: - ReferenceCaller(Environment& environment) : BindFirstOpaque< Function1 >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque< Function1 > -{ -public: - ConstReferenceCaller(const Environment& environment) : BindFirstOpaque< Function1 >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque1< Function2 > -{ -public: - ReferenceCaller1(Environment& environment) : BindFirstOpaque1< Function2 >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque1< Function2 > -{ -public: - ConstReferenceCaller1(const Environment& environment) : BindFirstOpaque1< Function2 >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque< Function1 > -{ -public: - PointerCaller(Environment* environment) : BindFirstOpaque< Function1 >(environment) - { - } -}; - -/// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer. -template -class ConstPointerCaller : public BindFirstOpaque< Function1 > -{ -public: - ConstPointerCaller(const Environment* environment) : BindFirstOpaque< Function1 >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque1< Function2 > -{ -public: - PointerCaller1(Environment* environment) : BindFirstOpaque1< Function2 >(environment) - { - } -}; - -/// \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 : public BindFirstOpaque1< Function2 > -{ -public: - ConstPointerCaller1(const Environment* environment) : BindFirstOpaque1< Function2 >(environment) - { - } -}; - -/// \brief Forms a Callback from a free function which takes no arguments. -template -class FreeCaller : public BindFirstOpaque< Caller0To1< Function0 > > -{ -public: - FreeCaller() : BindFirstOpaque< Caller0To1< Function0 > >(0) - { - } -}; - -/// \brief Forms a Callback from a free function which takes a single argument. -template -class FreeCaller1 : public BindFirstOpaque1< Caller1To2< Function1 > > -{ -public: - FreeCaller1() : BindFirstOpaque1< Caller1To2< Function1 > >(0) - { - } -}; - - -/// \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)); -} - - -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; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/callbackfwd.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/callbackfwd.cpp deleted file mode 100644 index a2faa664..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/callbackfwd.cpp +++ /dev/null @@ -1,3 +0,0 @@ - -#include "callbackfwd.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/callbackfwd.h b/misc/mediasource/extra/netradiant-src/libs/generic/callbackfwd.h deleted file mode 100644 index f89f9090..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/callbackfwd.h +++ /dev/null @@ -1,18 +0,0 @@ - -#if !defined(INCLUDED_CALLBACKFWD_H) -#define INCLUDED_CALLBACKFWD_H - -template -class Callback0; -typedef Callback0 Callback; - -template -class Callback1; - -template -class Callback2; - -template -class Callback3; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/constant.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/constant.cpp deleted file mode 100644 index ff54c9cc..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/constant.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "constant.h" - -#if defined(_DEBUG) || defined(DOXYGEN) - -namespace ExampleConstant -{ - class Bleh - { - public: - - STRING_CONSTANT(Name, "Bleh"); - INTEGER_CONSTANT(Version, 1); - }; - - int version = Bleh::Version(); - const char* name = Bleh::Name(); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/constant.h b/misc/mediasource/extra/netradiant-src/libs/generic/constant.h deleted file mode 100644 index 42b2fa5d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/constant.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GENERIC_CONSTANT_H) -#define INCLUDED_GENERIC_CONSTANT_H - -/// \file -/// \brief Language extensions for constants that are guaranteed to be evaluated at compile-time. - -/// \brief A compile-time-constant as a type. -template -struct ConstantWrapper -{ - typedef typename Type::Value Value; - operator Value() const - { - return Type::evaluate(); - } -}; -template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const ConstantWrapper& c) -{ - return ostream_write(ostream, typename Type::Value(c)); -} - -#define TYPE_CONSTANT(name, value, type) struct name##_CONSTANT_ { typedef type Value; static Value evaluate() { return value; } }; typedef ConstantWrapper name -#define STRING_CONSTANT(name, value) TYPE_CONSTANT(name, value, const char*) -#define INTEGER_CONSTANT(name, value) TYPE_CONSTANT(name, value, int) - -STRING_CONSTANT(EmptyString, ""); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/enumeration.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/enumeration.cpp deleted file mode 100644 index 4591fda9..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/enumeration.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "enumeration.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/enumeration.h b/misc/mediasource/extra/netradiant-src/libs/generic/enumeration.h deleted file mode 100644 index 31e43052..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/enumeration.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/generic/functional.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/functional.cpp deleted file mode 100644 index 4717c8e2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/functional.cpp +++ /dev/null @@ -1,3 +0,0 @@ - -#include "functional.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/functional.h b/misc/mediasource/extra/netradiant-src/libs/generic/functional.h deleted file mode 100644 index bd253486..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/functional.h +++ /dev/null @@ -1,313 +0,0 @@ - -#if !defined(INCLUDED_FUNCTIONAL_H) -#define INCLUDED_FUNCTIONAL_H - -template -class Member -{ -public: - typedef Object& first_argument_type; - typedef R result_type; - static result_type call(first_argument_type object) - { - return (object.*member)(); - } -}; - -template -class ConstMember -{ -public: - typedef const Object& first_argument_type; - typedef R result_type; - static result_type call(first_argument_type object) - { - return (object.*member)(); - } -}; - -template -class Member1 -{ -public: - typedef Object& first_argument_type; - typedef A1 second_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a1) - { - return (object.*member)(a1); - } -}; - -template -class ConstMember1 -{ -public: - typedef const Object& first_argument_type; - typedef A1 second_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a1) - { - return (object.*member)(a1); - } -}; - -template -class Member2 -{ -public: - typedef Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3) - { - return (object.*member)(a2, a3); - } -}; - -template -class ConstMember2 -{ -public: - typedef const Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3) - { - return (object.*member)(a2, a3); - } -}; - -template -class Member3 -{ -public: - typedef Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef A4 fourth_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return (object.*member)(a2, a3, a4); - } -}; - -template -class ConstMember3 -{ -public: - typedef const Object& first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef A4 fourth_argument_type; - typedef R result_type; - static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return (object.*member)(a2, a3, a4); - } -}; - -template -class Function0 -{ -public: - typedef R result_type; - static result_type call() - { - return (func)(); - } -}; - -template -class Function1 -{ -public: - typedef A1 first_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1) - { - return (func)(a1); - } -}; - -template -class Function2 -{ -public: - typedef A1 first_argument_type; - typedef A2 second_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1, second_argument_type a2) - { - return (func)(a1, a2); - } -}; - -template -class Function3 -{ -public: - typedef A1 first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1, second_argument_type a2, third_argument_type a3) - { - return (func)(a1, a2, a3); - } -}; - -template -class Function4 -{ -public: - typedef A1 first_argument_type; - typedef A2 second_argument_type; - typedef A3 third_argument_type; - typedef A4 fourth_argument_type; - typedef R result_type; - static result_type call(first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return (func)(a1, a2, a3, a4); - } -}; - -template -class Caller0To1 -{ -public: - typedef FirstArgument first_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type) - { - return Caller::call(); - } -}; - -template -class Caller1To2 -{ -public: - typedef FirstArgument first_argument_type; - typedef typename Caller::first_argument_type second_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type, second_argument_type a2) - { - return Caller::call(a2); - } -}; - -template -class Caller2To3 -{ -public: - typedef FirstArgument first_argument_type; - typedef typename Caller::first_argument_type second_argument_type; - typedef typename Caller::second_argument_type third_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type, second_argument_type a2, third_argument_type a3) - { - return Caller::call(a2, a3); - } -}; - -template -class Caller3To4 -{ -public: - typedef FirstArgument first_argument_type; - typedef typename Caller::first_argument_type second_argument_type; - typedef typename Caller::second_argument_type third_argument_type; - typedef typename Caller::third_argument_type fourth_argument_type; - typedef typename Caller::result_type result_type; - static result_type call(first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) - { - return Caller::call(a2, a3, a4); - } -}; - -template -class FunctorInvoke -{ -public: - typedef typename Functor::result_type result_type; - inline result_type operator()(Functor functor) - { - return functor(); - } -}; - -template -class Functor1Invoke -{ - typename Functor::first_argument_type a1; -public: - typedef typename Functor::first_argument_type first_argument_type; - typedef typename Functor::result_type result_type; - Functor1Invoke(first_argument_type a1) : a1(a1) - { - } - inline result_type operator()(Functor functor) - { - return functor(a1); - } -}; - -template -class Functor2Invoke -{ - typename Functor::first_argument_type a1; - typename Functor::second_argument_type a2; -public: - typedef typename Functor::first_argument_type first_argument_type; - typedef typename Functor::second_argument_type second_argument_type; - typedef typename Functor::result_type result_type; - Functor2Invoke(first_argument_type a1, second_argument_type a2) - : a1(a1), a2(a2) - { - } - inline result_type operator()(Functor functor) - { - return functor(a1, a2); - } -}; - -template -class Functor3Invoke -{ - typename Functor::first_argument_type a1; - typename Functor::second_argument_type a2; - typename Functor::third_argument_type a3; -public: - typedef typename Functor::first_argument_type first_argument_type; - typedef typename Functor::second_argument_type second_argument_type; - typedef typename Functor::third_argument_type third_argument_type; - typedef typename Functor::result_type result_type; - Functor3Invoke(first_argument_type a1, second_argument_type a2, third_argument_type a3) - : a1(a1), a2(a2), a3(a3) - { - } - inline result_type operator()(Functor functor) - { - return functor(a1, a2, a3); - } -}; - -template -class TypeEqual -{ -public: - typedef False type; -}; -template -class TypeEqual -{ -public: - typedef True type; -}; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/object.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/object.cpp deleted file mode 100644 index a6ed31c0..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/object.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/generic/object.h b/misc/mediasource/extra/netradiant-src/libs/generic/object.h deleted file mode 100644 index ec8e7262..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/object.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/generic/reference.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/reference.cpp deleted file mode 100644 index c09cad82..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/reference.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "reference.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/reference.h b/misc/mediasource/extra/netradiant-src/libs/generic/reference.h deleted file mode 100644 index 62e2c238..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/reference.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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) - { - } - 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) - { - } - 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/misc/mediasource/extra/netradiant-src/libs/generic/referencecounted.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/referencecounted.cpp deleted file mode 100644 index 757e08d8..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/referencecounted.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "referencecounted.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/referencecounted.h b/misc/mediasource/extra/netradiant-src/libs/generic/referencecounted.h deleted file mode 100644 index e761cccc..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/referencecounted.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/generic/static.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/static.cpp deleted file mode 100644 index ecd539f3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/static.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/generic/static.h b/misc/mediasource/extra/netradiant-src/libs/generic/static.h deleted file mode 100644 index 81691827..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/static.h +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GENERIC_STATIC_H) -#define INCLUDED_GENERIC_STATIC_H - -/// \file -/// \brief Template techniques for instantiating singletons. - -#include - -class Null -{ -}; - -/// \brief A singleton which is statically initialised. -/// -/// \param Type The singleton object type. -/// \param Type The type distinguishing this instance from others of the same 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. -/// \param Type The type distinguishing this instance from others of the same 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. -/// \param Type The type distinguishing this instance from others of the same 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. -/// \param Type The type distinguishing this instance from others of the same type. -/// -/// \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/misc/mediasource/extra/netradiant-src/libs/generic/vector.cpp b/misc/mediasource/extra/netradiant-src/libs/generic/vector.cpp deleted file mode 100644 index 83765dcb..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/vector.cpp +++ /dev/null @@ -1,3 +0,0 @@ - -#include "vector.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/generic/vector.h b/misc/mediasource/extra/netradiant-src/libs/generic/vector.h deleted file mode 100644 index 6e6f74e2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/generic/vector.h +++ /dev/null @@ -1,259 +0,0 @@ - -#if !defined(INCLUDED_VECTOR_H) -#define INCLUDED_VECTOR_H - -#include - -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]; - } - - Element* data() - { - return m_elements; - } - const Element* data() const - { - return m_elements; - } -}; - -/// \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]; - } - - Element* data() - { - return m_elements; - } - const Element* data() const - { - return m_elements; - } -}; - -/// \brief A 4-element vector. -template -class BasicVector4 -{ - Element m_elements[4]; -public: - - BasicVector4() - { - } - BasicVector4(Element x_, Element y_, Element z_, Element w_) - { - x() = x_; - y() = y_; - z() = z_; - w() = w_; - } - BasicVector4(const BasicVector3& self, Element w_) - { - x() = self.x(); - y() = self.y(); - z() = self.z(); - w() = w_; - } - - 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]; - } - Element& w() - { - return m_elements[3]; - } - const Element& w() const - { - return m_elements[3]; - } - - Element index(std::size_t i) const - { - return m_elements[i]; - } - Element& index(std::size_t i) - { - return m_elements[i]; - } - Element operator[](std::size_t i) const - { - return m_elements[i]; - } - Element& operator[](std::size_t i) - { - return m_elements[i]; - } - - Element* data() - { - return m_elements; - } - const Element* data() const - { - return m_elements; - } -}; - -template -inline BasicVector3 vector3_from_array(const Element* array) -{ - return BasicVector3(array[0], array[1], array[2]); -} - -template -inline Element* vector3_to_array(BasicVector3& self) -{ - return self.data(); -} -template -inline const Element* vector3_to_array(const BasicVector3& self) -{ - return self.data(); -} - -template -inline Element* vector4_to_array(BasicVector4& self) -{ - return self.data(); -} -template -inline const Element* vector4_to_array(const BasicVector4& self) -{ - return self.data(); -} - -template -inline BasicVector3& vector4_to_vector3(BasicVector4& self) -{ - return *reinterpret_cast*>(vector4_to_array(self)); -} -template -inline const BasicVector3& vector4_to_vector3(const BasicVector4& self) -{ - return *reinterpret_cast*>(vector4_to_array(self)); -} - -/// \brief A 2-element vector stored in single-precision floating-point. -typedef BasicVector2 Vector2; - -/// \brief A 3-element vector stored in single-precision floating-point. -typedef BasicVector3 Vector3; - -/// \brief A 4-element vector stored in single-precision floating-point. -typedef BasicVector4 Vector4; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/accelerator.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/accelerator.cpp deleted file mode 100644 index 214cc36c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/accelerator.cpp +++ /dev/null @@ -1,662 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "accelerator.h" - -#include "debugging/debugging.h" - -#include -#include -#include -#include - -#include "generic/callback.h" -#include "generic/bitfield.h" -#include "string/string.h" - -#include "pointer.h" -#include "closure.h" - -#include - - - -const char* global_keys_find(unsigned int key) -{ - const char *s; - if(key == 0) - return ""; - s = gdk_keyval_name(key); - if(!s) - return ""; - return s; -} - -unsigned int global_keys_find(const char* name) -{ - guint k; - if(!name || !*name) - return 0; - k = gdk_keyval_from_name(name); - if(k == GDK_VoidSymbol) - return 0; - return k; -} - -void accelerator_write(const Accelerator& accelerator, TextOutputStream& ostream) -{ -#if 0 - if(accelerator.modifiers & GDK_SHIFT_MASK) - { - ostream << "Shift + "; - } - if(accelerator.modifiers & GDK_MOD1_MASK) - { - ostream << "Alt + "; - } - if(accelerator.modifiers & GDK_CONTROL_MASK) - { - ostream << "Control + "; - } - - const char* keyName = global_keys_find(accelerator.key); - if(!string_empty(keyName)) - { - ostream << keyName; - } - else - { - ostream << static_cast(accelerator.key); - } -#endif - ostream << gtk_accelerator_get_label(accelerator.key, accelerator.modifiers); -} - -typedef std::map AcceleratorMap; -typedef std::set AcceleratorSet; - -bool accelerator_map_insert(AcceleratorMap& acceleratorMap, Accelerator accelerator, const Callback& callback) -{ - if(accelerator.key != 0) - { - return acceleratorMap.insert(AcceleratorMap::value_type(accelerator, callback)).second; - } - return true; -} - -bool accelerator_map_erase(AcceleratorMap& acceleratorMap, Accelerator accelerator) -{ - if(accelerator.key != 0) - { - AcceleratorMap::iterator i = acceleratorMap.find(accelerator); - if(i == acceleratorMap.end()) - { - return false; - } - acceleratorMap.erase(i); - } - return true; -} - -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; -} - - -GClosure* accel_group_add_accelerator(GtkAccelGroup* group, Accelerator accelerator, const Callback& callback); -void accel_group_remove_accelerator(GtkAccelGroup* group, Accelerator accelerator); - -AcceleratorMap g_queuedAcceleratorsAdd; -AcceleratorSet g_queuedAcceleratorsRemove; - -void globalQueuedAccelerators_add(Accelerator accelerator, const Callback& callback) -{ - if(!g_queuedAcceleratorsAdd.insert(AcceleratorMap::value_type(accelerator, callback)).second) - { - globalErrorStream() << "globalQueuedAccelerators_add: accelerator already queued: " << accelerator << "\n"; - } -} - -void globalQueuedAccelerators_remove(Accelerator accelerator) -{ - if(g_queuedAcceleratorsAdd.erase(accelerator) == 0) - { - if(!g_queuedAcceleratorsRemove.insert(accelerator).second) - { - globalErrorStream() << "globalQueuedAccelerators_remove: accelerator already queued: " << accelerator << "\n"; - } - } -} - -void globalQueuedAccelerators_commit() -{ - for(AcceleratorSet::const_iterator i = g_queuedAcceleratorsRemove.begin(); i != g_queuedAcceleratorsRemove.end(); ++i) - { - //globalOutputStream() << "removing: " << (*i).first << "\n"; - accel_group_remove_accelerator(global_accel, *i); - } - g_queuedAcceleratorsRemove.clear(); - for(AcceleratorMap::const_iterator i = g_queuedAcceleratorsAdd.begin(); i != g_queuedAcceleratorsAdd.end(); ++i) - { - //globalOutputStream() << "adding: " << (*i).first << "\n"; - accel_group_add_accelerator(global_accel, (*i).first, (*i).second); - } - g_queuedAcceleratorsAdd.clear(); -} - -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) -{ - //globalOutputStream() << "special_accelerators_add: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_insert(g_special_accelerators, accelerator, callback)) - { - globalErrorStream() << "special_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; - } -} -void special_accelerators_remove(Accelerator accelerator) -{ - //globalOutputStream() << "special_accelerators_remove: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_erase(g_special_accelerators, accelerator)) - { - globalErrorStream() << "special_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; - } -} - -void keydown_accelerators_add(Accelerator accelerator, const Callback& callback) -{ - //globalOutputStream() << "keydown_accelerators_add: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_insert(g_keydown_accelerators, accelerator, callback)) - { - globalErrorStream() << "keydown_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; - } -} -void keydown_accelerators_remove(Accelerator accelerator) -{ - //globalOutputStream() << "keydown_accelerators_remove: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_erase(g_keydown_accelerators, accelerator)) - { - globalErrorStream() << "keydown_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; - } -} - -void keyup_accelerators_add(Accelerator accelerator, const Callback& callback) -{ - //globalOutputStream() << "keyup_accelerators_add: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_insert(g_keyup_accelerators, accelerator, callback)) - { - globalErrorStream() << "keyup_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; - } -} -void keyup_accelerators_remove(Accelerator accelerator) -{ - //globalOutputStream() << "keyup_accelerators_remove: " << makeQuoted(accelerator) << "\n"; - if(!accelerator_map_erase(g_keyup_accelerators, accelerator)) - { - globalErrorStream() << "keyup_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; - } -} - - -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() << "global_accel_connect: " << makeQuoted(accelerator) << "\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)) - { - //globalOutputStream() << "global_accel_disconnect: " << makeQuoted(accelerator) << "\n"; - 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 - //globalOutputStream() << "queued for add: " << accelerator << "\n"; - globalQueuedAccelerators_add(accelerator, callback); - return 0; - } - return accel_group_add_accelerator(global_accel, accelerator, callback); -} -void global_accel_group_remove_accelerator(Accelerator accelerator) -{ - if(!global_accel_enabled()) - { - //globalOutputStream() << "queued for remove: " << accelerator << "\n"; - globalQueuedAccelerators_remove(accelerator); - return; - } - 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) -{ - gboolean b = gtk_window_propagate_key_event(window, event); - return b; -} - -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 global_accel_group_connect(const Accelerator& accelerator, const Callback& callback) -{ - if(accelerator.key != 0) - { - global_accel_group_add_accelerator(accelerator, callback); - } -} - -void global_accel_group_disconnect(const Accelerator& accelerator, const Callback& callback) -{ - if(accelerator.key != 0) - { - global_accel_group_remove_accelerator(accelerator); - } -} - - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/accelerator.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/accelerator.h deleted file mode 100644 index 4e441b21..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/accelerator.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_ACCELERATOR_H) -#define INCLUDED_GTKUTIL_ACCELERATOR_H - -#include -#include -#include - -#include "generic/callback.h" - -// ignore numlock -#define ALLOWED_MODIFIERS (~(GDK_MOD2_MASK | GDK_LOCK_MASK | GDK_MOD3_MASK | GDK_MOD4_MASK | GDK_MOD5_MASK)) - -struct Accelerator -{ - Accelerator(guint _key) - : key(gdk_keyval_to_upper(_key)), modifiers((GdkModifierType)0) - { - } - Accelerator(guint _key, GdkModifierType _modifiers) - : key(gdk_keyval_to_upper(_key)), modifiers((GdkModifierType) (_modifiers & ALLOWED_MODIFIERS)) - { - } - Accelerator(const Accelerator &src) - : key(gdk_keyval_to_upper(src.key)), modifiers((GdkModifierType) (src.modifiers & ALLOWED_MODIFIERS)) - { - } - bool operator<(const Accelerator& other) const - { - guint k1 = key; - guint k2 = other.key; - int mod1 = modifiers & ALLOWED_MODIFIERS; - int mod2 = other.modifiers & ALLOWED_MODIFIERS; - return k1 < k2 || (!(k2 < k1) && mod1 < mod2); - } - bool operator==(const Accelerator& other) const - { - guint k1 = key; - guint k2 = other.key; - int mod1 = modifiers & ALLOWED_MODIFIERS; - int mod2 = other.modifiers & ALLOWED_MODIFIERS; - return k1 == k2 && mod1 == mod2; - } - Accelerator &operator=(const Accelerator& other) - { - key = other.key; - modifiers = (GdkModifierType) (other.modifiers & ALLOWED_MODIFIERS); - return *this; - } - guint key; - GdkModifierType modifiers; -}; - -inline Accelerator accelerator_null() -{ - return Accelerator(0, (GdkModifierType)0); -} - -const char* global_keys_find(unsigned int key); -unsigned int global_keys_find(const char* name); - -class TextOutputStream; -void accelerator_write(const Accelerator& accelerator, TextOutputStream& ostream); - -template -TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const Accelerator& accelerator) -{ - accelerator_write(accelerator, ostream); - return ostream; -} - -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 global_accel_group_connect(const Accelerator& accelerator, const Callback& callback); -void global_accel_group_disconnect(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/button.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/button.cpp deleted file mode 100644 index 0356ba39..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/button.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/gtkutil/button.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/button.h deleted file mode 100644 index 69ddac4b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/button.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_BUTTON_H) -#define INCLUDED_GTKUTIL_BUTTON_H - -#include "generic/callbackfwd.h" - -typedef struct _GtkButton GtkButton; -typedef struct _GtkToggleButton GtkToggleButton; -typedef struct _GtkRadioButton GtkRadioButton; -typedef int gint; -typedef gint gboolean; -typedef unsigned int guint; - -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/misc/mediasource/extra/netradiant-src/libs/gtkutil/clipboard.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/clipboard.cpp deleted file mode 100644 index f7b9466a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/clipboard.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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(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(); - } -} - -#else - -#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); -} - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/clipboard.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/clipboard.h deleted file mode 100644 index 1589a66a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/clipboard.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/closure.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/closure.cpp deleted file mode 100644 index 4926d994..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/closure.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "closure.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/closure.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/closure.h deleted file mode 100644 index 9a74b95e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/closure.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/container.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/container.cpp deleted file mode 100644 index 627e0c88..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/container.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "container.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/container.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/container.h deleted file mode 100644 index c41478ba..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/container.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/cursor.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/cursor.cpp deleted file mode 100644 index 2c4225a2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/cursor.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "cursor.h" - -#include "stream/textstream.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(GtkWindow* window, int *x, int *y) -{ - POINT pos; - GetCursorPos(&pos); - ScreenToClient((HWND)GDK_WINDOW_HWND(GTK_WIDGET(window)->window), &pos); - *x = pos.x; - *y = pos.y; -} - -void Sys_SetCursorPos(GtkWindow* window, int x, int y) -{ - POINT pos; - pos.x = x; - pos.y = y; - ClientToScreen((HWND)GDK_WINDOW_HWND(GTK_WIDGET(window)->window), &pos); - SetCursorPos(pos.x, pos.y); -} - -#else - -#include - -void Sys_GetCursorPos(GtkWindow* window, int *x, int *y) -{ - gdk_display_get_pointer(gdk_display_get_default(), 0, x, y, 0); -} - -void Sys_SetCursorPos(GtkWindow* window, int x, int y) -{ - XWarpPointer(GDK_DISPLAY(), None, GDK_ROOT_WINDOW(), 0, 0, 0, 0, x, y); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/cursor.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/cursor.h deleted file mode 100644 index eadae085..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/cursor.h +++ /dev/null @@ -1,193 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_CURSOR_H) -#define INCLUDED_GTKUTIL_CURSOR_H - -#include -#include -#include -#include - -#include "debugging/debugging.h" - -typedef struct _GdkCursor GdkCursor; -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; - -GdkCursor* create_blank_cursor(); -void blank_cursor(GtkWidget* widget); -void default_cursor(GtkWidget* widget); -void Sys_GetCursorPos(GtkWindow* window, int *x, int *y); -void Sys_SetCursorPos(GtkWindow* window, 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(GTK_WINDOW(widget), ¤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(GTK_WINDOW(widget), self->recorded_x, self->recorded_y); - self->m_function(dx, dy, event->state, self->m_data); - } - return FALSE; - } - - void freeze_pointer(GtkWindow* window, MotionDeltaFunction function, void* data) - { - ASSERT_MESSAGE(m_function == 0, "can't freeze pointer"); - - 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); - - GdkCursor* cursor = create_blank_cursor(); - //GdkGrabStatus status = - gdk_pointer_grab(GTK_WIDGET(window)->window, TRUE, mask, 0, cursor, GDK_CURRENT_TIME); - gdk_cursor_unref(cursor); - - Sys_GetCursorPos(window, &recorded_x, &recorded_y); - - Sys_SetCursorPos(window, 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(GtkWindow* window) - { - g_signal_handler_disconnect(G_OBJECT(window), handle_motion); - - m_function = 0; - m_data = 0; - - Sys_SetCursorPos(window, recorded_x, recorded_y); - - gdk_pointer_ungrab(GDK_CURRENT_TIME); - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/dialog.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/dialog.cpp deleted file mode 100644 index 0f95e9ae..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/dialog.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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.first; i != names.last; ++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/misc/mediasource/extra/netradiant-src/libs/gtkutil/dialog.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/dialog.h deleted file mode 100644 index 150404a2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/dialog.h +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/entry.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/entry.cpp deleted file mode 100644 index 9c3c1553..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/entry.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "entry.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/entry.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/entry.h deleted file mode 100644 index 82957d29..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/entry.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/filechooser.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/filechooser.cpp deleted file mode 100644 index 2246b57b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/filechooser.cpp +++ /dev/null @@ -1,305 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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)); - } -}; - - -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, bool want_load, bool want_import, bool want_save) -{ - filetype_t type; - - if(pattern == 0) - { - pattern = "*"; - } - - FileTypeList typelist; - GlobalFiletypes().getTypeList(pattern, &typelist, want_load, want_import, want_save); - - 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)); - if(filter != 0) // no filter set? some file-chooser implementations may allow the user to set no filter, which we treat as 'all files' - { - 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; -} - -const char* file_dialog(GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern, bool want_load, bool want_import, bool want_save) -{ - for(;;) - { - const char* file = file_dialog_show(parent, open, title, path, pattern, want_load, want_import, want_save); - - if(open - || file == 0 - || !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/misc/mediasource/extra/netradiant-src/libs/gtkutil/filechooser.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/filechooser.h deleted file mode 100644 index 3789321e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/filechooser.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_FILECHOOSER_H) -#define INCLUDED_GTKUTIL_FILECHOOSER_H - -/// \file -/// GTK+ file-chooser dialogs. - -typedef struct _GtkWidget GtkWidget; -const char* file_dialog(GtkWidget *parent, bool open, const char* title, const char* path = 0, const char* pattern = 0, bool want_load = false, bool want_import = false, bool want_save = false); - - -/// \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/misc/mediasource/extra/netradiant-src/libs/gtkutil/frame.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/frame.cpp deleted file mode 100644 index 026de650..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/frame.cpp +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/gtkutil/frame.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/frame.h deleted file mode 100644 index 12305db2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/frame.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/glfont.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/glfont.cpp deleted file mode 100644 index a3eac91d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/glfont.cpp +++ /dev/null @@ -1,354 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "glfont.h" -#include "igl.h" - -// generic string printing with call lists -class GLFontCallList: public GLFont -{ - GLuint m_displayList; - int m_pixelHeight; - int m_pixelAscent; - int m_pixelDescent; - public: - GLFontCallList(GLuint displayList, int asc, int desc, int pixelHeight) : m_displayList(displayList), m_pixelHeight(pixelHeight), m_pixelAscent(asc), m_pixelDescent(desc) - { - } - virtual ~GLFontCallList() - { - glDeleteLists(m_displayList, 256); - } - void printString(const char *s) - { - GlobalOpenGL().m_glListBase(m_displayList); - GlobalOpenGL().m_glCallLists(GLsizei(strlen(s)), GL_UNSIGNED_BYTE, reinterpret_cast(s)); - } - virtual int getPixelAscent() const - { - return m_pixelAscent; - } - virtual int getPixelDescent() const - { - return m_pixelDescent; - } - virtual int getPixelHeight() const - { - return m_pixelHeight; - } -}; - -#ifdef _WIN32 - #include -#endif -#include "debugging/debugging.h" - -// LordHavoc: this is code for direct Xlib bitmap character fetching, as an -// alternative to requiring gtkglarea, it was created due to a lack of this -// package on SuSE 9.x but this package is now commonly shipping in Linux -// distributions so this code may be unnecessary, feel free however to enable -// it when building packages for distros that do not ship with that package, -// or if you just prefer less dependencies... -#if 0 - -#include -#include -#include - -GLFont *glfont_create(const char* font_string) -{ - GLuint font_list_base; - XFontStruct *fontInfo; - Display *dpy = GDK_DISPLAY (); - unsigned int i, first, last, firstrow, lastrow; - int maxchars; - int firstbitmap; - - fontInfo = XLoadQueryFont (dpy, "-*-fixed-*-*-*-*-8-*-*-*-*-*-*-*"); - if (fontInfo == NULL) - { - // try to load other fonts - fontInfo = XLoadQueryFont (dpy, "-*-fixed-*-*-*-*-*-*-*-*-*-*-*-*"); - - // any font will do ! - if (fontInfo == NULL) - fontInfo = XLoadQueryFont(dpy, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*"); - - if (fontInfo == NULL) - ERROR_MESSAGE("couldn't create font"); - } - - first = (int)fontInfo->min_char_or_byte2; - last = (int)fontInfo->max_char_or_byte2; - firstrow = (int)fontInfo->min_byte1; - lastrow = (int)fontInfo->max_byte1; - /* - * How many chars in the charset - */ - maxchars = 256 * lastrow + last; - font_list_base = glGenLists(maxchars+1); - if (font_list_base == 0) - { - ERROR_MESSAGE( "couldn't create font" ); - } - - /* - * Get offset to first char in the charset - */ - firstbitmap = 256 * firstrow + first; - /* - * for each row of chars, call glXUseXFont to build the bitmaps. - */ - - for(i=firstrow; i<=lastrow; i++) - { - glXUseXFont(fontInfo->fid, firstbitmap, last-first+1, font_list_base+firstbitmap); - firstbitmap += 256; - } - -/* *height = fontInfo->ascent + fontInfo->descent; - *width = fontInfo->max_bounds.width; */ - return new GLFontCallList(font_list_base, fontInfo->ascent, fontInfo->descent, fontInfo->ascent + fontInfo->descent); -} - -#elif 0 - -#include - -GLFont *glfont_create(const char* font_string) -{ - GLuint font_list_base = glGenLists (256); - gint font_height = 0, font_ascent = 0, font_descent = 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) - { - pango_font_description_free (font_desc); - font_desc = pango_font_description_from_string ("fixed 8"); - font = gdk_gl_font_use_pango_font (font_desc, 0, 256, font_list_base); - } - - if(font == 0) - { - pango_font_description_free (font_desc); - font_desc = pango_font_description_from_string ("courier new 8"); - 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_ascent = pango_font_metrics_get_ascent (font_metrics); - font_descent = pango_font_metrics_get_descent (font_metrics); - font_height = font_ascent + font_descent; - - font_ascent = PANGO_PIXELS (font_ascent); - font_descent = PANGO_PIXELS (font_descent); - font_height = PANGO_PIXELS (font_height); - - pango_font_metrics_unref (font_metrics); - } - - pango_font_description_free (font_desc); - - // fix for pango/gtkglext metrix bug - if(font_height > 256) - font_height = 16; - - return new GLFontCallList(font_list_base, font_ascent, font_descent, font_height); -} -#else - -// new font code ripped from ZeroRadiant - -#include -#include - -class GLFontInternal: public GLFont -{ - const char *font_string; - int font_height; - int font_ascent; - int font_descent; - int y_offset_bitmap_render_pango_units; - PangoContext *ft2_context; - PangoFontMap *fontmap; - - public: - GLFontInternal(const char *_font_string): font_string(_font_string) - { - PangoFontDescription *font_desc; - PangoLayout *layout; - PangoRectangle log_rect; - int font_ascent_pango_units; - int font_descent_pango_units; - -#if !PANGO_VERSION_CHECK(1,22,0) - ft2_context = pango_ft2_get_context(72, 72); -#else - fontmap = pango_ft2_font_map_new(); - pango_ft2_font_map_set_resolution(PANGO_FT2_FONT_MAP(fontmap), 72, 72); - ft2_context = pango_font_map_create_context(fontmap); -#endif - - font_desc = pango_font_description_from_string(font_string); - //pango_font_description_set_size(font_desc, 10 * PANGO_SCALE); - pango_context_set_font_description(ft2_context, font_desc); - pango_font_description_free(font_desc); - // TODO fallback to fixed 8, courier new 8 - - layout = pango_layout_new(ft2_context); - -#ifdef FONT_SIZE_WORKAROUND - pango_layout_set_width(layout, -1); // -1 no wrapping. All text on one line. - pango_layout_set_text(layout, "The quick brown fox jumped over the lazy sleeping dog's back then sat on a tack.", -1); // -1 null-terminated string. -#endif - -#if !PANGO_VERSION_CHECK(1,22,0) - PangoLayoutIter *iter; - iter = pango_layout_get_iter(layout); - font_ascent_pango_units = pango_layout_iter_get_baseline(iter); - pango_layout_iter_free(iter); -#else - font_ascent_pango_units = pango_layout_get_baseline(layout); -#endif - pango_layout_get_extents(layout, NULL, &log_rect); - g_object_unref(G_OBJECT(layout)); - font_descent_pango_units = log_rect.height - font_ascent_pango_units; - - font_ascent = PANGO_PIXELS_CEIL(font_ascent_pango_units); - font_descent = PANGO_PIXELS_CEIL(font_descent_pango_units); - font_height = font_ascent + font_descent; - y_offset_bitmap_render_pango_units = (font_ascent * PANGO_SCALE) - font_ascent_pango_units; - } - - virtual ~GLFontInternal() - { - g_object_unref(G_OBJECT(ft2_context)); - g_object_unref(G_OBJECT(fontmap)); - } - - // Renders the input text at the current location with the current color. - // The X position of the current location is used to place the left edge of the text image, - // where the text image bounds are defined as the logical extents of the line of text. - // The Y position of the current location is used to place the bottom of the text image. - // You should offset the Y position by the amount returned by gtk_glwidget_font_descent() - // if you want to place the baseline of the text image at the current Y position. - // Note: A problem with this function is that if the lower left corner of the text falls - // just a hair outside of the viewport (meaning the current raster position is invalid), - // then no text will be rendered. The solution to this is a very hacky one. You can search - // Google for "glDrawPixels clipping". - virtual void printString(const char *s) - { - // The idea for this code initially came from the font-pangoft2.c example that comes with GtkGLExt. - - PangoLayout *layout; - PangoRectangle log_rect; - FT_Bitmap bitmap; - unsigned char *begin_bitmap_buffer; - GLfloat color[4]; - GLint previous_unpack_alignment; - GLboolean previous_blend_enabled; - GLint previous_blend_func_src; - GLint previous_blend_func_dst; - GLfloat previous_red_bias; - GLfloat previous_green_bias; - GLfloat previous_blue_bias; - GLfloat previous_alpha_scale; - - layout = pango_layout_new(ft2_context); - pango_layout_set_width(layout, -1); // -1 no wrapping. All text on one line. - pango_layout_set_text(layout, s, -1); // -1 null-terminated string. - pango_layout_get_extents(layout, NULL, &log_rect); - - if (log_rect.width > 0 && log_rect.height > 0) { - bitmap.rows = font_ascent + font_descent; - bitmap.width = PANGO_PIXELS_CEIL(log_rect.width); - bitmap.pitch = -bitmap.width; // Rendering it "upside down" for OpenGL. - begin_bitmap_buffer = (unsigned char *) g_malloc(bitmap.rows * bitmap.width); - memset(begin_bitmap_buffer, 0, bitmap.rows * bitmap.width); - bitmap.buffer = begin_bitmap_buffer + (bitmap.rows - 1) * bitmap.width; // See pitch above. - bitmap.num_grays = 0xff; - bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; - pango_ft2_render_layout_subpixel(&bitmap, layout, -log_rect.x, - y_offset_bitmap_render_pango_units); - GlobalOpenGL().m_glGetFloatv(GL_CURRENT_COLOR, color); - - // Save state. I didn't see any OpenGL push/pop operations for these. - // Question: Is saving/restoring this state necessary? Being safe. - GlobalOpenGL().m_glGetIntegerv(GL_UNPACK_ALIGNMENT, &previous_unpack_alignment); - previous_blend_enabled = GlobalOpenGL().m_glIsEnabled(GL_BLEND); - GlobalOpenGL().m_glGetIntegerv(GL_BLEND_SRC, &previous_blend_func_src); - GlobalOpenGL().m_glGetIntegerv(GL_BLEND_DST, &previous_blend_func_dst); - GlobalOpenGL().m_glGetFloatv(GL_RED_BIAS, &previous_red_bias); - GlobalOpenGL().m_glGetFloatv(GL_GREEN_BIAS, &previous_green_bias); - GlobalOpenGL().m_glGetFloatv(GL_BLUE_BIAS, &previous_blue_bias); - GlobalOpenGL().m_glGetFloatv(GL_ALPHA_SCALE, &previous_alpha_scale); - - GlobalOpenGL().m_glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - GlobalOpenGL().m_glEnable(GL_BLEND); - GlobalOpenGL().m_glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - GlobalOpenGL().m_glPixelTransferf(GL_RED_BIAS, color[0]); - GlobalOpenGL().m_glPixelTransferf(GL_GREEN_BIAS, color[1]); - GlobalOpenGL().m_glPixelTransferf(GL_BLUE_BIAS, color[2]); - GlobalOpenGL().m_glPixelTransferf(GL_ALPHA_SCALE, color[3]); - - GlobalOpenGL().m_glDrawPixels(bitmap.width, bitmap.rows, - GL_ALPHA, GL_UNSIGNED_BYTE, begin_bitmap_buffer); - g_free(begin_bitmap_buffer); - - // Restore state in reverse order of how we set it. - GlobalOpenGL().m_glPixelTransferf(GL_ALPHA_SCALE, previous_alpha_scale); - GlobalOpenGL().m_glPixelTransferf(GL_BLUE_BIAS, previous_blue_bias); - GlobalOpenGL().m_glPixelTransferf(GL_GREEN_BIAS, previous_green_bias); - GlobalOpenGL().m_glPixelTransferf(GL_RED_BIAS, previous_red_bias); - GlobalOpenGL().m_glBlendFunc(previous_blend_func_src, previous_blend_func_dst); - if (!previous_blend_enabled) { GlobalOpenGL().m_glDisable(GL_BLEND); } - GlobalOpenGL().m_glPixelStorei(GL_UNPACK_ALIGNMENT, previous_unpack_alignment); - } - - g_object_unref(G_OBJECT(layout)); - } - - virtual int getPixelAscent() const - { - return font_ascent; - } - virtual int getPixelDescent() const - { - return font_descent; - } - virtual int getPixelHeight() const - { - return font_height; - } -}; - -GLFont *glfont_create(const char* font_string) -{ - return new GLFontInternal(font_string); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/glfont.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/glfont.h deleted file mode 100644 index 0d1e0000..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/glfont.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_GLFONT_H) -#define INCLUDED_GTKUTIL_GLFONT_H - -typedef unsigned int GLuint; - -class GLFont -{ - public: - virtual int getPixelHeight() const = 0; - virtual int getPixelAscent() const = 0; - virtual int getPixelDescent() const = 0; - virtual void printString(const char *s) = 0; - virtual ~GLFont() - { - } -}; - -GLFont *glfont_create(const char* font_string); -// release with delete - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/glwidget.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/glwidget.cpp deleted file mode 100644 index cda5366a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/glwidget.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 -*/ - -// 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/misc/mediasource/extra/netradiant-src/libs/gtkutil/glwidget.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/glwidget.h deleted file mode 100644 index 235b0908..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/glwidget.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/idledraw.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/idledraw.cpp deleted file mode 100644 index 47d432ca..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/idledraw.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "idledraw.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/idledraw.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/idledraw.h deleted file mode 100644 index 48081237..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/idledraw.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/image.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/image.cpp deleted file mode 100644 index 66e61d1e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/image.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/gtkutil/image.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/image.h deleted file mode 100644 index bd865142..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/image.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/menu.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/menu.cpp deleted file mode 100644 index 86be24e7..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/menu.cpp +++ /dev/null @@ -1,311 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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) -{ - 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) -{ - 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/misc/mediasource/extra/netradiant-src/libs/gtkutil/menu.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/menu.h deleted file mode 100644 index a394d823..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/menu.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_MENU_H) -#define INCLUDED_GTKUTIL_MENU_H - -#include "generic/callbackfwd.h" - -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/misc/mediasource/extra/netradiant-src/libs/gtkutil/messagebox.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/messagebox.cpp deleted file mode 100644 index 4c430ed3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/messagebox.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/gtkutil/messagebox.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/messagebox.h deleted file mode 100644 index 8806a3bd..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/messagebox.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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 = "NetRadiant", EMessageBoxType type = eMB_OK, EMessageBoxIcon icon = eMB_ICONDEFAULT); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/nonmodal.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/nonmodal.cpp deleted file mode 100644 index 6252e2dd..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/nonmodal.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "nonmodal.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/nonmodal.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/nonmodal.h deleted file mode 100644 index eed4be37..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/nonmodal.h +++ /dev/null @@ -1,186 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/paned.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/paned.cpp deleted file mode 100644 index db0c308b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/paned.cpp +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/gtkutil/paned.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/paned.h deleted file mode 100644 index 578a3c5d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/paned.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/pointer.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/pointer.cpp deleted file mode 100644 index 2c36d2d7..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/pointer.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "pointer.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/pointer.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/pointer.h deleted file mode 100644 index c8294467..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/pointer.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/toolbar.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/toolbar.cpp deleted file mode 100644 index 194aff2d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/toolbar.cpp +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/gtkutil/toolbar.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/toolbar.h deleted file mode 100644 index 9bf847d2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/toolbar.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_TOOLBAR_H) -#define INCLUDED_GTKUTIL_TOOLBAR_H - -#include "generic/callbackfwd.h" - -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/misc/mediasource/extra/netradiant-src/libs/gtkutil/widget.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/widget.cpp deleted file mode 100644 index 62a1b6ca..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/widget.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "widget.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/widget.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/widget.h deleted file mode 100644 index 225fccf4..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/widget.h +++ /dev/null @@ -1,190 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GTKUTIL_WIDGET_H) -#define INCLUDED_GTKUTIL_WIDGET_H - -#include -#include -#include "generic/callback.h" -#include "warnings.h" -#include "debugging/debugging.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); -} - -class WidgetFocusPrinter -{ - const char* m_name; - - static gboolean focus_in(GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self) - { - globalOutputStream() << self->m_name << " takes focus\n"; - return FALSE; - } - static gboolean focus_out(GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self) - { - globalOutputStream() << self->m_name << " loses focus\n"; - return FALSE; - } -public: - WidgetFocusPrinter(const char* name) : m_name(name) - { - } - void connect(GtkWidget* widget) - { - g_signal_connect(G_OBJECT(widget), "focus_in_event", G_CALLBACK(focus_in), this); - g_signal_connect(G_OBJECT(widget), "focus_out_event", G_CALLBACK(focus_out), this); - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/window.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/window.cpp deleted file mode 100644 index 5d465531..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/window.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/gtkutil/window.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/window.h deleted file mode 100644 index 5ab1e500..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/window.h +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/gtkutil/xorrectangle.cpp b/misc/mediasource/extra/netradiant-src/libs/gtkutil/xorrectangle.cpp deleted file mode 100644 index d968337d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/xorrectangle.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "xorrectangle.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/gtkutil/xorrectangle.h b/misc/mediasource/extra/netradiant-src/libs/gtkutil/xorrectangle.h deleted file mode 100644 index 0d89203e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/gtkutil/xorrectangle.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (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/misc/mediasource/extra/netradiant-src/libs/imagelib.cpp b/misc/mediasource/extra/netradiant-src/libs/imagelib.cpp deleted file mode 100644 index 5c205f63..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/imagelib.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "imagelib.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/imagelib.h b/misc/mediasource/extra/netradiant-src/libs/imagelib.h deleted file mode 100644 index 5a1afa67..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/imagelib.h +++ /dev/null @@ -1,152 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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, int 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/misc/mediasource/extra/netradiant-src/libs/instancelib.cpp b/misc/mediasource/extra/netradiant-src/libs/instancelib.cpp deleted file mode 100644 index 053ac73b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/instancelib.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "instancelib.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/instancelib.h b/misc/mediasource/extra/netradiant-src/libs/instancelib.h deleted file mode 100644 index 9ff32e6d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/instancelib.h +++ /dev/null @@ -1,193 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (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 InstanceSet : 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(), "InstanceSet::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(), "InstanceSet::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; -}; - -template -inline void InstanceSet_forEach(InstanceSet& instances, const Functor& functor) -{ - for(InstanceSet::iterator i = instances.begin(), end = instances.end(); i != end; ++i) - { - functor(*(*i).second); - } -} - -template -class InstanceEvaluateTransform -{ -public: - inline void operator()(scene::Instance& instance) const - { - InstanceTypeCast::cast(instance)->evaluateTransform(); - } -}; - -template -class InstanceSetEvaluateTransform -{ -public: - static void apply(InstanceSet& instances) - { - InstanceSet_forEach(instances, InstanceEvaluateTransform()); - } - typedef ReferenceCaller::apply> Caller; -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/jpeg6/.cvswrappers b/misc/mediasource/extra/netradiant-src/libs/jpeg6/.cvswrappers deleted file mode 100644 index ed97d402..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/.cvswrappers +++ /dev/null @@ -1,3 +0,0 @@ -*.dsp -m 'COPY' -k 'b' -*.dsw -m 'COPY' -k 'b' -*.scc -m 'COPY' -k 'b' diff --git a/misc/mediasource/extra/netradiant-src/libs/jpeg6/README b/misc/mediasource/extra/netradiant-src/libs/jpeg6/README deleted file mode 100644 index 86cc2066..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/README +++ /dev/null @@ -1,385 +0,0 @@ -The Independent JPEG Group's JPEG software -========================================== - -README for release 6b of 27-Mar-1998 -==================================== - -This distribution contains the sixth public release of the Independent JPEG -Group's free JPEG software. You are welcome to redistribute this software and -to use it for any purpose, subject to the conditions under LEGAL ISSUES, below. - -Serious users of this software (particularly those incorporating it into -larger programs) should contact IJG at jpeg-info@uunet.uu.net to be added to -our electronic mailing list. Mailing list members are notified of updates -and have a chance to participate in technical discussions, etc. - -This software is the work of Tom Lane, Philip Gladstone, Jim Boucher, -Lee Crocker, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, -Guido Vollbeding, Ge' Weijers, and other members of the Independent JPEG -Group. - -IJG is not affiliated with the official ISO JPEG standards committee. - - -DOCUMENTATION ROADMAP -===================== - -This file contains the following sections: - -OVERVIEW General description of JPEG and the IJG software. -LEGAL ISSUES Copyright, lack of warranty, terms of distribution. -REFERENCES Where to learn more about JPEG. -ARCHIVE LOCATIONS Where to find newer versions of this software. -RELATED SOFTWARE Other stuff you should get. -FILE FORMAT WARS Software *not* to get. -TO DO Plans for future IJG releases. - -Other documentation files in the distribution are: - -User documentation: - install.doc How to configure and install the IJG software. - usage.doc Usage instructions for cjpeg, djpeg, jpegtran, - rdjpgcom, and wrjpgcom. - *.1 Unix-style man pages for programs (same info as usage.doc). - wizard.doc Advanced usage instructions for JPEG wizards only. - change.log Version-to-version change highlights. -Programmer and internal documentation: - libjpeg.doc How to use the JPEG library in your own programs. - example.c Sample code for calling the JPEG library. - structure.doc Overview of the JPEG library's internal structure. - filelist.doc Road map of IJG files. - coderules.doc Coding style rules --- please read if you contribute code. - -Please read at least the files install.doc and usage.doc. Useful information -can also be found in the JPEG FAQ (Frequently Asked Questions) article. See -ARCHIVE LOCATIONS below to find out where to obtain the FAQ article. - -If you want to understand how the JPEG code works, we suggest reading one or -more of the REFERENCES, then looking at the documentation files (in roughly -the order listed) before diving into the code. - - -OVERVIEW -======== - -This package contains C software to implement JPEG image compression and -decompression. JPEG (pronounced "jay-peg") is a standardized compression -method for full-color and gray-scale images. JPEG is intended for compressing -"real-world" scenes; line drawings, cartoons and other non-realistic images -are not its strong suit. JPEG is lossy, meaning that the output image is not -exactly identical to the input image. Hence you must not use JPEG if you -have to have identical output bits. However, on typical photographic images, -very good compression levels can be obtained with no visible change, and -remarkably high compression levels are possible if you can tolerate a -low-quality image. For more details, see the references, or just experiment -with various compression settings. - -This software implements JPEG baseline, extended-sequential, and progressive -compression processes. Provision is made for supporting all variants of these -processes, although some uncommon parameter settings aren't implemented yet. -For legal reasons, we are not distributing code for the arithmetic-coding -variants of JPEG; see LEGAL ISSUES. We have made no provision for supporting -the hierarchical or lossless processes defined in the standard. - -We provide a set of library routines for reading and writing JPEG image files, -plus two sample applications "cjpeg" and "djpeg", which use the library to -perform conversion between JPEG and some other popular image file formats. -The library is intended to be reused in other applications. - -In order to support file conversion and viewing software, we have included -considerable functionality beyond the bare JPEG coding/decoding capability; -for example, the color quantization modules are not strictly part of JPEG -decoding, but they are essential for output to colormapped file formats or -colormapped displays. These extra functions can be compiled out of the -library if not required for a particular application. We have also included -"jpegtran", a utility for lossless transcoding between different JPEG -processes, and "rdjpgcom" and "wrjpgcom", two simple applications for -inserting and extracting textual comments in JFIF files. - -The emphasis in designing this software has been on achieving portability and -flexibility, while also making it fast enough to be useful. In particular, -the software is not intended to be read as a tutorial on JPEG. (See the -REFERENCES section for introductory material.) Rather, it is intended to -be reliable, portable, industrial-strength code. We do not claim to have -achieved that goal in every aspect of the software, but we strive for it. - -We welcome the use of this software as a component of commercial products. -No royalty is required, but we do ask for an acknowledgement in product -documentation, as described under LEGAL ISSUES. - - -LEGAL ISSUES -============ - -In plain English: - -1. We don't promise that this software works. (But if you find any bugs, - please let us know!) -2. You can use this software for whatever you want. You don't have to pay us. -3. You may not pretend that you wrote this software. If you use it in a - program, you must acknowledge somewhere in your documentation that - you've used the IJG code. - -In legalese: - -The authors make NO WARRANTY or representation, either express or implied, -with respect to this software, its quality, accuracy, merchantability, or -fitness for a particular purpose. This software is provided "AS IS", and you, -its user, assume the entire risk as to its quality and accuracy. - -This software is copyright (C) 1991-1998, Thomas G. Lane. -All Rights Reserved except as specified below. - -Permission is hereby granted to use, copy, modify, and distribute this -software (or portions thereof) for any purpose, without fee, subject to these -conditions: -(1) If any part of the source code for this software is distributed, then this -README file must be included, with this copyright and no-warranty notice -unaltered; and any additions, deletions, or changes to the original files -must be clearly indicated in accompanying documentation. -(2) If only executable code is distributed, then the accompanying -documentation must state that "this software is based in part on the work of -the Independent JPEG Group". -(3) Permission for use of this software is granted only if the user accepts -full responsibility for any undesirable consequences; the authors accept -NO LIABILITY for damages of any kind. - -These conditions apply to any software derived from or based on the IJG code, -not just to the unmodified library. If you use our work, you ought to -acknowledge us. - -Permission is NOT granted for the use of any IJG author's name or company name -in advertising or publicity relating to this software or products derived from -it. This software may be referred to only as "the Independent JPEG Group's -software". - -We specifically permit and encourage the use of this software as the basis of -commercial products, provided that all warranty or liability claims are -assumed by the product vendor. - - -ansi2knr.c is included in this distribution by permission of L. Peter Deutsch, -sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA. -ansi2knr.c is NOT covered by the above copyright and conditions, but instead -by the usual distribution terms of the Free Software Foundation; principally, -that you must include source code if you redistribute it. (See the file -ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part -of any program generated from the IJG code, this does not limit you more than -the foregoing paragraphs do. - -The Unix configuration script "configure" was produced with GNU Autoconf. -It is copyright by the Free Software Foundation but is freely distributable. -The same holds for its supporting scripts (config.guess, config.sub, -ltconfig, ltmain.sh). Another support script, install-sh, is copyright -by M.I.T. but is also freely distributable. - -It appears that the arithmetic coding option of the JPEG spec is covered by -patents owned by IBM, AT&T, and Mitsubishi. Hence arithmetic coding cannot -legally be used without obtaining one or more licenses. For this reason, -support for arithmetic coding has been removed from the free JPEG software. -(Since arithmetic coding provides only a marginal gain over the unpatented -Huffman mode, it is unlikely that very many implementations will support it.) -So far as we are aware, there are no patent restrictions on the remaining -code. - -The IJG distribution formerly included code to read and write GIF files. -To avoid entanglement with the Unisys LZW patent, GIF reading support has -been removed altogether, and the GIF writer has been simplified to produce -"uncompressed GIFs". This technique does not use the LZW algorithm; the -resulting GIF files are larger than usual, but are readable by all standard -GIF decoders. - -We are required to state that - "The Graphics Interchange Format(c) is the Copyright property of - CompuServe Incorporated. GIF(sm) is a Service Mark property of - CompuServe Incorporated." - - -REFERENCES -========== - -We highly recommend reading one or more of these references before trying to -understand the innards of the JPEG software. - -The best short technical introduction to the JPEG compression algorithm is - Wallace, Gregory K. "The JPEG Still Picture Compression Standard", - Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44. -(Adjacent articles in that issue discuss MPEG motion picture compression, -applications of JPEG, and related topics.) If you don't have the CACM issue -handy, a PostScript file containing a revised version of Wallace's article is -available at ftp://ftp.uu.net/graphics/jpeg/wallace.ps.gz. The file (actually -a preprint for an article that appeared in IEEE Trans. Consumer Electronics) -omits the sample images that appeared in CACM, but it includes corrections -and some added material. Note: the Wallace article is copyright ACM and IEEE, -and it may not be used for commercial purposes. - -A somewhat less technical, more leisurely introduction to JPEG can be found in -"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by -M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides -good explanations and example C code for a multitude of compression methods -including JPEG. It is an excellent source if you are comfortable reading C -code but don't know much about data compression in general. The book's JPEG -sample code is far from industrial-strength, but when you are ready to look -at a full implementation, you've got one here... - -The best full description of JPEG is the textbook "JPEG Still Image Data -Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published -by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp. -The book includes the complete text of the ISO JPEG standards (DIS 10918-1 -and draft DIS 10918-2). This is by far the most complete exposition of JPEG -in existence, and we highly recommend it. - -The JPEG standard itself is not available electronically; you must order a -paper copy through ISO or ITU. (Unless you feel a need to own a certified -official copy, we recommend buying the Pennebaker and Mitchell book instead; -it's much cheaper and includes a great deal of useful explanatory material.) -In the USA, copies of the standard may be ordered from ANSI Sales at (212) -642-4900, or from Global Engineering Documents at (800) 854-7179. (ANSI -doesn't take credit card orders, but Global does.) It's not cheap: as of -1992, ANSI was charging $95 for Part 1 and $47 for Part 2, plus 7% -shipping/handling. The standard is divided into two parts, Part 1 being the -actual specification, while Part 2 covers compliance testing methods. Part 1 -is titled "Digital Compression and Coding of Continuous-tone Still Images, -Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS -10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of -Continuous-tone Still Images, Part 2: Compliance testing" and has document -numbers ISO/IEC IS 10918-2, ITU-T T.83. - -Some extensions to the original JPEG standard are defined in JPEG Part 3, -a newer ISO standard numbered ISO/IEC IS 10918-3 and ITU-T T.84. IJG -currently does not support any Part 3 extensions. - -The JPEG standard does not specify all details of an interchangeable file -format. For the omitted details we follow the "JFIF" conventions, revision -1.02. A copy of the JFIF spec is available from: - Literature Department - C-Cube Microsystems, Inc. - 1778 McCarthy Blvd. - Milpitas, CA 95035 - phone (408) 944-6300, fax (408) 944-6314 -A PostScript version of this document is available by FTP at -ftp://ftp.uu.net/graphics/jpeg/jfif.ps.gz. There is also a plain text -version at ftp://ftp.uu.net/graphics/jpeg/jfif.txt.gz, but it is missing -the figures. - -The TIFF 6.0 file format specification can be obtained by FTP from -ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme -found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems. -IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6). -Instead, we recommend the JPEG design proposed by TIFF Technical Note #2 -(Compression tag 7). Copies of this Note can be obtained from ftp.sgi.com or -from ftp://ftp.uu.net/graphics/jpeg/. It is expected that the next revision -of the TIFF spec will replace the 6.0 JPEG design with the Note's design. -Although IJG's own code does not support TIFF/JPEG, the free libtiff library -uses our library to implement TIFF/JPEG per the Note. libtiff is available -from ftp://ftp.sgi.com/graphics/tiff/. - - -ARCHIVE LOCATIONS -================= - -The "official" archive site for this software is ftp.uu.net (Internet -address 192.48.96.9). The most recent released version can always be found -there in directory graphics/jpeg. This particular version will be archived -as ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz. If you don't have -direct Internet access, UUNET's archives are also available via UUCP; contact -help@uunet.uu.net for information on retrieving files that way. - -Numerous Internet sites maintain copies of the UUNET files. However, only -ftp.uu.net is guaranteed to have the latest official version. - -You can also obtain this software in DOS-compatible "zip" archive format from -the SimTel archives (ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/), or -on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12 -"JPEG Tools". Again, these versions may sometimes lag behind the ftp.uu.net -release. - -The JPEG FAQ (Frequently Asked Questions) article is a useful source of -general information about JPEG. It is updated constantly and therefore is -not included in this distribution. The FAQ is posted every two weeks to -Usenet newsgroups comp.graphics.misc, news.answers, and other groups. -It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/ -and other news.answers archive sites, including the official news.answers -archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/. -If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu -with body - send usenet/news.answers/jpeg-faq/part1 - send usenet/news.answers/jpeg-faq/part2 - - -RELATED SOFTWARE -================ - -Numerous viewing and image manipulation programs now support JPEG. (Quite a -few of them use this library to do so.) The JPEG FAQ described above lists -some of the more popular free and shareware viewers, and tells where to -obtain them on Internet. - -If you are on a Unix machine, we highly recommend Jef Poskanzer's free -PBMPLUS software, which provides many useful operations on PPM-format image -files. In particular, it can convert PPM images to and from a wide range of -other formats, thus making cjpeg/djpeg considerably more useful. The latest -version is distributed by the NetPBM group, and is available from numerous -sites, notably ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/. -Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is; -you are likely to have difficulty making it work on any non-Unix machine. - -A different free JPEG implementation, written by the PVRG group at Stanford, -is available from ftp://havefun.stanford.edu/pub/jpeg/. This program -is designed for research and experimentation rather than production use; -it is slower, harder to use, and less portable than the IJG code, but it -is easier to read and modify. Also, the PVRG code supports lossless JPEG, -which we do not. (On the other hand, it doesn't do progressive JPEG.) - - -FILE FORMAT WARS -================ - -Some JPEG programs produce files that are not compatible with our library. -The root of the problem is that the ISO JPEG committee failed to specify a -concrete file format. Some vendors "filled in the blanks" on their own, -creating proprietary formats that no one else could read. (For example, none -of the early commercial JPEG implementations for the Macintosh were able to -exchange compressed files.) - -The file format we have adopted is called JFIF (see REFERENCES). This format -has been agreed to by a number of major commercial JPEG vendors, and it has -become the de facto standard. JFIF is a minimal or "low end" representation. -We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF -Technical Note #2) for "high end" applications that need to record a lot of -additional data about an image. TIFF/JPEG is fairly new and not yet widely -supported, unfortunately. - -The upcoming JPEG Part 3 standard defines a file format called SPIFF. -SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should -be able to read the most common variant of SPIFF. SPIFF has some technical -advantages over JFIF, but its major claim to fame is simply that it is an -official standard rather than an informal one. At this point it is unclear -whether SPIFF will supersede JFIF or whether JFIF will remain the de-facto -standard. IJG intends to support SPIFF once the standard is frozen, but we -have not decided whether it should become our default output format or not. -(In any case, our decoder will remain capable of reading JFIF indefinitely.) - -Various proprietary file formats incorporating JPEG compression also exist. -We have little or no sympathy for the existence of these formats. Indeed, -one of the original reasons for developing this free software was to help -force convergence on common, open format standards for JPEG files. Don't -use a proprietary file format! - - -TO DO -===== - -The major thrust for v7 will probably be improvement of visual quality. -The current method for scaling the quantization tables is known not to be -very good at low Q values. We also intend to investigate block boundary -smoothing, "poor man's variable quantization", and other means of improving -quality-vs-file-size performance without sacrificing compatibility. - -In future versions, we are considering supporting some of the upcoming JPEG -Part 3 extensions --- principally, variable quantization and the SPIFF file -format. - -As always, speeding things up is of great interest. - -Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net. diff --git a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jchuff.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jchuff.h deleted file mode 100644 index f43d571d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jchuff.h +++ /dev/null @@ -1,34 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jcomapi.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jcomapi.cpp deleted file mode 100644 index df3302cb..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jcomapi.cpp +++ /dev/null @@ -1,94 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jconfig.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jconfig.h deleted file mode 100644 index 7d2f733b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jconfig.h +++ /dev/null @@ -1,41 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdapimin.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdapimin.cpp deleted file mode 100644 index c5c3be32..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdapimin.cpp +++ /dev/null @@ -1,400 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdapistd.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdapistd.cpp deleted file mode 100644 index 22da01b3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdapistd.cpp +++ /dev/null @@ -1,275 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdatasrc.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdatasrc.cpp deleted file mode 100644 index 9bb30dbe..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdatasrc.cpp +++ /dev/null @@ -1,189 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdcoefct.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdcoefct.cpp deleted file mode 100644 index 4b371313..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdcoefct.cpp +++ /dev/null @@ -1,725 +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< 0 && pred >= (1<= 0) { - pred = (int) (((Q10<<7) + num) / (Q10<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { - pred = (int) (((Q20<<7) + num) / (Q20<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { - pred = (int) (((Q11<<7) + num) / (Q11<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { - pred = (int) (((Q02<<7) + num) / (Q02<<8)); - if (Al > 0 && pred >= (1< 0 && pred >= (1<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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdcolor.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdcolor.cpp deleted file mode 100644 index 50e66f26..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdcolor.cpp +++ /dev/null @@ -1,367 +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<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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdct.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdct.h deleted file mode 100644 index 3ce790bc..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdct.h +++ /dev/null @@ -1,176 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jddctmgr.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jddctmgr.cpp deleted file mode 100644 index 5267ade9..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jddctmgr.cpp +++ /dev/null @@ -1,270 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdhuff.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdhuff.cpp deleted file mode 100644 index 025d5187..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdhuff.cpp +++ /dev/null @@ -1,574 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdhuff.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdhuff.h deleted file mode 100644 index d375c781..00000000 --- a/misc/mediasource/extra/netradiant-src/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< 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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdinput.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdinput.cpp deleted file mode 100644 index f48307d0..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdinput.cpp +++ /dev/null @@ -1,381 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmainct.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmainct.cpp deleted file mode 100644 index d445649f..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmainct.cpp +++ /dev/null @@ -1,512 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmarker.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmarker.cpp deleted file mode 100644 index b897b507..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmarker.cpp +++ /dev/null @@ -1,1052 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmaster.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmaster.cpp deleted file mode 100644 index 6d38f604..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdmaster.cpp +++ /dev/null @@ -1,558 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdpostct.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdpostct.cpp deleted file mode 100644 index e8b934cc..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdpostct.cpp +++ /dev/null @@ -1,290 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdsample.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdsample.cpp deleted file mode 100644 index f53ceaf3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdsample.cpp +++ /dev/null @@ -1,478 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdtrans.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdtrans.cpp deleted file mode 100644 index 3f05ae37..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jdtrans.cpp +++ /dev/null @@ -1,122 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jerror.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jerror.cpp deleted file mode 100644 index dda71a56..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jerror.cpp +++ /dev/null @@ -1,233 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jerror.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jerror.h deleted file mode 100644 index 86a36c70..00000000 --- a/misc/mediasource/extra/netradiant-src/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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jfdctflt.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jfdctflt.cpp deleted file mode 100644 index 785e93ef..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jfdctflt.cpp +++ /dev/null @@ -1,168 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jidctflt.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jidctflt.cpp deleted file mode 100644 index 82d1e61d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jidctflt.cpp +++ /dev/null @@ -1,241 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jinclude.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jinclude.h deleted file mode 100644 index 0a4f1514..00000000 --- a/misc/mediasource/extra/netradiant-src/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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemmgr.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemmgr.cpp deleted file mode 100644 index 9862e2f8..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemmgr.cpp +++ /dev/null @@ -1,1115 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemnobs.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemnobs.cpp deleted file mode 100644 index df0abb0c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemnobs.cpp +++ /dev/null @@ -1,103 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemsys.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemsys.h deleted file mode 100644 index 033d29a7..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmemsys.h +++ /dev/null @@ -1,182 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmorecfg.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmorecfg.h deleted file mode 100644 index e14f31bd..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jmorecfg.h +++ /dev/null @@ -1,348 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jpegint.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jpegint.h deleted file mode 100644 index ab5bee2c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jpegint.h +++ /dev/null @@ -1,388 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jpgload.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jpgload.cpp deleted file mode 100644 index fa3523ed..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jpgload.cpp +++ /dev/null @@ -1,200 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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; - int i; - - // 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. - */ - - if( cinfo.output_components != 1 && cinfo.output_components != 3 && cinfo.output_components != 4 ) - { - *pic = const_cast(reinterpret_cast("Non-Y/RGB/RGBA 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*4; - - 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 ); - - // we convert downwards to not overwrite values we want to read later - switch(cinfo.output_components) - { - case 4: - // clear all the alphas to 255 - for(i = cinfo.output_width; i-- > 0; ) - { - bbuf[i*4+3] = 255; - } - break; - case 3: - // expand 3 to 4 - for(i = cinfo.output_width; i-- > 0; ) - { - bbuf[i*4+3] = 255; - bbuf[i*4+2] = bbuf[i*3+2]; - bbuf[i*4+1] = bbuf[i*3+1]; - bbuf[i*4+0] = bbuf[i*3+0]; - } - break; - case 1: - // expand 1 to 4 - for(i = cinfo.output_width; i-- > 0; ) - { - bbuf[i*4+3] = 255; - bbuf[i*4+2] = bbuf[i]; - bbuf[i*4+1] = bbuf[i]; - bbuf[i*4+0] = bbuf[i]; - } - break; - } - } - - /* 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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jutils.cpp b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jutils.cpp deleted file mode 100644 index 549648de..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jutils.cpp +++ /dev/null @@ -1,175 +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/misc/mediasource/extra/netradiant-src/libs/jpeg6/jversion.h b/misc/mediasource/extra/netradiant-src/libs/jpeg6/jversion.h deleted file mode 100644 index f2f1b8da..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeg6/jversion.h +++ /dev/null @@ -1,14 +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/misc/mediasource/extra/netradiant-src/libs/jpeglib.h b/misc/mediasource/extra/netradiant-src/libs/jpeglib.h deleted file mode 100644 index f5b59010..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/jpeglib.h +++ /dev/null @@ -1,1123 +0,0 @@ -/* -Copyright (C) 1999-2006 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 (WIN32) - -#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/misc/mediasource/extra/netradiant-src/libs/l_net/l_net.c b/misc/mediasource/extra/netradiant-src/libs/l_net/l_net.c deleted file mode 100644 index ca730d03..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/l_net/l_net.c +++ /dev/null @@ -1,626 +0,0 @@ -/* -Copyright (C) 1999-2006 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(const char *str, ...) -{ - va_list argptr; - char text[4096]; - - va_start (argptr,str); - vsprintf (text, str, argptr); - va_end (argptr); - - printf(text); -} -#else -void WinPrint(const 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); -#else - 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(const 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 - memcpy(&msg->data[msg->size], string, strlen(string) + 1); - 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->read + 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 ((size_t) l < sizeof(string)-1); - string[l] = 0; - return string; -} //end of the function NMSG_ReadString diff --git a/misc/mediasource/extra/netradiant-src/libs/l_net/l_net.h b/misc/mediasource/extra/netradiant-src/libs/l_net/l_net.h deleted file mode 100644 index 6c548334..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/l_net/l_net.h +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright (C) 1999-2006 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; - -void WinPrint(const char *format, ...); - -//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(const 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 -const char *WINS_ErrorMessage(int error); - -#ifdef __cplusplus -} -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_berkley.c b/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_berkley.c deleted file mode 100644 index edc06fa1..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_berkley.c +++ /dev/null @@ -1,770 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#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: - -//=========================================================================== -const 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; -/* - 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) -{ - socklen_t 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) -{ - socklen_t 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; - ret = 0; - - 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) -{ - socklen_t 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/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_wins.c b/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_wins.c deleted file mode 100644 index 1b365da0..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_wins.c +++ /dev/null @@ -1,783 +0,0 @@ -/* -Copyright (C) 1999-2006 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} -}; - -//=========================================================================== -// -// Parameter: - -// Returns: - -// Changes Globals: - -//=========================================================================== -const 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/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_wins.h b/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_wins.h deleted file mode 100644 index ad1b41fb..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/l_net/l_net_wins.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/libs/maplib.cpp b/misc/mediasource/extra/netradiant-src/libs/maplib.cpp deleted file mode 100644 index 80504f1d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/maplib.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "maplib.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/maplib.h b/misc/mediasource/extra/netradiant-src/libs/maplib.h deleted file mode 100644 index 6a2d5cea..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/maplib.h +++ /dev/null @@ -1,282 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (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; - InstanceSet m_instances; - typedef SelectableInstance Instance; - NameableString m_name; - UndoFileChangeTracker m_changeTracker; -public: - typedef LazyStatic StaticTypeCasts; - - scene::Traversable& get(NullType) - { - return m_traverse; - } - TransformNode& 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/misc/mediasource/extra/netradiant-src/libs/math/aabb.cpp b/misc/mediasource/extra/netradiant-src/libs/math/aabb.cpp deleted file mode 100644 index 8bed2209..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/aabb.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "aabb.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/aabb.h b/misc/mediasource/extra/netradiant-src/libs/math/aabb.h deleted file mode 100644 index 1341a340..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/aabb.h +++ /dev/null @@ -1,331 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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< IntegralConstant<0> >::apply(aabb, point); - AABBExtend< IntegralConstant<1> >::apply(aabb, point); - AABBExtend< IntegralConstant<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< IntegralConstant<0> >::apply(aabb, other); - AABBExtend< IntegralConstant<1> >::apply(aabb, other); - AABBExtend< IntegralConstant<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< IntegralConstant<0> >(aabb, point) - && aabb_intersects_point_dimension< IntegralConstant<1> >(aabb, point) - && aabb_intersects_point_dimension< IntegralConstant<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< IntegralConstant<0> >(aabb, other) - && aabb_intersects_aabb_dimension< IntegralConstant<1> >(aabb, other) - && aabb_intersects_aabb_dimension< IntegralConstant<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_corners_oriented(const AABB& aabb, const Matrix4& rotation, Vector3 corners[8]) -{ - Vector3 x = vector4_to_vector3(rotation.x()) * aabb.extents.x(); - Vector3 y = vector4_to_vector3(rotation.y()) * aabb.extents.y(); - Vector3 z = vector4_to_vector3(rotation.z()) * aabb.extents.z(); - - corners[0] = aabb.origin + -x + y + z; - corners[1] = aabb.origin + x + y + z; - corners[2] = aabb.origin + x + -y + z; - corners[3] = aabb.origin + -x + -y + z; - corners[4] = aabb.origin + -x + y + -z; - corners[5] = aabb.origin + x + y + -z; - corners[6] = aabb.origin + x + -y + -z; - corners[7] = aabb.origin + -x + -y + -z; -} - -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])); -} - -inline void aabb_planes_oriented(const AABB& aabb, const Matrix4& rotation, Plane3 planes[6]) -{ - double x = vector3_dot(vector4_to_vector3(rotation.x()), aabb.origin); - double y = vector3_dot(vector4_to_vector3(rotation.y()), aabb.origin); - double z = vector3_dot(vector4_to_vector3(rotation.z()), aabb.origin); - - planes[0] = Plane3(vector4_to_vector3(rotation.x()), x + aabb.extents[0]); - planes[1] = Plane3(-vector4_to_vector3(rotation.x()), -(x - aabb.extents[0])); - planes[2] = Plane3(vector4_to_vector3(rotation.y()), y + aabb.extents[1]); - planes[3] = Plane3(-vector4_to_vector3(rotation.y()), -(y - aabb.extents[1])); - planes[4] = Plane3(vector4_to_vector3(rotation.z()), z + aabb.extents[2]); - planes[5] = Plane3(-vector4_to_vector3(rotation.z()), -(z - 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/misc/mediasource/extra/netradiant-src/libs/math/curve.cpp b/misc/mediasource/extra/netradiant-src/libs/math/curve.cpp deleted file mode 100644 index dd2bc0e3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/curve.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "curve.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/curve.h b/misc/mediasource/extra/netradiant-src/libs/math/curve.h deleted file mode 100644 index 9000734c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/curve.h +++ /dev/null @@ -1,273 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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 IntegralConstant<0> Zero; -typedef IntegralConstant<1> One; -typedef IntegralConstant<2> Two; -typedef IntegralConstant<3> Three; -typedef IntegralConstant<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/misc/mediasource/extra/netradiant-src/libs/math/expression.cpp b/misc/mediasource/extra/netradiant-src/libs/math/expression.cpp deleted file mode 100644 index 5fc8d051..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/expression.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/math/expression.h b/misc/mediasource/extra/netradiant-src/libs/math/expression.h deleted file mode 100644 index c609bb16..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/expression.h +++ /dev/null @@ -1,617 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (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 IntegralConstant<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 IntegralConstant<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< IntegralConstant >::apply(first, second) - ); - } - }; - - template<> - struct eval_dot< IntegralConstant<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< IntegralConstant >::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< IntegralConstant >::apply(first) - ); - } - }; - - template<> - struct eval_squared< IntegralConstant<0> > - { - static value_type apply(const First& first) - { - return squared(first.eval(0)); - } - }; - - value_type eval() const - { - return eval_squared< IntegralConstant >::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 IntegralConstant<4> dimension0; - typedef IntegralConstant<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 IntegralConstant<4> dimension0; - typedef IntegralConstant<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/misc/mediasource/extra/netradiant-src/libs/math/frustum.cpp b/misc/mediasource/extra/netradiant-src/libs/math/frustum.cpp deleted file mode 100644 index 84481e20..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/frustum.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "frustum.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/frustum.h b/misc/mediasource/extra/netradiant-src/libs/math/frustum.h deleted file mode 100644 index fe98db20..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/frustum.h +++ /dev/null @@ -1,629 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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< IntegralConstant<0> >::compare(p)) -#define CLIP_X_GT_W(p) (Vector4ClipGT< IntegralConstant<0> >::compare(p)) -#define CLIP_Y_LT_W(p) (Vector4ClipLT< IntegralConstant<1> >::compare(p)) -#define CLIP_Y_GT_W(p) (Vector4ClipGT< IntegralConstant<1> >::compare(p)) -#define CLIP_Z_LT_W(p) (Vector4ClipLT< IntegralConstant<2> >::compare(p)) -#define CLIP_Z_GT_W(p) (Vector4ClipGT< IntegralConstant<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< IntegralConstant<0> > >::apply(clipped, clipped + count, buffer); - count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<0> > >::apply(buffer, buffer + count, clipped); - count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<1> > >::apply(clipped, clipped + count, buffer); - count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<1> > >::apply(buffer, buffer + count, clipped); - count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<2> > >::apply(clipped, clipped + count, buffer); - return Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<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/misc/mediasource/extra/netradiant-src/libs/math/line.cpp b/misc/mediasource/extra/netradiant-src/libs/math/line.cpp deleted file mode 100644 index a0bdea1a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/line.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "line.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/line.h b/misc/mediasource/extra/netradiant-src/libs/math/line.h deleted file mode 100644 index 26d58369..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/line.h +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/math/matrix.cpp b/misc/mediasource/extra/netradiant-src/libs/math/matrix.cpp deleted file mode 100644 index e3831647..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/matrix.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "matrix.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/matrix.h b/misc/mediasource/extra/netradiant-src/libs/math/matrix.h deleted file mode 100644 index b28c2688..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/matrix.h +++ /dev/null @@ -1,1322 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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 direction 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 Matrix4 matrix4_affine_inverse(const Matrix4& self) -{ - Matrix4 result; - - // determinant of rotation submatrix - double det - = self[0] * ( self[5]*self[10] - self[9]*self[6] ) - - self[1] * ( self[4]*self[10] - self[8]*self[6] ) - + self[2] * ( self[4]*self[9] - self[8]*self[5] ); - - // throw exception here if (det*det < 1e-25) - - // invert rotation submatrix - det = 1.0 / det; - - result[0] = static_cast( (self[5]*self[10]- self[6]*self[9] )*det); - result[1] = static_cast(- (self[1]*self[10]- self[2]*self[9] )*det); - result[2] = static_cast( (self[1]*self[6] - self[2]*self[5] )*det); - result[3] = 0; - result[4] = static_cast(- (self[4]*self[10]- self[6]*self[8] )*det); - result[5] = static_cast( (self[0]*self[10]- self[2]*self[8] )*det); - result[6] = static_cast(- (self[0]*self[6] - self[2]*self[4] )*det); - result[7] = 0; - result[8] = static_cast( (self[4]*self[9] - self[5]*self[8] )*det); - result[9] = static_cast(- (self[0]*self[9] - self[1]*self[8] )*det); - result[10]= static_cast( (self[0]*self[5] - self[1]*self[4] )*det); - result[11] = 0; - - // multiply translation part by rotation - result[12] = - (self[12] * result[0] + - self[13] * result[4] + - self[14] * result[8]); - result[13] = - (self[12] * result[1] + - self[13] * result[5] + - self[14] * result[9]); - result[14] = - (self[12] * result[2] + - self[13] * result[6] + - self[14] * result[10]); - result[15] = 1; - - return result; -} - -inline void matrix4_affine_invert(Matrix4& self) -{ - self = matrix4_affine_inverse(self); -} - -/// \brief A compile-time-constant integer. -template -struct IntegralConstant -{ - enum unnamed_{ VALUE = VALUE_ }; -}; - -/// \brief A compile-time-constant row/column index into a 4x4 matrix. -template -class Matrix4Index -{ -public: - typedef IntegralConstant r; - typedef IntegralConstant c; - typedef IntegralConstant<(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 IntegralConstant<(Element <= 0) ? 1 : 0> x; - typedef IntegralConstant<(Element <= 1) ? 2 : 1> y; - typedef IntegralConstant<(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/misc/mediasource/extra/netradiant-src/libs/math/pi.cpp b/misc/mediasource/extra/netradiant-src/libs/math/pi.cpp deleted file mode 100644 index 34930192..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/pi.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "pi.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/pi.h b/misc/mediasource/extra/netradiant-src/libs/math/pi.h deleted file mode 100644 index 9cc74c1b..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/pi.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/math/plane.cpp b/misc/mediasource/extra/netradiant-src/libs/math/plane.cpp deleted file mode 100644 index 4182a175..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/plane.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "plane.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/plane.h b/misc/mediasource/extra/netradiant-src/libs/math/plane.h deleted file mode 100644 index af05db74..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/plane.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/math/quaternion.cpp b/misc/mediasource/extra/netradiant-src/libs/math/quaternion.cpp deleted file mode 100644 index 6688368e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/quaternion.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "quaternion.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/quaternion.h b/misc/mediasource/extra/netradiant-src/libs/math/quaternion.h deleted file mode 100644 index d91ad62a..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/quaternion.h +++ /dev/null @@ -1,327 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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_for_x(double angle) -{ - angle *= 0.5; - return Quaternion(static_cast(sin(angle)), 0, 0, static_cast(cos(angle))); -} - -inline Quaternion quaternion_for_y(double angle) -{ - angle *= 0.5; - return Quaternion(0, static_cast(sin(angle)), 0, static_cast(cos(angle))); -} - -inline Quaternion quaternion_for_z(double angle) -{ - angle *= 0.5; - return Quaternion(0, 0, static_cast(sin(angle)), 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/misc/mediasource/extra/netradiant-src/libs/math/vector.cpp b/misc/mediasource/extra/netradiant-src/libs/math/vector.cpp deleted file mode 100644 index d72bd9e4..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/vector.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "vector.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/math/vector.h b/misc/mediasource/extra/netradiant-src/libs/math/vector.h deleted file mode 100644 index 075c58fe..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/math/vector.h +++ /dev/null @@ -1,813 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_MATH_VECTOR_H) -#define INCLUDED_MATH_VECTOR_H - -/// \file -/// \brief Vector data types and related operations. - -#include "generic/vector.h" - -#if defined (_MSC_VER) - -inline int lrint (double flt) -{ - int i; - - _asm - { - fld flt - fistp i - }; - - return i; -} - -inline __int64 llrint(double f) -{ - return static_cast<__int64>(f + 0.5); -} - -#elif defined(__FreeBSD__) - -inline long lrint(double f) -{ - return static_cast(f + 0.5); -} - -inline long long llrint(double f) -{ - return static_cast(f + 0.5); -} - -#elif defined(__GNUC__) - - // lrint is part of ISO C99 -#define _ISOC9X_SOURCE 1 -#define _ISOC99_SOURCE 1 - -#define __USE_ISOC9X 1 -#define __USE_ISOC99 1 - -#else -#error "unsupported platform" -#endif - -#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 \p snap. -template -inline Element float_snapped(const Element& f, const OtherElement& snap) -{ - //return Element(float_to_integer(f / snap) * snap); - if(snap == 0) - return f; - return Element(llrint(f / snap) * snap); // llrint has more significant bits -} - -/// \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 -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); -} - -template -inline double vector2_length(const BasicVector2& self) -{ - return sqrt(vector2_length_squared(self)); -} - -template -inline double vector2_cross(const BasicVector2& self, const BasicVector2& other) -{ - return self.x() * other.y() - self.y() * other.x(); -} - -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 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 BasicVector3 operator-(const BasicVector3& self) -{ - return vector3_negated(self); -} - -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)) - ); -} - - - - -template -inline bool vector4_equal(const BasicVector4& self, const BasicVector4& other) -{ - return self.x() == other.x() && self.y() == other.y() && self.z() == other.z() && self.w() == other.w(); -} -template -inline bool operator==(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_equal(self, other); -} -template -inline bool operator!=(const BasicVector4& self, const BasicVector4& other) -{ - return !vector4_equal(self, other); -} - -template -inline bool vector4_equal_epsilon(const BasicVector4& self, const BasicVector4& other, Element 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) - && float_equal_epsilon(self.w(), other.w(), epsilon); -} - -template -inline BasicVector4 vector4_added(const BasicVector4& self, const BasicVector4& other) -{ - return BasicVector4( - float(self.x() + other.x()), - float(self.y() + other.y()), - float(self.z() + other.z()), - float(self.w() + other.w()) - ); -} -template -inline BasicVector4 operator+(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_added(self, other); -} -template -inline void vector4_add(BasicVector4& self, const BasicVector4& 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()); -} -template -inline void operator+=(BasicVector4& self, const BasicVector4& other) -{ - vector4_add(self, other); -} - -template -inline BasicVector4 vector4_subtracted(const BasicVector4& self, const BasicVector4& other) -{ - return BasicVector4( - float(self.x() - other.x()), - float(self.y() - other.y()), - float(self.z() - other.z()), - float(self.w() - other.w()) - ); -} -template -inline BasicVector4 operator-(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_subtracted(self, other); -} -template -inline void vector4_subtract(BasicVector4& self, const BasicVector4& 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()); -} -template -inline void operator-=(BasicVector4& self, const BasicVector4& other) -{ - vector4_subtract(self, other); -} - -template -inline BasicVector4 vector4_scaled(const BasicVector4& self, const BasicVector4& other) -{ - return BasicVector4( - float(self.x() * other.x()), - float(self.y() * other.y()), - float(self.z() * other.z()), - float(self.w() * other.w()) - ); -} -template -inline BasicVector4 operator*(const BasicVector4& self, const BasicVector4& other) -{ - return vector4_scaled(self, other); -} -template -inline void vector4_scale(BasicVector4& self, const BasicVector4& 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()); -} -template -inline void operator*=(BasicVector4& self, const BasicVector4& other) -{ - vector4_scale(self, other); -} - -template -inline BasicVector4 vector4_scaled(const BasicVector4& self, OtherElement scale) -{ - return BasicVector4( - float(self.x() * scale), - float(self.y() * scale), - float(self.z() * scale), - float(self.w() * scale) - ); -} -template -inline BasicVector4 operator*(const BasicVector4& self, OtherElement scale) -{ - return vector4_scaled(self, scale); -} -template -inline void vector4_scale(BasicVector4& self, OtherElement scale) -{ - self.x() *= static_cast(scale); - self.y() *= static_cast(scale); - self.z() *= static_cast(scale); - self.w() *= static_cast(scale); -} -template -inline void operator*=(BasicVector4& self, OtherElement scale) -{ - vector4_scale(self, scale); -} - -template -inline BasicVector4 vector4_divided(const BasicVector4& self, OtherElement divisor) -{ - return BasicVector4( - float(self.x() / divisor), - float(self.y() / divisor), - float(self.z() / divisor), - float(self.w() / divisor) - ); -} -template -inline BasicVector4 operator/(const BasicVector4& self, OtherElement divisor) -{ - return vector4_divided(self, divisor); -} -template -inline void vector4_divide(BasicVector4& self, OtherElement divisor) -{ - self.x() /= divisor; - self.y() /= divisor; - self.z() /= divisor; - self.w() /= divisor; -} -template -inline void operator/=(BasicVector4& self, OtherElement divisor) -{ - vector4_divide(self, divisor); -} - -template -inline double vector4_dot(const BasicVector4& self, const BasicVector4& other) -{ - return self.x() * other.x() + self.y() * other.y() + self.z() * other.z() + self.w() * other.w(); -} - -template -inline BasicVector3 vector4_projected(const BasicVector4& self) -{ - return vector3_scaled(vector4_to_vector3(self), 1.0 / self[3]); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/mathlib.h b/misc/mediasource/extra/netradiant-src/libs/mathlib.h deleted file mode 100644 index 382933d7..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/mathlib.h +++ /dev/null @@ -1,483 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#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]; - -// Smallest positive value for vec_t such that 1.0 + VEC_SMALLEST_EPSILON_AROUND_ONE != 1.0. -// In the case of 32 bit floats (which is almost certainly the case), it's 0.00000011921. -// Don't forget that your epsilons should depend on the possible range of values, -// because for example adding VEC_SMALLEST_EPSILON_AROUND_ONE to 1024.0 will have no effect. -#define VEC_SMALLEST_EPSILON_AROUND_ONE FLT_EPSILON - -#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 RGBTOGRAY(x) ( (float)((x)[0]) * 0.2989f + (float)((x)[1]) * 0.5870f + (float)((x)[2]) * 0.1140f ) - -#define Q_rint(in) ((vec_t)floor(in+0.5)) - -qboolean VectorCompare (const vec3_t v1, const vec3_t v2); - -qboolean VectorIsOnAxis(vec3_t v); -qboolean VectorIsOnAxialPlane(vec3_t v); - -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); -// I need this define in order to test some of the regression tests from time to time. -// This define affect the precision of VectorNormalize() function only. -#define MATHLIB_VECTOR_NORMALIZE_PRECISION_FIX 1 -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); -/*! m4_det */ -float m4_det( m4x4_t mr ); -/*! 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); - - - -//////////////////////////////////////////////////////////////////////////////// -// Below is double-precision math stuff. This was initially needed by the new -// "base winding" code in q3map2 brush processing in order to fix the famous -// "disappearing triangles" issue. These definitions can be used wherever extra -// precision is needed. -//////////////////////////////////////////////////////////////////////////////// - -typedef double vec_accu_t; -typedef vec_accu_t vec3_accu_t[3]; - -// Smallest positive value for vec_accu_t such that 1.0 + VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE != 1.0. -// In the case of 64 bit doubles (which is almost certainly the case), it's 0.00000000000000022204. -// Don't forget that your epsilons should depend on the possible range of values, -// because for example adding VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE to 1024.0 will have no effect. -#define VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE DBL_EPSILON - -vec_accu_t VectorLengthAccu(const vec3_accu_t v); - -// I have a feeling it may be safer to break these #define functions out into actual functions -// in order to avoid accidental loss of precision. For example, say you call -// VectorScaleAccu(vec3_t, vec_t, vec3_accu_t). The scale would take place in 32 bit land -// and the result would be cast to 64 bit, which would cause total loss of precision when -// scaling by a large factor. -//#define DotProductAccu(x, y) ((x)[0] * (y)[0] + (x)[1] * (y)[1] + (x)[2] * (y)[2]) -//#define VectorSubtractAccu(a, b, c) ((c)[0] = (a)[0] - (b)[0], (c)[1] = (a)[1] - (b)[1], (c)[2] = (a)[2] - (b)[2]) -//#define VectorAddAccu(a, b, c) ((c)[0] = (a)[0] + (b)[0], (c)[1] = (a)[1] + (b)[1], (c)[2] = (a)[2] + (b)[2]) -//#define VectorCopyAccu(a, b) ((b)[0] = (a)[0], (b)[1] = (a)[1], (b)[2] = (a)[2]) -//#define VectorScaleAccu(a, b, c) ((c)[0] = (b) * (a)[0], (c)[1] = (b) * (a)[1], (c)[2] = (b) * (a)[2]) -//#define CrossProductAccu(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 Q_rintAccu(in) ((vec_accu_t) floor(in + 0.5)) - -vec_accu_t DotProductAccu(const vec3_accu_t a, const vec3_accu_t b); -void VectorSubtractAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); -void VectorAddAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); -void VectorCopyAccu(const vec3_accu_t in, vec3_accu_t out); -void VectorScaleAccu(const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out); -void CrossProductAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); -vec_accu_t Q_rintAccu(vec_accu_t val); - -void VectorCopyAccuToRegular(const vec3_accu_t in, vec3_t out); -void VectorCopyRegularToAccu(const vec3_t in, vec3_accu_t out); -vec_accu_t VectorNormalizeAccu(const vec3_accu_t in, vec3_accu_t out); - -#ifdef __cplusplus -} -#endif - -#endif /* __MATHLIB__ */ diff --git a/misc/mediasource/extra/netradiant-src/libs/mathlib/bbox.c b/misc/mediasource/extra/netradiant-src/libs/mathlib/bbox.c deleted file mode 100644 index e8dc8657..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/mathlib/bbox.c +++ /dev/null @@ -1,462 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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; iorigin[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/misc/mediasource/extra/netradiant-src/libs/mathlib/line.c b/misc/mediasource/extra/netradiant-src/libs/mathlib/line.c deleted file mode 100644 index 41b868fb..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/mathlib/line.c +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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/misc/mediasource/extra/netradiant-src/libs/mathlib/m4x4.c b/misc/mediasource/extra/netradiant-src/libs/mathlib/m4x4.c deleted file mode 100644 index 3b114610..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/mathlib/m4x4.c +++ /dev/null @@ -1,1878 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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= 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; - else - continue; - - for ( tj = 0; tj < 4; tj++ ) - { - if ( tj < j ) - jdst = tj; - else if ( tj > j ) - jdst = tj-1; - else - continue; - - 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 scale[r]) - { - scale[r] = (float)fabs(*p); - } - } - } - - for (c=0; c 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=0; r--) - { - f = aug[indx[r]]; - p = matrix + (indx[r]*N); - for(c=(r+1); c=0;i--) - { - temp = b[i]; - for(j=(i+1);j - -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, }; - -/* -================ -VectorIsOnAxis -================ -*/ -qboolean VectorIsOnAxis(vec3_t v) -{ - int i, zeroComponentCount; - - zeroComponentCount = 0; - for (i = 0; i < 3; i++) - { - if (v[i] == 0.0) - { - zeroComponentCount++; - } - } - - if (zeroComponentCount > 1) - { - // The zero vector will be on axis. - return qtrue; - } - - return qfalse; -} - -/* -================ -VectorIsOnAxialPlane -================ -*/ -qboolean VectorIsOnAxialPlane(vec3_t v) -{ - int i; - - for (i = 0; i < 3; i++) - { - if (v[i] == 0.0) - { - // The zero vector will be on axial plane. - return qtrue; - } - } - - return qfalse; -} - -/* -================ -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 ) { - -#if MATHLIB_VECTOR_NORMALIZE_PRECISION_FIX - - // The sqrt() function takes double as an input and returns double as an - // output according the the man pages on Debian and on FreeBSD. Therefore, - // I don't see a reason why using a double outright (instead of using the - // vec_accu_t alias for example) could possibly be frowned upon. - - double x, y, z, length; - - x = (double) in[0]; - y = (double) in[1]; - z = (double) in[2]; - - length = sqrt((x * x) + (y * y) + (z * z)); - if (length == 0) - { - VectorClear (out); - return 0; - } - - out[0] = (vec_t) (x / length); - out[1] = (vec_t) (y / length); - out[2] = (vec_t) (z / length); - - return (vec_t) length; - -#else - - 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; - -#endif - -} - -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 -#define INVALID_BOUNDS 99999 -void ClearBounds (vec3_t mins, vec3_t maxs) -{ - mins[0] = mins[1] = mins[2] = +INVALID_BOUNDS; - maxs[0] = maxs[1] = maxs[2] = -INVALID_BOUNDS; -} - -void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs) -{ - int i; - vec_t val; - - if(mins[0] == +INVALID_BOUNDS) - if(maxs[0] == -INVALID_BOUNDS) - { - VectorCopy(v, mins); - VectorCopy(v, maxs); - } - - 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]; - } -} - - -//////////////////////////////////////////////////////////////////////////////// -// Below is double-precision math stuff. This was initially needed by the new -// "base winding" code in q3map2 brush processing in order to fix the famous -// "disappearing triangles" issue. These definitions can be used wherever extra -// precision is needed. -//////////////////////////////////////////////////////////////////////////////// - -/* -================= -VectorLengthAccu -================= -*/ -vec_accu_t VectorLengthAccu(const vec3_accu_t v) -{ - return (vec_accu_t) sqrt((v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2])); -} - -/* -================= -DotProductAccu -================= -*/ -vec_accu_t DotProductAccu(const vec3_accu_t a, const vec3_accu_t b) -{ - return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]); -} - -/* -================= -VectorSubtractAccu -================= -*/ -void VectorSubtractAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) -{ - out[0] = a[0] - b[0]; - out[1] = a[1] - b[1]; - out[2] = a[2] - b[2]; -} - -/* -================= -VectorAddAccu -================= -*/ -void VectorAddAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) -{ - out[0] = a[0] + b[0]; - out[1] = a[1] + b[1]; - out[2] = a[2] + b[2]; -} - -/* -================= -VectorCopyAccu -================= -*/ -void VectorCopyAccu(const vec3_accu_t in, vec3_accu_t out) -{ - out[0] = in[0]; - out[1] = in[1]; - out[2] = in[2]; -} - -/* -================= -VectorScaleAccu -================= -*/ -void VectorScaleAccu(const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out) -{ - out[0] = in[0] * scaleFactor; - out[1] = in[1] * scaleFactor; - out[2] = in[2] * scaleFactor; -} - -/* -================= -CrossProductAccu -================= -*/ -void CrossProductAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) -{ - out[0] = (a[1] * b[2]) - (a[2] * b[1]); - out[1] = (a[2] * b[0]) - (a[0] * b[2]); - out[2] = (a[0] * b[1]) - (a[1] * b[0]); -} - -/* -================= -Q_rintAccu -================= -*/ -vec_accu_t Q_rintAccu(vec_accu_t val) -{ - return (vec_accu_t) floor(val + 0.5); -} - -/* -================= -VectorCopyAccuToRegular -================= -*/ -void VectorCopyAccuToRegular(const vec3_accu_t in, vec3_t out) -{ - out[0] = (vec_t) in[0]; - out[1] = (vec_t) in[1]; - out[2] = (vec_t) in[2]; -} - -/* -================= -VectorCopyRegularToAccu -================= -*/ -void VectorCopyRegularToAccu(const vec3_t in, vec3_accu_t out) -{ - out[0] = (vec_accu_t) in[0]; - out[1] = (vec_accu_t) in[1]; - out[2] = (vec_accu_t) in[2]; -} - -/* -================= -VectorNormalizeAccu -================= -*/ -vec_accu_t VectorNormalizeAccu(const vec3_accu_t in, vec3_accu_t out) -{ - // The sqrt() function takes double as an input and returns double as an - // output according the the man pages on Debian and on FreeBSD. Therefore, - // I don't see a reason why using a double outright (instead of using the - // vec_accu_t alias for example) could possibly be frowned upon. - - vec_accu_t length; - - length = (vec_accu_t) sqrt((in[0] * in[0]) + (in[1] * in[1]) + (in[2] * in[2])); - if (length == 0) - { - VectorClear(out); - return 0; - } - - out[0] = in[0] / length; - out[1] = in[1] / length; - out[2] = in[2] / length; - - return length; -} - - diff --git a/misc/mediasource/extra/netradiant-src/libs/mathlib/ray.c b/misc/mediasource/extra/netradiant-src/libs/mathlib/ray.c deleted file mode 100644 index bea7c5c5..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/mathlib/ray.c +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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/misc/mediasource/extra/netradiant-src/libs/md5lib.h b/misc/mediasource/extra/netradiant-src/libs/md5lib.h deleted file mode 100644 index f0aca115..00000000 --- a/misc/mediasource/extra/netradiant-src/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/misc/mediasource/extra/netradiant-src/libs/md5lib/md5lib.c b/misc/mediasource/extra/netradiant-src/libs/md5lib/md5lib.c deleted file mode 100644 index 60b45148..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/md5lib/md5lib.c +++ /dev/null @@ -1,395 +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/misc/mediasource/extra/netradiant-src/libs/memory/allocator.cpp b/misc/mediasource/extra/netradiant-src/libs/memory/allocator.cpp deleted file mode 100644 index 17fbdaca..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/memory/allocator.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "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/misc/mediasource/extra/netradiant-src/libs/memory/allocator.h b/misc/mediasource/extra/netradiant-src/libs/memory/allocator.h deleted file mode 100644 index c513d708..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/memory/allocator.h +++ /dev/null @@ -1,336 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/moduleobservers.cpp b/misc/mediasource/extra/netradiant-src/libs/moduleobservers.cpp deleted file mode 100644 index a2d51f7d..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/moduleobservers.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "moduleobservers.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/moduleobservers.h b/misc/mediasource/extra/netradiant-src/libs/moduleobservers.h deleted file mode 100644 index cd3bb1ef..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/moduleobservers.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/modulesystem/moduleregistry.cpp b/misc/mediasource/extra/netradiant-src/libs/modulesystem/moduleregistry.cpp deleted file mode 100644 index 9841f797..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/modulesystem/moduleregistry.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "moduleregistry.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/modulesystem/moduleregistry.h b/misc/mediasource/extra/netradiant-src/libs/modulesystem/moduleregistry.h deleted file mode 100644 index bd39cb06..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/modulesystem/moduleregistry.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/modulesystem/modulesmap.cpp b/misc/mediasource/extra/netradiant-src/libs/modulesystem/modulesmap.cpp deleted file mode 100644 index 4edfc701..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/modulesystem/modulesmap.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "modulesmap.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/modulesystem/modulesmap.h b/misc/mediasource/extra/netradiant-src/libs/modulesystem/modulesmap.h deleted file mode 100644 index dfc2ea45..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/modulesystem/modulesmap.h +++ /dev/null @@ -1,152 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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(const 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) const - { - 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(typename Type::Name(), typename Type::Version(), visitor); - } - else - { - StringTokeniser tokeniser(names); - for(;;) - { - const char* name = tokeniser.getToken(); - if(string_empty(name)) - { - break; - } - Module* module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); - if(module == 0) - { - globalModuleServer().setError(true); - globalErrorStream() << "ModulesRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; - break; - } - else - { - m_modules.insert(name, *module); - } - } - } - } - } - ModulesMap& get() - { - return m_modules; - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/modulesystem/singletonmodule.cpp b/misc/mediasource/extra/netradiant-src/libs/modulesystem/singletonmodule.cpp deleted file mode 100644 index 866c24fa..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/modulesystem/singletonmodule.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "singletonmodule.h" -#include "generic/constant.h" - -class NullType -{ -public: - INTEGER_CONSTANT(Version, 1); - STRING_CONSTANT(Name, ""); -}; - -class NullModule -{ -public: - typedef NullType Type; - STRING_CONSTANT(Name, ""); - void* getTable() - { - return NULL; - } -}; - -void TEST_SINGLETONMODULE() -{ - SingletonModule null; - null.capture(); - null.release(); -} diff --git a/misc/mediasource/extra/netradiant-src/libs/modulesystem/singletonmodule.h b/misc/mediasource/extra/netradiant-src/libs/modulesystem/singletonmodule.h deleted file mode 100644 index f68587b7..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/modulesystem/singletonmodule.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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 typename API::Name(); - } - - API* constructAPI(Dependencies& dependencies) - { - return new API; - } - void destroyAPI(API* api) - { - delete api; - } -}; - -template -class DependenciesAPIConstructor -{ -public: - const char* getName() - { - return typename API::Name(); - } - - 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(typename Type::Name(), typename 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: '" << typename 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: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; - } - else - { - globalOutputStream() << "Module Dependencies Failed: '" << typename 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/misc/mediasource/extra/netradiant-src/libs/os/dir.cpp b/misc/mediasource/extra/netradiant-src/libs/os/dir.cpp deleted file mode 100644 index a775e5bd..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/os/dir.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "dir.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/os/dir.h b/misc/mediasource/extra/netradiant-src/libs/os/dir.h deleted file mode 100644 index bdb385e1..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/os/dir.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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/misc/mediasource/extra/netradiant-src/libs/os/file.cpp b/misc/mediasource/extra/netradiant-src/libs/os/file.cpp deleted file mode 100644 index 766638f9..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/os/file.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "file.h" - diff --git a/misc/mediasource/extra/netradiant-src/libs/os/file.h b/misc/mediasource/extra/netradiant-src/libs/os/file.h deleted file mode 100644 index b1290760..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/os/file.h +++ /dev/null @@ -1,152 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(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 -#define access(path, mode) _access(path, mode) -#else -#include // access() -#endif - -#include // rename(), remove() -#include // stat() -#include // this is included by stat.h on win32 -#include -#include - -#include "debugging/debugging.h" - -/// \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) -{ - ASSERT_MESSAGE(from != 0 && to != 0, "file_move: invalid path"); - 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) -{ - ASSERT_MESSAGE(path != 0, "file_remove: invalid 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) -{ - ASSERT_MESSAGE(path != 0, "file_accessible: invalid path"); - 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) -{ - ASSERT_MESSAGE(path != 0, "file_is_directory: invalid 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) -{ - ASSERT_MESSAGE(path != 0, "file_size: invalid 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) -{ - ASSERT_MESSAGE(path != 0, "file_modified: invalid path"); - struct stat st; - if(stat(path, &st) == -1) - { - return c_invalidFileTime; - } - return st.st_mtime; -} - - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/os/path.cpp b/misc/mediasource/extra/netradiant-src/libs/os/path.cpp deleted file mode 100644 index ab03e1d2..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/os/path.cpp +++ /dev/null @@ -1,22 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "path.h" diff --git a/misc/mediasource/extra/netradiant-src/libs/os/path.h b/misc/mediasource/extra/netradiant-src/libs/os/path.h deleted file mode 100644 index 082b56fa..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/os/path.h +++ /dev/null @@ -1,283 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (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(POSIX) - 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/misc/mediasource/extra/netradiant-src/libs/picomodel.h b/misc/mediasource/extra/netradiant-src/libs/picomodel.h deleted file mode 100644 index 1e6f8920..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel.h +++ /dev/null @@ -1,351 +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 ]; -}; - - -/* 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 \ - const char *fileName, const void *buffer, int bufSize - -#define PM_PARAMS_LOAD \ - const char *fileName, int frameNum, const void *buffer, int bufSize - -#define PM_PARAMS_CANSAVE \ - void - -#define PM_PARAMS_SAVE \ - const 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)( const 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( const 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, const char *fileName ); - -/* 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, const char *name ); -void PicoSetModelFileName( picoModel_t *model, const 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* smoothingGroup); - -/* end marker */ -#ifdef __cplusplus -} -#endif - -#endif diff --git a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/clip.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/clip.c deleted file mode 100644 index d83ea61f..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/clip.c +++ /dev/null @@ -1,278 +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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/envelope.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/envelope.c deleted file mode 100644 index 3720a8eb..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/envelope.c +++ /dev/null @@ -1,600 +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 = NULL; - 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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/list.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/list.c deleted file mode 100644 index d337296c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/list.c +++ /dev/null @@ -1,101 +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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwio.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwio.c deleted file mode 100644 index 63e9af76..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwio.c +++ /dev/null @@ -1,442 +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( (const char *) 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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwo2.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwo2.c deleted file mode 100644 index 56c756c3..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwo2.c +++ /dev/null @@ -1,308 +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( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ) -{ - lwObject *object; - lwLayer *layer; - lwNode *node; - unsigned int id, formsize, type; - int i, rlen, 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; - } - - /* 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 <= (unsigned int) (_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( const 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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwo2.h b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwo2.h deleted file mode 100644 index e5b96115..00000000 --- a/misc/mediasource/extra/netradiant-src/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( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); -int lwValidateObject( const 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( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); -int lwValidateObject5( const 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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwob.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwob.c deleted file mode 100644 index f12e3a36..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/lwob.c +++ /dev/null @@ -1,740 +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 = NULL; - lwPlugin *shdr = NULL; - 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: - if(!tex) goto Fail; - flags = getU2( fp ); - - i = -1; - if ( flags & 1 ) i = 0; - if ( flags & 2 ) i = 1; - if ( flags & 4 ) i = 2; - if(i < 0) goto Fail; - 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: - if(!tex) goto Fail; - for ( i = 0; i < 3; i++ ) - tex->tmap.size.val[ i ] = getF4( fp ); - break; - - case ID_TCTR: - if(!tex) goto Fail; - for ( i = 0; i < 3; i++ ) - tex->tmap.center.val[ i ] = getF4( fp ); - break; - - case ID_TFAL: - if(!tex) goto Fail; - for ( i = 0; i < 3; i++ ) - tex->tmap.falloff.val[ i ] = getF4( fp ); - break; - - case ID_TVEL: - if(!tex) goto Fail; - 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) goto Fail; - if ( tex->type == ID_PROC ) - for ( i = 0; i < 3; i++ ) - tex->param.proc.value[ i ] = getU1( fp ) / 255.0f; - break; - - case ID_TVAL: - if(!tex) goto Fail; - tex->param.proc.value[ 0 ] = getI2( fp ) / 256.0f; - break; - - case ID_TAMP: - if(!tex) goto Fail; - if ( tex->type == ID_IMAP ) - tex->param.imap.amplitude.val = getF4( fp ); - break; - - case ID_TIMG: - if(!tex) goto Fail; - s = getS0( fp ); - tex->param.imap.cindex = add_clip( s, &obj->clip, &obj->nclips ); - break; - - case ID_TAAS: - if(!tex) goto Fail; - tex->param.imap.aa_strength = getF4( fp ); - tex->param.imap.aas_flags = 1; - break; - - case ID_TREF: - if(!tex) goto Fail; - tex->tmap.ref_object = getbytes( fp, sz ); - break; - - case ID_TOPC: - if(!tex) goto Fail; - tex->opacity.val = getF4( fp ); - break; - - case ID_TFP0: - if(!tex) goto Fail; - if ( tex->type == ID_IMAP ) - tex->param.imap.wrapw.val = getF4( fp ); - break; - - case ID_TFP1: - if(!tex) goto Fail; - 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: - if(!shdr) goto Fail; - 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 * ) (size_t) 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( const 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 <= (unsigned int) (_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( const 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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/pntspols.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/pntspols.c deleted file mode 100644 index 31475819..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/pntspols.c +++ /dev/null @@ -1,537 +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 = ( size_t ) 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 * ) (size_t) 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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/surface.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/surface.c deleted file mode 100644 index 6b2bbe62..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/surface.c +++ /dev/null @@ -1,1005 +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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/vecmath.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/vecmath.c deleted file mode 100644 index eaa1e8fc..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/vecmath.c +++ /dev/null @@ -1,37 +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/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/vmap.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/vmap.c deleted file mode 100644 index 69f87cf9..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/lwo/vmap.c +++ /dev/null @@ -1,243 +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/misc/mediasource/extra/netradiant-src/libs/picomodel/picointernal.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/picointernal.c deleted file mode 100644 index f08a9962..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/picointernal.c +++ /dev/null @@ -1,1356 +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 )( const 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( const 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 - */ -const char *_pico_stristr( const 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; poscursor == 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( const 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 = (const char *) buffer; - p->cursor = (const char *) 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; - const 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( const 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/misc/mediasource/extra/netradiant-src/libs/picomodel/picointernal.h b/misc/mediasource/extra/netradiant-src/libs/picomodel/picointernal.h deleted file mode 100644 index 10769e33..00000000 --- a/misc/mediasource/extra/netradiant-src/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 -{ - const char *buffer; - int bufSize; - char *token; - int tokenSize; - int tokenMax; - const char *cursor; - const char *max; - int curLine; -} -picoParser_t; - -typedef struct picoMemStream_s -{ - const picoByte_t *buffer; - int bufSize; - const 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)( const 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( const 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, ... ); -const char *_pico_stristr( const 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( const 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( const 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/misc/mediasource/extra/netradiant-src/libs/picomodel/picomodel.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/picomodel.c deleted file mode 100644 index aed467ca..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/picomodel.c +++ /dev/null @@ -1,2285 +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)( const 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, const 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( const 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, const char *fileName ) -{ - 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'; - - model = PicoModuleLoadModel(module, fileName, buffer, bufSize, frameNum); - - if(model != 0) - { - _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, const 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, const 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; - - - /* 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; - -#define THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL 1 - -void _pico_triangles_generate_weighted_normals(picoIndexIter_t first, picoIndexIter_t end, picoVec3_t* xyz, picoVec3_t* normals) -{ - for(; first != end; first += 3) - { -#if (THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL) - 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 ); - } -#endif - { - int j = 0; - for(; j < 3; ++j) - { - float* normal = normals[*(first + j)]; -#if (!THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL) - picoVec3_t weightedNormal; - { - float* a = xyz[*(first + ((j + 0) % 3))]; - float* b = xyz[*(first + ((j + 1) % 3))]; - float* c = xyz[*(first + ((j + 2) % 3))]; - picoVec3_t ba, ca; - _pico_subtract_vec( b, a, ba ); - _pico_subtract_vec( c, a, ca ); - _pico_cross_vec( ca, ba, weightedNormal ); - } -#endif - _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) - { - 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); - - _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 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 ) - { - 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 ); - } - - /* 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 = 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/misc/mediasource/extra/netradiant-src/libs/picomodel/picomodules.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/picomodules.c deleted file mode 100644 index 59a6a9ee..00000000 --- a/misc/mediasource/extra/netradiant-src/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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_3ds.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_3ds.c deleted file mode 100644 index 5ec21bf6..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_3ds.c +++ /dev/null @@ -1,775 +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; ilen)) - 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; isurface,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; isurface, (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; isurface == 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; ishader ) - { - 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 *)_pico_alloc(bufSize); - memcpy(pers.bufptr, buffer, bufSize); - 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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_ase.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_ase.c deleted file mode 100644 index 31c448e6..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_ase.c +++ /dev/null @@ -1,1190 +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. - ------------------------------------------------------------------------------ */ - - -/* 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; - - /* create pico parser */ - p = _pico_new_parser( (const 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; - picoVec3_t normal; - 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; -}; -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 void _ase_submit_triangles( picoModel_t* model , aseMaterial_t* materials , aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces ) -{ - aseFacesIter_t i = faces, end = faces + numFaces; - 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; - } - - { - picoVec3_t* xyz[3]; - picoVec3_t* normal[3]; - picoVec2_t* st[3]; - picoColor_t* color[3]; - picoIndex_t smooth[3]; - int j; - /* we pull the data from the vertex, color and texcoord arrays using the face index data */ - for ( j = 0 ; j < 3 ; j ++ ) - { - xyz[j] = &vertices[(*i).indices[j]].xyz; - normal[j] = &vertices[(*i).indices[j]].normal; - 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] = (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 ); - } - } -} - -static void shadername_convert(char* shaderName) -{ - /* unix-style path separators */ - char* s = shaderName; - for(; *s != '\0'; ++s) - { - if(*s == '\\') - { - *s = '/'; - } - } -} - - -/* _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; - - 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( (const 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); - _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)); - } - 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++; - } - /* 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"); - if (!_pico_parse_vec( p,vertices[index].normal )) - _ase_error_return("Vertex parse error"); - } - /* 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" )) - { - _pico_parse_int ( p , &faces[index].smoothingGroup ); - } - 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("Texture Vertex parse error"); - - /* get uv vertex index */ - if (!_pico_parse_int( p,&index ) || index >= numTextureVertices) - _ase_error_return("Texture vertex parse error"); - - /* get uv vertex s */ - if (!_pico_parse_float( p,&texcoords[index].texcoord[0] )) - _ase_error_return("Texture vertex parse error"); - - /* get uv vertex t */ - if (!_pico_parse_float( p,&texcoords[index].texcoord[1] )) - _ase_error_return("Texture 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; - } - /* 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 = NULL; - 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 ); - shadername_convert(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 */ - shadername_convert(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 ); - - /* extract shadername from bitmap path */ - if(mapname != NULL) - { - char* p = mapname; - - /* convert to shader-name format */ - shadername_convert(mapname); - { - /* remove extension */ - char* last_period = strrchr(p, '.'); - if(last_period != NULL) - { - *last_period = '\0'; - } - } - - /* find shader path */ - for(; *p != '\0'; ++p) - { - if(_pico_strnicmp(p, "models/", 7) == 0 || _pico_strnicmp(p, "textures/", 9) == 0) - { - 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); - _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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_fm.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_fm.c deleted file mode 100644 index 1065160e..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_fm.c +++ /dev/null @@ -1,695 +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, *bb0; - int fm_file_pos; - - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - - // 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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 - _pico_free(bb0); - 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, *bb0; - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - - // 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"); - _pico_free(bb0); - return NULL; - } - - if( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Header Version incorrect\n"); - _pico_free(bb0); - 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"); - _pico_free(bb0); - return NULL; - } - - if( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n"); - _pico_free(bb0); - 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"); - _pico_free(bb0); - return NULL; - } - - if( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM ST Version incorrect\n"); - _pico_free(bb0); - 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"); - _pico_free(bb0); - return NULL; - } - - if( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n"); - _pico_free(bb0); - 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"); - _pico_free(bb0); - return NULL; - } - - if( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) - { - _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n"); - _pico_free(bb0); - 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 ); - _pico_free(bb0); - return NULL; - } - - if( frameNum < 0 || frameNum >= fm_head->numFrames ) - { - _pico_printf( PICO_ERROR, "Invalid or out-of-range FM frame specified" ); - _pico_free(bb0); - 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, (const 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" ); - _pico_free(bb0); - 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 ); - _pico_free(bb0); - 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 ); - _pico_free(bb0); - 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; inumXYZ; 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; inumTris; 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; inumXYZ; 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; inumXYZ; 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; inumTris; 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; iverts[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; inumXYZ; 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 */ - _pico_free(bb0); - 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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_fm.h b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_fm.h deleted file mode 100644 index 3fd5148e..00000000 --- a/misc/mediasource/extra/netradiant-src/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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_lwo.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_lwo.c deleted file mode 100644 index 09cdde9c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_lwo.c +++ /dev/null @@ -1,445 +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( (const 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[ 256 ]; - 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( (const 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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_md2.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_md2.c deleted file mode 100644 index d53f7029..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_md2.c +++ /dev/null @@ -1,672 +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 ) -{ - const md2_t *md2; - - /* sanity check */ - if( (size_t) bufSize < ( sizeof( *md2 ) * 2) ) - return PICO_PMV_ERROR_SIZE; - - /* set as md2 */ - md2 = (const md2_t*) buffer; - - /* check md2 magic */ - if( *((const int*) md2->magic) != *((const 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, *bb0; - picoModel_t *picoModel; - picoSurface_t *picoSurface; - picoShader_t *picoShader; - picoVec3_t xyz, normal; - picoVec2_t st; - picoColor_t color; - - - /* set as md2 */ - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - md2 = (md2_t*) bb; - - /* check ident and version */ - if( *((const int*) md2->magic) != *((const 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 ); - _pico_free(bb0); - 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 ); - _pico_free(bb0); - return NULL; - } - - if( frameNum < 0 || frameNum >= md2->numFrames ) - { - _pico_printf( PICO_ERROR, "Invalid or out-of-range MD2 frame specified" ); - _pico_free(bb0); - 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, (const char *) (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" ); - _pico_free(bb0); - 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 ); - _pico_free(bb0); - 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 ); - _pico_free(bb0); - 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; inumXYZ; 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; inumTris; 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; inumXYZ; 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; iverts[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; inumXYZ; 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 */ - _pico_free(bb0); - 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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_md3.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_md3.c deleted file mode 100644 index b22704da..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_md3.c +++ /dev/null @@ -1,430 +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 ) -{ - const md3_t *md3; - - - /* sanity check */ - if( (size_t) bufSize < ( sizeof( *md3 ) * 2) ) - return PICO_PMV_ERROR_SIZE; - - /* set as md3 */ - md3 = (const md3_t*) buffer; - - /* check md3 magic */ - if( *((const int*) md3->magic) != *((const 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, *bb0; - 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 */ - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - md3 = (md3_t*) bb; - - /* 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) */ - _pico_free(bb0); - 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" ); - _pico_free(bb0); - return NULL; - } - - if( frameNum < 0 || frameNum >= md3->numFrames ) - { - _pico_printf( PICO_ERROR, "Invalid or out-of-range MD3 frame specified" ); - _pico_free(bb0); - 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" ); - _pico_free(bb0); - 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 */ - _pico_free(bb0); - 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 ); - _pico_free(bb0); - 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 */ - _pico_free(bb0); - 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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_mdc.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_mdc.c deleted file mode 100644 index d1243b2c..00000000 --- a/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_mdc.c +++ /dev/null @@ -1,755 +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 ) -{ - const mdc_t *mdc; - - - /* sanity check */ - if( (size_t) bufSize < ( sizeof( *mdc ) * 2) ) - return PICO_PMV_ERROR_SIZE; - - /* set as mdc */ - mdc = (const mdc_t*) buffer; - - /* check mdc magic */ - if( *((const int*) mdc->magic) != *((const 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, *bb0; - mdc_t *mdc; - mdcSurface_t *surface; - mdcShader_t *shader; - mdcTexCoord_t *texCoord; - mdcFrame_t *frame; - mdcTriangle_t *triangle; - mdcVertex_t *vertex; - mdcXyzCompressed_t *vertexComp = NULL; - short *mdcShort, *mdcCompVert = NULL; - 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 */ - bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bb, buffer, bufSize); - mdc = (mdc_t*) bb; - - /* 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) */ - _pico_free(bb0); - 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" ); - _pico_free(bb0); - return NULL; - } - - if( frameNum < 0 || frameNum >= mdc->numFrames ) - { - _pico_printf( PICO_ERROR, "Invalid or out-of-range MDC frame specified" ); - _pico_free(bb0); - 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" ); - _pico_free(bb0); - 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 */ - _pico_free(bb0); - 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 ); - _pico_free(bb0); - 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 */ - _pico_free(bb0); - 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/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_ms3d.c b/misc/mediasource/extra/netradiant-src/libs/picomodel/pm_ms3d.c deleted file mode 100644 index 8626beed..00000000 --- a/misc/mediasource/extra/netradiant-src/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 ) -{ - const TMsHeader *hdr; - - - /* sanity check */ - if ((size_t) bufSize < sizeof(TMsHeader)) - return PICO_PMV_ERROR_SIZE; - - /* get ms3d header */ - hdr = (const 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, *bufptr0; - 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 ); - - bufptr0 = bufptr = (picoByte_t*) _pico_alloc(bufSize); - memcpy(bufptr, buffer, bufSize); - /* skip header */ - bufptr += 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; ixyz[ 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; iflags = _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 ); - _pico_free(bufptr0); - 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 - - TexTool plugin for Q3Radiant - documentation -
- - -TexTool plugin for Q3Radiant
-
Introduction -

TexTool is a set of texture tools for Q3Radiant. It was designed to help fine-tuning texture placement -on brushes and patches.

-Warning: -

The plugin needs brush primitives texture coordinates to operate. If this feature is not enabled in your project -settings you'll only be able to edit patches.

-
Basic use -

It's a "drag-n-drop control points" interface. Select a single face on a brush ( with shift+ctrl+left mouse clic), -or a patch, and do Plugins > Q3 Texture Tools > Go.... You can select points and move them... if you are editing -a brush face, you can rotate the shape by clicking on an anchor point first, then dragging another point.

-
- - - - - -TexTool screenshot - -
- -

There are also a few misc keys to help you. You can - -right clic + move the mouse to change the point of view -and use - -Inser and - -Suppr to zoom in/out. - - - - - -
- -


-Appendix: keyboard shortcuts -

You can use the following keyboard shortcuts:

-

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - KEY
-
- - usage
-
ESC
-
cancel the changes and hide TexTool window
-
RETURN
-
validate changes into the editor (also resets the view)
-
INSERT
-
zoom in
-
SUPPR
-
zoom out
-
RIGHT CLIC+MOVE
-
move the view
-
LEFT CLIC+MOVE
-
grab a control point and move it
-
RIGHT CLIC
-
drop down menu
-

-

Feedback, enhancements bugs etc. to timo@qeradiant.com

-

- - - diff --git a/misc/mediasource/extra/netradiant-src/plugins/textool/StdAfx.cpp b/misc/mediasource/extra/netradiant-src/plugins/textool/StdAfx.cpp deleted file mode 100644 index 1b6e3d3c..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/textool/StdAfx.cpp +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// stdafx.cpp : source file that includes just the standard includes -// stdafx.obj will contain the pre-compiled type information - -#include "stdafx.h" - -// TODO: reference any additional headers you need in STDAFX.H -// and not in this file diff --git a/misc/mediasource/extra/netradiant-src/plugins/textool/StdAfx.h b/misc/mediasource/extra/netradiant-src/plugins/textool/StdAfx.h deleted file mode 100644 index f23eeafd..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/textool/StdAfx.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// stdafx.h -// precompiled headers - -// standard headers -#include -#include -#include -#include - -#if !defined(WIN32) - -// Necessary for proper boolean type declaration -#include "qertypes.h" - -typedef void* HMODULE; -typedef void* LPVOID; -typedef char* LPCSTR; - -#define MB_OK 0x00000000L -#define MB_OKCANCEL 0x00000001L -#define MB_ABORTRETRYIGNORE 0x00000002L -#define MB_YESNOCANCEL 0x00000003L -#define MB_YESNO 0x00000004L -#define MB_RETRYCANCEL 0x00000005L - - -#define MB_ICONHAND 0x00000010L -#define MB_ICONQUESTION 0x00000020L -#define MB_ICONEXCLAMATION 0x00000030L -#define MB_ICONASTERISK 0x00000040L - -#define MB_USERICON 0x00000080L -#define MB_ICONWARNING MB_ICONEXCLAMATION -#define MB_ICONERROR MB_ICONHAND -#define MB_ICONINFORMATION MB_ICONASTERISK -#define MB_ICONSTOP MB_ICONHAND - -#define MB_TYPEMASK 0x0000000FL -#define MB_ICONMASK 0x000000F0L -#define MB_DEFMASK 0x00000F00L -#define MB_MODEMASK 0x00003000L -#define MB_MISCMASK 0x0000C000L - -#define IDOK 1 -#define IDCANCEL 2 -#define IDABORT 3 -#define IDRETRY 4 -#define IDIGNORE 5 -#define IDYES 6 -#define IDNO 7 - -typedef struct tagRECT -{ - long left; - long top; - long right; - long bottom; -} RECT, *PRECT, *LPRECT; - -#endif // __linux__ - -// plugin -// FIXME TTimo: drop this -extern "C" void Sys_Printf (char *text, ...); - -#include "synapse.h" -#include "iplugin.h" -#include "qerplugin.h" -#include "mathlib.h" -#include "igl.h" -#include "iselectedface.h" -#include "isurfaceplugin.h" -#include "iui.h" - -// internals -// the implementation of a IWindowListener interface to use with the native UI -// TODO: move in it's own set of files? -// NOTE: I'm not too sure about the bool flags being any use.. they are supposed to tell if we handle the event or not -class CWindowListener : public IWindowListener -{ - int refCount; -public: - // Increment the number of references to this object - void IncRef () { refCount++; } - // Decrement the reference count - void DecRef () { if ( --refCount <= 0 ) delete this; } - // IWindowListener --------------------------------------- - bool OnLButtonDown(guint32 nFlags, double x, double y); - bool OnMButtonDown(guint32 nFlags, double x, double y) { return false; } - bool OnRButtonDown(guint32 nFlags, double x, double y); - bool OnLButtonUp(guint32 nFlags, double x, double y); - bool OnMButtonUp(guint32 nFlags, double x, double y) { return false; } - bool OnRButtonUp(guint32 nFlags, double x, double y); - bool OnMouseMove(guint32 nFlags, double x, double y); - bool OnKeyPressed(char *s); - bool Paint(); - void Close(); -}; - -#include "2DView.h" -typedef struct -{ - float data[MAX_POINTS_ON_WINDING][2]; -} CtrlPts_t; -#include "ControlPointsManager.h" - -extern OpenGLBinding g_QglTable; -extern _QERFuncTable_1 g_FuncTable; -// prefs globals -// NOTE: these are used by the CControlPointsManager classes, not very C++ish -extern bool g_bPrefsUpdateCameraView; -extern _QERSelectedFaceTable g_SelectedFaceTable; -extern _QERFaceData g_CancelFaceData; - -#define Sys_Printf g_FuncTable.m_pfnSysPrintf -#define Sys_FPrintf g_FuncTable.m_pfnSysFPrintf - -// call to validate the current changes into the editor -extern void Textool_Validate(); -extern void Textool_Cancel(); - -class CSynapseClientTexTool : public CSynapseClient -{ -public: - // CSynapseClient API - bool RequestAPI(APIDescriptor_t *pAPI); - const char* GetInfo(); - - CSynapseClientTexTool() { } - virtual ~CSynapseClientTexTool() { } -}; - -extern IWindow *g_pToolWnd; diff --git a/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.cpp b/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.cpp deleted file mode 100644 index 9ba7b01b..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.cpp +++ /dev/null @@ -1,962 +0,0 @@ -/* -Copyright (C) 1999-2006 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: -// main plugin implementation -// texturing tools for Radiant -// - -#include "StdAfx.h" - -static void dialog_button_callback (GtkWidget *widget, gpointer data) -{ - GtkWidget *parent; - int *loop, *ret; - - parent = gtk_widget_get_toplevel (widget); - loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); - ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); - - *loop = 0; - *ret = gpointer_to_int (data); -} - -static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - int *loop; - - gtk_widget_hide (widget); - loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); - *loop = 0; - - return TRUE; -} - -int DoMessageBox (const char* lpText, const char* lpCaption, guint32 uType) -{ - GtkWidget *window, *w, *vbox, *hbox; - int mode = (uType & MB_TYPEMASK), ret, loop = 1; - - window = gtk_window_new (GTK_WINDOW_TOPLEVEL); - gtk_signal_connect (GTK_OBJECT (window), "delete_event", - GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); - gtk_signal_connect (GTK_OBJECT (window), "destroy", - GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); - gtk_window_set_title (GTK_WINDOW (window), lpCaption); - gtk_container_border_width (GTK_CONTAINER (window), 10); - g_object_set_data (G_OBJECT (window), "loop", &loop); - g_object_set_data (G_OBJECT (window), "ret", &ret); - gtk_widget_realize (window); - - vbox = gtk_vbox_new (FALSE, 10); - gtk_container_add (GTK_CONTAINER (window), vbox); - gtk_widget_show (vbox); - - w = gtk_label_new (lpText); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); - gtk_widget_show (w); - - w = gtk_hseparator_new (); - gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); - gtk_widget_show (w); - - hbox = gtk_hbox_new (FALSE, 10); - gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); - gtk_widget_show (hbox); - - if (mode == MB_OK) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - ret = IDOK; - } - else if (mode == MB_OKCANCEL) - { - w = gtk_button_new_with_label ("Ok"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_show (w); - ret = IDCANCEL; - } - else if (mode == MB_YESNOCANCEL) - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("Cancel"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); - gtk_widget_show (w); - ret = IDCANCEL; - } - else /* if (mode == MB_YESNO) */ - { - w = gtk_button_new_with_label ("Yes"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); - GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); - gtk_widget_grab_default (w); - gtk_widget_show (w); - - w = gtk_button_new_with_label ("No"); - gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); - gtk_signal_connect (GTK_OBJECT (w), "clicked", - GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); - gtk_widget_show (w); - ret = IDNO; - } - - gtk_widget_show (window); - gtk_grab_add (window); - - while (loop) - gtk_main_iteration (); - - gtk_grab_remove (window); - gtk_widget_destroy (window); - - return ret; -} - -// Radiant function table -_QERFuncTable_1 g_FuncTable; - -// plugin name -const char *PLUGIN_NAME = "Q3 Texture Tools"; - -// commands in the menu -const char *PLUGIN_COMMANDS = "About...;Go..."; - -// cast to GtkWidget* -void *g_pMainWnd; -IWindow *g_pToolWnd = NULL; // handle to the window -CWindowListener g_Listen; - -// plugin interfaces --------------------------- -bool g_bQglInitDone = false; -OpenGLBinding g_QglTable; -bool g_bSelectedFaceInitDone = false; -_QERSelectedFaceTable g_SelectedFaceTable; -bool g_bUITable = false; -_QERUITable g_UITable; - -// selected face ------------------------------- -// we use this one to commit / read with Radiant -_QERFaceData g_SelectedFaceData; -// g_pSelectedFaceWindings gets allocated with MAX_POINTS_ON_WINDING at plugin startup ( QERPlug_Init ) -winding_t *g_pSelectedFaceWinding = NULL; -const float g_ViewportRatio = 1.2f; -// usefull class to manage the 2D view -C2DView g_2DView; -// control points to move the polygon -CControlPointsManagerBFace g_ControlPointsBFace; -// tells if a face is selected and we have something to render in the TexWindow -bool g_bTexViewReady = false; -// data for texture work -int g_NumPoints; -CtrlPts_t g_WorkWinding; -// reference _QERFaceData we use on Cancel, and for Commit -_QERFaceData g_CancelFaceData; - -// patches ------------------------------------- -bool g_bPatch = false; -//++timo we use this one to grab selected patchMesh_t -// FIXME: update when there's a real interface to read/write patches -bool g_bSurfaceTableInitDone = false; -_QERAppSurfaceTable g_SurfaceTable; -CControlPointsManagerPatch g_ControlPointsPatch; -// data for texture work -patchMesh_t* g_pPatch; -// we only use ctrl[][].st in this one -patchMesh_t g_WorkPatch; -// copy of initial g_pPatch for Cancel situation -patchMesh_t g_CancelPatch; - -// --------------------------------------------- -// holds the manager we are currently using -CControlPointsManager *g_pManager = NULL; - -// --------------------------------------------- -// globals flags for user preferences -//++timo TODO: this should be retrieved from the Editor's .INI prefs in a dedicated interface -// update camera view during manipulation ? -bool g_bPrefsUpdateCameraView = true; - -// misc ---------------------------------------- -bool g_bHelp = false; -//++timo FIXME: used to close the plugin window if InitTexView fails -// it's dirty, only use is to prevent infinite loop in DialogProc -bool g_bClosing = false; - -const char *PLUGIN_ABOUT = "Texture Tools for Radiant\n\n" - "Gtk port by Leonardo Zide (leo@lokigames.com)\n" - "Original version by Timothee \"TTimo\" Besset (timo@qeradiant.com)"; - -extern "C" void* WINAPI QERPlug_GetFuncTable () -{ - return &g_FuncTable; -} - -const char* QERPlug_Init (void* hApp, void *pWidget) -{ - int size; - GtkWidget* pMainWidget = static_cast(pWidget); - - g_pMainWnd = pMainWidget; - memset(&g_FuncTable, 0, sizeof(_QERFuncTable_1)); - g_FuncTable.m_nSize = sizeof(_QERFuncTable_1); - size = (int)((winding_t *)0)->points[MAX_POINTS_ON_WINDING]; - g_pSelectedFaceWinding = (winding_t *)malloc( size ); - memset( g_pSelectedFaceWinding, 0, size ); - return "Texture tools for Radiant"; -} - -const char* QERPlug_GetName() -{ - return (char*)PLUGIN_NAME; -} - -const char* QERPlug_GetCommandList() -{ - return PLUGIN_COMMANDS; -} - -char *TranslateString (char *buf) -{ - static char buf2[32768]; - int i, l; - char *out; - - l = strlen(buf); - out = buf2; - for (i=0 ; igetHeight(); - g_2DView.m_rect.right = hwndDlg->getWidth(); - - // we need to draw this area, now compute a bigger area so the texture scale is the same along X and Y - // compute box shape in XY space, let's say X <-> S we'll get a ratio for Y: - if (!g_bPatch) - { - g_SelectedFaceTable.m_pfnGetTextureSize( 0, TexSize ); - } - else - { - TexSize[0] = g_pPatch->d_texture->width; - TexSize[1] = g_pPatch->d_texture->height; - } - // we want a texture with the same X / Y ratio - // compute XY space / window size ratio - float SSize = (float)fabs( g_2DView.m_Maxs[0] - g_2DView.m_Mins[0] ); - float TSize = (float)fabs( g_2DView.m_Maxs[1] - g_2DView.m_Mins[1] ); - float XSize = TexSize[0] * SSize; - float YSize = TexSize[1] * TSize; - float RatioX = XSize / (float)abs( g_2DView.m_rect.left - g_2DView.m_rect.right ); - float RatioY = YSize / (float)abs( g_2DView.m_rect.top - g_2DView.m_rect.bottom ); - if ( RatioX > RatioY ) - { - YSize = (float)abs( g_2DView.m_rect.top - g_2DView.m_rect.bottom ) * RatioX; - TSize = YSize / (float)TexSize[1]; - } - else - { - XSize = (float)abs( g_2DView.m_rect.left - g_2DView.m_rect.right ) * RatioY; - SSize = XSize / (float)TexSize[0]; - } - g_2DView.m_Mins[0] = g_2DView.m_Center[0] - 0.5f * SSize; - g_2DView.m_Maxs[0] = g_2DView.m_Center[0] + 0.5f * SSize; - g_2DView.m_Mins[1] = g_2DView.m_Center[1] - 0.5f * TSize; - g_2DView.m_Maxs[1] = g_2DView.m_Center[1] + 0.5f * TSize; -} - -// call this one each time we need to re-init -//++timo TODO: re-init objects state, g_2DView and g_ControlPointsManager -void InitTexView( IWindow* hwndDlg ) -{ - // size of the texture we are working on - int TexSize[2]; - g_bTexViewReady = false; - if (g_SelectedFaceTable.m_pfnGetSelectedFaceCount() != 0) - { - g_SelectedFaceTable.m_pfnGetFaceInfo( 0, &g_SelectedFaceData, g_pSelectedFaceWinding ); - g_bPatch = false; - int i; - // we have something selected - // setup: compute BBox for the winding ( in ST space ) - //++timo FIXME: move this in a C2DView member ? used as well for patches - g_2DView.m_Mins[0] = +9999.0f; g_2DView.m_Mins[1] = +9999.0f; - g_2DView.m_Maxs[0] = -9999.0f; g_2DView.m_Maxs[1] = -9999.0f; - for ( i=0; inumpoints; i++ ) - { - if ( g_pSelectedFaceWinding->points[i][3] < g_2DView.m_Mins[0] ) - g_2DView.m_Mins[0] = g_pSelectedFaceWinding->points[i][3]; - if ( g_pSelectedFaceWinding->points[i][3] > g_2DView.m_Maxs[0] ) - g_2DView.m_Maxs[0] = g_pSelectedFaceWinding->points[i][3]; - if ( g_pSelectedFaceWinding->points[i][4] < g_2DView.m_Mins[1] ) - g_2DView.m_Mins[1] = g_pSelectedFaceWinding->points[i][4]; - if ( g_pSelectedFaceWinding->points[i][4] > g_2DView.m_Maxs[1] ) - g_2DView.m_Maxs[1] = g_pSelectedFaceWinding->points[i][4]; - } - // NOTE: FitView will read and init TexSize - FitView( hwndDlg, TexSize ); - // now init the work tables - g_NumPoints = g_pSelectedFaceWinding->numpoints; - for ( i=0; ipoints[i][3]; - g_WorkWinding.data[i][1] = g_pSelectedFaceWinding->points[i][4]; - } - g_ControlPointsBFace.Init( g_NumPoints, &g_WorkWinding, &g_2DView, TexSize, &g_SelectedFaceData, &g_QglTable ); - // init snap-to-grid - float fTexStep[2]; - fTexStep[0] = 1.0f / float(TexSize[0]); - fTexStep[1] = 1.0f / float(TexSize[1]); - g_2DView.SetGrid( fTexStep[0], fTexStep[1] ); - g_pManager = &g_ControlPointsBFace; - // prepare the "Cancel" data - memcpy( &g_CancelFaceData, &g_SelectedFaceData, sizeof(_QERFaceData) ); - // we are done - g_bTexViewReady = true; - } - else if ( g_SurfaceTable.m_pfnAnyPatchesSelected()) - { - g_pPatch = g_SurfaceTable.m_pfnGetSelectedPatch(); - g_bPatch = true; - int i,j; - // compute BBox for all patch points - g_2DView.m_Mins[0] = +9999.0f; g_2DView.m_Mins[1] = +9999.0f; - g_2DView.m_Maxs[0] = -9999.0f; g_2DView.m_Maxs[1] = -9999.0f; - for ( i=0; iwidth; i++ ) - { - for ( j=0; jheight; j++ ) - { - if ( g_pPatch->ctrl[i][j].st[0] < g_2DView.m_Mins[0] ) - g_2DView.m_Mins[0] = g_pPatch->ctrl[i][j].st[0]; - if ( g_pPatch->ctrl[i][j].st[0] > g_2DView.m_Maxs[0] ) - g_2DView.m_Maxs[0] = g_pPatch->ctrl[i][j].st[0]; - if ( g_pPatch->ctrl[i][j].st[1] < g_2DView.m_Mins[1] ) - g_2DView.m_Mins[1] = g_pPatch->ctrl[i][j].st[1]; - if ( g_pPatch->ctrl[i][j].st[1] > g_2DView.m_Maxs[1] ) - g_2DView.m_Maxs[1] = g_pPatch->ctrl[i][j].st[1]; - } - } - FitView( hwndDlg, TexSize); - // init the work tables - g_WorkPatch = *g_pPatch; - g_ControlPointsPatch.Init( &g_WorkPatch, &g_2DView, &g_QglTable, g_pPatch ); - // init snap-to-grid - float fTexStep[2]; - fTexStep[0] = 1.0f / float(TexSize[0]); - fTexStep[1] = 1.0f / float(TexSize[1]); - g_2DView.SetGrid( fTexStep[0], fTexStep[1] ); - g_pManager = &g_ControlPointsPatch; - // prepare the "cancel" data - g_CancelPatch = *g_pPatch; - // we are done - g_bTexViewReady = true; - } -} - -void Textool_Validate() -{ - // validate current situation into the main view - g_pManager->Commit( ); - // for a brush face we have an aditionnal step - if (!g_bPatch) - { - // tell Radiant to update (will also send update windows messages ) - g_SelectedFaceTable.m_pfnSetFaceInfo( 0, &g_SelectedFaceData ); - } - else - { - // ask to rebuild the patch display data - g_pPatch->bDirty = true; - // send a repaint to the camera window as well - g_FuncTable.m_pfnSysUpdateWindows( W_CAMERA ); - } - // we'll need to update after that as well: - g_bTexViewReady = false; - // send a repaint message - g_pToolWnd->Redraw (); -} - -void Textool_Cancel() -{ - if (!g_bPatch) - { - // tell Radiant to update (will also send update windows messages ) - g_SelectedFaceTable.m_pfnSetFaceInfo( 0, &g_CancelFaceData ); - } - else - { - *g_pPatch = g_CancelPatch; - g_pPatch->bDirty = true; - g_FuncTable.m_pfnSysUpdateWindows( W_CAMERA ); - } - // do not call destroy, decref it - g_pToolWnd->DecRef(); - g_pToolWnd = NULL; -} - -static void DoExpose () -{ - int i,j; - - g_2DView.PreparePaint(); - g_QglTable.m_pfn_qglColor3f(1, 1, 1); - // draw the texture background - g_QglTable.m_pfn_qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); - if (!g_bPatch) - { - g_QglTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, g_SelectedFaceTable.m_pfnGetTextureNumber(0) ); - } - else - { - g_QglTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, g_pPatch->d_texture->texture_number ); - } - - g_QglTable.m_pfn_qglEnable( GL_TEXTURE_2D ); - g_QglTable.m_pfn_qglBegin( GL_QUADS ); - g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Mins[0], g_2DView.m_Mins[1] ); - g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Mins[0], g_2DView.m_Mins[1] ); - g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Maxs[0], g_2DView.m_Mins[1] ); - g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Maxs[0], g_2DView.m_Mins[1] ); - g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Maxs[0], g_2DView.m_Maxs[1] ); - g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Maxs[0], g_2DView.m_Maxs[1] ); - g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Mins[0], g_2DView.m_Maxs[1] ); - g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Mins[0], g_2DView.m_Maxs[1] ); - g_QglTable.m_pfn_qglEnd(); - g_QglTable.m_pfn_qglDisable( GL_TEXTURE_2D ); - - if (!g_bPatch) - { - g_QglTable.m_pfn_qglBegin( GL_LINE_LOOP ); - for ( i=0; iwidth; i++ ) - for ( j=0; jheight; j++ ) - { - if ( i < g_pPatch->width-1 ) - { - g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i][j].st[0], g_WorkPatch.ctrl[i][j].st[1] ); - g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i+1][j].st[0], g_WorkPatch.ctrl[i+1][j].st[1] ); - } - - if ( j < g_pPatch->height-1 ) - { - g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i][j].st[0], g_WorkPatch.ctrl[i][j].st[1] ); - g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i][j+1].st[0], g_WorkPatch.ctrl[i][j+1].st[1] ); - } - } - g_QglTable.m_pfn_qglEnd(); - } - - // let the control points manager render - g_pManager->render( ); -} - -static bool CanProcess () -{ - if (!g_bTexViewReady && !g_bClosing) - { - InitTexView (g_pToolWnd); - - if (!g_bTexViewReady) - { - g_bClosing = true; - DoMessageBox ("You must have brush primitives activated in your project settings and\n" - "have a patch or a single face selected to use the TexTool plugin.\n" - "See plugins/TexToolHelp for documentation.", "TexTool plugin", MB_ICONERROR | MB_OK); - // decref, this will destroy - g_pToolWnd->DecRef(); - g_pToolWnd = NULL; - return 0; - } - else - g_bClosing = false; - } - else if (!g_bTexViewReady && g_bClosing) - { - return 0; - } - - return 1; -} - -#if 0 -static void button_press (GtkWidget *widget, GdkEventButton *event, gpointer data) -{ - if (CanProcess ()) - { - switch (event->button) - { - case 1: - g_pManager->OnLButtonDown (event->x, event->y); break; - case 3: - g_2DView.OnRButtonDown (event->x, event->y); break; - } - } -} - -static void button_release (GtkWidget *widget, GdkEventButton *event, gpointer data) -{ - if (CanProcess ()) - { - switch (event->button) - { - case 1: - g_pManager->OnLButtonUp (event->x, event->y); break; - case 3: - g_2DView.OnRButtonUp (event->x, event->y); break; - } - } -} - -static void motion (GtkWidget *widget, GdkEventMotion *event, gpointer data) -{ - if (CanProcess ()) - { - if (g_2DView.OnMouseMove (event->x, event->y)) - return; - - if (g_pManager->OnMouseMove (event->x, event->y)) - return; - } -} - -static gint expose (GtkWidget *widget, GdkEventExpose *event, gpointer data) -{ - if (event->count > 0) - return TRUE; - - if (!CanProcess ()) - return TRUE; - - if (g_bTexViewReady) - { - g_2DView.m_rect.bottom = widget->allocation.height; - g_2DView.m_rect.right = widget->allocation.width; - - if (!g_QglTable.m_pfn_glwidget_make_current (g_pToolWidget)) - { - Sys_Printf("TexTool: glMakeCurrent failed\n"); - return TRUE; - } - - DoExpose (); - - g_QglTable.m_pfn_glwidget_swap_buffers (g_pToolWidget); - } - - return TRUE; -} - -static gint keypress (GtkWidget* widget, GdkEventKey* event, gpointer data) -{ - unsigned int code = gdk_keyval_to_upper(event->keyval); - - if (code == GDK_Escape) - { - gtk_widget_destroy (g_pToolWnd); - g_pToolWnd = NULL; - return TRUE; - } - - if (CanProcess ()) - { - if (g_2DView.OnKeyDown (code)) - return FALSE; - - if (code == GDK_Return) - { - Textool_Validate(); - return FALSE; - } - } - - return TRUE; -} - -static gint close (GtkWidget *widget, GdkEvent* event, gpointer data) -{ - gtk_widget_destroy (widget); - g_pToolWnd = NULL; - - return TRUE; -} - -static GtkWidget* CreateOpenGLWidget () -{ - g_pToolWidget = g_QglTable.m_pfn_glwidget_new (FALSE, g_QglTable.m_pfn_GetQeglobalsGLWidget ()); - - gtk_widget_set_events (g_pToolWidget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_KEY_PRESS_MASK | - GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK); - - // Connect signal handlers - gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "expose_event", GTK_SIGNAL_FUNC (expose), NULL); - gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "motion_notify_event", - GTK_SIGNAL_FUNC (motion), NULL); - gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "button_press_event", - GTK_SIGNAL_FUNC (button_press), NULL); - gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "button_release_event", - GTK_SIGNAL_FUNC (button_release), NULL); - - gtk_signal_connect (GTK_OBJECT (g_pToolWnd), "delete_event", GTK_SIGNAL_FUNC (close), NULL); - gtk_signal_connect (GTK_OBJECT (g_pToolWnd), "key_press_event", - GTK_SIGNAL_FUNC (keypress), NULL); - - return g_pToolWidget; -} -#endif - -#if 0 -static void DoPaint () -{ - if (!CanProcess ()) - return; - - if (g_bTexViewReady) - { - g_2DView.m_rect.bottom = g_pToolWnd->getHeight(); - g_2DView.m_rect.right = g_pToolWnd->getWidth(); - - // set GL_PROJECTION - g_2DView.PreparePaint(); - // render the objects - // the master is not rendered the same way, draw over a unified texture background - g_2DView.TextureBackground(g_DrawObjects[0].pObject->getTextureNumber()); - if (g_nDrawObjects >= 1) - { - int i; - for (i=1;iPrepareModelView(g_DrawObjects[i].pTopo); - g_DrawObjects[i].pObject->RenderAuxiliary(); - } - } - // draw the polygon outline and control points - g_DrawObjects[0].pObject->PrepareModelView(NULL); - g_DrawObjects[0].pObject->RenderUI(); - } -} -#endif - -bool CWindowListener::OnLButtonDown(guint32 nFlags, double x, double y) -{ - if (CanProcess()) - { - g_pManager->OnLButtonDown((int)x, (int)y); - return true; - } - return false; -} - -bool CWindowListener::OnRButtonDown(guint32 nFlags, double x, double y) -{ - if (CanProcess()) - { - g_2DView.OnRButtonDown ((int)x, (int)y); - return true; - } - return false; -} - -bool CWindowListener::OnLButtonUp(guint32 nFlags, double x, double y) -{ - if (CanProcess()) - { - g_pManager->OnLButtonUp((int)x, (int)y); - return true; - } - return false; -} - -bool CWindowListener::OnRButtonUp(guint32 nFlags, double x, double y) -{ - if (CanProcess()) - { - g_2DView.OnRButtonUp ((int)x, (int)y); - return true; - } - return false; -} - -bool CWindowListener::OnMouseMove(guint32 nFlags, double x, double y) -{ - if (CanProcess ()) - { - if (g_2DView.OnMouseMove ((int)x, (int)y)) - return true; - - g_pManager->OnMouseMove((int)x, (int)y); - return true; - } - return false; -} - -// the widget is closing -void CWindowListener::Close() -{ - g_pToolWnd = NULL; -} - -bool CWindowListener::Paint() -{ - if (!CanProcess ()) - return false; - - if (g_bTexViewReady) - DoExpose(); - - return true; -} - -bool CWindowListener::OnKeyPressed(char *s) -{ - if (!strcmp(s,"Escape")) - { - Textool_Cancel(); - return TRUE; - } - if (CanProcess ()) - { - if (g_2DView.OnKeyDown (s)) - return TRUE; - - if (!strcmp(s,"Return")) - { - Textool_Validate(); - return TRUE; - } - } - return FALSE; -} - -extern "C" void QERPlug_Dispatch(const char* p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) -{ - #if 0 - // if it's the first call, perhaps we need some additional init steps - if (!g_bQglInitDone) - { - g_QglTable.m_nSize = sizeof(OpenGLBinding); - if ( g_FuncTable.m_pfnRequestInterface( QERQglTable_GUID, static_cast(&g_QglTable) ) ) - { - g_bQglInitDone = true; - } - else - { - Sys_Printf("TexTool plugin: OpenGLBinding interface request failed\n"); - return; - } - } - - if (!g_bSelectedFaceInitDone) - { - g_SelectedFaceTable.m_nSize = sizeof(_QERSelectedFaceTable); - if (g_FuncTable.m_pfnRequestInterface (QERSelectedFaceTable_GUID, - static_cast(&g_SelectedFaceTable))) - { - g_bSelectedFaceInitDone = true; - } - else - { - Sys_Printf("TexTool plugin: _QERSelectedFaceTable interface request failed\n"); - return; - } - } - - if (!g_bSurfaceTableInitDone) - { - g_SurfaceTable.m_nSize = sizeof(_QERAppSurfaceTable); - if ( g_FuncTable.m_pfnRequestInterface( QERAppSurfaceTable_GUID, static_cast(&g_SurfaceTable) ) ) - { - g_bSurfaceTableInitDone = true; - } - else - { - Sys_Printf("TexTool plugin: _QERAppSurfaceTable interface request failed\n"); - return; - } - } - - if (!g_bUITable) - { - g_UITable.m_nSize = sizeof(_QERUITable); - if ( g_FuncTable.m_pfnRequestInterface( QERUI_GUID, static_cast(&g_UITable) ) ) - { - g_bUITable = true; - } - else - { - Sys_Printf("TexTool plugin: _QERUITable interface request failed\n"); - return; - } - } - #endif - - if (!strcmp(p, "About...")) - { - DoMessageBox (PLUGIN_ABOUT, "About ...", MB_OK ); - } - else if (!strcmp(p, "Go...")) - { - if (!g_pToolWnd) - { - g_pToolWnd = g_UITable.m_pfnCreateGLWindow(); - g_pToolWnd->setSizeParm(300,300); - g_pToolWnd->setName("TexTool"); - // g_Listener is a static class, we need to bump the refCount to avoid premature release problems - g_Listen.IncRef(); - // setListener will incRef on the listener too - g_pToolWnd->setListener(&g_Listen); - if (!g_pToolWnd->Show()) - { - DoMessageBox ("Error creating texture tools window!", "TexTool plugin", MB_ICONERROR | MB_OK); - return; - } - } - - g_bTexViewReady = false; - g_bClosing = false; - } - else if (!strcmp(p, "Help...")) - { - if (!g_bHelp) - DoMessageBox ("Select a brush face (ctrl+shift+left mouse) or a patch, and hit Go...\n" - "See tutorials for more", "TexTool plugin", MB_OK ); - else - DoMessageBox ("Are you kidding me ?", "TexTool plugin", MB_OK ); - g_bHelp = true; - } -} - -// ============================================================================= -// SYNAPSE - -CSynapseServer* g_pSynapseServer = NULL; -CSynapseClientTexTool g_SynapseClient; - -extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) -{ - if (strcmp(version, SYNAPSE_VERSION)) - { - Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); - return NULL; - } - g_pSynapseServer = pServer; - g_pSynapseServer->IncRef(); - Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); - - g_SynapseClient.AddAPI(PLUGIN_MAJOR, "textool", sizeof(_QERPluginTable)); - g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(g_FuncTable), SYN_REQUIRE, &g_FuncTable); - g_SynapseClient.AddAPI(QGL_MAJOR, NULL, sizeof(g_QglTable), SYN_REQUIRE, &g_QglTable); - g_SynapseClient.AddAPI(SELECTEDFACE_MAJOR, NULL, sizeof(g_SelectedFaceTable), SYN_REQUIRE, &g_SelectedFaceTable); - - return &g_SynapseClient; -} - -bool CSynapseClientTexTool::RequestAPI(APIDescriptor_t *pAPI) -{ - if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) - { - _QERPluginTable *pTable = static_cast<_QERPluginTable*>(pAPI->mpTable); - pTable->m_pfnQERPlug_Init = QERPlug_Init; - pTable->m_pfnQERPlug_GetName = QERPlug_GetName; - pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; - pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; - return true; - } - - Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); - return false; -} - -#include "version.h" - -const char* CSynapseClientTexTool::GetInfo() -{ - return "Texture Tools plugin built " __DATE__ " " RADIANT_VERSION; -} diff --git a/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.def b/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.def deleted file mode 100644 index 95cbb273..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.def +++ /dev/null @@ -1,12 +0,0 @@ -; TexTool.def : Declares the module parameters for the DLL. - -LIBRARY "TexTool" -DESCRIPTION 'TexTool Windows Dynamic Link Library' - -EXPORTS - ; Explicit exports can go here - QERPlug_Init @1 - QERPlug_GetName @2 - QERPlug_GetCommandList @3 - QERPlug_Dispatch @4 - QERPlug_GetFuncTable @5 diff --git a/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.rc b/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.rc deleted file mode 100644 index 69d0eaf5..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/textool/TexTool.rc +++ /dev/null @@ -1,136 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// Neutral resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) -#ifdef _WIN32 -LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_DIALOG2 DIALOGEX 0, 0, 290, 206 -STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME -EXSTYLE WS_EX_TOOLWINDOW -FONT 8, "MS Sans Serif" -BEGIN -END - - -///////////////////////////////////////////////////////////////////////////// -// -// DESIGNINFO -// - -#ifdef APSTUDIO_INVOKED -GUIDELINES DESIGNINFO DISCARDABLE -BEGIN - IDD_DIALOG2, DIALOG - BEGIN - LEFTMARGIN, 7 - RIGHTMARGIN, 283 - TOPMARGIN, 7 - BOTTOMMARGIN, 199 - END -END -#endif // APSTUDIO_INVOKED - -#endif // Neutral resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Menu -// - -IDR_DROP_MENU MENU DISCARDABLE -BEGIN - POPUP "Drop" - BEGIN - MENUITEM "Validate (RETURN)", ID_DROP_VALIDATE - MENUITEM "Zoom in (INSERT)", ID_DROP_ZOOMIN - MENUITEM "Zoom out (SUPPR)", ID_DROP_ZOOMOUT - MENUITEM "Cancel (ESC)", ID_DROP_CANCEL - END -END - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// French (France) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRA) -#ifdef _WIN32 -LANGUAGE LANG_FRENCH, SUBLANG_FRENCH -#pragma code_page(1252) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // French (France) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/misc/mediasource/extra/netradiant-src/plugins/textool/changelog.txt b/misc/mediasource/extra/netradiant-src/plugins/textool/changelog.txt deleted file mode 100644 index 9d660cbc..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/textool/changelog.txt +++ /dev/null @@ -1,8 +0,0 @@ -11/19/99 -first usable version -here is the TODO-list for next release, ( most certainly a wish list ) - -- TODO: add hooks with the selected face and selected patch data. tell the plugin when selected face -or selected patch has changed. -the hooks should use a generic interface inside Radiant for "observers" -- TODO: add other usefull texturing tools, if designers come up with good ideas \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/plugins/textool/resource.h b/misc/mediasource/extra/netradiant-src/plugins/textool/resource.h deleted file mode 100644 index 85ba8d7d..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/textool/resource.h +++ /dev/null @@ -1,23 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by TexTool.rc -// -#define IDUNDO 3 -#define IDD_DIALOG 101 -#define IDD_DIALOG2 102 -#define IDR_DROP_MENU 103 -#define ID_DROP_VALIDATE 40001 -#define ID_DROP_ZOOMIN 40002 -#define ID_DROP_ZOOMOUT 40003 -#define ID_DROP_CANCEL 40004 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 104 -#define _APS_NEXT_COMMAND_VALUE 40005 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/archive.cpp b/misc/mediasource/extra/netradiant-src/plugins/vfspk3/archive.cpp deleted file mode 100644 index 9147f8f0..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/archive.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "archive.h" - -#include "idatastream.h" -#include "iarchive.h" - -#include -#include -#include - -#include "stream/filestream.h" -#include "stream/textfilestream.h" -#include "string/string.h" -#include "os/path.h" -#include "os/file.h" -#include "os/dir.h" -#include "archivelib.h" -#include "fs_path.h" - -#include "vfspk3.h" - - -class DirectoryArchive : public Archive -{ - CopiedString m_root; -public: - DirectoryArchive(const char* root) : m_root(root) - { - } - - void release() - { - delete this; - } - virtual ArchiveFile* openFile(const char* name) - { - UnixPath path(m_root.c_str()); - path.push_filename(name); - DirectoryArchiveFile* file = new DirectoryArchiveFile(name, path.c_str()); - if(!file->failed()) - { - return file; - } - file->release(); - return 0; - } - virtual ArchiveTextFile* openTextFile(const char* name) - { - UnixPath path(m_root.c_str()); - path.push_filename(name); - DirectoryArchiveTextFile* file = new DirectoryArchiveTextFile(name, path.c_str()); - if(!file->failed()) - { - return file; - } - file->release(); - return 0; - } - virtual bool containsFile(const char* name) - { - UnixPath path(m_root.c_str()); - path.push_filename(name); - return file_readable(path.c_str()); - } - virtual void forEachFile(VisitorFunc visitor, const char* root) - { - std::vector dirs; - UnixPath path(m_root.c_str()); - path.push(root); - dirs.push_back(directory_open(path.c_str())); - - while(!dirs.empty() && directory_good(dirs.back())) - { - const char* name = directory_read_and_increment(dirs.back()); - - if(name == 0) - { - directory_close(dirs.back()); - dirs.pop_back(); - path.pop(); - } - else if(!string_equal(name, ".") && !string_equal(name, "..")) - { - path.push_filename(name); - - bool is_directory = file_is_directory(path.c_str()); - - if(!is_directory) - visitor.file(path_make_relative(path.c_str(), m_root.c_str())); - - path.pop(); - - if(is_directory) - { - path.push(name); - - if(!visitor.directory(path_make_relative(path.c_str(), m_root.c_str()), dirs.size())) - dirs.push_back(directory_open(path.c_str())); - else - path.pop(); - } - } - } - } -}; - -Archive* OpenArchive(const char* name) -{ - return new DirectoryArchive(name); -} - -#if 0 - -class TestArchive -{ - class TestVisitor : public Archive::IVisitor - { - public: - virtual void visit(const char* name) - { - int bleh = 0; - } - }; -public: - void test1() - { - Archive* archive = OpenArchive("d:/quake/id1/"); - ArchiveFile* file = archive->openFile("quake101.wad"); - if(file != 0) - { - char buffer[1024]; - file->getInputStream().read(buffer, 1024); - file->release(); - } - TestVisitor visitor; - archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 0), ""); - archive->release(); - } - void test2() - { - Archive* archive = OpenArchive("d:/gtkradiant_root/baseq3/"); - TestVisitor visitor; - archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 2), ""); - archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFiles, 1), "textures"); - archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eDirectories, 1), "textures"); - archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 1), "textures"); - archive->release(); - } - TestArchive() - { - test1(); - test2(); - } -}; - -TestArchive g_test; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/archive.h b/misc/mediasource/extra/netradiant-src/plugins/vfspk3/archive.h deleted file mode 100644 index 09874c37..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/archive.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ARCHIVE_H) -#define INCLUDED_ARCHIVE_H - -#include "iarchive.h" - -const _QERArchiveTable* GetArchiveTable(ArchiveModules& archiveModules, const char* type); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfs.cpp b/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfs.cpp deleted file mode 100644 index b47942ba..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfs.cpp +++ /dev/null @@ -1,742 +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 "vfs.h" - -#include -#include -#include -#include -#include - -#include "qerplugin.h" -#include "idatastream.h" -#include "iarchive.h" -ArchiveModules& FileSystemQ3API_getArchiveModules(); -#include "ifilesystem.h" - -#include "generic/callback.h" -#include "string/string.h" -#include "stream/stringstream.h" -#include "os/path.h" -#include "moduleobservers.h" - - -#define VFS_MAXDIRS 64 - -#if defined(WIN32) -#define PATH_MAX 260 -#endif - -#define gamemode_get GlobalRadiant().getGameMode - - - -// ============================================================================= -// Global variables - -Archive* OpenArchive(const char* name); - -struct archive_entry_t -{ - CopiedString name; - Archive* archive; - bool is_pakfile; -}; - -#include - -typedef std::list archives_t; - -static archives_t g_archives; -static char g_strDirs[VFS_MAXDIRS][PATH_MAX+1]; -static int g_numDirs; -static char g_strForbiddenDirs[VFS_MAXDIRS][PATH_MAX+1]; -static int g_numForbiddenDirs = 0; -static bool g_bUsePak = true; - -ModuleObservers g_observers; - -// ============================================================================= -// Static functions - -static void AddSlash (char *str) -{ - std::size_t n = strlen (str); - if (n > 0) - { - if (str[n-1] != '\\' && str[n-1] != '/') - { - globalErrorStream() << "WARNING: directory path does not end with separator: " << str << "\n"; - strcat (str, "/"); - } - } -} - -static void FixDOSName (char *src) -{ - if (src == 0 || strchr(src, '\\') == 0) - return; - - globalErrorStream() << "WARNING: invalid path separator '\\': " << src << "\n"; - - while (*src) - { - if (*src == '\\') - *src = '/'; - src++; - } -} - - - -const _QERArchiveTable* GetArchiveTable(ArchiveModules& archiveModules, const char* ext) -{ - StringOutputStream tmp(16); - tmp << LowerCase(ext); - return archiveModules.findModule(tmp.c_str()); -} -static void InitPakFile (ArchiveModules& archiveModules, const char *filename) -{ - const _QERArchiveTable* table = GetArchiveTable(archiveModules, path_get_extension(filename)); - - if(table != 0) - { - archive_entry_t entry; - entry.name = filename; - - entry.archive = table->m_pfnOpenArchive(filename); - entry.is_pakfile = true; - g_archives.push_back(entry); - globalOutputStream() << " pak file: " << filename << "\n"; - } -} - -inline void pathlist_prepend_unique(GSList*& pathlist, char* path) -{ - if(g_slist_find_custom(pathlist, path, (GCompareFunc)path_compare) == 0) - { - pathlist = g_slist_prepend(pathlist, path); - } - else - { - g_free(path); - } -} - -class DirectoryListVisitor : public Archive::Visitor -{ - GSList*& m_matches; - const char* m_directory; -public: - DirectoryListVisitor(GSList*& matches, const char* directory) - : m_matches(matches), m_directory(directory) - {} - void visit(const char* name) - { - const char* subname = path_make_relative(name, m_directory); - if(subname != name) - { - if(subname[0] == '/') - ++subname; - char* dir = g_strdup(subname); - char* last_char = dir + strlen(dir); - if(last_char != dir && *(--last_char) == '/') - *last_char = '\0'; - pathlist_prepend_unique(m_matches, dir); - } - } -}; - -class FileListVisitor : public Archive::Visitor -{ - GSList*& m_matches; - const char* m_directory; - const char* m_extension; -public: - FileListVisitor(GSList*& matches, const char* directory, const char* extension) - : m_matches(matches), m_directory(directory), m_extension(extension) - {} - void visit(const char* name) - { - const char* subname = path_make_relative(name, m_directory); - if(subname != name) - { - if(subname[0] == '/') - ++subname; - if(m_extension[0] == '*' || extension_equal(path_get_extension(subname), m_extension)) - pathlist_prepend_unique(m_matches, g_strdup (subname)); - } - } -}; - -static GSList* GetListInternal (const char *refdir, const char *ext, bool directories, std::size_t depth) -{ - GSList* files = 0; - - ASSERT_MESSAGE(refdir[strlen(refdir) - 1] == '/', "search path does not end in '/'"); - - if(directories) - { - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - DirectoryListVisitor visitor(files, refdir); - (*i).archive->forEachFile(Archive::VisitorFunc(visitor, Archive::eDirectories, depth), refdir); - } - } - else - { - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - FileListVisitor visitor(files, refdir, ext); - (*i).archive->forEachFile(Archive::VisitorFunc(visitor, Archive::eFiles, depth), refdir); - } - } - - files = g_slist_reverse(files); - - return files; -} - -inline int ascii_to_upper(int c) -{ - if (c >= 'a' && c <= 'z') - { - return c - ('a' - 'A'); - } - return c; -} - -/*! -This behaves identically to stricmp(a,b), except that ASCII chars -[\]^`_ come AFTER alphabet chars instead of before. This is because -it converts all alphabet chars to uppercase before comparison, -while stricmp converts them to lowercase. -*/ -static int string_compare_nocase_upper(const char* a, const char* b) -{ - for(;;) - { - int c1 = ascii_to_upper(*a++); - int c2 = ascii_to_upper(*b++); - - if (c1 < c2) - { - return -1; // a < b - } - if (c1 > c2) - { - return 1; // a > b - } - if(c1 == 0) - { - return 0; // a == b - } - } -} - -// Arnout: note - sort pakfiles in reverse order. This ensures that -// later pakfiles override earlier ones. This because the vfs module -// returns a filehandle to the first file it can find (while it should -// return the filehandle to the file in the most overriding pakfile, the -// last one in the list that is). - -//!\todo Analyse the code in rtcw/q3 to see which order it sorts pak files. -class PakLess -{ -public: - bool operator()(const CopiedString& self, const CopiedString& other) const - { - return string_compare_nocase_upper(self.c_str(), other.c_str()) > 0; - } -}; - -typedef std::set Archives; - -// ============================================================================= -// Global functions - -// reads all pak files from a dir -void InitDirectory(const char* directory, ArchiveModules& archiveModules) -{ - int j; - - g_numForbiddenDirs = 0; - StringTokeniser st(GlobalRadiant().getGameDescriptionKeyValue("forbidden_paths"), " "); - for(j = 0; j < VFS_MAXDIRS; ++j) - { - const char *t = st.getToken(); - if(string_empty(t)) - break; - strncpy(g_strForbiddenDirs[g_numForbiddenDirs], t, PATH_MAX); - g_strForbiddenDirs[g_numForbiddenDirs][PATH_MAX] = '\0'; - ++g_numForbiddenDirs; - } - - for(j = 0; j < g_numForbiddenDirs; ++j) - { - if(!string_compare_nocase_upper(directory, g_strForbiddenDirs[j]) - || (string_length(directory) > string_length(g_strForbiddenDirs[j]) && directory[string_length(directory) - string_length(g_strForbiddenDirs[j]) - 1] == '/' && !string_compare_nocase_upper(directory + string_length(directory) - string_length(g_strForbiddenDirs[j]), g_strForbiddenDirs[j]))) - break; - } - if(j < g_numForbiddenDirs) - { - printf("Directory %s matched by forbidden dirs, removed\n", directory); - return; - } - - if (g_numDirs == VFS_MAXDIRS) - return; - - strncpy(g_strDirs[g_numDirs], directory, PATH_MAX); - g_strDirs[g_numDirs][PATH_MAX] = '\0'; - FixDOSName (g_strDirs[g_numDirs]); - AddSlash (g_strDirs[g_numDirs]); - - const char* path = g_strDirs[g_numDirs]; - - g_numDirs++; - - { - archive_entry_t entry; - entry.name = path; - entry.archive = OpenArchive(path); - entry.is_pakfile = false; - g_archives.push_back(entry); - } - - if (g_bUsePak) - { - GDir* dir = g_dir_open (path, 0, 0); - - if (dir != 0) - { - globalOutputStream() << "vfs directory: " << path << "\n"; - - const char* ignore_prefix = ""; - const char* override_prefix = ""; - - { - // See if we are in "sp" or "mp" mapping mode - const char* gamemode = gamemode_get(); - - if (strcmp (gamemode, "sp") == 0) - { - ignore_prefix = "mp_"; - override_prefix = "sp_"; - } - else if (strcmp (gamemode, "mp") == 0) - { - ignore_prefix = "sp_"; - override_prefix = "mp_"; - } - } - - Archives archives; - Archives archivesOverride; - for(;;) - { - const char* name = g_dir_read_name(dir); - if(name == 0) - break; - - for(j = 0; j < g_numForbiddenDirs; ++j) - if(!string_compare_nocase_upper(name, g_strForbiddenDirs[j])) - break; - if(j < g_numForbiddenDirs) - continue; - - const char *ext = strrchr (name, '.'); - - if(ext && !string_compare_nocase_upper(ext, ".pk3dir")) - { - if (g_numDirs == VFS_MAXDIRS) - continue; - snprintf(g_strDirs[g_numDirs], PATH_MAX, "%s%s/", path, name); - g_strDirs[g_numDirs][PATH_MAX] = '\0'; - FixDOSName (g_strDirs[g_numDirs]); - AddSlash (g_strDirs[g_numDirs]); - g_numDirs++; - - { - archive_entry_t entry; - entry.name = g_strDirs[g_numDirs-1]; - entry.archive = OpenArchive(g_strDirs[g_numDirs-1]); - entry.is_pakfile = false; - g_archives.push_back(entry); - } - } - - if ((ext == 0) || *(++ext) == '\0' || GetArchiveTable(archiveModules, ext) == 0) - continue; - - // using the same kludge as in engine to ensure consistency - if(!string_empty(ignore_prefix) && strncmp(name, ignore_prefix, strlen(ignore_prefix)) == 0) - { - continue; - } - if(!string_empty(override_prefix) && strncmp(name, override_prefix, strlen(override_prefix)) == 0) - { - archivesOverride.insert(name); - continue; - } - - archives.insert(name); - } - - g_dir_close (dir); - - // add the entries to the vfs - for(Archives::iterator i = archivesOverride.begin(); i != archivesOverride.end(); ++i) - { - char filename[PATH_MAX]; - strcpy(filename, path); - strcat(filename, (*i).c_str()); - InitPakFile(archiveModules, filename); - } - for(Archives::iterator i = archives.begin(); i != archives.end(); ++i) - { - char filename[PATH_MAX]; - strcpy(filename, path); - strcat(filename, (*i).c_str()); - InitPakFile(archiveModules, filename); - } - } - else - { - globalErrorStream() << "vfs directory not found: " << path << "\n"; - } - } -} - -// frees all memory that we allocated -// FIXME TTimo this should be improved so that we can shutdown and restart the VFS without exiting Radiant? -// (for instance when modifying the project settings) -void Shutdown() -{ - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - (*i).archive->release(); - } - g_archives.clear(); - - g_numDirs = 0; - g_numForbiddenDirs = 0; -} - -#define VFS_SEARCH_PAK 0x1 -#define VFS_SEARCH_DIR 0x2 - -int GetFileCount (const char *filename, int flag) -{ - int count = 0; - char fixed[PATH_MAX+1]; - - strncpy(fixed, filename, PATH_MAX); - fixed[PATH_MAX] = '\0'; - FixDOSName (fixed); - - if(!flag) - flag = VFS_SEARCH_PAK | VFS_SEARCH_DIR; - - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - if((*i).is_pakfile && (flag & VFS_SEARCH_PAK) != 0 - || !(*i).is_pakfile && (flag & VFS_SEARCH_DIR) != 0) - { - if((*i).archive->containsFile(fixed)) - ++count; - } - } - - return count; -} - -ArchiveFile* OpenFile(const char* filename) -{ - ASSERT_MESSAGE(strchr(filename, '\\') == 0, "path contains invalid separator '\\': \"" << filename << "\""); - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - ArchiveFile* file = (*i).archive->openFile(filename); - if(file != 0) - { - return file; - } - } - - return 0; -} - -ArchiveTextFile* OpenTextFile(const char* filename) -{ - ASSERT_MESSAGE(strchr(filename, '\\') == 0, "path contains invalid separator '\\': \"" << filename << "\""); - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - ArchiveTextFile* file = (*i).archive->openTextFile(filename); - if(file != 0) - { - return file; - } - } - - return 0; -} - -// NOTE: when loading a file, you have to allocate one extra byte and set it to \0 -std::size_t LoadFile (const char *filename, void **bufferptr, int index) -{ - char fixed[PATH_MAX+1]; - - strncpy (fixed, filename, PATH_MAX); - fixed[PATH_MAX] = '\0'; - FixDOSName (fixed); - - ArchiveFile* file = OpenFile(fixed); - - if(file != 0) - { - *bufferptr = malloc (file->size()+1); - // we need to end the buffer with a 0 - ((char*) (*bufferptr))[file->size()] = 0; - - std::size_t length = file->getInputStream().read((InputStream::byte_type*)*bufferptr, file->size()); - file->release(); - return length; - } - - *bufferptr = 0; - return 0; -} - -void FreeFile (void *p) -{ - free(p); -} - -GSList* GetFileList (const char *dir, const char *ext, std::size_t depth) -{ - return GetListInternal (dir, ext, false, depth); -} - -GSList* GetDirList (const char *dir, std::size_t depth) -{ - return GetListInternal (dir, 0, true, depth); -} - -void ClearFileDirList (GSList **lst) -{ - while (*lst) - { - g_free ((*lst)->data); - *lst = g_slist_remove (*lst, (*lst)->data); - } -} - -const char* FindFile(const char* relative) -{ - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - if((*i).archive->containsFile(relative)) - { - return (*i).name.c_str(); - } - } - - return ""; -} - -const char* FindPath(const char* absolute) -{ - const char *best = ""; - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - if(string_length((*i).name.c_str()) > string_length(best)) - if(path_equal_n(absolute, (*i).name.c_str(), string_length((*i).name.c_str()))) - best = (*i).name.c_str(); - } - - return best; -} - - -class Quake3FileSystem : public VirtualFileSystem -{ -public: - void initDirectory(const char *path) - { - InitDirectory(path, FileSystemQ3API_getArchiveModules()); - } - void initialise() - { - globalOutputStream() << "filesystem initialised\n"; - g_observers.realise(); - } - void shutdown() - { - g_observers.unrealise(); - globalOutputStream() << "filesystem shutdown\n"; - Shutdown(); - } - - int getFileCount(const char *filename, int flags) - { - return GetFileCount(filename, flags); - } - ArchiveFile* openFile(const char* filename) - { - return OpenFile(filename); - } - ArchiveTextFile* openTextFile(const char* filename) - { - return OpenTextFile(filename); - } - std::size_t loadFile(const char *filename, void **buffer) - { - return LoadFile(filename, buffer, 0); - } - void freeFile(void *p) - { - FreeFile(p); - } - - void forEachDirectory(const char* basedir, const FileNameCallback& callback, std::size_t depth) - { - GSList* list = GetDirList(basedir, depth); - - for(GSList* i = list; i != 0; i = g_slist_next(i)) - { - callback(reinterpret_cast((*i).data)); - } - - ClearFileDirList(&list); - } - void forEachFile(const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth) - { - GSList* list = GetFileList(basedir, extension, depth); - - for(GSList* i = list; i != 0; i = g_slist_next(i)) - { - const char* name = reinterpret_cast((*i).data); - if(extension_equal(path_get_extension(name), extension)) - { - callback(name); - } - } - - ClearFileDirList(&list); - } - GSList* getDirList(const char *basedir) - { - return GetDirList(basedir, 1); - } - GSList* getFileList(const char *basedir, const char *extension) - { - return GetFileList(basedir, extension, 1); - } - void clearFileDirList(GSList **lst) - { - ClearFileDirList(lst); - } - - const char* findFile(const char *name) - { - return FindFile(name); - } - const char* findRoot(const char *name) - { - return FindPath(name); - } - - void attach(ModuleObserver& observer) - { - g_observers.attach(observer); - } - void detach(ModuleObserver& observer) - { - g_observers.detach(observer); - } - - Archive* getArchive(const char* archiveName, bool pakonly) - { - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - if(pakonly && !(*i).is_pakfile) - continue; - - if(path_equal((*i).name.c_str(), archiveName)) - return (*i).archive; - } - return 0; - } - void forEachArchive(const ArchiveNameCallback& callback, bool pakonly, bool reverse) - { - if (reverse) - g_archives.reverse(); - - for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) - { - if(pakonly && !(*i).is_pakfile) - continue; - - callback((*i).name.c_str()); - } - - if (reverse) - g_archives.reverse(); - } -}; - -Quake3FileSystem g_Quake3FileSystem; - -void FileSystem_Init() -{ -} - -void FileSystem_Shutdown() -{ -} - -VirtualFileSystem& GetFileSystem() -{ - return g_Quake3FileSystem; -} diff --git a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfs.h b/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfs.h deleted file mode 100644 index 3fe10791..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfs.h +++ /dev/null @@ -1,39 +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. -*/ - -#if !defined(INCLUDED_VFS_H) -#define INCLUDED_VFS_H - -void FileSystem_Init(); -void FileSystem_Shutdown(); -class VirtualFileSystem; -VirtualFileSystem& GetFileSystem(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfspk3.cpp b/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfspk3.cpp deleted file mode 100644 index e7fca372..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfspk3.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "vfspk3.h" - -#include "qerplugin.h" -#include "iarchive.h" -#include "ifilesystem.h" - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/modulesmap.h" - -#include "vfs.h" - -class FileSystemDependencies : public GlobalRadiantModuleRef -{ - ArchiveModulesRef m_archive_modules; -public: - FileSystemDependencies() : - m_archive_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("archivetypes")) - { - } - ArchiveModules& getArchiveModules() - { - return m_archive_modules.get(); - } -}; - -class FileSystemQ3API -{ - VirtualFileSystem* m_filesystemq3; -public: - typedef VirtualFileSystem Type; - STRING_CONSTANT(Name, "*"); - - FileSystemQ3API() - { - FileSystem_Init(); - m_filesystemq3 = &GetFileSystem(); - } - ~FileSystemQ3API() - { - FileSystem_Shutdown(); - } - VirtualFileSystem* getTable() - { - return m_filesystemq3; - } -}; - -typedef SingletonModule FileSystemQ3Module; - -FileSystemQ3Module g_FileSystemQ3Module; - -ArchiveModules& FileSystemQ3API_getArchiveModules() -{ - return g_FileSystemQ3Module.getDependencies().getArchiveModules(); -} - - - -extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) -{ - initialiseModule(server); - - g_FileSystemQ3Module.selfRegister(); -} diff --git a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfspk3.h b/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfspk3.h deleted file mode 100644 index 8710fd13..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfspk3.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_VFSPK3_H) -#define INCLUDED_VFSPK3_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfsq3.def b/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfsq3.def deleted file mode 100644 index 885ffeb9..00000000 --- a/misc/mediasource/extra/netradiant-src/plugins/vfspk3/vfsq3.def +++ /dev/null @@ -1,7 +0,0 @@ -; vfsq3.def : Declares the module parameters for the DLL. - -LIBRARY "VFSQ3" - -EXPORTS - ; Explicit exports can go here - Radiant_RegisterModules @1 diff --git a/misc/mediasource/extra/netradiant-src/radiant/autosave.cpp b/misc/mediasource/extra/netradiant-src/radiant/autosave.cpp deleted file mode 100644 index febe95af..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/autosave.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "autosave.h" - -#include "os/file.h" -#include "os/path.h" -#include "cmdlib.h" -#include "stream/stringstream.h" -#include "gtkutil/messagebox.h" -#include "scenelib.h" -#include "mapfile.h" - -#include "map.h" -#include "mainframe.h" -#include "qe3.h" -#include "preferences.h" - - -#if defined(WIN32) -#define PATH_MAX 260 -#endif - - -bool DoesFileExist(const char* name, std::size_t& size) -{ - if(file_exists(name)) - { - size += file_size(name); - return true; - } - return false; -} - -void Map_Snapshot() -{ - // we need to do the following - // 1. make sure the snapshot directory exists (create it if it doesn't) - // 2. find out what the lastest save is based on number - // 3. inc that and save the map - const char* path = Map_Name(g_map); - const char* name = path_get_filename_start(path); - - StringOutputStream snapshotsDir(256); - snapshotsDir << StringRange(path, name) << "snapshots"; - - if(file_exists(snapshotsDir.c_str()) || Q_mkdir(snapshotsDir.c_str())) - { - std::size_t lSize = 0; - StringOutputStream strNewPath(256); - strNewPath << snapshotsDir.c_str() << '/' << name; - - StringOutputStream snapshotFilename(256); - - for(int nCount = 0; ; ++nCount) - { - // The original map's filename is "/." - // The snapshot's filename will be "/snapshots/.." - const char* end = path_get_filename_base_end(strNewPath.c_str()); - snapshotFilename << StringRange(strNewPath.c_str(), end) << '.' << nCount << end; - - if(!DoesFileExist(snapshotFilename.c_str(), lSize)) - { - break; - } - - snapshotFilename.clear(); - } - - // save in the next available slot - Map_SaveFile(snapshotFilename.c_str()); - - if (lSize > 50 * 1024 * 1024) // total size of saves > 50 mb - { - globalOutputStream() << "The snapshot files in " << snapshotsDir.c_str() << " total more than 50 megabytes. You might consider cleaning up."; - } - } - else - { - StringOutputStream strMsg(256); - strMsg << "Snapshot save failed.. unabled to create directory\n" << snapshotsDir.c_str(); - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), strMsg.c_str()); - } -} -/* -=============== -QE_CheckAutoSave - -If five minutes have passed since making a change -and the map hasn't been saved, save it out. -=============== -*/ - -bool g_AutoSave_Enabled = true; -int m_AutoSave_Frequency = 5; -bool g_SnapShots_Enabled = false; - -namespace -{ - time_t s_start = 0; - std::size_t s_changes = 0; -} - -void AutoSave_clear() -{ - s_changes = 0; -} - -scene::Node& Map_Node() -{ - return GlobalSceneGraph().root(); -} - -void QE_CheckAutoSave( void ) -{ - if(!Map_Valid(g_map) || !ScreenUpdates_Enabled()) - { - return; - } - - time_t now; - time(&now); - - if(s_start == 0 || s_changes == Node_getMapFile(Map_Node())->changes()) - { - s_start = now; - } - - if((now - s_start) > (60 * m_AutoSave_Frequency)) - { - s_start = now; - s_changes = Node_getMapFile(Map_Node())->changes(); - - if (g_AutoSave_Enabled) - { - const char* strMsg = g_SnapShots_Enabled ? "Autosaving snapshot..." : "Autosaving..."; - globalOutputStream() << strMsg << "\n"; - //Sys_Status(strMsg); - - // only snapshot if not working on a default map - if (g_SnapShots_Enabled && !Map_Unnamed(g_map)) - { - Map_Snapshot(); - } - else - { - if(Map_Unnamed(g_map)) - { - StringOutputStream autosave(256); - autosave << g_qeglobals.m_userGamePath.c_str() << "maps/"; - Q_mkdir(autosave.c_str()); - autosave << "autosave.map"; - Map_SaveFile(autosave.c_str()); - } - else - { - const char* name = Map_Name(g_map); - const char* extension = path_get_filename_base_end(name); - StringOutputStream autosave(256); - autosave << StringRange(name, extension) << ".autosave" << extension; - Map_SaveFile(autosave.c_str()); - } - } - } - else - { - globalOutputStream() << "Autosave skipped...\n"; - //Sys_Status ("Autosave skipped..."); - } - } -} - -void Autosave_constructPreferences(PreferencesPage& page) -{ - GtkWidget* autosave_enabled = page.appendCheckBox("Autosave", "Enable Autosave", g_AutoSave_Enabled); - GtkWidget* autosave_frequency = page.appendSpinner("Autosave Frequency (minutes)", m_AutoSave_Frequency, 1, 1, 60); - Widget_connectToggleDependency(autosave_frequency, autosave_enabled); - page.appendCheckBox("", "Save Snapshots", g_SnapShots_Enabled); -} -void Autosave_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Autosave", "Autosave Preferences")); - Autosave_constructPreferences(page); -} -void Autosave_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - - -#include "preferencesystem.h" -#include "stringio.h" - -void Autosave_Construct() -{ - GlobalPreferenceSystem().registerPreference("Autosave", BoolImportStringCaller(g_AutoSave_Enabled), BoolExportStringCaller(g_AutoSave_Enabled)); - GlobalPreferenceSystem().registerPreference("AutosaveMinutes", IntImportStringCaller(m_AutoSave_Frequency), IntExportStringCaller(m_AutoSave_Frequency)); - GlobalPreferenceSystem().registerPreference("Snapshots", BoolImportStringCaller(g_SnapShots_Enabled), BoolExportStringCaller(g_SnapShots_Enabled)); - - Autosave_registerPreferencesPage(); -} - -void Autosave_Destroy() -{ -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/autosave.h b/misc/mediasource/extra/netradiant-src/radiant/autosave.h deleted file mode 100644 index 730ef2e1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/autosave.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_AUTOSAVE_H) -#define INCLUDED_AUTOSAVE_H - -extern bool g_SnapShots_Enabled; - -void AutoSave_clear(); -void QE_CheckAutoSave( void ); -void Map_Snapshot(); - -void Autosave_Construct(); -void Autosave_Destroy(); - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brush.cpp b/misc/mediasource/extra/netradiant-src/radiant/brush.cpp deleted file mode 100644 index 2593ac55..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brush.cpp +++ /dev/null @@ -1,419 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "brush.h" -#include "signal/signal.h" - -Signal0 g_brushTextureChangedCallbacks; - -void Brush_addTextureChangedCallback(const SignalHandler& handler) -{ - g_brushTextureChangedCallbacks.connectLast(handler); -} - -void Brush_textureChanged() -{ - g_brushTextureChangedCallbacks(); -} - -QuantiseFunc Face::m_quantise; -EBrushType Face::m_type; -EBrushType FacePlane::m_type; -bool g_brush_texturelock_enabled = true; - -EBrushType Brush::m_type; -double Brush::m_maxWorldCoord = 0; -Shader* Brush::m_state_point; -Shader* BrushClipPlane::m_state = 0; -Shader* BrushInstance::m_state_selpoint; -Counter* BrushInstance::m_counter = 0; - -FaceInstanceSet g_SelectedFaceInstances; - - -struct SListNode -{ - SListNode* m_next; -}; - -class ProximalVertex -{ -public: - const SListNode* m_vertices; - - ProximalVertex(const SListNode* next) - : m_vertices(next) - { - } - - bool operator<(const ProximalVertex& other) const - { - if(!(operator==(other))) - { - return m_vertices < other.m_vertices; - } - return false; - } - bool operator==(const ProximalVertex& other) const - { - const SListNode* v = m_vertices; - std::size_t DEBUG_LOOP = 0; - do - { - if(v == other.m_vertices) - return true; - v = v->m_next; - //ASSERT_MESSAGE(DEBUG_LOOP < c_brush_maxFaces, "infinite loop"); - if(!(DEBUG_LOOP < c_brush_maxFaces)) - { - break; - } - ++DEBUG_LOOP; - } - while(v != m_vertices); - return false; - } -}; - -typedef Array ProximalVertexArray; -std::size_t ProximalVertexArray_index(const ProximalVertexArray& array, const ProximalVertex& vertex) -{ - return vertex.m_vertices - array.data(); -} - - - -inline bool Brush_isBounded(const Brush& brush) -{ - for(Brush::const_iterator i = brush.begin(); i != brush.end(); ++i) - { - if(!(*i)->is_bounded()) - { - return false; - } - } - return true; -} - -void Brush::buildBRep() -{ - bool degenerate = buildWindings(); - - std::size_t faces_size = 0; - std::size_t faceVerticesCount = 0; - for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - if((*i)->contributes()) - { - ++faces_size; - } - faceVerticesCount += (*i)->getWinding().numpoints; - } - - if(degenerate || faces_size < 4 || faceVerticesCount != (faceVerticesCount>>1)<<1) // sum of vertices for each face of a valid polyhedron is always even - { - m_uniqueVertexPoints.resize(0); - - vertex_clear(); - edge_clear(); - - m_edge_indices.resize(0); - m_edge_faces.resize(0); - - m_faceCentroidPoints.resize(0); - m_uniqueEdgePoints.resize(0); - m_uniqueVertexPoints.resize(0); - - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->getWinding().resize(0); - } - } - else - { - { - typedef std::vector FaceVertices; - FaceVertices faceVertices; - faceVertices.reserve(faceVerticesCount); - - { - for(std::size_t i = 0; i != m_faces.size(); ++i) - { - for(std::size_t j = 0; j < m_faces[i]->getWinding().numpoints; ++j) - { - faceVertices.push_back(FaceVertexId(i, j)); - } - } - } - - IndexBuffer uniqueEdgeIndices; - typedef VertexBuffer UniqueEdges; - UniqueEdges uniqueEdges; - - uniqueEdgeIndices.reserve(faceVertices.size()); - uniqueEdges.reserve(faceVertices.size()); - - { - ProximalVertexArray edgePairs; - edgePairs.resize(faceVertices.size()); - - { - for(std::size_t i=0; i inserter(uniqueEdges); - for(ProximalVertexArray::iterator i = edgePairs.begin(); i != edgePairs.end(); ++i) - { - uniqueEdgeIndices.insert(inserter.insert(ProximalVertex(&(*i)))); - } - } - - { - edge_clear(); - m_select_edges.reserve(uniqueEdges.size()); - for(UniqueEdges::iterator i = uniqueEdges.begin(); i != uniqueEdges.end(); ++i) - { - edge_push_back(faceVertices[ProximalVertexArray_index(edgePairs, *i)]); - } - } - - { - m_edge_faces.resize(uniqueEdges.size()); - for(std::size_t i=0; igetWinding()[faceVertex.getVertex()].adjacent); - } - } - - { - m_uniqueEdgePoints.resize(uniqueEdges.size()); - for(std::size_t i=0; igetWinding(); - Vector3 edge = vector3_mid(w[faceVertex.getVertex()].vertex, w[Winding_next(w, faceVertex.getVertex())].vertex); - m_uniqueEdgePoints[i] = pointvertex_for_windingpoint(edge, colour_vertex); - } - } - - } - - - IndexBuffer uniqueVertexIndices; - typedef VertexBuffer UniqueVertices; - UniqueVertices uniqueVertices; - - uniqueVertexIndices.reserve(faceVertices.size()); - uniqueVertices.reserve(faceVertices.size()); - - { - ProximalVertexArray vertexRings; - vertexRings.resize(faceVertices.size()); - - { - for(std::size_t i=0; i inserter(uniqueVertices); - for(ProximalVertexArray::iterator i = vertexRings.begin(); i != vertexRings.end(); ++i) - { - uniqueVertexIndices.insert(inserter.insert(ProximalVertex(&(*i)))); - } - } - - { - vertex_clear(); - m_select_vertices.reserve(uniqueVertices.size()); - for(UniqueVertices::iterator i = uniqueVertices.begin(); i != uniqueVertices.end(); ++i) - { - vertex_push_back(faceVertices[ProximalVertexArray_index(vertexRings, (*i))]); - } - } - - { - m_uniqueVertexPoints.resize(uniqueVertices.size()); - for(std::size_t i=0; igetWinding(); - m_uniqueVertexPoints[i] = pointvertex_for_windingpoint(winding[faceVertex.getVertex()].vertex, colour_vertex); - } - } - } - - if((uniqueVertices.size() + faces_size) - uniqueEdges.size() != 2) - { - globalErrorStream() << "Final B-Rep: inconsistent vertex count\n"; - } - -#if BRUSH_CONNECTIVITY_DEBUG - if((uniqueVertices.size() + faces_size) - uniqueEdges.size() != 2) - { - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - std::size_t faceIndex = std::distance(m_faces.begin(), i); - - if(!(*i)->contributes()) - { - globalOutputStream() << "face: " << Unsigned(faceIndex) << " does not contribute\n"; - } - - Winding_printConnectivity((*i)->getWinding()); - } - } -#endif - - // edge-index list for wireframe rendering - { - m_edge_indices.resize(uniqueEdgeIndices.size()); - - for(std::size_t i=0, count=0; igetWinding(); - for(std::size_t j = 0; j < winding.numpoints; ++j) - { - const RenderIndex edge_index = uniqueEdgeIndices[count+j]; - - m_edge_indices[edge_index].first = uniqueVertexIndices[count + j]; - m_edge_indices[edge_index].second = uniqueVertexIndices[count + Winding_next(winding, j)]; - } - count += winding.numpoints; - } - } - } - - { - m_faceCentroidPoints.resize(m_faces.size()); - for(std::size_t i=0; iconstruct_centroid(); - m_faceCentroidPoints[i] = pointvertex_for_windingpoint(m_faces[i]->centroid(), colour_vertex); - } - } - } -} - - -class FaceFilterWrapper : public Filter -{ - FaceFilter& m_filter; - bool m_active; - bool m_invert; -public: - FaceFilterWrapper(FaceFilter& filter, bool invert) : - m_filter(filter), - m_invert(invert) - { - } - void setActive(bool active) - { - m_active = active; - } - bool active() - { - return m_active; - } - bool filter(const Face& face) - { - return m_invert ^ m_filter.filter(face); - } -}; - - -typedef std::list FaceFilters; -FaceFilters g_faceFilters; - -void add_face_filter(FaceFilter& filter, int mask, bool invert) -{ - g_faceFilters.push_back(FaceFilterWrapper(filter, invert)); - GlobalFilterSystem().addFilter(g_faceFilters.back(), mask); -} - -bool face_filtered(Face& face) -{ - for(FaceFilters::iterator i = g_faceFilters.begin(); i != g_faceFilters.end(); ++i) - { - if((*i).active() && (*i).filter(face)) - { - return true; - } - } - return false; -} - - -class BrushFilterWrapper : public Filter -{ - bool m_active; - bool m_invert; - BrushFilter& m_filter; -public: - BrushFilterWrapper(BrushFilter& filter, bool invert) : m_invert(invert), m_filter(filter) - { - } - void setActive(bool active) - { - m_active = active; - } - bool active() - { - return m_active; - } - bool filter(const Brush& brush) - { - return m_invert ^ m_filter.filter(brush); - } -}; - - -typedef std::list BrushFilters; -BrushFilters g_brushFilters; - -void add_brush_filter(BrushFilter& filter, int mask, bool invert) -{ - g_brushFilters.push_back(BrushFilterWrapper(filter, invert)); - GlobalFilterSystem().addFilter(g_brushFilters.back(), mask); -} - -bool brush_filtered(Brush& brush) -{ - for(BrushFilters::iterator i = g_brushFilters.begin(); i != g_brushFilters.end(); ++i) - { - if((*i).active() && (*i).filter(brush)) - { - return true; - } - } - return false; -} - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/brush.h b/misc/mediasource/extra/netradiant-src/radiant/brush.h deleted file mode 100644 index 158077fd..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brush.h +++ /dev/null @@ -1,4230 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_BRUSH_H) -#define INCLUDED_BRUSH_H - -/// \file -/// \brief The brush primitive. -/// -/// A collection of planes that define a convex polyhedron. -/// The Boundary-Representation of this primitive is a manifold polygonal mesh. -/// Each face polygon is represented by a list of vertices in a \c Winding. -/// Each vertex is associated with another face that is adjacent to the edge -/// formed by itself and the next vertex in the winding. This information can -/// be used to find edge-pairs and vertex-rings. - - -#include "debugging/debugging.h" - -#include "itexdef.h" -#include "iundo.h" -#include "iselection.h" -#include "irender.h" -#include "imap.h" -#include "ibrush.h" -#include "igl.h" -#include "ifilter.h" -#include "nameable.h" -#include "moduleobserver.h" - -#include - -#include "cullable.h" -#include "renderable.h" -#include "selectable.h" -#include "editable.h" -#include "mapfile.h" - -#include "math/frustum.h" -#include "selectionlib.h" -#include "render.h" -#include "texturelib.h" -#include "container/container.h" -#include "generic/bitfield.h" -#include "signal/signalfwd.h" - -#include "winding.h" -#include "brush_primit.h" - -const unsigned int BRUSH_DETAIL_FLAG = 27; -const unsigned int BRUSH_DETAIL_MASK = (1 << BRUSH_DETAIL_FLAG); - -enum EBrushType -{ - eBrushTypeQuake, - eBrushTypeQuake2, - eBrushTypeQuake3, - eBrushTypeQuake3BP, - eBrushTypeDoom3, - eBrushTypeQuake4, - eBrushTypeHalfLife, -}; - - -#define BRUSH_CONNECTIVITY_DEBUG 0 -#define BRUSH_DEGENERATE_DEBUG 0 - -template -inline TextOuputStreamType& ostream_write(TextOuputStreamType& ostream, const Matrix4& m) -{ - return ostream << "(" << m[0] << " " << m[1] << " " << m[2] << " " << m[3] << ", " - << m[4] << " " << m[5] << " " << m[6] << " " << m[7] << ", " - << m[8] << " " << m[9] << " " << m[10] << " " << m[11] << ", " - << m[12] << " " << m[13] << " " << m[14] << " " << m[15] << ")"; -} - -inline void print_vector3(const Vector3& v) -{ - globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n"; -} - -inline void print_3x3(const Matrix4& m) -{ - globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) " - << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) " - << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n"; -} - - - -inline bool texdef_sane(const texdef_t& texdef) -{ - return fabs(texdef.shift[0]) < (1 << 16) - && fabs(texdef.shift[1]) < (1 << 16); -} - -inline void Winding_DrawWireframe(const Winding& winding) -{ - glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex); - glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints)); -} - -inline void Winding_Draw(const Winding& winding, const Vector3& normal, RenderStateFlags state) -{ - glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex); - - if((state & RENDER_BUMP) != 0) - { - Vector3 normals[c_brush_maxFaces]; - typedef Vector3* Vector3Iter; - for(Vector3Iter i = normals, end = normals + winding.numpoints; i != end; ++i) - { - *i = normal; - } - if(GlobalShaderCache().useShaderLanguage()) - { - glNormalPointer(GL_FLOAT, sizeof(Vector3), normals); - glVertexAttribPointerARB(c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord); - glVertexAttribPointerARB(c_attr_Tangent, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent); - glVertexAttribPointerARB(c_attr_Binormal, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent); - } - else - { - glVertexAttribPointerARB(11, 3, GL_FLOAT, 0, sizeof(Vector3), normals); - glVertexAttribPointerARB(8, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord); - glVertexAttribPointerARB(9, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent); - glVertexAttribPointerARB(10, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent); - } - } - else - { - if (state & RENDER_LIGHTING) - { - Vector3 normals[c_brush_maxFaces]; - typedef Vector3* Vector3Iter; - for(Vector3Iter i = normals, last = normals + winding.numpoints; i != last; ++i) - { - *i = normal; - } - glNormalPointer(GL_FLOAT, sizeof(Vector3), normals); - } - - if (state & RENDER_TEXTURE) - { - glTexCoordPointer(2, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->texcoord); - } - } -#if 0 - if (state & RENDER_FILL) - { - glDrawArrays(GL_TRIANGLE_FAN, 0, GLsizei(winding.numpoints)); - } - else - { - glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints)); - } -#else - glDrawArrays(GL_POLYGON, 0, GLsizei(winding.numpoints)); -#endif - -#if 0 - const Winding& winding = winding; - - if(state & RENDER_FILL) - { - glBegin(GL_POLYGON); - } - else - { - glBegin(GL_LINE_LOOP); - } - - if (state & RENDER_LIGHTING) - glNormal3fv(normal); - - for(int i = 0; i < winding.numpoints; ++i) - { - if (state & RENDER_TEXTURE) - glTexCoord2fv(&winding.points[i][3]); - glVertex3fv(winding.points[i]); - } - glEnd(); -#endif -} - - -#include "shaderlib.h" - -typedef DoubleVector3 PlanePoints[3]; - -inline bool planepts_equal(const PlanePoints planepts, const PlanePoints other) -{ - return planepts[0] == other[0] && planepts[1] == other[1] && planepts[2] == other[2]; -} - -inline void planepts_assign(PlanePoints planepts, const PlanePoints other) -{ - planepts[0] = other[0]; - planepts[1] = other[1]; - planepts[2] = other[2]; -} - -inline void planepts_quantise(PlanePoints planepts, double snap) -{ - vector3_snap(planepts[0], snap); - vector3_snap(planepts[1], snap); - vector3_snap(planepts[2], snap); -} - -inline float vector3_max_component(const Vector3& vec3) -{ - return std::max(fabsf(vec3[0]), std::max(fabsf(vec3[1]), fabsf(vec3[2]))); -} - -inline void edge_snap(Vector3& edge, double snap) -{ - float scale = static_cast(ceil(fabs(snap / vector3_max_component(edge)))); - if(scale > 0.0f) - { - vector3_scale(edge, scale); - } - vector3_snap(edge, snap); -} - -inline void planepts_snap(PlanePoints planepts, double snap) -{ - Vector3 edge01(vector3_subtracted(planepts[1], planepts[0])); - Vector3 edge12(vector3_subtracted(planepts[2], planepts[1])); - Vector3 edge20(vector3_subtracted(planepts[0], planepts[2])); - - double length_squared_01 = vector3_dot(edge01, edge01); - double length_squared_12 = vector3_dot(edge12, edge12); - double length_squared_20 = vector3_dot(edge20, edge20); - - vector3_snap(planepts[0], snap); - - if(length_squared_01 < length_squared_12) - { - if(length_squared_12 < length_squared_20) - { - edge_snap(edge01, snap); - edge_snap(edge12, snap); - planepts[1] = vector3_added(planepts[0], edge01); - planepts[2] = vector3_added(planepts[1], edge12); - } - else - { - edge_snap(edge20, snap); - edge_snap(edge01, snap); - planepts[1] = vector3_added(planepts[0], edge20); - planepts[2] = vector3_added(planepts[1], edge01); - } - } - else - { - if(length_squared_01 < length_squared_20) - { - edge_snap(edge01, snap); - edge_snap(edge12, snap); - planepts[1] = vector3_added(planepts[0], edge01); - planepts[2] = vector3_added(planepts[1], edge12); - } - else - { - edge_snap(edge12, snap); - edge_snap(edge20, snap); - planepts[1] = vector3_added(planepts[0], edge12); - planepts[2] = vector3_added(planepts[1], edge20); - } - } -} - -inline PointVertex pointvertex_for_planept(const DoubleVector3& point, const Colour4b& colour) -{ - return PointVertex( - Vertex3f( - static_cast(point.x()), - static_cast(point.y()), - static_cast(point.z()) - ), - colour - ); -} - -inline PointVertex pointvertex_for_windingpoint(const Vector3& point, const Colour4b& colour) -{ - return PointVertex( - vertex3f_for_vector3(point), - colour - ); -} - -inline bool check_plane_is_integer(const PlanePoints& planePoints) -{ - return !float_is_integer(planePoints[0][0]) - || !float_is_integer(planePoints[0][1]) - || !float_is_integer(planePoints[0][2]) - || !float_is_integer(planePoints[1][0]) - || !float_is_integer(planePoints[1][1]) - || !float_is_integer(planePoints[1][2]) - || !float_is_integer(planePoints[2][0]) - || !float_is_integer(planePoints[2][1]) - || !float_is_integer(planePoints[2][2]); -} - -inline void brush_check_shader(const char* name) -{ - if(!shader_valid(name)) - { - globalErrorStream() << "brush face has invalid texture name: '" << name << "'\n"; - } -} - -class FaceShaderObserver -{ -public: - virtual void realiseShader() = 0; - virtual void unrealiseShader() = 0; -}; - -class FaceShaderObserverRealise -{ -public: - void operator()(FaceShaderObserver& observer) const - { - observer.realiseShader(); - } -}; - -class FaceShaderObserverUnrealise -{ -public: - void operator()(FaceShaderObserver& observer) const - { - observer.unrealiseShader(); - } -}; - -typedef ReferencePair FaceShaderObserverPair; - - -class ContentsFlagsValue -{ -public: - ContentsFlagsValue() - { - } - ContentsFlagsValue(int surfaceFlags, int contentFlags, int value, bool specified) : - m_surfaceFlags(surfaceFlags), - m_contentFlags(contentFlags), - m_value(value), - m_specified(specified) - { - } - int m_surfaceFlags; - int m_contentFlags; - int m_value; - bool m_specified; -}; - -inline void ContentsFlagsValue_assignMasked(ContentsFlagsValue& flags, const ContentsFlagsValue& other) -{ - bool detail = bitfield_enabled(flags.m_contentFlags, BRUSH_DETAIL_MASK); - flags = other; - if(detail) - { - flags.m_contentFlags = bitfield_enable(flags.m_contentFlags, BRUSH_DETAIL_MASK); - } - else - { - flags.m_contentFlags = bitfield_disable(flags.m_contentFlags, BRUSH_DETAIL_MASK); - } -} - - -class FaceShader : public ModuleObserver -{ -public: - class SavedState - { - public: - CopiedString m_shader; - ContentsFlagsValue m_flags; - - SavedState(const FaceShader& faceShader) - { - m_shader = faceShader.getShader(); - m_flags = faceShader.m_flags; - } - - void exportState(FaceShader& faceShader) const - { - faceShader.setShader(m_shader.c_str()); - faceShader.setFlags(m_flags); - } - }; - - CopiedString m_shader; - Shader* m_state; - ContentsFlagsValue m_flags; - FaceShaderObserverPair m_observers; - bool m_instanced; - bool m_realised; - - FaceShader(const char* shader, const ContentsFlagsValue& flags = ContentsFlagsValue(0, 0, 0, false)) : - m_shader(shader), - m_state(0), - m_flags(flags), - m_instanced(false), - m_realised(false) - { - captureShader(); - } - ~FaceShader() - { - releaseShader(); - } - // copy-construction not supported - FaceShader(const FaceShader& other); - - void instanceAttach() - { - m_instanced = true; - m_state->incrementUsed(); - } - void instanceDetach() - { - m_state->decrementUsed(); - m_instanced = false; - } - - void captureShader() - { - ASSERT_MESSAGE(m_state == 0, "shader cannot be captured"); - brush_check_shader(m_shader.c_str()); - m_state = GlobalShaderCache().capture(m_shader.c_str()); - m_state->attach(*this); - } - void releaseShader() - { - ASSERT_MESSAGE(m_state != 0, "shader cannot be released"); - m_state->detach(*this); - GlobalShaderCache().release(m_shader.c_str()); - m_state = 0; - } - - void realise() - { - ASSERT_MESSAGE(!m_realised, "FaceTexdef::realise: already realised"); - m_realised = true; - m_observers.forEach(FaceShaderObserverRealise()); - } - void unrealise() - { - ASSERT_MESSAGE(m_realised, "FaceTexdef::unrealise: already unrealised"); - m_observers.forEach(FaceShaderObserverUnrealise()); - m_realised = false; - } - - void attach(FaceShaderObserver& observer) - { - m_observers.attach(observer); - if(m_realised) - { - observer.realiseShader(); - } - } - - void detach(FaceShaderObserver& observer) - { - if(m_realised) - { - observer.unrealiseShader(); - } - m_observers.detach(observer); - } - - const char* getShader() const - { - return m_shader.c_str(); - } - void setShader(const char* name) - { - if(m_instanced) - { - m_state->decrementUsed(); - } - releaseShader(); - m_shader = name; - captureShader(); - if(m_instanced) - { - m_state->incrementUsed(); - } - } - ContentsFlagsValue getFlags() const - { - ASSERT_MESSAGE(m_realised, "FaceShader::getFlags: flags not valid when unrealised"); - if(!m_flags.m_specified) - { - return ContentsFlagsValue( - m_state->getTexture().surfaceFlags, - m_state->getTexture().contentFlags, - m_state->getTexture().value, - true - ); - } - return m_flags; - } - void setFlags(const ContentsFlagsValue& flags) - { - ASSERT_MESSAGE(m_realised, "FaceShader::setFlags: flags not valid when unrealised"); - ContentsFlagsValue_assignMasked(m_flags, flags); - } - - Shader* state() const - { - return m_state; - } - - std::size_t width() const - { - if(m_realised) - { - return m_state->getTexture().width; - } - return 1; - } - std::size_t height() const - { - if(m_realised) - { - return m_state->getTexture().height; - } - return 1; - } - unsigned int shaderFlags() const - { - if(m_realised) - { - return m_state->getFlags(); - } - return 0; - } -}; - - - - -class FaceTexdef : public FaceShaderObserver -{ - // not copyable - FaceTexdef(const FaceTexdef& other); - // not assignable - FaceTexdef& operator=(const FaceTexdef& other); -public: - class SavedState - { - public: - TextureProjection m_projection; - - SavedState(const FaceTexdef& faceTexdef) - { - m_projection = faceTexdef.m_projection; - } - - void exportState(FaceTexdef& faceTexdef) const - { - Texdef_Assign(faceTexdef.m_projection, m_projection); - } - }; - - FaceShader& m_shader; - TextureProjection m_projection; - bool m_projectionInitialised; - bool m_scaleApplied; - - FaceTexdef( - FaceShader& shader, - const TextureProjection& projection, - bool projectionInitialised = true - ) : - m_shader(shader), - m_projection(projection), - m_projectionInitialised(projectionInitialised), - m_scaleApplied(false) - { - m_shader.attach(*this); - } - ~FaceTexdef() - { - m_shader.detach(*this); - } - - void addScale() - { - ASSERT_MESSAGE(!m_scaleApplied, "texture scale aready added"); - m_scaleApplied = true; - m_projection.m_brushprimit_texdef.addScale(m_shader.width(), m_shader.height()); - } - void removeScale() - { - ASSERT_MESSAGE(m_scaleApplied, "texture scale aready removed"); - m_scaleApplied = false; - m_projection.m_brushprimit_texdef.removeScale(m_shader.width(), m_shader.height()); - } - - void realiseShader() - { - if(m_projectionInitialised && !m_scaleApplied) - { - addScale(); - } - } - void unrealiseShader() - { - if(m_projectionInitialised && m_scaleApplied) - { - removeScale(); - } - } - - void setTexdef(const TextureProjection& projection) - { - removeScale(); - Texdef_Assign(m_projection, projection); - addScale(); - } - - void shift(float s, float t) - { - ASSERT_MESSAGE(texdef_sane(m_projection.m_texdef), "FaceTexdef::shift: bad texdef"); - removeScale(); - Texdef_Shift(m_projection, s, t); - addScale(); - } - - void scale(float s, float t) - { - removeScale(); - Texdef_Scale(m_projection, s, t); - addScale(); - } - - void rotate(float angle) - { - removeScale(); - Texdef_Rotate(m_projection, angle); - addScale(); - } - - void fit(const Vector3& normal, const Winding& winding, float s_repeat, float t_repeat) - { - Texdef_FitTexture(m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat); - } - - void emitTextureCoordinates(Winding& winding, const Vector3& normal, const Matrix4& localToWorld) - { - Texdef_EmitTextureCoordinates(m_projection, m_shader.width(), m_shader.height(), winding, normal, localToWorld); - } - - void transform(const Plane3& plane, const Matrix4& matrix) - { - removeScale(); - Texdef_transformLocked(m_projection, m_shader.width(), m_shader.height(), plane, matrix); - addScale(); - } - - TextureProjection normalised() const - { - brushprimit_texdef_t tmp(m_projection.m_brushprimit_texdef); - tmp.removeScale(m_shader.width(), m_shader.height()); - return TextureProjection(m_projection.m_texdef, tmp, m_projection.m_basis_s, m_projection.m_basis_t); - } - void setBasis(const Vector3& normal) - { - Matrix4 basis; - Normal_GetTransform(normal, basis); - m_projection.m_basis_s = Vector3(basis.xx(), basis.yx(), basis.zx()); - m_projection.m_basis_t = Vector3(-basis.xy(), -basis.yy(), -basis.zy()); - } -}; - -inline void planepts_print(const PlanePoints& planePoints, TextOutputStream& ostream) -{ - ostream << "( " << planePoints[0][0] << " " << planePoints[0][1] << " " << planePoints[0][2] << " ) " - << "( " << planePoints[1][0] << " " << planePoints[1][1] << " " << planePoints[1][2] << " ) " - << "( " << planePoints[2][0] << " " << planePoints[2][1] << " " << planePoints[2][2] << " )"; -} - - -inline Plane3 Plane3_applyTranslation(const Plane3& plane, const Vector3& translation) -{ - Plane3 tmp(plane3_translated(Plane3(plane.normal(), -plane.dist()), translation)); - return Plane3(tmp.normal(), -tmp.dist()); -} - -inline Plane3 Plane3_applyTransform(const Plane3& plane, const Matrix4& matrix) -{ - Plane3 tmp(plane3_transformed(Plane3(plane.normal(), -plane.dist()), matrix)); - return Plane3(tmp.normal(), -tmp.dist()); -} - -class FacePlane -{ - PlanePoints m_planepts; - Plane3 m_planeCached; - Plane3 m_plane; -public: - Vector3 m_funcStaticOrigin; - - static EBrushType m_type; - - static bool isDoom3Plane() - { - return FacePlane::m_type == eBrushTypeDoom3 || FacePlane::m_type == eBrushTypeQuake4; - } - - class SavedState - { - public: - PlanePoints m_planepts; - Plane3 m_plane; - - SavedState(const FacePlane& facePlane) - { - if(facePlane.isDoom3Plane()) - { - m_plane = facePlane.m_plane; - } - else - { - planepts_assign(m_planepts, facePlane.planePoints()); - } - } - - void exportState(FacePlane& facePlane) const - { - if(facePlane.isDoom3Plane()) - { - facePlane.m_plane = m_plane; - facePlane.updateTranslated(); - } - else - { - planepts_assign(facePlane.planePoints(), m_planepts); - facePlane.MakePlane(); - } - } - }; - - FacePlane() : m_funcStaticOrigin(0, 0, 0) - { - } - FacePlane(const FacePlane& other) : m_funcStaticOrigin(0, 0, 0) - { - if(!isDoom3Plane()) - { - planepts_assign(m_planepts, other.m_planepts); - MakePlane(); - } - else - { - m_plane = other.m_plane; - updateTranslated(); - } - } - - void MakePlane() - { - if(!isDoom3Plane()) - { -#if 0 - if(check_plane_is_integer(m_planepts)) - { - globalErrorStream() << "non-integer planepts: "; - planepts_print(m_planepts, globalErrorStream()); - globalErrorStream() << "\n"; - } -#endif - m_planeCached = plane3_for_points(m_planepts); - } - } - - void reverse() - { - if(!isDoom3Plane()) - { - vector3_swap(m_planepts[0], m_planepts[2]); - MakePlane(); - } - else - { - m_planeCached = plane3_flipped(m_plane); - updateSource(); - } - } - void transform(const Matrix4& matrix, bool mirror) - { - if(!isDoom3Plane()) - { - -#if 0 - bool off = check_plane_is_integer(planePoints()); -#endif - - matrix4_transform_point(matrix, m_planepts[0]); - matrix4_transform_point(matrix, m_planepts[1]); - matrix4_transform_point(matrix, m_planepts[2]); - - if(mirror) - { - reverse(); - } - -#if 0 - if(check_plane_is_integer(planePoints())) - { - if(!off) - { - globalErrorStream() << "caused by transform\n"; - } - } -#endif - MakePlane(); - } - else - { - m_planeCached = Plane3_applyTransform(m_planeCached, matrix); - updateSource(); - } - } - void offset(float offset) - { - if(!isDoom3Plane()) - { - Vector3 move(vector3_scaled(m_planeCached.normal(), -offset)); - - vector3_subtract(m_planepts[0], move); - vector3_subtract(m_planepts[1], move); - vector3_subtract(m_planepts[2], move); - - MakePlane(); - } - else - { - m_planeCached.d += offset; - updateSource(); - } - } - - void updateTranslated() - { - m_planeCached = Plane3_applyTranslation(m_plane, m_funcStaticOrigin); - } - void updateSource() - { - m_plane = Plane3_applyTranslation(m_planeCached, vector3_negated(m_funcStaticOrigin)); - } - - - PlanePoints& planePoints() - { - return m_planepts; - } - const PlanePoints& planePoints() const - { - return m_planepts; - } - const Plane3& plane3() const - { - return m_planeCached; - } - void setDoom3Plane(const Plane3& plane) - { - m_plane = plane; - updateTranslated(); - } - const Plane3& getDoom3Plane() const - { - return m_plane; - } - - void copy(const FacePlane& other) - { - if(!isDoom3Plane()) - { - planepts_assign(m_planepts, other.m_planepts); - MakePlane(); - } - else - { - m_planeCached = other.m_plane; - updateSource(); - } - } - void copy(const Vector3& p0, const Vector3& p1, const Vector3& p2) - { - if(!isDoom3Plane()) - { - m_planepts[0] = p0; - m_planepts[1] = p1; - m_planepts[2] = p2; - MakePlane(); - } - else - { - m_planeCached = plane3_for_points(p2, p1, p0); - updateSource(); - } - } -}; - -inline void Winding_testSelect(Winding& winding, SelectionTest& test, SelectionIntersection& best) -{ - test.TestPolygon(VertexPointer(reinterpret_cast(&winding.points.data()->vertex), sizeof(WindingVertex)), winding.numpoints, best); -} - -const double GRID_MIN = 0.125; - -inline double quantiseInteger(double f) -{ - return float_to_integer(f); -} - -inline double quantiseFloating(double f) -{ - return float_snapped(f, 1.f / (1 << 16)); -} - -typedef double (*QuantiseFunc)(double f); - -class Face; - -class FaceFilter -{ -public: - virtual bool filter(const Face& face) const = 0; -}; - -bool face_filtered(Face& face); -void add_face_filter(FaceFilter& filter, int mask, bool invert = false); - -void Brush_addTextureChangedCallback(const SignalHandler& callback); -void Brush_textureChanged(); - - -extern bool g_brush_texturelock_enabled; - -class FaceObserver -{ -public: - virtual void planeChanged() = 0; - virtual void connectivityChanged() = 0; - virtual void shaderChanged() = 0; - virtual void evaluateTransform() = 0; -}; - -class Face : -public OpenGLRenderable, -public Filterable, -public Undoable, -public FaceShaderObserver -{ - std::size_t m_refcount; - - class SavedState : public UndoMemento - { - public: - FacePlane::SavedState m_planeState; - FaceTexdef::SavedState m_texdefState; - FaceShader::SavedState m_shaderState; - - SavedState(const Face& face) : m_planeState(face.getPlane()), m_texdefState(face.getTexdef()), m_shaderState(face.getShader()) - { - } - - void exportState(Face& face) const - { - m_planeState.exportState(face.getPlane()); - m_shaderState.exportState(face.getShader()); - m_texdefState.exportState(face.getTexdef()); - } - - void release() - { - delete this; - } - }; - -public: - static QuantiseFunc m_quantise; - static EBrushType m_type; - - PlanePoints m_move_planepts; - PlanePoints m_move_planeptsTransformed; -private: - FacePlane m_plane; - FacePlane m_planeTransformed; - FaceShader m_shader; - FaceTexdef m_texdef; - TextureProjection m_texdefTransformed; - - Winding m_winding; - Vector3 m_centroid; - bool m_filtered; - - FaceObserver* m_observer; - UndoObserver* m_undoable_observer; - MapFile* m_map; - - // assignment not supported - Face& operator=(const Face& other); - // copy-construction not supported - Face(const Face& other); - -public: - - Face(FaceObserver* observer) : - m_refcount(0), - m_shader(texdef_name_default()), - m_texdef(m_shader, TextureProjection(), false), - m_filtered(false), - m_observer(observer), - m_undoable_observer(0), - m_map(0) - { - m_shader.attach(*this); - m_plane.copy(Vector3(0, 0, 0), Vector3(64, 0, 0), Vector3(0, 64, 0)); - m_texdef.setBasis(m_plane.plane3().normal()); - planeChanged(); - } - Face( - const Vector3& p0, - const Vector3& p1, - const Vector3& p2, - const char* shader, - const TextureProjection& projection, - FaceObserver* observer - ) : - m_refcount(0), - m_shader(shader), - m_texdef(m_shader, projection), - m_observer(observer), - m_undoable_observer(0), - m_map(0) - { - m_shader.attach(*this); - m_plane.copy(p0, p1, p2); - m_texdef.setBasis(m_plane.plane3().normal()); - planeChanged(); - updateFiltered(); - } - Face(const Face& other, FaceObserver* observer) : - m_refcount(0), - m_shader(other.m_shader.getShader(), other.m_shader.m_flags), - m_texdef(m_shader, other.getTexdef().normalised()), - m_observer(observer), - m_undoable_observer(0), - m_map(0) - { - m_shader.attach(*this); - m_plane.copy(other.m_plane); - planepts_assign(m_move_planepts, other.m_move_planepts); - m_texdef.setBasis(m_plane.plane3().normal()); - planeChanged(); - updateFiltered(); - } - ~Face() - { - m_shader.detach(*this); - } - - void planeChanged() - { - revertTransform(); - m_observer->planeChanged(); - } - - void realiseShader() - { - m_observer->shaderChanged(); - } - void unrealiseShader() - { - } - - void instanceAttach(MapFile* map) - { - m_shader.instanceAttach(); - m_map = map; - m_undoable_observer = GlobalUndoSystem().observer(this); - GlobalFilterSystem().registerFilterable(*this); - } - void instanceDetach(MapFile* map) - { - GlobalFilterSystem().unregisterFilterable(*this); - m_undoable_observer = 0; - GlobalUndoSystem().release(this); - m_map = 0; - m_shader.instanceDetach(); - } - - void render(RenderStateFlags state) const - { - Winding_Draw(m_winding, m_planeTransformed.plane3().normal(), state); - } - - void updateFiltered() - { - m_filtered = face_filtered(*this); - } - bool isFiltered() const - { - return m_filtered; - } - - void undoSave() - { - if(m_map != 0) - { - m_map->changed(); - } - if(m_undoable_observer != 0) - { - m_undoable_observer->save(this); - } - } - - // undoable - UndoMemento* exportState() const - { - return new SavedState(*this); - } - void importState(const UndoMemento* data) - { - undoSave(); - - static_cast(data)->exportState(*this); - - planeChanged(); - m_observer->connectivityChanged(); - texdefChanged(); - m_observer->shaderChanged(); - updateFiltered(); - } - - void IncRef() - { - ++m_refcount; - } - void DecRef() - { - if(--m_refcount == 0) - delete this; - } - - void flipWinding() - { - m_plane.reverse(); - planeChanged(); - } - - bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const - { - return volume.TestPlane(Plane3(plane3().normal(), -plane3().dist()), localToWorld); - } - - void render(Renderer& renderer, const Matrix4& localToWorld) const - { - renderer.SetState(m_shader.state(), Renderer::eFullMaterials); - renderer.addRenderable(*this, localToWorld); - } - - void transform(const Matrix4& matrix, bool mirror) - { - if(g_brush_texturelock_enabled) - Texdef_transformLocked(m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix); - - m_planeTransformed.transform(matrix, mirror); - -#if 0 - ASSERT_MESSAGE(projectionaxis_for_normal(normal) == projectionaxis_for_normal(plane3().normal()), "bleh"); -#endif - m_observer->planeChanged(); - - if(g_brush_texturelock_enabled) - Brush_textureChanged(); - } - - void assign_planepts(const PlanePoints planepts) - { - m_planeTransformed.copy(planepts[0], planepts[1], planepts[2]); - m_observer->planeChanged(); - } - - /// \brief Reverts the transformable state of the brush to identity. - void revertTransform() - { - m_planeTransformed = m_plane; - planepts_assign(m_move_planeptsTransformed, m_move_planepts); - m_texdefTransformed = m_texdef.m_projection; - } - void freezeTransform() - { - undoSave(); - m_plane = m_planeTransformed; - planepts_assign(m_move_planepts, m_move_planeptsTransformed); - m_texdef.m_projection = m_texdefTransformed; - } - - void update_move_planepts_vertex(std::size_t index, PlanePoints planePoints) - { - std::size_t numpoints = getWinding().numpoints; - ASSERT_MESSAGE(index < numpoints, "update_move_planepts_vertex: invalid index"); - - std::size_t opposite = Winding_Opposite(getWinding(), index); - std::size_t adjacent = Winding_wrap(getWinding(), opposite+numpoints-1); - planePoints[0] = getWinding()[opposite].vertex; - planePoints[1] = getWinding()[index].vertex; - planePoints[2] = getWinding()[adjacent].vertex; - // winding points are very inaccurate, so they must be quantised before using them to generate the face-plane - planepts_quantise(planePoints, GRID_MIN); - } - - void snapto(float snap) - { - if(contributes()) - { -#if 0 - ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane before snap to grid"); - planepts_snap(m_plane.planePoints(), snap); - ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane after snap to grid"); -#else - PlanePoints planePoints; - update_move_planepts_vertex(0, planePoints); - vector3_snap(planePoints[0], snap); - vector3_snap(planePoints[1], snap); - vector3_snap(planePoints[2], snap); - assign_planepts(planePoints); - freezeTransform(); -#endif - SceneChangeNotify(); - if(!plane3_valid(m_plane.plane3())) - { - globalErrorStream() << "WARNING: invalid plane after snap to grid\n"; - } - } - } - - void testSelect(SelectionTest& test, SelectionIntersection& best) - { - Winding_testSelect(m_winding, test, best); - } - - void testSelect_centroid(SelectionTest& test, SelectionIntersection& best) - { - test.TestPoint(m_centroid, best); - } - - void shaderChanged() - { - EmitTextureCoordinates(); - Brush_textureChanged(); - m_observer->shaderChanged(); - updateFiltered(); - planeChanged(); - SceneChangeNotify(); - } - - const char* GetShader() const - { - return m_shader.getShader(); - } - void SetShader(const char* name) - { - undoSave(); - m_shader.setShader(name); - shaderChanged(); - } - - void revertTexdef() - { - m_texdefTransformed = m_texdef.m_projection; - } - void texdefChanged() - { - revertTexdef(); - EmitTextureCoordinates(); - Brush_textureChanged(); - } - - void GetTexdef(TextureProjection& projection) const - { - projection = m_texdef.normalised(); - } - void SetTexdef(const TextureProjection& projection) - { - undoSave(); - m_texdef.setTexdef(projection); - texdefChanged(); - } - - void GetFlags(ContentsFlagsValue& flags) const - { - flags = m_shader.getFlags(); - } - void SetFlags(const ContentsFlagsValue& flags) - { - undoSave(); - m_shader.setFlags(flags); - m_observer->shaderChanged(); - updateFiltered(); - } - - void ShiftTexdef(float s, float t) - { - undoSave(); - m_texdef.shift(s, t); - texdefChanged(); - } - - void ScaleTexdef(float s, float t) - { - undoSave(); - m_texdef.scale(s, t); - texdefChanged(); - } - - void RotateTexdef(float angle) - { - undoSave(); - m_texdef.rotate(angle); - texdefChanged(); - } - - void FitTexture(float s_repeat, float t_repeat) - { - undoSave(); - m_texdef.fit(m_plane.plane3().normal(), m_winding, s_repeat, t_repeat); - texdefChanged(); - } - - void EmitTextureCoordinates() - { - Texdef_EmitTextureCoordinates(m_texdefTransformed, m_shader.width(), m_shader.height(), m_winding, plane3().normal(), g_matrix4_identity); - } - - - const Vector3& centroid() const - { - return m_centroid; - } - - void construct_centroid() - { - Winding_Centroid(m_winding, plane3(), m_centroid); - } - - const Winding& getWinding() const - { - return m_winding; - } - Winding& getWinding() - { - return m_winding; - } - - const Plane3& plane3() const - { - m_observer->evaluateTransform(); - return m_planeTransformed.plane3(); - } - FacePlane& getPlane() - { - return m_plane; - } - const FacePlane& getPlane() const - { - return m_plane; - } - FaceTexdef& getTexdef() - { - return m_texdef; - } - const FaceTexdef& getTexdef() const - { - return m_texdef; - } - FaceShader& getShader() - { - return m_shader; - } - const FaceShader& getShader() const - { - return m_shader; - } - - bool isDetail() const - { - return (m_shader.m_flags.m_contentFlags & BRUSH_DETAIL_MASK) != 0; - } - void setDetail(bool detail) - { - undoSave(); - if(detail && !isDetail()) - { - m_shader.m_flags.m_contentFlags |= BRUSH_DETAIL_MASK; - } - else if(!detail && isDetail()) - { - m_shader.m_flags.m_contentFlags &= ~BRUSH_DETAIL_MASK; - } - m_observer->shaderChanged(); - } - - bool contributes() const - { - return m_winding.numpoints > 2; - } - bool is_bounded() const - { - for(Winding::const_iterator i = m_winding.begin(); i != m_winding.end(); ++i) - { - if((*i).adjacent == c_brush_maxFaces) - { - return false; - } - } - return true; - } -}; - - -class FaceVertexId -{ - std::size_t m_face; - std::size_t m_vertex; - -public: - FaceVertexId(std::size_t face, std::size_t vertex) - : m_face(face), m_vertex(vertex) - { - } - - std::size_t getFace() const - { - return m_face; - } - std::size_t getVertex() const - { - return m_vertex; - } -}; - -typedef std::size_t faceIndex_t; - -struct EdgeRenderIndices -{ - RenderIndex first; - RenderIndex second; - - EdgeRenderIndices() - : first(0), second(0) - { - } - EdgeRenderIndices(const RenderIndex _first, const RenderIndex _second) - : first(_first), second(_second) - { - } -}; - -struct EdgeFaces -{ - faceIndex_t first; - faceIndex_t second; - - EdgeFaces() - : first(c_brush_maxFaces), second(c_brush_maxFaces) - { - } - EdgeFaces(const faceIndex_t _first, const faceIndex_t _second) - : first(_first), second(_second) - { - } -}; - -class RenderableWireframe : public OpenGLRenderable -{ -public: - void render(RenderStateFlags state) const - { -#if 1 - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices->colour); - glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices->vertex); - glDrawElements(GL_LINES, GLsizei(m_size<<1), RenderIndexTypeID, m_faceVertex.data()); -#else - glBegin(GL_LINES); - for(std::size_t i = 0; i < m_size; ++i) - { - glVertex3fv(&m_vertices[m_faceVertex[i].first].vertex.x); - glVertex3fv(&m_vertices[m_faceVertex[i].second].vertex.x); - } - glEnd(); -#endif - } - - Array m_faceVertex; - std::size_t m_size; - const PointVertex* m_vertices; -}; - -class Brush; -typedef std::vector brush_vector_t; - -class BrushFilter -{ -public: - virtual bool filter(const Brush& brush) const = 0; -}; - -bool brush_filtered(Brush& brush); -void add_brush_filter(BrushFilter& filter, int mask, bool invert = false); - - -/// \brief Returns true if 'self' takes priority when building brush b-rep. -inline bool plane3_inside(const Plane3& self, const Plane3& other, bool selfIsLater) -{ - if(vector3_equal_epsilon(self.normal(), other.normal(), 0.001)) - { - // same plane? prefer the one with smaller index - if(self.dist() == other.dist()) - return selfIsLater; - return self.dist() < other.dist(); - } - return true; -} - -typedef SmartPointer FaceSmartPointer; -typedef std::vector Faces; - -/// \brief Returns the unique-id of the edge adjacent to \p faceVertex in the edge-pair for the set of \p faces. -inline FaceVertexId next_edge(const Faces& faces, FaceVertexId faceVertex) -{ - std::size_t adjacent_face = faces[faceVertex.getFace()]->getWinding()[faceVertex.getVertex()].adjacent; - std::size_t adjacent_vertex = Winding_FindAdjacent(faces[adjacent_face]->getWinding(), faceVertex.getFace()); - - ASSERT_MESSAGE(adjacent_vertex != c_brush_maxFaces, "connectivity data invalid"); - if(adjacent_vertex == c_brush_maxFaces) - { - return faceVertex; - } - - return FaceVertexId(adjacent_face, adjacent_vertex); -} - -/// \brief Returns the unique-id of the vertex adjacent to \p faceVertex in the vertex-ring for the set of \p faces. -inline FaceVertexId next_vertex(const Faces& faces, FaceVertexId faceVertex) -{ - FaceVertexId nextEdge = next_edge(faces, faceVertex); - return FaceVertexId(nextEdge.getFace(), Winding_next(faces[nextEdge.getFace()]->getWinding(), nextEdge.getVertex())); -} - -class SelectableEdge -{ - Vector3 getEdge() const - { - const Winding& winding = getFace().getWinding(); - return vector3_mid(winding[m_faceVertex.getVertex()].vertex, winding[Winding_next(winding, m_faceVertex.getVertex())].vertex); - } - -public: - Faces& m_faces; - FaceVertexId m_faceVertex; - - SelectableEdge(Faces& faces, FaceVertexId faceVertex) - : m_faces(faces), m_faceVertex(faceVertex) - { - } - SelectableEdge& operator=(const SelectableEdge& other) - { - m_faceVertex = other.m_faceVertex; - return *this; - } - - Face& getFace() const - { - return *m_faces[m_faceVertex.getFace()]; - } - - void testSelect(SelectionTest& test, SelectionIntersection& best) - { - test.TestPoint(getEdge(), best); - } -}; - -class SelectableVertex -{ - Vector3 getVertex() const - { - return getFace().getWinding()[m_faceVertex.getVertex()].vertex; - } - -public: - Faces& m_faces; - FaceVertexId m_faceVertex; - - SelectableVertex(Faces& faces, FaceVertexId faceVertex) - : m_faces(faces), m_faceVertex(faceVertex) - { - } - SelectableVertex& operator=(const SelectableVertex& other) - { - m_faceVertex = other.m_faceVertex; - return *this; - } - - Face& getFace() const - { - return *m_faces[m_faceVertex.getFace()]; - } - - void testSelect(SelectionTest& test, SelectionIntersection& best) - { - test.TestPoint(getVertex(), best); - } -}; - -class BrushObserver -{ -public: - virtual void reserve(std::size_t size) = 0; - virtual void clear() = 0; - virtual void push_back(Face& face) = 0; - virtual void pop_back() = 0; - virtual void erase(std::size_t index) = 0; - virtual void connectivityChanged() = 0; - - virtual void edge_clear() = 0; - virtual void edge_push_back(SelectableEdge& edge) = 0; - - virtual void vertex_clear() = 0; - virtual void vertex_push_back(SelectableVertex& vertex) = 0; - - virtual void DEBUG_verify() const = 0; -}; - -class BrushVisitor -{ -public: - virtual void visit(Face& face) const = 0; -}; - -class Brush : - public TransformNode, - public Bounded, - public Cullable, - public Snappable, - public Undoable, - public FaceObserver, - public Filterable, - public Nameable, - public BrushDoom3 -{ -private: - scene::Node* m_node; - typedef UniqueSet Observers; - Observers m_observers; - UndoObserver* m_undoable_observer; - MapFile* m_map; - - // state - Faces m_faces; - // ---- - - // cached data compiled from state - Array m_faceCentroidPoints; - RenderablePointArray m_render_faces; - - Array m_uniqueVertexPoints; - typedef std::vector SelectableVertices; - SelectableVertices m_select_vertices; - RenderablePointArray m_render_vertices; - - Array m_uniqueEdgePoints; - typedef std::vector SelectableEdges; - SelectableEdges m_select_edges; - RenderablePointArray m_render_edges; - - Array m_edge_indices; - Array m_edge_faces; - - AABB m_aabb_local; - // ---- - - Callback m_evaluateTransform; - Callback m_boundsChanged; - - mutable bool m_planeChanged; // b-rep evaluation required - mutable bool m_transformChanged; // transform evaluation required - // ---- - -public: - STRING_CONSTANT(Name, "Brush"); - - Callback m_lightsChanged; - - // static data - static Shader* m_state_point; - // ---- - - static EBrushType m_type; - static double m_maxWorldCoord; - - Brush(scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : - m_node(&node), - m_undoable_observer(0), - m_map(0), - m_render_faces(m_faceCentroidPoints, GL_POINTS), - m_render_vertices(m_uniqueVertexPoints, GL_POINTS), - m_render_edges(m_uniqueEdgePoints, GL_POINTS), - m_evaluateTransform(evaluateTransform), - m_boundsChanged(boundsChanged), - m_planeChanged(false), - m_transformChanged(false) - { - planeChanged(); - } - Brush(const Brush& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : - m_node(&node), - m_undoable_observer(0), - m_map(0), - m_render_faces(m_faceCentroidPoints, GL_POINTS), - m_render_vertices(m_uniqueVertexPoints, GL_POINTS), - m_render_edges(m_uniqueEdgePoints, GL_POINTS), - m_evaluateTransform(evaluateTransform), - m_boundsChanged(boundsChanged), - m_planeChanged(false), - m_transformChanged(false) - { - copy(other); - } - Brush(const Brush& other) : - TransformNode(other), - Bounded(other), - Cullable(other), - Snappable(), - Undoable(other), - FaceObserver(other), - Filterable(other), - Nameable(other), - BrushDoom3(other), - m_node(0), - m_undoable_observer(0), - m_map(0), - m_render_faces(m_faceCentroidPoints, GL_POINTS), - m_render_vertices(m_uniqueVertexPoints, GL_POINTS), - m_render_edges(m_uniqueEdgePoints, GL_POINTS), - m_planeChanged(false), - m_transformChanged(false) - { - copy(other); - } - ~Brush() - { - ASSERT_MESSAGE(m_observers.empty(), "Brush::~Brush: observers still attached"); - } - - // assignment not supported - Brush& operator=(const Brush& other); - - void setDoom3GroupOrigin(const Vector3& origin) - { - //globalOutputStream() << "func_static origin before: " << m_funcStaticOrigin << " after: " << origin << "\n"; - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->getPlane().m_funcStaticOrigin = origin; - (*i)->getPlane().updateTranslated(); - (*i)->planeChanged(); - } - planeChanged(); - } - - void attach(BrushObserver& observer) - { - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - observer.push_back(*(*i)); - } - - for(SelectableEdges::iterator i = m_select_edges.begin(); i !=m_select_edges.end(); ++i) - { - observer.edge_push_back(*i); - } - - for(SelectableVertices::iterator i = m_select_vertices.begin(); i != m_select_vertices.end(); ++i) - { - observer.vertex_push_back(*i); - } - - m_observers.insert(&observer); - } - void detach(BrushObserver& observer) - { - m_observers.erase(&observer); - } - - void forEachFace(const BrushVisitor& visitor) const - { - for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - visitor.visit(*(*i)); - } - } - - void forEachFace_instanceAttach(MapFile* map) const - { - for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->instanceAttach(map); - } - } - void forEachFace_instanceDetach(MapFile* map) const - { - for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->instanceDetach(map); - } - } - - InstanceCounter m_instanceCounter; - void instanceAttach(const scene::Path& path) - { - if(++m_instanceCounter.m_count == 1) - { - m_map = path_find_mapfile(path.begin(), path.end()); - m_undoable_observer = GlobalUndoSystem().observer(this); - GlobalFilterSystem().registerFilterable(*this); - forEachFace_instanceAttach(m_map); - } - else - { - ASSERT_MESSAGE(path_find_mapfile(path.begin(), path.end()) == m_map, "node is instanced across more than one file"); - } - } - void instanceDetach(const scene::Path& path) - { - if(--m_instanceCounter.m_count == 0) - { - forEachFace_instanceDetach(m_map); - GlobalFilterSystem().unregisterFilterable(*this); - m_map = 0; - m_undoable_observer = 0; - GlobalUndoSystem().release(this); - } - } - - // nameable - const char* name() const - { - return "brush"; - } - void attach(const NameCallback& callback) - { - } - void detach(const NameCallback& callback) - { - } - - // filterable - void updateFiltered() - { - if(m_node != 0) - { - if(brush_filtered(*this)) - { - m_node->enable(scene::Node::eFiltered); - } - else - { - m_node->disable(scene::Node::eFiltered); - } - } - } - - // observer - void planeChanged() - { - m_planeChanged = true; - aabbChanged(); - m_lightsChanged(); - } - void shaderChanged() - { - updateFiltered(); - planeChanged(); - } - - void evaluateBRep() const - { - if(m_planeChanged) - { - m_planeChanged = false; - const_cast(this)->buildBRep(); - } - } - - void transformChanged() - { - m_transformChanged = true; - planeChanged(); - } - typedef MemberCaller TransformChangedCaller; - - void evaluateTransform() - { - if(m_transformChanged) - { - m_transformChanged = false; - revertTransform(); - m_evaluateTransform(); - } - } - const Matrix4& localToParent() const - { - return g_matrix4_identity; - } - void aabbChanged() - { - m_boundsChanged(); - } - const AABB& localAABB() const - { - evaluateBRep(); - return m_aabb_local; - } - - VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const - { - return test.TestAABB(m_aabb_local, localToWorld); - } - - void renderComponents(SelectionSystem::EComponentMode mode, Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - switch(mode) - { - case SelectionSystem::eVertex: - renderer.addRenderable(m_render_vertices, localToWorld); - break; - case SelectionSystem::eEdge: - renderer.addRenderable(m_render_edges, localToWorld); - break; - case SelectionSystem::eFace: - renderer.addRenderable(m_render_faces, localToWorld); - break; - default: - break; - } - } - - void transform(const Matrix4& matrix) - { - bool mirror = matrix4_handedness(matrix) == MATRIX4_LEFTHANDED; - - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->transform(matrix, mirror); - } - } - void snapto(float snap) - { - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->snapto(snap); - } - } - void revertTransform() - { - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->revertTransform(); - } - } - void freezeTransform() - { - for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) - { - (*i)->freezeTransform(); - } - } - - /// \brief Returns the absolute index of the \p faceVertex. - std::size_t absoluteIndex(FaceVertexId faceVertex) - { - std::size_t index = 0; - for(std::size_t i = 0; i < faceVertex.getFace(); ++i) - { - index += m_faces[i]->getWinding().numpoints; - } - return index + faceVertex.getVertex(); - } - - void appendFaces(const Faces& other) - { - clear(); - for(Faces::const_iterator i = other.begin(); i != other.end(); ++i) - { - push_back(*i); - } - } - - /// \brief The undo memento for a brush stores only the list of face references - the faces are not copied. - class BrushUndoMemento : public UndoMemento - { - public: - BrushUndoMemento(const Faces& faces) : m_faces(faces) - { - } - void release() - { - delete this; - } - - Faces m_faces; - }; - - void undoSave() - { - if(m_map != 0) - { - m_map->changed(); - } - if(m_undoable_observer != 0) - { - m_undoable_observer->save(this); - } - } - - UndoMemento* exportState() const - { - return new BrushUndoMemento(m_faces); - } - - void importState(const UndoMemento* state) - { - undoSave(); - appendFaces(static_cast(state)->m_faces); - planeChanged(); - - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->DEBUG_verify(); - } - } - - bool isDetail() - { - return !m_faces.empty() && m_faces.front()->isDetail(); - } - - /// \brief Appends a copy of \p face to the end of the face list. - Face* addFace(const Face& face) - { - if(m_faces.size() == c_brush_maxFaces) - { - return 0; - } - undoSave(); - push_back(FaceSmartPointer(new Face(face, this))); - m_faces.back()->setDetail(isDetail()); - planeChanged(); - return m_faces.back(); - } - - /// \brief Appends a new face constructed from the parameters to the end of the face list. - Face* addPlane(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection) - { - if(m_faces.size() == c_brush_maxFaces) - { - return 0; - } - undoSave(); - push_back(FaceSmartPointer(new Face(p0, p1, p2, shader, projection, this))); - m_faces.back()->setDetail(isDetail()); - planeChanged(); - return m_faces.back(); - } - - static void constructStatic(EBrushType type) - { - m_type = type; - Face::m_type = type; - FacePlane::m_type = type; - - g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_QUAKE; - if(m_type == eBrushTypeQuake3BP || m_type == eBrushTypeDoom3 || m_type == eBrushTypeQuake4) - { - g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_BRUSHPRIMITIVES; - // g_brush_texturelock_enabled = true; // bad idea, this overrides user setting - } - else if(m_type == eBrushTypeHalfLife) - { - g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_HALFLIFE; - // g_brush_texturelock_enabled = true; // bad idea, this overrides user setting - } - - Face::m_quantise = (m_type == eBrushTypeQuake) ? quantiseInteger : quantiseFloating; - - m_state_point = GlobalShaderCache().capture("$POINT"); - } - static void destroyStatic() - { - GlobalShaderCache().release("$POINT"); - } - - std::size_t DEBUG_size() - { - return m_faces.size(); - } - - typedef Faces::const_iterator const_iterator; - - const_iterator begin() const - { - return m_faces.begin(); - } - const_iterator end() const - { - return m_faces.end(); - } - - Face* back() - { - return m_faces.back(); - } - const Face* back() const - { - return m_faces.back(); - } - void reserve(std::size_t count) - { - m_faces.reserve(count); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->reserve(count); - } - } - void push_back(Faces::value_type face) - { - m_faces.push_back(face); - if(m_instanceCounter.m_count != 0) - { - m_faces.back()->instanceAttach(m_map); - } - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->push_back(*face); - (*i)->DEBUG_verify(); - } - } - void pop_back() - { - if(m_instanceCounter.m_count != 0) - { - m_faces.back()->instanceDetach(m_map); - } - m_faces.pop_back(); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->pop_back(); - (*i)->DEBUG_verify(); - } - } - void erase(std::size_t index) - { - if(m_instanceCounter.m_count != 0) - { - m_faces[index]->instanceDetach(m_map); - } - m_faces.erase(m_faces.begin() + index); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->erase(index); - (*i)->DEBUG_verify(); - } - } - void connectivityChanged() - { - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->connectivityChanged(); - } - } - - - void clear() - { - undoSave(); - if(m_instanceCounter.m_count != 0) - { - forEachFace_instanceDetach(m_map); - } - m_faces.clear(); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->clear(); - (*i)->DEBUG_verify(); - } - } - std::size_t size() const - { - return m_faces.size(); - } - bool empty() const - { - return m_faces.empty(); - } - - /// \brief Returns true if any face of the brush contributes to the final B-Rep. - bool hasContributingFaces() const - { - for(const_iterator i = begin(); i != end(); ++i) - { - if((*i)->contributes()) - { - return true; - } - } - return false; - } - - /// \brief Removes faces that do not contribute to the brush. This is useful for cleaning up after CSG operations on the brush. - /// Note: removal of empty faces is not performed during direct brush manipulations, because it would make a manipulation irreversible if it created an empty face. - void removeEmptyFaces() - { - evaluateBRep(); - - { - std::size_t i = 0; - while(i < m_faces.size()) - { - if(!m_faces[i]->contributes()) - { - erase(i); - planeChanged(); - } - else - { - ++i; - } - } - } - } - - /// \brief Constructs \p winding from the intersection of \p plane with the other planes of the brush. - void windingForClipPlane(Winding& winding, const Plane3& plane) const - { - FixedWinding buffer[2]; - bool swap = false; - - // get a poly that covers an effectively infinite area - Winding_createInfinite(buffer[swap], plane, m_maxWorldCoord + 1); - - // chop the poly by all of the other faces - { - for (std::size_t i = 0; i < m_faces.size(); ++i) - { - const Face& clip = *m_faces[i]; - - if(plane3_equal(clip.plane3(), plane) - || !plane3_valid(clip.plane3()) || !plane_unique(i) - || plane3_opposing(plane, clip.plane3())) - { - continue; - } - - buffer[!swap].clear(); - -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "clip vs face: " << i << "\n"; -#endif - - { - // flip the plane, because we want to keep the back side - Plane3 clipPlane(vector3_negated(clip.plane3().normal()), -clip.plane3().dist()); - Winding_Clip(buffer[swap], plane, clipPlane, i, buffer[!swap]); - } - -#if BRUSH_CONNECTIVITY_DEBUG - for(FixedWinding::Points::iterator k = buffer[!swap].points.begin(), j = buffer[!swap].points.end() - 1; k != buffer[!swap].points.end(); j = k, ++k) - { - if(vector3_length_squared(vector3_subtracted((*k).vertex, (*j).vertex)) < 1) - { - globalOutputStream() << "v: " << std::distance(buffer[!swap].points.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n"; - } - } -#endif - - //ASSERT_MESSAGE(buffer[!swap].numpoints != 1, "created single-point winding"); - - swap = !swap; - } - } - - Winding_forFixedWinding(winding, buffer[swap]); - -#if BRUSH_CONNECTIVITY_DEBUG - Winding_printConnectivity(winding); - - for(Winding::iterator i = winding.begin(), j = winding.end() - 1; i != winding.end(); j = i, ++i) - { - if(vector3_length_squared(vector3_subtracted((*i).vertex, (*j).vertex)) < 1) - { - globalOutputStream() << "v: " << std::distance(winding.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n"; - } - } -#endif - } - - void update_wireframe(RenderableWireframe& wire, const bool* faces_visible) const - { - wire.m_faceVertex.resize(m_edge_indices.size()); - wire.m_vertices = m_uniqueVertexPoints.data(); - wire.m_size = 0; - for(std::size_t i = 0; i < m_edge_faces.size(); ++i) - { - if(faces_visible[m_edge_faces[i].first] - || faces_visible[m_edge_faces[i].second]) - { - wire.m_faceVertex[wire.m_size++] = m_edge_indices[i]; - } - } - } - - - void update_faces_wireframe(Array& wire, const bool* faces_visible) const - { - std::size_t count = 0; - for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i) - { - if(faces_visible[i]) - { - ++count; - } - } - - wire.resize(count); - Array::iterator p = wire.begin(); - for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i) - { - if(faces_visible[i]) - { - *p++ = m_faceCentroidPoints[i]; - } - } - } - - /// \brief Makes this brush a deep-copy of the \p other. - void copy(const Brush& other) - { - for(Faces::const_iterator i = other.m_faces.begin(); i != other.m_faces.end(); ++i) - { - addFace(*(*i)); - } - planeChanged(); - } - -private: - void edge_push_back(FaceVertexId faceVertex) - { - m_select_edges.push_back(SelectableEdge(m_faces, faceVertex)); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->edge_push_back(m_select_edges.back()); - } - } - void edge_clear() - { - m_select_edges.clear(); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->edge_clear(); - } - } - void vertex_push_back(FaceVertexId faceVertex) - { - m_select_vertices.push_back(SelectableVertex(m_faces, faceVertex)); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->vertex_push_back(m_select_vertices.back()); - } - } - void vertex_clear() - { - m_select_vertices.clear(); - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->vertex_clear(); - } - } - - /// \brief Returns true if the face identified by \p index is preceded by another plane that takes priority over it. - bool plane_unique(std::size_t index) const - { - // duplicate plane - for(std::size_t i = 0; i < m_faces.size(); ++i) - { - if(index != i && !plane3_inside(m_faces[index]->plane3(), m_faces[i]->plane3(), index < i)) - { - return false; - } - } - return true; - } - - /// \brief Removes edges that are smaller than the tolerance used when generating brush windings. - void removeDegenerateEdges() - { - for (std::size_t i = 0; i < m_faces.size(); ++i) - { - Winding& winding = m_faces[i]->getWinding(); - for(Winding::iterator j = winding.begin(); j != winding.end();) - { - std::size_t index = std::distance(winding.begin(), j); - std::size_t next = Winding_next(winding, index); - if(Edge_isDegenerate(winding[index].vertex, winding[next].vertex)) - { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate edge adjacent to " << winding[index].adjacent << "\n"; -#endif - Winding& other = m_faces[winding[index].adjacent]->getWinding(); - std::size_t adjacent = Winding_FindAdjacent(other, i); - if(adjacent != c_brush_maxFaces) - { - other.erase(other.begin() + adjacent); - } - winding.erase(j); - } - else - { - ++j; - } - } - } - } - - /// \brief Invalidates faces that have only two vertices in their winding, while preserving edge-connectivity information. - void removeDegenerateFaces() - { - // save adjacency info for degenerate faces - for (std::size_t i = 0; i < m_faces.size(); ++i) - { - Winding& degen = m_faces[i]->getWinding(); - - if(degen.numpoints == 2) - { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate winding adjacent to " << degen[0].adjacent << ", " << degen[1].adjacent << "\n"; -#endif - // this is an "edge" face, where the plane touches the edge of the brush - { - Winding& winding = m_faces[degen[0].adjacent]->getWinding(); - std::size_t index = Winding_FindAdjacent(winding, i); - if(index != c_brush_maxFaces) - { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << degen[0].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[1].adjacent << "\n"; -#endif - winding[index].adjacent = degen[1].adjacent; - } - } - - { - Winding& winding = m_faces[degen[1].adjacent]->getWinding(); - std::size_t index = Winding_FindAdjacent(winding, i); - if(index != c_brush_maxFaces) - { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << degen[1].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[0].adjacent << "\n"; -#endif - winding[index].adjacent = degen[0].adjacent; - } - } - - degen.resize(0); - } - } - } - - /// \brief Removes edges that have the same adjacent-face as their immediate neighbour. - void removeDuplicateEdges() - { - // verify face connectivity graph - for(std::size_t i = 0; i < m_faces.size(); ++i) - { - //if(m_faces[i]->contributes()) - { - Winding& winding = m_faces[i]->getWinding(); - for(std::size_t j = 0; j != winding.numpoints;) - { - std::size_t next = Winding_next(winding, j); - if(winding[j].adjacent == winding[next].adjacent) - { -#if BRUSH_DEGENERATE_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": removed duplicate edge adjacent to face " << winding[j].adjacent << "\n"; -#endif - winding.erase(winding.begin() + next); - } - else - { - ++j; - } - } - } - } - } - - /// \brief Removes edges that do not have a matching pair in their adjacent-face. - void verifyConnectivityGraph() - { - // verify face connectivity graph - for(std::size_t i = 0; i < m_faces.size(); ++i) - { - //if(m_faces[i]->contributes()) - { - Winding& winding = m_faces[i]->getWinding(); - for(Winding::iterator j = winding.begin(); j != winding.end();) - { -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": adjacent to face " << (*j).adjacent << "\n"; -#endif - // remove unidirectional graph edges - if((*j).adjacent == c_brush_maxFaces - || Winding_FindAdjacent(m_faces[(*j).adjacent]->getWinding(), i) == c_brush_maxFaces) - { -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "Brush::buildWindings: face " << i << ": removing unidirectional connectivity graph edge adjacent to face " << (*j).adjacent << "\n"; -#endif - winding.erase(j); - } - else - { - ++j; - } - } - } - } - } - - /// \brief Returns true if the brush is a finite volume. A brush without a finite volume extends past the maximum world bounds and is not valid. - bool isBounded() - { - for(const_iterator i = begin(); i != end(); ++i) - { - if(!(*i)->is_bounded()) - { - return false; - } - } - return true; - } - - /// \brief Constructs the polygon windings for each face of the brush. Also updates the brush bounding-box and face texture-coordinates. - bool buildWindings() - { - - { - m_aabb_local = AABB(); - - for (std::size_t i = 0; i < m_faces.size(); ++i) - { - Face& f = *m_faces[i]; - - if(!plane3_valid(f.plane3()) || !plane_unique(i)) - { - f.getWinding().resize(0); - } - else - { -#if BRUSH_CONNECTIVITY_DEBUG - globalOutputStream() << "face: " << i << "\n"; -#endif - windingForClipPlane(f.getWinding(), f.plane3()); - - // update brush bounds - const Winding& winding = f.getWinding(); - for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i) - { - aabb_extend_by_point_safe(m_aabb_local, (*i).vertex); - } - - // update texture coordinates - f.EmitTextureCoordinates(); - } - } - } - - bool degenerate = !isBounded(); - - if(!degenerate) - { - // clean up connectivity information. - // these cleanups must be applied in a specific order. - removeDegenerateEdges(); - removeDegenerateFaces(); - removeDuplicateEdges(); - verifyConnectivityGraph(); - } - - return degenerate; - } - - /// \brief Constructs the face windings and updates anything that depends on them. - void buildBRep(); -}; - - - -class FaceInstance; - -class FaceInstanceSet -{ - typedef SelectionList FaceInstances; - FaceInstances m_faceInstances; -public: - void insert(FaceInstance& faceInstance) - { - m_faceInstances.append(faceInstance); - } - void erase(FaceInstance& faceInstance) - { - m_faceInstances.erase(faceInstance); - } - - template - void foreach(Functor functor) - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - functor(*(*i)); - } - } - - bool empty() const - { - return m_faceInstances.empty(); - } - FaceInstance& last() const - { - return m_faceInstances.back(); - } -}; - -extern FaceInstanceSet g_SelectedFaceInstances; - -typedef std::list VertexSelection; - -inline VertexSelection::iterator VertexSelection_find(VertexSelection& self, std::size_t value) -{ - return std::find(self.begin(), self.end(), value); -} - -inline VertexSelection::const_iterator VertexSelection_find(const VertexSelection& self, std::size_t value) -{ - return std::find(self.begin(), self.end(), value); -} - -inline VertexSelection::iterator VertexSelection_insert(VertexSelection& self, std::size_t value) -{ - VertexSelection::iterator i = VertexSelection_find(self, value); - if(i == self.end()) - { - self.push_back(value); - return --self.end(); - } - return i; -} -inline void VertexSelection_erase(VertexSelection& self, std::size_t value) -{ - VertexSelection::iterator i = VertexSelection_find(self, value); - if(i != self.end()) - { - self.erase(i); - } -} - -inline bool triangle_reversed(std::size_t x, std::size_t y, std::size_t z) -{ - return !((x < y && y < z) || (z < x && x < y) || (y < z && z < x)); -} -template -inline Vector3 triangle_cross(const BasicVector3& x, const BasicVector3 y, const BasicVector3& z) -{ - return vector3_cross(y - x, z - x); -} -template -inline bool triangles_same_winding(const BasicVector3& x1, const BasicVector3 y1, const BasicVector3& z1, const BasicVector3& x2, const BasicVector3 y2, const BasicVector3& z2) -{ - return vector3_dot(triangle_cross(x1, y1, z1), triangle_cross(x2, y2, z2)) > 0; -} - - -typedef const Plane3* PlanePointer; -typedef PlanePointer* PlanesIterator; - -class VectorLightList : public LightList -{ - typedef std::vector Lights; - Lights m_lights; -public: - void addLight(const RendererLight& light) - { - m_lights.push_back(&light); - } - void clear() - { - m_lights.clear(); - } - void evaluateLights() const - { - } - void lightsChanged() const - { - } - void forEachLight(const RendererLightCallback& callback) const - { - for(Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i) - { - callback(*(*i)); - } - } -}; - -class FaceInstance -{ - Face* m_face; - ObservedSelectable m_selectable; - ObservedSelectable m_selectableVertices; - ObservedSelectable m_selectableEdges; - SelectionChangeCallback m_selectionChanged; - - VertexSelection m_vertexSelection; - VertexSelection m_edgeSelection; - -public: - mutable VectorLightList m_lights; - - FaceInstance(Face& face, const SelectionChangeCallback& observer) : - m_face(&face), - m_selectable(SelectedChangedCaller(*this)), - m_selectableVertices(observer), - m_selectableEdges(observer), - m_selectionChanged(observer) - { - } - FaceInstance(const FaceInstance& other) : - m_face(other.m_face), - m_selectable(SelectedChangedCaller(*this)), - m_selectableVertices(other.m_selectableVertices), - m_selectableEdges(other.m_selectableEdges), - m_selectionChanged(other.m_selectionChanged) - { - } - FaceInstance& operator=(const FaceInstance& other) - { - m_face = other.m_face; - return *this; - } - - Face& getFace() - { - return *m_face; - } - const Face& getFace() const - { - return *m_face; - } - - void selectedChanged(const Selectable& selectable) - { - if(selectable.isSelected()) - { - g_SelectedFaceInstances.insert(*this); - } - else - { - g_SelectedFaceInstances.erase(*this); - } - m_selectionChanged(selectable); - } - typedef MemberCaller1 SelectedChangedCaller; - - bool selectedVertices() const - { - return !m_vertexSelection.empty(); - } - bool selectedEdges() const - { - return !m_edgeSelection.empty(); - } - bool isSelected() const - { - return m_selectable.isSelected(); - } - - bool selectedComponents() const - { - return selectedVertices() || selectedEdges() || isSelected(); - } - bool selectedComponents(SelectionSystem::EComponentMode mode) const - { - switch(mode) - { - case SelectionSystem::eVertex: - return selectedVertices(); - case SelectionSystem::eEdge: - return selectedEdges(); - case SelectionSystem::eFace: - return isSelected(); - default: - return false; - } - } - void setSelected(SelectionSystem::EComponentMode mode, bool select) - { - switch(mode) - { - case SelectionSystem::eFace: - m_selectable.setSelected(select); - break; - case SelectionSystem::eVertex: - ASSERT_MESSAGE(!select, "select-all not supported"); - - m_vertexSelection.clear(); - m_selectableVertices.setSelected(false); - break; - case SelectionSystem::eEdge: - ASSERT_MESSAGE(!select, "select-all not supported"); - - m_edgeSelection.clear(); - m_selectableEdges.setSelected(false); - break; - default: - break; - } - } - - template - void SelectedVertices_foreach(Functor functor) const - { - for(VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i) - { - std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i); - if(index != c_brush_maxFaces) - { - functor(getFace().getWinding()[index].vertex); - } - } - } - template - void SelectedEdges_foreach(Functor functor) const - { - for(VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i) - { - std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i); - if(index != c_brush_maxFaces) - { - const Winding& winding = getFace().getWinding(); - std::size_t adjacent = Winding_next(winding, index); - functor(vector3_mid(winding[index].vertex, winding[adjacent].vertex)); - } - } - } - template - void SelectedFaces_foreach(Functor functor) const - { - if(isSelected()) - { - functor(centroid()); - } - } - - template - void SelectedComponents_foreach(Functor functor) const - { - SelectedVertices_foreach(functor); - SelectedEdges_foreach(functor); - SelectedFaces_foreach(functor); - } - - void iterate_selected(AABB& aabb) const - { - SelectedComponents_foreach(AABBExtendByPoint(aabb)); - } - - class RenderablePointVectorPushBack - { - RenderablePointVector& m_points; - public: - RenderablePointVectorPushBack(RenderablePointVector& points) : m_points(points) - { - } - void operator()(const Vector3& point) const - { - const Colour4b colour_selected(0, 0, 255, 255); - m_points.push_back(pointvertex_for_windingpoint(point, colour_selected)); - } - }; - - void iterate_selected(RenderablePointVector& points) const - { - SelectedComponents_foreach(RenderablePointVectorPushBack(points)); - } - - bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const - { - return m_face->intersectVolume(volume, localToWorld); - } - - void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - if(!m_face->isFiltered() && m_face->contributes() && intersectVolume(volume, localToWorld)) - { - renderer.PushState(); - if(selectedComponents()) - { - renderer.Highlight(Renderer::eFace); - } - m_face->render(renderer, localToWorld); - renderer.PopState(); - } - } - - void testSelect(SelectionTest& test, SelectionIntersection& best) - { - if(!m_face->isFiltered()) - { - m_face->testSelect(test, best); - } - } - void testSelect(Selector& selector, SelectionTest& test) - { - SelectionIntersection best; - testSelect(test, best); - if(best.valid()) - { - Selector_add(selector, m_selectable, best); - } - } - void testSelect_centroid(Selector& selector, SelectionTest& test) - { - if(m_face->contributes() && !m_face->isFiltered()) - { - SelectionIntersection best; - m_face->testSelect_centroid(test, best); - if(best.valid()) - { - Selector_add(selector, m_selectable, best); - } - } - } - - void selectPlane(Selector& selector, const Line& line, PlanesIterator first, PlanesIterator last, const PlaneCallback& selectedPlaneCallback) - { - for(Winding::const_iterator i = getFace().getWinding().begin(); i != getFace().getWinding().end(); ++i) - { - Vector3 v(vector3_subtracted(line_closest_point(line, (*i).vertex), (*i).vertex)); - double dot = vector3_dot(getFace().plane3().normal(), v); - if(dot <= 0) - { - return; - } - } - - Selector_add(selector, m_selectable); - - selectedPlaneCallback(getFace().plane3()); - } - void selectReversedPlane(Selector& selector, const SelectedPlanes& selectedPlanes) - { - if(selectedPlanes.contains(plane3_flipped(getFace().plane3()))) - { - Selector_add(selector, m_selectable); - } - } - - void transformComponents(const Matrix4& matrix) - { - if(isSelected()) - { - m_face->transform(matrix, false); - } - if(selectedVertices()) - { - if(m_vertexSelection.size() == 1) - { - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); - m_face->assign_planepts(m_face->m_move_planeptsTransformed); - } - else if(m_vertexSelection.size() == 2) - { - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]); - m_face->assign_planepts(m_face->m_move_planeptsTransformed); - } - else if(m_vertexSelection.size() >= 3) - { - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]); - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]); - m_face->assign_planepts(m_face->m_move_planeptsTransformed); - } - } - if(selectedEdges()) - { - if(m_edgeSelection.size() == 1) - { - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]); - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); - m_face->assign_planepts(m_face->m_move_planeptsTransformed); - } - else if(m_edgeSelection.size() >= 2) - { - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]); - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); - matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]); - m_face->assign_planepts(m_face->m_move_planeptsTransformed); - } - } - } - - void snapto(float snap) - { - m_face->snapto(snap); - } - - void snapComponents(float snap) - { - if(isSelected()) - { - snapto(snap); - } - if(selectedVertices()) - { - vector3_snap(m_face->m_move_planepts[0], snap); - vector3_snap(m_face->m_move_planepts[1], snap); - vector3_snap(m_face->m_move_planepts[2], snap); - m_face->assign_planepts(m_face->m_move_planepts); - planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts); - m_face->freezeTransform(); - } - if(selectedEdges()) - { - vector3_snap(m_face->m_move_planepts[0], snap); - vector3_snap(m_face->m_move_planepts[1], snap); - vector3_snap(m_face->m_move_planepts[2], snap); - m_face->assign_planepts(m_face->m_move_planepts); - planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts); - m_face->freezeTransform(); - } - } - void update_move_planepts_vertex(std::size_t index) - { - m_face->update_move_planepts_vertex(index, m_face->m_move_planepts); - } - void update_move_planepts_vertex2(std::size_t index, std::size_t other) - { - const std::size_t numpoints = m_face->getWinding().numpoints; - ASSERT_MESSAGE(index < numpoints, "select_vertex: invalid index"); - - const std::size_t opposite = Winding_Opposite(m_face->getWinding(), index, other); - - if(triangle_reversed(index, other, opposite)) - { - std::swap(index, other); - } - - ASSERT_MESSAGE( - triangles_same_winding( - m_face->getWinding()[opposite].vertex, - m_face->getWinding()[index].vertex, - m_face->getWinding()[other].vertex, - m_face->getWinding()[0].vertex, - m_face->getWinding()[1].vertex, - m_face->getWinding()[2].vertex - ), - "update_move_planepts_vertex2: error" - ); - - m_face->m_move_planepts[0] = m_face->getWinding()[opposite].vertex; - m_face->m_move_planepts[1] = m_face->getWinding()[index].vertex; - m_face->m_move_planepts[2] = m_face->getWinding()[other].vertex; - planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate - } - void update_selection_vertex() - { - if(m_vertexSelection.size() == 0) - { - m_selectableVertices.setSelected(false); - } - else - { - m_selectableVertices.setSelected(true); - - if(m_vertexSelection.size() == 1) - { - std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin()); - - if(index != c_brush_maxFaces) - { - update_move_planepts_vertex(index); - } - } - else if(m_vertexSelection.size() == 2) - { - std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin()); - std::size_t other = Winding_FindAdjacent(getFace().getWinding(), *(++m_vertexSelection.begin())); - - if(index != c_brush_maxFaces - && other != c_brush_maxFaces) - { - update_move_planepts_vertex2(index, other); - } - } - } - } - void select_vertex(std::size_t index, bool select) - { - if(select) - { - VertexSelection_insert(m_vertexSelection, getFace().getWinding()[index].adjacent); - } - else - { - VertexSelection_erase(m_vertexSelection, getFace().getWinding()[index].adjacent); - } - - SceneChangeNotify(); - update_selection_vertex(); - } - - bool selected_vertex(std::size_t index) const - { - return VertexSelection_find(m_vertexSelection, getFace().getWinding()[index].adjacent) != m_vertexSelection.end(); - } - - void update_move_planepts_edge(std::size_t index) - { - std::size_t numpoints = m_face->getWinding().numpoints; - ASSERT_MESSAGE(index < numpoints, "select_edge: invalid index"); - - std::size_t adjacent = Winding_next(m_face->getWinding(), index); - std::size_t opposite = Winding_Opposite(m_face->getWinding(), index); - m_face->m_move_planepts[0] = m_face->getWinding()[index].vertex; - m_face->m_move_planepts[1] = m_face->getWinding()[adjacent].vertex; - m_face->m_move_planepts[2] = m_face->getWinding()[opposite].vertex; - planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate - } - void update_selection_edge() - { - if(m_edgeSelection.size() == 0) - { - m_selectableEdges.setSelected(false); - } - else - { - m_selectableEdges.setSelected(true); - - if(m_edgeSelection.size() == 1) - { - std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_edgeSelection.begin()); - - if(index != c_brush_maxFaces) - { - update_move_planepts_edge(index); - } - } - } - } - void select_edge(std::size_t index, bool select) - { - if(select) - { - VertexSelection_insert(m_edgeSelection, getFace().getWinding()[index].adjacent); - } - else - { - VertexSelection_erase(m_edgeSelection, getFace().getWinding()[index].adjacent); - } - - SceneChangeNotify(); - update_selection_edge(); - } - - bool selected_edge(std::size_t index) const - { - return VertexSelection_find(m_edgeSelection, getFace().getWinding()[index].adjacent) != m_edgeSelection.end(); - } - - const Vector3& centroid() const - { - return m_face->centroid(); - } - - void connectivityChanged() - { - // This occurs when a face is added or removed. - // The current vertex and edge selections no longer valid and must be cleared. - m_vertexSelection.clear(); - m_selectableVertices.setSelected(false); - m_edgeSelection.clear(); - m_selectableEdges.setSelected(false); - } -}; - -class BrushClipPlane : public OpenGLRenderable -{ - Plane3 m_plane; - Winding m_winding; - static Shader* m_state; -public: - static void constructStatic() - { - m_state = GlobalShaderCache().capture("$CLIPPER_OVERLAY"); - } - static void destroyStatic() - { - GlobalShaderCache().release("$CLIPPER_OVERLAY"); - } - - void setPlane(const Brush& brush, const Plane3& plane) - { - m_plane = plane; - if(plane3_valid(m_plane)) - { - brush.windingForClipPlane(m_winding, m_plane); - } - else - { - m_winding.resize(0); - } - } - - void render(RenderStateFlags state) const - { - if((state & RENDER_FILL) != 0) - { - Winding_Draw(m_winding, m_plane.normal(), state); - } - else - { - Winding_DrawWireframe(m_winding); - - // also draw a line indicating the direction of the cut - Vector3 lineverts[2]; - Winding_Centroid(m_winding, m_plane, lineverts[0]); - lineverts[1] = vector3_added(lineverts[0], vector3_scaled(m_plane.normal(), Brush::m_maxWorldCoord * 4)); - - glVertexPointer(3, GL_FLOAT, sizeof(Vector3), &lineverts[0]); - glDrawArrays(GL_LINES, 0, GLsizei(2)); - } - } - - void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - renderer.SetState(m_state, Renderer::eWireframeOnly); - renderer.SetState(m_state, Renderer::eFullMaterials); - renderer.addRenderable(*this, localToWorld); - } -}; - -inline void Face_addLight(const FaceInstance& face, const Matrix4& localToWorld, const RendererLight& light) -{ - const Plane3& facePlane = face.getFace().plane3(); - const Vector3& origin = light.aabb().origin; - Plane3 tmp(plane3_transformed(Plane3(facePlane.normal(), -facePlane.dist()), localToWorld)); - if(!plane3_test_point(tmp, origin) - || !plane3_test_point(tmp, vector3_added(origin, light.offset()))) - { - face.m_lights.addLight(light); - } -} - - - -typedef std::vector FaceInstances; - -class EdgeInstance : public Selectable -{ - FaceInstances& m_faceInstances; - SelectableEdge* m_edge; - - void select_edge(bool select) - { - FaceVertexId faceVertex = m_edge->m_faceVertex; - m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select); - faceVertex = next_edge(m_edge->m_faces, faceVertex); - m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select); - } - bool selected_edge() const - { - FaceVertexId faceVertex = m_edge->m_faceVertex; - if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex())) - { - return false; - } - faceVertex = next_edge(m_edge->m_faces, faceVertex); - if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex())) - { - return false; - } - - return true; - } - -public: - EdgeInstance(FaceInstances& faceInstances, SelectableEdge& edge) - : m_faceInstances(faceInstances), m_edge(&edge) - { - } - EdgeInstance& operator=(const EdgeInstance& other) - { - m_edge = other.m_edge; - return *this; - } - - void setSelected(bool select) - { - select_edge(select); - } - bool isSelected() const - { - return selected_edge(); - } - - - void testSelect(Selector& selector, SelectionTest& test) - { - SelectionIntersection best; - m_edge->testSelect(test, best); - if(best.valid()) - { - Selector_add(selector, *this, best); - } - } -}; - -class VertexInstance : public Selectable -{ - FaceInstances& m_faceInstances; - SelectableVertex* m_vertex; - - void select_vertex(bool select) - { - FaceVertexId faceVertex = m_vertex->m_faceVertex; - do - { - m_faceInstances[faceVertex.getFace()].select_vertex(faceVertex.getVertex(), select); - faceVertex = next_vertex(m_vertex->m_faces, faceVertex); - } - while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace()); - } - bool selected_vertex() const - { - FaceVertexId faceVertex = m_vertex->m_faceVertex; - do - { - if(!m_faceInstances[faceVertex.getFace()].selected_vertex(faceVertex.getVertex())) - { - return false; - } - faceVertex = next_vertex(m_vertex->m_faces, faceVertex); - } - while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace()); - return true; - } - -public: - VertexInstance(FaceInstances& faceInstances, SelectableVertex& vertex) - : m_faceInstances(faceInstances), m_vertex(&vertex) - { - } - VertexInstance& operator=(const VertexInstance& other) - { - m_vertex = other.m_vertex; - return *this; - } - - void setSelected(bool select) - { - select_vertex(select); - } - bool isSelected() const - { - return selected_vertex(); - } - - void testSelect(Selector& selector, SelectionTest& test) - { - SelectionIntersection best; - m_vertex->testSelect(test, best); - if(best.valid()) - { - Selector_add(selector, *this, best); - } - } -}; - -class BrushInstanceVisitor -{ -public: - virtual void visit(FaceInstance& face) const = 0; -}; - -class BrushInstance : -public BrushObserver, -public scene::Instance, -public Selectable, -public Renderable, -public SelectionTestable, -public ComponentSelectionTestable, -public ComponentEditable, -public ComponentSnappable, -public PlaneSelectable, -public LightCullable -{ - class TypeCasts - { - InstanceTypeCastTable m_casts; - public: - TypeCasts() - { - InstanceStaticCast::install(m_casts); - InstanceContainedCast::install(m_casts); - InstanceContainedCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceIdentityCast::install(m_casts); - InstanceContainedCast::install(m_casts); - } - InstanceTypeCastTable& get() - { - return m_casts; - } - }; - - - Brush& m_brush; - - FaceInstances m_faceInstances; - - typedef std::vector EdgeInstances; - EdgeInstances m_edgeInstances; - typedef std::vector VertexInstances; - VertexInstances m_vertexInstances; - - ObservedSelectable m_selectable; - - mutable RenderableWireframe m_render_wireframe; - mutable RenderablePointVector m_render_selected; - mutable AABB m_aabb_component; - mutable Array m_faceCentroidPointsCulled; - RenderablePointArray m_render_faces_wireframe; - mutable bool m_viewChanged; // requires re-evaluation of view-dependent cached data - - BrushClipPlane m_clipPlane; - - static Shader* m_state_selpoint; - - const LightList* m_lightList; - - TransformModifier m_transform; - - BrushInstance(const BrushInstance& other); // NOT COPYABLE - BrushInstance& operator=(const BrushInstance& other); // NOT ASSIGNABLE -public: - static Counter* m_counter; - - typedef LazyStatic StaticTypeCasts; - - void lightsChanged() - { - m_lightList->lightsChanged(); - } - typedef MemberCaller LightsChangedCaller; - - STRING_CONSTANT(Name, "BrushInstance"); - - BrushInstance(const scene::Path& path, scene::Instance* parent, Brush& brush) : - Instance(path, parent, this, StaticTypeCasts::instance().get()), - m_brush(brush), - m_selectable(SelectedChangedCaller(*this)), - m_render_selected(GL_POINTS), - m_render_faces_wireframe(m_faceCentroidPointsCulled, GL_POINTS), - m_viewChanged(false), - m_transform(Brush::TransformChangedCaller(m_brush), ApplyTransformCaller(*this)) - { - m_brush.instanceAttach(Instance::path()); - m_brush.attach(*this); - m_counter->increment(); - - m_lightList = &GlobalShaderCache().attach(*this); - m_brush.m_lightsChanged = LightsChangedCaller(*this); ///\todo Make this work with instancing. - - Instance::setTransformChangedCallback(LightsChangedCaller(*this)); - } - ~BrushInstance() - { - Instance::setTransformChangedCallback(Callback()); - - m_brush.m_lightsChanged = Callback(); - GlobalShaderCache().detach(*this); - - m_counter->decrement(); - m_brush.detach(*this); - m_brush.instanceDetach(Instance::path()); - } - - Brush& getBrush() - { - return m_brush; - } - const Brush& getBrush() const - { - return m_brush; - } - - Bounded& get(NullType) - { - return m_brush; - } - Cullable& get(NullType) - { - return m_brush; - } - Transformable& get(NullType) - { - return m_transform; - } - - void selectedChanged(const Selectable& selectable) - { - GlobalSelectionSystem().getObserver(SelectionSystem::ePrimitive)(selectable); - GlobalSelectionSystem().onSelectedChanged(*this, selectable); - - Instance::selectedChanged(); - } - typedef MemberCaller1 SelectedChangedCaller; - - void selectedChangedComponent(const Selectable& selectable) - { - GlobalSelectionSystem().getObserver(SelectionSystem::eComponent)(selectable); - GlobalSelectionSystem().onComponentSelection(*this, selectable); - } - typedef MemberCaller1 SelectedChangedComponentCaller; - - const BrushInstanceVisitor& forEachFaceInstance(const BrushInstanceVisitor& visitor) - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - visitor.visit(*i); - } - return visitor; - } - - static void constructStatic() - { - m_state_selpoint = GlobalShaderCache().capture("$SELPOINT"); - } - static void destroyStatic() - { - GlobalShaderCache().release("$SELPOINT"); - } - - void clear() - { - m_faceInstances.clear(); - } - void reserve(std::size_t size) - { - m_faceInstances.reserve(size); - } - - void push_back(Face& face) - { - m_faceInstances.push_back(FaceInstance(face, SelectedChangedComponentCaller(*this))); - } - void pop_back() - { - ASSERT_MESSAGE(!m_faceInstances.empty(), "erasing invalid element"); - m_faceInstances.pop_back(); - } - void erase(std::size_t index) - { - ASSERT_MESSAGE(index < m_faceInstances.size(), "erasing invalid element"); - m_faceInstances.erase(m_faceInstances.begin() + index); - } - void connectivityChanged() - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).connectivityChanged(); - } - } - - void edge_clear() - { - m_edgeInstances.clear(); - } - void edge_push_back(SelectableEdge& edge) - { - m_edgeInstances.push_back(EdgeInstance(m_faceInstances, edge)); - } - - void vertex_clear() - { - m_vertexInstances.clear(); - } - void vertex_push_back(SelectableVertex& vertex) - { - m_vertexInstances.push_back(VertexInstance(m_faceInstances, vertex)); - } - - void DEBUG_verify() const - { - ASSERT_MESSAGE(m_faceInstances.size() == m_brush.DEBUG_size(), "FATAL: mismatch"); - } - - bool isSelected() const - { - return m_selectable.isSelected(); - } - void setSelected(bool select) - { - m_selectable.setSelected(select); - } - - void update_selected() const - { - m_render_selected.clear(); - for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - if((*i).getFace().contributes()) - { - (*i).iterate_selected(m_render_selected); - } - } - } - - void evaluateViewDependent(const VolumeTest& volume, const Matrix4& localToWorld) const - { - if(m_viewChanged) - { - m_viewChanged = false; - - bool faces_visible[c_brush_maxFaces]; - { - bool* j = faces_visible; - for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i, ++j) - { - *j = (*i).intersectVolume(volume, localToWorld); - } - } - - m_brush.update_wireframe(m_render_wireframe, faces_visible); - m_brush.update_faces_wireframe(m_faceCentroidPointsCulled, faces_visible); - } - } - - void renderComponentsSelected(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - m_brush.evaluateBRep(); - - update_selected(); - if(!m_render_selected.empty()) - { - renderer.Highlight(Renderer::ePrimitive, false); - renderer.SetState(m_state_selpoint, Renderer::eWireframeOnly); - renderer.SetState(m_state_selpoint, Renderer::eFullMaterials); - renderer.addRenderable(m_render_selected, localToWorld); - } - } - - void renderComponents(Renderer& renderer, const VolumeTest& volume) const - { - m_brush.evaluateBRep(); - - const Matrix4& localToWorld = Instance::localToWorld(); - - renderer.SetState(m_brush.m_state_point, Renderer::eWireframeOnly); - renderer.SetState(m_brush.m_state_point, Renderer::eFullMaterials); - - if(volume.fill() && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace) - { - evaluateViewDependent(volume, localToWorld); - renderer.addRenderable(m_render_faces_wireframe, localToWorld); - } - else - { - m_brush.renderComponents(GlobalSelectionSystem().ComponentMode(), renderer, volume, localToWorld); - } - } - - void renderClipPlane(Renderer& renderer, const VolumeTest& volume) const - { - if(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip && isSelected()) - { - m_clipPlane.render(renderer, volume, localToWorld()); - } - } - - void renderCommon(Renderer& renderer, const VolumeTest& volume) const - { - bool componentMode = GlobalSelectionSystem().Mode() == SelectionSystem::eComponent; - - if(componentMode && isSelected()) - { - renderComponents(renderer, volume); - } - - if(parentSelected()) - { - if(!componentMode) - { - renderer.Highlight(Renderer::eFace); - } - renderer.Highlight(Renderer::ePrimitive); - } - } - - void renderSolid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - //renderCommon(renderer, volume); - - m_lightList->evaluateLights(); - - for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - renderer.setLights((*i).m_lights); - (*i).render(renderer, volume, localToWorld); - } - - renderComponentsSelected(renderer, volume, localToWorld); - } - - void renderWireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - //renderCommon(renderer, volume); - - evaluateViewDependent(volume, localToWorld); - - if(m_render_wireframe.m_size != 0) - { - renderer.addRenderable(m_render_wireframe, localToWorld); - } - - renderComponentsSelected(renderer, volume, localToWorld); - } - - void renderSolid(Renderer& renderer, const VolumeTest& volume) const - { - m_brush.evaluateBRep(); - - renderClipPlane(renderer, volume); - - renderSolid(renderer, volume, localToWorld()); - } - - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const - { - m_brush.evaluateBRep(); - - renderClipPlane(renderer, volume); - - renderWireframe(renderer, volume, localToWorld()); - } - - void viewChanged() const - { - m_viewChanged = true; - } - - void testSelect(Selector& selector, SelectionTest& test) - { - test.BeginMesh(localToWorld()); - - SelectionIntersection best; - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).testSelect(test, best); - } - if(best.valid()) - { - selector.addIntersection(best); - } - } - - bool isSelectedComponents() const - { - for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - if((*i).selectedComponents()) - { - return true; - } - } - return false; - } - void setSelectedComponents(bool select, SelectionSystem::EComponentMode mode) - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).setSelected(mode, select); - } - } - void testSelectComponents(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) - { - test.BeginMesh(localToWorld()); - - switch(mode) - { - case SelectionSystem::eVertex: - { - for(VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i) - { - (*i).testSelect(selector, test); - } - } - break; - case SelectionSystem::eEdge: - { - for(EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i) - { - (*i).testSelect(selector, test); - } - } - break; - case SelectionSystem::eFace: - { - if(test.getVolume().fill()) - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).testSelect(selector, test); - } - } - else - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).testSelect_centroid(selector, test); - } - } - } - break; - default: - break; - } - } - - void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) - { - test.BeginMesh(localToWorld()); - - PlanePointer brushPlanes[c_brush_maxFaces]; - PlanesIterator j = brushPlanes; - - for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i) - { - *j++ = &(*i)->plane3(); - } - - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).selectPlane(selector, Line(test.getNear(), test.getFar()), brushPlanes, j, selectedPlaneCallback); - } - } - void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).selectReversedPlane(selector, selectedPlanes); - } - } - - - void transformComponents(const Matrix4& matrix) - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).transformComponents(matrix); - } - } - const AABB& getSelectedComponentsBounds() const - { - m_aabb_component = AABB(); - - for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).iterate_selected(m_aabb_component); - } - - return m_aabb_component; - } - - void snapComponents(float snap) - { - for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).snapComponents(snap); - } - } - void evaluateTransform() - { - Matrix4 matrix(m_transform.calculateTransform()); - //globalOutputStream() << "matrix: " << matrix << "\n"; - - if(m_transform.getType() == TRANSFORM_PRIMITIVE) - { - m_brush.transform(matrix); - } - else - { - transformComponents(matrix); - } - } - void applyTransform() - { - m_brush.revertTransform(); - evaluateTransform(); - m_brush.freezeTransform(); - } - typedef MemberCaller ApplyTransformCaller; - - void setClipPlane(const Plane3& plane) - { - m_clipPlane.setPlane(m_brush, plane); - } - - bool testLight(const RendererLight& light) const - { - return light.testAABB(worldAABB()); - } - void insertLight(const RendererLight& light) - { - const Matrix4& localToWorld = Instance::localToWorld(); - for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - Face_addLight(*i, localToWorld, light); - } - } - void clearLights() - { - for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) - { - (*i).m_lights.clear(); - } - } -}; - -inline BrushInstance* Instance_getBrush(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); -} - - -template -class BrushSelectedVisitor : public SelectionSystem::Visitor -{ - const Functor& m_functor; -public: - BrushSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - BrushInstance* brush = Instance_getBrush(instance); - if(brush != 0) - { - m_functor(*brush); - } - } -}; - -template -inline const Functor& Scene_forEachSelectedBrush(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(BrushSelectedVisitor(functor)); - return functor; -} - -template -class BrushVisibleSelectedVisitor : public SelectionSystem::Visitor -{ - const Functor& m_functor; -public: - BrushVisibleSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - BrushInstance* brush = Instance_getBrush(instance); - if(brush != 0 - && instance.path().top().get().visible()) - { - m_functor(*brush); - } - } -}; - -template -inline const Functor& Scene_forEachVisibleSelectedBrush(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(BrushVisibleSelectedVisitor(functor)); - return functor; -} - -class BrushForEachFace -{ - const BrushInstanceVisitor& m_visitor; -public: - BrushForEachFace(const BrushInstanceVisitor& visitor) : m_visitor(visitor) - { - } - void operator()(BrushInstance& brush) const - { - brush.forEachFaceInstance(m_visitor); - } -}; - -template -class FaceInstanceVisitFace : public BrushInstanceVisitor -{ - const Functor& functor; -public: - FaceInstanceVisitFace(const Functor& functor) - : functor(functor) - { - } - void visit(FaceInstance& face) const - { - functor(face.getFace()); - } -}; - -template -inline const Functor& Brush_forEachFace(BrushInstance& brush, const Functor& functor) -{ - brush.forEachFaceInstance(FaceInstanceVisitFace(functor)); - return functor; -} - -template -class FaceVisitAll : public BrushVisitor -{ - const Functor& functor; -public: - FaceVisitAll(const Functor& functor) - : functor(functor) - { - } - void visit(Face& face) const - { - functor(face); - } -}; - -template -inline const Functor& Brush_forEachFace(const Brush& brush, const Functor& functor) -{ - brush.forEachFace(FaceVisitAll(functor)); - return functor; -} - -template -inline const Functor& Brush_forEachFace(Brush& brush, const Functor& functor) -{ - brush.forEachFace(FaceVisitAll(functor)); - return functor; -} - -template -class FaceInstanceVisitAll : public BrushInstanceVisitor -{ - const Functor& functor; -public: - FaceInstanceVisitAll(const Functor& functor) - : functor(functor) - { - } - void visit(FaceInstance& face) const - { - functor(face); - } -}; - -template -inline const Functor& Brush_ForEachFaceInstance(BrushInstance& brush, const Functor& functor) -{ - brush.forEachFaceInstance(FaceInstanceVisitAll(functor)); - return functor; -} - -template -inline const Functor& Scene_forEachBrush(scene::Graph& graph, const Functor& functor) -{ - graph.traverse(InstanceWalker< InstanceApply >(functor)); - return functor; -} - -template -class InstanceIfVisible : public Functor -{ -public: - InstanceIfVisible(const Functor& functor) : Functor(functor) - { - } - void operator()(scene::Instance& instance) - { - if(instance.path().top().get().visible()) - { - Functor::operator()(instance); - } - } -}; - -template -class BrushVisibleWalker : public scene::Graph::Walker -{ - const Functor& m_functor; -public: - BrushVisibleWalker(const Functor& functor) : m_functor(functor) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - BrushInstance* brush = Instance_getBrush(instance); - if(brush != 0) - { - m_functor(*brush); - } - } - return true; - } -}; - -template -inline const Functor& Scene_forEachVisibleBrush(scene::Graph& graph, const Functor& functor) -{ - graph.traverse(BrushVisibleWalker(functor)); - return functor; -} - -template -inline const Functor& Scene_ForEachBrush_ForEachFace(scene::Graph& graph, const Functor& functor) -{ - Scene_forEachBrush(graph, BrushForEachFace(FaceInstanceVisitFace(functor))); - return functor; -} - -// d1223m -template -inline const Functor& Scene_ForEachBrush_ForEachFaceInstance(scene::Graph& graph, const Functor& functor) -{ - Scene_forEachBrush(graph, BrushForEachFace(FaceInstanceVisitAll(functor))); - return functor; -} - -template -inline const Functor& Scene_ForEachSelectedBrush_ForEachFace(scene::Graph& graph, const Functor& functor) -{ - Scene_forEachSelectedBrush(BrushForEachFace(FaceInstanceVisitFace(functor))); - return functor; -} - -template -inline const Functor& Scene_ForEachSelectedBrush_ForEachFaceInstance(scene::Graph& graph, const Functor& functor) -{ - Scene_forEachSelectedBrush(BrushForEachFace(FaceInstanceVisitAll(functor))); - return functor; -} - -template -class FaceVisitorWrapper -{ - const Functor& functor; -public: - FaceVisitorWrapper(const Functor& functor) : functor(functor) - { - } - - void operator()(FaceInstance& faceInstance) const - { - functor(faceInstance.getFace()); - } -}; - -template -inline const Functor& Scene_ForEachSelectedBrushFace(scene::Graph& graph, const Functor& functor) -{ - g_SelectedFaceInstances.foreach(FaceVisitorWrapper(functor)); - return functor; -} - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brush_primit.cpp b/misc/mediasource/extra/netradiant-src/radiant/brush_primit.cpp deleted file mode 100644 index 02b821dd..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brush_primit.cpp +++ /dev/null @@ -1,1466 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "brush_primit.h" - -#include "debugging/debugging.h" - -#include "itexdef.h" -#include "itextures.h" - -#include - -#include "stringio.h" -#include "texturelib.h" -#include "math/matrix.h" -#include "math/plane.h" -#include "math/aabb.h" - -#include "winding.h" -#include "preferences.h" - - -/*! -\brief Construct a transform from XYZ space to ST space (3d to 2d). -This will be one of three axis-aligned spaces, depending on the surface normal. -NOTE: could also be done by swapping values. -*/ -void Normal_GetTransform(const Vector3& normal, Matrix4& transform) -{ - switch (projectionaxis_for_normal(normal)) - { - case eProjectionAxisZ: - transform[0] = 1; - transform[1] = 0; - transform[2] = 0; - - transform[4] = 0; - transform[5] = 1; - transform[6] = 0; - - transform[8] = 0; - transform[9] = 0; - transform[10] = 1; - break; - case eProjectionAxisY: - transform[0] = 1; - transform[1] = 0; - transform[2] = 0; - - transform[4] = 0; - transform[5] = 0; - transform[6] = -1; - - transform[8] = 0; - transform[9] = 1; - transform[10] = 0; - break; - case eProjectionAxisX: - transform[0] = 0; - transform[1] = 0; - transform[2] = 1; - - transform[4] = 1; - transform[5] = 0; - transform[6] = 0; - - transform[8] = 0; - transform[9] = 1; - transform[10] = 0; - break; - } - transform[3] = transform[7] = transform[11] = transform[12] = transform[13] = transform[14] = 0; - transform[15] = 1; -} - -/*! -\brief Construct a transform in ST space from the texdef. -Transforms constructed from quake's texdef format are (-shift)*(1/scale)*(-rotate) with x translation sign flipped. -This would really make more sense if it was inverseof(shift*rotate*scale).. oh well. -*/ -inline void Texdef_toTransform(const texdef_t& texdef, float width, float height, Matrix4& transform) -{ - double inverse_scale[2]; - - // transform to texdef shift/scale/rotate - inverse_scale[0] = 1 / (texdef.scale[0] * width); - inverse_scale[1] = 1 / (texdef.scale[1] * -height); - transform[12] = texdef.shift[0] / width; - transform[13] = -texdef.shift[1] / -height; - double c = cos(degrees_to_radians(-texdef.rotate)); - double s = sin(degrees_to_radians(-texdef.rotate)); - transform[0] = static_cast(c * inverse_scale[0]); - transform[1] = static_cast(s * inverse_scale[1]); - transform[4] = static_cast(-s * inverse_scale[0]); - transform[5] = static_cast(c * inverse_scale[1]); - transform[2] = transform[3] = transform[6] = transform[7] = transform[8] = transform[9] = transform[11] = transform[14] = 0; - transform[10] = transform[15] = 1; -} - -inline void BPTexdef_toTransform(const brushprimit_texdef_t& bp_texdef, Matrix4& transform) -{ - transform = g_matrix4_identity; - transform.xx() = bp_texdef.coords[0][0]; - transform.yx() = bp_texdef.coords[0][1]; - transform.tx() = bp_texdef.coords[0][2]; - transform.xy() = bp_texdef.coords[1][0]; - transform.yy() = bp_texdef.coords[1][1]; - transform.ty() = bp_texdef.coords[1][2]; -} - -inline void Texdef_toTransform(const TextureProjection& projection, float width, float height, Matrix4& transform) -{ - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - BPTexdef_toTransform(projection.m_brushprimit_texdef, transform); - } - else - { - Texdef_toTransform(projection.m_texdef, width, height, transform); - } -} - -// handles degenerate cases, just in case library atan2 doesn't -inline double arctangent_yx(double y, double x) -{ - if(fabs(x) > 1.0E-6) - { - return atan2(y, x); - } - else if(y > 0) - { - return c_half_pi; - } - else - { - return -c_half_pi; - } -} - -inline void Texdef_fromTransform(texdef_t& texdef, float width, float height, const Matrix4& transform) -{ - texdef.scale[0] = static_cast((1.0 / vector2_length(Vector2(transform[0], transform[4]))) / width); - texdef.scale[1] = static_cast((1.0 / vector2_length(Vector2(transform[1], transform[5]))) / height); - - texdef.rotate = static_cast(-radians_to_degrees(arctangent_yx(-transform[4], transform[0]))); - - if(texdef.rotate == -180.0f) - { - texdef.rotate = 180.0f; - } - - texdef.shift[0] = transform[12] * width; - texdef.shift[1] = transform[13] * height; - - // If the 2d cross-product of the x and y axes is positive, one of the axes has a negative scale. - if(vector2_cross(Vector2(transform[0], transform[4]), Vector2(transform[1], transform[5])) > 0) - { - if(texdef.rotate >= 180.0f) - { - texdef.rotate -= 180.0f; - texdef.scale[0] = -texdef.scale[0]; - } - else - { - texdef.scale[1] = -texdef.scale[1]; - } - } - //globalOutputStream() << "fromTransform: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n"; -} - -inline void BPTexdef_fromTransform(brushprimit_texdef_t& bp_texdef, const Matrix4& transform) -{ - bp_texdef.coords[0][0] = transform.xx(); - bp_texdef.coords[0][1] = transform.yx(); - bp_texdef.coords[0][2] = transform.tx(); - bp_texdef.coords[1][0] = transform.xy(); - bp_texdef.coords[1][1] = transform.yy(); - bp_texdef.coords[1][2] = transform.ty(); -} - -inline void Texdef_fromTransform(TextureProjection& projection, float width, float height, const Matrix4& transform) -{ - ASSERT_MESSAGE((transform[0] != 0 || transform[4] != 0) - && (transform[1] != 0 || transform[5] != 0), "invalid texture matrix"); - - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - BPTexdef_fromTransform(projection.m_brushprimit_texdef, transform); - } - else - { - Texdef_fromTransform(projection.m_texdef, width, height, transform); - } -} - -inline void Texdef_normalise(texdef_t& texdef, float width, float height) -{ - // it may be useful to also normalise the rotation here, if this function is used elsewhere. - texdef.shift[0] = float_mod(texdef.shift[0], width); - texdef.shift[1] = float_mod(texdef.shift[1], height); - //globalOutputStream() << "normalise: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n"; -} - -inline void BPTexdef_normalise(brushprimit_texdef_t& bp_texdef, float width, float height) -{ - bp_texdef.coords[0][2] = float_mod(bp_texdef.coords[0][2], width); - bp_texdef.coords[1][2] = float_mod(bp_texdef.coords[1][2], height); -} - -/// \brief Normalise \p projection for a given texture \p width and \p height. -/// -/// All texture-projection translation (shift) values are congruent modulo the dimensions of the texture. -/// This function normalises shift values to the smallest positive congruent values. -void Texdef_normalise(TextureProjection& projection, float width, float height) -{ - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - BPTexdef_normalise(projection.m_brushprimit_texdef, width, height); - } - else - { - Texdef_normalise(projection.m_texdef, width, height); - } -} - -void ComputeAxisBase(const Vector3& normal, Vector3& texS, Vector3& texT); - -inline void DebugAxisBase(const Vector3& normal) -{ - Vector3 x, y; - ComputeAxisBase(normal, x, y); - globalOutputStream() << "BP debug: " << x << y << normal << "\n"; -} - -void Texdef_basisForNormal(const TextureProjection& projection, const Vector3& normal, Matrix4& basis) -{ - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - basis = g_matrix4_identity; - ComputeAxisBase(normal, vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y())); - vector4_to_vector3(basis.z()) = normal; - matrix4_transpose(basis); - //DebugAxisBase(normal); - } - else if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) - { - basis = g_matrix4_identity; - vector4_to_vector3(basis.x()) = projection.m_basis_s; - vector4_to_vector3(basis.y()) = vector3_negated(projection.m_basis_t); - vector4_to_vector3(basis.z()) = vector3_normalised(vector3_cross(vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y()))); - matrix4_multiply_by_matrix4(basis, matrix4_rotation_for_z_degrees(-projection.m_texdef.rotate)); - //globalOutputStream() << "debug: " << projection.m_basis_s << projection.m_basis_t << normal << "\n"; - matrix4_transpose(basis); - } - else - { - Normal_GetTransform(normal, basis); - } -} - -void Texdef_EmitTextureCoordinates(const TextureProjection& projection, std::size_t width, std::size_t height, Winding& w, const Vector3& normal, const Matrix4& localToWorld) -{ - if(w.numpoints < 3) - { - return; - } - //globalOutputStream() << "normal: " << normal << "\n"; - - Matrix4 local2tex; - Texdef_toTransform(projection, (float)width, (float)height, local2tex); - //globalOutputStream() << "texdef: " << static_cast(local2tex.x()) << static_cast(local2tex.y()) << "\n"; - -#if 0 - { - TextureProjection tmp; - Texdef_fromTransform(tmp, (float)width, (float)height, local2tex); - Matrix4 tmpTransform; - Texdef_toTransform(tmp, (float)width, (float)height, tmpTransform); - ASSERT_MESSAGE(matrix4_equal_epsilon(local2tex, tmpTransform, 0.0001f), "bleh"); - } -#endif - - { - Matrix4 xyz2st; - // we don't care if it's not normalised... - Texdef_basisForNormal(projection, matrix4_transformed_direction(localToWorld, normal), xyz2st); - //globalOutputStream() << "basis: " << static_cast(xyz2st.x()) << static_cast(xyz2st.y()) << static_cast(xyz2st.z()) << "\n"; - matrix4_multiply_by_matrix4(local2tex, xyz2st); - } - - Vector3 tangent(vector3_normalised(vector4_to_vector3(matrix4_transposed(local2tex).x()))); - Vector3 bitangent(vector3_normalised(vector4_to_vector3(matrix4_transposed(local2tex).y()))); - - matrix4_multiply_by_matrix4(local2tex, localToWorld); - - for(Winding::iterator i = w.begin(); i != w.end(); ++i) - { - Vector3 texcoord = matrix4_transformed_point(local2tex, (*i).vertex); - (*i).texcoord[0] = texcoord[0]; - (*i).texcoord[1] = texcoord[1]; - - (*i).tangent = tangent; - (*i).bitangent = bitangent; - } -} - -/*! -\brief Provides the axis-base of the texture ST space for this normal, -as they had been transformed to world XYZ space. -*/ -void TextureAxisFromNormal(const Vector3& normal, Vector3& s, Vector3& t) -{ - switch (projectionaxis_for_normal(normal)) - { - case eProjectionAxisZ: - s[0] = 1; - s[1] = 0; - s[2] = 0; - - t[0] = 0; - t[1] = -1; - t[2] = 0; - - break; - case eProjectionAxisY: - s[0] = 1; - s[1] = 0; - s[2] = 0; - - t[0] = 0; - t[1] = 0; - t[2] = -1; - - break; - case eProjectionAxisX: - s[0] = 0; - s[1] = 1; - s[2] = 0; - - t[0] = 0; - t[1] = 0; - t[2] = -1; - - break; - } -} - -void Texdef_Assign(texdef_t& td, const texdef_t& other) -{ - td = other; -} - -void Texdef_Shift(texdef_t& td, float s, float t) -{ - td.shift[0] += s; - td.shift[1] += t; -} - -void Texdef_Scale(texdef_t& td, float s, float t) -{ - td.scale[0] += s; - td.scale[1] += t; -} - -void Texdef_Rotate(texdef_t& td, float angle) -{ - td.rotate += angle; - td.rotate = static_cast(float_to_integer(td.rotate) % 360); -} - -// NOTE: added these from Ritual's Q3Radiant -void ClearBounds(Vector3& mins, Vector3& maxs) -{ - mins[0] = mins[1] = mins[2] = 99999; - maxs[0] = maxs[1] = maxs[2] = -99999; -} - -void AddPointToBounds(const Vector3& v, Vector3& mins, Vector3& maxs) -{ - int i; - float val; - - for (i=0 ; i<3 ; i++) - { - val = v[i]; - if (val < mins[i]) - mins[i] = val; - if (val > maxs[i]) - maxs[i] = val; - } -} - -template -inline BasicVector3 vector3_inverse(const BasicVector3& self) -{ - return BasicVector3( - Element(1.0 / self.x()), - Element(1.0 / self.y()), - Element(1.0 / self.z()) - ); -} - -// low level functions .. put in mathlib? -#define BPMatCopy(a,b) {b[0][0] = a[0][0]; b[0][1] = a[0][1]; b[0][2] = a[0][2]; b[1][0] = a[1][0]; b[1][1] = a[1][1]; b[1][2] = a[1][2];} -// apply a scale transformation to the BP matrix -#define BPMatScale(m,sS,sT) {m[0][0]*=sS; m[1][0]*=sS; m[0][1]*=sT; m[1][1]*=sT;} -// apply a translation transformation to a BP matrix -#define BPMatTranslate(m,s,t) {m[0][2] += m[0][0]*s + m[0][1]*t; m[1][2] += m[1][0]*s+m[1][1]*t;} -// 2D homogeneous matrix product C = A*B -void BPMatMul(float A[2][3], float B[2][3], float C[2][3]); -// apply a rotation (degrees) -void BPMatRotate(float A[2][3], float theta); -#ifdef _DEBUG -void BPMatDump(float A[2][3]); -#endif - -#ifdef _DEBUG -//#define DBG_BP -#endif - - -bp_globals_t g_bp_globals; -float g_texdef_default_scale; - -// compute a determinant using Sarrus rule -//++timo "inline" this with a macro -// NOTE : the three vectors are understood as columns of the matrix -inline float SarrusDet(const Vector3& a, const Vector3& b, const Vector3& c) -{ - return a[0]*b[1]*c[2]+b[0]*c[1]*a[2]+c[0]*a[1]*b[2] - -c[0]*b[1]*a[2]-a[1]*b[0]*c[2]-a[0]*b[2]*c[1]; -} - -// in many case we know three points A,B,C in two axis base B1 and B2 -// and we want the matrix M so that A(B1) = T * A(B2) -// NOTE: 2D homogeneous space stuff -// NOTE: we don't do any check to see if there's a solution or we have a particular case .. need to make sure before calling -// NOTE: the third coord of the A,B,C point is ignored -// NOTE: see the commented out section to fill M and D -//++timo TODO: update the other members to use this when possible -void MatrixForPoints( Vector3 M[3], Vector3 D[2], brushprimit_texdef_t *T ) -{ -// Vector3 M[3]; // columns of the matrix .. easier that way (the indexing is not standard! it's column-line .. later computations are easier that way) - float det; -// Vector3 D[2]; - M[2][0]=1.0f; M[2][1]=1.0f; M[2][2]=1.0f; -#if 0 - // fill the data vectors - M[0][0]=A2[0]; M[0][1]=B2[0]; M[0][2]=C2[0]; - M[1][0]=A2[1]; M[1][1]=B2[1]; M[1][2]=C2[1]; - M[2][0]=1.0f; M[2][1]=1.0f; M[2][2]=1.0f; - D[0][0]=A1[0]; - D[0][1]=B1[0]; - D[0][2]=C1[0]; - D[1][0]=A1[1]; - D[1][1]=B1[1]; - D[1][2]=C1[1]; -#endif - // solve - det = SarrusDet( M[0], M[1], M[2] ); - T->coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det; - T->coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det; - T->coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det; - T->coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det; - T->coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det; - T->coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det; -} - -//++timo replace everywhere texX by texS etc. ( ----> and in q3map !) -// NOTE : ComputeAxisBase here and in q3map code must always BE THE SAME ! -// WARNING : special case behaviour of atan2(y,x) <-> atan(y/x) might not be the same everywhere when x == 0 -// rotation by (0,RotY,RotZ) assigns X to normal -void ComputeAxisBase(const Vector3& normal, Vector3& texS, Vector3& texT) -{ -#if 1 - const Vector3 up(0, 0, 1); - const Vector3 down(0, 0, -1); - - if(vector3_equal_epsilon(normal, up, float(1e-6))) - { - texS = Vector3(0, 1, 0); - texT = Vector3(1, 0, 0); - } - else if(vector3_equal_epsilon(normal, down, float(1e-6))) - { - texS = Vector3(0, 1, 0); - texT = Vector3(-1, 0, 0); - } - else - { - texS = vector3_normalised(vector3_cross(normal, up)); - texT = vector3_normalised(vector3_cross(normal, texS)); - vector3_negate(texS); - } - -#else - float RotY,RotZ; - // do some cleaning - /* - if (fabs(normal[0])<1e-6) - normal[0]=0.0f; - if (fabs(normal[1])<1e-6) - normal[1]=0.0f; - if (fabs(normal[2])<1e-6) - normal[2]=0.0f; - */ - RotY=-atan2(normal[2],sqrt(normal[1]*normal[1]+normal[0]*normal[0])); - RotZ=atan2(normal[1],normal[0]); - // rotate (0,1,0) and (0,0,1) to compute texS and texT - texS[0]=-sin(RotZ); - texS[1]=cos(RotZ); - texS[2]=0; - // the texT vector is along -Z ( T texture coorinates axis ) - texT[0]=-sin(RotY)*cos(RotZ); - texT[1]=-sin(RotY)*sin(RotZ); - texT[2]=-cos(RotY); -#endif -} - -#if 0 // texdef conversion -void FaceToBrushPrimitFace(face_t *f) -{ - Vector3 texX,texY; - Vector3 proj; - // ST of (0,0) (1,0) (0,1) - float ST[3][5]; // [ point index ] [ xyz ST ] - //++timo not used as long as brushprimit_texdef and texdef are static -/* f->brushprimit_texdef.contents=f->texdef.contents; - f->brushprimit_texdef.flags=f->texdef.flags; - f->brushprimit_texdef.value=f->texdef.value; - strcpy(f->brushprimit_texdef.name,f->texdef.name); */ -#ifdef DBG_BP - if ( f->plane.normal[0]==0.0f && f->plane.normal[1]==0.0f && f->plane.normal[2]==0.0f ) - { - globalOutputStream() << "Warning : f->plane.normal is (0,0,0) in FaceToBrushPrimitFace\n"; - } - // check d_texture - if (!f->d_texture) - { - globalOutputStream() << "Warning : f.d_texture is 0 in FaceToBrushPrimitFace\n"; - return; - } -#endif - // compute axis base - ComputeAxisBase(f->plane.normal,texX,texY); - // compute projection vector - VectorCopy(f->plane.normal,proj); - VectorScale(proj,f->plane.dist,proj); - // (0,0) in plane axis base is (0,0,0) in world coordinates + projection on the affine plane - // (1,0) in plane axis base is texX in world coordinates + projection on the affine plane - // (0,1) in plane axis base is texY in world coordinates + projection on the affine plane - // use old texture code to compute the ST coords of these points - VectorCopy(proj,ST[0]); - EmitTextureCoordinates(ST[0], f->pShader->getTexture(), f); - VectorCopy(texX,ST[1]); - VectorAdd(ST[1],proj,ST[1]); - EmitTextureCoordinates(ST[1], f->pShader->getTexture(), f); - VectorCopy(texY,ST[2]); - VectorAdd(ST[2],proj,ST[2]); - EmitTextureCoordinates(ST[2], f->pShader->getTexture(), f); - // compute texture matrix - f->brushprimit_texdef.coords[0][2]=ST[0][3]; - f->brushprimit_texdef.coords[1][2]=ST[0][4]; - f->brushprimit_texdef.coords[0][0]=ST[1][3]-f->brushprimit_texdef.coords[0][2]; - f->brushprimit_texdef.coords[1][0]=ST[1][4]-f->brushprimit_texdef.coords[1][2]; - f->brushprimit_texdef.coords[0][1]=ST[2][3]-f->brushprimit_texdef.coords[0][2]; - f->brushprimit_texdef.coords[1][1]=ST[2][4]-f->brushprimit_texdef.coords[1][2]; -} - -// compute texture coordinates for the winding points -void EmitBrushPrimitTextureCoordinates(face_t * f, Winding * w) -{ - Vector3 texX,texY; - float x,y; - // compute axis base - ComputeAxisBase(f->plane.normal,texX,texY); - // in case the texcoords matrix is empty, build a default one - // same behaviour as if scale[0]==0 && scale[1]==0 in old code - if (f->brushprimit_texdef.coords[0][0]==0 && f->brushprimit_texdef.coords[1][0]==0 && f->brushprimit_texdef.coords[0][1]==0 && f->brushprimit_texdef.coords[1][1]==0) - { - f->brushprimit_texdef.coords[0][0] = 1.0f; - f->brushprimit_texdef.coords[1][1] = 1.0f; - ConvertTexMatWithQTexture( &f->brushprimit_texdef, 0, &f->brushprimit_texdef, f->pShader->getTexture() ); - } - int i; - for (i=0 ; ibrushprimit_texdef.coords[0][0]*x+f->brushprimit_texdef.coords[0][1]*y+f->brushprimit_texdef.coords[0][2]; - float T=f->brushprimit_texdef.coords[1][0]*x+f->brushprimit_texdef.coords[1][1]*y+f->brushprimit_texdef.coords[1][2]; - if ( fabs(S-w.point_at(i)[3])>1e-2 || fabs(T-w.point_at(i)[4])>1e-2 ) - { - if ( fabs(S-w.point_at(i)[3])>1e-4 || fabs(T-w.point_at(i)[4])>1e-4 ) - globalOutputStream() << "Warning : precision loss in brush -> brush primitive texture computation\n"; - else - globalOutputStream() << "Warning : brush -> brush primitive texture computation bug detected\n"; - } - } -#endif -#endif - w.point_at(i)[3]=f->brushprimit_texdef.coords[0][0]*x+f->brushprimit_texdef.coords[0][1]*y+f->brushprimit_texdef.coords[0][2]; - w.point_at(i)[4]=f->brushprimit_texdef.coords[1][0]*x+f->brushprimit_texdef.coords[1][1]*y+f->brushprimit_texdef.coords[1][2]; - } -} -#endif - -typedef float texmat_t[2][3]; - -void TexMat_Scale(texmat_t texmat, float s, float t) -{ - texmat[0][0] *= s; - texmat[0][1] *= s; - texmat[0][2] *= s; - texmat[1][0] *= t; - texmat[1][1] *= t; - texmat[1][2] *= t; -} - -void TexMat_Assign(texmat_t texmat, const texmat_t other) -{ - texmat[0][0] = other[0][0]; - texmat[0][1] = other[0][1]; - texmat[0][2] = other[0][2]; - texmat[1][0] = other[1][0]; - texmat[1][1] = other[1][1]; - texmat[1][2] = other[1][2]; -} - -void ConvertTexMatWithDimensions(const texmat_t texmat1, std::size_t w1, std::size_t h1, - texmat_t texmat2, std::size_t w2, std::size_t h2) -{ - TexMat_Assign(texmat2, texmat1); - TexMat_Scale(texmat2, static_cast(w1) / static_cast(w2), static_cast(h1) / static_cast(h2)); -} - -#if 0 -// convert a texture matrix between two qtexture_t -// if 0 for qtexture_t, basic 2x2 texture is assumed ( straight mapping between s/t coordinates and geometric coordinates ) -void ConvertTexMatWithQTexture( const float texMat1[2][3], const qtexture_t *qtex1, float texMat2[2][3], const qtexture_t *qtex2 ) -{ - ConvertTexMatWithDimensions(texMat1, (qtex1) ? qtex1->width : 2, (qtex1) ? qtex1->height : 2, - texMat2, (qtex2) ? qtex2->width : 2, (qtex2) ? qtex2->height : 2); -} - -void ConvertTexMatWithQTexture( const brushprimit_texdef_t *texMat1, const qtexture_t *qtex1, brushprimit_texdef_t *texMat2, const qtexture_t *qtex2 ) -{ - ConvertTexMatWithQTexture(texMat1->coords, qtex1, texMat2->coords, qtex2); -} -#endif - -// compute a fake shift scale rot representation from the texture matrix -// these shift scale rot values are to be understood in the local axis base -// Note: this code looks similar to Texdef_fromTransform, but the algorithm is slightly different. - -void TexMatToFakeTexCoords(const brushprimit_texdef_t& bp_texdef, texdef_t& texdef) -{ - texdef.scale[0] = static_cast(1.0 / vector2_length(Vector2(bp_texdef.coords[0][0], bp_texdef.coords[1][0]))); - texdef.scale[1] = static_cast(1.0 / vector2_length(Vector2(bp_texdef.coords[0][1], bp_texdef.coords[1][1]))); - - texdef.rotate = -static_cast(radians_to_degrees(arctangent_yx(bp_texdef.coords[1][0], bp_texdef.coords[0][0]))); - - texdef.shift[0] = -bp_texdef.coords[0][2]; - texdef.shift[1] = bp_texdef.coords[1][2]; - - // determine whether or not an axis is flipped using a 2d cross-product - double cross = vector2_cross(Vector2(bp_texdef.coords[0][0], bp_texdef.coords[0][1]), Vector2(bp_texdef.coords[1][0], bp_texdef.coords[1][1])); - if(cross < 0) - { - // This is a bit of a compromise when using BPs--since we don't know *which* axis was flipped, - // we pick one (rather arbitrarily) using the following convention: If the X-axis is between - // 0 and 180, we assume it's the Y-axis that flipped, otherwise we assume it's the X-axis and - // subtract out 180 degrees to compensate. - if(texdef.rotate >= 180.0f) - { - texdef.rotate -= 180.0f; - texdef.scale[0] = -texdef.scale[0]; - } - else - { - texdef.scale[1] = -texdef.scale[1]; - } - } -} - -// compute back the texture matrix from fake shift scale rot -void FakeTexCoordsToTexMat(const texdef_t& texdef, brushprimit_texdef_t& bp_texdef) -{ - double r = degrees_to_radians(-texdef.rotate); - double c = cos(r); - double s = sin(r); - double x = 1.0f / texdef.scale[0]; - double y = 1.0f / texdef.scale[1]; - bp_texdef.coords[0][0] = static_cast(x * c); - bp_texdef.coords[1][0] = static_cast(x * s); - bp_texdef.coords[0][1] = static_cast(y * -s); - bp_texdef.coords[1][1] = static_cast(y * c); - bp_texdef.coords[0][2] = -texdef.shift[0]; - bp_texdef.coords[1][2] = texdef.shift[1]; -} - -#if 0 // texture locking (brush primit) -// used for texture locking -// will move the texture according to a geometric vector -void ShiftTextureGeometric_BrushPrimit(face_t *f, Vector3& delta) -{ - Vector3 texS,texT; - float tx,ty; - Vector3 M[3]; // columns of the matrix .. easier that way - float det; - Vector3 D[2]; - // compute plane axis base ( doesn't change with translation ) - ComputeAxisBase( f->plane.normal, texS, texT ); - // compute translation vector in plane axis base - tx = vector3_dot( delta, texS ); - ty = vector3_dot( delta, texT ); - // fill the data vectors - M[0][0]=tx; M[0][1]=1.0f+tx; M[0][2]=tx; - M[1][0]=ty; M[1][1]=ty; M[1][2]=1.0f+ty; - M[2][0]=1.0f; M[2][1]=1.0f; M[2][2]=1.0f; - D[0][0]=f->brushprimit_texdef.coords[0][2]; - D[0][1]=f->brushprimit_texdef.coords[0][0]+f->brushprimit_texdef.coords[0][2]; - D[0][2]=f->brushprimit_texdef.coords[0][1]+f->brushprimit_texdef.coords[0][2]; - D[1][0]=f->brushprimit_texdef.coords[1][2]; - D[1][1]=f->brushprimit_texdef.coords[1][0]+f->brushprimit_texdef.coords[1][2]; - D[1][2]=f->brushprimit_texdef.coords[1][1]+f->brushprimit_texdef.coords[1][2]; - // solve - det = SarrusDet( M[0], M[1], M[2] ); - f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det; - f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det; - f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det; - f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det; - f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det; - f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det; -} - -// shift a texture (texture adjustments) along it's current texture axes -// x and y are geometric values, which we must compute as ST increments -// this depends on the texture size and the pixel/texel ratio -void ShiftTextureRelative_BrushPrimit( face_t *f, float x, float y) -{ - float s,t; - // as a ratio against texture size - // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors) - s = (x * 2.0) / (float)f->pShader->getTexture().width; - t = (y * 2.0) / (float)f->pShader->getTexture().height; - f->brushprimit_texdef.coords[0][2] -= s; - f->brushprimit_texdef.coords[1][2] -= t; -} -#endif - -// TTimo: FIXME: I don't like that, it feels broken -// (and it's likely that it's not used anymore) -// best fitted 2D vector is x.X+y.Y -void ComputeBest2DVector( Vector3& v, Vector3& X, Vector3& Y, int &x, int &y ) -{ - double sx,sy; - sx = vector3_dot( v, X ); - sy = vector3_dot( v, Y ); - if ( fabs(sy) > fabs(sx) ) - { - x = 0; - if ( sy > 0.0 ) - y = 1; - else - y = -1; - } - else - { - y = 0; - if ( sx > 0.0 ) - x = 1; - else - x = -1; - } -} - - -#if 0 // texdef conversion -void BrushPrimitFaceToFace(face_t *face) -{ - // we have parsed brush primitives and need conversion back to standard format - // NOTE: converting back is a quick hack, there's some information lost and we can't do anything about it - // FIXME: if we normalize the texture matrix to a standard 2x2 size, we end up with wrong scaling - // I tried various tweaks, no luck .. seems shifting is lost - brushprimit_texdef_t aux; - ConvertTexMatWithQTexture( &face->brushprimit_texdef, face->pShader->getTexture(), &aux, 0 ); - TexMatToFakeTexCoords( aux.coords, face->texdef.shift, &face->texdef.rotate, face->texdef.scale ); - face->texdef.scale[0]/=2.0; - face->texdef.scale[1]/=2.0; -} -#endif - - -#if 0 // texture locking (brush primit) -// TEXTURE LOCKING ----------------------------------------------------------------------------------------------------- -// (Relevant to the editor only?) - -// internally used for texture locking on rotation and flipping -// the general algorithm is the same for both lockings, it's only the geometric transformation part that changes -// so I wanted to keep it in a single function -// if there are more linear transformations that need the locking, going to a C++ or code pointer solution would be best -// (but right now I want to keep brush_primit.cpp striclty C) - -bool txlock_bRotation; - -// rotation locking params -int txl_nAxis; -float txl_fDeg; -Vector3 txl_vOrigin; - -// flip locking params -Vector3 txl_matrix[3]; -Vector3 txl_origin; - -void TextureLockTransformation_BrushPrimit(face_t *f) -{ - Vector3 Orig,texS,texT; // axis base of initial plane - // used by transformation algo - Vector3 temp; int j; - Vector3 vRotate; // rotation vector - - Vector3 rOrig,rvecS,rvecT; // geometric transformation of (0,0) (1,0) (0,1) { initial plane axis base } - Vector3 rNormal,rtexS,rtexT; // axis base for the transformed plane - Vector3 lOrig,lvecS,lvecT; // [2] are not used ( but usefull for debugging ) - Vector3 M[3]; - float det; - Vector3 D[2]; - - // compute plane axis base - ComputeAxisBase( f->plane.normal, texS, texT ); - VectorSet(Orig, 0.0f, 0.0f, 0.0f); - - // compute coordinates of (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) after transformation - // (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) <-> (0,0,0) texS texT ( expressed world axis base ) - // input: Orig, texS, texT (and the global locking params) - // ouput: rOrig, rvecS, rvecT, rNormal - if (txlock_bRotation) { - // rotation vector - VectorSet( vRotate, 0.0f, 0.0f, 0.0f ); - vRotate[txl_nAxis]=txl_fDeg; - VectorRotateOrigin ( Orig, vRotate, txl_vOrigin, rOrig ); - VectorRotateOrigin ( texS, vRotate, txl_vOrigin, rvecS ); - VectorRotateOrigin ( texT, vRotate, txl_vOrigin, rvecT ); - // compute normal of plane after rotation - VectorRotate ( f->plane.normal, vRotate, rNormal ); - } - else - { - for (j=0 ; j<3 ; j++) - rOrig[j] = vector3_dot(vector3_subtracted(Orig, txl_origin), txl_matrix[j]) + txl_origin[j]; - for (j=0 ; j<3 ; j++) - rvecS[j] = vector3_dot(vector3_subtracted(texS, txl_origin), txl_matrix[j]) + txl_origin[j]; - for (j=0 ; j<3 ; j++) - rvecT[j] = vector3_dot(vector3_subtracted(texT, txl_origin), txl_matrix[j]) + txl_origin[j]; - // we also need the axis base of the target plane, apply the transformation matrix to the normal too.. - for (j=0 ; j<3 ; j++) - rNormal[j] = vector3_dot(f->plane.normal, txl_matrix[j]); - } - - // compute rotated plane axis base - ComputeAxisBase( rNormal, rtexS, rtexT ); - // compute S/T coordinates of the three points in rotated axis base ( in M matrix ) - lOrig[0] = vector3_dot( rOrig, rtexS ); - lOrig[1] = vector3_dot( rOrig, rtexT ); - lvecS[0] = vector3_dot( rvecS, rtexS ); - lvecS[1] = vector3_dot( rvecS, rtexT ); - lvecT[0] = vector3_dot( rvecT, rtexS ); - lvecT[1] = vector3_dot( rvecT, rtexT ); - M[0][0] = lOrig[0]; M[1][0] = lOrig[1]; M[2][0] = 1.0f; - M[0][1] = lvecS[0]; M[1][1] = lvecS[1]; M[2][1] = 1.0f; - M[0][2] = lvecT[0]; M[1][2] = lvecT[1]; M[2][2] = 1.0f; - // fill data vector - D[0][0]=f->brushprimit_texdef.coords[0][2]; - D[0][1]=f->brushprimit_texdef.coords[0][0]+f->brushprimit_texdef.coords[0][2]; - D[0][2]=f->brushprimit_texdef.coords[0][1]+f->brushprimit_texdef.coords[0][2]; - D[1][0]=f->brushprimit_texdef.coords[1][2]; - D[1][1]=f->brushprimit_texdef.coords[1][0]+f->brushprimit_texdef.coords[1][2]; - D[1][2]=f->brushprimit_texdef.coords[1][1]+f->brushprimit_texdef.coords[1][2]; - // solve - det = SarrusDet( M[0], M[1], M[2] ); - f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det; - f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det; - f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det; - f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det; - f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det; - f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det; -} - -// texture locking -// called before the points on the face are actually rotated -void RotateFaceTexture_BrushPrimit(face_t *f, int nAxis, float fDeg, Vector3& vOrigin ) -{ - // this is a placeholder to call the general texture locking algorithm - txlock_bRotation = true; - txl_nAxis = nAxis; - txl_fDeg = fDeg; - VectorCopy(vOrigin, txl_vOrigin); - TextureLockTransformation_BrushPrimit(f); -} - -// compute the new brush primit texture matrix for a transformation matrix and a flip order flag (change plane orientation) -// this matches the select_matrix algo used in select.cpp -// this needs to be called on the face BEFORE any geometric transformation -// it will compute the texture matrix that will represent the same texture on the face after the geometric transformation is done -void ApplyMatrix_BrushPrimit(face_t *f, Vector3 matrix[3], Vector3& origin) -{ - // this is a placeholder to call the general texture locking algorithm - txlock_bRotation = false; - VectorCopy(matrix[0], txl_matrix[0]); - VectorCopy(matrix[1], txl_matrix[1]); - VectorCopy(matrix[2], txl_matrix[2]); - VectorCopy(origin, txl_origin); - TextureLockTransformation_BrushPrimit(f); -} -#endif - -// don't do C==A! -void BPMatMul(float A[2][3], float B[2][3], float C[2][3]) -{ - C[0][0] = A[0][0]*B[0][0]+A[0][1]*B[1][0]; - C[1][0] = A[1][0]*B[0][0]+A[1][1]*B[1][0]; - C[0][1] = A[0][0]*B[0][1]+A[0][1]*B[1][1]; - C[1][1] = A[1][0]*B[0][1]+A[1][1]*B[1][1]; - C[0][2] = A[0][0]*B[0][2]+A[0][1]*B[1][2]+A[0][2]; - C[1][2] = A[1][0]*B[0][2]+A[1][1]*B[1][2]+A[1][2]; -} - -void BPMatDump(float A[2][3]) -{ - globalOutputStream() << "" << A[0][0] - << " " << A[0][1] - << " " << A[0][2] - << "\n" << A[1][0] - << " " << A[1][2] - << " " << A[1][2] - << "\n0 0 1\n"; -} - -void BPMatRotate(float A[2][3], float theta) -{ - float m[2][3]; - float aux[2][3]; - memset(&m, 0, sizeof(float)*6); - m[0][0] = static_cast(cos(degrees_to_radians(theta))); - m[0][1] = static_cast(-sin(degrees_to_radians(theta))); - m[1][0] = -m[0][1]; - m[1][1] = m[0][0]; - BPMatMul(A, m, aux); - BPMatCopy(aux,A); -} - -#if 0 // camera-relative texture shift -// get the relative axes of the current texturing -void BrushPrimit_GetRelativeAxes(face_t *f, Vector3& vecS, Vector3& vecT) -{ - float vS[2],vT[2]; - // first we compute them as expressed in plane axis base - // BP matrix has coordinates of plane axis base expressed in geometric axis base - // so we use the line vectors - vS[0] = f->brushprimit_texdef.coords[0][0]; - vS[1] = f->brushprimit_texdef.coords[0][1]; - vT[0] = f->brushprimit_texdef.coords[1][0]; - vT[1] = f->brushprimit_texdef.coords[1][1]; - // now compute those vectors in geometric space - Vector3 texS, texT; // axis base of the plane (geometric) - ComputeAxisBase(f->plane.normal, texS, texT); - // vecS[] = vS[0].texS[] + vS[1].texT[] - // vecT[] = vT[0].texS[] + vT[1].texT[] - vecS[0] = vS[0]*texS[0] + vS[1]*texT[0]; - vecS[1] = vS[0]*texS[1] + vS[1]*texT[1]; - vecS[2] = vS[0]*texS[2] + vS[1]*texT[2]; - vecT[0] = vT[0]*texS[0] + vT[1]*texT[0]; - vecT[1] = vT[0]*texS[1] + vT[1]*texT[1]; - vecT[2] = vT[0]*texS[2] + vT[1]*texT[2]; -} - -// brush primitive texture adjustments, use the camera view to map adjustments -// ShiftTextureRelative_BrushPrimit ( s , t ) will shift relative to the texture -void ShiftTextureRelative_Camera(face_t *f, int x, int y) -{ - Vector3 vecS, vecT; - float XY[2]; // the values we are going to send for translation - float sgn[2]; // +1 or -1 - int axis[2]; - CamWnd* pCam; - - // get the two relative texture axes for the current texturing - BrushPrimit_GetRelativeAxes(f, vecS, vecT); - - // center point of the face, project it on the camera space - Vector3 C; - VectorClear(C); - int i; - for (i=0; iface_winding->numpoints; i++) - { - VectorAdd(C,f->face_winding->point_at(i),C); - } - VectorScale(C,1.0/f->face_winding->numpoints,C); - - pCam = g_pParentWnd->GetCamWnd(); - pCam->MatchViewAxes(C, vecS, axis[0], sgn[0]); - pCam->MatchViewAxes(C, vecT, axis[1], sgn[1]); - - // this happens when the two directions can't be mapped on two different directions on the screen - // then the move will occur against a single axis - // (i.e. the user is not positioned well enough to send understandable shift commands) - // NOTE: in most cases this warning is not very relevant because the user would use one of the two axes - // for which the solution is easy (the other one being unknown) - // so this warning could be removed - if (axis[0] == axis[1]) - globalOutputStream() << "Warning: degenerate in ShiftTextureRelative_Camera\n"; - - // compute the X Y geometric increments - // those geometric increments will be applied along the texture axes (the ones we computed above) - XY[0] = 0; - XY[1] = 0; - if (x!=0) - { - // moving right/left - XY[axis[0]] += sgn[0]*x; - } - if (y!=0) - { - XY[axis[1]] += sgn[1]*y; - } - // we worked out a move along vecS vecT, and we now it's geometric amplitude - // apply it - ShiftTextureRelative_BrushPrimit(f, XY[0], XY[1]); -} -#endif - - -void BPTexdef_Assign(brushprimit_texdef_t& bp_td, const brushprimit_texdef_t& bp_other) -{ - bp_td = bp_other; -} - -void BPTexdef_Shift(brushprimit_texdef_t& bp_td, float s, float t) -{ - // shift a texture (texture adjustments) along it's current texture axes - // x and y are geometric values, which we must compute as ST increments - // this depends on the texture size and the pixel/texel ratio - // as a ratio against texture size - // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors) - bp_td.coords[0][2] -= s; - bp_td.coords[1][2] += t; -} - -void BPTexdef_Scale(brushprimit_texdef_t& bp_td, float s, float t) -{ - // apply same scale as the spinner button of the surface inspector - texdef_t texdef; - // compute fake shift scale rot - TexMatToFakeTexCoords( bp_td, texdef ); - // update - texdef.scale[0] += s; - texdef.scale[1] += t; - // compute new normalized texture matrix - FakeTexCoordsToTexMat( texdef, bp_td ); -} - -void BPTexdef_Rotate(brushprimit_texdef_t& bp_td, float angle) -{ - // apply same scale as the spinner button of the surface inspector - texdef_t texdef; - // compute fake shift scale rot - TexMatToFakeTexCoords( bp_td, texdef ); - // update - texdef.rotate += angle; - // compute new normalized texture matrix - FakeTexCoordsToTexMat( texdef, bp_td ); -} - -void BPTexdef_Construct(brushprimit_texdef_t& bp_td, std::size_t width, std::size_t height) -{ - bp_td.coords[0][0] = 1.0f; - bp_td.coords[1][1] = 1.0f; - ConvertTexMatWithDimensions(bp_td.coords, 2, 2, bp_td.coords, width, height); -} - -void Texdef_Assign(TextureProjection& projection, const TextureProjection& other) -{ - if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - BPTexdef_Assign(projection.m_brushprimit_texdef, other.m_brushprimit_texdef); - } - else - { - Texdef_Assign(projection.m_texdef, other.m_texdef); - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) - { - projection.m_basis_s = other.m_basis_s; - projection.m_basis_t = other.m_basis_t; - } - } -} - -void Texdef_Shift(TextureProjection& projection, float s, float t) -{ - if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - BPTexdef_Shift(projection.m_brushprimit_texdef, s, t); - } - else - { - Texdef_Shift(projection.m_texdef, s, t); - } -} - -void Texdef_Scale(TextureProjection& projection, float s, float t) -{ - if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - BPTexdef_Scale(projection.m_brushprimit_texdef, s, t); - } - else - { - Texdef_Scale(projection.m_texdef, s, t); - } -} - -void Texdef_Rotate(TextureProjection& projection, float angle) -{ - if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - BPTexdef_Rotate(projection.m_brushprimit_texdef, angle); - } - else - { - Texdef_Rotate(projection.m_texdef, angle); - } -} - -void Texdef_FitTexture(TextureProjection& projection, std::size_t width, std::size_t height, const Vector3& normal, const Winding& w, float s_repeat, float t_repeat) -{ - if(w.numpoints < 3) - { - return; - } - - Matrix4 st2tex; - Texdef_toTransform(projection, (float)width, (float)height, st2tex); - - // the current texture transform - Matrix4 local2tex = st2tex; - { - Matrix4 xyz2st; - Texdef_basisForNormal(projection, normal, xyz2st); - matrix4_multiply_by_matrix4(local2tex, xyz2st); - } - - // the bounds of the current texture transform - AABB bounds; - for(Winding::const_iterator i = w.begin(); i != w.end(); ++i) - { - Vector3 texcoord = matrix4_transformed_point(local2tex, (*i).vertex); - aabb_extend_by_point_safe(bounds, texcoord); - } - bounds.origin.z() = 0; - bounds.extents.z() = 1; - - // the bounds of a perfectly fitted texture transform - AABB perfect(Vector3(s_repeat * 0.5, t_repeat * 0.5, 0), Vector3(s_repeat * 0.5, t_repeat * 0.5, 1)); - - // the difference between the current texture transform and the perfectly fitted transform - Matrix4 matrix(matrix4_translation_for_vec3(bounds.origin - perfect.origin)); - matrix4_pivoted_scale_by_vec3(matrix, bounds.extents / perfect.extents, perfect.origin); - matrix4_affine_invert(matrix); - - // apply the difference to the current texture transform - matrix4_premultiply_by_matrix4(st2tex, matrix); - - Texdef_fromTransform(projection, (float)width, (float)height, st2tex); - Texdef_normalise(projection, (float)width, (float)height); -} - -float Texdef_getDefaultTextureScale() -{ - return g_texdef_default_scale; -} - -void TexDef_Construct_Default(TextureProjection& projection) -{ - projection.m_texdef.scale[0] = Texdef_getDefaultTextureScale(); - projection.m_texdef.scale[1] = Texdef_getDefaultTextureScale(); - - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - FakeTexCoordsToTexMat(projection.m_texdef, projection.m_brushprimit_texdef); - } -} - - - -void ShiftScaleRotate_fromFace(texdef_t& shiftScaleRotate, const TextureProjection& projection) -{ - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - TexMatToFakeTexCoords(projection.m_brushprimit_texdef, shiftScaleRotate); - } - else - { - shiftScaleRotate = projection.m_texdef; - } -} - -void ShiftScaleRotate_toFace(const texdef_t& shiftScaleRotate, TextureProjection& projection) -{ - if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - // compute texture matrix - // the matrix returned must be understood as a qtexture_t with width=2 height=2 - FakeTexCoordsToTexMat( shiftScaleRotate, projection.m_brushprimit_texdef ); - } - else - { - projection.m_texdef = shiftScaleRotate; - } -} - - -inline void print_vector3(const Vector3& v) -{ - globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n"; -} - -inline void print_3x3(const Matrix4& m) -{ - globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) " - << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) " - << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n"; -} - - -inline Matrix4 matrix4_rotation_for_vector3(const Vector3& x, const Vector3& y, const Vector3& z) -{ - return Matrix4( - x.x(), x.y(), x.z(), 0, - y.x(), y.y(), y.z(), 0, - z.x(), z.y(), z.z(), 0, - 0, 0, 0, 1 - ); -} - -inline Matrix4 matrix4_swap_axes(const Vector3& from, const Vector3& to) -{ - if(from.x() != 0 && to.y() != 0) - { - return matrix4_rotation_for_vector3(to, from, g_vector3_axis_z); - } - - if(from.x() != 0 && to.z() != 0) - { - return matrix4_rotation_for_vector3(to, g_vector3_axis_y, from); - } - - if(from.y() != 0 && to.z() != 0) - { - return matrix4_rotation_for_vector3(g_vector3_axis_x, to, from); - } - - if(from.y() != 0 && to.x() != 0) - { - return matrix4_rotation_for_vector3(from, to, g_vector3_axis_z); - } - - if(from.z() != 0 && to.x() != 0) - { - return matrix4_rotation_for_vector3(from, g_vector3_axis_y, to); - } - - if(from.z() != 0 && to.y() != 0) - { - return matrix4_rotation_for_vector3(g_vector3_axis_x, from, to); - } - - ERROR_MESSAGE("unhandled axis swap case"); - - return g_matrix4_identity; -} - -inline Matrix4 matrix4_reflection_for_plane(const Plane3& plane) -{ - return Matrix4( - static_cast(1 - (2 * plane.a * plane.a)), - static_cast(-2 * plane.a * plane.b), - static_cast(-2 * plane.a * plane.c), - 0, - static_cast(-2 * plane.b * plane.a), - static_cast(1 - (2 * plane.b * plane.b)), - static_cast(-2 * plane.b * plane.c), - 0, - static_cast(-2 * plane.c * plane.a), - static_cast(-2 * plane.c * plane.b), - static_cast(1 - (2 * plane.c * plane.c)), - 0, - static_cast(-2 * plane.d * plane.a), - static_cast(-2 * plane.d * plane.b), - static_cast(-2 * plane.d * plane.c), - 1 - ); -} - -inline Matrix4 matrix4_reflection_for_plane45(const Plane3& plane, const Vector3& from, const Vector3& to) -{ - Vector3 first = from; - Vector3 second = to; - - if(vector3_dot(from, plane.normal()) > 0 == vector3_dot(to, plane.normal()) > 0) - { - first = vector3_negated(first); - second = vector3_negated(second); - } - -#if 0 - globalOutputStream() << "normal: "; - print_vector3(plane.normal()); - - globalOutputStream() << "from: "; - print_vector3(first); - - globalOutputStream() << "to: "; - print_vector3(second); -#endif - - Matrix4 swap = matrix4_swap_axes(first, second); - - Matrix4 tmp = matrix4_reflection_for_plane(plane); - - swap.tx() = -static_cast(-2 * plane.a * plane.d); - swap.ty() = -static_cast(-2 * plane.b * plane.d); - swap.tz() = -static_cast(-2 * plane.c * plane.d); - - return swap; -} - -void Texdef_transformLocked(TextureProjection& projection, std::size_t width, std::size_t height, const Plane3& plane, const Matrix4& identity2transformed) -{ - //globalOutputStream() << "identity2transformed: " << identity2transformed << "\n"; - - //globalOutputStream() << "plane.normal(): " << plane.normal() << "\n"; - - Vector3 normalTransformed(matrix4_transformed_direction(identity2transformed, plane.normal())); - - //globalOutputStream() << "normalTransformed: " << normalTransformed << "\n"; - - // identity: identity space - // transformed: transformation - // stIdentity: base st projection space before transformation - // stTransformed: base st projection space after transformation - // stOriginal: original texdef space - - // stTransformed2stOriginal = stTransformed -> transformed -> identity -> stIdentity -> stOriginal - - Matrix4 identity2stIdentity; - Texdef_basisForNormal(projection, plane.normal(), identity2stIdentity); - //globalOutputStream() << "identity2stIdentity: " << identity2stIdentity << "\n"; - - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) - { - matrix4_transform_direction(identity2transformed, projection.m_basis_s); - matrix4_transform_direction(identity2transformed, projection.m_basis_t); - } - - Matrix4 transformed2stTransformed; - Texdef_basisForNormal(projection, normalTransformed, transformed2stTransformed); - - Matrix4 stTransformed2identity(matrix4_affine_inverse(matrix4_multiplied_by_matrix4(transformed2stTransformed, identity2transformed))); - - Vector3 originalProjectionAxis(vector4_to_vector3(matrix4_affine_inverse(identity2stIdentity).z())); - - Vector3 transformedProjectionAxis(vector4_to_vector3(stTransformed2identity.z())); - - Matrix4 stIdentity2stOriginal; - Texdef_toTransform(projection, (float)width, (float)height, stIdentity2stOriginal); - Matrix4 identity2stOriginal(matrix4_multiplied_by_matrix4(stIdentity2stOriginal, identity2stIdentity)); - - //globalOutputStream() << "originalProj: " << originalProjectionAxis << "\n"; - //globalOutputStream() << "transformedProj: " << transformedProjectionAxis << "\n"; - double dot = vector3_dot(originalProjectionAxis, transformedProjectionAxis); - //globalOutputStream() << "dot: " << dot << "\n"; - if(dot == 0) - { - // The projection axis chosen for the transformed normal is at 90 degrees - // to the transformed projection axis chosen for the original normal. - // This happens when the projection axis is ambiguous - e.g. for the plane - // 'X == Y' the projection axis could be either X or Y. - //globalOutputStream() << "flipped\n"; -#if 0 - globalOutputStream() << "projection off by 90\n"; - globalOutputStream() << "normal: "; - print_vector3(plane.normal()); - globalOutputStream() << "original projection: "; - print_vector3(originalProjectionAxis); - globalOutputStream() << "transformed projection: "; - print_vector3(transformedProjectionAxis); -#endif - - Matrix4 identityCorrected = matrix4_reflection_for_plane45(plane, originalProjectionAxis, transformedProjectionAxis); - - identity2stOriginal = matrix4_multiplied_by_matrix4(identity2stOriginal, identityCorrected); - } - - Matrix4 stTransformed2stOriginal = matrix4_multiplied_by_matrix4(identity2stOriginal, stTransformed2identity); - - Texdef_fromTransform(projection, (float)width, (float)height, stTransformed2stOriginal); - Texdef_normalise(projection, (float)width, (float)height); -} - -#if 1 -void Q3_to_matrix(const texdef_t& texdef, float width, float height, const Vector3& normal, Matrix4& matrix) -{ - Normal_GetTransform(normal, matrix); - - Matrix4 transform; - - Texdef_toTransform(texdef, width, height, transform); - - matrix4_multiply_by_matrix4(matrix, transform); -} - -void BP_from_matrix(brushprimit_texdef_t& bp_texdef, const Vector3& normal, const Matrix4& transform) -{ - Matrix4 basis; - basis = g_matrix4_identity; - ComputeAxisBase(normal, vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y())); - vector4_to_vector3(basis.z()) = normal; - matrix4_transpose(basis); - matrix4_affine_invert(basis); - - Matrix4 basis2texture = matrix4_multiplied_by_matrix4(basis, transform); - - BPTexdef_fromTransform(bp_texdef, basis2texture); -} - -void Q3_to_BP(const texdef_t& texdef, float width, float height, const Vector3& normal, brushprimit_texdef_t& bp_texdef) -{ - Matrix4 matrix; - Q3_to_matrix(texdef, width, height, normal, matrix); - BP_from_matrix(bp_texdef, normal, matrix); -} -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brush_primit.h b/misc/mediasource/extra/netradiant-src/radiant/brush_primit.h deleted file mode 100644 index 590fba94..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brush_primit.h +++ /dev/null @@ -1,142 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_BRUSH_PRIMIT_H) -#define INCLUDED_BRUSH_PRIMIT_H - -#include "math/vector.h" -#include "itexdef.h" -#include "debugging/debugging.h" -// Timo -// new brush primitive texdef -struct brushprimit_texdef_t -{ - brushprimit_texdef_t() - { - coords[0][0] = 2.0f; - coords[0][1] = 0.f; - coords[0][2] = 0.f; - coords[1][0] = 0.f; - coords[1][1] = 2.0f; - coords[1][2] = 0.f; - } - void removeScale(std::size_t width, std::size_t height) - { -#if 1 - coords[0][0] *= width; - coords[0][1] *= width; - coords[0][2] *= width; - coords[1][0] *= height; - coords[1][1] *= height; - coords[1][2] *= height; -#endif - } - void addScale(std::size_t width, std::size_t height) - { -#if 1 - ASSERT_MESSAGE(width > 0, "shader-width is 0"); - ASSERT_MESSAGE(height > 0, "shader-height is 0"); - coords[0][0] /= width; - coords[0][1] /= width; - coords[0][2] /= width; - coords[1][0] /= height; - coords[1][1] /= height; - coords[1][2] /= height; -#endif - } - float coords[2][3]; -}; - -class TextureProjection -{ -public: - texdef_t m_texdef; - brushprimit_texdef_t m_brushprimit_texdef; - Vector3 m_basis_s; - Vector3 m_basis_t; - - TextureProjection() - { - } - TextureProjection( - const texdef_t& texdef, - const brushprimit_texdef_t& brushprimit_texdef, - const Vector3& basis_s, - const Vector3& basis_t - ) : - m_texdef(texdef), - m_brushprimit_texdef(brushprimit_texdef), - m_basis_s(basis_s), - m_basis_t(basis_t) - { - } -}; - -float Texdef_getDefaultTextureScale(); - -class texdef_t; -struct Winding; -template class BasicVector3; -typedef BasicVector3 Vector3; -template class BasicVector4; -typedef BasicVector4 Vector4; -typedef Vector4 Quaternion; -class Matrix4; -class Plane3; - -void Normal_GetTransform(const Vector3& normal, Matrix4& transform); - -void TexDef_Construct_Default(TextureProjection& projection); - -void Texdef_Assign(TextureProjection& projection, const TextureProjection& other); -void Texdef_Shift(TextureProjection& projection, float s, float t); -void Texdef_Scale(TextureProjection& projection, float s, float t); -void Texdef_Rotate(TextureProjection& projection, float angle); -void Texdef_FitTexture(TextureProjection& projection, std::size_t width, std::size_t height, const Vector3& normal, const Winding& w, float s_repeat, float t_repeat); -void Texdef_EmitTextureCoordinates(const TextureProjection& projection, std::size_t width, std::size_t height, Winding& w, const Vector3& normal, const Matrix4& localToWorld); - -void ShiftScaleRotate_fromFace(texdef_t& shiftScaleRotate, const TextureProjection& projection); -void ShiftScaleRotate_toFace(const texdef_t& shiftScaleRotate, TextureProjection& projection); - -void Texdef_transformLocked(TextureProjection& projection, std::size_t width, std::size_t height, const Plane3& plane, const Matrix4& transform); -void Texdef_normalise(TextureProjection& projection, float width, float height); - -enum TexdefTypeId -{ - TEXDEFTYPEID_QUAKE, - TEXDEFTYPEID_BRUSHPRIMITIVES, - TEXDEFTYPEID_HALFLIFE, -}; - -struct bp_globals_t -{ - // tells if we are internally using brush primitive (texture coordinates and map format) - // this is a shortcut for IntForKey( g_qeglobals.d_project_entity, "brush_primit" ) - // NOTE: must keep the two ones in sync - TexdefTypeId m_texdefTypeId; -}; - -extern bp_globals_t g_bp_globals; -extern float g_texdef_default_scale; - -void ComputeAxisBase(const Vector3& normal, Vector3& texS, Vector3& texT); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushmanip.cpp b/misc/mediasource/extra/netradiant-src/radiant/brushmanip.cpp deleted file mode 100644 index ca367100..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushmanip.cpp +++ /dev/null @@ -1,1571 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "brushmanip.h" - - -#include "gtkutil/widget.h" -#include "gtkutil/menu.h" -#include "gtkmisc.h" -#include "brushnode.h" -#include "map.h" -#include "texwindow.h" -#include "gtkdlgs.h" -#include "commands.h" -#include "mainframe.h" -#include "dialog.h" -#include "xywindow.h" -#include "preferences.h" - -#include - -void Brush_ConstructCuboid(Brush& brush, const AABB& bounds, const char* shader, const TextureProjection& projection) -{ - const unsigned char box[3][2] = { { 0, 1 }, { 2, 0 }, { 1, 2 } }; - Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); - Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); - - brush.clear(); - brush.reserve(6); - - { - for(int i=0; i < 3; ++i) - { - Vector3 planepts1(maxs); - Vector3 planepts2(maxs); - planepts2[box[i][0]] = mins[box[i][0]]; - planepts1[box[i][1]] = mins[box[i][1]]; - - brush.addPlane(maxs, planepts1, planepts2, shader, projection); - } - } - { - for(int i=0; i < 3; ++i) - { - Vector3 planepts1(mins); - Vector3 planepts2(mins); - planepts1[box[i][0]] = maxs[box[i][0]]; - planepts2[box[i][1]] = maxs[box[i][1]]; - - brush.addPlane(mins, planepts1, planepts2, shader, projection); - } - } -} - -inline float max_extent(const Vector3& extents) -{ - return std::max(std::max(extents[0], extents[1]), extents[2]); -} - -inline float max_extent_2d(const Vector3& extents, int axis) -{ - switch(axis) - { - case 0: - return std::max(extents[1], extents[2]); - case 1: - return std::max(extents[0], extents[2]); - default: - return std::max(extents[0], extents[1]); - } -} - -const std::size_t c_brushPrism_minSides = 3; -const std::size_t c_brushPrism_maxSides = c_brush_maxFaces - 2; -const char* const c_brushPrism_name = "brushPrism"; - -void Brush_ConstructPrism(Brush& brush, const AABB& bounds, std::size_t sides, int axis, const char* shader, const TextureProjection& projection) -{ - if(sides < c_brushPrism_minSides) - { - globalErrorStream() << c_brushPrism_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushPrism_minSides) << "\n"; - return; - } - if(sides > c_brushPrism_maxSides) - { - globalErrorStream() << c_brushPrism_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushPrism_maxSides) << "\n"; - return; - } - - brush.clear(); - brush.reserve(sides+2); - - Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); - Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); - - float radius = max_extent_2d(bounds.extents, axis); - const Vector3& mid = bounds.origin; - Vector3 planepts[3]; - - planepts[2][(axis+1)%3] = mins[(axis+1)%3]; - planepts[2][(axis+2)%3] = mins[(axis+2)%3]; - planepts[2][axis] = maxs[axis]; - planepts[1][(axis+1)%3] = maxs[(axis+1)%3]; - planepts[1][(axis+2)%3] = mins[(axis+2)%3]; - planepts[1][axis] = maxs[axis]; - planepts[0][(axis+1)%3] = maxs[(axis+1)%3]; - planepts[0][(axis+2)%3] = maxs[(axis+2)%3]; - planepts[0][axis] = maxs[axis]; - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - - planepts[0][(axis+1)%3] = mins[(axis+1)%3]; - planepts[0][(axis+2)%3] = mins[(axis+2)%3]; - planepts[0][axis] = mins[axis]; - planepts[1][(axis+1)%3] = maxs[(axis+1)%3]; - planepts[1][(axis+2)%3] = mins[(axis+2)%3]; - planepts[1][axis] = mins[axis]; - planepts[2][(axis+1)%3] = maxs[(axis+1)%3]; - planepts[2][(axis+2)%3] = maxs[(axis+2)%3]; - planepts[2][axis] = mins[axis]; - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - - for (std::size_t i=0 ; i(floor(mid[(axis+1)%3]+radius*cv+0.5)); - planepts[0][(axis+2)%3] = static_cast(floor(mid[(axis+2)%3]+radius*sv+0.5)); - planepts[0][axis] = mins[axis]; - - planepts[1][(axis+1)%3] = planepts[0][(axis+1)%3]; - planepts[1][(axis+2)%3] = planepts[0][(axis+2)%3]; - planepts[1][axis] = maxs[axis]; - - planepts[2][(axis+1)%3] = static_cast(floor(planepts[0][(axis+1)%3] - radius*sv + 0.5)); - planepts[2][(axis+2)%3] = static_cast(floor(planepts[0][(axis+2)%3] + radius*cv + 0.5)); - planepts[2][axis] = maxs[axis]; - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - } -} - -const std::size_t c_brushCone_minSides = 3; -const std::size_t c_brushCone_maxSides = 32; -const char* const c_brushCone_name = "brushCone"; - -void Brush_ConstructCone(Brush& brush, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) -{ - if(sides < c_brushCone_minSides) - { - globalErrorStream() << c_brushCone_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushCone_minSides) << "\n"; - return; - } - if(sides > c_brushCone_maxSides) - { - globalErrorStream() << c_brushCone_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushCone_maxSides) << "\n"; - return; - } - - brush.clear(); - brush.reserve(sides+1); - - Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); - Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); - - float radius = max_extent(bounds.extents); - const Vector3& mid = bounds.origin; - Vector3 planepts[3]; - - planepts[0][0] = mins[0];planepts[0][1] = mins[1];planepts[0][2] = mins[2]; - planepts[1][0] = maxs[0];planepts[1][1] = mins[1];planepts[1][2] = mins[2]; - planepts[2][0] = maxs[0];planepts[2][1] = maxs[1];planepts[2][2] = mins[2]; - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - - for (std::size_t i=0 ; i(floor(mid[0]+radius*cv+0.5)); - planepts[0][1] = static_cast(floor(mid[1]+radius*sv+0.5)); - planepts[0][2] = mins[2]; - - planepts[1][0] = mid[0]; - planepts[1][1] = mid[1]; - planepts[1][2] = maxs[2]; - - planepts[2][0] = static_cast(floor(planepts[0][0] - radius * sv + 0.5)); - planepts[2][1] = static_cast(floor(planepts[0][1] + radius * cv + 0.5)); - planepts[2][2] = maxs[2]; - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - } -} - -const std::size_t c_brushSphere_minSides = 3; -const std::size_t c_brushSphere_maxSides = 31; -const char* const c_brushSphere_name = "brushSphere"; - -void Brush_ConstructSphere(Brush& brush, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) -{ - if(sides < c_brushSphere_minSides) - { - globalErrorStream() << c_brushSphere_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushSphere_minSides) << "\n"; - return; - } - if(sides > c_brushSphere_maxSides) - { - globalErrorStream() << c_brushSphere_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushSphere_maxSides) << "\n"; - return; - } - - brush.clear(); - brush.reserve(sides*sides); - - float radius = max_extent(bounds.extents); - const Vector3& mid = bounds.origin; - Vector3 planepts[3]; - - double dt = 2 * c_pi / sides; - double dp = c_pi / sides; - for(std::size_t i=0; i < sides; i++) - { - for(std::size_t j=0;j < sides-1; j++) - { - double t = i * dt; - double p = float(j * dp - c_pi / 2); - - planepts[0] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t, p), radius)); - planepts[1] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t, p + dp), radius)); - planepts[2] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t + dt, p + dp), radius)); - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - } - } - - { - double p = (sides - 1) * dp - c_pi / 2; - for(std::size_t i = 0; i < sides; i++) - { - double t = i * dt; - - planepts[0] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t, p), radius)); - planepts[1] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t + dt, p + dp), radius)); - planepts[2] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t + dt, p), radius)); - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - } - } -} - -const std::size_t c_brushRock_minSides = 10; -const std::size_t c_brushRock_maxSides = 1000; -const char* const c_brushRock_name = "brushRock"; - -void Brush_ConstructRock(Brush& brush, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) -{ - if(sides < c_brushRock_minSides) - { - globalErrorStream() << c_brushRock_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushRock_minSides) << "\n"; - return; - } - if(sides > c_brushRock_maxSides) - { - globalErrorStream() << c_brushRock_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushRock_maxSides) << "\n"; - return; - } - - brush.clear(); - brush.reserve(sides*sides); - - float radius = max_extent(bounds.extents); - const Vector3& mid = bounds.origin; - Vector3 planepts[3]; - - for(std::size_t j=0;j < sides; j++) - { - planepts[0][0] = rand() - (RAND_MAX/2); - planepts[0][1] = rand() - (RAND_MAX/2); - planepts[0][2] = rand() - (RAND_MAX/2); - vector3_normalise(planepts[0]); - - // find two vectors that are perpendicular to planepts[0] - ComputeAxisBase(planepts[0], planepts[1], planepts[2]); - - planepts[0] = vector3_added(mid, vector3_scaled(planepts[0], radius)); - planepts[1] = vector3_added(planepts[0], vector3_scaled(planepts[1], radius)); - planepts[2] = vector3_added(planepts[0], vector3_scaled(planepts[2], radius)); - -#if 0 - // make sure the orientation is right - if(vector3_dot(vector3_subtracted(planepts[0], mid), vector3_cross(vector3_subtracted(planepts[1], mid), vector3_subtracted(planepts[2], mid))) > 0) - { - Vector3 h; - h = planepts[1]; - planepts[1] = planepts[2]; - planepts[2] = h; - globalOutputStream() << "flip\n"; - } - else - globalOutputStream() << "no flip\n"; -#endif - - brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); - } -} - -int GetViewAxis() -{ - switch(GlobalXYWnd_getCurrentViewType()) - { - case XY: - return 2; - case XZ: - return 1; - case YZ: - return 0; - } - return 2; -} - -void Brush_ConstructPrefab(Brush& brush, EBrushPrefab type, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) -{ - switch(type) - { - case eBrushCuboid: - { - UndoableCommand undo("brushCuboid"); - - Brush_ConstructCuboid(brush, bounds, shader, projection); - } - break; - case eBrushPrism: - { - int axis = GetViewAxis(); - StringOutputStream command; - command << c_brushPrism_name << " -sides " << Unsigned(sides) << " -axis " << axis; - UndoableCommand undo(command.c_str()); - - Brush_ConstructPrism(brush, bounds, sides, axis, shader, projection); - } - break; - case eBrushCone: - { - StringOutputStream command; - command << c_brushCone_name << " -sides " << Unsigned(sides); - UndoableCommand undo(command.c_str()); - - Brush_ConstructCone(brush, bounds, sides, shader, projection); - } - break; - case eBrushSphere: - { - StringOutputStream command; - command << c_brushSphere_name << " -sides " << Unsigned(sides); - UndoableCommand undo(command.c_str()); - - Brush_ConstructSphere(brush, bounds, sides, shader, projection); - } - break; - case eBrushRock: - { - StringOutputStream command; - command << c_brushRock_name << " -sides " << Unsigned(sides); - UndoableCommand undo(command.c_str()); - - Brush_ConstructRock(brush, bounds, sides, shader, projection); - } - break; - } -} - - -void ConstructRegionBrushes(scene::Node* brushes[6], const Vector3& region_mins, const Vector3& region_maxs) -{ - { - // set mins - Vector3 mins(region_mins[0]-32, region_mins[1]-32, region_mins[2]-32); - - // vary maxs - for(std::size_t i=0; i<3; i++) - { - Vector3 maxs(region_maxs[0]+32, region_maxs[1]+32, region_maxs[2]+32); - maxs[i] = region_mins[i]; - Brush_ConstructCuboid(*Node_getBrush(*brushes[i]), aabb_for_minmax(mins, maxs), texdef_name_default(), TextureProjection()); - } - } - - { - // set maxs - Vector3 maxs(region_maxs[0]+32, region_maxs[1]+32, region_maxs[2]+32); - - // vary mins - for(std::size_t i=0; i<3; i++) - { - Vector3 mins(region_mins[0]-32, region_mins[1]-32, region_mins[2]-32); - mins[i] = region_maxs[i]; - Brush_ConstructCuboid(*Node_getBrush(*brushes[i+3]), aabb_for_minmax(mins, maxs), texdef_name_default(), TextureProjection()); - } - } -} - - -class FaceSetTexdef -{ - const TextureProjection& m_projection; -public: - FaceSetTexdef(const TextureProjection& projection) : m_projection(projection) - { - } - void operator()(Face& face) const - { - face.SetTexdef(m_projection); - } -}; - -void Scene_BrushSetTexdef_Selected(scene::Graph& graph, const TextureProjection& projection) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetTexdef(projection)); - SceneChangeNotify(); -} - -void Scene_BrushSetTexdef_Component_Selected(scene::Graph& graph, const TextureProjection& projection) -{ - Scene_ForEachSelectedBrushFace(graph, FaceSetTexdef(projection)); - SceneChangeNotify(); -} - - -class FaceSetFlags -{ - const ContentsFlagsValue& m_projection; -public: - FaceSetFlags(const ContentsFlagsValue& flags) : m_projection(flags) - { - } - void operator()(Face& face) const - { - face.SetFlags(m_projection); - } -}; - -void Scene_BrushSetFlags_Selected(scene::Graph& graph, const ContentsFlagsValue& flags) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetFlags(flags)); - SceneChangeNotify(); -} - -void Scene_BrushSetFlags_Component_Selected(scene::Graph& graph, const ContentsFlagsValue& flags) -{ - Scene_ForEachSelectedBrushFace(graph, FaceSetFlags(flags)); - SceneChangeNotify(); -} - -class FaceShiftTexdef -{ - float m_s, m_t; -public: - FaceShiftTexdef(float s, float t) : m_s(s), m_t(t) - { - } - void operator()(Face& face) const - { - face.ShiftTexdef(m_s, m_t); - } -}; - -void Scene_BrushShiftTexdef_Selected(scene::Graph& graph, float s, float t) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceShiftTexdef(s, t)); - SceneChangeNotify(); -} - -void Scene_BrushShiftTexdef_Component_Selected(scene::Graph& graph, float s, float t) -{ - Scene_ForEachSelectedBrushFace(graph, FaceShiftTexdef(s, t)); - SceneChangeNotify(); -} - -class FaceScaleTexdef -{ - float m_s, m_t; -public: - FaceScaleTexdef(float s, float t) : m_s(s), m_t(t) - { - } - void operator()(Face& face) const - { - face.ScaleTexdef(m_s, m_t); - } -}; - -void Scene_BrushScaleTexdef_Selected(scene::Graph& graph, float s, float t) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceScaleTexdef(s, t)); - SceneChangeNotify(); -} - -void Scene_BrushScaleTexdef_Component_Selected(scene::Graph& graph, float s, float t) -{ - Scene_ForEachSelectedBrushFace(graph, FaceScaleTexdef(s, t)); - SceneChangeNotify(); -} - -class FaceRotateTexdef -{ - float m_angle; -public: - FaceRotateTexdef(float angle) : m_angle(angle) - { - } - void operator()(Face& face) const - { - face.RotateTexdef(m_angle); - } -}; - -void Scene_BrushRotateTexdef_Selected(scene::Graph& graph, float angle) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceRotateTexdef(angle)); - SceneChangeNotify(); -} - -void Scene_BrushRotateTexdef_Component_Selected(scene::Graph& graph, float angle) -{ - Scene_ForEachSelectedBrushFace(graph, FaceRotateTexdef(angle)); - SceneChangeNotify(); -} - - -class FaceSetShader -{ - const char* m_name; -public: - FaceSetShader(const char* name) : m_name(name) {} - void operator()(Face& face) const - { - face.SetShader(m_name); - } -}; - -void Scene_BrushSetShader_Selected(scene::Graph& graph, const char* name) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetShader(name)); - SceneChangeNotify(); -} - -void Scene_BrushSetShader_Component_Selected(scene::Graph& graph, const char* name) -{ - Scene_ForEachSelectedBrushFace(graph, FaceSetShader(name)); - SceneChangeNotify(); -} - -class FaceSetDetail -{ - bool m_detail; -public: - FaceSetDetail(bool detail) : m_detail(detail) - { - } - void operator()(Face& face) const - { - face.setDetail(m_detail); - } -}; - -void Scene_BrushSetDetail_Selected(scene::Graph& graph, bool detail) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetDetail(detail)); - SceneChangeNotify(); -} - -bool Face_FindReplaceShader(Face& face, const char* find, const char* replace) -{ - if(shader_equal(face.GetShader(), find)) - { - face.SetShader(replace); - return true; - } - return false; -} - -class FaceFindReplaceShader -{ - const char* m_find; - const char* m_replace; -public: - FaceFindReplaceShader(const char* find, const char* replace) : m_find(find), m_replace(replace) - { - } - void operator()(Face& face) const - { - Face_FindReplaceShader(face, m_find, m_replace); - } -}; - -class FaceFindShader -{ - const char* m_find; - const char* m_replace; -public: - FaceFindShader(const char* find) : m_find(find) - { - } - void operator()(FaceInstance& faceinst) const - { - if(shader_equal(faceinst.getFace().GetShader(), m_find)) - { - faceinst.setSelected(SelectionSystem::eFace, true); - } - } -}; - -bool DoingSearch(const char *repl) -{ - return (repl == NULL || (strcmp("textures/", repl)==0)); -} - -void Scene_BrushFindReplaceShader(scene::Graph& graph, const char* find, const char* replace) -{ - if (DoingSearch(replace)) - { - Scene_ForEachBrush_ForEachFaceInstance(graph, FaceFindShader(find)); - } - else - { - Scene_ForEachBrush_ForEachFace(graph, FaceFindReplaceShader(find, replace)); - } -} - -void Scene_BrushFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace) -{ - if (DoingSearch(replace)) - { - Scene_ForEachSelectedBrush_ForEachFaceInstance(graph, - FaceFindShader(find)); - } - else - { - Scene_ForEachSelectedBrush_ForEachFace(graph, - FaceFindReplaceShader(find, replace)); - } -} - -// TODO: find for components -// d1223m: dont even know what they are... -void Scene_BrushFindReplaceShader_Component_Selected(scene::Graph& graph, const char* find, const char* replace) -{ - if (DoingSearch(replace)) - { - - } - else - { - Scene_ForEachSelectedBrushFace(graph, FaceFindReplaceShader(find, replace)); - } -} - - -class FaceFitTexture -{ - float m_s_repeat, m_t_repeat; -public: - FaceFitTexture(float s_repeat, float t_repeat) : m_s_repeat(s_repeat), m_t_repeat(t_repeat) - { - } - void operator()(Face& face) const - { - face.FitTexture(m_s_repeat, m_t_repeat); - } -}; - -void Scene_BrushFitTexture_Selected(scene::Graph& graph, float s_repeat, float t_repeat) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceFitTexture(s_repeat, t_repeat)); - SceneChangeNotify(); -} - -void Scene_BrushFitTexture_Component_Selected(scene::Graph& graph, float s_repeat, float t_repeat) -{ - Scene_ForEachSelectedBrushFace(graph, FaceFitTexture(s_repeat, t_repeat)); - SceneChangeNotify(); -} - -TextureProjection g_defaultTextureProjection; -const TextureProjection& TextureTransform_getDefault() -{ - TexDef_Construct_Default(g_defaultTextureProjection); - return g_defaultTextureProjection; -} - -void Scene_BrushConstructPrefab(scene::Graph& graph, EBrushPrefab type, std::size_t sides, const char* shader) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); - - Brush* brush = Node_getBrush(path.top()); - if(brush != 0) - { - AABB bounds = brush->localAABB(); // copy bounds because the brush will be modified - Brush_ConstructPrefab(*brush, type, bounds, sides, shader, TextureTransform_getDefault()); - SceneChangeNotify(); - } - } -} - -void Scene_BrushResize_Selected(scene::Graph& graph, const AABB& bounds, const char* shader) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); - - Brush* brush = Node_getBrush(path.top()); - if(brush != 0) - { - Brush_ConstructCuboid(*brush, bounds, shader, TextureTransform_getDefault()); - SceneChangeNotify(); - } - } -} - -bool Brush_hasShader(const Brush& brush, const char* name) -{ - for(Brush::const_iterator i = brush.begin(); i != brush.end(); ++i) - { - if(shader_equal((*i)->GetShader(), name)) - { - return true; - } - } - return false; -} - -class BrushSelectByShaderWalker : public scene::Graph::Walker -{ - const char* m_name; -public: - BrushSelectByShaderWalker(const char* name) - : m_name(name) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Brush* brush = Node_getBrush(path.top()); - if(brush != 0 && Brush_hasShader(*brush, m_name)) - { - Instance_getSelectable(instance)->setSelected(true); - } - } - return true; - } -}; - -void Scene_BrushSelectByShader(scene::Graph& graph, const char* name) -{ - graph.traverse(BrushSelectByShaderWalker(name)); -} - -class FaceSelectByShader -{ - const char* m_name; -public: - FaceSelectByShader(const char* name) - : m_name(name) - { - } - void operator()(FaceInstance& face) const - { - printf("checking %s = %s\n", face.getFace().GetShader(), m_name); - if(shader_equal(face.getFace().GetShader(), m_name)) - { - face.setSelected(SelectionSystem::eFace, true); - } - } -}; - -void Scene_BrushSelectByShader_Component(scene::Graph& graph, const char* name) -{ - Scene_ForEachSelectedBrush_ForEachFaceInstance(graph, FaceSelectByShader(name)); -} - -class FaceGetTexdef -{ - TextureProjection& m_projection; - mutable bool m_done; -public: - FaceGetTexdef(TextureProjection& projection) - : m_projection(projection), m_done(false) - { - } - void operator()(Face& face) const - { - if(!m_done) - { - m_done = true; - face.GetTexdef(m_projection); - } - } -}; - - -void Scene_BrushGetTexdef_Selected(scene::Graph& graph, TextureProjection& projection) -{ - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceGetTexdef(projection)); -} - -void Scene_BrushGetTexdef_Component_Selected(scene::Graph& graph, TextureProjection& projection) -{ -#if 1 - if(!g_SelectedFaceInstances.empty()) - { - FaceInstance& faceInstance = g_SelectedFaceInstances.last(); - faceInstance.getFace().GetTexdef(projection); - } -#else - FaceGetTexdef visitor(projection); - Scene_ForEachSelectedBrushFace(graph, visitor); -#endif -} - -void Scene_BrushGetShaderSize_Component_Selected(scene::Graph& graph, size_t& width, size_t& height) -{ - if(!g_SelectedFaceInstances.empty()) - { - FaceInstance& faceInstance = g_SelectedFaceInstances.last(); - width = faceInstance.getFace().getShader().width(); - height = faceInstance.getFace().getShader().height(); - } -} - - -class FaceGetFlags -{ - ContentsFlagsValue& m_flags; - mutable bool m_done; -public: - FaceGetFlags(ContentsFlagsValue& flags) - : m_flags(flags), m_done(false) - { - } - void operator()(Face& face) const - { - if(!m_done) - { - m_done = true; - face.GetFlags(m_flags); - } - } -}; - - -void Scene_BrushGetFlags_Selected(scene::Graph& graph, ContentsFlagsValue& flags) -{ -#if 1 - if(GlobalSelectionSystem().countSelected() != 0) - { - BrushInstance* brush = Instance_getBrush(GlobalSelectionSystem().ultimateSelected()); - if(brush != 0) - { - Brush_forEachFace(*brush, FaceGetFlags(flags)); - } - } -#else - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceGetFlags(flags)); -#endif -} - -void Scene_BrushGetFlags_Component_Selected(scene::Graph& graph, ContentsFlagsValue& flags) -{ -#if 1 - if(!g_SelectedFaceInstances.empty()) - { - FaceInstance& faceInstance = g_SelectedFaceInstances.last(); - faceInstance.getFace().GetFlags(flags); - } -#else - Scene_ForEachSelectedBrushFace(graph, FaceGetFlags(flags)); -#endif -} - - -class FaceGetShader -{ - CopiedString& m_shader; - mutable bool m_done; -public: - FaceGetShader(CopiedString& shader) - : m_shader(shader), m_done(false) - { - } - void operator()(Face& face) const - { - if(!m_done) - { - m_done = true; - m_shader = face.GetShader(); - } - } -}; - -void Scene_BrushGetShader_Selected(scene::Graph& graph, CopiedString& shader) -{ -#if 1 - if(GlobalSelectionSystem().countSelected() != 0) - { - BrushInstance* brush = Instance_getBrush(GlobalSelectionSystem().ultimateSelected()); - if(brush != 0) - { - Brush_forEachFace(*brush, FaceGetShader(shader)); - } - } -#else - Scene_ForEachSelectedBrush_ForEachFace(graph, FaceGetShader(shader)); -#endif -} - -void Scene_BrushGetShader_Component_Selected(scene::Graph& graph, CopiedString& shader) -{ -#if 1 - if(!g_SelectedFaceInstances.empty()) - { - FaceInstance& faceInstance = g_SelectedFaceInstances.last(); - shader = faceInstance.getFace().GetShader(); - } -#else - FaceGetShader visitor(shader); - Scene_ForEachSelectedBrushFace(graph, visitor); -#endif -} - - -class filter_face_shader : public FaceFilter -{ - const char* m_shader; -public: - filter_face_shader(const char* shader) : m_shader(shader) - { - } - bool filter(const Face& face) const - { - return shader_equal(face.GetShader(), m_shader); - } -}; - -class filter_face_shader_prefix : public FaceFilter -{ - const char* m_prefix; -public: - filter_face_shader_prefix(const char* prefix) : m_prefix(prefix) - { - } - bool filter(const Face& face) const - { - return shader_equal_n(face.GetShader(), m_prefix, strlen(m_prefix)); - } -}; - -class filter_face_flags : public FaceFilter -{ - int m_flags; -public: - filter_face_flags(int flags) : m_flags(flags) - { - } - bool filter(const Face& face) const - { - return (face.getShader().shaderFlags() & m_flags) != 0; - } -}; - -class filter_face_contents : public FaceFilter -{ - int m_contents; -public: - filter_face_contents(int contents) : m_contents(contents) - { - } - bool filter(const Face& face) const - { - return (face.getShader().m_flags.m_contentFlags & m_contents) != 0; - } -}; - - - -class FaceFilterAny -{ - FaceFilter* m_filter; - bool& m_filtered; -public: - FaceFilterAny(FaceFilter* filter, bool& filtered) : m_filter(filter), m_filtered(filtered) - { - m_filtered = false; - } - void operator()(Face& face) const - { - if(m_filter->filter(face)) - { - m_filtered = true; - } - } -}; - -class filter_brush_any_face : public BrushFilter -{ - FaceFilter* m_filter; -public: - filter_brush_any_face(FaceFilter* filter) : m_filter(filter) - { - } - bool filter(const Brush& brush) const - { - bool filtered; - Brush_forEachFace(brush, FaceFilterAny(m_filter, filtered)); - return filtered; - } -}; - -class FaceFilterAll -{ - FaceFilter* m_filter; - bool& m_filtered; -public: - FaceFilterAll(FaceFilter* filter, bool& filtered) : m_filter(filter), m_filtered(filtered) - { - m_filtered = true; - } - void operator()(Face& face) const - { - if(!m_filter->filter(face)) - { - m_filtered = false; - } - } -}; - -class filter_brush_all_faces : public BrushFilter -{ - FaceFilter* m_filter; -public: - filter_brush_all_faces(FaceFilter* filter) : m_filter(filter) - { - } - bool filter(const Brush& brush) const - { - bool filtered; - Brush_forEachFace(brush, FaceFilterAll(m_filter, filtered)); - return filtered; - } -}; - - -filter_face_flags g_filter_face_clip(QER_CLIP); -filter_brush_all_faces g_filter_brush_clip(&g_filter_face_clip); - -filter_face_shader g_filter_face_clip_q2("textures/clip"); -filter_brush_all_faces g_filter_brush_clip_q2(&g_filter_face_clip_q2); - -filter_face_shader g_filter_face_weapclip("textures/common/weapclip"); -filter_brush_all_faces g_filter_brush_weapclip(&g_filter_face_weapclip); - -filter_face_shader g_filter_face_commonclip("textures/common/clip"); -filter_brush_all_faces g_filter_brush_commonclip(&g_filter_face_commonclip); - -filter_face_shader g_filter_face_fullclip("textures/common/fullclip"); -filter_brush_all_faces g_filter_brush_fullclip(&g_filter_face_fullclip); - -filter_face_shader g_filter_face_botclip("textures/common/botclip"); -filter_brush_all_faces g_filter_brush_botclip(&g_filter_face_botclip); - -filter_face_shader_prefix g_filter_face_caulk("textures/common/caulk"); -filter_brush_all_faces g_filter_brush_caulk(&g_filter_face_caulk); - -filter_face_shader_prefix g_filter_face_caulk_ja("textures/system/caulk"); -filter_brush_all_faces g_filter_brush_caulk_ja(&g_filter_face_caulk_ja); - -filter_face_shader_prefix g_filter_face_liquids("textures/liquids/"); -filter_brush_any_face g_filter_brush_liquids(&g_filter_face_liquids); - -filter_face_shader g_filter_face_hint("textures/common/hint"); -filter_brush_any_face g_filter_brush_hint(&g_filter_face_hint); - -filter_face_shader g_filter_face_hint_q2("textures/hint"); -filter_brush_any_face g_filter_brush_hint_q2(&g_filter_face_hint_q2); - -filter_face_shader g_filter_face_hint_ja("textures/system/hint"); -filter_brush_any_face g_filter_brush_hint_ja(&g_filter_face_hint_ja); - -filter_face_shader g_filter_face_areaportal("textures/common/areaportal"); -filter_brush_all_faces g_filter_brush_areaportal(&g_filter_face_areaportal); - -filter_face_shader g_filter_face_visportal("textures/editor/visportal"); -filter_brush_any_face g_filter_brush_visportal(&g_filter_face_visportal); - -filter_face_shader g_filter_face_clusterportal("textures/common/clusterportal"); -filter_brush_all_faces g_filter_brush_clusterportal(&g_filter_face_clusterportal); - -filter_face_shader g_filter_face_lightgrid("textures/common/lightgrid"); -filter_brush_all_faces g_filter_brush_lightgrid(&g_filter_face_lightgrid); - -filter_face_flags g_filter_face_translucent(QER_TRANS); -filter_brush_all_faces g_filter_brush_translucent(&g_filter_face_translucent); - -filter_face_contents g_filter_face_detail(BRUSH_DETAIL_MASK); -filter_brush_all_faces g_filter_brush_detail(&g_filter_face_detail); - -filter_face_shader_prefix g_filter_face_decals("textures/decals/"); -filter_brush_any_face g_filter_brush_decals(&g_filter_face_decals); - - -void BrushFilters_construct() -{ - add_brush_filter(g_filter_brush_clip, EXCLUDE_CLIP); - add_brush_filter(g_filter_brush_clip_q2, EXCLUDE_CLIP); - add_brush_filter(g_filter_brush_weapclip, EXCLUDE_CLIP); - add_brush_filter(g_filter_brush_fullclip, EXCLUDE_CLIP); - add_brush_filter(g_filter_brush_commonclip, EXCLUDE_CLIP); - add_brush_filter(g_filter_brush_botclip, EXCLUDE_BOTCLIP); - add_brush_filter(g_filter_brush_caulk, EXCLUDE_CAULK); - add_brush_filter(g_filter_brush_caulk_ja, EXCLUDE_CAULK); - add_face_filter(g_filter_face_caulk, EXCLUDE_CAULK); - add_face_filter(g_filter_face_caulk_ja, EXCLUDE_CAULK); - add_brush_filter(g_filter_brush_liquids, EXCLUDE_LIQUIDS); - add_brush_filter(g_filter_brush_hint, EXCLUDE_HINTSSKIPS); - add_brush_filter(g_filter_brush_hint_q2, EXCLUDE_HINTSSKIPS); - add_brush_filter(g_filter_brush_hint_ja, EXCLUDE_HINTSSKIPS); - add_brush_filter(g_filter_brush_clusterportal, EXCLUDE_CLUSTERPORTALS); - add_brush_filter(g_filter_brush_visportal, EXCLUDE_VISPORTALS); - add_brush_filter(g_filter_brush_areaportal, EXCLUDE_AREAPORTALS); - add_brush_filter(g_filter_brush_translucent, EXCLUDE_TRANSLUCENT); - add_brush_filter(g_filter_brush_detail, EXCLUDE_DETAILS); - add_brush_filter(g_filter_brush_detail, EXCLUDE_STRUCTURAL, true); - add_brush_filter(g_filter_brush_lightgrid, EXCLUDE_LIGHTGRID); - add_brush_filter(g_filter_brush_decals, EXCLUDE_DECALS); -} - -#if 0 - -void normalquantisation_draw() -{ - glPointSize(1); - glBegin(GL_POINTS); - for(std::size_t i = 0; i <= c_quantise_normal; ++i) - { - for(std::size_t j = 0; j <= c_quantise_normal; ++j) - { - Normal3f vertex(normal3f_normalised(Normal3f( - static_cast(c_quantise_normal - j - i), - static_cast(i), - static_cast(j) - ))); - VectorScale(normal3f_to_array(vertex), 64.f, normal3f_to_array(vertex)); - glVertex3fv(normal3f_to_array(vertex)); - vertex.x = -vertex.x; - glVertex3fv(normal3f_to_array(vertex)); - } - } - glEnd(); -} - -class RenderableNormalQuantisation : public OpenGLRenderable -{ -public: - void render(RenderStateFlags state) const - { - normalquantisation_draw(); - } -}; - -const float g_test_quantise_normal = 1.f / static_cast(1 << 3); - -class TestNormalQuantisation -{ - void check_normal(const Normal3f& normal, const Normal3f& other) - { - spherical_t spherical = spherical_from_normal3f(normal); - double longditude = RAD2DEG(spherical.longditude); - double latitude = RAD2DEG(spherical.latitude); - double x = cos(spherical.longditude) * sin(spherical.latitude); - double y = sin(spherical.longditude) * sin(spherical.latitude); - double z = cos(spherical.latitude); - - ASSERT_MESSAGE(normal3f_dot(normal, other) > 0.99, "bleh"); - } - - void test_normal(const Normal3f& normal) - { - Normal3f test = normal3f_from_spherical(spherical_from_normal3f(normal)); - check_normal(normal, test); - - EOctant octant = normal3f_classify_octant(normal); - Normal3f folded = normal3f_fold_octant(normal, octant); - ESextant sextant = normal3f_classify_sextant(folded); - folded = normal3f_fold_sextant(folded, sextant); - - double scale = static_cast(c_quantise_normal) / (folded.x + folded.y + folded.z); - - double zbits = folded.z * scale; - double ybits = folded.y * scale; - - std::size_t zbits_q = static_cast(zbits); - std::size_t ybits_q = static_cast(ybits); - - ASSERT_MESSAGE(zbits_q <= (c_quantise_normal / 8) * 3, "bleh"); - ASSERT_MESSAGE(ybits_q <= (c_quantise_normal / 2), "bleh"); - ASSERT_MESSAGE(zbits_q + ((c_quantise_normal / 2) - ybits_q) <= (c_quantise_normal / 2), "bleh"); - - std::size_t y_t = (zbits_q < (c_quantise_normal / 4)) ? ybits_q : (c_quantise_normal / 2) - ybits_q; - std::size_t z_t = (zbits_q < (c_quantise_normal / 4)) ? zbits_q : (c_quantise_normal / 2) - zbits_q; - std::size_t index = (c_quantise_normal / 4) * y_t + z_t; - ASSERT_MESSAGE(index <= (c_quantise_normal / 4)*(c_quantise_normal / 2), "bleh"); - - Normal3f tmp(c_quantise_normal - zbits_q - ybits_q, ybits_q, zbits_q); - tmp = normal3f_normalised(tmp); - - Normal3f unfolded = normal3f_unfold_octant(normal3f_unfold_sextant(tmp, sextant), octant); - - check_normal(normal, unfolded); - - double dot = normal3f_dot(normal, unfolded); - float length = VectorLength(normal3f_to_array(unfolded)); - float inv_length = 1 / length; - - Normal3f quantised = normal3f_quantised(normal); - check_normal(normal, quantised); - } - void test2(const Normal3f& normal, const Normal3f& other) - { - if(normal3f_quantised(normal) != normal3f_quantised(other)) - { - int bleh = 0; - } - } - - static Normal3f normalise(float x, float y, float z) - { - return normal3f_normalised(Normal3f(x, y, z)); - } - - float vec_rand() - { - return static_cast(rand() - (RAND_MAX/2)); - } - - Normal3f normal3f_rand() - { - return normalise(vec_rand(), vec_rand(), vec_rand()); - } - -public: - TestNormalQuantisation() - { - for(int i = 4096; i > 0; --i) - test_normal(normal3f_rand()); - - test_normal(normalise(1, 0, 0)); - test_normal(normalise(0, 1, 0)); - test_normal(normalise(0, 0, 1)); - test_normal(normalise(1, 1, 0)); - test_normal(normalise(1, 0, 1)); - test_normal(normalise(0, 1, 1)); - - test_normal(normalise(10000, 10000, 10000)); - test_normal(normalise(10000, 10000, 10001)); - test_normal(normalise(10000, 10000, 10002)); - test_normal(normalise(10000, 10000, 10010)); - test_normal(normalise(10000, 10000, 10020)); - test_normal(normalise(10000, 10000, 10030)); - test_normal(normalise(10000, 10000, 10100)); - test_normal(normalise(10000, 10000, 10101)); - test_normal(normalise(10000, 10000, 10102)); - test_normal(normalise(10000, 10000, 10200)); - test_normal(normalise(10000, 10000, 10201)); - test_normal(normalise(10000, 10000, 10202)); - test_normal(normalise(10000, 10000, 10203)); - test_normal(normalise(10000, 10000, 10300)); - - - test2(normalise(10000, 10000, 10000), normalise(10000, 10000, 10001)); - test2(normalise(10000, 10000, 10001), normalise(10000, 10001, 10000)); - } -}; - -TestNormalQuantisation g_testNormalQuantisation; - - -#endif - -#if 0 -class TestSelectableObserver : public observer_template -{ -public: - void notify(const Selectable& arguments) - { - bool bleh = arguments.isSelected(); - } -}; - -inline void test_bleh() -{ - TestSelectableObserver test; - ObservableSelectableInstance< SingleObservable< SelectionChangeCallback > > bleh; - bleh.attach(test); - bleh.setSelected(true); - bleh.detach(test); -} - -class TestBleh -{ -public: - TestBleh() - { - test_bleh(); - } -}; - -const TestBleh testbleh; -#endif - - -#if 0 -class TestRefcountedString -{ -public: - TestRefcountedString() - { - { - // copy construct - SmartString string1("string1"); - SmartString string2(string1); - SmartString string3(string2); - } - { - // refcounted assignment - SmartString string1("string1"); - SmartString string2("string2"); - string1 = string2; - } - { - // copy assignment - SmartString string1("string1"); - SmartString string2("string2"); - string1 = string2.c_str(); - } - { - // self-assignment - SmartString string1("string1"); - string1 = string1; - } - { - // self-assignment via another reference - SmartString string1("string1"); - SmartString string2(string1); - string1 = string2; - } - } -}; - -const TestRefcountedString g_testRefcountedString; - -#endif - -void Select_MakeDetail() -{ - UndoableCommand undo("brushSetDetail"); - Scene_BrushSetDetail_Selected(GlobalSceneGraph(), true); -} - -void Select_MakeStructural() -{ - UndoableCommand undo("brushClearDetail"); - Scene_BrushSetDetail_Selected(GlobalSceneGraph(), false); -} - -class BrushMakeSided -{ - std::size_t m_count; -public: - BrushMakeSided(std::size_t count) - : m_count(count) - { - } - void set() - { - Scene_BrushConstructPrefab(GlobalSceneGraph(), eBrushPrism, m_count, TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); - } - typedef MemberCaller SetCaller; -}; - - -BrushMakeSided g_brushmakesided3(3); -BrushMakeSided g_brushmakesided4(4); -BrushMakeSided g_brushmakesided5(5); -BrushMakeSided g_brushmakesided6(6); -BrushMakeSided g_brushmakesided7(7); -BrushMakeSided g_brushmakesided8(8); -BrushMakeSided g_brushmakesided9(9); - -inline int axis_for_viewtype(int viewtype) -{ - switch(viewtype) - { - case XY: - return 2; - case XZ: - return 1; - case YZ: - return 0; - } - return 2; -} - -class BrushPrefab -{ - EBrushPrefab m_type; -public: - BrushPrefab(EBrushPrefab type) - : m_type(type) - { - } - void set() - { - DoSides(m_type, axis_for_viewtype(GetViewAxis())); - } - typedef MemberCaller SetCaller; -}; - -BrushPrefab g_brushprism(eBrushPrism); -BrushPrefab g_brushcone(eBrushCone); -BrushPrefab g_brushsphere(eBrushSphere); -BrushPrefab g_brushrock(eBrushRock); - - -void FlipClip(); -void SplitClip(); -void Clip(); -void OnClipMode(bool enable); -bool ClipMode(); - - -void ClipSelected() -{ - if(ClipMode()) - { - UndoableCommand undo("clipperClip"); - Clip(); - } -} - -void SplitSelected() -{ - if(ClipMode()) - { - UndoableCommand undo("clipperSplit"); - SplitClip(); - } -} - -void FlipClipper() -{ - FlipClip(); -} - - -Callback g_texture_lock_status_changed; -BoolExportCaller g_texdef_movelock_caller(g_brush_texturelock_enabled); -ToggleItem g_texdef_movelock_item(g_texdef_movelock_caller); - -void Texdef_ToggleMoveLock() -{ - g_brush_texturelock_enabled = !g_brush_texturelock_enabled; - g_texdef_movelock_item.update(); - g_texture_lock_status_changed(); -} - - - - - -void Brush_registerCommands() -{ - GlobalToggles_insert("TogTexLock", FreeCaller(), ToggleItem::AddCallbackCaller(g_texdef_movelock_item), Accelerator('T', (GdkModifierType)GDK_SHIFT_MASK)); - - GlobalCommands_insert("BrushPrism", BrushPrefab::SetCaller(g_brushprism)); - GlobalCommands_insert("BrushCone", BrushPrefab::SetCaller(g_brushcone)); - GlobalCommands_insert("BrushSphere", BrushPrefab::SetCaller(g_brushsphere)); - GlobalCommands_insert("BrushRock", BrushPrefab::SetCaller(g_brushrock)); - - GlobalCommands_insert("Brush3Sided", BrushMakeSided::SetCaller(g_brushmakesided3), Accelerator('3', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Brush4Sided", BrushMakeSided::SetCaller(g_brushmakesided4), Accelerator('4', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Brush5Sided", BrushMakeSided::SetCaller(g_brushmakesided5), Accelerator('5', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Brush6Sided", BrushMakeSided::SetCaller(g_brushmakesided6), Accelerator('6', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Brush7Sided", BrushMakeSided::SetCaller(g_brushmakesided7), Accelerator('7', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Brush8Sided", BrushMakeSided::SetCaller(g_brushmakesided8), Accelerator('8', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Brush9Sided", BrushMakeSided::SetCaller(g_brushmakesided9), Accelerator('9', (GdkModifierType)GDK_CONTROL_MASK)); - - GlobalCommands_insert("ClipSelected", FreeCaller(), Accelerator(GDK_Return)); - GlobalCommands_insert("SplitSelected", FreeCaller(), Accelerator(GDK_Return, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("FlipClip", FreeCaller(), Accelerator(GDK_Return, (GdkModifierType)GDK_CONTROL_MASK)); - - GlobalCommands_insert("MakeDetail", FreeCaller(), Accelerator('M', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("MakeStructural", FreeCaller(), Accelerator('S', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); -} - -void Brush_constructMenu(GtkMenu* menu) -{ - create_menu_item_with_mnemonic(menu, "Prism...", "BrushPrism"); - create_menu_item_with_mnemonic(menu, "Cone...", "BrushCone"); - create_menu_item_with_mnemonic(menu, "Sphere...", "BrushSphere"); - create_menu_item_with_mnemonic(menu, "Rock...", "BrushRock"); - menu_separator (menu); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "CSG"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Make _Hollow", "CSGHollow"); - create_menu_item_with_mnemonic(menu_in_menu, "CSG _Subtract", "CSGSubtract"); - create_menu_item_with_mnemonic(menu_in_menu, "CSG _Merge", "CSGMerge"); - } - menu_separator(menu); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Clipper"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - - create_menu_item_with_mnemonic(menu_in_menu, "Clip selection", "ClipSelected"); - create_menu_item_with_mnemonic(menu_in_menu, "Split selection", "SplitSelected"); - create_menu_item_with_mnemonic(menu_in_menu, "Flip Clip orientation", "FlipClip"); - } - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Make detail", "MakeDetail"); - create_menu_item_with_mnemonic(menu, "Make structural", "MakeStructural"); - create_menu_item_with_mnemonic(menu, "Snap selection to _grid", "SnapToGrid"); - - create_check_menu_item_with_mnemonic(menu, "Texture Lock", "TogTexLock"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Copy Face Texture", "FaceCopyTexture"); - create_menu_item_with_mnemonic(menu, "Paste Face Texture", "FacePasteTexture"); - - command_connect_accelerator("Brush3Sided"); - command_connect_accelerator("Brush4Sided"); - command_connect_accelerator("Brush5Sided"); - command_connect_accelerator("Brush6Sided"); - command_connect_accelerator("Brush7Sided"); - command_connect_accelerator("Brush8Sided"); - command_connect_accelerator("Brush9Sided"); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushmanip.h b/misc/mediasource/extra/netradiant-src/radiant/brushmanip.h deleted file mode 100644 index 74ae68b4..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushmanip.h +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright (C) 1999-2006 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 (INCLUDED_BRUSHWRAPPER_H) -#define INCLUDED_BRUSHWRAPPER_H - -#include -#include "string/stringfwd.h" -#include "generic/callbackfwd.h" - -enum EBrushPrefab -{ - eBrushCuboid, - eBrushPrism, - eBrushCone, - eBrushSphere, - eBrushRock, -}; - -class TextureProjection; -class ContentsFlagsValue; -namespace scene -{ - class Graph; -} -void Scene_BrushConstructPrefab(scene::Graph& graph, EBrushPrefab type, std::size_t sides, const char* shader); -class AABB; -void Scene_BrushResize_Selected(scene::Graph& graph, const AABB& bounds, const char* shader); -void Scene_BrushSetTexdef_Selected(scene::Graph& graph, const TextureProjection& projection); -void Scene_BrushSetTexdef_Component_Selected(scene::Graph& graph, const TextureProjection& projection); -void Scene_BrushGetTexdef_Selected(scene::Graph& graph, TextureProjection& projection); -void Scene_BrushGetTexdef_Component_Selected(scene::Graph& graph, TextureProjection& projection); -void Scene_BrushGetShaderSize_Component_Selected(scene::Graph& graph, size_t& width, size_t& height); -void Scene_BrushSetFlags_Selected(scene::Graph& graph, const ContentsFlagsValue& flags); -void Scene_BrushSetFlags_Component_Selected(scene::Graph& graph, const ContentsFlagsValue& flags); -void Scene_BrushGetFlags_Selected(scene::Graph& graph, ContentsFlagsValue& flags); -void Scene_BrushGetFlags_Component_Selected(scene::Graph& graph, ContentsFlagsValue& flags); -void Scene_BrushShiftTexdef_Selected(scene::Graph& graph, float s, float t); -void Scene_BrushShiftTexdef_Component_Selected(scene::Graph& graph, float s, float t); -void Scene_BrushScaleTexdef_Selected(scene::Graph& graph, float s, float t); -void Scene_BrushScaleTexdef_Component_Selected(scene::Graph& graph, float s, float t); -void Scene_BrushRotateTexdef_Selected(scene::Graph& graph, float angle); -void Scene_BrushRotateTexdef_Component_Selected(scene::Graph& graph, float angle); -void Scene_BrushSetShader_Selected(scene::Graph& graph, const char* name); -void Scene_BrushSetShader_Component_Selected(scene::Graph& graph, const char* name); -void Scene_BrushGetShader_Selected(scene::Graph& graph, CopiedString& shader); -void Scene_BrushGetShader_Component_Selected(scene::Graph& graph, CopiedString& shader); -void Scene_BrushFindReplaceShader(scene::Graph& graph, const char* find, const char* replace); -void Scene_BrushFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace); -void Scene_BrushFindReplaceShader_Component_Selected(scene::Graph& graph, const char* find, const char* replace); -void Scene_BrushSelectByShader(scene::Graph& graph, const char* name); -void Scene_BrushSelectByShader_Component(scene::Graph& graph, const char* name); -void Scene_BrushFitTexture_Selected(scene::Graph& graph, float s_repeat, float t_repeat); -void Scene_BrushFitTexture_Component_Selected(scene::Graph& graph, float s_repeat, float t_repeat); - -typedef struct _GtkMenu GtkMenu; -void Brush_constructMenu(GtkMenu* menu); - -extern Callback g_texture_lock_status_changed; - -void BrushFilters_construct(); -void Brush_registerCommands(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushmodule.cpp b/misc/mediasource/extra/netradiant-src/radiant/brushmodule.cpp deleted file mode 100644 index 21cec0ee..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushmodule.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "brushmodule.h" - -#include "qerplugin.h" - -#include "brushnode.h" -#include "brushmanip.h" - -#include "preferencesystem.h" -#include "stringio.h" - -#include "map.h" -#include "qe3.h" -#include "mainframe.h" -#include "preferences.h" - -LatchedBool g_useAlternativeTextureProjection(false, "Use alternative texture-projection"); -bool g_showAlternativeTextureProjectionOption = false; -bool g_brush_always_caulk; - -bool getTextureLockEnabled() -{ - return g_brush_texturelock_enabled; -} - -void Face_importSnapPlanes(bool value) -{ - Face::m_quantise = value ? quantiseInteger : quantiseFloating; -} -typedef FreeCaller1 FaceImportSnapPlanesCaller; - -void Face_exportSnapPlanes(const BoolImportCallback& importer) -{ - importer(Face::m_quantise == quantiseInteger); -} -typedef FreeCaller1 FaceExportSnapPlanesCaller; - -void Brush_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox( - "", "Snap planes to integer grid", - FaceImportSnapPlanesCaller(), - FaceExportSnapPlanesCaller() - ); - page.appendEntry( - "Default texture scale", - g_texdef_default_scale - ); - if(g_showAlternativeTextureProjectionOption) - { - page.appendCheckBox( - "", "Use alternative texture-projection", - LatchedBoolImportCaller(g_useAlternativeTextureProjection), - BoolExportCaller(g_useAlternativeTextureProjection.m_latched) - ); - } - // d1223m - page.appendCheckBox("", - "Always use caulk for new brushes", - g_brush_always_caulk - ); -} -void Brush_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Brush", "Brush Settings")); - Brush_constructPreferences(page); -} -void Brush_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - -void Brush_unlatchPreferences() -{ - Brush_toggleFormat(0); -} - -void Brush_toggleFormat(int i) -{ - if(g_showAlternativeTextureProjectionOption) - { - g_useAlternativeTextureProjection.m_value = g_useAlternativeTextureProjection.m_latched ^ i; - Brush::destroyStatic(); - Brush::constructStatic(g_useAlternativeTextureProjection.m_value ? eBrushTypeQuake3BP : eBrushTypeQuake3); - } -} - -int Brush_toggleFormatCount() -{ - if(g_showAlternativeTextureProjectionOption) - return 2; - return 1; -} - -void Brush_Construct(EBrushType type) -{ - if(type == eBrushTypeQuake3) - { - g_showAlternativeTextureProjectionOption = true; - - GlobalPreferenceSystem().registerPreference( - "AlternativeTextureProjection", - BoolImportStringCaller(g_useAlternativeTextureProjection.m_latched), - BoolExportStringCaller(g_useAlternativeTextureProjection.m_latched) - ); - g_useAlternativeTextureProjection.useLatched(); - - if(g_useAlternativeTextureProjection.m_value) - { - type = eBrushTypeQuake3BP; - } - - // d1223m - GlobalPreferenceSystem().registerPreference( - "BrushAlwaysCaulk", - BoolImportStringCaller(g_brush_always_caulk), - BoolExportStringCaller(g_brush_always_caulk)); - } - - Brush_registerCommands(); - Brush_registerPreferencesPage(); - - BrushFilters_construct(); - - BrushClipPlane::constructStatic(); - BrushInstance::constructStatic(); - Brush::constructStatic(type); - - Brush::m_maxWorldCoord = g_MaxWorldCoord; - BrushInstance::m_counter = &g_brushCount; - - g_texdef_default_scale = 0.5f; - const char* value = g_pGameDescription->getKeyValue("default_scale"); - if(!string_empty(value)) - { - float scale = static_cast(atof(value)); - if(scale != 0) - { - g_texdef_default_scale = scale; - } - else - { - globalErrorStream() << "error parsing \"default_scale\" attribute\n"; - } - } - - GlobalPreferenceSystem().registerPreference("TextureLock", BoolImportStringCaller(g_brush_texturelock_enabled), BoolExportStringCaller(g_brush_texturelock_enabled)); - GlobalPreferenceSystem().registerPreference("BrushSnapPlanes", makeBoolStringImportCallback(FaceImportSnapPlanesCaller()), makeBoolStringExportCallback(FaceExportSnapPlanesCaller())); - GlobalPreferenceSystem().registerPreference("TexdefDefaultScale", FloatImportStringCaller(g_texdef_default_scale), FloatExportStringCaller(g_texdef_default_scale)); - - GridStatus_getTextureLockEnabled = getTextureLockEnabled; - g_texture_lock_status_changed = FreeCaller(); -} - -void Brush_Destroy() -{ - Brush::m_maxWorldCoord = 0; - BrushInstance::m_counter = 0; - - Brush::destroyStatic(); - BrushInstance::destroyStatic(); - BrushClipPlane::destroyStatic(); -} - -void Brush_clipperColourChanged() -{ - BrushClipPlane::destroyStatic(); - BrushClipPlane::constructStatic(); -} - -void BrushFaceData_fromFace(const BrushFaceDataCallback& callback, Face& face) -{ - _QERFaceData faceData; - faceData.m_p0 = face.getPlane().planePoints()[0]; - faceData.m_p1 = face.getPlane().planePoints()[1]; - faceData.m_p2 = face.getPlane().planePoints()[2]; - faceData.m_shader = face.GetShader(); - faceData.m_texdef = face.getTexdef().m_projection.m_texdef; - faceData.contents = face.getShader().m_flags.m_contentFlags; - faceData.flags = face.getShader().m_flags.m_surfaceFlags; - faceData.value = face.getShader().m_flags.m_value; - callback(faceData); -} -typedef ConstReferenceCaller1 BrushFaceDataFromFaceCaller; -typedef Callback1 FaceCallback; - -class Quake3BrushCreator : public BrushCreator -{ -public: - scene::Node& createBrush() - { - return (new BrushNode)->node(); - } - bool useAlternativeTextureProjection() const - { - return g_useAlternativeTextureProjection.m_value; - } - void Brush_forEachFace(scene::Node& brush, const BrushFaceDataCallback& callback) - { - ::Brush_forEachFace(*Node_getBrush(brush), FaceCallback(BrushFaceDataFromFaceCaller(callback))); - } - bool Brush_addFace(scene::Node& brush, const _QERFaceData& faceData) - { - Node_getBrush(brush)->undoSave(); - return Node_getBrush(brush)->addPlane(faceData.m_p0, faceData.m_p1, faceData.m_p2, faceData.m_shader, TextureProjection(faceData.m_texdef, brushprimit_texdef_t(), Vector3(0, 0, 0), Vector3(0, 0, 0))) != 0; - } -}; - -Quake3BrushCreator g_Quake3BrushCreator; - -BrushCreator& GetBrushCreator() -{ - return g_Quake3BrushCreator; -} - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - - -class BrushDependencies : - public GlobalRadiantModuleRef, - public GlobalSceneGraphModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalSelectionModuleRef, - public GlobalOpenGLModuleRef, - public GlobalUndoModuleRef, - public GlobalFilterModuleRef -{ -}; - -class BrushDoom3API : public TypeSystemRef -{ - BrushCreator* m_brushdoom3; -public: - typedef BrushCreator Type; - STRING_CONSTANT(Name, "doom3"); - - BrushDoom3API() - { - Brush_Construct(eBrushTypeDoom3); - - m_brushdoom3 = &GetBrushCreator(); - } - ~BrushDoom3API() - { - Brush_Destroy(); - } - BrushCreator* getTable() - { - return m_brushdoom3; - } -}; - -typedef SingletonModule BrushDoom3Module; -typedef Static StaticBrushDoom3Module; -StaticRegisterModule staticRegisterBrushDoom3(StaticBrushDoom3Module::instance()); - - -class BrushQuake4API : public TypeSystemRef -{ - BrushCreator* m_brushquake4; -public: - typedef BrushCreator Type; - STRING_CONSTANT(Name, "quake4"); - - BrushQuake4API() - { - Brush_Construct(eBrushTypeQuake4); - - m_brushquake4 = &GetBrushCreator(); - } - ~BrushQuake4API() - { - Brush_Destroy(); - } - BrushCreator* getTable() - { - return m_brushquake4; - } -}; - -typedef SingletonModule BrushQuake4Module; -typedef Static StaticBrushQuake4Module; -StaticRegisterModule staticRegisterBrushQuake4(StaticBrushQuake4Module::instance()); - - -class BrushQuake3API : public TypeSystemRef -{ - BrushCreator* m_brushquake3; -public: - typedef BrushCreator Type; - STRING_CONSTANT(Name, "quake3"); - - BrushQuake3API() - { - Brush_Construct(eBrushTypeQuake3); - - m_brushquake3 = &GetBrushCreator(); - } - ~BrushQuake3API() - { - Brush_Destroy(); - } - BrushCreator* getTable() - { - return m_brushquake3; - } -}; - -typedef SingletonModule BrushQuake3Module; -typedef Static StaticBrushQuake3Module; -StaticRegisterModule staticRegisterBrushQuake3(StaticBrushQuake3Module::instance()); - - -class BrushQuake2API : public TypeSystemRef -{ - BrushCreator* m_brushquake2; -public: - typedef BrushCreator Type; - STRING_CONSTANT(Name, "quake2"); - - BrushQuake2API() - { - Brush_Construct(eBrushTypeQuake2); - - m_brushquake2 = &GetBrushCreator(); - } - ~BrushQuake2API() - { - Brush_Destroy(); - } - BrushCreator* getTable() - { - return m_brushquake2; - } -}; - -typedef SingletonModule BrushQuake2Module; -typedef Static StaticBrushQuake2Module; -StaticRegisterModule staticRegisterBrushQuake2(StaticBrushQuake2Module::instance()); - - -class BrushQuake1API : public TypeSystemRef -{ - BrushCreator* m_brushquake1; -public: - typedef BrushCreator Type; - STRING_CONSTANT(Name, "quake"); - - BrushQuake1API() - { - Brush_Construct(eBrushTypeQuake); - - m_brushquake1 = &GetBrushCreator(); - } - ~BrushQuake1API() - { - Brush_Destroy(); - } - BrushCreator* getTable() - { - return m_brushquake1; - } -}; - -typedef SingletonModule BrushQuake1Module; -typedef Static StaticBrushQuake1Module; -StaticRegisterModule staticRegisterBrushQuake1(StaticBrushQuake1Module::instance()); - - -class BrushHalfLifeAPI : public TypeSystemRef -{ - BrushCreator* m_brushhalflife; -public: - typedef BrushCreator Type; - STRING_CONSTANT(Name, "halflife"); - - BrushHalfLifeAPI() - { - Brush_Construct(eBrushTypeHalfLife); - - m_brushhalflife = &GetBrushCreator(); - } - ~BrushHalfLifeAPI() - { - Brush_Destroy(); - } - BrushCreator* getTable() - { - return m_brushhalflife; - } -}; - -typedef SingletonModule BrushHalfLifeModule; -typedef Static StaticBrushHalfLifeModule; -StaticRegisterModule staticRegisterBrushHalfLife(StaticBrushHalfLifeModule::instance()); diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushmodule.h b/misc/mediasource/extra/netradiant-src/radiant/brushmodule.h deleted file mode 100644 index ac89a890..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushmodule.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_BRUSHMODULE_H) -#define INCLUDED_BRUSHMODULE_H - -void Brush_clipperColourChanged(); -void Brush_unlatchPreferences(); -int Brush_toggleFormatCount(); -void Brush_toggleFormat(int i); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushnode.cpp b/misc/mediasource/extra/netradiant-src/radiant/brushnode.cpp deleted file mode 100644 index 35f46877..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushnode.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "brushnode.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushnode.h b/misc/mediasource/extra/netradiant-src/radiant/brushnode.h deleted file mode 100644 index 5e1465e3..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushnode.h +++ /dev/null @@ -1,167 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_BRUSHNODE_H) -#define INCLUDED_BRUSHNODE_H - -#include "instancelib.h" -#include "brush.h" -#include "brushtokens.h" -#include "brushxml.h" - -class BrushNode : -public scene::Node::Symbiot, -public scene::Instantiable, -public scene::Cloneable -{ - class TypeCasts - { - NodeTypeCastTable m_casts; - public: - TypeCasts() - { - NodeStaticCast::install(m_casts); - NodeStaticCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::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; - InstanceSet m_instances; - Brush m_brush; - BrushTokenImporter m_mapImporter; - BrushTokenExporter m_mapExporter; - BrushXMLImporter m_xmlImporter; - BrushXMLExporter m_xmlExporter; - -public: - - typedef LazyStatic StaticTypeCasts; - - Snappable& get(NullType) - { - return m_brush; - } - TransformNode& get(NullType) - { - return m_brush; - } - Brush& get(NullType) - { - return m_brush; - } - XMLImporter& get(NullType) - { - return m_xmlImporter; - } - XMLExporter& get(NullType) - { - return m_xmlExporter; - } - MapImporter& get(NullType) - { - return m_mapImporter; - } - MapExporter& get(NullType) - { - return m_mapExporter; - } - Nameable& get(NullType) - { - return m_brush; - } - BrushDoom3& get(NullType) - { - return m_brush; - } - - BrushNode() : - m_node(this, this, StaticTypeCasts::instance().get()), - m_brush(m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), - m_mapImporter(m_brush), - m_mapExporter(m_brush), - m_xmlImporter(m_brush), - m_xmlExporter(m_brush) - { - } - BrushNode(const BrushNode& other) : - scene::Node::Symbiot(other), - scene::Instantiable(other), - scene::Cloneable(other), - m_node(this, this, StaticTypeCasts::instance().get()), - m_brush(other.m_brush, m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), - m_mapImporter(m_brush), - m_mapExporter(m_brush), - m_xmlImporter(m_brush), - m_xmlExporter(m_brush) - { - } - void release() - { - delete this; - } - scene::Node& node() - { - return m_node; - } - - scene::Node& clone() const - { - return (new BrushNode(*this))->node(); - } - - scene::Instance* create(const scene::Path& path, scene::Instance* parent) - { - return new BrushInstance(path, parent, m_brush); - } - 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); - } - scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) - { - return m_instances.erase(observer, path); - } -}; - -inline Brush* Node_getBrush(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushtokens.cpp b/misc/mediasource/extra/netradiant-src/radiant/brushtokens.cpp deleted file mode 100644 index e8674c98..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushtokens.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "brushtokens.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushtokens.h b/misc/mediasource/extra/netradiant-src/radiant/brushtokens.h deleted file mode 100644 index 19d8c7b9..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushtokens.h +++ /dev/null @@ -1,738 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_BRUSHTOKENS_H) -#define INCLUDED_BRUSHTOKENS_H - -#include "stringio.h" -#include "stream/stringstream.h" -#include "brush.h" - -inline bool FaceShader_importContentsFlagsValue(FaceShader& faceShader, Tokeniser& tokeniser) -{ - // parse the optional contents/flags/value - RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, faceShader.m_flags.m_contentFlags)); - RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, faceShader.m_flags.m_surfaceFlags)); - RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, faceShader.m_flags.m_value)); - return true; -} - -inline bool FaceTexdef_importTokens(FaceTexdef& texdef, Tokeniser& tokeniser) -{ - // parse texdef - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[0])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[1])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.rotate)); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[0])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[1])); - - ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_importTokens: bad texdef"); - return true; -} - -inline bool FaceTexdef_BP_importTokens(FaceTexdef& texdef, Tokeniser& tokeniser) -{ - // parse alternate texdef - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); - { - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[0][0])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[0][1])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[0][2])); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); - } - { - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[1][0])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[1][1])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[1][2])); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); - } - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); - return true; -} - -inline bool FaceTexdef_HalfLife_importTokens(FaceTexdef& texdef, Tokeniser& tokeniser) -{ - // parse texdef - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "[")); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_s.x())); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_s.y())); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_s.z())); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[0])); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "]")); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "[")); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_t.x())); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_t.y())); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_t.z())); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[1])); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "]")); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.rotate)); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[0])); - RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[1])); - - texdef.m_projection.m_texdef.rotate = -texdef.m_projection.m_texdef.rotate; - - ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_importTokens: bad texdef"); - return true; -} - -inline bool FacePlane_importTokens(FacePlane& facePlane, Tokeniser& tokeniser) -{ - // parse planepts - for(std::size_t i = 0; i<3; i++) - { - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); - for(std::size_t j = 0; j < 3; ++j) - { - RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, facePlane.planePoints()[i][j])); - } - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); - } - facePlane.MakePlane(); - return true; -} - -inline bool FacePlane_Doom3_importTokens(FacePlane& facePlane, Tokeniser& tokeniser) -{ - Plane3 plane; - // parse plane equation - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); - RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.a)); - RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.b)); - RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.c)); - RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.d)); - plane.d = -plane.d; - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); - - facePlane.setDoom3Plane(plane); - return true; -} - -inline bool FaceShader_Doom3_importTokens(FaceShader& faceShader, Tokeniser& tokeniser) -{ - const char *shader = tokeniser.getToken(); - if(shader == 0) - { - Tokeniser_unexpectedError(tokeniser, shader, "#shader-name"); - return false; - } - if(string_equal(shader, "_emptyname")) - { - shader = texdef_name_default(); - } - faceShader.setShader(shader); - return true; -} - -inline bool FaceShader_importTokens(FaceShader& faceShader, Tokeniser& tokeniser) -{ - const char* texture = tokeniser.getToken(); - if(texture == 0) - { - Tokeniser_unexpectedError(tokeniser, texture, "#texture-name"); - return false; - } - if(string_equal(texture, "NULL")) - { - faceShader.setShader(texdef_name_default()); - } - else - { - StringOutputStream shader(string_length(GlobalTexturePrefix_get()) + string_length(texture)); - shader << GlobalTexturePrefix_get() << texture; - faceShader.setShader(shader.c_str()); - } - return true; -} - - - - -class Doom3FaceTokenImporter -{ - Face& m_face; -public: - Doom3FaceTokenImporter(Face& face) : m_face(face) - { - } - bool importTokens(Tokeniser& tokeniser) - { - RETURN_FALSE_IF_FAIL(FacePlane_Doom3_importTokens(m_face.getPlane(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceTexdef_BP_importTokens(m_face.getTexdef(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_Doom3_importTokens(m_face.getShader(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); - - m_face.getTexdef().m_projectionInitialised = true; - m_face.getTexdef().m_scaleApplied = true; - - return true; - } -}; - -class Quake4FaceTokenImporter -{ - Face& m_face; -public: - Quake4FaceTokenImporter(Face& face) : m_face(face) - { - } - bool importTokens(Tokeniser& tokeniser) - { - RETURN_FALSE_IF_FAIL(FacePlane_Doom3_importTokens(m_face.getPlane(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceTexdef_BP_importTokens(m_face.getTexdef(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_Doom3_importTokens(m_face.getShader(), tokeniser)); - - m_face.getTexdef().m_projectionInitialised = true; - m_face.getTexdef().m_scaleApplied = true; - - return true; - } -}; - -class Quake2FaceTokenImporter -{ - Face& m_face; -public: - Quake2FaceTokenImporter(Face& face) : m_face(face) - { - } - bool importTokens(Tokeniser& tokeniser) - { - RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceTexdef_importTokens(m_face.getTexdef(), tokeniser)); - if(Tokeniser_nextTokenIsDigit(tokeniser)) - { - m_face.getShader().m_flags.m_specified = true; - RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); - } - m_face.getTexdef().m_scaleApplied = true; - return true; - } -}; - -class Quake3FaceTokenImporter -{ - Face& m_face; -public: - Quake3FaceTokenImporter(Face& face) : m_face(face) - { - } - bool importTokens(Tokeniser& tokeniser) - { - RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceTexdef_importTokens(m_face.getTexdef(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); - m_face.getTexdef().m_scaleApplied = true; - return true; - } -}; - -class Quake3BPFaceTokenImporter -{ - Face& m_face; -public: - Quake3BPFaceTokenImporter(Face& face) : m_face(face) - { - } - bool importTokens(Tokeniser& tokeniser) - { - RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceTexdef_BP_importTokens(m_face.getTexdef(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); - - m_face.getTexdef().m_projectionInitialised = true; - m_face.getTexdef().m_scaleApplied = true; - - return true; - } -}; - -class QuakeFaceTokenImporter -{ - Face& m_face; -public: - QuakeFaceTokenImporter(Face& face) : m_face(face) - { - } - bool importTokens(Tokeniser& tokeniser) - { - RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceTexdef_importTokens(m_face.getTexdef(), tokeniser)); - m_face.getTexdef().m_scaleApplied = true; - return true; - } -}; - -class HalfLifeFaceTokenImporter -{ - Face& m_face; -public: - HalfLifeFaceTokenImporter(Face& face) : m_face(face) - { - } - bool importTokens(Tokeniser& tokeniser) - { - RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); - RETURN_FALSE_IF_FAIL(FaceTexdef_HalfLife_importTokens(m_face.getTexdef(), tokeniser)); - m_face.getTexdef().m_scaleApplied = true; - return true; - } -}; - - -inline void FacePlane_Doom3_exportTokens(const FacePlane& facePlane, TokenWriter& writer) -{ - // write plane equation - writer.writeToken("("); - writer.writeFloat(facePlane.getDoom3Plane().a); - writer.writeFloat(facePlane.getDoom3Plane().b); - writer.writeFloat(facePlane.getDoom3Plane().c); - writer.writeFloat(-facePlane.getDoom3Plane().d); - writer.writeToken(")"); -} - -inline void FacePlane_exportTokens(const FacePlane& facePlane, TokenWriter& writer) -{ - // write planepts - for(std::size_t i=0; i<3; i++) - { - writer.writeToken("("); - for(std::size_t j=0; j<3; j++) - { - writer.writeFloat(Face::m_quantise(facePlane.planePoints()[i][j])); - } - writer.writeToken(")"); - } -} - -inline void FaceTexdef_BP_exportTokens(const FaceTexdef& faceTexdef, TokenWriter& writer) -{ - // write alternate texdef - writer.writeToken("("); - { - writer.writeToken("("); - for(std::size_t i=0;i<3;i++) - { - writer.writeFloat(faceTexdef.m_projection.m_brushprimit_texdef.coords[0][i]); - } - writer.writeToken(")"); - } - { - writer.writeToken("("); - for(std::size_t i=0;i<3;i++) - { - writer.writeFloat(faceTexdef.m_projection.m_brushprimit_texdef.coords[1][i]); - } - writer.writeToken(")"); - } - writer.writeToken(")"); -} - -inline void FaceTexdef_exportTokens(const FaceTexdef& faceTexdef, TokenWriter& writer) -{ - ASSERT_MESSAGE(texdef_sane(faceTexdef.m_projection.m_texdef), "FaceTexdef_exportTokens: bad texdef"); - // write texdef - writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[0]); - writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[1]); - writer.writeFloat(faceTexdef.m_projection.m_texdef.rotate); - writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[0]); - writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[1]); -} - -inline void FaceTexdef_HalfLife_exportTokens(const FaceTexdef& faceTexdef, TokenWriter& writer) -{ - ASSERT_MESSAGE(texdef_sane(faceTexdef.m_projection.m_texdef), "FaceTexdef_exportTokens: bad texdef"); - // write texdef - writer.writeToken("["); - writer.writeFloat(faceTexdef.m_projection.m_basis_s.x()); - writer.writeFloat(faceTexdef.m_projection.m_basis_s.y()); - writer.writeFloat(faceTexdef.m_projection.m_basis_s.z()); - writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[0]); - writer.writeToken("]"); - writer.writeToken("["); - writer.writeFloat(faceTexdef.m_projection.m_basis_t.x()); - writer.writeFloat(faceTexdef.m_projection.m_basis_t.y()); - writer.writeFloat(faceTexdef.m_projection.m_basis_t.z()); - writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[1]); - writer.writeToken("]"); - writer.writeFloat(-faceTexdef.m_projection.m_texdef.rotate); - writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[0]); - writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[1]); -} - -inline void FaceShader_ContentsFlagsValue_exportTokens(const FaceShader& faceShader, TokenWriter& writer) -{ - // write surface flags - writer.writeInteger(faceShader.m_flags.m_contentFlags); - writer.writeInteger(faceShader.m_flags.m_surfaceFlags); - writer.writeInteger(faceShader.m_flags.m_value); -} - -inline void FaceShader_exportTokens(const FaceShader& faceShader, TokenWriter& writer) -{ - // write shader name - if(string_empty(shader_get_textureName(faceShader.getShader()))) - { - writer.writeToken("NULL"); - } - else - { - writer.writeToken(shader_get_textureName(faceShader.getShader())); - } -} - -inline void FaceShader_Doom3_exportTokens(const FaceShader& faceShader, TokenWriter& writer) -{ - // write shader name - if(string_empty(shader_get_textureName(faceShader.getShader()))) - { - writer.writeString("_emptyname"); - } - else - { - writer.writeString(faceShader.getShader()); - } -} - -class Doom3FaceTokenExporter -{ - const Face& m_face; -public: - Doom3FaceTokenExporter(const Face& face) : m_face(face) - { - } - void exportTokens(TokenWriter& writer) const - { - FacePlane_Doom3_exportTokens(m_face.getPlane(), writer); - FaceTexdef_BP_exportTokens(m_face.getTexdef(), writer); - FaceShader_Doom3_exportTokens(m_face.getShader(), writer); - FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); - writer.nextLine(); - } -}; - -class Quake4FaceTokenExporter -{ - const Face& m_face; -public: - Quake4FaceTokenExporter(const Face& face) : m_face(face) - { - } - void exportTokens(TokenWriter& writer) const - { - FacePlane_Doom3_exportTokens(m_face.getPlane(), writer); - FaceTexdef_BP_exportTokens(m_face.getTexdef(), writer); - FaceShader_Doom3_exportTokens(m_face.getShader(), writer); - writer.nextLine(); - } -}; - -class Quake2FaceTokenExporter -{ - const Face& m_face; -public: - Quake2FaceTokenExporter(const Face& face) : m_face(face) - { - } - void exportTokens(TokenWriter& writer) const - { - FacePlane_exportTokens(m_face.getPlane(), writer); - FaceShader_exportTokens(m_face.getShader(), writer); - FaceTexdef_exportTokens(m_face.getTexdef(), writer); - if(m_face.getShader().m_flags.m_specified || m_face.isDetail()) - { - FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); - } - writer.nextLine(); - } -}; - -class Quake3FaceTokenExporter -{ - const Face& m_face; -public: - Quake3FaceTokenExporter(const Face& face) : m_face(face) - { - } - void exportTokens(TokenWriter& writer) const - { - FacePlane_exportTokens(m_face.getPlane(), writer); - FaceShader_exportTokens(m_face.getShader(), writer); - FaceTexdef_exportTokens(m_face.getTexdef(), writer); - FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); - writer.nextLine(); - } -}; - -class Quake3BPFaceTokenExporter -{ - const Face& m_face; -public: - Quake3BPFaceTokenExporter(const Face& face) : m_face(face) - { - } - void exportTokens(TokenWriter& writer) const - { - FacePlane_exportTokens(m_face.getPlane(), writer); - FaceTexdef_BP_exportTokens(m_face.getTexdef(), writer); - FaceShader_exportTokens(m_face.getShader(), writer); - FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); - writer.nextLine(); - } -}; - -class QuakeFaceTokenExporter -{ - const Face& m_face; -public: - QuakeFaceTokenExporter(const Face& face) : m_face(face) - { - } - void exportTokens(TokenWriter& writer) const - { - FacePlane_exportTokens(m_face.getPlane(), writer); - FaceShader_exportTokens(m_face.getShader(), writer); - FaceTexdef_exportTokens(m_face.getTexdef(), writer); - writer.nextLine(); - } -}; - -class HalfLifeFaceTokenExporter -{ - const Face& m_face; -public: - HalfLifeFaceTokenExporter(const Face& face) : m_face(face) - { - } - void exportTokens(TokenWriter& writer) const - { - FacePlane_exportTokens(m_face.getPlane(), writer); - FaceShader_exportTokens(m_face.getShader(), writer); - FaceTexdef_HalfLife_exportTokens(m_face.getTexdef(), writer); - writer.nextLine(); - } -}; - - -class BrushTokenImporter : public MapImporter -{ - Brush& m_brush; - -public: - BrushTokenImporter(Brush& brush) : m_brush(brush) - { - } - bool importTokens(Tokeniser& tokeniser) - { - if(Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) - { - tokeniser.nextLine(); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "{")); - } - while(1) - { - // check for end of brush - tokeniser.nextLine(); - const char* token = tokeniser.getToken(); - if(string_equal(token, "}")) - { - break; - } - - tokeniser.ungetToken(); - - m_brush.push_back(FaceSmartPointer(new Face(&m_brush))); - - //!todo BP support - tokeniser.nextLine(); - - Face& face = *m_brush.back(); - - switch(Brush::m_type) - { - case eBrushTypeDoom3: - { - Doom3FaceTokenImporter importer(face); - RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); - } - break; - case eBrushTypeQuake4: - { - Quake4FaceTokenImporter importer(face); - RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); - } - break; - case eBrushTypeQuake2: - { - Quake2FaceTokenImporter importer(face); - RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); - } - break; - case eBrushTypeQuake3: - { - Quake3FaceTokenImporter importer(face); - RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); - } - break; - case eBrushTypeQuake3BP: - { - Quake3BPFaceTokenImporter importer(face); - RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); - } - break; - case eBrushTypeQuake: - { - QuakeFaceTokenImporter importer(face); - RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); - } - break; - case eBrushTypeHalfLife: - { - HalfLifeFaceTokenImporter importer(face); - RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); - } - break; - } - face.planeChanged(); - } - if(Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) - { - tokeniser.nextLine(); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "}")); - } - - m_brush.planeChanged(); - m_brush.shaderChanged(); - - return true; - } -}; - - -class BrushTokenExporter : public MapExporter -{ - const Brush& m_brush; - -public: - BrushTokenExporter(const Brush& brush) : m_brush(brush) - { - } - void exportTokens(TokenWriter& writer) const - { - m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. - - if(!m_brush.hasContributingFaces()) - { - return; - } - - writer.writeToken("{"); - writer.nextLine(); - - if(Brush::m_type == eBrushTypeQuake3BP) - { - writer.writeToken("brushDef"); - writer.nextLine(); - writer.writeToken("{"); - writer.nextLine(); - } - - if(Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) - { - writer.writeToken("brushDef3"); - writer.nextLine(); - writer.writeToken("{"); - writer.nextLine(); - } - - for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i) - { - const Face& face = *(*i); - - if(face.contributes()) - { - switch(Brush::m_type) - { - case eBrushTypeDoom3: - { - Doom3FaceTokenExporter exporter(face); - exporter.exportTokens(writer); - } - break; - case eBrushTypeQuake4: - { - Quake4FaceTokenExporter exporter(face); - exporter.exportTokens(writer); - } - break; - case eBrushTypeQuake2: - { - Quake2FaceTokenExporter exporter(face); - exporter.exportTokens(writer); - } - break; - case eBrushTypeQuake3: - { - Quake3FaceTokenExporter exporter(face); - exporter.exportTokens(writer); - } - break; - case eBrushTypeQuake3BP: - { - Quake3BPFaceTokenExporter exporter(face); - exporter.exportTokens(writer); - } - break; - case eBrushTypeQuake: - { - QuakeFaceTokenExporter exporter(face); - exporter.exportTokens(writer); - } - break; - case eBrushTypeHalfLife: - { - HalfLifeFaceTokenExporter exporter(face); - exporter.exportTokens(writer); - } - break; - } - } - } - - if(Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) - { - writer.writeToken("}"); - writer.nextLine(); - } - - writer.writeToken("}"); - writer.nextLine(); - } -}; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushxml.cpp b/misc/mediasource/extra/netradiant-src/radiant/brushxml.cpp deleted file mode 100644 index ae18cf34..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushxml.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "brushxml.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/brushxml.h b/misc/mediasource/extra/netradiant-src/radiant/brushxml.h deleted file mode 100644 index afadc8a0..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/brushxml.h +++ /dev/null @@ -1,457 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_BRUSHXML_H) -#define INCLUDED_BRUSHXML_H - -#include "stream/stringstream.h" -#include "xml/xmlelement.h" - -#include "brush.h" - -inline void FaceTexdef_BP_importXML(FaceTexdef& texdef, const char* xmlContent) -{ - StringTokeniser content(xmlContent); - - texdef.m_projection.m_brushprimit_texdef.coords[0][0] = static_cast(atof(content.getToken())); - texdef.m_projection.m_brushprimit_texdef.coords[0][1] = static_cast(atof(content.getToken())); - texdef.m_projection.m_brushprimit_texdef.coords[0][2] = static_cast(atof(content.getToken())); - texdef.m_projection.m_brushprimit_texdef.coords[1][0] = static_cast(atof(content.getToken())); - texdef.m_projection.m_brushprimit_texdef.coords[1][1] = static_cast(atof(content.getToken())); - texdef.m_projection.m_brushprimit_texdef.coords[1][2] = static_cast(atof(content.getToken())); -} -inline void FaceTexdef_importXML(FaceTexdef& texdef, const char* xmlContent) -{ - StringTokeniser content(xmlContent); - - texdef.m_projection.m_texdef.shift[0] = static_cast(atof(content.getToken())); - texdef.m_projection.m_texdef.shift[1] = static_cast(atof(content.getToken())); - texdef.m_projection.m_texdef.rotate = static_cast(atof(content.getToken())); - texdef.m_projection.m_texdef.scale[0] = static_cast(atof(content.getToken())); - texdef.m_projection.m_texdef.scale[1] = static_cast(atof(content.getToken())); - - ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_importXML: bad texdef"); -} - -inline void FacePlane_importXML(FacePlane& facePlane, const char* xmlContent) -{ - StringTokeniser content(xmlContent); - - for (int i = 0; i < 3; ++i) - { - for (int j = 0; j < 3; ++j) - { - facePlane.planePoints()[i][j] = atof(content.getToken()); - } - } - facePlane.MakePlane(); -} - - -class FaceXMLImporter -{ - struct xml_state_t - { - enum EState - { - eDefault, - ePlanePts, - eTexdef, - eBPMatrix, - eFlags, - eShader, - }; - - EState m_state; - StringOutputStream m_content; - - xml_state_t(EState state) - : m_state(state) - {} - - EState state() const - { - return m_state; - } - const char* content() const - { - return m_content.c_str(); - } - std::size_t write(const char* buffer, std::size_t length) - { - return m_content.write(buffer, length); - } - }; - - std::vector m_xml_state; - Face& m_face; -public: - FaceXMLImporter(Face& face) : m_face(face) - { - m_xml_state.push_back(xml_state_t::eDefault); - } - ~FaceXMLImporter() - { - m_face.planeChanged(); - } - - void pushElement(const XMLElement& element) - { - ASSERT_MESSAGE(m_xml_state.back().state() == xml_state_t::eDefault, "parse error"); - - if(strcmp(element.name(), "planepts") == 0) - { - m_xml_state.push_back(xml_state_t::ePlanePts); - } - else if(strcmp(element.name(), "texdef") == 0) - { - m_xml_state.push_back(xml_state_t::eTexdef); - } - else if(strcmp(element.name(), "bpmatrix") == 0) - { - m_xml_state.push_back(xml_state_t::eBPMatrix); - } - else if(strcmp(element.name(), "flags") == 0) - { - m_xml_state.push_back(xml_state_t::eFlags); - } - else if(strcmp(element.name(), "shader") == 0) - { - m_xml_state.push_back(xml_state_t::eShader); - } - } - void popElement(const char* name) - { - ASSERT_MESSAGE(m_xml_state.back().state() != xml_state_t::eDefault, "parse error"); - - switch(m_xml_state.back().state()) - { - case xml_state_t::ePlanePts: - { - FacePlane_importXML(m_face.getPlane(), m_xml_state.back().content()); - } - break; - case xml_state_t::eTexdef: - { - FaceTexdef_importXML(m_face.getTexdef(), m_xml_state.back().content()); - } - break; - case xml_state_t::eBPMatrix: - { - FaceTexdef_BP_importXML(m_face.getTexdef(), m_xml_state.back().content()); - } - break; - case xml_state_t::eFlags: - { - StringTokeniser content(m_xml_state.back().content()); - - m_face.getShader().m_flags.m_contentFlags = atoi(content.getToken()); - m_face.getShader().m_flags.m_surfaceFlags = atoi(content.getToken()); - m_face.getShader().m_flags.m_value = atoi(content.getToken()); - } - break; - case xml_state_t::eShader: - { - m_face.getShader().setShader(m_xml_state.back().content()); - } - break; - default: - break; - } - - m_xml_state.pop_back(); - } - std::size_t write(const char* data, std::size_t length) - { - ASSERT_MESSAGE(!m_xml_state.empty(), "parse error"); - return m_xml_state.back().write(data, length); - } -}; - - -inline void FaceTexdef_exportXML(const FaceTexdef& texdef, XMLImporter& importer) -{ - StaticElement element("texdef"); - importer.pushElement(element); - - ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_exportXML: bad texdef"); - - importer << texdef.m_projection.m_texdef.shift[0] - << ' ' << texdef.m_projection.m_texdef.shift[1] - << ' ' << texdef.m_projection.m_texdef.rotate - << ' ' << texdef.m_projection.m_texdef.scale[0] - << ' ' << texdef.m_projection.m_texdef.scale[1]; - - importer.popElement(element.name()); -} -inline void FaceTexdef_BP_exportXML(const FaceTexdef& texdef, XMLImporter& importer) -{ - StaticElement element("texdef"); - importer.pushElement(element); - - for(int i = 0; i < 2; ++i) - { - for(int j = 0; j < 3; ++j) - { - importer << texdef.m_projection.m_brushprimit_texdef.coords[i][j] << ' '; - } - } - - importer.popElement(element.name()); -} -inline void FaceShader_ContentsFlagsValue_exportXML(const FaceShader& faceShader, XMLImporter& importer) -{ - StaticElement element("flags"); - importer.pushElement(element); - - { - importer << faceShader.m_flags.m_contentFlags - << ' ' << faceShader.m_flags.m_surfaceFlags - << ' ' << faceShader.m_flags.m_value; - } - - importer.popElement(element.name()); -} - -inline void FacePlane_exportXML(const FacePlane& facePlane, XMLImporter& importer) -{ - StaticElement element("planepts"); - importer.pushElement(element); - - { - // write planepts - for (int i=0 ; i<3 ; i++) - { - for (int j=0 ; j<3 ; j++) - { - importer << Face::m_quantise(facePlane.planePoints()[i][j]) << ' '; - } - } - } - - importer.popElement(element.name()); -} - -inline void FacePolygon_exportXML(const Winding& w, const BasicVector3& normal, XMLImporter& importer) -{ - DynamicElement element("polygon"); - - char tmp[32]; - - sprintf(tmp, "%f", normal.x()); - element.insertAttribute("nx", tmp); - - sprintf(tmp, "%f", normal.y()); - element.insertAttribute("ny", tmp); - - sprintf(tmp, "%f", normal.z()); - element.insertAttribute("nz", tmp); - - importer.pushElement(element); - - for(unsigned int i = 0; i < w.numpoints; ++i) - { - DynamicElement c("vertex"); - - sprintf(tmp, "%f", w.points[i].vertex.x()); - c.insertAttribute("x", tmp); - - sprintf(tmp, "%f", w.points[i].vertex.y()); - c.insertAttribute("y", tmp); - - sprintf(tmp, "%f", w.points[i].vertex.z()); - c.insertAttribute("z", tmp); - - sprintf(tmp, "%f", w.points[i].texcoord.x()); - c.insertAttribute("s", tmp); - - sprintf(tmp, "%f", w.points[i].texcoord.y()); - c.insertAttribute("t", tmp); - - importer.pushElement(c); - importer.popElement(c.name()); - } - - importer.popElement(element.name()); -} - -class FaceXMLExporter -{ - const Face& m_face; -public: - FaceXMLExporter(const Face& face) : m_face(face) - { - } - void exportXML(XMLImporter& importer) - { - bool bAlternateTexdef = (Face::m_type == eBrushTypeQuake3BP || Face::m_type == eBrushTypeDoom3 || Face::m_type == eBrushTypeQuake4); - - // write shader - { - StaticElement element("shader"); - importer.pushElement(element); - importer << m_face.getShader().getShader(); - importer.popElement(element.name()); - } - - FacePolygon_exportXML(m_face.getWinding(), m_face.getPlane().plane3().normal(), importer); - FacePlane_exportXML(m_face.getPlane(), importer); - - if(!bAlternateTexdef) - { - FaceTexdef_exportXML(m_face.getTexdef(), importer); - } - else - { - FaceTexdef_BP_exportXML(m_face.getTexdef(), importer); - } - - FaceShader_ContentsFlagsValue_exportXML(m_face.getShader(), importer); - } -}; - - -class BrushXMLImporter : public XMLImporter -{ - class xml_state_t - { - public: - enum EState - { - eDefault, - eBrush, - eFace, - }; - - private: - EState m_state; - - public: - xml_state_t(EState state) - : m_state(state) - { - } - EState state() const - { - return m_state; - } - }; - - std::vector m_xml_state; - char m_faceImporter[sizeof(FaceXMLImporter)]; - Brush& m_brush; - - FaceXMLImporter& faceImporter() - { - return *reinterpret_cast(m_faceImporter); - } - -public: - BrushXMLImporter(Brush& brush) : m_brush(brush) - { - m_xml_state.push_back(xml_state_t::eDefault); - } - void pushElement(const XMLElement& element) - { - switch(m_xml_state.back().state()) - { - case xml_state_t::eDefault: - ASSERT_MESSAGE(strcmp(element.name(), "brush") == 0, "parse error"); - m_xml_state.push_back(xml_state_t::eBrush); - break; - case xml_state_t::eBrush: - ASSERT_MESSAGE(strcmp(element.name(), "plane") == 0, "parse error"); - m_xml_state.push_back(xml_state_t::eFace); - m_brush.push_back(FaceSmartPointer(new Face(&m_brush))); - constructor(faceImporter(), makeReference(*m_brush.back())); - m_brush.planeChanged(); - m_brush.shaderChanged(); - break; - case xml_state_t::eFace: - m_xml_state.push_back(xml_state_t::eFace); - faceImporter().pushElement(element); - break; - } - } - void popElement(const char* name) - { - ASSERT_MESSAGE(!m_xml_state.empty(), "parse error"); - m_xml_state.pop_back(); - - switch(m_xml_state.back().state()) - { - case xml_state_t::eDefault: - break; - case xml_state_t::eBrush: - destructor(faceImporter()); - break; - case xml_state_t::eFace: - faceImporter().popElement(name); - break; - } - } - std::size_t write(const char* data, std::size_t length) - { - switch(m_xml_state.back().state()) - { - case xml_state_t::eFace: - return faceImporter().write(data, length); - break; - default: - break; - } - return length; - } -}; - -class BrushXMLExporter : public XMLExporter -{ - const Brush& m_brush; - -public: - BrushXMLExporter(const Brush& brush) : m_brush(brush) - { - } - void exportXML(XMLImporter& importer) - { - m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. - ASSERT_MESSAGE(m_brush.hasContributingFaces(), "exporting an empty brush"); - - const StaticElement brushElement("brush"); - importer.pushElement(brushElement); - - for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i) - { - if((*i)->contributes()) - { - const StaticElement element("plane"); - importer.pushElement(element); - FaceXMLExporter(*(*i)).exportXML(importer); - importer.popElement(element.name()); - } - } - - importer.popElement(brushElement.name()); - } -}; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/build.cpp b/misc/mediasource/extra/netradiant-src/radiant/build.cpp deleted file mode 100644 index dcb23a28..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/build.cpp +++ /dev/null @@ -1,1158 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "build.h" -#include "debugging/debugging.h" - -#include -#include -#include "stream/stringstream.h" -#include "versionlib.h" - -#include "mainframe.h" - -typedef std::map Variables; -Variables g_build_variables; - -void build_clear_variables() -{ - g_build_variables.clear(); -} - -void build_set_variable(const char* name, const char* value) -{ - g_build_variables[name] = value; -} - -const char* build_get_variable(const char* name) -{ - Variables::iterator i = g_build_variables.find(name); - if(i != g_build_variables.end()) - { - return (*i).second.c_str(); - } - globalErrorStream() << "undefined build variable: " << makeQuoted(name) << "\n"; - return ""; -} - -#include "xml/ixml.h" -#include "xml/xmlelement.h" - -class Evaluatable -{ -public: - virtual void evaluate(StringBuffer& output) = 0; - virtual void exportXML(XMLImporter& importer) = 0; -}; - -class VariableString : public Evaluatable -{ - CopiedString m_string; -public: - VariableString() : m_string() - { - } - VariableString(const char* string) : m_string(string) - { - } - const char* c_str() const - { - return m_string.c_str(); - } - void setString(const char* string) - { - m_string = string; - } - void evaluate(StringBuffer& output) - { - StringBuffer variable; - bool in_variable = false; - for(const char* i = m_string.c_str(); *i != '\0'; ++i) - { - if(!in_variable) - { - switch(*i) - { - case '[': - in_variable = true; - break; - default: - output.push_back(*i); - break; - } - } - else - { - switch(*i) - { - case ']': - in_variable = false; - output.push_string(build_get_variable(variable.c_str())); - variable.clear(); - break; - default: - variable.push_back(*i); - break; - } - } - } - } - void exportXML(XMLImporter& importer) - { - importer << c_str(); - } -}; - -class Conditional : public Evaluatable -{ - VariableString* m_test; -public: - Evaluatable* m_result; - Conditional(VariableString* test) : m_test(test) - { - } - ~Conditional() - { - delete m_test; - delete m_result; - } - void evaluate(StringBuffer& output) - { - StringBuffer buffer; - m_test->evaluate(buffer); - if(!string_empty(buffer.c_str())) - { - m_result->evaluate(output); - } - } - void exportXML(XMLImporter& importer) - { - StaticElement conditionElement("cond"); - conditionElement.insertAttribute("value", m_test->c_str()); - importer.pushElement(conditionElement); - m_result->exportXML(importer); - importer.popElement(conditionElement.name()); - } -}; - -typedef std::vector Evaluatables; - -class Tool : public Evaluatable -{ - Evaluatables m_evaluatables; -public: - ~Tool() - { - for(Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i) - { - delete (*i); - } - } - void push_back(Evaluatable* evaluatable) - { - m_evaluatables.push_back(evaluatable); - } - void evaluate(StringBuffer& output) - { - for(Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i) - { - (*i)->evaluate(output); - } - } - void exportXML(XMLImporter& importer) - { - for(Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i) - { - (*i)->exportXML(importer); - } - } -}; - -#include "xml/ixml.h" - -class XMLElementParser : public TextOutputStream -{ -public: - virtual XMLElementParser& pushElement(const XMLElement& element) = 0; - virtual void popElement(const char* name) = 0; -}; - -class VariableStringXMLConstructor : public XMLElementParser -{ - StringBuffer m_buffer; - VariableString& m_variableString; -public: - VariableStringXMLConstructor(VariableString& variableString) : m_variableString(variableString) - { - } - ~VariableStringXMLConstructor() - { - m_variableString.setString(m_buffer.c_str()); - } - std::size_t write(const char* buffer, std::size_t length) - { - m_buffer.push_range(buffer, buffer + length); - return length; - } - XMLElementParser& pushElement(const XMLElement& element) - { - ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); - return *this; - } - void popElement(const char* name) - { - } -}; - -class ConditionalXMLConstructor : public XMLElementParser -{ - StringBuffer m_buffer; - Conditional& m_conditional; -public: - ConditionalXMLConstructor(Conditional& conditional) : m_conditional(conditional) - { - } - ~ConditionalXMLConstructor() - { - m_conditional.m_result = new VariableString(m_buffer.c_str()); - } - std::size_t write(const char* buffer, std::size_t length) - { - m_buffer.push_range(buffer, buffer + length); - return length; - } - XMLElementParser& pushElement(const XMLElement& element) - { - ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); - return *this; - } - void popElement(const char* name) - { - } -}; - -class ToolXMLConstructor : public XMLElementParser -{ - StringBuffer m_buffer; - Tool& m_tool; - ConditionalXMLConstructor* m_conditional; -public: - ToolXMLConstructor(Tool& tool) : m_tool(tool) - { - } - ~ToolXMLConstructor() - { - flush(); - } - std::size_t write(const char* buffer, std::size_t length) - { - m_buffer.push_range(buffer, buffer + length); - return length; - } - XMLElementParser& pushElement(const XMLElement& element) - { - if(string_equal(element.name(), "cond")) - { - flush(); - Conditional* conditional = new Conditional(new VariableString(element.attribute("value"))); - m_tool.push_back(conditional); - m_conditional = new ConditionalXMLConstructor(*conditional); - return *m_conditional; - } - else - { - ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); - return *this; - } - } - void popElement(const char* name) - { - if(string_equal(name, "cond")) - { - delete m_conditional; - } - } - - void flush() - { - if(!m_buffer.empty()) - { - m_tool.push_back(new VariableString(m_buffer.c_str())); - m_buffer.clear(); - } - } -}; - -typedef VariableString BuildCommand; -typedef std::list Build; - -class BuildXMLConstructor : public XMLElementParser -{ - VariableStringXMLConstructor* m_variableString; - Build& m_build; -public: - BuildXMLConstructor(Build& build) : m_build(build) - { - } - std::size_t write(const char* buffer, std::size_t length) - { - return length; - } - XMLElementParser& pushElement(const XMLElement& element) - { - if(string_equal(element.name(), "command")) - { - m_build.push_back(BuildCommand()); - m_variableString = new VariableStringXMLConstructor(m_build.back()); - return *m_variableString; - } - else - { - ERROR_MESSAGE("parse error: invalid element"); - return *this; - } - } - void popElement(const char* name) - { - delete m_variableString; - } -}; - -typedef std::pair BuildPair; - -class BuildPairEqual -{ - const char* m_name; -public: - BuildPairEqual(const char* name) : m_name(name) - { - } - bool operator()(const BuildPair& self) const - { - return string_equal(self.first.c_str(), m_name); - } -}; - -typedef std::list Project; - -Project::iterator Project_find(Project& project, const char* name) -{ - return std::find_if(project.begin(), project.end(), BuildPairEqual(name)); -} - -Project::iterator Project_find(Project& project, std::size_t index) -{ - Project::iterator i = project.begin(); - while(index-- != 0 && i != project.end()) - { - ++i; - } - return i; -} - -Build& project_find(Project& project, const char* build) -{ - Project::iterator i = Project_find(project, build); - ASSERT_MESSAGE(i != project.end(), "error finding build command"); - return (*i).second; -} - -Build::iterator Build_find(Build& build, std::size_t index) -{ - Build::iterator i = build.begin(); - while(index-- != 0 && i != build.end()) - { - ++i; - } - return i; -} - -typedef std::map Tools; - -class ProjectXMLConstructor : public XMLElementParser -{ - ToolXMLConstructor* m_tool; - BuildXMLConstructor* m_build; - Project& m_project; - Tools& m_tools; -public: - ProjectXMLConstructor(Project& project, Tools& tools) : m_project(project), m_tools(tools) - { - } - std::size_t write(const char* buffer, std::size_t length) - { - return length; - } - XMLElementParser& pushElement(const XMLElement& element) - { - if(string_equal(element.name(), "var")) - { - Tools::iterator i = m_tools.insert(Tools::value_type(element.attribute("name"), Tool())).first; - m_tool = new ToolXMLConstructor((*i).second); - return *m_tool; - } - else if(string_equal(element.name(), "build")) - { - m_project.push_back(Project::value_type(element.attribute("name"), Build())); - m_build = new BuildXMLConstructor(m_project.back().second); - return *m_build; - } - else - { - ERROR_MESSAGE("parse error: invalid element"); - return *this; - } - } - void popElement(const char* name) - { - if(string_equal(name, "var")) - { - delete m_tool; - } - else if(string_equal(name, "build")) - { - delete m_build; - } - } -}; - -class SkipAllParser : public XMLElementParser -{ -public: - std::size_t write(const char* buffer, std::size_t length) - { - return length; - } - XMLElementParser& pushElement(const XMLElement& element) - { - return *this; - } - void popElement(const char* name) - { - } -}; - -class RootXMLConstructor : public XMLElementParser -{ - CopiedString m_elementName; - XMLElementParser& m_parser; - SkipAllParser m_skip; - Version m_version; - bool m_compatible; -public: - RootXMLConstructor(const char* elementName, XMLElementParser& parser, const char* version) : - m_elementName(elementName), - m_parser(parser), - m_version(version_parse(version)), - m_compatible(false) - { - } - std::size_t write(const char* buffer, std::size_t length) - { - return length; - } - XMLElementParser& pushElement(const XMLElement& element) - { - if(string_equal(element.name(), m_elementName.c_str())) - { - Version dataVersion(version_parse(element.attribute("version"))); - if(version_compatible(m_version, dataVersion)) - { - m_compatible = true; - return m_parser; - } - else - { - return m_skip; - } - } - else - { - //ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); - return *this; - } - } - void popElement(const char* name) - { - } - - bool versionCompatible() const - { - return m_compatible; - } -}; - -namespace -{ - Project g_build_project; - Tools g_build_tools; - bool g_build_changed = false; -} - -void build_error_undefined_tool(const char* build, const char* tool) -{ - globalErrorStream() << "build " << makeQuoted(build) << " refers to undefined tool " << makeQuoted(tool) << '\n'; -} - -void project_verify(Project& project, Tools& tools) -{ -#if 0 - for(Project::iterator i = project.begin(); i != project.end(); ++i) - { - Build& build = (*i).second; - for(Build::iterator j = build.begin(); j != build.end(); ++j) - { - Tools::iterator k = tools.find((*j).first); - if(k == g_build_tools.end()) - { - build_error_undefined_tool((*i).first.c_str(), (*j).first.c_str()); - } - } - } -#endif -} - -void build_run(const char* name, CommandListener& listener) -{ - for(Tools::iterator i = g_build_tools.begin(); i != g_build_tools.end(); ++i) - { - StringBuffer output; - (*i).second.evaluate(output); - build_set_variable((*i).first.c_str(), output.c_str()); - } - - { - Project::iterator i = Project_find(g_build_project, name); - if(i != g_build_project.end()) - { - Build& build = (*i).second; - for(Build::iterator j = build.begin(); j != build.end(); ++j) - { - StringBuffer output; - (*j).evaluate(output); - listener.execute(output.c_str()); - } - } - else - { - globalErrorStream() << "build " << makeQuoted(name) << " not defined"; - } - } -} - - -typedef std::vector XMLElementStack; - -class XMLParser : public XMLImporter -{ - XMLElementStack m_stack; -public: - XMLParser(XMLElementParser& parser) - { - m_stack.push_back(&parser); - } - std::size_t write(const char* buffer, std::size_t length) - { - return m_stack.back()->write(buffer, length); - } - void pushElement(const XMLElement& element) - { - m_stack.push_back(&m_stack.back()->pushElement(element)); - } - void popElement(const char* name) - { - m_stack.pop_back(); - m_stack.back()->popElement(name); - } -}; - -#include "stream/textfilestream.h" -#include "xml/xmlparser.h" - -const char* const BUILDMENU_VERSION = "2.0"; - -bool build_commands_parse(const char* filename) -{ - TextFileInputStream projectFile(filename); - if(!projectFile.failed()) - { - ProjectXMLConstructor projectConstructor(g_build_project, g_build_tools); - RootXMLConstructor rootConstructor("project", projectConstructor, BUILDMENU_VERSION); - XMLParser importer(rootConstructor); - XMLStreamParser parser(projectFile); - parser.exportXML(importer); - - if(rootConstructor.versionCompatible()) - { - project_verify(g_build_project, g_build_tools); - - return true; - } - globalErrorStream() << "failed to parse build menu: " << makeQuoted(filename) << "\n"; - } - return false; -} - -void build_commands_clear() -{ - g_build_project.clear(); - g_build_tools.clear(); -} - -class BuildXMLExporter -{ - Build& m_build; -public: - BuildXMLExporter(Build& build) : m_build(build) - { - } - void exportXML(XMLImporter& importer) - { - importer << "\n"; - for(Build::iterator i = m_build.begin(); i != m_build.end(); ++i) - { - StaticElement commandElement("command"); - importer.pushElement(commandElement); - (*i).exportXML(importer); - importer.popElement(commandElement.name()); - importer << "\n"; - } - } -}; - -class ProjectXMLExporter -{ - Project& m_project; - Tools& m_tools; -public: - ProjectXMLExporter(Project& project, Tools& tools) : m_project(project), m_tools(tools) - { - } - void exportXML(XMLImporter& importer) - { - StaticElement projectElement("project"); - projectElement.insertAttribute("version", BUILDMENU_VERSION); - importer.pushElement(projectElement); - importer << "\n"; - - for(Tools::iterator i = m_tools.begin(); i != m_tools.end(); ++i) - { - StaticElement toolElement("var"); - toolElement.insertAttribute("name", (*i).first.c_str()); - importer.pushElement(toolElement); - (*i).second.exportXML(importer); - importer.popElement(toolElement.name()); - importer << "\n"; - } - for(Project::iterator i = m_project.begin(); i != m_project.end(); ++i) - { - StaticElement buildElement("build"); - buildElement.insertAttribute("name", (*i).first.c_str()); - importer.pushElement(buildElement); - BuildXMLExporter buildExporter((*i).second); - buildExporter.exportXML(importer); - importer.popElement(buildElement.name()); - importer << "\n"; - } - importer.popElement(projectElement.name()); - } -}; - -#include "xml/xmlwriter.h" - -void build_commands_write(const char* filename) -{ - TextFileOutputStream projectFile(filename); - if(!projectFile.failed()) - { - XMLStreamWriter writer(projectFile); - ProjectXMLExporter projectExporter(g_build_project, g_build_tools); - writer << "\n"; - projectExporter.exportXML(writer); - writer << "\n"; - } -} - - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gtkutil/dialog.h" -#include "gtkutil/closure.h" -#include "gtkutil/window.h" -#include "gtkdlgs.h" - -void Build_refreshMenu(GtkMenu* menu); - - -void BSPCommandList_Construct(GtkListStore* store, Project& project) -{ - gtk_list_store_clear(store); - - for(Project::iterator i = project.begin(); i != project.end(); ++i) - { - const char* buildName = (*i).first.c_str(); - - GtkTreeIter buildIter; - gtk_list_store_append(store, &buildIter); - gtk_list_store_set(store, &buildIter, 0, const_cast(buildName), -1); - } - - GtkTreeIter lastIter; - gtk_list_store_append(store, &lastIter); -} - -class ProjectList -{ -public: - Project& m_project; - GtkListStore* m_store; - bool m_changed; - ProjectList(Project& project) : m_project(project), m_changed(false) - { - } -}; - -gboolean project_cell_edited(GtkCellRendererText* cell, gchar* path_string, gchar* new_text, ProjectList* projectList) -{ - Project& project = projectList->m_project; - - GtkTreePath* path = gtk_tree_path_new_from_string(path_string); - - ASSERT_MESSAGE(gtk_tree_path_get_depth(path) == 1, "invalid path length"); - - GtkTreeIter iter; - gtk_tree_model_get_iter(GTK_TREE_MODEL(projectList->m_store), &iter, path); - - Project::iterator i = Project_find(project, gtk_tree_path_get_indices(path)[0]); - if(i != project.end()) - { - projectList->m_changed = true; - if(string_empty(new_text)) - { - project.erase(i); - Build_refreshMenu(g_bsp_menu); - - gtk_list_store_remove(projectList->m_store, &iter); - } - else - { - (*i).first = new_text; - Build_refreshMenu(g_bsp_menu); - - gtk_list_store_set(projectList->m_store, &iter, 0, new_text, -1); - } - } - else if(!string_empty(new_text)) - { - projectList->m_changed = true; - project.push_back(Project::value_type(new_text, Build())); - Build_refreshMenu(g_bsp_menu); - - gtk_list_store_set(projectList->m_store, &iter, 0, new_text, -1); - GtkTreeIter lastIter; - gtk_list_store_append(projectList->m_store, &lastIter); - } - - gtk_tree_path_free(path); - - return FALSE; -} - -gboolean project_key_press(GtkWidget* widget, GdkEventKey* event, ProjectList* projectList) -{ - Project& project = projectList->m_project; - - if(event->keyval == GDK_Delete) - { - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); - GtkTreeIter iter; - GtkTreeModel* model; - if(gtk_tree_selection_get_selected(selection, &model, &iter)) - { - GtkTreePath* path = gtk_tree_model_get_path(model, &iter); - Project::iterator x = Project_find(project, gtk_tree_path_get_indices(path)[0]); - gtk_tree_path_free(path); - - if(x != project.end()) - { - projectList->m_changed = true; - project.erase(x); - Build_refreshMenu(g_bsp_menu); - - gtk_list_store_remove(projectList->m_store, &iter); - } - } - } - return FALSE; -} - - -Build* g_current_build = 0; - -gboolean project_selection_changed(GtkTreeSelection* selection, GtkListStore* store) -{ - Project& project = g_build_project; - - gtk_list_store_clear(store); - - GtkTreeIter iter; - GtkTreeModel* model; - if(gtk_tree_selection_get_selected(selection, &model, &iter)) - { - GtkTreePath* path = gtk_tree_model_get_path(model, &iter); - Project::iterator x = Project_find(project, gtk_tree_path_get_indices(path)[0]); - gtk_tree_path_free(path); - - if(x != project.end()) - { - Build& build = (*x).second; - g_current_build = &build; - - for(Build::iterator i = build.begin(); i != build.end(); ++i) - { - GtkTreeIter commandIter; - gtk_list_store_append(store, &commandIter); - gtk_list_store_set(store, &commandIter, 0, const_cast((*i).c_str()), -1); - } - GtkTreeIter lastIter; - gtk_list_store_append(store, &lastIter); - } - else - { - g_current_build = 0; - } - } - else - { - g_current_build = 0; - } - - return FALSE; -} - -gboolean commands_cell_edited(GtkCellRendererText* cell, gchar* path_string, gchar* new_text, GtkListStore* store) -{ - if(g_current_build == 0) - { - return FALSE; - } - Build& build = *g_current_build; - - GtkTreePath* path = gtk_tree_path_new_from_string(path_string); - - ASSERT_MESSAGE(gtk_tree_path_get_depth(path) == 1, "invalid path length"); - - GtkTreeIter iter; - gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, path); - - Build::iterator i = Build_find(build, gtk_tree_path_get_indices(path)[0]); - if(i != build.end()) - { - g_build_changed = true; - (*i).setString(new_text); - - gtk_list_store_set(store, &iter, 0, new_text, -1); - } - else if(!string_empty(new_text)) - { - g_build_changed = true; - build.push_back(Build::value_type(VariableString(new_text))); - - gtk_list_store_set(store, &iter, 0, new_text, -1); - - GtkTreeIter lastIter; - gtk_list_store_append(store, &lastIter); - } - - gtk_tree_path_free(path); - - return FALSE; -} - -gboolean commands_key_press(GtkWidget* widget, GdkEventKey* event, GtkListStore* store) -{ - if(g_current_build == 0) - { - return FALSE; - } - Build& build = *g_current_build; - - if(event->keyval == GDK_Delete) - { - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); - GtkTreeIter iter; - GtkTreeModel* model; - if(gtk_tree_selection_get_selected(selection, &model, &iter)) - { - GtkTreePath* path = gtk_tree_model_get_path(model, &iter); - Build::iterator i = Build_find(build, gtk_tree_path_get_indices(path)[0]); - gtk_tree_path_free(path); - - if(i != build.end()) - { - g_build_changed = true; - build.erase(i); - - gtk_list_store_remove(store, &iter); - } - } - } - return FALSE; -} - - -GtkWindow* BuildMenuDialog_construct(ModalDialog& modal, ProjectList& projectList) -{ - GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Build Menu", G_CALLBACK(dialog_delete_callback), &modal, -1, 400); - - GtkWidget* buildView = 0; - - { - GtkTable* table1 = create_dialog_table(2, 2, 4, 4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(table1)); - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_table_attach(table1, GTK_WIDGET(vbox), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - { - GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &modal); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - { - GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &modal); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - } - { - GtkFrame* frame = create_dialog_frame("Build menu"); - gtk_table_attach(table1, GTK_WIDGET(frame), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), 0, 0); - { - GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(scr)); - - { - GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING); - - GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); - - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - object_set_boolean_property(G_OBJECT(renderer), "editable", TRUE); - g_signal_connect(renderer, "edited", G_CALLBACK(project_cell_edited), &projectList); - - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, 0); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - - GtkTreeSelection* selection = gtk_tree_view_get_selection (GTK_TREE_VIEW(view)); - gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE); - - gtk_widget_show(view); - - buildView = view; - projectList.m_store = store; - gtk_container_add(GTK_CONTAINER (scr), view); - - g_signal_connect(G_OBJECT(view), "key_press_event", G_CALLBACK(project_key_press), &projectList); - - g_object_unref(G_OBJECT(store)); - } - } - } - { - GtkFrame* frame = create_dialog_frame("Commandline"); - gtk_table_attach(table1, GTK_WIDGET(frame), 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), 0, 0); - { - GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(scr)); - - { - GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING); - - GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); - - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - object_set_boolean_property(G_OBJECT(renderer), "editable", TRUE); - g_signal_connect(renderer, "edited", G_CALLBACK(commands_cell_edited), store); - - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, 0); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - - GtkTreeSelection* selection = gtk_tree_view_get_selection (GTK_TREE_VIEW(view)); - gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE); - - gtk_widget_show(view); - - gtk_container_add(GTK_CONTAINER (scr), view); - - g_object_unref(G_OBJECT(store)); - - g_signal_connect(G_OBJECT(view), "key_press_event", G_CALLBACK(commands_key_press), store); - - g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(buildView))), "changed", G_CALLBACK(project_selection_changed), store); - } - } - } - } - - BSPCommandList_Construct(projectList.m_store, g_build_project); - - return window; -} - -namespace -{ - CopiedString g_buildMenu; -} - -void LoadBuildMenu(); - -void DoBuildMenu() -{ - ModalDialog modal; - - ProjectList projectList(g_build_project); - - GtkWindow* window = BuildMenuDialog_construct(modal, projectList); - - if(modal_dialog_show(window, modal) == eIDCANCEL) - { - build_commands_clear(); - LoadBuildMenu(); - - Build_refreshMenu(g_bsp_menu); - } - else if(projectList.m_changed) - { - g_build_changed = true; - } - - gtk_widget_destroy(GTK_WIDGET(window)); -} - - - -#include "gtkutil/menu.h" -#include "mainframe.h" -#include "preferences.h" -#include "qe3.h" - -typedef struct _GtkMenuItem GtkMenuItem; - -class BuildMenuItem -{ - const char* m_name; -public: - GtkMenuItem* m_item; - BuildMenuItem(const char* name, GtkMenuItem* item) - : m_name(name), m_item(item) - { - } - void run() - { - RunBSP(m_name); - } - typedef MemberCaller RunCaller; -}; - -typedef std::list BuildMenuItems; -BuildMenuItems g_BuildMenuItems; - - -GtkMenu* g_bsp_menu; - -void Build_constructMenu(GtkMenu* menu) -{ - for(Project::iterator i = g_build_project.begin(); i != g_build_project.end(); ++i) - { - g_BuildMenuItems.push_back(BuildMenuItem((*i).first.c_str(), 0)); - g_BuildMenuItems.back().m_item = create_menu_item_with_mnemonic(menu, (*i).first.c_str(), BuildMenuItem::RunCaller(g_BuildMenuItems.back())); - } -} - - -void Build_refreshMenu(GtkMenu* menu) -{ - for(BuildMenuItems::iterator i = g_BuildMenuItems.begin(); i != g_BuildMenuItems.end(); ++i) - { - gtk_container_remove(GTK_CONTAINER(menu), GTK_WIDGET((*i).m_item)); - } - - g_BuildMenuItems.clear(); - - Build_constructMenu(menu); -} - - -void LoadBuildMenu() -{ - if(string_empty(g_buildMenu.c_str()) || !build_commands_parse(g_buildMenu.c_str())) - { - { - StringOutputStream buffer(256); - buffer << GameToolsPath_get() << "default_build_menu.xml"; - - bool success = build_commands_parse(buffer.c_str()); - ASSERT_MESSAGE(success, "failed to parse default build commands: " << buffer.c_str()); - } - { - StringOutputStream buffer(256); - buffer << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/build_menu.xml"; - - g_buildMenu = buffer.c_str(); - } - } -} - -void SaveBuildMenu() -{ - if(g_build_changed) - { - g_build_changed = false; - build_commands_write(g_buildMenu.c_str()); - } -} - -#include "preferencesystem.h" -#include "stringio.h" - -void BuildMenu_Construct() -{ - GlobalPreferenceSystem().registerPreference("BuildMenu", CopiedStringImportStringCaller(g_buildMenu), CopiedStringExportStringCaller(g_buildMenu)); - LoadBuildMenu(); -} -void BuildMenu_Destroy() -{ - SaveBuildMenu(); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/build.h b/misc/mediasource/extra/netradiant-src/radiant/build.h deleted file mode 100644 index 3b3244d7..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/build.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_BUILD_H) -#define INCLUDED_BUILD_H - -void build_set_variable(const char* name, const char* value); -void build_clear_variables(); - -class CommandListener -{ -public: - virtual void execute(const char* command) = 0; -}; -void build_run(const char* name, CommandListener& listener); - -void DoBuildMenu(); - -void BuildMenu_Construct(); -void BuildMenu_Destroy(); - -typedef struct _GtkMenu GtkMenu; -void Build_constructMenu(GtkMenu* menu); -extern GtkMenu* g_bsp_menu; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/camwindow.cpp b/misc/mediasource/extra/netradiant-src/radiant/camwindow.cpp deleted file mode 100644 index f0744e48..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/camwindow.cpp +++ /dev/null @@ -1,2116 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Camera Window -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "camwindow.h" - -#include "debugging/debugging.h" - -#include "iscenegraph.h" -#include "irender.h" -#include "igl.h" -#include "icamera.h" -#include "cullable.h" -#include "renderable.h" -#include "preferencesystem.h" - -#include "signal/signal.h" -#include "container/array.h" -#include "scenelib.h" -#include "render.h" -#include "cmdlib.h" -#include "math/frustum.h" - -#include "gtkutil/widget.h" -#include "gtkutil/button.h" -#include "gtkutil/toolbar.h" -#include "gtkutil/glwidget.h" -#include "gtkutil/xorrectangle.h" -#include "gtkmisc.h" -#include "selection.h" -#include "mainframe.h" -#include "preferences.h" -#include "commands.h" -#include "xywindow.h" -#include "windowobservers.h" -#include "renderstate.h" - -#include "timer.h" - -Signal0 g_cameraMoved_callbacks; - -void AddCameraMovedCallback(const SignalHandler& handler) -{ - g_cameraMoved_callbacks.connectLast(handler); -} - -void CameraMovedNotify() -{ - g_cameraMoved_callbacks(); -} - - -struct camwindow_globals_private_t -{ - int m_nMoveSpeed; - bool m_bCamLinkSpeed; - int m_nAngleSpeed; - bool m_bCamInverseMouse; - bool m_bCamDiscrete; - bool m_bCubicClipping; - bool m_showStats; - int m_nStrafeMode; - - camwindow_globals_private_t() : - m_nMoveSpeed(100), - m_bCamLinkSpeed(true), - m_nAngleSpeed(3), - m_bCamInverseMouse(false), - m_bCamDiscrete(true), - m_bCubicClipping(true), - m_showStats(true), - m_nStrafeMode(0) - { - } - -}; - -camwindow_globals_private_t g_camwindow_globals_private; - - -const Matrix4 g_opengl2radiant( - 0, 0,-1, 0, - -1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 0, 1 -); - -const Matrix4 g_radiant2opengl( - 0,-1, 0, 0, - 0, 0, 1, 0, - -1, 0, 0, 0, - 0, 0, 0, 1 -); - -struct camera_t; -void Camera_mouseMove(camera_t& camera, int x, int y); - -enum camera_draw_mode -{ - cd_wire, - cd_solid, - cd_texture, - cd_lighting -}; - -struct camera_t -{ - int width, height; - - bool timing; - - Vector3 origin; - Vector3 angles; - - Vector3 color; // background - - Vector3 forward, right; // move matrix (TTimo: used to have up but it was not updated) - Vector3 vup, vpn, vright; // view matrix (taken from the modelview matrix) - - Matrix4 projection; - Matrix4 modelview; - - bool m_strafe; // true when in strafemode toggled by the ctrl-key - bool m_strafe_forward; // true when in strafemode by ctrl-key and shift is pressed for forward strafing - - unsigned int movementflags; // movement flags - Timer m_keycontrol_timer; - guint m_keymove_handler; - - - float fieldOfView; - - DeferredMotionDelta m_mouseMove; - - static void motionDelta(int x, int y, void* data) - { - Camera_mouseMove(*reinterpret_cast(data), x, y); - } - - View* m_view; - Callback m_update; - - static camera_draw_mode draw_mode; - - camera_t(View* view, const Callback& update) - : width(0), - height(0), - timing(false), - origin(0, 0, 0), - angles(0, 0, 0), - color(0, 0, 0), - movementflags(0), - m_keymove_handler(0), - fieldOfView(90.0f), - m_mouseMove(motionDelta, this), - m_view(view), - m_update(update) - { - } -}; - -camera_draw_mode camera_t::draw_mode = cd_texture; - -inline Matrix4 projection_for_camera(float near_z, float far_z, float fieldOfView, int width, int height) -{ - const float half_width = static_cast(near_z * tan(degrees_to_radians(fieldOfView * 0.5))); - const float half_height = half_width * (static_cast(height) / static_cast(width)); - - return matrix4_frustum( - -half_width, - half_width, - -half_height, - half_height, - near_z, - far_z - ); -} - -float Camera_getFarClipPlane(camera_t& camera) -{ - return (g_camwindow_globals_private.m_bCubicClipping)? pow(2.0, (g_camwindow_globals.m_nCubicScale + 7) / 2.0) : 32768.0f; -} - -void Camera_updateProjection(camera_t& camera) -{ - float farClip = Camera_getFarClipPlane(camera); - camera.projection = projection_for_camera(farClip / 4096.0f, farClip, camera.fieldOfView, camera.width, camera.height); - - camera.m_view->Construct(camera.projection, camera.modelview, camera.width, camera.height); -} - -void Camera_updateVectors(camera_t& camera) -{ - for (int i=0 ; i<3 ; i++) - { - camera.vright[i] = camera.modelview[(i<<2)+0]; - camera.vup[i] = camera.modelview[(i<<2)+1]; - camera.vpn[i] = camera.modelview[(i<<2)+2]; - } -} - -void Camera_updateModelview(camera_t& camera) -{ - camera.modelview = g_matrix4_identity; - - // roll, pitch, yaw - Vector3 radiant_eulerXYZ(0, -camera.angles[CAMERA_PITCH], camera.angles[CAMERA_YAW]); - - matrix4_translate_by_vec3(camera.modelview, camera.origin); - matrix4_rotate_by_euler_xyz_degrees(camera.modelview, radiant_eulerXYZ); - matrix4_multiply_by_matrix4(camera.modelview, g_radiant2opengl); - matrix4_affine_invert(camera.modelview); - - Camera_updateVectors(camera); - - camera.m_view->Construct(camera.projection, camera.modelview, camera.width, camera.height); -} - - -void Camera_Move_updateAxes(camera_t& camera) -{ - double ya = degrees_to_radians(camera.angles[CAMERA_YAW]); - - // the movement matrix is kept 2d - camera.forward[0] = static_cast(cos(ya)); - camera.forward[1] = static_cast(sin(ya)); - camera.forward[2] = 0; - camera.right[0] = camera.forward[1]; - camera.right[1] = -camera.forward[0]; -} - -void Camera_Freemove_updateAxes(camera_t& camera) -{ - camera.right = camera.vright; - camera.forward = vector3_negated(camera.vpn); -} - -const Vector3& Camera_getOrigin(camera_t& camera) -{ - return camera.origin; -} - -void Camera_setOrigin(camera_t& camera, const Vector3& origin) -{ - camera.origin = origin; - Camera_updateModelview(camera); - camera.m_update(); - CameraMovedNotify(); -} - -const Vector3& Camera_getAngles(camera_t& camera) -{ - return camera.angles; -} - -void Camera_setAngles(camera_t& camera, const Vector3& angles) -{ - camera.angles = angles; - Camera_updateModelview(camera); - camera.m_update(); - CameraMovedNotify(); -} - - -void Camera_FreeMove(camera_t& camera, int dx, int dy) -{ - // free strafe mode, toggled by the ctrl key with optional shift for forward movement - if(camera.m_strafe) - { - float strafespeed = 0.65f; - - if(g_camwindow_globals_private.m_bCamLinkSpeed) - { - strafespeed = (float)g_camwindow_globals_private.m_nMoveSpeed / 100; - } - - camera.origin -= camera.vright * strafespeed * dx; - if(camera.m_strafe_forward) - camera.origin += camera.vpn * strafespeed * dy; - else - camera.origin += camera.vup * strafespeed * dy; - } - else// free rotation - { - const float dtime = 0.1f; - - if (g_camwindow_globals_private.m_bCamInverseMouse) - camera.angles[CAMERA_PITCH] -= dy * dtime * g_camwindow_globals_private.m_nAngleSpeed; - else - camera.angles[CAMERA_PITCH] += dy * dtime * g_camwindow_globals_private.m_nAngleSpeed; - - camera.angles[CAMERA_YAW] += dx * dtime * g_camwindow_globals_private.m_nAngleSpeed; - - if (camera.angles[CAMERA_PITCH] > 90) - camera.angles[CAMERA_PITCH] = 90; - else if (camera.angles[CAMERA_PITCH] < -90) - camera.angles[CAMERA_PITCH] = -90; - - if (camera.angles[CAMERA_YAW] >= 360) - camera.angles[CAMERA_YAW] -=360; - else if (camera.angles[CAMERA_YAW] <= 0) - camera.angles[CAMERA_YAW] +=360; - } - - Camera_updateModelview(camera); - Camera_Freemove_updateAxes(camera); -} - -void Cam_MouseControl(camera_t& camera, int x, int y) -{ - int xl, xh; - int yl, yh; - float xf, yf; - - xf = (float)(x - camera.width/2) / (camera.width/2); - yf = (float)(y - camera.height/2) / (camera.height/2); - - xl = camera.width/3; - xh = xl*2; - yl = camera.height/3; - yh = yl*2; - - xf *= 1.0f - fabsf(yf); - if (xf < 0) - { - xf += 0.1f; - if (xf > 0) - xf = 0; - } - else - { - xf -= 0.1f; - if (xf < 0) - xf = 0; - } - - vector3_add(camera.origin, vector3_scaled(camera.forward, yf * 0.1f* g_camwindow_globals_private.m_nMoveSpeed)); - camera.angles[CAMERA_YAW] += xf * -0.1f * g_camwindow_globals_private.m_nAngleSpeed; - - Camera_updateModelview(camera); -} - -void Camera_mouseMove(camera_t& camera, int x, int y) -{ - //globalOutputStream() << "mousemove... "; - Camera_FreeMove(camera, -x, -y); - camera.m_update(); - CameraMovedNotify(); -} - -const unsigned int MOVE_NONE = 0; -const unsigned int MOVE_FORWARD = 1 << 0; -const unsigned int MOVE_BACK = 1 << 1; -const unsigned int MOVE_ROTRIGHT = 1 << 2; -const unsigned int MOVE_ROTLEFT = 1 << 3; -const unsigned int MOVE_STRAFERIGHT = 1 << 4; -const unsigned int MOVE_STRAFELEFT = 1 << 5; -const unsigned int MOVE_UP = 1 << 6; -const unsigned int MOVE_DOWN = 1 << 7; -const unsigned int MOVE_PITCHUP = 1 << 8; -const unsigned int MOVE_PITCHDOWN = 1 << 9; -const unsigned int MOVE_ALL = MOVE_FORWARD|MOVE_BACK|MOVE_ROTRIGHT|MOVE_ROTLEFT|MOVE_STRAFERIGHT|MOVE_STRAFELEFT|MOVE_UP|MOVE_DOWN|MOVE_PITCHUP|MOVE_PITCHDOWN; - -void Cam_KeyControl(camera_t& camera, float dtime) -{ - // Update angles - if (camera.movementflags & MOVE_ROTLEFT) - camera.angles[CAMERA_YAW] += 15 * dtime* g_camwindow_globals_private.m_nAngleSpeed; - if (camera.movementflags & MOVE_ROTRIGHT) - camera.angles[CAMERA_YAW] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed; - if (camera.movementflags & MOVE_PITCHUP) - { - camera.angles[CAMERA_PITCH] += 15 * dtime* g_camwindow_globals_private.m_nAngleSpeed; - if(camera.angles[CAMERA_PITCH] > 90) - camera.angles[CAMERA_PITCH] = 90; - } - if (camera.movementflags & MOVE_PITCHDOWN) - { - camera.angles[CAMERA_PITCH] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed; - if(camera.angles[CAMERA_PITCH] < -90) - camera.angles[CAMERA_PITCH] = -90; - } - - Camera_updateModelview(camera); - Camera_Freemove_updateAxes(camera); - - // Update position - if (camera.movementflags & MOVE_FORWARD) - vector3_add(camera.origin, vector3_scaled(camera.forward, dtime * g_camwindow_globals_private.m_nMoveSpeed)); - if (camera.movementflags & MOVE_BACK) - vector3_add(camera.origin, vector3_scaled(camera.forward, -dtime * g_camwindow_globals_private.m_nMoveSpeed)); - if (camera.movementflags & MOVE_STRAFELEFT) - vector3_add(camera.origin, vector3_scaled(camera.right, -dtime * g_camwindow_globals_private.m_nMoveSpeed)); - if (camera.movementflags & MOVE_STRAFERIGHT) - vector3_add(camera.origin, vector3_scaled(camera.right, dtime * g_camwindow_globals_private.m_nMoveSpeed)); - if (camera.movementflags & MOVE_UP) - vector3_add(camera.origin, vector3_scaled(g_vector3_axis_z, dtime * g_camwindow_globals_private.m_nMoveSpeed)); - if (camera.movementflags & MOVE_DOWN) - vector3_add(camera.origin, vector3_scaled(g_vector3_axis_z, -dtime * g_camwindow_globals_private.m_nMoveSpeed)); - - Camera_updateModelview(camera); -} - -void Camera_keyMove(camera_t& camera) -{ - camera.m_mouseMove.flush(); - - //globalOutputStream() << "keymove... "; - float time_seconds = camera.m_keycontrol_timer.elapsed_msec() / static_cast(msec_per_sec); - camera.m_keycontrol_timer.start(); - if(time_seconds > 0.05f) - { - time_seconds = 0.05f; // 20fps - } - Cam_KeyControl(camera, time_seconds * 5.0f); - - camera.m_update(); - CameraMovedNotify(); -} - -gboolean camera_keymove(gpointer data) -{ - Camera_keyMove(*reinterpret_cast(data)); - return TRUE; -} - -void Camera_setMovementFlags(camera_t& camera, unsigned int mask) -{ - if((~camera.movementflags & mask) != 0 && camera.movementflags == 0) - { - camera.m_keymove_handler = g_idle_add(camera_keymove, &camera); - } - camera.movementflags |= mask; -} -void Camera_clearMovementFlags(camera_t& camera, unsigned int mask) -{ - if((camera.movementflags & ~mask) == 0 && camera.movementflags != 0) - { - g_source_remove(camera.m_keymove_handler); - camera.m_keymove_handler = 0; - } - camera.movementflags &= ~mask; -} - -void Camera_MoveForward_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_FORWARD); -} -void Camera_MoveForward_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_FORWARD); -} -void Camera_MoveBack_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_BACK); -} -void Camera_MoveBack_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_BACK); -} - -void Camera_MoveLeft_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_STRAFELEFT); -} -void Camera_MoveLeft_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_STRAFELEFT); -} -void Camera_MoveRight_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_STRAFERIGHT); -} -void Camera_MoveRight_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_STRAFERIGHT); -} - -void Camera_MoveUp_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_UP); -} -void Camera_MoveUp_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_UP); -} -void Camera_MoveDown_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_DOWN); -} -void Camera_MoveDown_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_DOWN); -} - -void Camera_RotateLeft_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_ROTLEFT); -} -void Camera_RotateLeft_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_ROTLEFT); -} -void Camera_RotateRight_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_ROTRIGHT); -} -void Camera_RotateRight_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_ROTRIGHT); -} - -void Camera_PitchUp_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_PITCHUP); -} -void Camera_PitchUp_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_PITCHUP); -} -void Camera_PitchDown_KeyDown(camera_t& camera) -{ - Camera_setMovementFlags(camera, MOVE_PITCHDOWN); -} -void Camera_PitchDown_KeyUp(camera_t& camera) -{ - Camera_clearMovementFlags(camera, MOVE_PITCHDOWN); -} - - -typedef ReferenceCaller FreeMoveCameraMoveForwardKeyDownCaller; -typedef ReferenceCaller FreeMoveCameraMoveForwardKeyUpCaller; -typedef ReferenceCaller FreeMoveCameraMoveBackKeyDownCaller; -typedef ReferenceCaller FreeMoveCameraMoveBackKeyUpCaller; -typedef ReferenceCaller FreeMoveCameraMoveLeftKeyDownCaller; -typedef ReferenceCaller FreeMoveCameraMoveLeftKeyUpCaller; -typedef ReferenceCaller FreeMoveCameraMoveRightKeyDownCaller; -typedef ReferenceCaller FreeMoveCameraMoveRightKeyUpCaller; -typedef ReferenceCaller FreeMoveCameraMoveUpKeyDownCaller; -typedef ReferenceCaller FreeMoveCameraMoveUpKeyUpCaller; -typedef ReferenceCaller FreeMoveCameraMoveDownKeyDownCaller; -typedef ReferenceCaller FreeMoveCameraMoveDownKeyUpCaller; - - -#define SPEED_MOVE 32 -#define SPEED_TURN 22.5 -#define MIN_CAM_SPEED 10 -#define MAX_CAM_SPEED 610 -#define CAM_SPEED_STEP 50 - -void Camera_MoveForward_Discrete(camera_t& camera) -{ - Camera_Move_updateAxes(camera); - Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.forward, SPEED_MOVE))); -} -void Camera_MoveBack_Discrete(camera_t& camera) -{ - Camera_Move_updateAxes(camera); - Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.forward, -SPEED_MOVE))); -} - -void Camera_MoveUp_Discrete(camera_t& camera) -{ - Vector3 origin(Camera_getOrigin(camera)); - origin[2] += SPEED_MOVE; - Camera_setOrigin(camera, origin); -} -void Camera_MoveDown_Discrete(camera_t& camera) -{ - Vector3 origin(Camera_getOrigin(camera)); - origin[2] -= SPEED_MOVE; - Camera_setOrigin(camera, origin); -} - -void Camera_MoveLeft_Discrete(camera_t& camera) -{ - Camera_Move_updateAxes(camera); - Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.right, -SPEED_MOVE))); -} -void Camera_MoveRight_Discrete(camera_t& camera) -{ - Camera_Move_updateAxes(camera); - Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.right, SPEED_MOVE))); -} - -void Camera_RotateLeft_Discrete(camera_t& camera) -{ - Vector3 angles(Camera_getAngles(camera)); - angles[CAMERA_YAW] += SPEED_TURN; - Camera_setAngles(camera, angles); -} -void Camera_RotateRight_Discrete(camera_t& camera) -{ - Vector3 angles(Camera_getAngles(camera)); - angles[CAMERA_YAW] -= SPEED_TURN; - Camera_setAngles(camera, angles); -} - -void Camera_PitchUp_Discrete(camera_t& camera) -{ - Vector3 angles(Camera_getAngles(camera)); - angles[CAMERA_PITCH] += SPEED_TURN; - if (angles[CAMERA_PITCH] > 90) - angles[CAMERA_PITCH] = 90; - Camera_setAngles(camera, angles); -} -void Camera_PitchDown_Discrete(camera_t& camera) -{ - Vector3 angles(Camera_getAngles(camera)); - angles[CAMERA_PITCH] -= SPEED_TURN; - if (angles[CAMERA_PITCH] < -90) - angles[CAMERA_PITCH] = -90; - Camera_setAngles(camera, angles); -} - - -class RadiantCameraView : public CameraView -{ - camera_t& m_camera; - View* m_view; - Callback m_update; -public: - RadiantCameraView(camera_t& camera, View* view, const Callback& update) : m_camera(camera), m_view(view), m_update(update) - { - } - void update() - { - m_view->Construct(m_camera.projection, m_camera.modelview, m_camera.width, m_camera.height); - m_update(); - } - void setModelview(const Matrix4& modelview) - { - m_camera.modelview = modelview; - matrix4_multiply_by_matrix4(m_camera.modelview, g_radiant2opengl); - matrix4_affine_invert(m_camera.modelview); - Camera_updateVectors(m_camera); - update(); - } - void setFieldOfView(float fieldOfView) - { - float farClip = Camera_getFarClipPlane(m_camera); - m_camera.projection = projection_for_camera(farClip / 4096.0f, farClip, fieldOfView, m_camera.width, m_camera.height); - update(); - } -}; - - -void Camera_motionDelta(int x, int y, unsigned int state, void* data) -{ - camera_t* cam = reinterpret_cast(data); - - cam->m_mouseMove.motion_delta(x, y, state); - - switch(g_camwindow_globals_private.m_nStrafeMode) - { - case 0: - cam->m_strafe = (state & GDK_CONTROL_MASK) != 0; - if(cam->m_strafe) - cam->m_strafe_forward = (state & GDK_SHIFT_MASK) != 0; - else - cam->m_strafe_forward = false; - break; - case 1: - cam->m_strafe = (state & GDK_CONTROL_MASK) != 0 && (state & GDK_SHIFT_MASK) == 0; - cam->m_strafe_forward = false; - break; - case 2: - cam->m_strafe = (state & GDK_CONTROL_MASK) != 0 && (state & GDK_SHIFT_MASK) == 0; - cam->m_strafe_forward = cam->m_strafe; - break; - } -} - -class CamWnd -{ - View m_view; - camera_t m_Camera; - RadiantCameraView m_cameraview; -#if 0 - int m_PositionDragCursorX; - int m_PositionDragCursorY; -#endif - - guint m_freemove_handle_focusout; - - static Shader* m_state_select1; - static Shader* m_state_select2; - - FreezePointer m_freezePointer; - -public: - GtkWidget* m_gl_widget; - GtkWindow* m_parent; - - SelectionSystemWindowObserver* m_window_observer; - XORRectangle m_XORRectangle; - - DeferredDraw m_deferredDraw; - DeferredMotion m_deferred_motion; - - guint m_selection_button_press_handler; - guint m_selection_button_release_handler; - guint m_selection_motion_handler; - - guint m_freelook_button_press_handler; - - guint m_sizeHandler; - guint m_exposeHandler; - - CamWnd(); - ~CamWnd(); - - bool m_drawing; - void queue_draw() - { - //ASSERT_MESSAGE(!m_drawing, "CamWnd::queue_draw(): called while draw is already in progress"); - if(m_drawing) - { - return; - } - //globalOutputStream() << "queue... "; - m_deferredDraw.draw(); - } - void draw(); - - static void captureStates() - { - m_state_select1 = GlobalShaderCache().capture("$CAM_HIGHLIGHT"); - m_state_select2 = GlobalShaderCache().capture("$CAM_OVERLAY"); - } - static void releaseStates() - { - GlobalShaderCache().release("$CAM_HIGHLIGHT"); - GlobalShaderCache().release("$CAM_OVERLAY"); - } - - camera_t& getCamera() - { - return m_Camera; - }; - - void BenchMark(); - void Cam_ChangeFloor(bool up); - - void DisableFreeMove(); - void EnableFreeMove(); - bool m_bFreeMove; - - CameraView& getCameraView() - { - return m_cameraview; - } - -private: - void Cam_Draw(); -}; - -typedef MemberCaller CamWndQueueDraw; - -Shader* CamWnd::m_state_select1 = 0; -Shader* CamWnd::m_state_select2 = 0; - -CamWnd* NewCamWnd() -{ - return new CamWnd; -} -void DeleteCamWnd(CamWnd* camwnd) -{ - delete camwnd; -} - -void CamWnd_constructStatic() -{ - CamWnd::captureStates(); -} - -void CamWnd_destroyStatic() -{ - CamWnd::releaseStates(); -} - -static CamWnd* g_camwnd = 0; - -void GlobalCamera_setCamWnd(CamWnd& camwnd) -{ - g_camwnd = &camwnd; -} - - -GtkWidget* CamWnd_getWidget(CamWnd& camwnd) -{ - return camwnd.m_gl_widget; -} - -GtkWindow* CamWnd_getParent(CamWnd& camwnd) -{ - return camwnd.m_parent; -} - -ToggleShown g_camera_shown(true); - -void CamWnd_setParent(CamWnd& camwnd, GtkWindow* parent) -{ - camwnd.m_parent = parent; - g_camera_shown.connect(GTK_WIDGET(camwnd.m_parent)); -} - -void CamWnd_Update(CamWnd& camwnd) -{ - camwnd.queue_draw(); -} - - - -camwindow_globals_t g_camwindow_globals; - -const Vector3& Camera_getOrigin(CamWnd& camwnd) -{ - return Camera_getOrigin(camwnd.getCamera()); -} - -void Camera_setOrigin(CamWnd& camwnd, const Vector3& origin) -{ - Camera_setOrigin(camwnd.getCamera(), origin); -} - -const Vector3& Camera_getAngles(CamWnd& camwnd) -{ - return Camera_getAngles(camwnd.getCamera()); -} - -void Camera_setAngles(CamWnd& camwnd, const Vector3& angles) -{ - Camera_setAngles(camwnd.getCamera(), angles); -} - - -// ============================================================================= -// CamWnd class - -gboolean enable_freelook_button_press(GtkWidget* widget, GdkEventButton* event, CamWnd* camwnd) -{ - if(event->type == GDK_BUTTON_PRESS && event->button == 3) - { - camwnd->EnableFreeMove(); - return TRUE; - } - return FALSE; -} - -gboolean disable_freelook_button_press(GtkWidget* widget, GdkEventButton* event, CamWnd* camwnd) -{ - if(event->type == GDK_BUTTON_PRESS && event->button == 3) - { - camwnd->DisableFreeMove(); - return TRUE; - } - return FALSE; -} - -#if 0 -gboolean mousecontrol_button_press(GtkWidget* widget, GdkEventButton* event, CamWnd* camwnd) -{ - if(event->type == GDK_BUTTON_PRESS && event->button == 3) - { - Cam_MouseControl(camwnd->getCamera(), event->x, widget->allocation.height - 1 - event->y); - } - return FALSE; -} -#endif - -void camwnd_update_xor_rectangle(CamWnd& self, rect_t area) -{ - if(GTK_WIDGET_VISIBLE(self.m_gl_widget)) - { - self.m_XORRectangle.set(rectangle_from_area(area.min, area.max, self.getCamera().width, self.getCamera().height)); - } -} - - -gboolean selection_button_press(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) -{ - if(event->type == GDK_BUTTON_PRESS) - { - observer->onMouseDown(WindowVector_forDouble(event->x, event->y), button_for_button(event->button), modifiers_for_state(event->state)); - } - return FALSE; -} - -gboolean selection_button_release(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) -{ - if(event->type == GDK_BUTTON_RELEASE) - { - observer->onMouseUp(WindowVector_forDouble(event->x, event->y), button_for_button(event->button), modifiers_for_state(event->state)); - } - return FALSE; -} - -void selection_motion(gdouble x, gdouble y, guint state, void* data) -{ - //globalOutputStream() << "motion... "; - reinterpret_cast(data)->onMouseMotion(WindowVector_forDouble(x, y), modifiers_for_state(state)); -} - -inline WindowVector windowvector_for_widget_centre(GtkWidget* widget) -{ - return WindowVector(static_cast(widget->allocation.width / 2), static_cast(widget->allocation.height / 2)); -} - -gboolean selection_button_press_freemove(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) -{ - if(event->type == GDK_BUTTON_PRESS) - { - observer->onMouseDown(windowvector_for_widget_centre(widget), button_for_button(event->button), modifiers_for_state(event->state)); - } - return FALSE; -} - -gboolean selection_button_release_freemove(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) -{ - if(event->type == GDK_BUTTON_RELEASE) - { - observer->onMouseUp(windowvector_for_widget_centre(widget), button_for_button(event->button), modifiers_for_state(event->state)); - } - return FALSE; -} - -gboolean selection_motion_freemove(GtkWidget *widget, GdkEventMotion *event, WindowObserver* observer) -{ - observer->onMouseMotion(windowvector_for_widget_centre(widget), modifiers_for_state(event->state)); - return FALSE; -} - -gboolean wheelmove_scroll(GtkWidget* widget, GdkEventScroll* event, CamWnd* camwnd) -{ - if(event->direction == GDK_SCROLL_UP) - { - Camera_Freemove_updateAxes(camwnd->getCamera()); - Camera_setOrigin(*camwnd, vector3_added(Camera_getOrigin(*camwnd), vector3_scaled(camwnd->getCamera().forward, static_cast(g_camwindow_globals_private.m_nMoveSpeed)))); - } - else if(event->direction == GDK_SCROLL_DOWN) - { - Camera_Freemove_updateAxes(camwnd->getCamera()); - Camera_setOrigin(*camwnd, vector3_added(Camera_getOrigin(*camwnd), vector3_scaled(camwnd->getCamera().forward, -static_cast(g_camwindow_globals_private.m_nMoveSpeed)))); - } - - return FALSE; -} - -gboolean camera_size_allocate(GtkWidget* widget, GtkAllocation* allocation, CamWnd* camwnd) -{ - camwnd->getCamera().width = allocation->width; - camwnd->getCamera().height = allocation->height; - Camera_updateProjection(camwnd->getCamera()); - camwnd->m_window_observer->onSizeChanged(camwnd->getCamera().width, camwnd->getCamera().height); - camwnd->queue_draw(); - return FALSE; -} - -gboolean camera_expose(GtkWidget* widget, GdkEventExpose* event, gpointer data) -{ - reinterpret_cast(data)->draw(); - return FALSE; -} - -void KeyEvent_connect(const char* name) -{ - const KeyEvent& keyEvent = GlobalKeyEvents_find(name); - keydown_accelerators_add(keyEvent.m_accelerator, keyEvent.m_keyDown); - keyup_accelerators_add(keyEvent.m_accelerator, keyEvent.m_keyUp); -} - -void KeyEvent_disconnect(const char* name) -{ - const KeyEvent& keyEvent = GlobalKeyEvents_find(name); - keydown_accelerators_remove(keyEvent.m_accelerator); - keyup_accelerators_remove(keyEvent.m_accelerator); -} - -void CamWnd_registerCommands(CamWnd& camwnd) -{ - GlobalKeyEvents_insert("CameraForward", Accelerator(GDK_Up), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraBack", Accelerator(GDK_Down), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraLeft", Accelerator(GDK_Left), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraRight", Accelerator(GDK_Right), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraStrafeRight", Accelerator(GDK_period), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraStrafeLeft", Accelerator(GDK_comma), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraUp", Accelerator('D'), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraDown", Accelerator('C'), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraAngleDown", Accelerator('A'), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraAngleUp", Accelerator('Z'), - ReferenceCaller(camwnd.getCamera()), - ReferenceCaller(camwnd.getCamera()) - ); - - GlobalKeyEvents_insert("CameraFreeMoveForward", Accelerator(GDK_Up), - FreeMoveCameraMoveForwardKeyDownCaller(camwnd.getCamera()), - FreeMoveCameraMoveForwardKeyUpCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraFreeMoveBack", Accelerator(GDK_Down), - FreeMoveCameraMoveBackKeyDownCaller(camwnd.getCamera()), - FreeMoveCameraMoveBackKeyUpCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraFreeMoveLeft", Accelerator(GDK_Left), - FreeMoveCameraMoveLeftKeyDownCaller(camwnd.getCamera()), - FreeMoveCameraMoveLeftKeyUpCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraFreeMoveRight", Accelerator(GDK_Right), - FreeMoveCameraMoveRightKeyDownCaller(camwnd.getCamera()), - FreeMoveCameraMoveRightKeyUpCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraFreeMoveUp", Accelerator('D'), - FreeMoveCameraMoveUpKeyDownCaller(camwnd.getCamera()), - FreeMoveCameraMoveUpKeyUpCaller(camwnd.getCamera()) - ); - GlobalKeyEvents_insert("CameraFreeMoveDown", Accelerator('C'), - FreeMoveCameraMoveDownKeyDownCaller(camwnd.getCamera()), - FreeMoveCameraMoveDownKeyUpCaller(camwnd.getCamera()) - ); - - GlobalCommands_insert("CameraForward", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Up)); - GlobalCommands_insert("CameraBack", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Down)); - GlobalCommands_insert("CameraLeft", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Left)); - GlobalCommands_insert("CameraRight", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Right)); - GlobalCommands_insert("CameraStrafeRight", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_period)); - GlobalCommands_insert("CameraStrafeLeft", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_comma)); - - GlobalCommands_insert("CameraUp", ReferenceCaller(camwnd.getCamera()), Accelerator('D')); - GlobalCommands_insert("CameraDown", ReferenceCaller(camwnd.getCamera()), Accelerator('C')); - GlobalCommands_insert("CameraAngleUp", ReferenceCaller(camwnd.getCamera()), Accelerator('A')); - GlobalCommands_insert("CameraAngleDown", ReferenceCaller(camwnd.getCamera()), Accelerator('Z')); -} - -void CamWnd_Move_Enable(CamWnd& camwnd) -{ - KeyEvent_connect("CameraForward"); - KeyEvent_connect("CameraBack"); - KeyEvent_connect("CameraLeft"); - KeyEvent_connect("CameraRight"); - KeyEvent_connect("CameraStrafeRight"); - KeyEvent_connect("CameraStrafeLeft"); - KeyEvent_connect("CameraUp"); - KeyEvent_connect("CameraDown"); - KeyEvent_connect("CameraAngleUp"); - KeyEvent_connect("CameraAngleDown"); -} - -void CamWnd_Move_Disable(CamWnd& camwnd) -{ - KeyEvent_disconnect("CameraForward"); - KeyEvent_disconnect("CameraBack"); - KeyEvent_disconnect("CameraLeft"); - KeyEvent_disconnect("CameraRight"); - KeyEvent_disconnect("CameraStrafeRight"); - KeyEvent_disconnect("CameraStrafeLeft"); - KeyEvent_disconnect("CameraUp"); - KeyEvent_disconnect("CameraDown"); - KeyEvent_disconnect("CameraAngleUp"); - KeyEvent_disconnect("CameraAngleDown"); -} - -void CamWnd_Move_Discrete_Enable(CamWnd& camwnd) -{ - command_connect_accelerator("CameraForward"); - command_connect_accelerator("CameraBack"); - command_connect_accelerator("CameraLeft"); - command_connect_accelerator("CameraRight"); - command_connect_accelerator("CameraStrafeRight"); - command_connect_accelerator("CameraStrafeLeft"); - command_connect_accelerator("CameraUp"); - command_connect_accelerator("CameraDown"); - command_connect_accelerator("CameraAngleUp"); - command_connect_accelerator("CameraAngleDown"); -} - -void CamWnd_Move_Discrete_Disable(CamWnd& camwnd) -{ - command_disconnect_accelerator("CameraForward"); - command_disconnect_accelerator("CameraBack"); - command_disconnect_accelerator("CameraLeft"); - command_disconnect_accelerator("CameraRight"); - command_disconnect_accelerator("CameraStrafeRight"); - command_disconnect_accelerator("CameraStrafeLeft"); - command_disconnect_accelerator("CameraUp"); - command_disconnect_accelerator("CameraDown"); - command_disconnect_accelerator("CameraAngleUp"); - command_disconnect_accelerator("CameraAngleDown"); -} - -void CamWnd_Move_Discrete_Import(CamWnd& camwnd, bool value) -{ - if(g_camwindow_globals_private.m_bCamDiscrete) - { - CamWnd_Move_Discrete_Disable(camwnd); - } - else - { - CamWnd_Move_Disable(camwnd); - } - - g_camwindow_globals_private.m_bCamDiscrete = value; - - if(g_camwindow_globals_private.m_bCamDiscrete) - { - CamWnd_Move_Discrete_Enable(camwnd); - } - else - { - CamWnd_Move_Enable(camwnd); - } -} - -void CamWnd_Move_Discrete_Import(bool value) -{ - if(g_camwnd != 0) - { - CamWnd_Move_Discrete_Import(*g_camwnd, value); - } - else - { - g_camwindow_globals_private.m_bCamDiscrete = value; - } -} - - - -void CamWnd_Add_Handlers_Move(CamWnd& camwnd) -{ - camwnd.m_selection_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(selection_button_press), camwnd.m_window_observer); - camwnd.m_selection_button_release_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_release_event", G_CALLBACK(selection_button_release), camwnd.m_window_observer); - camwnd.m_selection_motion_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "motion_notify_event", G_CALLBACK(DeferredMotion::gtk_motion), &camwnd.m_deferred_motion); - - camwnd.m_freelook_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(enable_freelook_button_press), &camwnd); - - if(g_camwindow_globals_private.m_bCamDiscrete) - { - CamWnd_Move_Discrete_Enable(camwnd); - } - else - { - CamWnd_Move_Enable(camwnd); - } -} - -void CamWnd_Remove_Handlers_Move(CamWnd& camwnd) -{ - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_press_handler); - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_release_handler); - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_motion_handler); - - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_freelook_button_press_handler); - - if(g_camwindow_globals_private.m_bCamDiscrete) - { - CamWnd_Move_Discrete_Disable(camwnd); - } - else - { - CamWnd_Move_Disable(camwnd); - } -} - -void CamWnd_Add_Handlers_FreeMove(CamWnd& camwnd) -{ - camwnd.m_selection_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(selection_button_press_freemove), camwnd.m_window_observer); - camwnd.m_selection_button_release_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_release_event", G_CALLBACK(selection_button_release_freemove), camwnd.m_window_observer); - camwnd.m_selection_motion_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "motion_notify_event", G_CALLBACK(selection_motion_freemove), camwnd.m_window_observer); - - camwnd.m_freelook_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(disable_freelook_button_press), &camwnd); - - KeyEvent_connect("CameraFreeMoveForward"); - KeyEvent_connect("CameraFreeMoveBack"); - KeyEvent_connect("CameraFreeMoveLeft"); - KeyEvent_connect("CameraFreeMoveRight"); - KeyEvent_connect("CameraFreeMoveUp"); - KeyEvent_connect("CameraFreeMoveDown"); -} - -void CamWnd_Remove_Handlers_FreeMove(CamWnd& camwnd) -{ - KeyEvent_disconnect("CameraFreeMoveForward"); - KeyEvent_disconnect("CameraFreeMoveBack"); - KeyEvent_disconnect("CameraFreeMoveLeft"); - KeyEvent_disconnect("CameraFreeMoveRight"); - KeyEvent_disconnect("CameraFreeMoveUp"); - KeyEvent_disconnect("CameraFreeMoveDown"); - - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_press_handler); - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_release_handler); - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_motion_handler); - - g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_freelook_button_press_handler); -} - -CamWnd::CamWnd() : - m_view(true), - m_Camera(&m_view, CamWndQueueDraw(*this)), - m_cameraview(m_Camera, &m_view, ReferenceCaller(*this)), - m_gl_widget(glwidget_new(TRUE)), - m_window_observer(NewWindowObserver()), - m_XORRectangle(m_gl_widget), - m_deferredDraw(WidgetQueueDrawCaller(*m_gl_widget)), - m_deferred_motion(selection_motion, m_window_observer), - m_selection_button_press_handler(0), - m_selection_button_release_handler(0), - m_selection_motion_handler(0), - m_freelook_button_press_handler(0), - m_drawing(false) -{ - m_bFreeMove = false; - - GlobalWindowObservers_add(m_window_observer); - GlobalWindowObservers_connectWidget(m_gl_widget); - - m_window_observer->setRectangleDrawCallback(ReferenceCaller1(*this)); - m_window_observer->setView(m_view); - - gtk_widget_ref(m_gl_widget); - - gtk_widget_set_events(m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK); - GTK_WIDGET_SET_FLAGS (m_gl_widget, GTK_CAN_FOCUS); - - m_sizeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "size_allocate", G_CALLBACK(camera_size_allocate), this); - m_exposeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "expose_event", G_CALLBACK(camera_expose), this); - - Map_addValidCallback(g_map, DeferredDrawOnMapValidChangedCaller(m_deferredDraw)); - - CamWnd_registerCommands(*this); - - CamWnd_Add_Handlers_Move(*this); - - g_signal_connect(G_OBJECT(m_gl_widget), "scroll_event", G_CALLBACK(wheelmove_scroll), this); - - AddSceneChangeCallback(ReferenceCaller(*this)); - - PressedButtons_connect(g_pressedButtons, m_gl_widget); -} - -CamWnd::~CamWnd() -{ - if(m_bFreeMove) - { - DisableFreeMove(); - } - - CamWnd_Remove_Handlers_Move(*this); - - g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_sizeHandler); - g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_exposeHandler); - - gtk_widget_unref(m_gl_widget); - - m_window_observer->release(); -} - -class FloorHeightWalker : public scene::Graph::Walker -{ - float m_current; - float& m_bestUp; - float& m_bestDown; -public: - FloorHeightWalker(float current, float& bestUp, float& bestDown) : - m_current(current), m_bestUp(bestUp), m_bestDown(bestDown) - { - bestUp = g_MaxWorldCoord; - bestDown = -g_MaxWorldCoord; - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible() - && Node_isBrush(path.top())) // this node is a floor - { - const AABB& aabb = instance.worldAABB(); - float floorHeight = aabb.origin.z() + aabb.extents.z(); - if(floorHeight > m_current && floorHeight < m_bestUp) - { - m_bestUp = floorHeight; - } - if(floorHeight < m_current && floorHeight > m_bestDown) - { - m_bestDown = floorHeight; - } - } - return true; - } -}; - -void CamWnd::Cam_ChangeFloor(bool up) -{ - float current = m_Camera.origin[2] - 48; - float bestUp; - float bestDown; - GlobalSceneGraph().traverse(FloorHeightWalker(current, bestUp, bestDown)); - - if(up && bestUp != g_MaxWorldCoord) - { - current = bestUp; - } - if(!up && bestDown != -g_MaxWorldCoord) - { - current = bestDown; - } - - m_Camera.origin[2] = current + 48; - Camera_updateModelview(getCamera()); - CamWnd_Update(*this); - CameraMovedNotify(); -} - - -#if 0 - -// button_press - Sys_GetCursorPos(&m_PositionDragCursorX, &m_PositionDragCursorY); - -// motion - if ( (m_bFreeMove && (buttons == (RAD_CONTROL|RAD_SHIFT))) - || (!m_bFreeMove && (buttons == (RAD_RBUTTON|RAD_CONTROL))) ) - { - Cam_PositionDrag(); - CamWnd_Update(camwnd); - CameraMovedNotify(); - return; - } - -void CamWnd::Cam_PositionDrag() -{ - int x, y; - - Sys_GetCursorPos(GTK_WINDOW(m_gl_widget), &x, &y); - if (x != m_PositionDragCursorX || y != m_PositionDragCursorY) - { - x -= m_PositionDragCursorX; - vector3_add(m_Camera.origin, vector3_scaled(m_Camera.vright, x)); - y -= m_PositionDragCursorY; - m_Camera.origin[2] -= y; - Camera_updateModelview(); - CamWnd_Update(camwnd); - CameraMovedNotify(); - - Sys_SetCursorPos(GTK_WINDOW(m_parent), m_PositionDragCursorX, m_PositionDragCursorY); - } -} -#endif - - -// NOTE TTimo if there's an OS-level focus out of the application -// then we can release the camera cursor grab -static gboolean camwindow_freemove_focusout(GtkWidget* widget, GdkEventFocus* event, gpointer data) -{ - reinterpret_cast(data)->DisableFreeMove(); - return FALSE; -} - -void CamWnd::EnableFreeMove() -{ - //globalOutputStream() << "EnableFreeMove\n"; - - ASSERT_MESSAGE(!m_bFreeMove, "EnableFreeMove: free-move was already enabled"); - m_bFreeMove = true; - Camera_clearMovementFlags(getCamera(), MOVE_ALL); - - CamWnd_Remove_Handlers_Move(*this); - CamWnd_Add_Handlers_FreeMove(*this); - - gtk_window_set_focus(m_parent, m_gl_widget); - m_freemove_handle_focusout = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(camwindow_freemove_focusout), this); - m_freezePointer.freeze_pointer(m_parent, Camera_motionDelta, &m_Camera); - - CamWnd_Update(*this); -} - -void CamWnd::DisableFreeMove() -{ - //globalOutputStream() << "DisableFreeMove\n"; - - ASSERT_MESSAGE(m_bFreeMove, "DisableFreeMove: free-move was not enabled"); - m_bFreeMove = false; - Camera_clearMovementFlags(getCamera(), MOVE_ALL); - - CamWnd_Remove_Handlers_FreeMove(*this); - CamWnd_Add_Handlers_Move(*this); - - m_freezePointer.unfreeze_pointer(m_parent); - g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_freemove_handle_focusout); - - CamWnd_Update(*this); -} - - -#include "renderer.h" - -class CamRenderer: public Renderer -{ - struct state_type - { - state_type() : m_highlight(0), m_state(0), m_lights(0) - { - } - unsigned int m_highlight; - Shader* m_state; - const LightList* m_lights; - }; - - std::vector m_state_stack; - RenderStateFlags m_globalstate; - Shader* m_state_select0; - Shader* m_state_select1; - const Vector3& m_viewer; - -public: - CamRenderer(RenderStateFlags globalstate, Shader* select0, Shader* select1, const Vector3& viewer) : - m_globalstate(globalstate), - m_state_select0(select0), - m_state_select1(select1), - m_viewer(viewer) - { - ASSERT_NOTNULL(select0); - ASSERT_NOTNULL(select1); - m_state_stack.push_back(state_type()); - } - - void SetState(Shader* state, EStyle style) - { - ASSERT_NOTNULL(state); - if(style == eFullMaterials) - { - m_state_stack.back().m_state = state; - } - } - const EStyle getStyle() const - { - return eFullMaterials; - } - void PushState() - { - m_state_stack.push_back(m_state_stack.back()); - } - void PopState() - { - ASSERT_MESSAGE(!m_state_stack.empty(), "popping empty stack"); - m_state_stack.pop_back(); - } - void Highlight(EHighlightMode mode, bool bEnable = true) - { - (bEnable) - ? m_state_stack.back().m_highlight |= mode - : m_state_stack.back().m_highlight &= ~mode; - } - void setLights(const LightList& lights) - { - m_state_stack.back().m_lights = &lights; - } - void addRenderable(const OpenGLRenderable& renderable, const Matrix4& world) - { - if(m_state_stack.back().m_highlight & ePrimitive) - { - m_state_select0->addRenderable(renderable, world, m_state_stack.back().m_lights); - } - if(m_state_stack.back().m_highlight & eFace) - { - m_state_select1->addRenderable(renderable, world, m_state_stack.back().m_lights); - } - - m_state_stack.back().m_state->addRenderable(renderable, world, m_state_stack.back().m_lights); - } - - void render(const Matrix4& modelview, const Matrix4& projection) - { - GlobalShaderCache().render(m_globalstate, modelview, projection, m_viewer); - } -}; - -/* -============== -Cam_Draw -============== -*/ - -void ShowStatsToggle() -{ - g_camwindow_globals_private.m_showStats ^= 1; -} -typedef FreeCaller ShowStatsToggleCaller; - -void ShowStatsExport(const BoolImportCallback& importer) -{ - importer(g_camwindow_globals_private.m_showStats); -} -typedef FreeCaller1 ShowStatsExportCaller; - -ShowStatsExportCaller g_show_stats_caller; -BoolExportCallback g_show_stats_callback(g_show_stats_caller); -ToggleItem g_show_stats(g_show_stats_callback); - -void CamWnd::Cam_Draw() -{ - glViewport(0, 0, m_Camera.width, m_Camera.height); -#if 0 - GLint viewprt[4]; - glGetIntegerv (GL_VIEWPORT, viewprt); -#endif - - // enable depth buffer writes - glDepthMask(GL_TRUE); - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - - Vector3 clearColour(0, 0, 0); - if(m_Camera.draw_mode != cd_lighting) - { - clearColour = g_camwindow_globals.color_cameraback; - } - - glClearColor(clearColour[0], clearColour[1], clearColour[2], 0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - extern void Renderer_ResetStats(); - Renderer_ResetStats(); - extern void Cull_ResetStats(); - Cull_ResetStats(); - - glMatrixMode(GL_PROJECTION); - glLoadMatrixf(reinterpret_cast(&m_Camera.projection)); - - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(reinterpret_cast(&m_Camera.modelview)); - - - // one directional light source directly behind the viewer - { - GLfloat inverse_cam_dir[4], ambient[4], diffuse[4];//, material[4]; - - ambient[0] = ambient[1] = ambient[2] = 0.4f; - ambient[3] = 1.0f; - diffuse[0] = diffuse[1] = diffuse[2] = 0.4f; - diffuse[3] = 1.0f; - //material[0] = material[1] = material[2] = 0.8f; - //material[3] = 1.0f; - - inverse_cam_dir[0] = m_Camera.vpn[0]; - inverse_cam_dir[1] = m_Camera.vpn[1]; - inverse_cam_dir[2] = m_Camera.vpn[2]; - inverse_cam_dir[3] = 0; - - glLightfv(GL_LIGHT0, GL_POSITION, inverse_cam_dir); - - glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); - glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); - - glEnable(GL_LIGHT0); - } - - - unsigned int globalstate = RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_ALPHATEST|RENDER_BLEND|RENDER_CULLFACE|RENDER_COLOURARRAY|RENDER_OFFSETLINE|RENDER_POLYGONSMOOTH|RENDER_LINESMOOTH|RENDER_FOG|RENDER_COLOURCHANGE; - switch (m_Camera.draw_mode) - { - case cd_wire: - break; - case cd_solid: - globalstate |= RENDER_FILL - | RENDER_LIGHTING - | RENDER_SMOOTH - | RENDER_SCALED; - break; - case cd_texture: - globalstate |= RENDER_FILL - | RENDER_LIGHTING - | RENDER_TEXTURE - | RENDER_SMOOTH - | RENDER_SCALED; - break; - case cd_lighting: - globalstate |= RENDER_FILL - | RENDER_LIGHTING - | RENDER_TEXTURE - | RENDER_SMOOTH - | RENDER_SCALED - | RENDER_BUMP - | RENDER_PROGRAM - | RENDER_SCREEN; - break; - default: - globalstate = 0; - break; - } - - if(!g_xywindow_globals.m_bNoStipple) - { - globalstate |= RENDER_LINESTIPPLE|RENDER_POLYGONSTIPPLE; - } - - { - CamRenderer renderer(globalstate, m_state_select2, m_state_select1, m_view.getViewer()); - - Scene_Render(renderer, m_view); - - renderer.render(m_Camera.modelview, m_Camera.projection); - } - - // prepare for 2d stuff - glColor4f(1, 1, 1, 1); - glDisable(GL_BLEND); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - glOrtho(0, (float)m_Camera.width, 0, (float)m_Camera.height, -100, 100); - glScalef(1, -1, 1); - glTranslatef(0, -(float)m_Camera.height, 0); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - - if(GlobalOpenGL().GL_1_3()) - { - glClientActiveTexture(GL_TEXTURE0); - glActiveTexture(GL_TEXTURE0); - } - - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - - glDisable(GL_TEXTURE_2D); - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); - glDisable(GL_DEPTH_TEST); - glColor3f( 1.f, 1.f, 1.f ); - glLineWidth(1); - - // draw the crosshair - if (m_bFreeMove) - { - glBegin( GL_LINES ); - glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 6 ); - glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 2 ); - glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 6 ); - glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 2 ); - glVertex2f( (float)m_Camera.width / 2.f + 6, (float)m_Camera.height / 2.f ); - glVertex2f( (float)m_Camera.width / 2.f + 2, (float)m_Camera.height / 2.f ); - glVertex2f( (float)m_Camera.width / 2.f - 6, (float)m_Camera.height / 2.f ); - glVertex2f( (float)m_Camera.width / 2.f - 2, (float)m_Camera.height / 2.f ); - glEnd(); - } - - if(g_camwindow_globals_private.m_showStats) - { - glRasterPos3f(1.0f, static_cast(m_Camera.height) - GlobalOpenGL().m_font->getPixelDescent(), 0.0f); - extern const char* Renderer_GetStats(); - GlobalOpenGL().drawString(Renderer_GetStats()); - - glRasterPos3f(1.0f, static_cast(m_Camera.height) - GlobalOpenGL().m_font->getPixelDescent() - GlobalOpenGL().m_font->getPixelHeight(), 0.0f); - extern const char* Cull_GetStats(); - GlobalOpenGL().drawString(Cull_GetStats()); - } - - // bind back to the default texture so that we don't have problems - // elsewhere using/modifying texture maps between contexts - glBindTexture( GL_TEXTURE_2D, 0 ); -} - -void CamWnd::draw() -{ - m_drawing = true; - - //globalOutputStream() << "draw...\n"; - if (glwidget_make_current(m_gl_widget) != FALSE) - { - if(Map_Valid(g_map) && ScreenUpdates_Enabled()) - { - GlobalOpenGL_debugAssertNoErrors(); - Cam_Draw(); - GlobalOpenGL_debugAssertNoErrors(); - //qglFinish(); - - m_XORRectangle.set(rectangle_t()); - } - - glwidget_swap_buffers(m_gl_widget); - } - - m_drawing = false; -} - -void CamWnd::BenchMark() -{ - double dStart = Sys_DoubleTime(); - for (int i=0 ; i < 100 ; i++) - { - Vector3 angles; - angles[CAMERA_ROLL] = 0; - angles[CAMERA_PITCH] = 0; - angles[CAMERA_YAW] = static_cast(i * (360.0 / 100.0)); - Camera_setAngles(*this, angles); - } - double dEnd = Sys_DoubleTime(); - globalOutputStream() << FloatFormat(dEnd - dStart, 5, 2) << " seconds\n"; -} - - -void fill_view_camera_menu(GtkMenu* menu) -{ - create_check_menu_item_with_mnemonic(menu, "Camera View", "ToggleCamera"); -} - -void GlobalCamera_ResetAngles() -{ - CamWnd& camwnd = *g_camwnd; - Vector3 angles; - angles[CAMERA_ROLL] = angles[CAMERA_PITCH] = 0; - angles[CAMERA_YAW] = static_cast(22.5 * floor((Camera_getAngles(camwnd)[CAMERA_YAW]+11)/22.5)); - Camera_setAngles(camwnd, angles); -} - -void Camera_ChangeFloorUp() -{ - CamWnd& camwnd = *g_camwnd; - camwnd.Cam_ChangeFloor (true); -} - -void Camera_ChangeFloorDown() -{ - CamWnd& camwnd = *g_camwnd; - camwnd.Cam_ChangeFloor (false); -} - -void Camera_CubeIn() -{ - CamWnd& camwnd = *g_camwnd; - g_camwindow_globals.m_nCubicScale--; - if (g_camwindow_globals.m_nCubicScale < 1) - g_camwindow_globals.m_nCubicScale = 1; - Camera_updateProjection(camwnd.getCamera()); - CamWnd_Update(camwnd); - g_pParentWnd->SetGridStatus(); -} - -void Camera_CubeOut() -{ - CamWnd& camwnd = *g_camwnd; - g_camwindow_globals.m_nCubicScale++; - if (g_camwindow_globals.m_nCubicScale > 23) - g_camwindow_globals.m_nCubicScale = 23; - Camera_updateProjection(camwnd.getCamera()); - CamWnd_Update(camwnd); - g_pParentWnd->SetGridStatus(); -} - -bool Camera_GetFarClip() -{ - return g_camwindow_globals_private.m_bCubicClipping; -} - -BoolExportCaller g_getfarclip_caller(g_camwindow_globals_private.m_bCubicClipping); -ToggleItem g_getfarclip_item(g_getfarclip_caller); - -void Camera_SetFarClip(bool value) -{ - CamWnd& camwnd = *g_camwnd; - g_camwindow_globals_private.m_bCubicClipping = value; - g_getfarclip_item.update(); - Camera_updateProjection(camwnd.getCamera()); - CamWnd_Update(camwnd); -} - -void Camera_ToggleFarClip() -{ - Camera_SetFarClip(!Camera_GetFarClip()); -} - - -void CamWnd_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_toggle_button(toolbar, "Cubic clip the camera view (\\)", "view_cubicclipping.bmp", "ToggleCubicClip"); -} - -void CamWnd_registerShortcuts() -{ - toggle_add_accelerator("ToggleCubicClip"); - - if(g_pGameDescription->mGameType == "doom3") - { - command_connect_accelerator("TogglePreview"); - } - - command_connect_accelerator("CameraSpeedInc"); - command_connect_accelerator("CameraSpeedDec"); -} - - -void GlobalCamera_Benchmark() -{ - CamWnd& camwnd = *g_camwnd; - camwnd.BenchMark(); -} - -void GlobalCamera_Update() -{ - CamWnd& camwnd = *g_camwnd; - CamWnd_Update(camwnd); -} - -camera_draw_mode CamWnd_GetMode() -{ - return camera_t::draw_mode; -} -void CamWnd_SetMode(camera_draw_mode mode) -{ - ShaderCache_setBumpEnabled(mode == cd_lighting); - camera_t::draw_mode = mode; - if(g_camwnd != 0) - { - CamWnd_Update(*g_camwnd); - } -} - -void CamWnd_TogglePreview(void) -{ - // gametype must be doom3 for this function to work - // if the gametype is not doom3 something is wrong with the - // global command list or somebody else calls this function. - ASSERT_MESSAGE(g_pGameDescription->mGameType == "doom3", "CamWnd_TogglePreview called although mGameType is not doom3 compatible"); - - // switch between textured and lighting mode - CamWnd_SetMode((CamWnd_GetMode() == cd_lighting) ? cd_texture : cd_lighting); -} - - -CameraModel* g_camera_model = 0; - -void CamWnd_LookThroughCamera(CamWnd& camwnd) -{ - if(g_camera_model != 0) - { - CamWnd_Add_Handlers_Move(camwnd); - g_camera_model->setCameraView(0, Callback()); - g_camera_model = 0; - Camera_updateModelview(camwnd.getCamera()); - Camera_updateProjection(camwnd.getCamera()); - CamWnd_Update(camwnd); - } -} - -inline CameraModel* Instance_getCameraModel(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); -} - -void CamWnd_LookThroughSelected(CamWnd& camwnd) -{ - if(g_camera_model != 0) - { - CamWnd_LookThroughCamera(camwnd); - } - - if(GlobalSelectionSystem().countSelected() != 0) - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - CameraModel* cameraModel = Instance_getCameraModel(instance); - if(cameraModel != 0) - { - CamWnd_Remove_Handlers_Move(camwnd); - g_camera_model = cameraModel; - g_camera_model->setCameraView(&camwnd.getCameraView(), ReferenceCaller(camwnd)); - } - } -} - -void GlobalCamera_LookThroughSelected() -{ - CamWnd_LookThroughSelected(*g_camwnd); -} - -void GlobalCamera_LookThroughCamera() -{ - CamWnd_LookThroughCamera(*g_camwnd); -} - - -void RenderModeImport(int value) -{ - switch(value) - { - case 0: - CamWnd_SetMode(cd_wire); - break; - case 1: - CamWnd_SetMode(cd_solid); - break; - case 2: - CamWnd_SetMode(cd_texture); - break; - case 3: - CamWnd_SetMode(cd_lighting); - break; - default: - CamWnd_SetMode(cd_texture); - } -} -typedef FreeCaller1 RenderModeImportCaller; - -void RenderModeExport(const IntImportCallback& importer) -{ - switch(CamWnd_GetMode()) - { - case cd_wire: - importer(0); - break; - case cd_solid: - importer(1); - break; - case cd_texture: - importer(2); - break; - case cd_lighting: - importer(3); - break; - } -} -typedef FreeCaller1 RenderModeExportCaller; - -void Camera_constructPreferences(PreferencesPage& page) -{ - page.appendSlider("Movement Speed", g_camwindow_globals_private.m_nMoveSpeed, TRUE, 0, 0, 100, MIN_CAM_SPEED, MAX_CAM_SPEED, 1, 10); - page.appendCheckBox("", "Link strafe speed to movement speed", g_camwindow_globals_private.m_bCamLinkSpeed); - page.appendSlider("Rotation Speed", g_camwindow_globals_private.m_nAngleSpeed, TRUE, 0, 0, 3, 1, 180, 1, 10); - page.appendCheckBox("", "Invert mouse vertical axis", g_camwindow_globals_private.m_bCamInverseMouse); - page.appendCheckBox( - "", "Discrete movement", - FreeCaller1(), - BoolExportCaller(g_camwindow_globals_private.m_bCamDiscrete) - ); - page.appendCheckBox( - "", "Enable far-clip plane", - FreeCaller1(), - BoolExportCaller(g_camwindow_globals_private.m_bCubicClipping) - ); - - if(g_pGameDescription->mGameType == "doom3") - { - const char* render_mode[] = { "Wireframe", "Flatshade", "Textured", "Lighting" }; - - page.appendCombo( - "Render Mode", - STRING_ARRAY_RANGE(render_mode), - IntImportCallback(RenderModeImportCaller()), - IntExportCallback(RenderModeExportCaller()) - ); - } - else - { - const char* render_mode[] = { "Wireframe", "Flatshade", "Textured" }; - - page.appendCombo( - "Render Mode", - STRING_ARRAY_RANGE(render_mode), - IntImportCallback(RenderModeImportCaller()), - IntExportCallback(RenderModeExportCaller()) - ); - } - - const char* strafe_mode[] = { "Both", "Forward", "Up" }; - - page.appendCombo( - "Strafe Mode", - g_camwindow_globals_private.m_nStrafeMode, - STRING_ARRAY_RANGE(strafe_mode) - ); -} -void Camera_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Camera", "Camera View Preferences")); - Camera_constructPreferences(page); -} -void Camera_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - -#include "preferencesystem.h" -#include "stringio.h" -#include "dialog.h" - -typedef FreeCaller1 CamWndMoveDiscreteImportCaller; - -void CameraSpeed_increase() -{ - if(g_camwindow_globals_private.m_nMoveSpeed <= (MAX_CAM_SPEED - CAM_SPEED_STEP - 10)) - { - g_camwindow_globals_private.m_nMoveSpeed += CAM_SPEED_STEP; - } else { - g_camwindow_globals_private.m_nMoveSpeed = MAX_CAM_SPEED - 10; - } -} - -void CameraSpeed_decrease() -{ - if(g_camwindow_globals_private.m_nMoveSpeed >= (MIN_CAM_SPEED + CAM_SPEED_STEP)) - { - g_camwindow_globals_private.m_nMoveSpeed -= CAM_SPEED_STEP; - } else { - g_camwindow_globals_private.m_nMoveSpeed = MIN_CAM_SPEED; - } -} - -/// \brief Initialisation for things that have the same lifespan as this module. -void CamWnd_Construct() -{ - GlobalCommands_insert("CenterView", FreeCaller(), Accelerator(GDK_End)); - - GlobalToggles_insert("ToggleCubicClip", FreeCaller(), ToggleItem::AddCallbackCaller(g_getfarclip_item), Accelerator('\\', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("CubicClipZoomIn", FreeCaller(), Accelerator('[', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("CubicClipZoomOut", FreeCaller(), Accelerator(']', (GdkModifierType)GDK_CONTROL_MASK)); - - GlobalCommands_insert("UpFloor", FreeCaller(), Accelerator(GDK_Prior)); - GlobalCommands_insert("DownFloor", FreeCaller(), Accelerator(GDK_Next)); - - GlobalToggles_insert("ToggleCamera", ToggleShown::ToggleCaller(g_camera_shown), ToggleItem::AddCallbackCaller(g_camera_shown.m_item), Accelerator('C', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("LookThroughSelected", FreeCaller()); - GlobalCommands_insert("LookThroughCamera", FreeCaller()); - - if(g_pGameDescription->mGameType == "doom3") - { - GlobalCommands_insert("TogglePreview", FreeCaller(), Accelerator(GDK_F3)); - } - - GlobalCommands_insert("CameraSpeedInc", FreeCaller(), Accelerator(GDK_KP_Add, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("CameraSpeedDec", FreeCaller(), Accelerator(GDK_KP_Subtract, (GdkModifierType)GDK_SHIFT_MASK)); - - GlobalShortcuts_insert("CameraForward", Accelerator(GDK_Up)); - GlobalShortcuts_insert("CameraBack", Accelerator(GDK_Down)); - GlobalShortcuts_insert("CameraLeft", Accelerator(GDK_Left)); - GlobalShortcuts_insert("CameraRight", Accelerator(GDK_Right)); - GlobalShortcuts_insert("CameraStrafeRight", Accelerator(GDK_period)); - GlobalShortcuts_insert("CameraStrafeLeft", Accelerator(GDK_comma)); - - GlobalShortcuts_insert("CameraUp", Accelerator('D')); - GlobalShortcuts_insert("CameraDown", Accelerator('C')); - GlobalShortcuts_insert("CameraAngleUp", Accelerator('A')); - GlobalShortcuts_insert("CameraAngleDown", Accelerator('Z')); - - GlobalShortcuts_insert("CameraFreeMoveForward", Accelerator(GDK_Up)); - GlobalShortcuts_insert("CameraFreeMoveBack", Accelerator(GDK_Down)); - GlobalShortcuts_insert("CameraFreeMoveLeft", Accelerator(GDK_Left)); - GlobalShortcuts_insert("CameraFreeMoveRight", Accelerator(GDK_Right)); - - GlobalToggles_insert("ShowStats", ShowStatsToggleCaller(), ToggleItem::AddCallbackCaller(g_show_stats)); - - GlobalPreferenceSystem().registerPreference("ShowStats", BoolImportStringCaller(g_camwindow_globals_private.m_showStats), BoolExportStringCaller(g_camwindow_globals_private.m_showStats)); - GlobalPreferenceSystem().registerPreference("MoveSpeed", IntImportStringCaller(g_camwindow_globals_private.m_nMoveSpeed), IntExportStringCaller(g_camwindow_globals_private.m_nMoveSpeed)); - GlobalPreferenceSystem().registerPreference("CamLinkSpeed", BoolImportStringCaller(g_camwindow_globals_private.m_bCamLinkSpeed), BoolExportStringCaller(g_camwindow_globals_private.m_bCamLinkSpeed)); - GlobalPreferenceSystem().registerPreference("AngleSpeed", IntImportStringCaller(g_camwindow_globals_private.m_nAngleSpeed), IntExportStringCaller(g_camwindow_globals_private.m_nAngleSpeed)); - GlobalPreferenceSystem().registerPreference("CamInverseMouse", BoolImportStringCaller(g_camwindow_globals_private.m_bCamInverseMouse), BoolExportStringCaller(g_camwindow_globals_private.m_bCamInverseMouse)); - GlobalPreferenceSystem().registerPreference("CamDiscrete", makeBoolStringImportCallback(CamWndMoveDiscreteImportCaller()), BoolExportStringCaller(g_camwindow_globals_private.m_bCamDiscrete)); - GlobalPreferenceSystem().registerPreference("CubicClipping", BoolImportStringCaller(g_camwindow_globals_private.m_bCubicClipping), BoolExportStringCaller(g_camwindow_globals_private.m_bCubicClipping)); - GlobalPreferenceSystem().registerPreference("CubicScale", IntImportStringCaller(g_camwindow_globals.m_nCubicScale), IntExportStringCaller(g_camwindow_globals.m_nCubicScale)); - GlobalPreferenceSystem().registerPreference("SI_Colors4", Vector3ImportStringCaller(g_camwindow_globals.color_cameraback), Vector3ExportStringCaller(g_camwindow_globals.color_cameraback)); - GlobalPreferenceSystem().registerPreference("SI_Colors12", Vector3ImportStringCaller(g_camwindow_globals.color_selbrushes3d), Vector3ExportStringCaller(g_camwindow_globals.color_selbrushes3d)); - GlobalPreferenceSystem().registerPreference("CameraRenderMode", makeIntStringImportCallback(RenderModeImportCaller()), makeIntStringExportCallback(RenderModeExportCaller())); - GlobalPreferenceSystem().registerPreference("StrafeMode", IntImportStringCaller(g_camwindow_globals_private.m_nStrafeMode), IntExportStringCaller(g_camwindow_globals_private.m_nStrafeMode)); - - CamWnd_constructStatic(); - - Camera_registerPreferencesPage(); -} -void CamWnd_Destroy() -{ - CamWnd_destroyStatic(); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/camwindow.h b/misc/mediasource/extra/netradiant-src/radiant/camwindow.h deleted file mode 100644 index 2c8c59f7..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/camwindow.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_CAMWINDOW_H) -#define INCLUDED_CAMWINDOW_H - -#include "math/vector.h" -#include "signal/signalfwd.h" - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; - -class CamWnd; -CamWnd* NewCamWnd(); -void DeleteCamWnd(CamWnd* camwnd); - -void AddCameraMovedCallback(const SignalHandler& handler); - -void CamWnd_Update(CamWnd& camwnd); - -GtkWidget* CamWnd_getWidget(CamWnd& camwnd); -void CamWnd_setParent(CamWnd& camwnd, GtkWindow* parent); - -void GlobalCamera_setCamWnd(CamWnd& camwnd); - -typedef struct _GtkMenu GtkMenu; -void fill_view_camera_menu(GtkMenu* menu); -typedef struct _GtkToolbar GtkToolbar; -void CamWnd_constructToolbar(GtkToolbar* toolbar); -void CamWnd_registerShortcuts(); - -void GlobalCamera_Benchmark(); - -const Vector3& Camera_getOrigin(CamWnd& camwnd); -void Camera_setOrigin(CamWnd& camwnd, const Vector3& origin); - -enum -{ - CAMERA_PITCH = 0, // up / down - CAMERA_YAW = 1, // left / right - CAMERA_ROLL = 2, // fall over -}; - -const Vector3& Camera_getAngles(CamWnd& camwnd); -void Camera_setAngles(CamWnd& camwnd, const Vector3& angles); - - -struct camwindow_globals_t -{ - Vector3 color_cameraback; - Vector3 color_selbrushes3d; - - int m_nCubicScale; - - camwindow_globals_t() : - color_cameraback(0.25f, 0.25f, 0.25f), - color_selbrushes3d(1.0f, 0.f, 0.f), - m_nCubicScale(13) - { - } - -}; - -extern camwindow_globals_t g_camwindow_globals; - -void CamWnd_Construct(); -void CamWnd_Destroy(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/clippertool.cpp b/misc/mediasource/extra/netradiant-src/radiant/clippertool.cpp deleted file mode 100644 index a49b7246..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/clippertool.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "clippertool.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/clippertool.h b/misc/mediasource/extra/netradiant-src/radiant/clippertool.h deleted file mode 100644 index 6101f1a6..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/clippertool.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_CLIPPERTOOL_H) -#define INCLUDED_CLIPPERTOOL_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/commands.cpp b/misc/mediasource/extra/netradiant-src/radiant/commands.cpp deleted file mode 100644 index 31720686..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/commands.cpp +++ /dev/null @@ -1,644 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "commands.h" - -#include "debugging/debugging.h" -#include "warnings.h" - -#include -#include "string/string.h" -#include "versionlib.h" -#include "gtkutil/accelerator.h" -#include "gtkutil/messagebox.h" -#include -#include -#include "gtkmisc.h" - -typedef std::pair ShortcutValue; // accelerator, isRegistered -typedef std::map Shortcuts; - -void Shortcuts_foreach(Shortcuts& shortcuts, CommandVisitor& visitor) -{ - for(Shortcuts::iterator i = shortcuts.begin(); i != shortcuts.end(); ++i) - { - visitor.visit((*i).first.c_str(), (*i).second.first); - } -} - -Shortcuts g_shortcuts; - -const Accelerator& GlobalShortcuts_insert(const char* name, const Accelerator& accelerator) -{ - return (*g_shortcuts.insert(Shortcuts::value_type(name, ShortcutValue(accelerator, false))).first).second.first; -} - -void GlobalShortcuts_foreach(CommandVisitor& visitor) -{ - Shortcuts_foreach(g_shortcuts, visitor); -} - -void GlobalShortcuts_register(const char* name, int type) -{ - Shortcuts::iterator i = g_shortcuts.find(name); - if(i != g_shortcuts.end()) - { - (*i).second.second = type; - } -} - -void GlobalShortcuts_reportUnregistered() -{ - for(Shortcuts::iterator i = g_shortcuts.begin(); i != g_shortcuts.end(); ++i) - { - if((*i).second.first.key != 0 && !(*i).second.second) - { - globalOutputStream() << "shortcut not registered: " << (*i).first.c_str() << "\n"; - } - } -} - -typedef std::map Commands; - -Commands g_commands; - -void GlobalCommands_insert(const char* name, const Callback& callback, const Accelerator& accelerator) -{ - bool added = g_commands.insert(Commands::value_type(name, Command(callback, GlobalShortcuts_insert(name, accelerator)))).second; - ASSERT_MESSAGE(added, "command already registered: " << makeQuoted(name)); -} - -const Command& GlobalCommands_find(const char* command) -{ - Commands::iterator i = g_commands.find(command); - ASSERT_MESSAGE(i != g_commands.end(), "failed to lookup command " << makeQuoted(command)); - return (*i).second; -} - -typedef std::map Toggles; - - -Toggles g_toggles; - -void GlobalToggles_insert(const char* name, const Callback& callback, const BoolExportCallback& exportCallback, const Accelerator& accelerator) -{ - bool added = g_toggles.insert(Toggles::value_type(name, Toggle(callback, GlobalShortcuts_insert(name, accelerator), exportCallback))).second; - ASSERT_MESSAGE(added, "toggle already registered: " << makeQuoted(name)); -} -const Toggle& GlobalToggles_find(const char* name) -{ - Toggles::iterator i = g_toggles.find(name); - ASSERT_MESSAGE(i != g_toggles.end(), "failed to lookup toggle " << makeQuoted(name)); - return (*i).second; -} - -typedef std::map KeyEvents; - - -KeyEvents g_keyEvents; - -void GlobalKeyEvents_insert(const char* name, const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp) -{ - bool added = g_keyEvents.insert(KeyEvents::value_type(name, KeyEvent(GlobalShortcuts_insert(name, accelerator), keyDown, keyUp))).second; - ASSERT_MESSAGE(added, "command already registered: " << makeQuoted(name)); -} -const KeyEvent& GlobalKeyEvents_find(const char* name) -{ - KeyEvents::iterator i = g_keyEvents.find(name); - ASSERT_MESSAGE(i != g_keyEvents.end(), "failed to lookup keyEvent " << makeQuoted(name)); - return (*i).second; -} - - -void disconnect_accelerator(const char *name) -{ - Shortcuts::iterator i = g_shortcuts.find(name); - if(i != g_shortcuts.end()) - { - switch((*i).second.second) - { - case 1: - // command - command_disconnect_accelerator(name); - break; - case 2: - // toggle - toggle_remove_accelerator(name); - break; - } - } -} - -void connect_accelerator(const char *name) -{ - Shortcuts::iterator i = g_shortcuts.find(name); - if(i != g_shortcuts.end()) - { - switch((*i).second.second) - { - case 1: - // command - command_connect_accelerator(name); - break; - case 2: - // toggle - toggle_add_accelerator(name); - break; - } - } -} - - -#include - -#include -#include -#include -#include -#include - -#include "gtkutil/dialog.h" -#include "mainframe.h" - -#include "stream/textfilestream.h" -#include "stream/stringstream.h" - - -struct command_list_dialog_t : public ModalDialog -{ - command_list_dialog_t() - : m_close_button(*this, eIDCANCEL), m_list(NULL), m_command_iter(), m_model(NULL), m_waiting_for_key(false) - { - } - ModalDialogButton m_close_button; - - GtkTreeView *m_list; - GtkTreeIter m_command_iter; - GtkTreeModel *m_model; - bool m_waiting_for_key; -}; - -void accelerator_clear_button_clicked(GtkButton *btn, gpointer dialogptr) -{ - command_list_dialog_t &dialog = * (command_list_dialog_t *) dialogptr; - - if(dialog.m_waiting_for_key) - { - // just unhighlight, user wanted to cancel - dialog.m_waiting_for_key = false; - gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 2, false, -1); - gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), true); - dialog.m_model = NULL; - return; - } - - GtkTreeSelection *sel = gtk_tree_view_get_selection(dialog.m_list); - GtkTreeModel *model; - GtkTreeIter iter; - if(!gtk_tree_selection_get_selected(sel, &model, &iter)) - return; - - GValue val; - memset(&val, 0, sizeof(val)); - gtk_tree_model_get_value(GTK_TREE_MODEL(model), &iter, 0, &val); - const char *commandName = g_value_get_string(&val);; - - // clear the ACTUAL accelerator too! - disconnect_accelerator(commandName); - - Shortcuts::iterator thisShortcutIterator = g_shortcuts.find(commandName); - if(thisShortcutIterator == g_shortcuts.end()) - return; - thisShortcutIterator->second.first = accelerator_null(); - - gtk_list_store_set(GTK_LIST_STORE(model), &iter, 1, "", -1); - - g_value_unset(&val); -} - -void accelerator_edit_button_clicked(GtkButton *btn, gpointer dialogptr) -{ - command_list_dialog_t &dialog = * (command_list_dialog_t *) dialogptr; - - // 1. find selected row - GtkTreeSelection *sel = gtk_tree_view_get_selection(dialog.m_list); - GtkTreeModel *model; - GtkTreeIter iter; - if(!gtk_tree_selection_get_selected(sel, &model, &iter)) - return; - dialog.m_command_iter = iter; - dialog.m_model = model; - - // 2. disallow changing the row - //gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), false); - - // 3. highlight the row - gtk_list_store_set(GTK_LIST_STORE(model), &iter, 2, true, -1); - - // 4. grab keyboard focus - dialog.m_waiting_for_key = true; -} - -gboolean accelerator_window_key_press(GtkWidget *widget, GdkEventKey *event, gpointer dialogptr) -{ - command_list_dialog_t &dialog = * (command_list_dialog_t *) dialogptr; - - if(!dialog.m_waiting_for_key) - return false; - -#if 0 - if(event->is_modifier) - return false; -#else - switch(event->keyval) - { - case GDK_Shift_L: - case GDK_Shift_R: - case GDK_Control_L: - case GDK_Control_R: - case GDK_Caps_Lock: - case GDK_Shift_Lock: - case GDK_Meta_L: - case GDK_Meta_R: - case GDK_Alt_L: - case GDK_Alt_R: - case GDK_Super_L: - case GDK_Super_R: - case GDK_Hyper_L: - case GDK_Hyper_R: - return false; - } -#endif - - dialog.m_waiting_for_key = false; - - // 7. find the name of the accelerator - GValue val; - memset(&val, 0, sizeof(val)); - gtk_tree_model_get_value(GTK_TREE_MODEL(dialog.m_model), &dialog.m_command_iter, 0, &val); - const char *commandName = g_value_get_string(&val);; - Shortcuts::iterator thisShortcutIterator = g_shortcuts.find(commandName); - if(thisShortcutIterator == g_shortcuts.end()) - { - gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 2, false, -1); - gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), true); - return true; - } - - // 8. build an Accelerator - Accelerator newAccel(event->keyval, (GdkModifierType) event->state); - - // 8. verify the key is still free, show a dialog to ask what to do if not - class VerifyAcceleratorNotTaken : public CommandVisitor - { - const char *commandName; - const Accelerator &newAccel; - GtkWidget *widget; - GtkTreeModel *model; - public: - bool allow; - VerifyAcceleratorNotTaken(const char *name, const Accelerator &accelerator, GtkWidget *w, GtkTreeModel *m) : commandName(name), newAccel(accelerator), widget(w), model(m), allow(true) - { - } - void visit(const char* name, Accelerator& accelerator) - { - if(!strcmp(name, commandName)) - return; - if(!allow) - return; - if(accelerator.key == 0) - return; - if(accelerator == newAccel) - { - StringOutputStream msg; - msg << "The command " << name << " is already assigned to the key " << accelerator << ".\n\n" - << "Do you want to unassign " << name << " first?"; - EMessageBoxReturn r = gtk_MessageBox (widget, msg.c_str(), "Key already used", eMB_YESNOCANCEL); - if(r == eIDYES) - { - // clear the ACTUAL accelerator too! - disconnect_accelerator(name); - // delete the modifier - accelerator = accelerator_null(); - // empty the cell of the key binds dialog - GtkTreeIter i; - if(gtk_tree_model_get_iter_first(GTK_TREE_MODEL(model), &i)) - { - for(;;) - { - GValue val; - memset(&val, 0, sizeof(val)); - gtk_tree_model_get_value(GTK_TREE_MODEL(model), &i, 0, &val); - const char *thisName = g_value_get_string(&val);; - if(!strcmp(thisName, name)) - gtk_list_store_set(GTK_LIST_STORE(model), &i, 1, "", -1); - g_value_unset(&val); - if(!gtk_tree_model_iter_next(GTK_TREE_MODEL(model), &i)) - break; - } - } - } - else if(r == eIDCANCEL) - { - // aborted - allow = false; - } - } - } - } verify_visitor(commandName, newAccel, widget, dialog.m_model); - GlobalShortcuts_foreach(verify_visitor); - - gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 2, false, -1); - gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), true); - - if(verify_visitor.allow) - { - // clear the ACTUAL accelerator first - disconnect_accelerator(commandName); - - thisShortcutIterator->second.first = newAccel; - - // write into the cell - StringOutputStream modifiers; - modifiers << newAccel; - gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 1, modifiers.c_str(), -1); - - // set the ACTUAL accelerator too! - connect_accelerator(commandName); - } - - g_value_unset(&val); - - dialog.m_model = NULL; - - return true; -} - -/* - GtkTreeIter row; - GValue val; - if(!model) {g_error("Unable to get model from cell renderer");} - gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(model), &row, path_string); - - gtk_tree_model_get_value(GTK_TREE_MODEL(model), &row, 0, &val); - const char *name = g_value_get_string(&val); - Shortcuts::iterator i = g_shortcuts.find(name); - if(i != g_shortcuts.end()) - { - accelerator_parse(i->second.first, new_text); - StringOutputStream modifiers; - modifiers << i->second.first; - gtk_list_store_set(GTK_LIST_STORE(model), &row, 1, modifiers.c_str(), -1); - } -}; -*/ - -void DoCommandListDlg() -{ - command_list_dialog_t dialog; - - GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Mapped Commands", dialog, -1, 400); - g_signal_connect(G_OBJECT(window), "key-press-event", (GCallback) accelerator_window_key_press, &dialog); - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel); - - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - - { - GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(scr), TRUE, TRUE, 0); - - { - GtkListStore* store = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_INT); - - GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); - dialog.m_list = GTK_TREE_VIEW(view); - - gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), false); // annoying - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Command", renderer, "text", 0, "weight-set", 2, "weight", 3, NULL); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - } - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Key", renderer, "text", 1, "weight-set", 2, "weight", 3, NULL); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - } - - gtk_widget_show(view); - gtk_container_add(GTK_CONTAINER (scr), view); - - { - // Initialize dialog - StringOutputStream path(256); - path << SettingsPath_get() << "commandlist.txt"; - globalOutputStream() << "Writing the command list to " << path.c_str() << "\n"; - class BuildCommandList : public CommandVisitor - { - TextFileOutputStream m_commandList; - GtkListStore* m_store; - public: - BuildCommandList(const char* filename, GtkListStore* store) : m_commandList(filename), m_store(store) - { - } - void visit(const char* name, Accelerator& accelerator) - { - StringOutputStream modifiers; - modifiers << accelerator; - - { - GtkTreeIter iter; - gtk_list_store_append(m_store, &iter); - gtk_list_store_set(m_store, &iter, 0, name, 1, modifiers.c_str(), 2, false, 3, 800, -1); - } - - if(!m_commandList.failed()) - { - int l = strlen(name); - m_commandList << name; - while(l++ < 25) - m_commandList << ' '; - m_commandList << modifiers.c_str() << '\n'; - } - } - } visitor(path.c_str(), store); - - GlobalShortcuts_foreach(visitor); - } - - g_object_unref(G_OBJECT(store)); - } - } - - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - GtkButton* editbutton = create_dialog_button("Edit", (GCallback) accelerator_edit_button_clicked, &dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(editbutton), FALSE, FALSE, 0); - - GtkButton* clearbutton = create_dialog_button("Clear", (GCallback) accelerator_clear_button_clicked, &dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(clearbutton), FALSE, FALSE, 0); - - GtkWidget *spacer = gtk_image_new(); - gtk_widget_show(spacer); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(spacer), TRUE, TRUE, 0); - - GtkButton* button = create_modal_dialog_button("Close", dialog.m_close_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_grab_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - } - - modal_dialog_show(window, dialog); - gtk_widget_destroy(GTK_WIDGET(window)); -} - -#include "profile/profile.h" - -const char* const COMMANDS_VERSION = "1.0-gtk-accelnames"; - -void SaveCommandMap(const char* path) -{ - StringOutputStream strINI(256); - strINI << path << "shortcuts.ini"; - - TextFileOutputStream file(strINI.c_str()); - if(!file.failed()) - { - file << "[Version]\n"; - file << "number=" << COMMANDS_VERSION << "\n"; - file << "\n"; - file << "[Commands]\n"; - class WriteCommandMap : public CommandVisitor - { - TextFileOutputStream& m_file; - public: - WriteCommandMap(TextFileOutputStream& file) : m_file(file) - { - } - void visit(const char* name, Accelerator& accelerator) - { - m_file << name << "="; - - const char* key = gtk_accelerator_name(accelerator.key, accelerator.modifiers); - m_file << key; - m_file << "\n"; - } - } visitor(file); - GlobalShortcuts_foreach(visitor); - } -} - -const char* stringrange_find(const char* first, const char* last, char c) -{ - const char* p = strchr(first, '+'); - if(p == 0) - { - return last; - } - return p; -} - -class ReadCommandMap : public CommandVisitor -{ - const char* m_filename; - std::size_t m_count; -public: - ReadCommandMap(const char* filename) : m_filename(filename), m_count(0) - { - } - void visit(const char* name, Accelerator& accelerator) - { - char value[1024]; - if (read_var(m_filename, "Commands", name, value )) - { - if(string_empty(value)) - { - accelerator.key = 0; - accelerator.modifiers = (GdkModifierType)0; - return; - } - - gtk_accelerator_parse(value, &accelerator.key, &accelerator.modifiers); - accelerator = accelerator; // fix modifiers - - if(accelerator.key != 0) - { - ++m_count; - } - else - { - globalOutputStream() << "WARNING: failed to parse user command " << makeQuoted(name) << ": unknown key " << makeQuoted(value) << "\n"; - } - } - } - std::size_t count() const - { - return m_count; - } -}; - -void LoadCommandMap(const char* path) -{ - StringOutputStream strINI(256); - strINI << path << "shortcuts.ini"; - - FILE* f = fopen (strINI.c_str(), "r"); - if (f != 0) - { - fclose(f); - globalOutputStream() << "loading custom shortcuts list from " << makeQuoted(strINI.c_str()) << "\n"; - - Version version = version_parse(COMMANDS_VERSION); - Version dataVersion = { 0, 0 }; - - { - char value[1024]; - if(read_var(strINI.c_str(), "Version", "number", value)) - { - dataVersion = version_parse(value); - } - } - - if(version_compatible(version, dataVersion)) - { - globalOutputStream() << "commands import: data version " << dataVersion << " is compatible with code version " << version << "\n"; - ReadCommandMap visitor(strINI.c_str()); - GlobalShortcuts_foreach(visitor); - globalOutputStream() << "parsed " << Unsigned(visitor.count()) << " custom shortcuts\n"; - } - else - { - globalOutputStream() << "commands import: data version " << dataVersion << " is not compatible with code version " << version << "\n"; - } - } - else - { - globalOutputStream() << "failed to load custom shortcuts from " << makeQuoted(strINI.c_str()) << "\n"; - } -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/commands.h b/misc/mediasource/extra/netradiant-src/radiant/commands.h deleted file mode 100644 index 677f0854..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/commands.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_COMMANDS_H) -#define INCLUDED_COMMANDS_H - -#include "gtkutil/accelerator.h" - - -const Accelerator& GlobalShortcuts_insert(const char* name, const Accelerator& accelerator); -void GlobalShortcuts_register(const char* name, int type); // 1 = command, 2 = toggle -void GlobalShortcuts_reportUnregistered(); - -class CommandVisitor -{ -public: - virtual void visit(const char* name, Accelerator& accelerator) = 0; -}; - -void GlobalCommands_insert(const char* name, const Callback& callback, const Accelerator& accelerator = accelerator_null()); -const Command& GlobalCommands_find(const char* name); - -void GlobalToggles_insert(const char* name, const Callback& callback, const BoolExportCallback& exportCallback, const Accelerator& accelerator = accelerator_null()); -const Toggle& GlobalToggles_find(const char* name); - -void GlobalKeyEvents_insert(const char* name, const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp); -const KeyEvent& GlobalKeyEvents_find(const char* name); - - -void DoCommandListDlg(); - -void LoadCommandMap(const char* path); -void SaveCommandMap(const char* path); - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/console.cpp b/misc/mediasource/extra/netradiant-src/radiant/console.cpp deleted file mode 100644 index cff963f2..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/console.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "console.h" - -#include -#include -#include -#include -#include - -#include "gtkutil/accelerator.h" -#include "gtkutil/messagebox.h" -#include "gtkutil/container.h" -#include "gtkutil/menu.h" -#include "gtkutil/nonmodal.h" -#include "stream/stringstream.h" -#include "convert.h" - -#include "version.h" -#include "aboutmsg.h" -#include "gtkmisc.h" -#include "mainframe.h" - -// handle to the console log file -namespace -{ - FILE* g_hLogFile; -} - -bool g_Console_enableLogging = false; - -// called whenever we need to open/close/check the console log file -void Sys_LogFile(bool enable) -{ - if (enable && !g_hLogFile) - { - // settings say we should be logging and we don't have a log file .. so create it - if(!SettingsPath_get()[0]) - return; // cannot open a log file yet - // open a file to log the console (if user prefs say so) - // the file handle is g_hLogFile - // the log file is erased - StringOutputStream name(256); - name << SettingsPath_get() << "radiant.log"; - g_hLogFile = fopen( name.c_str(), "w" ); - if (g_hLogFile != 0) - { - globalOutputStream() << "Started logging to " << name.c_str() << "\n"; - time_t localtime; - time(&localtime); - globalOutputStream() << "Today is: " << ctime(&localtime) - << "This is NetRadiant '" RADIANT_VERSION "' compiled " __DATE__ "\n" RADIANT_ABOUTMSG "\n"; - } - else - gtk_MessageBox (0, "Failed to create log file, check write permissions in Radiant directory.\n", - "Console logging", eMB_OK, eMB_ICONERROR ); - } - else if (!enable && g_hLogFile != 0) - { - // settings say we should not be logging but still we have an active logfile .. close it - time_t localtime; - time(&localtime); - globalOutputStream() << "Closing log file at " << ctime(&localtime) << "\n"; - fclose( g_hLogFile ); - g_hLogFile = 0; - } -} - -GtkWidget* g_console = 0; - -void console_clear() -{ - GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(g_console)); - gtk_text_buffer_set_text(buffer, "", -1); -} - -void console_populate_popup(GtkTextView* textview, GtkMenu* menu, gpointer user_data) -{ - menu_separator(menu); - - GtkWidget* item = gtk_menu_item_new_with_label ("Clear"); - g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(console_clear), 0); - gtk_widget_show (item); - container_add_widget(GTK_CONTAINER(menu), item); -} - -gboolean destroy_set_null(GtkWindow* widget, GtkWidget** p) -{ - *p = 0; - return FALSE; -} - -WidgetFocusPrinter g_consoleWidgetFocusPrinter("console"); - -GtkWidget* Console_constructWindow(GtkWindow* toplevel) -{ - GtkWidget* scr = gtk_scrolled_window_new (0, 0); - gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scr), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); - gtk_widget_show(scr); - - { - GtkWidget* text = gtk_text_view_new(); - gtk_widget_set_size_request(text, 0, -1); // allow shrinking - gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD); - gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE); - gtk_container_add(GTK_CONTAINER (scr), text); - gtk_widget_show(text); - g_console = text; - - //globalExtendedASCIICharacterSet().print(); - - widget_connect_escape_clear_focus_widget(g_console); - - //g_consoleWidgetFocusPrinter.connect(g_console); - - g_signal_connect(G_OBJECT(g_console), "populate-popup", G_CALLBACK(console_populate_popup), 0); - g_signal_connect(G_OBJECT(g_console), "destroy", G_CALLBACK(destroy_set_null), &g_console); - } - - gtk_container_set_focus_chain(GTK_CONTAINER(scr), NULL); - - return scr; -} - -class GtkTextBufferOutputStream : public TextOutputStream -{ - GtkTextBuffer* textBuffer; - GtkTextIter* iter; - GtkTextTag* tag; -public: - GtkTextBufferOutputStream(GtkTextBuffer* textBuffer, GtkTextIter* iter, GtkTextTag* tag) : textBuffer(textBuffer), iter(iter), tag(tag) - { - } - std::size_t write(const char* buffer, std::size_t length) - { - gtk_text_buffer_insert_with_tags(textBuffer, iter, buffer, gint(length), tag, 0); - return length; - } -}; - -std::size_t Sys_Print(int level, const char* buf, std::size_t length) -{ - bool contains_newline = std::find(buf, buf+length, '\n') != buf+length; - - if(level == SYS_ERR) - { - Sys_LogFile(true); - } - - if (g_hLogFile != 0) - { - fwrite(buf, 1, length, g_hLogFile); - if(contains_newline) - { - fflush(g_hLogFile); - } - } - - if (level != SYS_NOCON) - { - if (g_console != 0) - { - GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(g_console)); - - GtkTextIter iter; - gtk_text_buffer_get_end_iter(buffer, &iter); - - static GtkTextMark* end = gtk_text_buffer_create_mark(buffer, "end", &iter, FALSE); - - const GdkColor yellow = { 0, 0xb0ff, 0xb0ff, 0x0000 }; - const GdkColor red = { 0, 0xffff, 0x0000, 0x0000 }; - - static GtkTextTag* error_tag = gtk_text_buffer_create_tag (buffer, "red_foreground", "foreground-gdk", &red, 0); - static GtkTextTag* warning_tag = gtk_text_buffer_create_tag (buffer, "yellow_foreground", "foreground-gdk", &yellow, 0); - static GtkTextTag* standard_tag = gtk_text_buffer_create_tag (buffer, "black_foreground", 0); - GtkTextTag* tag; - switch (level) - { - case SYS_WRN: - tag = warning_tag; - break; - case SYS_ERR: - tag = error_tag; - break; - case SYS_STD: - case SYS_VRB: - default: - tag = standard_tag; - break; - } - - - { - GtkTextBufferOutputStream textBuffer(buffer, &iter, tag); - if(!globalCharacterSet().isUTF8()) - { - BufferedTextOutputStream buffered(textBuffer); - buffered << StringRange(buf, buf + length); - } - else - { - textBuffer << StringRange(buf, buf + length); - } - } - - // update console widget immediatly if we're doing something time-consuming - if(contains_newline) - { - gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(g_console), end); - - if(!ScreenUpdates_Enabled() && GTK_WIDGET_REALIZED(g_console)) - { - ScreenUpdates_process(); - } - } - } - } - return length; -} - - -class SysPrintOutputStream : public TextOutputStream -{ -public: - std::size_t write(const char* buffer, std::size_t length) - { - return Sys_Print(SYS_STD, buffer, length); - } -}; - -class SysPrintErrorStream : public TextOutputStream -{ -public: - std::size_t write(const char* buffer, std::size_t length) - { - return Sys_Print(SYS_ERR, buffer, length); - } -}; - -SysPrintOutputStream g_outputStream; - -TextOutputStream& getSysPrintOutputStream() -{ - return g_outputStream; -} - -SysPrintErrorStream g_errorStream; - -TextOutputStream& getSysPrintErrorStream() -{ - return g_errorStream; -} - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/console.h b/misc/mediasource/extra/netradiant-src/radiant/console.h deleted file mode 100644 index 4e79782e..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/console.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_CONSOLE_H) -#define INCLUDED_CONSOLE_H - -#include - -#define SYS_VRB 0 ///< verbose support (on/off) -#define SYS_STD 1 ///< standard print level - this is the default -#define SYS_WRN 2 ///< warnings -#define SYS_ERR 3 ///< error -#define SYS_NOCON 4 ///< no console, only print to the file (useful whenever Sys_Printf and output IS the problem) - -std::size_t Sys_Print(int level, const char* buf, std::size_t length); -class TextOutputStream; -TextOutputStream& getSysPrintOutputStream(); -TextOutputStream& getSysPrintErrorStream(); - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; -GtkWidget* Console_constructWindow(GtkWindow* toplevel); - -// will open/close the log file based on the parameter -void Sys_LogFile(bool enable); -extern bool g_Console_enableLogging; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/csg.cpp b/misc/mediasource/extra/netradiant-src/radiant/csg.cpp deleted file mode 100644 index f30fb980..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/csg.cpp +++ /dev/null @@ -1,692 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "csg.h" - -#include "debugging/debugging.h" - -#include - -#include "map.h" -#include "brushmanip.h" -#include "brushnode.h" -#include "grid.h" - -void Face_makeBrush(Face& face, const Brush& brush, brush_vector_t& out, float offset) -{ - if(face.contributes()) - { - out.push_back(new Brush(brush)); - Face* newFace = out.back()->addFace(face); - if(newFace != 0) - { - newFace->flipWinding(); - newFace->getPlane().offset(offset); - newFace->planeChanged(); - } - } -} - -class FaceMakeBrush -{ - const Brush& brush; - brush_vector_t& out; - float offset; -public: - FaceMakeBrush(const Brush& brush, brush_vector_t& out, float offset) - : brush(brush), out(out), offset(offset) - { - } - void operator()(Face& face) const - { - Face_makeBrush(face, brush, out, offset); - } -}; - -void Brush_makeHollow(const Brush& brush, brush_vector_t& out, float offset) -{ - Brush_forEachFace(brush, FaceMakeBrush(brush, out, offset)); -} - -class BrushHollowSelectedWalker : public scene::Graph::Walker -{ - float m_offset; -public: - BrushHollowSelectedWalker(float offset) - : m_offset(offset) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Brush* brush = Node_getBrush(path.top()); - if(brush != 0 - && Instance_getSelectable(instance)->isSelected() - && path.size() > 1) - { - brush_vector_t out; - Brush_makeHollow(*brush, out, m_offset); - for(brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i) - { - (*i)->removeEmptyFaces(); - NodeSmartReference node((new BrushNode())->node()); - Node_getBrush(node)->copy(*(*i)); - delete (*i); - Node_getTraversable(path.parent())->insert(node); - } - } - } - return true; - } -}; - -typedef std::list brushlist_t; - -class BrushGatherSelected : public scene::Graph::Walker -{ - brush_vector_t& m_brushlist; -public: - BrushGatherSelected(brush_vector_t& brushlist) - : m_brushlist(brushlist) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Brush* brush = Node_getBrush(path.top()); - if(brush != 0 - && Instance_getSelectable(instance)->isSelected()) - { - m_brushlist.push_back(brush); - } - } - return true; - } -}; - -class BrushDeleteSelected : public scene::Graph::Walker -{ -public: - bool pre(const scene::Path& path, scene::Instance& instance) const - { - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Brush* brush = Node_getBrush(path.top()); - if(brush != 0 - && Instance_getSelectable(instance)->isSelected() - && path.size() > 1) - { - Path_deleteTop(path); - } - } - } -}; - -void Scene_BrushMakeHollow_Selected(scene::Graph& graph) -{ - GlobalSceneGraph().traverse(BrushHollowSelectedWalker(GetGridSize())); - GlobalSceneGraph().traverse(BrushDeleteSelected()); -} - -/* -============= -CSG_MakeHollow -============= -*/ - -void CSG_MakeHollow (void) -{ - UndoableCommand undo("brushHollow"); - - Scene_BrushMakeHollow_Selected(GlobalSceneGraph()); - - SceneChangeNotify(); -} - -template -class RemoveReference -{ -public: - typedef Type type; -}; - -template -class RemoveReference -{ -public: - typedef Type type; -}; - -template -class Dereference -{ - const Functor& functor; -public: - typedef typename RemoveReference::type* first_argument_type; - typedef typename Functor::result_type result_type; - Dereference(const Functor& functor) : functor(functor) - { - } - result_type operator()(first_argument_type firstArgument) const - { - return functor(*firstArgument); - } -}; - -template -inline Dereference makeDereference(const Functor& functor) -{ - return Dereference(functor); -} - -typedef Face* FacePointer; -const FacePointer c_nullFacePointer = 0; - -template -Face* Brush_findIf(const Brush& brush, const Predicate& predicate) -{ - Brush::const_iterator i = std::find_if(brush.begin(), brush.end(), makeDereference(predicate)); - return i == brush.end() ? c_nullFacePointer : *i; // uses c_nullFacePointer instead of 0 because otherwise gcc 4.1 attempts conversion to int -} - -template -class BindArguments1 -{ - typedef typename Caller::second_argument_type FirstBound; - FirstBound firstBound; -public: - typedef typename Caller::result_type result_type; - typedef typename Caller::first_argument_type first_argument_type; - BindArguments1(FirstBound firstBound) - : firstBound(firstBound) - { - } - result_type operator()(first_argument_type firstArgument) const - { - return Caller::call(firstArgument, firstBound); - } -}; - -template -class BindArguments2 -{ - typedef typename Caller::second_argument_type FirstBound; - typedef typename Caller::third_argument_type SecondBound; - FirstBound firstBound; - SecondBound secondBound; -public: - typedef typename Caller::result_type result_type; - typedef typename Caller::first_argument_type first_argument_type; - BindArguments2(FirstBound firstBound, SecondBound secondBound) - : firstBound(firstBound), secondBound(secondBound) - { - } - result_type operator()(first_argument_type firstArgument) const - { - return Caller::call(firstArgument, firstBound, secondBound); - } -}; - -template -BindArguments2 bindArguments(const Caller& caller, FirstBound firstBound, SecondBound secondBound) -{ - return BindArguments2(firstBound, secondBound); -} - -inline bool Face_testPlane(const Face& face, const Plane3& plane, bool flipped) -{ - return face.contributes() && !Winding_TestPlane(face.getWinding(), plane, flipped); -} -typedef Function3 FaceTestPlane; - - - -/// \brief Returns true if -/// \li !flipped && brush is BACK or ON -/// \li flipped && brush is FRONT or ON -bool Brush_testPlane(const Brush& brush, const Plane3& plane, bool flipped) -{ - brush.evaluateBRep(); -#if 1 - for(Brush::const_iterator i(brush.begin()); i != brush.end(); ++i) - { - if(Face_testPlane(*(*i), plane, flipped)) - { - return false; - } - } - return true; -#else - return Brush_findIf(brush, bindArguments(FaceTestPlane(), makeReference(plane), flipped)) == 0; -#endif -} - -brushsplit_t Brush_classifyPlane(const Brush& brush, const Plane3& plane) -{ - brush.evaluateBRep(); - brushsplit_t split; - for(Brush::const_iterator i(brush.begin()); i != brush.end(); ++i) - { - if((*i)->contributes()) - { - split += Winding_ClassifyPlane((*i)->getWinding(), plane); - } - } - return split; -} - -bool Brush_subtract(const Brush& brush, const Brush& other, brush_vector_t& ret_fragments) -{ - if(aabb_intersects_aabb(brush.localAABB(), other.localAABB())) - { - brush_vector_t fragments; - fragments.reserve(other.size()); - Brush back(brush); - - for(Brush::const_iterator i(other.begin()); i != other.end(); ++i) - { - if((*i)->contributes()) - { - brushsplit_t split = Brush_classifyPlane(back, (*i)->plane3()); - if(split.counts[ePlaneFront] != 0 - && split.counts[ePlaneBack] != 0) - { - fragments.push_back(new Brush(back)); - Face* newFace = fragments.back()->addFace(*(*i)); - if(newFace != 0) - { - newFace->flipWinding(); - } - back.addFace(*(*i)); - } - else if(split.counts[ePlaneBack] == 0) - { - for(brush_vector_t::iterator i = fragments.begin(); i != fragments.end(); ++i) - { - delete(*i); - } - return false; - } - } - } - ret_fragments.insert(ret_fragments.end(), fragments.begin(), fragments.end()); - return true; - } - return false; -} - -class SubtractBrushesFromUnselected : public scene::Graph::Walker -{ - const brush_vector_t& m_brushlist; - std::size_t& m_before; - std::size_t& m_after; -public: - SubtractBrushesFromUnselected(const brush_vector_t& brushlist, std::size_t& before, std::size_t& after) - : m_brushlist(brushlist), m_before(before), m_after(after) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Brush* brush = Node_getBrush(path.top()); - if(brush != 0 - && !Instance_getSelectable(instance)->isSelected()) - { - brush_vector_t buffer[2]; - bool swap = false; - Brush* original = new Brush(*brush); - buffer[static_cast(swap)].push_back(original); - - { - for(brush_vector_t::const_iterator i(m_brushlist.begin()); i != m_brushlist.end(); ++i) - { - for(brush_vector_t::iterator j(buffer[static_cast(swap)].begin()); j != buffer[static_cast(swap)].end(); ++j) - { - if(Brush_subtract(*(*j), *(*i), buffer[static_cast(!swap)])) - { - delete (*j); - } - else - { - buffer[static_cast(!swap)].push_back((*j)); - } - } - buffer[static_cast(swap)].clear(); - swap = !swap; - } - } - - brush_vector_t& out = buffer[static_cast(swap)]; - - if(out.size() == 1 && out.back() == original) - { - delete original; - } - else - { - ++m_before; - for(brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i) - { - ++m_after; - NodeSmartReference node((new BrushNode())->node()); - (*i)->removeEmptyFaces(); - ASSERT_MESSAGE(!(*i)->empty(), "brush left with no faces after subtract"); - Node_getBrush(node)->copy(*(*i)); - delete (*i); - Node_getTraversable(path.parent())->insert(node); - } - Path_deleteTop(path); - } - } - } - } -}; - -void CSG_Subtract() -{ - brush_vector_t selected_brushes; - GlobalSceneGraph().traverse(BrushGatherSelected(selected_brushes)); - - if (selected_brushes.empty()) - { - globalOutputStream() << "CSG Subtract: No brushes selected.\n"; - } - else - { - globalOutputStream() << "CSG Subtract: Subtracting " << Unsigned(selected_brushes.size()) << " brushes.\n"; - - UndoableCommand undo("brushSubtract"); - - // subtract selected from unselected - std::size_t before = 0; - std::size_t after = 0; - GlobalSceneGraph().traverse(SubtractBrushesFromUnselected(selected_brushes, before, after)); - globalOutputStream() << "CSG Subtract: Result: " - << Unsigned(after) << " fragment" << (after == 1 ? "" : "s") - << " from " << Unsigned(before) << " brush" << (before == 1? "" : "es") << ".\n"; - - SceneChangeNotify(); - } -} - -class BrushSplitByPlaneSelected : public scene::Graph::Walker -{ - const Vector3& m_p0; - const Vector3& m_p1; - const Vector3& m_p2; - const char* m_shader; - const TextureProjection& m_projection; - EBrushSplit m_split; -public: - BrushSplitByPlaneSelected(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection, EBrushSplit split) - : m_p0(p0), m_p1(p1), m_p2(p2), m_shader(shader), m_projection(projection), m_split(split) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Brush* brush = Node_getBrush(path.top()); - if(brush != 0 - && Instance_getSelectable(instance)->isSelected()) - { - Plane3 plane(plane3_for_points(m_p0, m_p1, m_p2)); - if(plane3_valid(plane)) - { - brushsplit_t split = Brush_classifyPlane(*brush, m_split == eFront ? plane3_flipped(plane) : plane); - if(split.counts[ePlaneBack] && split.counts[ePlaneFront]) - { - // the plane intersects this brush - if(m_split == eFrontAndBack) - { - NodeSmartReference node((new BrushNode())->node()); - Brush* fragment = Node_getBrush(node); - fragment->copy(*brush); - Face* newFace = fragment->addPlane(m_p0, m_p1, m_p2, m_shader, m_projection); - if(newFace != 0 && m_split != eFront) - { - newFace->flipWinding(); - } - fragment->removeEmptyFaces(); - ASSERT_MESSAGE(!fragment->empty(), "brush left with no faces after split"); - - Node_getTraversable(path.parent())->insert(node); - { - scene::Path fragmentPath = path; - fragmentPath.top() = makeReference(node.get()); - selectPath(fragmentPath, true); - } - } - - Face* newFace = brush->addPlane(m_p0, m_p1, m_p2, m_shader, m_projection); - if(newFace != 0 && m_split == eFront) - { - newFace->flipWinding(); - } - brush->removeEmptyFaces(); - ASSERT_MESSAGE(!brush->empty(), "brush left with no faces after split"); - } - else - // the plane does not intersect this brush - if(m_split != eFrontAndBack && split.counts[ePlaneBack] != 0) - { - // the brush is "behind" the plane - Path_deleteTop(path); - } - } - } - } - } -}; - -void Scene_BrushSplitByPlane(scene::Graph& graph, const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, EBrushSplit split) -{ - TextureProjection projection; - TexDef_Construct_Default(projection); - graph.traverse(BrushSplitByPlaneSelected(p0, p1, p2, shader, projection, split)); - SceneChangeNotify(); -} - - -class BrushInstanceSetClipPlane : public scene::Graph::Walker -{ - Plane3 m_plane; -public: - BrushInstanceSetClipPlane(const Plane3& plane) - : m_plane(plane) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - BrushInstance* brush = Instance_getBrush(instance); - if(brush != 0 - && path.top().get().visible() - && brush->isSelected()) - { - BrushInstance& brushInstance = *brush; - brushInstance.setClipPlane(m_plane); - } - return true; - } -}; - -void Scene_BrushSetClipPlane(scene::Graph& graph, const Plane3& plane) -{ - graph.traverse(BrushInstanceSetClipPlane(plane)); -} - -/* -============= -CSG_Merge -============= -*/ -bool Brush_merge(Brush& brush, const brush_vector_t& in, bool onlyshape) -{ - // gather potential outer faces - - { - typedef std::vector Faces; - Faces faces; - for(brush_vector_t::const_iterator i(in.begin()); i != in.end(); ++i) - { - (*i)->evaluateBRep(); - for(Brush::const_iterator j((*i)->begin()); j != (*i)->end(); ++j) - { - if(!(*j)->contributes()) - { - continue; - } - - const Face& face1 = *(*j); - - bool skip = false; - // test faces of all input brushes - //!\todo SPEEDUP: Flag already-skip faces and only test brushes from i+1 upwards. - for(brush_vector_t::const_iterator k(in.begin()); !skip && k != in.end(); ++k) - { - if(k != i) // don't test a brush against itself - { - for(Brush::const_iterator l((*k)->begin()); !skip && l != (*k)->end(); ++l) - { - const Face& face2 = *(*l); - - // face opposes another face - if(plane3_opposing(face1.plane3(), face2.plane3())) - { - // skip opposing planes - skip = true; - break; - } - } - } - } - - // check faces already stored - for(Faces::const_iterator m = faces.begin(); !skip && m != faces.end(); ++m) - { - const Face& face2 = *(*m); - - // face equals another face - if (plane3_equal(face1.plane3(), face2.plane3())) - { - //if the texture/shader references should be the same but are not - if (!onlyshape && !shader_equal(face1.getShader().getShader(), face2.getShader().getShader())) - { - return false; - } - // skip duplicate planes - skip = true; - break; - } - - // face1 plane intersects face2 winding or vice versa - if (Winding_PlanesConcave(face1.getWinding(), face2.getWinding(), face1.plane3(), face2.plane3())) - { - // result would not be convex - return false; - } - } - - if(!skip) - { - faces.push_back(&face1); - } - } - } - for(Faces::const_iterator i = faces.begin(); i != faces.end(); ++i) - { - if(!brush.addFace(*(*i))) - { - // result would have too many sides - return false; - } - } - } - - brush.removeEmptyFaces(); - - return true; -} - -void CSG_Merge(void) -{ - brush_vector_t selected_brushes; - - // remove selected - GlobalSceneGraph().traverse(BrushGatherSelected(selected_brushes)); - - if (selected_brushes.empty()) - { - globalOutputStream() << "CSG Merge: No brushes selected.\n"; - return; - } - - if (selected_brushes.size() < 2) - { - globalOutputStream() << "CSG Merge: At least two brushes have to be selected.\n"; - return; - } - - globalOutputStream() << "CSG Merge: Merging " << Unsigned(selected_brushes.size()) << " brushes.\n"; - - UndoableCommand undo("brushMerge"); - - scene::Path merged_path = GlobalSelectionSystem().ultimateSelected().path(); - - NodeSmartReference node((new BrushNode())->node()); - Brush* brush = Node_getBrush(node); - // if the new brush would not be convex - if(!Brush_merge(*brush, selected_brushes, true)) - { - globalOutputStream() << "CSG Merge: Failed - result would not be convex.\n"; - } - else - { - ASSERT_MESSAGE(!brush->empty(), "brush left with no faces after merge"); - - // free the original brushes - GlobalSceneGraph().traverse(BrushDeleteSelected()); - - merged_path.pop(); - Node_getTraversable(merged_path.top())->insert(node); - merged_path.push(makeReference(node.get())); - - selectPath(merged_path, true); - - globalOutputStream() << "CSG Merge: Succeeded.\n"; - SceneChangeNotify(); - } -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/csg.h b/misc/mediasource/extra/netradiant-src/radiant/csg.h deleted file mode 100644 index 867ab199..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/csg.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_CSG_H) -#define INCLUDED_CSG_H - -void CSG_MakeHollow (void); -void CSG_Subtract (void); -void CSG_Merge (void); - -namespace scene -{ - class Graph; -} -template class BasicVector3; -typedef BasicVector3 Vector3; -class Plane3; - -void Scene_BrushSetClipPlane(scene::Graph& graph, const Plane3& plane); -enum EBrushSplit -{ - eFront, - eBack, - eFrontAndBack, -}; -void Scene_BrushSplitByPlane(scene::Graph& graph, const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, EBrushSplit split); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/dialog.cpp b/misc/mediasource/extra/netradiant-src/radiant/dialog.cpp deleted file mode 100644 index d3e4dba1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/dialog.cpp +++ /dev/null @@ -1,735 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Base dialog class, provides a way to run modal dialogs and -// set/get the widget values in member variables. -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "dialog.h" - -#include "debugging/debugging.h" - - -#include "mainframe.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "stream/stringstream.h" -#include "convert.h" -#include "gtkutil/dialog.h" -#include "gtkutil/button.h" -#include "gtkutil/entry.h" -#include "gtkutil/image.h" - -#include "gtkmisc.h" - - -GtkEntry* DialogEntry_new() -{ - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_widget_set_size_request(GTK_WIDGET(entry), 64, -1); - return entry; -} - -class DialogEntryRow -{ -public: - DialogEntryRow(GtkWidget* row, GtkEntry* entry) : m_row(row), m_entry(entry) - { - } - GtkWidget* m_row; - GtkEntry* m_entry; -}; - -DialogEntryRow DialogEntryRow_new(const char* name) -{ - GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); - gtk_widget_show(alignment); - - GtkEntry* entry = DialogEntry_new(); - gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(entry)); - - return DialogEntryRow(GTK_WIDGET(DialogRow_new(name, alignment)), entry); -} - - -GtkSpinButton* DialogSpinner_new(double value, double lower, double upper, int fraction) -{ - double step = 1.0 / double(fraction); - unsigned int digits = 0; - for(;fraction > 1; fraction /= 10) - { - ++digits; - } - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(value, lower, upper, step, 10, 0)), step, digits)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); - return spin; -} - -class DialogSpinnerRow -{ -public: - DialogSpinnerRow(GtkWidget* row, GtkSpinButton* spin) : m_row(row), m_spin(spin) - { - } - GtkWidget* m_row; - GtkSpinButton* m_spin; -}; - -DialogSpinnerRow DialogSpinnerRow_new(const char* name, double value, double lower, double upper, int fraction) -{ - GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); - gtk_widget_show(alignment); - - GtkSpinButton* spin = DialogSpinner_new(value, lower, upper, fraction); - gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(spin)); - - return DialogSpinnerRow(GTK_WIDGET(DialogRow_new(name, alignment)), spin); -} - - - -template< - typename Type_, - typename Other_, - void(*Import)(Type_&, Other_), - void(*Export)(Type_&, const Callback1&) -> -class ImportExport -{ -public: - typedef Type_ Type; - typedef Other_ Other; - - typedef ReferenceCaller1 ImportCaller; - typedef ReferenceCaller1&, Export> ExportCaller; -}; - -typedef ImportExport BoolImportExport; -typedef ImportExport IntImportExport; -typedef ImportExport SizeImportExport; -typedef ImportExport FloatImportExport; -typedef ImportExport StringImportExport; - - - -void BoolToggleImport(GtkToggleButton& widget, bool value) -{ - gtk_toggle_button_set_active(&widget, value); -} -void BoolToggleExport(GtkToggleButton& widget, const BoolImportCallback& importCallback) -{ - importCallback(gtk_toggle_button_get_active(&widget) != FALSE); -} -typedef ImportExport BoolToggleImportExport; - - -void IntRadioImport(GtkRadioButton& widget, int index) -{ - radio_button_set_active(&widget, index); -} -void IntRadioExport(GtkRadioButton& widget, const IntImportCallback& importCallback) -{ - importCallback(radio_button_get_active(&widget)); -} -typedef ImportExport IntRadioImportExport; - -void TextEntryImport(GtkEntry& widget, const char* text) -{ - gtk_entry_set_text(&widget, text); -} -void TextEntryExport(GtkEntry& widget, const StringImportCallback& importCallback) -{ - importCallback(gtk_entry_get_text(&widget)); -} -typedef ImportExport TextEntryImportExport; - - -void IntEntryImport(GtkEntry& widget, int value) -{ - entry_set_int(&widget, value); -} -void IntEntryExport(GtkEntry& widget, const IntImportCallback& importCallback) -{ - importCallback(atoi(gtk_entry_get_text (&widget))); -} -typedef ImportExport IntEntryImportExport; - - -void SizeEntryImport(GtkEntry& widget, std::size_t value) -{ - entry_set_int(&widget, int(value)); -} -void SizeEntryExport(GtkEntry& widget, const SizeImportCallback& importCallback) -{ - int value = atoi(gtk_entry_get_text(&widget)); - if(value < 0) - { - value = 0; - } - importCallback(value); -} -typedef ImportExport SizeEntryImportExport; - - -void FloatEntryImport(GtkEntry& widget, float value) -{ - entry_set_float(&widget, value); -} -void FloatEntryExport(GtkEntry& widget, const FloatImportCallback& importCallback) -{ - importCallback((float)atof(gtk_entry_get_text(&widget))); -} -typedef ImportExport FloatEntryImportExport; - - -void FloatSpinnerImport(GtkSpinButton& widget, float value) -{ - gtk_spin_button_set_value(&widget, value); -} -void FloatSpinnerExport(GtkSpinButton& widget, const FloatImportCallback& importCallback) -{ - importCallback(float(gtk_spin_button_get_value_as_float(&widget))); -} -typedef ImportExport FloatSpinnerImportExport; - - -void IntSpinnerImport(GtkSpinButton& widget, int value) -{ - gtk_spin_button_set_value(&widget, value); -} -void IntSpinnerExport(GtkSpinButton& widget, const IntImportCallback& importCallback) -{ - importCallback(gtk_spin_button_get_value_as_int(&widget)); -} -typedef ImportExport IntSpinnerImportExport; - - -void IntAdjustmentImport(GtkAdjustment& widget, int value) -{ - gtk_adjustment_set_value(&widget, value); -} -void IntAdjustmentExport(GtkAdjustment& widget, const IntImportCallback& importCallback) -{ - importCallback((int)gtk_adjustment_get_value(&widget)); -} -typedef ImportExport IntAdjustmentImportExport; - - -void IntComboImport(GtkComboBox& widget, int value) -{ - gtk_combo_box_set_active(&widget, value); -} -void IntComboExport(GtkComboBox& widget, const IntImportCallback& importCallback) -{ - importCallback(gtk_combo_box_get_active(&widget)); -} -typedef ImportExport IntComboImportExport; - - -template -class CallbackDialogData : public DLG_DATA -{ -public: - typedef Callback1 ImportCallback; - typedef Callback1 ExportCallback; - -private: - ImportCallback m_importWidget; - ExportCallback m_exportWidget; - ImportCallback m_importViewer; - ExportCallback m_exportViewer; - -public: - CallbackDialogData(const ImportCallback& importWidget, const ExportCallback& exportWidget, const ImportCallback& importViewer, const ExportCallback& exportViewer) - : m_importWidget(importWidget), m_exportWidget(exportWidget), m_importViewer(importViewer), m_exportViewer(exportViewer) - { - } - void release() - { - delete this; - } - void importData() const - { - m_exportViewer(m_importWidget); - } - void exportData() const - { - m_exportWidget(m_importViewer); - } -}; - -template -class AddData -{ - DialogDataList& m_data; -public: - AddData(DialogDataList& data) : m_data(data) - { - } - void apply(typename Widget::Type& widget, typename Viewer::Type& viewer) const - { - m_data.push_back( - new CallbackDialogData( - typename Widget::ImportCaller(widget), - typename Widget::ExportCaller(widget), - typename Viewer::ImportCaller(viewer), - typename Viewer::ExportCaller(viewer) - ) - ); - } -}; - -template -class AddCustomData -{ - DialogDataList& m_data; -public: - AddCustomData(DialogDataList& data) : m_data(data) - { - } - void apply( - typename Widget::Type& widget, - const Callback1& importViewer, - const Callback1&>& exportViewer - ) const - { - m_data.push_back( - new CallbackDialogData( - typename Widget::ImportCaller(widget), - typename Widget::ExportCaller(widget), - importViewer, - exportViewer - ) - ); - } -}; - -// ============================================================================= -// Dialog class - -Dialog::Dialog() : m_window(0), m_parent(0) -{ -} - -Dialog::~Dialog() -{ - for(DialogDataList::iterator i = m_data.begin(); i != m_data.end(); ++i) - { - (*i)->release(); - } - - ASSERT_MESSAGE(m_window == 0, "dialog window not destroyed"); -} - -void Dialog::ShowDlg() -{ - ASSERT_MESSAGE(m_window != 0, "dialog was not constructed"); - importData(); - gtk_widget_show(GTK_WIDGET(m_window)); -} - -void Dialog::HideDlg() -{ - ASSERT_MESSAGE(m_window != 0, "dialog was not constructed"); - exportData(); - gtk_widget_hide(GTK_WIDGET(m_window)); -} - -static gint delete_event_callback(GtkWidget *widget, GdkEvent* event, gpointer data) -{ - reinterpret_cast(data)->HideDlg(); - reinterpret_cast(data)->EndModal(eIDCANCEL); - return TRUE; -} - -void Dialog::Create() -{ - ASSERT_MESSAGE(m_window == 0, "dialog cannot be constructed"); - - m_window = BuildDialog(); - g_signal_connect(G_OBJECT(m_window), "delete_event", G_CALLBACK(delete_event_callback), this); -} - -void Dialog::Destroy() -{ - ASSERT_MESSAGE(m_window != 0, "dialog cannot be destroyed"); - - gtk_widget_destroy(GTK_WIDGET(m_window)); - m_window = 0; -} - - -void Dialog::AddBoolToggleData(GtkToggleButton& widget, const BoolImportCallback& importViewer, const BoolExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddIntRadioData(GtkRadioButton& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddTextEntryData(GtkEntry& widget, const StringImportCallback& importViewer, const StringExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddIntEntryData(GtkEntry& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddSizeEntryData(GtkEntry& widget, const SizeImportCallback& importViewer, const SizeExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddFloatEntryData(GtkEntry& widget, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddFloatSpinnerData(GtkSpinButton& widget, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddIntSpinnerData(GtkSpinButton& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddIntAdjustmentData(GtkAdjustment& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - -void Dialog::AddIntComboData(GtkComboBox& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - AddCustomData(m_data).apply(widget, importViewer, exportViewer); -} - - -void Dialog::AddDialogData(GtkToggleButton& widget, bool& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkRadioButton& widget, int& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkEntry& widget, CopiedString& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkEntry& widget, int& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkEntry& widget, std::size_t& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkEntry& widget, float& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkSpinButton& widget, float& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkSpinButton& widget, int& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkAdjustment& widget, int& data) -{ - AddData(m_data).apply(widget, data); -} -void Dialog::AddDialogData(GtkComboBox& widget, int& data) -{ - AddData(m_data).apply(widget, data); -} - -void Dialog::exportData() -{ - for(DialogDataList::iterator i = m_data.begin(); i != m_data.end(); ++i) - { - (*i)->exportData(); - } -} - -void Dialog::importData() -{ - for(DialogDataList::iterator i = m_data.begin(); i != m_data.end(); ++i) - { - (*i)->importData(); - } -} - -void Dialog::EndModal (EMessageBoxReturn code) -{ - m_modal.loop = 0; - m_modal.ret = code; -} - -EMessageBoxReturn Dialog::DoModal() -{ - importData(); - - PreModal(); - - EMessageBoxReturn ret = modal_dialog_show(m_window, m_modal); - ASSERT_NOTNULL(m_window); - if(ret == eIDOK) - { - exportData(); - } - - gtk_widget_hide(GTK_WIDGET(m_window)); - - PostModal(m_modal.ret); - - return m_modal.ret; -} - - -GtkWidget* Dialog::addCheckBox(GtkWidget* vbox, const char* name, const char* flag, const BoolImportCallback& importViewer, const BoolExportCallback& exportViewer) -{ - GtkWidget* check = gtk_check_button_new_with_label(flag); - gtk_widget_show(check); - AddBoolToggleData(*GTK_TOGGLE_BUTTON(check), importViewer, exportViewer); - - DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(DialogRow_new(name, check))); - return check; -} - -GtkWidget* Dialog::addCheckBox(GtkWidget* vbox, const char* name, const char* flag, bool& data) -{ - return addCheckBox(vbox, name, flag, BoolImportCaller(data), BoolExportCaller(data)); -} - -void Dialog::addCombo(GtkWidget* vbox, const char* name, StringArrayRange values, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); - gtk_widget_show(alignment); - { - GtkWidget* combo = gtk_combo_box_new_text(); - - for(StringArrayRange::Iterator i = values.first; i != values.last; ++i) - { - gtk_combo_box_append_text(GTK_COMBO_BOX(combo), *i); - } - - AddIntComboData(*GTK_COMBO_BOX(combo), importViewer, exportViewer); - - gtk_widget_show (combo); - gtk_container_add(GTK_CONTAINER(alignment), combo); - } - - GtkTable* row = DialogRow_new(name, alignment); - DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); -} - -void Dialog::addCombo(GtkWidget* vbox, const char* name, int& data, StringArrayRange values) -{ - addCombo(vbox, name, values, IntImportCaller(data), IntExportCaller(data)); -} - -void Dialog::addSlider(GtkWidget* vbox, const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment) -{ -#if 0 - if(draw_value == FALSE) - { - GtkWidget* hbox2 = gtk_hbox_new (FALSE, 0); - gtk_widget_show (hbox2); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox2), FALSE, FALSE, 0); - { - GtkWidget* label = gtk_label_new (low); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, FALSE, 0); - } - { - GtkWidget* label = gtk_label_new (high); - gtk_widget_show (label); - gtk_box_pack_end (GTK_BOX (hbox2), label, FALSE, FALSE, 0); - } - } -#endif - - // adjustment - GtkObject* adj = gtk_adjustment_new(value, lower, upper, step_increment, page_increment, 0); - AddIntAdjustmentData(*GTK_ADJUSTMENT(adj), IntImportCaller(data), IntExportCaller(data)); - - // scale - GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 1.0, 0.0); - gtk_widget_show(alignment); - - GtkWidget* scale = gtk_hscale_new(GTK_ADJUSTMENT(adj)); - gtk_scale_set_value_pos(GTK_SCALE(scale), GTK_POS_LEFT); - gtk_widget_show(scale); - gtk_container_add(GTK_CONTAINER(alignment), scale); - - gtk_scale_set_draw_value(GTK_SCALE (scale), draw_value); - gtk_scale_set_digits(GTK_SCALE (scale), 0); - - GtkTable* row = DialogRow_new(name, alignment); - DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); -} - -void Dialog::addRadio(GtkWidget* vbox, const char* name, StringArrayRange names, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); - gtk_widget_show(alignment); - { - RadioHBox radioBox = RadioHBox_new(names); - gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(radioBox.m_hbox)); - AddIntRadioData(*GTK_RADIO_BUTTON(radioBox.m_radio), importViewer, exportViewer); - } - - GtkTable* row = DialogRow_new(name, alignment); - DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); -} - -void Dialog::addRadio(GtkWidget* vbox, const char* name, int& data, StringArrayRange names) -{ - addRadio(vbox, name, names, IntImportCaller(data), IntExportCaller(data)); -} - -void Dialog::addRadioIcons(GtkWidget* vbox, const char* name, StringArrayRange icons, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - GtkWidget* table = gtk_table_new (2, static_cast(icons.last - icons.first), FALSE); - gtk_widget_show (table); - - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - GSList* group = 0; - GtkWidget* radio = 0; - for(StringArrayRange::Iterator icon = icons.first; icon != icons.last; ++icon) - { - guint pos = static_cast(icon - icons.first); - GtkImage* image = new_local_image(*icon); - gtk_widget_show(GTK_WIDGET(image)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(image), pos, pos+1, 0, 1, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - - radio = gtk_radio_button_new(group); - gtk_widget_show (radio); - gtk_table_attach (GTK_TABLE (table), radio, pos, pos+1, 1, 2, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - - group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(radio)); - } - - AddIntRadioData(*GTK_RADIO_BUTTON(radio), importViewer, exportViewer); - - DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(DialogRow_new(name, table))); -} - -void Dialog::addRadioIcons(GtkWidget* vbox, const char* name, int& data, StringArrayRange icons) -{ - addRadioIcons(vbox, name, icons, IntImportCaller(data), IntExportCaller(data)); -} - -GtkWidget* Dialog::addIntEntry(GtkWidget* vbox, const char* name, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - DialogEntryRow row(DialogEntryRow_new(name)); - AddIntEntryData(*row.m_entry, importViewer, exportViewer); - DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); - return row.m_row; -} - -GtkWidget* Dialog::addSizeEntry(GtkWidget* vbox, const char* name, const SizeImportCallback& importViewer, const SizeExportCallback& exportViewer) -{ - DialogEntryRow row(DialogEntryRow_new(name)); - AddSizeEntryData(*row.m_entry, importViewer, exportViewer); - DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); - return row.m_row; -} - -GtkWidget* Dialog::addFloatEntry(GtkWidget* vbox, const char* name, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) -{ - DialogEntryRow row(DialogEntryRow_new(name)); - AddFloatEntryData(*row.m_entry, importViewer, exportViewer); - DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); - return row.m_row; -} - -GtkWidget* Dialog::addPathEntry(GtkWidget* vbox, const char* name, bool browse_directory, const StringImportCallback& importViewer, const StringExportCallback& exportViewer) -{ - PathEntry pathEntry = PathEntry_new(); - g_signal_connect(G_OBJECT(pathEntry.m_button), "clicked", G_CALLBACK(browse_directory ? button_clicked_entry_browse_directory : button_clicked_entry_browse_file), pathEntry.m_entry); - - AddTextEntryData(*GTK_ENTRY(pathEntry.m_entry), importViewer, exportViewer); - - GtkTable* row = DialogRow_new(name, GTK_WIDGET(pathEntry.m_frame)); - DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); - - return GTK_WIDGET(row); -} - -GtkWidget* Dialog::addPathEntry(GtkWidget* vbox, const char* name, CopiedString& data, bool browse_directory) -{ - return addPathEntry(vbox, name, browse_directory, StringImportCallback(StringImportCaller(data)), StringExportCallback(StringExportCaller(data))); -} - -GtkWidget* Dialog::addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) -{ - DialogSpinnerRow row(DialogSpinnerRow_new(name, value, lower, upper, 1)); - AddIntSpinnerData(*row.m_spin, importViewer, exportViewer); - DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); - return row.m_row; -} - -GtkWidget* Dialog::addSpinner(GtkWidget* vbox, const char* name, int& data, double value, double lower, double upper) -{ - return addSpinner(vbox, name, value, lower, upper, IntImportCallback(IntImportCaller(data)), IntExportCallback(IntExportCaller(data))); -} - -GtkWidget* Dialog::addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) -{ - DialogSpinnerRow row(DialogSpinnerRow_new(name, value, lower, upper, 10)); - AddFloatSpinnerData(*row.m_spin, importViewer, exportViewer); - DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); - return row.m_row; -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/dialog.h b/misc/mediasource/extra/netradiant-src/radiant/dialog.h deleted file mode 100644 index 444fe516..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/dialog.h +++ /dev/null @@ -1,208 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_DIALOG_H) -#define INCLUDED_DIALOG_H - -#include - -#include "gtkutil/dialog.h" -#include "generic/callback.h" -#include "string/string.h" - -template -class ReferenceCaller1; - -inline void BoolImport(bool& self, bool value) -{ - self = value; -} -typedef ReferenceCaller1 BoolImportCaller; - -inline void BoolExport(bool& self, const BoolImportCallback& importCallback) -{ - importCallback(self); -} -typedef ReferenceCaller1 BoolExportCaller; - - -inline void IntImport(int& self, int value) -{ - self = value; -} -typedef ReferenceCaller1 IntImportCaller; - -inline void IntExport(int& self, const IntImportCallback& importCallback) -{ - importCallback(self); -} -typedef ReferenceCaller1 IntExportCaller; - - -inline void SizeImport(std::size_t& self, std::size_t value) -{ - self = value; -} -typedef ReferenceCaller1 SizeImportCaller; - -inline void SizeExport(std::size_t& self, const SizeImportCallback& importCallback) -{ - importCallback(self); -} -typedef ReferenceCaller1 SizeExportCaller; - - -inline void FloatImport(float& self, float value) -{ - self = value; -} -typedef ReferenceCaller1 FloatImportCaller; - -inline void FloatExport(float& self, const FloatImportCallback& importCallback) -{ - importCallback(self); -} -typedef ReferenceCaller1 FloatExportCaller; - - -inline void StringImport(CopiedString& self, const char* value) -{ - self = value; -} -typedef ReferenceCaller1 StringImportCaller; -inline void StringExport(CopiedString& self, const StringImportCallback& importCallback) -{ - importCallback(self.c_str()); -} -typedef ReferenceCaller1 StringExportCaller; - - -struct DLG_DATA -{ - virtual void release() = 0; - virtual void importData() const = 0; - virtual void exportData() const = 0; -}; - -typedef struct _GtkWindow GtkWindow; -typedef struct _GtkToggleButton GtkToggleButton; -typedef struct _GtkRadioButton GtkRadioButton; -typedef struct _GtkSpinButton GtkSpinButton; -typedef struct _GtkComboBox GtkComboBox; -typedef struct _GtkEntry GtkEntry; -typedef struct _GtkAdjustment GtkAdjustment; - -template -class CallbackDialogData; - -typedef std::list DialogDataList; - -class Dialog -{ - GtkWindow* m_window; - DialogDataList m_data; -public: - ModalDialog m_modal; - GtkWindow* m_parent; - - Dialog(); - virtual ~Dialog(); - - /*! - start modal dialog box - you need to use AddModalButton to select eIDOK eIDCANCEL buttons - */ - EMessageBoxReturn DoModal(); - void EndModal (EMessageBoxReturn code); - virtual GtkWindow* BuildDialog() = 0; - virtual void exportData(); - virtual void importData(); - virtual void PreModal() { }; - virtual void PostModal (EMessageBoxReturn code) { }; - virtual void ShowDlg(); - virtual void HideDlg(); - void Create(); - void Destroy(); - GtkWindow* GetWidget() - { - return m_window; - } - const GtkWindow* GetWidget() const - { - return m_window; - } - - GtkWidget* addCheckBox(GtkWidget* vbox, const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback); - GtkWidget* addCheckBox(GtkWidget* vbox, const char* name, const char* flag, bool& data); - void addCombo(GtkWidget* vbox, const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - void addCombo(GtkWidget* vbox, const char* name, int& data, StringArrayRange values); - void addSlider(GtkWidget* vbox, const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment); - void addRadio(GtkWidget* vbox, const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - void addRadio(GtkWidget* vbox, const char* name, int& data, StringArrayRange names); - void addRadioIcons(GtkWidget* vbox, const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - void addRadioIcons(GtkWidget* vbox, const char* name, int& data, StringArrayRange icons); - GtkWidget* addIntEntry(GtkWidget* vbox, const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - GtkWidget* addEntry(GtkWidget* vbox, const char* name, int& data) - { - return addIntEntry(vbox, name, IntImportCaller(data), IntExportCaller(data)); - } - GtkWidget* addSizeEntry(GtkWidget* vbox, const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback); - GtkWidget* addEntry(GtkWidget* vbox, const char* name, std::size_t& data) - { - return addSizeEntry(vbox, name, SizeImportCaller(data), SizeExportCaller(data)); - } - GtkWidget* addFloatEntry(GtkWidget* vbox, const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); - GtkWidget* addEntry(GtkWidget* vbox, const char* name, float& data) - { - return addFloatEntry(vbox, name, FloatImportCaller(data), FloatExportCaller(data)); - } - GtkWidget* addPathEntry(GtkWidget* vbox, const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback); - GtkWidget* addPathEntry(GtkWidget* vbox, const char* name, CopiedString& data, bool directory); - GtkWidget* addSpinner(GtkWidget* vbox, const char* name, int& data, double value, double lower, double upper); - GtkWidget* addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - GtkWidget* addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); - -protected: - - void AddBoolToggleData(GtkToggleButton& object, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback); - void AddIntRadioData(GtkRadioButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - void AddTextEntryData(GtkEntry& object, const StringImportCallback& importCallback, const StringExportCallback& exportCallback); - void AddIntEntryData(GtkEntry& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - void AddSizeEntryData(GtkEntry& object, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback); - void AddFloatEntryData(GtkEntry& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); - void AddFloatSpinnerData(GtkSpinButton& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); - void AddIntSpinnerData(GtkSpinButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - void AddIntAdjustmentData(GtkAdjustment& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - void AddIntComboData(GtkComboBox& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); - - void AddDialogData(GtkToggleButton& object, bool& data); - void AddDialogData(GtkRadioButton& object, int& data); - void AddDialogData(GtkEntry& object, CopiedString& data); - void AddDialogData(GtkEntry& object, int& data); - void AddDialogData(GtkEntry& object, std::size_t& data); - void AddDialogData(GtkEntry& object, float& data); - void AddDialogData(GtkSpinButton& object, float& data); - void AddDialogData(GtkSpinButton& object, int& data); - void AddDialogData(GtkAdjustment& object, int& data); - void AddDialogData(GtkComboBox& object, int& data); -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass.cpp b/misc/mediasource/extra/netradiant-src/radiant/eclass.cpp deleted file mode 100644 index edbf4156..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass.cpp +++ /dev/null @@ -1,414 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "eclass.h" - -#include "debugging/debugging.h" - -#include - -#include "ifilesystem.h" - -#include "string/string.h" -#include "eclasslib.h" -#include "os/path.h" -#include "os/dir.h" -#include "stream/stringstream.h" -#include "moduleobservers.h" - -#include "cmdlib.h" - -#include "preferences.h" -#include "mainframe.h" - - -namespace -{ - typedef std::map EntityClasses; - EntityClasses g_entityClasses; - EntityClass *eclass_bad = 0; - char eclass_directory[1024]; - typedef std::map ListAttributeTypes; - ListAttributeTypes g_listTypes; -} - -EClassModules& EntityClassManager_getEClassModules(); - -/*! -implementation of the EClass manager API -*/ - -void CleanEntityList(EntityClasses& entityClasses) -{ - for(EntityClasses::iterator i = entityClasses.begin(); i != entityClasses.end(); ++i) - { - (*i).second->free((*i).second); - } - entityClasses.clear(); -} - -void Eclass_Clear() -{ - CleanEntityList(g_entityClasses); - g_listTypes.clear(); -} - -EntityClass* EClass_InsertSortedList(EntityClasses& entityClasses, EntityClass *entityClass) -{ - std::pair result = entityClasses.insert(EntityClasses::value_type(entityClass->name(), entityClass)); - if(!result.second) - { - entityClass->free(entityClass); - } - return (*result.first).second; -} - -EntityClass* Eclass_InsertAlphabetized (EntityClass *e) -{ - return EClass_InsertSortedList(g_entityClasses, e); -} - -void Eclass_forEach(EntityClassVisitor& visitor) -{ - for(EntityClasses::iterator i = g_entityClasses.begin(); i != g_entityClasses.end(); ++i) - { - visitor.visit((*i).second); - } -} - - -class RadiantEclassCollector : public EntityClassCollector -{ -public: - void insert(EntityClass* eclass) - { - Eclass_InsertAlphabetized(eclass); - } - void insert(const char* name, const ListAttributeType& list) - { - g_listTypes.insert(ListAttributeTypes::value_type(name, list)); - } -}; - -RadiantEclassCollector g_collector; - -const ListAttributeType* EntityClass_findListType(const char* name) -{ - ListAttributeTypes::iterator i = g_listTypes.find(name); - if(i != g_listTypes.end()) - { - return &(*i).second; - } - return 0; -} - - -class EntityClassFilterMode -{ -public: - bool filter_mp_sp; - const char* mp_ignore_prefix; - const char* sp_ignore_prefix; - - EntityClassFilterMode() : - filter_mp_sp(!string_empty(g_pGameDescription->getKeyValue("eclass_filter_gamemode"))), - mp_ignore_prefix(g_pGameDescription->getKeyValue("eclass_sp_prefix")), - sp_ignore_prefix(g_pGameDescription->getKeyValue("eclass_mp_prefix")) - { - if(string_empty(mp_ignore_prefix)) - { - mp_ignore_prefix = "sp_"; - } - if(string_empty(sp_ignore_prefix)) - { - sp_ignore_prefix = "mp_"; - } - } -}; - -class EntityClassesLoadFile -{ - const EntityClassScanner& scanner; - const char* m_directory; -public: - EntityClassesLoadFile(const EntityClassScanner& scanner, const char* directory) : scanner(scanner), m_directory(directory) - { - } - void operator()(const char* name) const - { - EntityClassFilterMode filterMode; - - if(filterMode.filter_mp_sp) - { - if(string_empty(GlobalRadiant().getGameMode()) || string_equal(GlobalRadiant().getGameMode(), "sp")) - { - if(string_equal_n(name, filterMode.sp_ignore_prefix, strlen(filterMode.sp_ignore_prefix))) - { - globalOutputStream() << "Ignoring '" << name << "'\n"; - return; - } - } - else - { - if(string_equal_n(name, filterMode.mp_ignore_prefix, strlen(filterMode.mp_ignore_prefix))) - { - globalOutputStream() << "Ignoring '" << name << "'\n"; - return; - } - } - } - - // for a given name, we grab the first .def in the vfs - // this allows to override baseq3/scripts/entities.def for instance - StringOutputStream relPath(256); - relPath << m_directory << name; - - scanner.scanFile(g_collector, relPath.c_str()); - } -}; - -struct PathLess -{ - bool operator()(const CopiedString& path, const CopiedString& other) const - { - return path_less(path.c_str(), other.c_str()); - } -}; - -typedef std::map Paths; - -class PathsInsert -{ - Paths& m_paths; - const char* m_directory; -public: - PathsInsert(Paths& paths, const char* directory) : m_paths(paths), m_directory(directory) - { - } - void operator()(const char* name) const - { - m_paths.insert(Paths::value_type(name, m_directory)); - } -}; - - -void EntityClassQuake3_constructDirectory(const char* directory, const char* extension, Paths& paths) -{ - globalOutputStream() << "EntityClass: searching " << makeQuoted(directory) << " for *." << extension << '\n'; - Directory_forEach(directory, matchFileExtension(extension, PathsInsert(paths, directory))); -} - - -void EntityClassQuake3_Construct() -{ - StringOutputStream baseDirectory(256); - StringOutputStream gameDirectory(256); - const char* basegame = GlobalRadiant().getRequiredGameDescriptionKeyValue("basegame"); - const char* gamename = GlobalRadiant().getGameName(); - baseDirectory << GlobalRadiant().getGameToolsPath() << basegame << '/'; - gameDirectory << GlobalRadiant().getGameToolsPath() << gamename << '/'; - - class LoadEntityDefinitionsVisitor : public EClassModules::Visitor - { - const char* baseDirectory; - const char* gameDirectory; - public: - LoadEntityDefinitionsVisitor(const char* baseDirectory, const char* gameDirectory) - : baseDirectory(baseDirectory), gameDirectory(gameDirectory) - { - } - void visit(const char* name, const EntityClassScanner& table) const - { - Paths paths; - EntityClassQuake3_constructDirectory(baseDirectory, table.getExtension(), paths); - if(!string_equal(baseDirectory, gameDirectory)) - { - EntityClassQuake3_constructDirectory(gameDirectory, table.getExtension(), paths); - } - - for(Paths::iterator i = paths.begin(); i != paths.end(); ++i) - { - EntityClassesLoadFile(table, (*i).second)((*i).first.c_str()); - } - } - }; - - EntityClassManager_getEClassModules().foreachModule(LoadEntityDefinitionsVisitor(baseDirectory.c_str(), gameDirectory.c_str())); -} - -EntityClass *Eclass_ForName(const char *name, bool has_brushes) -{ - ASSERT_NOTNULL(name); - - if(string_empty(name)) - { - return eclass_bad; - } - - EntityClasses::iterator i = g_entityClasses.find(name); - if(i != g_entityClasses.end() && string_equal((*i).first, name)) - { - return (*i).second; - } - - EntityClass* e = EntityClass_Create_Default(name, has_brushes); - return Eclass_InsertAlphabetized(e); -} - -class EntityClassQuake3 : public ModuleObserver -{ - std::size_t m_unrealised; - ModuleObservers m_observers; -public: - EntityClassQuake3() : m_unrealised(4) - { - } - void realise() - { - if(--m_unrealised == 0) - { - //globalOutputStream() << "Entity Classes: realise\n"; - EntityClassQuake3_Construct(); - m_observers.realise(); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - m_observers.unrealise(); - //globalOutputStream() << "Entity Classes: unrealise\n"; - Eclass_Clear(); - } - } - void attach(ModuleObserver& observer) - { - m_observers.attach(observer); - } - void detach(ModuleObserver& observer) - { - m_observers.detach(observer); - } -}; - -EntityClassQuake3 g_EntityClassQuake3; - -void EntityClass_attach(ModuleObserver& observer) -{ - g_EntityClassQuake3.attach(observer); -} -void EntityClass_detach(ModuleObserver& observer) -{ - g_EntityClassQuake3.detach(observer); -} - -void EntityClass_realise() -{ - g_EntityClassQuake3.realise(); -} -void EntityClass_unrealise() -{ - g_EntityClassQuake3.unrealise(); -} - -void EntityClassQuake3_construct() -{ - // start by creating the default unknown eclass - eclass_bad = EClass_Create("UNKNOWN_CLASS", Vector3(0.0f, 0.5f, 0.0f), ""); - - EntityClass_realise(); -} - -void EntityClassQuake3_destroy() -{ - EntityClass_unrealise(); - - eclass_bad->free(eclass_bad); -} - -#include "modulesystem/modulesmap.h" - -class EntityClassQuake3Dependencies : - public GlobalRadiantModuleRef, - public GlobalFileSystemModuleRef, - public GlobalShaderCacheModuleRef -{ - EClassModulesRef m_eclass_modules; -public: - EntityClassQuake3Dependencies() : - m_eclass_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclasstype")) - { - } - EClassModules& getEClassModules() - { - return m_eclass_modules.get(); - } -}; - -class EclassManagerAPI -{ - EntityClassManager m_eclassmanager; -public: - typedef EntityClassManager Type; - STRING_CONSTANT(Name, "quake3"); - - EclassManagerAPI() - { - EntityClassQuake3_construct(); - - m_eclassmanager.findOrInsert = &Eclass_ForName; - m_eclassmanager.findListType = &EntityClass_findListType; - m_eclassmanager.forEach = &Eclass_forEach; - m_eclassmanager.attach = &EntityClass_attach; - m_eclassmanager.detach = &EntityClass_detach; - m_eclassmanager.realise = &EntityClass_realise; - m_eclassmanager.unrealise = &EntityClass_unrealise; - - GlobalRadiant().attachGameToolsPathObserver(g_EntityClassQuake3); - GlobalRadiant().attachGameModeObserver(g_EntityClassQuake3); - GlobalRadiant().attachGameNameObserver(g_EntityClassQuake3); - } - ~EclassManagerAPI() - { - GlobalRadiant().detachGameNameObserver(g_EntityClassQuake3); - GlobalRadiant().detachGameModeObserver(g_EntityClassQuake3); - GlobalRadiant().detachGameToolsPathObserver(g_EntityClassQuake3); - - EntityClassQuake3_destroy(); - } - EntityClassManager* getTable() - { - return &m_eclassmanager; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule EclassManagerModule; -typedef Static StaticEclassManagerModule; -StaticRegisterModule staticRegisterEclassManager(StaticEclassManagerModule::instance()); - -EClassModules& EntityClassManager_getEClassModules() -{ - return StaticEclassManagerModule::instance().getDependencies().getEClassModules(); -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass.h b/misc/mediasource/extra/netradiant-src/radiant/eclass.h deleted file mode 100644 index 48d52ba3..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_ECLASS_H) -#define INCLUDED_ECLASS_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_def.cpp b/misc/mediasource/extra/netradiant-src/radiant/eclass_def.cpp deleted file mode 100644 index 01341ed5..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_def.cpp +++ /dev/null @@ -1,407 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "eclass_def.h" - -#include "iscriplib.h" -#include "ifilesystem.h" -#include "iarchive.h" - -#include "eclasslib.h" -#include "stream/stringstream.h" -#include "stream/textfilestream.h" -#include "modulesystem/moduleregistry.h" -#include "os/path.h" - -const char* EClass_GetExtension() -{ - return "def"; -} -void Eclass_ScanFile (EntityClassCollector& collector, const char *filename); - - -#include "modulesystem/singletonmodule.h" - -class EntityClassDefDependencies : public GlobalShaderCacheModuleRef, public GlobalScripLibModuleRef -{ -}; - -class EclassDefAPI -{ - EntityClassScanner m_eclassdef; -public: - typedef EntityClassScanner Type; - STRING_CONSTANT(Name, "def"); - - EclassDefAPI() - { - m_eclassdef.scanFile = &Eclass_ScanFile; - m_eclassdef.getExtension = &EClass_GetExtension; - } - EntityClassScanner* getTable() - { - return &m_eclassdef; - } -}; - -typedef SingletonModule EclassDefModule; -typedef Static StaticEclassDefModule; -StaticRegisterModule staticRegisterEclassDef(StaticEclassDefModule::instance()); - - -#include "string/string.h" - -#include - - -char com_token[1024]; -bool com_eof; - -/* -============== -COM_Parse - -Parse a token out of a string -============== -*/ -const char *COM_Parse (const char *data) -{ - int c; - int len; - - len = 0; - com_token[0] = 0; - - if (!data) - return 0; - -// skip whitespace -skipwhite: - while ( (c = *data) <= ' ') - { - if (c == 0) - { - com_eof = true; - return 0; // 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; -} - -const char* Get_COM_Token() -{ - return com_token; -} - - -const char *debugname; - -void setSpecialLoad(EntityClass *e, const char* pWhat, CopiedString& p) -{ - // Hydra: removed some amazingly bad cstring usage, whoever wrote that - // needs to be taken out and shot. - - const char *pText = 0; - const char *where = 0; - - where = strstr(e->comments(),pWhat); - if (!where) - return; - - pText = where + strlen(pWhat); - if (*pText == '\"') - pText++; - - where = strchr(pText,'\"'); - if (where) - { - p = StringRange(pText, where); - } - else - { - p = pText; - } -} - -#include "eclasslib.h" - -/* - -the classname, color triple, and bounding box are parsed out of comments -A ? size means take the exact brush size. - -/ *QUAKED (0 0 0) ? -/ *QUAKED (0 0 0) (-8 -8 -8) (8 8 8) - -Flag names can follow the size description: - -/ *QUAKED func_door (0 .5 .8) ? START_OPEN STONE_SOUND DOOR_DONT_LINK GOLD_KEY SILVER_KEY - -*/ - -EntityClass *Eclass_InitFromText (const char *text) -{ - EntityClass* e = Eclass_Alloc(); - e->free = &Eclass_Free; - - // grab the name - text = COM_Parse (text); - e->m_name = Get_COM_Token(); - debugname = e->name(); - - { - // grab the color, reformat as texture name - int r = sscanf (text," (%f %f %f)", &e->color[0], &e->color[1], &e->color[2]); - if (r != 3) - return e; - eclass_capture_state(e); - } - - while (*text != ')') - { - if (!*text) { - return 0; - } - text++; - } - text++; - - // get the size - text = COM_Parse (text); - if (Get_COM_Token()[0] == '(') - { // parse the size as two vectors - e->fixedsize = true; - int r = sscanf (text,"%f %f %f) (%f %f %f)", &e->mins[0], &e->mins[1], &e->mins[2], - &e->maxs[0], &e->maxs[1], &e->maxs[2]); - if (r != 6) { - return 0; - } - - for (int i=0 ; i<2 ; i++) - { - while (*text != ')') - { - if (!*text) { - return 0; - } - text++; - } - text++; - } - } - - char parms[256]; - // get the flags - { - // copy to the first /n - char* p = parms; - while (*text && *text != '\n') - *p++ = *text++; - *p = 0; - text++; - } - - { - // any remaining words are parm flags - const char* p = parms; - for (std::size_t i=0 ; iflagnames[i], Get_COM_Token()); - } - } - - e->m_comments = text; - - setSpecialLoad(e, "model=", e->m_modelpath); - StringOutputStream buffer(string_length(e->m_modelpath.c_str())); - buffer << PathCleaned(e->m_modelpath.c_str()); - e->m_modelpath = buffer.c_str(); - - if(!e->fixedsize) - { - EntityClass_insertAttribute(*e, "angle", EntityClassAttribute("direction", "Direction", "0")); - } - else - { - EntityClass_insertAttribute(*e, "angle", EntityClassAttribute("angle", "Yaw Angle", "0")); - } - EntityClass_insertAttribute(*e, "model", EntityClassAttribute("model", "Model")); - EntityClass_insertAttribute(*e, "noise", EntityClassAttribute("sound", "Sound")); - - return e; -} - -void Eclass_ScanFile (EntityClassCollector& collector, const char *filename) -{ - EntityClass *e; - - TextFileInputStream inputFile(filename); - if(inputFile.failed()) - { - globalErrorStream() << "ScanFile: " << filename << " not found\n"; - return; - } - globalOutputStream() << "ScanFile: " << filename << "\n"; - - enum EParserState - { - eParseDefault, - eParseSolidus, - eParseComment, - eParseQuakeED, - eParseEntityClass, - eParseEntityClassEnd, - } state = eParseDefault; - const char* quakeEd = "QUAKED"; - const char* p = 0; - StringBuffer buffer; - SingleCharacterInputStream bufferedInput(inputFile); - for(;;) - { - char c; - if(!bufferedInput.readChar(c)) - { - break; - } - - switch(state) - { - case eParseDefault: - if(c == '/') - { - state = eParseSolidus; - } - break; - case eParseSolidus: - if(c == '/') - { - state = eParseComment; - } - else if(c == '*') - { - p = quakeEd; - state = eParseQuakeED; - } - break; - case eParseComment: - if(c == '\n') - { - state = eParseDefault; - } - break; - case eParseQuakeED: - if(c == *p) - { - if(*(++p) == '\0') - { - state = eParseEntityClass; - } - } - else - { - state = eParseDefault; - } - break; - case eParseEntityClass: - if(c == '*') - { - state = eParseEntityClassEnd; - } - else - { - buffer.push_back(c); - } - break; - case eParseEntityClassEnd: - if(c == '/') - { - e = Eclass_InitFromText(buffer.c_str()); - state = eParseDefault; - if (e) - collector.insert(e); - else - globalErrorStream() << "Error parsing: " << debugname << " in " << filename << "\n"; - - buffer.clear(); - state = eParseDefault; - } - else - { - buffer.push_back('*'); - buffer.push_back(c); - state = eParseEntityClass; - } - break; - } - } -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_def.h b/misc/mediasource/extra/netradiant-src/radiant/eclass_def.h deleted file mode 100644 index 23a5ef4d..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_def.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_ECLASS_DEF_H) -#define INCLUDED_ECLASS_DEF_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_doom3.cpp b/misc/mediasource/extra/netradiant-src/radiant/eclass_doom3.cpp deleted file mode 100644 index 217c4ec5..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_doom3.cpp +++ /dev/null @@ -1,929 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "eclass_doom3.h" - -#include "debugging/debugging.h" - -#include - -#include "ifilesystem.h" -#include "iscriplib.h" -#include "iarchive.h" -#include "qerplugin.h" - -#include "generic/callback.h" -#include "string/string.h" -#include "eclasslib.h" -#include "os/path.h" -#include "os/dir.h" -#include "stream/stringstream.h" -#include "moduleobservers.h" -#include "stringio.h" - -class RawString -{ - const char* m_value; -public: - RawString(const char* value) : m_value(value) - { - } - const char* c_str() const - { - return m_value; - } -}; - -inline bool operator<(const RawString& self, const RawString& other) -{ - return string_less_nocase(self.c_str(), other.c_str()); -} - -typedef std::map EntityClasses; -EntityClasses g_EntityClassDoom3_classes; -EntityClass *g_EntityClassDoom3_bad = 0; - - -void EntityClassDoom3_clear() -{ - for(EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i) - { - (*i).second->free((*i).second); - } - g_EntityClassDoom3_classes.clear(); -} - -// entityClass will be inserted only if another of the same name does not already exist. -// if entityClass was inserted, the same object is returned, otherwise the already-existing object is returned. -EntityClass* EntityClassDoom3_insertUnique(EntityClass* entityClass) -{ - return (*g_EntityClassDoom3_classes.insert(EntityClasses::value_type(entityClass->name(), entityClass)).first).second; -} - -void EntityClassDoom3_forEach(EntityClassVisitor& visitor) -{ - for(EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i) - { - visitor.visit((*i).second); - } -} - -inline void printParseError(const char* message) -{ - globalErrorStream() << message; -} - -#define PARSE_RETURN_FALSE_IF_FAIL(expression) if(!(expression)) { printParseError(FILE_LINE "\nparse failed: " #expression "\n"); return false; } else - -bool EntityClassDoom3_parseToken(Tokeniser& tokeniser) -{ - const char* token = tokeniser.getToken(); - PARSE_RETURN_FALSE_IF_FAIL(token != 0); - return true; -} - -bool EntityClassDoom3_parseToken(Tokeniser& tokeniser, const char* string) -{ - const char* token = tokeniser.getToken(); - PARSE_RETURN_FALSE_IF_FAIL(token != 0); - return string_equal(token, string); -} - -bool EntityClassDoom3_parseString(Tokeniser& tokeniser, const char*& s) -{ - const char* token = tokeniser.getToken(); - PARSE_RETURN_FALSE_IF_FAIL(token != 0); - s = token; - return true; -} - -bool EntityClassDoom3_parseString(Tokeniser& tokeniser, CopiedString& s) -{ - const char* token = tokeniser.getToken(); - PARSE_RETURN_FALSE_IF_FAIL(token != 0); - s = token; - return true; -} - -bool EntityClassDoom3_parseString(Tokeniser& tokeniser, StringOutputStream& s) -{ - const char* token = tokeniser.getToken(); - PARSE_RETURN_FALSE_IF_FAIL(token != 0); - s << token; - return true; -} - -bool EntityClassDoom3_parseUnknown(Tokeniser& tokeniser) -{ - //const char* name = - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - - //globalOutputStream() << "parsing unknown block " << makeQuoted(name) << "\n"; - - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "{")); - tokeniser.nextLine(); - - std::size_t depth = 1; - for(;;) - { - const char* token; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); - if(string_equal(token, "}")) - { - if(--depth == 0) - { - tokeniser.nextLine(); - break; - } - } - else if(string_equal(token, "{")) - { - ++depth; - } - tokeniser.nextLine(); - } - return true; -} - - -class Model -{ -public: - bool m_resolved; - CopiedString m_mesh; - CopiedString m_skin; - CopiedString m_parent; - typedef std::map Anims; - Anims m_anims; - Model() : m_resolved(false) - { - } -}; - -typedef std::map Models; - -Models g_models; - -void Model_resolveInheritance(const char* name, Model& model) -{ - if(model.m_resolved == false) - { - model.m_resolved = true; - - if(!string_empty(model.m_parent.c_str())) - { - Models::iterator i = g_models.find(model.m_parent); - if(i == g_models.end()) - { - globalErrorStream() << "model " << name << " inherits unknown model " << model.m_parent.c_str() << "\n"; - } - else - { - Model_resolveInheritance((*i).first.c_str(), (*i).second); - model.m_mesh = (*i).second.m_mesh; - model.m_skin = (*i).second.m_skin; - } - } - } -} - -bool EntityClassDoom3_parseModel(Tokeniser& tokeniser) -{ - const char* name; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, name)); - - Model& model = g_models[name]; - - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "{")); - tokeniser.nextLine(); - - for(;;) - { - const char* parameter; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, parameter)); - if(string_equal(parameter, "}")) - { - tokeniser.nextLine(); - break; - } - else if(string_equal(parameter, "inherit")) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, model.m_parent)); - tokeniser.nextLine(); - } - else if(string_equal(parameter, "remove")) - { - //const char* remove = - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - tokeniser.nextLine(); - } - else if(string_equal(parameter, "mesh")) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, model.m_mesh)); - tokeniser.nextLine(); - } - else if(string_equal(parameter, "skin")) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, model.m_skin)); - tokeniser.nextLine(); - } - else if(string_equal(parameter, "offset")) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "(")); - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, ")")); - tokeniser.nextLine(); - } - else if(string_equal(parameter, "channel")) - { - //const char* channelName = - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "(")); - for(;;) - { - const char* end; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, end)); - if(string_equal(end, ")")) - { - tokeniser.nextLine(); - break; - } - } - } - else if(string_equal(parameter, "anim")) - { - CopiedString animName; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, animName)); - const char* animFile; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, animFile)); - model.m_anims.insert(Model::Anims::value_type(animName, animFile)); - - const char* token; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); - - while(string_equal(token, ",")) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, animFile)); - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); - } - - if(string_equal(token, "{")) - { - for(;;) - { - const char* end; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, end)); - if(string_equal(end, "}")) - { - tokeniser.nextLine(); - break; - } - tokeniser.nextLine(); - } - } - else - { - tokeniser.ungetToken(); - } - } - else - { - globalErrorStream() << "unknown model parameter: " << makeQuoted(parameter) << "\n"; - return false; - } - tokeniser.nextLine(); - } - return true; -} - -inline bool char_isSpaceOrTab(char c) -{ - return c == ' ' || c == '\t'; -} - -inline bool char_isNotSpaceOrTab(char c) -{ - return !char_isSpaceOrTab(c); -} - -template -inline const char* string_find_if(const char* string, Predicate predicate) -{ - for(; *string != 0; ++string) - { - if(predicate(*string)) - { - return string; - } - } - return string; -} - -inline const char* string_findFirstSpaceOrTab(const char* string) -{ - return string_find_if(string, char_isSpaceOrTab); -} - -inline const char* string_findFirstNonSpaceOrTab(const char* string) -{ - return string_find_if(string, char_isNotSpaceOrTab); -} - - -static bool EntityClass_parse(EntityClass& entityClass, Tokeniser& tokeniser) -{ - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, entityClass.m_name)); - - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "{")); - tokeniser.nextLine(); - - StringOutputStream usage(256); - StringOutputStream description(256); - CopiedString* currentDescription = 0; - StringOutputStream* currentString = 0; - - for(;;) - { - const char* key; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, key)); - - const char* last = string_findFirstSpaceOrTab(key); - CopiedString first(StringRange(key, last)); - - if(!string_empty(last)) - { - last = string_findFirstNonSpaceOrTab(last); - } - - if(currentString != 0 && string_equal(key, "\\")) - { - tokeniser.nextLine(); - *currentString << " "; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, *currentString)); - continue; - } - - if(currentDescription != 0) - { - *currentDescription = description.c_str(); - description.clear(); - currentDescription = 0; - } - currentString = 0; - - if(string_equal(key, "}")) - { - tokeniser.nextLine(); - break; - } - else if(string_equal(key, "model")) - { - const char* token; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); - entityClass.fixedsize = true; - StringOutputStream buffer(256); - buffer << PathCleaned(token); - entityClass.m_modelpath = buffer.c_str(); - } - else if(string_equal(key, "editor_color")) - { - const char* value; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); - if(!string_empty(value)) - { - entityClass.colorSpecified = true; - bool success = string_parse_vector3(value, entityClass.color); - ASSERT_MESSAGE(success, "editor_color: parse error"); - } - } - else if(string_equal(key, "editor_ragdoll")) - { - //bool ragdoll = atoi(tokeniser.getToken()) != 0; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - } - else if(string_equal(key, "editor_mins")) - { - entityClass.sizeSpecified = true; - const char* value; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); - if(!string_empty(value) && !string_equal(value, "?")) - { - entityClass.fixedsize = true; - bool success = string_parse_vector3(value, entityClass.mins); - ASSERT_MESSAGE(success, "editor_mins: parse error"); - } - } - else if(string_equal(key, "editor_maxs")) - { - entityClass.sizeSpecified = true; - const char* value; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); - if(!string_empty(value) && !string_equal(value, "?")) - { - entityClass.fixedsize = true; - bool success = string_parse_vector3(value, entityClass.maxs); - ASSERT_MESSAGE(success, "editor_maxs: parse error"); - } - } - else if(string_equal(key, "editor_usage")) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, usage)); - currentString = &usage; - } - else if(string_equal_n(key, "editor_usage", 12)) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, usage)); - currentString = &usage; - } - else if(string_equal(key, "editor_rotatable") - || string_equal(key, "editor_showangle") - || string_equal(key, "editor_showangles") // typo? in prey movables.def - || string_equal(key, "editor_mover") - || string_equal(key, "editor_model") - || string_equal(key, "editor_material") - || string_equal(key, "editor_combatnode") - || (!string_empty(last) && string_equal(first.c_str(), "editor_gui")) - || string_equal_n(key, "editor_copy", 11)) - { - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - } - else if(!string_empty(last) && (string_equal(first.c_str(), "editor_var") || string_equal(first.c_str(), "editor_string"))) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "string"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(!string_empty(last) && string_equal(first.c_str(), "editor_float")) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "string"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(!string_empty(last) && string_equal(first.c_str(), "editor_snd")) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "sound"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(!string_empty(last) && string_equal(first.c_str(), "editor_bool")) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "boolean"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(!string_empty(last) && string_equal(first.c_str(), "editor_int")) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "integer"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(!string_empty(last) && string_equal(first.c_str(), "editor_model")) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "model"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(!string_empty(last) && string_equal(first.c_str(), "editor_color")) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "color"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(!string_empty(last) && (string_equal(first.c_str(), "editor_material") || string_equal(first.c_str(), "editor_mat"))) - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; - attribute.m_type = "shader"; - currentDescription = &attribute.m_description; - currentString = &description; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); - } - else if(string_equal(key, "inherit")) - { - entityClass.inheritanceResolved = false; - ASSERT_MESSAGE(entityClass.m_parent.empty(), "only one 'inherit' supported per entityDef"); - const char* token; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); - entityClass.m_parent.push_back(token); - } - // begin quake4-specific keys - else if(string_equal(key, "editor_targetonsel")) - { - //const char* value = - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - } - else if(string_equal(key, "editor_menu")) - { - //const char* value = - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - } - else if(string_equal(key, "editor_ignore")) - { - //const char* value = - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - } - // end quake4-specific keys - // begin ignore prey (unknown/unused?) entity keys - else if(string_equal(key, "editor_light") - || string_equal(key, "editor_def def_debrisspawner") - || string_equal(key, "editor_def def_drop") - || string_equal(key, "editor_def def_guihand") - || string_equal(key, "editor_def def_mine")) - { - //const char* value = - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); - } - // end ignore prey entity keys - else - { - CopiedString tmp(key); - ASSERT_MESSAGE(!string_equal_n(key, "editor_", 7), "unsupported editor key: " << makeQuoted(key)); - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, key).second; - attribute.m_type = "string"; - const char* value; - PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); - if(string_equal(value, "}")) // hack for quake4 powerups.def bug - { - globalErrorStream() << "entityDef " << makeQuoted(entityClass.m_name.c_str()) << " key " << makeQuoted(tmp.c_str()) << " has no value\n"; - break; - } - else - { - attribute.m_value = value; - } - } - tokeniser.nextLine(); - } - - entityClass.m_comments = usage.c_str(); - - if(string_equal(entityClass.m_name.c_str(), "light")) - { - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "light_radius").second; - attribute.m_type = "vector3"; - attribute.m_value = "300 300 300"; - } - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "light_center").second; - attribute.m_type = "vector3"; - } - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "noshadows").second; - attribute.m_type = "boolean"; - attribute.m_value = "0"; - } - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "nospecular").second; - attribute.m_type = "boolean"; - attribute.m_value = "0"; - } - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "nodiffuse").second; - attribute.m_type = "boolean"; - attribute.m_value = "0"; - } - { - EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "falloff").second; - attribute.m_type = "real"; - } - } - - return true; -} - -bool EntityClassDoom3_parseEntityDef(Tokeniser& tokeniser) -{ - EntityClass* entityClass = Eclass_Alloc(); - entityClass->free = &Eclass_Free; - - if(!EntityClass_parse(*entityClass, tokeniser)) - { - eclass_capture_state(entityClass); // finish constructing the entity so that it can be destroyed cleanly. - entityClass->free(entityClass); - return false; - } - - EntityClass* inserted = EntityClassDoom3_insertUnique(entityClass); - if(inserted != entityClass) - { - globalErrorStream() << "entityDef " << entityClass->name() << " is already defined, second definition ignored\n"; - eclass_capture_state(entityClass); // finish constructing the entity so that it can be destroyed cleanly. - entityClass->free(entityClass); - } - return true; -} - -bool EntityClassDoom3_parseBlock(Tokeniser& tokeniser, const char* blockType) -{ - if(string_equal(blockType, "entityDef")) - { - return EntityClassDoom3_parseEntityDef(tokeniser); - } - else if(string_equal(blockType, "model")) - { - return EntityClassDoom3_parseModel(tokeniser); - } - else - { - return EntityClassDoom3_parseUnknown(tokeniser); - } -} - -bool EntityClassDoom3_parse(TextInputStream& inputStream, const char* filename) -{ - Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser(inputStream); - - tokeniser.nextLine(); - - for(;;) - { - const char* blockType = tokeniser.getToken(); - if(blockType == 0) - { - return true; - } - CopiedString tmp(blockType); - if(!EntityClassDoom3_parseBlock(tokeniser, tmp.c_str())) - { - globalErrorStream() << GlobalFileSystem().findFile(filename) << filename << ":" << (unsigned int)tokeniser.getLine() << ": " << tmp.c_str() << " parse failed, skipping rest of file\n"; - return false; - } - } - - tokeniser.release(); -} - - -void EntityClassDoom3_loadFile(const char* filename) -{ - globalOutputStream() << "parsing entity classes from " << makeQuoted(filename) << "\n"; - - StringOutputStream fullname(256); - fullname << "def/" << filename; - - ArchiveTextFile* file = GlobalFileSystem().openTextFile(fullname.c_str()); - if(file != 0) - { - EntityClassDoom3_parse(file->getInputStream(), fullname.c_str()); - file->release(); - } -} - -EntityClass* EntityClassDoom3_findOrInsert(const char *name, bool has_brushes) -{ - ASSERT_NOTNULL(name); - - if(string_empty(name)) - { - return g_EntityClassDoom3_bad; - } - - EntityClasses::iterator i = g_EntityClassDoom3_classes.find(name); - if(i != g_EntityClassDoom3_classes.end() - //&& string_equal((*i).first, name) - ) - { - return (*i).second; - } - - EntityClass* e = EntityClass_Create_Default(name, has_brushes); - EntityClass* inserted = EntityClassDoom3_insertUnique(e); - ASSERT_MESSAGE(inserted == e, ""); - return inserted; -} - -const ListAttributeType* EntityClassDoom3_findListType(const char* name) -{ - return 0; -} - - -void EntityClass_resolveInheritance(EntityClass* derivedClass) -{ - if(derivedClass->inheritanceResolved == false) - { - derivedClass->inheritanceResolved = true; - EntityClasses::iterator i = g_EntityClassDoom3_classes.find(derivedClass->m_parent.front().c_str()); - if(i == g_EntityClassDoom3_classes.end()) - { - globalErrorStream() << "failed to find entityDef " << makeQuoted(derivedClass->m_parent.front().c_str()) << " inherited by " << makeQuoted(derivedClass->m_name.c_str()) << "\n"; - } - else - { - EntityClass* parentClass = (*i).second; - EntityClass_resolveInheritance(parentClass); - if(!derivedClass->colorSpecified) - { - derivedClass->colorSpecified = parentClass->colorSpecified; - derivedClass->color = parentClass->color; - } - if(!derivedClass->sizeSpecified) - { - derivedClass->sizeSpecified = parentClass->sizeSpecified; - derivedClass->mins = parentClass->mins; - derivedClass->maxs = parentClass->maxs; - derivedClass->fixedsize = parentClass->fixedsize; - } - - for(EntityClassAttributes::iterator j = parentClass->m_attributes.begin(); j != parentClass->m_attributes.end(); ++j) - { - EntityClass_insertAttribute(*derivedClass, (*j).first.c_str(), (*j).second); - } - } - } -} - -class EntityClassDoom3 : public ModuleObserver -{ - std::size_t m_unrealised; - ModuleObservers m_observers; -public: - EntityClassDoom3() : m_unrealised(2) - { - } - void realise() - { - if(--m_unrealised == 0) - { - globalOutputStream() << "searching vfs directory " << makeQuoted("def") << " for *.def\n"; - GlobalFileSystem().forEachFile("def/", "def", FreeCaller1()); - - { - for(Models::iterator i = g_models.begin(); i != g_models.end(); ++i) - { - Model_resolveInheritance((*i).first.c_str(), (*i).second); - } - } - { - for(EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i) - { - EntityClass_resolveInheritance((*i).second); - if(!string_empty((*i).second->m_modelpath.c_str())) - { - Models::iterator j = g_models.find((*i).second->m_modelpath); - if(j != g_models.end()) - { - (*i).second->m_modelpath = (*j).second.m_mesh; - (*i).second->m_skin = (*j).second.m_skin; - } - } - eclass_capture_state((*i).second); - - StringOutputStream usage(256); - - usage << "-------- NOTES --------\n"; - - if(!string_empty((*i).second->m_comments.c_str())) - { - usage << (*i).second->m_comments.c_str() << "\n"; - } - - usage << "\n-------- KEYS --------\n"; - - for(EntityClassAttributes::iterator j = (*i).second->m_attributes.begin(); j != (*i).second->m_attributes.end(); ++j) - { - const char* name = EntityClassAttributePair_getName(*j); - const char* description = EntityClassAttributePair_getDescription(*j); - if(!string_equal(name, description)) - { - usage << EntityClassAttributePair_getName(*j) << " : " << EntityClassAttributePair_getDescription(*j) << "\n"; - } - } - - (*i).second->m_comments = usage.c_str(); - } - } - - m_observers.realise(); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - m_observers.unrealise(); - EntityClassDoom3_clear(); - } - } - void attach(ModuleObserver& observer) - { - m_observers.attach(observer); - } - void detach(ModuleObserver& observer) - { - m_observers.detach(observer); - } -}; - -EntityClassDoom3 g_EntityClassDoom3; - -void EntityClassDoom3_attach(ModuleObserver& observer) -{ - g_EntityClassDoom3.attach(observer); -} -void EntityClassDoom3_detach(ModuleObserver& observer) -{ - g_EntityClassDoom3.detach(observer); -} - -void EntityClassDoom3_realise() -{ - g_EntityClassDoom3.realise(); -} -void EntityClassDoom3_unrealise() -{ - g_EntityClassDoom3.unrealise(); -} - -void EntityClassDoom3_construct() -{ - GlobalFileSystem().attach(g_EntityClassDoom3); - - // start by creating the default unknown eclass - g_EntityClassDoom3_bad = EClass_Create("UNKNOWN_CLASS", Vector3(0.0f, 0.5f, 0.0f), ""); - - EntityClassDoom3_realise(); -} - -void EntityClassDoom3_destroy() -{ - EntityClassDoom3_unrealise(); - - g_EntityClassDoom3_bad->free(g_EntityClassDoom3_bad); - - GlobalFileSystem().detach(g_EntityClassDoom3); -} - -class EntityClassDoom3Dependencies : public GlobalFileSystemModuleRef, public GlobalShaderCacheModuleRef -{ -}; - -class EntityClassDoom3API -{ - EntityClassManager m_eclassmanager; -public: - typedef EntityClassManager Type; - STRING_CONSTANT(Name, "doom3"); - - EntityClassDoom3API() - { - EntityClassDoom3_construct(); - - m_eclassmanager.findOrInsert = &EntityClassDoom3_findOrInsert; - m_eclassmanager.findListType = &EntityClassDoom3_findListType; - m_eclassmanager.forEach = &EntityClassDoom3_forEach; - m_eclassmanager.attach = &EntityClassDoom3_attach; - m_eclassmanager.detach = &EntityClassDoom3_detach; - m_eclassmanager.realise = &EntityClassDoom3_realise; - m_eclassmanager.unrealise = &EntityClassDoom3_unrealise; - } - ~EntityClassDoom3API() - { - EntityClassDoom3_destroy(); - } - EntityClassManager* getTable() - { - return &m_eclassmanager; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule EntityClassDoom3Module; -typedef Static StaticEntityClassDoom3Module; -StaticRegisterModule staticRegisterEntityClassDoom3(StaticEntityClassDoom3Module::instance()); diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_doom3.h b/misc/mediasource/extra/netradiant-src/radiant/eclass_doom3.h deleted file mode 100644 index 7c8169cb..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_doom3.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ECLASS_DOOM3_H) -#define INCLUDED_ECLASS_DOOM3_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_fgd.cpp b/misc/mediasource/extra/netradiant-src/radiant/eclass_fgd.cpp deleted file mode 100644 index 6d5fb663..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_fgd.cpp +++ /dev/null @@ -1,807 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "eclass_fgd.h" - -#include "debugging/debugging.h" - -#include - -#include "ifilesystem.h" -#include "iscriplib.h" -#include "qerplugin.h" - -#include "string/string.h" -#include "eclasslib.h" -#include "os/path.h" -#include "os/dir.h" -#include "stream/stringstream.h" -#include "moduleobservers.h" -#include "stringio.h" -#include "stream/textfilestream.h" - -namespace -{ - typedef std::map EntityClasses; - EntityClasses g_EntityClassFGD_classes; - typedef std::map BaseClasses; - BaseClasses g_EntityClassFGD_bases; - EntityClass *g_EntityClassFGD_bad = 0; - typedef std::map ListAttributeTypes; - ListAttributeTypes g_listTypesFGD; -} - - -void EntityClassFGD_clear() -{ - for(BaseClasses::iterator i = g_EntityClassFGD_bases.begin(); i != g_EntityClassFGD_bases.end(); ++i) - { - (*i).second->free((*i).second); - } - g_EntityClassFGD_bases.clear(); - g_listTypesFGD.clear(); -} - -EntityClass* EntityClassFGD_insertUniqueBase(EntityClass* entityClass) -{ - std::pair result = g_EntityClassFGD_bases.insert(BaseClasses::value_type(entityClass->name(), entityClass)); - if(!result.second) - { - globalErrorStream() << "duplicate base class: " << makeQuoted(entityClass->name()) << "\n"; - //eclass_capture_state(entityClass); - //entityClass->free(entityClass); - } - return (*result.first).second; -} - -EntityClass* EntityClassFGD_insertUnique(EntityClass* entityClass) -{ - EntityClassFGD_insertUniqueBase(entityClass); - std::pair result = g_EntityClassFGD_classes.insert(EntityClasses::value_type(entityClass->name(), entityClass)); - if(!result.second) - { - globalErrorStream() << "duplicate entity class: " << makeQuoted(entityClass->name()) << "\n"; - eclass_capture_state(entityClass); - entityClass->free(entityClass); - } - return (*result.first).second; -} - -void EntityClassFGD_forEach(EntityClassVisitor& visitor) -{ - for(EntityClasses::iterator i = g_EntityClassFGD_classes.begin(); i != g_EntityClassFGD_classes.end(); ++i) - { - visitor.visit((*i).second); - } -} - -inline bool EntityClassFGD_parseToken(Tokeniser& tokeniser, const char* token) -{ - return string_equal(tokeniser.getToken(), token); -} - -#define PARSE_ERROR "error parsing entity class definition" - -void EntityClassFGD_parseSplitString(Tokeniser& tokeniser, CopiedString& string) -{ - StringOutputStream buffer(256); - for(;;) - { - buffer << tokeniser.getToken(); - if(!string_equal(tokeniser.getToken(), "+")) - { - tokeniser.ungetToken(); - string = buffer.c_str(); - return; - } - } -} - -void EntityClassFGD_parseClass(Tokeniser& tokeniser, bool fixedsize, bool isBase) -{ - EntityClass* entityClass = Eclass_Alloc(); - entityClass->free = &Eclass_Free; - entityClass->fixedsize = fixedsize; - entityClass->inheritanceResolved = false; - entityClass->mins = Vector3(-8, -8, -8); - entityClass->maxs = Vector3(8, 8, 8); - - for(;;) - { - const char* property = tokeniser.getToken(); - if(string_equal(property, "=")) - { - break; - } - else if(string_equal(property, "base")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - for(;;) - { - const char* base = tokeniser.getToken(); - if(string_equal(base, ")")) - { - break; - } - else if(!string_equal(base, ",")) - { - entityClass->m_parent.push_back(base); - } - } - } - else if(string_equal(property, "size")) - { - entityClass->sizeSpecified = true; - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - Tokeniser_getFloat(tokeniser, entityClass->mins.x()); - Tokeniser_getFloat(tokeniser, entityClass->mins.y()); - Tokeniser_getFloat(tokeniser, entityClass->mins.z()); - const char* token = tokeniser.getToken(); - if(string_equal(token, ",")) - { - Tokeniser_getFloat(tokeniser, entityClass->maxs.x()); - Tokeniser_getFloat(tokeniser, entityClass->maxs.y()); - Tokeniser_getFloat(tokeniser, entityClass->maxs.z()); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - else - { - entityClass->maxs = entityClass->mins; - vector3_negate(entityClass->mins); - ASSERT_MESSAGE(string_equal(token, ")"), ""); - } - } - else if(string_equal(property, "color")) - { - entityClass->colorSpecified = true; - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - Tokeniser_getFloat(tokeniser, entityClass->color.x()); - entityClass->color.x() /= 256.0; - Tokeniser_getFloat(tokeniser, entityClass->color.y()); - entityClass->color.y() /= 256.0; - Tokeniser_getFloat(tokeniser, entityClass->color.z()); - entityClass->color.z() /= 256.0; - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - else if(string_equal(property, "iconsprite")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - StringOutputStream buffer(256); - buffer << PathCleaned(tokeniser.getToken()); - entityClass->m_modelpath = buffer.c_str(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - else if(string_equal(property, "sprite") - || string_equal(property, "decal") - // hl2 below - || string_equal(property, "overlay") - || string_equal(property, "light") - || string_equal(property, "keyframe") - || string_equal(property, "animator") - || string_equal(property, "quadbounds")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - // hl2 below - else if(string_equal(property, "sphere") - || string_equal(property, "sweptplayerhull") - || string_equal(property, "studio") - || string_equal(property, "studioprop") - || string_equal(property, "lightprop") - || string_equal(property, "lightcone") - || string_equal(property, "sidelist")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - if(string_equal(tokeniser.getToken(), ")")) - { - tokeniser.ungetToken(); - } - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - else if(string_equal(property, "line") - || string_equal(property, "cylinder")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - //const char* r = - tokeniser.getToken(); - //const char* g = - tokeniser.getToken(); - //const char* b = - tokeniser.getToken(); - for(;;) - { - if(string_equal(tokeniser.getToken(), ")")) - { - tokeniser.ungetToken(); - break; - } - //const char* name = - tokeniser.getToken(); - } - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - else if(string_equal(property, "wirebox")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - //const char* mins = - tokeniser.getToken(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ","), PARSE_ERROR); - //const char* maxs = - tokeniser.getToken(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - else if(string_equal(property, "halfgridsnap")) - { - } - else - { - ERROR_MESSAGE(PARSE_ERROR); - } - } - - entityClass->m_name = tokeniser.getToken(); - - if(!isBase) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); - - EntityClassFGD_parseSplitString(tokeniser, entityClass->m_comments); - } - - tokeniser.nextLine(); - - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "["), PARSE_ERROR); - - tokeniser.nextLine(); - - for(;;) - { - CopiedString key = tokeniser.getToken(); - if(string_equal(key.c_str(), "]")) - { - tokeniser.nextLine(); - break; - } - - if(string_equal_nocase(key.c_str(), "input") - || string_equal_nocase(key.c_str(), "output")) - { - const char* name = tokeniser.getToken(); - if(!string_equal(name, "(")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - //const char* type = - tokeniser.getToken(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - const char* descriptionSeparator = tokeniser.getToken(); - if(string_equal(descriptionSeparator, ":")) - { - CopiedString description; - EntityClassFGD_parseSplitString(tokeniser, description); - } - else - { - tokeniser.ungetToken(); - } - tokeniser.nextLine(); - continue; - } - } - - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - CopiedString type = tokeniser.getToken(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - - if(string_equal_nocase(type.c_str(), "flags")) - { - EntityClassAttribute attribute; - - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "="), PARSE_ERROR); - tokeniser.nextLine(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "["), PARSE_ERROR); - tokeniser.nextLine(); - for(;;) - { - const char* flag = tokeniser.getToken(); - if(string_equal(flag, "]")) - { - tokeniser.nextLine(); - break; - } - else - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); - //const char* name = - tokeniser.getToken(); - { - const char* defaultSeparator = tokeniser.getToken(); - if(string_equal(defaultSeparator, ":")) - { - tokeniser.getToken(); - { - const char* descriptionSeparator = tokeniser.getToken(); - if(string_equal(descriptionSeparator, ":")) - { - EntityClassFGD_parseSplitString(tokeniser, attribute.m_description); - } - else - { - tokeniser.ungetToken(); - } - } - } - else - { - tokeniser.ungetToken(); - } - } - } - tokeniser.nextLine(); - } - EntityClass_insertAttribute(*entityClass, key.c_str(), attribute); - } - else if(string_equal_nocase(type.c_str(), "choices")) - { - EntityClassAttribute attribute; - - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); - attribute.m_name = tokeniser.getToken(); - const char* valueSeparator = tokeniser.getToken(); - if(string_equal(valueSeparator, ":")) - { - const char* value = tokeniser.getToken(); - if(!string_equal(value, ":")) - { - attribute.m_value = value; - } - else - { - tokeniser.ungetToken(); - } - { - const char* descriptionSeparator = tokeniser.getToken(); - if(string_equal(descriptionSeparator, ":")) - { - EntityClassFGD_parseSplitString(tokeniser, attribute.m_description); - } - else - { - tokeniser.ungetToken(); - } - } - } - else - { - tokeniser.ungetToken(); - } - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "="), PARSE_ERROR); - tokeniser.nextLine(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "["), PARSE_ERROR); - tokeniser.nextLine(); - - StringOutputStream listTypeName(64); - listTypeName << entityClass->m_name.c_str() << "_" << attribute.m_name.c_str(); - attribute.m_type = listTypeName.c_str(); - - ListAttributeType& listType = g_listTypesFGD[listTypeName.c_str()]; - - for(;;) - { - const char* value = tokeniser.getToken(); - if(string_equal(value, "]")) - { - tokeniser.nextLine(); - break; - } - else - { - CopiedString tmp(value); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); - const char* name = tokeniser.getToken(); - listType.push_back(name, tmp.c_str()); - } - tokeniser.nextLine(); - } - - for(ListAttributeType::const_iterator i = listType.begin(); i != listType.end(); ++i) - { - if(string_equal(attribute.m_value.c_str(), (*i).first.c_str())) - { - attribute.m_value = (*i).second.c_str(); - } - } - - EntityClass_insertAttribute(*entityClass, key.c_str(), attribute); - } - else if(string_equal_nocase(type.c_str(), "decal")) - { - } - else if(string_equal_nocase(type.c_str(), "string") - || string_equal_nocase(type.c_str(), "integer") - || string_equal_nocase(type.c_str(), "studio") - || string_equal_nocase(type.c_str(), "sprite") - || string_equal_nocase(type.c_str(), "color255") - || string_equal_nocase(type.c_str(), "target_source") - || string_equal_nocase(type.c_str(), "target_destination") - || string_equal_nocase(type.c_str(), "sound") - // hl2 below - || string_equal_nocase(type.c_str(), "angle") - || string_equal_nocase(type.c_str(), "origin") - || string_equal_nocase(type.c_str(), "float") - || string_equal_nocase(type.c_str(), "node_dest") - || string_equal_nocase(type.c_str(), "filterclass") - || string_equal_nocase(type.c_str(), "vector") - || string_equal_nocase(type.c_str(), "sidelist") - || string_equal_nocase(type.c_str(), "material") - || string_equal_nocase(type.c_str(), "vecline") - || string_equal_nocase(type.c_str(), "axis") - || string_equal_nocase(type.c_str(), "npcclass") - || string_equal_nocase(type.c_str(), "target_name_or_class") - || string_equal_nocase(type.c_str(), "pointentityclass") - || string_equal_nocase(type.c_str(), "scene")) - { - if(!string_equal(tokeniser.getToken(), "readonly")) - { - tokeniser.ungetToken(); - } - - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); - const char* attributeType = "string"; - if(string_equal_nocase(type.c_str(), "studio")) - { - attributeType = "model"; - } - - EntityClassAttribute attribute; - attribute.m_type = attributeType; - attribute.m_name = tokeniser.getToken(); - - const char* defaultSeparator = tokeniser.getToken(); - if(string_equal(defaultSeparator, ":")) - { - const char* value = tokeniser.getToken(); - if(!string_equal(value, ":")) - { - attribute.m_value = value; - } - else - { - tokeniser.ungetToken(); - } - - { - const char* descriptionSeparator = tokeniser.getToken(); - if(string_equal(descriptionSeparator, ":")) - { - EntityClassFGD_parseSplitString(tokeniser, attribute.m_description); - } - else - { - tokeniser.ungetToken(); - } - } - } - else - { - tokeniser.ungetToken(); - } - EntityClass_insertAttribute(*entityClass, key.c_str(), attribute); - } - else - { - ERROR_MESSAGE("unknown key type: " << makeQuoted(type.c_str())); - } - tokeniser.nextLine(); - } - - if(isBase) - { - EntityClassFGD_insertUniqueBase(entityClass); - } - else - { - EntityClassFGD_insertUnique(entityClass); - } -} - -void EntityClassFGD_loadFile(const char* filename); - -void EntityClassFGD_parse(TextInputStream& inputStream, const char* path) -{ - Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser(inputStream); - - tokeniser.nextLine(); - - for(;;) - { - const char* blockType = tokeniser.getToken(); - if(blockType == 0) - { - break; - } - if(string_equal(blockType, "@SolidClass")) - { - EntityClassFGD_parseClass(tokeniser, false, false); - } - else if(string_equal(blockType, "@BaseClass")) - { - EntityClassFGD_parseClass(tokeniser, false, true); - } - else if(string_equal(blockType, "@PointClass") - // hl2 below - || string_equal(blockType, "@KeyFrameClass") - || string_equal(blockType, "@MoveClass") - || string_equal(blockType, "@FilterClass") - || string_equal(blockType, "@NPCClass")) - { - EntityClassFGD_parseClass(tokeniser, true, false); - } - // hl2 below - else if(string_equal(blockType, "@include")) - { - StringOutputStream includePath(256); - includePath << StringRange(path, path_get_filename_start(path)); - includePath << tokeniser.getToken(); - EntityClassFGD_loadFile(includePath.c_str()); - } - else if(string_equal(blockType, "@mapsize")) - { - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); - //const char* min = - tokeniser.getToken(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ","), PARSE_ERROR); - //const char* max = - tokeniser.getToken(); - ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); - } - else - { - ERROR_MESSAGE("unknown block type: " << makeQuoted(blockType)); - } - } - - tokeniser.release(); -} - - -void EntityClassFGD_loadFile(const char* filename) -{ - TextFileInputStream file(filename); - if(!file.failed()) - { - globalOutputStream() << "parsing entity classes from " << makeQuoted(filename) << "\n"; - - EntityClassFGD_parse(file, filename); - } -} - -EntityClass* EntityClassFGD_findOrInsert(const char *name, bool has_brushes) -{ - ASSERT_NOTNULL(name); - - if(string_empty(name)) - { - return g_EntityClassFGD_bad; - } - - EntityClasses::iterator i = g_EntityClassFGD_classes.find(name); - if(i != g_EntityClassFGD_classes.end() - //&& string_equal((*i).first, name) - ) - { - return (*i).second; - } - - EntityClass* e = EntityClass_Create_Default(name, has_brushes); - return EntityClassFGD_insertUnique(e); -} - -const ListAttributeType* EntityClassFGD_findListType(const char *name) -{ - ListAttributeTypes::iterator i = g_listTypesFGD.find(name); - if(i != g_listTypesFGD.end()) - { - return &(*i).second; - } - return 0; - -} - - -void EntityClassFGD_resolveInheritance(EntityClass* derivedClass) -{ - if(derivedClass->inheritanceResolved == false) - { - derivedClass->inheritanceResolved = true; - for(StringList::iterator j = derivedClass->m_parent.begin(); j != derivedClass->m_parent.end(); ++j) - { - BaseClasses::iterator i = g_EntityClassFGD_bases.find((*j).c_str()); - if(i == g_EntityClassFGD_bases.end()) - { - globalErrorStream() << "failed to find entityDef " << makeQuoted((*j).c_str()) << " inherited by " << makeQuoted(derivedClass->m_name.c_str()) << "\n"; - } - else - { - EntityClass* parentClass = (*i).second; - EntityClassFGD_resolveInheritance(parentClass); - if(!derivedClass->colorSpecified) - { - derivedClass->colorSpecified = parentClass->colorSpecified; - derivedClass->color = parentClass->color; - } - if(!derivedClass->sizeSpecified) - { - derivedClass->sizeSpecified = parentClass->sizeSpecified; - derivedClass->mins = parentClass->mins; - derivedClass->maxs = parentClass->maxs; - } - - for(EntityClassAttributes::iterator k = parentClass->m_attributes.begin(); k != parentClass->m_attributes.end(); ++k) - { - EntityClass_insertAttribute(*derivedClass, (*k).first.c_str(), (*k).second); - } - } - } - } -} - -class EntityClassFGD : public ModuleObserver -{ - std::size_t m_unrealised; - ModuleObservers m_observers; -public: - EntityClassFGD() : m_unrealised(3) - { - } - void realise() - { - if(--m_unrealised == 0) - { - StringOutputStream filename(256); - filename << GlobalRadiant().getGameToolsPath() << GlobalRadiant().getGameName() << "/halflife.fgd"; - EntityClassFGD_loadFile(filename.c_str()); - - { - for(EntityClasses::iterator i = g_EntityClassFGD_classes.begin(); i != g_EntityClassFGD_classes.end(); ++i) - { - EntityClassFGD_resolveInheritance((*i).second); - if((*i).second->fixedsize && string_empty((*i).second->m_modelpath.c_str())) - { - if(!(*i).second->sizeSpecified) - { - globalErrorStream() << "size not specified for entity class: " << makeQuoted((*i).second->m_name.c_str()) << '\n'; - } - if(!(*i).second->colorSpecified) - { - globalErrorStream() << "color not specified for entity class: " << makeQuoted((*i).second->m_name.c_str()) << '\n'; - } - } - } - } - { - for(BaseClasses::iterator i = g_EntityClassFGD_bases.begin(); i != g_EntityClassFGD_bases.end(); ++i) - { - eclass_capture_state((*i).second); - } - } - - m_observers.realise(); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - m_observers.unrealise(); - EntityClassFGD_clear(); - } - } - void attach(ModuleObserver& observer) - { - m_observers.attach(observer); - } - void detach(ModuleObserver& observer) - { - m_observers.detach(observer); - } -}; - -EntityClassFGD g_EntityClassFGD; - -void EntityClassFGD_attach(ModuleObserver& observer) -{ - g_EntityClassFGD.attach(observer); -} -void EntityClassFGD_detach(ModuleObserver& observer) -{ - g_EntityClassFGD.detach(observer); -} - -void EntityClassFGD_realise() -{ - g_EntityClassFGD.realise(); -} -void EntityClassFGD_unrealise() -{ - g_EntityClassFGD.unrealise(); -} - -void EntityClassFGD_construct() -{ - // start by creating the default unknown eclass - g_EntityClassFGD_bad = EClass_Create("UNKNOWN_CLASS", Vector3(0.0f, 0.5f, 0.0f), ""); - - EntityClassFGD_realise(); -} - -void EntityClassFGD_destroy() -{ - EntityClassFGD_unrealise(); - - g_EntityClassFGD_bad->free(g_EntityClassFGD_bad); -} - -class EntityClassFGDDependencies : public GlobalFileSystemModuleRef, public GlobalShaderCacheModuleRef, public GlobalRadiantModuleRef -{ -}; - -class EntityClassFGDAPI -{ - EntityClassManager m_eclassmanager; -public: - typedef EntityClassManager Type; - STRING_CONSTANT(Name, "halflife"); - - EntityClassFGDAPI() - { - EntityClassFGD_construct(); - - m_eclassmanager.findOrInsert = &EntityClassFGD_findOrInsert; - m_eclassmanager.findListType = &EntityClassFGD_findListType; - m_eclassmanager.forEach = &EntityClassFGD_forEach; - m_eclassmanager.attach = &EntityClassFGD_attach; - m_eclassmanager.detach = &EntityClassFGD_detach; - m_eclassmanager.realise = &EntityClassFGD_realise; - m_eclassmanager.unrealise = &EntityClassFGD_unrealise; - - GlobalRadiant().attachGameToolsPathObserver(g_EntityClassFGD); - GlobalRadiant().attachGameNameObserver(g_EntityClassFGD); - } - ~EntityClassFGDAPI() - { - GlobalRadiant().detachGameNameObserver(g_EntityClassFGD); - GlobalRadiant().detachGameToolsPathObserver(g_EntityClassFGD); - - EntityClassFGD_destroy(); - } - EntityClassManager* getTable() - { - return &m_eclassmanager; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule EntityClassFGDModule; -typedef Static StaticEntityClassFGDModule; -StaticRegisterModule staticRegisterEntityClassFGD(StaticEntityClassFGDModule::instance()); diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_fgd.h b/misc/mediasource/extra/netradiant-src/radiant/eclass_fgd.h deleted file mode 100644 index f8540b39..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_fgd.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ECLASS_FGD_H) -#define INCLUDED_ECLASS_FGD_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_xml.cpp b/misc/mediasource/extra/netradiant-src/radiant/eclass_xml.cpp deleted file mode 100644 index 5195b4e7..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_xml.cpp +++ /dev/null @@ -1,610 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 -*/ - -///\file -///\brief EntityClass plugin that supports the .ent xml entity-definition format. -/// -/// the .ent xml format expresses entity-definitions. -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// the attributes of an entity type are defined like this: -/// -/// <[name of attribute type] -/// key="[entity key name]" -/// name="[name shown in gui]" -/// value="[default entity key value]" -/// >[comment text shown in gui] -/// -/// each attribute type has a specialised attribute-editor GUI -/// -/// currently-supported attribute types: -/// -/// string a string -/// array an array of strings - value is a semi-colon-delimited string -/// integer an integer value -/// boolean an integer - shows as a checkbox - true = non-zero -/// integer2 two integer values -/// integer3 three integer values -/// real3 three floating-point values -/// angle specialisation of real - Yaw angle -/// direction specialisation of real - Yaw angle, -1 = down, -2 = up -/// angles specialisation of real3 - Pitch Yaw Roll -/// color specialisation of real3 - RGB floating-point colour -/// target a string that uniquely identifies an entity or group of entities -/// targetname a string that uniquely identifies an entity or group of entities -/// sound the VFS path to a sound file -/// texture the VFS path to a texture file or a shader name -/// model the VFS path to a model file -/// skin the VFS path to a skin file -/// -/// -/// flag attributes define a flag in the "spawnflags" key: -/// -/// [comment text shown in gui] -/// -/// the default value for a flag bit is always 0. -/// -/// -/// List attributes have a set of valid values. -/// Create new list attribute types like this: -/// -/// -/// -/// -/// -/// -/// these can then be used as attribute types. -/// -/// -/// An attribute definition should specify a default value that corresponds -/// with the default value given by the game. If the default value is not -/// specified in the attribute definition, it is assumed to be an empty string. -/// -/// If the currently-selected entity in Radiant does not specify a value for -/// the key of an attribute, the default value from the attribute-definition -/// will be displayed in the attribute-editor and used when visualising the -/// entity in the preview windows. E.g. the Doom3 "light" entity has a -/// "light_radius" key. Light entities without a "light_radius" key are -/// displayed in Doom3 with a radius of 300. The default value for the -/// "light_radius" attribute definition should be specified as "300 300 300". -/// - - - - -#include "eclass_xml.h" - -#include "ieclass.h" -#include "irender.h" -#include "ifilesystem.h" -#include "iarchive.h" - -#include "xml/xmlparser.h" -#include "generic/object.h" -#include "generic/reference.h" -#include "stream/stringstream.h" -#include "stream/textfilestream.h" -#include "os/path.h" -#include "eclasslib.h" -#include "modulesystem/moduleregistry.h" -#include "stringio.h" - -#define PARSE_ERROR(elementName, name) makeQuoted(elementName) << " is not a valid child of " << makeQuoted(name) - -class IgnoreBreaks -{ -public: - const char* m_first; - const char* m_last; - IgnoreBreaks(const char* first, const char* last) : m_first(first), m_last(last) - { - } -}; - -template -TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const IgnoreBreaks& ignoreBreaks) -{ - for(const char* i = ignoreBreaks.m_first; i != ignoreBreaks.m_last; ++i) - { - if(*i != '\n') - { - ostream << *i; - } - } - return ostream; -} - -namespace -{ - -class TreeXMLImporter : public TextOutputStream -{ -public: - virtual TreeXMLImporter& pushElement(const XMLElement& element) = 0; - virtual void popElement(const char* name) = 0; -}; - -template -class Storage -{ - char m_storage[sizeof(Type)]; -public: - Type& get() - { - return *reinterpret_cast(m_storage); - } - const Type& get() const - { - return *reinterpret_cast(m_storage); - } -}; - -class BreakImporter : public TreeXMLImporter -{ -public: - BreakImporter(StringOutputStream& comment) - { - comment << '\n'; - } - static const char* name() - { - return "n"; - } - TreeXMLImporter& pushElement(const XMLElement& element) - { - ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); - return *this; - } - void popElement(const char* elementName) - { - ERROR_MESSAGE(PARSE_ERROR(elementName, name())); - } - std::size_t write(const char* data, std::size_t length) - { - return length; - } -}; - -class AttributeImporter : public TreeXMLImporter -{ - StringOutputStream& m_comment; - -public: - AttributeImporter(StringOutputStream& comment, EntityClass* entityClass, const XMLElement& element) : m_comment(comment) - { - const char* type = element.name(); - const char* key = element.attribute("key"); - const char* name = element.attribute("name"); - const char* value = element.attribute("value"); - - ASSERT_MESSAGE(!string_empty(key), "key attribute not specified"); - ASSERT_MESSAGE(!string_empty(name), "name attribute not specified"); - - if(string_equal(type, "flag")) - { - std::size_t bit = atoi(element.attribute("bit")); - ASSERT_MESSAGE(bit < MAX_FLAGS, "invalid flag bit"); - ASSERT_MESSAGE(string_empty(entityClass->flagnames[bit]), "non-unique flag bit"); - strcpy(entityClass->flagnames[bit], key); - } - - m_comment << key; - m_comment << " : "; - - EntityClass_insertAttribute(*entityClass, key, EntityClassAttribute(type, name, value)); - } - ~AttributeImporter() - { - } - TreeXMLImporter& pushElement(const XMLElement& element) - { - ERROR_MESSAGE(PARSE_ERROR(element.name(), "attribute")); - return *this; - } - void popElement(const char* elementName) - { - ERROR_MESSAGE(PARSE_ERROR(elementName, "attribute")); - } - std::size_t write(const char* data, std::size_t length) - { - return m_comment.write(data, length); - } -}; - -bool attributeSupported(const char* name) -{ - return string_equal(name, "real") - || string_equal(name, "integer") - || string_equal(name, "boolean") - || string_equal(name, "string") - || string_equal(name, "array") - || string_equal(name, "flag") - || string_equal(name, "real3") - || string_equal(name, "integer3") - || string_equal(name, "direction") - || string_equal(name, "angle") - || string_equal(name, "angles") - || string_equal(name, "color") - || string_equal(name, "target") - || string_equal(name, "targetname") - || string_equal(name, "sound") - || string_equal(name, "texture") - || string_equal(name, "model") - || string_equal(name, "skin") - || string_equal(name, "integer2"); -} - -typedef std::map ListAttributeTypes; - -bool listAttributeSupported(ListAttributeTypes& listTypes, const char* name) -{ - return listTypes.find(name) != listTypes.end(); -} - - -class ClassImporter : public TreeXMLImporter -{ - EntityClassCollector& m_collector; - EntityClass* m_eclass; - StringOutputStream m_comment; - Storage m_attribute; - ListAttributeTypes& m_listTypes; - -public: - ClassImporter(EntityClassCollector& collector, ListAttributeTypes& listTypes, const XMLElement& element) : m_collector(collector), m_listTypes(listTypes) - { - m_eclass = Eclass_Alloc(); - m_eclass->free = &Eclass_Free; - - const char* name = element.attribute("name"); - ASSERT_MESSAGE(!string_empty(name), "name attribute not specified for class"); - m_eclass->m_name = name; - - const char* color = element.attribute("color"); - ASSERT_MESSAGE(!string_empty(name), "color attribute not specified for class " << name); - string_parse_vector3(color, m_eclass->color); - eclass_capture_state(m_eclass); - - const char* model = element.attribute("model"); - if(!string_empty(model)) - { - StringOutputStream buffer(256); - buffer << PathCleaned(model); - m_eclass->m_modelpath = buffer.c_str(); - } - - const char* type = element.name(); - if(string_equal(type, "point")) - { - const char* box = element.attribute("box"); - ASSERT_MESSAGE(!string_empty(box), "box attribute not found for class " << name); - m_eclass->fixedsize = true; - string_parse_vector(box, &m_eclass->mins.x(), &m_eclass->mins.x() + 6); - } - } - ~ClassImporter() - { - m_eclass->m_comments = m_comment.c_str(); - m_collector.insert(m_eclass); - - for(ListAttributeTypes::iterator i = m_listTypes.begin(); i != m_listTypes.end(); ++i) - { - m_collector.insert((*i).first.c_str(), (*i).second); - } - } - static const char* name() - { - return "class"; - } - TreeXMLImporter& pushElement(const XMLElement& element) - { - if(attributeSupported(element.name()) || listAttributeSupported(m_listTypes, element.name())) - { - constructor(m_attribute.get(), makeReference(m_comment), m_eclass, element); - return m_attribute.get(); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); - return *this; - } - } - void popElement(const char* elementName) - { - if(attributeSupported(elementName) || listAttributeSupported(m_listTypes, elementName)) - { - destructor(m_attribute.get()); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(elementName, name())); - } - } - std::size_t write(const char* data, std::size_t length) - { - return m_comment.write(data, length); - } -}; - -class ItemImporter : public TreeXMLImporter -{ -public: - ItemImporter(ListAttributeType& list, const XMLElement& element) - { - const char* name = element.attribute("name"); - const char* value = element.attribute("value"); - list.push_back(name, value); - } - TreeXMLImporter& pushElement(const XMLElement& element) - { - ERROR_MESSAGE(PARSE_ERROR(element.name(), "item")); - return *this; - } - void popElement(const char* elementName) - { - ERROR_MESSAGE(PARSE_ERROR(elementName, "item")); - } - std::size_t write(const char* data, std::size_t length) - { - return length; - } -}; - -bool isItem(const char* name) -{ - return string_equal(name, "item"); -} - -class ListAttributeImporter : public TreeXMLImporter -{ - ListAttributeType* m_listType; - Storage m_item; -public: - ListAttributeImporter(ListAttributeTypes& listTypes, const XMLElement& element) - { - const char* name = element.attribute("name"); - m_listType = &listTypes[name]; - } - TreeXMLImporter& pushElement(const XMLElement& element) - { - if(isItem(element.name())) - { - constructor(m_item.get(), makeReference(*m_listType), element); - return m_item.get(); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(element.name(), "list")); - return *this; - } - } - void popElement(const char* elementName) - { - if(isItem(elementName)) - { - destructor(m_item.get()); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(elementName, "list")); - } - } - std::size_t write(const char* data, std::size_t length) - { - return length; - } -}; - -bool classSupported(const char* name) -{ - return string_equal(name, "group") - || string_equal(name, "point"); -} - -bool listSupported(const char* name) -{ - return string_equal(name, "list"); -} - -class ClassesImporter : public TreeXMLImporter -{ - EntityClassCollector& m_collector; - Storage m_class; - Storage m_list; - ListAttributeTypes m_listTypes; - -public: - ClassesImporter(EntityClassCollector& collector) : m_collector(collector) - { - } - static const char* name() - { - return "classes"; - } - TreeXMLImporter& pushElement(const XMLElement& element) - { - if(classSupported(element.name())) - { - constructor(m_class.get(), makeReference(m_collector), makeReference(m_listTypes), element); - return m_class.get(); - } - else if(listSupported(element.name())) - { - constructor(m_list.get(), makeReference(m_listTypes), element); - return m_list.get(); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); - return *this; - } - } - void popElement(const char* elementName) - { - if(classSupported(elementName)) - { - destructor(m_class.get()); - } - else if(listSupported(elementName)) - { - destructor(m_list.get()); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(elementName, name())); - } - } - std::size_t write(const char* data, std::size_t length) - { - return length; - } -}; - -class EclassXMLImporter : public TreeXMLImporter -{ - EntityClassCollector& m_collector; - Storage m_classes; - -public: - EclassXMLImporter(EntityClassCollector& collector) : m_collector(collector) - { - } - static const char* name() - { - return "classes"; - } - TreeXMLImporter& pushElement(const XMLElement& element) - { - if(string_equal(element.name(), ClassesImporter::name())) - { - constructor(m_classes.get(), makeReference(m_collector)); - return m_classes.get(); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); - return *this; - } - } - void popElement(const char* elementName) - { - if(string_equal(elementName, ClassesImporter::name())) - { - destructor(m_classes.get()); - } - else - { - ERROR_MESSAGE(PARSE_ERROR(elementName, name())); - } - } - std::size_t write(const char* data, std::size_t length) - { - return length; - } -}; - -class TreeXMLImporterStack : public XMLImporter -{ - std::vector< Reference > m_importers; -public: - TreeXMLImporterStack(TreeXMLImporter& importer) - { - m_importers.push_back(makeReference(importer)); - } - void pushElement(const XMLElement& element) - { - m_importers.push_back(makeReference(m_importers.back().get().pushElement(element))); - } - void popElement(const char* name) - { - m_importers.pop_back(); - m_importers.back().get().popElement(name); - } - std::size_t write(const char* buffer, std::size_t length) - { - return m_importers.back().get().write(buffer, length); - } -}; - - - -const char* GetExtension() -{ - return "ent"; -} -void ScanFile(EntityClassCollector& collector, const char *filename) -{ - TextFileInputStream inputFile(filename); - if(!inputFile.failed()) - { - XMLStreamParser parser(inputFile); - - EclassXMLImporter importer(collector); - TreeXMLImporterStack stack(importer); - parser.exportXML(stack); - } -} - - -} - -#include "modulesystem/singletonmodule.h" - -class EntityClassXMLDependencies : public GlobalFileSystemModuleRef, public GlobalShaderCacheModuleRef -{ -}; - -class EclassXMLAPI -{ - EntityClassScanner m_eclassxml; -public: - typedef EntityClassScanner Type; - STRING_CONSTANT(Name, "xml"); - - EclassXMLAPI() - { - m_eclassxml.scanFile = &ScanFile; - m_eclassxml.getExtension = &GetExtension; - } - EntityClassScanner* getTable() - { - return &m_eclassxml; - } -}; - -typedef SingletonModule EclassXMLModule; -typedef Static StaticEclassXMLModule; -StaticRegisterModule staticRegisterEclassXML(StaticEclassXMLModule::instance()); diff --git a/misc/mediasource/extra/netradiant-src/radiant/eclass_xml.h b/misc/mediasource/extra/netradiant-src/radiant/eclass_xml.h deleted file mode 100644 index 7884d0e8..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/eclass_xml.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ECLASS_XML_H) -#define INCLUDED_ECLASS_XML_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/entity.cpp b/misc/mediasource/extra/netradiant-src/radiant/entity.cpp deleted file mode 100644 index 9478bda2..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/entity.cpp +++ /dev/null @@ -1,665 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "entity.h" - -#include "ientity.h" -#include "iselection.h" -#include "imodel.h" -#include "ifilesystem.h" -#include "iundo.h" -#include "editable.h" - -#include "eclasslib.h" -#include "scenelib.h" -#include "os/path.h" -#include "os/file.h" -#include "stream/stringstream.h" -#include "stringio.h" - -#include "gtkutil/filechooser.h" -#include "gtkmisc.h" -#include "select.h" -#include "map.h" -#include "preferences.h" -#include "gtkdlgs.h" -#include "mainframe.h" -#include "qe3.h" -#include "commands.h" - -struct entity_globals_t -{ - Vector3 color_entity; - - entity_globals_t() : - color_entity(0.0f, 0.0f, 0.0f) - { - } -}; - -entity_globals_t g_entity_globals; - -class EntitySetKeyValueSelected : public scene::Graph::Walker -{ - const char* m_key; - const char* m_value; -public: - EntitySetKeyValueSelected(const char* key, const char* value) - : m_key(key), m_value(value) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && (instance.childSelected() || Instance_getSelectable(instance)->isSelected())) - { - entity->setKeyValue(m_key, m_value); - } - } -}; - -class EntitySetClassnameSelected : public scene::Graph::Walker -{ - const char* m_classname; -public: - EntitySetClassnameSelected(const char* classname) - : m_classname(classname) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && (instance.childSelected() || Instance_getSelectable(instance)->isSelected())) - { - NodeSmartReference node(GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert(m_classname, node_is_group(path.top())))); - - EntityCopyingVisitor visitor(*Node_getEntity(node)); - - entity->forEachKeyValue(visitor); - - NodeSmartReference child(path.top().get()); - NodeSmartReference parent(path.parent().get()); - Node_getTraversable(parent)->erase(child); - if(Node_getTraversable(child) != 0 - && Node_getTraversable(node) != 0 - && node_is_group(node)) - { - parentBrushes(child, node); - } - Node_getTraversable(parent)->insert(node); - } - } -}; - -void Scene_EntitySetKeyValue_Selected(const char* key, const char* value) -{ - GlobalSceneGraph().traverse(EntitySetKeyValueSelected(key, value)); -} - -void Scene_EntitySetClassname_Selected(const char* classname) -{ - GlobalSceneGraph().traverse(EntitySetClassnameSelected(classname)); -} - - -void Entity_ungroupSelected() -{ - if (GlobalSelectionSystem().countSelected() < 1) return; - - UndoableCommand undo("ungroupSelectedEntities"); - - scene::Path world_path(makeReference(GlobalSceneGraph().root())); - world_path.push(makeReference(Map_FindOrInsertWorldspawn(g_map))); - - scene::Instance &instance = GlobalSelectionSystem().ultimateSelected(); - scene::Path path = instance.path(); - - if (!Node_isEntity(path.top())) path.pop(); - - if(Node_getEntity(path.top()) != 0 - && node_is_group(path.top())) - { - if(world_path.top().get_pointer() != path.top().get_pointer()) - { - parentBrushes(path.top(), world_path.top()); - Path_deleteTop(path); - } - } -} - - -class EntityFindSelected : public scene::Graph::Walker -{ -public: - mutable const scene::Path *groupPath; - mutable scene::Instance *groupInstance; - EntityFindSelected(): groupPath(0), groupInstance(0) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && Instance_getSelectable(instance)->isSelected() - && node_is_group(path.top()) - && !groupPath) - { - groupPath = &path; - groupInstance = &instance; - } - } -}; - -class EntityGroupSelected : public scene::Graph::Walker -{ - NodeSmartReference group, worldspawn; - //typedef std::pair DeletionPair; - //Stack deleteme; - public: - EntityGroupSelected(const scene::Path &p): group(p.top().get()), worldspawn(Map_FindOrInsertWorldspawn(g_map)) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - Selectable *selectable = Instance_getSelectable(instance); - if(selectable && selectable->isSelected()) - { - Entity* entity = Node_getEntity(path.top()); - if(entity == 0 && Node_isPrimitive(path.top())) - { - NodeSmartReference child(path.top().get()); - NodeSmartReference parent(path.parent().get()); - - if(path.size() >= 3 && parent != worldspawn) - { - NodeSmartReference parentparent(path[path.size() - 3].get()); - - Node_getTraversable(parent)->erase(child); - Node_getTraversable(group)->insert(child); - - if(Node_getTraversable(parent)->empty()) - { - //deleteme.push(DeletionPair(parentparent, parent)); - Node_getTraversable(parentparent)->erase(parent); - } - } - else - { - Node_getTraversable(parent)->erase(child); - Node_getTraversable(group)->insert(child); - } - } - } - } -}; - -void Entity_groupSelected() -{ - if (GlobalSelectionSystem().countSelected() < 1) return; - - UndoableCommand undo("groupSelectedEntities"); - - scene::Path world_path(makeReference(GlobalSceneGraph().root())); - world_path.push(makeReference(Map_FindOrInsertWorldspawn(g_map))); - - EntityFindSelected fse; - GlobalSceneGraph().traverse(fse); - if(fse.groupPath) - { - GlobalSceneGraph().traverse(EntityGroupSelected(*fse.groupPath)); - } - else - { - GlobalSceneGraph().traverse(EntityGroupSelected(world_path)); - } -} - - - -void Entity_connectSelected() -{ - if(GlobalSelectionSystem().countSelected() == 2) - { - GlobalEntityCreator().connectEntities( - GlobalSelectionSystem().penultimateSelected().path(), - GlobalSelectionSystem().ultimateSelected().path(), - 0 - ); - } - else - { - globalErrorStream() << "entityConnectSelected: exactly two instances must be selected\n"; - } -} - -void Entity_killconnectSelected() -{ - if(GlobalSelectionSystem().countSelected() == 2) - { - GlobalEntityCreator().connectEntities( - GlobalSelectionSystem().penultimateSelected().path(), - GlobalSelectionSystem().ultimateSelected().path(), - 1 - ); - } - else - { - globalErrorStream() << "entityKillConnectSelected: exactly two instances must be selected\n"; - } -} - -AABB Doom3Light_getBounds(const AABB& workzone) -{ - AABB aabb(workzone); - - Vector3 defaultRadius(300, 300, 300); - if(!string_parse_vector3(EntityClass_valueForKey(*GlobalEntityClassManager().findOrInsert("light", false), "light_radius"), defaultRadius)) - { - globalErrorStream() << "Doom3Light_getBounds: failed to parse default light radius\n"; - } - - if(aabb.extents[0] == 0) - { - aabb.extents[0] = defaultRadius[0]; - } - if(aabb.extents[1] == 0) - { - aabb.extents[1] = defaultRadius[1]; - } - if(aabb.extents[2] == 0) - { - aabb.extents[2] = defaultRadius[2]; - } - - if(aabb_valid(aabb)) - { - return aabb; - } - return AABB(Vector3(0, 0, 0), Vector3(64, 64, 64)); -} - -int g_iLastLightIntensity; - -void Entity_createFromSelection(const char* name, const Vector3& origin) -{ -#if 0 - if(string_equal_nocase(name, "worldspawn")) - { - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "Can't create an entity with worldspawn.", "info"); - return; - } -#endif - - EntityClass* entityClass = GlobalEntityClassManager().findOrInsert(name, true); - - bool isModel = (string_compare_nocase_n(name, "misc_", 5) == 0 && string_equal_nocase(name + string_length(name) - 5, "model")) // misc_*model (also misc_model) - || string_equal_nocase(name, "model_static") - || (GlobalSelectionSystem().countSelected() == 0 && string_equal_nocase(name, "func_static")); - - bool brushesSelected = Scene_countSelectedBrushes(GlobalSceneGraph()) != 0; - - if(!(entityClass->fixedsize || isModel) && !brushesSelected) - { - globalErrorStream() << "failed to create a group entity - no brushes are selected\n"; - return; - } - - AABB workzone(aabb_for_minmax(Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max)); - - - NodeSmartReference node(GlobalEntityCreator().createEntity(entityClass)); - - Node_getTraversable(GlobalSceneGraph().root())->insert(node); - - scene::Path entitypath(makeReference(GlobalSceneGraph().root())); - entitypath.push(makeReference(node.get())); - scene::Instance& instance = findInstance(entitypath); - - if(entityClass->fixedsize || (isModel && !brushesSelected)) - { - Select_Delete(); - - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - transform->setType(TRANSFORM_PRIMITIVE); - transform->setTranslation(origin); - transform->freezeTransform(); - } - - GlobalSelectionSystem().setSelectedAll(false); - - Instance_setSelected(instance, true); - } - else - { - if (g_pGameDescription->mGameType == "doom3") - { - Node_getEntity(node)->setKeyValue("model", Node_getEntity(node)->getKeyValue("name")); - } - - Scene_parentSelectedBrushesToEntity(GlobalSceneGraph(), node); - Scene_forEachChildSelectable(SelectableSetSelected(true), instance.path()); - } - - // tweaking: when right clic dropping a light entity, ask for light value in a custom dialog box - // see SF bug 105383 - - if (g_pGameDescription->mGameType == "hl") - { - // FIXME - Hydra: really we need a combined light AND color dialog for halflife. - if (string_equal_nocase(name, "light") - || string_equal_nocase(name, "light_environment") - || string_equal_nocase(name, "light_spot")) - { - int intensity = g_iLastLightIntensity; - - if (DoLightIntensityDlg (&intensity) == eIDOK) - { - g_iLastLightIntensity = intensity; - char buf[30]; - sprintf( buf, "255 255 255 %d", intensity ); - Node_getEntity(node)->setKeyValue("_light", buf); - } - } - } - else if(string_equal_nocase(name, "light")) - { - if(g_pGameDescription->mGameType != "doom3") - { - int intensity = g_iLastLightIntensity; - - if (DoLightIntensityDlg (&intensity) == eIDOK) - { - g_iLastLightIntensity = intensity; - char buf[10]; - sprintf( buf, "%d", intensity ); - Node_getEntity(node)->setKeyValue("light", buf); - } - } - else if(brushesSelected) // use workzone to set light position/size for doom3 lights, if there are brushes selected - { - AABB bounds(Doom3Light_getBounds(workzone)); - StringOutputStream key(64); - key << bounds.origin[0] << " " << bounds.origin[1] << " " << bounds.origin[2]; - Node_getEntity(node)->setKeyValue("origin", key.c_str()); - key.clear(); - key << bounds.extents[0] << " " << bounds.extents[1] << " " << bounds.extents[2]; - Node_getEntity(node)->setKeyValue("light_radius", key.c_str()); - } - } - - if(isModel) - { - const char* model = misc_model_dialog(GTK_WIDGET(MainFrame_getWindow())); - if(model != 0) - { - Node_getEntity(node)->setKeyValue("model", model); - } - } -} - -#if 0 -bool DoNormalisedColor(Vector3& color) -{ - if(!color_dialog(GTK_WIDGET(MainFrame_getWindow()), color)) - return false; - /* - ** scale colors so that at least one component is at 1.0F - */ - - float largest = 0.0F; - - if ( color[0] > largest ) - largest = color[0]; - if ( color[1] > largest ) - largest = color[1]; - if ( color[2] > largest ) - largest = color[2]; - - if ( largest == 0.0F ) - { - color[0] = 1.0F; - color[1] = 1.0F; - color[2] = 1.0F; - } - else - { - float scaler = 1.0F / largest; - - color[0] *= scaler; - color[1] *= scaler; - color[2] *= scaler; - } - - return true; -} -#endif - -void NormalizeColor(Vector3& color) -{ - // scale colors so that at least one component is at 1.0F - - float largest = 0.0F; - - if ( color[0] > largest ) - largest = color[0]; - if ( color[1] > largest ) - largest = color[1]; - if ( color[2] > largest ) - largest = color[2]; - - if ( largest == 0.0F ) - { - color[0] = 1.0F; - color[1] = 1.0F; - color[2] = 1.0F; - } - else - { - float scaler = 1.0F / largest; - - color[0] *= scaler; - color[1] *= scaler; - color[2] *= scaler; - } -} - -void Entity_normalizeColor() -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); - Entity* entity = Node_getEntity(path.top()); - - if(entity != 0) - { - const char* strColor = entity->getKeyValue("_color"); - if(!string_empty(strColor)) - { - Vector3 rgb; - if (string_parse_vector3(strColor, rgb)) - { - g_entity_globals.color_entity = rgb; - NormalizeColor(g_entity_globals.color_entity); - - char buffer[128]; - sprintf(buffer, "%g %g %g", g_entity_globals.color_entity[0], - g_entity_globals.color_entity[1], - g_entity_globals.color_entity[2]); - - Scene_EntitySetKeyValue_Selected("_color", buffer); - } - } - } - } -} - -void Entity_setColour() -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - bool normalize = false; - const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); - Entity* entity = Node_getEntity(path.top()); - - if(entity != 0) - { - const char* strColor = entity->getKeyValue("_color"); - if(!string_empty(strColor)) - { - Vector3 rgb; - if (string_parse_vector3(strColor, rgb)) - { - g_entity_globals.color_entity = rgb; - } - } - - if( g_pGameDescription->mGameType == "doom3" ) - normalize = false; - - if(color_dialog(GTK_WIDGET(MainFrame_getWindow()), g_entity_globals.color_entity)) - { - if( normalize ) - NormalizeColor(g_entity_globals.color_entity); - - char buffer[128]; - sprintf(buffer, "%g %g %g", g_entity_globals.color_entity[0], - g_entity_globals.color_entity[1], - g_entity_globals.color_entity[2]); - - Scene_EntitySetKeyValue_Selected("_color", buffer); - } - } - } -} - -const char* misc_model_dialog(GtkWidget* parent) -{ - StringOutputStream buffer(1024); - - buffer << g_qeglobals.m_userGamePath.c_str() << "models/"; - - if(!file_readable(buffer.c_str())) - { - // just go to fsmain - buffer.clear(); - buffer << g_qeglobals.m_userGamePath.c_str() << "/"; - } - - const char *filename = file_dialog (parent, TRUE, "Choose Model", buffer.c_str(), ModelLoader::Name()); - if (filename != 0) - { - // use VFS to get the correct relative path - const char* relative = path_make_relative(filename, GlobalFileSystem().findRoot(filename)); - if(relative == filename) - { - globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n"; - } - return relative; - } - return 0; -} - -void LightRadiiImport(EntityCreator& self, bool value) -{ - self.setLightRadii(value); -} -typedef ReferenceCaller1 LightRadiiImportCaller; - -void LightRadiiExport(EntityCreator& self, const BoolImportCallback& importer) -{ - importer(self.getLightRadii()); -} -typedef ReferenceCaller1 LightRadiiExportCaller; - -void Entity_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox( - "Show", "Light Radii", - LightRadiiImportCaller(GlobalEntityCreator()), - LightRadiiExportCaller(GlobalEntityCreator()) - ); -} -void Entity_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Entities", "Entity Display Preferences")); - Entity_constructPreferences(page); -} -void Entity_registerPreferencesPage() -{ - PreferencesDialog_addDisplayPage(FreeCaller1()); -} - - - -void Entity_constructMenu(GtkMenu* menu) -{ - create_menu_item_with_mnemonic(menu, "_Regroup", "GroupSelection"); - create_menu_item_with_mnemonic(menu, "_Ungroup", "UngroupSelection"); - create_menu_item_with_mnemonic(menu, "_Connect", "ConnectSelection"); - create_menu_item_with_mnemonic(menu, "_KillConnect", "KillConnectSelection"); - create_menu_item_with_mnemonic(menu, "_Select Color...", "EntityColor"); - create_menu_item_with_mnemonic(menu, "_Normalize Color...", "NormalizeColor"); -} - - - -#include "preferencesystem.h" -#include "stringio.h" - -void Entity_Construct() -{ - GlobalCommands_insert("EntityColor", FreeCaller(), Accelerator('K')); - GlobalCommands_insert("NormalizeColor", FreeCaller()); - GlobalCommands_insert("ConnectSelection", FreeCaller(), Accelerator('K', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("KillConnectSelection", FreeCaller(), Accelerator('K', (GdkModifierType)(GDK_SHIFT_MASK))); - GlobalCommands_insert("GroupSelection", FreeCaller()); - GlobalCommands_insert("UngroupSelection", FreeCaller()); - - GlobalPreferenceSystem().registerPreference("SI_Colors5", Vector3ImportStringCaller(g_entity_globals.color_entity), Vector3ExportStringCaller(g_entity_globals.color_entity)); - GlobalPreferenceSystem().registerPreference("LastLightIntensity", IntImportStringCaller(g_iLastLightIntensity), IntExportStringCaller(g_iLastLightIntensity)); - - Entity_registerPreferencesPage(); -} - -void Entity_Destroy() -{ -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/entity.h b/misc/mediasource/extra/netradiant-src/radiant/entity.h deleted file mode 100644 index 3e962178..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/entity.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_ENTITY_H) -#define INCLUDED_ENTITY_H - -template class BasicVector3; -typedef BasicVector3 Vector3; -void Entity_createFromSelection(const char* name, const Vector3& origin); - -void Scene_EntitySetKeyValue_Selected(const char* key, const char* value); -void Scene_EntitySetClassname_Selected(const char* classname); - - -typedef struct _GtkWidget GtkWidget; -const char* misc_model_dialog(GtkWidget* parent); - -typedef struct _GtkMenu GtkMenu; -void Entity_constructMenu(GtkMenu* menu); - -void Entity_Construct(); -void Entity_Destroy(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/entityinspector.cpp b/misc/mediasource/extra/netradiant-src/radiant/entityinspector.cpp deleted file mode 100644 index b5636780..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/entityinspector.cpp +++ /dev/null @@ -1,1762 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "entityinspector.h" - -#include "debugging/debugging.h" - -#include "ientity.h" -#include "ifilesystem.h" -#include "imodel.h" -#include "iscenegraph.h" -#include "iselection.h" -#include "iundo.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#include "os/path.h" -#include "eclasslib.h" -#include "scenelib.h" -#include "generic/callback.h" -#include "os/file.h" -#include "stream/stringstream.h" -#include "moduleobserver.h" -#include "convert.h" -#include "stringio.h" - -#include "gtkutil/accelerator.h" -#include "gtkutil/dialog.h" -#include "gtkutil/filechooser.h" -#include "gtkutil/messagebox.h" -#include "gtkutil/nonmodal.h" -#include "gtkutil/button.h" -#include "gtkutil/entry.h" -#include "gtkutil/container.h" - -#include "qe3.h" -#include "gtkmisc.h" -#include "gtkdlgs.h" -#include "entity.h" -#include "mainframe.h" -#include "textureentry.h" - -GtkEntry* numeric_entry_new() -{ - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_widget_set_size_request(GTK_WIDGET(entry), 64, -1); - return entry; -} - -namespace -{ - typedef std::map KeyValues; - KeyValues g_selectedKeyValues; - KeyValues g_selectedDefaultKeyValues; -} - -const char* SelectedEntity_getValueForKey(const char* key) -{ - { - KeyValues::const_iterator i = g_selectedKeyValues.find(key); - if(i != g_selectedKeyValues.end()) - { - return (*i).second.c_str(); - } - } - { - KeyValues::const_iterator i = g_selectedDefaultKeyValues.find(key); - if(i != g_selectedDefaultKeyValues.end()) - { - return (*i).second.c_str(); - } - } - return ""; -} - -void Scene_EntitySetKeyValue_Selected_Undoable(const char* key, const char* value) -{ - StringOutputStream command(256); - command << "entitySetKeyValue -key " << makeQuoted(key) << " -value " << makeQuoted(value); - UndoableCommand undo(command.c_str()); - Scene_EntitySetKeyValue_Selected(key, value); -} - -class EntityAttribute -{ -public: - virtual GtkWidget* getWidget() const = 0; - virtual void update() = 0; - virtual void release() = 0; -}; - -class BooleanAttribute : public EntityAttribute -{ - CopiedString m_key; - GtkCheckButton* m_check; - - static gboolean toggled(GtkWidget *widget, BooleanAttribute* self) - { - self->apply(); - return FALSE; - } -public: - BooleanAttribute(const char* key) : - m_key(key), - m_check(0) - { - GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new()); - gtk_widget_show(GTK_WIDGET(check)); - - m_check = check; - - guint handler = g_signal_connect(G_OBJECT(check), "toggled", G_CALLBACK(toggled), this); - g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler)); - - update(); - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_check); - } - void release() - { - delete this; - } - void apply() - { - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_check)) ? "1" : "0"); - } - typedef MemberCaller ApplyCaller; - - void update() - { - const char* value = SelectedEntity_getValueForKey(m_key.c_str()); - if(!string_empty(value)) - { - toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(m_check), atoi(value) != 0); - } - else - { - toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(m_check), false); - } - } - typedef MemberCaller UpdateCaller; -}; - - -class StringAttribute : public EntityAttribute -{ - CopiedString m_key; - GtkEntry* m_entry; - NonModalEntry m_nonModal; -public: - StringAttribute(const char* key) : - m_key(key), - m_entry(0), - m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_widget_set_size_request(GTK_WIDGET(entry), 50, -1); - - m_entry = entry; - m_nonModal.connect(m_entry); - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_entry); - } - GtkEntry* getEntry() const - { - return m_entry; - } - - void release() - { - delete this; - } - void apply() - { - StringOutputStream value(64); - value << gtk_entry_get_text(m_entry); - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), value.c_str()); - } - typedef MemberCaller ApplyCaller; - - void update() - { - StringOutputStream value(64); - value << SelectedEntity_getValueForKey(m_key.c_str()); - gtk_entry_set_text(m_entry, value.c_str()); - } - typedef MemberCaller UpdateCaller; -}; - -class ShaderAttribute : public StringAttribute -{ -public: - ShaderAttribute(const char* key) : StringAttribute(key) - { - GlobalShaderEntryCompletion::instance().connect(StringAttribute::getEntry()); - } -}; - - -class ModelAttribute : public EntityAttribute -{ - CopiedString m_key; - BrowsedPathEntry m_entry; - NonModalEntry m_nonModal; -public: - ModelAttribute(const char* key) : - m_key(key), - m_entry(BrowseCaller(*this)), - m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) - { - m_nonModal.connect(m_entry.m_entry.m_entry); - } - void release() - { - delete this; - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_entry.m_entry.m_frame); - } - void apply() - { - StringOutputStream value(64); - value << gtk_entry_get_text(GTK_ENTRY(m_entry.m_entry.m_entry)); - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), value.c_str()); - } - typedef MemberCaller ApplyCaller; - void update() - { - StringOutputStream value(64); - value << SelectedEntity_getValueForKey(m_key.c_str()); - gtk_entry_set_text(GTK_ENTRY(m_entry.m_entry.m_entry), value.c_str()); - } - typedef MemberCaller UpdateCaller; - void browse(const BrowsedPathEntry::SetPathCallback& setPath) - { - const char *filename = misc_model_dialog(gtk_widget_get_toplevel(GTK_WIDGET(m_entry.m_entry.m_frame))); - - if(filename != 0) - { - setPath(filename); - apply(); - } - } - typedef MemberCaller1 BrowseCaller; -}; - -const char* browse_sound(GtkWidget* parent) -{ - StringOutputStream buffer(1024); - - buffer << g_qeglobals.m_userGamePath.c_str() << "sound/"; - - if(!file_readable(buffer.c_str())) - { - // just go to fsmain - buffer.clear(); - buffer << g_qeglobals.m_userGamePath.c_str() << "/"; - } - - const char* filename = file_dialog(parent, TRUE, "Open Wav File", buffer.c_str(), "sound"); - if(filename != 0) - { - const char* relative = path_make_relative(filename, GlobalFileSystem().findRoot(filename)); - if(relative == filename) - { - globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n"; - } - return relative; - } - return filename; -} - -class SoundAttribute : public EntityAttribute -{ - CopiedString m_key; - BrowsedPathEntry m_entry; - NonModalEntry m_nonModal; -public: - SoundAttribute(const char* key) : - m_key(key), - m_entry(BrowseCaller(*this)), - m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) - { - m_nonModal.connect(m_entry.m_entry.m_entry); - } - void release() - { - delete this; - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_entry.m_entry.m_frame); - } - void apply() - { - StringOutputStream value(64); - value << gtk_entry_get_text(GTK_ENTRY(m_entry.m_entry.m_entry)); - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), value.c_str()); - } - typedef MemberCaller ApplyCaller; - void update() - { - StringOutputStream value(64); - value << SelectedEntity_getValueForKey(m_key.c_str()); - gtk_entry_set_text(GTK_ENTRY(m_entry.m_entry.m_entry), value.c_str()); - } - typedef MemberCaller UpdateCaller; - void browse(const BrowsedPathEntry::SetPathCallback& setPath) - { - const char *filename = browse_sound(gtk_widget_get_toplevel(GTK_WIDGET(m_entry.m_entry.m_frame))); - - if(filename != 0) - { - setPath(filename); - apply(); - } - } - typedef MemberCaller1 BrowseCaller; -}; - -inline double angle_normalised(double angle) -{ - return float_mod(angle, 360.0); -} - -class AngleAttribute : public EntityAttribute -{ - CopiedString m_key; - GtkEntry* m_entry; - NonModalEntry m_nonModal; -public: - AngleAttribute(const char* key) : - m_key(key), - m_entry(0), - m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) - { - GtkEntry* entry = numeric_entry_new(); - m_entry = entry; - m_nonModal.connect(m_entry); - } - void release() - { - delete this; - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_entry); - } - void apply() - { - StringOutputStream angle(32); - angle << angle_normalised(entry_get_float(m_entry)); - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), angle.c_str()); - } - typedef MemberCaller ApplyCaller; - - void update() - { - const char* value = SelectedEntity_getValueForKey(m_key.c_str()); - if(!string_empty(value)) - { - StringOutputStream angle(32); - angle << angle_normalised(atof(value)); - gtk_entry_set_text(m_entry, angle.c_str()); - } - else - { - gtk_entry_set_text(m_entry, "0"); - } - } - typedef MemberCaller UpdateCaller; -}; - -namespace -{ - typedef const char* String; - const String buttons[] = { "up", "down", "z-axis" }; -} - -class DirectionAttribute : public EntityAttribute -{ - CopiedString m_key; - GtkEntry* m_entry; - NonModalEntry m_nonModal; - RadioHBox m_radio; - NonModalRadio m_nonModalRadio; - GtkHBox* m_hbox; -public: - DirectionAttribute(const char* key) : - m_key(key), - m_entry(0), - m_nonModal(ApplyCaller(*this), UpdateCaller(*this)), - m_radio(RadioHBox_new(STRING_ARRAY_RANGE(buttons))), - m_nonModalRadio(ApplyRadioCaller(*this)) - { - GtkEntry* entry = numeric_entry_new(); - m_entry = entry; - m_nonModal.connect(m_entry); - - m_nonModalRadio.connect(m_radio.m_radio); - - m_hbox = GTK_HBOX(gtk_hbox_new(FALSE, 4)); - gtk_widget_show(GTK_WIDGET(m_hbox)); - - gtk_box_pack_start(GTK_BOX(m_hbox), GTK_WIDGET(m_radio.m_hbox), TRUE, TRUE, 0); - gtk_box_pack_start(GTK_BOX(m_hbox), GTK_WIDGET(m_entry), TRUE, TRUE, 0); - } - void release() - { - delete this; - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_hbox); - } - void apply() - { - StringOutputStream angle(32); - angle << angle_normalised(entry_get_float(m_entry)); - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), angle.c_str()); - } - typedef MemberCaller ApplyCaller; - - void update() - { - const char* value = SelectedEntity_getValueForKey(m_key.c_str()); - if(!string_empty(value)) - { - float f = float(atof(value)); - if(f == -1) - { - gtk_widget_set_sensitive(GTK_WIDGET(m_entry), FALSE); - radio_button_set_active_no_signal(m_radio.m_radio, 0); - gtk_entry_set_text(m_entry, ""); - } - else if(f == -2) - { - gtk_widget_set_sensitive(GTK_WIDGET(m_entry), FALSE); - radio_button_set_active_no_signal(m_radio.m_radio, 1); - gtk_entry_set_text(m_entry, ""); - } - else - { - gtk_widget_set_sensitive(GTK_WIDGET(m_entry), TRUE); - radio_button_set_active_no_signal(m_radio.m_radio, 2); - StringOutputStream angle(32); - angle << angle_normalised(f); - gtk_entry_set_text(m_entry, angle.c_str()); - } - } - else - { - gtk_entry_set_text(m_entry, "0"); - } - } - typedef MemberCaller UpdateCaller; - - void applyRadio() - { - int index = radio_button_get_active(m_radio.m_radio); - if(index == 0) - { - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), "-1"); - } - else if(index == 1) - { - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), "-2"); - } - else if(index == 2) - { - apply(); - } - } - typedef MemberCaller ApplyRadioCaller; -}; - - -class AnglesEntry -{ -public: - GtkEntry* m_roll; - GtkEntry* m_pitch; - GtkEntry* m_yaw; - AnglesEntry() : m_roll(0), m_pitch(0), m_yaw(0) - { - } -}; - -typedef BasicVector3 DoubleVector3; - -class AnglesAttribute : public EntityAttribute -{ - CopiedString m_key; - AnglesEntry m_angles; - NonModalEntry m_nonModal; - GtkBox* m_hbox; -public: - AnglesAttribute(const char* key) : - m_key(key), - m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) - { - m_hbox = GTK_BOX(gtk_hbox_new(TRUE, 4)); - gtk_widget_show(GTK_WIDGET(m_hbox)); - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); - m_angles.m_pitch = entry; - m_nonModal.connect(m_angles.m_pitch); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); - m_angles.m_yaw = entry; - m_nonModal.connect(m_angles.m_yaw); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); - m_angles.m_roll = entry; - m_nonModal.connect(m_angles.m_roll); - } - } - void release() - { - delete this; - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_hbox); - } - void apply() - { - StringOutputStream angles(64); - angles << angle_normalised(entry_get_float(m_angles.m_pitch)) - << " " << angle_normalised(entry_get_float(m_angles.m_yaw)) - << " " << angle_normalised(entry_get_float(m_angles.m_roll)); - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), angles.c_str()); - } - typedef MemberCaller ApplyCaller; - - void update() - { - StringOutputStream angle(32); - const char* value = SelectedEntity_getValueForKey(m_key.c_str()); - if(!string_empty(value)) - { - DoubleVector3 pitch_yaw_roll; - if(!string_parse_vector3(value, pitch_yaw_roll)) - { - pitch_yaw_roll = DoubleVector3(0, 0, 0); - } - - angle << angle_normalised(pitch_yaw_roll.x()); - gtk_entry_set_text(m_angles.m_pitch, angle.c_str()); - angle.clear(); - - angle << angle_normalised(pitch_yaw_roll.y()); - gtk_entry_set_text(m_angles.m_yaw, angle.c_str()); - angle.clear(); - - angle << angle_normalised(pitch_yaw_roll.z()); - gtk_entry_set_text(m_angles.m_roll, angle.c_str()); - angle.clear(); - } - else - { - gtk_entry_set_text(m_angles.m_pitch, "0"); - gtk_entry_set_text(m_angles.m_yaw, "0"); - gtk_entry_set_text(m_angles.m_roll, "0"); - } - } - typedef MemberCaller UpdateCaller; -}; - -class Vector3Entry -{ -public: - GtkEntry* m_x; - GtkEntry* m_y; - GtkEntry* m_z; - Vector3Entry() : m_x(0), m_y(0), m_z(0) - { - } -}; - -class Vector3Attribute : public EntityAttribute -{ - CopiedString m_key; - Vector3Entry m_vector3; - NonModalEntry m_nonModal; - GtkBox* m_hbox; -public: - Vector3Attribute(const char* key) : - m_key(key), - m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) - { - m_hbox = GTK_BOX(gtk_hbox_new(TRUE, 4)); - gtk_widget_show(GTK_WIDGET(m_hbox)); - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); - m_vector3.m_x = entry; - m_nonModal.connect(m_vector3.m_x); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); - m_vector3.m_y = entry; - m_nonModal.connect(m_vector3.m_y); - } - { - GtkEntry* entry = numeric_entry_new(); - gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); - m_vector3.m_z = entry; - m_nonModal.connect(m_vector3.m_z); - } - } - void release() - { - delete this; - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_hbox); - } - void apply() - { - StringOutputStream vector3(64); - vector3 << entry_get_float(m_vector3.m_x) - << " " << entry_get_float(m_vector3.m_y) - << " " << entry_get_float(m_vector3.m_z); - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), vector3.c_str()); - } - typedef MemberCaller ApplyCaller; - - void update() - { - StringOutputStream buffer(32); - const char* value = SelectedEntity_getValueForKey(m_key.c_str()); - if(!string_empty(value)) - { - DoubleVector3 x_y_z; - if(!string_parse_vector3(value, x_y_z)) - { - x_y_z = DoubleVector3(0, 0, 0); - } - - buffer << x_y_z.x(); - gtk_entry_set_text(m_vector3.m_x, buffer.c_str()); - buffer.clear(); - - buffer << x_y_z.y(); - gtk_entry_set_text(m_vector3.m_y, buffer.c_str()); - buffer.clear(); - - buffer << x_y_z.z(); - gtk_entry_set_text(m_vector3.m_z, buffer.c_str()); - buffer.clear(); - } - else - { - gtk_entry_set_text(m_vector3.m_x, "0"); - gtk_entry_set_text(m_vector3.m_y, "0"); - gtk_entry_set_text(m_vector3.m_z, "0"); - } - } - typedef MemberCaller UpdateCaller; -}; - -class NonModalComboBox -{ - Callback m_changed; - guint m_changedHandler; - - static gboolean changed(GtkComboBox *widget, NonModalComboBox* self) - { - self->m_changed(); - return FALSE; - } - -public: - NonModalComboBox(const Callback& changed) : m_changed(changed), m_changedHandler(0) - { - } - void connect(GtkComboBox* combo) - { - m_changedHandler = g_signal_connect(G_OBJECT(combo), "changed", G_CALLBACK(changed), this); - } - void setActive(GtkComboBox* combo, int value) - { - g_signal_handler_disconnect(G_OBJECT(combo), m_changedHandler); - gtk_combo_box_set_active(combo, value); - connect(combo); - } -}; - -class ListAttribute : public EntityAttribute -{ - CopiedString m_key; - GtkComboBox* m_combo; - NonModalComboBox m_nonModal; - const ListAttributeType& m_type; -public: - ListAttribute(const char* key, const ListAttributeType& type) : - m_key(key), - m_combo(0), - m_nonModal(ApplyCaller(*this)), - m_type(type) - { - GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); - - for(ListAttributeType::const_iterator i = type.begin(); i != type.end(); ++i) - { - gtk_combo_box_append_text(GTK_COMBO_BOX(combo), (*i).first.c_str()); - } - - gtk_widget_show(GTK_WIDGET(combo)); - m_nonModal.connect(combo); - - m_combo = combo; - } - void release() - { - delete this; - } - GtkWidget* getWidget() const - { - return GTK_WIDGET(m_combo); - } - void apply() - { - Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), m_type[gtk_combo_box_get_active(m_combo)].second.c_str()); - } - typedef MemberCaller ApplyCaller; - - void update() - { - const char* value = SelectedEntity_getValueForKey(m_key.c_str()); - ListAttributeType::const_iterator i = m_type.findValue(value); - if(i != m_type.end()) - { - m_nonModal.setActive(m_combo, static_cast(std::distance(m_type.begin(), i))); - } - else - { - m_nonModal.setActive(m_combo, 0); - } - } - typedef MemberCaller UpdateCaller; -}; - - -namespace -{ - GtkWidget* g_entity_split1 = 0; - GtkWidget* g_entity_split2 = 0; - int g_entitysplit1_position; - int g_entitysplit2_position; - - bool g_entityInspector_windowConstructed = false; - - GtkTreeView* g_entityClassList; - GtkTextView* g_entityClassComment; - - GtkCheckButton* g_entitySpawnflagsCheck[MAX_FLAGS]; - - GtkEntry* g_entityKeyEntry; - GtkEntry* g_entityValueEntry; - - GtkListStore* g_entlist_store; - GtkListStore* g_entprops_store; - const EntityClass* g_current_flags = 0; - const EntityClass* g_current_comment = 0; - const EntityClass* g_current_attributes = 0; - - // the number of active spawnflags - int g_spawnflag_count; - // table: index, match spawnflag item to the spawnflag index (i.e. which bit) - int spawn_table[MAX_FLAGS]; - // we change the layout depending on how many spawn flags we need to display - // the table is a 4x4 in which we need to put the comment box g_entityClassComment and the spawn flags.. - GtkTable* g_spawnflagsTable; - - GtkVBox* g_attributeBox = 0; - typedef std::vector EntityAttributes; - EntityAttributes g_entityAttributes; -} - -void GlobalEntityAttributes_clear() -{ - for(EntityAttributes::iterator i = g_entityAttributes.begin(); i != g_entityAttributes.end(); ++i) - { - (*i)->release(); - } - g_entityAttributes.clear(); -} - -class GetKeyValueVisitor : public Entity::Visitor -{ - KeyValues& m_keyvalues; -public: - GetKeyValueVisitor(KeyValues& keyvalues) - : m_keyvalues(keyvalues) - { - } - - void visit(const char* key, const char* value) - { - m_keyvalues.insert(KeyValues::value_type(CopiedString(key), CopiedString(value))); - } - -}; - -void Entity_GetKeyValues(const Entity& entity, KeyValues& keyvalues, KeyValues& defaultValues) -{ - GetKeyValueVisitor visitor(keyvalues); - - entity.forEachKeyValue(visitor); - - const EntityClassAttributes& attributes = entity.getEntityClass().m_attributes; - - for(EntityClassAttributes::const_iterator i = attributes.begin(); i != attributes.end(); ++i) - { - defaultValues.insert(KeyValues::value_type((*i).first, (*i).second.m_value)); - } -} - -void Entity_GetKeyValues_Selected(KeyValues& keyvalues, KeyValues& defaultValues) -{ - class EntityGetKeyValues : public SelectionSystem::Visitor - { - KeyValues& m_keyvalues; - KeyValues& m_defaultValues; - mutable std::set m_visited; - public: - EntityGetKeyValues(KeyValues& keyvalues, KeyValues& defaultValues) - : m_keyvalues(keyvalues), m_defaultValues(defaultValues) - { - } - void visit(scene::Instance& instance) const - { - Entity* entity = Node_getEntity(instance.path().top()); - if(entity == 0 && instance.path().size() != 1) - { - entity = Node_getEntity(instance.path().parent()); - } - if(entity != 0 && m_visited.insert(entity).second) - { - Entity_GetKeyValues(*entity, m_keyvalues, m_defaultValues); - } - } - } visitor(keyvalues, defaultValues); - GlobalSelectionSystem().foreachSelected(visitor); -} - -const char* keyvalues_valueforkey(KeyValues& keyvalues, const char* key) -{ - KeyValues::iterator i = keyvalues.find(CopiedString(key)); - if(i != keyvalues.end()) - return (*i).second.c_str(); - return ""; -} - -class EntityClassListStoreAppend : public EntityClassVisitor -{ - GtkListStore* store; -public: - EntityClassListStoreAppend(GtkListStore* store_) : store(store_) - { - } - void visit(EntityClass* e) - { - GtkTreeIter iter; - gtk_list_store_append(store, &iter); - gtk_list_store_set(store, &iter, 0, e->name(), 1, e, -1); - } -}; - -void EntityClassList_fill() -{ - EntityClassListStoreAppend append(g_entlist_store); - GlobalEntityClassManager().forEach(append); -} - -void EntityClassList_clear() -{ - gtk_list_store_clear(g_entlist_store); -} - -void SetComment(EntityClass* eclass) -{ - if(eclass == g_current_comment) - return; - - g_current_comment = eclass; - - GtkTextBuffer* buffer = gtk_text_view_get_buffer(g_entityClassComment); - gtk_text_buffer_set_text(buffer, eclass->comments(), -1); -} - -void SurfaceFlags_setEntityClass(EntityClass* eclass) -{ - if(eclass == g_current_flags) - return; - - g_current_flags = eclass; - - int spawnflag_count = 0; - - { - // do a first pass to count the spawn flags, don't touch the widgets, we don't know in what state they are - for (int i=0 ; iflagnames[i] && eclass->flagnames[i][0] != 0 && strcmp(eclass->flagnames[i],"-")) - { - spawn_table[spawnflag_count] = i; - spawnflag_count++; - } - } - } - - // disable all remaining boxes - // NOTE: these boxes might not even be on display - { - for (int i = 0; i < g_spawnflag_count; ++i) - { - GtkWidget* widget = GTK_WIDGET(g_entitySpawnflagsCheck[i]); - gtk_label_set_text(GTK_LABEL(GTK_BIN(widget)->child), " "); - gtk_widget_hide(widget); - gtk_widget_ref(widget); - gtk_container_remove(GTK_CONTAINER(g_spawnflagsTable), widget); - } - } - - g_spawnflag_count = spawnflag_count; - - { - for (int i = 0; i < g_spawnflag_count; ++i) - { - GtkWidget* widget = GTK_WIDGET(g_entitySpawnflagsCheck[i]); - gtk_widget_show (widget); - - StringOutputStream str(16); - str << LowerCase(eclass->flagnames[spawn_table[i]]); - - gtk_table_attach(g_spawnflagsTable, widget, i%4, i%4+1, i/4, i/4+1, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(GTK_FILL), 0, 0); - gtk_widget_unref(widget); - - gtk_label_set_text(GTK_LABEL(GTK_BIN(widget)->child), str.c_str()); - } - } -} - -void EntityClassList_selectEntityClass(EntityClass* eclass) -{ - GtkTreeModel* model = GTK_TREE_MODEL(g_entlist_store); - GtkTreeIter iter; - for(gboolean good = gtk_tree_model_get_iter_first(model, &iter); good != FALSE; good = gtk_tree_model_iter_next(model, &iter)) - { - char* text; - gtk_tree_model_get(model, &iter, 0, &text, -1); - if (strcmp (text, eclass->name()) == 0) - { - GtkTreeView* view = g_entityClassList; - GtkTreePath* path = gtk_tree_model_get_path(model, &iter); - gtk_tree_selection_select_path(gtk_tree_view_get_selection(view), path); - if(GTK_WIDGET_REALIZED(view)) - { - gtk_tree_view_scroll_to_cell(view, path, 0, FALSE, 0, 0); - } - gtk_tree_path_free(path); - good = FALSE; - } - g_free(text); - } -} - -void EntityInspector_appendAttribute(const char* name, EntityAttribute& attribute) -{ - GtkTable* row = DialogRow_new(name, attribute.getWidget()); - DialogVBox_packRow(g_attributeBox, GTK_WIDGET(row)); -} - - -template -class StatelessAttributeCreator -{ -public: - static EntityAttribute* create(const char* name) - { - return new Attribute(name); - } -}; - -class EntityAttributeFactory -{ - typedef EntityAttribute* (*CreateFunc)(const char* name); - typedef std::map Creators; - Creators m_creators; -public: - EntityAttributeFactory() - { - m_creators.insert(Creators::value_type("string", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("color", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("integer", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("real", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("shader", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("boolean", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("angle", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("direction", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("angles", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("model", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("sound", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("vector3", &StatelessAttributeCreator::create)); - m_creators.insert(Creators::value_type("real3", &StatelessAttributeCreator::create)); - } - EntityAttribute* create(const char* type, const char* name) - { - Creators::iterator i = m_creators.find(type); - if(i != m_creators.end()) - { - return (*i).second(name); - } - const ListAttributeType* listType = GlobalEntityClassManager().findListType(type); - if(listType != 0) - { - return new ListAttribute(name, *listType); - } - return 0; - } -}; - -typedef Static GlobalEntityAttributeFactory; - -void EntityInspector_setEntityClass(EntityClass *eclass) -{ - EntityClassList_selectEntityClass(eclass); - SurfaceFlags_setEntityClass(eclass); - - if(eclass != g_current_attributes) - { - g_current_attributes = eclass; - - container_remove_all(GTK_CONTAINER(g_attributeBox)); - GlobalEntityAttributes_clear(); - - for(EntityClassAttributes::const_iterator i = eclass->m_attributes.begin(); i != eclass->m_attributes.end(); ++i) - { - EntityAttribute* attribute = GlobalEntityAttributeFactory::instance().create((*i).second.m_type.c_str(), (*i).first.c_str()); - if(attribute != 0) - { - g_entityAttributes.push_back(attribute); - EntityInspector_appendAttribute(EntityClassAttributePair_getName(*i), *g_entityAttributes.back()); - } - } - } -} - -void EntityInspector_updateSpawnflags() -{ - { - int f = atoi(SelectedEntity_getValueForKey("spawnflags")); - for (int i = 0; i < g_spawnflag_count; ++i) - { - int v = !!(f&(1<update(); - } -} - -class EntityInspectorDraw -{ - IdleDraw m_idleDraw; -public: - EntityInspectorDraw() : m_idleDraw(FreeCaller()) - { - } - void queueDraw() - { - m_idleDraw.queueDraw(); - } -}; - -EntityInspectorDraw g_EntityInspectorDraw; - - -void EntityInspector_keyValueChanged() -{ - g_EntityInspectorDraw.queueDraw(); -} -void EntityInspector_selectionChanged(const Selectable&) -{ - EntityInspector_keyValueChanged(); -} - -// Creates a new entity based on the currently selected brush and entity type. -// -void EntityClassList_createEntity() -{ - GtkTreeView* view = g_entityClassList; - - // find out what type of entity we are trying to create - GtkTreeModel* model; - GtkTreeIter iter; - if(gtk_tree_selection_get_selected(gtk_tree_view_get_selection(view), &model, &iter) == FALSE) - { - gtk_MessageBox(gtk_widget_get_toplevel(GTK_WIDGET(g_entityClassList)), "You must have a selected class to create an entity", "info"); - return; - } - - char* text; - gtk_tree_model_get(model, &iter, 0, &text, -1); - - { - StringOutputStream command; - command << "entityCreate -class " << text; - - UndoableCommand undo(command.c_str()); - - Entity_createFromSelection(text, g_vector3_identity); - } - g_free(text); -} - -void EntityInspector_applyKeyValue() -{ - // Get current selection text - StringOutputStream key(64); - key << gtk_entry_get_text(g_entityKeyEntry); - StringOutputStream value(64); - value << gtk_entry_get_text(g_entityValueEntry); - - - // TTimo: if you change the classname to worldspawn you won't merge back in the structural brushes but create a parasite entity - if (!strcmp(key.c_str(), "classname") && !strcmp(value.c_str(), "worldspawn")) - { - gtk_MessageBox(gtk_widget_get_toplevel(GTK_WIDGET(g_entityKeyEntry)), "Cannot change \"classname\" key back to worldspawn.", 0, eMB_OK ); - return; - } - - - // RR2DO2: we don't want spaces in entity keys - if (strstr( key.c_str(), " " )) - { - gtk_MessageBox(gtk_widget_get_toplevel(GTK_WIDGET(g_entityKeyEntry)), "No spaces are allowed in entity keys.", 0, eMB_OK ); - return; - } - - if(strcmp(key.c_str(), "classname") == 0) - { - StringOutputStream command; - command << "entitySetClass -class " << value.c_str(); - UndoableCommand undo(command.c_str()); - Scene_EntitySetClassname_Selected(value.c_str()); - } - else - { - Scene_EntitySetKeyValue_Selected_Undoable(key.c_str(), value.c_str()); - } -} - -void EntityInspector_clearKeyValue() -{ - // Get current selection text - StringOutputStream key(64); - key << gtk_entry_get_text(g_entityKeyEntry); - - if(strcmp(key.c_str(), "classname") != 0) - { - StringOutputStream command; - command << "entityDeleteKey -key " << key.c_str(); - UndoableCommand undo(command.c_str()); - Scene_EntitySetKeyValue_Selected(key.c_str(), ""); - } -} - -void EntityInspector_clearAllKeyValues() -{ - UndoableCommand undo("entityClear"); - - // remove all keys except classname - for(KeyValues::iterator i = g_selectedKeyValues.begin(); i != g_selectedKeyValues.end(); ++i) - { - if(strcmp((*i).first.c_str(), "classname") != 0) - { - Scene_EntitySetKeyValue_Selected((*i).first.c_str(), ""); - } - } -} - -// ============================================================================= -// callbacks - -static void EntityClassList_selection_changed(GtkTreeSelection* selection, gpointer data) -{ - GtkTreeModel* model; - GtkTreeIter selected; - if(gtk_tree_selection_get_selected(selection, &model, &selected)) - { - EntityClass* eclass; - gtk_tree_model_get(model, &selected, 1, &eclass, -1); - if(eclass != 0) - { - SetComment(eclass); - } - } -} - -static gint EntityClassList_button_press(GtkWidget *widget, GdkEventButton *event, gpointer data) -{ - if (event->type == GDK_2BUTTON_PRESS) - { - EntityClassList_createEntity(); - return TRUE; - } - return FALSE; -} - -static gint EntityClassList_keypress(GtkWidget* widget, GdkEventKey* event, gpointer data) -{ - unsigned int code = gdk_keyval_to_upper (event->keyval); - - if (event->keyval == GDK_Return) - { - EntityClassList_createEntity(); - return TRUE; - } - - // select the entity that starts with the key pressed - if (code <= 'Z' && code >= 'A') - { - GtkTreeView* view = g_entityClassList; - GtkTreeModel* model; - GtkTreeIter iter; - if(gtk_tree_selection_get_selected(gtk_tree_view_get_selection(view), &model, &iter) == FALSE - || gtk_tree_model_iter_next(model, &iter) == FALSE) - { - gtk_tree_model_get_iter_first(model, &iter); - } - - for(std::size_t count = gtk_tree_model_iter_n_children(model, 0); count > 0; --count) - { - char* text; - gtk_tree_model_get(model, &iter, 0, &text, -1); - - if (toupper (text[0]) == (int)code) - { - GtkTreePath* path = gtk_tree_model_get_path(model, &iter); - gtk_tree_selection_select_path(gtk_tree_view_get_selection(view), path); - if(GTK_WIDGET_REALIZED(view)) - { - gtk_tree_view_scroll_to_cell(view, path, 0, FALSE, 0, 0); - } - gtk_tree_path_free(path); - count = 1; - } - - g_free(text); - - if(gtk_tree_model_iter_next(model, &iter) == FALSE) - gtk_tree_model_get_iter_first(model, &iter); - } - - return TRUE; - } - return FALSE; -} - -static void EntityProperties_selection_changed(GtkTreeSelection* selection, gpointer data) -{ - // find out what type of entity we are trying to create - GtkTreeModel* model; - GtkTreeIter iter; - if(gtk_tree_selection_get_selected(selection, &model, &iter) == FALSE) - { - return; - } - - char* key; - char* val; - gtk_tree_model_get(model, &iter, 0, &key, 1, &val, -1); - - gtk_entry_set_text(g_entityKeyEntry, key); - gtk_entry_set_text(g_entityValueEntry, val); - - g_free(key); - g_free(val); -} - -static void SpawnflagCheck_toggled(GtkWidget *widget, gpointer data) -{ - EntityInspector_applySpawnflags(); -} - -static gint EntityEntry_keypress(GtkEntry* widget, GdkEventKey* event, gpointer data) -{ - if (event->keyval == GDK_Return) - { - if(widget == g_entityKeyEntry) - { - gtk_entry_set_text(g_entityValueEntry, ""); - gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(widget))), GTK_WIDGET(g_entityValueEntry)); - } - else - { - EntityInspector_applyKeyValue(); - } - return TRUE; - } - if (event->keyval == GDK_Escape) - { - gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(widget))), NULL); - return TRUE; - } - - return FALSE; -} - -void EntityInspector_destroyWindow(GtkWidget* widget, gpointer data) -{ - g_entitysplit1_position = gtk_paned_get_position(GTK_PANED(g_entity_split1)); - g_entitysplit2_position = gtk_paned_get_position(GTK_PANED(g_entity_split2)); - - g_entityInspector_windowConstructed = false; - GlobalEntityAttributes_clear(); -} - -GtkWidget* EntityInspector_constructWindow(GtkWindow* toplevel) -{ - GtkWidget* vbox = gtk_vbox_new(FALSE, 2); - gtk_widget_show (vbox); - gtk_container_set_border_width(GTK_CONTAINER (vbox), 2); - - g_signal_connect(G_OBJECT(vbox), "destroy", G_CALLBACK(EntityInspector_destroyWindow), 0); - - { - GtkWidget* split1 = gtk_vpaned_new(); - gtk_box_pack_start(GTK_BOX(vbox), split1, TRUE, TRUE, 0); - gtk_widget_show (split1); - - g_entity_split1 = split1; - - { - GtkWidget* split2 = gtk_vpaned_new(); - gtk_paned_add1 (GTK_PANED (split1), split2); - gtk_widget_show (split2); - - g_entity_split2 = split2; - - { - // class list - GtkWidget* scr = gtk_scrolled_window_new (0, 0); - gtk_widget_show (scr); - gtk_paned_add1 (GTK_PANED (split2), scr); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); - gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); - - { - GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_POINTER); - - GtkTreeView* view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(GTK_TREE_MODEL(store))); - gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), FALSE); - gtk_tree_view_set_headers_visible(view, FALSE); - g_signal_connect(G_OBJECT(view), "button_press_event", G_CALLBACK(EntityClassList_button_press), 0); - g_signal_connect(G_OBJECT(view), "key_press_event", G_CALLBACK(EntityClassList_keypress), 0); - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Key", renderer, "text", 0, 0); - gtk_tree_view_append_column(view, column); - } - - { - GtkTreeSelection* selection = gtk_tree_view_get_selection(view); - g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(EntityClassList_selection_changed), 0); - } - - gtk_widget_show(GTK_WIDGET(view)); - - gtk_container_add(GTK_CONTAINER(scr), GTK_WIDGET(view)); - - g_object_unref(G_OBJECT(store)); - g_entityClassList = view; - g_entlist_store = store; - } - } - - { - GtkWidget* scr = gtk_scrolled_window_new (0, 0); - gtk_widget_show (scr); - gtk_paned_add2 (GTK_PANED (split2), scr); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); - gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); - - { - GtkTextView* text = GTK_TEXT_VIEW(gtk_text_view_new()); - gtk_widget_set_size_request(GTK_WIDGET(text), 0, -1); // allow shrinking - gtk_text_view_set_wrap_mode(text, GTK_WRAP_WORD); - gtk_text_view_set_editable(text, FALSE); - gtk_widget_show(GTK_WIDGET(text)); - gtk_container_add(GTK_CONTAINER(scr), GTK_WIDGET(text)); - g_entityClassComment = text; - } - } - } - - { - GtkWidget* split2 = gtk_vpaned_new(); - gtk_paned_add2 (GTK_PANED (split1), split2); - gtk_widget_show(split2); - - { - GtkWidget* vbox2 = gtk_vbox_new (FALSE, 2); - gtk_widget_show (vbox2); - gtk_paned_pack1(GTK_PANED(split2), vbox2, FALSE, FALSE); - - { - // Spawnflags (4 colums wide max, or window gets too wide.) - GtkTable* table = GTK_TABLE(gtk_table_new(4, 4, FALSE)); - gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(table), FALSE, TRUE, 0); - gtk_widget_show(GTK_WIDGET(table)); - - g_spawnflagsTable = table; - - for (int i = 0; i < MAX_FLAGS; i++) - { - GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new_with_label("")); - gtk_widget_ref(GTK_WIDGET(check)); - g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(check), "toggled", G_CALLBACK(SpawnflagCheck_toggled), 0))); - g_entitySpawnflagsCheck[i] = check; - } - } - - { - // key/value list - GtkWidget* scr = gtk_scrolled_window_new (0, 0); - gtk_widget_show (scr); - gtk_box_pack_start (GTK_BOX (vbox2), scr, TRUE, TRUE, 0); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); - - { - GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_STRING); - - GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); - gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), FALSE); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, 0); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - } - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 1, 0); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - } - - { - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); - g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(EntityProperties_selection_changed), 0); - } - - gtk_widget_show(view); - - gtk_container_add(GTK_CONTAINER (scr), view); - - g_object_unref(G_OBJECT(store)); - - g_entprops_store = store; - } - } - - { - // key/value entry - GtkTable* table = GTK_TABLE(gtk_table_new(2, 2, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(table), FALSE, TRUE, 0); - gtk_table_set_row_spacings(table, 3); - gtk_table_set_col_spacings(table, 5); - - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_events(GTK_WIDGET(entry), GDK_KEY_PRESS_MASK); - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(EntityEntry_keypress), 0); - g_entityKeyEntry = entry; - } - - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_events(GTK_WIDGET(entry), GDK_KEY_PRESS_MASK); - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(EntityEntry_keypress), 0); - g_entityValueEntry = entry; - } - - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Value")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Key")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - } - - { - GtkBox* hbox = GTK_BOX(gtk_hbox_new(TRUE, 4)); - gtk_widget_show(GTK_WIDGET(hbox)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(hbox), FALSE, TRUE, 0); - - { - GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Clear All")); - gtk_widget_show(GTK_WIDGET(button)); - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(EntityInspector_clearAllKeyValues), 0); - gtk_box_pack_start(hbox, GTK_WIDGET(button), TRUE, TRUE, 0); - } - { - GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Delete Key")); - gtk_widget_show(GTK_WIDGET(button)); - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(EntityInspector_clearKeyValue), 0); - gtk_box_pack_start(hbox, GTK_WIDGET(button), TRUE, TRUE, 0); - } - } - } - - { - GtkWidget* scr = gtk_scrolled_window_new(0, 0); - gtk_widget_show(scr); - gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scr), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); - - GtkWidget* viewport = gtk_viewport_new(0, 0); - gtk_widget_show(viewport); - gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE); - - g_attributeBox = GTK_VBOX(gtk_vbox_new(FALSE, 2)); - gtk_widget_show(GTK_WIDGET(g_attributeBox)); - - gtk_container_add(GTK_CONTAINER(viewport), GTK_WIDGET(g_attributeBox)); - gtk_container_add(GTK_CONTAINER(scr), viewport); - gtk_paned_pack2(GTK_PANED(split2), scr, FALSE, FALSE); - } - } - } - - - { - // show the sliders in any case - if(g_entitysplit2_position > 22) - { - gtk_paned_set_position (GTK_PANED(g_entity_split2), g_entitysplit2_position); - } else { - g_entitysplit2_position = 22; - gtk_paned_set_position (GTK_PANED(g_entity_split2), 22); - } - if((g_entitysplit1_position - g_entitysplit2_position) > 27) - { - gtk_paned_set_position (GTK_PANED(g_entity_split1), g_entitysplit1_position); - } else { - gtk_paned_set_position (GTK_PANED(g_entity_split1), g_entitysplit2_position + 27); - } - } - - g_entityInspector_windowConstructed = true; - EntityClassList_fill(); - - typedef FreeCaller1 EntityInspectorSelectionChangedCaller; - GlobalSelectionSystem().addSelectionChangeCallback(EntityInspectorSelectionChangedCaller()); - GlobalEntityCreator().setKeyValueChangedFunc(EntityInspector_keyValueChanged); - - // hack - gtk_container_set_focus_chain(GTK_CONTAINER(vbox), NULL); - - return vbox; -} - -class EntityInspector : public ModuleObserver -{ - std::size_t m_unrealised; -public: - EntityInspector() : m_unrealised(1) - { - } - void realise() - { - if(--m_unrealised == 0) - { - if(g_entityInspector_windowConstructed) - { - //globalOutputStream() << "Entity Inspector: realise\n"; - EntityClassList_fill(); - } - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - if(g_entityInspector_windowConstructed) - { - //globalOutputStream() << "Entity Inspector: unrealise\n"; - EntityClassList_clear(); - } - } - } -}; - -EntityInspector g_EntityInspector; - -#include "preferencesystem.h" -#include "stringio.h" - -void EntityInspector_construct() -{ - GlobalEntityClassManager().attach(g_EntityInspector); - - GlobalPreferenceSystem().registerPreference("EntitySplit1", IntImportStringCaller(g_entitysplit1_position), IntExportStringCaller(g_entitysplit1_position)); - GlobalPreferenceSystem().registerPreference("EntitySplit2", IntImportStringCaller(g_entitysplit2_position), IntExportStringCaller(g_entitysplit2_position)); - -} - -void EntityInspector_destroy() -{ - GlobalEntityClassManager().detach(g_EntityInspector); -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/entityinspector.h b/misc/mediasource/extra/netradiant-src/radiant/entityinspector.h deleted file mode 100644 index 62a69ab6..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/entityinspector.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_ENTITYINSPECTOR_H) -#define INCLUDED_ENTITYINSPECTOR_H - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; -GtkWidget* EntityInspector_constructWindow(GtkWindow* parent); -void EntityInspector_construct(); -void EntityInspector_destroy(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/entitylist.cpp b/misc/mediasource/extra/netradiant-src/radiant/entitylist.cpp deleted file mode 100644 index e6944a6d..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/entitylist.cpp +++ /dev/null @@ -1,430 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "entitylist.h" - -#include "iselection.h" - -#include -#include -#include -#include - -#include "string/string.h" -#include "scenelib.h" -#include "nameable.h" -#include "signal/isignal.h" -#include "generic/object.h" - -#include "gtkutil/widget.h" -#include "gtkutil/window.h" -#include "gtkutil/idledraw.h" -#include "gtkutil/accelerator.h" -#include "gtkutil/closure.h" - -#include "treemodel.h" - -void RedrawEntityList(); -typedef FreeCaller RedrawEntityListCaller; - -typedef struct _GtkTreeView GtkTreeView; - -class EntityList -{ -public: - enum EDirty - { - eDefault, - eSelection, - eInsertRemove, - }; - - EDirty m_dirty; - - IdleDraw m_idleDraw; - WindowPositionTracker m_positionTracker; - - GtkWindow* m_window; - GtkTreeView* m_tree_view; - GraphTreeModel* m_tree_model; - bool m_selection_disabled; - - EntityList() : - m_dirty(EntityList::eDefault), - m_idleDraw(RedrawEntityListCaller()), - m_window(0), - m_selection_disabled(false) - { - } - - bool visible() const - { - return GTK_WIDGET_VISIBLE(GTK_WIDGET(m_window)); - } -}; - -namespace -{ - EntityList* g_EntityList; - - inline EntityList& getEntityList() - { - ASSERT_NOTNULL(g_EntityList); - return *g_EntityList; - } -} - - -inline Nameable* Node_getNameable(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -const char* node_get_name(scene::Node& node) -{ - Nameable* nameable = Node_getNameable(node); - return (nameable != 0) - ? nameable->name() - : "node"; -} - -template -inline void gtk_tree_model_get_pointer(GtkTreeModel* model, GtkTreeIter* iter, gint column, value_type** pointer) -{ - GValue value = GValue_default(); - gtk_tree_model_get_value(model, iter, column, &value); - *pointer = (value_type*)g_value_get_pointer(&value); -} - - - -void entitylist_treeviewcolumn_celldatafunc(GtkTreeViewColumn* column, GtkCellRenderer* renderer, GtkTreeModel* model, GtkTreeIter* iter, gpointer data) -{ - scene::Node* node; - gtk_tree_model_get_pointer(model, iter, 0, &node); - scene::Instance* instance; - gtk_tree_model_get_pointer(model, iter, 1, &instance); - if(node != 0) - { - gtk_cell_renderer_set_fixed_size(renderer, -1, -1); - char* name = const_cast(node_get_name(*node)); - g_object_set(G_OBJECT(renderer), "text", name, "visible", TRUE, 0); - - //globalOutputStream() << "rendering cell " << makeQuoted(name) << "\n"; - GtkStyle* style = gtk_widget_get_style(GTK_WIDGET(getEntityList().m_tree_view)); - if(instance->childSelected()) - { - g_object_set(G_OBJECT(renderer), "cell-background-gdk", &style->base[GTK_STATE_ACTIVE], 0); - } - else - { - g_object_set(G_OBJECT(renderer), "cell-background-gdk", &style->base[GTK_STATE_NORMAL], 0); - } - } - else - { - gtk_cell_renderer_set_fixed_size(renderer, -1, 0); - g_object_set(G_OBJECT(renderer), "text", "", "visible", FALSE, 0); - } -} - -static gboolean entitylist_tree_select(GtkTreeSelection *selection, GtkTreeModel *model, GtkTreePath *path, gboolean path_currently_selected, gpointer data) -{ - GtkTreeIter iter; - gtk_tree_model_get_iter(model, &iter, path); - scene::Node* node; - gtk_tree_model_get_pointer(model, &iter, 0, &node); - scene::Instance* instance; - gtk_tree_model_get_pointer(model, &iter, 1, &instance); - Selectable* selectable = Instance_getSelectable(*instance); - - if(node == 0) - { - if(path_currently_selected != FALSE) - { - getEntityList().m_selection_disabled = true; - GlobalSelectionSystem().setSelectedAll(false); - getEntityList().m_selection_disabled = false; - } - } - else if(selectable != 0) - { - getEntityList().m_selection_disabled = true; - selectable->setSelected(path_currently_selected == FALSE); - getEntityList().m_selection_disabled = false; - return TRUE; - } - - return FALSE; -} - -static gboolean entitylist_tree_select_null(GtkTreeSelection *selection, GtkTreeModel *model, GtkTreePath *path, gboolean path_currently_selected, gpointer data) -{ - return TRUE; -} - -void EntityList_ConnectSignals(GtkTreeView* view) -{ - GtkTreeSelection* select = gtk_tree_view_get_selection(view); - gtk_tree_selection_set_select_function(select, entitylist_tree_select, NULL, 0); -} - -void EntityList_DisconnectSignals(GtkTreeView* view) -{ - GtkTreeSelection* select = gtk_tree_view_get_selection(view); - gtk_tree_selection_set_select_function(select, entitylist_tree_select_null, 0, 0); -} - - - -gboolean treemodel_update_selection(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, gpointer data) -{ - GtkTreeView* view = reinterpret_cast(data); - - scene::Instance* instance; - gtk_tree_model_get_pointer(model, iter, 1, &instance); - Selectable* selectable = Instance_getSelectable(*instance); - - if(selectable != 0) - { - GtkTreeSelection* selection = gtk_tree_view_get_selection(view); - if(selectable->isSelected()) - { - gtk_tree_selection_select_path(selection, path); - } - else - { - gtk_tree_selection_unselect_path(selection, path); - } - } - - return FALSE; -} - -void EntityList_UpdateSelection(GtkTreeModel* model, GtkTreeView* view) -{ - EntityList_DisconnectSignals(view); - gtk_tree_model_foreach(model, treemodel_update_selection, view); - EntityList_ConnectSignals(view); -} - - -void RedrawEntityList() -{ - switch(getEntityList().m_dirty) - { - case EntityList::eInsertRemove: - case EntityList::eSelection: - EntityList_UpdateSelection(GTK_TREE_MODEL(getEntityList().m_tree_model), getEntityList().m_tree_view); - default: - break; - } - getEntityList().m_dirty = EntityList::eDefault; -} - -void entitylist_queue_draw() -{ - getEntityList().m_idleDraw.queueDraw(); -} - -void EntityList_SelectionUpdate() -{ - if(getEntityList().m_selection_disabled) - return; - - if(getEntityList().m_dirty < EntityList::eSelection) - getEntityList().m_dirty = EntityList::eSelection; - entitylist_queue_draw(); -} - -void EntityList_SelectionChanged(const Selectable& selectable) -{ - EntityList_SelectionUpdate(); -} - -void entitylist_treeview_rowcollapsed(GtkTreeView* view, GtkTreeIter* iter, GtkTreePath* path, gpointer user_data) -{ -} - -void entitylist_treeview_row_expanded(GtkTreeView* view, GtkTreeIter* iter, GtkTreePath* path, gpointer user_data) -{ - EntityList_SelectionUpdate(); -} - - -void EntityList_SetShown(bool shown) -{ - widget_set_visible(GTK_WIDGET(getEntityList().m_window), shown); -} - -void EntityList_toggleShown() -{ - EntityList_SetShown(!getEntityList().visible()); -} - -gint graph_tree_model_compare_name(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, gpointer user_data) -{ - scene::Node* first; - gtk_tree_model_get(model, a, 0, (gpointer*)&first, -1); - scene::Node* second; - gtk_tree_model_get(model, b, 0, (gpointer*)&second, -1); - int result = 0; - if(first != 0 && second != 0) - { - result = string_compare(node_get_name(*first), node_get_name(*second)); - } - if(result == 0) - { - return (first < second) ? -1 : (second < first) ? 1 : 0; - } - return result; -} - -extern GraphTreeModel* scene_graph_get_tree_model(); -void AttachEntityTreeModel() -{ - getEntityList().m_tree_model = scene_graph_get_tree_model(); - - gtk_tree_view_set_model(getEntityList().m_tree_view, GTK_TREE_MODEL(getEntityList().m_tree_model)); -} - -void DetachEntityTreeModel() -{ - getEntityList().m_tree_model = 0; - - gtk_tree_view_set_model(getEntityList().m_tree_view, 0); -} - -void EntityList_constructWindow(GtkWindow* main_window) -{ - ASSERT_MESSAGE(getEntityList().m_window == 0, "error"); - - GtkWindow* window = create_persistent_floating_window("Entity List", main_window); - - gtk_window_add_accel_group(window, global_accel); - - getEntityList().m_positionTracker.connect(window); - - - getEntityList().m_window = window; - - { - GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(scr)); - - { - GtkWidget* view = gtk_tree_view_new(); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); - - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new(); - gtk_tree_view_column_pack_start(column, renderer, TRUE); - gtk_tree_view_column_set_cell_data_func(column, renderer, entitylist_treeviewcolumn_celldatafunc, 0, 0); - - GtkTreeSelection* select = gtk_tree_view_get_selection (GTK_TREE_VIEW(view)); - gtk_tree_selection_set_mode(select, GTK_SELECTION_MULTIPLE); - - g_signal_connect(G_OBJECT(view), "row_expanded", G_CALLBACK(entitylist_treeview_row_expanded), 0); - g_signal_connect(G_OBJECT(view), "row_collapsed", G_CALLBACK(entitylist_treeview_rowcollapsed), 0); - - gtk_tree_view_append_column (GTK_TREE_VIEW (view), column); - - gtk_widget_show(view); - gtk_container_add (GTK_CONTAINER(scr), view); - getEntityList().m_tree_view = GTK_TREE_VIEW(view); - } - } - - EntityList_ConnectSignals(getEntityList().m_tree_view); - AttachEntityTreeModel(); -} - -void EntityList_destroyWindow() -{ - DetachEntityTreeModel(); - EntityList_DisconnectSignals(getEntityList().m_tree_view); - destroy_floating_window(getEntityList().m_window); -} - -#include "preferencesystem.h" - -#include "iselection.h" - -namespace -{ - scene::Node* nullNode = 0; -} - -class NullSelectedInstance : public scene::Instance, public Selectable -{ - class TypeCasts - { - InstanceTypeCastTable m_casts; - public: - TypeCasts() - { - InstanceStaticCast::install(m_casts); - } - InstanceTypeCastTable& get() - { - return m_casts; - } - }; - -public: - typedef LazyStatic StaticTypeCasts; - - NullSelectedInstance() : Instance(scene::Path(makeReference(*nullNode)), 0, this, StaticTypeCasts::instance().get()) - { - } - - void setSelected(bool select) - { - ERROR_MESSAGE("error"); - } - bool isSelected() const - { - return true; - } -}; - -typedef LazyStatic StaticNullSelectedInstance; - - -void EntityList_Construct() -{ - graph_tree_model_insert(scene_graph_get_tree_model(), StaticNullSelectedInstance::instance()); - - g_EntityList = new EntityList; - - getEntityList().m_positionTracker.setPosition(c_default_window_pos); - - GlobalPreferenceSystem().registerPreference("EntityInfoDlg", WindowPositionTrackerImportStringCaller(getEntityList().m_positionTracker), WindowPositionTrackerExportStringCaller(getEntityList().m_positionTracker)); - - typedef FreeCaller1 EntityListSelectionChangedCaller; - GlobalSelectionSystem().addSelectionChangeCallback(EntityListSelectionChangedCaller()); -} -void EntityList_Destroy() -{ - delete g_EntityList; - - graph_tree_model_erase(scene_graph_get_tree_model(), StaticNullSelectedInstance::instance()); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/entitylist.h b/misc/mediasource/extra/netradiant-src/radiant/entitylist.h deleted file mode 100644 index cdad18db..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/entitylist.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ENTITYLIST_H) -#define INCLUDED_ENTITYLIST_H - -void EntityList_Construct(); -void EntityList_Destroy(); - -typedef struct _GtkWindow GtkWindow; -void EntityList_constructWindow(GtkWindow* main_window); -void EntityList_destroyWindow(); -void EntityList_toggleShown(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/environment.cpp b/misc/mediasource/extra/netradiant-src/radiant/environment.cpp deleted file mode 100644 index 04033579..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/environment.cpp +++ /dev/null @@ -1,312 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "environment.h" - -#include "stream/textstream.h" -#include "string/string.h" -#include "stream/stringstream.h" -#include "debugging/debugging.h" -#include "os/path.h" -#include "os/file.h" -#include "cmdlib.h" - -int g_argc; -char** g_argv; - -void args_init(int argc, char* argv[]) -{ - int i, j, k; - - for (i = 1; i < argc; i++) - { - for (k = i; k < argc; k++) - if (argv[k] != 0) - break; - - if (k > i) - { - k -= i; - for (j = i + k; j < argc; j++) - argv[j-k] = argv[j]; - argc -= k; - } - } - - g_argc = argc; - g_argv = argv; -} - -char *gamedetect_argv_buffer[1024]; -void gamedetect_found_game(char *game, char *path) -{ - int argc; - static char buf[128]; - - if(g_argv == gamedetect_argv_buffer) - return; - - globalOutputStream() << "Detected game " << game << " in " << path << "\n"; - - sprintf(buf, "-%s-EnginePath", game); - argc = 0; - gamedetect_argv_buffer[argc++] = "-global-gamefile"; - gamedetect_argv_buffer[argc++] = game; - gamedetect_argv_buffer[argc++] = buf; - gamedetect_argv_buffer[argc++] = path; - if((size_t) (argc + g_argc) >= sizeof(gamedetect_argv_buffer) / sizeof(*gamedetect_argv_buffer) - 1) - g_argc = sizeof(gamedetect_argv_buffer) / sizeof(*gamedetect_argv_buffer) - g_argc - 1; - memcpy(gamedetect_argv_buffer + 4, g_argv, sizeof(*gamedetect_argv_buffer) * g_argc); - g_argc += argc; - g_argv = gamedetect_argv_buffer; -} - -bool gamedetect_check_game(char *gamefile, const char *checkfile1, const char *checkfile2, char *buf /* must have 64 bytes free after bufpos */, int bufpos) -{ - buf[bufpos] = '/'; - - strcpy(buf + bufpos + 1, checkfile1); - globalOutputStream() << "Checking for a game file in " << buf << "\n"; - if(!file_exists(buf)) - return false; - - if(checkfile2) - { - strcpy(buf + bufpos + 1, checkfile2); - globalOutputStream() << "Checking for a game file in " << buf << "\n"; - if(!file_exists(buf)) - return false; - } - - buf[bufpos + 1] = 0; - gamedetect_found_game(gamefile, buf); - return true; -} - -void gamedetect() -{ - // if we're inside a Nexuiz install - // default to nexuiz.game (unless the user used an option to inhibit this) - bool nogamedetect = false; - int i; - for(i = 1; i < g_argc - 1; ++i) - if(g_argv[i][0] == '-') - { - if(!strcmp(g_argv[i], "-gamedetect")) - nogamedetect = !strcmp(g_argv[i+1], "false"); - ++i; - } - if(!nogamedetect) - { - static char buf[1024 + 64]; - strncpy(buf, environment_get_app_path(), sizeof(buf)); - buf[sizeof(buf) - 1 - 64] = 0; - if(!strlen(buf)) - return; - - char *p = buf + strlen(buf) - 1; // point directly on the slash of get_app_path - while(p != buf) - { - // TODO add more games to this - - // try to detect Nexuiz installs -#if defined(WIN32) - if(gamedetect_check_game("nexuiz.game", "data/common-spog.pk3", "nexuiz.exe", buf, p - buf)) -#elif defined(__APPLE__) - if(gamedetect_check_game("nexuiz.game", "data/common-spog.pk3", "Nexuiz.app/Contents/Info.plist", buf, p - buf)) -#else - if(gamedetect_check_game("nexuiz.game", "data/common-spog.pk3", "nexuiz-linux-glx.sh", buf, p - buf)) -#endif - return; - - // try to detect Q2World installs - if(gamedetect_check_game("q2w.game", "default/quake2world.version", NULL, buf, p - buf)) - return; - - // try to detect Warsow installs - if(gamedetect_check_game("warsow.game", "basewsw/dedicated_autoexec.cfg", NULL, buf, p - buf)) - return; - - // we found nothing - // go backwards - --p; - while(p != buf && *p != '/' && *p != '\\') - --p; - } - } -} - -namespace -{ - CopiedString home_path; - CopiedString app_path; -} - -const char* environment_get_home_path() -{ - return home_path.c_str(); -} - -const char* environment_get_app_path() -{ - return app_path.c_str(); -} - -bool portable_app_setup() -{ - StringOutputStream confdir(256); - confdir << app_path.c_str() << "settings/"; - if(file_exists(confdir.c_str())) - { - home_path = confdir.c_str(); - return true; - } - return false; -} - -#if defined(POSIX) - -#include -#include -#include - -#include - -const char* LINK_NAME = -#if defined (__linux__) - "/proc/self/exe" -#else // FreeBSD and OSX - "/proc/curproc/file" -#endif -; - -/// brief Returns the filename of the executable belonging to the current process, or 0 if not found. -char* getexename(char *buf) -{ - /* Now read the symbolic link */ - int ret = readlink(LINK_NAME, buf, PATH_MAX); - - if(ret == -1) - { - globalOutputStream() << "getexename: falling back to argv[0]: " << makeQuoted(g_argv[0]); - const char* path = realpath(g_argv[0], buf); - if(path == 0) - { - /* In case of an error, leave the handling up to the caller */ - return ""; - } - } - - /* Ensure proper NUL termination */ - buf[ret] = 0; - - /* delete the program name */ - *(strrchr(buf, '/')) = '\0'; - - // NOTE: we build app path with a trailing '/' - // it's a general convention in Radiant to have the slash at the end of directories - if (buf[strlen(buf)-1] != '/') - { - strcat(buf, "/"); - } - - return buf; -} - -void environment_init(int argc, char* argv[]) -{ - // Give away unnecessary root privileges. - // Important: must be done before calling gtk_init(). - char *loginname; - struct passwd *pw; - seteuid(getuid()); - if (geteuid() == 0 && (loginname = getlogin()) != 0 && - (pw = getpwnam(loginname)) != 0) - setuid(pw->pw_uid); - - args_init(argc, argv); - - { - char real[PATH_MAX]; - app_path = getexename(real); - ASSERT_MESSAGE(!string_empty(app_path.c_str()), "failed to deduce app path"); - } - - if(!portable_app_setup()) - { - StringOutputStream home(256); - home << DirectoryCleaned(g_get_home_dir()) << ".netradiant/"; - Q_mkdir(home.c_str()); - home_path = home.c_str(); - } - gamedetect(); -} - -#elif defined(WIN32) - -#include - -void environment_init(int argc, char* argv[]) -{ - args_init(argc, argv); - - { - // get path to the editor - char filename[MAX_PATH+1]; - GetModuleFileName(0, filename, MAX_PATH); - char* last_separator = strrchr(filename, '\\'); - if(last_separator != 0) - { - *(last_separator+1) = '\0'; - } - else - { - filename[0] = '\0'; - } - StringOutputStream app(256); - app << PathCleaned(filename); - app_path = app.c_str(); - } - - if(!portable_app_setup()) - { - char *appdata = getenv("APPDATA"); - StringOutputStream home(256); - if(!appdata || string_empty(appdata)) - { - ERROR_MESSAGE("Application Data folder not available.\n" - "Radiant will use C:\\ for user preferences.\n"); - home << "C:"; - } - else - { - home << PathCleaned(appdata); - } - home << "/NetRadiantSettings/"; - Q_mkdir(home.c_str()); - home_path = home.c_str(); - } - gamedetect(); -} - -#else -#error "unsupported platform" -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/environment.h b/misc/mediasource/extra/netradiant-src/radiant/environment.h deleted file mode 100644 index 49d595e0..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/environment.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_ENVIRONMENT_H) -#define INCLUDED_ENVIRONMENT_H - -void environment_init(int argc, char* argv[]); -const char* environment_get_home_path(); -const char* environment_get_app_path(); - -extern int g_argc; -extern char** g_argv; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/error.cpp b/misc/mediasource/extra/netradiant-src/radiant/error.cpp deleted file mode 100644 index 0ff75d1c..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/error.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "error.h" - -#include "debugging/debugging.h" -#include "igl.h" - -#include "gtkutil/messagebox.h" -#include "console.h" -#include "preferences.h" - - -#ifdef WIN32 -#define UNICODE -#include -#else -#include -#include -#endif - - - -/* -================= -Error - -For abnormal program terminations -================= -*/ - -/*! -\todo -FIXME the prompt wether to do prefs dialog, may not even be possible -if the crash happens before the game is loaded -*/ - -void Error (const char *error, ...) -{ - va_list argptr; - char text[4096]; - - va_start (argptr,error); - vsprintf (text, error,argptr); - va_end (argptr); - - strcat( text, "\n" ); - -#ifdef WIN32 - if (GetLastError() != 0) - { - LPVOID lpMsgBuf; - FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - 0, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - (LPTSTR) &lpMsgBuf, - 0, - 0 - ); - strcat( text, "GetLastError: " ); - /* - Gtk will only crunch 0<=char<=127 - this is a bit hackish, but I didn't find useful functions in win32 API for this - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516 - */ - TCHAR *scan, *next = (TCHAR*)lpMsgBuf; - do - { - scan = next; - text[strlen(text)+1] = '\0'; - if ((scan[0] >= 0) && (scan[0] <= 127)) - text[strlen(text)] = char(scan[0]); - else - text[strlen(text)] = '?'; - next = CharNext(scan); - } while (next != scan); - strcat( text, "\n"); - LocalFree( lpMsgBuf ); - } -#else - if (errno != 0) - { - strcat( text, "errno: " ); - strcat( text, strerror (errno)); - strcat( text, "\n"); - } -#endif - - -#if 0 - // we need to have a current context to call glError() - if (g_glwindow_globals.d_glBase != 0) - { - // glGetError .. can record several errors, clears after calling - //++timo TODO: be able to deal with several errors if necessary, for now I'm just warning about pending error messages - // NOTE: forget that, most boards don't seem to follow the OpenGL standard - GLenum iGLError = glGetError(); - if (iGLError != GL_NO_ERROR) - { - // use our own gluErrorString - strcat( text, "gluErrorString: " ); - strcat( text, (char*)gluErrorString( iGLError ) ); - strcat( text, "\n" ); - } - } -#endif - - strcat (text, "An unrecoverable error has occured.\n"); - - ERROR_MESSAGE(text); - - // force close logging if necessary - Sys_LogFile(false); - - _exit (1); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/error.h b/misc/mediasource/extra/netradiant-src/radiant/error.h deleted file mode 100644 index b114640a..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/error.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_ERROR_H) -#define INCLUDED_ERROR_H - -void Error(const char *error, ...); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/feedback.cpp b/misc/mediasource/extra/netradiant-src/radiant/feedback.cpp deleted file mode 100644 index 9a847ce2..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/feedback.cpp +++ /dev/null @@ -1,372 +0,0 @@ -/* -Copyright (C) 1999-2006 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: -// classes used for describing geometry information from q3map feedback -// - -#include "feedback.h" - -#include "debugging/debugging.h" - -#include "igl.h" -#include "iselection.h" - -#include -#include -#include -#include -#include -#include - -#include "map.h" -#include "dialog.h" -#include "mainframe.h" - - -CDbgDlg g_DbgDlg; - -void Feedback_draw2D(VIEWTYPE viewType) -{ - g_DbgDlg.draw2D(viewType); -} - -void CSelectMsg::saxStartElement(message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) -{ - if(string_equal(reinterpret_cast(name), "select")) - { - // read the message - ESelectState = SELECT_MESSAGE; - } - else - { - // read the brush - ASSERT_MESSAGE(string_equal(reinterpret_cast(name), "brush"), "FEEDBACK PARSE ERROR"); - ASSERT_MESSAGE(ESelectState == SELECT_MESSAGE, "FEEDBACK PARSE ERROR"); - ESelectState = SELECT_BRUSH; - globalOutputStream() << message.c_str() << '\n'; - } -} - -void CSelectMsg::saxEndElement(message_info_t *ctx, const xmlChar *name) -{ - if(string_equal(reinterpret_cast(name), "select")) - { - } -} - -void CSelectMsg::saxCharacters(message_info_t *ctx, const xmlChar *ch, int len) -{ - if(ESelectState == SELECT_MESSAGE) - { - message.write(reinterpret_cast(ch), len); - } - else - { - brush.write(reinterpret_cast(ch), len); - } -} - -IGL2DWindow* CSelectMsg::Highlight() -{ - GlobalSelectionSystem().setSelectedAll(false); - int entitynum, brushnum; - if(sscanf(reinterpret_cast(brush.c_str()), "%i %i", &entitynum, &brushnum) == 2) - { - SelectBrush (entitynum, brushnum); - } - return 0; -} - -void CPointMsg::saxStartElement(message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) -{ - if(string_equal(reinterpret_cast(name), "pointmsg")) - { - // read the message - EPointState = POINT_MESSAGE; - } - else - { - // read the brush - ASSERT_MESSAGE(string_equal(reinterpret_cast(name), "point"), "FEEDBACK PARSE ERROR"); - ASSERT_MESSAGE(EPointState == POINT_MESSAGE, "FEEDBACK PARSE ERROR"); - EPointState = POINT_POINT; - globalOutputStream() << message.c_str() << '\n'; - } -} - -void CPointMsg::saxEndElement (message_info_t *ctx, const xmlChar *name) -{ - if(string_equal(reinterpret_cast(name), "pointmsg")) - { - } - else if(string_equal(reinterpret_cast(name), "point")) - { - sscanf(point.c_str(), "%g %g %g", &(pt[0]), &(pt[1]), &(pt[2])); - point.clear(); - } -} - -void CPointMsg::saxCharacters (message_info_t *ctx, const xmlChar *ch, int len) -{ - if(EPointState == POINT_MESSAGE) - { - message.write(reinterpret_cast(ch), len); - } - else - { - ASSERT_MESSAGE(EPointState == POINT_POINT, "FEEDBACK PARSE ERROR"); - point.write(reinterpret_cast(ch), len); - } -} - -IGL2DWindow* CPointMsg::Highlight() -{ - return this; -} - -void CPointMsg::DropHighlight() -{ -} - -void CPointMsg::Draw2D( VIEWTYPE vt ) -{ - int nDim1 = (vt == YZ) ? 1 : 0; - int nDim2 = (vt == XY) ? 1 : 2; - glPointSize(4); - glColor3f(1.0f,0.0f,0.0f); - glBegin (GL_POINTS); - glVertex2f (pt[nDim1], pt[nDim2]); - glEnd(); - glBegin (GL_LINE_LOOP); - glVertex2f (pt[nDim1]-8, pt[nDim2]-8); - glVertex2f (pt[nDim1]+8, pt[nDim2]-8); - glVertex2f (pt[nDim1]+8, pt[nDim2]+8); - glVertex2f (pt[nDim1]-8, pt[nDim2]+8); - glEnd(); -} - -void CWindingMsg::saxStartElement(message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) -{ - if(string_equal(reinterpret_cast(name), "windingmsg")) - { - // read the message - EPointState = WINDING_MESSAGE; - } - else - { - // read the brush - ASSERT_MESSAGE(string_equal(reinterpret_cast(name), "winding"), "FEEDBACK PARSE ERROR"); - ASSERT_MESSAGE(EPointState == WINDING_MESSAGE, "FEEDBACK PARSE ERROR"); - EPointState = WINDING_WINDING; - globalOutputStream() << message.c_str() << '\n'; - } -} - -void CWindingMsg::saxEndElement(message_info_t *ctx, const xmlChar *name) -{ - if(string_equal(reinterpret_cast(name), "windingmsg")) - { - } - else if(string_equal(reinterpret_cast(name), "winding")) - { - const char* c = winding.c_str(); - sscanf(c, "%i ", &numpoints); - - int i = 0; - for(; i < numpoints; i++) - { - c = strchr(c + 1, '('); - if(c) // even if we are given the number of points when the cycle begins .. don't trust it too much - sscanf(c, "(%g %g %g)", &wt[i][0], &wt[i][1], &wt[i][2]); - else - break; - } - numpoints = i; - } -} - -void CWindingMsg::saxCharacters(message_info_t *ctx, const xmlChar *ch, int len) -{ - if(EPointState == WINDING_MESSAGE) - { - message.write(reinterpret_cast(ch), len); - } - else - { - ASSERT_MESSAGE(EPointState == WINDING_WINDING, "FEEDBACK PARSE ERROR"); - winding.write(reinterpret_cast(ch), len); - } -} - -IGL2DWindow* CWindingMsg::Highlight() -{ - return this; -} - -void CWindingMsg::DropHighlight() -{ -} - -void CWindingMsg::Draw2D( VIEWTYPE vt ) -{ - int i; - - int nDim1 = (vt == YZ) ? 1 : 0; - int nDim2 = (vt == XY) ? 1 : 2; - glColor3f(1.0f,0.f,0.0f); - - glPointSize(4); - glBegin (GL_POINTS); - for(i = 0; i < numpoints; i++) - glVertex2f (wt[i][nDim1], wt[i][nDim2]); - glEnd(); - glPointSize(1); - - glEnable (GL_BLEND); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glColor4f(0.133f,0.4f,1.0f,0.5f); - glBegin (GL_POLYGON); - for(i = 0; i < numpoints; i++) - glVertex2f (wt[i][nDim1], wt[i][nDim2]); - glEnd(); - glDisable (GL_BLEND); -} - -// triggered when the user selects an entry in the feedback box -static void feedback_selection_changed(GtkTreeSelection* selection, gpointer data) -{ - g_DbgDlg.DropHighlight(); - - GtkTreeModel* model; - GtkTreeIter selected; - if(gtk_tree_selection_get_selected(selection, &model, &selected)) - { - GtkTreePath* path = gtk_tree_model_get_path(model, &selected); - g_DbgDlg.SetHighlight(gtk_tree_path_get_indices(path)[0]); - gtk_tree_path_free(path); - } -} - -void CDbgDlg::DropHighlight() -{ - if(m_pHighlight != 0) - { - m_pHighlight->DropHighlight(); - m_pHighlight = 0; - m_pDraw2D = 0; - } -} - -void CDbgDlg::SetHighlight(gint row) -{ - ISAXHandler *h = GetElement(row); - if(h != NULL) - { - m_pDraw2D = h->Highlight(); - m_pHighlight = h; - } -} - -ISAXHandler *CDbgDlg::GetElement (std::size_t row) -{ - return static_cast(g_ptr_array_index(m_pFeedbackElements, gint(row))); -} - -void CDbgDlg::Init() -{ - DropHighlight(); - - // free all the ISAXHandler*, clean it - while (m_pFeedbackElements->len) - { - static_cast(g_ptr_array_index (m_pFeedbackElements, 0))->Release(); - g_ptr_array_remove_index (m_pFeedbackElements, 0); - } - - if(m_clist != NULL) - gtk_list_store_clear (m_clist); -} - -void CDbgDlg::Push (ISAXHandler *pHandler) -{ - // push in the list - g_ptr_array_add (m_pFeedbackElements, (void *)pHandler); - - if(GetWidget() == 0) - { - Create(); - } - - // put stuff in the list - gtk_list_store_clear (m_clist); - for(std::size_t i = 0; i < static_cast(m_pFeedbackElements->len); ++i) - { - GtkTreeIter iter; - gtk_list_store_append(m_clist, &iter); - gtk_list_store_set(m_clist, &iter, 0, GetElement(i)->getName(), -1); - } - - ShowDlg(); -} - -GtkWindow* CDbgDlg::BuildDialog() -{ - GtkWindow* window = create_floating_window("Q3Map debug window", MainFrame_getWindow()); - - GtkWidget* scr = gtk_scrolled_window_new (NULL, NULL); - gtk_widget_show (scr); - gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (scr)); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); - - { - GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING); - - GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, NULL); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - } - - { - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); - gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE); - g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(feedback_selection_changed), NULL); - } - - gtk_widget_show(view); - - gtk_container_add(GTK_CONTAINER (scr), view); - - g_object_unref(G_OBJECT(store)); - - m_clist = store; - } - - return window; -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/feedback.h b/misc/mediasource/extra/netradiant-src/radiant/feedback.h deleted file mode 100644 index 4d199bd4..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/feedback.h +++ /dev/null @@ -1,186 +0,0 @@ -/* -Copyright (C) 1999-2006 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: -// classes used for describing geometry information from q3map feedback -// - -#ifndef __Q3MAP_FEEDBACK__ -#define __Q3MAP_FEEDBACK__ - -#include "math/vector.h" -#include "stream/stringstream.h" -#include -#include "xmlstuff.h" -#include "dialog.h" -#include "xywindow.h" - -// we use these classes to let plugins draw inside the Radiant windows -// 2D window like YZ XZ XY -class IGL2DWindow -{ -public: - // Increment the number of references to this object - virtual void IncRef() = 0; - // Decrement the reference count - virtual void DecRef() = 0; - virtual void Draw2D( VIEWTYPE vt ) = 0; -}; - -// 3D window -class IGL3DWindow -{ -public: - // Increment the number of references to this object - virtual void IncRef() = 0; - // Decrement the reference count - virtual void DecRef() = 0; - virtual void Draw3D() = 0; -}; - -// a select message with a brush/entity select information -class CSelectMsg : public ISAXHandler -{ - enum { SELECT_MESSAGE, SELECT_BRUSH } ESelectState; - StringOutputStream message; - StringOutputStream brush; -public: - CSelectMsg() { ESelectState = SELECT_MESSAGE; } - // SAX interface - void saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs); - void saxEndElement (message_info_t *ctx, const xmlChar *name); - void saxCharacters (message_info_t *ctx, const xmlChar *ch, int len); - // for use in the dialog window - const char* getName() { return message.c_str(); } - IGL2DWindow* Highlight(); - void DropHighlight() { } -}; - -class CPointMsg : public ISAXHandler, public IGL2DWindow -{ - enum { POINT_MESSAGE, POINT_POINT } EPointState; - StringOutputStream message; - StringOutputStream point; - Vector3 pt; - int refCount; -public: - CPointMsg() { EPointState = POINT_MESSAGE; refCount = 0; } - // SAX interface - void Release() - { - delete this; - } - void saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs); - void saxEndElement (message_info_t *ctx, const xmlChar *name); - void saxCharacters (message_info_t *ctx, const xmlChar *ch, int len); - // for use in the dialog window - const char* getName() { return message.c_str(); } - IGL2DWindow* Highlight(); - void DropHighlight(); - - // IGL2DWindow interface -------------------------------- - // Increment the number of references to this object - void IncRef() { refCount++; } - // Decrement the reference count - void DecRef() { refCount--; if (refCount <= 0) delete this; } - void Draw2D( VIEWTYPE vt ); -}; - -class CWindingMsg : public ISAXHandler, public IGL2DWindow -{ - enum { WINDING_MESSAGE, WINDING_WINDING } EPointState; - StringOutputStream message; - StringOutputStream winding; - Vector3 wt[256]; - int numpoints; - int refCount; -public: - CWindingMsg() { EPointState = WINDING_MESSAGE; refCount = 0; numpoints = 0; } - // SAX interface - void Release() - { - delete this; - } - void saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs); - void saxEndElement (message_info_t *ctx, const xmlChar *name); - void saxCharacters (message_info_t *ctx, const xmlChar *ch, int len); - // for use in the dialog window - const char* getName() { return message.c_str(); } - IGL2DWindow* Highlight(); - void DropHighlight(); - - // IGL2DWindow interface -------------------------------- - // Increment the number of references to this object - void IncRef() { refCount++; } - // Decrement the reference count - void DecRef() { refCount--; if (refCount <= 0) delete this; } - void Draw2D( VIEWTYPE vt ); -}; - -typedef struct _GtkListStore GtkListStore; - -class CDbgDlg : public Dialog -{ - GPtrArray *m_pFeedbackElements; - // the list widget we use in the dialog - GtkListStore* m_clist; - ISAXHandler *m_pHighlight; - IGL2DWindow* m_pDraw2D; -public: - CDbgDlg() - { - m_pFeedbackElements = g_ptr_array_new(); - m_pHighlight = NULL; - m_pDraw2D = NULL; - } - // refresh items - void Push (ISAXHandler *); - // clean the debug window, release all ISAXHanlders we have - void Init(); - ISAXHandler *GetElement(std::size_t row); - void SetHighlight(gint row); - void DropHighlight(); - void draw2D(VIEWTYPE viewType) - { - if(m_pDraw2D != 0) - { - m_pDraw2D->Draw2D(viewType); - } - } - void destroyWindow() - { - if(GetWidget() != 0) - { - Destroy(); - } - } -// void HideDlg(); -protected: - GtkWindow* BuildDialog(); -}; - -extern CDbgDlg g_DbgDlg; - -void Feedback_draw2D(VIEWTYPE viewType); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/filetypes.cpp b/misc/mediasource/extra/netradiant-src/radiant/filetypes.cpp deleted file mode 100644 index 11c0a272..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/filetypes.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "filetypes.h" - -#include "debugging/debugging.h" - -#include "ifiletypes.h" - -#include "string/string.h" -#include "os/path.h" -#include -#include - -class RadiantFileTypeRegistry : public IFileTypeRegistry -{ - struct filetype_copy_t - { - filetype_copy_t(const char* moduleName, const filetype_t other) - : m_moduleName(moduleName), m_name(other.name), m_pattern(other.pattern), m_can_load(other.can_load), m_can_import(other.can_import), m_can_save(other.can_save) - { - } - const char* getModuleName() const - { - return m_moduleName.c_str(); - } - filetype_t getType() const - { - return filetype_t(m_name.c_str(), m_pattern.c_str(), m_can_load, m_can_save, m_can_import); - } - bool m_can_load; - bool m_can_import; - bool m_can_save; - private: - CopiedString m_moduleName; - CopiedString m_name; - CopiedString m_pattern; - }; - typedef std::vector filetype_list_t; - std::map m_typelists; -public: - RadiantFileTypeRegistry() - { - addType("*", "*", filetype_t("All Files", "*.*")); - } - void addType(const char* moduleType, const char* moduleName, filetype_t type) - { - m_typelists[moduleType].push_back(filetype_copy_t(moduleName, type)); - } - void getTypeList(const char* moduleType, IFileTypeList* typelist, bool want_load, bool want_import, bool want_save) - { - filetype_list_t& list_ref = m_typelists[moduleType]; - for(filetype_list_t::iterator i = list_ref.begin(); i != list_ref.end(); ++i) - { - if(want_load && !(*i).m_can_load) return; - if(want_import && !(*i).m_can_import) return; - if(want_save && !(*i).m_can_save) return; - typelist->addType((*i).getModuleName(), (*i).getType()); - } - } -}; - -static RadiantFileTypeRegistry g_patterns; - -IFileTypeRegistry* GetFileTypeRegistry() -{ - return &g_patterns; -} - -const char* findModuleName(IFileTypeRegistry* registry, const char* moduleType, const char* extension) -{ - class SearchFileTypeList : public IFileTypeList - { - char m_pattern[128]; - const char* m_moduleName; - public: - SearchFileTypeList(const char* ext) - : m_moduleName("") - { - m_pattern[0] = '*'; - m_pattern[1] = '.'; - strncpy(m_pattern + 2, ext, 125); - m_pattern[127] = '\0'; - } - void addType(const char* moduleName, filetype_t type) - { - if(extension_equal(m_pattern, type.pattern)) - { - m_moduleName = moduleName; - } - } - - const char* getModuleName() - { - return m_moduleName; - } - } search(extension); - registry->getTypeList(moduleType, &search); - return search.getModuleName(); -} - - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class FiletypesAPI -{ - IFileTypeRegistry* m_filetypes; -public: - typedef IFileTypeRegistry Type; - STRING_CONSTANT(Name, "*"); - - FiletypesAPI() - { - m_filetypes = GetFileTypeRegistry(); - } - IFileTypeRegistry* getTable() - { - return m_filetypes; - } -}; - -typedef SingletonModule FiletypesModule; -typedef Static StaticFiletypesModule; -StaticRegisterModule staticRegisterFiletypes(StaticFiletypesModule::instance()); - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/filetypes.h b/misc/mediasource/extra/netradiant-src/radiant/filetypes.h deleted file mode 100644 index f924c793..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/filetypes.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_FILETYPES_H) -#define INCLUDED_FILETYPES_H - -class IFileTypeRegistry; -IFileTypeRegistry* GetFileTypeRegistry(); -const char* findModuleName(IFileTypeRegistry* registry, const char* moduleType, const char* extension); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/filters.cpp b/misc/mediasource/extra/netradiant-src/radiant/filters.cpp deleted file mode 100644 index 235e2910..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/filters.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "filters.h" - -#include "debugging/debugging.h" - -#include "ifilter.h" - -#include "scenelib.h" - -#include -#include - -#include "gtkutil/widget.h" -#include "gtkutil/menu.h" -#include "gtkmisc.h" -#include "mainframe.h" -#include "commands.h" -#include "preferences.h" - -struct filters_globals_t -{ - std::size_t exclude; - - filters_globals_t() : - exclude(0) - { - } -}; - -filters_globals_t g_filters_globals; - -inline bool filter_active(int mask) -{ - return (g_filters_globals.exclude & mask) > 0; -} - -class FilterWrapper -{ -public: - FilterWrapper(Filter& filter, int mask) : m_filter(filter), m_mask(mask) - { - } - void update() - { - m_filter.setActive(filter_active(m_mask)); - } -private: - Filter& m_filter; - int m_mask; -}; - -typedef std::list Filters; -Filters g_filters; - -typedef std::set Filterables; -Filterables g_filterables; - -void UpdateFilters() -{ - { - for(Filters::iterator i = g_filters.begin(); i != g_filters.end(); ++i) - { - (*i).update(); - } - } - - { - for(Filterables::iterator i = g_filterables.begin(); i != g_filterables.end(); ++i) - { - (*i)->updateFiltered(); - } - } -} - - -class BasicFilterSystem : public FilterSystem -{ -public: - void addFilter(Filter& filter, int mask) - { - g_filters.push_back(FilterWrapper(filter, mask)); - g_filters.back().update(); - } - void registerFilterable(Filterable& filterable) - { - ASSERT_MESSAGE(g_filterables.find(&filterable) == g_filterables.end(), "filterable already registered"); - filterable.updateFiltered(); - g_filterables.insert(&filterable); - } - void unregisterFilterable(Filterable& filterable) - { - ASSERT_MESSAGE(g_filterables.find(&filterable) != g_filterables.end(), "filterable not registered"); - g_filterables.erase(&filterable); - } -}; - -BasicFilterSystem g_FilterSystem; - -FilterSystem& GetFilterSystem() -{ - return g_FilterSystem; -} - -void PerformFiltering() -{ - UpdateFilters(); - SceneChangeNotify(); -} - -class ToggleFilterFlag -{ - const unsigned int m_mask; -public: - ToggleItem m_item; - - ToggleFilterFlag(unsigned int mask) : m_mask(mask), m_item(ActiveCaller(*this)) - { - } - ToggleFilterFlag(const ToggleFilterFlag& other) : m_mask(other.m_mask), m_item(ActiveCaller(*this)) - { - } - void active(const BoolImportCallback& importCallback) - { - importCallback((g_filters_globals.exclude & m_mask) != 0); - } - typedef MemberCaller1 ActiveCaller; - void toggle() - { - g_filters_globals.exclude ^= m_mask; - m_item.update(); - PerformFiltering(); - } - void reset() - { - g_filters_globals.exclude = 0; - m_item.update(); - PerformFiltering(); - } - typedef MemberCaller ToggleCaller; -}; - - -typedef std::list ToggleFilterFlags; -ToggleFilterFlags g_filter_items; - -void add_filter_command(unsigned int flag, const char* command, const Accelerator& accelerator) -{ - g_filter_items.push_back(ToggleFilterFlag(flag)); - GlobalToggles_insert(command, ToggleFilterFlag::ToggleCaller(g_filter_items.back()), ToggleItem::AddCallbackCaller(g_filter_items.back().m_item), accelerator); -} - -void InvertFilters() -{ - std::list::iterator iter; - - for(iter = g_filter_items.begin(); iter != g_filter_items.end(); ++iter) - { - iter->toggle(); - } -} - -void ResetFilters() -{ - std::list::iterator iter; - - for(iter = g_filter_items.begin(); iter != g_filter_items.end(); ++iter) - { - iter->reset(); - } -} - -void Filters_constructMenu(GtkMenu* menu_in_menu) -{ - create_check_menu_item_with_mnemonic(menu_in_menu, "World", "FilterWorldBrushes"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Entities", "FilterEntities"); - if(g_pGameDescription->mGameType == "doom3") - { - create_check_menu_item_with_mnemonic(menu_in_menu, "Visportals", "FilterVisportals"); - } - else - { - create_check_menu_item_with_mnemonic(menu_in_menu, "Areaportals", "FilterAreaportals"); - } - create_check_menu_item_with_mnemonic(menu_in_menu, "Translucent", "FilterTranslucent"); - if(g_pGameDescription->mGameType != "doom3") - { - create_check_menu_item_with_mnemonic(menu_in_menu, "Liquids", "FilterLiquids"); - } - create_check_menu_item_with_mnemonic(menu_in_menu, "Caulk", "FilterCaulk"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Clips", "FilterClips"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Paths", "FilterPaths"); - if(g_pGameDescription->mGameType != "doom3") - { - create_check_menu_item_with_mnemonic(menu_in_menu, "Clusterportals", "FilterClusterportals"); - } - create_check_menu_item_with_mnemonic(menu_in_menu, "Lights", "FilterLights"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Structural", "FilterStructural"); - if(g_pGameDescription->mGameType != "doom3") - { - create_check_menu_item_with_mnemonic(menu_in_menu, "Lightgrid", "FilterLightgrid"); - } - create_check_menu_item_with_mnemonic(menu_in_menu, "Patches", "FilterPatches"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Details", "FilterDetails"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Hints", "FilterHintsSkips"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Models", "FilterModels"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Triggers", "FilterTriggers"); - if(g_pGameDescription->mGameType != "doom3") - { - create_check_menu_item_with_mnemonic(menu_in_menu, "Botclips", "FilterBotClips"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Decals", "FilterDecals"); - } - // filter manipulation - menu_separator(menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Invert filters", "InvertFilters"); - create_menu_item_with_mnemonic(menu_in_menu, "Reset filters", "ResetFilters"); -} - - -#include "preferencesystem.h" -#include "stringio.h" - -void ConstructFilters() -{ - GlobalPreferenceSystem().registerPreference("SI_Exclude", SizeImportStringCaller(g_filters_globals.exclude), SizeExportStringCaller(g_filters_globals.exclude)); - - GlobalCommands_insert("InvertFilters", FreeCaller()); - GlobalCommands_insert("ResetFilters", FreeCaller()); - - add_filter_command(EXCLUDE_WORLD, "FilterWorldBrushes", Accelerator('1', (GdkModifierType)GDK_MOD1_MASK)); - add_filter_command(EXCLUDE_ENT, "FilterEntities", Accelerator('2', (GdkModifierType)GDK_MOD1_MASK)); - if(g_pGameDescription->mGameType == "doom3") - { - add_filter_command(EXCLUDE_VISPORTALS, "FilterVisportals", Accelerator('3', (GdkModifierType)GDK_MOD1_MASK)); - } - else - { - add_filter_command(EXCLUDE_AREAPORTALS, "FilterAreaportals", Accelerator('3', (GdkModifierType)GDK_MOD1_MASK)); - } - add_filter_command(EXCLUDE_TRANSLUCENT, "FilterTranslucent", Accelerator('4', (GdkModifierType)GDK_MOD1_MASK)); - add_filter_command(EXCLUDE_LIQUIDS, "FilterLiquids", Accelerator('5', (GdkModifierType)GDK_MOD1_MASK)); - add_filter_command(EXCLUDE_CAULK, "FilterCaulk", Accelerator('6', (GdkModifierType)GDK_MOD1_MASK )); - add_filter_command(EXCLUDE_CLIP, "FilterClips", Accelerator('7', (GdkModifierType)GDK_MOD1_MASK)); - add_filter_command(EXCLUDE_PATHS, "FilterPaths", Accelerator('8', (GdkModifierType)GDK_MOD1_MASK)); - if(g_pGameDescription->mGameType != "doom3") - { - add_filter_command(EXCLUDE_CLUSTERPORTALS, "FilterClusterportals", Accelerator('9', (GdkModifierType)GDK_MOD1_MASK)); - } - add_filter_command(EXCLUDE_LIGHTS, "FilterLights", Accelerator('0', (GdkModifierType)GDK_MOD1_MASK)); - add_filter_command(EXCLUDE_STRUCTURAL, "FilterStructural", Accelerator('D', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - if(g_pGameDescription->mGameType != "doom3") - { - add_filter_command(EXCLUDE_LIGHTGRID, "FilterLightgrid", accelerator_null()); - } - add_filter_command(EXCLUDE_CURVES, "FilterPatches", Accelerator('P', (GdkModifierType)GDK_CONTROL_MASK)); - add_filter_command(EXCLUDE_DETAILS, "FilterDetails", Accelerator('D', (GdkModifierType)GDK_CONTROL_MASK)); - add_filter_command(EXCLUDE_HINTSSKIPS, "FilterHintsSkips", Accelerator('H', (GdkModifierType)GDK_CONTROL_MASK)); - add_filter_command(EXCLUDE_MODELS, "FilterModels", Accelerator('M', (GdkModifierType)GDK_SHIFT_MASK)); - add_filter_command(EXCLUDE_TRIGGERS, "FilterTriggers", Accelerator('T', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - if(g_pGameDescription->mGameType != "doom3") - { - add_filter_command(EXCLUDE_BOTCLIP, "FilterBotClips", Accelerator('M', (GdkModifierType)GDK_MOD1_MASK)); - add_filter_command(EXCLUDE_DECALS, "FilterDecals", Accelerator('D', (GdkModifierType)GDK_SHIFT_MASK)); - } - - PerformFiltering(); -} - -void DestroyFilters() -{ - g_filters.clear(); -} - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class FilterAPI -{ - FilterSystem* m_filter; -public: - typedef FilterSystem Type; - STRING_CONSTANT(Name, "*"); - - FilterAPI() - { - ConstructFilters(); - - m_filter = &GetFilterSystem(); - } - ~FilterAPI() - { - DestroyFilters(); - } - FilterSystem* getTable() - { - return m_filter; - } -}; - -typedef SingletonModule FilterModule; -typedef Static StaticFilterModule; -StaticRegisterModule staticRegisterFilter(StaticFilterModule::instance()); - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/filters.h b/misc/mediasource/extra/netradiant-src/radiant/filters.h deleted file mode 100644 index 631cef84..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/filters.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_FILTERS_H) -#define INCLUDED_FILTERS_H - -typedef struct _GtkMenu GtkMenu; -void Filters_constructMenu(GtkMenu* menu_in_menu); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/findtexturedialog.cpp b/misc/mediasource/extra/netradiant-src/radiant/findtexturedialog.cpp deleted file mode 100644 index 52891d80..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/findtexturedialog.cpp +++ /dev/null @@ -1,301 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Find/Replace textures dialogs -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "findtexturedialog.h" - -#include "debugging/debugging.h" - -#include "ishaders.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gtkutil/window.h" -#include "stream/stringstream.h" - -#include "commands.h" -#include "dialog.h" -#include "select.h" -#include "textureentry.h" - - - -class FindTextureDialog : public Dialog -{ - public: - static void setReplaceStr(const char* name); - static void setFindStr(const char* name); - static bool isOpen(); - static void show(); - typedef FreeCaller<&FindTextureDialog::show> ShowCaller; - static void updateTextures(const char* name); - - FindTextureDialog(); - virtual ~FindTextureDialog(); - GtkWindow* BuildDialog(); - - void constructWindow(GtkWindow* parent) - { - m_parent = parent; - Create(); - } - void destroyWindow() - { - Destroy(); - } - - - bool m_bSelectedOnly; - CopiedString m_strFind; - CopiedString m_strReplace; -}; - -FindTextureDialog g_FindTextureDialog; -static bool g_bFindActive = true; - -namespace -{ - void FindTextureDialog_apply() - { - StringOutputStream find(256); - StringOutputStream replace(256); - - find << "textures/" << g_FindTextureDialog.m_strFind.c_str(); - replace << "textures/" << g_FindTextureDialog.m_strReplace.c_str(); - FindReplaceTextures(find.c_str(), replace.c_str(), g_FindTextureDialog.m_bSelectedOnly); - } - - static void OnApply(GtkWidget* widget, gpointer data) - { - g_FindTextureDialog.exportData(); - FindTextureDialog_apply(); - } - - static void OnFind(GtkWidget* widget, gpointer data) - { - g_FindTextureDialog.exportData(); - FindTextureDialog_apply(); - } - - static void OnOK(GtkWidget* widget, gpointer data) - { - g_FindTextureDialog.exportData(); - FindTextureDialog_apply(); - g_FindTextureDialog.HideDlg(); - } - - static void OnClose(GtkWidget* widget, gpointer data) - { - g_FindTextureDialog.HideDlg(); - } - - - static gint find_focus_in (GtkWidget* widget, GdkEventFocus *event, gpointer data) - { - g_bFindActive = true; - return FALSE; - } - - static gint replace_focus_in (GtkWidget* widget, GdkEventFocus *event, gpointer data) - { - g_bFindActive = false; - return FALSE; - } -} - -// ============================================================================= -// FindTextureDialog class - -FindTextureDialog::FindTextureDialog() -{ - m_bSelectedOnly = FALSE; -} - -FindTextureDialog::~FindTextureDialog() -{ -} - -GtkWindow* FindTextureDialog::BuildDialog() -{ - GtkWidget* vbox, *hbox, *table, *label; - GtkWidget* button, *check, *entry; - - GtkWindow* dlg = create_floating_window("Find / Replace Texture(s)", m_parent); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_container_add(GTK_CONTAINER(dlg), GTK_WIDGET(hbox)); - gtk_container_set_border_width (GTK_CONTAINER (hbox), 5); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - - table = gtk_table_new (2, 2, FALSE); - gtk_widget_show (table); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings (GTK_TABLE (table), 5); - gtk_table_set_col_spacings (GTK_TABLE (table), 5); - - label = gtk_label_new ("Find:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - - label = gtk_label_new ("Replace:"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); - - entry = gtk_entry_new(); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(entry), "focus_in_event", - G_CALLBACK(find_focus_in), 0); - AddDialogData(*GTK_ENTRY(entry), m_strFind); - GlobalTextureEntryCompletion::instance().connect(GTK_ENTRY(entry)); - - entry = gtk_entry_new(); - gtk_widget_show (entry); - gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(entry), "focus_in_event", - G_CALLBACK(replace_focus_in), 0); - AddDialogData(*GTK_ENTRY(entry), m_strReplace); - GlobalTextureEntryCompletion::instance().connect(GTK_ENTRY(entry)); - - check = gtk_check_button_new_with_label ("Within selected brushes only"); - gtk_widget_show (check); - gtk_box_pack_start(GTK_BOX(vbox), check, TRUE, TRUE, 0); - AddDialogData(*GTK_TOGGLE_BUTTON(check), m_bSelectedOnly); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); - - button = gtk_button_new_with_label ("Apply"); - gtk_widget_show (button); - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnApply), 0); - gtk_widget_set_usize (button, 60, -2); - - button = gtk_button_new_with_label ("Close"); - gtk_widget_show (button); - gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnClose), 0); - gtk_widget_set_usize (button, 60, -2); - - return dlg; -} - -void FindTextureDialog::updateTextures(const char* name) -{ - if (isOpen()) - { - if (g_bFindActive) - { - setFindStr(name + 9); - } - else - { - setReplaceStr(name + 9); - } - } -} - -bool FindTextureDialog::isOpen() -{ - return GTK_WIDGET_VISIBLE(g_FindTextureDialog.GetWidget()) == TRUE; -} - -void FindTextureDialog::setFindStr(const char* name) -{ - g_FindTextureDialog.exportData(); - g_FindTextureDialog.m_strFind = name; - g_FindTextureDialog.importData(); -} - -void FindTextureDialog::setReplaceStr(const char* name) -{ - g_FindTextureDialog.exportData(); - g_FindTextureDialog.m_strReplace = name; - g_FindTextureDialog.importData(); -} - -void FindTextureDialog::show() -{ - g_FindTextureDialog.ShowDlg(); -} - - -void FindTextureDialog_constructWindow(GtkWindow* main_window) -{ - g_FindTextureDialog.constructWindow(main_window); -} - -void FindTextureDialog_destroyWindow() -{ - g_FindTextureDialog.destroyWindow(); -} - -bool FindTextureDialog_isOpen() -{ - return g_FindTextureDialog.isOpen(); -} - -void FindTextureDialog_selectTexture(const char* name) -{ - g_FindTextureDialog.updateTextures(name); -} - -void FindTextureDialog_Construct() -{ - GlobalCommands_insert("FindReplaceTextures", FindTextureDialog::ShowCaller()); -} - -void FindTextureDialog_Destroy() -{ -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/findtexturedialog.h b/misc/mediasource/extra/netradiant-src/radiant/findtexturedialog.h deleted file mode 100644 index 5535ec5d..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/findtexturedialog.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_FINDTEXTUREDIALOG_H) -#define INCLUDED_FINDTEXTUREDIALOG_H - -void FindTextureDialog_Construct(); -void FindTextureDialog_Destroy(); - -typedef struct _GtkWindow GtkWindow; -void FindTextureDialog_constructWindow(GtkWindow* main_window); -void FindTextureDialog_destroyWindow(); -bool FindTextureDialog_isOpen(); -void FindTextureDialog_selectTexture(const char* name); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/glwidget.cpp b/misc/mediasource/extra/netradiant-src/radiant/glwidget.cpp deleted file mode 100644 index 47500097..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/glwidget.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "glwidget.h" - -#include "igtkgl.h" -#include "modulesystem.h" -#include "gtkutil/glwidget.h" - -class GtkGLAPI -{ - _QERGtkGLTable m_gtkgl; -public: - typedef _QERGtkGLTable Type; - STRING_CONSTANT(Name, "*"); - - GtkGLAPI() - { - m_gtkgl.glwidget_new = &glwidget_new; - m_gtkgl.glwidget_swap_buffers = &glwidget_swap_buffers; - m_gtkgl.glwidget_make_current = &glwidget_make_current; - m_gtkgl.glwidget_destroy_context = &glwidget_destroy_context; - m_gtkgl.glwidget_create_context = &glwidget_create_context; - } - _QERGtkGLTable* getTable() - { - return &m_gtkgl; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule GtkGLModule; -typedef Static StaticGtkGLModule; -StaticRegisterModule staticRegisterGtkGL(StaticGtkGLModule::instance()); - diff --git a/misc/mediasource/extra/netradiant-src/radiant/glwidget.h b/misc/mediasource/extra/netradiant-src/radiant/glwidget.h deleted file mode 100644 index 6d9ab361..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/glwidget.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GLWIDGET_H) -#define INCLUDED_GLWIDGET_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/grid.cpp b/misc/mediasource/extra/netradiant-src/radiant/grid.cpp deleted file mode 100644 index f25a0d92..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/grid.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "grid.h" - -#include -#include -#include - -#include "preferencesystem.h" - -#include "gtkutil/widget.h" -#include "signal/signal.h" -#include "stringio.h" - -#include "gtkmisc.h" -#include "commands.h" -#include "preferences.h" - - - -Signal0 g_gridChange_callbacks; - -void AddGridChangeCallback(const SignalHandler& handler) -{ - g_gridChange_callbacks.connectLast(handler); - handler(); -} - -void GridChangeNotify() -{ - g_gridChange_callbacks(); -} - -enum GridPower -{ - GRIDPOWER_0125 = -3, - GRIDPOWER_025 = -2, - GRIDPOWER_05 = -1, - GRIDPOWER_1 = 0, - GRIDPOWER_2 = 1, - GRIDPOWER_4 = 2, - GRIDPOWER_8 = 3, - GRIDPOWER_16 = 4, - GRIDPOWER_32 = 5, - GRIDPOWER_64 = 6, - GRIDPOWER_128 = 7, - GRIDPOWER_256 = 8, -}; - - -typedef const char* GridName; -// this must match the GridPower enumeration -const GridName g_gridnames[] = { - "0.125", - "0.25", - "0.5", - "1", - "2", - "4", - "8", - "16", - "32", - "64", - "128", - "256", -}; - -inline GridPower GridPower_forGridDefault(int gridDefault) -{ - return static_cast(gridDefault - 3); -} - -inline int GridDefault_forGridPower(GridPower gridPower) -{ - return gridPower + 3; -} - -int g_grid_default = GridDefault_forGridPower(GRIDPOWER_8); - -int g_grid_power = GridPower_forGridDefault(g_grid_default); - -bool g_grid_snap = true; - -int Grid_getPower() -{ - return g_grid_power; -} - -inline float GridSize_forGridPower(int gridPower) -{ - return pow(2.0f, gridPower); -} - -float g_gridsize = GridSize_forGridPower(g_grid_power); - -float GetSnapGridSize() -{ - return g_grid_snap ? g_gridsize : 0; -} - -float GetGridSize() -{ - return g_gridsize; -} - - -void setGridPower(GridPower power); - -class GridMenuItem -{ - GridPower m_id; - - GridMenuItem(const GridMenuItem& other); // NOT COPYABLE - GridMenuItem& operator=(const GridMenuItem& other); // NOT ASSIGNABLE -public: - ToggleItem m_item; - - GridMenuItem(GridPower id) : m_id(id), m_item(ExportCaller(*this)) - { - } - void set() - { - g_grid_power = m_id; - m_item.update(); - setGridPower(m_id); - } - typedef MemberCaller SetCaller; - void active(const BoolImportCallback& importCallback) - { - importCallback(g_grid_power == m_id); - } - typedef MemberCaller1 ExportCaller; -}; - -GridMenuItem g_gridMenu0125(GRIDPOWER_0125); -GridMenuItem g_gridMenu025(GRIDPOWER_025); -GridMenuItem g_gridMenu05(GRIDPOWER_05); -GridMenuItem g_gridMenu1(GRIDPOWER_1); -GridMenuItem g_gridMenu2(GRIDPOWER_2); -GridMenuItem g_gridMenu4(GRIDPOWER_4); -GridMenuItem g_gridMenu8(GRIDPOWER_8); -GridMenuItem g_gridMenu16(GRIDPOWER_16); -GridMenuItem g_gridMenu32(GRIDPOWER_32); -GridMenuItem g_gridMenu64(GRIDPOWER_64); -GridMenuItem g_gridMenu128(GRIDPOWER_128); -GridMenuItem g_gridMenu256(GRIDPOWER_256); - -void setGridPower(GridPower power) -{ - g_grid_snap = true; - g_gridsize = GridSize_forGridPower(power); - - g_gridMenu0125.m_item.update(); - g_gridMenu025.m_item.update(); - g_gridMenu05.m_item.update(); - g_gridMenu1.m_item.update(); - g_gridMenu2.m_item.update(); - g_gridMenu4.m_item.update(); - g_gridMenu8.m_item.update(); - g_gridMenu16.m_item.update(); - g_gridMenu32.m_item.update(); - g_gridMenu64.m_item.update(); - g_gridMenu128.m_item.update(); - g_gridMenu256.m_item.update(); - GridChangeNotify(); -} - -void GridPrev() -{ - g_grid_snap = true; - if(g_grid_power > GRIDPOWER_0125) - { - setGridPower(static_cast(--g_grid_power)); - } -} - -void GridNext() -{ - g_grid_snap = true; - if(g_grid_power < GRIDPOWER_256) - { - setGridPower(static_cast(++g_grid_power)); - } -} - -void ToggleGridSnap() -{ - g_grid_snap = !g_grid_snap; - GridChangeNotify(); -} - -void Grid_registerCommands() -{ - GlobalCommands_insert("GridDown", FreeCaller(), Accelerator('[')); - GlobalCommands_insert("GridUp", FreeCaller(), Accelerator(']')); - - GlobalCommands_insert("ToggleGridSnap", FreeCaller()); - - GlobalToggles_insert("SetGrid0.125", GridMenuItem::SetCaller(g_gridMenu0125), ToggleItem::AddCallbackCaller(g_gridMenu0125.m_item)); - GlobalToggles_insert("SetGrid0.25", GridMenuItem::SetCaller(g_gridMenu025), ToggleItem::AddCallbackCaller(g_gridMenu025.m_item)); - GlobalToggles_insert("SetGrid0.5", GridMenuItem::SetCaller(g_gridMenu05), ToggleItem::AddCallbackCaller(g_gridMenu05.m_item)); - GlobalToggles_insert("SetGrid1", GridMenuItem::SetCaller(g_gridMenu1), ToggleItem::AddCallbackCaller(g_gridMenu1.m_item), Accelerator('1')); - GlobalToggles_insert("SetGrid2", GridMenuItem::SetCaller(g_gridMenu2), ToggleItem::AddCallbackCaller(g_gridMenu2.m_item), Accelerator('2')); - GlobalToggles_insert("SetGrid4", GridMenuItem::SetCaller(g_gridMenu4), ToggleItem::AddCallbackCaller(g_gridMenu4.m_item), Accelerator('3')); - GlobalToggles_insert("SetGrid8", GridMenuItem::SetCaller(g_gridMenu8), ToggleItem::AddCallbackCaller(g_gridMenu8.m_item), Accelerator('4')); - GlobalToggles_insert("SetGrid16", GridMenuItem::SetCaller(g_gridMenu16), ToggleItem::AddCallbackCaller(g_gridMenu16.m_item), Accelerator('5')); - GlobalToggles_insert("SetGrid32", GridMenuItem::SetCaller(g_gridMenu32), ToggleItem::AddCallbackCaller(g_gridMenu32.m_item), Accelerator('6')); - GlobalToggles_insert("SetGrid64", GridMenuItem::SetCaller(g_gridMenu64), ToggleItem::AddCallbackCaller(g_gridMenu64.m_item), Accelerator('7')); - GlobalToggles_insert("SetGrid128", GridMenuItem::SetCaller(g_gridMenu128), ToggleItem::AddCallbackCaller(g_gridMenu128.m_item), Accelerator('8')); - GlobalToggles_insert("SetGrid256", GridMenuItem::SetCaller(g_gridMenu256), ToggleItem::AddCallbackCaller(g_gridMenu256.m_item), Accelerator('9')); -} - - -void Grid_constructMenu(GtkMenu* menu) -{ - create_check_menu_item_with_mnemonic(menu, "Grid0.125", "SetGrid0.125"); - create_check_menu_item_with_mnemonic(menu, "Grid0.25", "SetGrid0.25"); - create_check_menu_item_with_mnemonic(menu, "Grid0.5", "SetGrid0.5"); - create_check_menu_item_with_mnemonic(menu, "Grid1", "SetGrid1"); - create_check_menu_item_with_mnemonic(menu, "Grid2", "SetGrid2"); - create_check_menu_item_with_mnemonic(menu, "Grid4", "SetGrid4"); - create_check_menu_item_with_mnemonic(menu, "Grid8", "SetGrid8"); - create_check_menu_item_with_mnemonic(menu, "Grid16", "SetGrid16"); - create_check_menu_item_with_mnemonic(menu, "Grid32", "SetGrid32"); - create_check_menu_item_with_mnemonic(menu, "Grid64", "SetGrid64"); - create_check_menu_item_with_mnemonic(menu, "Grid128", "SetGrid128"); - create_check_menu_item_with_mnemonic(menu, "Grid256", "SetGrid256"); -} - -void Grid_registerShortcuts() -{ - command_connect_accelerator("ToggleGrid"); - command_connect_accelerator("GridDown"); - command_connect_accelerator("GridUp"); - command_connect_accelerator("ToggleGridSnap"); -} - -void Grid_constructPreferences(PreferencesPage& page) -{ - page.appendCombo( - "Default grid spacing", - g_grid_default, - ARRAY_RANGE(g_gridnames) - ); -} -void Grid_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Grid", "Grid Settings")); - Grid_constructPreferences(page); -} -void Grid_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - -void Grid_construct() -{ - Grid_registerPreferencesPage(); - - g_grid_default = GridDefault_forGridPower(GRIDPOWER_8); - - GlobalPreferenceSystem().registerPreference("GridDefault", IntImportStringCaller(g_grid_default), IntExportStringCaller(g_grid_default)); - - g_grid_power = GridPower_forGridDefault(g_grid_default); - g_gridsize = GridSize_forGridPower(g_grid_power); -} - -void Grid_destroy() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/grid.h b/misc/mediasource/extra/netradiant-src/radiant/grid.h deleted file mode 100644 index 42dfd703..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/grid.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_GRID_H) -#define INCLUDED_GRID_H - -#include "signal/signalfwd.h" - -float GetSnapGridSize(); -float GetGridSize(); -int Grid_getPower(); - -void AddGridChangeCallback(const SignalHandler& handler); - -void Grid_registerCommands(); -typedef struct _GtkMenu GtkMenu; -void Grid_constructMenu(GtkMenu* menu); - -void Grid_registerShortcuts(); - -void Grid_construct(); -void Grid_destroy(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/groupdialog.cpp b/misc/mediasource/extra/netradiant-src/radiant/groupdialog.cpp deleted file mode 100644 index 1b89cc2f..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/groupdialog.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Floating dialog that contains a notebook with at least Entities and Group tabs -// I merged the 2 MS Windows dialogs in a single class -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "groupdialog.h" - -#include "debugging/debugging.h" - -#include - -#include -#include -#include -#include - -#include "gtkutil/widget.h" -#include "gtkutil/accelerator.h" -#include "entityinspector.h" -#include "gtkmisc.h" -#include "multimon.h" -#include "console.h" -#include "commands.h" - - -#include -#include "gtkutil/window.h" - -class GroupDlg -{ -public: - GtkWidget* m_pNotebook; - GtkWindow* m_window; - - GroupDlg(); - void Create(GtkWindow* parent); - - void Show() - { - // workaround for strange gtk behaviour - modifying the contents of a window while it is not visible causes the window position to change without sending a configure_event - m_position_tracker.sync(m_window); - gtk_widget_show(GTK_WIDGET(m_window)); - } - void Hide() - { - gtk_widget_hide(GTK_WIDGET(m_window)); - } - - WindowPositionTracker m_position_tracker; -}; - -namespace -{ - GroupDlg g_GroupDlg; - - std::size_t g_current_page; - std::vector g_pages; -} - -void GroupDialog_updatePageTitle(GtkWindow* window, std::size_t pageIndex) -{ - if(pageIndex < g_pages.size()) - { - g_pages[pageIndex](PointerCaller1(window)); - } -} - -static gboolean switch_page(GtkNotebook *notebook, GtkNotebookPage *page, guint page_num, gpointer data) -{ - GroupDialog_updatePageTitle(GTK_WINDOW(data), page_num); - g_current_page = page_num; - - return FALSE; -} - -GroupDlg::GroupDlg() : m_window(0) -{ - m_position_tracker.setPosition(c_default_window_pos); -} - -void GroupDlg::Create(GtkWindow* parent) -{ - ASSERT_MESSAGE(m_window == 0, "dialog already created"); - - GtkWindow* window = create_persistent_floating_window("Entities", parent); - - global_accel_connect_window(window); - - window_connect_focus_in_clear_focus_widget(window); - - m_window = window; - -#ifdef WIN32 - if( g_multimon_globals.m_bStartOnPrimMon ) - { - WindowPosition pos(m_position_tracker.getPosition()); - PositionWindowOnPrimaryScreen(pos); - m_position_tracker.setPosition(pos); - } -#endif - m_position_tracker.connect(window); - - { - GtkWidget* notebook = gtk_notebook_new(); - gtk_widget_show(notebook); - gtk_container_add (GTK_CONTAINER (window), notebook); - gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_BOTTOM); - m_pNotebook = notebook; - - g_signal_connect(G_OBJECT(notebook), "switch_page", G_CALLBACK(switch_page), window); - } -} - - -GtkWidget* GroupDialog_addPage(const char* tabLabel, GtkWidget* widget, const StringExportCallback& title) -{ - GtkWidget* w = gtk_label_new(tabLabel); - gtk_widget_show(w); - GtkWidget* page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gtk_notebook_insert_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), widget, w, -1)); - g_pages.push_back(title); - - return page; -} - - -bool GroupDialog_isShown() -{ - return widget_is_visible(GTK_WIDGET(g_GroupDlg.m_window)); -} -void GroupDialog_setShown(bool shown) -{ - shown ? g_GroupDlg.Show() : g_GroupDlg.Hide(); -} -void GroupDialog_ToggleShow() -{ - GroupDialog_setShown(!GroupDialog_isShown()); -} - -void GroupDialog_constructWindow(GtkWindow* main_window) -{ - g_GroupDlg.Create(main_window); -} -void GroupDialog_destroyWindow() -{ - ASSERT_NOTNULL(g_GroupDlg.m_window); - destroy_floating_window(g_GroupDlg.m_window); - g_GroupDlg.m_window = 0; -} - - -GtkWindow* GroupDialog_getWindow() -{ - return g_GroupDlg.m_window; -} -void GroupDialog_show() -{ - g_GroupDlg.Show(); -} - -GtkWidget* GroupDialog_getPage() -{ - return gtk_notebook_get_nth_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gint(g_current_page)); -} - -void GroupDialog_setPage(GtkWidget* page) -{ - g_current_page = gtk_notebook_page_num(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), page); - gtk_notebook_set_current_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gint(g_current_page)); -} - -void GroupDialog_showPage(GtkWidget* page) -{ - if(GroupDialog_getPage() == page) - { - GroupDialog_ToggleShow(); - } - else - { - gtk_widget_show(GTK_WIDGET(g_GroupDlg.m_window)); - GroupDialog_setPage(page); - } -} - -void GroupDialog_cycle() -{ - g_current_page = (g_current_page + 1) % g_pages.size(); - gtk_notebook_set_current_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gint(g_current_page)); -} - -void GroupDialog_updatePageTitle(GtkWidget* page) -{ - if(GroupDialog_getPage() == page) - { - GroupDialog_updatePageTitle(g_GroupDlg.m_window, g_current_page); - } -} - - -#include "preferencesystem.h" - -void GroupDialog_Construct() -{ - GlobalPreferenceSystem().registerPreference("EntityWnd", WindowPositionTrackerImportStringCaller(g_GroupDlg.m_position_tracker), WindowPositionTrackerExportStringCaller(g_GroupDlg.m_position_tracker)); - - GlobalCommands_insert("ViewEntityInfo", FreeCaller(), Accelerator('N')); -} -void GroupDialog_Destroy() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/groupdialog.h b/misc/mediasource/extra/netradiant-src/radiant/groupdialog.h deleted file mode 100644 index 92caffab..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/groupdialog.h +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_GROUPDIALOG_H) -#define INCLUDED_GROUPDIALOG_H - -#include "generic/callback.h" - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; - -void GroupDialog_Construct(); -void GroupDialog_Destroy(); - -void GroupDialog_constructWindow(GtkWindow* main_window); -void GroupDialog_destroyWindow(); -GtkWindow* GroupDialog_getWindow(); -void GroupDialog_show(); - -inline void RawStringExport(const char* string, const StringImportCallback& importer) -{ - importer(string); -} -typedef ConstPointerCaller1 RawStringExportCaller; -GtkWidget* GroupDialog_addPage(const char* tabLabel, GtkWidget* widget, const StringExportCallback& title); - -void GroupDialog_showPage(GtkWidget* page); -void GroupDialog_updatePageTitle(GtkWidget* page); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/gtkdlgs.cpp b/misc/mediasource/extra/netradiant-src/radiant/gtkdlgs.cpp deleted file mode 100644 index 57ed278d..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/gtkdlgs.cpp +++ /dev/null @@ -1,1105 +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. -*/ - -// -// Some small dialogs that don't need much -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "gtkdlgs.h" - -#include "debugging/debugging.h" -#include "version.h" -#include "aboutmsg.h" - -#include "igl.h" -#include "iscenegraph.h" -#include "iselection.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "os/path.h" -#include "math/aabb.h" -#include "container/array.h" -#include "generic/static.h" -#include "stream/stringstream.h" -#include "convert.h" -#include "gtkutil/messagebox.h" -#include "gtkutil/image.h" - -#include "gtkmisc.h" -#include "brushmanip.h" -#include "build.h" -#include "qe3.h" -#include "texwindow.h" -#include "xywindow.h" -#include "mainframe.h" -#include "preferences.h" -#include "url.h" -#include "cmdlib.h" - - - -// ============================================================================= -// Project settings dialog - -class GameComboConfiguration -{ -public: - const char* basegame_dir; - const char* basegame; - const char* known_dir; - const char* known; - const char* custom; - - GameComboConfiguration() : - basegame_dir(g_pGameDescription->getRequiredKeyValue("basegame")), - basegame(g_pGameDescription->getRequiredKeyValue("basegamename")), - known_dir(g_pGameDescription->getKeyValue("knowngame")), - known(g_pGameDescription->getKeyValue("knowngamename")), - custom(g_pGameDescription->getRequiredKeyValue("unknowngamename")) - { - } -}; - -typedef LazyStatic LazyStaticGameComboConfiguration; - -inline GameComboConfiguration& globalGameComboConfiguration() -{ - return LazyStaticGameComboConfiguration::instance(); -} - - -struct gamecombo_t -{ - gamecombo_t(int _game, const char* _fs_game, bool _sensitive) - : game(_game), fs_game(_fs_game), sensitive(_sensitive) - {} - int game; - const char* fs_game; - bool sensitive; -}; - -gamecombo_t gamecombo_for_dir(const char* dir) -{ - if(string_equal(dir, globalGameComboConfiguration().basegame_dir)) - { - return gamecombo_t(0, "", false); - } - else if(string_equal(dir, globalGameComboConfiguration().known_dir)) - { - return gamecombo_t(1, dir, false); - } - else - { - return gamecombo_t(string_empty(globalGameComboConfiguration().known_dir) ? 1 : 2, dir, true); - } -} - -gamecombo_t gamecombo_for_gamename(const char* gamename) -{ - if ((strlen(gamename) == 0) || !strcmp(gamename, globalGameComboConfiguration().basegame)) - { - return gamecombo_t(0, "", false); - } - else if (!strcmp(gamename, globalGameComboConfiguration().known)) - { - return gamecombo_t(1, globalGameComboConfiguration().known_dir, false); - } - else - { - return gamecombo_t(string_empty(globalGameComboConfiguration().known_dir) ? 1 : 2, "", true); - } -} - -inline void path_copy_clean(char* destination, const char* source) -{ - char* i = destination; - - while(*source != '\0') - { - *i++ = (*source == '\\') ? '/' : *source; - ++source; - } - - if(i != destination && *(i-1) != '/') - *(i++) = '/'; - - *i = '\0'; -} - - -struct GameCombo -{ - GtkComboBox* game_select; - GtkEntry* fsgame_entry; -}; - -gboolean OnSelchangeComboWhatgame(GtkWidget *widget, GameCombo* combo) -{ - const char *gamename; - { - GtkTreeIter iter; - gtk_combo_box_get_active_iter(combo->game_select, &iter); - gtk_tree_model_get(gtk_combo_box_get_model(combo->game_select), &iter, 0, (gpointer*)&gamename, -1); - } - - gamecombo_t gamecombo = gamecombo_for_gamename(gamename); - - gtk_entry_set_text(combo->fsgame_entry, gamecombo.fs_game); - gtk_widget_set_sensitive(GTK_WIDGET(combo->fsgame_entry), gamecombo.sensitive); - - return FALSE; -} - -class MappingMode -{ -public: - bool do_mapping_mode; - const char* sp_mapping_mode; - const char* mp_mapping_mode; - - MappingMode() : - do_mapping_mode(!string_empty(g_pGameDescription->getKeyValue("show_gamemode"))), - sp_mapping_mode("Single Player mapping mode"), - mp_mapping_mode("Multiplayer mapping mode") - { - } -}; - -typedef LazyStatic LazyStaticMappingMode; - -inline MappingMode& globalMappingMode() -{ - return LazyStaticMappingMode::instance(); -} - -class ProjectSettingsDialog -{ -public: - GameCombo game_combo; - GtkComboBox* gamemode_combo; -}; - -GtkWindow* ProjectSettingsDialog_construct(ProjectSettingsDialog& dialog, ModalDialog& modal) -{ - GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Project Settings", G_CALLBACK(dialog_delete_callback), &modal); - - { - GtkTable* table1 = create_dialog_table(1, 2, 4, 4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(table1)); - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_table_attach(table1, GTK_WIDGET(vbox), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - { - GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &modal); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - { - GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &modal); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - } - { - GtkFrame* frame = create_dialog_frame("Project settings"); - gtk_table_attach(table1, GTK_WIDGET(frame), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (GTK_FILL), 0, 0); - { - GtkTable* table2 = create_dialog_table((globalMappingMode().do_mapping_mode) ? 4 : 3, 2, 4, 4, 4); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(table2)); - - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Select mod")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table2, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); - } - { - dialog.game_combo.game_select = GTK_COMBO_BOX(gtk_combo_box_new_text()); - - gtk_combo_box_append_text(dialog.game_combo.game_select, globalGameComboConfiguration().basegame); - if(globalGameComboConfiguration().known[0] != '\0') - gtk_combo_box_append_text(dialog.game_combo.game_select, globalGameComboConfiguration().known); - gtk_combo_box_append_text(dialog.game_combo.game_select, globalGameComboConfiguration().custom); - - gtk_widget_show(GTK_WIDGET(dialog.game_combo.game_select)); - gtk_table_attach(table2, GTK_WIDGET(dialog.game_combo.game_select), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - g_signal_connect(G_OBJECT(dialog.game_combo.game_select), "changed", G_CALLBACK(OnSelchangeComboWhatgame), &dialog.game_combo); - } - - { - GtkLabel* label = GTK_LABEL(gtk_label_new("fs_game")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table2, GTK_WIDGET(label), 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table2, GTK_WIDGET(entry), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - dialog.game_combo.fsgame_entry = entry; - } - - if(globalMappingMode().do_mapping_mode) - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Mapping mode")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table2, GTK_WIDGET(label), 0, 1, 3, 4, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); - - GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); - gtk_combo_box_append_text(combo, globalMappingMode().sp_mapping_mode); - gtk_combo_box_append_text(combo, globalMappingMode().mp_mapping_mode); - - gtk_widget_show(GTK_WIDGET(combo)); - gtk_table_attach(table2, GTK_WIDGET(combo), 1, 2, 3, 4, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - dialog.gamemode_combo = combo; - } - } - } - } - - // initialise the fs_game selection from the project settings into the dialog - const char* dir = gamename_get(); - gamecombo_t gamecombo = gamecombo_for_dir(dir); - - gtk_combo_box_set_active(dialog.game_combo.game_select, gamecombo.game); - gtk_entry_set_text(dialog.game_combo.fsgame_entry, gamecombo.fs_game); - gtk_widget_set_sensitive(GTK_WIDGET(dialog.game_combo.fsgame_entry), gamecombo.sensitive); - - if(globalMappingMode().do_mapping_mode) - { - const char *gamemode = gamemode_get(); - if (string_empty(gamemode) || string_equal(gamemode, "sp")) - { - gtk_combo_box_set_active(dialog.gamemode_combo, 0); - } - else - { - gtk_combo_box_set_active(dialog.gamemode_combo, 1); - } - } - - return window; -} - -void ProjectSettingsDialog_ok(ProjectSettingsDialog& dialog) -{ - const char* dir = gtk_entry_get_text(dialog.game_combo.fsgame_entry); - - const char* new_gamename = path_equal(dir, globalGameComboConfiguration().basegame_dir) - ? "" - : dir; - - if(!path_equal(new_gamename, gamename_get())) - { - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Changing Game Name"); - - EnginePath_Unrealise(); - - gamename_set(new_gamename); - - EnginePath_Realise(); - } - - if(globalMappingMode().do_mapping_mode) - { - // read from gamemode_combo - int active = gtk_combo_box_get_active(dialog.gamemode_combo); - if(active == -1 || active == 0) - { - gamemode_set("sp"); - } - else - { - gamemode_set("mp"); - } - } -} - -void DoProjectSettings() -{ - if(ConfirmModified("Edit Project Settings")) - { - ModalDialog modal; - ProjectSettingsDialog dialog; - - GtkWindow* window = ProjectSettingsDialog_construct(dialog, modal); - - if(modal_dialog_show(window, modal) == eIDOK) - { - ProjectSettingsDialog_ok(dialog); - } - - gtk_widget_destroy(GTK_WIDGET(window)); - } -} - -// ============================================================================= -// Arbitrary Sides dialog - -void DoSides (int type, int axis) -{ - ModalDialog dialog; - GtkEntry* sides_entry; - - GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Arbitrary sides", G_CALLBACK(dialog_delete_callback), &dialog); - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Sides:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(label), FALSE, FALSE, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(entry), FALSE, FALSE, 0); - sides_entry = entry; - gtk_widget_grab_focus(GTK_WIDGET(entry)); - } - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - } - } - } - - if(modal_dialog_show(window, dialog) == eIDOK) - { - const char *str = gtk_entry_get_text(sides_entry); - - Scene_BrushConstructPrefab(GlobalSceneGraph(), (EBrushPrefab)type, atoi(str), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); - } - - gtk_widget_destroy(GTK_WIDGET(window)); -} - -// ============================================================================= -// About dialog (no program is complete without one) - -void about_button_changelog (GtkWidget *widget, gpointer data) -{ - StringOutputStream log(256); - log << AppPath_get() << "changelog.txt"; - OpenURL(log.c_str()); -} - -void about_button_credits (GtkWidget *widget, gpointer data) -{ - StringOutputStream cred(256); - cred << AppPath_get() << "credits.html"; - OpenURL(cred.c_str()); -} - -void DoAbout() -{ - ModalDialog dialog; - ModalDialogButton ok_button(dialog, eIDOK); - - GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "About NetRadiant", dialog); - - { - GtkVBox* vbox = create_dialog_vbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); - - { - GtkHBox* hbox = create_dialog_hbox(4); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, TRUE, 0); - - { - GtkVBox* vbox2 = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), TRUE, FALSE, 0); - { - GtkFrame* frame = create_dialog_frame(0, GTK_SHADOW_IN); - gtk_box_pack_start(GTK_BOX (vbox2), GTK_WIDGET(frame), FALSE, FALSE, 0); - { - GtkImage* image = new_local_image("logo.bmp"); - gtk_widget_show(GTK_WIDGET(image)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(image)); - } - } - } - - { - GtkLabel* label = GTK_LABEL(gtk_label_new("NetRadiant " RADIANT_VERSION "\n" - __DATE__ "\n\n" - RADIANT_ABOUTMSG "\n\n" - "By alientrap.org\n\n" - "This program is free software\n" - "licensed under the GNU GPL.\n\n" - "NetRadiant is unsupported, however\n" - "you may report your problems at\n" - "http://www.icculus.org/netradiant/" - )); - - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(label), FALSE, FALSE, 0); - gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); - gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); - } - - { - GtkVBox* vbox2 = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), FALSE, TRUE, 0); - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); - } - { - GtkButton* button = create_dialog_button("Credits", G_CALLBACK(about_button_credits), 0); - gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); - } - { - GtkButton* button = create_dialog_button("Changelog", G_CALLBACK(about_button_changelog), 0); - gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); - } - } - } - { - GtkFrame* frame = create_dialog_frame("OpenGL Properties"); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), FALSE, FALSE, 0); - { - GtkTable* table = create_dialog_table(3, 2, 4, 4, 4); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(table)); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Vendor:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Version:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Renderer:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new(reinterpret_cast(glGetString(GL_VENDOR)))); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new(reinterpret_cast(glGetString(GL_VERSION)))); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new(reinterpret_cast(glGetString(GL_RENDERER)))); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - } - { - GtkFrame* frame = create_dialog_frame("OpenGL Extensions"); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); - { - GtkScrolledWindow* sc_extensions = create_scrolled_window(GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS, 4); - gtk_container_add (GTK_CONTAINER (frame), GTK_WIDGET(sc_extensions)); - { - GtkWidget* text_extensions = gtk_text_view_new(); - gtk_text_view_set_editable(GTK_TEXT_VIEW(text_extensions), FALSE); - gtk_container_add (GTK_CONTAINER (sc_extensions), text_extensions); - GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_extensions)); - gtk_text_buffer_set_text(buffer, reinterpret_cast(glGetString(GL_EXTENSIONS)), -1); - gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_extensions), GTK_WRAP_WORD); - gtk_widget_show(text_extensions); - } - } - } - } - } - - modal_dialog_show(window, dialog); - - gtk_widget_destroy(GTK_WIDGET(window)); -} - -// ============================================================================= -// TextureLayout dialog - -EMessageBoxReturn DoTextureLayout (float *fx, float *fy) -{ - ModalDialog dialog; - ModalDialogButton ok_button(dialog, eIDOK); - ModalDialogButton cancel_button(dialog, eIDCANCEL); - GtkEntry* x; - GtkEntry* y; - - GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Patch texture layout", dialog); - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Texture will be fit across the patch based\n" - "on the x and y values given. Values of 1x1\n" - "will \"fit\" the texture. 2x2 will repeat\n" - "it twice, etc.")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), TRUE, TRUE, 0); - gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); - } - { - GtkTable* table = create_dialog_table(2, 2, 4, 4); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), TRUE, TRUE, 0); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Texture x:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Texture y:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - gtk_widget_grab_focus(GTK_WIDGET(entry)); - - x = entry; - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - y = entry; - } - } - } - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - } - } - } - - // Initialize - gtk_entry_set_text(x, "4.0"); - gtk_entry_set_text(y, "4.0"); - - - EMessageBoxReturn ret = modal_dialog_show(window, dialog); - if (ret == eIDOK) - { - *fx = static_cast(atof(gtk_entry_get_text(x))); - *fy = static_cast(atof(gtk_entry_get_text(y))); - } - - gtk_widget_destroy(GTK_WIDGET(window)); - - return ret; -} - -// ============================================================================= -// Text Editor dialog - -// master window widget -static GtkWidget *text_editor = 0; -static GtkWidget *text_widget; // slave, text widget from the gtk editor - -static gint editor_delete (GtkWidget *widget, gpointer data) -{ - if (gtk_MessageBox (widget, "Close the shader editor ?", "Radiant", eMB_YESNO, eMB_ICONQUESTION) == eIDNO) - return TRUE; - - gtk_widget_hide (text_editor); - - return TRUE; -} - -static void editor_save (GtkWidget *widget, gpointer data) -{ - FILE *f = fopen ((char*)g_object_get_data (G_OBJECT (data), "filename"), "w"); - gpointer text = g_object_get_data (G_OBJECT (data), "text"); - - if (f == 0) - { - gtk_MessageBox (GTK_WIDGET(data), "Error saving file !"); - return; - } - - char *str = gtk_editable_get_chars (GTK_EDITABLE (text), 0, -1); - fwrite (str, 1, strlen (str), f); - fclose (f); -} - -static void editor_close (GtkWidget *widget, gpointer data) -{ - if (gtk_MessageBox (text_editor, "Close the shader editor ?", "Radiant", eMB_YESNO, eMB_ICONQUESTION) == eIDNO) - return; - - gtk_widget_hide (text_editor); -} - -static void CreateGtkTextEditor() -{ - GtkWidget *dlg; - GtkWidget *vbox, *hbox, *button, *scr, *text; - - dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - g_signal_connect(G_OBJECT(dlg), "delete_event", - G_CALLBACK(editor_delete), 0); - gtk_window_set_default_size (GTK_WINDOW (dlg), 600, 300); - - vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add(GTK_CONTAINER(dlg), GTK_WIDGET(vbox)); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - scr = gtk_scrolled_window_new (0, 0); - gtk_widget_show (scr); - gtk_box_pack_start(GTK_BOX(vbox), scr, TRUE, TRUE, 0); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); - gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); - - text = gtk_text_view_new(); - gtk_container_add (GTK_CONTAINER (scr), text); - gtk_widget_show (text); - g_object_set_data (G_OBJECT (dlg), "text", text); - gtk_text_view_set_editable (GTK_TEXT_VIEW(text), TRUE); - - hbox = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, TRUE, 0); - - button = gtk_button_new_with_label ("Close"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(editor_close), dlg); - gtk_widget_set_usize (button, 60, -2); - - button = gtk_button_new_with_label ("Save"); - gtk_widget_show (button); - gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(editor_save), dlg); - gtk_widget_set_usize (button, 60, -2); - - text_editor = dlg; - text_widget = text; -} - -static void DoGtkTextEditor (const char* filename, guint cursorpos) -{ - if (!text_editor) - CreateGtkTextEditor(); // build it the first time we need it - - // Load file - FILE *f = fopen (filename, "r"); - - if (f == 0) - { - globalOutputStream() << "Unable to load file " << filename << " in shader editor.\n"; - gtk_widget_hide (text_editor); - } - else - { - fseek (f, 0, SEEK_END); - int len = ftell (f); - void *buf = malloc (len); - void *old_filename; - - rewind (f); - fread (buf, 1, len, f); - - gtk_window_set_title (GTK_WINDOW (text_editor), filename); - - GtkTextBuffer* text_buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_widget)); - gtk_text_buffer_set_text(text_buffer, (char*)buf, len); - - old_filename = g_object_get_data (G_OBJECT (text_editor), "filename"); - if (old_filename) - free(old_filename); - g_object_set_data (G_OBJECT (text_editor), "filename", strdup (filename)); - - // trying to show later - gtk_widget_show (text_editor); - -#ifdef WIN32 - process_gui(); -#endif - - // only move the cursor if it's not exceeding the size.. - // NOTE: this is erroneous, cursorpos is the offset in bytes, not in characters - // len is the max size in bytes, not in characters either, but the character count is below that limit.. - // thinking .. the difference between character count and byte count would be only because of CR/LF? - { - GtkTextIter text_iter; - // character offset, not byte offset - gtk_text_buffer_get_iter_at_offset(text_buffer, &text_iter, cursorpos); - gtk_text_buffer_place_cursor(text_buffer, &text_iter); - } - -#ifdef WIN32 - gtk_widget_queue_draw(text_widget); -#endif - - free (buf); - fclose (f); - } -} - -// ============================================================================= -// Light Intensity dialog - -EMessageBoxReturn DoLightIntensityDlg (int *intensity) -{ - ModalDialog dialog; - GtkEntry* intensity_entry; - ModalDialogButton ok_button(dialog, eIDOK); - ModalDialogButton cancel_button(dialog, eIDCANCEL); - - GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Light intensity", dialog, -1, -1); - - GtkAccelGroup *accel_group = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel_group); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("ESC for default, ENTER to validate")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(entry), TRUE, TRUE, 0); - - gtk_widget_grab_focus(GTK_WIDGET(entry)); - - intensity_entry = entry; - } - } - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); - - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); - } - { - GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Escape, (GdkModifierType)0, GTK_ACCEL_VISIBLE); - } - } - } - - char buf[16]; - sprintf (buf, "%d", *intensity); - gtk_entry_set_text(intensity_entry, buf); - - EMessageBoxReturn ret = modal_dialog_show(window, dialog); - if(ret == eIDOK) - *intensity = atoi (gtk_entry_get_text(intensity_entry)); - - gtk_widget_destroy(GTK_WIDGET(window)); - - return ret; -} - -// ============================================================================= -// Add new shader tag dialog - -EMessageBoxReturn DoShaderTagDlg (CopiedString* tag, char* title) -{ - ModalDialog dialog; - GtkEntry* textentry; - ModalDialogButton ok_button(dialog, eIDOK); - ModalDialogButton cancel_button(dialog, eIDCANCEL); - - GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), title, dialog, -1, -1); - - GtkAccelGroup *accel_group = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel_group); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - //GtkLabel* label = GTK_LABEL(gtk_label_new("Enter one ore more tags separated by spaces")); - GtkLabel* label = GTK_LABEL(gtk_label_new("ESC to cancel, ENTER to validate")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(entry), TRUE, TRUE, 0); - - gtk_widget_grab_focus(GTK_WIDGET(entry)); - - textentry = entry; - } - } - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); - - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); - } - { - GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Escape, (GdkModifierType)0, GTK_ACCEL_VISIBLE); - } - } - } - - EMessageBoxReturn ret = modal_dialog_show(window, dialog); - if(ret == eIDOK) - { - *tag = gtk_entry_get_text(textentry); - } - - gtk_widget_destroy(GTK_WIDGET(window)); - - return ret; -} - -EMessageBoxReturn DoShaderInfoDlg (const char* name, const char* filename, char* title) -{ - ModalDialog dialog; - ModalDialogButton ok_button(dialog, eIDOK); - - GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), title, dialog, -1, -1); - - GtkAccelGroup *accel_group = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel_group); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("The selected shader")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new(name)); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("is located in file")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new(filename)); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); - } - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); - } - } - } - - EMessageBoxReturn ret = modal_dialog_show(window, dialog); - - gtk_widget_destroy(GTK_WIDGET(window)); - - return ret; -} - - - -#ifdef WIN32 -#include -#endif - -#ifdef WIN32 - // use the file associations to open files instead of builtin Gtk editor -bool g_TextEditor_useWin32Editor = true; -#else - // custom shader editor -bool g_TextEditor_useCustomEditor = false; -CopiedString g_TextEditor_editorCommand(""); -#endif - -void DoTextEditor (const char* filename, int cursorpos) -{ -#ifdef WIN32 - if (g_TextEditor_useWin32Editor) - { - globalOutputStream() << "opening file '" << filename << "' (line " << cursorpos << " info ignored)\n"; - ShellExecute((HWND)GDK_WINDOW_HWND (GTK_WIDGET(MainFrame_getWindow())->window), "open", filename, 0, 0, SW_SHOW ); - return; - } -#else - // check if a custom editor is set - if(g_TextEditor_useCustomEditor && !g_TextEditor_editorCommand.empty()) - { - StringOutputStream strEditCommand(256); - strEditCommand << g_TextEditor_editorCommand.c_str() << " \"" << filename << "\""; - - globalOutputStream() << "Launching: " << strEditCommand.c_str() << "\n"; - // note: linux does not return false if the command failed so it will assume success - if (Q_Exec(0, const_cast(strEditCommand.c_str()), 0, true, false) == false) - { - globalOutputStream() << "Failed to execute " << strEditCommand.c_str() << ", using default\n"; - } - else - { - // the command (appeared) to run successfully, no need to do anything more - return; - } - } -#endif - - DoGtkTextEditor (filename, cursorpos); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/gtkdlgs.h b/misc/mediasource/extra/netradiant-src/radiant/gtkdlgs.h deleted file mode 100644 index 36989916..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/gtkdlgs.h +++ /dev/null @@ -1,59 +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. -*/ - -#if !defined(INCLUDED_GTKDLGS_H) -#define INCLUDED_GTKDLGS_H - -#include "qerplugin.h" -#include "string/string.h" - -EMessageBoxReturn DoLightIntensityDlg (int *intensity); -EMessageBoxReturn DoShaderTagDlg (CopiedString *tag, char* title); -EMessageBoxReturn DoShaderInfoDlg (const char* name, const char* filename, char* title); -EMessageBoxReturn DoTextureLayout (float *fx, float *fy); -void DoTextEditor (const char* filename, int cursorpos); - -void DoProjectSettings(); - -void DoFind(); -void DoSides(int type, int axis); -void DoAbout(); - - -#ifdef WIN32 -extern bool g_TextEditor_useWin32Editor; -#else -#include "string/stringfwd.h" -extern bool g_TextEditor_useCustomEditor; -extern CopiedString g_TextEditor_editorCommand; -#endif - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/gtkmisc.cpp b/misc/mediasource/extra/netradiant-src/radiant/gtkmisc.cpp deleted file mode 100644 index fc28c5d7..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/gtkmisc.cpp +++ /dev/null @@ -1,170 +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. -*/ - -// -// Small functions to help with GTK -// - -#include "gtkmisc.h" - -#include -#include - -#include "math/vector.h" -#include "os/path.h" - -#include "gtkutil/dialog.h" -#include "gtkutil/filechooser.h" -#include "gtkutil/menu.h" -#include "gtkutil/toolbar.h" -#include "commands.h" - - -// ============================================================================= -// Misc stuff - -void command_connect_accelerator(const char* name) -{ - const Command& command = GlobalCommands_find(name); - GlobalShortcuts_register(name, 1); - global_accel_group_connect(command.m_accelerator, command.m_callback); -} - -void command_disconnect_accelerator(const char* name) -{ - const Command& command = GlobalCommands_find(name); - global_accel_group_disconnect(command.m_accelerator, command.m_callback); -} - -void toggle_add_accelerator(const char* name) -{ - const Toggle& toggle = GlobalToggles_find(name); - GlobalShortcuts_register(name, 2); - global_accel_group_connect(toggle.m_command.m_accelerator, toggle.m_command.m_callback); -} - -void toggle_remove_accelerator(const char* name) -{ - const Toggle& toggle = GlobalToggles_find(name); - global_accel_group_disconnect(toggle.m_command.m_accelerator, toggle.m_command.m_callback); -} - -GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const char* commandName) -{ - GlobalShortcuts_register(commandName, 2); - const Toggle& toggle = GlobalToggles_find(commandName); - global_accel_group_connect(toggle.m_command.m_accelerator, toggle.m_command.m_callback); - return create_check_menu_item_with_mnemonic(menu, mnemonic, toggle); -} - -GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu* menu, const char *mnemonic, const char* commandName) -{ - GlobalShortcuts_register(commandName, 1); - const Command& command = GlobalCommands_find(commandName); - global_accel_group_connect(command.m_accelerator, command.m_callback); - return create_menu_item_with_mnemonic(menu, mnemonic, command); -} - -GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName) -{ - return toolbar_append_button(toolbar, description, icon, GlobalCommands_find(commandName)); -} - -GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName) -{ - return toolbar_append_toggle_button(toolbar, description, icon, GlobalToggles_find(commandName)); -} - -// ============================================================================= -// File dialog - -bool color_dialog (GtkWidget *parent, Vector3& color, const char* title) -{ - GtkWidget* dlg; - double clr[3]; - ModalDialog dialog; - - clr[0] = color[0]; - clr[1] = color[1]; - clr[2] = color[2]; - - dlg = gtk_color_selection_dialog_new (title); - gtk_color_selection_set_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), clr); - g_signal_connect(G_OBJECT(dlg), "delete_event", G_CALLBACK(dialog_delete_callback), &dialog); - g_signal_connect(G_OBJECT(GTK_COLOR_SELECTION_DIALOG(dlg)->ok_button), "clicked", G_CALLBACK(dialog_button_ok), &dialog); - g_signal_connect(G_OBJECT(GTK_COLOR_SELECTION_DIALOG(dlg)->cancel_button), "clicked", G_CALLBACK(dialog_button_cancel), &dialog); - - if (parent != 0) - gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (parent)); - - bool ok = modal_dialog_show(GTK_WINDOW(dlg), dialog) == eIDOK; - if(ok) - { - GdkColor gdkcolor; - gtk_color_selection_get_current_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), &gdkcolor); - clr[0] = gdkcolor.red / 65535.0; - clr[1] = gdkcolor.green / 65535.0; - clr[2] = gdkcolor.blue / 65535.0; - - color[0] = (float)clr[0]; - color[1] = (float)clr[1]; - color[2] = (float)clr[2]; - } - - gtk_widget_destroy(dlg); - - return ok; -} - -void button_clicked_entry_browse_file(GtkWidget* widget, GtkEntry* entry) -{ - const char *filename = file_dialog(gtk_widget_get_toplevel(widget), TRUE, "Choose File", gtk_entry_get_text(entry)); - - if(filename != 0) - { - gtk_entry_set_text(entry, filename); - } -} - -void button_clicked_entry_browse_directory(GtkWidget* widget, GtkEntry* entry) -{ - const char* text = gtk_entry_get_text(entry); - char *dir = dir_dialog(gtk_widget_get_toplevel(widget), "Choose Directory", path_is_absolute(text) ? text : "" ); - - if(dir != 0) - { - gchar* converted = g_filename_to_utf8(dir, -1, 0, 0, 0); - gtk_entry_set_text(entry, converted); - g_free(dir); - g_free(converted); - } -} - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/gtkmisc.h b/misc/mediasource/extra/netradiant-src/radiant/gtkmisc.h deleted file mode 100644 index c1ddf0b1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/gtkmisc.h +++ /dev/null @@ -1,76 +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. -*/ - -#if !defined(INCLUDED_GTKMISC_H) -#define INCLUDED_GTKMISC_H - -#include - -inline void process_gui() -{ - while(gtk_events_pending()) - { - gtk_main_iteration(); - } -} - -void command_connect_accelerator(const char* commandName); -void command_disconnect_accelerator(const char* commandName); -void toggle_add_accelerator(const char* commandName); -void toggle_remove_accelerator(const char* name); - -typedef struct _GtkMenu GtkMenu; -typedef struct _GtkMenuItem GtkMenuItem; -typedef struct _GtkCheckMenuItem GtkCheckMenuItem; - -// this also sets up the shortcut using command_connect_accelerator -GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu *menu, const char *mnemonic, const char* commandName); -// this also sets up the shortcut using command_connect_accelerator -GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const char* commandName); - -typedef struct _GtkButton GtkButton; -typedef struct _GtkToggleButton GtkToggleButton; -typedef struct _GtkToolbar GtkToolbar; - -// this DOES NOT set up the shortcut using command_connect_accelerator -GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName); -// this DOES NOT set up the shortcut using command_connect_accelerator -GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName); - - -template class BasicVector3; -typedef BasicVector3 Vector3; -bool color_dialog (GtkWidget *parent, Vector3& color, const char* title = "Choose Color"); - -typedef struct _GtkEntry GtkEntry; -void button_clicked_entry_browse_file(GtkWidget* widget, GtkEntry* entry); -void button_clicked_entry_browse_directory(GtkWidget* widget, GtkEntry* entry); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/help.cpp b/misc/mediasource/extra/netradiant-src/radiant/help.cpp deleted file mode 100644 index 363b1f0a..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/help.cpp +++ /dev/null @@ -1,140 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "help.h" - -#include "debugging/debugging.h" - -#include -#include - -#include "libxml/parser.h" -#include "generic/callback.h" -#include "gtkutil/menu.h" -#include "stream/stringstream.h" -#include "os/file.h" - -#include "url.h" -#include "preferences.h" -#include "mainframe.h" - -/*! -the urls to fire up in the game packs help menus -*/ -namespace -{ - std::list mHelpURLs; -} - -/*! -needed for hooking in Gtk+ -*/ -void HandleHelpCommand(CopiedString& str) -{ - OpenURL(str.c_str()); -} - -void process_xlink(const char* filename, const char *menu_name, const char *base_url, GtkMenu *menu) -{ - if(file_exists(filename)) - { - xmlDocPtr pDoc = xmlParseFile(filename); - if (pDoc) - { - globalOutputStream() << "Processing .xlink file '" << filename << "'\n"; - // create sub menu - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic(menu, menu_name); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - // start walking the nodes, find the 'links' one - xmlNodePtr pNode = pDoc->children; - while (pNode && strcmp((const char*)pNode->name, "links")) - pNode=pNode->next; - if (pNode) - { - pNode = pNode->children; - while(pNode) - { - if(!strcmp((const char*)pNode->name, "item")) - { - // process the URL - CopiedString url; - - xmlChar* prop = xmlGetProp(pNode, reinterpret_cast("url")); - ASSERT_NOTNULL(prop); - if(strstr(reinterpret_cast(prop), "http://")) - { - // complete URL - url = reinterpret_cast(prop); - } - else - { - // relative URL - StringOutputStream full(256); - full << base_url << reinterpret_cast(prop); - url = full.c_str(); - } - - mHelpURLs.push_back(url); - - xmlFree(prop); - - prop = xmlGetProp(pNode, reinterpret_cast("name")); - ASSERT_NOTNULL(prop); - create_menu_item_with_mnemonic(menu_in_menu, reinterpret_cast(prop), ReferenceCaller(mHelpURLs.back())); - xmlFree(prop); - } - pNode=pNode->next; - } - } - xmlFreeDoc(pDoc); - } - else - { - globalOutputStream() << "'" << filename << "' parse failed\n"; - } - } - else - { - globalOutputStream() << "'" << filename << "' not found\n"; - } -} - -void create_game_help_menu(GtkMenu *menu) -{ - StringOutputStream filename(256); - filename << AppPath_get() << "global.xlink"; - process_xlink(filename.c_str(), "General", AppPath_get(), menu); - -#if 1 - filename.clear(); - filename << g_pGameDescription->mGameToolsPath.c_str() << "game.xlink"; - process_xlink(filename.c_str(), g_pGameDescription->getRequiredKeyValue("name"), g_pGameDescription->mGameToolsPath.c_str(), menu); -#else - for(std::list::iterator iGame = g_GamesDialog.mGames.begin(); iGame != g_GamesDialog.mGames.end(); ++iGame) - { - filename.clear(); - filename << (*iGame)->mGameToolsPath.c_str() << "game.xlink"; - process_xlink(filename.c_str(), (*iGame)->getRequiredKeyValue("name"), (*iGame)->mGameToolsPath.c_str(), menu); - } -#endif -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/help.h b/misc/mediasource/extra/netradiant-src/radiant/help.h deleted file mode 100644 index 02c6b14c..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/help.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_HELP_H) -#define INCLUDED_HELP_H - -typedef struct _GtkMenu GtkMenu; -void create_game_help_menu(GtkMenu *menu); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/image.cpp b/misc/mediasource/extra/netradiant-src/radiant/image.cpp deleted file mode 100644 index 7495db68..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/image.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "image.h" - -#include "modulesystem.h" -#include "iimage.h" -#include "ifilesystem.h" -#include "iarchive.h" - -#include "generic/reference.h" -#include "os/path.h" -#include "stream/stringstream.h" - - -typedef Modules<_QERPlugImageTable> ImageModules; -ImageModules& Textures_getImageModules(); - -/// \brief Returns a new image for the first file matching \p name in one of the available texture formats, or 0 if no file is found. -Image* QERApp_LoadImage(void* environment, const char* name) -{ - Image* image = 0; - class LoadImageVisitor : public ImageModules::Visitor - { - const char* m_name; - Image*& m_image; - public: - LoadImageVisitor(const char* name, Image*& image) - : m_name(name), m_image(image) - { - } - void visit(const char* name, const _QERPlugImageTable& table) const - { - if(m_image == 0) - { - StringOutputStream fullname(256); - fullname << m_name << '.' << name; - ArchiveFile* file = GlobalFileSystem().openFile(fullname.c_str()); - if(file != 0) - { - m_image = table.loadImage(*file); - file->release(); - } - } - } - }; - - Textures_getImageModules().foreachModule(LoadImageVisitor(name, image)); - - return image; -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/image.h b/misc/mediasource/extra/netradiant-src/radiant/image.h deleted file mode 100644 index 3607c071..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/image.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (INCLUDED_IMAGE_H) -#define INCLUDED_IMAGE_H - -class Image; -Image* QERApp_LoadImage(void* environment, const char* name); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/main.cpp b/misc/mediasource/extra/netradiant-src/radiant/main.cpp deleted file mode 100644 index a7c22426..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/main.cpp +++ /dev/null @@ -1,686 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/*! \mainpage GtkRadiant Documentation Index - -\section intro_sec Introduction - -This documentation is generated from comments in the source code. - -\section links_sec Useful Links - -\link include/itextstream.h include/itextstream.h \endlink - Global output and error message streams, similar to std::cout and std::cerr. \n - -FileInputStream - similar to std::ifstream (binary mode) \n -FileOutputStream - similar to std::ofstream (binary mode) \n -TextFileInputStream - similar to std::ifstream (text mode) \n -TextFileOutputStream - similar to std::ofstream (text mode) \n -StringOutputStream - similar to std::stringstream \n - -\link string/string.h string/string.h \endlink - C-style string comparison and memory management. \n -\link os/path.h os/path.h \endlink - Path manipulation for radiant's standard path format \n -\link os/file.h os/file.h \endlink - OS file-system access. \n - -::CopiedString - automatic string memory management \n -Array - automatic array memory management \n -HashTable - generic hashtable, similar to std::hash_map \n - -\link math/vector.h math/vector.h \endlink - Vectors \n -\link math/matrix.h math/matrix.h \endlink - Matrices \n -\link math/quaternion.h math/quaternion.h \endlink - Quaternions \n -\link math/plane.h math/plane.h \endlink - Planes \n -\link math/aabb.h math/aabb.h \endlink - AABBs \n - -Callback MemberCaller FunctionCaller - callbacks similar to using boost::function with boost::bind \n -SmartPointer SmartReference - smart-pointer and smart-reference similar to Loki's SmartPtr \n - -\link generic/bitfield.h generic/bitfield.h \endlink - Type-safe bitfield \n -\link generic/enumeration.h generic/enumeration.h \endlink - Type-safe enumeration \n - -DefaultAllocator - Memory allocation using new/delete, compliant with std::allocator interface \n - -\link debugging/debugging.h debugging/debugging.h \endlink - Debugging macros \n - -*/ - -#include "main.h" - -#include "version.h" - -#include "debugging/debugging.h" - -#include "iundo.h" - -#include - -#include "cmdlib.h" -#include "os/file.h" -#include "os/path.h" -#include "stream/stringstream.h" -#include "stream/textfilestream.h" - -#include "gtkutil/messagebox.h" -#include "gtkutil/image.h" -#include "console.h" -#include "texwindow.h" -#include "map.h" -#include "mainframe.h" -#include "commands.h" -#include "preferences.h" -#include "environment.h" -#include "referencecache.h" -#include "stacktrace.h" - -#ifdef WIN32 -#include -#endif - -void show_splash(); -void hide_splash(); - -void error_redirect (const gchar *domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) -{ - gboolean in_recursion; - gboolean is_fatal; - char buf[256]; - - in_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0; - is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0; - log_level = (GLogLevelFlags) (log_level & G_LOG_LEVEL_MASK); - - if (!message) - message = "(0) message"; - - if (domain) - strcpy (buf, domain); - else - strcpy (buf, "**"); - strcat (buf, "-"); - - switch (log_level) - { - case G_LOG_LEVEL_ERROR: - if (in_recursion) - strcat (buf, "ERROR (recursed) **: "); - else - strcat (buf, "ERROR **: "); - break; - case G_LOG_LEVEL_CRITICAL: - if (in_recursion) - strcat (buf, "CRITICAL (recursed) **: "); - else - strcat (buf, "CRITICAL **: "); - break; - case G_LOG_LEVEL_WARNING: - if (in_recursion) - strcat (buf, "WARNING (recursed) **: "); - else - strcat (buf, "WARNING **: "); - break; - case G_LOG_LEVEL_MESSAGE: - if (in_recursion) - strcat (buf, "Message (recursed): "); - else - strcat (buf, "Message: "); - break; - case G_LOG_LEVEL_INFO: - if (in_recursion) - strcat (buf, "INFO (recursed): "); - else - strcat (buf, "INFO: "); - break; - case G_LOG_LEVEL_DEBUG: - if (in_recursion) - strcat (buf, "DEBUG (recursed): "); - else - strcat (buf, "DEBUG: "); - break; - default: - /* we are used for a log level that is not defined by GLib itself, - * try to make the best out of it. - */ - if (in_recursion) - strcat (buf, "LOG (recursed:"); - else - strcat (buf, "LOG ("); - if (log_level) - { - gchar string[] = "0x00): "; - gchar *p = string + 2; - guint i; - - i = g_bit_nth_msf (log_level, -1); - *p = i >> 4; - p++; - *p = '0' + (i & 0xf); - if (*p > '9') - *p += 'A' - '9' - 1; - - strcat (buf, string); - } else - strcat (buf, "): "); - } - - strcat (buf, message); - if (is_fatal) - strcat (buf, "\naborting...\n"); - else - strcat (buf, "\n"); - - // spam it... - globalErrorStream() << buf << "\n"; - - // FIXME why are warnings is_fatal? -#ifndef _DEBUG - if(is_fatal) -#endif - ERROR_MESSAGE("GTK+ error: " << buf); -} - -#if defined (_DEBUG) && defined (WIN32) && defined (_MSC_VER) -#include "crtdbg.h" -#endif - -void crt_init() -{ -#if defined (_DEBUG) && defined (WIN32) && defined (_MSC_VER) - _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); -#endif -} - -class Lock -{ - bool m_locked; -public: - Lock() : m_locked(false) - { - } - void lock() - { - m_locked = true; - } - void unlock() - { - m_locked = false; - } - bool locked() const - { - return m_locked; - } -}; - -class ScopedLock -{ - Lock& m_lock; -public: - ScopedLock(Lock& lock) : m_lock(lock) - { - m_lock.lock(); - } - ~ScopedLock() - { - m_lock.unlock(); - } -}; - -class LineLimitedTextOutputStream : public TextOutputStream -{ - TextOutputStream& outputStream; - std::size_t count; -public: - LineLimitedTextOutputStream(TextOutputStream& outputStream, std::size_t count) - : outputStream(outputStream), count(count) - { - } - std::size_t write(const char* buffer, std::size_t length) - { - if(count != 0) - { - const char* p = buffer; - const char* end = buffer+length; - for(;;) - { - p = std::find(p, end, '\n'); - if(p == end) - { - break; - } - ++p; - if(--count == 0) - { - length = p - buffer; - break; - } - } - outputStream.write(buffer, length); - } - return length; - } -}; - -class PopupDebugMessageHandler : public DebugMessageHandler -{ - StringOutputStream m_buffer; - Lock m_lock; -public: - TextOutputStream& getOutputStream() - { - if(!m_lock.locked()) - { - return m_buffer; - } - return globalErrorStream(); - } - bool handleMessage() - { - getOutputStream() << "----------------\n"; - LineLimitedTextOutputStream outputStream(getOutputStream(), 24); - write_stack_trace(outputStream); - getOutputStream() << "----------------\n"; - globalErrorStream() << m_buffer.c_str(); - if(!m_lock.locked()) - { - ScopedLock lock(m_lock); -#if defined _DEBUG - m_buffer << "Break into the debugger?\n"; - bool handled = gtk_MessageBox(0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_YESNO, eMB_ICONERROR) == eIDNO; - m_buffer.clear(); - return handled; -#else - m_buffer << "Please report this error to the developers\n"; - gtk_MessageBox(0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_OK, eMB_ICONERROR); - m_buffer.clear(); -#endif - } - return true; - } -}; - -typedef Static GlobalPopupDebugMessageHandler; - -void streams_init() -{ - GlobalErrorStream::instance().setOutputStream(getSysPrintErrorStream()); - GlobalOutputStream::instance().setOutputStream(getSysPrintOutputStream()); -} - -void paths_init() -{ - const char* home = environment_get_home_path(); - Q_mkdir(home); - - { - StringOutputStream path(256); - path << home << "1." << RADIANT_MAJOR_VERSION "." << RADIANT_MINOR_VERSION << '/'; - g_strSettingsPath = path.c_str(); - } - - Q_mkdir(g_strSettingsPath.c_str()); - - g_strAppPath = environment_get_app_path(); - - // radiant is installed in the parent dir of "tools/" - // NOTE: this is not very easy for debugging - // maybe add options to lookup in several places? - // (for now I had to create symlinks) - { - StringOutputStream path(256); - path << g_strAppPath.c_str() << "bitmaps/"; - BitmapsPath_set(path.c_str()); - } - - // we will set this right after the game selection is done - g_strGameToolsPath = g_strAppPath; -} - -bool check_version_file(const char* filename, const char* version) -{ - TextFileInputStream file(filename); - if(!file.failed()) - { - char buf[10]; - buf[file.read(buf, 9)] = '\0'; - - // chomp it (the hard way) - int chomp = 0; - while(buf[chomp] >= '0' && buf[chomp] <= '9') - chomp++; - buf[chomp] = '\0'; - - return string_equal(buf, version); - } - return false; -} - -bool check_version() -{ - // a safe check to avoid people running broken installations - // (otherwise, they run it, crash it, and blame us for not forcing them hard enough to pay attention while installing) - // make something idiot proof and someone will make better idiots, this may be overkill - // let's leave it disabled in debug mode in any case - // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=431 -#ifndef _DEBUG -#define CHECK_VERSION -#endif -#ifdef CHECK_VERSION - // locate and open RADIANT_MAJOR and RADIANT_MINOR - bool bVerIsGood = true; - { - StringOutputStream ver_file_name(256); - ver_file_name << AppPath_get() << "RADIANT_MAJOR"; - bVerIsGood = check_version_file(ver_file_name.c_str(), RADIANT_MAJOR_VERSION); - } - { - StringOutputStream ver_file_name(256); - ver_file_name << AppPath_get() << "RADIANT_MINOR"; - bVerIsGood = check_version_file(ver_file_name.c_str(), RADIANT_MINOR_VERSION); - } - - if (!bVerIsGood) - { - StringOutputStream msg(256); - msg << "This editor binary (" RADIANT_VERSION ") doesn't match what the latest setup has configured in this directory\n" - "Make sure you run the right/latest editor binary you installed\n" - << AppPath_get(); - gtk_MessageBox(0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONDEFAULT); - } - return bVerIsGood; -#else - return true; -#endif -} - -void create_global_pid() -{ - /*! - the global prefs loading / game selection dialog might fail for any reason we don't know about - we need to catch when it happens, to cleanup the stateful prefs which might be killing it - and to turn on console logging for lookup of the problem - this is the first part of the two step .pid system - http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297 - */ - StringOutputStream g_pidFile(256); ///< the global .pid file (only for global part of the startup) - - g_pidFile << SettingsPath_get() << "radiant.pid"; - - FILE *pid; - pid = fopen (g_pidFile.c_str(), "r"); - if (pid != 0) - { - fclose (pid); - - if (remove (g_pidFile.c_str()) == -1) - { - StringOutputStream msg(256); - msg << "WARNING: Could not delete " << g_pidFile.c_str(); - gtk_MessageBox (0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR ); - } - - // in debug, never prompt to clean registry, turn console logging auto after a failed start -#if !defined(_DEBUG) - StringOutputStream msg(256); - msg << "Radiant failed to start properly the last time it was run.\n" - "The failure may be related to current global preferences.\n" - "Do you want to reset global preferences to defaults?"; - - if (gtk_MessageBox (0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION) == eIDYES) - { - g_GamesDialog.Reset(); - } - - msg.clear(); - msg << "Logging console output to " << SettingsPath_get() << "radiant.log\nRefer to the log if Radiant fails to start again."; - - gtk_MessageBox (0, msg.c_str(), "Radiant - Console Log", eMB_OK); -#endif - - // set without saving, the class is not in a coherent state yet - // just do the value change and call to start logging, CGamesDialog will pickup when relevant - g_GamesDialog.m_bForceLogConsole = true; - Sys_LogFile(true); - } - - // create a primary .pid for global init run - pid = fopen (g_pidFile.c_str(), "w"); - if (pid) - fclose (pid); -} - -void remove_global_pid() -{ - StringOutputStream g_pidFile(256); - g_pidFile << SettingsPath_get() << "radiant.pid"; - - // close the primary - if (remove (g_pidFile.c_str()) == -1) - { - StringOutputStream msg(256); - msg << "WARNING: Could not delete " << g_pidFile.c_str(); - gtk_MessageBox (0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR ); - } -} - -/*! -now the secondary game dependant .pid file -http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297 -*/ -void create_local_pid() -{ - StringOutputStream g_pidGameFile(256); ///< the game-specific .pid file - g_pidGameFile << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/radiant-game.pid"; - - FILE *pid = fopen (g_pidGameFile.c_str(), "r"); - if (pid != 0) - { - fclose (pid); - if (remove (g_pidGameFile.c_str()) == -1) - { - StringOutputStream msg; - msg << "WARNING: Could not delete " << g_pidGameFile.c_str(); - gtk_MessageBox (0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR ); - } - - // in debug, never prompt to clean registry, turn console logging auto after a failed start -#if !defined(_DEBUG) - StringOutputStream msg; - msg << "Radiant failed to start properly the last time it was run.\n" - "The failure may be caused by current preferences.\n" - "Do you want to reset all preferences to defaults?"; - - if (gtk_MessageBox (0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION) == eIDYES) - { - Preferences_Reset(); - } - - msg.clear(); - msg << "Logging console output to " << SettingsPath_get() << "radiant.log\nRefer to the log if Radiant fails to start again."; - - gtk_MessageBox (0, msg.c_str(), "Radiant - Console Log", eMB_OK); -#endif - - // force console logging on! (will go in prefs too) - g_GamesDialog.m_bForceLogConsole = true; - Sys_LogFile(true); - } - else - { - // create one, will remove right after entering message loop - pid = fopen (g_pidGameFile.c_str(), "w"); - if (pid) - fclose (pid); - } -} - - -/*! -now the secondary game dependant .pid file -http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297 -*/ -void remove_local_pid() -{ - StringOutputStream g_pidGameFile(256); - g_pidGameFile << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/radiant-game.pid"; - remove(g_pidGameFile.c_str()); -} - -void user_shortcuts_init() -{ - StringOutputStream path(256); - path << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << '/'; - LoadCommandMap(path.c_str()); - SaveCommandMap(path.c_str()); -} - -void user_shortcuts_save() -{ - StringOutputStream path(256); - path << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << '/'; - SaveCommandMap(path.c_str()); -} - -int main (int argc, char* argv[]) -{ - crt_init(); - - streams_init(); - -#ifdef WIN32 - HMODULE lib; - lib = LoadLibrary("dwmapi.dll"); - if(lib != 0) - { - void (WINAPI *qDwmEnableComposition) (bool bEnable) = (void (WINAPI *) (bool bEnable)) GetProcAddress(lib, "DwmEnableComposition"); - if(qDwmEnableComposition) - qDwmEnableComposition(FALSE); - FreeLibrary(lib); - } -#endif - - gtk_disable_setlocale(); - gtk_init(&argc, &argv); - - // redirect Gtk warnings to the console - g_log_set_handler ("Gdk", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| - G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); - g_log_set_handler ("Gtk", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| - G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); - g_log_set_handler ("GtkGLExt", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| - G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); - g_log_set_handler ("GLib", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| - G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); - g_log_set_handler (0, (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| - G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); - - GlobalDebugMessageHandler::instance().setHandler(GlobalPopupDebugMessageHandler::instance()); - - environment_init(argc, argv); - - paths_init(); - - if(!check_version()) - { - return EXIT_FAILURE; - } - - show_splash(); - - create_global_pid(); - - GlobalPreferences_Init(); - - g_GamesDialog.Init(); - - g_strGameToolsPath = g_pGameDescription->mGameToolsPath; - - remove_global_pid(); - - g_Preferences.Init(); // must occur before create_local_pid() to allow preferences to be reset - - create_local_pid(); - - // in a very particular post-.pid startup - // we may have the console turned on and want to keep it that way - // so we use a latching system - if (g_GamesDialog.m_bForceLogConsole) - { - Sys_LogFile(true); - g_Console_enableLogging = true; - g_GamesDialog.m_bForceLogConsole = false; - } - - - Radiant_Initialise(); - - global_accel_init(); - - user_shortcuts_init(); - - g_pParentWnd = 0; - g_pParentWnd = new MainFrame(); - - hide_splash(); - - if (g_bLoadLastMap && !g_strLastMap.empty()) - { - Map_LoadFile(g_strLastMap.c_str()); - } - else - { - Map_New(); - } - - // load up shaders now that we have the map loaded - // eviltypeguy - TextureBrowser_ShowStartupShaders(GlobalTextureBrowser()); - - - remove_local_pid(); - - gtk_main(); - - // avoid saving prefs when the app is minimized - if (g_pParentWnd->IsSleeping()) - { - globalOutputStream() << "Shutdown while sleeping, not saving prefs\n"; - g_preferences_globals.disable_ini = true; - } - - Map_Free(); - - if (!Map_Unnamed(g_map)) - { - g_strLastMap = Map_Name(g_map); - } - - delete g_pParentWnd; - - user_shortcuts_save(); - - global_accel_destroy(); - - Radiant_Shutdown(); - - // close the log file if any - Sys_LogFile(false); - - return EXIT_SUCCESS; -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/main.h b/misc/mediasource/extra/netradiant-src/radiant/main.h deleted file mode 100644 index bda8f3da..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/main.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_MAIN_H) -#define INCLUDED_MAIN_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/mainframe.cpp b/misc/mediasource/extra/netradiant-src/radiant/mainframe.cpp deleted file mode 100644 index c8a739b6..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/mainframe.cpp +++ /dev/null @@ -1,3601 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Main Window for Q3Radiant -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "mainframe.h" - -#include "debugging/debugging.h" -#include "version.h" - -#include "ifilesystem.h" -#include "iundo.h" -#include "ifilter.h" -#include "itoolbar.h" -#include "editable.h" -#include "ientity.h" -#include "ishaders.h" -#include "igl.h" -#include "moduleobserver.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -#include "cmdlib.h" -#include "scenelib.h" -#include "stream/stringstream.h" -#include "signal/isignal.h" -#include "os/path.h" -#include "os/file.h" -#include "eclasslib.h" -#include "moduleobservers.h" - -#include "gtkutil/clipboard.h" -#include "gtkutil/container.h" -#include "gtkutil/frame.h" -#include "gtkutil/glfont.h" -#include "gtkutil/glwidget.h" -#include "gtkutil/image.h" -#include "gtkutil/menu.h" -#include "gtkutil/paned.h" -#include "gtkutil/widget.h" - -#include "autosave.h" -#include "build.h" -#include "brushmanip.h" -#include "brushmodule.h" -#include "camwindow.h" -#include "csg.h" -#include "commands.h" -#include "console.h" -#include "entity.h" -#include "entityinspector.h" -#include "entitylist.h" -#include "filters.h" -#include "findtexturedialog.h" -#include "grid.h" -#include "groupdialog.h" -#include "gtkdlgs.h" -#include "gtkmisc.h" -#include "help.h" -#include "map.h" -#include "mru.h" -#include "multimon.h" -#include "patchdialog.h" -#include "patchmanip.h" -#include "plugin.h" -#include "pluginmanager.h" -#include "pluginmenu.h" -#include "plugintoolbar.h" -#include "points.h" -#include "preferences.h" -#include "qe3.h" -#include "qgl.h" -#include "select.h" -#include "server.h" -#include "surfacedialog.h" -#include "textures.h" -#include "texwindow.h" -#include "url.h" -#include "xywindow.h" -#include "windowobservers.h" -#include "renderstate.h" -#include "feedback.h" -#include "referencecache.h" - - - -struct layout_globals_t -{ - WindowPosition m_position; - - - int nXYHeight; - int nXYWidth; - int nCamWidth; - int nCamHeight; - int nState; - - layout_globals_t() : - m_position(-1, -1, 640, 480), - - nXYHeight(300), - nXYWidth(300), - nCamWidth(200), - nCamHeight(200), - nState(GDK_WINDOW_STATE_MAXIMIZED) - { - } -}; - -layout_globals_t g_layout_globals; -glwindow_globals_t g_glwindow_globals; - - -// VFS -class VFSModuleObserver : public ModuleObserver -{ - std::size_t m_unrealised; -public: - VFSModuleObserver() : m_unrealised(1) - { - } - void realise() - { - if(--m_unrealised == 0) - { - QE_InitVFS(); - GlobalFileSystem().initialise(); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - GlobalFileSystem().shutdown(); - } - } -}; - -VFSModuleObserver g_VFSModuleObserver; - -void VFS_Construct() -{ - Radiant_attachHomePathsObserver(g_VFSModuleObserver); -} -void VFS_Destroy() -{ - Radiant_detachHomePathsObserver(g_VFSModuleObserver); -} - -// Home Paths - -void HomePaths_Realise() -{ -#if defined(POSIX) - const char* prefix = g_pGameDescription->getKeyValue("prefix"); - if(!string_empty(prefix)) - { - StringOutputStream path(256); - path << DirectoryCleaned(g_get_home_dir()) << prefix << "/"; - g_qeglobals.m_userEnginePath = path.c_str(); - Q_mkdir(g_qeglobals.m_userEnginePath.c_str()); - } - else -#endif - { - g_qeglobals.m_userEnginePath = EnginePath_get(); - } - - { - StringOutputStream path(256); - path << g_qeglobals.m_userEnginePath.c_str() << gamename_get() << '/'; - g_qeglobals.m_userGamePath = path.c_str(); - } - ASSERT_MESSAGE(!string_empty(g_qeglobals.m_userGamePath.c_str()), "HomePaths_Realise: user-game-path is empty"); - Q_mkdir(g_qeglobals.m_userGamePath.c_str()); -} - -ModuleObservers g_homePathObservers; - -void Radiant_attachHomePathsObserver(ModuleObserver& observer) -{ - g_homePathObservers.attach(observer); -} - -void Radiant_detachHomePathsObserver(ModuleObserver& observer) -{ - g_homePathObservers.detach(observer); -} - -class HomePathsModuleObserver : public ModuleObserver -{ - std::size_t m_unrealised; -public: - HomePathsModuleObserver() : m_unrealised(1) - { - } - void realise() - { - if(--m_unrealised == 0) - { - HomePaths_Realise(); - g_homePathObservers.realise(); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - g_homePathObservers.unrealise(); - } - } -}; - -HomePathsModuleObserver g_HomePathsModuleObserver; - -void HomePaths_Construct() -{ - Radiant_attachEnginePathObserver(g_HomePathsModuleObserver); -} -void HomePaths_Destroy() -{ - Radiant_detachEnginePathObserver(g_HomePathsModuleObserver); -} - - -// Engine Path - -CopiedString g_strEnginePath; -ModuleObservers g_enginePathObservers; -std::size_t g_enginepath_unrealised = 1; - -void Radiant_attachEnginePathObserver(ModuleObserver& observer) -{ - g_enginePathObservers.attach(observer); -} - -void Radiant_detachEnginePathObserver(ModuleObserver& observer) -{ - g_enginePathObservers.detach(observer); -} - - -void EnginePath_Realise() -{ - if(--g_enginepath_unrealised == 0) - { - g_enginePathObservers.realise(); - } -} - - -const char* EnginePath_get() -{ - ASSERT_MESSAGE(g_enginepath_unrealised == 0, "EnginePath_get: engine path not realised"); - return g_strEnginePath.c_str(); -} - -void EnginePath_Unrealise() -{ - if(++g_enginepath_unrealised == 1) - { - g_enginePathObservers.unrealise(); - } -} - -void setEnginePath(const char* path) -{ - StringOutputStream buffer(256); - buffer << DirectoryCleaned(path); - if(!path_equal(buffer.c_str(), g_strEnginePath.c_str())) - { -#if 0 - while(!ConfirmModified("Paths Changed")) - { - if(Map_Unnamed(g_map)) - { - Map_SaveAs(); - } - else - { - Map_Save(); - } - } - Map_RegionOff(); -#endif - - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Changing Engine Path"); - - EnginePath_Unrealise(); - - g_strEnginePath = buffer.c_str(); - - EnginePath_Realise(); - } -} - - -// App Path - -CopiedString g_strAppPath; ///< holds the full path of the executable - -const char* AppPath_get() -{ - return g_strAppPath.c_str(); -} - -/// the path to the local rc-dir -const char* LocalRcPath_get(void) -{ - static CopiedString rc_path; - if(rc_path.empty()) - { - StringOutputStream stream(256); - stream << GlobalRadiant().getSettingsPath() << g_pGameDescription->mGameFile.c_str() << "/"; - rc_path = stream.c_str(); - } - return rc_path.c_str(); -} - -/// directory for temp files -/// NOTE: on *nix this is were we check for .pid -CopiedString g_strSettingsPath; -const char* SettingsPath_get() -{ - return g_strSettingsPath.c_str(); -} - - -/*! -points to the game tools directory, for instance -C:/Program Files/Quake III Arena/GtkRadiant -(or other games) -this is one of the main variables that are configured by the game selection on startup -[GameToolsPath]/plugins -[GameToolsPath]/modules -and also q3map, bspc -*/ -CopiedString g_strGameToolsPath; ///< this is set by g_GamesDialog - -const char* GameToolsPath_get() -{ - return g_strGameToolsPath.c_str(); -} - -void EnginePathImport(CopiedString& self, const char* value) -{ - setEnginePath(value); -} -typedef ReferenceCaller1 EnginePathImportCaller; - -void Paths_constructPreferences(PreferencesPage& page) -{ - page.appendPathEntry("Engine Path", true, - StringImportCallback(EnginePathImportCaller(g_strEnginePath)), - StringExportCallback(StringExportCaller(g_strEnginePath)) - ); -} -void Paths_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Paths", "Path Settings")); - Paths_constructPreferences(page); -} -void Paths_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - - -class PathsDialog : public Dialog -{ -public: - GtkWindow* BuildDialog() - { - GtkFrame* frame = create_dialog_frame("Path settings", GTK_SHADOW_ETCHED_IN); - - GtkVBox* vbox2 = create_dialog_vbox(0, 4); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox2)); - - { - PreferencesPage preferencesPage(*this, GTK_WIDGET(vbox2)); - Paths_constructPreferences(preferencesPage); - } - - return create_simple_modal_dialog_window("Engine Path Not Found", m_modal, GTK_WIDGET(frame)); - } -}; - -PathsDialog g_PathsDialog; - -void EnginePath_verify() -{ - if(!file_exists(g_strEnginePath.c_str())) - { - g_PathsDialog.Create(); - g_PathsDialog.DoModal(); - g_PathsDialog.Destroy(); - } -} - -namespace -{ - CopiedString g_gamename; - CopiedString g_gamemode; - ModuleObservers g_gameNameObservers; - ModuleObservers g_gameModeObservers; -} - -void Radiant_attachGameNameObserver(ModuleObserver& observer) -{ - g_gameNameObservers.attach(observer); -} - -void Radiant_detachGameNameObserver(ModuleObserver& observer) -{ - g_gameNameObservers.detach(observer); -} - -const char* basegame_get() -{ - return g_pGameDescription->getRequiredKeyValue("basegame"); -} - -const char* gamename_get() -{ - const char* gamename = g_gamename.c_str(); - if(string_empty(gamename)) - { - return basegame_get(); - } - return gamename; -} - -void gamename_set(const char* gamename) -{ - if(!string_equal(gamename, g_gamename.c_str())) - { - g_gameNameObservers.unrealise(); - g_gamename = gamename; - g_gameNameObservers.realise(); - } -} - -void Radiant_attachGameModeObserver(ModuleObserver& observer) -{ - g_gameModeObservers.attach(observer); -} - -void Radiant_detachGameModeObserver(ModuleObserver& observer) -{ - g_gameModeObservers.detach(observer); -} - -const char* gamemode_get() -{ - return g_gamemode.c_str(); -} - -void gamemode_set(const char* gamemode) -{ - if(!string_equal(gamemode, g_gamemode.c_str())) - { - g_gameModeObservers.unrealise(); - g_gamemode = gamemode; - g_gameModeObservers.realise(); - } -} - -#include "os/dir.h" - -class CLoadModule -{ - const char* m_path; -public: - CLoadModule(const char* path) : m_path(path) - { - } - void operator()(const char* name) const - { - char fullname[1024]; - ASSERT_MESSAGE(strlen(m_path) + strlen(name) < 1024, ""); - strcpy(fullname, m_path); - strcat(fullname, name); - globalOutputStream() << "Found '" << fullname << "'\n"; - GlobalModuleServer_loadModule(fullname); - } -}; - -const char* const c_library_extension = -#if defined(WIN32) -"dll" -#elif defined (__APPLE__) -"dylib" -#elif defined(__linux__) || defined (__FreeBSD__) -"so" -#endif -; - -void Radiant_loadModules(const char* path) -{ - Directory_forEach(path, MatchFileExtension(c_library_extension, CLoadModule(path))); -} - -void Radiant_loadModulesFromRoot(const char* directory) -{ - { - StringOutputStream path(256); - path << directory << g_pluginsDir; - Radiant_loadModules(path.c_str()); - } - - if(!string_equal(g_pluginsDir, g_modulesDir)) - { - StringOutputStream path(256); - path << directory << g_modulesDir; - Radiant_loadModules(path.c_str()); - } -} - -//! Make COLOR_BRUSHES override worldspawn eclass colour. -void SetWorldspawnColour(const Vector3& colour) -{ - EntityClass* worldspawn = GlobalEntityClassManager().findOrInsert("worldspawn", true); - eclass_release_state(worldspawn); - worldspawn->color = colour; - eclass_capture_state(worldspawn); -} - - -class WorldspawnColourEntityClassObserver : public ModuleObserver -{ - std::size_t m_unrealised; -public: - WorldspawnColourEntityClassObserver() : m_unrealised(1) - { - } - void realise() - { - if(--m_unrealised == 0) - { - SetWorldspawnColour(g_xywindow_globals.color_brushes); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - } - } -}; - -WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver; - - -ModuleObservers g_gameToolsPathObservers; - -void Radiant_attachGameToolsPathObserver(ModuleObserver& observer) -{ - g_gameToolsPathObservers.attach(observer); -} - -void Radiant_detachGameToolsPathObserver(ModuleObserver& observer) -{ - g_gameToolsPathObservers.detach(observer); -} - -void Radiant_Initialise() -{ - GlobalModuleServer_Initialise(); - - Radiant_loadModulesFromRoot(AppPath_get()); - - Preferences_Load(); - - bool success = Radiant_Construct(GlobalModuleServer_get()); - ASSERT_MESSAGE(success, "module system failed to initialise - see radiant.log for error messages"); - - g_gameToolsPathObservers.realise(); - g_gameModeObservers.realise(); - g_gameNameObservers.realise(); -} - -void Radiant_Shutdown() -{ - g_gameNameObservers.unrealise(); - g_gameModeObservers.unrealise(); - g_gameToolsPathObservers.unrealise(); - - if (!g_preferences_globals.disable_ini) - { - globalOutputStream() << "Start writing prefs\n"; - Preferences_Save(); - globalOutputStream() << "Done prefs\n"; - } - - Radiant_Destroy(); - - GlobalModuleServer_Shutdown(); -} - -void Exit() -{ - if(ConfirmModified("Exit Radiant")) - { - gtk_main_quit(); - } -} - - -void Undo() -{ - GlobalUndoSystem().undo(); - SceneChangeNotify(); -} - -void Redo() -{ - GlobalUndoSystem().redo(); - SceneChangeNotify(); -} - -void deleteSelection() -{ - UndoableCommand undo("deleteSelected"); - Select_Delete(); -} - -void Map_ExportSelected(TextOutputStream& ostream) -{ - Map_ExportSelected(ostream, Map_getFormat(g_map)); -} - -void Map_ImportSelected(TextInputStream& istream) -{ - Map_ImportSelected(istream, Map_getFormat(g_map)); -} - -void Selection_Copy() -{ - clipboard_copy(Map_ExportSelected); -} - -void Selection_Paste() -{ - clipboard_paste(Map_ImportSelected); -} - -void Copy() -{ - if(SelectedFaces_empty()) - { - Selection_Copy(); - } - else - { - SelectedFaces_copyTexture(); - } -} - -void Paste() -{ - if(SelectedFaces_empty()) - { - UndoableCommand undo("paste"); - - GlobalSelectionSystem().setSelectedAll(false); - Selection_Paste(); - } - else - { - SelectedFaces_pasteTexture(); - } -} - -void PasteToCamera() -{ - CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); - GlobalSelectionSystem().setSelectedAll(false); - - UndoableCommand undo("pasteToCamera"); - - Selection_Paste(); - - // Work out the delta - Vector3 mid; - Select_GetMid(mid); - Vector3 delta = vector3_subtracted(vector3_snapped(Camera_getOrigin(camwnd), GetSnapGridSize()), mid); - - // Move to camera - GlobalSelectionSystem().translateSelected(delta); -} - - -void ColorScheme_Original() -{ - TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); - - g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); - g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); - CamWnd_Update(*g_pParentWnd->GetCamWnd()); - - g_xywindow_globals.color_gridback = Vector3(1.0f, 1.0f, 1.0f); - g_xywindow_globals.color_gridminor = Vector3(0.75f, 0.75f, 0.75f); - g_xywindow_globals.color_gridmajor = Vector3(0.5f, 0.5f, 0.5f); - g_xywindow_globals.color_gridminor_alt = Vector3(0.5f, 0.0f, 0.0f); - g_xywindow_globals.color_gridmajor_alt = Vector3(1.0f, 0.0f, 0.0f); - g_xywindow_globals.color_gridblock = Vector3(0.0f, 0.0f, 1.0f); - g_xywindow_globals.color_gridtext = Vector3(0.0f, 0.0f, 0.0f); - g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); - g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); - g_xywindow_globals.color_brushes = Vector3(0.0f, 0.0f, 0.0f); - SetWorldspawnColour(g_xywindow_globals.color_brushes); - g_xywindow_globals.color_viewname = Vector3(0.5f, 0.0f, 0.75f); - XY_UpdateAllWindows(); -} - -void ColorScheme_QER() -{ - TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); - - g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); - g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); - CamWnd_Update(*g_pParentWnd->GetCamWnd()); - - g_xywindow_globals.color_gridback = Vector3(1.0f, 1.0f, 1.0f); - g_xywindow_globals.color_gridminor = Vector3(1.0f, 1.0f, 1.0f); - g_xywindow_globals.color_gridmajor = Vector3(0.5f, 0.5f, 0.5f); - g_xywindow_globals.color_gridblock = Vector3(0.0f, 0.0f, 1.0f); - g_xywindow_globals.color_gridtext = Vector3(0.0f, 0.0f, 0.0f); - g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); - g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); - g_xywindow_globals.color_brushes = Vector3(0.0f, 0.0f, 0.0f); - SetWorldspawnColour(g_xywindow_globals.color_brushes); - g_xywindow_globals.color_viewname = Vector3(0.5f, 0.0f, 0.75f); - XY_UpdateAllWindows(); -} - -void ColorScheme_Black() -{ - TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); - - g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); - g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); - CamWnd_Update(*g_pParentWnd->GetCamWnd()); - - g_xywindow_globals.color_gridback = Vector3(0.0f, 0.0f, 0.0f); - g_xywindow_globals.color_gridminor = Vector3(0.2f, 0.2f, 0.2f); - g_xywindow_globals.color_gridmajor = Vector3(0.3f, 0.5f, 0.5f); - g_xywindow_globals.color_gridblock = Vector3(0.0f, 0.0f, 1.0f); - g_xywindow_globals.color_gridtext = Vector3(1.0f, 1.0f, 1.0f); - g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); - g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); - g_xywindow_globals.color_brushes = Vector3(1.0f, 1.0f, 1.0f); - SetWorldspawnColour(g_xywindow_globals.color_brushes); - g_xywindow_globals.color_viewname = Vector3(0.7f, 0.7f, 0.0f); - XY_UpdateAllWindows(); -} - -/* ydnar: to emulate maya/max/lightwave color schemes */ -void ColorScheme_Ydnar() -{ - TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); - - g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); - g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); - CamWnd_Update(*g_pParentWnd->GetCamWnd()); - - g_xywindow_globals.color_gridback = Vector3(0.77f, 0.77f, 0.77f); - g_xywindow_globals.color_gridminor = Vector3(0.83f, 0.83f, 0.83f); - g_xywindow_globals.color_gridmajor = Vector3(0.89f, 0.89f, 0.89f); - g_xywindow_globals.color_gridblock = Vector3(1.0f, 1.0f, 1.0f); - g_xywindow_globals.color_gridtext = Vector3(0.0f, 0.0f, 0.0f); - g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); - g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); - g_xywindow_globals.color_brushes = Vector3(0.0f, 0.0f, 0.0f); - SetWorldspawnColour(g_xywindow_globals.color_brushes); - g_xywindow_globals.color_viewname = Vector3(0.5f, 0.0f, 0.75f); - XY_UpdateAllWindows(); -} - -typedef Callback1 GetColourCallback; -typedef Callback1 SetColourCallback; - -class ChooseColour -{ - GetColourCallback m_get; - SetColourCallback m_set; -public: - ChooseColour(const GetColourCallback& get, const SetColourCallback& set) - : m_get(get), m_set(set) - { - } - void operator()() - { - Vector3 colour; - m_get(colour); - color_dialog(GTK_WIDGET(MainFrame_getWindow()), colour); - m_set(colour); - } -}; - - - -void Colour_get(const Vector3& colour, Vector3& other) -{ - other = colour; -} -typedef ConstReferenceCaller1 ColourGetCaller; - -void Colour_set(Vector3& colour, const Vector3& other) -{ - colour = other; - SceneChangeNotify(); -} -typedef ReferenceCaller1 ColourSetCaller; - -void BrushColour_set(const Vector3& other) -{ - g_xywindow_globals.color_brushes = other; - SetWorldspawnColour(g_xywindow_globals.color_brushes); - SceneChangeNotify(); -} -typedef FreeCaller1 BrushColourSetCaller; - -void ClipperColour_set(const Vector3& other) -{ - g_xywindow_globals.color_clipper = other; - Brush_clipperColourChanged(); - SceneChangeNotify(); -} -typedef FreeCaller1 ClipperColourSetCaller; - -void TextureBrowserColour_get(Vector3& other) -{ - other = TextureBrowser_getBackgroundColour(GlobalTextureBrowser()); -} -typedef FreeCaller1 TextureBrowserColourGetCaller; - -void TextureBrowserColour_set(const Vector3& other) -{ - TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), other); -} -typedef FreeCaller1 TextureBrowserColourSetCaller; - - -class ColoursMenu -{ -public: - ChooseColour m_textureback; - ChooseColour m_xyback; - ChooseColour m_gridmajor; - ChooseColour m_gridminor; - ChooseColour m_gridmajor_alt; - ChooseColour m_gridminor_alt; - ChooseColour m_gridtext; - ChooseColour m_gridblock; - ChooseColour m_cameraback; - ChooseColour m_brush; - ChooseColour m_selectedbrush; - ChooseColour m_selectedbrush3d; - ChooseColour m_clipper; - ChooseColour m_viewname; - - ColoursMenu() : - m_textureback(TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller()), - m_xyback(ColourGetCaller(g_xywindow_globals.color_gridback), ColourSetCaller(g_xywindow_globals.color_gridback)), - m_gridmajor(ColourGetCaller(g_xywindow_globals.color_gridmajor), ColourSetCaller(g_xywindow_globals.color_gridmajor)), - m_gridminor(ColourGetCaller(g_xywindow_globals.color_gridminor), ColourSetCaller(g_xywindow_globals.color_gridminor)), - m_gridmajor_alt(ColourGetCaller(g_xywindow_globals.color_gridmajor_alt), ColourSetCaller(g_xywindow_globals.color_gridmajor_alt)), - m_gridminor_alt(ColourGetCaller(g_xywindow_globals.color_gridminor_alt), ColourSetCaller(g_xywindow_globals.color_gridminor_alt)), - m_gridtext(ColourGetCaller(g_xywindow_globals.color_gridtext), ColourSetCaller(g_xywindow_globals.color_gridtext)), - m_gridblock(ColourGetCaller(g_xywindow_globals.color_gridblock), ColourSetCaller(g_xywindow_globals.color_gridblock)), - m_cameraback(ColourGetCaller(g_camwindow_globals.color_cameraback), ColourSetCaller(g_camwindow_globals.color_cameraback)), - m_brush(ColourGetCaller(g_xywindow_globals.color_brushes), BrushColourSetCaller()), - m_selectedbrush(ColourGetCaller(g_xywindow_globals.color_selbrushes), ColourSetCaller(g_xywindow_globals.color_selbrushes)), - m_selectedbrush3d(ColourGetCaller(g_camwindow_globals.color_selbrushes3d), ColourSetCaller(g_camwindow_globals.color_selbrushes3d)), - m_clipper(ColourGetCaller(g_xywindow_globals.color_clipper), ClipperColourSetCaller()), - m_viewname(ColourGetCaller(g_xywindow_globals.color_viewname), ColourSetCaller(g_xywindow_globals.color_viewname)) - { - } -}; - -ColoursMenu g_ColoursMenu; - -GtkMenuItem* create_colours_menu() -{ - GtkMenuItem* colours_menu_item = new_sub_menu_item_with_mnemonic("Colors"); - GtkMenu* menu_in_menu = GTK_MENU(gtk_menu_item_get_submenu(colours_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - - GtkMenu* menu_3 = create_sub_menu_with_mnemonic(menu_in_menu, "Themes"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_3); - - create_menu_item_with_mnemonic(menu_3, "QE4 Original", "ColorSchemeOriginal"); - create_menu_item_with_mnemonic(menu_3, "Q3Radiant Original", "ColorSchemeQER"); - create_menu_item_with_mnemonic(menu_3, "Black and Green", "ColorSchemeBlackAndGreen"); - create_menu_item_with_mnemonic(menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar"); - - menu_separator(menu_in_menu); - - create_menu_item_with_mnemonic(menu_in_menu, "_Texture Background...", "ChooseTextureBackgroundColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Grid Background...", "ChooseGridBackgroundColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Grid Major...", "ChooseGridMajorColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Grid Minor...", "ChooseGridMinorColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Grid Major Small...", "ChooseSmallGridMajorColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Grid Minor Small...", "ChooseSmallGridMinorColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Grid Text...", "ChooseGridTextColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Grid Block...", "ChooseGridBlockColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Default Brush...", "ChooseBrushColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Camera Background...", "ChooseCameraBackgroundColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Selected Brush...", "ChooseSelectedBrushColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Selected Brush (Camera)...", "ChooseCameraSelectedBrushColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Clipper...", "ChooseClipperColor"); - create_menu_item_with_mnemonic(menu_in_menu, "Active View name...", "ChooseOrthoViewNameColor"); - - return colours_menu_item; -} - - -void Restart() -{ - PluginsMenu_clear(); - PluginToolbar_clear(); - - Radiant_Shutdown(); - Radiant_Initialise(); - - PluginsMenu_populate(); - - PluginToolbar_populate(); -} - - -void thunk_OnSleep() -{ - g_pParentWnd->OnSleep(); -} - -void OpenUpdateURL() -{ - // build the URL - StringOutputStream URL(256); - URL << "http://www.icculus.org/netradiant/?cmd=update&data=dlupdate&query_dlup=1"; -#ifdef WIN32 - URL << "&OS_dlup=1"; -#elif defined(__APPLE__) - URL << "&OS_dlup=2"; -#else - URL << "&OS_dlup=3"; -#endif - URL << "&Version_dlup=" RADIANT_VERSION; - g_GamesDialog.AddPacksURL(URL); - OpenURL(URL.c_str()); -} - -// open the Q3Rad manual -void OpenHelpURL() -{ - // at least on win32, AppPath + "docs/index.html" - StringOutputStream help(256); - help << AppPath_get() << "docs/index.html"; - OpenURL(help.c_str()); -} - -void OpenBugReportURL() -{ - OpenURL("http://www.icculus.org/netradiant/?cmd=bugs"); -} - - -GtkWidget* g_page_console; - -void Console_ToggleShow() -{ - GroupDialog_showPage(g_page_console); -} - -GtkWidget* g_page_entity; - -void EntityInspector_ToggleShow() -{ - GroupDialog_showPage(g_page_entity); -} - - - -void SetClipMode(bool enable); -void ModeChangeNotify(); - -typedef void(*ToolMode)(); -ToolMode g_currentToolMode = 0; -bool g_currentToolModeSupportsComponentEditing = false; -ToolMode g_defaultToolMode = 0; - - - -void SelectionSystem_DefaultMode() -{ - GlobalSelectionSystem().SetMode(SelectionSystem::ePrimitive); - GlobalSelectionSystem().SetComponentMode(SelectionSystem::eDefault); - ModeChangeNotify(); -} - - -bool EdgeMode() -{ - return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge; -} - -bool VertexMode() -{ - return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex; -} - -bool FaceMode() -{ - return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace; -} - -template -class BoolFunctionExport -{ -public: - static void apply(const BoolImportCallback& importCallback) - { - importCallback(BoolFunction()); - } -}; - -typedef FreeCaller1::apply> EdgeModeApplyCaller; -EdgeModeApplyCaller g_edgeMode_button_caller; -BoolExportCallback g_edgeMode_button_callback(g_edgeMode_button_caller); -ToggleItem g_edgeMode_button(g_edgeMode_button_callback); - -typedef FreeCaller1::apply> VertexModeApplyCaller; -VertexModeApplyCaller g_vertexMode_button_caller; -BoolExportCallback g_vertexMode_button_callback(g_vertexMode_button_caller); -ToggleItem g_vertexMode_button(g_vertexMode_button_callback); - -typedef FreeCaller1::apply> FaceModeApplyCaller; -FaceModeApplyCaller g_faceMode_button_caller; -BoolExportCallback g_faceMode_button_callback(g_faceMode_button_caller); -ToggleItem g_faceMode_button(g_faceMode_button_callback); - -void ComponentModeChanged() -{ - g_edgeMode_button.update(); - g_vertexMode_button.update(); - g_faceMode_button.update(); -} - -void ComponentMode_SelectionChanged(const Selectable& selectable) -{ - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && GlobalSelectionSystem().countSelected() == 0) - { - SelectionSystem_DefaultMode(); - ComponentModeChanged(); - } -} - -void SelectEdgeMode() -{ -#if 0 - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) - { - GlobalSelectionSystem().Select(false); - } -#endif - - if(EdgeMode()) - { - SelectionSystem_DefaultMode(); - } - else if(GlobalSelectionSystem().countSelected() != 0) - { - if(!g_currentToolModeSupportsComponentEditing) - { - g_defaultToolMode(); - } - - GlobalSelectionSystem().SetMode(SelectionSystem::eComponent); - GlobalSelectionSystem().SetComponentMode(SelectionSystem::eEdge); - } - - ComponentModeChanged(); - - ModeChangeNotify(); -} - -void SelectVertexMode() -{ -#if 0 - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) - { - GlobalSelectionSystem().Select(false); - } -#endif - - if(VertexMode()) - { - SelectionSystem_DefaultMode(); - } - else if(GlobalSelectionSystem().countSelected() != 0) - { - if(!g_currentToolModeSupportsComponentEditing) - { - g_defaultToolMode(); - } - - GlobalSelectionSystem().SetMode(SelectionSystem::eComponent); - GlobalSelectionSystem().SetComponentMode(SelectionSystem::eVertex); - } - - ComponentModeChanged(); - - ModeChangeNotify(); -} - -void SelectFaceMode() -{ -#if 0 - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) - { - GlobalSelectionSystem().Select(false); - } -#endif - - if(FaceMode()) - { - SelectionSystem_DefaultMode(); - } - else if(GlobalSelectionSystem().countSelected() != 0) - { - if(!g_currentToolModeSupportsComponentEditing) - { - g_defaultToolMode(); - } - - GlobalSelectionSystem().SetMode(SelectionSystem::eComponent); - GlobalSelectionSystem().SetComponentMode(SelectionSystem::eFace); - } - - ComponentModeChanged(); - - ModeChangeNotify(); -} - - -class CloneSelected : public scene::Graph::Walker -{ - bool doMakeUnique; - NodeSmartReference worldspawn; -public: - CloneSelected(bool d): doMakeUnique(d), worldspawn(Map_FindOrInsertWorldspawn(g_map)) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.size() == 1) - return true; - - // ignore worldspawn, but keep checking children - NodeSmartReference me(path.top().get()); - if(me == worldspawn) - return true; - - if(!path.top().get().isRoot()) - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected()) - { - return false; - } - } - - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - if(path.size() == 1) - return; - - // ignore worldspawn, but keep checking children - NodeSmartReference me(path.top().get()); - if(me == worldspawn) - return; - - if(!path.top().get().isRoot()) - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected()) - { - NodeSmartReference clone(Node_Clone(path.top())); - if(doMakeUnique) - Map_gatherNamespaced(clone); - Node_getTraversable(path.parent().get())->insert(clone); - } - } - } -}; - -void Scene_Clone_Selected(scene::Graph& graph, bool doMakeUnique) -{ - graph.traverse(CloneSelected(doMakeUnique)); - - Map_mergeClonedNames(); -} - -enum ENudgeDirection -{ - eNudgeUp = 1, - eNudgeDown = 3, - eNudgeLeft = 0, - eNudgeRight = 2, -}; - -struct AxisBase -{ - Vector3 x; - Vector3 y; - Vector3 z; - AxisBase(const Vector3& x_, const Vector3& y_, const Vector3& z_) - : x(x_), y(y_), z(z_) - { - } -}; - -AxisBase AxisBase_forViewType(VIEWTYPE viewtype) -{ - switch(viewtype) - { - case XY: - return AxisBase(g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z); - case XZ: - return AxisBase(g_vector3_axis_x, g_vector3_axis_z, g_vector3_axis_y); - case YZ: - return AxisBase(g_vector3_axis_y, g_vector3_axis_z, g_vector3_axis_x); - } - - ERROR_MESSAGE("invalid viewtype"); - return AxisBase(Vector3(0, 0, 0), Vector3(0, 0, 0), Vector3(0, 0, 0)); -} - -Vector3 AxisBase_axisForDirection(const AxisBase& axes, ENudgeDirection direction) -{ - switch (direction) - { - case eNudgeLeft: - return vector3_negated(axes.x); - case eNudgeUp: - return axes.y; - case eNudgeRight: - return axes.x; - case eNudgeDown: - return vector3_negated(axes.y); - } - - ERROR_MESSAGE("invalid direction"); - return Vector3(0, 0, 0); -} - -void NudgeSelection(ENudgeDirection direction, float fAmount, VIEWTYPE viewtype) -{ - AxisBase axes(AxisBase_forViewType(viewtype)); - Vector3 view_direction(vector3_negated(axes.z)); - Vector3 nudge(vector3_scaled(AxisBase_axisForDirection(axes, direction), fAmount)); - GlobalSelectionSystem().NudgeManipulator(nudge, view_direction); -} - -void Selection_Clone() -{ - if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) - { - UndoableCommand undo("cloneSelected"); - - Scene_Clone_Selected(GlobalSceneGraph(), false); - - //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType()); - //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType()); - } -} - -void Selection_Clone_MakeUnique() -{ - if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) - { - UndoableCommand undo("cloneSelectedMakeUnique"); - - Scene_Clone_Selected(GlobalSceneGraph(), true); - - //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType()); - //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType()); - } -} - -// called when the escape key is used (either on the main window or on an inspector) -void Selection_Deselect() -{ - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) - { - if(GlobalSelectionSystem().countSelectedComponents() != 0) - { - GlobalSelectionSystem().setSelectedAllComponents(false); - } - else - { - SelectionSystem_DefaultMode(); - ComponentModeChanged(); - } - } - else - { - if(GlobalSelectionSystem().countSelectedComponents() != 0) - { - GlobalSelectionSystem().setSelectedAllComponents(false); - } - else - { - GlobalSelectionSystem().setSelectedAll(false); - } - } -} - - -void Selection_NudgeUp() -{ - UndoableCommand undo("nudgeSelectedUp"); - NudgeSelection(eNudgeUp, GetGridSize(), GlobalXYWnd_getCurrentViewType()); -} - -void Selection_NudgeDown() -{ - UndoableCommand undo("nudgeSelectedDown"); - NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType()); -} - -void Selection_NudgeLeft() -{ - UndoableCommand undo("nudgeSelectedLeft"); - NudgeSelection(eNudgeLeft, GetGridSize(), GlobalXYWnd_getCurrentViewType()); -} - -void Selection_NudgeRight() -{ - UndoableCommand undo("nudgeSelectedRight"); - NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType()); -} - - -void TranslateToolExport(const BoolImportCallback& importCallback) -{ - importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eTranslate); -} - -void RotateToolExport(const BoolImportCallback& importCallback) -{ - importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eRotate); -} - -void ScaleToolExport(const BoolImportCallback& importCallback) -{ - importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eScale); -} - -void DragToolExport(const BoolImportCallback& importCallback) -{ - importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag); -} - -void ClipperToolExport(const BoolImportCallback& importCallback) -{ - importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip); -} - -FreeCaller1 g_translatemode_button_caller; -BoolExportCallback g_translatemode_button_callback(g_translatemode_button_caller); -ToggleItem g_translatemode_button(g_translatemode_button_callback); - -FreeCaller1 g_rotatemode_button_caller; -BoolExportCallback g_rotatemode_button_callback(g_rotatemode_button_caller); -ToggleItem g_rotatemode_button(g_rotatemode_button_callback); - -FreeCaller1 g_scalemode_button_caller; -BoolExportCallback g_scalemode_button_callback(g_scalemode_button_caller); -ToggleItem g_scalemode_button(g_scalemode_button_callback); - -FreeCaller1 g_dragmode_button_caller; -BoolExportCallback g_dragmode_button_callback(g_dragmode_button_caller); -ToggleItem g_dragmode_button(g_dragmode_button_callback); - -FreeCaller1 g_clipper_button_caller; -BoolExportCallback g_clipper_button_callback(g_clipper_button_caller); -ToggleItem g_clipper_button(g_clipper_button_callback); - -void ToolChanged() -{ - g_translatemode_button.update(); - g_rotatemode_button.update(); - g_scalemode_button.update(); - g_dragmode_button.update(); - g_clipper_button.update(); -} - -const char* const c_ResizeMode_status = "QE4 Drag Tool: move and resize objects"; - -void DragMode() -{ - if(g_currentToolMode == DragMode && g_defaultToolMode != DragMode) - { - g_defaultToolMode(); - } - else - { - g_currentToolMode = DragMode; - g_currentToolModeSupportsComponentEditing = true; - - OnClipMode(false); - - Sys_Status(c_ResizeMode_status); - GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eDrag); - ToolChanged(); - ModeChangeNotify(); - } -} - - -const char* const c_TranslateMode_status = "Translate Tool: translate objects and components"; - -void TranslateMode() -{ - if(g_currentToolMode == TranslateMode && g_defaultToolMode != TranslateMode) - { - g_defaultToolMode(); - } - else - { - g_currentToolMode = TranslateMode; - g_currentToolModeSupportsComponentEditing = true; - - OnClipMode(false); - - Sys_Status(c_TranslateMode_status); - GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eTranslate); - ToolChanged(); - ModeChangeNotify(); - } -} - -const char* const c_RotateMode_status = "Rotate Tool: rotate objects and components"; - -void RotateMode() -{ - if(g_currentToolMode == RotateMode && g_defaultToolMode != RotateMode) - { - g_defaultToolMode(); - } - else - { - g_currentToolMode = RotateMode; - g_currentToolModeSupportsComponentEditing = true; - - OnClipMode(false); - - Sys_Status(c_RotateMode_status); - GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eRotate); - ToolChanged(); - ModeChangeNotify(); - } -} - -const char* const c_ScaleMode_status = "Scale Tool: scale objects and components"; - -void ScaleMode() -{ - if(g_currentToolMode == ScaleMode && g_defaultToolMode != ScaleMode) - { - g_defaultToolMode(); - } - else - { - g_currentToolMode = ScaleMode; - g_currentToolModeSupportsComponentEditing = true; - - OnClipMode(false); - - Sys_Status(c_ScaleMode_status); - GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eScale); - ToolChanged(); - ModeChangeNotify(); - } -} - - -const char* const c_ClipperMode_status = "Clipper Tool: apply clip planes to objects"; - - -void ClipperMode() -{ - if(g_currentToolMode == ClipperMode && g_defaultToolMode != ClipperMode) - { - g_defaultToolMode(); - } - else - { - g_currentToolMode = ClipperMode; - g_currentToolModeSupportsComponentEditing = false; - - SelectionSystem_DefaultMode(); - - OnClipMode(true); - - Sys_Status(c_ClipperMode_status); - GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eClip); - ToolChanged(); - ModeChangeNotify(); - } -} - - -void Texdef_Rotate(float angle) -{ - StringOutputStream command; - command << "brushRotateTexture -angle " << angle; - UndoableCommand undo(command.c_str()); - Select_RotateTexture(angle); -} - -void Texdef_RotateClockwise() -{ - Texdef_Rotate(static_cast(fabs(g_si_globals.rotate))); -} - -void Texdef_RotateAntiClockwise() -{ - Texdef_Rotate(static_cast(-fabs(g_si_globals.rotate))); -} - -void Texdef_Scale(float x, float y) -{ - StringOutputStream command; - command << "brushScaleTexture -x " << x << " -y " << y; - UndoableCommand undo(command.c_str()); - Select_ScaleTexture(x, y); -} - -void Texdef_ScaleUp() -{ - Texdef_Scale(0, g_si_globals.scale[1]); -} - -void Texdef_ScaleDown() -{ - Texdef_Scale(0, -g_si_globals.scale[1]); -} - -void Texdef_ScaleLeft() -{ - Texdef_Scale(-g_si_globals.scale[0],0); -} - -void Texdef_ScaleRight() -{ - Texdef_Scale(g_si_globals.scale[0],0); -} - -void Texdef_Shift(float x, float y) -{ - StringOutputStream command; - command << "brushShiftTexture -x " << x << " -y " << y; - UndoableCommand undo(command.c_str()); - Select_ShiftTexture(x, y); -} - -void Texdef_ShiftLeft() -{ - Texdef_Shift(-g_si_globals.shift[0], 0); -} - -void Texdef_ShiftRight() -{ - Texdef_Shift(g_si_globals.shift[0], 0); -} - -void Texdef_ShiftUp() -{ - Texdef_Shift(0, g_si_globals.shift[1]); -} - -void Texdef_ShiftDown() -{ - Texdef_Shift(0, -g_si_globals.shift[1]); -} - - - -class SnappableSnapToGridSelected : public scene::Graph::Walker -{ - float m_snap; -public: - SnappableSnapToGridSelected(float snap) - : m_snap(snap) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Snappable* snappable = Node_getSnappable(path.top()); - if(snappable != 0 - && Instance_getSelectable(instance)->isSelected()) - { - snappable->snapto(m_snap); - } - } - return true; - } -}; - -void Scene_SnapToGrid_Selected(scene::Graph& graph, float snap) -{ - graph.traverse(SnappableSnapToGridSelected(snap)); -} - -class ComponentSnappableSnapToGridSelected : public scene::Graph::Walker -{ - float m_snap; -public: - ComponentSnappableSnapToGridSelected(float snap) - : m_snap(snap) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - ComponentSnappable* componentSnappable = Instance_getComponentSnappable(instance); - if(componentSnappable != 0 - && Instance_getSelectable(instance)->isSelected()) - { - componentSnappable->snapComponents(m_snap); - } - } - return true; - } -}; - -void Scene_SnapToGrid_Component_Selected(scene::Graph& graph, float snap) -{ - graph.traverse(ComponentSnappableSnapToGridSelected(snap)); -} - -void Selection_SnapToGrid() -{ - StringOutputStream command; - command << "snapSelected -grid " << GetGridSize(); - UndoableCommand undo(command.c_str()); - - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) - { - Scene_SnapToGrid_Component_Selected(GlobalSceneGraph(), GetGridSize()); - } - else - { - Scene_SnapToGrid_Selected(GlobalSceneGraph(), GetGridSize()); - } -} - - -static gint qe_every_second(gpointer data) -{ - GdkModifierType mask; - - gdk_window_get_pointer (0, 0, 0, &mask); - - if ((mask & (GDK_BUTTON1_MASK|GDK_BUTTON2_MASK|GDK_BUTTON3_MASK)) == 0) - { - QE_CheckAutoSave(); - } - - return TRUE; -} - -guint s_qe_every_second_id = 0; - -void EverySecondTimer_enable() -{ - if(s_qe_every_second_id == 0) - { - s_qe_every_second_id = gtk_timeout_add(1000, qe_every_second, 0); - } -} - -void EverySecondTimer_disable() -{ - if(s_qe_every_second_id != 0) - { - gtk_timeout_remove(s_qe_every_second_id); - s_qe_every_second_id = 0; - } -} - -gint window_realize_remove_decoration(GtkWidget* widget, gpointer data) -{ - gdk_window_set_decorations(widget->window, (GdkWMDecoration)(GDK_DECOR_ALL|GDK_DECOR_MENU|GDK_DECOR_MINIMIZE|GDK_DECOR_MAXIMIZE)); - return FALSE; -} - -class WaitDialog -{ -public: - GtkWindow* m_window; - GtkLabel* m_label; -}; - -WaitDialog create_wait_dialog(const char* title, const char* text) -{ - WaitDialog dialog; - - dialog.m_window = create_floating_window(title, MainFrame_getWindow()); - gtk_window_set_resizable(dialog.m_window, FALSE); - gtk_container_set_border_width(GTK_CONTAINER(dialog.m_window), 0); - gtk_window_set_position(dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT); - - g_signal_connect(G_OBJECT(dialog.m_window), "realize", G_CALLBACK(window_realize_remove_decoration), 0); - - { - dialog.m_label = GTK_LABEL(gtk_label_new(text)); - gtk_misc_set_alignment(GTK_MISC(dialog.m_label), 0.0, 0.5); - gtk_label_set_justify(dialog.m_label, GTK_JUSTIFY_LEFT); - gtk_widget_show(GTK_WIDGET(dialog.m_label)); - gtk_widget_set_size_request(GTK_WIDGET(dialog.m_label), 200, -1); - - gtk_container_add(GTK_CONTAINER(dialog.m_window), GTK_WIDGET(dialog.m_label)); - } - return dialog; -} - -namespace -{ - clock_t g_lastRedrawTime = 0; - const clock_t c_redrawInterval = clock_t(CLOCKS_PER_SEC / 10); - - bool redrawRequired() - { - clock_t currentTime = std::clock(); - if(currentTime - g_lastRedrawTime >= c_redrawInterval) - { - g_lastRedrawTime = currentTime; - return true; - } - return false; - } -} - -bool MainFrame_isActiveApp() -{ - //globalOutputStream() << "listing\n"; - GList* list = gtk_window_list_toplevels(); - for(GList* i = list; i != 0; i = g_list_next(i)) - { - //globalOutputStream() << "toplevel.. "; - if(gtk_window_is_active(GTK_WINDOW(i->data))) - { - //globalOutputStream() << "is active\n"; - return true; - } - //globalOutputStream() << "not active\n"; - } - return false; -} - -typedef std::list StringStack; -StringStack g_wait_stack; -WaitDialog g_wait; - -bool ScreenUpdates_Enabled() -{ - return g_wait_stack.empty(); -} - -void ScreenUpdates_process() -{ - if(redrawRequired() && GTK_WIDGET_VISIBLE(g_wait.m_window)) - { - process_gui(); - } -} - - -void ScreenUpdates_Disable(const char* message, const char* title) -{ - if(g_wait_stack.empty()) - { - EverySecondTimer_disable(); - - process_gui(); - - bool isActiveApp = MainFrame_isActiveApp(); - - g_wait = create_wait_dialog(title, message); - gtk_grab_add(GTK_WIDGET(g_wait.m_window)); - - if(isActiveApp) - { - gtk_widget_show(GTK_WIDGET(g_wait.m_window)); - ScreenUpdates_process(); - } - } - else if(GTK_WIDGET_VISIBLE(g_wait.m_window)) - { - gtk_label_set_text(g_wait.m_label, message); - ScreenUpdates_process(); - } - g_wait_stack.push_back(message); -} - -void ScreenUpdates_Enable() -{ - ASSERT_MESSAGE(!ScreenUpdates_Enabled(), "screen updates already enabled"); - g_wait_stack.pop_back(); - if(g_wait_stack.empty()) - { - EverySecondTimer_enable(); - //gtk_widget_set_sensitive(GTK_WIDGET(MainFrame_getWindow()), TRUE); - - gtk_grab_remove(GTK_WIDGET(g_wait.m_window)); - destroy_floating_window(g_wait.m_window); - g_wait.m_window = 0; - - //gtk_window_present(MainFrame_getWindow()); - } - else if(GTK_WIDGET_VISIBLE(g_wait.m_window)) - { - gtk_label_set_text(g_wait.m_label, g_wait_stack.back().c_str()); - ScreenUpdates_process(); - } -} - - - -void GlobalCamera_UpdateWindow() -{ - if(g_pParentWnd != 0) - { - CamWnd_Update(*g_pParentWnd->GetCamWnd()); - } -} - -void XY_UpdateWindow(MainFrame& mainframe) -{ - if(mainframe.GetXYWnd() != 0) - { - XYWnd_Update(*mainframe.GetXYWnd()); - } -} - -void XZ_UpdateWindow(MainFrame& mainframe) -{ - if(mainframe.GetXZWnd() != 0) - { - XYWnd_Update(*mainframe.GetXZWnd()); - } -} - -void YZ_UpdateWindow(MainFrame& mainframe) -{ - if(mainframe.GetYZWnd() != 0) - { - XYWnd_Update(*mainframe.GetYZWnd()); - } -} - -void XY_UpdateAllWindows(MainFrame& mainframe) -{ - XY_UpdateWindow(mainframe); - XZ_UpdateWindow(mainframe); - YZ_UpdateWindow(mainframe); -} - -void XY_UpdateAllWindows() -{ - if(g_pParentWnd != 0) - { - XY_UpdateAllWindows(*g_pParentWnd); - } -} - -void UpdateAllWindows() -{ - GlobalCamera_UpdateWindow(); - XY_UpdateAllWindows(); -} - - -void ModeChangeNotify() -{ - SceneChangeNotify(); -} - -void ClipperChangeNotify() -{ - GlobalCamera_UpdateWindow(); - XY_UpdateAllWindows(); -} - - -LatchedInt g_Layout_viewStyle(0, "Window Layout"); -LatchedBool g_Layout_enableDetachableMenus(true, "Detachable Menus"); -LatchedBool g_Layout_enablePatchToolbar(true, "Patch Toolbar"); -LatchedBool g_Layout_enablePluginToolbar(true, "Plugin Toolbar"); - - - -GtkMenuItem* create_file_menu() -{ - // File menu - GtkMenuItem* file_menu_item = new_sub_menu_item_with_mnemonic("_File"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(file_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - create_menu_item_with_mnemonic(menu, "_New Map", "NewMap"); - menu_separator(menu); - -#if 0 - //++timo temporary experimental stuff for sleep mode.. - create_menu_item_with_mnemonic(menu, "_Sleep", "Sleep"); - menu_separator(menu); - // end experimental -#endif - - create_menu_item_with_mnemonic(menu, "_Open...", "OpenMap"); - - create_menu_item_with_mnemonic(menu, "_Import...", "ImportMap"); - create_menu_item_with_mnemonic(menu, "_Save", "SaveMap"); - create_menu_item_with_mnemonic(menu, "Save _as...", "SaveMapAs"); - create_menu_item_with_mnemonic(menu, "Save s_elected...", "SaveSelected"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Save re_gion...", "SaveRegion"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "_Refresh models", "RefreshReferences"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Pro_ject settings...", "ProjectSettings"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "_Pointfile...", "TogglePointfile"); - menu_separator(menu); - MRU_constructMenu(menu); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Check for NetRadiant update (web)", "CheckForUpdate"); // FIXME - create_menu_item_with_mnemonic(menu, "E_xit", "Exit"); - - return file_menu_item; -} - -GtkMenuItem* create_edit_menu() -{ - // Edit menu - GtkMenuItem* edit_menu_item = new_sub_menu_item_with_mnemonic("_Edit"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(edit_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - create_menu_item_with_mnemonic(menu, "_Undo", "Undo"); - create_menu_item_with_mnemonic(menu, "_Redo", "Redo"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "_Copy", "Copy"); - create_menu_item_with_mnemonic(menu, "_Paste", "Paste"); - create_menu_item_with_mnemonic(menu, "P_aste To Camera", "PasteToCamera"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "_Duplicate", "CloneSelection"); - create_menu_item_with_mnemonic(menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique"); - create_menu_item_with_mnemonic(menu, "D_elete", "DeleteSelection"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Pa_rent", "ParentSelection"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "C_lear Selection", "UnSelectSelection"); - create_menu_item_with_mnemonic(menu, "_Invert Selection", "InvertSelection"); - create_menu_item_with_mnemonic(menu, "Select i_nside", "SelectInside"); - create_menu_item_with_mnemonic(menu, "Select _touching", "SelectTouching"); - - GtkMenu* convert_menu = create_sub_menu_with_mnemonic(menu, "E_xpand Selection"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (convert_menu); - create_menu_item_with_mnemonic(convert_menu, "To Whole _Entities", "ExpandSelectionToEntities"); - - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Pre_ferences...", "Preferences"); - - return edit_menu_item; -} - -void fill_view_xy_top_menu(GtkMenu* menu) -{ - create_check_menu_item_with_mnemonic(menu, "XY (Top) View", "ToggleView"); -} - - -void fill_view_yz_side_menu(GtkMenu* menu) -{ - create_check_menu_item_with_mnemonic(menu, "YZ (Side) View", "ToggleSideView"); -} - - -void fill_view_xz_front_menu(GtkMenu* menu) -{ - create_check_menu_item_with_mnemonic(menu, "XZ (Front) View", "ToggleFrontView"); -} - - -GtkWidget* g_toggle_z_item = 0; -GtkWidget* g_toggle_console_item = 0; -GtkWidget* g_toggle_entity_item = 0; -GtkWidget* g_toggle_entitylist_item = 0; - -GtkMenuItem* create_view_menu(MainFrame::EViewStyle style) -{ - // View menu - GtkMenuItem* view_menu_item = new_sub_menu_item_with_mnemonic("Vie_w"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(view_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - if(style == MainFrame::eFloating) - { - fill_view_camera_menu(menu); - fill_view_xy_top_menu(menu); - fill_view_yz_side_menu(menu); - fill_view_xz_front_menu(menu); - } - if(style == MainFrame::eFloating || style == MainFrame::eSplit) - { - create_menu_item_with_mnemonic(menu, "Console View", "ToggleConsole"); - create_menu_item_with_mnemonic(menu, "Texture Browser", "ToggleTextures"); - create_menu_item_with_mnemonic(menu, "Entity Inspector", "ToggleEntityInspector"); - } - else - { - create_menu_item_with_mnemonic(menu, "Entity Inspector", "ViewEntityInfo"); - } - create_menu_item_with_mnemonic(menu, "_Surface Inspector", "SurfaceInspector"); - create_menu_item_with_mnemonic(menu, "Entity List", "EntityList"); - - menu_separator(menu); - { - GtkMenu* camera_menu = create_sub_menu_with_mnemonic (menu, "Camera"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (camera_menu); - create_menu_item_with_mnemonic(camera_menu, "_Center", "CenterView"); - create_menu_item_with_mnemonic(camera_menu, "_Up Floor", "UpFloor"); - create_menu_item_with_mnemonic(camera_menu, "_Down Floor", "DownFloor"); - menu_separator(camera_menu); - create_menu_item_with_mnemonic(camera_menu, "Far Clip Plane In", "CubicClipZoomIn"); - create_menu_item_with_mnemonic(camera_menu, "Far Clip Plane Out", "CubicClipZoomOut"); - menu_separator(camera_menu); - create_menu_item_with_mnemonic(camera_menu, "Next leak spot", "NextLeakSpot"); - create_menu_item_with_mnemonic(camera_menu, "Previous leak spot", "PrevLeakSpot"); - menu_separator(camera_menu); - create_menu_item_with_mnemonic(camera_menu, "Look Through Selected", "LookThroughSelected"); - create_menu_item_with_mnemonic(camera_menu, "Look Through Camera", "LookThroughCamera"); - } - menu_separator(menu); - { - GtkMenu* orthographic_menu = create_sub_menu_with_mnemonic(menu, "Orthographic"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (orthographic_menu); - if(style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating) - { - create_menu_item_with_mnemonic(orthographic_menu, "_Next (XY, YZ, XY)", "NextView"); - create_menu_item_with_mnemonic(orthographic_menu, "XY (Top)", "ViewTop"); - create_menu_item_with_mnemonic(orthographic_menu, "YZ", "ViewSide"); - create_menu_item_with_mnemonic(orthographic_menu, "XZ", "ViewFront"); - menu_separator(orthographic_menu); - } - - create_menu_item_with_mnemonic(orthographic_menu, "_XY 100%", "Zoom100"); - create_menu_item_with_mnemonic(orthographic_menu, "XY Zoom _In", "ZoomIn"); - create_menu_item_with_mnemonic(orthographic_menu, "XY Zoom _Out", "ZoomOut"); - } - - menu_separator(menu); - - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Show"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show _Angles", "ShowAngles"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show _Names", "ShowNames"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show Blocks", "ShowBlocks"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show C_oordinates", "ShowCoordinates"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show Window Outline", "ShowWindowOutline"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show Axes", "ShowAxes"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show Workzone", "ShowWorkzone"); - create_check_menu_item_with_mnemonic(menu_in_menu, "Show Stats", "ShowStats"); - } - - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Filter"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - Filters_constructMenu(menu_in_menu); - } - menu_separator(menu); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Hide/Show"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Hide Selected", "HideSelected"); - create_menu_item_with_mnemonic(menu_in_menu, "Show Hidden", "ShowHidden"); - } - menu_separator(menu); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Region"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "_Off", "RegionOff"); - create_menu_item_with_mnemonic(menu_in_menu, "_Set XY", "RegionSetXY"); - create_menu_item_with_mnemonic(menu_in_menu, "Set _Brush", "RegionSetBrush"); - create_menu_item_with_mnemonic(menu_in_menu, "Set Se_lected Brushes", "RegionSetSelection"); - } - - command_connect_accelerator("CenterXYView"); - - return view_menu_item; -} - -GtkMenuItem* create_selection_menu() -{ - // Selection menu - GtkMenuItem* selection_menu_item = new_sub_menu_item_with_mnemonic("M_odify"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(selection_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Components"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_check_menu_item_with_mnemonic(menu_in_menu, "_Edges", "DragEdges"); - create_check_menu_item_with_mnemonic(menu_in_menu, "_Vertices", "DragVertices"); - create_check_menu_item_with_mnemonic(menu_in_menu, "_Faces", "DragFaces"); - } - - menu_separator(menu); - - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic(menu, "Nudge"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Nudge Left", "SelectNudgeLeft"); - create_menu_item_with_mnemonic(menu_in_menu, "Nudge Right", "SelectNudgeRight"); - create_menu_item_with_mnemonic(menu_in_menu, "Nudge Up", "SelectNudgeUp"); - create_menu_item_with_mnemonic(menu_in_menu, "Nudge Down", "SelectNudgeDown"); - } - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Rotate"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Rotate X", "RotateSelectionX"); - create_menu_item_with_mnemonic(menu_in_menu, "Rotate Y", "RotateSelectionY"); - create_menu_item_with_mnemonic(menu_in_menu, "Rotate Z", "RotateSelectionZ"); - } - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Flip"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Flip _X", "MirrorSelectionX"); - create_menu_item_with_mnemonic(menu_in_menu, "Flip _Y", "MirrorSelectionY"); - create_menu_item_with_mnemonic(menu_in_menu, "Flip _Z", "MirrorSelectionZ"); - } - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Arbitrary rotation...", "ArbitraryRotation"); - create_menu_item_with_mnemonic(menu, "Arbitrary scale...", "ArbitraryScale"); - - return selection_menu_item; -} - -GtkMenuItem* create_bsp_menu() -{ - // BSP menu - GtkMenuItem* bsp_menu_item = new_sub_menu_item_with_mnemonic("_Build"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(bsp_menu_item)); - - if (g_Layout_enableDetachableMenus.m_value) - { - menu_tearoff(menu); - } - - create_menu_item_with_mnemonic(menu, "Customize...", "BuildMenuCustomize"); - - menu_separator(menu); - - Build_constructMenu(menu); - - g_bsp_menu = menu; - - return bsp_menu_item; -} - -GtkMenuItem* create_grid_menu() -{ - // Grid menu - GtkMenuItem* grid_menu_item = new_sub_menu_item_with_mnemonic("_Grid"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(grid_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - Grid_constructMenu(menu); - - return grid_menu_item; -} - -GtkMenuItem* create_misc_menu() -{ - // Misc menu - GtkMenuItem* misc_menu_item = new_sub_menu_item_with_mnemonic("M_isc"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(misc_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - -#if 0 - create_menu_item_with_mnemonic(menu, "_Benchmark", FreeCaller()); -#endif - gtk_container_add(GTK_CONTAINER(menu), GTK_WIDGET(create_colours_menu())); - - create_menu_item_with_mnemonic(menu, "Find brush...", "FindBrush"); - create_menu_item_with_mnemonic(menu, "Map Info...", "MapInfo"); - // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394 -// create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller()); - create_menu_item_with_mnemonic(menu, "_Background select", FreeCaller()); - return misc_menu_item; -} - -GtkMenuItem* create_entity_menu() -{ - // Brush menu - GtkMenuItem* entity_menu_item = new_sub_menu_item_with_mnemonic("E_ntity"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(entity_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - Entity_constructMenu(menu); - - return entity_menu_item; -} - -GtkMenuItem* create_brush_menu() -{ - // Brush menu - GtkMenuItem* brush_menu_item = new_sub_menu_item_with_mnemonic("B_rush"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(brush_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - Brush_constructMenu(menu); - - return brush_menu_item; -} - -GtkMenuItem* create_patch_menu() -{ - // Curve menu - GtkMenuItem* patch_menu_item = new_sub_menu_item_with_mnemonic("_Curve"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(patch_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - { - menu_tearoff(menu); - } - - Patch_constructMenu(menu); - - return patch_menu_item; -} - -GtkMenuItem* create_help_menu() -{ - // Help menu - GtkMenuItem* help_menu_item = new_sub_menu_item_with_mnemonic("_Help"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(help_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - create_menu_item_with_mnemonic(menu, "Manual", "OpenManual"); - - // this creates all the per-game drop downs for the game pack helps - // it will take care of hooking the Sys_OpenURL calls etc. - create_game_help_menu(menu); - - create_menu_item_with_mnemonic(menu, "Bug report", FreeCaller()); - create_menu_item_with_mnemonic(menu, "Shortcuts list", FreeCaller()); - create_menu_item_with_mnemonic(menu, "_About", FreeCaller()); - - return help_menu_item; -} - -GtkMenuBar* create_main_menu(MainFrame::EViewStyle style) -{ - GtkMenuBar* menu_bar = GTK_MENU_BAR(gtk_menu_bar_new()); - gtk_widget_show(GTK_WIDGET(menu_bar)); - - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_file_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_edit_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_view_menu(style))); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_selection_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_bsp_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_grid_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_misc_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_entity_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_brush_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_patch_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_plugins_menu())); - gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_help_menu())); - - return menu_bar; -} - - -void PatchInspector_registerShortcuts() -{ - command_connect_accelerator("PatchInspector"); -} - -void Patch_registerShortcuts() -{ - command_connect_accelerator("InvertCurveTextureX"); - command_connect_accelerator("InvertCurveTextureY"); - command_connect_accelerator("IncPatchColumn"); - command_connect_accelerator("IncPatchRow"); - command_connect_accelerator("DecPatchColumn"); - command_connect_accelerator("DecPatchRow"); - command_connect_accelerator("NaturalizePatch"); - //command_connect_accelerator("CapCurrentCurve"); -} - -void Manipulators_registerShortcuts() -{ - toggle_add_accelerator("MouseRotate"); - toggle_add_accelerator("MouseTranslate"); - toggle_add_accelerator("MouseScale"); - toggle_add_accelerator("MouseDrag"); - toggle_add_accelerator("ToggleClipper"); -} - -void TexdefNudge_registerShortcuts() -{ - command_connect_accelerator("TexRotateClock"); - command_connect_accelerator("TexRotateCounter"); - command_connect_accelerator("TexScaleUp"); - command_connect_accelerator("TexScaleDown"); - command_connect_accelerator("TexScaleLeft"); - command_connect_accelerator("TexScaleRight"); - command_connect_accelerator("TexShiftUp"); - command_connect_accelerator("TexShiftDown"); - command_connect_accelerator("TexShiftLeft"); - command_connect_accelerator("TexShiftRight"); -} - -void SelectNudge_registerShortcuts() -{ - command_connect_accelerator("MoveSelectionDOWN"); - command_connect_accelerator("MoveSelectionUP"); - //command_connect_accelerator("SelectNudgeLeft"); - //command_connect_accelerator("SelectNudgeRight"); - //command_connect_accelerator("SelectNudgeUp"); - //command_connect_accelerator("SelectNudgeDown"); -} - -void SnapToGrid_registerShortcuts() -{ - command_connect_accelerator("SnapToGrid"); -} - -void SelectByType_registerShortcuts() -{ - command_connect_accelerator("SelectAllOfType"); -} - -void SurfaceInspector_registerShortcuts() -{ - command_connect_accelerator("FitTexture"); -} - - -void register_shortcuts() -{ - PatchInspector_registerShortcuts(); - Patch_registerShortcuts(); - Grid_registerShortcuts(); - XYWnd_registerShortcuts(); - CamWnd_registerShortcuts(); - Manipulators_registerShortcuts(); - SurfaceInspector_registerShortcuts(); - TexdefNudge_registerShortcuts(); - SelectNudge_registerShortcuts(); - SnapToGrid_registerShortcuts(); - SelectByType_registerShortcuts(); -} - -void File_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_button(toolbar, "Open an existing map (CTRL + O)", "file_open.bmp", "OpenMap"); - toolbar_append_button(toolbar, "Save the active map (CTRL + S)", "file_save.bmp", "SaveMap"); -} - -void UndoRedo_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_button(toolbar, "Undo (CTRL + Z)", "undo.bmp", "Undo"); - toolbar_append_button(toolbar, "Redo (CTRL + Y)", "redo.bmp", "Redo"); -} - -void RotateFlip_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_button(toolbar, "x-axis Flip", "brush_flipx.bmp", "MirrorSelectionX"); - toolbar_append_button(toolbar, "x-axis Rotate", "brush_rotatex.bmp", "RotateSelectionX"); - toolbar_append_button(toolbar, "y-axis Flip", "brush_flipy.bmp", "MirrorSelectionY"); - toolbar_append_button(toolbar, "y-axis Rotate", "brush_rotatey.bmp", "RotateSelectionY"); - toolbar_append_button(toolbar, "z-axis Flip", "brush_flipz.bmp", "MirrorSelectionZ"); - toolbar_append_button(toolbar, "z-axis Rotate", "brush_rotatez.bmp", "RotateSelectionZ"); -} - -void Select_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_button(toolbar, "Select touching", "selection_selecttouching.bmp", "SelectTouching"); - toolbar_append_button(toolbar, "Select inside", "selection_selectinside.bmp", "SelectInside"); -} - -void CSG_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_button(toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.bmp", "CSGSubtract"); - toolbar_append_button(toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.bmp", "CSGMerge"); - toolbar_append_button(toolbar, "Hollow", "selection_makehollow.bmp", "CSGHollow"); -} - -void ComponentModes_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_toggle_button(toolbar, "Select Vertices (V)", "modify_vertices.bmp", "DragVertices"); - toolbar_append_toggle_button(toolbar, "Select Edges (E)", "modify_edges.bmp", "DragEdges"); - toolbar_append_toggle_button(toolbar, "Select Faces (F)", "modify_faces.bmp", "DragFaces"); -} - -void Clipper_constructToolbar(GtkToolbar* toolbar) -{ - - toolbar_append_toggle_button(toolbar, "Clipper (X)", "view_clipper.bmp", "ToggleClipper"); -} - -void XYWnd_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_button(toolbar, "Change views", "view_change.bmp", "NextView"); -} - -void Manipulators_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_toggle_button(toolbar, "Translate (W)", "select_mousetranslate.bmp", "MouseTranslate"); - toolbar_append_toggle_button(toolbar, "Rotate (R)", "select_mouserotate.bmp", "MouseRotate"); - toolbar_append_toggle_button(toolbar, "Scale", "select_mousescale.bmp", "MouseScale"); - toolbar_append_toggle_button(toolbar, "Resize (Q)", "select_mouseresize.bmp", "MouseDrag"); - - Clipper_constructToolbar(toolbar); -} - -GtkToolbar* create_main_toolbar(MainFrame::EViewStyle style) -{ - GtkToolbar* toolbar = GTK_TOOLBAR(gtk_toolbar_new()); - gtk_toolbar_set_orientation(toolbar, GTK_ORIENTATION_HORIZONTAL); - gtk_toolbar_set_style(toolbar, GTK_TOOLBAR_ICONS); - - gtk_widget_show(GTK_WIDGET(toolbar)); - - File_constructToolbar(toolbar); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - UndoRedo_constructToolbar(toolbar); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - RotateFlip_constructToolbar(toolbar); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - Select_constructToolbar(toolbar); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - CSG_constructToolbar(toolbar); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - ComponentModes_constructToolbar(toolbar); - - if(style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating) - { - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - XYWnd_constructToolbar(toolbar); - } - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - CamWnd_constructToolbar(toolbar); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - Manipulators_constructToolbar(toolbar); - - if (g_Layout_enablePatchToolbar.m_value) - { - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - Patch_constructToolbar(toolbar); - } - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - toolbar_append_toggle_button(toolbar, "Texture Lock (SHIFT +T)", "texture_lock.bmp", "TogTexLock"); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - - GtkButton* g_view_entities_button = toolbar_append_button(toolbar, "Entities (N)", "entities.bmp", "ToggleEntityInspector"); - GtkButton* g_view_console_button = toolbar_append_button(toolbar, "Console (O)", "console.bmp", "ToggleConsole"); - GtkButton* g_view_textures_button = toolbar_append_button(toolbar, "Texture Browser (T)", "texture_browser.bmp", "ToggleTextures"); - // TODO: call light inspector - //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.bmp", "ToggleLightInspector"); - - gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); - GtkButton* g_refresh_models_button = toolbar_append_button(toolbar, "Refresh Models", "refresh_models.bmp", "RefreshReferences"); - - - // disable the console and texture button in the regular layouts - if(style == MainFrame::eRegular || style == MainFrame::eRegularLeft) - { - gtk_widget_set_sensitive(GTK_WIDGET(g_view_console_button), FALSE); - gtk_widget_set_sensitive(GTK_WIDGET(g_view_textures_button), FALSE); - } - - return toolbar; -} - -GtkWidget* create_main_statusbar(GtkWidget *pStatusLabel[c_count_status]) -{ - GtkTable* table = GTK_TABLE(gtk_table_new(1, c_count_status, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - - { - GtkLabel* label = GTK_LABEL(gtk_label_new ("Label")); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - gtk_misc_set_padding(GTK_MISC(label), 4, 2); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach_defaults(table, GTK_WIDGET(label), 0, 1, 0, 1); - pStatusLabel[c_command_status] = GTK_WIDGET(label); - } - - for(int i = 1; i < c_count_status; ++i) - { - GtkFrame* frame = GTK_FRAME(gtk_frame_new(0)); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_table_attach_defaults(table, GTK_WIDGET(frame), i, i + 1, 0, 1); - gtk_frame_set_shadow_type(frame, GTK_SHADOW_IN); - - GtkLabel* label = GTK_LABEL(gtk_label_new ("Label")); - gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - gtk_misc_set_padding(GTK_MISC(label), 4, 2); - gtk_widget_show(GTK_WIDGET(label)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(label)); - pStatusLabel[i] = GTK_WIDGET(label); - } - - return GTK_WIDGET(table); -} - -#if 0 - - -WidgetFocusPrinter g_mainframeWidgetFocusPrinter("mainframe"); - -class WindowFocusPrinter -{ - const char* m_name; - - static gboolean frame_event(GtkWidget *widget, GdkEvent* event, WindowFocusPrinter* self) - { - globalOutputStream() << self->m_name << " frame_event\n"; - return FALSE; - } - static gboolean keys_changed(GtkWidget *widget, WindowFocusPrinter* self) - { - globalOutputStream() << self->m_name << " keys_changed\n"; - return FALSE; - } - static gboolean notify(GtkWindow* window, gpointer dummy, WindowFocusPrinter* self) - { - if(gtk_window_is_active(window)) - { - globalOutputStream() << self->m_name << " takes toplevel focus\n"; - } - else - { - globalOutputStream() << self->m_name << " loses toplevel focus\n"; - } - return FALSE; - } -public: - WindowFocusPrinter(const char* name) : m_name(name) - { - } - void connect(GtkWindow* toplevel_window) - { - g_signal_connect(G_OBJECT(toplevel_window), "notify::has_toplevel_focus", G_CALLBACK(notify), this); - g_signal_connect(G_OBJECT(toplevel_window), "notify::is_active", G_CALLBACK(notify), this); - g_signal_connect(G_OBJECT(toplevel_window), "keys_changed", G_CALLBACK(keys_changed), this); - g_signal_connect(G_OBJECT(toplevel_window), "frame_event", G_CALLBACK(frame_event), this); - } -}; - -WindowFocusPrinter g_mainframeFocusPrinter("mainframe"); - -#endif - -class MainWindowActive -{ - static gboolean notify(GtkWindow* window, gpointer dummy, MainWindowActive* self) - { - if(g_wait.m_window != 0 && gtk_window_is_active(window) && !GTK_WIDGET_VISIBLE(g_wait.m_window)) - { - gtk_widget_show(GTK_WIDGET(g_wait.m_window)); - } - - return FALSE; - } -public: - void connect(GtkWindow* toplevel_window) - { - g_signal_connect(G_OBJECT(toplevel_window), "notify::is-active", G_CALLBACK(notify), this); - } -}; - -MainWindowActive g_MainWindowActive; - -SignalHandlerId XYWindowDestroyed_connect(const SignalHandler& handler) -{ - return g_pParentWnd->GetXYWnd()->onDestroyed.connectFirst(handler); -} - -void XYWindowDestroyed_disconnect(SignalHandlerId id) -{ - g_pParentWnd->GetXYWnd()->onDestroyed.disconnect(id); -} - -MouseEventHandlerId XYWindowMouseDown_connect(const MouseEventHandler& handler) -{ - return g_pParentWnd->GetXYWnd()->onMouseDown.connectFirst(handler); -} - -void XYWindowMouseDown_disconnect(MouseEventHandlerId id) -{ - g_pParentWnd->GetXYWnd()->onMouseDown.disconnect(id); -} - -// ============================================================================= -// MainFrame class - -MainFrame* g_pParentWnd = 0; - -GtkWindow* MainFrame_getWindow() -{ - if(g_pParentWnd == 0) - { - return 0; - } - return g_pParentWnd->m_window; -} - -std::vector g_floating_windows; - -MainFrame::MainFrame() : m_window(0), m_idleRedrawStatusText(RedrawStatusTextCaller(*this)) -{ - m_pXYWnd = 0; - m_pCamWnd = 0; - m_pZWnd = 0; - m_pYZWnd = 0; - m_pXZWnd = 0; - m_pActiveXY = 0; - - for (int n = 0;n < c_count_status;n++) - { - m_pStatusLabel[n] = 0; - } - - m_bSleeping = false; - - Create(); -} - -MainFrame::~MainFrame() -{ - SaveWindowInfo(); - - gtk_widget_hide(GTK_WIDGET(m_window)); - - Shutdown(); - - for(std::vector::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i) - { - gtk_widget_destroy(*i); - } - - gtk_widget_destroy(GTK_WIDGET(m_window)); -} - -void MainFrame::SetActiveXY(XYWnd* p) -{ - if (m_pActiveXY) - m_pActiveXY->SetActive(false); - - m_pActiveXY = p; - - if (m_pActiveXY) - m_pActiveXY->SetActive(true); - -} - -void MainFrame::ReleaseContexts() -{ -#if 0 - if (m_pXYWnd) - m_pXYWnd->DestroyContext(); - if (m_pYZWnd) - m_pYZWnd->DestroyContext(); - if (m_pXZWnd) - m_pXZWnd->DestroyContext(); - if (m_pCamWnd) - m_pCamWnd->DestroyContext(); - if (m_pTexWnd) - m_pTexWnd->DestroyContext(); - if (m_pZWnd) - m_pZWnd->DestroyContext(); -#endif -} - -void MainFrame::CreateContexts() -{ -#if 0 - if (m_pCamWnd) - m_pCamWnd->CreateContext(); - if (m_pXYWnd) - m_pXYWnd->CreateContext(); - if (m_pYZWnd) - m_pYZWnd->CreateContext(); - if (m_pXZWnd) - m_pXZWnd->CreateContext(); - if (m_pTexWnd) - m_pTexWnd->CreateContext(); - if (m_pZWnd) - m_pZWnd->CreateContext(); -#endif -} - -#ifdef _DEBUG -//#define DBG_SLEEP -#endif - -void MainFrame::OnSleep() -{ -#if 0 - m_bSleeping ^= 1; - if (m_bSleeping) - { - // useful when trying to debug crashes in the sleep code - globalOutputStream() << "Going into sleep mode..\n"; - - globalOutputStream() << "Dispatching sleep msg..."; - DispatchRadiantMsg (RADIANT_SLEEP); - globalOutputStream() << "Done.\n"; - - gtk_window_iconify(m_window); - GlobalSelectionSystem().setSelectedAll(false); - - GlobalShaderCache().unrealise(); - Shaders_Free(); - GlobalOpenGL_debugAssertNoErrors(); - ScreenUpdates_Disable(); - - // release contexts - globalOutputStream() << "Releasing contexts..."; - ReleaseContexts(); - globalOutputStream() << "Done.\n"; - } - else - { - globalOutputStream() << "Waking up\n"; - - gtk_window_deiconify(m_window); - - // create contexts - globalOutputStream() << "Creating contexts..."; - CreateContexts(); - globalOutputStream() << "Done.\n"; - - globalOutputStream() << "Making current on camera..."; - m_pCamWnd->MakeCurrent(); - globalOutputStream() << "Done.\n"; - - globalOutputStream() << "Reloading shaders..."; - Shaders_Load(); - GlobalShaderCache().realise(); - globalOutputStream() << "Done.\n"; - - ScreenUpdates_Enable(); - - globalOutputStream() << "Dispatching wake msg..."; - DispatchRadiantMsg (RADIANT_WAKEUP); - globalOutputStream() << "Done\n"; - } -#endif -} - - -GtkWindow* create_splash() -{ - GtkWindow* window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL)); - gtk_window_set_decorated(window, FALSE); - gtk_window_set_resizable(window, FALSE); - gtk_window_set_modal(window, TRUE); - gtk_window_set_default_size(window, -1, -1); - gtk_window_set_position(window, GTK_WIN_POS_CENTER); - gtk_container_set_border_width(GTK_CONTAINER(window), 0); - - GtkImage* image = new_local_image("splash.bmp"); - gtk_widget_show(GTK_WIDGET(image)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(image)); - - gtk_widget_set_size_request(GTK_WIDGET(window), -1, -1); - gtk_widget_show(GTK_WIDGET(window)); - - return window; -} - -static GtkWindow *splash_screen = 0; - -void show_splash() -{ - splash_screen = create_splash(); - - process_gui(); -} - -void hide_splash() -{ - gtk_widget_destroy(GTK_WIDGET(splash_screen)); -} - -WindowPositionTracker g_posCamWnd; -WindowPositionTracker g_posXYWnd; -WindowPositionTracker g_posXZWnd; -WindowPositionTracker g_posYZWnd; - -static gint mainframe_delete (GtkWidget *widget, GdkEvent *event, gpointer data) -{ - if(ConfirmModified("Exit Radiant")) - { - gtk_main_quit(); - } - - return TRUE; -} - -void MainFrame::Create() -{ - GtkWindow* window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL)); - - GlobalWindowObservers_connectTopLevel(window); - - gtk_window_set_transient_for(splash_screen, window); - -#if !defined(WIN32) - { - GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask("bitmaps/icon.bmp"); - if(pixbuf != 0) - { - gtk_window_set_icon(window, pixbuf); - gdk_pixbuf_unref(pixbuf); - } - } -#endif - - gtk_widget_add_events(GTK_WIDGET(window), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK); - g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(mainframe_delete), this); - - m_position_tracker.connect(window); - -#if 0 - g_mainframeWidgetFocusPrinter.connect(window); - g_mainframeFocusPrinter.connect(window); -#endif - - g_MainWindowActive.connect(window); - - GetPlugInMgr().Init(GTK_WIDGET(window)); - - GtkWidget* vbox = gtk_vbox_new (FALSE, 0); - gtk_container_add(GTK_CONTAINER(window), vbox); - gtk_widget_show(vbox); - - global_accel_connect_window(window); - - m_nCurrentStyle = (EViewStyle)g_Layout_viewStyle.m_value; - - register_shortcuts(); - - GtkMenuBar* main_menu = create_main_menu(CurrentStyle()); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(main_menu), FALSE, FALSE, 0); - - GtkToolbar* main_toolbar = create_main_toolbar(CurrentStyle()); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(main_toolbar), FALSE, FALSE, 0); - - GtkToolbar* plugin_toolbar = create_plugin_toolbar(); - if (!g_Layout_enablePluginToolbar.m_value) - { - gtk_widget_hide(GTK_WIDGET(plugin_toolbar)); - } - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(plugin_toolbar), FALSE, FALSE, 0); - - GtkWidget* main_statusbar = create_main_statusbar(m_pStatusLabel); - gtk_box_pack_end(GTK_BOX(vbox), main_statusbar, FALSE, TRUE, 2); - - GroupDialog_constructWindow(window); - g_page_entity = GroupDialog_addPage("Entities", EntityInspector_constructWindow(GroupDialog_getWindow()), RawStringExportCaller("Entities")); - - if(FloatingGroupDialog()) - { - g_page_console = GroupDialog_addPage("Console", Console_constructWindow(GroupDialog_getWindow()), RawStringExportCaller("Console")); - } - -#ifdef WIN32 - if( g_multimon_globals.m_bStartOnPrimMon ) - { - PositionWindowOnPrimaryScreen(g_layout_globals.m_position); - window_set_position(window, g_layout_globals.m_position); - } - else -#endif - if(g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED) - { - gtk_window_maximize(window); - WindowPosition default_position(-1, -1, 640, 480); - window_set_position(window, default_position); - } - else - { - window_set_position(window, g_layout_globals.m_position); - } - - m_window = window; - - gtk_widget_show(GTK_WIDGET(window)); - - if (CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft) - { - { - GtkWidget* vsplit = gtk_vpaned_new(); - m_vSplit = vsplit; - gtk_box_pack_start(GTK_BOX(vbox), vsplit, TRUE, TRUE, 0); - gtk_widget_show (vsplit); - - // console - GtkWidget* console_window = Console_constructWindow(window); - gtk_paned_pack2(GTK_PANED(vsplit), console_window, FALSE, TRUE); - - { - GtkWidget* hsplit = gtk_hpaned_new(); - gtk_widget_show (hsplit); - m_hSplit = hsplit; - gtk_paned_add1(GTK_PANED(vsplit), hsplit); - - // xy - m_pXYWnd = new XYWnd(); - m_pXYWnd->SetViewType(XY); - GtkWidget* xy_window = GTK_WIDGET(create_framed_widget(m_pXYWnd->GetWidget())); - - { - GtkWidget* vsplit2 = gtk_vpaned_new(); - gtk_widget_show(vsplit2); - m_vSplit2 = vsplit2; - - if (CurrentStyle() == eRegular) - { - gtk_paned_add1(GTK_PANED(hsplit), xy_window); - gtk_paned_add2(GTK_PANED(hsplit), vsplit2); - } - else - { - gtk_paned_add1(GTK_PANED(hsplit), vsplit2); - gtk_paned_add2(GTK_PANED(hsplit), xy_window); - } - - - // camera - m_pCamWnd = NewCamWnd(); - GlobalCamera_setCamWnd(*m_pCamWnd); - CamWnd_setParent(*m_pCamWnd, window); - GtkFrame* camera_window = create_framed_widget(CamWnd_getWidget(*m_pCamWnd)); - - gtk_paned_add1(GTK_PANED(vsplit2), GTK_WIDGET(camera_window)); - - // textures - GtkFrame* texture_window = create_framed_widget(TextureBrowser_constructWindow(window)); - - gtk_paned_add2(GTK_PANED(vsplit2), GTK_WIDGET(texture_window)); - } - } - } - - gtk_paned_set_position(GTK_PANED(m_vSplit), g_layout_globals.nXYHeight); - - if (CurrentStyle() == eRegular) - { - gtk_paned_set_position(GTK_PANED(m_hSplit), g_layout_globals.nXYWidth); - } - else - { - gtk_paned_set_position(GTK_PANED(m_hSplit), g_layout_globals.nCamWidth); - } - - gtk_paned_set_position(GTK_PANED(m_vSplit2), g_layout_globals.nCamHeight); - } - else if (CurrentStyle() == eFloating) - { - { - GtkWindow* window = create_persistent_floating_window("Camera", m_window); - global_accel_connect_window(window); - g_posCamWnd.connect(window); - - gtk_widget_show(GTK_WIDGET(window)); - - m_pCamWnd = NewCamWnd(); - GlobalCamera_setCamWnd(*m_pCamWnd); - - { - GtkFrame* frame = create_framed_widget(CamWnd_getWidget(*m_pCamWnd)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); - } - CamWnd_setParent(*m_pCamWnd, window); - - g_floating_windows.push_back(GTK_WIDGET(window)); - } - - { - GtkWindow* window = create_persistent_floating_window(ViewType_getTitle(XY), m_window); - global_accel_connect_window(window); - g_posXYWnd.connect(window); - - m_pXYWnd = new XYWnd(); - m_pXYWnd->m_parent = window; - m_pXYWnd->SetViewType(XY); - - - { - GtkFrame* frame = create_framed_widget(m_pXYWnd->GetWidget()); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); - } - XY_Top_Shown_Construct(window); - - g_floating_windows.push_back(GTK_WIDGET(window)); - } - - { - GtkWindow* window = create_persistent_floating_window(ViewType_getTitle(XZ), m_window); - global_accel_connect_window(window); - g_posXZWnd.connect(window); - - m_pXZWnd = new XYWnd(); - m_pXZWnd->m_parent = window; - m_pXZWnd->SetViewType(XZ); - - { - GtkFrame* frame = create_framed_widget(m_pXZWnd->GetWidget()); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); - } - - XZ_Front_Shown_Construct(window); - - g_floating_windows.push_back(GTK_WIDGET(window)); - } - - { - GtkWindow* window = create_persistent_floating_window(ViewType_getTitle(YZ), m_window); - global_accel_connect_window(window); - g_posYZWnd.connect(window); - - m_pYZWnd = new XYWnd(); - m_pYZWnd->m_parent = window; - m_pYZWnd->SetViewType(YZ); - - { - GtkFrame* frame = create_framed_widget(m_pYZWnd->GetWidget()); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); - } - - YZ_Side_Shown_Construct(window); - - g_floating_windows.push_back(GTK_WIDGET(window)); - } - - { - GtkFrame* frame = create_framed_widget(TextureBrowser_constructWindow(GroupDialog_getWindow())); - g_page_textures = GroupDialog_addPage("Textures", GTK_WIDGET(frame), TextureBrowserExportTitleCaller()); - } - - GroupDialog_show(); - } - else // 4 way - { - m_pCamWnd = NewCamWnd(); - GlobalCamera_setCamWnd(*m_pCamWnd); - CamWnd_setParent(*m_pCamWnd, window); - - GtkWidget* camera = CamWnd_getWidget(*m_pCamWnd); - - m_pYZWnd = new XYWnd(); - m_pYZWnd->SetViewType(YZ); - - GtkWidget* yz = m_pYZWnd->GetWidget(); - - m_pXYWnd = new XYWnd(); - m_pXYWnd->SetViewType(XY); - - GtkWidget* xy = m_pXYWnd->GetWidget(); - - m_pXZWnd = new XYWnd(); - m_pXZWnd->SetViewType(XZ); - - GtkWidget* xz = m_pXZWnd->GetWidget(); - - GtkHPaned* split = create_split_views(camera, yz, xy, xz); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(split), TRUE, TRUE, 0); - - { - GtkFrame* frame = create_framed_widget(TextureBrowser_constructWindow(window)); - g_page_textures = GroupDialog_addPage("Textures", GTK_WIDGET(frame), TextureBrowserExportTitleCaller()); - } - } - - EntityList_constructWindow(window); - PreferencesDialog_constructWindow(window); - FindTextureDialog_constructWindow(window); - SurfaceInspector_constructWindow(window); - PatchInspector_constructWindow(window); - - SetActiveXY(m_pXYWnd); - - AddGridChangeCallback(SetGridStatusCaller(*this)); - AddGridChangeCallback(ReferenceCaller(*this)); - - g_defaultToolMode = DragMode; - g_defaultToolMode(); - SetStatusText(m_command_status, c_TranslateMode_status); - - EverySecondTimer_enable(); - - //GlobalShortcuts_reportUnregistered(); -} - -void MainFrame::SaveWindowInfo() -{ - if (!FloatingGroupDialog()) - { - g_layout_globals.nXYHeight = gtk_paned_get_position(GTK_PANED(m_vSplit)); - - if(CurrentStyle() != eRegular) - { - g_layout_globals.nCamWidth = gtk_paned_get_position(GTK_PANED(m_hSplit)); - } - else - { - g_layout_globals.nXYWidth = gtk_paned_get_position(GTK_PANED(m_hSplit)); - } - - g_layout_globals.nCamHeight = gtk_paned_get_position(GTK_PANED(m_vSplit2)); - } - - g_layout_globals.m_position = m_position_tracker.getPosition(); - - g_layout_globals.nState = gdk_window_get_state(GTK_WIDGET(m_window)->window); -} - -void MainFrame::Shutdown() -{ - EverySecondTimer_disable(); - - EntityList_destroyWindow(); - - delete m_pXYWnd; - m_pXYWnd = 0; - delete m_pYZWnd; - m_pYZWnd = 0; - delete m_pXZWnd; - m_pXZWnd = 0; - - TextureBrowser_destroyWindow(); - - DeleteCamWnd(m_pCamWnd); - m_pCamWnd = 0; - - PreferencesDialog_destroyWindow(); - SurfaceInspector_destroyWindow(); - FindTextureDialog_destroyWindow(); - PatchInspector_destroyWindow(); - - g_DbgDlg.destroyWindow(); - - // destroying group-dialog last because it may contain texture-browser - GroupDialog_destroyWindow(); -} - -void MainFrame::RedrawStatusText() -{ - gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_command_status]), m_command_status.c_str()); - gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_position_status]), m_position_status.c_str()); - gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_brushcount_status]), m_brushcount_status.c_str()); - gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_texture_status]), m_texture_status.c_str()); - gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_grid_status]), m_grid_status.c_str()); -} - -void MainFrame::UpdateStatusText() -{ - m_idleRedrawStatusText.queueDraw(); -} - -void MainFrame::SetStatusText(CopiedString& status_text, const char* pText) -{ - status_text = pText; - UpdateStatusText(); -} - -void Sys_Status(const char* status) -{ - if(g_pParentWnd != 0) - { - g_pParentWnd->SetStatusText (g_pParentWnd->m_command_status, status); - } -} - -int getRotateIncrement() -{ - return static_cast(g_si_globals.rotate); -} - -int getFarClipDistance() -{ - return g_camwindow_globals.m_nCubicScale; -} - -float (*GridStatus_getGridSize)() = GetGridSize; -int (*GridStatus_getRotateIncrement)() = getRotateIncrement; -int (*GridStatus_getFarClipDistance)() = getFarClipDistance; -bool (*GridStatus_getTextureLockEnabled)(); - -void MainFrame::SetGridStatus() -{ - StringOutputStream status(64); - const char* lock = (GridStatus_getTextureLockEnabled()) ? "ON" : "OFF"; - status << (GetSnapGridSize() > 0 ? "G:" : "g:") << GridStatus_getGridSize() - << " R:" << GridStatus_getRotateIncrement() - << " C:" << GridStatus_getFarClipDistance() - << " L:" << lock; - SetStatusText(m_grid_status, status.c_str()); -} - -void GridStatus_onTextureLockEnabledChanged() -{ - if(g_pParentWnd != 0) - { - g_pParentWnd->SetGridStatus(); - } -} - -void GlobalGL_sharedContextCreated() -{ - GLFont *g_font = NULL; - - // report OpenGL information - globalOutputStream() << "GL_VENDOR: " << reinterpret_cast(glGetString (GL_VENDOR)) << "\n"; - globalOutputStream() << "GL_RENDERER: " << reinterpret_cast(glGetString (GL_RENDERER)) << "\n"; - globalOutputStream() << "GL_VERSION: " << reinterpret_cast(glGetString (GL_VERSION)) << "\n"; - globalOutputStream() << "GL_EXTENSIONS: " << reinterpret_cast(glGetString (GL_EXTENSIONS)) << "\n"; - - QGL_sharedContextCreated(GlobalOpenGL()); - - ShaderCache_extensionsInitialised(); - - GlobalShaderCache().realise(); - Textures_Realise(); - -#ifdef WIN32 - /* win32 is dodgy here, just use courier new then */ - g_font = glfont_create("arial 9"); -#else - GtkSettings *settings = gtk_settings_get_default(); - gchar *fontname; - g_object_get(settings, "gtk-font-name", &fontname, NULL); - g_font = glfont_create(fontname); -#endif - - GlobalOpenGL().m_font = g_font; -} - -void GlobalGL_sharedContextDestroyed() -{ - Textures_Unrealise(); - GlobalShaderCache().unrealise(); - - QGL_sharedContextDestroyed(GlobalOpenGL()); -} - - -void Layout_constructPreferences(PreferencesPage& page) -{ - { - const char* layouts[] = { "window1.bmp", "window2.bmp", "window3.bmp", "window4.bmp" }; - page.appendRadioIcons( - "Window Layout", - STRING_ARRAY_RANGE(layouts), - LatchedIntImportCaller(g_Layout_viewStyle), - IntExportCaller(g_Layout_viewStyle.m_latched) - ); - } - page.appendCheckBox( - "", "Detachable Menus", - LatchedBoolImportCaller(g_Layout_enableDetachableMenus), - BoolExportCaller(g_Layout_enableDetachableMenus.m_latched) - ); - if (!string_empty(g_pGameDescription->getKeyValue("no_patch"))) - { - page.appendCheckBox( - "", "Patch Toolbar", - LatchedBoolImportCaller(g_Layout_enablePatchToolbar), - BoolExportCaller(g_Layout_enablePatchToolbar.m_latched) - ); - } - page.appendCheckBox( - "", "Plugin Toolbar", - LatchedBoolImportCaller(g_Layout_enablePluginToolbar), - BoolExportCaller(g_Layout_enablePluginToolbar.m_latched) - ); -} - -void Layout_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Layout", "Layout Preferences")); - Layout_constructPreferences(page); -} - -void Layout_registerPreferencesPage() -{ - PreferencesDialog_addInterfacePage(FreeCaller1()); -} - - -#include "preferencesystem.h" -#include "stringio.h" - -void MainFrame_Construct() -{ - GlobalCommands_insert("OpenManual", FreeCaller(), Accelerator(GDK_F1)); - - GlobalCommands_insert("Sleep", FreeCaller(), Accelerator('P', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("NewMap", FreeCaller()); - GlobalCommands_insert("OpenMap", FreeCaller(), Accelerator('O', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("ImportMap", FreeCaller()); - GlobalCommands_insert("SaveMap", FreeCaller(), Accelerator('S', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("SaveMapAs", FreeCaller()); - GlobalCommands_insert("SaveSelected", FreeCaller()); - GlobalCommands_insert("SaveRegion", FreeCaller()); - GlobalCommands_insert("RefreshReferences", FreeCaller()); - GlobalCommands_insert("ProjectSettings", FreeCaller()); - GlobalCommands_insert("CheckForUpdate", FreeCaller()); - GlobalCommands_insert("Exit", FreeCaller()); - - GlobalCommands_insert("Undo", FreeCaller(), Accelerator('Z', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Redo", FreeCaller(), Accelerator('Y', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Copy", FreeCaller(), Accelerator('C', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("Paste", FreeCaller(), Accelerator('V', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("PasteToCamera", FreeCaller(), Accelerator('V', (GdkModifierType)GDK_MOD1_MASK)); - GlobalCommands_insert("CloneSelection", FreeCaller(), Accelerator(GDK_space)); - GlobalCommands_insert("CloneSelectionAndMakeUnique", FreeCaller(), Accelerator(GDK_space, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("DeleteSelection", FreeCaller(), Accelerator(GDK_BackSpace)); - GlobalCommands_insert("ParentSelection", FreeCaller()); - GlobalCommands_insert("UnSelectSelection", FreeCaller(), Accelerator(GDK_Escape)); - GlobalCommands_insert("InvertSelection", FreeCaller(), Accelerator('I')); - GlobalCommands_insert("SelectInside", FreeCaller()); - GlobalCommands_insert("SelectTouching", FreeCaller()); - GlobalCommands_insert("ExpandSelectionToEntities", FreeCaller(), Accelerator('E', (GdkModifierType)(GDK_MOD1_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("Preferences", FreeCaller(), Accelerator('P')); - - GlobalCommands_insert("ToggleConsole", FreeCaller(), Accelerator('O')); - GlobalCommands_insert("ToggleEntityInspector", FreeCaller(), Accelerator('N')); - GlobalCommands_insert("EntityList", FreeCaller(), Accelerator('L')); - - GlobalCommands_insert("ShowHidden", FreeCaller(), Accelerator('H', (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("HideSelected", FreeCaller(), Accelerator('H')); - - GlobalToggles_insert("DragVertices", FreeCaller(), ToggleItem::AddCallbackCaller(g_vertexMode_button), Accelerator('V')); - GlobalToggles_insert("DragEdges", FreeCaller(), ToggleItem::AddCallbackCaller(g_edgeMode_button), Accelerator('E')); - GlobalToggles_insert("DragFaces", FreeCaller(), ToggleItem::AddCallbackCaller(g_faceMode_button), Accelerator('F')); - - GlobalCommands_insert("MirrorSelectionX", FreeCaller()); - GlobalCommands_insert("RotateSelectionX", FreeCaller()); - GlobalCommands_insert("MirrorSelectionY", FreeCaller()); - GlobalCommands_insert("RotateSelectionY", FreeCaller()); - GlobalCommands_insert("MirrorSelectionZ", FreeCaller()); - GlobalCommands_insert("RotateSelectionZ", FreeCaller()); - - GlobalCommands_insert("ArbitraryRotation", FreeCaller()); - GlobalCommands_insert("ArbitraryScale", FreeCaller()); - - GlobalCommands_insert("BuildMenuCustomize", FreeCaller()); - - GlobalCommands_insert("FindBrush", FreeCaller()); - - GlobalCommands_insert("MapInfo", FreeCaller(), Accelerator('M')); - - - GlobalToggles_insert("ToggleClipper", FreeCaller(), ToggleItem::AddCallbackCaller(g_clipper_button), Accelerator('X')); - - GlobalToggles_insert("MouseTranslate", FreeCaller(), ToggleItem::AddCallbackCaller(g_translatemode_button), Accelerator('W')); - GlobalToggles_insert("MouseRotate", FreeCaller(), ToggleItem::AddCallbackCaller(g_rotatemode_button), Accelerator('R')); - GlobalToggles_insert("MouseScale", FreeCaller(), ToggleItem::AddCallbackCaller(g_scalemode_button)); - GlobalToggles_insert("MouseDrag", FreeCaller(), ToggleItem::AddCallbackCaller(g_dragmode_button), Accelerator('Q')); - - GlobalCommands_insert("ColorSchemeOriginal", FreeCaller()); - GlobalCommands_insert("ColorSchemeQER", FreeCaller()); - GlobalCommands_insert("ColorSchemeBlackAndGreen", FreeCaller()); - GlobalCommands_insert("ColorSchemeYdnar", FreeCaller()); - GlobalCommands_insert("ChooseTextureBackgroundColor", makeCallback(g_ColoursMenu.m_textureback)); - GlobalCommands_insert("ChooseGridBackgroundColor", makeCallback(g_ColoursMenu.m_xyback)); - GlobalCommands_insert("ChooseGridMajorColor", makeCallback(g_ColoursMenu.m_gridmajor)); - GlobalCommands_insert("ChooseGridMinorColor", makeCallback(g_ColoursMenu.m_gridminor)); - GlobalCommands_insert("ChooseSmallGridMajorColor", makeCallback(g_ColoursMenu.m_gridmajor_alt)); - GlobalCommands_insert("ChooseSmallGridMinorColor", makeCallback(g_ColoursMenu.m_gridminor_alt)); - GlobalCommands_insert("ChooseGridTextColor", makeCallback(g_ColoursMenu.m_gridtext)); - GlobalCommands_insert("ChooseGridBlockColor", makeCallback(g_ColoursMenu.m_gridblock)); - GlobalCommands_insert("ChooseBrushColor", makeCallback(g_ColoursMenu.m_brush)); - GlobalCommands_insert("ChooseCameraBackgroundColor", makeCallback(g_ColoursMenu.m_cameraback)); - GlobalCommands_insert("ChooseSelectedBrushColor", makeCallback(g_ColoursMenu.m_selectedbrush)); - GlobalCommands_insert("ChooseCameraSelectedBrushColor", makeCallback(g_ColoursMenu.m_selectedbrush3d)); - GlobalCommands_insert("ChooseClipperColor", makeCallback(g_ColoursMenu.m_clipper)); - GlobalCommands_insert("ChooseOrthoViewNameColor", makeCallback(g_ColoursMenu.m_viewname)); - - - GlobalCommands_insert("CSGSubtract", FreeCaller(), Accelerator('U', (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("CSGMerge", FreeCaller(), Accelerator('U', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("CSGHollow", FreeCaller()); - - Grid_registerCommands(); - - GlobalCommands_insert("SnapToGrid", FreeCaller(), Accelerator('G', (GdkModifierType)GDK_CONTROL_MASK)); - - GlobalCommands_insert("SelectAllOfType", FreeCaller(), Accelerator('A', (GdkModifierType)GDK_SHIFT_MASK)); - - GlobalCommands_insert("TexRotateClock", FreeCaller(), Accelerator(GDK_Next, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("TexRotateCounter", FreeCaller(), Accelerator(GDK_Prior, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("TexScaleUp", FreeCaller(), Accelerator(GDK_Up, (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("TexScaleDown", FreeCaller(), Accelerator(GDK_Down, (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("TexScaleLeft", FreeCaller(), Accelerator(GDK_Left, (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("TexScaleRight", FreeCaller(), Accelerator(GDK_Right, (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("TexShiftUp", FreeCaller(), Accelerator(GDK_Up, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("TexShiftDown", FreeCaller(), Accelerator(GDK_Down, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("TexShiftLeft", FreeCaller(), Accelerator(GDK_Left, (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("TexShiftRight", FreeCaller(), Accelerator(GDK_Right, (GdkModifierType)GDK_SHIFT_MASK)); - - GlobalCommands_insert("MoveSelectionDOWN", FreeCaller(), Accelerator(GDK_KP_Subtract)); - GlobalCommands_insert("MoveSelectionUP", FreeCaller(), Accelerator(GDK_KP_Add)); - - GlobalCommands_insert("SelectNudgeLeft", FreeCaller(), Accelerator(GDK_Left, (GdkModifierType)GDK_MOD1_MASK)); - GlobalCommands_insert("SelectNudgeRight", FreeCaller(), Accelerator(GDK_Right, (GdkModifierType)GDK_MOD1_MASK)); - GlobalCommands_insert("SelectNudgeUp", FreeCaller(), Accelerator(GDK_Up, (GdkModifierType)GDK_MOD1_MASK)); - GlobalCommands_insert("SelectNudgeDown", FreeCaller(), Accelerator(GDK_Down, (GdkModifierType)GDK_MOD1_MASK)); - - Patch_registerCommands(); - XYShow_registerCommands(); - - typedef FreeCaller1 ComponentModeSelectionChangedCaller; - GlobalSelectionSystem().addSelectionChangeCallback(ComponentModeSelectionChangedCaller()); - - GlobalPreferenceSystem().registerPreference("DetachableMenus", BoolImportStringCaller(g_Layout_enableDetachableMenus.m_latched), BoolExportStringCaller(g_Layout_enableDetachableMenus.m_latched)); - GlobalPreferenceSystem().registerPreference("PatchToolBar", BoolImportStringCaller(g_Layout_enablePatchToolbar.m_latched), BoolExportStringCaller(g_Layout_enablePatchToolbar.m_latched)); - GlobalPreferenceSystem().registerPreference("PluginToolBar", BoolImportStringCaller(g_Layout_enablePluginToolbar.m_latched), BoolExportStringCaller(g_Layout_enablePluginToolbar.m_latched)); - GlobalPreferenceSystem().registerPreference("QE4StyleWindows", IntImportStringCaller(g_Layout_viewStyle.m_latched), IntExportStringCaller(g_Layout_viewStyle.m_latched)); - GlobalPreferenceSystem().registerPreference("XYHeight", IntImportStringCaller(g_layout_globals.nXYHeight), IntExportStringCaller(g_layout_globals.nXYHeight)); - GlobalPreferenceSystem().registerPreference("XYWidth", IntImportStringCaller(g_layout_globals.nXYWidth), IntExportStringCaller(g_layout_globals.nXYWidth)); - GlobalPreferenceSystem().registerPreference("CamWidth", IntImportStringCaller(g_layout_globals.nCamWidth), IntExportStringCaller(g_layout_globals.nCamWidth)); - GlobalPreferenceSystem().registerPreference("CamHeight", IntImportStringCaller(g_layout_globals.nCamHeight), IntExportStringCaller(g_layout_globals.nCamHeight)); - - GlobalPreferenceSystem().registerPreference("State", IntImportStringCaller(g_layout_globals.nState), IntExportStringCaller(g_layout_globals.nState)); - GlobalPreferenceSystem().registerPreference("PositionX", IntImportStringCaller(g_layout_globals.m_position.x), IntExportStringCaller(g_layout_globals.m_position.x)); - GlobalPreferenceSystem().registerPreference("PositionY", IntImportStringCaller(g_layout_globals.m_position.y), IntExportStringCaller(g_layout_globals.m_position.y)); - GlobalPreferenceSystem().registerPreference("Width", IntImportStringCaller(g_layout_globals.m_position.w), IntExportStringCaller(g_layout_globals.m_position.w)); - GlobalPreferenceSystem().registerPreference("Height", IntImportStringCaller(g_layout_globals.m_position.h), IntExportStringCaller(g_layout_globals.m_position.h)); - - GlobalPreferenceSystem().registerPreference("CamWnd", WindowPositionTrackerImportStringCaller(g_posCamWnd), WindowPositionTrackerExportStringCaller(g_posCamWnd)); - GlobalPreferenceSystem().registerPreference("XYWnd", WindowPositionTrackerImportStringCaller(g_posXYWnd), WindowPositionTrackerExportStringCaller(g_posXYWnd)); - GlobalPreferenceSystem().registerPreference("YZWnd", WindowPositionTrackerImportStringCaller(g_posYZWnd), WindowPositionTrackerExportStringCaller(g_posYZWnd)); - GlobalPreferenceSystem().registerPreference("XZWnd", WindowPositionTrackerImportStringCaller(g_posXZWnd), WindowPositionTrackerExportStringCaller(g_posXZWnd)); - - { - const char* ENGINEPATH_ATTRIBUTE = -#if defined(WIN32) - "enginepath_win32" -#elif defined(__linux__) || defined (__FreeBSD__) - "enginepath_linux" -#elif defined(__APPLE__) - "enginepath_macos" -#else -#error "unknown platform" -#endif - ; - StringOutputStream path(256); - path << DirectoryCleaned(g_pGameDescription->getRequiredKeyValue(ENGINEPATH_ATTRIBUTE)); - g_strEnginePath = path.c_str(); - } - - GlobalPreferenceSystem().registerPreference("EnginePath", CopiedStringImportStringCaller(g_strEnginePath), CopiedStringExportStringCaller(g_strEnginePath)); - - g_Layout_viewStyle.useLatched(); - g_Layout_enableDetachableMenus.useLatched(); - g_Layout_enablePatchToolbar.useLatched(); - g_Layout_enablePluginToolbar.useLatched(); - - Layout_registerPreferencesPage(); - Paths_registerPreferencesPage(); - - g_brushCount.setCountChangedCallback(FreeCaller()); - g_entityCount.setCountChangedCallback(FreeCaller()); - GlobalEntityCreator().setCounter(&g_entityCount); - - GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated; - GLWidget_sharedContextDestroyed = GlobalGL_sharedContextDestroyed; - - GlobalEntityClassManager().attach(g_WorldspawnColourEntityClassObserver); -} - -void MainFrame_Destroy() -{ - GlobalEntityClassManager().detach(g_WorldspawnColourEntityClassObserver); - - GlobalEntityCreator().setCounter(0); - g_entityCount.setCountChangedCallback(Callback()); - g_brushCount.setCountChangedCallback(Callback()); -} - - -void GLWindow_Construct() -{ - GlobalPreferenceSystem().registerPreference("MouseButtons", IntImportStringCaller(g_glwindow_globals.m_nMouseType), IntExportStringCaller(g_glwindow_globals.m_nMouseType)); -} - -void GLWindow_Destroy() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/mainframe.h b/misc/mediasource/extra/netradiant-src/radiant/mainframe.h deleted file mode 100644 index 5997abd3..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/mainframe.h +++ /dev/null @@ -1,286 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_MAINFRAME_H) -#define INCLUDED_MAINFRAME_H - -#include "gtkutil/window.h" -#include "gtkutil/idledraw.h" -#include "gtkutil/widget.h" -#include "string/string.h" - -#include "qerplugin.h" - -class IPlugIn; -class IToolbarButton; - -class XYWnd; -class CamWnd; -class ZWnd; - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; - -const int c_command_status = 0; -const int c_position_status = 1; -const int c_brushcount_status = 2; -const int c_texture_status = 3; -const int c_grid_status = 4; -const int c_count_status = 5; - -class MainFrame -{ -public: - enum EViewStyle - { - eRegular = 0, - eFloating = 1, - eSplit = 2, - eRegularLeft = 3, - }; - - MainFrame(); - ~MainFrame(); - - GtkWindow* m_window; - - CopiedString m_command_status; - CopiedString m_position_status; - CopiedString m_brushcount_status; - CopiedString m_texture_status; - CopiedString m_grid_status; -private: - - void Create(); - void SaveWindowInfo(); - void Shutdown(); - - GtkWidget* m_vSplit; - GtkWidget* m_hSplit; - GtkWidget* m_vSplit2; - - XYWnd* m_pXYWnd; - XYWnd* m_pYZWnd; - XYWnd* m_pXZWnd; - CamWnd* m_pCamWnd; - ZWnd* m_pZWnd; - XYWnd* m_pActiveXY; - - bool m_bSleeping; - - GtkWidget *m_pStatusLabel[c_count_status]; - - - EViewStyle m_nCurrentStyle; - WindowPositionTracker m_position_tracker; - - IdleDraw m_idleRedrawStatusText; - -public: - - bool IsSleeping() - { - return m_bSleeping; - } - void OnSleep(); - - void SetStatusText(CopiedString& status_text, const char* pText); - void UpdateStatusText(); - void RedrawStatusText(); - typedef MemberCaller RedrawStatusTextCaller; - - void SetGridStatus(); - typedef MemberCaller SetGridStatusCaller; - - void SetActiveXY(XYWnd* p); - XYWnd* ActiveXY() - { - return m_pActiveXY; - }; - XYWnd* GetXYWnd() - { - return m_pXYWnd; - } - XYWnd* GetXZWnd() - { - return m_pXZWnd; - } - XYWnd* GetYZWnd() - { - return m_pYZWnd; - } - ZWnd* GetZWnd() - { - return m_pZWnd; - } - CamWnd* GetCamWnd() - { - return m_pCamWnd; - } - - void ReleaseContexts(); - void CreateContexts(); - - EViewStyle CurrentStyle() - { - return m_nCurrentStyle; - }; - bool FloatingGroupDialog() - { - return CurrentStyle() == eFloating || CurrentStyle() == eSplit; - }; -}; - -extern MainFrame* g_pParentWnd; - -GtkWindow* MainFrame_getWindow(); - -enum EMouseButtonMode -{ - ETwoButton = 0, - EThreeButton = 1, -}; - -struct glwindow_globals_t -{ - int m_nMouseType; - - glwindow_globals_t() : - m_nMouseType(EThreeButton) - { - } -}; - -void GLWindow_Construct(); -void GLWindow_Destroy(); - -extern glwindow_globals_t g_glwindow_globals; -template -class LatchedValue; -typedef LatchedValue LatchedBool; -extern LatchedBool g_Layout_enableDetachableMenus; - -void deleteSelection(); - - -void Sys_Status(const char* status); - - -void ScreenUpdates_Disable(const char* message, const char* title); -void ScreenUpdates_Enable(); -bool ScreenUpdates_Enabled(); -void ScreenUpdates_process(); - -class ScopeDisableScreenUpdates -{ -public: - ScopeDisableScreenUpdates(const char* message, const char* title) - { - ScreenUpdates_Disable(message, title); - } - ~ScopeDisableScreenUpdates() - { - ScreenUpdates_Enable(); - } -}; - - -void EnginePath_Realise(); -void EnginePath_Unrealise(); - -class ModuleObserver; - -void Radiant_attachEnginePathObserver(ModuleObserver& observer); -void Radiant_detachEnginePathObserver(ModuleObserver& observer); - -void Radiant_attachGameToolsPathObserver(ModuleObserver& observer); -void Radiant_detachGameToolsPathObserver(ModuleObserver& observer); - -extern CopiedString g_strEnginePath; -void EnginePath_verify(); -const char* EnginePath_get(); -const char* QERApp_GetGamePath(); - -extern CopiedString g_strAppPath; -const char* AppPath_get(); - -extern CopiedString g_strSettingsPath; -const char* SettingsPath_get(); - -const char* LocalRcPath_get(void); - -const char* const g_pluginsDir = "plugins/"; ///< name of plugins directory, always sub-directory of toolspath -const char* const g_modulesDir = "modules/"; ///< name of modules directory, always sub-directory of toolspath - -extern CopiedString g_strGameToolsPath; -const char* GameToolsPath_get(); - -void Radiant_Initialise(); -void Radiant_Shutdown(); - -void SaveMapAs(); - - -void XY_UpdateAllWindows(); -void UpdateAllWindows(); - - -void ClipperChangeNotify(); - -void DefaultMode(); - -const char* basegame_get(); -const char* gamename_get(); -void gamename_set(const char* gamename); -void Radiant_attachGameNameObserver(ModuleObserver& observer); -void Radiant_detachGameNameObserver(ModuleObserver& observer); -const char* gamemode_get(); -void gamemode_set(const char* gamemode); -void Radiant_attachGameModeObserver(ModuleObserver& observer); -void Radiant_detachGameModeObserver(ModuleObserver& observer); - - - -void VFS_Construct(); -void VFS_Destroy(); - -void HomePaths_Construct(); -void HomePaths_Destroy(); -void Radiant_attachHomePathsObserver(ModuleObserver& observer); -void Radiant_detachHomePathsObserver(ModuleObserver& observer); - - -void MainFrame_Construct(); -void MainFrame_Destroy(); - - -extern float (*GridStatus_getGridSize)(); -extern int (*GridStatus_getRotateIncrement)(); -extern int (*GridStatus_getFarClipDistance)(); -extern bool (*GridStatus_getTextureLockEnabled)(); -void GridStatus_onTextureLockEnabledChanged(); - -SignalHandlerId XYWindowDestroyed_connect(const SignalHandler& handler); -void XYWindowDestroyed_disconnect(SignalHandlerId id); -MouseEventHandlerId XYWindowMouseDown_connect(const MouseEventHandler& handler); -void XYWindowMouseDown_disconnect(MouseEventHandlerId id); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/map.cpp b/misc/mediasource/extra/netradiant-src/radiant/map.cpp deleted file mode 100644 index 57245990..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/map.cpp +++ /dev/null @@ -1,2415 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "map.h" - -#include "debugging/debugging.h" - -#include "imap.h" -MapModules& ReferenceAPI_getMapModules(); -#include "iselection.h" -#include "iundo.h" -#include "ibrush.h" -#include "ifilter.h" -#include "ireference.h" -#include "ifiletypes.h" -#include "ieclass.h" -#include "irender.h" -#include "ientity.h" -#include "editable.h" -#include "ifilesystem.h" -#include "namespace.h" -#include "moduleobserver.h" - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "scenelib.h" -#include "transformlib.h" -#include "selectionlib.h" -#include "instancelib.h" -#include "traverselib.h" -#include "maplib.h" -#include "eclasslib.h" -#include "cmdlib.h" -#include "stream/textfilestream.h" -#include "os/path.h" -#include "uniquenames.h" -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" -#include "stream/stringstream.h" -#include "signal/signal.h" - -#include "gtkutil/filechooser.h" -#include "timer.h" -#include "select.h" -#include "plugin.h" -#include "filetypes.h" -#include "gtkdlgs.h" -#include "entityinspector.h" -#include "points.h" -#include "qe3.h" -#include "camwindow.h" -#include "xywindow.h" -#include "mainframe.h" -#include "preferences.h" -#include "referencecache.h" -#include "mru.h" -#include "commands.h" -#include "autosave.h" -#include "brushmodule.h" -#include "brush.h" - -class NameObserver -{ - UniqueNames& m_names; - CopiedString m_name; - - void construct() - { - if(!empty()) - { - //globalOutputStream() << "construct " << makeQuoted(c_str()) << "\n"; - m_names.insert(name_read(c_str())); - } - } - void destroy() - { - if(!empty()) - { - //globalOutputStream() << "destroy " << makeQuoted(c_str()) << "\n"; - m_names.erase(name_read(c_str())); - } - } - - NameObserver& operator=(const NameObserver& other); -public: - NameObserver(UniqueNames& names) : m_names(names) - { - construct(); - } - NameObserver(const NameObserver& other) : m_names(other.m_names), m_name(other.m_name) - { - construct(); - } - ~NameObserver() - { - destroy(); - } - bool empty() const - { - return string_empty(c_str()); - } - const char* c_str() const - { - return m_name.c_str(); - } - void nameChanged(const char* name) - { - destroy(); - m_name = name; - construct(); - } - typedef MemberCaller1 NameChangedCaller; -}; - -class BasicNamespace : public Namespace -{ - typedef std::map Names; - Names m_names; - UniqueNames m_uniqueNames; -public: - ~BasicNamespace() - { - ASSERT_MESSAGE(m_names.empty(), "namespace: names still registered at shutdown"); - } - void attach(const NameCallback& setName, const NameCallbackCallback& attachObserver) - { - std::pair result = m_names.insert(Names::value_type(setName, m_uniqueNames)); - ASSERT_MESSAGE(result.second, "cannot attach name"); - attachObserver(NameObserver::NameChangedCaller((*result.first).second)); - //globalOutputStream() << "attach: " << reinterpret_cast(setName) << "\n"; - } - void detach(const NameCallback& setName, const NameCallbackCallback& detachObserver) - { - Names::iterator i = m_names.find(setName); - ASSERT_MESSAGE(i != m_names.end(), "cannot detach name"); - //globalOutputStream() << "detach: " << reinterpret_cast(setName) << "\n"; - detachObserver(NameObserver::NameChangedCaller((*i).second)); - m_names.erase(i); - } - - void makeUnique(const char* name, const NameCallback& setName) const - { - char buffer[1024]; - name_write(buffer, m_uniqueNames.make_unique(name_read(name))); - setName(buffer); - } - - void mergeNames(const BasicNamespace& other) const - { - typedef std::list SetNameCallbacks; - typedef std::map NameGroups; - NameGroups groups; - - UniqueNames uniqueNames(other.m_uniqueNames); - - for(Names::const_iterator i = m_names.begin(); i != m_names.end(); ++i) - { - groups[(*i).second.c_str()].push_back((*i).first); - } - - for(NameGroups::iterator i = groups.begin(); i != groups.end(); ++i) - { - name_t uniqueName(uniqueNames.make_unique(name_read((*i).first.c_str()))); - uniqueNames.insert(uniqueName); - - char buffer[1024]; - name_write(buffer, uniqueName); - - //globalOutputStream() << "renaming " << makeQuoted((*i).first.c_str()) << " to " << makeQuoted(buffer) << "\n"; - - SetNameCallbacks& setNameCallbacks = (*i).second; - - for(SetNameCallbacks::const_iterator j = setNameCallbacks.begin(); j != setNameCallbacks.end(); ++j) - { - (*j)(buffer); - } - } - } -}; - -BasicNamespace g_defaultNamespace; -BasicNamespace g_cloneNamespace; - -class NamespaceAPI -{ - Namespace* m_namespace; -public: - typedef Namespace Type; - STRING_CONSTANT(Name, "*"); - - NamespaceAPI() - { - m_namespace = &g_defaultNamespace; - } - Namespace* getTable() - { - return m_namespace; - } -}; - -typedef SingletonModule NamespaceModule; -typedef Static StaticNamespaceModule; -StaticRegisterModule staticRegisterDefaultNamespace(StaticNamespaceModule::instance()); - - -std::list g_cloned; - -inline Namespaced* Node_getNamespaced(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -void Node_gatherNamespaced(scene::Node& node) -{ - Namespaced* namespaced = Node_getNamespaced(node); - if(namespaced != 0) - { - g_cloned.push_back(namespaced); - } -} - -class GatherNamespaced : public scene::Traversable::Walker -{ -public: - bool pre(scene::Node& node) const - { - Node_gatherNamespaced(node); - return true; - } -}; - -void Map_gatherNamespaced(scene::Node& root) -{ - Node_traverseSubgraph(root, GatherNamespaced()); -} - -void Map_mergeClonedNames() -{ - for(std::list::const_iterator i = g_cloned.begin(); i != g_cloned.end(); ++i) - { - (*i)->setNamespace(g_cloneNamespace); - } - g_cloneNamespace.mergeNames(g_defaultNamespace); - for(std::list::const_iterator i = g_cloned.begin(); i != g_cloned.end(); ++i) - { - (*i)->setNamespace(g_defaultNamespace); - } - - g_cloned.clear(); -} - -class WorldNode -{ - scene::Node* m_node; -public: - WorldNode() - : m_node(0) - { - } - void set(scene::Node* node) - { - if(m_node != 0) - m_node->DecRef(); - m_node = node; - if(m_node != 0) - m_node->IncRef(); - } - scene::Node* get() const - { - return m_node; - } -}; - -class Map; -void Map_SetValid(Map& map, bool valid); -void Map_UpdateTitle(const Map& map); -void Map_SetWorldspawn(Map& map, scene::Node* node); - - -class Map : public ModuleObserver -{ -public: - CopiedString m_name; - Resource* m_resource; - bool m_valid; - - bool m_modified; - void (*m_modified_changed)(const Map&); - - Signal0 m_mapValidCallbacks; - - WorldNode m_world_node; // "classname" "worldspawn" ! - - Map() : m_resource(0), m_valid(false), m_modified_changed(Map_UpdateTitle) - { - } - - void realise() - { - if(m_resource != 0) - { - if(Map_Unnamed(*this)) - { - g_map.m_resource->setNode(NewMapRoot("").get_pointer()); - MapFile* map = Node_getMapFile(*g_map.m_resource->getNode()); - if(map != 0) - { - map->save(); - } - } - else - { - m_resource->load(); - } - - GlobalSceneGraph().insert_root(*m_resource->getNode()); - - AutoSave_clear(); - - Map_SetValid(g_map, true); - } - } - void unrealise() - { - if(m_resource != 0) - { - Map_SetValid(g_map, false); - Map_SetWorldspawn(g_map, 0); - - - GlobalUndoSystem().clear(); - - GlobalSceneGraph().erase_root(); - } - } -}; - -Map g_map; -Map* g_currentMap = 0; - -void Map_addValidCallback(Map& map, const SignalHandler& handler) -{ - map.m_mapValidCallbacks.connectLast(handler); -} - -bool Map_Valid(const Map& map) -{ - return map.m_valid; -} - -void Map_SetValid(Map& map, bool valid) -{ - map.m_valid = valid; - map.m_mapValidCallbacks(); -} - - -const char* Map_Name(const Map& map) -{ - return map.m_name.c_str(); -} - -bool Map_Unnamed(const Map& map) -{ - return string_equal(Map_Name(map), "unnamed.map"); -} - -inline const MapFormat& MapFormat_forFile(const char* filename) -{ - const char* moduleName = findModuleName(GetFileTypeRegistry(), MapFormat::Name(), path_get_extension(filename)); - MapFormat* format = Radiant_getMapModules().findModule(moduleName); - ASSERT_MESSAGE(format != 0, "map format not found for file " << makeQuoted(filename)); - return *format; -} - -const MapFormat& Map_getFormat(const Map& map) -{ - return MapFormat_forFile(Map_Name(map)); -} - - -bool Map_Modified(const Map& map) -{ - return map.m_modified; -} - -void Map_SetModified(Map& map, bool modified) -{ - if(map.m_modified ^ modified) - { - map.m_modified = modified; - - map.m_modified_changed(map); - } -} - -void Map_UpdateTitle(const Map& map) -{ - Sys_SetTitle(map.m_name.c_str(), Map_Modified(map)); -} - - - -scene::Node* Map_GetWorldspawn(const Map& map) -{ - return map.m_world_node.get(); -} - -void Map_SetWorldspawn(Map& map, scene::Node* node) -{ - map.m_world_node.set(node); -} - - -// TTimo -// need that in a variable, will have to tweak depending on the game -float g_MaxWorldCoord = 64*1024; -float g_MinWorldCoord = -64*1024; - -void AddRegionBrushes (void); -void RemoveRegionBrushes (void); - - -/* -================ -Map_Free -free all map elements, reinitialize the structures that depend on them -================ -*/ -void Map_Free() -{ - Pointfile_Clear(); - - g_map.m_resource->detach(g_map); - GlobalReferenceCache().release(g_map.m_name.c_str()); - g_map.m_resource = 0; - - FlushReferences(); - - g_currentMap = 0; - Brush_unlatchPreferences(); -} - -class EntityFindByClassname : public scene::Graph::Walker -{ - const char* m_name; - Entity*& m_entity; -public: - EntityFindByClassname(const char* name, Entity*& entity) : m_name(name), m_entity(entity) - { - m_entity = 0; - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(m_entity == 0) - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && string_equal(m_name, entity->getKeyValue("classname"))) - { - m_entity = entity; - } - } - return true; - } -}; - -Entity* Scene_FindEntityByClass(const char* name) -{ - Entity* entity; - GlobalSceneGraph().traverse(EntityFindByClassname(name, entity)); - return entity; -} - -Entity *Scene_FindPlayerStart() -{ - typedef const char* StaticString; - StaticString strings[] = { - "info_player_start", - "info_player_deathmatch", - "team_CTF_redplayer", - "team_CTF_blueplayer", - "team_CTF_redspawn", - "team_CTF_bluespawn", - }; - typedef const StaticString* StaticStringIterator; - for(StaticStringIterator i = strings, end = strings+(sizeof(strings)/sizeof(StaticString)); i != end; ++i) - { - Entity* entity = Scene_FindEntityByClass(*i); - if(entity != 0) - { - return entity; - } - } - return 0; -} - -// -// move the view to a start position -// - - -void FocusViews(const Vector3& point, float angle) -{ - CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); - Camera_setOrigin(camwnd, point); - Vector3 angles(Camera_getAngles(camwnd)); - angles[CAMERA_PITCH] = 0; - angles[CAMERA_YAW] = angle; - Camera_setAngles(camwnd, angles); - - XYWnd* xywnd = g_pParentWnd->GetXYWnd(); - xywnd->SetOrigin(point); -} - -#include "stringio.h" - -void Map_StartPosition() -{ - Entity* entity = Scene_FindPlayerStart(); - - if (entity) - { - Vector3 origin; - string_parse_vector3(entity->getKeyValue("origin"), origin); - FocusViews(origin, string_read_float(entity->getKeyValue("angle"))); - } - else - { - FocusViews(g_vector3_identity, 0); - } -} - - -inline bool node_is_worldspawn(scene::Node& node) -{ - Entity* entity = Node_getEntity(node); - return entity != 0 && string_equal(entity->getKeyValue("classname"), "worldspawn"); -} - - -// use first worldspawn -class entity_updateworldspawn : public scene::Traversable::Walker -{ -public: - bool pre(scene::Node& node) const - { - if(node_is_worldspawn(node)) - { - if(Map_GetWorldspawn(g_map) == 0) - { - Map_SetWorldspawn(g_map, &node); - } - } - return false; - } -}; - -scene::Node* Map_FindWorldspawn(Map& map) -{ - Map_SetWorldspawn(map, 0); - - Node_getTraversable(GlobalSceneGraph().root())->traverse(entity_updateworldspawn()); - - return Map_GetWorldspawn(map); -} - - -class CollectAllWalker : public scene::Traversable::Walker -{ - scene::Node& m_root; - UnsortedNodeSet& m_nodes; -public: - CollectAllWalker(scene::Node& root, UnsortedNodeSet& nodes) : m_root(root), m_nodes(nodes) - { - } - bool pre(scene::Node& node) const - { - m_nodes.insert(NodeSmartReference(node)); - Node_getTraversable(m_root)->erase(node); - return false; - } -}; - -void Node_insertChildFirst(scene::Node& parent, scene::Node& child) -{ - UnsortedNodeSet nodes; - Node_getTraversable(parent)->traverse(CollectAllWalker(parent, nodes)); - Node_getTraversable(parent)->insert(child); - - for(UnsortedNodeSet::iterator i = nodes.begin(); i != nodes.end(); ++i) - { - Node_getTraversable(parent)->insert((*i)); - } -} - -scene::Node& createWorldspawn() -{ - NodeSmartReference worldspawn(GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert("worldspawn", true))); - Node_insertChildFirst(GlobalSceneGraph().root(), worldspawn); - return worldspawn; -} - -void Map_UpdateWorldspawn(Map& map) -{ - if(Map_FindWorldspawn(map) == 0) - { - Map_SetWorldspawn(map, &createWorldspawn()); - } -} - -scene::Node& Map_FindOrInsertWorldspawn(Map& map) -{ - Map_UpdateWorldspawn(map); - return *Map_GetWorldspawn(map); -} - - -class MapMergeAll : public scene::Traversable::Walker -{ - mutable scene::Path m_path; -public: - MapMergeAll(const scene::Path& root) - : m_path(root) - { - } - bool pre(scene::Node& node) const - { - Node_getTraversable(m_path.top())->insert(node); - m_path.push(makeReference(node)); - selectPath(m_path, true); - return false; - } - void post(scene::Node& node) const - { - m_path.pop(); - } -}; - -class MapMergeEntities : public scene::Traversable::Walker -{ - mutable scene::Path m_path; -public: - MapMergeEntities(const scene::Path& root) - : m_path(root) - { - } - bool pre(scene::Node& node) const - { - if(node_is_worldspawn(node)) - { - scene::Node* world_node = Map_FindWorldspawn(g_map); - if(world_node == 0) - { - Map_SetWorldspawn(g_map, &node); - Node_getTraversable(m_path.top().get())->insert(node); - m_path.push(makeReference(node)); - Node_getTraversable(node)->traverse(SelectChildren(m_path)); - } - else - { - m_path.push(makeReference(*world_node)); - Node_getTraversable(node)->traverse(MapMergeAll(m_path)); - } - } - else - { - Node_getTraversable(m_path.top())->insert(node); - m_path.push(makeReference(node)); - if(node_is_group(node)) - { - Node_getTraversable(node)->traverse(SelectChildren(m_path)); - } - else - { - selectPath(m_path, true); - } - } - return false; - } - void post(scene::Node& node) const - { - m_path.pop(); - } -}; - -class BasicContainer : public scene::Node::Symbiot -{ - class TypeCasts - { - NodeTypeCastTable m_casts; - public: - TypeCasts() - { - NodeContainedCast::install(m_casts); - } - NodeTypeCastTable& get() - { - return m_casts; - } - }; - - scene::Node m_node; - TraversableNodeSet m_traverse; -public: - - typedef LazyStatic StaticTypeCasts; - - scene::Traversable& get(NullType) - { - return m_traverse; - } - - BasicContainer() : m_node(this, this, StaticTypeCasts::instance().get()) - { - } - void release() - { - delete this; - } - scene::Node& node() - { - return m_node; - } -}; - -/// Merges the map graph rooted at \p node into the global scene-graph. -void MergeMap(scene::Node& node) -{ - Node_getTraversable(node)->traverse(MapMergeEntities(scene::Path(makeReference(GlobalSceneGraph().root())))); -} -void Map_ImportSelected(TextInputStream& in, const MapFormat& format) -{ - NodeSmartReference node((new BasicContainer)->node()); - format.readGraph(node, in, GlobalEntityCreator()); - Map_gatherNamespaced(node); - Map_mergeClonedNames(); - MergeMap(node); -} - -inline scene::Cloneable* Node_getCloneable(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -inline scene::Node& node_clone(scene::Node& node) -{ - scene::Cloneable* cloneable = Node_getCloneable(node); - if(cloneable != 0) - { - return cloneable->clone(); - } - - return (new scene::NullNode)->node(); -} - -class CloneAll : public scene::Traversable::Walker -{ - mutable scene::Path m_path; -public: - CloneAll(scene::Node& root) - : m_path(makeReference(root)) - { - } - bool pre(scene::Node& node) const - { - if(node.isRoot()) - { - return false; - } - - m_path.push(makeReference(node_clone(node))); - m_path.top().get().IncRef(); - - return true; - } - void post(scene::Node& node) const - { - if(node.isRoot()) - { - return; - } - - Node_getTraversable(m_path.parent())->insert(m_path.top()); - - m_path.top().get().DecRef(); - m_path.pop(); - } -}; - -scene::Node& Node_Clone(scene::Node& node) -{ - scene::Node& clone = node_clone(node); - scene::Traversable* traversable = Node_getTraversable(node); - if(traversable != 0) - { - traversable->traverse(CloneAll(clone)); - } - return clone; -} - - -typedef std::map EntityBreakdown; - -class EntityBreakdownWalker : public scene::Graph::Walker -{ - EntityBreakdown& m_entitymap; -public: - EntityBreakdownWalker(EntityBreakdown& entitymap) - : m_entitymap(entitymap) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0) - { - const EntityClass& eclass = entity->getEntityClass(); - if(m_entitymap.find(eclass.name()) == m_entitymap.end()) - { - m_entitymap[eclass.name()] = 1; - } - else ++m_entitymap[eclass.name()]; - } - return true; - } -}; - -void Scene_EntityBreakdown(EntityBreakdown& entitymap) -{ - GlobalSceneGraph().traverse(EntityBreakdownWalker(entitymap)); -} - - -WindowPosition g_posMapInfoWnd(c_default_window_pos); - -void DoMapInfo() -{ - ModalDialog dialog; - GtkEntry* brushes_entry; - GtkEntry* entities_entry; - GtkListStore* EntityBreakdownWalker; - - GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Map Info", G_CALLBACK(dialog_delete_callback), &dialog); - - window_set_position(window, g_posMapInfoWnd); - - { - GtkVBox* vbox = create_dialog_vbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); - - { - GtkHBox* hbox = create_dialog_hbox(4); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, TRUE, 0); - - { - GtkTable* table = create_dialog_table(2, 2, 4, 4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); - - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_entry_set_editable(entry, FALSE); - - brushes_entry = entry; - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_entry_set_editable(entry, FALSE); - - entities_entry = entry; - } - { - GtkWidget* label = gtk_label_new ("Total Brushes"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkWidget* label = gtk_label_new ("Total Entities"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - } - { - GtkVBox* vbox2 = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), FALSE, FALSE, 0); - - { - GtkButton* button = create_dialog_button("Close", G_CALLBACK(dialog_button_ok), &dialog); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); - } - } - } - { - GtkWidget* label = gtk_label_new ("Entity breakdown"); - gtk_widget_show (label); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, TRUE, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4); - gtk_box_pack_start(GTK_BOX (vbox), GTK_WIDGET(scr), TRUE, TRUE, 0); - - { - GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_STRING); - - GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); - gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(view), TRUE); - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Entity", renderer, "text", 0, 0); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - gtk_tree_view_column_set_sort_column_id(column, 0); - } - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Count", renderer, "text", 1, 0); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - gtk_tree_view_column_set_sort_column_id(column, 1); - } - - gtk_widget_show(view); - - gtk_container_add(GTK_CONTAINER(scr), view); - - EntityBreakdownWalker = store; - } - } - } - - // Initialize fields - - { - EntityBreakdown entitymap; - Scene_EntityBreakdown(entitymap); - - for(EntityBreakdown::iterator i=entitymap.begin(); i != entitymap.end(); ++i) - { - char tmp[16]; - sprintf (tmp, "%u", Unsigned((*i).second)); - GtkTreeIter iter; - gtk_list_store_append(GTK_LIST_STORE(EntityBreakdownWalker), &iter); - gtk_list_store_set(GTK_LIST_STORE(EntityBreakdownWalker), &iter, 0, (*i).first.c_str(), 1, tmp, -1); - } - } - - g_object_unref(G_OBJECT(EntityBreakdownWalker)); - - char tmp[16]; - sprintf (tmp, "%u", Unsigned(g_brushCount.get())); - gtk_entry_set_text (GTK_ENTRY (brushes_entry), tmp); - sprintf (tmp, "%u", Unsigned(g_entityCount.get())); - gtk_entry_set_text (GTK_ENTRY (entities_entry), tmp); - - modal_dialog_show(window, dialog); - - // save before exit - window_get_position(window, g_posMapInfoWnd); - - gtk_widget_destroy(GTK_WIDGET(window)); -} - - - -class ScopeTimer -{ - Timer m_timer; - const char* m_message; -public: - ScopeTimer(const char* message) - : m_message(message) - { - m_timer.start(); - } - ~ScopeTimer() - { - double elapsed_time = m_timer.elapsed_msec() / 1000.f; - globalOutputStream() << m_message << " timer: " << FloatFormat(elapsed_time, 5, 2) << " second(s) elapsed\n"; - } -}; - -/* -================ -Map_LoadFile -================ -*/ - -void Map_LoadFile (const char *filename) -{ - globalOutputStream() << "Loading map from " << filename << "\n"; - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Map"); - - { - ScopeTimer timer("map load"); - - const MapFormat* format = NULL; - const char* moduleName = findModuleName(&GlobalFiletypes(), MapFormat::Name(), path_get_extension(filename)); - if(string_not_empty(moduleName)) - format = ReferenceAPI_getMapModules().findModule(moduleName); - - for(int i = 0; i < Brush_toggleFormatCount(); ++i) - { - if(i) - Map_Free(); - Brush_toggleFormat(i); - g_map.m_name = filename; - Map_UpdateTitle(g_map); - g_map.m_resource = GlobalReferenceCache().capture(g_map.m_name.c_str()); - if(format) - format->wrongFormat = false; - g_map.m_resource->attach(g_map); - if(format) - if(!format->wrongFormat) - break; - } - - Node_getTraversable(GlobalSceneGraph().root())->traverse(entity_updateworldspawn()); - } - - globalOutputStream() << "--- LoadMapFile ---\n"; - globalOutputStream() << g_map.m_name.c_str() << "\n"; - - globalOutputStream() << Unsigned(g_brushCount.get()) << " primitive\n"; - globalOutputStream() << Unsigned(g_entityCount.get()) << " entities\n"; - - //GlobalEntityCreator().printStatistics(); - - // - // move the view to a start position - // - Map_StartPosition(); - - g_currentMap = &g_map; -} - -class Excluder -{ -public: - virtual bool excluded(scene::Node& node) const = 0; -}; - -class ExcludeWalker : public scene::Traversable::Walker -{ - const scene::Traversable::Walker& m_walker; - const Excluder* m_exclude; - mutable bool m_skip; -public: - ExcludeWalker(const scene::Traversable::Walker& walker, const Excluder& exclude) - : m_walker(walker), m_exclude(&exclude), m_skip(false) - { - } - bool pre(scene::Node& node) const - { - if(m_exclude->excluded(node) || node.isRoot()) - { - m_skip = true; - return false; - } - else - { - m_walker.pre(node); - } - return true; - } - void post(scene::Node& node) const - { - if(m_skip) - { - m_skip = false; - } - else - { - m_walker.post(node); - } - } -}; - -class AnyInstanceSelected : public scene::Instantiable::Visitor -{ - bool& m_selected; -public: - AnyInstanceSelected(bool& selected) : m_selected(selected) - { - m_selected = false; - } - void visit(scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected()) - { - m_selected = true; - } - } -}; - -bool Node_instanceSelected(scene::Node& node) -{ - scene::Instantiable* instantiable = Node_getInstantiable(node); - ASSERT_NOTNULL(instantiable); - bool selected; - instantiable->forEachInstance(AnyInstanceSelected(selected)); - return selected; -} - -class SelectedDescendantWalker : public scene::Traversable::Walker -{ - bool& m_selected; -public: - SelectedDescendantWalker(bool& selected) : m_selected(selected) - { - m_selected = false; - } - - bool pre(scene::Node& node) const - { - if(node.isRoot()) - { - return false; - } - - if(Node_instanceSelected(node)) - { - m_selected = true; - } - - return true; - } -}; - -bool Node_selectedDescendant(scene::Node& node) -{ - bool selected; - Node_traverseSubgraph(node, SelectedDescendantWalker(selected)); - return selected; -} - -class SelectionExcluder : public Excluder -{ -public: - bool excluded(scene::Node& node) const - { - return !Node_selectedDescendant(node); - } -}; - -class IncludeSelectedWalker : public scene::Traversable::Walker -{ - const scene::Traversable::Walker& m_walker; - mutable std::size_t m_selected; - mutable bool m_skip; - - bool selectedParent() const - { - return m_selected != 0; - } -public: - IncludeSelectedWalker(const scene::Traversable::Walker& walker) - : m_walker(walker), m_selected(0), m_skip(false) - { - } - bool pre(scene::Node& node) const - { - // include node if: - // node is not a 'root' AND ( node is selected OR any child of node is selected OR any parent of node is selected ) - if(!node.isRoot() && (Node_selectedDescendant(node) || selectedParent())) - { - if(Node_instanceSelected(node)) - { - ++m_selected; - } - m_walker.pre(node); - return true; - } - else - { - m_skip = true; - return false; - } - } - void post(scene::Node& node) const - { - if(m_skip) - { - m_skip = false; - } - else - { - if(Node_instanceSelected(node)) - { - --m_selected; - } - m_walker.post(node); - } - } -}; - -void Map_Traverse_Selected(scene::Node& root, const scene::Traversable::Walker& walker) -{ - scene::Traversable* traversable = Node_getTraversable(root); - if(traversable != 0) - { -#if 0 - traversable->traverse(ExcludeWalker(walker, SelectionExcluder())); -#else - traversable->traverse(IncludeSelectedWalker(walker)); -#endif - } -} - -void Map_ExportSelected(TextOutputStream& out, const MapFormat& format) -{ - format.writeGraph(GlobalSceneGraph().root(), Map_Traverse_Selected, out); -} - -void Map_Traverse(scene::Node& root, const scene::Traversable::Walker& walker) -{ - scene::Traversable* traversable = Node_getTraversable(root); - if(traversable != 0) - { - traversable->traverse(walker); - } -} - -class RegionExcluder : public Excluder -{ -public: - bool excluded(scene::Node& node) const - { - return node.excluded(); - } -}; - -void Map_Traverse_Region(scene::Node& root, const scene::Traversable::Walker& walker) -{ - scene::Traversable* traversable = Node_getTraversable(root); - if(traversable != 0) - { - traversable->traverse(ExcludeWalker(walker, RegionExcluder())); - } -} - -bool Map_SaveRegion(const char *filename) -{ - AddRegionBrushes(); - - bool success = MapResource_saveFile(MapFormat_forFile(filename), GlobalSceneGraph().root(), Map_Traverse_Region, filename); - - RemoveRegionBrushes(); - - return success; -} - - -void Map_RenameAbsolute(const char* absolute) -{ - Resource* resource = GlobalReferenceCache().capture(absolute); - NodeSmartReference clone(NewMapRoot(path_make_relative(absolute, GlobalFileSystem().findRoot(absolute)))); - resource->setNode(clone.get_pointer()); - - { - //ScopeTimer timer("clone subgraph"); - Node_getTraversable(GlobalSceneGraph().root())->traverse(CloneAll(clone)); - } - - g_map.m_resource->detach(g_map); - GlobalReferenceCache().release(g_map.m_name.c_str()); - - g_map.m_resource = resource; - - g_map.m_name = absolute; - Map_UpdateTitle(g_map); - - g_map.m_resource->attach(g_map); -} - -void Map_Rename(const char* filename) -{ - if(!string_equal(g_map.m_name.c_str(), filename)) - { - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Saving Map"); - - Map_RenameAbsolute(filename); - - SceneChangeNotify(); - } - else - { - SaveReferences(); - } -} - -bool Map_Save() -{ - Pointfile_Clear(); - - ScopeTimer timer("map save"); - SaveReferences(); - return true; // assume success.. -} - -/* -=========== -Map_New - -=========== -*/ -void Map_New() -{ - //globalOutputStream() << "Map_New\n"; - - g_map.m_name = "unnamed.map"; - Map_UpdateTitle(g_map); - - { - g_map.m_resource = GlobalReferenceCache().capture(g_map.m_name.c_str()); -// ASSERT_MESSAGE(g_map.m_resource->getNode() == 0, "bleh"); - g_map.m_resource->attach(g_map); - - SceneChangeNotify(); - } - - FocusViews(g_vector3_identity, 0); - - g_currentMap = &g_map; -} - -extern void ConstructRegionBrushes(scene::Node* brushes[6], const Vector3& region_mins, const Vector3& region_maxs); - -void ConstructRegionStartpoint(scene::Node* startpoint, const Vector3& region_mins, const Vector3& region_maxs) -{ - /*! - \todo we need to make sure that the player start IS inside the region and bail out if it's not - the compiler will refuse to compile a map with a player_start somewhere in empty space.. - for now, let's just print an error - */ - - Vector3 vOrig(Camera_getOrigin(*g_pParentWnd->GetCamWnd())); - - for (int i=0 ; i<3 ; i++) - { - if (vOrig[i] > region_maxs[i] || vOrig[i] < region_mins[i]) - { - globalErrorStream() << "Camera is NOT in the region, it's likely that the region won't compile correctly\n"; - break; - } - } - - // write the info_playerstart - char sTmp[1024]; - sprintf(sTmp, "%d %d %d", (int)vOrig[0], (int)vOrig[1], (int)vOrig[2]); - Node_getEntity(*startpoint)->setKeyValue("origin", sTmp); - sprintf(sTmp, "%d", (int)Camera_getAngles(*g_pParentWnd->GetCamWnd())[CAMERA_YAW]); - Node_getEntity(*startpoint)->setKeyValue("angle", sTmp); -} - -/* -=========================================================== - - REGION - -=========================================================== -*/ -bool region_active; -Vector3 region_mins(g_MinWorldCoord, g_MinWorldCoord, g_MinWorldCoord); -Vector3 region_maxs(g_MaxWorldCoord, g_MaxWorldCoord, g_MaxWorldCoord); - -scene::Node* region_sides[6]; -scene::Node* region_startpoint = 0; - -/* -=========== -AddRegionBrushes -a regioned map will have temp walls put up at the region boundary -\todo TODO TTimo old implementation of region brushes - we still add them straight in the worldspawn and take them out after the map is saved - with the new implementation we should be able to append them in a temporary manner to the data we pass to the map module -=========== -*/ -void AddRegionBrushes (void) -{ - int i; - - for(i=0; i<6; i++) - { - region_sides[i] = &GlobalBrushCreator().createBrush(); - Node_getTraversable(Map_FindOrInsertWorldspawn(g_map))->insert(NodeSmartReference(*region_sides[i])); - } - - region_startpoint = &GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert("info_player_start", false)); - - ConstructRegionBrushes(region_sides, region_mins, region_maxs); - ConstructRegionStartpoint(region_startpoint, region_mins, region_maxs); - - Node_getTraversable(GlobalSceneGraph().root())->insert(NodeSmartReference(*region_startpoint)); -} - -void RemoveRegionBrushes (void) -{ - for(std::size_t i=0; i<6; i++) - { - Node_getTraversable(*Map_GetWorldspawn(g_map))->erase(*region_sides[i]); - } - Node_getTraversable(GlobalSceneGraph().root())->erase(*region_startpoint); -} - -inline void exclude_node(scene::Node& node, bool exclude) -{ - exclude - ? node.enable(scene::Node::eExcluded) - : node.disable(scene::Node::eExcluded); -} - -class ExcludeAllWalker : public scene::Graph::Walker -{ - bool m_exclude; -public: - ExcludeAllWalker(bool exclude) - : m_exclude(exclude) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - exclude_node(path.top(), m_exclude); - - return true; - } -}; - -void Scene_Exclude_All(bool exclude) -{ - GlobalSceneGraph().traverse(ExcludeAllWalker(exclude)); -} - -bool Instance_isSelected(const scene::Instance& instance) -{ - const Selectable* selectable = Instance_getSelectable(instance); - return selectable != 0 && selectable->isSelected(); -} - -class ExcludeSelectedWalker : public scene::Graph::Walker -{ - bool m_exclude; -public: - ExcludeSelectedWalker(bool exclude) - : m_exclude(exclude) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - exclude_node(path.top(), (instance.isSelected() || instance.childSelected() || instance.parentSelected()) == m_exclude); - return true; - } -}; - -void Scene_Exclude_Selected(bool exclude) -{ - GlobalSceneGraph().traverse(ExcludeSelectedWalker(exclude)); -} - -class ExcludeRegionedWalker : public scene::Graph::Walker -{ - bool m_exclude; -public: - ExcludeRegionedWalker(bool exclude) - : m_exclude(exclude) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - exclude_node( - path.top(), - !( - ( - aabb_intersects_aabb( - instance.worldAABB(), - aabb_for_minmax(region_mins, region_maxs) - ) != 0 - ) ^ m_exclude - ) - ); - - return true; - } -}; - -void Scene_Exclude_Region(bool exclude) -{ - GlobalSceneGraph().traverse(ExcludeRegionedWalker(exclude)); -} - -/* -=========== -Map_RegionOff - -Other filtering options may still be on -=========== -*/ -void Map_RegionOff() -{ - region_active = false; - - region_maxs[0] = g_MaxWorldCoord - 64; - region_mins[0] = g_MinWorldCoord + 64; - region_maxs[1] = g_MaxWorldCoord - 64; - region_mins[1] = g_MinWorldCoord + 64; - region_maxs[2] = g_MaxWorldCoord - 64; - region_mins[2] = g_MinWorldCoord + 64; - - Scene_Exclude_All(false); -} - -void Map_ApplyRegion (void) -{ - region_active = true; - - Scene_Exclude_Region(false); -} - - -/* -======================== -Map_RegionSelectedBrushes -======================== -*/ -void Map_RegionSelectedBrushes (void) -{ - Map_RegionOff(); - - if(GlobalSelectionSystem().countSelected() != 0 - && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) - { - region_active = true; - Select_GetBounds (region_mins, region_maxs); - - Scene_Exclude_Selected(false); - - GlobalSelectionSystem().setSelectedAll(false); - } -} - - -/* -=========== -Map_RegionXY -=========== -*/ -void Map_RegionXY(float x_min, float y_min, float x_max, float y_max) -{ - Map_RegionOff(); - - region_mins[0] = x_min; - region_maxs[0] = x_max; - region_mins[1] = y_min; - region_maxs[1] = y_max; - region_mins[2] = g_MinWorldCoord + 64; - region_maxs[2] = g_MaxWorldCoord - 64; - - Map_ApplyRegion(); -} - -void Map_RegionBounds(const AABB& bounds) -{ - Map_RegionOff(); - - region_mins = vector3_subtracted(bounds.origin, bounds.extents); - region_maxs = vector3_added(bounds.origin, bounds.extents); - - deleteSelection(); - - Map_ApplyRegion(); -} - -/* -=========== -Map_RegionBrush -=========== -*/ -void Map_RegionBrush (void) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - Map_RegionBounds(instance.worldAABB()); - } -} - -// -//================ -//Map_ImportFile -//================ -// -bool Map_ImportFile(const char* filename) -{ - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Map"); - - bool success = false; - - if(extension_equal(path_get_extension(filename), "bsp")) - goto tryDecompile; - - { - const MapFormat* format = NULL; - const char* moduleName = findModuleName(&GlobalFiletypes(), MapFormat::Name(), path_get_extension(filename)); - if(string_not_empty(moduleName)) - format = ReferenceAPI_getMapModules().findModule(moduleName); - - if(format) - format->wrongFormat = false; - Resource* resource = GlobalReferenceCache().capture(filename); - resource->refresh(); // avoid loading old version if map has changed on disk since last import - if(!resource->load()) - { - GlobalReferenceCache().release(filename); - goto tryDecompile; - } - if(format) - if(format->wrongFormat) - { - GlobalReferenceCache().release(filename); - goto tryDecompile; - } - NodeSmartReference clone(NewMapRoot("")); - Node_getTraversable(*resource->getNode())->traverse(CloneAll(clone)); - Map_gatherNamespaced(clone); - Map_mergeClonedNames(); - MergeMap(clone); - success = true; - GlobalReferenceCache().release(filename); - } - - SceneChangeNotify(); - - return success; - -tryDecompile: - - const char *type = GlobalRadiant().getRequiredGameDescriptionKeyValue("q3map2_type"); - int n = string_length(path_get_extension(filename)); - if(n && (extension_equal(path_get_extension(filename), "bsp") || extension_equal(path_get_extension(filename), "map"))) - { - StringBuffer output; - output.push_string(AppPath_get()); - output.push_string("q3map2."); - output.push_string(RADIANT_EXECUTABLE); - output.push_string(" -v -game "); - output.push_string((type && *type) ? type : "quake3"); - output.push_string(" -fs_basepath \""); - output.push_string(EnginePath_get()); - output.push_string("\" -fs_game "); - output.push_string(gamename_get()); - output.push_string(" -convert -format "); - output.push_string(Brush::m_type == eBrushTypeQuake3BP ? "map_bp" : "map"); - output.push_string(" -readmap \""); - output.push_string(filename); - output.push_string("\""); - - // run - Q_Exec(NULL, output.c_str(), NULL, false, true); - - // rebuild filename as "filenamewithoutext_converted.map" - output.clear(); - output.push_range(filename, filename + string_length(filename) - (n + 1)); - output.push_string("_converted.map"); - filename = output.c_str(); - - // open - Resource* resource = GlobalReferenceCache().capture(filename); - resource->refresh(); // avoid loading old version if map has changed on disk since last import - if(!resource->load()) - { - GlobalReferenceCache().release(filename); - goto tryDecompile; - } - NodeSmartReference clone(NewMapRoot("")); - Node_getTraversable(*resource->getNode())->traverse(CloneAll(clone)); - Map_gatherNamespaced(clone); - Map_mergeClonedNames(); - MergeMap(clone); - success = true; - GlobalReferenceCache().release(filename); - } - - SceneChangeNotify(); - return success; -} - -/* -=========== -Map_SaveFile -=========== -*/ -bool Map_SaveFile(const char* filename) -{ - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Saving Map"); - return MapResource_saveFile(MapFormat_forFile(filename), GlobalSceneGraph().root(), Map_Traverse, filename); -} - -// -//=========== -//Map_SaveSelected -//=========== -// -// Saves selected world brushes and whole entities with partial/full selections -// -bool Map_SaveSelected(const char* filename) -{ - return MapResource_saveFile(MapFormat_forFile(filename), GlobalSceneGraph().root(), Map_Traverse_Selected, filename); -} - - -class ParentSelectedBrushesToEntityWalker : public scene::Graph::Walker -{ - scene::Node& m_parent; -public: - ParentSelectedBrushesToEntityWalker(scene::Node& parent) : m_parent(parent) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get_pointer() != &m_parent - && Node_isPrimitive(path.top())) - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected() - && path.size() > 1) - { - return false; - } - } - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get_pointer() != &m_parent - && Node_isPrimitive(path.top())) - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected() - && path.size() > 1) - { - scene::Node& parent = path.parent(); - if(&parent != &m_parent) - { - NodeSmartReference node(path.top().get()); - Node_getTraversable(parent)->erase(node); - Node_getTraversable(m_parent)->insert(node); - } - } - } - } -}; - -void Scene_parentSelectedBrushesToEntity(scene::Graph& graph, scene::Node& parent) -{ - graph.traverse(ParentSelectedBrushesToEntityWalker(parent)); -} - -class CountSelectedBrushes : public scene::Graph::Walker -{ - std::size_t& m_count; - mutable std::size_t m_depth; -public: - CountSelectedBrushes(std::size_t& count) : m_count(count), m_depth(0) - { - m_count = 0; - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(++m_depth != 1 && path.top().get().isRoot()) - { - return false; - } - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected() - && Node_isPrimitive(path.top())) - { - ++m_count; - } - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - --m_depth; - } -}; - -std::size_t Scene_countSelectedBrushes(scene::Graph& graph) -{ - std::size_t count; - graph.traverse(CountSelectedBrushes(count)); - return count; -} - -enum ENodeType -{ - eNodeUnknown, - eNodeMap, - eNodeEntity, - eNodePrimitive, -}; - -const char* nodetype_get_name(ENodeType type) -{ - if(type == eNodeMap) - return "map"; - if(type == eNodeEntity) - return "entity"; - if(type == eNodePrimitive) - return "primitive"; - return "unknown"; -} - -ENodeType node_get_nodetype(scene::Node& node) -{ - if(Node_isEntity(node)) - { - return eNodeEntity; - } - if(Node_isPrimitive(node)) - { - return eNodePrimitive; - } - return eNodeUnknown; -} - -bool contains_entity(scene::Node& node) -{ - return Node_getTraversable(node) != 0 && !Node_isBrush(node) && !Node_isPatch(node) && !Node_isEntity(node); -} - -bool contains_primitive(scene::Node& node) -{ - return Node_isEntity(node) && Node_getTraversable(node) != 0 && Node_getEntity(node)->isContainer(); -} - -ENodeType node_get_contains(scene::Node& node) -{ - if(contains_entity(node)) - { - return eNodeEntity; - } - if(contains_primitive(node)) - { - return eNodePrimitive; - } - return eNodeUnknown; -} - -void Path_parent(const scene::Path& parent, const scene::Path& child) -{ - ENodeType contains = node_get_contains(parent.top()); - ENodeType type = node_get_nodetype(child.top()); - - if(contains != eNodeUnknown && contains == type) - { - NodeSmartReference node(child.top().get()); - Path_deleteTop(child); - Node_getTraversable(parent.top())->insert(node); - SceneChangeNotify(); - } - else - { - globalErrorStream() << "failed - " << nodetype_get_name(type) << " cannot be parented to " << nodetype_get_name(contains) << " container.\n"; - } -} - -void Scene_parentSelected() -{ - UndoableCommand undo("parentSelected"); - - if(GlobalSelectionSystem().countSelected() > 1) - { - class ParentSelectedBrushesToEntityWalker : public SelectionSystem::Visitor - { - const scene::Path& m_parent; - public: - ParentSelectedBrushesToEntityWalker(const scene::Path& parent) : m_parent(parent) - { - } - void visit(scene::Instance& instance) const - { - if(&m_parent != &instance.path()) - { - Path_parent(m_parent, instance.path()); - } - } - }; - - ParentSelectedBrushesToEntityWalker visitor(GlobalSelectionSystem().ultimateSelected().path()); - GlobalSelectionSystem().foreachSelected(visitor); - } - else - { - globalOutputStream() << "failed - did not find two selected nodes.\n"; - } -} - - - -void NewMap() -{ - if (ConfirmModified("New Map")) - { - Map_RegionOff(); - Map_Free(); - Map_New(); - } -} - -CopiedString g_mapsPath; - -const char* getMapsPath() -{ - return g_mapsPath.c_str(); -} - -const char* map_open(const char* title) -{ - return file_dialog(GTK_WIDGET(MainFrame_getWindow()), TRUE, title, getMapsPath(), MapFormat::Name(), true, false, false); -} - -const char* map_import(const char* title) -{ - return file_dialog(GTK_WIDGET(MainFrame_getWindow()), TRUE, title, getMapsPath(), MapFormat::Name(), false, true, false); -} - -const char* map_save(const char* title) -{ - return file_dialog(GTK_WIDGET(MainFrame_getWindow()), FALSE, title, getMapsPath(), MapFormat::Name(), false, false, true); -} - -void OpenMap() -{ - if (!ConfirmModified("Open Map")) - return; - - const char* filename = map_open("Open Map"); - - if (filename != 0) - { - MRU_AddFile(filename); - Map_RegionOff(); - Map_Free(); - Map_LoadFile(filename); - } -} - -void ImportMap() -{ - const char* filename = map_import("Import Map"); - - if(filename != 0) - { - UndoableCommand undo("mapImport"); - Map_ImportFile(filename); - } -} - -bool Map_SaveAs() -{ - const char* filename = map_save("Save Map"); - - if(filename != 0) - { - MRU_AddFile(filename); - Map_Rename(filename); - return Map_Save(); - } - return false; -} - -void SaveMapAs() -{ - Map_SaveAs(); -} - -void SaveMap() -{ - if(Map_Unnamed(g_map)) - { - SaveMapAs(); - } - else if(Map_Modified(g_map)) - { - Map_Save(); - } -} - -void ExportMap() -{ - const char* filename = map_save("Export Selection"); - - if(filename != 0) - { - Map_SaveSelected(filename); - } -} - -void SaveRegion() -{ - const char* filename = map_save("Export Region"); - - if(filename != 0) - { - Map_SaveRegion(filename); - } -} - - -void RegionOff() -{ - Map_RegionOff(); - SceneChangeNotify(); -} - -void RegionXY() -{ - Map_RegionXY( - g_pParentWnd->GetXYWnd()->GetOrigin()[0] - 0.5f * g_pParentWnd->GetXYWnd()->Width() / g_pParentWnd->GetXYWnd()->Scale(), - g_pParentWnd->GetXYWnd()->GetOrigin()[1] - 0.5f * g_pParentWnd->GetXYWnd()->Height() / g_pParentWnd->GetXYWnd()->Scale(), - g_pParentWnd->GetXYWnd()->GetOrigin()[0] + 0.5f * g_pParentWnd->GetXYWnd()->Width() / g_pParentWnd->GetXYWnd()->Scale(), - g_pParentWnd->GetXYWnd()->GetOrigin()[1] + 0.5f * g_pParentWnd->GetXYWnd()->Height() / g_pParentWnd->GetXYWnd()->Scale() - ); - SceneChangeNotify(); -} - -void RegionBrush() -{ - Map_RegionBrush(); - SceneChangeNotify(); -} - -void RegionSelected() -{ - Map_RegionSelectedBrushes(); - SceneChangeNotify(); -} - - - - - -class BrushFindByIndexWalker : public scene::Traversable::Walker -{ - mutable std::size_t m_index; - scene::Path& m_path; -public: - BrushFindByIndexWalker(std::size_t index, scene::Path& path) - : m_index(index), m_path(path) - { - } - bool pre(scene::Node& node) const - { - if(Node_isPrimitive(node) && m_index-- == 0) - { - m_path.push(makeReference(node)); - } - return false; - } -}; - -class EntityFindByIndexWalker : public scene::Traversable::Walker -{ - mutable std::size_t m_index; - scene::Path& m_path; -public: - EntityFindByIndexWalker(std::size_t index, scene::Path& path) - : m_index(index), m_path(path) - { - } - bool pre(scene::Node& node) const - { - if(Node_isEntity(node) && m_index-- == 0) - { - m_path.push(makeReference(node)); - } - return false; - } -}; - -void Scene_FindEntityBrush(std::size_t entity, std::size_t brush, scene::Path& path) -{ - path.push(makeReference(GlobalSceneGraph().root())); - { - Node_getTraversable(path.top())->traverse(EntityFindByIndexWalker(entity, path)); - } - if(path.size() == 2) - { - scene::Traversable* traversable = Node_getTraversable(path.top()); - if(traversable != 0) - { - traversable->traverse(BrushFindByIndexWalker(brush, path)); - } - } -} - -inline bool Node_hasChildren(scene::Node& node) -{ - scene::Traversable* traversable = Node_getTraversable(node); - return traversable != 0 && !traversable->empty(); -} - -void SelectBrush (int entitynum, int brushnum) -{ - scene::Path path; - Scene_FindEntityBrush(entitynum, brushnum, path); - if(path.size() == 3 || (path.size() == 2 && !Node_hasChildren(path.top()))) - { - scene::Instance* instance = GlobalSceneGraph().find(path); - ASSERT_MESSAGE(instance != 0, "SelectBrush: path not found in scenegraph"); - Selectable* selectable = Instance_getSelectable(*instance); - ASSERT_MESSAGE(selectable != 0, "SelectBrush: path not selectable"); - selectable->setSelected(true); - g_pParentWnd->GetXYWnd()->PositionView(instance->worldAABB().origin); - } -} - - -class BrushFindIndexWalker : public scene::Graph::Walker -{ - mutable const scene::Node* m_node; - std::size_t& m_count; -public: - BrushFindIndexWalker(const scene::Node& node, std::size_t& count) - : m_node(&node), m_count(count) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(Node_isPrimitive(path.top())) - { - if(m_node == path.top().get_pointer()) - { - m_node = 0; - } - if(m_node) - { - ++m_count; - } - } - return true; - } -}; - -class EntityFindIndexWalker : public scene::Graph::Walker -{ - mutable const scene::Node* m_node; - std::size_t& m_count; -public: - EntityFindIndexWalker(const scene::Node& node, std::size_t& count) - : m_node(&node), m_count(count) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(Node_isEntity(path.top())) - { - if(m_node == path.top().get_pointer()) - { - m_node = 0; - } - if(m_node) - { - ++m_count; - } - } - return true; - } -}; - -static void GetSelectionIndex (int *ent, int *brush) -{ - std::size_t count_brush = 0; - std::size_t count_entity = 0; - if(GlobalSelectionSystem().countSelected() != 0) - { - const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); - - GlobalSceneGraph().traverse(BrushFindIndexWalker(path.top(), count_brush)); - GlobalSceneGraph().traverse(EntityFindIndexWalker(path.parent(), count_entity)); - } - *brush = int(count_brush); - *ent = int(count_entity); -} - -void DoFind() -{ - ModalDialog dialog; - GtkEntry* entity; - GtkEntry* brush; - - GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Find Brush", G_CALLBACK(dialog_delete_callback), &dialog); - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel); - - { - GtkVBox* vbox = create_dialog_vbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); - { - GtkTable* table = create_dialog_table(2, 2, 4, 4); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), TRUE, TRUE, 0); - { - GtkWidget* label = gtk_label_new ("Entity number"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new ("Brush number"); - gtk_widget_show (label); - gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_grab_focus(GTK_WIDGET(entry)); - entity = entry; - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - brush = entry; - } - } - { - GtkHBox* hbox = create_dialog_hbox(4); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), TRUE, TRUE, 0); - { - GtkButton* button = create_dialog_button("Find", G_CALLBACK(dialog_button_ok), &dialog); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_dialog_button("Close", G_CALLBACK(dialog_button_cancel), &dialog); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - } - } - } - - // Initialize dialog - char buf[16]; - int ent, br; - - GetSelectionIndex (&ent, &br); - sprintf (buf, "%i", ent); - gtk_entry_set_text(entity, buf); - sprintf (buf, "%i", br); - gtk_entry_set_text(brush, buf); - - if(modal_dialog_show(window, dialog) == eIDOK) - { - const char *entstr = gtk_entry_get_text(entity); - const char *brushstr = gtk_entry_get_text(brush); - SelectBrush (atoi(entstr), atoi(brushstr)); - } - - gtk_widget_destroy(GTK_WIDGET(window)); -} - -void Map_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox("", "Load last map on open", g_bLoadLastMap); -} - - -class MapEntityClasses : public ModuleObserver -{ - std::size_t m_unrealised; -public: - MapEntityClasses() : m_unrealised(1) - { - } - void realise() - { - if(--m_unrealised == 0) - { - if(g_map.m_resource != 0) - { - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Map"); - g_map.m_resource->realise(); - } - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - if(g_map.m_resource != 0) - { - g_map.m_resource->flush(); - g_map.m_resource->unrealise(); - } - } - } -}; - -MapEntityClasses g_MapEntityClasses; - - -class MapModuleObserver : public ModuleObserver -{ - std::size_t m_unrealised; -public: - MapModuleObserver() : m_unrealised(1) - { - } - void realise() - { - if(--m_unrealised == 0) - { - ASSERT_MESSAGE(!string_empty(g_qeglobals.m_userGamePath.c_str()), "maps_directory: user-game-path is empty"); - StringOutputStream buffer(256); - buffer << g_qeglobals.m_userGamePath.c_str() << "maps/"; - Q_mkdir(buffer.c_str()); - g_mapsPath = buffer.c_str(); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - g_mapsPath = ""; - } - } -}; - -MapModuleObserver g_MapModuleObserver; - -#include "preferencesystem.h" - -CopiedString g_strLastMap; -bool g_bLoadLastMap = false; - -void Map_Construct() -{ - GlobalCommands_insert("RegionOff", FreeCaller()); - GlobalCommands_insert("RegionSetXY", FreeCaller()); - GlobalCommands_insert("RegionSetBrush", FreeCaller()); - GlobalCommands_insert("RegionSetSelection", FreeCaller(), Accelerator('R', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - - GlobalPreferenceSystem().registerPreference("LastMap", CopiedStringImportStringCaller(g_strLastMap), CopiedStringExportStringCaller(g_strLastMap)); - GlobalPreferenceSystem().registerPreference("LoadLastMap", BoolImportStringCaller(g_bLoadLastMap), BoolExportStringCaller(g_bLoadLastMap)); - GlobalPreferenceSystem().registerPreference("MapInfoDlg", WindowPositionImportStringCaller(g_posMapInfoWnd), WindowPositionExportStringCaller(g_posMapInfoWnd)); - - PreferencesDialog_addSettingsPreferences(FreeCaller1()); - - GlobalEntityClassManager().attach(g_MapEntityClasses); - Radiant_attachHomePathsObserver(g_MapModuleObserver); -} - -void Map_Destroy() -{ - Radiant_detachHomePathsObserver(g_MapModuleObserver); - GlobalEntityClassManager().detach(g_MapEntityClasses); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/map.h b/misc/mediasource/extra/netradiant-src/radiant/map.h deleted file mode 100644 index 2529bd2c..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/map.h +++ /dev/null @@ -1,173 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_MAP_H) -#define INCLUDED_MAP_H - -#include "iscenegraph.h" -#include "generic/callback.h" -#include "signal/signalfwd.h" -#include "string/stringfwd.h" - -class Map; -extern Map g_map; - -class MapFormat; - -void Map_addValidCallback(Map& map, const SignalHandler& handler); -bool Map_Valid(const Map& map); - -class DeferredDraw -{ - Callback m_draw; - bool m_defer; - bool m_deferred; -public: - DeferredDraw(const Callback& draw) : m_draw(draw), m_defer(false), m_deferred(false) - { - } - void defer() - { - m_defer = true; - } - void draw() - { - if(m_defer) - { - m_deferred = true; - } - else - { - m_draw(); - } - } - void flush() - { - if(m_defer && m_deferred) - { - m_draw(); - } - m_deferred = false; - m_defer = false; - } -}; - -inline void DeferredDraw_onMapValidChanged(DeferredDraw& self) -{ - if(Map_Valid(g_map)) - { - self.flush(); - } - else - { - self.defer(); - } -} -typedef ReferenceCaller DeferredDrawOnMapValidChangedCaller; - - - -const char* Map_Name(const Map& map); -const MapFormat& Map_getFormat(const Map& map); -bool Map_Unnamed(const Map& map); - - -namespace scene -{ - class Node; - class Graph; -} - -scene::Node* Map_GetWorldspawn(const Map& map); -scene::Node* Map_FindWorldspawn(Map& map); -scene::Node& Map_FindOrInsertWorldspawn(Map& map); - -template class BasicVector3; -typedef BasicVector3 Vector3; - -extern Vector3 region_mins, region_maxs; -extern bool region_active; - -// used to be #defines, multiple engine support suggests we should go towards dynamic -extern float g_MaxWorldCoord; -extern float g_MinWorldCoord; - -void Map_LoadFile(const char* filename); -bool Map_SaveFile(const char* filename); - -void Map_New(); -void Map_Free(); - -void Map_RegionOff(); - -bool Map_SaveRegion(const char* filename); - -class TextInputStream; -class TextOutputStream; - -void Map_ImportSelected(TextInputStream& in, const MapFormat& format); -void Map_ExportSelected(TextOutputStream& out, const MapFormat& format); - -bool Map_Modified(const Map& map); -void Map_SetModified(Map& map, bool modified); - -bool Map_Save(); -bool Map_SaveAs(); - -scene::Node& Node_Clone(scene::Node& node); - -void DoMapInfo(); - -void Scene_parentSelectedBrushesToEntity(scene::Graph& graph, scene::Node& parent); -std::size_t Scene_countSelectedBrushes(scene::Graph& graph); - -void Scene_parentSelected(); - -void OnUndoSizeChanged(); - -void NewMap(); -void OpenMap(); -void ImportMap(); -void SaveMapAs(); -void SaveMap(); -void ExportMap(); -void SaveRegion(); - - -void Map_Traverse(scene::Node& root, const scene::Traversable::Walker& walker); - - -void SelectBrush (int entitynum, int brushnum); - -extern CopiedString g_strLastMap; -extern bool g_bLoadLastMap; - -void Map_Construct(); -void Map_Destroy(); - - -void Map_gatherNamespaced(scene::Node& root); -void Map_mergeClonedNames(); - - -const char* getMapsPath(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/mru.cpp b/misc/mediasource/extra/netradiant-src/radiant/mru.cpp deleted file mode 100644 index 2dd0da72..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/mru.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "mru.h" - -#include -#include -#include - -#include "os/file.h" -#include "generic/callback.h" -#include "stream/stringstream.h" -#include "convert.h" - -#include "gtkutil/menu.h" -#include "map.h" -#include "qe3.h" - -#define MRU_MAX 4 -namespace { - GtkMenuItem *MRU_items[MRU_MAX]; - std::size_t MRU_used; - typedef CopiedString MRU_filename_t; - MRU_filename_t MRU_filenames[MRU_MAX]; - typedef const char* MRU_key_t; - MRU_key_t MRU_keys[MRU_MAX] = { "File0", "File1", "File2", "File3" }; -} - -inline const char* MRU_GetText(std::size_t index) -{ - return MRU_filenames[index].c_str(); -} - -class EscapedMnemonic -{ - StringBuffer m_buffer; -public: - EscapedMnemonic(std::size_t capacity) : m_buffer(capacity) - { - m_buffer.push_back('_'); - } - const char* c_str() const - { - return m_buffer.c_str(); - } - void push_back(char c) // not escaped - { - m_buffer.push_back(c); - } - std::size_t write(const char* buffer, std::size_t length) - { - for(const char* end = buffer + length; buffer != end; ++buffer) - { - if(*buffer == '_') - { - m_buffer.push_back('_'); - } - - m_buffer.push_back(*buffer); - } - return length; - } -}; - -template -inline EscapedMnemonic& operator<<(EscapedMnemonic& ostream, const T& t) -{ - return ostream_write(ostream, t); -} - - -void MRU_updateWidget(std::size_t index, const char *filename) -{ - EscapedMnemonic mnemonic(64); - mnemonic << Unsigned(index + 1) << "- " << filename; - gtk_label_set_text_with_mnemonic(GTK_LABEL(gtk_bin_get_child(GTK_BIN(MRU_items[index]))), mnemonic.c_str()); -} - -void MRU_SetText(std::size_t index, const char *filename) -{ - MRU_filenames[index] = filename; - MRU_updateWidget(index, filename); -} - -void MRU_AddFile (const char *str) -{ - std::size_t i; - const char* text; - - // check if file is already in our list - for (i = 0; i < MRU_used; i++) - { - text = MRU_GetText (i); - - if (strcmp (text, str) == 0) - { - // reorder menu - for(; i > 0; i--) - MRU_SetText(i, MRU_GetText (i-1)); - - MRU_SetText(0, str); - - return; - } - } - - if (MRU_used < MRU_MAX) - MRU_used++; - - // move items down - for (i = MRU_used-1; i > 0; i--) - MRU_SetText (i, MRU_GetText (i-1)); - - MRU_SetText (0, str); - gtk_widget_set_sensitive(GTK_WIDGET(MRU_items[0]), TRUE); - gtk_widget_show(GTK_WIDGET(MRU_items[MRU_used-1])); -} - -void MRU_Init() -{ - if(MRU_used > MRU_MAX) - MRU_used = MRU_MAX; -} - -void MRU_AddWidget(GtkMenuItem *widget, std::size_t pos) -{ - if(pos < MRU_MAX) - { - MRU_items[pos] = widget; - if(pos < MRU_used) - { - MRU_updateWidget(pos, MRU_GetText(pos)); - gtk_widget_set_sensitive(GTK_WIDGET(MRU_items[0]), TRUE); - gtk_widget_show(GTK_WIDGET(MRU_items[pos])); - } - } -} - -void MRU_Activate (std::size_t index) -{ - char text[1024]; - strcpy(text, MRU_GetText(index)); - - if (file_readable(text)) //\todo Test 'map load succeeds' instead of 'file is readable'. - { - MRU_AddFile (text); - Map_RegionOff(); - Map_Free(); - Map_LoadFile (text); - } - else - { - MRU_used--; - - for (std::size_t i = index; i < MRU_used; i++) - MRU_SetText (i, MRU_GetText (i+1)); - - if (MRU_used == 0) - { - gtk_label_set_text(GTK_LABEL(GTK_BIN(MRU_items[0])->child), "Recent Files"); - gtk_widget_set_sensitive(GTK_WIDGET(MRU_items[0]), FALSE); - } - else - { - gtk_widget_hide(GTK_WIDGET(MRU_items[MRU_used])); - } - } -} - - -class LoadMRU -{ - std::size_t m_number; -public: - LoadMRU(std::size_t number) - : m_number(number) - { - } - void load() - { - if (ConfirmModified("Open Map")) - { - MRU_Activate(m_number - 1); - } - } -}; - -typedef MemberCaller LoadMRUCaller; - -LoadMRU g_load_mru1(1); -LoadMRU g_load_mru2(2); -LoadMRU g_load_mru3(3); -LoadMRU g_load_mru4(4); - -void MRU_constructMenu(GtkMenu* menu) -{ - { - GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_1", LoadMRUCaller(g_load_mru1)); - gtk_widget_set_sensitive(GTK_WIDGET(item), FALSE); - MRU_AddWidget(item, 0); - } - { - GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_2", LoadMRUCaller(g_load_mru2)); - gtk_widget_hide(GTK_WIDGET(item)); - MRU_AddWidget(item, 1); - } - { - GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_3", LoadMRUCaller(g_load_mru3)); - gtk_widget_hide(GTK_WIDGET(item)); - MRU_AddWidget(item, 2); - } - { - GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_4", LoadMRUCaller(g_load_mru4)); - gtk_widget_hide(GTK_WIDGET(item)); - MRU_AddWidget(item, 3); - } -} - -#include "preferencesystem.h" -#include "stringio.h" - -void MRU_Construct() -{ - GlobalPreferenceSystem().registerPreference("Count", SizeImportStringCaller(MRU_used), SizeExportStringCaller(MRU_used)); - - for(std::size_t i = 0; i != MRU_MAX; ++i) - { - GlobalPreferenceSystem().registerPreference(MRU_keys[i], CopiedStringImportStringCaller(MRU_filenames[i]), CopiedStringExportStringCaller(MRU_filenames[i])); - } - - MRU_Init(); -} -void MRU_Destroy() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/mru.h b/misc/mediasource/extra/netradiant-src/radiant/mru.h deleted file mode 100644 index 010e99b7..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/mru.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_MRU_H) -#define INCLUDED_MRU_H - -void MRU_AddFile (const char *str); - -typedef struct _GtkMenu GtkMenu; -void MRU_constructMenu(GtkMenu* menu); - -void MRU_Construct(); -void MRU_Destroy(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/multimon.cpp b/misc/mediasource/extra/netradiant-src/radiant/multimon.cpp deleted file mode 100644 index acc756fd..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/multimon.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "multimon.h" - -#include "debugging/debugging.h" - -#include "gtkutil/window.h" -#include "preferences.h" - - -multimon_globals_t g_multimon_globals; - -LatchedBool g_Multimon_enableSysMenuPopups(false, "Floating windows sysmenu icons"); - -void MultiMonitor_constructPreferences(PreferencesPage& page) -{ - GtkWidget* primary_monitor = page.appendCheckBox("Multi Monitor", "Start on Primary Monitor", g_multimon_globals.m_bStartOnPrimMon); - GtkWidget* popup = page.appendCheckBox( - "", "Disable system menu on popup windows", - LatchedBoolImportCaller(g_Multimon_enableSysMenuPopups), - BoolExportCaller(g_Multimon_enableSysMenuPopups.m_latched) - ); - Widget_connectToggleDependency(popup, primary_monitor); -} - -#include "preferencesystem.h" -#include "stringio.h" - -#include - -namespace -{ - GdkRectangle primaryMonitor; -} - -void PositionWindowOnPrimaryScreen(WindowPosition& position) -{ - if( position.w >= primaryMonitor.width - 12 ) - { - position.w = primaryMonitor.width - 12; - } - if( position.h >= primaryMonitor.height - 24 ) - { - position.h = primaryMonitor.height - 48; - } - if( position.x <= primaryMonitor.x || position.x + position.w >= (primaryMonitor.x + primaryMonitor.width) - 12 ) - { - position.x = primaryMonitor.x + 6; - } - if( position.y <= primaryMonitor.y || position.y + position.h >= (primaryMonitor.y + primaryMonitor.height) - 48 ) - { - position.y = primaryMonitor.y + 24; - } -} - -void MultiMon_Construct() -{ - // detect multiple monitors - - GdkScreen* screen = gdk_display_get_default_screen(gdk_display_get_default()); - gint m = gdk_screen_get_n_monitors(screen); - globalOutputStream() << "default screen has " << m << " monitors\n"; - for(int j = 0; j != m; ++j) - { - GdkRectangle geom; - gdk_screen_get_monitor_geometry(screen, j, &geom); - globalOutputStream() << "monitor " << j << " geometry: " << geom.x << ", " << geom.y << ", " << geom.width << ", " << geom.height << "\n"; - if(j == 0) - { - // I am making the assumption that monitor 0 is always the primary monitor on win32. Tested on WinXP with gtk+-2.4. - primaryMonitor = geom; - } - } - - if(m > 1) - { - g_multimon_globals.m_bStartOnPrimMon = true; - } - - GlobalPreferenceSystem().registerPreference("StartOnPrimMon", BoolImportStringCaller(g_multimon_globals.m_bStartOnPrimMon), BoolExportStringCaller(g_multimon_globals.m_bStartOnPrimMon)); - GlobalPreferenceSystem().registerPreference("NoSysMenuPopups", BoolImportStringCaller(g_Multimon_enableSysMenuPopups.m_latched), BoolExportStringCaller(g_Multimon_enableSysMenuPopups.m_latched)); - - g_Multimon_enableSysMenuPopups.useLatched(); - - PreferencesDialog_addInterfacePreferences(FreeCaller1()); -} -void MultiMon_Destroy() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/multimon.h b/misc/mediasource/extra/netradiant-src/radiant/multimon.h deleted file mode 100644 index f14d3633..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/multimon.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_MULTIMON_H) -#define INCLUDED_MULTIMON_H - -struct WindowPosition; - -void PositionWindowOnPrimaryScreen(WindowPosition& position); - -struct multimon_globals_t -{ - bool m_bStartOnPrimMon; - - multimon_globals_t() : - m_bStartOnPrimMon(false) - { - } -}; - -extern multimon_globals_t g_multimon_globals; - -#if defined(WIN32) -void MultiMon_Construct(); -void MultiMon_Destroy(); -#else -inline void MultiMon_Construct() -{ -} -inline void MultiMon_Destroy() -{ -} -#endif - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/nullmodel.cpp b/misc/mediasource/extra/netradiant-src/radiant/nullmodel.cpp deleted file mode 100644 index ed2333b4..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/nullmodel.cpp +++ /dev/null @@ -1,214 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "nullmodel.h" - -#include "debugging/debugging.h" - -#include "iscenegraph.h" -#include "irender.h" -#include "iselection.h" -#include "iundo.h" -#include "ientity.h" -#include "ireference.h" -#include "igl.h" -#include "cullable.h" -#include "renderable.h" -#include "selectable.h" - -#include "math/frustum.h" -#include "scenelib.h" -#include "instancelib.h" -#include "entitylib.h" - -class NullModel : -public Bounded, -public Cullable -{ - Shader* m_state; - AABB m_aabb_local; - RenderableSolidAABB m_aabb_solid; - RenderableWireframeAABB m_aabb_wire; -public: - NullModel() : m_aabb_local(Vector3(0, 0, 0), Vector3(8, 8, 8)), m_aabb_solid(m_aabb_local), m_aabb_wire(m_aabb_local) - { - m_state = GlobalShaderCache().capture(""); - } - ~NullModel() - { - GlobalShaderCache().release(""); - } - - VolumeIntersectionValue intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const - { - return volume.TestAABB(m_aabb_local, localToWorld); - } - - const AABB& localAABB() const - { - return m_aabb_local; - } - - void renderSolid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - renderer.SetState(m_state, Renderer::eFullMaterials); - renderer.addRenderable(m_aabb_solid, localToWorld); - } - void renderWireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - renderer.addRenderable(m_aabb_wire, localToWorld); - } - - void testSelect(Selector& selector, SelectionTest& test, const Matrix4& localToWorld) - { - test.BeginMesh(localToWorld); - - SelectionIntersection best; - aabb_testselect(m_aabb_local, test, best); - if(best.valid()) - { - selector.addIntersection(best); - } - } -}; - -class NullModelInstance : public scene::Instance, public Renderable, public SelectionTestable -{ - class TypeCasts - { - InstanceTypeCastTable m_casts; - public: - TypeCasts() - { - InstanceContainedCast::install(m_casts); - InstanceContainedCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - } - InstanceTypeCastTable& get() - { - return m_casts; - } - }; - - NullModel& m_nullmodel; -public: - - typedef LazyStatic StaticTypeCasts; - - Bounded& get(NullType) - { - return m_nullmodel; - } - Cullable& get(NullType) - { - return m_nullmodel; - } - - NullModelInstance(const scene::Path& path, scene::Instance* parent, NullModel& nullmodel) : - Instance(path, parent, this, StaticTypeCasts::instance().get()), - m_nullmodel(nullmodel) - { - } - - void renderSolid(Renderer& renderer, const VolumeTest& volume) const - { - m_nullmodel.renderSolid(renderer, volume, Instance::localToWorld()); - } - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const - { - m_nullmodel.renderWireframe(renderer, volume, Instance::localToWorld()); - } - - void testSelect(Selector& selector, SelectionTest& test) - { - m_nullmodel.testSelect(selector, test, Instance::localToWorld()); - } -}; - -class NullModelNode : public scene::Node::Symbiot, public scene::Instantiable -{ - class TypeCasts - { - NodeTypeCastTable m_casts; - public: - TypeCasts() - { - NodeStaticCast::install(m_casts); - } - NodeTypeCastTable& get() - { - return m_casts; - } - }; - - - scene::Node m_node; - InstanceSet m_instances; - NullModel m_nullmodel; -public: - - typedef LazyStatic StaticTypeCasts; - - NullModelNode() : m_node(this, this, StaticTypeCasts::instance().get()) - { - m_node.m_isRoot = true; - } - - void release() - { - delete this; - } - scene::Node& node() - { - return m_node; - } - - scene::Instance* create(const scene::Path& path, scene::Instance* parent) - { - return new NullModelInstance(path, parent, m_nullmodel); - } - 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); - } - scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) - { - return m_instances.erase(observer, path); - } -}; - -NodeSmartReference NewNullModel() -{ - return NodeSmartReference((new NullModelNode)->node()); -} - -void NullModel_construct() -{ -} -void NullModel_destroy() -{ -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/nullmodel.h b/misc/mediasource/extra/netradiant-src/radiant/nullmodel.h deleted file mode 100644 index 2713fb08..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/nullmodel.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (INCLUDED_NULLMODEL_H) -#define INCLUDED_NULLMODEL_H - -namespace scene -{ - class Node; -} - -#include "generic/referencecounted.h" -typedef SmartReference > NodeSmartReference; -NodeSmartReference NewNullModel(); - -void NullModel_construct(); -void NullModel_destroy(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/parse.cpp b/misc/mediasource/extra/netradiant-src/radiant/parse.cpp deleted file mode 100644 index 8e3fd5c0..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/parse.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "parse.h" - -#include "script/scripttokeniser.h" -#include "script/scripttokenwriter.h" - -class ScriptLibraryAPI -{ - _QERScripLibTable m_scriptlibrary; -public: - typedef _QERScripLibTable Type; - STRING_CONSTANT(Name, "*"); - - ScriptLibraryAPI() - { - m_scriptlibrary.m_pfnNewScriptTokeniser = &NewScriptTokeniser; - m_scriptlibrary.m_pfnNewSimpleTokeniser = &NewSimpleTokeniser; - m_scriptlibrary.m_pfnNewSimpleTokenWriter = &NewSimpleTokenWriter; - } - _QERScripLibTable* getTable() - { - return &m_scriptlibrary; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule ScriptLibraryModule; -typedef Static StaticScriptLibraryModule; -StaticRegisterModule staticRegisterScriptLibrary(StaticScriptLibraryModule::instance()); diff --git a/misc/mediasource/extra/netradiant-src/radiant/parse.h b/misc/mediasource/extra/netradiant-src/radiant/parse.h deleted file mode 100644 index 3e64113e..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/parse.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_PARSE_H) -#define INCLUDED_PARSE_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/patch.cpp b/misc/mediasource/extra/netradiant-src/radiant/patch.cpp deleted file mode 100644 index ac96240f..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patch.cpp +++ /dev/null @@ -1,2919 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "patch.h" - -#include -#include "preferences.h" -#include "brush_primit.h" -#include "signal/signal.h" - - -Signal0 g_patchTextureChangedCallbacks; - -void Patch_addTextureChangedCallback(const SignalHandler& handler) -{ - g_patchTextureChangedCallbacks.connectLast(handler); -} - -void Patch_textureChanged() -{ - g_patchTextureChangedCallbacks(); -} - - -Shader* PatchInstance::m_state_selpoint; -Shader* Patch::m_state_ctrl; -Shader* Patch::m_state_lattice; -EPatchType Patch::m_type; - - -std::size_t MAX_PATCH_WIDTH = 0; -std::size_t MAX_PATCH_HEIGHT = 0; - -int g_PatchSubdivideThreshold = 4; - -void BezierCurveTree_Delete(BezierCurveTree *pCurve) -{ - if(pCurve) - { - BezierCurveTree_Delete(pCurve->left); - BezierCurveTree_Delete(pCurve->right); - delete pCurve; - } -} - -std::size_t BezierCurveTree_Setup(BezierCurveTree *pCurve, std::size_t index, std::size_t stride) -{ - if(pCurve) - { - if(pCurve->left && pCurve->right) - { - index = BezierCurveTree_Setup(pCurve->left, index, stride); - pCurve->index = index*stride; - index++; - index = BezierCurveTree_Setup(pCurve->right, index, stride); - } - else - { - pCurve->index = BEZIERCURVETREE_MAX_INDEX; - } - } - - return index; -} - -bool BezierCurve_IsCurved(BezierCurve *pCurve) -{ - Vector3 vTemp(vector3_subtracted(pCurve->right, pCurve->left)); - Vector3 v1(vector3_subtracted(pCurve->crd, pCurve->left)); - Vector3 v2(vector3_subtracted(pCurve->right, pCurve->crd)); - - if(vector3_equal(v1, g_vector3_identity) || vector3_equal(vTemp, v1)) // return 0 if 1->2 == 0 or 1->2 == 1->3 - return false; - - vector3_normalise(v1); - vector3_normalise(v2); - if(vector3_equal(v1, v2)) - return false; - - Vector3 v3(vTemp); - const double width = vector3_length(v3); - vector3_scale(v3, 1.0 / width); - - if(vector3_equal(v1, v3) && vector3_equal(v2, v3)) - return false; - - const double angle = acos(vector3_dot(v1, v2)) / c_pi; - - const double index = width * angle; - - if(index > static_cast(g_PatchSubdivideThreshold)) - return true; - return false; -} - -void BezierInterpolate(BezierCurve *pCurve) -{ - pCurve->left = vector3_mid(pCurve->left, pCurve->crd); - pCurve->right = vector3_mid(pCurve->crd, pCurve->right); - pCurve->crd = vector3_mid(pCurve->left, pCurve->right); -} - -const std::size_t PATCH_MAX_SUBDIVISION_DEPTH = 16; - -void BezierCurveTree_FromCurveList(BezierCurveTree *pTree, GSList *pCurveList, std::size_t depth = 0) -{ - GSList *pLeftList = 0; - GSList *pRightList = 0; - BezierCurve *pCurve, *pLeftCurve, *pRightCurve; - bool bSplit = false; - - for (GSList *l = pCurveList; l; l = l->next) - { - pCurve = (BezierCurve *)(l->data); - if(bSplit || BezierCurve_IsCurved(pCurve)) - { - bSplit = true; - pLeftCurve = new BezierCurve; - pRightCurve = new BezierCurve; - pLeftCurve->left = pCurve->left; - pRightCurve->right = pCurve->right; - BezierInterpolate(pCurve); - pLeftCurve->crd = pCurve->left; - pRightCurve->crd = pCurve->right; - pLeftCurve->right = pCurve->crd; - pRightCurve->left = pCurve->crd; - - pLeftList = g_slist_prepend(pLeftList, pLeftCurve); - pRightList = g_slist_prepend(pRightList, pRightCurve); - } - } - - if(pLeftList != 0 && pRightList != 0 && depth != PATCH_MAX_SUBDIVISION_DEPTH) - { - pTree->left = new BezierCurveTree; - pTree->right = new BezierCurveTree; - BezierCurveTree_FromCurveList(pTree->left, pLeftList, depth + 1); - BezierCurveTree_FromCurveList(pTree->right, pRightList, depth + 1); - - for(GSList* l = pLeftList; l != 0; l = g_slist_next(l)) - { - delete (BezierCurve*)l->data; - } - - for(GSList* l = pRightList; l != 0; l = g_slist_next(l)) - { - delete (BezierCurve*)l->data; - } - - g_slist_free(pLeftList); - g_slist_free(pRightList); - } - else - { - pTree->left = 0; - pTree->right = 0; - } -} - - -int Patch::m_CycleCapIndex = 0; - - -void Patch::setDims (std::size_t w, std::size_t h) -{ - if((w%2)==0) - w -= 1; - ASSERT_MESSAGE(w <= MAX_PATCH_WIDTH, "patch too wide"); - if(w > MAX_PATCH_WIDTH) - w = MAX_PATCH_WIDTH; - else if(w < MIN_PATCH_WIDTH) - w = MIN_PATCH_WIDTH; - - if((h%2)==0) - m_height -= 1; - ASSERT_MESSAGE(h <= MAX_PATCH_HEIGHT, "patch too tall"); - if(h > MAX_PATCH_HEIGHT) - h = MAX_PATCH_HEIGHT; - else if(h < MIN_PATCH_HEIGHT) - h = MIN_PATCH_HEIGHT; - - m_width = w; m_height = h; - - if(m_width * m_height != m_ctrl.size()) - { - m_ctrl.resize(m_width * m_height); - onAllocate(m_ctrl.size()); - } -} - -inline const Colour4b& colour_for_index(std::size_t i, std::size_t width) -{ - return (i%2 || (i/width)%2) ? colour_inside : colour_corner; -} - -inline bool float_valid(float f) -{ - return f == f; -} - -bool Patch::isValid() const -{ - if(!m_width || !m_height) - { - return false; - } - - for(const_iterator i = m_ctrl.begin(); i != m_ctrl.end(); ++i) - { - if(!float_valid((*i).m_vertex.x()) - || !float_valid((*i).m_vertex.y()) - || !float_valid((*i).m_vertex.z()) - || !float_valid((*i).m_texcoord.x()) - || !float_valid((*i).m_texcoord.y())) - { - globalErrorStream() << "patch has invalid control points\n"; - return false; - } - } - return true; -} - -void Patch::UpdateCachedData() -{ - m_ctrl_vertices.clear(); - m_lattice_indices.clear(); - - if(!isValid()) - { - m_tess.m_numStrips = 0; - m_tess.m_lenStrips = 0; - m_tess.m_nArrayHeight = 0; - m_tess.m_nArrayWidth = 0; - m_tess.m_curveTreeU.resize(0); - m_tess.m_curveTreeV.resize(0); - m_tess.m_indices.resize(0); - m_tess.m_vertices.resize(0); - m_tess.m_arrayHeight.resize(0); - m_tess.m_arrayWidth.resize(0); - m_aabb_local = AABB(); - return; - } - - BuildTesselationCurves(ROW); - BuildTesselationCurves(COL); - BuildVertexArray(); - AccumulateBBox(); - - IndexBuffer ctrl_indices; - - m_lattice_indices.reserve(((m_width * (m_height - 1)) + (m_height * (m_width - 1))) << 1); - ctrl_indices.reserve(m_ctrlTransformed.size()); - { - UniqueVertexBuffer inserter(m_ctrl_vertices); - for(iterator i = m_ctrlTransformed.begin(); i != m_ctrlTransformed.end(); ++i) - { - ctrl_indices.insert(inserter.insert(pointvertex_quantised(PointVertex(reinterpret_cast((*i).m_vertex), colour_for_index(i - m_ctrlTransformed.begin(), m_width))))); - } - } - { - for(IndexBuffer::iterator i = ctrl_indices.begin(); i != ctrl_indices.end(); ++i) - { - if(std::size_t(i - ctrl_indices.begin()) % m_width) - { - m_lattice_indices.insert(*(i - 1)); - m_lattice_indices.insert(*i); - } - if(std::size_t(i - ctrl_indices.begin()) >= m_width) - { - m_lattice_indices.insert(*(i - m_width)); - m_lattice_indices.insert(*i); - } - } - } - -#if 0 - { - Array::iterator first = m_tess.m_indices.begin(); - for(std::size_t s=0; s::iterator last = first + m_tess.m_lenStrips; - - for(Array::iterator i(first); i+2 != last; i += 2) - { - ArbitraryMeshTriangle_sumTangents(m_tess.m_vertices[*(i+0)], m_tess.m_vertices[*(i+1)], m_tess.m_vertices[*(i+2)]); - ArbitraryMeshTriangle_sumTangents(m_tess.m_vertices[*(i+2)], m_tess.m_vertices[*(i+1)], m_tess.m_vertices[*(i+3)]); - } - - first = last; - } - - for(Array::iterator i = m_tess.m_vertices.begin(); i != m_tess.m_vertices.end(); ++i) - { - vector3_normalise(reinterpret_cast((*i).tangent)); - vector3_normalise(reinterpret_cast((*i).bitangent)); - } - } -#endif - - SceneChangeNotify(); -} - -void Patch::InvertMatrix() -{ - undoSave(); - - PatchControlArray_invert(m_ctrl, m_width, m_height); - - controlPointsChanged(); -} - -void Patch::TransposeMatrix() -{ - undoSave(); - - { - Array tmp(m_width * m_height); - copy_ctrl(tmp.data(), m_ctrl.data(), m_ctrl.data() + m_width * m_height); - - PatchControlIter from = tmp.data(); - for(std::size_t h = 0; h != m_height; ++h) - { - PatchControlIter to = m_ctrl.data() + h; - for(std::size_t w = 0; w != m_width; ++w, ++from, to += m_height) - { - *to = *from; - } - } - } - - { - std::size_t tmp = m_width; - m_width = m_height; - m_height = tmp; - } - - controlPointsChanged(); -} - -void Patch::Redisperse(EMatrixMajor mt) -{ - std::size_t w, h, width, height, row_stride, col_stride; - PatchControl* p1, * p2, * p3; - - undoSave(); - - switch(mt) - { - case COL: - width = (m_width-1)>>1; - height = m_height; - col_stride = 1; - row_stride = m_width; - break; - case ROW: - width = (m_height-1)>>1; - height = m_width; - col_stride = m_width; - row_stride = 1; - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return; - } - - for(h=0;hm_vertex = vector3_mid(p1->m_vertex, p3->m_vertex); - p1 = p3; - } - } - - controlPointsChanged(); -} - -void Patch::Smooth(EMatrixMajor mt) -{ - std::size_t w, h, width, height, row_stride, col_stride; - bool wrap; - PatchControl* p1, * p2, * p3, * p2b; - - undoSave(); - - switch(mt) - { - case COL: - width = (m_width-1)>>1; - height = m_height; - col_stride = 1; - row_stride = m_width; - break; - case ROW: - width = (m_height-1)>>1; - height = m_width; - col_stride = m_width; - row_stride = 1; - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return; - } - - wrap = true; - for(h=0;hm_vertex << " and " << p2->m_vertex << "\n"; - if(vector3_length_squared(vector3_subtracted(p1->m_vertex, p2->m_vertex)) > 1.0) - { - //globalErrorStream() << "too far\n"; - wrap = false; - break; - } - } - - for(h=0;hm_vertex = vector3_mid(p1->m_vertex, p3->m_vertex); - p1 = p3; - } - if(wrap) - { - p1 = m_ctrl.data()+(h*row_stride)+(2*width-1)*col_stride; - p2 = m_ctrl.data()+(h*row_stride); - p2b = m_ctrl.data()+(h*row_stride)+(2*width)*col_stride; - p3 = m_ctrl.data()+(h*row_stride)+col_stride; - p2->m_vertex = p2b->m_vertex = vector3_mid(p1->m_vertex, p3->m_vertex); - } - } - - controlPointsChanged(); -} - -void Patch::InsertRemove(bool bInsert, bool bColumn, bool bFirst) -{ - undoSave(); - - if(bInsert) - { - if(bColumn && (m_width + 2 <= MAX_PATCH_WIDTH)) - InsertPoints(COL, bFirst); - else if(m_height + 2 <= MAX_PATCH_HEIGHT) - InsertPoints(ROW, bFirst); - } - else - { - if(bColumn && (m_width - 2 >= MIN_PATCH_WIDTH)) - RemovePoints(COL, bFirst); - else if(m_height - 2 >= MIN_PATCH_HEIGHT) - RemovePoints(ROW, bFirst); - } - - controlPointsChanged(); -} - -Patch* Patch::MakeCap(Patch* patch, EPatchCap eType, EMatrixMajor mt, bool bFirst) -{ - std::size_t i, width, height; - - switch(mt) - { - case ROW: - width = m_width; - height = m_height; - break; - case COL: - width = m_height; - height = m_width; - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return 0; - } - - Array p(width); - - std::size_t nIndex = (bFirst) ? 0 : height-1; - if(mt == ROW) - { - for (i=0; iConstructSeam(eType, p.data(), width); - return patch; -} - -void Patch::FlipTexture(int nAxis) -{ - undoSave(); - - for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) - { - (*i).m_texcoord[nAxis] = -(*i).m_texcoord[nAxis]; - } - - controlPointsChanged(); -} - -void Patch::TranslateTexture(float s, float t) -{ - undoSave(); - - s = -1 * s / m_state->getTexture().width; - t = t / m_state->getTexture().height; - - for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) - { - (*i).m_texcoord[0] += s; - (*i).m_texcoord[1] += t; - } - - controlPointsChanged(); -} - -void Patch::ScaleTexture(float s, float t) -{ - undoSave(); - - for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) - { - (*i).m_texcoord[0] *= s; - (*i).m_texcoord[1] *= t; - } - - controlPointsChanged(); -} - -void Patch::RotateTexture(float angle) -{ - undoSave(); - - const float s = static_cast(sin(degrees_to_radians(angle))); - const float c = static_cast(cos(degrees_to_radians(angle))); - - for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) - { - const float x = (*i).m_texcoord[0]; - const float y = (*i).m_texcoord[1]; - (*i).m_texcoord[0] = (x * c) - (y * s); - (*i).m_texcoord[1] = (y * c) + (x * s); - } - - controlPointsChanged(); -} - - -void Patch::SetTextureRepeat(float s, float t) -{ - std::size_t w, h; - float si, ti, sc, tc; - PatchControl *pDest; - - undoSave(); - - si = s / (float)(m_width - 1); - ti = t / (float)(m_height - 1); - - pDest = m_ctrl.data(); - for (h=0, tc = 0.0f; hm_texcoord[0] = sc; - pDest->m_texcoord[1] = tc; - pDest++; - } - } - - controlPointsChanged(); -} - -/* -void Patch::SetTextureInfo(texdef_t *pt) -{ - if(pt->getShift()[0] || pt->getShift()[1]) - TranslateTexture (pt->getShift()[0], pt->getShift()[1]); - else if(pt->getScale()[0] || pt->getScale()[1]) - { - if(pt->getScale()[0] == 0.0f) pt->setScale(0, 1.0f); - if(pt->getScale()[1] == 0.0f) pt->setScale(1, 1.0f); - ScaleTexture (pt->getScale()[0], pt->getScale()[1]); - } - else if(pt->rotate) - RotateTexture (pt->rotate); -} -*/ - -inline int texture_axis(const Vector3& normal) -{ - // axis dominance order: Z, X, Y - return (normal.x() >= normal.y()) ? (normal.x() > normal.z()) ? 0 : 2 : (normal.y() > normal.z()) ? 1 : 2; -} - -void Patch::CapTexture() -{ - const PatchControl& p1 = m_ctrl[m_width]; - const PatchControl& p2 = m_ctrl[m_width*(m_height-1)]; - const PatchControl& p3 = m_ctrl[(m_width*m_height)-1]; - - - Vector3 normal(g_vector3_identity); - - { - Vector3 tmp(vector3_cross( - vector3_subtracted(p2.m_vertex, m_ctrl[0].m_vertex), - vector3_subtracted(p3.m_vertex, m_ctrl[0].m_vertex) - )); - if(!vector3_equal(tmp, g_vector3_identity)) - { - vector3_add(normal, tmp); - } - } - { - Vector3 tmp(vector3_cross( - vector3_subtracted(p1.m_vertex, p3.m_vertex), - vector3_subtracted(m_ctrl[0].m_vertex, p3.m_vertex) - )); - if(!vector3_equal(tmp, g_vector3_identity)) - { - vector3_add(normal, tmp); - } - } - - ProjectTexture(texture_axis(normal)); -} - -// uses longest parallel chord to calculate texture coords for each row/col -void Patch::NaturalTexture() -{ - undoSave(); - - { - float fSize = (float)m_state->getTexture().width * Texdef_getDefaultTextureScale(); - - double texBest = 0; - double tex = 0; - PatchControl* pWidth = m_ctrl.data(); - for (std::size_t w=0; wm_texcoord[0] = static_cast(tex); - } - - if(w+1 == m_width) - break; - - { - PatchControl* pHeight = pWidth; - for (std::size_t h=0; hm_vertex, (pHeight+1)->m_vertex)); - double length = tex + (vector3_length(v) / fSize); - if(fabs(length) > texBest) texBest = length; - } - } - - tex=texBest; - } - } - - { - float fSize = -(float)m_state->getTexture().height * Texdef_getDefaultTextureScale(); - - double texBest = 0; - double tex = 0; - PatchControl* pHeight = m_ctrl.data(); - for (std::size_t h=0; hm_texcoord[1] = static_cast(tex); - } - - if(h+1 == m_height) - break; - - { - PatchControl* pWidth = pHeight; - for (std::size_t w=0; wm_vertex, (pWidth+m_width)->m_vertex)); - double length = tex + (vector3_length(v) / fSize); - if(fabs(length) > texBest) texBest = length; - } - } - - tex=texBest; - } - } - - controlPointsChanged(); -} - - - -// private: - -void Patch::AccumulateBBox() -{ - m_aabb_local = AABB(); - - for(PatchControlArray::iterator i = m_ctrlTransformed.begin(); i != m_ctrlTransformed.end(); ++i) - { - aabb_extend_by_point_safe(m_aabb_local, (*i).m_vertex); - } - - m_boundsChanged(); - m_lightsChanged(); -} - -void Patch::InsertPoints(EMatrixMajor mt, bool bFirst) -{ - std::size_t width, height, row_stride, col_stride; - - switch(mt) - { - case ROW: - col_stride = 1; - row_stride = m_width; - width = m_width; - height = m_height; - break; - case COL: - col_stride = m_width; - row_stride = 1; - width = m_height; - height = m_width; - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return; - } - - std::size_t pos = 0; - { - PatchControl* p1 = m_ctrl.data(); - /* - if(GlobalSelectionSystem().countSelected() != 0) - { - scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); - PatchInstance* patch = Instance_getPatch(instance); - patch->m_selectable.isSelected(); - } - */ - for(std::size_t w = 0; w != width; ++w, p1 += col_stride) - { - { - PatchControl* p2 = p1; - for(std::size_t h = 1; h < height; h += 2, p2 += 2 * row_stride) - { - if(0)//p2->m_selectable.isSelected()) - { - pos = h; - break; - } - } - if(pos != 0) - { - break; - } - } - - { - PatchControl* p2 = p1; - for(std::size_t h = 0; h < height; h += 2, p2 += 2 * row_stride) - { - if(0)//p2->m_selectable.isSelected()) - { - pos = h; - break; - } - } - if(pos != 0) - { - break; - } - } - } - } - - Array tmp(m_ctrl); - - std::size_t row_stride2, col_stride2; - switch(mt) - { - case ROW: - setDims(m_width, m_height+2); - col_stride2 = 1; - row_stride2 = m_width; - break; - case COL: - setDims(m_width+2, m_height); - col_stride2 = m_width; - row_stride2 = 1; - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return; - } - if(bFirst) - { - pos = height - 1; - } - else - { - pos = 2; - } - - if(pos >= height) - { - if(bFirst) - { - pos = height - 1; - } - else - { - pos = 2; - } - } - else if(pos == 0) - { - pos = 2; - } - else if(pos % 2) - { - ++pos; - } - - - for(std::size_t w = 0; w != width; ++w) - { - PatchControl* p1 = tmp.data() + (w*col_stride); - PatchControl* p2 = m_ctrl.data() + (w*col_stride2); - for(std::size_t h = 0; h != height; ++h, p2 += row_stride2, p1 += row_stride) - { - if(h == pos) - { - p2 += 2 * row_stride2; - } - *p2 = *p1; - } - - p1 = tmp.data() + (w*col_stride+pos*row_stride); - p2 = m_ctrl.data() + (w*col_stride2+pos*row_stride2); - - PatchControl* r2a = (p2+row_stride2); - PatchControl* r2b = (p2-row_stride2); - PatchControl* c2a = (p1-2*row_stride); - PatchControl* c2b = (p1-row_stride); - - // set two new row points - *(p2+2*row_stride2) = *p1; - *r2a = *c2b; - - for(std::size_t i = 0; i != 3; ++i) - { - r2a->m_vertex[i] = float_mid(c2b->m_vertex[i], p1->m_vertex[i]); - - r2b->m_vertex[i] = float_mid(c2a->m_vertex[i], c2b->m_vertex[i]); - - p2->m_vertex[i] = float_mid(r2a->m_vertex[i], r2b->m_vertex[i]); - } - for(std::size_t i = 0; i != 2; ++i) - { - r2a->m_texcoord[i] = float_mid(c2b->m_texcoord[i], p1->m_texcoord[i]); - - r2b->m_texcoord[i] = float_mid(c2a->m_texcoord[i], c2b->m_texcoord[i]); - - p2->m_texcoord[i] = float_mid(r2a->m_texcoord[i], r2b->m_texcoord[i]); - } - } -} - -void Patch::RemovePoints(EMatrixMajor mt, bool bFirst) -{ - std::size_t width, height, row_stride, col_stride; - - switch(mt) - { - case ROW: - col_stride = 1; - row_stride = m_width; - width = m_width; - height = m_height; - break; - case COL: - col_stride = m_width; - row_stride = 1; - width = m_height; - height = m_width; - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return; - } - - std::size_t pos = 0; - { - PatchControl* p1 = m_ctrl.data(); - for(std::size_t w = 0; w != width; ++w, p1 += col_stride) - { - { - PatchControl* p2 = p1; - for(std::size_t h=1; h < height; h += 2, p2 += 2 * row_stride) - { - if(0)//p2->m_selectable.isSelected()) - { - pos = h; - break; - } - } - if(pos != 0) - { - break; - } - } - - { - PatchControl* p2 = p1; - for(std::size_t h=0; h < height; h += 2, p2 += 2 * row_stride) - { - if(0)//p2->m_selectable.isSelected()) - { - pos = h; - break; - } - } - if(pos != 0) - { - break; - } - } - } - } - - Array tmp(m_ctrl); - - std::size_t row_stride2, col_stride2; - switch(mt) - { - case ROW: - setDims(m_width, m_height-2); - col_stride2 = 1; - row_stride2 = m_width; - break; - case COL: - setDims(m_width-2, m_height); - col_stride2 = m_width; - row_stride2 = 1; - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return; - } - if(bFirst) - { - pos=height-3; - } - else - { - pos=2; - } - if(pos >= height) - { - if(bFirst) - { - pos=height-3; - } - else - { - pos=2; - } - } - else if(pos == 0) - { - pos=2; - } - else if(pos > height - 3) - { - pos = height - 3; - } - else if(pos % 2) - { - ++pos; - } - - for(std::size_t w = 0; w != width; w++) - { - PatchControl* p1 = tmp.data() + (w*col_stride); - PatchControl* p2 = m_ctrl.data() + (w*col_stride2); - for(std::size_t h = 0; h != height; ++h, p2 += row_stride2, p1 += row_stride) - { - if(h == pos) - { - p1 += 2 * row_stride2; h += 2; - } - *p2 = *p1; - } - - p1 = tmp.data() + (w*col_stride+pos*row_stride); - p2 = m_ctrl.data() + (w*col_stride2+pos*row_stride2); - - for(std::size_t i=0; i<3; i++) - { - (p2-row_stride2)->m_vertex[i] = ((p1+2*row_stride)->m_vertex[i]+(p1-2*row_stride)->m_vertex[i]) * 0.5f; - - (p2-row_stride2)->m_vertex[i] = (p2-row_stride2)->m_vertex[i]+(2.0f * ((p1)->m_vertex[i]-(p2-row_stride2)->m_vertex[i])); - } - for(std::size_t i=0; i<2; i++) - { - (p2-row_stride2)->m_texcoord[i] = ((p1+2*row_stride)->m_texcoord[i]+(p1-2*row_stride)->m_texcoord[i]) * 0.5f; - - (p2-row_stride2)->m_texcoord[i] = (p2-row_stride2)->m_texcoord[i]+(2.0f * ((p1)->m_texcoord[i]-(p2-row_stride2)->m_texcoord[i])); - } - } -} - -void Patch::ConstructSeam(EPatchCap eType, Vector3* p, std::size_t width) -{ - switch(eType) - { - case eCapIBevel: - { - setDims(3, 3); - m_ctrl[0].m_vertex = p[0]; - m_ctrl[1].m_vertex = p[1]; - m_ctrl[2].m_vertex = p[1]; - m_ctrl[3].m_vertex = p[1]; - m_ctrl[4].m_vertex = p[1]; - m_ctrl[5].m_vertex = p[1]; - m_ctrl[6].m_vertex = p[2]; - m_ctrl[7].m_vertex = p[1]; - m_ctrl[8].m_vertex = p[1]; - } - break; - case eCapBevel: - { - setDims(3, 3); - Vector3 p3(vector3_added(p[2], vector3_subtracted(p[0], p[1]))); - m_ctrl[0].m_vertex = p3; - m_ctrl[1].m_vertex = p3; - m_ctrl[2].m_vertex = p[2]; - m_ctrl[3].m_vertex = p3; - m_ctrl[4].m_vertex = p3; - m_ctrl[5].m_vertex = p[1]; - m_ctrl[6].m_vertex = p3; - m_ctrl[7].m_vertex = p3; - m_ctrl[8].m_vertex = p[0]; - } - break; - case eCapEndCap: - { - Vector3 p5(vector3_mid(p[0], p[4])); - - setDims(3, 3); - m_ctrl[0].m_vertex = p[0]; - m_ctrl[1].m_vertex = p5; - m_ctrl[2].m_vertex = p[4]; - m_ctrl[3].m_vertex = p[1]; - m_ctrl[4].m_vertex = p[2]; - m_ctrl[5].m_vertex = p[3]; - m_ctrl[6].m_vertex = p[2]; - m_ctrl[7].m_vertex = p[2]; - m_ctrl[8].m_vertex = p[2]; - } - break; - case eCapIEndCap: - { - setDims(5, 3); - m_ctrl[0].m_vertex = p[4]; - m_ctrl[1].m_vertex = p[3]; - m_ctrl[2].m_vertex = p[2]; - m_ctrl[3].m_vertex = p[1]; - m_ctrl[4].m_vertex = p[0]; - m_ctrl[5].m_vertex = p[3]; - m_ctrl[6].m_vertex = p[3]; - m_ctrl[7].m_vertex = p[2]; - m_ctrl[8].m_vertex = p[1]; - m_ctrl[9].m_vertex = p[1]; - m_ctrl[10].m_vertex = p[3]; - m_ctrl[11].m_vertex = p[3]; - m_ctrl[12].m_vertex = p[2]; - m_ctrl[13].m_vertex = p[1]; - m_ctrl[14].m_vertex = p[1]; - } - break; - case eCapCylinder: - { - std::size_t mid = (width - 1) >> 1; - - bool degenerate = (mid % 2) != 0; - - std::size_t newHeight = mid + (degenerate ? 2 : 1); - - setDims(3, newHeight); - - if(degenerate) - { - ++mid; - for(std::size_t i = width; i != width + 2; ++i) - { - p[i] = p[width - 1]; - } - } - - { - PatchControl* pCtrl = m_ctrl.data(); - for(std::size_t i = 0; i != m_height; ++i, pCtrl += m_width) - { - pCtrl->m_vertex = p[i]; - } - } - { - PatchControl* pCtrl = m_ctrl.data() + 2; - std::size_t h = m_height - 1; - for(std::size_t i = 0; i != m_height; ++i, pCtrl += m_width) - { - pCtrl->m_vertex = p[h + (h - i)]; - } - } - - Redisperse(COL); - } - break; - default: - ERROR_MESSAGE("invalid patch-cap type"); - return; - } - CapTexture(); - controlPointsChanged(); -} - -void Patch::ProjectTexture(int nAxis) -{ - undoSave(); - - int s, t; - - switch (nAxis) - { - case 2: - s = 0; - t = 1; - break; - case 0: - s = 1; - t = 2; - break; - case 1: - s = 0; - t = 2; - break; - default: - ERROR_MESSAGE("invalid axis"); - return; - } - - float fWidth = 1 / (m_state->getTexture().width * Texdef_getDefaultTextureScale()); - float fHeight = 1 / (m_state->getTexture().height * -Texdef_getDefaultTextureScale()); - - for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) - { - (*i).m_texcoord[0] = (*i).m_vertex[s] * fWidth; - (*i).m_texcoord[1] = (*i).m_vertex[t] * fHeight; - } - - controlPointsChanged(); -} - -void Patch::constructPlane(const AABB& aabb, int axis, std::size_t width, std::size_t height) -{ - setDims(width, height); - - int x, y, z; - switch(axis) - { - case 2: x=0; y=1; z=2; break; - case 1: x=0; y=2; z=1; break; - case 0: x=1; y=2; z=0; break; - default: - ERROR_MESSAGE("invalid view-type"); - return; - } - - if(m_width < MIN_PATCH_WIDTH || m_width > MAX_PATCH_WIDTH) m_width = 3; - if(m_height < MIN_PATCH_HEIGHT || m_height > MAX_PATCH_HEIGHT) m_height = 3; - - Vector3 vStart; - vStart[x] = aabb.origin[x] - aabb.extents[x]; - vStart[y] = aabb.origin[y] - aabb.extents[y]; - vStart[z] = aabb.origin[z]; - - float xAdj = fabsf((vStart[x] - (aabb.origin[x] + aabb.extents[x])) / (float)(m_width - 1)); - float yAdj = fabsf((vStart[y] - (aabb.origin[y] + aabb.extents[y])) / (float)(m_height - 1)); - - Vector3 vTmp; - vTmp[z] = vStart[z]; - PatchControl* pCtrl = m_ctrl.data(); - - vTmp[y]=vStart[y]; - for (std::size_t h=0; hm_vertex = vTmp; - vTmp[x]+=xAdj; - } - vTmp[y]+=yAdj; - } - - NaturalTexture(); -} - -void Patch::ConstructPrefab(const AABB& aabb, EPatchPrefab eType, int axis, std::size_t width, std::size_t height) -{ - Vector3 vPos[3]; - - if(eType != ePlane) - { - vPos[0] = vector3_subtracted(aabb.origin, aabb.extents); - vPos[1] = aabb.origin; - vPos[2] = vector3_added(aabb.origin, aabb.extents); - } - - if(eType == ePlane) - { - constructPlane(aabb, axis, width, height); - } - else if(eType == eSqCylinder - || eType == eCylinder - || eType == eDenseCylinder - || eType == eVeryDenseCylinder - || eType == eCone - || eType == eSphere) - { - unsigned char *pIndex; - unsigned char pCylIndex[] = - { - 0, 0, - 1, 0, - 2, 0, - 2, 1, - 2, 2, - 1, 2, - 0, 2, - 0, 1, - 0, 0 - }; - - - PatchControl *pStart; - switch(eType) - { - case eSqCylinder: setDims(9, 3); - pStart = m_ctrl.data(); - break; - case eDenseCylinder: - case eVeryDenseCylinder: - case eCylinder: - setDims(9, 3); - pStart = m_ctrl.data() + 1; - break; - case eCone: setDims(9, 3); - pStart = m_ctrl.data() + 1; - break; - case eSphere: - setDims(9, 5); - pStart = m_ctrl.data() + (9+1); - break; - default: - ERROR_MESSAGE("this should be unreachable"); - return; - } - - for(std::size_t h=0; h<3; h++, pStart+=9) - { - pIndex = pCylIndex; - PatchControl* pCtrl = pStart; - for(std::size_t w=0; w<8; w++, pCtrl++) - { - pCtrl->m_vertex[0] = vPos[pIndex[0]][0]; - pCtrl->m_vertex[1] = vPos[pIndex[1]][1]; - pCtrl->m_vertex[2] = vPos[h][2]; - pIndex+=2; - } - } - - switch(eType) - { - case eSqCylinder: - { - PatchControl* pCtrl=m_ctrl.data(); - for(std::size_t h=0; h<3; h++, pCtrl+=9) - { - pCtrl[8].m_vertex = pCtrl[0].m_vertex; - } - } - break; - case eDenseCylinder: - case eVeryDenseCylinder: - case eCylinder: - { - PatchControl* pCtrl=m_ctrl.data(); - for (std::size_t h=0; h<3; h++, pCtrl+=9) - { - pCtrl[0].m_vertex = pCtrl[8].m_vertex; - } - } - break; - case eCone: - { - PatchControl* pCtrl=m_ctrl.data(); - for (std::size_t h=0; h<2; h++, pCtrl+=9) - { - pCtrl[0].m_vertex = pCtrl[8].m_vertex; - } - } - { - PatchControl* pCtrl=m_ctrl.data()+9*2; - for (std::size_t w=0; w<9; w++, pCtrl++) - { - pCtrl->m_vertex[0] = vPos[1][0]; - pCtrl->m_vertex[1] = vPos[1][1]; - pCtrl->m_vertex[2] = vPos[2][2]; - } - } - break; - case eSphere: - { - PatchControl* pCtrl=m_ctrl.data()+9; - for (std::size_t h=0; h<3; h++, pCtrl+=9) - { - pCtrl[0].m_vertex = pCtrl[8].m_vertex; - } - } - { - PatchControl* pCtrl = m_ctrl.data(); - for (std::size_t w=0; w<9; w++, pCtrl++) - { - pCtrl->m_vertex[0] = vPos[1][0]; - pCtrl->m_vertex[1] = vPos[1][1]; - pCtrl->m_vertex[2] = vPos[0][2]; - } - } - { - PatchControl* pCtrl = m_ctrl.data()+(9*4); - for (std::size_t w=0; w<9; w++, pCtrl++) - { - pCtrl->m_vertex[0] = vPos[1][0]; - pCtrl->m_vertex[1] = vPos[1][1]; - pCtrl->m_vertex[2] = vPos[2][2]; - } - } - break; - default: - ERROR_MESSAGE("this should be unreachable"); - return; - } - } - else if (eType == eBevel) - { - unsigned char *pIndex; - unsigned char pBevIndex[] = - { - 0, 0, - 2, 0, - 2, 2, - }; - - setDims(3, 3); - - PatchControl* pCtrl = m_ctrl.data(); - for(std::size_t h=0; h<3; h++) - { - pIndex=pBevIndex; - for(std::size_t w=0; w<3; w++, pIndex+=2, pCtrl++) - { - pCtrl->m_vertex[0] = vPos[pIndex[0]][0]; - pCtrl->m_vertex[1] = vPos[pIndex[1]][1]; - pCtrl->m_vertex[2] = vPos[h][2]; - } - } - } - else if(eType == eEndCap) - { - unsigned char *pIndex; - unsigned char pEndIndex[] = - { - 2, 0, - 2, 2, - 1, 2, - 0, 2, - 0, 0, - }; - - setDims(5, 3); - - PatchControl* pCtrl = m_ctrl.data(); - for(std::size_t h=0; h<3; h++) - { - pIndex=pEndIndex; - for(std::size_t w=0; w<5; w++, pIndex+=2, pCtrl++) - { - pCtrl->m_vertex[0] = vPos[pIndex[0]][0]; - pCtrl->m_vertex[1] = vPos[pIndex[1]][1]; - pCtrl->m_vertex[2] = vPos[h][2]; - } - } - } - - if(eType == eDenseCylinder) - { - InsertRemove(true, false, true); - } - - if(eType == eVeryDenseCylinder) - { - InsertRemove(true, false, false); - InsertRemove(true, false, true); - } - - NaturalTexture(); -} - -void Patch::RenderDebug(RenderStateFlags state) const -{ - for (std::size_t i = 0; inormal)); - glTexCoord2fv(texcoord2f_to_array((m_tess.m_vertices.data() + m_tess.m_indices[i*m_tess.m_lenStrips+j])->texcoord)); - glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + m_tess.m_indices[i*m_tess.m_lenStrips+j])->vertex)); - } - glEnd(); - } -} - -void RenderablePatchSolid::RenderNormals() const -{ - const std::size_t width = m_tess.m_numStrips+1; - const std::size_t height = m_tess.m_lenStrips>>1; - glBegin(GL_LINES); - for(std::size_t i=0;ivertex), - vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->normal), 8) - ) - ); - glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex)); - glVertex3fv(&vNormal[0]); - } - { - Vector3 vNormal( - vector3_added( - vertex3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->vertex), - vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->tangent), 8) - ) - ); - glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex)); - glVertex3fv(&vNormal[0]); - } - { - Vector3 vNormal( - vector3_added( - vertex3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->vertex), - vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->bitangent), 8) - ) - ); - glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex)); - glVertex3fv(&vNormal[0]); - } - } - } - glEnd(); -} - -#define DEGEN_0a 0x01 -#define DEGEN_1a 0x02 -#define DEGEN_2a 0x04 -#define DEGEN_0b 0x08 -#define DEGEN_1b 0x10 -#define DEGEN_2b 0x20 -#define SPLIT 0x40 -#define AVERAGE 0x80 - - -unsigned int subarray_get_degen(PatchControlIter subarray, std::size_t strideU, std::size_t strideV) -{ - unsigned int nDegen = 0; - const PatchControl* p1; - const PatchControl* p2; - - p1 = subarray; - p2 = p1 + strideU; - if(vector3_equal(p1->m_vertex, p2->m_vertex)) - nDegen |= DEGEN_0a; - p1 = p2; - p2 = p1 + strideU; - if(vector3_equal(p1->m_vertex, p2->m_vertex)) - nDegen |= DEGEN_0b; - - p1 = subarray + strideV; - p2 = p1 + strideU; - if(vector3_equal(p1->m_vertex, p2->m_vertex)) - nDegen |= DEGEN_1a; - p1 = p2; - p2 = p1 + strideU; - if(vector3_equal(p1->m_vertex, p2->m_vertex)) - nDegen |= DEGEN_1b; - - p1 = subarray + (strideV << 1); - p2 = p1 + strideU; - if(vector3_equal(p1->m_vertex, p2->m_vertex)) - nDegen |= DEGEN_2a; - p1 = p2; - p2 = p1 + strideU; - if(vector3_equal(p1->m_vertex, p2->m_vertex)) - nDegen |= DEGEN_2b; - - return nDegen; -} - - -inline void deCasteljau3(const Vector3& P0, const Vector3& P1, const Vector3& P2, Vector3& P01, Vector3& P12, Vector3& P012) -{ - P01 = vector3_mid(P0, P1); - P12 = vector3_mid(P1, P2); - P012 = vector3_mid(P01, P12); -} - -inline void BezierInterpolate3( const Vector3& start, Vector3& left, Vector3& mid, Vector3& right, const Vector3& end ) -{ - left = vector3_mid(start, mid); - right = vector3_mid(mid, end); - mid = vector3_mid(left, right); -} - -inline void BezierInterpolate2( const Vector2& start, Vector2& left, Vector2& mid, Vector2& right, const Vector2& end ) -{ - left[0]= float_mid(start[0], mid[0]); - left[1] = float_mid(start[1], mid[1]); - right[0] = float_mid(mid[0], end[0]); - right[1] = float_mid(mid[1], end[1]); - mid[0] = float_mid(left[0], right[0]); - mid[1] = float_mid(left[1], right[1]); -} - - -inline Vector2& texcoord_for_index(Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].texcoord); -} - -inline Vector3& vertex_for_index(Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].vertex); -} - -inline Vector3& normal_for_index(Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].normal); -} - -inline Vector3& tangent_for_index(Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].tangent); -} - -inline Vector3& bitangent_for_index(Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].bitangent); -} - -inline const Vector2& texcoord_for_index(const Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].texcoord); -} - -inline const Vector3& vertex_for_index(const Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].vertex); -} - -inline const Vector3& normal_for_index(const Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].normal); -} - -inline const Vector3& tangent_for_index(const Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].tangent); -} - -inline const Vector3& bitangent_for_index(const Array& vertices, std::size_t index) -{ - return reinterpret_cast(vertices[index].bitangent); -} - -#include "math/curve.h" - -inline PatchControl QuadraticBezier_evaluate(const PatchControl* firstPoint, double t) -{ - PatchControl result = { Vector3(0, 0, 0), Vector2(0, 0) }; - double denominator = 0; - - { - double weight = BernsteinPolynomial::apply(t); - vector3_add(result.m_vertex, vector3_scaled(firstPoint[0].m_vertex, weight)); - vector2_add(result.m_texcoord, vector2_scaled(firstPoint[0].m_texcoord, weight)); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply(t); - vector3_add(result.m_vertex, vector3_scaled(firstPoint[1].m_vertex, weight)); - vector2_add(result.m_texcoord, vector2_scaled(firstPoint[1].m_texcoord, weight)); - denominator += weight; - } - { - double weight = BernsteinPolynomial::apply(t); - vector3_add(result.m_vertex, vector3_scaled(firstPoint[2].m_vertex, weight)); - vector2_add(result.m_texcoord, vector2_scaled(firstPoint[2].m_texcoord, weight)); - denominator += weight; - } - - vector3_divide(result.m_vertex, denominator); - vector2_divide(result.m_texcoord, denominator); - return result; -} - -inline Vector3 vector3_linear_interpolated(const Vector3& a, const Vector3& b, double t) -{ - return vector3_added(vector3_scaled(a, 1.0 - t), vector3_scaled(b, t)); -} - -inline Vector2 vector2_linear_interpolated(const Vector2& a, const Vector2& b, double t) -{ - return vector2_added(vector2_scaled(a, 1.0 - t), vector2_scaled(b, t)); -} - -void normalise_safe(Vector3& normal) -{ - if(!vector3_equal(normal, g_vector3_identity)) - { - vector3_normalise(normal); - } -} - -inline void QuadraticBezier_evaluate(const PatchControl& a, const PatchControl& b, const PatchControl& c, double t, PatchControl& point, PatchControl& left, PatchControl& right) -{ - left.m_vertex = vector3_linear_interpolated(a.m_vertex, b.m_vertex, t); - left.m_texcoord = vector2_linear_interpolated(a.m_texcoord, b.m_texcoord, t); - right.m_vertex = vector3_linear_interpolated(b.m_vertex, c.m_vertex, t); - right.m_texcoord = vector2_linear_interpolated(b.m_texcoord, c.m_texcoord, t); - point.m_vertex = vector3_linear_interpolated(left.m_vertex, right.m_vertex, t); - point.m_texcoord = vector2_linear_interpolated(left.m_texcoord, right.m_texcoord, t); -} - -void Patch::TesselateSubMatrixFixed(ArbitraryMeshVertex* vertices, std::size_t strideX, std::size_t strideY, unsigned int nFlagsX, unsigned int nFlagsY, PatchControl* subMatrix[3][3]) -{ - double incrementU = 1.0 / m_subdivisions_x; - double incrementV = 1.0 / m_subdivisions_y; - const std::size_t width = m_subdivisions_x + 1; - const std::size_t height = m_subdivisions_y + 1; - - for(std::size_t i = 0; i != width; ++i) - { - double tU = (i + 1 == width) ? 1 : i * incrementU; - PatchControl pointX[3]; - PatchControl leftX[3]; - PatchControl rightX[3]; - QuadraticBezier_evaluate(*subMatrix[0][0], *subMatrix[0][1], *subMatrix[0][2], tU, pointX[0], leftX[0], rightX[0]); - QuadraticBezier_evaluate(*subMatrix[1][0], *subMatrix[1][1], *subMatrix[1][2], tU, pointX[1], leftX[1], rightX[1]); - QuadraticBezier_evaluate(*subMatrix[2][0], *subMatrix[2][1], *subMatrix[2][2], tU, pointX[2], leftX[2], rightX[2]); - - ArbitraryMeshVertex* p = vertices + i * strideX; - for(std::size_t j = 0; j != height; ++j) - { - if((j == 0 || j + 1 == height) && (i == 0 || i + 1 == width)) - { - } - else - { - double tV = (j + 1 == height) ? 1 : j * incrementV; - - PatchControl pointY[3]; - PatchControl leftY[3]; - PatchControl rightY[3]; - QuadraticBezier_evaluate(*subMatrix[0][0], *subMatrix[1][0], *subMatrix[2][0], tV, pointY[0], leftY[0], rightY[0]); - QuadraticBezier_evaluate(*subMatrix[0][1], *subMatrix[1][1], *subMatrix[2][1], tV, pointY[1], leftY[1], rightY[1]); - QuadraticBezier_evaluate(*subMatrix[0][2], *subMatrix[1][2], *subMatrix[2][2], tV, pointY[2], leftY[2], rightY[2]); - - PatchControl point; - PatchControl left; - PatchControl right; - QuadraticBezier_evaluate(pointX[0], pointX[1], pointX[2], tV, point, left, right); - PatchControl up; - PatchControl down; - QuadraticBezier_evaluate(pointY[0], pointY[1], pointY[2], tU, point, up, down); - - vertex3f_to_vector3(p->vertex) = point.m_vertex; - texcoord2f_to_vector2(p->texcoord) = point.m_texcoord; - - ArbitraryMeshVertex a, b, c; - - a.vertex = vertex3f_for_vector3(left.m_vertex); - a.texcoord = texcoord2f_for_vector2(left.m_texcoord); - b.vertex = vertex3f_for_vector3(right.m_vertex); - b.texcoord = texcoord2f_for_vector2(right.m_texcoord); - - if(i != 0) - { - c.vertex = vertex3f_for_vector3(up.m_vertex); - c.texcoord = texcoord2f_for_vector2(up.m_texcoord); - } - else - { - c.vertex = vertex3f_for_vector3(down.m_vertex); - c.texcoord = texcoord2f_for_vector2(down.m_texcoord); - } - - Vector3 normal = vector3_normalised(vector3_cross(right.m_vertex - left.m_vertex, up.m_vertex - down.m_vertex)); - - Vector3 tangent, bitangent; - ArbitraryMeshTriangle_calcTangents(a, b, c, tangent, bitangent); - vector3_normalise(tangent); - vector3_normalise(bitangent); - - if(((nFlagsX & AVERAGE) != 0 && i == 0) || ((nFlagsY & AVERAGE) != 0 && j == 0)) - { - normal3f_to_vector3(p->normal) = vector3_normalised(vector3_added(normal3f_to_vector3(p->normal), normal)); - normal3f_to_vector3(p->tangent) = vector3_normalised(vector3_added(normal3f_to_vector3(p->tangent), tangent)); - normal3f_to_vector3(p->bitangent) = vector3_normalised(vector3_added(normal3f_to_vector3(p->bitangent), bitangent)); - } - else - { - normal3f_to_vector3(p->normal) = normal; - normal3f_to_vector3(p->tangent) = tangent; - normal3f_to_vector3(p->bitangent) = bitangent; - } - } - - p += strideY; - } - } -} - -void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY, - std::size_t offStartX, std::size_t offStartY, - std::size_t offEndX, std::size_t offEndY, - std::size_t nFlagsX, std::size_t nFlagsY, - Vector3& left, Vector3& mid, Vector3& right, - Vector2& texLeft, Vector2& texMid, Vector2& texRight, - bool bTranspose ) -{ - int newFlagsX, newFlagsY; - - Vector3 tmp; - Vector3 vertex_0_0, vertex_0_1, vertex_1_0, vertex_1_1, vertex_2_0, vertex_2_1; - Vector2 texTmp; - Vector2 texcoord_0_0, texcoord_0_1, texcoord_1_0, texcoord_1_1, texcoord_2_0, texcoord_2_1; - - { - // texcoords - - BezierInterpolate2( texcoord_for_index(m_tess.m_vertices, offStartX + offStartY), - texcoord_0_0, - texcoord_for_index(m_tess.m_vertices, BX->index + offStartY), - texcoord_0_1, - texcoord_for_index(m_tess.m_vertices, offEndX + offStartY) ); - - - BezierInterpolate2( texcoord_for_index(m_tess.m_vertices, offStartX + offEndY), - texcoord_2_0, - texcoord_for_index(m_tess.m_vertices, BX->index + offEndY), - texcoord_2_1, - texcoord_for_index(m_tess.m_vertices, offEndX + offEndY) ); - - texTmp = texMid; - - BezierInterpolate2(texLeft, - texcoord_1_0, - texTmp, - texcoord_1_1, - texRight); - - if(!BezierCurveTree_isLeaf(BY)) - { - texcoord_for_index(m_tess.m_vertices, BX->index + BY->index) = texTmp; - } - - - if(!BezierCurveTree_isLeaf(BX->left)) - { - texcoord_for_index(m_tess.m_vertices, BX->left->index + offStartY) = texcoord_0_0; - texcoord_for_index(m_tess.m_vertices, BX->left->index + offEndY) = texcoord_2_0; - - if(!BezierCurveTree_isLeaf(BY)) - { - texcoord_for_index(m_tess.m_vertices, BX->left->index + BY->index) = texcoord_1_0; - } - } - if(!BezierCurveTree_isLeaf(BX->right)) - { - texcoord_for_index(m_tess.m_vertices, BX->right->index + offStartY) = texcoord_0_1; - texcoord_for_index(m_tess.m_vertices, BX->right->index + offEndY) = texcoord_2_1; - - if(!BezierCurveTree_isLeaf(BY)) - { - texcoord_for_index(m_tess.m_vertices, BX->right->index + BY->index) = texcoord_1_1; - } - } - - - // verts - - BezierInterpolate3( vertex_for_index(m_tess.m_vertices, offStartX + offStartY), - vertex_0_0, - vertex_for_index(m_tess.m_vertices, BX->index + offStartY), - vertex_0_1, - vertex_for_index(m_tess.m_vertices, offEndX + offStartY) ); - - - BezierInterpolate3( vertex_for_index(m_tess.m_vertices, offStartX + offEndY), - vertex_2_0, - vertex_for_index(m_tess.m_vertices, BX->index + offEndY), - vertex_2_1, - vertex_for_index(m_tess.m_vertices, offEndX + offEndY) ); - - - tmp = mid; - - BezierInterpolate3( left, - vertex_1_0, - tmp, - vertex_1_1, - right ); - - if(!BezierCurveTree_isLeaf(BY)) - { - vertex_for_index(m_tess.m_vertices, BX->index + BY->index) = tmp; - } - - - if(!BezierCurveTree_isLeaf(BX->left)) - { - vertex_for_index(m_tess.m_vertices, BX->left->index + offStartY) = vertex_0_0; - vertex_for_index(m_tess.m_vertices, BX->left->index + offEndY) = vertex_2_0; - - if(!BezierCurveTree_isLeaf(BY)) - { - vertex_for_index(m_tess.m_vertices, BX->left->index + BY->index) = vertex_1_0; - } - } - if(!BezierCurveTree_isLeaf(BX->right)) - { - vertex_for_index(m_tess.m_vertices, BX->right->index + offStartY) = vertex_0_1; - vertex_for_index(m_tess.m_vertices, BX->right->index + offEndY) = vertex_2_1; - - if(!BezierCurveTree_isLeaf(BY)) - { - vertex_for_index(m_tess.m_vertices, BX->right->index + BY->index) = vertex_1_1; - } - } - - // normals - - if(nFlagsX & SPLIT) - { - ArbitraryMeshVertex a, b, c; - Vector3 tangentU; - - if(!(nFlagsX & DEGEN_0a) || !(nFlagsX & DEGEN_0b)) - { - tangentU = vector3_subtracted(vertex_0_1, vertex_0_0); - a.vertex = vertex3f_for_vector3(vertex_0_0); - a.texcoord = texcoord2f_for_vector2(texcoord_0_0); - c.vertex = vertex3f_for_vector3(vertex_0_1); - c.texcoord = texcoord2f_for_vector2(texcoord_0_1); - } - else if(!(nFlagsX & DEGEN_1a) || !(nFlagsX & DEGEN_1b)) - { - tangentU = vector3_subtracted(vertex_1_1, vertex_1_0); - a.vertex = vertex3f_for_vector3(vertex_1_0); - a.texcoord = texcoord2f_for_vector2(texcoord_1_0); - c.vertex = vertex3f_for_vector3(vertex_1_1); - c.texcoord = texcoord2f_for_vector2(texcoord_1_1); - } - else - { - tangentU = vector3_subtracted(vertex_2_1, vertex_2_0); - a.vertex = vertex3f_for_vector3(vertex_2_0); - a.texcoord = texcoord2f_for_vector2(texcoord_2_0); - c.vertex = vertex3f_for_vector3(vertex_2_1); - c.texcoord = texcoord2f_for_vector2(texcoord_2_1); - } - - Vector3 tangentV; - - if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_1a) && (nFlagsY & DEGEN_2a)) - { - tangentV = vector3_subtracted(vertex_for_index(m_tess.m_vertices, BX->index + offEndY), tmp); - b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offEndY].vertex; - b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offEndY].texcoord; - } - else - { - tangentV = vector3_subtracted(tmp, vertex_for_index(m_tess.m_vertices, BX->index + offStartY)); - b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offStartY].vertex; - b.texcoord = texcoord2f_for_vector2(texTmp); //m_tess.m_vertices[BX->index + offStartY].texcoord; - } - - - Vector3 normal, s, t; - ArbitraryMeshVertex& v = m_tess.m_vertices[offStartY + BX->index]; - Vector3& p = normal3f_to_vector3(v.normal); - Vector3& ps = normal3f_to_vector3(v.tangent); - Vector3& pt = normal3f_to_vector3(v.bitangent); - - if(bTranspose) - { - normal = vector3_cross(tangentV, tangentU); - } - else - { - normal = vector3_cross(tangentU, tangentV); - } - normalise_safe(normal); - - ArbitraryMeshTriangle_calcTangents(a, b, c, s, t); - normalise_safe(s); - normalise_safe(t); - - if(nFlagsX & AVERAGE) - { - p = vector3_normalised(vector3_added(p, normal)); - ps = vector3_normalised(vector3_added(ps, s)); - pt = vector3_normalised(vector3_added(pt, t)); - } - else - { - p = normal; - ps = s; - pt = t; - } - } - - { - ArbitraryMeshVertex a, b, c; - Vector3 tangentU; - - if(!(nFlagsX & DEGEN_2a) || !(nFlagsX & DEGEN_2b)) - { - tangentU = vector3_subtracted(vertex_2_1, vertex_2_0); - a.vertex = vertex3f_for_vector3(vertex_2_0); - a.texcoord = texcoord2f_for_vector2(texcoord_2_0); - c.vertex = vertex3f_for_vector3(vertex_2_1); - c.texcoord = texcoord2f_for_vector2(texcoord_2_1); - } - else if(!(nFlagsX & DEGEN_1a) || !(nFlagsX & DEGEN_1b)) - { - tangentU = vector3_subtracted(vertex_1_1, vertex_1_0); - a.vertex = vertex3f_for_vector3(vertex_1_0); - a.texcoord = texcoord2f_for_vector2(texcoord_1_0); - c.vertex = vertex3f_for_vector3(vertex_1_1); - c.texcoord = texcoord2f_for_vector2(texcoord_1_1); - } - else - { - tangentU = vector3_subtracted(vertex_0_1, vertex_0_0); - a.vertex = vertex3f_for_vector3(vertex_0_0); - a.texcoord = texcoord2f_for_vector2(texcoord_0_0); - c.vertex = vertex3f_for_vector3(vertex_0_1); - c.texcoord = texcoord2f_for_vector2(texcoord_0_1); - } - - Vector3 tangentV; - - if((nFlagsY & DEGEN_0b) && (nFlagsY & DEGEN_1b) && (nFlagsY & DEGEN_2b)) - { - tangentV = vector3_subtracted(tmp, vertex_for_index(m_tess.m_vertices, BX->index + offStartY)); - b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offStartY].vertex; - b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offStartY].texcoord; - } - else - { - tangentV = vector3_subtracted(vertex_for_index(m_tess.m_vertices, BX->index + offEndY), tmp); - b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offEndY].vertex; - b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offEndY].texcoord; - } - - ArbitraryMeshVertex& v = m_tess.m_vertices[offEndY+BX->index]; - Vector3& p = normal3f_to_vector3(v.normal); - Vector3& ps = normal3f_to_vector3(v.tangent); - Vector3& pt = normal3f_to_vector3(v.bitangent); - - if(bTranspose) - { - p = vector3_cross(tangentV, tangentU); - } - else - { - p = vector3_cross(tangentU, tangentV); - } - normalise_safe(p); - - ArbitraryMeshTriangle_calcTangents(a, b, c, ps, pt); - normalise_safe(ps); - normalise_safe(pt); - } - } - - - newFlagsX = newFlagsY = 0; - - if((nFlagsX & DEGEN_0a) && (nFlagsX & DEGEN_0b)) - { - newFlagsX |= DEGEN_0a; - newFlagsX |= DEGEN_0b; - } - if((nFlagsX & DEGEN_1a) && (nFlagsX & DEGEN_1b)) - { - newFlagsX |= DEGEN_1a; - newFlagsX |= DEGEN_1b; - } - if((nFlagsX & DEGEN_2a) && (nFlagsX & DEGEN_2b)) - { - newFlagsX |= DEGEN_2a; - newFlagsX |= DEGEN_2b; - } - if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_1a) && (nFlagsY & DEGEN_2a)) - { - newFlagsY |= DEGEN_0a; - newFlagsY |= DEGEN_1a; - newFlagsY |= DEGEN_2a; - } - if((nFlagsY & DEGEN_0b) && (nFlagsY & DEGEN_1b) && (nFlagsY & DEGEN_2b)) - { - newFlagsY |= DEGEN_0b; - newFlagsY |= DEGEN_1b; - newFlagsY |= DEGEN_2b; - } - - - //if((nFlagsX & DEGEN_0a) && (nFlagsX & DEGEN_1a) && (nFlagsX & DEGEN_2a)) { newFlagsX |= DEGEN_0a; newFlagsX |= DEGEN_1a; newFlagsX |= DEGEN_2a; } - //if((nFlagsX & DEGEN_0b) && (nFlagsX & DEGEN_1b) && (nFlagsX & DEGEN_2b)) { newFlagsX |= DEGEN_0b; newFlagsX |= DEGEN_1b; newFlagsX |= DEGEN_2b; } - - newFlagsX |= (nFlagsX & SPLIT); - newFlagsX |= (nFlagsX & AVERAGE); - - if(!BezierCurveTree_isLeaf(BY)) - { - { - int nTemp = newFlagsY; - - if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_0b)) - { - newFlagsY |= DEGEN_0a; - newFlagsY |= DEGEN_0b; - } - newFlagsY |= (nFlagsY & SPLIT); - newFlagsY |= (nFlagsY & AVERAGE); - - Vector3& p = vertex_for_index(m_tess.m_vertices, BX->index+BY->index); - Vector3 vTemp(p); - - Vector2& p2 = texcoord_for_index(m_tess.m_vertices, BX->index+BY->index); - Vector2 stTemp(p2); - - TesselateSubMatrix( BY, BX->left, - offStartY, offStartX, - offEndY, BX->index, - newFlagsY, newFlagsX, - vertex_0_0, vertex_1_0, vertex_2_0, - texcoord_0_0, texcoord_1_0, texcoord_2_0, - !bTranspose ); - - newFlagsY = nTemp; - p = vTemp; - p2 = stTemp; - } - - if((nFlagsY & DEGEN_2a) && (nFlagsY & DEGEN_2b)) { newFlagsY |= DEGEN_2a; newFlagsY |= DEGEN_2b; } - - TesselateSubMatrix( BY, BX->right, - offStartY, BX->index, - offEndY, offEndX, - newFlagsY, newFlagsX, - vertex_0_1, vertex_1_1, vertex_2_1, - texcoord_0_1, texcoord_1_1, texcoord_2_1, - !bTranspose ); - } - else - { - if(!BezierCurveTree_isLeaf(BX->left)) - { - TesselateSubMatrix( BX->left, BY, - offStartX, offStartY, - BX->index, offEndY, - newFlagsX, newFlagsY, - left, vertex_1_0, tmp, - texLeft, texcoord_1_0, texTmp, - bTranspose ); - } - - if(!BezierCurveTree_isLeaf(BX->right)) - { - TesselateSubMatrix( BX->right, BY, - BX->index, offStartY, - offEndX, offEndY, - newFlagsX, newFlagsY, - tmp, vertex_1_1, right, - texTmp, texcoord_1_1, texRight, - bTranspose ); - } - } - -} - -void Patch::BuildTesselationCurves(EMatrixMajor major) -{ - std::size_t nArrayStride, length, cross, strideU, strideV; - switch(major) - { - case ROW: - nArrayStride = 1; - length = (m_width - 1) >> 1; - cross = m_height; - strideU = 1; - strideV = m_width; - - if(!m_patchDef3) - { - BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeU); - } - - break; - case COL: - nArrayStride = m_tess.m_nArrayWidth; - length = (m_height - 1) >> 1; - cross = m_width; - strideU = m_width; - strideV = 1; - - if(!m_patchDef3) - { - BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeV); - } - - break; - default: - ERROR_MESSAGE("neither row-major nor column-major"); - return; - } - - Array arrayLength(length); - Array pCurveTree(length); - - std::size_t nArrayLength = 1; - - if(m_patchDef3) - { - for(Array::iterator i = arrayLength.begin(); i != arrayLength.end(); ++i) - { - *i = Array::value_type((major == ROW) ? m_subdivisions_x : m_subdivisions_y); - nArrayLength += *i; - } - } - else - { - // create a list of the horizontal control curves in each column of sub-patches - // adaptively tesselate each horizontal control curve in the list - // create a binary tree representing the combined tesselation of the list - for(std::size_t i = 0; i != length; ++i) - { - PatchControl* p1 = m_ctrlTransformed.data() + (i * 2 * strideU); - GSList* pCurveList = 0; - for(std::size_t j = 0; j < cross; j += 2) - { - PatchControl* p2 = p1+strideV; - PatchControl* p3 = p2+strideV; - - // directly taken from one row of control points - { - BezierCurve* pCurve = new BezierCurve; - pCurve->crd = (p1+strideU)->m_vertex; - pCurve->left = p1->m_vertex; - pCurve->right = (p1+(strideU<<1))->m_vertex; - pCurveList = g_slist_prepend(pCurveList, pCurve); - } - - if(j+2 >= cross) - { - break; - } - - // interpolated from three columns of control points - { - BezierCurve* pCurve = new BezierCurve; - pCurve->crd = vector3_mid((p1+strideU)->m_vertex, (p3+strideU)->m_vertex); - pCurve->left = vector3_mid(p1->m_vertex, p3->m_vertex); - pCurve->right = vector3_mid((p1+(strideU<<1))->m_vertex, (p3+(strideU<<1))->m_vertex); - - pCurve->crd = vector3_mid(pCurve->crd, (p2+strideU)->m_vertex); - pCurve->left = vector3_mid(pCurve->left, p2->m_vertex); - pCurve->right = vector3_mid(pCurve->right, (p2+(strideU<<1))->m_vertex); - pCurveList = g_slist_prepend(pCurveList, pCurve); - } - - p1 = p3; - } - - pCurveTree[i] = new BezierCurveTree; - BezierCurveTree_FromCurveList(pCurveTree[i], pCurveList); - for(GSList* l = pCurveList; l != 0; l = g_slist_next(l)) - { - delete static_cast((*l).data); - } - g_slist_free(pCurveList); - - // set up array indices for binary tree - // accumulate subarray width - arrayLength[i] = Array::value_type(BezierCurveTree_Setup(pCurveTree[i], nArrayLength, nArrayStride) - (nArrayLength - 1)); - // accumulate total array width - nArrayLength += arrayLength[i]; - } - } - - switch(major) - { - case ROW: - m_tess.m_nArrayWidth = nArrayLength; - std::swap(m_tess.m_arrayWidth, arrayLength); - - if(!m_patchDef3) - { - std::swap(m_tess.m_curveTreeU, pCurveTree); - } - break; - case COL: - m_tess.m_nArrayHeight = nArrayLength; - std::swap(m_tess.m_arrayHeight, arrayLength); - - if(!m_patchDef3) - { - std::swap(m_tess.m_curveTreeV, pCurveTree); - } - break; - } -} - -inline void vertex_assign_ctrl(ArbitraryMeshVertex& vertex, const PatchControl& ctrl) -{ - vertex.vertex = vertex3f_for_vector3(ctrl.m_vertex); - vertex.texcoord = texcoord2f_for_vector2(ctrl.m_texcoord); -} - -inline void vertex_clear_normal(ArbitraryMeshVertex& vertex) -{ - vertex.normal = Normal3f(0, 0, 0); - vertex.tangent = Normal3f(0, 0, 0); - vertex.bitangent = Normal3f(0, 0, 0); -} - -inline void tangents_remove_degenerate(Vector3 tangents[6], Vector2 textureTangents[6], unsigned int flags) -{ - if(flags & DEGEN_0a) - { - const std::size_t i = - (flags & DEGEN_0b) - ? (flags & DEGEN_1a) - ? (flags & DEGEN_1b) - ? (flags & DEGEN_2a) - ? 5 - : 4 - : 3 - : 2 - : 1; - tangents[0] = tangents[i]; - textureTangents[0] = textureTangents[i]; - } - if(flags & DEGEN_0b) - { - const std::size_t i = - (flags & DEGEN_0a) - ? (flags & DEGEN_1b) - ? (flags & DEGEN_1a) - ? (flags & DEGEN_2b) - ? 4 - : 5 - : 2 - : 3 - : 0; - tangents[1] = tangents[i]; - textureTangents[1] = textureTangents[i]; - } - if(flags & DEGEN_2a) - { - const std::size_t i = - (flags & DEGEN_2b) - ? (flags & DEGEN_1a) - ? (flags & DEGEN_1b) - ? (flags & DEGEN_0a) - ? 1 - : 0 - : 3 - : 2 - : 5; - tangents[4] = tangents[i]; - textureTangents[4] = textureTangents[i]; - } - if(flags & DEGEN_2b) - { - const std::size_t i = - (flags & DEGEN_2a) - ? (flags & DEGEN_1b) - ? (flags & DEGEN_1a) - ? (flags & DEGEN_0b) - ? 0 - : 1 - : 2 - : 3 - : 4; - tangents[5] = tangents[i]; - textureTangents[5] = textureTangents[i]; - } -} - -void bestTangents00(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) -{ - if(fabs(dot + length) < 0.001) // opposing direction = degenerate - { - if(!(degenerateFlags & DEGEN_1a)) // if this tangent is degenerate we cannot use it - { - index0 = 2; - index1 = 0; - } - else if(!(degenerateFlags & DEGEN_0b)) - { - index0 = 0; - index1 = 1; - } - else - { - index0 = 1; - index1 = 0; - } - } - else if(fabs(dot - length) < 0.001) // same direction = degenerate - { - if(degenerateFlags & DEGEN_0b) - { - index0 = 0; - index1 = 1; - } - else - { - index0 = 1; - index1 = 0; - } - } -} - -void bestTangents01(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) -{ - if(fabs(dot - length) < 0.001) // same direction = degenerate - { - if(!(degenerateFlags & DEGEN_1a)) // if this tangent is degenerate we cannot use it - { - index0 = 2; - index1 = 1; - } - else if(!(degenerateFlags & DEGEN_2b)) - { - index0 = 4; - index1 = 0; - } - else - { - index0 = 5; - index1 = 1; - } - } - else if(fabs(dot + length) < 0.001) // opposing direction = degenerate - { - if(degenerateFlags & DEGEN_2b) - { - index0 = 4; - index1 = 0; - } - else - { - index0 = 5; - index1 = 1; - } - } -} - -void bestTangents10(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) -{ - if(fabs(dot - length) < 0.001) // same direction = degenerate - { - if(!(degenerateFlags & DEGEN_1b)) // if this tangent is degenerate we cannot use it - { - index0 = 3; - index1 = 4; - } - else if(!(degenerateFlags & DEGEN_0a)) - { - index0 = 1; - index1 = 5; - } - else - { - index0 = 0; - index1 = 4; - } - } - else if(fabs(dot + length) < 0.001) // opposing direction = degenerate - { - if(degenerateFlags & DEGEN_0a) - { - index0 = 1; - index1 = 5; - } - else - { - index0 = 0; - index1 = 4; - } - } -} - -void bestTangents11(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) -{ - if(fabs(dot + length) < 0.001) // opposing direction = degenerate - { - if(!(degenerateFlags & DEGEN_1b)) // if this tangent is degenerate we cannot use it - { - index0 = 3; - index1 = 5; - } - else if(!(degenerateFlags & DEGEN_2a)) - { - index0 = 5; - index1 = 4; - } - else - { - index0 = 4; - index1 = 5; - } - } - else if(fabs(dot - length) < 0.001) // same direction = degenerate - { - if(degenerateFlags & DEGEN_2a) - { - index0 = 5; - index1 = 4; - } - else - { - index0 = 4; - index1 = 5; - } - } -} - -void Patch::accumulateVertexTangentSpace(std::size_t index, Vector3 tangentX[6], Vector3 tangentY[6], Vector2 tangentS[6], Vector2 tangentT[6], std::size_t index0, std::size_t index1) -{ - { - Vector3 normal(vector3_cross(tangentX[index0], tangentY[index1])); - if(!vector3_equal(normal, g_vector3_identity)) - { - vector3_add(normal_for_index(m_tess.m_vertices, index), vector3_normalised(normal)); - } - } - - { - ArbitraryMeshVertex a, b, c; - a.vertex = Vertex3f(0, 0, 0); - a.texcoord = TexCoord2f(0, 0); - b.vertex = vertex3f_for_vector3(tangentX[index0]); - b.texcoord = texcoord2f_for_vector2(tangentS[index0]); - c.vertex = vertex3f_for_vector3(tangentY[index1]); - c.texcoord = texcoord2f_for_vector2(tangentT[index1]); - - Vector3 s, t; - ArbitraryMeshTriangle_calcTangents(a, b, c, s, t); - if(!vector3_equal(s, g_vector3_identity)) - { - vector3_add(tangent_for_index(m_tess.m_vertices, index), vector3_normalised(s)); - } - if(!vector3_equal(t, g_vector3_identity)) - { - vector3_add(bitangent_for_index(m_tess.m_vertices, index), vector3_normalised(t)); - } - } -} - -const std::size_t PATCH_MAX_VERTEX_ARRAY = 1048576; - -void Patch::BuildVertexArray() -{ - const std::size_t strideU = 1; - const std::size_t strideV = m_width; - - const std::size_t numElems = m_tess.m_nArrayWidth*m_tess.m_nArrayHeight; // total number of elements in vertex array - - const bool bWidthStrips = (m_tess.m_nArrayWidth >= m_tess.m_nArrayHeight); // decide if horizontal strips are longer than vertical - - - // allocate vertex, normal, texcoord and primitive-index arrays - m_tess.m_vertices.resize(numElems); - m_tess.m_indices.resize(m_tess.m_nArrayWidth *2 * (m_tess.m_nArrayHeight - 1)); - - // set up strip indices - if(bWidthStrips) - { - m_tess.m_numStrips = m_tess.m_nArrayHeight-1; - m_tess.m_lenStrips = m_tess.m_nArrayWidth*2; - - for(std::size_t i=0; i>1]); - const std::size_t offMidY = (m_patchDef3) ? 0 : m_tess.m_curveTreeV[j>>1]->index; - const std::size_t widthY = m_tess.m_arrayHeight[j>>1] * m_tess.m_nArrayWidth; - const std::size_t offEndY = offStartY + widthY; - - for(std::size_t i = 0, offStartX = 0; i+1 < m_width; i += 2, pCtrl += (strideU << 1)) - { - const bool leafX = (m_patchDef3) ? false : BezierCurveTree_isLeaf(m_tess.m_curveTreeU[i>>1]); - const std::size_t offMidX = (m_patchDef3) ? 0 : m_tess.m_curveTreeU[i>>1]->index; - const std::size_t widthX = m_tess.m_arrayWidth[i>>1]; - const std::size_t offEndX = offStartX + widthX; - - PatchControl *subMatrix[3][3]; - subMatrix[0][0] = pCtrl; - subMatrix[0][1] = subMatrix[0][0]+strideU; - subMatrix[0][2] = subMatrix[0][1]+strideU; - subMatrix[1][0] = subMatrix[0][0]+strideV; - subMatrix[1][1] = subMatrix[1][0]+strideU; - subMatrix[1][2] = subMatrix[1][1]+strideU; - subMatrix[2][0] = subMatrix[1][0]+strideV; - subMatrix[2][1] = subMatrix[2][0]+strideU; - subMatrix[2][2] = subMatrix[2][1]+strideU; - - // assign on-patch control points to vertex array - if(i == 0 && j == 0) - { - vertex_clear_normal(m_tess.m_vertices[offStartX + offStartY]); - } - vertex_assign_ctrl(m_tess.m_vertices[offStartX + offStartY], *subMatrix[0][0]); - if(j == 0) - { - vertex_clear_normal(m_tess.m_vertices[offEndX + offStartY]); - } - vertex_assign_ctrl(m_tess.m_vertices[offEndX + offStartY], *subMatrix[0][2]); - if(i == 0) - { - vertex_clear_normal(m_tess.m_vertices[offStartX + offEndY]); - } - vertex_assign_ctrl(m_tess.m_vertices[offStartX + offEndY], *subMatrix[2][0]); - - vertex_clear_normal(m_tess.m_vertices[offEndX + offEndY]); - vertex_assign_ctrl(m_tess.m_vertices[offEndX + offEndY], *subMatrix[2][2]); - - if(!m_patchDef3) - { - // assign remaining control points to vertex array - if(!leafX) - { - vertex_assign_ctrl(m_tess.m_vertices[offMidX + offStartY], *subMatrix[0][1]); - vertex_assign_ctrl(m_tess.m_vertices[offMidX + offEndY], *subMatrix[2][1]); - } - if(!leafY) - { - vertex_assign_ctrl(m_tess.m_vertices[offStartX + offMidY], *subMatrix[1][0]); - vertex_assign_ctrl(m_tess.m_vertices[offEndX + offMidY], *subMatrix[1][2]); - - if(!leafX) - { - vertex_assign_ctrl(m_tess.m_vertices[offMidX + offMidY], *subMatrix[1][1]); - } - } - } - - // test all 12 edges for degeneracy - unsigned int nFlagsX = subarray_get_degen(pCtrl, strideU, strideV); - unsigned int nFlagsY = subarray_get_degen(pCtrl, strideV, strideU); - Vector3 tangentX[6], tangentY[6]; - Vector2 tangentS[6], tangentT[6]; - - // set up tangents for each of the 12 edges if they were not degenerate - if(!(nFlagsX & DEGEN_0a)) - { - tangentX[0] = vector3_subtracted(subMatrix[0][1]->m_vertex, subMatrix[0][0]->m_vertex); - tangentS[0] = vector2_subtracted(subMatrix[0][1]->m_texcoord, subMatrix[0][0]->m_texcoord); - } - if(!(nFlagsX & DEGEN_0b)) - { - tangentX[1] = vector3_subtracted(subMatrix[0][2]->m_vertex, subMatrix[0][1]->m_vertex); - tangentS[1] = vector2_subtracted(subMatrix[0][2]->m_texcoord, subMatrix[0][1]->m_texcoord); - } - if(!(nFlagsX & DEGEN_1a)) - { - tangentX[2] = vector3_subtracted(subMatrix[1][1]->m_vertex, subMatrix[1][0]->m_vertex); - tangentS[2] = vector2_subtracted(subMatrix[1][1]->m_texcoord, subMatrix[1][0]->m_texcoord); - } - if(!(nFlagsX & DEGEN_1b)) - { - tangentX[3] = vector3_subtracted(subMatrix[1][2]->m_vertex, subMatrix[1][1]->m_vertex); - tangentS[3] = vector2_subtracted(subMatrix[1][2]->m_texcoord, subMatrix[1][1]->m_texcoord); - } - if(!(nFlagsX & DEGEN_2a)) - { - tangentX[4] = vector3_subtracted(subMatrix[2][1]->m_vertex, subMatrix[2][0]->m_vertex); - tangentS[4] = vector2_subtracted(subMatrix[2][1]->m_texcoord, subMatrix[2][0]->m_texcoord); - } - if(!(nFlagsX & DEGEN_2b)) - { - tangentX[5] = vector3_subtracted(subMatrix[2][2]->m_vertex, subMatrix[2][1]->m_vertex); - tangentS[5] = vector2_subtracted(subMatrix[2][2]->m_texcoord, subMatrix[2][1]->m_texcoord); - } - - if(!(nFlagsY & DEGEN_0a)) - { - tangentY[0] = vector3_subtracted(subMatrix[1][0]->m_vertex, subMatrix[0][0]->m_vertex); - tangentT[0] = vector2_subtracted(subMatrix[1][0]->m_texcoord, subMatrix[0][0]->m_texcoord); - } - if(!(nFlagsY & DEGEN_0b)) - { - tangentY[1] = vector3_subtracted(subMatrix[2][0]->m_vertex, subMatrix[1][0]->m_vertex); - tangentT[1] = vector2_subtracted(subMatrix[2][0]->m_texcoord, subMatrix[1][0]->m_texcoord); - } - if(!(nFlagsY & DEGEN_1a)) - { - tangentY[2] = vector3_subtracted(subMatrix[1][1]->m_vertex, subMatrix[0][1]->m_vertex); - tangentT[2] = vector2_subtracted(subMatrix[1][1]->m_texcoord, subMatrix[0][1]->m_texcoord); - } - if(!(nFlagsY & DEGEN_1b)) - { - tangentY[3] = vector3_subtracted(subMatrix[2][1]->m_vertex, subMatrix[1][1]->m_vertex); - tangentT[3] = vector2_subtracted(subMatrix[2][1]->m_texcoord, subMatrix[1][1]->m_texcoord); - } - if(!(nFlagsY & DEGEN_2a)) - { - tangentY[4] = vector3_subtracted(subMatrix[1][2]->m_vertex, subMatrix[0][2]->m_vertex); - tangentT[4] = vector2_subtracted(subMatrix[1][2]->m_texcoord, subMatrix[0][2]->m_texcoord); - } - if(!(nFlagsY & DEGEN_2b)) - { - tangentY[5] = vector3_subtracted(subMatrix[2][2]->m_vertex, subMatrix[1][2]->m_vertex); - tangentT[5] = vector2_subtracted(subMatrix[2][2]->m_texcoord, subMatrix[1][2]->m_texcoord); - } - - // set up remaining edge tangents by borrowing the tangent from the closest parallel non-degenerate edge - tangents_remove_degenerate(tangentX, tangentS, nFlagsX); - tangents_remove_degenerate(tangentY, tangentT, nFlagsY); - - { - // x=0, y=0 - std::size_t index = offStartX + offStartY; - std::size_t index0 = 0; - std::size_t index1 = 0; - - double dot = vector3_dot(tangentX[index0], tangentY[index1]); - double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]); - - bestTangents00(nFlagsX, dot, length, index0, index1); - - accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); - } - - { - // x=1, y=0 - std::size_t index = offEndX + offStartY; - std::size_t index0 = 1; - std::size_t index1 = 4; - - double dot = vector3_dot(tangentX[index0],tangentY[index1]); - double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]); - - bestTangents10(nFlagsX, dot, length, index0, index1); - - accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); - } - - { - // x=0, y=1 - std::size_t index = offStartX + offEndY; - std::size_t index0 = 4; - std::size_t index1 = 1; - - double dot = vector3_dot(tangentX[index0], tangentY[index1]); - double length = vector3_length(tangentX[index1]) * vector3_length(tangentY[index1]); - - bestTangents01(nFlagsX, dot, length, index0, index1); - - accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); - } - - { - // x=1, y=1 - std::size_t index = offEndX + offEndY; - std::size_t index0 = 5; - std::size_t index1 = 5; - - double dot = vector3_dot(tangentX[index0],tangentY[index1]); - double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]); - - bestTangents11(nFlagsX, dot, length, index0, index1); - - accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); - } - - //normalise normals that won't be accumulated again - if(i!=0 || j!=0) - { - normalise_safe(normal_for_index(m_tess.m_vertices, offStartX + offStartY)); - normalise_safe(tangent_for_index(m_tess.m_vertices, offStartX + offStartY)); - normalise_safe(bitangent_for_index(m_tess.m_vertices, offStartX + offStartY)); - } - if(i+3 == m_width) - { - normalise_safe(normal_for_index(m_tess.m_vertices, offEndX + offStartY)); - normalise_safe(tangent_for_index(m_tess.m_vertices, offEndX + offStartY)); - normalise_safe(bitangent_for_index(m_tess.m_vertices, offEndX + offStartY)); - } - if(j+3 == m_height) - { - normalise_safe(normal_for_index(m_tess.m_vertices, offStartX + offEndY)); - normalise_safe(tangent_for_index(m_tess.m_vertices, offStartX + offEndY)); - normalise_safe(bitangent_for_index(m_tess.m_vertices, offStartX + offEndY)); - } - if(i+3 == m_width && j+3 == m_height) - { - normalise_safe(normal_for_index(m_tess.m_vertices, offEndX + offEndY)); - normalise_safe(tangent_for_index(m_tess.m_vertices, offEndX + offEndY)); - normalise_safe(bitangent_for_index(m_tess.m_vertices, offEndX + offEndY)); - } - - // set flags to average normals between shared edges - if(j != 0) - { - nFlagsX |= AVERAGE; - } - if(i != 0) - { - nFlagsY |= AVERAGE; - } - // set flags to save evaluating shared edges twice - nFlagsX |= SPLIT; - nFlagsY |= SPLIT; - - // if the patch is curved.. tesselate recursively - // use the relevant control curves for this sub-patch - if(m_patchDef3) - { - TesselateSubMatrixFixed(m_tess.m_vertices.data() + offStartX + offStartY, 1, m_tess.m_nArrayWidth, nFlagsX, nFlagsY, subMatrix); - } - else - { - if(!leafX) - { - TesselateSubMatrix( m_tess.m_curveTreeU[i>>1], m_tess.m_curveTreeV[j>>1], - offStartX, offStartY, offEndX, offEndY, // array offsets - nFlagsX, nFlagsY, - subMatrix[1][0]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[1][2]->m_vertex, - subMatrix[1][0]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[1][2]->m_texcoord, - false ); - } - else if(!leafY) - { - TesselateSubMatrix( m_tess.m_curveTreeV[j>>1], m_tess.m_curveTreeU[i>>1], - offStartY, offStartX, offEndY, offEndX, // array offsets - nFlagsY, nFlagsX, - subMatrix[0][1]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[2][1]->m_vertex, - subMatrix[0][1]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[2][1]->m_texcoord, - true ); - } - } - - offStartX = offEndX; - } - offStartY = offEndY; - } - } -} - - - -class PatchFilterWrapper : public Filter -{ - bool m_active; - bool m_invert; - PatchFilter& m_filter; -public: - PatchFilterWrapper(PatchFilter& filter, bool invert) : m_invert(invert), m_filter(filter) - { - } - void setActive(bool active) - { - m_active = active; - } - bool active() - { - return m_active; - } - bool filter(const Patch& patch) - { - return m_invert ^ m_filter.filter(patch); - } -}; - - -typedef std::list PatchFilters; -PatchFilters g_patchFilters; - -void add_patch_filter(PatchFilter& filter, int mask, bool invert) -{ - g_patchFilters.push_back(PatchFilterWrapper(filter, invert)); - GlobalFilterSystem().addFilter(g_patchFilters.back(), mask); -} - -bool patch_filtered(Patch& patch) -{ - for(PatchFilters::iterator i = g_patchFilters.begin(); i != g_patchFilters.end(); ++i) - { - if((*i).active() && (*i).filter(patch)) - { - return true; - } - } - return false; -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/patch.h b/misc/mediasource/extra/netradiant-src/radiant/patch.h deleted file mode 100644 index d55e712b..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patch.h +++ /dev/null @@ -1,2071 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_PATCH_H) -#define INCLUDED_PATCH_H - -/// \file -/// \brief The patch primitive. -/// -/// A 2-dimensional matrix of vertices that define a quadratic bezier surface. -/// The Boundary-Representation of this primitive is a triangle mesh. -/// The surface is recursively tesselated until the angle between each triangle -/// edge is smaller than a specified tolerance. - - -#include "nameable.h" -#include "ifilter.h" -#include "imap.h" -#include "ipatch.h" -#include "cullable.h" -#include "renderable.h" -#include "editable.h" -#include "selectable.h" - -#include "debugging/debugging.h" - -#include -#include - -#include "math/frustum.h" -#include "string/string.h" -#include "stream/stringstream.h" -#include "stream/textstream.h" -#include "xml/xmlelement.h" -#include "scenelib.h" -#include "transformlib.h" -#include "instancelib.h" -#include "selectionlib.h" -#include "traverselib.h" -#include "render.h" -#include "stringio.h" -#include "shaderlib.h" -#include "generic/callback.h" -#include "signal/signalfwd.h" -#include "texturelib.h" -#include "xml/ixml.h" -#include "dragplanes.h" - -enum EPatchType -{ - ePatchTypeQuake3, - ePatchTypeDoom3, -}; - -extern int g_PatchSubdivideThreshold; - - -#define MIN_PATCH_WIDTH 3 -#define MIN_PATCH_HEIGHT 3 - -extern std::size_t MAX_PATCH_WIDTH; -extern std::size_t MAX_PATCH_HEIGHT; - -#define MAX_PATCH_ROWCTRL (((MAX_PATCH_WIDTH-1)-1)/2) -#define MAX_PATCH_COLCTRL (((MAX_PATCH_HEIGHT-1)-1)/2) - -enum EPatchCap -{ - eCapBevel, - eCapEndCap, - eCapIBevel, - eCapIEndCap, - eCapCylinder, -}; - -enum EPatchPrefab -{ - ePlane, - eBevel, - eEndCap, - eCylinder, - eDenseCylinder, - eVeryDenseCylinder, - eSqCylinder, - eCone, - eSphere, -}; - -enum EMatrixMajor -{ - ROW, COL, -}; - -struct BezierCurve -{ - Vector3 crd; - Vector3 left; - Vector3 right; -}; - -const std::size_t BEZIERCURVETREE_MAX_INDEX = std::size_t(1) << (std::numeric_limits::digits - 1); - -struct BezierCurveTree -{ - std::size_t index; - BezierCurveTree* left; - BezierCurveTree* right; -}; - -inline bool BezierCurveTree_isLeaf(const BezierCurveTree* node) -{ - return node->left == 0 && node->right == 0; -} - -void BezierCurveTree_Delete(BezierCurveTree *pCurve); - - -inline VertexPointer vertexpointer_arbitrarymeshvertex(const ArbitraryMeshVertex* array) -{ - return VertexPointer(VertexPointer::pointer(&array->vertex), sizeof(ArbitraryMeshVertex)); -} - -typedef PatchControl* PatchControlIter; -typedef const PatchControl* PatchControlConstIter; - -inline void copy_ctrl(PatchControlIter ctrl, PatchControlConstIter begin, PatchControlConstIter end) -{ - std::copy(begin, end, ctrl); -} - -const Colour4b colour_corner(0, 255, 0, 255); -const Colour4b colour_inside(255, 0, 255, 255); - -class Patch; - -class PatchFilter -{ -public: - virtual bool filter(const Patch& patch) const = 0; -}; - -bool patch_filtered(Patch& patch); -void add_patch_filter(PatchFilter& filter, int mask, bool invert = false); - -void Patch_addTextureChangedCallback(const SignalHandler& handler); -void Patch_textureChanged(); - -inline void BezierCurveTreeArray_deleteAll(Array& curveTrees) -{ - for(Array::iterator i = curveTrees.begin(); i != curveTrees.end(); ++i) - { - BezierCurveTree_Delete(*i); - } -} - -inline void PatchControlArray_invert(Array& ctrl, std::size_t width, std::size_t height) -{ - Array tmp(width); - - PatchControlIter from = ctrl.data() + (width * (height - 1)); - PatchControlIter to = ctrl.data(); - for(std::size_t h = 0; h != ((height - 1) >> 1); ++h, to += width, from -= width) - { - copy_ctrl(tmp.data(), to, to + width); - copy_ctrl(to, from, from + width); - copy_ctrl(from, tmp.data(), tmp.data() + width); - } -} - -class PatchTesselation -{ -public: - PatchTesselation() - : m_numStrips(0), m_lenStrips(0), m_nArrayWidth(0), m_nArrayHeight(0) - { - } - Array m_vertices; - Array m_indices; - std::size_t m_numStrips; - std::size_t m_lenStrips; - - Array m_arrayWidth; - std::size_t m_nArrayWidth; - Array m_arrayHeight; - std::size_t m_nArrayHeight; - - Array m_curveTreeU; - Array m_curveTreeV; -}; - -class RenderablePatchWireframe : public OpenGLRenderable -{ - PatchTesselation& m_tess; -public: - RenderablePatchWireframe(PatchTesselation& tess) : m_tess(tess) - { - } - void render(RenderStateFlags state) const - { - { - #if NV_DRIVER_BUG - glVertexPointer(3, GL_FLOAT, 0, 0); - glDrawArrays(GL_TRIANGLE_FAN, 0, 0); - #endif - - std::size_t n = 0; - glVertexPointer(3, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->vertex); - for(std::size_t i = 0; i <= m_tess.m_curveTreeV.size(); ++i) - { - glDrawArrays(GL_LINE_STRIP, GLint(n), GLsizei(m_tess.m_nArrayWidth)); - - if(i == m_tess.m_curveTreeV.size()) break; - - if(!BezierCurveTree_isLeaf(m_tess.m_curveTreeV[i])) - glDrawArrays(GL_LINE_STRIP, GLint(m_tess.m_curveTreeV[i]->index), GLsizei(m_tess.m_nArrayWidth)); - - n += (m_tess.m_arrayHeight[i]*m_tess.m_nArrayWidth); - - } - } - - { - const ArbitraryMeshVertex* p = m_tess.m_vertices.data(); - std::size_t n = m_tess.m_nArrayWidth * sizeof(ArbitraryMeshVertex); - for(std::size_t i = 0; i <= m_tess.m_curveTreeU.size(); ++i) - { - glVertexPointer(3, GL_FLOAT, GLsizei(n), &p->vertex); - glDrawArrays(GL_LINE_STRIP, 0, GLsizei(m_tess.m_nArrayHeight)); - - if(i == m_tess.m_curveTreeU.size()) break; - - if(!BezierCurveTree_isLeaf(m_tess.m_curveTreeU[i])) - { - glVertexPointer(3, GL_FLOAT, GLsizei(n), &(m_tess.m_vertices.data() + (m_tess.m_curveTreeU[i]->index))->vertex); - glDrawArrays(GL_LINE_STRIP, 0, GLsizei(m_tess.m_nArrayHeight)); - } - - p += m_tess.m_arrayWidth[i]; - } - } - } -}; - -class RenderablePatchFixedWireframe : public OpenGLRenderable -{ - PatchTesselation& m_tess; -public: - RenderablePatchFixedWireframe(PatchTesselation& tess) : m_tess(tess) - { - } - void render(RenderStateFlags state) const - { - glVertexPointer(3, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->vertex); - const RenderIndex* strip_indices = m_tess.m_indices.data(); - for(std::size_t i = 0; inormal); - glVertexAttribPointerARB(c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->texcoord); - glVertexAttribPointerARB(c_attr_Tangent, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->tangent); - glVertexAttribPointerARB(c_attr_Binormal, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->bitangent); - } - else - { - glVertexAttribPointerARB(11, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->normal); - glVertexAttribPointerARB(8, 2, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->texcoord); - glVertexAttribPointerARB(9, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->tangent); - glVertexAttribPointerARB(10, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->bitangent); - } - } - else - { - glNormalPointer(GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->normal); - glTexCoordPointer(2, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->texcoord); - } - glVertexPointer(3, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->vertex); - const RenderIndex* strip_indices = m_tess.m_indices.data(); - for(std::size_t i = 0; i m_xml_state; - - typedef Array PatchControlArray; - - class SavedState : public UndoMemento - { - public: - SavedState( - std::size_t width, - std::size_t height, - const PatchControlArray& ctrl, - const char* shader, - bool patchDef3, - std::size_t subdivisions_x, - std::size_t subdivisions_y - ) : - m_width(width), - m_height(height), - m_shader(shader), - m_ctrl(ctrl), - m_patchDef3(patchDef3), - m_subdivisions_x(subdivisions_x), - m_subdivisions_y(subdivisions_y) - { - } - - void release() - { - delete this; - } - - std::size_t m_width, m_height; - CopiedString m_shader; - PatchControlArray m_ctrl; - bool m_patchDef3; - std::size_t m_subdivisions_x; - std::size_t m_subdivisions_y; - }; - -public: - class Observer - { - public: - virtual void allocate(std::size_t size) = 0; - }; - -private: - typedef UniqueSet Observers; - Observers m_observers; - - scene::Node* m_node; - - AABB m_aabb_local; // local bbox - - CopiedString m_shader; - Shader* m_state; - - std::size_t m_width; - std::size_t m_height; -public: - bool m_patchDef3; - std::size_t m_subdivisions_x; - std::size_t m_subdivisions_y; -private: - - UndoObserver* m_undoable_observer; - MapFile* m_map; - - // dynamically allocated array of control points, size is m_width*m_height - PatchControlArray m_ctrl; - PatchControlArray m_ctrlTransformed; - - PatchTesselation m_tess; - RenderablePatchSolid m_render_solid; - RenderablePatchWireframe m_render_wireframe; - RenderablePatchFixedWireframe m_render_wireframe_fixed; - - static Shader* m_state_ctrl; - static Shader* m_state_lattice; - VertexBuffer m_ctrl_vertices; - RenderableVertexBuffer m_render_ctrl; - IndexBuffer m_lattice_indices; - RenderableIndexBuffer m_render_lattice; - - bool m_bOverlay; - - bool m_transformChanged; - Callback m_evaluateTransform; - Callback m_boundsChanged; - - void construct() - { - m_bOverlay = false; - m_width = m_height = 0; - - m_patchDef3 = false; - m_subdivisions_x = 0; - m_subdivisions_y = 0; - - check_shader(); - captureShader(); - - m_xml_state.push_back(xml_state_t::eDefault); - } - -public: - Callback m_lightsChanged; - - static int m_CycleCapIndex;// = 0; - static EPatchType m_type; - - STRING_CONSTANT(Name, "Patch"); - - Patch(scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : - m_node(&node), - m_shader(texdef_name_default()), - m_state(0), - m_undoable_observer(0), - m_map(0), - m_render_solid(m_tess), - m_render_wireframe(m_tess), - m_render_wireframe_fixed(m_tess), - m_render_ctrl(GL_POINTS, m_ctrl_vertices), - m_render_lattice(GL_LINES, m_lattice_indices, m_ctrl_vertices), - m_transformChanged(false), - m_evaluateTransform(evaluateTransform), - m_boundsChanged(boundsChanged) - { - construct(); - } - Patch(const Patch& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : - m_node(&node), - m_shader(texdef_name_default()), - m_state(0), - m_undoable_observer(0), - m_map(0), - m_render_solid(m_tess), - m_render_wireframe(m_tess), - m_render_wireframe_fixed(m_tess), - m_render_ctrl(GL_POINTS, m_ctrl_vertices), - m_render_lattice(GL_LINES, m_lattice_indices, m_ctrl_vertices), - m_transformChanged(false), - m_evaluateTransform(evaluateTransform), - m_boundsChanged(boundsChanged) - { - construct(); - - m_patchDef3 = other.m_patchDef3; - m_subdivisions_x = other.m_subdivisions_x; - m_subdivisions_y = other.m_subdivisions_y; - setDims(other.m_width, other.m_height); - copy_ctrl(m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data()+(m_width*m_height)); - SetShader(other.m_shader.c_str()); - controlPointsChanged(); - } - - Patch(const Patch& other) : - XMLImporter(other), - XMLExporter(other), - TransformNode(other), - Bounded(other), - Cullable(other), - Snappable(), - Undoable(other), - Filterable(other), - Nameable(other), - m_state(0), - m_undoable_observer(0), - m_map(0), - m_render_solid(m_tess), - m_render_wireframe(m_tess), - m_render_wireframe_fixed(m_tess), - m_render_ctrl(GL_POINTS, m_ctrl_vertices), - m_render_lattice(GL_LINES, m_lattice_indices, m_ctrl_vertices), - m_transformChanged(false), - m_evaluateTransform(other.m_evaluateTransform), - m_boundsChanged(other.m_boundsChanged) - { - m_bOverlay = false; - - m_patchDef3 = other.m_patchDef3; - m_subdivisions_x = other.m_subdivisions_x; - m_subdivisions_y = other.m_subdivisions_y; - setDims(other.m_width, other.m_height); - copy_ctrl(m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data()+(m_width*m_height)); - SetShader(other.m_shader.c_str()); - controlPointsChanged(); - } - - ~Patch() - { - BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeU); - BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeV); - - releaseShader(); - - ASSERT_MESSAGE(m_observers.empty(), "Patch::~Patch: observers still attached"); - } - - InstanceCounter m_instanceCounter; - void instanceAttach(const scene::Path& path) - { - if(++m_instanceCounter.m_count == 1) - { - m_state->incrementUsed(); - m_map = path_find_mapfile(path.begin(), path.end()); - m_undoable_observer = GlobalUndoSystem().observer(this); - GlobalFilterSystem().registerFilterable(*this); - } - else - { - ASSERT_MESSAGE(path_find_mapfile(path.begin(), path.end()) == m_map, "node is instanced across more than one file"); - } - } - void instanceDetach(const scene::Path& path) - { - if(--m_instanceCounter.m_count == 0) - { - m_map = 0; - m_undoable_observer = 0; - GlobalUndoSystem().release(this); - GlobalFilterSystem().unregisterFilterable(*this); - m_state->decrementUsed(); - } - } - - const char* name() const - { - return "patch"; - } - void attach(const NameCallback& callback) - { - } - void detach(const NameCallback& callback) - { - } - - void attach(Observer* observer) - { - observer->allocate(m_width * m_height); - - m_observers.insert(observer); - } - void detach(Observer* observer) - { - m_observers.erase(observer); - } - - void updateFiltered() - { - if(m_node != 0) - { - if(patch_filtered(*this)) - { - m_node->enable(scene::Node::eFiltered); - } - else - { - m_node->disable(scene::Node::eFiltered); - } - } - } - - void onAllocate(std::size_t size) - { - for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) - { - (*i)->allocate(size); - } - } - - const Matrix4& localToParent() const - { - return g_matrix4_identity; - } - const AABB& localAABB() const - { - return m_aabb_local; - } - VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const - { - return test.TestAABB(m_aabb_local, localToWorld); - } - void render_solid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - renderer.SetState(m_state, Renderer::eFullMaterials); - renderer.addRenderable(m_render_solid, localToWorld); - } - void render_wireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - renderer.SetState(m_state, Renderer::eFullMaterials); - if(m_patchDef3) - { - renderer.addRenderable(m_render_wireframe_fixed, localToWorld); - } - else - { - renderer.addRenderable(m_render_wireframe, localToWorld); - } - } - - void render_component(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const - { - renderer.SetState(m_state_lattice, Renderer::eWireframeOnly); - renderer.SetState(m_state_lattice, Renderer::eFullMaterials); - renderer.addRenderable(m_render_lattice, localToWorld); - - renderer.SetState(m_state_ctrl, Renderer::eWireframeOnly); - renderer.SetState(m_state_ctrl, Renderer::eFullMaterials); - renderer.addRenderable(m_render_ctrl, localToWorld); - } - void testSelect(Selector& selector, SelectionTest& test) - { - SelectionIntersection best; - IndexPointer::index_type* pIndex = m_tess.m_indices.data(); - for(std::size_t s=0; s TransformChangedCaller; - - void evaluateTransform() - { - if(m_transformChanged) - { - m_transformChanged = false; - revertTransform(); - m_evaluateTransform(); - } - } - - void revertTransform() - { - m_ctrlTransformed = m_ctrl; - } - void freezeTransform() - { - undoSave(); - evaluateTransform(); - ASSERT_MESSAGE(m_ctrlTransformed.size() == m_ctrl.size(), "Patch::freeze: size mismatch"); - std::copy(m_ctrlTransformed.begin(), m_ctrlTransformed.end(), m_ctrl.begin()); - } - - void controlPointsChanged() - { - transformChanged(); - evaluateTransform(); - UpdateCachedData(); - } - bool isValid() const; - - void snapto(float snap) - { - undoSave(); - - for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) - { - vector3_snap((*i).m_vertex, snap); - } - - controlPointsChanged(); - } - - - - - void RenderDebug(RenderStateFlags state) const; - void RenderNormals(RenderStateFlags state) const; - - void pushElement(const XMLElement& element) - { - switch(m_xml_state.back().state()) - { - case xml_state_t::eDefault: - ASSERT_MESSAGE(string_equal(element.name(), "patch"), "parse error"); - m_xml_state.push_back(xml_state_t::ePatch); - break; - case xml_state_t::ePatch: - if(string_equal(element.name(), "matrix")) - { - setDims(atoi(element.attribute("width")), atoi(element.attribute("height"))); - m_xml_state.push_back(xml_state_t::eMatrix); - } - else if(string_equal(element.name(), "shader")) - { - m_xml_state.push_back(xml_state_t::eShader); - } - break; - default: - ERROR_MESSAGE("parse error"); - } - - } - void popElement(const char* name) - { - switch(m_xml_state.back().state()) - { - case xml_state_t::eDefault: - ERROR_MESSAGE("parse error"); - break; - case xml_state_t::ePatch: - break; - case xml_state_t::eMatrix: - { - StringTokeniser content(m_xml_state.back().content()); - - for(PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i) - { - (*i).m_vertex[0] = string_read_float(content.getToken()); - (*i).m_vertex[1] = string_read_float(content.getToken()); - (*i).m_vertex[2] = string_read_float(content.getToken()); - (*i).m_texcoord[0] = string_read_float(content.getToken()); - (*i).m_texcoord[1] = string_read_float(content.getToken()); - } - controlPointsChanged(); - } - break; - case xml_state_t::eShader: - { - SetShader(m_xml_state.back().content()); - } - break; - default: - ERROR_MESSAGE("parse error"); - } - - ASSERT_MESSAGE(!m_xml_state.empty(), "popping empty stack"); - m_xml_state.pop_back(); - } - std::size_t write(const char* buffer, std::size_t length) - { - switch(m_xml_state.back().state()) - { - case xml_state_t::eDefault: - break; - case xml_state_t::ePatch: - break; - case xml_state_t::eMatrix: - case xml_state_t::eShader: - return m_xml_state.back().write(buffer, length); - break; - default: - ERROR_MESSAGE("parse error"); - } - return length; - } - - void exportXML(XMLImporter& importer) - { - StaticElement patchElement("patch"); - importer.pushElement(patchElement); - - { - const StaticElement element("shader"); - importer.pushElement(element); - importer.write(m_shader.c_str(), strlen(m_shader.c_str())); - importer.popElement(element.name()); - } - - { - char width[16], height[16]; - sprintf(width, "%u", Unsigned(m_width)); - sprintf(height, "%u", Unsigned(m_height)); - StaticElement element("matrix"); - element.insertAttribute("width", width); - element.insertAttribute("height", height); - - importer.pushElement(element); - { - for(PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i) - { - importer << (*i).m_vertex[0] - << ' ' << (*i).m_vertex[1] - << ' ' << (*i).m_vertex[2] - << ' ' << (*i).m_texcoord[0] - << ' ' << (*i).m_texcoord[1]; - } - } - importer.popElement(element.name()); - } - - importer.popElement(patchElement.name()); - } - - void UpdateCachedData(); - - const char *GetShader() const - { - return m_shader.c_str(); - } - void SetShader(const char* name) - { - ASSERT_NOTNULL(name); - - if(shader_equal(m_shader.c_str(), name)) - return; - - undoSave(); - - if(m_instanceCounter.m_count != 0) - { - m_state->decrementUsed(); - } - releaseShader(); - m_shader = name; - captureShader(); - if(m_instanceCounter.m_count != 0) - { - m_state->incrementUsed(); - } - - check_shader(); - Patch_textureChanged(); - } - int getShaderFlags() const - { - if(m_state != 0) - { - return m_state->getFlags(); - } - return 0; - } - - typedef PatchControl* iterator; - typedef const PatchControl* const_iterator; - - iterator begin() - { - return m_ctrl.data(); - } - const_iterator begin() const - { - return m_ctrl.data(); - } - iterator end() - { - return m_ctrl.data() + m_ctrl.size(); - } - const_iterator end() const - { - return m_ctrl.data() + m_ctrl.size(); - } - - PatchControlArray& getControlPoints() - { - return m_ctrl; - } - PatchControlArray& getControlPointsTransformed() - { - return m_ctrlTransformed; - } - - void setDims (std::size_t w, std::size_t h); - std::size_t getWidth() const - { - return m_width; - } - std::size_t getHeight() const - { - return m_height; - } - PatchControl& ctrlAt(std::size_t row, std::size_t col) - { - return m_ctrl[row*m_width+col]; - } - const PatchControl& ctrlAt(std::size_t row, std::size_t col) const - { - return m_ctrl[row*m_width+col]; - } - - void ConstructPrefab(const AABB& aabb, EPatchPrefab eType, int axis, std::size_t width = 3, std::size_t height = 3); - void constructPlane(const AABB& aabb, int axis, std::size_t width, std::size_t height); - void InvertMatrix(); - void TransposeMatrix(); - void Redisperse(EMatrixMajor mt); - void Smooth(EMatrixMajor mt); - void InsertRemove(bool bInsert, bool bColumn, bool bFirst); - Patch* MakeCap(Patch* patch, EPatchCap eType, EMatrixMajor mt, bool bFirst); - void ConstructSeam(EPatchCap eType, Vector3* p, std::size_t width); - - void FlipTexture(int nAxis); - void TranslateTexture(float s, float t); - void ScaleTexture(float s, float t); - void RotateTexture(float angle); - void SetTextureRepeat(float s, float t); // call with s=1 t=1 for FIT - void CapTexture(); - void NaturalTexture(); - void ProjectTexture(int nAxis); - - void undoSave() - { - if(m_map != 0) - { - m_map->changed(); - } - if(m_undoable_observer != 0) - { - m_undoable_observer->save(this); - } - } - - UndoMemento* exportState() const - { - return new SavedState(m_width, m_height, m_ctrl, m_shader.c_str(), m_patchDef3, m_subdivisions_x, m_subdivisions_y); - } - void importState(const UndoMemento* state) - { - undoSave(); - - const SavedState& other = *(static_cast(state)); - - // begin duplicate of SavedState copy constructor, needs refactoring - - // copy construct - { - m_width = other.m_width; - m_height = other.m_height; - SetShader(other.m_shader.c_str()); - m_ctrl = other.m_ctrl; - onAllocate(m_ctrl.size()); - m_patchDef3 = other.m_patchDef3; - m_subdivisions_x = other.m_subdivisions_x; - m_subdivisions_y = other.m_subdivisions_y; - } - - // end duplicate code - - Patch_textureChanged(); - - controlPointsChanged(); - } - - static void constructStatic(EPatchType type) - { - Patch::m_type = type; - Patch::m_state_ctrl = GlobalShaderCache().capture("$POINT"); - Patch::m_state_lattice = GlobalShaderCache().capture("$LATTICE"); - } - - static void destroyStatic() - { - GlobalShaderCache().release("$LATTICE"); - GlobalShaderCache().release("$POINT"); - } -private: - void captureShader() - { - m_state = GlobalShaderCache().capture(m_shader.c_str()); - } - - void releaseShader() - { - GlobalShaderCache().release(m_shader.c_str()); - } - - void check_shader() - { - if(!shader_valid(GetShader())) - { - globalErrorStream() << "patch has invalid texture name: '" << GetShader() << "'\n"; - } - } - - void InsertPoints(EMatrixMajor mt, bool bFirst); - void RemovePoints(EMatrixMajor mt, bool bFirst); - - void AccumulateBBox(); - - void TesselateSubMatrixFixed(ArbitraryMeshVertex* vertices, std::size_t strideX, std::size_t strideY, unsigned int nFlagsX, unsigned int nFlagsY, PatchControl* subMatrix[3][3]); - - // uses binary trees representing bezier curves to recursively tesselate a bezier sub-patch - void TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY, - std::size_t offStartX, std::size_t offStartY, - std::size_t offEndX, std::size_t offEndY, - std::size_t nFlagsX, std::size_t nFlagsY, - Vector3& left, Vector3& mid, Vector3& right, - Vector2& texLeft, Vector2& texMid, Vector2& texRight, - bool bTranspose ); - - // tesselates the entire surface - void BuildTesselationCurves(EMatrixMajor major); - void accumulateVertexTangentSpace(std::size_t index, Vector3 tangentX[6], Vector3 tangentY[6], Vector2 tangentS[6], Vector2 tangentT[6], std::size_t index0, std::size_t index1); - void BuildVertexArray(); -}; - -inline bool Patch_importHeader(Patch& patch, Tokeniser& tokeniser) -{ - tokeniser.nextLine(); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "{")); - return true; -} - -inline bool Patch_importShader(Patch& patch, Tokeniser& tokeniser) -{ - // parse shader name - tokeniser.nextLine(); - const char* texture = tokeniser.getToken(); - if(texture == 0) - { - Tokeniser_unexpectedError(tokeniser, texture, "#texture-name"); - return false; - } - if(string_equal(texture, "NULL")) - { - patch.SetShader(texdef_name_default()); - } - else - { - StringOutputStream shader(string_length(GlobalTexturePrefix_get()) + string_length(texture)); - shader << GlobalTexturePrefix_get() << texture; - patch.SetShader(shader.c_str()); - } - return true; -} - -inline bool PatchDoom3_importShader(Patch& patch, Tokeniser& tokeniser) -{ - // parse shader name - tokeniser.nextLine(); - const char *shader = tokeniser.getToken(); - if(shader == 0) - { - Tokeniser_unexpectedError(tokeniser, shader, "#shader-name"); - return false; - } - if(string_equal(shader, "_emptyname")) - { - shader = texdef_name_default(); - } - patch.SetShader(shader); - return true; -} - -inline bool Patch_importParams(Patch& patch, Tokeniser& tokeniser) -{ - tokeniser.nextLine(); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); - - // parse matrix dimensions - { - std::size_t c, r; - RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, c)); - RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, r)); - - patch.setDims(c, r); - } - - if(patch.m_patchDef3) - { - RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, patch.m_subdivisions_x)); - RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, patch.m_subdivisions_y)); - } - - // ignore contents/flags/value - int tmp; - RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, tmp)); - RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, tmp)); - RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, tmp)); - - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); - return true; -} - -inline bool Patch_importMatrix(Patch& patch, Tokeniser& tokeniser) -{ - // parse matrix - tokeniser.nextLine(); - RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); - { - for(std::size_t c=0; cm_vertex, best); - if(best.valid()) - { - Selector_add(selector, m_selectable, best); - } - } - void snapto(float snap) - { - vector3_snap(m_ctrl->m_vertex, snap); - } -}; - - -class PatchInstance : -public Patch::Observer, -public scene::Instance, -public Selectable, -public Renderable, -public SelectionTestable, -public ComponentSelectionTestable, -public ComponentEditable, -public ComponentSnappable, -public PlaneSelectable, -public LightCullable -{ - class TypeCasts - { - InstanceTypeCastTable m_casts; - public: - TypeCasts() - { - InstanceStaticCast::install(m_casts); - InstanceContainedCast::install(m_casts); - InstanceContainedCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceStaticCast::install(m_casts); - InstanceIdentityCast::install(m_casts); - InstanceContainedCast::install(m_casts); - } - InstanceTypeCastTable& get() - { - return m_casts; - } - }; - - - Patch& m_patch; - typedef std::vector PatchControlInstances; - PatchControlInstances m_ctrl_instances; - - ObservedSelectable m_selectable; - - DragPlanes m_dragPlanes; - - mutable RenderablePointVector m_render_selected; - mutable AABB m_aabb_component; - - static Shader* m_state_selpoint; - - const LightList* m_lightList; - - TransformModifier m_transform; -public: - - typedef LazyStatic StaticTypeCasts; - - void lightsChanged() - { - m_lightList->lightsChanged(); - } - typedef MemberCaller LightsChangedCaller; - - STRING_CONSTANT(Name, "PatchInstance"); - - PatchInstance(const scene::Path& path, scene::Instance* parent, Patch& patch) : - Instance(path, parent, this, StaticTypeCasts::instance().get()), - m_patch(patch), - m_selectable(SelectedChangedCaller(*this)), - m_dragPlanes(SelectedChangedComponentCaller(*this)), - m_render_selected(GL_POINTS), - m_transform(Patch::TransformChangedCaller(m_patch), ApplyTransformCaller(*this)) - { - m_patch.instanceAttach(Instance::path()); - m_patch.attach(this); - - m_lightList = &GlobalShaderCache().attach(*this); - m_patch.m_lightsChanged = LightsChangedCaller(*this); - - Instance::setTransformChangedCallback(LightsChangedCaller(*this)); - } - ~PatchInstance() - { - Instance::setTransformChangedCallback(Callback()); - - m_patch.m_lightsChanged = Callback(); - GlobalShaderCache().detach(*this); - - m_patch.detach(this); - m_patch.instanceDetach(Instance::path()); - } - - void selectedChanged(const Selectable& selectable) - { - GlobalSelectionSystem().getObserver(SelectionSystem::ePrimitive)(selectable); - GlobalSelectionSystem().onSelectedChanged(*this, selectable); - - Instance::selectedChanged(); - } - typedef MemberCaller1 SelectedChangedCaller; - - void selectedChangedComponent(const Selectable& selectable) - { - GlobalSelectionSystem().getObserver(SelectionSystem::eComponent)(selectable); - GlobalSelectionSystem().onComponentSelection(*this, selectable); - } - typedef MemberCaller1 SelectedChangedComponentCaller; - - Patch& getPatch() - { - return m_patch; - } - Bounded& get(NullType) - { - return m_patch; - } - Cullable& get(NullType) - { - return m_patch; - } - Transformable& get(NullType) - { - return m_transform; - } - - static void constructStatic() - { - m_state_selpoint = GlobalShaderCache().capture("$SELPOINT"); - } - - static void destroyStatic() - { - GlobalShaderCache().release("$SELPOINT"); - } - - - void allocate(std::size_t size) - { - m_ctrl_instances.clear(); - m_ctrl_instances.reserve(size); - for(Patch::iterator i = m_patch.begin(); i != m_patch.end(); ++i) - { - m_ctrl_instances.push_back(PatchControlInstance(&(*i), SelectedChangedComponentCaller(*this))); - } - } - - void setSelected(bool select) - { - m_selectable.setSelected(select); - } - bool isSelected() const - { - return m_selectable.isSelected(); - } - - - void update_selected() const - { - m_render_selected.clear(); - Patch::iterator ctrl = m_patch.getControlPointsTransformed().begin(); - for(PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl) - { - if((*i).m_selectable.isSelected()) - { - const Colour4b colour_selected(0, 0, 255, 255); - m_render_selected.push_back(PointVertex(reinterpret_cast((*ctrl).m_vertex), colour_selected)); - } - } - } - -#if 0 - void render(Renderer& renderer, const VolumeTest& volume) const - { - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && m_selectable.isSelected()) - { - renderer.Highlight(Renderer::eFace, false); - - m_patch.render(renderer, volume, localToWorld()); - - if(GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex) - { - renderer.Highlight(Renderer::ePrimitive, false); - - m_patch.render_component(renderer, volume, localToWorld()); - - renderComponentsSelected(renderer, volume); - } - } - else - m_patch.render(renderer, volume, localToWorld()); - } -#endif - - void renderSolid(Renderer& renderer, const VolumeTest& volume) const - { - m_patch.evaluateTransform(); - renderer.setLights(*m_lightList); - m_patch.render_solid(renderer, volume, localToWorld()); - - renderComponentsSelected(renderer, volume); - } - - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const - { - m_patch.evaluateTransform(); - m_patch.render_wireframe(renderer, volume, localToWorld()); - - renderComponentsSelected(renderer, volume); - } - - void renderComponentsSelected(Renderer& renderer, const VolumeTest& volume) const - { - m_patch.evaluateTransform(); - update_selected(); - if(!m_render_selected.empty()) - { - renderer.Highlight(Renderer::ePrimitive, false); - renderer.SetState(m_state_selpoint, Renderer::eWireframeOnly); - renderer.SetState(m_state_selpoint, Renderer::eFullMaterials); - renderer.addRenderable(m_render_selected, localToWorld()); - } - } - void renderComponents(Renderer& renderer, const VolumeTest& volume) const - { - m_patch.evaluateTransform(); - if(GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex) - { - m_patch.render_component(renderer, volume, localToWorld()); - } - } - - void testSelect(Selector& selector, SelectionTest& test) - { - test.BeginMesh(localToWorld(), true); - m_patch.testSelect(selector, test); - } - - void selectCtrl(bool select) - { - for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) - { - (*i).m_selectable.setSelected(select); - } - } - bool isSelectedComponents() const - { - for(PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) - { - if((*i).m_selectable.isSelected()) - { - return true; - } - } - return false; - } - void setSelectedComponents(bool select, SelectionSystem::EComponentMode mode) - { - if(mode == SelectionSystem::eVertex) - { - selectCtrl(select); - } - else if(mode == SelectionSystem::eFace) - { - m_dragPlanes.setSelected(select); - } - } - const AABB& getSelectedComponentsBounds() const - { - m_aabb_component = AABB(); - - for(PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) - { - if((*i).m_selectable.isSelected()) - { - aabb_extend_by_point_safe(m_aabb_component, (*i).m_ctrl->m_vertex); - } - } - - return m_aabb_component; - } - - void testSelectComponents(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) - { - test.BeginMesh(localToWorld()); - - switch(mode) - { - case SelectionSystem::eVertex: - { - for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) - { - (*i).testSelect(selector, test); - } - } - break; - default: - break; - } - } - - bool selectedVertices() - { - for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) - { - if((*i).m_selectable.isSelected()) - { - return true; - } - } - return false; - } - - void transformComponents(const Matrix4& matrix) - { - if(selectedVertices()) - { - PatchControlIter ctrl = m_patch.getControlPointsTransformed().begin(); - for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl) - { - if((*i).m_selectable.isSelected()) - { - matrix4_transform_point(matrix, (*ctrl).m_vertex); - } - } - m_patch.UpdateCachedData(); - } - - if(m_dragPlanes.isSelected()) // this should only be true when the transform is a pure translation. - { - m_patch.transform(m_dragPlanes.evaluateTransform(vector4_to_vector3(matrix.t()))); - } - } - - - void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) - { - test.BeginMesh(localToWorld()); - - m_dragPlanes.selectPlanes(m_patch.localAABB(), selector, test, selectedPlaneCallback); - } - void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) - { - m_dragPlanes.selectReversedPlanes(m_patch.localAABB(), selector, selectedPlanes); - } - - - void snapComponents(float snap) - { - if(selectedVertices()) - { - m_patch.undoSave(); - for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) - { - if((*i).m_selectable.isSelected()) - { - (*i).snapto(snap); - } - } - m_patch.controlPointsChanged(); - } - } - - void evaluateTransform() - { - Matrix4 matrix(m_transform.calculateTransform()); - - if(m_transform.getType() == TRANSFORM_PRIMITIVE) - { - m_patch.transform(matrix); - } - else - { - transformComponents(matrix); - } - } - void applyTransform() - { - m_patch.revertTransform(); - evaluateTransform(); - m_patch.freezeTransform(); - } - typedef MemberCaller ApplyTransformCaller; - - - bool testLight(const RendererLight& light) const - { - return light.testAABB(worldAABB()); - } -}; - - -template -class PatchNode : - public scene::Node::Symbiot, - public scene::Instantiable, - public scene::Cloneable -{ - typedef PatchNode Self; - - class TypeCasts - { - InstanceTypeCastTable m_casts; - public: - TypeCasts() - { - NodeStaticCast::install(m_casts); - NodeStaticCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - NodeContainedCast::install(m_casts); - } - InstanceTypeCastTable& get() - { - return m_casts; - } - }; - - - scene::Node m_node; - InstanceSet m_instances; - Patch m_patch; - TokenImporter m_importMap; - TokenExporter m_exportMap; - -public: - - typedef LazyStatic StaticTypeCasts; - - Snappable& get(NullType) - { - return m_patch; - } - TransformNode& get(NullType) - { - return m_patch; - } - Patch& get(NullType) - { - return m_patch; - } - XMLImporter& get(NullType) - { - return m_patch; - } - XMLExporter& get(NullType) - { - return m_patch; - } - MapImporter& get(NullType) - { - return m_importMap; - } - MapExporter& get(NullType) - { - return m_exportMap; - } - Nameable& get(NullType) - { - return m_patch; - } - - PatchNode(bool patchDef3 = false) : - m_node(this, this, StaticTypeCasts::instance().get()), - m_patch(m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), - m_importMap(m_patch), - m_exportMap(m_patch) - { - m_patch.m_patchDef3 = patchDef3; - } - PatchNode(const PatchNode& other) : - scene::Node::Symbiot(other), - scene::Instantiable(other), - scene::Cloneable(other), - m_node(this, this, StaticTypeCasts::instance().get()), - m_patch(other.m_patch, m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), - m_importMap(m_patch), - m_exportMap(m_patch) - { - } - void release() - { - delete this; - } - scene::Node& node() - { - return m_node; - } - Patch& get() - { - return m_patch; - } - const Patch& get() const - { - return m_patch; - } - - scene::Node& clone() const - { - return (new PatchNode(*this))->node(); - } - - scene::Instance* create(const scene::Path& path, scene::Instance* parent) - { - return new PatchInstance(path, parent, m_patch); - } - 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); - } - scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) - { - return m_instances.erase(observer, path); - } -}; - - - -typedef PatchNode PatchNodeQuake3; -typedef PatchNode PatchNodeDoom3; - -inline Patch* Node_getPatch(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -inline PatchInstance* Instance_getPatch(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); -} - -template -class PatchSelectedVisitor : public SelectionSystem::Visitor -{ - const Functor& m_functor; -public: - PatchSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - PatchInstance* patch = Instance_getPatch(instance); - if(patch != 0) - { - m_functor(*patch); - } - } -}; - -template -inline void Scene_forEachSelectedPatch(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(PatchSelectedVisitor(functor)); -} - - -template -class PatchVisibleSelectedVisitor : public SelectionSystem::Visitor -{ - const Functor& m_functor; -public: - PatchVisibleSelectedVisitor(const Functor& functor) : m_functor(functor) - { - } - void visit(scene::Instance& instance) const - { - PatchInstance* patch = Instance_getPatch(instance); - if(patch != 0 - && instance.path().top().get().visible()) - { - m_functor(*patch); - } - } -}; - -template -inline void Scene_forEachVisibleSelectedPatchInstance(const Functor& functor) -{ - GlobalSelectionSystem().foreachSelected(PatchVisibleSelectedVisitor(functor)); -} - -template -class PatchForEachWalker : public scene::Graph::Walker -{ - const Functor& m_functor; -public: - PatchForEachWalker(const Functor& functor) : m_functor(functor) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Patch* patch = Node_getPatch(path.top()); - if(patch != 0) - { - m_functor(*patch); - } - } - return true; - } -}; - -template -inline void Scene_forEachVisiblePatch(const Functor& functor) -{ - GlobalSceneGraph().traverse(PatchForEachWalker(functor)); -} - -template -class PatchForEachSelectedWalker : public scene::Graph::Walker -{ - const Functor& m_functor; -public: - PatchForEachSelectedWalker(const Functor& functor) : m_functor(functor) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Patch* patch = Node_getPatch(path.top()); - if(patch != 0 - && Instance_getSelectable(instance)->isSelected()) - { - m_functor(*patch); - } - } - return true; - } -}; - -template -inline void Scene_forEachVisibleSelectedPatch(const Functor& functor) -{ - GlobalSceneGraph().traverse(PatchForEachSelectedWalker(functor)); -} - -template -class PatchForEachInstanceWalker : public scene::Graph::Walker -{ - const Functor& m_functor; -public: - PatchForEachInstanceWalker(const Functor& functor) : m_functor(functor) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - PatchInstance* patch = Instance_getPatch(instance); - if(patch != 0) - { - m_functor(*patch); - } - } - return true; - } -}; - -template -inline void Scene_forEachVisiblePatchInstance(const Functor& functor) -{ - GlobalSceneGraph().traverse(PatchForEachInstanceWalker(functor)); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/patchdialog.cpp b/misc/mediasource/extra/netradiant-src/radiant/patchdialog.cpp deleted file mode 100644 index b62b574e..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patchdialog.cpp +++ /dev/null @@ -1,1218 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Patch Dialog -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "patchdialog.h" - -#include "itexdef.h" - -#include "debugging/debugging.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "gtkutil/idledraw.h" -#include "gtkutil/entry.h" -#include "gtkutil/button.h" -#include "gtkutil/nonmodal.h" -#include "dialog.h" -#include "gtkdlgs.h" -#include "mainframe.h" -#include "patchmanip.h" -#include "patch.h" -#include "commands.h" -#include "preferences.h" -#include "signal/isignal.h" - - -#include - -// the increment we are using for the patch inspector (this is saved in the prefs) -struct pi_globals_t -{ - float shift[2]; - float scale[2]; - float rotate; - - pi_globals_t() - { - shift[0] = 8.0f; - shift[1] = 8.0f; - scale[0] = 0.5f; - scale[1] = 0.5f; - rotate = 45.0f; - } -}; - -pi_globals_t g_pi_globals; - -class PatchFixedSubdivisions -{ -public: - PatchFixedSubdivisions() : m_enabled(false), m_x(0), m_y(0) - { - } - PatchFixedSubdivisions(bool enabled, std::size_t x, std::size_t y) : m_enabled(enabled), m_x(x), m_y(y) - { - } - bool m_enabled; - std::size_t m_x; - std::size_t m_y; -}; - -void Patch_getFixedSubdivisions(const Patch& patch, PatchFixedSubdivisions& subdivisions) -{ - subdivisions.m_enabled = patch.m_patchDef3; - subdivisions.m_x = patch.m_subdivisions_x; - subdivisions.m_y = patch.m_subdivisions_y; -} - -const std::size_t MAX_PATCH_SUBDIVISIONS = 32; - -void Patch_setFixedSubdivisions(Patch& patch, const PatchFixedSubdivisions& subdivisions) -{ - patch.undoSave(); - - patch.m_patchDef3 = subdivisions.m_enabled; - patch.m_subdivisions_x = subdivisions.m_x; - patch.m_subdivisions_y = subdivisions.m_y; - - if(patch.m_subdivisions_x == 0) - { - patch.m_subdivisions_x = 4; - } - else if(patch.m_subdivisions_x > MAX_PATCH_SUBDIVISIONS) - { - patch.m_subdivisions_x = MAX_PATCH_SUBDIVISIONS; - } - if(patch.m_subdivisions_y == 0) - { - patch.m_subdivisions_y = 4; - } - else if(patch.m_subdivisions_y > MAX_PATCH_SUBDIVISIONS) - { - patch.m_subdivisions_y = MAX_PATCH_SUBDIVISIONS; - } - - SceneChangeNotify(); - Patch_textureChanged(); - patch.controlPointsChanged(); -} - -class PatchGetFixedSubdivisions -{ - PatchFixedSubdivisions& m_subdivisions; -public: - PatchGetFixedSubdivisions(PatchFixedSubdivisions& subdivisions) : m_subdivisions(subdivisions) - { - } - void operator()(Patch& patch) - { - Patch_getFixedSubdivisions(patch, m_subdivisions); - SceneChangeNotify(); - } -}; - -void Scene_PatchGetFixedSubdivisions(PatchFixedSubdivisions& subdivisions) -{ -#if 1 - if(GlobalSelectionSystem().countSelected() != 0) - { - Patch* patch = Node_getPatch(GlobalSelectionSystem().ultimateSelected().path().top()); - if(patch != 0) - { - Patch_getFixedSubdivisions(*patch, subdivisions); - } - } -#else - Scene_forEachVisibleSelectedPatch(PatchGetFixedSubdivisions(subdivisions)); -#endif -} - -class PatchSetFixedSubdivisions -{ - const PatchFixedSubdivisions& m_subdivisions; -public: - PatchSetFixedSubdivisions(const PatchFixedSubdivisions& subdivisions) : m_subdivisions(subdivisions) - { - } - void operator()(Patch& patch) const - { - Patch_setFixedSubdivisions(patch, m_subdivisions); - } -}; - -void Scene_PatchSetFixedSubdivisions(const PatchFixedSubdivisions& subdivisions) -{ - UndoableCommand command("patchSetFixedSubdivisions"); - Scene_forEachVisibleSelectedPatch(PatchSetFixedSubdivisions(subdivisions)); -} - -typedef struct _GtkCheckButton GtkCheckButton; - -class Subdivisions -{ -public: - GtkCheckButton* m_enabled; - GtkEntry* m_horizontal; - GtkEntry* m_vertical; - Subdivisions() : m_enabled(0), m_horizontal(0), m_vertical(0) - { - } - void update() - { - PatchFixedSubdivisions subdivisions; - Scene_PatchGetFixedSubdivisions(subdivisions); - - toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(m_enabled), subdivisions.m_enabled); - - if(subdivisions.m_enabled) - { - entry_set_int(m_horizontal, static_cast(subdivisions.m_x)); - entry_set_int(m_vertical, static_cast(subdivisions.m_y)); - gtk_widget_set_sensitive(GTK_WIDGET(m_horizontal), TRUE); - gtk_widget_set_sensitive(GTK_WIDGET(m_vertical), TRUE); - } - else - { - gtk_entry_set_text(m_horizontal, ""); - gtk_entry_set_text(m_vertical, ""); - gtk_widget_set_sensitive(GTK_WIDGET(m_horizontal), FALSE); - gtk_widget_set_sensitive(GTK_WIDGET(m_vertical), FALSE); - } - } - void cancel() - { - update(); - } - typedef MemberCaller CancelCaller; - void apply() - { - Scene_PatchSetFixedSubdivisions( - PatchFixedSubdivisions( - gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_enabled)) != FALSE, - static_cast(entry_get_int(m_horizontal)), - static_cast(entry_get_int(m_vertical)) - ) - ); - } - typedef MemberCaller ApplyCaller; - static void applyGtk(GtkToggleButton* toggle, Subdivisions* self) - { - self->apply(); - } -}; - -class PatchInspector : public Dialog -{ - GtkWindow* BuildDialog(); - Subdivisions m_subdivisions; - NonModalEntry m_horizontalSubdivisionsEntry; - NonModalEntry m_verticalSubdivisionsEntry; -public: - IdleDraw m_idleDraw; - WindowPositionTracker m_position_tracker; - - Patch *m_Patch; - - CopiedString m_strName; - float m_fS; - float m_fT; - float m_fX; - float m_fY; - float m_fZ; -/* float m_fHScale; - float m_fHShift; - float m_fRotate; - float m_fVScale; - float m_fVShift; */ - int m_nCol; - int m_nRow; - GtkComboBox *m_pRowCombo; - GtkComboBox *m_pColCombo; - std::size_t m_countRows; - std::size_t m_countCols; - - // turn on/off processing of the "changed" "value_changed" messages - // (need to turn off when we are feeding data in) - // NOTE: much more simple than blocking signals - bool m_bListenChanged; - - PatchInspector() : - m_horizontalSubdivisionsEntry(Subdivisions::ApplyCaller(m_subdivisions), Subdivisions::CancelCaller(m_subdivisions)), - m_verticalSubdivisionsEntry(Subdivisions::ApplyCaller(m_subdivisions), Subdivisions::CancelCaller(m_subdivisions)), - m_idleDraw(MemberCaller(*this)) - { - m_fS = 0.0f; - m_fT = 0.0f; - m_fX = 0.0f; - m_fY = 0.0f; - m_fZ = 0.0f; - m_nCol = 0; - m_nRow = 0; - m_countRows = 0; - m_countCols = 0; - m_Patch = 0; - m_bListenChanged = true; - - m_position_tracker.setPosition(c_default_window_pos); - } - - bool visible() - { - return GTK_WIDGET_VISIBLE(GetWidget()); - } - -// void UpdateInfo(); -// void SetPatchInfo(); - void GetPatchInfo(); - void UpdateSpinners(bool bUp, int nID); - // read the current patch on map and initialize m_fX m_fY accordingly - void UpdateRowColInfo(); - // sync the dialog our internal data structures - // depending on the flag it will read or write - // we use m_nCol m_nRow m_fX m_fY m_fZ m_fS m_fT m_strName - // (NOTE: this doesn't actually commit stuff to the map or read from it) - void importData(); - void exportData(); -}; - -PatchInspector g_PatchInspector; - -void PatchInspector_constructWindow(GtkWindow* main_window) -{ - g_PatchInspector.m_parent = main_window; - g_PatchInspector.Create(); -} -void PatchInspector_destroyWindow() -{ - g_PatchInspector.Destroy(); -} - -void PatchInspector_queueDraw() -{ - if(g_PatchInspector.visible()) - { - g_PatchInspector.m_idleDraw.queueDraw(); - } -} - -void DoPatchInspector() -{ - g_PatchInspector.GetPatchInfo(); - if (!g_PatchInspector.visible()) - g_PatchInspector.ShowDlg(); -} - -void PatchInspector_toggleShown() -{ - if (g_PatchInspector.visible()) - { - g_PatchInspector.m_Patch = 0; - g_PatchInspector.HideDlg(); - } - else - DoPatchInspector(); -} - - -// ============================================================================= -// static functions - -// memorize the current state (that is don't try to undo our do before changing something else) -static void OnApply (GtkWidget *widget, gpointer data) -{ - g_PatchInspector.exportData(); - if (g_PatchInspector.m_Patch != 0) - { - UndoableCommand command("patchSetTexture"); - g_PatchInspector.m_Patch->undoSave(); - - if (!texdef_name_valid(g_PatchInspector.m_strName.c_str())) - { - globalErrorStream() << "invalid texture name '" << g_PatchInspector.m_strName.c_str() << "'\n"; - g_PatchInspector.m_strName = texdef_name_default(); - } - g_PatchInspector.m_Patch->SetShader(g_PatchInspector.m_strName.c_str()); - - std::size_t r = g_PatchInspector.m_nRow; - std::size_t c = g_PatchInspector.m_nCol; - if(r < g_PatchInspector.m_Patch->getHeight() - && c < g_PatchInspector.m_Patch->getWidth()) - { - PatchControl& p = g_PatchInspector.m_Patch->ctrlAt(r,c); - p.m_vertex[0] = g_PatchInspector.m_fX; - p.m_vertex[1] = g_PatchInspector.m_fY; - p.m_vertex[2] = g_PatchInspector.m_fZ; - p.m_texcoord[0] = g_PatchInspector.m_fS; - p.m_texcoord[1] = g_PatchInspector.m_fT; - g_PatchInspector.m_Patch->controlPointsChanged(); - } - } -} - -static void OnSelchangeComboColRow (GtkWidget *widget, gpointer data) -{ - if (!g_PatchInspector.m_bListenChanged) - return; - // retrieve the current m_nRow and m_nCol, other params are not relevant - g_PatchInspector.exportData(); - // read the changed values ourselves - g_PatchInspector.UpdateRowColInfo(); - // now reflect our changes - g_PatchInspector.importData(); -} - -class PatchSetTextureRepeat -{ - float m_s, m_t; -public: - PatchSetTextureRepeat(float s, float t) : m_s(s), m_t(t) - { - } - void operator()(Patch& patch) const - { - patch.SetTextureRepeat(m_s, m_t); - } -}; - -void Scene_PatchTileTexture_Selected(scene::Graph& graph, float s, float t) -{ - Scene_forEachVisibleSelectedPatch(PatchSetTextureRepeat(s, t)); - SceneChangeNotify(); -} - -static void OnBtnPatchdetails (GtkWidget *widget, gpointer data) -{ - UndoableCommand command("patchCapTexture"); - - Scene_PatchCapTexture_Selected(GlobalSceneGraph()); -} - -static void OnBtnPatchfit (GtkWidget *widget, gpointer data) -{ - UndoableCommand command("patchFitTexture"); - - Scene_PatchTileTexture_Selected(GlobalSceneGraph(), 1, 1); -} - -static void OnBtnPatchnatural (GtkWidget *widget, gpointer data) -{ - UndoableCommand command("patchNaturalTexture"); - - Scene_PatchNaturalTexture_Selected(GlobalSceneGraph()); -} - -static void OnBtnPatchreset (GtkWidget *widget, gpointer data) -{ - float fx, fy; - if (DoTextureLayout (&fx, &fy) == eIDOK) - { - UndoableCommand command("patchTileTexture"); - Scene_PatchTileTexture_Selected(GlobalSceneGraph(), fx, fy); - } -} - -struct PatchRotateTexture -{ - float m_angle; -public: - PatchRotateTexture(float angle) : m_angle(angle) - { - } - void operator()(Patch& patch) const - { - patch.RotateTexture(m_angle); - } -}; - -void Scene_PatchRotateTexture_Selected(scene::Graph& graph, float angle) -{ - Scene_forEachVisibleSelectedPatch(PatchRotateTexture(angle)); -} - -class PatchScaleTexture -{ - float m_s, m_t; -public: - PatchScaleTexture(float s, float t) : m_s(s), m_t(t) - { - } - void operator()(Patch& patch) const - { - patch.ScaleTexture(m_s, m_t); - } -}; - -float Patch_convertScale(float scale) -{ - if(scale > 0) - { - return scale; - } - if(scale < 0) - { - return -1 / scale; - } - return 1; -} - -void Scene_PatchScaleTexture_Selected(scene::Graph& graph, float s, float t) -{ - Scene_forEachVisibleSelectedPatch(PatchScaleTexture(Patch_convertScale(s), Patch_convertScale(t))); -} - -class PatchTranslateTexture -{ - float m_s, m_t; -public: - PatchTranslateTexture(float s, float t) - : m_s(s), m_t(t) - { - } - void operator()(Patch& patch) const - { - patch.TranslateTexture(m_s, m_t); - } -}; - -void Scene_PatchTranslateTexture_Selected(scene::Graph& graph, float s, float t) -{ - Scene_forEachVisibleSelectedPatch(PatchTranslateTexture(s, t)); -} - -static void OnSpinChanged (GtkAdjustment *adj, gpointer data) -{ - texdef_t td; - - td.rotate = 0; - td.scale[0] = td.scale[1] = 0; - td.shift[0] = td.shift[1] = 0; - - if (adj->value == 0) - return; - - if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "hshift_adj")) - { - g_pi_globals.shift[0] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); - - if (adj->value > 0) - td.shift[0] = g_pi_globals.shift[0]; - else - td.shift[0] = -g_pi_globals.shift[0]; - } - else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "vshift_adj")) - { - g_pi_globals.shift[1] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); - - if (adj->value > 0) - td.shift[1] = g_pi_globals.shift[1]; - else - td.shift[1] = -g_pi_globals.shift[1]; - } - else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "hscale_adj")) - { - g_pi_globals.scale[0] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); - if (g_pi_globals.scale[0] == 0.0f) - return; - if (adj->value > 0) - td.scale[0] = g_pi_globals.scale[0]; - else - td.scale[0] = -g_pi_globals.scale[0]; - } - else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "vscale_adj")) - { - g_pi_globals.scale[1] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); - if (g_pi_globals.scale[1] == 0.0f) - return; - if (adj->value > 0) - td.scale[1] = g_pi_globals.scale[1]; - else - td.scale[1] = -g_pi_globals.scale[1]; - } - else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "rotate_adj")) - { - g_pi_globals.rotate = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); - - if (adj->value > 0) - td.rotate = g_pi_globals.rotate; - else - td.rotate = -g_pi_globals.rotate; - } - - adj->value = 0; - - // will scale shift rotate the patch accordingly - - - if (td.shift[0] || td.shift[1]) - { - UndoableCommand command("patchTranslateTexture"); - Scene_PatchTranslateTexture_Selected (GlobalSceneGraph(), td.shift[0], td.shift[1]); - } - else if (td.scale[0] || td.scale[1]) - { - UndoableCommand command("patchScaleTexture"); - Scene_PatchScaleTexture_Selected (GlobalSceneGraph(), td.scale[0], td.scale[1]); - } - else if (td.rotate) - { - UndoableCommand command("patchRotateTexture"); - Scene_PatchRotateTexture_Selected (GlobalSceneGraph(), td.rotate); - } - - // update the point-by-point view - OnSelchangeComboColRow(0,0); -} - -static gint OnDialogKey (GtkWidget* widget, GdkEventKey* event, gpointer data) -{ - if (event->keyval == GDK_Return) - { - OnApply (0, 0); - return TRUE; - } - else if (event->keyval == GDK_Escape) - { - g_PatchInspector.GetPatchInfo(); - return TRUE; - } - return FALSE; -} - -// ============================================================================= -// PatchInspector class - -GtkWindow* PatchInspector::BuildDialog() -{ - GtkWindow* window = create_floating_window("Patch Properties", m_parent); - - m_position_tracker.connect(window); - - global_accel_connect_window(window); - - window_connect_focus_in_clear_focus_widget(window); - - - { - GtkVBox* vbox = GTK_VBOX(gtk_vbox_new(FALSE, 5)); - gtk_container_set_border_width(GTK_CONTAINER(vbox), 5); - gtk_widget_show(GTK_WIDGET(vbox)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); - { - GtkHBox* hbox = GTK_HBOX(gtk_hbox_new(FALSE, 5)); - gtk_widget_show(GTK_WIDGET(hbox)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), TRUE, TRUE, 0); - { - GtkVBox* vbox2 = GTK_VBOX(gtk_vbox_new(FALSE, 0)); - gtk_container_set_border_width(GTK_CONTAINER(vbox2), 0); - gtk_widget_show(GTK_WIDGET(vbox2)); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), TRUE, TRUE, 0); - { - GtkFrame* frame = GTK_FRAME(gtk_frame_new("Details")); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(frame), TRUE, TRUE, 0); - { - GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 5)); - gtk_container_set_border_width(GTK_CONTAINER(vbox3), 5); - gtk_widget_show(GTK_WIDGET(vbox3)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); - { - GtkTable* table = GTK_TABLE(gtk_table_new(2, 2, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings(table, 5); - gtk_table_set_col_spacings(table, 5); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Row:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Column:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 0, 1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); - g_signal_connect(G_OBJECT(combo), "changed", G_CALLBACK(OnSelchangeComboColRow), this); - AddDialogData(*combo, m_nRow); - - gtk_widget_show(GTK_WIDGET(combo)); - gtk_table_attach(table, GTK_WIDGET(combo), 0, 1, 1, 2, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(combo), 60, -1); - m_pRowCombo = combo; - } - - { - GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); - g_signal_connect(G_OBJECT(combo), "changed", G_CALLBACK(OnSelchangeComboColRow), this); - AddDialogData(*combo, m_nCol); - - gtk_widget_show(GTK_WIDGET(combo)); - gtk_table_attach(table, GTK_WIDGET(combo), 1, 2, 1, 2, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(combo), 60, -1); - m_pColCombo = combo; - } - } - GtkTable* table = GTK_TABLE(gtk_table_new(5, 2, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings(table, 5); - gtk_table_set_col_spacings(table, 5); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("X:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Y:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Z:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 2, 3, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("S:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 3, 4, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("T:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 4, 5, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - AddDialogData(*entry, m_fX); - - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - AddDialogData(*entry, m_fY); - - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 2, 3, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - AddDialogData(*entry, m_fZ); - - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 3, 4, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - AddDialogData(*entry, m_fS); - - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 4, 5, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - AddDialogData(*entry, m_fT); - - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); - } - } - } - if(g_pGameDescription->mGameType == "doom3") - { - GtkFrame* frame = GTK_FRAME(gtk_frame_new("Tesselation")); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(frame), TRUE, TRUE, 0); - { - GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 5)); - gtk_container_set_border_width(GTK_CONTAINER(vbox3), 5); - gtk_widget_show(GTK_WIDGET(vbox3)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); - { - GtkTable* table = GTK_TABLE(gtk_table_new(3, 2, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings(table, 5); - gtk_table_set_col_spacings(table, 5); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Fixed")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new()); - gtk_widget_show(GTK_WIDGET(check)); - gtk_table_attach(table, GTK_WIDGET(check), 1, 2, 0, 1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - m_subdivisions.m_enabled = check; - guint handler_id = g_signal_connect(G_OBJECT(check), "toggled", G_CALLBACK(&Subdivisions::applyGtk), &m_subdivisions); - g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler_id)); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Horizontal")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - m_subdivisions.m_horizontal = entry; - m_horizontalSubdivisionsEntry.connect(entry); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Vertical")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 2, 3, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 2, 3, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - m_subdivisions.m_vertical = entry; - m_verticalSubdivisionsEntry.connect(entry); - } - } - } - } - } - { - GtkFrame* frame = GTK_FRAME(gtk_frame_new("Texturing")); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(frame), TRUE, TRUE, 0); - { - GtkVBox* vbox2 = GTK_VBOX(gtk_vbox_new(FALSE, 5)); - gtk_widget_show(GTK_WIDGET(vbox2)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox2)); - gtk_container_set_border_width(GTK_CONTAINER(vbox2), 5); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Name:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(label), TRUE, TRUE, 0); - gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - // gtk_entry_set_editable (GTK_ENTRY (entry), false); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(entry), TRUE, TRUE, 0); - AddDialogData(*entry, m_strName); - - g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); - } - { - GtkTable* table = GTK_TABLE(gtk_table_new(5, 3, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings(table, 5); - gtk_table_set_col_spacings(table, 5); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Horizontal Shift Step")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 0, 1, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Vertical Shift Step")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 1, 2, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Horizontal Stretch Step")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 2, 3, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Vertical Stretch Step")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 3, 4, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Rotate Step")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 4, 5, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 0, 1, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - g_object_set_data(G_OBJECT(window), "hshift_entry", entry); - // we fill in this data, if no patch is selected the widgets are unmodified when the inspector is raised - // so we need to have at least one initialisation somewhere - entry_set_float(entry, g_pi_globals.shift[0]); - - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 1, 1, 0)); - g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); - g_object_set_data(G_OBJECT(window), "hshift_adj", adj); - - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 0, 1, - (GtkAttachOptions)(0), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); - GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 1, 2, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - entry_set_float(entry, g_pi_globals.shift[1]); - - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 1, 1, 0)); - g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); - g_object_set_data(G_OBJECT(window), "vshift_adj", adj); - - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 1, 2, - (GtkAttachOptions)(0), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); - GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 2, 3, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - entry_set_float(entry, g_pi_globals.scale[0]); - - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -1000, 1000, 1, 1, 0)); - g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); - g_object_set_data(G_OBJECT(window), "hscale_adj", adj); - - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 2, 3, - (GtkAttachOptions)(0), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); - GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 3, 4, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - entry_set_float(entry, g_pi_globals.scale[1]); - - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -1000, 1000, 1, 1, 0)); - g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); - g_object_set_data(G_OBJECT(window), "vscale_adj", adj); - - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 3, 4, - (GtkAttachOptions)(0), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); - GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 4, 5, - (GtkAttachOptions)(GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - entry_set_float(entry, g_pi_globals.rotate); - - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -1000, 1000, 1, 1, 0)); // NOTE: Arnout - this really should be 360 but can't change it anymore as it could break existing maps - g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); - g_object_set_data(G_OBJECT(window), "rotate_adj", adj); - - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 4, 5, - (GtkAttachOptions)(0), - (GtkAttachOptions)(0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); - GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); - } - } - GtkHBox* hbox2 = GTK_HBOX(gtk_hbox_new(TRUE, 5)); - gtk_widget_show(GTK_WIDGET(hbox2)); - gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(hbox2), TRUE, FALSE, 0); - { - GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("CAP")); - gtk_widget_show(GTK_WIDGET(button)); - gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchdetails), 0); - gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); - } - { - GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Set...")); - gtk_widget_show(GTK_WIDGET(button)); - gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchreset), 0); - gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); - } - { - GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Natural")); - gtk_widget_show(GTK_WIDGET(button)); - gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchnatural), 0); - gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); - } - { - GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Fit")); - gtk_widget_show(GTK_WIDGET(button)); - gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchfit), 0); - gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); - } - } - } - } - } - - return window; -} - -// sync the dialog our internal data structures -void PatchInspector::exportData() -{ - m_bListenChanged = false; - Dialog::exportData(); - m_bListenChanged = true; -} -void PatchInspector::importData() -{ - m_bListenChanged = false; - Dialog::importData(); - m_bListenChanged = true; -} - -// read the map and feed in the stuff to the dialog box -void PatchInspector::GetPatchInfo() -{ - if(g_pGameDescription->mGameType == "doom3") - { - m_subdivisions.update(); - } - - if(GlobalSelectionSystem().countSelected() == 0) - { - m_Patch = 0; - } - else - { - m_Patch = Node_getPatch(GlobalSelectionSystem().ultimateSelected().path().top()); - } - - if (m_Patch != 0) - { - m_strName = m_Patch->GetShader(); - - // fill in the numbers for Row / Col selection - m_bListenChanged = false; - - { - gtk_combo_box_set_active(m_pRowCombo, 0); - - for (std::size_t i = 0; i < m_countRows; ++i) - { - gtk_combo_box_remove_text(m_pRowCombo, gint(m_countRows - i - 1)); - } - - m_countRows = m_Patch->getHeight(); - for (std::size_t i = 0; i < m_countRows; ++i) - { - char buffer[16]; - sprintf(buffer, "%u", Unsigned(i)); - gtk_combo_box_append_text(m_pRowCombo, buffer); - } - - gtk_combo_box_set_active(m_pRowCombo, 0); - } - - { - gtk_combo_box_set_active(m_pColCombo, 0); - - for (std::size_t i = 0; i < m_countCols; ++i) - { - gtk_combo_box_remove_text(m_pColCombo, gint(m_countCols - i - 1)); - } - - m_countCols = m_Patch->getWidth(); - for (std::size_t i = 0; i < m_countCols; ++i) - { - char buffer[16]; - sprintf(buffer, "%u", Unsigned(i)); - gtk_combo_box_append_text(m_pColCombo, buffer); - } - - gtk_combo_box_set_active(m_pColCombo, 0); - } - - m_bListenChanged = true; - - } - else - { - //globalOutputStream() << "WARNING: no patch\n"; - } - // fill in our internal structs - m_nRow = 0; m_nCol = 0; - UpdateRowColInfo(); - // now update the dialog box - importData(); -} - -// read the current patch on map and initialize m_fX m_fY accordingly -// NOTE: don't call UpdateData in there, it's not meant for -void PatchInspector::UpdateRowColInfo() -{ - m_fX = m_fY = m_fZ = m_fS = m_fT = 0.0; - - if (m_Patch != 0) - { - // we rely on whatever active row/column has been set before we get called - std::size_t r = m_nRow; - std::size_t c = m_nCol; - if(r < m_Patch->getHeight() - && c < m_Patch->getWidth()) - { - const PatchControl& p = m_Patch->ctrlAt(r,c); - m_fX = p.m_vertex[0]; - m_fY = p.m_vertex[1]; - m_fZ = p.m_vertex[2]; - m_fS = p.m_texcoord[0]; - m_fT = p.m_texcoord[1]; - } - } -} - - -void PatchInspector_SelectionChanged(const Selectable& selectable) -{ - PatchInspector_queueDraw(); -} - - -#include "preferencesystem.h" - - -void PatchInspector_Construct() -{ - GlobalCommands_insert("PatchInspector", FreeCaller(), Accelerator('S', (GdkModifierType)GDK_SHIFT_MASK)); - - GlobalPreferenceSystem().registerPreference("PatchWnd", WindowPositionTrackerImportStringCaller(g_PatchInspector.m_position_tracker), WindowPositionTrackerExportStringCaller(g_PatchInspector.m_position_tracker)); - GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Scale1", FloatImportStringCaller(g_pi_globals.scale[0]), FloatExportStringCaller(g_pi_globals.scale[0])); - GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Scale2", FloatImportStringCaller(g_pi_globals.scale[1]), FloatExportStringCaller(g_pi_globals.scale[1])); - GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Shift1", FloatImportStringCaller(g_pi_globals.shift[0]), FloatExportStringCaller(g_pi_globals.shift[0])); - GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Shift2", FloatImportStringCaller(g_pi_globals.shift[1]), FloatExportStringCaller(g_pi_globals.shift[1])); - GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Rotate", FloatImportStringCaller(g_pi_globals.rotate), FloatExportStringCaller(g_pi_globals.rotate)); - - typedef FreeCaller1 PatchInspectorSelectionChangedCaller; - GlobalSelectionSystem().addSelectionChangeCallback(PatchInspectorSelectionChangedCaller()); - typedef FreeCaller PatchInspectorQueueDrawCaller; - Patch_addTextureChangedCallback(PatchInspectorQueueDrawCaller()); -} -void PatchInspector_Destroy() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/patchdialog.h b/misc/mediasource/extra/netradiant-src/radiant/patchdialog.h deleted file mode 100644 index 61bcb07b..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patchdialog.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_PATCHDIALOG_H) -#define INCLUDED_PATCHDIALOG_H - -void PatchInspector_Construct(); -void PatchInspector_Destroy(); - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; -void PatchInspector_constructWindow(GtkWindow* main_window); -void PatchInspector_destroyWindow(); - -namespace scene -{ - class Graph; -} - -void Scene_PatchTranslateTexture_Selected(scene::Graph& graph, float s, float t); -void Scene_PatchRotateTexture_Selected(scene::Graph& graph, float angle); -void Scene_PatchScaleTexture_Selected(scene::Graph& graph, float s, float t); - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/patchmanip.cpp b/misc/mediasource/extra/netradiant-src/radiant/patchmanip.cpp deleted file mode 100644 index b8bccee6..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patchmanip.cpp +++ /dev/null @@ -1,1149 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "patchmanip.h" - -#include "debugging/debugging.h" - - -#include "iselection.h" -#include "ipatch.h" - -#include "math/vector.h" -#include "math/aabb.h" -#include "generic/callback.h" - -#include "gtkutil/menu.h" -#include "gtkutil/image.h" -#include "map.h" -#include "mainframe.h" -#include "commands.h" -#include "gtkmisc.h" -#include "gtkdlgs.h" -#include "texwindow.h" -#include "xywindow.h" -#include "select.h" -#include "patch.h" -#include "grid.h" - -PatchCreator* g_patchCreator = 0; - -void Scene_PatchConstructPrefab(scene::Graph& graph, const AABB aabb, const char* shader, EPatchPrefab eType, int axis, std::size_t width = 3, std::size_t height = 3) -{ - Select_Delete(); - GlobalSelectionSystem().setSelectedAll(false); - - NodeSmartReference node(g_patchCreator->createPatch()); - Node_getTraversable(Map_FindOrInsertWorldspawn(g_map))->insert(node); - - Patch* patch = Node_getPatch(node); - patch->SetShader(shader); - - patch->ConstructPrefab(aabb, eType, axis, width, height); - patch->controlPointsChanged(); - - { - scene::Path patchpath(makeReference(GlobalSceneGraph().root())); - patchpath.push(makeReference(*Map_GetWorldspawn(g_map))); - patchpath.push(makeReference(node.get())); - Instance_getSelectable(*graph.find(patchpath))->setSelected(true); - } -} - - -void Patch_makeCaps(Patch& patch, scene::Instance& instance, EPatchCap type, const char* shader) -{ - if((type == eCapEndCap || type == eCapIEndCap) - && patch.getWidth() != 5) - { - globalErrorStream() << "cannot create end-cap - patch width != 5\n"; - return; - } - if((type == eCapBevel || type == eCapIBevel) - && patch.getWidth() != 3 && patch.getWidth() != 5) - { - globalErrorStream() << "cannot create bevel-cap - patch width != 3\n"; - return; - } - if(type == eCapCylinder - && patch.getWidth() != 9) - { - globalErrorStream() << "cannot create cylinder-cap - patch width != 9\n"; - return; - } - - { - NodeSmartReference cap(g_patchCreator->createPatch()); - Node_getTraversable(instance.path().parent())->insert(cap); - - patch.MakeCap(Node_getPatch(cap), type, ROW, true); - Node_getPatch(cap)->SetShader(shader); - - scene::Path path(instance.path()); - path.pop(); - path.push(makeReference(cap.get())); - selectPath(path, true); - } - - { - NodeSmartReference cap(g_patchCreator->createPatch()); - Node_getTraversable(instance.path().parent())->insert(cap); - - patch.MakeCap(Node_getPatch(cap), type, ROW, false); - Node_getPatch(cap)->SetShader(shader); - - scene::Path path(instance.path()); - path.pop(); - path.push(makeReference(cap.get())); - selectPath(path, true); - } -} - -typedef std::vector InstanceVector; - -class PatchStoreInstance -{ - InstanceVector& m_instances; -public: - PatchStoreInstance(InstanceVector& instances) : m_instances(instances) - { - } - void operator()(PatchInstance& patch) const - { - m_instances.push_back(&patch); - } -}; - -enum ECapDialog { - PATCHCAP_BEVEL = 0, - PATCHCAP_ENDCAP, - PATCHCAP_INVERTED_BEVEL, - PATCHCAP_INVERTED_ENDCAP, - PATCHCAP_CYLINDER -}; - -EMessageBoxReturn DoCapDlg(ECapDialog *type); - -void Scene_PatchDoCap_Selected(scene::Graph& graph, const char* shader) -{ - ECapDialog nType; - - if(DoCapDlg(&nType) == eIDOK) - { - EPatchCap eType; - switch(nType) - { - case PATCHCAP_INVERTED_BEVEL: - eType = eCapIBevel; - break; - case PATCHCAP_BEVEL: - eType = eCapBevel; - break; - case PATCHCAP_INVERTED_ENDCAP: - eType = eCapIEndCap; - break; - case PATCHCAP_ENDCAP: - eType = eCapEndCap; - break; - case PATCHCAP_CYLINDER: - eType = eCapCylinder; - break; - default: - ERROR_MESSAGE("invalid patch cap type"); - return; - } - - InstanceVector instances; - Scene_forEachVisibleSelectedPatchInstance(PatchStoreInstance(instances)); - for(InstanceVector::const_iterator i = instances.begin(); i != instances.end(); ++i) - { - Patch_makeCaps(* Node_getPatch((*i)->path().top()), *(*i), eType, shader); - } - } -} - -Patch* Scene_GetUltimateSelectedVisiblePatch() -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - scene::Node& node = GlobalSelectionSystem().ultimateSelected().path().top(); - if(node.visible()) - { - return Node_getPatch(node); - } - } - return 0; -} - - -class PatchCapTexture -{ -public: - void operator()(Patch& patch) const - { - patch.ProjectTexture(Patch::m_CycleCapIndex); - } -}; - -void Scene_PatchCapTexture_Selected(scene::Graph& graph) -{ - Scene_forEachVisibleSelectedPatch(PatchCapTexture()); - Patch::m_CycleCapIndex = (Patch::m_CycleCapIndex == 0) ? 1 : (Patch::m_CycleCapIndex == 1) ? 2 : 0; - SceneChangeNotify(); -} - -class PatchFlipTexture -{ - int m_axis; -public: - PatchFlipTexture(int axis) : m_axis(axis) - { - } - void operator()(Patch& patch) const - { - patch.FlipTexture(m_axis); - } -}; - -void Scene_PatchFlipTexture_Selected(scene::Graph& graph, int axis) -{ - Scene_forEachVisibleSelectedPatch(PatchFlipTexture(axis)); -} - -class PatchNaturalTexture -{ -public: - void operator()(Patch& patch) const - { - patch.NaturalTexture(); - } -}; - -void Scene_PatchNaturalTexture_Selected(scene::Graph& graph) -{ - Scene_forEachVisibleSelectedPatch(PatchNaturalTexture()); - SceneChangeNotify(); -} - - -class PatchInsertRemove -{ - bool m_insert, m_column, m_first; -public: - PatchInsertRemove(bool insert, bool column, bool first) : m_insert(insert), m_column(column), m_first(first) - { - } - void operator()(Patch& patch) const - { - patch.InsertRemove(m_insert, m_column, m_first); - } -}; - -void Scene_PatchInsertRemove_Selected(scene::Graph& graph, bool bInsert, bool bColumn, bool bFirst) -{ - Scene_forEachVisibleSelectedPatch(PatchInsertRemove(bInsert, bColumn, bFirst)); -} - -class PatchInvertMatrix -{ -public: - void operator()(Patch& patch) const - { - patch.InvertMatrix(); - } -}; - -void Scene_PatchInvert_Selected(scene::Graph& graph) -{ - Scene_forEachVisibleSelectedPatch(PatchInvertMatrix()); -} - -class PatchRedisperse -{ - EMatrixMajor m_major; -public: - PatchRedisperse(EMatrixMajor major) : m_major(major) - { - } - void operator()(Patch& patch) const - { - patch.Redisperse(m_major); - } -}; - -void Scene_PatchRedisperse_Selected(scene::Graph& graph, EMatrixMajor major) -{ - Scene_forEachVisibleSelectedPatch(PatchRedisperse(major)); -} - -class PatchSmooth -{ - EMatrixMajor m_major; -public: - PatchSmooth(EMatrixMajor major) : m_major(major) - { - } - void operator()(Patch& patch) const - { - patch.Smooth(m_major); - } -}; - -void Scene_PatchSmooth_Selected(scene::Graph& graph, EMatrixMajor major) -{ - Scene_forEachVisibleSelectedPatch(PatchSmooth(major)); -} - -class PatchTransposeMatrix -{ -public: - void operator()(Patch& patch) const - { - patch.TransposeMatrix(); - } -}; - -void Scene_PatchTranspose_Selected(scene::Graph& graph) -{ - Scene_forEachVisibleSelectedPatch(PatchTransposeMatrix()); -} - -class PatchSetShader -{ - const char* m_name; -public: - PatchSetShader(const char* name) - : m_name(name) - { - } - void operator()(Patch& patch) const - { - patch.SetShader(m_name); - } -}; - -void Scene_PatchSetShader_Selected(scene::Graph& graph, const char* name) -{ - Scene_forEachVisibleSelectedPatch(PatchSetShader(name)); - SceneChangeNotify(); -} - -void Scene_PatchGetShader_Selected(scene::Graph& graph, CopiedString& name) -{ - Patch* patch = Scene_GetUltimateSelectedVisiblePatch(); - if(patch != 0) - { - name = patch->GetShader(); - } -} - -class PatchSelectByShader -{ - const char* m_name; -public: - inline PatchSelectByShader(const char* name) - : m_name(name) - { - } - void operator()(PatchInstance& patch) const - { - if(shader_equal(patch.getPatch().GetShader(), m_name)) - { - patch.setSelected(true); - } - } -}; - -void Scene_PatchSelectByShader(scene::Graph& graph, const char* name) -{ - Scene_forEachVisiblePatchInstance(PatchSelectByShader(name)); -} - - -class PatchFindReplaceShader -{ - const char* m_find; - const char* m_replace; -public: - PatchFindReplaceShader(const char* find, const char* replace) : m_find(find), m_replace(replace) - { - } - void operator()(Patch& patch) const - { - if(shader_equal(patch.GetShader(), m_find)) - { - patch.SetShader(m_replace); - } - } -}; - -void Scene_PatchFindReplaceShader(scene::Graph& graph, const char* find, const char* replace) -{ - Scene_forEachVisiblePatch(PatchFindReplaceShader(find, replace)); -} - -void Scene_PatchFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace) -{ - Scene_forEachVisibleSelectedPatch(PatchFindReplaceShader(find, replace)); -} - - -AABB PatchCreator_getBounds() -{ - AABB aabb(aabb_for_minmax(Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max)); - - float gridSize = GetGridSize(); - - if(aabb.extents[0] == 0) - { - aabb.extents[0] = gridSize; - } - if(aabb.extents[1] == 0) - { - aabb.extents[1] = gridSize; - } - if(aabb.extents[2] == 0) - { - aabb.extents[2] = gridSize; - } - - if(aabb_valid(aabb)) - { - return aabb; - } - return AABB(Vector3(0, 0, 0), Vector3(64, 64, 64)); -} - -void Patch_Cylinder() -{ - UndoableCommand undo("patchCreateCylinder"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eCylinder, GlobalXYWnd_getCurrentViewType()); -} - -void Patch_DenseCylinder() -{ - UndoableCommand undo("patchCreateDenseCylinder"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eDenseCylinder, GlobalXYWnd_getCurrentViewType()); -} - -void Patch_VeryDenseCylinder() -{ - UndoableCommand undo("patchCreateVeryDenseCylinder"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eVeryDenseCylinder, GlobalXYWnd_getCurrentViewType()); -} - -void Patch_SquareCylinder() -{ - UndoableCommand undo("patchCreateSquareCylinder"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eSqCylinder, GlobalXYWnd_getCurrentViewType()); -} - -void Patch_Endcap() -{ - UndoableCommand undo("patchCreateCaps"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eEndCap, GlobalXYWnd_getCurrentViewType()); -} - -void Patch_Bevel() -{ - UndoableCommand undo("patchCreateBevel"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eBevel, GlobalXYWnd_getCurrentViewType()); -} - -void Patch_Sphere() -{ - UndoableCommand undo("patchCreateSphere"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eSphere, GlobalXYWnd_getCurrentViewType()); -} - -void Patch_SquareBevel() -{ -} - -void Patch_SquareEndcap() -{ -} - -void Patch_Cone() -{ - UndoableCommand undo("patchCreateCone"); - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eCone, GlobalXYWnd_getCurrentViewType()); -} - -void DoNewPatchDlg(); - -void Patch_Plane() -{ - UndoableCommand undo("patchCreatePlane"); - - DoNewPatchDlg(); -} - -void Patch_InsertInsertColumn() -{ - UndoableCommand undo("patchInsertColumns"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, true, false); -} - -void Patch_InsertAddColumn() -{ - UndoableCommand undo("patchAddColumns"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, true, true); -} - -void Patch_InsertInsertRow() -{ - UndoableCommand undo("patchInsertRows"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, false, false); -} - -void Patch_InsertAddRow() -{ - UndoableCommand undo("patchAddRows"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, false, true); -} - -void Patch_DeleteFirstColumn() -{ - UndoableCommand undo("patchDeleteFirstColumns"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, true, true); -} - -void Patch_DeleteLastColumn() -{ - UndoableCommand undo("patchDeleteLastColumns"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, true, false); -} - -void Patch_DeleteFirstRow() -{ - UndoableCommand undo("patchDeleteFirstRows"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, false, true); -} - -void Patch_DeleteLastRow() -{ - UndoableCommand undo("patchDeleteLastRows"); - - Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, false, false); -} - -void Patch_Invert() -{ - UndoableCommand undo("patchInvert"); - - Scene_PatchInvert_Selected(GlobalSceneGraph()); -} - -void Patch_RedisperseRows() -{ - UndoableCommand undo("patchRedisperseRows"); - - Scene_PatchRedisperse_Selected(GlobalSceneGraph(), ROW); -} - -void Patch_RedisperseCols() -{ - UndoableCommand undo("patchRedisperseColumns"); - - Scene_PatchRedisperse_Selected(GlobalSceneGraph(), COL); -} - -void Patch_SmoothRows() -{ - UndoableCommand undo("patchSmoothRows"); - - Scene_PatchSmooth_Selected(GlobalSceneGraph(), ROW); -} - -void Patch_SmoothCols() -{ - UndoableCommand undo("patchSmoothColumns"); - - Scene_PatchSmooth_Selected(GlobalSceneGraph(), COL); -} - -void Patch_Transpose() -{ - UndoableCommand undo("patchTranspose"); - - Scene_PatchTranspose_Selected(GlobalSceneGraph()); -} - -void Patch_Cap() -{ - // FIXME: add support for patch cap creation - // Patch_CapCurrent(); - UndoableCommand undo("patchCreateCaps"); - - Scene_PatchDoCap_Selected(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); -} - -void Patch_CycleProjection() -{ - UndoableCommand undo("patchCycleUVProjectionAxis"); - - Scene_PatchCapTexture_Selected(GlobalSceneGraph()); -} - -///\todo Unfinished. -void Patch_OverlayOn() -{ -} - -///\todo Unfinished. -void Patch_OverlayOff() -{ -} - -void Patch_FlipTextureX() -{ - UndoableCommand undo("patchFlipTextureU"); - - Scene_PatchFlipTexture_Selected(GlobalSceneGraph(), 0); -} - -void Patch_FlipTextureY() -{ - UndoableCommand undo("patchFlipTextureV"); - - Scene_PatchFlipTexture_Selected(GlobalSceneGraph(), 1); -} - -void Patch_NaturalTexture() -{ - UndoableCommand undo("patchNaturalTexture"); - - Scene_PatchNaturalTexture_Selected(GlobalSceneGraph()); -} - - - - -#include "ifilter.h" - - -class filter_patch_all : public PatchFilter -{ -public: - bool filter(const Patch& patch) const - { - return true; - } -}; - -class filter_patch_shader : public PatchFilter -{ - const char* m_shader; -public: - filter_patch_shader(const char* shader) : m_shader(shader) - { - } - bool filter(const Patch& patch) const - { - return shader_equal(patch.GetShader(), m_shader); - } -}; - -class filter_patch_flags : public PatchFilter -{ - int m_flags; -public: - filter_patch_flags(int flags) : m_flags(flags) - { - } - bool filter(const Patch& patch) const - { - return (patch.getShaderFlags() & m_flags) != 0; - } -}; - - -filter_patch_all g_filter_patch_all; -filter_patch_shader g_filter_patch_clip("textures/common/clip"); -filter_patch_shader g_filter_patch_weapclip("textures/common/weapclip"); -filter_patch_flags g_filter_patch_translucent(QER_TRANS); - -void PatchFilters_construct() -{ - add_patch_filter(g_filter_patch_all, EXCLUDE_CURVES); - add_patch_filter(g_filter_patch_clip, EXCLUDE_CLIP); - add_patch_filter(g_filter_patch_weapclip, EXCLUDE_CLIP); - add_patch_filter(g_filter_patch_translucent, EXCLUDE_TRANSLUCENT); -} - - -#include "preferences.h" - -void Patch_constructPreferences(PreferencesPage& page) -{ - page.appendEntry("Patch Subdivide Threshold", g_PatchSubdivideThreshold); -} -void Patch_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Patches", "Patch Display Preferences")); - Patch_constructPreferences(page); -} -void Patch_registerPreferencesPage() -{ - PreferencesDialog_addDisplayPage(FreeCaller1()); -} - - -#include "preferencesystem.h" - -void PatchPreferences_construct() -{ - GlobalPreferenceSystem().registerPreference("Subdivisions", IntImportStringCaller(g_PatchSubdivideThreshold), IntExportStringCaller(g_PatchSubdivideThreshold)); -} - - -#include "generic/callback.h" - -void Patch_registerCommands() -{ - GlobalCommands_insert("InvertCurveTextureX", FreeCaller(), Accelerator('I', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("InvertCurveTextureY", FreeCaller(), Accelerator('I', (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("IncPatchColumn", FreeCaller(), Accelerator(GDK_KP_Add, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("IncPatchRow", FreeCaller(), Accelerator(GDK_KP_Add, (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("DecPatchColumn", FreeCaller(), Accelerator(GDK_KP_Subtract, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("DecPatchRow", FreeCaller(), Accelerator(GDK_KP_Subtract, (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("NaturalizePatch", FreeCaller(), Accelerator('N', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("PatchCylinder", FreeCaller()); - GlobalCommands_insert("PatchDenseCylinder", FreeCaller()); - GlobalCommands_insert("PatchVeryDenseCylinder", FreeCaller()); - GlobalCommands_insert("PatchSquareCylinder", FreeCaller()); - GlobalCommands_insert("PatchEndCap", FreeCaller()); - GlobalCommands_insert("PatchBevel", FreeCaller()); - GlobalCommands_insert("PatchSquareBevel", FreeCaller()); - GlobalCommands_insert("PatchSquareEndcap", FreeCaller()); - GlobalCommands_insert("PatchCone", FreeCaller()); - GlobalCommands_insert("PatchSphere", FreeCaller()); - GlobalCommands_insert("SimplePatchMesh", FreeCaller(), Accelerator('P', (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("PatchInsertInsertColumn", FreeCaller()); - GlobalCommands_insert("PatchInsertAddColumn", FreeCaller()); - GlobalCommands_insert("PatchInsertInsertRow", FreeCaller()); - GlobalCommands_insert("PatchInsertAddRow", FreeCaller()); - GlobalCommands_insert("PatchDeleteFirstColumn", FreeCaller()); - GlobalCommands_insert("PatchDeleteLastColumn", FreeCaller()); - GlobalCommands_insert("PatchDeleteFirstRow", FreeCaller()); - GlobalCommands_insert("PatchDeleteLastRow", FreeCaller()); - GlobalCommands_insert("InvertCurve", FreeCaller(), Accelerator('I', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("RedisperseRows", FreeCaller(), Accelerator('E', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("RedisperseCols", FreeCaller(), Accelerator('E', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("SmoothRows", FreeCaller(), Accelerator('W', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("SmoothCols", FreeCaller(), Accelerator('W', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("MatrixTranspose", FreeCaller(), Accelerator('M', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("CapCurrentCurve", FreeCaller(), Accelerator('C', (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("CycleCapTexturePatch", FreeCaller(), Accelerator('N', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("MakeOverlayPatch", FreeCaller(), Accelerator('Y')); - GlobalCommands_insert("ClearPatchOverlays", FreeCaller(), Accelerator('L', (GdkModifierType)GDK_CONTROL_MASK)); -} - -void Patch_constructToolbar(GtkToolbar* toolbar) -{ - toolbar_append_button(toolbar, "Put caps on the current patch (SHIFT + C)", "curve_cap.bmp", "CapCurrentCurve"); -} - -void Patch_constructMenu(GtkMenu* menu) -{ - create_menu_item_with_mnemonic(menu, "Cylinder", "PatchCylinder"); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "More Cylinders"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Dense Cylinder", "PatchDenseCylinder"); - create_menu_item_with_mnemonic(menu_in_menu, "Very Dense Cylinder", "PatchVeryDenseCylinder"); - create_menu_item_with_mnemonic(menu_in_menu, "Square Cylinder", "PatchSquareCylinder"); - } - menu_separator (menu); - create_menu_item_with_mnemonic(menu, "End cap", "PatchEndCap"); - create_menu_item_with_mnemonic(menu, "Bevel", "PatchBevel"); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "More End caps, Bevels"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Square Endcap", "PatchSquareBevel"); - create_menu_item_with_mnemonic(menu_in_menu, "Square Bevel", "PatchSquareEndcap"); - } - menu_separator (menu); - create_menu_item_with_mnemonic(menu, "Cone", "PatchCone"); - create_menu_item_with_mnemonic(menu, "Sphere", "PatchSphere"); - menu_separator (menu); - create_menu_item_with_mnemonic(menu, "Simple Patch Mesh...", "SimplePatchMesh"); - menu_separator (menu); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Insert"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Insert (2) Columns", "PatchInsertInsertColumn"); - create_menu_item_with_mnemonic(menu_in_menu, "Add (2) Columns", "PatchInsertAddColumn"); - menu_separator (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Insert (2) Rows", "PatchInsertInsertRow"); - create_menu_item_with_mnemonic(menu_in_menu, "Add (2) Rows", "PatchInsertAddRow"); - } - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Delete"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "First (2) Columns", "PatchDeleteFirstColumn"); - create_menu_item_with_mnemonic(menu_in_menu, "Last (2) Columns", "PatchDeleteLastColumn"); - menu_separator (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "First (2) Rows", "PatchDeleteFirstRow"); - create_menu_item_with_mnemonic(menu_in_menu, "Last (2) Rows", "PatchDeleteLastRow"); - } - menu_separator (menu); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Matrix"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Invert", "InvertCurve"); - GtkMenu* menu_3 = create_sub_menu_with_mnemonic (menu_in_menu, "Re-disperse"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_3); - create_menu_item_with_mnemonic(menu_3, "Rows", "RedisperseRows"); - create_menu_item_with_mnemonic(menu_3, "Columns", "RedisperseCols"); - GtkMenu* menu_4 = create_sub_menu_with_mnemonic (menu_in_menu, "Smooth"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_4); - create_menu_item_with_mnemonic(menu_4, "Rows", "SmoothRows"); - create_menu_item_with_mnemonic(menu_4, "Columns", "SmoothCols"); - create_menu_item_with_mnemonic(menu_in_menu, "Transpose", "MatrixTranspose"); - } - menu_separator (menu); - create_menu_item_with_mnemonic(menu, "Cap Selection", "CapCurrentCurve"); - create_menu_item_with_mnemonic(menu, "Cycle Cap Texture", "CycleCapTexturePatch"); - menu_separator (menu); - { - GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Overlay"); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu_in_menu); - create_menu_item_with_mnemonic(menu_in_menu, "Set", "MakeOverlayPatch"); - create_menu_item_with_mnemonic(menu_in_menu, "Clear", "ClearPatchOverlays"); - } -} - - -#include -#include -#include -#include -#include -#include -#include "gtkutil/dialog.h" -#include "gtkutil/widget.h" - -void DoNewPatchDlg() -{ - ModalDialog dialog; - GtkComboBox* width; - GtkComboBox* height; - - GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Patch density", G_CALLBACK(dialog_delete_callback), &dialog); - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - { - GtkTable* table = create_dialog_table(2, 2, 4, 4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Width:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - { - GtkLabel* label = GTK_LABEL(gtk_label_new("Height:")); - gtk_widget_show(GTK_WIDGET(label)); - gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); - } - - { - GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); - gtk_combo_box_append_text(combo, "3"); - gtk_combo_box_append_text(combo, "5"); - gtk_combo_box_append_text(combo, "7"); - gtk_combo_box_append_text(combo, "9"); - gtk_combo_box_append_text(combo, "11"); - gtk_combo_box_append_text(combo, "13"); - gtk_combo_box_append_text(combo, "15"); - gtk_combo_box_append_text(combo, "17"); - gtk_combo_box_append_text(combo, "19"); - gtk_combo_box_append_text(combo, "21"); - gtk_combo_box_append_text(combo, "23"); - gtk_combo_box_append_text(combo, "25"); - gtk_combo_box_append_text(combo, "27"); - gtk_combo_box_append_text(combo, "29"); - gtk_combo_box_append_text(combo, "31"); // MAX_PATCH_SIZE is 32, so we should be able to do 31... - gtk_widget_show(GTK_WIDGET(combo)); - gtk_table_attach(table, GTK_WIDGET(combo), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - width = combo; - } - { - GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); - gtk_combo_box_append_text(combo, "3"); - gtk_combo_box_append_text(combo, "5"); - gtk_combo_box_append_text(combo, "7"); - gtk_combo_box_append_text(combo, "9"); - gtk_combo_box_append_text(combo, "11"); - gtk_combo_box_append_text(combo, "13"); - gtk_combo_box_append_text(combo, "15"); - gtk_combo_box_append_text(combo, "17"); - gtk_combo_box_append_text(combo, "19"); - gtk_combo_box_append_text(combo, "21"); - gtk_combo_box_append_text(combo, "23"); - gtk_combo_box_append_text(combo, "25"); - gtk_combo_box_append_text(combo, "27"); - gtk_combo_box_append_text(combo, "29"); - gtk_combo_box_append_text(combo, "31"); // MAX_PATCH_SIZE is 32, so we should be able to do 31... - gtk_widget_show(GTK_WIDGET(combo)); - gtk_table_attach(table, GTK_WIDGET(combo), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - height = combo; - } - } - - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_grab_focus(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - } - } - } - - // Initialize dialog - gtk_combo_box_set_active(width, 0); - gtk_combo_box_set_active(height, 0); - - if(modal_dialog_show(window, dialog) == eIDOK) - { - int w = gtk_combo_box_get_active(width) * 2 + 3; - int h = gtk_combo_box_get_active(height) * 2 + 3; - - Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), ePlane, GlobalXYWnd_getCurrentViewType(), w, h); - } - - gtk_widget_destroy(GTK_WIDGET(window)); -} - - - - -EMessageBoxReturn DoCapDlg(ECapDialog* type) -{ - ModalDialog dialog; - ModalDialogButton ok_button(dialog, eIDOK); - ModalDialogButton cancel_button(dialog, eIDCANCEL); - GtkWidget* bevel; - GtkWidget* ibevel; - GtkWidget* endcap; - GtkWidget* iendcap; - GtkWidget* cylinder; - - GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Cap", dialog); - - GtkAccelGroup *accel_group = gtk_accel_group_new(); - gtk_window_add_accel_group(window, accel_group); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); - - { - // Gef: Added a vbox to contain the toggle buttons - GtkVBox* radio_vbox = create_dialog_vbox(4); - gtk_container_add(GTK_CONTAINER(hbox), GTK_WIDGET(radio_vbox)); - - { - GtkTable* table = GTK_TABLE(gtk_table_new(5, 2, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(radio_vbox), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings(table, 5); - gtk_table_set_col_spacings(table, 5); - - { - GtkImage* image = new_local_image("cap_bevel.bmp"); - gtk_widget_show(GTK_WIDGET(image)); - gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkImage* image = new_local_image("cap_endcap.bmp"); - gtk_widget_show(GTK_WIDGET(image)); - gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkImage* image = new_local_image("cap_ibevel.bmp"); - gtk_widget_show(GTK_WIDGET(image)); - gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkImage* image = new_local_image("cap_iendcap.bmp"); - gtk_widget_show(GTK_WIDGET(image)); - gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 3, 4, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkImage* image = new_local_image("cap_cylinder.bmp"); - gtk_widget_show(GTK_WIDGET(image)); - gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 4, 5, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - - GSList* group = 0; - { - GtkWidget* button = gtk_radio_button_new_with_label (group, "Bevel"); - gtk_widget_show (button); - gtk_table_attach(table, button, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), - (GtkAttachOptions) (0), 0, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); - - bevel = button; - } - { - GtkWidget* button = gtk_radio_button_new_with_label (group, "Endcap"); - gtk_widget_show (button); - gtk_table_attach(table, button, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), - (GtkAttachOptions) (0), 0, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); - - endcap = button; - } - { - GtkWidget* button = gtk_radio_button_new_with_label (group, "Inverted Bevel"); - gtk_widget_show (button); - gtk_table_attach(table, button, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), - (GtkAttachOptions) (0), 0, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); - - ibevel = button; - } - { - GtkWidget* button = gtk_radio_button_new_with_label (group, "Inverted Endcap"); - gtk_widget_show (button); - gtk_table_attach(table, button, 1, 2, 3, 4, - (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), - (GtkAttachOptions) (0), 0, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); - - iendcap = button; - } - { - GtkWidget* button = gtk_radio_button_new_with_label (group, "Cylinder"); - gtk_widget_show (button); - gtk_table_attach(table, button, 1, 2, 4, 5, - (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), - (GtkAttachOptions) (0), 0, 0); - group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); - - cylinder = button; - } - } - } - - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); - { - GtkButton* button = create_modal_dialog_button("OK", ok_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); - } - { - GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Escape, (GdkModifierType)0, GTK_ACCEL_VISIBLE); - } - } - } - - // Initialize dialog - gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (bevel), TRUE); - - EMessageBoxReturn ret = modal_dialog_show(window, dialog); - if (ret == eIDOK) - { - if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (bevel))) - *type = PATCHCAP_BEVEL; - else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(endcap))) - *type = PATCHCAP_ENDCAP; - else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(ibevel))) - *type = PATCHCAP_INVERTED_BEVEL; - else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(iendcap))) - *type = PATCHCAP_INVERTED_ENDCAP; - else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cylinder))) - *type = PATCHCAP_CYLINDER; - } - - gtk_widget_destroy(GTK_WIDGET(window)); - - return ret; -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/patchmanip.h b/misc/mediasource/extra/netradiant-src/radiant/patchmanip.h deleted file mode 100644 index e4d372e1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patchmanip.h +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright (C) 1999-2006 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 (INCLUDED_PATCHMANIP_H) -#define INCLUDED_PATCHMANIP_H - -#include "string/stringfwd.h" - -void Patch_registerCommands(); -typedef struct _GtkToolbar GtkToolbar; -typedef struct _GtkMenu GtkMenu; -void Patch_constructToolbar(GtkToolbar* toolbar); -void Patch_constructMenu(GtkMenu* menu); - -namespace scene -{ - class Graph; -} - -void Scene_PatchSetShader_Selected(scene::Graph& graph, const char* name); -void Scene_PatchGetShader_Selected(scene::Graph& graph, CopiedString& name); -void Scene_PatchSelectByShader(scene::Graph& graph, const char* name); -void Scene_PatchFindReplaceShader(scene::Graph& graph, const char* find, const char* replace); -void Scene_PatchFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace); - -void Scene_PatchCapTexture_Selected(scene::Graph& graph); -void Scene_PatchNaturalTexture_Selected(scene::Graph& graph); -void Scene_PatchTileTexture_Selected(scene::Graph& graph, float s, float t); - -void PatchFilters_construct(); - -void PatchPreferences_construct(); - -void Patch_registerPreferencesPage(); - -class PatchCreator; -extern PatchCreator* g_patchCreator; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/patchmodule.cpp b/misc/mediasource/extra/netradiant-src/radiant/patchmodule.cpp deleted file mode 100644 index d9296243..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patchmodule.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "patchmodule.h" - -#include "qerplugin.h" -#include "ipatch.h" - -#include "patch.h" -#include "patchmanip.h" - -namespace -{ - std::size_t g_patchModuleCount = 0; -} - -void Patch_Construct(EPatchType type) -{ - if(++g_patchModuleCount != 1) - { - return; - } - - PatchFilters_construct(); - - PatchPreferences_construct(); - - Patch_registerPreferencesPage(); - - Patch::constructStatic(type); - PatchInstance::constructStatic(); - - if(type == ePatchTypeDoom3) - { - MAX_PATCH_WIDTH = MAX_PATCH_HEIGHT = 99; - } - else - { - MAX_PATCH_WIDTH = MAX_PATCH_HEIGHT = 31; // matching q3map2 - } -} - -void Patch_Destroy() -{ - if(--g_patchModuleCount != 0) - { - return; - } - - Patch::destroyStatic(); - PatchInstance::destroyStatic(); -} - -class CommonPatchCreator : public PatchCreator -{ -public: - void Patch_undoSave(scene::Node& patch) const - { - Node_getPatch(patch)->undoSave(); - } - void Patch_resize(scene::Node& patch, std::size_t width, std::size_t height) const - { - Node_getPatch(patch)->setDims(width, height); - } - PatchControlMatrix Patch_getControlPoints(scene::Node& node) const - { - Patch& patch = *Node_getPatch(node); - return PatchControlMatrix(patch.getHeight(), patch.getWidth(), patch.getControlPoints().data()); - } - void Patch_controlPointsChanged(scene::Node& patch) const - { - return Node_getPatch(patch)->controlPointsChanged(); - } - const char* Patch_getShader(scene::Node& patch) const - { - return Node_getPatch(patch)->GetShader(); - } - void Patch_setShader(scene::Node& patch, const char* shader) const - { - Node_getPatch(patch)->SetShader(shader); - } -}; - -class Quake3PatchCreator : public CommonPatchCreator -{ -public: - scene::Node& createPatch() - { - return (new PatchNodeQuake3())->node(); - } -}; - -Quake3PatchCreator g_Quake3PatchCreator; - -PatchCreator& GetQuake3PatchCreator() -{ - return g_Quake3PatchCreator; -} - -class Doom3PatchCreator : public CommonPatchCreator -{ -public: - scene::Node& createPatch() - { - return (new PatchNodeDoom3(true))->node(); - } -}; - -Doom3PatchCreator g_Doom3PatchCreator; - -PatchCreator& GetDoom3PatchCreator() -{ - return g_Doom3PatchCreator; -} - -class Doom3PatchDef2Creator : public CommonPatchCreator -{ -public: - scene::Node& createPatch() - { - return (new PatchNodeDoom3())->node(); - } -}; - -Doom3PatchDef2Creator g_Doom3PatchDef2Creator; - -PatchCreator& GetDoom3PatchDef2Creator() -{ - return g_Doom3PatchDef2Creator; -} - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class PatchDependencies : - public GlobalRadiantModuleRef, - public GlobalSceneGraphModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalSelectionModuleRef, - public GlobalOpenGLModuleRef, - public GlobalUndoModuleRef, - public GlobalFilterModuleRef -{ -}; - -class PatchQuake3API : public TypeSystemRef -{ - PatchCreator* m_patchquake3; -public: - typedef PatchCreator Type; - STRING_CONSTANT(Name, "quake3"); - - PatchQuake3API() - { - Patch_Construct(ePatchTypeQuake3); - - m_patchquake3 = &GetQuake3PatchCreator(); - g_patchCreator = m_patchquake3; - } - ~PatchQuake3API() - { - Patch_Destroy(); - } - PatchCreator* getTable() - { - return m_patchquake3; - } -}; - -typedef SingletonModule PatchQuake3Module; -typedef Static StaticPatchQuake3Module; -StaticRegisterModule staticRegisterPatchQuake3(StaticPatchQuake3Module::instance()); - - - -class PatchDoom3API : public TypeSystemRef -{ - PatchCreator* m_patchdoom3; -public: - typedef PatchCreator Type; - STRING_CONSTANT(Name, "doom3"); - - PatchDoom3API() - { - Patch_Construct(ePatchTypeDoom3); - - m_patchdoom3 = &GetDoom3PatchCreator(); - } - ~PatchDoom3API() - { - Patch_Destroy(); - } - PatchCreator* getTable() - { - return m_patchdoom3; - } -}; - -typedef SingletonModule PatchDoom3Module; -typedef Static StaticPatchDoom3Module; -StaticRegisterModule staticRegisterPatchDoom3(StaticPatchDoom3Module::instance()); - - -class PatchDef2Doom3API : public TypeSystemRef -{ - PatchCreator* m_patchdef2doom3; -public: - typedef PatchCreator Type; - STRING_CONSTANT(Name, "def2doom3"); - - PatchDef2Doom3API() - { - Patch_Construct(ePatchTypeDoom3); - - m_patchdef2doom3 = &GetDoom3PatchDef2Creator(); - g_patchCreator = m_patchdef2doom3; - } - ~PatchDef2Doom3API() - { - Patch_Destroy(); - } - PatchCreator* getTable() - { - return m_patchdef2doom3; - } -}; - -typedef SingletonModule PatchDef2Doom3Module; -typedef Static StaticPatchDef2Doom3Module; -StaticRegisterModule staticRegisterPatchDef2Doom3(StaticPatchDef2Doom3Module::instance()); - - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/patchmodule.h b/misc/mediasource/extra/netradiant-src/radiant/patchmodule.h deleted file mode 100644 index 074d5947..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/patchmodule.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_PATCHMODULE_H) -#define INCLUDED_PATCHMODULE_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/plugin.cpp b/misc/mediasource/extra/netradiant-src/radiant/plugin.cpp deleted file mode 100644 index fad47ea2..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/plugin.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "plugin.h" - -#include "debugging/debugging.h" - -#include "qerplugin.h" -#include "ifilesystem.h" -#include "ishaders.h" -#include "ientity.h" -#include "ieclass.h" -#include "irender.h" -#include "iscenegraph.h" -#include "iselection.h" -#include "ifilter.h" -#include "iscriplib.h" -#include "igl.h" -#include "iundo.h" -#include "itextures.h" -#include "ireference.h" -#include "ifiletypes.h" -#include "preferencesystem.h" -#include "ibrush.h" -#include "ipatch.h" -#include "iimage.h" -#include "itoolbar.h" -#include "iplugin.h" -#include "imap.h" -#include "namespace.h" - -#include "gtkutil/messagebox.h" -#include "gtkutil/filechooser.h" -#include "maplib.h" - -#include "error.h" -#include "map.h" -#include "qe3.h" -#include "entityinspector.h" -#include "entitylist.h" -#include "points.h" -#include "gtkmisc.h" -#include "texwindow.h" -#include "mainframe.h" -#include "build.h" -#include "mru.h" -#include "multimon.h" -#include "surfacedialog.h" -#include "groupdialog.h" -#include "patchdialog.h" -#include "camwindow.h" -#include "watchbsp.h" -#include "xywindow.h" -#include "entity.h" -#include "select.h" -#include "preferences.h" -#include "autosave.h" -#include "plugintoolbar.h" -#include "findtexturedialog.h" -#include "nullmodel.h" -#include "grid.h" - -#include "modulesystem/modulesmap.h" -#include "modulesystem/singletonmodule.h" - -#include "generic/callback.h" - -const char* GameDescription_getKeyValue(const char* key) -{ - return g_pGameDescription->getKeyValue(key); -} - -const char* GameDescription_getRequiredKeyValue(const char* key) -{ - return g_pGameDescription->getRequiredKeyValue(key); -} - -const char* getMapName() -{ - return Map_Name(g_map); -} - -scene::Node& getMapWorldEntity() -{ - return Map_FindOrInsertWorldspawn(g_map); -} - -VIEWTYPE XYWindow_getViewType() -{ - return g_pParentWnd->GetXYWnd()->GetViewType(); -} - -Vector3 XYWindow_windowToWorld(const WindowVector& position) -{ - Vector3 result(0, 0, 0); - g_pParentWnd->GetXYWnd()->XY_ToPoint(static_cast(position.x()), static_cast(position.y()), result); - return result; -} - -const char* TextureBrowser_getSelectedShader() -{ - return TextureBrowser_GetSelectedShader(GlobalTextureBrowser()); -} - -class RadiantCoreAPI -{ - _QERFuncTable_1 m_radiantcore; -public: - typedef _QERFuncTable_1 Type; - STRING_CONSTANT(Name, "*"); - - RadiantCoreAPI() - { - m_radiantcore.getEnginePath = &EnginePath_get; - m_radiantcore.getLocalRcPath = &LocalRcPath_get; - m_radiantcore.getAppPath = &AppPath_get; - m_radiantcore.getGameToolsPath = &GameToolsPath_get; - m_radiantcore.getSettingsPath = &SettingsPath_get; - m_radiantcore.getMapsPath = &getMapsPath; - - m_radiantcore.getGameName = &gamename_get; - m_radiantcore.getGameMode = &gamemode_get; - - m_radiantcore.getMapName = &getMapName; - m_radiantcore.getMapWorldEntity = getMapWorldEntity; - m_radiantcore.getGridSize = GetGridSize; - - m_radiantcore.getGameDescriptionKeyValue = &GameDescription_getKeyValue; - m_radiantcore.getRequiredGameDescriptionKeyValue = &GameDescription_getRequiredKeyValue; - - m_radiantcore.attachGameToolsPathObserver = Radiant_attachGameToolsPathObserver; - m_radiantcore.detachGameToolsPathObserver = Radiant_detachGameToolsPathObserver; - m_radiantcore.attachEnginePathObserver = Radiant_attachEnginePathObserver; - m_radiantcore.detachEnginePathObserver = Radiant_detachEnginePathObserver; - m_radiantcore.attachGameNameObserver = Radiant_attachGameNameObserver; - m_radiantcore.detachGameNameObserver = Radiant_detachGameNameObserver; - m_radiantcore.attachGameModeObserver = Radiant_attachGameModeObserver; - m_radiantcore.detachGameModeObserver = Radiant_detachGameModeObserver; - - m_radiantcore.XYWindowDestroyed_connect = XYWindowDestroyed_connect; - m_radiantcore.XYWindowDestroyed_disconnect = XYWindowDestroyed_disconnect; - m_radiantcore.XYWindowMouseDown_connect = XYWindowMouseDown_connect; - m_radiantcore.XYWindowMouseDown_disconnect = XYWindowMouseDown_disconnect; - m_radiantcore.XYWindow_getViewType = XYWindow_getViewType; - m_radiantcore.XYWindow_windowToWorld = XYWindow_windowToWorld; - m_radiantcore.TextureBrowser_getSelectedShader = TextureBrowser_getSelectedShader; - - m_radiantcore.m_pfnMessageBox = >k_MessageBox; - m_radiantcore.m_pfnFileDialog = &file_dialog; - m_radiantcore.m_pfnColorDialog = &color_dialog; - m_radiantcore.m_pfnDirDialog = &dir_dialog; - m_radiantcore.m_pfnNewImage = &new_plugin_image; - } - _QERFuncTable_1* getTable() - { - return &m_radiantcore; - } -}; - -typedef SingletonModule RadiantCoreModule; -typedef Static StaticRadiantCoreModule; -StaticRegisterModule staticRegisterRadiantCore(StaticRadiantCoreModule::instance()); - - -class RadiantDependencies : - public GlobalRadiantModuleRef, - public GlobalFileSystemModuleRef, - public GlobalEntityModuleRef, - public GlobalShadersModuleRef, - public GlobalBrushModuleRef, - public GlobalSceneGraphModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalFiletypesModuleRef, - public GlobalSelectionModuleRef, - public GlobalReferenceModuleRef, - public GlobalOpenGLModuleRef, - public GlobalEntityClassManagerModuleRef, - public GlobalUndoModuleRef, - public GlobalScripLibModuleRef, - public GlobalNamespaceModuleRef -{ - ImageModulesRef m_image_modules; - MapModulesRef m_map_modules; - ToolbarModulesRef m_toolbar_modules; - PluginModulesRef m_plugin_modules; - -public: - RadiantDependencies() : - GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities")), - GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")), - GlobalBrushModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("brushtypes")), - GlobalEntityClassManagerModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclass")), - m_image_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("texturetypes")), - m_map_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("maptypes")), - m_toolbar_modules("*"), - m_plugin_modules("*") - { - } - - ImageModules& getImageModules() - { - return m_image_modules.get(); - } - MapModules& getMapModules() - { - return m_map_modules.get(); - } - ToolbarModules& getToolbarModules() - { - return m_toolbar_modules.get(); - } - PluginModules& getPluginModules() - { - return m_plugin_modules.get(); - } -}; - -class Radiant : public TypeSystemRef -{ -public: - Radiant() - { - Preferences_Init(); - - GlobalFiletypes().addType("sound", "wav", filetype_t("PCM sound files", "*.wav")); - - Selection_construct(); - HomePaths_Construct(); - VFS_Construct(); - Grid_construct(); - MultiMon_Construct(); - MRU_Construct(); - Pointfile_Construct(); - GLWindow_Construct(); - BuildMenu_Construct(); - Map_Construct(); - EntityList_Construct(); - MainFrame_Construct(); - GroupDialog_Construct(); - SurfaceInspector_Construct(); - PatchInspector_Construct(); - CamWnd_Construct(); - XYWindow_Construct(); - BuildMonitor_Construct(); - TextureBrowser_Construct(); - Entity_Construct(); - Autosave_Construct(); - EntityInspector_construct(); - FindTextureDialog_Construct(); - NullModel_construct(); - MapRoot_construct(); - - EnginePath_verify(); - EnginePath_Realise(); - } - ~Radiant() - { - EnginePath_Unrealise(); - - MapRoot_destroy(); - NullModel_destroy(); - FindTextureDialog_Destroy(); - EntityInspector_destroy(); - Autosave_Destroy(); - Entity_Destroy(); - TextureBrowser_Destroy(); - BuildMonitor_Destroy(); - XYWindow_Destroy(); - CamWnd_Destroy(); - PatchInspector_Destroy(); - SurfaceInspector_Destroy(); - GroupDialog_Destroy(); - MainFrame_Destroy(); - EntityList_Destroy(); - Map_Destroy(); - BuildMenu_Destroy(); - GLWindow_Destroy(); - Pointfile_Destroy(); - MRU_Destroy(); - MultiMon_Destroy(); - Grid_destroy(); - VFS_Destroy(); - HomePaths_Destroy(); - Selection_destroy(); - } -}; - -namespace -{ - bool g_RadiantInitialised = false; - RadiantDependencies* g_RadiantDependencies; - Radiant* g_Radiant; -} - - - -bool Radiant_Construct(ModuleServer& server) -{ - GlobalModuleServer::instance().set(server); - StaticModuleRegistryList().instance().registerModules(); - - g_RadiantDependencies = new RadiantDependencies(); - - g_RadiantInitialised = !server.getError(); - - if(g_RadiantInitialised) - { - g_Radiant = new Radiant; - } - - return g_RadiantInitialised; -} -void Radiant_Destroy() -{ - if(g_RadiantInitialised) - { - delete g_Radiant; - } - - delete g_RadiantDependencies; -} - -ImageModules& Radiant_getImageModules() -{ - return g_RadiantDependencies->getImageModules(); -} -MapModules& Radiant_getMapModules() -{ - return g_RadiantDependencies->getMapModules(); -} -ToolbarModules& Radiant_getToolbarModules() -{ - return g_RadiantDependencies->getToolbarModules(); -} -PluginModules& Radiant_getPluginModules() -{ - return g_RadiantDependencies->getPluginModules(); -} - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/plugin.h b/misc/mediasource/extra/netradiant-src/radiant/plugin.h deleted file mode 100644 index e4d2493d..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/plugin.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_PLUGIN_H) -#define INCLUDED_PLUGIN_H - -class ModuleServer; -bool Radiant_Construct(ModuleServer& server); -void Radiant_Destroy(); - - -template -class Modules; - -struct _QERPlugImageTable; -typedef Modules<_QERPlugImageTable> ImageModules; -ImageModules& Radiant_getImageModules(); -class MapFormat; -typedef Modules MapModules; -MapModules& Radiant_getMapModules(); -struct _QERPlugToolbarTable; -typedef Modules<_QERPlugToolbarTable> ToolbarModules; -ToolbarModules& Radiant_getToolbarModules(); -struct _QERPluginTable; -typedef Modules<_QERPluginTable> PluginModules; -PluginModules& Radiant_getPluginModules(); - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/pluginapi.cpp b/misc/mediasource/extra/netradiant-src/radiant/pluginapi.cpp deleted file mode 100644 index be91b9a6..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/pluginapi.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "pluginapi.h" - -#include "modulesystem.h" -#include "qerplugin.h" - -#include "generic/callback.h" -#include "math/vector.h" - -#include "gtkmisc.h" - -#include "camwindow.h" - -#include "mainframe.h" - - -// camera API -void QERApp_GetCamera( Vector3& origin, Vector3& angles ) -{ - CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); - origin = Camera_getOrigin(camwnd); - angles = Camera_getAngles(camwnd); -} - -void QERApp_SetCamera( const Vector3& origin, const Vector3& angles ) -{ - CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); - Camera_setOrigin(camwnd, origin); - Camera_setAngles(camwnd, angles); -} - -void QERApp_GetCamWindowExtents( int *x, int *y, int *width, int *height ) -{ -#if 0 - CamWnd* camwnd = g_pParentWnd->GetCamWnd(); - - gtk_window_get_position(GTK_WINDOW(camwnd->m_window), x, y); - - *width = camwnd->Camera()->width; - *height = camwnd->Camera()->height; -#endif -} - -#include "icamera.h" - -class CameraAPI -{ - _QERCameraTable m_camera; -public: - typedef _QERCameraTable Type; - STRING_CONSTANT(Name, "*"); - - CameraAPI() - { - m_camera.m_pfnGetCamera = &QERApp_GetCamera; - m_camera.m_pfnSetCamera = &QERApp_SetCamera; - m_camera.m_pfnGetCamWindowExtents = &QERApp_GetCamWindowExtents; - } - _QERCameraTable* getTable() - { - return &m_camera; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule CameraModule; -typedef Static StaticCameraModule; -StaticRegisterModule staticRegisterCamera(StaticCameraModule::instance()); - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/pluginapi.h b/misc/mediasource/extra/netradiant-src/radiant/pluginapi.h deleted file mode 100644 index 267b0d7a..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/pluginapi.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_PLUGINAPI_H) -#define INCLUDED_PLUGINAPI_H - -template class BasicVector3; -typedef BasicVector3 Vector3; - -// camera API -void QERApp_GetCamera( Vector3& origin, Vector3& angles ); -void QERApp_SetCamera( const Vector3& origin, const Vector3& angles ); -void QERApp_GetCamWindowExtents( int *x, int *y, int *width, int *height ); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/pluginmanager.cpp b/misc/mediasource/extra/netradiant-src/radiant/pluginmanager.cpp deleted file mode 100644 index 35933014..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/pluginmanager.cpp +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// PlugInManager.cpp: implementation of the CPlugInManager class. -// -////////////////////////////////////////////////////////////////////// - -#include "pluginmanager.h" - -#include "modulesystem.h" -#include "qerplugin.h" -#include "iplugin.h" - -#include "math/vector.h" -#include "string/string.h" - -#include "error.h" -#include "select.h" -#include "plugin.h" - -#include "modulesystem.h" - -#include - -/* plugin manager --------------------------------------- */ -class CPluginSlot : public IPlugIn -{ - CopiedString m_menu_name; - const _QERPluginTable *mpTable; - std::list m_CommandStrings; - std::list m_CommandTitleStrings; - std::list m_CommandIDs; - -public: - /*! - build directly from a SYN_PROVIDE interface - */ - CPluginSlot(GtkWidget* main_window, const char* name, const _QERPluginTable& table); - /*! - dispatching a command by name to the plugin - */ - void Dispatch(const char *p); - - // IPlugIn ------------------------------------------------------------ - const char* getMenuName(); - std::size_t getCommandCount(); - const char* getCommand(std::size_t n); - const char* getCommandTitle(std::size_t n); - void addMenuID(std::size_t n); - bool ownsCommandID(std::size_t n); - -}; - -CPluginSlot::CPluginSlot(GtkWidget* main_window, const char* name, const _QERPluginTable& table) -{ - mpTable = &table; - m_menu_name = name; - - const char* commands = mpTable->m_pfnQERPlug_GetCommandList(); - const char* titles = mpTable->m_pfnQERPlug_GetCommandTitleList(); - - StringTokeniser commandTokeniser(commands, ",;"); - StringTokeniser titleTokeniser(titles, ",;"); - - const char* cmdToken = commandTokeniser.getToken(); - const char *titleToken = titleTokeniser.getToken(); - while (!string_empty(cmdToken)) - { - if(string_empty(titleToken)) - { - m_CommandStrings.push_back(cmdToken); - m_CommandTitleStrings.push_back(cmdToken); - cmdToken = commandTokeniser.getToken(); - titleToken = ""; - } - else - { - m_CommandStrings.push_back(cmdToken); - m_CommandTitleStrings.push_back(titleToken); - cmdToken = commandTokeniser.getToken(); - titleToken = titleTokeniser.getToken(); - } - } - mpTable->m_pfnQERPlug_Init(0, (void*)main_window); -} - -const char* CPluginSlot::getMenuName() -{ - return m_menu_name.c_str(); -} - -std::size_t CPluginSlot::getCommandCount() -{ - return m_CommandStrings.size(); -} - -const char* CPluginSlot::getCommand(std::size_t n) -{ - std::list::iterator i = m_CommandStrings.begin(); - while(n-- != 0) - ++i; - return (*i).c_str(); -} - -const char* CPluginSlot::getCommandTitle(std::size_t n) -{ - std::list::iterator i = m_CommandTitleStrings.begin(); - while(n-- != 0) - ++i; - return (*i).c_str(); -} - -void CPluginSlot::addMenuID(std::size_t n) -{ - m_CommandIDs.push_back(n); -} - -bool CPluginSlot::ownsCommandID(std::size_t n) -{ - for(std::list::iterator i = m_CommandIDs.begin(); i != m_CommandIDs.end(); ++i) - { - if (*i == n) - return true; - } - return false; -} - -void CPluginSlot::Dispatch(const char *p) -{ - Vector3 vMin, vMax; - Select_GetBounds (vMin, vMax); - mpTable->m_pfnQERPlug_Dispatch(p, reinterpret_cast(&vMin), reinterpret_cast(&vMax), true);//QE_SingleBrush(true)); -} - - -class CPluginSlots -{ - std::list mSlots; -public: - virtual ~CPluginSlots(); - - void AddPluginSlot(GtkWidget* main_window, const char* name, const _QERPluginTable& table) - { - mSlots.push_back(new CPluginSlot(main_window, name, table)); - } - - void PopulateMenu(PluginsVisitor& menu); - bool Dispatch(std::size_t n, const char* p); -}; - -CPluginSlots::~CPluginSlots() -{ - std::list::iterator iSlot; - for(iSlot=mSlots.begin(); iSlot!=mSlots.end(); ++iSlot) - { - delete *iSlot; - *iSlot = 0; - } -} - -void CPluginSlots::PopulateMenu(PluginsVisitor& menu) -{ - std::list::iterator iPlug; - for(iPlug=mSlots.begin(); iPlug != mSlots.end(); ++iPlug) - { - menu.visit(*(*iPlug)); - } -} - -bool CPluginSlots::Dispatch(std::size_t n, const char* p) -{ - std::list::iterator iPlug; - for(iPlug=mSlots.begin(); iPlug!=mSlots.end(); ++iPlug) - { - CPluginSlot *pPlug = *iPlug; - if (pPlug->ownsCommandID(n)) - { - pPlug->Dispatch(p); - return true; - } - } - return false; -} - -CPluginSlots g_plugin_slots; - - -void FillPluginSlots(CPluginSlots& slots, GtkWidget* main_window) -{ - class AddPluginVisitor : public PluginModules::Visitor - { - CPluginSlots& m_slots; - GtkWidget* m_main_window; - public: - AddPluginVisitor(CPluginSlots& slots, GtkWidget* main_window) - : m_slots(slots), m_main_window(main_window) - { - } - void visit(const char* name, const _QERPluginTable& table) const - { - m_slots.AddPluginSlot(m_main_window, name, table); - } - } visitor(slots, main_window); - - Radiant_getPluginModules().foreachModule(visitor); -} - - -#include "pluginmanager.h" - -CPlugInManager g_PlugInMgr; - -CPlugInManager& GetPlugInMgr() -{ - return g_PlugInMgr; -} - -void CPlugInManager::Dispatch(std::size_t n, const char * p) -{ - g_plugin_slots.Dispatch(n, p); -} - -void CPlugInManager::Init(GtkWidget* main_window) -{ - FillPluginSlots(g_plugin_slots, main_window); -} - -void CPlugInManager::constructMenu(PluginsVisitor& menu) -{ - g_plugin_slots.PopulateMenu(menu); -} - -void CPlugInManager::Shutdown() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/pluginmanager.h b/misc/mediasource/extra/netradiant-src/radiant/pluginmanager.h deleted file mode 100644 index cf148bb5..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/pluginmanager.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_PLUGINMANAGER_H) -#define INCLUDED_PLUGINMANAGER_H - -#include - -typedef struct _GtkWidget GtkWidget; - -/*! -\class IPlugin -pure virtual interface for a plugin -temporary solution for migration from old plugin tech to synapse plugins -*/ -class IPlugIn -{ -public: - IPlugIn() { } - virtual ~IPlugIn() { } - - virtual const char* getMenuName() = 0; - virtual std::size_t getCommandCount() = 0; - virtual const char* getCommand(std::size_t) = 0; - virtual const char* getCommandTitle(std::size_t) = 0; - virtual void addMenuID(std::size_t) = 0; - virtual bool ownsCommandID(std::size_t n) = 0; -}; - -class PluginsVisitor -{ -public: - virtual void visit(IPlugIn& plugin) = 0; -}; - -class CPlugInManager -{ -public: - void Dispatch(std::size_t n, const char *p); - void Init(GtkWidget* main_window); - void constructMenu(PluginsVisitor& menu); - void Shutdown(); -}; - -CPlugInManager& GetPlugInMgr(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/pluginmenu.cpp b/misc/mediasource/extra/netradiant-src/radiant/pluginmenu.cpp deleted file mode 100644 index 0fe758ed..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/pluginmenu.cpp +++ /dev/null @@ -1,196 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "pluginmenu.h" - -#include "stream/textstream.h" - -#include -#include - -#include "gtkutil/pointer.h" -#include "gtkutil/menu.h" - -#include "pluginmanager.h" -#include "mainframe.h" -#include "preferences.h" - - -int m_nNextPlugInID = 0; - -void plugin_activated(GtkWidget* widget, gpointer data) -{ - const char* str = (const char*)g_object_get_data(G_OBJECT(widget),"command"); - GetPlugInMgr().Dispatch(gpointer_to_int(data), str); -} - -#include -typedef std::stack WidgetStack; - -void PlugInMenu_Add(GtkMenu* plugin_menu, IPlugIn* pPlugIn) -{ - GtkWidget *menu, *item, *parent, *subMenu; - const char *menuText, *menuCommand; - WidgetStack menuStack; - - parent = gtk_menu_item_new_with_label (pPlugIn->getMenuName()); - gtk_widget_show (parent); - gtk_container_add (GTK_CONTAINER (plugin_menu), parent); - - std::size_t nCount = pPlugIn->getCommandCount(); - if (nCount > 0) - { - menu = gtk_menu_new(); - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (GTK_MENU(menu)); - while (nCount > 0) - { - menuText = pPlugIn->getCommandTitle(--nCount); - menuCommand = pPlugIn->getCommand(nCount); - - if (menuText != 0 && strlen(menuText) > 0) - { - if (!strcmp(menuText, "-")) - { - item = gtk_menu_item_new(); - gtk_widget_set_sensitive (item, FALSE); - } - else if (!strcmp(menuText, ">")) - { - menuText = pPlugIn->getCommandTitle(--nCount); - menuCommand = pPlugIn->getCommand(nCount); - if (!strcmp(menuText, "-") || !strcmp(menuText, ">") || !strcmp(menuText, "<")) - { - globalErrorStream() << pPlugIn->getMenuName() << " Invalid title (" << menuText << ") for submenu.\n"; - continue; - } - - item = gtk_menu_item_new_with_label(menuText); - gtk_widget_show (item); - gtk_container_add (GTK_CONTAINER (menu), item); - - subMenu = gtk_menu_new(); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), subMenu); - menuStack.push(menu); - menu = subMenu; - continue; - } - else if (!strcmp(menuText, "<")) - { - if (!menuStack.empty()) - { - menu = menuStack.top(); - menuStack.pop(); - } - else - { - globalErrorStream() << pPlugIn->getMenuName() << ": Attempt to end non-existent submenu ignored.\n"; - } - continue; - } - else - { - item = gtk_menu_item_new_with_label (menuText); - g_object_set_data(G_OBJECT(item),"command", const_cast(static_cast(menuCommand))); - g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(plugin_activated), gint_to_pointer(m_nNextPlugInID)); - } - gtk_widget_show (item); - gtk_container_add (GTK_CONTAINER (menu), item); - pPlugIn->addMenuID(m_nNextPlugInID++); - } - } - if (!menuStack.empty()) - { - std::size_t size = menuStack.size(); - if (size != 0) - { - globalErrorStream() << pPlugIn->getMenuName() << " mismatched > <. " << Unsigned(size) << " submenu(s) not closed.\n"; - } - for (std::size_t i = 0; i < (size -1); i++) - { - menuStack.pop(); - } - menu = menuStack.top(); - menuStack.pop(); - } - gtk_menu_item_set_submenu (GTK_MENU_ITEM (parent), menu); - } -} - -GtkMenu* g_plugins_menu = 0; -GtkMenuItem* g_plugins_menu_separator = 0; - -void PluginsMenu_populate() -{ - class PluginsMenuConstructor : public PluginsVisitor - { - GtkMenu* m_menu; - public: - PluginsMenuConstructor(GtkMenu* menu) : m_menu(menu) - { - } - void visit(IPlugIn& plugin) - { - PlugInMenu_Add(m_menu, &plugin); - } - }; - - PluginsMenuConstructor constructor(g_plugins_menu); - GetPlugInMgr().constructMenu(constructor); -} - -void PluginsMenu_clear() -{ - m_nNextPlugInID = 0; - - GList* lst = g_list_find (gtk_container_children(GTK_CONTAINER(g_plugins_menu)), GTK_WIDGET(g_plugins_menu_separator)); - while (lst->next) - { - gtk_container_remove (GTK_CONTAINER(g_plugins_menu), GTK_WIDGET (lst->next->data)); - lst = g_list_find (gtk_container_children(GTK_CONTAINER(g_plugins_menu)), GTK_WIDGET(g_plugins_menu_separator)); - } -} - -GtkMenuItem* create_plugins_menu() -{ - // Plugins menu - GtkMenuItem* plugins_menu_item = new_sub_menu_item_with_mnemonic("_Plugins"); - GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(plugins_menu_item)); - if (g_Layout_enableDetachableMenus.m_value) - { - menu_tearoff(menu); - } - - g_plugins_menu = menu; - - //TODO: some modules/plugins do not yet support refresh -#if 0 - create_menu_item_with_mnemonic(menu, "Refresh", FreeCaller()); - - // NOTE: the seperator is used when doing a refresh of the list, everything past the seperator is removed - g_plugins_menu_separator = menu_separator(menu); -#endif - - PluginsMenu_populate(); - - return plugins_menu_item; -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/pluginmenu.h b/misc/mediasource/extra/netradiant-src/radiant/pluginmenu.h deleted file mode 100644 index f843bcb4..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/pluginmenu.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_PLUGINMENU_H) -#define INCLUDED_PLUGINMENU_H - -typedef struct _GtkMenuItem GtkMenuItem; -GtkMenuItem* create_plugins_menu(); - -typedef struct _GtkMenu GtkMenu; -typedef struct _GtkMenuItem GtkMenuItem; -void PluginsMenu_populate(); -void PluginsMenu_clear(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/plugintoolbar.cpp b/misc/mediasource/extra/netradiant-src/radiant/plugintoolbar.cpp deleted file mode 100644 index 4612fbd4..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/plugintoolbar.cpp +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "plugintoolbar.h" - - -#include "itoolbar.h" -#include "modulesystem.h" - -#include - -#include "stream/stringstream.h" -#include "gtkutil/image.h" -#include "gtkutil/container.h" - -#include "mainframe.h" -#include "plugin.h" - -GtkImage* new_plugin_image(const char* filename) -{ - { - StringOutputStream fullpath(256); - fullpath << GameToolsPath_get() << g_pluginsDir << "bitmaps/" << filename; - GtkImage* image = image_new_from_file_with_mask(fullpath.c_str()); - if(image != 0) - { - return image; - } - } - - { - StringOutputStream fullpath(256); - fullpath << AppPath_get() << g_pluginsDir << "bitmaps/" << filename; - GtkImage* image = image_new_from_file_with_mask(fullpath.c_str()); - if(image != 0) - { - return image; - } - } - - { - StringOutputStream fullpath(256); - fullpath << AppPath_get() << g_modulesDir << "bitmaps/" << filename; - GtkImage* image = image_new_from_file_with_mask(fullpath.c_str()); - if(image != 0) - { - return image; - } - } - - return image_new_missing(); -} - -inline GtkToolbarChildType gtktoolbarchildtype_for_toolbarbuttontype(IToolbarButton::EType type) -{ - switch(type) - { - case IToolbarButton::eSpace: - return GTK_TOOLBAR_CHILD_SPACE; - case IToolbarButton::eButton: - return GTK_TOOLBAR_CHILD_BUTTON; - case IToolbarButton::eToggleButton: - return GTK_TOOLBAR_CHILD_TOGGLEBUTTON; - case IToolbarButton::eRadioButton: - return GTK_TOOLBAR_CHILD_RADIOBUTTON; - } - ERROR_MESSAGE("invalid toolbar button type"); - return (GtkToolbarChildType)0; -} - -void toolbar_insert(GtkToolbar *toolbar, const char* icon, const char* text, const char* tooltip, IToolbarButton::EType type, GtkSignalFunc handler, gpointer data) -{ - gtk_toolbar_append_element(toolbar, gtktoolbarchildtype_for_toolbarbuttontype(type), 0, text, tooltip, "", GTK_WIDGET(new_plugin_image(icon)), handler, data); -} - -void ActivateToolbarButton(GtkWidget *widget, gpointer data) -{ - const_cast(reinterpret_cast(data))->activate(); -} - -void PlugInToolbar_AddButton(GtkToolbar* toolbar, const IToolbarButton* button) -{ - toolbar_insert(toolbar, button->getImage(), button->getText(), button->getTooltip(), button->getType(), GTK_SIGNAL_FUNC(ActivateToolbarButton), reinterpret_cast(const_cast(button))); -} - -GtkToolbar* g_plugin_toolbar = 0; - -void PluginToolbar_populate() -{ - class AddToolbarItemVisitor : public ToolbarModules::Visitor - { - GtkToolbar* m_toolbar; - public: - AddToolbarItemVisitor(GtkToolbar* toolbar) - : m_toolbar(toolbar) - { - } - void visit(const char* name, const _QERPlugToolbarTable& table) const - { - const std::size_t count = table.m_pfnToolbarButtonCount(); - for(std::size_t i=0;iGetCamWnd(); - Camera_setOrigin(camwnd, *i); - g_pParentWnd->GetXYWnd()->SetOrigin(*i); - { - Vector3 dir(vector3_normalised(vector3_subtracted(*(++i), Camera_getOrigin(camwnd)))); - Vector3 angles(Camera_getAngles(camwnd)); - angles[CAMERA_YAW] = static_cast(radians_to_degrees(atan2(dir[1], dir[0]))); - angles[CAMERA_PITCH] = static_cast(radians_to_degrees(asin(dir[2]))); - Camera_setAngles(camwnd, angles); - } -} - -// advance camera to previous point -void Pointfile_Prev (void) -{ - if(!s_pointfile.shown()) - return; - - if (s_check_point == s_pointfile.begin()) - { - globalOutputStream() << "Start of pointfile\n"; - return; - } - - CPointfile::const_iterator i = --s_check_point; - - CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); - Camera_setOrigin(camwnd, *i); - g_pParentWnd->GetXYWnd()->SetOrigin(*i); - { - Vector3 dir(vector3_normalised(vector3_subtracted(*(++i), Camera_getOrigin(camwnd)))); - Vector3 angles(Camera_getAngles(camwnd)); - angles[CAMERA_YAW] = static_cast(radians_to_degrees(atan2(dir[1], dir[0]))); - angles[CAMERA_PITCH] = static_cast(radians_to_degrees(asin(dir[2]))); - Camera_setAngles(camwnd, angles); - } -} - -int LoadFile (const char *filename, void **bufferptr) -{ - FILE *f; - long len; - - f = fopen (filename, "rb"); - if (f == 0) - return -1; - - fseek (f, 0, SEEK_END); - len = ftell (f); - rewind (f); - - *bufferptr = malloc (len+1); - if (*bufferptr == 0) - return -1; - - fread (*bufferptr, 1, len, f); - fclose (f); - - // we need to end the buffer with a 0 - ((char*) (*bufferptr))[len] = 0; - - return len; -} - -void Pointfile_Parse(CPointfile& pointfile) -{ - int size; - char *data; - char *text; - int line = 1; - - const char* mapname = Map_Name(g_map); - StringOutputStream name(256); - name << StringRange(mapname, path_get_filename_base_end(mapname)) << ".lin"; - - size = LoadFile (name.c_str(), (void**)&data); - if (size == -1) - { - globalErrorStream() << "Pointfile " << name.c_str() << " not found\n"; - return; - } - - // store a pointer - text = data; - - globalOutputStream() << "Reading pointfile " << name.c_str() << "\n"; - - pointfile.Init(); - - while (*data) - { - Vector3 v; - if (sscanf(data,"%f %f %f", &v[0], &v[1], &v[2]) != 3) - { - globalOutputStream() << "Corrupt point file, line " << line << "\n"; - break; - } - - while (*data && *data != '\n') - { - if (*(data-1) == ' ' && *(data) == '-' && *(data+1) == ' ') - break; - data++; - } - // deal with zhlt style point files. - if (*data == '-') - { - if (sscanf(data,"- %f %f %f", &v[0], &v[1], &v[2]) != 3) - { - globalOutputStream() << "Corrupt point file, line " << line << "\n"; - break; - } - - while (*data && *data != '\n') - data++; - - } - while (*data == '\n') - { - data++; // skip the \n - line++; - } - pointfile.PushPoint (v); - } - - g_free(text); -} - -void Pointfile_Clear() -{ - s_pointfile.show(false); -} - -void Pointfile_Toggle() -{ - s_pointfile.show(!s_pointfile.shown()); - - s_check_point = s_pointfile.begin(); -} - -void Pointfile_Construct() -{ - CPointfile::constructStatic(); - - GlobalShaderCache().attachRenderable(s_pointfile); - - GlobalCommands_insert("TogglePointfile", FreeCaller()); - GlobalCommands_insert("NextLeakSpot", FreeCaller(), Accelerator('K', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalCommands_insert("PrevLeakSpot", FreeCaller(), Accelerator('L', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); -} - -void Pointfile_Destroy() -{ - GlobalShaderCache().detachRenderable(s_pointfile); - - CPointfile::destroyStatic(); -} - - - -// CPointfile implementation for SAX-specific stuff ------------------------------- -void CPointfile::saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) -{ - if(string_equal(reinterpret_cast(name), "polyline")) - { - Init(); - // there's a prefs setting to avoid stopping on leak - if (!g_WatchBSP_LeakStop) - ctx->stop_depth = 0; - } -} - -void CPointfile::saxEndElement (message_info_t *ctx, const xmlChar *name) -{ - if(string_equal(reinterpret_cast(name), "polyline")) - { - // we are done - GenerateDisplayList(); - SceneChangeNotify(); - s_check_point = begin(); - } - else if(string_equal(reinterpret_cast(name), "point")) - { - Vector3 v; - sscanf(m_characters.c_str(), "%f %f %f\n", &v[0], &v[1], &v[2]); - PushPoint(v); - m_characters.clear(); - } -} - -// only "point" is expected to have characters around here -void CPointfile::saxCharacters (message_info_t *ctx, const xmlChar *ch, int len) -{ - m_characters.write(reinterpret_cast(ch), len); -} - -const char* CPointfile::getName() -{ - return "Map leaked"; -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/points.h b/misc/mediasource/extra/netradiant-src/radiant/points.h deleted file mode 100644 index 63665b78..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/points.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright (C) 1999-2006 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: -// header for Pointfile stuff (adding a C++ class to wrap the pointfile thing in the SAX parser) -// - -#if !defined(INCLUDED_POINTS_H) -#define INCLUDED_POINTS_H - -void Pointfile_Clear(); -void Pointfile_Delete (void); - -void Pointfile_Construct(); -void Pointfile_Destroy(); - -class ISAXHandler; -extern ISAXHandler& g_pointfile; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/preferencedictionary.cpp b/misc/mediasource/extra/netradiant-src/radiant/preferencedictionary.cpp deleted file mode 100644 index 598190eb..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/preferencedictionary.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "preferencedictionary.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/preferencedictionary.h b/misc/mediasource/extra/netradiant-src/radiant/preferencedictionary.h deleted file mode 100644 index 45757d01..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/preferencedictionary.h +++ /dev/null @@ -1,296 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_PREFERENCEDICTIONARY_H) -#define INCLUDED_PREFERENCEDICTIONARY_H - -#include "preferencesystem.h" -#include "xml/ixml.h" -#include "stream/stringstream.h" -#include "generic/callback.h" -#include "versionlib.h" -#include - -class PreferenceDictionary : public PreferenceSystem -{ - class PreferenceEntry - { - StringImportCallback m_importer; - StringExportCallback m_exporter; - public: - PreferenceEntry(const StringImportCallback& importer, const StringExportCallback& exporter) - : m_importer(importer), m_exporter(exporter) - { - } - void importString(const char* string) - { - m_importer(string); - } - void exportString(const StringImportCallback& importer) - { - m_exporter(importer); - } - }; - - typedef std::map PreferenceEntries; - PreferenceEntries m_preferences; - - typedef std::map PreferenceCache; - PreferenceCache m_cache; - -public: - typedef PreferenceEntries::iterator iterator; - - iterator begin() - { - return m_preferences.begin(); - } - iterator end() - { - return m_preferences.end(); - } - iterator find(const char* name) - { - return m_preferences.find(name); - } - - void registerPreference(const char* name, const StringImportCallback& importer, const StringExportCallback& exporter) - { - m_preferences.insert(PreferenceEntries::value_type(name, PreferenceEntry(importer, exporter))); - PreferenceCache::iterator i = m_cache.find(name); - if(i != m_cache.end()) - { - importer((*i).second.c_str()); - m_cache.erase(i); - } - } - - void importPref(const char* name, const char* value) - { - PreferenceEntries::iterator i = m_preferences.find(name); - if(i != m_preferences.end()) - { - (*i).second.importString(value); - } - else - { - m_cache.erase(name); - m_cache.insert(PreferenceCache::value_type(name, value)); - } - } -}; - -inline void XMLPreference_importString(XMLImporter& importer, const char* value) -{ - importer.write(value, string_length(value)); -} -typedef ReferenceCaller1 XMLPreferenceImportStringCaller; - -class XMLPreferenceDictionaryExporter : public XMLExporter -{ - class XMLQPrefElement : public XMLElement - { - const char* m_version; - public: - XMLQPrefElement(const char* version) : m_version(version) - { - } - const char* name() const - { - return "qpref"; - } - const char* attribute(const char* name) const - { - if(string_equal(name, "version")) - { - return m_version; - } - return ""; - } - void forEachAttribute(XMLAttrVisitor& visitor) const - { - visitor.visit("version", m_version); - } - }; - - class XMLPreferenceElement : public XMLElement - { - const char* m_name; - public: - XMLPreferenceElement(const char* name) - : m_name(name) - { - } - const char* name() const - { - return "epair"; - } - const char* attribute(const char* name) const - { - if(string_equal(name, "name")) - return m_name; - return ""; - } - void forEachAttribute(XMLAttrVisitor& visitor) const - { - visitor.visit("name", m_name); - } - }; - - typedef PreferenceDictionary PreferenceEntries; - PreferenceEntries& m_preferences; - const char* m_version; -public: - XMLPreferenceDictionaryExporter(PreferenceDictionary& preferences, const char* version) - : m_preferences(preferences), m_version(version) - { - } - - void exportXML(XMLImporter& importer) - { - importer.write("\n", 1); - - XMLQPrefElement qpref_element(m_version); - importer.pushElement(qpref_element); - importer.write("\n", 1); - - for(PreferenceEntries::iterator i = m_preferences.begin(); i != m_preferences.end(); ++i) - { - XMLPreferenceElement epair_element((*i).first.c_str()); - - importer.pushElement(epair_element); - - (*i).second.exportString(XMLPreferenceImportStringCaller(importer)); - - importer.popElement(epair_element.name()); - importer.write("\n", 1); - } - - importer.popElement(qpref_element.name()); - importer.write("\n", 1); - } -}; - -class XMLPreferenceDictionaryImporter : public XMLImporter -{ - struct xml_state_t - { - enum ETag - { - tag_qpref, - tag_qpref_ignore, - tag_epair, - tag_epair_ignore - }; - - xml_state_t(ETag tag) - : m_tag(tag) - { - } - - ETag m_tag; - CopiedString m_name; - StringOutputStream m_ostream; - }; - - typedef std::vector xml_stack_t; - xml_stack_t m_xml_stack; - - typedef PreferenceDictionary PreferenceEntries; - PreferenceEntries& m_preferences; - Version m_version; -public: - XMLPreferenceDictionaryImporter(PreferenceDictionary& preferences, const char* version) - : m_preferences(preferences), m_version(version_parse(version)) - { - } - - void pushElement(const XMLElement& element) - { - if(m_xml_stack.empty()) - { - if(string_equal(element.name(), "qpref")) - { - Version dataVersion(version_parse(element.attribute("version"))); - if(!version_compatible(m_version, dataVersion)) - { - globalOutputStream() << "qpref import: data version " << dataVersion << " is not compatible with code version " << m_version << "\n"; - m_xml_stack.push_back(xml_state_t::tag_qpref_ignore); - } - else - { - globalOutputStream() << "qpref import: data version " << dataVersion << " is compatible with code version " << m_version << "\n"; - m_xml_stack.push_back(xml_state_t::tag_qpref); - } - } - else - { - // not valid - } - } - else - { - switch(m_xml_stack.back().m_tag) - { - case xml_state_t::tag_qpref: - if(string_equal(element.name(), "epair")) - { - m_xml_stack.push_back(xml_state_t::tag_epair); - m_xml_stack.back().m_name = element.attribute("name"); - } - else - { - // not valid - } - break; - case xml_state_t::tag_qpref_ignore: - if(string_equal(element.name(), "epair")) - { - m_xml_stack.push_back(xml_state_t::tag_epair_ignore); - } - else - { - // not valid - } - break; - case xml_state_t::tag_epair: - case xml_state_t::tag_epair_ignore: - // not valid - break; - } - } - - } - void popElement(const char* name) - { - if(m_xml_stack.back().m_tag == xml_state_t::tag_epair) - { - m_preferences.importPref(m_xml_stack.back().m_name.c_str(), m_xml_stack.back().m_ostream.c_str()); - } - m_xml_stack.pop_back(); - } - std::size_t write(const char* buffer, std::size_t length) - { - return m_xml_stack.back().m_ostream.write(buffer, length); - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/preferences.cpp b/misc/mediasource/extra/netradiant-src/radiant/preferences.cpp deleted file mode 100644 index a691d812..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/preferences.cpp +++ /dev/null @@ -1,1084 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// User preferences -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "preferences.h" -#include "environment.h" - -#include "debugging/debugging.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "generic/callback.h" -#include "math/vector.h" -#include "string/string.h" -#include "stream/stringstream.h" -#include "os/file.h" -#include "os/path.h" -#include "os/dir.h" -#include "gtkutil/filechooser.h" -#include "gtkutil/messagebox.h" -#include "cmdlib.h" - -#include "error.h" -#include "console.h" -#include "xywindow.h" -#include "mainframe.h" -#include "qe3.h" -#include "gtkdlgs.h" - - - -void Global_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox("Console", "Enable Logging", g_Console_enableLogging); -} - -void Interface_constructPreferences(PreferencesPage& page) -{ -#ifdef WIN32 - page.appendCheckBox("", "Default Text Editor", g_TextEditor_useWin32Editor); -#else - { - GtkWidget* use_custom = page.appendCheckBox("Text Editor", "Custom", g_TextEditor_useCustomEditor); - GtkWidget* custom_editor = page.appendPathEntry("Text Editor Command", g_TextEditor_editorCommand, true); - Widget_connectToggleDependency(custom_editor, use_custom); - } -#endif -} - -void Mouse_constructPreferences(PreferencesPage& page) -{ - { - const char* buttons[] = { "2 button", "3 button", }; - page.appendRadio("Mouse Type", g_glwindow_globals.m_nMouseType, STRING_ARRAY_RANGE(buttons)); - } - page.appendCheckBox("Right Button", "Activates Context Menu", g_xywindow_globals.m_bRightClick); -} -void Mouse_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Mouse", "Mouse Preferences")); - Mouse_constructPreferences(page); -} -void Mouse_registerPreferencesPage() -{ - PreferencesDialog_addInterfacePage(FreeCaller1()); -} - - -/*! -========================================================= -Games selection dialog -========================================================= -*/ - -#include - -inline const char* xmlAttr_getName(xmlAttrPtr attr) -{ - return reinterpret_cast(attr->name); -} - -inline const char* xmlAttr_getValue(xmlAttrPtr attr) -{ - return reinterpret_cast(attr->children->content); -} - -CGameDescription::CGameDescription(xmlDocPtr pDoc, const CopiedString& gameFile) -{ - // read the user-friendly game name - xmlNodePtr pNode = pDoc->children; - - while (strcmp((const char*)pNode->name, "game") && pNode != 0) - { - pNode=pNode->next; - } - if (!pNode) - { - Error("Didn't find 'game' node in the game description file '%s'\n", pDoc->URL); - } - - for(xmlAttrPtr attr = pNode->properties; attr != 0; attr = attr->next) - { - m_gameDescription.insert(GameDescription::value_type(xmlAttr_getName(attr), xmlAttr_getValue(attr))); - } - - { - StringOutputStream path(256); - path << AppPath_get() << gameFile.c_str() << "/"; - mGameToolsPath = path.c_str(); - } - - ASSERT_MESSAGE(file_exists(mGameToolsPath.c_str()), "game directory not found: " << makeQuoted(mGameToolsPath.c_str())); - - mGameFile = gameFile; - - { - GameDescription::iterator i = m_gameDescription.find("type"); - if(i == m_gameDescription.end()) - { - globalErrorStream() << "Warning, 'type' attribute not found in '" << reinterpret_cast(pDoc->URL) << "'\n"; - // default - mGameType = "q3"; - } - else - { - mGameType = (*i).second.c_str(); - } - } -} - -void CGameDescription::Dump() -{ - globalOutputStream() << "game description file: " << makeQuoted(mGameFile.c_str()) << "\n"; - for(GameDescription::iterator i = m_gameDescription.begin(); i != m_gameDescription.end(); ++i) - { - globalOutputStream() << (*i).first.c_str() << " = " << makeQuoted((*i).second.c_str()) << "\n"; - } -} - -CGameDescription *g_pGameDescription; ///< shortcut to g_GamesDialog.m_pCurrentDescription - - -#include "warnings.h" -#include "stream/textfilestream.h" -#include "container/array.h" -#include "xml/ixml.h" -#include "xml/xmlparser.h" -#include "xml/xmlwriter.h" - -#include "preferencedictionary.h" -#include "stringio.h" - -const char* const PREFERENCES_VERSION = "1.0"; - -bool Preferences_Load(PreferenceDictionary& preferences, const char* filename, const char *cmdline_prefix) -{ - bool ret = false; - TextFileInputStream file(filename); - if(!file.failed()) - { - XMLStreamParser parser(file); - XMLPreferenceDictionaryImporter importer(preferences, PREFERENCES_VERSION); - parser.exportXML(importer); - ret = true; - } - - int l = strlen(cmdline_prefix); - for(int i = 1; i < g_argc - 1; ++i) - { - if(g_argv[i][0] == '-') - { - if(!strncmp(g_argv[i]+1, cmdline_prefix, l)) - if(g_argv[i][l+1] == '-') - preferences.importPref(g_argv[i]+l+2, g_argv[i+1]); - ++i; - } - } - - return ret; -} - -bool Preferences_Save(PreferenceDictionary& preferences, const char* filename) -{ - TextFileOutputStream file(filename); - if(!file.failed()) - { - XMLStreamWriter writer(file); - XMLPreferenceDictionaryExporter exporter(preferences, PREFERENCES_VERSION); - exporter.exportXML(writer); - return true; - } - return false; -} - -bool Preferences_Save_Safe(PreferenceDictionary& preferences, const char* filename) -{ - Array tmpName(filename, filename + strlen(filename) + 1 + 3); - *(tmpName.end() - 4) = 'T'; - *(tmpName.end() - 3) = 'M'; - *(tmpName.end() - 2) = 'P'; - *(tmpName.end() - 1) = '\0'; - - return Preferences_Save(preferences, tmpName.data()) - && (!file_exists(filename) || file_remove(filename)) - && file_move(tmpName.data(), filename); -} - - - -void LogConsole_importString(const char* string) -{ - g_Console_enableLogging = string_equal(string, "true"); - Sys_LogFile(g_Console_enableLogging); -} -typedef FreeCaller1 LogConsoleImportStringCaller; - - -void RegisterGlobalPreferences(PreferenceSystem& preferences) -{ - preferences.registerPreference("gamefile", CopiedStringImportStringCaller(g_GamesDialog.m_sGameFile), CopiedStringExportStringCaller(g_GamesDialog.m_sGameFile)); - preferences.registerPreference("gamePrompt", BoolImportStringCaller(g_GamesDialog.m_bGamePrompt), BoolExportStringCaller(g_GamesDialog.m_bGamePrompt)); - preferences.registerPreference("log console", LogConsoleImportStringCaller(), BoolExportStringCaller(g_Console_enableLogging)); -} - - -PreferenceDictionary g_global_preferences; - -void GlobalPreferences_Init() -{ - RegisterGlobalPreferences(g_global_preferences); -} - -void CGameDialog::LoadPrefs() -{ - // load global .pref file - StringOutputStream strGlobalPref(256); - strGlobalPref << g_Preferences.m_global_rc_path->str << "global.pref"; - - globalOutputStream() << "loading global preferences from " << makeQuoted(strGlobalPref.c_str()) << "\n"; - - if(!Preferences_Load(g_global_preferences, strGlobalPref.c_str(), "global")) - { - globalOutputStream() << "failed to load global preferences from " << strGlobalPref.c_str() << "\n"; - } -} - -void CGameDialog::SavePrefs() -{ - StringOutputStream strGlobalPref(256); - strGlobalPref << g_Preferences.m_global_rc_path->str << "global.pref"; - - globalOutputStream() << "saving global preferences to " << strGlobalPref.c_str() << "\n"; - - if(!Preferences_Save_Safe(g_global_preferences, strGlobalPref.c_str())) - { - globalOutputStream() << "failed to save global preferences to " << strGlobalPref.c_str() << "\n"; - } -} - -void CGameDialog::DoGameDialog() -{ - // show the UI - DoModal(); - - // we save the prefs file - SavePrefs(); -} - -void CGameDialog::GameFileImport(int value) -{ - m_nComboSelect = value; - // use value to set m_sGameFile - std::list::iterator iGame = mGames.begin(); - int i; - for(i=0; imGameFile; -} - -void CGameDialog::GameFileExport(const IntImportCallback& importCallback) const -{ - // use m_sGameFile to set value - std::list::const_iterator iGame; - int i = 0; - for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) - { - if ((*iGame)->mGameFile == m_sGameFile) - { - m_nComboSelect = i; - break; - } - i++; - } - importCallback(m_nComboSelect); -} - -void CGameDialog_GameFileImport(CGameDialog& self, int value) -{ - self.GameFileImport(value); -} - -void CGameDialog_GameFileExport(CGameDialog& self, const IntImportCallback& importCallback) -{ - self.GameFileExport(importCallback); -} - -void CGameDialog::CreateGlobalFrame(PreferencesPage& page) -{ - std::vector games; - games.reserve(mGames.size()); - for(std::list::iterator i = mGames.begin(); i != mGames.end(); ++i) - { - games.push_back((*i)->getRequiredKeyValue("name")); - } - page.appendCombo( - "Select the game", - StringArrayRange(&(*games.begin()), &(*games.end())), - ReferenceCaller1(*this), - ReferenceCaller1(*this) - ); - page.appendCheckBox("Startup", "Show Global Preferences", m_bGamePrompt); -} - -GtkWindow* CGameDialog::BuildDialog() -{ - GtkFrame* frame = create_dialog_frame("Game settings", GTK_SHADOW_ETCHED_IN); - - GtkVBox* vbox2 = create_dialog_vbox(0, 4); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox2)); - - { - PreferencesPage preferencesPage(*this, GTK_WIDGET(vbox2)); - Global_constructPreferences(preferencesPage); - CreateGlobalFrame(preferencesPage); - } - - return create_simple_modal_dialog_window("Global Preferences", m_modal, GTK_WIDGET(frame)); -} - -class LoadGameFile -{ - std::list& mGames; - const char* mPath; -public: - LoadGameFile(std::list& games, const char* path) : mGames(games), mPath(path) - { - } - void operator()(const char* name) const - { - if(!extension_equal(path_get_extension(name), "game")) - { - return; - } - StringOutputStream strPath(256); - strPath << mPath << name; - globalOutputStream() << strPath.c_str() << '\n'; - - xmlDocPtr pDoc = xmlParseFile(strPath.c_str()); - if(pDoc) - { - mGames.push_front(new CGameDescription(pDoc, name)); - xmlFreeDoc(pDoc); - } - else - { - globalErrorStream() << "XML parser failed on '" << strPath.c_str() << "'\n"; - } - } -}; - -void CGameDialog::ScanForGames() -{ - StringOutputStream strGamesPath(256); - strGamesPath << AppPath_get() << "games/"; - const char *path = strGamesPath.c_str(); - - globalOutputStream() << "Scanning for game description files: " << path << '\n'; - - /*! - \todo FIXME LINUX: - do we put game description files below AppPath, or in ~/.radiant - i.e. read only or read/write? - my guess .. readonly cause it's an install - we will probably want to add ~/.radiant//games/ scanning on top of that for developers - (if that's really needed) - */ - - Directory_forEach(path, LoadGameFile(mGames, path)); -} - -CGameDescription* CGameDialog::GameDescriptionForComboItem() -{ - std::list::iterator iGame; - int i=0; - for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame,i++) - { - if (i == m_nComboSelect) - { - return (*iGame); - } - } - return 0; // not found -} - -void CGameDialog::InitGlobalPrefPath() -{ - g_Preferences.m_global_rc_path = g_string_new(SettingsPath_get()); -} - -void CGameDialog::Reset() -{ - if (!g_Preferences.m_global_rc_path) - InitGlobalPrefPath(); - StringOutputStream strGlobalPref(256); - strGlobalPref << g_Preferences.m_global_rc_path->str << "global.pref"; - file_remove(strGlobalPref.c_str()); -} - -void CGameDialog::Init() -{ - InitGlobalPrefPath(); - LoadPrefs(); - ScanForGames(); - if (mGames.empty()) - { - Error("Didn't find any valid game file descriptions, aborting\n"); - } - else - { - std::list::iterator iGame, iPrevGame; - for(iGame=mGames.begin(), iPrevGame = mGames.end(); iGame!=mGames.end(); iPrevGame = iGame, ++iGame) - { - if(iPrevGame != mGames.end()) - if(strcmp((*iGame)->getRequiredKeyValue("name"), (*iPrevGame)->getRequiredKeyValue("name")) < 0) - { - CGameDescription *h = *iGame; - *iGame = *iPrevGame; - *iPrevGame = h; - } - } - } - - CGameDescription* currentGameDescription = 0; - - if (!m_bGamePrompt) - { - // search by .game name - std::list::iterator iGame; - for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) - { - if ((*iGame)->mGameFile == m_sGameFile) - { - currentGameDescription = (*iGame); - break; - } - } - } - if (m_bGamePrompt || !currentGameDescription) - { - Create(); - DoGameDialog(); - // use m_nComboSelect to identify the game to run as and set the globals - currentGameDescription = GameDescriptionForComboItem(); - ASSERT_NOTNULL(currentGameDescription); - } - g_pGameDescription = currentGameDescription; - - g_pGameDescription->Dump(); -} - -CGameDialog::~CGameDialog() -{ - // free all the game descriptions - std::list::iterator iGame; - for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) - { - delete (*iGame); - *iGame = 0; - } - if(GetWidget() != 0) - { - Destroy(); - } -} - -inline const char* GameDescription_getIdentifier(const CGameDescription& gameDescription) -{ - const char* identifier = gameDescription.getKeyValue("index"); - if(string_empty(identifier)) - { - identifier = "1"; - } - return identifier; -} - -void CGameDialog::AddPacksURL(StringOutputStream &URL) -{ - // add the URLs for the list of game packs installed - // FIXME: this is kinda hardcoded for now.. - std::list::iterator iGame; - for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) - { - URL << "&Games_dlup%5B%5D=" << GameDescription_getIdentifier(*(*iGame)); - } -} - -CGameDialog g_GamesDialog; - - -// ============================================================================= -// Widget callbacks for PrefsDlg - -static void OnButtonClean (GtkWidget *widget, gpointer data) -{ - // make sure this is what the user wants - if (gtk_MessageBox(GTK_WIDGET(g_Preferences.GetWidget()), "This will close Radiant and clean the corresponding registry entries.\n" - "Next time you start Radiant it will be good as new. Do you wish to continue?", - "Reset Registry", eMB_YESNO, eMB_ICONASTERISK) == eIDYES) - { - PrefsDlg *dlg = (PrefsDlg*)data; - dlg->EndModal (eIDCANCEL); - - g_preferences_globals.disable_ini = true; - Preferences_Reset(); - gtk_main_quit(); - } -} - -// ============================================================================= -// PrefsDlg class - -/* -======== - -very first prefs init deals with selecting the game and the game tools path -then we can load .ini stuff - -using prefs / ini settings: -those are per-game - -look in ~/.radiant//gamename -======== -*/ - -#define PREFS_LOCAL_FILENAME "local.pref" - -void PrefsDlg::Init() -{ - // m_global_rc_path has been set above - // m_rc_path is for game specific preferences - // takes the form: global-pref-path/gamename/prefs-file - - // this is common to win32 and Linux init now - m_rc_path = g_string_new (m_global_rc_path->str); - - // game sub-dir - g_string_append (m_rc_path, g_pGameDescription->mGameFile.c_str()); - g_string_append (m_rc_path, "/"); - Q_mkdir (m_rc_path->str); - - // then the ini file - m_inipath = g_string_new (m_rc_path->str); - g_string_append (m_inipath, PREFS_LOCAL_FILENAME); -} - -void notebook_set_page(GtkWidget* notebook, GtkWidget* page) -{ - int pagenum = gtk_notebook_page_num(GTK_NOTEBOOK(notebook), page); - if(gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook)) != pagenum) - { - gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), pagenum); - } -} - -void PrefsDlg::showPrefPage(GtkWidget* prefpage) -{ - notebook_set_page(m_notebook, prefpage); - return; -} - -static void treeSelection(GtkTreeSelection* selection, gpointer data) -{ - PrefsDlg *dlg = (PrefsDlg*)data; - - GtkTreeModel* model; - GtkTreeIter selected; - if(gtk_tree_selection_get_selected(selection, &model, &selected)) - { - GtkWidget* prefpage; - gtk_tree_model_get(model, &selected, 1, (gpointer*)&prefpage, -1); - dlg->showPrefPage(prefpage); - } -} - -typedef std::list PreferenceGroupCallbacks; - -inline void PreferenceGroupCallbacks_constructGroup(const PreferenceGroupCallbacks& callbacks, PreferenceGroup& group) -{ - for(PreferenceGroupCallbacks::const_iterator i = callbacks.begin(); i != callbacks.end(); ++i) - { - (*i)(group); - } -} - - -inline void PreferenceGroupCallbacks_pushBack(PreferenceGroupCallbacks& callbacks, const PreferenceGroupCallback& callback) -{ - callbacks.push_back(callback); -} - -typedef std::list PreferencesPageCallbacks; - -inline void PreferencesPageCallbacks_constructPage(const PreferencesPageCallbacks& callbacks, PreferencesPage& page) -{ - for(PreferencesPageCallbacks::const_iterator i = callbacks.begin(); i != callbacks.end(); ++i) - { - (*i)(page); - } -} - -inline void PreferencesPageCallbacks_pushBack(PreferencesPageCallbacks& callbacks, const PreferencesPageCallback& callback) -{ - callbacks.push_back(callback); -} - -PreferencesPageCallbacks g_interfacePreferences; -void PreferencesDialog_addInterfacePreferences(const PreferencesPageCallback& callback) -{ - PreferencesPageCallbacks_pushBack(g_interfacePreferences, callback); -} -PreferenceGroupCallbacks g_interfaceCallbacks; -void PreferencesDialog_addInterfacePage(const PreferenceGroupCallback& callback) -{ - PreferenceGroupCallbacks_pushBack(g_interfaceCallbacks, callback); -} - -PreferencesPageCallbacks g_displayPreferences; -void PreferencesDialog_addDisplayPreferences(const PreferencesPageCallback& callback) -{ - PreferencesPageCallbacks_pushBack(g_displayPreferences, callback); -} -PreferenceGroupCallbacks g_displayCallbacks; -void PreferencesDialog_addDisplayPage(const PreferenceGroupCallback& callback) -{ - PreferenceGroupCallbacks_pushBack(g_displayCallbacks, callback); -} - -PreferencesPageCallbacks g_settingsPreferences; -void PreferencesDialog_addSettingsPreferences(const PreferencesPageCallback& callback) -{ - PreferencesPageCallbacks_pushBack(g_settingsPreferences, callback); -} -PreferenceGroupCallbacks g_settingsCallbacks; -void PreferencesDialog_addSettingsPage(const PreferenceGroupCallback& callback) -{ - PreferenceGroupCallbacks_pushBack(g_settingsCallbacks, callback); -} - -void Widget_updateDependency(GtkWidget* self, GtkWidget* toggleButton) -{ - gtk_widget_set_sensitive(self, gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggleButton)) && GTK_WIDGET_IS_SENSITIVE(toggleButton)); -} - -void ToggleButton_toggled_Widget_updateDependency(GtkWidget *toggleButton, GtkWidget* self) -{ - Widget_updateDependency(self, toggleButton); -} - -void ToggleButton_state_changed_Widget_updateDependency(GtkWidget* toggleButton, GtkStateType state, GtkWidget* self) -{ - if(state == GTK_STATE_INSENSITIVE) - { - Widget_updateDependency(self, toggleButton); - } -} - -void Widget_connectToggleDependency(GtkWidget* self, GtkWidget* toggleButton) -{ - g_signal_connect(G_OBJECT(toggleButton), "state_changed", G_CALLBACK(ToggleButton_state_changed_Widget_updateDependency), self); - g_signal_connect(G_OBJECT(toggleButton), "toggled", G_CALLBACK(ToggleButton_toggled_Widget_updateDependency), self); - Widget_updateDependency(self, toggleButton); -} - - -inline GtkWidget* getVBox(GtkWidget* page) -{ - return gtk_bin_get_child(GTK_BIN(page)); -} - -GtkTreeIter PreferenceTree_appendPage(GtkTreeStore* store, GtkTreeIter* parent, const char* name, GtkWidget* page) -{ - GtkTreeIter group; - gtk_tree_store_append(store, &group, parent); - gtk_tree_store_set(store, &group, 0, name, 1, page, -1); - return group; -} - -GtkWidget* PreferencePages_addPage(GtkWidget* notebook, const char* name) -{ - GtkWidget* preflabel = gtk_label_new(name); - gtk_widget_show(preflabel); - - GtkWidget* pageframe = gtk_frame_new(name); - gtk_container_set_border_width(GTK_CONTAINER(pageframe), 4); - gtk_widget_show(pageframe); - - GtkWidget* vbox = gtk_vbox_new(FALSE, 4); - gtk_widget_show(vbox); - gtk_container_set_border_width(GTK_CONTAINER(vbox), 4); - gtk_container_add(GTK_CONTAINER(pageframe), vbox); - - // Add the page to the notebook - gtk_notebook_append_page(GTK_NOTEBOOK(notebook), pageframe, preflabel); - - return pageframe; -} - -class PreferenceTreeGroup : public PreferenceGroup -{ - Dialog& m_dialog; - GtkWidget* m_notebook; - GtkTreeStore* m_store; - GtkTreeIter m_group; -public: - PreferenceTreeGroup(Dialog& dialog, GtkWidget* notebook, GtkTreeStore* store, GtkTreeIter group) : - m_dialog(dialog), - m_notebook(notebook), - m_store(store), - m_group(group) - { - } - PreferencesPage createPage(const char* treeName, const char* frameName) - { - GtkWidget* page = PreferencePages_addPage(m_notebook, frameName); - PreferenceTree_appendPage(m_store, &m_group, treeName, page); - return PreferencesPage(m_dialog, getVBox(page)); - } -}; - -GtkWindow* PrefsDlg::BuildDialog() -{ - PreferencesDialog_addInterfacePreferences(FreeCaller1()); - Mouse_registerPreferencesPage(); - - GtkWindow* dialog = create_floating_window("NetRadiant Preferences", m_parent); - - { - GtkWidget* mainvbox = gtk_vbox_new(FALSE, 5); - gtk_container_add(GTK_CONTAINER(dialog), mainvbox); - gtk_container_set_border_width(GTK_CONTAINER(mainvbox), 5); - gtk_widget_show(mainvbox); - - { - GtkWidget* hbox = gtk_hbox_new(FALSE, 5); - gtk_widget_show(hbox); - gtk_box_pack_end(GTK_BOX(mainvbox), hbox, FALSE, TRUE, 0); - - { - GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &m_modal); - gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - { - GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &m_modal); - gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - { - GtkButton* button = create_dialog_button("Clean", G_CALLBACK(OnButtonClean), this); - gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - } - - { - GtkWidget* hbox = gtk_hbox_new(FALSE, 5); - gtk_box_pack_start(GTK_BOX(mainvbox), hbox, TRUE, TRUE, 0); - gtk_widget_show(hbox); - - { - GtkWidget* sc_win = gtk_scrolled_window_new(0, 0); - gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sc_win), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); - gtk_box_pack_start(GTK_BOX(hbox), sc_win, FALSE, FALSE, 0); - gtk_widget_show(sc_win); - gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sc_win), GTK_SHADOW_IN); - - // prefs pages notebook - m_notebook = gtk_notebook_new(); - // hide the notebook tabs since its not supposed to look like a notebook - gtk_notebook_set_show_tabs(GTK_NOTEBOOK(m_notebook), FALSE); - gtk_box_pack_start(GTK_BOX(hbox), m_notebook, TRUE, TRUE, 0); - gtk_widget_show(m_notebook); - - - { - GtkTreeStore* store = gtk_tree_store_new(2, G_TYPE_STRING, G_TYPE_POINTER); - - GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); - - { - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Preferences", renderer, "text", 0, NULL); - gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); - } - - { - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); - g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(treeSelection), this); - } - - gtk_widget_show(view); - - gtk_container_add(GTK_CONTAINER (sc_win), view); - - { - /********************************************************************/ - /* Add preference tree options */ - /********************************************************************/ - // Front page... - //GtkWidget* front = - PreferencePages_addPage(m_notebook, "Front Page"); - - { - GtkWidget* global = PreferencePages_addPage(m_notebook, "Global Preferences"); - { - PreferencesPage preferencesPage(*this, getVBox(global)); - Global_constructPreferences(preferencesPage); - } - GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Global", global); - { - GtkWidget* game = PreferencePages_addPage(m_notebook, "Game"); - PreferencesPage preferencesPage(*this, getVBox(game)); - g_GamesDialog.CreateGlobalFrame(preferencesPage); - - PreferenceTree_appendPage(store, &group, "Game", game); - } - } - - { - GtkWidget* interfacePage = PreferencePages_addPage(m_notebook, "Interface Preferences"); - { - PreferencesPage preferencesPage(*this, getVBox(interfacePage)); - PreferencesPageCallbacks_constructPage(g_interfacePreferences, preferencesPage); - } - - GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Interface", interfacePage); - PreferenceTreeGroup preferenceGroup(*this, m_notebook, store, group); - - PreferenceGroupCallbacks_constructGroup(g_interfaceCallbacks, preferenceGroup); - } - - { - GtkWidget* display = PreferencePages_addPage(m_notebook, "Display Preferences"); - { - PreferencesPage preferencesPage(*this, getVBox(display)); - PreferencesPageCallbacks_constructPage(g_displayPreferences, preferencesPage); - } - GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Display", display); - PreferenceTreeGroup preferenceGroup(*this, m_notebook, store, group); - - PreferenceGroupCallbacks_constructGroup(g_displayCallbacks, preferenceGroup); - } - - { - GtkWidget* settings = PreferencePages_addPage(m_notebook, "General Settings"); - { - PreferencesPage preferencesPage(*this, getVBox(settings)); - PreferencesPageCallbacks_constructPage(g_settingsPreferences, preferencesPage); - } - - GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Settings", settings); - PreferenceTreeGroup preferenceGroup(*this, m_notebook, store, group); - - PreferenceGroupCallbacks_constructGroup(g_settingsCallbacks, preferenceGroup); - } - } - - gtk_tree_view_expand_all(GTK_TREE_VIEW(view)); - - g_object_unref(G_OBJECT(store)); - } - } - } - } - - gtk_notebook_set_page(GTK_NOTEBOOK(m_notebook), 0); - - return dialog; -} - -preferences_globals_t g_preferences_globals; - -PrefsDlg g_Preferences; // global prefs instance - - -void PreferencesDialog_constructWindow(GtkWindow* main_window) -{ - g_Preferences.m_parent = main_window; - g_Preferences.Create(); -} -void PreferencesDialog_destroyWindow() -{ - g_Preferences.Destroy(); -} - - -PreferenceDictionary g_preferences; - -PreferenceSystem& GetPreferenceSystem() -{ - return g_preferences; -} - -class PreferenceSystemAPI -{ - PreferenceSystem* m_preferencesystem; -public: - typedef PreferenceSystem Type; - STRING_CONSTANT(Name, "*"); - - PreferenceSystemAPI() - { - m_preferencesystem = &GetPreferenceSystem(); - } - PreferenceSystem* getTable() - { - return m_preferencesystem; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule PreferenceSystemModule; -typedef Static StaticPreferenceSystemModule; -StaticRegisterModule staticRegisterPreferenceSystem(StaticPreferenceSystemModule::instance()); - -void Preferences_Load() -{ - g_GamesDialog.LoadPrefs(); - - globalOutputStream() << "loading local preferences from " << g_Preferences.m_inipath->str << "\n"; - - if(!Preferences_Load(g_preferences, g_Preferences.m_inipath->str, g_GamesDialog.m_sGameFile.c_str())) - { - globalOutputStream() << "failed to load local preferences from " << g_Preferences.m_inipath->str << "\n"; - } -} - -void Preferences_Save() -{ - if (g_preferences_globals.disable_ini) - return; - - g_GamesDialog.SavePrefs(); - - globalOutputStream() << "saving local preferences to " << g_Preferences.m_inipath->str << "\n"; - - if(!Preferences_Save_Safe(g_preferences, g_Preferences.m_inipath->str)) - { - globalOutputStream() << "failed to save local preferences to " << g_Preferences.m_inipath->str << "\n"; - } -} - -void Preferences_Reset() -{ - file_remove(g_Preferences.m_inipath->str); -} - - -void PrefsDlg::PostModal (EMessageBoxReturn code) -{ - if (code == eIDOK) - { - Preferences_Save(); - UpdateAllWindows(); - } -} - -std::vector g_restart_required; - -void PreferencesDialog_restartRequired(const char* staticName) -{ - g_restart_required.push_back(staticName); -} - -void PreferencesDialog_showDialog() -{ - if(ConfirmModified("Edit Preferences") && g_Preferences.DoModal() == eIDOK) - { - if(!g_restart_required.empty()) - { - StringOutputStream message(256); - message << "Preference changes require a restart:\n"; - for(std::vector::iterator i = g_restart_required.begin(); i != g_restart_required.end(); ++i) - { - message << (*i) << '\n'; - } - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), message.c_str()); - g_restart_required.clear(); - } - } -} - - - - - -void GameName_importString(const char* value) -{ - gamename_set(value); -} -typedef FreeCaller1 GameNameImportStringCaller; -void GameName_exportString(const StringImportCallback& importer) -{ - importer(gamename_get()); -} -typedef FreeCaller1 GameNameExportStringCaller; - -void GameMode_importString(const char* value) -{ - gamemode_set(value); -} -typedef FreeCaller1 GameModeImportStringCaller; -void GameMode_exportString(const StringImportCallback& importer) -{ - importer(gamemode_get()); -} -typedef FreeCaller1 GameModeExportStringCaller; - - -void RegisterPreferences(PreferenceSystem& preferences) -{ -#ifdef WIN32 - preferences.registerPreference("UseCustomShaderEditor", BoolImportStringCaller(g_TextEditor_useWin32Editor), BoolExportStringCaller(g_TextEditor_useWin32Editor)); -#else - preferences.registerPreference("UseCustomShaderEditor", BoolImportStringCaller(g_TextEditor_useCustomEditor), BoolExportStringCaller(g_TextEditor_useCustomEditor)); - preferences.registerPreference("CustomShaderEditorCommand", CopiedStringImportStringCaller(g_TextEditor_editorCommand), CopiedStringExportStringCaller(g_TextEditor_editorCommand)); -#endif - - preferences.registerPreference("GameName", GameNameImportStringCaller(), GameNameExportStringCaller()); - preferences.registerPreference("GameMode", GameModeImportStringCaller(), GameModeExportStringCaller()); -} - -void Preferences_Init() -{ - RegisterPreferences(GetPreferenceSystem()); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/preferences.h b/misc/mediasource/extra/netradiant-src/radiant/preferences.h deleted file mode 100644 index 6375bec1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/preferences.h +++ /dev/null @@ -1,434 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -The following source code is licensed by Id Software and subject to the terms of -its LIMITED USE SOFTWARE LICENSE AGREEMENT, a copy of which is included with -GtkRadiant. If you did not receive a LIMITED USE SOFTWARE LICENSE AGREEMENT, -please contact Id Software immediately at info@idsoftware.com. -*/ - -#if !defined(INCLUDED_PREFERENCES_H) -#define INCLUDED_PREFERENCES_H - -#include "libxml/parser.h" -#include "dialog.h" -#include -#include - -void Widget_connectToggleDependency(GtkWidget* self, GtkWidget* toggleButton); - -class PreferencesPage -{ - Dialog& m_dialog; - GtkWidget* m_vbox; -public: - PreferencesPage(Dialog& dialog, GtkWidget* vbox) : m_dialog(dialog), m_vbox(vbox) - { - } - GtkWidget* appendCheckBox(const char* name, const char* flag, bool& data) - { - return m_dialog.addCheckBox(m_vbox, name, flag, data); - } - GtkWidget* appendCheckBox(const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback) - { - return m_dialog.addCheckBox(m_vbox, name, flag, importCallback, exportCallback); - } - void appendCombo(const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) - { - m_dialog.addCombo(m_vbox, name, values, importCallback, exportCallback); - } - void appendCombo(const char* name, int& data, StringArrayRange values) - { - m_dialog.addCombo(m_vbox, name, data, values); - } - void appendSlider(const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment) - { - m_dialog.addSlider(m_vbox, name, data, draw_value, low, high, value, lower, upper, step_increment, page_increment); - } - void appendRadio(const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) - { - m_dialog.addRadio(m_vbox, name, names, importCallback, exportCallback); - } - void appendRadio(const char* name, int& data, StringArrayRange names) - { - m_dialog.addRadio(m_vbox, name, data, names); - } - void appendRadioIcons(const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) - { - m_dialog.addRadioIcons(m_vbox, name, icons, importCallback, exportCallback); - } - void appendRadioIcons(const char* name, int& data, StringArrayRange icons) - { - m_dialog.addRadioIcons(m_vbox, name, data, icons); - } - GtkWidget* appendEntry(const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) - { - return m_dialog.addIntEntry(m_vbox, name, importCallback, exportCallback); - } - GtkWidget* appendEntry(const char* name, int& data) - { - return m_dialog.addEntry(m_vbox, name, data); - } - GtkWidget* appendEntry(const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback) - { - return m_dialog.addSizeEntry(m_vbox, name, importCallback, exportCallback); - } - GtkWidget* appendEntry(const char* name, std::size_t& data) - { - return m_dialog.addEntry(m_vbox, name, data); - } - GtkWidget* appendEntry(const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback) - { - return m_dialog.addFloatEntry(m_vbox, name, importCallback, exportCallback); - } - GtkWidget* appendEntry(const char* name, float& data) - { - return m_dialog.addEntry(m_vbox, name, data); - } - GtkWidget* appendPathEntry(const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback) - { - return m_dialog.addPathEntry(m_vbox, name, browse_directory, importCallback, exportCallback); - } - GtkWidget* appendPathEntry(const char* name, CopiedString& data, bool directory) - { - return m_dialog.addPathEntry(m_vbox, name, data, directory); - } - GtkWidget* appendSpinner(const char* name, int& data, double value, double lower, double upper) - { - return m_dialog.addSpinner(m_vbox, name, data, value, lower, upper); - } - GtkWidget* appendSpinner(const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) - { - return m_dialog.addSpinner(m_vbox, name, value, lower, upper, importCallback, exportCallback); - } - GtkWidget* appendSpinner(const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback) - { - return m_dialog.addSpinner(m_vbox, name, value, lower, upper, importCallback, exportCallback); - } -}; - -typedef Callback1 PreferencesPageCallback; - -class PreferenceGroup -{ -public: - virtual PreferencesPage createPage(const char* treeName, const char* frameName) = 0; -}; - -typedef Callback1 PreferenceGroupCallback; - -void PreferencesDialog_addInterfacePreferences(const PreferencesPageCallback& callback); -void PreferencesDialog_addInterfacePage(const PreferenceGroupCallback& callback); -void PreferencesDialog_addDisplayPreferences(const PreferencesPageCallback& callback); -void PreferencesDialog_addDisplayPage(const PreferenceGroupCallback& callback); -void PreferencesDialog_addSettingsPreferences(const PreferencesPageCallback& callback); -void PreferencesDialog_addSettingsPage(const PreferenceGroupCallback& callback); - -void PreferencesDialog_restartRequired(const char* staticName); - -template -class LatchedValue -{ -public: - Value m_value; - Value m_latched; - const char* m_description; - - LatchedValue(Value value, const char* description) : m_latched(value), m_description(description) - { - } - void useLatched() - { - m_value = m_latched; - } - void import(Value value) - { - m_latched = value; - if(m_latched != m_value) - { - PreferencesDialog_restartRequired(m_description); - } - } -}; - -typedef LatchedValue LatchedBool; -typedef MemberCaller1 LatchedBoolImportCaller; - -typedef LatchedValue LatchedInt; -typedef MemberCaller1 LatchedIntImportCaller; - -/*! -holds information for a given game -I'm a bit unclear on that still -it holds game specific configuration stuff -such as base names, engine names, some game specific features to activate in the various modules -it is not strictly a prefs thing since the user is not supposed to edit that (unless he is hacking -support for a new game) - -what we do now is fully generate the information for this during the setup. We might want to -generate a piece that just says "the game pack is there", but put the rest of the config somwhere -else (i.e. not generated, copied over during setup .. for instance in the game tools directory) -*/ -class CGameDescription -{ -typedef std::map GameDescription; - -public: - CopiedString mGameFile; ///< the .game file that describes this game - GameDescription m_gameDescription; - - CopiedString mGameToolsPath; ///< the explicit path to the game-dependent modules - CopiedString mGameType; ///< the type of the engine - - const char* getKeyValue(const char* key) const - { - GameDescription::const_iterator i = m_gameDescription.find(key); - if(i != m_gameDescription.end()) - { - return (*i).second.c_str(); - } - return ""; - } - const char* getRequiredKeyValue(const char* key) const - { - GameDescription::const_iterator i = m_gameDescription.find(key); - if(i != m_gameDescription.end()) - { - return (*i).second.c_str(); - } - ERROR_MESSAGE("game attribute " << makeQuoted(key) << " not found in " << makeQuoted(mGameFile.c_str())); - return ""; - } - - CGameDescription(xmlDocPtr pDoc, const CopiedString &GameFile); - - void Dump(); -}; - -extern CGameDescription *g_pGameDescription; - -typedef struct _GtkWidget GtkWidget; -class PrefsDlg; - -class PreferencesPage; - -class StringOutputStream; - -/*! -standalone dialog for games selection, and more generally global settings -*/ -class CGameDialog : public Dialog -{ -protected: - - mutable int m_nComboSelect; ///< intermediate int value for combo in dialog box - -public: - - /*! - those settings are saved in the global prefs file - I'm too lazy to wrap behind protected access, not sure this needs to be public - NOTE: those are preference settings. if you change them it is likely that you would - have to restart the editor for them to take effect - */ - /*@{*/ - /*! - what game has been selected - this is the name of the .game file - */ - CopiedString m_sGameFile; - /*! - prompt which game to load on startup - */ - bool m_bGamePrompt; - /*! - log console to radiant.log - m_bForceLogConsole is an obscure forced latching situation - */ - bool m_bForceLogConsole; - /*@}*/ - - /*! - the list of game descriptions we scanned from the game/ dir - */ - std::list mGames; - - CGameDialog() : - m_sGameFile(""), - m_bGamePrompt(true), - m_bForceLogConsole(false) - { - } - virtual ~CGameDialog(); - - void AddPacksURL(StringOutputStream &s); - - /*! - intialize the game dialog, called at CPrefsDlg::Init - will scan for games, load prefs, and do game selection dialog if needed - */ - void Init(); - - /*! - reset the global settings by removing the file - */ - void Reset(); - - /*! - run the dialog UI for the list of games - */ - void DoGameDialog(); - - /*! - Dialog API - this is only called when the dialog is built at startup for main engine select - */ - GtkWindow* BuildDialog(); - - void GameFileImport(int value); - void GameFileExport(const IntImportCallback& importCallback) const; - - /*! - construction of the dialog frame - this is the part to be re-used in prefs dialog - for the standalone dialog, we include this in a modal box - for prefs, we hook the frame in the main notebook - build the frame on-demand (only once) - */ - void CreateGlobalFrame(PreferencesPage& page); - - /*! - global preferences subsystem - XML-based this time, hopefully this will generalize to other prefs - LoadPrefs has hardcoded defaults - NOTE: it may not be strictly 'CGameDialog' to put the global prefs here - could have named the class differently I guess - */ - /*@{*/ - void LoadPrefs(); ///< load from file into variables - void SavePrefs(); ///< save pref variables to file - /*@}*/ - -private: - /*! - scan for .game files, load them - */ - void ScanForGames(); - - /*! - inits g_Preferences.m_global_rc_path - */ - void InitGlobalPrefPath(); - - /*! - uses m_nComboItem to find the right mGames - */ - CGameDescription *GameDescriptionForComboItem(); -}; - -/*! -this holds global level preferences -*/ -extern CGameDialog g_GamesDialog; - - -class texdef_t; - -class PrefsDlg : public Dialog -{ -public: -protected: - std::list mGames; - -public: - - GtkWidget *m_notebook; - - virtual ~PrefsDlg() - { - g_string_free (m_rc_path, true ); - g_string_free (m_inipath, true ); - } - - /*! - path for global settings - win32: AppPath - linux: ~/.radiant/[version]/ - */ - GString *m_global_rc_path; - - /*! - path to per-game settings - used for various game dependant storage - win32: GameToolsPath - linux: ~/.radiant/[version]/[gamename]/ - */ - GString *m_rc_path; - - /*! - holds per-game settings - m_rc_path+"local.pref" - \todo FIXME at some point this should become XML property bag code too - */ - GString *m_inipath; - - // initialize the above paths - void Init(); - - /*! Utility function for swapping notebook pages for tree list selections */ - void showPrefPage(GtkWidget* prefpage); - -protected: - - /*! Dialog API */ - GtkWindow* BuildDialog(); - void PostModal (EMessageBoxReturn code); -}; - -extern PrefsDlg g_Preferences; - -struct preferences_globals_t -{ - // disabled all INI / registry read write .. used when shutting down after registry cleanup - bool disable_ini; - preferences_globals_t() : disable_ini(false) - { - } -}; -extern preferences_globals_t g_preferences_globals; - -typedef struct _GtkWindow GtkWindow; -void PreferencesDialog_constructWindow(GtkWindow* main_window); -void PreferencesDialog_destroyWindow(); - -void PreferencesDialog_showDialog(); - -void GlobalPreferences_Init(); -void Preferences_Init(); - -void Preferences_Load(); -void Preferences_Save(); - -void Preferences_Reset(); - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/qe3.cpp b/misc/mediasource/extra/netradiant-src/radiant/qe3.cpp deleted file mode 100644 index 67ffebec..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/qe3.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -The following source code is licensed by Id Software and subject to the terms of -its LIMITED USE SOFTWARE LICENSE AGREEMENT, a copy of which is included with -GtkRadiant. If you did not receive a LIMITED USE SOFTWARE LICENSE AGREEMENT, -please contact Id Software immediately at info@idsoftware.com. -*/ - -// -// Linux stuff -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "qe3.h" - -#include "debugging/debugging.h" - -#include "ifilesystem.h" -//#include "imap.h" - -#include - -#include - -#include "stream/textfilestream.h" -#include "cmdlib.h" -#include "stream/stringstream.h" -#include "os/path.h" -#include "scenelib.h" - -#include "gtkutil/messagebox.h" -#include "error.h" -#include "map.h" -#include "build.h" -#include "points.h" -#include "camwindow.h" -#include "mainframe.h" -#include "preferences.h" -#include "watchbsp.h" -#include "autosave.h" -#include "convert.h" - -QEGlobals_t g_qeglobals; - - -#if defined(WIN32) -#define PATH_MAX 260 -#endif - - -void QE_InitVFS() -{ - // VFS initialization ----------------------- - // we will call GlobalFileSystem().initDirectory, giving the directories to look in (for files in pk3's and for standalone files) - // we need to call in order, the mod ones first, then the base ones .. they will be searched in this order - // *nix systems have a dual filesystem in ~/.q3a, which is searched first .. so we need to add that too - - const char* gamename = gamename_get(); - const char* basegame = basegame_get(); -#if defined(POSIX) - const char* userRoot = g_qeglobals.m_userEnginePath.c_str(); -#endif - const char* globalRoot = EnginePath_get(); - - // if we have a mod dir - if(!string_equal(gamename, basegame)) - { -#if defined(POSIX) - // ~/./ - { - StringOutputStream userGamePath(256); - userGamePath << userRoot << gamename << '/'; - GlobalFileSystem().initDirectory(userGamePath.c_str()); - } -#endif - - // / - { - StringOutputStream globalGamePath(256); - globalGamePath << globalRoot << gamename << '/'; - GlobalFileSystem().initDirectory(globalGamePath.c_str()); - } - } - -#if defined(POSIX) - // ~/./ - { - StringOutputStream userBasePath(256); - userBasePath << userRoot << basegame << '/'; - GlobalFileSystem().initDirectory(userBasePath.c_str()); - } -#endif - - // / - { - StringOutputStream globalBasePath(256); - globalBasePath << globalRoot << basegame << '/'; - GlobalFileSystem().initDirectory(globalBasePath.c_str()); - } -} - -int g_numbrushes = 0; -int g_numentities = 0; - -void QE_UpdateStatusBar() -{ - char buffer[128]; - sprintf(buffer, "Brushes: %d Entities: %d", g_numbrushes, g_numentities); - g_pParentWnd->SetStatusText(g_pParentWnd->m_brushcount_status, buffer); -} - -SimpleCounter g_brushCount; - -void QE_brushCountChanged() -{ - g_numbrushes = int(g_brushCount.get()); - QE_UpdateStatusBar(); -} - -SimpleCounter g_entityCount; - -void QE_entityCountChanged() -{ - g_numentities = int(g_entityCount.get()); - QE_UpdateStatusBar(); -} - -bool ConfirmModified(const char* title) -{ - if (!Map_Modified(g_map)) - return true; - - EMessageBoxReturn result = gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "The current map has changed since it was last saved.\nDo you want to save the current map before continuing?", title, eMB_YESNOCANCEL, eMB_ICONQUESTION); - if(result == eIDCANCEL) - { - return false; - } - if(result == eIDYES) - { - if(Map_Unnamed(g_map)) - { - return Map_SaveAs(); - } - else - { - return Map_Save(); - } - } - return true; -} - -void bsp_init() -{ - build_set_variable("RadiantPath", AppPath_get()); - build_set_variable("ExecutableType", RADIANT_EXECUTABLE); - build_set_variable("EnginePath", EnginePath_get()); - build_set_variable("MonitorAddress", (g_WatchBSP_Enabled) ? "127.0.0.1:39000" : ""); - build_set_variable("GameName", gamename_get()); - - const char* mapname = Map_Name(g_map); - StringOutputStream name(256); - name << StringRange(mapname, path_get_filename_base_end(mapname)) << ".bsp"; - - build_set_variable("MapFile", mapname); - build_set_variable("BspFile", name.c_str()); -} - -void bsp_shutdown() -{ - build_clear_variables(); -} - -class ArrayCommandListener : public CommandListener -{ - GPtrArray* m_array; -public: - ArrayCommandListener() - { - m_array = g_ptr_array_new(); - } - ~ArrayCommandListener() - { - g_ptr_array_free(m_array, TRUE); - } - - void execute(const char* command) - { - g_ptr_array_add(m_array, g_strdup(command)); - } - - GPtrArray* array() const - { - return m_array; - } -}; - -class BatchCommandListener : public CommandListener -{ - TextOutputStream& m_file; - std::size_t m_commandCount; - const char* m_outputRedirect; -public: - BatchCommandListener(TextOutputStream& file, const char* outputRedirect) : m_file(file), m_commandCount(0), m_outputRedirect(outputRedirect) - { - } - - void execute(const char* command) - { - m_file << command; - if (m_commandCount == 0) - { - m_file << " > "; - } - else - { - m_file << " >> "; - } - m_file << "\"" << m_outputRedirect << "\""; - m_file << "\n"; - ++m_commandCount; - } -}; - -bool Region_cameraValid() -{ - Vector3 vOrig(vector3_snapped(Camera_getOrigin(*g_pParentWnd->GetCamWnd()))); - - for (int i=0 ; i<3 ; i++) - { - if (vOrig[i] > region_maxs[i] || vOrig[i] < region_mins[i]) - { - return false; - } - } - return true; -} - - -void RunBSP(const char* name) -{ - // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=503 - // make sure we don't attempt to region compile a map with the camera outside the region - if (region_active && !Region_cameraValid()) - { - globalErrorStream() << "The camera must be in the region to start a region compile.\n"; - return; - } - - SaveMap(); - - if(Map_Unnamed(g_map)) - { - globalOutputStream() << "build cancelled\n"; - return; - } - - if (g_SnapShots_Enabled && !Map_Unnamed(g_map) && Map_Modified(g_map)) - { - Map_Snapshot(); - } - - if (region_active) - { - const char* mapname = Map_Name(g_map); - StringOutputStream name(256); - name << StringRange(mapname, path_get_filename_base_end(mapname)) << ".reg"; - Map_SaveRegion(name.c_str()); - } - - Pointfile_Delete(); - - bsp_init(); - - if (g_WatchBSP_Enabled) - { - ArrayCommandListener listener; - build_run(name, listener); - // grab the file name for engine running - const char* fullname = Map_Name(g_map); - StringOutputStream bspname(64); - bspname << StringRange(path_get_filename_start(fullname), path_get_filename_base_end(fullname)); - BuildMonitor_Run( listener.array(), bspname.c_str() ); - } - else - { - char junkpath[PATH_MAX]; - strcpy(junkpath, SettingsPath_get()); - strcat(junkpath, "junk.txt"); - - char batpath[PATH_MAX]; -#if defined(POSIX) - strcpy(batpath, SettingsPath_get()); - strcat(batpath, "qe3bsp.sh"); -#elif defined(WIN32) - strcpy(batpath, SettingsPath_get()); - strcat(batpath, "qe3bsp.bat"); -#else -#error "unsupported platform" -#endif - bool written = false; - { - TextFileOutputStream batchFile(batpath); - if(!batchFile.failed()) - { -#if defined (POSIX) - batchFile << "#!/bin/sh \n\n"; -#endif - BatchCommandListener listener(batchFile, junkpath); - build_run(name, listener); - written = true; - } - } - if(written) - { -#if defined (POSIX) - chmod (batpath, 0744); -#endif - globalOutputStream() << "Writing the compile script to '" << batpath << "'\n"; - globalOutputStream() << "The build output will be saved in '" << junkpath << "'\n"; - Q_Exec(batpath, NULL, NULL, true, false); - } - } - - bsp_shutdown(); -} - -// ============================================================================= -// Sys_ functions - -void Sys_SetTitle(const char *text, bool modified) -{ - StringOutputStream title; - title << text; - - if(modified) - { - title << " *"; - } - - gtk_window_set_title(MainFrame_getWindow(), title.c_str()); -} - -bool g_bWaitCursor = false; - -void Sys_BeginWait (void) -{ - ScreenUpdates_Disable("Processing...", "Please Wait"); - GdkCursor *cursor = gdk_cursor_new (GDK_WATCH); - gdk_window_set_cursor(GTK_WIDGET(MainFrame_getWindow())->window, cursor); - gdk_cursor_unref (cursor); - g_bWaitCursor = true; -} - -void Sys_EndWait (void) -{ - ScreenUpdates_Enable(); - gdk_window_set_cursor(GTK_WIDGET(MainFrame_getWindow())->window, 0); - g_bWaitCursor = false; -} - -void Sys_Beep (void) -{ - gdk_beep(); -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/qe3.h b/misc/mediasource/extra/netradiant-src/radiant/qe3.h deleted file mode 100644 index b07223a0..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/qe3.h +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_QE3_H) -#define INCLUDED_QE3_H - -#include "string/string.h" - -// -// system functions -// -void Sys_SetTitle (const char *text, bool modified); - - -void RunBSP(const char* name); - - -void QE_InitVFS(); - -void QE_brushCountChanged(); -void QE_entityCountChanged(); - -bool ConfirmModified(const char* title); - - -// most of the QE globals are stored in this structure -typedef struct -{ - /*! - win32: engine full path. - unix: user home full path + engine dir. - */ - CopiedString m_userEnginePath; - /*! - cache for m_userEnginePath + mod subdirectory. - */ - CopiedString m_userGamePath; - -} QEGlobals_t; - -extern QEGlobals_t g_qeglobals; - -class SimpleCounter; -extern SimpleCounter g_brushCount; -extern SimpleCounter g_entityCount; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/qgl.cpp b/misc/mediasource/extra/netradiant-src/radiant/qgl.cpp deleted file mode 100644 index 335cb46b..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/qgl.cpp +++ /dev/null @@ -1,1542 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qgl.h" - -#include "debugging/debugging.h" - -#include -#include -#include - -#if defined(_WIN32) -#define WINGDIAPI __declspec(dllimport) -#define APIENTRY __stdcall -#endif - -#include - -#if defined(_WIN32) -#undef WINGDIAPI -#undef APIENTRY -#endif - -#include "igl.h" - - - - -#if defined(_WIN32) - -#include - -PROC ( WINAPI * qwglGetProcAddress)(LPCSTR); - -#elif defined (XWINDOWS) - -#include -#include -#include - -Bool (*qglXQueryExtension)( Display *dpy, int *errorb, int *event ); -void* (*qglXGetProcAddressARB) (const GLubyte *procName); -typedef void* (*glXGetProcAddressARBProc) (const GLubyte *procName); - -#else -#error "unsupported platform" -#endif - - -void QGL_Shutdown(OpenGLBinding& table) -{ - globalOutputStream() << "Shutting down OpenGL module..."; - -#if defined(WIN32) - qwglGetProcAddress = 0; -#elif defined(XWINDOWS) - qglXQueryExtension = glXQueryExtension; - qglXGetProcAddressARB = 0; -#else -#error "unsupported platform" -#endif - - globalOutputStream() << "Done.\n"; -} - - -typedef struct glu_error_struct -{ - GLenum errnum; - const char *errstr; -} GLU_ERROR_STRUCT; - -GLU_ERROR_STRUCT glu_errlist[] = { - {GL_NO_ERROR, "GL_NO_ERROR - no error"}, - {GL_INVALID_ENUM, "GL_INVALID_ENUM - An unacceptable value is specified for an enumerated argument."}, - {GL_INVALID_VALUE, "GL_INVALID_VALUE - A numeric argument is out of range."}, - {GL_INVALID_OPERATION, "GL_INVALID_OPERATION - The specified operation is not allowed in the current state."}, - {GL_STACK_OVERFLOW, "GL_STACK_OVERFLOW - Function would cause a stack overflow."}, - {GL_STACK_UNDERFLOW, "GL_STACK_UNDERFLOW - Function would cause a stack underflow."}, - {GL_OUT_OF_MEMORY, "GL_OUT_OF_MEMORY - There is not enough memory left to execute the function."}, - {0, 0} -}; - -const GLubyte* qgluErrorString(GLenum errCode ) -{ - int search = 0; - for (search = 0; glu_errlist[search].errstr; search++) - { - if (errCode == glu_errlist[search].errnum) - return (const GLubyte *)glu_errlist[search].errstr; - } //end for - return (const GLubyte *)"Unknown error"; -} - - -void glInvalidFunction() -{ - ERROR_MESSAGE("calling an invalid OpenGL function"); -} - -#define EXTENSIONS_ENABLED 1 - -bool QGL_ExtensionSupported(const char* extension) -{ -#if EXTENSIONS_ENABLED - const GLubyte *extensions = 0; - const GLubyte *start; - GLubyte *where, *terminator; - - // Extension names should not have spaces. - where = (GLubyte *) strchr (extension, ' '); - if (where || *extension == '\0') - return false; - - extensions = GlobalOpenGL().m_glGetString (GL_EXTENSIONS); -#ifndef __APPLE__ - if (!extensions) - return false; -#endif - - // It takes a bit of care to be fool-proof about parsing the - // OpenGL extensions string. Don't be fooled by sub-strings, etc. - for (start = extensions; ;) - { - where = (GLubyte *) strstr ((const char *) start, extension); - if (!where) - break; - - terminator = where + strlen (extension); - if (where == start || *(where - 1) == ' ') - if (*terminator == ' ' || *terminator == '\0') - return true; - - start = terminator; - } -#endif - - return false; -} - -typedef int (QGL_DLLEXPORT *QGLFunctionPointer)(); - -QGLFunctionPointer QGL_getExtensionFunc(const char* symbol) -{ -#if defined(XWINDOWS) - //ASSERT_NOTNULL(qglXGetProcAddressARB); - if (qglXGetProcAddressARB == 0) - { - return reinterpret_cast(glInvalidFunction); - } - else - { - return (QGLFunctionPointer)qglXGetProcAddressARB(reinterpret_cast(symbol)); - } -#elif defined(WIN32) - ASSERT_NOTNULL(qwglGetProcAddress); - return qwglGetProcAddress(symbol); -#else -#error "unsupported platform" -#endif -} - - -template -bool QGL_constructExtensionFunc(Func& func, const char* symbol) -{ - func = reinterpret_cast(QGL_getExtensionFunc(symbol)); - return func != 0; -} - -template -void QGL_invalidateExtensionFunc(Func& func) -{ - func = reinterpret_cast(glInvalidFunction); -} - -void QGL_clear(OpenGLBinding& table) -{ - QGL_invalidateExtensionFunc(table.m_glAccum); - QGL_invalidateExtensionFunc(table.m_glAlphaFunc); - QGL_invalidateExtensionFunc(table.m_glAreTexturesResident); - QGL_invalidateExtensionFunc(table.m_glArrayElement); - QGL_invalidateExtensionFunc(table.m_glBegin); - QGL_invalidateExtensionFunc(table.m_glBindTexture); - QGL_invalidateExtensionFunc(table.m_glBitmap); - QGL_invalidateExtensionFunc(table.m_glBlendFunc); - QGL_invalidateExtensionFunc(table.m_glCallList); - QGL_invalidateExtensionFunc(table.m_glCallLists); - QGL_invalidateExtensionFunc(table.m_glClear); - QGL_invalidateExtensionFunc(table.m_glClearAccum); - QGL_invalidateExtensionFunc(table.m_glClearColor); - QGL_invalidateExtensionFunc(table.m_glClearDepth); - QGL_invalidateExtensionFunc(table.m_glClearIndex); - QGL_invalidateExtensionFunc(table.m_glClearStencil); - QGL_invalidateExtensionFunc(table.m_glClipPlane); - QGL_invalidateExtensionFunc(table.m_glColor3b); - QGL_invalidateExtensionFunc(table.m_glColor3bv); - QGL_invalidateExtensionFunc(table.m_glColor3d); - QGL_invalidateExtensionFunc(table.m_glColor3dv); - QGL_invalidateExtensionFunc(table.m_glColor3f); - QGL_invalidateExtensionFunc(table.m_glColor3fv); - QGL_invalidateExtensionFunc(table.m_glColor3i); - QGL_invalidateExtensionFunc(table.m_glColor3iv); - QGL_invalidateExtensionFunc(table.m_glColor3s); - QGL_invalidateExtensionFunc(table.m_glColor3sv); - QGL_invalidateExtensionFunc(table.m_glColor3ub); - QGL_invalidateExtensionFunc(table.m_glColor3ubv); - QGL_invalidateExtensionFunc(table.m_glColor3ui); - QGL_invalidateExtensionFunc(table.m_glColor3uiv); - QGL_invalidateExtensionFunc(table.m_glColor3us); - QGL_invalidateExtensionFunc(table.m_glColor3usv); - QGL_invalidateExtensionFunc(table.m_glColor4b); - QGL_invalidateExtensionFunc(table.m_glColor4bv); - QGL_invalidateExtensionFunc(table.m_glColor4d); - QGL_invalidateExtensionFunc(table.m_glColor4dv); - QGL_invalidateExtensionFunc(table.m_glColor4f); - QGL_invalidateExtensionFunc(table.m_glColor4fv); - QGL_invalidateExtensionFunc(table.m_glColor4i); - QGL_invalidateExtensionFunc(table.m_glColor4iv); - QGL_invalidateExtensionFunc(table.m_glColor4s); - QGL_invalidateExtensionFunc(table.m_glColor4sv); - QGL_invalidateExtensionFunc(table.m_glColor4ub); - QGL_invalidateExtensionFunc(table.m_glColor4ubv); - QGL_invalidateExtensionFunc(table.m_glColor4ui); - QGL_invalidateExtensionFunc(table.m_glColor4uiv); - QGL_invalidateExtensionFunc(table.m_glColor4us); - QGL_invalidateExtensionFunc(table.m_glColor4usv); - QGL_invalidateExtensionFunc(table.m_glColorMask); - QGL_invalidateExtensionFunc(table.m_glColorMaterial); - QGL_invalidateExtensionFunc(table.m_glColorPointer); - QGL_invalidateExtensionFunc(table.m_glCopyPixels); - QGL_invalidateExtensionFunc(table.m_glCopyTexImage1D); - QGL_invalidateExtensionFunc(table.m_glCopyTexImage2D); - QGL_invalidateExtensionFunc(table.m_glCopyTexSubImage1D); - QGL_invalidateExtensionFunc(table.m_glCopyTexSubImage2D); - QGL_invalidateExtensionFunc(table.m_glCullFace); - QGL_invalidateExtensionFunc(table.m_glDeleteLists); - QGL_invalidateExtensionFunc(table.m_glDeleteTextures); - QGL_invalidateExtensionFunc(table.m_glDepthFunc); - QGL_invalidateExtensionFunc(table.m_glDepthMask); - QGL_invalidateExtensionFunc(table.m_glDepthRange); - QGL_invalidateExtensionFunc(table.m_glDisable); - QGL_invalidateExtensionFunc(table.m_glDisableClientState); - QGL_invalidateExtensionFunc(table.m_glDrawArrays); - QGL_invalidateExtensionFunc(table.m_glDrawBuffer); - QGL_invalidateExtensionFunc(table.m_glDrawElements); - QGL_invalidateExtensionFunc(table.m_glDrawPixels); - QGL_invalidateExtensionFunc(table.m_glEdgeFlag); - QGL_invalidateExtensionFunc(table.m_glEdgeFlagPointer); - QGL_invalidateExtensionFunc(table.m_glEdgeFlagv); - QGL_invalidateExtensionFunc(table.m_glEnable); - QGL_invalidateExtensionFunc(table.m_glEnableClientState); - QGL_invalidateExtensionFunc(table.m_glEnd); - QGL_invalidateExtensionFunc(table.m_glEndList); - QGL_invalidateExtensionFunc(table.m_glEvalCoord1d); - QGL_invalidateExtensionFunc(table.m_glEvalCoord1dv); - QGL_invalidateExtensionFunc(table.m_glEvalCoord1f); - QGL_invalidateExtensionFunc(table.m_glEvalCoord1fv); - QGL_invalidateExtensionFunc(table.m_glEvalCoord2d); - QGL_invalidateExtensionFunc(table.m_glEvalCoord2dv); - QGL_invalidateExtensionFunc(table.m_glEvalCoord2f); - QGL_invalidateExtensionFunc(table.m_glEvalCoord2fv); - QGL_invalidateExtensionFunc(table.m_glEvalMesh1); - QGL_invalidateExtensionFunc(table.m_glEvalMesh2); - QGL_invalidateExtensionFunc(table.m_glEvalPoint1); - QGL_invalidateExtensionFunc(table.m_glEvalPoint2); - QGL_invalidateExtensionFunc(table.m_glFeedbackBuffer); - QGL_invalidateExtensionFunc(table.m_glFinish); - QGL_invalidateExtensionFunc(table.m_glFlush); - QGL_invalidateExtensionFunc(table.m_glFogf); - QGL_invalidateExtensionFunc(table.m_glFogfv); - QGL_invalidateExtensionFunc(table.m_glFogi); - QGL_invalidateExtensionFunc(table.m_glFogiv); - QGL_invalidateExtensionFunc(table.m_glFrontFace); - QGL_invalidateExtensionFunc(table.m_glFrustum); - QGL_invalidateExtensionFunc(table.m_glGenLists); - QGL_invalidateExtensionFunc(table.m_glGenTextures); - QGL_invalidateExtensionFunc(table.m_glGetBooleanv); - QGL_invalidateExtensionFunc(table.m_glGetClipPlane); - QGL_invalidateExtensionFunc(table.m_glGetDoublev); - QGL_invalidateExtensionFunc(table.m_glGetError); - QGL_invalidateExtensionFunc(table.m_glGetFloatv); - QGL_invalidateExtensionFunc(table.m_glGetIntegerv); - QGL_invalidateExtensionFunc(table.m_glGetLightfv); - QGL_invalidateExtensionFunc(table.m_glGetLightiv); - QGL_invalidateExtensionFunc(table.m_glGetMapdv); - QGL_invalidateExtensionFunc(table.m_glGetMapfv); - QGL_invalidateExtensionFunc(table.m_glGetMapiv); - QGL_invalidateExtensionFunc(table.m_glGetMaterialfv); - QGL_invalidateExtensionFunc(table.m_glGetMaterialiv); - QGL_invalidateExtensionFunc(table.m_glGetPixelMapfv); - QGL_invalidateExtensionFunc(table.m_glGetPixelMapuiv); - QGL_invalidateExtensionFunc(table.m_glGetPixelMapusv); - QGL_invalidateExtensionFunc(table.m_glGetPointerv); - QGL_invalidateExtensionFunc(table.m_glGetPolygonStipple); - table.m_glGetString = glGetString; - QGL_invalidateExtensionFunc(table.m_glGetTexEnvfv); - QGL_invalidateExtensionFunc(table.m_glGetTexEnviv); - QGL_invalidateExtensionFunc(table.m_glGetTexGendv); - QGL_invalidateExtensionFunc(table.m_glGetTexGenfv); - QGL_invalidateExtensionFunc(table.m_glGetTexGeniv); - QGL_invalidateExtensionFunc(table.m_glGetTexImage); - QGL_invalidateExtensionFunc(table.m_glGetTexLevelParameterfv); - QGL_invalidateExtensionFunc(table.m_glGetTexLevelParameteriv); - QGL_invalidateExtensionFunc(table.m_glGetTexParameterfv); - QGL_invalidateExtensionFunc(table.m_glGetTexParameteriv); - QGL_invalidateExtensionFunc(table.m_glHint); - QGL_invalidateExtensionFunc(table.m_glIndexMask); - QGL_invalidateExtensionFunc(table.m_glIndexPointer); - QGL_invalidateExtensionFunc(table.m_glIndexd); - QGL_invalidateExtensionFunc(table.m_glIndexdv); - QGL_invalidateExtensionFunc(table.m_glIndexf); - QGL_invalidateExtensionFunc(table.m_glIndexfv); - QGL_invalidateExtensionFunc(table.m_glIndexi); - QGL_invalidateExtensionFunc(table.m_glIndexiv); - QGL_invalidateExtensionFunc(table.m_glIndexs); - QGL_invalidateExtensionFunc(table.m_glIndexsv); - QGL_invalidateExtensionFunc(table.m_glIndexub); - QGL_invalidateExtensionFunc(table.m_glIndexubv); - QGL_invalidateExtensionFunc(table.m_glInitNames); - QGL_invalidateExtensionFunc(table.m_glInterleavedArrays); - QGL_invalidateExtensionFunc(table.m_glIsEnabled); - QGL_invalidateExtensionFunc(table.m_glIsList); - QGL_invalidateExtensionFunc(table.m_glIsTexture); - QGL_invalidateExtensionFunc(table.m_glLightModelf); - QGL_invalidateExtensionFunc(table.m_glLightModelfv); - QGL_invalidateExtensionFunc(table.m_glLightModeli); - QGL_invalidateExtensionFunc(table.m_glLightModeliv); - QGL_invalidateExtensionFunc(table.m_glLightf); - QGL_invalidateExtensionFunc(table.m_glLightfv); - QGL_invalidateExtensionFunc(table.m_glLighti); - QGL_invalidateExtensionFunc(table.m_glLightiv); - QGL_invalidateExtensionFunc(table.m_glLineStipple); - QGL_invalidateExtensionFunc(table.m_glLineWidth); - QGL_invalidateExtensionFunc(table.m_glListBase); - QGL_invalidateExtensionFunc(table.m_glLoadIdentity); - QGL_invalidateExtensionFunc(table.m_glLoadMatrixd); - QGL_invalidateExtensionFunc(table.m_glLoadMatrixf); - QGL_invalidateExtensionFunc(table.m_glLoadName); - QGL_invalidateExtensionFunc(table.m_glLogicOp); - QGL_invalidateExtensionFunc(table.m_glMap1d); - QGL_invalidateExtensionFunc(table.m_glMap1f); - QGL_invalidateExtensionFunc(table.m_glMap2d); - QGL_invalidateExtensionFunc(table.m_glMap2f); - QGL_invalidateExtensionFunc(table.m_glMapGrid1d); - QGL_invalidateExtensionFunc(table.m_glMapGrid1f); - QGL_invalidateExtensionFunc(table.m_glMapGrid2d); - QGL_invalidateExtensionFunc(table.m_glMapGrid2f); - QGL_invalidateExtensionFunc(table.m_glMaterialf); - QGL_invalidateExtensionFunc(table.m_glMaterialfv); - QGL_invalidateExtensionFunc(table.m_glMateriali); - QGL_invalidateExtensionFunc(table.m_glMaterialiv); - QGL_invalidateExtensionFunc(table.m_glMatrixMode); - QGL_invalidateExtensionFunc(table.m_glMultMatrixd); - QGL_invalidateExtensionFunc(table.m_glMultMatrixf); - QGL_invalidateExtensionFunc(table.m_glNewList); - QGL_invalidateExtensionFunc(table.m_glNormal3b); - QGL_invalidateExtensionFunc(table.m_glNormal3bv); - QGL_invalidateExtensionFunc(table.m_glNormal3d); - QGL_invalidateExtensionFunc(table.m_glNormal3dv); - QGL_invalidateExtensionFunc(table.m_glNormal3f); - QGL_invalidateExtensionFunc(table.m_glNormal3fv); - QGL_invalidateExtensionFunc(table.m_glNormal3i); - QGL_invalidateExtensionFunc(table.m_glNormal3iv); - QGL_invalidateExtensionFunc(table.m_glNormal3s); - QGL_invalidateExtensionFunc(table.m_glNormal3sv); - QGL_invalidateExtensionFunc(table.m_glNormalPointer); - QGL_invalidateExtensionFunc(table.m_glOrtho); - QGL_invalidateExtensionFunc(table.m_glPassThrough); - QGL_invalidateExtensionFunc(table.m_glPixelMapfv); - QGL_invalidateExtensionFunc(table.m_glPixelMapuiv); - QGL_invalidateExtensionFunc(table.m_glPixelMapusv); - QGL_invalidateExtensionFunc(table.m_glPixelStoref); - QGL_invalidateExtensionFunc(table.m_glPixelStorei); - QGL_invalidateExtensionFunc(table.m_glPixelTransferf); - QGL_invalidateExtensionFunc(table.m_glPixelTransferi); - QGL_invalidateExtensionFunc(table.m_glPixelZoom); - QGL_invalidateExtensionFunc(table.m_glPointSize); - QGL_invalidateExtensionFunc(table.m_glPolygonMode); - QGL_invalidateExtensionFunc(table.m_glPolygonOffset); - QGL_invalidateExtensionFunc(table.m_glPolygonStipple); - QGL_invalidateExtensionFunc(table.m_glPopAttrib); - QGL_invalidateExtensionFunc(table.m_glPopClientAttrib); - QGL_invalidateExtensionFunc(table.m_glPopMatrix); - QGL_invalidateExtensionFunc(table.m_glPopName); - QGL_invalidateExtensionFunc(table.m_glPrioritizeTextures); - QGL_invalidateExtensionFunc(table.m_glPushAttrib); - QGL_invalidateExtensionFunc(table.m_glPushClientAttrib); - QGL_invalidateExtensionFunc(table.m_glPushMatrix); - QGL_invalidateExtensionFunc(table.m_glPushName); - QGL_invalidateExtensionFunc(table.m_glRasterPos2d); - QGL_invalidateExtensionFunc(table.m_glRasterPos2dv); - QGL_invalidateExtensionFunc(table.m_glRasterPos2f); - QGL_invalidateExtensionFunc(table.m_glRasterPos2fv); - QGL_invalidateExtensionFunc(table.m_glRasterPos2i); - QGL_invalidateExtensionFunc(table.m_glRasterPos2iv); - QGL_invalidateExtensionFunc(table.m_glRasterPos2s); - QGL_invalidateExtensionFunc(table.m_glRasterPos2sv); - QGL_invalidateExtensionFunc(table.m_glRasterPos3d); - QGL_invalidateExtensionFunc(table.m_glRasterPos3dv); - QGL_invalidateExtensionFunc(table.m_glRasterPos3f); - QGL_invalidateExtensionFunc(table.m_glRasterPos3fv); - QGL_invalidateExtensionFunc(table.m_glRasterPos3i); - QGL_invalidateExtensionFunc(table.m_glRasterPos3iv); - QGL_invalidateExtensionFunc(table.m_glRasterPos3s); - QGL_invalidateExtensionFunc(table.m_glRasterPos3sv); - QGL_invalidateExtensionFunc(table.m_glRasterPos4d); - QGL_invalidateExtensionFunc(table.m_glRasterPos4dv); - QGL_invalidateExtensionFunc(table.m_glRasterPos4f); - QGL_invalidateExtensionFunc(table.m_glRasterPos4fv); - QGL_invalidateExtensionFunc(table.m_glRasterPos4i); - QGL_invalidateExtensionFunc(table.m_glRasterPos4iv); - QGL_invalidateExtensionFunc(table.m_glRasterPos4s); - QGL_invalidateExtensionFunc(table.m_glRasterPos4sv); - QGL_invalidateExtensionFunc(table.m_glReadBuffer); - QGL_invalidateExtensionFunc(table.m_glReadPixels); - QGL_invalidateExtensionFunc(table.m_glRectd); - QGL_invalidateExtensionFunc(table.m_glRectdv); - QGL_invalidateExtensionFunc(table.m_glRectf); - QGL_invalidateExtensionFunc(table.m_glRectfv); - QGL_invalidateExtensionFunc(table.m_glRecti); - QGL_invalidateExtensionFunc(table.m_glRectiv); - QGL_invalidateExtensionFunc(table.m_glRects); - QGL_invalidateExtensionFunc(table.m_glRectsv); - QGL_invalidateExtensionFunc(table.m_glRenderMode); - QGL_invalidateExtensionFunc(table.m_glRotated); - QGL_invalidateExtensionFunc(table.m_glRotatef); - QGL_invalidateExtensionFunc(table.m_glScaled); - QGL_invalidateExtensionFunc(table.m_glScalef); - QGL_invalidateExtensionFunc(table.m_glScissor); - QGL_invalidateExtensionFunc(table.m_glSelectBuffer); - QGL_invalidateExtensionFunc(table.m_glShadeModel); - QGL_invalidateExtensionFunc(table.m_glStencilFunc); - QGL_invalidateExtensionFunc(table.m_glStencilMask); - QGL_invalidateExtensionFunc(table.m_glStencilOp); - QGL_invalidateExtensionFunc(table.m_glTexCoord1d); - QGL_invalidateExtensionFunc(table.m_glTexCoord1dv); - QGL_invalidateExtensionFunc(table.m_glTexCoord1f); - QGL_invalidateExtensionFunc(table.m_glTexCoord1fv); - QGL_invalidateExtensionFunc(table.m_glTexCoord1i); - QGL_invalidateExtensionFunc(table.m_glTexCoord1iv); - QGL_invalidateExtensionFunc(table.m_glTexCoord1s); - QGL_invalidateExtensionFunc(table.m_glTexCoord1sv); - QGL_invalidateExtensionFunc(table.m_glTexCoord2d); - QGL_invalidateExtensionFunc(table.m_glTexCoord2dv); - QGL_invalidateExtensionFunc(table.m_glTexCoord2f); - QGL_invalidateExtensionFunc(table.m_glTexCoord2fv); - QGL_invalidateExtensionFunc(table.m_glTexCoord2i); - QGL_invalidateExtensionFunc(table.m_glTexCoord2iv); - QGL_invalidateExtensionFunc(table.m_glTexCoord2s); - QGL_invalidateExtensionFunc(table.m_glTexCoord2sv); - QGL_invalidateExtensionFunc(table.m_glTexCoord3d); - QGL_invalidateExtensionFunc(table.m_glTexCoord3dv); - QGL_invalidateExtensionFunc(table.m_glTexCoord3f); - QGL_invalidateExtensionFunc(table.m_glTexCoord3fv); - QGL_invalidateExtensionFunc(table.m_glTexCoord3i); - QGL_invalidateExtensionFunc(table.m_glTexCoord3iv); - QGL_invalidateExtensionFunc(table.m_glTexCoord3s); - QGL_invalidateExtensionFunc(table.m_glTexCoord3sv); - QGL_invalidateExtensionFunc(table.m_glTexCoord4d); - QGL_invalidateExtensionFunc(table.m_glTexCoord4dv); - QGL_invalidateExtensionFunc(table.m_glTexCoord4f); - QGL_invalidateExtensionFunc(table.m_glTexCoord4fv); - QGL_invalidateExtensionFunc(table.m_glTexCoord4i); - QGL_invalidateExtensionFunc(table.m_glTexCoord4iv); - QGL_invalidateExtensionFunc(table.m_glTexCoord4s); - QGL_invalidateExtensionFunc(table.m_glTexCoord4sv); - QGL_invalidateExtensionFunc(table.m_glTexCoordPointer); - QGL_invalidateExtensionFunc(table.m_glTexEnvf); - QGL_invalidateExtensionFunc(table.m_glTexEnvfv); - QGL_invalidateExtensionFunc(table.m_glTexEnvi); - QGL_invalidateExtensionFunc(table.m_glTexEnviv); - QGL_invalidateExtensionFunc(table.m_glTexGend); - QGL_invalidateExtensionFunc(table.m_glTexGendv); - QGL_invalidateExtensionFunc(table.m_glTexGenf); - QGL_invalidateExtensionFunc(table.m_glTexGenfv); - QGL_invalidateExtensionFunc(table.m_glTexGeni); - QGL_invalidateExtensionFunc(table.m_glTexGeniv); - QGL_invalidateExtensionFunc(table.m_glTexImage1D); - QGL_invalidateExtensionFunc(table.m_glTexImage2D); - QGL_invalidateExtensionFunc(table.m_glTexParameterf); - QGL_invalidateExtensionFunc(table.m_glTexParameterfv); - QGL_invalidateExtensionFunc(table.m_glTexParameteri); - QGL_invalidateExtensionFunc(table.m_glTexParameteriv); - QGL_invalidateExtensionFunc(table.m_glTexSubImage1D); - QGL_invalidateExtensionFunc(table.m_glTexSubImage2D); - QGL_invalidateExtensionFunc(table.m_glTranslated); - QGL_invalidateExtensionFunc(table.m_glTranslatef); - QGL_invalidateExtensionFunc(table.m_glVertex2d); - QGL_invalidateExtensionFunc(table.m_glVertex2dv); - QGL_invalidateExtensionFunc(table.m_glVertex2f); - QGL_invalidateExtensionFunc(table.m_glVertex2fv); - QGL_invalidateExtensionFunc(table.m_glVertex2i); - QGL_invalidateExtensionFunc(table.m_glVertex2iv); - QGL_invalidateExtensionFunc(table.m_glVertex2s); - QGL_invalidateExtensionFunc(table.m_glVertex2sv); - QGL_invalidateExtensionFunc(table.m_glVertex3d); - QGL_invalidateExtensionFunc(table.m_glVertex3dv); - QGL_invalidateExtensionFunc(table.m_glVertex3f); - QGL_invalidateExtensionFunc(table.m_glVertex3fv); - QGL_invalidateExtensionFunc(table.m_glVertex3i); - QGL_invalidateExtensionFunc(table.m_glVertex3iv); - QGL_invalidateExtensionFunc(table.m_glVertex3s); - QGL_invalidateExtensionFunc(table.m_glVertex3sv); - QGL_invalidateExtensionFunc(table.m_glVertex4d); - QGL_invalidateExtensionFunc(table.m_glVertex4dv); - QGL_invalidateExtensionFunc(table.m_glVertex4f); - QGL_invalidateExtensionFunc(table.m_glVertex4fv); - QGL_invalidateExtensionFunc(table.m_glVertex4i); - QGL_invalidateExtensionFunc(table.m_glVertex4iv); - QGL_invalidateExtensionFunc(table.m_glVertex4s); - QGL_invalidateExtensionFunc(table.m_glVertex4sv); - QGL_invalidateExtensionFunc(table.m_glVertexPointer); - QGL_invalidateExtensionFunc(table.m_glViewport); -} - -int QGL_Init(OpenGLBinding& table) -{ - QGL_clear(table); - -#if defined(WIN32) - qwglGetProcAddress = wglGetProcAddress; -#elif defined(XWINDOWS) - qglXGetProcAddressARB = (glXGetProcAddressARBProc)dlsym(RTLD_DEFAULT, "glXGetProcAddressARB"); - if ((qglXQueryExtension == 0) || (qglXQueryExtension(GDK_DISPLAY(),0,0) != True)) - return 0; -#else -#error "unsupported platform" -#endif - - return 1; -} - -int g_qglMajorVersion = 0; -int g_qglMinorVersion = 0; - -// requires a valid gl context -void QGL_InitVersion() -{ -#if EXTENSIONS_ENABLED - const std::size_t versionSize = 256; - char version[versionSize]; - strncpy(version, reinterpret_cast(GlobalOpenGL().m_glGetString(GL_VERSION)), versionSize - 1); - version[versionSize - 1] = '\0'; - char* firstDot = strchr(version, '.'); - ASSERT_NOTNULL(firstDot); - *firstDot = '\0'; - g_qglMajorVersion = atoi(version); - char* secondDot = strchr(firstDot + 1, '.'); - if(secondDot != 0) - { - *secondDot = '\0'; - } - g_qglMinorVersion = atoi(firstDot + 1); -#else - g_qglMajorVersion = 1; - g_qglMinorVersion = 1; -#endif -} - - -inline void extension_not_implemented(const char* extension) -{ - globalErrorStream() << "WARNING: OpenGL driver reports support for " << extension << " but does not implement it\n"; -} - -float g_maxTextureAnisotropy; - -float QGL_maxTextureAnisotropy() -{ - return g_maxTextureAnisotropy; -} - -void QGL_sharedContextCreated(OpenGLBinding& table) -{ - QGL_InitVersion(); - - table.major_version = g_qglMajorVersion; - table.minor_version = g_qglMinorVersion; - - table.m_glAccum = glAccum; - table.m_glAlphaFunc = glAlphaFunc; - table.m_glAreTexturesResident = glAreTexturesResident; - table.m_glArrayElement = glArrayElement; - table.m_glBegin = glBegin; - table.m_glBindTexture = glBindTexture; - table.m_glBitmap = glBitmap; - table.m_glBlendFunc = glBlendFunc; - table.m_glCallList = glCallList; - table.m_glCallLists = glCallLists; - table.m_glClear = glClear; - table.m_glClearAccum = glClearAccum; - table.m_glClearColor = glClearColor; - table.m_glClearDepth = glClearDepth; - table.m_glClearIndex = glClearIndex; - table.m_glClearStencil = glClearStencil; - table.m_glClipPlane = glClipPlane; - table.m_glColor3b = glColor3b; - table.m_glColor3bv = glColor3bv; - table.m_glColor3d = glColor3d; - table.m_glColor3dv = glColor3dv; - table.m_glColor3f = glColor3f; - table.m_glColor3fv = glColor3fv; - table.m_glColor3i = glColor3i; - table.m_glColor3iv = glColor3iv; - table.m_glColor3s = glColor3s; - table.m_glColor3sv = glColor3sv; - table.m_glColor3ub = glColor3ub; - table.m_glColor3ubv = glColor3ubv; - table.m_glColor3ui = glColor3ui; - table.m_glColor3uiv = glColor3uiv; - table.m_glColor3us = glColor3us; - table.m_glColor3usv = glColor3usv; - table.m_glColor4b = glColor4b; - table.m_glColor4bv = glColor4bv; - table.m_glColor4d = glColor4d; - table.m_glColor4dv = glColor4dv; - table.m_glColor4f = glColor4f; - table.m_glColor4fv = glColor4fv; - table.m_glColor4i = glColor4i; - table.m_glColor4iv = glColor4iv; - table.m_glColor4s = glColor4s; - table.m_glColor4sv = glColor4sv; - table.m_glColor4ub = glColor4ub; - table.m_glColor4ubv = glColor4ubv; - table.m_glColor4ui = glColor4ui; - table.m_glColor4uiv = glColor4uiv; - table.m_glColor4us = glColor4us; - table.m_glColor4usv = glColor4usv; - table.m_glColorMask = glColorMask; - table.m_glColorMaterial = glColorMaterial; - table.m_glColorPointer = glColorPointer; - table.m_glCopyPixels = glCopyPixels; - table.m_glCopyTexImage1D = glCopyTexImage1D; - table.m_glCopyTexImage2D = glCopyTexImage2D; - table.m_glCopyTexSubImage1D = glCopyTexSubImage1D; - table.m_glCopyTexSubImage2D = glCopyTexSubImage2D; - table.m_glCullFace = glCullFace; - table.m_glDeleteLists = glDeleteLists; - table.m_glDeleteTextures = glDeleteTextures; - table.m_glDepthFunc = glDepthFunc; - table.m_glDepthMask = glDepthMask; - table.m_glDepthRange = glDepthRange; - table.m_glDisable = glDisable; - table.m_glDisableClientState = glDisableClientState; - table.m_glDrawArrays = glDrawArrays; - table.m_glDrawBuffer = glDrawBuffer; - table.m_glDrawElements = glDrawElements; - table.m_glDrawPixels = glDrawPixels; - table.m_glEdgeFlag = glEdgeFlag; - table.m_glEdgeFlagPointer = glEdgeFlagPointer; - table.m_glEdgeFlagv = glEdgeFlagv; - table.m_glEnable = glEnable; - table.m_glEnableClientState = glEnableClientState; - table.m_glEnd = glEnd; - table.m_glEndList = glEndList; - table.m_glEvalCoord1d = glEvalCoord1d; - table.m_glEvalCoord1dv = glEvalCoord1dv; - table.m_glEvalCoord1f = glEvalCoord1f; - table.m_glEvalCoord1fv = glEvalCoord1fv; - table.m_glEvalCoord2d = glEvalCoord2d; - table.m_glEvalCoord2dv = glEvalCoord2dv; - table.m_glEvalCoord2f = glEvalCoord2f; - table.m_glEvalCoord2fv = glEvalCoord2fv; - table.m_glEvalMesh1 = glEvalMesh1; - table.m_glEvalMesh2 = glEvalMesh2; - table.m_glEvalPoint1 = glEvalPoint1; - table.m_glEvalPoint2 = glEvalPoint2; - table.m_glFeedbackBuffer = glFeedbackBuffer; - table.m_glFinish = glFinish; - table.m_glFlush = glFlush; - table.m_glFogf = glFogf; - table.m_glFogfv = glFogfv; - table.m_glFogi = glFogi; - table.m_glFogiv = glFogiv; - table.m_glFrontFace = glFrontFace; - table.m_glFrustum = glFrustum; - table.m_glGenLists = glGenLists; - table.m_glGenTextures = glGenTextures; - table.m_glGetBooleanv = glGetBooleanv; - table.m_glGetClipPlane = glGetClipPlane; - table.m_glGetDoublev = glGetDoublev; - table.m_glGetError = glGetError; - table.m_glGetFloatv = glGetFloatv; - table.m_glGetIntegerv = glGetIntegerv; - table.m_glGetLightfv = glGetLightfv; - table.m_glGetLightiv = glGetLightiv; - table.m_glGetMapdv = glGetMapdv; - table.m_glGetMapfv = glGetMapfv; - table.m_glGetMapiv = glGetMapiv; - table.m_glGetMaterialfv = glGetMaterialfv; - table.m_glGetMaterialiv = glGetMaterialiv; - table.m_glGetPixelMapfv = glGetPixelMapfv; - table.m_glGetPixelMapuiv = glGetPixelMapuiv; - table.m_glGetPixelMapusv = glGetPixelMapusv; - table.m_glGetPointerv = glGetPointerv; - table.m_glGetPolygonStipple = glGetPolygonStipple; - table.m_glGetString = glGetString; - table.m_glGetTexEnvfv = glGetTexEnvfv; - table.m_glGetTexEnviv = glGetTexEnviv; - table.m_glGetTexGendv = glGetTexGendv; - table.m_glGetTexGenfv = glGetTexGenfv; - table.m_glGetTexGeniv = glGetTexGeniv; - table.m_glGetTexImage = glGetTexImage; - table.m_glGetTexLevelParameterfv = glGetTexLevelParameterfv; - table.m_glGetTexLevelParameteriv = glGetTexLevelParameteriv; - table.m_glGetTexParameterfv = glGetTexParameterfv; - table.m_glGetTexParameteriv = glGetTexParameteriv; - table.m_glHint = glHint; - table.m_glIndexMask = glIndexMask; - table.m_glIndexPointer = glIndexPointer; - table.m_glIndexd = glIndexd; - table.m_glIndexdv = glIndexdv; - table.m_glIndexf = glIndexf; - table.m_glIndexfv = glIndexfv; - table.m_glIndexi = glIndexi; - table.m_glIndexiv = glIndexiv; - table.m_glIndexs = glIndexs; - table.m_glIndexsv = glIndexsv; - table.m_glIndexub = glIndexub; - table.m_glIndexubv = glIndexubv; - table.m_glInitNames = glInitNames; - table.m_glInterleavedArrays = glInterleavedArrays; - table.m_glIsEnabled = glIsEnabled; - table.m_glIsList = glIsList; - table.m_glIsTexture = glIsTexture; - table.m_glLightModelf = glLightModelf; - table.m_glLightModelfv = glLightModelfv; - table.m_glLightModeli = glLightModeli; - table.m_glLightModeliv = glLightModeliv; - table.m_glLightf = glLightf; - table.m_glLightfv = glLightfv; - table.m_glLighti = glLighti; - table.m_glLightiv = glLightiv; - table.m_glLineStipple = glLineStipple; - table.m_glLineWidth = glLineWidth; - table.m_glListBase = glListBase; - table.m_glLoadIdentity = glLoadIdentity; - table.m_glLoadMatrixd = glLoadMatrixd; - table.m_glLoadMatrixf = glLoadMatrixf; - table.m_glLoadName = glLoadName; - table.m_glLogicOp = glLogicOp; - table.m_glMap1d = glMap1d; - table.m_glMap1f = glMap1f; - table.m_glMap2d = glMap2d; - table.m_glMap2f = glMap2f; - table.m_glMapGrid1d = glMapGrid1d; - table.m_glMapGrid1f = glMapGrid1f; - table.m_glMapGrid2d = glMapGrid2d; - table.m_glMapGrid2f = glMapGrid2f; - table.m_glMaterialf = glMaterialf; - table.m_glMaterialfv = glMaterialfv; - table.m_glMateriali = glMateriali; - table.m_glMaterialiv = glMaterialiv; - table.m_glMatrixMode = glMatrixMode; - table.m_glMultMatrixd = glMultMatrixd; - table.m_glMultMatrixf = glMultMatrixf; - table.m_glNewList = glNewList; - table.m_glNormal3b = glNormal3b; - table.m_glNormal3bv = glNormal3bv; - table.m_glNormal3d = glNormal3d; - table.m_glNormal3dv = glNormal3dv; - table.m_glNormal3f = glNormal3f; - table.m_glNormal3fv = glNormal3fv; - table.m_glNormal3i = glNormal3i; - table.m_glNormal3iv = glNormal3iv; - table.m_glNormal3s = glNormal3s; - table.m_glNormal3sv = glNormal3sv; - table.m_glNormalPointer = glNormalPointer; - table.m_glOrtho = glOrtho; - table.m_glPassThrough = glPassThrough; - table.m_glPixelMapfv = glPixelMapfv; - table.m_glPixelMapuiv = glPixelMapuiv; - table.m_glPixelMapusv = glPixelMapusv; - table.m_glPixelStoref = glPixelStoref; - table.m_glPixelStorei = glPixelStorei; - table.m_glPixelTransferf = glPixelTransferf; - table.m_glPixelTransferi = glPixelTransferi; - table.m_glPixelZoom = glPixelZoom; - table.m_glPointSize = glPointSize; - table.m_glPolygonMode = glPolygonMode; - table.m_glPolygonOffset = glPolygonOffset; - table.m_glPolygonStipple = glPolygonStipple; - table.m_glPopAttrib = glPopAttrib; - table.m_glPopClientAttrib = glPopClientAttrib; - table.m_glPopMatrix = glPopMatrix; - table.m_glPopName = glPopName; - table.m_glPrioritizeTextures = glPrioritizeTextures; - table.m_glPushAttrib = glPushAttrib; - table.m_glPushClientAttrib = glPushClientAttrib; - table.m_glPushMatrix = glPushMatrix; - table.m_glPushName = glPushName; - table.m_glRasterPos2d = glRasterPos2d; - table.m_glRasterPos2dv = glRasterPos2dv; - table.m_glRasterPos2f = glRasterPos2f; - table.m_glRasterPos2fv = glRasterPos2fv; - table.m_glRasterPos2i = glRasterPos2i; - table.m_glRasterPos2iv = glRasterPos2iv; - table.m_glRasterPos2s = glRasterPos2s; - table.m_glRasterPos2sv = glRasterPos2sv; - table.m_glRasterPos3d = glRasterPos3d; - table.m_glRasterPos3dv = glRasterPos3dv; - table.m_glRasterPos3f = glRasterPos3f; - table.m_glRasterPos3fv = glRasterPos3fv; - table.m_glRasterPos3i = glRasterPos3i; - table.m_glRasterPos3iv = glRasterPos3iv; - table.m_glRasterPos3s = glRasterPos3s; - table.m_glRasterPos3sv = glRasterPos3sv; - table.m_glRasterPos4d = glRasterPos4d; - table.m_glRasterPos4dv = glRasterPos4dv; - table.m_glRasterPos4f = glRasterPos4f; - table.m_glRasterPos4fv = glRasterPos4fv; - table.m_glRasterPos4i = glRasterPos4i; - table.m_glRasterPos4iv = glRasterPos4iv; - table.m_glRasterPos4s = glRasterPos4s; - table.m_glRasterPos4sv = glRasterPos4sv; - table.m_glReadBuffer = glReadBuffer; - table.m_glReadPixels = glReadPixels; - table.m_glRectd = glRectd; - table.m_glRectdv = glRectdv; - table.m_glRectf = glRectf; - table.m_glRectfv = glRectfv; - table.m_glRecti = glRecti; - table.m_glRectiv = glRectiv; - table.m_glRects = glRects; - table.m_glRectsv = glRectsv; - table.m_glRenderMode = glRenderMode; - table.m_glRotated = glRotated; - table.m_glRotatef = glRotatef; - table.m_glScaled = glScaled; - table.m_glScalef = glScalef; - table.m_glScissor = glScissor; - table.m_glSelectBuffer = glSelectBuffer; - table.m_glShadeModel = glShadeModel; - table.m_glStencilFunc = glStencilFunc; - table.m_glStencilMask = glStencilMask; - table.m_glStencilOp = glStencilOp; - table.m_glTexCoord1d = glTexCoord1d; - table.m_glTexCoord1dv = glTexCoord1dv; - table.m_glTexCoord1f = glTexCoord1f; - table.m_glTexCoord1fv = glTexCoord1fv; - table.m_glTexCoord1i = glTexCoord1i; - table.m_glTexCoord1iv = glTexCoord1iv; - table.m_glTexCoord1s = glTexCoord1s; - table.m_glTexCoord1sv = glTexCoord1sv; - table.m_glTexCoord2d = glTexCoord2d; - table.m_glTexCoord2dv = glTexCoord2dv; - table.m_glTexCoord2f = glTexCoord2f; - table.m_glTexCoord2fv = glTexCoord2fv; - table.m_glTexCoord2i = glTexCoord2i; - table.m_glTexCoord2iv = glTexCoord2iv; - table.m_glTexCoord2s = glTexCoord2s; - table.m_glTexCoord2sv = glTexCoord2sv; - table.m_glTexCoord3d = glTexCoord3d; - table.m_glTexCoord3dv = glTexCoord3dv; - table.m_glTexCoord3f = glTexCoord3f; - table.m_glTexCoord3fv = glTexCoord3fv; - table.m_glTexCoord3i = glTexCoord3i; - table.m_glTexCoord3iv = glTexCoord3iv; - table.m_glTexCoord3s = glTexCoord3s; - table.m_glTexCoord3sv = glTexCoord3sv; - table.m_glTexCoord4d = glTexCoord4d; - table.m_glTexCoord4dv = glTexCoord4dv; - table.m_glTexCoord4f = glTexCoord4f; - table.m_glTexCoord4fv = glTexCoord4fv; - table.m_glTexCoord4i = glTexCoord4i; - table.m_glTexCoord4iv = glTexCoord4iv; - table.m_glTexCoord4s = glTexCoord4s; - table.m_glTexCoord4sv = glTexCoord4sv; - table.m_glTexCoordPointer = glTexCoordPointer; - table.m_glTexEnvf = glTexEnvf; - table.m_glTexEnvfv = glTexEnvfv; - table.m_glTexEnvi = glTexEnvi; - table.m_glTexEnviv = glTexEnviv; - table.m_glTexGend = glTexGend; - table.m_glTexGendv = glTexGendv; - table.m_glTexGenf = glTexGenf; - table.m_glTexGenfv = glTexGenfv; - table.m_glTexGeni = glTexGeni; - table.m_glTexGeniv = glTexGeniv; - table.m_glTexImage1D = glTexImage1D; - table.m_glTexImage2D = glTexImage2D; - table.m_glTexParameterf = glTexParameterf; - table.m_glTexParameterfv = glTexParameterfv; - table.m_glTexParameteri = glTexParameteri; - table.m_glTexParameteriv = glTexParameteriv; - table.m_glTexSubImage1D = glTexSubImage1D; - table.m_glTexSubImage2D = glTexSubImage2D; - table.m_glTranslated = glTranslated; - table.m_glTranslatef = glTranslatef; - table.m_glVertex2d = glVertex2d; - table.m_glVertex2dv = glVertex2dv; - table.m_glVertex2f = glVertex2f; - table.m_glVertex2fv = glVertex2fv; - table.m_glVertex2i = glVertex2i; - table.m_glVertex2iv = glVertex2iv; - table.m_glVertex2s = glVertex2s; - table.m_glVertex2sv = glVertex2sv; - table.m_glVertex3d = glVertex3d; - table.m_glVertex3dv = glVertex3dv; - table.m_glVertex3f = glVertex3f; - table.m_glVertex3fv = glVertex3fv; - table.m_glVertex3i = glVertex3i; - table.m_glVertex3iv = glVertex3iv; - table.m_glVertex3s = glVertex3s; - table.m_glVertex3sv = glVertex3sv; - table.m_glVertex4d = glVertex4d; - table.m_glVertex4dv = glVertex4dv; - table.m_glVertex4f = glVertex4f; - table.m_glVertex4fv = glVertex4fv; - table.m_glVertex4i = glVertex4i; - table.m_glVertex4iv = glVertex4iv; - table.m_glVertex4s = glVertex4s; - table.m_glVertex4sv = glVertex4sv; - table.m_glVertexPointer = glVertexPointer; - table.m_glViewport = glViewport; - - if(QGL_ExtensionSupported("GL_ARB_multitexture")) - { - table.support_ARB_multitexture = - QGL_constructExtensionFunc(table.m_glActiveTextureARB, "glActiveTextureARB") - && QGL_constructExtensionFunc(table.m_glClientActiveTextureARB, "glClientActiveTextureARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1dARB, "glMultiTexCoord1dARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1dvARB, "glMultiTexCoord1dvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1fARB, "glMultiTexCoord1fARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1fvARB, "glMultiTexCoord1fvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1iARB, "glMultiTexCoord1iARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1ivARB, "glMultiTexCoord1ivARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1sARB, "glMultiTexCoord1sARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1svARB, "glMultiTexCoord1svARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2dARB, "glMultiTexCoord2dARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2dvARB, "glMultiTexCoord2dvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2fARB, "glMultiTexCoord2fARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2fvARB, "glMultiTexCoord2fvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2iARB, "glMultiTexCoord2iARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2ivARB, "glMultiTexCoord2ivARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2sARB, "glMultiTexCoord2sARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2svARB, "glMultiTexCoord2svARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3dARB, "glMultiTexCoord3dARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3dvARB, "glMultiTexCoord3dvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3fARB, "glMultiTexCoord3fARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3fvARB, "glMultiTexCoord3fvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3iARB, "glMultiTexCoord3iARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3ivARB, "glMultiTexCoord3ivARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3sARB, "glMultiTexCoord3sARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3svARB, "glMultiTexCoord3svARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4dARB, "glMultiTexCoord4dARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4dvARB, "glMultiTexCoord4dvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4fARB, "glMultiTexCoord4fARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4fvARB, "glMultiTexCoord4fvARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4iARB, "glMultiTexCoord4iARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4ivARB, "glMultiTexCoord4ivARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4sARB, "glMultiTexCoord4sARB") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4svARB, "glMultiTexCoord4svARB"); - - if(!table.support_ARB_multitexture) - { - extension_not_implemented("GL_ARB_multitexture"); - } - } - else - { - table.support_ARB_multitexture = false; - } - - if(QGL_ExtensionSupported("GL_ARB_texture_compression")) - { - table.support_ARB_texture_compression = - QGL_constructExtensionFunc(table.m_glCompressedTexImage3DARB, "glCompressedTexImage3DARB") - && QGL_constructExtensionFunc(table.m_glCompressedTexImage2DARB, "glCompressedTexImage2DARB") - && QGL_constructExtensionFunc(table.m_glCompressedTexImage1DARB, "glCompressedTexImage1DARB") - && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage3DARB, "glCompressedTexSubImage3DARB") - && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage2DARB, "glCompressedTexSubImage2DARB") - && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage1DARB, "glCompressedTexSubImage1DARB") - && QGL_constructExtensionFunc(table.m_glGetCompressedTexImageARB, "glGetCompressedTexImageARB"); - - if(!table.support_ARB_texture_compression) - { - extension_not_implemented("GL_ARB_texture_compression"); - } - } - else - { - table.support_ARB_texture_compression = false; - } - - table.support_EXT_texture_compression_s3tc = QGL_ExtensionSupported("GL_EXT_texture_compression_s3tc"); - - // GL 1.2 - if(table.major_version > 1 || table.minor_version >= 2) - { - table.support_GL_1_2 = - QGL_constructExtensionFunc(table.m_glCopyTexSubImage3D, "glCopyTexSubImage3D") - && QGL_constructExtensionFunc(table.m_glDrawRangeElements, "glDrawRangeElements") - && QGL_constructExtensionFunc(table.m_glTexImage3D, "glTexImage3D") - && QGL_constructExtensionFunc(table.m_glTexSubImage3D, "glTexSubImage3D"); - - if(!table.support_GL_1_2) - { - extension_not_implemented("GL_VERSION_1_2"); - } - } - else - { - table.support_GL_1_2 = false; - } - - // GL 1.3 - if(table.major_version > 1 || table.minor_version >= 3) - { - table.support_GL_1_3 = - QGL_constructExtensionFunc(table.m_glActiveTexture, "glActiveTexture") - && QGL_constructExtensionFunc(table.m_glClientActiveTexture, "glClientActiveTexture") - && QGL_constructExtensionFunc(table.m_glCompressedTexImage1D, "glCompressedTexImage1D") - && QGL_constructExtensionFunc(table.m_glCompressedTexImage2D, "glCompressedTexImage2D") - && QGL_constructExtensionFunc(table.m_glCompressedTexImage3D, "glCompressedTexImage3D") - && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage1D, "glCompressedTexSubImage1D") - && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage2D, "glCompressedTexSubImage2D") - && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage3D, "glCompressedTexSubImage3D") - && QGL_constructExtensionFunc(table.m_glGetCompressedTexImage, "glGetCompressedTexImage") - && QGL_constructExtensionFunc(table.m_glLoadTransposeMatrixd, "glLoadTransposeMatrixd") - && QGL_constructExtensionFunc(table.m_glLoadTransposeMatrixf, "glLoadTransposeMatrixf") - && QGL_constructExtensionFunc(table.m_glMultTransposeMatrixd, "glMultTransposeMatrixd") - && QGL_constructExtensionFunc(table.m_glMultTransposeMatrixf, "glMultTransposeMatrixf") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1d, "glMultiTexCoord1d") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1dv, "glMultiTexCoord1dv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1f, "glMultiTexCoord1f") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1fv, "glMultiTexCoord1fv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1i, "glMultiTexCoord1i") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1iv, "glMultiTexCoord1iv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1s, "glMultiTexCoord1s") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord1sv, "glMultiTexCoord1sv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2d, "glMultiTexCoord2d") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2dv, "glMultiTexCoord2dv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2f, "glMultiTexCoord2f") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2fv, "glMultiTexCoord2fv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2i, "glMultiTexCoord2i") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2iv, "glMultiTexCoord2iv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2s, "glMultiTexCoord2s") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord2sv, "glMultiTexCoord2sv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3d, "glMultiTexCoord3d") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3dv, "glMultiTexCoord3dv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3f, "glMultiTexCoord3f") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3fv, "glMultiTexCoord3fv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3i, "glMultiTexCoord3i") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3iv, "glMultiTexCoord3iv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3s, "glMultiTexCoord3s") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord3sv, "glMultiTexCoord3sv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4d, "glMultiTexCoord4d") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4dv, "glMultiTexCoord4dv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4f, "glMultiTexCoord4f") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4fv, "glMultiTexCoord4fv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4i, "glMultiTexCoord4i") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4iv, "glMultiTexCoord4iv") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4s, "glMultiTexCoord4s") - && QGL_constructExtensionFunc(table.m_glMultiTexCoord4sv, "glMultiTexCoord4sv") - && QGL_constructExtensionFunc(table.m_glSampleCoverage, "glSampleCoverage"); - - if(!table.support_GL_1_3) - { - extension_not_implemented("GL_VERSION_1_3"); - } - } - else - { - table.support_GL_1_3 = false; - } - - // GL 1.4 - if(table.major_version > 1 || table.minor_version >= 4) - { - table.support_GL_1_4 = - QGL_constructExtensionFunc(table.m_glBlendColor, "glBlendColor") - && QGL_constructExtensionFunc(table.m_glBlendEquation, "glBlendEquation") - && QGL_constructExtensionFunc(table.m_glBlendFuncSeparate, "glBlendFuncSeparate") - && QGL_constructExtensionFunc(table.m_glFogCoordPointer, "glFogCoordPointer") - && QGL_constructExtensionFunc(table.m_glFogCoordd, "glFogCoordd") - && QGL_constructExtensionFunc(table.m_glFogCoorddv, "glFogCoorddv") - && QGL_constructExtensionFunc(table.m_glFogCoordf, "glFogCoordf") - && QGL_constructExtensionFunc(table.m_glFogCoordfv, "glFogCoordfv") - && QGL_constructExtensionFunc(table.m_glMultiDrawArrays, "glMultiDrawArrays") - && QGL_constructExtensionFunc(table.m_glMultiDrawElements, "glMultiDrawElements") - && QGL_constructExtensionFunc(table.m_glPointParameterf, "glPointParameterf") - && QGL_constructExtensionFunc(table.m_glPointParameterfv, "glPointParameterfv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3b, "glSecondaryColor3b") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3bv, "glSecondaryColor3bv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3d, "glSecondaryColor3d") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3dv, "glSecondaryColor3dv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3f, "glSecondaryColor3f") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3fv, "glSecondaryColor3fv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3i, "glSecondaryColor3i") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3iv, "glSecondaryColor3iv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3s, "glSecondaryColor3s") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3sv, "glSecondaryColor3sv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3ub, "glSecondaryColor3ub") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3ubv, "glSecondaryColor3ubv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3ui, "glSecondaryColor3ui") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3uiv, "glSecondaryColor3uiv") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3us, "glSecondaryColor3us") - && QGL_constructExtensionFunc(table.m_glSecondaryColor3usv, "glSecondaryColor3usv") - && QGL_constructExtensionFunc(table.m_glSecondaryColorPointer, "glSecondaryColorPointer") - && QGL_constructExtensionFunc(table.m_glWindowPos2d, "glWindowPos2d") - && QGL_constructExtensionFunc(table.m_glWindowPos2dv, "glWindowPos2dv") - && QGL_constructExtensionFunc(table.m_glWindowPos2f, "glWindowPos2f") - && QGL_constructExtensionFunc(table.m_glWindowPos2fv, "glWindowPos2fv") - && QGL_constructExtensionFunc(table.m_glWindowPos2i, "glWindowPos2i") - && QGL_constructExtensionFunc(table.m_glWindowPos2iv, "glWindowPos2iv") - && QGL_constructExtensionFunc(table.m_glWindowPos2s, "glWindowPos2s") - && QGL_constructExtensionFunc(table.m_glWindowPos2sv, "glWindowPos2sv") - && QGL_constructExtensionFunc(table.m_glWindowPos3d, "glWindowPos3d") - && QGL_constructExtensionFunc(table.m_glWindowPos3dv, "glWindowPos3dv") - && QGL_constructExtensionFunc(table.m_glWindowPos3f, "glWindowPos3f") - && QGL_constructExtensionFunc(table.m_glWindowPos3fv, "glWindowPos3fv") - && QGL_constructExtensionFunc(table.m_glWindowPos3i, "glWindowPos3i") - && QGL_constructExtensionFunc(table.m_glWindowPos3iv, "glWindowPos3iv") - && QGL_constructExtensionFunc(table.m_glWindowPos3s, "glWindowPos3s") - && QGL_constructExtensionFunc(table.m_glWindowPos3sv, "glWindowPos3sv"); - - if(!table.support_GL_1_4) - { - extension_not_implemented("GL_VERSION_1_4"); - } - } - else - { - table.support_GL_1_4 = false; - } - - // GL 1.5 - if(table.major_version > 1 || table.minor_version >= 5) - { - table.support_GL_1_5 = - QGL_constructExtensionFunc(table.m_glBeginQuery, "glBeginQuery") - && QGL_constructExtensionFunc(table.m_glBindBuffer, "glBindBuffer") - && QGL_constructExtensionFunc(table.m_glBufferData, "glBufferData") - && QGL_constructExtensionFunc(table.m_glBufferSubData, "glBufferSubData") - && QGL_constructExtensionFunc(table.m_glDeleteBuffers, "glDeleteBuffers") - && QGL_constructExtensionFunc(table.m_glDeleteQueries, "glDeleteQueries") - && QGL_constructExtensionFunc(table.m_glEndQuery, "glEndQuery") - && QGL_constructExtensionFunc(table.m_glGenBuffers, "glGenBuffers") - && QGL_constructExtensionFunc(table.m_glGenQueries, "glGenQueries") - && QGL_constructExtensionFunc(table.m_glGetBufferParameteriv, "glGetBufferParameteriv") - && QGL_constructExtensionFunc(table.m_glGetBufferPointerv, "glGetBufferPointerv") - && QGL_constructExtensionFunc(table.m_glGetBufferSubData, "glGetBufferSubData") - && QGL_constructExtensionFunc(table.m_glGetQueryObjectiv, "glGetQueryObjectiv") - && QGL_constructExtensionFunc(table.m_glGetQueryObjectuiv, "glGetQueryObjectuiv") - && QGL_constructExtensionFunc(table.m_glGetQueryiv, "glGetQueryiv") - && QGL_constructExtensionFunc(table.m_glIsBuffer, "glIsBuffer") - && QGL_constructExtensionFunc(table.m_glIsQuery, "glIsQuery") - && QGL_constructExtensionFunc(table.m_glMapBuffer, "glMapBuffer") - && QGL_constructExtensionFunc(table.m_glUnmapBuffer, "glUnmapBuffer"); - - if(!table.support_GL_1_5) - { - extension_not_implemented("GL_VERSION_1_5"); - } - } - else - { - table.support_GL_1_5 = false; - } - - - if(QGL_ExtensionSupported("GL_ARB_vertex_program")) - { - table.support_ARB_vertex_program = - QGL_constructExtensionFunc(table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB") - && QGL_constructExtensionFunc(table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB") - && QGL_constructExtensionFunc(table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB") - && QGL_constructExtensionFunc(table.m_glProgramStringARB, "glProgramStringARB") - && QGL_constructExtensionFunc(table.m_glBindProgramARB, "glBindProgramARB") - && QGL_constructExtensionFunc(table.m_glDeleteProgramsARB, "glDeleteProgramsARB") - && QGL_constructExtensionFunc(table.m_glGenProgramsARB, "glGenProgramsARB") - && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4dARB, "glProgramEnvParameter4dARB") - && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4dvARB, "glProgramEnvParameter4dvARB") - && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4fARB, "glProgramEnvParameter4fARB") - && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4fvARB, "glProgramEnvParameter4fvARB") - && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4dARB, "glProgramLocalParameter4dARB") - && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4dvARB, "glProgramLocalParameter4dvARB") - && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4fARB, "glProgramLocalParameter4fARB") - && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4fvARB, "glProgramLocalParameter4fvARB") - && QGL_constructExtensionFunc(table.m_glGetProgramEnvParameterdvARB, "glGetProgramEnvParameterdvARB") - && QGL_constructExtensionFunc(table.m_glGetProgramEnvParameterfvARB, "glGetProgramEnvParameterfvARB") - && QGL_constructExtensionFunc(table.m_glGetProgramLocalParameterdvARB, "glGetProgramLocalParameterdvARB") - && QGL_constructExtensionFunc(table.m_glGetProgramLocalParameterfvARB, "glGetProgramLocalParameterfvARB") - && QGL_constructExtensionFunc(table.m_glGetProgramivARB, "glGetProgramivARB") - && QGL_constructExtensionFunc(table.m_glGetProgramStringARB, "glGetProgramStringARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB") - && QGL_constructExtensionFunc(table.m_glIsProgramARB, "glIsProgramARB"); - - if(!table.support_ARB_vertex_program) - { - extension_not_implemented("GL_ARB_vertex_program"); - } - } - else - { - table.support_ARB_vertex_program = false; - } - - - table.support_ARB_fragment_program = QGL_ExtensionSupported("GL_ARB_fragment_program"); - - if(QGL_ExtensionSupported("GL_ARB_shader_objects")) - { - table.support_ARB_shader_objects = - QGL_constructExtensionFunc(table.m_glDeleteObjectARB, "glDeleteObjectARB") - && QGL_constructExtensionFunc(table.m_glGetHandleARB, "glGetHandleARB") - && QGL_constructExtensionFunc(table.m_glDetachObjectARB, "glDetachObjectARB") - && QGL_constructExtensionFunc(table.m_glCreateShaderObjectARB, "glCreateShaderObjectARB") - && QGL_constructExtensionFunc(table.m_glShaderSourceARB, "glShaderSourceARB") - && QGL_constructExtensionFunc(table.m_glCompileShaderARB, "glCompileShaderARB") - && QGL_constructExtensionFunc(table.m_glCreateProgramObjectARB, "glCreateProgramObjectARB") - && QGL_constructExtensionFunc(table.m_glAttachObjectARB, "glAttachObjectARB") - && QGL_constructExtensionFunc(table.m_glLinkProgramARB, "glLinkProgramARB") - && QGL_constructExtensionFunc(table.m_glUseProgramObjectARB, "glUseProgramObjectARB") - && QGL_constructExtensionFunc(table.m_glValidateProgramARB, "glValidateProgramARB") - && QGL_constructExtensionFunc(table.m_glUniform1fARB, "glUniform1fARB") - && QGL_constructExtensionFunc(table.m_glUniform2fARB, "glUniform2fARB") - && QGL_constructExtensionFunc(table.m_glUniform3fARB, "glUniform3fARB") - && QGL_constructExtensionFunc(table.m_glUniform4fARB, "glUniform4fARB") - && QGL_constructExtensionFunc(table.m_glUniform1iARB, "glUniform1iARB") - && QGL_constructExtensionFunc(table.m_glUniform2iARB, "glUniform2iARB") - && QGL_constructExtensionFunc(table.m_glUniform3iARB, "glUniform3iARB") - && QGL_constructExtensionFunc(table.m_glUniform4iARB, "glUniform4iARB") - && QGL_constructExtensionFunc(table.m_glUniform1fvARB, "glUniform1fvARB") - && QGL_constructExtensionFunc(table.m_glUniform2fvARB, "glUniform2fvARB") - && QGL_constructExtensionFunc(table.m_glUniform3fvARB, "glUniform3fvARB") - && QGL_constructExtensionFunc(table.m_glUniform4fvARB, "glUniform4fvARB") - && QGL_constructExtensionFunc(table.m_glUniform1ivARB, "glUniform1ivARB") - && QGL_constructExtensionFunc(table.m_glUniform2ivARB, "glUniform2ivARB") - && QGL_constructExtensionFunc(table.m_glUniform3ivARB, "glUniform3ivARB") - && QGL_constructExtensionFunc(table.m_glUniform4ivARB, "glUniform4ivARB") - && QGL_constructExtensionFunc(table.m_glUniformMatrix2fvARB, "glUniformMatrix2fvARB") - && QGL_constructExtensionFunc(table.m_glUniformMatrix3fvARB, "glUniformMatrix3fvARB") - && QGL_constructExtensionFunc(table.m_glUniformMatrix4fvARB, "glUniformMatrix4fvARB") - && QGL_constructExtensionFunc(table.m_glGetObjectParameterfvARB, "glGetObjectParameterfvARB") - && QGL_constructExtensionFunc(table.m_glGetObjectParameterivARB, "glGetObjectParameterivARB") - && QGL_constructExtensionFunc(table.m_glGetInfoLogARB, "glGetInfoLogARB") - && QGL_constructExtensionFunc(table.m_glGetAttachedObjectsARB, "glGetAttachedObjectsARB") - && QGL_constructExtensionFunc(table.m_glGetUniformLocationARB, "glGetUniformLocationARB") - && QGL_constructExtensionFunc(table.m_glGetActiveUniformARB, "glGetActiveUniformARB") - && QGL_constructExtensionFunc(table.m_glGetUniformfvARB, "glGetUniformfvARB") - && QGL_constructExtensionFunc(table.m_glGetUniformivARB, "glGetUniformivARB") - && QGL_constructExtensionFunc(table.m_glGetShaderSourceARB, "glGetShaderSourceARB"); - - if(!table.support_ARB_shader_objects) - { - extension_not_implemented("GL_ARB_shader_objects"); - } - } - else - { - table.support_ARB_shader_objects = false; - } - - if(QGL_ExtensionSupported("GL_ARB_vertex_shader")) - { - table.support_ARB_vertex_shader = - QGL_constructExtensionFunc(table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB") - && QGL_constructExtensionFunc(table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB") - && QGL_constructExtensionFunc(table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB") - && QGL_constructExtensionFunc(table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB") - && QGL_constructExtensionFunc(table.m_glBindAttribLocationARB, "glBindAttribLocationARB") - && QGL_constructExtensionFunc(table.m_glGetActiveAttribARB, "glGetActiveAttribARB") - && QGL_constructExtensionFunc(table.m_glGetAttribLocationARB, "glGetAttribLocationARB"); - - if(!table.support_ARB_vertex_shader) - { - extension_not_implemented("GL_ARB_vertex_shader"); - } - } - else - { - table.support_ARB_vertex_shader = false; - } - - if(QGL_ExtensionSupported("GL_NV_vertex_program2")) - { - table.support_NV_vertex_program2 = - QGL_constructExtensionFunc(table.m_glAreProgramsResidentNV, "glAreProgramsResidentNV") - && QGL_constructExtensionFunc(table.m_glBindProgramNV, "glBindProgramNV") - && QGL_constructExtensionFunc(table.m_glDeleteProgramsNV, "glDeleteProgramsNV") - && QGL_constructExtensionFunc(table.m_glExecuteProgramNV, "glExecuteProgramNV") - && QGL_constructExtensionFunc(table.m_glGenProgramsNV, "glGenProgramsNV") - && QGL_constructExtensionFunc(table.m_glGetProgramParameterdvNV, "glGetProgramParameterdvNV") - && QGL_constructExtensionFunc(table.m_glGetProgramParameterfvNV, "glGetProgramParameterfvNV") - && QGL_constructExtensionFunc(table.m_glGetProgramivNV, "glGetProgramivNV") - && QGL_constructExtensionFunc(table.m_glGetProgramStringNV, "glGetProgramStringNV") - && QGL_constructExtensionFunc(table.m_glGetTrackMatrixivNV, "glGetTrackMatrixivNV") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribdvNV, "glGetVertexAttribdvNV") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribfvNV, "glGetVertexAttribfvNV") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribivNV, "glGetVertexAttribivNV") - && QGL_constructExtensionFunc(table.m_glGetVertexAttribPointervNV, "glGetVertexAttribPointervNV") - && QGL_constructExtensionFunc(table.m_glIsProgramNV, "glIsProgramNV") - && QGL_constructExtensionFunc(table.m_glLoadProgramNV, "glLoadProgramNV") - && QGL_constructExtensionFunc(table.m_glProgramParameter4fNV, "glProgramParameter4fNV") - && QGL_constructExtensionFunc(table.m_glProgramParameter4fvNV, "glProgramParameter4fvNV") - && QGL_constructExtensionFunc(table.m_glProgramParameters4fvNV, "glProgramParameters4fvNV") - && QGL_constructExtensionFunc(table.m_glRequestResidentProgramsNV, "glRequestResidentProgramsNV") - && QGL_constructExtensionFunc(table.m_glTrackMatrixNV, "glTrackMatrixNV") - && QGL_constructExtensionFunc(table.m_glVertexAttribPointerNV, "glVertexAttribPointerNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1fNV, "glVertexAttrib1fNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib1fvNV, "glVertexAttrib1fvNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2fNV, "glVertexAttrib2fNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib2fvNV, "glVertexAttrib2fvNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3fNV, "glVertexAttrib3fNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib3fvNV, "glVertexAttrib3fvNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4fNV, "glVertexAttrib4fNV") - && QGL_constructExtensionFunc(table.m_glVertexAttrib4fvNV, "glVertexAttrib4fvNV") - && QGL_constructExtensionFunc(table.m_glVertexAttribs1fvNV, "glVertexAttribs1fvNV") - && QGL_constructExtensionFunc(table.m_glVertexAttribs2fvNV, "glVertexAttribs2fvNV") - && QGL_constructExtensionFunc(table.m_glVertexAttribs3fvNV, "glVertexAttribs3fvNV") - && QGL_constructExtensionFunc(table.m_glVertexAttribs4fvNV, "glVertexAttribs4fvNV"); - - if(!table.support_NV_vertex_program2) - { - extension_not_implemented("GL_NV_vertex_program2"); - } - } - else - { - table.support_NV_vertex_program2 = false; - QGL_invalidateExtensionFunc(table.m_glAreProgramsResidentNV); - QGL_invalidateExtensionFunc(table.m_glBindProgramNV); - QGL_invalidateExtensionFunc(table.m_glDeleteProgramsNV); - QGL_invalidateExtensionFunc(table.m_glExecuteProgramNV); - QGL_invalidateExtensionFunc(table.m_glGenProgramsNV); - QGL_invalidateExtensionFunc(table.m_glGetProgramParameterdvNV); - QGL_invalidateExtensionFunc(table.m_glGetProgramParameterfvNV); - QGL_invalidateExtensionFunc(table.m_glGetProgramivNV); - QGL_invalidateExtensionFunc(table.m_glGetProgramStringNV); - QGL_invalidateExtensionFunc(table.m_glGetTrackMatrixivNV); - QGL_invalidateExtensionFunc(table.m_glGetVertexAttribdvNV); - QGL_invalidateExtensionFunc(table.m_glGetVertexAttribfvNV); - QGL_invalidateExtensionFunc(table.m_glGetVertexAttribivNV); - QGL_invalidateExtensionFunc(table.m_glGetVertexAttribPointervNV); - QGL_invalidateExtensionFunc(table.m_glIsProgramNV); - QGL_invalidateExtensionFunc(table.m_glLoadProgramNV); - QGL_invalidateExtensionFunc(table.m_glProgramParameter4fNV); - QGL_invalidateExtensionFunc(table.m_glProgramParameter4fvNV); - QGL_invalidateExtensionFunc(table.m_glProgramParameters4fvNV); - QGL_invalidateExtensionFunc(table.m_glRequestResidentProgramsNV); - QGL_invalidateExtensionFunc(table.m_glTrackMatrixNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttribPointerNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib1fNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib1fvNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib2fNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib2fvNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib3fNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib3fvNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib4fNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttrib4fvNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttribs1fvNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttribs2fvNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttribs3fvNV); - QGL_invalidateExtensionFunc(table.m_glVertexAttribs4fvNV); - } - - if(QGL_ExtensionSupported("GL_NV_fragment_program")) - { - table.support_NV_fragment_program = - QGL_constructExtensionFunc(table.m_glProgramNamedParameter4fNV, "glProgramNamedParameter4fNV") - && QGL_constructExtensionFunc(table.m_glProgramNamedParameter4fvNV, "glProgramNamedParameter4fvNV") - && QGL_constructExtensionFunc(table.m_glGetProgramNamedParameterfvNV, "glGetProgramNamedParameterfvNV"); - - if(!table.support_NV_fragment_program) - { - extension_not_implemented("GL_NV_fragment_program"); - } - } - else - { - table.support_NV_fragment_program = false; - } - - table.support_ARB_fragment_shader = QGL_ExtensionSupported("GL_ARB_fragment_shader"); - table.support_ARB_shading_language_100 = QGL_ExtensionSupported("GL_ARB_shading_language_100"); - - if(QGL_ExtensionSupported("GL_EXT_texture_filter_anisotropic")) - { - glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &g_maxTextureAnisotropy); - globalOutputStream() << "Anisotropic filtering possible (max " << g_maxTextureAnisotropy << "x)\n"; - } - else - { - globalOutputStream() << "No Anisotropic filtering available\n"; - g_maxTextureAnisotropy = 0; - } -} - -void QGL_sharedContextDestroyed(OpenGLBinding& table) -{ - QGL_clear(table); -} - - -void QGL_assertNoErrors(const char *file, int line) -{ - GLenum error = GlobalOpenGL().m_glGetError(); - while (error != GL_NO_ERROR) - { - const char* errorString = reinterpret_cast(qgluErrorString(error)); - if (error == GL_OUT_OF_MEMORY) - { - ERROR_MESSAGE("OpenGL out of memory error at " << file << ":" << line << ": " << errorString); - } - else - { - ERROR_MESSAGE("OpenGL error at " << file << ":" << line << ": " << errorString); - } - error = GlobalOpenGL().m_glGetError(); - } -} - - -class QglAPI -{ - OpenGLBinding m_qgl; -public: - typedef OpenGLBinding Type; - STRING_CONSTANT(Name, "*"); - - QglAPI() - { - QGL_Init(m_qgl); - - m_qgl.assertNoErrors = &QGL_assertNoErrors; - } - ~QglAPI() - { - QGL_Shutdown(m_qgl); - } - OpenGLBinding* getTable() - { - return &m_qgl; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule QglModule; -typedef Static StaticQglModule; -StaticRegisterModule staticRegisterQgl(StaticQglModule::instance()); diff --git a/misc/mediasource/extra/netradiant-src/radiant/qgl.h b/misc/mediasource/extra/netradiant-src/radiant/qgl.h deleted file mode 100644 index 55d1570e..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/qgl.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_QGL_H) -#define INCLUDED_QGL_H - -struct OpenGLBinding; -void QGL_sharedContextCreated(OpenGLBinding& table); -void QGL_sharedContextDestroyed(OpenGLBinding& table); - -bool QGL_ExtensionSupported(const char* extension); - -float QGL_maxTextureAnisotropy(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/radiant.ico b/misc/mediasource/extra/netradiant-src/radiant/radiant.ico deleted file mode 100644 index 45e8258e..00000000 Binary files a/misc/mediasource/extra/netradiant-src/radiant/radiant.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/radiant/radiant.rc b/misc/mediasource/extra/netradiant-src/radiant/radiant.rc deleted file mode 100644 index 51087c04..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/radiant.rc +++ /dev/null @@ -1,72 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -//#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -//#ifdef _WIN32 -//LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -//#pragma code_page(1252) -//#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_RADIANT ICON DISCARDABLE "radiant.ico" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "//#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/misc/mediasource/extra/netradiant-src/radiant/radiant_old.ico b/misc/mediasource/extra/netradiant-src/radiant/radiant_old.ico deleted file mode 100644 index b45ef36a..00000000 Binary files a/misc/mediasource/extra/netradiant-src/radiant/radiant_old.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/radiant/referencecache.cpp b/misc/mediasource/extra/netradiant-src/radiant/referencecache.cpp deleted file mode 100644 index d41b9344..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/referencecache.cpp +++ /dev/null @@ -1,846 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "referencecache.h" - -#include "debugging/debugging.h" - -#include "iscenegraph.h" -#include "iselection.h" -#include "iundo.h" -#include "imap.h" -MapModules& ReferenceAPI_getMapModules(); -#include "imodel.h" -ModelModules& ReferenceAPI_getModelModules(); -#include "ifilesystem.h" -#include "iarchive.h" -#include "ifiletypes.h" -#include "ireference.h" -#include "ientity.h" -#include "qerplugin.h" - -#include - -#include "container/cache.h" -#include "container/hashfunc.h" -#include "os/path.h" -#include "stream/textfilestream.h" -#include "nullmodel.h" -#include "maplib.h" -#include "stream/stringstream.h" -#include "os/file.h" -#include "moduleobserver.h" -#include "moduleobservers.h" - -#include "mainframe.h" -#include "map.h" -#include "filetypes.h" - - -bool References_Saved(); - -void MapChanged() -{ - Map_SetModified(g_map, !References_Saved()); -} - - -EntityCreator* g_entityCreator = 0; - -bool MapResource_loadFile(const MapFormat& format, scene::Node& root, const char* filename) -{ - globalOutputStream() << "Open file " << filename << " for read..."; - TextFileInputStream file(filename); - if(!file.failed()) - { - globalOutputStream() << "success\n"; - ScopeDisableScreenUpdates disableScreenUpdates(path_get_filename_start(filename), "Loading Map"); - ASSERT_NOTNULL(g_entityCreator); - format.readGraph(root, file, *g_entityCreator); - return true; - } - else - { - globalErrorStream() << "failure\n"; - return false; - } -} - -NodeSmartReference MapResource_load(const MapFormat& format, const char* path, const char* name) -{ - NodeSmartReference root(NewMapRoot(name)); - - StringOutputStream fullpath(256); - fullpath << path << name; - - if(path_is_absolute(fullpath.c_str())) - { - MapResource_loadFile(format, root, fullpath.c_str()); - } - else - { - globalErrorStream() << "map path is not fully qualified: " << makeQuoted(fullpath.c_str()) << "\n"; - } - - return root; -} - -bool MapResource_saveFile(const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename) -{ - //ASSERT_MESSAGE(path_is_absolute(filename), "MapResource_saveFile: path is not absolute: " << makeQuoted(filename)); - globalOutputStream() << "Open file " << filename << " for write..."; - TextFileOutputStream file(filename); - if(!file.failed()) - { - globalOutputStream() << "success\n"; - ScopeDisableScreenUpdates disableScreenUpdates(path_get_filename_start(filename), "Saving Map"); - format.writeGraph(root, traverse, file); - return true; - } - - globalErrorStream() << "failure\n"; - return false; -} - -bool file_saveBackup(const char* path) -{ - if(file_writeable(path)) - { - StringOutputStream backup(256); - backup << StringRange(path, path_get_extension(path)) << "bak"; - - return (!file_exists(backup.c_str()) || file_remove(backup.c_str())) // remove backup - && file_move(path, backup.c_str()); // rename current to backup - } - - globalErrorStream() << "map path is not writeable: " << makeQuoted(path) << "\n"; - return false; -} - -bool MapResource_save(const MapFormat& format, scene::Node& root, const char* path, const char* name) -{ - StringOutputStream fullpath(256); - fullpath << path << name; - - if(path_is_absolute(fullpath.c_str())) - { - if(!file_exists(fullpath.c_str()) || file_saveBackup(fullpath.c_str())) - { - return MapResource_saveFile(format, root, Map_Traverse, fullpath.c_str()); - } - - globalErrorStream() << "failed to save a backup map file: " << makeQuoted(fullpath.c_str()) << "\n"; - return false; - } - - globalErrorStream() << "map path is not fully qualified: " << makeQuoted(fullpath.c_str()) << "\n"; - return false; -} - -namespace -{ - NodeSmartReference g_nullNode(NewNullNode()); - NodeSmartReference g_nullModel(g_nullNode); -} - -class NullModelLoader : public ModelLoader -{ -public: - scene::Node& loadModel(ArchiveFile& file) - { - return g_nullModel; - } -}; - -namespace -{ - NullModelLoader g_NullModelLoader; -} - - -/// \brief Returns the model loader for the model \p type or 0 if the model \p type has no loader module -ModelLoader* ModelLoader_forType(const char* type) -{ - const char* moduleName = findModuleName(&GlobalFiletypes(), ModelLoader::Name(), type); - if(string_not_empty(moduleName)) - { - ModelLoader* table = ReferenceAPI_getModelModules().findModule(moduleName); - if(table != 0) - { - return table; - } - else - { - globalErrorStream() << "ERROR: Model type incorrectly registered: \"" << moduleName << "\"\n"; - return &g_NullModelLoader; - } - } - return 0; -} - -NodeSmartReference ModelResource_load(ModelLoader* loader, const char* name) -{ - ScopeDisableScreenUpdates disableScreenUpdates(path_get_filename_start(name), "Loading Model"); - - NodeSmartReference model(g_nullModel); - - { - ArchiveFile* file = GlobalFileSystem().openFile(name); - - if(file != 0) - { - globalOutputStream() << "Loaded Model: \"" << name << "\"\n"; - model = loader->loadModel(*file); - file->release(); - } - else - { - globalErrorStream() << "Model load failed: \"" << name << "\"\n"; - } - } - - model.get().m_isRoot = true; - - return model; -} - - -inline hash_t path_hash(const char* path, hash_t previous = 0) -{ -#if defined(WIN32) - return string_hash_nocase(path, previous); -#else // UNIX - return string_hash(path, previous); -#endif -} - -struct PathEqual -{ - bool operator()(const CopiedString& path, const CopiedString& other) const - { - return path_equal(path.c_str(), other.c_str()); - } -}; - -struct PathHash -{ - typedef hash_t hash_type; - hash_type operator()(const CopiedString& path) const - { - return path_hash(path.c_str()); - } -}; - -typedef std::pair ModelKey; - -struct ModelKeyEqual -{ - bool operator()(const ModelKey& key, const ModelKey& other) const - { - return path_equal(key.first.c_str(), other.first.c_str()) && path_equal(key.second.c_str(), other.second.c_str()); - } -}; - -struct ModelKeyHash -{ - typedef hash_t hash_type; - hash_type operator()(const ModelKey& key) const - { - return hash_combine(path_hash(key.first.c_str()), path_hash(key.second.c_str())); - } -}; - -typedef HashTable ModelCache; -ModelCache g_modelCache; -bool g_modelCache_enabled = true; - -ModelCache::iterator ModelCache_find(const char* path, const char* name) -{ - if(g_modelCache_enabled) - { - return g_modelCache.find(ModelKey(path, name)); - } - return g_modelCache.end(); -} - -ModelCache::iterator ModelCache_insert(const char* path, const char* name, scene::Node& node) -{ - if(g_modelCache_enabled) - { - return g_modelCache.insert(ModelKey(path, name), NodeSmartReference(node)); - } - return g_modelCache.insert(ModelKey("", ""), g_nullModel); -} - -void ModelCache_flush(const char* path, const char* name) -{ - ModelCache::iterator i = g_modelCache.find(ModelKey(path, name)); - if(i != g_modelCache.end()) - { - //ASSERT_MESSAGE((*i).value.getCount() == 0, "resource flushed while still in use: " << (*i).key.first.c_str() << (*i).key.second.c_str()); - g_modelCache.erase(i); - } -} - -void ModelCache_clear() -{ - g_modelCache_enabled = false; - g_modelCache.clear(); - g_modelCache_enabled = true; -} - -NodeSmartReference Model_load(ModelLoader* loader, const char* path, const char* name, const char* type) -{ - if(loader != 0) - { - return ModelResource_load(loader, name); - } - else - { - const char* moduleName = findModuleName(&GlobalFiletypes(), MapFormat::Name(), type); - if(string_not_empty(moduleName)) - { - const MapFormat* format = ReferenceAPI_getMapModules().findModule(moduleName); - if(format != 0) - { - return MapResource_load(*format, path, name); - } - else - { - globalErrorStream() << "ERROR: Map type incorrectly registered: \"" << moduleName << "\"\n"; - return g_nullModel; - } - } - else - { - if(string_not_empty(type)) - { - globalErrorStream() << "Model type not supported: \"" << name << "\"\n"; - } - return g_nullModel; - } - } -} - -namespace -{ - bool g_realised = false; - - // name may be absolute or relative - const char* rootPath(const char* name) - { - return GlobalFileSystem().findRoot( - path_is_absolute(name) - ? name - : GlobalFileSystem().findFile(name) - ); - } -} - -struct ModelResource : public Resource -{ - NodeSmartReference m_model; - const CopiedString m_originalName; - CopiedString m_path; - CopiedString m_name; - CopiedString m_type; - ModelLoader* m_loader; - ModuleObservers m_observers; - std::time_t m_modified; - std::size_t m_unrealised; - - ModelResource(const CopiedString& name) : - m_model(g_nullModel), - m_originalName(name), - m_type(path_get_extension(name.c_str())), - m_loader(0), - m_modified(0), - m_unrealised(1) - { - m_loader = ModelLoader_forType(m_type.c_str()); - - if(g_realised) - { - realise(); - } - } - ~ModelResource() - { - if(realised()) - { - unrealise(); - } - ASSERT_MESSAGE(!realised(), "ModelResource::~ModelResource: resource reference still realised: " << makeQuoted(m_name.c_str())); - } - // NOT COPYABLE - ModelResource(const ModelResource&); - // NOT ASSIGNABLE - ModelResource& operator=(const ModelResource&); - - void setModel(const NodeSmartReference& model) - { - m_model = model; - } - void clearModel() - { - m_model = g_nullModel; - } - - void loadCached() - { - if(g_modelCache_enabled) - { - // cache lookup - ModelCache::iterator i = ModelCache_find(m_path.c_str(), m_name.c_str()); - if(i == g_modelCache.end()) - { - i = ModelCache_insert( - m_path.c_str(), - m_name.c_str(), - Model_load(m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str()) - ); - } - - setModel((*i).value); - } - else - { - setModel(Model_load(m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str())); - } - } - - void loadModel() - { - loadCached(); - connectMap(); - mapSave(); - } - - bool load() - { - ASSERT_MESSAGE(realised(), "resource not realised"); - if(m_model == g_nullModel) - { - loadModel(); - } - - return m_model != g_nullModel; - } - bool save() - { - if(!mapSaved()) - { - const char* moduleName = findModuleName(GetFileTypeRegistry(), MapFormat::Name(), m_type.c_str()); - if(string_not_empty(moduleName)) - { - const MapFormat* format = ReferenceAPI_getMapModules().findModule(moduleName); - if(format != 0 && MapResource_save(*format, m_model.get(), m_path.c_str(), m_name.c_str())) - { - mapSave(); - return true; - } - } - } - return false; - } - void flush() - { - if(realised()) - { - ModelCache_flush(m_path.c_str(), m_name.c_str()); - } - } - scene::Node* getNode() - { - //if(m_model != g_nullModel) - { - return m_model.get_pointer(); - } - //return 0; - } - void setNode(scene::Node* node) - { - ModelCache::iterator i = ModelCache_find(m_path.c_str(), m_name.c_str()); - if(i != g_modelCache.end()) - { - (*i).value = NodeSmartReference(*node); - } - setModel(NodeSmartReference(*node)); - - connectMap(); - } - void attach(ModuleObserver& observer) - { - if(realised()) - { - observer.realise(); - } - m_observers.attach(observer); - } - void detach(ModuleObserver& observer) - { - if(realised()) - { - observer.unrealise(); - } - m_observers.detach(observer); - } - bool realised() - { - return m_unrealised == 0; - } - void realise() - { - ASSERT_MESSAGE(m_unrealised != 0, "ModelResource::realise: already realised"); - if(--m_unrealised == 0) - { - m_path = rootPath(m_originalName.c_str()); - m_name = path_make_relative(m_originalName.c_str(), m_path.c_str()); - - //globalOutputStream() << "ModelResource::realise: " << m_path.c_str() << m_name.c_str() << "\n"; - - m_observers.realise(); - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - m_observers.unrealise(); - - //globalOutputStream() << "ModelResource::unrealise: " << m_path.c_str() << m_name.c_str() << "\n"; - clearModel(); - } - } - bool isMap() const - { - return Node_getMapFile(m_model) != 0; - } - void connectMap() - { - MapFile* map = Node_getMapFile(m_model); - if(map != 0) - { - map->setChangedCallback(FreeCaller()); - } - } - std::time_t modified() const - { - StringOutputStream fullpath(256); - fullpath << m_path.c_str() << m_name.c_str(); - return file_modified(fullpath.c_str()); - } - void mapSave() - { - m_modified = modified(); - MapFile* map = Node_getMapFile(m_model); - if(map != 0) - { - map->save(); - } - } - bool mapSaved() const - { - MapFile* map = Node_getMapFile(m_model); - if(map != 0) - { - return m_modified == modified() && map->saved(); - } - return true; - } - bool isModified() const - { - return ((!string_empty(m_path.c_str()) // had or has an absolute path - && m_modified != modified()) // AND disk timestamp changed - || !path_equal(rootPath(m_originalName.c_str()), m_path.c_str())); // OR absolute vfs-root changed - } - void refresh() - { - if(isModified()) - { - flush(); - unrealise(); - realise(); - } - } -}; - -class HashtableReferenceCache : public ReferenceCache, public ModuleObserver -{ - typedef HashedCache ModelReferences; - ModelReferences m_references; - std::size_t m_unrealised; - - class ModelReferencesSnapshot - { - ModelReferences& m_references; - typedef std::list Iterators; - Iterators m_iterators; - public: - typedef Iterators::iterator iterator; - ModelReferencesSnapshot(ModelReferences& references) : m_references(references) - { - for(ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i) - { - m_references.capture(i); - m_iterators.push_back(i); - } - } - ~ModelReferencesSnapshot() - { - for(Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i) - { - m_references.release(*i); - } - } - iterator begin() - { - return m_iterators.begin(); - } - iterator end() - { - return m_iterators.end(); - } - }; - -public: - - typedef ModelReferences::iterator iterator; - - HashtableReferenceCache() : m_unrealised(1) - { - } - - iterator begin() - { - return m_references.begin(); - } - iterator end() - { - return m_references.end(); - } - - void clear() - { - m_references.clear(); - } - - Resource* capture(const char* path) - { - //globalOutputStream() << "capture: \"" << path << "\"\n"; - return m_references.capture(CopiedString(path)).get(); - } - void release(const char* path) - { - m_references.release(CopiedString(path)); - //globalOutputStream() << "release: \"" << path << "\"\n"; - } - - void setEntityCreator(EntityCreator& entityCreator) - { - g_entityCreator = &entityCreator; - } - - bool realised() const - { - return m_unrealised == 0; - } - void realise() - { - ASSERT_MESSAGE(m_unrealised != 0, "HashtableReferenceCache::realise: already realised"); - if(--m_unrealised == 0) - { - g_realised = true; - - { - ModelReferencesSnapshot snapshot(m_references); - for(ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i) - { - ModelReferences::value_type& value = *(*i); - if(value.value.count() != 1) - { - value.value.get()->realise(); - } - } - } - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - g_realised = false; - - { - ModelReferencesSnapshot snapshot(m_references); - for(ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i) - { - ModelReferences::value_type& value = *(*i); - if(value.value.count() != 1) - { - value.value.get()->unrealise(); - } - } - } - - ModelCache_clear(); - } - } - void refresh() - { - ModelReferencesSnapshot snapshot(m_references); - for(ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i) - { - ModelResource* resource = (*(*i)).value.get(); - if(!resource->isMap()) - { - resource->refresh(); - } - } - } -}; - -namespace -{ - HashtableReferenceCache g_referenceCache; -} - -#if 0 -class ResourceVisitor -{ -public: - virtual void visit(const char* name, const char* path, const -}; -#endif - -void SaveReferences() -{ - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Saving Map"); - for(HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i) - { - (*i).value->save(); - } - MapChanged(); -} - -bool References_Saved() -{ - for(HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i) - { - scene::Node* node = (*i).value->getNode(); - if(node != 0) - { - MapFile* map = Node_getMapFile(*node); - if(map != 0 && !map->saved()) - { - return false; - } - } - } - return true; -} - -void RefreshReferences() -{ - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Refreshing Models"); - g_referenceCache.refresh(); -} - - -void FlushReferences() -{ - ModelCache_clear(); - - g_referenceCache.clear(); -} - -ReferenceCache& GetReferenceCache() -{ - return g_referenceCache; -} - - -#include "modulesystem/modulesmap.h" -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class ReferenceDependencies : - public GlobalRadiantModuleRef, - public GlobalFileSystemModuleRef, - public GlobalFiletypesModuleRef -{ - ModelModulesRef m_model_modules; - MapModulesRef m_map_modules; -public: - ReferenceDependencies() : - m_model_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("modeltypes")), - m_map_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("maptypes")) - { - } - ModelModules& getModelModules() - { - return m_model_modules.get(); - } - MapModules& getMapModules() - { - return m_map_modules.get(); - } -}; - -class ReferenceAPI : public TypeSystemRef -{ - ReferenceCache* m_reference; -public: - typedef ReferenceCache Type; - STRING_CONSTANT(Name, "*"); - - ReferenceAPI() - { - g_nullModel = NewNullModel(); - - GlobalFileSystem().attach(g_referenceCache); - - m_reference = &GetReferenceCache(); - } - ~ReferenceAPI() - { - GlobalFileSystem().detach(g_referenceCache); - - g_nullModel = g_nullNode; - } - ReferenceCache* getTable() - { - return m_reference; - } -}; - -typedef SingletonModule ReferenceModule; -typedef Static StaticReferenceModule; -StaticRegisterModule staticRegisterReference(StaticReferenceModule::instance()); - -ModelModules& ReferenceAPI_getModelModules() -{ - return StaticReferenceModule::instance().getDependencies().getModelModules(); -} -MapModules& ReferenceAPI_getMapModules() -{ - return StaticReferenceModule::instance().getDependencies().getMapModules(); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/referencecache.h b/misc/mediasource/extra/netradiant-src/radiant/referencecache.h deleted file mode 100644 index 32d121e7..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/referencecache.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (INCLUDED_REFERENCECACHE_H) -#define INCLUDED_REFERENCECACHE_H - -/// \brief Saves all open resource references if they differ from the version on disk. -void SaveReferences(); -/// \brief Flushes the cache of resource references. All resource references must be released before calling this. -void FlushReferences(); -/// \brief Reloads all resource references that differ from the version on disk. -void RefreshReferences(); - -#include "iscenegraph.h" -namespace scene -{ - class Node; -} -class MapFormat; -typedef void(*GraphTraversalFunc)(scene::Node& root, const scene::Traversable::Walker& walker); - -bool MapResource_saveFile(const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/renderer.cpp b/misc/mediasource/extra/netradiant-src/radiant/renderer.cpp deleted file mode 100644 index 386653b9..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/renderer.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "renderer.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/renderer.h b/misc/mediasource/extra/netradiant-src/radiant/renderer.h deleted file mode 100644 index 71865d62..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/renderer.h +++ /dev/null @@ -1,199 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_RENDERER_H) -#define INCLUDED_RENDERER_H - -#include "irender.h" -#include "renderable.h" -#include "iselection.h" -#include "cullable.h" -#include "scenelib.h" -#include "math/frustum.h" -#include - -inline Cullable* Instance_getCullable(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); -} - -inline Renderable* Instance_getRenderable(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); -} - -inline VolumeIntersectionValue Cullable_testVisible(scene::Instance& instance, const VolumeTest& volume, VolumeIntersectionValue parentVisible) -{ - if(parentVisible == c_volumePartial) - { - Cullable* cullable = Instance_getCullable(instance); - if(cullable != 0) - { - return cullable->intersectVolume(volume, instance.localToWorld()); - } - } - return parentVisible; -} - -template -class CullingWalker -{ - const VolumeTest& m_volume; - const _Walker& m_walker; -public: - CullingWalker(const VolumeTest& volume, const _Walker& walker) - : m_volume(volume), m_walker(walker) - { - } - bool pre(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const - { - VolumeIntersectionValue visible = Cullable_testVisible(instance, m_volume, parentVisible); - if(visible != c_volumeOutside) - { - return m_walker.pre(path, instance); - } - return true; - } - void post(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const - { - return m_walker.post(path, instance); - } -}; - -template -class ForEachVisible : public scene::Graph::Walker -{ - const VolumeTest& m_volume; - const Walker_& m_walker; - mutable std::vector m_state; -public: - ForEachVisible(const VolumeTest& volume, const Walker_& walker) - : m_volume(volume), m_walker(walker) - { - m_state.push_back(c_volumePartial); - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - VolumeIntersectionValue visible = (path.top().get().visible()) ? m_state.back() : c_volumeOutside; - - if(visible == c_volumePartial) - { - visible = m_volume.TestAABB(instance.worldAABB()); - } - - m_state.push_back(visible); - - if(visible == c_volumeOutside) - { - return false; - } - else - { - return m_walker.pre(path, instance, m_state.back()); - } - } - void post(const scene::Path& path, scene::Instance& instance) const - { - if(m_state.back() != c_volumeOutside) - { - m_walker.post(path, instance, m_state.back()); - } - - m_state.pop_back(); - } -}; - -template -inline void Scene_forEachVisible(scene::Graph& graph, const VolumeTest& volume, const Functor& functor) -{ - graph.traverse(ForEachVisible< CullingWalker >(volume, CullingWalker(volume, functor))); -} - -class RenderHighlighted -{ - Renderer& m_renderer; - const VolumeTest& m_volume; -public: - RenderHighlighted(Renderer& renderer, const VolumeTest& volume) - : m_renderer(renderer), m_volume(volume) - { - } - void render(const Renderable& renderable) const - { - switch(m_renderer.getStyle()) - { - case Renderer::eFullMaterials: - renderable.renderSolid(m_renderer, m_volume); - break; - case Renderer::eWireframeOnly: - renderable.renderWireframe(m_renderer, m_volume); - break; - } - } - typedef ConstMemberCaller1 RenderCaller; - - bool pre(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const - { - m_renderer.PushState(); - - if(Cullable_testVisible(instance, m_volume, parentVisible) != c_volumeOutside) - { - Renderable* renderable = Instance_getRenderable(instance); - if(renderable) - { - renderable->viewChanged(); - } - - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 && selectable->isSelected()) - { - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - m_renderer.Highlight(Renderer::eFace); - } - else if(renderable) - { - renderable->renderComponents(m_renderer, m_volume); - } - m_renderer.Highlight(Renderer::ePrimitive); - } - - if(renderable) - { - render(*renderable); - } - } - - return true; - } - void post(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const - { - m_renderer.PopState(); - } -}; - -inline void Scene_Render(Renderer& renderer, const VolumeTest& volume) -{ - GlobalSceneGraph().traverse(ForEachVisible(volume, RenderHighlighted(renderer, volume))); - GlobalShaderCache().forEachRenderable(RenderHighlighted::RenderCaller(RenderHighlighted(renderer, volume))); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/renderstate.cpp b/misc/mediasource/extra/netradiant-src/radiant/renderstate.cpp deleted file mode 100644 index 2f5596d1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/renderstate.cpp +++ /dev/null @@ -1,2693 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "renderstate.h" - -#include "debugging/debugging.h" -#include "warnings.h" - -#include "ishaders.h" -#include "irender.h" -#include "itextures.h" -#include "igl.h" -#include "iglrender.h" -#include "renderable.h" -#include "qerplugin.h" - -#include -#include -#include -#include - -#include "math/matrix.h" -#include "math/aabb.h" -#include "generic/callback.h" -#include "texturelib.h" -#include "string/string.h" -#include "container/hashfunc.h" -#include "container/cache.h" -#include "generic/reference.h" -#include "moduleobservers.h" -#include "stream/filestream.h" -#include "stream/stringstream.h" -#include "os/file.h" -#include "preferences.h" - -#include "xywindow.h" - - - -#define DEBUG_RENDER 0 - -inline void debug_string(const char* string) -{ -#if(DEBUG_RENDER) - globalOutputStream() << string << "\n"; -#endif -} - -inline void debug_int(const char* comment, int i) -{ -#if(DEBUG_RENDER) - globalOutputStream() << comment << " " << i << "\n"; -#endif -} - -inline void debug_colour(const char* comment) -{ -#if(DEBUG_RENDER) - Vector4 v; - glGetFloatv(GL_CURRENT_COLOR, reinterpret_cast(&v)); - globalOutputStream() << comment << " colour: " - << v[0] << " " - << v[1] << " " - << v[2] << " " - << v[3]; - if(glIsEnabled(GL_COLOR_ARRAY)) - { - globalOutputStream() << " ARRAY"; - } - if(glIsEnabled(GL_COLOR_MATERIAL)) - { - globalOutputStream() << " MATERIAL"; - } - globalOutputStream() << "\n"; -#endif -} - -#include "timer.h" - -StringOutputStream g_renderer_stats; -std::size_t g_count_prims; -std::size_t g_count_states; -std::size_t g_count_transforms; -Timer g_timer; - -inline void count_prim() -{ - ++g_count_prims; -} - -inline void count_state() -{ - ++g_count_states; -} - -inline void count_transform() -{ - ++g_count_transforms; -} - -void Renderer_ResetStats() -{ - g_count_prims = 0; - g_count_states = 0; - g_count_transforms = 0; - g_timer.start(); -} - -const char* Renderer_GetStats() -{ - g_renderer_stats.clear(); - g_renderer_stats << "prims: " << Unsigned(g_count_prims) - << " | states: " << Unsigned(g_count_states) - << " | transforms: " << Unsigned(g_count_transforms) - << " | msec: " << g_timer.elapsed_msec(); - return g_renderer_stats.c_str(); -} - - -void printShaderLog(GLhandleARB object) -{ - GLint log_length = 0; - glGetObjectParameterivARB(object, GL_OBJECT_INFO_LOG_LENGTH_ARB, &log_length); - - Array log(log_length); - glGetInfoLogARB(object, log_length, &log_length, log.data()); - - globalErrorStream() << StringRange(log.begin(), log.begin() + log_length) << "\n"; -} - -void createShader(GLhandleARB program, const char* filename, GLenum type) -{ - GLhandleARB shader = glCreateShaderObjectARB(type); - GlobalOpenGL_debugAssertNoErrors(); - - // load shader - { - std::size_t size = file_size(filename); - FileInputStream file(filename); - ASSERT_MESSAGE(!file.failed(), "failed to open " << makeQuoted(filename)); - Array buffer(size); - size = file.read(reinterpret_cast(buffer.data()), size); - - const GLcharARB* string = buffer.data(); - GLint length = GLint(size); - glShaderSourceARB(shader, 1, &string, &length); - } - - // compile shader - { - glCompileShaderARB(shader); - - GLint compiled = 0; - glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &compiled); - - if(!compiled) - { - printShaderLog(shader); - } - - ASSERT_MESSAGE(compiled, "shader compile failed: " << makeQuoted(filename)); - } - - // attach shader - glAttachObjectARB(program, shader); - - glDeleteObjectARB(shader); - - GlobalOpenGL_debugAssertNoErrors(); -} - -void GLSLProgram_link(GLhandleARB program) -{ - glLinkProgramARB(program); - - GLint linked = false; - glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &linked); - - if(!linked) - { - printShaderLog(program); - } - - ASSERT_MESSAGE(linked, "program link failed"); -} - -void GLSLProgram_validate(GLhandleARB program) -{ - glValidateProgramARB(program); - - GLint validated = false; - glGetObjectParameterivARB(program, GL_OBJECT_VALIDATE_STATUS_ARB, &validated); - - if(!validated) - { - printShaderLog(program); - } - - ASSERT_MESSAGE(validated, "program validation failed"); -} - -bool g_bumpGLSLPass_enabled = false; -bool g_depthfillPass_enabled = false; - -class GLSLBumpProgram : public GLProgram -{ -public: - GLhandleARB m_program; - qtexture_t* m_light_attenuation_xy; - qtexture_t* m_light_attenuation_z; - GLint u_view_origin; - GLint u_light_origin; - GLint u_light_color; - GLint u_bump_scale; - GLint u_specular_exponent; - - GLSLBumpProgram() : m_program(0), m_light_attenuation_xy(0), m_light_attenuation_z(0) - { - } - - void create() - { - // create program - m_program = glCreateProgramObjectARB(); - - // create shader - { - StringOutputStream filename(256); - filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_vp.glsl"; - createShader(m_program, filename.c_str(), GL_VERTEX_SHADER_ARB); - filename.clear(); - filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_fp.glsl"; - createShader(m_program, filename.c_str(), GL_FRAGMENT_SHADER_ARB); - } - - GLSLProgram_link(m_program); - GLSLProgram_validate(m_program); - - glUseProgramObjectARB(m_program); - - glBindAttribLocationARB(m_program, c_attr_TexCoord0, "attr_TexCoord0"); - glBindAttribLocationARB(m_program, c_attr_Tangent, "attr_Tangent"); - glBindAttribLocationARB(m_program, c_attr_Binormal, "attr_Binormal"); - - glUniform1iARB(glGetUniformLocationARB(m_program, "u_diffusemap"), 0); - glUniform1iARB(glGetUniformLocationARB(m_program, "u_bumpmap"), 1); - glUniform1iARB(glGetUniformLocationARB(m_program, "u_specularmap"), 2); - glUniform1iARB(glGetUniformLocationARB(m_program, "u_attenuationmap_xy"), 3); - glUniform1iARB(glGetUniformLocationARB(m_program, "u_attenuationmap_z"), 4); - - u_view_origin = glGetUniformLocationARB(m_program, "u_view_origin"); - u_light_origin = glGetUniformLocationARB(m_program, "u_light_origin"); - u_light_color = glGetUniformLocationARB(m_program, "u_light_color"); - u_bump_scale = glGetUniformLocationARB(m_program, "u_bump_scale"); - u_specular_exponent = glGetUniformLocationARB(m_program, "u_specular_exponent"); - - glUseProgramObjectARB(0); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void destroy() - { - glDeleteObjectARB(m_program); - m_program = 0; - } - - void enable() - { - glUseProgramObjectARB(m_program); - - glEnableVertexAttribArrayARB(c_attr_TexCoord0); - glEnableVertexAttribArrayARB(c_attr_Tangent); - glEnableVertexAttribArrayARB(c_attr_Binormal); - - GlobalOpenGL_debugAssertNoErrors(); - - debug_string("enable bump"); - g_bumpGLSLPass_enabled = true; - } - - void disable() - { - glUseProgramObjectARB(0); - - glDisableVertexAttribArrayARB(c_attr_TexCoord0); - glDisableVertexAttribArrayARB(c_attr_Tangent); - glDisableVertexAttribArrayARB(c_attr_Binormal); - - GlobalOpenGL_debugAssertNoErrors(); - - debug_string("disable bump"); - g_bumpGLSLPass_enabled = false; - } - - void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) - { - Matrix4 world2local(localToWorld); - matrix4_affine_invert(world2local); - - Vector3 localLight(origin); - matrix4_transform_point(world2local, localLight); - - Vector3 localViewer(viewer); - matrix4_transform_point(world2local, localViewer); - - Matrix4 local2light(world2light); - matrix4_multiply_by_matrix4(local2light, localToWorld); // local->world->light - - glUniform3fARB(u_view_origin, localViewer.x(), localViewer.y(), localViewer.z()); - glUniform3fARB(u_light_origin, localLight.x(), localLight.y(), localLight.z()); - glUniform3fARB(u_light_color, colour.x(), colour.y(), colour.z()); - glUniform1fARB(u_bump_scale, 1.0); - glUniform1fARB(u_specular_exponent, 32.0); - - glActiveTexture(GL_TEXTURE3); - glClientActiveTexture(GL_TEXTURE3); - - glMatrixMode(GL_TEXTURE); - glLoadMatrixf(reinterpret_cast(&local2light)); - glMatrixMode(GL_MODELVIEW); - - GlobalOpenGL_debugAssertNoErrors(); - } -}; - -GLSLBumpProgram g_bumpGLSL; - - -class GLSLDepthFillProgram : public GLProgram -{ -public: - GLhandleARB m_program; - - void create() - { - // create program - m_program = glCreateProgramObjectARB(); - - // create shader - { - StringOutputStream filename(256); - filename << GlobalRadiant().getAppPath() << "gl/zfill_vp.glsl"; - createShader(m_program, filename.c_str(), GL_VERTEX_SHADER_ARB); - filename.clear(); - filename << GlobalRadiant().getAppPath() << "gl/zfill_fp.glsl"; - createShader(m_program, filename.c_str(), GL_FRAGMENT_SHADER_ARB); - } - - GLSLProgram_link(m_program); - GLSLProgram_validate(m_program); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void destroy() - { - glDeleteObjectARB(m_program); - m_program = 0; - } - void enable() - { - glUseProgramObjectARB(m_program); - GlobalOpenGL_debugAssertNoErrors(); - debug_string("enable depthfill"); - g_depthfillPass_enabled = true; - } - void disable() - { - glUseProgramObjectARB(0); - GlobalOpenGL_debugAssertNoErrors(); - debug_string("disable depthfill"); - g_depthfillPass_enabled = false; - } - void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) - { - } -}; - -GLSLDepthFillProgram g_depthFillGLSL; - - -// ARB path - -void createProgram(const char* filename, GLenum type) -{ - std::size_t size = file_size(filename); - FileInputStream file(filename); - ASSERT_MESSAGE(!file.failed(), "failed to open " << makeQuoted(filename)); - Array buffer(size); - size = file.read(reinterpret_cast(buffer.data()), size); - - glProgramStringARB(type, GL_PROGRAM_FORMAT_ASCII_ARB, GLsizei(size), buffer.data()); - - if(GL_INVALID_OPERATION == glGetError()) - { - GLint errPos; - glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos); - const GLubyte* errString = glGetString(GL_PROGRAM_ERROR_STRING_ARB); - - globalErrorStream() << reinterpret_cast(filename) << ":" << errPos << "\n" << reinterpret_cast(errString); - - ERROR_MESSAGE("error in gl program"); - } -} - -class ARBBumpProgram : public GLProgram -{ -public: - GLuint m_vertex_program; - GLuint m_fragment_program; - - void create() - { - glEnable(GL_VERTEX_PROGRAM_ARB); - glEnable(GL_FRAGMENT_PROGRAM_ARB); - - { - glGenProgramsARB(1, &m_vertex_program); - glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); - StringOutputStream filename(256); - filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_vp.glp"; - createProgram(filename.c_str(), GL_VERTEX_PROGRAM_ARB); - - glGenProgramsARB(1, &m_fragment_program); - glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); - filename.clear(); - filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_fp.glp"; - createProgram(filename.c_str(), GL_FRAGMENT_PROGRAM_ARB); - } - - glDisable(GL_VERTEX_PROGRAM_ARB); - glDisable(GL_FRAGMENT_PROGRAM_ARB); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void destroy() - { - glDeleteProgramsARB(1, &m_vertex_program); - glDeleteProgramsARB(1, &m_fragment_program); - GlobalOpenGL_debugAssertNoErrors(); - } - - void enable() - { - glEnable(GL_VERTEX_PROGRAM_ARB); - glEnable(GL_FRAGMENT_PROGRAM_ARB); - glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); - glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); - - glEnableVertexAttribArrayARB(8); - glEnableVertexAttribArrayARB(9); - glEnableVertexAttribArrayARB(10); - glEnableVertexAttribArrayARB(11); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void disable() - { - glDisable(GL_VERTEX_PROGRAM_ARB); - glDisable(GL_FRAGMENT_PROGRAM_ARB); - - glDisableVertexAttribArrayARB(8); - glDisableVertexAttribArrayARB(9); - glDisableVertexAttribArrayARB(10); - glDisableVertexAttribArrayARB(11); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) - { - Matrix4 world2local(localToWorld); - matrix4_affine_invert(world2local); - - Vector3 localLight(origin); - matrix4_transform_point(world2local, localLight); - - Vector3 localViewer(viewer); - matrix4_transform_point(world2local, localViewer); - - Matrix4 local2light(world2light); - matrix4_multiply_by_matrix4(local2light, localToWorld); // local->world->light - - // view origin - glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 4, localViewer.x(), localViewer.y(), localViewer.z(), 0); - - // light origin - glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, localLight.x(), localLight.y(), localLight.z(), 1); - - // light colour - glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 3, colour.x(), colour.y(), colour.z(), 0); - - // bump scale - glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, 1, 0, 0, 0); - - // specular exponent - glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 5, 32, 0, 0, 0); - - - glActiveTexture(GL_TEXTURE3); - glClientActiveTexture(GL_TEXTURE3); - - glMatrixMode(GL_TEXTURE); - glLoadMatrixf(reinterpret_cast(&local2light)); - glMatrixMode(GL_MODELVIEW); - - GlobalOpenGL_debugAssertNoErrors(); - } -}; - -class ARBDepthFillProgram : public GLProgram -{ -public: - GLuint m_vertex_program; - GLuint m_fragment_program; - - void create() - { - glEnable(GL_VERTEX_PROGRAM_ARB); - glEnable(GL_FRAGMENT_PROGRAM_ARB); - - { - glGenProgramsARB(1, &m_vertex_program); - glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); - StringOutputStream filename(256); - filename << GlobalRadiant().getAppPath() << "gl/zfill_vp.glp"; - createProgram(filename.c_str(), GL_VERTEX_PROGRAM_ARB); - - glGenProgramsARB(1, &m_fragment_program); - glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); - filename.clear(); - filename << GlobalRadiant().getAppPath() << "gl/zfill_fp.glp"; - createProgram(filename.c_str(), GL_FRAGMENT_PROGRAM_ARB); - } - - glDisable(GL_VERTEX_PROGRAM_ARB); - glDisable(GL_FRAGMENT_PROGRAM_ARB); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void destroy() - { - glDeleteProgramsARB(1, &m_vertex_program); - glDeleteProgramsARB(1, &m_fragment_program); - GlobalOpenGL_debugAssertNoErrors(); - } - - void enable() - { - glEnable(GL_VERTEX_PROGRAM_ARB); - glEnable(GL_FRAGMENT_PROGRAM_ARB); - glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); - glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void disable() - { - glDisable(GL_VERTEX_PROGRAM_ARB); - glDisable(GL_FRAGMENT_PROGRAM_ARB); - - GlobalOpenGL_debugAssertNoErrors(); - } - - void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) - { - } -}; - -ARBBumpProgram g_bumpARB; -ARBDepthFillProgram g_depthFillARB; - - -#if 0 -// NV20 path (unfinished) - -void createProgram(GLint program, const char* filename, GLenum type) -{ - std::size_t size = file_size(filename); - FileInputStream file(filename); - ASSERT_MESSAGE(!file.failed(), "failed to open " << makeQuoted(filename)); - Array buffer(size); - size = file.read(reinterpret_cast(buffer.data()), size); - - glLoadProgramNV(type, program, GLsizei(size), buffer.data()); - - if(GL_INVALID_OPERATION == glGetError()) - { - GLint errPos; - glGetIntegerv(GL_PROGRAM_ERROR_POSITION_NV, &errPos); - const GLubyte* errString = glGetString(GL_PROGRAM_ERROR_STRING_NV); - - globalErrorStream() << filename << ":" << errPos << "\n" << errString; - - ERROR_MESSAGE("error in gl program"); - } -} - -GLuint m_vertex_program; -GLuint m_fragment_program; -qtexture_t* g_cube = 0; -qtexture_t* g_specular_lookup = 0; -qtexture_t* g_attenuation_xy = 0; -qtexture_t* g_attenuation_z = 0; - -void createVertexProgram() -{ - { - glGenProgramsNV(1, &m_vertex_program); - glBindProgramNV(GL_VERTEX_PROGRAM_NV, m_vertex_program); - StringOutputStream filename(256); - filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_vp.nv30"; - createProgram(m_vertex_program, filename.c_str(), GL_VERTEX_PROGRAM_NV); - - glGenProgramsNV(1, &m_fragment_program); - glBindProgramNV(GL_FRAGMENT_PROGRAM_NV, m_fragment_program); - filename.clear(); - filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_fp.nv30"; - createProgram(m_fragment_program, filename.c_str(), GL_FRAGMENT_PROGRAM_NV); - } - - g_cube = GlobalTexturesCache().capture("generated/cube"); - g_specular_lookup = GlobalTexturesCache().capture("generated/specular"); - - g_attenuation_xy = GlobalTexturesCache().capture("lights/squarelight1"); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, g_attenuation_xy->texture_number); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - - g_attenuation_z = GlobalTexturesCache().capture("lights/squarelight1a"); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, g_attenuation_z->texture_number); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - GlobalOpenGL_debugAssertNoErrors(); -} - -void destroyVertexProgram() -{ - glDeleteProgramsNV(1, &m_vertex_program); - glDeleteProgramsNV(1, &m_fragment_program); - GlobalOpenGL_debugAssertNoErrors(); - - GlobalTexturesCache().release(g_cube); - GlobalTexturesCache().release(g_specular_lookup); - GlobalTexturesCache().release(g_attenuation_xy); - GlobalTexturesCache().release(g_attenuation_z); -} - -bool g_vertexProgram_enabled = false; - -void enableVertexProgram() -{ - //set up the register combiners - //two general combiners - glCombinerParameteriNV(GL_NUM_GENERAL_COMBINERS_NV, 2); - - //combiner 0 does tex0+tex1 -> spare0 - glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, - GL_UNSIGNED_IDENTITY_NV, GL_RGB); - glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_ZERO, - GL_UNSIGNED_INVERT_NV, GL_RGB); - glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE1_ARB, - GL_UNSIGNED_IDENTITY_NV, GL_RGB); - glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_ZERO, - GL_UNSIGNED_INVERT_NV, GL_RGB); - glCombinerOutputNV(GL_COMBINER0_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE0_NV, - GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE); - - //combiner 1 does tex2 dot tex3 -> spare1 - glCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, - GL_EXPAND_NORMAL_NV, GL_RGB); - glCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE3_ARB, - GL_EXPAND_NORMAL_NV, GL_RGB); - glCombinerOutputNV(GL_COMBINER1_NV, GL_RGB, GL_SPARE1_NV, GL_DISCARD_NV, GL_DISCARD_NV, - GL_NONE, GL_NONE, GL_TRUE, GL_FALSE, GL_FALSE); - - - - //final combiner outputs (1-spare0)*constant color 0*spare1 - //do constant color 0*spare1 in the EF multiplier - glFinalCombinerInputNV(GL_VARIABLE_E_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_F_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); - - //now do (1-spare0)*EF - glFinalCombinerInputNV(GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_C_NV, GL_E_TIMES_F_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); - glFinalCombinerInputNV(GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB); - - glEnable(GL_VERTEX_PROGRAM_NV); - glEnable(GL_REGISTER_COMBINERS_NV); - glBindProgramNV(GL_VERTEX_PROGRAM_NV, m_vertex_program); - glBindProgramNV(GL_FRAGMENT_PROGRAM_NV, m_fragment_program); - - glActiveTexture(GL_TEXTURE0); - glEnable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE1); - glEnable(GL_TEXTURE_1D); - glActiveTexture(GL_TEXTURE2); - glEnable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE3); - glEnable(GL_TEXTURE_2D); - - glEnableClientState(GL_VERTEX_ATTRIB_ARRAY8_NV); - glEnableClientState(GL_VERTEX_ATTRIB_ARRAY9_NV); - glEnableClientState(GL_VERTEX_ATTRIB_ARRAY10_NV); - glEnableClientState(GL_VERTEX_ATTRIB_ARRAY11_NV); - - GlobalOpenGL_debugAssertNoErrors(); - g_vertexProgram_enabled = true; -} - -void disableVertexProgram() -{ - glDisable(GL_VERTEX_PROGRAM_NV); - glDisable(GL_REGISTER_COMBINERS_NV); - - glActiveTexture(GL_TEXTURE0); - glDisable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE1); - glDisable(GL_TEXTURE_1D); - glActiveTexture(GL_TEXTURE2); - glDisable(GL_TEXTURE_2D); - glActiveTexture(GL_TEXTURE3); - glDisable(GL_TEXTURE_2D); - - glDisableClientState(GL_VERTEX_ATTRIB_ARRAY8_NV); - glDisableClientState(GL_VERTEX_ATTRIB_ARRAY9_NV); - glDisableClientState(GL_VERTEX_ATTRIB_ARRAY10_NV); - glDisableClientState(GL_VERTEX_ATTRIB_ARRAY11_NV); - - GlobalOpenGL_debugAssertNoErrors(); - g_vertexProgram_enabled = false; -} - -class GLstringNV -{ -public: - const GLubyte* m_string; - const GLint m_length; - GLstringNV(const char* string) : m_string(reinterpret_cast(string)), m_length(GLint(string_length(string))) - { - } -}; - -GLstringNV g_light_origin("light_origin"); -GLstringNV g_view_origin("view_origin"); -GLstringNV g_light_color("light_color"); -GLstringNV g_bumpGLSL_scale("bump_scale"); -GLstringNV g_specular_exponent("specular_exponent"); - -void setVertexProgramEnvironment(const Vector3& localViewer) -{ - Matrix4 local2light(g_matrix4_identity); - matrix4_translate_by_vec3(local2light, Vector3(0.5, 0.5, 0.5)); - matrix4_scale_by_vec3(local2light, Vector3(0.5, 0.5, 0.5)); - matrix4_scale_by_vec3(local2light, Vector3(1.0 / 512.0, 1.0 / 512.0, 1.0 / 512.0)); - matrix4_translate_by_vec3(local2light, vector3_negated(localViewer)); - - glActiveTexture(GL_TEXTURE3); - glClientActiveTexture(GL_TEXTURE3); - - glMatrixMode(GL_TEXTURE); - glLoadMatrixf(reinterpret_cast(&local2light)); - glMatrixMode(GL_MODELVIEW); - - glTrackMatrixNV(GL_VERTEX_PROGRAM_NV, 0, GL_MODELVIEW_PROJECTION_NV, GL_IDENTITY_NV); - glTrackMatrixNV(GL_VERTEX_PROGRAM_NV, 4, GL_TEXTURE0_ARB, GL_IDENTITY_NV); - - // view origin - //qglProgramNamedParameter4fNV(m_fragment_program, g_view_origin.m_length, g_view_origin.m_string, localViewer.x(), localViewer.y(), localViewer.z(), 0); - - // light origin - glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 8, localViewer.x(), localViewer.y(), localViewer.z(), 1.0f); - - // light colour - glCombinerParameterfNV(GL_CONSTANT_COLOR0_NV, 1, 1, 1, 1) - - // bump scale - //qglProgramNamedParameter4fNV(m_fragment_program, g_bumpGLSL_scale.m_length, g_bumpGLSL_scale.m_string, 1, 0, 0, 0); - - // specular exponent - //qglProgramNamedParameter4fNV(m_fragment_program, g_specular_exponent.m_length, g_specular_exponent.m_string, 32, 0, 0, 0); - - GlobalOpenGL_debugAssertNoErrors(); -} - -#endif - - -bool g_vertexArray_enabled = false; -bool g_normalArray_enabled = false; -bool g_texcoordArray_enabled = false; -bool g_colorArray_enabled = false; - -inline bool OpenGLState_less(const OpenGLState& self, const OpenGLState& other) -{ - //! Sort by sort-order override. - if(self.m_sort != other.m_sort) - { - return self.m_sort < other.m_sort; - } - //! Sort by texture handle. - if(self.m_texture != other.m_texture) - { - return self.m_texture < other.m_texture; - } - if(self.m_texture1 != other.m_texture1) - { - return self.m_texture1 < other.m_texture1; - } - if(self.m_texture2 != other.m_texture2) - { - return self.m_texture2 < other.m_texture2; - } - if(self.m_texture3 != other.m_texture3) - { - return self.m_texture3 < other.m_texture3; - } - if(self.m_texture4 != other.m_texture4) - { - return self.m_texture4 < other.m_texture4; - } - if(self.m_texture5 != other.m_texture5) - { - return self.m_texture5 < other.m_texture5; - } - if(self.m_texture6 != other.m_texture6) - { - return self.m_texture6 < other.m_texture6; - } - if(self.m_texture7 != other.m_texture7) - { - return self.m_texture7 < other.m_texture7; - } - //! Sort by state bit-vector. - if(self.m_state != other.m_state) - { - return self.m_state < other.m_state; - } - //! Comparing address makes sure states are never equal. - return &self < &other; -} - -void OpenGLState_constructDefault(OpenGLState& state) -{ - state.m_state = RENDER_DEFAULT; - - state.m_texture = 0; - state.m_texture1 = 0; - state.m_texture2 = 0; - state.m_texture3 = 0; - state.m_texture4 = 0; - state.m_texture5 = 0; - state.m_texture6 = 0; - state.m_texture7 = 0; - - state.m_colour[0] = 1; - state.m_colour[1] = 1; - state.m_colour[2] = 1; - state.m_colour[3] = 1; - - state.m_depthfunc = GL_LESS; - - state.m_blend_src = GL_SRC_ALPHA; - state.m_blend_dst = GL_ONE_MINUS_SRC_ALPHA; - - state.m_alphafunc = GL_ALWAYS; - state.m_alpharef = 0; - - state.m_linewidth = 1; - state.m_pointsize = 1; - - state.m_linestipple_factor = 1; - state.m_linestipple_pattern = 0xaaaa; - - state.m_fog = OpenGLFogState(); -} - - - - -/// \brief A container of Renderable references. -/// May contain the same Renderable multiple times, with different transforms. -class OpenGLStateBucket -{ -public: - struct RenderTransform - { - const Matrix4* m_transform; - const OpenGLRenderable *m_renderable; - const RendererLight* m_light; - - RenderTransform(const OpenGLRenderable& renderable, const Matrix4& transform, const RendererLight* light) - : m_transform(&transform), m_renderable(&renderable), m_light(light) - { - } - }; - - typedef std::vector Renderables; - -private: - - OpenGLState m_state; - Renderables m_renderables; - -public: - OpenGLStateBucket() - { - } - void addRenderable(const OpenGLRenderable& renderable, const Matrix4& modelview, const RendererLight* light = 0) - { - m_renderables.push_back(RenderTransform(renderable, modelview, light)); - } - - OpenGLState& state() - { - return m_state; - } - - void render(OpenGLState& current, unsigned int globalstate, const Vector3& viewer); -}; - -#define LIGHT_SHADER_DEBUG 0 - -#if LIGHT_SHADER_DEBUG -typedef std::vector LightDebugShaders; -LightDebugShaders g_lightDebugShaders; -#endif - -class OpenGLStateLess -{ -public: - bool operator()(const OpenGLState& self, const OpenGLState& other) const - { - return OpenGLState_less(self, other); - } -}; - -typedef ConstReference OpenGLStateReference; -typedef std::map OpenGLStates; -OpenGLStates g_state_sorted; - -class OpenGLStateBucketAdd -{ - OpenGLStateBucket& m_bucket; - const OpenGLRenderable& m_renderable; - const Matrix4& m_modelview; -public: - typedef const RendererLight& first_argument_type; - - OpenGLStateBucketAdd(OpenGLStateBucket& bucket, const OpenGLRenderable& renderable, const Matrix4& modelview) : - m_bucket(bucket), m_renderable(renderable), m_modelview(modelview) - { - } - void operator()(const RendererLight& light) - { - m_bucket.addRenderable(m_renderable, m_modelview, &light); - } -}; - -class CountLights -{ - std::size_t m_count; -public: - typedef RendererLight& first_argument_type; - - CountLights() : m_count(0) - { - } - void operator()(const RendererLight& light) - { - ++m_count; - } - std::size_t count() const - { - return m_count; - } -}; - -class OpenGLShader : public Shader -{ - typedef std::list Passes; - Passes m_passes; - IShader* m_shader; - std::size_t m_used; - ModuleObservers m_observers; -public: - OpenGLShader() : m_shader(0), m_used(0) - { - } - ~OpenGLShader() - { - } - void construct(const char* name); - void destroy() - { - if(m_shader) - { - m_shader->DecRef(); - } - m_shader = 0; - - for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) - { - delete *i; - } - m_passes.clear(); - } - void addRenderable(const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights) - { - for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) - { -#if LIGHT_SHADER_DEBUG - if(((*i)->state().m_state & RENDER_BUMP) != 0) - { - if(lights != 0) - { - CountLights counter; - lights->forEachLight(makeCallback1(counter)); - globalOutputStream() << "count = " << counter.count() << "\n"; - for(std::size_t i = 0; i < counter.count(); ++i) - { - g_lightDebugShaders[counter.count()]->addRenderable(renderable, modelview); - } - } - } - else -#else - if(((*i)->state().m_state & RENDER_BUMP) != 0) - { - if(lights != 0) - { - OpenGLStateBucketAdd add(*(*i), renderable, modelview); - lights->forEachLight(makeCallback1(add)); - } - } - else -#endif - { - (*i)->addRenderable(renderable, modelview); - } - } - } - void incrementUsed() - { - if(++m_used == 1 && m_shader != 0) - { - m_shader->SetInUse(true); - } - } - void decrementUsed() - { - if(--m_used == 0 && m_shader != 0) - { - m_shader->SetInUse(false); - } - } - bool realised() const - { - return m_shader != 0; - } - void attach(ModuleObserver& observer) - { - if(realised()) - { - observer.realise(); - } - m_observers.attach(observer); - } - void detach(ModuleObserver& observer) - { - if(realised()) - { - observer.unrealise(); - } - m_observers.detach(observer); - } - void realise(const CopiedString& name) - { - construct(name.c_str()); - - if(m_used != 0 && m_shader != 0) - { - m_shader->SetInUse(true); - } - - for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) - { - g_state_sorted.insert(OpenGLStates::value_type(OpenGLStateReference((*i)->state()), *i)); - } - - m_observers.realise(); - } - void unrealise() - { - m_observers.unrealise(); - - for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) - { - g_state_sorted.erase(OpenGLStateReference((*i)->state())); - } - - destroy(); - } - qtexture_t& getTexture() const - { - ASSERT_NOTNULL(m_shader); - return *m_shader->getTexture(); - } - unsigned int getFlags() const - { - ASSERT_NOTNULL(m_shader); - return m_shader->getFlags(); - } - IShader& getShader() const - { - ASSERT_NOTNULL(m_shader); - return *m_shader; - } - OpenGLState& appendDefaultPass() - { - m_passes.push_back(new OpenGLStateBucket); - OpenGLState& state = m_passes.back()->state(); - OpenGLState_constructDefault(state); - return state; - } -}; - - -inline bool lightEnabled(const RendererLight& light, const LightCullable& cullable) -{ - return cullable.testLight(light); -} - -typedef std::set RendererLights; - -#define DEBUG_LIGHT_SYNC 0 - -class LinearLightList : public LightList -{ - LightCullable& m_cullable; - RendererLights& m_allLights; - Callback m_evaluateChanged; - - typedef std::list Lights; - mutable Lights m_lights; - mutable bool m_lightsChanged; -public: - LinearLightList(LightCullable& cullable, RendererLights& lights, const Callback& evaluateChanged) : - m_cullable(cullable), m_allLights(lights), m_evaluateChanged(evaluateChanged) - { - m_lightsChanged = true; - } - void evaluateLights() const - { - m_evaluateChanged(); - if(m_lightsChanged) - { - m_lightsChanged = false; - - m_lights.clear(); - m_cullable.clearLights(); - for(RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i) - { - if(lightEnabled(*(*i), m_cullable)) - { - m_lights.push_back(*i); - m_cullable.insertLight(*(*i)); - } - } - } -#if(DEBUG_LIGHT_SYNC) - else - { - Lights lights; - for(RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i) - { - if(lightEnabled(*(*i), m_cullable)) - { - lights.push_back(*i); - } - } - ASSERT_MESSAGE( - !std::lexicographical_compare(lights.begin(), lights.end(), m_lights.begin(), m_lights.end()) - && !std::lexicographical_compare(m_lights.begin(), m_lights.end(), lights.begin(), lights.end()), - "lights out of sync" - ); - } -#endif - } - void forEachLight(const RendererLightCallback& callback) const - { - evaluateLights(); - - for(Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i) - { - callback(*(*i)); - } - } - void lightsChanged() const - { - m_lightsChanged = true; - } -}; - -inline void setFogState(const OpenGLFogState& state) -{ - glFogi(GL_FOG_MODE, state.mode); - glFogf(GL_FOG_DENSITY, state.density); - glFogf(GL_FOG_START, state.start); - glFogf(GL_FOG_END, state.end); - glFogi(GL_FOG_INDEX, state.index); - glFogfv(GL_FOG_COLOR, vector4_to_array(state.colour)); -} - -#define DEBUG_SHADERS 0 - -class OpenGLShaderCache : public ShaderCache, public TexturesCacheObserver, public ModuleObserver -{ - class CreateOpenGLShader - { - OpenGLShaderCache* m_cache; - public: - explicit CreateOpenGLShader(OpenGLShaderCache* cache = 0) - : m_cache(cache) - { - } - OpenGLShader* construct(const CopiedString& name) - { - OpenGLShader* shader = new OpenGLShader; - if(m_cache->realised()) - { - shader->realise(name); - } - return shader; - } - void destroy(OpenGLShader* shader) - { - if(m_cache->realised()) - { - shader->unrealise(); - } - delete shader; - } - }; - - typedef HashedCache, CreateOpenGLShader> Shaders; - Shaders m_shaders; - std::size_t m_unrealised; - - bool m_lightingEnabled; - bool m_lightingSupported; - bool m_useShaderLanguage; - -public: - OpenGLShaderCache() - : m_shaders(CreateOpenGLShader(this)), - m_unrealised(3), // wait until shaders, gl-context and textures are realised before creating any render-states - m_lightingEnabled(true), - m_lightingSupported(false), - m_useShaderLanguage(false), - m_lightsChanged(true), - m_traverseRenderablesMutex(false) - { - } - ~OpenGLShaderCache() - { - for(Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i) - { - globalOutputStream() << "leaked shader: " << makeQuoted((*i).key.c_str()) << "\n"; - } - } - Shader* capture(const char* name) - { - ASSERT_MESSAGE(name[0] == '$' - || *name == '[' - || *name == '<' - || *name == '(' - || strchr(name, '\\') == 0, "shader name contains invalid characters: \"" << name << "\""); -#if DEBUG_SHADERS - globalOutputStream() << "shaders capture: " << makeQuoted(name) << '\n'; -#endif - return m_shaders.capture(name).get(); - } - void release(const char *name) - { -#if DEBUG_SHADERS - globalOutputStream() << "shaders release: " << makeQuoted(name) << '\n'; -#endif - m_shaders.release(name); - } - void render(RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer) - { - glMatrixMode(GL_PROJECTION); - glLoadMatrixf(reinterpret_cast(&projection)); - #if 0 - //qglGetFloatv(GL_PROJECTION_MATRIX, reinterpret_cast(&projection)); - #endif - - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(reinterpret_cast(&modelview)); - #if 0 - //qglGetFloatv(GL_MODELVIEW_MATRIX, reinterpret_cast(&modelview)); - #endif - - ASSERT_MESSAGE(realised(), "render states are not realised"); - - // global settings that are not set in renderstates - glFrontFace(GL_CW); - glCullFace(GL_BACK); - glPolygonOffset(-1, 1); - { - const GLubyte pattern[132] = { - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, - 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55 - }; - glPolygonStipple(pattern); - } - glEnableClientState(GL_VERTEX_ARRAY); - g_vertexArray_enabled = true; - glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); - - if(GlobalOpenGL().GL_1_3()) - { - glActiveTexture(GL_TEXTURE0); - glClientActiveTexture(GL_TEXTURE0); - } - - if(GlobalOpenGL().ARB_shader_objects()) - { - glUseProgramObjectARB(0); - glDisableVertexAttribArrayARB(c_attr_TexCoord0); - glDisableVertexAttribArrayARB(c_attr_Tangent); - glDisableVertexAttribArrayARB(c_attr_Binormal); - } - - if(globalstate & RENDER_TEXTURE) - { - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); - } - - OpenGLState current; - OpenGLState_constructDefault(current); - current.m_sort = OpenGLState::eSortFirst; - - // default renderstate settings - glLineStipple(current.m_linestipple_factor, current.m_linestipple_pattern); - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); - glDisable(GL_LIGHTING); - glDisable(GL_TEXTURE_2D); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - g_texcoordArray_enabled = false; - glDisableClientState(GL_COLOR_ARRAY); - g_colorArray_enabled = false; - glDisableClientState(GL_NORMAL_ARRAY); - g_normalArray_enabled = false; - glDisable(GL_BLEND); - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDisable(GL_CULL_FACE); - glShadeModel(GL_FLAT); - glDisable(GL_DEPTH_TEST); - glDepthMask(GL_FALSE); - glDisable(GL_ALPHA_TEST); - glDisable(GL_LINE_STIPPLE); - glDisable(GL_POLYGON_STIPPLE); - glDisable(GL_POLYGON_OFFSET_LINE); - - glBindTexture(GL_TEXTURE_2D, 0); - glColor4f(1,1,1,1); - glDepthFunc(GL_LESS); - glAlphaFunc(GL_ALWAYS, 0); - glLineWidth(1); - glPointSize(1); - - glHint(GL_FOG_HINT, GL_NICEST); - glDisable(GL_FOG); - setFogState(OpenGLFogState()); - - GlobalOpenGL_debugAssertNoErrors(); - - debug_string("begin rendering"); - for(OpenGLStates::iterator i = g_state_sorted.begin(); i != g_state_sorted.end(); ++i) - { - (*i).second->render(current, globalstate, viewer); - } - debug_string("end rendering"); - } - void realise() - { - if(--m_unrealised == 0) - { - if(lightingSupported() && lightingEnabled()) - { - if(useShaderLanguage()) - { - g_bumpGLSL.create(); - g_depthFillGLSL.create(); - } - else - { - g_bumpARB.create(); - g_depthFillARB.create(); - } - } - - for(Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i) - { - if(!(*i).value.empty()) - { - (*i).value->realise(i->key); - } - } - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - for(Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i) - { - if(!(*i).value.empty()) - { - (*i).value->unrealise(); - } - } - if(GlobalOpenGL().contextValid && lightingSupported() && lightingEnabled()) - { - if(useShaderLanguage()) - { - g_bumpGLSL.destroy(); - g_depthFillGLSL.destroy(); - } - else - { - g_bumpARB.destroy(); - g_depthFillARB.destroy(); - } - } - } - } - bool realised() - { - return m_unrealised == 0; - } - - - bool lightingEnabled() const - { - return m_lightingEnabled; - } - bool lightingSupported() const - { - return m_lightingSupported; - } - bool useShaderLanguage() const - { - return m_useShaderLanguage; - } - void setLighting(bool supported, bool enabled) - { - bool refresh = (m_lightingSupported && m_lightingEnabled) != (supported && enabled); - - if(refresh) - { - unrealise(); - GlobalShaderSystem().setLightingEnabled(supported && enabled); - } - - m_lightingSupported = supported; - m_lightingEnabled = enabled; - - if(refresh) - { - realise(); - } - } - void extensionsInitialised() - { - setLighting(GlobalOpenGL().GL_1_3() - && GlobalOpenGL().ARB_vertex_program() - && GlobalOpenGL().ARB_fragment_program() - && GlobalOpenGL().ARB_shader_objects() - && GlobalOpenGL().ARB_vertex_shader() - && GlobalOpenGL().ARB_fragment_shader() - && GlobalOpenGL().ARB_shading_language_100(), - m_lightingEnabled - ); - - if(!lightingSupported()) - { - globalOutputStream() << "Lighting mode requires OpenGL features not supported by your graphics drivers:\n"; - if(!GlobalOpenGL().GL_1_3()) - { - globalOutputStream() << " GL version 1.3 or better\n"; - } - if(!GlobalOpenGL().ARB_vertex_program()) - { - globalOutputStream() << " GL_ARB_vertex_program\n"; - } - if(!GlobalOpenGL().ARB_fragment_program()) - { - globalOutputStream() << " GL_ARB_fragment_program\n"; - } - if(!GlobalOpenGL().ARB_shader_objects()) - { - globalOutputStream() << " GL_ARB_shader_objects\n"; - } - if(!GlobalOpenGL().ARB_vertex_shader()) - { - globalOutputStream() << " GL_ARB_vertex_shader\n"; - } - if(!GlobalOpenGL().ARB_fragment_shader()) - { - globalOutputStream() << " GL_ARB_fragment_shader\n"; - } - if(!GlobalOpenGL().ARB_shading_language_100()) - { - globalOutputStream() << " GL_ARB_shading_language_100\n"; - } - } - } - void setLightingEnabled(bool enabled) - { - setLighting(m_lightingSupported, enabled); - } - - // light culling - - RendererLights m_lights; - bool m_lightsChanged; - typedef std::map LightLists; - LightLists m_lightLists; - - const LightList& attach(LightCullable& cullable) - { - return (*m_lightLists.insert(LightLists::value_type(&cullable, LinearLightList(cullable, m_lights, EvaluateChangedCaller(*this)))).first).second; - } - void detach(LightCullable& cullable) - { - m_lightLists.erase(&cullable); - } - void changed(LightCullable& cullable) - { - LightLists::iterator i = m_lightLists.find(&cullable); - ASSERT_MESSAGE(i != m_lightLists.end(), "cullable not attached"); - (*i).second.lightsChanged(); - } - void attach(RendererLight& light) - { - ASSERT_MESSAGE(m_lights.find(&light) == m_lights.end(), "light could not be attached"); - m_lights.insert(&light); - changed(light); - } - void detach(RendererLight& light) - { - ASSERT_MESSAGE(m_lights.find(&light) != m_lights.end(), "light could not be detached"); - m_lights.erase(&light); - changed(light); - } - void changed(RendererLight& light) - { - m_lightsChanged = true; - } - void evaluateChanged() - { - if(m_lightsChanged) - { - m_lightsChanged = false; - for(LightLists::iterator i = m_lightLists.begin(); i != m_lightLists.end(); ++i) - { - (*i).second.lightsChanged(); - } - } - } - typedef MemberCaller EvaluateChangedCaller; - - typedef std::set Renderables; - Renderables m_renderables; - mutable bool m_traverseRenderablesMutex; - - // renderables - void attachRenderable(const Renderable& renderable) - { - ASSERT_MESSAGE(!m_traverseRenderablesMutex, "attaching renderable during traversal"); - ASSERT_MESSAGE(m_renderables.find(&renderable) == m_renderables.end(), "renderable could not be attached"); - m_renderables.insert(&renderable); - } - void detachRenderable(const Renderable& renderable) - { - ASSERT_MESSAGE(!m_traverseRenderablesMutex, "detaching renderable during traversal"); - ASSERT_MESSAGE(m_renderables.find(&renderable) != m_renderables.end(), "renderable could not be detached"); - m_renderables.erase(&renderable); - } - void forEachRenderable(const RenderableCallback& callback) const - { - ASSERT_MESSAGE(!m_traverseRenderablesMutex, "for-each during traversal"); - m_traverseRenderablesMutex = true; - for(Renderables::const_iterator i = m_renderables.begin(); i != m_renderables.end(); ++i) - { - callback(*(*i)); - } - m_traverseRenderablesMutex = false; - } -}; - -static OpenGLShaderCache* g_ShaderCache; - -void ShaderCache_extensionsInitialised() -{ - g_ShaderCache->extensionsInitialised(); -} - -void ShaderCache_setBumpEnabled(bool enabled) -{ - g_ShaderCache->setLightingEnabled(enabled); -} - - -Vector3 g_DebugShaderColours[256]; -Shader* g_defaultPointLight = 0; - -void ShaderCache_Construct() -{ - g_ShaderCache = new OpenGLShaderCache; - GlobalTexturesCache().attach(*g_ShaderCache); - GlobalShaderSystem().attach(*g_ShaderCache); - - if(g_pGameDescription->mGameType == "doom3") - { - g_defaultPointLight = g_ShaderCache->capture("lights/defaultPointLight"); - //Shader* overbright = - g_ShaderCache->capture("$OVERBRIGHT"); - -#if LIGHT_SHADER_DEBUG - for(std::size_t i = 0; i < 256; ++i) - { - g_DebugShaderColours[i] = Vector3(i / 256.0, i / 256.0, i / 256.0); - } - - g_DebugShaderColours[0] = Vector3(1, 0, 0); - g_DebugShaderColours[1] = Vector3(1, 0.5, 0); - g_DebugShaderColours[2] = Vector3(1, 1, 0); - g_DebugShaderColours[3] = Vector3(0.5, 1, 0); - g_DebugShaderColours[4] = Vector3(0, 1, 0); - g_DebugShaderColours[5] = Vector3(0, 1, 0.5); - g_DebugShaderColours[6] = Vector3(0, 1, 1); - g_DebugShaderColours[7] = Vector3(0, 0.5, 1); - g_DebugShaderColours[8] = Vector3(0, 0, 1); - g_DebugShaderColours[9] = Vector3(0.5, 0, 1); - g_DebugShaderColours[10] = Vector3(1, 0, 1); - g_DebugShaderColours[11] = Vector3(1, 0, 0.5); - - g_lightDebugShaders.reserve(256); - StringOutputStream buffer(256); - for(std::size_t i = 0; i < 256; ++i) - { - buffer << "(" << g_DebugShaderColours[i].x() << " " << g_DebugShaderColours[i].y() << " " << g_DebugShaderColours[i].z() << ")"; - g_lightDebugShaders.push_back(g_ShaderCache->capture(buffer.c_str())); - buffer.clear(); - } -#endif - } -} - -void ShaderCache_Destroy() -{ - if(g_pGameDescription->mGameType == "doom3") - { - g_ShaderCache->release("lights/defaultPointLight"); - g_ShaderCache->release("$OVERBRIGHT"); - g_defaultPointLight = 0; - -#if LIGHT_SHADER_DEBUG - g_lightDebugShaders.clear(); - StringOutputStream buffer(256); - for(std::size_t i = 0; i < 256; ++i) - { - buffer << "(" << g_DebugShaderColours[i].x() << " " << g_DebugShaderColours[i].y() << " " << g_DebugShaderColours[i].z() << ")"; - g_ShaderCache->release(buffer.c_str()); - } -#endif - } - - GlobalShaderSystem().detach(*g_ShaderCache); - GlobalTexturesCache().detach(*g_ShaderCache); - delete g_ShaderCache; -} - -ShaderCache* GetShaderCache() -{ - return g_ShaderCache; -} - -inline void setTextureState(GLint& current, const GLint& texture, GLenum textureUnit) -{ - if(texture != current) - { - glActiveTexture(textureUnit); - glClientActiveTexture(textureUnit); - glBindTexture(GL_TEXTURE_2D, texture); - GlobalOpenGL_debugAssertNoErrors(); - current = texture; - } -} - -inline void setTextureState(GLint& current, const GLint& texture) -{ - if(texture != current) - { - glBindTexture(GL_TEXTURE_2D, texture); - GlobalOpenGL_debugAssertNoErrors(); - current = texture; - } -} - -inline void setState(unsigned int state, unsigned int delta, unsigned int flag, GLenum glflag) -{ - if(delta & state & flag) - { - glEnable(glflag); - GlobalOpenGL_debugAssertNoErrors(); - } - else if(delta & ~state & flag) - { - glDisable(glflag); - GlobalOpenGL_debugAssertNoErrors(); - } -} - -void OpenGLState_apply(const OpenGLState& self, OpenGLState& current, unsigned int globalstate) -{ - debug_int("sort", int(self.m_sort)); - debug_int("texture", self.m_texture); - debug_int("state", self.m_state); - debug_int("address", int(std::size_t(&self))); - - count_state(); - - if(self.m_state & RENDER_OVERRIDE) - { - globalstate |= RENDER_FILL | RENDER_DEPTHWRITE; - } - - const unsigned int state = self.m_state & globalstate; - const unsigned int delta = state ^ current.m_state; - - GlobalOpenGL_debugAssertNoErrors(); - - GLProgram* program = (state & RENDER_PROGRAM) != 0 ? self.m_program : 0; - - if(program != current.m_program) - { - if(current.m_program != 0) - { - current.m_program->disable(); - glColor4fv(vector4_to_array(current.m_colour)); - debug_colour("cleaning program"); - } - - current.m_program = program; - - if(current.m_program != 0) - { - current.m_program->enable(); - } - } - - if(delta & state & RENDER_FILL) - { - //qglPolygonMode (GL_BACK, GL_LINE); - //qglPolygonMode (GL_FRONT, GL_FILL); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - GlobalOpenGL_debugAssertNoErrors(); - } - else if(delta & ~state & RENDER_FILL) - { - glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); - GlobalOpenGL_debugAssertNoErrors(); - } - - setState(state, delta, RENDER_OFFSETLINE, GL_POLYGON_OFFSET_LINE); - - if(delta & state & RENDER_LIGHTING) - { - glEnable(GL_LIGHTING); - glEnable(GL_COLOR_MATERIAL); - //qglEnable(GL_RESCALE_NORMAL); - glEnableClientState(GL_NORMAL_ARRAY); - GlobalOpenGL_debugAssertNoErrors(); - g_normalArray_enabled = true; - } - else if(delta & ~state & RENDER_LIGHTING) - { - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); - //qglDisable(GL_RESCALE_NORMAL); - glDisableClientState(GL_NORMAL_ARRAY); - GlobalOpenGL_debugAssertNoErrors(); - g_normalArray_enabled = false; - } - - if(delta & state & RENDER_TEXTURE) - { - GlobalOpenGL_debugAssertNoErrors(); - - if(GlobalOpenGL().GL_1_3()) - { - glActiveTexture(GL_TEXTURE0); - glClientActiveTexture(GL_TEXTURE0); - } - - glEnable(GL_TEXTURE_2D); - - glColor4f(1,1,1,self.m_colour[3]); - debug_colour("setting texture"); - - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - GlobalOpenGL_debugAssertNoErrors(); - g_texcoordArray_enabled = true; - } - else if(delta & ~state & RENDER_TEXTURE) - { - if(GlobalOpenGL().GL_1_3()) - { - glActiveTexture(GL_TEXTURE0); - glClientActiveTexture(GL_TEXTURE0); - } - - glDisable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, 0); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - - GlobalOpenGL_debugAssertNoErrors(); - g_texcoordArray_enabled = false; - } - - if(delta & state & RENDER_BLEND) - { -// FIXME: some .TGA are buggy, have a completely empty alpha channel -// if such brushes are rendered in this loop they would be totally transparent with GL_MODULATE -// so I decided using GL_DECAL instead -// if an empty-alpha-channel or nearly-empty texture is used. It will be blank-transparent. -// this could get better if you can get glTexEnviv (GL_TEXTURE_ENV, to work .. patches are welcome - - glEnable(GL_BLEND); - if(GlobalOpenGL().GL_1_3()) - { - glActiveTexture(GL_TEXTURE0); - } - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); - GlobalOpenGL_debugAssertNoErrors(); - } - else if(delta & ~state & RENDER_BLEND) - { - glDisable(GL_BLEND); - if(GlobalOpenGL().GL_1_3()) - { - glActiveTexture(GL_TEXTURE0); - } - glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - GlobalOpenGL_debugAssertNoErrors(); - } - - setState(state, delta, RENDER_CULLFACE, GL_CULL_FACE); - - if(delta & state & RENDER_SMOOTH) - { - glShadeModel(GL_SMOOTH); - GlobalOpenGL_debugAssertNoErrors(); - } - else if(delta & ~state & RENDER_SMOOTH) - { - glShadeModel(GL_FLAT); - GlobalOpenGL_debugAssertNoErrors(); - } - - setState(state, delta, RENDER_SCALED, GL_NORMALIZE); // not GL_RESCALE_NORMAL - - setState(state, delta, RENDER_DEPTHTEST, GL_DEPTH_TEST); - - if(delta & state & RENDER_DEPTHWRITE) - { - glDepthMask(GL_TRUE); - -#if DEBUG_RENDER - GLboolean depthEnabled; - glGetBooleanv(GL_DEPTH_WRITEMASK, &depthEnabled); - ASSERT_MESSAGE(depthEnabled, "failed to set depth buffer mask bit"); -#endif - debug_string("enabled depth-buffer writing"); - - GlobalOpenGL_debugAssertNoErrors(); - } - else if(delta & ~state & RENDER_DEPTHWRITE) - { - glDepthMask(GL_FALSE); - -#if DEBUG_RENDER - GLboolean depthEnabled; - glGetBooleanv(GL_DEPTH_WRITEMASK, &depthEnabled); - ASSERT_MESSAGE(!depthEnabled, "failed to set depth buffer mask bit"); -#endif - debug_string("disabled depth-buffer writing"); - - GlobalOpenGL_debugAssertNoErrors(); - } - - if(delta & state & RENDER_COLOURWRITE) - { - glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - GlobalOpenGL_debugAssertNoErrors(); - } - else if(delta & ~state & RENDER_COLOURWRITE) - { - glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); - GlobalOpenGL_debugAssertNoErrors(); - } - - setState(state, delta, RENDER_ALPHATEST, GL_ALPHA_TEST); - - if(delta & state & RENDER_COLOURARRAY) - { - glEnableClientState(GL_COLOR_ARRAY); - GlobalOpenGL_debugAssertNoErrors(); - debug_colour("enabling color_array"); - g_colorArray_enabled = true; - } - else if(delta & ~state & RENDER_COLOURARRAY) - { - glDisableClientState(GL_COLOR_ARRAY); - glColor4fv(vector4_to_array(self.m_colour)); - debug_colour("cleaning color_array"); - GlobalOpenGL_debugAssertNoErrors(); - g_colorArray_enabled = false; - } - - if(delta & ~state & RENDER_COLOURCHANGE) - { - glColor4fv(vector4_to_array(self.m_colour)); - GlobalOpenGL_debugAssertNoErrors(); - } - - setState(state, delta, RENDER_LINESTIPPLE, GL_LINE_STIPPLE); - setState(state, delta, RENDER_LINESMOOTH, GL_LINE_SMOOTH); - - setState(state, delta, RENDER_POLYGONSTIPPLE, GL_POLYGON_STIPPLE); - setState(state, delta, RENDER_POLYGONSMOOTH, GL_POLYGON_SMOOTH); - - setState(state, delta, RENDER_FOG, GL_FOG); - - if((state & RENDER_FOG) != 0) - { - setFogState(self.m_fog); - GlobalOpenGL_debugAssertNoErrors(); - current.m_fog = self.m_fog; - } - - if(state & RENDER_DEPTHTEST && self.m_depthfunc != current.m_depthfunc) - { - glDepthFunc(self.m_depthfunc); - GlobalOpenGL_debugAssertNoErrors(); - current.m_depthfunc = self.m_depthfunc; - } - - if(state & RENDER_LINESTIPPLE - && (self.m_linestipple_factor != current.m_linestipple_factor - || self.m_linestipple_pattern != current.m_linestipple_pattern)) - { - glLineStipple(self.m_linestipple_factor, self.m_linestipple_pattern); - GlobalOpenGL_debugAssertNoErrors(); - current.m_linestipple_factor = self.m_linestipple_factor; - current.m_linestipple_pattern = self.m_linestipple_pattern; - } - - - if(state & RENDER_ALPHATEST - && ( self.m_alphafunc != current.m_alphafunc - || self.m_alpharef != current.m_alpharef ) ) - { - glAlphaFunc(self.m_alphafunc, self.m_alpharef); - GlobalOpenGL_debugAssertNoErrors(); - current.m_alphafunc = self.m_alphafunc; - current.m_alpharef = self.m_alpharef; - } - - { - GLint texture0 = 0; - GLint texture1 = 0; - GLint texture2 = 0; - GLint texture3 = 0; - GLint texture4 = 0; - GLint texture5 = 0; - GLint texture6 = 0; - GLint texture7 = 0; - //if(state & RENDER_TEXTURE) != 0) - { - texture0 = self.m_texture; - texture1 = self.m_texture1; - texture2 = self.m_texture2; - texture3 = self.m_texture3; - texture4 = self.m_texture4; - texture5 = self.m_texture5; - texture6 = self.m_texture6; - texture7 = self.m_texture7; - } - - if(GlobalOpenGL().GL_1_3()) - { - setTextureState(current.m_texture, texture0, GL_TEXTURE0); - setTextureState(current.m_texture1, texture1, GL_TEXTURE1); - setTextureState(current.m_texture2, texture2, GL_TEXTURE2); - setTextureState(current.m_texture3, texture3, GL_TEXTURE3); - setTextureState(current.m_texture4, texture4, GL_TEXTURE4); - setTextureState(current.m_texture5, texture5, GL_TEXTURE5); - setTextureState(current.m_texture6, texture6, GL_TEXTURE6); - setTextureState(current.m_texture7, texture7, GL_TEXTURE7); - } - else - { - setTextureState(current.m_texture, texture0); - } - } - - - if(state & RENDER_TEXTURE && self.m_colour[3] != current.m_colour[3]) - { - debug_colour("setting alpha"); - glColor4f(1,1,1,self.m_colour[3]); - GlobalOpenGL_debugAssertNoErrors(); - } - - if(!(state & RENDER_TEXTURE) - && (self.m_colour[0] != current.m_colour[0] - || self.m_colour[1] != current.m_colour[1] - || self.m_colour[2] != current.m_colour[2] - || self.m_colour[3] != current.m_colour[3])) - { - glColor4fv(vector4_to_array(self.m_colour)); - debug_colour("setting non-texture"); - GlobalOpenGL_debugAssertNoErrors(); - } - current.m_colour = self.m_colour; - - if(state & RENDER_BLEND - && (self.m_blend_src != current.m_blend_src || self.m_blend_dst != current.m_blend_dst)) - { - glBlendFunc(self.m_blend_src, self.m_blend_dst); - GlobalOpenGL_debugAssertNoErrors(); - current.m_blend_src = self.m_blend_src; - current.m_blend_dst = self.m_blend_dst; - } - - if(!(state & RENDER_FILL) - && self.m_linewidth != current.m_linewidth) - { - glLineWidth(self.m_linewidth); - GlobalOpenGL_debugAssertNoErrors(); - current.m_linewidth = self.m_linewidth; - } - - if(!(state & RENDER_FILL) - && self.m_pointsize != current.m_pointsize) - { - glPointSize(self.m_pointsize); - GlobalOpenGL_debugAssertNoErrors(); - current.m_pointsize = self.m_pointsize; - } - - current.m_state = state; - - GlobalOpenGL_debugAssertNoErrors(); -} - -void Renderables_flush(OpenGLStateBucket::Renderables& renderables, OpenGLState& current, unsigned int globalstate, const Vector3& viewer) -{ - const Matrix4* transform = 0; - glPushMatrix(); - for(OpenGLStateBucket::Renderables::const_iterator i = renderables.begin(); i != renderables.end(); ++i) - { - //qglLoadMatrixf(i->m_transform); - if(!transform || (transform != (*i).m_transform && !matrix4_affine_equal(*transform, *(*i).m_transform))) - { - count_transform(); - transform = (*i).m_transform; - glPopMatrix(); - glPushMatrix(); - glMultMatrixf(reinterpret_cast(transform)); - glFrontFace(((current.m_state & RENDER_CULLFACE) != 0 && matrix4_handedness(*transform) == MATRIX4_RIGHTHANDED) ? GL_CW : GL_CCW); - } - - count_prim(); - - if(current.m_program != 0 && (*i).m_light != 0) - { - const IShader& lightShader = static_cast((*i).m_light->getShader())->getShader(); - if(lightShader.firstLayer() != 0) - { - GLuint attenuation_xy = lightShader.firstLayer()->texture()->texture_number; - GLuint attenuation_z = lightShader.lightFalloffImage() != 0 - ? lightShader.lightFalloffImage()->texture_number - : static_cast(g_defaultPointLight)->getShader().lightFalloffImage()->texture_number; - - setTextureState(current.m_texture3, attenuation_xy, GL_TEXTURE3); - glActiveTexture(GL_TEXTURE3); - glBindTexture(GL_TEXTURE_2D, attenuation_xy); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); - - setTextureState(current.m_texture4, attenuation_z, GL_TEXTURE4); - glActiveTexture(GL_TEXTURE4); - glBindTexture(GL_TEXTURE_2D, attenuation_z); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - - AABB lightBounds((*i).m_light->aabb()); - - Matrix4 world2light(g_matrix4_identity); - - if((*i).m_light->isProjected()) - { - world2light = (*i).m_light->projection(); - matrix4_multiply_by_matrix4(world2light, matrix4_transposed((*i).m_light->rotation())); - matrix4_translate_by_vec3(world2light, vector3_negated(lightBounds.origin)); // world->lightBounds - } - if(!(*i).m_light->isProjected()) - { - matrix4_translate_by_vec3(world2light, Vector3(0.5f, 0.5f, 0.5f)); - matrix4_scale_by_vec3(world2light, Vector3(0.5f, 0.5f, 0.5f)); - matrix4_scale_by_vec3(world2light, Vector3(1.0f / lightBounds.extents.x(), 1.0f / lightBounds.extents.y(), 1.0f / lightBounds.extents.z())); - matrix4_multiply_by_matrix4(world2light, matrix4_transposed((*i).m_light->rotation())); - matrix4_translate_by_vec3(world2light, vector3_negated(lightBounds.origin)); // world->lightBounds - } - - current.m_program->setParameters(viewer, *(*i).m_transform, lightBounds.origin + (*i).m_light->offset(), (*i).m_light->colour(), world2light); - debug_string("set lightBounds parameters"); - } - } - - (*i).m_renderable->render(current.m_state); - } - glPopMatrix(); - renderables.clear(); -} - -void OpenGLStateBucket::render(OpenGLState& current, unsigned int globalstate, const Vector3& viewer) -{ - if((globalstate & m_state.m_state & RENDER_SCREEN) != 0) - { - OpenGLState_apply(m_state, current, globalstate); - debug_colour("screen fill"); - - glMatrixMode(GL_PROJECTION); - glPushMatrix(); - glLoadMatrixf(reinterpret_cast(&g_matrix4_identity)); - - glMatrixMode(GL_MODELVIEW); - glPushMatrix(); - glLoadMatrixf(reinterpret_cast(&g_matrix4_identity)); - - glBegin(GL_QUADS); - glVertex3f(-1, -1, 0); - glVertex3f(1, -1, 0); - glVertex3f(1, 1, 0); - glVertex3f(-1, 1, 0); - glEnd(); - - glMatrixMode(GL_PROJECTION); - glPopMatrix(); - - glMatrixMode(GL_MODELVIEW); - glPopMatrix(); - } - else if(!m_renderables.empty()) - { - OpenGLState_apply(m_state, current, globalstate); - Renderables_flush(m_renderables, current, globalstate, viewer); - } -} - - -class OpenGLStateMap : public OpenGLStateLibrary -{ - typedef std::map States; - States m_states; -public: - ~OpenGLStateMap() - { - ASSERT_MESSAGE(m_states.empty(), "OpenGLStateMap::~OpenGLStateMap: not empty"); - } - - typedef States::iterator iterator; - iterator begin() - { - return m_states.begin(); - } - iterator end() - { - return m_states.end(); - } - - void getDefaultState(OpenGLState& state) const - { - OpenGLState_constructDefault(state); - } - - void insert(const char* name, const OpenGLState& state) - { - bool inserted = m_states.insert(States::value_type(name, state)).second; - ASSERT_MESSAGE(inserted, "OpenGLStateMap::insert: " << name << " already exists"); - } - void erase(const char* name) - { - std::size_t count = m_states.erase(name); - ASSERT_MESSAGE(count == 1, "OpenGLStateMap::erase: " << name << " does not exist"); - } - - iterator find(const char* name) - { - return m_states.find(name); - } -}; - -OpenGLStateMap* g_openglStates = 0; - -inline GLenum convertBlendFactor(BlendFactor factor) -{ - switch(factor) - { - case BLEND_ZERO: - return GL_ZERO; - case BLEND_ONE: - return GL_ONE; - case BLEND_SRC_COLOUR: - return GL_SRC_COLOR; - case BLEND_ONE_MINUS_SRC_COLOUR: - return GL_ONE_MINUS_SRC_COLOR; - case BLEND_SRC_ALPHA: - return GL_SRC_ALPHA; - case BLEND_ONE_MINUS_SRC_ALPHA: - return GL_ONE_MINUS_SRC_ALPHA; - case BLEND_DST_COLOUR: - return GL_DST_COLOR; - case BLEND_ONE_MINUS_DST_COLOUR: - return GL_ONE_MINUS_DST_COLOR; - case BLEND_DST_ALPHA: - return GL_DST_ALPHA; - case BLEND_ONE_MINUS_DST_ALPHA: - return GL_ONE_MINUS_DST_ALPHA; - case BLEND_SRC_ALPHA_SATURATE: - return GL_SRC_ALPHA_SATURATE; - } - return GL_ZERO; -} - -/// \todo Define special-case shaders in a data file. -void OpenGLShader::construct(const char* name) -{ - OpenGLState& state = appendDefaultPass(); - switch(name[0]) - { - case '(': - sscanf(name, "(%g %g %g)", &state.m_colour[0], &state.m_colour[1], &state.m_colour[2]); - state.m_colour[3] = 1.0f; - state.m_state = RENDER_FILL|RENDER_LIGHTING|RENDER_DEPTHTEST|RENDER_CULLFACE|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortFullbright; - break; - - case '[': - sscanf(name, "[%g %g %g]", &state.m_colour[0], &state.m_colour[1], &state.m_colour[2]); - state.m_colour[3] = 0.5f; - state.m_state = RENDER_FILL|RENDER_LIGHTING|RENDER_DEPTHTEST|RENDER_CULLFACE|RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_BLEND; - state.m_sort = OpenGLState::eSortTranslucent; - break; - - case '<': - sscanf(name, "<%g %g %g>", &state.m_colour[0], &state.m_colour[1], &state.m_colour[2]); - state.m_colour[3] = 1; - state.m_state = RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortFullbright; - state.m_depthfunc = GL_LESS; - state.m_linewidth = 1; - state.m_pointsize = 1; - break; - - case '$': - { - OpenGLStateMap::iterator i = g_openglStates->find(name); - if(i != g_openglStates->end()) - { - state = (*i).second; - break; - } - } - if(string_equal(name+1, "POINT")) - { - state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortControlFirst; - state.m_pointsize = 4; - } - else if(string_equal(name+1, "SELPOINT")) - { - state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortControlFirst + 1; - state.m_pointsize = 4; - } - else if(string_equal(name+1, "BIGPOINT")) - { - state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortControlFirst; - state.m_pointsize = 6; - } - else if(string_equal(name+1, "PIVOT")) - { - state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHTEST|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortGUI1; - state.m_linewidth = 2; - state.m_depthfunc = GL_LEQUAL; - - OpenGLState& hiddenLine = appendDefaultPass(); - hiddenLine.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHTEST|RENDER_LINESTIPPLE; - hiddenLine.m_sort = OpenGLState::eSortGUI0; - hiddenLine.m_linewidth = 2; - hiddenLine.m_depthfunc = GL_GREATER; - } - else if(string_equal(name+1, "LATTICE")) - { - state.m_colour[0] = 1; - state.m_colour[1] = 0.5; - state.m_colour[2] = 0; - state.m_colour[3] = 1; - state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortControlFirst; - } - else if(string_equal(name+1, "WIREFRAME")) - { - state.m_state = RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortFullbright; - } - else if(string_equal(name+1, "CAM_HIGHLIGHT")) - { - state.m_colour[0] = 1; - state.m_colour[1] = 0; - state.m_colour[2] = 0; - state.m_colour[3] = 0.3f; - state.m_state = RENDER_FILL|RENDER_DEPTHTEST|RENDER_CULLFACE|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortHighlight; - state.m_depthfunc = GL_LEQUAL; - } - else if(string_equal(name+1, "CAM_OVERLAY")) - { -#if 0 - state.m_state = RENDER_CULLFACE|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortOverlayFirst; -#else - state.m_state = RENDER_CULLFACE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_OFFSETLINE; - state.m_sort = OpenGLState::eSortOverlayFirst + 1; - state.m_depthfunc = GL_LEQUAL; - - OpenGLState& hiddenLine = appendDefaultPass(); - hiddenLine.m_colour[0] = 0.75; - hiddenLine.m_colour[1] = 0.75; - hiddenLine.m_colour[2] = 0.75; - hiddenLine.m_colour[3] = 1; - hiddenLine.m_state = RENDER_CULLFACE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_OFFSETLINE|RENDER_LINESTIPPLE; - hiddenLine.m_sort = OpenGLState::eSortOverlayFirst; - hiddenLine.m_depthfunc = GL_GREATER; - hiddenLine.m_linestipple_factor = 2; -#endif - } - else if(string_equal(name+1, "XY_OVERLAY")) - { - state.m_colour[0] = g_xywindow_globals.color_selbrushes[0]; - state.m_colour[1] = g_xywindow_globals.color_selbrushes[1]; - state.m_colour[2] = g_xywindow_globals.color_selbrushes[2]; - state.m_colour[3] = 1; - state.m_state = RENDER_COLOURWRITE | RENDER_LINESTIPPLE; - state.m_sort = OpenGLState::eSortOverlayFirst; - state.m_linewidth = 2; - state.m_linestipple_factor = 3; - } - else if(string_equal(name+1, "DEBUG_CLIPPED")) - { - state.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortLast; - } - else if(string_equal(name+1, "POINTFILE")) - { - state.m_colour[0] = 1; - state.m_colour[1] = 0; - state.m_colour[2] = 0; - state.m_colour[3] = 1; - state.m_state = RENDER_DEPTHTEST | RENDER_COLOURWRITE | RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortFullbright; - state.m_linewidth = 4; - } - else if(string_equal(name+1, "LIGHT_SPHERE")) - { - state.m_colour[0] = .15f * .95f; - state.m_colour[1] = .15f * .95f; - state.m_colour[2] = .15f * .95f; - state.m_colour[3] = 1; - state.m_state = RENDER_CULLFACE | RENDER_DEPTHTEST | RENDER_BLEND | RENDER_FILL | RENDER_COLOURWRITE | RENDER_DEPTHWRITE; - state.m_blend_src = GL_ONE; - state.m_blend_dst = GL_ONE; - state.m_sort = OpenGLState::eSortTranslucent; - } - else if(string_equal(name+1, "Q3MAP2_LIGHT_SPHERE")) - { - state.m_colour[0] = .05f; - state.m_colour[1] = .05f; - state.m_colour[2] = .05f; - state.m_colour[3] = 1; - state.m_state = RENDER_CULLFACE | RENDER_DEPTHTEST | RENDER_BLEND | RENDER_FILL; - state.m_blend_src = GL_ONE; - state.m_blend_dst = GL_ONE; - state.m_sort = OpenGLState::eSortTranslucent; - } - else if(string_equal(name+1, "WIRE_OVERLAY")) - { -#if 0 - state.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE; - state.m_sort = OpenGLState::eSortOverlayFirst; -#else - state.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE; - state.m_sort = OpenGLState::eSortGUI1; - state.m_depthfunc = GL_LEQUAL; - - OpenGLState& hiddenLine = appendDefaultPass(); - hiddenLine.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE | RENDER_LINESTIPPLE; - hiddenLine.m_sort = OpenGLState::eSortGUI0; - hiddenLine.m_depthfunc = GL_GREATER; -#endif - } - else if(string_equal(name+1, "FLATSHADE_OVERLAY")) - { - state.m_state = RENDER_CULLFACE | RENDER_LIGHTING | RENDER_SMOOTH | RENDER_SCALED | RENDER_COLOURARRAY | RENDER_FILL | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE; - state.m_sort = OpenGLState::eSortGUI1; - state.m_depthfunc = GL_LEQUAL; - - OpenGLState& hiddenLine = appendDefaultPass(); - hiddenLine.m_state = RENDER_CULLFACE | RENDER_LIGHTING | RENDER_SMOOTH | RENDER_SCALED | RENDER_COLOURARRAY | RENDER_FILL | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE | RENDER_POLYGONSTIPPLE; - hiddenLine.m_sort = OpenGLState::eSortGUI0; - hiddenLine.m_depthfunc = GL_GREATER; - } - else if(string_equal(name+1, "CLIPPER_OVERLAY")) - { - state.m_colour[0] = g_xywindow_globals.color_clipper[0]; - state.m_colour[1] = g_xywindow_globals.color_clipper[1]; - state.m_colour[2] = g_xywindow_globals.color_clipper[2]; - state.m_colour[3] = 1; - state.m_state = RENDER_CULLFACE | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_FILL | RENDER_POLYGONSTIPPLE; - state.m_sort = OpenGLState::eSortOverlayFirst; - } - else if(string_equal(name+1, "OVERBRIGHT")) - { - const float lightScale = 2; - state.m_colour[0] = lightScale * 0.5f; - state.m_colour[1] = lightScale * 0.5f; - state.m_colour[2] = lightScale * 0.5f; - state.m_colour[3] = 0.5; - state.m_state = RENDER_FILL|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_SCREEN; - state.m_sort = OpenGLState::eSortOverbrighten; - state.m_blend_src = GL_DST_COLOR; - state.m_blend_dst = GL_SRC_COLOR; - } - else - { - // default to something recognisable.. =) - ERROR_MESSAGE("hardcoded renderstate not found"); - state.m_colour[0] = 1; - state.m_colour[1] = 0; - state.m_colour[2] = 1; - state.m_colour[3] = 1; - state.m_state = RENDER_COLOURWRITE | RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortFirst; - } - break; - default: - // construction from IShader - m_shader = QERApp_Shader_ForName(name); - - if(g_ShaderCache->lightingSupported() && g_ShaderCache->lightingEnabled() && m_shader->getBump() != 0 && m_shader->getBump()->texture_number != 0) // is a bump shader - { - state.m_state = RENDER_FILL | RENDER_CULLFACE | RENDER_TEXTURE | RENDER_DEPTHTEST | RENDER_DEPTHWRITE | RENDER_COLOURWRITE | RENDER_PROGRAM; - state.m_colour[0] = 0; - state.m_colour[1] = 0; - state.m_colour[2] = 0; - state.m_colour[3] = 1; - state.m_sort = OpenGLState::eSortOpaque; - - if(g_ShaderCache->useShaderLanguage()) - { - state.m_program = &g_depthFillGLSL; - } - else - { - state.m_program = &g_depthFillARB; - } - - OpenGLState& bumpPass = appendDefaultPass(); - bumpPass.m_texture = m_shader->getDiffuse()->texture_number; - bumpPass.m_texture1 = m_shader->getBump()->texture_number; - bumpPass.m_texture2 = m_shader->getSpecular()->texture_number; - - bumpPass.m_state = RENDER_BLEND|RENDER_FILL|RENDER_CULLFACE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_SMOOTH|RENDER_BUMP|RENDER_PROGRAM; - - if(g_ShaderCache->useShaderLanguage()) - { - bumpPass.m_state |= RENDER_LIGHTING; - bumpPass.m_program = &g_bumpGLSL; - } - else - { - bumpPass.m_program = &g_bumpARB; - } - - bumpPass.m_depthfunc = GL_LEQUAL; - bumpPass.m_sort = OpenGLState::eSortMultiFirst; - bumpPass.m_blend_src = GL_ONE; - bumpPass.m_blend_dst = GL_ONE; - } - else - { - state.m_texture = m_shader->getTexture()->texture_number; - - state.m_state = RENDER_FILL|RENDER_TEXTURE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_LIGHTING|RENDER_SMOOTH; - if((m_shader->getFlags() & QER_CULL) != 0) - { - if(m_shader->getCull() == IShader::eCullBack) - { - state.m_state |= RENDER_CULLFACE; - } - } - else - { - state.m_state |= RENDER_CULLFACE; - } - if((m_shader->getFlags() & QER_ALPHATEST) != 0) - { - state.m_state |= RENDER_ALPHATEST; - IShader::EAlphaFunc alphafunc; - m_shader->getAlphaFunc(&alphafunc, &state.m_alpharef); - switch(alphafunc) - { - case IShader::eAlways: - state.m_alphafunc = GL_ALWAYS; - case IShader::eEqual: - state.m_alphafunc = GL_EQUAL; - case IShader::eLess: - state.m_alphafunc = GL_LESS; - case IShader::eGreater: - state.m_alphafunc = GL_GREATER; - case IShader::eLEqual: - state.m_alphafunc = GL_LEQUAL; - case IShader::eGEqual: - state.m_alphafunc = GL_GEQUAL; - } - } - reinterpret_cast(state.m_colour) = m_shader->getTexture()->color; - state.m_colour[3] = 1.0f; - - if((m_shader->getFlags() & QER_TRANS) != 0) - { - state.m_state |= RENDER_BLEND; - state.m_colour[3] = m_shader->getTrans(); - state.m_sort = OpenGLState::eSortTranslucent; - BlendFunc blendFunc = m_shader->getBlendFunc(); - state.m_blend_src = convertBlendFactor(blendFunc.m_src); - state.m_blend_dst = convertBlendFactor(blendFunc.m_dst); - if(state.m_blend_src == GL_SRC_ALPHA || state.m_blend_dst == GL_SRC_ALPHA) - { - state.m_state |= RENDER_DEPTHWRITE; - } - } - else - { - state.m_state |= RENDER_DEPTHWRITE; - state.m_sort = OpenGLState::eSortFullbright; - } - } - } -} - - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class OpenGLStateLibraryAPI -{ - OpenGLStateMap m_stateMap; -public: - typedef OpenGLStateLibrary Type; - STRING_CONSTANT(Name, "*"); - - OpenGLStateLibraryAPI() - { - g_openglStates = &m_stateMap; - } - ~OpenGLStateLibraryAPI() - { - g_openglStates = 0; - } - OpenGLStateLibrary* getTable() - { - return &m_stateMap; - } -}; - -typedef SingletonModule OpenGLStateLibraryModule; -typedef Static StaticOpenGLStateLibraryModule; -StaticRegisterModule staticRegisterOpenGLStateLibrary(StaticOpenGLStateLibraryModule::instance()); - -class ShaderCacheDependencies : public GlobalShadersModuleRef, public GlobalTexturesModuleRef, public GlobalOpenGLStateLibraryModuleRef -{ -public: - ShaderCacheDependencies() : - GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")) - { - } -}; - -class ShaderCacheAPI -{ - ShaderCache* m_shaderCache; -public: - typedef ShaderCache Type; - STRING_CONSTANT(Name, "*"); - - ShaderCacheAPI() - { - ShaderCache_Construct(); - - m_shaderCache = GetShaderCache(); - } - ~ShaderCacheAPI() - { - ShaderCache_Destroy(); - } - ShaderCache* getTable() - { - return m_shaderCache; - } -}; - -typedef SingletonModule ShaderCacheModule; -typedef Static StaticShaderCacheModule; -StaticRegisterModule staticRegisterShaderCache(StaticShaderCacheModule::instance()); - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/renderstate.h b/misc/mediasource/extra/netradiant-src/radiant/renderstate.h deleted file mode 100644 index 9bbd2918..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/renderstate.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_RENDERSTATE_H) -#define INCLUDED_RENDERSTATE_H - -void ShaderCache_setBumpEnabled(bool enabled); -void ShaderCache_extensionsInitialised(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/resource.h b/misc/mediasource/extra/netradiant-src/radiant/resource.h deleted file mode 100644 index dc86a878..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/resource.h +++ /dev/null @@ -1,18 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by radiant.rc -// -#define IDI_RADIANT 101 -#define IDR_MENU1 102 -#define IDD_DIALOG1 103 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 104 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/scenegraph.cpp b/misc/mediasource/extra/netradiant-src/radiant/scenegraph.cpp deleted file mode 100644 index cb83691e..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/scenegraph.cpp +++ /dev/null @@ -1,312 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "scenegraph.h" - -#include "debugging/debugging.h" - -#include -#include -#include - -#include "string/string.h" -#include "signal/signal.h" -#include "scenelib.h" -#include "instancelib.h" -#include "treemodel.h" - -class StringEqualPredicate -{ - const char* m_string; -public: - StringEqualPredicate(const char* string) : m_string(string) - { - } - bool operator()(const char* other) const - { - return string_equal(m_string, other); - } -}; - -template -class TypeIdMap -{ - typedef const char* TypeName; - typedef TypeName TypeNames[SIZE]; - TypeNames m_typeNames; - TypeName* m_typeNamesEnd; - -public: - TypeIdMap() : m_typeNamesEnd(m_typeNames) - { - } - TypeId getTypeId(const char* name) - { - TypeName* i = std::find_if(m_typeNames, m_typeNamesEnd, StringEqualPredicate(name)); - if(i == m_typeNamesEnd) - { - ASSERT_MESSAGE(m_typeNamesEnd != m_typeNames + SIZE, "reached maximum number of type names supported (" << Unsigned(SIZE) << ")"); - *m_typeNamesEnd++ = name; - } - return i - m_typeNames; - } -}; - -class CompiledGraph : public scene::Graph, public scene::Instantiable::Observer -{ - typedef std::map InstanceMap; - - InstanceMap m_instances; - scene::Instantiable::Observer* m_observer; - Signal0 m_boundsChanged; - scene::Path m_rootpath; - Signal0 m_sceneChangedCallbacks; - - TypeIdMap m_nodeTypeIds; - TypeIdMap m_instanceTypeIds; - -public: - - CompiledGraph(scene::Instantiable::Observer* observer) - : m_observer(observer) - { - } - - void addSceneChangedCallback(const SignalHandler& handler) - { - m_sceneChangedCallbacks.connectLast(handler); - } - void sceneChanged() - { - m_sceneChangedCallbacks(); - } - - scene::Node& root() - { - ASSERT_MESSAGE(!m_rootpath.empty(), "scenegraph root does not exist"); - return m_rootpath.top(); - } - void insert_root(scene::Node& root) - { - //globalOutputStream() << "insert_root\n"; - - ASSERT_MESSAGE(m_rootpath.empty(), "scenegraph root already exists"); - - root.IncRef(); - - Node_traverseSubgraph(root, InstanceSubgraphWalker(this, scene::Path(), 0)); - - m_rootpath.push(makeReference(root)); - } - void erase_root() - { - //globalOutputStream() << "erase_root\n"; - - ASSERT_MESSAGE(!m_rootpath.empty(), "scenegraph root does not exist"); - - scene::Node& root = m_rootpath.top(); - - m_rootpath.pop(); - - Node_traverseSubgraph(root, UninstanceSubgraphWalker(this, scene::Path())); - - root.DecRef(); - } - void boundsChanged() - { - m_boundsChanged(); - } - - void traverse(const Walker& walker) - { - traverse_subgraph(walker, m_instances.begin()); - } - - void traverse_subgraph(const Walker& walker, const scene::Path& start) - { - if(!m_instances.empty()) - { - traverse_subgraph(walker, m_instances.find(PathConstReference(start))); - } - } - - scene::Instance* find(const scene::Path& path) - { - InstanceMap::iterator i = m_instances.find(PathConstReference(path)); - if(i == m_instances.end()) - { - return 0; - } - return (*i).second; - } - - void insert(scene::Instance* instance) - { - m_instances.insert(InstanceMap::value_type(PathConstReference(instance->path()), instance)); - - m_observer->insert(instance); - } - void erase(scene::Instance* instance) - { - m_observer->erase(instance); - - m_instances.erase(PathConstReference(instance->path())); - } - - SignalHandlerId addBoundsChangedCallback(const SignalHandler& boundsChanged) - { - return m_boundsChanged.connectLast(boundsChanged); - } - void removeBoundsChangedCallback(SignalHandlerId id) - { - m_boundsChanged.disconnect(id); - } - - TypeId getNodeTypeId(const char* name) - { - return m_nodeTypeIds.getTypeId(name); - } - - TypeId getInstanceTypeId(const char* name) - { - return m_instanceTypeIds.getTypeId(name); - } - -private: - - bool pre(const Walker& walker, const InstanceMap::iterator& i) - { - return walker.pre(i->first, *i->second); - } - - void post(const Walker& walker, const InstanceMap::iterator& i) - { - walker.post(i->first, *i->second); - } - - void traverse_subgraph(const Walker& walker, InstanceMap::iterator i) - { - Stack stack; - if(i != m_instances.end()) - { - const std::size_t startSize = (*i).first.get().size(); - do - { - if(i != m_instances.end() - && stack.size() < ((*i).first.get().size() - startSize + 1)) - { - stack.push(i); - ++i; - if(!pre(walker, stack.top())) - { - // skip subgraph - while(i != m_instances.end() - && stack.size() < ((*i).first.get().size() - startSize + 1)) - { - ++i; - } - } - } - else - { - post(walker, stack.top()); - stack.pop(); - } - } - while(!stack.empty()); - } - } -}; - -namespace -{ - CompiledGraph* g_sceneGraph; - GraphTreeModel* g_tree_model; -} - -GraphTreeModel* scene_graph_get_tree_model() -{ - return g_tree_model; -} - - -class SceneGraphObserver : public scene::Instantiable::Observer -{ -public: - void insert(scene::Instance* instance) - { - g_sceneGraph->sceneChanged(); - graph_tree_model_insert(g_tree_model, *instance); - } - void erase(scene::Instance* instance) - { - g_sceneGraph->sceneChanged(); - graph_tree_model_erase(g_tree_model, *instance); - } -}; - -SceneGraphObserver g_SceneGraphObserver; - -void SceneGraph_Construct() -{ - g_tree_model = graph_tree_model_new(); - - g_sceneGraph = new CompiledGraph(&g_SceneGraphObserver); -} - -void SceneGraph_Destroy() -{ - delete g_sceneGraph; - - graph_tree_model_delete(g_tree_model); -} - - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class SceneGraphAPI -{ - scene::Graph* m_scenegraph; -public: - typedef scene::Graph Type; - STRING_CONSTANT(Name, "*"); - - SceneGraphAPI() - { - SceneGraph_Construct(); - - m_scenegraph = g_sceneGraph; - } - ~SceneGraphAPI() - { - SceneGraph_Destroy(); - } - scene::Graph* getTable() - { - return m_scenegraph; - } -}; - -typedef SingletonModule SceneGraphModule; -typedef Static StaticSceneGraphModule; -StaticRegisterModule staticRegisterSceneGraph(StaticSceneGraphModule::instance()); - diff --git a/misc/mediasource/extra/netradiant-src/radiant/scenegraph.h b/misc/mediasource/extra/netradiant-src/radiant/scenegraph.h deleted file mode 100644 index d269f8b4..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/scenegraph.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDEDE_SCENEGRAPH_H) -#define INCLUDED_SCENEGRAPH_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/select.cpp b/misc/mediasource/extra/netradiant-src/radiant/select.cpp deleted file mode 100644 index 5889fd5a..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/select.cpp +++ /dev/null @@ -1,1273 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "select.h" - -#include "debugging/debugging.h" - -#include "ientity.h" -#include "iselection.h" -#include "iundo.h" - -#include - -#include "stream/stringstream.h" -#include "signal/isignal.h" -#include "shaderlib.h" -#include "scenelib.h" - -#include "gtkutil/idledraw.h" -#include "gtkutil/dialog.h" -#include "gtkutil/widget.h" -#include "brushmanip.h" -#include "brush.h" -#include "patchmanip.h" -#include "patchdialog.h" -#include "selection.h" -#include "texwindow.h" -#include "gtkmisc.h" -#include "mainframe.h" -#include "grid.h" -#include "map.h" - - - -select_workzone_t g_select_workzone; - - -/** - Loops over all selected brushes and stores their - world AABBs in the specified array. -*/ -class CollectSelectedBrushesBounds : public SelectionSystem::Visitor -{ - AABB* m_bounds; // array of AABBs - Unsigned m_max; // max AABB-elements in array - Unsigned& m_count;// count of valid AABBs stored in array - -public: - CollectSelectedBrushesBounds(AABB* bounds, Unsigned max, Unsigned& count) - : m_bounds(bounds), - m_max(max), - m_count(count) - { - m_count = 0; - } - - void visit(scene::Instance& instance) const - { - ASSERT_MESSAGE(m_count <= m_max, "Invalid m_count in CollectSelectedBrushesBounds"); - - // stop if the array is already full - if(m_count == m_max) - return; - - Selectable* selectable = Instance_getSelectable(instance); - if((selectable != 0) - && instance.isSelected()) - { - // brushes only - if(Instance_getBrush(instance) != 0) - { - m_bounds[m_count] = instance.worldAABB(); - ++m_count; - } - } - } -}; - -/** - Selects all objects that intersect one of the bounding AABBs. - The exact intersection-method is specified through TSelectionPolicy -*/ -template -class SelectByBounds : public scene::Graph::Walker -{ - AABB* m_aabbs; // selection aabbs - Unsigned m_count; // number of aabbs in m_aabbs - TSelectionPolicy policy; // type that contains a custom intersection method aabb<->aabb - -public: - SelectByBounds(AABB* aabbs, Unsigned count) - : m_aabbs(aabbs), - m_count(count) - { - } - - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - - // ignore worldspawn - Entity* entity = Node_getEntity(path.top()); - if(entity) - { - if(string_equal(entity->getKeyValue("classname"), "worldspawn")) - return true; - } - - if( (path.size() > 1) && - (!path.top().get().isRoot()) && - (selectable != 0) - ) - { - for(Unsigned i = 0; i < m_count; ++i) - { - if(policy.Evaluate(m_aabbs[i], instance)) - { - selectable->setSelected(true); - } - } - } - - return true; - } - - /** - Performs selection operation on the global scenegraph. - If delete_bounds_src is true, then the objects which were - used as source for the selection aabbs will be deleted. -*/ - static void DoSelection(bool delete_bounds_src = true) - { - if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) - { - // we may not need all AABBs since not all selected objects have to be brushes - const Unsigned max = (Unsigned)GlobalSelectionSystem().countSelected(); - AABB* aabbs = new AABB[max]; - - Unsigned count; - CollectSelectedBrushesBounds collector(aabbs, max, count); - GlobalSelectionSystem().foreachSelected(collector); - - // nothing usable in selection - if(!count) - { - delete[] aabbs; - return; - } - - // delete selected objects - if(delete_bounds_src)// see deleteSelection - { - UndoableCommand undo("deleteSelected"); - Select_Delete(); - } - - // select objects with bounds - GlobalSceneGraph().traverse(SelectByBounds(aabbs, count)); - - SceneChangeNotify(); - delete[] aabbs; - } - } -}; - -/** - SelectionPolicy for SelectByBounds - Returns true if box and the AABB of instance intersect -*/ -class SelectionPolicy_Touching -{ -public: - bool Evaluate(const AABB& box, scene::Instance& instance) const - { - const AABB& other(instance.worldAABB()); - for(Unsigned i = 0; i < 3; ++i) - { - if(fabsf(box.origin[i] - other.origin[i]) > (box.extents[i] + other.extents[i])) - return false; - } - return true; - } -}; - -/** - SelectionPolicy for SelectByBounds - Returns true if the AABB of instance is inside box -*/ -class SelectionPolicy_Inside -{ -public: - bool Evaluate(const AABB& box, scene::Instance& instance) const - { - const AABB& other(instance.worldAABB()); - for(Unsigned i = 0; i < 3; ++i) - { - if(fabsf(box.origin[i] - other.origin[i]) > (box.extents[i] - other.extents[i])) - return false; - } - return true; - } -}; - -class DeleteSelected : public scene::Graph::Walker -{ - mutable bool m_remove; - mutable bool m_removedChild; -public: - DeleteSelected() - : m_remove(false), m_removedChild(false) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - m_removedChild = false; - - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected() - && path.size() > 1 - && !path.top().get().isRoot()) - { - m_remove = true; - - return false;// dont traverse into child elements - } - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - - if(m_removedChild) - { - m_removedChild = false; - - // delete empty entities - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && path.top().get_pointer() != Map_FindWorldspawn(g_map) - && Node_getTraversable(path.top())->empty()) - { - Path_deleteTop(path); - } - } - - // node should be removed - if(m_remove) - { - if(Node_isEntity(path.parent()) != 0) - { - m_removedChild = true; - } - - m_remove = false; - Path_deleteTop(path); - } - } -}; - -void Scene_DeleteSelected(scene::Graph& graph) -{ - graph.traverse(DeleteSelected()); - SceneChangeNotify(); -} - -void Select_Delete (void) -{ - Scene_DeleteSelected(GlobalSceneGraph()); -} - -class InvertSelectionWalker : public scene::Graph::Walker -{ - SelectionSystem::EMode m_mode; - mutable Selectable* m_selectable; -public: - InvertSelectionWalker(SelectionSystem::EMode mode) - : m_mode(mode), m_selectable(0) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable) - { - switch(m_mode) - { - case SelectionSystem::eEntity: - if(Node_isEntity(path.top()) != 0) - { - m_selectable = path.top().get().visible() ? selectable : 0; - } - break; - case SelectionSystem::ePrimitive: - m_selectable = path.top().get().visible() ? selectable : 0; - break; - case SelectionSystem::eComponent: - break; - } - } - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - if(m_selectable != 0) - { - m_selectable->setSelected(!m_selectable->isSelected()); - m_selectable = 0; - } - } -}; - -void Scene_Invert_Selection(scene::Graph& graph) -{ - graph.traverse(InvertSelectionWalker(GlobalSelectionSystem().Mode())); -} - -void Select_Invert() -{ - Scene_Invert_Selection(GlobalSceneGraph()); -} - -class ExpandSelectionToEntitiesWalker : public scene::Graph::Walker -{ - mutable std::size_t m_depth; - NodeSmartReference worldspawn; -public: - ExpandSelectionToEntitiesWalker() : m_depth(0), worldspawn(Map_FindOrInsertWorldspawn(g_map)) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - ++m_depth; - - // ignore worldspawn - NodeSmartReference me(path.top().get()); - if(me == worldspawn) - return false; - - if(m_depth == 2) // entity depth - { - // traverse and select children if any one is selected - if(instance.childSelected()) - Instance_setSelected(instance, true); - return Node_getEntity(path.top())->isContainer() && instance.isSelected(); - } - else if(m_depth == 3) // primitive depth - { - Instance_setSelected(instance, true); - return false; - } - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - --m_depth; - } -}; - -void Scene_ExpandSelectionToEntities() -{ - GlobalSceneGraph().traverse(ExpandSelectionToEntitiesWalker()); -} - - -namespace -{ - void Selection_UpdateWorkzone() - { - if(GlobalSelectionSystem().countSelected() != 0) - { - Select_GetBounds(g_select_workzone.d_work_min, g_select_workzone.d_work_max); - } - } - typedef FreeCaller SelectionUpdateWorkzoneCaller; - - IdleDraw g_idleWorkzone = IdleDraw(SelectionUpdateWorkzoneCaller()); -} - -const select_workzone_t& Select_getWorkZone() -{ - g_idleWorkzone.flush(); - return g_select_workzone; -} - -void UpdateWorkzone_ForSelection() -{ - g_idleWorkzone.queueDraw(); -} - -// update the workzone to the current selection -void UpdateWorkzone_ForSelectionChanged(const Selectable& selectable) -{ - if(selectable.isSelected()) - { - UpdateWorkzone_ForSelection(); - } -} - -void Select_SetShader(const char* shader) -{ - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushSetShader_Selected(GlobalSceneGraph(), shader); - Scene_PatchSetShader_Selected(GlobalSceneGraph(), shader); - } - Scene_BrushSetShader_Component_Selected(GlobalSceneGraph(), shader); -} - -void Select_SetTexdef(const TextureProjection& projection) -{ - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushSetTexdef_Selected(GlobalSceneGraph(), projection); - } - Scene_BrushSetTexdef_Component_Selected(GlobalSceneGraph(), projection); -} - -void Select_SetFlags(const ContentsFlagsValue& flags) -{ - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushSetFlags_Selected(GlobalSceneGraph(), flags); - } - Scene_BrushSetFlags_Component_Selected(GlobalSceneGraph(), flags); -} - -void Select_GetBounds (Vector3& mins, Vector3& maxs) -{ - AABB bounds; - Scene_BoundsSelected(GlobalSceneGraph(), bounds); - maxs = vector3_added(bounds.origin, bounds.extents); - mins = vector3_subtracted(bounds.origin, bounds.extents); -} - -void Select_GetMid (Vector3& mid) -{ - AABB bounds; - Scene_BoundsSelected(GlobalSceneGraph(), bounds); - mid = vector3_snapped(bounds.origin); -} - - -void Select_FlipAxis (int axis) -{ - Vector3 flip(1, 1, 1); - flip[axis] = -1; - GlobalSelectionSystem().scaleSelected(flip); -} - - -void Select_Scale(float x, float y, float z) -{ - GlobalSelectionSystem().scaleSelected(Vector3(x, y, z)); -} - -enum axis_t -{ - eAxisX = 0, - eAxisY = 1, - eAxisZ = 2, -}; - -enum sign_t -{ - eSignPositive = 1, - eSignNegative = -1, -}; - -inline Matrix4 matrix4_rotation_for_axis90(axis_t axis, sign_t sign) -{ - switch(axis) - { - case eAxisX: - if(sign == eSignPositive) - { - return matrix4_rotation_for_sincos_x(1, 0); - } - else - { - return matrix4_rotation_for_sincos_x(-1, 0); - } - case eAxisY: - if(sign == eSignPositive) - { - return matrix4_rotation_for_sincos_y(1, 0); - } - else - { - return matrix4_rotation_for_sincos_y(-1, 0); - } - default://case eAxisZ: - if(sign == eSignPositive) - { - return matrix4_rotation_for_sincos_z(1, 0); - } - else - { - return matrix4_rotation_for_sincos_z(-1, 0); - } - } -} - -inline void matrix4_rotate_by_axis90(Matrix4& matrix, axis_t axis, sign_t sign) -{ - matrix4_multiply_by_matrix4(matrix, matrix4_rotation_for_axis90(axis, sign)); -} - -inline void matrix4_pivoted_rotate_by_axis90(Matrix4& matrix, axis_t axis, sign_t sign, const Vector3& pivotpoint) -{ - matrix4_translate_by_vec3(matrix, pivotpoint); - matrix4_rotate_by_axis90(matrix, axis, sign); - matrix4_translate_by_vec3(matrix, vector3_negated(pivotpoint)); -} - -inline Quaternion quaternion_for_axis90(axis_t axis, sign_t sign) -{ -#if 1 - switch(axis) - { - case eAxisX: - if(sign == eSignPositive) - { - return Quaternion(c_half_sqrt2f, 0, 0, c_half_sqrt2f); - } - else - { - return Quaternion(-c_half_sqrt2f, 0, 0, -c_half_sqrt2f); - } - case eAxisY: - if(sign == eSignPositive) - { - return Quaternion(0, c_half_sqrt2f, 0, c_half_sqrt2f); - } - else - { - return Quaternion(0, -c_half_sqrt2f, 0, -c_half_sqrt2f); - } - default://case eAxisZ: - if(sign == eSignPositive) - { - return Quaternion(0, 0, c_half_sqrt2f, c_half_sqrt2f); - } - else - { - return Quaternion(0, 0, -c_half_sqrt2f, -c_half_sqrt2f); - } - } -#else - quaternion_for_matrix4_rotation(matrix4_rotation_for_axis90((axis_t)axis, (deg > 0) ? eSignPositive : eSignNegative)); -#endif -} - -void Select_RotateAxis (int axis, float deg) -{ - if(fabs(deg) == 90.f) - { - GlobalSelectionSystem().rotateSelected(quaternion_for_axis90((axis_t)axis, (deg > 0) ? eSignPositive : eSignNegative)); - } - else - { - switch(axis) - { - case 0: - GlobalSelectionSystem().rotateSelected(quaternion_for_matrix4_rotation(matrix4_rotation_for_x_degrees(deg))); - break; - case 1: - GlobalSelectionSystem().rotateSelected(quaternion_for_matrix4_rotation(matrix4_rotation_for_y_degrees(deg))); - break; - case 2: - GlobalSelectionSystem().rotateSelected(quaternion_for_matrix4_rotation(matrix4_rotation_for_z_degrees(deg))); - break; - } - } -} - - -void Select_ShiftTexture(float x, float y) -{ - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushShiftTexdef_Selected(GlobalSceneGraph(), x, y); - Scene_PatchTranslateTexture_Selected(GlobalSceneGraph(), x, y); - } - //globalOutputStream() << "shift selected face textures: s=" << x << " t=" << y << '\n'; - Scene_BrushShiftTexdef_Component_Selected(GlobalSceneGraph(), x, y); -} - -void Select_ScaleTexture(float x, float y) -{ - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushScaleTexdef_Selected(GlobalSceneGraph(), x, y); - Scene_PatchScaleTexture_Selected(GlobalSceneGraph(), x, y); - } - Scene_BrushScaleTexdef_Component_Selected(GlobalSceneGraph(), x, y); -} - -void Select_RotateTexture(float amt) -{ - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushRotateTexdef_Selected(GlobalSceneGraph(), amt); - Scene_PatchRotateTexture_Selected(GlobalSceneGraph(), amt); - } - Scene_BrushRotateTexdef_Component_Selected(GlobalSceneGraph(), amt); -} - -// TTimo modified to handle shader architecture: -// expects shader names at input, comparison relies on shader names .. texture names no longer relevant -void FindReplaceTextures(const char* pFind, const char* pReplace, bool bSelected) -{ - if(!texdef_name_valid(pFind)) - { - globalErrorStream() << "FindReplaceTextures: invalid texture name: '" << pFind << "', aborted\n"; - return; - } - if(!texdef_name_valid(pReplace)) - { - globalErrorStream() << "FindReplaceTextures: invalid texture name: '" << pReplace << "', aborted\n"; - return; - } - - StringOutputStream command; - command << "textureFindReplace -find " << pFind << " -replace " << pReplace; - UndoableCommand undo(command.c_str()); - - if(bSelected) - { - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushFindReplaceShader_Selected(GlobalSceneGraph(), pFind, pReplace); - Scene_PatchFindReplaceShader_Selected(GlobalSceneGraph(), pFind, pReplace); - } - Scene_BrushFindReplaceShader_Component_Selected(GlobalSceneGraph(), pFind, pReplace); - } - else - { - Scene_BrushFindReplaceShader(GlobalSceneGraph(), pFind, pReplace); - Scene_PatchFindReplaceShader(GlobalSceneGraph(), pFind, pReplace); - } -} - -typedef std::vector Classnames; - -bool classnames_match_entity(const Classnames& classnames, Entity* entity) -{ - for(Classnames::const_iterator i = classnames.begin(); i != classnames.end(); ++i) - { - if(string_equal(entity->getKeyValue("classname"), *i)) - { - return true; - } - } - return false; -} - -class EntityFindByClassnameWalker : public scene::Graph::Walker -{ - const Classnames& m_classnames; -public: - EntityFindByClassnameWalker(const Classnames& classnames) - : m_classnames(classnames) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0 - && classnames_match_entity(m_classnames, entity)) - { - Instance_getSelectable(instance)->setSelected(true); - } - return true; - } -}; - -void Scene_EntitySelectByClassnames(scene::Graph& graph, const Classnames& classnames) -{ - graph.traverse(EntityFindByClassnameWalker(classnames)); -} - -class EntityGetSelectedClassnamesWalker : public scene::Graph::Walker -{ - Classnames& m_classnames; -public: - EntityGetSelectedClassnamesWalker(Classnames& classnames) - : m_classnames(classnames) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected()) - { - Entity* entity = Node_getEntity(path.top()); - if(entity != 0) - { - m_classnames.push_back(entity->getKeyValue("classname")); - } - } - return true; - } -}; - -void Scene_EntityGetClassnames(scene::Graph& graph, Classnames& classnames) -{ - graph.traverse(EntityGetSelectedClassnamesWalker(classnames)); -} - -void Select_AllOfType() -{ - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) - { - if(GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace) - { - GlobalSelectionSystem().setSelectedAllComponents(false); - Scene_BrushSelectByShader_Component(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); - } - } - else - { - Classnames classnames; - Scene_EntityGetClassnames(GlobalSceneGraph(), classnames); - GlobalSelectionSystem().setSelectedAll(false); - if(!classnames.empty()) - { - Scene_EntitySelectByClassnames(GlobalSceneGraph(), classnames); - } - else - { - Scene_BrushSelectByShader(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); - Scene_PatchSelectByShader(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); - } - } -} - -void Select_Inside(void) -{ - SelectByBounds::DoSelection(); -} - -void Select_Touching(void) -{ - SelectByBounds::DoSelection(false); -} - -void Select_FitTexture(float horizontal, float vertical) -{ - if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) - { - Scene_BrushFitTexture_Selected(GlobalSceneGraph(), horizontal, vertical); - } - Scene_BrushFitTexture_Component_Selected(GlobalSceneGraph(), horizontal, vertical); - - SceneChangeNotify(); -} - -inline void hide_node(scene::Node& node, bool hide) -{ - hide - ? node.enable(scene::Node::eHidden) - : node.disable(scene::Node::eHidden); -} - -class HideSelectedWalker : public scene::Graph::Walker -{ - bool m_hide; -public: - HideSelectedWalker(bool hide) - : m_hide(hide) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected()) - { - hide_node(path.top(), m_hide); - } - return true; - } -}; - -void Scene_Hide_Selected(bool hide) -{ - GlobalSceneGraph().traverse(HideSelectedWalker(hide)); -} - -void Select_Hide() -{ - Scene_Hide_Selected(true); - SceneChangeNotify(); -} - -void HideSelected() -{ - Select_Hide(); - GlobalSelectionSystem().setSelectedAll(false); -} - - -class HideAllWalker : public scene::Graph::Walker -{ - bool m_hide; -public: - HideAllWalker(bool hide) - : m_hide(hide) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - hide_node(path.top(), m_hide); - return true; - } -}; - -void Scene_Hide_All(bool hide) -{ - GlobalSceneGraph().traverse(HideAllWalker(hide)); -} - -void Select_ShowAllHidden() -{ - Scene_Hide_All(false); - SceneChangeNotify(); -} - - - -void Selection_Flipx() -{ - UndoableCommand undo("mirrorSelected -axis x"); - Select_FlipAxis(0); -} - -void Selection_Flipy() -{ - UndoableCommand undo("mirrorSelected -axis y"); - Select_FlipAxis(1); -} - -void Selection_Flipz() -{ - UndoableCommand undo("mirrorSelected -axis z"); - Select_FlipAxis(2); -} - -void Selection_Rotatex() -{ - UndoableCommand undo("rotateSelected -axis x -angle -90"); - Select_RotateAxis(0,-90); -} - -void Selection_Rotatey() -{ - UndoableCommand undo("rotateSelected -axis y -angle 90"); - Select_RotateAxis(1, 90); -} - -void Selection_Rotatez() -{ - UndoableCommand undo("rotateSelected -axis z -angle -90"); - Select_RotateAxis(2,-90); -} - - - -void Nudge(int nDim, float fNudge) -{ - Vector3 translate(0, 0, 0); - translate[nDim] = fNudge; - - GlobalSelectionSystem().translateSelected(translate); -} - -void Selection_NudgeZ(float amount) -{ - StringOutputStream command; - command << "nudgeSelected -axis z -amount " << amount; - UndoableCommand undo(command.c_str()); - - Nudge(2, amount); -} - -void Selection_MoveDown() -{ - Selection_NudgeZ(-GetGridSize()); -} - -void Selection_MoveUp() -{ - Selection_NudgeZ(GetGridSize()); -} - -void SceneSelectionChange(const Selectable& selectable) -{ - SceneChangeNotify(); -} - -SignalHandlerId Selection_boundsChanged; - -void Selection_construct() -{ - typedef FreeCaller1 SceneSelectionChangeCaller; - GlobalSelectionSystem().addSelectionChangeCallback(SceneSelectionChangeCaller()); - typedef FreeCaller1 UpdateWorkzoneForSelectionChangedCaller; - GlobalSelectionSystem().addSelectionChangeCallback(UpdateWorkzoneForSelectionChangedCaller()); - typedef FreeCaller UpdateWorkzoneForSelectionCaller; - Selection_boundsChanged = GlobalSceneGraph().addBoundsChangedCallback(UpdateWorkzoneForSelectionCaller()); -} - -void Selection_destroy() -{ - GlobalSceneGraph().removeBoundsChangedCallback(Selection_boundsChanged); -} - - -#include "gtkdlgs.h" -#include -#include -#include -#include -#include - - -inline Quaternion quaternion_for_euler_xyz_degrees(const Vector3& eulerXYZ) -{ -#if 0 - return quaternion_for_matrix4_rotation(matrix4_rotation_for_euler_xyz_degrees(eulerXYZ)); -#elif 0 - return quaternion_multiplied_by_quaternion( - quaternion_multiplied_by_quaternion( - quaternion_for_z(degrees_to_radians(eulerXYZ[2])), - quaternion_for_y(degrees_to_radians(eulerXYZ[1])) - ), - quaternion_for_x(degrees_to_radians(eulerXYZ[0])) - ); -#elif 1 - double cx = cos(degrees_to_radians(eulerXYZ[0] * 0.5)); - double sx = sin(degrees_to_radians(eulerXYZ[0] * 0.5)); - double cy = cos(degrees_to_radians(eulerXYZ[1] * 0.5)); - double sy = sin(degrees_to_radians(eulerXYZ[1] * 0.5)); - double cz = cos(degrees_to_radians(eulerXYZ[2] * 0.5)); - double sz = sin(degrees_to_radians(eulerXYZ[2] * 0.5)); - - return Quaternion( - cz * cy * sx - sz * sy * cx, - cz * sy * cx + sz * cy * sx, - sz * cy * cx - cz * sy * sx, - cz * cy * cx + sz * sy * sx - ); -#endif -} - -struct RotateDialog -{ - GtkSpinButton* x; - GtkSpinButton* y; - GtkSpinButton* z; - GtkWindow *window; -}; - -static gboolean rotatedlg_apply (GtkWidget *widget, RotateDialog* rotateDialog) -{ - Vector3 eulerXYZ; - - eulerXYZ[0] = static_cast(gtk_spin_button_get_value(rotateDialog->x)); - eulerXYZ[1] = static_cast(gtk_spin_button_get_value(rotateDialog->y)); - eulerXYZ[2] = static_cast(gtk_spin_button_get_value(rotateDialog->z)); - - StringOutputStream command; - command << "rotateSelectedEulerXYZ -x " << eulerXYZ[0] << " -y " << eulerXYZ[1] << " -z " << eulerXYZ[2]; - UndoableCommand undo(command.c_str()); - - GlobalSelectionSystem().rotateSelected(quaternion_for_euler_xyz_degrees(eulerXYZ)); - return TRUE; -} - -static gboolean rotatedlg_cancel (GtkWidget *widget, RotateDialog* rotateDialog) -{ - gtk_widget_hide(GTK_WIDGET(rotateDialog->window)); - - gtk_spin_button_set_value(rotateDialog->x, 0.0f); // reset to 0 on close - gtk_spin_button_set_value(rotateDialog->y, 0.0f); - gtk_spin_button_set_value(rotateDialog->z, 0.0f); - - return TRUE; -} - -static gboolean rotatedlg_ok (GtkWidget *widget, RotateDialog* rotateDialog) -{ - rotatedlg_apply(widget, rotateDialog); - rotatedlg_cancel(widget, rotateDialog); - return TRUE; -} - -static gboolean rotatedlg_delete (GtkWidget *widget, GdkEventAny *event, RotateDialog* rotateDialog) -{ - rotatedlg_cancel(widget, rotateDialog); - return TRUE; -} - -RotateDialog g_rotate_dialog; -void DoRotateDlg() -{ - if(g_rotate_dialog.window == NULL) - { - g_rotate_dialog.window = create_dialog_window(MainFrame_getWindow(), "Arbitrary rotation", G_CALLBACK(rotatedlg_delete), &g_rotate_dialog); - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(g_rotate_dialog.window, accel); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(g_rotate_dialog.window), GTK_WIDGET(hbox)); - { - GtkTable* table = create_dialog_table(3, 2, 4, 4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); - { - GtkWidget* label = gtk_label_new (" X "); - gtk_widget_show (label); - gtk_table_attach(table, label, 0, 1, 0, 1, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new (" Y "); - gtk_widget_show (label); - gtk_table_attach(table, label, 0, 1, 1, 2, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new (" Z "); - gtk_widget_show (label); - gtk_table_attach(table, label, 0, 1, 2, 3, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -359, 359, 1, 10, 0)); - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); - gtk_spin_button_set_wrap(spin, TRUE); - - gtk_widget_grab_focus(GTK_WIDGET(spin)); - - g_rotate_dialog.x = spin; - } - { - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -359, 359, 1, 10, 0)); - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); - gtk_spin_button_set_wrap(spin, TRUE); - - g_rotate_dialog.y = spin; - } - { - GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -359, 359, 1, 10, 0)); - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); - gtk_spin_button_set_wrap(spin, TRUE); - - g_rotate_dialog.z = spin; - } - } - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - GtkButton* button = create_dialog_button("OK", G_CALLBACK(rotatedlg_ok), &g_rotate_dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(rotatedlg_cancel), &g_rotate_dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_dialog_button("Apply", G_CALLBACK(rotatedlg_apply), &g_rotate_dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - } - } - } - - gtk_widget_show(GTK_WIDGET(g_rotate_dialog.window)); -} - - - - - - - - - -struct ScaleDialog -{ - GtkWidget* x; - GtkWidget* y; - GtkWidget* z; - GtkWindow *window; -}; - -static gboolean scaledlg_apply (GtkWidget *widget, ScaleDialog* scaleDialog) -{ - float sx, sy, sz; - - sx = static_cast(atof(gtk_entry_get_text (GTK_ENTRY (scaleDialog->x)))); - sy = static_cast(atof(gtk_entry_get_text (GTK_ENTRY (scaleDialog->y)))); - sz = static_cast(atof(gtk_entry_get_text (GTK_ENTRY (scaleDialog->z)))); - - StringOutputStream command; - command << "scaleSelected -x " << sx << " -y " << sy << " -z " << sz; - UndoableCommand undo(command.c_str()); - - Select_Scale(sx, sy, sz); - - return TRUE; -} - -static gboolean scaledlg_cancel (GtkWidget *widget, ScaleDialog* scaleDialog) -{ - gtk_widget_hide(GTK_WIDGET(scaleDialog->window)); - - gtk_entry_set_text (GTK_ENTRY(scaleDialog->x), "1.0"); - gtk_entry_set_text (GTK_ENTRY(scaleDialog->y), "1.0"); - gtk_entry_set_text (GTK_ENTRY(scaleDialog->z), "1.0"); - - return TRUE; -} - -static gboolean scaledlg_ok (GtkWidget *widget, ScaleDialog* scaleDialog) -{ - scaledlg_apply(widget, scaleDialog); - scaledlg_cancel(widget, scaleDialog); - return TRUE; -} - -static gboolean scaledlg_delete (GtkWidget *widget, GdkEventAny *event, ScaleDialog* scaleDialog) -{ - scaledlg_cancel(widget, scaleDialog); - return TRUE; -} - -ScaleDialog g_scale_dialog; - -void DoScaleDlg() -{ - if(g_scale_dialog.window == NULL) - { - g_scale_dialog.window = create_dialog_window(MainFrame_getWindow(), "Arbitrary scale", G_CALLBACK(scaledlg_delete), &g_scale_dialog); - - GtkAccelGroup* accel = gtk_accel_group_new(); - gtk_window_add_accel_group(g_scale_dialog.window, accel); - - { - GtkHBox* hbox = create_dialog_hbox(4, 4); - gtk_container_add(GTK_CONTAINER(g_scale_dialog.window), GTK_WIDGET(hbox)); - { - GtkTable* table = create_dialog_table(3, 2, 4, 4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); - { - GtkWidget* label = gtk_label_new (" X "); - gtk_widget_show (label); - gtk_table_attach(table, label, 0, 1, 0, 1, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new (" Y "); - gtk_widget_show (label); - gtk_table_attach(table, label, 0, 1, 1, 2, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new (" Z "); - gtk_widget_show (label); - gtk_table_attach(table, label, 0, 1, 2, 3, - (GtkAttachOptions) (0), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* entry = gtk_entry_new(); - gtk_entry_set_text (GTK_ENTRY(entry), "1.0"); - gtk_widget_show (entry); - gtk_table_attach(table, entry, 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - g_scale_dialog.x = entry; - } - { - GtkWidget* entry = gtk_entry_new(); - gtk_entry_set_text (GTK_ENTRY(entry), "1.0"); - gtk_widget_show (entry); - gtk_table_attach(table, entry, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - g_scale_dialog.y = entry; - } - { - GtkWidget* entry = gtk_entry_new(); - gtk_entry_set_text (GTK_ENTRY(entry), "1.0"); - gtk_widget_show (entry); - gtk_table_attach(table, entry, 1, 2, 2, 3, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - - g_scale_dialog.z = entry; - } - } - { - GtkVBox* vbox = create_dialog_vbox(4); - gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); - { - GtkButton* button = create_dialog_button("OK", G_CALLBACK(scaledlg_ok), &g_scale_dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - widget_make_default(GTK_WIDGET(button)); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(scaledlg_cancel), &g_scale_dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); - } - { - GtkButton* button = create_dialog_button("Apply", G_CALLBACK(scaledlg_apply), &g_scale_dialog); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); - } - } - } - } - - gtk_widget_show(GTK_WIDGET(g_scale_dialog.window)); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/select.h b/misc/mediasource/extra/netradiant-src/radiant/select.h deleted file mode 100644 index 5a019f7c..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/select.h +++ /dev/null @@ -1,91 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_SELECT_H) -#define INCLUDED_SELECT_H - -#include "math/vector.h" - -void Select_GetBounds(Vector3& mins, Vector3& maxs); -void Select_GetMid(Vector3& mid); - -void Select_Delete(); -void Select_Invert(); -void Select_Inside(); -void Select_Touching(); -void Scene_ExpandSelectionToEntities(); - -void Selection_Flipx(); -void Selection_Flipy(); -void Selection_Flipz(); -void Selection_Rotatex(); -void Selection_Rotatey(); -void Selection_Rotatez(); - - -void Selection_MoveDown(); -void Selection_MoveUp(); - -void Select_AllOfType(); - -void DoRotateDlg(); -void DoScaleDlg(); - - -void Select_SetShader(const char* shader); - -class TextureProjection; -void Select_SetTexdef(const TextureProjection& projection); - -class ContentsFlagsValue; -void Select_SetFlags(const ContentsFlagsValue& flags); - -void Select_RotateTexture(float amt); -void Select_ScaleTexture(float x, float y); -void Select_ShiftTexture(float x, float y); -void Select_FitTexture(float horizontal = 1, float vertical = 1); -void FindReplaceTextures(const char* pFind, const char* pReplace, bool bSelected); - -void HideSelected(); -void Select_ShowAllHidden(); - -// updating workzone to a given brush (depends on current view) - -void Selection_construct(); -void Selection_destroy(); - - -struct select_workzone_t -{ - // defines the boundaries of the current work area - // is used to guess brushes and drop points third coordinate when creating from 2D view - Vector3 d_work_min, d_work_max; - - select_workzone_t() : - d_work_min(-64.0f,-64.0f,-64.0f), - d_work_max( 64.0f, 64.0f, 64.0f) - { - } -}; - -const select_workzone_t& Select_getWorkZone(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/selection.cpp b/misc/mediasource/extra/netradiant-src/radiant/selection.cpp deleted file mode 100644 index 3b477990..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/selection.cpp +++ /dev/null @@ -1,4179 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "selection.h" - -#include "debugging/debugging.h" - -#include -#include -#include - -#include "windowobserver.h" -#include "iundo.h" -#include "ientity.h" -#include "cullable.h" -#include "renderable.h" -#include "selectable.h" -#include "editable.h" - -#include "math/frustum.h" -#include "signal/signal.h" -#include "generic/object.h" -#include "selectionlib.h" -#include "render.h" -#include "view.h" -#include "renderer.h" -#include "stream/stringstream.h" -#include "eclasslib.h" -#include "generic/bitfield.h" -#include "generic/static.h" -#include "pivot.h" -#include "stringio.h" -#include "container/container.h" - -#include "grid.h" - -TextOutputStream& ostream_write(TextOutputStream& t, const Vector4& v) -{ - return t << "[ " << v.x() << " " << v.y() << " " << v.z() << " " << v.w() << " ]"; -} - -TextOutputStream& ostream_write(TextOutputStream& t, const Matrix4& m) -{ - return t << "[ " << m.x() << " " << m.y() << " " << m.z() << " " << m.t() << " ]"; -} - -struct Pivot2World -{ - Matrix4 m_worldSpace; - Matrix4 m_viewpointSpace; - Matrix4 m_viewplaneSpace; - Vector3 m_axis_screen; - - void update(const Matrix4& pivot2world, const Matrix4& modelview, const Matrix4& projection, const Matrix4& viewport) - { - Pivot2World_worldSpace(m_worldSpace, pivot2world, modelview, projection, viewport); - Pivot2World_viewpointSpace(m_viewpointSpace, m_axis_screen, pivot2world, modelview, projection, viewport); - Pivot2World_viewplaneSpace(m_viewplaneSpace, pivot2world, modelview, projection, viewport); - } -}; - - -void point_for_device_point(Vector3& point, const Matrix4& device2object, const float x, const float y, const float z) -{ - // transform from normalised device coords to object coords - point = vector4_projected(matrix4_transformed_vector4(device2object, Vector4(x, y, z, 1))); -} - -void ray_for_device_point(Ray& ray, const Matrix4& device2object, const float x, const float y) -{ - // point at x, y, zNear - point_for_device_point(ray.origin, device2object, x, y, -1); - - // point at x, y, zFar - point_for_device_point(ray.direction, device2object, x, y, 1); - - // construct ray - vector3_subtract(ray.direction, ray.origin); - vector3_normalise(ray.direction); -} - -bool sphere_intersect_ray(const Vector3& origin, float radius, const Ray& ray, Vector3& intersection) -{ - intersection = vector3_subtracted(origin, ray.origin); - const double a = vector3_dot(intersection, ray.direction); - const double d = radius * radius - (vector3_dot(intersection, intersection) - a * a); - - if(d > 0) - { - intersection = vector3_added(ray.origin, vector3_scaled(ray.direction, a - sqrt(d))); - return true; - } - else - { - intersection = vector3_added( ray.origin, vector3_scaled(ray.direction, a)); - return false; - } -} - -void ray_intersect_ray(const Ray& ray, const Ray& other, Vector3& intersection) -{ - intersection = vector3_subtracted(ray.origin, other.origin); - //float a = 1;//vector3_dot(ray.direction, ray.direction); // always >= 0 - double dot = vector3_dot(ray.direction, other.direction); - //float c = 1;//vector3_dot(other.direction, other.direction); // always >= 0 - double d = vector3_dot(ray.direction, intersection); - double e = vector3_dot(other.direction, intersection); - double D = 1 - dot*dot;//a*c - dot*dot; // always >= 0 - - if (D < 0.000001) - { - // the lines are almost parallel - intersection = vector3_added(other.origin, vector3_scaled(other.direction, e)); - } - else - { - intersection = vector3_added(other.origin, vector3_scaled(other.direction, (e - dot*d) / D)); - } -} - -const Vector3 g_origin(0, 0, 0); -const float g_radius = 64; - -void point_on_sphere(Vector3& point, const Matrix4& device2object, const float x, const float y) -{ - Ray ray; - ray_for_device_point(ray, device2object, x, y); - sphere_intersect_ray(g_origin, g_radius, ray, point); -} - -void point_on_axis(Vector3& point, const Vector3& axis, const Matrix4& device2object, const float x, const float y) -{ - Ray ray; - ray_for_device_point(ray, device2object, x, y); - ray_intersect_ray(ray, Ray(Vector3(0, 0, 0), axis), point); -} - -void point_on_plane(Vector3& point, const Matrix4& device2object, const float x, const float y) -{ - Matrix4 object2device(matrix4_full_inverse(device2object)); - point = vector4_projected(matrix4_transformed_vector4(device2object, Vector4(x, y, object2device[14] / object2device[15], 1))); -} - -//! a and b are unit vectors .. returns angle in radians -inline float angle_between(const Vector3& a, const Vector3& b) -{ - return static_cast(2.0 * atan2( - vector3_length(vector3_subtracted(a, b)), - vector3_length(vector3_added(a, b)) - )); -} - - -#if defined(_DEBUG) -class test_quat -{ -public: - test_quat(const Vector3& from, const Vector3& to) - { - Vector4 quaternion(quaternion_for_unit_vectors(from, to)); - Matrix4 matrix(matrix4_rotation_for_quaternion(quaternion_multiplied_by_quaternion(quaternion, c_quaternion_identity))); - } -private: -}; - -static test_quat bleh(g_vector3_axis_x, g_vector3_axis_y); -#endif - -//! axis is a unit vector -inline void constrain_to_axis(Vector3& vec, const Vector3& axis) -{ - vec = vector3_normalised(vector3_added(vec, vector3_scaled(axis, -vector3_dot(vec, axis)))); -} - -//! a and b are unit vectors .. a and b must be orthogonal to axis .. returns angle in radians -float angle_for_axis(const Vector3& a, const Vector3& b, const Vector3& axis) -{ - if(vector3_dot(axis, vector3_cross(a, b)) > 0.0) - return angle_between(a, b); - else - return -angle_between(a, b); -} - -float distance_for_axis(const Vector3& a, const Vector3& b, const Vector3& axis) -{ - return static_cast(vector3_dot(b, axis) - vector3_dot(a, axis)); -} - -class Manipulatable -{ -public: - virtual void Construct(const Matrix4& device2manip, const float x, const float y) = 0; - virtual void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) = 0; -}; - -void transform_local2object(Matrix4& object, const Matrix4& local, const Matrix4& local2object) -{ - object = matrix4_multiplied_by_matrix4( - matrix4_multiplied_by_matrix4(local2object, local), - matrix4_full_inverse(local2object) - ); -} - -class Rotatable -{ -public: - virtual void rotate(const Quaternion& rotation) = 0; -}; - -class RotateFree : public Manipulatable -{ - Vector3 m_start; - Rotatable& m_rotatable; -public: - RotateFree(Rotatable& rotatable) - : m_rotatable(rotatable) - { - } - void Construct(const Matrix4& device2manip, const float x, const float y) - { - point_on_sphere(m_start, device2manip, x, y); - vector3_normalise(m_start); - } - void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) - { - Vector3 current; - - point_on_sphere(current, device2manip, x, y); - vector3_normalise(current); - - m_rotatable.rotate(quaternion_for_unit_vectors(m_start, current)); - } -}; - -class RotateAxis : public Manipulatable -{ - Vector3 m_axis; - Vector3 m_start; - Rotatable& m_rotatable; -public: - RotateAxis(Rotatable& rotatable) - : m_rotatable(rotatable) - { - } - void Construct(const Matrix4& device2manip, const float x, const float y) - { - point_on_sphere(m_start, device2manip, x, y); - constrain_to_axis(m_start, m_axis); - } - /// \brief Converts current position to a normalised vector orthogonal to axis. - void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) - { - Vector3 current; - point_on_sphere(current, device2manip, x, y); - constrain_to_axis(current, m_axis); - - m_rotatable.rotate(quaternion_for_axisangle(m_axis, angle_for_axis(m_start, current, m_axis))); - } - - void SetAxis(const Vector3& axis) - { - m_axis = axis; - } -}; - -void translation_local2object(Vector3& object, const Vector3& local, const Matrix4& local2object) -{ - object = matrix4_get_translation_vec3( - matrix4_multiplied_by_matrix4( - matrix4_translated_by_vec3(local2object, local), - matrix4_full_inverse(local2object) - ) - ); -} - -class Translatable -{ -public: - virtual void translate(const Vector3& translation) = 0; -}; - -class TranslateAxis : public Manipulatable -{ - Vector3 m_start; - Vector3 m_axis; - Translatable& m_translatable; -public: - TranslateAxis(Translatable& translatable) - : m_translatable(translatable) - { - } - void Construct(const Matrix4& device2manip, const float x, const float y) - { - point_on_axis(m_start, m_axis, device2manip, x, y); - } - void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) - { - Vector3 current; - point_on_axis(current, m_axis, device2manip, x, y); - current = vector3_scaled(m_axis, distance_for_axis(m_start, current, m_axis)); - - translation_local2object(current, current, manip2object); - vector3_snap(current, GetSnapGridSize()); - - m_translatable.translate(current); - } - - void SetAxis(const Vector3& axis) - { - m_axis = axis; - } -}; - -class TranslateFree : public Manipulatable -{ -private: - Vector3 m_start; - Translatable& m_translatable; -public: - TranslateFree(Translatable& translatable) - : m_translatable(translatable) - { - } - void Construct(const Matrix4& device2manip, const float x, const float y) - { - point_on_plane(m_start, device2manip, x, y); - } - void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) - { - Vector3 current; - point_on_plane(current, device2manip, x, y); - current = vector3_subtracted(current, m_start); - - translation_local2object(current, current, manip2object); - vector3_snap(current, GetSnapGridSize()); - - m_translatable.translate(current); - } -}; - - -class Scalable -{ -public: - virtual void scale(const Vector3& scaling) = 0; -}; - - -class ScaleAxis : public Manipulatable -{ -private: - Vector3 m_start; - Vector3 m_axis; - Scalable& m_scalable; -public: - ScaleAxis(Scalable& scalable) - : m_scalable(scalable) - { - } - void Construct(const Matrix4& device2manip, const float x, const float y) - { - point_on_axis(m_start, m_axis, device2manip, x, y); - } - void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) - { - Vector3 current; - point_on_axis(current, m_axis, device2manip, x, y); - Vector3 delta = vector3_subtracted(current, m_start); - - translation_local2object(delta, delta, manip2object); - vector3_snap(delta, GetSnapGridSize()); - - Vector3 start(vector3_snapped(m_start, GetSnapGridSize())); - Vector3 scale( - start[0] == 0 ? 1 : 1 + delta[0] / start[0], - start[1] == 0 ? 1 : 1 + delta[1] / start[1], - start[2] == 0 ? 1 : 1 + delta[2] / start[2] - ); - m_scalable.scale(scale); - } - - void SetAxis(const Vector3& axis) - { - m_axis = axis; - } -}; - -class ScaleFree : public Manipulatable -{ -private: - Vector3 m_start; - Scalable& m_scalable; -public: - ScaleFree(Scalable& scalable) - : m_scalable(scalable) - { - } - void Construct(const Matrix4& device2manip, const float x, const float y) - { - point_on_plane(m_start, device2manip, x, y); - } - void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) - { - Vector3 current; - point_on_plane(current, device2manip, x, y); - Vector3 delta = vector3_subtracted(current, m_start); - - translation_local2object(delta, delta, manip2object); - vector3_snap(delta, GetSnapGridSize()); - - Vector3 start(vector3_snapped(m_start, GetSnapGridSize())); - Vector3 scale( - start[0] == 0 ? 1 : 1 + delta[0] / start[0], - start[1] == 0 ? 1 : 1 + delta[1] / start[1], - start[2] == 0 ? 1 : 1 + delta[2] / start[2] - ); - m_scalable.scale(scale); - } -}; - - - - - - - - - - -class RenderableClippedPrimitive : public OpenGLRenderable -{ - struct primitive_t - { - PointVertex m_points[9]; - std::size_t m_count; - }; - Matrix4 m_inverse; - std::vector m_primitives; -public: - Matrix4 m_world; - - void render(RenderStateFlags state) const - { - for(std::size_t i=0; i P[1])) // an upward crossing - || (((*prev)[1] > P[1]) && ((*cur)[1] <= P[1]))) - { // a downward crossing - // compute the actual edge-ray intersect x-coordinate - float vt = (float)(P[1] - (*prev)[1]) / ((*cur)[1] - (*prev)[1]); - if (P[0] < (*prev)[0] + vt * ((*cur)[0] - (*prev)[0])) // P[0] < intersect - { - ++crossings; // a valid crossing of y=P[1] right of P[0] - } - } - } - return (crossings & 0x1) != 0; // 0 if even (out), and 1 if odd (in) -} - -inline double triangle_signed_area_XY(const Vector3& p0, const Vector3& p1, const Vector3& p2) -{ - return ((p1[0] - p0[0]) * (p2[1] - p0[1])) - ((p2[0] - p0[0]) * (p1[1] - p0[1])); -} - -enum clipcull_t -{ - eClipCullNone, - eClipCullCW, - eClipCullCCW, -}; - - -inline SelectionIntersection select_point_from_clipped(Vector4& clipped) -{ - return SelectionIntersection(clipped[2] / clipped[3], static_cast(vector3_length_squared(Vector3(clipped[0] / clipped[3], clipped[1] / clipped[3], 0)))); -} - -void BestPoint(std::size_t count, Vector4 clipped[9], SelectionIntersection& best, clipcull_t cull) -{ - Vector3 normalised[9]; - - { - for(std::size_t i=0; i 2) - { - double signed_area = triangle_signed_area_XY(normalised[0], normalised[1], normalised[2]); - - if((cull == eClipCullCW && signed_area > 0) - || (cull == eClipCullCCW && signed_area < 0)) - return; - } - - if(count == 2) - { - Segment3D segment(normalised[0], normalised[1]); - Point3D point = segment_closest_point_to_point(segment, Vector3(0, 0, 0)); - assign_if_closer(best, SelectionIntersection(point.z(), 0)); - } - else if(count > 2 && !point_test_polygon_2d(Vector3(0, 0, 0), normalised, normalised + count)) - { - point_iterator_t end = normalised + count; - for(point_iterator_t previous = end-1, current = normalised; current != end; previous = current, ++current) - { - Segment3D segment(*previous, *current); - Point3D point = segment_closest_point_to_point(segment, Vector3(0, 0, 0)); - float depth = point.z(); - point.z() = 0; - float distance = static_cast(vector3_length_squared(point)); - - assign_if_closer(best, SelectionIntersection(depth, distance)); - } - } - else if(count > 2) - { - assign_if_closer( - best, - SelectionIntersection( - static_cast(ray_distance_to_plane( - Ray(Vector3(0, 0, 0), Vector3(0, 0, 1)), - plane3_for_points(normalised[0], normalised[1], normalised[2]) - )), - 0 - ) - ); - } - -#if defined(DEBUG_SELECTION) - if(count >= 2) - g_render_clipped.insert(clipped, count); -#endif -} - -void LineStrip_BestPoint(const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best) -{ - Vector4 clipped[2]; - for(std::size_t i = 0; (i + 1) < size; ++i) - { - const std::size_t count = matrix4_clip_line(local2view, vertex3f_to_vector3(vertices[i].vertex), vertex3f_to_vector3(vertices[i + 1].vertex), clipped); - BestPoint(count, clipped, best, eClipCullNone); - } -} - -void LineLoop_BestPoint(const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best) -{ - Vector4 clipped[2]; - for(std::size_t i = 0; i < size; ++i) - { - const std::size_t count = matrix4_clip_line(local2view, vertex3f_to_vector3(vertices[i].vertex), vertex3f_to_vector3(vertices[(i+1)%size].vertex), clipped); - BestPoint(count, clipped, best, eClipCullNone); - } -} - -void Line_BestPoint(const Matrix4& local2view, const PointVertex vertices[2], SelectionIntersection& best) -{ - Vector4 clipped[2]; - const std::size_t count = matrix4_clip_line(local2view, vertex3f_to_vector3(vertices[0].vertex), vertex3f_to_vector3(vertices[1].vertex), clipped); - BestPoint(count, clipped, best, eClipCullNone); -} - -void Circle_BestPoint(const Matrix4& local2view, clipcull_t cull, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best) -{ - Vector4 clipped[9]; - for(std::size_t i=0; i((*x).vertex), - reinterpret_cast((*y).vertex), - reinterpret_cast((*z).vertex), - clipped - ), - clipped, - best, - cull - ); - } -} - - -typedef std::multimap SelectableSortedSet; - -class SelectionPool : public Selector -{ - SelectableSortedSet m_pool; - SelectionIntersection m_intersection; - Selectable* m_selectable; - -public: - void pushSelectable(Selectable& selectable) - { - m_intersection = SelectionIntersection(); - m_selectable = &selectable; - } - void popSelectable() - { - addSelectable(m_intersection, m_selectable); - m_intersection = SelectionIntersection(); - } - void addIntersection(const SelectionIntersection& intersection) - { - assign_if_closer(m_intersection, intersection); - } - void addSelectable(const SelectionIntersection& intersection, Selectable* selectable) - { - if(intersection.valid()) - { - m_pool.insert(SelectableSortedSet::value_type(intersection, selectable)); - } - } - - typedef SelectableSortedSet::iterator iterator; - - iterator begin() - { - return m_pool.begin(); - } - iterator end() - { - return m_pool.end(); - } - - bool failed() - { - return m_pool.empty(); - } -}; - - -const Colour4b g_colour_sphere(0, 0, 0, 255); -const Colour4b g_colour_screen(0, 255, 255, 255); -const Colour4b g_colour_selected(255, 255, 0, 255); - -inline const Colour4b& colourSelected(const Colour4b& colour, bool selected) -{ - return (selected) ? g_colour_selected : colour; -} - -template -inline void draw_semicircle(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; - remap_policy::set(vertices[segments << 2].vertex, -radius, 0, 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); - -#if 0 - PointVertex* m = i + (segments << 2); - PointVertex* n = j + (segments << 2); - PointVertex* o = k + (segments << 2); - PointVertex* p = l + (segments << 2); -#endif - - remap_policy::set(i->vertex, x,-y, 0); - remap_policy::set(k->vertex,-y,-x, 0); -#if 0 - remap_policy::set(m->vertex,-x, y, 0); - remap_policy::set(o->vertex, y, x, 0); -#endif - - ++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); -#if 0 - remap_policy::set(n->vertex,-y, x, 0); - remap_policy::set(p->vertex, x, y, 0); -#endif - } -} - -class Manipulator -{ -public: - virtual Manipulatable* GetManipulatable() = 0; - virtual void testSelect(const View& view, const Matrix4& pivot2world) - { - } - virtual void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) - { - } - virtual void setSelected(bool select) = 0; - virtual bool isSelected() const = 0; -}; - - -inline Vector3 normalised_safe(const Vector3& self) -{ - if(vector3_equal(self, g_vector3_identity)) - { - return g_vector3_identity; - } - return vector3_normalised(self); -} - - -class RotateManipulator : public Manipulator -{ - struct RenderableCircle : public OpenGLRenderable - { - Array m_vertices; - - RenderableCircle(std::size_t size) : m_vertices(size) - { - } - void render(RenderStateFlags state) const - { - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices.data()->colour); - glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices.data()->vertex); - glDrawArrays(GL_LINE_LOOP, 0, GLsizei(m_vertices.size())); - } - void setColour(const Colour4b& colour) - { - for(Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i) - { - (*i).colour = colour; - } - } - }; - - struct RenderableSemiCircle : public OpenGLRenderable - { - Array m_vertices; - - RenderableSemiCircle(std::size_t size) : m_vertices(size) - { - } - void render(RenderStateFlags state) const - { - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices.data()->colour); - glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices.data()->vertex); - glDrawArrays(GL_LINE_STRIP, 0, GLsizei(m_vertices.size())); - } - void setColour(const Colour4b& colour) - { - for(Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i) - { - (*i).colour = colour; - } - } - }; - - RotateFree m_free; - RotateAxis m_axis; - Vector3 m_axis_screen; - RenderableSemiCircle m_circle_x; - RenderableSemiCircle m_circle_y; - RenderableSemiCircle m_circle_z; - RenderableCircle m_circle_screen; - RenderableCircle m_circle_sphere; - SelectableBool m_selectable_x; - SelectableBool m_selectable_y; - SelectableBool m_selectable_z; - SelectableBool m_selectable_screen; - SelectableBool m_selectable_sphere; - Pivot2World m_pivot; - Matrix4 m_local2world_x; - Matrix4 m_local2world_y; - Matrix4 m_local2world_z; - bool m_circle_x_visible; - bool m_circle_y_visible; - bool m_circle_z_visible; -public: - static Shader* m_state_outer; - - RotateManipulator(Rotatable& rotatable, std::size_t segments, float radius) : - m_free(rotatable), - m_axis(rotatable), - m_circle_x((segments << 2) + 1), - m_circle_y((segments << 2) + 1), - m_circle_z((segments << 2) + 1), - m_circle_screen(segments<<3), - m_circle_sphere(segments<<3) - { - draw_semicircle(segments, radius, m_circle_x.m_vertices.data(), RemapYZX()); - draw_semicircle(segments, radius, m_circle_y.m_vertices.data(), RemapZXY()); - draw_semicircle(segments, radius, m_circle_z.m_vertices.data(), RemapXYZ()); - - draw_circle(segments, radius * 1.15f, m_circle_screen.m_vertices.data(), RemapXYZ()); - draw_circle(segments, radius, m_circle_sphere.m_vertices.data(), RemapXYZ()); - } - - - void UpdateColours() - { - m_circle_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); - m_circle_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); - m_circle_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); - m_circle_screen.setColour(colourSelected(g_colour_screen, m_selectable_screen.isSelected())); - m_circle_sphere.setColour(colourSelected(g_colour_sphere, false)); - } - - void updateCircleTransforms() - { - Vector3 localViewpoint(matrix4_transformed_direction(matrix4_transposed(m_pivot.m_worldSpace), vector4_to_vector3(m_pivot.m_viewpointSpace.z()))); - - m_circle_x_visible = !vector3_equal_epsilon(g_vector3_axis_x, localViewpoint, 1e-6f); - if(m_circle_x_visible) - { - m_local2world_x = g_matrix4_identity; - vector4_to_vector3(m_local2world_x.y()) = normalised_safe( - vector3_cross(g_vector3_axis_x, localViewpoint) - ); - vector4_to_vector3(m_local2world_x.z()) = normalised_safe( - vector3_cross(vector4_to_vector3(m_local2world_x.x()), vector4_to_vector3(m_local2world_x.y())) - ); - matrix4_premultiply_by_matrix4(m_local2world_x, m_pivot.m_worldSpace); - } - - m_circle_y_visible = !vector3_equal_epsilon(g_vector3_axis_y, localViewpoint, 1e-6f); - if(m_circle_y_visible) - { - m_local2world_y = g_matrix4_identity; - vector4_to_vector3(m_local2world_y.z()) = normalised_safe( - vector3_cross(g_vector3_axis_y, localViewpoint) - ); - vector4_to_vector3(m_local2world_y.x()) = normalised_safe( - vector3_cross(vector4_to_vector3(m_local2world_y.y()), vector4_to_vector3(m_local2world_y.z())) - ); - matrix4_premultiply_by_matrix4(m_local2world_y, m_pivot.m_worldSpace); - } - - m_circle_z_visible = !vector3_equal_epsilon(g_vector3_axis_z, localViewpoint, 1e-6f); - if(m_circle_z_visible) - { - m_local2world_z = g_matrix4_identity; - vector4_to_vector3(m_local2world_z.x()) = normalised_safe( - vector3_cross(g_vector3_axis_z, localViewpoint) - ); - vector4_to_vector3(m_local2world_z.y()) = normalised_safe( - vector3_cross(vector4_to_vector3(m_local2world_z.z()), vector4_to_vector3(m_local2world_z.x())) - ); - matrix4_premultiply_by_matrix4(m_local2world_z, m_pivot.m_worldSpace); - } - } - - void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) - { - m_pivot.update(pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport()); - updateCircleTransforms(); - - // temp hack - UpdateColours(); - - renderer.SetState(m_state_outer, Renderer::eWireframeOnly); - renderer.SetState(m_state_outer, Renderer::eFullMaterials); - - renderer.addRenderable(m_circle_screen, m_pivot.m_viewpointSpace); - renderer.addRenderable(m_circle_sphere, m_pivot.m_viewpointSpace); - - if(m_circle_x_visible) - { - renderer.addRenderable(m_circle_x, m_local2world_x); - } - if(m_circle_y_visible) - { - renderer.addRenderable(m_circle_y, m_local2world_y); - } - if(m_circle_z_visible) - { - renderer.addRenderable(m_circle_z, m_local2world_z); - } - } - void testSelect(const View& view, const Matrix4& pivot2world) - { - m_pivot.update(pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport()); - updateCircleTransforms(); - - SelectionPool selector; - - { - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_local2world_x)); - -#if defined(DEBUG_SELECTION) - g_render_clipped.construct(view.GetViewMatrix()); -#endif - - SelectionIntersection best; - LineStrip_BestPoint(local2view, m_circle_x.m_vertices.data(), m_circle_x.m_vertices.size(), best); - selector.addSelectable(best, &m_selectable_x); - } - - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_local2world_y)); - -#if defined(DEBUG_SELECTION) - g_render_clipped.construct(view.GetViewMatrix()); -#endif - - SelectionIntersection best; - LineStrip_BestPoint(local2view, m_circle_y.m_vertices.data(), m_circle_y.m_vertices.size(), best); - selector.addSelectable(best, &m_selectable_y); - } - - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_local2world_z)); - -#if defined(DEBUG_SELECTION) - g_render_clipped.construct(view.GetViewMatrix()); -#endif - - SelectionIntersection best; - LineStrip_BestPoint(local2view, m_circle_z.m_vertices.data(), m_circle_z.m_vertices.size(), best); - selector.addSelectable(best, &m_selectable_z); - } - } - - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_viewpointSpace)); - - { - SelectionIntersection best; - LineLoop_BestPoint(local2view, m_circle_screen.m_vertices.data(), m_circle_screen.m_vertices.size(), best); - selector.addSelectable(best, &m_selectable_screen); - } - - { - SelectionIntersection best; - Circle_BestPoint(local2view, eClipCullCW, m_circle_sphere.m_vertices.data(), m_circle_sphere.m_vertices.size(), best); - selector.addSelectable(best, &m_selectable_sphere); - } - } - - m_axis_screen = m_pivot.m_axis_screen; - - if(!selector.failed()) - { - (*selector.begin()).second->setSelected(true); - } - } - - Manipulatable* GetManipulatable() - { - if(m_selectable_x.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_x); - return &m_axis; - } - else if(m_selectable_y.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_y); - return &m_axis; - } - else if(m_selectable_z.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_z); - return &m_axis; - } - else if(m_selectable_screen.isSelected()) - { - m_axis.SetAxis(m_axis_screen); - return &m_axis; - } - else - return &m_free; - } - - void setSelected(bool select) - { - m_selectable_x.setSelected(select); - m_selectable_y.setSelected(select); - m_selectable_z.setSelected(select); - m_selectable_screen.setSelected(select); - } - bool isSelected() const - { - return m_selectable_x.isSelected() - | m_selectable_y.isSelected() - | m_selectable_z.isSelected() - | m_selectable_screen.isSelected() - | m_selectable_sphere.isSelected(); - } -}; - -Shader* RotateManipulator::m_state_outer; - - -const float arrowhead_length = 16; -const float arrowhead_radius = 4; - -inline void draw_arrowline(const float length, PointVertex* line, const std::size_t axis) -{ - (*line++).vertex = vertex3f_identity; - (*line).vertex = vertex3f_identity; - vertex3f_to_array((*line).vertex)[axis] = length - arrowhead_length; -} - -template -inline void draw_arrowhead(const std::size_t segments, const float length, FlatShadedVertex* vertices, VertexRemap, NormalRemap) -{ - std::size_t head_tris = (segments << 3); - const double head_segment = c_2pi / head_tris; - for(std::size_t i = 0; i < head_tris; ++i) - { - { - FlatShadedVertex& point = vertices[i*6+0]; - VertexRemap::x(point.vertex) = length - arrowhead_length; - VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos(i * head_segment)); - VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin(i * head_segment)); - NormalRemap::x(point.normal) = arrowhead_radius / arrowhead_length; - NormalRemap::y(point.normal) = static_cast(cos(i * head_segment)); - NormalRemap::z(point.normal) = static_cast(sin(i * head_segment)); - } - { - FlatShadedVertex& point = vertices[i*6+1]; - VertexRemap::x(point.vertex) = length; - VertexRemap::y(point.vertex) = 0; - VertexRemap::z(point.vertex) = 0; - NormalRemap::x(point.normal) = arrowhead_radius / arrowhead_length; - NormalRemap::y(point.normal) = static_cast(cos((i + 0.5) * head_segment)); - NormalRemap::z(point.normal) = static_cast(sin((i + 0.5) * head_segment)); - } - { - FlatShadedVertex& point = vertices[i*6+2]; - VertexRemap::x(point.vertex) = length - arrowhead_length; - VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos((i+1) * head_segment)); - VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin((i+1) * head_segment)); - NormalRemap::x(point.normal) = arrowhead_radius / arrowhead_length; - NormalRemap::y(point.normal) = static_cast(cos((i+1) * head_segment)); - NormalRemap::z(point.normal) = static_cast(sin((i+1) * head_segment)); - } - - { - FlatShadedVertex& point = vertices[i*6+3]; - VertexRemap::x(point.vertex) = length - arrowhead_length; - VertexRemap::y(point.vertex) = 0; - VertexRemap::z(point.vertex) = 0; - NormalRemap::x(point.normal) = -1; - NormalRemap::y(point.normal) = 0; - NormalRemap::z(point.normal) = 0; - } - { - FlatShadedVertex& point = vertices[i*6+4]; - VertexRemap::x(point.vertex) = length - arrowhead_length; - VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos(i * head_segment)); - VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin(i * head_segment)); - NormalRemap::x(point.normal) = -1; - NormalRemap::y(point.normal) = 0; - NormalRemap::z(point.normal) = 0; - } - { - FlatShadedVertex& point = vertices[i*6+5]; - VertexRemap::x(point.vertex) = length - arrowhead_length; - VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos((i+1) * head_segment)); - VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin((i+1) * head_segment)); - NormalRemap::x(point.normal) = -1; - NormalRemap::y(point.normal) = 0; - NormalRemap::z(point.normal) = 0; - } - } -} - -template -class TripleRemapXYZ -{ -public: - static float& x(Triple& triple) - { - return triple.x(); - } - static float& y(Triple& triple) - { - return triple.y(); - } - static float& z(Triple& triple) - { - return triple.z(); - } -}; - -template -class TripleRemapYZX -{ -public: - static float& x(Triple& triple) - { - return triple.y(); - } - static float& y(Triple& triple) - { - return triple.z(); - } - static float& z(Triple& triple) - { - return triple.x(); - } -}; - -template -class TripleRemapZXY -{ -public: - static float& x(Triple& triple) - { - return triple.z(); - } - static float& y(Triple& triple) - { - return triple.x(); - } - static float& z(Triple& triple) - { - return triple.y(); - } -}; - -void vector3_print(const Vector3& v) -{ - globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )"; -} - -class TranslateManipulator : public Manipulator -{ - struct RenderableArrowLine : public OpenGLRenderable - { - PointVertex m_line[2]; - - RenderableArrowLine() - { - } - void render(RenderStateFlags state) const - { - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_line[0].colour); - glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_line[0].vertex); - glDrawArrays(GL_LINES, 0, 2); - } - void setColour(const Colour4b& colour) - { - m_line[0].colour = colour; - m_line[1].colour = colour; - } - }; - struct RenderableArrowHead : public OpenGLRenderable - { - Array m_vertices; - - RenderableArrowHead(std::size_t size) - : m_vertices(size) - { - } - void render(RenderStateFlags state) const - { - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(FlatShadedVertex), &m_vertices.data()->colour); - glVertexPointer(3, GL_FLOAT, sizeof(FlatShadedVertex), &m_vertices.data()->vertex); - glNormalPointer(GL_FLOAT, sizeof(FlatShadedVertex), &m_vertices.data()->normal); - glDrawArrays(GL_TRIANGLES, 0, GLsizei(m_vertices.size())); - } - void setColour(const Colour4b& colour) - { - for(Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i) - { - (*i).colour = colour; - } - } - }; - struct RenderableQuad : public OpenGLRenderable - { - PointVertex m_quad[4]; - void render(RenderStateFlags state) const - { - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_quad[0].colour); - glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_quad[0].vertex); - glDrawArrays(GL_LINE_LOOP, 0, 4); - } - void setColour(const Colour4b& colour) - { - m_quad[0].colour = colour; - m_quad[1].colour = colour; - m_quad[2].colour = colour; - m_quad[3].colour = colour; - } - }; - - TranslateFree m_free; - TranslateAxis m_axis; - RenderableArrowLine m_arrow_x; - RenderableArrowLine m_arrow_y; - RenderableArrowLine m_arrow_z; - RenderableArrowHead m_arrow_head_x; - RenderableArrowHead m_arrow_head_y; - RenderableArrowHead m_arrow_head_z; - RenderableQuad m_quad_screen; - SelectableBool m_selectable_x; - SelectableBool m_selectable_y; - SelectableBool m_selectable_z; - SelectableBool m_selectable_screen; - Pivot2World m_pivot; -public: - static Shader* m_state_wire; - static Shader* m_state_fill; - - TranslateManipulator(Translatable& translatable, std::size_t segments, float length) : - m_free(translatable), - m_axis(translatable), - m_arrow_head_x(3 * 2 * (segments << 3)), - m_arrow_head_y(3 * 2 * (segments << 3)), - m_arrow_head_z(3 * 2 * (segments << 3)) - { - draw_arrowline(length, m_arrow_x.m_line, 0); - draw_arrowhead(segments, length, m_arrow_head_x.m_vertices.data(), TripleRemapXYZ(), TripleRemapXYZ()); - draw_arrowline(length, m_arrow_y.m_line, 1); - draw_arrowhead(segments, length, m_arrow_head_y.m_vertices.data(), TripleRemapYZX(), TripleRemapYZX()); - draw_arrowline(length, m_arrow_z.m_line, 2); - draw_arrowhead(segments, length, m_arrow_head_z.m_vertices.data(), TripleRemapZXY(), TripleRemapZXY()); - - draw_quad(16, m_quad_screen.m_quad); - } - - void UpdateColours() - { - m_arrow_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); - m_arrow_head_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); - m_arrow_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); - m_arrow_head_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); - m_arrow_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); - m_arrow_head_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); - m_quad_screen.setColour(colourSelected(g_colour_screen, m_selectable_screen.isSelected())); - } - - bool manipulator_show_axis(const Pivot2World& pivot, const Vector3& axis) - { - return fabs(vector3_dot(pivot.m_axis_screen, axis)) < 0.95; - } - - void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) - { - m_pivot.update(pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport()); - - // temp hack - UpdateColours(); - - Vector3 x = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.x())); - bool show_x = manipulator_show_axis(m_pivot, x); - - Vector3 y = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.y())); - bool show_y = manipulator_show_axis(m_pivot, y); - - Vector3 z = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.z())); - bool show_z = manipulator_show_axis(m_pivot, z); - - renderer.SetState(m_state_wire, Renderer::eWireframeOnly); - renderer.SetState(m_state_wire, Renderer::eFullMaterials); - - if(show_x) - { - renderer.addRenderable(m_arrow_x, m_pivot.m_worldSpace); - } - if(show_y) - { - renderer.addRenderable(m_arrow_y, m_pivot.m_worldSpace); - } - if(show_z) - { - renderer.addRenderable(m_arrow_z, m_pivot.m_worldSpace); - } - - renderer.addRenderable(m_quad_screen, m_pivot.m_viewplaneSpace); - - renderer.SetState(m_state_fill, Renderer::eWireframeOnly); - renderer.SetState(m_state_fill, Renderer::eFullMaterials); - - if(show_x) - { - renderer.addRenderable(m_arrow_head_x, m_pivot.m_worldSpace); - } - if(show_y) - { - renderer.addRenderable(m_arrow_head_y, m_pivot.m_worldSpace); - } - if(show_z) - { - renderer.addRenderable(m_arrow_head_z, m_pivot.m_worldSpace); - } - } - void testSelect(const View& view, const Matrix4& pivot2world) - { - m_pivot.update(pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport()); - - SelectionPool selector; - - Vector3 x = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.x())); - bool show_x = manipulator_show_axis(m_pivot, x); - - Vector3 y = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.y())); - bool show_y = manipulator_show_axis(m_pivot, y); - - Vector3 z = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.z())); - bool show_z = manipulator_show_axis(m_pivot, z); - - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_viewpointSpace)); - - { - SelectionIntersection best; - Quad_BestPoint(local2view, eClipCullCW, m_quad_screen.m_quad, best); - if(best.valid()) - { - best = SelectionIntersection(0, 0); - selector.addSelectable(best, &m_selectable_screen); - } - } - } - - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_worldSpace)); - -#if defined(DEBUG_SELECTION) - g_render_clipped.construct(view.GetViewMatrix()); -#endif - - if(show_x) - { - SelectionIntersection best; - Line_BestPoint(local2view, m_arrow_x.m_line, best); - Triangles_BestPoint(local2view, eClipCullCW, m_arrow_head_x.m_vertices.begin(), m_arrow_head_x.m_vertices.end(), best); - selector.addSelectable(best, &m_selectable_x); - } - - if(show_y) - { - SelectionIntersection best; - Line_BestPoint(local2view, m_arrow_y.m_line, best); - Triangles_BestPoint(local2view, eClipCullCW, m_arrow_head_y.m_vertices.begin(), m_arrow_head_y.m_vertices.end(), best); - selector.addSelectable(best, &m_selectable_y); - } - - if(show_z) - { - SelectionIntersection best; - Line_BestPoint(local2view, m_arrow_z.m_line, best); - Triangles_BestPoint(local2view, eClipCullCW, m_arrow_head_z.m_vertices.begin(), m_arrow_head_z.m_vertices.end(), best); - selector.addSelectable(best, &m_selectable_z); - } - } - - if(!selector.failed()) - { - (*selector.begin()).second->setSelected(true); - } - } - - Manipulatable* GetManipulatable() - { - if(m_selectable_x.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_x); - return &m_axis; - } - else if(m_selectable_y.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_y); - return &m_axis; - } - else if(m_selectable_z.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_z); - return &m_axis; - } - else - { - return &m_free; - } - } - - void setSelected(bool select) - { - m_selectable_x.setSelected(select); - m_selectable_y.setSelected(select); - m_selectable_z.setSelected(select); - m_selectable_screen.setSelected(select); - } - bool isSelected() const - { - return m_selectable_x.isSelected() - | m_selectable_y.isSelected() - | m_selectable_z.isSelected() - | m_selectable_screen.isSelected(); - } -}; - -Shader* TranslateManipulator::m_state_wire; -Shader* TranslateManipulator::m_state_fill; - -class ScaleManipulator : public Manipulator -{ - struct RenderableArrow : public OpenGLRenderable - { - PointVertex m_line[2]; - - void render(RenderStateFlags state) const - { - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_line[0].colour); - glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_line[0].vertex); - glDrawArrays(GL_LINES, 0, 2); - } - void setColour(const Colour4b& colour) - { - m_line[0].colour = colour; - m_line[1].colour = colour; - } - }; - struct RenderableQuad : public OpenGLRenderable - { - PointVertex m_quad[4]; - void render(RenderStateFlags state) const - { - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_quad[0].colour); - glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_quad[0].vertex); - glDrawArrays(GL_QUADS, 0, 4); - } - void setColour(const Colour4b& colour) - { - m_quad[0].colour = colour; - m_quad[1].colour = colour; - m_quad[2].colour = colour; - m_quad[3].colour = colour; - } - }; - - ScaleFree m_free; - ScaleAxis m_axis; - RenderableArrow m_arrow_x; - RenderableArrow m_arrow_y; - RenderableArrow m_arrow_z; - RenderableQuad m_quad_screen; - SelectableBool m_selectable_x; - SelectableBool m_selectable_y; - SelectableBool m_selectable_z; - SelectableBool m_selectable_screen; - Pivot2World m_pivot; -public: - ScaleManipulator(Scalable& scalable, std::size_t segments, float length) : - m_free(scalable), - m_axis(scalable) - { - draw_arrowline(length, m_arrow_x.m_line, 0); - draw_arrowline(length, m_arrow_y.m_line, 1); - draw_arrowline(length, m_arrow_z.m_line, 2); - - draw_quad(16, m_quad_screen.m_quad); - } - - Pivot2World& getPivot() - { - return m_pivot; - } - - void UpdateColours() - { - m_arrow_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); - m_arrow_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); - m_arrow_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); - m_quad_screen.setColour(colourSelected(g_colour_screen, m_selectable_screen.isSelected())); - } - - void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) - { - m_pivot.update(pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport()); - - // temp hack - UpdateColours(); - - renderer.addRenderable(m_arrow_x, m_pivot.m_worldSpace); - renderer.addRenderable(m_arrow_y, m_pivot.m_worldSpace); - renderer.addRenderable(m_arrow_z, m_pivot.m_worldSpace); - - renderer.addRenderable(m_quad_screen, m_pivot.m_viewpointSpace); - } - void testSelect(const View& view, const Matrix4& pivot2world) - { - m_pivot.update(pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport()); - - SelectionPool selector; - - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_worldSpace)); - -#if defined(DEBUG_SELECTION) - g_render_clipped.construct(view.GetViewMatrix()); -#endif - - { - SelectionIntersection best; - Line_BestPoint(local2view, m_arrow_x.m_line, best); - selector.addSelectable(best, &m_selectable_x); - } - - { - SelectionIntersection best; - Line_BestPoint(local2view, m_arrow_y.m_line, best); - selector.addSelectable(best, &m_selectable_y); - } - - { - SelectionIntersection best; - Line_BestPoint(local2view, m_arrow_z.m_line, best); - selector.addSelectable(best, &m_selectable_z); - } - } - - { - Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_viewpointSpace)); - - { - SelectionIntersection best; - Quad_BestPoint(local2view, eClipCullCW, m_quad_screen.m_quad, best); - selector.addSelectable(best, &m_selectable_screen); - } - } - - if(!selector.failed()) - { - (*selector.begin()).second->setSelected(true); - } - } - - Manipulatable* GetManipulatable() - { - if(m_selectable_x.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_x); - return &m_axis; - } - else if(m_selectable_y.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_y); - return &m_axis; - } - else if(m_selectable_z.isSelected()) - { - m_axis.SetAxis(g_vector3_axis_z); - return &m_axis; - } - else - return &m_free; - } - - void setSelected(bool select) - { - m_selectable_x.setSelected(select); - m_selectable_y.setSelected(select); - m_selectable_z.setSelected(select); - m_selectable_screen.setSelected(select); - } - bool isSelected() const - { - return m_selectable_x.isSelected() - | m_selectable_y.isSelected() - | m_selectable_z.isSelected() - | m_selectable_screen.isSelected(); - } -}; - - -inline PlaneSelectable* Instance_getPlaneSelectable(scene::Instance& instance) -{ - return InstanceTypeCast::cast(instance); -} - -class PlaneSelectableSelectPlanes : public scene::Graph::Walker -{ - Selector& m_selector; - SelectionTest& m_test; - PlaneCallback m_selectedPlaneCallback; -public: - PlaneSelectableSelectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) - : m_selector(selector), m_test(test), m_selectedPlaneCallback(selectedPlaneCallback) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 && selectable->isSelected()) - { - PlaneSelectable* planeSelectable = Instance_getPlaneSelectable(instance); - if(planeSelectable != 0) - { - planeSelectable->selectPlanes(m_selector, m_test, m_selectedPlaneCallback); - } - } - } - return true; - } -}; - -class PlaneSelectableSelectReversedPlanes : public scene::Graph::Walker -{ - Selector& m_selector; - const SelectedPlanes& m_selectedPlanes; -public: - PlaneSelectableSelectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) - : m_selector(selector), m_selectedPlanes(selectedPlanes) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 && selectable->isSelected()) - { - PlaneSelectable* planeSelectable = Instance_getPlaneSelectable(instance); - if(planeSelectable != 0) - { - planeSelectable->selectReversedPlanes(m_selector, m_selectedPlanes); - } - } - } - return true; - } -}; - -void Scene_forEachPlaneSelectable_selectPlanes(scene::Graph& graph, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) -{ - graph.traverse(PlaneSelectableSelectPlanes(selector, test, selectedPlaneCallback)); -} - -void Scene_forEachPlaneSelectable_selectReversedPlanes(scene::Graph& graph, Selector& selector, const SelectedPlanes& selectedPlanes) -{ - graph.traverse(PlaneSelectableSelectReversedPlanes(selector, selectedPlanes)); -} - - -class PlaneLess -{ -public: - bool operator()(const Plane3& plane, const Plane3& other) const - { - if(plane.a < other.a) - { - return true; - } - if(other.a < plane.a) - { - return false; - } - - if(plane.b < other.b) - { - return true; - } - if(other.b < plane.b) - { - return false; - } - - if(plane.c < other.c) - { - return true; - } - if(other.c < plane.c) - { - return false; - } - - if(plane.d < other.d) - { - return true; - } - if(other.d < plane.d) - { - return false; - } - - return false; - } -}; - -typedef std::set PlaneSet; - -inline void PlaneSet_insert(PlaneSet& self, const Plane3& plane) -{ - self.insert(plane); -} - -inline bool PlaneSet_contains(const PlaneSet& self, const Plane3& plane) -{ - return self.find(plane) != self.end(); -} - - -class SelectedPlaneSet : public SelectedPlanes -{ - PlaneSet m_selectedPlanes; -public: - bool empty() const - { - return m_selectedPlanes.empty(); - } - - void insert(const Plane3& plane) - { - PlaneSet_insert(m_selectedPlanes, plane); - } - bool contains(const Plane3& plane) const - { - return PlaneSet_contains(m_selectedPlanes, plane); - } - typedef MemberCaller1 InsertCaller; -}; - - -bool Scene_forEachPlaneSelectable_selectPlanes(scene::Graph& graph, Selector& selector, SelectionTest& test) -{ - SelectedPlaneSet selectedPlanes; - - Scene_forEachPlaneSelectable_selectPlanes(graph, selector, test, SelectedPlaneSet::InsertCaller(selectedPlanes)); - Scene_forEachPlaneSelectable_selectReversedPlanes(graph, selector, selectedPlanes); - - return !selectedPlanes.empty(); -} - -void Scene_Translate_Component_Selected(scene::Graph& graph, const Vector3& translation); -void Scene_Translate_Selected(scene::Graph& graph, const Vector3& translation); -void Scene_TestSelect_Primitive(Selector& selector, SelectionTest& test, const VolumeTest& volume); -void Scene_TestSelect_Component(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode); -void Scene_TestSelect_Component_Selected(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode); -void Scene_SelectAll_Component(bool select, SelectionSystem::EComponentMode componentMode); - -class ResizeTranslatable : public Translatable -{ - void translate(const Vector3& translation) - { - Scene_Translate_Component_Selected(GlobalSceneGraph(), translation); - } -}; - -class DragTranslatable : public Translatable -{ - void translate(const Vector3& translation) - { - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) - { - Scene_Translate_Component_Selected(GlobalSceneGraph(), translation); - } - else - { - Scene_Translate_Selected(GlobalSceneGraph(), translation); - } - } -}; - -class SelectionVolume : public SelectionTest -{ - Matrix4 m_local2view; - const View& m_view; - clipcull_t m_cull; - Vector3 m_near; - Vector3 m_far; -public: - SelectionVolume(const View& view) - : m_view(view) - { - } - - const VolumeTest& getVolume() const - { - return m_view; - } - - const Vector3& getNear() const - { - return m_near; - } - const Vector3& getFar() const - { - return m_far; - } - - void BeginMesh(const Matrix4& localToWorld, bool twoSided) - { - m_local2view = matrix4_multiplied_by_matrix4(m_view.GetViewMatrix(), localToWorld); - - // Cull back-facing polygons based on winding being clockwise or counter-clockwise. - // Don't cull if the view is wireframe and the polygons are two-sided. - m_cull = twoSided && !m_view.fill() ? eClipCullNone : (matrix4_handedness(localToWorld) == MATRIX4_RIGHTHANDED) ? eClipCullCW : eClipCullCCW; - - { - Matrix4 screen2world(matrix4_full_inverse(m_local2view)); - - m_near = vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4(0, 0, -1, 1) - ) - ); - - m_far = vector4_projected( - matrix4_transformed_vector4( - screen2world, - Vector4(0, 0, 1, 1) - ) - ); - } - -#if defined(DEBUG_SELECTION) - g_render_clipped.construct(m_view.GetViewMatrix()); -#endif - } - void TestPoint(const Vector3& point, SelectionIntersection& best) - { - Vector4 clipped; - if(matrix4_clip_point(m_local2view, point, clipped) == c_CLIP_PASS) - { - best = select_point_from_clipped(clipped); - } - } - void TestPolygon(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) - { - Vector4 clipped[9]; - for(std::size_t i=0; i+2(vertices[0]), - reinterpret_cast(vertices[i+1]), - reinterpret_cast(vertices[i+2]), - clipped - ), - clipped, - best, - m_cull - ); - } - } - void TestLineLoop(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) - { - if(count == 0) - return; - Vector4 clipped[9]; - for(VertexPointer::iterator i = vertices.begin(), end = i + count, prev = i + (count-1); i != end; prev = i, ++i) - { - BestPoint( - matrix4_clip_line( - m_local2view, - reinterpret_cast((*prev)), - reinterpret_cast((*i)), - clipped - ), - clipped, - best, - m_cull - ); - } - } - void TestLineStrip(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) - { - if(count == 0) - return; - Vector4 clipped[9]; - for(VertexPointer::iterator i = vertices.begin(), end = i + count, next = i + 1; next != end; i = next, ++next) - { - BestPoint( - matrix4_clip_line( - m_local2view, - reinterpret_cast((*i)), - reinterpret_cast((*next)), - clipped - ), - clipped, - best, - m_cull - ); - } - } - void TestLines(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) - { - if(count == 0) - return; - Vector4 clipped[9]; - for(VertexPointer::iterator i = vertices.begin(), end = i + count; i != end; i += 2) - { - BestPoint( - matrix4_clip_line( - m_local2view, - reinterpret_cast((*i)), - reinterpret_cast((*(i+1))), - clipped - ), - clipped, - best, - m_cull - ); - } - } - void TestTriangles(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) - { - Vector4 clipped[9]; - for(IndexPointer::iterator i(indices.begin()); i != indices.end(); i += 3) - { - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast(vertices[*i]), - reinterpret_cast(vertices[*(i+1)]), - reinterpret_cast(vertices[*(i+2)]), - clipped - ), - clipped, - best, - m_cull - ); - } - } - void TestQuads(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) - { - Vector4 clipped[9]; - for(IndexPointer::iterator i(indices.begin()); i != indices.end(); i += 4) - { - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast(vertices[*i]), - reinterpret_cast(vertices[*(i+1)]), - reinterpret_cast(vertices[*(i+3)]), - clipped - ), - clipped, - best, - m_cull - ); - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast(vertices[*(i+1)]), - reinterpret_cast(vertices[*(i+2)]), - reinterpret_cast(vertices[*(i+3)]), - clipped - ), - clipped, - best, - m_cull - ); - } - } - void TestQuadStrip(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) - { - Vector4 clipped[9]; - for(IndexPointer::iterator i(indices.begin()); i+2 != indices.end(); i += 2) - { - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast(vertices[*i]), - reinterpret_cast(vertices[*(i+1)]), - reinterpret_cast(vertices[*(i+2)]), - clipped - ), - clipped, - best, - m_cull - ); - BestPoint( - matrix4_clip_triangle( - m_local2view, - reinterpret_cast(vertices[*(i+2)]), - reinterpret_cast(vertices[*(i+1)]), - reinterpret_cast(vertices[*(i+3)]), - clipped - ), - clipped, - best, - m_cull - ); - } - } -}; - -class SelectionCounter -{ -public: - typedef const Selectable& first_argument_type; - - SelectionCounter(const SelectionChangeCallback& onchanged) - : m_count(0), m_onchanged(onchanged) - { - } - void operator()(const Selectable& selectable) - { - if(selectable.isSelected()) - { - ++m_count; - } - else - { - ASSERT_MESSAGE(m_count != 0, "selection counter underflow"); - --m_count; - } - - m_onchanged(selectable); - } - bool empty() const - { - return m_count == 0; - } - std::size_t size() const - { - return m_count; - } -private: - std::size_t m_count; - SelectionChangeCallback m_onchanged; -}; - -inline void ConstructSelectionTest(View& view, const rect_t selection_box) -{ - view.EnableScissor(selection_box.min[0], selection_box.max[0], selection_box.min[1], selection_box.max[1]); -} - -inline const rect_t SelectionBoxForPoint(const float device_point[2], const float device_epsilon[2]) -{ - rect_t selection_box; - selection_box.min[0] = device_point[0] - device_epsilon[0]; - selection_box.min[1] = device_point[1] - device_epsilon[1]; - selection_box.max[0] = device_point[0] + device_epsilon[0]; - selection_box.max[1] = device_point[1] + device_epsilon[1]; - return selection_box; -} - -inline const rect_t SelectionBoxForArea(const float device_point[2], const float device_delta[2]) -{ - rect_t selection_box; - selection_box.min[0] = (device_delta[0] < 0) ? (device_point[0] + device_delta[0]) : (device_point[0]); - selection_box.min[1] = (device_delta[1] < 0) ? (device_point[1] + device_delta[1]) : (device_point[1]); - selection_box.max[0] = (device_delta[0] > 0) ? (device_point[0] + device_delta[0]) : (device_point[0]); - selection_box.max[1] = (device_delta[1] > 0) ? (device_point[1] + device_delta[1]) : (device_point[1]); - return selection_box; -} - -Quaternion construct_local_rotation(const Quaternion& world, const Quaternion& localToWorld) -{ - return quaternion_normalised(quaternion_multiplied_by_quaternion( - quaternion_normalised(quaternion_multiplied_by_quaternion( - quaternion_inverse(localToWorld), - world - )), - localToWorld - )); -} - -inline void matrix4_assign_rotation(Matrix4& matrix, const Matrix4& other) -{ - matrix[0] = other[0]; - matrix[1] = other[1]; - matrix[2] = other[2]; - matrix[4] = other[4]; - matrix[5] = other[5]; - matrix[6] = other[6]; - matrix[8] = other[8]; - matrix[9] = other[9]; - matrix[10] = other[10]; -} - -void matrix4_assign_rotation_for_pivot(Matrix4& matrix, scene::Instance& instance) -{ - Editable* editable = Node_getEditable(instance.path().top()); - if(editable != 0) - { - matrix4_assign_rotation(matrix, matrix4_multiplied_by_matrix4(instance.localToWorld(), editable->getLocalPivot())); - } - else - { - matrix4_assign_rotation(matrix, instance.localToWorld()); - } -} - -inline bool Instance_isSelectedComponents(scene::Instance& instance) -{ - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); - return componentSelectionTestable != 0 - && componentSelectionTestable->isSelectedComponents(); -} - -class TranslateSelected : public SelectionSystem::Visitor -{ - const Vector3& m_translate; -public: - TranslateSelected(const Vector3& translate) - : m_translate(translate) - { - } - void visit(scene::Instance& instance) const - { - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - transform->setType(TRANSFORM_PRIMITIVE); - transform->setTranslation(m_translate); - } - } -}; - -void Scene_Translate_Selected(scene::Graph& graph, const Vector3& translation) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - GlobalSelectionSystem().foreachSelected(TranslateSelected(translation)); - } -} - -Vector3 get_local_pivot(const Vector3& world_pivot, const Matrix4& localToWorld) -{ - return Vector3( - matrix4_transformed_point( - matrix4_full_inverse(localToWorld), - world_pivot - ) - ); -} - -void translation_for_pivoted_matrix_transform(Vector3& parent_translation, const Matrix4& local_transform, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent) -{ - // we need a translation inside the parent system to move the origin of this object to the right place - - // mathematically, it must fulfill: - // - // local_translation local_transform local_pivot = local_pivot - // local_translation = local_pivot - local_transform local_pivot - // - // or maybe? - // local_transform local_translation local_pivot = local_pivot - // local_translation local_pivot = local_transform^-1 local_pivot - // local_translation + local_pivot = local_transform^-1 local_pivot - // local_translation = local_transform^-1 local_pivot - local_pivot - - Vector3 local_pivot(get_local_pivot(world_pivot, localToWorld)); - - Vector3 local_translation( - vector3_subtracted( - local_pivot, - matrix4_transformed_point( - local_transform, - local_pivot - ) - /* - matrix4_transformed_point( - matrix4_full_inverse(local_transform), - local_pivot - ), - local_pivot - */ - ) - ); - - translation_local2object(parent_translation, local_translation, localToParent); - - /* - // verify it! - globalOutputStream() << "World pivot is at " << world_pivot << "\n"; - globalOutputStream() << "Local pivot is at " << local_pivot << "\n"; - globalOutputStream() << "Transformation " << local_transform << " moves it to: " << matrix4_transformed_point(local_transform, local_pivot) << "\n"; - globalOutputStream() << "Must move by " << local_translation << " in the local system" << "\n"; - globalOutputStream() << "Must move by " << parent_translation << " in the parent system" << "\n"; - */ -} - -void translation_for_pivoted_rotation(Vector3& parent_translation, const Quaternion& local_rotation, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent) -{ - translation_for_pivoted_matrix_transform(parent_translation, matrix4_rotation_for_quaternion_quantised(local_rotation), world_pivot, localToWorld, localToParent); -} - -void translation_for_pivoted_scale(Vector3& parent_translation, const Vector3& world_scale, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent) -{ - Matrix4 local_transform( - matrix4_multiplied_by_matrix4( - matrix4_full_inverse(localToWorld), - matrix4_multiplied_by_matrix4( - matrix4_scale_for_vec3(world_scale), - localToWorld - ) - ) - ); - local_transform.tx() = local_transform.ty() = local_transform.tz() = 0; // cancel translation parts - translation_for_pivoted_matrix_transform(parent_translation, local_transform, world_pivot, localToWorld, localToParent); -} - -class rotate_selected : public SelectionSystem::Visitor -{ - const Quaternion& m_rotate; - const Vector3& m_world_pivot; -public: - rotate_selected(const Quaternion& rotation, const Vector3& world_pivot) - : m_rotate(rotation), m_world_pivot(world_pivot) - { - } - void visit(scene::Instance& instance) const - { - TransformNode* transformNode = Node_getTransformNode(instance.path().top()); - if(transformNode != 0) - { - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - transform->setType(TRANSFORM_PRIMITIVE); - transform->setScale(c_scale_identity); - transform->setTranslation(c_translation_identity); - - transform->setType(TRANSFORM_PRIMITIVE); - transform->setRotation(m_rotate); - - { - Editable* editable = Node_getEditable(instance.path().top()); - const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; - - Vector3 parent_translation; - translation_for_pivoted_rotation( - parent_translation, - m_rotate, - m_world_pivot, - matrix4_multiplied_by_matrix4(instance.localToWorld(), localPivot), - matrix4_multiplied_by_matrix4(transformNode->localToParent(), localPivot) - ); - - transform->setTranslation(parent_translation); - } - } - } - } -}; - -void Scene_Rotate_Selected(scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - GlobalSelectionSystem().foreachSelected(rotate_selected(rotation, world_pivot)); - } -} - -class scale_selected : public SelectionSystem::Visitor -{ - const Vector3& m_scale; - const Vector3& m_world_pivot; -public: - scale_selected(const Vector3& scaling, const Vector3& world_pivot) - : m_scale(scaling), m_world_pivot(world_pivot) - { - } - void visit(scene::Instance& instance) const - { - TransformNode* transformNode = Node_getTransformNode(instance.path().top()); - if(transformNode != 0) - { - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - transform->setType(TRANSFORM_PRIMITIVE); - transform->setScale(c_scale_identity); - transform->setTranslation(c_translation_identity); - - transform->setType(TRANSFORM_PRIMITIVE); - transform->setScale(m_scale); - { - Editable* editable = Node_getEditable(instance.path().top()); - const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; - - Vector3 parent_translation; - translation_for_pivoted_scale( - parent_translation, - m_scale, - m_world_pivot, - matrix4_multiplied_by_matrix4(instance.localToWorld(), localPivot), - matrix4_multiplied_by_matrix4(transformNode->localToParent(), localPivot) - ); - - transform->setTranslation(parent_translation); - } - } - } - } -}; - -void Scene_Scale_Selected(scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - GlobalSelectionSystem().foreachSelected(scale_selected(scaling, world_pivot)); - } -} - - -class translate_component_selected : public SelectionSystem::Visitor -{ - const Vector3& m_translate; -public: - translate_component_selected(const Vector3& translate) - : m_translate(translate) - { - } - void visit(scene::Instance& instance) const - { - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - transform->setType(TRANSFORM_COMPONENT); - transform->setTranslation(m_translate); - } - } -}; - -void Scene_Translate_Component_Selected(scene::Graph& graph, const Vector3& translation) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - GlobalSelectionSystem().foreachSelectedComponent(translate_component_selected(translation)); - } -} - -class rotate_component_selected : public SelectionSystem::Visitor -{ - const Quaternion& m_rotate; - const Vector3& m_world_pivot; -public: - rotate_component_selected(const Quaternion& rotation, const Vector3& world_pivot) - : m_rotate(rotation), m_world_pivot(world_pivot) - { - } - void visit(scene::Instance& instance) const - { - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - Vector3 parent_translation; - translation_for_pivoted_rotation(parent_translation, m_rotate, m_world_pivot, instance.localToWorld(), Node_getTransformNode(instance.path().top())->localToParent()); - - transform->setType(TRANSFORM_COMPONENT); - transform->setRotation(m_rotate); - transform->setTranslation(parent_translation); - } - } -}; - -void Scene_Rotate_Component_Selected(scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot) -{ - if(GlobalSelectionSystem().countSelectedComponents() != 0) - { - GlobalSelectionSystem().foreachSelectedComponent(rotate_component_selected(rotation, world_pivot)); - } -} - -class scale_component_selected : public SelectionSystem::Visitor -{ - const Vector3& m_scale; - const Vector3& m_world_pivot; -public: - scale_component_selected(const Vector3& scaling, const Vector3& world_pivot) - : m_scale(scaling), m_world_pivot(world_pivot) - { - } - void visit(scene::Instance& instance) const - { - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - Vector3 parent_translation; - translation_for_pivoted_scale(parent_translation, m_scale, m_world_pivot, instance.localToWorld(), Node_getTransformNode(instance.path().top())->localToParent()); - - transform->setType(TRANSFORM_COMPONENT); - transform->setScale(m_scale); - transform->setTranslation(parent_translation); - } - } -}; - -void Scene_Scale_Component_Selected(scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot) -{ - if(GlobalSelectionSystem().countSelectedComponents() != 0) - { - GlobalSelectionSystem().foreachSelectedComponent(scale_component_selected(scaling, world_pivot)); - } -} - - -class BooleanSelector : public Selector -{ - bool m_selected; - SelectionIntersection m_intersection; - Selectable* m_selectable; -public: - BooleanSelector() : m_selected(false) - { - } - - void pushSelectable(Selectable& selectable) - { - m_intersection = SelectionIntersection(); - m_selectable = &selectable; - } - void popSelectable() - { - if(m_intersection.valid()) - { - m_selected = true; - } - m_intersection = SelectionIntersection(); - } - void addIntersection(const SelectionIntersection& intersection) - { - if(m_selectable->isSelected()) - { - assign_if_closer(m_intersection, intersection); - } - } - - bool isSelected() - { - return m_selected; - } -}; - -class BestSelector : public Selector -{ - SelectionIntersection m_intersection; - Selectable* m_selectable; - SelectionIntersection m_bestIntersection; - std::list m_bestSelectable; -public: - BestSelector() : m_bestIntersection(SelectionIntersection()), m_bestSelectable(0) - { - } - - void pushSelectable(Selectable& selectable) - { - m_intersection = SelectionIntersection(); - m_selectable = &selectable; - } - void popSelectable() - { - if(m_intersection.equalEpsilon(m_bestIntersection, 0.25f, 0.001f)) - { - m_bestSelectable.push_back(m_selectable); - m_bestIntersection = m_intersection; - } - else if(m_intersection < m_bestIntersection) - { - m_bestSelectable.clear(); - m_bestSelectable.push_back(m_selectable); - m_bestIntersection = m_intersection; - } - m_intersection = SelectionIntersection(); - } - void addIntersection(const SelectionIntersection& intersection) - { - assign_if_closer(m_intersection, intersection); - } - - std::list& best() - { - return m_bestSelectable; - } -}; - -class DragManipulator : public Manipulator -{ - TranslateFree m_freeResize; - TranslateFree m_freeDrag; - ResizeTranslatable m_resize; - DragTranslatable m_drag; - SelectableBool m_dragSelectable; -public: - - bool m_selected; - - DragManipulator() : m_freeResize(m_resize), m_freeDrag(m_drag), m_selected(false) - { - } - - Manipulatable* GetManipulatable() - { - return m_dragSelectable.isSelected() ? &m_freeDrag : &m_freeResize; - } - - void testSelect(const View& view, const Matrix4& pivot2world) - { - SelectionPool selector; - - SelectionVolume test(view); - - if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) - { - BooleanSelector booleanSelector; - - Scene_TestSelect_Primitive(booleanSelector, test, view); - - if(booleanSelector.isSelected()) - { - selector.addSelectable(SelectionIntersection(0, 0), &m_dragSelectable); - m_selected = false; - } - else - { - m_selected = Scene_forEachPlaneSelectable_selectPlanes(GlobalSceneGraph(), selector, test); - } - } - else - { - BestSelector bestSelector; - Scene_TestSelect_Component_Selected(bestSelector, test, view, GlobalSelectionSystem().ComponentMode()); - for(std::list::iterator i = bestSelector.best().begin(); i != bestSelector.best().end(); ++i) - { - if(!(*i)->isSelected()) - { - GlobalSelectionSystem().setSelectedAllComponents(false); - } - m_selected = false; - selector.addSelectable(SelectionIntersection(0, 0), (*i)); - m_dragSelectable.setSelected(true); - } - } - - for(SelectionPool::iterator i = selector.begin(); i != selector.end(); ++i) - { - (*i).second->setSelected(true); - } - } - - void setSelected(bool select) - { - m_selected = select; - m_dragSelectable.setSelected(select); - } - bool isSelected() const - { - return m_selected || m_dragSelectable.isSelected(); - } -}; - -class ClipManipulator : public Manipulator -{ -public: - - Manipulatable* GetManipulatable() - { - ERROR_MESSAGE("clipper is not manipulatable"); - return 0; - } - - void setSelected(bool select) - { - } - bool isSelected() const - { - return false; - } -}; - -class select_all : public scene::Graph::Walker -{ - bool m_select; -public: - select_all(bool select) - : m_select(select) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0) - { - selectable->setSelected(m_select); - } - return true; - } -}; - -class select_all_component : public scene::Graph::Walker -{ - bool m_select; - SelectionSystem::EComponentMode m_mode; -public: - select_all_component(bool select, SelectionSystem::EComponentMode mode) - : m_select(select), m_mode(mode) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); - if(componentSelectionTestable) - { - componentSelectionTestable->setSelectedComponents(m_select, m_mode); - } - return true; - } -}; - -void Scene_SelectAll_Component(bool select, SelectionSystem::EComponentMode componentMode) -{ - GlobalSceneGraph().traverse(select_all_component(select, componentMode)); -} - - -// RadiantSelectionSystem -class RadiantSelectionSystem : - public SelectionSystem, - public Translatable, - public Rotatable, - public Scalable, - public Renderable -{ - mutable Matrix4 m_pivot2world; - Matrix4 m_pivot2world_start; - Matrix4 m_manip2pivot_start; - Translation m_translation; - Rotation m_rotation; - Scale m_scale; -public: - static Shader* m_state; -private: - EManipulatorMode m_manipulator_mode; - Manipulator* m_manipulator; - - // state - bool m_undo_begun; - EMode m_mode; - EComponentMode m_componentmode; - - SelectionCounter m_count_primitive; - SelectionCounter m_count_component; - - TranslateManipulator m_translate_manipulator; - RotateManipulator m_rotate_manipulator; - ScaleManipulator m_scale_manipulator; - DragManipulator m_drag_manipulator; - ClipManipulator m_clip_manipulator; - - typedef SelectionList selection_t; - selection_t m_selection; - selection_t m_component_selection; - - Signal1 m_selectionChanged_callbacks; - - void ConstructPivot() const; - mutable bool m_pivotChanged; - bool m_pivot_moving; - - void Scene_TestSelect(Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode); - - bool nothingSelected() const - { - return (Mode() == eComponent && m_count_component.empty()) - || (Mode() == ePrimitive && m_count_primitive.empty()); - } - - -public: - enum EModifier - { - eManipulator, - eToggle, - eReplace, - eCycle, - }; - - RadiantSelectionSystem() : - m_undo_begun(false), - m_mode(ePrimitive), - m_componentmode(eDefault), - m_count_primitive(SelectionChangedCaller(*this)), - m_count_component(SelectionChangedCaller(*this)), - m_translate_manipulator(*this, 2, 64), - m_rotate_manipulator(*this, 8, 64), - m_scale_manipulator(*this, 0, 64), - m_pivotChanged(false), - m_pivot_moving(false) - { - SetManipulatorMode(eTranslate); - pivotChanged(); - addSelectionChangeCallback(PivotChangedSelectionCaller(*this)); - AddGridChangeCallback(PivotChangedCaller(*this)); - } - void pivotChanged() const - { - m_pivotChanged = true; - SceneChangeNotify(); - } - typedef ConstMemberCaller PivotChangedCaller; - void pivotChangedSelection(const Selectable& selectable) - { - pivotChanged(); - } - typedef MemberCaller1 PivotChangedSelectionCaller; - - void SetMode(EMode mode) - { - if(m_mode != mode) - { - m_mode = mode; - pivotChanged(); - } - } - EMode Mode() const - { - return m_mode; - } - void SetComponentMode(EComponentMode mode) - { - m_componentmode = mode; - } - EComponentMode ComponentMode() const - { - return m_componentmode; - } - void SetManipulatorMode(EManipulatorMode mode) - { - m_manipulator_mode = mode; - switch(m_manipulator_mode) - { - case eTranslate: m_manipulator = &m_translate_manipulator; break; - case eRotate: m_manipulator = &m_rotate_manipulator; break; - case eScale: m_manipulator = &m_scale_manipulator; break; - case eDrag: m_manipulator = &m_drag_manipulator; break; - case eClip: m_manipulator = &m_clip_manipulator; break; - } - pivotChanged(); - } - EManipulatorMode ManipulatorMode() const - { - return m_manipulator_mode; - } - - SelectionChangeCallback getObserver(EMode mode) - { - if(mode == ePrimitive) - { - return makeCallback1(m_count_primitive); - } - else - { - return makeCallback1(m_count_component); - } - } - std::size_t countSelected() const - { - return m_count_primitive.size(); - } - std::size_t countSelectedComponents() const - { - return m_count_component.size(); - } - void onSelectedChanged(scene::Instance& instance, const Selectable& selectable) - { - if(selectable.isSelected()) - { - m_selection.append(instance); - } - else - { - m_selection.erase(instance); - } - - ASSERT_MESSAGE(m_selection.size() == m_count_primitive.size(), "selection-tracking error"); - } - void onComponentSelection(scene::Instance& instance, const Selectable& selectable) - { - if(selectable.isSelected()) - { - m_component_selection.append(instance); - } - else - { - m_component_selection.erase(instance); - } - - ASSERT_MESSAGE(m_component_selection.size() == m_count_component.size(), "selection-tracking error"); - } - scene::Instance& ultimateSelected() const - { - ASSERT_MESSAGE(m_selection.size() > 0, "no instance selected"); - return m_selection.back(); - } - scene::Instance& penultimateSelected() const - { - ASSERT_MESSAGE(m_selection.size() > 1, "only one instance selected"); - return *(*(--(--m_selection.end()))); - } - void setSelectedAll(bool selected) - { - GlobalSceneGraph().traverse(select_all(selected)); - - m_manipulator->setSelected(selected); - } - void setSelectedAllComponents(bool selected) - { - Scene_SelectAll_Component(selected, SelectionSystem::eVertex); - Scene_SelectAll_Component(selected, SelectionSystem::eEdge); - Scene_SelectAll_Component(selected, SelectionSystem::eFace); - - m_manipulator->setSelected(selected); - } - - void foreachSelected(const Visitor& visitor) const - { - selection_t::const_iterator i = m_selection.begin(); - while(i != m_selection.end()) - { - visitor.visit(*(*(i++))); - } - } - void foreachSelectedComponent(const Visitor& visitor) const - { - selection_t::const_iterator i = m_component_selection.begin(); - while(i != m_component_selection.end()) - { - visitor.visit(*(*(i++))); - } - } - - void addSelectionChangeCallback(const SelectionChangeHandler& handler) - { - m_selectionChanged_callbacks.connectLast(handler); - } - void selectionChanged(const Selectable& selectable) - { - m_selectionChanged_callbacks(selectable); - } - typedef MemberCaller1 SelectionChangedCaller; - - - void startMove() - { - m_pivot2world_start = GetPivot2World(); - } - - bool SelectManipulator(const View& view, const float device_point[2], const float device_epsilon[2]) - { - if(!nothingSelected() || (ManipulatorMode() == eDrag && Mode() == eComponent)) - { -#if defined (DEBUG_SELECTION) - g_render_clipped.destroy(); -#endif - - m_manipulator->setSelected(false); - - if(!nothingSelected() || (ManipulatorMode() == eDrag && Mode() == eComponent)) - { - View scissored(view); - ConstructSelectionTest(scissored, SelectionBoxForPoint(device_point, device_epsilon)); - m_manipulator->testSelect(scissored, GetPivot2World()); - } - - startMove(); - - m_pivot_moving = m_manipulator->isSelected(); - - if(m_pivot_moving) - { - Pivot2World pivot; - pivot.update(GetPivot2World(), view.GetModelview(), view.GetProjection(), view.GetViewport()); - - m_manip2pivot_start = matrix4_multiplied_by_matrix4(matrix4_full_inverse(m_pivot2world_start), pivot.m_worldSpace); - - Matrix4 device2manip; - ConstructDevice2Manip(device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport()); - m_manipulator->GetManipulatable()->Construct(device2manip, device_point[0], device_point[1]); - - m_undo_begun = false; - } - - SceneChangeNotify(); - } - - return m_pivot_moving; - } - - void deselectAll() - { - if(Mode() == eComponent) - { - setSelectedAllComponents(false); - } - else - { - setSelectedAll(false); - } - } - - void SelectPoint(const View& view, const float device_point[2], const float device_epsilon[2], RadiantSelectionSystem::EModifier modifier, bool face) - { - ASSERT_MESSAGE(fabs(device_point[0]) <= 1.0f && fabs(device_point[1]) <= 1.0f, "point-selection error"); - if(modifier == eReplace) - { - if(face) - { - setSelectedAllComponents(false); - } - else - { - deselectAll(); - } - } - - #if defined (DEBUG_SELECTION) - g_render_clipped.destroy(); - #endif - - { - View scissored(view); - ConstructSelectionTest(scissored, SelectionBoxForPoint(device_point, device_epsilon)); - - SelectionVolume volume(scissored); - SelectionPool selector; - if(face) - { - Scene_TestSelect_Component(selector, volume, scissored, eFace); - } - else - { - Scene_TestSelect(selector, volume, scissored, Mode(), ComponentMode()); - } - - if(!selector.failed()) - { - switch(modifier) - { - case RadiantSelectionSystem::eToggle: - { - SelectableSortedSet::iterator best = selector.begin(); - // toggle selection of the object with least depth - if((*best).second->isSelected()) - (*best).second->setSelected(false); - else - (*best).second->setSelected(true); - } - break; - // if cycle mode not enabled, enable it - case RadiantSelectionSystem::eReplace: - { - // select closest - (*selector.begin()).second->setSelected(true); - } - break; - // select the next object in the list from the one already selected - case RadiantSelectionSystem::eCycle: - { - SelectionPool::iterator i = selector.begin(); - while(i != selector.end()) - { - if((*i).second->isSelected()) - { - (*i).second->setSelected(false); - ++i; - if(i != selector.end()) - { - i->second->setSelected(true); - } - else - { - selector.begin()->second->setSelected(true); - } - break; - } - ++i; - } - } - break; - default: - break; - } - } - } - } - - void SelectArea(const View& view, const float device_point[2], const float device_delta[2], RadiantSelectionSystem::EModifier modifier, bool face) - { - if(modifier == eReplace) - { - if(face) - { - setSelectedAllComponents(false); - } - else - { - deselectAll(); - } - } - - #if defined (DEBUG_SELECTION) - g_render_clipped.destroy(); - #endif - - { - View scissored(view); - ConstructSelectionTest(scissored, SelectionBoxForArea(device_point, device_delta)); - - SelectionVolume volume(scissored); - SelectionPool pool; - if(face) - { - Scene_TestSelect_Component(pool, volume, scissored, eFace); - } - else - { - Scene_TestSelect(pool, volume, scissored, Mode(), ComponentMode()); - } - - for(SelectionPool::iterator i = pool.begin(); i != pool.end(); ++i) - { - (*i).second->setSelected(!(modifier == RadiantSelectionSystem::eToggle && (*i).second->isSelected())); - } - } - } - - - void translate(const Vector3& translation) - { - if(!nothingSelected()) - { - //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); - - m_translation = translation; - - m_pivot2world = m_pivot2world_start; - matrix4_translate_by_vec3(m_pivot2world, translation); - - if(Mode() == eComponent) - { - Scene_Translate_Component_Selected(GlobalSceneGraph(), m_translation); - } - else - { - Scene_Translate_Selected(GlobalSceneGraph(), m_translation); - } - - SceneChangeNotify(); - } - } - void outputTranslation(TextOutputStream& ostream) - { - ostream << " -xyz " << m_translation.x() << " " << m_translation.y() << " " << m_translation.z(); - } - void rotate(const Quaternion& rotation) - { - if(!nothingSelected()) - { - //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); - - m_rotation = rotation; - - if(Mode() == eComponent) - { - Scene_Rotate_Component_Selected(GlobalSceneGraph(), m_rotation, vector4_to_vector3(m_pivot2world.t())); - - matrix4_assign_rotation_for_pivot(m_pivot2world, m_component_selection.back()); - } - else - { - Scene_Rotate_Selected(GlobalSceneGraph(), m_rotation, vector4_to_vector3(m_pivot2world.t())); - - matrix4_assign_rotation_for_pivot(m_pivot2world, m_selection.back()); - } - - SceneChangeNotify(); - } - } - void outputRotation(TextOutputStream& ostream) - { - ostream << " -eulerXYZ " << m_rotation.x() << " " << m_rotation.y() << " " << m_rotation.z(); - } - void scale(const Vector3& scaling) - { - if(!nothingSelected()) - { - m_scale = scaling; - - if(Mode() == eComponent) - { - Scene_Scale_Component_Selected(GlobalSceneGraph(), m_scale, vector4_to_vector3(m_pivot2world.t())); - } - else - { - Scene_Scale_Selected(GlobalSceneGraph(), m_scale, vector4_to_vector3(m_pivot2world.t())); - } - - SceneChangeNotify(); - } - } - void outputScale(TextOutputStream& ostream) - { - ostream << " -scale " << m_scale.x() << " " << m_scale.y() << " " << m_scale.z(); - } - - void rotateSelected(const Quaternion& rotation) - { - startMove(); - rotate(rotation); - freezeTransforms(); - } - void translateSelected(const Vector3& translation) - { - startMove(); - translate(translation); - freezeTransforms(); - } - void scaleSelected(const Vector3& scaling) - { - startMove(); - scale(scaling); - freezeTransforms(); - } - - void MoveSelected(const View& view, const float device_point[2]) - { - if(m_manipulator->isSelected()) - { - if(!m_undo_begun) - { - m_undo_begun = true; - GlobalUndoSystem().start(); - } - - Matrix4 device2manip; - ConstructDevice2Manip(device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport()); - m_manipulator->GetManipulatable()->Transform(m_manip2pivot_start, device2manip, device_point[0], device_point[1]); - } - } - - /// \todo Support view-dependent nudge. - void NudgeManipulator(const Vector3& nudge, const Vector3& view) - { - if(ManipulatorMode() == eTranslate || ManipulatorMode() == eDrag) - { - translateSelected(nudge); - } - } - - void endMove(); - void freezeTransforms(); - - void renderSolid(Renderer& renderer, const VolumeTest& volume) const; - void renderWireframe(Renderer& renderer, const VolumeTest& volume) const - { - renderSolid(renderer, volume); - } - - const Matrix4& GetPivot2World() const - { - ConstructPivot(); - return m_pivot2world; - } - - static void constructStatic() - { - m_state = GlobalShaderCache().capture("$POINT"); - #if defined(DEBUG_SELECTION) - g_state_clipped = GlobalShaderCache().capture("$DEBUG_CLIPPED"); - #endif - TranslateManipulator::m_state_wire = GlobalShaderCache().capture("$WIRE_OVERLAY"); - TranslateManipulator::m_state_fill = GlobalShaderCache().capture("$FLATSHADE_OVERLAY"); - RotateManipulator::m_state_outer = GlobalShaderCache().capture("$WIRE_OVERLAY"); - } - - static void destroyStatic() - { - #if defined(DEBUG_SELECTION) - GlobalShaderCache().release("$DEBUG_CLIPPED"); - #endif - GlobalShaderCache().release("$WIRE_OVERLAY"); - GlobalShaderCache().release("$FLATSHADE_OVERLAY"); - GlobalShaderCache().release("$WIRE_OVERLAY"); - GlobalShaderCache().release("$POINT"); - } -}; - -Shader* RadiantSelectionSystem::m_state = 0; - - -namespace -{ - RadiantSelectionSystem* g_RadiantSelectionSystem; - - inline RadiantSelectionSystem& getSelectionSystem() - { - return *g_RadiantSelectionSystem; - } -} - - - -class testselect_entity_visible : public scene::Graph::Walker -{ - Selector& m_selector; - SelectionTest& m_test; -public: - testselect_entity_visible(Selector& selector, SelectionTest& test) - : m_selector(selector), m_test(test) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && Node_isEntity(path.top())) - { - m_selector.pushSelectable(*selectable); - } - - SelectionTestable* selectionTestable = Instance_getSelectionTestable(instance); - if(selectionTestable) - { - selectionTestable->testSelect(m_selector, m_test); - } - - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && Node_isEntity(path.top())) - { - m_selector.popSelectable(); - } - } -}; - -class testselect_primitive_visible : public scene::Graph::Walker -{ - Selector& m_selector; - SelectionTest& m_test; -public: - testselect_primitive_visible(Selector& selector, SelectionTest& test) - : m_selector(selector), m_test(test) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0) - { - m_selector.pushSelectable(*selectable); - } - - SelectionTestable* selectionTestable = Instance_getSelectionTestable(instance); - if(selectionTestable) - { - selectionTestable->testSelect(m_selector, m_test); - } - - return true; - } - void post(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0) - { - m_selector.popSelectable(); - } - } -}; - -class testselect_component_visible : public scene::Graph::Walker -{ - Selector& m_selector; - SelectionTest& m_test; - SelectionSystem::EComponentMode m_mode; -public: - testselect_component_visible(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) - : m_selector(selector), m_test(test), m_mode(mode) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); - if(componentSelectionTestable) - { - componentSelectionTestable->testSelectComponents(m_selector, m_test, m_mode); - } - - return true; - } -}; - - -class testselect_component_visible_selected : public scene::Graph::Walker -{ - Selector& m_selector; - SelectionTest& m_test; - SelectionSystem::EComponentMode m_mode; -public: - testselect_component_visible_selected(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) - : m_selector(selector), m_test(test), m_mode(mode) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 && selectable->isSelected()) - { - ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); - if(componentSelectionTestable) - { - componentSelectionTestable->testSelectComponents(m_selector, m_test, m_mode); - } - } - - return true; - } -}; - -void Scene_TestSelect_Primitive(Selector& selector, SelectionTest& test, const VolumeTest& volume) -{ - Scene_forEachVisible(GlobalSceneGraph(), volume, testselect_primitive_visible(selector, test)); -} - -void Scene_TestSelect_Component_Selected(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode) -{ - Scene_forEachVisible(GlobalSceneGraph(), volume, testselect_component_visible_selected(selector, test, componentMode)); -} - -void Scene_TestSelect_Component(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode) -{ - Scene_forEachVisible(GlobalSceneGraph(), volume, testselect_component_visible(selector, test, componentMode)); -} - -void RadiantSelectionSystem::Scene_TestSelect(Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode) -{ - switch(mode) - { - case eEntity: - { - Scene_forEachVisible(GlobalSceneGraph(), view, testselect_entity_visible(selector, test)); - } - break; - case ePrimitive: - Scene_TestSelect_Primitive(selector, test, view); - break; - case eComponent: - Scene_TestSelect_Component_Selected(selector, test, view, componentMode); - break; - } -} - -class FreezeTransforms : public scene::Graph::Walker -{ -public: - bool pre(const scene::Path& path, scene::Instance& instance) const - { - TransformNode* transformNode = Node_getTransformNode(path.top()); - if(transformNode != 0) - { - Transformable* transform = Instance_getTransformable(instance); - if(transform != 0) - { - transform->freezeTransform(); - } - } - return true; - } -}; - -void RadiantSelectionSystem::freezeTransforms() -{ - GlobalSceneGraph().traverse(FreezeTransforms()); -} - - -void RadiantSelectionSystem::endMove() -{ - freezeTransforms(); - - if(Mode() == ePrimitive) - { - if(ManipulatorMode() == eDrag) - { - Scene_SelectAll_Component(false, SelectionSystem::eFace); - } - } - - m_pivot_moving = false; - pivotChanged(); - - SceneChangeNotify(); - - if(m_undo_begun) - { - StringOutputStream command; - - if(ManipulatorMode() == eTranslate) - { - command << "translateTool"; - outputTranslation(command); - } - else if(ManipulatorMode() == eRotate) - { - command << "rotateTool"; - outputRotation(command); - } - else if(ManipulatorMode() == eScale) - { - command << "scaleTool"; - outputScale(command); - } - else if(ManipulatorMode() == eDrag) - { - command << "dragTool"; - } - - GlobalUndoSystem().finish(command.c_str()); - } - -} - -inline AABB Instance_getPivotBounds(scene::Instance& instance) -{ - Entity* entity = Node_getEntity(instance.path().top()); - if(entity != 0 - && (entity->getEntityClass().fixedsize - || !node_is_group(instance.path().top()))) - { - Editable* editable = Node_getEditable(instance.path().top()); - if(editable != 0) - { - return AABB(vector4_to_vector3(matrix4_multiplied_by_matrix4(instance.localToWorld(), editable->getLocalPivot()).t()), Vector3(0, 0, 0)); - } - else - { - return AABB(vector4_to_vector3(instance.localToWorld().t()), Vector3(0, 0, 0)); - } - } - - return instance.worldAABB(); -} - -class bounds_selected : public scene::Graph::Walker -{ - AABB& m_bounds; -public: - bounds_selected(AABB& bounds) - : m_bounds(bounds) - { - m_bounds = AABB(); - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected()) - { - aabb_extend_by_aabb_safe(m_bounds, Instance_getPivotBounds(instance)); - } - return true; - } -}; - -class bounds_selected_component : public scene::Graph::Walker -{ - AABB& m_bounds; -public: - bounds_selected_component(AABB& bounds) - : m_bounds(bounds) - { - m_bounds = AABB(); - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - Selectable* selectable = Instance_getSelectable(instance); - if(selectable != 0 - && selectable->isSelected()) - { - ComponentEditable* componentEditable = Instance_getComponentEditable(instance); - if(componentEditable) - { - aabb_extend_by_aabb_safe(m_bounds, aabb_for_oriented_aabb_safe(componentEditable->getSelectedComponentsBounds(), instance.localToWorld())); - } - } - return true; - } -}; - -void Scene_BoundsSelected(scene::Graph& graph, AABB& bounds) -{ - graph.traverse(bounds_selected(bounds)); -} - -void Scene_BoundsSelectedComponent(scene::Graph& graph, AABB& bounds) -{ - graph.traverse(bounds_selected_component(bounds)); -} - -#if 0 -inline void pivot_for_node(Matrix4& pivot, scene::Node& node, scene::Instance& instance) -{ - ComponentEditable* componentEditable = Instance_getComponentEditable(instance); - if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent - && componentEditable != 0) - { - pivot = matrix4_translation_for_vec3(componentEditable->getSelectedComponentsBounds().origin); - } - else - { - Bounded* bounded = Instance_getBounded(instance); - if(bounded != 0) - { - pivot = matrix4_translation_for_vec3(bounded->localAABB().origin); - } - else - { - pivot = g_matrix4_identity; - } - } -} -#endif - -void RadiantSelectionSystem::ConstructPivot() const -{ - if(!m_pivotChanged || m_pivot_moving) - return; - m_pivotChanged = false; - - Vector3 m_object_pivot; - - if(!nothingSelected()) - { - { - AABB bounds; - if(Mode() == eComponent) - { - Scene_BoundsSelectedComponent(GlobalSceneGraph(), bounds); - } - else - { - Scene_BoundsSelected(GlobalSceneGraph(), bounds); - } - m_object_pivot = bounds.origin; - } - - vector3_snap(m_object_pivot, GetSnapGridSize()); - m_pivot2world = matrix4_translation_for_vec3(m_object_pivot); - - switch(m_manipulator_mode) - { - case eTranslate: - break; - case eRotate: - if(Mode() == eComponent) - { - matrix4_assign_rotation_for_pivot(m_pivot2world, m_component_selection.back()); - } - else - { - matrix4_assign_rotation_for_pivot(m_pivot2world, m_selection.back()); - } - break; - case eScale: - if(Mode() == eComponent) - { - matrix4_assign_rotation_for_pivot(m_pivot2world, m_component_selection.back()); - } - else - { - matrix4_assign_rotation_for_pivot(m_pivot2world, m_selection.back()); - } - break; - default: - break; - } - } -} - -void RadiantSelectionSystem::renderSolid(Renderer& renderer, const VolumeTest& volume) const -{ - //if(view->TestPoint(m_object_pivot)) - if(!nothingSelected()) - { - renderer.Highlight(Renderer::ePrimitive, false); - renderer.Highlight(Renderer::eFace, false); - - renderer.SetState(m_state, Renderer::eWireframeOnly); - renderer.SetState(m_state, Renderer::eFullMaterials); - - m_manipulator->render(renderer, volume, GetPivot2World()); - } - -#if defined(DEBUG_SELECTION) - renderer.SetState(g_state_clipped, Renderer::eWireframeOnly); - renderer.SetState(g_state_clipped, Renderer::eFullMaterials); - renderer.addRenderable(g_render_clipped, g_render_clipped.m_world); -#endif -} - - -void SelectionSystem_OnBoundsChanged() -{ - getSelectionSystem().pivotChanged(); -} - - -SignalHandlerId SelectionSystem_boundsChanged; - -void SelectionSystem_Construct() -{ - RadiantSelectionSystem::constructStatic(); - - g_RadiantSelectionSystem = new RadiantSelectionSystem; - - SelectionSystem_boundsChanged = GlobalSceneGraph().addBoundsChangedCallback(FreeCaller()); - - GlobalShaderCache().attachRenderable(getSelectionSystem()); -} - -void SelectionSystem_Destroy() -{ - GlobalShaderCache().detachRenderable(getSelectionSystem()); - - GlobalSceneGraph().removeBoundsChangedCallback(SelectionSystem_boundsChanged); - - delete g_RadiantSelectionSystem; - - RadiantSelectionSystem::destroyStatic(); -} - - - - -inline float screen_normalised(float pos, std::size_t size) -{ - return ((2.0f * pos) / size) - 1.0f; -} - -typedef Vector2 DeviceVector; - -inline DeviceVector window_to_normalised_device(WindowVector window, std::size_t width, std::size_t height) -{ - return DeviceVector(screen_normalised(window.x(), width), screen_normalised(height - 1 - window.y(), height)); -} - -inline float device_constrained(float pos) -{ - return std::min(1.0f, std::max(-1.0f, pos)); -} - -inline DeviceVector device_constrained(DeviceVector device) -{ - return DeviceVector(device_constrained(device.x()), device_constrained(device.y())); -} - -inline float window_constrained(float pos, std::size_t origin, std::size_t size) -{ - return std::min(static_cast(origin + size), std::max(static_cast(origin), pos)); -} - -inline WindowVector window_constrained(WindowVector window, std::size_t x, std::size_t y, std::size_t width, std::size_t height) -{ - return WindowVector(window_constrained(window.x(), x, width), window_constrained(window.y(), y, height)); -} - -typedef Callback1 MouseEventCallback; - -Single g_mouseMovedCallback; -Single g_mouseUpCallback; - -#if 1 -const ButtonIdentifier c_button_select = c_buttonLeft; -const ModifierFlags c_modifier_manipulator = c_modifierNone; -const ModifierFlags c_modifier_toggle = c_modifierShift; -const ModifierFlags c_modifier_replace = c_modifierShift | c_modifierAlt; -const ModifierFlags c_modifier_face = c_modifierControl; -#else -const ButtonIdentifier c_button_select = c_buttonLeft; -const ModifierFlags c_modifier_manipulator = c_modifierNone; -const ModifierFlags c_modifier_toggle = c_modifierControl; -const ModifierFlags c_modifier_replace = c_modifierNone; -const ModifierFlags c_modifier_face = c_modifierShift; -#endif -const ModifierFlags c_modifier_toggle_face = c_modifier_toggle | c_modifier_face; -const ModifierFlags c_modifier_replace_face = c_modifier_replace | c_modifier_face; - -const ButtonIdentifier c_button_texture = c_buttonMiddle; -const ModifierFlags c_modifier_apply_texture = c_modifierControl | c_modifierShift; -const ModifierFlags c_modifier_copy_texture = c_modifierNone; - -class Selector_ -{ - RadiantSelectionSystem::EModifier modifier_for_state(ModifierFlags state) - { - if(state == c_modifier_toggle || state == c_modifier_toggle_face) - { - return RadiantSelectionSystem::eToggle; - } - if(state == c_modifier_replace || state == c_modifier_replace_face) - { - return RadiantSelectionSystem::eReplace; - } - return RadiantSelectionSystem::eManipulator; - } - - rect_t getDeviceArea() const - { - DeviceVector delta(m_current - m_start); - if(selecting() && fabs(delta.x()) > m_epsilon.x() && fabs(delta.y()) > m_epsilon.y()) - { - return SelectionBoxForArea(&m_start[0], &delta[0]); - } - else - { - rect_t default_area = { { 0, 0, }, { 0, 0, }, }; - return default_area; - } - } - -public: - DeviceVector m_start; - DeviceVector m_current; - DeviceVector m_epsilon; - std::size_t m_unmoved_replaces; - ModifierFlags m_state; - const View* m_view; - RectangleCallback m_window_update; - - Selector_() : m_start(0.0f, 0.0f), m_current(0.0f, 0.0f), m_unmoved_replaces(0), m_state(c_modifierNone) - { - } - - void draw_area() - { - m_window_update(getDeviceArea()); - } - - void testSelect(DeviceVector position) - { - RadiantSelectionSystem::EModifier modifier = modifier_for_state(m_state); - if(modifier != RadiantSelectionSystem::eManipulator) - { - DeviceVector delta(position - m_start); - if(fabs(delta.x()) > m_epsilon.x() && fabs(delta.y()) > m_epsilon.y()) - { - DeviceVector delta(position - m_start); - getSelectionSystem().SelectArea(*m_view, &m_start[0], &delta[0], modifier, (m_state & c_modifier_face) != c_modifierNone); - } - else - { - if(modifier == RadiantSelectionSystem::eReplace && m_unmoved_replaces++ > 0) - { - modifier = RadiantSelectionSystem::eCycle; - } - getSelectionSystem().SelectPoint(*m_view, &position[0], &m_epsilon[0], modifier, (m_state & c_modifier_face) != c_modifierNone); - } - } - - m_start = m_current = DeviceVector(0.0f, 0.0f); - draw_area(); - } - - bool selecting() const - { - return m_state != c_modifier_manipulator; - } - - void setState(ModifierFlags state) - { - bool was_selecting = selecting(); - m_state = state; - if(was_selecting ^ selecting()) - { - draw_area(); - } - } - - ModifierFlags getState() const - { - return m_state; - } - - void modifierEnable(ModifierFlags type) - { - setState(bitfield_enable(getState(), type)); - } - void modifierDisable(ModifierFlags type) - { - setState(bitfield_disable(getState(), type)); - } - - void mouseDown(DeviceVector position) - { - m_start = m_current = device_constrained(position); - } - - void mouseMoved(DeviceVector position) - { - m_current = device_constrained(position); - draw_area(); - } - typedef MemberCaller1 MouseMovedCaller; - - void mouseUp(DeviceVector position) - { - testSelect(device_constrained(position)); - - g_mouseMovedCallback.clear(); - g_mouseUpCallback.clear(); - } - typedef MemberCaller1 MouseUpCaller; -}; - - -class Manipulator_ -{ -public: - DeviceVector m_epsilon; - const View* m_view; - - bool mouseDown(DeviceVector position) - { - return getSelectionSystem().SelectManipulator(*m_view, &position[0], &m_epsilon[0]); - } - - void mouseMoved(DeviceVector position) - { - getSelectionSystem().MoveSelected(*m_view, &position[0]); - } - typedef MemberCaller1 MouseMovedCaller; - - void mouseUp(DeviceVector position) - { - getSelectionSystem().endMove(); - g_mouseMovedCallback.clear(); - g_mouseUpCallback.clear(); - } - typedef MemberCaller1 MouseUpCaller; -}; - -void Scene_copyClosestTexture(SelectionTest& test); -void Scene_applyClosestTexture(SelectionTest& test); - -class RadiantWindowObserver : public SelectionSystemWindowObserver -{ - enum - { - SELECT_EPSILON = 8, - }; - - int m_width; - int m_height; - - bool m_mouse_down; - -public: - Selector_ m_selector; - Manipulator_ m_manipulator; - - RadiantWindowObserver() : m_mouse_down(false) - { - } - void release() - { - delete this; - } - void setView(const View& view) - { - m_selector.m_view = &view; - m_manipulator.m_view = &view; - } - void setRectangleDrawCallback(const RectangleCallback& callback) - { - m_selector.m_window_update = callback; - } - void onSizeChanged(int width, int height) - { - m_width = width; - m_height = height; - DeviceVector epsilon(SELECT_EPSILON / static_cast(m_width), SELECT_EPSILON / static_cast(m_height)); - m_selector.m_epsilon = m_manipulator.m_epsilon = epsilon; - } - void onMouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) - { - if(button == c_button_select) - { - m_mouse_down = true; - - DeviceVector devicePosition(window_to_normalised_device(position, m_width, m_height)); - if(modifiers == c_modifier_manipulator && m_manipulator.mouseDown(devicePosition)) - { - g_mouseMovedCallback.insert(MouseEventCallback(Manipulator_::MouseMovedCaller(m_manipulator))); - g_mouseUpCallback.insert(MouseEventCallback(Manipulator_::MouseUpCaller(m_manipulator))); - } - else - { - m_selector.mouseDown(devicePosition); - g_mouseMovedCallback.insert(MouseEventCallback(Selector_::MouseMovedCaller(m_selector))); - g_mouseUpCallback.insert(MouseEventCallback(Selector_::MouseUpCaller(m_selector))); - } - } - else if(button == c_button_texture) - { - DeviceVector devicePosition(device_constrained(window_to_normalised_device(position, m_width, m_height))); - - View scissored(*m_selector.m_view); - ConstructSelectionTest(scissored, SelectionBoxForPoint(&devicePosition[0], &m_selector.m_epsilon[0])); - SelectionVolume volume(scissored); - - if(modifiers == c_modifier_apply_texture) - { - Scene_applyClosestTexture(volume); - } - else if(modifiers == c_modifier_copy_texture) - { - Scene_copyClosestTexture(volume); - } - } - } - void onMouseMotion(const WindowVector& position, ModifierFlags modifiers) - { - m_selector.m_unmoved_replaces = 0; - - if(m_mouse_down && !g_mouseMovedCallback.empty()) - { - g_mouseMovedCallback.get()(window_to_normalised_device(position, m_width, m_height)); - } - } - void onMouseUp(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) - { - if(button == c_button_select && !g_mouseUpCallback.empty()) - { - m_mouse_down = false; - - g_mouseUpCallback.get()(window_to_normalised_device(position, m_width, m_height)); - } - } - void onModifierDown(ModifierFlags type) - { - m_selector.modifierEnable(type); - } - void onModifierUp(ModifierFlags type) - { - m_selector.modifierDisable(type); - } -}; - - - -SelectionSystemWindowObserver* NewWindowObserver() -{ - return new RadiantWindowObserver; -} - - - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class SelectionDependencies : - public GlobalSceneGraphModuleRef, - public GlobalShaderCacheModuleRef, - public GlobalOpenGLModuleRef -{ -}; - -class SelectionAPI : public TypeSystemRef -{ - SelectionSystem* m_selection; -public: - typedef SelectionSystem Type; - STRING_CONSTANT(Name, "*"); - - SelectionAPI() - { - SelectionSystem_Construct(); - - m_selection = &getSelectionSystem(); - } - ~SelectionAPI() - { - SelectionSystem_Destroy(); - } - SelectionSystem* getTable() - { - return m_selection; - } -}; - -typedef SingletonModule SelectionModule; -typedef Static StaticSelectionModule; -StaticRegisterModule staticRegisterSelection(StaticSelectionModule::instance()); diff --git a/misc/mediasource/extra/netradiant-src/radiant/selection.h b/misc/mediasource/extra/netradiant-src/radiant/selection.h deleted file mode 100644 index 8334ec63..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/selection.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_SELECTION_H) -#define INCLUDED_SELECTION_H - -#include "windowobserver.h" -#include "generic/callbackfwd.h" - -struct rect_t -{ - float min[2]; - float max[2]; -}; - -typedef Callback1 RectangleCallback; - -class View; - -class SelectionSystemWindowObserver : public WindowObserver -{ -public: - virtual void setView(const View& view) = 0; - virtual void setRectangleDrawCallback(const RectangleCallback& callback) = 0; -}; - -SelectionSystemWindowObserver* NewWindowObserver(); - -class AABB; -namespace scene -{ - class Graph; -} -void Scene_BoundsSelected(scene::Graph& graph, AABB& bounds); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/server.cpp b/misc/mediasource/extra/netradiant-src/radiant/server.cpp deleted file mode 100644 index e6b4dbb1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/server.cpp +++ /dev/null @@ -1,291 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "server.h" - -#include "debugging/debugging.h" -#include "warnings.h" - -#include -#include -#include "os/path.h" - -#include "modulesystem.h" - -class RadiantModuleServer : public ModuleServer -{ - typedef std::pair ModuleType; - typedef std::pair ModuleKey; - typedef std::map Modules_; - Modules_ m_modules; - bool m_error; - -public: - RadiantModuleServer() : m_error(false) - { - } - - void setError(bool error) - { - m_error = error; - } - bool getError() const - { - return m_error; - } - - TextOutputStream& getOutputStream() - { - return globalOutputStream(); - } - TextOutputStream& getErrorStream() - { - return globalErrorStream(); - } - DebugMessageHandler& getDebugMessageHandler() - { - return globalDebugMessageHandler(); - } - - void registerModule(const char* type, int version, const char* name, Module& module) - { - ASSERT_NOTNULL(&module); - if(!m_modules.insert(Modules_::value_type(ModuleKey(ModuleType(type, version), name), &module)).second) - { - globalErrorStream() << "module already registered: type=" << makeQuoted(type) << " name=" << makeQuoted(name) << "\n"; - } - else - { - globalOutputStream() << "Module Registered: type=" << makeQuoted(type) << " version=" << makeQuoted(version) << " name=" << makeQuoted(name) << "\n"; - } - } - - Module* findModule(const char* type, int version, const char* name) const - { - Modules_::const_iterator i = m_modules.find(ModuleKey(ModuleType(type, version), name)); - if(i != m_modules.end()) - { - return (*i).second; - } - return 0; - } - - void foreachModule(const char* type, int version, const Visitor& visitor) - { - for(Modules_::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i) - { - if(string_equal((*i).first.first.first.c_str(), type)) - { - visitor.visit((*i).first.second.c_str(), *(*i).second); - } - } - } -}; - - -#if defined(WIN32) - -#include - -#define FORMAT_BUFSIZE 2048 -const char* FormatGetLastError() -{ - static char buf[FORMAT_BUFSIZE]; - FormatMessage( - FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, - GetLastError(), - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language - buf, - FORMAT_BUFSIZE, - NULL - ); - return buf; -} - -class DynamicLibrary -{ - HMODULE m_library; -public: - typedef int (__stdcall* FunctionPointer)(); - - DynamicLibrary(const char* filename) - { - m_library = LoadLibrary(filename); - if(m_library == 0) - { - globalErrorStream() << "LoadLibrary failed: '" << filename << "'\n"; - globalErrorStream() << "GetLastError: " << FormatGetLastError(); - } - } - ~DynamicLibrary() - { - if(!failed()) - { - FreeLibrary(m_library); - } - } - bool failed() - { - return m_library == 0; - } - FunctionPointer findSymbol(const char* symbol) - { - FunctionPointer address = GetProcAddress(m_library, symbol); - if(address == 0) - { - globalErrorStream() << "GetProcAddress failed: '" << symbol << "'\n"; - globalErrorStream() << "GetLastError: " << FormatGetLastError(); - } - return address; - } -}; - -#elif defined(POSIX) - -#include - -class DynamicLibrary -{ - void* m_library; -public: - typedef int (* FunctionPointer)(); - - DynamicLibrary(const char* filename) - { - m_library = dlopen(filename, RTLD_NOW); - } - ~DynamicLibrary() - { - if(!failed()) - dlclose(m_library); - } - bool failed() - { - return m_library == 0; - } - FunctionPointer findSymbol(const char* symbol) - { - FunctionPointer p = (FunctionPointer)dlsym(m_library, symbol); - if(p == 0) - { - const char* error = reinterpret_cast(dlerror()); - if(error != 0) - { - globalErrorStream() << error; - } - } - return p; - } -}; - -#else -#error "unsupported platform" -#endif - -class DynamicLibraryModule -{ - typedef void (RADIANT_DLLIMPORT* RegisterModulesFunc)(ModuleServer& server); - DynamicLibrary m_library; - RegisterModulesFunc m_registerModule; -public: - DynamicLibraryModule(const char* filename) - : m_library(filename), m_registerModule(0) - { - if(!m_library.failed()) - { - m_registerModule = reinterpret_cast(m_library.findSymbol("Radiant_RegisterModules")); -#if 0 - if(!m_registerModule) - m_registerModule = reinterpret_cast(m_library.findSymbol("Radiant_RegisterModules@4")); -#endif - } - } - bool failed() - { - return m_registerModule == 0; - } - void registerModules(ModuleServer& server) - { - m_registerModule(server); - } -}; - - -class Libraries -{ - typedef std::vector libraries_t; - libraries_t m_libraries; - -public: - ~Libraries() - { - release(); - } - void registerLibrary(const char* filename, ModuleServer& server) - { - DynamicLibraryModule* library = new DynamicLibraryModule(filename); - - if(library->failed()) - { - delete library; - } - else - { - m_libraries.push_back(library); - library->registerModules(server); - } - } - void release() - { - for(libraries_t::iterator i = m_libraries.begin(); i != m_libraries.end(); ++i) - { - delete *i; - } - } - void clear() - { - m_libraries.clear(); - } -}; - - -Libraries g_libraries; -RadiantModuleServer g_server; - -ModuleServer& GlobalModuleServer_get() -{ - return g_server; -} - -void GlobalModuleServer_loadModule(const char* filename) -{ - g_libraries.registerLibrary(filename, g_server); -} - -void GlobalModuleServer_Initialise() -{ -} - -void GlobalModuleServer_Shutdown() -{ -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/server.h b/misc/mediasource/extra/netradiant-src/radiant/server.h deleted file mode 100644 index ded73098..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/server.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_SERVER_H) -#define INCLUDED_SERVER_H - -class ModuleServer; -ModuleServer& GlobalModuleServer_get(); -void GlobalModuleServer_loadModule(const char* filename); -void GlobalModuleServer_Initialise(); -void GlobalModuleServer_Shutdown(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/shaders.cpp b/misc/mediasource/extra/netradiant-src/radiant/shaders.cpp deleted file mode 100644 index 696ef5ba..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/shaders.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "shaders.h" - -#include "ifilesystem.h" - -#include "stream/stringstream.h" - -#include "gtkdlgs.h" - -void ViewShader(const char *pFile, const char *pName) -{ - char* pBuff = 0; - //int nSize = - vfsLoadFile(pFile, reinterpret_cast(&pBuff)); - if (pBuff == 0) - { - globalErrorStream() << "Failed to load shader file " << pFile << "\n"; - return; - } - // look for the shader declaration - StringOutputStream strFind(string_length(pName)); - strFind << LowerCase(pName); - StringOutputStream strLook(string_length(pBuff)); - strFind << LowerCase(pBuff); - // offset used when jumping over commented out definitions - std::size_t nOffset = 0; - while (true) - { - const char* substr = strstr(strFind.c_str() + nOffset, strFind.c_str()); - if (substr == 0) - break; - std::size_t nStart = substr - strLook.c_str(); - // we have found something, maybe it's a commented out shader name? - char *strCheck = new char[string_length(strLook.c_str())+1]; - strcpy( strCheck, strLook.c_str() ); - strCheck[nStart] = 0; - char *pCheck = strrchr( strCheck, '\n' ); - // if there's a commentary sign in-between we'll continue - if (pCheck && strstr( pCheck, "//" )) - { - delete[] strCheck; - nOffset = nStart + 1; - continue; - } - delete[] strCheck; - nOffset = nStart; - break; - } - // now close the file - vfsFreeFile(pBuff); - - DoTextEditor (pFile, static_cast(nOffset)); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/shaders.h b/misc/mediasource/extra/netradiant-src/radiant/shaders.h deleted file mode 100644 index 58b398cf..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/shaders.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_SHADERS_H) -#define INCLUDED_SHADERS_H - -void ViewShader(const char* file, const char* shader); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/sockets.cpp b/misc/mediasource/extra/netradiant-src/radiant/sockets.cpp deleted file mode 100644 index e08680be..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/sockets.cpp +++ /dev/null @@ -1,47 +0,0 @@ - -#include "sockets.h" - -#if defined(WIN32) -#include -#elif defined (POSIX) -#include -#define SOCKET_ERROR -1 -#else -#error "unsupported platform" -#endif - -#ifdef __APPLE__ -#include -#endif - -int Net_Wait(socket_t *sock, long sec, long usec) -{ -// used for select() -#ifdef WIN32 - TIMEVAL tout = { sec, usec }; -#endif -#if defined (POSIX) - timeval tout; - tout.tv_sec = sec; - tout.tv_usec = usec; -#endif - - // select() will identify if the socket needs an update - // if the socket is identified that means there's either a message or the connection has been closed/reset/terminated - fd_set readfds; - FD_ZERO(&readfds); - FD_SET(((unsigned int)sock->socket), &readfds); - // from select man page: - // n is the highest-numbered descriptor in any of the three sets, plus 1 - // (no use on windows) - switch( select( sock->socket + 1, &readfds, 0, 0, &tout ) ) - { - case SOCKET_ERROR: - return -1; - case 0: - return 0; - default: - return 1; - } -} - diff --git a/misc/mediasource/extra/netradiant-src/radiant/sockets.h b/misc/mediasource/extra/netradiant-src/radiant/sockets.h deleted file mode 100644 index 3bc2274d..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/sockets.h +++ /dev/null @@ -1,14 +0,0 @@ - -#if !defined(INCLUDED_SOCKETS_H) -#define INCLUDED_SOCKETS_H - -#include "l_net/l_net.h" - -// waits for a socket to become ready -// returns -// -1: error -// 0: timeout -// 1: ready -int Net_Wait(socket_t *sock, long sec, long usec); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/stacktrace.cpp b/misc/mediasource/extra/netradiant-src/radiant/stacktrace.cpp deleted file mode 100644 index 18a70462..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/stacktrace.cpp +++ /dev/null @@ -1,319 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "stacktrace.h" -#include "stream/textstream.h" - -#include "environment.h" - -#ifdef __linux__ -#include - -void write_stack_trace(TextOutputStream& outputStream) -{ - const unsigned int MAX_SYMBOLS = 256; - void* symbols[MAX_SYMBOLS]; - - // get return addresses - int symbol_count = backtrace(symbols, MAX_SYMBOLS); - - if(!symbol_count) - return; - - // resolve and print names - char** symbol_names = backtrace_symbols(symbols, symbol_count); - if(symbol_names) - { - for(int i = 0; (i < symbol_count); ++i) - outputStream << symbol_names[i] << "\n"; - - // not a memleak, see www.gnu.org/software/libc/manual (Debugging Support, Backtraces) - free(symbol_names); - } -} -#elif defined (WIN32) && defined (_MSC_VER) - -#include "windows.h" -#include "winnt.h" -#include "dbghelp.h" - -class Address -{ -public: - void* m_value; - Address(void* value) : m_value(value) - { - } -}; - -/// \brief Writes an address \p p to \p ostream in hexadecimal form. -template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const Address& p) -{ - const std::size_t bufferSize = (sizeof(void*) * 2) + 1; - char buf[bufferSize]; - ostream.write(buf, snprintf(buf, bufferSize, "%0p", p.m_value)); - return ostream; -} - -class Offset -{ -public: - void* m_value; - Offset(void* value) : m_value(value) - { - } -}; - -/// \brief Writes an address \p p to \p ostream in hexadecimal form. -template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const Offset& p) -{ - const std::size_t bufferSize = (sizeof(void*) * 2) + 1; - char buf[bufferSize]; - ostream.write(buf, snprintf(buf, bufferSize, "%X", p.m_value)); - return ostream; -} - -/// \brief Writes a WCHAR string \p s to \p ostream. -template -inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const WCHAR* s) -{ - const std::size_t bufferSize = 1024; - char buf[bufferSize]; - ostream.write(buf, snprintf(buf, bufferSize, "%ls", s)); - return ostream; -} - -struct EnumerateSymbolsContext -{ - STACKFRAME64& sf; - TextOutputStream& outputStream; - std::size_t count; - EnumerateSymbolsContext(STACKFRAME64& sf, TextOutputStream& outputStream) : sf(sf), outputStream(outputStream), count(0) - { - } -}; - -void write_symbol(PSYMBOL_INFO pSym, STACKFRAME64& sf, TextOutputStream& outputStream, std::size_t& count) -{ -#if 0 - if ( pSym->Flags & SYMFLAG_PARAMETER ) - { - - DWORD basicType; - if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, - TI_GET_BASETYPE, &basicType ) ) - { - int bleh = 0; - } - else - { - DWORD typeId; - if(SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, - TI_GET_TYPEID, &typeId )) - { - if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, - TI_GET_BASETYPE, &basicType ) ) - { - int bleh = 0; - } - else - { - const char* FormatGetLastError(); - const char* error = FormatGetLastError(); - int bleh = 0; - - WCHAR* name; - if(SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, typeId, - TI_GET_SYMNAME, &name )) - { - outputStream << name << " "; - LocalFree(name); - int bleh = 0; - } - else - { - const char* FormatGetLastError(); - const char* error = FormatGetLastError(); - int bleh = 0; - } - } - } - else - { - const char* FormatGetLastError(); - const char* error = FormatGetLastError(); - int bleh = 0; - } - } - if(count != 0) - { - outputStream << ", "; - } - outputStream << pSym->Name; - ++count; - } -#endif -} - -BOOL CALLBACK -EnumerateSymbolsCallback( - PSYMBOL_INFO pSymInfo, - ULONG SymbolSize, - PVOID UserContext ) -{ - write_symbol( pSymInfo, ((EnumerateSymbolsContext*)UserContext)->sf, ((EnumerateSymbolsContext*)UserContext)->outputStream, ((EnumerateSymbolsContext*)UserContext)->count); - - - return TRUE; -} - -void write_stack_trace(PCONTEXT pContext, TextOutputStream& outputStream) -{ - HANDLE m_hProcess = GetCurrentProcess(); - DWORD dwMachineType = 0; - - CONTEXT context = *pContext; - - // Could use SymSetOptions here to add the SYMOPT_DEFERRED_LOADS flag - if ( !SymInitialize( m_hProcess, (PSTR)environment_get_app_path(), TRUE ) ) - { - return; - } - - STACKFRAME64 sf; - memset( &sf, 0, sizeof(sf) ); - sf.AddrPC.Mode = AddrModeFlat; - sf.AddrStack.Mode = AddrModeFlat; - sf.AddrFrame.Mode = AddrModeFlat; - -#ifdef _M_IX86 - // Initialize the STACKFRAME structure for the first call. This is only - // necessary for Intel CPUs, and isn't mentioned in the documentation. - sf.AddrPC.Offset = context.Eip; - sf.AddrStack.Offset = context.Esp; - sf.AddrFrame.Offset = context.Ebp; - - dwMachineType = IMAGE_FILE_MACHINE_I386; -#elif _M_X64 - sf.AddrPC.Offset = context.Rip; - sf.AddrStack.Offset = context.Rsp; - - // MSDN: x64: The frame pointer is RBP or RDI. This value is not always used. - // very funny, we'll try Rdi for now - sf.AddrFrame.Offset = context.Rdi; - - dwMachineType = IMAGE_FILE_MACHINE_AMD64; -#endif - - const unsigned int max_sym_name = 1024;// should be enough - - while ( 1 ) - { - // Get the next stack frame - if ( ! StackWalk64( dwMachineType, - m_hProcess, - GetCurrentThread(), - &sf, - &context, - 0, - SymFunctionTableAccess64, - SymGetModuleBase64, - 0 ) ) - break; - - if ( 0 == sf.AddrFrame.Offset ) // Basic sanity check to make sure - break; // the frame is OK. Bail if not. - - // Get the name of the function for this stack frame entry - BYTE symbolBuffer[ sizeof(SYMBOL_INFO) + max_sym_name ]; - PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbolBuffer; - pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); - pSymbol->MaxNameLen = max_sym_name; - - DWORD64 symDisplacement = 0; // Displacement of the input address, - // relative to the start of the symbol - - IMAGEHLP_MODULE64 module = { sizeof(IMAGEHLP_MODULE64) }; - if(SymGetModuleInfo64(m_hProcess, sf.AddrPC.Offset, &module)) - { - outputStream << module.ModuleName << "!"; - - if ( SymFromAddr(m_hProcess, sf.AddrPC.Offset, &symDisplacement, pSymbol)) - { - char undecoratedName[max_sym_name]; - UnDecorateSymbolName(pSymbol->Name, undecoratedName, max_sym_name, UNDNAME_COMPLETE); - - outputStream << undecoratedName; - - outputStream << "("; - // Use SymSetContext to get just the locals/params for this frame - IMAGEHLP_STACK_FRAME imagehlpStackFrame; - imagehlpStackFrame.InstructionOffset = sf.AddrPC.Offset; - SymSetContext( m_hProcess, &imagehlpStackFrame, 0 ); - - // Enumerate the locals/parameters - EnumerateSymbolsContext context(sf, outputStream); - SymEnumSymbols( m_hProcess, 0, 0, EnumerateSymbolsCallback, &context ); - outputStream << ")"; - - outputStream << " + " << Offset(reinterpret_cast(symDisplacement)); - - // Get the source line for this stack frame entry - IMAGEHLP_LINE64 lineInfo = { sizeof(IMAGEHLP_LINE64) }; - DWORD dwLineDisplacement; - if ( SymGetLineFromAddr64( m_hProcess, sf.AddrPC.Offset, - &dwLineDisplacement, &lineInfo ) ) - { - outputStream << " " << lineInfo.FileName << " line " << Unsigned(lineInfo.LineNumber); - } - } - else - { - outputStream << Address(reinterpret_cast(sf.AddrPC.Offset)); - } - } - - outputStream << "\n"; - } - - SymCleanup(m_hProcess); - - return; -} - -void write_stack_trace(TextOutputStream& outputStream) -{ - __try{ RaiseException(0,0,0,0); } __except(write_stack_trace((GetExceptionInformation())->ContextRecord, outputStream), EXCEPTION_CONTINUE_EXECUTION) {} -} - -#elif defined (WIN32) -void write_stack_trace(TextOutputStream& outputStream) -{ - outputStream << "\nStacktrace is disabled on this compiler\n"; -} -#else -void write_stack_trace(TextOutputStream& outputStream) -{ - outputStream << "\nStacktrace is disabled on this platform\n"; -} -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/stacktrace.h b/misc/mediasource/extra/netradiant-src/radiant/stacktrace.h deleted file mode 100644 index 6f2ee0e5..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/stacktrace.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_STACKTRACE_H) -#define INCLUDED_STACKTRACE_H - -class TextOutputStream; -void write_stack_trace(TextOutputStream& outputStream); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/surfacedialog.cpp b/misc/mediasource/extra/netradiant-src/radiant/surfacedialog.cpp deleted file mode 100644 index b2067014..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/surfacedialog.cpp +++ /dev/null @@ -1,2450 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Surface Dialog -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "surfacedialog.h" - -#include "debugging/debugging.h" -#include "warnings.h" - -#include "iscenegraph.h" -#include "itexdef.h" -#include "iundo.h" -#include "iselection.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include //Shamus: For Textool - -#include "signal/isignal.h" -#include "generic/object.h" -#include "math/vector.h" -#include "texturelib.h" -#include "shaderlib.h" -#include "stringio.h" - -#include "gtkutil/idledraw.h" -#include "gtkutil/dialog.h" -#include "gtkutil/entry.h" -#include "gtkutil/nonmodal.h" -#include "gtkutil/pointer.h" -#include "gtkutil/glwidget.h" //Shamus: For Textool -#include "gtkutil/button.h" -#include "map.h" -#include "select.h" -#include "patchmanip.h" -#include "brushmanip.h" -#include "patchdialog.h" -#include "preferences.h" -#include "brush_primit.h" -#include "xywindow.h" -#include "mainframe.h" -#include "gtkdlgs.h" -#include "dialog.h" -#include "brush.h" //Shamus: for Textool -#include "patch.h" -#include "commands.h" -#include "stream/stringstream.h" -#include "grid.h" -#include "textureentry.h" - -//NOTE: Proper functioning of Textool currently requires that the "#if 1" lines in -// brush_primit.h be changed to "#if 0". add/removeScale screws this up ATM. :-) -// Plus, Radiant seems to work just fine without that stuff. ;-) - -#define TEXTOOL_ENABLED 0 - -#if TEXTOOL_ENABLED - -namespace TexTool -{ - -//Shamus: Textool function prototypes -gboolean size_allocate(GtkWidget *, GtkAllocation *, gpointer); -gboolean expose(GtkWidget *, GdkEventExpose *, gpointer); -gboolean button_press(GtkWidget *, GdkEventButton *, gpointer); -gboolean button_release(GtkWidget *, GdkEventButton *, gpointer); -gboolean motion(GtkWidget *, GdkEventMotion *, gpointer); -void flipX(GtkToggleButton *, gpointer); -void flipY(GtkToggleButton *, gpointer); - -//End Textool function prototypes - -//Shamus: Textool globals -GtkWidget * g_textoolWin; -//End Textool globals - -void queueDraw() -{ - gtk_widget_queue_draw(g_textoolWin); -} - -} - -#endif - -inline void spin_button_set_step(GtkSpinButton* spin, gfloat step) -{ -#if 1 - gtk_spin_button_get_adjustment(spin)->step_increment = step; -#else - GValue gvalue = GValue_default(); - g_value_init(&gvalue, G_TYPE_DOUBLE); - g_value_set_double(&gvalue, step); - g_object_set(G_OBJECT(gtk_spin_button_get_adjustment(spin)), "step-increment", &gvalue, NULL); -#endif -} - -class Increment -{ - float& m_f; -public: - GtkSpinButton* m_spin; - GtkEntry* m_entry; - Increment(float& f) : m_f(f), m_spin(0), m_entry(0) - { - } - void cancel() - { - entry_set_float(m_entry, m_f); - } - typedef MemberCaller CancelCaller; - void apply() - { - m_f = static_cast(entry_get_float(m_entry)); - spin_button_set_step(m_spin, m_f); - } - typedef MemberCaller ApplyCaller; -}; - -void SurfaceInspector_GridChange(); - -class SurfaceInspector : public Dialog -{ - GtkWindow* BuildDialog(); - - NonModalEntry m_textureEntry; - NonModalSpinner m_hshiftSpinner; - NonModalEntry m_hshiftEntry; - NonModalSpinner m_vshiftSpinner; - NonModalEntry m_vshiftEntry; - NonModalSpinner m_hscaleSpinner; - NonModalEntry m_hscaleEntry; - NonModalSpinner m_vscaleSpinner; - NonModalEntry m_vscaleEntry; - NonModalSpinner m_rotateSpinner; - NonModalEntry m_rotateEntry; - - IdleDraw m_idleDraw; - - GtkCheckButton* m_surfaceFlags[32]; - GtkCheckButton* m_contentFlags[32]; - - NonModalEntry m_valueEntry; - GtkEntry* m_valueEntryWidget; -public: - WindowPositionTracker m_positionTracker; - WindowPositionTrackerImportStringCaller m_importPosition; - WindowPositionTrackerExportStringCaller m_exportPosition; - - // Dialog Data - float m_fitHorizontal; - float m_fitVertical; - - Increment m_hshiftIncrement; - Increment m_vshiftIncrement; - Increment m_hscaleIncrement; - Increment m_vscaleIncrement; - Increment m_rotateIncrement; - GtkEntry* m_texture; - - SurfaceInspector() : - m_textureEntry(ApplyShaderCaller(*this), UpdateCaller(*this)), - m_hshiftSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), - m_hshiftEntry(Increment::ApplyCaller(m_hshiftIncrement), Increment::CancelCaller(m_hshiftIncrement)), - m_vshiftSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), - m_vshiftEntry(Increment::ApplyCaller(m_vshiftIncrement), Increment::CancelCaller(m_vshiftIncrement)), - m_hscaleSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), - m_hscaleEntry(Increment::ApplyCaller(m_hscaleIncrement), Increment::CancelCaller(m_hscaleIncrement)), - m_vscaleSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), - m_vscaleEntry(Increment::ApplyCaller(m_vscaleIncrement), Increment::CancelCaller(m_vscaleIncrement)), - m_rotateSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), - m_rotateEntry(Increment::ApplyCaller(m_rotateIncrement), Increment::CancelCaller(m_rotateIncrement)), - m_idleDraw(UpdateCaller(*this)), - m_valueEntry(ApplyFlagsCaller(*this), UpdateCaller(*this)), - m_importPosition(m_positionTracker), - m_exportPosition(m_positionTracker), - m_hshiftIncrement(g_si_globals.shift[0]), - m_vshiftIncrement(g_si_globals.shift[1]), - m_hscaleIncrement(g_si_globals.scale[0]), - m_vscaleIncrement(g_si_globals.scale[1]), - m_rotateIncrement(g_si_globals.rotate) - { - m_fitVertical = 1; - m_fitHorizontal = 1; - m_positionTracker.setPosition(c_default_window_pos); - } - - void constructWindow(GtkWindow* main_window) - { - m_parent = main_window; - Create(); - AddGridChangeCallback(FreeCaller()); - } - void destroyWindow() - { - Destroy(); - } - bool visible() const - { - return GTK_WIDGET_VISIBLE(const_cast(GetWidget())); - } - void queueDraw() - { - if(visible()) - { - m_idleDraw.queueDraw(); - } - } - - void Update(); - typedef MemberCaller UpdateCaller; - void ApplyShader(); - typedef MemberCaller ApplyShaderCaller; - void ApplyTexdef(); - typedef MemberCaller ApplyTexdefCaller; - void ApplyFlags(); - typedef MemberCaller ApplyFlagsCaller; -}; - -namespace -{ - SurfaceInspector* g_SurfaceInspector; - - inline SurfaceInspector& getSurfaceInspector() - { - ASSERT_NOTNULL(g_SurfaceInspector); - return *g_SurfaceInspector; - } -} - -void SurfaceInspector_constructWindow(GtkWindow* main_window) -{ - getSurfaceInspector().constructWindow(main_window); -} -void SurfaceInspector_destroyWindow() -{ - getSurfaceInspector().destroyWindow(); -} - -void SurfaceInspector_queueDraw() -{ - getSurfaceInspector().queueDraw(); -} - -namespace -{ - CopiedString g_selectedShader; - TextureProjection g_selectedTexdef; - ContentsFlagsValue g_selectedFlags; - size_t g_selectedShaderSize[2]; -} - -void SurfaceInspector_SetSelectedShader(const char* shader) -{ - g_selectedShader = shader; - SurfaceInspector_queueDraw(); -} - -void SurfaceInspector_SetSelectedTexdef(const TextureProjection& projection) -{ - g_selectedTexdef = projection; - SurfaceInspector_queueDraw(); -} - -void SurfaceInspector_SetSelectedFlags(const ContentsFlagsValue& flags) -{ - g_selectedFlags = flags; - SurfaceInspector_queueDraw(); -} - -static bool s_texture_selection_dirty = false; - -void SurfaceInspector_updateSelection() -{ - s_texture_selection_dirty = true; - SurfaceInspector_queueDraw(); - -#if TEXTOOL_ENABLED - if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - TexTool::queueDraw(); - //globalOutputStream() << "textool texture changed..\n"; - } -#endif -} - -void SurfaceInspector_SelectionChanged(const Selectable& selectable) -{ - SurfaceInspector_updateSelection(); -} - -void SurfaceInspector_SetCurrent_FromSelected() -{ - if(s_texture_selection_dirty == true) - { - s_texture_selection_dirty = false; - if(!g_SelectedFaceInstances.empty()) - { - TextureProjection projection; -//This *may* be the point before it fucks up... Let's see! -//Yep, there was a call to removeScale in there... - Scene_BrushGetTexdef_Component_Selected(GlobalSceneGraph(), projection); - - SurfaceInspector_SetSelectedTexdef(projection); - - Scene_BrushGetShaderSize_Component_Selected(GlobalSceneGraph(), g_selectedShaderSize[0], g_selectedShaderSize[1]); - g_selectedTexdef.m_brushprimit_texdef.coords[0][2] = float_mod(g_selectedTexdef.m_brushprimit_texdef.coords[0][2], (float)g_selectedShaderSize[0]); - g_selectedTexdef.m_brushprimit_texdef.coords[1][2] = float_mod(g_selectedTexdef.m_brushprimit_texdef.coords[1][2], (float)g_selectedShaderSize[1]); - - CopiedString name; - Scene_BrushGetShader_Component_Selected(GlobalSceneGraph(), name); - if(string_not_empty(name.c_str())) - { - SurfaceInspector_SetSelectedShader(name.c_str()); - } - - ContentsFlagsValue flags; - Scene_BrushGetFlags_Component_Selected(GlobalSceneGraph(), flags); - SurfaceInspector_SetSelectedFlags(flags); - } - else - { - TextureProjection projection; - Scene_BrushGetTexdef_Selected(GlobalSceneGraph(), projection); - SurfaceInspector_SetSelectedTexdef(projection); - - CopiedString name; - Scene_BrushGetShader_Selected(GlobalSceneGraph(), name); - if(string_empty(name.c_str())) - { - Scene_PatchGetShader_Selected(GlobalSceneGraph(), name); - } - if(string_not_empty(name.c_str())) - { - SurfaceInspector_SetSelectedShader(name.c_str()); - } - - ContentsFlagsValue flags(0, 0, 0, false); - Scene_BrushGetFlags_Selected(GlobalSceneGraph(), flags); - SurfaceInspector_SetSelectedFlags(flags); - } - } -} - -const char* SurfaceInspector_GetSelectedShader() -{ - SurfaceInspector_SetCurrent_FromSelected(); - return g_selectedShader.c_str(); -} - -const TextureProjection& SurfaceInspector_GetSelectedTexdef() -{ - SurfaceInspector_SetCurrent_FromSelected(); - return g_selectedTexdef; -} - -const ContentsFlagsValue& SurfaceInspector_GetSelectedFlags() -{ - SurfaceInspector_SetCurrent_FromSelected(); - return g_selectedFlags; -} - - - -/* -=================================================== - - SURFACE INSPECTOR - -=================================================== -*/ - -si_globals_t g_si_globals; - - -// make the shift increments match the grid settings -// the objective being that the shift+arrows shortcuts move the texture by the corresponding grid size -// this depends on a scale value if you have selected a particular texture on which you want it to work: -// we move the textures in pixels, not world units. (i.e. increment values are in pixel) -// depending on the texture scale it doesn't take the same amount of pixels to move of GetGridSize() -// increment * scale = gridsize -// hscale and vscale are optional parameters, if they are zero they will be set to the default scale -// NOTE: the default scale depends if you are using BP mode or regular. -// For regular it's 0.5f (128 pixels cover 64 world units), for BP it's simply 1.0f -// see fenris #2810 -void DoSnapTToGrid(float hscale, float vscale) -{ - g_si_globals.shift[0] = static_cast(float_to_integer(static_cast(GetGridSize()) / hscale)); - g_si_globals.shift[1] = static_cast(float_to_integer(static_cast(GetGridSize()) / vscale)); - getSurfaceInspector().queueDraw(); -} - -void SurfaceInspector_GridChange() -{ - if (g_si_globals.m_bSnapTToGrid) - DoSnapTToGrid(Texdef_getDefaultTextureScale(), Texdef_getDefaultTextureScale()); -} - -// make the shift increments match the grid settings -// the objective being that the shift+arrows shortcuts move the texture by the corresponding grid size -// this depends on the current texture scale used? -// we move the textures in pixels, not world units. (i.e. increment values are in pixel) -// depending on the texture scale it doesn't take the same amount of pixels to move of GetGridSize() -// increment * scale = gridsize -static void OnBtnMatchGrid(GtkWidget *widget, gpointer data) -{ - float hscale, vscale; - hscale = static_cast(gtk_spin_button_get_value_as_float(getSurfaceInspector().m_hscaleIncrement.m_spin)); - vscale = static_cast(gtk_spin_button_get_value_as_float(getSurfaceInspector().m_vscaleIncrement.m_spin)); - - if (hscale == 0.0f || vscale == 0.0f) - { - globalOutputStream() << "ERROR: unexpected scale == 0.0f\n"; - return; - } - - DoSnapTToGrid (hscale, vscale); -} - -// DoSurface will always try to show the surface inspector -// or update it because something new has been selected -// Shamus: It does get called when the SI is hidden, but not when you select something new. ;-) -void DoSurface (void) -{ - if(getSurfaceInspector().GetWidget() == 0) - { - getSurfaceInspector().Create(); - - } - getSurfaceInspector().Update(); - getSurfaceInspector().importData(); - getSurfaceInspector().ShowDlg(); -} - -void SurfaceInspector_toggleShown() -{ - if (getSurfaceInspector().visible()) - { - getSurfaceInspector().HideDlg(); - } - else - { - DoSurface(); - } -} - -void SurfaceInspector_FitTexture() -{ - UndoableCommand undo("textureAutoFit"); - Select_FitTexture(getSurfaceInspector().m_fitHorizontal, getSurfaceInspector().m_fitVertical); -} - -static void OnBtnPatchdetails(GtkWidget *widget, gpointer data) -{ - Scene_PatchCapTexture_Selected(GlobalSceneGraph()); -} - -static void OnBtnPatchnatural(GtkWidget *widget, gpointer data) -{ - Scene_PatchNaturalTexture_Selected(GlobalSceneGraph()); -} - -static void OnBtnPatchreset(GtkWidget *widget, gpointer data) -{ - float fx, fy; - - if (DoTextureLayout (&fx, &fy) == eIDOK) - { - Scene_PatchTileTexture_Selected(GlobalSceneGraph(), fx, fy); - } -} - -static void OnBtnPatchFit(GtkWidget *widget, gpointer data) -{ - Scene_PatchTileTexture_Selected(GlobalSceneGraph(), 1, 1); -} - -static void OnBtnAxial(GtkWidget *widget, gpointer data) -{ -//globalOutputStream() << "--> [OnBtnAxial]...\n"; - UndoableCommand undo("textureDefault"); - TextureProjection projection; -//globalOutputStream() << " TexDef_Construct_Default()...\n"; - TexDef_Construct_Default(projection); -//globalOutputStream() << " Select_SetTexdef()...\n"; - -#if TEXTOOL_ENABLED - - //Shamus: - if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) - { - // Scale up texture width/height if in BP mode... -//NOTE: This may not be correct any more! :-P - if (!g_SelectedFaceInstances.empty()) - { - Face & face = g_SelectedFaceInstances.last().getFace(); - float x = face.getShader().m_state->getTexture().width; - float y = face.getShader().m_state->getTexture().height; - projection.m_brushprimit_texdef.coords[0][0] /= x; - projection.m_brushprimit_texdef.coords[0][1] /= y; - projection.m_brushprimit_texdef.coords[1][0] /= x; - projection.m_brushprimit_texdef.coords[1][1] /= y; - } - } -#endif - - Select_SetTexdef(projection); -} - -static void OnBtnFaceFit(GtkWidget *widget, gpointer data) -{ - getSurfaceInspector().exportData(); - SurfaceInspector_FitTexture(); -} - -typedef const char* FlagName; - -const FlagName surfaceflagNamesDefault[32] = { - "surf1", - "surf2", - "surf3", - "surf4", - "surf5", - "surf6", - "surf7", - "surf8", - "surf9", - "surf10", - "surf11", - "surf12", - "surf13", - "surf14", - "surf15", - "surf16", - "surf17", - "surf18", - "surf19", - "surf20", - "surf21", - "surf22", - "surf23", - "surf24", - "surf25", - "surf26", - "surf27", - "surf28", - "surf29", - "surf30", - "surf31", - "surf32" -}; - -const FlagName contentflagNamesDefault[32] = { - "cont1", - "cont2", - "cont3", - "cont4", - "cont5", - "cont6", - "cont7", - "cont8", - "cont9", - "cont10", - "cont11", - "cont12", - "cont13", - "cont14", - "cont15", - "cont16", - "cont17", - "cont18", - "cont19", - "cont20", - "cont21", - "cont22", - "cont23", - "cont24", - "cont25", - "cont26", - "cont27", - "cont28", - "cont29", - "cont30", - "cont31", - "cont32" -}; - -const char* getSurfaceFlagName(std::size_t bit) -{ - const char* value = g_pGameDescription->getKeyValue(surfaceflagNamesDefault[bit]); - if(string_empty(value)) - { - return surfaceflagNamesDefault[bit]; - } - return value; -} - -const char* getContentFlagName(std::size_t bit) -{ - const char* value = g_pGameDescription->getKeyValue(contentflagNamesDefault[bit]); - if(string_empty(value)) - { - return contentflagNamesDefault[bit]; - } - return value; -} - - -// ============================================================================= -// SurfaceInspector class - -guint togglebutton_connect_toggled(GtkToggleButton* button, const Callback& callback) -{ - return g_signal_connect_swapped(G_OBJECT(button), "toggled", G_CALLBACK(callback.getThunk()), callback.getEnvironment()); -} - -GtkWindow* SurfaceInspector::BuildDialog() -{ - GtkWindow* window = create_floating_window("Surface Inspector", m_parent); - - m_positionTracker.connect(window); - - global_accel_connect_window(window); - - window_connect_focus_in_clear_focus_widget(window); - - - { - // replaced by only the vbox: - GtkWidget* vbox = gtk_vbox_new (FALSE, 5); - gtk_widget_show (vbox); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); - gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); - - { - GtkWidget* hbox2 = gtk_hbox_new (FALSE, 5); - gtk_widget_show (hbox2); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox2), FALSE, FALSE, 0); - - { - GtkWidget* label = gtk_label_new ("Texture"); - gtk_widget_show (label); - gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, TRUE, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_box_pack_start(GTK_BOX(hbox2), GTK_WIDGET(entry), TRUE, TRUE, 0); - m_texture = entry; - m_textureEntry.connect(entry); - GlobalTextureEntryCompletion::instance().connect(entry); - } - } - - - { - GtkWidget* table = gtk_table_new (6, 4, FALSE); - gtk_widget_show (table); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), FALSE, FALSE, 0); - gtk_table_set_row_spacings(GTK_TABLE(table), 5); - gtk_table_set_col_spacings(GTK_TABLE(table), 5); - { - GtkWidget* label = gtk_label_new ("Horizontal shift"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 2)); - m_hshiftIncrement.m_spin = spin; - m_hshiftSpinner.connect(spin); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach (GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); - } - { - GtkWidget* label = gtk_label_new ("Step"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 0, 1, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - m_hshiftIncrement.m_entry = entry; - m_hshiftEntry.connect(entry); - } - { - GtkWidget* label = gtk_label_new ("Vertical shift"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 2)); - m_vshiftIncrement.m_spin = spin; - m_vshiftSpinner.connect(spin); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); - } - { - GtkWidget* label = gtk_label_new ("Step"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 1, 2, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - m_vshiftIncrement.m_entry = entry; - m_vshiftEntry.connect(entry); - } - { - GtkWidget* label = gtk_label_new ("Horizontal stretch"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 5)); - m_hscaleIncrement.m_spin = spin; - m_hscaleSpinner.connect(spin); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); - } - { - GtkWidget* label = gtk_label_new ("Step"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 2, 3, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 2, 3); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 2, 3); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - m_hscaleIncrement.m_entry = entry; - m_hscaleEntry.connect(entry); - } - { - GtkWidget* label = gtk_label_new ("Vertical stretch"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 5)); - m_vscaleIncrement.m_spin = spin; - m_vscaleSpinner.connect(spin); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 3, 4, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); - } - { - GtkWidget* label = gtk_label_new ("Step"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 2, 3, 3, 4, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 3, 4, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - m_vscaleIncrement.m_entry = entry; - m_vscaleEntry.connect(entry); - } - { - GtkWidget* label = gtk_label_new ("Rotate"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, 4, 5, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 2)); - m_rotateIncrement.m_spin = spin; - m_rotateSpinner.connect(spin); - gtk_widget_show(GTK_WIDGET(spin)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 4, 5, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); - gtk_spin_button_set_wrap(spin, TRUE); - } - { - GtkWidget* label = gtk_label_new ("Step"); - gtk_widget_show (label); - gtk_misc_set_alignment (GTK_MISC (label), 0, 0); - gtk_table_attach(GTK_TABLE(table), label, 2, 3, 4, 5, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 4, 5, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); - m_rotateIncrement.m_entry = entry; - m_rotateEntry.connect(entry); - } - { - // match grid button - GtkWidget* button = gtk_button_new_with_label ("Match Grid"); - gtk_widget_show (button); - gtk_table_attach(GTK_TABLE(table), button, 2, 4, 5, 6, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnMatchGrid), 0); - } - } - - { - GtkWidget* frame = gtk_frame_new ("Texturing"); - gtk_widget_show (frame); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), FALSE, FALSE, 0); - { - GtkWidget* table = gtk_table_new (4, 4, FALSE); - gtk_widget_show (table); - gtk_container_add (GTK_CONTAINER (frame), table); - gtk_table_set_row_spacings(GTK_TABLE(table), 5); - gtk_table_set_col_spacings(GTK_TABLE(table), 5); - gtk_container_set_border_width (GTK_CONTAINER (table), 5); - { - GtkWidget* label = gtk_label_new ("Brush"); - gtk_widget_show (label); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new ("Patch"); - gtk_widget_show (label); - gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new ("Width"); - gtk_widget_show (label); - gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* label = gtk_label_new ("Height"); - gtk_widget_show (label); - gtk_table_attach(GTK_TABLE(table), label, 3, 4, 0, 1, - (GtkAttachOptions) (GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - } - { - GtkWidget* button = gtk_button_new_with_label ("Axial"); - gtk_widget_show (button); - gtk_table_attach(GTK_TABLE(table), button, 0, 1, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnBtnAxial), 0); - gtk_widget_set_usize (button, 60, -2); - } - { - GtkWidget* button = gtk_button_new_with_label ("Fit"); - gtk_widget_show (button); - gtk_table_attach(GTK_TABLE(table), button, 1, 2, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnBtnFaceFit), 0); - gtk_widget_set_usize (button, 60, -2); - } - { - GtkWidget* button = gtk_button_new_with_label ("CAP"); - gtk_widget_show (button); - gtk_table_attach(GTK_TABLE(table), button, 0, 1, 3, 4, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnBtnPatchdetails), 0); - gtk_widget_set_usize (button, 60, -2); - } - { - GtkWidget* button = gtk_button_new_with_label ("Set..."); - gtk_widget_show (button); - gtk_table_attach(GTK_TABLE(table), button, 1, 2, 3, 4, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnBtnPatchreset), 0); - gtk_widget_set_usize (button, 60, -2); - } - { - GtkWidget* button = gtk_button_new_with_label ("Natural"); - gtk_widget_show (button); - gtk_table_attach(GTK_TABLE(table), button, 2, 3, 3, 4, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnBtnPatchnatural), 0); - gtk_widget_set_usize (button, 60, -2); - } - { - GtkWidget* button = gtk_button_new_with_label ("Fit"); - gtk_widget_show (button); - gtk_table_attach(GTK_TABLE(table), button, 3, 4, 3, 4, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - g_signal_connect(G_OBJECT(button), "clicked", - G_CALLBACK(OnBtnPatchFit), 0); - gtk_widget_set_usize (button, 60, -2); - } - { - GtkWidget* spin = gtk_spin_button_new (GTK_ADJUSTMENT (gtk_adjustment_new (1, 0, 1 << 16, 1, 10, 0)), 0, 6); - gtk_widget_show (spin); - gtk_table_attach(GTK_TABLE(table), spin, 2, 3, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - AddDialogData(*GTK_SPIN_BUTTON(spin), m_fitHorizontal); - } - { - GtkWidget* spin = gtk_spin_button_new (GTK_ADJUSTMENT (gtk_adjustment_new (1, 0, 1 << 16, 1, 10, 0)), 0, 6); - gtk_widget_show (spin); - gtk_table_attach(GTK_TABLE(table), spin, 3, 4, 1, 2, - (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), - (GtkAttachOptions) (0), 0, 0); - gtk_widget_set_usize (spin, 60, -2); - AddDialogData(*GTK_SPIN_BUTTON(spin), m_fitVertical); - } - } - } - if(!string_empty(g_pGameDescription->getKeyValue("si_flags"))) - { - { - GtkFrame* frame = GTK_FRAME(gtk_frame_new("Surface Flags")); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); - { - GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 4)); - //gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); - gtk_widget_show(GTK_WIDGET(vbox3)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); - { - GtkTable* table = GTK_TABLE(gtk_table_new(8, 4, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings(table, 0); - gtk_table_set_col_spacings(table, 0); - - GtkCheckButton** p = m_surfaceFlags; - - for(int c = 0; c != 4; ++c) - { - for(int r = 0; r != 8; ++r) - { - GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new_with_label(getSurfaceFlagName(c * 8 + r))); - gtk_widget_show(GTK_WIDGET(check)); - gtk_table_attach(table, GTK_WIDGET(check), c, c+1, r, r+1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - *p++ = check; - guint handler_id = togglebutton_connect_toggled(GTK_TOGGLE_BUTTON(check), ApplyFlagsCaller(*this)); - g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler_id)); - } - } - } - } - } - { - GtkFrame* frame = GTK_FRAME(gtk_frame_new("Content Flags")); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); - { - GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 4)); - //gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); - gtk_widget_show(GTK_WIDGET(vbox3)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); - { - - GtkTable* table = GTK_TABLE(gtk_table_new(8, 4, FALSE)); - gtk_widget_show(GTK_WIDGET(table)); - gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); - gtk_table_set_row_spacings(table, 0); - gtk_table_set_col_spacings(table, 0); - - GtkCheckButton** p = m_contentFlags; - - for(int c = 0; c != 4; ++c) - { - for(int r = 0; r != 8; ++r) - { - GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new_with_label(getContentFlagName(c * 8 + r))); - gtk_widget_show(GTK_WIDGET(check)); - gtk_table_attach(table, GTK_WIDGET(check), c, c+1, r, r+1, - (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), - (GtkAttachOptions)(0), 0, 0); - *p++ = check; - guint handler_id = togglebutton_connect_toggled(GTK_TOGGLE_BUTTON(check), ApplyFlagsCaller(*this)); - g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler_id)); - } - } - - // not allowed to modify detail flag using Surface Inspector - gtk_widget_set_sensitive(GTK_WIDGET(m_contentFlags[BRUSH_DETAIL_FLAG]), FALSE); - } - } - } - { - GtkFrame* frame = GTK_FRAME(gtk_frame_new("Value")); - gtk_widget_show(GTK_WIDGET(frame)); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); - { - GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 4)); - gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); - gtk_widget_show(GTK_WIDGET(vbox3)); - gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); - - { - GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); - gtk_widget_show(GTK_WIDGET(entry)); - gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(entry), TRUE, TRUE, 0); - m_valueEntryWidget = entry; - m_valueEntry.connect(entry); - } - } - } - } - -#if TEXTOOL_ENABLED - if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) -// Shamus: Textool goodies... - { - GtkWidget * frame = gtk_frame_new("Textool"); - gtk_widget_show(frame); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), FALSE, FALSE, 0); - { - //Prolly should make this a member or global var, so the SI can draw on it... - TexTool::g_textoolWin = glwidget_new(FALSE); - // --> Dunno, but this stuff may be necessary... (Looks like it!) - gtk_widget_ref(TexTool::g_textoolWin); - gtk_widget_set_events(TexTool::g_textoolWin, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK); - GTK_WIDGET_SET_FLAGS(TexTool::g_textoolWin, GTK_CAN_FOCUS); - // <-- end stuff... - gtk_widget_show(TexTool::g_textoolWin); - gtk_widget_set_usize(TexTool::g_textoolWin, -1, 240); //Yeah! - gtk_container_add(GTK_CONTAINER(frame), TexTool::g_textoolWin); - - g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "size_allocate", G_CALLBACK(TexTool::size_allocate), NULL); - g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "expose_event", G_CALLBACK(TexTool::expose), NULL); - g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "button_press_event", G_CALLBACK(TexTool::button_press), NULL); - g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "button_release_event", G_CALLBACK(TexTool::button_release), NULL); - g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "motion_notify_event", G_CALLBACK(TexTool::motion), NULL); - } - { - GtkWidget * hbox = gtk_hbox_new(FALSE, 5); - gtk_widget_show(hbox); - gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, FALSE, 0); - // Checkboxes go here... (Flip X/Y) - GtkWidget * flipX = gtk_check_button_new_with_label("Flip X axis"); - GtkWidget * flipY = gtk_check_button_new_with_label("Flip Y axis"); - gtk_widget_show(flipX); - gtk_widget_show(flipY); - gtk_box_pack_start(GTK_BOX(hbox), flipX, FALSE, FALSE, 0); - gtk_box_pack_start(GTK_BOX(hbox), flipY, FALSE, FALSE, 0); - -//Instead of this, we probably need to create a vbox to put into the frame, then the -//window, then the hbox. !!! FIX !!! -// gtk_container_add(GTK_CONTAINER(frame), hbox); - -//Hmm. Do we really need g_object_set_data? Mebbe not... And we don't! :-) -// g_object_set_data(G_OBJECT(flipX), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(flipX), "toggled", G_CALLBACK(TexTool::flipX), 0))); -// g_object_set_data(G_OBJECT(flipY), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(flipY), "toggled", G_CALLBACK(TexTool::flipY), 0))); -//Instead, just do: - g_signal_connect(G_OBJECT(flipX), "toggled", G_CALLBACK(TexTool::flipX), NULL); - g_signal_connect(G_OBJECT(flipY), "toggled", G_CALLBACK(TexTool::flipY), NULL); - } - } -#endif - } - - return window; -} - -/* -============== -Update - -Set the fields to the current texdef (i.e. map/texdef -> dialog widgets) -if faces selected (instead of brushes) -> will read this face texdef, else current texdef -if only patches selected, will read the patch texdef -=============== -*/ - -void spin_button_set_value_no_signal(GtkSpinButton* spin, gdouble value) -{ - guint handler_id = gpointer_to_int(g_object_get_data(G_OBJECT(spin), "handler")); - g_signal_handler_block(G_OBJECT(gtk_spin_button_get_adjustment(spin)), handler_id); - gtk_spin_button_set_value(spin, value); - g_signal_handler_unblock(G_OBJECT(gtk_spin_button_get_adjustment(spin)), handler_id); -} - -void spin_button_set_step_increment(GtkSpinButton* spin, gdouble value) -{ - GtkAdjustment* adjust = gtk_spin_button_get_adjustment(spin); - adjust->step_increment = value; -} - -void SurfaceInspector::Update() -{ - const char * name = SurfaceInspector_GetSelectedShader(); - - if(shader_is_texture(name)) - { - gtk_entry_set_text(m_texture, shader_get_textureName(name)); - } - else - { - gtk_entry_set_text(m_texture, ""); - } - - texdef_t shiftScaleRotate; -//Shamus: This is where we get into trouble--the BP code tries to convert to a "faked" -//shift, rotate & scale values from the brush face, which seems to screw up for some reason. -//!!! FIX !!! -/*globalOutputStream() << "--> SI::Update. About to do ShiftScaleRotate_fromFace()...\n"; -SurfaceInspector_GetSelectedBPTexdef(); -globalOutputStream() << "BP: (" << g_selectedBrushPrimitTexdef.coords[0][0] << ", " << g_selectedBrushPrimitTexdef.coords[0][1] << ")(" - << g_selectedBrushPrimitTexdef.coords[1][0] << ", " << g_selectedBrushPrimitTexdef.coords[1][1] << ")(" - << g_selectedBrushPrimitTexdef.coords[0][2] << ", " << g_selectedBrushPrimitTexdef.coords[1][2] << ") SurfaceInspector::Update\n";//*/ -//Ok, it's screwed up *before* we get here... - ShiftScaleRotate_fromFace(shiftScaleRotate, SurfaceInspector_GetSelectedTexdef()); - - // normalize again to hide the ridiculously high scale values that get created when using texlock - shiftScaleRotate.shift[0] = float_mod(shiftScaleRotate.shift[0], (float)g_selectedShaderSize[0]); - shiftScaleRotate.shift[1] = float_mod(shiftScaleRotate.shift[1], (float)g_selectedShaderSize[1]); - - { - spin_button_set_value_no_signal(m_hshiftIncrement.m_spin, shiftScaleRotate.shift[0]); - spin_button_set_step_increment(m_hshiftIncrement.m_spin, g_si_globals.shift[0]); - entry_set_float(m_hshiftIncrement.m_entry, g_si_globals.shift[0]); - } - - { - spin_button_set_value_no_signal(m_vshiftIncrement.m_spin, shiftScaleRotate.shift[1]); - spin_button_set_step_increment(m_vshiftIncrement.m_spin, g_si_globals.shift[1]); - entry_set_float(m_vshiftIncrement.m_entry, g_si_globals.shift[1]); - } - - { - spin_button_set_value_no_signal(m_hscaleIncrement.m_spin, shiftScaleRotate.scale[0]); - spin_button_set_step_increment(m_hscaleIncrement.m_spin, g_si_globals.scale[0]); - entry_set_float(m_hscaleIncrement.m_entry, g_si_globals.scale[0]); - } - - { - spin_button_set_value_no_signal(m_vscaleIncrement.m_spin, shiftScaleRotate.scale[1]); - spin_button_set_step_increment(m_vscaleIncrement.m_spin, g_si_globals.scale[1]); - entry_set_float(m_vscaleIncrement.m_entry, g_si_globals.scale[1]); - } - - { - spin_button_set_value_no_signal(m_rotateIncrement.m_spin, shiftScaleRotate.rotate); - spin_button_set_step_increment(m_rotateIncrement.m_spin, g_si_globals.rotate); - entry_set_float(m_rotateIncrement.m_entry, g_si_globals.rotate); - } - - if(!string_empty(g_pGameDescription->getKeyValue("si_flags"))) - { - ContentsFlagsValue flags(SurfaceInspector_GetSelectedFlags()); - - entry_set_int(m_valueEntryWidget, flags.m_value); - - for(GtkCheckButton** p = m_surfaceFlags; p != m_surfaceFlags + 32; ++p) - { - toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(*p), flags.m_surfaceFlags & (1 << (p - m_surfaceFlags))); - } - - for(GtkCheckButton** p = m_contentFlags; p != m_contentFlags + 32; ++p) - { - toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(*p), flags.m_contentFlags & (1 << (p - m_contentFlags))); - } - } -} - -/* -============== -Apply - -Reads the fields to get the current texdef (i.e. widgets -> MAP) -in brush primitive mode, grab the fake shift scale rot and compute a new texture matrix -=============== -*/ -void SurfaceInspector::ApplyShader() -{ - StringOutputStream name(256); - name << GlobalTexturePrefix_get() << gtk_entry_get_text(m_texture); - - // TTimo: detect and refuse invalid texture names (at least the ones with spaces) - if(!texdef_name_valid(name.c_str())) - { - globalErrorStream() << "invalid texture name '" << name.c_str() << "'\n"; - SurfaceInspector_queueDraw(); - return; - } - - UndoableCommand undo("textureNameSetSelected"); - Select_SetShader(name.c_str()); -} - -void SurfaceInspector::ApplyTexdef() -{ - texdef_t shiftScaleRotate; - - shiftScaleRotate.shift[0] = static_cast(gtk_spin_button_get_value_as_float(m_hshiftIncrement.m_spin)); - shiftScaleRotate.shift[1] = static_cast(gtk_spin_button_get_value_as_float(m_vshiftIncrement.m_spin)); - shiftScaleRotate.scale[0] = static_cast(gtk_spin_button_get_value_as_float(m_hscaleIncrement.m_spin)); - shiftScaleRotate.scale[1] = static_cast(gtk_spin_button_get_value_as_float(m_vscaleIncrement.m_spin)); - shiftScaleRotate.rotate = static_cast(gtk_spin_button_get_value_as_float(m_rotateIncrement.m_spin)); - - TextureProjection projection; -//Shamus: This is the other place that screws up, it seems, since it doesn't seem to do the -//conversion from the face (I think) and so bogus values end up in the thing... !!! FIX !!! -//This is actually OK. :-P - ShiftScaleRotate_toFace(shiftScaleRotate, projection); - - UndoableCommand undo("textureProjectionSetSelected"); - Select_SetTexdef(projection); -} - -void SurfaceInspector::ApplyFlags() -{ - unsigned int surfaceflags = 0; - for(GtkCheckButton** p = m_surfaceFlags; p != m_surfaceFlags + 32; ++p) - { - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(*p))) - { - surfaceflags |= (1 << (p - m_surfaceFlags)); - } - } - - unsigned int contentflags = 0; - for(GtkCheckButton** p = m_contentFlags; p != m_contentFlags + 32; ++p) - { - if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(*p))) - { - contentflags |= (1 << (p - m_contentFlags)); - } - } - - int value = entry_get_int(m_valueEntryWidget); - - UndoableCommand undo("flagsSetSelected"); - Select_SetFlags(ContentsFlagsValue(surfaceflags, contentflags, value, true)); -} - - -void Face_getTexture(Face& face, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags) -{ - shader = face.GetShader(); - face.GetTexdef(projection); - flags = face.getShader().m_flags; -} -typedef Function4 FaceGetTexture; - -void Face_setTexture(Face& face, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags) -{ - face.SetShader(shader); - face.SetTexdef(projection); - face.SetFlags(flags); -} -typedef Function4 FaceSetTexture; - - -void Patch_getTexture(Patch& patch, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags) -{ - shader = patch.GetShader(); - projection = TextureProjection(texdef_t(), brushprimit_texdef_t(), Vector3(0, 0, 0), Vector3(0, 0, 0)); - flags = ContentsFlagsValue(0, 0, 0, false); -} -typedef Function4 PatchGetTexture; - -void Patch_setTexture(Patch& patch, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags) -{ - patch.SetShader(shader); -} -typedef Function4 PatchSetTexture; - - -typedef Callback3 GetTextureCallback; -typedef Callback3 SetTextureCallback; - -struct Texturable -{ - GetTextureCallback getTexture; - SetTextureCallback setTexture; -}; - - -void Face_getClosest(Face& face, SelectionTest& test, SelectionIntersection& bestIntersection, Texturable& texturable) -{ - SelectionIntersection intersection; - face.testSelect(test, intersection); - if(intersection.valid() - && SelectionIntersection_closer(intersection, bestIntersection)) - { - bestIntersection = intersection; - texturable.setTexture = makeCallback3(FaceSetTexture(), face); - texturable.getTexture = makeCallback3(FaceGetTexture(), face); - } -} - - -class OccludeSelector : public Selector -{ - SelectionIntersection& m_bestIntersection; - bool& m_occluded; -public: - OccludeSelector(SelectionIntersection& bestIntersection, bool& occluded) : m_bestIntersection(bestIntersection), m_occluded(occluded) - { - m_occluded = false; - } - void pushSelectable(Selectable& selectable) - { - } - void popSelectable() - { - } - void addIntersection(const SelectionIntersection& intersection) - { - if(SelectionIntersection_closer(intersection, m_bestIntersection)) - { - m_bestIntersection = intersection; - m_occluded = true; - } - } -}; - -class BrushGetClosestFaceVisibleWalker : public scene::Graph::Walker -{ - SelectionTest& m_test; - Texturable& m_texturable; - mutable SelectionIntersection m_bestIntersection; -public: - BrushGetClosestFaceVisibleWalker(SelectionTest& test, Texturable& texturable) : m_test(test), m_texturable(texturable) - { - } - bool pre(const scene::Path& path, scene::Instance& instance) const - { - if(path.top().get().visible()) - { - BrushInstance* brush = Instance_getBrush(instance); - if(brush != 0) - { - m_test.BeginMesh(brush->localToWorld()); - - for(Brush::const_iterator i = brush->getBrush().begin(); i != brush->getBrush().end(); ++i) - { - Face_getClosest(*(*i), m_test, m_bestIntersection, m_texturable); - } - } - else - { - SelectionTestable* selectionTestable = Instance_getSelectionTestable(instance); - if(selectionTestable) - { - bool occluded; - OccludeSelector selector(m_bestIntersection, occluded); - selectionTestable->testSelect(selector, m_test); - if(occluded) - { - Patch* patch = Node_getPatch(path.top()); - if(patch != 0) - { - m_texturable.setTexture = makeCallback3(PatchSetTexture(), *patch); - m_texturable.getTexture = makeCallback3(PatchGetTexture(), *patch); - } - else - { - m_texturable = Texturable(); - } - } - } - } - } - return true; - } -}; - -Texturable Scene_getClosestTexturable(scene::Graph& graph, SelectionTest& test) -{ - Texturable texturable; - graph.traverse(BrushGetClosestFaceVisibleWalker(test, texturable)); - return texturable; -} - -bool Scene_getClosestTexture(scene::Graph& graph, SelectionTest& test, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags) -{ - Texturable texturable = Scene_getClosestTexturable(graph, test); - if(texturable.getTexture != GetTextureCallback()) - { - texturable.getTexture(shader, projection, flags); - return true; - } - return false; -} - -void Scene_setClosestTexture(scene::Graph& graph, SelectionTest& test, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags) -{ - Texturable texturable = Scene_getClosestTexturable(graph, test); - if(texturable.setTexture != SetTextureCallback()) - { - texturable.setTexture(shader, projection, flags); - } -} - - -class FaceTexture -{ -public: - TextureProjection m_projection; - ContentsFlagsValue m_flags; -}; - -FaceTexture g_faceTextureClipboard; - -void FaceTextureClipboard_setDefault() -{ - g_faceTextureClipboard.m_flags = ContentsFlagsValue(0, 0, 0, false); - TexDef_Construct_Default(g_faceTextureClipboard.m_projection); -} - -void TextureClipboard_textureSelected(const char* shader) -{ - FaceTextureClipboard_setDefault(); -} - -class TextureBrowser; -extern TextureBrowser g_TextureBrowser; -void TextureBrowser_SetSelectedShader(TextureBrowser& textureBrowser, const char* shader); -const char* TextureBrowser_GetSelectedShader(TextureBrowser& textureBrowser); - -void Scene_copyClosestTexture(SelectionTest& test) -{ - CopiedString shader; - if(Scene_getClosestTexture(GlobalSceneGraph(), test, shader, g_faceTextureClipboard.m_projection, g_faceTextureClipboard.m_flags)) - { - TextureBrowser_SetSelectedShader(g_TextureBrowser, shader.c_str()); - } -} - -void Scene_applyClosestTexture(SelectionTest& test) -{ - UndoableCommand command("facePaintTexture"); - - Scene_setClosestTexture(GlobalSceneGraph(), test, TextureBrowser_GetSelectedShader(g_TextureBrowser), g_faceTextureClipboard.m_projection, g_faceTextureClipboard.m_flags); - - SceneChangeNotify(); -} - - - - - -void SelectedFaces_copyTexture() -{ - if(!g_SelectedFaceInstances.empty()) - { - Face& face = g_SelectedFaceInstances.last().getFace(); - face.GetTexdef(g_faceTextureClipboard.m_projection); - g_faceTextureClipboard.m_flags = face.getShader().m_flags; - - TextureBrowser_SetSelectedShader(g_TextureBrowser, face.getShader().getShader()); - } -} - -void FaceInstance_pasteTexture(FaceInstance& faceInstance) -{ - faceInstance.getFace().SetTexdef(g_faceTextureClipboard.m_projection); - faceInstance.getFace().SetShader(TextureBrowser_GetSelectedShader(g_TextureBrowser)); - faceInstance.getFace().SetFlags(g_faceTextureClipboard.m_flags); - SceneChangeNotify(); -} - -bool SelectedFaces_empty() -{ - return g_SelectedFaceInstances.empty(); -} - -void SelectedFaces_pasteTexture() -{ - UndoableCommand command("facePasteTexture"); - g_SelectedFaceInstances.foreach(FaceInstance_pasteTexture); -} - - - -void SurfaceInspector_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox("", "Surface Inspector Increments Match Grid", g_si_globals.m_bSnapTToGrid); -} -void SurfaceInspector_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Surface Inspector", "Surface Inspector Preferences")); - SurfaceInspector_constructPreferences(page); -} -void SurfaceInspector_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - -void SurfaceInspector_registerCommands() -{ - GlobalCommands_insert("FitTexture", FreeCaller(), Accelerator('B', (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("SurfaceInspector", FreeCaller(), Accelerator('S')); - - GlobalCommands_insert("FaceCopyTexture", FreeCaller()); - GlobalCommands_insert("FacePasteTexture", FreeCaller()); -} - - -#include "preferencesystem.h" - - -void SurfaceInspector_Construct() -{ - g_SurfaceInspector = new SurfaceInspector; - - SurfaceInspector_registerCommands(); - - FaceTextureClipboard_setDefault(); - - GlobalPreferenceSystem().registerPreference("SurfaceWnd", getSurfaceInspector().m_importPosition, getSurfaceInspector().m_exportPosition); - GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Scale1", FloatImportStringCaller(g_si_globals.scale[0]), FloatExportStringCaller(g_si_globals.scale[0])); - GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Scale2", FloatImportStringCaller(g_si_globals.scale[1]), FloatExportStringCaller(g_si_globals.scale[1])); - GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Shift1", FloatImportStringCaller(g_si_globals.shift[0]), FloatExportStringCaller(g_si_globals.shift[0])); - GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Shift2", FloatImportStringCaller(g_si_globals.shift[1]), FloatExportStringCaller(g_si_globals.shift[1])); - GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Rotate", FloatImportStringCaller(g_si_globals.rotate), FloatExportStringCaller(g_si_globals.rotate)); - GlobalPreferenceSystem().registerPreference("SnapTToGrid", BoolImportStringCaller(g_si_globals.m_bSnapTToGrid), BoolExportStringCaller(g_si_globals.m_bSnapTToGrid)); - - typedef FreeCaller1 SurfaceInspectorSelectionChangedCaller; - GlobalSelectionSystem().addSelectionChangeCallback(SurfaceInspectorSelectionChangedCaller()); - typedef FreeCaller SurfaceInspectorUpdateSelectionCaller; - Brush_addTextureChangedCallback(SurfaceInspectorUpdateSelectionCaller()); - Patch_addTextureChangedCallback(SurfaceInspectorUpdateSelectionCaller()); - - SurfaceInspector_registerPreferencesPage(); -} -void SurfaceInspector_Destroy() -{ - delete g_SurfaceInspector; -} - - - -#if TEXTOOL_ENABLED - -namespace TexTool { // namespace hides these symbols from other object-files -// -//Shamus: Textool functions, including GTK+ callbacks -// - -//NOTE: Black screen when TT first comes up is caused by an uninitialized Extent... !!! FIX !!! -// But... You can see down below that it *is* initialized! WTF? -struct Extent -{ - float minX, minY, maxX, maxY; - float width(void) { return fabs(maxX - minX); } - float height(void) { return fabs(maxY - minY); } -}; - -//This seems to control the texture scale... (Yep! ;-) -Extent extents = { -2.0f, -2.0f, +2.0f, +2.0f }; -brushprimit_texdef_t tm; // Texture transform matrix -Vector2 pts[c_brush_maxFaces]; -Vector2 center; -int numPts; -int textureNum; -Vector2 textureSize; -Vector2 windowSize; -#define VP_PADDING 1.2 -#define PI 3.14159265358979 -bool lButtonDown = false; -bool rButtonDown = false; -//int dragPoint; -//int anchorPoint; -bool haveAnchor = false; -brushprimit_texdef_t currentBP; -brushprimit_texdef_t origBP; // Original brush primitive (before we muck it up) -float controlRadius = 5.0f; -float rotationAngle = 0.0f; -float rotationAngle2 = 0.0f; -float oldRotationAngle; -Vector2 rotationPoint; -bool translatingX = false; // Widget state variables -bool translatingY = false; -bool scalingX = false; -bool scalingY = false; -bool rotating = false; -bool resizingX = false; // Not sure what this means... :-/ -bool resizingY = false; -float origAngle, origScaleX, origScaleY; -Vector2 oldCenter; - - -// Function prototypes (move up to top later...) - -void DrawCircularArc(Vector2 ctr, float startAngle, float endAngle, float radius); - - -void CopyPointsFromSelectedFace(void) -{ - // Make sure that there's a face and winding to get! - - if (g_SelectedFaceInstances.empty()) - { - numPts = 0; - return; - } - - Face & face = g_SelectedFaceInstances.last().getFace(); - textureNum = face.getShader().m_state->getTexture().texture_number; - textureSize.x() = face.getShader().m_state->getTexture().width; - textureSize.y() = face.getShader().m_state->getTexture().height; -//globalOutputStream() << "--> Texture #" << textureNum << ": " << textureSize.x() << " x " << textureSize.y() << "...\n"; - - currentBP = SurfaceInspector_GetSelectedTexdef().m_brushprimit_texdef; - - face.EmitTextureCoordinates(); - Winding & w = face.getWinding(); - int count = 0; - - for(Winding::const_iterator i=w.begin(); i!=w.end(); i++) - { - //globalOutputStream() << (*i).texcoord.x() << " " << (*i).texcoord.y() << ", "; - pts[count].x() = (*i).texcoord.x(); - pts[count].y() = (*i).texcoord.y(); - count++; - } - - numPts = count; - - //globalOutputStream() << " ..copied points\n"; -} - - brushprimit_texdef_t bp; -//This approach is probably wrongheaded and just not right anyway. So, !!! FIX !!! [DONE] -void CommitChanges(void) -{ - texdef_t t; // Throwaway, since this is BP only - - bp.coords[0][0] = tm.coords[0][0] * origBP.coords[0][0] + tm.coords[0][1] * origBP.coords[1][0]; - bp.coords[0][1] = tm.coords[0][0] * origBP.coords[0][1] + tm.coords[0][1] * origBP.coords[1][1]; - bp.coords[0][2] = tm.coords[0][0] * origBP.coords[0][2] + tm.coords[0][1] * origBP.coords[1][2] + tm.coords[0][2]; -//Ok, this works for translation... -// bp.coords[0][2] = tm.coords[0][0] * origBP.coords[0][2] + tm.coords[0][1] * origBP.coords[1][2] + tm.coords[0][2] * textureSize.x(); - bp.coords[1][0] = tm.coords[1][0] * origBP.coords[0][0] + tm.coords[1][1] * origBP.coords[1][0]; - bp.coords[1][1] = tm.coords[1][0] * origBP.coords[0][1] + tm.coords[1][1] * origBP.coords[1][1]; - bp.coords[1][2] = tm.coords[1][0] * origBP.coords[0][2] + tm.coords[1][1] * origBP.coords[1][2] + tm.coords[1][2]; -// bp.coords[1][2] = tm.coords[1][0] * origBP.coords[0][2] + tm.coords[1][1] * origBP.coords[1][2] + tm.coords[1][2] * textureSize.y(); - -//This doesn't work: g_brush_texture_changed(); -// Let's try this: -//Note: We should only set an undo *after* the button has been released... !!! FIX !!! -//Definitely *should* have an undo, though! -// UndoableCommand undo("textureProjectionSetSelected"); - Select_SetTexdef(TextureProjection(t, bp, Vector3(0, 0, 0), Vector3(0, 0, 0))); -//This is working, but for some reason the translate is causing the rest of the SI -//widgets to yield bad readings... !!! FIX !!! -//I.e., click on textool window, translate face wireframe, then controls go crazy. Dunno why. -//It's because there were some uncommented out add/removeScale functions in brush.h and a -//removeScale in brushmanip.cpp... :-/ -//Translate isn't working at all now... :-( -//It's because we need to multiply in some scaling factor (prolly the texture width/height) -//Yep. :-P -} - -void UpdateControlPoints(void) -{ - CommitChanges(); - - // Init texture transform matrix - - tm.coords[0][0] = 1.0f; tm.coords[0][1] = 0.0f; tm.coords[0][2] = 0.0f; - tm.coords[1][0] = 0.0f; tm.coords[1][1] = 1.0f; tm.coords[1][2] = 0.0f; -} - - -/* -For shifting we have: -*/ -/* -The code that should provide reasonable defaults, but doesn't for some reason: -It's scaling the BP by 128 for some reason, between the time it's created and the -time we get back to the SI widgets: - -static void OnBtnAxial(GtkWidget *widget, gpointer data) -{ - UndoableCommand undo("textureDefault"); - TextureProjection projection; - TexDef_Construct_Default(projection); - Select_SetTexdef(projection); -} - -Select_SetTexdef() calls Scene_BrushSetTexdef_Component_Selected(GlobalSceneGraph(), projection) -which is in brushmanip.h: This eventually calls -Texdef_Assign(m_texdef, texdef, m_brushprimit_texdef, brushprimit_texdef) in class Face... -which just copies from brushpr to m_brushpr... -*/ - -//Small problem with this thing: It's scaled to the texture which is all screwed up... !!! FIX !!! [DONE] -//Prolly should separate out the grid drawing so that we can draw it behind the polygon. -const float gridWidth = 1.3f;// Let's try an absolute height... WORKS!!! -// NOTE that 2.0 is the height of the viewport. Dunno why... Should make collision -// detection easier... -const float gridRadius = gridWidth * 0.5f; - -typedef const float WidgetColor[3]; -const WidgetColor widgetColor[10] = { - { 1.0000f, 0.2000f, 0.0000f }, // Red - { 0.9137f, 0.9765f, 0.4980f }, // Yellow - { 0.0000f, 0.6000f, 0.3216f }, // Green - { 0.6157f, 0.7726f, 0.8196f }, // Cyan - { 0.4980f, 0.5000f, 0.4716f }, // Grey - - // Highlight colors - { 1.0000f, 0.6000f, 0.4000f }, // Light Red - { 1.0000f, 1.0000f, 0.8980f }, // Light Yellow - { 0.4000f, 1.0000f, 0.7216f }, // Light Green - { 1.0000f, 1.0000f, 1.0000f }, // Light Cyan - { 0.8980f, 0.9000f, 0.8716f } // Light Grey -}; - -#define COLOR_RED 0 -#define COLOR_YELLOW 1 -#define COLOR_GREEN 2 -#define COLOR_CYAN 3 -#define COLOR_GREY 4 -#define COLOR_LT_RED 5 -#define COLOR_LT_YELLOW 6 -#define COLOR_LT_GREEN 7 -#define COLOR_LT_CYAN 8 -#define COLOR_LT_GREY 9 - -void DrawControlWidgets(void) -{ -//Note that the grid should go *behind* the face outline... !!! FIX !!! - // Grid - float xStart = center.x() - (gridWidth / 2.0f); - float yStart = center.y() - (gridWidth / 2.0f); - float xScale = (extents.height() / extents.width()) * (textureSize.y() / textureSize.x()); - - glPushMatrix(); -//Small problem with this approach: Changing the center point in the TX code doesn't seem to -//change anything here--prolly because we load a new identity matrix. A couple of ways to fix -//this would be to get rid of that code, or change the center to a new point by taking into -//account the transforms that we toss with the new identity matrix. Dunno which is better. - glLoadIdentity(); - glScalef(xScale, 1.0, 1.0); // Will that square it up? Yup. - glRotatef(static_cast(radians_to_degrees(atan2(-currentBP.coords[0][1], currentBP.coords[0][0]))), 0.0, 0.0, -1.0); - glTranslatef(-center.x(), -center.y(), 0.0); - - // Circle - glColor3fv(translatingX && translatingY ? widgetColor[COLOR_LT_YELLOW] : widgetColor[COLOR_YELLOW]); - glBegin(GL_LINE_LOOP); - DrawCircularArc(center, 0, 2.0f * PI, gridRadius * 0.16); - - glEnd(); - - // Axes - glBegin(GL_LINES); - glColor3fv(translatingY && !translatingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN]); - glVertex2f(center.x(), center.y() + (gridRadius * 0.16)); - glVertex2f(center.x(), center.y() + (gridRadius * 1.00)); - glColor3fv(translatingX && !translatingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED]); - glVertex2f(center.x() + (gridRadius * 0.16), center.y()); - glVertex2f(center.x() + (gridRadius * 1.00), center.y()); - glEnd(); - - // Arrowheads - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - glBegin(GL_TRIANGLES); - glColor3fv(translatingY && !translatingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN]); - glVertex2f(center.x(), center.y() + (gridRadius * 1.10)); - glVertex2f(center.x() + (gridRadius * 0.06), center.y() + (gridRadius * 0.94)); - glVertex2f(center.x() - (gridRadius * 0.06), center.y() + (gridRadius * 0.94)); - glColor3fv(translatingX && !translatingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED]); - glVertex2f(center.x() + (gridRadius * 1.10), center.y()); - glVertex2f(center.x() + (gridRadius * 0.94), center.y() + (gridRadius * 0.06)); - glVertex2f(center.x() + (gridRadius * 0.94), center.y() - (gridRadius * 0.06)); - glEnd(); - - // Arc - glBegin(GL_LINE_STRIP); - glColor3fv(rotating ? widgetColor[COLOR_LT_CYAN] : widgetColor[COLOR_CYAN]); - DrawCircularArc(center, 0.03f * PI, 0.47f * PI, gridRadius * 0.90); - glEnd(); - - // Boxes - glColor3fv(scalingY && !scalingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN]); - glBegin(GL_LINES); - glVertex2f(center.x() + (gridRadius * 0.20), center.y() + (gridRadius * 1.50)); - glVertex2f(center.x() - (gridRadius * 0.20), center.y() + (gridRadius * 1.50)); - glEnd(); - glBegin(GL_LINE_LOOP); - glVertex2f(center.x() + (gridRadius * 0.10), center.y() + (gridRadius * 1.40)); - glVertex2f(center.x() - (gridRadius * 0.10), center.y() + (gridRadius * 1.40)); - glVertex2f(center.x() - (gridRadius * 0.10), center.y() + (gridRadius * 1.20)); - glVertex2f(center.x() + (gridRadius * 0.10), center.y() + (gridRadius * 1.20)); - glEnd(); - - glColor3fv(scalingX && !scalingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED]); - glBegin(GL_LINES); - glVertex2f(center.x() + (gridRadius * 1.50), center.y() + (gridRadius * 0.20)); - glVertex2f(center.x() + (gridRadius * 1.50), center.y() - (gridRadius * 0.20)); - glEnd(); - glBegin(GL_LINE_LOOP); - glVertex2f(center.x() + (gridRadius * 1.40), center.y() + (gridRadius * 0.10)); - glVertex2f(center.x() + (gridRadius * 1.40), center.y() - (gridRadius * 0.10)); - glVertex2f(center.x() + (gridRadius * 1.20), center.y() - (gridRadius * 0.10)); - glVertex2f(center.x() + (gridRadius * 1.20), center.y() + (gridRadius * 0.10)); - glEnd(); - - glColor3fv(scalingX && scalingY ? widgetColor[COLOR_LT_CYAN] : widgetColor[COLOR_CYAN]); - glBegin(GL_LINE_STRIP); - glVertex2f(center.x() + (gridRadius * 1.50), center.y() + (gridRadius * 1.10)); - glVertex2f(center.x() + (gridRadius * 1.50), center.y() + (gridRadius * 1.50)); - glVertex2f(center.x() + (gridRadius * 1.10), center.y() + (gridRadius * 1.50)); - glEnd(); - glBegin(GL_LINE_LOOP); - glVertex2f(center.x() + (gridRadius * 1.40), center.y() + (gridRadius * 1.40)); - glVertex2f(center.x() + (gridRadius * 1.40), center.y() + (gridRadius * 1.20)); - glVertex2f(center.x() + (gridRadius * 1.20), center.y() + (gridRadius * 1.20)); - glVertex2f(center.x() + (gridRadius * 1.20), center.y() + (gridRadius * 1.40)); - glEnd(); - - glPopMatrix(); -} - -void DrawControlPoints(void) -{ - glColor3f(1, 1, 1); - glBegin(GL_LINE_LOOP); - - for(int i=0; i extents.maxX) - extents.maxX = pts[i].x(); - if (pts[i].y() < extents.minY) - extents.minY = pts[i].y(); - if (pts[i].y() > extents.maxY) - extents.maxY = pts[i].y(); - } - - // Do some viewport fitting stuff... - -//globalOutputStream() << "--> Center: " << center.x() << ", " << center.y() << "\n"; -//globalOutputStream() << "--> Extents (stage 1): " << extents.minX << ", " -// << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; - // TTimo: Apply a ratio to get the area we'll draw. - center.x() = 0.5f * (extents.minX + extents.maxX), - center.y() = 0.5f * (extents.minY + extents.maxY); - extents.minX = center.x() + VP_PADDING * (extents.minX - center.x()), - extents.minY = center.y() + VP_PADDING * (extents.minY - center.y()), - extents.maxX = center.x() + VP_PADDING * (extents.maxX - center.x()), - extents.maxY = center.y() + VP_PADDING * (extents.maxY - center.y()); -//globalOutputStream() << "--> Extents (stage 2): " << extents.minX << ", " -// << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; - - // TTimo: We want a texture with the same X / Y ratio. - // TTimo: Compute XY space / window size ratio. - float SSize = extents.width(), TSize = extents.height(); - float ratioX = textureSize.x() * extents.width() / windowSize.x(), - ratioY = textureSize.y() * extents.height() / windowSize.y(); -//globalOutputStream() << "--> Texture size: " << textureSize.x() << ", " << textureSize.y() << "\n"; -//globalOutputStream() << "--> Window size: " << windowSize.x() << ", " << windowSize.y() << "\n"; - - if (ratioX > ratioY) - { - TSize = (windowSize.y() * ratioX) / textureSize.y(); -// TSize = extents.width() * (windowSize.y() / windowSize.x()) * (textureSize.x() / textureSize.y()); - } - else - { - SSize = (windowSize.x() * ratioY) / textureSize.x(); -// SSize = extents.height() * (windowSize.x() / windowSize.y()) * (textureSize.y() / textureSize.x()); - } - - extents.minX = center.x() - 0.5f * SSize, extents.maxX = center.x() + 0.5f * SSize, - extents.minY = center.y() - 0.5f * TSize, extents.maxY = center.y() + 0.5f * TSize; -//globalOutputStream() << "--> Extents (stage 3): " << extents.minX << ", " -// << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; -} - -gboolean size_allocate(GtkWidget * win, GtkAllocation * a, gpointer) -{ - windowSize.x() = a->width; - windowSize.y() = a->height; - queueDraw(); - return false; -} - -gboolean expose(GtkWidget * win, GdkEventExpose * e, gpointer) -{ -// globalOutputStream() << "--> Textool Window was exposed!\n"; -// globalOutputStream() << " (window width/height: " << cc << "/" << e->area.height << ")\n"; - -// windowSize.x() = e->area.width, windowSize.y() = e->area.height; -//This needs to go elsewhere... -// InitTextool(); - - if (glwidget_make_current(win) == FALSE) - { - globalOutputStream() << " FAILED to make current! Oh, the agony! :-(\n"; - return true; - } - - CopyPointsFromSelectedFace(); - - if(!lButtonDown) - { - focus(); - } - - // Probably should init button/anchor states here as well... -// rotationAngle = 0.0f; - glClearColor(0, 0, 0, 0); - glViewport(0, 0, e->area.width, e->area.height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - -//??? - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glDisable(GL_DEPTH_TEST); - glDisable(GL_BLEND); - - glOrtho(extents.minX, extents.maxX, extents.maxY, extents.minY, -1, 1); - - glColor3f(1, 1, 1); - // draw the texture background - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - glBindTexture(GL_TEXTURE_2D, textureNum); - - glEnable(GL_TEXTURE_2D); - glBegin(GL_QUADS); - glTexCoord2f(extents.minX, extents.minY); - glVertex2f(extents.minX, extents.minY); - glTexCoord2f(extents.maxX, extents.minY); - glVertex2f(extents.maxX, extents.minY); - glTexCoord2f(extents.maxX, extents.maxY); - glVertex2f(extents.maxX, extents.maxY); - glTexCoord2f(extents.minX, extents.maxY); - glVertex2f(extents.minX, extents.maxY); - glEnd(); - glDisable(GL_TEXTURE_2D); - - // draw the texture-space grid - glColor3fv(widgetColor[COLOR_GREY]); - glBegin(GL_LINES); - - const int gridSubdivisions = 8; - const float gridExtents = 4.0f; - - for(int i = 0; i < gridSubdivisions + 1; ++i) - { - float y = i * (gridExtents / float(gridSubdivisions)); - float x = i * (gridExtents / float(gridSubdivisions)); - glVertex2f(0, y); - glVertex2f(gridExtents, y); - glVertex2f(x, 0); - glVertex2f(x, gridExtents); - } - - glEnd(); - - DrawControlPoints(); - DrawControlWidgets(); -//??? - // reset the current texture -// glBindTexture(GL_TEXTURE_2D, 0); -// glFinish(); - glwidget_swap_buffers(win); - - return false; -} - -/*int FindSelectedPoint(int x, int y) -{ - for(int i=0; i Textool button press...\n"; - - if (e->button == 1) - { - lButtonDown = true; - GlobalUndoSystem().start(); - - origBP = currentBP; - - //globalOutputStream() << "--> Original BP: [" << origBP.coords[0][0] << "][" << origBP.coords[0][1] << "][" << origBP.coords[0][2] << "]\n"; - //globalOutputStream() << " [" << origBP.coords[1][0] << "][" << origBP.coords[1][1] << "][" << origBP.coords[1][2] << "]\n"; - //float angle = atan2(origBP.coords[0][1], origBP.coords[0][0]) * 180.0f / 3.141592653589f; - origAngle = (origBP.coords[0][1] > 0 ? PI : -PI); // Could also be -PI... !!! FIX !!! [DONE] - - if (origBP.coords[0][0] != 0.0f) - origAngle = atan(origBP.coords[0][1] / origBP.coords[0][0]); - - origScaleX = origBP.coords[0][0] / cos(origAngle); - origScaleY = origBP.coords[1][1] / cos(origAngle); - rotationAngle = origAngle; - oldCenter[0] = oldCenter[1] = 0; - - //globalOutputStream() << "--> BP stats: ang=" << origAngle * RAD_TO_DEG << ", scale=" << origScaleX << "/" << origScaleY << "\n"; - //Should also set the Flip X/Y checkboxes here as well... !!! FIX !!! - //Also: should reverse texture left/right up/down instead of flipping the points... - -//disnowok -//float nx = windowSize.x() * (e->x - extents.minX) / (extents.maxX - extents.minX); -//float ny = windowSize.y() * (e->y - extents.minY) / (extents.maxY - extents.minY); -//disdoes... -//But I want it to scroll the texture window, not the points... !!! FIX !!! -//Actually, should scroll the texture window only when mouse is down on no widgets... - float nx = e->x / windowSize.x() * extents.width() + extents.minX; - float ny = e->y / windowSize.y() * extents.height() + extents.minY; - trans.x() = -tm.coords[0][0] * nx - tm.coords[0][1] * ny; - trans.y() = -tm.coords[1][0] * nx - tm.coords[1][1] * ny; - - dragPoint.x() = e->x, dragPoint.y() = e->y; - trans2.x() = nx, trans2.y() = ny; - oldRotationAngle = rotationAngle; -// oldTrans.x() = tm.coords[0][2] - nx * textureSize.x(); -// oldTrans.y() = tm.coords[1][2] - ny * textureSize.y(); - oldTrans.x() = tm.coords[0][2]; - oldTrans.y() = tm.coords[1][2]; - oldCenter.x() = center.x(); - oldCenter.y() = center.y(); - - queueDraw(); - - return true; - } -/* else if (e->button == 3) - { - rButtonDown = true; - }//*/ - -//globalOutputStream() << "(" << (haveAnchor ? "anchor" : "released") << ")\n"; - - return false; -} - -gboolean button_release(GtkWidget * win, GdkEventButton * e, gpointer) -{ -// globalOutputStream() << "--> Textool button release...\n"; - - if (e->button == 1) - { -/* float ptx = e->x / windowSize.x() * extents.width() + extents.minX; - float pty = e->y / windowSize.y() * extents.height() + extents.minY; - -//This prolly should go into the mouse move code... -//Doesn't work correctly anyway... - if (translatingX || translatingY) - center.x() = ptx, center.y() = pty;//*/ - - lButtonDown = false; - - if(translatingX || translatingY) - { - GlobalUndoSystem().finish("translateTexture"); - } - else if(rotating) - { - GlobalUndoSystem().finish("rotateTexture"); - } - else if(scalingX || scalingY) - { - GlobalUndoSystem().finish("scaleTexture"); - } - else if(resizingX || resizingY) - { - GlobalUndoSystem().finish("resizeTexture"); - } - else - { - GlobalUndoSystem().finish("textoolUnknown"); - } - - rotating = translatingX = translatingY = scalingX = scalingY - = resizingX = resizingY = false; - - queueDraw(); - } - else if (e->button == 3) - { - rButtonDown = false; - } - - return true; -} - -/* -void C2DView::GridForWindow( float c[2], int x, int y) -{ - SpaceForWindow( c, x, y ); - if ( !m_bDoGrid ) - return; - c[0] /= m_GridStep[0]; - c[1] /= m_GridStep[1]; - c[0] = (float)floor( c[0] + 0.5f ); - c[1] = (float)floor( c[1] + 0.5f ); - c[0] *= m_GridStep[0]; - c[1] *= m_GridStep[1]; -} -void C2DView::SpaceForWindow( float c[2], int x, int y) -{ - c[0] = ((float)(x))/((float)(m_rect.right-m_rect.left))*(m_Maxs[0]-m_Mins[0])+m_Mins[0]; - c[1] = ((float)(y))/((float)(m_rect.bottom-m_rect.top))*(m_Maxs[1]-m_Mins[1])+m_Mins[1]; -} -*/ -gboolean motion(GtkWidget * win, GdkEventMotion * e, gpointer) -{ -// globalOutputStream() << "--> Textool motion...\n"; - - if (lButtonDown) - { - if (translatingX || translatingY) - { - float ptx = e->x / windowSize.x() * extents.width() + extents.minX; - float pty = e->y / windowSize.y() * extents.height() + extents.minY; - -//Need to fix this to take the rotation angle into account, so that it moves along -//the rotated X/Y axis... - if (translatingX) - { -// tm.coords[0][2] = (trans.x() + ptx) * textureSize.x(); -//This works, but only when the angle is zero. !!! FIX !!! [DONE] -// tm.coords[0][2] = oldCenter.x() + (ptx * textureSize.x()); - tm.coords[0][2] = oldTrans.x() + (ptx - trans2.x()) * textureSize.x(); -// center.x() = oldCenter.x() + (ptx - trans2.x()); - } - - if (translatingY) - { -// tm.coords[1][2] = (trans.y() + pty) * textureSize.y(); -// tm.coords[1][2] = oldCenter.y() + (pty * textureSize.y()); - tm.coords[1][2] = oldTrans.y() + (pty - trans2.y()) * textureSize.y(); -// center.y() = oldCenter.y() + (pty - trans2.y()); - } - -//Need to update center.x/y() so that the widget translates as well. Also, oldCenter -//is badly named... Should be oldTrans or something like that... !!! FIX !!! -//Changing center.x/y() here doesn't seem to change anything... :-/ - UpdateControlPoints(); - } - else if (rotating) - { - // Shamus: New rotate code - int cx = (int)(windowSize.x() * (center.x() - extents.minX) / extents.width()); - int cy = (int)(windowSize.y() * (center.y() - extents.minY) / extents.height()); - Vector3 v1(dragPoint.x() - cx, dragPoint.y() - cy, 0), v2(e->x - cx, e->y - cy, 0); - - vector3_normalise(v1); - vector3_normalise(v2); - float c = vector3_dot(v1, v2); - Vector3 cross = vector3_cross(v1, v2); - float s = vector3_length(cross); - - if (cross[2] > 0) - s = -s; - -// Problem with this: arcsin/cos seems to only return -90 to 90 and 0 to 180... -// Can't derive angle from that! - -//rotationAngle = asin(s);// * 180.0f / 3.141592653589f; -rotationAngle = acos(c); -//rotationAngle2 = asin(s); -if (cross[2] < 0) - rotationAngle = -rotationAngle; - -//NO! DOESN'T WORK! rotationAngle -= 45.0f * DEG_TO_RAD; -//Let's try this: -//No wok. -/*c = cos(rotationAngle - oldRotationAngle); -s = sin(rotationAngle - oldRotationAngle); -rotationAngle += oldRotationAngle; -//c += cos(oldRotationAngle); -//s += sin(oldRotationAngle); -//rotationAngle += oldRotationAngle; -//c %= 2.0 * PI; -//s %= 2.0 * PI; -//rotationAngle %= 2.0 * PI;//*/ - -//This is wrong... Hmm... -//It seems to shear the texture instead of rotating it... !!! FIX !!! -// Now it rotates correctly. Seems TTimo was overcomplicating things here... ;-) - -// Seems like what needs to happen here is multiplying these rotations by tm... !!! FIX !!! - -// See brush_primit.cpp line 244 (Texdef_EmitTextureCoordinates()) for where texcoords come from... - - tm.coords[0][0] = c; - tm.coords[0][1] = s; - tm.coords[1][0] = -s; - tm.coords[1][1] = c; -//It doesn't work anymore... Dunno why... -//tm.coords[0][2] = -trans.x(); // This works!!! Yeah!!! -//tm.coords[1][2] = -trans.y(); -//nope. -//tm.coords[0][2] = rotationPoint.x(); // This works, but strangely... -//tm.coords[1][2] = rotationPoint.y(); -//tm.coords[0][2] = 0;// center.x() / 2.0f; -//tm.coords[1][2] = 0;// center.y() / 2.0f; -//No. -//tm.coords[0][2] = -(center.x() * textureSize.x()); -//tm.coords[1][2] = -(center.y() * textureSize.y()); -//Eh? No, but seems to be getting closer... -/*float ptx = e->x / windowSize.x() * extents.width() + extents.minX; -float pty = e->y / windowSize.y() * extents.height() + extents.minY; -tm.coords[0][2] = -c * center.x() - s * center.y() + ptx; -tm.coords[1][2] = s * center.x() - c * center.x() + pty;//*/ -//Kinda works, but center drifts around on non-square textures... -/*tm.coords[0][2] = (-c * center.x() - s * center.y()) * textureSize.x(); -tm.coords[1][2] = ( s * center.x() - c * center.y()) * textureSize.y();//*/ -//Rotates correctly, but not around the actual center of the face's points... -/*tm.coords[0][2] = -c * center.x() * textureSize.x() - s * center.y() * textureSize.y(); -tm.coords[1][2] = s * center.x() * textureSize.x() - c * center.y() * textureSize.y();//*/ -//Yes!!! - tm.coords[0][2] = (-c * center.x() * textureSize.x() - s * center.y() * textureSize.y()) + center.x() * textureSize.x(); - tm.coords[1][2] = ( s * center.x() * textureSize.x() - c * center.y() * textureSize.y()) + center.y() * textureSize.y();//*/ -//This doesn't work... -//And this is the wrong place for this anyway (I'm pretty sure). -/*tm.coords[0][2] += oldCenter.x(); -tm.coords[1][2] += oldCenter.y();//*/ - UpdateControlPoints(); // will cause a redraw - } - - return true; - } - else // Check for widget mouseovers - { - Vector2 tran; - float nx = e->x / windowSize.x() * extents.width() + extents.minX; - float ny = e->y / windowSize.y() * extents.height() + extents.minY; - // Translate nx/y to the "center" point... - nx -= center.x(); - ny -= center.y(); - ny = -ny; // Flip Y-axis so that increasing numbers move up - - tran.x() = tm.coords[0][0] * nx + tm.coords[0][1] * ny; - tran.y() = tm.coords[1][0] * nx + tm.coords[1][1] * ny; -//This doesn't seem to generate a valid distance from the center--for some reason it -//calculates a fixed number every time -//Look at nx/y above: they're getting fixed there! !!! FIX !!! [DONE] - float dist = sqrt((nx * nx) + (ny * ny)); - // Normalize to the 2.0 = height standard (for now) -//globalOutputStream() << "--> Distance before: " << dist; - dist = dist * 2.0f / extents.height(); -//globalOutputStream() << ". After: " << dist; - tran.x() = tran.x() * 2.0f / extents.height(); - tran.y() = tran.y() * 2.0f / extents.height(); -//globalOutputStream() << ". Trans: " << tran.x() << ", " << tran.y() << "\n"; - -//Let's try this instead... -//Interesting! It seems that e->x/y are rotated -//(no, they're not--the TM above is what's doing it...) -nx = ((e->x / windowSize.y()) * 2.0f) - (windowSize.x() / windowSize.y()); -ny = ((e->y / windowSize.y()) * 2.0f) - (windowSize.y() / windowSize.y()); -ny = -ny; -//Cool! It works! Now just need to do rotation... - - rotating = translatingX = translatingY = scalingX = scalingY - = resizingX = resizingY = false; - - if (dist < (gridRadius * 0.16f)) - { - translatingX = translatingY = true; - } - else if (dist > (gridRadius * 0.16f) && dist < (gridRadius * 1.10f) - && fabs(ny) < (gridRadius * 0.05f) && nx > 0) - { - translatingX = true; - } - else if (dist > (gridRadius * 0.16f) && dist < (gridRadius * 1.10f) - && fabs(nx) < (gridRadius * 0.05f) && ny > 0) - { - translatingY = true; - } - // Should tighten up the angle on this, or put this test after the axis tests... - else if (tran.x() > 0 && tran.y() > 0 - && (dist > (gridRadius * 0.82f) && dist < (gridRadius * 0.98f))) - { - rotating = true; - } - - queueDraw(); - - return true; - } - - return false; -} - -//It seems the fake tex coords conversion is screwing this stuff up... !!! FIX !!! -//This is still wrong... Prolly need to do something with the oldScaleX/Y stuff... -void flipX(GtkToggleButton *, gpointer) -{ -// globalOutputStream() << "--> Flip X...\n"; - //Shamus: -// SurfaceInspector_GetSelectedBPTexdef(); // Refresh g_selectedBrushPrimitTexdef... -// tm.coords[0][0] = -tm.coords[0][0]; -// tm.coords[1][0] = -tm.coords[1][0]; -// tm.coords[0][0] = -tm.coords[0][0]; // This should be correct now...Nope. -// tm.coords[1][1] = -tm.coords[1][1]; - tm.coords[0][0] = -tm.coords[0][0]; // This should be correct now... - tm.coords[1][0] = -tm.coords[1][0]; -// tm.coords[2][0] = -tm.coords[2][0];//wil wok? no. - UpdateControlPoints(); -} - -void flipY(GtkToggleButton *, gpointer) -{ -// globalOutputStream() << "--> Flip Y...\n"; -// tm.coords[0][1] = -tm.coords[0][1]; -// tm.coords[1][1] = -tm.coords[1][1]; -// tm.coords[0][1] = -tm.coords[0][1]; // This should be correct now...Nope. -// tm.coords[1][0] = -tm.coords[1][0]; - tm.coords[0][1] = -tm.coords[0][1]; // This should be correct now... - tm.coords[1][1] = -tm.coords[1][1]; -// tm.coords[2][1] = -tm.coords[2][1];//wil wok? no. - UpdateControlPoints(); -} - -} // end namespace TexTool - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/surfacedialog.h b/misc/mediasource/extra/netradiant-src/radiant/surfacedialog.h deleted file mode 100644 index 034cf1d6..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/surfacedialog.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_SURFACEDIALOG_H) -#define INCLUDED_SURFACEDIALOG_H - - -void SurfaceInspector_Construct(); -void SurfaceInspector_Destroy(); - -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; -void SurfaceInspector_constructWindow(GtkWindow* widget); -void SurfaceInspector_destroyWindow(); - -bool SelectedFaces_empty(); -void SelectedFaces_copyTexture(); -void SelectedFaces_pasteTexture(); -void FaceTextureClipboard_setDefault(); - - -// the increment we are using for the surface inspector (this is saved in the prefs) -struct si_globals_t -{ - float shift[2]; - float scale[2]; - float rotate; - - bool m_bSnapTToGrid; - - si_globals_t() : m_bSnapTToGrid(false) - { - shift[0] = 8.0f; - shift[1] = 8.0f; - scale[0] = 0.5f; - scale[1] = 0.5f; - rotate = 45.0f; - } -}; -extern si_globals_t g_si_globals; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/texmanip.cpp b/misc/mediasource/extra/netradiant-src/radiant/texmanip.cpp deleted file mode 100644 index 8fa88ca2..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/texmanip.cpp +++ /dev/null @@ -1,388 +0,0 @@ -/* -Copyright (c) 2002 Forest "LordHavoc" Hale - -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 Forest Hale nor the names of other 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. -*/ - -#include "texmanip.h" - -#include -#include "stream/textstream.h" - -static byte *row1 = NULL, *row2 = NULL; -static int rowsize = 0; - -void R_ResampleTextureLerpLine (const byte *in, byte *out, int inwidth, int outwidth, int bytesperpixel) -{ - int j, xi, oldx = 0, f, fstep, endx, lerp; -#define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i]) - - fstep = (int) (inwidth * 65536.0f / outwidth); - endx = (inwidth - 1); - if (bytesperpixel == 4) - { - for (j = 0,f = 0;j < outwidth;j++, f += fstep) - { - xi = f >> 16; - if (xi != oldx) - { - in += (xi - oldx) * 4; - oldx = xi; - } - - if (xi < endx) - { - lerp = f & 0xFFFF; - *out++ = (byte) ((((in[4] - in[0]) * lerp) >> 16) + in[0]); - *out++ = (byte) ((((in[5] - in[1]) * lerp) >> 16) + in[1]); - *out++ = (byte) ((((in[6] - in[2]) * lerp) >> 16) + in[2]); - *out++ = (byte) ((((in[7] - in[3]) * lerp) >> 16) + in[3]); - } - else // last pixel of the line has no pixel to lerp to - { - *out++ = in[0]; - *out++ = in[1]; - *out++ = in[2]; - *out++ = in[3]; - } - } - } - else if (bytesperpixel == 3) - { - for (j = 0, f = 0; j < outwidth; j++, f += fstep) - { - xi = f >> 16; - if (xi != oldx) - { - in += (xi - oldx) * 3; - oldx = xi; - } - - if (xi < endx) - { - lerp = f & 0xFFFF; - *out++ = (byte) ((((in[3] - in[0]) * lerp) >> 16) + in[0]); - *out++ = (byte) ((((in[4] - in[1]) * lerp) >> 16) + in[1]); - *out++ = (byte) ((((in[5] - in[2]) * lerp) >> 16) + in[2]); - } - else // last pixel of the line has no pixel to lerp to - { - *out++ = in[0]; - *out++ = in[1]; - *out++ = in[2]; - } - } - } - else - { - globalOutputStream() << "R_ResampleTextureLerpLine: unsupported bytesperpixel " << bytesperpixel << "\n"; - } -} - -/* -================ -R_ResampleTexture -================ -*/ -void R_ResampleTexture (const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight, int bytesperpixel) -{ - if (rowsize < outwidth * bytesperpixel) - { - if (row1) - free(row1); - if (row2) - free(row2); - - rowsize = outwidth * bytesperpixel; - row1 = (byte *)malloc(rowsize); - row2 = (byte *)malloc(rowsize); - } - - if (bytesperpixel == 4) - { - int i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4; - byte *inrow, *out; - out = (byte *)outdata; - fstep = (int) (inheight * 65536.0f / outheight); -#define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i]) - - inrow = (byte *)indata; - oldy = 0; - R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); - R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel); - - for (i = 0, f = 0;i < outheight;i++,f += fstep) - { - yi = f >> 16; - if (yi < endy) - { - lerp = f & 0xFFFF; - if (yi != oldy) - { - inrow = (byte *)indata + inwidth4 * yi; - if (yi == oldy+1) - memcpy(row1, row2, outwidth4); - else - R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); - - R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel); - oldy = yi; - } - j = outwidth - 4; - while(j >= 0) - { - LERPBYTE( 0); - LERPBYTE( 1); - LERPBYTE( 2); - LERPBYTE( 3); - LERPBYTE( 4); - LERPBYTE( 5); - LERPBYTE( 6); - LERPBYTE( 7); - LERPBYTE( 8); - LERPBYTE( 9); - LERPBYTE(10); - LERPBYTE(11); - LERPBYTE(12); - LERPBYTE(13); - LERPBYTE(14); - LERPBYTE(15); - out += 16; - row1 += 16; - row2 += 16; - j -= 4; - } - if (j & 2) - { - LERPBYTE( 0); - LERPBYTE( 1); - LERPBYTE( 2); - LERPBYTE( 3); - LERPBYTE( 4); - LERPBYTE( 5); - LERPBYTE( 6); - LERPBYTE( 7); - out += 8; - row1 += 8; - row2 += 8; - } - if (j & 1) - { - LERPBYTE( 0); - LERPBYTE( 1); - LERPBYTE( 2); - LERPBYTE( 3); - out += 4; - row1 += 4; - row2 += 4; - } - row1 -= outwidth4; - row2 -= outwidth4; - } - else - { - if (yi != oldy) - { - inrow = (byte *)indata + inwidth4*yi; - if (yi == oldy+1) - memcpy(row1, row2, outwidth4); - else - R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); - - oldy = yi; - } - memcpy(out, row1, outwidth4); - } - } - } - else if (bytesperpixel == 3) - { - int i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth3 = inwidth * 3, outwidth3 = outwidth * 3; - byte *inrow, *out; - out = (byte *)outdata; - fstep = (int) (inheight*65536.0f/outheight); -#define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i]) - - inrow = (byte *)indata; - oldy = 0; - R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); - R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel); - for (i = 0, f = 0;i < outheight;i++,f += fstep) - { - yi = f >> 16; - if (yi < endy) - { - lerp = f & 0xFFFF; - if (yi != oldy) - { - inrow = (byte *)indata + inwidth3*yi; - if (yi == oldy+1) - memcpy(row1, row2, outwidth3); - else - R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); - - R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel); - oldy = yi; - } - j = outwidth - 4; - while(j >= 0) - { - LERPBYTE( 0); - LERPBYTE( 1); - LERPBYTE( 2); - LERPBYTE( 3); - LERPBYTE( 4); - LERPBYTE( 5); - LERPBYTE( 6); - LERPBYTE( 7); - LERPBYTE( 8); - LERPBYTE( 9); - LERPBYTE(10); - LERPBYTE(11); - out += 12; - row1 += 12; - row2 += 12; - j -= 4; - } - if (j & 2) - { - LERPBYTE( 0); - LERPBYTE( 1); - LERPBYTE( 2); - LERPBYTE( 3); - LERPBYTE( 4); - LERPBYTE( 5); - out += 6; - row1 += 6; - row2 += 6; - } - if (j & 1) - { - LERPBYTE( 0); - LERPBYTE( 1); - LERPBYTE( 2); - out += 3; - row1 += 3; - row2 += 3; - } - row1 -= outwidth3; - row2 -= outwidth3; - } - else - { - if (yi != oldy) - { - inrow = (byte *)indata + inwidth3*yi; - if (yi == oldy+1) - memcpy(row1, row2, outwidth3); - else - R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); - - oldy = yi; - } - memcpy(out, row1, outwidth3); - } - } - } - else - { - globalOutputStream() << "R_ResampleTexture: unsupported bytesperpixel " << bytesperpixel << "\n"; - } -} - -// in can be the same as out -void GL_MipReduce(byte *in, byte *out, int width, int height, int destwidth, int destheight) -{ - int x, y, width2, height2, nextrow; - if (width > destwidth) - { - if (height > destheight) - { - // reduce both - width2 = width >> 1; - height2 = height >> 1; - nextrow = width << 2; - for (y = 0;y < height2;y++) - { - for (x = 0;x < width2;x++) - { - out[0] = (byte) ((in[0] + in[4] + in[nextrow ] + in[nextrow+4]) >> 2); - out[1] = (byte) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2); - out[2] = (byte) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2); - out[3] = (byte) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2); - out += 4; - in += 8; - } - in += nextrow; // skip a line - } - } - else - { - // reduce width - width2 = width >> 1; - for (y = 0;y < height;y++) - { - for (x = 0;x < width2;x++) - { - out[0] = (byte) ((in[0] + in[4]) >> 1); - out[1] = (byte) ((in[1] + in[5]) >> 1); - out[2] = (byte) ((in[2] + in[6]) >> 1); - out[3] = (byte) ((in[3] + in[7]) >> 1); - out += 4; - in += 8; - } - } - } - } - else - { - if (height > destheight) - { - // reduce height - height2 = height >> 1; - nextrow = width << 2; - for (y = 0;y < height2;y++) - { - for (x = 0;x < width;x++) - { - out[0] = (byte) ((in[0] + in[nextrow ]) >> 1); - out[1] = (byte) ((in[1] + in[nextrow+1]) >> 1); - out[2] = (byte) ((in[2] + in[nextrow+2]) >> 1); - out[3] = (byte) ((in[3] + in[nextrow+3]) >> 1); - out += 4; - in += 4; - } - in += nextrow; // skip a line - } - } - else - { - globalOutputStream() << "GL_MipReduce: desired size already achieved\n"; - } - } -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/texmanip.h b/misc/mediasource/extra/netradiant-src/radiant/texmanip.h deleted file mode 100644 index 3cca3ce2..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/texmanip.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -Copyright (c) 2002 Forest "LordHavoc" Hale - -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 Forest Hale nor the names of other 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. -*/ - -#if !defined(INCLUDED_TEXMANIP_H) -#define INCLUDED_TEXMANIP_H - -typedef unsigned char byte; - -void R_ResampleTexture (const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight, int bytesperpixel); -void GL_MipReduce(byte *in, byte *out, int width, int height, int destwidth, int destheight); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/textureentry.cpp b/misc/mediasource/extra/netradiant-src/radiant/textureentry.cpp deleted file mode 100644 index 615143c1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/textureentry.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "textureentry.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/textureentry.h b/misc/mediasource/extra/netradiant-src/radiant/textureentry.h deleted file mode 100644 index 3965fe29..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/textureentry.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_TEXTUREENTRY_H) -#define INCLUDED_TEXTUREENTRY_H - - -#include -#include -#include "gtkutil/idledraw.h" - -#include "generic/static.h" -#include "signal/isignal.h" -#include "shaderlib.h" - -#include "texwindow.h" - -template -class EntryCompletion -{ - GtkListStore* m_store; - IdleDraw m_idleUpdate; -public: - EntryCompletion() : m_store(0), m_idleUpdate(UpdateCaller(*this)) - { - } - - void connect(GtkEntry* entry) - { - if(m_store == 0) - { - m_store = gtk_list_store_new(1, G_TYPE_STRING); - - fill(); - - StringList().connect(IdleDraw::QueueDrawCaller(m_idleUpdate)); - } - - GtkEntryCompletion* completion = gtk_entry_completion_new(); - gtk_entry_set_completion(entry, completion); - gtk_entry_completion_set_model(completion, GTK_TREE_MODEL(m_store)); - gtk_entry_completion_set_text_column(completion, 0); - } - - void append(const char* string) - { - GtkTreeIter iter; - gtk_list_store_append(m_store, &iter); - gtk_list_store_set(m_store, &iter, 0, string, -1); - } - typedef MemberCaller1 AppendCaller; - - void fill() - { - StringList().forEach(AppendCaller(*this)); - } - - void clear() - { - gtk_list_store_clear(m_store); - } - - void update() - { - clear(); - fill(); - } - typedef MemberCaller UpdateCaller; -}; - -class TextureNameList -{ -public: - void forEach(const ShaderNameCallback& callback) const - { - for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) - { - IShader *shader = QERApp_ActiveShaders_IteratorCurrent(); - - if(shader_equal_prefix(shader->getName(), "textures/")) - { - callback(shader->getName() + 9); - } - } - } - void connect(const SignalHandler& update) const - { - TextureBrowser_addActiveShadersChangedCallback(update); - } -}; - -typedef Static< EntryCompletion > GlobalTextureEntryCompletion; - - -class ShaderList -{ -public: - void forEach(const ShaderNameCallback& callback) const - { - GlobalShaderSystem().foreachShaderName(callback); - } - void connect(const SignalHandler& update) const - { - TextureBrowser_addShadersRealiseCallback(update); - } -}; - -typedef Static< EntryCompletion > GlobalShaderEntryCompletion; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/textures.cpp b/misc/mediasource/extra/netradiant-src/radiant/textures.cpp deleted file mode 100644 index e7ff7e42..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/textures.cpp +++ /dev/null @@ -1,912 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "textures.h" - -#include "debugging/debugging.h" -#include "warnings.h" - -#include "itextures.h" -#include "igl.h" -#include "preferencesystem.h" -#include "qgl.h" - -#include "texturelib.h" -#include "container/hashfunc.h" -#include "container/cache.h" -#include "generic/callback.h" -#include "stringio.h" - -#include "image.h" -#include "texmanip.h" -#include "preferences.h" - - - -enum ETexturesMode -{ - eTextures_NEAREST = 0, - eTextures_NEAREST_MIPMAP_NEAREST = 1, - eTextures_NEAREST_MIPMAP_LINEAR = 2, - eTextures_LINEAR = 3, - eTextures_LINEAR_MIPMAP_NEAREST = 4, - eTextures_LINEAR_MIPMAP_LINEAR = 5, - eTextures_MAX_ANISOTROPY = 6, -}; - -enum TextureCompressionFormat -{ - TEXTURECOMPRESSION_NONE = 0, - TEXTURECOMPRESSION_RGBA = 1, - TEXTURECOMPRESSION_RGBA_S3TC_DXT1 = 2, - TEXTURECOMPRESSION_RGBA_S3TC_DXT3 = 3, - TEXTURECOMPRESSION_RGBA_S3TC_DXT5 = 4, -}; - -struct texture_globals_t -{ - // RIANT - // texture compression format - TextureCompressionFormat m_nTextureCompressionFormat; - - float fGamma; - - bool bTextureCompressionSupported; // is texture compression supported by hardware? - GLint texture_components; - - // temporary values that should be initialised only once at run-time - bool m_bOpenGLCompressionSupported; - bool m_bS3CompressionSupported; - - texture_globals_t(GLint components) : - m_nTextureCompressionFormat(TEXTURECOMPRESSION_NONE), - fGamma(1.0f), - bTextureCompressionSupported(false), - texture_components(components), - m_bOpenGLCompressionSupported(false), - m_bS3CompressionSupported(false) - { - } -}; - -texture_globals_t g_texture_globals(GL_RGBA); - -void SetTexParameters(ETexturesMode mode) -{ - float maxAniso = QGL_maxTextureAnisotropy(); - if(maxAniso > 1) - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); - else - if(mode == eTextures_MAX_ANISOTROPY) - mode = eTextures_LINEAR_MIPMAP_LINEAR; - - switch (mode) - { - case eTextures_NEAREST: - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - break; - case eTextures_NEAREST_MIPMAP_NEAREST: - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - break; - case eTextures_NEAREST_MIPMAP_LINEAR: - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); - break; - case eTextures_LINEAR: - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - break; - case eTextures_LINEAR_MIPMAP_NEAREST: - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - break; - case eTextures_LINEAR_MIPMAP_LINEAR: - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); - break; - case eTextures_MAX_ANISOTROPY: - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAniso); - break; - default: - globalOutputStream() << "invalid texture mode\n"; - } -} - -ETexturesMode g_texture_mode = eTextures_LINEAR_MIPMAP_LINEAR; - - - - -byte g_gammatable[256]; -void ResampleGamma(float fGamma) -{ - int i,inf; - if (fGamma == 1.0) - { - for (i = 0; i < 256; i++) - g_gammatable[i] = i; - } else - { - for (i = 0; i < 256; i++) - { - inf = (int)(255 * pow ( static_cast((i + 0.5) / 255.5) , static_cast(fGamma) ) + 0.5); - if (inf < 0) - inf = 0; - if (inf > 255) - inf = 255; - g_gammatable[i] = inf; - } - } -} - -inline const int& min_int(const int& left, const int& right) -{ - return std::min(left, right); -} - -int max_tex_size = 0; -const int max_texture_quality = 3; -LatchedInt g_Textures_textureQuality(3, "Texture Quality"); - -/// \brief This function does the actual processing of raw RGBA data into a GL texture. -/// It will also resample to power-of-two dimensions, generate the mipmaps and adjust gamma. -void LoadTextureRGBA(qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight) -{ - static float fGamma = -1; - float total[3]; - byte *outpixels = 0; - int nCount = nWidth * nHeight; - - if (fGamma != g_texture_globals.fGamma) - { - fGamma = g_texture_globals.fGamma; - ResampleGamma(fGamma); - } - - q->width = nWidth; - q->height = nHeight; - - total[0] = total[1] = total[2] = 0.0f; - - // resample texture gamma according to user settings - for (int i = 0; i < (nCount * 4); i += 4) - { - for (int j = 0; j < 3; j++) - { - total[j] += (pPixels + i)[j]; - byte b = (pPixels + i)[j]; - (pPixels + i)[j] = g_gammatable[b]; - } - } - - q->color[0] = total[0] / (nCount * 255); - q->color[1] = total[1] / (nCount * 255); - q->color[2] = total[2] / (nCount * 255); - - glGenTextures (1, &q->texture_number); - - glBindTexture( GL_TEXTURE_2D, q->texture_number ); - - SetTexParameters(g_texture_mode); - - int gl_width = 1; - while(gl_width < nWidth) - gl_width <<= 1; - - int gl_height = 1; - while(gl_height < nHeight) - gl_height <<= 1; - - bool resampled = false; - if (!(gl_width == nWidth && gl_height == nHeight)) - { - resampled = true; - outpixels = (byte *)malloc(gl_width * gl_height * 4); - R_ResampleTexture(pPixels, nWidth, nHeight, outpixels, gl_width, gl_height, 4); - } - else - { - outpixels = pPixels; - } - - int quality_reduction = max_texture_quality - g_Textures_textureQuality.m_value; - int target_width = min_int(gl_width >> quality_reduction, max_tex_size); - int target_height = min_int(gl_height >> quality_reduction, max_tex_size); - - while (gl_width > target_width || gl_height > target_height) - { - GL_MipReduce(outpixels, outpixels, gl_width, gl_height, target_width, target_height); - - if (gl_width > target_width) - gl_width >>= 1; - if (gl_height > target_height) - gl_height >>= 1; - } - - int mip = 0; - glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels); - while (gl_width > 1 || gl_height > 1) - { - GL_MipReduce(outpixels, outpixels, gl_width, gl_height, 1, 1); - - if (gl_width > 1) - gl_width >>= 1; - if (gl_height > 1) - gl_height >>= 1; - - glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels); - } - - glBindTexture(GL_TEXTURE_2D, 0); - if (resampled) - free(outpixels); -} - -#if 0 -/* -============== -Texture_InitPalette -============== -*/ -void Texture_InitPalette (byte *pal) -{ - int r,g,b; - int i; - int inf; - byte gammatable[256]; - float gamma; - - gamma = g_texture_globals.fGamma; - - if (gamma == 1.0) - { - for (i=0 ; i<256 ; i++) - gammatable[i] = i; - } else - { - for (i=0 ; i<256 ; i++) - { - inf = (int)(255 * pow ( (i+0.5)/255.5 , gamma ) + 0.5); - if (inf < 0) - inf = 0; - if (inf > 255) - inf = 255; - gammatable[i] = inf; - } - } - - for (i=0 ; i<256 ; i++) - { - r = gammatable[pal[0]]; - g = gammatable[pal[1]]; - b = gammatable[pal[2]]; - pal += 3; - - //v = (r<<24) + (g<<16) + (b<<8) + 255; - //v = BigLong (v); - - //tex_palette[i] = v; - tex_palette[i*3+0] = r; - tex_palette[i*3+1] = g; - tex_palette[i*3+2] = b; - } -} -#endif - -#if 0 -class TestHashtable -{ -public: - TestHashtable() - { - HashTable strings; - strings["Monkey"] = "bleh"; - strings["MonkeY"] = "blah"; - } -}; - -const TestHashtable g_testhashtable; - -#endif - -typedef std::pair TextureKey; - -void qtexture_realise(qtexture_t& texture, const TextureKey& key) -{ - texture.texture_number = 0; - if(!string_empty(key.second.c_str())) - { - Image* image = key.first.loadImage(key.second.c_str()); - if(image != 0) - { - LoadTextureRGBA(&texture, image->getRGBAPixels(), image->getWidth(), image->getHeight()); - texture.surfaceFlags = image->getSurfaceFlags(); - texture.contentFlags = image->getContentFlags(); - texture.value = image->getValue(); - image->release(); - globalOutputStream() << "Loaded Texture: \"" << key.second.c_str() << "\"\n"; - GlobalOpenGL_debugAssertNoErrors(); - } - else - { - globalErrorStream() << "Texture load failed: \"" << key.second.c_str() << "\"\n"; - } - } -} - -void qtexture_unrealise(qtexture_t& texture) -{ - if(GlobalOpenGL().contextValid && texture.texture_number != 0) - { - glDeleteTextures(1, &texture.texture_number); - GlobalOpenGL_debugAssertNoErrors(); - } -} - -class TextureKeyEqualNoCase -{ -public: - bool operator()(const TextureKey& key, const TextureKey& other) const - { - return key.first == other.first && string_equal_nocase(key.second.c_str(), other.second.c_str()); - } -}; - -class TextureKeyHashNoCase -{ -public: - typedef hash_t hash_type; - hash_t operator()(const TextureKey& key) const - { - return hash_combine(string_hash_nocase(key.second.c_str()), pod_hash(key.first)); - } -}; - -#define DEBUG_TEXTURES 0 - -class TexturesMap : public TexturesCache -{ - class TextureConstructor - { - TexturesMap* m_cache; - public: - explicit TextureConstructor(TexturesMap* cache) - : m_cache(cache) - { - } - qtexture_t* construct(const TextureKey& key) - { - qtexture_t* texture = new qtexture_t(key.first, key.second.c_str()); - if(m_cache->realised()) - { - qtexture_realise(*texture, key); - } - return texture; - } - void destroy(qtexture_t* texture) - { - if(m_cache->realised()) - { - qtexture_unrealise(*texture); - } - delete texture; - } - }; - - typedef HashedCache qtextures_t; - qtextures_t m_qtextures; - TexturesCacheObserver* m_observer; - std::size_t m_unrealised; - -public: - TexturesMap() : m_qtextures(TextureConstructor(this)), m_observer(0), m_unrealised(1) - { - } - typedef qtextures_t::iterator iterator; - - iterator begin() - { - return m_qtextures.begin(); - } - iterator end() - { - return m_qtextures.end(); - } - - LoadImageCallback defaultLoader() const - { - return LoadImageCallback(0, QERApp_LoadImage); - } - Image* loadImage(const char* name) - { - return defaultLoader().loadImage(name); - } - qtexture_t* capture(const char* name) - { - return capture(defaultLoader(), name); - } - qtexture_t* capture(const LoadImageCallback& loader, const char* name) - { -#if DEBUG_TEXTURES - globalOutputStream() << "textures capture: " << makeQuoted(name) << '\n'; -#endif - return m_qtextures.capture(TextureKey(loader, name)).get(); - } - void release(qtexture_t* texture) - { -#if DEBUG_TEXTURES - globalOutputStream() << "textures release: " << makeQuoted(texture->name) << '\n'; -#endif - m_qtextures.release(TextureKey(texture->load, texture->name)); - } - void attach(TexturesCacheObserver& observer) - { - ASSERT_MESSAGE(m_observer == 0, "TexturesMap::attach: cannot attach observer"); - m_observer = &observer; - } - void detach(TexturesCacheObserver& observer) - { - ASSERT_MESSAGE(m_observer == &observer, "TexturesMap::detach: cannot detach observer"); - m_observer = 0; - } - void realise() - { - if(--m_unrealised == 0) - { - g_texture_globals.bTextureCompressionSupported = false; - - if(GlobalOpenGL().ARB_texture_compression()) - { - g_texture_globals.bTextureCompressionSupported = true; - g_texture_globals.m_bOpenGLCompressionSupported = true; - } - - if(GlobalOpenGL().EXT_texture_compression_s3tc()) - { - g_texture_globals.bTextureCompressionSupported = true; - g_texture_globals.m_bS3CompressionSupported = true; - } - - switch(g_texture_globals.texture_components) - { - case GL_RGBA: - break; - case GL_COMPRESSED_RGBA_ARB: - if (!g_texture_globals.m_bOpenGLCompressionSupported) - { - globalOutputStream() << "OpenGL extension GL_ARB_texture_compression not supported by current graphics drivers\n"; - g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; - g_texture_globals.texture_components = GL_RGBA; - } - break; - case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: - case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: - case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: - if(!g_texture_globals.m_bS3CompressionSupported) - { - globalOutputStream() << "OpenGL extension GL_EXT_texture_compression_s3tc not supported by current graphics drivers\n"; - if(g_texture_globals.m_bOpenGLCompressionSupported) - { - g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_RGBA; - g_texture_globals.texture_components = GL_COMPRESSED_RGBA_ARB; - } - else - { - g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; - g_texture_globals.texture_components = GL_RGBA; - } - } - break; - default: - globalOutputStream() << "Unknown texture compression selected, reverting\n"; - g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; - g_texture_globals.texture_components = GL_RGBA; - break; - } - - - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size); - if(max_tex_size == 0) - { - max_tex_size = 1024; - } - - for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i) - { - if(!(*i).value.empty()) - { - qtexture_realise(*(*i).value, (*i).key); - } - } - if(m_observer != 0) - { - m_observer->realise(); - } - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - if(m_observer != 0) - { - m_observer->unrealise(); - } - for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i) - { - if(!(*i).value.empty()) - { - qtexture_unrealise(*(*i).value); - } - } - } - } - bool realised() - { - return m_unrealised == 0; - } -}; - -TexturesMap* g_texturesmap; - -TexturesCache& GetTexturesCache() -{ - return *g_texturesmap; -} - - -void Textures_Realise() -{ - g_texturesmap->realise(); -} - -void Textures_Unrealise() -{ - g_texturesmap->unrealise(); -} - - -Callback g_texturesModeChangedNotify; - -void Textures_setModeChangedNotify(const Callback& notify) -{ - g_texturesModeChangedNotify = notify; -} - -void Textures_ModeChanged() -{ - if(g_texturesmap->realised()) - { - SetTexParameters(g_texture_mode); - - for(TexturesMap::iterator i = g_texturesmap->begin(); i != g_texturesmap->end(); ++i) - { - glBindTexture (GL_TEXTURE_2D, (*i).value->texture_number); - SetTexParameters(g_texture_mode); - } - - glBindTexture( GL_TEXTURE_2D, 0 ); - } - g_texturesModeChangedNotify(); -} - -void Textures_SetMode(ETexturesMode mode) -{ - if(g_texture_mode != mode) - { - g_texture_mode = mode; - - Textures_ModeChanged(); - } -} - -void Textures_setTextureComponents(GLint texture_components) -{ - if(g_texture_globals.texture_components != texture_components) - { - Textures_Unrealise(); - g_texture_globals.texture_components = texture_components; - Textures_Realise(); - } -} - -void Textures_UpdateTextureCompressionFormat() -{ - GLint texture_components = GL_RGBA; - - switch (g_texture_globals.m_nTextureCompressionFormat) - { - case (TEXTURECOMPRESSION_NONE): - { - texture_components = GL_RGBA; - break; - } - case (TEXTURECOMPRESSION_RGBA): - { - texture_components = GL_COMPRESSED_RGBA_ARB; - break; - } - case (TEXTURECOMPRESSION_RGBA_S3TC_DXT1): - { - texture_components = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; - break; - } - case (TEXTURECOMPRESSION_RGBA_S3TC_DXT3): - { - texture_components = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; - break; - } - case (TEXTURECOMPRESSION_RGBA_S3TC_DXT5): - { - texture_components = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; - break; - } - } - - Textures_setTextureComponents(texture_components); -} - -void TextureCompressionImport(TextureCompressionFormat& self, int value) -{ - if(!g_texture_globals.m_bOpenGLCompressionSupported - && g_texture_globals.m_bS3CompressionSupported - && value >= 1) - { - ++value; - } - switch(value) - { - case 0: - self = TEXTURECOMPRESSION_NONE; - break; - case 1: - self = TEXTURECOMPRESSION_RGBA; - break; - case 2: - self = TEXTURECOMPRESSION_RGBA_S3TC_DXT1; - break; - case 3: - self = TEXTURECOMPRESSION_RGBA_S3TC_DXT3; - break; - case 4: - self = TEXTURECOMPRESSION_RGBA_S3TC_DXT5; - break; - } - Textures_UpdateTextureCompressionFormat(); -} -typedef ReferenceCaller1 TextureCompressionImportCaller; - -void TextureGammaImport(float& self, float value) -{ - if(self != value) - { - Textures_Unrealise(); - self = value; - Textures_Realise(); - } -} -typedef ReferenceCaller1 TextureGammaImportCaller; - -void TextureModeImport(ETexturesMode& self, int value) -{ - switch(value) - { - case 0: - Textures_SetMode(eTextures_NEAREST); - break; - case 1: - Textures_SetMode(eTextures_NEAREST_MIPMAP_NEAREST); - break; - case 2: - Textures_SetMode(eTextures_LINEAR); - break; - case 3: - Textures_SetMode(eTextures_NEAREST_MIPMAP_LINEAR); - break; - case 4: - Textures_SetMode(eTextures_LINEAR_MIPMAP_NEAREST); - break; - case 5: - Textures_SetMode(eTextures_LINEAR_MIPMAP_LINEAR); - break; - case 6: - Textures_SetMode(eTextures_MAX_ANISOTROPY); - } -} -typedef ReferenceCaller1 TextureModeImportCaller; - -void TextureModeExport(ETexturesMode& self, const IntImportCallback& importer) -{ - switch(self) - { - case eTextures_NEAREST: - importer(0); - break; - case eTextures_NEAREST_MIPMAP_NEAREST: - importer(1); - break; - case eTextures_LINEAR: - importer(2); - break; - case eTextures_NEAREST_MIPMAP_LINEAR: - importer(3); - break; - case eTextures_LINEAR_MIPMAP_NEAREST: - importer(4); - break; - case eTextures_LINEAR_MIPMAP_LINEAR: - importer(5); - break; - case eTextures_MAX_ANISOTROPY: - importer(6); - break; - default: - importer(4); - } -} -typedef ReferenceCaller1 TextureModeExportCaller; - -void Textures_constructPreferences(PreferencesPage& page) -{ - { - const char* percentages[] = { "12.5%", "25%", "50%", "100%", }; - page.appendRadio( - "Texture Quality", - STRING_ARRAY_RANGE(percentages), - LatchedIntImportCaller(g_Textures_textureQuality), - IntExportCaller(g_Textures_textureQuality.m_latched) - ); - } - page.appendSpinner( - "Texture Gamma", - 1.0, - 0.0, - 1.0, - FloatImportCallback(TextureGammaImportCaller(g_texture_globals.fGamma)), - FloatExportCallback(FloatExportCaller(g_texture_globals.fGamma)) - ); - { - const char* texture_mode[] = { "Nearest", "Nearest Mipmap", "Linear", "Bilinear", "Bilinear Mipmap", "Trilinear", "Anisotropy" }; - page.appendCombo( - "Texture Render Mode", - STRING_ARRAY_RANGE(texture_mode), - IntImportCallback(TextureModeImportCaller(g_texture_mode)), - IntExportCallback(TextureModeExportCaller(g_texture_mode)) - ); - } - { - const char* compression_none[] = { "None" }; - const char* compression_opengl[] = { "None", "OpenGL ARB" }; - const char* compression_s3tc[] = { "None", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" }; - const char* compression_opengl_s3tc[] = { "None", "OpenGL ARB", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" }; - StringArrayRange compression( - (g_texture_globals.m_bOpenGLCompressionSupported) - ? (g_texture_globals.m_bS3CompressionSupported) - ? STRING_ARRAY_RANGE(compression_opengl_s3tc) - : STRING_ARRAY_RANGE(compression_opengl) - : (g_texture_globals.m_bS3CompressionSupported) - ? STRING_ARRAY_RANGE(compression_s3tc) - : STRING_ARRAY_RANGE(compression_none) - ); - page.appendCombo( - "Hardware Texture Compression", - compression, - TextureCompressionImportCaller(g_texture_globals.m_nTextureCompressionFormat), - IntExportCaller(reinterpret_cast(g_texture_globals.m_nTextureCompressionFormat)) - ); - } -} -void Textures_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Textures", "Texture Settings")); - Textures_constructPreferences(page); -} -void Textures_registerPreferencesPage() -{ - PreferencesDialog_addDisplayPage(FreeCaller1()); -} - -void TextureCompression_importString(const char* string) -{ - g_texture_globals.m_nTextureCompressionFormat = static_cast(atoi(string)); - Textures_UpdateTextureCompressionFormat(); -} -typedef FreeCaller1 TextureCompressionImportStringCaller; - - -void Textures_Construct() -{ - g_texturesmap = new TexturesMap; - - GlobalPreferenceSystem().registerPreference("TextureCompressionFormat", TextureCompressionImportStringCaller(), IntExportStringCaller(reinterpret_cast(g_texture_globals.m_nTextureCompressionFormat))); - GlobalPreferenceSystem().registerPreference("TextureFiltering", IntImportStringCaller(reinterpret_cast(g_texture_mode)), IntExportStringCaller(reinterpret_cast(g_texture_mode))); - GlobalPreferenceSystem().registerPreference("TextureQuality", IntImportStringCaller(g_Textures_textureQuality.m_latched), IntExportStringCaller(g_Textures_textureQuality.m_latched)); - GlobalPreferenceSystem().registerPreference("SI_Gamma", FloatImportStringCaller(g_texture_globals.fGamma), FloatExportStringCaller(g_texture_globals.fGamma)); - - g_Textures_textureQuality.useLatched(); - - Textures_registerPreferencesPage(); - - Textures_ModeChanged(); -} -void Textures_Destroy() -{ - delete g_texturesmap; -} - - -#include "modulesystem/modulesmap.h" -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -class TexturesDependencies : - public GlobalRadiantModuleRef, - public GlobalOpenGLModuleRef, - public GlobalPreferenceSystemModuleRef -{ - ImageModulesRef m_image_modules; -public: - TexturesDependencies() : - m_image_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("texturetypes")) - { - } - ImageModules& getImageModules() - { - return m_image_modules.get(); - } -}; - -class TexturesAPI -{ - TexturesCache* m_textures; -public: - typedef TexturesCache Type; - STRING_CONSTANT(Name, "*"); - - TexturesAPI() - { - Textures_Construct(); - - m_textures = &GetTexturesCache(); - } - ~TexturesAPI() - { - Textures_Destroy(); - } - TexturesCache* getTable() - { - return m_textures; - } -}; - -typedef SingletonModule TexturesModule; -typedef Static StaticTexturesModule; -StaticRegisterModule staticRegisterTextures(StaticTexturesModule::instance()); - -ImageModules& Textures_getImageModules() -{ - return StaticTexturesModule::instance().getDependencies().getImageModules(); -} - - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/textures.h b/misc/mediasource/extra/netradiant-src/radiant/textures.h deleted file mode 100644 index 0a570b7d..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/textures.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 1999-2006 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 (INCLUDED_TEXTURES_H) -#define INCLUDED_TEXTURES_H - -#include "generic/callbackfwd.h" - -void Textures_Realise(); -void Textures_Unrealise(); -void Textures_sharedContextDestroyed(); - -void Textures_setModeChangedNotify(const Callback& notify); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/texwindow.cpp b/misc/mediasource/extra/netradiant-src/radiant/texwindow.cpp deleted file mode 100644 index 95d490ab..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/texwindow.cpp +++ /dev/null @@ -1,2723 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Texture Window -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "texwindow.h" - -#include "debugging/debugging.h" -#include "warnings.h" - -#include "ifilesystem.h" -#include "iundo.h" -#include "igl.h" -#include "iarchive.h" -#include "moduleobserver.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include "signal/signal.h" -#include "math/vector.h" -#include "texturelib.h" -#include "string/string.h" -#include "shaderlib.h" -#include "os/file.h" -#include "os/path.h" -#include "stream/memstream.h" -#include "stream/textfilestream.h" -#include "stream/stringstream.h" -#include "cmdlib.h" -#include "texmanip.h" -#include "textures.h" -#include "convert.h" - -#include "gtkutil/menu.h" -#include "gtkutil/nonmodal.h" -#include "gtkutil/cursor.h" -#include "gtkutil/widget.h" -#include "gtkutil/glwidget.h" -#include "gtkutil/messagebox.h" - -#include "error.h" -#include "map.h" -#include "qgl.h" -#include "select.h" -#include "brush_primit.h" -#include "brushmanip.h" -#include "patchmanip.h" -#include "plugin.h" -#include "qe3.h" -#include "gtkdlgs.h" -#include "gtkmisc.h" -#include "mainframe.h" -#include "findtexturedialog.h" -#include "surfacedialog.h" -#include "patchdialog.h" -#include "groupdialog.h" -#include "preferences.h" -#include "shaders.h" -#include "commands.h" - -bool TextureBrowser_showWads() -{ - return !string_empty(g_pGameDescription->getKeyValue("show_wads")); -} - -void TextureBrowser_queueDraw(TextureBrowser& textureBrowser); - -bool string_equal_start(const char* string, StringRange start) -{ - return string_equal_n(string, start.first, start.last - start.first); -} - -typedef std::set TextureGroups; - -void TextureGroups_addWad(TextureGroups& groups, const char* archive) -{ - if(extension_equal(path_get_extension(archive), "wad")) - { -#if 1 - groups.insert(archive); -#else - CopiedString archiveBaseName(path_get_filename_start(archive), path_get_filename_base_end(archive)); - groups.insert(archiveBaseName); -#endif - } -} -typedef ReferenceCaller1 TextureGroupsAddWadCaller; - -void TextureGroups_addShader(TextureGroups& groups, const char* shaderName) -{ - const char* texture = path_make_relative(shaderName, "textures/"); - if(texture != shaderName) - { - const char* last = path_remove_directory(texture); - if(!string_empty(last)) - { - groups.insert(CopiedString(StringRange(texture, --last))); - } - } -} -typedef ReferenceCaller1 TextureGroupsAddShaderCaller; - -void TextureGroups_addDirectory(TextureGroups& groups, const char* directory) -{ - groups.insert(directory); -} -typedef ReferenceCaller1 TextureGroupsAddDirectoryCaller; - -namespace -{ - bool g_TextureBrowser_shaderlistOnly = false; - bool g_TextureBrowser_fixedSize = false; - bool g_TextureBrowser_filterNotex = false; -} - -class DeferredAdjustment -{ - gdouble m_value; - guint m_handler; - typedef void (*ValueChangedFunction)(void* data, gdouble value); - ValueChangedFunction m_function; - void* m_data; - - static gboolean deferred_value_changed(gpointer data) - { - reinterpret_cast(data)->m_function( - reinterpret_cast(data)->m_data, - reinterpret_cast(data)->m_value - ); - reinterpret_cast(data)->m_handler = 0; - reinterpret_cast(data)->m_value = 0; - return FALSE; - } -public: - DeferredAdjustment(ValueChangedFunction function, void* data) : m_value(0), m_handler(0), m_function(function), m_data(data) - { - } - void flush() - { - if(m_handler != 0) - { - g_source_remove(m_handler); - deferred_value_changed(this); - } - } - void value_changed(gdouble value) - { - m_value = value; - if(m_handler == 0) - { - m_handler = g_idle_add(deferred_value_changed, this); - } - } - static void adjustment_value_changed(GtkAdjustment *adjustment, DeferredAdjustment* self) - { - self->value_changed(adjustment->value); - } -}; - - - -class TextureBrowser; - -typedef ReferenceCaller TextureBrowserQueueDrawCaller; - -void TextureBrowser_scrollChanged(void* data, gdouble value); - - -enum StartupShaders -{ - STARTUPSHADERS_NONE = 0, - STARTUPSHADERS_COMMON, -}; - -void TextureBrowser_hideUnusedExport(const BoolImportCallback& importer); -typedef FreeCaller1 TextureBrowserHideUnusedExport; - -void TextureBrowser_showShadersExport(const BoolImportCallback& importer); -typedef FreeCaller1 TextureBrowserShowShadersExport; - -void TextureBrowser_showShaderlistOnly(const BoolImportCallback& importer); -typedef FreeCaller1 TextureBrowserShowShaderlistOnlyExport; - -void TextureBrowser_fixedSize(const BoolImportCallback& importer); -typedef FreeCaller1 TextureBrowserFixedSizeExport; - -void TextureBrowser_filterNotex(const BoolImportCallback& importer); -typedef FreeCaller1 TextureBrowserFilterNotexExport; - -class TextureBrowser -{ -public: - int width, height; - int originy; - int m_nTotalHeight; - - CopiedString shader; - - GtkWindow* m_parent; - GtkWidget* m_gl_widget; - GtkWidget* m_texture_scroll; - GtkWidget* m_treeViewTree; - GtkWidget* m_treeViewTags; - GtkWidget* m_tag_frame; - GtkListStore* m_assigned_store; - GtkListStore* m_available_store; - GtkWidget* m_assigned_tree; - GtkWidget* m_available_tree; - GtkWidget* m_scr_win_tree; - GtkWidget* m_scr_win_tags; - GtkWidget* m_tag_notebook; - GtkWidget* m_search_button; - GtkWidget* m_shader_info_item; - - std::set m_all_tags; - GtkListStore* m_all_tags_list; - std::vector m_copied_tags; - std::set m_found_shaders; - - ToggleItem m_hideunused_item; - ToggleItem m_showshaders_item; - ToggleItem m_showshaderlistonly_item; - ToggleItem m_fixedsize_item; - ToggleItem m_filternotex_item; - - guint m_sizeHandler; - guint m_exposeHandler; - - bool m_heightChanged; - bool m_originInvalid; - - DeferredAdjustment m_scrollAdjustment; - FreezePointer m_freezePointer; - - Vector3 color_textureback; - // the increment step we use against the wheel mouse - std::size_t m_mouseWheelScrollIncrement; - std::size_t m_textureScale; - // make the texture increments match the grid changes - bool m_showShaders; - bool m_showTextureScrollbar; - StartupShaders m_startupShaders; - // if true, the texture window will only display in-use shaders - // if false, all the shaders in memory are displayed - bool m_hideUnused; - bool m_rmbSelected; - bool m_searchedTags; - bool m_tags; - // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true. - int m_uniformTextureSize; - // Return the display width of a texture in the texture browser - int getTextureWidth(qtexture_t* tex) - { - int width; - if (!g_TextureBrowser_fixedSize) - { - // Don't use uniform size - width = (int)(tex->width * ((float)m_textureScale / 100)); - } else if - (tex->width >= tex->height) - { - // Texture is square, or wider than it is tall - width = m_uniformTextureSize; - } else { - // Otherwise, preserve the texture's aspect ratio - width = (int)(m_uniformTextureSize * ((float)tex->width / tex->height)); - } - return width; - } - // Return the display height of a texture in the texture browser - int getTextureHeight(qtexture_t* tex) - { - int height; - if (!g_TextureBrowser_fixedSize) - { - // Don't use uniform size - height = (int)(tex->height * ((float)m_textureScale / 100)); - } else if (tex->height >= tex->width) - { - // Texture is square, or taller than it is wide - height = m_uniformTextureSize; - } else { - // Otherwise, preserve the texture's aspect ratio - height = (int)(m_uniformTextureSize * ((float)tex->height / tex->width)); - } - return height; - } - - TextureBrowser() : - m_texture_scroll(0), - m_hideunused_item(TextureBrowserHideUnusedExport()), - m_showshaders_item(TextureBrowserShowShadersExport()), - m_showshaderlistonly_item(TextureBrowserShowShaderlistOnlyExport()), - m_fixedsize_item(TextureBrowserFixedSizeExport()), - m_filternotex_item(TextureBrowserFilterNotexExport()), - m_heightChanged(true), - m_originInvalid(true), - m_scrollAdjustment(TextureBrowser_scrollChanged, this), - color_textureback(0.25f, 0.25f, 0.25f), - m_mouseWheelScrollIncrement(64), - m_textureScale(50), - m_showShaders(true), - m_showTextureScrollbar(true), - m_startupShaders(STARTUPSHADERS_NONE), - m_hideUnused(false), - m_rmbSelected(false), - m_searchedTags(false), - m_tags(false), - m_uniformTextureSize(128) - { - } -}; - -void(*TextureBrowser_textureSelected)(const char* shader); - - -void TextureBrowser_updateScroll(TextureBrowser& textureBrowser); - - -const char* TextureBrowser_getComonShadersName() -{ - const char* value = g_pGameDescription->getKeyValue("common_shaders_name"); - if(!string_empty(value)) - { - return value; - } - return "Common"; -} - -const char* TextureBrowser_getComonShadersDir() -{ - const char* value = g_pGameDescription->getKeyValue("common_shaders_dir"); - if(!string_empty(value)) - { - return value; - } - return "common/"; -} - -inline int TextureBrowser_fontHeight(TextureBrowser& textureBrowser) -{ - return GlobalOpenGL().m_font->getPixelHeight(); -} - -const char* TextureBrowser_GetSelectedShader(TextureBrowser& textureBrowser) -{ - return textureBrowser.shader.c_str(); -} - -void TextureBrowser_SetStatus(TextureBrowser& textureBrowser, const char* name) -{ - IShader* shader = QERApp_Shader_ForName( name); - qtexture_t* q = shader->getTexture(); - StringOutputStream strTex(256); - strTex << name << " W: " << Unsigned(q->width) << " H: " << Unsigned(q->height); - shader->DecRef(); - g_pParentWnd->SetStatusText(g_pParentWnd->m_texture_status, strTex.c_str()); -} - -void TextureBrowser_Focus(TextureBrowser& textureBrowser, const char* name); - -void TextureBrowser_SetSelectedShader(TextureBrowser& textureBrowser, const char* shader) -{ - textureBrowser.shader = shader; - TextureBrowser_SetStatus(textureBrowser, shader); - TextureBrowser_Focus(textureBrowser, shader); - - if(FindTextureDialog_isOpen()) - { - FindTextureDialog_selectTexture(shader); - } - - // disable the menu item "shader info" if no shader was selected - IShader* ishader = QERApp_Shader_ForName(shader); - CopiedString filename = ishader->getShaderFileName(); - - if(filename.empty()) - { - if(textureBrowser.m_shader_info_item != NULL) - { - gtk_widget_set_sensitive(textureBrowser.m_shader_info_item, FALSE); - } - } else { - gtk_widget_set_sensitive(textureBrowser.m_shader_info_item, TRUE); - } - - ishader->DecRef(); -} - - -CopiedString g_TextureBrowser_currentDirectory; - -/* -============================================================================ - -TEXTURE LAYOUT - -TTimo: now based on a rundown through all the shaders -NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle - otherwise we may need to rely on a list instead of an array storage -============================================================================ -*/ - -class TextureLayout -{ -public: - // texture layout functions - // TTimo: now based on shaders - int current_x, current_y, current_row; -}; - -void Texture_StartPos(TextureLayout& layout) -{ - layout.current_x = 8; - layout.current_y = -8; - layout.current_row = 0; -} - -void Texture_NextPos(TextureBrowser& textureBrowser, TextureLayout& layout, qtexture_t* current_texture, int *x, int *y) -{ - qtexture_t* q = current_texture; - - int nWidth = textureBrowser.getTextureWidth(q); - int nHeight = textureBrowser.getTextureHeight(q); - if (layout.current_x + nWidth > textureBrowser.width-8 && layout.current_row) - { // go to the next row unless the texture is the first on the row - layout.current_x = 8; - layout.current_y -= layout.current_row + TextureBrowser_fontHeight(textureBrowser) + 4; - layout.current_row = 0; - } - - *x = layout.current_x; - *y = layout.current_y; - - // Is our texture larger than the row? If so, grow the - // row height to match it - - if (layout.current_row < nHeight) - layout.current_row = nHeight; - - // never go less than 96, or the names get all crunched up - layout.current_x += nWidth < 96 ? 96 : nWidth; - layout.current_x += 8; -} - -bool TextureSearch_IsShown(const char* name) -{ - std::set::iterator iter; - - iter = GlobalTextureBrowser().m_found_shaders.find(name); - - if(iter == GlobalTextureBrowser().m_found_shaders.end()) - { - return false; - } else { - return true; - } -} - -CopiedString g_notex; -CopiedString g_shadernotex; - -// if texture_showinuse jump over non in-use textures -bool Texture_IsShown(IShader* shader, bool show_shaders, bool hideUnused) -{ - // filter notex / shadernotex images - if(g_TextureBrowser_filterNotex && (string_equal(g_notex.c_str(), shader->getTexture()->name) || string_equal(g_shadernotex.c_str(), shader->getTexture()->name))) - { - return false; - } - - if(g_TextureBrowser_currentDirectory == "Untagged") - { - std::set::iterator iter; - - iter = GlobalTextureBrowser().m_found_shaders.find(shader->getName()); - - if(iter == GlobalTextureBrowser().m_found_shaders.end()) - { - return false; - } else { - return true; - } - } - - if(!shader_equal_prefix(shader->getName(), "textures/")) - return false; - - if (!show_shaders && !shader->IsDefault()) - return false; - - if(hideUnused && !shader->IsInUse()) - return false; - - if(GlobalTextureBrowser().m_searchedTags) - { - if(!TextureSearch_IsShown(shader->getName())) - { - return false; - } else { - return true; - } - } else { - if(!shader_equal_prefix(shader_get_textureName(shader->getName()), g_TextureBrowser_currentDirectory.c_str())) - { - return false; - } - } - - return true; -} - -void TextureBrowser_heightChanged(TextureBrowser& textureBrowser) -{ - textureBrowser.m_heightChanged = true; - - TextureBrowser_updateScroll(textureBrowser); - TextureBrowser_queueDraw(textureBrowser); -} - -void TextureBrowser_evaluateHeight(TextureBrowser& textureBrowser) -{ - if(textureBrowser.m_heightChanged) - { - textureBrowser.m_heightChanged = false; - - textureBrowser.m_nTotalHeight = 0; - - TextureLayout layout; - Texture_StartPos(layout); - for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) - { - IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); - - if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) - continue; - - int x, y; - Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); - textureBrowser.m_nTotalHeight = std::max(textureBrowser.m_nTotalHeight, abs(layout.current_y) + TextureBrowser_fontHeight(textureBrowser) + textureBrowser.getTextureHeight(shader->getTexture()) + 4); - } - } -} - -int TextureBrowser_TotalHeight(TextureBrowser& textureBrowser) -{ - TextureBrowser_evaluateHeight(textureBrowser); - return textureBrowser.m_nTotalHeight; -} - -inline const int& min_int(const int& left, const int& right) -{ - return std::min(left, right); -} - -void TextureBrowser_clampOriginY(TextureBrowser& textureBrowser) -{ - if(textureBrowser.originy > 0) - { - textureBrowser.originy = 0; - } - int lower = min_int(textureBrowser.height - TextureBrowser_TotalHeight(textureBrowser), 0); - if(textureBrowser.originy < lower) - { - textureBrowser.originy = lower; - } -} - -int TextureBrowser_getOriginY(TextureBrowser& textureBrowser) -{ - if(textureBrowser.m_originInvalid) - { - textureBrowser.m_originInvalid = false; - TextureBrowser_clampOriginY(textureBrowser); - TextureBrowser_updateScroll(textureBrowser); - } - return textureBrowser.originy; -} - -void TextureBrowser_setOriginY(TextureBrowser& textureBrowser, int originy) -{ - textureBrowser.originy = originy; - TextureBrowser_clampOriginY(textureBrowser); - TextureBrowser_updateScroll(textureBrowser); - TextureBrowser_queueDraw(textureBrowser); -} - - -Signal0 g_activeShadersChangedCallbacks; - -void TextureBrowser_addActiveShadersChangedCallback(const SignalHandler& handler) -{ - g_activeShadersChangedCallbacks.connectLast(handler); -} - -class ShadersObserver : public ModuleObserver -{ - Signal0 m_realiseCallbacks; -public: - void realise() - { - m_realiseCallbacks(); - } - void unrealise() - { - } - void insert(const SignalHandler& handler) - { - m_realiseCallbacks.connectLast(handler); - } -}; - -namespace -{ - ShadersObserver g_ShadersObserver; -} - -void TextureBrowser_addShadersRealiseCallback(const SignalHandler& handler) -{ - g_ShadersObserver.insert(handler); -} - -void TextureBrowser_activeShadersChanged(TextureBrowser& textureBrowser) -{ - TextureBrowser_heightChanged(textureBrowser); - textureBrowser.m_originInvalid = true; - - g_activeShadersChangedCallbacks(); -} - -void TextureBrowser_importShowScrollbar(TextureBrowser& textureBrowser, bool value) -{ - textureBrowser.m_showTextureScrollbar = value; - if(textureBrowser.m_texture_scroll != 0) - { - widget_set_visible(textureBrowser.m_texture_scroll, textureBrowser.m_showTextureScrollbar); - TextureBrowser_updateScroll(textureBrowser); - } -} -typedef ReferenceCaller1 TextureBrowserImportShowScrollbarCaller; - - -/* -============== -TextureBrowser_ShowDirectory -relies on texture_directory global for the directory to use -1) Load the shaders for the given directory -2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader) -NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made - available through the IShaders interface -NOTE: for texture window layout: - all shaders are stored with alphabetical order after load - previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown - ( the GL textures are not flushed though) -============== -*/ - -bool endswith(const char *haystack, const char *needle) -{ - size_t lh = strlen(haystack); - size_t ln = strlen(needle); - if(lh < ln) - return false; - return !memcmp(haystack + (lh - ln), needle, ln); -} - -bool texture_name_ignore(const char* name) -{ - StringOutputStream strTemp(string_length(name)); - strTemp << LowerCase(name); - - return - endswith(strTemp.c_str(), ".specular") || - endswith(strTemp.c_str(), ".glow") || - endswith(strTemp.c_str(), ".bump") || - endswith(strTemp.c_str(), ".diffuse") || - endswith(strTemp.c_str(), ".blend") || - endswith(strTemp.c_str(), ".alpha") || - endswith(strTemp.c_str(), "_norm") || - endswith(strTemp.c_str(), "_bump") || - endswith(strTemp.c_str(), "_glow") || - endswith(strTemp.c_str(), "_gloss") || - endswith(strTemp.c_str(), "_pants") || - endswith(strTemp.c_str(), "_shirt") || - endswith(strTemp.c_str(), "_reflect") || - endswith(strTemp.c_str(), "_alpha") || - 0; -} - -class LoadShaderVisitor : public Archive::Visitor -{ -public: - void visit(const char* name) - { - IShader* shader = QERApp_Shader_ForName(CopiedString(StringRange(name, path_get_filename_base_end(name))).c_str()); - shader->DecRef(); - } -}; - -void TextureBrowser_SetHideUnused(TextureBrowser& textureBrowser, bool hideUnused); - -GtkWidget* g_page_textures; - -void TextureBrowser_toggleShow() -{ - GroupDialog_showPage(g_page_textures); -} - - -void TextureBrowser_updateTitle() -{ - GroupDialog_updatePageTitle(g_page_textures); -} - - - -class TextureCategoryLoadShader -{ - const char* m_directory; - std::size_t& m_count; -public: - typedef const char* first_argument_type; - - TextureCategoryLoadShader(const char* directory, std::size_t& count) - : m_directory(directory), m_count(count) - { - m_count = 0; - } - void operator()(const char* name) const - { - if(shader_equal_prefix(name, "textures/") - && shader_equal_prefix(name + string_length("textures/"), m_directory)) - { - ++m_count; - // request the shader, this will load the texture if needed - // this Shader_ForName call is a kind of hack - IShader *pFoo = QERApp_Shader_ForName(name); - pFoo->DecRef(); - } - } -}; - -void TextureDirectory_loadTexture(const char* directory, const char* texture) -{ - StringOutputStream name(256); - name << directory << StringRange(texture, path_get_filename_base_end(texture)); - - if(texture_name_ignore(name.c_str())) - { - return; - } - - if (!shader_valid(name.c_str())) - { - globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n"; - return; - } - - // if a texture is already in use to represent a shader, ignore it - IShader* shader = QERApp_Shader_ForName(name.c_str()); - shader->DecRef(); -} -typedef ConstPointerCaller1 TextureDirectoryLoadTextureCaller; - -class LoadTexturesByTypeVisitor : public ImageModules::Visitor -{ - const char* m_dirstring; -public: - LoadTexturesByTypeVisitor(const char* dirstring) - : m_dirstring(dirstring) - { - } - void visit(const char* minor, const _QERPlugImageTable& table) const - { - GlobalFileSystem().forEachFile(m_dirstring, minor, TextureDirectoryLoadTextureCaller(m_dirstring)); - } -}; - -void TextureBrowser_ShowDirectory(TextureBrowser& textureBrowser, const char* directory) -{ - if(TextureBrowser_showWads()) - { - Archive* archive = GlobalFileSystem().getArchive(directory); - ASSERT_NOTNULL(archive); - LoadShaderVisitor visitor; - archive->forEachFile(Archive::VisitorFunc(visitor, Archive::eFiles, 0), "textures/"); - } - else - { - g_TextureBrowser_currentDirectory = directory; - TextureBrowser_heightChanged(textureBrowser); - - std::size_t shaders_count; - GlobalShaderSystem().foreachShaderName(makeCallback1(TextureCategoryLoadShader(directory, shaders_count))); - globalOutputStream() << "Showing " << Unsigned(shaders_count) << " shaders.\n"; - - if(g_pGameDescription->mGameType != "doom3") - { - // load remaining texture files - - StringOutputStream dirstring(64); - dirstring << "textures/" << directory; - - Radiant_getImageModules().foreachModule(LoadTexturesByTypeVisitor(dirstring.c_str())); - } - } - - // we'll display the newly loaded textures + all the ones already in use - TextureBrowser_SetHideUnused(textureBrowser, false); - - TextureBrowser_updateTitle(); -} - -void TextureBrowser_ShowTagSearchResult(TextureBrowser& textureBrowser, const char* directory) -{ - g_TextureBrowser_currentDirectory = directory; - TextureBrowser_heightChanged(textureBrowser); - - std::size_t shaders_count; - GlobalShaderSystem().foreachShaderName(makeCallback1(TextureCategoryLoadShader(directory, shaders_count))); - globalOutputStream() << "Showing " << Unsigned(shaders_count) << " shaders.\n"; - - if(g_pGameDescription->mGameType != "doom3") - { - // load remaining texture files - StringOutputStream dirstring(64); - dirstring << "textures/" << directory; - - { - LoadTexturesByTypeVisitor visitor(dirstring.c_str()); - Radiant_getImageModules().foreachModule(visitor); - } - } - - // we'll display the newly loaded textures + all the ones already in use - TextureBrowser_SetHideUnused(textureBrowser, false); -} - - -bool TextureBrowser_hideUnused(); - -void TextureBrowser_hideUnusedExport(const BoolImportCallback& importer) -{ - importer(TextureBrowser_hideUnused()); -} -typedef FreeCaller1 TextureBrowserHideUnusedExport; - -void TextureBrowser_showShadersExport(const BoolImportCallback& importer) -{ - importer(GlobalTextureBrowser().m_showShaders); -} -typedef FreeCaller1 TextureBrowserShowShadersExport; - -void TextureBrowser_showShaderlistOnly(const BoolImportCallback& importer) -{ - importer(g_TextureBrowser_shaderlistOnly); -} -typedef FreeCaller1 TextureBrowserShowShaderlistOnlyExport; - -void TextureBrowser_fixedSize(const BoolImportCallback& importer) -{ - importer(g_TextureBrowser_fixedSize); -} -typedef FreeCaller1 TextureBrowser_FixedSizeExport; - -void TextureBrowser_filterNotex(const BoolImportCallback& importer) -{ - importer(g_TextureBrowser_filterNotex); -} -typedef FreeCaller1 TextureBrowser_filterNotexExport; - -void TextureBrowser_SetHideUnused(TextureBrowser& textureBrowser, bool hideUnused) -{ - if(hideUnused) - { - textureBrowser.m_hideUnused = true; - } - else - { - textureBrowser.m_hideUnused = false; - } - - textureBrowser.m_hideunused_item.update(); - - TextureBrowser_heightChanged(textureBrowser); - textureBrowser.m_originInvalid = true; -} - -void TextureBrowser_ShowStartupShaders(TextureBrowser& textureBrowser) -{ - if(textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON) - { - TextureBrowser_ShowDirectory(textureBrowser, TextureBrowser_getComonShadersDir()); - } -} - - -//++timo NOTE: this is a mix of Shader module stuff and texture explorer -// it might need to be split in parts or moved out .. dunno -// scroll origin so the specified texture is completely on screen -// if current texture is not displayed, nothing is changed -void TextureBrowser_Focus(TextureBrowser& textureBrowser, const char* name) -{ - TextureLayout layout; - // scroll origin so the texture is completely on screen - Texture_StartPos(layout); - - for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) - { - IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); - - if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) - continue; - - int x, y; - Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); - qtexture_t* q = shader->getTexture(); - if (!q) - break; - - // we have found when texdef->name and the shader name match - // NOTE: as everywhere else for our comparisons, we are not case sensitive - if (shader_equal(name, shader->getName())) - { - int textureHeight = (int)(q->height * ((float)textureBrowser.m_textureScale / 100)) - + 2 * TextureBrowser_fontHeight(textureBrowser); - - int originy = TextureBrowser_getOriginY(textureBrowser); - if (y > originy) - { - originy = y; - } - - if (y - textureHeight < originy - textureBrowser.height) - { - originy = (y - textureHeight) + textureBrowser.height; - } - - TextureBrowser_setOriginY(textureBrowser, originy); - return; - } - } -} - -IShader* Texture_At(TextureBrowser& textureBrowser, int mx, int my) -{ - my += TextureBrowser_getOriginY(textureBrowser) - textureBrowser.height; - - TextureLayout layout; - Texture_StartPos(layout); - for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) - { - IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); - - if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) - continue; - - int x, y; - Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); - qtexture_t *q = shader->getTexture(); - if (!q) - break; - - int nWidth = textureBrowser.getTextureWidth(q); - int nHeight = textureBrowser.getTextureHeight(q); - if (mx > x && mx - x < nWidth - && my < y && y - my < nHeight + TextureBrowser_fontHeight(textureBrowser)) - { - return shader; - } - } - - return 0; -} - -/* -============== -SelectTexture - - By mouse click -============== -*/ -void SelectTexture(TextureBrowser& textureBrowser, int mx, int my, bool bShift) -{ - IShader* shader = Texture_At(textureBrowser, mx, my); - if(shader != 0) - { - if (bShift) - { - if (shader->IsDefault()) - globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n"; - else - ViewShader( shader->getShaderFileName(), shader->getName() ); - } - else - { - TextureBrowser_SetSelectedShader(textureBrowser, shader->getName()); - TextureBrowser_textureSelected(shader->getName()); - - if (!FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected) - { - UndoableCommand undo("textureNameSetSelected"); - Select_SetShader(shader->getName()); - } - } - } -} - -/* -============================================================================ - - MOUSE ACTIONS - -============================================================================ -*/ - -void TextureBrowser_trackingDelta(int x, int y, unsigned int state, void* data) -{ - TextureBrowser& textureBrowser = *reinterpret_cast(data); - if(y != 0) - { - int scale = 1; - - if(state & GDK_SHIFT_MASK) - scale = 4; - - int originy = TextureBrowser_getOriginY(textureBrowser); - originy += y * scale; - TextureBrowser_setOriginY(textureBrowser, originy); - } -} - -void TextureBrowser_Tracking_MouseDown(TextureBrowser& textureBrowser) -{ - textureBrowser.m_freezePointer.freeze_pointer(textureBrowser.m_parent, TextureBrowser_trackingDelta, &textureBrowser); -} - -void TextureBrowser_Tracking_MouseUp(TextureBrowser& textureBrowser) -{ - textureBrowser.m_freezePointer.unfreeze_pointer(textureBrowser.m_parent); -} - -void TextureBrowser_Selection_MouseDown(TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy) -{ - SelectTexture(textureBrowser, pointx, textureBrowser.height - 1 - pointy, (flags & GDK_SHIFT_MASK) != 0); -} - -/* -============================================================================ - -DRAWING - -============================================================================ -*/ - -/* -============ -Texture_Draw -TTimo: relying on the shaders list to display the textures -we must query all qtexture_t* to manage and display through the IShaders interface -this allows a plugin to completely override the texture system -============ -*/ -void Texture_Draw(TextureBrowser& textureBrowser) -{ - int originy = TextureBrowser_getOriginY(textureBrowser); - - glClearColor(textureBrowser.color_textureback[0], - textureBrowser.color_textureback[1], - textureBrowser.color_textureback[2], - 0); - glViewport(0, 0, textureBrowser.width, textureBrowser.height); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); - - glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - glDisable (GL_DEPTH_TEST); - glDisable(GL_BLEND); - glOrtho (0, textureBrowser.width, originy-textureBrowser.height, originy, -100, 100); - glEnable (GL_TEXTURE_2D); - - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - - int last_y = 0, last_height = 0; - - TextureLayout layout; - Texture_StartPos(layout); - for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) - { - IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); - - if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) - continue; - - int x, y; - Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); - qtexture_t *q = shader->getTexture(); - if (!q) - break; - - int nWidth = textureBrowser.getTextureWidth(q); - int nHeight = textureBrowser.getTextureHeight(q); - - if (y != last_y) - { - last_y = y; - last_height = 0; - } - last_height = std::max (nHeight, last_height); - - // Is this texture visible? - if ((y-nHeight-TextureBrowser_fontHeight(textureBrowser) < originy) - && (y > originy - textureBrowser.height)) - { - // borders rules: - // if it's the current texture, draw a thick red line, else: - // shaders have a white border, simple textures don't - // if !texture_showinuse: (some textures displayed may not be in use) - // draw an additional square around with 0.5 1 0.5 color - if (shader_equal(TextureBrowser_GetSelectedShader(textureBrowser), shader->getName())) - { - glLineWidth (3); - if(textureBrowser.m_rmbSelected) - { - glColor3f (0,0,1); - } else { - glColor3f (1,0,0); - } - glDisable (GL_TEXTURE_2D); - - glBegin (GL_LINE_LOOP); - glVertex2i (x-4,y-TextureBrowser_fontHeight(textureBrowser)+4); - glVertex2i (x-4,y-TextureBrowser_fontHeight(textureBrowser)-nHeight-4); - glVertex2i (x+4+nWidth,y-TextureBrowser_fontHeight(textureBrowser)-nHeight-4); - glVertex2i (x+4+nWidth,y-TextureBrowser_fontHeight(textureBrowser)+4); - glEnd(); - - glEnable (GL_TEXTURE_2D); - glLineWidth (1); - } - else - { - glLineWidth (1); - // shader border: - if (!shader->IsDefault()) - { - glColor3f (1,1,1); - glDisable (GL_TEXTURE_2D); - - glBegin (GL_LINE_LOOP); - glVertex2i (x-1,y+1-TextureBrowser_fontHeight(textureBrowser)); - glVertex2i (x-1,y-nHeight-1-TextureBrowser_fontHeight(textureBrowser)); - glVertex2i (x+1+nWidth,y-nHeight-1-TextureBrowser_fontHeight(textureBrowser)); - glVertex2i (x+1+nWidth,y+1-TextureBrowser_fontHeight(textureBrowser)); - glEnd(); - glEnable (GL_TEXTURE_2D); - } - - // highlight in-use textures - if (!textureBrowser.m_hideUnused && shader->IsInUse()) - { - glColor3f (0.5,1,0.5); - glDisable (GL_TEXTURE_2D); - glBegin (GL_LINE_LOOP); - glVertex2i (x-3,y+3-TextureBrowser_fontHeight(textureBrowser)); - glVertex2i (x-3,y-nHeight-3-TextureBrowser_fontHeight(textureBrowser)); - glVertex2i (x+3+nWidth,y-nHeight-3-TextureBrowser_fontHeight(textureBrowser)); - glVertex2i (x+3+nWidth,y+3-TextureBrowser_fontHeight(textureBrowser)); - glEnd(); - glEnable (GL_TEXTURE_2D); - } - } - - // Draw the texture - glBindTexture (GL_TEXTURE_2D, q->texture_number); - GlobalOpenGL_debugAssertNoErrors(); - glColor3f (1,1,1); - glBegin (GL_QUADS); - glTexCoord2i (0,0); - glVertex2i (x,y-TextureBrowser_fontHeight(textureBrowser)); - glTexCoord2i (1,0); - glVertex2i (x+nWidth,y-TextureBrowser_fontHeight(textureBrowser)); - glTexCoord2i (1,1); - glVertex2i (x+nWidth,y-TextureBrowser_fontHeight(textureBrowser)-nHeight); - glTexCoord2i (0,1); - glVertex2i (x,y-TextureBrowser_fontHeight(textureBrowser)-nHeight); - glEnd(); - - // draw the texture name - glDisable (GL_TEXTURE_2D); - glColor3f (1,1,1); - - glRasterPos2i (x, y-TextureBrowser_fontHeight(textureBrowser)+5); - - // don't draw the directory name - const char* name = shader->getName(); - name += strlen(name); - while(name != shader->getName() && *(name-1) != '/' && *(name-1) != '\\') - name--; - - GlobalOpenGL().drawString(name); - glEnable (GL_TEXTURE_2D); - } - - //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4; - } - - - // reset the current texture - glBindTexture(GL_TEXTURE_2D, 0); - //qglFinish(); -} - -void TextureBrowser_queueDraw(TextureBrowser& textureBrowser) -{ - if(textureBrowser.m_gl_widget != 0) - { - gtk_widget_queue_draw(textureBrowser.m_gl_widget); - } -} - - -void TextureBrowser_setScale(TextureBrowser& textureBrowser, std::size_t scale) -{ - textureBrowser.m_textureScale = scale; - - TextureBrowser_queueDraw(textureBrowser); -} - - -void TextureBrowser_MouseWheel(TextureBrowser& textureBrowser, bool bUp) -{ - int originy = TextureBrowser_getOriginY(textureBrowser); - - if (bUp) - { - originy += int(textureBrowser.m_mouseWheelScrollIncrement); - } - else - { - originy -= int(textureBrowser.m_mouseWheelScrollIncrement); - } - - TextureBrowser_setOriginY(textureBrowser, originy); -} - -XmlTagBuilder TagBuilder; - -enum -{ - TAG_COLUMN, - N_COLUMNS -}; - -void BuildStoreAssignedTags(GtkListStore* store, const char* shader, TextureBrowser* textureBrowser) -{ - GtkTreeIter iter; - - gtk_list_store_clear(store); - - std::vector assigned_tags; - TagBuilder.GetShaderTags(shader, assigned_tags); - - for (size_t i = 0; i < assigned_tags.size(); i++) - { - gtk_list_store_append (store, &iter); - gtk_list_store_set (store, &iter, TAG_COLUMN, assigned_tags[i].c_str(), -1); - } -} - -void BuildStoreAvailableTags( GtkListStore* storeAvailable, - GtkListStore* storeAssigned, - const std::set& allTags, - TextureBrowser* textureBrowser) -{ - GtkTreeIter iterAssigned; - GtkTreeIter iterAvailable; - std::set::const_iterator iterAll; - gchar* tag_assigned; - - gtk_list_store_clear(storeAvailable); - - bool row = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(storeAssigned), &iterAssigned) != 0; - - if(!row) // does the shader have tags assigned? - { - for (iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll) - { - gtk_list_store_append (storeAvailable, &iterAvailable); - gtk_list_store_set (storeAvailable, &iterAvailable, TAG_COLUMN, (*iterAll).c_str(), -1); - } - } - else - { - while(row) // available tags = all tags - assigned tags - { - gtk_tree_model_get(GTK_TREE_MODEL(storeAssigned), &iterAssigned, TAG_COLUMN, &tag_assigned, -1); - - for (iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll) - { - if(strcmp((char*)tag_assigned, (*iterAll).c_str()) != 0) - { - gtk_list_store_append (storeAvailable, &iterAvailable); - gtk_list_store_set (storeAvailable, &iterAvailable, TAG_COLUMN, (*iterAll).c_str(), -1); - } - else - { - row = gtk_tree_model_iter_next(GTK_TREE_MODEL(storeAssigned), &iterAssigned) != 0; - - if(row) - { - gtk_tree_model_get(GTK_TREE_MODEL(storeAssigned), &iterAssigned, TAG_COLUMN, &tag_assigned, -1); - } - } - } - } - } -} - -gboolean TextureBrowser_button_press(GtkWidget* widget, GdkEventButton* event, TextureBrowser* textureBrowser) -{ - if(event->type == GDK_BUTTON_PRESS) - { - if(event->button == 3) - { - if(GlobalTextureBrowser().m_tags) - { - textureBrowser->m_rmbSelected = true; - TextureBrowser_Selection_MouseDown (*textureBrowser, event->state, static_cast(event->x), static_cast(event->y)); - - BuildStoreAssignedTags(textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser); - BuildStoreAvailableTags(textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser); - textureBrowser->m_heightChanged = true; - gtk_widget_show(textureBrowser->m_tag_frame); - - process_gui(); - - TextureBrowser_Focus(*textureBrowser, textureBrowser->shader.c_str()); - } - else - { - TextureBrowser_Tracking_MouseDown(*textureBrowser); - } - } - else if(event->button == 1) - { - TextureBrowser_Selection_MouseDown(*textureBrowser, event->state, static_cast(event->x), static_cast(event->y)); - - if(GlobalTextureBrowser().m_tags) - { - textureBrowser->m_rmbSelected = false; - gtk_widget_hide(textureBrowser->m_tag_frame); - } - } - } - return FALSE; -} - -gboolean TextureBrowser_button_release(GtkWidget* widget, GdkEventButton* event, TextureBrowser* textureBrowser) -{ - if(event->type == GDK_BUTTON_RELEASE) - { - if(event->button == 3) - { - if(!GlobalTextureBrowser().m_tags) - { - TextureBrowser_Tracking_MouseUp(*textureBrowser); - } - } - } - return FALSE; -} - -gboolean TextureBrowser_motion(GtkWidget *widget, GdkEventMotion *event, TextureBrowser* textureBrowser) -{ - return FALSE; -} - -gboolean TextureBrowser_scroll(GtkWidget* widget, GdkEventScroll* event, TextureBrowser* textureBrowser) -{ - if(event->direction == GDK_SCROLL_UP) - { - TextureBrowser_MouseWheel(*textureBrowser, true); - } - else if(event->direction == GDK_SCROLL_DOWN) - { - TextureBrowser_MouseWheel(*textureBrowser, false); - } - return FALSE; -} - -void TextureBrowser_scrollChanged(void* data, gdouble value) -{ - //globalOutputStream() << "vertical scroll\n"; - TextureBrowser_setOriginY(*reinterpret_cast(data), -(int)value); -} - -static void TextureBrowser_verticalScroll(GtkAdjustment *adjustment, TextureBrowser* textureBrowser) -{ - textureBrowser->m_scrollAdjustment.value_changed(adjustment->value); -} - -void TextureBrowser_updateScroll(TextureBrowser& textureBrowser) -{ - if(textureBrowser.m_showTextureScrollbar) - { - int totalHeight = TextureBrowser_TotalHeight(textureBrowser); - - totalHeight = std::max(totalHeight, textureBrowser.height); - - GtkAdjustment *vadjustment = gtk_range_get_adjustment(GTK_RANGE(textureBrowser.m_texture_scroll)); - - vadjustment->value = -TextureBrowser_getOriginY(textureBrowser); - vadjustment->page_size = textureBrowser.height; - vadjustment->page_increment = textureBrowser.height/2; - vadjustment->step_increment = 20; - vadjustment->lower = 0; - vadjustment->upper = totalHeight; - - g_signal_emit_by_name(G_OBJECT (vadjustment), "changed"); - } -} - -gboolean TextureBrowser_size_allocate(GtkWidget* widget, GtkAllocation* allocation, TextureBrowser* textureBrowser) -{ - textureBrowser->width = allocation->width; - textureBrowser->height = allocation->height; - TextureBrowser_heightChanged(*textureBrowser); - textureBrowser->m_originInvalid = true; - TextureBrowser_queueDraw(*textureBrowser); - return FALSE; -} - -gboolean TextureBrowser_expose(GtkWidget* widget, GdkEventExpose* event, TextureBrowser* textureBrowser) -{ - if(glwidget_make_current(textureBrowser->m_gl_widget) != FALSE) - { - GlobalOpenGL_debugAssertNoErrors(); - TextureBrowser_evaluateHeight(*textureBrowser); - Texture_Draw(*textureBrowser); - GlobalOpenGL_debugAssertNoErrors(); - glwidget_swap_buffers(textureBrowser->m_gl_widget); - } - return FALSE; -} - - -TextureBrowser g_TextureBrowser; - -TextureBrowser& GlobalTextureBrowser() -{ - return g_TextureBrowser; -} - -bool TextureBrowser_hideUnused() -{ - return g_TextureBrowser.m_hideUnused; -} - -void TextureBrowser_ToggleHideUnused() -{ - if(g_TextureBrowser.m_hideUnused) - { - TextureBrowser_SetHideUnused(g_TextureBrowser, false); - } - else - { - TextureBrowser_SetHideUnused(g_TextureBrowser, true); - } -} - -void TextureGroups_constructTreeModel(TextureGroups groups, GtkTreeStore* store) -{ - // put the information from the old textures menu into a treeview - GtkTreeIter iter, child; - - TextureGroups::const_iterator i = groups.begin(); - while (i != groups.end()) - { - const char* dirName = (*i).c_str(); - const char* firstUnderscore = strchr(dirName, '_'); - StringRange dirRoot (dirName, (firstUnderscore == 0) ? dirName : firstUnderscore + 1); - - TextureGroups::const_iterator next = i; - ++next; - if(firstUnderscore != 0 - && next != groups.end() - && string_equal_start((*next).c_str(), dirRoot)) - { - gtk_tree_store_append(store, &iter, NULL); - gtk_tree_store_set (store, &iter, 0, CopiedString(StringRange(dirName, firstUnderscore)).c_str(), -1); - - // keep going... - while (i != groups.end() && string_equal_start((*i).c_str(), dirRoot)) - { - gtk_tree_store_append(store, &child, &iter); - gtk_tree_store_set (store, &child, 0, (*i).c_str(), -1); - ++i; - } - } - else - { - gtk_tree_store_append(store, &iter, NULL); - gtk_tree_store_set (store, &iter, 0, dirName, -1); - ++i; - } - } -} - -TextureGroups TextureGroups_constructTreeView() -{ - TextureGroups groups; - - if (TextureBrowser_showWads()) - { - GlobalFileSystem().forEachArchive (TextureGroupsAddWadCaller (groups)); - } - else - { - // scan texture dirs and pak files only if not restricting to shaderlist - if (g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly) - { - GlobalFileSystem().forEachDirectory ("textures/", TextureGroupsAddDirectoryCaller(groups)); - } - - GlobalShaderSystem().foreachShaderName(TextureGroupsAddShaderCaller(groups)); - } - - return groups; -} - -void TextureBrowser_constructTreeStore() -{ - TextureGroups groups = TextureGroups_constructTreeView(); - GtkTreeStore* store = gtk_tree_store_new(1, G_TYPE_STRING); - TextureGroups_constructTreeModel(groups, store); - std::set::iterator iter; - - GtkTreeModel* model = GTK_TREE_MODEL(store); - - gtk_tree_view_set_model(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), model); - - g_object_unref(G_OBJECT(store)); -} - -void TextureBrowser_constructTreeStoreTags() -{ - TextureGroups groups; - GtkTreeStore* store = gtk_tree_store_new(1, G_TYPE_STRING); - GtkTreeModel* model = GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list); - - gtk_tree_view_set_model(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), model); - - g_object_unref(G_OBJECT(store)); -} - -void TreeView_onRowActivated(GtkTreeView* treeview, GtkTreePath* path, GtkTreeViewColumn* col, gpointer userdata) -{ - GtkTreeIter iter; - - GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(treeview)); - - if (gtk_tree_model_get_iter (model, &iter, path)) - { - gchar dirName[1024]; - - gchar* buffer; - gtk_tree_model_get(model, &iter, 0, &buffer, -1); - strcpy(dirName, buffer); - g_free(buffer); - - g_TextureBrowser.m_searchedTags = false; - - if(!TextureBrowser_showWads()) - strcat(dirName, "/"); - - ScopeDisableScreenUpdates disableScreenUpdates(dirName, "Loading Textures"); - TextureBrowser_ShowDirectory(GlobalTextureBrowser (), dirName); - TextureBrowser_queueDraw(GlobalTextureBrowser ()); - } -} - -void TextureBrowser_createTreeViewTree() -{ - GtkCellRenderer* renderer; - g_TextureBrowser.m_treeViewTree = GTK_WIDGET(gtk_tree_view_new()); - gtk_tree_view_set_enable_search(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), FALSE); - - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), FALSE); - g_signal_connect(g_TextureBrowser.m_treeViewTree, "row-activated", (GCallback) TreeView_onRowActivated, NULL); - - renderer = gtk_cell_renderer_text_new(); - gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), -1, "", renderer, "text", 0, NULL); - - TextureBrowser_constructTreeStore(); -} - -void TextureBrowser_addTag(); -void TextureBrowser_renameTag(); -void TextureBrowser_deleteTag(); - -void TextureBrowser_createContextMenu(GtkWidget *treeview, GdkEventButton *event) -{ - GtkWidget* menu = gtk_menu_new(); - - GtkWidget* menuitem = gtk_menu_item_new_with_label("Add tag"); - g_signal_connect(menuitem, "activate", (GCallback)TextureBrowser_addTag, treeview); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem); - - menuitem = gtk_menu_item_new_with_label("Rename tag"); - g_signal_connect(menuitem, "activate", (GCallback)TextureBrowser_renameTag, treeview); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem); - - menuitem = gtk_menu_item_new_with_label("Delete tag"); - g_signal_connect(menuitem, "activate", (GCallback)TextureBrowser_deleteTag, treeview); - gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem); - - gtk_widget_show_all(menu); - - gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, - (event != NULL) ? event->button : 0, - gdk_event_get_time((GdkEvent*)event)); -} - -gboolean TreeViewTags_onButtonPressed(GtkWidget *treeview, GdkEventButton *event) -{ - if (event->type == GDK_BUTTON_PRESS && event->button == 3) - { - GtkTreePath *path; - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); - - if(gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(treeview), event->x, event->y, &path, NULL, NULL, NULL)) - { - gtk_tree_selection_unselect_all(selection); - gtk_tree_selection_select_path(selection, path); - gtk_tree_path_free(path); - } - - TextureBrowser_createContextMenu(treeview, event); - return TRUE; - } - return FALSE; -} - -void TextureBrowser_createTreeViewTags() -{ - GtkCellRenderer* renderer; - g_TextureBrowser.m_treeViewTags = GTK_WIDGET(gtk_tree_view_new()); - gtk_tree_view_set_enable_search(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), FALSE); - - g_signal_connect(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL); - - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), FALSE); - - renderer = gtk_cell_renderer_text_new(); - gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), -1, "", renderer, "text", 0, NULL); - - TextureBrowser_constructTreeStoreTags(); -} - -GtkMenuItem* TextureBrowser_constructViewMenu(GtkMenu* menu) -{ - GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic("_View"); - - if(g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - create_check_menu_item_with_mnemonic(menu, "Hide _Unused", "ShowInUse"); - if(string_empty(g_pGameDescription->getKeyValue("show_wads"))) - { - create_check_menu_item_with_mnemonic(menu, "Hide Image Missing", "FilterNotex"); - } - menu_separator(menu); - - create_menu_item_with_mnemonic(menu, "Show All", "ShowAllTextures"); - - // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games - if(g_pGameDescription->mGameType == "doom3" || !string_empty(g_pGameDescription->getKeyValue("show_wads"))) - { - g_TextureBrowser.m_showShaders = true; - } - else - { - create_check_menu_item_with_mnemonic(menu, "Show shaders", "ToggleShowShaders"); - } - - if(g_pGameDescription->mGameType != "doom3" && string_empty(g_pGameDescription->getKeyValue("show_wads"))) - { - create_check_menu_item_with_mnemonic (menu, "Shaders Only", "ToggleShowShaderlistOnly"); - } - if(g_TextureBrowser.m_tags) - { - create_menu_item_with_mnemonic(menu, "Show Untagged", "ShowUntagged"); - } - - create_check_menu_item_with_mnemonic(menu, "Fixed Size", "FixedSize"); - - if(string_empty(g_pGameDescription->getKeyValue("show_wads"))) - { - menu_separator(menu); - g_TextureBrowser.m_shader_info_item = GTK_WIDGET(create_menu_item_with_mnemonic(menu, "Shader Info", "ShaderInfo")); - gtk_widget_set_sensitive(g_TextureBrowser.m_shader_info_item, FALSE); - } - - return textures_menu_item; -} - -GtkMenuItem* TextureBrowser_constructToolsMenu(GtkMenu* menu) -{ - GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic("_Tools"); - - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - create_menu_item_with_mnemonic(menu, "Flush & Reload Shaders", "RefreshShaders"); - create_menu_item_with_mnemonic(menu, "Find / Replace...", "FindReplaceTextures"); - - return textures_menu_item; -} - -GtkMenuItem* TextureBrowser_constructTagsMenu(GtkMenu* menu) -{ - GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic("T_ags"); - - if (g_Layout_enableDetachableMenus.m_value) - menu_tearoff (menu); - - create_menu_item_with_mnemonic(menu, "Add tag", "AddTag"); - create_menu_item_with_mnemonic(menu, "Rename tag", "RenameTag"); - create_menu_item_with_mnemonic(menu, "Delete tag", "DeleteTag"); - menu_separator(menu); - create_menu_item_with_mnemonic(menu, "Copy tags from selected", "CopyTag"); - create_menu_item_with_mnemonic(menu, "Paste tags to selected", "PasteTag"); - - return textures_menu_item; -} - -gboolean TextureBrowser_tagMoveHelper(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected) -{ - g_assert(selected != NULL); - - GtkTreeRowReference* rowref = gtk_tree_row_reference_new (model, path); - *selected = g_slist_append(*selected, rowref); - - return FALSE; -} - -void TextureBrowser_assignTags() -{ - GSList* selected = NULL; - GSList* node; - gchar* tag_assigned; - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_available_tree)); - - gtk_tree_selection_selected_foreach(selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected); - - if(selected != NULL) - { - for (node = selected; node != NULL; node = node->next) - { - GtkTreePath* path = gtk_tree_row_reference_get_path((GtkTreeRowReference*)node->data); - - if(path) - { - GtkTreeIter iter; - - if (gtk_tree_model_get_iter(GTK_TREE_MODEL(g_TextureBrowser.m_available_store), &iter, path)) - { - gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_available_store), &iter, TAG_COLUMN, &tag_assigned, -1); - if(!TagBuilder.CheckShaderTag(g_TextureBrowser.shader.c_str())) - { - // create a custom shader/texture entry - IShader* ishader = QERApp_Shader_ForName(g_TextureBrowser.shader.c_str()); - CopiedString filename = ishader->getShaderFileName(); - - if(filename.empty()) - { - // it's a texture - TagBuilder.AddShaderNode(g_TextureBrowser.shader.c_str(), CUSTOM, TEXTURE); - } else { - // it's a shader - TagBuilder.AddShaderNode(g_TextureBrowser.shader.c_str(), CUSTOM, SHADER); - } - ishader->DecRef(); - } - TagBuilder.AddShaderTag(g_TextureBrowser.shader.c_str(), (char*)tag_assigned, TAG); - - gtk_list_store_remove(g_TextureBrowser.m_available_store, &iter); - gtk_list_store_append (g_TextureBrowser.m_assigned_store, &iter); - gtk_list_store_set (g_TextureBrowser.m_assigned_store, &iter, TAG_COLUMN, (char*)tag_assigned, -1); - } - } - } - - g_slist_foreach(selected, (GFunc)gtk_tree_row_reference_free, NULL); - - // Save changes - TagBuilder.SaveXmlDoc(); - } - g_slist_free(selected); -} - -void TextureBrowser_removeTags() -{ - GSList* selected = NULL; - GSList* node; - gchar* tag; - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_assigned_tree)); - - gtk_tree_selection_selected_foreach(selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected); - - if(selected != NULL) - { - for (node = selected; node != NULL; node = node->next) - { - GtkTreePath* path = gtk_tree_row_reference_get_path((GtkTreeRowReference*)node->data); - - if (path) - { - GtkTreeIter iter; - - if (gtk_tree_model_get_iter(GTK_TREE_MODEL(g_TextureBrowser.m_assigned_store), &iter, path)) - { - gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_assigned_store), &iter, TAG_COLUMN, &tag, -1); - TagBuilder.DeleteShaderTag(g_TextureBrowser.shader.c_str(), tag); - gtk_list_store_remove(g_TextureBrowser.m_assigned_store, &iter); - } - } - } - - g_slist_foreach(selected, (GFunc)gtk_tree_row_reference_free, NULL); - - // Update the "available tags list" - BuildStoreAvailableTags(g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); - - // Save changes - TagBuilder.SaveXmlDoc(); - } - g_slist_free(selected); -} - -void TextureBrowser_buildTagList() -{ - GtkTreeIter treeIter; - gtk_list_store_clear(g_TextureBrowser.m_all_tags_list); - - std::set::iterator iter; - - for (iter = g_TextureBrowser.m_all_tags.begin(); iter != g_TextureBrowser.m_all_tags.end(); ++iter) - { - gtk_list_store_append(g_TextureBrowser.m_all_tags_list, &treeIter); - gtk_list_store_set(g_TextureBrowser.m_all_tags_list, &treeIter, TAG_COLUMN, (*iter).c_str(), -1); - } -} - -void TextureBrowser_searchTags() -{ - GSList* selected = NULL; - GSList* node; - gchar* tag; - char buffer[256]; - char tags_searched[256]; - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); - - gtk_tree_selection_selected_foreach(selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected); - - if(selected != NULL) - { - strcpy(buffer, "/root/*/*[tag='"); - strcpy(tags_searched, "[TAGS] "); - - for (node = selected; node != NULL; node = node->next) - { - GtkTreePath* path = gtk_tree_row_reference_get_path((GtkTreeRowReference*)node->data); - - if (path) - { - GtkTreeIter iter; - - if (gtk_tree_model_get_iter(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iter, path)) - { - gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iter, TAG_COLUMN, &tag, -1); - - strcat(buffer, tag); - strcat(tags_searched, tag); - if(node != g_slist_last(node)) - { - strcat(buffer, "' and tag='"); - strcat(tags_searched, ", "); - } - } - } - } - - strcat(buffer, "']"); - - g_slist_foreach(selected, (GFunc)gtk_tree_row_reference_free, NULL); - - g_TextureBrowser.m_found_shaders.clear(); // delete old list - TagBuilder.TagSearch(buffer, g_TextureBrowser.m_found_shaders); - - if(!g_TextureBrowser.m_found_shaders.empty()) // found something - { - size_t shaders_found = g_TextureBrowser.m_found_shaders.size(); - - globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n"; - ScopeDisableScreenUpdates disableScreenUpdates("Searching...", "Loading Textures"); - - std::set::iterator iter; - - for(iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++) - { - std::string path = (*iter).c_str(); - size_t pos = path.find_last_of("/", path.size()); - std::string name = path.substr(pos + 1, path.size()); - path = path.substr(0, pos + 1); - TextureDirectory_loadTexture(path.c_str(), name.c_str()); - } - } - g_TextureBrowser.m_searchedTags = true; - g_TextureBrowser_currentDirectory = tags_searched; - - g_TextureBrowser.m_nTotalHeight = 0; - TextureBrowser_setOriginY(g_TextureBrowser, 0); - TextureBrowser_heightChanged(g_TextureBrowser); - TextureBrowser_updateTitle(); - } - g_slist_free(selected); -} - -void TextureBrowser_toggleSearchButton() -{ - gint page = gtk_notebook_get_current_page(GTK_NOTEBOOK(g_TextureBrowser.m_tag_notebook)); - - if(page == 0) // tag page - { - gtk_widget_show_all(g_TextureBrowser.m_search_button); - } else { - gtk_widget_hide_all(g_TextureBrowser.m_search_button); - } -} - -void TextureBrowser_constructTagNotebook() -{ - g_TextureBrowser.m_tag_notebook = gtk_notebook_new(); - GtkWidget* labelTags = gtk_label_new("Tags"); - GtkWidget* labelTextures = gtk_label_new("Textures"); - - gtk_notebook_append_page(GTK_NOTEBOOK(g_TextureBrowser.m_tag_notebook), g_TextureBrowser.m_scr_win_tree, labelTextures); - gtk_notebook_append_page(GTK_NOTEBOOK(g_TextureBrowser.m_tag_notebook), g_TextureBrowser.m_scr_win_tags, labelTags); - - g_signal_connect(G_OBJECT(g_TextureBrowser.m_tag_notebook), "switch-page", G_CALLBACK(TextureBrowser_toggleSearchButton), NULL); - - gtk_widget_show_all(g_TextureBrowser.m_tag_notebook); -} - -void TextureBrowser_constructSearchButton() -{ - GtkTooltips* tooltips = gtk_tooltips_new(); - - GtkWidget* image = gtk_image_new_from_stock(GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR); - g_TextureBrowser.m_search_button = gtk_button_new(); - g_signal_connect(G_OBJECT(g_TextureBrowser.m_search_button), "clicked", G_CALLBACK(TextureBrowser_searchTags), NULL); - gtk_tooltips_set_tip(GTK_TOOLTIPS(tooltips), g_TextureBrowser.m_search_button, "Search with selected tags", "Search with selected tags"); - gtk_container_add(GTK_CONTAINER(g_TextureBrowser.m_search_button), image); -} - -void TextureBrowser_checkTagFile() -{ - const char SHADERTAG_FILE[] = "shadertags.xml"; - CopiedString default_filename, rc_filename; - StringOutputStream stream(256); - - stream << LocalRcPath_get(); - stream << SHADERTAG_FILE; - rc_filename = stream.c_str(); - - if(file_exists(rc_filename.c_str())) - { - g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc(rc_filename.c_str()); - - if(g_TextureBrowser.m_tags) - { - globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n"; - } - } - else - { - // load default tagfile - stream.clear(); - stream << g_pGameDescription->mGameToolsPath.c_str(); - stream << SHADERTAG_FILE; - default_filename = stream.c_str(); - - if(file_exists(default_filename.c_str())) - { - g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc(default_filename.c_str(), rc_filename.c_str()); - - if(g_TextureBrowser.m_tags) - { - globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n"; - } - } - else - { - globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n"; - } - } -} - -void TextureBrowser_SetNotex() -{ - StringOutputStream name(256); - name << GlobalRadiant().getAppPath() << "bitmaps/notex.bmp"; - g_notex = name.c_str(); - - name = NULL; - name << GlobalRadiant().getAppPath() << "bitmaps/shadernotex.bmp"; - g_shadernotex = name.c_str(); -} - -GtkWidget* TextureBrowser_constructWindow(GtkWindow* toplevel) -{ - // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider - // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't - // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing - // for the "once-the-gtk-libs-are-updated-TODO-list" :x - - TextureBrowser_checkTagFile(); - TextureBrowser_SetNotex(); - - GlobalShaderSystem().setActiveShadersChangedNotify(ReferenceCaller(g_TextureBrowser)); - - g_TextureBrowser.m_parent = toplevel; - - GtkWidget* table = gtk_table_new(3, 3, FALSE); - GtkWidget* frame_table = NULL; - GtkWidget* vbox = gtk_vbox_new(FALSE, 0); - gtk_table_attach(GTK_TABLE(table), vbox, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0); - gtk_widget_show(vbox); - - GtkWidget* menu_bar; - - { // menu bar - menu_bar = gtk_menu_bar_new(); - GtkWidget* menu_view = gtk_menu_new(); - GtkWidget* view_item = (GtkWidget*)TextureBrowser_constructViewMenu(GTK_MENU(menu_view)); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(view_item), menu_view); - gtk_menu_bar_append(GTK_MENU_BAR(menu_bar), view_item); - - GtkWidget* menu_tools = gtk_menu_new(); - GtkWidget* tools_item = (GtkWidget*)TextureBrowser_constructToolsMenu(GTK_MENU(menu_tools)); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(tools_item), menu_tools); - gtk_menu_bar_append(GTK_MENU_BAR(menu_bar), tools_item); - - gtk_table_attach(GTK_TABLE (table), menu_bar, 0, 3, 0, 1, GTK_FILL, GTK_SHRINK, 0, 0); - gtk_widget_show(menu_bar); - } - { // Texture TreeView - g_TextureBrowser.m_scr_win_tree = gtk_scrolled_window_new(NULL, NULL); - gtk_container_set_border_width(GTK_CONTAINER(g_TextureBrowser.m_scr_win_tree), 0); - - // vertical only scrolling for treeview - gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(g_TextureBrowser.m_scr_win_tree), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); - - gtk_widget_show(g_TextureBrowser.m_scr_win_tree); - - TextureBrowser_createTreeViewTree(); - - gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(g_TextureBrowser.m_scr_win_tree), GTK_WIDGET(g_TextureBrowser.m_treeViewTree)); - gtk_widget_show(GTK_WIDGET(g_TextureBrowser.m_treeViewTree)); - } - { // gl_widget scrollbar - GtkWidget* w = gtk_vscrollbar_new(GTK_ADJUSTMENT(gtk_adjustment_new (0,0,0,1,1,0))); - gtk_table_attach(GTK_TABLE (table), w, 2, 3, 1, 2, GTK_SHRINK, GTK_FILL, 0, 0); - gtk_widget_show(w); - g_TextureBrowser.m_texture_scroll = w; - - GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_TextureBrowser.m_texture_scroll)); - g_signal_connect(G_OBJECT(vadjustment), "value_changed", G_CALLBACK(TextureBrowser_verticalScroll), &g_TextureBrowser); - - widget_set_visible(g_TextureBrowser.m_texture_scroll, g_TextureBrowser.m_showTextureScrollbar); - } - { // gl_widget - g_TextureBrowser.m_gl_widget = glwidget_new(FALSE); - gtk_widget_ref(g_TextureBrowser.m_gl_widget); - - gtk_widget_set_events(g_TextureBrowser.m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK); - GTK_WIDGET_SET_FLAGS(g_TextureBrowser.m_gl_widget, GTK_CAN_FOCUS); - - gtk_table_attach_defaults(GTK_TABLE(table), g_TextureBrowser.m_gl_widget, 1, 2, 1, 2); - gtk_widget_show(g_TextureBrowser.m_gl_widget); - - g_TextureBrowser.m_sizeHandler = g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "size_allocate", G_CALLBACK(TextureBrowser_size_allocate), &g_TextureBrowser); - g_TextureBrowser.m_exposeHandler = g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "expose_event", G_CALLBACK(TextureBrowser_expose), &g_TextureBrowser); - - g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "button_press_event", G_CALLBACK(TextureBrowser_button_press), &g_TextureBrowser); - g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "button_release_event", G_CALLBACK(TextureBrowser_button_release), &g_TextureBrowser); - g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "motion_notify_event", G_CALLBACK(TextureBrowser_motion), &g_TextureBrowser); - g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "scroll_event", G_CALLBACK(TextureBrowser_scroll), &g_TextureBrowser); - } - - // tag stuff - if(g_TextureBrowser.m_tags) - { - { // fill tag GtkListStore - g_TextureBrowser.m_all_tags_list = gtk_list_store_new(N_COLUMNS, G_TYPE_STRING); - GtkTreeSortable* sortable = GTK_TREE_SORTABLE(g_TextureBrowser.m_all_tags_list); - gtk_tree_sortable_set_sort_column_id(sortable, TAG_COLUMN, GTK_SORT_ASCENDING); - - TagBuilder.GetAllTags(g_TextureBrowser.m_all_tags); - TextureBrowser_buildTagList(); - } - { // tag menu bar - GtkWidget* menu_tags = gtk_menu_new(); - GtkWidget* tags_item = (GtkWidget*)TextureBrowser_constructTagsMenu(GTK_MENU(menu_tags)); - gtk_menu_item_set_submenu(GTK_MENU_ITEM(tags_item), menu_tags); - gtk_menu_bar_append(GTK_MENU_BAR(menu_bar), tags_item); - } - { // Tag TreeView - g_TextureBrowser.m_scr_win_tags = gtk_scrolled_window_new(NULL, NULL); - gtk_container_set_border_width(GTK_CONTAINER(g_TextureBrowser.m_scr_win_tags), 0); - - // vertical only scrolling for treeview - gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(g_TextureBrowser.m_scr_win_tags), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); - - TextureBrowser_createTreeViewTags(); - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); - gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); - - gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW (g_TextureBrowser.m_scr_win_tags), GTK_WIDGET (g_TextureBrowser.m_treeViewTags)); - gtk_widget_show(GTK_WIDGET(g_TextureBrowser.m_treeViewTags)); - } - { // Texture/Tag notebook - TextureBrowser_constructTagNotebook(); - gtk_box_pack_start(GTK_BOX(vbox), g_TextureBrowser.m_tag_notebook, TRUE, TRUE, 0); - } - { // Tag search button - TextureBrowser_constructSearchButton(); - gtk_box_pack_end(GTK_BOX(vbox), g_TextureBrowser.m_search_button, FALSE, FALSE, 0); - } - { // Tag frame - frame_table = gtk_table_new(3, 3, FALSE); - - g_TextureBrowser.m_tag_frame = gtk_frame_new("Tag assignment"); - gtk_frame_set_label_align(GTK_FRAME(g_TextureBrowser.m_tag_frame), 0.5, 0.5); - gtk_frame_set_shadow_type(GTK_FRAME(g_TextureBrowser.m_tag_frame), GTK_SHADOW_NONE); - - gtk_table_attach(GTK_TABLE(table), g_TextureBrowser.m_tag_frame, 1, 3, 2, 3, GTK_FILL, GTK_SHRINK, 0, 0); - - gtk_widget_show(frame_table); - - gtk_container_add (GTK_CONTAINER(g_TextureBrowser.m_tag_frame), frame_table); - } - { // assigned tag list - GtkWidget* scrolled_win = gtk_scrolled_window_new(NULL, NULL); - gtk_container_set_border_width(GTK_CONTAINER (scrolled_win), 0); - gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolled_win), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); - - g_TextureBrowser.m_assigned_store = gtk_list_store_new(N_COLUMNS, G_TYPE_STRING); - - GtkTreeSortable* sortable = GTK_TREE_SORTABLE(g_TextureBrowser.m_assigned_store); - gtk_tree_sortable_set_sort_column_id(sortable, TAG_COLUMN, GTK_SORT_ASCENDING); - - GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); - - g_TextureBrowser.m_assigned_tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL (g_TextureBrowser.m_assigned_store)); - g_object_unref(G_OBJECT (g_TextureBrowser.m_assigned_store)); - g_signal_connect(g_TextureBrowser.m_assigned_tree, "row-activated", (GCallback) TextureBrowser_removeTags, NULL); - gtk_tree_view_set_headers_visible(GTK_TREE_VIEW (g_TextureBrowser.m_assigned_tree), FALSE); - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_assigned_tree)); - gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); - - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", TAG_COLUMN, NULL); - gtk_tree_view_append_column(GTK_TREE_VIEW (g_TextureBrowser.m_assigned_tree), column); - gtk_widget_show(g_TextureBrowser.m_assigned_tree); - - gtk_widget_show(scrolled_win); - gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW (scrolled_win), GTK_WIDGET (g_TextureBrowser.m_assigned_tree)); - - gtk_table_attach(GTK_TABLE(frame_table), scrolled_win, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0); - } - { // available tag list - GtkWidget* scrolled_win = gtk_scrolled_window_new (NULL, NULL); - gtk_container_set_border_width (GTK_CONTAINER (scrolled_win), 0); - gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); - - g_TextureBrowser.m_available_store = gtk_list_store_new (N_COLUMNS, G_TYPE_STRING); - GtkTreeSortable* sortable = GTK_TREE_SORTABLE(g_TextureBrowser.m_available_store); - gtk_tree_sortable_set_sort_column_id(sortable, TAG_COLUMN, GTK_SORT_ASCENDING); - - GtkCellRenderer* renderer = gtk_cell_renderer_text_new (); - - g_TextureBrowser.m_available_tree = gtk_tree_view_new_with_model (GTK_TREE_MODEL (g_TextureBrowser.m_available_store)); - g_object_unref (G_OBJECT (g_TextureBrowser.m_available_store)); - g_signal_connect(g_TextureBrowser.m_available_tree, "row-activated", (GCallback) TextureBrowser_assignTags, NULL); - gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (g_TextureBrowser.m_available_tree), FALSE); - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_available_tree)); - gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE); - - GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes ("", renderer, "text", TAG_COLUMN, NULL); - gtk_tree_view_append_column (GTK_TREE_VIEW (g_TextureBrowser.m_available_tree), column); - gtk_widget_show (g_TextureBrowser.m_available_tree); - - gtk_widget_show (scrolled_win); - gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scrolled_win), GTK_WIDGET (g_TextureBrowser.m_available_tree)); - - gtk_table_attach (GTK_TABLE (frame_table), scrolled_win, 2, 3, 1, 3, GTK_FILL, GTK_FILL, 0, 0); - } - { // tag arrow buttons - GtkWidget* m_btn_left = gtk_button_new(); - GtkWidget* m_btn_right = gtk_button_new(); - GtkWidget* m_arrow_left = gtk_arrow_new(GTK_ARROW_LEFT, GTK_SHADOW_OUT); - GtkWidget* m_arrow_right = gtk_arrow_new(GTK_ARROW_RIGHT, GTK_SHADOW_OUT); - gtk_container_add(GTK_CONTAINER(m_btn_left), m_arrow_left); - gtk_container_add(GTK_CONTAINER(m_btn_right), m_arrow_right); - - // workaround. the size of the tag frame depends of the requested size of the arrow buttons. - gtk_widget_set_size_request(m_arrow_left, -1, 68); - gtk_widget_set_size_request(m_arrow_right, -1, 68); - - gtk_table_attach(GTK_TABLE(frame_table), m_btn_left, 1, 2, 1, 2, GTK_SHRINK, GTK_EXPAND, 0, 0); - gtk_table_attach(GTK_TABLE(frame_table), m_btn_right, 1, 2, 2, 3, GTK_SHRINK, GTK_EXPAND, 0, 0); - - g_signal_connect(G_OBJECT (m_btn_left), "clicked", G_CALLBACK(TextureBrowser_assignTags), NULL); - g_signal_connect(G_OBJECT (m_btn_right), "clicked", G_CALLBACK(TextureBrowser_removeTags), NULL); - - gtk_widget_show(m_btn_left); - gtk_widget_show(m_btn_right); - gtk_widget_show(m_arrow_left); - gtk_widget_show(m_arrow_right); - } - { // tag fram labels - GtkWidget* m_lbl_assigned = gtk_label_new ("Assigned"); - GtkWidget* m_lbl_unassigned = gtk_label_new ("Available"); - - gtk_table_attach (GTK_TABLE (frame_table), m_lbl_assigned, 0, 1, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0); - gtk_table_attach (GTK_TABLE (frame_table), m_lbl_unassigned, 2, 3, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0); - - gtk_widget_show (m_lbl_assigned); - gtk_widget_show (m_lbl_unassigned); - } - } else { // no tag support, show the texture tree only - gtk_box_pack_start(GTK_BOX(vbox), g_TextureBrowser.m_scr_win_tree, TRUE, TRUE, 0); - } - - // TODO do we need this? - //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL); - - return table; -} - -void TextureBrowser_destroyWindow() -{ - GlobalShaderSystem().setActiveShadersChangedNotify(Callback()); - - g_signal_handler_disconnect(G_OBJECT(g_TextureBrowser.m_gl_widget), g_TextureBrowser.m_sizeHandler); - g_signal_handler_disconnect(G_OBJECT(g_TextureBrowser.m_gl_widget), g_TextureBrowser.m_exposeHandler); - - gtk_widget_unref(g_TextureBrowser.m_gl_widget); -} - -const Vector3& TextureBrowser_getBackgroundColour(TextureBrowser& textureBrowser) -{ - return textureBrowser.color_textureback; -} - -void TextureBrowser_setBackgroundColour(TextureBrowser& textureBrowser, const Vector3& colour) -{ - textureBrowser.color_textureback = colour; - TextureBrowser_queueDraw(textureBrowser); -} - -void TextureBrowser_selectionHelper(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected) -{ - g_assert(selected != NULL); - - gchar* name; - gtk_tree_model_get(model, iter, TAG_COLUMN, &name, -1); - *selected = g_slist_append(*selected, name); -} - -void TextureBrowser_shaderInfo() -{ - const char* name = TextureBrowser_GetSelectedShader(g_TextureBrowser); - IShader* shader = QERApp_Shader_ForName(name); - - DoShaderInfoDlg(name, shader->getShaderFileName(), "Shader Info"); - - shader->DecRef(); -} - -void TextureBrowser_addTag() -{ - CopiedString tag; - - EMessageBoxReturn result = DoShaderTagDlg(&tag, "Add shader tag"); - - if (result == eIDOK && !tag.empty()) - { - GtkTreeIter iter, iter2; - g_TextureBrowser.m_all_tags.insert(tag.c_str()); - gtk_list_store_append(g_TextureBrowser.m_available_store, &iter); - gtk_list_store_set(g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1); - - // Select the currently added tag in the available list - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_available_tree)); - gtk_tree_selection_select_iter(selection, &iter); - - gtk_list_store_append(g_TextureBrowser.m_all_tags_list, &iter2); - gtk_list_store_set(g_TextureBrowser.m_all_tags_list, &iter2, TAG_COLUMN, tag.c_str(), -1); - } -} - -void TextureBrowser_renameTag() -{ - /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because - gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE, - we need to count the number of selected rows first and use - gtk_tree_selection_selected_foreach() then to go through the list of selected - rows (which always containins a single row). - */ - - GSList* selected = NULL; - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); - gtk_tree_selection_selected_foreach(selection, GtkTreeSelectionForeachFunc(TextureBrowser_selectionHelper), &selected); - - if(g_slist_length(selected) == 1) // we only rename a single tag - { - CopiedString newTag; - EMessageBoxReturn result = DoShaderTagDlg(&newTag, "Rename shader tag"); - - if (result == eIDOK && !newTag.empty()) - { - GtkTreeIter iterList; - gchar* rowTag; - gchar* oldTag = (char*)selected->data; - - bool row = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterList) != 0; - - while(row) - { - gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterList, TAG_COLUMN, &rowTag, -1); - - if(strcmp(rowTag, oldTag) == 0) - { - gtk_list_store_set(g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1); - } - row = gtk_tree_model_iter_next(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterList) != 0; - } - - TagBuilder.RenameShaderTag(oldTag, newTag.c_str()); - - g_TextureBrowser.m_all_tags.erase((CopiedString)oldTag); - g_TextureBrowser.m_all_tags.insert(newTag); - - BuildStoreAssignedTags(g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser); - BuildStoreAvailableTags(g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); - } - } - else - { - gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "Select a single tag for renaming."); - } -} - -void TextureBrowser_deleteTag() -{ - GSList* selected = NULL; - - GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); - gtk_tree_selection_selected_foreach(selection, GtkTreeSelectionForeachFunc(TextureBrowser_selectionHelper), &selected); - - if(g_slist_length(selected) == 1) // we only delete a single tag - { - EMessageBoxReturn result = gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "Are you sure you want to delete the selected tag?", "Delete Tag", eMB_YESNO, eMB_ICONQUESTION); - - if(result == eIDYES) - { - GtkTreeIter iterSelected; - gchar *rowTag; - - gchar* tagSelected = (char*)selected->data; - - bool row = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterSelected) != 0; - - while(row) - { - gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterSelected, TAG_COLUMN, &rowTag, -1); - - if(strcmp(rowTag, tagSelected) == 0) - { - gtk_list_store_remove(g_TextureBrowser.m_all_tags_list, &iterSelected); - break; - } - row = gtk_tree_model_iter_next(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterSelected) != 0; - } - - TagBuilder.DeleteTag(tagSelected); - g_TextureBrowser.m_all_tags.erase((CopiedString)tagSelected); - - BuildStoreAssignedTags(g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser); - BuildStoreAvailableTags(g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); - } - } else { - gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "Select a single tag for deletion."); - } -} - -void TextureBrowser_copyTag() -{ - g_TextureBrowser.m_copied_tags.clear(); - TagBuilder.GetShaderTags(g_TextureBrowser.shader.c_str(), g_TextureBrowser.m_copied_tags); -} - -void TextureBrowser_pasteTag() -{ - IShader* ishader = QERApp_Shader_ForName(g_TextureBrowser.shader.c_str()); - CopiedString shader = g_TextureBrowser.shader.c_str(); - - if(!TagBuilder.CheckShaderTag(shader.c_str())) - { - CopiedString shaderFile = ishader->getShaderFileName(); - if(shaderFile.empty()) - { - // it's a texture - TagBuilder.AddShaderNode(shader.c_str(), CUSTOM, TEXTURE); - } - else - { - // it's a shader - TagBuilder.AddShaderNode(shader.c_str(), CUSTOM, SHADER); - } - - for(size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i) - { - TagBuilder.AddShaderTag(shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG); - } - } - else - { - for(size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i) - { - if(!TagBuilder.CheckShaderTag(shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str())) - { - // the tag doesn't exist - let's add it - TagBuilder.AddShaderTag(shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG); - } - } - } - - ishader->DecRef(); - - TagBuilder.SaveXmlDoc(); - BuildStoreAssignedTags(g_TextureBrowser.m_assigned_store, shader.c_str(), &g_TextureBrowser); - BuildStoreAvailableTags (g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); -} - -void RefreshShaders() -{ - ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Shaders"); - GlobalShaderSystem().refresh(); - UpdateAllWindows(); -} - -void TextureBrowser_ToggleShowShaders() -{ - g_TextureBrowser.m_showShaders ^= 1; - g_TextureBrowser.m_showshaders_item.update(); - TextureBrowser_queueDraw(g_TextureBrowser); -} - -void TextureBrowser_ToggleShowShaderListOnly() -{ - g_TextureBrowser_shaderlistOnly ^= 1; - g_TextureBrowser.m_showshaderlistonly_item.update(); - - TextureBrowser_constructTreeStore(); -} - -void TextureBrowser_showAll() -{ - g_TextureBrowser_currentDirectory = ""; - g_TextureBrowser.m_searchedTags = false; - TextureBrowser_heightChanged(g_TextureBrowser); - TextureBrowser_updateTitle(); -} - -void TextureBrowser_showUntagged() -{ - EMessageBoxReturn result = gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "WARNING! This function might need a lot of memory and time. Are you sure you want to use it?", "Show Untagged", eMB_YESNO, eMB_ICONWARNING); - - if(result == eIDYES) - { - g_TextureBrowser.m_found_shaders.clear(); - TagBuilder.GetUntagged(g_TextureBrowser.m_found_shaders); - std::set::iterator iter; - - ScopeDisableScreenUpdates disableScreenUpdates("Searching untagged textures...", "Loading Textures"); - - for(iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++) - { - std::string path = (*iter).c_str(); - size_t pos = path.find_last_of("/", path.size()); - std::string name = path.substr(pos + 1, path.size()); - path = path.substr(0, pos + 1); - TextureDirectory_loadTexture(path.c_str(), name.c_str()); - globalErrorStream() << path.c_str() << name.c_str() << "\n"; - } - - g_TextureBrowser_currentDirectory = "Untagged"; - TextureBrowser_queueDraw(GlobalTextureBrowser()); - TextureBrowser_heightChanged(g_TextureBrowser); - TextureBrowser_updateTitle(); - } -} - -void TextureBrowser_FixedSize() -{ - g_TextureBrowser_fixedSize ^= 1; - GlobalTextureBrowser().m_fixedsize_item.update(); - TextureBrowser_activeShadersChanged(GlobalTextureBrowser()); -} - -void TextureBrowser_FilterNotex() -{ - g_TextureBrowser_filterNotex ^= 1; - GlobalTextureBrowser().m_filternotex_item.update(); - TextureBrowser_activeShadersChanged(GlobalTextureBrowser()); -} - -void TextureBrowser_exportTitle(const StringImportCallback& importer) -{ - StringOutputStream buffer(64); - buffer << "Textures: "; - if(!string_empty(g_TextureBrowser_currentDirectory.c_str())) - { - buffer << g_TextureBrowser_currentDirectory.c_str(); - } - else - { - buffer << "all"; - } - importer(buffer.c_str()); -} - - -void TextureScaleImport(TextureBrowser& textureBrowser, int value) -{ - switch(value) - { - case 0: - TextureBrowser_setScale(textureBrowser, 10); - break; - case 1: - TextureBrowser_setScale(textureBrowser, 25); - break; - case 2: - TextureBrowser_setScale(textureBrowser, 50); - break; - case 3: - TextureBrowser_setScale(textureBrowser, 100); - break; - case 4: - TextureBrowser_setScale(textureBrowser, 200); - break; - } -} -typedef ReferenceCaller1 TextureScaleImportCaller; - -void TextureScaleExport(TextureBrowser& textureBrowser, const IntImportCallback& importer) -{ - switch(textureBrowser.m_textureScale) - { - case 10: - importer(0); - break; - case 25: - importer(1); - break; - case 50: - importer(2); - break; - case 100: - importer(3); - break; - case 200: - importer(4); - break; - } -} -typedef ReferenceCaller1 TextureScaleExportCaller; - -void TextureBrowser_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox( - "", "Texture scrollbar", - TextureBrowserImportShowScrollbarCaller(GlobalTextureBrowser()), - BoolExportCaller(GlobalTextureBrowser().m_showTextureScrollbar) - ); - { - const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" }; - page.appendCombo( - "Texture Thumbnail Scale", - STRING_ARRAY_RANGE(texture_scale), - IntImportCallback(TextureScaleImportCaller(GlobalTextureBrowser())), - IntExportCallback(TextureScaleExportCaller(GlobalTextureBrowser())) - ); - } - page.appendEntry("Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement); - { - const char* startup_shaders[] = { "None", TextureBrowser_getComonShadersName() }; - page.appendCombo("Load Shaders at Startup", reinterpret_cast(GlobalTextureBrowser().m_startupShaders), STRING_ARRAY_RANGE(startup_shaders)); - } -} -void TextureBrowser_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Texture Browser", "Texture Browser Preferences")); - TextureBrowser_constructPreferences(page); -} -void TextureBrowser_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - - -#include "preferencesystem.h" -#include "stringio.h" - -typedef ReferenceCaller1 TextureBrowserSetScaleCaller; - - - -void TextureClipboard_textureSelected(const char* shader); - -void TextureBrowser_Construct() -{ - GlobalCommands_insert("ShaderInfo", FreeCaller()); - GlobalCommands_insert("ShowUntagged", FreeCaller()); - GlobalCommands_insert("AddTag", FreeCaller()); - GlobalCommands_insert("RenameTag", FreeCaller()); - GlobalCommands_insert("DeleteTag", FreeCaller()); - GlobalCommands_insert("CopyTag", FreeCaller()); - GlobalCommands_insert("PasteTag", FreeCaller()); - GlobalCommands_insert("RefreshShaders", FreeCaller()); - GlobalToggles_insert("ShowInUse", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_hideunused_item), Accelerator('U')); - GlobalCommands_insert("ShowAllTextures", FreeCaller(), Accelerator('A', (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("ToggleTextures", FreeCaller(), Accelerator('T')); - GlobalToggles_insert("ToggleShowShaders", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_showshaders_item)); - GlobalToggles_insert("ToggleShowShaderlistOnly", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_showshaderlistonly_item)); - GlobalToggles_insert("FixedSize", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_fixedsize_item)); - GlobalToggles_insert("FilterNotex", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_filternotex_item)); - - GlobalPreferenceSystem().registerPreference("TextureScale", - makeSizeStringImportCallback(TextureBrowserSetScaleCaller(g_TextureBrowser)), - SizeExportStringCaller(g_TextureBrowser.m_textureScale) - ); - GlobalPreferenceSystem().registerPreference("TextureScrollbar", - makeBoolStringImportCallback(TextureBrowserImportShowScrollbarCaller(g_TextureBrowser)), - BoolExportStringCaller(GlobalTextureBrowser().m_showTextureScrollbar) - ); - GlobalPreferenceSystem().registerPreference("ShowShaders", BoolImportStringCaller(GlobalTextureBrowser().m_showShaders), BoolExportStringCaller(GlobalTextureBrowser().m_showShaders)); - GlobalPreferenceSystem().registerPreference("ShowShaderlistOnly", BoolImportStringCaller(g_TextureBrowser_shaderlistOnly), BoolExportStringCaller(g_TextureBrowser_shaderlistOnly)); - GlobalPreferenceSystem().registerPreference("FixedSize", BoolImportStringCaller(g_TextureBrowser_fixedSize), BoolExportStringCaller(g_TextureBrowser_fixedSize)); - GlobalPreferenceSystem().registerPreference("FilterNotex", BoolImportStringCaller(g_TextureBrowser_filterNotex), BoolExportStringCaller(g_TextureBrowser_filterNotex)); - GlobalPreferenceSystem().registerPreference("LoadShaders", IntImportStringCaller(reinterpret_cast(GlobalTextureBrowser().m_startupShaders)), IntExportStringCaller(reinterpret_cast(GlobalTextureBrowser().m_startupShaders))); - GlobalPreferenceSystem().registerPreference("WheelMouseInc", SizeImportStringCaller(GlobalTextureBrowser().m_mouseWheelScrollIncrement), SizeExportStringCaller(GlobalTextureBrowser().m_mouseWheelScrollIncrement)); - GlobalPreferenceSystem().registerPreference("SI_Colors0", Vector3ImportStringCaller(GlobalTextureBrowser().color_textureback), Vector3ExportStringCaller(GlobalTextureBrowser().color_textureback)); - - g_TextureBrowser.shader = texdef_name_default(); - - Textures_setModeChangedNotify(ReferenceCaller(g_TextureBrowser)); - - TextureBrowser_registerPreferencesPage(); - - GlobalShaderSystem().attach(g_ShadersObserver); - - TextureBrowser_textureSelected = TextureClipboard_textureSelected; -} -void TextureBrowser_Destroy() -{ - GlobalShaderSystem().detach(g_ShadersObserver); - - Textures_setModeChangedNotify(Callback()); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/texwindow.h b/misc/mediasource/extra/netradiant-src/radiant/texwindow.h deleted file mode 100644 index c5dbf33c..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/texwindow.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_TEXWINDOW_H) -#define INCLUDED_TEXWINDOW_H - -#include "math/vector.h" -#include "generic/callbackfwd.h" -#include "signal/signalfwd.h" -#include "xml/xmltextags.h" - -typedef struct _GtkWidget GtkWidget; - -class TextureBrowser; -TextureBrowser& GlobalTextureBrowser(); - -typedef struct _GtkWindow GtkWindow; -GtkWidget* TextureBrowser_constructWindow(GtkWindow* toplevel); -void TextureBrowser_destroyWindow(); - - -void TextureBrowser_ShowDirectory(TextureBrowser& textureBrowser, const char* name); -void TextureBrowser_ShowStartupShaders(TextureBrowser& textureBrowser); - -const char* TextureBrowser_GetSelectedShader(TextureBrowser& textureBrower); - -void TextureBrowser_Construct(); -void TextureBrowser_Destroy(); - -typedef Callback1 StringImportCallback; -template -class FreeCaller1; - -extern GtkWidget* g_page_textures; -void TextureBrowser_exportTitle(const StringImportCallback& importer); -typedef FreeCaller1 TextureBrowserExportTitleCaller; - -const Vector3& TextureBrowser_getBackgroundColour(TextureBrowser& textureBrowser); -void TextureBrowser_setBackgroundColour(TextureBrowser& textureBrowser, const Vector3& colour); - -void TextureBrowser_addActiveShadersChangedCallback(const SignalHandler& handler); -void TextureBrowser_addShadersRealiseCallback(const SignalHandler& handler); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/timer.cpp b/misc/mediasource/extra/netradiant-src/radiant/timer.cpp deleted file mode 100644 index 617112e1..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/timer.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "timer.h" - - -#if defined(WIN32) - -#include - -MillisecondTime MillisecondTime::current() -{ - static class Cached - { - LONGLONG m_frequency; - LONGLONG m_base; - public: - Cached() - { - QueryPerformanceFrequency((LARGE_INTEGER *) &m_frequency); - QueryPerformanceCounter((LARGE_INTEGER *) &m_base); - } - LONGLONG frequency() - { - return m_frequency; - } - LONGLONG base() - { - return m_base; - } - } cached; - - if(cached.frequency() > 0) - { - LONGLONG count; - QueryPerformanceCounter((LARGE_INTEGER *) &count); - return time_from_ticks(count - cached.base(), cached.frequency()); - } - else - { -#if 1 - return MillisecondTime(); -#else - return time_from_ticks(timeGetTime(), 1000); -#endif - } -} - - - - -#elif defined(POSIX) - -#include -#include "sys/time.h" - -MillisecondTime MillisecondTime::current() -{ - static class Cached - { - time_t m_base; - public: - Cached() - { - time(&m_base); - } - time_t base() - { - return m_base; - } - } cached; - - timeval time; - gettimeofday(&time, 0); - return MillisecondTime((time.tv_sec - cached.base()) * 1000 + time.tv_usec / 1000); -} - - - -#else - -#include - -MillisecondTime MillisecondTime::current() -{ - return time_from_ticks(std::clock(), CLOCKS_PER_SEC); -} - - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/timer.h b/misc/mediasource/extra/netradiant-src/radiant/timer.h deleted file mode 100644 index a8945200..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/timer.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 (INCLUDED_TIMER_H) -#define INCLUDED_TIMER_H - -#if 1 - -const int msec_per_sec = 1000; - -class MillisecondTime -{ - unsigned int m_milliseconds; -public: - MillisecondTime(unsigned int milliseconds) - : m_milliseconds(milliseconds) - { - } - MillisecondTime() - { - } - static MillisecondTime current(); - - unsigned int milliseconds_since(const MillisecondTime& other) const - { - return m_milliseconds - other.m_milliseconds; - } -}; - -template -inline MillisecondTime time_from_ticks(tick_type tick_count, tick_type ticks_per_sec) -{ - return MillisecondTime(static_cast(tick_count / static_cast(ticks_per_sec / msec_per_sec))); -} - -#else - -const unsigned int usec_per_sec = 1000000; - -class MillisecondTime -{ - unsigned int m_sec; - unsigned int m_usec; -public: - MillisecondTime(unsigned int sec, unsigned int usec) - : m_sec(sec), m_usec(usec) - { - } - MillisecondTime() - { - } - staticMillisecondTime current(); - - unsigned int milliseconds_since(const MillisecondTime& other) const - { - return static_cast((m_sec * static_cast(usec_per_sec) + m_usec) - - (other.m_sec * static_cast(usec_per_sec) + other.m_usec)) / 1000; - } -}; - -template -inline MillisecondTime time_from_ticks(tick_type tick_count, tick_type ticks_per_sec) -{ - return MillisecondTime(static_cast(tick_count / ticks_per_sec), - static_cast((tick_count % ticks_per_sec) * (usec_per_sec / static_cast(ticks_per_sec)))); -} - -#endif - -class Timer -{ - MillisecondTime m_start; - -public: - void start() - { - m_start = MillisecondTime::current(); - } - unsigned int elapsed_msec() - { - return MillisecondTime::current().milliseconds_since(m_start); - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/treemodel.cpp b/misc/mediasource/extra/netradiant-src/radiant/treemodel.cpp deleted file mode 100644 index cd13ecff..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/treemodel.cpp +++ /dev/null @@ -1,1551 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "treemodel.h" - -#include "debugging/debugging.h" - -#include -#include -#include -#include - -#include "iscenegraph.h" -#include "nameable.h" - -#include "generic/callback.h" -#include "scenelib.h" -#include "string/string.h" -#include "generic/reference.h" - -inline Nameable* Node_getNameable(scene::Node& node) -{ - return NodeTypeCast::cast(node); -} - -#if 0 - -#include "gtkutil/gtktreestore.h" - -template -inline void gtk_tree_model_get_pointer(GtkTreeModel* model, GtkTreeIter* iter, gint column, value_type** pointer) -{ - GValue value = GValue_default(); - gtk_tree_model_get_value(model, iter, column, &value); - *pointer = (value_type*)g_value_get_pointer(&value); -} - - -typedef GtkTreeStore GraphTreeModel; - -GtkTreeStore* graph_tree_model_new(graph_type* graph) -{ - return gtk_tree_store_new(2, G_TYPE_POINTER, G_TYPE_POINTER); -} - -void graph_tree_model_delete(GraphTreeModel* model) -{ - g_object_unref(G_OBJECT(model)); -} - - -bool graph_tree_model_subtree_find_node(GraphTreeModel* model, GtkTreeIter* parent, const scene::Node& node, GtkTreeIter* iter) -{ - for(gboolean success = gtk_tree_model_iter_children(GTK_TREE_MODEL(model), iter, parent); - success != FALSE; - success = gtk_tree_model_iter_next(GTK_TREE_MODEL(model), iter)) - { - scene::Node* current; - gtk_tree_model_get_pointer(GTK_TREE_MODEL(model), iter, 0, ¤t); - if(current == node) - { - return true; - } - } - return false; -} - -typedef GtkTreeIter DoubleGtkTreeIter[2]; - -bool graph_tree_model_find_top(GraphTreeModel* model, const scene::Path& path, GtkTreeIter& iter) -{ - int swap = 0; - GtkTreeIter* parent_pointer = NULL; - GtkTreeIter parent; - for(scene::Path::const_iterator i = path.begin(); i != path.end(); ++i) - { - if(!graph_tree_model_subtree_find_node(model, parent_pointer, *i, &iter)) - { - return false; - } - parent = iter; - parent_pointer = &parent; - } - return true; -} - -bool graph_tree_model_find_parent(GraphTreeModel* model, const scene::Path& path, GtkTreeIter& iter) -{ - int swap = 0; - GtkTreeIter* parent_pointer = NULL; - ASSERT_MESSAGE(path.size() > 1, "path too short"); - for(scene::Path::const_iterator i = path.begin(); i != path.end()-1; ++i) - { - GtkTreeIter child; - if(!graph_tree_model_subtree_find_node(model, parent_pointer, *i, &child)) - { - return false; - } - iter = child; - parent_pointer = &iter; - } - return true; -} - -void node_attach_name_changed_callback(scene::Node& node, const Callback& callback) -{ - if(node != 0) - { - Nameable* nameable = Node_getNameable(node); - if(nameable != 0) - { - nameable->attach(callback); - } - } -} -void node_detach_name_changed_callback(scene::Node& node, const Callback& callback) -{ - if(node != 0) - { - Nameable* nameable = Node_getNameable(node); - if(nameable != 0) - { - nameable->detach(callback); - } - } -} - -GraphTreeModel* scene_graph_get_tree_model(); // temp hack - -void graph_tree_model_row_changed(const scene::Instance& instance) -{ - GraphTreeModel* model = scene_graph_get_tree_model(); - - GtkTreeIter child; - ASSERT_MESSAGE(graph_tree_model_find_top(model, instance.path(), child), "RUNTIME ERROR"); - - gtk_tree_store_set(GTK_TREE_STORE(model), &child, 0, instance.path().top(), -1); -} - -void graph_tree_model_row_inserted(GraphTreeModel* model, const scene::Instance& instance) -{ - GtkTreeIter parent; - GtkTreeIter* parent_pointer = NULL; - if(instance.path().size() != 1) - { - ASSERT_MESSAGE(graph_tree_model_find_parent(model, instance.path(), parent), "RUNTIME ERROR"); - parent_pointer = &parent; - } - - gpointer node = instance.path().top(); - gconstpointer selectable = Instance_getSelectable(instance); - - GtkTreeIter child; - gtk_tree_store_append(GTK_TREE_STORE(model), &child, parent_pointer); - gtk_tree_store_set(GTK_TREE_STORE(model), &child, 0, node, 1, selectable, -1); - - node_attach_name_changed_callback(instance.path().top(), ConstReferenceCaller(instance)); -} - -void graph_tree_model_row_deleted(GraphTreeModel* model, const scene::Instance& instance) -{ - GtkTreeIter child; - ASSERT_MESSAGE(graph_tree_model_find_top(model, instance.path(), child), "RUNTIME ERROR"); - - node_detach_name_changed_callback(instance.path().top(), ConstReferenceCaller(instance)); - - gtk_tree_store_remove(GTK_TREE_STORE(model), &child); -} - -#elif 0 - -const char* node_get_name(scene::Node& node); - -typedef scene::Node* NodePointer; - -class NodeNameLess -{ -public: - bool operator()(const NodePointer& self, const NodePointer& other) const - { - if(self == 0) - { - return true; - } - if(other == 0) - { - return false; - } - int result = string_compare(node_get_name(self), node_get_name(other)); - if(result == 0) - { - return self < other; - } - return result < 0; - } -}; - -class PathNameLess -{ -public: - bool operator()(const PathConstReference& self, const PathConstReference& other) const - { - return std::lexicographical_compare(self.get().begin(), self.get().end(), other.get().begin(), other.get().end(), NodeNameLess()); - } -}; - -typedef std::map graph_type; - -struct GraphTreeModel -{ - GObject parent; - - graph_type* graph; -}; - -struct GraphTreeModelClass -{ - GObjectClass parent_class; -}; - -#define GRAPH_TREE_MODEL(p) (reinterpret_cast(p)) - -static GtkTreeModelFlags graph_tree_model_get_flags (GtkTreeModel* tree_model) -{ - return GTK_TREE_MODEL_ITERS_PERSIST; -} - -static gint graph_tree_model_get_n_columns (GtkTreeModel* tree_model) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeModel* graph_tree_model = (GraphTreeModel*) tree_model; - - return 2; -} - -static const gint c_stamp = 0xabcdef; - -inline graph_type::iterator graph_iterator_read_tree_iter(GtkTreeIter* iter) -{ - ASSERT_MESSAGE(iter != 0, "tree model error"); - ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); - ASSERT_MESSAGE(iter->stamp == c_stamp, "tree model error"); - return *reinterpret_cast(&iter->user_data); -} - -inline void graph_iterator_write_tree_iter(graph_type::iterator i, GtkTreeIter* iter) -{ - ASSERT_MESSAGE(iter != 0, "tree model error"); - iter->stamp = c_stamp; - *reinterpret_cast(&iter->user_data) = i; - ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); -} - -static GType graph_tree_model_get_column_type (GtkTreeModel *tree_model, gint index) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeModel *graph_tree_model = (GraphTreeModel *) tree_model; - - return G_TYPE_POINTER; -} - -static gboolean graph_tree_model_get_iter(GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreePath* path) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - gint* indices = gtk_tree_path_get_indices (path); - gint depth = gtk_tree_path_get_depth (path); - - g_return_val_if_fail (depth > 0, FALSE); - - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - - if(graph.empty()) - return FALSE; - - GtkTreeIter tmp; - GtkTreeIter* parent = 0; - - for(gint i = 0; i < depth; i++) - { - if (! gtk_tree_model_iter_nth_child (tree_model, iter, parent, indices[i])) - return FALSE; - tmp = *iter; - parent = &tmp; - } - - return TRUE; -} - -static GtkTreePath* graph_tree_model_get_path(GtkTreeModel* tree_model, GtkTreeIter* iter) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - graph_type::iterator i = graph_iterator_read_tree_iter(iter); - - GtkTreePath* path = gtk_tree_path_new(); - - for(std::size_t depth = (*i).first.get().size(); depth != 0; --depth) - { - std::size_t index = 0; - - while(i != graph.begin() && (*i).first.get().size() >= depth) - { - --i; - if((*i).first.get().size() == depth) - ++index; - } - - gtk_tree_path_prepend_index(path, index); - } - - return path; -} - - -static void graph_tree_model_get_value (GtkTreeModel *tree_model, GtkTreeIter *iter, gint column, GValue *value) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - ASSERT_MESSAGE(column == 0 || column == 1, "tree model error"); - - graph_type::iterator i = graph_iterator_read_tree_iter(iter); - - g_value_init (value, G_TYPE_POINTER); - - if(column == 0) - g_value_set_pointer(value, reinterpret_cast((*i).first.get().top())); - else - g_value_set_pointer(value, reinterpret_cast(Instance_getSelectable(*(*i).second))); -} - -static gboolean graph_tree_model_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - graph_type::iterator i = graph_iterator_read_tree_iter(iter); - std::size_t depth = (*i).first.get().size(); - - ++i; - - while(i != graph.end() && (*i).first.get().size() > depth) - { - ++i; - } - - if(i == graph.end() || (*i).first.get().size() != depth) - { - return FALSE; - } - - graph_iterator_write_tree_iter(i, iter); - - return TRUE; -} - -static gboolean graph_tree_model_iter_children (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - graph_type::iterator i = (parent == 0) ? graph.begin() : graph_iterator_read_tree_iter(parent); - std::size_t depth = (parent == 0) ? 1 : (*i).first.get().size() + 1; - - if(parent != 0) - ++i; - - if(i != graph.end() && (*i).first.get().size() == depth) - { - graph_iterator_write_tree_iter(i, iter); - return TRUE; - } - - return FALSE; -} - -static gboolean graph_tree_model_iter_has_child (GtkTreeModel *tree_model, GtkTreeIter *iter) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - graph_type::iterator i = graph_iterator_read_tree_iter(iter); - std::size_t depth = (*i).first.get().size() + 1; - - return ++i != graph.end() && (*i).first.get().size() == depth; -} - -static gint graph_tree_model_iter_n_children (GtkTreeModel *tree_model, GtkTreeIter *parent) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - graph_type::iterator i = (parent == 0) ? graph.begin() : graph_iterator_read_tree_iter(parent); - std::size_t depth = (parent == 0) ? 1 : (*i).first.get().size() + 1; - - if(parent != 0) - ++i; - - gint count = 0; - while(i != graph.end() && (*i).first.get().size() >= depth) - { - ++count; - ++i; - } - - return count; -} - -static gboolean graph_tree_model_iter_nth_child (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent, gint n) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - graph_type::iterator i = (parent == 0) ? graph.begin() : graph_iterator_read_tree_iter(parent); - std::size_t depth = (parent == 0) ? 1 : (*i).first.get().size() + 1; - - if(parent != 0) - ++i; - - while(i != graph.end() && (*i).first.get().size() >= depth) - { - if((*i).first.get().size() == depth && n-- == 0) - { - graph_iterator_write_tree_iter(i, iter); - return TRUE; - } - ++i; - } - - return FALSE; -} - -static gboolean graph_tree_model_iter_parent(GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *child) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; - graph_type::iterator i = graph_iterator_read_tree_iter(child); - std::size_t depth = (*i).first.get().size(); - if(depth == 1) - { - return FALSE; - } - else - { - do - { - --i; - } - while((*i).first.get().size() >= depth); - graph_iterator_write_tree_iter(i, iter); - return TRUE; - } -} - -static GObjectClass *g_parent_class = 0; - -static void graph_tree_model_init (GraphTreeModel *graph_tree_model) -{ - graph_tree_model->graph = 0; -} - -static void graph_tree_model_finalize(GObject* object) -{ - GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(object); - - /* must chain up */ - (* g_parent_class->finalize) (object); -} - -static void graph_tree_model_class_init (GraphTreeModelClass *class_) -{ - GObjectClass *object_class; - - g_parent_class = (GObjectClass*)g_type_class_peek_parent (class_); - object_class = (GObjectClass *) class_; - - object_class->finalize = graph_tree_model_finalize; -} - -static void graph_tree_model_tree_model_init (GtkTreeModelIface *iface) -{ - iface->get_flags = graph_tree_model_get_flags; - iface->get_n_columns = graph_tree_model_get_n_columns; - iface->get_column_type = graph_tree_model_get_column_type; - iface->get_iter = graph_tree_model_get_iter; - iface->get_path = graph_tree_model_get_path; - iface->get_value = graph_tree_model_get_value; - iface->iter_next = graph_tree_model_iter_next; - iface->iter_children = graph_tree_model_iter_children; - iface->iter_has_child = graph_tree_model_iter_has_child; - iface->iter_n_children = graph_tree_model_iter_n_children; - iface->iter_nth_child = graph_tree_model_iter_nth_child; - iface->iter_parent = graph_tree_model_iter_parent; -} - -static gboolean graph_tree_model_row_draggable(GtkTreeDragSource *drag_source, GtkTreePath *path) -{ -#ifdef _DEBUG - gint depth = gtk_tree_path_get_depth(path); -#endif - return gtk_tree_path_get_depth(path) > 1; -} - -static gboolean graph_tree_model_drag_data_delete(GtkTreeDragSource *drag_source, GtkTreePath *path) -{ - GtkTreeIter iter; - - if(gtk_tree_model_get_iter(GTK_TREE_MODEL(drag_source), &iter, path)) - { - graph_type::iterator i = graph_iterator_read_tree_iter(&iter); - Path_deleteTop((*i).first); - return TRUE; - } - else - { - return FALSE; - } -} - -static gboolean graph_tree_model_drag_data_get (GtkTreeDragSource *drag_source, GtkTreePath *path, GtkSelectionData *selection_data) -{ - if(gtk_tree_set_row_drag_data(selection_data, GTK_TREE_MODEL(drag_source), path)) - { - return TRUE; - } - else - { - /* FIXME handle text targets at least. */ - } - - return FALSE; -} - -static void graph_tree_model_drag_source_init (GtkTreeDragSourceIface *iface) -{ - iface->row_draggable = graph_tree_model_row_draggable; - iface->drag_data_delete = graph_tree_model_drag_data_delete; - iface->drag_data_get = graph_tree_model_drag_data_get; -} - -static gboolean graph_tree_model_drag_data_received (GtkTreeDragDest *drag_dest, GtkTreePath *dest, GtkSelectionData *selection_data) -{ - GtkTreeModel *tree_model = GTK_TREE_MODEL (drag_dest); - - GtkTreeModel *src_model = 0; - GtkTreePath *src_path = 0; - if(gtk_tree_get_row_drag_data(selection_data, &src_model, &src_path) - && src_model == tree_model) - { - /* Copy the given row to a new position */ - GtkTreeIter iter; - - if(gtk_tree_model_get_iter(src_model, &iter, src_path)) - { - int bleh = 0; - } - } - else - { - /* FIXME maybe add some data targets eventually, or handle text - * targets in the simple case. - */ - } - - return FALSE; -} - -static gboolean graph_tree_model_row_drop_possible(GtkTreeDragDest *drag_dest, GtkTreePath *dest_path, GtkSelectionData *selection_data) -{ - gboolean retval = FALSE; - - GtkTreeModel *src_model = 0; - GtkTreePath *src_path = 0; - if(gtk_tree_get_row_drag_data(selection_data, &src_model, &src_path) != FALSE) - { - /* can only drag to ourselves */ - if(src_model == GTK_TREE_MODEL(drag_dest)) - { - /* Can't drop into ourself. */ - if(!gtk_tree_path_is_ancestor(src_path, dest_path)) - { - /* Can't drop if dest_path's parent doesn't exist */ - if (gtk_tree_path_get_depth (dest_path) > 1) - { - GtkTreePath* tmp = gtk_tree_path_copy (dest_path); - gtk_tree_path_up (tmp); - - GtkTreeIter iter; - retval = gtk_tree_model_get_iter (GTK_TREE_MODEL (drag_dest), &iter, tmp); - - gtk_tree_path_free (tmp); - } - } - } - - gtk_tree_path_free (src_path); - } - - return retval; -} - -static void graph_tree_model_drag_dest_init (GtkTreeDragDestIface *iface) -{ - iface->drag_data_received = graph_tree_model_drag_data_received; - iface->row_drop_possible = graph_tree_model_row_drop_possible; -} - -GType graph_tree_model_get_type (void) -{ - static GType graph_tree_model_type = 0; - - if (!graph_tree_model_type) - { - static const GTypeInfo graph_tree_model_info = - { - sizeof (GraphTreeModelClass), - 0, /* base_init */ - 0, /* base_finalize */ - (GClassInitFunc) graph_tree_model_class_init, - 0, /* class_finalize */ - 0, /* class_data */ - sizeof (GraphTreeModel), - 0, /* n_preallocs */ - (GInstanceInitFunc) graph_tree_model_init - }; - - static const GInterfaceInfo tree_model_info = - { - (GInterfaceInitFunc) graph_tree_model_tree_model_init, - 0, - 0 - }; - - static const GInterfaceInfo drag_source_info = - { - (GInterfaceInitFunc) graph_tree_model_drag_source_init, - 0, - 0 - }; - - static const GInterfaceInfo drag_dest_info = - { - (GInterfaceInitFunc) graph_tree_model_drag_dest_init, - 0, - 0 - }; - - graph_tree_model_type = g_type_register_static (G_TYPE_OBJECT, "GraphTreeModel", - &graph_tree_model_info, (GTypeFlags)0); - - g_type_add_interface_static (graph_tree_model_type, - GTK_TYPE_TREE_MODEL, - &tree_model_info); - g_type_add_interface_static (graph_tree_model_type, - GTK_TYPE_TREE_DRAG_SOURCE, - &drag_source_info); - g_type_add_interface_static (graph_tree_model_type, - GTK_TYPE_TREE_DRAG_DEST, - &drag_dest_info); - } - - return graph_tree_model_type; -} - -GraphTreeModel* graph_tree_model_new() -{ - GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(g_object_new (graph_tree_model_get_type(), 0)); - - graph_tree_model->graph = new graph_type; - - return graph_tree_model; -} - -void graph_tree_model_delete(GraphTreeModel* model) -{ - delete model->graph; - g_object_unref(G_OBJECT(model)); -} - - -class TempNameable : public Nameable -{ - const char* m_name; -public: - TempNameable(const char* name) : m_name(name) - { - } - const char* name() const - { - return m_name; - } - void attach(const NameCallback& callback) - { - } - void detach(const NameCallback& callback) - { - } -}; - -void node_attach_name_changed_callback(scene::Node& node, const NameCallback& callback) -{ - if(&node != 0) - { - Nameable* nameable = Node_getNameable(node); - if(nameable != 0) - { - nameable->attach(callback); - } - } -} -void node_detach_name_changed_callback(scene::Node& node, const NameCallback& callback) -{ - if(&node != 0) - { - Nameable* nameable = Node_getNameable(node); - if(nameable != 0) - { - nameable->detach(callback); - } - } -} - -GraphTreeModel* scene_graph_get_tree_model(); // temp hack - -void graph_tree_model_row_inserted(GraphTreeModel* model, graph_type::iterator i) -{ - GtkTreeIter iter; - graph_iterator_write_tree_iter(i, &iter); - - GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); - - gint depth = gtk_tree_path_get_depth(tree_path); - gint* indices = gtk_tree_path_get_indices(tree_path); - - gtk_tree_model_row_inserted(GTK_TREE_MODEL(model), tree_path, &iter); - - gtk_tree_path_free(tree_path); -} - -void graph_tree_model_row_deleted(GraphTreeModel* model, graph_type::iterator i) -{ - GtkTreeIter iter; - graph_iterator_write_tree_iter(i, &iter); - - GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); - - gtk_tree_model_row_deleted(GTK_TREE_MODEL(model), tree_path); - - gtk_tree_path_free(tree_path); -} - -#include "generic/referencecounted.h" - -void graph_tree_model_set_name(const scene::Instance& instance, const char* name) -{ - GraphTreeModel* model = scene_graph_get_tree_model(); - - if(string_empty(name)) // hack! - { - graph_type::iterator i = model->graph->find(PathConstReference(instance.path())); - ASSERT_MESSAGE(i != model->graph->end(), "ERROR"); - - graph_tree_model_row_deleted(model, i); - - model->graph->erase(i); - } - else - { - graph_type::iterator i = model->graph->insert(graph_type::value_type(PathConstReference(instance.path()), &const_cast(instance))).first; - - graph_tree_model_row_inserted(model, i); - } -} - -void graph_tree_model_insert(GraphTreeModel* model, const scene::Instance& instance) -{ - graph_type::iterator i = model->graph->insert(graph_type::value_type(PathConstReference(instance.path()), &const_cast(instance))).first; - - graph_tree_model_row_inserted(model, i); - - node_attach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); -} - -void graph_tree_model_erase(GraphTreeModel* model, const scene::Instance& instance) -{ - node_detach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); - - graph_type::iterator i = model->graph->find(PathConstReference(instance.path())); - ASSERT_MESSAGE(i != model->graph->end(), "ERROR"); - - graph_tree_model_row_deleted(model, i); - - model->graph->erase(i); -} - -#elif 1 - -class GraphTreeNode; -void graph_tree_model_row_changed(GraphTreeNode& node); - -class GraphTreeNode -{ - typedef std::map, GraphTreeNode*> ChildNodes; - ChildNodes m_childnodes; -public: - Reference m_instance; - GraphTreeNode* m_parent; - - typedef ChildNodes::iterator iterator; - typedef ChildNodes::key_type key_type; - typedef ChildNodes::value_type value_type; - typedef ChildNodes::size_type size_type; - - GraphTreeNode(scene::Instance& instance) : m_instance(instance), m_parent(0) - { - m_instance.get().setChildSelectedChangedCallback(RowChangedCaller(*this)); - } - ~GraphTreeNode() - { - m_instance.get().setChildSelectedChangedCallback(Callback()); - ASSERT_MESSAGE(empty(), "GraphTreeNode::~GraphTreeNode: memory leak"); - } - - iterator begin() - { - return m_childnodes.begin(); - } - iterator end() - { - return m_childnodes.end(); - } - - size_type size() const - { - return m_childnodes.size(); - } - bool empty() const - { - return m_childnodes.empty(); - } - - iterator insert(const value_type& value) - { - iterator i = m_childnodes.insert(value).first; - (*i).second->m_parent = this; - return i; - } - void erase(iterator i) - { - m_childnodes.erase(i); - } - iterator find(const key_type& key) - { - return m_childnodes.find(key); - } - - void swap(GraphTreeNode& other) - { - std::swap(m_parent, other.m_parent); - std::swap(m_childnodes, other.m_childnodes); - std::swap(m_instance, other.m_instance); - } - - void rowChanged() - { - graph_tree_model_row_changed(*this); - } - typedef MemberCaller RowChangedCaller; -}; - -struct GraphTreeModel -{ - GObject parent; - - GraphTreeNode* m_graph; -}; - -struct GraphTreeModelClass -{ - GObjectClass parent_class; -}; - -#define GRAPH_TREE_MODEL(p) (reinterpret_cast(p)) - -static GtkTreeModelFlags graph_tree_model_get_flags (GtkTreeModel* tree_model) -{ - return GTK_TREE_MODEL_ITERS_PERSIST; -} - -static gint graph_tree_model_get_n_columns (GtkTreeModel* tree_model) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - //GraphTreeModel* graph_tree_model = (GraphTreeModel*) tree_model; - - return 2; -} - -static const gint c_stamp = 0xabcdef; - -inline GraphTreeNode::iterator graph_iterator_read_tree_iter(GtkTreeIter* iter) -{ - ASSERT_MESSAGE(iter != 0, "tree model error"); - ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); - ASSERT_MESSAGE(iter->stamp == c_stamp, "tree model error"); - return *reinterpret_cast(&iter->user_data); -} - -inline void graph_iterator_write_tree_iter(GraphTreeNode::iterator i, GtkTreeIter* iter) -{ - ASSERT_MESSAGE(iter != 0, "tree model error"); - iter->stamp = c_stamp; - *reinterpret_cast(&iter->user_data) = i; - ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); -} - -static GType graph_tree_model_get_column_type (GtkTreeModel *tree_model, gint index) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - //GraphTreeModel *graph_tree_model = (GraphTreeModel *) tree_model; - - return G_TYPE_POINTER; -} - -static gboolean graph_tree_model_get_iter(GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreePath* path) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - gint* indices = gtk_tree_path_get_indices (path); - gint depth = gtk_tree_path_get_depth (path); - - g_return_val_if_fail (depth > 0, FALSE); - - GraphTreeNode* graph = GRAPH_TREE_MODEL(tree_model)->m_graph; - - if(graph->empty()) - return FALSE; - - GtkTreeIter tmp; - GtkTreeIter* parent = 0; - - for(gint i = 0; i < depth; i++) - { - if (! gtk_tree_model_iter_nth_child (tree_model, iter, parent, indices[i])) - return FALSE; - tmp = *iter; - parent = &tmp; - } - - return TRUE; -} - -static GtkTreePath* graph_tree_model_get_path(GtkTreeModel* tree_model, GtkTreeIter* iter) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeNode* graph = GRAPH_TREE_MODEL(tree_model)->m_graph; - - GtkTreePath* path = gtk_tree_path_new(); - - for(GraphTreeNode* node = (*graph_iterator_read_tree_iter(iter)).second; node != graph; node = node->m_parent) - { - std::size_t index = 0; - for(GraphTreeNode::iterator i = node->m_parent->begin(); i != node->m_parent->end(); ++i, ++index) - { - if((*i).second == node) - { - gtk_tree_path_prepend_index(path, gint(index)); - break; - } - } - ASSERT_MESSAGE(index != node->m_parent->size(), "error resolving tree path"); - } - - return path; -} - - -static void graph_tree_model_get_value (GtkTreeModel *tree_model, GtkTreeIter *iter, gint column, GValue *value) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - ASSERT_MESSAGE(column == 0 || column == 1, "tree model error"); - - GraphTreeNode::iterator i = graph_iterator_read_tree_iter(iter); - - g_value_init (value, G_TYPE_POINTER); - - if(column == 0) - { - g_value_set_pointer(value, reinterpret_cast((*i).first.second)); - } - else - { - g_value_set_pointer(value, reinterpret_cast(&(*i).second->m_instance.get())); - } -} - -static gboolean graph_tree_model_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeNode::iterator i = graph_iterator_read_tree_iter(iter); - GraphTreeNode& parent = *(*i).second->m_parent; - - ASSERT_MESSAGE(i != parent.end(), "RUNTIME ERROR"); - - if(++i == parent.end()) - { - return FALSE; - } - - graph_iterator_write_tree_iter(i, iter); - - return TRUE; -} - -static gboolean graph_tree_model_iter_children (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeNode& node = (parent == 0) ? *GRAPH_TREE_MODEL(tree_model)->m_graph : *(*graph_iterator_read_tree_iter(parent)).second; - if(!node.empty()) - { - graph_iterator_write_tree_iter(node.begin(), iter); - return TRUE; - } - - return FALSE; -} - -static gboolean graph_tree_model_iter_has_child (GtkTreeModel *tree_model, GtkTreeIter *iter) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeNode& node = *(*graph_iterator_read_tree_iter(iter)).second; - return !node.empty(); -} - -static gint graph_tree_model_iter_n_children (GtkTreeModel *tree_model, GtkTreeIter *parent) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeNode& node = (parent == 0) ? *GRAPH_TREE_MODEL(tree_model)->m_graph : *(*graph_iterator_read_tree_iter(parent)).second; - return static_cast(node.size()); -} - -static gboolean graph_tree_model_iter_nth_child (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent, gint n) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeNode& node = (parent == 0) ? *GRAPH_TREE_MODEL(tree_model)->m_graph : *(*graph_iterator_read_tree_iter(parent)).second; - if(static_cast(n) < node.size()) - { - GraphTreeNode::iterator i = node.begin(); - std::advance(i, n); - graph_iterator_write_tree_iter(i, iter); - return TRUE; - } - - return FALSE; -} - -static gboolean graph_tree_model_iter_parent(GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *child) -{ - ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); - GraphTreeNode& node = *(*graph_iterator_read_tree_iter(child)).second; - if(node.m_parent != GRAPH_TREE_MODEL(tree_model)->m_graph) - { - GraphTreeNode& parentParent = *node.m_parent->m_parent; - for(GraphTreeNode::iterator i = parentParent.begin(); i != parentParent.end(); ++i) - { - if((*i).second == node.m_parent) - { - graph_iterator_write_tree_iter(i, iter); - return TRUE; - } - } - } - return FALSE; -} - -static GObjectClass *g_parent_class = 0; - -namespace -{ - scene::Node* g_null_node = 0; -} - -class NullInstance : public scene::Instance -{ -public: - NullInstance() : scene::Instance(scene::Path(makeReference(*g_null_node)), 0, 0, Static::instance()) - { - } -}; - -namespace -{ - NullInstance g_null_instance; -} - -static void graph_tree_model_init (GraphTreeModel *graph_tree_model) -{ - graph_tree_model->m_graph = new GraphTreeNode(g_null_instance); -} - -static void graph_tree_model_finalize(GObject* object) -{ - GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(object); - - delete graph_tree_model->m_graph; - - /* must chain up */ - (* g_parent_class->finalize) (object); -} - -static void graph_tree_model_class_init (GraphTreeModelClass *class_) -{ - GObjectClass *object_class; - - g_parent_class = (GObjectClass*)g_type_class_peek_parent (class_); - object_class = (GObjectClass *) class_; - - object_class->finalize = graph_tree_model_finalize; -} - -static void graph_tree_model_tree_model_init (GtkTreeModelIface *iface) -{ - iface->get_flags = graph_tree_model_get_flags; - iface->get_n_columns = graph_tree_model_get_n_columns; - iface->get_column_type = graph_tree_model_get_column_type; - iface->get_iter = graph_tree_model_get_iter; - iface->get_path = graph_tree_model_get_path; - iface->get_value = graph_tree_model_get_value; - iface->iter_next = graph_tree_model_iter_next; - iface->iter_children = graph_tree_model_iter_children; - iface->iter_has_child = graph_tree_model_iter_has_child; - iface->iter_n_children = graph_tree_model_iter_n_children; - iface->iter_nth_child = graph_tree_model_iter_nth_child; - iface->iter_parent = graph_tree_model_iter_parent; -} - -GType graph_tree_model_get_type (void) -{ - static GType graph_tree_model_type = 0; - - if (!graph_tree_model_type) - { - static const GTypeInfo graph_tree_model_info = - { - sizeof (GraphTreeModelClass), - 0, /* base_init */ - 0, /* base_finalize */ - (GClassInitFunc) graph_tree_model_class_init, - 0, /* class_finalize */ - 0, /* class_data */ - sizeof (GraphTreeModel), - 0, /* n_preallocs */ - (GInstanceInitFunc) graph_tree_model_init, - 0 - }; - - static const GInterfaceInfo tree_model_info = - { - (GInterfaceInitFunc) graph_tree_model_tree_model_init, - 0, - 0 - }; - - graph_tree_model_type = g_type_register_static (G_TYPE_OBJECT, "GraphTreeModel", - &graph_tree_model_info, (GTypeFlags)0); - - g_type_add_interface_static (graph_tree_model_type, - GTK_TYPE_TREE_MODEL, - &tree_model_info); - } - - return graph_tree_model_type; -} - -GraphTreeModel* graph_tree_model_new() -{ - GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(g_object_new (graph_tree_model_get_type(), 0)); - - return graph_tree_model; -} - -void graph_tree_model_delete(GraphTreeModel* model) -{ - g_object_unref(G_OBJECT(model)); -} - -void graph_tree_model_row_changed(GraphTreeModel* model, GraphTreeNode::iterator i) -{ - GtkTreeIter iter; - graph_iterator_write_tree_iter(i, &iter); - - GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); - - gtk_tree_model_row_changed(GTK_TREE_MODEL(model), tree_path, &iter); - - gtk_tree_path_free(tree_path); -} - -void graph_tree_model_row_inserted(GraphTreeModel* model, GraphTreeNode::iterator i) -{ - GtkTreeIter iter; - graph_iterator_write_tree_iter(i, &iter); - - GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); - - gtk_tree_model_row_inserted(GTK_TREE_MODEL(model), tree_path, &iter); - - gtk_tree_path_free(tree_path); -} - -void graph_tree_model_row_deleted(GraphTreeModel* model, GraphTreeNode::iterator i) -{ - GtkTreeIter iter; - graph_iterator_write_tree_iter(i, &iter); - - GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); - - gtk_tree_model_row_deleted(GTK_TREE_MODEL(model), tree_path); - - gtk_tree_path_free(tree_path); -} - -void graph_tree_model_row_inserted(GraphTreeModel& model, GraphTreeNode::iterator i) -{ - graph_tree_model_row_inserted(&model, i); -} - -void graph_tree_model_row_deleted(GraphTreeModel& model, GraphTreeNode::iterator i) -{ - graph_tree_model_row_deleted(&model, i); -} - -const char* node_get_name(scene::Node& node); - -const char* node_get_name_safe(scene::Node& node) -{ - if(&node == 0) - { - return ""; - } - return node_get_name(node); -} - -GraphTreeNode* graph_tree_model_find_parent(GraphTreeModel* model, const scene::Path& path) -{ - GraphTreeNode* parent = model->m_graph; - for(scene::Path::const_iterator i = path.begin(); i != path.end()-1; ++i) - { - GraphTreeNode::iterator child = parent->find(GraphTreeNode::key_type(node_get_name_safe((*i).get()), (*i).get_pointer())); - ASSERT_MESSAGE(child != parent->end(), "ERROR"); - parent = (*child).second; - } - return parent; -} - -void node_attach_name_changed_callback(scene::Node& node, const NameCallback& callback) -{ - if(&node != 0) - { - Nameable* nameable = Node_getNameable(node); - if(nameable != 0) - { - nameable->attach(callback); - } - } -} -void node_detach_name_changed_callback(scene::Node& node, const NameCallback& callback) -{ - if(&node != 0) - { - Nameable* nameable = Node_getNameable(node); - if(nameable != 0) - { - nameable->detach(callback); - } - } -} - -GraphTreeModel* scene_graph_get_tree_model(); // temp hack - -void graph_tree_node_foreach_pre(GraphTreeNode::iterator root, const Callback1& callback) -{ - callback(root); - for(GraphTreeNode::iterator i = (*root).second->begin(); i != (*root).second->end(); ++i) - { - graph_tree_node_foreach_pre(i, callback); - } -} - -void graph_tree_node_foreach_post(GraphTreeNode::iterator root, const Callback1& callback) -{ - for(GraphTreeNode::iterator i = (*root).second->begin(); i != (*root).second->end(); ++i) - { - graph_tree_node_foreach_post(i, callback); - } - callback(root); -} - -void graph_tree_model_row_changed(GraphTreeNode& node) -{ - GraphTreeModel* model = scene_graph_get_tree_model(); - const scene::Instance& instance = node.m_instance.get(); - - GraphTreeNode::iterator i = node.m_parent->find(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer())); - - graph_tree_model_row_changed(model, i); -} - -void graph_tree_model_set_name(const scene::Instance& instance, const char* name) -{ - GraphTreeModel* model = scene_graph_get_tree_model(); - GraphTreeNode* parent = graph_tree_model_find_parent(model, instance.path()); - - GraphTreeNode::iterator oldNode = parent->find(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer())); - graph_tree_node_foreach_post(oldNode, ReferenceCaller1(*model)); - GraphTreeNode* node((*oldNode).second); - parent->erase(oldNode); - - GraphTreeNode::iterator newNode = parent->insert(GraphTreeNode::value_type(GraphTreeNode::key_type(name, &instance.path().top().get()), node)); - graph_tree_node_foreach_pre(newNode, ReferenceCaller1(*model)); -} - -void graph_tree_model_insert(GraphTreeModel* model, const scene::Instance& instance) -{ - GraphTreeNode* parent = graph_tree_model_find_parent(model, instance.path()); - - GraphTreeNode::iterator i = parent->insert(GraphTreeNode::value_type(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer()), new GraphTreeNode(const_cast(instance)))); - - graph_tree_model_row_inserted(model, i); - - node_attach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); -} - -void graph_tree_model_erase(GraphTreeModel* model, const scene::Instance& instance) -{ - node_detach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); - - GraphTreeNode* parent = graph_tree_model_find_parent(model, instance.path()); - - GraphTreeNode::iterator i = parent->find(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer())); - - graph_tree_model_row_deleted(model, i); - - GraphTreeNode* node((*i).second); - parent->erase(i); - delete node; -} - - - -#endif - - - - -#if 0 -class TestGraphTreeModel -{ -public: - TestGraphTreeModel() - { - gtk_init(0, 0); - - graph_type graph; - - scene::Node* root = *(scene::Node*)0xa0000000; - scene::Node* node1 = (scene::Node*)0xa0000001; - scene::Node* node2 = (scene::Node*)0xa0000002; - scene::Node* node3 = (scene::Node*)0xa0000003; - scene::Node* node4 = (scene::Node*)0xa0000004; - scene::Instance* instance = (scene::Instance*)0xaaaaaaaa; - - scene::Path rootpath(root); - - graph.insert(graph_type::value_type(rootpath, instance)); - - rootpath.push(node1); - graph.insert(graph_type::value_type(rootpath, instance)); - rootpath.pop(); - - rootpath.push(node2); - graph.insert(graph_type::value_type(rootpath, instance)); - rootpath.push(node3); - graph.insert(graph_type::value_type(rootpath, instance)); - rootpath.pop(); - rootpath.push(node4); - graph.insert(graph_type::value_type(rootpath, instance)); - rootpath.pop(); - rootpath.pop(); - - GtkTreeModel* model = GTK_TREE_MODEL(graph_tree_model_new(&graph)); - - { - gint n_columns = gtk_tree_model_get_n_columns(model); - ASSERT_MESSAGE(n_columns == 2, "test failed!"); - } - - { - GType type = gtk_tree_model_get_column_type(model, 0); - ASSERT_MESSAGE(type == G_TYPE_POINTER, "test failed!"); - } - - { - GType type = gtk_tree_model_get_column_type(model, 1); - ASSERT_MESSAGE(type == G_TYPE_POINTER, "test failed!"); - } - - - { - GtkTreeIter iter; - gtk_tree_model_get_iter_first(model, &iter); - - graph_type::iterator i = graph_iterator_read_tree_iter(&iter); - ASSERT_MESSAGE((*i).first.get().size() == 2 && (*i).first.get().top() == node1, "test failed!"); - } - - { - GtkTreeIter iter; - gtk_tree_model_get_iter_first(model, &iter); - - ASSERT_MESSAGE(gtk_tree_model_iter_has_child(model, &iter) == FALSE, "test failed!"); - - ASSERT_MESSAGE(gtk_tree_model_iter_n_children(model, &iter) == 0, "test failed!"); - - gtk_tree_model_iter_next(model, &iter); - - ASSERT_MESSAGE(gtk_tree_model_iter_has_child(model, &iter) != FALSE, "test failed!"); - - ASSERT_MESSAGE(gtk_tree_model_iter_n_children(model, &iter) == 2, "test failed!"); - - { - GtkTreeIter child; - gtk_tree_model_iter_nth_child(model, &child, &iter, 0); - - scene::Node* test; - gtk_tree_model_get_value(model, &child, 0, (GValue*)&test); - ASSERT_MESSAGE(test == node3, "test failed!"); - - { - GtkTreeIter parent; - gtk_tree_model_iter_parent(model, &parent, &child); - - scene::Node* test; - gtk_tree_model_get_value(model, &parent, 0, (GValue*)&test); - ASSERT_MESSAGE(test == node2, "test failed!"); - } - } - - { - GtkTreeIter child; - gtk_tree_model_iter_nth_child(model, &child, &iter, 1); - - scene::Node* test; - gtk_tree_model_get_value(model, &child, 0, (GValue*)&test); - ASSERT_MESSAGE(test == node4, "test failed!"); - } - } - - { - GtkTreeIter iter; - std::size_t count = 0; - for(gboolean good = gtk_tree_model_get_iter_first(model, &iter); good; good = gtk_tree_model_iter_next(model, &iter)) - { - scene::Node* test; - gtk_tree_model_get_value(model, &iter, 0, (GValue*)&test); - - ASSERT_MESSAGE((count == 0 && test == node1) || (count == 1 && test == node2), "test failed!"); - ++count; - } - - ASSERT_MESSAGE(count == 2, "test failed!"); - - } - - { - GtkTreeIter iter; - gtk_tree_model_get_iter_first(model, &iter); - - scene::Node* test; - gtk_tree_model_get_value(model, &iter, 0, (GValue*)&test); - ASSERT_MESSAGE(test == node1, "test failed!"); - } - - { - GtkTreeIter iter; - GtkTreePath* path = gtk_tree_path_new_from_string("0"); - gtk_tree_model_get_iter(model, &iter, path); - gtk_tree_path_free(path); - - graph_type::iterator i = graph_iterator_read_tree_iter(&iter); - ASSERT_MESSAGE((*i).first.get().size() == 2 && (*i).first.get().top() == node1, "test failed!"); - } - - { - GtkTreeIter iter; - GtkTreePath* path = gtk_tree_path_new_from_string("1"); - gtk_tree_model_get_iter(model, &iter, path); - gtk_tree_path_free(path); - - graph_type::iterator i = graph_iterator_read_tree_iter(&iter); - ASSERT_MESSAGE((*i).first.get().size() == 2 && (*i).first.get().top() == node2, "test failed!"); - } - - { - GtkTreeIter iter; - graph_type::iterator i = graph.begin(); - ++i; - graph_iterator_write_tree_iter(i, &iter); - - GtkTreePath* path = gtk_tree_model_get_path(model, &iter); - - gint depth = gtk_tree_path_get_depth(path); - gint* indices = gtk_tree_path_get_indices(path); - - ASSERT_MESSAGE(depth == 1 && indices[0] == 0, "test failed!"); - - gtk_tree_path_free(path); - } - - { - GtkTreeIter iter; - graph_type::iterator i = graph.begin(); - ++i; - ++i; - graph_iterator_write_tree_iter(i, &iter); - - GtkTreePath* path = gtk_tree_model_get_path(model, &iter); - - gint depth = gtk_tree_path_get_depth(path); - gint* indices = gtk_tree_path_get_indices(path); - - ASSERT_MESSAGE(depth == 1 && indices[0] == 1, "test failed!"); - - gtk_tree_path_free(path); - } - } -}; - - -TestGraphTreeModel g_TestGraphTreeModel; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/treemodel.h b/misc/mediasource/extra/netradiant-src/radiant/treemodel.h deleted file mode 100644 index 7c33485b..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/treemodel.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_TREEMODEL_H) -#define INCLUDED_TREEMODEL_H - -struct GraphTreeModel; - -GraphTreeModel* graph_tree_model_new(); -void graph_tree_model_delete(GraphTreeModel* model); - -namespace scene -{ - class Instance; -} -void graph_tree_model_insert(GraphTreeModel* model, const scene::Instance& instance); -void graph_tree_model_erase(GraphTreeModel* model, const scene::Instance& instance); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/undo.cpp b/misc/mediasource/extra/netradiant-src/radiant/undo.cpp deleted file mode 100644 index aa75d950..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/undo.cpp +++ /dev/null @@ -1,590 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "undo.h" - -#include "debugging/debugging.h" -#include "warnings.h" - -#include "iundo.h" -#include "preferencesystem.h" -#include "string/string.h" -#include "generic/callback.h" -#include "preferences.h" -#include "stringio.h" - -#include -#include -#include - -#include "timer.h" - -class DebugScopeTimer -{ - Timer m_timer; - const char* m_operation; -public: - DebugScopeTimer(const char* operation) - : m_operation(operation) - { - m_timer.start(); - } - ~DebugScopeTimer() - { - unsigned int elapsed = m_timer.elapsed_msec(); - if(elapsed > 0) - { - globalOutputStream() << m_operation << ": " << elapsed << " msec\n"; - } - } -}; - - -class RadiantUndoSystem : public UndoSystem -{ - INTEGER_CONSTANT(MAX_UNDO_LEVELS, 1024); - - class Snapshot - { - class StateApplicator - { - public: - Undoable* m_undoable; - private: - UndoMemento* m_data; - public: - - StateApplicator(Undoable* undoable, UndoMemento* data) - : m_undoable(undoable), m_data(data) - { - } - void restore() - { - m_undoable->importState(m_data); - } - void release() - { - m_data->release(); - } - }; - - typedef std::list states_t; - states_t m_states; - - public: - bool empty() const - { - return m_states.empty(); - } - std::size_t size() const - { - return m_states.size(); - } - void save(Undoable* undoable) - { - m_states.push_front(StateApplicator(undoable, undoable->exportState())); - } - void restore() - { - for(states_t::iterator i = m_states.begin(); i != m_states.end(); ++i) - { - (*i).restore(); - } - } - void release() - { - for(states_t::iterator i = m_states.begin(); i != m_states.end(); ++i) - { - (*i).release(); - } - } - }; - - struct Operation - { - Snapshot m_snapshot; - CopiedString m_command; - - Operation(const char* command) - : m_command(command) - { - } - ~Operation() - { - m_snapshot.release(); - } - }; - - - class UndoStack - { - //! Note: using std::list instead of vector/deque, to avoid copying of undos - typedef std::list Operations; - - Operations m_stack; - Operation* m_pending; - - public: - UndoStack() : m_pending(0) - { - } - ~UndoStack() - { - clear(); - } - bool empty() const - { - return m_stack.empty(); - } - std::size_t size() const - { - return m_stack.size(); - } - Operation* back() - { - return m_stack.back(); - } - const Operation* back() const - { - return m_stack.back(); - } - Operation* front() - { - return m_stack.front(); - } - const Operation* front() const - { - return m_stack.front(); - } - void pop_front() - { - delete m_stack.front(); - m_stack.pop_front(); - } - void pop_back() - { - delete m_stack.back(); - m_stack.pop_back(); - } - void clear() - { - if(!m_stack.empty()) - { - for(Operations::iterator i = m_stack.begin(); i != m_stack.end(); ++i) - { - delete *i; - } - m_stack.clear(); - } - } - void start(const char* command) - { - if(m_pending != 0) - { - delete m_pending; - } - m_pending = new Operation(command); - } - bool finish(const char* command) - { - if(m_pending != 0) - { - delete m_pending; - m_pending = 0; - return false; - } - else - { - ASSERT_MESSAGE(!m_stack.empty(), "undo stack empty"); - m_stack.back()->m_command = command; - return true; - } - } - void save(Undoable* undoable) - { - if(m_pending != 0) - { - m_stack.push_back(m_pending); - m_pending = 0; - } - back()->m_snapshot.save(undoable); - } - }; - - UndoStack m_undo_stack; - UndoStack m_redo_stack; - - class UndoStackFiller : public UndoObserver - { - UndoStack* m_stack; - public: - - UndoStackFiller() - : m_stack(0) - { - } - void save(Undoable* undoable) - { - ASSERT_NOTNULL(undoable); - - if(m_stack != 0) - { - m_stack->save(undoable); - m_stack = 0; - } - } - void setStack(UndoStack* stack) - { - m_stack = stack; - } - }; - - typedef std::map undoables_t; - undoables_t m_undoables; - - void mark_undoables(UndoStack* stack) - { - for(undoables_t::iterator i = m_undoables.begin(); i != m_undoables.end(); ++i) - { - (*i).second.setStack(stack); - } - } - - std::size_t m_undo_levels; - - typedef std::set Trackers; - Trackers m_trackers; -public: - RadiantUndoSystem() - : m_undo_levels(64) - { - } - ~RadiantUndoSystem() - { - clear(); - } - UndoObserver* observer(Undoable* undoable) - { - ASSERT_NOTNULL(undoable); - - return &m_undoables[undoable]; - } - void release(Undoable* undoable) - { - ASSERT_NOTNULL(undoable); - - m_undoables.erase(undoable); - } - void setLevels(std::size_t levels) - { - if(levels > MAX_UNDO_LEVELS()) - { - levels = MAX_UNDO_LEVELS(); - } - - while(m_undo_stack.size() > levels) - { - m_undo_stack.pop_front(); - } - m_undo_levels = levels; - } - std::size_t getLevels() const - { - return m_undo_levels; - } - std::size_t size() const - { - return m_undo_stack.size(); - } - void startUndo() - { - m_undo_stack.start("unnamedCommand"); - mark_undoables(&m_undo_stack); - } - bool finishUndo(const char* command) - { - bool changed = m_undo_stack.finish(command); - mark_undoables(0); - return changed; - } - void startRedo() - { - m_redo_stack.start("unnamedCommand"); - mark_undoables(&m_redo_stack); - } - bool finishRedo(const char* command) - { - bool changed = m_redo_stack.finish(command); - mark_undoables(0); - return changed; - } - void start() - { - m_redo_stack.clear(); - if(m_undo_stack.size() == m_undo_levels) - { - m_undo_stack.pop_front(); - } - startUndo(); - trackersBegin(); - } - void finish(const char* command) - { - if(finishUndo(command)) - { - globalOutputStream() << command << '\n'; - } - } - void undo() - { - if(m_undo_stack.empty()) - { - globalOutputStream() << "Undo: no undo available\n"; - } - else - { - Operation* operation = m_undo_stack.back(); - globalOutputStream() << "Undo: " << operation->m_command.c_str() << "\n"; - - startRedo(); - trackersUndo(); - operation->m_snapshot.restore(); - finishRedo(operation->m_command.c_str()); - m_undo_stack.pop_back(); - } - } - void redo() - { - if(m_redo_stack.empty()) - { - globalOutputStream() << "Redo: no redo available\n"; - } - else - { - Operation* operation = m_redo_stack.back(); - globalOutputStream() << "Redo: " << operation->m_command.c_str() << "\n"; - - startUndo(); - trackersRedo(); - operation->m_snapshot.restore(); - finishUndo(operation->m_command.c_str()); - m_redo_stack.pop_back(); - } - } - void clear() - { - mark_undoables(0); - m_undo_stack.clear(); - m_redo_stack.clear(); - trackersClear(); - } - void trackerAttach(UndoTracker& tracker) - { - ASSERT_MESSAGE(m_trackers.find(&tracker) == m_trackers.end(), "undo tracker already attached"); - m_trackers.insert(&tracker); - } - void trackerDetach(UndoTracker& tracker) - { - ASSERT_MESSAGE(m_trackers.find(&tracker) != m_trackers.end(), "undo tracker cannot be detached"); - m_trackers.erase(&tracker); - } - void trackersClear() const - { - for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) - { - (*i)->clear(); - } - } - void trackersBegin() const - { - for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) - { - (*i)->begin(); - } - } - void trackersUndo() const - { - for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) - { - (*i)->undo(); - } - } - void trackersRedo() const - { - for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) - { - (*i)->redo(); - } - } -}; - - - -void UndoLevels_importString(RadiantUndoSystem& undo, const char* value) -{ - int levels; - Int_importString(levels, value); - undo.setLevels(levels); -} -typedef ReferenceCaller1 UndoLevelsImportStringCaller; -void UndoLevels_exportString(const RadiantUndoSystem& undo, const StringImportCallback& importer) -{ - Int_exportString(static_cast(undo.getLevels()), importer); -} -typedef ConstReferenceCaller1 UndoLevelsExportStringCaller; - -#include "generic/callback.h" - -void UndoLevelsImport(RadiantUndoSystem& self, int value) -{ - self.setLevels(value); -} -typedef ReferenceCaller1 UndoLevelsImportCaller; -void UndoLevelsExport(const RadiantUndoSystem& self, const IntImportCallback& importCallback) -{ - importCallback(static_cast(self.getLevels())); -} -typedef ConstReferenceCaller1 UndoLevelsExportCaller; - - -void Undo_constructPreferences(RadiantUndoSystem& undo, PreferencesPage& page) -{ - page.appendSpinner("Undo Queue Size", 64, 0, 1024, IntImportCallback(UndoLevelsImportCaller(undo)), IntExportCallback(UndoLevelsExportCaller(undo))); -} -void Undo_constructPage(RadiantUndoSystem& undo, PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Undo", "Undo Queue Settings")); - Undo_constructPreferences(undo, page); -} -void Undo_registerPreferencesPage(RadiantUndoSystem& undo) -{ - PreferencesDialog_addSettingsPage(ReferenceCaller1(undo)); -} - -class UndoSystemDependencies : public GlobalPreferenceSystemModuleRef -{ -}; - -class UndoSystemAPI -{ - RadiantUndoSystem m_undosystem; -public: - typedef UndoSystem Type; - STRING_CONSTANT(Name, "*"); - - UndoSystemAPI() - { - GlobalPreferenceSystem().registerPreference("UndoLevels", makeIntStringImportCallback(UndoLevelsImportCaller(m_undosystem)), makeIntStringExportCallback(UndoLevelsExportCaller(m_undosystem))); - - Undo_registerPreferencesPage(m_undosystem); - } - UndoSystem* getTable() - { - return &m_undosystem; - } -}; - -#include "modulesystem/singletonmodule.h" -#include "modulesystem/moduleregistry.h" - -typedef SingletonModule UndoSystemModule; -typedef Static StaticUndoSystemModule; -StaticRegisterModule staticRegisterUndoSystem(StaticUndoSystemModule::instance()); - - - - - - - - - - -class undoable_test : public Undoable -{ - struct state_type : public UndoMemento - { - state_type() : test_data(0) - { - } - state_type(const state_type& other) : UndoMemento(other), test_data(other.test_data) - { - } - void release() - { - delete this; - } - - int test_data; - }; - state_type m_state; - UndoObserver* m_observer; -public: - undoable_test() - : m_observer(GlobalUndoSystem().observer(this)) - { - } - ~undoable_test() - { - GlobalUndoSystem().release(this); - } - UndoMemento* exportState() const - { - return new state_type(m_state); - } - void importState(const UndoMemento* state) - { - ASSERT_NOTNULL(state); - - m_observer->save(this); - m_state = *(static_cast(state)); - } - - void mutate(unsigned int data) - { - m_observer->save(this); - m_state.test_data = data; - } -}; - -#if 0 - -class TestUndo -{ -public: - TestUndo() - { - undoable_test test; - GlobalUndoSystem().begin("bleh"); - test.mutate(3); - GlobalUndoSystem().begin("blah"); - test.mutate(4); - GlobalUndoSystem().undo(); - GlobalUndoSystem().undo(); - GlobalUndoSystem().redo(); - GlobalUndoSystem().redo(); - } -}; - -TestUndo g_TestUndo; - -#endif - diff --git a/misc/mediasource/extra/netradiant-src/radiant/undo.h b/misc/mediasource/extra/netradiant-src/radiant/undo.h deleted file mode 100644 index 171af8cf..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/undo.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_UNDO_H) -#define INCLUDED_UNDO_H - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/url.cpp b/misc/mediasource/extra/netradiant-src/radiant/url.cpp deleted file mode 100644 index 96f13a2e..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/url.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "url.h" - -#include "mainframe.h" -#include "gtkutil/messagebox.h" - -#ifdef WIN32 -#include -#include -bool open_url(const char* url) -{ - return ShellExecute( (HWND)GDK_WINDOW_HWND (GTK_WIDGET(MainFrame_getWindow())->window), "open", url, 0, 0, SW_SHOW ) > (HINSTANCE)32; -} -#endif - -#if defined(__linux__) || defined(__FreeBSD__) -#include -bool open_url(const char* url) -{ - // \todo FIXME: the way we open URLs on *nix should be improved. A script is good (see how I do on RTCW) - char command[2*PATH_MAX]; - snprintf (command, sizeof(command), - "firefox -remote \"openURL(%s,new-window)\" || firefox \"%s\" &", url, url); - return system(command) == 0; -} -#endif - -#ifdef __APPLE__ -#include -bool open_url(const char* url) -{ - char command[2*PATH_MAX]; - snprintf (command, sizeof(command), "open \"%s\" &", url); - return system(command) == 0; -} -#endif - -void OpenURL(const char *url) -{ - // let's put a little comment - globalOutputStream() << "OpenURL: " << url << "\n"; - if(!open_url(url)) - { - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "Failed to launch browser!"); - } -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/url.h b/misc/mediasource/extra/netradiant-src/radiant/url.h deleted file mode 100644 index 38d50b51..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/url.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_URL_H) -#define INCLUDED_URL_H - -void OpenURL(const char *url); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/view.cpp b/misc/mediasource/extra/netradiant-src/radiant/view.cpp deleted file mode 100644 index 5282eb0f..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/view.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "view.h" - -#if defined(DEBUG_CULLING) - -#include - -char g_cull_stats[1024]; -int g_count_dots; -int g_count_planes; -int g_count_oriented_planes; -int g_count_bboxs; -int g_count_oriented_bboxs; - -#endif - -void Cull_ResetStats() -{ -#if defined(DEBUG_CULLING) - g_count_dots = 0; - g_count_planes = 0; - g_count_oriented_planes = 0; - g_count_bboxs = 0; - g_count_oriented_bboxs = 0; -#endif -} - - -const char* Cull_GetStats() -{ -#if defined(DEBUG_CULLING) - sprintf(g_cull_stats, "dots: %d | planes %d + %d | bboxs %d + %d", g_count_dots, g_count_planes, g_count_oriented_planes, g_count_bboxs, g_count_oriented_bboxs); - return g_cull_stats; -#else - return ""; -#endif -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/view.h b/misc/mediasource/extra/netradiant-src/radiant/view.h deleted file mode 100644 index b6dc414a..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/view.h +++ /dev/null @@ -1,211 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_VIEW_H) -#define INCLUDED_VIEW_H - -#include "cullable.h" -#include "math/frustum.h" - - -#if defined(_DEBUG) -#define DEBUG_CULLING -#endif - - -#if defined(DEBUG_CULLING) - -extern int g_count_dots; -extern int g_count_planes; -extern int g_count_oriented_planes; -extern int g_count_bboxs; -extern int g_count_oriented_bboxs; - -#endif - -inline void debug_count_dot() -{ -#if defined(DEBUG_CULLING) - ++g_count_dots; -#endif -} - -inline void debug_count_plane() -{ -#if defined(DEBUG_CULLING) - ++g_count_planes; -#endif -} - -inline void debug_count_oriented_plane() -{ -#if defined(DEBUG_CULLING) - ++g_count_oriented_planes; -#endif -} - -inline void debug_count_bbox() -{ -#if defined(DEBUG_CULLING) - ++g_count_bboxs; -#endif -} - -inline void debug_count_oriented_bbox() -{ -#if defined(DEBUG_CULLING) - ++g_count_oriented_bboxs; -#endif -} - - - - -/// \brief View-volume culling and transformations. -class View : public VolumeTest -{ - /// modelview matrix - Matrix4 m_modelview; - /// projection matrix - Matrix4 m_projection; - /// device-to-screen transform - Matrix4 m_viewport; - - Matrix4 m_scissor; - - /// combined modelview and projection matrix - Matrix4 m_viewproj; - /// camera position in world space - Vector4 m_viewer; - /// view frustum in world space - Frustum m_frustum; - - bool m_fill; - - void construct() - { - m_viewproj = matrix4_multiplied_by_matrix4(matrix4_multiplied_by_matrix4(m_scissor, m_projection), m_modelview); - - m_frustum = frustum_from_viewproj(m_viewproj); - m_viewer = viewer_from_viewproj(m_viewproj); - } -public: - View(bool fill = false) : - m_modelview(g_matrix4_identity), - m_projection(g_matrix4_identity), - m_scissor(g_matrix4_identity), - m_fill(fill) - { - } - void Construct(const Matrix4& projection, const Matrix4& modelview, std::size_t width, std::size_t height) - { - // modelview - m_modelview = modelview; - - // projection - m_projection = projection; - - // viewport - m_viewport = g_matrix4_identity; - m_viewport[0] = float(width/2); - m_viewport[5] = float(height/2); - if(fabs(m_projection[11]) > 0.0000001) - m_viewport[10] = m_projection[0] * m_viewport[0]; - else - m_viewport[10] = 1 / m_projection[10]; - - construct(); - } - void EnableScissor(float min_x, float max_x, float min_y, float max_y) - { - m_scissor = g_matrix4_identity; - m_scissor[0] = static_cast((max_x - min_x) * 0.5); - m_scissor[5] = static_cast((max_y - min_y) * 0.5); - m_scissor[12] = static_cast((min_x + max_x) * 0.5); - m_scissor[13] = static_cast((min_y + max_y) * 0.5); - matrix4_full_invert(m_scissor); - - construct(); - } - void DisableScissor() - { - m_scissor = g_matrix4_identity; - - construct(); - } - - bool TestPoint(const Vector3& point) const - { - return viewproj_test_point(m_viewproj, point); - } - bool TestLine(const Segment& segment) const - { - return frustum_test_line(m_frustum, segment); - } - bool TestPlane(const Plane3& plane) const - { - debug_count_plane(); - return viewer_test_plane(m_viewer, plane); - } - bool TestPlane(const Plane3& plane, const Matrix4& localToWorld) const - { - debug_count_oriented_plane(); - return viewer_test_transformed_plane(m_viewer, plane, localToWorld); - } - VolumeIntersectionValue TestAABB(const AABB& aabb) const - { - debug_count_bbox(); - return frustum_test_aabb(m_frustum, aabb); - } - VolumeIntersectionValue TestAABB(const AABB& aabb, const Matrix4& localToWorld) const - { - debug_count_oriented_bbox(); - return frustum_intersects_transformed_aabb(m_frustum, aabb, localToWorld); - } - - const Matrix4& GetViewMatrix() const - { - return m_viewproj; - } - const Matrix4& GetViewport() const - { - return m_viewport; - }; - const Matrix4& GetModelview() const - { - return m_modelview; - } - const Matrix4& GetProjection() const - { - return m_projection; - } - - bool fill() const - { - return m_fill; - } - const Vector3& getViewer() const - { - return vector4_to_vector3(m_viewer); - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/watchbsp.cpp b/misc/mediasource/extra/netradiant-src/radiant/watchbsp.cpp deleted file mode 100644 index 5c170b66..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/watchbsp.cpp +++ /dev/null @@ -1,879 +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. -*/ - -//----------------------------------------------------------------------------- -// -// DESCRIPTION: -// monitoring window for running BSP processes (and possibly various other stuff) - -#include "watchbsp.h" - -#include -#include - -#include "cmdlib.h" -#include "convert.h" -#include "string/string.h" -#include "stream/stringstream.h" - -#include "gtkutil/messagebox.h" -#include "xmlstuff.h" -#include "console.h" -#include "preferences.h" -#include "points.h" -#include "feedback.h" -#include "mainframe.h" -#include "sockets.h" - -void message_flush(message_info_t* self) -{ - Sys_Print(self->msg_level, self->m_buffer, self->m_length); - self->m_length = 0; -} - -void message_print(message_info_t* self, const char* characters, std::size_t length) -{ - const char* end = characters + length; - while(characters != end) - { - std::size_t space = message_info_t::bufsize - 1 - self->m_length; - if(space == 0) - { - message_flush(self); - } - else - { - std::size_t size = std::min(space, std::size_t(end - characters)); - memcpy(self->m_buffer + self->m_length, characters, size); - self->m_length += size; - characters += size; - } - } -} - - -#include -#include -#include "xmlstuff.h" - -class CWatchBSP -{ -private: - // a flag we have set to true when using an external BSP plugin - // the resulting code with that is a bit dirty, cleaner solution would be to seperate the succession of commands from the listening loop - // (in two seperate classes probably) - bool m_bBSPPlugin; - - // EIdle: we are not listening - // DoMonitoringLoop will change state to EBeginStep - // EBeginStep: the socket is up for listening, we are expecting incoming connection - // incoming connection will change state to EWatching - // EWatching: we have a connection, monitor it - // connection closed will see if we start a new step (EBeginStep) or launch Quake3 and end (EIdle) - enum EWatchBSPState { EIdle, EBeginStep, EWatching } m_eState; - socket_t *m_pListenSocket; - socket_t *m_pInSocket; - netmessage_t msg; - GPtrArray *m_pCmd; - // used to timeout EBeginStep - GTimer *m_pTimer; - std::size_t m_iCurrentStep; - // name of the map so we can run the engine - char *m_sBSPName; - // buffer we use in push mode to receive data directly from the network - xmlParserInputBufferPtr m_xmlInputBuffer; - xmlParserInputPtr m_xmlInput; - xmlParserCtxtPtr m_xmlParserCtxt; - // call this to switch the set listening mode - bool SetupListening(); - // start a new EBeginStep - void DoEBeginStep(); - // the xml and sax parser state - char m_xmlBuf[MAX_NETMESSAGE]; - bool m_bNeedCtxtInit; - message_info_t m_message_info; - -public: - CWatchBSP() - { - m_pCmd = 0; - m_bBSPPlugin = false; - m_pListenSocket = NULL; - m_pInSocket = NULL; - m_eState = EIdle; - m_pTimer = g_timer_new(); - m_sBSPName = NULL; - m_xmlInputBuffer = NULL; - m_bNeedCtxtInit = true; - } - virtual ~CWatchBSP() - { - EndMonitoringLoop(); - Net_Shutdown(); - - g_timer_destroy(m_pTimer); - } - - bool HasBSPPlugin() const - { return m_bBSPPlugin; } - - // called regularly to keep listening - void RoutineProcessing(); - // start a monitoring loop with the following steps - void DoMonitoringLoop( GPtrArray *pCmd, const char *sBSPName ); - void EndMonitoringLoop() - { - Reset(); - if (m_sBSPName) - { - string_release(m_sBSPName, string_length(m_sBSPName)); - m_sBSPName = 0; - } - if(m_pCmd) - { - g_ptr_array_free(m_pCmd, TRUE); - m_pCmd = 0; - } - } - // close everything - may be called from the outside to abort the process - void Reset(); - // start a listening loop for an external process, possibly a BSP plugin - void ExternalListen(); -}; - -CWatchBSP* g_pWatchBSP; - - // watch the BSP process through network connections - // true: trigger the BSP steps one by one and monitor them through the network - // false: create a BAT / .sh file and execute it. don't bother monitoring it. -bool g_WatchBSP_Enabled = true; - // do we stop the compilation process if we come accross a leak? -bool g_WatchBSP_LeakStop = true; -bool g_WatchBSP_RunQuake = false; - // store prefs setting for automatic sleep mode activation -bool g_WatchBSP_DoSleep = true; - // timeout when beginning a step (in seconds) - // if we don't get a connection quick enough we assume something failed and go back to idling -int g_WatchBSP_Timeout = 10; - - -void Build_constructPreferences(PreferencesPage& page) -{ - GtkWidget* monitorbsp = page.appendCheckBox("", "Enable Build Process Monitoring", g_WatchBSP_Enabled); - GtkWidget* leakstop = page.appendCheckBox("", "Stop Compilation on Leak", g_WatchBSP_LeakStop); - GtkWidget* runengine = page.appendCheckBox("", "Run Engine After Compile", g_WatchBSP_RunQuake); - GtkWidget* sleep = page.appendCheckBox("", "Sleep When Running the Engine", g_WatchBSP_DoSleep); - Widget_connectToggleDependency(leakstop, monitorbsp); - Widget_connectToggleDependency(runengine, monitorbsp); - Widget_connectToggleDependency(sleep, runengine); -} -void Build_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Build", "Build Preferences")); - Build_constructPreferences(page); -} -void Build_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - -#include "preferencesystem.h" -#include "stringio.h" - -void BuildMonitor_Construct() -{ - g_pWatchBSP = new CWatchBSP(); - - g_WatchBSP_Enabled = !string_equal(g_pGameDescription->getKeyValue("no_bsp_monitor"), "1"); - - GlobalPreferenceSystem().registerPreference("WatchBSP", BoolImportStringCaller(g_WatchBSP_Enabled), BoolExportStringCaller(g_WatchBSP_Enabled)); - GlobalPreferenceSystem().registerPreference("RunQuake2Run", BoolImportStringCaller(g_WatchBSP_RunQuake), BoolExportStringCaller(g_WatchBSP_RunQuake)); - GlobalPreferenceSystem().registerPreference("LeakStop", BoolImportStringCaller(g_WatchBSP_LeakStop), BoolExportStringCaller(g_WatchBSP_LeakStop)); - GlobalPreferenceSystem().registerPreference("SleepMode", BoolImportStringCaller(g_WatchBSP_DoSleep), BoolExportStringCaller(g_WatchBSP_DoSleep)); - - Build_registerPreferencesPage(); -} - -void BuildMonitor_Destroy() -{ - delete g_pWatchBSP; -} - -CWatchBSP *GetWatchBSP() -{ - return g_pWatchBSP; -} - -void BuildMonitor_Run(GPtrArray* commands, const char* mapName) -{ - GetWatchBSP()->DoMonitoringLoop(commands, mapName); -} - - -// Static functions for the SAX callbacks ------------------------------------------------------- - -// utility for saxStartElement below -static void abortStream(message_info_t *data) -{ - GetWatchBSP()->EndMonitoringLoop(); - // tell there has been an error -#if 0 - if (GetWatchBSP()->HasBSPPlugin()) - g_BSPFrontendTable.m_pfnEndListen(2); -#endif - // yeah this doesn't look good.. but it's needed so that everything will be ignored until the stream goes out - data->ignore_depth = -1; - data->recurse++; -} - -#include "stream_version.h" - -static void saxStartElement(message_info_t *data, const xmlChar *name, const xmlChar **attrs) -{ -#if 0 - globalOutputStream() << "<" << name; - if(attrs != 0) - { - for(const xmlChar** p = attrs; *p != 0; p += 2) - { - globalOutputStream() << " " << p[0] << "=" << makeQuoted(p[1]); - } - } - globalOutputStream() << ">\n"; -#endif - - if (data->ignore_depth == 0) - { - if(data->pGeometry != 0) - // we have a handler - { - data->pGeometry->saxStartElement (data, name, attrs); - } - else - { - if (strcmp(reinterpret_cast(name), "q3map_feedback") == 0) - { - // check the correct version - // old q3map don't send a version attribute - // the ones we support .. send Q3MAP_STREAM_VERSION - if (!attrs[0] || !attrs[1] || (strcmp(reinterpret_cast(attrs[0]), "version") != 0)) - { - message_flush(data); - globalErrorStream() << "No stream version given in the feedback stream, this is an old q3map version.\n" - "Please turn off monitored compiling if you still wish to use this q3map executable\n"; - abortStream(data); - return; - } - else if (strcmp(reinterpret_cast(attrs[1]), Q3MAP_STREAM_VERSION) != 0) - { - message_flush(data); - globalErrorStream() << - "This version of Radiant reads version " Q3MAP_STREAM_VERSION " debug streams, I got an incoming connection with version " << reinterpret_cast(attrs[1]) << "\n" - "Please make sure your versions of Radiant and q3map are matching.\n"; - abortStream(data); - return; - } - } - // we don't treat locally - else if (strcmp(reinterpret_cast(name), "message") == 0) - { - int msg_level = atoi(reinterpret_cast(attrs[1])); - if(msg_level != data->msg_level) - { - message_flush(data); - data->msg_level = msg_level; - } - } - else if (strcmp(reinterpret_cast(name), "polyline") == 0) - // polyline has a particular status .. right now we only use it for leakfile .. - { - data->geometry_depth = data->recurse; - data->pGeometry = &g_pointfile; - data->pGeometry->saxStartElement (data, name, attrs); - } - else if (strcmp(reinterpret_cast(name), "select") == 0) - { - CSelectMsg *pSelect = new CSelectMsg(); - data->geometry_depth = data->recurse; - data->pGeometry = pSelect; - data->pGeometry->saxStartElement (data, name, attrs); - } - else if (strcmp(reinterpret_cast(name), "pointmsg") == 0) - { - CPointMsg *pPoint = new CPointMsg(); - data->geometry_depth = data->recurse; - data->pGeometry = pPoint; - data->pGeometry->saxStartElement (data, name, attrs); - } - else if (strcmp(reinterpret_cast(name), "windingmsg") == 0) - { - CWindingMsg *pWinding = new CWindingMsg(); - data->geometry_depth = data->recurse; - data->pGeometry = pWinding; - data->pGeometry->saxStartElement (data, name, attrs); - } - else - { - globalErrorStream() << "Warning: ignoring unrecognized node in XML stream (" << reinterpret_cast(name) << ")\n"; - // we don't recognize this node, jump over it - // (NOTE: the ignore mechanism is a bit screwed, only works when starting an ignore at the highest level) - data->ignore_depth = data->recurse; - } - } - } - data->recurse++; -} - -static void saxEndElement(message_info_t *data, const xmlChar *name) -{ -#if 0 - globalOutputStream() << "<" << name << "/>\n"; -#endif - - data->recurse--; - // we are out of an ignored chunk - if(data->recurse == data->ignore_depth) - { - data->ignore_depth = 0; - return; - } - if(data->pGeometry != 0) - { - data->pGeometry->saxEndElement (data, name); - // we add the object to the debug window - if(data->geometry_depth == data->recurse) - { - g_DbgDlg.Push(data->pGeometry); - data->pGeometry = 0; - } - } - if (data->recurse == data->stop_depth) - { - message_flush(data); -#ifdef _DEBUG - globalOutputStream() << "Received error msg .. shutting down..\n"; -#endif - GetWatchBSP()->EndMonitoringLoop(); - // tell there has been an error -#if 0 - if (GetWatchBSP()->HasBSPPlugin()) - g_BSPFrontendTable.m_pfnEndListen(2); -#endif - return; - } -} - -class MessageOutputStream : public TextOutputStream -{ - message_info_t* m_data; -public: - MessageOutputStream(message_info_t* data) : m_data(data) - { - } - std::size_t write(const char* buffer, std::size_t length) - { - if(m_data->pGeometry != 0) - { - m_data->pGeometry->saxCharacters(m_data, reinterpret_cast(buffer), int(length)); - } - else - { - if (m_data->ignore_depth == 0) - { - // output the message using the level - message_print(m_data, buffer, length); - // if this message has error level flag, we mark the depth to stop the compilation when we get out - // we don't set the msg level if we don't stop on leak - if (m_data->msg_level == 3) - { - m_data->stop_depth = m_data->recurse-1; - } - } - } - - return length; - } -}; - -template -inline MessageOutputStream& operator<<(MessageOutputStream& ostream, const T& t) -{ - return ostream_write(ostream, t); -} - -static void saxCharacters(message_info_t *data, const xmlChar *ch, int len) -{ - MessageOutputStream ostream(data); - ostream << StringRange(reinterpret_cast(ch), reinterpret_cast(ch + len)); -} - -static void saxComment(void *ctx, const xmlChar *msg) -{ - globalOutputStream() << "XML comment: " << reinterpret_cast(msg) << "\n"; -} - -static void saxWarning(void *ctx, const char *msg, ...) -{ - char saxMsgBuffer[4096]; - va_list args; - - va_start(args, msg); - vsprintf (saxMsgBuffer, msg, args); - va_end(args); - globalOutputStream() << "XML warning: " << saxMsgBuffer << "\n"; -} - -static void saxError(void *ctx, const char *msg, ...) -{ - char saxMsgBuffer[4096]; - va_list args; - - va_start(args, msg); - vsprintf (saxMsgBuffer, msg, args); - va_end(args); - globalErrorStream() << "XML error: " << saxMsgBuffer << "\n"; -} - -static void saxFatal(void *ctx, const char *msg, ...) -{ - char buffer[4096]; - - va_list args; - - va_start(args, msg); - vsprintf (buffer, msg, args); - va_end(args); - globalErrorStream() << "XML fatal error: " << buffer << "\n"; -} - -static xmlSAXHandler saxParser = { - 0, /* internalSubset */ - 0, /* isStandalone */ - 0, /* hasInternalSubset */ - 0, /* hasExternalSubset */ - 0, /* resolveEntity */ - 0, /* getEntity */ - 0, /* entityDecl */ - 0, /* notationDecl */ - 0, /* attributeDecl */ - 0, /* elementDecl */ - 0, /* unparsedEntityDecl */ - 0, /* setDocumentLocator */ - 0, /* startDocument */ - 0, /* endDocument */ - (startElementSAXFunc)saxStartElement, /* startElement */ - (endElementSAXFunc)saxEndElement, /* endElement */ - 0, /* reference */ - (charactersSAXFunc)saxCharacters, /* characters */ - 0, /* ignorableWhitespace */ - 0, /* processingInstruction */ - (commentSAXFunc)saxComment, /* comment */ - (warningSAXFunc)saxWarning, /* warning */ - (errorSAXFunc)saxError, /* error */ - (fatalErrorSAXFunc)saxFatal, /* fatalError */ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 -}; - -// ------------------------------------------------------------------------------------------------ - - -guint s_routine_id; -static gint watchbsp_routine(gpointer data) -{ - reinterpret_cast(data)->RoutineProcessing(); - return TRUE; -} - -void CWatchBSP::Reset() -{ - if (m_pInSocket) - { - Net_Disconnect(m_pInSocket); - m_pInSocket = NULL; - } - if (m_pListenSocket) - { - Net_Disconnect(m_pListenSocket); - m_pListenSocket = NULL; - } - if (m_xmlInputBuffer) - { - xmlFreeParserInputBuffer (m_xmlInputBuffer); - m_xmlInputBuffer = NULL; - } - m_eState = EIdle; - if (s_routine_id) - gtk_timeout_remove(s_routine_id); -} - -bool CWatchBSP::SetupListening() -{ -#ifdef _DEBUG - if (m_pListenSocket) - { - globalOutputStream() << "ERROR: m_pListenSocket != NULL in CWatchBSP::SetupListening\n"; - return false; - } -#endif - globalOutputStream() << "Setting up\n"; - Net_Setup(); - m_pListenSocket = Net_ListenSocket(39000); - if (m_pListenSocket == NULL) - return false; - globalOutputStream() << "Listening...\n"; - return true; -} - -void CWatchBSP::DoEBeginStep() -{ - Reset(); - if (SetupListening() == false) - { - const char* msg = "Failed to get a listening socket on port 39000.\nTry running with Build monitoring disabled if you can't fix this.\n"; - globalOutputStream() << msg; - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), msg, "Build monitoring", eMB_OK, eMB_ICONERROR); - return; - } - // set the timer for timeouts and step cancellation - g_timer_reset( m_pTimer ); - g_timer_start( m_pTimer ); - - if (!m_bBSPPlugin) - { - globalOutputStream() << "=== running build command ===\n" - << static_cast(g_ptr_array_index( m_pCmd, m_iCurrentStep )) << "\n"; - - if (!Q_Exec(NULL, (char *)g_ptr_array_index( m_pCmd, m_iCurrentStep ), NULL, true, false )) - { - StringOutputStream msg(256); - msg << "Failed to execute the following command: "; - msg << reinterpret_cast(g_ptr_array_index(m_pCmd, m_iCurrentStep)); - msg << "\nCheck that the file exists and that you don't run out of system resources.\n"; - globalOutputStream() << msg.c_str(); - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), msg.c_str(), "Build monitoring", eMB_OK, eMB_ICONERROR ); - return; - } - // re-initialise the debug window - if (m_iCurrentStep == 0) - g_DbgDlg.Init(); - } - m_eState = EBeginStep; - s_routine_id = gtk_timeout_add(25, watchbsp_routine, this); -} - - -#if defined(WIN32) -#define ENGINE_ATTRIBUTE "engine_win32" -#define MP_ENGINE_ATTRIBUTE "mp_engine_win32" -#elif defined(__linux__) || defined (__FreeBSD__) -#define ENGINE_ATTRIBUTE "engine_linux" -#define MP_ENGINE_ATTRIBUTE "mp_engine_linux" -#elif defined(__APPLE__) -#define ENGINE_ATTRIBUTE "engine_macos" -#define MP_ENGINE_ATTRIBUTE "mp_engine_macos" -#else -#error "unsupported platform" -#endif - -class RunEngineConfiguration -{ -public: - const char* executable; - const char* mp_executable; - bool do_sp_mp; - - RunEngineConfiguration() : - executable(g_pGameDescription->getRequiredKeyValue(ENGINE_ATTRIBUTE)), - mp_executable(g_pGameDescription->getKeyValue(MP_ENGINE_ATTRIBUTE)) - { - do_sp_mp = !string_empty(mp_executable); - } -}; - -inline void GlobalGameDescription_string_write_mapparameter(StringOutputStream& string, const char* mapname) -{ - if(g_pGameDescription->mGameType == "q2" - || g_pGameDescription->mGameType == "heretic2") - { - string << ". +exec radiant.cfg +map " << mapname; - } - else - { - string << "+set sv_pure 0 "; - // TTimo: a check for vm_* but that's all fine - //cmdline = "+set sv_pure 0 +set vm_ui 0 +set vm_cgame 0 +set vm_game 0 "; - const char* fs_game = gamename_get(); - if (!string_equal(fs_game, basegame_get())) - { - string << "+set fs_game " << fs_game << " "; - } - if(g_pGameDescription->mGameType == "wolf" - || g_pGameDescription->mGameType == "et") - { - if (string_equal(gamemode_get(), "mp")) - { - // MP - string << "+devmap " << mapname; - } - else - { - // SP - string << "+set nextmap \"spdevmap " << mapname << "\""; - } - } - else - { - string << "+devmap " << mapname; - } - } -} - - -void CWatchBSP::RoutineProcessing() -{ - switch (m_eState) - { - case EBeginStep: - // timeout: if we don't get an incoming connection fast enough, go back to idle - if ( g_timer_elapsed( m_pTimer, NULL ) > g_WatchBSP_Timeout ) - { - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "The connection timed out, assuming the build process failed\nMake sure you are using a networked version of Q3Map?\nOtherwise you need to disable BSP Monitoring in prefs.", "BSP process monitoring", eMB_OK ); - EndMonitoringLoop(); -#if 0 - if (m_bBSPPlugin) - { - // status == 1 : didn't get the connection - g_BSPFrontendTable.m_pfnEndListen(1); - } -#endif - return; - } -#ifdef _DEBUG - // some debug checks - if (!m_pListenSocket) - { - globalErrorStream() << "ERROR: m_pListenSocket == NULL in CWatchBSP::RoutineProcessing EBeginStep state\n"; - return; - } -#endif - // we are not connected yet, accept any incoming connection - m_pInSocket = Net_Accept(m_pListenSocket); - if (m_pInSocket) - { - globalOutputStream() << "Connected.\n"; - // prepare the message info struct for diving in - memset (&m_message_info, 0, sizeof(message_info_t)); - // a dumb flag to make sure we init the push parser context when first getting a msg - m_bNeedCtxtInit = true; - m_eState = EWatching; - } - break; - case EWatching: - { -#ifdef _DEBUG - // some debug checks - if (!m_pInSocket) - { - globalErrorStream() << "ERROR: m_pInSocket == NULL in CWatchBSP::RoutineProcessing EWatching state\n"; - return; - } -#endif - - int ret = Net_Wait(m_pInSocket, 0, 0); - if (ret == -1) - { - globalOutputStream() << "WARNING: SOCKET_ERROR in CWatchBSP::RoutineProcessing\n"; - globalOutputStream() << "Terminating the connection.\n"; - EndMonitoringLoop(); - return; - } - - if (ret == 1) - { - // the socket has been identified, there's something (message or disconnection) - // see if there's anything in input - ret = Net_Receive( m_pInSocket, &msg ); - if (ret > 0) - { - // unsigned int size = msg.size; //++timo just a check - strcpy (m_xmlBuf, NMSG_ReadString (&msg)); - if (m_bNeedCtxtInit) - { - m_xmlParserCtxt = NULL; - m_xmlParserCtxt = xmlCreatePushParserCtxt (&saxParser, &m_message_info, m_xmlBuf, static_cast(strlen(m_xmlBuf)), NULL); - - if (m_xmlParserCtxt == NULL) - { - globalErrorStream() << "Failed to create the XML parser (incoming stream began with: " << m_xmlBuf << ")\n"; - EndMonitoringLoop(); - } - m_bNeedCtxtInit = false; - } - else - { - xmlParseChunk(m_xmlParserCtxt, m_xmlBuf, static_cast(strlen(m_xmlBuf)), 0); - } - } - else - { - message_flush(&m_message_info); - // error or connection closed/reset - // NOTE: if we get an error down the XML stream we don't reach here - Net_Disconnect( m_pInSocket ); - m_pInSocket = NULL; - globalOutputStream() << "Connection closed.\n"; -#if 0 - if (m_bBSPPlugin) - { - EndMonitoringLoop(); - // let the BSP plugin know that the job is done - g_BSPFrontendTable.m_pfnEndListen(0); - return; - } -#endif - // move to next step or finish - m_iCurrentStep++; - if (m_iCurrentStep < m_pCmd->len ) - { - DoEBeginStep(); - } - else - { - // launch the engine .. OMG - if (g_WatchBSP_RunQuake) - { -#if 0 - // do we enter sleep mode before? - if (g_WatchBSP_DoSleep) - { - globalOutputStream() << "Going into sleep mode..\n"; - g_pParentWnd->OnSleep(); - } -#endif - globalOutputStream() << "Running engine...\n"; - StringOutputStream cmd(256); - // build the command line - cmd << EnginePath_get(); - // this is game dependant - - RunEngineConfiguration engineConfig; - - if(engineConfig.do_sp_mp) - { - if (string_equal(gamemode_get(), "mp")) - { - cmd << engineConfig.mp_executable; - } - else - { - cmd << engineConfig.executable; - } - } - else - { - cmd << engineConfig.executable; - } - - StringOutputStream cmdline; - - GlobalGameDescription_string_write_mapparameter(cmdline, m_sBSPName); - - globalOutputStream() << cmd.c_str() << " " << cmdline.c_str() << "\n"; - - // execute now - if (!Q_Exec(cmd.c_str(), (char *)cmdline.c_str(), EnginePath_get(), false, false)) - { - StringOutputStream msg; - msg << "Failed to execute the following command: " << cmd.c_str() << cmdline.c_str(); - globalOutputStream() << msg.c_str(); - gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), msg.c_str(), "Build monitoring", eMB_OK, eMB_ICONERROR ); - } - } - EndMonitoringLoop(); - } - } - } - } - break; - default: - break; - } -} - -GPtrArray* str_ptr_array_clone(GPtrArray* array) -{ - GPtrArray* cloned = g_ptr_array_sized_new(array->len); - for(guint i = 0; i < array->len; ++i) - { - g_ptr_array_add(cloned, g_strdup((char*)g_ptr_array_index(array, i))); - } - return cloned; -} - -void CWatchBSP::DoMonitoringLoop( GPtrArray *pCmd, const char *sBSPName ) -{ - m_sBSPName = string_clone(sBSPName); - if (m_eState != EIdle) - { - globalOutputStream() << "WatchBSP got a monitoring request while not idling...\n"; - // prompt the user, should we cancel the current process and go ahead? - if (gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "I am already monitoring a Build process.\nDo you want me to override and start a new compilation?", - "Build process monitoring", eMB_YESNO ) == eIDYES) - { - // disconnect and set EIdle state - Reset(); - } - } - m_pCmd = str_ptr_array_clone(pCmd); - m_iCurrentStep = 0; - DoEBeginStep(); -} - -void CWatchBSP::ExternalListen() -{ - m_bBSPPlugin = true; - DoEBeginStep(); -} - -// the part of the watchbsp interface we export to plugins -// NOTE: in the long run, the whole watchbsp.cpp interface needs to go out and be handled at the BSP plugin level -// for now we provide something really basic and limited, the essential is to have something that works fine and fast (for 1.1 final) -void QERApp_Listen() -{ - // open the listening socket - GetWatchBSP()->ExternalListen(); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/watchbsp.h b/misc/mediasource/extra/netradiant-src/radiant/watchbsp.h deleted file mode 100644 index ac6a2b22..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/watchbsp.h +++ /dev/null @@ -1,43 +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. -*/ - -#if !defined(INCLUDED_WATCHBSP_H) -#define INCLUDED_WATCHBSP_H - -void BuildMonitor_Construct(); -void BuildMonitor_Destroy(); - -typedef struct _GPtrArray GPtrArray; -void BuildMonitor_Run(GPtrArray* commands, const char* mapName); - -extern bool g_WatchBSP_Enabled; -extern bool g_WatchBSP_LeakStop; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/winding.cpp b/misc/mediasource/extra/netradiant-src/radiant/winding.cpp deleted file mode 100644 index bba89501..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/winding.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "winding.h" - -#include - -#include "math/line.h" - - -inline double plane3_distance_to_point(const Plane3& plane, const DoubleVector3& point) -{ - return vector3_dot(point, plane.normal()) - plane.dist(); -} - -inline double plane3_distance_to_point(const Plane3& plane, const Vector3& point) -{ - return vector3_dot(point, plane.normal()) - plane.dist(); -} - -/// \brief Returns the point at which \p line intersects \p plane, or an undefined value if there is no intersection. -inline DoubleVector3 line_intersect_plane(const DoubleLine& line, const Plane3& plane) -{ - return line.origin + vector3_scaled( - line.direction, - -plane3_distance_to_point(plane, line.origin) - / vector3_dot(line.direction, plane.normal()) - ); -} - -inline bool float_is_largest_absolute(double axis, double other) -{ - return fabs(axis) > fabs(other); -} - -/// \brief Returns the index of the component of \p v that has the largest absolute value. -inline int vector3_largest_absolute_component_index(const DoubleVector3& v) -{ - return (float_is_largest_absolute(v[1], v[0])) - ? (float_is_largest_absolute(v[1], v[2])) - ? 1 - : 2 - : (float_is_largest_absolute(v[0], v[2])) - ? 0 - : 2; -} - -/// \brief Returns the infinite line that is the intersection of \p plane and \p other. -inline DoubleLine plane3_intersect_plane3(const Plane3& plane, const Plane3& other) -{ - DoubleLine line; - line.direction = vector3_cross(plane.normal(), other.normal()); - switch(vector3_largest_absolute_component_index(line.direction)) - { - case 0: - line.origin.x() = 0; - line.origin.y() = (-other.dist() * plane.normal().z() - -plane.dist() * other.normal().z()) / line.direction.x(); - line.origin.z() = (-plane.dist() * other.normal().y() - -other.dist() * plane.normal().y()) / line.direction.x(); - break; - case 1: - line.origin.x() = (-plane.dist() * other.normal().z() - -other.dist() * plane.normal().z()) / line.direction.y(); - line.origin.y() = 0; - line.origin.z() = (-other.dist() * plane.normal().x() - -plane.dist() * other.normal().x()) / line.direction.y(); - break; - case 2: - line.origin.x() = (-other.dist() * plane.normal().y() - -plane.dist() * other.normal().y()) / line.direction.z(); - line.origin.y() = (-plane.dist() * other.normal().x() - -other.dist() * plane.normal().x()) / line.direction.z(); - line.origin.z() = 0; - break; - default: - break; - } - - return line; -} - - -/// \brief Keep the value of \p infinity as small as possible to improve precision in Winding_Clip. -void Winding_createInfinite(FixedWinding& winding, const Plane3& plane, double infinity) -{ - double max = -infinity; - int x = -1; - for (int i=0 ; i<3; i++) - { - double d = fabs(plane.normal()[i]); - if (d > max) - { - x = i; - max = d; - } - } - if(x == -1) - { - globalErrorStream() << "invalid plane\n"; - return; - } - - DoubleVector3 vup = g_vector3_identity; - switch (x) - { - case 0: - case 1: - vup[2] = 1; - break; - case 2: - vup[0] = 1; - break; - } - - - vector3_add(vup, vector3_scaled(plane.normal(), -vector3_dot(vup, plane.normal()))); - vector3_normalise(vup); - - DoubleVector3 org = vector3_scaled(plane.normal(), plane.dist()); - - DoubleVector3 vright = vector3_cross(vup, plane.normal()); - - vector3_scale(vup, infinity); - vector3_scale(vright, infinity); - - // project a really big axis aligned box onto the plane - - DoubleLine r1, r2, r3, r4; - r1.origin = vector3_added(vector3_subtracted(org, vright), vup); - r1.direction = vector3_normalised(vright); - winding.push_back(FixedWindingVertex(r1.origin, r1, c_brush_maxFaces)); - r2.origin = vector3_added(vector3_added(org, vright), vup); - r2.direction = vector3_normalised(vector3_negated(vup)); - winding.push_back(FixedWindingVertex(r2.origin, r2, c_brush_maxFaces)); - r3.origin = vector3_subtracted(vector3_added(org, vright), vup); - r3.direction = vector3_normalised(vector3_negated(vright)); - winding.push_back(FixedWindingVertex(r3.origin, r3, c_brush_maxFaces)); - r4.origin = vector3_subtracted(vector3_subtracted(org, vright), vup); - r4.direction = vector3_normalised(vup); - winding.push_back(FixedWindingVertex(r4.origin, r4, c_brush_maxFaces)); -} - - -inline PlaneClassification Winding_ClassifyDistance(const double distance, const double epsilon) -{ - if(distance > epsilon) - { - return ePlaneFront; - } - if(distance < -epsilon) - { - return ePlaneBack; - } - return ePlaneOn; -} - -/// \brief Returns true if -/// !flipped && winding is completely BACK or ON -/// or flipped && winding is completely FRONT or ON -bool Winding_TestPlane(const Winding& winding, const Plane3& plane, bool flipped) -{ - const int test = (flipped) ? ePlaneBack : ePlaneFront; - for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i) - { - if(test == Winding_ClassifyDistance(plane3_distance_to_point(plane, (*i).vertex), ON_EPSILON)) - { - return false; - } - } - return true; -} - -/// \brief Returns true if any point in \p w1 is in front of plane2, or any point in \p w2 is in front of plane1 -bool Winding_PlanesConcave(const Winding& w1, const Winding& w2, const Plane3& plane1, const Plane3& plane2) -{ - return !Winding_TestPlane(w1, plane2, false) || !Winding_TestPlane(w2, plane1, false); -} - -brushsplit_t Winding_ClassifyPlane(const Winding& winding, const Plane3& plane) -{ - brushsplit_t split; - for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i) - { - ++split.counts[Winding_ClassifyDistance(plane3_distance_to_point(plane, (*i).vertex), ON_EPSILON)]; - } - return split; -} - - -#define DEBUG_EPSILON ON_EPSILON -const double DEBUG_EPSILON_SQUARED = DEBUG_EPSILON * DEBUG_EPSILON; - -#define WINDING_DEBUG 0 - -/// \brief Clip \p winding which lies on \p plane by \p clipPlane, resulting in \p clipped. -/// If \p winding is completely in front of the plane, \p clipped will be identical to \p winding. -/// If \p winding is completely in back of the plane, \p clipped will be empty. -/// If \p winding intersects the plane, the edge of \p clipped which lies on \p clipPlane will store the value of \p adjacent. -void Winding_Clip(const FixedWinding& winding, const Plane3& plane, const Plane3& clipPlane, std::size_t adjacent, FixedWinding& clipped) -{ - PlaneClassification classification = Winding_ClassifyDistance(plane3_distance_to_point(clipPlane, winding.back().vertex), ON_EPSILON); - PlaneClassification nextClassification; - // for each edge - for(std::size_t next = 0, i = winding.size()-1; next != winding.size(); i = next, ++next, classification = nextClassification) - { - nextClassification = Winding_ClassifyDistance(plane3_distance_to_point(clipPlane, winding[next].vertex), ON_EPSILON); - const FixedWindingVertex& vertex = winding[i]; - - // if first vertex of edge is ON - if(classification == ePlaneOn) - { - // append first vertex to output winding - if(nextClassification == ePlaneBack) - { - // this edge lies on the clip plane - clipped.push_back(FixedWindingVertex(vertex.vertex, plane3_intersect_plane3(plane, clipPlane), adjacent)); - } - else - { - clipped.push_back(vertex); - } - continue; - } - - // if first vertex of edge is FRONT - if(classification == ePlaneFront) - { - // add first vertex to output winding - clipped.push_back(vertex); - } - // if second vertex of edge is ON - if(nextClassification == ePlaneOn) - { - continue; - } - // else if second vertex of edge is same as first - else if(nextClassification == classification) - { - continue; - } - // else if first vertex of edge is FRONT and there are only two edges - else if(classification == ePlaneFront && winding.size() == 2) - { - continue; - } - // else first vertex is FRONT and second is BACK or vice versa - else - { - // append intersection point of line and plane to output winding - DoubleVector3 mid(line_intersect_plane(vertex.edge, clipPlane)); - - if(classification == ePlaneFront) - { - // this edge lies on the clip plane - clipped.push_back(FixedWindingVertex(mid, plane3_intersect_plane3(plane, clipPlane), adjacent)); - } - else - { - clipped.push_back(FixedWindingVertex(mid, vertex.edge, vertex.adjacent)); - } - } - } -} - -std::size_t Winding_FindAdjacent(const Winding& winding, std::size_t face) -{ - for(std::size_t i=0; i dist_best) - { - dist_best = dist_squared; - index_best = i; - } - } - return index_best; -} - -std::size_t Winding_Opposite(const Winding& winding, const std::size_t index) -{ - return Winding_Opposite(winding, index, Winding_next(winding, index)); -} - -/// \brief Calculate the \p centroid of the polygon defined by \p winding which lies on plane \p plane. -void Winding_Centroid(const Winding& winding, const Plane3& plane, Vector3& centroid) -{ - double area2 = 0, x_sum = 0, y_sum = 0; - const ProjectionAxis axis = projectionaxis_for_normal(plane.normal()); - const indexremap_t remap = indexremap_for_projectionaxis(axis); - for(std::size_t i = winding.numpoints-1, j = 0; j < winding.numpoints; i = j, ++j) - { - const double ai = winding[i].vertex[remap.x] * winding[j].vertex[remap.y] - winding[j].vertex[remap.x] * winding[i].vertex[remap.y]; - area2 += ai; - x_sum += (winding[j].vertex[remap.x] + winding[i].vertex[remap.x]) * ai; - y_sum += (winding[j].vertex[remap.y] + winding[i].vertex[remap.y]) * ai; - } - - centroid[remap.x] = static_cast(x_sum / (3 * area2)); - centroid[remap.y] = static_cast(y_sum / (3 * area2)); - { - Ray ray(Vector3(0, 0, 0), Vector3(0, 0, 0)); - ray.origin[remap.x] = centroid[remap.x]; - ray.origin[remap.y] = centroid[remap.y]; - ray.direction[remap.z] = 1; - centroid[remap.z] = static_cast(ray_distance_to_plane(ray, plane)); - } -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/winding.h b/misc/mediasource/extra/netradiant-src/radiant/winding.h deleted file mode 100644 index 233a9c82..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/winding.h +++ /dev/null @@ -1,322 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_WINDING_H) -#define INCLUDED_WINDING_H - -#include "debugging/debugging.h" - -#include - -#include "math/vector.h" -#include "container/array.h" - -enum ProjectionAxis -{ - eProjectionAxisX = 0, - eProjectionAxisY = 1, - eProjectionAxisZ = 2, -}; - -const float ProjectionAxisEpsilon = static_cast(0.0001); - -inline bool projectionaxis_better(float axis, float other) -{ - return fabs(axis) > fabs(other) + ProjectionAxisEpsilon; -} - -/// \brief Texture axis precedence: Z > X > Y -inline ProjectionAxis projectionaxis_for_normal(const Vector3& normal) -{ - return (projectionaxis_better(normal[eProjectionAxisY], normal[eProjectionAxisX])) - ? (projectionaxis_better(normal[eProjectionAxisY], normal[eProjectionAxisZ])) - ? eProjectionAxisY - : eProjectionAxisZ - : (projectionaxis_better(normal[eProjectionAxisX], normal[eProjectionAxisZ])) - ? eProjectionAxisX - : eProjectionAxisZ; -} - - -struct indexremap_t -{ - indexremap_t(std::size_t _x, std::size_t _y, std::size_t _z) - : x(_x), y(_y), z(_z) - { - } - std::size_t x, y, z; -}; - -inline indexremap_t indexremap_for_projectionaxis(const ProjectionAxis axis) -{ - switch(axis) - { - case eProjectionAxisX: return indexremap_t(1, 2, 0); - case eProjectionAxisY: return indexremap_t(2, 0, 1); - default: return indexremap_t(0, 1, 2); - } -} - -enum PlaneClassification -{ - ePlaneFront = 0, - ePlaneBack = 1, - ePlaneOn = 2, -}; - -#define MAX_POINTS_ON_WINDING 64 -const std::size_t c_brush_maxFaces = 1024; - - -class WindingVertex -{ -public: - Vector3 vertex; - Vector2 texcoord; - Vector3 tangent; - Vector3 bitangent; - std::size_t adjacent; -}; - - - -struct Winding -{ - typedef Array container_type; - - std::size_t numpoints; - container_type points; - - typedef container_type::iterator iterator; - typedef container_type::const_iterator const_iterator; - - Winding() : numpoints(0) - { - } - Winding(std::size_t size) : numpoints(0), points(size) - { - } - void resize(std::size_t size) - { - points.resize(size); - numpoints = 0; - } - - iterator begin() - { - return points.begin(); - } - const_iterator begin() const - { - return points.begin(); - } - iterator end() - { - return points.begin() + numpoints; - } - const_iterator end() const - { - return points.begin() + numpoints; - } - - WindingVertex& operator[](std::size_t index) - { - ASSERT_MESSAGE(index < points.size(), "winding: index out of bounds"); - return points[index]; - } - const WindingVertex& operator[](std::size_t index) const - { - ASSERT_MESSAGE(index < points.size(), "winding: index out of bounds"); - return points[index]; - } - - void push_back(const WindingVertex& point) - { - points[numpoints] = point; - ++numpoints; - } - void erase(iterator point) - { - for(iterator i = point + 1; i != end(); point = i, ++i) - { - *point = *i; - } - --numpoints; - } -}; - -typedef BasicVector3 DoubleVector3; - -class DoubleLine -{ -public: - DoubleVector3 origin; - DoubleVector3 direction; -}; - -class FixedWindingVertex -{ -public: - DoubleVector3 vertex; - DoubleLine edge; - std::size_t adjacent; - - FixedWindingVertex(const DoubleVector3& vertex_, const DoubleLine& edge_, std::size_t adjacent_) - : vertex(vertex_), edge(edge_), adjacent(adjacent_) - { - } -}; - -struct FixedWinding -{ - typedef std::vector Points; - Points points; - - FixedWinding() - { - points.reserve(MAX_POINTS_ON_WINDING); - } - - FixedWindingVertex& front() - { - return points.front(); - } - const FixedWindingVertex& front() const - { - return points.front(); - } - FixedWindingVertex& back() - { - return points.back(); - } - const FixedWindingVertex& back() const - { - return points.back(); - } - - void clear() - { - points.clear(); - } - - void push_back(const FixedWindingVertex& point) - { - points.push_back(point); - } - std::size_t size() const - { - return points.size(); - } - - FixedWindingVertex& operator[](std::size_t index) - { - //ASSERT_MESSAGE(index < MAX_POINTS_ON_WINDING, "winding: index out of bounds"); - return points[index]; - } - const FixedWindingVertex& operator[](std::size_t index) const - { - //ASSERT_MESSAGE(index < MAX_POINTS_ON_WINDING, "winding: index out of bounds"); - return points[index]; - } - -}; - - -inline void Winding_forFixedWinding(Winding& winding, const FixedWinding& fixed) -{ - winding.resize(fixed.size()); - winding.numpoints = fixed.size(); - for(std::size_t i = 0; i < fixed.size(); ++i) - { - winding[i].vertex[0] = static_cast(fixed[i].vertex[0]); - winding[i].vertex[1] = static_cast(fixed[i].vertex[1]); - winding[i].vertex[2] = static_cast(fixed[i].vertex[2]); - winding[i].adjacent = fixed[i].adjacent; - } -} - -inline std::size_t Winding_wrap(const Winding& winding, std::size_t i) -{ - ASSERT_MESSAGE(winding.numpoints != 0, "Winding_wrap: empty winding"); - return i % winding.numpoints; -} - -inline std::size_t Winding_next(const Winding& winding, std::size_t i) -{ - return Winding_wrap(winding, ++i); -} - - -class Plane3; - -void Winding_createInfinite(FixedWinding& w, const Plane3& plane, double infinity); - -const double ON_EPSILON = 1.0 / (1 << 8); - -/// \brief Returns true if edge (\p x, \p y) is smaller than the epsilon used to classify winding points against a plane. -inline bool Edge_isDegenerate(const Vector3& x, const Vector3& y) -{ - return vector3_length_squared(y - x) < (ON_EPSILON * ON_EPSILON); -} - -void Winding_Clip(const FixedWinding& winding, const Plane3& plane, const Plane3& clipPlane, std::size_t adjacent, FixedWinding& clipped); - -struct brushsplit_t -{ - brushsplit_t() - { - counts[0] = 0; - counts[1] = 0; - counts[2] = 0; - } - brushsplit_t& operator+=(const brushsplit_t& other) - { - counts[0] += other.counts[0]; - counts[1] += other.counts[1]; - counts[2] += other.counts[2]; - return *this; - } - std::size_t counts[3]; -}; - -brushsplit_t Winding_ClassifyPlane(const Winding& w, const Plane3& plane); - -bool Winding_PlanesConcave(const Winding& w1, const Winding& w2, const Plane3& plane1, const Plane3& plane2); -bool Winding_TestPlane(const Winding& w, const Plane3& plane, bool flipped); - -std::size_t Winding_FindAdjacent(const Winding& w, std::size_t face); - -std::size_t Winding_Opposite(const Winding& w, const std::size_t index, const std::size_t other); -std::size_t Winding_Opposite(const Winding& w, std::size_t index); - -void Winding_Centroid(const Winding& w, const Plane3& plane, Vector3& centroid); - - -inline void Winding_printConnectivity(Winding& winding) -{ - for(Winding::iterator i = winding.begin(); i != winding.end(); ++i) - { - std::size_t vertexIndex = std::distance(winding.begin(), i); - globalOutputStream() << "vertex: " << Unsigned(vertexIndex) << " adjacent: " << Unsigned((*i).adjacent) << "\n"; - } -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/windowobservers.cpp b/misc/mediasource/extra/netradiant-src/radiant/windowobservers.cpp deleted file mode 100644 index 481f6998..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/windowobservers.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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 "windowobservers.h" - -#include -#include -#include "generic/bitfield.h" - -namespace -{ - ModifierFlags g_modifier_state = c_modifierNone; -} - -typedef std::vector WindowObservers; - -inline void WindowObservers_OnModifierDown(WindowObservers& observers, ModifierFlags type) -{ - g_modifier_state = bitfield_enable(g_modifier_state, type); - for(WindowObservers::iterator i = observers.begin(); i != observers.end(); ++i) - { - (*i)->onModifierDown(type); - } -} - -inline void WindowObservers_OnModifierUp(WindowObservers& observers, ModifierFlags type) -{ - g_modifier_state = bitfield_disable(g_modifier_state, type); - for(WindowObservers::iterator i = observers.begin(); i != observers.end(); ++i) - { - (*i)->onModifierUp(type); - } -} - -#include - -gboolean selection_modifier_key_press(GtkWidget* widget, GdkEventKey* event, WindowObservers& observers) -{ - switch(event->keyval) - { - case GDK_Alt_L: - case GDK_Alt_R: - //globalOutputStream() << "Alt PRESSED\n"; - WindowObservers_OnModifierDown(observers, c_modifierAlt); - break; - case GDK_Shift_L: - case GDK_Shift_R: - //globalOutputStream() << "Shift PRESSED\n"; - WindowObservers_OnModifierDown(observers, c_modifierShift); - break; - case GDK_Control_L: - case GDK_Control_R: - //globalOutputStream() << "Control PRESSED\n"; - WindowObservers_OnModifierDown(observers, c_modifierControl); - break; - } - return FALSE; -} - -gboolean selection_modifier_key_release(GtkWidget* widget, GdkEventKey* event, WindowObservers& observers) -{ - switch(event->keyval) - { - case GDK_Alt_L: - case GDK_Alt_R: - //globalOutputStream() << "Alt RELEASED\n"; - WindowObservers_OnModifierUp(observers, c_modifierAlt); - break; - case GDK_Shift_L: - case GDK_Shift_R: - //globalOutputStream() << "Shift RELEASED\n"; - WindowObservers_OnModifierUp(observers, c_modifierShift); - break; - case GDK_Control_L: - case GDK_Control_R: - //globalOutputStream() << "Control RELEASED\n"; - WindowObservers_OnModifierUp(observers, c_modifierControl); - break; - } - return FALSE; -} - -void WindowObservers_UpdateModifier(WindowObservers& observers, ModifierFlags modifiers, ModifierFlags modifier) -{ - if(!bitfield_enabled(g_modifier_state, modifier) && bitfield_enabled(modifiers, modifier)) - { - WindowObservers_OnModifierDown(observers, modifier); - } - if(bitfield_enabled(g_modifier_state, modifier) && !bitfield_enabled(modifiers, modifier)) - { - WindowObservers_OnModifierUp(observers, modifier); - } -} - -void WindowObservers_UpdateModifiers(WindowObservers& observers, ModifierFlags modifiers) -{ - WindowObservers_UpdateModifier(observers, modifiers, c_modifierAlt); - WindowObservers_UpdateModifier(observers, modifiers, c_modifierShift); - WindowObservers_UpdateModifier(observers, modifiers, c_modifierControl); -} - -gboolean modifiers_button_press(GtkWidget* widget, GdkEventButton* event, WindowObservers* observers) -{ - if(event->type == GDK_BUTTON_PRESS) - { - WindowObservers_UpdateModifiers(*observers, modifiers_for_state(event->state)); - } - return FALSE; -} - -gboolean modifiers_button_release(GtkWidget* widget, GdkEventButton* event, WindowObservers* observers) -{ - if(event->type == GDK_BUTTON_RELEASE) - { - WindowObservers_UpdateModifiers(*observers, modifiers_for_state(event->state)); - } - return FALSE; -} - -gboolean modifiers_motion(GtkWidget *widget, GdkEventMotion *event, WindowObservers* observers) -{ - WindowObservers_UpdateModifiers(*observers, modifiers_for_state(event->state)); - return FALSE; -} - - -WindowObservers g_window_observers; - -void GlobalWindowObservers_updateModifiers(ModifierFlags modifiers) -{ - WindowObservers_UpdateModifiers(g_window_observers, modifiers); -} - -void GlobalWindowObservers_add(WindowObserver* observer) -{ - g_window_observers.push_back(observer); -} - -void GlobalWindowObservers_connectTopLevel(GtkWindow* window) -{ - g_signal_connect(G_OBJECT(window), "key_press_event", G_CALLBACK(selection_modifier_key_press), &g_window_observers); - g_signal_connect(G_OBJECT(window), "key_release_event", G_CALLBACK(selection_modifier_key_release), &g_window_observers); -} - -void GlobalWindowObservers_connectWidget(GtkWidget* widget) -{ - g_signal_connect(G_OBJECT(widget), "button_press_event", G_CALLBACK(modifiers_button_press), &g_window_observers); - g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(modifiers_button_release), &g_window_observers); - g_signal_connect(G_OBJECT(widget), "motion_notify_event", G_CALLBACK(modifiers_motion), &g_window_observers); -} - - diff --git a/misc/mediasource/extra/netradiant-src/radiant/windowobservers.h b/misc/mediasource/extra/netradiant-src/radiant/windowobservers.h deleted file mode 100644 index 7a47a936..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/windowobservers.h +++ /dev/null @@ -1,69 +0,0 @@ -/* -Copyright (C) 2001-2006, William Joseph. -All Rights Reserved. - -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(INCLUDED_WINDOWOBSERVERS_H) -#define INCLUDED_WINDOWOBSERVERS_H - -#include "windowobserver.h" - -#include - -#include "math/vector.h" - -class WindowObserver; -void GlobalWindowObservers_add(WindowObserver* observer); -typedef struct _GtkWidget GtkWidget; -typedef struct _GtkWindow GtkWindow; -void GlobalWindowObservers_connectWidget(GtkWidget* widget); -void GlobalWindowObservers_connectTopLevel(GtkWindow* window); - -inline ButtonIdentifier button_for_button(unsigned int button) -{ - switch(button) - { - case 1: - return c_buttonLeft; - case 2: - return c_buttonMiddle; - case 3: - return c_buttonRight; - } - return c_buttonInvalid; -} - -inline ModifierFlags modifiers_for_state(unsigned int state) -{ - ModifierFlags modifiers = c_modifierNone; - if(state & GDK_SHIFT_MASK) - modifiers |= c_modifierShift; - if(state & GDK_CONTROL_MASK) - modifiers |= c_modifierControl; - if(state & GDK_MOD1_MASK) - modifiers |= c_modifierAlt; - return modifiers; -} - -inline WindowVector WindowVector_forDouble(double x, double y) -{ - return WindowVector(static_cast(x), static_cast(y)); -} - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/xmlstuff.cpp b/misc/mediasource/extra/netradiant-src/radiant/xmlstuff.cpp deleted file mode 100644 index a92a1683..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/xmlstuff.cpp +++ /dev/null @@ -1,32 +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. -*/ - -#include "xmlstuff.h" - diff --git a/misc/mediasource/extra/netradiant-src/radiant/xmlstuff.h b/misc/mediasource/extra/netradiant-src/radiant/xmlstuff.h deleted file mode 100644 index 0ffb8e2b..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/xmlstuff.h +++ /dev/null @@ -1,90 +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. -*/ - -//----------------------------------------------------------------------------- -// -// DESCRIPTION: -// header for xml stuff used in radiant -// - -#ifndef __XMLSTUFF__ -#define __XMLSTUFF__ - -#include "libxml/parser.h" - -#include - -class ISAXHandler; - -// a 'user data' structure we pass along in the SAX callbacks to represent the current state -// the recurse value tracks the current depth in the tree -// message_info also stores information to exit the stream listening cleanly with an error: -// if msg_level == SYS_ERR, then we will reset the listening at the end of the current node -// the level for stopping the feed is stored in stop_depth -// unkown nodes are ignored, we use ignore_depth to track the level we start ignoring from -struct message_info_t -{ - int msg_level; // current message level (SYS_MSG, SYS_WRN, SYS_ERR) - int recurse; // current recursion depth (used to track various things) - int ignore_depth; // the ignore depth limit when we are jumping over unknown nodes (0 means we are not ignoring) - int stop_depth; // the depth we need to stop at the end - int geometry_depth; // are we parsing some geometry information (i.e. do we forward the SAX calls?) - ISAXHandler* pGeometry; // the handler - - enum unnamed0 { bufsize = 1024 }; - char m_buffer[bufsize]; - std::size_t m_length; -}; - -class IGL2DWindow; - -class ISAXHandler -{ -public: - virtual void Release() - { - } - virtual void saxStartElement(message_info_t* ctx, const xmlChar* name, const xmlChar** attrs) = 0; - virtual void saxEndElement(message_info_t* ctx, const xmlChar* name) = 0; - virtual void saxCharacters(message_info_t* ctx, const xmlChar* ch, int len) = 0; - virtual const char* getName() - { - return NULL; - } - virtual IGL2DWindow* Highlight() - { - return 0; - } - virtual void DropHighlight() - { - } -}; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/radiant/xywindow.cpp b/misc/mediasource/extra/netradiant-src/radiant/xywindow.cpp deleted file mode 100644 index 7352b386..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/xywindow.cpp +++ /dev/null @@ -1,3012 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// XY Window -// -// Leonardo Zide (leo@lokigames.com) -// - -#include "xywindow.h" - -#include "debugging/debugging.h" - -#include "ientity.h" -#include "igl.h" -#include "ibrush.h" -#include "iundo.h" -#include "iimage.h" -#include "ifilesystem.h" -#include "os/path.h" -#include "image.h" -#include "gtkutil/messagebox.h" - -#include -#include - -#include "generic/callback.h" -#include "string/string.h" -#include "stream/stringstream.h" - -#include "scenelib.h" -#include "eclasslib.h" -#include "renderer.h" -#include "moduleobserver.h" - -#include "gtkutil/menu.h" -#include "gtkutil/container.h" -#include "gtkutil/widget.h" -#include "gtkutil/glwidget.h" -#include "gtkutil/filechooser.h" -#include "gtkmisc.h" -#include "select.h" -#include "csg.h" -#include "brushmanip.h" -#include "selection.h" -#include "entity.h" -#include "camwindow.h" -#include "texwindow.h" -#include "mainframe.h" -#include "preferences.h" -#include "commands.h" -#include "feedback.h" -#include "grid.h" -#include "windowobservers.h" - -void LoadTextureRGBA(qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight); - -// d1223m -extern bool g_brush_always_caulk; - -//!\todo Rewrite. -class ClipPoint -{ -public: - Vector3 m_ptClip; // the 3d point - bool m_bSet; - - ClipPoint() - { - Reset(); - }; - void Reset() - { - m_ptClip[0] = m_ptClip[1] = m_ptClip[2] = 0.0; - m_bSet = false; - } - bool Set() - { - return m_bSet; - } - void Set(bool b) - { - m_bSet = b; - } - operator Vector3&() - { - return m_ptClip; - }; - - /*! Draw clip/path point with rasterized number label */ - void Draw(int num, float scale); - /*! Draw clip/path point with rasterized string label */ - void Draw(const char *label, float scale); -}; - -VIEWTYPE g_clip_viewtype; -bool g_bSwitch = true; -bool g_clip_useCaulk = false; -ClipPoint g_Clip1; -ClipPoint g_Clip2; -ClipPoint g_Clip3; -ClipPoint* g_pMovingClip = 0; - -/* Drawing clip points */ -void ClipPoint::Draw(int num, float scale) -{ - StringOutputStream label(4); - label << num; - Draw(label.c_str(), scale); -} - -void ClipPoint::Draw(const char *label, float scale) -{ - // draw point - glPointSize (4); - glColor3fv(vector3_to_array(g_xywindow_globals.color_clipper)); - glBegin (GL_POINTS); - glVertex3fv(vector3_to_array(m_ptClip)); - glEnd(); - glPointSize (1); - - float offset = 2.0f / scale; - - // draw label - glRasterPos3f (m_ptClip[0] + offset, m_ptClip[1] + offset, m_ptClip[2] + offset); - glCallLists (GLsizei(strlen(label)), GL_UNSIGNED_BYTE, label); -} - -float fDiff(float f1, float f2) -{ - if (f1 > f2) - return f1 - f2; - else - return f2 - f1; -} - -inline double ClipPoint_Intersect(const ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale) -{ - int nDim1 = (viewtype == YZ) ? 1 : 0; - int nDim2 = (viewtype == XY) ? 1 : 2; - double screenDistanceSquared(vector2_length_squared(Vector2(fDiff(clip.m_ptClip[nDim1], point[nDim1]) * scale, fDiff(clip.m_ptClip[nDim2], point[nDim2]) * scale))); - if(screenDistanceSquared < 8*8) - { - return screenDistanceSquared; - } - return FLT_MAX; -} - -inline void ClipPoint_testSelect(ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale, double& bestDistance, ClipPoint*& bestClip) -{ - if(clip.Set()) - { - double distance = ClipPoint_Intersect(clip, point, viewtype, scale); - if(distance < bestDistance) - { - bestDistance = distance; - bestClip = &clip; - } - } -} - -inline ClipPoint* GlobalClipPoints_Find(const Vector3& point, VIEWTYPE viewtype, float scale) -{ - double bestDistance = FLT_MAX; - ClipPoint* bestClip = 0; - ClipPoint_testSelect(g_Clip1, point, viewtype, scale, bestDistance, bestClip); - ClipPoint_testSelect(g_Clip2, point, viewtype, scale, bestDistance, bestClip); - ClipPoint_testSelect(g_Clip3, point, viewtype, scale, bestDistance, bestClip); - return bestClip; -} - -inline void GlobalClipPoints_Draw(float scale) -{ - // Draw clip points - if (g_Clip1.Set()) - g_Clip1.Draw(1, scale); - if (g_Clip2.Set()) - g_Clip2.Draw(2, scale); - if (g_Clip3.Set()) - g_Clip3.Draw(3, scale); -} - -inline bool GlobalClipPoints_valid() -{ - return g_Clip1.Set() && g_Clip2.Set(); -} - -void PlanePointsFromClipPoints(Vector3 planepts[3], const AABB& bounds, int viewtype) -{ - ASSERT_MESSAGE(GlobalClipPoints_valid(), "clipper points not initialised"); - planepts[0] = g_Clip1.m_ptClip; - planepts[1] = g_Clip2.m_ptClip; - planepts[2] = g_Clip3.m_ptClip; - Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); - Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); - if(!g_Clip3.Set()) - { - int n = (viewtype == XY) ? 2 : (viewtype == YZ) ? 0 : 1; - int x = (n == 0) ? 1 : 0; - int y = (n == 2) ? 1 : 2; - - if (n == 1) // on viewtype XZ, flip clip points - { - planepts[0][n] = maxs[n]; - planepts[1][n] = maxs[n]; - planepts[2][x] = g_Clip1.m_ptClip[x]; - planepts[2][y] = g_Clip1.m_ptClip[y]; - planepts[2][n] = mins[n]; - } - else - { - planepts[0][n] = mins[n]; - planepts[1][n] = mins[n]; - planepts[2][x] = g_Clip1.m_ptClip[x]; - planepts[2][y] = g_Clip1.m_ptClip[y]; - planepts[2][n] = maxs[n]; - } - } -} - -void Clip_Update() -{ - Vector3 planepts[3]; - if(!GlobalClipPoints_valid()) - { - planepts[0] = Vector3(0, 0, 0); - planepts[1] = Vector3(0, 0, 0); - planepts[2] = Vector3(0, 0, 0); - Scene_BrushSetClipPlane(GlobalSceneGraph(), Plane3(0, 0, 0, 0)); - } - else - { - AABB bounds(Vector3(0, 0, 0), Vector3(64, 64, 64)); - PlanePointsFromClipPoints(planepts, bounds, g_clip_viewtype); - if(g_bSwitch) - { - std::swap(planepts[0], planepts[1]); - } - Scene_BrushSetClipPlane(GlobalSceneGraph(), plane3_for_points(planepts[0], planepts[1], planepts[2])); - } - ClipperChangeNotify(); -} - -const char* Clip_getShader() -{ - return g_clip_useCaulk ? "textures/common/caulk" : TextureBrowser_GetSelectedShader(GlobalTextureBrowser()); -} - -void Clip() -{ - if (ClipMode() && GlobalClipPoints_valid()) - { - Vector3 planepts[3]; - AABB bounds(Vector3(0, 0, 0), Vector3(64, 64, 64)); - PlanePointsFromClipPoints(planepts, bounds, g_clip_viewtype); - Scene_BrushSplitByPlane(GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), (!g_bSwitch) ? eFront : eBack); - g_Clip1.Reset(); - g_Clip2.Reset(); - g_Clip3.Reset(); - Clip_Update(); - ClipperChangeNotify(); - } -} - -void SplitClip() -{ - if (ClipMode() && GlobalClipPoints_valid()) - { - Vector3 planepts[3]; - AABB bounds(Vector3(0, 0, 0), Vector3(64, 64, 64)); - PlanePointsFromClipPoints(planepts, bounds, g_clip_viewtype); - Scene_BrushSplitByPlane(GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), eFrontAndBack); - g_Clip1.Reset(); - g_Clip2.Reset(); - g_Clip3.Reset(); - Clip_Update(); - ClipperChangeNotify(); - } -} - -void FlipClip() -{ - g_bSwitch = !g_bSwitch; - Clip_Update(); - ClipperChangeNotify(); -} - -void OnClipMode(bool enabled) -{ - g_Clip1.Reset(); - g_Clip2.Reset(); - g_Clip3.Reset(); - - if(!enabled && g_pMovingClip) - { - g_pMovingClip = 0; - } - - Clip_Update(); - ClipperChangeNotify(); -} - -bool ClipMode() -{ - return GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip; -} - -void NewClipPoint(const Vector3& point) -{ - if (g_Clip1.Set() == false) - { - g_Clip1.m_ptClip = point; - g_Clip1.Set(true); - } - else if (g_Clip2.Set() == false) - { - g_Clip2.m_ptClip = point; - g_Clip2.Set(true); - } - else if (g_Clip3.Set() == false) - { - g_Clip3.m_ptClip = point; - g_Clip3.Set(true); - } - else - { - g_Clip1.Reset(); - g_Clip2.Reset(); - g_Clip3.Reset(); - g_Clip1.m_ptClip = point; - g_Clip1.Set(true); - } - - Clip_Update(); - ClipperChangeNotify(); -} - - - -struct xywindow_globals_private_t -{ - bool d_showgrid; - - // these are in the View > Show menu with Show coordinates - bool show_names; - bool show_coordinates; - bool show_angles; - bool show_outline; - bool show_axis; - - bool d_show_work; - - bool show_blocks; - int blockSize; - - bool m_bCamXYUpdate; - bool m_bChaseMouse; - bool m_bSizePaint; - - xywindow_globals_private_t() : - d_showgrid(true), - - show_names(false), - show_coordinates(true), - show_angles(true), - show_outline(false), - show_axis(true), - - d_show_work(false), - - show_blocks(false), - - m_bCamXYUpdate(true), - m_bChaseMouse(true), - m_bSizePaint(true) - { - } - -}; - -xywindow_globals_t g_xywindow_globals; -xywindow_globals_private_t g_xywindow_globals_private; - -const unsigned int RAD_NONE = 0x00; -const unsigned int RAD_SHIFT = 0x01; -const unsigned int RAD_ALT = 0x02; -const unsigned int RAD_CONTROL = 0x04; -const unsigned int RAD_PRESS = 0x08; -const unsigned int RAD_LBUTTON = 0x10; -const unsigned int RAD_MBUTTON = 0x20; -const unsigned int RAD_RBUTTON = 0x40; - -inline ButtonIdentifier button_for_flags(unsigned int flags) -{ - if(flags & RAD_LBUTTON) - return c_buttonLeft; - if(flags & RAD_RBUTTON) - return c_buttonRight; - if(flags & RAD_MBUTTON) - return c_buttonMiddle; - return c_buttonInvalid; -} - -inline ModifierFlags modifiers_for_flags(unsigned int flags) -{ - ModifierFlags modifiers = c_modifierNone; - if(flags & RAD_SHIFT) - modifiers |= c_modifierShift; - if(flags & RAD_CONTROL) - modifiers |= c_modifierControl; - if(flags & RAD_ALT) - modifiers |= c_modifierAlt; - return modifiers; -} - -inline unsigned int buttons_for_button_and_modifiers(ButtonIdentifier button, ModifierFlags flags) -{ - unsigned int buttons = 0; - - switch (button.get()) - { - case ButtonEnumeration::LEFT: buttons |= RAD_LBUTTON; break; - case ButtonEnumeration::MIDDLE: buttons |= RAD_MBUTTON; break; - case ButtonEnumeration::RIGHT: buttons |= RAD_RBUTTON; break; - } - - if(bitfield_enabled(flags, c_modifierControl)) - buttons |= RAD_CONTROL; - - if(bitfield_enabled(flags, c_modifierShift)) - buttons |= RAD_SHIFT; - - if(bitfield_enabled(flags, c_modifierAlt)) - buttons |= RAD_ALT; - - return buttons; -} - -inline unsigned int buttons_for_event_button(GdkEventButton* event) -{ - unsigned int flags = 0; - - switch (event->button) - { - case 1: flags |= RAD_LBUTTON; break; - case 2: flags |= RAD_MBUTTON; break; - case 3: flags |= RAD_RBUTTON; break; - } - - if ((event->state & GDK_CONTROL_MASK) != 0) - flags |= RAD_CONTROL; - - if ((event->state & GDK_SHIFT_MASK) != 0) - flags |= RAD_SHIFT; - - if((event->state & GDK_MOD1_MASK) != 0) - flags |= RAD_ALT; - - return flags; -} - -inline unsigned int buttons_for_state(guint state) -{ - unsigned int flags = 0; - - if ((state & GDK_BUTTON1_MASK) != 0) - flags |= RAD_LBUTTON; - - if ((state & GDK_BUTTON2_MASK) != 0) - flags |= RAD_MBUTTON; - - if ((state & GDK_BUTTON3_MASK) != 0) - flags |= RAD_RBUTTON; - - if ((state & GDK_CONTROL_MASK) != 0) - flags |= RAD_CONTROL; - - if ((state & GDK_SHIFT_MASK) != 0) - flags |= RAD_SHIFT; - - if ((state & GDK_MOD1_MASK) != 0) - flags |= RAD_ALT; - - return flags; -} - - -void XYWnd::SetScale(float f) -{ - m_fScale = f; - updateProjection(); - updateModelview(); - XYWnd_Update(*this); -} - -void XYWnd_ZoomIn(XYWnd* xy) -{ - float max_scale = 64; - float scale = xy->Scale() * 5.0f / 4.0f; - if(scale > max_scale) - { - if(xy->Scale() != max_scale) - { - xy->SetScale (max_scale); - } - } - else - { - xy->SetScale(scale); - } -} - - -// NOTE: the zoom out factor is 4/5, we could think about customizing it -// we don't go below a zoom factor corresponding to 10% of the max world size -// (this has to be computed against the window size) -void XYWnd_ZoomOut(XYWnd* xy) -{ - float min_scale = MIN(xy->Width(),xy->Height()) / ( 1.1f * (g_MaxWorldCoord-g_MinWorldCoord)); - float scale = xy->Scale() * 4.0f / 5.0f; - if(scale < min_scale) - { - if(xy->Scale() != min_scale) - { - xy->SetScale (min_scale); - } - } - else - { - xy->SetScale(scale); - } -} - -VIEWTYPE GlobalXYWnd_getCurrentViewType() -{ - ASSERT_NOTNULL(g_pParentWnd); - ASSERT_NOTNULL(g_pParentWnd->ActiveXY()); - return g_pParentWnd->ActiveXY()->GetViewType(); -} - -// ============================================================================= -// variables - -bool g_bCrossHairs = false; - -GtkMenu* XYWnd::m_mnuDrop = 0; - -// this is disabled, and broken -// http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394 -#if 0 -void WXY_Print() -{ - long width, height; - width = g_pParentWnd->ActiveXY()->Width(); - height = g_pParentWnd->ActiveXY()->Height(); - unsigned char* img; - const char* filename; - - filename = file_dialog(GTK_WIDGET(MainFrame_getWindow()), FALSE, "Save Image", 0, FILTER_BMP); - if (!filename) - return; - - g_pParentWnd->ActiveXY()->MakeCurrent(); - img = (unsigned char*)malloc (width*height*3); - glReadPixels (0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,img); - - FILE *fp; - fp = fopen(filename, "wb"); - if (fp) - { - unsigned short bits; - unsigned long cmap, bfSize; - - bits = 24; - cmap = 0; - bfSize = 54 + width*height*3; - - long byteswritten = 0; - long pixoff = 54 + cmap*4; - short res = 0; - char m1 ='B', m2 ='M'; - fwrite(&m1, 1, 1, fp); byteswritten++; // B - fwrite(&m2, 1, 1, fp); byteswritten++; // M - fwrite(&bfSize, 4, 1, fp); byteswritten+=4;// bfSize - fwrite(&res, 2, 1, fp); byteswritten+=2;// bfReserved1 - fwrite(&res, 2, 1, fp); byteswritten+=2;// bfReserved2 - fwrite(&pixoff, 4, 1, fp); byteswritten+=4;// bfOffBits - - unsigned long biSize = 40, compress = 0, size = 0; - long pixels = 0; - unsigned short planes = 1; - fwrite(&biSize, 4, 1, fp); byteswritten+=4;// biSize - fwrite(&width, 4, 1, fp); byteswritten+=4;// biWidth - fwrite(&height, 4, 1, fp); byteswritten+=4;// biHeight - fwrite(&planes, 2, 1, fp); byteswritten+=2;// biPlanes - fwrite(&bits, 2, 1, fp); byteswritten+=2;// biBitCount - fwrite(&compress, 4, 1, fp);byteswritten+=4;// biCompression - fwrite(&size, 4, 1, fp); byteswritten+=4;// biSizeImage - fwrite(&pixels, 4, 1, fp); byteswritten+=4;// biXPelsPerMeter - fwrite(&pixels, 4, 1, fp); byteswritten+=4;// biYPelsPerMeter - fwrite(&cmap, 4, 1, fp); byteswritten+=4;// biClrUsed - fwrite(&cmap, 4, 1, fp); byteswritten+=4;// biClrImportant - - unsigned long widthDW = (((width*24) + 31) / 32 * 4); - long row, row_size = width*3; - for (row = 0; row < height; row++) - { - unsigned char* buf = img+row*row_size; - - // write a row - int col; - for (col = 0; col < row_size; col += 3) - { - putc(buf[col+2], fp); - putc(buf[col+1], fp); - putc(buf[col], fp); - } - byteswritten += row_size; - - unsigned long count; - for (count = row_size; count < widthDW; count++) - { - putc(0, fp); // dummy - byteswritten++; - } - } - - fclose(fp); - } - - free (img); -} -#endif - - -#include "timer.h" - -Timer g_chasemouse_timer; - -void XYWnd::ChaseMouse() -{ - float multiplier = g_chasemouse_timer.elapsed_msec() / 10.0f; - Scroll(float_to_integer(multiplier * m_chasemouse_delta_x), float_to_integer(multiplier * -m_chasemouse_delta_y)); - - //globalOutputStream() << "chasemouse: multiplier=" << multiplier << " x=" << m_chasemouse_delta_x << " y=" << m_chasemouse_delta_y << '\n'; - - XY_MouseMoved(m_chasemouse_current_x, m_chasemouse_current_y , getButtonState()); - g_chasemouse_timer.start(); -} - -gboolean xywnd_chasemouse(gpointer data) -{ - reinterpret_cast(data)->ChaseMouse(); - return TRUE; -} - -inline const int& min_int(const int& left, const int& right) -{ - return std::min(left, right); -} - -bool XYWnd::chaseMouseMotion(int pointx, int pointy) -{ - m_chasemouse_delta_x = 0; - m_chasemouse_delta_y = 0; - - if (g_xywindow_globals_private.m_bChaseMouse && getButtonState() == RAD_LBUTTON) - { - const int epsilon = 16; - - if (pointx < epsilon) - { - m_chasemouse_delta_x = std::max(pointx, 0) - epsilon; - } - else if ((pointx - m_nWidth) > -epsilon) - { - m_chasemouse_delta_x = min_int((pointx - m_nWidth), 0) + epsilon; - } - - if (pointy < epsilon) - { - m_chasemouse_delta_y = std::max(pointy, 0) - epsilon; - } - else if ((pointy - m_nHeight) > -epsilon) - { - m_chasemouse_delta_y = min_int((pointy - m_nHeight), 0) + epsilon; - } - - if(m_chasemouse_delta_y != 0 || m_chasemouse_delta_x != 0) - { - //globalOutputStream() << "chasemouse motion: x=" << pointx << " y=" << pointy << "... "; - m_chasemouse_current_x = pointx; - m_chasemouse_current_y = pointy; - if(m_chasemouse_handler == 0) - { - //globalOutputStream() << "chasemouse timer start... "; - g_chasemouse_timer.start(); - m_chasemouse_handler = g_idle_add(xywnd_chasemouse, this); - } - return true; - } - else - { - if(m_chasemouse_handler != 0) - { - //globalOutputStream() << "chasemouse cancel\n"; - g_source_remove(m_chasemouse_handler); - m_chasemouse_handler = 0; - } - } - } - else - { - if(m_chasemouse_handler != 0) - { - //globalOutputStream() << "chasemouse cancel\n"; - g_source_remove(m_chasemouse_handler); - m_chasemouse_handler = 0; - } - } - return false; -} - -// ============================================================================= -// XYWnd class -Shader* XYWnd::m_state_selected = 0; - -void xy_update_xor_rectangle(XYWnd& self, rect_t area) -{ - if(GTK_WIDGET_VISIBLE(self.GetWidget())) - { - self.m_XORRectangle.set(rectangle_from_area(area.min, area.max, self.Width(), self.Height())); - } -} - -gboolean xywnd_button_press(GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd) -{ - if(event->type == GDK_BUTTON_PRESS) - { - g_pParentWnd->SetActiveXY(xywnd); - - xywnd->ButtonState_onMouseDown(buttons_for_event_button(event)); - - xywnd->onMouseDown(WindowVector(event->x, event->y), button_for_button(event->button), modifiers_for_state(event->state)); - } - return FALSE; -} - -gboolean xywnd_button_release(GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd) -{ - if(event->type == GDK_BUTTON_RELEASE) - { - xywnd->XY_MouseUp(static_cast(event->x), static_cast(event->y), buttons_for_event_button(event)); - - xywnd->ButtonState_onMouseUp(buttons_for_event_button(event)); - } - return FALSE; -} - -gboolean xywnd_focus_in(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd) -{ - if(event->type == GDK_FOCUS_CHANGE) - { - if(event->in) - g_pParentWnd->SetActiveXY(xywnd); - } - return FALSE; -} - -void xywnd_motion(gdouble x, gdouble y, guint state, void* data) -{ - if(reinterpret_cast(data)->chaseMouseMotion(static_cast(x), static_cast(y))) - { - return; - } - reinterpret_cast(data)->XY_MouseMoved(static_cast(x), static_cast(y), buttons_for_state(state)); -} - -gboolean xywnd_wheel_scroll(GtkWidget* widget, GdkEventScroll* event, XYWnd* xywnd) -{ - if(event->direction == GDK_SCROLL_UP) - { - XYWnd_ZoomIn(xywnd); - } - else if(event->direction == GDK_SCROLL_DOWN) - { - XYWnd_ZoomOut(xywnd); - } - return FALSE; -} - -gboolean xywnd_size_allocate(GtkWidget* widget, GtkAllocation* allocation, XYWnd* xywnd) -{ - xywnd->m_nWidth = allocation->width; - xywnd->m_nHeight = allocation->height; - xywnd->updateProjection(); - xywnd->m_window_observer->onSizeChanged(xywnd->Width(), xywnd->Height()); - return FALSE; -} - -gboolean xywnd_expose(GtkWidget* widget, GdkEventExpose* event, XYWnd* xywnd) -{ - if(glwidget_make_current(xywnd->GetWidget()) != FALSE) - { - if(Map_Valid(g_map) && ScreenUpdates_Enabled()) - { - GlobalOpenGL_debugAssertNoErrors(); - xywnd->XY_Draw(); - GlobalOpenGL_debugAssertNoErrors(); - - xywnd->m_XORRectangle.set(rectangle_t()); - } - glwidget_swap_buffers(xywnd->GetWidget()); - } - return FALSE; -} - - -void XYWnd_CameraMoved(XYWnd& xywnd) -{ - if(g_xywindow_globals_private.m_bCamXYUpdate) - { - XYWnd_Update(xywnd); - } -} - -XYWnd::XYWnd() : - m_gl_widget(glwidget_new(FALSE)), - m_deferredDraw(WidgetQueueDrawCaller(*m_gl_widget)), - m_deferred_motion(xywnd_motion, this), - m_parent(0), - m_window_observer(NewWindowObserver()), - m_XORRectangle(m_gl_widget), - m_chasemouse_handler(0) -{ - m_bActive = false; - m_buttonstate = 0; - - m_bNewBrushDrag = false; - m_move_started = false; - m_zoom_started = false; - - m_nWidth = 0; - m_nHeight = 0; - - m_vOrigin[0] = 0; - m_vOrigin[1] = 20; - m_vOrigin[2] = 46; - m_fScale = 1; - m_viewType = XY; - - m_backgroundActivated = false; - m_alpha = 1.0f; - m_xmin = 0.0f; - m_ymin = 0.0f; - m_xmax = 0.0f; - m_ymax = 0.0f; - - m_entityCreate = false; - - m_mnuDrop = 0; - - GlobalWindowObservers_add(m_window_observer); - GlobalWindowObservers_connectWidget(m_gl_widget); - - m_window_observer->setRectangleDrawCallback(ReferenceCaller1(*this)); - m_window_observer->setView(m_view); - - gtk_widget_ref(m_gl_widget); - - gtk_widget_set_events(m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK); - GTK_WIDGET_SET_FLAGS(m_gl_widget, GTK_CAN_FOCUS); - - m_sizeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "size_allocate", G_CALLBACK(xywnd_size_allocate), this); - m_exposeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "expose_event", G_CALLBACK(xywnd_expose), this); - - g_signal_connect(G_OBJECT(m_gl_widget), "button_press_event", G_CALLBACK(xywnd_button_press), this); - g_signal_connect(G_OBJECT(m_gl_widget), "button_release_event", G_CALLBACK(xywnd_button_release), this); - g_signal_connect(G_OBJECT(m_gl_widget), "focus_in_event", G_CALLBACK(xywnd_focus_in), this); - g_signal_connect(G_OBJECT(m_gl_widget), "motion_notify_event", G_CALLBACK(DeferredMotion::gtk_motion), &m_deferred_motion); - - g_signal_connect(G_OBJECT(m_gl_widget), "scroll_event", G_CALLBACK(xywnd_wheel_scroll), this); - - Map_addValidCallback(g_map, DeferredDrawOnMapValidChangedCaller(m_deferredDraw)); - - updateProjection(); - updateModelview(); - - AddSceneChangeCallback(ReferenceCaller(*this)); - AddCameraMovedCallback(ReferenceCaller(*this)); - - PressedButtons_connect(g_pressedButtons, m_gl_widget); - - onMouseDown.connectLast(makeSignalHandler3(MouseDownCaller(), *this)); -} - -XYWnd::~XYWnd() -{ - onDestroyed(); - - if(m_mnuDrop != 0) - { - gtk_widget_destroy(GTK_WIDGET(m_mnuDrop)); - m_mnuDrop = 0; - } - - g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_sizeHandler); - g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_exposeHandler); - - gtk_widget_unref(m_gl_widget); - - m_window_observer->release(); -} - -void XYWnd::captureStates() -{ - m_state_selected = GlobalShaderCache().capture("$XY_OVERLAY"); -} - -void XYWnd::releaseStates() -{ - GlobalShaderCache().release("$XY_OVERLAY"); -} - -const Vector3& XYWnd::GetOrigin() -{ - return m_vOrigin; -} - -void XYWnd::SetOrigin(const Vector3& origin) -{ - m_vOrigin = origin; - updateModelview(); -} - -void XYWnd::Scroll(int x, int y) -{ - int nDim1 = (m_viewType == YZ) ? 1 : 0; - int nDim2 = (m_viewType == XY) ? 1 : 2; - m_vOrigin[nDim1] += x / m_fScale; - m_vOrigin[nDim2] += y / m_fScale; - updateModelview(); - queueDraw(); -} - -unsigned int Clipper_buttons() -{ - return RAD_LBUTTON; -} - -void XYWnd::DropClipPoint(int pointx, int pointy) -{ - Vector3 point; - - XY_ToPoint(pointx, pointy, point); - - Vector3 mid; - Select_GetMid(mid); - g_clip_viewtype = static_cast(GetViewType()); - const int nDim = (g_clip_viewtype == YZ ) ? 0 : ( (g_clip_viewtype == XZ) ? 1 : 2 ); - point[nDim] = mid[nDim]; - vector3_snap(point, GetSnapGridSize()); - NewClipPoint(point); -} - -void XYWnd::Clipper_OnLButtonDown(int x, int y) -{ - Vector3 mousePosition; - XY_ToPoint(x, y , mousePosition); - g_pMovingClip = GlobalClipPoints_Find(mousePosition, (VIEWTYPE)m_viewType, m_fScale); - if(!g_pMovingClip) - { - DropClipPoint(x, y); - } -} - -void XYWnd::Clipper_OnLButtonUp(int x, int y) -{ - if (g_pMovingClip) - { - g_pMovingClip = 0; - } -} - -void XYWnd::Clipper_OnMouseMoved(int x, int y) -{ - if (g_pMovingClip) - { - XY_ToPoint(x, y , g_pMovingClip->m_ptClip); - XY_SnapToGrid(g_pMovingClip->m_ptClip); - Clip_Update(); - ClipperChangeNotify(); - } -} - -void XYWnd::Clipper_Crosshair_OnMouseMoved(int x, int y) -{ - Vector3 mousePosition; - XY_ToPoint(x, y , mousePosition); - if(ClipMode() && GlobalClipPoints_Find(mousePosition, (VIEWTYPE)m_viewType, m_fScale) != 0) - { - GdkCursor *cursor; - cursor = gdk_cursor_new (GDK_CROSSHAIR); - gdk_window_set_cursor (m_gl_widget->window, cursor); - gdk_cursor_unref (cursor); - } - else - { - gdk_window_set_cursor (m_gl_widget->window, 0); - } -} - -unsigned int MoveCamera_buttons() -{ - return RAD_CONTROL | (g_glwindow_globals.m_nMouseType == ETwoButton ? RAD_RBUTTON : RAD_MBUTTON); -} - -void XYWnd_PositionCamera(XYWnd* xywnd, int x, int y, CamWnd& camwnd) -{ - Vector3 origin(Camera_getOrigin(camwnd)); - xywnd->XY_ToPoint(x, y, origin); - xywnd->XY_SnapToGrid(origin); - Camera_setOrigin(camwnd, origin); -} - -unsigned int OrientCamera_buttons() -{ - if(g_glwindow_globals.m_nMouseType == ETwoButton) - return RAD_RBUTTON | RAD_SHIFT | RAD_CONTROL; - return RAD_MBUTTON; -} - -void XYWnd_OrientCamera(XYWnd* xywnd, int x, int y, CamWnd& camwnd) -{ - Vector3 point = g_vector3_identity; - xywnd->XY_ToPoint(x, y, point); - xywnd->XY_SnapToGrid(point); - vector3_subtract(point, Camera_getOrigin(camwnd)); - - int n1 = (xywnd->GetViewType() == XY) ? 1 : 2; - int n2 = (xywnd->GetViewType() == YZ) ? 1 : 0; - int nAngle = (xywnd->GetViewType() == XY) ? CAMERA_YAW : CAMERA_PITCH; - if (point[n1] || point[n2]) - { - Vector3 angles(Camera_getAngles(camwnd)); - angles[nAngle] = static_cast(radians_to_degrees(atan2 (point[n1], point[n2]))); - Camera_setAngles(camwnd, angles); - } -} - -/* -============== -NewBrushDrag -============== -*/ -unsigned int NewBrushDrag_buttons() -{ - return RAD_LBUTTON; -} - -void XYWnd::NewBrushDrag_Begin(int x, int y) -{ - m_NewBrushDrag = 0; - m_nNewBrushPressx = x; - m_nNewBrushPressy = y; - - m_bNewBrushDrag = true; - GlobalUndoSystem().start(); -} - -void XYWnd::NewBrushDrag_End(int x, int y) -{ - if(m_NewBrushDrag != 0) - { - GlobalUndoSystem().finish("brushDragNew"); - } -} - -void XYWnd::NewBrushDrag(int x, int y) -{ - Vector3 mins, maxs; - XY_ToPoint(m_nNewBrushPressx, m_nNewBrushPressy, mins); - XY_SnapToGrid(mins); - XY_ToPoint(x, y, maxs); - XY_SnapToGrid(maxs); - - int nDim = (m_viewType == XY) ? 2 : (m_viewType == YZ) ? 0 : 1; - - mins[nDim] = float_snapped(Select_getWorkZone().d_work_min[nDim], GetSnapGridSize()); - maxs[nDim] = float_snapped(Select_getWorkZone().d_work_max[nDim], GetSnapGridSize()); - - if (maxs[nDim] <= mins[nDim]) - maxs[nDim] = mins[nDim] + GetGridSize(); - - for(int i=0 ; i<3 ; i++) - { - if (mins[i] == maxs[i]) - return; // don't create a degenerate brush - if (mins[i] > maxs[i]) - { - float temp = mins[i]; - mins[i] = maxs[i]; - maxs[i] = temp; - } - } - - if(m_NewBrushDrag == 0) - { - NodeSmartReference node(GlobalBrushCreator().createBrush()); - Node_getTraversable(Map_FindOrInsertWorldspawn(g_map))->insert(node); - - scene::Path brushpath(makeReference(GlobalSceneGraph().root())); - brushpath.push(makeReference(*Map_GetWorldspawn(g_map))); - brushpath.push(makeReference(node.get())); - selectPath(brushpath, true); - - m_NewBrushDrag = node.get_pointer(); - } - - // d1223m - //Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); - Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), - g_brush_always_caulk ? - "textures/common/caulk" : TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); -} - -void entitycreate_activated(GtkWidget* item) -{ - scene::Node* world_node = Map_FindWorldspawn(g_map); - const char* entity_name = gtk_label_get_text(GTK_LABEL(GTK_BIN(item)->child)); - - if(!(world_node && string_equal(entity_name, "worldspawn"))) - { - g_pParentWnd->ActiveXY()->OnEntityCreate(entity_name); - } else { - GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(MainFrame_getWindow()), "There's already a worldspawn in your map!" - "", - "Info", - eMB_OK, - eMB_ICONDEFAULT); - } -} - -void EntityClassMenu_addItem(GtkMenu* menu, const char* name) -{ - GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(name)); - g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(entitycreate_activated), item); - gtk_widget_show(GTK_WIDGET(item)); - menu_add_item(menu, item); -} - -class EntityClassMenuInserter : public EntityClassVisitor -{ - typedef std::pair MenuPair; - typedef std::vector MenuStack; - MenuStack m_stack; - CopiedString m_previous; -public: - EntityClassMenuInserter(GtkMenu* menu) - { - m_stack.reserve(2); - m_stack.push_back(MenuPair(menu, "")); - } - ~EntityClassMenuInserter() - { - if(!string_empty(m_previous.c_str())) - { - addItem(m_previous.c_str(), ""); - } - } - void visit(EntityClass* e) - { - ASSERT_MESSAGE(!string_empty(e->name()), "entity-class has no name"); - if(!string_empty(m_previous.c_str())) - { - addItem(m_previous.c_str(), e->name()); - } - m_previous = e->name(); - } - void pushMenu(const CopiedString& name) - { - GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(name.c_str())); - gtk_widget_show(GTK_WIDGET(item)); - container_add_widget(GTK_CONTAINER(m_stack.back().first), GTK_WIDGET(item)); - - GtkMenu* submenu = GTK_MENU(gtk_menu_new()); - gtk_menu_item_set_submenu(item, GTK_WIDGET(submenu)); - - m_stack.push_back(MenuPair(submenu, name)); - } - void popMenu() - { - m_stack.pop_back(); - } - void addItem(const char* name, const char* next) - { - const char* underscore = strchr(name, '_'); - - if(underscore != 0 && underscore != name) - { - bool nextEqual = string_equal_n(name, next, (underscore + 1) - name); - const char* parent = m_stack.back().second.c_str(); - - if(!string_empty(parent) - && string_length(parent) == std::size_t(underscore - name) - && string_equal_n(name, parent, underscore - name)) // this is a child - { - } - else if(nextEqual) - { - if(m_stack.size() == 2) - { - popMenu(); - } - pushMenu(CopiedString(StringRange(name, underscore))); - } - else if(m_stack.size() == 2) - { - popMenu(); - } - } - else if(m_stack.size() == 2) - { - popMenu(); - } - - EntityClassMenu_addItem(m_stack.back().first, name); - } -}; - -void XYWnd::OnContextMenu() -{ - if (g_xywindow_globals.m_bRightClick == false) - return; - - if (m_mnuDrop == 0) // first time, load it up - { - GtkMenu* menu = m_mnuDrop = GTK_MENU(gtk_menu_new()); - - EntityClassMenuInserter inserter(menu); - GlobalEntityClassManager().forEach(inserter); - } - - gtk_menu_popup(m_mnuDrop, 0, 0, 0, 0, 1, GDK_CURRENT_TIME); -} - -FreezePointer g_xywnd_freezePointer; - -unsigned int Move_buttons() -{ - return RAD_RBUTTON; -} - -void XYWnd_moveDelta(int x, int y, unsigned int state, void* data) -{ - reinterpret_cast(data)->EntityCreate_MouseMove(x, y); - reinterpret_cast(data)->Scroll(-x, y); -} - -gboolean XYWnd_Move_focusOut(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd) -{ - xywnd->Move_End(); - return FALSE; -} - -void XYWnd::Move_Begin() -{ - if(m_move_started) - { - Move_End(); - } - m_move_started = true; - g_xywnd_freezePointer.freeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow(), XYWnd_moveDelta, this); - m_move_focusOut = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(XYWnd_Move_focusOut), this); -} - -void XYWnd::Move_End() -{ - m_move_started = false; - g_xywnd_freezePointer.unfreeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow()); - g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_move_focusOut); -} - -unsigned int Zoom_buttons() -{ - return RAD_RBUTTON | RAD_SHIFT; -} - -int g_dragZoom = 0; - -void XYWnd_zoomDelta(int x, int y, unsigned int state, void* data) -{ - if(y != 0) - { - g_dragZoom += y; - - while(abs(g_dragZoom) > 8) - { - if(g_dragZoom > 0) - { - XYWnd_ZoomOut(reinterpret_cast(data)); - g_dragZoom -= 8; - } - else - { - XYWnd_ZoomIn(reinterpret_cast(data)); - g_dragZoom += 8; - } - } - } -} - -gboolean XYWnd_Zoom_focusOut(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd) -{ - xywnd->Zoom_End(); - return FALSE; -} - -void XYWnd::Zoom_Begin() -{ - if(m_zoom_started) - { - Zoom_End(); - } - m_zoom_started = true; - g_dragZoom = 0; - g_xywnd_freezePointer.freeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow(), XYWnd_zoomDelta, this); - m_zoom_focusOut = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(XYWnd_Zoom_focusOut), this); -} - -void XYWnd::Zoom_End() -{ - m_zoom_started = false; - g_xywnd_freezePointer.unfreeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow()); - g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_zoom_focusOut); -} - -// makes sure the selected brush or camera is in view -void XYWnd::PositionView(const Vector3& position) -{ - int nDim1 = (m_viewType == YZ) ? 1 : 0; - int nDim2 = (m_viewType == XY) ? 1 : 2; - - m_vOrigin[nDim1] = position[nDim1]; - m_vOrigin[nDim2] = position[nDim2]; - - updateModelview(); - - XYWnd_Update(*this); -} - -void XYWnd::SetViewType(VIEWTYPE viewType) -{ - m_viewType = viewType; - updateModelview(); - - if(m_parent != 0) - { - gtk_window_set_title(m_parent, ViewType_getTitle(m_viewType)); - } -} - - -inline WindowVector WindowVector_forInteger(int x, int y) -{ - return WindowVector(static_cast(x), static_cast(y)); -} - -void XYWnd::mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) -{ - XY_MouseDown(static_cast(position.x()), static_cast(position.y()), buttons_for_button_and_modifiers(button, modifiers)); -} -void XYWnd::XY_MouseDown (int x, int y, unsigned int buttons) -{ - if(buttons == Move_buttons()) - { - Move_Begin(); - EntityCreate_MouseDown(x, y); - } - else if(buttons == Zoom_buttons()) - { - Zoom_Begin(); - } - else if(ClipMode() && buttons == Clipper_buttons()) - { - Clipper_OnLButtonDown(x, y); - } - else if(buttons == NewBrushDrag_buttons() && GlobalSelectionSystem().countSelected() == 0) - { - NewBrushDrag_Begin(x, y); - } - // control mbutton = move camera - else if (buttons == MoveCamera_buttons()) - { - XYWnd_PositionCamera(this, x, y, *g_pParentWnd->GetCamWnd()); - } - // mbutton = angle camera - else if(buttons == OrientCamera_buttons()) - { - XYWnd_OrientCamera(this, x, y, *g_pParentWnd->GetCamWnd()); - } - else - { - m_window_observer->onMouseDown(WindowVector_forInteger(x, y), button_for_flags(buttons), modifiers_for_flags(buttons)); - } -} - -void XYWnd::XY_MouseUp(int x, int y, unsigned int buttons) -{ - if(m_move_started) - { - Move_End(); - EntityCreate_MouseUp(x, y); - } - else if(m_zoom_started) - { - Zoom_End(); - } - else if (ClipMode() && buttons == Clipper_buttons()) - { - Clipper_OnLButtonUp(x, y); - } - else if (m_bNewBrushDrag) - { - m_bNewBrushDrag = false; - NewBrushDrag_End(x, y); - } - else - { - m_window_observer->onMouseUp(WindowVector_forInteger(x, y), button_for_flags(buttons), modifiers_for_flags(buttons)); - } -} - -void XYWnd::XY_MouseMoved (int x, int y, unsigned int buttons) -{ - // rbutton = drag xy origin - if(m_move_started) - { - } - // zoom in/out - else if(m_zoom_started) - { - } - - else if (ClipMode() && g_pMovingClip != 0) - { - Clipper_OnMouseMoved(x, y); - } - // lbutton without selection = drag new brush - else if (m_bNewBrushDrag) - { - NewBrushDrag(x, y); - } - - // control mbutton = move camera - else if (getButtonState() == MoveCamera_buttons()) - { - XYWnd_PositionCamera(this, x, y, *g_pParentWnd->GetCamWnd()); - } - - // mbutton = angle camera - else if (getButtonState() == OrientCamera_buttons()) - { - XYWnd_OrientCamera(this, x, y, *g_pParentWnd->GetCamWnd()); - } - - else - { - m_window_observer->onMouseMotion(WindowVector_forInteger(x, y), modifiers_for_flags(buttons)); - - m_mousePosition[0] = m_mousePosition[1] = m_mousePosition[2] = 0.0; - XY_ToPoint(x, y , m_mousePosition); - XY_SnapToGrid(m_mousePosition); - - StringOutputStream status(64); - status << "x:: " << FloatFormat(m_mousePosition[0], 6, 1) - << " y:: " << FloatFormat(m_mousePosition[1], 6, 1) - << " z:: " << FloatFormat(m_mousePosition[2], 6, 1); - g_pParentWnd->SetStatusText(g_pParentWnd->m_position_status, status.c_str()); - - if (g_bCrossHairs) - { - XYWnd_Update(*this); - } - - Clipper_Crosshair_OnMouseMoved(x, y); - } -} - -void XYWnd::EntityCreate_MouseDown(int x, int y) -{ - m_entityCreate = true; - m_entityCreate_x = x; - m_entityCreate_y = y; -} - -void XYWnd::EntityCreate_MouseMove(int x, int y) -{ - if(m_entityCreate && (m_entityCreate_x != x || m_entityCreate_y != y)) - { - m_entityCreate = false; - } -} - -void XYWnd::EntityCreate_MouseUp(int x, int y) -{ - if(m_entityCreate) - { - m_entityCreate = false; - OnContextMenu(); - } -} - -inline float screen_normalised(int pos, unsigned int size) -{ - return ((2.0f * pos) / size) - 1.0f; -} - -inline float normalised_to_world(float normalised, float world_origin, float normalised2world_scale) -{ - return world_origin + normalised * normalised2world_scale; -} - - -// TTimo: watch it, this doesn't init one of the 3 coords -void XYWnd::XY_ToPoint (int x, int y, Vector3& point) -{ - float normalised2world_scale_x = m_nWidth / 2 / m_fScale; - float normalised2world_scale_y = m_nHeight / 2 / m_fScale; - if (m_viewType == XY) - { - point[0] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[0], normalised2world_scale_x); - point[1] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[1], normalised2world_scale_y); - } - else if (m_viewType == YZ) - { - point[1] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[1], normalised2world_scale_x); - point[2] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[2], normalised2world_scale_y); - } - else - { - point[0] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[0], normalised2world_scale_x); - point[2] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[2], normalised2world_scale_y); - } -} - -void XYWnd::XY_SnapToGrid(Vector3& point) -{ - if (m_viewType == XY) - { - point[0] = float_snapped(point[0], GetSnapGridSize()); - point[1] = float_snapped(point[1], GetSnapGridSize()); - } - else if (m_viewType == YZ) - { - point[1] = float_snapped(point[1], GetSnapGridSize()); - point[2] = float_snapped(point[2], GetSnapGridSize()); - } - else - { - point[0] = float_snapped(point[0], GetSnapGridSize()); - point[2] = float_snapped(point[2], GetSnapGridSize()); - } -} - -void XYWnd::XY_LoadBackgroundImage(const char *name) -{ - const char* relative = path_make_relative(name, GlobalFileSystem().findRoot(name)); - if (relative == name) - globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n"; - - char fileNameWithoutExt[512]; - strncpy(fileNameWithoutExt, relative, sizeof(fileNameWithoutExt) - 1); - fileNameWithoutExt[512 - 1] = '\0'; - fileNameWithoutExt[strlen(fileNameWithoutExt) - 4] = '\0'; - - Image *image = QERApp_LoadImage(0, fileNameWithoutExt); - if (!image) { - globalOutputStream() << "Could not load texture " << fileNameWithoutExt << "\n"; - return; - } - g_pParentWnd->ActiveXY()->m_tex = (qtexture_t*)malloc(sizeof(qtexture_t)); - LoadTextureRGBA(g_pParentWnd->ActiveXY()->XYWnd::m_tex, image->getRGBAPixels(), image->getWidth(), image->getHeight()); - globalOutputStream() << "Loaded background texture " << relative << "\n"; - g_pParentWnd->ActiveXY()->m_backgroundActivated = true; - - int m_ix, m_iy; - switch(g_pParentWnd->ActiveXY()->m_viewType) - { - case XY: - m_ix = 0; - m_iy = 1; - break; - case XZ: - m_ix = 0; - m_iy = 2; - break; - case YZ: - m_ix = 1; - m_iy = 2; - break; - } - - Vector3 min, max; - Select_GetBounds(min, max); - g_pParentWnd->ActiveXY()->m_xmin = min[m_ix]; - g_pParentWnd->ActiveXY()->m_ymin = min[m_iy]; - g_pParentWnd->ActiveXY()->m_xmax = max[m_ix]; - g_pParentWnd->ActiveXY()->m_ymax = max[m_iy]; -} - -void XYWnd::XY_DisableBackground (void) -{ - g_pParentWnd->ActiveXY()->m_backgroundActivated = false; - if (g_pParentWnd->ActiveXY()->m_tex) - free(g_pParentWnd->ActiveXY()->m_tex); - g_pParentWnd->ActiveXY()->m_tex = NULL; -} - -void WXY_BackgroundSelect(void) -{ - bool brushesSelected = Scene_countSelectedBrushes(GlobalSceneGraph()) != 0; - if (!brushesSelected) { - gtk_MessageBox(0, "You have to select some brushes to get the bounding box for.\n", - "No selection", eMB_OK, eMB_ICONERROR); - return; - } - - const char *filename = file_dialog(GTK_WIDGET(MainFrame_getWindow()), TRUE, "Background Image", NULL, NULL); - g_pParentWnd->ActiveXY()->XY_DisableBackground(); - if (filename) - g_pParentWnd->ActiveXY()->XY_LoadBackgroundImage(filename); -} - -/* -============================================================================ - -DRAWING - -============================================================================ -*/ - -/* -============== -XY_DrawGrid -============== -*/ - -double two_to_the_power(int power) -{ - return pow(2.0f, power); -} - -void XYWnd::XY_DrawAxis(void) -{ - if ( g_xywindow_globals_private.show_axis) { - const char g_AxisName[3] = { 'X', 'Y', 'Z' }; - const int nDim1 = (m_viewType == YZ) ? 1 : 0; - const int nDim2 = (m_viewType == XY) ? 1 : 2; - const int w = (m_nWidth / 2 / m_fScale); - const int h = (m_nHeight / 2 / m_fScale); - - const Vector3& colourX = (m_viewType == YZ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorX; - const Vector3& colourY = (m_viewType == XY) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorZ; - - // draw two lines with corresponding axis colors to highlight current view - // horizontal line: nDim1 color - glLineWidth(2); - glBegin( GL_LINES ); - glColor3fv (vector3_to_array(colourX)); - glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale ); - glVertex2f( m_vOrigin[nDim1] - w + 65 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale ); - glVertex2f( 0, 0 ); - glVertex2f( 32 / m_fScale, 0 ); - glColor3fv (vector3_to_array(colourY)); - glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale ); - glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale ); - glVertex2f( 0, 0 ); - glVertex2f( 0, 32 / m_fScale ); - glEnd(); - glLineWidth(1); - // now print axis symbols - glColor3fv (vector3_to_array(colourX)); - glRasterPos2f ( m_vOrigin[nDim1] - w + 55 / m_fScale, m_vOrigin[nDim2] + h - 55 / m_fScale ); - GlobalOpenGL().drawChar(g_AxisName[nDim1]); - glRasterPos2f (28 / m_fScale, -10 / m_fScale ); - GlobalOpenGL().drawChar(g_AxisName[nDim1]); - glColor3fv (vector3_to_array(colourY)); - glRasterPos2f ( m_vOrigin[nDim1] - w + 25 / m_fScale, m_vOrigin[nDim2] + h - 30 / m_fScale ); - GlobalOpenGL().drawChar(g_AxisName[nDim2]); - glRasterPos2f ( -10 / m_fScale, 28 / m_fScale ); - GlobalOpenGL().drawChar(g_AxisName[nDim2]); - } -} - -void XYWnd::XY_DrawBackground(void) -{ - glPushAttrib(GL_ALL_ATTRIB_BITS); - - glEnable(GL_TEXTURE_2D); - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); - - glPolygonMode(GL_FRONT, GL_FILL); - - glBindTexture(GL_TEXTURE_2D, m_tex->texture_number); - glBegin(GL_QUADS); - - glColor4f(1.0, 1.0, 1.0, m_alpha); - glTexCoord2f(0.0, 1.0); - glVertex2f(m_xmin, m_ymin); - - glTexCoord2f(1.0, 1.0); - glVertex2f(m_xmax, m_ymin); - - glTexCoord2f(1.0, 0.0); - glVertex2f(m_xmax, m_ymax); - - glTexCoord2f(0.0, 0.0); - glVertex2f(m_xmin, m_ymax); - - glEnd(); - glBindTexture(GL_TEXTURE_2D, 0); - - glPopAttrib(); -} - -void XYWnd::XY_DrawGrid(void) { - float x, y, xb, xe, yb, ye; - float w, h, a; - char text[32]; - float step, minor_step, stepx, stepy; - step = minor_step = stepx = stepy = GetGridSize(); - - int minor_power = Grid_getPower(); - int mask; - - while ((minor_step * m_fScale) <= 4.0f) { // make sure minor grid spacing is at least 4 pixels on the screen - ++minor_power; - minor_step *= 2; - } - int power = minor_power; - while ((power % 3) != 0 || (step * m_fScale) <= 32.0f) { // make sure major grid spacing is at least 32 pixels on the screen - ++power; - step = float(two_to_the_power(power)); - } - mask = (1 << (power - minor_power)) - 1; - while ((stepx * m_fScale) <= 32.0f) // text step x must be at least 32 - stepx *= 2; - while ((stepy * m_fScale) <= 32.0f) // text step y must be at least 32 - stepy *= 2; - - a = ((GetSnapGridSize() > 0.0f) ? 1.0f : 0.3f); - - glDisable(GL_TEXTURE_2D); - glDisable(GL_TEXTURE_1D); - glDisable(GL_DEPTH_TEST); - glDisable(GL_BLEND); - glLineWidth(1); - - w = (m_nWidth / 2 / m_fScale); - h = (m_nHeight / 2 / m_fScale); - - const int nDim1 = (m_viewType == YZ) ? 1 : 0; - const int nDim2 = (m_viewType == XY) ? 1 : 2; - - xb = m_vOrigin[nDim1] - w; - if (xb < region_mins[nDim1]) - xb = region_mins[nDim1]; - xb = step * floor (xb / step); - - xe = m_vOrigin[nDim1] + w; - if (xe > region_maxs[nDim1]) - xe = region_maxs[nDim1]; - xe = step * ceil (xe / step); - - yb = m_vOrigin[nDim2] - h; - if (yb < region_mins[nDim2]) - yb = region_mins[nDim2]; - yb = step * floor (yb / step); - - ye = m_vOrigin[nDim2] + h; - if (ye > region_maxs[nDim2]) - ye = region_maxs[nDim2]; - ye = step * ceil (ye / step); - -#define COLORS_DIFFER(a,b) \ - ((a)[0] != (b)[0] || \ - (a)[1] != (b)[1] || \ - (a)[2] != (b)[2]) - - // djbob - // draw minor blocks - if (g_xywindow_globals_private.d_showgrid || a < 1.0f) { - if(a < 1.0f) - glEnable(GL_BLEND); - - if (COLORS_DIFFER(g_xywindow_globals.color_gridminor, g_xywindow_globals.color_gridback)) { - glColor4fv(vector4_to_array(Vector4(g_xywindow_globals.color_gridminor, a))); - - glBegin (GL_LINES); - int i = 0; - for (x = xb ; x < xe ; x += minor_step, ++i) { - if ((i & mask) != 0) { - glVertex2f (x, yb); - glVertex2f (x, ye); - } - } - i = 0; - for (y = yb ; y < ye ; y += minor_step, ++i) { - if ((i & mask) != 0) { - glVertex2f (xb, y); - glVertex2f (xe, y); - } - } - glEnd(); - } - - // draw major blocks - if (COLORS_DIFFER(g_xywindow_globals.color_gridmajor, g_xywindow_globals.color_gridminor)) { - glColor4fv(vector4_to_array(Vector4(g_xywindow_globals.color_gridmajor, a))); - - glBegin (GL_LINES); - for (x = xb ; x <= xe ; x += step) { - glVertex2f (x, yb); - glVertex2f (x, ye); - } - for (y = yb ; y <= ye ; y += step) { - glVertex2f (xb, y); - glVertex2f (xe, y); - } - glEnd(); - } - - if(a < 1.0f) - glDisable(GL_BLEND); - } - - // draw coordinate text if needed - if ( g_xywindow_globals_private.show_coordinates) { - glColor4fv(vector4_to_array(Vector4(g_xywindow_globals.color_gridtext, 1.0f))); - float offx = m_vOrigin[nDim2] + h - (4 + GlobalOpenGL().m_font->getPixelAscent()) / m_fScale; - float offy = m_vOrigin[nDim1] - w + 4 / m_fScale; - for (x = xb - fmod(xb, stepx); x <= xe ; x += stepx) { - glRasterPos2f (x, offx); - sprintf (text, "%g", x); - GlobalOpenGL().drawString(text); - } - for (y = yb - fmod(yb, stepy); y <= ye ; y += stepy) { - glRasterPos2f (offy, y); - sprintf (text, "%g", y); - GlobalOpenGL().drawString(text); - } - - if (Active()) - glColor3fv(vector3_to_array(g_xywindow_globals.color_viewname)); - - // we do this part (the old way) only if show_axis is disabled - if (!g_xywindow_globals_private.show_axis) { - glRasterPos2f ( m_vOrigin[nDim1] - w + 35 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale ); - - GlobalOpenGL().drawString(ViewType_getTitle(m_viewType)); - } - } - - XYWnd::XY_DrawAxis(); - - // show current work zone? - // the work zone is used to place dropped points and brushes - if (g_xywindow_globals_private.d_show_work) { - glColor4f( 1.0f, 0.0f, 0.0f, 1.0f ); - glBegin( GL_LINES ); - glVertex2f( xb, Select_getWorkZone().d_work_min[nDim2] ); - glVertex2f( xe, Select_getWorkZone().d_work_min[nDim2] ); - glVertex2f( xb, Select_getWorkZone().d_work_max[nDim2] ); - glVertex2f( xe, Select_getWorkZone().d_work_max[nDim2] ); - glVertex2f( Select_getWorkZone().d_work_min[nDim1], yb ); - glVertex2f( Select_getWorkZone().d_work_min[nDim1], ye ); - glVertex2f( Select_getWorkZone().d_work_max[nDim1], yb ); - glVertex2f( Select_getWorkZone().d_work_max[nDim1], ye ); - glEnd(); - } -} - -/* -============== -XY_DrawBlockGrid -============== -*/ -void XYWnd::XY_DrawBlockGrid() -{ - if(Map_FindWorldspawn(g_map) == 0) - { - return; - } - const char *value = Node_getEntity(*Map_GetWorldspawn(g_map))->getKeyValue("_blocksize" ); - if (strlen(value)) - sscanf( value, "%i", &g_xywindow_globals_private.blockSize ); - - if (!g_xywindow_globals_private.blockSize || g_xywindow_globals_private.blockSize > 65536 || g_xywindow_globals_private.blockSize < 1024) - // don't use custom blocksize if it is less than the default, or greater than the maximum world coordinate - g_xywindow_globals_private.blockSize = 1024; - - float x, y, xb, xe, yb, ye; - float w, h; - char text[32]; - - glDisable(GL_TEXTURE_2D); - glDisable(GL_TEXTURE_1D); - glDisable(GL_DEPTH_TEST); - glDisable(GL_BLEND); - - w = (m_nWidth / 2 / m_fScale); - h = (m_nHeight / 2 / m_fScale); - - int nDim1 = (m_viewType == YZ) ? 1 : 0; - int nDim2 = (m_viewType == XY) ? 1 : 2; - - xb = m_vOrigin[nDim1] - w; - if (xb < region_mins[nDim1]) - xb = region_mins[nDim1]; - xb = static_cast(g_xywindow_globals_private.blockSize * floor (xb/g_xywindow_globals_private.blockSize)); - - xe = m_vOrigin[nDim1] + w; - if (xe > region_maxs[nDim1]) - xe = region_maxs[nDim1]; - xe = static_cast(g_xywindow_globals_private.blockSize * ceil (xe/g_xywindow_globals_private.blockSize)); - - yb = m_vOrigin[nDim2] - h; - if (yb < region_mins[nDim2]) - yb = region_mins[nDim2]; - yb = static_cast(g_xywindow_globals_private.blockSize * floor (yb/g_xywindow_globals_private.blockSize)); - - ye = m_vOrigin[nDim2] + h; - if (ye > region_maxs[nDim2]) - ye = region_maxs[nDim2]; - ye = static_cast(g_xywindow_globals_private.blockSize * ceil (ye/g_xywindow_globals_private.blockSize)); - - // draw major blocks - - glColor3fv(vector3_to_array(g_xywindow_globals.color_gridblock)); - glLineWidth (2); - - glBegin (GL_LINES); - - for (x=xb ; x<=xe ; x+=g_xywindow_globals_private.blockSize) - { - glVertex2f (x, yb); - glVertex2f (x, ye); - } - - if (m_viewType == XY) - { - for (y=yb ; y<=ye ; y+=g_xywindow_globals_private.blockSize) - { - glVertex2f (xb, y); - glVertex2f (xe, y); - } - } - - glEnd(); - glLineWidth (1); - - // draw coordinate text if needed - - if (m_viewType == XY && m_fScale > .1) - { - for (x=xb ; x(fov*cos(a+c_pi/4)), y + static_cast(fov*sin(a+c_pi/4)), 0); - glVertex3f (x, y, 0); - glVertex3f (x + static_cast(fov*cos(a-c_pi/4)), y + static_cast(fov*sin(a-c_pi/4)), 0); - glEnd(); - -} - - -float Betwixt(float f1, float f2) -{ - if (f1 > f2) - return f2 + ((f1 - f2) / 2); - else - return f1 + ((f2 - f1) / 2); -} - - -// can be greatly simplified but per usual i am in a hurry -// which is not an excuse, just a fact -void XYWnd::PaintSizeInfo(int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds) -{ - if(vector3_equal(vMinBounds, vMaxBounds)) - { - return; - } - const char* g_pDimStrings[] = {"x:", "y:", "z:"}; - typedef const char* OrgStrings[2]; - const OrgStrings g_pOrgStrings[] = { { "x:", "y:", }, { "x:", "z:", }, { "y:", "z:", } }; - - Vector3 vSize(vector3_subtracted(vMaxBounds, vMinBounds)); - - glColor3f(g_xywindow_globals.color_selbrushes[0] * .65f, - g_xywindow_globals.color_selbrushes[1] * .65f, - g_xywindow_globals.color_selbrushes[2] * .65f); - - StringOutputStream dimensions(16); - - if (m_viewType == XY) - { - glBegin (GL_LINES); - - glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale, 0.0f); - glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); - - glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); - glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); - - glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale, 0.0f); - glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); - - - glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, vMinBounds[nDim2], 0.0f); - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2], 0.0f); - - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2], 0.0f); - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2], 0.0f); - - glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, vMaxBounds[nDim2], 0.0f); - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2], 0.0f); - - glEnd(); - - glRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), vMinBounds[nDim2] - 20.0f / m_fScale, 0.0f); - dimensions << g_pDimStrings[nDim1] << vSize[nDim1]; - GlobalOpenGL().drawString(dimensions.c_str()); - dimensions.clear(); - - glRasterPos3f (vMaxBounds[nDim1] + 16.0f / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]), 0.0f); - dimensions << g_pDimStrings[nDim2] << vSize[nDim2]; - GlobalOpenGL().drawString(dimensions.c_str()); - dimensions.clear(); - - glRasterPos3f (vMinBounds[nDim1] + 4, vMaxBounds[nDim2] + 8 / m_fScale, 0.0f); - dimensions << "(" << g_pOrgStrings[0][0] << vMinBounds[nDim1] << " " << g_pOrgStrings[0][1] << vMaxBounds[nDim2] << ")"; - GlobalOpenGL().drawString(dimensions.c_str()); - } - else if (m_viewType == XZ) - { - glBegin (GL_LINES); - - glVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 6.0f / m_fScale); - glVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 10.0f / m_fScale); - - glVertex3f(vMinBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale); - glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale); - - glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 6.0f / m_fScale); - glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale); - - - glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, 0,vMinBounds[nDim2]); - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMinBounds[nDim2]); - - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMinBounds[nDim2]); - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMaxBounds[nDim2]); - - glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, 0,vMaxBounds[nDim2]); - glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMaxBounds[nDim2]); - - glEnd(); - - glRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), 0, vMinBounds[nDim2] - 20.0f / m_fScale); - dimensions << g_pDimStrings[nDim1] << vSize[nDim1]; - GlobalOpenGL().drawString(dimensions.c_str()); - dimensions.clear(); - - glRasterPos3f (vMaxBounds[nDim1] + 16.0f / m_fScale, 0, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2])); - dimensions << g_pDimStrings[nDim2] << vSize[nDim2]; - GlobalOpenGL().drawString(dimensions.c_str()); - dimensions.clear(); - - glRasterPos3f (vMinBounds[nDim1] + 4, 0, vMaxBounds[nDim2] + 8 / m_fScale); - dimensions << "(" << g_pOrgStrings[1][0] << vMinBounds[nDim1] << " " << g_pOrgStrings[1][1] << vMaxBounds[nDim2] << ")"; - GlobalOpenGL().drawString(dimensions.c_str()); - } - else - { - glBegin (GL_LINES); - - glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale); - glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); - - glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); - glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); - - glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale); - glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); - - - glVertex3f(0, vMaxBounds[nDim1] + 6.0f / m_fScale, vMinBounds[nDim2]); - glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2]); - - glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2]); - glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2]); - - glVertex3f(0, vMaxBounds[nDim1] + 6.0f / m_fScale, vMaxBounds[nDim2]); - glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2]); - - glEnd(); - - glRasterPos3f (0, Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), vMinBounds[nDim2] - 20.0f / m_fScale); - dimensions << g_pDimStrings[nDim1] << vSize[nDim1]; - GlobalOpenGL().drawString(dimensions.c_str()); - dimensions.clear(); - - glRasterPos3f (0, vMaxBounds[nDim1] + 16.0f / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2])); - dimensions << g_pDimStrings[nDim2] << vSize[nDim2]; - GlobalOpenGL().drawString(dimensions.c_str()); - dimensions.clear(); - - glRasterPos3f (0, vMinBounds[nDim1] + 4.0f, vMaxBounds[nDim2] + 8 / m_fScale); - dimensions << "(" << g_pOrgStrings[2][0] << vMinBounds[nDim1] << " " << g_pOrgStrings[2][1] << vMaxBounds[nDim2] << ")"; - GlobalOpenGL().drawString(dimensions.c_str()); - } -} - -class XYRenderer: public Renderer -{ - struct state_type - { - state_type() : - m_highlight(0), - m_state(0) - { - } - unsigned int m_highlight; - Shader* m_state; - }; -public: - XYRenderer(RenderStateFlags globalstate, Shader* selected) : - m_globalstate(globalstate), - m_state_selected(selected) - { - ASSERT_NOTNULL(selected); - m_state_stack.push_back(state_type()); - } - - void SetState(Shader* state, EStyle style) - { - ASSERT_NOTNULL(state); - if(style == eWireframeOnly) - m_state_stack.back().m_state = state; - } - const EStyle getStyle() const - { - return eWireframeOnly; - } - void PushState() - { - m_state_stack.push_back(m_state_stack.back()); - } - void PopState() - { - ASSERT_MESSAGE(!m_state_stack.empty(), "popping empty stack"); - m_state_stack.pop_back(); - } - void Highlight(EHighlightMode mode, bool bEnable = true) - { - (bEnable) - ? m_state_stack.back().m_highlight |= mode - : m_state_stack.back().m_highlight &= ~mode; - } - void addRenderable(const OpenGLRenderable& renderable, const Matrix4& localToWorld) - { - if(m_state_stack.back().m_highlight & ePrimitive) - { - m_state_selected->addRenderable(renderable, localToWorld); - } - else - { - m_state_stack.back().m_state->addRenderable(renderable, localToWorld); - } - } - - void render(const Matrix4& modelview, const Matrix4& projection) - { - GlobalShaderCache().render(m_globalstate, modelview, projection); - } -private: - std::vector m_state_stack; - RenderStateFlags m_globalstate; - Shader* m_state_selected; -}; - -void XYWnd::updateProjection() -{ - m_projection[0] = 1.0f / static_cast(m_nWidth / 2); - m_projection[5] = 1.0f / static_cast(m_nHeight / 2); - m_projection[10] = 1.0f / (g_MaxWorldCoord * m_fScale); - - m_projection[12] = 0.0f; - m_projection[13] = 0.0f; - m_projection[14] = -1.0f; - - m_projection[1] = - m_projection[2] = - m_projection[3] = - - m_projection[4] = - m_projection[6] = - m_projection[7] = - - m_projection[8] = - m_projection[9] = - m_projection[11] = 0.0f; - - m_projection[15] = 1.0f; - - m_view.Construct(m_projection, m_modelview, m_nWidth, m_nHeight); -} - -// note: modelview matrix must have a uniform scale, otherwise strange things happen when rendering the rotation manipulator. -void XYWnd::updateModelview() -{ - int nDim1 = (m_viewType == YZ) ? 1 : 0; - int nDim2 = (m_viewType == XY) ? 1 : 2; - - // translation - m_modelview[12] = -m_vOrigin[nDim1] * m_fScale; - m_modelview[13] = -m_vOrigin[nDim2] * m_fScale; - m_modelview[14] = g_MaxWorldCoord * m_fScale; - - // axis base - switch(m_viewType) - { - case XY: - m_modelview[0] = m_fScale; - m_modelview[1] = 0; - m_modelview[2] = 0; - - m_modelview[4] = 0; - m_modelview[5] = m_fScale; - m_modelview[6] = 0; - - m_modelview[8] = 0; - m_modelview[9] = 0; - m_modelview[10] = -m_fScale; - break; - case XZ: - m_modelview[0] = m_fScale; - m_modelview[1] = 0; - m_modelview[2] = 0; - - m_modelview[4] = 0; - m_modelview[5] = 0; - m_modelview[6] = m_fScale; - - m_modelview[8] = 0; - m_modelview[9] = m_fScale; - m_modelview[10] = 0; - break; - case YZ: - m_modelview[0] = 0; - m_modelview[1] = 0; - m_modelview[2] = -m_fScale; - - m_modelview[4] = m_fScale; - m_modelview[5] = 0; - m_modelview[6] = 0; - - m_modelview[8] = 0; - m_modelview[9] = m_fScale; - m_modelview[10] = 0; - break; - } - - m_modelview[3] = m_modelview[7] = m_modelview[11] = 0; - m_modelview[15] = 1; - - m_view.Construct(m_projection, m_modelview, m_nWidth, m_nHeight); -} - -/* -============== -XY_Draw -============== -*/ - -//#define DBG_SCENEDUMP - -void XYWnd::XY_Draw() -{ - // - // clear - // - glViewport(0, 0, m_nWidth, m_nHeight); - glClearColor (g_xywindow_globals.color_gridback[0], - g_xywindow_globals.color_gridback[1], - g_xywindow_globals.color_gridback[2],0); - - glClear(GL_COLOR_BUFFER_BIT); - - // - // set up viewpoint - // - - glMatrixMode(GL_PROJECTION); - glLoadMatrixf(reinterpret_cast(&m_projection)); - - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); - glScalef(m_fScale, m_fScale, 1); - int nDim1 = (m_viewType == YZ) ? 1 : 0; - int nDim2 = (m_viewType == XY) ? 1 : 2; - glTranslatef(-m_vOrigin[nDim1], -m_vOrigin[nDim2], 0); - - glDisable (GL_LINE_STIPPLE); - glLineWidth(1); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - glDisable(GL_TEXTURE_2D); - glDisable(GL_LIGHTING); - glDisable(GL_COLOR_MATERIAL); - glDisable(GL_DEPTH_TEST); - - if (m_backgroundActivated) - XY_DrawBackground(); - XY_DrawGrid(); - - if ( g_xywindow_globals_private.show_blocks) - XY_DrawBlockGrid(); - - glLoadMatrixf(reinterpret_cast(&m_modelview)); - - unsigned int globalstate = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH; - if(!g_xywindow_globals.m_bNoStipple) - { - globalstate |= RENDER_LINESTIPPLE; - } - - { - XYRenderer renderer(globalstate, m_state_selected); - - Scene_Render(renderer, m_view); - - GlobalOpenGL_debugAssertNoErrors(); - renderer.render(m_modelview, m_projection); - GlobalOpenGL_debugAssertNoErrors(); - } - - glDepthMask(GL_FALSE); - - GlobalOpenGL_debugAssertNoErrors(); - - glLoadMatrixf(reinterpret_cast(&m_modelview)); - - GlobalOpenGL_debugAssertNoErrors(); - glDisable(GL_LINE_STIPPLE); - GlobalOpenGL_debugAssertNoErrors(); - glLineWidth(1); - GlobalOpenGL_debugAssertNoErrors(); - if(GlobalOpenGL().GL_1_3()) - { - glActiveTexture(GL_TEXTURE0); - glClientActiveTexture(GL_TEXTURE0); - } - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - GlobalOpenGL_debugAssertNoErrors(); - glDisableClientState(GL_NORMAL_ARRAY); - GlobalOpenGL_debugAssertNoErrors(); - glDisableClientState(GL_COLOR_ARRAY); - GlobalOpenGL_debugAssertNoErrors(); - glDisable(GL_TEXTURE_2D); - GlobalOpenGL_debugAssertNoErrors(); - glDisable(GL_LIGHTING); - GlobalOpenGL_debugAssertNoErrors(); - glDisable(GL_COLOR_MATERIAL); - GlobalOpenGL_debugAssertNoErrors(); - - GlobalOpenGL_debugAssertNoErrors(); - - - // size info - if(g_xywindow_globals_private.m_bSizePaint && GlobalSelectionSystem().countSelected() != 0) - { - Vector3 min, max; - Select_GetBounds(min, max); - PaintSizeInfo(nDim1, nDim2, min, max); - } - - if (g_bCrossHairs) - { - glColor4f(0.2f, 0.9f, 0.2f, 0.8f); - glBegin (GL_LINES); - if (m_viewType == XY) - { - glVertex2f(2.0f * g_MinWorldCoord, m_mousePosition[1]); - glVertex2f(2.0f * g_MaxWorldCoord, m_mousePosition[1]); - glVertex2f(m_mousePosition[0], 2.0f * g_MinWorldCoord); - glVertex2f(m_mousePosition[0], 2.0f * g_MaxWorldCoord); - } - else if (m_viewType == YZ) - { - glVertex3f(m_mousePosition[0], 2.0f * g_MinWorldCoord, m_mousePosition[2]); - glVertex3f(m_mousePosition[0], 2.0f * g_MaxWorldCoord, m_mousePosition[2]); - glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord); - glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord); - } - else - { - glVertex3f (2.0f * g_MinWorldCoord, m_mousePosition[1], m_mousePosition[2]); - glVertex3f (2.0f * g_MaxWorldCoord, m_mousePosition[1], m_mousePosition[2]); - glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord); - glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord); - } - glEnd(); - } - - if (ClipMode()) - { - GlobalClipPoints_Draw(m_fScale); - } - - GlobalOpenGL_debugAssertNoErrors(); - - // reset modelview - glLoadIdentity(); - glScalef(m_fScale, m_fScale, 1); - glTranslatef(-m_vOrigin[nDim1], -m_vOrigin[nDim2], 0); - - DrawCameraIcon (Camera_getOrigin(*g_pParentWnd->GetCamWnd()), Camera_getAngles(*g_pParentWnd->GetCamWnd())); - - Feedback_draw2D( m_viewType ); - - if (g_xywindow_globals_private.show_outline) - { - if (Active()) - { - glMatrixMode (GL_PROJECTION); - glLoadIdentity(); - glOrtho (0, m_nWidth, 0, m_nHeight, 0, 1); - - glMatrixMode (GL_MODELVIEW); - glLoadIdentity(); - - // four view mode doesn't colorize - if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit) - glColor3fv(vector3_to_array(g_xywindow_globals.color_viewname)); - else - { - switch(m_viewType) - { - case YZ: - glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorX)); - break; - case XZ: - glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorY)); - break; - case XY: - glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorZ)); - break; - } - } - glBegin (GL_LINE_LOOP); - glVertex2f (0.5, 0.5); - glVertex2f (m_nWidth-0.5, 1); - glVertex2f (m_nWidth-0.5, m_nHeight-0.5); - glVertex2f (0.5, m_nHeight-0.5); - glEnd(); - } - } - - GlobalOpenGL_debugAssertNoErrors(); - - glFinish(); -} - -void XYWnd_MouseToPoint(XYWnd* xywnd, int x, int y, Vector3& point) -{ - xywnd->XY_ToPoint(x, y, point); - xywnd->XY_SnapToGrid(point); - - int nDim = (xywnd->GetViewType() == XY) ? 2 : (xywnd->GetViewType() == YZ) ? 0 : 1; - float fWorkMid = float_mid(Select_getWorkZone().d_work_min[nDim], Select_getWorkZone().d_work_max[nDim]); - point[nDim] = float_snapped(fWorkMid, GetGridSize()); -} - -void XYWnd::OnEntityCreate (const char* item) -{ - StringOutputStream command; - command << "entityCreate -class " << item; - UndoableCommand undo(command.c_str()); - Vector3 point; - XYWnd_MouseToPoint(this, m_entityCreate_x, m_entityCreate_y, point); - Entity_createFromSelection(item, point); -} - - - -void GetFocusPosition(Vector3& position) -{ - if(GlobalSelectionSystem().countSelected() != 0) - { - Select_GetMid(position); - } - else - { - position = Camera_getOrigin(*g_pParentWnd->GetCamWnd()); - } -} - -void XYWnd_Focus(XYWnd* xywnd) -{ - Vector3 position; - GetFocusPosition(position); - xywnd->PositionView(position); -} - -void XY_Split_Focus() -{ - Vector3 position; - GetFocusPosition(position); - if(g_pParentWnd->GetXYWnd()) - g_pParentWnd->GetXYWnd()->PositionView(position); - if(g_pParentWnd->GetXZWnd()) - g_pParentWnd->GetXZWnd()->PositionView(position); - if(g_pParentWnd->GetYZWnd()) - g_pParentWnd->GetYZWnd()->PositionView(position); -} - -void XY_Focus() -{ - if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit) - { - // cannot do this in a split window - // do something else that the user may want here - XY_Split_Focus(); - return; - } - - XYWnd* xywnd = g_pParentWnd->GetXYWnd(); - XYWnd_Focus(xywnd); -} - -void XY_Top() -{ - if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) - { - // cannot do this in a split window - // do something else that the user may want here - XY_Split_Focus(); - return; - } - - XYWnd* xywnd = g_pParentWnd->GetXYWnd(); - xywnd->SetViewType(XY); - XYWnd_Focus(xywnd); -} - -void XY_Side() -{ - if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) - { - // cannot do this in a split window - // do something else that the user may want here - XY_Split_Focus(); - return; - } - - XYWnd* xywnd = g_pParentWnd->GetXYWnd(); - xywnd->SetViewType(XZ); - XYWnd_Focus(xywnd); -} - -void XY_Front() -{ - if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) - { - // cannot do this in a split window - // do something else that the user may want here - XY_Split_Focus(); - return; - } - - XYWnd* xywnd = g_pParentWnd->GetXYWnd(); - xywnd->SetViewType(YZ); - XYWnd_Focus(xywnd); -} - -void XY_Next() -{ - if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) - { - // cannot do this in a split window - // do something else that the user may want here - XY_Split_Focus(); - return; - } - - XYWnd* xywnd = g_pParentWnd->GetXYWnd(); - if (xywnd->GetViewType() == XY) - xywnd->SetViewType(XZ); - else if (xywnd->GetViewType() == XZ) - xywnd->SetViewType(YZ); - else - xywnd->SetViewType(XY); - XYWnd_Focus(xywnd); -} - -void XY_Zoom100() -{ - if (g_pParentWnd->GetXYWnd()) - g_pParentWnd->GetXYWnd()->SetScale(1); - if (g_pParentWnd->GetXZWnd()) - g_pParentWnd->GetXZWnd()->SetScale(1); - if (g_pParentWnd->GetYZWnd()) - g_pParentWnd->GetYZWnd()->SetScale(1); -} - -void XY_ZoomIn() -{ - XYWnd_ZoomIn(g_pParentWnd->ActiveXY()); -} - -// NOTE: the zoom out factor is 4/5, we could think about customizing it -// we don't go below a zoom factor corresponding to 10% of the max world size -// (this has to be computed against the window size) -void XY_ZoomOut() -{ - XYWnd_ZoomOut(g_pParentWnd->ActiveXY()); -} - - - -void ToggleShowCrosshair() -{ - g_bCrossHairs ^= 1; - XY_UpdateAllWindows(); -} - -void ToggleShowSizeInfo() -{ - g_xywindow_globals_private.m_bSizePaint = !g_xywindow_globals_private.m_bSizePaint; - XY_UpdateAllWindows(); -} - -void ToggleShowGrid() -{ - g_xywindow_globals_private.d_showgrid = !g_xywindow_globals_private.d_showgrid; - XY_UpdateAllWindows(); -} - -ToggleShown g_xy_top_shown(true); - -void XY_Top_Shown_Construct(GtkWindow* parent) -{ - g_xy_top_shown.connect(GTK_WIDGET(parent)); -} - -ToggleShown g_yz_side_shown(false); - -void YZ_Side_Shown_Construct(GtkWindow* parent) -{ - g_yz_side_shown.connect(GTK_WIDGET(parent)); -} - -ToggleShown g_xz_front_shown(false); - -void XZ_Front_Shown_Construct(GtkWindow* parent) -{ - g_xz_front_shown.connect(GTK_WIDGET(parent)); -} - - -class EntityClassMenu : public ModuleObserver -{ - std::size_t m_unrealised; -public: - EntityClassMenu() : m_unrealised(1) - { - } - void realise() - { - if(--m_unrealised == 0) - { - } - } - void unrealise() - { - if(++m_unrealised == 1) - { - if(XYWnd::m_mnuDrop != 0) - { - gtk_widget_destroy(GTK_WIDGET(XYWnd::m_mnuDrop)); - XYWnd::m_mnuDrop = 0; - } - } - } -}; - -EntityClassMenu g_EntityClassMenu; - - - - -void ShowNamesToggle() -{ - GlobalEntityCreator().setShowNames(!GlobalEntityCreator().getShowNames()); - XY_UpdateAllWindows(); -} -typedef FreeCaller ShowNamesToggleCaller; -void ShowNamesExport(const BoolImportCallback& importer) -{ - importer(GlobalEntityCreator().getShowNames()); -} -typedef FreeCaller1 ShowNamesExportCaller; - -void ShowAnglesToggle() -{ - GlobalEntityCreator().setShowAngles(!GlobalEntityCreator().getShowAngles()); - XY_UpdateAllWindows(); -} -typedef FreeCaller ShowAnglesToggleCaller; -void ShowAnglesExport(const BoolImportCallback& importer) -{ - importer(GlobalEntityCreator().getShowAngles()); -} -typedef FreeCaller1 ShowAnglesExportCaller; - -void ShowBlocksToggle() -{ - g_xywindow_globals_private.show_blocks ^= 1; - XY_UpdateAllWindows(); -} -typedef FreeCaller ShowBlocksToggleCaller; -void ShowBlocksExport(const BoolImportCallback& importer) -{ - importer(g_xywindow_globals_private.show_blocks); -} -typedef FreeCaller1 ShowBlocksExportCaller; - -void ShowCoordinatesToggle() -{ - g_xywindow_globals_private.show_coordinates ^= 1; - XY_UpdateAllWindows(); -} -typedef FreeCaller ShowCoordinatesToggleCaller; -void ShowCoordinatesExport(const BoolImportCallback& importer) -{ - importer(g_xywindow_globals_private.show_coordinates); -} -typedef FreeCaller1 ShowCoordinatesExportCaller; - -void ShowOutlineToggle() -{ - g_xywindow_globals_private.show_outline ^= 1; - XY_UpdateAllWindows(); -} -typedef FreeCaller ShowOutlineToggleCaller; -void ShowOutlineExport(const BoolImportCallback& importer) -{ - importer(g_xywindow_globals_private.show_outline); -} -typedef FreeCaller1 ShowOutlineExportCaller; - -void ShowAxesToggle() -{ - g_xywindow_globals_private.show_axis ^= 1; - XY_UpdateAllWindows(); -} -typedef FreeCaller ShowAxesToggleCaller; -void ShowAxesExport(const BoolImportCallback& importer) -{ - importer(g_xywindow_globals_private.show_axis); -} -typedef FreeCaller1 ShowAxesExportCaller; - -void ShowWorkzoneToggle() -{ - g_xywindow_globals_private.d_show_work ^= 1; - XY_UpdateAllWindows(); -} -typedef FreeCaller ShowWorkzoneToggleCaller; -void ShowWorkzoneExport(const BoolImportCallback& importer) -{ - importer(g_xywindow_globals_private.d_show_work); -} -typedef FreeCaller1 ShowWorkzoneExportCaller; - -ShowNamesExportCaller g_show_names_caller; -BoolExportCallback g_show_names_callback(g_show_names_caller); -ToggleItem g_show_names(g_show_names_callback); - -ShowAnglesExportCaller g_show_angles_caller; -BoolExportCallback g_show_angles_callback(g_show_angles_caller); -ToggleItem g_show_angles(g_show_angles_callback); - -ShowBlocksExportCaller g_show_blocks_caller; -BoolExportCallback g_show_blocks_callback(g_show_blocks_caller); -ToggleItem g_show_blocks(g_show_blocks_callback); - -ShowCoordinatesExportCaller g_show_coordinates_caller; -BoolExportCallback g_show_coordinates_callback(g_show_coordinates_caller); -ToggleItem g_show_coordinates(g_show_coordinates_callback); - -ShowOutlineExportCaller g_show_outline_caller; -BoolExportCallback g_show_outline_callback(g_show_outline_caller); -ToggleItem g_show_outline(g_show_outline_callback); - -ShowAxesExportCaller g_show_axes_caller; -BoolExportCallback g_show_axes_callback(g_show_axes_caller); -ToggleItem g_show_axes(g_show_axes_callback); - -ShowWorkzoneExportCaller g_show_workzone_caller; -BoolExportCallback g_show_workzone_callback(g_show_workzone_caller); -ToggleItem g_show_workzone(g_show_workzone_callback); - -void XYShow_registerCommands() -{ - GlobalToggles_insert("ShowAngles", ShowAnglesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_angles)); - GlobalToggles_insert("ShowNames", ShowNamesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_names)); - GlobalToggles_insert("ShowBlocks", ShowBlocksToggleCaller(), ToggleItem::AddCallbackCaller(g_show_blocks)); - GlobalToggles_insert("ShowCoordinates", ShowCoordinatesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_coordinates)); - GlobalToggles_insert("ShowWindowOutline", ShowOutlineToggleCaller(), ToggleItem::AddCallbackCaller(g_show_outline)); - GlobalToggles_insert("ShowAxes", ShowAxesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_axes)); - GlobalToggles_insert("ShowWorkzone", ShowWorkzoneToggleCaller(), ToggleItem::AddCallbackCaller(g_show_workzone)); -} - -void XYWnd_registerShortcuts() -{ - command_connect_accelerator("ToggleCrosshairs"); - command_connect_accelerator("ToggleSizePaint"); -} - - - -void Orthographic_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox("", "Solid selection boxes", g_xywindow_globals.m_bNoStipple); - page.appendCheckBox("", "Display size info", g_xywindow_globals_private.m_bSizePaint); - page.appendCheckBox("", "Chase mouse during drags", g_xywindow_globals_private.m_bChaseMouse); - page.appendCheckBox("", "Update views on camera move", g_xywindow_globals_private.m_bCamXYUpdate); -} -void Orthographic_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Orthographic", "Orthographic View Preferences")); - Orthographic_constructPreferences(page); -} -void Orthographic_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - -void Clipper_constructPreferences(PreferencesPage& page) -{ - page.appendCheckBox("", "Clipper tool uses caulk", g_clip_useCaulk); -} -void Clipper_constructPage(PreferenceGroup& group) -{ - PreferencesPage page(group.createPage("Clipper", "Clipper Tool Settings")); - Clipper_constructPreferences(page); -} -void Clipper_registerPreferencesPage() -{ - PreferencesDialog_addSettingsPage(FreeCaller1()); -} - - -#include "preferencesystem.h" -#include "stringio.h" - - - - -void ToggleShown_importBool(ToggleShown& self, bool value) -{ - self.set(value); -} -typedef ReferenceCaller1 ToggleShownImportBoolCaller; -void ToggleShown_exportBool(const ToggleShown& self, const BoolImportCallback& importer) -{ - importer(self.active()); -} -typedef ConstReferenceCaller1 ToggleShownExportBoolCaller; - - -void XYWindow_Construct() -{ - GlobalCommands_insert("ToggleCrosshairs", FreeCaller(), Accelerator('X', (GdkModifierType)GDK_SHIFT_MASK)); - GlobalCommands_insert("ToggleSizePaint", FreeCaller(), Accelerator('J')); - GlobalCommands_insert("ToggleGrid", FreeCaller(), Accelerator('0')); - - GlobalToggles_insert("ToggleView", ToggleShown::ToggleCaller(g_xy_top_shown), ToggleItem::AddCallbackCaller(g_xy_top_shown.m_item), Accelerator('V', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - GlobalToggles_insert("ToggleSideView", ToggleShown::ToggleCaller(g_yz_side_shown), ToggleItem::AddCallbackCaller(g_yz_side_shown.m_item)); - GlobalToggles_insert("ToggleFrontView", ToggleShown::ToggleCaller(g_xz_front_shown), ToggleItem::AddCallbackCaller(g_xz_front_shown.m_item)); - GlobalCommands_insert("NextView", FreeCaller(), Accelerator(GDK_Tab, (GdkModifierType)GDK_CONTROL_MASK)); - GlobalCommands_insert("ZoomIn", FreeCaller(), Accelerator(GDK_Delete)); - GlobalCommands_insert("ZoomOut", FreeCaller(), Accelerator(GDK_Insert)); - GlobalCommands_insert("ViewTop", FreeCaller(), Accelerator(GDK_KP_Home)); - GlobalCommands_insert("ViewSide", FreeCaller(), Accelerator(GDK_KP_Page_Down)); - GlobalCommands_insert("ViewFront", FreeCaller(), Accelerator(GDK_KP_End)); - GlobalCommands_insert("Zoom100", FreeCaller()); - GlobalCommands_insert("CenterXYView", FreeCaller(), Accelerator(GDK_Tab, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); - - GlobalPreferenceSystem().registerPreference("ClipCaulk", BoolImportStringCaller(g_clip_useCaulk), BoolExportStringCaller(g_clip_useCaulk)); - - GlobalPreferenceSystem().registerPreference("NewRightClick", BoolImportStringCaller(g_xywindow_globals.m_bRightClick), BoolExportStringCaller(g_xywindow_globals.m_bRightClick)); - GlobalPreferenceSystem().registerPreference("ChaseMouse", BoolImportStringCaller(g_xywindow_globals_private.m_bChaseMouse), BoolExportStringCaller(g_xywindow_globals_private.m_bChaseMouse)); - GlobalPreferenceSystem().registerPreference("SizePainting", BoolImportStringCaller(g_xywindow_globals_private.m_bSizePaint), BoolExportStringCaller(g_xywindow_globals_private.m_bSizePaint)); - GlobalPreferenceSystem().registerPreference("NoStipple", BoolImportStringCaller(g_xywindow_globals.m_bNoStipple), BoolExportStringCaller(g_xywindow_globals.m_bNoStipple)); - GlobalPreferenceSystem().registerPreference("SI_ShowCoords", BoolImportStringCaller(g_xywindow_globals_private.show_coordinates), BoolExportStringCaller(g_xywindow_globals_private.show_coordinates)); - GlobalPreferenceSystem().registerPreference("SI_ShowOutlines", BoolImportStringCaller(g_xywindow_globals_private.show_outline), BoolExportStringCaller(g_xywindow_globals_private.show_outline)); - GlobalPreferenceSystem().registerPreference("SI_ShowAxis", BoolImportStringCaller(g_xywindow_globals_private.show_axis), BoolExportStringCaller(g_xywindow_globals_private.show_axis)); - GlobalPreferenceSystem().registerPreference("CamXYUpdate", BoolImportStringCaller(g_xywindow_globals_private.m_bCamXYUpdate), BoolExportStringCaller(g_xywindow_globals_private.m_bCamXYUpdate)); - GlobalPreferenceSystem().registerPreference("ShowWorkzone", BoolImportStringCaller(g_xywindow_globals_private.d_show_work), BoolExportStringCaller(g_xywindow_globals_private.d_show_work)); - - GlobalPreferenceSystem().registerPreference("SI_AxisColors0", Vector3ImportStringCaller(g_xywindow_globals.AxisColorX), Vector3ExportStringCaller(g_xywindow_globals.AxisColorX)); - GlobalPreferenceSystem().registerPreference("SI_AxisColors1", Vector3ImportStringCaller(g_xywindow_globals.AxisColorY), Vector3ExportStringCaller(g_xywindow_globals.AxisColorY)); - GlobalPreferenceSystem().registerPreference("SI_AxisColors2", Vector3ImportStringCaller(g_xywindow_globals.AxisColorZ), Vector3ExportStringCaller(g_xywindow_globals.AxisColorZ)); - GlobalPreferenceSystem().registerPreference("SI_Colors1", Vector3ImportStringCaller(g_xywindow_globals.color_gridback), Vector3ExportStringCaller(g_xywindow_globals.color_gridback)); - GlobalPreferenceSystem().registerPreference("SI_Colors2", Vector3ImportStringCaller(g_xywindow_globals.color_gridminor), Vector3ExportStringCaller(g_xywindow_globals.color_gridminor)); - GlobalPreferenceSystem().registerPreference("SI_Colors3", Vector3ImportStringCaller(g_xywindow_globals.color_gridmajor), Vector3ExportStringCaller(g_xywindow_globals.color_gridmajor)); - GlobalPreferenceSystem().registerPreference("SI_Colors6", Vector3ImportStringCaller(g_xywindow_globals.color_gridblock), Vector3ExportStringCaller(g_xywindow_globals.color_gridblock)); - GlobalPreferenceSystem().registerPreference("SI_Colors7", Vector3ImportStringCaller(g_xywindow_globals.color_gridtext), Vector3ExportStringCaller(g_xywindow_globals.color_gridtext)); - GlobalPreferenceSystem().registerPreference("SI_Colors8", Vector3ImportStringCaller(g_xywindow_globals.color_brushes), Vector3ExportStringCaller(g_xywindow_globals.color_brushes)); - GlobalPreferenceSystem().registerPreference("SI_Colors14", Vector3ImportStringCaller(g_xywindow_globals.color_gridmajor_alt), Vector3ExportStringCaller(g_xywindow_globals.color_gridmajor_alt)); - - - GlobalPreferenceSystem().registerPreference("XZVIS", makeBoolStringImportCallback(ToggleShownImportBoolCaller(g_xz_front_shown)), makeBoolStringExportCallback(ToggleShownExportBoolCaller(g_xz_front_shown))); - GlobalPreferenceSystem().registerPreference("YZVIS", makeBoolStringImportCallback(ToggleShownImportBoolCaller(g_yz_side_shown)), makeBoolStringExportCallback(ToggleShownExportBoolCaller(g_yz_side_shown))); - - Orthographic_registerPreferencesPage(); - Clipper_registerPreferencesPage(); - - XYWnd::captureStates(); - GlobalEntityClassManager().attach(g_EntityClassMenu); -} - -void XYWindow_Destroy() -{ - GlobalEntityClassManager().detach(g_EntityClassMenu); - XYWnd::releaseStates(); -} diff --git a/misc/mediasource/extra/netradiant-src/radiant/xywindow.h b/misc/mediasource/extra/netradiant-src/radiant/xywindow.h deleted file mode 100644 index fd795c45..00000000 --- a/misc/mediasource/extra/netradiant-src/radiant/xywindow.h +++ /dev/null @@ -1,315 +0,0 @@ -/* -Copyright (C) 1999-2006 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(INCLUDED_XYWINDOW_H) -#define INCLUDED_XYWINDOW_H - -#include "math/matrix.h" -#include "signal/signal.h" - -#include "gtkutil/cursor.h" -#include "gtkutil/window.h" -#include "gtkutil/xorrectangle.h" -#include "view.h" -#include "map.h" -#include "texturelib.h" - -#include "qerplugin.h" - -class Shader; -class SelectionSystemWindowObserver; -namespace scene -{ - class Node; -} -typedef struct _GtkWindow GtkWindow; -typedef struct _GtkMenu GtkMenu; - - -void FlipClip(); -void SplitClip(); -void Clip(); -void OnClipMode(bool enabled); -bool ClipMode(); - -inline const char* ViewType_getTitle(VIEWTYPE viewtype) -{ - if(viewtype == XY) - { - return "XY Top"; - } - if(viewtype == XZ) - { - return "XZ Front"; - } - if(viewtype == YZ) - { - return "YZ Side"; - } - return ""; -} - -class XYWnd -{ - GtkWidget* m_gl_widget; - guint m_sizeHandler; - guint m_exposeHandler; - - DeferredDraw m_deferredDraw; - DeferredMotion m_deferred_motion; -public: - GtkWindow* m_parent; - XYWnd(); - ~XYWnd(); - - void queueDraw() - { - m_deferredDraw.draw(); - } - GtkWidget* GetWidget() - { - return m_gl_widget; - } - -public: - SelectionSystemWindowObserver* m_window_observer; - XORRectangle m_XORRectangle; - WindowPositionTracker m_positionTracker; - - static void captureStates(); - static void releaseStates(); - - void PositionView(const Vector3& position); - const Vector3& GetOrigin(); - void SetOrigin(const Vector3& origin); - void Scroll(int x, int y); - - void XY_Draw(); - void DrawCameraIcon(const Vector3& origin, const Vector3& angles); - void XY_DrawBlockGrid(); - void XY_DrawAxis(); - void XY_DrawGrid(); - void XY_DrawBackground(); - void XY_LoadBackgroundImage(const char *name); - void XY_DisableBackground(); - - void XY_MouseUp(int x, int y, unsigned int buttons); - void XY_MouseDown(int x, int y, unsigned int buttons); - void XY_MouseMoved(int x, int y, unsigned int buttons); - - void NewBrushDrag_Begin(int x, int y); - void NewBrushDrag(int x, int y); - void NewBrushDrag_End(int x, int y); - - void XY_ToPoint(int x, int y, Vector3& point); - void XY_SnapToGrid(Vector3& point); - - void Move_Begin(); - void Move_End(); - bool m_move_started; - guint m_move_focusOut; - - void Zoom_Begin(); - void Zoom_End(); - bool m_zoom_started; - guint m_zoom_focusOut; - - void SetActive(bool b) - { - m_bActive = b; - }; - bool Active() - { - return m_bActive; - }; - - void Clipper_OnLButtonDown(int x, int y); - void Clipper_OnLButtonUp(int x, int y); - void Clipper_OnMouseMoved(int x, int y); - void Clipper_Crosshair_OnMouseMoved(int x, int y); - void DropClipPoint(int pointx, int pointy); - - void SetViewType(VIEWTYPE n); - bool m_bActive; - - static GtkMenu* m_mnuDrop; - - int m_chasemouse_current_x, m_chasemouse_current_y; - int m_chasemouse_delta_x, m_chasemouse_delta_y; - - - guint m_chasemouse_handler; - void ChaseMouse(); - bool chaseMouseMotion(int pointx, int pointy); - - void updateModelview(); - void updateProjection(); - Matrix4 m_projection; - Matrix4 m_modelview; - - int m_nWidth; - int m_nHeight; - // background image stuff - qtexture_t *m_tex; - bool m_backgroundActivated; - float m_alpha; // vertex alpha - float m_xmin, m_ymin, m_xmax, m_ymax; -private: - float m_fScale; - Vector3 m_vOrigin; - - - View m_view; - static Shader* m_state_selected; - - int m_ptCursorX, m_ptCursorY; - - unsigned int m_buttonstate; - - int m_nNewBrushPressx; - int m_nNewBrushPressy; - scene::Node* m_NewBrushDrag; - bool m_bNewBrushDrag; - - Vector3 m_mousePosition; - - VIEWTYPE m_viewType; - - void OriginalButtonUp(guint32 nFlags, int point, int pointy); - void OriginalButtonDown(guint32 nFlags, int point, int pointy); - - void OnContextMenu(); - void PaintSizeInfo(int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds); - - int m_entityCreate_x, m_entityCreate_y; - bool m_entityCreate; - -public: - void ButtonState_onMouseDown(unsigned int buttons) - { - m_buttonstate |= buttons; - } - void ButtonState_onMouseUp(unsigned int buttons) - { - m_buttonstate &= ~buttons; - } - unsigned int getButtonState() const - { - return m_buttonstate; - } - void EntityCreate_MouseDown(int x, int y); - void EntityCreate_MouseMove(int x, int y); - void EntityCreate_MouseUp(int x, int y); - - void OnEntityCreate(const char* item); - VIEWTYPE GetViewType() - { - return m_viewType; - } - void SetScale(float f); - float Scale() - { - return m_fScale; - } - int Width() - { - return m_nWidth; - } - int Height() - { - return m_nHeight; - } - - Signal0 onDestroyed; - Signal3 onMouseDown; - void mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers); - typedef Member3 MouseDownCaller; -}; - -inline void XYWnd_Update(XYWnd& xywnd) -{ - xywnd.queueDraw(); -} - - -struct xywindow_globals_t -{ - Vector3 color_gridback; - Vector3 color_gridminor; - Vector3 color_gridmajor; - Vector3 color_gridblock; - Vector3 color_gridtext; - Vector3 color_brushes; - Vector3 color_selbrushes; - Vector3 color_clipper; - Vector3 color_viewname; - Vector3 color_gridminor_alt; - Vector3 color_gridmajor_alt; - Vector3 AxisColorX; - Vector3 AxisColorY; - Vector3 AxisColorZ; - - bool m_bRightClick; - bool m_bNoStipple; - - xywindow_globals_t() : - color_gridback(1.f, 1.f, 1.f), - color_gridminor(0.75f, 0.75f, 0.75f), - color_gridmajor(0.5f, 0.5f, 0.5f), - color_gridblock(0.f, 0.f, 1.f), - color_gridtext(0.f, 0.f, 0.f), - color_brushes(0.f, 0.f, 0.f), - color_selbrushes(1.f, 0.f, 0.f), - color_clipper(0.f, 0.f, 1.f), - color_viewname(0.5f, 0.f, 0.75f), - color_gridminor_alt(0.f, 0.f, 0.f), - color_gridmajor_alt(0.f, 0.f, 0.f), - - AxisColorX(1.f, 0.f, 0.f), - AxisColorY(0.f, 1.f, 0.f), - AxisColorZ(0.f, 0.f, 1.f), - m_bRightClick(true), - m_bNoStipple(false) - { - } - -}; - -extern xywindow_globals_t g_xywindow_globals; - - -VIEWTYPE GlobalXYWnd_getCurrentViewType(); - -typedef struct _GtkWindow GtkWindow; -void XY_Top_Shown_Construct(GtkWindow* parent); -void YZ_Side_Shown_Construct(GtkWindow* parent); -void XZ_Front_Shown_Construct(GtkWindow* parent); - -void XYWindow_Construct(); -void XYWindow_Destroy(); - -void WXY_Print(); -void WXY_BackgroundSelect(); - -void XYShow_registerCommands(); -void XYWnd_registerShortcuts(); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/README.txt deleted file mode 100644 index 599ec3d4..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/README.txt +++ /dev/null @@ -1,8 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The provided map, maps/base_winding.map, serves as an example map to test -changes to BaseWindingForPlane(). This map has planes at many different -angles. Use the patch base_winding_logging.patch to log the computed -base windings, in order to compare before and after when making changes to -BaseWindingForPlane(). diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/base_winding_logging.patch b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/base_winding_logging.patch deleted file mode 100644 index 20fbaee3..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/base_winding_logging.patch +++ /dev/null @@ -1,27 +0,0 @@ -Index: tools/quake3/q3map2/brush.c -=================================================================== ---- tools/quake3/q3map2/brush.c (revision 369) -+++ tools/quake3/q3map2/brush.c (working copy) -@@ -357,6 +357,8 @@ - side_t *side; - plane_t *plane; - -+ static int brushord = -1; -+ brushord++; - - /* walk the list of brush sides */ - for( i = 0; i < brush->numsides; i++ ) -@@ -367,6 +369,13 @@ - - /* make huge winding */ - w = BaseWindingForPlane( plane->normal, plane->dist ); -+ Sys_Printf(">>> BaseWindingForPlane() for brush %i, side %i is as follows:\n", brushord, i); -+ for (j = 0; j < w->numpoints; j++) { -+ Sys_Printf(">>> (%.1f %.1f %.1f) [rounded to nearest integer coordinates]\n", -+ Q_rint(w->p[j][0]), -+ Q_rint(w->p[j][1]), -+ Q_rint(w->p[j][2])); -+ } - - /* walk the list of brush sides */ - for( j = 0; j < brush->numsides && w != NULL; j++ ) diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/maps/base_winding.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/maps/base_winding.map deleted file mode 100644 index 237278a2..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/base_winding/maps/base_winding.map +++ /dev/null @@ -1,1284 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 768 256 0 ) ( 768 115 -256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 768 256 0 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 768 115 -256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 512 0 0 ) ( 768 0 0 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 512 0 0 ) ( 428 115 -256 ) ( 443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 128 -443 ) ( 768 0 -443 ) ( 768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 768 128 -443 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 768 0 -443 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 768 115 -256 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 256 0 -443 ) ( 222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 128 -768 ) ( 768 0 -768 ) ( 768 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 768 128 -443 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -768 ) ( 768 128 -768 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -768 ) ( 768 0 -768 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 768 0 -443 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 256 0 -768 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 222 128 -768 ) ( 0 0 -768 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 222 128 -768 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 256 0 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 0 0 -512 ) ( 222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 314 -256 ) ( 768 115 -256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 768 314 -256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 768 115 -256 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 768 256 0 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 428 115 -256 ) ( 314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 314 -256 ) ( 768 128 -443 ) ( 768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 768 314 -256 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 768 128 -443 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 768 115 -256 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 222 128 -443 ) ( 314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 443 0 ) ( 768 314 -256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 768 443 0 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 768 314 -256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 768 256 0 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 314 314 -256 ) ( 256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 222 -443 ) ( 768 128 -443 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 768 222 -443 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 768 128 -443 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 768 314 -256 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 222 128 -443 ) ( 128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 222 -768 ) ( 768 128 -768 ) ( 768 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 768 222 -443 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -768 ) ( 768 222 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -768 ) ( 768 128 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 768 128 -443 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 222 128 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 128 222 -768 ) ( 0 0 -768 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 222 -768 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 222 128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 -443 ) ( 0 0 -512 ) ( 128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 115 768 -256 ) ( 314 768 -256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 115 768 -256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 314 768 -256 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 256 768 0 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 314 314 -256 ) ( 115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 768 -256 ) ( 768 768 0 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 314 768 -256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 314 -256 ) ( 768 768 -256 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 443 0 ) ( 768 768 0 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 256 768 0 ) ( 768 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 768 443 0 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 115 768 -256 ) ( 128 768 -443 ) ( 314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 115 768 -256 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 768 -443 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 314 768 -256 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 128 222 -443 ) ( 115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 768 -443 ) ( 768 768 -256 ) ( 314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 768 -443 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 222 -443 ) ( 768 768 -443 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 314 -256 ) ( 768 768 -256 ) ( 768 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 314 768 -256 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 -256 ) ( 768 314 -256 ) ( 768 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 768 768 -768 ) ( 128 768 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 222 -443 ) ( 768 222 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 768 -443 ) ( 768 768 -768 ) ( 768 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 768 -443 ) ( 128 768 -768 ) ( 768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 222 -768 ) ( 128 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 768 -443 ) ( 768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 768 0 ) ( 115 768 -256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 512 0 ) ( 0 768 0 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 115 768 -256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 256 768 0 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 115 428 -256 ) ( 0 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 0 768 -443 ) ( 128 768 -443 ) ( 115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -443 ) ( 0 768 -443 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 768 -443 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 115 768 -256 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 128 222 -443 ) ( 0 256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 0 768 -768 ) ( 128 768 -768 ) ( 128 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -443 ) ( 0 768 -443 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -768 ) ( 0 768 -768 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -768 ) ( 128 768 -768 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 768 -443 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 222 -768 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 256 -768 ) ( 0 0 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -443 ) ( 0 256 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 128 222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 -443 ) ( 0 0 -512 ) ( 0 256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -115 768 -256 ) ( 115 768 -256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 -256 ) ( -115 768 -256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 115 768 -256 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 512 0 ) ( 0 768 0 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 512 0 ) ( 115 428 -256 ) ( -115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -115 768 -256 ) ( 0 768 -443 ) ( 115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 -256 ) ( -115 768 -256 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -443 ) ( 0 768 -443 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 115 768 -256 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 -256 ) ( 0 256 -443 ) ( -115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 0 -512 0 ) ( 115 -428 -256 ) ( 256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 0 -512 0 ) ( 0 -768 0 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 -256 ) ( 115 -768 -256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 -443 0 ) ( 256 -768 0 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 -768 0 ) ( 115 -768 -256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 115 -428 -256 ) ( 0 -256 -443 ) ( 128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 115 -428 -256 ) ( 115 -768 -256 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -443 ) ( 0 -768 -443 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -443 ) ( 128 -768 -443 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -768 -443 ) ( 0 -768 -443 ) ( 115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 -256 -443 ) ( 0 -256 -768 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -443 ) ( 0 -768 -443 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -768 ) ( 0 -768 -768 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -768 ) ( 128 -768 -768 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -443 ) ( 128 -768 -443 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -768 -768 ) ( 0 -768 -768 ) ( 0 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 -256 -443 ) ( 0 0 -512 ) ( 128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 0 -256 -443 ) ( 0 -256 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -443 ) ( 128 -222 -768 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -768 ) ( 0 0 -768 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 -443 0 ) ( 115 -428 -256 ) ( 314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 256 -443 0 ) ( 256 -768 0 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 -256 ) ( 115 -768 -256 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 -256 ) ( 314 -768 -256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -768 -256 ) ( 115 -768 -256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 115 -428 -256 ) ( 128 -222 -443 ) ( 314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 115 -428 -256 ) ( 115 -768 -256 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -443 ) ( 128 -768 -443 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 -256 ) ( 314 -768 -256 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -768 -256 ) ( 128 -768 -443 ) ( 115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 -443 0 ) ( 314 -314 -256 ) ( 443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 256 -443 0 ) ( 256 -768 0 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 -256 ) ( 314 -768 -256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 -256 0 ) ( 443 -768 0 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 -768 0 ) ( 314 -768 -256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 314 -314 -256 ) ( 128 -222 -443 ) ( 222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 314 -314 -256 ) ( 314 -768 -256 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -443 ) ( 128 -768 -443 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 222 -768 -443 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -768 -443 ) ( 128 -768 -443 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 128 -222 -443 ) ( 128 -222 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -443 ) ( 128 -768 -443 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 -768 ) ( 128 -768 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -768 ) ( 222 -768 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 222 -768 -443 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -768 -768 ) ( 128 -768 -768 ) ( 128 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 128 -222 -443 ) ( 0 0 -512 ) ( 222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 128 -222 -443 ) ( 128 -222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 222 -128 -768 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -768 ) ( 0 0 -768 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 443 -256 0 ) ( 314 -314 -256 ) ( 428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 443 -256 0 ) ( 768 -256 0 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 -256 ) ( 768 -314 -256 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 -256 ) ( 768 -115 -256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -115 -256 ) ( 768 -314 -256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 443 -256 0 ) ( 443 -768 0 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 -256 0 ) ( 768 -256 0 ) ( 443 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 -768 0 ) ( 768 -768 0 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -768 -256 ) ( 768 -768 -256 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 -256 ) ( 768 -314 -256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 -256 ) ( 768 -768 0 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 314 -314 -256 ) ( 222 -128 -443 ) ( 428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 314 -314 -256 ) ( 768 -314 -256 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 768 -128 -443 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 -256 ) ( 768 -115 -256 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -115 -256 ) ( 768 -128 -443 ) ( 768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 314 -314 -256 ) ( 314 -768 -256 ) ( 222 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 -256 ) ( 768 -314 -256 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -768 -256 ) ( 768 -768 -256 ) ( 222 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -768 -443 ) ( 768 -768 -443 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 768 -128 -443 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 -443 ) ( 768 -768 -256 ) ( 768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 222 -128 -443 ) ( 768 -128 -443 ) ( 768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 222 -128 -768 ) ( 768 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -128 -443 ) ( 768 -128 -768 ) ( 768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 -443 ) ( 768 -768 -768 ) ( 222 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -768 -443 ) ( 222 -768 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 -768 ) ( 768 -128 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 443 -256 0 ) ( 428 -115 -256 ) ( 512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 443 -256 0 ) ( 768 -256 0 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 -256 ) ( 768 -115 -256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 512 0 0 ) ( 768 0 0 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 0 0 ) ( 768 -115 -256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 428 -115 -256 ) ( 222 -128 -443 ) ( 256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 428 -115 -256 ) ( 768 -115 -256 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 768 -128 -443 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 768 0 -443 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 0 -443 ) ( 768 -128 -443 ) ( 768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 222 -128 -443 ) ( 222 -128 -768 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -443 ) ( 768 -128 -443 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 -768 ) ( 768 -128 -768 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -768 ) ( 768 0 -768 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 768 0 -443 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 0 -768 ) ( 768 -128 -768 ) ( 768 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 222 -128 -443 ) ( 0 0 -512 ) ( 256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 222 -128 -443 ) ( 222 -128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 256 0 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -768 ) ( 0 0 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 512 0 0 ) ( 428 -115 -256 ) ( 428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 512 0 0 ) ( 768 0 0 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 -256 ) ( 768 -115 -256 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 768 115 -256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 115 -256 ) ( 768 -115 -256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 428 -115 -256 ) ( 256 0 -443 ) ( 428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 428 -115 -256 ) ( 768 -115 -256 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 -443 ) ( 768 0 -443 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 -256 ) ( 768 115 -256 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 115 -256 ) ( 768 0 -443 ) ( 768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -768 -256 0 ) ( -768 -115 -256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -768 -256 0 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -768 -115 -256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -512 0 0 ) ( -768 0 0 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -512 0 0 ) ( -428 -115 -256 ) ( -443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -128 -443 ) ( -768 0 -443 ) ( -768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -768 -128 -443 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -768 0 -443 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -768 -115 -256 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -256 0 -443 ) ( -222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -128 -768 ) ( -768 0 -768 ) ( -768 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -768 -128 -443 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -768 ) ( -768 -128 -768 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -768 ) ( -768 0 -768 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -768 0 -443 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -256 0 -768 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -222 -128 -768 ) ( 0 0 -768 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -222 -128 -768 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -256 0 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( 0 0 -512 ) ( -222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -314 -256 ) ( -768 -115 -256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -768 -314 -256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -768 -115 -256 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -768 -256 0 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -428 -115 -256 ) ( -314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -314 -256 ) ( -768 -128 -443 ) ( -768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -768 -314 -256 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -768 -128 -443 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -768 -115 -256 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -222 -128 -443 ) ( -314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -443 0 ) ( -768 -314 -256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -768 -443 0 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -768 -314 -256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -768 -256 0 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -314 -314 -256 ) ( -256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -222 -443 ) ( -768 -128 -443 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -768 -222 -443 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -768 -128 -443 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -768 -314 -256 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -222 -128 -443 ) ( -128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -222 -768 ) ( -768 -128 -768 ) ( -768 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -768 -222 -443 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -768 ) ( -768 -222 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -768 ) ( -768 -128 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -768 -128 -443 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -222 -128 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -128 -222 -768 ) ( 0 0 -768 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -222 -768 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( -222 -128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 -443 ) ( 0 0 -512 ) ( -128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -115 -768 -256 ) ( -314 -768 -256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( -115 -768 -256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -314 -768 -256 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -256 -768 0 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -314 -314 -256 ) ( -115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -768 -256 ) ( -768 -768 0 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -314 -768 -256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -314 -256 ) ( -768 -768 -256 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -443 0 ) ( -768 -768 0 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -256 -768 0 ) ( -768 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -768 -443 0 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -115 -768 -256 ) ( -128 -768 -443 ) ( -314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( -115 -768 -256 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -768 -443 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -314 -768 -256 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -128 -222 -443 ) ( -115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -768 -443 ) ( -768 -768 -256 ) ( -314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -768 -443 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -222 -443 ) ( -768 -768 -443 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -314 -256 ) ( -768 -768 -256 ) ( -768 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -314 -768 -256 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 -256 ) ( -768 -314 -256 ) ( -768 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -768 -768 -768 ) ( -128 -768 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -222 -443 ) ( -768 -222 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -768 -443 ) ( -768 -768 -768 ) ( -768 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -768 -443 ) ( -128 -768 -768 ) ( -768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -222 -768 ) ( -128 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -768 -443 ) ( -768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 -768 0 ) ( -115 -768 -256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -512 0 ) ( 0 -768 0 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( -115 -768 -256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -256 -768 0 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -115 -428 -256 ) ( 0 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 0 -768 -443 ) ( -128 -768 -443 ) ( -115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -443 ) ( 0 -768 -443 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -768 -443 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( -115 -768 -256 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( -128 -222 -443 ) ( 0 -256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 0 -768 -768 ) ( -128 -768 -768 ) ( -128 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -443 ) ( 0 -768 -443 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -768 ) ( 0 -768 -768 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -768 ) ( -128 -768 -768 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -768 -443 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -222 -768 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 -256 -768 ) ( 0 0 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -443 ) ( 0 -256 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( -128 -222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 -443 ) ( 0 0 -512 ) ( 0 -256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 115 -768 -256 ) ( -115 -768 -256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 -256 ) ( 115 -768 -256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( -115 -768 -256 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -512 0 ) ( 0 -768 0 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -512 0 ) ( -115 -428 -256 ) ( 115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 115 -768 -256 ) ( 0 -768 -443 ) ( -115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 -256 ) ( 115 -768 -256 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 -443 ) ( 0 -768 -443 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( -115 -768 -256 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 -256 ) ( 0 -256 -443 ) ( 115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 0 512 0 ) ( -115 428 -256 ) ( -256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 0 512 0 ) ( 0 768 0 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 -256 ) ( -115 768 -256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 443 0 ) ( -256 768 0 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 768 0 ) ( -115 768 -256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -115 428 -256 ) ( 0 256 -443 ) ( -128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -115 428 -256 ) ( -115 768 -256 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -443 ) ( 0 768 -443 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -443 ) ( -128 768 -443 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 768 -443 ) ( 0 768 -443 ) ( -115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 256 -443 ) ( 0 256 -768 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -443 ) ( 0 768 -443 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 -768 ) ( 0 768 -768 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -768 ) ( -128 768 -768 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -443 ) ( -128 768 -443 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 768 -768 ) ( 0 768 -768 ) ( 0 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 256 -443 ) ( 0 0 -512 ) ( -128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 0 256 -443 ) ( 0 256 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -443 ) ( -128 222 -768 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -768 ) ( 0 0 -768 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 443 0 ) ( -115 428 -256 ) ( -314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -256 443 0 ) ( -256 768 0 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 -256 ) ( -115 768 -256 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 -256 ) ( -314 768 -256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 768 -256 ) ( -115 768 -256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -115 428 -256 ) ( -128 222 -443 ) ( -314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -115 428 -256 ) ( -115 768 -256 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -443 ) ( -128 768 -443 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 -256 ) ( -314 768 -256 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 768 -256 ) ( -128 768 -443 ) ( -115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 443 0 ) ( -314 314 -256 ) ( -443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -256 443 0 ) ( -256 768 0 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 -256 ) ( -314 768 -256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 256 0 ) ( -443 768 0 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 768 0 ) ( -314 768 -256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -314 314 -256 ) ( -128 222 -443 ) ( -222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -314 314 -256 ) ( -314 768 -256 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -443 ) ( -128 768 -443 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -222 768 -443 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 768 -443 ) ( -128 768 -443 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -128 222 -443 ) ( -128 222 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -443 ) ( -128 768 -443 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 -768 ) ( -128 768 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -768 ) ( -222 768 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -222 768 -443 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 768 -768 ) ( -128 768 -768 ) ( -128 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -128 222 -443 ) ( 0 0 -512 ) ( -222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -128 222 -443 ) ( -128 222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -222 128 -768 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -768 ) ( 0 0 -768 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -443 256 0 ) ( -314 314 -256 ) ( -428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -443 256 0 ) ( -768 256 0 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 -256 ) ( -768 314 -256 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 -256 ) ( -768 115 -256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 115 -256 ) ( -768 314 -256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -443 256 0 ) ( -443 768 0 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 256 0 ) ( -768 256 0 ) ( -443 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 768 0 ) ( -768 768 0 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 768 -256 ) ( -768 768 -256 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 -256 ) ( -768 314 -256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 -256 ) ( -768 768 0 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -314 314 -256 ) ( -222 128 -443 ) ( -428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -314 314 -256 ) ( -768 314 -256 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -768 128 -443 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 -256 ) ( -768 115 -256 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 115 -256 ) ( -768 128 -443 ) ( -768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -314 314 -256 ) ( -314 768 -256 ) ( -222 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 -256 ) ( -768 314 -256 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 768 -256 ) ( -768 768 -256 ) ( -222 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 768 -443 ) ( -768 768 -443 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -768 128 -443 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 -443 ) ( -768 768 -256 ) ( -768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -222 128 -443 ) ( -768 128 -443 ) ( -768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -222 128 -768 ) ( -768 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 128 -443 ) ( -768 128 -768 ) ( -768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 -443 ) ( -768 768 -768 ) ( -222 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 768 -443 ) ( -222 768 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 -768 ) ( -768 128 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -443 256 0 ) ( -428 115 -256 ) ( -512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -443 256 0 ) ( -768 256 0 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 -256 ) ( -768 115 -256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -512 0 0 ) ( -768 0 0 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 0 0 ) ( -768 115 -256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -428 115 -256 ) ( -222 128 -443 ) ( -256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -428 115 -256 ) ( -768 115 -256 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -768 128 -443 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -768 0 -443 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 0 -443 ) ( -768 128 -443 ) ( -768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -222 128 -443 ) ( -222 128 -768 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -443 ) ( -768 128 -443 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 -768 ) ( -768 128 -768 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -768 ) ( -768 0 -768 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -768 0 -443 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 0 -768 ) ( -768 128 -768 ) ( -768 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -222 128 -443 ) ( 0 0 -512 ) ( -256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -222 128 -443 ) ( -222 128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 -512 ) ( 0 0 -768 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -256 0 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -768 ) ( 0 0 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -512 0 0 ) ( -428 115 -256 ) ( -428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -512 0 0 ) ( -768 0 0 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 -256 ) ( -768 115 -256 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -768 -115 -256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -115 -256 ) ( -768 115 -256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -428 115 -256 ) ( -256 0 -443 ) ( -428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -428 115 -256 ) ( -768 115 -256 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 -443 ) ( -768 0 -443 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 -256 ) ( -768 -115 -256 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -115 -256 ) ( -768 0 -443 ) ( -768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 512 0 0 ) ( 428 -115 256 ) ( 443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 512 0 0 ) ( 768 0 0 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 256 ) ( 768 -115 256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 -256 0 ) ( 768 -256 0 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -256 0 ) ( 768 -115 256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 428 -115 256 ) ( 256 0 443 ) ( 222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 428 -115 256 ) ( 768 -115 256 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 443 ) ( 768 0 443 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 443 ) ( 768 -128 443 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -128 443 ) ( 768 0 443 ) ( 768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 0 443 ) ( 256 0 768 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 443 ) ( 768 0 443 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 768 ) ( 768 0 768 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 768 ) ( 768 -128 768 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 443 ) ( 768 -128 443 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -128 768 ) ( 768 0 768 ) ( 768 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 0 443 ) ( 0 0 512 ) ( 222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 256 0 443 ) ( 256 0 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 443 ) ( 222 -128 768 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 768 ) ( 0 0 768 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 443 -256 0 ) ( 428 -115 256 ) ( 314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 443 -256 0 ) ( 768 -256 0 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 256 ) ( 768 -115 256 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 256 ) ( 768 -314 256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -314 256 ) ( 768 -115 256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 428 -115 256 ) ( 222 -128 443 ) ( 314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 428 -115 256 ) ( 768 -115 256 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 443 ) ( 768 -128 443 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 256 ) ( 768 -314 256 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -314 256 ) ( 768 -128 443 ) ( 768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 443 -256 0 ) ( 314 -314 256 ) ( 256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 443 -256 0 ) ( 768 -256 0 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 256 ) ( 768 -314 256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 -443 0 ) ( 768 -443 0 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -443 0 ) ( 768 -314 256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 314 -314 256 ) ( 222 -128 443 ) ( 128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 314 -314 256 ) ( 768 -314 256 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 443 ) ( 768 -128 443 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 768 -222 443 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -222 443 ) ( 768 -128 443 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 222 -128 443 ) ( 222 -128 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 443 ) ( 768 -128 443 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 -128 768 ) ( 768 -128 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 768 ) ( 768 -222 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 768 -222 443 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -222 768 ) ( 768 -128 768 ) ( 768 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 222 -128 443 ) ( 0 0 512 ) ( 128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 222 -128 443 ) ( 222 -128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 128 -222 768 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 768 ) ( 0 0 768 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 -443 0 ) ( 314 -314 256 ) ( 115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 256 -443 0 ) ( 256 -768 0 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 256 ) ( 314 -768 256 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 256 ) ( 115 -768 256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -768 256 ) ( 314 -768 256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 -443 0 ) ( 768 -443 0 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 -443 0 ) ( 256 -768 0 ) ( 768 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -443 0 ) ( 768 -768 0 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -314 256 ) ( 768 -768 256 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 256 ) ( 314 -768 256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 256 ) ( 768 -768 0 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 314 -314 256 ) ( 128 -222 443 ) ( 115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 314 -314 256 ) ( 314 -768 256 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 128 -768 443 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 256 ) ( 115 -768 256 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -768 256 ) ( 128 -768 443 ) ( 314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 314 -314 256 ) ( 768 -314 256 ) ( 768 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 -314 256 ) ( 314 -768 256 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -314 256 ) ( 768 -768 256 ) ( 768 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -222 443 ) ( 768 -768 443 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 128 -768 443 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 443 ) ( 768 -768 256 ) ( 314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 128 -222 443 ) ( 128 -768 443 ) ( 768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 128 -222 768 ) ( 128 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -768 443 ) ( 128 -768 768 ) ( 768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 443 ) ( 768 -768 768 ) ( 768 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -222 443 ) ( 768 -222 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 -768 768 ) ( 128 -768 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 -443 0 ) ( 115 -428 256 ) ( 0 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 256 -443 0 ) ( 256 -768 0 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 256 ) ( 115 -768 256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -512 0 ) ( 0 -768 0 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -768 0 ) ( 115 -768 256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 115 -428 256 ) ( 128 -222 443 ) ( 0 -256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 115 -428 256 ) ( 115 -768 256 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 128 -768 443 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -768 443 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -768 443 ) ( 128 -768 443 ) ( 115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 128 -222 443 ) ( 128 -222 768 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 443 ) ( 128 -768 443 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 -222 768 ) ( 128 -768 768 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 768 ) ( 0 -768 768 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -768 443 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -768 768 ) ( 128 -768 768 ) ( 128 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 128 -222 443 ) ( 0 0 512 ) ( 0 -256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 128 -222 443 ) ( 128 -222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -256 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 768 ) ( 0 0 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 -512 0 ) ( 115 -428 256 ) ( -115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 0 -512 0 ) ( 0 -768 0 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 -428 256 ) ( 115 -768 256 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( -115 -768 256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -768 256 ) ( 115 -768 256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 115 -428 256 ) ( 0 -256 443 ) ( -115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 115 -428 256 ) ( 115 -768 256 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -768 443 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( -115 -768 256 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -768 256 ) ( 0 -768 443 ) ( 115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 768 0 ) ( 115 768 256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 256 768 0 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 115 768 256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 512 0 ) ( 0 768 0 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 512 0 ) ( 115 428 256 ) ( 256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 128 768 443 ) ( 0 768 443 ) ( 115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 768 443 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 768 443 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 115 768 256 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 0 256 443 ) ( 128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 128 768 768 ) ( 0 768 768 ) ( 0 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 768 443 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 768 ) ( 128 768 768 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 768 ) ( 0 768 768 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 768 443 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 256 768 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 128 222 768 ) ( 0 0 768 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 222 768 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 256 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 0 512 ) ( 128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 314 768 256 ) ( 115 768 256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 314 768 256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 115 768 256 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 256 768 0 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 115 428 256 ) ( 314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 314 768 256 ) ( 128 768 443 ) ( 115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 314 768 256 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 768 443 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 115 768 256 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 128 222 443 ) ( 314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 443 768 0 ) ( 314 768 256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 443 768 0 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 314 768 256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 256 768 0 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 443 0 ) ( 314 314 256 ) ( 443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 222 768 443 ) ( 128 768 443 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 222 768 443 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 768 443 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 314 768 256 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 128 222 443 ) ( 222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 222 768 768 ) ( 128 768 768 ) ( 128 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 222 768 443 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 768 ) ( 222 768 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 768 ) ( 128 768 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 768 443 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 222 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 222 128 768 ) ( 0 0 768 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 222 128 768 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 128 222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 128 222 443 ) ( 0 0 512 ) ( 222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 115 256 ) ( 768 314 256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 768 115 256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 768 314 256 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 768 256 0 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 314 314 256 ) ( 428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 768 256 ) ( 768 768 0 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 768 314 256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 768 256 ) ( 768 768 256 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 768 0 ) ( 768 768 0 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 768 256 0 ) ( 443 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 443 768 0 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 768 115 256 ) ( 768 128 443 ) ( 768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 768 115 256 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 768 128 443 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 768 314 256 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 222 128 443 ) ( 428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 768 443 ) ( 768 768 256 ) ( 768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 768 128 443 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 768 443 ) ( 768 768 443 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 768 256 ) ( 768 768 256 ) ( 222 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 768 314 256 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 314 314 256 ) ( 314 768 256 ) ( 222 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 768 768 768 ) ( 768 128 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 768 443 ) ( 222 768 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 768 443 ) ( 768 768 768 ) ( 222 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 768 128 443 ) ( 768 128 768 ) ( 768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 222 128 768 ) ( 768 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 768 128 443 ) ( 768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 768 0 0 ) ( 768 115 256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 512 0 0 ) ( 768 0 0 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 768 115 256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 768 256 0 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 443 256 0 ) ( 428 115 256 ) ( 512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 0 443 ) ( 768 128 443 ) ( 768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 443 ) ( 768 0 443 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 768 128 443 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 768 115 256 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 222 128 443 ) ( 256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 0 768 ) ( 768 128 768 ) ( 768 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 443 ) ( 768 0 443 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 768 ) ( 768 0 768 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 768 ) ( 768 128 768 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 768 128 443 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 222 128 768 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 256 0 768 ) ( 0 0 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 443 ) ( 256 0 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 222 128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 222 128 443 ) ( 0 0 512 ) ( 256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 -115 256 ) ( 768 115 256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 256 ) ( 768 -115 256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 768 115 256 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 512 0 0 ) ( 768 0 0 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 512 0 0 ) ( 428 115 256 ) ( 428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 768 -115 256 ) ( 768 0 443 ) ( 768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 -115 256 ) ( 768 -115 256 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 256 0 443 ) ( 768 0 443 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 768 115 256 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 428 115 256 ) ( 256 0 443 ) ( 428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -512 0 0 ) ( -428 115 256 ) ( -443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -512 0 0 ) ( -768 0 0 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 256 ) ( -768 115 256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 256 0 ) ( -768 256 0 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 256 0 ) ( -768 115 256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -428 115 256 ) ( -256 0 443 ) ( -222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -428 115 256 ) ( -768 115 256 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 443 ) ( -768 0 443 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 443 ) ( -768 128 443 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 128 443 ) ( -768 0 443 ) ( -768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 0 443 ) ( -256 0 768 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 443 ) ( -768 0 443 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 768 ) ( -768 0 768 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 768 ) ( -768 128 768 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 443 ) ( -768 128 443 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 128 768 ) ( -768 0 768 ) ( -768 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 0 443 ) ( 0 0 512 ) ( -222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -256 0 443 ) ( -256 0 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 443 ) ( -222 128 768 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 768 ) ( 0 0 768 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -443 256 0 ) ( -428 115 256 ) ( -314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -443 256 0 ) ( -768 256 0 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 256 ) ( -768 115 256 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 256 ) ( -768 314 256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 314 256 ) ( -768 115 256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -428 115 256 ) ( -222 128 443 ) ( -314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -428 115 256 ) ( -768 115 256 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 443 ) ( -768 128 443 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 256 ) ( -768 314 256 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 314 256 ) ( -768 128 443 ) ( -768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -443 256 0 ) ( -314 314 256 ) ( -256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -443 256 0 ) ( -768 256 0 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 256 ) ( -768 314 256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 443 0 ) ( -768 443 0 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 443 0 ) ( -768 314 256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -314 314 256 ) ( -222 128 443 ) ( -128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -314 314 256 ) ( -768 314 256 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 443 ) ( -768 128 443 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -768 222 443 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 222 443 ) ( -768 128 443 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -222 128 443 ) ( -222 128 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 443 ) ( -768 128 443 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 128 768 ) ( -768 128 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 768 ) ( -768 222 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -768 222 443 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 222 768 ) ( -768 128 768 ) ( -768 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -222 128 443 ) ( 0 0 512 ) ( -128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -222 128 443 ) ( -222 128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -128 222 768 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 768 ) ( 0 0 768 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 443 0 ) ( -314 314 256 ) ( -115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -256 443 0 ) ( -256 768 0 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 256 ) ( -314 768 256 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 256 ) ( -115 768 256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 768 256 ) ( -314 768 256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 443 0 ) ( -768 443 0 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 443 0 ) ( -256 768 0 ) ( -768 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 443 0 ) ( -768 768 0 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 314 256 ) ( -768 768 256 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 256 ) ( -314 768 256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 256 ) ( -768 768 0 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -314 314 256 ) ( -128 222 443 ) ( -115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -314 314 256 ) ( -314 768 256 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -128 768 443 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 256 ) ( -115 768 256 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 768 256 ) ( -128 768 443 ) ( -314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -314 314 256 ) ( -768 314 256 ) ( -768 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 314 256 ) ( -314 768 256 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 314 256 ) ( -768 768 256 ) ( -768 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 222 443 ) ( -768 768 443 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -128 768 443 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 443 ) ( -768 768 256 ) ( -314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -128 222 443 ) ( -128 768 443 ) ( -768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -128 222 768 ) ( -128 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 768 443 ) ( -128 768 768 ) ( -768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 443 ) ( -768 768 768 ) ( -768 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 222 443 ) ( -768 222 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 768 768 ) ( -128 768 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 443 0 ) ( -115 428 256 ) ( 0 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -256 443 0 ) ( -256 768 0 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 256 ) ( -115 768 256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 512 0 ) ( 0 768 0 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 768 0 ) ( -115 768 256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -115 428 256 ) ( -128 222 443 ) ( 0 256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -115 428 256 ) ( -115 768 256 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -128 768 443 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 768 443 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 768 443 ) ( -128 768 443 ) ( -115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -128 222 443 ) ( -128 222 768 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 443 ) ( -128 768 443 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 222 768 ) ( -128 768 768 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 768 ) ( 0 768 768 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 768 443 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 768 768 ) ( -128 768 768 ) ( -128 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -128 222 443 ) ( 0 0 512 ) ( 0 256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -128 222 443 ) ( -128 222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 256 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 768 ) ( 0 0 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 0 512 0 ) ( -115 428 256 ) ( 115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 0 512 0 ) ( 0 768 0 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 428 256 ) ( -115 768 256 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 115 768 256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 768 256 ) ( -115 768 256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -115 428 256 ) ( 0 256 443 ) ( 115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( -115 428 256 ) ( -115 768 256 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 256 443 ) ( 0 768 443 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 428 256 ) ( 115 768 256 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 115 768 256 ) ( 0 768 443 ) ( -115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 -768 0 ) ( -115 -768 256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -256 -768 0 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( -115 -768 256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -512 0 ) ( 0 -768 0 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -512 0 ) ( -115 -428 256 ) ( -256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -128 -768 443 ) ( 0 -768 443 ) ( -115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -768 443 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -768 443 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( -115 -768 256 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( 0 -256 443 ) ( -128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -128 -768 768 ) ( 0 -768 768 ) ( 0 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -768 443 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 768 ) ( -128 -768 768 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 768 ) ( 0 -768 768 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -768 443 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -256 768 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -128 -222 768 ) ( 0 0 768 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -222 768 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 -256 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 -256 443 ) ( 0 0 512 ) ( -128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -314 -768 256 ) ( -115 -768 256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -314 -768 256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( -115 -768 256 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -256 -768 0 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -115 -428 256 ) ( -314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -314 -768 256 ) ( -128 -768 443 ) ( -115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -314 -768 256 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -768 443 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( -115 -768 256 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -115 -428 256 ) ( -128 -222 443 ) ( -314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -443 -768 0 ) ( -314 -768 256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -443 -768 0 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -314 -768 256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -256 -768 0 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 -443 0 ) ( -314 -314 256 ) ( -443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -222 -768 443 ) ( -128 -768 443 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -222 -768 443 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -768 443 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -314 -768 256 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -128 -222 443 ) ( -222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -222 -768 768 ) ( -128 -768 768 ) ( -128 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -222 -768 443 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 768 ) ( -222 -768 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 768 ) ( -128 -768 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -768 443 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -222 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -222 -128 768 ) ( 0 0 768 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -222 -128 768 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( -128 -222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -128 -222 443 ) ( 0 0 512 ) ( -222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -115 256 ) ( -768 -314 256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -768 -115 256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -768 -314 256 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -768 -256 0 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -314 -314 256 ) ( -428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -768 256 ) ( -768 -768 0 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -768 -314 256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -768 256 ) ( -768 -768 256 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -768 0 ) ( -768 -768 0 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -768 -256 0 ) ( -443 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -443 -768 0 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -768 -115 256 ) ( -768 -128 443 ) ( -768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -768 -115 256 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -768 -128 443 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -768 -314 256 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -222 -128 443 ) ( -428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 -768 443 ) ( -768 -768 256 ) ( -768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -768 -128 443 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -768 443 ) ( -768 -768 443 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -768 256 ) ( -768 -768 256 ) ( -222 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -768 -314 256 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -314 -314 256 ) ( -314 -768 256 ) ( -222 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -768 -768 768 ) ( -768 -128 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -768 443 ) ( -222 -768 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -768 443 ) ( -768 -768 768 ) ( -222 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -768 -128 443 ) ( -768 -128 768 ) ( -768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -222 -128 768 ) ( -768 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -768 -128 443 ) ( -768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -768 0 0 ) ( -768 -115 256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -512 0 0 ) ( -768 0 0 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -768 -115 256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -768 -256 0 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -443 -256 0 ) ( -428 -115 256 ) ( -512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 0 443 ) ( -768 -128 443 ) ( -768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 443 ) ( -768 0 443 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -768 -128 443 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -768 -115 256 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -222 -128 443 ) ( -256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 0 768 ) ( -768 -128 768 ) ( -768 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 443 ) ( -768 0 443 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 768 ) ( -768 0 768 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 768 ) ( -768 -128 768 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -768 -128 443 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -222 -128 768 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( -256 0 768 ) ( 0 0 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 443 ) ( -256 0 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 0 0 512 ) ( 0 0 768 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( -222 -128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -222 -128 443 ) ( 0 0 512 ) ( -256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 115 256 ) ( -768 -115 256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 256 ) ( -768 115 256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -768 -115 256 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -512 0 0 ) ( -768 0 0 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -512 0 0 ) ( -428 -115 256 ) ( -428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( -768 115 256 ) ( -768 0 443 ) ( -768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 115 256 ) ( -768 115 256 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -256 0 443 ) ( -768 0 443 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -768 -115 256 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -428 -115 256 ) ( -256 0 443 ) ( -428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 1024 768 -768 ) ( 768 768 -768 ) ( 768 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 832 -128 768 ) ( 832 768 768 ) ( 1088 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 704 -768 0 ) ( 960 -768 0 ) ( 960 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 776 -128 0 ) ( 776 768 0 ) ( 776 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 1024 768 0 ) ( 768 768 0 ) ( 768 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 768 0 ) ( 768 -128 0 ) ( 768 -128 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 768 -768 -768 ) ( -768 -768 -768 ) ( -768 -832 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 -832 768 ) ( -768 -768 768 ) ( 768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 -776 760 ) ( 768 -776 760 ) ( 768 -776 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 -832 768 ) ( 768 -768 768 ) ( 768 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 -768 768 ) ( -768 -768 768 ) ( -768 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 -768 768 ) ( -768 -832 768 ) ( -768 -832 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -768 768 -768 ) ( -1088 768 -768 ) ( -1088 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -1088 -768 768 ) ( -1088 768 768 ) ( -768 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -1088 -768 768 ) ( -768 -768 768 ) ( -768 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 -768 768 ) ( -768 768 768 ) ( -768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 768 768 ) ( -1088 768 768 ) ( -1088 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -776 704 768 ) ( -776 -832 768 ) ( -776 -832 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 768 1088 -768 ) ( -768 1088 -768 ) ( -768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 768 768 ) ( -768 1088 768 ) ( 768 1088 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 768 768 ) ( 768 768 768 ) ( 768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 768 768 ) ( 768 1088 768 ) ( 768 1088 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 832 776 768 ) ( -704 776 768 ) ( -704 776 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 1088 768 ) ( -768 768 768 ) ( -768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 768 768 768 ) ( -768 768 768 ) ( -768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -744 -704 776 ) ( -744 832 776 ) ( 792 832 776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 -768 1344 ) ( 768 -768 1344 ) ( 768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 -768 1344 ) ( 768 768 1344 ) ( 768 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 768 1344 ) ( -768 768 1344 ) ( -768 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 768 1344 ) ( -768 -768 1344 ) ( -768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 768 768 -776 ) ( -768 768 -776 ) ( -768 -768 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 -768 -768 ) ( -768 768 -768 ) ( 768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 -768 -768 ) ( 768 -768 -768 ) ( 768 -768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 -768 -768 ) ( 768 768 -768 ) ( 768 768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 768 768 -768 ) ( -768 768 -768 ) ( -768 768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -768 768 -768 ) ( -768 -768 -768 ) ( -768 -768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"origin" "-64 0 -384" -"classname" "info_player_deathmatch" -} -{ -"light" "1000" -"origin" "0 0 64" -"classname" "light" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/coarse_snap_normal/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/coarse_snap_normal/README.txt deleted file mode 100644 index 6525380d..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/coarse_snap_normal/README.txt +++ /dev/null @@ -1,16 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -Because of the coarse nature of SnapNormal(), planes that are 0.25 degrees -away from being axial are "snapped" to be axial. The "normal epsilon" -is a very small value by default, and cannot go much smaller (without -running into limits of floating point numbers). The problem with -SnapNormal() is that we compare the components of the normal that are near -1, instead of comaring the components that are near 0. This leads to a very -coarse and inaccurate SnapNormal(). - -If you open the example map in Radiant, you can see that the red brick should -touch the middle checkered brick at the edge. However, once this map is -compiled, the edges are a significant distance apart. This is due to the -coarse and inaccurate nature of SnapNormal(). Likewise, the green brick should -be flush with the center tiled brick, but it's not. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/coarse_snap_normal/maps/coarse_snap_normal.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/coarse_snap_normal/maps/coarse_snap_normal.map deleted file mode 100644 index 9be4523b..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/coarse_snap_normal/maps/coarse_snap_normal.map +++ /dev/null @@ -1,84 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 544 312 -8 ) ( -584 312 -8 ) ( -584 -488 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -576 -488 0 ) ( -576 312 0 ) ( 552 312 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -584 -512 8 ) ( 544 -512 8 ) ( 544 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -488 8 ) ( 512 312 8 ) ( 512 312 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 528 512 8 ) ( -600 512 8 ) ( -600 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 312 8 ) ( -512 -488 8 ) ( -512 -488 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 720 512 0 ) ( 512 512 0 ) ( 512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 512 ) ( 512 512 512 ) ( 720 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 512 ) ( 720 -512 512 ) ( 720 -512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 520 -512 520 ) ( 520 512 520 ) ( 520 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 720 512 512 ) ( 512 512 512 ) ( 512 512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 512 512 ) ( 512 -512 512 ) ( 512 -512 -8 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -512 512 0 ) ( -592 512 0 ) ( -592 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -592 -512 512 ) ( -592 512 512 ) ( -512 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -592 -512 512 ) ( -512 -512 512 ) ( -512 -512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -512 512 ) ( -512 512 512 ) ( -512 512 -8 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -512 512 512 ) ( -592 512 512 ) ( -592 512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -520 512 536 ) ( -520 -512 536 ) ( -520 -512 16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 512 512 512 ) ( -512 512 512 ) ( -512 -512 512 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -488 -512 520 ) ( -488 512 520 ) ( 536 512 520 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -512 664 ) ( 512 -512 664 ) ( 512 -512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 664 ) ( 512 512 664 ) ( 512 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 512 664 ) ( -512 512 664 ) ( -512 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 512 664 ) ( -512 -512 664 ) ( -512 -512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 512 608 0 ) ( -512 608 0 ) ( -512 520 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 520 512 ) ( -512 608 512 ) ( 512 608 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 512 512 ) ( 512 512 512 ) ( 512 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 512 520 512 ) ( 512 608 512 ) ( 512 608 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 520 520 ) ( -512 520 520 ) ( -512 520 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 608 512 ) ( -512 520 512 ) ( -512 520 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 512 -512 0 ) ( -512 -512 0 ) ( -512 -600 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -600 512 ) ( -512 -512 512 ) ( 512 -512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -520 520 ) ( 512 -520 520 ) ( 512 -520 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -600 512 ) ( 512 -512 512 ) ( 512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 512 ) ( -512 -512 512 ) ( -512 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -512 -512 512 ) ( -512 -600 512 ) ( -512 -600 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 512 72 64 ) ( -512 72 64 ) ( -512 -448 64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -128 448 260 ) ( 192 448 260 ) ( 192 -448 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -512 -448 256 ) ( 512 -448 256 ) ( 512 -448 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 192 -440 256 ) ( 192 80 256 ) ( 192 80 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 192 448 260 ) ( -128 448 260 ) ( -128 448 64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -128 56 256 ) ( -128 -464 256 ) ( -128 -464 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 192 -448 232 ) ( -128 -448 232 ) ( -128 -472 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -128 -472 256 ) ( -128 -448 256 ) ( 192 -448 256 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -128 -472 256 ) ( 192 -472 256 ) ( 192 -472 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 192 -472 256 ) ( 192 -448 256 ) ( 192 -448 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 192 -448 256 ) ( -128 -448 256 ) ( -128 -448 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -128 -448 256 ) ( -128 -472 256 ) ( -128 -472 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 192 472 260 ) ( -128 472 260 ) ( -128 448 260 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( -128 448 280 ) ( -128 472 280 ) ( 192 472 280 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( -128 448 280 ) ( 192 448 280 ) ( 192 448 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( 192 448 280 ) ( 192 472 280 ) ( 192 472 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( 192 472 280 ) ( -128 472 280 ) ( -128 472 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( -128 472 280 ) ( -128 448 280 ) ( -128 448 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -} -} -{ -"light" "3000" -"origin" "0 0 384" -"classname" "light" -} -{ -"origin" "0 -64 384" -"classname" "info_player_deathmatch" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/README.txt deleted file mode 100644 index f9aa3d6d..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/README.txt +++ /dev/null @@ -1,16 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The info_null in the map for the decal is not 100% below the center of the -decal itself, because to be totally below it would have to lie on half-units. -So, the info_null lies almost directly below the center of the decal. In -this particular case, all kinds of bad things happen to the decal. For one, -during compiling we get warnings like this: - - Bad texture matrix! (B) (50.512253, -49.515625) != (50.484375, -49.515625) - Bad texture matrix! (C) (48.723190, -49.522587) != (48.695312, -49.515625) - Bad texture matrix! (B) (48.723186, -49.522587) != (48.695312, -49.515625) - -If you look at where the decal (it's just a blue translucent tile texture) -meets the far wall, it's clearly not aligned correctly. The tile on the decal -and the tile on the wall should align perfectly, and it's quite a bit off. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/maps/decal_misalignment.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/maps/decal_misalignment.map deleted file mode 100644 index b764bf20..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/maps/decal_misalignment.map +++ /dev/null @@ -1,89 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 6472 6336 -960 ) ( 6288 6336 -960 ) ( 6288 6320 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6264 6320 -576 ) ( 6264 6336 -576 ) ( 6448 6336 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6280 6328 -832 ) ( 6464 6328 -832 ) ( 6464 6328 -848 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 6320 -832 ) ( 6464 6336 -832 ) ( 6464 6336 -848 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 6336 -832 ) ( 6280 6336 -832 ) ( 6280 6336 -848 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 6336 -832 ) ( 6144 6320 -832 ) ( 6144 6320 -848 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6552 6520 -960 ) ( 6464 6520 -960 ) ( 6464 6336 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 6336 -576 ) ( 6464 6520 -576 ) ( 6552 6520 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 6336 -576 ) ( 6552 6336 -576 ) ( 6552 6336 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6472 6344 -576 ) ( 6472 6528 -576 ) ( 6472 6528 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6528 7360 -576 ) ( 6440 7360 -576 ) ( 6440 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 6520 -576 ) ( 6464 6336 -576 ) ( 6464 6336 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 6464 7424 -960 ) ( 6144 7424 -960 ) ( 6144 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 7360 -576 ) ( 6144 7424 -576 ) ( 6464 7424 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 7360 -576 ) ( 6464 7360 -576 ) ( 6464 7360 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 6464 7360 -576 ) ( 6464 7424 -576 ) ( 6464 7424 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 7368 -576 ) ( 6144 7368 -576 ) ( 6144 7368 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 7424 -576 ) ( 6144 7360 -576 ) ( 6144 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6144 7360 -960 ) ( 5880 7360 -960 ) ( 5880 6808 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 5880 6808 -576 ) ( 5880 7360 -576 ) ( 6144 7360 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 5864 6336 -576 ) ( 6128 6336 -576 ) ( 6128 6336 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 6808 -576 ) ( 6144 7360 -576 ) ( 6144 7360 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 7360 -576 ) ( 5880 7360 -576 ) ( 5880 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 7384 -576 ) ( 6136 6832 -576 ) ( 6136 6832 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6456 7360 -968 ) ( 6136 7360 -968 ) ( 6136 6336 -968 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 6336 -960 ) ( 6144 7360 -960 ) ( 6464 7360 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 6336 -960 ) ( 6464 6336 -960 ) ( 6464 6336 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 6336 -960 ) ( 6464 7360 -960 ) ( 6464 7360 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 7360 -960 ) ( 6144 7360 -960 ) ( 6144 7360 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 7360 -960 ) ( 6144 6336 -960 ) ( 6144 6336 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6464 7360 -576 ) ( 6152 7360 -576 ) ( 6152 6336 -576 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 6176 6336 -568 ) ( 6176 7360 -568 ) ( 6488 7360 -568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6152 6336 -472 ) ( 6464 6336 -472 ) ( 6464 6336 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 6336 -472 ) ( 6464 7360 -472 ) ( 6464 7360 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6464 7360 -472 ) ( 6152 7360 -472 ) ( 6152 7360 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 7360 -472 ) ( 6144 6336 -472 ) ( 6144 6336 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6200 7360 -896 ) ( 6200 6336 -896 ) ( 6592 6336 -896 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 -( 6360 6336 -832 ) ( 6360 7256 -832 ) ( 6464 7256 -832 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 -( 6208 6337 -832 ) ( 6400 6337 -832 ) ( 6400 6337 -896 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 -( 6463 6336 -816 ) ( 6463 7360 -816 ) ( 6463 7360 -880 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 -( 6232 7264 -896 ) ( 6232 7264 -832 ) ( 6232 6337 -896 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 -( 6232 7256 -832 ) ( 6232 7256 -896 ) ( 6463 7256 -832 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 -} -} -{ -"target" "checker" -"classname" "_decal" -{ -patchDef2 -{ -radiant_regression_tests/tile_trans -( 3 3 0 0 0 ) -( -( ( 6462 7255 -832 50.484375 -56.679688 ) ( 6462 6796.500000 -832 50.484375 -53.097656 ) ( 6462 6338 -832 50.484375 -49.515625 ) ) -( ( 6347.500000 7255 -832 49.589844 -56.679688 ) ( 6347.500000 6796.500000 -832 49.589844 -53.097656 ) ( 6347.500000 6338 -832 49.589844 -49.515625 ) ) -( ( 6233 7255 -832 48.695312 -56.679688 ) ( 6233 6796.500000 -832 48.695312 -53.097656 ) ( 6233 6338 -832 48.695312 -49.515625 ) ) -) -} -} -} -{ -"targetname" "checker" -"origin" "6347 6796 -840" -"classname" "info_null" -} -{ -"origin" "6288 6704 -712" -"classname" "info_player_deathmatch" -} -{ -"light" "2000" -"origin" "6304 6792 -704" -"classname" "light" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/scripts/radiant_regression_tests.shader b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/scripts/radiant_regression_tests.shader deleted file mode 100644 index af31c07d..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/decal_misalignment/scripts/radiant_regression_tests.shader +++ /dev/null @@ -1,29 +0,0 @@ -textures/radiant_regression_tests/tile_trans -{ - qer_trans 0.9 - q3map_bounceScale 0.0 - surfaceparm trans - cull disable - polygonOffset - { - map textures/radiant_regression_tests/tile_trans.tga - blendFunc blend - alphaGen const 1 - } -} - -textures/radiant_regression_tests/glass -{ - qer_editorImage textures/radiant_regression_tests/qer_glass.tga - qer_trans 0.6 - q3map_bounceScale 0.0 - surfaceparm nolightmap - surfaceparm detail - surfaceparm trans - cull disable - { - map textures/radiant_regression_tests/glass.tga - blendFunc add - tcGen environment - } -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding/README.txt deleted file mode 100644 index b060d083..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding/README.txt +++ /dev/null @@ -1,4 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -I'm testing when windings become degenerate. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding/maps/degenerate_winding.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding/maps/degenerate_winding.map deleted file mode 100644 index 808de186..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding/maps/degenerate_winding.map +++ /dev/null @@ -1,68 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 256 256 -8 ) ( -256 256 -8 ) ( -256 -264 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -264 0 ) ( -256 256 0 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -256 -256 8 ) ( 256 -256 8 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -264 8 ) ( 256 256 8 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 256 8 ) ( -256 256 8 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 8 ) ( -256 -264 8 ) ( -256 -264 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 296 256 0 ) ( 256 256 0 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 280 -256 512 ) ( 280 256 512 ) ( 320 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 392 ) ( 296 -256 392 ) ( 296 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 264 -256 384 ) ( 264 256 384 ) ( 264 256 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 296 256 392 ) ( 256 256 392 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 256 392 ) ( 256 -256 392 ) ( 256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -256 256 0 ) ( -320 256 0 ) ( -320 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -320 -256 512 ) ( -320 256 512 ) ( -256 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -320 -256 504 ) ( -256 -256 504 ) ( -256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -256 504 ) ( -256 256 504 ) ( -256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -256 256 504 ) ( -320 256 504 ) ( -320 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -264 256 496 ) ( -264 -256 496 ) ( -264 -256 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 256 256 512 ) ( -256 256 512 ) ( -256 -256 512 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -224 -256 520 ) ( -224 256 520 ) ( 288 256 520 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -256 584 ) ( 256 -256 584 ) ( 256 -256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 584 ) ( 256 256 584 ) ( 256 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 256 584 ) ( -256 256 584 ) ( -256 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 584 ) ( -256 -256 584 ) ( -256 -256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 256 328 0 ) ( -256 328 0 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 512 ) ( -256 328 512 ) ( 256 328 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 512 ) ( 256 256 512 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 256 256 512 ) ( 256 328 512 ) ( 256 328 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 264 536 ) ( -256 264 536 ) ( -256 264 24 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 328 512 ) ( -256 256 512 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 256 -256 0 ) ( -256 -256 0 ) ( -256 -304 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -304 512 ) ( -256 -256 512 ) ( 256 -256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -264 520 ) ( 256 -264 520 ) ( 256 -264 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -304 512 ) ( 256 -256 512 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 512 ) ( -256 -256 512 ) ( -256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -256 -256 512 ) ( -256 -304 512 ) ( -256 -304 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 64 0 128 ) ( 8 0 128 ) ( 8 -8 128 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( 8 -8 464 ) ( 8 0 464 ) ( 64 0 464 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( -240 8 464 ) ( -240 0 464 ) ( -240 0 160 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( -240 24 128 ) ( 160 8 128 ) ( -240 24 464 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 160 8 128 ) ( -240 0 128 ) ( 160 8 464 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 159 11 128 ) ( 159 0 128 ) ( 159 11 464 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -} -} -{ -"light" "1000" -"origin" "-40 0 32" -"classname" "light" -} -{ -"origin" "-40 128 96" -"classname" "info_player_deathmatch" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding2/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding2/README.txt deleted file mode 100644 index b36f2db3..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding2/README.txt +++ /dev/null @@ -1,14 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The sample map contains a wedge brush. The tip (the sharp edge) of the wedge -is chopped off by 2 planes, leaving very narrow windings. Each of these 2 -narrow windings is less than 0.1 units tall. However, the wedge has height -exactly equal to 1/8 unit at the point where it is chopped. Therefore, -the two narrow sides caused by the chops are expected to be degenerate and the -top face of the wedge is expected to be unaffected. This should leave a -"hole" in the narrow part of the wedge. - -The hole isn't desirable but it's expected based on the logic in the code. -Still, if there is a hole in the brush, I consider this regression test to -be broken. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding2/maps/degenerate_winding2.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding2/maps/degenerate_winding2.map deleted file mode 100644 index 70abf7cc..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding2/maps/degenerate_winding2.map +++ /dev/null @@ -1,69 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 7 0 0 ) ( 7 0 1 ) ( 7 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 7 0 0 ) ( 7 64 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 -( 7 0 1 ) ( 7 0 0 ) ( -1 0 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -1 64 0 ) ( 7 64 0 ) ( 7 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 7 0 1 ) ( -1 0 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 -( -1 0 2 ) ( 0 0 0 ) ( 0 64 0 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( 1 0 2 ) ( -7 0 -13 ) ( -7 64 -13 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 128 72 -72 ) ( -128 72 -72 ) ( -128 8 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 120 -64 ) ( -128 184 -64 ) ( 128 184 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -128 -128 -64 ) ( 128 -128 -64 ) ( 128 -128 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 0 -64 ) ( 192 64 -64 ) ( 192 64 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 128 192 -64 ) ( -128 192 -64 ) ( -128 192 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 64 -64 ) ( -192 0 -64 ) ( -192 0 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 256 192 -64 ) ( 192 192 -64 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 256 ) ( 192 192 256 ) ( 256 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 256 ) ( 256 -128 256 ) ( 256 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 200 -128 240 ) ( 200 192 240 ) ( 200 192 -80 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -192 192 -64 ) ( -280 192 -64 ) ( -280 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -280 -128 256 ) ( -280 192 256 ) ( -192 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -280 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -128 256 ) ( -192 192 256 ) ( -192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -192 192 256 ) ( -280 192 256 ) ( -280 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -200 192 256 ) ( -200 -128 256 ) ( -200 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 192 192 256 ) ( -192 192 256 ) ( -192 -128 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -176 -128 264 ) ( -176 192 264 ) ( 208 192 264 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -128 304 ) ( 192 -128 304 ) ( 192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 304 ) ( 192 192 304 ) ( 192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 192 304 ) ( -192 192 304 ) ( -192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 192 304 ) ( -192 -128 304 ) ( -192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 192 272 -64 ) ( -192 272 -64 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 192 256 ) ( -192 272 256 ) ( 192 272 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 192 192 256 ) ( 192 272 256 ) ( 192 272 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 200 256 ) ( -192 200 256 ) ( -192 200 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 272 256 ) ( -192 192 256 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 192 -128 -64 ) ( -192 -128 -64 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -192 256 ) ( -192 -128 256 ) ( 192 -128 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -136 280 ) ( 192 -136 280 ) ( 192 -136 -40 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -192 -128 256 ) ( -192 -192 256 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"light" "1000" -"origin" "-8 40 128" -"classname" "light" -} -{ -"origin" "-112 -40 40" -"classname" "info_player_deathmatch" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding3/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding3/README.txt deleted file mode 100644 index 3aa08fc9..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding3/README.txt +++ /dev/null @@ -1,18 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The sample map contains a wedge brush. The tip (the sharp edge) of the wedge -is chopped off by the YZ plane (side 5, or the last side, of the brush). -The height of the wedge where it is chopped is about 0.9. This makes it -barely smaller than DEGENERATE_EPSILON. So the face resulting from the chop -is probably degenerate, and that winding will be removed. I'm now wondering -what happens to the rest of the brush. 0.9 rounded to the nearest 1/8 unit -is 1/8, so the top face of the brush should get a slight raise, making the -"hole" even bigger. The sides will have degenerate edges near the chop, so -they will become triangles, creating open slivers in the sides. - -Although this behavior is a tad nasty, it is expected based on the way the -code is written. I want to make sure nothing really nasty happens. - -I consider this regression test to be broken if there is a "hole" in the brush, -and I consider this test to be very broken if something more drastic happens. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding3/maps/degenerate_winding3.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding3/maps/degenerate_winding3.map deleted file mode 100644 index 1817265b..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/degenerate_winding3/maps/degenerate_winding3.map +++ /dev/null @@ -1,68 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 10 0 0 ) ( 10 0 1 ) ( 10 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 10 0 0 ) ( 10 64 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 -( 10 0 1 ) ( 10 0 0 ) ( -1 0 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -1 64 0 ) ( 10 64 0 ) ( 10 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( 10 0 1 ) ( -1 0 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 -( 0 0 1 ) ( 0 0 0 ) ( 0 64 0 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 128 72 -72 ) ( -128 72 -72 ) ( -128 8 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 120 -64 ) ( -128 184 -64 ) ( 128 184 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -128 -128 -64 ) ( 128 -128 -64 ) ( 128 -128 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 0 -64 ) ( 192 64 -64 ) ( 192 64 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 128 192 -64 ) ( -128 192 -64 ) ( -128 192 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 64 -64 ) ( -192 0 -64 ) ( -192 0 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 256 192 -64 ) ( 192 192 -64 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 256 ) ( 192 192 256 ) ( 256 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 256 ) ( 256 -128 256 ) ( 256 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 200 -128 240 ) ( 200 192 240 ) ( 200 192 -80 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -192 192 -64 ) ( -280 192 -64 ) ( -280 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -280 -128 256 ) ( -280 192 256 ) ( -192 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -280 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -128 256 ) ( -192 192 256 ) ( -192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -192 192 256 ) ( -280 192 256 ) ( -280 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -200 192 256 ) ( -200 -128 256 ) ( -200 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 192 192 256 ) ( -192 192 256 ) ( -192 -128 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -176 -128 264 ) ( -176 192 264 ) ( 208 192 264 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -128 304 ) ( 192 -128 304 ) ( 192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 304 ) ( 192 192 304 ) ( 192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 192 304 ) ( -192 192 304 ) ( -192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 192 304 ) ( -192 -128 304 ) ( -192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 192 272 -64 ) ( -192 272 -64 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 192 256 ) ( -192 272 256 ) ( 192 272 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 192 192 256 ) ( 192 272 256 ) ( 192 272 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 200 256 ) ( -192 200 256 ) ( -192 200 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 272 256 ) ( -192 192 256 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 192 -128 -64 ) ( -192 -128 -64 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -192 256 ) ( -192 -128 256 ) ( 192 -128 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -192 -136 280 ) ( 192 -136 280 ) ( 192 -136 -40 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 192 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -192 -128 256 ) ( -192 -192 256 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"light" "1000" -"origin" "-8 40 128" -"classname" "light" -} -{ -"origin" "-112 -40 40" -"classname" "info_player_deathmatch" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/README.txt deleted file mode 100644 index a65d9203..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/README.txt +++ /dev/null @@ -1,183 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The example map, maps/disappearing_sliver.map, contains an example of this bug. -There are 6 walls in the map, and one tall thin triangular sliver brush in the -middle of the room (7 brushes total). Only one face of the sliver in the -middle of the room is a draw surface. The bug is that this sliver surface is -not rendered in the compiled BSP. Note that the sliver brush was hand-crafted -to demonstrate the bug. If you re-save the map, Radiant might adjust the -order in which the planes on the brush are defined, and this might, as a side -effect, get rid of the immediate bug. - -To trigger the bug, compile the map; you don't need -vis or -light. Only --bsp (the first q3map2 stage) is necessary to trigger the bug. The only -entities in the map are 2 lights and a single info_player_deathmatch, so the -map will compile for any Q3 mod. - - -SOLUTION TO PROBLEM: -==================== - -Several days were spent studying this problem in great detail. - -The fix for this problem was to make the outcome of the VectorNormalize() -function libs/mathlib/mathlib.c more accurate. The previous code in this -function looks something like this: - - vec_t length, ilength; // vec_t is a typedef for 32 bit float. - - /* Compute length */ - - ilength = 1.0f/length; - out[0] = in[0]*ilength; - out[1] = in[1]*ilength; - out[2] = in[2]*ilength; - -As you can see, we are introducing a lot of extra error into our normalized -vector by multiplying by the reciprocal length instead of outright dividing -by the length. The new fixed code looks like this: - - out[0] = in[0]/length; - out[1] = in[1]/length; - out[2] = in[2]/length; - -And we get rid of the recpirocal length ilength altogether. Even the -slightest math errors are magnified in successive calls to linear algebra -functions. - -The change described above was commmitted to GtkRadiant trunk as revision 363. - - -POSSIBLE SIDE EFFECTS: -====================== - -The only negative side effect is that compilation of a map might take longer -due to an increased number of divide operations. (I'm actually not sure if -that is indeed the case.) Another side effect might be that if you're used -to a map being broken (missing triangles) or having "sparklies" between -brushes, those might be gone now. :-) - - -IN-DEPTH DISCUSSION: -==================== - -VectorNormalize() is used very frequently in Radiant and tools code. My goal -for this fix was to make the least amount of code change but still be able to -demonstrate a significant improvement in math accuracy (including a fix to -the test case). At the same time don't risk that any other bugs pop up as a -side effect of this change. - -Here is the sequence of calls (stack trace) that cause the example bug to -happen: - - main() in main.c --> - BSPMain() in bsp.c --> - LoadMapFile() in map.c --> - ParseMapEntity() in map.c --> - ParseBrush() in map.c --> - FinishBrush() in map.c --> - CreateBrushWindings() in brush.c --> - ChopWindingInPlace() in polylib.c - -What basically happens in this sequence of calls is that a brush is parsed -out of the map file, "infinite" planes are created for each brush face, and -then the planes are "intersected" to find the exact vertex topologies of each -brush face. The vertex topology of the visible face of the sliver (in the -example map) gets computed with a significant amount of math error. If we -did our math with infinite precision, the sliver face would have the following -vertices: - - (67 -1022 0) - (88 -892 -768) - (134 -1015 0) - -In fact, if you open the map file (disappearing_sliver.map), you can actually -see these exact points embedded in the third plane defined on brush 0. - -I managed to print out the actual computed vertices of the sliver face before -and after this bug fix. Basically this is printed out after all the -ChopWindingInPlace() calls in the above stack trace: - - (66.984695 -1021.998657 0.000000) - (87.989571 -891.969116 -768.174316) - (133.998917 -1014.997314 0.000000) - -(If you want to print this out for yourself, use winding_logging.patch.) - -The same vertices after the bugfix have the following coordinates: - - (67.000229 -1021.998657 0.000000) - (88.000175 -891.999146 -767.997437) - (133.999146 -1014.998779 0.000000) - -As you can see, the vertices after the fix are substantially more accurate, -and all it took was an improvement to VectorNormalize(). - -The problem before the fix was the Z coordinate of the second point, namely --768.174316. There is a lot of "snap to nearest 1/8 unit" and "epsilon 0.1" -code used throughout q3map2. 0.174 is greater than the 0.1 epsilon, and that -is the problem. - - main() in main.c --> - BSPMain() in bsp.c --> - ProcessModels() in bsp.c --> - ProcessWorldModel() in bsp.c --> - ClipSidesIntoTree() in surface.c --> - ClipSideIntoTree_r() in surface.c --> - ClipWindingEpsilon() in polylib.c - -Now what ClipWindingEpsilon() does is, since -768.174316 reaches below the -plane z = -768 (and over the 0.1 epsilon), it clips the winding_t and creates -two points where there used to be only one. - - main() in main.c --> - BSPMain() in bsp.c --> - ProcessModels() in bsp.c --> - ProcessWorldModel() in bsp.c - FixTJunctions() in tjunction.c - FixBrokenSurface() in tjunction.c - -FixBrokenSurface() realizes that there are two points very close together -(in our case, since they were "snapped", the are coincident in fact). -Therefore it reports the surface to be broken. The drawable surface is -deleted as a result. - - -RELATED BUGS: -============= - -A lot of the math operations in the Radiant codebase cut corners like this -example demonstrates. There is a lot more code like this that can be -improved upon. In fact, it may make sense to use 64 bit floating points in -some important math operations (and then convert back to 32 bit for the return -values). Plans are to look at similar code and improve it. - -The following "issue" was discovered while doing research for this bug. -If FixBrokenSurface() sees two points very close together, it attempts to -partially fix the problem (the code is not complete) and then returns false, -which means that the surface is broken and should not be used. So in fact -it attempts to fix the problem partially but none of the fixes are used. -It seems that FixBrokenSurface() should be fixed to completely fix the case -where there are two close points, and should report the surface as fixed. -This might be a destabilizing change however, so if this is indeed fixed, it -may make sense to activate the fix only if a certain flag is set. - - -MORE NOTES: -=========== - -As stated above, the accuracy after revision 363 is: - - (67.000229 -1021.998657 0.000000) - (88.000175 -891.999146 -767.997437) - (133.999146 -1014.998779 0.000000) - -A further change was committed for a related problem in revision 377. After -this change: - - (66.99955750 -1022.00262451 0.00000000) - (87.99969482 -892.00170898 -768.00524902) - (133.99958801 -1015.00195312 0.00000000) - -The results look similar with respect to the amount of error present. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/maps/disappearing_sliver.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/maps/disappearing_sliver.map deleted file mode 100644 index 82528868..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/maps/disappearing_sliver.map +++ /dev/null @@ -1,73 +0,0 @@ -{ -"classname" "worldspawn" -{ -( -704 -1152 0 ) ( 4480 -1152 0 ) ( -704 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 67 -1022 0 ) ( 67 -4096 0 ) ( 88 -892 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 67 -1022 0 ) ( 88 -892 -768 ) ( 134 -1015 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 88 -892 -768 ) ( 88 -4096 -768 ) ( 134 -1015 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 134 -1015 0 ) ( 134 -4096 0 ) ( 67 -1022 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 584 -640 -768 ) ( 520 -640 -768 ) ( 520 -1160 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 528 -1160 320 ) ( 528 -640 320 ) ( 592 -640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 528 -1152 0 ) ( 592 -1152 0 ) ( 592 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 520 -1160 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 584 -640 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -640 0 ) ( 512 -1160 0 ) ( 512 -1160 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 512 -552 -768 ) ( -296 -552 -768 ) ( -296 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -296 -640 320 ) ( -296 -552 320 ) ( 512 -552 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -296 -640 320 ) ( 512 -640 320 ) ( 512 -640 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 512 -640 320 ) ( 512 -552 320 ) ( 512 -552 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 528 -632 320 ) ( -280 -632 320 ) ( -280 -632 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -536 320 ) ( -512 -624 320 ) ( -512 -624 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -512 -648 -768 ) ( -536 -648 -768 ) ( -536 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -536 -1152 320 ) ( -536 -648 320 ) ( -512 -648 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -536 -1152 320 ) ( -512 -1152 320 ) ( -512 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -1152 320 ) ( -512 -648 320 ) ( -512 -648 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -512 -640 320 ) ( -536 -640 320 ) ( -536 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -520 -648 320 ) ( -520 -1152 320 ) ( -520 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 512 -640 320 ) ( 24 -640 320 ) ( 24 -1152 320 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 48 -1152 328 ) ( 48 -640 328 ) ( 536 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 24 -1152 440 ) ( 512 -1152 440 ) ( 512 -1152 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -1152 440 ) ( 512 -640 440 ) ( 512 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -640 440 ) ( 24 -640 440 ) ( 24 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -640 464 ) ( -512 -1152 464 ) ( -512 -1152 352 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -328 -896 -776 ) ( -512 -896 -776 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -1152 -768 ) ( -512 -896 -768 ) ( -328 -896 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -512 -1152 -768 ) ( -328 -1152 -768 ) ( -328 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -896 -768 ) ( -512 -1152 -768 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -1152 -768 ) ( 512 -896 -768 ) ( 512 -896 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -368 -640 -824 ) ( -856 -640 -824 ) ( -856 -640 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -512 -1168 320 ) ( -512 -1584 320 ) ( -512 -1584 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 1152 -1152 320 ) ( 176 -1152 320 ) ( 176 -1152 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 512 -1576 320 ) ( 512 -1160 320 ) ( 512 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 208 -1160 320 ) ( 1184 -1160 320 ) ( 1184 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 176 -1568 320 ) ( 176 -1152 320 ) ( 1152 -1152 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -1152 -768 ) ( -520 -1152 -768 ) ( -520 -1192 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"light" "3000" -"origin" "0 -768 -480" -"classname" "light" -} -{ -"angle" "270" -"origin" "0 -712 -640" -"classname" "info_player_deathmatch" -} -{ -"classname" "light" -"origin" "0 -832 160" -"light" "3000" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/winding_logging.patch b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/winding_logging.patch deleted file mode 100644 index a1babe91..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver/winding_logging.patch +++ /dev/null @@ -1,105 +0,0 @@ -Index: tools/quake3/q3map2/brush.c -=================================================================== ---- tools/quake3/q3map2/brush.c (revision 391) -+++ tools/quake3/q3map2/brush.c (working copy) -@@ -421,10 +421,16 @@ - side_t *side; - plane_t *plane; - -- -+ static int brushord = -1; -+ brushord++; -+ -+ Sys_Printf("In CreateBrushWindings() for brush %i\n", brushord); -+ - /* walk the list of brush sides */ - for( i = 0; i < brush->numsides; i++ ) - { -+ Sys_Printf(" Handling side %i on the brush\n", i); -+ - /* get side and plane */ - side = &brush->sides[ i ]; - plane = &mapplanes[ side->planenum ]; -@@ -435,7 +441,13 @@ - #else - w = BaseWindingForPlane( plane->normal, plane->dist ); - #endif -- -+ -+ Sys_Printf(" Before clipping we have:\n"); -+ int z; -+ for (z = 0; z < w->numpoints; z++) { -+ Sys_Printf(" (%.8f %.8f %.8f)\n", w->p[z][0], w->p[z][1], w->p[z][2]); -+ } -+ - /* walk the list of brush sides */ - for( j = 0; j < brush->numsides && w != NULL; j++ ) - { -@@ -451,7 +463,20 @@ - #else - ChopWindingInPlace( &w, plane->normal, plane->dist, 0 ); // CLIP_EPSILON ); - #endif -- -+ -+ Sys_Printf(" After clipping w/ side %i we have:\n", j); -+ if (w) -+ { -+ for (z = 0; z < w->numpoints; z++) -+ { -+ Sys_Printf(" (%.8f %.8f %.8f)\n", w->p[z][0], w->p[z][1], w->p[z][2]); -+ } -+ } -+ else -+ { -+ Sys_Printf(" winding is NULL\n"); -+ } -+ - /* ydnar: fix broken windings that would generate trifans */ - #if EXPERIMENTAL_HIGH_PRECISION_MATH_Q3MAP2_FIXES - FixWindingAccu(w); -Index: tools/quake3/q3map2/map.c -=================================================================== ---- tools/quake3/q3map2/map.c (revision 391) -+++ tools/quake3/q3map2/map.c (working copy) -@@ -803,7 +803,11 @@ - char shader[ MAX_QPATH ]; - int flags; - -+ static int brushord = -1; -+ brushord++; - -+ Sys_Printf("In ParseRawBrush() for brush %i\n", brushord); -+ - /* initial setup */ - buildBrush->numsides = 0; - buildBrush->detail = qfalse; -@@ -812,9 +816,12 @@ - if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) - MatchToken( "{" ); - -+ int sideord = -1; -+ - /* parse sides */ - while( 1 ) - { -+ sideord++; - if( !GetToken( qtrue ) ) - break; - if( !strcmp( token, "}" ) ) -@@ -917,7 +924,16 @@ - } - - /* find the plane number */ -+ Sys_Printf(" Side %i:\n", sideord); -+ Sys_Printf(" (%f %f %f)\n", planePoints[0][0], planePoints[0][1], planePoints[0][2]); -+ Sys_Printf(" (%f %f %f)\n", planePoints[1][0], planePoints[1][1], planePoints[1][2]); -+ Sys_Printf(" (%f %f %f)\n", planePoints[2][0], planePoints[2][1], planePoints[2][2]); - planenum = MapPlaneFromPoints( planePoints ); -+ Sys_Printf(" normal: (%.10f %.10f %.10f)\n", -+ mapplanes[planenum].normal[0], -+ mapplanes[planenum].normal[1], -+ mapplanes[planenum].normal[2]); -+ Sys_Printf(" dist: %.10f\n", mapplanes[planenum].dist); - side->planenum = planenum; - - /* bp: get the texture mapping for this texturedef / plane combination */ diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver2/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver2/README.txt deleted file mode 100644 index ffa12be5..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver2/README.txt +++ /dev/null @@ -1,93 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The example map, maps/disappearing_sliver2.map, contains an example of this -bug. The triangle sliver surface in the middle of the room is not rendered -in the final BSP. - -To trigger the bug, compile the map; you don't need -vis or -light. Only --bsp (the first q3map2 stage) is necessary to trigger the bug. The only -entities in the map are a light and a info_player_deathmatch, so the map will -compile for any Q3 mod. - - -SOLUTION TO PROBLEM: -==================== - -It was discovered that BaseWindingForPlane() in polylib.c did some sloppy -mathematics with significant loss of precision. Those problems have been -addressed in commits to revisions 371 and 377. - - -POSSIBLE SIDE EFFECTS: -====================== - -Great care was taken to preserve the exact behavior of the original -BaseWindingForPlane() function except for the loss of precision. Therefore -no negative side effects should be seen. In fact performance may be -increased. - - -IN-DEPTH DISCUSSION: -==================== - -Turns out that the problem is very similar to the original disappearing_sliver -regression test. You should read that README.txt to familiarize yourself -with the situation. - -The thing we need to look at is side 0 of brush 0, if you applied -winding_logging.patch from disappearing_sliver regression test: - - In ParseRawBrush() for brush 0 - Side 0: - (6784.000000 16241.000000 -1722.000000) - (6144.000000 16083.000000 -1443.000000) - (6144.000000 16122.000000 -1424.000000) - -That is the exact plane defninition of our problem sliver, and in fact those -are also the correct points for the actual vertices of the triangle. - -Now the results of the winding for this surface after all the clipping takes -place: - - (6784.12500000 16241.02343750 -1722.06250000) - (6144.00000000 16082.99218750 -1443.00781250) - (6144.00000000 16122.00000000 -1424.00390625) - -As you can see, 6784.12500000 is more than epsilon distance (0.1) away from -the correct point. This is a big problem. - -After we apply the fix committed in revision 371, the result after clipping -is this: - - (6784.06250000 16241.01171875 -1722.03515625) - (6144.00000000 16082.99609375 -1443.00781250) - (6144.00000000 16122.00000000 -1424.00585938) - -As you can see, all points but one have an increase in accuracy. This is -still not accurate enough in my opinion, but is a step in the right direction. - -After the fix committed in revision 377, which is a further attempt to address -BaseWindingForPlane(), we get the following accuracy: - - (6784.00000000 16241.00000000 -1722.00000000) - (6144.00000000 16083.00000000 -1443.00000000) - (6144.00000000 16122.00000000 -1424.00000000) - -It's just a fluke for this particular case, but obviouly revision 377 looks -favorably upon this regression test, because there is zero percent error. - - -MORE NOTES: -=========== - -I attempted to improve upon revision 371 by streamlining the code in -BaseWindingForPlane() some more. Those attempts were committed as revision -375. After revision 375: - - (6784.09375000 16241.01757812 -1722.04687500) - (6144.00000000 16082.99414062 -1443.00390625) - (6144.00000000 16122.00000000 -1424.00097656) - -Revision 375 has since been reverted (undone) because of the loss in -accuracy. Revision 377 is a fix for those failed attempts. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver2/maps/disappearing_sliver2.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver2/maps/disappearing_sliver2.map deleted file mode 100644 index 53e18710..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver2/maps/disappearing_sliver2.map +++ /dev/null @@ -1,69 +0,0 @@ -{ -"message" "Icy Fantasy by Rambetter" -"classname" "worldspawn" -{ -( 6784 16241 -1722 ) ( 6144 16083 -1443 ) ( 6144 16122 -1424 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 6784 16241 -1722 ) ( 6784 16241 -2048 ) ( 6144 16083 -1443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 16083 -1443 ) ( 6144 16083 -2048 ) ( 6144 16122 -1424 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 16122 -1424 ) ( 6144 16122 -2048 ) ( 6784 16241 -1722 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 16122 -2048 ) ( 6144 16083 -2048 ) ( 6784 16241 -2048 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 6136 16424 168 ) ( 6136 15928 168 ) ( 6136 15928 -3544 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6112 16896 160 ) ( 6000 16896 160 ) ( 6000 16896 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 160 ) ( 6144 16432 160 ) ( 6144 16432 -3552 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6032 15936 160 ) ( 6144 15936 160 ) ( 6144 15936 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6128 15936 -896 ) ( 6128 16432 -896 ) ( 6240 16432 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6160 16432 -2048 ) ( 6048 16432 -2048 ) ( 6048 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6784 16672 -1296 ) ( 6784 16176 -1296 ) ( 6784 16176 -1776 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 16896 -1312 ) ( 6136 16896 -1312 ) ( 6136 16896 -1792 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6792 16160 -1296 ) ( 6792 16656 -1296 ) ( 6792 16656 -1776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 15936 -1280 ) ( 6144 15936 -1280 ) ( 6144 15936 -1760 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 16192 -896 ) ( 6136 16688 -896 ) ( 6144 16688 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16672 -2048 ) ( 6136 16672 -2048 ) ( 6136 16176 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6144 15936 -896 ) ( 6144 15880 -896 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15936 -896 ) ( 6144 15936 -896 ) ( 6144 15936 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6784 15880 -896 ) ( 6784 15936 -896 ) ( 6784 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15928 -896 ) ( 6784 15928 -896 ) ( 6784 15928 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15880 -896 ) ( 6144 15936 -896 ) ( 6784 15936 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15936 -2048 ) ( 6144 15936 -2048 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6144 16960 -896 ) ( 6144 16896 -896 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16904 -896 ) ( 6144 16904 -896 ) ( 6144 16904 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -896 ) ( 6784 16960 -896 ) ( 6784 16960 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -896 ) ( 6784 16896 -896 ) ( 6784 16896 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 16896 -896 ) ( 6144 16960 -896 ) ( 6784 16960 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16960 -2048 ) ( 6144 16960 -2048 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6144 16896 -784 ) ( 6144 16536 -784 ) ( 6144 16536 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -784 ) ( 6144 16896 -784 ) ( 6144 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16536 -784 ) ( 6784 16896 -784 ) ( 6784 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -744 ) ( 6784 15936 -744 ) ( 6784 15936 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16552 -888 ) ( 6144 16912 -888 ) ( 6784 16912 -888 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -896 ) ( 6144 16896 -896 ) ( 6144 16536 -896 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 6144 16544 -2048 ) ( 6144 15936 -2048 ) ( 6144 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -2048 ) ( 6144 16896 -2048 ) ( 6144 16896 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15936 -2048 ) ( 6784 16544 -2048 ) ( 6784 16544 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -2048 ) ( 6784 15936 -2048 ) ( 6784 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -2048 ) ( 6144 16544 -2048 ) ( 6784 16544 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6784 16584 -2056 ) ( 6144 16584 -2056 ) ( 6144 15976 -2056 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"classname" "info_player_deathmatch" -"origin" "6432 16168 -1472" -"angle" "180" -} -{ -"classname" "light" -"origin" "6440 16160 -1192" -"light" "1000" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/NOTES.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/NOTES.txt deleted file mode 100644 index 70bb752a..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/NOTES.txt +++ /dev/null @@ -1,72 +0,0 @@ -Random notes for Rambetter, don't expect to understand this: -============================================================ - -Brush 0 is the problem. - -Side 0 is the problem (under surf tri). -Side 1 is the +y 4-face. -Side 2 is the -x 4-face. -Side 3 is the -y 4-face. -side 4 is the +z tri. - -(6144, 16122) -> (6784, 16241) -x "climb" of side 1 is 6784 - 6144 = 640. -y "climb" of side 1 is 16241 - 16122 = 119. - -x/y "climb rate" of side 1 is 640 / 119 = 5.378151261. - -After clipping side 0 against side 1, we get -************ -**** (-262144, -33762.8125) -> (262144, 63722) -************ -The slope of that is (262144 + 262144) / (63722 + 33762.8125) = 5.378150571. - -(-262144, y) -> (6784, 16241) -So (6784 + 262144) / (16241 - y) = 640 / 119 -So y = 16241 - ((119 * (6784 + 262144)) / 640) = -33762.8 - -(6144, 16122) -> (262144, y) -So (262144 - 6144) / (y - 16122) = 640 / 119 -So y = 16122 + ((119 * (262144 - 6144)) / 640) = 63722 - -After clipping side 0 against side 1 should have -************ -**** (-262144, -33762.8) -> (262144, 63722) -************ - -Random notes for Rambetter, don't expect to understand this: -============================================================ - -Brush 0 is the problem. - -Side 0 is the problem (under surf tri). -Side 1 is the +y 4-face. -Side 2 is the -x 4-face. -Side 3 is the -y 4-face. -side 4 is the +z tri. - -(6144, 16122) -> (6784, 16241) -x "climb" of side 1 is 6784 - 6144 = 640. -y "climb" of side 1 is 16241 - 16122 = 119. - -x/y "climb rate" of side 1 is 640 / 119 = 5.378151261. - -After clipping side 0 against side 1, we get -************ -**** (-262144, -33762.8125) -> (262144, 63722) -************ -The slope of that is (262144 + 262144) / (63722 + 33762.8125) = 5.378150571. - -(-262144, y) -> (6784, 16241) -So (6784 + 262144) / (16241 - y) = 640 / 119 -So y = 16241 - ((119 * (6784 + 262144)) / 640) = -33762.8 - -(6144, 16122) -> (262144, y) -So (262144 - 6144) / (y - 16122) = 640 / 119 -So y = 16122 + ((119 * (262144 - 6144)) / 640) = 63722 - -After clipping side 0 against side 1 should have -************ -**** (-262144, -33762.8) -> (262144, 63722) -************ - diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/README.txt deleted file mode 100644 index 839bd692..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/README.txt +++ /dev/null @@ -1,49 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The example map, maps/disappearing_sliver3.map, contains an example of this -bug. The triangle sliver surface in the middle of the room is not rendered -in the final BSP. - -To trigger the bug, compile the map; you don't need -vis or -light. Only --bsp (the first q3map2 stage) is necessary to trigger the bug. The only -entities in the map are a light and a info_player_deathmatch, so the map will -compile for any Q3 mod. - - -SOLUTION TO PROBLEM: -==================== - -More work has been done to BaseWindingForPlane() to make it more accurate. -This function is in polylib.c. The changes to fix this regression test were -committed in revision 377; however, those changes are not "good enough". - - -IN-DEPTH DISCUSSION: -==================== - -This is the problem triangle: - - In ParseRawBrush() for brush 0 - Side 0: - (6144.000000 16122.000000 -2048.000000) - (6144.000000 16083.000000 -2048.000000) - (6784.000000 16241.000000 -2048.000000) - -Computed winding before fix: - - (6784.16406250 16241.04101562 -2048.00000000) - (6144.00000000 16122.00976562 -2048.00000000) - (6144.00000000 16083.00000000 -2048.00000000) - -Obviously the 6784.16406250 is beyond epsilon error. - -After revision 377: - - (6783.85937500 16240.96484375 -2048.00000000) - (6144.00000000 16121.99218750 -2048.00000000) - (6144.00000000 16083.00000000 -2048.00000000) - -Even though this fixes the regression test, the error in 6783.85937500 is -still greater than epsilon (but fortunately in the opposite direction). So -I don't consider this test case to be fixed quite yet. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/maps/disappearing_sliver3.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/maps/disappearing_sliver3.map deleted file mode 100644 index a56c649d..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/disappearing_sliver3/maps/disappearing_sliver3.map +++ /dev/null @@ -1,68 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 6144 16122 -2048 ) ( 6144 16083 -2048 ) ( 6784 16241 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 6144 16122 -1424 ) ( 6144 16122 -2048 ) ( 6784 16241 -1722 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 16083 -1443 ) ( 6144 16083 -2048 ) ( 6144 16122 -1424 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6784 16241 -1722 ) ( 6784 16241 -2048 ) ( 6144 16083 -1443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6784 16241 -1722 ) ( 6144 16083 -1443 ) ( 6144 16122 -1424 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 6160 16432 -2240 ) ( 6048 16432 -2240 ) ( 6048 15936 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6128 15936 -1376 ) ( 6128 16432 -1376 ) ( 6240 16432 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6032 15936 160 ) ( 6144 15936 160 ) ( 6144 15936 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -512 ) ( 6144 16432 -512 ) ( 6144 16432 -4224 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6112 16896 160 ) ( 6000 16896 160 ) ( 6000 16896 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 16424 168 ) ( 6136 15928 168 ) ( 6136 15928 -3544 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6144 16672 -2240 ) ( 6136 16672 -2240 ) ( 6136 16176 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 16192 -1376 ) ( 6136 16688 -1376 ) ( 6144 16688 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 15936 -1280 ) ( 6144 15936 -1280 ) ( 6144 15936 -1760 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6792 16160 -1296 ) ( 6792 16656 -1296 ) ( 6792 16656 -1776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -1312 ) ( 6136 16896 -1312 ) ( 6136 16896 -1792 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16672 -1968 ) ( 6784 16176 -1968 ) ( 6784 16176 -2448 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 6784 15936 -2240 ) ( 6144 15936 -2240 ) ( 6144 15880 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15880 -1376 ) ( 6144 15936 -1376 ) ( 6784 15936 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15928 -896 ) ( 6784 15928 -896 ) ( 6784 15928 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15880 -1568 ) ( 6784 15936 -1568 ) ( 6784 15936 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15936 -896 ) ( 6144 15936 -896 ) ( 6144 15936 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 15936 -1568 ) ( 6144 15880 -1568 ) ( 6144 15880 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6784 16960 -2240 ) ( 6144 16960 -2240 ) ( 6144 16896 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -1376 ) ( 6144 16960 -1376 ) ( 6784 16960 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -896 ) ( 6784 16896 -896 ) ( 6784 16896 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6784 16896 -1568 ) ( 6784 16960 -1568 ) ( 6784 16960 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16904 -896 ) ( 6144 16904 -896 ) ( 6144 16904 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16960 -1568 ) ( 6144 16896 -1568 ) ( 6144 16896 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6784 16896 -1376 ) ( 6144 16896 -1376 ) ( 6144 16536 -1376 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 16552 -1368 ) ( 6144 16912 -1368 ) ( 6784 16912 -1368 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -1224 ) ( 6784 15936 -1224 ) ( 6784 15936 -1336 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16536 -1264 ) ( 6784 16896 -1264 ) ( 6784 16896 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -1264 ) ( 6144 16896 -1264 ) ( 6144 16896 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -1264 ) ( 6144 16536 -1264 ) ( 6144 16536 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6784 16584 -2248 ) ( 6144 16584 -2248 ) ( 6144 15976 -2248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -2240 ) ( 6144 16544 -2240 ) ( 6784 16544 -2240 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 15936 -2240 ) ( 6784 15936 -2240 ) ( 6784 15936 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15936 -2240 ) ( 6784 16544 -2240 ) ( 6784 16544 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -2240 ) ( 6144 16896 -2240 ) ( 6144 16896 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16544 -2240 ) ( 6144 15936 -2240 ) ( 6144 15936 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"angle" "180" -"origin" "6432 16168 -2144" -"classname" "info_player_deathmatch" -} -{ -"light" "1000" -"origin" "6504 16160 -2152" -"classname" "light" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/duplicate_plane/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/duplicate_plane/README.txt deleted file mode 100644 index 8c2ef028..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/duplicate_plane/README.txt +++ /dev/null @@ -1,13 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The 4-sided brush in the middle of the room (brush 0) has a duplicate plane. -The last side (side 4) is a duplicate of the third side (side 2) with the -vertexes re-arranged. - -I wanted to make sure that ChopWindingInPlaceAccu() is doing the right thing -by setting a winding to NULL when all its points lie on the plane that the -winding is being chopped with. This seems to be the case. My concern was -that both windings for that duplicate plane will be NULL'ed out. - -Seems that some other code might be fixing duplicate planes. That's OK. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/duplicate_plane/maps/duplicate_plane.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/duplicate_plane/maps/duplicate_plane.map deleted file mode 100644 index d1913b42..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/duplicate_plane/maps/duplicate_plane.map +++ /dev/null @@ -1,67 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 136 128 64 ) ( -128 128 64 ) ( -128 -192 64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 136 128 384 ) ( -128 128 384 ) ( -128 128 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 128 -192 0 ) ( -128 128 0 ) ( 128 -192 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -128 128 256 ) ( 128 128 64 ) ( -128 -192 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 128 -192 384 ) ( 128 -192 0 ) ( -128 128 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 256 256 -8 ) ( -256 256 -8 ) ( -256 -256 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -256 0 ) ( -256 256 0 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -256 -256 8 ) ( 256 -256 8 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 8 ) ( 256 256 8 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 256 8 ) ( -256 256 8 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 8 ) ( -256 -256 8 ) ( -256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -256 256 0 ) ( -280 256 0 ) ( -280 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -280 -256 384 ) ( -280 256 384 ) ( -256 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -280 -256 384 ) ( -256 -256 384 ) ( -256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -256 384 ) ( -256 256 384 ) ( -256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -256 256 384 ) ( -280 256 384 ) ( -280 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -264 256 392 ) ( -264 -256 392 ) ( -264 -256 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 280 256 0 ) ( 256 256 0 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 384 ) ( 256 256 384 ) ( 280 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 384 ) ( 280 -256 384 ) ( 280 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 264 -256 384 ) ( 264 256 384 ) ( 264 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 280 256 384 ) ( 256 256 384 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 256 384 ) ( 256 -256 384 ) ( 256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 256 256 384 ) ( -256 256 384 ) ( -256 -256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -248 -256 392 ) ( -248 256 392 ) ( 264 256 392 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -256 424 ) ( 256 -256 424 ) ( 256 -256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 424 ) ( 256 256 424 ) ( 256 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 256 424 ) ( -256 256 424 ) ( -256 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 424 ) ( -256 -256 424 ) ( -256 -256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 256 296 0 ) ( -256 296 0 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 384 ) ( -256 296 384 ) ( 256 296 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 256 384 ) ( 256 256 384 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 256 256 384 ) ( 256 296 384 ) ( 256 296 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 264 392 ) ( -256 264 392 ) ( -256 264 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 296 384 ) ( -256 256 384 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 256 -256 0 ) ( -256 -256 0 ) ( -256 -296 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -296 384 ) ( -256 -256 384 ) ( 256 -256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -256 -264 392 ) ( 256 -264 392 ) ( 256 -264 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -296 384 ) ( 256 -256 384 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 256 -256 384 ) ( -256 -256 384 ) ( -256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -256 -256 384 ) ( -256 -296 384 ) ( -256 -296 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"origin" "-8 16 256" -"classname" "info_player_deathmatch" -} -{ -"light" "1000" -"origin" "-32 -40 256" -"classname" "light" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/README.txt deleted file mode 100644 index c3c2f88d..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/README.txt +++ /dev/null @@ -1,7 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -There are 3 model wedges in the map that are auto-clipped. The middle wedge -with the 45 degree slope is the problem. The slope face does not become solid; -therefore, there is a nonsolid "hole" on the wedge part. The other two wedges -are fine. 45 degrees seems to be a problem for model clipping. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/maps/model_clipping_45_degrees.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/maps/model_clipping_45_degrees.map deleted file mode 100644 index f358dba6..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/maps/model_clipping_45_degrees.map +++ /dev/null @@ -1,81 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 392 512 -8 ) ( 0 512 -8 ) ( 0 448 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 0 448 0 ) ( 0 512 0 ) ( 392 512 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 104 -192 0 ) ( 496 -192 0 ) ( 496 -192 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 448 0 ) ( 384 512 0 ) ( 384 512 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 400 640 0 ) ( 8 640 0 ) ( 8 640 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 528 0 ) ( -128 464 0 ) ( -128 464 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -128 688 320 ) ( -128 640 320 ) ( -128 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 648 320 ) ( -128 648 320 ) ( -128 648 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 640 320 ) ( 384 688 320 ) ( 384 688 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 640 320 ) ( 384 640 320 ) ( 384 640 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( -128 640 320 ) ( -128 688 320 ) ( 384 688 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 688 0 ) ( -128 688 0 ) ( -128 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -128 -184 328 ) ( -128 -240 328 ) ( -128 -240 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 -192 328 ) ( -128 -192 328 ) ( -128 -192 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 384 -240 328 ) ( 384 -184 328 ) ( 384 -184 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 -200 320 ) ( 384 -200 320 ) ( 384 -200 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 -240 320 ) ( -128 -184 320 ) ( 384 -184 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 -184 0 ) ( -128 -184 0 ) ( -128 -240 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -128 248 392 ) ( -128 -192 392 ) ( -128 -192 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 640 408 ) ( -128 640 408 ) ( -128 640 336 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 -192 392 ) ( 384 248 392 ) ( 384 248 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 -192 392 ) ( 384 -192 392 ) ( 384 -192 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 -176 328 ) ( -128 264 328 ) ( 384 264 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 248 320 ) ( -128 248 320 ) ( -128 -192 320 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 384 640 320 ) ( 384 -192 320 ) ( 384 -192 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( 432 640 320 ) ( 384 640 320 ) ( 384 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 392 -192 320 ) ( 392 640 320 ) ( 392 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 -192 320 ) ( 432 -192 320 ) ( 432 -192 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 384 -192 320 ) ( 384 640 320 ) ( 432 640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 432 640 0 ) ( 384 640 0 ) ( 384 -192 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -136 640 328 ) ( -136 -192 328 ) ( -136 -192 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 640 312 ) ( -224 640 312 ) ( -224 640 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 -192 312 ) ( -128 640 312 ) ( -128 640 -8 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 -( -224 -192 312 ) ( -128 -192 312 ) ( -128 -192 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -224 -192 320 ) ( -224 640 320 ) ( -128 640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 640 0 ) ( -224 640 0 ) ( -224 -192 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"model" "models/mapobjects/wedges/wedge_shallow.ase" -"origin" "0 -96 0" -"classname" "misc_model" -} -{ -"model" "models/mapobjects/wedges/wedge_45.ase" -"origin" "0 160 0" -"classname" "misc_model" -} -{ -"model" "models/mapobjects/wedges/wedge_steep.ase" -"origin" "0 416 0" -"classname" "misc_model" -} -{ -"classname" "light" -"origin" "192 384 160" -"light" "800" -} -{ -"light" "800" -"origin" "192 64 160" -"classname" "light" -} -{ -"classname" "info_player_deathmatch" -"origin" "256 208 128" -"angle" "225" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_45.ase b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_45.ase deleted file mode 100644 index dfb0d41d..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_45.ase +++ /dev/null @@ -1,368 +0,0 @@ -*3DSMAX_ASCIIEXPORT 200 -*COMMENT "Generated by Q3Map2 (ydnar) -convert -format ase" -*SCENE { - *SCENE_FILENAME "wedge_45.bsp" - *SCENE_FIRSTFRAME 0 - *SCENE_LASTFRAME 100 - *SCENE_FRAMESPEED 30 - *SCENE_TICKSPERFRAME 160 - *SCENE_BACKGROUND_STATIC 0.0000 0.0000 0.0000 - *SCENE_AMBIENT_STATIC 0.0000 0.0000 0.0000 -} -*MATERIAL_LIST { - *MATERIAL_COUNT 2 - *MATERIAL 0 { - *MATERIAL_NAME "textures/radiant_regression_tests/tile_model" - *MATERIAL_CLASS "Standard" - *MATERIAL_DIFFUSE 1.000000 1.000000 0.833333 - *MATERIAL_SHADING Phong - *MAP_DIFFUSE { - *MAP_NAME "textures/radiant_regression_tests/tile_model" - *MAP_CLASS "Bitmap" - *MAP_SUBNO 1 - *MAP_AMOUNT 1.0 - *MAP_TYPE Screen - *BITMAP "..\textures\radiant_regression_tests\tile_model.tga" - *BITMAP_FILTER Pyramidal - } - } - *MATERIAL 1 { - *MATERIAL_NAME "noshader" - *MATERIAL_CLASS "Standard" - *MATERIAL_DIFFUSE 1.000000 1.000000 1.000000 - *MATERIAL_SHADING Phong - *MAP_DIFFUSE { - *MAP_NAME "noshader" - *MAP_CLASS "Bitmap" - *MAP_SUBNO 1 - *MAP_AMOUNT 1.0 - *MAP_TYPE Screen - *BITMAP "..\noshader.tga" - *BITMAP_FILTER Pyramidal - } - } -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf0" - *NODE_TM { - *NODE_NAME "mat0model0surf0" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 128.000000 0.000000 0.000000 - *MESH_VERTEX 1 64.000000 0.000000 64.000000 - *MESH_VERTEX 2 128.000000 128.000000 0.000000 - *MESH_VERTEX 3 64.000000 128.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 - *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 0 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 1 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 2 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 3 0.707107 0.000000 0.707107 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 1.000000 -1.000000 1.000000 - *MESH_TVERT 1 -1.000000 -1.000000 1.000000 - *MESH_TVERT 2 1.000000 3.000000 1.000000 - *MESH_TVERT 3 -1.000000 3.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf1" - *NODE_TM { - *NODE_NAME "mat0model0surf1" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 128.000000 64.000000 - *MESH_VERTEX 1 0.000000 128.000000 0.000000 - *MESH_VERTEX 2 64.000000 128.000000 64.000000 - *MESH_VERTEX 3 128.000000 128.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 - *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 0 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 1 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 2 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 3 0.000000 1.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 2.000000 1.000000 - *MESH_TVERT 1 -2.000000 0.000000 1.000000 - *MESH_TVERT 2 0.000000 2.000000 1.000000 - *MESH_TVERT 3 2.000000 0.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf2" - *NODE_TM { - *NODE_NAME "mat0model0surf2" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 64.000000 0.000000 64.000000 - *MESH_VERTEX 1 0.000000 0.000000 64.000000 - *MESH_VERTEX 2 64.000000 128.000000 64.000000 - *MESH_VERTEX 3 0.000000 128.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 - *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 0 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 1 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 2 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 3 0.000000 0.000000 1.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 1.000000 -1.000000 1.000000 - *MESH_TVERT 1 -1.000000 -1.000000 1.000000 - *MESH_TVERT 2 1.000000 3.000000 1.000000 - *MESH_TVERT 3 -1.000000 3.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf3" - *NODE_TM { - *NODE_NAME "mat0model0surf3" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 0.000000 64.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 0.000000 128.000000 64.000000 - *MESH_VERTEX 3 0.000000 128.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 - *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 0 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 1 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 2 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 3 -1.000000 0.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 2.000000 1.000000 - *MESH_TVERT 1 -2.000000 0.000000 1.000000 - *MESH_TVERT 2 2.000000 2.000000 1.000000 - *MESH_TVERT 3 2.000000 0.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf4" - *NODE_TM { - *NODE_NAME "mat0model0surf4" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 128.000000 0.000000 0.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 64.000000 0.000000 64.000000 - *MESH_VERTEX 3 0.000000 0.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 - *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 0 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 1 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 2 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 3 0.000000 -1.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 2.000000 0.000000 1.000000 - *MESH_TVERT 1 -2.000000 0.000000 1.000000 - *MESH_TVERT 2 0.000000 2.000000 1.000000 - *MESH_TVERT 3 -2.000000 2.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf5" - *NODE_TM { - *NODE_NAME "mat0model0surf5" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 128.000000 0.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 128.000000 128.000000 0.000000 - *MESH_VERTEX 3 128.000000 0.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 - *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 - *MESH_VERTEXNORMAL 0 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 1 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 2 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 3 0.000000 0.000000 -1.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 3.000000 1.000000 - *MESH_TVERT 1 -2.000000 -1.000000 1.000000 - *MESH_TVERT 2 2.000000 3.000000 1.000000 - *MESH_TVERT 3 2.000000 -1.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_shallow.ase b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_shallow.ase deleted file mode 100644 index 4e23fd49..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_shallow.ase +++ /dev/null @@ -1,368 +0,0 @@ -*3DSMAX_ASCIIEXPORT 200 -*COMMENT "Generated by Q3Map2 (ydnar) -convert -format ase" -*SCENE { - *SCENE_FILENAME "wedge_shallow.bsp" - *SCENE_FIRSTFRAME 0 - *SCENE_LASTFRAME 100 - *SCENE_FRAMESPEED 30 - *SCENE_TICKSPERFRAME 160 - *SCENE_BACKGROUND_STATIC 0.0000 0.0000 0.0000 - *SCENE_AMBIENT_STATIC 0.0000 0.0000 0.0000 -} -*MATERIAL_LIST { - *MATERIAL_COUNT 2 - *MATERIAL 0 { - *MATERIAL_NAME "textures/radiant_regression_tests/tile_model" - *MATERIAL_CLASS "Standard" - *MATERIAL_DIFFUSE 1.000000 1.000000 0.833333 - *MATERIAL_SHADING Phong - *MAP_DIFFUSE { - *MAP_NAME "textures/radiant_regression_tests/tile_model" - *MAP_CLASS "Bitmap" - *MAP_SUBNO 1 - *MAP_AMOUNT 1.0 - *MAP_TYPE Screen - *BITMAP "..\textures\radiant_regression_tests\tile_model.tga" - *BITMAP_FILTER Pyramidal - } - } - *MATERIAL 1 { - *MATERIAL_NAME "noshader" - *MATERIAL_CLASS "Standard" - *MATERIAL_DIFFUSE 1.000000 1.000000 1.000000 - *MATERIAL_SHADING Phong - *MAP_DIFFUSE { - *MAP_NAME "noshader" - *MAP_CLASS "Bitmap" - *MAP_SUBNO 1 - *MAP_AMOUNT 1.0 - *MAP_TYPE Screen - *BITMAP "..\noshader.tga" - *BITMAP_FILTER Pyramidal - } - } -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf0" - *NODE_TM { - *NODE_NAME "mat0model0surf0" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 160.000000 0.000000 0.000000 - *MESH_VERTEX 1 64.000000 0.000000 64.000000 - *MESH_VERTEX 2 160.000000 128.000000 0.000000 - *MESH_VERTEX 3 64.000000 128.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 - *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 0 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 1 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 2 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 3 0.554700 0.000000 0.832050 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 2.000000 -1.000000 1.000000 - *MESH_TVERT 1 -1.000000 -1.000000 1.000000 - *MESH_TVERT 2 2.000000 3.000000 1.000000 - *MESH_TVERT 3 -1.000000 3.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf1" - *NODE_TM { - *NODE_NAME "mat0model0surf1" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 128.000000 64.000000 - *MESH_VERTEX 1 0.000000 128.000000 0.000000 - *MESH_VERTEX 2 64.000000 128.000000 64.000000 - *MESH_VERTEX 3 160.000000 128.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 - *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 0 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 1 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 2 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 3 0.000000 1.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 2.000000 1.000000 - *MESH_TVERT 1 -2.000000 0.000000 1.000000 - *MESH_TVERT 2 0.000000 2.000000 1.000000 - *MESH_TVERT 3 3.000000 0.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf2" - *NODE_TM { - *NODE_NAME "mat0model0surf2" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 64.000000 0.000000 64.000000 - *MESH_VERTEX 1 0.000000 0.000000 64.000000 - *MESH_VERTEX 2 64.000000 128.000000 64.000000 - *MESH_VERTEX 3 0.000000 128.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 - *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 0 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 1 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 2 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 3 0.000000 0.000000 1.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 1.000000 -1.000000 1.000000 - *MESH_TVERT 1 -1.000000 -1.000000 1.000000 - *MESH_TVERT 2 1.000000 3.000000 1.000000 - *MESH_TVERT 3 -1.000000 3.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf3" - *NODE_TM { - *NODE_NAME "mat0model0surf3" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 0.000000 64.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 0.000000 128.000000 64.000000 - *MESH_VERTEX 3 0.000000 128.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 - *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 0 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 1 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 2 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 3 -1.000000 0.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 2.000000 1.000000 - *MESH_TVERT 1 -2.000000 0.000000 1.000000 - *MESH_TVERT 2 2.000000 2.000000 1.000000 - *MESH_TVERT 3 2.000000 0.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf4" - *NODE_TM { - *NODE_NAME "mat0model0surf4" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 160.000000 0.000000 0.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 64.000000 0.000000 64.000000 - *MESH_VERTEX 3 0.000000 0.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 - *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 0 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 1 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 2 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 3 0.000000 -1.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 3.000000 0.000000 1.000000 - *MESH_TVERT 1 -2.000000 0.000000 1.000000 - *MESH_TVERT 2 0.000000 2.000000 1.000000 - *MESH_TVERT 3 -2.000000 2.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf5" - *NODE_TM { - *NODE_NAME "mat0model0surf5" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 128.000000 0.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 160.000000 128.000000 0.000000 - *MESH_VERTEX 3 160.000000 0.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 - *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 - *MESH_VERTEXNORMAL 0 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 1 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 2 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 3 0.000000 0.000000 -1.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 3.000000 1.000000 - *MESH_TVERT 1 -2.000000 -1.000000 1.000000 - *MESH_TVERT 2 3.000000 3.000000 1.000000 - *MESH_TVERT 3 3.000000 -1.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_steep.ase b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_steep.ase deleted file mode 100644 index 0e8727e0..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_steep.ase +++ /dev/null @@ -1,368 +0,0 @@ -*3DSMAX_ASCIIEXPORT 200 -*COMMENT "Generated by Q3Map2 (ydnar) -convert -format ase" -*SCENE { - *SCENE_FILENAME "wedge_steep.bsp" - *SCENE_FIRSTFRAME 0 - *SCENE_LASTFRAME 100 - *SCENE_FRAMESPEED 30 - *SCENE_TICKSPERFRAME 160 - *SCENE_BACKGROUND_STATIC 0.0000 0.0000 0.0000 - *SCENE_AMBIENT_STATIC 0.0000 0.0000 0.0000 -} -*MATERIAL_LIST { - *MATERIAL_COUNT 2 - *MATERIAL 0 { - *MATERIAL_NAME "textures/radiant_regression_tests/tile_model" - *MATERIAL_CLASS "Standard" - *MATERIAL_DIFFUSE 1.000000 1.000000 0.833333 - *MATERIAL_SHADING Phong - *MAP_DIFFUSE { - *MAP_NAME "textures/radiant_regression_tests/tile_model" - *MAP_CLASS "Bitmap" - *MAP_SUBNO 1 - *MAP_AMOUNT 1.0 - *MAP_TYPE Screen - *BITMAP "..\textures\radiant_regression_tests\tile_model.tga" - *BITMAP_FILTER Pyramidal - } - } - *MATERIAL 1 { - *MATERIAL_NAME "noshader" - *MATERIAL_CLASS "Standard" - *MATERIAL_DIFFUSE 1.000000 1.000000 1.000000 - *MATERIAL_SHADING Phong - *MAP_DIFFUSE { - *MAP_NAME "noshader" - *MAP_CLASS "Bitmap" - *MAP_SUBNO 1 - *MAP_AMOUNT 1.0 - *MAP_TYPE Screen - *BITMAP "..\noshader.tga" - *BITMAP_FILTER Pyramidal - } - } -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf0" - *NODE_TM { - *NODE_NAME "mat0model0surf0" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 112.000000 0.000000 0.000000 - *MESH_VERTEX 1 64.000000 0.000000 64.000000 - *MESH_VERTEX 2 112.000000 128.000000 0.000000 - *MESH_VERTEX 3 64.000000 128.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 - *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 0 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 1 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 2 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 3 0.800000 0.000000 0.600000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 0.000000 1.000000 - *MESH_TVERT 1 -2.000000 2.000000 1.000000 - *MESH_TVERT 2 2.000000 0.000000 1.000000 - *MESH_TVERT 3 2.000000 2.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf1" - *NODE_TM { - *NODE_NAME "mat0model0surf1" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 128.000000 64.000000 - *MESH_VERTEX 1 0.000000 128.000000 0.000000 - *MESH_VERTEX 2 64.000000 128.000000 64.000000 - *MESH_VERTEX 3 112.000000 128.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 - *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 0 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 1 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 2 0.000000 1.000000 0.000000 - *MESH_VERTEXNORMAL 3 0.000000 1.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -1.000000 2.000000 1.000000 - *MESH_TVERT 1 -1.000000 0.000000 1.000000 - *MESH_TVERT 2 1.000000 2.000000 1.000000 - *MESH_TVERT 3 2.500000 0.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf2" - *NODE_TM { - *NODE_NAME "mat0model0surf2" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 64.000000 0.000000 64.000000 - *MESH_VERTEX 1 0.000000 0.000000 64.000000 - *MESH_VERTEX 2 64.000000 128.000000 64.000000 - *MESH_VERTEX 3 0.000000 128.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 - *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 0 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 1 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 2 0.000000 0.000000 1.000000 - *MESH_VERTEXNORMAL 3 0.000000 0.000000 1.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 1.000000 -1.000000 1.000000 - *MESH_TVERT 1 -1.000000 -1.000000 1.000000 - *MESH_TVERT 2 1.000000 3.000000 1.000000 - *MESH_TVERT 3 -1.000000 3.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf3" - *NODE_TM { - *NODE_NAME "mat0model0surf3" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 0.000000 64.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 0.000000 128.000000 64.000000 - *MESH_VERTEX 3 0.000000 128.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 - *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 0 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 1 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 2 -1.000000 0.000000 0.000000 - *MESH_VERTEXNORMAL 3 -1.000000 0.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -2.000000 2.000000 1.000000 - *MESH_TVERT 1 -2.000000 0.000000 1.000000 - *MESH_TVERT 2 2.000000 2.000000 1.000000 - *MESH_TVERT 3 2.000000 0.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf4" - *NODE_TM { - *NODE_NAME "mat0model0surf4" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 112.000000 0.000000 0.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 64.000000 0.000000 64.000000 - *MESH_VERTEX 3 0.000000 0.000000 64.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 - *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 0 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 1 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 2 0.000000 -1.000000 0.000000 - *MESH_VERTEXNORMAL 3 0.000000 -1.000000 0.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 2.500000 0.000000 1.000000 - *MESH_TVERT 1 -1.000000 0.000000 1.000000 - *MESH_TVERT 2 1.000000 2.000000 1.000000 - *MESH_TVERT 3 -1.000000 2.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} -*GEOMOBJECT { - *NODE_NAME "mat0model0surf5" - *NODE_TM { - *NODE_NAME "mat0model0surf5" - *INHERIT_POS 0 0 0 - *INHERIT_ROT 0 0 0 - *INHERIT_SCL 0 0 0 - *TM_ROW0 1.0 0 0 - *TM_ROW1 0 1.0 0 - *TM_ROW2 0 0 1.0 - *TM_ROW3 0 0 0 - *TM_POS 0.000000 0.000000 0.000000 - } - *MESH { - *TIMEVALUE 0 - *MESH_NUMVERTEX 4 - *MESH_NUMFACES 2 - *COMMENT "SURFACETYPE MST_PLANAR" - *MESH_VERTEX_LIST { - *MESH_VERTEX 0 0.000000 128.000000 0.000000 - *MESH_VERTEX 1 0.000000 0.000000 0.000000 - *MESH_VERTEX 2 112.000000 128.000000 0.000000 - *MESH_VERTEX 3 112.000000 0.000000 0.000000 - } - *MESH_NORMALS { - *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 - *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 - *MESH_VERTEXNORMAL 0 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 1 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 2 0.000000 0.000000 -1.000000 - *MESH_VERTEXNORMAL 3 0.000000 0.000000 -1.000000 - } - *MESH_FACE_LIST { - *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 - } - *MESH_NUMTVERTEX 4 - *MESH_TVERTLIST { - *MESH_TVERT 0 -1.000000 3.000000 1.000000 - *MESH_TVERT 1 -1.000000 -1.000000 1.000000 - *MESH_TVERT 2 2.500000 3.000000 1.000000 - *MESH_TVERT 3 2.500000 -1.000000 1.000000 - } - *MESH_NUMTVFACES 2 - *MESH_TFACELIST { - *MESH_TFACE 0 0 2 1 - *MESH_TFACE 1 2 3 1 - } - } - *PROP_MOTIONBLUR 0 - *PROP_CASTSHADOW 1 - *PROP_RECVSHADOW 1 - *MATERIAL_REF 0 -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/scripts/radiant_regression_tests.shader b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/scripts/radiant_regression_tests.shader deleted file mode 100644 index a2c31ed6..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/scripts/radiant_regression_tests.shader +++ /dev/null @@ -1,12 +0,0 @@ -textures/radiant_regression_tests/tile_model -{ - q3map_clipModel - q3map_forceMeta - { - map $lightmap - } - { - map textures/radiant_regression_tests/tile_model.tga - blendFunc filter - } -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/piercing_triangle/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/piercing_triangle/README.txt deleted file mode 100644 index b09e2c31..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/piercing_triangle/README.txt +++ /dev/null @@ -1,14 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -In the disappearing_triangle regression test I outlined a potential problem -in the tjunction.c code, having to do with 2 points being too close together -on a winding, and that winding becoming invalid (drawsurf disappearing). - -This example map is the same as disappearing_triangle.map, except that the -floor is raised by 1 unit. Therefore the floor intersects the sliver triangle. -The resulting chopped sliver has a very short edge that is "degenerate" and -causes that draw surf to go away due to problems in the tjunction.c code. - -This is speculation at this point. I will provide more info after the bug has -been fixed. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/piercing_triangle/maps/piercing_triangle.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/piercing_triangle/maps/piercing_triangle.map deleted file mode 100644 index 8dc3552f..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/piercing_triangle/maps/piercing_triangle.map +++ /dev/null @@ -1,73 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 134 -1015 0 ) ( 134 -4096 0 ) ( 67 -1022 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 88 -892 -768 ) ( 88 -4096 -768 ) ( 134 -1015 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 67 -1022 0 ) ( 88 -892 -768 ) ( 134 -1015 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -( 67 -1022 0 ) ( 67 -4096 0 ) ( 88 -892 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( -704 -1152 0 ) ( 4480 -1152 0 ) ( -704 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -} -{ -( 512 -640 0 ) ( 512 -1160 0 ) ( 512 -1160 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 584 -640 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 520 -1160 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 528 -1152 0 ) ( 592 -1152 0 ) ( 592 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 528 -1160 320 ) ( 528 -640 320 ) ( 592 -640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 583 -640 -768 ) ( 519 -640 -768 ) ( 519 -1160 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -512 -536 320 ) ( -512 -624 320 ) ( -512 -624 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 528 -632 320 ) ( -280 -632 320 ) ( -280 -632 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -640 320 ) ( 512 -552 320 ) ( 512 -552 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -296 -640 320 ) ( 512 -640 320 ) ( 512 -640 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -296 -640 320 ) ( -296 -552 320 ) ( 512 -552 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 511 -552 -768 ) ( -297 -552 -768 ) ( -297 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -520 -648 320 ) ( -520 -1152 320 ) ( -520 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -640 320 ) ( -536 -640 320 ) ( -536 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -1152 320 ) ( -512 -648 320 ) ( -512 -648 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -536 -1152 320 ) ( -512 -1152 320 ) ( -512 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -536 -1152 320 ) ( -536 -648 320 ) ( -512 -648 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -648 -768 ) ( -536 -648 -768 ) ( -536 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -512 -640 464 ) ( -512 -1152 464 ) ( -512 -1152 352 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -640 440 ) ( 24 -640 440 ) ( 24 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -1152 440 ) ( 512 -640 440 ) ( 512 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 24 -1152 440 ) ( 512 -1152 440 ) ( 512 -1152 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 48 -1152 328 ) ( 48 -640 328 ) ( 536 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -640 320 ) ( 24 -640 320 ) ( 24 -1152 320 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -368 -640 -824 ) ( -856 -640 -824 ) ( -856 -640 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -1152 -768 ) ( 512 -896 -768 ) ( 512 -896 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -896 -768 ) ( -512 -1152 -768 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -1152 -768 ) ( -328 -1152 -768 ) ( -328 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -511 -1152 -767 ) ( -511 -896 -767 ) ( -327 -896 -767 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -328 -896 -776 ) ( -512 -896 -776 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -256 -1152 -768 ) ( -520 -1152 -768 ) ( -520 -1192 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 176 -1568 320 ) ( 176 -1152 320 ) ( 1152 -1152 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 208 -1160 320 ) ( 1184 -1160 320 ) ( 1184 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -1576 320 ) ( 512 -1160 320 ) ( 512 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 1152 -1152 320 ) ( 176 -1152 320 ) ( 176 -1152 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -512 -1168 320 ) ( -512 -1584 320 ) ( -512 -1584 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"classname" "light" -"origin" "0 -768 -480" -"light" "3000" -} -{ -"classname" "info_player_deathmatch" -"origin" "0 -712 -640" -"angle" "270" -} -{ -"light" "3000" -"origin" "0 -832 160" -"classname" "light" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/plane_aliasing/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/plane_aliasing/README.txt deleted file mode 100644 index c76d574f..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/plane_aliasing/README.txt +++ /dev/null @@ -1,129 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -This example map demonstrates what a relatively large value for plane distance -epsilon can do as far as destroying draw surfaces. The plane distance -epsilon was 0.01 at the time of this writing. This means that two planes -with the same normal and a distance 0.00999 apart are considered to be the -same plane. - -The recommended value of plane distance epsilon is more along the lines of -0.001; however, we can't currently change this epsilon to that value due to -lack of resolution in 32 bit floating point integers in the 2^16 number range. -The smallest epsilon in 32 bit float land that can be added to 2^16 that -results in a value greater than 2^16 is approximately 0.007, which is already -practically the current default plane distance epsilon (0.01). - -Brush 0 in the example map is a 6-sided brush with red top face. The red top -face is defined such in the .map file: - - ( -127 256 513 ) ( -127 384 513 ) ( 1 384 512 ) - -During the -bsp stage, - - In ParseRawBrush() for brush 0 - Side 4: - (-127.000000 256.000000 513.000000) - (-127.000000 384.000000 513.000000) - (1.000000 384.000000 512.000000) - normal: (0.0078122616 0.0000000000 0.9999694824) - dist: 511.9921875000 - -Now brush 1, the 4-sided brush with the red top face, has the following -defined as the red top face: - - ( -128 0 513 ) ( -128 128 513 ) ( 0 128 512 ) - -It's almost the same plane, only off by a distance of about 0.01. - -During compiling: - - In ParseRawBrush() for brush 1 - Side 1: - (-128.000000 0.000000 513.000000) - (-128.000000 128.000000 513.000000) - (0.000000 128.000000 512.000000) - normal: (0.0078122616 0.0000000000 0.9999694824) - dist: 511.9921875000 - -Note that the normal and dist are identical to the plane above, even though -the two are different. This leads to multiplying errors later on, when this -side is intersected with the bottom green face. In particular, the blue face -disappears from the map. The blue face: - - In CreateBrushWindings() for brush 1 - Handling side 2 on the brush - Before clipping we have: - (-262144.00000000 0.00000000 262144.00000000) - (262144.00000000 0.00000000 262144.00000000) - (262144.00000000 -0.00000000 -262144.00000000) - (-262144.00000000 0.00000000 -262144.00000000) - After clipping w/ side 0 we have: - (-262144.00000000 0.00000000 262144.00000000) - (262144.00000000 0.00000000 262144.00000000) - (262144.00000000 0.00000000 -19977.00073172) - (-262144.00000000 0.00000000 20983.00073758) - After clipping w/ side 1 we have: - (262144.00000000 0.00000000 -1535.99218726) - (262144.00000000 0.00000000 -19977.00073172) - (-128.11106773 0.00000000 513.00868046) - After clipping w/ side 3 we have: - (0.00000000 0.00000000 503.00000293) - (-128.11106773 0.00000000 513.00868046) - (-0.00000000 0.00000000 512.00781274) - -We see the error is greater than 0.1 in the X value -128.11106773. This -causes the draw surface to be discarded in processing later on. We must -not allow such a great error. An error greater than or equal to 0.1 is -considered to be very bad. - -This disappearing blue triangle can be fixed simply by deleting brush 0, -the 6-sided brush that causes the bad plane alias. I would suggest deleting -this brush by editing the .map file manually (and then renumbering the brushes -manually). - -After deleting this brush: - - In ParseRawBrush() for brush 0 - Side 1: - (-128.000000 0.000000 513.000000) - (-128.000000 128.000000 513.000000) - (0.000000 128.000000 512.000000) - normal: (0.0078122616 0.0000000000 0.9999694824) - dist: 511.9843750000 - - In CreateBrushWindings() for brush 0 - Handling side 1 on the brush - Before clipping we have: - (262132.00000000 262136.00000000 -1535.90625143) - (262132.00000000 -262136.00000000 -1535.90625143) - (-262124.00048828 -262136.00000000 2559.84375238) - (-262124.00048828 262136.00000000 2559.84375238) - After clipping w/ side 0 we have: - (262132.00000000 262136.00000000 -1535.90625143) - (262132.00000000 -262136.00000000 -1535.90625143) - (-127.99993289 -262136.00000000 512.99999805) - (-127.99993289 262136.00000000 512.99999805) - After clipping w/ side 2 we have: - (262132.00000000 262136.00000000 -1535.90625143) - (262132.00000000 -0.00000000 -1535.90625143) - (-127.99993289 -0.00000000 512.99999805) - (-127.99993289 262136.00000000 512.99999805) - After clipping w/ side 3 we have: - (0.00000000 0.00000000 511.99999857) - (-127.99993289 -0.00000000 512.99999805) - (-127.99993289 127.99993289 512.99999805) - -Note that we're way more accurate now, and we're nowhere near to approaching -the 0.1 error. All it took was the deletion of a seemintly unrelated brush. - - -SOLUTION TO PROBLEM: -==================== - -The suggested fix is to increase the resolution of plane distance from 32 bit -float to 64 bit float for the relevant brush processing operations. After that -is done, decrease the default plane distance epsilon from 0.01 to 0.001. Note -that even though plane distance epsilon can be specified on the command-line, -it will do no good (even if set to 0) if the plane distance is close to -2^16. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/plane_aliasing/maps/plane_aliasing.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/plane_aliasing/maps/plane_aliasing.map deleted file mode 100644 index 070d7ba9..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/plane_aliasing/maps/plane_aliasing.map +++ /dev/null @@ -1,74 +0,0 @@ -{ -"classname" "worldspawn" -{ -( -127 384 513 ) ( -127 256 513 ) ( -127 256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 1 384 512 ) ( -127 384 512 ) ( -127 384 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 1 256 512 ) ( 1 384 512 ) ( 1 384 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -127 256 512 ) ( 1 256 512 ) ( 1 256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -127 256 513 ) ( -127 384 513 ) ( 1 384 512 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( 1 384 384 ) ( -127 384 384 ) ( -127 256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 0 128 503 ) ( -128 128 513 ) ( 0 0 503 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -128 0 513 ) ( -128 128 513 ) ( 0 128 512 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -( -128 0 512 ) ( 0 0 512 ) ( 0 0 384 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 -( -128 128 503 ) ( 0 0 503 ) ( -128 128 513 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -128 472 8 ) ( -128 320 8 ) ( -128 320 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -232 512 8 ) ( -416 512 8 ) ( -416 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -304 8 ) ( 512 -152 8 ) ( 512 -152 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 48 -512 8 ) ( 232 -512 8 ) ( 232 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -432 232 0 ) ( -432 384 0 ) ( -248 384 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -256 384 -8 ) ( -440 384 -8 ) ( -440 232 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -136 512 1040 ) ( -136 -512 1040 ) ( -136 -512 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 512 1032 ) ( -520 512 1032 ) ( -520 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -128 -512 1032 ) ( -128 512 1032 ) ( -128 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -520 -512 1032 ) ( -512 -512 1032 ) ( -512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -520 -512 1024 ) ( -520 512 1024 ) ( -512 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 512 0 ) ( -520 512 0 ) ( -520 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 512 512 1024 ) ( 512 -512 1024 ) ( 512 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 592 512 1024 ) ( 512 512 1024 ) ( 512 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 520 -512 1000 ) ( 520 512 1000 ) ( 520 512 -24 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 1024 ) ( 592 -512 1024 ) ( 592 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 1024 ) ( 512 512 1024 ) ( 592 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 592 512 0 ) ( 512 512 0 ) ( 512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -128 512 1200 ) ( -128 -512 1200 ) ( -128 -512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 512 1200 ) ( -512 512 1200 ) ( -512 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 1200 ) ( 512 512 1200 ) ( 512 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -512 1200 ) ( 512 -512 1200 ) ( 512 -512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -456 -512 1032 ) ( -456 512 1032 ) ( 568 512 1032 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 512 1024 ) ( -512 512 1024 ) ( -512 -512 1024 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -128 712 1024 ) ( -128 512 1024 ) ( -128 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 520 1040 ) ( -512 520 1040 ) ( -512 520 16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 512 1024 ) ( 512 712 1024 ) ( 512 712 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 512 1024 ) ( 512 512 1024 ) ( 512 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -512 512 1024 ) ( -512 712 1024 ) ( 512 712 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 712 0 ) ( -512 712 0 ) ( -512 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -128 -512 1024 ) ( -128 -624 1024 ) ( -128 -624 56 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -512 1024 ) ( -512 -512 1024 ) ( -512 -512 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 512 -624 1024 ) ( 512 -512 1024 ) ( 512 -512 56 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -520 1048 ) ( 512 -520 1048 ) ( 512 -520 80 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -512 -624 1024 ) ( -512 -512 1024 ) ( 512 -512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 512 -504 0 ) ( -512 -504 0 ) ( -512 -616 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"classname" "light" -"origin" "192 64 640" -"light" "3000" -} -{ -"classname" "info_player_deathmatch" -"origin" "-64 64 640" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/segmentation_fault/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/segmentation_fault/README.txt deleted file mode 100644 index 05f30d2f..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/segmentation_fault/README.txt +++ /dev/null @@ -1,27 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The example map, maps/segmentation_fault.map, contains an example of this -bug. q3map2 might segfault while compiling this map. This sort of thing -might happen in certain intermediate versions of q3map2 while work is being -done on fixing the math accuracy. The bug may not have happened in older -version of q3map2, before the math accuracy issues were addressed. - -To trigger the bug, compile the map; you don't need -vis or -light. Only --bsp (the first q3map2 stage) is necessary to trigger the bug. The only -entities in the map are a light and a info_player_deathmatch, so the map will -compile for any Q3 mod. - -Here is a description of the problem brush (brush #0): - - side 0: -z face - side 1: +z face - side 2: -y face - side 3: +x face - side 4: +y face - side 5: -x face - side 6: problem side "accidentally showed up" :-) - -Side 6 is actually a superfluous plane and will be NULL'ed out in the code. -If the code does not handle a NULL'ed out winding correctly, it will -segfault. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/segmentation_fault/maps/segmentation_fault.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/segmentation_fault/maps/segmentation_fault.map deleted file mode 100644 index 610e7850..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/segmentation_fault/maps/segmentation_fault.map +++ /dev/null @@ -1,69 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 10296 17600 -592 ) ( 10240 17600 -592 ) ( 10240 17472 -592 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 -( 10280 17472 -576 ) ( 10280 17600 -576 ) ( 10336 17600 -576 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 -( 10280 17472 -576 ) ( 10336 17472 -576 ) ( 10336 17472 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 -( 10367 17472 -576 ) ( 10367 17600 -576 ) ( 10367 17600 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 -( 10328 17727 -576 ) ( 10272 17727 -576 ) ( 10272 17727 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 -( 10240 17608 -576 ) ( 10240 17480 -576 ) ( 10240 17480 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 -( 10240 17727 -576 ) ( 10240 17726 -621 ) ( 10335 17727 -576 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 -} -{ -( 10504 17800 -768 ) ( 10112 17800 -768 ) ( 10112 17792 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17792 -320 ) ( 10112 17800 -320 ) ( 10504 17800 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17792 -576 ) ( 10504 17792 -576 ) ( 10504 17792 -592 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 10496 17792 -576 ) ( 10496 17800 -576 ) ( 10496 17800 -592 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10504 17800 -576 ) ( 10112 17800 -576 ) ( 10112 17800 -592 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17800 -576 ) ( 10112 17792 -576 ) ( 10112 17792 -592 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 10496 17408 -768 ) ( 10112 17408 -768 ) ( 10112 17392 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17384 -320 ) ( 10112 17400 -320 ) ( 10496 17400 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17400 -544 ) ( 10496 17400 -544 ) ( 10496 17400 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17392 -544 ) ( 10496 17408 -544 ) ( 10496 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17408 -544 ) ( 10112 17408 -544 ) ( 10112 17408 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 10112 17408 -544 ) ( 10112 17392 -544 ) ( 10112 17392 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 10568 17784 -768 ) ( 10496 17784 -768 ) ( 10496 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17408 -320 ) ( 10496 17784 -320 ) ( 10568 17784 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17408 -320 ) ( 10568 17408 -320 ) ( 10568 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10504 17400 -320 ) ( 10504 17776 -320 ) ( 10504 17776 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10568 17792 -320 ) ( 10496 17792 -320 ) ( 10496 17792 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17784 -320 ) ( 10496 17408 -320 ) ( 10496 17408 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 10112 17792 -768 ) ( 10072 17792 -768 ) ( 10072 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10072 17408 -320 ) ( 10072 17792 -320 ) ( 10112 17792 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10072 17408 -320 ) ( 10112 17408 -320 ) ( 10112 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17408 -320 ) ( 10112 17792 -320 ) ( 10112 17792 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 10112 17792 -320 ) ( 10072 17792 -320 ) ( 10072 17792 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10104 17792 -320 ) ( 10104 17408 -320 ) ( 10104 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 10496 17792 -320 ) ( 10112 17792 -320 ) ( 10112 17408 -320 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 10112 17408 -312 ) ( 10112 17792 -312 ) ( 10496 17792 -312 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17408 -232 ) ( 10496 17408 -232 ) ( 10496 17408 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17408 -232 ) ( 10496 17792 -232 ) ( 10496 17792 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17792 -232 ) ( 10112 17792 -232 ) ( 10112 17792 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17792 -232 ) ( 10112 17408 -232 ) ( 10112 17408 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 10496 17792 -776 ) ( 10112 17792 -776 ) ( 10112 17408 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17408 -768 ) ( 10112 17792 -768 ) ( 10496 17792 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 10112 17408 -768 ) ( 10496 17408 -768 ) ( 10496 17408 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17408 -768 ) ( 10496 17792 -768 ) ( 10496 17792 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10496 17792 -768 ) ( 10112 17792 -768 ) ( 10112 17792 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 10112 17792 -768 ) ( 10112 17408 -768 ) ( 10112 17408 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"origin" "10312 17600 -480" -"classname" "info_player_deathmatch" -} -{ -"light" "1000" -"origin" "10240 17608 -464" -"classname" "light" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/snap_plane/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/snap_plane/README.txt deleted file mode 100644 index d66196be..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/snap_plane/README.txt +++ /dev/null @@ -1,45 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The example map, maps/snap_plane.map, contains an example of some bugs. -The green brush with the red face is transformed into something totally -unexpected. - -To trigger the bug, compile the map; you don't need -vis or -light. Only --bsp (the first q3map2 stage) is necessary to trigger the bug. The only -entities in the map are a light and a info_player_deathmatch, so the map will -compile for any Q3 mod. - - -SOLUTION TO PROBLEM: -==================== - -I actually came up with this regression test after reading the code to -SnapPlane() and SnapNormal(). I decided to make this map as a test of -whether or not I understand how the code is broken. Sure enough, the map -is broken in the same way that I would expect it to be broken. - -The problem is that the red face of the green brush in the center of the room -is very close to being axially aligned, but not quite. This plane will -therefore be "snapped" to become axial. This is not the problem. The -problem is that after the snap, the plane will be shifted a great deal, -and the corner of the green brush will no longer come even close to meeting -the corner of the other cube brush next to it (the two corners of the two -brushes will drift apart a great deal). - -If you study the legacy SnapPlane() code, you will see that planes are -defined as a unit normal and distance from origin. Well, because -of the position of this brush on the side of the world extents (far from -the original), the snap will cause drastic effects on the points that the -plane was supposed to approximate. - -Another problem with SnapPlane() is that SnapNormal() snaps too liberally. -Once SnapNormal() is changed to only snap normals that are REALLY close -to axial (and not anything within 0.25 degrees), this bug will no longer -appear, but the SnapPlane() problem will still be present. So, this -regression test should be fixed BEFORE SnapNormal() is fixed, otherwise -create another regression test with a red face that is much much closer to -being axially aligned. We want to make sure that SnapPlane() is fixed when -things actually do get snapped. - -The code to address these issues is currently being worked on. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/snap_plane/maps/snap_plane.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/snap_plane/maps/snap_plane.map deleted file mode 100644 index c2b490c5..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/snap_plane/maps/snap_plane.map +++ /dev/null @@ -1,78 +0,0 @@ -{ -"classname" "worldspawn" -{ -( -54784 5760 -64 ) ( -54976 5760 -64 ) ( -54976 5632 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -54976 5632 0 ) ( -54976 5760 0 ) ( -54784 5760 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -54976 5632 0 ) ( -54784 5632 0 ) ( -54784 5632 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -54784 5632 0 ) ( -54784 5760 0 ) ( -54784 5760 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -54784 5760 0 ) ( -54976 5760 0 ) ( -54976 5760 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -54976 5760 0 ) ( -54976 5632 0 ) ( -54976 5632 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -53808 5616 -64 ) ( -55064 5616 -64 ) ( -55064 4944 -64 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -55072 4944 0 ) ( -55072 5616 0 ) ( -53816 5616 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -55040 4096 8 ) ( -53784 4096 8 ) ( -53784 4096 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -54272 4936 8 ) ( -54272 5608 8 ) ( -54272 5608 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -53816 5632 8 ) ( -55072 5632 8 ) ( -55072 5632 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -54784 5592 8 ) ( -54784 4920 8 ) ( -54784 4920 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 -( -54528 5632 -64 ) ( -54272 5631 -64 ) ( -54528 5632 0 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -54200 5904 -128 ) ( -55032 5904 -128 ) ( -55032 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55024 5824 192 ) ( -55024 5904 192 ) ( -54192 5904 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55040 5824 0 ) ( -54208 5824 0 ) ( -54208 5824 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -54208 5824 0 ) ( -54208 5904 0 ) ( -54208 5904 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54200 5832 0 ) ( -55032 5832 0 ) ( -55032 5832 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55040 5904 0 ) ( -55040 5824 0 ) ( -55040 5824 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -54144 5824 -128 ) ( -54208 5824 -128 ) ( -54208 5424 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54208 5424 192 ) ( -54208 5824 192 ) ( -54144 5824 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54160 4032 192 ) ( -54096 4032 192 ) ( -54096 4032 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54200 5424 192 ) ( -54200 5824 192 ) ( -54200 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54144 5824 192 ) ( -54208 5824 192 ) ( -54208 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54208 5824 192 ) ( -54208 5424 192 ) ( -54208 5424 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( -54208 4032 -128 ) ( -54760 4032 -128 ) ( -54760 3944 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54760 3944 192 ) ( -54760 4032 192 ) ( -54208 4032 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54752 4024 192 ) ( -54200 4024 192 ) ( -54200 4024 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54208 3944 192 ) ( -54208 4032 192 ) ( -54208 4032 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54208 4032 192 ) ( -54760 4032 192 ) ( -54760 4032 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -55040 4016 192 ) ( -55040 3928 192 ) ( -55040 3928 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -55040 5824 -128 ) ( -55256 5824 -128 ) ( -55256 5256 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55256 5256 192 ) ( -55256 5824 192 ) ( -55040 5824 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55256 4032 192 ) ( -55040 4032 192 ) ( -55040 4032 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55040 5256 192 ) ( -55040 5824 192 ) ( -55040 5824 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -55040 5824 192 ) ( -55256 5824 192 ) ( -55256 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55048 5808 192 ) ( -55048 5240 192 ) ( -55048 5240 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -54208 4032 192 ) ( -55040 4032 192 ) ( -55040 4024 192 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -55016 4024 200 ) ( -55016 4032 200 ) ( -54184 4032 200 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55040 4032 296 ) ( -54208 4032 296 ) ( -54208 4032 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54208 4024 296 ) ( -54208 4032 296 ) ( -54208 4032 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54200 5824 296 ) ( -55032 5824 296 ) ( -55032 5824 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55040 4032 296 ) ( -55040 4024 296 ) ( -55040 4024 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( -54192 4560 -136 ) ( -55024 4560 -136 ) ( -55024 4552 -136 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55040 4024 -128 ) ( -55040 4032 -128 ) ( -54208 4032 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( -55040 4032 -128 ) ( -54208 4032 -128 ) ( -54208 4032 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54208 4024 -128 ) ( -54208 4032 -128 ) ( -54208 4032 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -54208 5824 -120 ) ( -55040 5824 -120 ) ( -55040 5824 -248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( -55040 4032 -128 ) ( -55040 4024 -128 ) ( -55040 4024 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"light" "1000" -"origin" "-54664 5696 40" -"classname" "light" -} -{ -"angle" "360" -"origin" "-54840 5696 88" -"classname" "info_player_deathmatch" -} diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/sparkly_seam/README.txt b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/sparkly_seam/README.txt deleted file mode 100644 index 3c54feb5..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/sparkly_seam/README.txt +++ /dev/null @@ -1,21 +0,0 @@ -DESCRIPTION OF PROBLEM: -======================= - -The example map, maps/sparkly_seam.map, contains two triangular brushes near -the side of the room. The seam between these two brushes "sparkles" even -though the endpoints of the edges are exactly the same. - -To trigger the bug, compile the map; you don't need -vis or -light. Only --bsp (the first q3map2 stage) is necessary to trigger the bug. The only -entities in the map are a light and a info_player_deathmatch, so the map will -compile for any Q3 mod. - - -SOLUTION TO PROBLEM: -==================== - -None yet. The problem is likely caused by sloppy math operations (significant -loss of precision). This bug pops in and out of existence with every other -commit at the moment. The problem is likely caused by the operations in the -brush winding computation (where the planes are intersected with each other). -I have not gotten around to addressing that code yet. diff --git a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/sparkly_seam/maps/sparkly_seam.map b/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/sparkly_seam/maps/sparkly_seam.map deleted file mode 100644 index 4b021372..00000000 --- a/misc/mediasource/extra/netradiant-src/regression_tests/q3map2/sparkly_seam/maps/sparkly_seam.map +++ /dev/null @@ -1,75 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 6784 16015 -2048 ) ( 6144 15958 -2048 ) ( 6784 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6784 16015 -1788 ) ( 6784 16015 -2048 ) ( 6784 15936 -1792 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 15958 -1471 ) ( 6144 15958 -2048 ) ( 6784 16015 -1788 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6784 15936 -1792 ) ( 6784 15936 -2048 ) ( 6144 15958 -1471 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6784 15936 -1792 ) ( 6144 15958 -1471 ) ( 6784 16015 -1788 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 6784 15936 -2048 ) ( 6144 15958 -2048 ) ( 6144 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6784 15936 -1792 ) ( 6144 15936 -2048 ) ( 6144 15936 -1472 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 15936 -1472 ) ( 6144 15958 -2048 ) ( 6144 15958 -1471 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 15958 -1471 ) ( 6784 15936 -2048 ) ( 6784 15936 -1792 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 -( 6144 15936 -1472 ) ( 6144 15958 -1471 ) ( 6784 15936 -1792 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 -} -{ -( 6160 16432 -2048 ) ( 6048 16432 -2048 ) ( 6048 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6128 15936 -896 ) ( 6128 16432 -896 ) ( 6240 16432 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6032 15936 160 ) ( 6144 15936 160 ) ( 6144 15936 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 160 ) ( 6144 16432 160 ) ( 6144 16432 -3552 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6112 16896 160 ) ( 6000 16896 160 ) ( 6000 16896 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 16424 168 ) ( 6136 15928 168 ) ( 6136 15928 -3544 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6144 16672 -2048 ) ( 6136 16672 -2048 ) ( 6136 16176 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 16192 -896 ) ( 6136 16688 -896 ) ( 6144 16688 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6136 15936 -1280 ) ( 6144 15936 -1280 ) ( 6144 15936 -1760 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6792 16160 -1296 ) ( 6792 16656 -1296 ) ( 6792 16656 -1776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -1312 ) ( 6136 16896 -1312 ) ( 6136 16896 -1792 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16672 -1296 ) ( 6784 16176 -1296 ) ( 6784 16176 -1776 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -} -{ -( 6784 15936 -2048 ) ( 6144 15936 -2048 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15880 -896 ) ( 6144 15936 -896 ) ( 6784 15936 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15928 -896 ) ( 6784 15928 -896 ) ( 6784 15928 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15880 -896 ) ( 6784 15936 -896 ) ( 6784 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15936 -896 ) ( 6144 15936 -896 ) ( 6144 15936 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 15936 -896 ) ( 6144 15880 -896 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6784 16960 -2048 ) ( 6144 16960 -2048 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -896 ) ( 6144 16960 -896 ) ( 6784 16960 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -896 ) ( 6784 16896 -896 ) ( 6784 16896 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6784 16896 -896 ) ( 6784 16960 -896 ) ( 6784 16960 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16904 -896 ) ( 6144 16904 -896 ) ( 6144 16904 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16960 -896 ) ( 6144 16896 -896 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6784 16896 -896 ) ( 6144 16896 -896 ) ( 6144 16536 -896 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 16552 -888 ) ( 6144 16912 -888 ) ( 6784 16912 -888 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -744 ) ( 6784 15936 -744 ) ( 6784 15936 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16536 -784 ) ( 6784 16896 -784 ) ( 6784 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -784 ) ( 6144 16896 -784 ) ( 6144 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16896 -784 ) ( 6144 16536 -784 ) ( 6144 16536 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -{ -( 6784 16584 -2056 ) ( 6144 16584 -2056 ) ( 6144 15976 -2056 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 15936 -2048 ) ( 6144 16544 -2048 ) ( 6784 16544 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 -( 6144 15936 -2048 ) ( 6784 15936 -2048 ) ( 6784 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 15936 -2048 ) ( 6784 16544 -2048 ) ( 6784 16544 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6784 16896 -2048 ) ( 6144 16896 -2048 ) ( 6144 16896 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -( 6144 16544 -2048 ) ( 6144 15936 -2048 ) ( 6144 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 -} -} -{ -"angle" "180" -"origin" "6608 15968 -1608" -"classname" "info_player_deathmatch" -} -{ -"light" "1000" -"origin" "6440 16160 -1192" -"classname" "light" -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Info.plist b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Info.plist deleted file mode 100644 index 81e377d1..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Info.plist +++ /dev/null @@ -1,18 +0,0 @@ - - - - - CFBundleDevelopmentRegion - English - CFBundleExecutable - netradiant.sh - CFBundleIconFile - NetRadiant - CFBundlePackageType - APPL - CFBundleSignature - ???? - CFBundleVersion - 1.5.0 - - diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.conf b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.conf deleted file mode 100644 index 86dc8af2..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.conf +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - /usr/share/fonts - /usr/X11/lib/X11/fonts /Library/Fonts /Network/Library/Fonts /System/Library/Fonts /opt/local/share/fonts - ~/.fonts - - - - - mono - - - monospace - - - - - - - sans serif - - - sans-serif - - - - - - - sans - - - sans-serif - - - - - conf.d - - - - ~/.fontconfig - - - - - 0x0020 - 0x00A0 - 0x00AD - 0x034F - 0x0600 - 0x0601 - 0x0602 - 0x0603 - 0x06DD - 0x070F - 0x115F - 0x1160 - 0x1680 - 0x17B4 - 0x17B5 - 0x180E - 0x2000 - 0x2001 - 0x2002 - 0x2003 - 0x2004 - 0x2005 - 0x2006 - 0x2007 - 0x2008 - 0x2009 - 0x200A - 0x200B - 0x200C - 0x200D - 0x200E - 0x200F - 0x2028 - 0x2029 - 0x202A - 0x202B - 0x202C - 0x202D - 0x202E - 0x202F - 0x205F - 0x2060 - 0x2061 - 0x2062 - 0x2063 - 0x206A - 0x206B - 0x206C - 0x206D - 0x206E - 0x206F - 0x2800 - 0x3000 - 0x3164 - 0xFEFF - 0xFFA0 - 0xFFF9 - 0xFFFA - 0xFFFB - - - - 30 - - - - diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.dtd b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.dtd deleted file mode 100644 index cbdfdab3..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.dtd +++ /dev/null @@ -1,224 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/gdk-pixbuf.loaders b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/gdk-pixbuf.loaders deleted file mode 100644 index f8852a26..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/gdk-pixbuf.loaders +++ /dev/null @@ -1,12 +0,0 @@ -# GdkPixbuf Image Loader Modules file -# Automatically generated file, do not edit -# Created by gdk-pixbuf-query-loaders from gtk+-2.6.10 -# -# LoaderDir = /sw.haha/lib/gtk-2.0/2.4.0/loaders -# -"./libpixbufloader-bmp.so" -"bmp" 5 "gtk20" "The BMP image format" -"image/bmp" "image/x-bmp" "image/x-MS-bmp" "" -"bmp" "" -"BM" "" 100 - diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pango.modules b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pango.modules deleted file mode 100644 index 9eecea48..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pango.modules +++ /dev/null @@ -1,7 +0,0 @@ -# Pango Modules file -# Automatically generated file, do not edit -# -# ModulesPath = /sw.haha/lib/pango/1.4.0/modules -# -./pango-basic-fc.so BasicScriptEngineFc PangoEngineShape PangoRenderFc armenian:* bopomofo:* cherokee:* coptic:* cyrillic:* deseret:* ethiopic:* georgian:* gothic:* greek:* han:* hiragana:* katakana:* latin:* ogham:* old-italic:* runic:* canadian-aboriginal:* yi:* braille:* cypriot:* limbu:* osmanya:* shavian:* linear-b:* ugaritic:* common: -./pango-basic-x.so BasicScriptEngineX PangoEngineShape PangoRenderX common: diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangorc b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangorc deleted file mode 100644 index 282e977e..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangorc +++ /dev/null @@ -1,5 +0,0 @@ -[Pango] -ModuleFiles = ./pango.modules - -[PangoX] -AliasFiles = ./pangox.aliases diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangox.aliases b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangox.aliases deleted file mode 100644 index 9b41aa75..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangox.aliases +++ /dev/null @@ -1,220 +0,0 @@ -# File defining aliases of PangoFontDescription to X font set -# -# family style variant weight stretch XLFD - -sans normal normal normal normal \ - "-*-helvetica-medium-r-normal--*-*-*-*-*-*-*-*,\ - -*-gulim-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -sans italic normal normal normal \ - "-*-helvetica-medium-o-normal--*-*-*-*-*-*-*-*,\ - -*-gulim-medium-o-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -sans normal normal bold normal \ - "-*-helvetica-bold-r-normal--*-*-*-*-*-*-*-*,\ - -*-gulim-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -sans italic normal bold normal \ - "-*-helvetica-bold-o-normal--*-*-*-*-*-*-*-*,\ - -*-gulim-bold-o-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - - -serif normal normal normal normal \ - "-*-times-medium-r-normal--*-*-*-*-*-*-*-*,\ - -*-batang-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -serif italic normal normal normal \ - "-*-times-medium-i-normal--*-*-*-*-*-*-*-*,\ - -*-batang-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -serif normal normal bold normal \ - "-*-times-bold-r-normal--*-*-*-*-*-*-*-*,\ - -*-batang-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -serif italic normal bold normal \ - "-*-times-bold-i-normal--*-*-*-*-*-*-*-*,\ - -*-batang-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -monospace normal normal normal normal \ - "-*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -*-dotum-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -monospace italic normal normal normal \ - "-*-fixed-medium-i-normal--*-*-*-*-*-*-*-*,\ - -*-dotum-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -monospace normal normal bold normal \ - "-*-fixed-bold-r-normal--*-*-*-*-*-*-*-*,\ - -*-dotum-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" - -monospace italic normal bold normal \ - "-*-fixed-bold-i-normal--*-*-*-*-*-*-*-*,\ - -*-dotum-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ - -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ - -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ - -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ - -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ - -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ - -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ - -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ - -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ - -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ - -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ - -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ - -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ - -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ - -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/PkgInfo b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/PkgInfo deleted file mode 100644 index bd04210f..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/PkgInfo +++ /dev/null @@ -1 +0,0 @@ -APPL???? \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/English.lproj/InfoPlist.strings b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/English.lproj/InfoPlist.strings deleted file mode 100644 index 4a182e50..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/English.lproj/InfoPlist.strings and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/NetRadiant.icns b/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/NetRadiant.icns deleted file mode 100644 index 339e718d..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/NetRadiant.icns and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools-src/splash.map b/misc/mediasource/extra/netradiant-src/setup/data/tools-src/splash.map deleted file mode 100644 index 1594ee88..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools-src/splash.map +++ /dev/null @@ -1,558 +0,0 @@ -{ -"classname" "worldspawn" -{ -( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 1280 4096 ) ( 1280 -1280 4096 ) ( 1280 1280 4096 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -} -{ -( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 1280 4096 0 ) ( -1280 4096 512 ) ( 1280 4096 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -} -{ -( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 4096 -1280 512 ) ( 4096 1280 0 ) ( 4096 1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -} -{ -( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 1280 -4096 ) ( 1280 -1280 -4096 ) ( -1280 -1280 -4096 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -} -{ -( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 1280 -4096 0 ) ( -1280 -4096 512 ) ( -1280 -4096 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -} -{ -( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -( -4096 -1536 512 ) ( -4096 1024 0 ) ( -4096 -1536 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 -} -} -{ -"classname" "func_group" -{ -( -32 40 80 ) ( -40 40 72 ) ( -40 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 56 88 ) ( -40 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 32 68 ) ( -40 40 76 ) ( -40 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 52 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 40 32 ) ( -40 40 48 ) ( -40 104 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -104 40 32 ) ( -104 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 40 96 ) ( -48 40 80 ) ( -40 48 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -48 56 88 ) ( -48 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 68 ) ( -48 40 76 ) ( -48 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 48 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 32 80 ) ( -40 32 80 ) ( -40 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 32 68 ) ( -40 40 76 ) ( -40 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 40 32 ) ( -40 40 48 ) ( -40 104 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 40 96 ) ( -48 40 80 ) ( -40 48 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 80 ) ( -48 32 80 ) ( -48 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -48 72 88 ) ( -48 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 24 96 ) ( -104 24 96 ) ( -104 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 24 32 ) ( -40 24 48 ) ( -40 88 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 48 ) ( -40 52 32 ) ( -48 60 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 68 ) ( -48 40 76 ) ( -48 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 32 96 ) ( -32 40 80 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 32 80 ) ( -40 48 96 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 56 88 ) ( -40 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 40 32 ) ( -40 40 48 ) ( -40 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 80 ) ( -96 48 96 ) ( -96 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 76 ) ( -60 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -32 40 80 ) ( -40 40 80 ) ( -40 40 72 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 96 ) ( -32 40 80 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 32 80 ) ( -40 32 80 ) ( -40 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 40 32 ) ( -40 40 48 ) ( -40 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 76 ) ( -60 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -32 40 80 ) ( -40 40 80 ) ( -40 40 72 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 96 ) ( -32 40 80 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 40 32 ) ( -40 40 48 ) ( -40 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 76 ) ( -60 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 96 ) ( -40 68 80 ) ( -32 60 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 96 64 ) ( -40 64 96 ) ( -40 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 64 96 ) ( -40 32 64 ) ( -40 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 24 32 ) ( -40 24 48 ) ( -40 88 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -56 60 80 ) ( -56 60 96 ) ( -96 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 48 ) ( -40 52 32 ) ( -48 60 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -48 32 64 ) ( -48 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -48 72 88 ) ( -48 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 68 48 ) ( -40 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 68 56 ) ( -60 60 76 ) ( -60 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 68 96 ) ( -40 68 80 ) ( -32 60 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 96 64 ) ( -40 96 64 ) ( -40 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 68 48 ) ( -40 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 68 56 ) ( -60 64 76 ) ( -60 64 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 96 ) ( -40 68 80 ) ( -32 60 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 64 96 ) ( -40 64 96 ) ( -40 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 32 68 ) ( -40 32 68 ) ( -40 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 24 32 ) ( -40 24 48 ) ( -40 88 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -56 60 80 ) ( -56 60 96 ) ( -96 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 48 ) ( -40 52 32 ) ( -48 60 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -48 64 96 ) ( -48 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -48 72 88 ) ( -48 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 68 ) ( -48 32 68 ) ( -48 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 68 32 ) ( -40 68 48 ) ( -40 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 64 56 ) ( -60 60 76 ) ( -60 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 96 32 ) ( -40 120 32 ) ( -40 96 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 88 96 ) ( -40 96 96 ) ( -40 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 96 80 ) ( -40 80 96 ) ( -40 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 88 76 ) ( -40 88 68 ) ( -40 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -40 32 32 ) ( -40 32 48 ) ( -40 96 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 96 56 ) ( -60 88 76 ) ( -60 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -32 52 80 ) ( -32 52 96 ) ( -32 116 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 88 96 ) ( -32 80 80 ) ( -40 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 56 88 ) ( -40 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 88 76 ) ( -40 88 76 ) ( -40 88 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 96 68 ) ( -40 96 68 ) ( -40 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 88 80 ) ( -76 80 80 ) ( -64 80 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -32 52 80 ) ( -32 52 96 ) ( -32 116 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 88 96 ) ( -32 80 80 ) ( -40 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 96 80 ) ( -40 80 96 ) ( -40 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -88 40 48 ) ( -48 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 32 68 ) ( -96 40 76 ) ( -96 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 52 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 40 32 ) ( -88 40 48 ) ( -72 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 104 32 ) ( -88 104 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 48 96 ) ( -88 48 80 ) ( -80 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 72 88 ) ( -88 56 88 ) ( -88 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 68 ) ( -88 40 76 ) ( -88 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 48 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 52 48 ) ( -80 60 32 ) ( -88 52 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 60 32 ) ( -88 60 48 ) ( -88 -4 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -72 -4 96 ) ( -88 -4 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 68 ) ( -88 40 76 ) ( -88 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 32 68 ) ( -96 40 76 ) ( -96 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 104 32 ) ( -88 104 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 48 96 ) ( -88 48 80 ) ( -80 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 80 ) ( -88 32 80 ) ( -88 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 40 96 ) ( -88 32 80 ) ( -96 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 80 ) ( -96 48 96 ) ( -96 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 56 ) ( -68 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 40 96 ) ( -88 32 80 ) ( -96 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 56 ) ( -68 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 40 96 ) ( -88 32 80 ) ( -96 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 56 ) ( -68 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -88 68 96 ) ( -48 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 52 48 ) ( -80 60 32 ) ( -88 52 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 60 32 ) ( -88 60 48 ) ( -88 -4 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -72 60 80 ) ( -72 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 64 96 ) ( -88 32 64 ) ( -88 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 68 76 ) ( -68 60 56 ) ( -68 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 80 ) ( -48 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -88 68 96 ) ( -48 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 96 68 ) ( -96 88 76 ) ( -96 96 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 68 76 ) ( -68 64 56 ) ( -68 64 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 52 48 ) ( -80 60 32 ) ( -88 52 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 60 32 ) ( -88 60 48 ) ( -88 -4 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -72 60 80 ) ( -72 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 64 96 ) ( -88 64 96 ) ( -88 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 32 68 ) ( -88 32 68 ) ( -88 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 64 76 ) ( -68 60 56 ) ( -68 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 80 ) ( -48 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 32 68 ) ( -96 32 68 ) ( -96 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 88 96 ) ( -96 88 80 ) ( -88 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 96 76 ) ( -68 88 56 ) ( -68 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 88 80 ) ( -48 88 96 ) ( -88 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 96 68 ) ( -96 96 68 ) ( -96 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 88 80 ) ( -76 76 80 ) ( -64 76 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -72 88 80 ) ( -72 88 96 ) ( -88 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 88 32 ) ( -88 88 48 ) ( -88 24 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 80 48 ) ( -80 88 32 ) ( -88 80 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 72 88 ) ( -88 56 88 ) ( -88 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 96 68 ) ( -88 96 68 ) ( -88 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 88 80 ) ( -76 80 80 ) ( -64 80 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 96 68 ) ( -96 96 68 ) ( -96 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 88 32 ) ( -88 88 48 ) ( -88 24 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 80 48 ) ( -80 88 32 ) ( -88 80 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 96 80 ) ( -88 80 96 ) ( -88 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 32 ) ( -96 32 32 ) ( -80 32 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 68 ) ( -96 40 76 ) ( -96 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 40 80 ) ( -64 32 80 ) ( -76 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 96 32 ) ( -96 32 32 ) ( -80 32 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -80 96 80 ) ( -80 96 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 96 80 ) ( -80 96 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 68 ) ( -96 88 76 ) ( -96 96 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 68 ) ( -96 32 68 ) ( -96 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 96 80 ) ( -80 96 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 68 ) ( -96 96 68 ) ( -96 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 96 80 ) ( -64 88 80 ) ( -76 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 80 ) ( -96 48 96 ) ( -96 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 68 76 ) ( -68 60 76 ) ( -68 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 68 56 ) ( -60 60 56 ) ( -60 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 68 76 ) ( -68 64 76 ) ( -68 64 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 68 56 ) ( -60 64 56 ) ( -60 64 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 64 76 ) ( -68 60 76 ) ( -68 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 64 56 ) ( -60 60 56 ) ( -60 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -{ -( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -40 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 -} -} -{ -"classname" "info_player_deathmatch" -"origin" "72 -68 -144" -"angle" "180" -} -{ -"classname" "light" -"origin" "0 0 -3000" -"light" "80000" -"_color" "0.5 0.5 1" -} -{ -"classname" "light" -"origin" "3000 0 0" -"light" "80000" -"_color" "0.5 1 0.5" -} -{ -"classname" "light" -"origin" "0 -3000 0" -"light" "80000" -"_color" "1 0.5 0.5" -} -{ -"classname" "func_group" -{ -( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -96 96 160 ) ( 96 -96 160 ) ( 96 96 160 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -} -{ -( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -112 80 -160 ) ( 80 -112 -160 ) ( -112 -112 -160 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -} -{ -( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( 96 -160 -32 ) ( -96 -160 32 ) ( -96 -160 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -} -{ -( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -160 -96 32 ) ( -160 96 -32 ) ( -160 -96 -32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -} -{ -( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -( 96 160 -24 ) ( -96 160 40 ) ( 96 160 40 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 -} -{ -( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -( 160 -88 32 ) ( 160 104 -32 ) ( 160 104 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 -} -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools-src/splash.xcf b/misc/mediasource/extra/netradiant-src/setup/data/tools-src/splash.xcf deleted file mode 100644 index 8001037a..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools-src/splash.xcf and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/black.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/black.bmp deleted file mode 100644 index 8fc59ba1..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/black.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipx.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipx.bmp deleted file mode 100644 index 48ee0dbc..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipx.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipy.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipy.bmp deleted file mode 100644 index d7408773..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipy.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipz.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipz.bmp deleted file mode 100644 index 017c33e9..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_flipz.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatex.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatex.bmp deleted file mode 100644 index c7e55053..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatex.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatey.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatey.bmp deleted file mode 100644 index e50e5d6d..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatey.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatez.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatez.bmp deleted file mode 100644 index 52ab554a..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/brush_rotatez.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_bevel.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_bevel.bmp deleted file mode 100644 index 3bb4186e..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_bevel.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_cylinder.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_cylinder.bmp deleted file mode 100644 index 21969267..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_cylinder.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_endcap.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_endcap.bmp deleted file mode 100644 index e6cea655..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_endcap.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_ibevel.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_ibevel.bmp deleted file mode 100644 index b1fa49b3..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_ibevel.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_iendcap.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_iendcap.bmp deleted file mode 100644 index da1f5b66..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/cap_iendcap.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/console.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/console.bmp deleted file mode 100644 index 7fe64b0e..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/console.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/curve_cap.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/curve_cap.bmp deleted file mode 100644 index 574e7611..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/curve_cap.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/dontselectcurve.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/dontselectcurve.bmp deleted file mode 100644 index a7b97954..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/dontselectcurve.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/dontselectmodel.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/dontselectmodel.bmp deleted file mode 100644 index e81b1189..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/dontselectmodel.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/ellipsis.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/ellipsis.bmp deleted file mode 100644 index a4360a9e..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/ellipsis.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/entities.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/entities.bmp deleted file mode 100644 index ce3d8124..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/entities.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/file_open.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/file_open.bmp deleted file mode 100644 index 754f10fb..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/file_open.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/file_save.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/file_save.bmp deleted file mode 100644 index 651afb68..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/file_save.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/icon.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/icon.bmp deleted file mode 100644 index 01aec6ea..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/icon.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/lightinspector.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/lightinspector.bmp deleted file mode 100644 index 00b00a90..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/lightinspector.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/logo.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/logo.bmp deleted file mode 100644 index ddbd3461..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/logo.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_edges.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_edges.bmp deleted file mode 100644 index 7b048f96..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_edges.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_faces.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_faces.bmp deleted file mode 100644 index 03d9f8c2..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_faces.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_vertices.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_vertices.bmp deleted file mode 100644 index c434732e..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/modify_vertices.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/noFalloff.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/noFalloff.bmp deleted file mode 100644 index e86d10c9..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/noFalloff.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/notex.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/notex.bmp deleted file mode 100644 index b06664a7..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/notex.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_bend.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_bend.bmp deleted file mode 100644 index af4fc94c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_bend.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_drilldown.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_drilldown.bmp deleted file mode 100644 index 01ebcf39..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_drilldown.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_insdel.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_insdel.bmp deleted file mode 100644 index b60b76b0..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_insdel.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_showboundingbox.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_showboundingbox.bmp deleted file mode 100644 index 357cfaf1..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_showboundingbox.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_weld.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_weld.bmp deleted file mode 100644 index a0c99730..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_weld.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_wireframe.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_wireframe.bmp deleted file mode 100644 index 9804274f..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/patch_wireframe.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/popup_selection.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/popup_selection.bmp deleted file mode 100644 index 676c4d98..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/popup_selection.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/redo.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/redo.bmp deleted file mode 100644 index 32a373af..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/redo.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/refresh_models.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/refresh_models.bmp deleted file mode 100644 index b6507f61..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/refresh_models.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelockx.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelockx.bmp deleted file mode 100644 index 61363da2..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelockx.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelocky.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelocky.bmp deleted file mode 100644 index 812394db..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelocky.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelockz.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelockz.bmp deleted file mode 100644 index 5692e4a7..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/scalelockz.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mouseresize.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mouseresize.bmp deleted file mode 100644 index ca0c9ac3..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mouseresize.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mouserotate.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mouserotate.bmp deleted file mode 100644 index 7f18a561..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mouserotate.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mousescale.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mousescale.bmp deleted file mode 100644 index d8f39024..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mousescale.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mousetranslate.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mousetranslate.bmp deleted file mode 100644 index 04962fde..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/select_mousetranslate.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_csgmerge.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_csgmerge.bmp deleted file mode 100644 index fb5df4f9..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_csgmerge.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_csgsubtract.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_csgsubtract.bmp deleted file mode 100644 index 267d3749..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_csgsubtract.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_makehollow.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_makehollow.bmp deleted file mode 100644 index 8c5d60cd..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_makehollow.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall.bmp deleted file mode 100644 index 8d2c1043..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall_old.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall_old.bmp deleted file mode 100644 index 1f911e8c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall_old.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectinside.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectinside.bmp deleted file mode 100644 index 12b22afb..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectinside.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall.bmp deleted file mode 100644 index d21ddc2c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall_old.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall_old.bmp deleted file mode 100644 index 77b418be..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall_old.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selecttouching.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selecttouching.bmp deleted file mode 100644 index e6d5c4b6..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/selection_selecttouching.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/shadernotex.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/shadernotex.bmp deleted file mode 100644 index 6be415e7..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/shadernotex.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/show_entities.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/show_entities.bmp deleted file mode 100644 index 9188bee6..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/show_entities.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/splash.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/splash.bmp deleted file mode 100644 index a484997f..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/splash.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/texture_browser.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/texture_browser.bmp deleted file mode 100644 index 22f72506..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/texture_browser.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/texture_lock.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/texture_lock.bmp deleted file mode 100644 index 0a003bcf..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/texture_lock.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/textures_popup.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/textures_popup.bmp deleted file mode 100644 index 5333382f..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/textures_popup.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/undo.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/undo.bmp deleted file mode 100644 index fd2b8392..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/undo.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cameratoggle.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cameratoggle.bmp deleted file mode 100644 index 4ec79ed6..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cameratoggle.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cameraupdate.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cameraupdate.bmp deleted file mode 100644 index dbb11956..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cameraupdate.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_change.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_change.bmp deleted file mode 100644 index 977ee1e7..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_change.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_clipper.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_clipper.bmp deleted file mode 100644 index 606a2095..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_clipper.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cubicclipping.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cubicclipping.bmp deleted file mode 100644 index 16f7cb0e..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_cubicclipping.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_entity.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_entity.bmp deleted file mode 100644 index 851ec2c3..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/view_entity.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/white.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/white.bmp deleted file mode 100644 index cbf038f7..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/white.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window1.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window1.bmp deleted file mode 100644 index a8913c72..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window1.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window2.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window2.bmp deleted file mode 100644 index 6db9e565..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window2.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window3.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window3.bmp deleted file mode 100644 index e81a299d..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window3.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window4.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window4.bmp deleted file mode 100644 index d753945f..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/bitmaps/window4.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbfp1.cg b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbfp1.cg deleted file mode 100644 index f535dbb2..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbfp1.cg +++ /dev/null @@ -1,92 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2004 Robert Beckebans -Please see the file "AUTHORS" for a list of contributors - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - -#include "utils.cg" - -struct cg_vertex2fragment -{ - float4 position : TEXCOORD0; - float4 tex_diffuse_bump : TEXCOORD1; - float4 tex_specular : TEXCOORD2; - float4 tex_atten_xy_z : TEXCOORD3; - - float3 tangent : TEXCOORD4; - float3 binormal : TEXCOORD5; - float3 normal : TEXCOORD6; -}; - -struct cg_fragment2final -{ - float4 color : COLOR; -}; - - -cg_fragment2final main(cg_vertex2fragment IN, - uniform sampler2D diffusemap, - uniform sampler2D bumpmap, - uniform sampler2D specularmap, - uniform sampler2D attenuationmap_xy, - uniform sampler2D attenuationmap_z, - uniform float3 view_origin, - uniform float3 light_origin, - uniform float3 light_color, - uniform float bump_scale, - uniform float specular_exponent) -{ - cg_fragment2final OUT; - - // construct object-space-to-tangent-space 3x3 matrix - float3x3 rotation = float3x3(IN.tangent, IN.binormal, IN.normal); - - // compute view direction in tangent space - float3 V = normalize(mul(rotation, view_origin - IN.position.xyz)); - - // compute light direction in tangent space - float3 L = normalize(mul(rotation, (light_origin - IN.position.xyz))); - - // compute half angle in tangent space - float3 H = normalize(L + V); - - // compute normal in tangent space from bumpmap - float3 T = CG_Expand(tex2D(bumpmap, IN.tex_diffuse_bump.zw).xyz); - T.z *= bump_scale; - float3 N = normalize(T); - - // compute the diffuse term - float4 diffuse = tex2D(diffusemap, IN.tex_diffuse_bump.xy); - diffuse.rgb *= light_color * saturate(dot(N, L)); - - // compute the specular term - float3 specular = tex2D(specularmap, IN.tex_specular.xy).rgb * light_color * pow(saturate(dot(N, H)), specular_exponent); - - // compute attenuation - float3 attenuation_xy = tex2Dproj(attenuationmap_xy, float3(IN.tex_atten_xy_z.x, IN.tex_atten_xy_z.y, IN.tex_atten_xy_z.w)).rgb; - float3 attenuation_z = tex2D(attenuationmap_z, float2(IN.tex_atten_xy_z.z, 0)).rgb; - - // compute final color - OUT.color.rgba = diffuse; - OUT.color.rgb += specular; - OUT.color.rgb *= attenuation_xy; - OUT.color.rgb *= attenuation_z; - - return OUT; -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbvp1.cg b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbvp1.cg deleted file mode 100644 index 59a6fc73..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbvp1.cg +++ /dev/null @@ -1,78 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2004 Robert Beckebans -Please see the file "AUTHORS" for a list of contributors - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - - -struct cg_app2vertex -{ - float4 position : POSITION; - float4 tex0 : ATTR8; - - float3 tangent : ATTR9; - float3 binormal : ATTR10; - float3 normal : ATTR11; -}; - -struct cg_vertex2fragment -{ - float4 hposition : POSITION; - - float4 position : TEXCOORD0; - float4 tex_diffuse_bump : TEXCOORD1; - float4 tex_specular : TEXCOORD2; - float4 tex_atten_xy_z : TEXCOORD3; - - float3 tangent : TEXCOORD4; - float3 binormal : TEXCOORD5; - float3 normal : TEXCOORD6; -}; - - - -cg_vertex2fragment main(cg_app2vertex IN) -{ - cg_vertex2fragment OUT; - - // transform vertex position into homogenous clip-space - OUT.hposition = mul(glstate.matrix.mvp, IN.position); - - // assign position in object space - OUT.position = IN.position; - - // transform texcoords - OUT.tex_diffuse_bump.xy = mul(glstate.matrix.texture[0], IN.tex0).xy; - - // transform texcoords - OUT.tex_diffuse_bump.zw = mul(glstate.matrix.texture[1], IN.tex0).xy; - - // transform texcoords - OUT.tex_specular = mul(glstate.matrix.texture[2], IN.tex0); - - // transform vertex position into light space - OUT.tex_atten_xy_z = mul(glstate.matrix.texture[3], IN.position); - - // assign tangent space vectors - OUT.tangent = IN.tangent; - OUT.binormal = IN.binormal; - OUT.normal = IN.normal; - - return OUT; -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glp b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glp deleted file mode 100644 index 88dab8d3..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glp +++ /dev/null @@ -1,86 +0,0 @@ -!!ARBfp1.0 -# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 -# command line args: -profile arbfp1 -# source file: ..\..\setup\data\tools\gl\lighting_DBS_XY_Z_arbfp1.cg -# source file: ..\..\setup\data\tools\gl/utils.cg -#vendor NVIDIA Corporation -#version 1.0.02 -#profile arbfp1 -#program main -#semantic main.diffusemap -#semantic main.bumpmap -#semantic main.specularmap -#semantic main.attenuationmap_xy -#semantic main.attenuationmap_z -#semantic main.view_origin -#semantic main.light_origin -#semantic main.light_color -#semantic main.bump_scale -#semantic main.specular_exponent -#var float4 IN.position : $vin.TEX0 : TEX0 : 0 : 1 -#var float4 IN.tex_diffuse_bump : $vin.TEX1 : TEX1 : 0 : 1 -#var float4 IN.tex_specular : $vin.TEX2 : TEX2 : 0 : 1 -#var float4 IN.tex_atten_xy_z : $vin.TEX3 : TEX3 : 0 : 1 -#var float3 IN.tangent : $vin.TEX4 : TEX4 : 0 : 1 -#var float3 IN.binormal : $vin.TEX5 : TEX5 : 0 : 1 -#var float3 IN.normal : $vin.TEX6 : TEX6 : 0 : 1 -#var sampler2D diffusemap : : texunit 0 : 1 : 1 -#var sampler2D bumpmap : : texunit 1 : 2 : 1 -#var sampler2D specularmap : : texunit 2 : 3 : 1 -#var sampler2D attenuationmap_xy : : texunit 3 : 4 : 1 -#var sampler2D attenuationmap_z : : texunit 4 : 5 : 1 -#var float3 view_origin : : c[4] : 6 : 1 -#var float3 light_origin : : c[2] : 7 : 1 -#var float3 light_color : : c[3] : 8 : 1 -#var float bump_scale : : c[1] : 9 : 1 -#var float specular_exponent : : c[5] : 10 : 1 -#var float4 main.color : $vout.COL : COL : -1 : 1 -#const c[0] = 0.5 2 0 -PARAM c[6] = { { 0.5, 2, 0 }, - program.local[1..5] }; -TEMP R0; -TEMP R1; -TEMP R2; -ADD R1.xyz, -fragment.texcoord[0], c[2]; -DP3 R0.z, fragment.texcoord[6], R1; -DP3 R0.x, fragment.texcoord[4], R1; -DP3 R0.y, fragment.texcoord[5], R1; -ADD R1.xyz, -fragment.texcoord[0], c[4]; -DP3 R0.w, R0, R0; -DP3 R2.z, fragment.texcoord[6], R1; -DP3 R2.x, fragment.texcoord[4], R1; -DP3 R2.y, fragment.texcoord[5], R1; -RSQ R0.w, R0.w; -MUL R1.xyz, R0.w, R0; -DP3 R1.w, R2, R2; -RSQ R0.w, R1.w; -MUL R2.xyz, R0.w, R2; -ADD R2.xyz, R1, R2; -DP3 R0.w, R2, R2; -RSQ R2.w, R0.w; -TEX R0.xyz, fragment.texcoord[1].zwzw, texture[1], 2D; -ADD R0.xyz, R0, -c[0].x; -MUL R0.xyz, R0, c[0].y; -MUL R0.z, R0, c[1].x; -DP3 R1.w, R0, R0; -RSQ R0.w, R1.w; -MUL R0.xyz, R0.w, R0; -MUL R2.xyz, R2.w, R2; -DP3_SAT R0.w, R0, R2; -DP3_SAT R0.x, R0, R1; -TEX R2.xyz, fragment.texcoord[2], texture[2], 2D; -MUL R1.xyz, R2, c[3]; -POW R0.w, R0.w, c[5].x; -MUL R2.xyz, R1, R0.w; -MUL R1.xyz, R0.x, c[3]; -TEX R0, fragment.texcoord[1], texture[0], 2D; -MAD R2.xyz, R0, R1, R2; -TXP R0.xyz, fragment.texcoord[3], texture[3], 2D; -MOV R1.y, c[0].z; -MOV R1.x, fragment.texcoord[3].z; -TEX R1.xyz, R1, texture[4], 2D; -MUL R0.xyz, R2, R0; -MUL result.color.xyz, R0, R1; -MOV result.color.w, R0; -END -# 41 instructions, 3 R-regs diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glsl b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glsl deleted file mode 100644 index 7f80fea2..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glsl +++ /dev/null @@ -1,73 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2004 Robert Beckebans -Please see the file "CONTRIBUTORS" for a list of contributors - -This program 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 program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - -uniform sampler2D u_diffusemap; -uniform sampler2D u_bumpmap; -uniform sampler2D u_specularmap; -uniform sampler2D u_attenuationmap_xy; -uniform sampler2D u_attenuationmap_z; -uniform vec3 u_view_origin; -uniform vec3 u_light_origin; -uniform vec3 u_light_color; -uniform float u_bump_scale; -uniform float u_specular_exponent; - -varying vec3 var_vertex; -varying vec4 var_tex_diffuse_bump; -varying vec2 var_tex_specular; -varying vec4 var_tex_atten_xy_z; -varying mat3 var_mat_os2ts; - -void main() -{ - // compute view direction in tangent space - vec3 V = normalize(var_mat_os2ts * (u_view_origin - var_vertex)); - - // compute light direction in tangent space - vec3 L = normalize(var_mat_os2ts * (u_light_origin - var_vertex)); - - // compute half angle in tangent space - vec3 H = normalize(L + V); - - // compute normal in tangent space from bumpmap - vec3 N = 2.0 * (texture2D(u_bumpmap, var_tex_diffuse_bump.pq).xyz - 0.5); - N.z *= u_bump_scale; - N = normalize(N); - - // compute the diffuse term - vec4 diffuse = texture2D(u_diffusemap, var_tex_diffuse_bump.st); - diffuse.rgb *= u_light_color * clamp(dot(N, L), 0.0, 1.0); - - // compute the specular term - vec3 specular = texture2D(u_specularmap, var_tex_specular).rgb * u_light_color * pow(clamp(dot(N, H), 0.0, 1.0), u_specular_exponent); - - // compute attenuation - vec3 attenuation_xy = texture2DProj(u_attenuationmap_xy, vec3(var_tex_atten_xy_z.x, var_tex_atten_xy_z.y, var_tex_atten_xy_z.w)).rgb; - vec3 attenuation_z = texture2D(u_attenuationmap_z, vec2(var_tex_atten_xy_z.z, 0)).rgb; - - // compute final color - gl_FragColor.rgba = diffuse; - gl_FragColor.rgb += specular; - gl_FragColor.rgb *= attenuation_xy; - gl_FragColor.rgb *= attenuation_z; -} - diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glp b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glp deleted file mode 100644 index b4472d70..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glp +++ /dev/null @@ -1,410 +0,0 @@ -!!ARBvp1.0 -# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 -# command line args: -profile arbvp1 -# source file: ..\..\setup\data\tools\gl\lighting_DBS_XY_Z_arbvp1.cg -#vendor NVIDIA Corporation -#version 1.0.02 -#profile arbvp1 -#program main -#semantic glstate : STATE -#var float4 glstate.material.ambient : STATE.MATERIAL.AMBIENT : : -1 : 0 -#var float4 glstate.material.diffuse : STATE.MATERIAL.DIFFUSE : : -1 : 0 -#var float4 glstate.material.specular : STATE.MATERIAL.SPECULAR : : -1 : 0 -#var float4 glstate.material.emission : STATE.MATERIAL.EMISSION : : -1 : 0 -#var float4 glstate.material.shininess : STATE.MATERIAL.SHININESS : : -1 : 0 -#var float4 glstate.material.front.ambient : STATE.MATERIAL.FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.material.front.diffuse : STATE.MATERIAL.FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.material.front.specular : STATE.MATERIAL.FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.material.front.emission : STATE.MATERIAL.FRONT.EMISSION : : -1 : 0 -#var float4 glstate.material.front.shininess : STATE.MATERIAL.FRONT.SHININESS : : -1 : 0 -#var float4 glstate.material.back.ambient : STATE.MATERIAL.BACK.AMBIENT : : -1 : 0 -#var float4 glstate.material.back.diffuse : STATE.MATERIAL.BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.material.back.specular : STATE.MATERIAL.BACK.SPECULAR : : -1 : 0 -#var float4 glstate.material.back.emission : STATE.MATERIAL.BACK.EMISSION : : -1 : 0 -#var float4 glstate.material.back.shininess : STATE.MATERIAL.BACK.SHININESS : : -1 : 0 -#var float4 glstate.light[0].ambient : STATE.LIGHT[0].AMBIENT : : -1 : 0 -#var float4 glstate.light[0].diffuse : STATE.LIGHT[0].DIFFUSE : : -1 : 0 -#var float4 glstate.light[0].specular : STATE.LIGHT[0].SPECULAR : : -1 : 0 -#var float4 glstate.light[0].position : STATE.LIGHT[0].POSITION : : -1 : 0 -#var float4 glstate.light[0].attenuation : STATE.LIGHT[0].ATTENUATION : : -1 : 0 -#var float4 glstate.light[0].spot.direction : STATE.LIGHT[0].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[0].half : STATE.LIGHT[0].HALF : : -1 : 0 -#var float4 glstate.light[1].ambient : STATE.LIGHT[1].AMBIENT : : -1 : 0 -#var float4 glstate.light[1].diffuse : STATE.LIGHT[1].DIFFUSE : : -1 : 0 -#var float4 glstate.light[1].specular : STATE.LIGHT[1].SPECULAR : : -1 : 0 -#var float4 glstate.light[1].position : STATE.LIGHT[1].POSITION : : -1 : 0 -#var float4 glstate.light[1].attenuation : STATE.LIGHT[1].ATTENUATION : : -1 : 0 -#var float4 glstate.light[1].spot.direction : STATE.LIGHT[1].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[1].half : STATE.LIGHT[1].HALF : : -1 : 0 -#var float4 glstate.light[2].ambient : STATE.LIGHT[2].AMBIENT : : -1 : 0 -#var float4 glstate.light[2].diffuse : STATE.LIGHT[2].DIFFUSE : : -1 : 0 -#var float4 glstate.light[2].specular : STATE.LIGHT[2].SPECULAR : : -1 : 0 -#var float4 glstate.light[2].position : STATE.LIGHT[2].POSITION : : -1 : 0 -#var float4 glstate.light[2].attenuation : STATE.LIGHT[2].ATTENUATION : : -1 : 0 -#var float4 glstate.light[2].spot.direction : STATE.LIGHT[2].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[2].half : STATE.LIGHT[2].HALF : : -1 : 0 -#var float4 glstate.light[3].ambient : STATE.LIGHT[3].AMBIENT : : -1 : 0 -#var float4 glstate.light[3].diffuse : STATE.LIGHT[3].DIFFUSE : : -1 : 0 -#var float4 glstate.light[3].specular : STATE.LIGHT[3].SPECULAR : : -1 : 0 -#var float4 glstate.light[3].position : STATE.LIGHT[3].POSITION : : -1 : 0 -#var float4 glstate.light[3].attenuation : STATE.LIGHT[3].ATTENUATION : : -1 : 0 -#var float4 glstate.light[3].spot.direction : STATE.LIGHT[3].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[3].half : STATE.LIGHT[3].HALF : : -1 : 0 -#var float4 glstate.light[4].ambient : STATE.LIGHT[4].AMBIENT : : -1 : 0 -#var float4 glstate.light[4].diffuse : STATE.LIGHT[4].DIFFUSE : : -1 : 0 -#var float4 glstate.light[4].specular : STATE.LIGHT[4].SPECULAR : : -1 : 0 -#var float4 glstate.light[4].position : STATE.LIGHT[4].POSITION : : -1 : 0 -#var float4 glstate.light[4].attenuation : STATE.LIGHT[4].ATTENUATION : : -1 : 0 -#var float4 glstate.light[4].spot.direction : STATE.LIGHT[4].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[4].half : STATE.LIGHT[4].HALF : : -1 : 0 -#var float4 glstate.light[5].ambient : STATE.LIGHT[5].AMBIENT : : -1 : 0 -#var float4 glstate.light[5].diffuse : STATE.LIGHT[5].DIFFUSE : : -1 : 0 -#var float4 glstate.light[5].specular : STATE.LIGHT[5].SPECULAR : : -1 : 0 -#var float4 glstate.light[5].position : STATE.LIGHT[5].POSITION : : -1 : 0 -#var float4 glstate.light[5].attenuation : STATE.LIGHT[5].ATTENUATION : : -1 : 0 -#var float4 glstate.light[5].spot.direction : STATE.LIGHT[5].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[5].half : STATE.LIGHT[5].HALF : : -1 : 0 -#var float4 glstate.light[6].ambient : STATE.LIGHT[6].AMBIENT : : -1 : 0 -#var float4 glstate.light[6].diffuse : STATE.LIGHT[6].DIFFUSE : : -1 : 0 -#var float4 glstate.light[6].specular : STATE.LIGHT[6].SPECULAR : : -1 : 0 -#var float4 glstate.light[6].position : STATE.LIGHT[6].POSITION : : -1 : 0 -#var float4 glstate.light[6].attenuation : STATE.LIGHT[6].ATTENUATION : : -1 : 0 -#var float4 glstate.light[6].spot.direction : STATE.LIGHT[6].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[6].half : STATE.LIGHT[6].HALF : : -1 : 0 -#var float4 glstate.light[7].ambient : STATE.LIGHT[7].AMBIENT : : -1 : 0 -#var float4 glstate.light[7].diffuse : STATE.LIGHT[7].DIFFUSE : : -1 : 0 -#var float4 glstate.light[7].specular : STATE.LIGHT[7].SPECULAR : : -1 : 0 -#var float4 glstate.light[7].position : STATE.LIGHT[7].POSITION : : -1 : 0 -#var float4 glstate.light[7].attenuation : STATE.LIGHT[7].ATTENUATION : : -1 : 0 -#var float4 glstate.light[7].spot.direction : STATE.LIGHT[7].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[7].half : STATE.LIGHT[7].HALF : : -1 : 0 -#var float4 glstate.lightmodel.ambient : STATE.LIGHTMODEL.AMBIENT : : -1 : 0 -#var float4 glstate.lightmodel.scenecolor : STATE.LIGHTMODEL.SCENECOLOR : : -1 : 0 -#var float4 glstate.lightmodel.front.scenecolor : STATE.LIGHTMODEL.FRONT.SCENECOLOR : : -1 : 0 -#var float4 glstate.lightmodel.back.scenecolor : STATE.LIGHTMODEL.BACK.SCENECOLOR : : -1 : 0 -#var float4 glstate.lightprod[0].ambient : STATE.LIGHTPROD[0].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[0].diffuse : STATE.LIGHTPROD[0].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[0].specular : STATE.LIGHTPROD[0].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[0].front.ambient : STATE.LIGHTPROD[0].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[0].front.diffuse : STATE.LIGHTPROD[0].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[0].front.specular : STATE.LIGHTPROD[0].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[0].back.ambient : STATE.LIGHTPROD[0].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[0].back.diffuse : STATE.LIGHTPROD[0].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[0].back.specular : STATE.LIGHTPROD[0].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[1].ambient : STATE.LIGHTPROD[1].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[1].diffuse : STATE.LIGHTPROD[1].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[1].specular : STATE.LIGHTPROD[1].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[1].front.ambient : STATE.LIGHTPROD[1].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[1].front.diffuse : STATE.LIGHTPROD[1].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[1].front.specular : STATE.LIGHTPROD[1].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[1].back.ambient : STATE.LIGHTPROD[1].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[1].back.diffuse : STATE.LIGHTPROD[1].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[1].back.specular : STATE.LIGHTPROD[1].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[2].ambient : STATE.LIGHTPROD[2].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[2].diffuse : STATE.LIGHTPROD[2].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[2].specular : STATE.LIGHTPROD[2].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[2].front.ambient : STATE.LIGHTPROD[2].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[2].front.diffuse : STATE.LIGHTPROD[2].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[2].front.specular : STATE.LIGHTPROD[2].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[2].back.ambient : STATE.LIGHTPROD[2].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[2].back.diffuse : STATE.LIGHTPROD[2].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[2].back.specular : STATE.LIGHTPROD[2].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[3].ambient : STATE.LIGHTPROD[3].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[3].diffuse : STATE.LIGHTPROD[3].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[3].specular : STATE.LIGHTPROD[3].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[3].front.ambient : STATE.LIGHTPROD[3].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[3].front.diffuse : STATE.LIGHTPROD[3].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[3].front.specular : STATE.LIGHTPROD[3].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[3].back.ambient : STATE.LIGHTPROD[3].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[3].back.diffuse : STATE.LIGHTPROD[3].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[3].back.specular : STATE.LIGHTPROD[3].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[4].ambient : STATE.LIGHTPROD[4].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[4].diffuse : STATE.LIGHTPROD[4].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[4].specular : STATE.LIGHTPROD[4].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[4].front.ambient : STATE.LIGHTPROD[4].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[4].front.diffuse : STATE.LIGHTPROD[4].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[4].front.specular : STATE.LIGHTPROD[4].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[4].back.ambient : STATE.LIGHTPROD[4].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[4].back.diffuse : STATE.LIGHTPROD[4].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[4].back.specular : STATE.LIGHTPROD[4].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[5].ambient : STATE.LIGHTPROD[5].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[5].diffuse : STATE.LIGHTPROD[5].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[5].specular : STATE.LIGHTPROD[5].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[5].front.ambient : STATE.LIGHTPROD[5].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[5].front.diffuse : STATE.LIGHTPROD[5].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[5].front.specular : STATE.LIGHTPROD[5].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[5].back.ambient : STATE.LIGHTPROD[5].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[5].back.diffuse : STATE.LIGHTPROD[5].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[5].back.specular : STATE.LIGHTPROD[5].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[6].ambient : STATE.LIGHTPROD[6].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[6].diffuse : STATE.LIGHTPROD[6].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[6].specular : STATE.LIGHTPROD[6].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[6].front.ambient : STATE.LIGHTPROD[6].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[6].front.diffuse : STATE.LIGHTPROD[6].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[6].front.specular : STATE.LIGHTPROD[6].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[6].back.ambient : STATE.LIGHTPROD[6].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[6].back.diffuse : STATE.LIGHTPROD[6].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[6].back.specular : STATE.LIGHTPROD[6].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[7].ambient : STATE.LIGHTPROD[7].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[7].diffuse : STATE.LIGHTPROD[7].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[7].specular : STATE.LIGHTPROD[7].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[7].front.ambient : STATE.LIGHTPROD[7].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[7].front.diffuse : STATE.LIGHTPROD[7].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[7].front.specular : STATE.LIGHTPROD[7].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[7].back.ambient : STATE.LIGHTPROD[7].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[7].back.diffuse : STATE.LIGHTPROD[7].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[7].back.specular : STATE.LIGHTPROD[7].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.texgen[0].eye.s : STATE.TEXGEN[0].EYE.S : : -1 : 0 -#var float4 glstate.texgen[0].eye.t : STATE.TEXGEN[0].EYE.T : : -1 : 0 -#var float4 glstate.texgen[0].eye.r : STATE.TEXGEN[0].EYE.R : : -1 : 0 -#var float4 glstate.texgen[0].eye.q : STATE.TEXGEN[0].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[0].object.s : STATE.TEXGEN[0].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[0].object.t : STATE.TEXGEN[0].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[0].object.r : STATE.TEXGEN[0].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[0].object.q : STATE.TEXGEN[0].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[1].eye.s : STATE.TEXGEN[1].EYE.S : : -1 : 0 -#var float4 glstate.texgen[1].eye.t : STATE.TEXGEN[1].EYE.T : : -1 : 0 -#var float4 glstate.texgen[1].eye.r : STATE.TEXGEN[1].EYE.R : : -1 : 0 -#var float4 glstate.texgen[1].eye.q : STATE.TEXGEN[1].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[1].object.s : STATE.TEXGEN[1].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[1].object.t : STATE.TEXGEN[1].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[1].object.r : STATE.TEXGEN[1].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[1].object.q : STATE.TEXGEN[1].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[2].eye.s : STATE.TEXGEN[2].EYE.S : : -1 : 0 -#var float4 glstate.texgen[2].eye.t : STATE.TEXGEN[2].EYE.T : : -1 : 0 -#var float4 glstate.texgen[2].eye.r : STATE.TEXGEN[2].EYE.R : : -1 : 0 -#var float4 glstate.texgen[2].eye.q : STATE.TEXGEN[2].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[2].object.s : STATE.TEXGEN[2].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[2].object.t : STATE.TEXGEN[2].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[2].object.r : STATE.TEXGEN[2].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[2].object.q : STATE.TEXGEN[2].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[3].eye.s : STATE.TEXGEN[3].EYE.S : : -1 : 0 -#var float4 glstate.texgen[3].eye.t : STATE.TEXGEN[3].EYE.T : : -1 : 0 -#var float4 glstate.texgen[3].eye.r : STATE.TEXGEN[3].EYE.R : : -1 : 0 -#var float4 glstate.texgen[3].eye.q : STATE.TEXGEN[3].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[3].object.s : STATE.TEXGEN[3].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[3].object.t : STATE.TEXGEN[3].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[3].object.r : STATE.TEXGEN[3].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[3].object.q : STATE.TEXGEN[3].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[4].eye.s : STATE.TEXGEN[4].EYE.S : : -1 : 0 -#var float4 glstate.texgen[4].eye.t : STATE.TEXGEN[4].EYE.T : : -1 : 0 -#var float4 glstate.texgen[4].eye.r : STATE.TEXGEN[4].EYE.R : : -1 : 0 -#var float4 glstate.texgen[4].eye.q : STATE.TEXGEN[4].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[4].object.s : STATE.TEXGEN[4].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[4].object.t : STATE.TEXGEN[4].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[4].object.r : STATE.TEXGEN[4].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[4].object.q : STATE.TEXGEN[4].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[5].eye.s : STATE.TEXGEN[5].EYE.S : : -1 : 0 -#var float4 glstate.texgen[5].eye.t : STATE.TEXGEN[5].EYE.T : : -1 : 0 -#var float4 glstate.texgen[5].eye.r : STATE.TEXGEN[5].EYE.R : : -1 : 0 -#var float4 glstate.texgen[5].eye.q : STATE.TEXGEN[5].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[5].object.s : STATE.TEXGEN[5].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[5].object.t : STATE.TEXGEN[5].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[5].object.r : STATE.TEXGEN[5].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[5].object.q : STATE.TEXGEN[5].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[6].eye.s : STATE.TEXGEN[6].EYE.S : : -1 : 0 -#var float4 glstate.texgen[6].eye.t : STATE.TEXGEN[6].EYE.T : : -1 : 0 -#var float4 glstate.texgen[6].eye.r : STATE.TEXGEN[6].EYE.R : : -1 : 0 -#var float4 glstate.texgen[6].eye.q : STATE.TEXGEN[6].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[6].object.s : STATE.TEXGEN[6].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[6].object.t : STATE.TEXGEN[6].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[6].object.r : STATE.TEXGEN[6].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[6].object.q : STATE.TEXGEN[6].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[7].eye.s : STATE.TEXGEN[7].EYE.S : : -1 : 0 -#var float4 glstate.texgen[7].eye.t : STATE.TEXGEN[7].EYE.T : : -1 : 0 -#var float4 glstate.texgen[7].eye.r : STATE.TEXGEN[7].EYE.R : : -1 : 0 -#var float4 glstate.texgen[7].eye.q : STATE.TEXGEN[7].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[7].object.s : STATE.TEXGEN[7].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[7].object.t : STATE.TEXGEN[7].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[7].object.r : STATE.TEXGEN[7].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[7].object.q : STATE.TEXGEN[7].OBJECT.Q : : -1 : 0 -#var float4 glstate.fog.color : STATE.FOG.COLOR : : -1 : 0 -#var float4 glstate.fog.params : STATE.FOG.PARAMS : : -1 : 0 -#var float4 glstate.clip[0].plane : STATE.CLIP[0].PLANE : : -1 : 0 -#var float4 glstate.clip[1].plane : STATE.CLIP[1].PLANE : : -1 : 0 -#var float4 glstate.clip[2].plane : STATE.CLIP[2].PLANE : : -1 : 0 -#var float4 glstate.clip[3].plane : STATE.CLIP[3].PLANE : : -1 : 0 -#var float4 glstate.clip[4].plane : STATE.CLIP[4].PLANE : : -1 : 0 -#var float4 glstate.clip[5].plane : STATE.CLIP[5].PLANE : : -1 : 0 -#var float4 glstate.clip[6].plane : STATE.CLIP[6].PLANE : : -1 : 0 -#var float4 glstate.clip[7].plane : STATE.CLIP[7].PLANE : : -1 : 0 -#var float glstate.point.size : STATE.POINT.SIZE : : -1 : 0 -#var float glstate.point.attenuation : STATE.POINT.ATTENUATION : : -1 : 0 -#var float4x4 glstate.matrix.modelview[0] : STATE.MATRIX.MODELVIEW[0] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[1] : STATE.MATRIX.MODELVIEW[1] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[2] : STATE.MATRIX.MODELVIEW[2] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[3] : STATE.MATRIX.MODELVIEW[3] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[4] : STATE.MATRIX.MODELVIEW[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[5] : STATE.MATRIX.MODELVIEW[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[6] : STATE.MATRIX.MODELVIEW[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[7] : STATE.MATRIX.MODELVIEW[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.projection : STATE.MATRIX.PROJECTION : , 4 : -1 : 0 -#var float4x4 glstate.matrix.mvp : STATE.MATRIX.MVP : c[0], 4 : -1 : 1 -#var float4x4 glstate.matrix.texture[0] : STATE.MATRIX.TEXTURE[0] : c[4], 4 : -1 : 1 -#var float4x4 glstate.matrix.texture[1] : STATE.MATRIX.TEXTURE[1] : c[8], 4 : -1 : 1 -#var float4x4 glstate.matrix.texture[2] : STATE.MATRIX.TEXTURE[2] : c[12], 4 : -1 : 1 -#var float4x4 glstate.matrix.texture[3] : STATE.MATRIX.TEXTURE[3] : c[16], 4 : -1 : 1 -#var float4x4 glstate.matrix.texture[4] : STATE.MATRIX.TEXTURE[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[5] : STATE.MATRIX.TEXTURE[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[6] : STATE.MATRIX.TEXTURE[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[7] : STATE.MATRIX.TEXTURE[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[0] : STATE.MATRIX.PALETTE[0] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[1] : STATE.MATRIX.PALETTE[1] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[2] : STATE.MATRIX.PALETTE[2] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[3] : STATE.MATRIX.PALETTE[3] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[4] : STATE.MATRIX.PALETTE[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[5] : STATE.MATRIX.PALETTE[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[6] : STATE.MATRIX.PALETTE[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[7] : STATE.MATRIX.PALETTE[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[0] : STATE.MATRIX.PROGRAM[0] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[1] : STATE.MATRIX.PROGRAM[1] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[2] : STATE.MATRIX.PROGRAM[2] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[3] : STATE.MATRIX.PROGRAM[3] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[4] : STATE.MATRIX.PROGRAM[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[5] : STATE.MATRIX.PROGRAM[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[6] : STATE.MATRIX.PROGRAM[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[7] : STATE.MATRIX.PROGRAM[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.projection : STATE.MATRIX.PROJECTION.INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.mvp : STATE.MATRIX.MVP.INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[0] : STATE.MATRIX.TEXTURE[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[1] : STATE.MATRIX.TEXTURE[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[2] : STATE.MATRIX.TEXTURE[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[3] : STATE.MATRIX.TEXTURE[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[4] : STATE.MATRIX.TEXTURE[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[5] : STATE.MATRIX.TEXTURE[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[6] : STATE.MATRIX.TEXTURE[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[7] : STATE.MATRIX.TEXTURE[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[0] : STATE.MATRIX.PALETTE[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[1] : STATE.MATRIX.PALETTE[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[2] : STATE.MATRIX.PALETTE[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[3] : STATE.MATRIX.PALETTE[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[4] : STATE.MATRIX.PALETTE[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[5] : STATE.MATRIX.PALETTE[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[6] : STATE.MATRIX.PALETTE[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[7] : STATE.MATRIX.PALETTE[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[0] : STATE.MATRIX.PROGRAM[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[1] : STATE.MATRIX.PROGRAM[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[2] : STATE.MATRIX.PROGRAM[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[3] : STATE.MATRIX.PROGRAM[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[4] : STATE.MATRIX.PROGRAM[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[5] : STATE.MATRIX.PROGRAM[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[6] : STATE.MATRIX.PROGRAM[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[7] : STATE.MATRIX.PROGRAM[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[0] : STATE.MATRIX.MODELVIEW[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[1] : STATE.MATRIX.MODELVIEW[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[2] : STATE.MATRIX.MODELVIEW[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[3] : STATE.MATRIX.MODELVIEW[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[4] : STATE.MATRIX.MODELVIEW[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[5] : STATE.MATRIX.MODELVIEW[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[6] : STATE.MATRIX.MODELVIEW[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[7] : STATE.MATRIX.MODELVIEW[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.projection : STATE.MATRIX.PROJECTION.TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.mvp : STATE.MATRIX.MVP.TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[0] : STATE.MATRIX.TEXTURE[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[1] : STATE.MATRIX.TEXTURE[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[2] : STATE.MATRIX.TEXTURE[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[3] : STATE.MATRIX.TEXTURE[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[4] : STATE.MATRIX.TEXTURE[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[5] : STATE.MATRIX.TEXTURE[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[6] : STATE.MATRIX.TEXTURE[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[7] : STATE.MATRIX.TEXTURE[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[0] : STATE.MATRIX.PALETTE[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[1] : STATE.MATRIX.PALETTE[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[2] : STATE.MATRIX.PALETTE[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[3] : STATE.MATRIX.PALETTE[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[4] : STATE.MATRIX.PALETTE[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[5] : STATE.MATRIX.PALETTE[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[6] : STATE.MATRIX.PALETTE[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[7] : STATE.MATRIX.PALETTE[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[0] : STATE.MATRIX.PROGRAM[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[1] : STATE.MATRIX.PROGRAM[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[2] : STATE.MATRIX.PROGRAM[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[3] : STATE.MATRIX.PROGRAM[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[4] : STATE.MATRIX.PROGRAM[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[5] : STATE.MATRIX.PROGRAM[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[6] : STATE.MATRIX.PROGRAM[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[7] : STATE.MATRIX.PROGRAM[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.projection : STATE.MATRIX.PROJECTION.INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.mvp : STATE.MATRIX.MVP.INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[0] : STATE.MATRIX.TEXTURE[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[1] : STATE.MATRIX.TEXTURE[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[2] : STATE.MATRIX.TEXTURE[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[3] : STATE.MATRIX.TEXTURE[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[4] : STATE.MATRIX.TEXTURE[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[5] : STATE.MATRIX.TEXTURE[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[6] : STATE.MATRIX.TEXTURE[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[7] : STATE.MATRIX.TEXTURE[7].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[0] : STATE.MATRIX.PALETTE[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[1] : STATE.MATRIX.PALETTE[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[2] : STATE.MATRIX.PALETTE[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[3] : STATE.MATRIX.PALETTE[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[4] : STATE.MATRIX.PALETTE[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[5] : STATE.MATRIX.PALETTE[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[6] : STATE.MATRIX.PALETTE[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[7] : STATE.MATRIX.PALETTE[7].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[0] : STATE.MATRIX.PROGRAM[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[1] : STATE.MATRIX.PROGRAM[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[2] : STATE.MATRIX.PROGRAM[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[3] : STATE.MATRIX.PROGRAM[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[4] : STATE.MATRIX.PROGRAM[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[5] : STATE.MATRIX.PROGRAM[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[6] : STATE.MATRIX.PROGRAM[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[7] : STATE.MATRIX.PROGRAM[7].INVTRANS : , 4 : -1 : 0 -#var float4 IN.position : $vin.POSITION : POSITION : 0 : 1 -#var float4 IN.tex0 : $vin.ATTR8 : ATTR8 : 0 : 1 -#var float3 IN.tangent : $vin.ATTR9 : ATTR9 : 0 : 1 -#var float3 IN.binormal : $vin.ATTR10 : ATTR10 : 0 : 1 -#var float3 IN.normal : $vin.ATTR11 : ATTR11 : 0 : 1 -#var float4 main.hposition : $vout.HPOS : HPOS : -1 : 1 -#var float4 main.position : $vout.TEX0 : TEX0 : -1 : 1 -#var float4 main.tex_diffuse_bump : $vout.TEX1 : TEX1 : -1 : 1 -#var float4 main.tex_specular : $vout.TEX2 : TEX2 : -1 : 1 -#var float4 main.tex_atten_xy_z : $vout.TEX3 : TEX3 : -1 : 1 -#var float3 main.tangent : $vout.TEX4 : TEX4 : -1 : 1 -#var float3 main.binormal : $vout.TEX5 : TEX5 : -1 : 1 -#var float3 main.normal : $vout.TEX6 : TEX6 : -1 : 1 -PARAM c[20] = { state.matrix.mvp, - state.matrix.texture[0], - state.matrix.texture[1], - state.matrix.texture[2], - state.matrix.texture[3] }; -TEMP R0; -DP4 result.position.w, vertex.position, c[3]; -DP4 result.position.z, vertex.position, c[2]; -DP4 result.position.y, vertex.position, c[1]; -DP4 result.position.x, vertex.position, c[0]; -DP4 R0.y, vertex.attrib[8], c[9]; -DP4 R0.x, vertex.attrib[8], c[8]; -MOV result.texcoord[0], vertex.position; -MOV result.texcoord[1].zw, R0.xyxy; -DP4 result.texcoord[1].y, vertex.attrib[8], c[5]; -DP4 result.texcoord[1].x, vertex.attrib[8], c[4]; -DP4 result.texcoord[2].w, vertex.attrib[8], c[15]; -DP4 result.texcoord[2].z, vertex.attrib[8], c[14]; -DP4 result.texcoord[2].y, vertex.attrib[8], c[13]; -DP4 result.texcoord[2].x, vertex.attrib[8], c[12]; -DP4 result.texcoord[3].w, vertex.position, c[19]; -DP4 result.texcoord[3].z, vertex.position, c[18]; -DP4 result.texcoord[3].y, vertex.position, c[17]; -DP4 result.texcoord[3].x, vertex.position, c[16]; -MOV result.texcoord[4].xyz, vertex.attrib[9]; -MOV result.texcoord[5].xyz, vertex.attrib[10]; -MOV result.texcoord[6].xyz, vertex.attrib[11]; -END -# 21 instructions, 1 R-regs diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glsl b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glsl deleted file mode 100644 index 6900b5af..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glsl +++ /dev/null @@ -1,58 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2004 Robert Beckebans -Please see the file "CONTRIBUTORS" for a list of contributors - -This program 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 program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - -attribute vec4 attr_TexCoord0; -attribute vec3 attr_Tangent; -attribute vec3 attr_Binormal; - -varying vec3 var_vertex; -varying vec4 var_tex_diffuse_bump; -varying vec2 var_tex_specular; -varying vec4 var_tex_atten_xy_z; -varying mat3 var_mat_os2ts; - -void main() -{ - // transform vertex position into homogenous clip-space - gl_Position = ftransform(); - - // assign position in object space - var_vertex = gl_Vertex.xyz; - - // transform texcoords into diffusemap texture space - var_tex_diffuse_bump.st = (gl_TextureMatrix[0] * attr_TexCoord0).st; - - // transform texcoords into bumpmap texture space - var_tex_diffuse_bump.pq = (gl_TextureMatrix[1] * attr_TexCoord0).st; - - // transform texcoords into specularmap texture space - var_tex_specular = (gl_TextureMatrix[2] * attr_TexCoord0).st; - - // calc light xy,z attenuation in light space - var_tex_atten_xy_z = gl_TextureMatrix[3] * gl_Vertex; - - - // construct object-space-to-tangent-space 3x3 matrix - var_mat_os2ts = mat3( attr_Tangent.x, attr_Binormal.x, gl_Normal.x, - attr_Tangent.y, attr_Binormal.y, gl_Normal.y, - attr_Tangent.z, attr_Binormal.z, gl_Normal.z ); -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/utils.cg b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/utils.cg deleted file mode 100644 index 63bfcb6c..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/utils.cg +++ /dev/null @@ -1,36 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2004 Robert Beckebans -Please see the file "AUTHORS" for a list of contributors - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - -// fresnel approximation -float fast_fresnel(float3 I, float3 N, float3 fresnel_values) -{ - float power = fresnel_values.x; - float scale = fresnel_values.y; - float bias = fresnel_values.z; - - return bias + pow(1.0 - dot(I, N), power) * scale; -} - -float3 CG_Expand(float3 v) -{ - return (v - 0.5) * 2; // expand a range-compressed vector -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_arbfp1.cg b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_arbfp1.cg deleted file mode 100644 index c80189c2..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_arbfp1.cg +++ /dev/null @@ -1,47 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2003 Robert Beckebans -Copyright (C) 2003, 2004 contributors of the XreaL project -Please see the file "AUTHORS" for a list of contributors - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - - -struct cg_vertex2fragment -{ - float4 position : POSITION; - float4 tex0 : TEXCOORD0; -}; - -struct cg_fragment2final -{ - float4 color : COLOR; -}; - - -cg_fragment2final main(in cg_vertex2fragment IN, - uniform sampler2D colormap) -{ - cg_fragment2final OUT; - - OUT.color.w = tex2D(colormap, IN.tex0.xy).a; - - OUT.color.xyz = 0; - - return OUT; -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_arbvp1.cg b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_arbvp1.cg deleted file mode 100644 index 4ffc6e27..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_arbvp1.cg +++ /dev/null @@ -1,49 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2003 Robert Beckebans -Copyright (C) 2003, 2004 contributors of the XreaL project -Please see the file "AUTHORS" for a list of contributors - -This program is free software; you can redistribute it and/or -modify it under the terms of the GNU General Public License -as published by the Free Software Foundation; either version 2 -of the License, or (at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - - -struct cg_app2vertex -{ - float4 position : ATTR0; - float4 texcoord0 : ATTR8; -}; - -struct cg_vertex2fragment -{ - float4 position : POSITION; - float4 tex0 : TEXCOORD0; -}; - - -cg_vertex2fragment main(cg_app2vertex IN) -{ - cg_vertex2fragment OUT; - - // transform vertex position into homogenous clip-space - OUT.position = mul(glstate.matrix.mvp, IN.position); - - // transform texcoords into 1st texture space - OUT.tex0 = mul(glstate.matrix.texture[0], IN.texcoord0); - - return OUT; -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_fp.glp b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_fp.glp deleted file mode 100644 index 5eb8b129..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_fp.glp +++ /dev/null @@ -1,19 +0,0 @@ -!!ARBfp1.0 -# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 -# command line args: -profile arbfp1 -# source file: ..\..\setup\data\tools\gl\zfill_arbfp1.cg -#vendor NVIDIA Corporation -#version 1.0.02 -#profile arbfp1 -#program main -#semantic main.colormap -#var float4 IN.position : : : 0 : 0 -#var float4 IN.tex0 : $vin.TEX0 : TEX0 : 0 : 1 -#var sampler2D colormap : : texunit 0 : 1 : 1 -#var float4 main.color : $vout.COL : COL : -1 : 1 -#const c[0] = 0 -PARAM c[1] = { { 0 } }; -MOV result.color.xyz, c[0].x; -TEX result.color.w, fragment.texcoord[0], texture[0], 2D; -END -# 2 instructions, 0 R-regs diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_fp.glsl b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_fp.glsl deleted file mode 100644 index 537db670..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_fp.glsl +++ /dev/null @@ -1,29 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2004 Robert Beckebans -Please see the file "CONTRIBUTORS" for a list of contributors - -This program 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 program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - -uniform sampler2D u_colormap; - -void main() -{ - gl_FragColor.a = texture2D(u_colormap, gl_TexCoord[0].st).a; - gl_FragColor.rgb = vec3(0.0, 0.0, 0.0); -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_vp.glp b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_vp.glp deleted file mode 100644 index f6eda0c0..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_vp.glp +++ /dev/null @@ -1,384 +0,0 @@ -!!ARBvp1.0 -# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 -# command line args: -profile arbvp1 -# source file: ..\..\setup\data\tools\gl\zfill_arbvp1.cg -#vendor NVIDIA Corporation -#version 1.0.02 -#profile arbvp1 -#program main -#semantic glstate : STATE -#var float4 glstate.material.ambient : STATE.MATERIAL.AMBIENT : : -1 : 0 -#var float4 glstate.material.diffuse : STATE.MATERIAL.DIFFUSE : : -1 : 0 -#var float4 glstate.material.specular : STATE.MATERIAL.SPECULAR : : -1 : 0 -#var float4 glstate.material.emission : STATE.MATERIAL.EMISSION : : -1 : 0 -#var float4 glstate.material.shininess : STATE.MATERIAL.SHININESS : : -1 : 0 -#var float4 glstate.material.front.ambient : STATE.MATERIAL.FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.material.front.diffuse : STATE.MATERIAL.FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.material.front.specular : STATE.MATERIAL.FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.material.front.emission : STATE.MATERIAL.FRONT.EMISSION : : -1 : 0 -#var float4 glstate.material.front.shininess : STATE.MATERIAL.FRONT.SHININESS : : -1 : 0 -#var float4 glstate.material.back.ambient : STATE.MATERIAL.BACK.AMBIENT : : -1 : 0 -#var float4 glstate.material.back.diffuse : STATE.MATERIAL.BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.material.back.specular : STATE.MATERIAL.BACK.SPECULAR : : -1 : 0 -#var float4 glstate.material.back.emission : STATE.MATERIAL.BACK.EMISSION : : -1 : 0 -#var float4 glstate.material.back.shininess : STATE.MATERIAL.BACK.SHININESS : : -1 : 0 -#var float4 glstate.light[0].ambient : STATE.LIGHT[0].AMBIENT : : -1 : 0 -#var float4 glstate.light[0].diffuse : STATE.LIGHT[0].DIFFUSE : : -1 : 0 -#var float4 glstate.light[0].specular : STATE.LIGHT[0].SPECULAR : : -1 : 0 -#var float4 glstate.light[0].position : STATE.LIGHT[0].POSITION : : -1 : 0 -#var float4 glstate.light[0].attenuation : STATE.LIGHT[0].ATTENUATION : : -1 : 0 -#var float4 glstate.light[0].spot.direction : STATE.LIGHT[0].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[0].half : STATE.LIGHT[0].HALF : : -1 : 0 -#var float4 glstate.light[1].ambient : STATE.LIGHT[1].AMBIENT : : -1 : 0 -#var float4 glstate.light[1].diffuse : STATE.LIGHT[1].DIFFUSE : : -1 : 0 -#var float4 glstate.light[1].specular : STATE.LIGHT[1].SPECULAR : : -1 : 0 -#var float4 glstate.light[1].position : STATE.LIGHT[1].POSITION : : -1 : 0 -#var float4 glstate.light[1].attenuation : STATE.LIGHT[1].ATTENUATION : : -1 : 0 -#var float4 glstate.light[1].spot.direction : STATE.LIGHT[1].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[1].half : STATE.LIGHT[1].HALF : : -1 : 0 -#var float4 glstate.light[2].ambient : STATE.LIGHT[2].AMBIENT : : -1 : 0 -#var float4 glstate.light[2].diffuse : STATE.LIGHT[2].DIFFUSE : : -1 : 0 -#var float4 glstate.light[2].specular : STATE.LIGHT[2].SPECULAR : : -1 : 0 -#var float4 glstate.light[2].position : STATE.LIGHT[2].POSITION : : -1 : 0 -#var float4 glstate.light[2].attenuation : STATE.LIGHT[2].ATTENUATION : : -1 : 0 -#var float4 glstate.light[2].spot.direction : STATE.LIGHT[2].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[2].half : STATE.LIGHT[2].HALF : : -1 : 0 -#var float4 glstate.light[3].ambient : STATE.LIGHT[3].AMBIENT : : -1 : 0 -#var float4 glstate.light[3].diffuse : STATE.LIGHT[3].DIFFUSE : : -1 : 0 -#var float4 glstate.light[3].specular : STATE.LIGHT[3].SPECULAR : : -1 : 0 -#var float4 glstate.light[3].position : STATE.LIGHT[3].POSITION : : -1 : 0 -#var float4 glstate.light[3].attenuation : STATE.LIGHT[3].ATTENUATION : : -1 : 0 -#var float4 glstate.light[3].spot.direction : STATE.LIGHT[3].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[3].half : STATE.LIGHT[3].HALF : : -1 : 0 -#var float4 glstate.light[4].ambient : STATE.LIGHT[4].AMBIENT : : -1 : 0 -#var float4 glstate.light[4].diffuse : STATE.LIGHT[4].DIFFUSE : : -1 : 0 -#var float4 glstate.light[4].specular : STATE.LIGHT[4].SPECULAR : : -1 : 0 -#var float4 glstate.light[4].position : STATE.LIGHT[4].POSITION : : -1 : 0 -#var float4 glstate.light[4].attenuation : STATE.LIGHT[4].ATTENUATION : : -1 : 0 -#var float4 glstate.light[4].spot.direction : STATE.LIGHT[4].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[4].half : STATE.LIGHT[4].HALF : : -1 : 0 -#var float4 glstate.light[5].ambient : STATE.LIGHT[5].AMBIENT : : -1 : 0 -#var float4 glstate.light[5].diffuse : STATE.LIGHT[5].DIFFUSE : : -1 : 0 -#var float4 glstate.light[5].specular : STATE.LIGHT[5].SPECULAR : : -1 : 0 -#var float4 glstate.light[5].position : STATE.LIGHT[5].POSITION : : -1 : 0 -#var float4 glstate.light[5].attenuation : STATE.LIGHT[5].ATTENUATION : : -1 : 0 -#var float4 glstate.light[5].spot.direction : STATE.LIGHT[5].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[5].half : STATE.LIGHT[5].HALF : : -1 : 0 -#var float4 glstate.light[6].ambient : STATE.LIGHT[6].AMBIENT : : -1 : 0 -#var float4 glstate.light[6].diffuse : STATE.LIGHT[6].DIFFUSE : : -1 : 0 -#var float4 glstate.light[6].specular : STATE.LIGHT[6].SPECULAR : : -1 : 0 -#var float4 glstate.light[6].position : STATE.LIGHT[6].POSITION : : -1 : 0 -#var float4 glstate.light[6].attenuation : STATE.LIGHT[6].ATTENUATION : : -1 : 0 -#var float4 glstate.light[6].spot.direction : STATE.LIGHT[6].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[6].half : STATE.LIGHT[6].HALF : : -1 : 0 -#var float4 glstate.light[7].ambient : STATE.LIGHT[7].AMBIENT : : -1 : 0 -#var float4 glstate.light[7].diffuse : STATE.LIGHT[7].DIFFUSE : : -1 : 0 -#var float4 glstate.light[7].specular : STATE.LIGHT[7].SPECULAR : : -1 : 0 -#var float4 glstate.light[7].position : STATE.LIGHT[7].POSITION : : -1 : 0 -#var float4 glstate.light[7].attenuation : STATE.LIGHT[7].ATTENUATION : : -1 : 0 -#var float4 glstate.light[7].spot.direction : STATE.LIGHT[7].SPOT.DIRECTION : : -1 : 0 -#var float4 glstate.light[7].half : STATE.LIGHT[7].HALF : : -1 : 0 -#var float4 glstate.lightmodel.ambient : STATE.LIGHTMODEL.AMBIENT : : -1 : 0 -#var float4 glstate.lightmodel.scenecolor : STATE.LIGHTMODEL.SCENECOLOR : : -1 : 0 -#var float4 glstate.lightmodel.front.scenecolor : STATE.LIGHTMODEL.FRONT.SCENECOLOR : : -1 : 0 -#var float4 glstate.lightmodel.back.scenecolor : STATE.LIGHTMODEL.BACK.SCENECOLOR : : -1 : 0 -#var float4 glstate.lightprod[0].ambient : STATE.LIGHTPROD[0].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[0].diffuse : STATE.LIGHTPROD[0].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[0].specular : STATE.LIGHTPROD[0].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[0].front.ambient : STATE.LIGHTPROD[0].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[0].front.diffuse : STATE.LIGHTPROD[0].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[0].front.specular : STATE.LIGHTPROD[0].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[0].back.ambient : STATE.LIGHTPROD[0].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[0].back.diffuse : STATE.LIGHTPROD[0].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[0].back.specular : STATE.LIGHTPROD[0].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[1].ambient : STATE.LIGHTPROD[1].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[1].diffuse : STATE.LIGHTPROD[1].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[1].specular : STATE.LIGHTPROD[1].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[1].front.ambient : STATE.LIGHTPROD[1].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[1].front.diffuse : STATE.LIGHTPROD[1].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[1].front.specular : STATE.LIGHTPROD[1].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[1].back.ambient : STATE.LIGHTPROD[1].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[1].back.diffuse : STATE.LIGHTPROD[1].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[1].back.specular : STATE.LIGHTPROD[1].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[2].ambient : STATE.LIGHTPROD[2].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[2].diffuse : STATE.LIGHTPROD[2].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[2].specular : STATE.LIGHTPROD[2].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[2].front.ambient : STATE.LIGHTPROD[2].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[2].front.diffuse : STATE.LIGHTPROD[2].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[2].front.specular : STATE.LIGHTPROD[2].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[2].back.ambient : STATE.LIGHTPROD[2].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[2].back.diffuse : STATE.LIGHTPROD[2].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[2].back.specular : STATE.LIGHTPROD[2].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[3].ambient : STATE.LIGHTPROD[3].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[3].diffuse : STATE.LIGHTPROD[3].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[3].specular : STATE.LIGHTPROD[3].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[3].front.ambient : STATE.LIGHTPROD[3].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[3].front.diffuse : STATE.LIGHTPROD[3].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[3].front.specular : STATE.LIGHTPROD[3].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[3].back.ambient : STATE.LIGHTPROD[3].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[3].back.diffuse : STATE.LIGHTPROD[3].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[3].back.specular : STATE.LIGHTPROD[3].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[4].ambient : STATE.LIGHTPROD[4].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[4].diffuse : STATE.LIGHTPROD[4].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[4].specular : STATE.LIGHTPROD[4].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[4].front.ambient : STATE.LIGHTPROD[4].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[4].front.diffuse : STATE.LIGHTPROD[4].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[4].front.specular : STATE.LIGHTPROD[4].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[4].back.ambient : STATE.LIGHTPROD[4].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[4].back.diffuse : STATE.LIGHTPROD[4].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[4].back.specular : STATE.LIGHTPROD[4].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[5].ambient : STATE.LIGHTPROD[5].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[5].diffuse : STATE.LIGHTPROD[5].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[5].specular : STATE.LIGHTPROD[5].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[5].front.ambient : STATE.LIGHTPROD[5].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[5].front.diffuse : STATE.LIGHTPROD[5].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[5].front.specular : STATE.LIGHTPROD[5].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[5].back.ambient : STATE.LIGHTPROD[5].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[5].back.diffuse : STATE.LIGHTPROD[5].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[5].back.specular : STATE.LIGHTPROD[5].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[6].ambient : STATE.LIGHTPROD[6].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[6].diffuse : STATE.LIGHTPROD[6].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[6].specular : STATE.LIGHTPROD[6].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[6].front.ambient : STATE.LIGHTPROD[6].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[6].front.diffuse : STATE.LIGHTPROD[6].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[6].front.specular : STATE.LIGHTPROD[6].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[6].back.ambient : STATE.LIGHTPROD[6].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[6].back.diffuse : STATE.LIGHTPROD[6].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[6].back.specular : STATE.LIGHTPROD[6].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[7].ambient : STATE.LIGHTPROD[7].AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[7].diffuse : STATE.LIGHTPROD[7].DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[7].specular : STATE.LIGHTPROD[7].SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[7].front.ambient : STATE.LIGHTPROD[7].FRONT.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[7].front.diffuse : STATE.LIGHTPROD[7].FRONT.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[7].front.specular : STATE.LIGHTPROD[7].FRONT.SPECULAR : : -1 : 0 -#var float4 glstate.lightprod[7].back.ambient : STATE.LIGHTPROD[7].BACK.AMBIENT : : -1 : 0 -#var float4 glstate.lightprod[7].back.diffuse : STATE.LIGHTPROD[7].BACK.DIFFUSE : : -1 : 0 -#var float4 glstate.lightprod[7].back.specular : STATE.LIGHTPROD[7].BACK.SPECULAR : : -1 : 0 -#var float4 glstate.texgen[0].eye.s : STATE.TEXGEN[0].EYE.S : : -1 : 0 -#var float4 glstate.texgen[0].eye.t : STATE.TEXGEN[0].EYE.T : : -1 : 0 -#var float4 glstate.texgen[0].eye.r : STATE.TEXGEN[0].EYE.R : : -1 : 0 -#var float4 glstate.texgen[0].eye.q : STATE.TEXGEN[0].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[0].object.s : STATE.TEXGEN[0].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[0].object.t : STATE.TEXGEN[0].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[0].object.r : STATE.TEXGEN[0].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[0].object.q : STATE.TEXGEN[0].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[1].eye.s : STATE.TEXGEN[1].EYE.S : : -1 : 0 -#var float4 glstate.texgen[1].eye.t : STATE.TEXGEN[1].EYE.T : : -1 : 0 -#var float4 glstate.texgen[1].eye.r : STATE.TEXGEN[1].EYE.R : : -1 : 0 -#var float4 glstate.texgen[1].eye.q : STATE.TEXGEN[1].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[1].object.s : STATE.TEXGEN[1].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[1].object.t : STATE.TEXGEN[1].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[1].object.r : STATE.TEXGEN[1].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[1].object.q : STATE.TEXGEN[1].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[2].eye.s : STATE.TEXGEN[2].EYE.S : : -1 : 0 -#var float4 glstate.texgen[2].eye.t : STATE.TEXGEN[2].EYE.T : : -1 : 0 -#var float4 glstate.texgen[2].eye.r : STATE.TEXGEN[2].EYE.R : : -1 : 0 -#var float4 glstate.texgen[2].eye.q : STATE.TEXGEN[2].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[2].object.s : STATE.TEXGEN[2].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[2].object.t : STATE.TEXGEN[2].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[2].object.r : STATE.TEXGEN[2].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[2].object.q : STATE.TEXGEN[2].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[3].eye.s : STATE.TEXGEN[3].EYE.S : : -1 : 0 -#var float4 glstate.texgen[3].eye.t : STATE.TEXGEN[3].EYE.T : : -1 : 0 -#var float4 glstate.texgen[3].eye.r : STATE.TEXGEN[3].EYE.R : : -1 : 0 -#var float4 glstate.texgen[3].eye.q : STATE.TEXGEN[3].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[3].object.s : STATE.TEXGEN[3].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[3].object.t : STATE.TEXGEN[3].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[3].object.r : STATE.TEXGEN[3].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[3].object.q : STATE.TEXGEN[3].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[4].eye.s : STATE.TEXGEN[4].EYE.S : : -1 : 0 -#var float4 glstate.texgen[4].eye.t : STATE.TEXGEN[4].EYE.T : : -1 : 0 -#var float4 glstate.texgen[4].eye.r : STATE.TEXGEN[4].EYE.R : : -1 : 0 -#var float4 glstate.texgen[4].eye.q : STATE.TEXGEN[4].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[4].object.s : STATE.TEXGEN[4].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[4].object.t : STATE.TEXGEN[4].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[4].object.r : STATE.TEXGEN[4].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[4].object.q : STATE.TEXGEN[4].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[5].eye.s : STATE.TEXGEN[5].EYE.S : : -1 : 0 -#var float4 glstate.texgen[5].eye.t : STATE.TEXGEN[5].EYE.T : : -1 : 0 -#var float4 glstate.texgen[5].eye.r : STATE.TEXGEN[5].EYE.R : : -1 : 0 -#var float4 glstate.texgen[5].eye.q : STATE.TEXGEN[5].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[5].object.s : STATE.TEXGEN[5].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[5].object.t : STATE.TEXGEN[5].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[5].object.r : STATE.TEXGEN[5].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[5].object.q : STATE.TEXGEN[5].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[6].eye.s : STATE.TEXGEN[6].EYE.S : : -1 : 0 -#var float4 glstate.texgen[6].eye.t : STATE.TEXGEN[6].EYE.T : : -1 : 0 -#var float4 glstate.texgen[6].eye.r : STATE.TEXGEN[6].EYE.R : : -1 : 0 -#var float4 glstate.texgen[6].eye.q : STATE.TEXGEN[6].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[6].object.s : STATE.TEXGEN[6].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[6].object.t : STATE.TEXGEN[6].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[6].object.r : STATE.TEXGEN[6].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[6].object.q : STATE.TEXGEN[6].OBJECT.Q : : -1 : 0 -#var float4 glstate.texgen[7].eye.s : STATE.TEXGEN[7].EYE.S : : -1 : 0 -#var float4 glstate.texgen[7].eye.t : STATE.TEXGEN[7].EYE.T : : -1 : 0 -#var float4 glstate.texgen[7].eye.r : STATE.TEXGEN[7].EYE.R : : -1 : 0 -#var float4 glstate.texgen[7].eye.q : STATE.TEXGEN[7].EYE.Q : : -1 : 0 -#var float4 glstate.texgen[7].object.s : STATE.TEXGEN[7].OBJECT.S : : -1 : 0 -#var float4 glstate.texgen[7].object.t : STATE.TEXGEN[7].OBJECT.T : : -1 : 0 -#var float4 glstate.texgen[7].object.r : STATE.TEXGEN[7].OBJECT.R : : -1 : 0 -#var float4 glstate.texgen[7].object.q : STATE.TEXGEN[7].OBJECT.Q : : -1 : 0 -#var float4 glstate.fog.color : STATE.FOG.COLOR : : -1 : 0 -#var float4 glstate.fog.params : STATE.FOG.PARAMS : : -1 : 0 -#var float4 glstate.clip[0].plane : STATE.CLIP[0].PLANE : : -1 : 0 -#var float4 glstate.clip[1].plane : STATE.CLIP[1].PLANE : : -1 : 0 -#var float4 glstate.clip[2].plane : STATE.CLIP[2].PLANE : : -1 : 0 -#var float4 glstate.clip[3].plane : STATE.CLIP[3].PLANE : : -1 : 0 -#var float4 glstate.clip[4].plane : STATE.CLIP[4].PLANE : : -1 : 0 -#var float4 glstate.clip[5].plane : STATE.CLIP[5].PLANE : : -1 : 0 -#var float4 glstate.clip[6].plane : STATE.CLIP[6].PLANE : : -1 : 0 -#var float4 glstate.clip[7].plane : STATE.CLIP[7].PLANE : : -1 : 0 -#var float glstate.point.size : STATE.POINT.SIZE : : -1 : 0 -#var float glstate.point.attenuation : STATE.POINT.ATTENUATION : : -1 : 0 -#var float4x4 glstate.matrix.modelview[0] : STATE.MATRIX.MODELVIEW[0] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[1] : STATE.MATRIX.MODELVIEW[1] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[2] : STATE.MATRIX.MODELVIEW[2] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[3] : STATE.MATRIX.MODELVIEW[3] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[4] : STATE.MATRIX.MODELVIEW[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[5] : STATE.MATRIX.MODELVIEW[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[6] : STATE.MATRIX.MODELVIEW[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.modelview[7] : STATE.MATRIX.MODELVIEW[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.projection : STATE.MATRIX.PROJECTION : , 4 : -1 : 0 -#var float4x4 glstate.matrix.mvp : STATE.MATRIX.MVP : c[0], 4 : -1 : 1 -#var float4x4 glstate.matrix.texture[0] : STATE.MATRIX.TEXTURE[0] : c[4], 4 : -1 : 1 -#var float4x4 glstate.matrix.texture[1] : STATE.MATRIX.TEXTURE[1] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[2] : STATE.MATRIX.TEXTURE[2] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[3] : STATE.MATRIX.TEXTURE[3] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[4] : STATE.MATRIX.TEXTURE[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[5] : STATE.MATRIX.TEXTURE[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[6] : STATE.MATRIX.TEXTURE[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.texture[7] : STATE.MATRIX.TEXTURE[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[0] : STATE.MATRIX.PALETTE[0] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[1] : STATE.MATRIX.PALETTE[1] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[2] : STATE.MATRIX.PALETTE[2] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[3] : STATE.MATRIX.PALETTE[3] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[4] : STATE.MATRIX.PALETTE[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[5] : STATE.MATRIX.PALETTE[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[6] : STATE.MATRIX.PALETTE[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.palette[7] : STATE.MATRIX.PALETTE[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[0] : STATE.MATRIX.PROGRAM[0] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[1] : STATE.MATRIX.PROGRAM[1] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[2] : STATE.MATRIX.PROGRAM[2] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[3] : STATE.MATRIX.PROGRAM[3] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[4] : STATE.MATRIX.PROGRAM[4] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[5] : STATE.MATRIX.PROGRAM[5] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[6] : STATE.MATRIX.PROGRAM[6] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.program[7] : STATE.MATRIX.PROGRAM[7] : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.projection : STATE.MATRIX.PROJECTION.INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.mvp : STATE.MATRIX.MVP.INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[0] : STATE.MATRIX.TEXTURE[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[1] : STATE.MATRIX.TEXTURE[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[2] : STATE.MATRIX.TEXTURE[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[3] : STATE.MATRIX.TEXTURE[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[4] : STATE.MATRIX.TEXTURE[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[5] : STATE.MATRIX.TEXTURE[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[6] : STATE.MATRIX.TEXTURE[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.texture[7] : STATE.MATRIX.TEXTURE[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[0] : STATE.MATRIX.PALETTE[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[1] : STATE.MATRIX.PALETTE[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[2] : STATE.MATRIX.PALETTE[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[3] : STATE.MATRIX.PALETTE[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[4] : STATE.MATRIX.PALETTE[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[5] : STATE.MATRIX.PALETTE[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[6] : STATE.MATRIX.PALETTE[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.palette[7] : STATE.MATRIX.PALETTE[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[0] : STATE.MATRIX.PROGRAM[0].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[1] : STATE.MATRIX.PROGRAM[1].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[2] : STATE.MATRIX.PROGRAM[2].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[3] : STATE.MATRIX.PROGRAM[3].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[4] : STATE.MATRIX.PROGRAM[4].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[5] : STATE.MATRIX.PROGRAM[5].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[6] : STATE.MATRIX.PROGRAM[6].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.inverse.program[7] : STATE.MATRIX.PROGRAM[7].INVERSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[0] : STATE.MATRIX.MODELVIEW[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[1] : STATE.MATRIX.MODELVIEW[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[2] : STATE.MATRIX.MODELVIEW[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[3] : STATE.MATRIX.MODELVIEW[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[4] : STATE.MATRIX.MODELVIEW[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[5] : STATE.MATRIX.MODELVIEW[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[6] : STATE.MATRIX.MODELVIEW[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.modelview[7] : STATE.MATRIX.MODELVIEW[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.projection : STATE.MATRIX.PROJECTION.TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.mvp : STATE.MATRIX.MVP.TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[0] : STATE.MATRIX.TEXTURE[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[1] : STATE.MATRIX.TEXTURE[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[2] : STATE.MATRIX.TEXTURE[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[3] : STATE.MATRIX.TEXTURE[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[4] : STATE.MATRIX.TEXTURE[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[5] : STATE.MATRIX.TEXTURE[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[6] : STATE.MATRIX.TEXTURE[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.texture[7] : STATE.MATRIX.TEXTURE[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[0] : STATE.MATRIX.PALETTE[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[1] : STATE.MATRIX.PALETTE[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[2] : STATE.MATRIX.PALETTE[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[3] : STATE.MATRIX.PALETTE[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[4] : STATE.MATRIX.PALETTE[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[5] : STATE.MATRIX.PALETTE[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[6] : STATE.MATRIX.PALETTE[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.palette[7] : STATE.MATRIX.PALETTE[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[0] : STATE.MATRIX.PROGRAM[0].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[1] : STATE.MATRIX.PROGRAM[1].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[2] : STATE.MATRIX.PROGRAM[2].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[3] : STATE.MATRIX.PROGRAM[3].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[4] : STATE.MATRIX.PROGRAM[4].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[5] : STATE.MATRIX.PROGRAM[5].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[6] : STATE.MATRIX.PROGRAM[6].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.transpose.program[7] : STATE.MATRIX.PROGRAM[7].TRANSPOSE : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.projection : STATE.MATRIX.PROJECTION.INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.mvp : STATE.MATRIX.MVP.INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[0] : STATE.MATRIX.TEXTURE[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[1] : STATE.MATRIX.TEXTURE[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[2] : STATE.MATRIX.TEXTURE[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[3] : STATE.MATRIX.TEXTURE[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[4] : STATE.MATRIX.TEXTURE[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[5] : STATE.MATRIX.TEXTURE[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[6] : STATE.MATRIX.TEXTURE[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.texture[7] : STATE.MATRIX.TEXTURE[7].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[0] : STATE.MATRIX.PALETTE[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[1] : STATE.MATRIX.PALETTE[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[2] : STATE.MATRIX.PALETTE[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[3] : STATE.MATRIX.PALETTE[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[4] : STATE.MATRIX.PALETTE[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[5] : STATE.MATRIX.PALETTE[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[6] : STATE.MATRIX.PALETTE[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.palette[7] : STATE.MATRIX.PALETTE[7].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[0] : STATE.MATRIX.PROGRAM[0].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[1] : STATE.MATRIX.PROGRAM[1].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[2] : STATE.MATRIX.PROGRAM[2].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[3] : STATE.MATRIX.PROGRAM[3].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[4] : STATE.MATRIX.PROGRAM[4].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[5] : STATE.MATRIX.PROGRAM[5].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[6] : STATE.MATRIX.PROGRAM[6].INVTRANS : , 4 : -1 : 0 -#var float4x4 glstate.matrix.invtrans.program[7] : STATE.MATRIX.PROGRAM[7].INVTRANS : , 4 : -1 : 0 -#var float4 IN.position : $vin.ATTR0 : ATTR0 : 0 : 1 -#var float4 IN.texcoord0 : $vin.ATTR8 : ATTR8 : 0 : 1 -#var float4 main.position : $vout.HPOS : HPOS : -1 : 1 -#var float4 main.tex0 : $vout.TEX0 : TEX0 : -1 : 1 -PARAM c[8] = { state.matrix.mvp, - state.matrix.texture[0] }; -DP4 result.position.w, vertex.attrib[0], c[3]; -DP4 result.position.z, vertex.attrib[0], c[2]; -DP4 result.position.y, vertex.attrib[0], c[1]; -DP4 result.position.x, vertex.attrib[0], c[0]; -DP4 result.texcoord[0].w, vertex.attrib[8], c[7]; -DP4 result.texcoord[0].z, vertex.attrib[8], c[6]; -DP4 result.texcoord[0].y, vertex.attrib[8], c[5]; -DP4 result.texcoord[0].x, vertex.attrib[8], c[4]; -END -# 8 instructions, 0 R-regs diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_vp.glsl b/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_vp.glsl deleted file mode 100644 index 4c81280e..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/gl/zfill_vp.glsl +++ /dev/null @@ -1,35 +0,0 @@ -/// ============================================================================ -/* -Copyright (C) 2004 Robert Beckebans -Please see the file "CONTRIBUTORS" for a list of contributors - -This program 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 program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - -See the GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -*/ -/// ============================================================================ - -attribute vec4 attr_TexCoord0; - -void main() -{ - // transform vertex position into homogenous clip-space - gl_Position = ftransform(); - - // transform texcoords - gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; - - // assign color - gl_FrontColor = gl_Color; -} diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/global.xlink b/misc/mediasource/extra/netradiant-src/setup/data/tools/global.xlink deleted file mode 100644 index 3ca47f1a..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/global.xlink +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_caulk.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_caulk.bmp deleted file mode 100644 index 52239503..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_caulk.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_cleanup.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_cleanup.bmp deleted file mode 100644 index 8939d5d7..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_cleanup.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_dropent.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_dropent.bmp deleted file mode 100644 index 2fcdcba3..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_dropent.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_merge.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_merge.bmp deleted file mode 100644 index 2184f7a7..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_merge.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_poly.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_poly.bmp deleted file mode 100644 index e714f3b9..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_poly.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_split.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_split.bmp deleted file mode 100644 index 7e1dc72f..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_split.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitcol.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitcol.bmp deleted file mode 100644 index 3d47fdcb..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitcol.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitrow.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitrow.bmp deleted file mode 100644 index 03b1ae3a..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitrow.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_trainpathplot.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_trainpathplot.bmp deleted file mode 100644 index 66537dc1..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_trainpathplot.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_treeplanter.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_treeplanter.bmp deleted file mode 100644 index 5c967ab2..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_treeplanter.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_turnedge.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_turnedge.bmp deleted file mode 100644 index b72cb2aa..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_turnedge.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_actorclip.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_actorclip.bmp deleted file mode 100644 index 4a2887c6..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_actorclip.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level1.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level1.bmp deleted file mode 100644 index 80a4b299..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level1.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level2.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level2.bmp deleted file mode 100644 index e84e2544..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level2.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level3.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level3.bmp deleted file mode 100644 index 141c3245..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level3.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level4.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level4.bmp deleted file mode 100644 index 3783a803..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level4.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level5.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level5.bmp deleted file mode 100644 index 8f62851c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level5.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level6.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level6.bmp deleted file mode 100644 index 418fdd28..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level6.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level7.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level7.bmp deleted file mode 100644 index d82dab61..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level7.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level8.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level8.bmp deleted file mode 100644 index c3809538..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level8.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_nodraw.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_nodraw.bmp deleted file mode 100644 index 3eaa529c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_nodraw.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_stepon.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_stepon.bmp deleted file mode 100644 index b73896fb..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_stepon.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_weaponclip.bmp b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_weaponclip.bmp deleted file mode 100644 index 799468ba..00000000 Binary files a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_weaponclip.bmp and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/bt-el1.txt b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/bt-el1.txt deleted file mode 100644 index f6485f94..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/bt-el1.txt +++ /dev/null @@ -1,17 +0,0 @@ -common/areaportal -common/clip -common/clusterportal -common/cushion -common/donotenter -common/full_clip -common/hint -common/missileclip -common/nodraw -common/nodrawnonsolid -common/nodrop -common/noimpact -common/origin -common/trigger -common/weapclip -liquid -fog \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/bt-el2.txt b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/bt-el2.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/door-tex-trim.txt b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/door-tex-trim.txt deleted file mode 100644 index d52ef76f..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/door-tex-trim.txt +++ /dev/null @@ -1,5 +0,0 @@ -base_support/support1rust -base_support/support1shiny -base_support/support2rust -base_support/wplat1_1 -base_support/plate2_5 \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/door-tex.txt b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/door-tex.txt deleted file mode 100644 index 69629989..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/door-tex.txt +++ /dev/null @@ -1,10 +0,0 @@ -base_door/shinymetaldoor -base_door/shinymetaldoor_outside -gothic_door/door02_bred -gothic_door/door02_bred2_shiny -gothic_door/door02_eblue2_shiny -gothic_door/door02_i_ornate5_fin -gothic_door/door02_j -gothic_door/door02_j3 -gothic_door/door02_j4 -gothic_door/door02_k2b \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/tp_ent.txt b/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/tp_ent.txt deleted file mode 100644 index f0645b34..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/plugins/bt/tp_ent.txt +++ /dev/null @@ -1,14 +0,0 @@ -{ - "entity" "misc_model" - - "offset" "-16" - - "model" "models/mapobjects/trees_sd/tree_a.md3" - "model" "models/mapobjects/trees_sd/tree_b.md3" - "model" "models/mapobjects/trees_sd/tree_c.md3" - "model" "models/mapobjects/trees_sd/tree_d.md3" - - "pitch" "-5" "5" - "yaw" "0" "360" - "scale" "1" "1.3" -} \ No newline at end of file diff --git a/misc/mediasource/extra/netradiant-src/setup/data/tools/q3data.qdt b/misc/mediasource/extra/netradiant-src/setup/data/tools/q3data.qdt deleted file mode 100644 index ba30ee12..00000000 --- a/misc/mediasource/extra/netradiant-src/setup/data/tools/q3data.qdt +++ /dev/null @@ -1,552 +0,0 @@ -$aseconvert models/mapobjects/spotlamp/spotlamp_x.ase -$exit - - -$aseconvert models/weapons2/machinegun/machinegun.ase -weapon -$aseconvert models/weapons2/bfg/bfg.ase -weapon -$aseconvert models/weapons2/railgun/railgun.ase -weapon -$aseconvert models/weapons2/shotgun/shotgun.ase -weapon - -$aseconvert models/weapons2/meshes/chaingun.ase -weapon -$aseconvert models/weapons2/meshes/flamethrower.ase -weapon -$aseconvert models/weapons2/meshes/grapple.ase -weapon -$aseconvert models/weapons2/meshes/grenadel.ase -weapon -$aseconvert models/weapons2/meshes/lightning.ase -weapon -$aseconvert models/weapons2/meshes/plasma.ase -weapon -$aseconvert models/weapons2/meshes/railgun.ase -weapon -$aseconvert models/weapons2/meshes/ricochet.ase -weapon -$aseconvert models/weapons2/meshes/rocketl.ase -weapon -$aseconvert models/weapons2/meshes/shotgun.ase -weapon - - -$aseconvert models/mapobjects/chain1.ase -$aseconvert models/mapobjects/chain2.ase -$aseconvert models/mapobjects/chain3.ase -$aseconvert models/mapobjects/chain4.ase - -$exit - -$aseanimconvert models/players/light/bandolier/bandolier.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/brandon/4brandon.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/cash/4cash.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/doom/doom.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/shauna/shauna.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/tim/4tim.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/visor/4visor.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/xian/4xian.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/carmack/carmack.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/heavy/paulj/4paulj.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/heavy/brock/brock.ase -origin 0 0 24 -playerparms 75 138 140 1 - -$exit - -// note: playerparms are "skipStart skipEnd maxUpperFrames maxHeadFrames" -$aseanimconvert models/players/medium/visor/4visor.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/visor/4visor.ase -lod 1 0 -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/visor/4visor.ase -lod 2 0 -origin 0 0 24 -playerparms 75 138 140 1 - - - -$aseconvert models/powerups/ammo/backpack.ase - -$aseconvert models/weapons2/meshes/assault.ase -weapon -$aseconvert models/weapons2/meshes/chaingun.ase -weapon -$aseconvert models/weapons2/meshes/flamethrower.ase -weapon -$aseconvert models/weapons2/meshes/grapple.ase -weapon -$aseconvert models/weapons2/meshes/grenadel.ase -weapon -$aseconvert models/weapons2/meshes/lightning.ase -weapon -$aseconvert models/weapons2/meshes/plasma.ase -weapon -$aseconvert models/weapons2/meshes/railgun.ase -weapon -$aseconvert models/weapons2/meshes/ricochet.ase -weapon -$aseconvert models/weapons2/meshes/rocketl.ase -weapon -$aseconvert models/weapons2/meshes/shotgun.ase -weapon - -$aseconvert models/mapobjects/arenalogo.ase - -// -// talk sprite -// -$modelname sprites/balloon -$cd sprites -$spritebase -8 -8 16 16 -$spriteshader sprites/balloon3.tga - -// plasma ball sprite -$modelname sprites/plasma -$cd sprites -$spritebase -16 -16 32 32 -$spriteshader sprites/plasma1.tga -$spriteshader sprites/plasma2.tga - -// -// player models -// note: playerparms are "skipStart skipEnd maxUpperFrames maxHeadFrames" -// -$aseanimconvert models/players/light/bandolier/bandolier.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/brandon/4brandon.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/cash/4cash.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/doom/doom.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/light/shauna/shauna.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/tim/4tim.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/visor/4visor.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/xian/4xian.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/medium/carmack/carmack.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/heavy/paulj/4paulj.ase -origin 0 0 24 -playerparms 75 138 140 1 -$aseanimconvert models/players/heavy/brock/brock.ase -origin 0 0 24 -playerparms 75 138 140 1 - -// -// weaphits -// -$modelname models/weaphits/bullet -$cd models/weaphits -$base bullet01.3ds -$frame bullet01.3ds -$frame bullet02.3ds -$frame bullet03.3ds -$frame bullet04.3ds -$frame bullet05.3ds -$frame bullet06.3ds -$skin bullet01.3ds -$skin bullet03.3ds -$skin bullet05.3ds - -$modelname models/weaphits/ring01 -$cd models/weaphits -$base ring01_1.3ds -$frame ring01_1.3ds -$frame ring01_2.3ds -$frame ring01_3.3ds -$frame ring01_4.3ds -$frame ring01_5.3ds -$frame ring01_6.3ds -$skin ring01_1.3ds -$skin ring01_3.3ds -$skin ring01_5.3ds - -$modelname models/weaphits/ring02 -$cd models/weaphits -$base ring02_1.3ds -$frame ring02_1.3ds -$frame ring02_2.3ds -$frame ring02_3.3ds -$frame ring02_4.3ds -$frame ring02_5.3ds -$frame ring02_6.3ds -$skin ring02_1.3ds -$skin ring02_3.3ds -$skin ring02_5.3ds - -$modelname models/weaphits/boomgra -$cd models/weaphits -$base boomgra1.3ds -$frame boomgra1.3ds -$frame boomgra2.3ds -$frame boomgra3.3ds -$frame boomgra4.3ds -$frame boomgra5.3ds -$frame boomgra6.3ds -$skin boomgra1.3ds -$skin boomgra3.3ds -$skin boomgra5.3ds - -$modelname models/weaphits/boom01 -$cd models/weaphits -$base boom01_1.3ds -$frame boom01_1.3ds -$frame boom01_2.3ds -$frame boom01_3.3ds -$frame boom01_4.3ds -$frame boom01_5.3ds -$frame boom01_6.3ds -$skin boom01_1.3ds -$skin boom01_3.3ds -$skin boom01_5.3ds - -$modelname models/weaphits/boom02 -$cd models/weaphits -$base boom02_1.3ds -$frame boom02_1.3ds -$frame boom02_2.3ds -$frame boom02_3.3ds -$frame boom02_4.3ds -$frame boom02_5.3ds -$frame boom02_6.3ds -$skin boom02_1.3ds -$skin boom02_3.3ds -$skin boom02_5.3ds - -$modelname models/weaphits/boom03 -$cd models/weaphits -$base boom03_1.3ds -$frame boom03_1.3ds -$frame boom03_2.3ds -$frame boom03_3.3ds -$frame boom03_4.3ds -$frame boom03_5.3ds -$frame boom03_6.3ds -$skin boom03_1.3ds -$skin boom03_3.3ds -$skin boom03_5.3ds - -$modelname models/weaphits/boom04 -$cd models/weaphits -$base boom04_1.3ds -$frame boom04_1.3ds -$frame boom04_2.3ds -$frame boom04_3.3ds -$frame boom04_4.3ds -$frame boom04_5.3ds -$frame boom04_6.3ds -$skin boom04_1.3ds -$skin boom04_3.3ds -$skin boom04_5.3ds - -$modelname models/weaphits/boom05 -$cd models/weaphits -$base boom05_1.3ds -$frame boom05_1.3ds -$frame boom05_2.3ds -$frame boom05_3.3ds -$frame boom05_4.3ds -$frame boom05_5.3ds -$frame boom05_6.3ds -$skin boom05_1.3ds -$skin boom05_3.3ds -$skin boom05_5.3ds - -// -// point powerups -// -$aseconvert models/powerups/points/small.ase -$aseconvert models/powerups/points/medium.ase -$aseconvert models/powerups/points/large.ase - -// -// ammo -// -$aseconvert models\powerups\ammo\bfgam.ASE -$aseconvert models\powerups\ammo\bfgam_1.ASE -$aseconvert models\powerups\ammo\bouncyam.ASE -$aseconvert models\powerups\ammo\bouncyam_1.ASE -$aseconvert models\powerups\ammo\carbineam.ASE -$aseconvert models\powerups\ammo\carbineam_1.ASE -$aseconvert models\powerups\ammo\flameam.ASE -$aseconvert models\powerups\ammo\flameam_1.ASE -$aseconvert models\powerups\ammo\grenadeam.ASE -$aseconvert models\powerups\ammo\grenadeam_1.ASE -$aseconvert models\powerups\ammo\lightningam.ASE -$aseconvert models\powerups\ammo\lightningam_1.ASE -$aseconvert models\powerups\ammo\machinegunam.ASE -$aseconvert models\powerups\ammo\machinegunam_1.ASE -$aseconvert models\powerups\ammo\plasmaam.ASE -$aseconvert models\powerups\ammo\plasmaam_1.ASE -$aseconvert models\powerups\ammo\railgunam.ASE -$aseconvert models\powerups\ammo\railgunam_1.ASE -$aseconvert models\powerups\ammo\rocketam.ASE -$aseconvert models\powerups\ammo\rocketam_1.ASE -$aseconvert models\powerups\ammo\shotgunam.ASE -$aseconvert models\powerups\ammo\shotgunam_1.ASE - -$aseconvert models/powerups/ammo/backpack.ase - -// -// missiles -// -$modelname models/ammo/plasma/plasma -$cd models/ammo/plasma -$base plasma1.3ds -$frame plasma1.3ds -$skin plasma1.3ds - -$modelname models/ammo/laser/laser -$cd models/ammo/laser -$base laser1.3ds -$frame laser1.3ds -$skin laser1.3ds - -$modelname models/ammo/rocket/rocket -$cd models/ammo/rocket -$base rocket1.3ds -$frame rocket1.3ds -$skin rocket1.3ds -$skin rocket2.3ds - -$aseconvert models/ammo/grenade1.ase -$aseconvert models/explosions/smoke2.ase - -// -// map objects -// -$aseconvert models/mapobjects/ceilinglamp1.ase -$aseconvert models/mapobjects/ceilinglamp2.ase -$aseconvert models/mapobjects/chain1.ase -$aseconvert models/mapobjects/chain2.ase -$aseconvert models/mapobjects/chain3.ase -$aseconvert models/mapobjects/chain4.ase -$aseconvert models/mapobjects/crux.ase -$aseconvert models/mapobjects/floorlamp1.ase -$aseconvert models/mapobjects/floorlamp2.ase -$aseconvert models/mapobjects/hook.ase -$aseconvert models/mapobjects/impale.ase -$aseconvert models/mapobjects/standinglamp1.ase -$aseconvert models/mapobjects/standinglamp2.ase -$aseconvert models/mapobjects/standinglamp3.ase -$aseconvert models/mapobjects/walllamp1.ase -$aseconvert models/mapobjects/walllamp2.ase -$aseconvert models/mapobjects/walllamp3.ase - - -// -// objects -// -$aseconvert models/objects/dmspot.ase -origin 0 0 24 -$aseconvert models/objects/box01.ase - -// -// weapons -// -$aseconvert models/weapons2/meshes/assault.ase -weapon -$aseconvert models/weapons2/meshes/bfg.ase -weapon -$aseconvert models/weapons2/meshes/chaingun.ase -weapon -$aseconvert models/weapons2/meshes/flamethrower.ase -weapon -$aseconvert models/weapons2/meshes/grapple.ase -weapon -$aseconvert models/weapons2/meshes/grenadel.ase -weapon -$aseconvert models/weapons2/meshes/lightning.ase -weapon -$aseconvert models/weapons2/meshes/plasma.ase -weapon -$aseconvert models/weapons2/meshes/railgun.ase -weapon -$aseconvert models/weapons2/meshes/ricochet.ase -weapon -$aseconvert models/weapons2/meshes/rocketl.ase -weapon -$aseconvert models/weapons2/meshes/shotgun.ase -weapon - -// -// blood -// -$modelname models/weaphits/blood -$cd models/weaphits -$spritebase -16 -16 32 32 -$spriteshader models/weaphits/blood201.tga -$spriteshader models/weaphits/blood202.tga -$spriteshader models/weaphits/blood203.tga -$spriteshader models/weaphits/blood204.tga -$spriteshader models/weaphits/blood205.tga - - -// -// missiles -// -$modelname models/ammo/plasma/plasma -$cd models/ammo/plasma -$base plasma1.3ds -$frame plasma1.3ds -$skin plasma1.3ds - -$modelname models/ammo/laser/laser -$cd models/ammo/laser -$base laser1.3ds -$frame laser1.3ds -$skin laser1.3ds - - -$modelname models/ammo/rocket/rocket -$cd models/ammo/rocket -$base rocket1.3ds -$frame rocket1.3ds -$skin rocket1.3ds -$skin rocket2.3ds - - -// weaphits - -$modelname models/weaphits/bullet -$cd models/weaphits -$base bullet01.3ds -$frame bullet01.3ds -$frame bullet02.3ds -$frame bullet03.3ds -$frame bullet04.3ds -$frame bullet05.3ds -$frame bullet06.3ds -$skin bullet01.3ds -$skin bullet03.3ds -$skin bullet05.3ds - -$modelname models/weaphits/ring01 -$cd models/weaphits -$base ring01_1.3ds -$frame ring01_1.3ds -$frame ring01_2.3ds -$frame ring01_3.3ds -$frame ring01_4.3ds -$frame ring01_5.3ds -$frame ring01_6.3ds -$skin ring01_1.3ds -$skin ring01_3.3ds -$skin ring01_5.3ds - -$modelname models/weaphits/ring02 -$cd models/weaphits -$base ring02_1.3ds -$frame ring02_1.3ds -$frame ring02_2.3ds -$frame ring02_3.3ds -$frame ring02_4.3ds -$frame ring02_5.3ds -$frame ring02_6.3ds -$skin ring02_1.3ds -$skin ring02_3.3ds -$skin ring02_5.3ds - -$modelname models/weaphits/boomgra -$cd models/weaphits -$base boomgra1.3ds -$frame boomgra1.3ds -$frame boomgra2.3ds -$frame boomgra3.3ds -$frame boomgra4.3ds -$frame boomgra5.3ds -$frame boomgra6.3ds -$skin boomgra1.3ds -$skin boomgra3.3ds -$skin boomgra5.3ds - -$modelname models/weaphits/boom01 -$cd models/weaphits -$base boom01_1.3ds -$frame boom01_1.3ds -$frame boom01_2.3ds -$frame boom01_3.3ds -$frame boom01_4.3ds -$frame boom01_5.3ds -$frame boom01_6.3ds -$skin boom01_1.3ds -$skin boom01_3.3ds -$skin boom01_5.3ds - -$modelname models/weaphits/boom02 -$cd models/weaphits -$base boom02_1.3ds -$frame boom02_1.3ds -$frame boom02_2.3ds -$frame boom02_3.3ds -$frame boom02_4.3ds -$frame boom02_5.3ds -$frame boom02_6.3ds -$skin boom02_1.3ds -$skin boom02_3.3ds -$skin boom02_5.3ds - -$modelname models/weaphits/boom03 -$cd models/weaphits -$base boom03_1.3ds -$frame boom03_1.3ds -$frame boom03_2.3ds -$frame boom03_3.3ds -$frame boom03_4.3ds -$frame boom03_5.3ds -$frame boom03_6.3ds -$skin boom03_1.3ds -$skin boom03_3.3ds -$skin boom03_5.3ds - -$modelname models/weaphits/boom04 -$cd models/weaphits -$base boom04_1.3ds -$frame boom04_1.3ds -$frame boom04_2.3ds -$frame boom04_3.3ds -$frame boom04_4.3ds -$frame boom04_5.3ds -$frame boom04_6.3ds -$skin boom04_1.3ds -$skin boom04_3.3ds -$skin boom04_5.3ds - -$modelname models/weaphits/boom05 -$cd models/weaphits -$base boom05_1.3ds -$frame boom05_1.3ds -$frame boom05_2.3ds -$frame boom05_3.3ds -$frame boom05_4.3ds -$frame boom05_5.3ds -$frame boom05_6.3ds -$skin boom05_1.3ds -$skin boom05_3.3ds -$skin boom05_5.3ds - - -// -// armor -// -$aseconvert models/powerups/armor/armor_red.ase -$aseconvert models/powerups/armor/armor_yel.ase -$aseconvert models/powerups/armor/armor_grn.ase -$aseconvert models/powerups/armor/shard.ase -$aseconvert models/powerups/armor/shard_sphere.ase -$aseconvert models/powerups/armor/shard_sphere_1.ase - -// -// health -// -$aseconvert models/powerups/health/small.ase -$aseconvert models/powerups/health/small_1.ase -$aseconvert models/powerups/health/medium.ase -$aseconvert models/powerups/health/medium_1.ase -$aseconvert models/powerups/health/large.ase -$aseconvert models/powerups/health/large_1.ase -$aseconvert models/powerups/health/mega.ase -$aseconvert models/powerups/health/mega_1.ase - -// -// holdable powerups -// -$aseconvert models/powerups/holdable/ringodeth.ase -$aseconvert models/powerups/holdable/medkit.ase -$aseconvert models/powerups/holdable/teleporter.ase - -// -// instant powerups -// -$aseconvert models/powerups/instant/enviro.ase -$aseconvert models/powerups/instant/enviro_1.ase -$aseconvert models/powerups/instant/enviro_ring.ase -$aseconvert models/powerups/instant/enviro_ring_1.ase -$aseconvert models/powerups/instant/flight.ase -$aseconvert models/powerups/instant/flight_1.ase -$aseconvert models/powerups/instant/flight_ring.ase -$aseconvert models/powerups/instant/flight_ring_1.ase -$aseconvert models/powerups/instant/haste.ase -$aseconvert models/powerups/instant/haste_1.ase -$aseconvert models/powerups/instant/haste_ring.ase -$aseconvert models/powerups/instant/haste_ring_1.ase -$aseconvert models/powerups/instant/invis.ase -$aseconvert models/powerups/instant/invis_1.ase -$aseconvert models/powerups/instant/invis_ring.ase -$aseconvert models/powerups/instant/invis_ring_1.ase -$aseconvert models/powerups/instant/scan.ase -$aseconvert models/powerups/instant/scan_1.ase -$aseconvert models/powerups/instant/scan_ring.ase -$aseconvert models/powerups/instant/scan_ring_1.ase -$aseconvert models/powerups/instant/quad.ase -$aseconvert models/powerups/instant/quad_1.ase -$aseconvert models/powerups/instant/quad_ring.ase -$aseconvert models/powerups/instant/quad_ring_1.ase -$aseconvert models/powerups/instant/regen.ase -$aseconvert models/powerups/instant/regen_1.ase -$aseconvert models/powerups/instant/regen_ring.ase -$aseconvert models/powerups/instant/regen_ring_1.ase - -$exit - -// -// maps -// -$maps test_box test_items mirror mirror2 - - -// -// misc -// -$file q3default.cfg - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/bspfile.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/bspfile.c deleted file mode 100644 index 05808c51..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/bspfile.c +++ /dev/null @@ -1,789 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "bspfile.h" -#include "scriplib.h" -#include "inout.h" - -void GetLeafNums (void); - -//============================================================================= - -int nummodels; -dmodel_t dmodels[MAX_MAP_MODELS]; - -int visdatasize; -byte dvisdata[MAX_MAP_VISIBILITY]; -dvis_t *dvis = (dvis_t *)dvisdata; - -int lightdatasize; -byte dlightdata[MAX_MAP_LIGHTING]; - -int entdatasize; -char dentdata[MAX_MAP_ENTSTRING]; - -int numleafs; -dleaf_t dleafs[MAX_MAP_LEAFS]; - -int numplanes; -dplane_t dplanes[MAX_MAP_PLANES]; - -int numvertexes; -dvertex_t dvertexes[MAX_MAP_VERTS]; - -int numnodes; -dnode_t dnodes[MAX_MAP_NODES]; - -int numtexinfo; -texinfo_t texinfo[MAX_MAP_TEXINFO]; - -int numfaces; -dface_t dfaces[MAX_MAP_FACES]; - -int numedges; -dedge_t dedges[MAX_MAP_EDGES]; - -int numleaffaces; -unsigned short dleaffaces[MAX_MAP_LEAFFACES]; - -int numleafbrushes; -unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; - -int numsurfedges; -int dsurfedges[MAX_MAP_SURFEDGES]; - -int numbrushes; -dbrush_t dbrushes[MAX_MAP_BRUSHES]; - -int numbrushsides; -dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; - -int numareas; -darea_t dareas[MAX_MAP_AREAS]; - -int numareaportals; -dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; - -byte dpop[256]; - -/* -=============== -CompressVis - -=============== -*/ -int CompressVis (byte *vis, byte *dest) -{ - int j; - int rep; - int visrow; - byte *dest_p; - - dest_p = dest; -// visrow = (r_numvisleafs + 7)>>3; - visrow = (dvis->numclusters + 7)>>3; - - for (j=0 ; j>3; - row = (dvis->numclusters+7)>>3; - out = decompressed; - - do - { - if (*in) - { - *out++ = *in++; - continue; - } - - c = in[1]; - if (!c) - Error ("DecompressVis: 0 repeat"); - in += 2; - while (c) - { - *out++ = 0; - c--; - } - } while (out - decompressed < row); -} - -//============================================================================= - -/* -============= -SwapBSPFile - -Byte swaps all data in a bsp file. -============= -*/ -void SwapBSPFile (qboolean todisk) -{ - int i, j; - dmodel_t *d; - - -// models - for (i=0 ; ifirstface = LittleLong (d->firstface); - d->numfaces = LittleLong (d->numfaces); - d->headnode = LittleLong (d->headnode); - - for (j=0 ; j<3 ; j++) - { - d->mins[j] = LittleFloat(d->mins[j]); - d->maxs[j] = LittleFloat(d->maxs[j]); - d->origin[j] = LittleFloat(d->origin[j]); - } - } - -// -// vertexes -// - for (i=0 ; inumclusters; - else - j = LittleLong(dvis->numclusters); - dvis->numclusters = LittleLong (dvis->numclusters); - for (i=0 ; ibitofs[i][0] = LittleLong (dvis->bitofs[i][0]); - dvis->bitofs[i][1] = LittleLong (dvis->bitofs[i][1]); - } -} - - -dheader_t *header; - -int CopyLump (int lump, void *dest, int size) -{ - int length, ofs; - - length = header->lumps[lump].filelen; - ofs = header->lumps[lump].fileofs; - - if (length % size) - Error ("LoadBSPFile: odd lump size"); - - memcpy (dest, (byte *)header + ofs, length); - - return length / size; -} - -/* -============= -LoadBSPFile -============= -*/ -void LoadBSPFile (char *filename) -{ - int i; - -// -// load the file header -// - LoadFile (filename, (void **)&header); - -// swap the header - for (i=0 ; i< sizeof(dheader_t)/4 ; i++) - ((int *)header)[i] = LittleLong ( ((int *)header)[i]); - - if (header->ident != IDBSPHEADER) - Error ("%s is not a IBSP file", filename); - if (header->version != BSPVERSION) - Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); - - nummodels = CopyLump (LUMP_MODELS, dmodels, sizeof(dmodel_t)); - numvertexes = CopyLump (LUMP_VERTEXES, dvertexes, sizeof(dvertex_t)); - numplanes = CopyLump (LUMP_PLANES, dplanes, sizeof(dplane_t)); - numleafs = CopyLump (LUMP_LEAFS, dleafs, sizeof(dleaf_t)); - numnodes = CopyLump (LUMP_NODES, dnodes, sizeof(dnode_t)); - numtexinfo = CopyLump (LUMP_TEXINFO, texinfo, sizeof(texinfo_t)); - numfaces = CopyLump (LUMP_FACES, dfaces, sizeof(dface_t)); - numleaffaces = CopyLump (LUMP_LEAFFACES, dleaffaces, sizeof(dleaffaces[0])); - numleafbrushes = CopyLump (LUMP_LEAFBRUSHES, dleafbrushes, sizeof(dleafbrushes[0])); - numsurfedges = CopyLump (LUMP_SURFEDGES, dsurfedges, sizeof(dsurfedges[0])); - numedges = CopyLump (LUMP_EDGES, dedges, sizeof(dedge_t)); - numbrushes = CopyLump (LUMP_BRUSHES, dbrushes, sizeof(dbrush_t)); - numbrushsides = CopyLump (LUMP_BRUSHSIDES, dbrushsides, sizeof(dbrushside_t)); - numareas = CopyLump (LUMP_AREAS, dareas, sizeof(darea_t)); - numareaportals = CopyLump (LUMP_AREAPORTALS, dareaportals, sizeof(dareaportal_t)); - - visdatasize = CopyLump (LUMP_VISIBILITY, dvisdata, 1); - lightdatasize = CopyLump (LUMP_LIGHTING, dlightdata, 1); - entdatasize = CopyLump (LUMP_ENTITIES, dentdata, 1); - - CopyLump (LUMP_POP, dpop, 1); - - free (header); // everything has been copied out - -// -// swap everything -// - SwapBSPFile (false); -} - - -/* -============= -LoadBSPFileTexinfo - -Only loads the texinfo lump, so qdata can scan for textures -============= -*/ -void LoadBSPFileTexinfo (char *filename) -{ - int i; - FILE *f; - int length, ofs; - - header = malloc(sizeof(dheader_t)); - - f = fopen (filename, "rb"); - fread (header, sizeof(dheader_t), 1, f); - -// swap the header - for (i=0 ; i< sizeof(dheader_t)/4 ; i++) - ((int *)header)[i] = LittleLong ( ((int *)header)[i]); - - if (header->ident != IDBSPHEADER) - Error ("%s is not a IBSP file", filename); - if (header->version != BSPVERSION) - Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); - - - length = header->lumps[LUMP_TEXINFO].filelen; - ofs = header->lumps[LUMP_TEXINFO].fileofs; - - fseek (f, ofs, SEEK_SET); - fread (texinfo, length, 1, f); - fclose (f); - - numtexinfo = length / sizeof(texinfo_t); - - free (header); // everything has been copied out - - SwapBSPFile (false); -} - - -//============================================================================ - -FILE *wadfile; -dheader_t outheader; - -void AddLump (int lumpnum, void *data, int len) -{ - lump_t *lump; - - lump = &header->lumps[lumpnum]; - - lump->fileofs = LittleLong( ftell(wadfile) ); - lump->filelen = LittleLong(len); - SafeWrite (wadfile, data, (len+3)&~3); -} - -/* -============= -WriteBSPFile - -Swaps the bsp file in place, so it should not be referenced again -============= -*/ -void WriteBSPFile (char *filename) -{ - header = &outheader; - memset (header, 0, sizeof(dheader_t)); - - SwapBSPFile (true); - - header->ident = LittleLong (IDBSPHEADER); - header->version = LittleLong (BSPVERSION); - - wadfile = SafeOpenWrite (filename); - SafeWrite (wadfile, header, sizeof(dheader_t)); // overwritten later - - AddLump (LUMP_PLANES, dplanes, numplanes*sizeof(dplane_t)); - AddLump (LUMP_LEAFS, dleafs, numleafs*sizeof(dleaf_t)); - AddLump (LUMP_VERTEXES, dvertexes, numvertexes*sizeof(dvertex_t)); - AddLump (LUMP_NODES, dnodes, numnodes*sizeof(dnode_t)); - AddLump (LUMP_TEXINFO, texinfo, numtexinfo*sizeof(texinfo_t)); - AddLump (LUMP_FACES, dfaces, numfaces*sizeof(dface_t)); - AddLump (LUMP_BRUSHES, dbrushes, numbrushes*sizeof(dbrush_t)); - AddLump (LUMP_BRUSHSIDES, dbrushsides, numbrushsides*sizeof(dbrushside_t)); - AddLump (LUMP_LEAFFACES, dleaffaces, numleaffaces*sizeof(dleaffaces[0])); - AddLump (LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes*sizeof(dleafbrushes[0])); - AddLump (LUMP_SURFEDGES, dsurfedges, numsurfedges*sizeof(dsurfedges[0])); - AddLump (LUMP_EDGES, dedges, numedges*sizeof(dedge_t)); - AddLump (LUMP_MODELS, dmodels, nummodels*sizeof(dmodel_t)); - AddLump (LUMP_AREAS, dareas, numareas*sizeof(darea_t)); - AddLump (LUMP_AREAPORTALS, dareaportals, numareaportals*sizeof(dareaportal_t)); - - AddLump (LUMP_LIGHTING, dlightdata, lightdatasize); - AddLump (LUMP_VISIBILITY, dvisdata, visdatasize); - AddLump (LUMP_ENTITIES, dentdata, entdatasize); - AddLump (LUMP_POP, dpop, sizeof(dpop)); - - fseek (wadfile, 0, SEEK_SET); - SafeWrite (wadfile, header, sizeof(dheader_t)); - fclose (wadfile); -} - -//============================================================================ - -/* -============= -PrintBSPFileSizes - -Dumps info about current file -============= -*/ -void PrintBSPFileSizes (void) -{ - if (!num_entities) - ParseEntities (); - - printf ("%5i models %7i\n" - ,nummodels, (int)(nummodels*sizeof(dmodel_t))); - printf ("%5i brushes %7i\n" - ,numbrushes, (int)(numbrushes*sizeof(dbrush_t))); - printf ("%5i brushsides %7i\n" - ,numbrushsides, (int)(numbrushsides*sizeof(dbrushside_t))); - printf ("%5i planes %7i\n" - ,numplanes, (int)(numplanes*sizeof(dplane_t))); - printf ("%5i texinfo %7i\n" - ,numtexinfo, (int)(numtexinfo*sizeof(texinfo_t))); - printf ("%5i entdata %7i\n", num_entities, entdatasize); - - printf ("\n"); - - printf ("%5i vertexes %7i\n" - ,numvertexes, (int)(numvertexes*sizeof(dvertex_t))); - printf ("%5i nodes %7i\n" - ,numnodes, (int)(numnodes*sizeof(dnode_t))); - printf ("%5i faces %7i\n" - ,numfaces, (int)(numfaces*sizeof(dface_t))); - printf ("%5i leafs %7i\n" - ,numleafs, (int)(numleafs*sizeof(dleaf_t))); - printf ("%5i leaffaces %7i\n" - ,numleaffaces, (int)(numleaffaces*sizeof(dleaffaces[0]))); - printf ("%5i leafbrushes %7i\n" - ,numleafbrushes, (int)(numleafbrushes*sizeof(dleafbrushes[0]))); - printf ("%5i surfedges %7i\n" - ,numsurfedges, (int)(numsurfedges*sizeof(dsurfedges[0]))); - printf ("%5i edges %7i\n" - ,numedges, (int)(numedges*sizeof(dedge_t))); - printf (" lightdata %7i\n", lightdatasize); - printf (" visdata %7i\n", visdatasize); -} - - -//============================================ - -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 = 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 (false); - if (strlen(token) >= MAX_VALUE-1) - Error ("ParseEpar: token too long"); - e->value = copystring(token); - - // strip trailing spaces - StripTrailing (e->key); - StripTrailing (e->value); - - return e; -} - - -/* -================ -ParseEntity -================ -*/ -qboolean ParseEntity (void) -{ - epair_t *e; - entity_t *mapent; - - if (!GetToken (true)) - return false; - - 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 (true)) - Error ("ParseEntity: EOF without closing brace"); - if (!strcmp (token, "}") ) - break; - e = ParseEpair (); - e->next = mapent->epairs; - mapent->epairs = e; - } while (1); - - return true; -} - -/* -================ -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 -================ -*/ -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 ; inext) - { - 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 (entity_t *ent) -{ - epair_t *ep; - - printf ("------- entity %p -------\n", ent); - for (ep=ent->epairs ; ep ; ep=ep->next) - { - printf ("%s = %s\n", ep->key, ep->value); - } - -} - -void SetKeyValue (entity_t *ent, char *key, 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 = malloc (sizeof(*ep)); - ep->next = ent->epairs; - ent->epairs = ep; - ep->key = copystring(key); - ep->value = copystring(value); -} - -char *ValueForKey (entity_t *ent, 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 (entity_t *ent, char *key) -{ - char *k; - - k = ValueForKey (ent, key); - return atof(k); -} - -void GetVectorForKey (entity_t *ent, char *key, vec3_t vec) -{ - 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/misc/mediasource/extra/netradiant-src/tools/quake2/common/bspfile.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/bspfile.h deleted file mode 100644 index e11ec208..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/bspfile.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -Copyright (C) 1999-2006 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" - - -extern int nummodels; -extern dmodel_t dmodels[MAX_MAP_MODELS]; - -extern int visdatasize; -extern byte dvisdata[MAX_MAP_VISIBILITY]; -extern dvis_t *dvis; - -extern int lightdatasize; -extern byte dlightdata[MAX_MAP_LIGHTING]; - -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 numvertexes; -extern dvertex_t dvertexes[MAX_MAP_VERTS]; - -extern int numnodes; -extern dnode_t dnodes[MAX_MAP_NODES]; - -extern int numtexinfo; -extern texinfo_t texinfo[MAX_MAP_TEXINFO]; - -extern int numfaces; -extern dface_t dfaces[MAX_MAP_FACES]; - -extern int numedges; -extern dedge_t dedges[MAX_MAP_EDGES]; - -extern int numleaffaces; -extern unsigned short dleaffaces[MAX_MAP_LEAFFACES]; - -extern int numleafbrushes; -extern unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; - -extern int numsurfedges; -extern int dsurfedges[MAX_MAP_SURFEDGES]; - -extern int numareas; -extern darea_t dareas[MAX_MAP_AREAS]; - -extern int numareaportals; -extern dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; - -extern int numbrushes; -extern dbrush_t dbrushes[MAX_MAP_BRUSHES]; - -extern int numbrushsides; -extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; - -extern byte dpop[256]; - -void DecompressVis (byte *in, byte *decompressed); -int CompressVis (byte *vis, byte *dest); - -void LoadBSPFile (char *filename); -void LoadBSPFileTexinfo (char *filename); // just for qdata -void WriteBSPFile (char *filename); -void PrintBSPFileSizes (void); - -//=============== - - -typedef struct epair_s -{ - struct epair_s *next; - char *key; - char *value; -} epair_t; - -typedef struct -{ - vec3_t origin; - int firstbrush; - int numbrushes; - epair_t *epairs; - -// only valid for func_areaportals - int areaportalnum; - int portalareas[2]; -} entity_t; - -extern int num_entities; -extern entity_t entities[MAX_MAP_ENTITIES]; - -void ParseEntities (void); -void UnparseEntities (void); - -void SetKeyValue (entity_t *ent, char *key, char *value); -char *ValueForKey (entity_t *ent, char *key); -// will return "" if not present - -vec_t FloatForKey (entity_t *ent, char *key); -void GetVectorForKey (entity_t *ent, char *key, vec3_t vec); - -epair_t *ParseEpair (void); - -void PrintEntity (entity_t *ent); - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/cmdlib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/cmdlib.c deleted file mode 100644 index e59bf215..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/cmdlib.c +++ /dev/null @@ -1,1221 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// Nurail: Swiped from quake3/common - -#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 HERETIC2_BASEDIRNAME "h" -#define PATHSEPERATOR '/' - -// qboolean verbose = false; - -#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); - - memset(p, 0, 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); - - memset(p, 0, 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; - char basedirname[256]; - - if (!(path[0] == '/' || path[0] == '\\' || path[1] == ':')) - { // path is partial - Q_getwd (temp); - strcat (temp, path); - path = temp; - } - - // search for "quake2" in path - - if ( !strcmp( game, "heretic2" ) ) - strncpy(basedirname, HERETIC2_BASEDIRNAME, 256); - else - strncpy(basedirname, BASEDIRNAME, 256); - - 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_FPrintf( SYS_VRB, "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_FPrintf( SYS_VRB, "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 = true; - 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); -} - -int Q_strcasecmp (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 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); -} -/* -// all output ends up through here -void FPrintf (int flag, char *buf) -{ - printf(buf); - -} - -void Sys_FPrintf (int flag, const char *format, ...) -{ - char out_buffer[4096]; - va_list argptr; - - if ((flag == SYS_VRB) && (verbose == false)) - 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 ); - - exit (1); -} -*/ - - -/* -============================================================================ - - 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/misc/mediasource/extra/netradiant-src/tools/quake2/common/cmdlib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/cmdlib.h deleted file mode 100644 index 5b08b81a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/cmdlib.h +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#include -#include -#include -#include -#include -#include - -#ifdef WIN32 - #ifdef NDEBUG // Don't show in a Release build - #pragma warning(disable : 4305) // truncate from double to float - #pragma warning(disable : 4244) // conversion from double to float - #pragma warning(disable : 4018) // signed/unsigned mismatch - #endif -#endif - -#ifdef WIN32 - #pragma intrinsic( memset, memcpy ) -#endif - -#ifndef __BYTEBOOL__ - #define __BYTEBOOL__ - typedef enum {false, true} qboolean; - typedef unsigned char byte; -#endif - -#ifdef PATH_MAX -#define MAX_OS_PATH PATH_MAX -#else -#define MAX_OS_PATH 1024 -#endif -#define MEM_BLOCKSIZE 4096 - -/* -extern qboolean verbose; -#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 -*/ - -// 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_strcasecmp( const char *s1, const char *s2 ); -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 ); - -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); - -//void Sys_Printf (const char *text, ...); -//void Sys_FPrintf (int flag, const char *text, ...); -//void Error( const char *error, ... ); - -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 -{ - byte *data; - int count; -} cblock_t; - -extern char game[64]; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/inout.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/inout.c deleted file mode 100644 index 3cf66e7f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/inout.c +++ /dev/null @@ -1,367 +0,0 @@ -/* -Copyright (C) 1999-2006 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" - -#ifdef WIN32 -HWND hwndOut = NULL; -qboolean lookedForServer = false; -UINT wm_BroadcastCommand = -1; -#endif - -socket_t *brdcst_socket; -netmessage_t msg; - -qboolean verbose = false; - -// 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 = false; - 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 = true; - } - node = xmlNewNode (NULL, "message"); - xmlNodeSetContent (node, buf); - 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 == false)) - 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/misc/mediasource/extra/netradiant-src/tools/quake2/common/inout.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/inout.h deleted file mode 100644 index 75ef55ee..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/inout.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright (C) 1999-2006 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" -#include "mathlib.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, ...); -void Error( const char *error, ...); - -#ifdef _DEBUG -#define DBG_XML 1 -#endif - -#ifdef DBG_XML -void DumpXML(); -#endif - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/l3dslib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/l3dslib.c deleted file mode 100644 index f120bec2..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/l3dslib.c +++ /dev/null @@ -1,300 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.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 - -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 MAXVERTS) - Error ("Error: Too many vertices"); - - for (i=0 ; i MAXTRIANGLES) - Error ("Error: Too many triangles"); - - for (i=0 ; i 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 = 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/misc/mediasource/extra/netradiant-src/tools/quake2/common/l3dslib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/l3dslib.h deleted file mode 100644 index 1d362ce9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/l3dslib.h +++ /dev/null @@ -1,25 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake2/common/lbmlib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/lbmlib.c deleted file mode 100644 index edc2c3e4..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/lbmlib.c +++ /dev/null @@ -1,837 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// lbmlib.c - -#include "cmdlib.h" -#include "inout.h" -#include "lbmlib.h" - - - -/* -============================================================================ - - 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 (countbpwidth) - Error ("Decompression exceeded width!\n"); - - - return source; -} - - -/* -================= -LoadLBM -================= -*/ -void LoadLBM (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 = malloc (768); - memset (cmapbuffer, 0, 768); - memcpy (cmapbuffer, LBM_P, chunklength); - break; - - case BODYID: - body_p = LBM_P; - - pic_p = picbuffer = malloc (bmhd.w*bmhd.h); - if (formtype == PBMID) - { - // - // unpack PBM - // - for (y=0 ; ydata; - - 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 = 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 = malloc ( (pcx->ymax+1) * (pcx->xmax+1) ); - if (!out) - Error ("Skin_Cache: couldn't allocate"); - - *pic = out; - - pix = out; - - for (y=0 ; y<=pcx->ymax ; y++, pix += pcx->xmax+1) - { - for (x=0 ; x<=pcx->xmax ; ) - { - dataByte = *raw++; - - if((dataByte & 0xC0) == 0xC0) - { - runLength = dataByte & 0x3F; - dataByte = *raw++; - } - else - runLength = 1; - - while(runLength-- > 0) - pix[x++] = dataByte; - } - - } - - if ( raw - (byte *)pcx > len) - Error ("PCX file %s was malformed", filename); - - free (pcx); -} - -/* -============== -WritePCXfile -============== -*/ -void WritePCXfile (char *filename, byte *data, - int width, int height, byte *palette) -{ - int i, j, length; - pcx_t *pcx; - byte *pack; - - pcx = 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(2); // not a grey scale - - // pack the image - pack = &pcx->data; - - for (i=0 ; i=0; row--) { - pixbuf = targa_rgba + row*columns*4; - for(column=0; column=0; row--) { - pixbuf = targa_rgba + row*columns*4; - for(column=0; column0) - row--; - else - goto breakOut; - pixbuf = targa_rgba + row*columns*4; - } - } - } - else { // non run-length packet - for(j=0;j0) - 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; - } - } - } - - fclose(fin); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/lbmlib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/lbmlib.h deleted file mode 100644 index 40e6dce6..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/lbmlib.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright (C) 1999-2006 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 (char *filename, byte **picture, byte **palette); -void WriteLBMfile (char *filename, byte *data, int width, int height - , byte *palette); -void LoadPCX (char *filename, byte **picture, byte **palette, int *width, int *height); -void WritePCXfile (char *filename, byte *data, int width, int height - , byte *palette); - -// loads / saves either lbm or pcx, depending on extension -void Load256Image (char *name, byte **pixels, byte **palette, - int *width, int *height); -void Save256Image (char *name, byte *pixels, byte *palette, - int width, int height); - - -void LoadTGA (char *filename, byte **pixels, int *width, int *height); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/mathlib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/mathlib.c deleted file mode 100644 index b912b450..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/mathlib.c +++ /dev/null @@ -1,172 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "cmdlib.h" -#include "mathlib.h" - -vec3_t vec3_origin = {0,0,0}; - - -double VectorLength(vec3_t v) -{ - int i; - double length; - - length = 0; - for (i=0 ; i< 3 ; i++) - length += v[i]*v[i]; - length = sqrt (length); // FIXME - - return length; -} - -qboolean VectorCompare (vec3_t v1, vec3_t v2) -{ - int i; - - for (i=0 ; i<3 ; i++) - if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON) - return false; - - return true; -} - -vec_t Q_rint (vec_t in) -{ - return floor (in + 0.5); -} - -void VectorMA (vec3_t va, double scale, 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]; -} - -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; -} - -vec_t VectorNormalize (vec3_t in, vec3_t out) -{ - vec_t length, ilength; - - length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]); - if (length == 0) - { - VectorClear (out); - return 0; - } - - ilength = 1.0/length; - out[0] = in[0]*ilength; - out[1] = in[1]*ilength; - out[2] = in[2]*ilength; - - return length; -} - -vec_t ColorNormalize (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) - return 0; - - scale = 1.0 / 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 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; - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/mathlib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/mathlib.h deleted file mode 100644 index eb10f0fc..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/mathlib.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright (C) 1999-2006 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 DOUBLEVEC_T -typedef double vec_t; -#else -typedef float vec_t; -#endif -typedef vec_t vec3_t[3]; - -#define SIDE_FRONT 0 -#define SIDE_ON 2 -#define SIDE_BACK 1 -#define SIDE_CROSS -2 - -#define Q_PI 3.14159265358979323846 - -extern vec3_t vec3_origin; - -#define EQUAL_EPSILON 0.001 - -qboolean VectorCompare (vec3_t v1, vec3_t v2); - -#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 VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];} -#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];} -#define VectorClear(x) {x[0] = x[1] = x[2] = 0;} -#define VectorNegate(x) {x[0]=-x[0];x[1]=-x[1];x[2]=-x[2];} - -vec_t Q_rint (vec_t in); -vec_t _DotProduct (vec3_t v1, vec3_t v2); -void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out); -void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out); -void _VectorCopy (vec3_t in, vec3_t out); -void _VectorScale (vec3_t v, vec_t scale, vec3_t out); - -double VectorLength(vec3_t v); - -void VectorMA (vec3_t va, double scale, vec3_t vb, vec3_t vc); - -void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross); -vec_t VectorNormalize (vec3_t in, vec3_t out); -vec_t ColorNormalize (vec3_t in, vec3_t out); -void VectorInverse (vec3_t v); - -void ClearBounds (vec3_t mins, vec3_t maxs); -void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/md4.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/md4.c deleted file mode 100644 index 7c2c9be4..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/md4.c +++ /dev/null @@ -1,227 +0,0 @@ -/* - mdfour.c - - An implementation of MD4 designed for use in the samba SMB - authentication protocol - - Copyright (C) 1997-1998 Andrew Tridgell - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - - See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to: - - Free Software Foundation, Inc. - 59 Temple Place - Suite 330 - Boston, MA 02111-1307, USA - - $Id: mdfour.c 7689 2007-11-12 14:28:40Z divverent $ -*/ - -#include /* XoXus: needed for memset call */ -#include "md4.h" - -/* NOTE: This code makes no attempt to be fast! - - It assumes that a int is at least 32 bits long -*/ - -static struct mdfour *m; - -#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)) -#ifdef LARGE_INT32 -#define lshift(x,s) ((((x)<<(s))&0xFFFFFFFF) | (((x)>>(32-(s)))&0xFFFFFFFF)) -#else -#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) -#endif - -#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) -#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) -#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) - -/* this applies md4 to 64 byte chunks */ -static void mdfour64(uint32 *M) -{ - int j; - uint32 AA, BB, CC, DD; - uint32 X[16]; - uint32 A,B,C,D; - - for (j=0;j<16;j++) - X[j] = M[j]; - - A = m->A; B = m->B; C = m->C; D = m->D; - AA = A; BB = B; CC = C; DD = D; - - ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); - ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); - ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); - ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); - ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); - ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); - ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); - ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); - - ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); - ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); - ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); - ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); - ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); - ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); - ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); - ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); - - ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); - ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); - ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); - ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); - ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); - ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); - ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); - ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); - - A += AA; B += BB; C += CC; D += DD; - -#ifdef LARGE_INT32 - A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; - C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; -#endif - - for (j=0;j<16;j++) - X[j] = 0; - - m->A = A; m->B = B; m->C = C; m->D = D; -} - -static void copy64(uint32 *M, unsigned char *in) -{ - int i; - - for (i=0;i<16;i++) - M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | - (in[i*4+1]<<8) | (in[i*4+0]<<0); -} - -static void copy4(unsigned char *out,uint32 x) -{ - out[0] = x&0xFF; - out[1] = (x>>8)&0xFF; - out[2] = (x>>16)&0xFF; - out[3] = (x>>24)&0xFF; -} - -void mdfour_begin(struct mdfour *md) -{ - md->A = 0x67452301; - md->B = 0xefcdab89; - md->C = 0x98badcfe; - md->D = 0x10325476; - md->totalN = 0; -} - - -static void mdfour_tail(unsigned char *in, int n) -{ - unsigned char buf[128]; - uint32 M[16]; - uint32 b; - - m->totalN += n; - - b = m->totalN * 8; - - memset(buf, 0, 128); - if (n) memcpy(buf, in, n); - buf[n] = 0x80; - - if (n <= 55) { - copy4(buf+56, b); - copy64(M, buf); - mdfour64(M); - } else { - copy4(buf+120, b); - copy64(M, buf); - mdfour64(M); - copy64(M, buf+64); - mdfour64(M); - } -} - -void mdfour_update(struct mdfour *md, unsigned char *in, int n) -{ - uint32 M[16]; - -// start of edit by Forest 'LordHavoc' Hale -// commented out to prevent crashing when length is 0 -// if (n == 0) mdfour_tail(in, n); -// end of edit by Forest 'LordHavoc' Hale - - m = md; - - while (n >= 64) { - copy64(M, in); - mdfour64(M); - in += 64; - n -= 64; - m->totalN += 64; - } - - mdfour_tail(in, n); -} - - -void mdfour_result(struct mdfour *md, unsigned char *out) -{ - m = md; - - copy4(out, m->A); - copy4(out+4, m->B); - copy4(out+8, m->C); - copy4(out+12, m->D); -} - - -void mdfour(unsigned char *out, unsigned char *in, int n) -{ - struct mdfour md; - mdfour_begin(&md); - mdfour_update(&md, in, n); - mdfour_result(&md, out); -} - -/////////////////////////////////////////////////////////////// -// MD4-based checksum utility functions -// -// Copyright (C) 2000 Jeff Teunissen -// -// Author: Jeff Teunissen -// Date: 01 Jan 2000 - -unsigned Com_BlockChecksum (void *buffer, int length) -{ - int digest[4]; - unsigned val; - - mdfour ( (unsigned char *) digest, (unsigned char *) buffer, length ); - - val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; - - return val; -} - -void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) -{ - mdfour ( outbuf, (unsigned char *) buffer, len ); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/md4.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/md4.h deleted file mode 100644 index 4373c2c9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/md4.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - mdfour.h - - an implementation of MD4 designed for use in the SMB authentication - protocol - - Copyright (C) Andrew Tridgell 1997-1998 - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - - See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to: - - Free Software Foundation, Inc. - 59 Temple Place - Suite 330 - Boston, MA 02111-1307, USA -*/ - -#ifndef _MDFOUR_H -#define _MDFOUR_H - -#ifndef int32 -#define int32 int -#endif - -#if SIZEOF_INT > 4 -#define LARGE_INT32 -#endif - -#ifndef uint32 -#define uint32 unsigned int32 -#endif - -struct mdfour { - uint32 A, B, C, D; - uint32 totalN; -}; - -void mdfour_begin(struct mdfour *md); // old: MD4Init -void mdfour_update(struct mdfour *md, unsigned char *in, int n); //old: MD4Update -void mdfour_result(struct mdfour *md, unsigned char *out); // old: MD4Final -void mdfour(unsigned char *out, unsigned char *in, int n); - -unsigned Com_BlockChecksum (void *buffer, int length); -void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf); - -#endif // _MDFOUR_H - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/path_init.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/path_init.c deleted file mode 100644 index d309e95c..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/path_init.c +++ /dev/null @@ -1,404 +0,0 @@ -/* ------------------------------------------------------------------------------- - -Copyright (C) 1999-2006 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 - -Nurail: Swiped from Q3Map2 - -*/ - - - -/* marker */ -#define PATH_INIT_C - -#if defined( __linux__ ) || defined( __APPLE__ ) - #define Q_UNIX -#endif - -#ifdef Q_UNIX - #include - #include - #include -#endif - - -/* dependencies */ -#include "cmdlib.h" -#include "inout.h" - - - -/* path support */ -#define MAX_BASE_PATHS 10 -#define MAX_GAME_PATHS 10 - -char *homePath; -char installPath[ MAX_OS_PATH ]; - -int numBasePaths; -char *basePaths[ MAX_BASE_PATHS ]; -int numGamePaths; -char *gamePaths[ MAX_GAME_PATHS ]; - -/* -some of this code is based off the original q3map port from loki -and finds various paths. moved here from bsp.c for clarity. -*/ - -/* -PathLokiGetHomeDir() -gets the user's home dir (for ~/.q3a) -*/ - -char *LokiGetHomeDir( void ) -{ - #ifndef Q_UNIX - return NULL; - #else - char *home; - uid_t id; - struct passwd *pwd; - - - /* get the home environment variable */ - home = getenv( "HOME" ); - if( home == NULL ) - { - /* do some more digging */ - id = getuid(); - setpwent(); - while( (pwd = getpwent()) != NULL ) - { - if( pwd->pw_uid == id ) - { - home = pwd->pw_dir; - break; - } - } - endpwent(); - } - - /* return it */ - return home; - #endif -} - - - -/* -PathLokiInitPaths() -initializes some paths on linux/os x -*/ - -void LokiInitPaths( char *argv0 ) -{ - #ifndef Q_UNIX - /* this is kinda crap, but hey */ - strcpy( installPath, "../" ); - #else - char temp[ MAX_OS_PATH ]; - char *home; - char *path; - char *last; - qboolean found; - - - /* get home dir */ - home = LokiGetHomeDir(); - if( home == NULL ) - home = "."; - - /* do some path divining */ - strcpy( temp, argv0 ); - if( strrchr( temp, '/' ) ) - argv0 = strrchr( argv0, '/' ) + 1; - else - { - /* get path environment variable */ - path = getenv( "PATH" ); - - /* minor setup */ - last[ 0 ] = path[ 0 ]; - last[ 1 ] = '\0'; - found = false; - - /* go through each : segment of path */ - while( last[ 0 ] != '\0' && found == false ) - { - /* null out temp */ - temp[ 0 ] = '\0'; - - /* find next chunk */ - last = strchr( path, ':' ); - if( last == NULL ) - last = path + strlen( path ); - - /* found home dir candidate */ - if( *path == '~' ) - { - strcpy( temp, home ); - path++; - } - - /* concatenate */ - if( last > (path + 1) ) - { - strncat( temp, path, (last - path) ); - strcat( temp, "/" ); - } - strcat( temp, "./" ); - strcat( temp, argv0 ); - - /* verify the path */ - if( access( temp, X_OK ) == 0 ) - found++; - path = last + 1; - } - } - - /* flake */ - if( realpath( temp, installPath ) ) - { - /* q3map is in "tools/" */ - *(strrchr( installPath, '/' )) = '\0'; - *(strrchr( installPath, '/' ) + 1) = '\0'; - } - - /* set home path */ - homePath = home; - #endif -} - - - -/* -CleanPath() - ydnar -cleans a dos path \ -> / -*/ - -void CleanPath( char *path ) -{ - while( *path ) - { - if( *path == '\\' ) - *path = '/'; - path++; - } -} - -/* -AddBasePath() - ydnar -adds a base path to the list -*/ - -void AddBasePath( char *path ) -{ - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' || numBasePaths >= MAX_BASE_PATHS ) - return; - - /* add it to the list */ - basePaths[ numBasePaths ] = safe_malloc( strlen( path ) + 1 ); - strcpy( basePaths[ numBasePaths ], path ); - CleanPath( basePaths[ numBasePaths ] ); - numBasePaths++; -} - - - -/* -AddHomeBasePath() - ydnar -adds a base path to the beginning of the list, prefixed by ~/ -*/ - -void AddHomeBasePath( char *path ) -{ - #ifdef Q_UNIX - int i; - char temp[ MAX_OS_PATH ]; - - - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' ) - return; - - /* make a hole */ - for( i = 0; i < (MAX_BASE_PATHS - 1); i++ ) - basePaths[ i + 1 ] = basePaths[ i ]; - - /* concatenate home dir and path */ - sprintf( temp, "%s/%s", homePath, path ); - - /* add it to the list */ - basePaths[ 0 ] = safe_malloc( strlen( temp ) + 1 ); - strcpy( basePaths[ 0 ], temp ); - CleanPath( basePaths[ 0 ] ); - numBasePaths++; - #endif -} - - - -/* -AddGamePath() - ydnar -adds a game path to the list -*/ - -void AddGamePath( char *path ) -{ - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' || numGamePaths >= MAX_GAME_PATHS ) - return; - - /* add it to the list */ - gamePaths[ numGamePaths ] = safe_malloc( strlen( path ) + 1 ); - strcpy( gamePaths[ numGamePaths ], path ); - CleanPath( gamePaths[ numGamePaths ] ); - numGamePaths++; -} - - - - -/* -InitPaths() - ydnar -cleaned up some of the path initialization code from bsp.c -will remove any arguments it uses -*/ - -void InitPaths( int *argc, char **argv ) -{ - int i, j, k, len, len2; - char temp[ MAX_OS_PATH ]; - char gamePath[MAX_OS_PATH], homeBasePath[MAX_OS_PATH], game_magic[10]; - - strcpy(gamePath, "baseq2"); - strcpy(game_magic, "quake"); - strcpy(homeBasePath, ".quake2"); - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- InitPaths ---\n" ); - - /* get the install path for backup */ - LokiInitPaths( argv[ 0 ] ); - - /* set game to default (q3a) */ - numBasePaths = 0; - numGamePaths = 0; - - /* parse through the arguments and extract those relevant to paths */ - for( i = 0; i < *argc; i++ ) - { - /* check for null */ - if( argv[ i ] == NULL ) - continue; - - /* -fs_basepath */ - if( strcmp( argv[ i ], "-fs_basepath" ) == 0 ) - { - if( ++i >= *argc ) - Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); - argv[ i - 1 ] = NULL; - AddBasePath( argv[ i ] ); - argv[ i ] = NULL; - } - - } - - /* remove processed arguments */ - for( i = 0, j = 0, k = 0; i < *argc && j < *argc; i++, j++ ) - { - for( j; j < *argc && argv[ j ] == NULL; j++ ); - argv[ i ] = argv[ j ]; - if( argv[ i ] != NULL ) - k++; - } - *argc = k; - - /* add standard game path */ - AddGamePath( gamePath ); - - /* if there is no base path set, figure it out */ - if( numBasePaths == 0 ) - { - /* this is another crappy replacement for SetQdirFromPath() */ - len2 = strlen( game_magic ); - for( i = 0; i < *argc && numBasePaths == 0; i++ ) - { - /* extract the arg */ - strcpy( temp, argv[ i ] ); - CleanPath( temp ); - len = strlen( temp ); - Sys_FPrintf( SYS_VRB, "Searching for \"%s\" in \"%s\" (%d)...\n", game_magic, temp, i ); - - /* this is slow, but only done once */ - for( j = 0; j < (len - len2); j++ ) - { - /* check for the game's magic word */ - if( Q_strncasecmp( &temp[ j ], game_magic, len2 ) == 0 ) - { - /* now find the next slash and nuke everything after it */ - while( temp[ ++j ] != '/' && temp[ j ] != '\0' ); - temp[ j ] = '\0'; - - /* add this as a base path */ - AddBasePath( temp ); - break; - } - } - } - - /* add install path */ - if( numBasePaths == 0 ) - AddBasePath( installPath ); - - /* check again */ - if( numBasePaths == 0 ) - Error( "Failed to find a valid base path." ); - } - - /* this only affects unix */ - AddHomeBasePath( homeBasePath ); - - /* initialize vfs paths */ - if( numBasePaths > MAX_BASE_PATHS ) - numBasePaths = MAX_BASE_PATHS; - if( numGamePaths > MAX_GAME_PATHS ) - numGamePaths = MAX_GAME_PATHS; - - /* walk the list of game paths */ - //for( j = 0; j < numGamePaths; j++ ) - //{ - /* walk the list of base paths */ - // for( i = 0; i < numBasePaths; i++ ) - // { - /* create a full path and initialize it */ - // sprintf( temp, "%s/%s/", basePaths[ i ], gamePaths[ j ] ); - // vfsInitDirectory( temp ); - // } - //} - - /* done */ - Sys_Printf( "\n" ); -} - - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/polylib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/polylib.c deleted file mode 100644 index e177d728..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/polylib.c +++ /dev/null @@ -1,642 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#include "mathlib.h" -#include "polylib.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 8192 - -void pw(winding_t *w) -{ - int i; - for (i=0 ; inumpoints ; i++) - 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 (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 = 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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, 8192, vup); - VectorScale (vright, 8192, 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; i++) - { - p1 = w->p[i]; - - for (j=0 ; j<3 ; j++) - if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE) - Error ("CheckFace: BUGUS_RANGE: %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 ; jnumpoints ; 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 = false; - back = false; - for (i=0 ; inumpoints ; i++) - { - d = DotProduct (w->p[i], normal) - dist; - if (d < -ON_EPSILON) - { - if (front) - return SIDE_CROSS; - back = true; - continue; - } - if (d > ON_EPSILON) - { - if (back) - return SIDE_CROSS; - front = true; - continue; - } - } - - if (back) - return SIDE_BACK; - if (front) - return SIDE_FRONT; - return SIDE_ON; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/polylib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/polylib.h deleted file mode 100644 index d89062d5..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/polylib.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright (C) 1999-2006 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 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/misc/mediasource/extra/netradiant-src/tools/quake2/common/q2_threads.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/q2_threads.h deleted file mode 100644 index b8fc2f53..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/q2_threads.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -Copyright (C) 1999-2006 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 _THREADS_H - -#define _THREADS_H - -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); - -#endif // _THREADS_H diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/qfiles.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/qfiles.h deleted file mode 100644 index 7c9cc864..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/qfiles.h +++ /dev/null @@ -1,563 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// qfiles.h: quake file formats -// This file must be identical in the quake and utils directories -// - -/* -======================================================================== - -The .pak files are just a linear collapse of a directory tree - -======================================================================== -*/ - -#ifdef WIN32 - #ifdef NDEBUG // Don't show in a Release build - #pragma warning(disable : 4305) // truncate from double to float - #pragma warning(disable : 4244) // conversion from double to float - #pragma warning(disable : 4018) // signed/unsigned mismatch - #endif -#endif - -#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P') - -typedef struct -{ - char name[56]; - int filepos, filelen; -} dpackfile_t; - -typedef struct -{ - int ident; // == IDPAKHEADER - int dirofs; - int dirlen; -} dpackheader_t; - -#define MAX_FILES_IN_PACK 4096 - - -/* -======================================================================== - -PCX files are used for as many images as possible - -======================================================================== -*/ - -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; - - -/* -======================================================================== - -.MD2 triangle model file format - -======================================================================== -*/ - -#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I') -#define ALIAS_VERSION 8 - -#define MAX_TRIANGLES 4096 -#define MAX_VERTS 2048 -#define MAX_FRAMES 512 -#define MAX_MD2SKINS 32 -#define MAX_SKINNAME 64 - -typedef struct -{ - short s; - short t; -} dstvert_t; - -typedef struct -{ - short index_xyz[3]; - short index_st[3]; -} dtriangle_t; - -typedef struct -{ - byte v[3]; // scaled byte to fit in frame mins/maxs - byte lightnormalindex; -} dtrivertx_t; - -#define DTRIVERTX_V0 0 -#define DTRIVERTX_V1 1 -#define DTRIVERTX_V2 2 -#define DTRIVERTX_LNI 3 -#define DTRIVERTX_SIZE 4 - -typedef struct -{ - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name from grabbing - dtrivertx_t verts[1]; // variable sized -} daliasframe_t; - - -// the glcmd format: -// a positive integer starts a tristrip command, followed by that many -// vertex structures. -// a negative integer starts a trifan command, followed by -x vertexes -// a zero indicates the end of the command list. -// a vertex consists of a floating point s, a floating point t, -// and an integer vertex index. - - -typedef struct -{ - int ident; - int version; - - int skinwidth; - int skinheight; - int framesize; // byte size of each frame - - int num_skins; - int num_xyz; - int num_st; // greater than num_xyz for seams - int num_tris; - int num_glcmds; // dwords in strip/fan command list - int num_frames; - - int ofs_skins; // each skin is a MAX_SKINNAME string - int ofs_st; // byte offset from start for stverts - int ofs_tris; // offset for dtriangles - int ofs_frames; // offset for first frame - int ofs_glcmds; - int ofs_end; // end of file - -} dmdl_t; - -/* -======================================================================== - -.SP2 sprite file format - -======================================================================== -*/ - -#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I') - // little-endian "IDS2" -#define SPRITE_VERSION 2 - -typedef struct -{ - int width, height; - int origin_x, origin_y; // raster coordinates inside pic - char name[MAX_SKINNAME]; // name of pcx file -} dsprframe_t; - -typedef struct { - int ident; - int version; - int numframes; - dsprframe_t frames[1]; // variable sized -} dsprite_t; - -/* -============================================================================== - - .WAL texture file format - -============================================================================== -*/ - - -#define MIPLEVELS 4 -typedef struct miptex_s -{ - char name[32]; - unsigned width, height; - unsigned offsets[MIPLEVELS]; // four mip maps stored - char animname[32]; // next frame in animation chain - int flags; - int contents; - int value; -} miptex_t; - - /* - ============================================================================== - -- .WAL texture file format -+ .M8 texture file format - - ============================================================================== - */ - -typedef struct palette_s -{ - union - { - struct - { - byte r,g,b; - }; - }; -} palette_t; - -#define MIP_VERSION 2 -#define PAL_SIZE 256 -#define H2_MIPLEVELS 16 - - typedef struct miptex_m8_s - { - int version; - char name[32]; - unsigned width[H2_MIPLEVELS], height[H2_MIPLEVELS]; - unsigned offsets[H2_MIPLEVELS]; // four mip maps stored - char animname[32]; // next frame in animation chain - palette_t palette[PAL_SIZE]; - int flags; - int contents; - int value; - } miptex_m8_t; - - -#define MIP32_VERSION 4 - -#define MIP32_NOMIP_FLAG2 0x00000001 -#define MIP32_DETAILER_FLAG2 0x00000002 - -typedef struct miptex_m32_s -{ - int version; - char name[128]; - char altname[128]; // texture substitution - char animname[128]; // next frame in animation chain - char damagename[128]; // image that should be shown when damaged - unsigned width[H2_MIPLEVELS], height[H2_MIPLEVELS]; - unsigned offsets[H2_MIPLEVELS]; - int flags; - int contents; - int value; - float scale_x, scale_y; - int mip_scale; - - // detail texturing info - char dt_name[128]; // detailed texture name - float dt_scale_x, dt_scale_y; - float dt_u, dt_v; - float dt_alpha; - int dt_src_blend_mode, dt_dst_blend_mode; - - int flags2; - int unused[19]; // future expansion to maintain compatibility with h2 -} miptex_m32_t; - - - - -/* -============================================================================== - - .BSP file format - -============================================================================== -*/ - -#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') - // little-endian "IBSP" - -#define BSPVERSION 38 - - -// upper design bounds -// leaffaces, leafbrushes, planes, and verts are still bounded by -// 16 bit short limits -#define MAX_MAP_MODELS 1024 -#define MAX_MAP_BRUSHES 8192 -#define MAX_MAP_ENTITIES 2048 -#define MAX_MAP_ENTSTRING 0x40000 -#define MAX_MAP_TEXINFO 8192 - -#define MAX_MAP_AREAS 256 -#define MAX_MAP_AREAPORTALS 1024 -#define MAX_MAP_PLANES 65536 -#define MAX_MAP_NODES 65536 -#define MAX_MAP_BRUSHSIDES 65536 -#define MAX_MAP_LEAFS 65536 -#define MAX_MAP_VERTS 65536 -#define MAX_MAP_FACES 65536 -#define MAX_MAP_LEAFFACES 65536 -#define MAX_MAP_LEAFBRUSHES 65536 -#define MAX_MAP_PORTALS 65536 -#define MAX_MAP_EDGES 128000 -#define MAX_MAP_SURFEDGES 256000 -#define MAX_MAP_LIGHTING 0x200000 -#define MAX_MAP_VISIBILITY 0x100000 - -// key / value pair sizes - -#define MAX_KEY 32 -#define MAX_VALUE 1024 - -//============================================================================= - -typedef struct -{ - int fileofs, filelen; -} lump_t; - -#define LUMP_ENTITIES 0 -#define LUMP_PLANES 1 -#define LUMP_VERTEXES 2 -#define LUMP_VISIBILITY 3 -#define LUMP_NODES 4 -#define LUMP_TEXINFO 5 -#define LUMP_FACES 6 -#define LUMP_LIGHTING 7 -#define LUMP_LEAFS 8 -#define LUMP_LEAFFACES 9 -#define LUMP_LEAFBRUSHES 10 -#define LUMP_EDGES 11 -#define LUMP_SURFEDGES 12 -#define LUMP_MODELS 13 -#define LUMP_BRUSHES 14 -#define LUMP_BRUSHSIDES 15 -#define LUMP_POP 16 -#define LUMP_AREAS 17 -#define LUMP_AREAPORTALS 18 -#define HEADER_LUMPS 19 - -typedef struct -{ - int ident; - int version; - lump_t lumps[HEADER_LUMPS]; -} dheader_t; - -typedef struct -{ - float mins[3], maxs[3]; - float origin[3]; // for sounds or lights - int headnode; - int firstface, numfaces; // submodels just draw faces - // without walking the bsp tree -} dmodel_t; - - -typedef struct -{ - float point[3]; -} dvertex_t; - - -// 0-2 are axial planes -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 - -// 3-5 are non-axial planes snapped to the nearest -#define PLANE_ANYX 3 -#define PLANE_ANYY 4 -#define PLANE_ANYZ 5 - -// planes (x&~1) and (x&~1)+1 are allways opposites - -typedef struct -{ - float normal[3]; - float dist; - int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate -} dplane_t; - - -// contents flags are seperate bits -// a given brush can contribute multiple content bits -// multiple brushes can be in a single leaf - -// these definitions also need to be in q_shared.h! - -// lower bits are stronger, and will eat weaker brushes completely -#define CONTENTS_SOLID 1 // an eye is never valid in a solid -#define CONTENTS_WINDOW 2 // translucent, but not watery -#define CONTENTS_AUX 4 -#define CONTENTS_LAVA 8 -#define CONTENTS_SLIME 16 -#define CONTENTS_WATER 32 -#define CONTENTS_MIST 64 -#define LAST_VISIBLE_CONTENTS 64 - -// remaining contents are non-visible, and don't eat brushes - -#define CONTENTS_AREAPORTAL 0x8000 - -#define CONTENTS_PLAYERCLIP 0x10000 -#define CONTENTS_MONSTERCLIP 0x20000 - -// currents can be added to any other contents, and may be mixed -#define CONTENTS_CURRENT_0 0x40000 -#define CONTENTS_CURRENT_90 0x80000 -#define CONTENTS_CURRENT_180 0x100000 -#define CONTENTS_CURRENT_270 0x200000 -#define CONTENTS_CURRENT_UP 0x400000 -#define CONTENTS_CURRENT_DOWN 0x800000 - -#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity - -#define CONTENTS_MONSTER 0x2000000 // should never be on a brush, only in game -#define CONTENTS_DEADMONSTER 0x4000000 -#define CONTENTS_DETAIL 0x8000000 // brushes to be added after vis leafs -#define CONTENTS_TRANSLUCENT 0x10000000 // auto set if any surface has trans -#define CONTENTS_LADDER 0x20000000 - - - -#define SURF_LIGHT 0x1 // value will hold the light strength - -#define SURF_SLICK 0x2 // effects game physics - -#define SURF_SKY 0x4 // don't draw, but add to skybox -#define SURF_WARP 0x8 // turbulent water warp -#define SURF_TRANS33 0x10 -#define SURF_TRANS66 0x20 -#define SURF_FLOWING 0x40 // scroll towards angle -#define SURF_NODRAW 0x80 // don't bother referencing the texture - -#define SURF_HINT 0x100 // make a primary bsp splitter -#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes - - - -typedef struct -{ - int planenum; - int children[2]; // negative numbers are -(leafs+1), not nodes - short mins[3]; // for frustom culling - short maxs[3]; - unsigned short firstface; - unsigned short numfaces; // counting both sides -} dnode_t; - - -typedef struct texinfo_s -{ - float vecs[2][4]; // [s/t][xyz offset] - int flags; // miptex flags + overrides - int value; // light emission, etc - char texture[32]; // texture name (textures/*.wal) - int nexttexinfo; // for animations, -1 = end of chain -} texinfo_t; - - -// note that edge 0 is never used, because negative edge nums are used for -// counterclockwise use of the edge in a face -typedef struct -{ - unsigned short v[2]; // vertex numbers -} dedge_t; - -#define MAXLIGHTMAPS 4 -typedef struct -{ - unsigned short planenum; - short side; - - int firstedge; // we must support > 64k edges - short numedges; - short texinfo; - -// lighting info - byte styles[MAXLIGHTMAPS]; - int lightofs; // start of [numstyles*surfsize] samples -} dface_t; - -typedef struct -{ - int contents; // OR of all brushes (not needed?) - - short cluster; - short area; - - short mins[3]; // for frustum culling - short maxs[3]; - - unsigned short firstleafface; - unsigned short numleaffaces; - - unsigned short firstleafbrush; - unsigned short numleafbrushes; -} dleaf_t; - -typedef struct -{ - unsigned short planenum; // facing out of the leaf - short texinfo; -} dbrushside_t; - -typedef struct -{ - int firstside; - int numsides; - int contents; -} dbrush_t; - -#define ANGLE_UP -1 -#define ANGLE_DOWN -2 - - -// the visibility lump consists of a header with a count, then -// byte offsets for the PVS and PHS of each cluster, then the raw -// compressed bit vectors -#define DVIS_PVS 0 -#define DVIS_PHS 1 -typedef struct -{ - int numclusters; - int bitofs[8][2]; // bitofs[numclusters][2] -} dvis_t; - -// each area has a list of portals that lead into other areas -// when portals are closed, other areas may not be visible or -// hearable even if the vis info says that it should be -typedef struct -{ - int portalnum; - int otherarea; -} dareaportal_t; - -typedef struct -{ - int numareaportals; - int firstareaportal; -} darea_t; diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/scriplib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/scriplib.c deleted file mode 100644 index 9cab6391..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/scriplib.c +++ /dev/null @@ -1,296 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#include "scriplib.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 true if UnGetToken was just called - -/* -============== -AddScriptToStack -============== -*/ -void AddScriptToStack (char *filename) -{ - int size; - - script++; - if (script == &scriptstack[MAX_INCLUDES]) - Error ("script file exceeded MAX_INCLUDES"); - strcpy (script->filename, ExpandPath (filename) ); - - size = LoadFile (script->filename, (void **)&script->buffer); - - printf ("entering %s\n", script->filename); - - script->line = 1; - - script->script_p = script->buffer; - script->end_p = script->buffer + size; -} - - -/* -============== -LoadScriptFile -============== -*/ -void LoadScriptFile (char *filename) -{ - script = scriptstack; - AddScriptToStack (filename); - - endofscript = false; - tokenready = false; -} - - -/* -============== -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 = false; - tokenready = false; -} - - -/* -============== -UnGetToken - -Signals that the current token was not used, and should be reported -for the next GetToken. Note that - -GetToken (true); -UnGetToken (); -GetToken (false); - -could cross a line boundary. -============== -*/ -void UnGetToken (void) -{ - tokenready = true; -} - - -qboolean EndOfScript (qboolean crossline) -{ - if (!crossline) - Error ("Line %i is incomplete\n",scriptline); - - if (!strcmp (script->filename, "memory buffer")) - { - endofscript = true; - return false; - } - - free (script->buffer); - if (script == scriptstack+1) - { - endofscript = true; - return false; - } - script--; - scriptline = script->line; - printf ("returning to %s\n", script->filename); - return GetToken (crossline); -} - -/* -============== -GetToken -============== -*/ -qboolean GetToken (qboolean crossline) -{ - char *token_p; - - if (tokenready) // is a token allready waiting? - { - tokenready = false; - return true; - } - - if (script->script_p >= script->end_p) - 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); - 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); - 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] != '/') - { - 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 (false); - AddScriptToStack (token); - return GetToken (crossline); - } - - return true; -} - - -/* -============== -TokenAvailable - -Returns true if there is another token on the line -============== -*/ -qboolean TokenAvailable (void) -{ - char *search_p; - - search_p = script->script_p; - - if (search_p >= script->end_p) - return false; - - while ( *search_p <= 32) - { - if (*search_p == '\n') - return false; - search_p++; - if (search_p == script->end_p) - return false; - - } - - if (*search_p == ';') - return false; - - return true; -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/scriplib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/scriplib.h deleted file mode 100644 index d07a9bb4..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/scriplib.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "cmdlib.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 (char *filename); -void ParseFromMemory (char *buffer, int size); - -qboolean GetToken (qboolean crossline); -void UnGetToken (void); -qboolean TokenAvailable (void); - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/threads.c b/misc/mediasource/extra/netradiant-src/tools/quake2/common/threads.c deleted file mode 100644 index 9c123a5a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/threads.c +++ /dev/null @@ -1,618 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "q2_threads.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_FPrintf( SYS_VRB,"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 - -// Setting default Threads to 1 -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 = true; - - // - // run threads in parallel - // - InitializeCriticalSection (&crit); - - if (numthreads == 1) - { // use same thread - func (0); - } - else - { - for (i=0 ; i - -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 = true; - - 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 -#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 = true; - - if (pacifier) - setbuf (stdout, NULL); - - init_lock (&lck); - - for (i=0 ; i 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 = true; - - if(pacifier) - setbuf(stdout, NULL); - - if(pthread_mutexattr_init(&mattrib) != 0) - Error("pthread_mutexattr_init failed"); - if (pthread_mutexattr_settype(&mattrib, PTHREAD_MUTEX_ERRORCHECK) != 0) - Error ("pthread_mutexattr_settype failed"); - recursive_mutex_init(mattrib); - - for (i=0 ; i -#include "cmdlib.h" -#include "inout.h" -#include "mathlib.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 - -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; - - -void ByteSwapTri (tf_triangle *tri) -{ - int i; - - for (i=0 ; iverts[j][k] = tri.pt[j].p.v[k]; - } - } - - ptri++; - - if ((ptri - *pptri) >= MAXTRIANGLES) - Error ("Error: too many triangles; increase MAXTRIANGLES\n"); - } - } - - *numtriangles = ptri - *pptri; - - fclose (input); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/common/trilib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/common/trilib.h deleted file mode 100644 index 5c32244a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/common/trilib.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -// -#define MAXTRIANGLES 2048 - -typedef struct { - vec3_t verts[3]; -} triangle_t; - -void LoadTriangleList (char *filename, triangle_t **pptri, int *numtriangles); - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/brushbsp.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/brushbsp.c deleted file mode 100644 index 53985b03..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/brushbsp.c +++ /dev/null @@ -1,1329 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - - -int c_nodes; -int c_nonvis; -int c_active_brushes; - -// if a brush just barely pokes onto the other side, -// let it slide by without chopping -#define PLANESIDE_EPSILON 0.001 -//0.1 - -#define PSIDE_FRONT 1 -#define PSIDE_BACK 2 -#define PSIDE_BOTH (PSIDE_FRONT|PSIDE_BACK) -#define PSIDE_FACING 4 - - -void FindBrushInTree (node_t *node, int brushnum) -{ - bspbrush_t *b; - - if (node->planenum == PLANENUM_LEAF) - { - for (b=node->brushlist ; b ; b=b->next) - if (b->original->brushnum == brushnum) - Sys_Printf ("here\n"); - return; - } - FindBrushInTree (node->children[0], brushnum); - FindBrushInTree (node->children[1], brushnum); -} - -//================================================== - -/* -================ -DrawBrushList -================ -*/ -void DrawBrushList (bspbrush_t *brush, node_t *node) -{ - int i; - side_t *s; - - GLS_BeginScene (); - for ( ; brush ; brush=brush->next) - { - for (i=0 ; inumsides ; i++) - { - s = &brush->sides[i]; - if (!s->winding) - continue; - if (s->texinfo == TEXINFO_NODE) - GLS_Winding (s->winding, 1); - else if (!s->visible) - GLS_Winding (s->winding, 2); - else - GLS_Winding (s->winding, 0); - } - } - GLS_EndScene (); -} - -/* -================ -WriteBrushList -================ -*/ -void WriteBrushList (char *name, bspbrush_t *brush, qboolean onlyvis) -{ - int i; - side_t *s; - FILE *f; - - Sys_FPrintf( SYS_VRB, "writing %s\n", name); - f = SafeOpenWrite (name); - - for ( ; brush ; brush=brush->next) - { - for (i=0 ; inumsides ; i++) - { - s = &brush->sides[i]; - if (!s->winding) - continue; - if (onlyvis && !s->visible) - continue; - OutputWinding (brush->sides[i].winding, f); - } - } - - fclose (f); -} - -void PrintBrush (bspbrush_t *brush) -{ - int i; - - Sys_Printf ("brush: %p\n", brush); - for (i=0;inumsides ; i++) - { - pw(brush->sides[i].winding); - Sys_Printf ("\n"); - } -} - -/* -================== -BoundBrush - -Sets the mins/maxs based on the windings -================== -*/ -void BoundBrush (bspbrush_t *brush) -{ - int i, j; - winding_t *w; - - ClearBounds (brush->mins, brush->maxs); - for (i=0 ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (!w) - continue; - for (j=0 ; jnumpoints ; j++) - AddPointToBounds (w->p[j], brush->mins, brush->maxs); - } -} - -/* -================== -CreateBrushWindings - -================== -*/ -void CreateBrushWindings (bspbrush_t *brush) -{ - int i, j; - winding_t *w; - side_t *side; - plane_t *plane; - - for (i=0 ; inumsides ; i++) - { - side = &brush->sides[i]; - plane = &mapplanes[side->planenum]; - w = BaseWindingForPlane (plane->normal, plane->dist); - for (j=0 ; jnumsides && w; j++) - { - if (i == j) - continue; - if (brush->sides[j].bevel) - continue; - plane = &mapplanes[brush->sides[j].planenum^1]; - ChopWindingInPlace (&w, plane->normal, plane->dist, 0); //CLIP_EPSILON); - } - - side->winding = w; - } - - BoundBrush (brush); -} - -/* -================== -BrushFromBounds - -Creates a new axial brush -================== -*/ -bspbrush_t *BrushFromBounds (vec3_t mins, vec3_t maxs) -{ - bspbrush_t *b; - int i; - vec3_t normal; - vec_t dist; - - b = AllocBrush (6); - b->numsides = 6; - for (i=0 ; i<3 ; i++) - { - VectorClear (normal); - normal[i] = 1; - dist = maxs[i]; - b->sides[i].planenum = FindFloatPlane (normal, dist); - - normal[i] = -1; - dist = -mins[i]; - b->sides[3+i].planenum = FindFloatPlane (normal, dist); - } - - CreateBrushWindings (b); - - return b; -} - -/* -================== -BrushVolume - -================== -*/ -vec_t BrushVolume (bspbrush_t *brush) -{ - int i; - winding_t *w; - vec3_t corner; - vec_t d, area, volume; - plane_t *plane; - - if (!brush) - return 0; - - // grab the first valid point as the corner - - w = NULL; - for (i=0 ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (w) - break; - } - if (!w) - return 0; - VectorCopy (w->p[0], corner); - - // make tetrahedrons to all other faces - - volume = 0; - for ( ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (!w) - continue; - plane = &mapplanes[brush->sides[i].planenum]; - d = -(DotProduct (corner, plane->normal) - plane->dist); - area = WindingArea (w); - volume += d*area; - } - - volume /= 3; - return volume; -} - -/* -================ -CountBrushList -================ -*/ -int CountBrushList (bspbrush_t *brushes) -{ - int c; - - c = 0; - for ( ; brushes ; brushes = brushes->next) - c++; - return c; -} - -/* -================ -AllocTree -================ -*/ -tree_t *AllocTree (void) -{ - tree_t *tree; - - tree = malloc(sizeof(*tree)); - memset (tree, 0, sizeof(*tree)); - ClearBounds (tree->mins, tree->maxs); - - return tree; -} - -/* -================ -AllocNode -================ -*/ -node_t *AllocNode (void) -{ - node_t *node; - - node = malloc(sizeof(*node)); - memset (node, 0, sizeof(*node)); - - return node; -} - - -/* -================ -AllocBrush -================ -*/ -bspbrush_t *AllocBrush (int numsides) -{ - bspbrush_t *bb; - int c; - - c = (int)&(((bspbrush_t *)0)->sides[numsides]); - bb = malloc(c); - memset (bb, 0, c); - if (numthreads == 1) - c_active_brushes++; - return bb; -} - -/* -================ -FreeBrush -================ -*/ -void FreeBrush (bspbrush_t *brushes) -{ - int i; - - for (i=0 ; inumsides ; i++) - if (brushes->sides[i].winding) - FreeWinding(brushes->sides[i].winding); - free (brushes); - if (numthreads == 1) - c_active_brushes--; -} - - -/* -================ -FreeBrushList -================ -*/ -void FreeBrushList (bspbrush_t *brushes) -{ - bspbrush_t *next; - - for ( ; brushes ; brushes = next) - { - next = brushes->next; - - FreeBrush (brushes); - } -} - -/* -================== -CopyBrush - -Duplicates the brush, the sides, and the windings -================== -*/ -bspbrush_t *CopyBrush (bspbrush_t *brush) -{ - bspbrush_t *newbrush; - int size; - int i; - - size = (int)&(((bspbrush_t *)0)->sides[brush->numsides]); - - newbrush = AllocBrush (brush->numsides); - memcpy (newbrush, brush, size); - - for (i=0 ; inumsides ; i++) - { - if (brush->sides[i].winding) - newbrush->sides[i].winding = CopyWinding (brush->sides[i].winding); - } - - return newbrush; -} - - -/* -================== -PointInLeaf - -================== -*/ -node_t *PointInLeaf (node_t *node, vec3_t point) -{ - vec_t d; - plane_t *plane; - - while (node->planenum != PLANENUM_LEAF) - { - plane = &mapplanes[node->planenum]; - d = DotProduct (point, plane->normal) - plane->dist; - if (d > 0) - node = node->children[0]; - else - node = node->children[1]; - } - - return node; -} - -//======================================================== - -/* -============== -BoxOnPlaneSide - -Returns PSIDE_FRONT, PSIDE_BACK, or PSIDE_BOTH -============== -*/ -int BoxOnPlaneSide (vec3_t mins, vec3_t maxs, plane_t *plane) -{ - int side; - int i; - vec3_t corners[2]; - vec_t dist1, dist2; - - // axial planes are easy - if (plane->type < 3) - { - side = 0; - if (maxs[plane->type] > plane->dist+PLANESIDE_EPSILON) - side |= PSIDE_FRONT; - if (mins[plane->type] < plane->dist-PLANESIDE_EPSILON) - side |= PSIDE_BACK; - return side; - } - - // create the proper leading and trailing verts for the box - - for (i=0 ; i<3 ; i++) - { - if (plane->normal[i] < 0) - { - corners[0][i] = mins[i]; - corners[1][i] = maxs[i]; - } - else - { - corners[1][i] = mins[i]; - corners[0][i] = maxs[i]; - } - } - - dist1 = DotProduct (plane->normal, corners[0]) - plane->dist; - dist2 = DotProduct (plane->normal, corners[1]) - plane->dist; - side = 0; - if (dist1 >= PLANESIDE_EPSILON) - side = PSIDE_FRONT; - if (dist2 < PLANESIDE_EPSILON) - side |= PSIDE_BACK; - - return side; -} - -/* -============ -QuickTestBrushToPlanenum - -============ -*/ -int QuickTestBrushToPlanenum (bspbrush_t *brush, int planenum, int *numsplits) -{ - int i, num; - plane_t *plane; - int s; - - *numsplits = 0; - - // if the brush actually uses the planenum, - // we can tell the side for sure - for (i=0 ; inumsides ; i++) - { - num = brush->sides[i].planenum; - if (num >= 0x10000) - Error ("bad planenum"); - if (num == planenum) - return PSIDE_BACK|PSIDE_FACING; - if (num == (planenum ^ 1) ) - return PSIDE_FRONT|PSIDE_FACING; - } - - // box on plane side - plane = &mapplanes[planenum]; - s = BoxOnPlaneSide (brush->mins, brush->maxs, plane); - - // if both sides, count the visible faces split - if (s == PSIDE_BOTH) - { - *numsplits += 3; - } - - return s; -} - -/* -============ -TestBrushToPlanenum - -============ -*/ -int TestBrushToPlanenum (bspbrush_t *brush, int planenum, - int *numsplits, qboolean *hintsplit, int *epsilonbrush) -{ - int i, j, num; - plane_t *plane; - int s; - winding_t *w; - vec_t d, d_front, d_back; - int front, back; - - *numsplits = 0; - *hintsplit = false; - - // if the brush actually uses the planenum, - // we can tell the side for sure - for (i=0 ; inumsides ; i++) - { - num = brush->sides[i].planenum; - if (num >= 0x10000) - Error ("bad planenum"); - if (num == planenum) - return PSIDE_BACK|PSIDE_FACING; - if (num == (planenum ^ 1) ) - return PSIDE_FRONT|PSIDE_FACING; - } - - // box on plane side - plane = &mapplanes[planenum]; - s = BoxOnPlaneSide (brush->mins, brush->maxs, plane); - - if (s != PSIDE_BOTH) - return s; - -// if both sides, count the visible faces split - d_front = d_back = 0; - - for (i=0 ; inumsides ; i++) - { - if (brush->sides[i].texinfo == TEXINFO_NODE) - continue; // on node, don't worry about splits - if (!brush->sides[i].visible) - continue; // we don't care about non-visible - w = brush->sides[i].winding; - if (!w) - continue; - front = back = 0; - for (j=0 ; jnumpoints; j++) - { - d = DotProduct (w->p[j], plane->normal) - plane->dist; - if (d > d_front) - d_front = d; - if (d < d_back) - d_back = d; - - if (d > 0.1) // PLANESIDE_EPSILON) - front = 1; - if (d < -0.1) // PLANESIDE_EPSILON) - back = 1; - } - if (front && back) - { - if ( !(brush->sides[i].surf & SURF_SKIP) ) - { - (*numsplits)++; - if (brush->sides[i].surf & SURF_HINT) - *hintsplit = true; - } - } - } - - if ( (d_front > 0.0 && d_front < 1.0) - || (d_back < 0.0 && d_back > -1.0) ) - (*epsilonbrush)++; - -#if 0 - if (*numsplits == 0) - { // didn't really need to be split - if (front) - s = PSIDE_FRONT; - else if (back) - s = PSIDE_BACK; - else - s = 0; - } -#endif - - return s; -} - -//======================================================== - -/* -================ -WindingIsTiny - -Returns true if the winding would be crunched out of -existance by the vertex snapping. -================ -*/ -#define EDGE_LENGTH 0.2 -qboolean WindingIsTiny (winding_t *w) -{ -#if 0 - if (WindingArea (w) < 1) - return true; - return false; -#else - int i, j; - vec_t len; - vec3_t delta; - int edges; - - edges = 0; - for (i=0 ; inumpoints ; i++) - { - j = i == w->numpoints - 1 ? 0 : i+1; - VectorSubtract (w->p[j], w->p[i], delta); - len = (float) VectorLength (delta); - if (len > EDGE_LENGTH) - { - if (++edges == 3) - return false; - } - } - return true; -#endif -} - -/* -================ -WindingIsHuge - -Returns true if the winding still has one of the points -from basewinding for plane -================ -*/ -qboolean WindingIsHuge (winding_t *w) -{ - int i, j; - - for (i=0 ; inumpoints ; i++) - { - for (j=0 ; j<3 ; j++) - if (w->p[i][j] < -8000 || w->p[i][j] > 8000) - return true; - } - return false; -} - -//============================================================ - -/* -================ -Leafnode -================ -*/ -void LeafNode (node_t *node, bspbrush_t *brushes) -{ - bspbrush_t *b; - int i; - - node->planenum = PLANENUM_LEAF; - node->contents = 0; - - for (b=brushes ; b ; b=b->next) - { - // if the brush is solid and all of its sides are on nodes, - // it eats everything - if (b->original->contents & CONTENTS_SOLID) - { - for (i=0 ; inumsides ; i++) - if (b->sides[i].texinfo != TEXINFO_NODE) - break; - if (i == b->numsides) - { - node->contents = CONTENTS_SOLID; - break; - } - } - node->contents |= b->original->contents; - } - - node->brushlist = brushes; -} - - -//============================================================ - -void CheckPlaneAgainstParents (int pnum, node_t *node) -{ - node_t *p; - - for (p=node->parent ; p ; p=p->parent) - { - if (p->planenum == pnum) - Error ("Tried parent"); - } -} - -qboolean CheckPlaneAgainstVolume (int pnum, node_t *node) -{ - bspbrush_t *front, *back; - qboolean good; - - SplitBrush (node->volume, pnum, &front, &back); - - good = (front && back); - - if (front) - FreeBrush (front); - if (back) - FreeBrush (back); - - return good; -} - -/* -================ -SelectSplitSide - -Using a hueristic, choses one of the sides out of the brushlist -to partition the brushes with. -Returns NULL if there are no valid planes to split with.. -================ -*/ -side_t *SelectSplitSide (bspbrush_t *brushes, node_t *node) -{ - int value, bestvalue; - bspbrush_t *brush, *test; - side_t *side, *bestside; - int i, j, pass, numpasses; - int pnum; - int s; - int front, back, both, facing, splits; - int bsplits; - int bestsplits; - int epsilonbrush; - qboolean hintsplit; - - bestside = NULL; - bestvalue = -99999; - bestsplits = 0; - - // the search order goes: visible-structural, visible-detail, - // nonvisible-structural, nonvisible-detail. - // If any valid plane is available in a pass, no further - // passes will be tried. - numpasses = 4; - for (pass = 0 ; pass < numpasses ; pass++) - { - for (brush = brushes ; brush ; brush=brush->next) - { - if ( (pass & 1) && !(brush->original->contents & CONTENTS_DETAIL) ) - continue; - if ( !(pass & 1) && (brush->original->contents & CONTENTS_DETAIL) ) - continue; - for (i=0 ; inumsides ; i++) - { - side = brush->sides + i; - if (side->bevel) - continue; // never use a bevel as a spliter - if (!side->winding) - continue; // nothing visible, so it can't split - if (side->texinfo == TEXINFO_NODE) - continue; // allready a node splitter - if (side->tested) - continue; // we allready have metrics for this plane - if (side->surf & SURF_SKIP) - continue; // skip surfaces are never chosen - if ( side->visible ^ (pass<2) ) - continue; // only check visible faces on first pass - - pnum = side->planenum; - pnum &= ~1; // allways use positive facing plane - - CheckPlaneAgainstParents (pnum, node); - - if (!CheckPlaneAgainstVolume (pnum, node)) - continue; // would produce a tiny volume - - front = 0; - back = 0; - both = 0; - facing = 0; - splits = 0; - epsilonbrush = 0; - - for (test = brushes ; test ; test=test->next) - { - s = TestBrushToPlanenum (test, pnum, &bsplits, &hintsplit, &epsilonbrush); - - splits += bsplits; - if (bsplits && (s&PSIDE_FACING) ) - Error ("PSIDE_FACING with splits"); - - test->testside = s; - // if the brush shares this face, don't bother - // testing that facenum as a splitter again - if (s & PSIDE_FACING) - { - facing++; - for (j=0 ; jnumsides ; j++) - { - if ( (test->sides[j].planenum&~1) == pnum) - test->sides[j].tested = true; - } - } - if (s & PSIDE_FRONT) - front++; - if (s & PSIDE_BACK) - back++; - if (s == PSIDE_BOTH) - both++; - } - - // give a value estimate for using this plane - - value = 5*facing - 5*splits - abs(front-back); -// value = -5*splits; -// value = 5*facing - 5*splits; - if (mapplanes[pnum].type < 3) - value+=5; // axial is better - value -= epsilonbrush*1000; // avoid! - - // never split a hint side except with another hint - if (hintsplit && !(side->surf & SURF_HINT) ) - value = -9999999; - - // save off the side test so we don't need - // to recalculate it when we actually seperate - // the brushes - if (value > bestvalue) - { - bestvalue = value; - bestside = side; - bestsplits = splits; - for (test = brushes ; test ; test=test->next) - test->side = test->testside; - } - } - } - - // if we found a good plane, don't bother trying any - // other passes - if (bestside) - { - if (pass > 1) - { - if (numthreads == 1) - c_nonvis++; - } - if (pass > 0) - node->detail_seperator = true; // not needed for vis - break; - } - } - - // - // clear all the tested flags we set - // - for (brush = brushes ; brush ; brush=brush->next) - { - for (i=0 ; inumsides ; i++) - brush->sides[i].tested = false; - } - - return bestside; -} - - -/* -================== -BrushMostlyOnSide - -================== -*/ -int BrushMostlyOnSide (bspbrush_t *brush, plane_t *plane) -{ - int i, j; - winding_t *w; - vec_t d, max; - int side; - - max = 0; - side = PSIDE_FRONT; - for (i=0 ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (!w) - continue; - for (j=0 ; jnumpoints ; j++) - { - d = DotProduct (w->p[j], plane->normal) - plane->dist; - if (d > max) - { - max = d; - side = PSIDE_FRONT; - } - if (-d > max) - { - max = -d; - side = PSIDE_BACK; - } - } - } - return side; -} - -/* -================ -SplitBrush - -Generates two new brushes, leaving the original -unchanged -================ -*/ -void SplitBrush (bspbrush_t *brush, int planenum, - bspbrush_t **front, bspbrush_t **back) -{ - bspbrush_t *b[2]; - int i, j; - winding_t *w, *cw[2], *midwinding; - plane_t *plane, *plane2; - side_t *s, *cs; - float d, d_front, d_back; - - *front = *back = NULL; - plane = &mapplanes[planenum]; - - // check all points - d_front = d_back = 0; - for (i=0 ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (!w) - continue; - for (j=0 ; jnumpoints ; j++) - { - d = DotProduct (w->p[j], plane->normal) - plane->dist; - if (d > 0 && d > d_front) - d_front = d; - if (d < 0 && d < d_back) - d_back = d; - } - } - if (d_front < 0.1) // PLANESIDE_EPSILON) - { // only on back - *back = CopyBrush (brush); - return; - } - if (d_back > -0.1) // PLANESIDE_EPSILON) - { // only on front - *front = CopyBrush (brush); - return; - } - - // create a new winding from the split plane - - w = BaseWindingForPlane (plane->normal, plane->dist); - for (i=0 ; inumsides && w ; i++) - { - plane2 = &mapplanes[brush->sides[i].planenum ^ 1]; - ChopWindingInPlace (&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON); - } - - if (!w || WindingIsTiny (w) ) - { // the brush isn't really split - int side; - - side = BrushMostlyOnSide (brush, plane); - if (side == PSIDE_FRONT) - *front = CopyBrush (brush); - if (side == PSIDE_BACK) - *back = CopyBrush (brush); - return; - } - - if (WindingIsHuge (w)) - { - Sys_FPrintf( SYS_VRB, "WARNING: huge winding\n"); - } - - midwinding = w; - - // split it for real - - for (i=0 ; i<2 ; i++) - { - b[i] = AllocBrush (brush->numsides+1); - b[i]->original = brush->original; - } - - // split all the current windings - - for (i=0 ; inumsides ; i++) - { - s = &brush->sides[i]; - w = s->winding; - if (!w) - continue; - ClipWindingEpsilon (w, plane->normal, plane->dist, - 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]); - for (j=0 ; j<2 ; j++) - { - if (!cw[j]) - continue; -#if 0 - if (WindingIsTiny (cw[j])) - { - FreeWinding (cw[j]); - continue; - } -#endif - cs = &b[j]->sides[b[j]->numsides]; - b[j]->numsides++; - *cs = *s; -// cs->planenum = s->planenum; -// cs->texinfo = s->texinfo; -// cs->visible = s->visible; -// cs->original = s->original; - cs->winding = cw[j]; - cs->tested = false; - } - } - - - // see if we have valid polygons on both sides - - for (i=0 ; i<2 ; i++) - { - BoundBrush (b[i]); - for (j=0 ; j<3 ; j++) - { - if (b[i]->mins[j] < -4096 || b[i]->maxs[j] > 4096) - { - Sys_FPrintf( SYS_VRB, "bogus brush after clip\n"); - break; - } - } - - if (b[i]->numsides < 3 || j < 3) - { - FreeBrush (b[i]); - b[i] = NULL; - } - } - - if ( !(b[0] && b[1]) ) - { - if (!b[0] && !b[1]) - Sys_FPrintf( SYS_VRB, "split removed brush\n"); - else - Sys_FPrintf( SYS_VRB, "split not on both sides\n"); - if (b[0]) - { - FreeBrush (b[0]); - *front = CopyBrush (brush); - } - if (b[1]) - { - FreeBrush (b[1]); - *back = CopyBrush (brush); - } - return; - } - - // add the midwinding to both sides - for (i=0 ; i<2 ; i++) - { - cs = &b[i]->sides[b[i]->numsides]; - b[i]->numsides++; - - cs->planenum = planenum^i^1; - cs->texinfo = TEXINFO_NODE; - cs->visible = false; - cs->tested = false; - if (i==0) - cs->winding = CopyWinding (midwinding); - else - cs->winding = midwinding; - } - -{ - vec_t v1; - int i; - - for (i=0 ; i<2 ; i++) - { - v1 = BrushVolume (b[i]); - if (v1 < 1.0) - { - FreeBrush (b[i]); - b[i] = NULL; - Sys_FPrintf( SYS_VRB, "tiny volume after clip\n"); - } - } -} - - *front = b[0]; - *back = b[1]; -} - -/* -================ -SplitBrushList -================ -*/ -void SplitBrushList (bspbrush_t *brushes, - node_t *node, bspbrush_t **front, bspbrush_t **back) -{ - bspbrush_t *brush, *newbrush, *newbrush2; - side_t *side; - int sides; - int i; - - *front = *back = NULL; - - for (brush = brushes ; brush ; brush=brush->next) - { - sides = brush->side; - - if (sides == PSIDE_BOTH) - { // split into two brushes - SplitBrush (brush, node->planenum, &newbrush, &newbrush2); - if (newbrush) - { - newbrush->next = *front; - *front = newbrush; - } - if (newbrush2) - { - newbrush2->next = *back; - *back = newbrush2; - } - continue; - } - - newbrush = CopyBrush (brush); - - // if the planenum is actualy a part of the brush - // find the plane and flag it as used so it won't be tried - // as a splitter again - if (sides & PSIDE_FACING) - { - for (i=0 ; inumsides ; i++) - { - side = newbrush->sides + i; - if ( (side->planenum& ~1) == node->planenum) - side->texinfo = TEXINFO_NODE; - } - } - - - if (sides & PSIDE_FRONT) - { - newbrush->next = *front; - *front = newbrush; - continue; - } - if (sides & PSIDE_BACK) - { - newbrush->next = *back; - *back = newbrush; - continue; - } - } -} - - -/* -================ -BuildTree_r -================ -*/ -node_t *BuildTree_r (node_t *node, bspbrush_t *brushes) -{ - node_t *newnode; - side_t *bestside; - int i; - bspbrush_t *children[2]; - - if (numthreads == 1) - c_nodes++; - - if (drawflag) - DrawBrushList (brushes, node); - - // find the best plane to use as a splitter - bestside = SelectSplitSide (brushes, node); - if (!bestside) - { - // leaf node - node->side = NULL; - node->planenum = -1; - LeafNode (node, brushes); - return node; - } - - // this is a splitplane node - node->side = bestside; - node->planenum = bestside->planenum & ~1; // always use front facing - - SplitBrushList (brushes, node, &children[0], &children[1]); - FreeBrushList (brushes); - - // allocate children before recursing - for (i=0 ; i<2 ; i++) - { - newnode = AllocNode (); - newnode->parent = node; - node->children[i] = newnode; - } - - SplitBrush (node->volume, node->planenum, &node->children[0]->volume, - &node->children[1]->volume); - - // recursively process children - for (i=0 ; i<2 ; i++) - { - node->children[i] = BuildTree_r (node->children[i], children[i]); - } - - return node; -} - -//=========================================================== - -/* -================= -BrushBSP - -The incoming list will be freed before exiting -================= -*/ -tree_t *BrushBSP (bspbrush_t *brushlist, vec3_t mins, vec3_t maxs) -{ - node_t *node; - bspbrush_t *b; - int c_faces, c_nonvisfaces; - int c_brushes; - tree_t *tree; - int i; - vec_t volume; - - Sys_FPrintf( SYS_VRB, "--- BrushBSP ---\n"); - - tree = AllocTree (); - - c_faces = 0; - c_nonvisfaces = 0; - c_brushes = 0; - for (b=brushlist ; b ; b=b->next) - { - c_brushes++; - - volume = BrushVolume (b); - if (volume < microvolume) - { - Sys_Printf ("WARNING: entity %i, brush %i: microbrush\n", - b->original->entitynum, b->original->brushnum); - } - - for (i=0 ; inumsides ; i++) - { - if (b->sides[i].bevel) - continue; - if (!b->sides[i].winding) - continue; - if (b->sides[i].texinfo == TEXINFO_NODE) - continue; - if (b->sides[i].visible) - c_faces++; - else - c_nonvisfaces++; - } - - AddPointToBounds (b->mins, tree->mins, tree->maxs); - AddPointToBounds (b->maxs, tree->mins, tree->maxs); - } - - Sys_FPrintf( SYS_VRB, "%5i brushes\n", c_brushes); - Sys_FPrintf( SYS_VRB, "%5i visible faces\n", c_faces); - Sys_FPrintf( SYS_VRB, "%5i nonvisible faces\n", c_nonvisfaces); - - c_nodes = 0; - c_nonvis = 0; - node = AllocNode (); - - node->volume = BrushFromBounds (mins, maxs); - - tree->headnode = node; - - node = BuildTree_r (node, brushlist); - Sys_FPrintf( SYS_VRB, "%5i visible nodes\n", c_nodes/2 - c_nonvis); - Sys_FPrintf( SYS_VRB, "%5i nonvis nodes\n", c_nonvis); - Sys_FPrintf( SYS_VRB, "%5i leafs\n", (c_nodes+1)/2); -#if 0 -{ // debug code -static node_t *tnode; -vec3_t p; - -p[0] = -1469; -p[1] = -118; -p[2] = 119; -tnode = PointInLeaf (tree->headnode, p); -Sys_Printf ("contents: %i\n", tnode->contents); -p[0] = 0; -} -#endif - return tree; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/csg.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/csg.c deleted file mode 100644 index 2e058299..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/csg.c +++ /dev/null @@ -1,634 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -/* - -tag all brushes with original contents -brushes may contain multiple contents -there will be no brush overlap after csg phase - - - - -each side has a count of the other sides it splits - -the best split will be the one that minimizes the total split counts -of all remaining sides - -precalc side on plane table - -evaluate split side -{ -cost = 0 -for all sides - for all sides - get - if side splits side and splitside is on same child - cost++; -} - - - */ - -void SplitBrush2 (bspbrush_t *brush, int planenum, - bspbrush_t **front, bspbrush_t **back) -{ - SplitBrush (brush, planenum, front, back); -#if 0 - if (*front && (*front)->sides[(*front)->numsides-1].texinfo == -1) - (*front)->sides[(*front)->numsides-1].texinfo = (*front)->sides[0].texinfo; // not -1 - if (*back && (*back)->sides[(*back)->numsides-1].texinfo == -1) - (*back)->sides[(*back)->numsides-1].texinfo = (*back)->sides[0].texinfo; // not -1 -#endif -} - -/* -=============== -SubtractBrush - -Returns a list of brushes that remain after B is subtracted from A. -May by empty if A is contained inside B. - -The originals are undisturbed. -=============== -*/ -bspbrush_t *SubtractBrush (bspbrush_t *a, bspbrush_t *b) -{ // a - b = out (list) - int i; - bspbrush_t *front, *back; - bspbrush_t *out, *in; - - in = a; - out = NULL; - for (i=0 ; inumsides && in ; i++) - { - SplitBrush2 (in, b->sides[i].planenum, &front, &back); - if (in != a) - FreeBrush (in); - if (front) - { // add to list - front->next = out; - out = front; - } - in = back; - } - if (in) - FreeBrush (in); - else - { // didn't really intersect - FreeBrushList (out); - return a; - } - return out; -} - -/* -=============== -IntersectBrush - -Returns a single brush made up by the intersection of the -two provided brushes, or NULL if they are disjoint. - -The originals are undisturbed. -=============== -*/ -bspbrush_t *IntersectBrush (bspbrush_t *a, bspbrush_t *b) -{ - int i; - bspbrush_t *front, *back; - bspbrush_t *in; - - in = a; - for (i=0 ; inumsides && in ; i++) - { - SplitBrush2 (in, b->sides[i].planenum, &front, &back); - if (in != a) - FreeBrush (in); - if (front) - FreeBrush (front); - in = back; - } - - if (in == a) - return NULL; - - in->next = NULL; - return in; -} - - -/* -=============== -BrushesDisjoint - -Returns true if the two brushes definately do not intersect. -There will be false negatives for some non-axial combinations. -=============== -*/ -qboolean BrushesDisjoint (bspbrush_t *a, bspbrush_t *b) -{ - int i, j; - - // check bounding boxes - for (i=0 ; i<3 ; i++) - if (a->mins[i] >= b->maxs[i] - || a->maxs[i] <= b->mins[i]) - return true; // bounding boxes don't overlap - - // check for opposing planes - for (i=0 ; inumsides ; i++) - { - for (j=0 ; jnumsides ; j++) - { - if (a->sides[i].planenum == - (b->sides[j].planenum^1) ) - return true; // opposite planes, so not touching - } - } - - return false; // might intersect -} - -/* -=============== -IntersectionContents - -Returns a content word for the intersection of two brushes. -Some combinations will generate a combination (water + clip), -but most will be the stronger of the two contents. -=============== -*/ -int IntersectionContents (int c1, int c2) -{ - int out; - - out = c1 | c2; - - if (out & CONTENTS_SOLID) - out = CONTENTS_SOLID; - - return out; -} - - -int minplanenums[3]; -int maxplanenums[3]; - -/* -=============== -ClipBrushToBox - -Any planes shared with the box edge will be set to no texinfo -=============== -*/ -bspbrush_t *ClipBrushToBox (bspbrush_t *brush, vec3_t clipmins, vec3_t clipmaxs) -{ - int i, j; - bspbrush_t *front, *back; - int p; - - for (j=0 ; j<2 ; j++) - { - if (brush->maxs[j] > clipmaxs[j]) - { - SplitBrush (brush, maxplanenums[j], &front, &back); - if (front) - FreeBrush (front); - brush = back; - if (!brush) - return NULL; - } - if (brush->mins[j] < clipmins[j]) - { - SplitBrush (brush, minplanenums[j], &front, &back); - if (back) - FreeBrush (back); - brush = front; - if (!brush) - return NULL; - } - } - - // remove any colinear faces - - for (i=0 ; inumsides ; i++) - { - p = brush->sides[i].planenum & ~1; - if (p == maxplanenums[0] || p == maxplanenums[1] - || p == minplanenums[0] || p == minplanenums[1]) - { - brush->sides[i].texinfo = TEXINFO_NODE; - brush->sides[i].visible = false; - } - } - return brush; -} - -/* -=============== -MakeBspBrushList -=============== -*/ -bspbrush_t *MakeBspBrushList (int startbrush, int endbrush, - vec3_t clipmins, vec3_t clipmaxs) -{ - mapbrush_t *mb; - bspbrush_t *brushlist, *newbrush; - int i, j; - int c_faces; - int c_brushes; - int numsides; - int vis; - vec3_t normal; - float dist; - - for (i=0 ; i<2 ; i++) - { - VectorClear (normal); - normal[i] = 1; - dist = clipmaxs[i]; - maxplanenums[i] = FindFloatPlane (normal, dist); - dist = clipmins[i]; - minplanenums[i] = FindFloatPlane (normal, dist); - } - - brushlist = NULL; - c_faces = 0; - c_brushes = 0; - - for (i=startbrush ; inumsides; - if (!numsides) - continue; - // make sure the brush has at least one face showing - vis = 0; - for (j=0 ; joriginal_sides[j].visible && mb->original_sides[j].winding) - vis++; -#if 0 - if (!vis) - continue; // no faces at all -#endif - // if the brush is outside the clip area, skip it - for (j=0 ; j<3 ; j++) - if (mb->mins[j] >= clipmaxs[j] - || mb->maxs[j] <= clipmins[j]) - break; - if (j != 3) - continue; - - // - // make a copy of the brush - // - newbrush = AllocBrush (mb->numsides); - newbrush->original = mb; - newbrush->numsides = mb->numsides; - memcpy (newbrush->sides, mb->original_sides, numsides*sizeof(side_t)); - for (j=0 ; jsides[j].winding) - newbrush->sides[j].winding = CopyWinding (newbrush->sides[j].winding); - if (newbrush->sides[j].surf & SURF_HINT) - newbrush->sides[j].visible = true; // hints are always visible - } - VectorCopy (mb->mins, newbrush->mins); - VectorCopy (mb->maxs, newbrush->maxs); - - // - // carve off anything outside the clip box - // - newbrush = ClipBrushToBox (newbrush, clipmins, clipmaxs); - if (!newbrush) - continue; - - c_faces += vis; - c_brushes++; - - newbrush->next = brushlist; - brushlist = newbrush; - } - - return brushlist; -} - -/* -=============== -AddBspBrushListToTail -=============== -*/ -bspbrush_t *AddBrushListToTail (bspbrush_t *list, bspbrush_t *tail) -{ - bspbrush_t *walk, *next; - - for (walk=list ; walk ; walk=next) - { // add to end of list - next = walk->next; - walk->next = NULL; - tail->next = walk; - tail = walk; - } - - return tail; -} - -/* -=========== -CullList - -Builds a new list that doesn't hold the given brush -=========== -*/ -bspbrush_t *CullList (bspbrush_t *list, bspbrush_t *skip1) -{ - bspbrush_t *newlist; - bspbrush_t *next; - - newlist = NULL; - - for ( ; list ; list = next) - { - next = list->next; - if (list == skip1) - { - FreeBrush (list); - continue; - } - list->next = newlist; - newlist = list; - } - return newlist; -} - - -/* -================== -WriteBrushMap -================== -*/ -void WriteBrushMap (char *name, bspbrush_t *list) -{ - FILE *f; - side_t *s; - int i; - winding_t *w; - - Sys_Printf ("writing %s\n", name); - f = fopen (name, "wb"); - if (!f) - Error ("Can't write %s\b", name); - - fprintf (f, "{\n\"classname\" \"worldspawn\"\n"); - - for ( ; list ; list=list->next ) - { - fprintf (f, "{\n"); - for (i=0,s=list->sides ; inumsides ; i++,s++) - { - w = BaseWindingForPlane (mapplanes[s->planenum].normal, mapplanes[s->planenum].dist); - - fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]); - fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]); - fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]); - - fprintf (f, "%s 0 0 0 1 1\n", texinfo[s->texinfo].texture); - FreeWinding (w); - } - fprintf (f, "}\n"); - } - fprintf (f, "}\n"); - - fclose (f); - -} - -/* -================== -BrushGE - -Returns true if b1 is allowed to bite b2 -================== -*/ -qboolean BrushGE (bspbrush_t *b1, bspbrush_t *b2) -{ - // detail brushes never bite structural brushes - if ( (b1->original->contents & CONTENTS_DETAIL) - && !(b2->original->contents & CONTENTS_DETAIL) ) - return false; - if (b1->original->contents & CONTENTS_SOLID) - return true; - return false; -} - -/* -================= -ChopBrushes - -Carves any intersecting solid brushes into the minimum number -of non-intersecting brushes. -================= -*/ -bspbrush_t *ChopBrushes (bspbrush_t *head) -{ - bspbrush_t *b1, *b2, *next; - bspbrush_t *tail; - bspbrush_t *keep; - bspbrush_t *sub, *sub2; - int c1, c2; - - Sys_FPrintf( SYS_VRB, "---- ChopBrushes ----\n"); - Sys_FPrintf( SYS_VRB, "original brushes: %i\n", CountBrushList (head)); - -#if 0 - if (startbrush == 0) - WriteBrushList ("before.gl", head, false); -#endif - keep = NULL; - -newlist: - // find tail - if (!head) - return NULL; - for (tail=head ; tail->next ; tail=tail->next) - ; - - for (b1=head ; b1 ; b1=next) - { - next = b1->next; - for (b2=b1->next ; b2 ; b2 = b2->next) - { - if (BrushesDisjoint (b1, b2)) - continue; - - sub = NULL; - sub2 = NULL; - c1 = 999999; - c2 = 999999; - - if ( BrushGE (b2, b1) ) - { - sub = SubtractBrush (b1, b2); - if (sub == b1) - continue; // didn't really intersect - if (!sub) - { // b1 is swallowed by b2 - head = CullList (b1, b1); - goto newlist; - } - c1 = CountBrushList (sub); - } - - if ( BrushGE (b1, b2) ) - { - sub2 = SubtractBrush (b2, b1); - if (sub2 == b2) - continue; // didn't really intersect - if (!sub2) - { // b2 is swallowed by b1 - FreeBrushList (sub); - head = CullList (b1, b2); - goto newlist; - } - c2 = CountBrushList (sub2); - } - - if (!sub && !sub2) - continue; // neither one can bite - - // only accept if it didn't fragment - // (commening this out allows full fragmentation) - if (c1 > 1 && c2 > 1) - { - if (sub2) - FreeBrushList (sub2); - if (sub) - FreeBrushList (sub); - continue; - } - - if (c1 < c2) - { - if (sub2) - FreeBrushList (sub2); - tail = AddBrushListToTail (sub, tail); - head = CullList (b1, b1); - goto newlist; - } - else - { - if (sub) - FreeBrushList (sub); - tail = AddBrushListToTail (sub2, tail); - head = CullList (b1, b2); - goto newlist; - } - } - - if (!b2) - { // b1 is no longer intersecting anything, so keep it - b1->next = keep; - keep = b1; - } - } - - Sys_FPrintf( SYS_VRB, "output brushes: %i\n", CountBrushList (keep)); -#if 0 - { - WriteBrushList ("after.gl", keep, false); - WriteBrushMap ("after.map", keep); - } -#endif - return keep; -} - - -/* -================= -InitialBrushList -================= -*/ -bspbrush_t *InitialBrushList (bspbrush_t *list) -{ - bspbrush_t *b; - bspbrush_t *out, *newb; - int i; - - // only return brushes that have visible faces - out = NULL; - for (b=list ; b ; b=b->next) - { -#if 0 - for (i=0 ; inumsides ; i++) - if (b->sides[i].visible) - break; - if (i == b->numsides) - continue; -#endif - newb = CopyBrush (b); - newb->next = out; - out = newb; - - // clear visible, so it must be set by MarkVisibleFaces_r - // to be used in the optimized list - for (i=0 ; inumsides ; i++) - { - newb->sides[i].original = &b->sides[i]; -// newb->sides[i].visible = true; - b->sides[i].visible = false; - } - } - - return out; -} - -/* -================= -OptimizedBrushList -================= -*/ -bspbrush_t *OptimizedBrushList (bspbrush_t *list) -{ - bspbrush_t *b; - bspbrush_t *out, *newb; - int i; - - // only return brushes that have visible faces - out = NULL; - for (b=list ; b ; b=b->next) - { - for (i=0 ; inumsides ; i++) - if (b->sides[i].visible) - break; - if (i == b->numsides) - continue; - newb = CopyBrush (b); - newb->next = out; - out = newb; - } - -// WriteBrushList ("vis.gl", out, true); - - return out; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/faces.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/faces.c deleted file mode 100644 index 03d5b955..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/faces.c +++ /dev/null @@ -1,1076 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// faces.c - -#include "qbsp.h" - -/* - - some faces will be removed before saving, but still form nodes: - - the insides of sky volumes - meeting planes of different water current volumes - -*/ - -// undefine for dumb linear searches -#define USE_HASHING - -#define INTEGRAL_EPSILON 0.01 -#define POINT_EPSILON 0.5 -#define OFF_EPSILON 0.5 - -int c_merge; -int c_subdivide; - -int c_totalverts; -int c_uniqueverts; -int c_degenerate; -int c_tjunctions; -int c_faceoverflows; -int c_facecollapse; -int c_badstartverts; - -#define MAX_SUPERVERTS 512 -int superverts[MAX_SUPERVERTS]; -int numsuperverts; - -face_t *edgefaces[MAX_MAP_EDGES][2]; -int firstmodeledge = 1; -int firstmodelface; - -int c_tryedges; - -vec3_t edge_dir; -vec3_t edge_start; -vec_t edge_len; - -int num_edge_verts; -int edge_verts[MAX_MAP_VERTS]; - - -float subdivide_size = 240; - - -face_t *NewFaceFromFace (face_t *f); - -//=========================================================================== - -typedef struct hashvert_s -{ - struct hashvert_s *next; - int num; -} hashvert_t; - - -#define HASH_SIZE 64 - - -int vertexchain[MAX_MAP_VERTS]; // the next vertex in a hash chain -int hashverts[HASH_SIZE*HASH_SIZE]; // a vertex number, or 0 for no verts - -face_t *edgefaces[MAX_MAP_EDGES][2]; - -//============================================================================ - - -unsigned HashVec (vec3_t vec) -{ - int x, y; - - x = (4096 + (int)(vec[0]+0.5)) >> 7; - y = (4096 + (int)(vec[1]+0.5)) >> 7; - - if ( x < 0 || x >= HASH_SIZE || y < 0 || y >= HASH_SIZE ) - Error ("HashVec: point outside valid range"); - - return y*HASH_SIZE + x; -} - -#ifdef USE_HASHING -/* -============= -GetVertex - -Uses hashing -============= -*/ -int GetVertexnum (vec3_t in) -{ - int h; - int i; - float *p; - vec3_t vert; - int vnum; - - c_totalverts++; - - for (i=0 ; i<3 ; i++) - { - if ( fabs(in[i] - Q_rint(in[i])) < INTEGRAL_EPSILON) - vert[i] = Q_rint(in[i]); - else - vert[i] = in[i]; - } - - h = HashVec (vert); - - for (vnum=hashverts[h] ; vnum ; vnum=vertexchain[vnum]) - { - p = dvertexes[vnum].point; - if ( fabs(p[0]-vert[0]) 4096) - Error ("GetVertexnum: outside +/- 4096"); - } - - // search for an existing vertex match - for (i=0, dv=dvertexes ; ipoint[j]; - if ( d > POINT_EPSILON || d < -POINT_EPSILON) - break; - } - if (j == 3) - return i; // a match - } - - // new point - if (numvertexes == MAX_MAP_VERTS) - Error ("MAX_MAP_VERTS"); - VectorCopy (v, dv->point); - numvertexes++; - c_uniqueverts++; - - return numvertexes-1; -} -#endif - - -/* -================== -FaceFromSuperverts - -The faces vertexes have beeb added to the superverts[] array, -and there may be more there than can be held in a face (MAXEDGES). - -If less, the faces vertexnums[] will be filled in, otherwise -face will reference a tree of split[] faces until all of the -vertexnums can be added. - -superverts[base] will become face->vertexnums[0], and the others -will be circularly filled in. -================== -*/ -void FaceFromSuperverts (node_t *node, face_t *f, int base) -{ - face_t *newf; - int remaining; - int i; - - remaining = numsuperverts; - while (remaining > MAXEDGES) - { // must split into two faces, because of vertex overload - c_faceoverflows++; - - newf = f->split[0] = NewFaceFromFace (f); - newf = f->split[0]; - newf->next = node->faces; - node->faces = newf; - - newf->numpoints = MAXEDGES; - for (i=0 ; ivertexnums[i] = superverts[(i+base)%numsuperverts]; - - f->split[1] = NewFaceFromFace (f); - f = f->split[1]; - f->next = node->faces; - node->faces = f; - - remaining -= (MAXEDGES-2); - base = (base+MAXEDGES-1)%numsuperverts; - } - - // copy the vertexes back to the face - f->numpoints = remaining; - for (i=0 ; ivertexnums[i] = superverts[(i+base)%numsuperverts]; -} - - -/* -================== -EmitFaceVertexes -================== -*/ -void EmitFaceVertexes (node_t *node, face_t *f) -{ - winding_t *w; - int i; - - if (f->merged || f->split[0] || f->split[1]) - return; - - w = f->w; - for (i=0 ; inumpoints ; i++) - { - if (noweld) - { // make every point unique - if (numvertexes == MAX_MAP_VERTS) - Error ("MAX_MAP_VERTS"); - superverts[i] = numvertexes; - VectorCopy (w->p[i], dvertexes[numvertexes].point); - numvertexes++; - c_uniqueverts++; - c_totalverts++; - } - else - superverts[i] = GetVertexnum (w->p[i]); - } - numsuperverts = w->numpoints; - - // this may fragment the face if > MAXEDGES - FaceFromSuperverts (node, f, 0); -} - -/* -================== -EmitVertexes_r -================== -*/ -void EmitVertexes_r (node_t *node) -{ - int i; - face_t *f; - - if (node->planenum == PLANENUM_LEAF) - return; - - for (f=node->faces ; f ; f=f->next) - { - EmitFaceVertexes (node, f); - } - - for (i=0 ; i<2 ; i++) - EmitVertexes_r (node->children[i]); -} - - -#ifdef USE_HASHING -/* -========== -FindEdgeVerts - -Uses the hash tables to cut down to a small number -========== -*/ -void FindEdgeVerts (vec3_t v1, vec3_t v2) -{ - int x1, x2, y1, y2, t; - int x, y; - int vnum; - -#if 0 -{ - int i; - num_edge_verts = numvertexes-1; - for (i=0 ; i> 7; - y1 = (4096 + (int)(v1[1]+0.5)) >> 7; - x2 = (4096 + (int)(v2[0]+0.5)) >> 7; - y2 = (4096 + (int)(v2[1]+0.5)) >> 7; - - if (x1 > x2) - { - t = x1; - x1 = x2; - x2 = t; - } - if (y1 > y2) - { - t = y1; - y1 = y2; - y2 = t; - } -#if 0 - x1--; - x2++; - y1--; - y2++; - if (x1 < 0) - x1 = 0; - if (x2 >= HASH_SIZE) - x2 = HASH_SIZE; - if (y1 < 0) - y1 = 0; - if (y2 >= HASH_SIZE) - y2 = HASH_SIZE; -#endif - num_edge_verts = 0; - for (x=x1 ; x <= x2 ; x++) - { - for (y=y1 ; y <= y2 ; y++) - { - for (vnum=hashverts[y*HASH_SIZE+x] ; vnum ; vnum=vertexchain[vnum]) - { - edge_verts[num_edge_verts++] = vnum; - } - } - } -} - -#else -/* -========== -FindEdgeVerts - -Forced a dumb check of everything -========== -*/ -void FindEdgeVerts (vec3_t v1, vec3_t v2) -{ - int i; - - num_edge_verts = numvertexes-1; - for (i=0 ; i= end) - continue; // off an end - VectorMA (edge_start, dist, edge_dir, exact); - VectorSubtract (p, exact, off); - error = VectorLength (off); - - if (fabs(error) > OFF_EPSILON) - continue; // not on the edge - - // break the edge - c_tjunctions++; - TestEdge (start, dist, p1, j, k+1); - TestEdge (dist, end, j, p2, k+1); - return; - } - - // the edge p1 to p2 is now free of tjunctions - if (numsuperverts >= MAX_SUPERVERTS) - Error ("MAX_SUPERVERTS"); - superverts[numsuperverts] = p1; - numsuperverts++; -} - -/* -================== -FixFaceEdges - -================== -*/ -void FixFaceEdges (node_t *node, face_t *f) -{ - int p1, p2; - int i; - vec3_t e2; - vec_t len; - int count[MAX_SUPERVERTS], start[MAX_SUPERVERTS]; - int base; - - if (f->merged || f->split[0] || f->split[1]) - return; - - numsuperverts = 0; - - for (i=0 ; inumpoints ; i++) - { - p1 = f->vertexnums[i]; - p2 = f->vertexnums[(i+1)%f->numpoints]; - - VectorCopy (dvertexes[p1].point, edge_start); - VectorCopy (dvertexes[p2].point, e2); - - FindEdgeVerts (edge_start, e2); - - VectorSubtract (e2, edge_start, edge_dir); - len = VectorNormalize (edge_dir, edge_dir); - - start[i] = numsuperverts; - TestEdge (0, len, p1, p2, 0); - - count[i] = numsuperverts - start[i]; - } - - if (numsuperverts < 3) - { // entire face collapsed - f->numpoints = 0; - c_facecollapse++; - return; - } - - // we want to pick a vertex that doesn't have tjunctions - // on either side, which can cause artifacts on trifans, - // especially underwater - for (i=0 ; inumpoints ; i++) - { - if (count[i] == 1 && count[(i+f->numpoints-1)%f->numpoints] == 1) - break; - } - if (i == f->numpoints) - { - f->badstartvert = true; - c_badstartverts++; - base = 0; - } - else - { // rotate the vertex order - base = start[i]; - } - - // this may fragment the face if > MAXEDGES - FaceFromSuperverts (node, f, base); -} - -/* -================== -FixEdges_r -================== -*/ -void FixEdges_r (node_t *node) -{ - int i; - face_t *f; - - if (node->planenum == PLANENUM_LEAF) - return; - - for (f=node->faces ; f ; f=f->next) - FixFaceEdges (node, f); - - for (i=0 ; i<2 ; i++) - FixEdges_r (node->children[i]); -} - -/* -=========== -FixTjuncs - -=========== -*/ -void FixTjuncs (node_t *headnode) -{ - // snap and merge all vertexes - Sys_FPrintf( SYS_VRB, "---- snap verts ----\n"); - memset (hashverts, 0, sizeof(hashverts)); - c_totalverts = 0; - c_uniqueverts = 0; - c_faceoverflows = 0; - EmitVertexes_r (headnode); - Sys_FPrintf( SYS_VRB, "%i unique from %i\n", c_uniqueverts, c_totalverts); - - // break edges on tjunctions - Sys_FPrintf( SYS_VRB, "---- tjunc ----\n"); - c_tryedges = 0; - c_degenerate = 0; - c_facecollapse = 0; - c_tjunctions = 0; - if (!notjunc) - FixEdges_r (headnode); - Sys_FPrintf( SYS_VRB, "%5i edges degenerated\n", c_degenerate); - Sys_FPrintf( SYS_VRB, "%5i faces degenerated\n", c_facecollapse); - Sys_FPrintf( SYS_VRB, "%5i edges added by tjunctions\n", c_tjunctions); - Sys_FPrintf( SYS_VRB, "%5i faces added by tjunctions\n", c_faceoverflows); - Sys_FPrintf( SYS_VRB, "%5i bad start verts\n", c_badstartverts); -} - - -//======================================================== - -int c_faces; - -face_t *AllocFace (void) -{ - face_t *f; - - f = malloc(sizeof(*f)); - memset (f, 0, sizeof(*f)); - c_faces++; - - return f; -} - -face_t *NewFaceFromFace (face_t *f) -{ - face_t *newf; - - newf = AllocFace (); - *newf = *f; - newf->merged = NULL; - newf->split[0] = newf->split[1] = NULL; - newf->w = NULL; - return newf; -} - -void FreeFace (face_t *f) -{ - if (f->w) - FreeWinding (f->w); - free (f); - c_faces--; -} - -//======================================================== - -/* -================== -GetEdge - -Called by writebsp. -Don't allow four way edges -================== -*/ -int GetEdge2 (int v1, int v2, face_t *f) -{ - dedge_t *edge; - int i; - - c_tryedges++; - - if (!noshare) - { - for (i=firstmodeledge ; i < numedges ; i++) - { - edge = &dedges[i]; - if (v1 == edge->v[1] && v2 == edge->v[0] - && edgefaces[i][0]->contents == f->contents) - { - if (edgefaces[i][1]) - // Sys_Printf ("WARNING: multiple backward edge\n"); - continue; - edgefaces[i][1] = f; - return -i; - } - #if 0 - if (v1 == edge->v[0] && v2 == edge->v[1]) - { - Sys_Printf ("WARNING: multiple forward edge\n"); - return i; - } - #endif - } - } - -// emit an edge - if (numedges >= MAX_MAP_EDGES) - Error ("numedges == MAX_MAP_EDGES"); - edge = &dedges[numedges]; - numedges++; - edge->v[0] = v1; - edge->v[1] = v2; - edgefaces[numedges-1][0] = f; - - return numedges-1; -} - -/* -=========================================================================== - -FACE MERGING - -=========================================================================== -*/ - -#define CONTINUOUS_EPSILON 0.001 - -/* -============= -TryMergeWinding - -If two polygons share a common edge and the edges that meet at the -common points are both inside the other polygons, merge them - -Returns NULL if the faces couldn't be merged, or the new face. -The originals will NOT be freed. -============= -*/ -winding_t *TryMergeWinding (winding_t *f1, winding_t *f2, vec3_t planenormal) -{ - vec_t *p1, *p2, *p3, *p4, *back; - winding_t *newf; - int i, j, k, l; - vec3_t normal, delta; - vec_t dot; - qboolean keep1, keep2; - - - // - // find a common edge - // - p1 = p2 = NULL; // stop compiler warning - j = 0; // - - for (i=0 ; inumpoints ; i++) - { - p1 = f1->p[i]; - p2 = f1->p[(i+1)%f1->numpoints]; - for (j=0 ; jnumpoints ; j++) - { - p3 = f2->p[j]; - p4 = f2->p[(j+1)%f2->numpoints]; - for (k=0 ; k<3 ; k++) - { - if (fabs(p1[k] - p4[k]) > EQUAL_EPSILON) - break; - if (fabs(p2[k] - p3[k]) > EQUAL_EPSILON) - break; - } - if (k==3) - break; - } - if (j < f2->numpoints) - break; - } - - if (i == f1->numpoints) - return NULL; // no matching edges - - // - // check slope of connected lines - // if the slopes are colinear, the point can be removed - // - back = f1->p[(i+f1->numpoints-1)%f1->numpoints]; - VectorSubtract (p1, back, delta); - CrossProduct (planenormal, delta, normal); - VectorNormalize (normal, normal); - - back = f2->p[(j+2)%f2->numpoints]; - VectorSubtract (back, p1, delta); - dot = DotProduct (delta, normal); - if (dot > CONTINUOUS_EPSILON) - return NULL; // not a convex polygon - keep1 = (qboolean)(dot < -CONTINUOUS_EPSILON); - - back = f1->p[(i+2)%f1->numpoints]; - VectorSubtract (back, p2, delta); - CrossProduct (planenormal, delta, normal); - VectorNormalize (normal, normal); - - back = f2->p[(j+f2->numpoints-1)%f2->numpoints]; - VectorSubtract (back, p2, delta); - dot = DotProduct (delta, normal); - if (dot > CONTINUOUS_EPSILON) - return NULL; // not a convex polygon - keep2 = (qboolean)(dot < -CONTINUOUS_EPSILON); - - // - // build the new polygon - // - newf = AllocWinding (f1->numpoints + f2->numpoints); - - // copy first polygon - for (k=(i+1)%f1->numpoints ; k != i ; k=(k+1)%f1->numpoints) - { - if (k==(i+1)%f1->numpoints && !keep2) - continue; - - VectorCopy (f1->p[k], newf->p[newf->numpoints]); - newf->numpoints++; - } - - // copy second polygon - for (l= (j+1)%f2->numpoints ; l != j ; l=(l+1)%f2->numpoints) - { - if (l==(j+1)%f2->numpoints && !keep1) - continue; - VectorCopy (f2->p[l], newf->p[newf->numpoints]); - newf->numpoints++; - } - - return newf; -} - -/* -============= -TryMerge - -If two polygons share a common edge and the edges that meet at the -common points are both inside the other polygons, merge them - -Returns NULL if the faces couldn't be merged, or the new face. -The originals will NOT be freed. -============= -*/ -face_t *TryMerge (face_t *f1, face_t *f2, vec3_t planenormal) -{ - face_t *newf; - winding_t *nw; - - if (!f1->w || !f2->w) - return NULL; - if (f1->texinfo != f2->texinfo) - return NULL; - if (f1->planenum != f2->planenum) // on front and back sides - return NULL; - if (f1->contents != f2->contents) - return NULL; - - - nw = TryMergeWinding (f1->w, f2->w, planenormal); - if (!nw) - return NULL; - - c_merge++; - newf = NewFaceFromFace (f1); - newf->w = nw; - - f1->merged = newf; - f2->merged = newf; - - return newf; -} - -/* -=============== -MergeNodeFaces -=============== -*/ -void MergeNodeFaces (node_t *node) -{ - face_t *f1, *f2, *end; - face_t *merged; - plane_t *plane; - - plane = &mapplanes[node->planenum]; - merged = NULL; - - for (f1 = node->faces ; f1 ; f1 = f1->next) - { - if (f1->merged || f1->split[0] || f1->split[1]) - continue; - for (f2 = node->faces ; f2 != f1 ; f2=f2->next) - { - if (f2->merged || f2->split[0] || f2->split[1]) - continue; - merged = TryMerge (f1, f2, plane->normal); - if (!merged) - continue; - - // add merged to the end of the node face list - // so it will be checked against all the faces again - for (end = node->faces ; end->next ; end = end->next) - ; - merged->next = NULL; - end->next = merged; - break; - } - } -} - -//===================================================================== - -/* -=============== -SubdivideFace - -Chop up faces that are larger than we want in the surface cache -=============== -*/ -void SubdivideFace (node_t *node, face_t *f) -{ - float mins, maxs; - vec_t v; - int axis, i; - texinfo_t *tex; - vec3_t temp; - vec_t dist; - winding_t *w, *frontw, *backw; - - if (f->merged) - return; - -// special (non-surface cached) faces don't need subdivision - tex = &texinfo[f->texinfo]; - - if ( tex->flags & (SURF_WARP|SURF_SKY) ) - { - return; - } - - for (axis = 0 ; axis < 2 ; axis++) - { - while (1) - { - mins = 999999; - maxs = -999999; - - VectorCopy (tex->vecs[axis], temp); - w = f->w; - for (i=0 ; inumpoints ; i++) - { - v = DotProduct (w->p[i], temp); - if (v < mins) - mins = v; - if (v > maxs) - maxs = v; - } -#if 0 - if (maxs - mins <= 0) - Error ("zero extents"); -#endif - if (axis == 2) - { // allow double high walls - if (maxs - mins <= subdivide_size/* *2 */) - break; - } - else if (maxs - mins <= subdivide_size) - break; - - // split it - c_subdivide++; - - v = VectorNormalize (temp, temp); - - dist = (mins + subdivide_size - 16)/v; - - ClipWindingEpsilon (w, temp, dist, ON_EPSILON, &frontw, &backw); - if (!frontw || !backw) - Error ("SubdivideFace: didn't split the polygon"); - - f->split[0] = NewFaceFromFace (f); - f->split[0]->w = frontw; - f->split[0]->next = node->faces; - node->faces = f->split[0]; - - f->split[1] = NewFaceFromFace (f); - f->split[1]->w = backw; - f->split[1]->next = node->faces; - node->faces = f->split[1]; - - SubdivideFace (node, f->split[0]); - SubdivideFace (node, f->split[1]); - return; - } - } -} - -void SubdivideNodeFaces (node_t *node) -{ - face_t *f; - - for (f = node->faces ; f ; f=f->next) - { - SubdivideFace (node, f); - } -} - -//=========================================================================== - -int c_nodefaces; - - -/* -============ -FaceFromPortal - -============ -*/ -face_t *FaceFromPortal (portal_t *p, int pside) -{ - face_t *f; - side_t *side; - - side = p->side; - if (!side) - return NULL; // portal does not bridge different visible contents - - f = AllocFace (); - - f->texinfo = side->texinfo; - f->planenum = (side->planenum & ~1) | pside; - f->portal = p; - - if ( (p->nodes[pside]->contents & CONTENTS_WINDOW) - && VisibleContents(p->nodes[!pside]->contents^p->nodes[pside]->contents) == CONTENTS_WINDOW ) - return NULL; // don't show insides of windows - - if (pside) - { - f->w = ReverseWinding(p->winding); - f->contents = p->nodes[1]->contents; - } - else - { - f->w = CopyWinding(p->winding); - f->contents = p->nodes[0]->contents; - } - return f; -} - - -/* -=============== -MakeFaces_r - -If a portal will make a visible face, -mark the side that originally created it - - solid / empty : solid - solid / water : solid - water / empty : water - water / water : none -=============== -*/ -void MakeFaces_r (node_t *node) -{ - portal_t *p; - int s; - - // recurse down to leafs - if (node->planenum != PLANENUM_LEAF) - { - MakeFaces_r (node->children[0]); - MakeFaces_r (node->children[1]); - - // merge together all visible faces on the node - if (!nomerge) - MergeNodeFaces (node); - if (!nosubdiv) - SubdivideNodeFaces (node); - - return; - } - - // solid leafs never have visible faces - if (node->contents & CONTENTS_SOLID) - return; - - // see which portals are valid - for (p=node->portals ; p ; p = p->next[s]) - { - s = (p->nodes[1] == node); - - p->face[s] = FaceFromPortal (p, s); - if (p->face[s]) - { - c_nodefaces++; - p->face[s]->next = p->onnode->faces; - p->onnode->faces = p->face[s]; - } - } -} - -/* -============ -MakeFaces -============ -*/ -void MakeFaces (node_t *node) -{ - Sys_FPrintf( SYS_VRB, "--- MakeFaces ---\n"); - c_merge = 0; - c_subdivide = 0; - c_nodefaces = 0; - - MakeFaces_r (node); - - Sys_FPrintf( SYS_VRB, "%5i makefaces\n", c_nodefaces); - Sys_FPrintf( SYS_VRB, "%5i merged\n", c_merge); - Sys_FPrintf( SYS_VRB, "%5i subdivided\n", c_subdivide); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/flow.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/flow.c deleted file mode 100644 index 8bd8022a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/flow.c +++ /dev/null @@ -1,787 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qvis.h" - -/* - - each portal will have a list of all possible to see from first portal - - if (!thread->portalmightsee[portalnum]) - - portal mightsee - - for p2 = all other portals in leaf - get sperating planes - for all portals that might be seen by p2 - mark as unseen if not present in seperating plane - flood fill a new mightsee - save as passagemightsee - - - void CalcMightSee (leaf_t *leaf, -*/ - -int CountBits (byte *bits, int numbits) -{ - int i; - int c; - - c = 0; - for (i=0 ; i>3] & (1<<(i&7)) ) - c++; - - return c; -} - -int c_fullskip; -int c_portalskip, c_leafskip; -int c_vistest, c_mighttest; - -int c_chop, c_nochop; - -int active; - -void CheckStack (leaf_t *leaf, threaddata_t *thread) -{ - pstack_t *p, *p2; - - for (p=thread->pstack_head.next ; p ; p=p->next) - { -// printf ("="); - if (p->leaf == leaf) - Error ("CheckStack: leaf recursion"); - for (p2=thread->pstack_head.next ; p2 != p ; p2=p2->next) - if (p2->leaf == p->leaf) - Error ("CheckStack: late leaf recursion"); - } -// printf ("\n"); -} - - -winding_t *AllocStackWinding (pstack_t *stack) -{ - int i; - - for (i=0 ; i<3 ; i++) - { - if (stack->freewindings[i]) - { - stack->freewindings[i] = 0; - return &stack->windings[i]; - } - } - - Error ("AllocStackWinding: failed"); - - return NULL; -} - -void FreeStackWinding (winding_t *w, pstack_t *stack) -{ - int i; - - i = w - stack->windings; - - if (i<0 || i>2) - return; // not from local - - if (stack->freewindings[i]) - Error ("FreeStackWinding: allready free"); - stack->freewindings[i] = 1; -} - -/* -============== -Vis_ChopWinding - -============== -*/ -winding_t *Vis_ChopWinding (winding_t *in, pstack_t *stack, plane_t *split) -{ - vec_t dists[128]; - int sides[128]; - int counts[3]; - vec_t dot; - int i, j; - vec_t *p1, *p2; - vec3_t mid; - winding_t *neww; - - counts[0] = counts[1] = counts[2] = 0; - -// determine sides for each point - for (i=0 ; inumpoints ; i++) - { - dot = DotProduct (in->points[i], split->normal); - dot -= split->dist; - dists[i] = dot; - if (dot > ON_EPSILON) - sides[i] = SIDE_FRONT; - else if (dot < -ON_EPSILON) - sides[i] = SIDE_BACK; - else - { - sides[i] = SIDE_ON; - } - counts[sides[i]]++; - } - - if (!counts[1]) - return in; // completely on front side - - if (!counts[0]) - { - FreeStackWinding (in, stack); - return NULL; - } - - sides[i] = sides[0]; - dists[i] = dists[0]; - - neww = AllocStackWinding (stack); - - neww->numpoints = 0; - - for (i=0 ; inumpoints ; i++) - { - p1 = in->points[i]; - - if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING) - { - FreeStackWinding (neww, stack); - return in; // can't chop -- fall back to original - } - - if (sides[i] == SIDE_ON) - { - VectorCopy (p1, neww->points[neww->numpoints]); - neww->numpoints++; - continue; - } - - if (sides[i] == SIDE_FRONT) - { - VectorCopy (p1, neww->points[neww->numpoints]); - neww->numpoints++; - } - - if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) - continue; - - if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING) - { - FreeStackWinding (neww, stack); - return in; // can't chop -- fall back to original - } - - // generate a split point - p2 = in->points[(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 (split->normal[j] == 1) - mid[j] = split->dist; - else if (split->normal[j] == -1) - mid[j] = -split->dist; - else - mid[j] = p1[j] + dot*(p2[j]-p1[j]); - } - - VectorCopy (mid, neww->points[neww->numpoints]); - neww->numpoints++; - } - -// free the original winding - FreeStackWinding (in, stack); - - return neww; -} - - -/* -============== -ClipToSeperators - -Source, pass, and target are an ordering of portals. - -Generates seperating planes canidates by taking two points from source and one -point from pass, and clips target by them. - -If target is totally clipped away, that portal can not be seen through. - -Normal clip keeps target on the same side as pass, which is correct if the -order goes source, pass, target. If the order goes pass, source, target then -flipclip should be set. -============== -*/ -winding_t *ClipToSeperators (winding_t *source, winding_t *pass, winding_t *target, qboolean flipclip, pstack_t *stack) -{ - int i, j, k, l; - plane_t plane; - vec3_t v1, v2; - float d; - vec_t length; - int counts[3]; - qboolean fliptest; - -// check all combinations - for (i=0 ; inumpoints ; i++) - { - l = (i+1)%source->numpoints; - VectorSubtract (source->points[l] , source->points[i], v1); - - // fing a vertex of pass that makes a plane that puts all of the - // vertexes of pass on the front side and all of the vertexes of - // source on the back side - for (j=0 ; jnumpoints ; j++) - { - VectorSubtract (pass->points[j], source->points[i], v2); - - plane.normal[0] = v1[1]*v2[2] - v1[2]*v2[1]; - plane.normal[1] = v1[2]*v2[0] - v1[0]*v2[2]; - plane.normal[2] = v1[0]*v2[1] - v1[1]*v2[0]; - - // if points don't make a valid plane, skip it - - length = plane.normal[0] * plane.normal[0] - + plane.normal[1] * plane.normal[1] - + plane.normal[2] * plane.normal[2]; - - if (length < ON_EPSILON) - continue; - - length = 1/sqrt(length); - - plane.normal[0] *= length; - plane.normal[1] *= length; - plane.normal[2] *= length; - - plane.dist = DotProduct (pass->points[j], plane.normal); - - // - // find out which side of the generated seperating plane has the - // source portal - // -#if 1 - fliptest = false; - for (k=0 ; knumpoints ; k++) - { - if (k == i || k == l) - continue; - d = DotProduct (source->points[k], plane.normal) - plane.dist; - if (d < -ON_EPSILON) - { // source is on the negative side, so we want all - // pass and target on the positive side - fliptest = false; - break; - } - else if (d > ON_EPSILON) - { // source is on the positive side, so we want all - // pass and target on the negative side - fliptest = true; - break; - } - } - if (k == source->numpoints) - continue; // planar with source portal -#else - fliptest = flipclip; -#endif - // - // flip the normal if the source portal is backwards - // - if (fliptest) - { - VectorSubtract (vec3_origin, plane.normal, plane.normal); - plane.dist = -plane.dist; - } -#if 1 - // - // if all of the pass portal points are now on the positive side, - // this is the seperating plane - // - counts[0] = counts[1] = counts[2] = 0; - for (k=0 ; knumpoints ; k++) - { - if (k==j) - continue; - d = DotProduct (pass->points[k], plane.normal) - plane.dist; - if (d < -ON_EPSILON) - break; - else if (d > ON_EPSILON) - counts[0]++; - else - counts[2]++; - } - if (k != pass->numpoints) - continue; // points on negative side, not a seperating plane - - if (!counts[0]) - continue; // planar with seperating plane -#else - k = (j+1)%pass->numpoints; - d = DotProduct (pass->points[k], plane.normal) - plane.dist; - if (d < -ON_EPSILON) - continue; - k = (j+pass->numpoints-1)%pass->numpoints; - d = DotProduct (pass->points[k], plane.normal) - plane.dist; - if (d < -ON_EPSILON) - continue; -#endif - // - // flip the normal if we want the back side - // - if (flipclip) - { - VectorSubtract (vec3_origin, plane.normal, plane.normal); - plane.dist = -plane.dist; - } - - // - // clip target by the seperating plane - // - target = Vis_ChopWinding (target, stack, &plane); - if (!target) - return NULL; // target is not visible - } - } - - return target; -} - - - -/* -================== -RecursiveLeafFlow - -Flood fill through the leafs -If src_portal is NULL, this is the originating leaf -================== -*/ -void RecursiveLeafFlow (int leafnum, threaddata_t *thread, pstack_t *prevstack) -{ - pstack_t stack; - portal_t *p; - plane_t backplane; - leaf_t *leaf; - int i, j; - long *test, *might, *vis, more; - int pnum; - - thread->c_chains++; - - leaf = &leafs[leafnum]; -// CheckStack (leaf, thread); - - prevstack->next = &stack; - - stack.next = NULL; - stack.leaf = leaf; - stack.portal = NULL; - - might = (long *)stack.mightsee; - vis = (long *)thread->base->portalvis; - -// check all portals for flowing into other leafs - for (i=0 ; inumportals ; i++) - { - p = leaf->portals[i]; - pnum = p - portals; - - if ( ! (prevstack->mightsee[pnum >> 3] & (1<<(pnum&7)) ) ) - { - continue; // can't possibly see it - } - - // if the portal can't see anything we haven't allready seen, skip it - if (p->status == stat_done) - { - test = (long *)p->portalvis; - } - else - { - test = (long *)p->portalflood; - } - - more = 0; - for (j=0 ; jmightsee)[j] & test[j]; - more |= (might[j] & ~vis[j]); - } - - if (!more && - (thread->base->portalvis[pnum>>3] & (1<<(pnum&7))) ) - { // can't see anything new - continue; - } - - // get plane of portal, point normal into the neighbor leaf - stack.portalplane = p->plane; - VectorSubtract (vec3_origin, p->plane.normal, backplane.normal); - backplane.dist = -p->plane.dist; - -// c_portalcheck++; - - stack.portal = p; - stack.next = NULL; - stack.freewindings[0] = 1; - stack.freewindings[1] = 1; - stack.freewindings[2] = 1; - -#if 1 -{ -float d; - - d = DotProduct (p->origin, thread->pstack_head.portalplane.normal); - d -= thread->pstack_head.portalplane.dist; - if (d < -p->radius) - { - continue; - } - else if (d > p->radius) - { - stack.pass = p->winding; - } - else - { - stack.pass = Vis_ChopWinding (p->winding, &stack, &thread->pstack_head.portalplane); - if (!stack.pass) - continue; - } -} -#else - stack.pass = Vis_ChopWinding (p->winding, &stack, &thread->pstack_head.portalplane); - if (!stack.pass) - continue; -#endif - - -#if 1 -{ -float d; - - d = DotProduct (thread->base->origin, p->plane.normal); - d -= p->plane.dist; - if (d > p->radius) - { - continue; - } - else if (d < -p->radius) - { - stack.source = prevstack->source; - } - else - { - stack.source = Vis_ChopWinding (prevstack->source, &stack, &backplane); - if (!stack.source) - continue; - } -} -#else - stack.source = Vis_ChopWinding (prevstack->source, &stack, &backplane); - if (!stack.source) - continue; -#endif - - if (!prevstack->pass) - { // the second leaf can only be blocked if coplanar - - // mark the portal as visible - thread->base->portalvis[pnum>>3] |= (1<<(pnum&7)); - - RecursiveLeafFlow (p->leaf, thread, &stack); - continue; - } - - stack.pass = ClipToSeperators (stack.source, prevstack->pass, stack.pass, false, &stack); - if (!stack.pass) - continue; - - stack.pass = ClipToSeperators (prevstack->pass, stack.source, stack.pass, true, &stack); - if (!stack.pass) - continue; - - // mark the portal as visible - thread->base->portalvis[pnum>>3] |= (1<<(pnum&7)); - - // flow through it for real - RecursiveLeafFlow (p->leaf, thread, &stack); - } -} - - -/* -=============== -PortalFlow - -generates the portalvis bit vector -=============== -*/ -void PortalFlow (int portalnum) -{ - threaddata_t data; - int i; - portal_t *p; - int c_might, c_can; - - p = sorted_portals[portalnum]; - p->status = stat_working; - - c_might = CountBits (p->portalflood, numportals*2); - - memset (&data, 0, sizeof(data)); - data.base = p; - - data.pstack_head.portal = p; - data.pstack_head.source = p->winding; - data.pstack_head.portalplane = p->plane; - for (i=0 ; iportalflood)[i]; - RecursiveLeafFlow (p->leaf, &data, &data.pstack_head); - - p->status = stat_done; - - c_can = CountBits (p->portalvis, numportals*2); - - Sys_FPrintf ( SYS_VRB, "portal:%4i mightsee:%4i cansee:%4i (%i chains)\n", - (int)(p - portals), c_might, c_can, data.c_chains); -} - - -/* -=============================================================================== - -This is a rough first-order aproximation that is used to trivially reject some -of the final calculations. - - -Calculates portalfront and portalflood bit vectors - -thinking about: - -typedef struct passage_s -{ - struct passage_s *next; - struct portal_s *to; - stryct sep_s *seperators; - byte *mightsee; -} passage_t; - -typedef struct portal_s -{ - struct passage_s *passages; - int leaf; // leaf portal faces into -} portal_s; - -leaf = portal->leaf -clear -for all portals - - -calc portal visibility - clear bit vector - for all passages - passage visibility - - -for a portal to be visible to a passage, it must be on the front of -all seperating planes, and both portals must be behind the mew portal - -=============================================================================== -*/ - -int c_flood, c_vis; - - -/* -================== -SimpleFlood - -================== -*/ -void SimpleFlood (portal_t *srcportal, int leafnum) -{ - int i; - leaf_t *leaf; - portal_t *p; - int pnum; - - leaf = &leafs[leafnum]; - - for (i=0 ; inumportals ; i++) - { - p = leaf->portals[i]; - pnum = p - portals; - if ( ! (srcportal->portalfront[pnum>>3] & (1<<(pnum&7)) ) ) - continue; - - if (srcportal->portalflood[pnum>>3] & (1<<(pnum&7)) ) - continue; - - srcportal->portalflood[pnum>>3] |= (1<<(pnum&7)); - - SimpleFlood (srcportal, p->leaf); - } -} - -/* -============== -BasePortalVis -============== -*/ -void BasePortalVis (int portalnum) -{ - int j, k; - portal_t *tp, *p; - float d; - winding_t *w; - - p = portals+portalnum; - - p->portalfront = malloc (portalbytes); - memset (p->portalfront, 0, portalbytes); - - p->portalflood = malloc (portalbytes); - memset (p->portalflood, 0, portalbytes); - - p->portalvis = malloc (portalbytes); - memset (p->portalvis, 0, portalbytes); - - for (j=0, tp = portals ; jwinding; - for (k=0 ; knumpoints ; k++) - { - d = DotProduct (w->points[k], p->plane.normal) - - p->plane.dist; - if (d > ON_EPSILON) - break; - } - if (k == w->numpoints) - continue; // no points on front - - w = p->winding; - for (k=0 ; knumpoints ; k++) - { - d = DotProduct (w->points[k], tp->plane.normal) - - tp->plane.dist; - if (d < -ON_EPSILON) - break; - } - if (k == w->numpoints) - continue; // no points on front - - p->portalfront[j>>3] |= (1<<(j&7)); - } - - SimpleFlood (p, p->leaf); - - p->nummightsee = CountBits (p->portalflood, numportals*2); -// printf ("portal %i: %i mightsee\n", portalnum, p->nummightsee); - c_flood += p->nummightsee; -} - - - - - -/* -=============================================================================== - -This is a second order aproximation - -Calculates portalvis bit vector - -WAAAAAAY too slow. - -=============================================================================== -*/ - -/* -================== -RecursiveLeafBitFlow - -================== -*/ -void RecursiveLeafBitFlow (int leafnum, byte *mightsee, byte *cansee) -{ - portal_t *p; - leaf_t *leaf; - int i, j; - long more; - int pnum; - byte newmight[MAX_PORTALS/8]; - - leaf = &leafs[leafnum]; - -// check all portals for flowing into other leafs - for (i=0 ; inumportals ; i++) - { - p = leaf->portals[i]; - pnum = p - portals; - - // if some previous portal can't see it, skip - if (! (mightsee[pnum>>3] & (1<<(pnum&7)) ) ) - continue; - - // if this portal can see some portals we mightsee, recurse - more = 0; - for (j=0 ; jportalflood)[j]; - more |= ((long *)newmight)[j] & ~((long *)cansee)[j]; - } - - if (!more) - continue; // can't see anything new - - cansee[pnum>>3] |= (1<<(pnum&7)); - - RecursiveLeafBitFlow (p->leaf, newmight, cansee); - } -} - -/* -============== -BetterPortalVis -============== -*/ -void BetterPortalVis (int portalnum) -{ - portal_t *p; - - p = portals+portalnum; - - RecursiveLeafBitFlow (p->leaf, p->portalflood, p->portalvis); - - // build leaf vis information - p->nummightsee = CountBits (p->portalvis, numportals*2); - c_vis += p->nummightsee; -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/gldraw.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/gldraw.c deleted file mode 100644 index 6e249c31..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/gldraw.c +++ /dev/null @@ -1,231 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#include -#include - -#include "qbsp.h" - -// can't use the glvertex3fv functions, because the vec3_t fields -// could be either floats or doubles, depending on DOUBLEVEC_T - -qboolean drawflag; -vec3_t draw_mins, draw_maxs; - - -#define WIN_SIZE 512 - -void InitWindow (void) -{ - auxInitDisplayMode (AUX_SINGLE | AUX_RGB); - auxInitPosition (0, 0, WIN_SIZE, WIN_SIZE); - auxInitWindow ("qcsg"); -} - -void Draw_ClearWindow (void) -{ - static int init; - int w, h, g; - vec_t mx, my; - - if (!drawflag) - return; - - if (!init) - { - init = true; - InitWindow (); - } - - glClearColor (1,0.8,0.8,0); - glClear (GL_COLOR_BUFFER_BIT); - - w = (draw_maxs[0] - draw_mins[0]); - h = (draw_maxs[1] - draw_mins[1]); - - mx = draw_mins[0] + w/2; - my = draw_mins[1] + h/2; - - g = w > h ? w : h; - - glLoadIdentity (); - gluPerspective (90, 1, 2, 16384); - gluLookAt (mx, my, draw_maxs[2] + g/2, mx , my, draw_maxs[2], 0, 1, 0); - - glColor3f (0,0,0); -// glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); - glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); - glDisable (GL_DEPTH_TEST); - glEnable (GL_BLEND); - glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - -#if 0 - glColor4f (1,0,0,0.5); - glBegin (GL_POLYGON); - - glVertex3f (0, 500, 0); - glVertex3f (0, 900, 0); - glVertex3f (0, 900, 100); - glVertex3f (0, 500, 100); - - glEnd (); -#endif - - glFlush (); - -} - -void Draw_SetRed (void) -{ - if (!drawflag) - return; - - glColor3f (1,0,0); -} - -void Draw_SetGrey (void) -{ - if (!drawflag) - return; - - glColor3f (0.5,0.5,0.5); -} - -void Draw_SetBlack (void) -{ - if (!drawflag) - return; - - glColor3f (0,0,0); -} - -void DrawWinding (winding_t *w) -{ - int i; - - if (!drawflag) - return; - - glColor4f (0,0,0,0.5); - glBegin (GL_LINE_LOOP); - for (i=0 ; inumpoints ; i++) - glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); - glEnd (); - - glColor4f (0,1,0,0.3); - glBegin (GL_POLYGON); - for (i=0 ; inumpoints ; i++) - glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); - glEnd (); - - glFlush (); -} - -void DrawAuxWinding (winding_t *w) -{ - int i; - - if (!drawflag) - return; - - glColor4f (0,0,0,0.5); - glBegin (GL_LINE_LOOP); - for (i=0 ; inumpoints ; i++) - glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); - glEnd (); - - glColor4f (1,0,0,0.3); - glBegin (GL_POLYGON); - for (i=0 ; inumpoints ; i++) - glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); - glEnd (); - - glFlush (); -} - -//============================================================ - -#define GLSERV_PORT 25001 - -qboolean wins_init; -int draw_socket; - -void GLS_BeginScene (void) -{ - WSADATA winsockdata; - WORD wVersionRequested; - struct sockaddr_in address; - int r; - - if (!wins_init) - { - wins_init = true; - - wVersionRequested = MAKEWORD(1, 1); - - r = WSAStartup (MAKEWORD(1, 1), &winsockdata); - - if (r) - Error ("Winsock initialization failed."); - - } - - // connect a socket to the server - - draw_socket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); - if (draw_socket == -1) - Error ("draw_socket failed"); - - address.sin_family = AF_INET; - address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - address.sin_port = GLSERV_PORT; - r = connect (draw_socket, (struct sockaddr *)&address, sizeof(address)); - if (r == -1) - { - closesocket (draw_socket); - draw_socket = 0; - } -} - -void GLS_Winding (winding_t *w, int code) -{ - byte buf[1024]; - int i, j; - - if (!draw_socket) - return; - - ((int *)buf)[0] = w->numpoints; - ((int *)buf)[1] = code; - for (i=0 ; inumpoints ; i++) - for (j=0 ; j<3 ; j++) - ((float *)buf)[2+i*3+j] = w->p[i][j]; - - send (draw_socket, buf, w->numpoints*12+8, 0); -} - -void GLS_EndScene (void) -{ - closesocket (draw_socket); - draw_socket = 0; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/glfile.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/glfile.c deleted file mode 100644 index 6e98bd0f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/glfile.c +++ /dev/null @@ -1,148 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -int c_glfaces; - -int PortalVisibleSides (portal_t *p) -{ - int fcon, bcon; - - if (!p->onnode) - return 0; // outside - - fcon = p->nodes[0]->contents; - bcon = p->nodes[1]->contents; - - // same contents never create a face - if (fcon == bcon) - return 0; - - // FIXME: is this correct now? - if (!fcon) - return 1; - if (!bcon) - return 2; - return 0; -} - -void OutputWinding (winding_t *w, FILE *glview) -{ - static int level = 128; - vec_t light; - int i; - - fprintf (glview, "%i\n", w->numpoints); - level+=28; - light = (level&255)/255.0; - for (i=0 ; inumpoints ; i++) - { - fprintf (glview, "%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f\n", - w->p[i][0], - w->p[i][1], - w->p[i][2], - light, - light, - light); - } - fprintf (glview, "\n"); -} - -/* -============= -OutputPortal -============= -*/ -void OutputPortal (portal_t *p, FILE *glview) -{ - winding_t *w; - int sides; - - sides = PortalVisibleSides (p); - if (!sides) - return; - - c_glfaces++; - - w = p->winding; - - if (sides == 2) // back side - w = ReverseWinding (w); - - OutputWinding (w, glview); - - if (sides == 2) - FreeWinding(w); -} - -/* -============= -WriteGLView_r -============= -*/ -void WriteGLView_r (node_t *node, FILE *glview) -{ - portal_t *p, *nextp; - - if (node->planenum != PLANENUM_LEAF) - { - WriteGLView_r (node->children[0], glview); - WriteGLView_r (node->children[1], glview); - return; - } - - // write all the portals - for (p=node->portals ; p ; p=nextp) - { - if (p->nodes[0] == node) - { - OutputPortal (p, glview); - nextp = p->next[0]; - } - else - nextp = p->next[1]; - } -} - -/* -============= -WriteGLView -============= -*/ -void WriteGLView (tree_t *tree, char *source) -{ - char name[1024]; - FILE *glview; - - c_glfaces = 0; - sprintf (name, "%s%s.gl",outbase, source); - Sys_Printf ("Writing %s\n", name); - - glview = fopen (name, "w"); - if (!glview) - Error ("Couldn't open %s", name); - WriteGLView_r (tree->headnode, glview); - fclose (glview); - - Sys_Printf ("%5i c_glfaces\n", c_glfaces); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/leakfile.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/leakfile.c deleted file mode 100644 index 8753eec5..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/leakfile.c +++ /dev/null @@ -1,180 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -/* -============================================================================== - -LEAF FILE GENERATION - -Save out name.line for qe3 to read -============================================================================== -*/ - - -/* -============= -LeakFile - -Finds the shortest possible chain of portals -that leads from the outside leaf to a specifically -occupied leaf -============= -*/ - -/* -void LeakFile (tree_t *tree) -{ - vec3_t mid; - FILE *linefile; - char filename[1024]; - node_t *node; - int count; - - if (!tree->outside_node.occupied) - return; - - Sys_Printf ("--- LeakFile ---\n"); - - // - // write the points to the file - // - sprintf (filename, "%s.lin", source); - linefile = fopen (filename, "w"); - if (!linefile) - Error ("Couldn't open %s\n", filename); - - count = 0; - node = &tree->outside_node; - while (node->occupied > 1) - { - int next; - portal_t *p, *nextportal; - node_t *nextnode; - int s; - - // find the best portal exit - next = node->occupied; - for (p=node->portals ; p ; p = p->next[!s]) - { - s = (p->nodes[0] == node); - if (p->nodes[s]->occupied - && p->nodes[s]->occupied < next) - { - nextportal = p; - nextnode = p->nodes[s]; - next = nextnode->occupied; - } - } - node = nextnode; - WindingCenter (nextportal->winding, mid); - fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); - count++; - } - // add the occupant center - GetVectorForKey (node->occupant, "origin", mid); - - fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); - Sys_Printf ("%5i point linefile\n", count+1); - - fclose (linefile); -} -*/ - -/* -============= -LeakFile - -Finds the shortest possible chain of portals -that leads from the outside leaf to a specifically -occupied leaf - -TTimo: builds a polyline xml node -============= -*/ -xmlNodePtr LeakFile (tree_t *tree) -{ - vec3_t mid; - FILE *linefile; - char filename[1024]; - node_t *node; - int count; - xmlNodePtr xml_node, point; - - if (!tree->outside_node.occupied) - return NULL; - - Sys_FPrintf (SYS_VRB,"--- LeakFile ---\n"); - - // - // write the points to the file - // - sprintf (filename, "%s.lin", source); - linefile = fopen (filename, "w"); - if (!linefile) - Error ("Couldn't open %s\n", filename); - - xml_node = xmlNewNode (NULL, "polyline"); - - count = 0; - node = &tree->outside_node; - while (node->occupied > 1) - { - int next; - portal_t *p, *nextportal; - node_t *nextnode; - int s; - - // find the best portal exit - next = node->occupied; - for (p=node->portals ; p ; p = p->next[!s]) - { - s = (p->nodes[0] == node); - if (p->nodes[s]->occupied - && p->nodes[s]->occupied < next) - { - nextportal = p; - nextnode = p->nodes[s]; - next = nextnode->occupied; - } - } - node = nextnode; - WindingCenter (nextportal->winding, mid); - fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); - point = xml_NodeForVec(mid); - xmlAddChild(xml_node, point); - count++; - } - // add the occupant center - GetVectorForKey (node->occupant, "origin", mid); - - fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); - point = xml_NodeForVec(mid); - xmlAddChild(xml_node, point); - Sys_FPrintf( SYS_VRB, "%9d point linefile\n", count+1); - - fclose (linefile); - - return xml_node; -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/lightmap.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/lightmap.c deleted file mode 100644 index 8a9580b7..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/lightmap.c +++ /dev/null @@ -1,1315 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qrad.h" - -#define MAX_LSTYLES 256 - -typedef struct -{ - dface_t *faces[2]; - qboolean coplanar; -} edgeshare_t; - -edgeshare_t edgeshare[MAX_MAP_EDGES]; - -int facelinks[MAX_MAP_FACES]; -int planelinks[2][MAX_MAP_PLANES]; - -/* -============ -LinkPlaneFaces -============ -*/ -void LinkPlaneFaces (void) -{ - int i; - dface_t *f; - - f = dfaces; - for (i=0 ; iside][f->planenum]; - planelinks[f->side][f->planenum] = i; - } -} - -/* -============ -PairEdges -============ -*/ -void PairEdges (void) -{ - int i, j, k; - dface_t *f; - edgeshare_t *e; - - f = dfaces; - for (i=0 ; inumedges ; j++) - { - k = dsurfedges[f->firstedge + j]; - if (k < 0) - { - e = &edgeshare[-k]; - e->faces[1] = f; - } - else - { - e = &edgeshare[k]; - e->faces[0] = f; - } - - if (e->faces[0] && e->faces[1]) - { - // determine if coplanar - if (e->faces[0]->planenum == e->faces[1]->planenum) - e->coplanar = true; - } - } - } -} - -/* -================================================================= - - POINT TRIANGULATION - -================================================================= -*/ - -typedef struct triedge_s -{ - int p0, p1; - vec3_t normal; - vec_t dist; - struct triangle_s *tri; -} triedge_t; - -typedef struct triangle_s -{ - triedge_t *edges[3]; -} triangle_t; - -#define MAX_TRI_POINTS 1024 -#define MAX_TRI_EDGES (MAX_TRI_POINTS*6) -#define MAX_TRI_TRIS (MAX_TRI_POINTS*2) - -typedef struct -{ - int numpoints; - int numedges; - int numtris; - dplane_t *plane; - triedge_t *edgematrix[MAX_TRI_POINTS][MAX_TRI_POINTS]; - patch_t *points[MAX_TRI_POINTS]; - triedge_t edges[MAX_TRI_EDGES]; - triangle_t tris[MAX_TRI_TRIS]; -} triangulation_t; - -/* -=============== -AllocTriangulation -=============== -*/ -triangulation_t *AllocTriangulation (dplane_t *plane) -{ - triangulation_t *t; - - t = malloc(sizeof(triangulation_t)); - t->numpoints = 0; - t->numedges = 0; - t->numtris = 0; - - t->plane = plane; - -// memset (t->edgematrix, 0, sizeof(t->edgematrix)); - - return t; -} - -/* -=============== -FreeTriangulation -=============== -*/ -void FreeTriangulation (triangulation_t *tr) -{ - free (tr); -} - - -triedge_t *FindEdge (triangulation_t *trian, int p0, int p1) -{ - triedge_t *e, *be; - vec3_t v1; - vec3_t normal; - vec_t dist; - - if (trian->edgematrix[p0][p1]) - return trian->edgematrix[p0][p1]; - - if (trian->numedges > MAX_TRI_EDGES-2) - Error ("trian->numedges > MAX_TRI_EDGES-2"); - - VectorSubtract (trian->points[p1]->origin, trian->points[p0]->origin, v1); - VectorNormalize (v1, v1); - CrossProduct (v1, trian->plane->normal, normal); - dist = DotProduct (trian->points[p0]->origin, normal); - - e = &trian->edges[trian->numedges]; - e->p0 = p0; - e->p1 = p1; - e->tri = NULL; - VectorCopy (normal, e->normal); - e->dist = dist; - trian->numedges++; - trian->edgematrix[p0][p1] = e; - - be = &trian->edges[trian->numedges]; - be->p0 = p1; - be->p1 = p0; - be->tri = NULL; - VectorSubtract (vec3_origin, normal, be->normal); - be->dist = -dist; - trian->numedges++; - trian->edgematrix[p1][p0] = be; - - return e; -} - -triangle_t *AllocTriangle (triangulation_t *trian) -{ - triangle_t *t; - - if (trian->numtris >= MAX_TRI_TRIS) - Error ("trian->numtris >= MAX_TRI_TRIS"); - - t = &trian->tris[trian->numtris]; - trian->numtris++; - - return t; -} - -/* -============ -TriEdge_r -============ -*/ -void TriEdge_r (triangulation_t *trian, triedge_t *e) -{ - int i, bestp; - vec3_t v1, v2; - vec_t *p0, *p1, *p; - vec_t best, ang; - triangle_t *nt; - - if (e->tri) - return; // allready connected by someone - - // find the point with the best angle - p0 = trian->points[e->p0]->origin; - p1 = trian->points[e->p1]->origin; - best = 1.1; - for (i=0 ; i< trian->numpoints ; i++) - { - p = trian->points[i]->origin; - // a 0 dist will form a degenerate triangle - if (DotProduct(p, e->normal) - e->dist < 0) - continue; // behind edge - VectorSubtract (p0, p, v1); - VectorSubtract (p1, p, v2); - if (!VectorNormalize (v1,v1)) - continue; - if (!VectorNormalize (v2,v2)) - continue; - ang = DotProduct (v1, v2); - if (ang < best) - { - best = ang; - bestp = i; - } - } - if (best >= 1) - return; // edge doesn't match anything - - // make a new triangle - nt = AllocTriangle (trian); - nt->edges[0] = e; - nt->edges[1] = FindEdge (trian, e->p1, bestp); - nt->edges[2] = FindEdge (trian, bestp, e->p0); - for (i=0 ; i<3 ; i++) - nt->edges[i]->tri = nt; - TriEdge_r (trian, FindEdge (trian, bestp, e->p1)); - TriEdge_r (trian, FindEdge (trian, e->p0, bestp)); -} - -/* -============ -TriangulatePoints -============ -*/ -void TriangulatePoints (triangulation_t *trian) -{ - vec_t d, bestd; - vec3_t v1; - int bp1, bp2, i, j; - vec_t *p1, *p2; - triedge_t *e, *e2; - - if (trian->numpoints < 2) - return; - - // find the two closest points - bestd = 9999; - for (i=0 ; inumpoints ; i++) - { - p1 = trian->points[i]->origin; - for (j=i+1 ; jnumpoints ; j++) - { - p2 = trian->points[j]->origin; - VectorSubtract (p2, p1, v1); - d = VectorLength (v1); - if (d < bestd) - { - bestd = d; - bp1 = i; - bp2 = j; - } - } - } - - e = FindEdge (trian, bp1, bp2); - e2 = FindEdge (trian, bp2, bp1); - TriEdge_r (trian, e); - TriEdge_r (trian, e2); -} - -/* -=============== -AddPointToTriangulation -=============== -*/ -void AddPointToTriangulation (patch_t *patch, triangulation_t *trian) -{ - int pnum; - - pnum = trian->numpoints; - if (pnum == MAX_TRI_POINTS) - Error ("trian->numpoints == MAX_TRI_POINTS"); - trian->points[pnum] = patch; - trian->numpoints++; -} - -/* -=============== -LerpTriangle -=============== -*/ -void LerpTriangle (triangulation_t *trian, triangle_t *t, vec3_t point, vec3_t color) -{ - patch_t *p1, *p2, *p3; - vec3_t base, d1, d2; - float x, y, x1, y1, x2, y2; - - p1 = trian->points[t->edges[0]->p0]; - p2 = trian->points[t->edges[1]->p0]; - p3 = trian->points[t->edges[2]->p0]; - - VectorCopy (p1->totallight, base); - VectorSubtract (p2->totallight, base, d1); - VectorSubtract (p3->totallight, base, d2); - - x = DotProduct (point, t->edges[0]->normal) - t->edges[0]->dist; - y = DotProduct (point, t->edges[2]->normal) - t->edges[2]->dist; - - x1 = 0; - y1 = DotProduct (p2->origin, t->edges[2]->normal) - t->edges[2]->dist; - - x2 = DotProduct (p3->origin, t->edges[0]->normal) - t->edges[0]->dist; - y2 = 0; - - if (fabs(y1)edges[i]; - d = DotProduct (e->normal, point) - e->dist; - if (d < 0) - return false; // not inside - } - - return true; -} - -/* -=============== -SampleTriangulation -=============== -*/ -void SampleTriangulation (vec3_t point, triangulation_t *trian, vec3_t color) -{ - triangle_t *t; - triedge_t *e; - vec_t d, best; - patch_t *p0, *p1; - vec3_t v1, v2; - int i, j; - - if (trian->numpoints == 0) - { - VectorClear (color); - return; - } - if (trian->numpoints == 1) - { - VectorCopy (trian->points[0]->totallight, color); - return; - } - - // search for triangles - for (t = trian->tris, j=0 ; j < trian->numtris ; t++, j++) - { - if (!PointInTriangle (point, t)) - continue; - - // this is it - LerpTriangle (trian, t, point, color); - return; - } - - // search for exterior edge - for (e=trian->edges, j=0 ; j< trian->numedges ; e++, j++) - { - if (e->tri) - continue; // not an exterior edge - - d = DotProduct (point, e->normal) - e->dist; - if (d < 0) - continue; // not in front of edge - - p0 = trian->points[e->p0]; - p1 = trian->points[e->p1]; - - VectorSubtract (p1->origin, p0->origin, v1); - VectorNormalize (v1, v1); - VectorSubtract (point, p0->origin, v2); - d = DotProduct (v2, v1); - if (d < 0) - continue; - if (d > 1) - continue; - for (i=0 ; i<3 ; i++) - color[i] = p0->totallight[i] + d * (p1->totallight[i] - p0->totallight[i]); - return; - } - - // search for nearest point - best = 99999; - p1 = NULL; - for (j=0 ; jnumpoints ; j++) - { - p0 = trian->points[j]; - VectorSubtract (point, p0->origin, v1); - d = VectorLength (v1); - if (d < best) - { - best = d; - p1 = p0; - } - } - - if (!p1) - Error ("SampleTriangulation: no points"); - - VectorCopy (p1->totallight, color); -} - -/* -================================================================= - - LIGHTMAP SAMPLE GENERATION - -================================================================= -*/ - - -#define SINGLEMAP (64*64*4) - -typedef struct -{ - vec_t facedist; - vec3_t facenormal; - - int numsurfpt; - vec3_t surfpt[SINGLEMAP]; - - vec3_t modelorg; // for origined bmodels - - vec3_t texorg; - vec3_t worldtotex[2]; // s = (world - texorg) . worldtotex[0] - vec3_t textoworld[2]; // world = texorg + s * textoworld[0] - - vec_t exactmins[2], exactmaxs[2]; - - int texmins[2], texsize[2]; - int surfnum; - dface_t *face; -} lightinfo_t; - - -/* -================ -CalcFaceExtents - -Fills in s->texmins[] and s->texsize[] -also sets exactmins[] and exactmaxs[] -================ -*/ -void CalcFaceExtents (lightinfo_t *l) -{ - dface_t *s; - vec_t mins[2], maxs[2], val; - int i,j, e; - dvertex_t *v; - texinfo_t *tex; - vec3_t vt; - - s = l->face; - - mins[0] = mins[1] = 999999; - maxs[0] = maxs[1] = -99999; - - tex = &texinfo[s->texinfo]; - - for (i=0 ; inumedges ; i++) - { - e = dsurfedges[s->firstedge+i]; - if (e >= 0) - v = dvertexes + dedges[e].v[0]; - else - v = dvertexes + dedges[-e].v[1]; - -// VectorAdd (v->point, l->modelorg, vt); - VectorCopy (v->point, vt); - - for (j=0 ; j<2 ; j++) - { - val = DotProduct (vt, tex->vecs[j]) + tex->vecs[j][3]; - if (val < mins[j]) - mins[j] = val; - if (val > maxs[j]) - maxs[j] = val; - } - } - - for (i=0 ; i<2 ; i++) - { - l->exactmins[i] = mins[i]; - l->exactmaxs[i] = maxs[i]; - - mins[i] = floor(mins[i]/16); - maxs[i] = ceil(maxs[i]/16); - - l->texmins[i] = mins[i]; - l->texsize[i] = maxs[i] - mins[i]; - if (l->texsize[0] * l->texsize[1] > SINGLEMAP/4) // div 4 for extrasamples - Error ("Surface to large to map"); - } -} - -/* -================ -CalcFaceVectors - -Fills in texorg, worldtotex. and textoworld -================ -*/ -void CalcFaceVectors (lightinfo_t *l) -{ - texinfo_t *tex; - int i, j; - vec3_t texnormal; - vec_t distscale; - vec_t dist, len; - int w, h; - - tex = &texinfo[l->face->texinfo]; - -// convert from float to double - for (i=0 ; i<2 ; i++) - for (j=0 ; j<3 ; j++) - l->worldtotex[i][j] = tex->vecs[i][j]; - -// calculate a normal to the texture axis. points can be moved along this -// without changing their S/T - texnormal[0] = tex->vecs[1][1]*tex->vecs[0][2] - - tex->vecs[1][2]*tex->vecs[0][1]; - texnormal[1] = tex->vecs[1][2]*tex->vecs[0][0] - - tex->vecs[1][0]*tex->vecs[0][2]; - texnormal[2] = tex->vecs[1][0]*tex->vecs[0][1] - - tex->vecs[1][1]*tex->vecs[0][0]; - VectorNormalize (texnormal, texnormal); - -// flip it towards plane normal - distscale = DotProduct (texnormal, l->facenormal); - if (!distscale) - { - Sys_FPrintf( SYS_VRB, "WARNING: Texture axis perpendicular to face\n"); - distscale = 1; - } - if (distscale < 0) - { - distscale = -distscale; - VectorSubtract (vec3_origin, texnormal, texnormal); - } - -// distscale is the ratio of the distance along the texture normal to -// the distance along the plane normal - distscale = 1/distscale; - - for (i=0 ; i<2 ; i++) - { - len = VectorLength (l->worldtotex[i]); - dist = DotProduct (l->worldtotex[i], l->facenormal); - dist *= distscale; - VectorMA (l->worldtotex[i], -dist, texnormal, l->textoworld[i]); - VectorScale (l->textoworld[i], (1/len)*(1/len), l->textoworld[i]); - } - - -// calculate texorg on the texture plane - for (i=0 ; i<3 ; i++) - l->texorg[i] = -tex->vecs[0][3]* l->textoworld[0][i] - tex->vecs[1][3] * l->textoworld[1][i]; - -// project back to the face plane - dist = DotProduct (l->texorg, l->facenormal) - l->facedist - 1; - dist *= distscale; - VectorMA (l->texorg, -dist, texnormal, l->texorg); - - // compensate for org'd bmodels - VectorAdd (l->texorg, l->modelorg, l->texorg); - - // total sample count - h = l->texsize[1]+1; - w = l->texsize[0]+1; - l->numsurfpt = w * h; -} - -/* -================= -CalcPoints - -For each texture aligned grid point, back project onto the plane -to get the world xyz value of the sample point -================= -*/ -void CalcPoints (lightinfo_t *l, float sofs, float tofs) -{ - int i; - int s, t, j; - int w, h, step; - vec_t starts, startt, us, ut; - vec_t *surf; - vec_t mids, midt; - vec3_t facemid; - dleaf_t *leaf; - - surf = l->surfpt[0]; - mids = (l->exactmaxs[0] + l->exactmins[0])/2; - midt = (l->exactmaxs[1] + l->exactmins[1])/2; - - for (j=0 ; j<3 ; j++) - facemid[j] = l->texorg[j] + l->textoworld[0][j]*mids + l->textoworld[1][j]*midt; - - h = l->texsize[1]+1; - w = l->texsize[0]+1; - l->numsurfpt = w * h; - - starts = l->texmins[0]*16; - startt = l->texmins[1]*16; - step = 16; - - - for (t=0 ; ttexorg[j] + l->textoworld[0][j]*us - + l->textoworld[1][j]*ut; - - leaf = Rad_PointInLeaf (surf); - if (leaf->contents != CONTENTS_SOLID) - { - if (!TestLine_r (0, facemid, surf)) - break; // got it - } - - // nudge it - if (i & 1) - { - if (us > mids) - { - us -= 8; - if (us < mids) - us = mids; - } - else - { - us += 8; - if (us > mids) - us = mids; - } - } - else - { - if (ut > midt) - { - ut -= 8; - if (ut < midt) - ut = midt; - } - else - { - ut += 8; - if (ut > midt) - ut = midt; - } - } - } - } - } - -} - - -//============================================================== - - - -#define MAX_STYLES 32 -typedef struct -{ - int numsamples; - float *origins; - int numstyles; - int stylenums[MAX_STYLES]; - float *samples[MAX_STYLES]; -} facelight_t; - -directlight_t *directlights[MAX_MAP_LEAFS]; -facelight_t facelight[MAX_MAP_FACES]; -int numdlights; - -/* -================== -FindTargetEntity -================== -*/ -entity_t *FindTargetEntity (char *target) -{ - int i; - char *n; - - for (i=0 ; itotallight[0] < DIRECT_LIGHT - && p->totallight[1] < DIRECT_LIGHT - && p->totallight[2] < DIRECT_LIGHT) - continue; - - numdlights++; - dl = malloc(sizeof(directlight_t)); - memset (dl, 0, sizeof(*dl)); - - VectorCopy (p->origin, dl->origin); - - leaf = Rad_PointInLeaf (dl->origin); - cluster = leaf->cluster; - dl->next = directlights[cluster]; - directlights[cluster] = dl; - - dl->type = emit_surface; - VectorCopy (p->plane->normal, dl->normal); - - dl->intensity = ColorNormalize (p->totallight, dl->color); - dl->intensity *= p->area * direct_scale; - VectorClear (p->totallight); // all sent now - } - - // - // entities - // - for (i=0 ; iorigin); - dl->style = FloatForKey (e, "_style"); - if (!dl->style) - dl->style = FloatForKey (e, "style"); - if (dl->style < 0 || dl->style >= MAX_LSTYLES) - dl->style = 0; - - leaf = Rad_PointInLeaf (dl->origin); - cluster = leaf->cluster; - - dl->next = directlights[cluster]; - directlights[cluster] = dl; - - intensity = FloatForKey (e, "light"); - if (!intensity) - intensity = FloatForKey (e, "_light"); - if (!intensity) - intensity = 300; - _color = ValueForKey (e, "_color"); - if (_color && _color[0]) - { - sscanf (_color, "%f %f %f", &dl->color[0],&dl->color[1],&dl->color[2]); - ColorNormalize (dl->color, dl->color); - } - else - dl->color[0] = dl->color[1] = dl->color[2] = 1.0; - dl->intensity = intensity*entity_scale; - dl->type = emit_point; - - target = ValueForKey (e, "target"); - - if (!strcmp (name, "light_spot") || target[0]) - { - dl->type = emit_spotlight; - dl->stopdot = FloatForKey (e, "_cone"); - if (!dl->stopdot) - dl->stopdot = 10; - dl->stopdot = cos(dl->stopdot/180*3.14159); - if (target[0]) - { // point towards target - e2 = FindTargetEntity (target); - if (!e2) - Sys_Printf ("WARNING: light at (%i %i %i) has missing target\n", - (int)dl->origin[0], (int)dl->origin[1], (int)dl->origin[2]); - else - { - GetVectorForKey (e2, "origin", dest); - VectorSubtract (dest, dl->origin, dl->normal); - VectorNormalize (dl->normal, dl->normal); - } - } - else - { // point down angle - angle = FloatForKey (e, "angle"); - if (angle == ANGLE_UP) - { - dl->normal[0] = dl->normal[1] = 0; - dl->normal[2] = 1; - } - else if (angle == ANGLE_DOWN) - { - dl->normal[0] = dl->normal[1] = 0; - dl->normal[2] = -1; - } - else - { - dl->normal[2] = 0; - dl->normal[0] = cos (angle/180*3.14159); - dl->normal[1] = sin (angle/180*3.14159); - } - } - } - } - - Sys_FPrintf( SYS_VRB, "%i direct lights\n", numdlights); -} - -/* -============= -GatherSampleLight - -Lightscale is the normalizer for multisampling -============= -*/ -void GatherSampleLight (vec3_t pos, vec3_t normal, - float **styletable, int offset, int mapsize, float lightscale) -{ - int i; - directlight_t *l; - byte pvs[(MAX_MAP_LEAFS+7)/8]; - vec3_t delta; - float dot, dot2; - float dist; - float scale; - float *dest; - - // get the PVS for the pos to limit the number of checks - if (!PvsForOrigin (pos, pvs)) - { - return; - } - - for (i = 0 ; inumclusters ; i++) - { - if ( ! (pvs[ i>>3] & (1<<(i&7))) ) - continue; - - for (l=directlights[i] ; l ; l=l->next) - { - VectorSubtract (l->origin, pos, delta); - dist = VectorNormalize (delta, delta); - dot = DotProduct (delta, normal); - if (dot <= 0.001) - continue; // behind sample surface - - switch (l->type) - { - case emit_point: - // linear falloff - scale = (l->intensity - dist) * dot; - break; - - case emit_surface: - dot2 = -DotProduct (delta, l->normal); - if (dot2 <= 0.001) - goto skipadd; // behind light surface - scale = (l->intensity / (dist*dist) ) * dot * dot2; - break; - - case emit_spotlight: - // linear falloff - dot2 = -DotProduct (delta, l->normal); - if (dot2 <= l->stopdot) - goto skipadd; // outside light cone - scale = (l->intensity - dist) * dot; - break; - default: - Error ("Bad l->type"); - } - - if (TestLine_r (0, pos, l->origin)) - continue; // occluded - - if (scale <= 0) - continue; - - // if this style doesn't have a table yet, allocate one - if (!styletable[l->style]) - { - styletable[l->style] = malloc (mapsize); - memset (styletable[l->style], 0, mapsize); - } - - dest = styletable[l->style] + offset; - // add some light to it - VectorMA (dest, scale*lightscale, l->color, dest); - -skipadd: ; - } - } - -} - -/* -============= -AddSampleToPatch - -Take the sample's collected light and -add it back into the apropriate patch -for the radiosity pass. - -The sample is added to all patches that might include -any part of it. They are counted and averaged, so it -doesn't generate extra light. -============= -*/ -void AddSampleToPatch (vec3_t pos, vec3_t color, int facenum) -{ - patch_t *patch; - vec3_t mins, maxs; - int i; - - if (numbounce == 0) - return; - if (color[0] + color[1] + color[2] < 3) - return; - - for (patch = face_patches[facenum] ; patch ; patch=patch->next) - { - // see if the point is in this patch (roughly) - WindingBounds (patch->winding, mins, maxs); - for (i=0 ; i<3 ; i++) - { - if (mins[i] > pos[i] + 16) - goto nextpatch; - if (maxs[i] < pos[i] - 16) - goto nextpatch; - } - - // add the sample to the patch - patch->samples++; - VectorAdd (patch->samplelight, color, patch->samplelight); -nextpatch:; - } - -} - - -/* -============= -BuildFacelights -============= -*/ -float sampleofs[5][2] = -{ {0,0}, {-0.25, -0.25}, {0.25, -0.25}, {0.25, 0.25}, {-0.25, 0.25} }; - - -void BuildFacelights (int facenum) -{ - dface_t *f; - lightinfo_t l[5]; - float *styletable[MAX_LSTYLES]; - int i, j; - float *spot; - patch_t *patch; - int numsamples; - int tablesize; - facelight_t *fl; - - f = &dfaces[facenum]; - - if ( texinfo[f->texinfo].flags & (SURF_WARP|SURF_SKY) ) - return; // non-lit texture - - memset (styletable,0, sizeof(styletable)); - - if (extrasamples) - numsamples = 5; - else - numsamples = 1; - for (i=0 ; iplanenum].normal, l[i].facenormal); - l[i].facedist = dplanes[f->planenum].dist; - if (f->side) - { - VectorSubtract (vec3_origin, l[i].facenormal, l[i].facenormal); - l[i].facedist = -l[i].facedist; - } - - // get the origin offset for rotating bmodels - VectorCopy (face_offset[facenum], l[i].modelorg); - - CalcFaceVectors (&l[i]); - CalcFaceExtents (&l[i]); - CalcPoints (&l[i], sampleofs[i][0], sampleofs[i][1]); - } - - tablesize = l[0].numsurfpt * sizeof(vec3_t); - styletable[0] = malloc(tablesize); - memset (styletable[0], 0, tablesize); - - fl = &facelight[facenum]; - fl->numsamples = l[0].numsurfpt; - fl->origins = malloc (tablesize); - memcpy (fl->origins, l[0].surfpt, tablesize); - - for (i=0 ; inext) - { - if (patch->samples) - { - VectorScale (patch->samplelight, 1.0/patch->samples, patch->samplelight); - } - else - { -// printf ("patch with no samples\n"); - } - } - - for (i=0 ; inumstyles == MAX_STYLES) - break; - fl->samples[fl->numstyles] = styletable[i]; - fl->stylenums[fl->numstyles] = i; - fl->numstyles++; - } - - // the light from DIRECT_LIGHTS is sent out, but the - // texture itself should still be full bright - - if (face_patches[facenum]->baselight[0] >= DIRECT_LIGHT || - face_patches[facenum]->baselight[1] >= DIRECT_LIGHT || - face_patches[facenum]->baselight[2] >= DIRECT_LIGHT - ) - { - spot = fl->samples[0]; - for (i=0 ; ibaselight, spot); - } - } -} - - -/* -============= -FinalLightFace - -Add the indirect lighting on top of the direct -lighting and save into final map format -============= -*/ -void FinalLightFace (int facenum) -{ - dface_t *f; - int i, j, k, st; - vec3_t lb; - patch_t *patch; - triangulation_t *trian; - facelight_t *fl; - float minlight; - float max, newmax; - byte *dest; - int pfacenum; - vec3_t facemins, facemaxs; - - f = &dfaces[facenum]; - fl = &facelight[facenum]; - - if ( texinfo[f->texinfo].flags & (SURF_WARP|SURF_SKY) ) - return; // non-lit texture - - ThreadLock (); - f->lightofs = lightdatasize; - lightdatasize += fl->numstyles*(fl->numsamples*3); - -// add green sentinals between lightmaps -#if 0 -lightdatasize += 64*3; -for (i=0 ; i<64 ; i++) -dlightdata[lightdatasize-(i+1)*3 + 1] = 255; -#endif - - if (lightdatasize > MAX_MAP_LIGHTING) - Error ("MAX_MAP_LIGHTING"); - ThreadUnlock (); - - f->styles[0] = 0; - f->styles[1] = f->styles[2] = f->styles[3] = 0xff; - - // - // set up the triangulation - // - if (numbounce > 0) - { - ClearBounds (facemins, facemaxs); - for (i=0 ; inumedges ; i++) - { - int ednum; - - ednum = dsurfedges[f->firstedge+i]; - if (ednum >= 0) - AddPointToBounds (dvertexes[dedges[ednum].v[0]].point, - facemins, facemaxs); - else - AddPointToBounds (dvertexes[dedges[-ednum].v[1]].point, - facemins, facemaxs); - } - - trian = AllocTriangulation (&dplanes[f->planenum]); - - // for all faces on the plane, add the nearby patches - // to the triangulation - for (pfacenum = planelinks[f->side][f->planenum] - ; pfacenum ; pfacenum = facelinks[pfacenum]) - { - for (patch = face_patches[pfacenum] ; patch ; patch=patch->next) - { - for (i=0 ; i < 3 ; i++) - { - if (facemins[i] - patch->origin[i] > subdiv*2) - break; - if (patch->origin[i] - facemaxs[i] > subdiv*2) - break; - } - if (i != 3) - continue; // not needed for this face - AddPointToTriangulation (patch, trian); - } - } - for (i=0 ; inumpoints ; i++) - memset (trian->edgematrix[i], 0, trian->numpoints*sizeof(trian->edgematrix[0][0]) ); - TriangulatePoints (trian); - } - - // - // sample the triangulation - // - - // _minlight allows models that have faces that would not be - // illuminated to receive a mottled light pattern instead of - // black - minlight = FloatForKey (face_entity[facenum], "_minlight") * 128; - - dest = &dlightdata[f->lightofs]; - - if (fl->numstyles > MAXLIGHTMAPS) - { - fl->numstyles = MAXLIGHTMAPS; - Sys_Printf ("face with too many lightstyles: (%f %f %f)\n", - face_patches[facenum]->origin[0], - face_patches[facenum]->origin[1], - face_patches[facenum]->origin[2] - ); - } - - for (st=0 ; stnumstyles ; st++) - { - f->styles[st] = fl->stylenums[st]; - for (j=0 ; jnumsamples ; j++) - { - VectorCopy ( (fl->samples[st]+j*3), lb); - if (numbounce > 0 && st == 0) - { - vec3_t add; - - SampleTriangulation (fl->origins + j*3, trian, add); - VectorAdd (lb, add, lb); - } - // add an ambient term if desired - lb[0] += ambient; - lb[1] += ambient; - lb[2] += ambient; - - VectorScale (lb, lightscale, lb); - - // we need to clamp without allowing hue to change - for (k=0 ; k<3 ; k++) - if (lb[k] < 1) - lb[k] = 1; - max = lb[0]; - if (lb[1] > max) - max = lb[1]; - if (lb[2] > max) - max = lb[2]; - newmax = max; - if (newmax < 0) - newmax = 0; // roundoff problems - if (newmax < minlight) - { - newmax = minlight + (rand()%48); - } - if (newmax > maxlight) - newmax = maxlight; - - for (k=0 ; k<3 ; k++) - { - *dest++ = lb[k]*newmax/max; - } - } - } - - if (numbounce > 0) - FreeTriangulation (trian); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/main.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/main.c deleted file mode 100644 index 5ed8daca..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/main.c +++ /dev/null @@ -1,721 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - - -/* marker */ -#define MAIN_C - - - -/* dependencies */ -#include "q2map.h" - -#define qtrue true -#define qfalse false - -char *mapname; -char game[64]; -extern qboolean verbose; - -/// BSP -extern qboolean drawflag; -extern qboolean noprune; -extern qboolean glview; -extern qboolean nodetail; -extern qboolean fulldetail; -extern qboolean onlyents; -extern qboolean nomerge; -extern qboolean nowater; -extern qboolean nofill; -extern qboolean nocsg; -extern qboolean noweld; -extern qboolean noshare; -extern qboolean nosubdiv; -extern qboolean notjunc; -extern qboolean noopt; -extern qboolean leaktest; -extern qboolean verboseentities; -extern char outbase[32]; -extern int block_xl, block_xh, block_yl, block_yh; -extern vec_t microvolume; -extern float subdivide_size; - -// VIS -extern char inbase[32]; -extern qboolean fastvis; -extern qboolean nosort; -extern int testlevel; - -// RAD -extern qboolean dumppatches; -extern int numbounce; -extern qboolean extrasamples; -extern float subdiv; -extern float lightscale; -extern float direct_scale; -extern float entity_scale; -extern qboolean nopvs; -extern float ambient; -extern float maxlight; - - -void InitPaths( int *argc, char **argv ); - -/* -Random() -returns a pseudorandom number between 0 and 1 -*/ -/* -vec_t Random( void ) -{ - return (vec_t) rand() / RAND_MAX; -} -*/ - - -/* -ExitQ2Map() -cleanup routine -*/ -/* -static void ExitQ2Map( void ) -{ - BSPFilesCleanup(); - if( mapDrawSurfs != NULL ) - free( mapDrawSurfs ); -} -*/ - - -/* -BSPInfo() -emits statistics about the bsp file -*/ - -int BSPInfo() -{ - char source[ 1024 ], ext[ 64 ]; - int size; - FILE *f; - - Sys_Printf ("\n----- INFO ----\n\n"); - - /* dummy check */ - if( mapname == NULL ) - { - Sys_Printf( "No files to dump info for.\n"); - return -1; - } - - /* enable info mode */ - //infoMode = qtrue; - - - /* mangle filename and get size */ - strcpy( source, mapname ); - ExtractFileExtension( source, ext ); - if( !Q_stricmp( ext, "map" ) ) - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - f = fopen( source, "rb" ); - if( f ) - { - size = Q_filelength (f); - fclose( f ); - } - else - size = 0; - - /* load the bsp file and print lump sizes */ - Sys_Printf( "Map: %s\n\n", source ); - - Sys_Printf( "-----------------------------------------------------\n" ); - - LoadBSPFile( source ); - PrintBSPFileSizes(); - - Sys_Printf( "-----------------------------------------------------\n" ); - - /* print sizes */ - Sys_Printf( "Total: %d B = %.3f kB = %.3f MB\n", size, size / 1024.0, size / (1024.0 * 1024.0) ); - - Sys_Printf( "-----------------------------------------------------\n" ); - - /* return count */ - return 0; -} - - - -/* -ScaleBSPMain() -amaze and confuse your enemies with wierd scaled maps! -*/ -/* -int ScaleBSPMain( int argc, char **argv ) -{ - int i; - float f, scale; - vec3_t vec; - char str[ 1024 ]; - - - // arg checking - if( argc < 2 ) - { - Sys_Printf( "Usage: q3map -scale [-v] \n" ); - return 0; - } - - // get scale - scale = atof( argv[ argc - 2 ] ); - if( scale == 0.0f ) - { - Sys_Printf( "Usage: q3map -scale [-v] \n" ); - Sys_Printf( "Non-zero scale value required.\n" ); - return 0; - } - - // do some path mangling - strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - - // load the bsp - Sys_Printf( "Loading %s\n", source ); - LoadBSPFile( source ); - ParseEntities(); - - // note it - Sys_Printf( "--- ScaleBSP ---\n" ); - Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities ); - - // scale entity keys - for( i = 0; i < numBSPEntities && i < numEntities; i++ ) - { - // scale origin - GetVectorForKey( &entities[ i ], "origin", vec ); - if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) ) - { - VectorScale( vec, scale, vec ); - sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); - SetKeyValue( &entities[ i ], "origin", str ); - } - - // scale door lip - f = FloatForKey( &entities[ i ], "lip" ); - if( f ) - { - f *= scale; - sprintf( str, "%f", f ); - SetKeyValue( &entities[ i ], "lip", str ); - } - } - - // scale models - for( i = 0; i < numBSPModels; i++ ) - { - VectorScale( bspModels[ i ].mins, scale, bspModels[ i ].mins ); - VectorScale( bspModels[ i ].maxs, scale, bspModels[ i ].maxs ); - } - - // scale nodes - for( i = 0; i < numBSPNodes; i++ ) - { - VectorScale( bspNodes[ i ].mins, scale, bspNodes[ i ].mins ); - VectorScale( bspNodes[ i ].maxs, scale, bspNodes[ i ].maxs ); - } - - // scale leafs - for( i = 0; i < numBSPLeafs; i++ ) - { - VectorScale( bspLeafs[ i ].mins, scale, bspLeafs[ i ].mins ); - VectorScale( bspLeafs[ i ].maxs, scale, bspLeafs[ i ].maxs ); - } - - // scale drawverts - for( i = 0; i < numBSPDrawVerts; i++ ) - VectorScale( bspDrawVerts[ i ].xyz, scale, bspDrawVerts[ i ].xyz ); - - // scale planes - for( i = 0; i < numBSPPlanes; i++ ) - bspPlanes[ i ].dist *= scale; - - // scale gridsize - GetVectorForKey( &entities[ 0 ], "gridsize", vec ); - if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f ) - VectorCopy( gridSize, vec ); - VectorScale( vec, scale, vec ); - sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); - SetKeyValue( &entities[ 0 ], "gridsize", str ); - - // write the bsp - UnparseEntities(); - StripExtension( source ); - DefaultExtension( source, "_s.bsp" ); - Sys_Printf( "Writing %s\n", source ); - WriteBSPFile( source ); - - // return to sender - return 0; -} -*/ - - -/* -ConvertBSPMain() -main argument processing function for bsp conversion -*/ -/* -int ConvertBSPMain( int argc, char **argv ) -{ - int i; - int (*convertFunc)( char * ); - - - // set default - convertFunc = ConvertBSPToASE; - - // arg checking - if( argc < 1 ) - { - Sys_Printf( "Usage: q3map -scale [-v] \n" ); - return 0; - } - - // process arguments - for( i = 1; i < (argc - 1); i++ ) - { - // -format map|ase|... - if( !strcmp( argv[ i ], "-format" ) ) - { - i++; - if( !Q_stricmp( argv[ i ], "ase" ) ) - convertFunc = ConvertBSPToASE; - else if( !Q_stricmp( argv[ i ], "map" ) ) - convertFunc = ConvertBSPToMap; - else - Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] ); - } - } - - // clean up map name - strcpy( source, ExpandArg( argv[ i ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - - LoadShaderInfo(); - - Sys_Printf( "Loading %s\n", source ); - - // ydnar: load surface file - //% LoadSurfaceExtraFile( source ); - - LoadBSPFile( source ); - - // parse bsp entities - ParseEntities(); - - // convert - return convertFunc( source ); -} -*/ - -int Check_BSP_Options( int argc, char **argv ) -{ - int i; - - for (i=1 ; i 59 ) - Sys_Printf("%d Minutes ", total_time/60 ); - Sys_Printf( "%d Seconds\n", total_time%60 ); - - /* shut down connection */ - Broadcast_Shutdown(); - - /* return any error code */ - return r; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/map.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/map.c deleted file mode 100644 index 818f2a1d..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/map.c +++ /dev/null @@ -1,1017 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// map.c - -#include "qbsp.h" - -extern qboolean onlyents; - -int nummapbrushes; -mapbrush_t mapbrushes[MAX_MAP_BRUSHES]; - -int nummapbrushsides; -side_t brushsides[MAX_MAP_SIDES]; -brush_texture_t side_brushtextures[MAX_MAP_SIDES]; - -int nummapplanes; -plane_t mapplanes[MAX_MAP_PLANES]; - -#define PLANE_HASHES 1024 -plane_t *planehash[PLANE_HASHES]; - -vec3_t map_mins, map_maxs; - -// undefine to make plane finding use linear sort -#define USE_HASHING - -void TestExpandBrushes (void); - -int c_boxbevels; -int c_edgebevels; - -int c_areaportals; - -int c_clipbrushes; - -/* -============================================================================= - -PLANE FINDING - -============================================================================= -*/ - - -/* -================= -PlaneTypeForNormal -================= -*/ -int PlaneTypeForNormal (vec3_t normal) -{ - vec_t ax, ay, az; - -// NOTE: should these have an epsilon around 1.0? - 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; - - ax = fabs(normal[0]); - ay = fabs(normal[1]); - az = fabs(normal[2]); - - if (ax >= ay && ax >= az) - return PLANE_ANYX; - if (ay >= ax && ay >= az) - return PLANE_ANYY; - return PLANE_ANYZ; -} - -/* -================ -PlaneEqual -================ -*/ -#define NORMAL_EPSILON 0.00001 -#define DIST_EPSILON 0.01 -qboolean PlaneEqual (plane_t *p, vec3_t normal, vec_t dist) -{ -#if 1 - if ( - fabs(p->normal[0] - normal[0]) < NORMAL_EPSILON - && fabs(p->normal[1] - normal[1]) < NORMAL_EPSILON - && fabs(p->normal[2] - normal[2]) < NORMAL_EPSILON - && fabs(p->dist - dist) < DIST_EPSILON ) - return true; -#else - if (p->normal[0] == normal[0] - && p->normal[1] == normal[1] - && p->normal[2] == normal[2] - && p->dist == dist) - return true; -#endif - return false; -} - -/* -================ -AddPlaneToHash -================ -*/ -void AddPlaneToHash (plane_t *p) -{ - int hash; - - hash = (int)fabs(p->dist) / 8; - hash &= (PLANE_HASHES-1); - - p->hash_chain = planehash[hash]; - planehash[hash] = p; -} - -/* -================ -CreateNewFloatPlane -================ -*/ -int CreateNewFloatPlane (vec3_t normal, vec_t dist) -{ - plane_t *p, temp; - - if (VectorLength(normal) < 0.5) - Error ("FloatPlane: bad normal"); - // create a new plane - if (nummapplanes+2 > MAX_MAP_PLANES) - Error ("MAX_MAP_PLANES"); - - p = &mapplanes[nummapplanes]; - VectorCopy (normal, p->normal); - p->dist = dist; - p->type = (p+1)->type = PlaneTypeForNormal (p->normal); - - VectorSubtract (vec3_origin, normal, (p+1)->normal); - (p+1)->dist = -dist; - - nummapplanes += 2; - - // allways put axial planes facing positive first - if (p->type < 3) - { - if (p->normal[0] < 0 || p->normal[1] < 0 || p->normal[2] < 0) - { - // flip order - temp = *p; - *p = *(p+1); - *(p+1) = temp; - - AddPlaneToHash (p); - AddPlaneToHash (p+1); - return nummapplanes - 1; - } - } - - AddPlaneToHash (p); - AddPlaneToHash (p+1); - return nummapplanes - 2; -} - -/* -============== -SnapVector -============== -*/ -void SnapVector (vec3_t normal) -{ - int i; - - for (i=0 ; i<3 ; i++) - { - if ( fabs(normal[i] - 1) < NORMAL_EPSILON ) - { - VectorClear (normal); - normal[i] = 1; - break; - } - if ( fabs(normal[i] - -1) < NORMAL_EPSILON ) - { - VectorClear (normal); - normal[i] = -1; - break; - } - } -} - -/* -============== -SnapPlane -============== -*/ -void SnapPlane (vec3_t normal, vec_t *dist) -{ - SnapVector (normal); - - if (fabs(*dist-Q_rint(*dist)) < DIST_EPSILON) - *dist = Q_rint(*dist); -} - -/* -============= -FindFloatPlane - -============= -*/ -#ifndef USE_HASHING -int FindFloatPlane (vec3_t normal, vec_t dist) -{ - int i; - plane_t *p; - - SnapPlane (normal, &dist); - for (i=0, p=mapplanes ; ihash_chain) - { - if (PlaneEqual (p, normal, dist)) - return p-mapplanes; - } - } - - return CreateNewFloatPlane (normal, dist); -} -#endif - -/* -================ -PlaneFromPoints -================ -*/ -int PlaneFromPoints (int *p0, int *p1, int *p2) -{ - vec3_t t1, t2, normal; - vec_t dist; - - VectorSubtract (p0, p1, t1); - VectorSubtract (p2, p1, t2); - CrossProduct (t1, t2, normal); - VectorNormalize (normal, normal); - - dist = DotProduct (p0, normal); - - return FindFloatPlane (normal, dist); -} - - -//==================================================================== - - -/* -=========== -BrushContents -=========== -*/ -int BrushContents (mapbrush_t *b) -{ - int contents; - side_t *s; - int i; - int trans; - - s = &b->original_sides[0]; - contents = s->contents; - trans = texinfo[s->texinfo].flags; - for (i=1 ; inumsides ; i++, s++) - { - s = &b->original_sides[i]; - trans |= texinfo[s->texinfo].flags; - if (s->contents != contents) - { - Sys_Printf ("Entity %i, Brush %i: mixed face contents\n" - , b->entitynum, b->brushnum); - break; - } - } - - // if any side is translucent, mark the contents - // and change solid to window - if ( trans & (SURF_TRANS33|SURF_TRANS66) ) - { - contents |= CONTENTS_TRANSLUCENT; - if (contents & CONTENTS_SOLID) - { - contents &= ~CONTENTS_SOLID; - contents |= CONTENTS_WINDOW; - } - } - - return contents; -} - - -//============================================================================ - -/* -================= -AddBrushBevels - -Adds any additional planes necessary to allow the brush to be expanded -against axial bounding boxes -================= -*/ -void AddBrushBevels (mapbrush_t *b) -{ - int axis, dir; - int i, j, k, l, order; - side_t sidetemp; - brush_texture_t tdtemp; - side_t *s, *s2; - vec3_t normal; - float dist; - winding_t *w, *w2; - vec3_t vec, vec2; - float d; - - // - // add the axial planes - // - order = 0; - for (axis=0 ; axis <3 ; axis++) - { - for (dir=-1 ; dir <= 1 ; dir+=2, order++) - { - // see if the plane is allready present - for (i=0, s=b->original_sides ; inumsides ; i++,s++) - { - if (mapplanes[s->planenum].normal[axis] == dir) - break; - } - - if (i == b->numsides) - { // add a new side - if (nummapbrushsides == MAX_MAP_BRUSHSIDES) - Error ("MAX_MAP_BRUSHSIDES"); - nummapbrushsides++; - b->numsides++; - VectorClear (normal); - normal[axis] = dir; - if (dir == 1) - dist = b->maxs[axis]; - else - dist = -b->mins[axis]; - s->planenum = FindFloatPlane (normal, dist); - s->texinfo = b->original_sides[0].texinfo; - s->contents = b->original_sides[0].contents; - s->bevel = true; - c_boxbevels++; - } - - // if the plane is not in it canonical order, swap it - if (i != order) - { - sidetemp = b->original_sides[order]; - b->original_sides[order] = b->original_sides[i]; - b->original_sides[i] = sidetemp; - - j = b->original_sides - brushsides; - tdtemp = side_brushtextures[j+order]; - side_brushtextures[j+order] = side_brushtextures[j+i]; - side_brushtextures[j+i] = tdtemp; - } - } - } - - // - // add the edge bevels - // - if (b->numsides == 6) - return; // pure axial - - // test the non-axial plane edges - for (i=6 ; inumsides ; i++) - { - s = b->original_sides + i; - w = s->winding; - if (!w) - continue; - for (j=0 ; jnumpoints ; j++) - { - k = (j+1)%w->numpoints; - VectorSubtract (w->p[j], w->p[k], vec); - if (VectorNormalize (vec, vec) < 0.5) - continue; - SnapVector (vec); - for (k=0 ; k<3 ; k++) - if ( vec[k] == -1 || vec[k] == 1) - break; // axial - if (k != 3) - continue; // only test non-axial edges - - // try the six possible slanted axials from this edge - for (axis=0 ; axis <3 ; axis++) - { - for (dir=-1 ; dir <= 1 ; dir+=2) - { - // construct a plane - VectorClear (vec2); - vec2[axis] = dir; - CrossProduct (vec, vec2, normal); - if (VectorNormalize (normal, normal) < 0.5) - continue; - dist = DotProduct (w->p[j], normal); - - // if all the points on all the sides are - // behind this plane, it is a proper edge bevel - for (k=0 ; knumsides ; k++) - { - // if this plane has allready been used, skip it - if (PlaneEqual (&mapplanes[b->original_sides[k].planenum] - , normal, dist) ) - break; - - w2 = b->original_sides[k].winding; - if (!w2) - continue; - for (l=0 ; lnumpoints ; l++) - { - d = DotProduct (w2->p[l], normal) - dist; - if (d > 0.1) - break; // point in front - } - if (l != w2->numpoints) - break; - } - - if (k != b->numsides) - continue; // wasn't part of the outer hull - // add this plane - if (nummapbrushsides == MAX_MAP_BRUSHSIDES) - Error ("MAX_MAP_BRUSHSIDES"); - nummapbrushsides++; - s2 = &b->original_sides[b->numsides]; - s2->planenum = FindFloatPlane (normal, dist); - s2->texinfo = b->original_sides[0].texinfo; - s2->contents = b->original_sides[0].contents; - s2->bevel = true; - c_edgebevels++; - b->numsides++; - } - } - } - } -} - - -/* -================ -MakeBrushWindings - -makes basewindigs for sides and mins / maxs for the brush -================ -*/ -qboolean MakeBrushWindings (mapbrush_t *ob) -{ - int i, j; - winding_t *w; - side_t *side; - plane_t *plane; - - ClearBounds (ob->mins, ob->maxs); - - for (i=0 ; inumsides ; i++) - { - plane = &mapplanes[ob->original_sides[i].planenum]; - w = BaseWindingForPlane (plane->normal, plane->dist); - for (j=0 ; jnumsides && w; j++) - { - if (i == j) - continue; - if (ob->original_sides[j].bevel) - continue; - plane = &mapplanes[ob->original_sides[j].planenum^1]; - ChopWindingInPlace (&w, plane->normal, plane->dist, 0); //CLIP_EPSILON); - } - - side = &ob->original_sides[i]; - side->winding = w; - if (w) - { - side->visible = true; - for (j=0 ; jnumpoints ; j++) - AddPointToBounds (w->p[j], ob->mins, ob->maxs); - } - } - - for (i=0 ; i<3 ; i++) - { - if (ob->mins[0] < -4096 || ob->maxs[0] > 4096) - Sys_Printf ("entity %i, brush %i: bounds out of range\n", ob->entitynum, ob->brushnum); - if (ob->mins[0] > 4096 || ob->maxs[0] < -4096) - Sys_Printf ("entity %i, brush %i: no visible sides on brush\n", ob->entitynum, ob->brushnum); - } - - return true; -} - - -/* -================= -ParseBrush -================= -*/ -void ParseBrush (entity_t *mapent) -{ - mapbrush_t *b; - int i,j, k; - int mt; - side_t *side, *s2; - int planenum; - brush_texture_t td; - int planepts[3][3]; - - if (nummapbrushes == MAX_MAP_BRUSHES) - Error ("nummapbrushes == MAX_MAP_BRUSHES"); - - b = &mapbrushes[nummapbrushes]; - b->original_sides = &brushsides[nummapbrushsides]; - b->entitynum = num_entities-1; - b->brushnum = nummapbrushes - mapent->firstbrush; - - do - { - if (!GetToken (true)) - break; - if (!strcmp (token, "}") ) - break; - - if (nummapbrushsides == MAX_MAP_BRUSHSIDES) - Error ("MAX_MAP_BRUSHSIDES"); - side = &brushsides[nummapbrushsides]; - - // read the three point plane definition - for (i=0 ; i<3 ; i++) - { - if (i != 0) - GetToken (true); - if (strcmp (token, "(") ) - Error ("parsing brush"); - - for (j=0 ; j<3 ; j++) - { - GetToken (false); - planepts[i][j] = atoi(token); - } - - GetToken (false); - if (strcmp (token, ")") ) - Error ("parsing brush"); - - } - - - // - // read the texturedef - // - GetToken (false); - strcpy (td.name, token); - - GetToken (false); - td.shift[0] = atoi(token); - GetToken (false); - td.shift[1] = atoi(token); - GetToken (false); - td.rotate = atoi(token); - GetToken (false); - td.scale[0] = atof(token); - GetToken (false); - td.scale[1] = atof(token); - - // find default flags and values - mt = FindMiptex (td.name); - td.flags = textureref[mt].flags; - td.value = textureref[mt].value; - side->contents = textureref[mt].contents; - side->surf = td.flags = textureref[mt].flags; - - if (TokenAvailable()) - { - GetToken (false); - side->contents = atoi(token); - GetToken (false); - side->surf = td.flags = atoi(token); - GetToken (false); - td.value = atoi(token); - } - - // translucent objects are automatically classified as detail - if (side->surf & (SURF_TRANS33|SURF_TRANS66) ) - side->contents |= CONTENTS_DETAIL; - if (side->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) ) - side->contents |= CONTENTS_DETAIL; - if (fulldetail) - side->contents &= ~CONTENTS_DETAIL; - if (!(side->contents & ((LAST_VISIBLE_CONTENTS-1) - | CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_MIST) ) ) - side->contents |= CONTENTS_SOLID; - - // hints and skips are never detail, and have no content - if (side->surf & (SURF_HINT|SURF_SKIP) ) - { - side->contents = 0; - side->surf &= ~CONTENTS_DETAIL; - } - - - // - // find the plane number - // - planenum = PlaneFromPoints (planepts[0], planepts[1], planepts[2]); - if (planenum == -1) - { - Sys_Printf ("Entity %i, Brush %i: plane with no normal\n" - , b->entitynum, b->brushnum); - continue; - } - - // - // see if the plane has been used already - // - for (k=0 ; knumsides ; k++) - { - s2 = b->original_sides + k; - if (s2->planenum == planenum) - { - Sys_Printf ("Entity %i, Brush %i: duplicate plane\n" - , b->entitynum, b->brushnum); - break; - } - if ( s2->planenum == (planenum^1) ) - { - Sys_Printf ("Entity %i, Brush %i: mirrored plane\n" - , b->entitynum, b->brushnum); - break; - } - } - if (k != b->numsides) - continue; // duplicated - - // - // keep this side - // - - side = b->original_sides + b->numsides; - side->planenum = planenum; - side->texinfo = TexinfoForBrushTexture (&mapplanes[planenum], - &td, vec3_origin); - - // save the td off in case there is an origin brush and we - // have to recalculate the texinfo - side_brushtextures[nummapbrushsides] = td; - - nummapbrushsides++; - b->numsides++; - } while (1); - - // get the content for the entire brush - b->contents = BrushContents (b); - - // allow detail brushes to be removed - if (nodetail && (b->contents & CONTENTS_DETAIL) ) - { - b->numsides = 0; - return; - } - - // allow water brushes to be removed - if (nowater && (b->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) ) - { - b->numsides = 0; - return; - } - - // create windings for sides and bounds for brush - MakeBrushWindings (b); - - // brushes that will not be visible at all will never be - // used as bsp splitters - if (b->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) ) - { - c_clipbrushes++; - for (i=0 ; inumsides ; i++) - b->original_sides[i].texinfo = TEXINFO_NODE; - } - - // - // origin brushes are removed, but they set - // the rotation origin for the rest of the brushes - // in the entity. After the entire entity is parsed, - // the planenums and texinfos will be adjusted for - // the origin brush - // - if (b->contents & CONTENTS_ORIGIN) - { - char string[32]; - vec3_t origin; - - if (num_entities == 1) - { - Error ("Entity %i, Brush %i: origin brushes not allowed in world" - , b->entitynum, b->brushnum); - return; - } - - VectorAdd (b->mins, b->maxs, origin); - VectorScale (origin, 0.5, origin); - - sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]); - SetKeyValue (&entities[b->entitynum], "origin", string); - - VectorCopy (origin, entities[b->entitynum].origin); - - // don't keep this brush - b->numsides = 0; - - return; - } - - AddBrushBevels (b); - - nummapbrushes++; - mapent->numbrushes++; -} - -/* -================ -MoveBrushesToWorld - -Takes all of the brushes from the current entity and -adds them to the world's brush list. - -Used by func_group and func_areaportal -================ -*/ -void MoveBrushesToWorld (entity_t *mapent) -{ - int newbrushes; - int worldbrushes; - mapbrush_t *temp; - int i; - - // this is pretty gross, because the brushes are expected to be - // in linear order for each entity - - newbrushes = mapent->numbrushes; - worldbrushes = entities[0].numbrushes; - - temp = malloc(newbrushes*sizeof(mapbrush_t)); - memcpy (temp, mapbrushes + mapent->firstbrush, newbrushes*sizeof(mapbrush_t)); - -#if 0 // let them keep their original brush numbers - for (i=0 ; inumbrushes = 0; -} - -/* -================ -ParseMapEntity -================ -*/ -qboolean ParseMapEntity (void) -{ - entity_t *mapent; - epair_t *e; - side_t *s; - int i, j; - int startbrush, startsides; - vec_t newdist; - mapbrush_t *b; - - if (!GetToken (true)) - return false; - - if (strcmp (token, "{") ) - Error ("ParseEntity: { not found"); - - if (num_entities == MAX_MAP_ENTITIES) - Error ("num_entities == MAX_MAP_ENTITIES"); - - startbrush = nummapbrushes; - startsides = nummapbrushsides; - - mapent = &entities[num_entities]; - num_entities++; - memset (mapent, 0, sizeof(*mapent)); - mapent->firstbrush = nummapbrushes; - mapent->numbrushes = 0; -// mapent->portalareas[0] = -1; -// mapent->portalareas[1] = -1; - - do - { - if (!GetToken (true)) - Error ("ParseEntity: EOF without closing brace"); - if (!strcmp (token, "}") ) - break; - if (!strcmp (token, "{") ) - ParseBrush (mapent); - else - { - e = ParseEpair (); - e->next = mapent->epairs; - mapent->epairs = e; - } - } while (1); - - GetVectorForKey (mapent, "origin", mapent->origin); - - // - // if there was an origin brush, offset all of the planes and texinfo - // - if (mapent->origin[0] || mapent->origin[1] || mapent->origin[2]) - { - for (i=0 ; inumbrushes ; i++) - { - b = &mapbrushes[mapent->firstbrush + i]; - for (j=0 ; jnumsides ; j++) - { - s = &b->original_sides[j]; - newdist = mapplanes[s->planenum].dist - - DotProduct (mapplanes[s->planenum].normal, mapent->origin); - s->planenum = FindFloatPlane (mapplanes[s->planenum].normal, newdist); - s->texinfo = TexinfoForBrushTexture (&mapplanes[s->planenum], - &side_brushtextures[s-brushsides], mapent->origin); - } - MakeBrushWindings (b); - } - } - - // group entities are just for editor convenience - // toss all brushes into the world entity - if (!strcmp ("func_group", ValueForKey (mapent, "classname"))) - { - MoveBrushesToWorld (mapent); - mapent->numbrushes = 0; - return true; - } - - // areaportal entities move their brushes, but don't eliminate - // the entity - if (!strcmp ("func_areaportal", ValueForKey (mapent, "classname"))) - { - char str[128]; - - if (mapent->numbrushes != 1) - Error ("Entity %i: func_areaportal can only be a single brush", num_entities-1); - - b = &mapbrushes[nummapbrushes-1]; - b->contents = CONTENTS_AREAPORTAL; - c_areaportals++; - mapent->areaportalnum = c_areaportals; - // set the portal number as "style" - sprintf (str, "%i", c_areaportals); - SetKeyValue (mapent, "style", str); - MoveBrushesToWorld (mapent); - return true; - } - - return true; -} - -//=================================================================== - -/* -================ -LoadMapFile -================ -*/ -void LoadMapFile (char *filename) -{ - int i; - - Sys_FPrintf( SYS_VRB, "--- LoadMapFile ---\n"); - - LoadScriptFile (filename); - - nummapbrushsides = 0; - num_entities = 0; - - while (ParseMapEntity ()) - { - } - - ClearBounds (map_mins, map_maxs); - for (i=0 ; i 4096) - continue; // no valid points - AddPointToBounds (mapbrushes[i].mins, map_mins, map_maxs); - AddPointToBounds (mapbrushes[i].maxs, map_mins, map_maxs); - } - - Sys_FPrintf( SYS_VRB, "%5i brushes\n", nummapbrushes); - Sys_FPrintf( SYS_VRB, "%5i clipbrushes\n", c_clipbrushes); - Sys_FPrintf( SYS_VRB, "%5i total sides\n", nummapbrushsides); - Sys_FPrintf( SYS_VRB, "%5i boxbevels\n", c_boxbevels); - Sys_FPrintf( SYS_VRB, "%5i edgebevels\n", c_edgebevels); - Sys_FPrintf( SYS_VRB, "%5i entities\n", num_entities); - Sys_FPrintf( SYS_VRB, "%5i planes\n", nummapplanes); - Sys_FPrintf( SYS_VRB, "%5i areaportals\n", c_areaportals); - Sys_FPrintf( SYS_VRB, "size: %5.0f,%5.0f,%5.0f to %5.0f,%5.0f,%5.0f\n", map_mins[0],map_mins[1],map_mins[2], - map_maxs[0],map_maxs[1],map_maxs[2]); - -// TestExpandBrushes (); -} - - -//==================================================================== - - -/* -================ -TestExpandBrushes - -Expands all the brush planes and saves a new map out -================ -*/ -void TestExpandBrushes (void) -{ - FILE *f; - side_t *s; - int i, j, bn; - winding_t *w; - char *name = "expanded.map"; - mapbrush_t *brush; - vec_t dist; - - Sys_Printf ("writing %s\n", name); - f = fopen (name, "wb"); - if (!f) - Error ("Can't write %s\b", name); - - fprintf (f, "{\n\"classname\" \"worldspawn\"\n"); - - for (bn=0 ; bnnumsides ; i++) - { - s = brush->original_sides + i; - dist = mapplanes[s->planenum].dist; - for (j=0 ; j<3 ; j++) - dist += fabs( 16 * mapplanes[s->planenum].normal[j] ); - - w = BaseWindingForPlane (mapplanes[s->planenum].normal, dist); - - fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]); - fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]); - fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]); - - fprintf (f, "%s 0 0 0 1 1\n", texinfo[s->texinfo].texture); - FreeWinding (w); - } - fprintf (f, "}\n"); - } - fprintf (f, "}\n"); - - fclose (f); - - Error ("can't proceed after expanding brushes"); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/nodraw.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/nodraw.c deleted file mode 100644 index 888b2570..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/nodraw.c +++ /dev/null @@ -1,46 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -vec3_t draw_mins, draw_maxs; -qboolean drawflag; - -void Draw_ClearWindow (void) -{ -} - -//============================================================ - -#define GLSERV_PORT 25001 - - -void GLS_BeginScene (void) -{ -} - -void GLS_Winding (winding_t *w, int code) -{ -} - -void GLS_EndScene (void) -{ -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/patches.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/patches.c deleted file mode 100644 index 2ff82315..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/patches.c +++ /dev/null @@ -1,603 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qrad.h" - -vec3_t texture_reflectivity[MAX_MAP_TEXINFO]; - -/* -=================================================================== - - TEXTURE LIGHT VALUES - -=================================================================== -*/ - -/* -====================== -CalcTextureReflectivity_Quake2 -====================== -*/ -void CalcTextureReflectivity_Quake2 (void) -{ - int i; - int j, k, texels; - int color[3]; - int texel; - byte *palette; - char path[1024]; - float r, scale; - miptex_t *mt; - - sprintf (path, "%spics/colormap.pcx", gamedir); - - // get the game palette - Load256Image (path, NULL, &palette, NULL, NULL); - - // allways set index 0 even if no textures - texture_reflectivity[0][0] = 0.5; - texture_reflectivity[0][1] = 0.5; - texture_reflectivity[0][2] = 0.5; - - for (i=0 ; iwidth)*LittleLong(mt->height); - color[0] = color[1] = color[2] = 0; - - for (j=0 ; joffsets[0]) + j]; - for (k=0 ; k<3 ; k++) - color[k] += palette[texel*3+k]; - } - - for (j=0 ; j<3 ; j++) - { - r = color[j]/texels/255.0; - texture_reflectivity[i][j] = r; - } - // scale the reflectivity up, because the textures are - // so dim - scale = ColorNormalize (texture_reflectivity[i], - texture_reflectivity[i]); - if (scale < 0.5) - { - scale *= 2; - VectorScale (texture_reflectivity[i], scale, texture_reflectivity[i]); - } -#if 0 -texture_reflectivity[i][0] = 0.5; -texture_reflectivity[i][1] = 0.5; -texture_reflectivity[i][2] = 0.5; -#endif - } -} - -/* -====================== -CalcTextureReflectivity_Heretic2 -====================== -*/ -void CalcTextureReflectivity_Heretic2 (void) -{ - int i; - int j, texels; - int color[3]; - int texel; - char path[1024]; - float r; - miptex_m8_t *mt; - miptex_m32_t *mt32; - byte *pos; - - - // allways set index 0 even if no textures - texture_reflectivity[0][0] = 0.5; - texture_reflectivity[0][1] = 0.5; - texture_reflectivity[0][2] = 0.5; - - for (i=0 ; iwidth[0])*LittleLong(mt->height[0]); - color[0] = color[1] = color[2] = 0; - - for (j=0 ; joffsets[0]) + j]; - color[0] += mt->palette[texel].r; - color[1] += mt->palette[texel].g; - color[2] += mt->palette[texel].b; - } - - free(mt); - } - else - { - texels = LittleLong(mt32->width[0])*LittleLong(mt32->height[0]); - color[0] = color[1] = color[2] = 0; - - for (j=0 ; joffsets[0] + (j<<2); - color[0] += *pos++; // r - color[1] += *pos++; // g - color[2] += *pos++; // b - } - - free(mt32); - } - - - for (j=0 ; j<3 ; j++) - { - r = color[j]/((float) texels*255.0); - texture_reflectivity[i][j] = r; - } - } -} - -/* -======================================================================= - -MAKE FACES - -======================================================================= -*/ - -/* -============= -WindingFromFace -============= -*/ -winding_t *WindingFromFace (dface_t *f) -{ - int i; - int se; - dvertex_t *dv; - int v; - winding_t *w; - - w = AllocWinding (f->numedges); - w->numpoints = f->numedges; - - for (i=0 ; inumedges ; i++) - { - se = dsurfedges[f->firstedge + i]; - if (se < 0) - v = dedges[-se].v[1]; - else - v = dedges[se].v[0]; - - dv = &dvertexes[v]; - VectorCopy (dv->point, w->p[i]); - } - - RemoveColinearPoints (w); - - return w; -} - -/* -============= -BaseLightForFace -============= -*/ -void BaseLightForFace (dface_t *f, vec3_t color) -{ - texinfo_t *tx; - - // - // check for light emited by texture - // - tx = &texinfo[f->texinfo]; - if (!(tx->flags & SURF_LIGHT) || tx->value == 0) - { - VectorClear (color); - return; - } - - VectorScale (texture_reflectivity[f->texinfo], tx->value, color); -} - -qboolean IsSky (dface_t *f) -{ - texinfo_t *tx; - - tx = &texinfo[f->texinfo]; - if (tx->flags & SURF_SKY) - return true; - return false; -} - -/* -============= -MakePatchForFace -============= -*/ -float totalarea; -void MakePatchForFace (int fn, winding_t *w) -{ - dface_t *f; - float area; - patch_t *patch; - dplane_t *pl; - int i; - vec3_t color; - dleaf_t *leaf; - - f = &dfaces[fn]; - - area = WindingArea (w); - totalarea += area; - - patch = &patches[num_patches]; - if (num_patches == MAX_PATCHES) - Error ("num_patches == MAX_PATCHES"); - patch->next = face_patches[fn]; - face_patches[fn] = patch; - - patch->winding = w; - - if (f->side) - patch->plane = &backplanes[f->planenum]; - else - patch->plane = &dplanes[f->planenum]; - if (face_offset[fn][0] || face_offset[fn][1] || face_offset[fn][2] ) - { // origin offset faces must create new planes - if (numplanes + fakeplanes >= MAX_MAP_PLANES) - Error ("numplanes + fakeplanes >= MAX_MAP_PLANES"); - pl = &dplanes[numplanes + fakeplanes]; - fakeplanes++; - - *pl = *(patch->plane); - pl->dist += DotProduct (face_offset[fn], pl->normal); - patch->plane = pl; - } - - WindingCenter (w, patch->origin); - VectorAdd (patch->origin, patch->plane->normal, patch->origin); - leaf = Rad_PointInLeaf(patch->origin); - patch->cluster = leaf->cluster; - if (patch->cluster == -1) - Sys_FPrintf( SYS_VRB, "patch->cluster == -1\n"); - - patch->area = area; - if (patch->area <= 1) - patch->area = 1; - patch->sky = IsSky (f); - - VectorCopy (texture_reflectivity[f->texinfo], patch->reflectivity); - - // non-bmodel patches can emit light - if (fn < dmodels[0].numfaces) - { - BaseLightForFace (f, patch->baselight); - - ColorNormalize (patch->reflectivity, color); - - for (i=0 ; i<3 ; i++) - patch->baselight[i] *= color[i]; - - VectorCopy (patch->baselight, patch->totallight); - } - num_patches++; -} - - -entity_t *EntityForModel (int modnum) -{ - int i; - char *s; - char name[16]; - - sprintf (name, "*%i", modnum); - // search the entities for one using modnum - for (i=0 ; inumfaces ; j++) - { - fn = mod->firstface + j; - face_entity[fn] = ent; - VectorCopy (origin, face_offset[fn]); - f = &dfaces[fn]; - w = WindingFromFace (f); - for (k=0 ; knumpoints ; k++) - { - VectorAdd (w->p[k], origin, w->p[k]); - } - MakePatchForFace (fn, w); - } - } - - Sys_FPrintf( SYS_VRB, "%i sqaure feet\n", (int)(totalarea/64)); -} - -/* -======================================================================= - -SUBDIVIDE - -======================================================================= -*/ - -void FinishSplit (patch_t *patch, patch_t *newp) -{ - dleaf_t *leaf; - - VectorCopy (patch->baselight, newp->baselight); - VectorCopy (patch->totallight, newp->totallight); - VectorCopy (patch->reflectivity, newp->reflectivity); - newp->plane = patch->plane; - newp->sky = patch->sky; - - patch->area = WindingArea (patch->winding); - newp->area = WindingArea (newp->winding); - - if (patch->area <= 1) - patch->area = 1; - if (newp->area <= 1) - newp->area = 1; - - WindingCenter (patch->winding, patch->origin); - VectorAdd (patch->origin, patch->plane->normal, patch->origin); - leaf = Rad_PointInLeaf(patch->origin); - patch->cluster = leaf->cluster; - if (patch->cluster == -1) - Sys_FPrintf( SYS_VRB, "patch->cluster == -1\n"); - - WindingCenter (newp->winding, newp->origin); - VectorAdd (newp->origin, newp->plane->normal, newp->origin); - leaf = Rad_PointInLeaf(newp->origin); - newp->cluster = leaf->cluster; - if (newp->cluster == -1) - Sys_FPrintf( SYS_VRB, "patch->cluster == -1\n"); -} - -/* -============= -SubdividePatch - -Chops the patch only if its local bounds exceed the max size -============= -*/ -void SubdividePatch (patch_t *patch) -{ - winding_t *w, *o1, *o2; - vec3_t mins, maxs, total; - vec3_t split; - vec_t dist; - int i, j; - vec_t v; - patch_t *newp; - - w = patch->winding; - mins[0] = mins[1] = mins[2] = 99999; - maxs[0] = maxs[1] = maxs[2] = -99999; - for (i=0 ; inumpoints ; 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; - } - } - VectorSubtract (maxs, mins, total); - for (i=0 ; i<3 ; i++) - if (total[i] > (subdiv+1) ) - break; - if (i == 3) - { - // no splitting needed - return; - } - - // - // split the winding - // - VectorCopy (vec3_origin, split); - split[i] = 1; - dist = (mins[i] + maxs[i])*0.5; - ClipWindingEpsilon (w, split, dist, ON_EPSILON, &o1, &o2); - - // - // create a new patch - // - if (num_patches == MAX_PATCHES) - Error ("MAX_PATCHES"); - newp = &patches[num_patches]; - num_patches++; - - newp->next = patch->next; - patch->next = newp; - - patch->winding = o1; - newp->winding = o2; - - FinishSplit (patch, newp); - - SubdividePatch (patch); - SubdividePatch (newp); -} - - -/* -============= -DicePatch - -Chops the patch by a global grid -============= -*/ -void DicePatch (patch_t *patch) -{ - winding_t *w, *o1, *o2; - vec3_t mins, maxs; - vec3_t split; - vec_t dist; - int i; - patch_t *newp; - - w = patch->winding; - WindingBounds (w, mins, maxs); - for (i=0 ; i<3 ; i++) - if (floor((mins[i]+1)/subdiv) < floor((maxs[i]-1)/subdiv)) - break; - if (i == 3) - { - // no splitting needed - return; - } - - // - // split the winding - // - VectorCopy (vec3_origin, split); - split[i] = 1; - dist = subdiv*(1+floor((mins[i]+1)/subdiv)); - ClipWindingEpsilon (w, split, dist, ON_EPSILON, &o1, &o2); - - // - // create a new patch - // - if (num_patches == MAX_PATCHES) - Error ("MAX_PATCHES"); - newp = &patches[num_patches]; - num_patches++; - - newp->next = patch->next; - patch->next = newp; - - patch->winding = o1; - newp->winding = o2; - - FinishSplit (patch, newp); - - DicePatch (patch); - DicePatch (newp); -} - - -/* -============= -SubdividePatches -============= -*/ -void SubdividePatches (void) -{ - int i, num; - - if (subdiv < 1) - return; - - num = num_patches; // because the list will grow - for (i=0 ; i c_peak_portals) - c_peak_portals = c_active_portals; - - p = malloc (sizeof(portal_t)); - memset (p, 0, sizeof(portal_t)); - - return p; -} - -void FreePortal (portal_t *p) -{ - if (p->winding) - FreeWinding (p->winding); - if (numthreads == 1) - c_active_portals--; - free (p); -} - -//============================================================== - -/* -============== -VisibleContents - -Returns the single content bit of the -strongest visible content present -============== -*/ -int VisibleContents (int contents) -{ - int i; - - for (i=1 ; i<=LAST_VISIBLE_CONTENTS ; i<<=1) - if (contents & i ) - return i; - - return 0; -} - - -/* -=============== -ClusterContents -=============== -*/ -int ClusterContents (node_t *node) -{ - int c1, c2, c; - - if (node->planenum == PLANENUM_LEAF) - return node->contents; - - c1 = ClusterContents(node->children[0]); - c2 = ClusterContents(node->children[1]); - c = c1|c2; - - // a cluster may include some solid detail areas, but - // still be seen into - if ( ! (c1&CONTENTS_SOLID) || ! (c2&CONTENTS_SOLID) ) - c &= ~CONTENTS_SOLID; - return c; -} - -/* -============= -Portal_VisFlood - -Returns true if the portal is empty or translucent, allowing -the PVS calculation to see through it. -The nodes on either side of the portal may actually be clusters, -not leafs, so all contents should be ored together -============= -*/ -qboolean Portal_VisFlood (portal_t *p) -{ - int c1, c2; - - if (!p->onnode) - return false; // to global outsideleaf - - c1 = ClusterContents(p->nodes[0]); - c2 = ClusterContents(p->nodes[1]); - - if (!VisibleContents (c1^c2)) - return true; - - if (c1 & (CONTENTS_TRANSLUCENT|CONTENTS_DETAIL)) - c1 = 0; - if (c2 & (CONTENTS_TRANSLUCENT|CONTENTS_DETAIL)) - c2 = 0; - - if ( (c1|c2) & CONTENTS_SOLID ) - return false; // can't see through solid - - if (! (c1 ^ c2)) - return true; // identical on both sides - - if (!VisibleContents (c1^c2)) - return true; - return false; -} - - -/* -=============== -Portal_EntityFlood - -The entity flood determines which areas are -"outside" on the map, which are then filled in. -Flowing from side s to side !s -=============== -*/ -qboolean Portal_EntityFlood (portal_t *p, int s) -{ - if (p->nodes[0]->planenum != PLANENUM_LEAF - || p->nodes[1]->planenum != PLANENUM_LEAF) - Error ("Portal_EntityFlood: not a leaf"); - - // can never cross to a solid - if ( (p->nodes[0]->contents & CONTENTS_SOLID) - || (p->nodes[1]->contents & CONTENTS_SOLID) ) - return false; - - // can flood through everything else - return true; -} - - -//============================================================================= - -int c_tinyportals; - -/* -============= -AddPortalToNodes -============= -*/ -void AddPortalToNodes (portal_t *p, node_t *front, node_t *back) -{ - if (p->nodes[0] || p->nodes[1]) - Error ("AddPortalToNode: allready included"); - - p->nodes[0] = front; - p->next[0] = front->portals; - front->portals = p; - - p->nodes[1] = back; - p->next[1] = back->portals; - back->portals = p; -} - - -/* -============= -RemovePortalFromNode -============= -*/ -void RemovePortalFromNode (portal_t *portal, node_t *l) -{ - portal_t **pp, *t; - -// remove reference to the current portal - pp = &l->portals; - while (1) - { - t = *pp; - if (!t) - Error ("RemovePortalFromNode: portal not in leaf"); - - if ( t == portal ) - break; - - if (t->nodes[0] == l) - pp = &t->next[0]; - else if (t->nodes[1] == l) - pp = &t->next[1]; - else - Error ("RemovePortalFromNode: portal not bounding leaf"); - } - - if (portal->nodes[0] == l) - { - *pp = portal->next[0]; - portal->nodes[0] = NULL; - } - else if (portal->nodes[1] == l) - { - *pp = portal->next[1]; - portal->nodes[1] = NULL; - } -} - -//============================================================================ - -void PrintPortal (portal_t *p) -{ - int i; - winding_t *w; - - w = p->winding; - for (i=0 ; inumpoints ; i++) - Sys_Printf ("(%5.0f,%5.0f,%5.0f)\n",w->p[i][0] - , w->p[i][1], w->p[i][2]); -} - -/* -================ -MakeHeadnodePortals - -The created portals will face the global outside_node -================ -*/ -#define SIDESPACE 8 -void MakeHeadnodePortals (tree_t *tree) -{ - vec3_t bounds[2]; - int i, j, n; - portal_t *p, *portals[6]; - plane_t bplanes[6], *pl; - node_t *node; - - node = tree->headnode; - -// pad with some space so there will never be null volume leafs - for (i=0 ; i<3 ; i++) - { - bounds[0][i] = tree->mins[i] - SIDESPACE; - bounds[1][i] = tree->maxs[i] + SIDESPACE; - } - - tree->outside_node.planenum = PLANENUM_LEAF; - tree->outside_node.brushlist = NULL; - tree->outside_node.portals = NULL; - tree->outside_node.contents = 0; - - for (i=0 ; i<3 ; i++) - for (j=0 ; j<2 ; j++) - { - n = j*3 + i; - - p = AllocPortal (); - portals[n] = p; - - pl = &bplanes[n]; - memset (pl, 0, sizeof(*pl)); - if (j) - { - pl->normal[i] = -1; - pl->dist = -bounds[j][i]; - } - else - { - pl->normal[i] = 1; - pl->dist = bounds[j][i]; - } - p->plane = *pl; - p->winding = BaseWindingForPlane (pl->normal, pl->dist); - AddPortalToNodes (p, node, &tree->outside_node); - } - -// clip the basewindings by all the other planes - for (i=0 ; i<6 ; i++) - { - for (j=0 ; j<6 ; j++) - { - if (j == i) - continue; - ChopWindingInPlace (&portals[i]->winding, bplanes[j].normal, bplanes[j].dist, ON_EPSILON); - } - } -} - -//=================================================== - - -/* -================ -BaseWindingForNode -================ -*/ -#define BASE_WINDING_EPSILON 0.001 -#define SPLIT_WINDING_EPSILON 0.001 - -winding_t *BaseWindingForNode (node_t *node) -{ - winding_t *w; - node_t *n; - plane_t *plane; - vec3_t normal; - vec_t dist; - - w = BaseWindingForPlane (mapplanes[node->planenum].normal - , mapplanes[node->planenum].dist); - - // clip by all the parents - for (n=node->parent ; n && w ; ) - { - plane = &mapplanes[n->planenum]; - - if (n->children[0] == node) - { // take front - ChopWindingInPlace (&w, plane->normal, plane->dist, BASE_WINDING_EPSILON); - } - else - { // take back - VectorSubtract (vec3_origin, plane->normal, normal); - dist = -plane->dist; - ChopWindingInPlace (&w, normal, dist, BASE_WINDING_EPSILON); - } - node = n; - n = n->parent; - } - - return w; -} - -//============================================================ - -qboolean WindingIsTiny (winding_t *w); - -/* -================== -MakeNodePortal - -create the new portal by taking the full plane winding for the cutting plane -and clipping it by all of parents of this node -================== -*/ -void MakeNodePortal (node_t *node) -{ - portal_t *new_portal, *p; - winding_t *w; - vec3_t normal; - float dist; - int side; - - w = BaseWindingForNode (node); - - // clip the portal by all the other portals in the node - for (p = node->portals ; p && w; p = p->next[side]) - { - if (p->nodes[0] == node) - { - side = 0; - VectorCopy (p->plane.normal, normal); - dist = p->plane.dist; - } - else if (p->nodes[1] == node) - { - side = 1; - VectorSubtract (vec3_origin, p->plane.normal, normal); - dist = -p->plane.dist; - } - else - Error ("CutNodePortals_r: mislinked portal"); - - ChopWindingInPlace (&w, normal, dist, 0.1); - } - - if (!w) - { - return; - } - - if (WindingIsTiny (w)) - { - c_tinyportals++; - FreeWinding (w); - return; - } - - - new_portal = AllocPortal (); - new_portal->plane = mapplanes[node->planenum]; - new_portal->onnode = node; - new_portal->winding = w; - AddPortalToNodes (new_portal, node->children[0], node->children[1]); -} - - -/* -============== -SplitNodePortals - -Move or split the portals that bound node so that the node's -children have portals instead of node. -============== -*/ -void SplitNodePortals (node_t *node) -{ - portal_t *p, *next_portal, *new_portal; - node_t *f, *b, *other_node; - int side; - plane_t *plane; - winding_t *frontwinding, *backwinding; - - plane = &mapplanes[node->planenum]; - f = node->children[0]; - b = node->children[1]; - - for (p = node->portals ; p ; p = next_portal) - { - if (p->nodes[0] == node) - side = 0; - else if (p->nodes[1] == node) - side = 1; - else - Error ("CutNodePortals_r: mislinked portal"); - next_portal = p->next[side]; - - other_node = p->nodes[!side]; - RemovePortalFromNode (p, p->nodes[0]); - RemovePortalFromNode (p, p->nodes[1]); - -// -// cut the portal into two portals, one on each side of the cut plane -// - ClipWindingEpsilon (p->winding, plane->normal, plane->dist, - SPLIT_WINDING_EPSILON, &frontwinding, &backwinding); - - if (frontwinding && WindingIsTiny(frontwinding)) - { - FreeWinding (frontwinding); - frontwinding = NULL; - c_tinyportals++; - } - - if (backwinding && WindingIsTiny(backwinding)) - { - FreeWinding (backwinding); - backwinding = NULL; - c_tinyportals++; - } - - if (!frontwinding && !backwinding) - { // tiny windings on both sides - continue; - } - - if (!frontwinding) - { - FreeWinding (backwinding); - if (side == 0) - AddPortalToNodes (p, b, other_node); - else - AddPortalToNodes (p, other_node, b); - continue; - } - if (!backwinding) - { - FreeWinding (frontwinding); - if (side == 0) - AddPortalToNodes (p, f, other_node); - else - AddPortalToNodes (p, other_node, f); - continue; - } - - // the winding is split - new_portal = AllocPortal (); - *new_portal = *p; - new_portal->winding = backwinding; - FreeWinding (p->winding); - p->winding = frontwinding; - - if (side == 0) - { - AddPortalToNodes (p, f, other_node); - AddPortalToNodes (new_portal, b, other_node); - } - else - { - AddPortalToNodes (p, other_node, f); - AddPortalToNodes (new_portal, other_node, b); - } - } - - node->portals = NULL; -} - - -/* -================ -CalcNodeBounds -================ -*/ -void CalcNodeBounds (node_t *node) -{ - portal_t *p; - int s; - int i; - - // calc mins/maxs for both leafs and nodes - ClearBounds (node->mins, node->maxs); - for (p = node->portals ; p ; p = p->next[s]) - { - s = (p->nodes[1] == node); - for (i=0 ; iwinding->numpoints ; i++) - AddPointToBounds (p->winding->p[i], node->mins, node->maxs); - } -} - - -/* -================== -MakeTreePortals_r -================== -*/ -void MakeTreePortals_r (node_t *node) -{ - int i; - - CalcNodeBounds (node); - if (node->mins[0] >= node->maxs[0]) - { - Sys_Printf ("WARNING: node without a volume\n"); - } - - for (i=0 ; i<3 ; i++) - { - if (node->mins[i] < -8000 || node->maxs[i] > 8000) - { - Sys_Printf ("WARNING: node with unbounded volume\n"); - break; - } - } - if (node->planenum == PLANENUM_LEAF) - return; - - MakeNodePortal (node); - SplitNodePortals (node); - - MakeTreePortals_r (node->children[0]); - MakeTreePortals_r (node->children[1]); -} - -/* -================== -MakeTreePortals -================== -*/ -void MakeTreePortals (tree_t *tree) -{ - MakeHeadnodePortals (tree); - MakeTreePortals_r (tree->headnode); -} - -/* -========================================================= - -FLOOD ENTITIES - -========================================================= -*/ - -/* -============= -FloodPortals_r -============= -*/ -void FloodPortals_r (node_t *node, int dist) -{ - portal_t *p; - int s; - - node->occupied = dist; - - for (p=node->portals ; p ; p = p->next[s]) - { - s = (p->nodes[1] == node); - - if (p->nodes[!s]->occupied) - continue; - - if (!Portal_EntityFlood (p, s)) - continue; - - FloodPortals_r (p->nodes[!s], dist+1); - } -} - -/* -============= -PlaceOccupant -============= -*/ -qboolean PlaceOccupant (node_t *headnode, vec3_t origin, entity_t *occupant) -{ - node_t *node; - vec_t d; - plane_t *plane; - - // find the leaf to start in - node = headnode; - while (node->planenum != PLANENUM_LEAF) - { - plane = &mapplanes[node->planenum]; - d = DotProduct (origin, plane->normal) - plane->dist; - if (d >= 0) - node = node->children[0]; - else - node = node->children[1]; - } - - if (node->contents == CONTENTS_SOLID) - return false; - node->occupant = occupant; - - FloodPortals_r (node, 1); - - return true; -} - -/* -============= -FloodEntities - -Marks all nodes that can be reached by entites -============= -*/ -qboolean FloodEntities (tree_t *tree) -{ - int i; - vec3_t origin; - char *cl; - qboolean inside; - node_t *headnode; - - headnode = tree->headnode; - Sys_FPrintf( SYS_VRB, "--- FloodEntities ---\n"); - inside = false; - tree->outside_node.occupied = 0; - - for (i=1 ; ioutside_node.occupied) - { - Sys_FPrintf( SYS_VRB, "entity reached from outside -- no filling\n"); - } - - return (qboolean)(inside && !tree->outside_node.occupied); -} - -/* -========================================================= - -FLOOD AREAS - -========================================================= -*/ - -int c_areas; - -/* -============= -FloodAreas_r -============= -*/ -void FloodAreas_r (node_t *node) -{ - portal_t *p; - int s; - bspbrush_t *b; - entity_t *e; - - if (node->contents == CONTENTS_AREAPORTAL) - { - // this node is part of an area portal - b = node->brushlist; - e = &entities[b->original->entitynum]; - - // if the current area has allready touched this - // portal, we are done - if (e->portalareas[0] == c_areas || e->portalareas[1] == c_areas) - return; - - // note the current area as bounding the portal - if (e->portalareas[1]) - { - Sys_Printf ("WARNING: areaportal entity %i touches > 2 areas\n", b->original->entitynum); - return; - } - if (e->portalareas[0]) - e->portalareas[1] = c_areas; - else - e->portalareas[0] = c_areas; - - return; - } - - if (node->area) - return; // allready got it - node->area = c_areas; - - for (p=node->portals ; p ; p = p->next[s]) - { - s = (p->nodes[1] == node); -#if 0 - if (p->nodes[!s]->occupied) - continue; -#endif - if (!Portal_EntityFlood (p, s)) - continue; - - FloodAreas_r (p->nodes[!s]); - } -} - -/* -============= -FindAreas_r - -Just decend the tree, and for each node that hasn't had an -area set, flood fill out from there -============= -*/ -void FindAreas_r (node_t *node) -{ - if (node->planenum != PLANENUM_LEAF) - { - FindAreas_r (node->children[0]); - FindAreas_r (node->children[1]); - return; - } - - if (node->area) - return; // allready got it - - if (node->contents & CONTENTS_SOLID) - return; - - if (!node->occupied) - return; // not reachable by entities - - // area portals are allways only flooded into, never - // out of - if (node->contents == CONTENTS_AREAPORTAL) - return; - - c_areas++; - FloodAreas_r (node); -} - -/* -============= -SetAreaPortalAreas_r - -Just decend the tree, and for each node that hasn't had an -area set, flood fill out from there -============= -*/ -void SetAreaPortalAreas_r (node_t *node) -{ - bspbrush_t *b; - entity_t *e; - - if (node->planenum != PLANENUM_LEAF) - { - SetAreaPortalAreas_r (node->children[0]); - SetAreaPortalAreas_r (node->children[1]); - return; - } - - if (node->contents == CONTENTS_AREAPORTAL) - { - if (node->area) - return; // allready set - - b = node->brushlist; - e = &entities[b->original->entitynum]; - node->area = e->portalareas[0]; - if (!e->portalareas[1]) - { - Sys_Printf ("WARNING: areaportal entity %i doesn't touch two areas\n", b->original->entitynum); - return; - } - } -} - -/* -============= -EmitAreaPortals - -============= -*/ -void EmitAreaPortals (node_t *headnode) -{ - int i, j; - entity_t *e; - dareaportal_t *dp; - - if (c_areas > MAX_MAP_AREAS) - Error ("MAX_MAP_AREAS"); - numareas = c_areas+1; - numareaportals = 1; // leave 0 as an error - - for (i=1 ; i<=c_areas ; i++) - { - dareas[i].firstareaportal = numareaportals; - for (j=0 ; jareaportalnum) - continue; - dp = &dareaportals[numareaportals]; - if (e->portalareas[0] == i) - { - dp->portalnum = e->areaportalnum; - dp->otherarea = e->portalareas[1]; - numareaportals++; - } - else if (e->portalareas[1] == i) - { - dp->portalnum = e->areaportalnum; - dp->otherarea = e->portalareas[0]; - numareaportals++; - } - } - dareas[i].numareaportals = numareaportals - dareas[i].firstareaportal; - } - - Sys_FPrintf( SYS_VRB, "%5i numareas\n", numareas); - Sys_FPrintf( SYS_VRB, "%5i numareaportals\n", numareaportals); -} - -/* -============= -FloodAreas - -Mark each leaf with an area, bounded by CONTENTS_AREAPORTAL -============= -*/ -void FloodAreas (tree_t *tree) -{ - Sys_FPrintf( SYS_VRB, "--- FloodAreas ---\n"); - FindAreas_r (tree->headnode); - SetAreaPortalAreas_r (tree->headnode); - Sys_FPrintf( SYS_VRB, "%5i areas\n", c_areas); -} - -//====================================================== - -int c_outside; -int c_inside; -int c_solid; - -void FillOutside_r (node_t *node) -{ - if (node->planenum != PLANENUM_LEAF) - { - FillOutside_r (node->children[0]); - FillOutside_r (node->children[1]); - return; - } - - // anything not reachable by an entity - // can be filled away - if (!node->occupied) - { - if (node->contents != CONTENTS_SOLID) - { - c_outside++; - node->contents = CONTENTS_SOLID; - } - else - c_solid++; - } - else - c_inside++; - -} - -/* -============= -FillOutside - -Fill all nodes that can't be reached by entities -============= -*/ -void FillOutside (node_t *headnode) -{ - c_outside = 0; - c_inside = 0; - c_solid = 0; - Sys_FPrintf( SYS_VRB, "--- FillOutside ---\n"); - FillOutside_r (headnode); - Sys_FPrintf( SYS_VRB, "%5i solid leafs\n", c_solid); - Sys_FPrintf( SYS_VRB, "%5i leafs filled\n", c_outside); - Sys_FPrintf( SYS_VRB, "%5i inside leafs\n", c_inside); -} - - -//============================================================== - -/* -============ -FindPortalSide - -Finds a brush side to use for texturing the given portal -============ -*/ -void FindPortalSide (portal_t *p) -{ - int viscontents; - bspbrush_t *bb; - mapbrush_t *brush; - node_t *n; - int i,j; - int planenum; - side_t *side, *bestside; - float dot, bestdot; - plane_t *p1, *p2; - - // decide which content change is strongest - // solid > lava > water, etc - viscontents = VisibleContents (p->nodes[0]->contents ^ p->nodes[1]->contents); - if (!viscontents) - return; - - planenum = p->onnode->planenum; - bestside = NULL; - bestdot = 0; - - for (j=0 ; j<2 ; j++) - { - n = p->nodes[j]; - p1 = &mapplanes[p->onnode->planenum]; - for (bb=n->brushlist ; bb ; bb=bb->next) - { - brush = bb->original; - if ( !(brush->contents & viscontents) ) - continue; - for (i=0 ; inumsides ; i++) - { - side = &brush->original_sides[i]; - if (side->bevel) - continue; - if (side->texinfo == TEXINFO_NODE) - continue; // non-visible - if ((side->planenum&~1) == planenum) - { // exact match - bestside = &brush->original_sides[i]; - goto gotit; - } - // see how close the match is - p2 = &mapplanes[side->planenum&~1]; - dot = DotProduct (p1->normal, p2->normal); - if (dot > bestdot) - { - bestdot = dot; - bestside = side; - } - } - } - } - -gotit: - if (!bestside) - Sys_FPrintf( SYS_VRB, "WARNING: side not found for portal\n"); - - p->sidefound = true; - p->side = bestside; -} - - -/* -=============== -MarkVisibleSides_r - -=============== -*/ -void MarkVisibleSides_r (node_t *node) -{ - portal_t *p; - int s; - - if (node->planenum != PLANENUM_LEAF) - { - MarkVisibleSides_r (node->children[0]); - MarkVisibleSides_r (node->children[1]); - return; - } - - // empty leafs are never boundary leafs - if (!node->contents) - return; - - // see if there is a visible face - for (p=node->portals ; p ; p = p->next[!s]) - { - s = (p->nodes[0] == node); - if (!p->onnode) - continue; // edge of world - if (!p->sidefound) - FindPortalSide (p); - if (p->side) - p->side->visible = true; - } - -} - -/* -============= -MarkVisibleSides - -============= -*/ -void MarkVisibleSides (tree_t *tree, int startbrush, int endbrush) -{ - int i, j; - mapbrush_t *mb; - int numsides; - - Sys_FPrintf( SYS_VRB, "--- MarkVisibleSides ---\n"); - - // clear all the visible flags - for (i=startbrush ; inumsides; - for (j=0 ; joriginal_sides[j].visible = false; - } - - // set visible flags on the sides that are used by portals - MarkVisibleSides_r (tree->headnode); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/prtfile.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/prtfile.c deleted file mode 100644 index 790db065..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/prtfile.c +++ /dev/null @@ -1,286 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -/* -============================================================================== - -PORTAL FILE GENERATION - -Save out name.prt for qvis to read -============================================================================== -*/ - - -#define PORTALFILE "PRT1" - -FILE *pf; -int num_visclusters; // clusters the player can be in -int num_visportals; - -void WriteFloat (FILE *f, vec_t v) -{ - if ( fabs(v - Q_rint(v)) < 0.001 ) - fprintf (f,"%i ",(int)Q_rint(v)); - else - fprintf (f,"%f ",v); -} - -/* -================= -WritePortalFile_r -================= -*/ -void WritePortalFile_r (node_t *node) -{ - int i, s; - portal_t *p; - winding_t *w; - vec3_t normal; - vec_t dist; - - // decision node - if (node->planenum != PLANENUM_LEAF && !node->detail_seperator) - { - WritePortalFile_r (node->children[0]); - WritePortalFile_r (node->children[1]); - return; - } - - if (node->contents & CONTENTS_SOLID) - return; - - for (p = node->portals ; p ; p=p->next[s]) - { - w = p->winding; - s = (p->nodes[1] == node); - if (w && p->nodes[0] == node) - { - if (!Portal_VisFlood (p)) - continue; - // write out to the file - - // sometimes planes get turned around when they are very near - // the changeover point between different axis. interpret the - // plane the same way vis will, and flip the side orders if needed - // FIXME: is this still relevent? - WindingPlane (w, normal, &dist); - if ( DotProduct (p->plane.normal, normal) < 0.99 ) - { // backwards... - fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[1]->cluster, p->nodes[0]->cluster); - } - else - fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[0]->cluster, p->nodes[1]->cluster); - for (i=0 ; inumpoints ; i++) - { - fprintf (pf,"("); - WriteFloat (pf, w->p[i][0]); - WriteFloat (pf, w->p[i][1]); - WriteFloat (pf, w->p[i][2]); - fprintf (pf,") "); - } - fprintf (pf,"\n"); - } - } - -} - -/* -================ -FillLeafNumbers_r - -All of the leafs under node will have the same cluster -================ -*/ -void FillLeafNumbers_r (node_t *node, int num) -{ - if (node->planenum == PLANENUM_LEAF) - { - if (node->contents & CONTENTS_SOLID) - node->cluster = -1; - else - node->cluster = num; - return; - } - node->cluster = num; - FillLeafNumbers_r (node->children[0], num); - FillLeafNumbers_r (node->children[1], num); -} - -/* -================ -NumberLeafs_r -================ -*/ -void NumberLeafs_r (node_t *node) -{ - portal_t *p; - - if (node->planenum != PLANENUM_LEAF && !node->detail_seperator) - { // decision node - node->cluster = -99; - NumberLeafs_r (node->children[0]); - NumberLeafs_r (node->children[1]); - return; - } - - // either a leaf or a detail cluster - - if ( node->contents & CONTENTS_SOLID ) - { // solid block, viewpoint never inside - node->cluster = -1; - return; - } - - FillLeafNumbers_r (node, num_visclusters); - num_visclusters++; - - // count the portals - for (p = node->portals ; p ; ) - { - if (p->nodes[0] == node) // only write out from first leaf - { - if (Portal_VisFlood (p)) - num_visportals++; - p = p->next[0]; - } - else - p = p->next[1]; - } - -} - - -/* -================ -CreateVisPortals_r -================ -*/ -void CreateVisPortals_r (node_t *node) -{ - // stop as soon as we get to a detail_seperator, which - // means that everything below is in a single cluster - if (node->planenum == PLANENUM_LEAF || node->detail_seperator ) - return; - - MakeNodePortal (node); - SplitNodePortals (node); - - CreateVisPortals_r (node->children[0]); - CreateVisPortals_r (node->children[1]); -} - -/* -================ -FinishVisPortals_r -================ -*/ -void FinishVisPortals2_r (node_t *node) -{ - if (node->planenum == PLANENUM_LEAF) - return; - - MakeNodePortal (node); - SplitNodePortals (node); - - FinishVisPortals2_r (node->children[0]); - FinishVisPortals2_r (node->children[1]); -} - -void FinishVisPortals_r (node_t *node) -{ - if (node->planenum == PLANENUM_LEAF) - return; - - if (node->detail_seperator) - { - FinishVisPortals2_r (node); - return; - } - - FinishVisPortals_r (node->children[0]); - FinishVisPortals_r (node->children[1]); -} - - -int clusterleaf; -void SaveClusters_r (node_t *node) -{ - if (node->planenum == PLANENUM_LEAF) - { - dleafs[clusterleaf++].cluster = node->cluster; - return; - } - SaveClusters_r (node->children[0]); - SaveClusters_r (node->children[1]); -} - -/* -================ -WritePortalFile -================ -*/ -void WritePortalFile (tree_t *tree) -{ - char filename[1024]; - node_t *headnode; - - Sys_FPrintf( SYS_VRB, "--- WritePortalFile ---\n"); - - headnode = tree->headnode; - num_visclusters = 0; - num_visportals = 0; - - FreeTreePortals_r (headnode); - - MakeHeadnodePortals (tree); - - CreateVisPortals_r (headnode); - -// set the cluster field in every leaf and count the total number of portals - - NumberLeafs_r (headnode); - -// write the file - sprintf (filename, "%s.prt", source); - Sys_Printf ("writing %s\n", filename); - pf = fopen (filename, "w"); - if (!pf) - Error ("Error opening %s", filename); - - fprintf (pf, "%s\n", PORTALFILE); - fprintf (pf, "%i\n", num_visclusters); - fprintf (pf, "%i\n", num_visportals); - - Sys_FPrintf( SYS_VRB, "%5i visclusters\n", num_visclusters); - Sys_FPrintf( SYS_VRB, "%5i visportals\n", num_visportals); - - WritePortalFile_r (headnode); - - fclose (pf); - - // we need to store the clusters out now because ordering - // issues made us do this after writebsp... - clusterleaf = 1; - SaveClusters_r (headnode); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/q2map.h b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/q2map.h deleted file mode 100644 index 331b35df..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/q2map.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// q2map.h - -/* platform-specific */ -#if defined( __linux__ ) || defined( __APPLE__ ) - #define Q_UNIX -#endif - -#ifdef Q_UNIX - #include - #include - #include -#endif - -#ifdef WIN32 - #include -#endif - -#include - -#include "cmdlib.h" -#include "mathlib.h" -#include "scriplib.h" -#include "polylib.h" -#include "q2_threads.h" -#include "bspfile.h" -#include "inout.h" - -int BSP_Main (); -int VIS_Main (); -int RAD_Main (); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qbsp.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qbsp.c deleted file mode 100644 index 2809390c..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qbsp.c +++ /dev/null @@ -1,426 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// csg4.c - -#include "qbsp.h" - -extern float subdivide_size; - -char source[1024]; -char name[1024]; - -vec_t microvolume = 1.0; -qboolean noprune; -qboolean glview; -qboolean nodetail; -qboolean fulldetail; -qboolean onlyents; -qboolean nomerge; -qboolean nowater; -qboolean nofill; -qboolean nocsg; -qboolean noweld; -qboolean noshare; -qboolean nosubdiv; -qboolean notjunc; -qboolean noopt; -qboolean leaktest; -qboolean verboseentities; - -char outbase[32]; - -int block_xl = -8, block_xh = 7, block_yl = -8, block_yh = 7; - -int entity_num; - - -node_t *block_nodes[10][10]; - - -/* -============ -BlockTree - -============ -*/ -node_t *BlockTree (int xl, int yl, int xh, int yh) -{ - node_t *node; - vec3_t normal; - float dist; - int mid; - - if (xl == xh && yl == yh) - { - node = block_nodes[xl+5][yl+5]; - if (!node) - { // return an empty leaf - node = AllocNode (); - node->planenum = PLANENUM_LEAF; - node->contents = 0; //CONTENTS_SOLID; - return node; - } - return node; - } - - // create a seperator along the largest axis - node = AllocNode (); - - if (xh - xl > yh - yl) - { // split x axis - mid = xl + (xh-xl)/2 + 1; - normal[0] = 1; - normal[1] = 0; - normal[2] = 0; - dist = mid*1024; - node->planenum = FindFloatPlane (normal, dist); - node->children[0] = BlockTree ( mid, yl, xh, yh); - node->children[1] = BlockTree ( xl, yl, mid-1, yh); - } - else - { - mid = yl + (yh-yl)/2 + 1; - normal[0] = 0; - normal[1] = 1; - normal[2] = 0; - dist = mid*1024; - node->planenum = FindFloatPlane (normal, dist); - node->children[0] = BlockTree ( xl, mid, xh, yh); - node->children[1] = BlockTree ( xl, yl, xh, mid-1); - } - - return node; -} - -/* -============ -ProcessBlock_Thread - -============ -*/ -int brush_start, brush_end; -void ProcessBlock_Thread (int blocknum) -{ - int xblock, yblock; - vec3_t mins, maxs; - bspbrush_t *brushes; - tree_t *tree; - node_t *node; - - yblock = block_yl + blocknum / (block_xh-block_xl+1); - xblock = block_xl + blocknum % (block_xh-block_xl+1); - - Sys_FPrintf( SYS_VRB, "############### block %2i,%2i ###############\n", xblock, yblock); - - mins[0] = xblock*1024; - mins[1] = yblock*1024; - mins[2] = -4096; - maxs[0] = (xblock+1)*1024; - maxs[1] = (yblock+1)*1024; - maxs[2] = 4096; - - // the makelist and chopbrushes could be cached between the passes... - brushes = MakeBspBrushList (brush_start, brush_end, mins, maxs); - if (!brushes) - { - node = AllocNode (); - node->planenum = PLANENUM_LEAF; - node->contents = CONTENTS_SOLID; - block_nodes[xblock+5][yblock+5] = node; - return; - } - - if (!nocsg) - brushes = ChopBrushes (brushes); - - tree = BrushBSP (brushes, mins, maxs); - - block_nodes[xblock+5][yblock+5] = tree->headnode; -} - -/* -============ -ProcessWorldModel - -============ -*/ -void ProcessWorldModel (void) -{ - entity_t *e; - tree_t *tree; - qboolean leaked; - qboolean optimize; - xmlNodePtr polyline, leaknode; - char level[ 2 ]; - - e = &entities[entity_num]; - - brush_start = e->firstbrush; - brush_end = brush_start + e->numbrushes; - leaked = false; - - // - // perform per-block operations - // - if (block_xh * 1024 > map_maxs[0]) - block_xh = floor(map_maxs[0]/1024.0); - if ( (block_xl+1) * 1024 < map_mins[0]) - block_xl = floor(map_mins[0]/1024.0); - if (block_yh * 1024 > map_maxs[1]) - block_yh = floor(map_maxs[1]/1024.0); - if ( (block_yl+1) * 1024 < map_mins[1]) - block_yl = floor(map_mins[1]/1024.0); - - if (block_xl <-4) - block_xl = -4; - if (block_yl <-4) - block_yl = -4; - if (block_xh > 3) - block_xh = 3; - if (block_yh > 3) - block_yh = 3; - - for (optimize = false ; optimize <= true ; optimize++) - { - Sys_FPrintf( SYS_VRB, "--------------------------------------------\n"); - - RunThreadsOnIndividual ((block_xh-block_xl+1)*(block_yh-block_yl+1), - !verbose, ProcessBlock_Thread); - - // - // build the division tree - // oversizing the blocks guarantees that all the boundaries - // will also get nodes. - // - - Sys_FPrintf( SYS_VRB, "--------------------------------------------\n"); - - tree = AllocTree (); - tree->headnode = BlockTree (block_xl-1, block_yl-1, block_xh+1, block_yh+1); - - tree->mins[0] = (block_xl)*1024; - tree->mins[1] = (block_yl)*1024; - tree->mins[2] = map_mins[2] - 8; - - tree->maxs[0] = (block_xh+1)*1024; - tree->maxs[1] = (block_yh+1)*1024; - tree->maxs[2] = map_maxs[2] + 8; - - // - // perform the global operations - // - MakeTreePortals (tree); - - if (FloodEntities (tree)) - FillOutside (tree->headnode); - else - { - - Sys_FPrintf( SYS_NOXML, "**********************\n" ); - Sys_FPrintf( SYS_NOXML, "******* leaked *******\n" ); - Sys_FPrintf( SYS_NOXML, "**********************\n" ); - polyline = LeakFile( tree ); - leaknode = xmlNewNode( NULL, "message" ); - xmlNodeSetContent( leaknode, "MAP LEAKED\n" ); - xmlAddChild( leaknode, polyline ); - level[0] = (int) '0' + SYS_ERR; - level[1] = 0; - xmlSetProp( leaknode, "level", (char*) &level ); - xml_SendNode( leaknode ); - if( leaktest ) - { - Sys_Printf ("--- MAP LEAKED, ABORTING LEAKTEST ---\n"); - exit( 0 ); - } - leaked = true; -/* - Sys_Printf ("**** leaked ****\n"); - leaked = true; - LeakFile (tree); - if (leaktest) - { - Sys_Printf ("--- MAP LEAKED ---\n"); - exit (0); - } */ - } - - MarkVisibleSides (tree, brush_start, brush_end); - if (noopt || leaked) - break; - if (!optimize) - { - FreeTree (tree); - } - } - - FloodAreas (tree); - if (glview) - WriteGLView (tree, source); - MakeFaces (tree->headnode); - FixTjuncs (tree->headnode); - - if (!noprune) - PruneNodes (tree->headnode); - - WriteBSP (tree->headnode); - - if (!leaked) - WritePortalFile (tree); - - FreeTree (tree); -} - -/* -============ -ProcessSubModel - -============ -*/ -void ProcessSubModel (void) -{ - entity_t *e; - int start, end; - tree_t *tree; - bspbrush_t *list; - vec3_t mins, maxs; - - e = &entities[entity_num]; - - start = e->firstbrush; - end = start + e->numbrushes; - - mins[0] = mins[1] = mins[2] = -4096; - maxs[0] = maxs[1] = maxs[2] = 4096; - list = MakeBspBrushList (start, end, mins, maxs); - if (!nocsg) - list = ChopBrushes (list); - tree = BrushBSP (list, mins, maxs); - MakeTreePortals (tree); - MarkVisibleSides (tree, start, end); - MakeFaces (tree->headnode); - FixTjuncs (tree->headnode); - WriteBSP (tree->headnode); - FreeTree (tree); -} - -/* -============ -ProcessModels -============ -*/ -void ProcessModels (void) -{ - BeginBSPFile (); - - for (entity_num=0 ; entity_num< num_entities ; entity_num++) - { - if (!entities[entity_num].numbrushes) - continue; - - Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", nummodels); - BeginModel (); - if (entity_num == 0) - ProcessWorldModel (); - else - ProcessSubModel (); - EndModel (); - - //if (!verboseentities) - // verbose = false; // don't bother printing submodels - } - - EndBSPFile (); -} - - -/* -============ -main -============ -*/ -int BSP_Main () -{ - double start, end; - char path[1024]; - int total_bsp_time; - - Sys_Printf ("\n----- BSP ----\n\n"); - - - start = I_FloatTime (); - - ThreadSetDefault (); - SetQdirFromPath (mapname); - - strcpy (source, ExpandArg (mapname)); - StripExtension (source); - - // delete portal and line files - sprintf (path, "%s.prt", source); - remove (path); - sprintf (path, "%s.lin", source); - remove (path); - - strcpy (name, ExpandArg (mapname)); - DefaultExtension (name, ".map"); // might be .reg - - // - // if onlyents, just grab the entites and resave - // - if (onlyents) - { - char out[1024]; - - sprintf (out, "%s.bsp", source); - LoadBSPFile (out); - num_entities = 0; - - LoadMapFile (name); - SetModelNumbers (); - SetLightStyles (); - - UnparseEntities (); - - WriteBSPFile (out); - } - else - { - // - // start from scratch - // - LoadMapFile (name); - SetModelNumbers (); - SetLightStyles (); - - ProcessModels (); - } - - end = I_FloatTime (); - total_bsp_time = (int) (end-start); - Sys_Printf("\nBSP Time: "); - if ( total_bsp_time > 59 ) - Sys_Printf("%d Minutes ", total_bsp_time/60 ); - Sys_Printf( "%d Seconds\n", total_bsp_time%60 ); - - - return 0; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qbsp.h b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qbsp.h deleted file mode 100644 index cc5c822a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qbsp.h +++ /dev/null @@ -1,390 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* Files: - -brushbsp.c -csg.c -faces.c -gldraw.c -glfile.c -leakfile.c -map.c -nodraw.c -portals.c -prtfile.c -qbsp3.c -textures.c -tree.c -writebsp.c - -*/ - -#include "cmdlib.h" -#include "mathlib.h" -#include "scriplib.h" -#include "polylib.h" -#include "q2_threads.h" -#include "bspfile.h" -#include "inout.h" - -#ifdef WIN32 - #ifdef NDEBUG // Don't show in a Release build - #pragma warning(disable : 4305) // truncate from double to float - #pragma warning(disable : 4244) // conversion from double to float - #pragma warning(disable : 4018) // signed/unsigned mismatch - #endif -#endif - -#define MAX_BRUSH_SIDES 128 -#define CLIP_EPSILON 0.1 - -#define BOGUS_RANGE 8192 - -#define TEXINFO_NODE -1 // side is allready on a node - -typedef struct plane_s -{ - vec3_t normal; - vec_t dist; - int type; - struct plane_s *hash_chain; -} plane_t; - -typedef struct -{ - vec_t shift[2]; - vec_t rotate; - vec_t scale[2]; - char name[32]; - int flags; - int value; -} brush_texture_t; - -typedef struct side_s -{ - int planenum; - int texinfo; - winding_t *winding; - struct side_s *original; // bspbrush_t sides will reference the mapbrush_t sides - int contents; // from miptex - int surf; // from miptex - qboolean visible; // choose visble planes first - qboolean tested; // this plane allready checked as a split - qboolean bevel; // don't ever use for bsp splitting -} side_t; - -typedef struct brush_s -{ - int entitynum; - int brushnum; - - int contents; - - vec3_t mins, maxs; - - int numsides; - side_t *original_sides; -} mapbrush_t; - -#define PLANENUM_LEAF -1 - -#define MAXEDGES 20 - -typedef struct face_s -{ - struct face_s *next; // on node - - // the chain of faces off of a node can be merged or split, - // but each face_t along the way will remain in the chain - // until the entire tree is freed - struct face_s *merged; // if set, this face isn't valid anymore - struct face_s *split[2]; // if set, this face isn't valid anymore - - struct portal_s *portal; - int texinfo; - int planenum; - int contents; // faces in different contents can't merge - int outputnumber; - winding_t *w; - int numpoints; - qboolean badstartvert; // tjunctions cannot be fixed without a midpoint vertex - int vertexnums[MAXEDGES]; -} face_t; - - - -typedef struct bspbrush_s -{ - struct bspbrush_s *next; - vec3_t mins, maxs; - int side, testside; // side of node during construction - mapbrush_t *original; - int numsides; - side_t sides[6]; // variably sized -} bspbrush_t; - - - -#define MAX_NODE_BRUSHES 8 -typedef struct node_s -{ - // both leafs and nodes - int planenum; // -1 = leaf node - struct node_s *parent; - vec3_t mins, maxs; // valid after portalization - bspbrush_t *volume; // one for each leaf/node - - // nodes only - qboolean detail_seperator; // a detail brush caused the split - side_t *side; // the side that created the node - struct node_s *children[2]; - face_t *faces; - - // leafs only - bspbrush_t *brushlist; // fragments of all brushes in this leaf - int contents; // OR of all brush contents - int occupied; // 1 or greater can reach entity - entity_t *occupant; // for leak file testing - int cluster; // for portalfile writing - int area; // for areaportals - struct portal_s *portals; // also on nodes during construction -} node_t; - -typedef struct portal_s -{ - plane_t plane; - node_t *onnode; // NULL = outside box - node_t *nodes[2]; // [0] = front side of plane - struct portal_s *next[2]; - winding_t *winding; - - qboolean sidefound; // false if ->side hasn't been checked - side_t *side; // NULL = non-visible - face_t *face[2]; // output face in bsp file -} portal_t; - -typedef struct -{ - node_t *headnode; - node_t outside_node; - vec3_t mins, maxs; -} tree_t; - -extern int entity_num; - -extern plane_t mapplanes[MAX_MAP_PLANES]; -extern int nummapplanes; - -extern int nummapbrushes; -extern mapbrush_t mapbrushes[MAX_MAP_BRUSHES]; - -extern vec3_t map_mins, map_maxs; - -#define MAX_MAP_SIDES (MAX_MAP_BRUSHES*6) - -extern int nummapbrushsides; -extern side_t brushsides[MAX_MAP_SIDES]; - -extern qboolean noprune; -extern qboolean nodetail; -extern qboolean fulldetail; -extern qboolean nomerge; -extern qboolean nosubdiv; -extern qboolean nowater; -extern qboolean noweld; -extern qboolean noshare; -extern qboolean notjunc; - -extern vec_t microvolume; - -extern char outbase[32]; - -extern char source[1024]; - -void LoadMapFile (char *filename); -int FindFloatPlane (vec3_t normal, vec_t dist); - -//============================================================================= - -// textures.c - -typedef struct -{ - char name[64]; - int flags; - int value; - int contents; - char animname[64]; -} textureref_t; - -#define MAX_MAP_TEXTURES 1024 - -extern textureref_t textureref[MAX_MAP_TEXTURES]; - -int FindMiptex (char *name); - -int TexinfoForBrushTexture (plane_t *plane, brush_texture_t *bt, vec3_t origin); - -//============================================================================= - -void FindGCD (int *v); - -mapbrush_t *Brush_LoadEntity (entity_t *ent); -int PlaneTypeForNormal (vec3_t normal); -qboolean MakeBrushPlanes (mapbrush_t *b); -int FindIntPlane (int *inormal, int *iorigin); -void CreateBrush (int brushnum); - - -//============================================================================= - -// draw.c - -extern vec3_t draw_mins, draw_maxs; -extern qboolean drawflag; - -void Draw_ClearWindow (void); -void DrawWinding (winding_t *w); - -void GLS_BeginScene (void); -void GLS_Winding (winding_t *w, int code); -void GLS_EndScene (void); - -//============================================================================= - -// csg - -bspbrush_t *MakeBspBrushList (int startbrush, int endbrush, - vec3_t clipmins, vec3_t clipmaxs); -bspbrush_t *ChopBrushes (bspbrush_t *head); -bspbrush_t *InitialBrushList (bspbrush_t *list); -bspbrush_t *OptimizedBrushList (bspbrush_t *list); - -void WriteBrushMap (char *name, bspbrush_t *list); - -//============================================================================= - -// brushbsp - -void WriteBrushList (char *name, bspbrush_t *brush, qboolean onlyvis); - -bspbrush_t *CopyBrush (bspbrush_t *brush); - -void SplitBrush (bspbrush_t *brush, int planenum, - bspbrush_t **front, bspbrush_t **back); - -tree_t *AllocTree (void); -node_t *AllocNode (void); -bspbrush_t *AllocBrush (int numsides); -int CountBrushList (bspbrush_t *brushes); -void FreeBrush (bspbrush_t *brushes); -vec_t BrushVolume (bspbrush_t *brush); - -void BoundBrush (bspbrush_t *brush); -void FreeBrushList (bspbrush_t *brushes); - -tree_t *BrushBSP (bspbrush_t *brushlist, vec3_t mins, vec3_t maxs); - -//============================================================================= - -// portals.c - -int VisibleContents (int contents); - -void MakeHeadnodePortals (tree_t *tree); -void MakeNodePortal (node_t *node); -void SplitNodePortals (node_t *node); - -qboolean Portal_VisFlood (portal_t *p); - -qboolean FloodEntities (tree_t *tree); -void FillOutside (node_t *headnode); -void FloodAreas (tree_t *tree); -void MarkVisibleSides (tree_t *tree, int start, int end); -void FreePortal (portal_t *p); -void EmitAreaPortals (node_t *headnode); - -void MakeTreePortals (tree_t *tree); - -//============================================================================= - -// glfile.c - -void OutputWinding (winding_t *w, FILE *glview); -void WriteGLView (tree_t *tree, char *source); - -//============================================================================= - -// leakfile.c - -//void LeakFile (tree_t *tree); -xmlNodePtr LeakFile (tree_t *tree); - -//============================================================================= - -// prtfile.c - -void WritePortalFile (tree_t *tree); - -//============================================================================= - -// writebsp.c - -void SetModelNumbers (void); -void SetLightStyles (void); - -void BeginBSPFile (void); -void WriteBSP (node_t *headnode); -void EndBSPFile (void); -void BeginModel (void); -void EndModel (void); - -//============================================================================= - -// faces.c - -void MakeFaces (node_t *headnode); -void FixTjuncs (node_t *headnode); -int GetEdge2 (int v1, int v2, face_t *f); - -face_t *AllocFace (void); -void FreeFace (face_t *f); - -void MergeNodeFaces (node_t *node); - -//============================================================================= - -// tree.c - -void FreeTree (tree_t *tree); -void FreeTree_r (node_t *node); -void PrintTree_r (node_t *node, int depth); -void FreeTreePortals_r (node_t *node); -void PruneNodes_r (node_t *node); -void PruneNodes (node_t *node); - -//============================================================================= - -// externs - -extern char *mapname; -extern char game[64]; diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qrad.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qrad.c deleted file mode 100644 index e1744cdd..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qrad.c +++ /dev/null @@ -1,647 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// qrad.c - -#include "qrad.h" - - - -/* - -NOTES ------ - -every surface must be divided into at least two patches each axis - -*/ - -patch_t *face_patches[MAX_MAP_FACES]; -entity_t *face_entity[MAX_MAP_FACES]; -patch_t patches[MAX_PATCHES]; -unsigned num_patches; - -vec3_t radiosity[MAX_PATCHES]; // light leaving a patch -vec3_t illumination[MAX_PATCHES]; // light arriving at a patch - -vec3_t face_offset[MAX_MAP_FACES]; // for rotating bmodels -dplane_t backplanes[MAX_MAP_PLANES]; - -char inbase[32], outbase[32]; - -int fakeplanes; // created planes for origin offset - -int numbounce = 8; -qboolean extrasamples; - -float subdiv = 64; -qboolean dumppatches; - -void BuildLightmaps (void); -int TestLine (vec3_t start, vec3_t stop); - -int junk; - -float ambient = 0; -float maxlight = 196; - -float lightscale = 1.0; - -qboolean glview; - -qboolean nopvs; - -char source[1024]; - -float direct_scale = 0.4; -float entity_scale = 1.0; - -/* -=================================================================== - -MISC - -=================================================================== -*/ - - -/* -============= -MakeBackplanes -============= -*/ -void MakeBackplanes (void) -{ - int i; - - for (i=0 ; ichildren[i]; - if (j < 0) - leafparents[-j - 1] = nodenum; - else - MakeParents (j, nodenum); - } -} - - -/* -=================================================================== - -TRANSFER SCALES - -=================================================================== -*/ - -int PointInLeafnum (vec3_t point) -{ - int nodenum; - vec_t dist; - dnode_t *node; - dplane_t *plane; - - nodenum = 0; - while (nodenum >= 0) - { - node = &dnodes[nodenum]; - plane = &dplanes[node->planenum]; - dist = DotProduct (point, plane->normal) - plane->dist; - if (dist > 0) - nodenum = node->children[0]; - else - nodenum = node->children[1]; - } - - return -nodenum - 1; -} - - -dleaf_t *Rad_PointInLeaf (vec3_t point) -{ - int num; - - num = PointInLeafnum (point); - return &dleafs[num]; -} - - -qboolean PvsForOrigin (vec3_t org, byte *pvs) -{ - dleaf_t *leaf; - - if (!visdatasize) - { - memset (pvs, 255, (numleafs+7)/8 ); - return true; - } - - leaf = Rad_PointInLeaf (org); - if (leaf->cluster == -1) - return false; // in solid leaf - - DecompressVis (dvisdata + dvis->bitofs[leaf->cluster][DVIS_PVS], pvs); - return true; -} - - -/* -============= -MakeTransfers - -============= -*/ -int total_transfer; - -void MakeTransfers (int i) -{ - int j; - vec3_t delta; - vec_t dist, scale; - float trans; - int itrans; - patch_t *patch, *patch2; - float total; - dplane_t plane; - vec3_t origin; - float transfers[MAX_PATCHES], *all_transfers; - int s; - int itotal; - byte pvs[(MAX_MAP_LEAFS+7)/8]; - int cluster; - - patch = patches + i; - total = 0; - - VectorCopy (patch->origin, origin); - plane = *patch->plane; - - if (!PvsForOrigin (patch->origin, pvs)) - return; - - // find out which patch2s will collect light - // from patch - - all_transfers = transfers; - patch->numtransfers = 0; - for (j=0, patch2 = patches ; jcluster; - if (cluster == -1) - continue; - if ( ! ( pvs[cluster>>3] & (1<<(cluster&7)) ) ) - continue; // not in pvs - } - - // calculate vector - VectorSubtract (patch2->origin, origin, delta); - dist = VectorNormalize (delta, delta); - if (!dist) - continue; // should never happen - - // reletive angles - scale = DotProduct (delta, plane.normal); - scale *= -DotProduct (delta, patch2->plane->normal); - if (scale <= 0) - continue; - - // check exact tramsfer - if (TestLine_r (0, patch->origin, patch2->origin) ) - continue; - - trans = scale * patch2->area / (dist*dist); - - if (trans < 0) - trans = 0; // rounding errors... - - transfers[j] = trans; - if (trans > 0) - { - total += trans; - patch->numtransfers++; - } - } - - // copy the transfers out and normalize - // total should be somewhere near PI if everything went right - // because partial occlusion isn't accounted for, and nearby - // patches have underestimated form factors, it will usually - // be higher than PI - if (patch->numtransfers) - { - transfer_t *t; - - if (patch->numtransfers < 0 || patch->numtransfers > MAX_PATCHES) - Error ("Weird numtransfers"); - s = patch->numtransfers * sizeof(transfer_t); - patch->transfers = malloc (s); - if (!patch->transfers) - Error ("Memory allocation failure"); - - // - // normalize all transfers so all of the light - // is transfered to the surroundings - // - t = patch->transfers; - itotal = 0; - for (j=0 ; jtransfer = itrans; - t->patch = j; - t++; - } - } - - // don't bother locking around this. not that important. - total_transfer += patch->numtransfers; -} - - -/* -============= -FreeTransfers -============= -*/ -void FreeTransfers (void) -{ - int i; - - for (i=0 ; iwinding; - fprintf (out, "%i\n", w->numpoints); - for (i=0 ; inumpoints ; i++) - { - fprintf (out, "%5.2f %5.2f %5.2f %5.3f %5.3f %5.3f\n", - w->p[i][0], - w->p[i][1], - w->p[i][2], - patch->totallight[0], - patch->totallight[1], - patch->totallight[2]); - } - fprintf (out, "\n"); - } - - fclose (out); -} - -/* -============= -WriteGlView -============= -*/ -void WriteGlView (void) -{ - char name[1024]; - FILE *f; - int i, j; - patch_t *p; - winding_t *w; - - strcpy (name, source); - StripExtension (name); - strcat (name, ".glr"); - - f = fopen (name, "w"); - if (!f) - Error ("Couldn't open %s", f); - - for (j=0 ; jwinding; - fprintf (f, "%i\n", w->numpoints); - for (i=0 ; inumpoints ; i++) - { - fprintf (f, "%5.2f %5.2f %5.2f %5.3f %5.3f %5.3f\n", - w->p[i][0], - w->p[i][1], - w->p[i][2], - p->totallight[0]/128, - p->totallight[1]/128, - p->totallight[2]/128); - } - fprintf (f, "\n"); - } - - fclose (f); -} - - -//============================================================== - -/* -============= -CollectLight -============= -*/ -float CollectLight (void) -{ - int i, j; - patch_t *patch; - vec_t total; - - total = 0; - - for (i=0, patch=patches ; isky) - { - VectorClear (radiosity[i]); - VectorClear (illumination[i]); - continue; - } - - for (j=0 ; j<3 ; j++) - { - patch->totallight[j] += illumination[i][j] / patch->area; - radiosity[i][j] = illumination[i][j] * patch->reflectivity[j]; - } - - total += radiosity[i][0] + radiosity[i][1] + radiosity[i][2]; - VectorClear (illumination[i]); - } - - return total; -} - - -/* -============= -ShootLight - -Send light out to other patches - Run multi-threaded -============= -*/ -void ShootLight (int patchnum) -{ - int k, l; - transfer_t *trans; - int num; - patch_t *patch; - vec3_t send; - - // this is the amount of light we are distributing - // prescale it so that multiplying by the 16 bit - // transfer values gives a proper output value - for (k=0 ; k<3 ; k++) - send[k] = radiosity[patchnum][k] / 0x10000; - patch = &patches[patchnum]; - - trans = patch->transfers; - num = patch->numtransfers; - - for (k=0 ; kpatch][l] += send[l]*trans->transfer; - } -} - -/* -============= -BounceLight -============= -*/ -void BounceLight (void) -{ - int i, j; - float added; - char name[64]; - patch_t *p; - - for (i=0 ; itotallight[j] = p->samplelight[j]; - radiosity[i][j] = p->samplelight[j] * p->reflectivity[j] * p->area; - } - } - - for (i=0 ; itotallight[0] < 0 || patch->totallight[1] < 0 || patch->totallight[2] < 0) - Error ("negative patch totallight\n"); - } -} - -/* -============= -RadWorld -============= -*/ -void RadWorld (void) -{ - if (numnodes == 0 || numfaces == 0) - Error ("Empty map"); - MakeBackplanes (); - MakeParents (0, -1); - MakeTnodes (&dmodels[0]); - - // turn each face into a single patch - MakePatches (); - - // subdivide patches to a maximum dimension - SubdividePatches (); - - // create directlights out of patches and lights - CreateDirectLights (); - - // build initial facelights - RunThreadsOnIndividual (numfaces, true, BuildFacelights); - - if (numbounce > 0) - { - // build transfer lists - RunThreadsOnIndividual (num_patches, true, MakeTransfers); - Sys_FPrintf( SYS_VRB, "transfer lists: %5.1f megs\n" - , (float)total_transfer * sizeof(transfer_t) / (1024*1024)); - - // spread light around - BounceLight (); - - FreeTransfers (); - - CheckPatches (); - } - - if (glview) - WriteGlView (); - - // blend bounced light into direct light and save - PairEdges (); - LinkPlaneFaces (); - - lightdatasize = 0; - RunThreadsOnIndividual (numfaces, true, FinalLightFace); -} - - -/* -======== -main - -light modelfile -======== -*/ -int RAD_Main () -{ - double start, end; - char name[1024]; - int total_rad_time; - - Sys_Printf ("\n----- RAD ----\n\n"); - - if (maxlight > 255) - maxlight = 255; - - start = I_FloatTime (); - - if ( !strcmp( game, "heretic2" ) ) - CalcTextureReflectivity = &CalcTextureReflectivity_Heretic2; - else - CalcTextureReflectivity = &CalcTextureReflectivity_Quake2; - - SetQdirFromPath (mapname); - strcpy (source, ExpandArg(mapname)); - StripExtension (source); - DefaultExtension (source, ".bsp"); - -// ReadLightFile (); - - sprintf (name, "%s%s", inbase, source); - Sys_Printf ("reading %s\n", name); - LoadBSPFile (name); - ParseEntities (); - (*CalcTextureReflectivity) (); - - if (!visdatasize) - { - Sys_Printf ("No vis information, direct lighting only.\n"); - numbounce = 0; - ambient = 0.1; - } - - RadWorld (); - - sprintf (name, "%s%s", outbase, source); - Sys_Printf ("writing %s\n", name); - WriteBSPFile (name); - - end = I_FloatTime (); - total_rad_time = (int) (end-start); - Sys_Printf("\nRAD Time: "); - if ( total_rad_time > 59 ) - Sys_Printf("%d Minutes ", total_rad_time/60 ); - Sys_Printf( "%d Seconds\n", total_rad_time%60 ); - - - return 0; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qrad.h b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qrad.h deleted file mode 100644 index eda18919..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qrad.h +++ /dev/null @@ -1,184 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -/* Files: - -lightmap.c -patches.c -qrad.c -trace.c - -*/ - - -#include "cmdlib.h" -#include "mathlib.h" -#include "bspfile.h" -#include "polylib.h" -#include "q2_threads.h" -#include "lbmlib.h" -#include "inout.h" - -#ifdef WIN32 -#include -#endif - -#ifdef WIN32 - #ifdef NDEBUG // Don't show in a Release build - #pragma warning(disable : 4305) // truncate from double to float - #pragma warning(disable : 4244) // conversion from double to float - #pragma warning(disable : 4018) // signed/unsigned mismatch - #endif -#endif - -typedef enum -{ - emit_surface, - emit_point, - emit_spotlight -} emittype_t; - - - -typedef struct directlight_s -{ - struct directlight_s *next; - emittype_t type; - - float intensity; - int style; - vec3_t origin; - vec3_t color; - vec3_t normal; // for surfaces and spotlights - float stopdot; // for spotlights -} directlight_t; - - -// the sum of all tranfer->transfer values for a given patch -// should equal exactly 0x10000, showing that all radiance -// reaches other patches -typedef struct -{ - unsigned short patch; - unsigned short transfer; -} transfer_t; - - -#define MAX_PATCHES 65000 // larger will cause 32 bit overflows - -typedef struct patch_s -{ - winding_t *winding; - struct patch_s *next; // next in face - int numtransfers; - transfer_t *transfers; - - int cluster; // for pvs checking - vec3_t origin; - dplane_t *plane; - - qboolean sky; - - vec3_t totallight; // accumulated by radiosity - // does NOT include light - // accounted for by direct lighting - float area; - - // illuminance * reflectivity = radiosity - vec3_t reflectivity; - vec3_t baselight; // emissivity only - - // each style 0 lightmap sample in the patch will be - // added up to get the average illuminance of the entire patch - vec3_t samplelight; - int samples; // for averaging direct light -} patch_t; - -extern patch_t *face_patches[MAX_MAP_FACES]; -extern entity_t *face_entity[MAX_MAP_FACES]; -extern vec3_t face_offset[MAX_MAP_FACES]; // for rotating bmodels -extern patch_t patches[MAX_PATCHES]; -extern unsigned num_patches; - -extern int leafparents[MAX_MAP_LEAFS]; -extern int nodeparents[MAX_MAP_NODES]; - -extern float lightscale; - - -void MakeShadowSplits (void); - -//============================================== - - -void BuildVisMatrix (void); -qboolean CheckVisBit (unsigned p1, unsigned p2); - -//============================================== - -extern float ambient, maxlight; - -void LinkPlaneFaces (void); - -extern qboolean extrasamples; -extern int numbounce; - -extern directlight_t *directlights[MAX_MAP_LEAFS]; - -extern byte nodehit[MAX_MAP_NODES]; - -void BuildLightmaps (void); - -void BuildFacelights (int facenum); - -void FinalLightFace (int facenum); - -qboolean PvsForOrigin (vec3_t org, byte *pvs); - -int TestLine_r (int node, vec3_t start, vec3_t stop); - -void CreateDirectLights (void); - -dleaf_t *Rad_PointInLeaf (vec3_t point); - - -extern dplane_t backplanes[MAX_MAP_PLANES]; -extern int fakeplanes; // created planes for origin offset - -extern float subdiv; - -extern float direct_scale; -extern float entity_scale; - -int PointInLeafnum (vec3_t point); -void MakeTnodes (dmodel_t *bm); -void MakePatches (void); -void SubdividePatches (void); -void PairEdges (void); -void (*CalcTextureReflectivity) (void); -void CalcTextureReflectivity_Quake2(void); -void CalcTextureReflectivity_Heretic2(void); - -//============================================================================= - -// externs - -extern char *mapname; -extern char game[64]; diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qvis.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qvis.c deleted file mode 100644 index 7785ebe5..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qvis.c +++ /dev/null @@ -1,581 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// qvis.c - -#include "qvis.h" -#include "q2_threads.h" -#include "stdlib.h" - -int numportals; -int portalclusters; - -char inbase[32]; -char outbase[32]; - -portal_t *portals; -leaf_t *leafs; - -int c_portaltest, c_portalpass, c_portalcheck; - -byte *uncompressedvis; - -byte *vismap, *vismap_p, *vismap_end; // past visfile -int originalvismapsize; - -int leafbytes; // (portalclusters+63)>>3 -int leaflongs; - -int portalbytes, portallongs; - -qboolean fastvis; -qboolean nosort; - -int testlevel = 2; - -int totalvis; - -portal_t *sorted_portals[MAX_MAP_PORTALS*2]; - - -//============================================================================= - -void PlaneFromWinding (winding_t *w, plane_t *plane) -{ - vec3_t v1, v2; - -// calc plane - VectorSubtract (w->points[2], w->points[1], v1); - VectorSubtract (w->points[0], w->points[1], v2); - CrossProduct (v2, v1, plane->normal); - VectorNormalize (plane->normal, plane->normal); - plane->dist = DotProduct (w->points[0], plane->normal); -} - - -/* -================== -NewWinding -================== -*/ -winding_t *NewWinding (int points) -{ - winding_t *w; - int size; - - if (points > MAX_POINTS_ON_WINDING) - Error ("NewWinding: %i points", points); - - size = (int)((winding_t *)0)->points[points]; - w = malloc (size); - memset (w, 0, size); - - return w; -} - - -/* -void pw(winding_t *w) -{ - int i; - for (i=0 ; inumpoints ; i++) - Sys_Printf ("(%5.1f, %5.1f, %5.1f)\n",w->points[i][0], w->points[i][1],w->points[i][2]); -} -*/ -void prl(leaf_t *l) -{ - int i; - portal_t *p; - plane_t pl; - - for (i=0 ; inumportals ; i++) - { - p = l->portals[i]; - pl = p->plane; - Sys_Printf ("portal %4i to leaf %4i : %7.1f : (%4.1f, %4.1f, %4.1f)\n",(int)(p-portals),p->leaf,pl.dist, pl.normal[0], pl.normal[1], pl.normal[2]); - } -} - - -//============================================================================= - -/* -============= -SortPortals - -Sorts the portals from the least complex, so the later ones can reuse -the earlier information. -============= -*/ -int PComp (const void *a, const void *b) -{ - if ( (*(portal_t **)a)->nummightsee == (*(portal_t **)b)->nummightsee) - return 0; - if ( (*(portal_t **)a)->nummightsee < (*(portal_t **)b)->nummightsee) - return -1; - return 1; -} -void SortPortals (void) -{ - int i; - - for (i=0 ; i>3] & (1<<(i&7)) ) - { - p = portals+i; - leafbits[p->leaf>>3] |= (1<<(p->leaf&7)); - } - } - - c_leafs = CountBits (leafbits, portalclusters); - - return c_leafs; -} - - -/* -=============== -ClusterMerge - -Merges the portal visibility for a leaf -=============== -*/ -void ClusterMerge (int leafnum) -{ - leaf_t *leaf; - byte portalvector[MAX_PORTALS/8]; - byte uncompressed[MAX_MAP_LEAFS/8]; - byte compressed[MAX_MAP_LEAFS/8]; - int i, j; - int numvis; - byte *dest; - portal_t *p; - int pnum; - - // OR together all the portalvis bits - - memset (portalvector, 0, portalbytes); - leaf = &leafs[leafnum]; - for (i=0 ; inumportals ; i++) - { - p = leaf->portals[i]; - if (p->status != stat_done) - Error ("portal not done"); - for (j=0 ; jportalvis)[j]; - pnum = p - portals; - portalvector[pnum>>3] |= 1<<(pnum&7); - } - - // convert portal bits to leaf bits - numvis = LeafVectorFromPortalVector (portalvector, uncompressed); - - if (uncompressed[leafnum>>3] & (1<<(leafnum&7))) - Sys_Printf ("WARNING: Leaf portals saw into leaf\n"); - - uncompressed[leafnum>>3] |= (1<<(leafnum&7)); - numvis++; // count the leaf itself - - // save uncompressed for PHS calculation - memcpy (uncompressedvis + leafnum*leafbytes, uncompressed, leafbytes); - -// -// compress the bit string -// - Sys_FPrintf( SYS_VRB, "cluster %4i : %4i visible\n", leafnum, numvis); - totalvis += numvis; - - i = CompressVis (uncompressed, compressed); - - dest = vismap_p; - vismap_p += i; - - if (vismap_p > vismap_end) - Error ("Vismap expansion overflow"); - - dvis->bitofs[leafnum][DVIS_PVS] = dest-vismap; - - memcpy (dest, compressed, i); -} - - -/* -================== -CalcPortalVis -================== -*/ -void CalcPortalVis (void) -{ - int i; - -// fastvis just uses mightsee for a very loose bound - if (fastvis) - { - for (i=0 ; iwinding; - VectorCopy (vec3_origin, total); - for (i=0 ; inumpoints ; i++) - { - VectorAdd (total, w->points[i], total); - } - - for (i=0 ; i<3 ; i++) - total[i] /= w->numpoints; - - bestr = 0; - for (i=0 ; inumpoints ; i++) - { - VectorSubtract (w->points[i], total, dist); - r = VectorLength (dist); - if (r > bestr) - bestr = r; - } - VectorCopy (total, p->origin); - p->radius = bestr; -} - -/* -============ -LoadPortals -============ -*/ -void LoadPortals (char *name) -{ - int i, j; - portal_t *p; - leaf_t *l; - char magic[80]; - FILE *f; - int numpoints; - winding_t *w; - int leafnums[2]; - plane_t plane; - - if (!strcmp(name,"-")) - f = stdin; - else - { - f = fopen(name, "r"); - if (!f) - Error ("LoadPortals: couldn't read %s\n",name); - } - - if (fscanf (f,"%79s\n%i\n%i\n",magic, &portalclusters, &numportals) != 3) - Error ("LoadPortals: failed to read header"); - if (strcmp(magic,PORTALFILE)) - Error ("LoadPortals: not a portal file"); - - Sys_Printf ("%4i portalclusters\n", portalclusters); - Sys_Printf ("%4i numportals\n", numportals); - - // these counts should take advantage of 64 bit systems automatically - leafbytes = ((portalclusters+63)&~63)>>3; - leaflongs = leafbytes/sizeof(long); - - portalbytes = ((numportals*2+63)&~63)>>3; - portallongs = portalbytes/sizeof(long); - -// each file portal is split into two memory portals - portals = malloc(2*numportals*sizeof(portal_t)); - memset (portals, 0, 2*numportals*sizeof(portal_t)); - - leafs = malloc(portalclusters*sizeof(leaf_t)); - memset (leafs, 0, portalclusters*sizeof(leaf_t)); - - originalvismapsize = portalclusters*leafbytes; - uncompressedvis = malloc(originalvismapsize); - - vismap = vismap_p = dvisdata; - dvis->numclusters = portalclusters; - vismap_p = (byte *)&dvis->bitofs[portalclusters]; - - vismap_end = vismap + MAX_MAP_VISIBILITY; - - for (i=0, p=portals ; i MAX_POINTS_ON_WINDING) - Error ("LoadPortals: portal %i has too many points", i); - if ( (unsigned)leafnums[0] > portalclusters - || (unsigned)leafnums[1] > portalclusters) - Error ("LoadPortals: reading portal %i", i); - - w = p->winding = NewWinding (numpoints); - w->original = true; - w->numpoints = numpoints; - - for (j=0 ; jpoints[j][k] = v[k]; - } - fscanf (f, "\n"); - - // calc plane - PlaneFromWinding (w, &plane); - - // create forward portal - l = &leafs[leafnums[0]]; - if (l->numportals == MAX_PORTALS_ON_LEAF) - Error ("Leaf with too many portals"); - l->portals[l->numportals] = p; - l->numportals++; - - p->winding = w; - VectorSubtract (vec3_origin, plane.normal, p->plane.normal); - p->plane.dist = -plane.dist; - p->leaf = leafnums[1]; - SetPortalSphere (p); - p++; - - // create backwards portal - l = &leafs[leafnums[1]]; - if (l->numportals == MAX_PORTALS_ON_LEAF) - Error ("Leaf with too many portals"); - l->portals[l->numportals] = p; - l->numportals++; - - p->winding = NewWinding(w->numpoints); - p->winding->numpoints = w->numpoints; - for (j=0 ; jnumpoints ; j++) - { - VectorCopy (w->points[w->numpoints-1-j], p->winding->points[j]); - } - - p->plane = plane; - p->leaf = leafnums[0]; - SetPortalSphere (p); - p++; - - } - - fclose (f); -} - - -/* -================ -CalcPHS - -Calculate the PHS (Potentially Hearable Set) -by ORing together all the PVS visible from a leaf -================ -*/ -void CalcPHS (void) -{ - int i, j, k, l, index; - int bitbyte; - long *dest, *src; - byte *scan; - int count; - byte uncompressed[MAX_MAP_LEAFS/8]; - byte compressed[MAX_MAP_LEAFS/8]; - - Sys_Printf ("Building PHS...\n"); - - count = 0; - for (i=0 ; i= portalclusters) - Error ("Bad bit in PVS"); // pad bits should be 0 - src = (long *)(uncompressedvis + index*leafbytes); - dest = (long *)uncompressed; - for (l=0 ; l>3] & (1<<(j&7)) ) - count++; - - // - // compress the bit string - // - j = CompressVis (uncompressed, compressed); - - dest = (long *)vismap_p; - vismap_p += j; - - if (vismap_p > vismap_end) - Error ("Vismap expansion overflow"); - - dvis->bitofs[i][DVIS_PHS] = (byte *)dest-vismap; - - memcpy (dest, compressed, j); - } - - Sys_Printf ("Average clusters hearable: %i\n", count/portalclusters); -} - -/* -=========== -main -=========== -*/ -int VIS_Main () -{ - char portalfile[1024]; - char source[1024]; - char name[1024]; - double start, end; - int total_vis_time; - - Sys_Printf ("\n----- VIS ----\n\n"); - - //if (i != argc - 1) - // Error ("usage: vis [-threads #] [-level 0-4] [-fast] [-v] bspfile"); - - start = I_FloatTime (); - - ThreadSetDefault (); - - SetQdirFromPath (mapname); - strcpy (source, ExpandArg(mapname)); - StripExtension (source); - DefaultExtension (source, ".bsp"); - - sprintf (name, "%s%s", inbase, source); - Sys_Printf ("reading %s\n", name); - LoadBSPFile (name); - if (numnodes == 0 || numfaces == 0) - Error ("Empty map"); - - sprintf (portalfile, "%s%s", inbase, ExpandArg(mapname)); - StripExtension (portalfile); - strcat (portalfile, ".prt"); - - Sys_Printf ("reading %s\n", portalfile); - LoadPortals (portalfile); - - CalcVis (); - - CalcPHS (); - - visdatasize = vismap_p - dvisdata; - Sys_Printf ("visdatasize:%i compressed from %i\n", visdatasize, originalvismapsize*2); - - sprintf (name, "%s%s", outbase, source); - Sys_Printf ("writing %s\n", name); - WriteBSPFile (name); - - end = I_FloatTime (); - total_vis_time = (int) (end-start); - Sys_Printf("\nVIS Time: "); - if ( total_vis_time > 59 ) - Sys_Printf("%d Minutes ", total_vis_time/60 ); - Sys_Printf( "%d Seconds\n", total_vis_time%60 ); - - - return 0; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qvis.h b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qvis.h deleted file mode 100644 index 3f2306fb..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/qvis.h +++ /dev/null @@ -1,169 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -/* Files: - -flow.c -qvis3.c - -*/ - -#include "cmdlib.h" -#include "mathlib.h" -#include "bspfile.h" -#include "inout.h" - -#ifdef WIN32 - #ifdef NDEBUG // Don't show in a Release build - #pragma warning(disable : 4305) // truncate from double to float - #pragma warning(disable : 4244) // conversion from double to float - #pragma warning(disable : 4018) // signed/unsigned mismatch - #endif -#endif - -#define MAX_PORTALS 32768 - -#define PORTALFILE "PRT1" - -#define ON_EPSILON 0.1 - -typedef struct -{ - vec3_t normal; - float dist; -} plane_t; - -#define MAX_POINTS_ON_WINDING 64 -#define MAX_POINTS_ON_FIXED_WINDING 12 - -typedef struct -{ - qboolean original; // don't free, it's part of the portal - int numpoints; - vec3_t points[MAX_POINTS_ON_FIXED_WINDING]; // variable sized -} winding_t; - -winding_t *NewWinding (int points); -void FreeWinding (winding_t *w); -winding_t *CopyWinding (winding_t *w); - - -typedef enum {stat_none, stat_working, stat_done} vstatus_t; -typedef struct -{ - plane_t plane; // normal pointing into neighbor - int leaf; // neighbor - - vec3_t origin; // for fast clip testing - float radius; - - winding_t *winding; - vstatus_t status; - byte *portalfront; // [portals], preliminary - byte *portalflood; // [portals], intermediate - byte *portalvis; // [portals], final - - int nummightsee; // bit count on portalflood for sort -} portal_t; - -typedef struct seperating_plane_s -{ - struct seperating_plane_s *next; - plane_t plane; // from portal is on positive side -} sep_t; - - -typedef struct passage_s -{ - struct passage_s *next; - int from, to; // leaf numbers - sep_t *planes; -} passage_t; - -#define MAX_PORTALS_ON_LEAF 128 -typedef struct leaf_s -{ - int numportals; - passage_t *passages; - portal_t *portals[MAX_PORTALS_ON_LEAF]; -} leaf_t; - - -typedef struct pstack_s -{ - byte mightsee[MAX_PORTALS/8]; // bit string - struct pstack_s *next; - leaf_t *leaf; - portal_t *portal; // portal exiting - winding_t *source; - winding_t *pass; - - winding_t windings[3]; // source, pass, temp in any order - int freewindings[3]; - - plane_t portalplane; -} pstack_t; - -typedef struct -{ - portal_t *base; - int c_chains; - pstack_t pstack_head; -} threaddata_t; - - - -extern int numportals; -extern int portalclusters; - -extern portal_t *portals; -extern leaf_t *leafs; - -extern int c_portaltest, c_portalpass, c_portalcheck; -extern int c_portalskip, c_leafskip; -extern int c_vistest, c_mighttest; -extern int c_chains; - -extern byte *vismap, *vismap_p, *vismap_end; // past visfile - -extern int testlevel; - -extern byte *uncompressed; - -extern int leafbytes, leaflongs; -extern int portalbytes, portallongs; - - -void LeafFlow (int leafnum); - - -void BasePortalVis (int portalnum); -void BetterPortalVis (int portalnum); -void PortalFlow (int portalnum); - -extern portal_t *sorted_portals[MAX_MAP_PORTALS*2]; - -int CountBits (byte *bits, int numbits); - -//============================================================================= - -// externs - -extern char *mapname; diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/textures.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/textures.c deleted file mode 100644 index 503d7a4d..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/textures.c +++ /dev/null @@ -1,249 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -int nummiptex; -textureref_t textureref[MAX_MAP_TEXTURES]; - -//========================================================================== - - -int FindMiptex (char *name) -{ - int i; - char path[1024]; - miptex_t *mt; - miptex_m8_t *mt_m8; - miptex_m32_t *mt_m32; - - for (i=0 ; ivalue); - textureref[i].flags = LittleLong (mt_m32->flags); - textureref[i].contents = LittleLong (mt_m32->contents); - strcpy (textureref[i].animname, mt_m32->animname); - free (mt_m32); - } - else - sprintf (path, "%stextures/%s.m8", gamedir, name); - - if (TryLoadFile (path, (void **)&mt_m8) != -1) - { - textureref[i].value = LittleLong (mt_m8->value); - textureref[i].flags = LittleLong (mt_m8->flags); - textureref[i].contents = LittleLong (mt_m8->contents); - strcpy (textureref[i].animname, mt_m8->animname); - free (mt_m8); - } - } - else - { - sprintf (path, "%stextures/%s.wal", gamedir, name); - if (TryLoadFile (path, (void **)&mt) != -1) - { - textureref[i].value = LittleLong (mt->value); - textureref[i].flags = LittleLong (mt->flags); - textureref[i].contents = LittleLong (mt->contents); - strcpy (textureref[i].animname, mt->animname); - free (mt); - } - } - - nummiptex++; - - if (textureref[i].animname[0]) - FindMiptex (textureref[i].animname); - - return i; -} - - -/* -================== -textureAxisFromPlane -================== -*/ -vec3_t baseaxis[18] = -{ -{0,0,1}, {1,0,0}, {0,-1,0}, // floor -{0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling -{1,0,0}, {0,1,0}, {0,0,-1}, // west wall -{-1,0,0}, {0,1,0}, {0,0,-1}, // east wall -{0,1,0}, {1,0,0}, {0,0,-1}, // south wall -{0,-1,0}, {1,0,0}, {0,0,-1} // north wall -}; - -void TextureAxisFromPlane(plane_t *pln, vec3_t xv, vec3_t yv) -{ - int bestaxis; - vec_t dot,best; - int i; - - best = 0; - bestaxis = 0; - - for (i=0 ; i<6 ; i++) - { - dot = DotProduct (pln->normal, baseaxis[i*3]); - if (dot > best) - { - best = dot; - bestaxis = i; - } - } - - VectorCopy (baseaxis[bestaxis*3+1], xv); - VectorCopy (baseaxis[bestaxis*3+2], yv); -} - - - - -int TexinfoForBrushTexture (plane_t *plane, brush_texture_t *bt, vec3_t origin) -{ - vec3_t vecs[2]; - int sv, tv; - vec_t ang, sinv, cosv; - vec_t ns, nt; - texinfo_t tx, *tc; - int i, j, k; - float shift[2]; - brush_texture_t anim; - int mt; - - if (!bt->name[0]) - return 0; - - memset (&tx, 0, sizeof(tx)); - strcpy (tx.texture, bt->name); - - TextureAxisFromPlane(plane, vecs[0], vecs[1]); - - shift[0] = DotProduct (origin, vecs[0]); - shift[1] = DotProduct (origin, vecs[1]); - - if (!bt->scale[0]) - bt->scale[0] = 1; - if (!bt->scale[1]) - bt->scale[1] = 1; - - -// rotate axis - if (bt->rotate == 0) - { sinv = 0 ; cosv = 1; } - else if (bt->rotate == 90) - { sinv = 1 ; cosv = 0; } - else if (bt->rotate == 180) - { sinv = 0 ; cosv = -1; } - else if (bt->rotate == 270) - { sinv = -1 ; cosv = 0; } - else - { - ang = bt->rotate / 180 * Q_PI; - sinv = sin(ang); - cosv = cos(ang); - } - - if (vecs[0][0]) - sv = 0; - else if (vecs[0][1]) - sv = 1; - else - sv = 2; - - if (vecs[1][0]) - tv = 0; - else if (vecs[1][1]) - tv = 1; - else - tv = 2; - - for (i=0 ; i<2 ; i++) - { - ns = cosv * vecs[i][sv] - sinv * vecs[i][tv]; - nt = sinv * vecs[i][sv] + cosv * vecs[i][tv]; - vecs[i][sv] = ns; - vecs[i][tv] = nt; - } - - for (i=0 ; i<2 ; i++) - for (j=0 ; j<3 ; j++) - tx.vecs[i][j] = vecs[i][j] / bt->scale[i]; - - tx.vecs[0][3] = bt->shift[0] + shift[0]; - tx.vecs[1][3] = bt->shift[1] + shift[1]; - tx.flags = bt->flags; - tx.value = bt->value; - - // - // find the texinfo - // - tc = texinfo; - for (i=0 ; iflags != tx.flags) - continue; - if (tc->value != tx.value) - continue; - for (j=0 ; j<2 ; j++) - { - if (strcmp (tc->texture, tx.texture)) - goto skip; - for (k=0 ; k<4 ; k++) - { - if (tc->vecs[j][k] != tx.vecs[j][k]) - goto skip; - } - } - return i; -skip:; - } - *tc = tx; - numtexinfo++; - - // load the next animation - mt = FindMiptex (bt->name); - if (textureref[mt].animname[0]) - { - anim = *bt; - strcpy (anim.name, textureref[mt].animname); - tc->nexttexinfo = TexinfoForBrushTexture (plane, &anim, origin); - } - else - tc->nexttexinfo = -1; - - - return i; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/trace.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/trace.c deleted file mode 100644 index b9392b17..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/trace.c +++ /dev/null @@ -1,298 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ -// trace.c -/* -#include "cmdlib.h" -#include "mathlib.h" -#include "bspfile.h" -*/ - -#include "qrad.h" - -#define ON_EPSILON 0.1 - -typedef struct tnode_s -{ - int type; - vec3_t normal; - float dist; - int children[2]; - int pad; -} tnode_t; - -tnode_t *tnodes, *tnode_p; - -/* -============== -MakeTnode - -Converts the disk node structure into the efficient tracing structure -============== -*/ -void MakeTnode (int nodenum) -{ - tnode_t *t; - dplane_t *plane; - int i; - dnode_t *node; - - t = tnode_p++; - - node = dnodes + nodenum; - plane = dplanes + node->planenum; - - t->type = plane->type; - VectorCopy (plane->normal, t->normal); - t->dist = plane->dist; - - for (i=0 ; i<2 ; i++) - { - if (node->children[i] < 0) - t->children[i] = (dleafs[-node->children[i] - 1].contents & CONTENTS_SOLID) | (1<<31); - else - { - t->children[i] = tnode_p - tnodes; - MakeTnode (node->children[i]); - } - } - -} - - -/* -============= -MakeTnodes - -Loads the node structure out of a .bsp file to be used for light occlusion -============= -*/ -void MakeTnodes (dmodel_t *bm) -{ - // 32 byte align the structs - tnodes = malloc( (numnodes+1) * sizeof(tnode_t)); - tnodes = (tnode_t *)(((int)tnodes + 31)&~31); - tnode_p = tnodes; - - MakeTnode (0); -} - - -//========================================================== - - -int TestLine_r (int node, vec3_t start, vec3_t stop) -{ - tnode_t *tnode; - float front, back; - vec3_t mid; - float frac; - int side; - int r; - - if (node & (1<<31)) - return node & ~(1<<31); // leaf node - - tnode = &tnodes[node]; - switch (tnode->type) - { - case PLANE_X: - front = start[0] - tnode->dist; - back = stop[0] - tnode->dist; - break; - case PLANE_Y: - front = start[1] - tnode->dist; - back = stop[1] - tnode->dist; - break; - case PLANE_Z: - front = start[2] - tnode->dist; - back = stop[2] - tnode->dist; - break; - default: - front = (start[0]*tnode->normal[0] + start[1]*tnode->normal[1] + start[2]*tnode->normal[2]) - tnode->dist; - back = (stop[0]*tnode->normal[0] + stop[1]*tnode->normal[1] + stop[2]*tnode->normal[2]) - tnode->dist; - break; - } - - if (front >= -ON_EPSILON && back >= -ON_EPSILON) - return TestLine_r (tnode->children[0], start, stop); - - if (front < ON_EPSILON && back < ON_EPSILON) - return TestLine_r (tnode->children[1], start, stop); - - side = front < 0; - - frac = front / (front-back); - - mid[0] = start[0] + (stop[0] - start[0])*frac; - mid[1] = start[1] + (stop[1] - start[1])*frac; - mid[2] = start[2] + (stop[2] - start[2])*frac; - - r = TestLine_r (tnode->children[side], start, mid); - if (r) - return r; - return TestLine_r (tnode->children[!side], mid, stop); -} - -int TestLine (vec3_t start, vec3_t stop) -{ - return TestLine_r (0, start, stop); -} - -/* -============================================================================== - -LINE TRACING - -The major lighting operation is a point to point visibility test, performed -by recursive subdivision of the line by the BSP tree. - -============================================================================== -*/ - -typedef struct -{ - vec3_t backpt; - int side; - int node; -} tracestack_t; - - -/* -============== -TestLine -============== -*/ -qboolean _TestLine (vec3_t start, vec3_t stop) -{ - int node; - float front, back; - tracestack_t *tstack_p; - int side; - float frontx,fronty, frontz, backx, backy, backz; - tracestack_t tracestack[64]; - tnode_t *tnode; - - frontx = start[0]; - fronty = start[1]; - frontz = start[2]; - backx = stop[0]; - backy = stop[1]; - backz = stop[2]; - - tstack_p = tracestack; - node = 0; - - while (1) - { - if (node == CONTENTS_SOLID) - { -#if 0 - float d1, d2, d3; - - d1 = backx - frontx; - d2 = backy - fronty; - d3 = backz - frontz; - - if (d1*d1 + d2*d2 + d3*d3 > 1) -#endif - return false; // DONE! - } - - while (node < 0) - { - // pop up the stack for a back side - tstack_p--; - if (tstack_p < tracestack) - return true; - node = tstack_p->node; - - // set the hit point for this plane - - frontx = backx; - fronty = backy; - frontz = backz; - - // go down the back side - - backx = tstack_p->backpt[0]; - backy = tstack_p->backpt[1]; - backz = tstack_p->backpt[2]; - - node = tnodes[tstack_p->node].children[!tstack_p->side]; - } - - tnode = &tnodes[node]; - - switch (tnode->type) - { - case PLANE_X: - front = frontx - tnode->dist; - back = backx - tnode->dist; - break; - case PLANE_Y: - front = fronty - tnode->dist; - back = backy - tnode->dist; - break; - case PLANE_Z: - front = frontz - tnode->dist; - back = backz - tnode->dist; - break; - default: - front = (frontx*tnode->normal[0] + fronty*tnode->normal[1] + frontz*tnode->normal[2]) - tnode->dist; - back = (backx*tnode->normal[0] + backy*tnode->normal[1] + backz*tnode->normal[2]) - tnode->dist; - break; - } - - if (front > -ON_EPSILON && back > -ON_EPSILON) -// if (front > 0 && back > 0) - { - node = tnode->children[0]; - continue; - } - - if (front < ON_EPSILON && back < ON_EPSILON) -// if (front <= 0 && back <= 0) - { - node = tnode->children[1]; - continue; - } - - side = front < 0; - - front = front / (front-back); - - tstack_p->node = node; - tstack_p->side = side; - tstack_p->backpt[0] = backx; - tstack_p->backpt[1] = backy; - tstack_p->backpt[2] = backz; - - tstack_p++; - - backx = frontx + front*(backx-frontx); - backy = fronty + front*(backy-fronty); - backz = frontz + front*(backz-frontz); - - node = tnode->children[side]; - } -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/tree.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/tree.c deleted file mode 100644 index 52d78fa8..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/tree.c +++ /dev/null @@ -1,218 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -extern int c_nodes; - -void RemovePortalFromNode (portal_t *portal, node_t *l); - -node_t *NodeForPoint (node_t *node, vec3_t origin) -{ - plane_t *plane; - vec_t d; - - while (node->planenum != PLANENUM_LEAF) - { - plane = &mapplanes[node->planenum]; - d = DotProduct (origin, plane->normal) - plane->dist; - if (d >= 0) - node = node->children[0]; - else - node = node->children[1]; - } - - return node; -} - - - -/* -============= -FreeTreePortals_r -============= -*/ -void FreeTreePortals_r (node_t *node) -{ - portal_t *p, *nextp; - int s; - - // free children - if (node->planenum != PLANENUM_LEAF) - { - FreeTreePortals_r (node->children[0]); - FreeTreePortals_r (node->children[1]); - } - - // free portals - for (p=node->portals ; p ; p=nextp) - { - s = (p->nodes[1] == node); - nextp = p->next[s]; - - RemovePortalFromNode (p, p->nodes[!s]); - FreePortal (p); - } - node->portals = NULL; -} - -/* -============= -FreeTree_r -============= -*/ -void FreeTree_r (node_t *node) -{ - face_t *f, *nextf; - - // free children - if (node->planenum != PLANENUM_LEAF) - { - FreeTree_r (node->children[0]); - FreeTree_r (node->children[1]); - } - - // free bspbrushes - FreeBrushList (node->brushlist); - - // free faces - for (f=node->faces ; f ; f=nextf) - { - nextf = f->next; - FreeFace (f); - } - - // free the node - if (node->volume) - FreeBrush (node->volume); - - if (numthreads == 1) - c_nodes--; - free (node); -} - - -/* -============= -FreeTree -============= -*/ -void FreeTree (tree_t *tree) -{ - FreeTreePortals_r (tree->headnode); - FreeTree_r (tree->headnode); - free (tree); -} - -//=============================================================== - -void PrintTree_r (node_t *node, int depth) -{ - int i; - plane_t *plane; - bspbrush_t *bb; - - for (i=0 ; iplanenum == PLANENUM_LEAF) - { - if (!node->brushlist) - Sys_Printf ("NULL\n"); - else - { - for (bb=node->brushlist ; bb ; bb=bb->next) - Sys_Printf ("%i ", bb->original->brushnum); - Sys_Printf ("\n"); - } - return; - } - - plane = &mapplanes[node->planenum]; - Sys_Printf ("#%i (%5.2f %5.2f %5.2f):%5.2f\n", node->planenum, - plane->normal[0], plane->normal[1], plane->normal[2], - plane->dist); - PrintTree_r (node->children[0], depth+1); - PrintTree_r (node->children[1], depth+1); -} - -/* -========================================================= - -NODES THAT DON'T SEPERATE DIFFERENT CONTENTS CAN BE PRUNED - -========================================================= -*/ - -int c_pruned; - -/* -============ -PruneNodes_r -============ -*/ -void PruneNodes_r (node_t *node) -{ - bspbrush_t *b, *next; - - if (node->planenum == PLANENUM_LEAF) - return; - PruneNodes_r (node->children[0]); - PruneNodes_r (node->children[1]); - - if ( (node->children[0]->contents & CONTENTS_SOLID) - && (node->children[1]->contents & CONTENTS_SOLID) ) - { - if (node->faces) - Error ("node->faces seperating CONTENTS_SOLID"); - if (node->children[0]->faces || node->children[1]->faces) - Error ("!node->faces with children"); - - // FIXME: free stuff - node->planenum = PLANENUM_LEAF; - node->contents = CONTENTS_SOLID; - node->detail_seperator = false; - - if (node->brushlist) - Error ("PruneNodes: node->brushlist"); - - // combine brush lists - node->brushlist = node->children[1]->brushlist; - - for (b=node->children[0]->brushlist ; b ; b=next) - { - next = b->next; - b->next = node->brushlist; - node->brushlist = b; - } - - c_pruned++; - } -} - - -void PruneNodes (node_t *node) -{ - Sys_FPrintf( SYS_VRB, "--- PruneNodes ---\n"); - c_pruned = 0; - PruneNodes_r (node); - Sys_FPrintf( SYS_VRB, "%5i pruned nodes\n", c_pruned); -} - -//=========================================================== diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/writebsp.c b/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/writebsp.c deleted file mode 100644 index 722f6ab9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/q2map/writebsp.c +++ /dev/null @@ -1,591 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qbsp.h" - -int c_nofaces; -int c_facenodes; - - -/* -========================================================= - -ONLY SAVE OUT PLANES THAT ARE ACTUALLY USED AS NODES - -========================================================= -*/ - -int planeused[MAX_MAP_PLANES]; - -/* -============ -EmitPlanes - -There is no oportunity to discard planes, because all of the original -brushes will be saved in the map. -============ -*/ -void EmitPlanes (void) -{ - int i; - dplane_t *dp; - plane_t *mp; - int planetranslate[MAX_MAP_PLANES]; - - mp = mapplanes; - for (i=0 ; inormal, dp->normal); - dp->dist = mp->dist; - dp->type = mp->type; - numplanes++; - } -} - - -//======================================================== - -void EmitMarkFace (dleaf_t *leaf_p, face_t *f) -{ - int i; - int facenum; - - while (f->merged) - f = f->merged; - - if (f->split[0]) - { - EmitMarkFace (leaf_p, f->split[0]); - EmitMarkFace (leaf_p, f->split[1]); - return; - } - - facenum = f->outputnumber; - if (facenum == -1) - return; // degenerate face - - if (facenum < 0 || facenum >= numfaces) - Error ("Bad leafface"); - for (i=leaf_p->firstleafface ; i= MAX_MAP_LEAFFACES) - Error ("MAX_MAP_LEAFFACES"); - - dleaffaces[numleaffaces] = facenum; - numleaffaces++; - } - -} - - -/* -================== -EmitLeaf -================== -*/ -void EmitLeaf (node_t *node) -{ - dleaf_t *leaf_p; - portal_t *p; - int s; - face_t *f; - bspbrush_t *b; - int i; - int brushnum; - - // emit a leaf - if (numleafs >= MAX_MAP_LEAFS) - Error ("MAX_MAP_LEAFS"); - - leaf_p = &dleafs[numleafs]; - numleafs++; - - leaf_p->contents = node->contents; - leaf_p->cluster = node->cluster; - leaf_p->area = node->area; - - // - // write bounding box info - // - VectorCopy ((short) node->mins, leaf_p->mins); - VectorCopy ((short) node->maxs, leaf_p->maxs); - - // - // write the leafbrushes - // - leaf_p->firstleafbrush = numleafbrushes; - for (b=node->brushlist ; b ; b=b->next) - { - if (numleafbrushes >= MAX_MAP_LEAFBRUSHES) - Error ("MAX_MAP_LEAFBRUSHES"); - - brushnum = b->original - mapbrushes; - for (i=leaf_p->firstleafbrush ; inumleafbrushes = numleafbrushes - leaf_p->firstleafbrush; - - // - // write the leaffaces - // - if (leaf_p->contents & CONTENTS_SOLID) - return; // no leaffaces in solids - - leaf_p->firstleafface = numleaffaces; - - for (p = node->portals ; p ; p = p->next[s]) - { - s = (p->nodes[1] == node); - f = p->face[s]; - if (!f) - continue; // not a visible portal - - EmitMarkFace (leaf_p, f); - } - - leaf_p->numleaffaces = numleaffaces - leaf_p->firstleafface; -} - - -/* -================== -EmitFace -================== -*/ -void EmitFace (face_t *f) -{ - dface_t *df; - int i; - int e; - - f->outputnumber = -1; - - if (f->numpoints < 3) - { - return; // degenerated - } - if (f->merged || f->split[0] || f->split[1]) - { - return; // not a final face - } - - // save output number so leaffaces can use - f->outputnumber = numfaces; - - if (numfaces >= MAX_MAP_FACES) - Error ("numfaces == MAX_MAP_FACES"); - df = &dfaces[numfaces]; - numfaces++; - - // planenum is used by qlight, but not quake - df->planenum = f->planenum & (~1); - df->side = f->planenum & 1; - - df->firstedge = numsurfedges; - df->numedges = f->numpoints; - df->texinfo = f->texinfo; - for (i=0 ; inumpoints ; i++) - { -// e = GetEdge (f->pts[i], f->pts[(i+1)%f->numpoints], f); - e = GetEdge2 (f->vertexnums[i], f->vertexnums[(i+1)%f->numpoints], f); - if (numsurfedges >= MAX_MAP_SURFEDGES) - Error ("numsurfedges == MAX_MAP_SURFEDGES"); - dsurfedges[numsurfedges] = e; - numsurfedges++; - } -} - -/* -============ -EmitDrawingNode_r -============ -*/ -int EmitDrawNode_r (node_t *node) -{ - dnode_t *n; - face_t *f; - int i; - - if (node->planenum == PLANENUM_LEAF) - { - EmitLeaf (node); - return -numleafs; - } - - // emit a node - if (numnodes == MAX_MAP_NODES) - Error ("MAX_MAP_NODES"); - n = &dnodes[numnodes]; - numnodes++; - - VectorCopy ((short) node->mins, n->mins); - VectorCopy ((short) node->maxs, n->maxs); - - planeused[node->planenum]++; - planeused[node->planenum^1]++; - - if (node->planenum & 1) - Error ("WriteDrawNodes_r: odd planenum"); - n->planenum = node->planenum; - n->firstface = numfaces; - - if (!node->faces) - c_nofaces++; - else - c_facenodes++; - - for (f=node->faces ; f ; f=f->next) - EmitFace (f); - - n->numfaces = numfaces - n->firstface; - - - // - // recursively output the other nodes - // - for (i=0 ; i<2 ; i++) - { - if (node->children[i]->planenum == PLANENUM_LEAF) - { - n->children[i] = -(numleafs + 1); - EmitLeaf (node->children[i]); - } - else - { - n->children[i] = numnodes; - EmitDrawNode_r (node->children[i]); - } - } - - return n - dnodes; -} - -//========================================================= - - -/* -============ -WriteBSP -============ -*/ -void WriteBSP (node_t *headnode) -{ - int oldfaces; - - c_nofaces = 0; - c_facenodes = 0; - - Sys_FPrintf( SYS_VRB, "--- WriteBSP ---\n"); - - oldfaces = numfaces; - dmodels[nummodels].headnode = EmitDrawNode_r (headnode); - EmitAreaPortals (headnode); - - Sys_FPrintf( SYS_VRB, "%5i nodes with faces\n", c_facenodes); - Sys_FPrintf( SYS_VRB, "%5i nodes without faces\n", c_nofaces); - Sys_FPrintf( SYS_VRB, "%5i faces\n", numfaces-oldfaces); -} - -//=========================================================== - -/* -============ -SetModelNumbers -============ -*/ -void SetModelNumbers (void) -{ - int i; - int models; - char value[10]; - - models = 1; - for (i=1 ; icontents = b->contents; - db->firstside = numbrushsides; - db->numsides = b->numsides; - for (j=0 ; jnumsides ; j++) - { - if (numbrushsides == MAX_MAP_BRUSHSIDES) - Error ("MAX_MAP_BRUSHSIDES"); - cp = &dbrushsides[numbrushsides]; - numbrushsides++; - cp->planenum = b->original_sides[j].planenum; - cp->texinfo = b->original_sides[j].texinfo; - } - - // add any axis planes not contained in the brush to bevel off corners - for (x=0 ; x<3 ; x++) - for (s=-1 ; s<=1 ; s+=2) - { - // add the plane - VectorCopy (vec3_origin, normal); - normal[x] = (float) s; - if (s == -1) - dist = -b->mins[x]; - else - dist = b->maxs[x]; - planenum = FindFloatPlane (normal, dist); - for (i=0 ; inumsides ; i++) - if (b->original_sides[i].planenum == planenum) - break; - if (i == b->numsides) - { - if (numbrushsides >= MAX_MAP_BRUSHSIDES) - Error ("MAX_MAP_BRUSHSIDES"); - - dbrushsides[numbrushsides].planenum = planenum; - dbrushsides[numbrushsides].texinfo = - dbrushsides[numbrushsides-1].texinfo; - numbrushsides++; - db->numsides++; - } - } - - } - -} - -//=========================================================== - -/* -================== -BeginBSPFile -================== -*/ -void BeginBSPFile (void) -{ - // these values may actually be initialized - // if the file existed when loaded, so clear them explicitly - nummodels = 0; - numfaces = 0; - numnodes = 0; - numbrushsides = 0; - numvertexes = 0; - numleaffaces = 0; - numleafbrushes = 0; - numsurfedges = 0; - - // edge 0 is not used, because 0 can't be negated - numedges = 1; - - // leave vertex 0 as an error - numvertexes = 1; - - // leave leaf 0 as an error - numleafs = 1; - dleafs[0].contents = CONTENTS_SOLID; -} - - -/* -============ -EndBSPFile -============ -*/ -void EndBSPFile (void) -{ - char path[1024]; - -#if 0 - int len; - byte *buf; -#endif - - EmitBrushes (); - EmitPlanes (); - UnparseEntities (); - - // load the pop -#if 0 - sprintf (path, "%s/pics/pop.lmp", gamedir); - len = LoadFile (path, &buf); - memcpy (dpop, buf, sizeof(dpop)); - free (buf); -#endif - - // write the map - sprintf (path, "%s.bsp", source); - Sys_Printf ("Writing %s\n", path); - WriteBSPFile (path); -} - - -/* -================== -BeginModel -================== -*/ -int firstmodleaf; -extern int firstmodeledge; -extern int firstmodelface; -void BeginModel (void) -{ - dmodel_t *mod; - int start, end; - mapbrush_t *b; - int j; - entity_t *e; - vec3_t mins, maxs; - - if (nummodels == MAX_MAP_MODELS) - Error ("MAX_MAP_MODELS"); - mod = &dmodels[nummodels]; - - mod->firstface = numfaces; - - firstmodleaf = numleafs; - firstmodeledge = numedges; - firstmodelface = numfaces; - - // - // bound the brushes - // - e = &entities[entity_num]; - - start = e->firstbrush; - end = start + e->numbrushes; - ClearBounds (mins, maxs); - - for (j=start ; jnumsides) - continue; // not a real brush (origin brush) - AddPointToBounds (b->mins, mins, maxs); - AddPointToBounds (b->maxs, mins, maxs); - } - - VectorCopy (mins, mod->mins); - VectorCopy (maxs, mod->maxs); -} - - -/* -================== -EndModel -================== -*/ -void EndModel (void) -{ - dmodel_t *mod; - - mod = &dmodels[nummodels]; - - mod->numfaces = numfaces - mod->firstface; - - nummodels++; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/anorms.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/anorms.h deleted file mode 100644 index 65170ad9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/anorms.h +++ /dev/null @@ -1,162 +0,0 @@ - { -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 }, diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/images.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/images.c deleted file mode 100644 index ec4e99f3..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/images.c +++ /dev/null @@ -1,763 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" -#include "inout.h" - -char mip_prefix[1024]; // directory to dump the textures in - -qboolean colormap_issued; -byte colormap_palette[768]; - -/* -============== -RemapZero - -Replaces all 0 bytes in an image with the closest palette entry. -This is because NT won't let us change index 0, so any palette -animation leaves those pixels untouched. -============== -*/ -void RemapZero (byte *pixels, byte *palette, int width, int height) -{ - int i, c; - int alt_zero; - int value, best; - - alt_zero = 0; - best = 9999999; - for (i=1 ; i<255 ; i++) - { - value = palette[i*3+0]+palette[i*3+1]+palette[i*3+2]; - if (value < best) - { - best = value; - alt_zero = i; - } - } - - c = width*height; - for (i=0 ; ibyteimagewidth || 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 ; ybyteimagewidth || 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 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 = true; - - 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 -must be multiples of sixteen -SURF_WINDOW -============== -*/ -void Cmd_Mip (void) -{ - int x,y,xl,yl,xh,yh,w,h; - byte *screen_p, *source; - int linedelta; - miptex_t *qtex; - int miplevel, mipstep; - int xx, yy, pix; - int count; - int flags, value, contents; - mipparm_t *mp; - char lumpname[64]; - byte *lump_p; - char filename[1024]; - char animname[64]; - - GetToken (false); - strcpy (lumpname, token); - - GetToken (false); - xl = atoi (token); - GetToken (false); - yl = atoi (token); - GetToken (false); - w = atoi (token); - GetToken (false); - h = atoi (token); - - if ( (w & 15) || (h & 15) ) - Error ("line %i: miptex sizes must be multiples of 16", scriptline); - - flags = 0; - contents = 0; - value = 0; - - animname[0] = 0; - - // get optional flags and values - while (TokenAvailable ()) - { - GetToken (false); - - for (mp=mipparms ; mp->name ; mp++) - { - if (!strcmp(mp->name, token)) - { - switch (mp->type) - { - case pt_animvalue: - GetToken (false); // specify the next animation frame - strcpy (animname, token); - break; - case pt_flags: - flags |= mp->flags; - break; - case pt_contents: - contents |= mp->flags; - break; - case pt_flagvalue: - flags |= mp->flags; - GetToken (false); // specify the light value - value = atoi(token); - break; - } - break; - } - } - if (!mp->name) - Error ("line %i: unknown parm %s", scriptline, token); - } - - sprintf (filename, "%stextures/%s/%s.wal", gamedir, mip_prefix, lumpname); - if (g_release) - return; // textures are only released by $maps - - xh = xl+w; - yh = yl+h; - - qtex = malloc (sizeof(miptex_t) + w*h*2); - memset (qtex, 0, sizeof(miptex_t)); - - qtex->width = LittleLong(w); - qtex->height = LittleLong(h); - qtex->flags = LittleLong(flags); - qtex->contents = LittleLong(contents); - qtex->value = LittleLong(value); - sprintf (qtex->name, "%s/%s", mip_prefix, lumpname); - if (animname[0]) - sprintf (qtex->animname, "%s/%s", mip_prefix, animname); - - lump_p = (byte *)(&qtex->value+1); - - screen_p = byteimage + yl*byteimagewidth + xl; - linedelta = byteimagewidth - w; - - source = lump_p; - qtex->offsets[0] = LittleLong(lump_p - (byte *)qtex); - - for (y=yl ; yoffsets[miplevel] = LittleLong(lump_p - (byte *)qtex); - - mipstep = 1< /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/models.o : models.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/sprites.o : sprites.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/images.o : images.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/tables.o : tables.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i - -$(ODIR)/cmdlib.o : ../common/cmdlib.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/scriplib.o : ../common/scriplib.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/lbmlib.o : ../common/lbmlib.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/mathlib.o : ../common/mathlib.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/trilib.o : ../common/trilib.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/l3dslib.o : ../common/l3dslib.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i -$(ODIR)/threads.o : ../common/threads.c - cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i - cc $(CFLAGS) -o $@ /tmp/temp.i diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/models.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/models.c deleted file mode 100644 index 2316b0f6..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/models.c +++ /dev/null @@ -1,1152 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" -#include "inout.h" - -//================================================================= - -typedef struct -{ - int numnormals; - vec3_t normalsum; -} vertexnormals_t; - -typedef struct -{ - vec3_t v; - int lightnormalindex; -} trivert_t; - -typedef struct -{ - vec3_t mins, maxs; - char name[16]; - trivert_t v[MAX_VERTS]; -} frame_t; - -//================================================================ - -frame_t g_frames[MAX_FRAMES]; - -dmdl_t model; - - -float scale_up; // set by $scale -vec3_t adjust; // set by $origin -int g_fixedwidth, g_fixedheight; // set by $skinsize - - -// -// base frame info -// -vec3_t base_xyz[MAX_VERTS]; -dstvert_t base_st[MAX_VERTS]; -dtriangle_t triangles[MAX_TRIANGLES]; - -int triangle_st[MAX_TRIANGLES][3][2]; - -// the command list holds counts, s/t values, and xyz indexes -// that are valid for every frame -int commands[16384]; -int numcommands; -int numglverts; -int used[MAX_TRIANGLES]; - -char g_skins[MAX_MD2SKINS][64]; - -char cdarchive[1024]; -char cdpartial[1024]; -char cddir[1024]; - -char modelname[64]; // empty unless $modelname issued (players) - -#define NUMVERTEXNORMALS 162 - -float avertexnormals[NUMVERTEXNORMALS][3] = { -#include "anorms.h" -}; - -FILE *headerouthandle = NULL; - -//============================================================== - -/* -=============== -ClearModel -=============== -*/ -void ClearModel (void) -{ - memset (&model, 0, sizeof(model)); - - modelname[0] = 0; - scale_up = 1.0; - VectorCopy (vec3_origin, adjust); - g_fixedwidth = g_fixedheight = 0; - g_skipmodel = false; -} - - -void H_printf(char *fmt, ...) -{ - va_list argptr; - char name[1024]; - - if (!headerouthandle) - { - sprintf (name, "%s/tris.h", cddir); - headerouthandle = SafeOpenWrite (name); - fprintf(headerouthandle, "// %s\n\n", cddir); - fprintf(headerouthandle, "// This file generated by qdata - Do NOT Modify\n\n"); - } - - va_start (argptr, fmt); - vfprintf (headerouthandle, fmt, argptr); - va_end (argptr); -} - - -/* -============ -WriteModelFile -============ -*/ -void WriteModelFile (FILE *modelouthandle) -{ - int i; - dmdl_t modeltemp; - int j, k; - frame_t *in; - daliasframe_t *out; - byte buffer[MAX_VERTS*4+128]; - float v; - int c_on, c_off; - - model.ident = IDALIASHEADER; - model.version = ALIAS_VERSION; - model.framesize = (int)&((daliasframe_t *)0)->verts[model.num_xyz]; - model.num_glcmds = numcommands; - model.ofs_skins = sizeof(dmdl_t); - model.ofs_st = model.ofs_skins + model.num_skins * MAX_SKINNAME; - model.ofs_tris = model.ofs_st + model.num_st*sizeof(dstvert_t); - model.ofs_frames = model.ofs_tris + model.num_tris*sizeof(dtriangle_t); - model.ofs_glcmds = model.ofs_frames + model.num_frames*model.framesize; - model.ofs_end = model.ofs_glcmds + model.num_glcmds*4; - - // - // write out the model header - // - for (i=0 ; iname, in->name); - for (j=0 ; j<3 ; j++) - { - out->scale[j] = (in->maxs[j] - in->mins[j])/255; - out->translate[j] = in->mins[j]; - } - - for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; - - for (k=0 ; k<3 ; k++) - { - // scale to byte values & min/max check - v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); - - // clamp, so rounding doesn't wrap from 255.6 to 0 - if (v > 255.0) - v = 255.0; - if (v < 0) - v = 0; - out->verts[j].v[k] = v; - } - } - - for (j=0 ; j<3 ; j++) - { - out->scale[j] = LittleFloat (out->scale[j]); - out->translate[j] = LittleFloat (out->translate[j]); - } - - SafeWrite (modelouthandle, out, model.framesize); - } - - // - // write out glcmds - // - SafeWrite (modelouthandle, commands, numcommands*4); -} - - -/* -=============== -FinishModel -=============== -*/ -void FinishModel (void) -{ - FILE *modelouthandle; - int i; - char name[1024]; - - if (!model.num_frames) - return; - -// -// copy to release directory tree if doing a release build -// - if (g_release) - { - if (modelname[0]) - sprintf (name, "%s", modelname); - else - sprintf (name, "%s/tris.md2", cdpartial); - ReleaseFile (name); - - for (i=0 ; iindex_xyz[(startv)%3]; - strip_xyz[1] = last->index_xyz[(startv+1)%3]; - strip_xyz[2] = last->index_xyz[(startv+2)%3]; - strip_st[0] = last->index_st[(startv)%3]; - strip_st[1] = last->index_st[(startv+1)%3]; - strip_st[2] = last->index_st[(startv+2)%3]; - - strip_tris[0] = starttri; - stripcount = 1; - - m1 = last->index_xyz[(startv+2)%3]; - st1 = last->index_st[(startv+2)%3]; - m2 = last->index_xyz[(startv+1)%3]; - st2 = last->index_st[(startv+1)%3]; - - // look for a matching triangle -nexttri: - for (j=starttri+1, check=&triangles[starttri+1] - ; jindex_xyz[k] != m1) - continue; - if (check->index_st[k] != st1) - continue; - if (check->index_xyz[ (k+1)%3 ] != m2) - continue; - if (check->index_st[ (k+1)%3 ] != st2) - continue; - - // this is the next part of the fan - - // if we can't use this triangle, this tristrip is done - if (used[j]) - goto done; - - // the new edge - if (stripcount & 1) - { - m2 = check->index_xyz[ (k+2)%3 ]; - st2 = check->index_st[ (k+2)%3 ]; - } - else - { - m1 = check->index_xyz[ (k+2)%3 ]; - st1 = check->index_st[ (k+2)%3 ]; - } - - strip_xyz[stripcount+2] = check->index_xyz[ (k+2)%3 ]; - strip_st[stripcount+2] = check->index_st[ (k+2)%3 ]; - strip_tris[stripcount] = j; - stripcount++; - - used[j] = 2; - goto nexttri; - } - } -done: - - // clear the temp used flags - for (j=starttri+1 ; jindex_xyz[(startv)%3]; - strip_xyz[1] = last->index_xyz[(startv+1)%3]; - strip_xyz[2] = last->index_xyz[(startv+2)%3]; - strip_st[0] = last->index_st[(startv)%3]; - strip_st[1] = last->index_st[(startv+1)%3]; - strip_st[2] = last->index_st[(startv+2)%3]; - - strip_tris[0] = starttri; - stripcount = 1; - - m1 = last->index_xyz[(startv+0)%3]; - st1 = last->index_st[(startv+0)%3]; - m2 = last->index_xyz[(startv+2)%3]; - st2 = last->index_st[(startv+2)%3]; - - - // look for a matching triangle -nexttri: - for (j=starttri+1, check=&triangles[starttri+1] - ; jindex_xyz[k] != m1) - continue; - if (check->index_st[k] != st1) - continue; - if (check->index_xyz[ (k+1)%3 ] != m2) - continue; - if (check->index_st[ (k+1)%3 ] != st2) - continue; - - // this is the next part of the fan - - // if we can't use this triangle, this tristrip is done - if (used[j]) - goto done; - - // the new edge - m2 = check->index_xyz[ (k+2)%3 ]; - st2 = check->index_st[ (k+2)%3 ]; - - strip_xyz[stripcount+2] = m2; - strip_st[stripcount+2] = st2; - strip_tris[stripcount] = j; - stripcount++; - - used[j] = 2; - goto nexttri; - } - } -done: - - // clear the temp used flags - for (j=starttri+1 ; j bestlen) - { - besttype = type; - bestlen = len; - for (j=0 ; j= 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_fixedwidth / 2; - iheight = g_fixedheight; - - s_scale = (float)(iwidth-4) / width; - t_scale = (float)(iheight-4) / height; - } - -// -// determine which side of each triangle to map the texture to -// - for (i=0 ; i 0) - { - basex = iwidth + 2; - } - else - { - basex = 2; - } - basey = 2; - - for (j=0 ; j<3 ; j++) - { - pbasevert = ptri[i].verts[j]; - - triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); - triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); - } - } - -// make the width a multiple of 4; some hardware requires this, and it ensures -// dword alignment for each scan - swidth = iwidth*2; - model.skinwidth = (swidth + 3) & ~3; - model.skinheight = iheight; -} - - -/* -================= -Cmd_Base -================= -*/ -void Cmd_Base (void) -{ - triangle_t *ptri; - int i, j, k; - int time1; - char file1[1024]; - - GetToken (false); - - if (g_skipmodel || g_release || g_archive) - return; - - printf ("---------------------\n"); - sprintf (file1, "%s/%s.%s", cdarchive, token, trifileext); - printf ("%s\n", file1); - - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s.%s", cddir, token, trifileext); - - time1 = FileTime (file1); - if (time1 == -1) - Error ("%s doesn't exist", file1); - -// -// load the base triangles -// - if (do3ds) - Load3DSTriangleList (file1, &ptri, &model.num_tris); - else - LoadTriangleList (file1, &ptri, &model.num_tris); - -// -// get the ST values -// - BuildST (ptri, model.num_tris); - -// -// run through all the base triangles, storing each unique vertex in the -// base vertex list and setting the indirect triangles to point to the base -// vertices -// - for (i=0 ; i= '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.%s",cddir, base, suffix, trifileext); - time1 = FileTime (file1); - if (time1 != -1) - { - sprintf (retname, "%s%s.%s", base, suffix, trifileext); - return retname; - } - - // check for 'run.1' - sprintf (file1, "%s/%s.%s",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; -} - -/* -=============== -GrabFrame -=============== -*/ -void GrabFrame (char *frame) -{ - triangle_t *ptri; - int i, j; - trivert_t *ptrivert; - int num_tris; - char file1[1024]; - frame_t *fr; - vertexnormals_t vnorms[MAX_VERTS]; - int index_xyz; - char *framefile; - - // the frame 'run1' will be looked for as either - // run.1 or run1.tri, so the new alias sequence save - // feature an be used - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - - printf ("grabbing %s\n", file1); - - if (model.num_frames >= MAX_FRAMES) - Error ("model.num_frames >= MAX_FRAMES"); - fr = &g_frames[model.num_frames]; - model.num_frames++; - - strcpy (fr->name, frame); - -// -// load the frame -// - if (do3ds) - Load3DSTriangleList (file1, &ptri, &num_tris); - else - LoadTriangleList (file1, &ptri, &num_tris); - - if (num_tris != model.num_tris) - Error ("%s: number of triangles doesn't match base frame\n", file1); - -// -// allocate storage for the frame's vertices -// - ptrivert = fr->v; - - for (i=0 ; imins, fr->maxs); - -// -// 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 ; imins, fr->maxs); - - VectorAdd (vnorms[index_xyz].normalsum, normal, vnorms[index_xyz].normalsum); - vnorms[index_xyz].numnormals++; - } - } - -// -// calculate the vertex normals, match them to the template list, and store the -// index of the best match -// - for (i=0 ; i maxdot) - { - maxdot = dot; - maxdotindex = j; - } - } - - ptrivert[i].lightnormalindex = maxdotindex; - } - - free (ptri); -} - -/* -=============== -Cmd_Frame -=============== -*/ -void Cmd_Frame (void) -{ - while (TokenAvailable()) - { - GetToken (false); - if (g_skipmodel) - continue; - if (g_release || g_archive) - { - model.num_frames = 1; // don't skip the writeout - continue; - } - - H_printf("#define FRAME_%-16s\t%i\n", token, model.num_frames); - - GrabFrame (token); - } -} - - -/* -=============== -Cmd_Skin - -Skins aren't actually stored in the file, only a reference -is saved out to the header file. -=============== -*/ -void Cmd_Skin (void) -{ - byte *palette; - byte *pixels; - int width, height; - byte *cropped; - int y; - char name[1024], savename[1024]; - - GetToken (false); - - if (model.num_skins == MAX_MD2SKINS) - Error ("model.num_skins == MAX_MD2SKINS"); - - if (g_skipmodel) - return; - - sprintf (name, "%s/%s.lbm", cdarchive, token); - strcpy (name, ExpandPathAndArchive( name ) ); -// sprintf (name, "%s/%s.lbm", cddir, token); - - if (TokenAvailable()) - { - GetToken (false); - sprintf (g_skins[model.num_skins], "%s.pcx", token); - sprintf (savename, "%s%s.pcx", gamedir, g_skins[model.num_skins]); - } - else - { - sprintf (savename, "%s/%s.pcx", cddir, token); - sprintf (g_skins[model.num_skins], "%s/%s.pcx", cdpartial, token); - } - - model.num_skins++; - - if (g_skipmodel || g_release || g_archive) - return; - - // load the image - printf ("loading %s\n", name); - Load256Image (name, &pixels, &palette, &width, &height); - RemapZero (pixels, palette, width, height); - - // crop it to the proper size - cropped = malloc (model.skinwidth*model.skinheight); - for (y=0 ; y= sizeof(pf->name)) - Error ("Filename too long for pak: %s", filename); - - len = LoadFile (source, (void **)&buf); - - if (g_compress_pak && len < 4096*1024 ) - { - cblock_t in, out; - cblock_t Huffman (cblock_t in); - - in.count = len; - in.data = buf; - - out = Huffman (in); - - if (out.count < in.count) - { - printf (" compressed from %i to %i\n", in.count, out.count); - free (in.data); - buf = out.data; - len = out.count; - } - else - free (out.data); - } - - strcpy (pf->name, filename); - pf->filepos = LittleLong(ftell(pakfile)); - pf->filelen = LittleLong(len); - pf++; - - SafeWrite (pakfile, buf, len); - - free (buf); -} - - -/* -============== -FinishPak -============== -*/ -void FinishPak (void) -{ - int dirlen; - int d; - int i; - unsigned checksum; - - if (!g_pak) - return; - - pakheader.id[0] = 'P'; - pakheader.id[1] = 'A'; - pakheader.id[2] = 'C'; - pakheader.id[3] = 'K'; - dirlen = (byte *)pf - (byte *)pfiles; - pakheader.dirofs = LittleLong(ftell(pakfile)); - pakheader.dirlen = LittleLong(dirlen); - - checksum = Com_BlockChecksum ( (void *)pfiles, dirlen ); - - SafeWrite (pakfile, pfiles, dirlen); - - i = ftell (pakfile); - - fseek (pakfile, 0, SEEK_SET); - SafeWrite (pakfile, &pakheader, sizeof(pakheader)); - fclose (pakfile); - - d = pf - pfiles; - printf ("%i files packed in %i bytes\n",d, i); - printf ("checksum: 0x%x\n", checksum); -} - - -/* -=============== -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 (false); - 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 -#include - -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 ; id_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 (false); - 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= argc) - Error ("usage: %s [-archive ] [-release ] [-only ] [-3ds] file.qgr", argv[ 0 ] ); - - if (do3ds) - trifileext = ext_3ds; - else - trifileext = ext_tri; - - for ( ; i -#include -#include -#include -#include - -#include "cmdlib.h" -#include "scriplib.h" -#include "mathlib.h" -#include "trilib.h" -#include "lbmlib.h" -#include "q2_threads.h" -#include "l3dslib.h" -#include "bspfile.h" - -#ifdef WIN32 - #ifdef NDEBUG // Don't show in a Release build - #pragma warning(disable : 4305) // truncate from double to float - #pragma warning(disable : 4244) // conversion from double to float - #pragma warning(disable : 4018) // signed/unsigned mismatch - #endif -#endif - -void Cmd_Modelname (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_Skin (void); -void Cmd_Skinsize (void); -void FinishModel (void); - -void Cmd_Inverse16Table( void ); - -void Cmd_SpriteName (void); -void Cmd_Load (void); -void Cmd_SpriteFrame (void); -void FinishSprite (void); - -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_Alphalight (void); - -void Cmd_Video (void); - -void RemapZero (byte *pixels, byte *palette, int width, int height); - -void ReleaseFile (char *filename); - -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 char *trifileext; diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/sprites.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/sprites.c deleted file mode 100644 index a70f0074..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/sprites.c +++ /dev/null @@ -1,228 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" -#include "inout.h" - -#define MAX_SPRFRAMES MAX_MD2SKINS - -dsprite_t sprite; -dsprframe_t frames[MAX_SPRFRAMES]; - -byte *byteimage, *lbmpalette; -int byteimagewidth, byteimageheight; - -char spritename[1024]; - - -void FinishSprite (void); -void Cmd_Spritename (void); - - - -/* -============== -FinishSprite -============== -*/ -void FinishSprite (void) -{ - FILE *spriteouthandle; - int i, curframe; - dsprite_t spritetemp; - char savename[1024]; - - if (sprite.numframes == 0) - return; - - if (!strlen(spritename)) - Error ("Didn't name sprite file"); - - sprintf (savename, "%s%s.sp2", gamedir, spritename); - - if (g_release) - { - char name[1024]; - - sprintf (name, "%s.sp2", spritename); - ReleaseFile (name); - spritename[0] = 0; // clear for a new sprite - sprite.numframes = 0; - return; - } - - - printf ("saving in %s\n", savename); - CreatePath (savename); - spriteouthandle = SafeOpenWrite (savename); - - -// -// write out the sprite header -// - spritetemp.ident = LittleLong (IDSPRITEHEADER); - spritetemp.version = LittleLong (SPRITE_VERSION); - spritetemp.numframes = LittleLong (sprite.numframes); - - SafeWrite (spriteouthandle, &spritetemp, 12); - -// -// write out the frames -// - curframe = 0; - - for (i=0 ; i 256) || (h > 256)) - Error ("Sprite has a dimension longer than 256"); - - xh = xl+w; - yh = yl+h; - - if (sprite.numframes >= MAX_SPRFRAMES) - Error ("Too many frames; increase MAX_SPRFRAMES\n"); - - pframe = &frames[sprite.numframes]; - pframe->width = w; - pframe->height = h; - pframe->origin_x = ox; - pframe->origin_y = oy; - sprintf (pframe->name, "%s_%i.pcx", spritename, sprite.numframes); - sprintf (savename, "%s%s_%i.pcx", gamedir, spritename, sprite.numframes); - sprite.numframes++; - - if (g_release) - { - ReleaseFile (pframe->name); - return; - } - - // crop it to the proper size - cropped = malloc (w*h); - for (y=0 ; y> 5 ) & 63 ) << 2; - b[0] = ( ( color >> 11 ) & 31 ) << 3; - - for ( i = 0; i < 256; i++ ) - { - r[1] = ( d_8to24table[i] >> 0 ) & 0xFF; - g[1] = ( d_8to24table[i] >> 8 ) & 0xFF; - b[1] = ( d_8to24table[i] >> 16 ) & 0xFF; - - d = ( r[1] - r[0] ) * ( r[1] - r[0] ) + - ( g[1] - g[0] ) * ( g[1] - g[0] ) + - ( b[1] - b[0] ) * ( b[1] - b[0] ); - - if ( d < closest_distance_so_far ) - { - closest_distance_so_far = d; - closest_so_far = i; - } - } - - return closest_so_far; -} -*/ - -extern byte BestColor( int, int, int, int, int ); - -void Inverse16_BuildTable( void ) -{ - int i; - - /* - ** create the 16-to-8 table - */ - for ( i = 0; i < 65536; i++ ) - { - int r = i & 31; - int g = ( i >> 5 ) & 63; - int b = ( i >> 11 ) & 31; - - r <<= 3; - g <<= 2; - b <<= 3; - - inverse16to8table[i] = BestColor( r, g, b, 0, 255 ); - } -} - -void Alphalight_Thread (int i) -{ - int j; - float r, g, b; - float mr, mg, mb, ma; - float distortion, bestdistortion; - float v; - - r = (i>>10) * (1.0/16); - g = ((i>>5)&31) * (1.0/16); - b = (i&31) * (1.0/16); - - bestdistortion = 999999; - for (j=0 ; j<16*16*16*16 ; j++) - { - mr = (j>>12) * (1.0/16); - mg = ((j>>8)&15) * (1.0/16); - mb = ((j>>4)&15) * (1.0/16); - ma = (j&15) * (1.0/16); - - v = r * 0.5 - (mr*ma + 0.5*(1.0-ma)); - distortion = v*v; - v = g * 0.5 - (mg*ma + 0.5*(1.0-ma)); - distortion += v*v; - v = b * 0.5 - (mb*ma + 0.5*(1.0-ma)); - distortion += v*v; - - distortion *= 1.0 + ma*4; - - if (distortion < bestdistortion) - { - bestdistortion = distortion; - alphamap[i] = j; - } - } -} - -void Cmd_Alphalight (void) -{ - char savename[1024]; - - GetToken (false); - - if (g_release) - { - ReleaseFile (token); - return; - } - - sprintf (savename, "%s%s", gamedir, token); - printf ("Building alphalight table...\n"); - - RunThreadsOnIndividual (32*32*32, true, Alphalight_Thread); - - SaveFile (savename, (byte *)alphamap, sizeof(alphamap)); -} - - -void Cmd_Inverse16Table( void ) -{ - char savename[1024]; - - if ( g_release ) - { - sprintf (savename, "pics/16to8.dat"); - ReleaseFile( savename ); - return; - } - - sprintf (savename, "%spics/16to8.dat", gamedir); - printf ("Building inverse 16-to-8 table...\n"); - - Inverse16_BuildTable(); - - SaveFile( savename, (byte *) inverse16to8table, sizeof( inverse16to8table ) ); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/video.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/video.c deleted file mode 100644 index c4027171..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata/video.c +++ /dev/null @@ -1,1259 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" -#include "inout.h" - -byte *soundtrack; -char 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; - - -int samplecounts[0x10000]; - -wavinfo_t 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; - - soundtrack = NULL; - sprintf (name, "%svideo/%s/%s.wav", gamedir, base, base); - printf ("%s\n", name); - f = fopen (name, "rb"); - if (!f) - { - printf ("no soundtrack for %s\n", base); - return; - } - len = Q_filelength(f); - soundtrack = malloc(len); - fread (soundtrack, 1, len, f); - fclose (f); - - wavinfo = GetWavinfo (name, soundtrack, len); - - // count samples for compression - memset (samplecounts, 0, sizeof(samplecounts)); - - j = wavinfo.samples/2; - for (i=0 ; i wavinfo.samples || !soundtrack) - fwrite (&empty, 1, width, output); - else - fwrite (soundtrack + wavinfo.dataofs + sample*width, 1, width,output); - } -} - -//========================================================================== - -/* -================== -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 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>8)&255; - *out_p++ = (in.count>>16)&255; - *out_p++ = (in.count>>24)&255; - - // write head index - for (i=0 ; i>8)&255; - *out_p++ = (i>>16)&255; - *out_p++ = (i>>24)&255; - - // write the L column - for (i=0 ; i 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 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>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 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) - max = in.count - i; - - start = lzss_head[val]; - while (start != -1 && start >= i-BACK_WINDOW) - { - // count match length - for (j=0 ; 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 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<>3] |= 1<<(outbits&7); - } - else - { // output a phrase - outbits++; // leave a 0 bit to mark phrase - for (j=0 ; j>3] |= 1<<(outbits&7); - for (j=0 ; j>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 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 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 max) - max = hnodes1[i][j].count; - } - if (max == 0) - max = 1; - total = 0; - for (j=0 ; j 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>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<>3] |= 1<<(outbits&7); - outbits++; - } - i += rept-1; - } -#endif - } - - out_p += (outbits+7)>>3; - - out.count = out_p - out.data; - - return out; -} - -//========================================================================== - - -/* -=================== -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.pcx", gamedir, base, base, ten3, ten2, ten1, ten0); - else - sprintf (name, "%svideo/%s/%s%i%i%i.pcx", gamedir, base, base, ten2, ten1, ten0); - - f = fopen(name, "rb"); - if (!f) - { - in.data = NULL; - return in; - } - fclose (f); - - printf ("%s\n", name); - Load256Image (name, &in.data, palette, &width, &height); - in.count = width*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) -{ - char savename[1024]; - char name[1024]; - FILE *output; - int startframe, frame; - byte *palette; - int width, height; - byte current_palette[768]; - int command; - int i; - int digits; - cblock_t in, huffman; - int swap; - - - GetToken (false); - strcpy (base, token); - if (g_release) - { -// sprintf (savename, "video/%s.cin", token); -// ReleaseFile (savename); - return; - } - - GetToken (false); - digits = atoi(token); - - // optionally skip frames - if (TokenAvailable ()) - { - GetToken (false); - startframe = atoi(token); - } - else - startframe=0; - - sprintf (savename, "%svideo/%s.cin", gamedir, base); - - - // clear stuff - memset (charbits1, 0, sizeof(charbits1)); - memset (charbitscount1, 0, sizeof(charbitscount1)); - memset (hnodes1, 0, sizeof(hnodes1)); - memset (numhnodes1, 0, sizeof(numhnodes1)); - memset (order0counts, 0, sizeof(order0counts)); - - - // load the entire sound wav file if present - LoadSoundtrack (); - - if (digits == 4) - sprintf (name, "%svideo/%s/%s0000.pcx", gamedir, base, base); - else - sprintf (name, "%svideo/%s/%s000.pcx", gamedir, base, base); - - printf ("%s\n", name); - Load256Image (name, NULL, &palette, &width, &height); - - output = fopen (savename, "wb"); - if (!output) - Error ("Can't open %s", savename); - - // write header info - i = LittleLong (width); - fwrite (&i, 4, 1, output); - i = LittleLong (height); - fwrite (&i, 4, 1, output); - i = LittleLong (wavinfo.rate); - fwrite (&i, 4, 1, output); - i = LittleLong (wavinfo.width); - fwrite (&i, 4, 1, output); - i = LittleLong (wavinfo.channels); - fwrite (&i, 4, 1, output); - - // build the dictionary - for ( frame=startframe ; ; frame++) - { - printf ("counting ", frame); - in = LoadFrame (base, frame, digits, &palette); - if (!in.data) - break; - Huffman1_Count (in); - free (in.data); - } - printf ("\n"); - - // build nodes and write counts - Huffman1_Build (output); - - - memset (current_palette, 0, sizeof(current_palette)); - - // compress it with the dictionary - for (frame=startframe ; ; frame++) - { - printf ("packing ", frame); - in = LoadFrame (base, frame, digits, &palette); - if (!in.data) - break; - - // see if the palette has changed - for (i=0 ; i<768 ; i++) - if (palette[i] != current_palette[i]) - { - // write a palette change - memcpy (current_palette, palette, sizeof(current_palette)); - command = LittleLong(1); - fwrite (&command, 1, 4, output); - fwrite (current_palette, 1, sizeof(current_palette), output); - break; - } - if (i == 768) - { - command = 0; // no palette change - fwrite (&command, 1, 4, output); - } - - // save the image - huffman = Huffman1 (in); - printf ("%5i bytes after huffman1\n", huffman.count); - - swap = LittleLong (huffman.count); - fwrite (&swap, 1, sizeof(swap), output); - - fwrite (huffman.data, 1, huffman.count, output); - - // save some sound samples - WriteSound (output, frame); - - free (palette); - free (in.data); - free (huffman.data); - } - printf ("\n"); - - // write end-of-file command - command = 2; - fwrite (&command, 1, 4, output); - - printf ("Total size: %i\n", ftell (output)); - - fclose (output); - - if (soundtrack) - free (soundtrack); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/adpcm.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/adpcm.h deleted file mode 100644 index e70f9664..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/adpcm.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -/* -** adpcm.h - include file for adpcm coder. -** -** Version 1.0, 7-Jul-92. -** -** Modded 10/3/98 -** John Scott -*/ - -typedef struct adpcm_state_s -{ - short in_valprev; // Previous output value - short in_index; // Index into stepsize table - short out_valprev; // Previous output value - short out_index; // Index into stepsize table - int count; // Number of sample counts -} adpcm_state_t; - -typedef struct adpcm_s -{ - adpcm_state_t state; - char adpcm[0x10000]; -} adpcm_t; - -void adpcm_coder(short [], adpcm_t *); -void adpcm_decoder(adpcm_t *, short []); - -// end diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/animcomp.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/animcomp.c deleted file mode 100644 index 6af022f6..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/animcomp.c +++ /dev/null @@ -1,351 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#include -#include -#include "animcomp.h" - - -void *SafeMalloc(size_t n, char *desc); - - - -float *matrix; -float *delta; -float *best; -float *comp; -float *tcomp; -float *bestcomp; -float *frames; -float *base; - -int MatWidth; -int MatHeight; -int CFrameSize; -int nFrames; - - -void AnimCompressInit(int nframes,int nVerts,int CompressedFrameSize) -{ - nFrames=nframes; - MatWidth=nVerts*3; - MatHeight=CompressedFrameSize; - CFrameSize=CompressedFrameSize; - matrix=(float *)SafeMalloc(MatWidth*MatHeight*sizeof(float), "AnimCompressInit"); - best=(float *)SafeMalloc(MatWidth*MatHeight*sizeof(float), "AnimCompressInit"); - delta=(float *)SafeMalloc(MatWidth*MatHeight*sizeof(float), "AnimCompressInit"); - comp=(float *)SafeMalloc(CFrameSize*nFrames*sizeof(float), "AnimCompressInit"); - tcomp=(float *)SafeMalloc(CFrameSize*nFrames*sizeof(float), "AnimCompressInit"); - bestcomp=(float *)SafeMalloc(CFrameSize*nFrames*sizeof(float), "AnimCompressInit"); - base=(float *)SafeMalloc(MatWidth*sizeof(float), "AnimCompressInit"); - frames=(float *)SafeMalloc(MatWidth*nFrames*sizeof(float), "AnimCompressInit"); -} - -void AnimSetFrame(int frame,int index,float x,float y,float z) -{ - frames[frame*MatWidth+index*3]=x; - frames[frame*MatWidth+index*3+1]=y; - frames[frame*MatWidth+index*3+2]=z; -} - -typedef struct -{ - int index; - float val; -} SORTP; - - -#define F_RANDOM (((float)rand())/(float)RAND_MAX) - -extern void DOsvd(float *a,float *res,float *comp,float *values,int nframes,int framesize,int compressedsize); - -void AnimCompressDoit() -{ - float compression; - float *rescale; - float *ans; - float maxdev; - float avedev; - float tmp; - int j,k,l,numave; - - for (k=0;kmaxdev) - maxdev=tmp; - avedev+=tmp; - numave++; - } - } - avedev/=(float)numave; -printf("%f Max Deviation (inches) %f Ave Dev. (inches)\n",maxdev,avedev); -printf("%d bytes original size\n",MatWidth*nFrames); -printf("%d bytes of overhead\n",MatWidth*MatHeight); -printf("%d bytes/frame * %d frames = %d bytes\n",CFrameSize,nFrames,CFrameSize*nFrames); - compression=(float)(MatWidth*MatHeight+CFrameSize*nFrames+MatWidth); - compression/=(float)(MatWidth*nFrames); -printf("Overall compression = %f %%\n",100.0f-100.0f*compression); - compression=(float)(CFrameSize); - compression/=(float)(MatWidth); -printf("frame size compression = %f %%\n",100.0f-100.0f*compression); - free(rescale); - free(ans); -} - -void AnimCompressToBytes(float *trans,float *scale,char *mat,char *ccomp,unsigned char *cbase,float *cscale,float *coffset,float *bmin,float *bmax) -{ - int k,l,nv,j; - float maxdev; - float avedev; - float tmp; - int numave; - float t,mx; - float *ans; - - - nv=MatWidth/3; - - trans[0]=1E30f; - scale[0]=-1E30f; - trans[1]=1E30f; - scale[1]=-1E30f; - trans[2]=1E30f; - scale[2]=-1E30f; - for (k=0;kscale[0]) - scale[0]=base[k]; - if (base[k]scale[1]) - scale[1]=base[k+1]; - if (base[k+1]scale[2]) - scale[2]=base[k+2]; - if (base[k+2]255.0f) - t=255.0f; - cbase[k]=(unsigned char)t; - - t=(base[k+1]-trans[1])/scale[1]; - if (t<0.0f) - t=0.0f; - if (t>255.0f) - t=255.0f; - cbase[k+1]=(unsigned char)t; - - t=(base[k+2]-trans[2])/scale[2]; - if (t<0.0f) - t=0.0f; - if (t>255.0f) - t=255.0f; - cbase[k+2]=(unsigned char)t; - } - for (l=0;lmx) - mx=(float)fabs(best[l*MatWidth+k]); - } - if (mx>1E-8) - { - mx/=127.0f; - coffset[l]=1E30f; - cscale[l]=-1E30f; - for (j=0;jcscale[l]) - cscale[l]=bestcomp[j*MatHeight+l]; - if (bestcomp[j*MatHeight+l]1E-10) - { - for (j=0;j127.0f) - tmp=127.0f; - if (tmp<-127.0f) - tmp=-127.0f; - ccomp[j*MatHeight+l]=(char)floor(tmp+0.5); - } - coffset[l]+=cscale[l]*127.0f/254.0f; - cscale[l]/=254.0f; - } - else - { - cscale[l]=1.0f; - coffset[l]=0.0f; - for (j=0;j127.0f) - tmp=127.0f; - if (tmp<-127.0f) - tmp=-127.0f; - mat[k*MatHeight+l]=(char)floor(tmp+0.5); - } - } - else - { - cscale[l]=1.0f; - coffset[l]=0.0f; - for (j=0;jmaxdev) - maxdev=tmp; - avedev+=tmp; - numave++; - - if (bmin[k%3]>ans[k]) - bmin[k%3]=ans[k]; - if (bmax[k%3]version = MIP_VERSION; - - for(i=j=0;i<256;i++,j+=3) - { - mp->palette[i].r = palette[j]; - mp->palette[i].g = palette[j+1]; - mp->palette[i].b = palette[j+2]; - } - pos = (byte *)(mp + 1); - - mp->width[0] = w; - mp->height[0] = h; - mp->offsets[0] = sizeof(*mp); - memcpy(pos, buffer, w * h); - - *FinalSize = size; - return(mp); -} - -miptex32_t *CreateBook32(long *buffer, int w, int h, int *FinalSize) -{ - miptex32_t *mp; - byte *pos; - int size; - - size = sizeof(*mp) + (w * h * 4); - mp = (miptex32_t *)SafeMalloc(size, "CreateBook32"); - memset(mp, 0, size); - - mp->version = MIP32_VERSION; - - pos = (byte *)(mp + 1); - - mp->width[0] = w; - mp->height[0] = h; - mp->offsets[0] = sizeof(*mp); - memcpy(pos, buffer, w * h * 4); - - *FinalSize = size; - return(mp); -} - - -// Routines to chop a random sized image into gl texture friendly chunks - -typedef struct rect_s -{ - int x, y; - int w, h; - char name[4]; -} rect_t; - -int GetCoords(int x, int store[MAX_MD2SKINS]) -{ - int index, start, delta; - - index = 0; - start = 0; - delta = 256; - - store[index++] = start; - while(x) - { - if(x >= delta) - { - start += delta; - store[index++] = start; - x -= delta; - } - else - { - delta >>= 1; - } - } - return(index); -} - -int ChopImage(int w, int h, rect_t coords[MAX_MD2SKINS]) -{ - int xs[MAX_MD2SKINS], ys[MAX_MD2SKINS]; - int xcount, ycount, x, y, index; - - index = 0; - xcount = GetCoords(w, xs) - 1; - ycount = GetCoords(h, ys) - 1; - - for(y = 0; y < ycount; y++) - { - for(x = 0; x < xcount; x++, index++) - { - coords[index].x = xs[x]; - coords[index].y = ys[y]; - coords[index].w = xs[x + 1] - xs[x]; - coords[index].h = ys[y + 1] - ys[y]; - coords[index].name[0] = x + '0'; - coords[index].name[1] = y + '0'; - coords[index].name[2] = 0; - } - } - return(index); -} - -/* -=============== -Cmd_Pic -=============== -*/ - -void Cmd_Book() -{ - int xl,yl,xh,yh,w,h; - byte *dest, *source; - int flags, value, contents; - char lumpname[64]; - char filename[1024]; - unsigned long *destl, *sourcel; - int linedelta, x, y; - int size; - miptex_t *qtex; - miptex32_t *qtex32; - float scale_x, scale_y; - int numrects, i; - rect_t coords[MAX_MD2SKINS]; - bookframe_t bframes[MAX_MD2SKINS]; - bookframe_t *bf; - book_t book; - - GetScriptToken (false); - strcpy (lumpname, token); - - GetScriptToken (false); - xl = atoi (token); - GetScriptToken (false); - yl = atoi (token); - GetScriptToken (false); - w = atoi (token); - GetScriptToken (false); - h = atoi (token); - - total_x += w; - total_y += h; - total_textures++; - - if ( (w & 7) || (h & 7) ) - Error ("line %i: miptex sizes must be multiples of 8", scriptline); - - flags = 0; - contents = 0; - value = 0; - - scale_x = scale_y = 0.5; - - if (g_release) - return; - - if(TrueColorImage) - { - xh = xl + w; - yh = yl + h; - - if (xl >= longimagewidth || xh > longimagewidth || - yl >= longimageheight || yh > longimageheight) - { - Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,longimagewidth,longimageheight); - } - - sourcel = (unsigned long *) longimage + (yl * longimagewidth) + xl; - destl = (unsigned long *) longimage; - linedelta = (longimagewidth - w); - - for(y = yl; y < yh; y++) - { - for(x = xl; x < xh; x++) - { - *destl++ = *sourcel++; // RGBA - } - sourcel += linedelta; - } - - // Get rectangles to chop into - numrects = ChopImage(w, h, coords); - - bf = bframes; - for(i = 0; i < numrects; i++, bf++) - { - // Copy section of image to buffer - sourcel = (unsigned long *) longimage + (coords[i].y * w) + coords[i].x; - destl = bufferl; - linedelta = w - coords[i].w; - - for(y = 0; y < coords[i].h; y++) - { - for(x = 0; x < coords[i].w; x++) - { - *destl++ = *sourcel++; - } - sourcel += linedelta; - } - - qtex32 = CreateBook32(bufferl, coords[i].w, coords[i].h, &size); - - qtex32->flags = flags; - qtex32->contents = contents; - qtex32->value = value; - qtex32->scale_x = scale_x; - qtex32->scale_y = scale_y; - - sprintf (filename, "%sbook/%s/%s_%s.m32", gamedir, book_prefix, lumpname, coords[i].name); - sprintf (qtex32->name, "%s/%s_%s.m32", book_prefix, lumpname, coords[i].name); - - strcpy(bf->name, qtex32->name); - bf->x = coords[i].x; - bf->y = coords[i].y; - bf->w = coords[i].w; - bf->h = coords[i].h; - // - // write it out - // - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex32, size); - - free (qtex32); - } - } - else - { - xh = xl + w; - yh = yl + h; - - if (xl >= byteimagewidth || xh > byteimagewidth || - yl >= byteimageheight || yh > byteimageheight) - { - Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); - } - - // Copy image to top left - source = byteimage + yl*byteimagewidth + xl; - dest = byteimage; - linedelta = byteimagewidth - w; - - for(y = yl; y < yh; y++) - { - for(x = xl; x < xh; x++) - { - *dest++ = *source++; - } - source += linedelta; - } - - // Get rectangles to chop into - numrects = ChopImage(w, h, coords); - - bf = bframes; - for(i = 0; i < numrects; i++, bf++) - { - // Copy section of image to buffer - source = byteimage + (coords[i].y * w) + coords[i].x; - dest = buffer; - linedelta = w - coords[i].w; - - for(y = 0; y < coords[i].h; y++) - { - for(x = 0; x < coords[i].w; x++) - { - *dest++ = *source++; - } - source += linedelta; - } - - qtex = CreateBook8(buffer, coords[i].w, coords[i].h, lbmpalette, &size); - - qtex->flags = flags; - qtex->contents = contents; - qtex->value = value; - - sprintf (filename, "%sbook/%s/%s_%s.m8", gamedir, book_prefix, lumpname, coords[i].name); - sprintf (qtex->name, "%s/%s_%s.m8", book_prefix, lumpname, coords[i].name); - - strcpy(bf->name, qtex->name); - bf->x = coords[i].x; - bf->y = coords[i].y; - bf->w = coords[i].w; - bf->h = coords[i].h; - // - // write it out - // - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex, size); - - free (qtex); - } - } - // Set up descriptor - size = sizeof(bookframe_t) * numrects; - - book.bheader.ident = IDBOOKHEADER; - book.bheader.version = BOOK_VERSION; - book.bheader.num_segments = numrects; - book.bheader.total_w = w; - book.bheader.total_h = h; - memcpy(book.bframes, bframes, size); - - // Save out segment descriptor - sprintf (filename, "%sBook/%s/%s.bk", gamedir, book_prefix, lumpname); - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)&book, size + sizeof(bookheader_t)); -} - -/* -=============== -Cmd_picdir -=============== -*/ -void Cmd_Bookdir (void) -{ - char filename[1024]; - - GetScriptToken (false); - strcpy (book_prefix, token); - // create the directory if needed - sprintf (filename, "%sBook", gamedir); - Q_mkdir (filename); - sprintf (filename, "%sBook/%s", gamedir, book_prefix); - Q_mkdir (filename); -} - -// end diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.c deleted file mode 100644 index 146e03f3..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.c +++ /dev/null @@ -1,793 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#include "mathlib.h" -#include "bspfile.h" -#include "scriplib.h" - -void GetLeafNums (void); - -//============================================================================= - -int nummodels; -dmodel_t dmodels[MAX_MAP_MODELS]; - -int visdatasize; -byte dvisdata[MAX_MAP_VISIBILITY]; -dvis_t *dvis = (dvis_t *)dvisdata; - -int lightdatasize; -byte dlightdata[MAX_MAP_LIGHTING]; - -int entdatasize; -char dentdata[MAX_MAP_ENTSTRING]; - -int numleafs; -dleaf_t dleafs[MAX_MAP_LEAFS]; - -int numplanes; -dplane_t dplanes[MAX_MAP_PLANES]; - -int numvertexes; -dvertex_t dvertexes[MAX_MAP_VERTS]; - -int numnodes; -dnode_t dnodes[MAX_MAP_NODES]; - -int numtexinfo; -texinfo_t texinfo[MAX_MAP_TEXINFO]; - -int numfaces; -dface_t dfaces[MAX_MAP_FACES]; - -int numedges; -dedge_t dedges[MAX_MAP_EDGES]; - -int numleaffaces; -unsigned short dleaffaces[MAX_MAP_LEAFFACES]; - -int numleafbrushes; -unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; - -int numsurfedges; -int dsurfedges[MAX_MAP_SURFEDGES]; - -int numbrushes; -dbrush_t dbrushes[MAX_MAP_BRUSHES]; - -int numbrushsides; -dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; - -int numareas; -darea_t dareas[MAX_MAP_AREAS]; - -int numareaportals; -dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; - -byte dpop[256]; - -/* -=============== -CompressVis - -=============== -*/ -int CompressVis (byte *vis, byte *dest) -{ - int j; - int rep; - int visrow; - byte *dest_p; - - dest_p = dest; -// visrow = (r_numvisleafs + 7)>>3; - visrow = (dvis->numclusters + 7)>>3; - - for (j=0 ; j>3; - row = (dvis->numclusters+7)>>3; - out = decompressed; - - do - { - if (*in) - { - *out++ = *in++; - continue; - } - - c = in[1]; - if (!c) - Error ("DecompressVis: 0 repeat"); - in += 2; - while (c) - { - *out++ = 0; - c--; - } - } while (out - decompressed < row); -} - -//============================================================================= - -/* -============= -SwapBSPFile - -Byte swaps all data in a bsp file. -============= -*/ -void SwapBSPFile (qboolean todisk) -{ - int i, j; - dmodel_t *d; - - -// models - for (i=0 ; ifirstface = LittleLong (d->firstface); - d->numfaces = LittleLong (d->numfaces); - d->headnode = LittleLong (d->headnode); - - for (j=0 ; j<3 ; j++) - { - d->mins[j] = LittleFloat(d->mins[j]); - d->maxs[j] = LittleFloat(d->maxs[j]); - d->origin[j] = LittleFloat(d->origin[j]); - } - } - -// -// vertexes -// - for (i=0 ; inumclusters; - else - j = LittleLong(dvis->numclusters); - dvis->numclusters = LittleLong (dvis->numclusters); - for (i=0 ; ibitofs[i][0] = LittleLong (dvis->bitofs[i][0]); - dvis->bitofs[i][1] = LittleLong (dvis->bitofs[i][1]); - } -} - - -dheader_t *header; - -int CopyLump (int lump, void *dest, int size) -{ - int length, ofs; - - length = header->lumps[lump].filelen; - ofs = header->lumps[lump].fileofs; - - if (length % size) - Error ("LoadBSPFile: odd lump size"); - - memcpy (dest, (byte *)header + ofs, length); - - return length / size; -} - -/* -============= -LoadBSPFile -============= -*/ -void LoadBSPFile (char *filename) -{ - int i; - -// -// load the file header -// - LoadFile (filename, (void **)&header); - -// swap the header - for (i=0 ; i< sizeof(dheader_t)/4 ; i++) - ((int *)header)[i] = LittleLong ( ((int *)header)[i]); - - if (header->ident != IDBSPHEADER) - Error ("%s is not a IBSP file", filename); - if (header->version != BSPVERSION) - Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); - - nummodels = CopyLump (LUMP_MODELS, dmodels, sizeof(dmodel_t)); - numvertexes = CopyLump (LUMP_VERTEXES, dvertexes, sizeof(dvertex_t)); - numplanes = CopyLump (LUMP_PLANES, dplanes, sizeof(dplane_t)); - numleafs = CopyLump (LUMP_LEAFS, dleafs, sizeof(dleaf_t)); - numnodes = CopyLump (LUMP_NODES, dnodes, sizeof(dnode_t)); - numtexinfo = CopyLump (LUMP_TEXINFO, texinfo, sizeof(texinfo_t)); - numfaces = CopyLump (LUMP_FACES, dfaces, sizeof(dface_t)); - numleaffaces = CopyLump (LUMP_LEAFFACES, dleaffaces, sizeof(dleaffaces[0])); - numleafbrushes = CopyLump (LUMP_LEAFBRUSHES, dleafbrushes, sizeof(dleafbrushes[0])); - numsurfedges = CopyLump (LUMP_SURFEDGES, dsurfedges, sizeof(dsurfedges[0])); - numedges = CopyLump (LUMP_EDGES, dedges, sizeof(dedge_t)); - numbrushes = CopyLump (LUMP_BRUSHES, dbrushes, sizeof(dbrush_t)); - numbrushsides = CopyLump (LUMP_BRUSHSIDES, dbrushsides, sizeof(dbrushside_t)); - numareas = CopyLump (LUMP_AREAS, dareas, sizeof(darea_t)); - numareaportals = CopyLump (LUMP_AREAPORTALS, dareaportals, sizeof(dareaportal_t)); - - visdatasize = CopyLump (LUMP_VISIBILITY, dvisdata, 1); - lightdatasize = CopyLump (LUMP_LIGHTING, dlightdata, 1); - entdatasize = CopyLump (LUMP_ENTITIES, dentdata, 1); - - CopyLump (LUMP_POP, dpop, 1); - - free (header); // everything has been copied out - -// -// swap everything -// - SwapBSPFile (false); -} - - -/* -============= -LoadBSPFileTexinfo - -Only loads the texinfo lump, so qdata can scan for textures -============= -*/ -void LoadBSPFileTexinfo (char *filename) -{ - int i; - FILE *f; - int length, ofs; - - header = malloc(sizeof(dheader_t)); - - f = fopen (filename, "rb"); - fread (header, sizeof(dheader_t), 1, f); - -// swap the header - for (i=0 ; i< sizeof(dheader_t)/4 ; i++) - ((int *)header)[i] = LittleLong ( ((int *)header)[i]); - - if (header->ident != IDBSPHEADER) - Error ("%s is not a IBSP file", filename); - if (header->version != BSPVERSION) - Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); - - - length = header->lumps[LUMP_TEXINFO].filelen; - ofs = header->lumps[LUMP_TEXINFO].fileofs; - - fseek (f, ofs, SEEK_SET); - fread (texinfo, length, 1, f); - fclose (f); - - numtexinfo = length / sizeof(texinfo_t); - - free (header); // everything has been copied out - - SwapBSPFile (false); -} - - -//============================================================================ - -FILE *wadfile; -dheader_t outheader; - -void AddLump (int lumpnum, void *data, int len) -{ - lump_t *lump; - - lump = &header->lumps[lumpnum]; - - lump->fileofs = LittleLong( ftell(wadfile) ); - lump->filelen = LittleLong(len); - SafeWrite (wadfile, data, (len+3)&~3); -} - -/* -============= -WriteBSPFile - -Swaps the bsp file in place, so it should not be referenced again -============= -*/ -void WriteBSPFile (char *filename) -{ - header = &outheader; - memset (header, 0, sizeof(dheader_t)); - - SwapBSPFile (true); - - header->ident = LittleLong (IDBSPHEADER); - header->version = LittleLong (BSPVERSION); - - wadfile = SafeOpenWrite (filename); - SafeWrite (wadfile, header, sizeof(dheader_t)); // overwritten later - - AddLump (LUMP_PLANES, dplanes, numplanes*sizeof(dplane_t)); - AddLump (LUMP_LEAFS, dleafs, numleafs*sizeof(dleaf_t)); - AddLump (LUMP_VERTEXES, dvertexes, numvertexes*sizeof(dvertex_t)); - AddLump (LUMP_NODES, dnodes, numnodes*sizeof(dnode_t)); - AddLump (LUMP_TEXINFO, texinfo, numtexinfo*sizeof(texinfo_t)); - AddLump (LUMP_FACES, dfaces, numfaces*sizeof(dface_t)); - AddLump (LUMP_BRUSHES, dbrushes, numbrushes*sizeof(dbrush_t)); - AddLump (LUMP_BRUSHSIDES, dbrushsides, numbrushsides*sizeof(dbrushside_t)); - AddLump (LUMP_LEAFFACES, dleaffaces, numleaffaces*sizeof(dleaffaces[0])); - AddLump (LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes*sizeof(dleafbrushes[0])); - AddLump (LUMP_SURFEDGES, dsurfedges, numsurfedges*sizeof(dsurfedges[0])); - AddLump (LUMP_EDGES, dedges, numedges*sizeof(dedge_t)); - AddLump (LUMP_MODELS, dmodels, nummodels*sizeof(dmodel_t)); - AddLump (LUMP_AREAS, dareas, numareas*sizeof(darea_t)); - AddLump (LUMP_AREAPORTALS, dareaportals, numareaportals*sizeof(dareaportal_t)); - - AddLump (LUMP_LIGHTING, dlightdata, lightdatasize); - AddLump (LUMP_VISIBILITY, dvisdata, visdatasize); - AddLump (LUMP_ENTITIES, dentdata, entdatasize); - AddLump (LUMP_POP, dpop, sizeof(dpop)); - - fseek (wadfile, 0, SEEK_SET); - SafeWrite (wadfile, header, sizeof(dheader_t)); - fclose (wadfile); -} - -//============================================================================ - -/* -============= -PrintBSPFileSizes - -Dumps info about current file -============= -*/ -void PrintBSPFileSizes (void) -{ - if (!num_entities) - ParseEntities (); - - printf ("%5i models %7i\n" - ,nummodels, (int)(nummodels*sizeof(dmodel_t))); - printf ("%5i brushes %7i\n" - ,numbrushes, (int)(numbrushes*sizeof(dbrush_t))); - printf ("%5i brushsides %7i\n" - ,numbrushsides, (int)(numbrushsides*sizeof(dbrushside_t))); - printf ("%5i planes %7i\n" - ,numplanes, (int)(numplanes*sizeof(dplane_t))); - printf ("%5i texinfo %7i\n" - ,numtexinfo, (int)(numtexinfo*sizeof(texinfo_t))); - printf ("%5i entdata %7i\n", num_entities, entdatasize); - - printf ("\n"); - - printf ("%5i vertexes %7i\n" - ,numvertexes, (int)(numvertexes*sizeof(dvertex_t))); - printf ("%5i nodes %7i\n" - ,numnodes, (int)(numnodes*sizeof(dnode_t))); - printf ("%5i faces %7i\n" - ,numfaces, (int)(numfaces*sizeof(dface_t))); - printf ("%5i leafs %7i\n" - ,numleafs, (int)(numleafs*sizeof(dleaf_t))); - printf ("%5i leaffaces %7i\n" - ,numleaffaces, (int)(numleaffaces*sizeof(dleaffaces[0]))); - printf ("%5i leafbrushes %7i\n" - ,numleafbrushes, (int)(numleafbrushes*sizeof(dleafbrushes[0]))); - printf ("%5i surfedges %7i\n" - ,numsurfedges, (int)(numsurfedges*sizeof(dsurfedges[0]))); - printf ("%5i edges %7i\n" - ,numedges, (int)(numedges*sizeof(dedge_t))); - printf (" lightdata %7i\n", lightdatasize); - printf (" visdata %7i\n", visdatasize); -} - - -//============================================ - -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 = 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); - GetScriptToken (false); - if (strlen(token) >= MAX_VALUE-1) - Error ("ParseEpar: token too long"); - e->value = copystring(token); - - // strip trailing spaces - StripTrailing (e->key); - StripTrailing (e->value); - - return e; -} - - -/* -================ -ParseEntity -================ -*/ -qboolean ParseEntity (void) -{ - epair_t *e; - entity_t *mapent; - - if (!GetScriptToken (true)) - return false; - - 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 (!GetScriptToken (true)) - Error ("ParseEntity: EOF without closing brace"); - if (!strcmp (token, "}") ) - break; - e = ParseEpair (); - e->next = mapent->epairs; - mapent->epairs = e; - } while (1); - - return true; -} - -/* -================ -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 -================ -*/ -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 ; inext) - { - 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 (entity_t *ent) -{ - epair_t *ep; - - printf ("------- entity %p -------\n", ent); - for (ep=ent->epairs ; ep ; ep=ep->next) - { - printf ("%s = %s\n", ep->key, ep->value); - } - -} - -void SetKeyValue (entity_t *ent, char *key, 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 = malloc (sizeof(*ep)); - if (!ep) - Error("SetKeyValue MALLOC failed! Could not allocate %s bytes.", sizeof(*ep)); - ep->next = ent->epairs; - ent->epairs = ep; - ep->key = copystring(key); - ep->value = copystring(value); -} - -char *ValueForKey (entity_t *ent, 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 (entity_t *ent, char *key) -{ - char *k; - - k = ValueForKey (ent, key); - return atof(k); -} - -void GetVectorForKey (entity_t *ent, char *key, vec3_t vec) -{ - 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/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.h deleted file mode 100644 index 1597a3df..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -Copyright (C) 1999-2006 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 _QBSP3_H -#define _QBSP3_H - - -#include "qfiles.h" - - -extern int nummodels; -extern dmodel_t dmodels[MAX_MAP_MODELS]; - -extern int visdatasize; -extern byte dvisdata[MAX_MAP_VISIBILITY]; -extern dvis_t *dvis; - -extern int lightdatasize; -extern byte dlightdata[MAX_MAP_LIGHTING]; - -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 numvertexes; -extern dvertex_t dvertexes[MAX_MAP_VERTS]; - -extern int numnodes; -extern dnode_t dnodes[MAX_MAP_NODES]; - -extern int numtexinfo; -extern texinfo_t texinfo[MAX_MAP_TEXINFO]; - -extern int numfaces; -extern dface_t dfaces[MAX_MAP_FACES]; - -extern int numedges; -extern dedge_t dedges[MAX_MAP_EDGES]; - -extern int numleaffaces; -extern unsigned short dleaffaces[MAX_MAP_LEAFFACES]; - -extern int numleafbrushes; -extern unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; - -extern int numsurfedges; -extern int dsurfedges[MAX_MAP_SURFEDGES]; - -extern int numareas; -extern darea_t dareas[MAX_MAP_AREAS]; - -extern int numareaportals; -extern dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; - -extern int numbrushes; -extern dbrush_t dbrushes[MAX_MAP_BRUSHES]; - -extern int numbrushsides; -extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; - -extern byte dpop[256]; - -void DecompressVis (byte *in, byte *decompressed); -int CompressVis (byte *vis, byte *dest); - -void LoadBSPFile (char *filename); -void LoadBSPFileTexinfo (char *filename); // just for qdata -void WriteBSPFile (char *filename); -void PrintBSPFileSizes (void); - -//=============== - - -typedef struct epair_s -{ - struct epair_s *next; - char *key; - char *value; -} epair_t; - -typedef struct -{ - vec3_t origin; - int firstbrush; - int numbrushes; - epair_t *epairs; - -// only valid for func_areaportals - int areaportalnum; - int portalareas[2]; -} entity_t; - -extern int num_entities; -extern entity_t entities[MAX_MAP_ENTITIES]; - -void ParseEntities (void); -void UnparseEntities (void); - -void SetKeyValue (entity_t *ent, char *key, char *value); -char *ValueForKey (entity_t *ent, char *key); -// will return "" if not present - -vec_t FloatForKey (entity_t *ent, char *key); -void GetVectorForKey (entity_t *ent, char *key, vec3_t vec); - -epair_t *ParseEpair (void); - -void PrintEntity (entity_t *ent); - -#endif //_QBSP3_H diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.c deleted file mode 100644 index f3115d29..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.c +++ /dev/null @@ -1,1238 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// Nurail: Swiped from quake3/common - -#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 "h" -#define PATHSEPERATOR '/' - -extern qboolean verbose; - -qboolean g_dokeypress = false; - -qboolean g_nomkdir = false; - - -#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 - -void *SafeMalloc(size_t n, char *desc) -{ - void *p; - - if((p = malloc(n)) == NULL) - { - Error("Failed to allocate %d bytes for '%s'.\n", n, desc); - } - memset(p, 0, n); - return p; -} - -#if defined (__linux__) || defined (__APPLE__) -void strlwr(char *conv_str) -{ - int i; - - for(i=0; i32); - - 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); -} - -int Q_strcasecmp (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 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); -} -/* -// all output ends up through here -void FPrintf (int flag, char *buf) -{ - printf(buf); - -} - -void Sys_FPrintf (int flag, const char *format, ...) -{ - char out_buffer[4096]; - va_list argptr; - - if ((flag == SYS_VRB) && (verbose == false)) - 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 ); - - exit (1); -} - -*/ - -/* -============================================================================ - - 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/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.h deleted file mode 100644 index a6cb14e9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.h +++ /dev/null @@ -1,181 +0,0 @@ -/* -Copyright (C) 1999-2006 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__ - -#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 - -#ifndef __BYTEBOOL__ - #define __BYTEBOOL__ - //typedef enum {false, true} qboolean; - //typedef unsigned char byte; - #include "q_typedef.h" -#endif - -#ifdef PATH_MAX -#define MAX_OS_PATH PATH_MAX -#else -#define MAX_OS_PATH 1024 -#endif -#define MEM_BLOCKSIZE 4096 -/* -extern qboolean verbose; -#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 -*/ -// 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 ); -int Q_strcasecmp( 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 ); - -int CheckParm( const char *check ); - -void *SafeMalloc(size_t n, char *desc); -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); -/* -void Sys_Printf (const char *text, ...); -void Sys_FPrintf (int flag, const char *text, ...); -void Error( const char *error, ... ); -*/ -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]; - -extern qboolean g_dokeypress; - -// sleep for the given amount of milliseconds -void Sys_Sleep(int n); - -// for compression routines -typedef struct -{ - byte *data; - int count; -} cblock_t; - - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/her2_threads.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/her2_threads.h deleted file mode 100644 index 339b0c86..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/her2_threads.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright (C) 1999-2006 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 _THREADS_H - -#define _THREADS_H - - -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); - -#endif //_THREADS_H diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/inout.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/inout.c deleted file mode 100644 index 3cf66e7f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/inout.c +++ /dev/null @@ -1,367 +0,0 @@ -/* -Copyright (C) 1999-2006 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" - -#ifdef WIN32 -HWND hwndOut = NULL; -qboolean lookedForServer = false; -UINT wm_BroadcastCommand = -1; -#endif - -socket_t *brdcst_socket; -netmessage_t msg; - -qboolean verbose = false; - -// 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 = false; - 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 = true; - } - node = xmlNewNode (NULL, "message"); - xmlNodeSetContent (node, buf); - 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 == false)) - 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/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/inout.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/inout.h deleted file mode 100644 index 75ef55ee..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/inout.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright (C) 1999-2006 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" -#include "mathlib.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, ...); -void Error( const char *error, ...); - -#ifdef _DEBUG -#define DBG_XML 1 -#endif - -#ifdef DBG_XML -void DumpXML(); -#endif - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.c deleted file mode 100644 index 853ff1ca..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.c +++ /dev/null @@ -1,476 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#include "mathlib.h" -#include "trilib.h" -#include "l3dslib.h" -#include "token.h" -#include "fmodel.h" -#include "bspfile.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 - -typedef struct { - int v[4]; -} tri; - -float fverts[MAXVERTS][3]; -tri tris[MAXTRIANGLES]; - -int bytesread, level, numtris, totaltris; -int vertsfound, trisfound; - -triangle_t *ptri; - - - -void DefaultNodesList(mesh_node_t **nodesList, int *num_mesh_nodes, int *numtriangles) -{ - int pos, bit, i; - - if (nodesList) - { - *num_mesh_nodes = 1; - memset(&(*nodesList)[0], 0, sizeof(mesh_node_t)); - strcpy((*nodesList)[0].name, "default"); - - // set all of the tris to be used for the top node - for(i = 0; i < (*numtriangles); i++) - { - pos = (i) >> 3; - bit = 1 << ((i) & 7 ); - - (*nodesList)[0].tris[pos] |= bit; - } - } -} - - -// 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 MAXVERTS) - Error ("Error: Too many vertices"); - - for (i=0 ; i MAXTRIANGLES) - Error ("Error: Too many triangles"); - - for (i=0 ; i 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, mesh_node_t **nodesList, int *num_mesh_nodes) -{ - FILE *input; - short int tshort; - - if (nodesList) - { - *num_mesh_nodes = 0; - *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); - } - - 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 = 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); - - DefaultNodesList(nodesList,num_mesh_nodes,numtriangles); -} - -//========================================================================== -// -// LoadASC -// -//========================================================================== - -void LoadASC(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) -{ - int i, j; - int vertexCount; - struct - { - float v[3]; - } *vList; - int triCount; - triangle_t *tList; - float x, y, z; -// float x2, y2, z2; -// float rx, ry, rz; - qboolean goodObject; - - if (nodesList) - { - *num_mesh_nodes = 0; - *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); - } - - TK_OpenSource(fileName); - - goodObject = false; - while(goodObject == false) - { - TK_Beyond(TK_C_NAMED); - TK_Beyond(TK_OBJECT); - TK_Beyond(TK_C_TRI); - TK_Beyond(TK_MESH); - TK_BeyondRequire(TK_C_VERTICES, TK_COLON); - TK_FetchRequire(TK_INTNUMBER); - vertexCount = tk_IntNumber; - if(vertexCount > 0) - { - goodObject = true; - } - } - TK_BeyondRequire(TK_C_FACES, TK_COLON); - TK_FetchRequire(TK_INTNUMBER); - triCount = tk_IntNumber; - if(triCount >= MAXTRIANGLES) - { - Error("Too many triangles in file %s\n", fileName); - } - *triangleCount = triCount; - tList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); - *triList = tList; - - memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); - TK_BeyondRequire(TK_C_VERTEX, TK_LIST); - -/* rx = ((rotation[0]+90.0)/360.0)*2.0*M_PI; - //rx = (rotation[0]/360.0)*2.0*M_PI; - ry = (rotation[1]/360.0)*2.0*M_PI; - rz = (rotation[2]/360.0)*2.0*M_PI; -*/ - vList = (void *) SafeMalloc(vertexCount*sizeof vList[0], "Vertex list"); - for(i = 0; i < vertexCount; i++) - { - TK_BeyondRequire(TK_C_VERTEX, TK_INTNUMBER); - if(tk_IntNumber != i) - { - Error("File '%s', line %d:\nVertex index mismatch.\n", - tk_SourceName, tk_Line); - } - TK_FetchRequireFetch(TK_COLON); - - TK_BeyondRequire(TK_COLON, TK_FLOATNUMBER); - x = tk_FloatNumber; - TK_BeyondRequire(TK_COLON, TK_FLOATNUMBER); - y = tk_FloatNumber; - TK_BeyondRequire(TK_COLON, TK_FLOATNUMBER); - z = tk_FloatNumber; - -/* x2 = x*cos(rz)+y*sin(rz); - y2 = -x*sin(rz)+y*cos(rz); - x = x2; - y = y2; - y2 = y*cos(rx)+z*sin(rx); - z2 = -y*sin(rx)+z*cos(rx); - y = y2; - z = z2; - x2 = x*cos(ry)-z*sin(ry); - z2 = x*sin(ry)+z*cos(ry); - x = x2; - z = z2; -*/ - vList[i].v[0] = x; - vList[i].v[1] = y; - vList[i].v[2] = z; - } - TK_BeyondRequire(TK_C_FACE, TK_LIST); - for(i = 0; i < triCount; i++) - { - TK_BeyondRequire(TK_C_FACE, TK_INTNUMBER); - if(tk_IntNumber != i) - { - Error("File '%s', line %d:\nTriangle index mismatch.\n", - tk_SourceName, tk_Line); - } - for(j = 0; j < 3; j++) - { - TK_BeyondRequire(TK_IDENTIFIER, TK_COLON); - TK_FetchRequire(TK_INTNUMBER); - if(tk_IntNumber >= vertexCount) - { - Error("File '%s', line %d:\nVertex number" - " > vertexCount: %d\n", tk_SourceName, tk_Line, - tk_IntNumber); - } - tList[i].verts[2-j][0] = vList[tk_IntNumber].v[0]; - tList[i].verts[2-j][1] = vList[tk_IntNumber].v[1]; - tList[i].verts[2-j][2] = vList[tk_IntNumber].v[2]; -#ifdef _QDATA - tList[i].indicies[2-j] = tk_IntNumber; -#endif - } - -/* printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" - " v2: %f, %f, %f\n", i, - tList[i].verts[0][0], - tList[i].verts[0][1], - tList[i].verts[0][2], - tList[i].verts[1][0], - tList[i].verts[1][1], - tList[i].verts[1][2], - tList[i].verts[2][0], - tList[i].verts[2][1], - tList[i].verts[2][2]); -*/ - } - - DefaultNodesList(nodesList,num_mesh_nodes,triangleCount); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.h deleted file mode 100644 index b20391c6..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 1999-2006 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 DefaultNodesList(mesh_node_t **nodesList, int *num_mesh_nodes, int *numtriangles); - -void Load3DSTriangleList (char *filename, triangle_t **pptri, int *numtriangles, mesh_node_t **ppmnodes, int *num_mesh_nodes); -void LoadASC(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **ppmnodes, int *num_mesh_nodes); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.c deleted file mode 100644 index 5ea39bd9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.c +++ /dev/null @@ -1,1052 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// lbmlib.c - -#include "cmdlib.h" -#include "inout.h" -#include "lbmlib.h" - -// Ups the palette values so no pixels except 0 appear transparent -// Need a value of 8 to cater for 16bit renderers - -typedef struct -{ - byte r; - byte g; - byte b; -} paletteRGB_t; - - -void CorrectPalette(byte *pal) -{ - paletteRGB_t *p; - - p = (paletteRGB_t *)pal; - // Color 0 always transparent - p->r = 0; - p->g = 0; - p->b = 0; -} - -/* -============================================================================ - - 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 (countbpwidth) - Error ("Decompression exceeded width!\n"); - - - return source; -} - - -/* -================= -LoadLBM -================= -*/ -void LoadLBM (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 = malloc (768); - memset (cmapbuffer, 0, 768); - memcpy (cmapbuffer, LBM_P, chunklength); - CorrectPalette(cmapbuffer); - break; - - case BODYID: - body_p = LBM_P; - - pic_p = picbuffer = malloc (bmhd.w*bmhd.h); - if (formtype == PBMID) - { - // - // unpack PBM - // - for (y=0 ; ydata; - - 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 = malloc(768); - memcpy (*palette, (byte *)pcx + len - 768, 768); - CorrectPalette(*palette); - } - - if (width) - *width = pcx->xmax+1; - if (height) - *height = pcx->ymax+1; - - if (!pic) - return; - - out = malloc ( (pcx->ymax+1) * (pcx->xmax+1) ); - if (!out) - Error ("Skin_Cache: couldn't allocate"); - - *pic = out; - - pix = out; - - for (y=0 ; y<=pcx->ymax ; y++, pix += pcx->xmax+1) - { - for (x=0 ; x<=pcx->xmax ; ) - { - dataByte = *raw++; - - if((dataByte & 0xC0) == 0xC0) - { - runLength = dataByte & 0x3F; - dataByte = *raw++; - } - else - runLength = 1; - - while(runLength-- > 0) - pix[x++] = dataByte; - } - - } - - if ( raw - (byte *)pcx > len) - Error ("PCX file %s was malformed", filename); - - free (pcx); -} - -/* -============== -WritePCXfile -============== -*/ - -void StuffPackedByte(int curRepCount, byte curByte, byte** packPtr) -{ - byte* pack; - - pack = *packPtr; - - while(curRepCount > 0) - { - if (curRepCount == 1) - { - if ((curByte & 0xc0) != 0xc0) - { - *pack++ = curByte; - } - else - { - *pack++ = 0xc1; - *pack++ = curByte; - } - break; - } - if (curRepCount < 0x0040) - { - *pack++ = (0x00c0 | curRepCount); - curRepCount = 0; - } - else - { - *pack++ = 0xff; - curRepCount -= 0x003f; - } - *pack++ = curByte; - } - *packPtr = pack; -} - -void WritePCXfile (char *filename, byte *data, - int width, int height, byte *palette) -{ - int i, j, length; - pcx_t *pcx; - byte *pack; - byte curByte; - int curRepCount; - - pcx = malloc (width*height*2+1000); - memset (pcx, 0, sizeof(*pcx)); - - pcx->manufacturer = 0x0a; // PCX id - pcx->version = 5; // 256 color - pcx->encoding = 1; // RLE - 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= rows) - goto breakOut; - pixbuf += rowOffset; - rowBuf = pixbuf; - } - } - } - else - { // non run-length packet - for(j = 0; j < packetSize; j++) - { - switch (targa_header.pixel_size) - { - case 24: - blue = getc(fin); - green = getc(fin); - red = getc(fin); - rowBuf[0] = red; - rowBuf[1] = green; - rowBuf[2] = blue; - rowBuf[3] = 255; - rowBuf += pixDirection; - break; - case 32: - blue = getc(fin); - green = getc(fin); - red = getc(fin); - alphabyte = getc(fin); - rowBuf[0] = red; - rowBuf[1] = green; - rowBuf[2] = blue; - rowBuf[3] = alphabyte; - rowBuf += pixDirection; - break; - } - column++; - if (column == columns) - { // pixel packet run spans across rows - column = 0; - row++; - if (row >= rows) - goto breakOut; - pixbuf += rowOffset; - rowBuf = pixbuf; - } - } - } - } - breakOut:; - pixbuf += rowOffset; - } - } - fclose(fin); -} - -void MergeAlpha(byte *pix, byte *alpha, byte *pal, byte **out, int width, int height) -{ - int size, i; - byte *data, *src, *srca; - - size = width * height; - data = malloc(size * 4); - if(!data) - Error("Could not allocate memory for true color image"); - - *out = data; - src = pix; - srca = alpha; - - for(i = 0; i < size; i++, src++, srca++) - { - *data++ = pal[*src * 3 + 0]; // r - *data++ = pal[*src * 3 + 1]; // g - *data++ = pal[*src * 3 + 2]; // b - *data++ = *srca; // a - } - free(pix); - free(alpha); - free(pal); -} - -/* -============== -LoadAnyImage - -Return Value: - false: paletted texture - true: true color RGBA image (no palette) -============== -*/ -qboolean LoadAnyImage (char *name, byte **pixels, byte **palette, int *width, int *height) -{ - char ext[128]; - int len; - int alpha_width, alpha_height; - char alpha_name[128]; - byte *alpha_pixels; - - ExtractFileExtension (name, ext); - - if(palette) - { - *palette = NULL; - } - - if (!Q_strcasecmp (ext, "lbm")) - { - LoadLBM (name, pixels, palette); - if (width) - *width = bmhd.w; - if (height) - *height = bmhd.h; - return false; - } - else if (!Q_strcasecmp (ext, "pcx")) - { - len = strlen(name); - strcpy(alpha_name, name); - strcpy(&alpha_name[len - 4], "_a.pcx"); // Alpha map name (may not exist) - - if(FileExists(alpha_name)) - { - LoadPCX (name, pixels, palette, width, height); // Load in image - LoadPCX (alpha_name, &alpha_pixels, NULL, &alpha_width, &alpha_height); // Load in alpha map - if((*width != alpha_width) || (*height != alpha_height)) - { - Error("Alpha image dimensions not equal to graphic image dimensions"); - } - MergeAlpha(*pixels, alpha_pixels, *palette, pixels, *width, *height); - *palette = NULL;//Merge Frees pal - return true; - } - else - { - LoadPCX (name, pixels, palette, width, height); // Load in image - return false; - } - } - else if (!Q_strcasecmp (ext, "tga")) - { - LoadTGA(name, pixels, width, height); - if (palette) - { - *palette = NULL; - } - - return true; - } - else - Error ("%s doesn't have a known image extension", name); - - return false; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.h deleted file mode 100644 index 5a5f46f2..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -Copyright (C) 1999-2006 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 (char *filename, byte **picture, byte **palette); -void WriteLBMfile (char *filename, byte *data, int width, int height - , byte *palette); -void LoadPCX (char *filename, byte **picture, byte **palette, int *width, int *height); -void WritePCXfile (char *filename, byte *data, int width, int height - , byte *palette); - -// loads / saves either lbm or pcx, depending on extension -void Load256Image (char *name, byte **pixels, byte **palette, - int *width, int *height); -void Save256Image (char *name, byte *pixels, byte *palette, - int width, int height); - - -void LoadTGA (char *filename, byte **pixels, int *width, int *height); - -qboolean LoadAnyImage (char *name, byte **pixels, byte **palette, int *width, int *height); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.c deleted file mode 100644 index aa53c44a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.c +++ /dev/null @@ -1,176 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "cmdlib.h" -#include "mathlib.h" - -vec3_t vec3_origin = {0,0,0}; - - -double VectorLength(vec3_t v) -{ - int i; - double length; - - length = 0; - for (i=0 ; i< 3 ; i++) - length += v[i]*v[i]; - length = sqrt (length); // FIXME - - return length; -} - -qboolean VectorCompare (vec3_t v1, vec3_t v2) -{ - int i; - - for (i=0 ; i<3 ; i++) - if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON) - return false; - - return true; -} - -vec_t Q_rint (vec_t in) -{ - return floor (in + 0.5); -} - -void VectorMA (vec3_t va, double scale, 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]; -} - -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; -} - -#pragma optimize("g", off) // went back to turning optimization off, - // the bug_fix thing stopped working - -vec_t VectorNormalize (vec3_t in, vec3_t out) -{ - vec_t length, ilength; - - length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]); - if (length == 0) - { - VectorClear (out); - return 0; - } - - ilength = 1.0/length; - out[0] = in[0]*ilength; - out[1] = in[1]*ilength; - out[2] = in[2]*ilength; - - return length; -} - -vec_t ColorNormalize (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) - return 0; - - scale = 1.0 / max; - - VectorScale (in, scale, out); - - return max; -} - -#pragma optimize("", on) - -void VectorInverse (vec3_t v) -{ - v[0] = -v[0]; - v[1] = -v[1]; - v[2] = -v[2]; -} - -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; - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.h deleted file mode 100644 index 76dfda32..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright (C) 1999-2006 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 DOUBLEVEC_T -typedef double vec_t; -#else -typedef float vec_t; -#endif -typedef vec_t vec3_t[3]; -*/ -#define SIDE_FRONT 0 -#define SIDE_ON 2 -#define SIDE_BACK 1 -#define SIDE_CROSS -2 - -#define Q_PI 3.14159265358979323846 - -extern vec3_t vec3_origin; - -#define EQUAL_EPSILON 0.001 - -qboolean VectorCompare (vec3_t v1, vec3_t v2); - -#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 VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];} -#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];} -#define VectorClear(x) {x[0] = x[1] = x[2] = 0;} -#define VectorNegate(x) {x[0]=-x[0];x[1]=-x[1];x[2]=-x[2];} - -vec_t Q_rint (vec_t in); -vec_t _DotProduct (vec3_t v1, vec3_t v2); -void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out); -void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out); -void _VectorCopy (vec3_t in, vec3_t out); -void _VectorScale (vec3_t v, vec_t scale, vec3_t out); - -double VectorLength(vec3_t v); - -void VectorMA (vec3_t va, double scale, vec3_t vb, vec3_t vc); - -void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross); -vec_t VectorNormalize (vec3_t in, vec3_t out); -vec_t ColorNormalize (vec3_t in, vec3_t out); -void VectorInverse (vec3_t v); - -void ClearBounds (vec3_t mins, vec3_t maxs); -void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/md4.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/md4.c deleted file mode 100644 index 7c2c9be4..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/md4.c +++ /dev/null @@ -1,227 +0,0 @@ -/* - mdfour.c - - An implementation of MD4 designed for use in the samba SMB - authentication protocol - - Copyright (C) 1997-1998 Andrew Tridgell - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - - See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to: - - Free Software Foundation, Inc. - 59 Temple Place - Suite 330 - Boston, MA 02111-1307, USA - - $Id: mdfour.c 7689 2007-11-12 14:28:40Z divverent $ -*/ - -#include /* XoXus: needed for memset call */ -#include "md4.h" - -/* NOTE: This code makes no attempt to be fast! - - It assumes that a int is at least 32 bits long -*/ - -static struct mdfour *m; - -#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)) -#ifdef LARGE_INT32 -#define lshift(x,s) ((((x)<<(s))&0xFFFFFFFF) | (((x)>>(32-(s)))&0xFFFFFFFF)) -#else -#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) -#endif - -#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) -#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) -#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) - -/* this applies md4 to 64 byte chunks */ -static void mdfour64(uint32 *M) -{ - int j; - uint32 AA, BB, CC, DD; - uint32 X[16]; - uint32 A,B,C,D; - - for (j=0;j<16;j++) - X[j] = M[j]; - - A = m->A; B = m->B; C = m->C; D = m->D; - AA = A; BB = B; CC = C; DD = D; - - ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); - ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); - ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); - ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); - ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); - ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); - ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); - ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); - - ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); - ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); - ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); - ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); - ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); - ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); - ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); - ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); - - ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); - ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); - ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); - ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); - ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); - ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); - ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); - ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); - - A += AA; B += BB; C += CC; D += DD; - -#ifdef LARGE_INT32 - A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; - C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; -#endif - - for (j=0;j<16;j++) - X[j] = 0; - - m->A = A; m->B = B; m->C = C; m->D = D; -} - -static void copy64(uint32 *M, unsigned char *in) -{ - int i; - - for (i=0;i<16;i++) - M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | - (in[i*4+1]<<8) | (in[i*4+0]<<0); -} - -static void copy4(unsigned char *out,uint32 x) -{ - out[0] = x&0xFF; - out[1] = (x>>8)&0xFF; - out[2] = (x>>16)&0xFF; - out[3] = (x>>24)&0xFF; -} - -void mdfour_begin(struct mdfour *md) -{ - md->A = 0x67452301; - md->B = 0xefcdab89; - md->C = 0x98badcfe; - md->D = 0x10325476; - md->totalN = 0; -} - - -static void mdfour_tail(unsigned char *in, int n) -{ - unsigned char buf[128]; - uint32 M[16]; - uint32 b; - - m->totalN += n; - - b = m->totalN * 8; - - memset(buf, 0, 128); - if (n) memcpy(buf, in, n); - buf[n] = 0x80; - - if (n <= 55) { - copy4(buf+56, b); - copy64(M, buf); - mdfour64(M); - } else { - copy4(buf+120, b); - copy64(M, buf); - mdfour64(M); - copy64(M, buf+64); - mdfour64(M); - } -} - -void mdfour_update(struct mdfour *md, unsigned char *in, int n) -{ - uint32 M[16]; - -// start of edit by Forest 'LordHavoc' Hale -// commented out to prevent crashing when length is 0 -// if (n == 0) mdfour_tail(in, n); -// end of edit by Forest 'LordHavoc' Hale - - m = md; - - while (n >= 64) { - copy64(M, in); - mdfour64(M); - in += 64; - n -= 64; - m->totalN += 64; - } - - mdfour_tail(in, n); -} - - -void mdfour_result(struct mdfour *md, unsigned char *out) -{ - m = md; - - copy4(out, m->A); - copy4(out+4, m->B); - copy4(out+8, m->C); - copy4(out+12, m->D); -} - - -void mdfour(unsigned char *out, unsigned char *in, int n) -{ - struct mdfour md; - mdfour_begin(&md); - mdfour_update(&md, in, n); - mdfour_result(&md, out); -} - -/////////////////////////////////////////////////////////////// -// MD4-based checksum utility functions -// -// Copyright (C) 2000 Jeff Teunissen -// -// Author: Jeff Teunissen -// Date: 01 Jan 2000 - -unsigned Com_BlockChecksum (void *buffer, int length) -{ - int digest[4]; - unsigned val; - - mdfour ( (unsigned char *) digest, (unsigned char *) buffer, length ); - - val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; - - return val; -} - -void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) -{ - mdfour ( outbuf, (unsigned char *) buffer, len ); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/md4.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/md4.h deleted file mode 100644 index 4373c2c9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/md4.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - mdfour.h - - an implementation of MD4 designed for use in the SMB authentication - protocol - - Copyright (C) Andrew Tridgell 1997-1998 - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - - See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to: - - Free Software Foundation, Inc. - 59 Temple Place - Suite 330 - Boston, MA 02111-1307, USA -*/ - -#ifndef _MDFOUR_H -#define _MDFOUR_H - -#ifndef int32 -#define int32 int -#endif - -#if SIZEOF_INT > 4 -#define LARGE_INT32 -#endif - -#ifndef uint32 -#define uint32 unsigned int32 -#endif - -struct mdfour { - uint32 A, B, C, D; - uint32 totalN; -}; - -void mdfour_begin(struct mdfour *md); // old: MD4Init -void mdfour_update(struct mdfour *md, unsigned char *in, int n); //old: MD4Update -void mdfour_result(struct mdfour *md, unsigned char *out); // old: MD4Final -void mdfour(unsigned char *out, unsigned char *in, int n); - -unsigned Com_BlockChecksum (void *buffer, int length); -void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf); - -#endif // _MDFOUR_H - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/path_init.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/path_init.c deleted file mode 100644 index 8947de84..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/path_init.c +++ /dev/null @@ -1,405 +0,0 @@ -/* ------------------------------------------------------------------------------- - -Copyright (C) 1999-2006 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 -*/ - -/* -Nurail: Swiped from Q3Map2 -*/ - - - -/* marker */ -#define PATH_INIT_C - -#if defined( __linux__ ) || defined( __APPLE__ ) - #define Q_UNIX -#endif - -#ifdef Q_UNIX - #include - #include - #include -#endif - - -/* dependencies */ -#include "cmdlib.h" -#include "inout.h" - - - -/* path support */ -#define MAX_BASE_PATHS 10 -#define MAX_GAME_PATHS 10 - -char *homePath; -char installPath[ MAX_OS_PATH ]; - -int numBasePaths; -char *basePaths[ MAX_BASE_PATHS ]; -int numGamePaths; -char *gamePaths[ MAX_GAME_PATHS ]; - -/* -some of this code is based off the original q3map port from loki -and finds various paths. moved here from bsp.c for clarity. -*/ - -/* -PathLokiGetHomeDir() -gets the user's home dir (for ~/.q3a) -*/ - -char *LokiGetHomeDir( void ) -{ - #ifndef Q_UNIX - return NULL; - #else - char *home; - uid_t id; - struct passwd *pwd; - - - /* get the home environment variable */ - home = getenv( "HOME" ); - if( home == NULL ) - { - /* do some more digging */ - id = getuid(); - setpwent(); - while( (pwd = getpwent()) != NULL ) - { - if( pwd->pw_uid == id ) - { - home = pwd->pw_dir; - break; - } - } - endpwent(); - } - - /* return it */ - return home; - #endif -} - - - -/* -PathLokiInitPaths() -initializes some paths on linux/os x -*/ - -void LokiInitPaths( char *argv0 ) -{ - #ifndef Q_UNIX - /* this is kinda crap, but hey */ - strcpy( installPath, "../" ); - #else - char temp[ MAX_OS_PATH ]; - char *home; - char *path; - char *last; - qboolean found; - - - /* get home dir */ - home = LokiGetHomeDir(); - if( home == NULL ) - home = "."; - - /* do some path divining */ - strcpy( temp, argv0 ); - if( strrchr( temp, '/' ) ) - argv0 = strrchr( argv0, '/' ) + 1; - else - { - /* get path environment variable */ - path = getenv( "PATH" ); - - /* minor setup */ - last[ 0 ] = path[ 0 ]; - last[ 1 ] = '\0'; - found = false; - - /* go through each : segment of path */ - while( last[ 0 ] != '\0' && found == false ) - { - /* null out temp */ - temp[ 0 ] = '\0'; - - /* find next chunk */ - last = strchr( path, ':' ); - if( last == NULL ) - last = path + strlen( path ); - - /* found home dir candidate */ - if( *path == '~' ) - { - strcpy( temp, home ); - path++; - } - - /* concatenate */ - if( last > (path + 1) ) - { - strncat( temp, path, (last - path) ); - strcat( temp, "/" ); - } - strcat( temp, "./" ); - strcat( temp, argv0 ); - - /* verify the path */ - if( access( temp, X_OK ) == 0 ) - found++; - path = last + 1; - } - } - - /* flake */ - if( realpath( temp, installPath ) ) - { - /* q3map is in "tools/" */ - *(strrchr( installPath, '/' )) = '\0'; - *(strrchr( installPath, '/' ) + 1) = '\0'; - } - - /* set home path */ - homePath = home; - #endif -} - - - -/* -CleanPath() - ydnar -cleans a dos path \ -> / -*/ - -void CleanPath( char *path ) -{ - while( *path ) - { - if( *path == '\\' ) - *path = '/'; - path++; - } -} - -/* -AddBasePath() - ydnar -adds a base path to the list -*/ - -void AddBasePath( char *path ) -{ - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' || numBasePaths >= MAX_BASE_PATHS ) - return; - - /* add it to the list */ - basePaths[ numBasePaths ] = safe_malloc( strlen( path ) + 1 ); - strcpy( basePaths[ numBasePaths ], path ); - CleanPath( basePaths[ numBasePaths ] ); - numBasePaths++; -} - - - -/* -AddHomeBasePath() - ydnar -adds a base path to the beginning of the list, prefixed by ~/ -*/ - -void AddHomeBasePath( char *path ) -{ - #ifdef Q_UNIX - int i; - char temp[ MAX_OS_PATH ]; - - - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' ) - return; - - /* make a hole */ - for( i = 0; i < (MAX_BASE_PATHS - 1); i++ ) - basePaths[ i + 1 ] = basePaths[ i ]; - - /* concatenate home dir and path */ - sprintf( temp, "%s/%s", homePath, path ); - - /* add it to the list */ - basePaths[ 0 ] = safe_malloc( strlen( temp ) + 1 ); - strcpy( basePaths[ 0 ], temp ); - CleanPath( basePaths[ 0 ] ); - numBasePaths++; - #endif -} - - - -/* -AddGamePath() - ydnar -adds a game path to the list -*/ - -void AddGamePath( char *path ) -{ - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' || numGamePaths >= MAX_GAME_PATHS ) - return; - - /* add it to the list */ - gamePaths[ numGamePaths ] = safe_malloc( strlen( path ) + 1 ); - strcpy( gamePaths[ numGamePaths ], path ); - CleanPath( gamePaths[ numGamePaths ] ); - numGamePaths++; -} - - - - -/* -InitPaths() - ydnar -cleaned up some of the path initialization code from bsp.c -will remove any arguments it uses -*/ - -void InitPaths( int *argc, char **argv ) -{ - int i, j, k, len, len2; - char temp[ MAX_OS_PATH ]; - char gamePath[MAX_OS_PATH], homeBasePath[MAX_OS_PATH], game_magic[10]; - - strcpy(gamePath, "base"); - strcpy(game_magic, "h"); - strcpy(homeBasePath, ".heretic2"); - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- InitPaths ---\n" ); - - /* get the install path for backup */ - LokiInitPaths( argv[ 0 ] ); - - /* set game to default (q3a) */ - numBasePaths = 0; - numGamePaths = 0; - - /* parse through the arguments and extract those relevant to paths */ - for( i = 0; i < *argc; i++ ) - { - /* check for null */ - if( argv[ i ] == NULL ) - continue; - - /* -fs_basepath */ - if( strcmp( argv[ i ], "-fs_basepath" ) == 0 ) - { - if( ++i >= *argc ) - Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); - argv[ i - 1 ] = NULL; - AddBasePath( argv[ i ] ); - argv[ i ] = NULL; - } - - } - - /* remove processed arguments */ - for( i = 0, j = 0, k = 0; i < *argc && j < *argc; i++, j++ ) - { - for( j; j < *argc && argv[ j ] == NULL; j++ ); - argv[ i ] = argv[ j ]; - if( argv[ i ] != NULL ) - k++; - } - *argc = k; - - /* add standard game path */ - AddGamePath( gamePath ); - - /* if there is no base path set, figure it out */ - if( numBasePaths == 0 ) - { - /* this is another crappy replacement for SetQdirFromPath() */ - len2 = strlen( game_magic ); - for( i = 0; i < *argc && numBasePaths == 0; i++ ) - { - /* extract the arg */ - strcpy( temp, argv[ i ] ); - CleanPath( temp ); - len = strlen( temp ); - Sys_FPrintf( SYS_VRB, "Searching for \"%s\" in \"%s\" (%d)...\n", game_magic, temp, i ); - - /* this is slow, but only done once */ - for( j = 0; j < (len - len2); j++ ) - { - /* check for the game's magic word */ - if( Q_strncasecmp( &temp[ j ], game_magic, len2 ) == 0 ) - { - /* now find the next slash and nuke everything after it */ - while( temp[ ++j ] != '/' && temp[ j ] != '\0' ); - temp[ j ] = '\0'; - - /* add this as a base path */ - AddBasePath( temp ); - break; - } - } - } - - /* add install path */ - if( numBasePaths == 0 ) - AddBasePath( installPath ); - - /* check again */ - if( numBasePaths == 0 ) - Error( "Failed to find a valid base path." ); - } - - /* this only affects unix */ - AddHomeBasePath( homeBasePath ); - - /* initialize vfs paths */ - if( numBasePaths > MAX_BASE_PATHS ) - numBasePaths = MAX_BASE_PATHS; - if( numGamePaths > MAX_GAME_PATHS ) - numGamePaths = MAX_GAME_PATHS; - - /* walk the list of game paths */ - //for( j = 0; j < numGamePaths; j++ ) - //{ - /* walk the list of base paths */ - // for( i = 0; i < numBasePaths; i++ ) - // { - /* create a full path and initialize it */ - // sprintf( temp, "%s/%s/", basePaths[ i ], gamePaths[ j ] ); - // vfsInitDirectory( temp ); - // } - //} - - /* done */ - Sys_Printf( "\n" ); -} - - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.c deleted file mode 100644 index ce1a909a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.c +++ /dev/null @@ -1,656 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#include "mathlib.h" -#include "polylib.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 8192 - -void pw(winding_t *w) -{ - int i; - for (i=0 ; inumpoints ; i++) - 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 (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 = malloc (s); - if (!w) - Error("AllocWinding MALLOC failed! Could not allocate %s bytes.", 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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, 8192, vup); - VectorScale (vright, 8192, 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 ; inumpoints ; 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]; - 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; - - if (in->numpoints >= MAX_POINTS_ON_WINDING-4) - Error ("ClipWinding: MAX_POINTS_ON_WINDING"); - - counts[0] = counts[1] = counts[2] = 0; - -// determine sides for each point - for (i=0 ; inumpoints ; 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 ; inumpoints ; 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]; - 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; - - if (!in) - { - printf ("Warning: NULL passed to ChopWindingInPlace\n"); - return; - } - if (in->numpoints >= MAX_POINTS_ON_WINDING-4) - Error ("ChopWinding: MAX_POINTS_ON_WINDING"); - -// determine sides for each point - for (i=0 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; i++) - { - p1 = w->p[i]; - - for (j=0 ; j<3 ; j++) - if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE) - Error ("CheckFace: BUGUS_RANGE: %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 ; jnumpoints ; 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 = false; - back = false; - for (i=0 ; inumpoints ; i++) - { - d = DotProduct (w->p[i], normal) - dist; - if (d < -ON_EPSILON) - { - if (front) - return SIDE_CROSS; - back = true; - continue; - } - if (d > ON_EPSILON) - { - if (back) - return SIDE_CROSS; - front = true; - continue; - } - } - - if (back) - return SIDE_BACK; - if (front) - return SIDE_FRONT; - return SIDE_ON; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.h deleted file mode 100644 index fec80e06..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright (C) 1999-2006 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 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/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.c deleted file mode 100644 index 25600a25..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.c +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "scriplib.h" -//#include - -materialtype_t defaultmaterialtypes[] = -{ - {"gravel", MATERIAL_GRAVEL}, - {"metal", MATERIAL_METAL}, - {"stone", MATERIAL_STONE}, - {"wood", MATERIAL_WOOD}, - {NULL, 0} -}; - -materialtype_t *materialtypes; - -void QFile_ReadMaterialTypes(char* filename) -{ - int i; - FILE *f; - - f = fopen (filename, "rb"); - if (!f) - { - materialtypes = defaultmaterialtypes; - return; - } - fclose (f); - - free(materialtypes); - materialtypes = (materialtype_t*)malloc(256 * sizeof(materialtype_t)); - - LoadScriptFile(filename); - i = 0; - - while (i < 255) - { - GetScriptToken (true); - if (endofscript) - { - break; - } - if (strcmp(token, "material") != 0) - { - while (ScriptTokenAvailable()) - { - GetScriptToken(false); - } - } - else - { - GetScriptToken(false); - materialtypes[i].name = (char*)malloc(strlen(token) + 1); - strcpy(materialtypes[i].name, token); - GetScriptToken (false); - materialtypes[i].value = atoi(token); - } - i++; - } - materialtypes[i].name = NULL; - materialtypes[i].value = 0; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.h deleted file mode 100644 index 3492136e..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.h +++ /dev/null @@ -1,619 +0,0 @@ -/* -Copyright (C) 1999-2006 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 - -#include "q_typedef.h" - -// -// qfiles.h: quake file formats -// This file must be identical in the quake and utils directories -// - -/* -======================================================================== - -The .pak files are just a linear collapse of a directory tree - -======================================================================== -*/ - -#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P') - -typedef struct -{ - char name[56]; - int filepos, filelen; -} dpackfile_t; - -typedef struct -{ - int ident; // == IDPAKHEADER - int dirofs; - int dirlen; -} dpackheader_t; - -#define MAX_FILES_IN_PACK 4096 - - -/* -======================================================================== - -PCX files are used for as many images as possible - -======================================================================== -*/ - -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; - - -/* -======================================================================== - -.MD2 compressed triangle model file format - -======================================================================== -*/ -#define IDJOINTEDALIASHEADER (('2'<<24)+('J'<<16)+('D'<<8)+'I') - -/* -======================================================================== - -.MD2 triangle model file format - -======================================================================== -*/ - -#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I') -#define ALIAS_VERSION 8 - -#define MAX_TRIANGLES 2048 -#define MAX_VERTS 2048 -#define MAX_FRAMES 512 -#define MAX_MD2SKINS 64 -#define MAX_SKINNAME 64 - -typedef struct -{ - short s; - short t; -} dstvert_t; - -typedef struct -{ - short index_xyz[3]; - short index_st[3]; -} dtriangle_t; - -typedef struct -{ - byte v[3]; // scaled byte to fit in frame mins/maxs - byte lightnormalindex; -} dtrivertx_t; - -#define DTRIVERTX_V0 0 -#define DTRIVERTX_V1 1 -#define DTRIVERTX_V2 2 -#define DTRIVERTX_LNI 3 -#define DTRIVERTX_SIZE 4 - -typedef struct -{ - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name from grabbing - dtrivertx_t verts[1]; // variable sized -} daliasframe_t; - - -// the glcmd format: -// a positive integer starts a tristrip command, followed by that many -// vertex structures. -// a negative integer starts a trifan command, followed by -x vertexes -// a zero indicates the end of the command list. -// a vertex consists of a floating point s, a floating point t, -// and an integer vertex index. - - -typedef struct -{ - int ident; - int version; - - int skinwidth; - int skinheight; - int framesize; // byte size of each frame - - int num_skins; - int num_xyz; - int num_st; // greater than num_xyz for seams - int num_tris; - int num_glcmds; // dwords in strip/fan command list - int num_frames; - - int ofs_skins; // each skin is a MAX_SKINNAME string - int ofs_st; // byte offset from start for stverts - int ofs_tris; // offset for dtriangles - int ofs_frames; // offset for first frame - int ofs_glcmds; - int ofs_end; // end of file - -} dmdl_t; - -/* -======================================================================== - -.BK file format - -======================================================================== -*/ - -#define IDBOOKHEADER (('K'<<24)+('O'<<16)+('O'<<8)+'B') -#define BOOK_VERSION 2 - -typedef struct bookframe_s -{ - int x; - int y; - int w; - int h; - char name[MAX_SKINNAME]; // name of gfx file -} bookframe_t; - -typedef struct bookheader_s -{ - unsigned int ident; - unsigned int version; - int num_segments; - int total_w; - int total_h; -} bookheader_t; - -typedef struct book_s -{ - bookheader_t bheader; - bookframe_t bframes[MAX_MD2SKINS]; -} book_t; - -/* -======================================================================== - -.SP2 sprite file format - -======================================================================== -*/ - -#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I') - // little-endian "IDS2" -#define SPRITE_VERSION 2 - -typedef struct -{ - int width, height; - int origin_x, origin_y; // raster coordinates inside pic - char name[MAX_SKINNAME]; // name of pcx file -} dsprframe_t; - -typedef struct { - int ident; - int version; - int numframes; - dsprframe_t frames[1]; // variable sized -} dsprite_t; - -/* -============================================================================== - - .M8 texture file format - -============================================================================== -*/ - -typedef struct palette_s -{ - union - { - struct - { - byte r,g,b; - }; - }; -} palette_t; - -#define MIP_VERSION 2 -#define PAL_SIZE 256 -#define MIPLEVELS 16 - -typedef struct miptex_s -{ - int version; - char name[32]; - unsigned width[MIPLEVELS], height[MIPLEVELS]; - unsigned offsets[MIPLEVELS]; // four mip maps stored - char animname[32]; // next frame in animation chain - palette_t palette[PAL_SIZE]; - int flags; - int contents; - int value; -} miptex_t; - - -#define MIP32_VERSION 4 - -#define MIP32_NOMIP_FLAG2 0x00000001 -#define MIP32_DETAILER_FLAG2 0x00000002 - -typedef struct miptex32_s -{ - int version; - char name[128]; - char altname[128]; // texture substitution - char animname[128]; // next frame in animation chain - char damagename[128]; // image that should be shown when damaged - unsigned width[MIPLEVELS], height[MIPLEVELS]; - unsigned offsets[MIPLEVELS]; - int flags; - int contents; - int value; - float scale_x, scale_y; - int mip_scale; - - // detail texturing info - char dt_name[128]; // detailed texture name - float dt_scale_x, dt_scale_y; - float dt_u, dt_v; - float dt_alpha; - int dt_src_blend_mode, dt_dst_blend_mode; - - int flags2; - int unused[19]; // future expansion to maintain compatibility with h2 -} miptex32_t; - - - -/* -============================================================================== - - .BSP file format - -============================================================================== -*/ - -#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') - // little-endian "IBSP" - -#define BSPVERSION 38 - - -// upper design bounds -// leaffaces, leafbrushes, planes, and verts are still bounded by -// 16 bit short limits -#define MAX_MAP_MODELS 1024 -#define MAX_MAP_BRUSHES 8192 -#define MAX_MAP_ENTITIES 2048 -#define MAX_MAP_ENTSTRING 0x40000 -#define MAX_MAP_TEXINFO 8192 - -#define MAX_MAP_AREAS 256 -#define MAX_MAP_AREAPORTALS 1024 -#define MAX_MAP_PLANES 65536 -#define MAX_MAP_NODES 65536 -#define MAX_MAP_BRUSHSIDES 65536 -#define MAX_MAP_LEAFS 65536 -#define MAX_MAP_VERTS 65536 -#define MAX_MAP_FACES 65536 -#define MAX_MAP_LEAFFACES 65536 -#define MAX_MAP_LEAFBRUSHES 65536 -#define MAX_MAP_PORTALS 65536 -#define MAX_MAP_EDGES 128000 -#define MAX_MAP_SURFEDGES 256000 -#define MAX_MAP_LIGHTING 0x200000 -#define MAX_MAP_VISIBILITY 0x180000 - -// key / value pair sizes - -#define MAX_KEY 32 -#define MAX_VALUE 1024 - -//============================================================================= - -typedef struct -{ - int fileofs, filelen; -} lump_t; - -#define LUMP_ENTITIES 0 -#define LUMP_PLANES 1 -#define LUMP_VERTEXES 2 -#define LUMP_VISIBILITY 3 -#define LUMP_NODES 4 -#define LUMP_TEXINFO 5 -#define LUMP_FACES 6 -#define LUMP_LIGHTING 7 -#define LUMP_LEAFS 8 -#define LUMP_LEAFFACES 9 -#define LUMP_LEAFBRUSHES 10 -#define LUMP_EDGES 11 -#define LUMP_SURFEDGES 12 -#define LUMP_MODELS 13 -#define LUMP_BRUSHES 14 -#define LUMP_BRUSHSIDES 15 -#define LUMP_POP 16 -#define LUMP_AREAS 17 -#define LUMP_AREAPORTALS 18 -#define HEADER_LUMPS 19 - -typedef struct -{ - int ident; - int version; - lump_t lumps[HEADER_LUMPS]; -} dheader_t; - -typedef struct -{ - float mins[3], maxs[3]; - float origin[3]; // for sounds or lights - int headnode; - int firstface, numfaces; // submodels just draw faces - // without walking the bsp tree -} dmodel_t; - - -typedef struct -{ - float point[3]; -} dvertex_t; - - -// 0-2 are axial planes -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 - -// 3-5 are non-axial planes snapped to the nearest -#define PLANE_ANYX 3 -#define PLANE_ANYY 4 -#define PLANE_ANYZ 5 - -// planes (x&~1) and (x&~1)+1 are allways opposites - -typedef struct -{ - float normal[3]; - float dist; - int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate -} dplane_t; - - -// contents flags are seperate bits -// a given brush can contribute multiple content bits -// multiple brushes can be in a single leaf - -// these definitions also need to be in q_shared.h! - -// lower bits are stronger, and will eat weaker brushes completely -#define CONTENTS_SOLID 0x00000001 // an eye is never valid in a solid -#define CONTENTS_WINDOW 0x00000002 // translucent, but not watery -#define CONTENTS_PUSHPULL 0x00000004 -#define CONTENTS_LAVA 0x00000008 -#define CONTENTS_SLIME 0x00000010 -#define CONTENTS_WATER 0x00000020 -#define CONTENTS_MIST 0x00000040 // 64 -#define LAST_VISIBLE_CONTENTS 64 // this one worries me a bit JKH - -// remaining contents are non-visible, and don't eat brushes - -#define CONTENTS_AREAPORTAL 0x00008000 - -#define CONTENTS_PLAYERCLIP 0x00010000 -#define CONTENTS_MONSTERCLIP 0x00020000 - -// currents can be added to any other contents, and may be mixed -#define CONTENTS_CURRENT_0 0x00040000 -#define CONTENTS_CURRENT_90 0x00080000 -#define CONTENTS_CURRENT_180 0x00100000 -#define CONTENTS_CURRENT_270 0x00200000 -#define CONTENTS_CURRENT_UP 0x00400000 -#define CONTENTS_CURRENT_DOWN 0x00800000 - -#define CONTENTS_ORIGIN 0x01000000 // removed before bsping an entity - -#define CONTENTS_MONSTER 0x02000000 // should never be on a brush, only in game -#define CONTENTS_DEADMONSTER 0x04000000 -#define CONTENTS_DETAIL 0x08000000 // brushes to be added after vis leafs -#define CONTENTS_TRANSLUCENT 0x10000000 // auto set if any surface has trans -#define CONTENTS_LADDER 0x20000000 - - - -#define SURF_LIGHT 0x00000001 // value will hold the light strength - -#define SURF_SLICK 0x00000002 // effects game physics - -#define SURF_SKY 0x00000004 // don't draw, but add to skybox -#define SURF_WARP 0x00000008 // turbulent water warp -#define SURF_TRANS33 0x00000010 -#define SURF_TRANS66 0x00000020 -#define SURF_FLOWING 0x00000040 // scroll towards angle -#define SURF_NODRAW 0x00000080 // don't bother referencing the texture - -#define SURF_HINT 0x00000100 // make a primary bsp splitter -#define SURF_SKIP 0x00000200 // completely ignore, allowing non-closed brushes -#define SURF_TALL_WALL 0x00000400 // face doesn't get broken up as normal - -#define SURF_ALPHA_TEXTURE 0x00000800 // texture has alpha in it, and should show through in bsp process -#define SURF_ANIMSPEED 0x00001000 // value will hold the anim speed in fps - -#define SURF_UNDULATE 0x00002000 // rock surface up and down... -#define SURF_SKYREFLECT 0x00004000 // liquid will somewhat reflect the sky - not quite finished.... - -#define SURF_TYPE_GRAVEL 0x00000000 -#define SURF_TYPE_METAL 0x01000000 -#define SURF_TYPE_STONE 0x02000000 -#define SURF_TYPE_WOOD 0x03000000 -#define SURF_MATERIAL 0xFF000000 - - - -typedef struct -{ - int planenum; - int children[2]; // negative numbers are -(leafs+1), not nodes - short mins[3]; // for frustom culling - short maxs[3]; - unsigned short firstface; - unsigned short numfaces; // counting both sides -} dnode_t; - - -typedef struct texinfo_s -{ - float vecs[2][4]; // [s/t][xyz offset] - int flags; // miptex flags + overrides - int value; // light emission, etc - char texture[32]; // texture name (textures/*.wal) - int nexttexinfo; // for animations, -1 = end of chain -} texinfo_t; - - -// note that edge 0 is never used, because negative edge nums are used for -// counterclockwise use of the edge in a face -typedef struct -{ - unsigned short v[2]; // vertex numbers -} dedge_t; - -#define MAXLIGHTMAPS 4 -typedef struct -{ - unsigned short planenum; - short side; - - int firstedge; // we must support > 64k edges - short numedges; - short texinfo; - -// lighting info - union { - byte styles[MAXLIGHTMAPS]; - paletteRGBA_t lighting; - }; - int lightofs; // start of [numstyles*surfsize] samples -} dface_t; - -typedef struct -{ - int contents; // OR of all brushes (not needed?) - - short cluster; - short area; - - short mins[3]; // for frustum culling - short maxs[3]; - - unsigned short firstleafface; - unsigned short numleaffaces; - - unsigned short firstleafbrush; - unsigned short numleafbrushes; -} dleaf_t; - -typedef struct -{ - unsigned short planenum; // facing out of the leaf - short texinfo; -} dbrushside_t; - -typedef struct -{ - int firstside; - int numsides; - int contents; -} dbrush_t; - -#define ANGLE_UP -1 -#define ANGLE_DOWN -2 - - -// the visibility lump consists of a header with a count, then -// byte offsets for the PVS and PHS of each cluster, then the raw -// compressed bit vectors -#define DVIS_PVS 0 -#define DVIS_PHS 1 -typedef struct -{ - int numclusters; - int bitofs[8][2]; // bitofs[numclusters][2] -} dvis_t; - -// each area has a list of portals that lead into other areas -// when portals are closed, other areas may not be visible or -// hearable even if the vis info says that it should be -typedef struct -{ - int portalnum; - int otherarea; -} dareaportal_t; - - -typedef struct -{ - int numareaportals; - int firstareaportal; -} darea_t; - -typedef struct -{ - char *name; - int value; -} materialtype_t; - -enum -{ - MATERIAL_GRAVEL, - MATERIAL_METAL, - MATERIAL_STONE, - MATERIAL_WOOD, -}; - -materialtype_t *materialtypes; - -void QFile_ReadMaterialTypes(char* filename); - - -#endif //_QFILES_H diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.c deleted file mode 100644 index c9001795..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.c +++ /dev/null @@ -1,297 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#include "scriplib.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 true if UnGetScriptToken was just called - -/* -============== -AddScriptToStack -============== -*/ -void AddScriptToStack (char *filename) -{ - int size; - - script++; - if (script == &scriptstack[MAX_INCLUDES]) - Error ("script file exceeded MAX_INCLUDES"); - strcpy (script->filename, ExpandPath (filename) ); - - size = LoadFile (script->filename, (void **)&script->buffer); - - printf ("entering %s\n", script->filename); - - script->line = 1; - - script->script_p = script->buffer; - script->end_p = script->buffer + size; -} - - -/* -============== -LoadScriptFile -============== -*/ -void LoadScriptFile (char *filename) -{ - script = scriptstack; - AddScriptToStack (filename); - - endofscript = false; - tokenready = false; -} - - -/* -============== -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 = false; - tokenready = false; -} - - -/* -============== -UnGetScriptToken - -Signals that the current token was not used, and should be reported -for the next GetScriptToken. Note that - -GetScriptToken (true); -UnGetScriptToken (); -GetScriptToken (false); - -could cross a line boundary. -============== -*/ -void UnGetScriptToken (void) -{ - tokenready = true; -} - - -qboolean EndOfScript (qboolean crossline) -{ - if (!crossline) - Error ("Line %i is incomplete\n",scriptline); - - if (!strcmp (script->filename, "memory buffer")) - { - endofscript = true; - return false; - } - - free (script->buffer); - if (script == scriptstack+1) - { - endofscript = true; - return false; - } - script--; - scriptline = script->line; - printf ("returning to %s\n", script->filename); - return GetScriptToken (crossline); -} - -/* -============== -GetScriptToken -============== -*/ -qboolean GetScriptToken (qboolean crossline) -{ - char *token_p; - - if (tokenready) // is a token allready waiting? - { - tokenready = false; - return true; - } - - if (script->script_p >= script->end_p) - 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); - 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); - 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] != '/') - { - 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")) - { - GetScriptToken (false); - AddScriptToStack (token); - return GetScriptToken (crossline); - } - - return true; -} - - -/* -============== -ScriptTokenAvailable - -Returns true if there is another token on the line -============== -*/ -qboolean ScriptTokenAvailable (void) -{ - char *search_p; - - search_p = script->script_p; - - if (search_p >= script->end_p) - return false; - - while ( *search_p <= 32) - { - if (*search_p == '\n') - return false; - search_p++; - if (search_p == script->end_p) - return false; - - } - - if (*search_p == ';') - return false; - - return true; -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.h deleted file mode 100644 index 4a87d582..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "cmdlib.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 (char *filename); -void ParseFromMemory (char *buffer, int size); - -qboolean GetScriptToken (qboolean crossline); -void UnGetScriptToken (void); -qboolean ScriptTokenAvailable (void); - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/threads.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/threads.c deleted file mode 100644 index bf37b9f7..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/threads.c +++ /dev/null @@ -1,620 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "her2_threads.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 = true; - - // - // run threads in parallel - // - InitializeCriticalSection (&crit); - - if (numthreads == 1) - { // use same thread - func (0); - } - else - { - for (i=0 ; i - -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 = true; - - 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 -#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 = true; - - if (pacifier) - setbuf (stdout, NULL); - - init_lock (&lck); - - for (i=0 ; i 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 = true; - - 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", - "", - "", - "", - "", - "", - "", - "(", - ")", - "{", - "}", - "[", - "]", - ":", - "mesh", - "model", - "nodes", - "rotation", - "scaling", - "translation", - "polygons", - "position", - "vertex", - "vertices", - "HRCH", - "Softimage" -}; - -// CODE -------------------------------------------------------------------- - -//========================================================================== -// -// TK_Init -// -//========================================================================== - -void TK_Init(void) -{ - int i; - - for(i = 0; i < 256; i++) - { - ASCIIToChrCode[i] = CHR_SPECIAL; - } - for(i = '0'; i <= '9'; i++) - { - ASCIIToChrCode[i] = CHR_NUMBER; - } - for(i = 'A'; i <= 'Z'; i++) - { - ASCIIToChrCode[i] = CHR_LETTER; - } - for(i = 'a'; i <= 'z'; i++) - { - ASCIIToChrCode[i] = CHR_LETTER; - } - ASCIIToChrCode[ASCII_QUOTE] = CHR_QUOTE; - ASCIIToChrCode[ASCII_UNDERSCORE] = CHR_LETTER; - ASCIIToChrCode[EOF_CHARACTER] = CHR_EOF; - tk_String = TokenStringBuffer; - IncLineNumber = FALSE; - SourceOpen = FALSE; -} - -//========================================================================== -// -// TK_OpenSource -// -//========================================================================== - -void TK_OpenSource(char *fileName) -{ - int size; - - TK_CloseSource(); - size = LoadFile(fileName, (void **)&FileStart); - strcpy(tk_SourceName, fileName); - SourceOpen = TRUE; - FileEnd = FileStart+size; - FilePtr = FileStart; - tk_Line = 1; - tk_Token = TK_NONE; - NextChr(); -} - -//========================================================================== -// -// TK_CloseSource -// -//========================================================================== - -void TK_CloseSource(void) -{ - if(SourceOpen) - { - free(FileStart); - SourceOpen = FALSE; - } -} - -//========================================================================== -// -// TK_Fetch -// -//========================================================================== - -tokenType_t TK_Fetch(void) -{ - while(Chr == ASCII_SPACE) - { - NextChr(); - } - if(Chr == '-') - { - ProcessNumberToken(); - } - else switch(ASCIIToChrCode[(byte)Chr]) - { - case CHR_EOF: - tk_Token = TK_EOF; - break; - case CHR_LETTER: - ProcessLetterToken(); - break; - case CHR_NUMBER: - ProcessNumberToken(); - break; - case CHR_QUOTE: - ProcessQuoteToken(); - break; - default: - ProcessSpecialToken(); - break; - } - return tk_Token; -} - -//========================================================================== -// -// TK_Require -// -//========================================================================== - -void TK_Require(tokenType_t tokType) -{ - if(tokType == TK_FLOATNUMBER && tk_Token == TK_INTNUMBER) - { - tk_FloatNumber = (float)tk_IntNumber; - tk_Token = TK_FLOATNUMBER; - return; - } - if(tk_Token != tokType) - { - Error("File '%s', line %d:\nExpected '%s', found '%s'.\n", - tk_SourceName, tk_Line, TokenNames[tokType], - TokenNames[tk_Token]); - } -} - -void TK_FetchRequire(tokenType_t tokType) -{ - TK_Fetch(); - TK_Require(tokType); -} - -tokenType_t TK_RequireFetch(tokenType_t tokType) -{ - TK_Require(tokType); - return TK_Fetch(); -} - -tokenType_t TK_FetchRequireFetch(tokenType_t tokType) -{ - TK_Fetch(); - TK_Require(tokType); - return TK_Fetch(); -} - -tokenType_t TK_Beyond(tokenType_t tokType) -{ - while(tk_Token != tokType) - { - if(TK_Fetch() == TK_EOF) - { - Error("File '%s':\nCould not find token '%s'.\n", // FIXME: TokenNames table not big enuff - tk_SourceName, TokenNames[tokType]); - } - } - return TK_Fetch(); -} - -void TK_BeyondRequire(tokenType_t bTok, tokenType_t rTok) -{ - TK_Beyond(bTok); - TK_Require(rTok); -} - -tokenType_t TK_Search(tokenType_t tokType) -{ - while(tk_Token != tokType) - { - if(TK_Fetch() == TK_EOF) - { - return TK_EOF; - } - } - return TK_Fetch(); -} - -tokenType_t TK_Get(tokenType_t tokType) -{ - while(tk_Token != tokType) - { - if(TK_Fetch() == TK_EOF) - { - Error("File '%s':\nCould not find token '%s'.\n", - tk_SourceName, TokenNames[tokType]); - } - } - return tk_Token; -} - -//========================================================================== -// -// ProcessLetterToken -// -//========================================================================== - -static void ProcessLetterToken(void) -{ - int i; - char *text; - - i = 0; - text = TokenStringBuffer; - while(ASCIIToChrCode[(byte)Chr] == CHR_LETTER - || ASCIIToChrCode[(byte)Chr] == CHR_NUMBER) - { - if(++i == MAX_IDENTIFIER_LENGTH) - { - Error("File '%s', line %d:\nIdentifier too long.\n", - tk_SourceName, tk_Line); - } - *text++ = Chr; - NextChr(); - } - *text = 0; - if(CheckForKeyword() == FALSE) - { - tk_Token = TK_IDENTIFIER; - } -} - -//========================================================================== -// -// CheckForKeyword -// -//========================================================================== - -static qboolean CheckForKeyword(void) -{ - int i; - - for(i = 0; Keywords[i].name != NULL; i++) - { - if(strcmp(tk_String, Keywords[i].name) == 0) - { - tk_Token = Keywords[i].token; - return TRUE; - } - } - return FALSE; -} - -//========================================================================== -// -// ProcessNumberToken -// -//========================================================================== - -static void ProcessNumberToken(void) -{ - char *buffer; - - buffer = TempBuffer; - *buffer++ = Chr; - NextChr(); - while(ASCIIToChrCode[(byte)Chr] == CHR_NUMBER) - { - *buffer++ = Chr; - NextChr(); - } - if(Chr == '.') - { // Float - *buffer++ = Chr; - NextChr(); // Skip period - while(ASCIIToChrCode[(byte)Chr] == CHR_NUMBER) - { - *buffer++ = Chr; - NextChr(); - } - *buffer = 0; - tk_FloatNumber = (float)atof(TempBuffer); - tk_Token = TK_FLOATNUMBER; - return; - } - - // Integer - *buffer = 0; - tk_IntNumber = atoi(TempBuffer); - tk_Token = TK_INTNUMBER; -} - -//========================================================================== -// -// ProcessQuoteToken -// -//========================================================================== - -static void ProcessQuoteToken(void) -{ - int i; - char *text; - - i = 0; - text = TokenStringBuffer; - NextChr(); - while(Chr != ASCII_QUOTE) - { - if(Chr == EOF_CHARACTER) - { - Error("File '%s', line %d:\n inside string.\n", - tk_SourceName, tk_Line); - } - if(++i > MAX_QUOTED_LENGTH-1) - { - Error("File '%s', line %d:\nString literal too long.\n", - tk_SourceName, tk_Line); - } - *text++ = Chr; - NextChr(); - } - *text = 0; - NextChr(); - tk_Token = TK_STRING; -} - -//========================================================================== -// -// ProcessSpecialToken -// -//========================================================================== - -static void ProcessSpecialToken(void) -{ - char c; - - c = Chr; - NextChr(); - switch(c) - { - case '(': - tk_Token = TK_LPAREN; - break; - case ')': - tk_Token = TK_RPAREN; - break; - case '{': - tk_Token = TK_LBRACE; - break; - case '}': - tk_Token = TK_RBRACE; - break; - case '[': - tk_Token = TK_LBRACKET; - break; - case ']': - tk_Token = TK_RBRACKET; - break; - case ':': - tk_Token = TK_COLON; - break; - default: - tk_Token = TK_UNKNOWNCHAR; - break; - } -} - -//========================================================================== -// -// NextChr -// -//========================================================================== - -static void NextChr(void) -{ - if(FilePtr >= FileEnd) - { - Chr = EOF_CHARACTER; - return; - } - if(IncLineNumber == TRUE) - { - tk_Line++; - IncLineNumber = FALSE; - } - Chr = *FilePtr++; - if(Chr < ASCII_SPACE) - { - if(Chr == '\n') - { - IncLineNumber = TRUE; - } - Chr = ASCII_SPACE; - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/token.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/token.h deleted file mode 100644 index 1e2fd27e..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/token.h +++ /dev/null @@ -1,132 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - - -//************************************************************************** -//** -//** token.h -//** -//************************************************************************** - -#ifndef __TOKEN_H__ -#define __TOKEN_H__ - -#include "cmdlib.h" - -#ifndef TRUE -#define TRUE 1 -#endif -#ifndef FALSE -#define FALSE 0 -#endif -#ifndef YES -#define YES 1 -#endif -#ifndef NO -#define NO 0 -#endif -#define ASCII_SPACE 32 -#define ASCII_QUOTE 34 -#define ASCII_UNDERSCORE 95 -#define EOF_CHARACTER 127 -#define MAX_IDENTIFIER_LENGTH 64 -#define MAX_QUOTED_LENGTH 1024 -#define MAX_FILE_NAME_LENGTH 1024 - -typedef enum -{ - TK_NONE, - TK_UNKNOWNCHAR, - TK_EOF, - TK_IDENTIFIER, // VALUE: (char *) tk_String - TK_STRING, // VALUE: (char *) tk_String - TK_INTNUMBER, // VALUE: (int) tk_IntNumber - TK_FLOATNUMBER, // VALUE: (float) tk_FloatNumber - TK_LPAREN, - TK_RPAREN, - TK_LBRACE, - TK_RBRACE, // 10 - TK_LBRACKET, - TK_RBRACKET, - TK_COLON, - TK_MESH, - TK_MODEL, // 15 - TK_NODES, - TK_ROTATION, - TK_SCALING, - TK_TRANSLATION, - TK_POLYGONS, // 20 - TK_POSITION, - TK_VERTEX, - TK_VERTICES, - TK_EDGES, - TK_HRCH, // 25 - TK_SOFTIMAGE, - TK_MATERIAL, - TK_SPLINE, // 28 - - TK_C_NAMED, - TK_OBJECT, // 30 - TK_C_TRI, - TK_C_VERTICES, - TK_C_FACES, - TK_C_VERTEX, - TK_LIST, // 35 - TK_C_FACE, - - TK_C_HEXEN, - TK_C_TRIANGLES, - TK_C_VERSION, - TK_FACES, // 40 - TK_FACE, - TK_ORIGIN, - - TK_CLUSTERS, - TK_NUM_CLUSTER_VERTICES, - TK_NAME, // 45 - TK_CLUSTER_NAME, - TK_CLUSTER_STATE, - - TK_ACTOR_DATA, - TK_UVTEXTURE, -} tokenType_t; - -void TK_Init(void); -void TK_OpenSource(char *fileName); -void TK_CloseSource(void); -tokenType_t TK_Fetch(void); -void TK_Require(tokenType_t tokType); -void TK_FetchRequire(tokenType_t tokType); -tokenType_t TK_RequireFetch(tokenType_t tokType); -tokenType_t TK_FetchRequireFetch(tokenType_t tokType); -tokenType_t TK_Beyond(tokenType_t tokType); -void TK_BeyondRequire(tokenType_t bTok, tokenType_t rTok); -tokenType_t TK_Search(tokenType_t tokType); -tokenType_t TK_Get(tokenType_t tokType); - -extern tokenType_t tk_Token; -extern int tk_Line; -extern int tk_IntNumber; -extern float tk_FloatNumber; -extern char *tk_String; -extern char tk_SourceName[MAX_FILE_NAME_LENGTH]; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.c deleted file mode 100644 index e7583447..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.c +++ /dev/null @@ -1,1077 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#include "mathlib.h" -#include "trilib.h" -#include "token.h" -#include "l3dslib.h" -#include "fmodel.h" -#if 1 -#include "qd_skeletons.h" -#endif - -// on disk representation of a face -#define FLOAT_START 99999.0 -#define FLOAT_END -FLOAT_START -#define MAGIC 123322 -#ifndef M_PI - #define M_PI 3.14159265 -#endif - -float FixHTRRotateX = 0.0; -float FixHTRRotateY = 0.0; -float FixHTRRotateZ = 0.0; -float FixHTRTranslateX = 0.0; -float FixHTRTranslateY = 0.0; -float FixHTRTranslateZ = 0.0; - -//#define NOISY 1 - -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; - - -void ByteSwapTri (tf_triangle *tri) -{ - int i; - - for (i=0 ; iverts[j][k] = tri.pt[j].p.v[k]; - } - } - - ptri++; - - if ((ptri - *pptri) >= MAXTRIANGLES) - Error ("Error: too many triangles; increase MAXTRIANGLES\n"); - } - } - - *numtriangles = ptri - *pptri; - - fclose (input); - - DefaultNodesList(nodesList,num_mesh_nodes,numtriangles); -} - - -//========================================================================== -// -// LoadHRC -// -//========================================================================== - -float scaling[3]; -float rotation[3]; -float translation[3]; -static char *hrc_name; - -struct -{ - float v[3]; -} vList[8192]; - -void HandleHRCModel(triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes, - int ActiveNode, int Depth, int numVerts) -{ - void ReadHRCClusterList(mesh_node_t *meshNode, int baseIndex); - - int i, j; - int vertexCount; - int triCount; - triangle_t *tList; - mesh_node_t *meshNode; - float x, y, z; - float x2, y2, z2; - float rx, ry, rz; - tokenType_t nextToken; - float orig_scaling[3]; - float orig_rotation[3]; - float orig_translation[3]; - int start_tri; - int pos,bit; - int vertIndexBase; - - // Update Node Info - if (nodesList) - { - TK_BeyondRequire(TK_NAME, TK_STRING); - - if (Depth == 0 || tk_String[0] == '_') - { // Root - ActiveNode = *num_mesh_nodes; - (*num_mesh_nodes)++; - if ((*num_mesh_nodes) > MAX_FM_MESH_NODES) - { - Error("Too many mesh nodes in file %s\n", hrc_name); - } - meshNode = &(*nodesList)[ActiveNode]; - -// memset(meshNode, 0, sizeof(mesh_node_t)); - strcpy(meshNode->name, tk_String); - - memset(meshNode->tris, 0, sizeof(meshNode->tris)); - memset(meshNode->verts, 0, sizeof(meshNode->verts)); - - meshNode->start_glcmds = 0; - meshNode->num_glcmds = 0; - vertIndexBase = 0; - } - else - { // Childs under the children - meshNode = &(*nodesList)[ActiveNode]; - vertIndexBase = numVerts; - } - } - else - { - meshNode = NULL; - } - - - // Get the scaling, rotation, and translation values - TK_Beyond(TK_SCALING); - for(i = 0; i < 3; i++) - { - orig_scaling[i] = scaling[i]; - - TK_Require(TK_FLOATNUMBER); - scaling[i] *= tk_FloatNumber; - - TK_Fetch(); - } - TK_Beyond(TK_ROTATION); - for(i = 0; i < 3; i++) - { - orig_rotation[i] = rotation[i]; - - TK_Require(TK_FLOATNUMBER); - rotation[i] = tk_FloatNumber; - - TK_Fetch(); - } - TK_Beyond(TK_TRANSLATION); - for(i = 0; i < 3; i++) - { - orig_translation[i] = translation[i]; - - TK_Require(TK_FLOATNUMBER); - translation[i] += tk_FloatNumber; - - TK_Fetch(); - } - - rx = ((rotation[0]-90.0)/360.0)*2.0*M_PI; - ry = (rotation[2]/360.0)*2.0*M_PI; - rz = (rotation[1]/360.0)*2.0*M_PI; - - // rjr - might not work if there an item doesn't have a mesh - nextToken = tk_Token; - if (nextToken == TK_ACTOR_DATA) - { - while (nextToken != TK_MODEL && nextToken != TK_RBRACE) - { - nextToken = TK_Fetch(); - } - } - - while (nextToken == TK_SPLINE) - { // spline node has two right braces - nextToken = TK_Beyond(TK_RBRACE); - nextToken = TK_Beyond(TK_RBRACE); - } - - while (nextToken == TK_MATERIAL) - { - nextToken = TK_Beyond(TK_RBRACE); - } - - while(nextToken == TK_MODEL) - { - HandleHRCModel(triList,triangleCount,nodesList,num_mesh_nodes,ActiveNode, Depth+1, 0); - - nextToken = TK_Fetch(); - } - - if (nextToken == TK_MESH) - { - // Get all the tri and vertex info - TK_BeyondRequire(TK_VERTICES, TK_INTNUMBER); - vertexCount = tk_IntNumber; - for(i = 0; i < vertexCount; i++) - { - TK_BeyondRequire(TK_LBRACKET, TK_INTNUMBER); - if(tk_IntNumber != i) - { - Error("File '%s', line %d:\nVertex index mismatch.\n", - tk_SourceName, tk_Line); - } - TK_Beyond(TK_POSITION); - // Apply the scaling, rotation, and translation in the order - // specified in the HRC file. This could be wrong. - TK_Require(TK_FLOATNUMBER); - x = tk_FloatNumber*scaling[0]; - TK_FetchRequire(TK_FLOATNUMBER); - y = tk_FloatNumber*scaling[1]; - TK_FetchRequire(TK_FLOATNUMBER); - z = tk_FloatNumber*scaling[2]; - - y2 = y*cos(rx)+z*sin(rx); - z2 = -y*sin(rx)+z*cos(rx); - y = y2; - z = z2; - - x2 = x*cos(ry)-z*sin(ry); - z2 = x*sin(ry)+z*cos(ry); - x = x2; - z = z2; - - x2 = x*cos(rz)+y*sin(rz); - y2 = -x*sin(rz)+y*cos(rz); - x = x2; - y = y2; - - vList[i].v[0] = x+translation[0]; - vList[i].v[1] = y-translation[2]; - vList[i].v[2] = z+translation[1]; - } - TK_BeyondRequire(TK_POLYGONS, TK_INTNUMBER); - triCount = tk_IntNumber; - if(triCount >= MAXTRIANGLES) - { - Error("Too many triangles in file %s\n", hrc_name); - } - - start_tri = *triangleCount; - *triangleCount += triCount; - - tList = *triList; - - for(i = 0; i < triCount; i++) - { - if (meshNode) - { // Update the node - pos = (i + start_tri) >> 3; - bit = 1 << ((i + start_tri) & 7 ); - meshNode->tris[pos] |= bit; - } - - TK_BeyondRequire(TK_LBRACKET, TK_INTNUMBER); - if(tk_IntNumber != i) - { - Error("File '%s', line %d:\nTriangle index mismatch.\n", - tk_SourceName, tk_Line); - } - TK_BeyondRequire(TK_NODES, TK_INTNUMBER); - if(tk_IntNumber != 3) - { - Error("File '%s', line %d:\nBad polygon vertex count: %d.", - tk_SourceName, tk_Line, tk_IntNumber); - } - tList[i+start_tri].HasUV = true; - for(j = 0; j < 3; j++) - { - TK_BeyondRequire(TK_LBRACKET, TK_INTNUMBER); - if(tk_IntNumber != j) - { - Error("File '%s', line %d:\nTriangle vertex index" - " mismatch. %d should be %d\n", tk_SourceName, tk_Line, - tk_IntNumber, j); - } - TK_BeyondRequire(TK_VERTEX, TK_INTNUMBER); - - tList[i+start_tri].verts[2-j][0] = vList[tk_IntNumber].v[0]; - tList[i+start_tri].verts[2-j][1] = vList[tk_IntNumber].v[1]; - tList[i+start_tri].verts[2-j][2] = vList[tk_IntNumber].v[2]; -#if 1 - tList[i+start_tri].indicies[2-j] = tk_IntNumber+vertIndexBase; -#endif - TK_BeyondRequire(TK_UVTEXTURE, TK_FLOATNUMBER); - tList[i+start_tri].uv[2-j][0] = tk_FloatNumber; - TK_Fetch(); - TK_Require(TK_FLOATNUMBER); - tList[i+start_tri].uv[2-j][1] = tk_FloatNumber; - } - - /* printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" - " v2: %f, %f, %f\n", i, - tList[i].verts[0][0], - tList[i].verts[0][1], - tList[i].verts[0][2], - tList[i].verts[1][0], - tList[i].verts[1][1], - tList[i].verts[1][2], - tList[i].verts[2][0], - tList[i].verts[2][1], - tList[i].verts[2][2]); - */ - } - - TK_Beyond(TK_RBRACE); - TK_Beyond(TK_RBRACE); - - if (tk_Token == TK_EDGES) - { - // TK_Beyond(TK_EDGES); - TK_Beyond(TK_RBRACE); - } - - scaling[0] = scaling[1] = scaling[2] = 1.0; - // rotation[0] = rotation[1] = rotation[2] = 0.0; - // translation[0] = translation[1] = translation[2] = 0.0; - - // See if there are any other models belonging to this node - -#if 1 - TK_Fetch(); - - nextToken = tk_Token; - if(nextToken == TK_CLUSTERS) - { - if(g_skelModel.clustered == -1) - { - ReadHRCClusterList(meshNode, vertIndexBase); - } - else - { - nextToken = TK_Get(TK_CLUSTER_NAME); - - while (nextToken == TK_CLUSTER_NAME) - { - TK_BeyondRequire(TK_CLUSTER_STATE, TK_INTNUMBER); - nextToken = TK_Fetch(); - } - } - - // one right brace follow the list of clusters - nextToken = TK_Beyond(TK_RBRACE); - } - else - { - if(g_skelModel.clustered == -1 && !vertIndexBase) - { - meshNode->clustered = false; - } - } -#endif - - nextToken = tk_Token; - if(nextToken == TK_SPLINE) - { - while (nextToken == TK_SPLINE) - { // spline node has two right braces - nextToken = TK_Beyond(TK_RBRACE); - nextToken = TK_Beyond(TK_RBRACE); - } - - nextToken = TK_Beyond(TK_RBRACE); - } - - while (nextToken == TK_MATERIAL) - { - nextToken = TK_Beyond(TK_RBRACE); - } - - while(nextToken == TK_MODEL) - { - HandleHRCModel(triList,triangleCount,nodesList, num_mesh_nodes, ActiveNode, Depth+1, vertexCount+vertIndexBase); - - nextToken = TK_Fetch(); - } - } - - for(i=0;i<3;i++) - { - scaling[i] = orig_scaling[i]; - rotation[i] = orig_rotation[i]; - translation[i] = orig_translation[i]; - } -} - -static void LoadHRC(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) -{ - if (nodesList) - { - *num_mesh_nodes = 0; - - if(!*nodesList) - { - *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); - } - } - - hrc_name = fileName; - - scaling[0] = scaling[1] = scaling[2] = 1.0; - rotation[0] = rotation[1] = rotation[2] = 0.0; - translation[0] = translation[1] = translation[2] = 0.0; - - *triangleCount = 0; - *triList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); - memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - - // prime it - TK_Beyond(TK_MODEL); - - HandleHRCModel(triList, triangleCount, nodesList, num_mesh_nodes, 0, 0, 0); - TK_CloseSource(); -} - -//========================================================================== -// -// LoadHTR -// -//========================================================================== -/* -static int Version2; - -void HandleHTRModel(triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes, - int ActiveNode, int Depth, int numVerts) -{ - int i, j; - int vertexCount; - int vertexNum; - int triCount; - float origin[3]; - triangle_t *tList; - float x, y, z; - float x2, y2, z2; - float rx, ry, rz; - mesh_node_t *meshNode; - int pos,bit; - int vertIndexBase; - int start_tri; - - if (nodesList) - { - TK_BeyondRequire(TK_NAME, TK_STRING); - - if (Depth == 0 || tk_String[0] == '_') - { // Root - ActiveNode = *num_mesh_nodes; - (*num_mesh_nodes)++; - if ((*num_mesh_nodes) > MAX_FM_MESH_NODES) - { - Error("Too many mesh nodes in file %s\n", hrc_name); - } - meshNode = &(*nodesList)[ActiveNode]; - -// memset(meshNode, 0, sizeof(mesh_node_t)); - strcpy(meshNode->name, tk_String); - - memset(meshNode->tris, 0, sizeof(meshNode->tris)); - memset(meshNode->verts, 0, sizeof(meshNode->verts)); - - meshNode->start_glcmds = 0; - meshNode->num_glcmds = 0; - vertIndexBase = 0; - } - else - { // Childs under the children - meshNode = &(*nodesList)[ActiveNode]; - vertIndexBase = numVerts; - } - } - else - { - meshNode = NULL; - } - - // Get vertex count - TK_BeyondRequire(TK_VERTICES, TK_INTNUMBER); - vertexCount = tk_IntNumber; - - // Get triangle count - TK_BeyondRequire(TK_FACES, TK_INTNUMBER); - triCount = tk_IntNumber; - if(triCount >= MAXTRIANGLES) - { - Error("Too many triangles in file %s\n", hrc_name); - } - - // Get origin - TK_Beyond(TK_ORIGIN); - TK_Require(TK_FLOATNUMBER); - origin[0] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - origin[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - origin[2] = tk_FloatNumber; - - //rx = 90.0/360.0*2.0*M_PI; - rx = FixHTRRotateX/360.0*2.0*M_PI; - ry = FixHTRRotateY/360.0*2.0*M_PI; - rz = FixHTRRotateZ/360.0*2.0*M_PI; - - // Get vertex list - for(i = 0; i < vertexCount; i++) - { - TK_FetchRequire(TK_VERTEX); - TK_FetchRequire(TK_FLOATNUMBER); - x = tk_FloatNumber-origin[0]; - TK_FetchRequire(TK_FLOATNUMBER); - y = tk_FloatNumber-origin[1]; - TK_FetchRequire(TK_FLOATNUMBER); - z = tk_FloatNumber-origin[2]; - - x += FixHTRTranslateX; - y += FixHTRTranslateY; - z += FixHTRTranslateZ; - - y2 = y*cos(rx)-z*sin(rx); - z2 = y*sin(rx)+z*cos(rx); - y = y2; - z = z2; - x2 = x*cos(ry)+z*sin(ry); - z2 = -x*sin(ry)+z*cos(ry); - x = x2; - z = z2; - x2 = x*cos(rz)-y*sin(rz); - y2 = x*sin(rz)+y*cos(rz); - x = x2; - y = y2; - - vList[i].v[0] = x; - vList[i].v[1] = y; - vList[i].v[2] = z; - } - - start_tri = *triangleCount; - *triangleCount += triCount; - - tList = *triList; - - // Get face list - for(i = 0; i < triCount; i++) - { - if (meshNode) - { // Update the node - pos = (i + start_tri) >> 3; - bit = 1 << ((i + start_tri) & 7 ); - meshNode->tris[pos] |= bit; - } - - TK_FetchRequire(TK_FACE); - TK_FetchRequire(TK_LPAREN); - for(j = 0; j < 3; j++) - { - TK_FetchRequire(TK_INTNUMBER); - vertexNum = tk_IntNumber-1; - if(vertexNum >= vertexCount) - { - Error("File '%s', line %d:\nVertex number" - " >= vertexCount: %d\n", tk_SourceName, tk_Line, - tk_IntNumber); - } - tList[i+start_tri].verts[2-j][0] = vList[vertexNum].v[0]; - tList[i+start_tri].verts[2-j][1] = vList[vertexNum].v[1]; - tList[i+start_tri].verts[2-j][2] = vList[vertexNum].v[2]; - } - TK_FetchRequire(TK_RPAREN); -#ifdef _QDATA - if (Version2) - { - TK_FetchRequire(TK_FLOATNUMBER); - tList[i+start_tri].uv[0][0]=tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - tList[i+start_tri].uv[0][1]=tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - tList[i+start_tri].uv[1][0]=tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - tList[i+start_tri].uv[1][1]=tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - tList[i+start_tri].uv[2][0]=tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - tList[i+start_tri].uv[2][1]=tk_FloatNumber; - tList[i+start_tri].HasUV=1; - } - else - tList[i+start_tri].HasUV=0; -#endif -// printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" -// " v2: %f, %f, %f\n", i, -// tList[i].verts[0][0], -// tList[i].verts[0][1], -// tList[i].verts[0][2], -// tList[i].verts[1][0], -// tList[i].verts[1][1], -// tList[i].verts[1][2], -// tList[i].verts[2][0], -// tList[i].verts[2][1], -// tList[i].verts[2][2]); - - } - - TK_Fetch(); - - if (tk_Token == TK_VERTICES) - { - HandleHTRModel(triList,triangleCount,nodesList, num_mesh_nodes, ActiveNode, Depth+1, vertexCount+vertIndexBase); - } -} - -static void LoadHTR(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) -{ - if (nodesList) - { - *num_mesh_nodes = 0; - - if(!*nodesList) - { - *nodesList = SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); - } - } - - hrc_name = fileName; - - scaling[0] = scaling[1] = scaling[2] = 1.0; - rotation[0] = rotation[1] = rotation[2] = 0.0; - translation[0] = translation[1] = translation[2] = 0.0; - - *triangleCount = 0; - *triList = SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); - memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); - - TK_OpenSource(fileName); - - TK_Beyond(TK_C_HEXEN); - TK_Beyond(TK_C_TRIANGLES); - TK_BeyondRequire(TK_C_VERSION, TK_INTNUMBER); - if(tk_IntNumber != 1&&tk_IntNumber != 2) - { - Error("Unsupported version (%d) in file %s\n", tk_IntNumber, - fileName); - } - Version2=(tk_IntNumber==2); - - - HandleHTRModel(triList, triangleCount, nodesList, num_mesh_nodes, 0, 0, 0); -} - -*/ - -static void LoadHTR(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) -{ - int Version2=0; - int i, j; - int vertexCount; - int vertexNum; - struct - { - float v[3]; - } *vList; - int triCount; - float origin[3]; - triangle_t *tList; - float x, y, z; - float x2, y2, z2; - float rx, ry, rz; - - if (nodesList) - { - *num_mesh_nodes = 0; - *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); - } - - TK_OpenSource(fileName); - - TK_Beyond(TK_C_HEXEN); - TK_Beyond(TK_C_TRIANGLES); - TK_BeyondRequire(TK_C_VERSION, TK_INTNUMBER); - if(tk_IntNumber != 1&&tk_IntNumber != 2) - { - Error("Unsupported version (%d) in file %s\n", tk_IntNumber, - fileName); - } - Version2=(tk_IntNumber==2); - - - // Get vertex count - TK_BeyondRequire(TK_VERTICES, TK_INTNUMBER); - vertexCount = tk_IntNumber; - vList = (void *) SafeMalloc(vertexCount*sizeof vList[0], "Vertex list"); - - // Get triangle count - TK_BeyondRequire(TK_FACES, TK_INTNUMBER); - triCount = tk_IntNumber; - if(triCount >= MAXTRIANGLES) - { - Error("Too many triangles in file %s\n", fileName); - } - *triangleCount = triCount; - tList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); - *triList = tList; - memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); - - // Get origin - TK_Beyond(TK_ORIGIN); - TK_Require(TK_FLOATNUMBER); - origin[0] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - origin[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - origin[2] = tk_FloatNumber; - - //rx = 90.0/360.0*2.0*M_PI; - rx = FixHTRRotateX/360.0*2.0*M_PI; - ry = FixHTRRotateY/360.0*2.0*M_PI; - rz = FixHTRRotateZ/360.0*2.0*M_PI; - - // Get vertex list - for(i = 0; i < vertexCount; i++) - { - TK_FetchRequire(TK_VERTEX); - TK_FetchRequire(TK_FLOATNUMBER); - x = tk_FloatNumber-origin[0]; - TK_FetchRequire(TK_FLOATNUMBER); - y = tk_FloatNumber-origin[1]; - TK_FetchRequire(TK_FLOATNUMBER); - z = tk_FloatNumber-origin[2]; - - x += FixHTRTranslateX; - y += FixHTRTranslateY; - z += FixHTRTranslateZ; - - y2 = y*cos(rx)-z*sin(rx); - z2 = y*sin(rx)+z*cos(rx); - y = y2; - z = z2; - x2 = x*cos(ry)+z*sin(ry); - z2 = -x*sin(ry)+z*cos(ry); - x = x2; - z = z2; - x2 = x*cos(rz)-y*sin(rz); - y2 = x*sin(rz)+y*cos(rz); - x = x2; - y = y2; - - vList[i].v[0] = x; - vList[i].v[1] = y; - vList[i].v[2] = z; - } - - // Get face list - for(i = 0; i < triCount; i++) - { - TK_FetchRequire(TK_FACE); - TK_FetchRequire(TK_LPAREN); - for(j = 0; j < 3; j++) - { - TK_FetchRequire(TK_INTNUMBER); - vertexNum = tk_IntNumber-1; - if(vertexNum >= vertexCount) - { - Error("File '%s', line %d:\nVertex number" - " >= vertexCount: %d\n", tk_SourceName, tk_Line, - tk_IntNumber); - } - tList[i].verts[2-j][0] = vList[vertexNum].v[0]; - tList[i].verts[2-j][1] = vList[vertexNum].v[1]; - tList[i].verts[2-j][2] = vList[vertexNum].v[2]; - } - TK_FetchRequire(TK_RPAREN); -#if 1 - if (Version2) - { - TK_FetchRequire(TK_FLOATNUMBER); - tList[i].uv[2][0]= fmod(1000+tk_FloatNumber,1); - TK_FetchRequire(TK_FLOATNUMBER); - tList[i].uv[2][1]=fmod(1000+tk_FloatNumber,1); - TK_FetchRequire(TK_FLOATNUMBER); - tList[i].uv[1][0]=fmod(1000+tk_FloatNumber,1); - TK_FetchRequire(TK_FLOATNUMBER); - tList[i].uv[1][1]=fmod(1000+tk_FloatNumber,1); - TK_FetchRequire(TK_FLOATNUMBER); - tList[i].uv[0][0]=fmod(1000+tk_FloatNumber,1); - TK_FetchRequire(TK_FLOATNUMBER); - tList[i].uv[0][1]=fmod(1000+tk_FloatNumber,1); - tList[i].HasUV=1; - } - else - tList[i].HasUV=0; -#endif -/* printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" - " v2: %f, %f, %f\n", i, - tList[i].verts[0][0], - tList[i].verts[0][1], - tList[i].verts[0][2], - tList[i].verts[1][0], - tList[i].verts[1][1], - tList[i].verts[1][2], - tList[i].verts[2][0], - tList[i].verts[2][1], - tList[i].verts[2][2]); -*/ - } - - free(vList); - TK_CloseSource(); - DefaultNodesList(nodesList,num_mesh_nodes,triangleCount); -} - -//========================================================================== -// -// LoadTriangleList -// -//========================================================================== - -void LoadTriangleList(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **ppmnodes, int *num_mesh_nodes) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - LoadHRC(InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - printf(" - assuming .HRC\n"); - return; - } - - strcpy(InputFileName, fileName); - strcat(InputFileName, ".asc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - LoadASC(InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - printf(" - assuming .ASC\n"); - return; - } - - strcpy(InputFileName, fileName); - strcat(InputFileName, ".tri"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - LoadTRI(InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - printf(" - assuming .TRI\n"); - return; - } - - strcpy(InputFileName, fileName); - strcat(InputFileName, ".3ds"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - Load3DSTriangleList (InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - printf(" - assuming .3DS\n"); - return; - } - - strcpy(InputFileName, fileName); - strcat(InputFileName, ".htr"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - LoadHTR (InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - printf(" - assuming .HTR\n"); - return; - } - Error("\n Could not open file '%s':\n" - "No HRC, ASC, 3DS, HTR, or TRI match.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { - printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRC(fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - } - else if (strcmp(dotstart,".asc") == 0 || strcmp(dotstart,".ASC") == 0) - { - LoadASC(fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - } - else if (strcmp(dotstart,".tri") == 0 || strcmp(dotstart,".TRI") == 0) - { - LoadTRI(fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - } - else if (strcmp(dotstart,".3ds") == 0 || strcmp(dotstart,".3DS") == 0) - { - Load3DSTriangleList (fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - } - else if (strcmp(dotstart,".htr") == 0 || strcmp(dotstart,".HTR") == 0) - { - LoadHTR (fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); - } - else - { - Error("Could not open file '%s':\n",fileName); - return; - } - } - else //failed to load file - { - Error("Could not open file '%s':\n",fileName); - } - - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.h deleted file mode 100644 index 94263e0b..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -// - -#include "fmodel.h" - -#define MAXTRIANGLES MAX_FM_TRIANGLES - -typedef struct -{ - vec3_t verts[3]; -#if 1 - int indicies[3]; - float uv[3][2]; - qboolean HasUV; -#endif -} triangle_t; - -#define NUM_CLUSTERS 8 - -typedef struct -{ - char name[64]; - byte tris[MAXTRIANGLES>>3]; - byte verts[MAX_FM_VERTS>>3]; - int start_glcmds, num_glcmds; - - int *clusters[NUM_CLUSTERS]; - struct IntListNode_s *vertLists[NUM_CLUSTERS]; - int num_verts[NUM_CLUSTERS + 1]; - int new_num_verts[NUM_CLUSTERS + 1]; - qboolean clustered; -} mesh_node_t; - -void LoadTriangleList (char *filename, triangle_t **pptri, int *numtriangles, mesh_node_t **ppmnodes, int *num_mesh_nodes); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/fmodels.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/fmodels.c deleted file mode 100644 index 7570240a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/fmodels.c +++ /dev/null @@ -1,3404 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qd_fmodel.h" -#include "animcomp.h" -#include "qd_skeletons.h" -#include "skeletons.h" -#include "qdata.h" -#include "flex.h" -#include "reference.h" - -#include - -/* -======================================================================== - -.FM triangle flexible model file format - -======================================================================== -*/ - -//================================================================= - -#define NUMVERTEXNORMALS 162 - -extern float avertexnormals[NUMVERTEXNORMALS][3]; - -#define MAX_GROUPS 128 - -typedef struct -{ - triangle_t triangle; - int group; -} trigroup_t; - -#define TRIVERT_DIST .1 - -typedef struct -{ - int start_frame; - int num_frames; - int degrees; - char *mat; - char *ccomp; - char *cbase; - float *cscale; - float *coffset; - float trans[3]; - float scale[3]; - float bmin[3]; - float bmax[3]; -} fmgroup_t; - -//================================================================ - -// Initial -fmheader_t fmheader; - -// Skin -extern char g_skins[MAX_FM_SKINS][64]; - -// ST Coord -extern fmstvert_t base_st[MAX_FM_VERTS]; - -// Triangles -extern fmtriangle_t triangles[MAX_FM_TRIANGLES]; - -// Frames -fmframe_t g_frames[MAX_FM_FRAMES]; -//fmframe_t *g_FMframes; - -// GL Commands -extern int commands[16384]; -extern int numcommands; - - -// -// varibles set by commands -// -extern float scale_up; // set by $scale -extern vec3_t adjust; // set by $origin -extern int g_fixedwidth, g_fixedheight; // set by $skinsize -extern char modelname[64]; // set by $modelname - - -extern char *g_outputDir; - - -// Mesh Nodes -mesh_node_t *pmnodes = NULL; -fmmeshnode_t mesh_nodes[MAX_FM_MESH_NODES]; - -fmgroup_t groups[MAX_GROUPS]; -int num_groups; -int frame_to_group[MAX_FM_FRAMES]; - -// -// variables set by command line arguments -// -qboolean g_no_opimizations = false; - - -// -// base frame info -// -static int triangle_st[MAX_FM_TRIANGLES][3][2]; - - -// number of gl vertices -extern int numglverts; -// indicates if a triangle has already been used in a glcmd -extern int used[MAX_FM_TRIANGLES]; -// indicates if a triangle has translucency in it or not -static qboolean translucent[MAX_FM_TRIANGLES]; - -// main output file handle -extern FILE *headerouthandle; -// output sizes of buildst() -static int skin_width, skin_height; - - -// statistics -static int total_skin_pixels; -static int skin_pixels_used; - -int ShareVertex( trigroup_t trione, trigroup_t tritwo); -float DistBetween(vec3_t point1, vec3_t point2); -int GetNumTris( trigroup_t *tris, int group); -void GetOneGroup(trigroup_t *tris, int grp, triangle_t* triangles); -void ScaleTris( vec3_t min, vec3_t max, int Width, int Height, float* u, float* v, int verts); -void NewDrawLine(int x1, int y1, int x2, int y2, unsigned char* picture, int width, int height); - -#ifndef _WIN32 - -void strupr(char *string) -{ - int i; - - for (i=0 ; iverts[fmheader.num_xyz]; - - WriteHeader(modelouthandle, FM_HEADER_NAME, FM_HEADER_VER, sizeof(fmheader), &fmheader); - - // - // write out the skin names - // - - WriteHeader(modelouthandle, FM_SKIN_NAME, FM_SKIN_VER, fmheader.num_skins * MAX_FM_SKINNAME, g_skins); - - // - // write out the texture coordinates - // - c_on = c_off = 0; - for (i=0 ; iname, in->name); - for (j=0 ; j<3 ; j++) - { - out->scale[j] = (in->maxs[j] - in->mins[j])/255; - out->translate[j] = in->mins[j]; - - outFrames[i].scale[j] = out->scale[j]; - outFrames[i].translate[j] = out->translate[j]; - } - - for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; - - for (k=0 ; k<3 ; k++) - { - // scale to byte values & min/max check - v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); - - // clamp, so rounding doesn't wrap from 255.6 to 0 - if (v > 255.0) - v = 255.0; - if (v < 0) - v = 0; - out->verts[j].v[k] = v; - } - } - - for (j=0 ; j<3 ; j++) - { - out->scale[j] = LittleFloat (out->scale[j]); - out->translate[j] = LittleFloat (out->translate[j]); - } - - SafeWrite (modelouthandle, out, fmheader.framesize); - } - - // Go back and finish the header - // WriteHeader(modelouthandle, FM_FRAME_NAME, FM_FRAME_VER, -1, NULL); - } - else - { - WriteHeader(modelouthandle, FM_SHORT_FRAME_NAME, FM_SHORT_FRAME_VER,FRAME_NAME_LEN*fmheader.num_frames, NULL); - for (i=0 ; iname,FRAME_NAME_LEN); - } - WriteHeader(modelouthandle, FM_NORMAL_NAME, FM_NORMAL_VER,fmheader.num_xyz, NULL); - in = &g_frames[0]; - for (j=0 ; jv[j].lightnormalindex,1); - } - - // - // write out glcmds - // - WriteHeader(modelouthandle, FM_GLCMDS_NAME, FM_GLCMDS_VER, numcommands*4, commands); - - // - // write out mesh nodes - // - for(i=0;idegrees*sizeof(char) - char *ccomp; g->num_frames*g->degrees*sizeof(char) - char *cbase; fmheader.num_xyz*3*sizeof(unsigned char) - float *cscale; g->degrees*sizeof(float) - float *coffset; g->degrees*sizeof(float) - float trans[3]; 3*sizeof(float) - float scale[3]; 3*sizeof(float) -} fmgroup_t; -*/ - int tmp,k; - fmgroup_t *g; - size=sizeof(int)+fmheader.num_frames*sizeof(int); - for (k=0;kdegrees*sizeof(char); - size+=g->num_frames*g->degrees*sizeof(char); - size+=fmheader.num_xyz*3*sizeof(unsigned char); - size+=g->degrees*sizeof(float); - size+=g->degrees*sizeof(float); - size+=12*sizeof(float); - } - WriteHeader(modelouthandle, FM_COMP_NAME, FM_COMP_VER,size, NULL); - SafeWrite (modelouthandle,&num_groups,sizeof(int)); - SafeWrite (modelouthandle,frame_to_group,sizeof(int)*fmheader.num_frames); - - for (k=0;kstart_frame); - SafeWrite (modelouthandle,&tmp,sizeof(int)); - tmp=LittleLong(g->num_frames); - SafeWrite (modelouthandle,&tmp,sizeof(int)); - tmp=LittleLong(g->degrees); - SafeWrite (modelouthandle,&tmp,sizeof(int)); - - SafeWrite (modelouthandle,g->mat,fmheader.num_xyz*3*g->degrees*sizeof(char)); - SafeWrite (modelouthandle,g->ccomp,g->num_frames*g->degrees*sizeof(char)); - SafeWrite (modelouthandle,g->cbase,fmheader.num_xyz*3*sizeof(unsigned char)); - SafeWrite (modelouthandle,g->cscale,g->degrees*sizeof(float)); - SafeWrite (modelouthandle,g->coffset,g->degrees*sizeof(float)); - SafeWrite (modelouthandle,g->trans,3*sizeof(float)); - SafeWrite (modelouthandle,g->scale,3*sizeof(float)); - SafeWrite (modelouthandle,g->bmin,3*sizeof(float)); - SafeWrite (modelouthandle,g->bmax,3*sizeof(float)); - free(g->mat); - free(g->ccomp); - free(g->cbase); - free(g->cscale); - free(g->coffset); - } - } - - // write the skeletal info - if(g_skelModel.type != SKEL_NULL) - { - size = 0; - - temp = sizeof(int); // change this to a byte - memcpy(data + size, &g_skelModel.type, temp); - size += temp; - - // number of joints - temp = sizeof(int); // change this to a byte - memcpy(data + size, &numJointsInSkeleton[g_skelModel.type], temp); - size += temp; - - // number of verts in each joint cluster - temp = sizeof(int)*numJointsInSkeleton[g_skelModel.type]; // change this to shorts - memcpy(data + size, &g_skelModel.new_num_verts[1], temp); - size += temp; - - // cluster verts - for(i = 0; i < numJointsInSkeleton[g_skelModel.type]; ++i) - { - current = g_skelModel.vertLists[i]; - while(current) - { - temp = sizeof(int); // change this to a short - memcpy(data + size, ¤t->data, temp); - size += temp; - toFree = current; - current = current->next; - free(toFree); // freeing of memory allocated in ReplaceClusterIndex called in Cmd_Base - } - } - - if(!num_groups) // joints are stored with regular verts for compressed models - { - framesWritten = true; - - temp = sizeof(int); // change this to a byte - memcpy(data + size, &framesWritten, temp); - size += temp; - - for (i = 0; i < fmheader.num_frames; ++i) - { - in = &g_frames[i]; - - for (j = 0 ; j < numJointsInSkeleton[g_skelModel.type]; ++j) - { - for (k=0 ; k<3 ; k++) - { - // scale to byte values & min/max check - v = Q_rint ( (in->joints[j].placement.origin[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // write out origin as a float since they arn't clamped - temp = sizeof(float); // change this to a short - assert(size+temp < DATA_SIZE); - memcpy(data + size, &v, temp); - size += temp; - } - - for (k=0 ; k<3 ; k++) - { - v = Q_rint ( (in->joints[j].placement.direction[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // write out origin as a float since they arn't clamped - temp = sizeof(float); // change this to a short - assert(size+temp < DATA_SIZE); - memcpy(data + size, &v, temp); - size += temp; - } - - for (k=0 ; k<3 ; k++) - { - v = Q_rint ( (in->joints[j].placement.up[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // write out origin as a float since they arn't clamped - temp = sizeof(float); // change this to a short - assert(size+temp < DATA_SIZE); - memcpy(data + size, &v, temp); - size += temp; - } - } - } - - } - else - { - temp = sizeof(int); // change this to a byte - memcpy(data + size, &framesWritten, temp); - size += temp; - } - - WriteHeader(modelouthandle, FM_SKELETON_NAME, FM_SKELETON_VER, size, data); - } - - if(g_skelModel.references != REF_NULL) - { - int refnum; - - size = 0; - if (RefPointNum <= 0) - { // Hard-coded labels - refnum = numReferences[g_skelModel.references]; - } - else - { // Labels indicated in QDT - refnum = RefPointNum; - } - - temp = sizeof(int); // change this to a byte - memcpy(data2 + size, &g_skelModel.references, temp); - size += temp; - - if(!num_groups) - { - framesWritten = true; - - temp = sizeof(int); // change this to a byte - memcpy(data2 + size, &framesWritten, temp); - size += temp; - - for (i = 0; i < fmheader.num_frames; ++i) - { - in = &g_frames[i]; - - for (j = 0 ; j < refnum; ++j) - { - for (k=0 ; k<3 ; k++) - { - // scale to byte values & min/max check - v = Q_rint ( (in->references[j].placement.origin[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // write out origin as a float since they arn't clamped - temp = sizeof(float); // change this to a short - assert(size+temp < DATA_SIZE); - memcpy(data2 + size, &v, temp); - size += temp; - } - - for (k=0 ; k<3 ; k++) - { - v = Q_rint ( (in->references[j].placement.direction[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // write out origin as a float since they arn't clamped - temp = sizeof(float); // change this to a short - assert(size+temp < DATA_SIZE); - memcpy(data2 + size, &v, temp); - size += temp; - } - - for (k=0 ; k<3 ; k++) - { - v = Q_rint ( (in->references[j].placement.up[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // write out origin as a float since they arn't clamped - temp = sizeof(float); // change this to a short - assert(size+temp < DATA_SIZE); - memcpy(data2 + size, &v, temp); - size += temp; - } - } - } - } - else // FINISH ME: references need to be stored with regular verts for compressed models - { - framesWritten = false; - - temp = sizeof(int); // change this to a byte - memcpy(data2 + size, &framesWritten, temp); - size += temp; - } - - WriteHeader(modelouthandle, FM_REFERENCES_NAME, FM_REFERENCES_VER, size, data2); - } -} - -static void CompressFrames() -{ - fmgroup_t *g; - int i,j,k; - fmframe_t *in; - - j=0; - for (i=0;i=groups[j].start_frame+groups[j].num_frames&&jnum_frames,fmheader.num_xyz,g->degrees); - for (i=0;inum_frames;i++) - { - in = &g_frames[i+g->start_frame]; - for (j=0;jv[j].v[0],in->v[j].v[1],in->v[j].v[2]); - } - AnimCompressDoit(); - g->mat= (char *) SafeMalloc(fmheader.num_xyz*3*g->degrees*sizeof(char), "CompressFrames"); - g->ccomp=(char *) SafeMalloc(g->num_frames*g->degrees*sizeof(char), "CompressFrames"); - g->cbase=(char *) SafeMalloc(fmheader.num_xyz*3*sizeof(unsigned char), "CompressFrames"); - g->cscale=(float *) SafeMalloc(g->degrees*sizeof(float), "CompressFrames"); - g->coffset=(float *) SafeMalloc(g->degrees*sizeof(float), "CompressFrames"); - AnimCompressToBytes(g->trans,g->scale,g->mat,g->ccomp,g->cbase,g->cscale,g->coffset,g->bmin,g->bmax); - AnimCompressEnd(); - } -} - -static void OptimizeVertices(void) -{ - qboolean vert_used[MAX_FM_VERTS]; - short vert_replacement[MAX_FM_VERTS]; - int i,j,k,l,pos,bit,set_pos,set_bit; - fmframe_t *in; - qboolean Found; - int num_unique; - static IntListNode_t *newVertLists[NUM_CLUSTERS]; - static int newNum_verts[NUM_CLUSTERS]; - IntListNode_t *current, *next; - - printf("Optimizing vertices..."); - - memset(vert_used, 0, sizeof(vert_used)); - - if(g_skelModel.clustered == true) - { - memset(newNum_verts, 0, sizeof(newNum_verts)); - memset(newVertLists, 0, sizeof(newVertLists)); - } - - num_unique = 0; - - // search for common points among all the frames - for (i=0 ; iv[j].v[0] == in->v[k].v[0] && - in->v[j].v[1] == in->v[k].v[1] && - in->v[j].v[2] == in->v[k].v[2]) - { - Found = true; - vert_replacement[j] = k; - break; - } - - } - - if (!Found) - { - if (!vert_used[j]) - { - num_unique++; - } - vert_used[j] = true; - } - } - } - - // recompute the light normals - for (i=0 ; iv[j].vnorm.normalsum, in->v[k].vnorm.normalsum, in->v[k].vnorm.normalsum); - in->v[k].vnorm.numnormals += in->v[j].vnorm.numnormals++; - } - } - - for (j=0 ; jv[j].vnorm.numnormals; - if (!c) - Error ("Vertex with no triangles attached"); - - VectorScale (in->v[j].vnorm.normalsum, 1.0/c, v); - VectorNormalize (v, v); - - maxdot = -999999.0; - maxdotindex = -1; - - for (k=0 ; k maxdot) - { - maxdot = dot; - maxdotindex = k; - } - } - - in->v[j].lightnormalindex = maxdotindex; - } - } - - // create substitution list - num_unique = 0; - for(i=0;inext) - { - if(current->data == i) - { - IntListNode_t *current2; - int m; - qboolean added = false; - - for(m = 0, current2 = newVertLists[k]; m < newNum_verts[k+1]; - ++m, current2 = current2->next) - { - if(current2->data == vert_replacement[i]) - { - added = true; - break; - } - } - - if(!added) - { - ++newNum_verts[k+1]; - - next = newVertLists[k]; - - newVertLists[k] = (IntListNode_t *) SafeMalloc(sizeof(IntListNode_t), "OptimizeVertices"); - // freed after model write out - - newVertLists[k]->data = vert_replacement[i]; - newVertLists[k]->next = next; - } - break; - } - } - } - } - } - - // substitute - for (i=0 ; iv[vert_replacement[j]] = in->v[j]; - } - - } - - for(i = 0; i < numJointsInSkeleton[g_skelModel.type]; ++i) - { - IntListNode_t *toFree; - current = g_skelModel.vertLists[i]; - - while(current) - { - toFree = current; - current = current->next; - free(toFree); // freeing of memory allocated in ReplaceClusterIndex called in Cmd_Base - } - - g_skelModel.vertLists[i] = newVertLists[i]; - g_skelModel.new_num_verts[i+1] = newNum_verts[i+1]; - } - -#ifndef NDEBUG - for(k = 0; k < numJointsInSkeleton[g_skelModel.type]; ++k) - { - for(l = 0, current = g_skelModel.vertLists[k]; - l < g_skelModel.new_num_verts[k+1]; ++l, current = current->next) - { - IntListNode_t *current2; - int m; - - for(m = l+1, current2 = current->next; m < newNum_verts[k+1]; - ++m, current2 = current2->next) - { - if(current->data == current2->data) - { - printf("Warning duplicate vertex: %d\n", current->data); - break; - } - } - } - } -#endif - - for(i=0;i> 3; - bit = 1 << (i & 7 ); - - for (j=0 ; j<3 ; j++) - { - set_bit = set_pos = triangles[i].index_xyz[j] = vert_replacement[triangles[i].index_xyz[j]]; - - set_pos >>= 3; - set_bit = 1 << (set_bit & 7); - - for(k=0;kreferences[j].placement.origin, in->v[index].v); - index++; - - VectorCopy(in->references[j].placement.direction, in->v[index].v); - index++; - - VectorCopy(in->references[j].placement.up, in->v[index].v); - index++; - } - } - - fmheader.num_xyz += refnum*3; - } - - // tack on the skeletal joint verts to the regular verts - if(g_skelModel.type != SKEL_NULL) - { - fmframe_t *in; - int index; - - for (i = 0; i < fmheader.num_frames; ++i) - { - in = &g_frames[i]; - index = fmheader.num_xyz; - - for (j = 0 ; j < numJointsInSkeleton[g_skelModel.type]; ++j) - { - VectorCopy(in->joints[j].placement.origin, in->v[index].v); - index++; - - VectorCopy(in->joints[j].placement.direction, in->v[index].v); - index++; - - VectorCopy(in->joints[j].placement.up, in->v[index].v); - index++; - } - } - - fmheader.num_xyz += numJointsInSkeleton[g_skelModel.type]*3; - } - - CompressFrames(); - } -} - - -/* -=============== -FinishModel -=============== -*/ -void FMFinishModel (void) -{ - FILE *modelouthandle; - int i,j,length,tris,verts,bit,pos,total_tris,total_verts; - char name[1024]; - int trans_count; - - if (!fmheader.num_frames) - return; - -// -// copy to release directory tree if doing a release build -// - if (g_release) - { - if (modelname[0]) - sprintf (name, "%s", modelname); - else - sprintf (name, "%s/tris.fm", cdpartial); - ReleaseFile (name); - - for (i=0 ; i> 3; - bit = 1 << ((j) & 7 ); - if (pmnodes[i].tris[pos] & bit) - { - tris++; - } - } - for(j=0;j> 3; - bit = 1 << ((j) & 7 ); - if (pmnodes[i].verts[pos] & bit) - { - verts++; - } - } - - printf("%-33s %4d %5d\n",pmnodes[i].name,tris,verts); - - total_tris += tris; - total_verts += verts; - } - printf("--------------------------------- ---- -----\n"); - printf("%-33s %4d %5d\n","TOTALS",total_tris,total_verts); - } - } - fclose (modelouthandle); - - // finish writing header file - H_printf("\n"); - - // scale_up is usefull to allow step distances to be adjusted - H_printf("#define MODEL_SCALE\t\t%f\n", scale_up); - - // mesh nodes - if (fmheader.num_mesh_nodes) - { - H_printf("\n"); - H_printf("#define NUM_MESH_NODES\t\t%d\n\n",fmheader.num_mesh_nodes); - for(i=0;iindex_xyz[(startv)%3]; - strip_xyz[1] = last->index_xyz[(startv+1)%3]; - strip_xyz[2] = last->index_xyz[(startv+2)%3]; - strip_st[0] = last->index_st[(startv)%3]; - strip_st[1] = last->index_st[(startv+1)%3]; - strip_st[2] = last->index_st[(startv+2)%3]; - - strip_tris[0] = starttri; - stripcount = 1; - - m1 = last->index_xyz[(startv+2)%3]; - st1 = last->index_st[(startv+2)%3]; - m2 = last->index_xyz[(startv+1)%3]; - st2 = last->index_st[(startv+1)%3]; - - // look for a matching triangle -nexttri: - for (j=starttri+1, check=&triangles[starttri+1] - ; j> 3; - bit = 1 << (j & 7 ); - if (!(pmnodes[node].tris[pos] & bit)) - { - continue; - } - for (k=0 ; k<3 ; k++) - { - if (check->index_xyz[k] != m1) - continue; - if (check->index_st[k] != st1) - continue; - if (check->index_xyz[ (k+1)%3 ] != m2) - continue; - if (check->index_st[ (k+1)%3 ] != st2) - continue; - - // this is the next part of the fan - - // if we can't use this triangle, this tristrip is done - if (used[j] || translucent[j] != translucent[starttri]) - goto done; - - // the new edge - if (stripcount & 1) - { - m2 = check->index_xyz[ (k+2)%3 ]; - st2 = check->index_st[ (k+2)%3 ]; - } - else - { - m1 = check->index_xyz[ (k+2)%3 ]; - st1 = check->index_st[ (k+2)%3 ]; - } - - strip_xyz[stripcount+2] = check->index_xyz[ (k+2)%3 ]; - strip_st[stripcount+2] = check->index_st[ (k+2)%3 ]; - strip_tris[stripcount] = j; - stripcount++; - - used[j] = 2; - goto nexttri; - } - } -done: - - // clear the temp used flags - for (j=starttri+1 ; jindex_xyz[(startv)%3]; - strip_xyz[1] = last->index_xyz[(startv+1)%3]; - strip_xyz[2] = last->index_xyz[(startv+2)%3]; - strip_st[0] = last->index_st[(startv)%3]; - strip_st[1] = last->index_st[(startv+1)%3]; - strip_st[2] = last->index_st[(startv+2)%3]; - - strip_tris[0] = starttri; - stripcount = 1; - - m1 = last->index_xyz[(startv+0)%3]; - st1 = last->index_st[(startv+0)%3]; - m2 = last->index_xyz[(startv+2)%3]; - st2 = last->index_st[(startv+2)%3]; - - - // look for a matching triangle -nexttri: - for (j=starttri+1, check=&triangles[starttri+1] - ; j> 3; - bit = 1 << (j & 7 ); - if (!(pmnodes[node].tris[pos] & bit)) - { - continue; - } - for (k=0 ; k<3 ; k++) - { - if (check->index_xyz[k] != m1) - continue; - if (check->index_st[k] != st1) - continue; - if (check->index_xyz[ (k+1)%3 ] != m2) - continue; - if (check->index_st[ (k+1)%3 ] != st2) - continue; - - // this is the next part of the fan - - // if we can't use this triangle, this tristrip is done - if (used[j] || translucent[j] != translucent[starttri]) - goto done; - - // the new edge - m2 = check->index_xyz[ (k+2)%3 ]; - st2 = check->index_st[ (k+2)%3 ]; - - strip_xyz[stripcount+2] = m2; - strip_st[stripcount+2] = st2; - strip_tris[stripcount] = j; - stripcount++; - - used[j] = 2; - goto nexttri; - } - } -done: - - // clear the temp used flags - for (j=starttri+1 ; j> 3; - bit = 1 << (i & 7 ); - if (!(pmnodes[l].tris[pos] & bit)) - { - continue; - } - - // pick an unused triangle and start the trifan - if (used[i] || trans_check != translucent[i]) - { - continue; - } - - bestlen = 0; - for (type = 0 ; type < 2 ; type++) - // type = 1; - { - for (startv =0 ; startv < 3 ; startv++) - { - if (type == 1) - len = StripLength (i, startv, fmheader.num_tris, l); - else - len = FanLength (i, startv, fmheader.num_tris, l); - if (len > bestlen) - { - besttype = type; - bestlen = len; - for (j=0 ; j - "-------------------------", // ? - "-------------------------", // @ - "-***-*---*******---**---*", // A - "****-*---*****-*---*****-", - "-*****----*----*-----****", - "****-*---**---**---*****-", - "******----****-*----*****", - "******----****-*----*----", - "-*****----*--***---*-****", - "*---**---*******---**---*", - "-***---*----*----*---***-", - "----*----*----**---*-***-", - "-*--*-*-*--**---*-*--*--*", - "-*----*----*----*----****", - "*---***-***-*-**---**---*", - "*---***--**-*-**--***---*", - "-***-*---**---**---*-***-", - "****-*---*****-*----*----", - "-***-*---**---*-***----**", - "****-*---*****-*-*--*--**", - "-*****-----***-----*****-", - "*****--*----*----*----*--", - "*---**---**---**---******", - "*---**---**---*-*-*---*--", - "*---**---**-*-***-***---*", - "*---*-*-*---*---*-*-*---*", - "*---**---*-*-*---*----*--", - "*****---*---*---*---*****" // Z -}; - -void DrawLine(int x1, int y1, int x2, int y2) -{ - int dx, dy; - int adx, ady; - int count; - float xfrac, yfrac, xstep, ystep; - unsigned sx, sy; - float u, v; - - dx = x2 - x1; - dy = y2 - y1; - adx = abs(dx); - ady = abs(dy); - - count = adx > ady ? adx : ady; - count++; - - if(count > 300) - { - printf("Bad count\n"); - return; // don't ever hang up on bad data - } - - xfrac = x1; - yfrac = y1; - - xstep = (float)dx/count; - ystep = (float)dy/count; - - switch(LineType) - { - case LINE_NORMAL: - do - { - if(xfrac < SKINPAGE_WIDTH && yfrac < SKINPAGE_HEIGHT) - { - pic[(int)yfrac*SKINPAGE_WIDTH+(int)xfrac] = LineColor; - } - xfrac += xstep; - yfrac += ystep; - count--; - } while (count > 0); - break; - case LINE_FAT: - do - { - for (u=-0.1 ; u<=0.9 ; u+=0.999) - { - for (v=-0.1 ; v<=0.9 ; v+=0.999) - { - sx = xfrac+u; - sy = yfrac+v; - if(sx < SKINPAGE_WIDTH && sy < SKINPAGE_HEIGHT) - { - pic[sy*SKINPAGE_WIDTH+sx] = LineColor; - } - } - } - xfrac += xstep; - yfrac += ystep; - count--; - } while (count > 0); - break; - case LINE_DOTTED: - do - { - if(count&1 && xfrac < SKINPAGE_WIDTH && - yfrac < SKINPAGE_HEIGHT) - { - pic[(int)yfrac*SKINPAGE_WIDTH+(int)xfrac] = LineColor; - } - xfrac += xstep; - yfrac += ystep; - count--; - } while (count > 0); - break; - default: - Error("Unknown %d.\n", LineType); - } -} - -//========================================================================== -// -// DrawCharacter -// -//========================================================================== - -static void DrawCharacter(int x, int y, int character) -{ - int r, c; - char *def; - - character = toupper(character); - if(character < ASCII_SPACE || character > 'Z') - { - character = ASCII_SPACE; - } - character -= ASCII_SPACE; - for(def = CharDefs[character], r = 0; r < 5; r++) - { - for(c = 0; c < 5; c++) - { - pic[(y+r)*SKINPAGE_WIDTH+x+c] = *def++ == '*' ? 255 : 0; - } - } -} - -//========================================================================== -// -// DrawTextChar -// -//========================================================================== - -void DrawTextChar(int x, int y, char *text) -{ - int c; - - while((c = *text++) != '\0') - { - DrawCharacter(x, y, c); - x += 6; - } -} - - -extern void DrawScreen(float s_scale, float t_scale, float iwidth, float iheight); - -//========================================================================== -// ExtractDigit - -static int ExtractDigit(byte *pic, int x, int y) -{ - int i; - int r, c; - char digString[32]; - char *buffer; - byte backColor; - char **DigitDefs; - - backColor = pic[(SKINPAGE_HEIGHT - 1) * SKINPAGE_WIDTH]; - DigitDefs = &CharDefs['0' - ASCII_SPACE]; - - buffer = digString; - for(r = 0; r < 5; r++) - { - for(c = 0; c < 5; c++) - { - *buffer++ = (pic[(y + r) * SKINPAGE_WIDTH + x + c] == backColor) ? ' ' : '*'; - } - } - *buffer = '\0'; - for(i = 0; i < 10; i++) - { - if(strcmp(DigitDefs[i], digString) == 0) - { - return i; - } - } - - Error("Unable to extract scaling info from skin PCX."); - return 0; -} - -//========================================================================== -// ExtractNumber - -int ExtractNumber(byte *pic, int x, int y) -{ - return ExtractDigit(pic, x, y) * 100 + ExtractDigit(pic, x + 6, y) * 10 + ExtractDigit(pic, x + 12, y); -} - - - - - -/* -============ -BuildST - -Builds the triangle_st array for the base frame and -fmheader.skinwidth / fmheader.skinheight - - FIXME: allow this to be loaded from a file for - arbitrary mappings -============ -*/ -static void BuildST (triangle_t *ptri, int numtri, qboolean DrawSkin) -{ - int backface_flag; - int i, j; - int width, height, iwidth, iheight, swidth; - float basex, basey; - float scale; - vec3_t mins, maxs; - float *pbasevert; - vec3_t vtemp1, vtemp2, normal; - float s_scale, t_scale; - float scWidth; - float scHeight; - int skinwidth; - int skinheight; - - // - // find bounds of all the verts on the base frame - // - ClearBounds (mins, maxs); - backface_flag = false; - - if (ptri[0].HasUV) // if we have the uv already, we don't want to double up or scale - { - iwidth = ScaleWidth; - iheight = ScaleHeight; - - t_scale = s_scale = 1.0; - } - else - { - for (i=0 ; i 0) - { - backface_flag = true; - break; - } - } - scWidth = ScaleWidth*SCALE_ADJUST_FACTOR; - if (backface_flag) //we are doubling - scWidth /= 2; - - scHeight = ScaleHeight*SCALE_ADJUST_FACTOR; - - scale = scWidth/width; - - if(height*scale >= scHeight) - { - scale = scHeight/height; - } - - iwidth = ceil(width*scale)+4; - iheight = ceil(height*scale)+4; - - s_scale = (float)(iwidth-4) / width; - t_scale = (float)(iheight-4) / height; - t_scale = s_scale; - } - if (DrawSkin) - { - if(backface_flag) - DrawScreen(s_scale, t_scale, iwidth*2, iheight); - else - DrawScreen(s_scale, t_scale, iwidth, iheight); - } - if (backface_flag) - skinwidth=iwidth*2; - else - skinwidth=iwidth; - skinheight=iheight; - - -/* if (!g_fixedwidth) - { // old style - scale = 8; - if (width*scale >= 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_fixedwidth / 2; - iheight = g_fixedheight; - - s_scale = (float)(iwidth-4) / width; - t_scale = (float)(iheight-4) / height; - }*/ - -// -// determine which side of each triangle to map the texture to -// - basey = 2; - for (i=0 ; i 0) - { - basex = iwidth + 2; - } - else - { - basex = 2; - } - - for (j=0 ; j<3 ; j++) - { - pbasevert = ptri[i].verts[j]; - - triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); - triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); - } - } - - if (DrawSkin) - { - DrawLine(triangle_st[i][0][0], triangle_st[i][0][1], - triangle_st[i][1][0], triangle_st[i][1][1]); - DrawLine(triangle_st[i][1][0], triangle_st[i][1][1], - triangle_st[i][2][0], triangle_st[i][2][1]); - DrawLine(triangle_st[i][2][0], triangle_st[i][2][1], - triangle_st[i][0][0], triangle_st[i][0][1]); - } - } - -// make the width a multiple of 4; some hardware requires this, and it ensures -// dword alignment for each scan - - swidth = iwidth; - if(backface_flag) - swidth *= 2; - fmheader.skinwidth = (swidth + 3) & ~3; - fmheader.skinheight = iheight; - - skin_width = iwidth; - skin_height = iheight; -} - - -static void BuildNewST (triangle_t *ptri, int numtri, qboolean DrawSkin) -{ - int i, j; - - for (i=0 ; i 1) - goto split; - d = lp2[1] - lp1[1]; - if (d < -1 || d > 1) - goto split; - - d = lp3[0] - lp2[0]; - if (d < -1 || d > 1) - goto split2; - d = lp3[1] - lp2[1]; - if (d < -1 || d > 1) - goto split2; - - d = lp1[0] - lp3[0]; - if (d < -1 || d > 1) - goto split3; - d = lp1[1] - lp3[1]; - if (d < -1 || d > 1) - { -split3: - temp = lp1; - lp1 = lp3; - lp3 = lp2; - lp2 = temp; - - goto split; - } - - return 0; // entire tri is filled - -split2: - temp = lp1; - lp1 = lp2; - lp2 = lp3; - lp3 = temp; - -split: -// split this edge - new[0] = (lp1[0] + lp2[0]) >> 1; - new[1] = (lp1[1] + lp2[1]) >> 1; - -// draw the point if splitting a leading edge - if (lp2[1] > lp1[1]) - goto nodraw; - if ((lp2[1] == lp1[1]) && (lp2[0] < lp1[0])) - goto nodraw; - - if (SetPixel) - { - assert ((new[1]*BaseWidth) + new[0] < BaseWidth*BaseHeight); - - if (BaseTrueColor) - { - BasePixels[((new[1]*BaseWidth) + new[0]) * 4] = 1; - } - else - { - BasePixels[(new[1]*BaseWidth) + new[0]] = 1; - } - } - else - { - if (TransPixels) - { - if (TransPixels[(new[1]*TransWidth) + new[0]] != 255) - return 1; - } - else if (BaseTrueColor) - { - if (BasePixels[(((new[1]*BaseWidth) + new[0]) * 4) + 3] != 255) - return 1; - } - else - { -// pixel = BasePixels[(new[1]*BaseWidth) + new[0]]; - } - } - -nodraw: -// recursively continue - if (CheckTransRecursiveTri(lp3, lp1, new)) - return 1; - - return CheckTransRecursiveTri(lp3, new, lp2); -} - -static void ReplaceClusterIndex(int newIndex, int oldindex, int **clusters, - IntListNode_t **vertLists, int *num_verts, int *new_num_verts) -{ - int i, j; - IntListNode_t *next; - - for(j = 0; j < numJointsInSkeleton[g_skelModel.type]; ++j) - { - if(!clusters[j]) - { - continue; - } - - for(i = 0; i < num_verts[j+1]; ++i) - { - if(clusters[j][i] == oldindex) - { - ++new_num_verts[j+1]; - - next = vertLists[j]; - - vertLists[j] = (IntListNode_t *) SafeMalloc(sizeof(IntListNode_t), "ReplaceClusterIndex"); - // Currently freed in WriteJointedModelFile only - - vertLists[j]->data = newIndex; - vertLists[j]->next = next; - } - } - } -} - -#define FUDGE_EPSILON 0.002 - -qboolean VectorFudgeCompare (vec3_t v1, vec3_t v2) -{ - int i; - - for (i=0 ; i<3 ; i++) - if (fabs(v1[i]-v2[i]) > FUDGE_EPSILON) - return false; - - return true; -} - -/* -================= -Cmd_Base -================= -*/ -void Cmd_FMBase (qboolean GetST) -{ - triangle_t *ptri, *st_tri; - int num_st_tris; - int i, j, k, l; - int x,y,z; -// int time1; - char file1[1024],file2[1024],trans_file[1024], stfile[1024], extension[256]; - vec3_t base_xyz[MAX_FM_VERTS]; - FILE *FH; - int pos,bit; - qboolean NewSkin; - - GetScriptToken (false); - - if (g_skipmodel || g_release || g_archive) - return; - - printf ("---------------------\n"); - sprintf (file1, "%s/%s.%s", cdarchive, token, trifileext); - printf ("%s ", file1); - - ExpandPathAndArchive (file1); - - // Use the input filepath for this one. - sprintf (file1, "%s/%s", cddir, token); - -// time1 = FileTime (file1); -// if (time1 == -1) -// Error ("%s doesn't exist", file1); - -// -// load the base triangles -// - if (do3ds) - Load3DSTriangleList (file1, &ptri, &fmheader.num_tris, &pmnodes, &fmheader.num_mesh_nodes); - else - LoadTriangleList (file1, &ptri, &fmheader.num_tris, &pmnodes, &fmheader.num_mesh_nodes); - - if (g_ignoreTriUV) - { - for (i=0;i> 3; - bit = 1 << (i & 7 ); - if (!(pmnodes[l].tris[pos] & bit)) - { - continue; - } - - for (j=0 ; j<3 ; j++) - { - // get the xyz index - for (k=0 ; k> 3; - bit = 1 << (k & 7); - pmnodes[l].verts[pos] |= bit; - - triangles[i].index_xyz[j] = k; - - // get the st index - for (k=0 ; k= fmheader.num_mesh_nodes) - { - Error("Node '%s' not in base list!\n", token); - } - } - - free(pmnodes); - pmnodes = newnodes; -} - -//=============================================================== - -extern char *FindFrameFile (char *frame); - - -/* -=============== -GrabFrame -=============== -*/ -void GrabFrame (char *frame) -{ - triangle_t *ptri; - int i, j; - fmtrivert_t *ptrivert; - int num_tris; - char file1[1024]; - fmframe_t *fr; - int index_xyz; - char *framefile; - - // the frame 'run1' will be looked for as either - // run.1 or run1.tri, so the new alias sequence save - // feature an be used - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - - printf ("grabbing %s ", file1); - - if (fmheader.num_frames >= MAX_FM_FRAMES) - Error ("fmheader.num_frames >= MAX_FM_FRAMES"); - fr = &g_frames[fmheader.num_frames]; - fmheader.num_frames++; - - strcpy (fr->name, frame); - -// -// load the frame -// - if (do3ds) - Load3DSTriangleList (file1, &ptri, &num_tris, NULL, NULL); - else - LoadTriangleList (file1, &ptri, &num_tris, NULL, NULL); - - if (num_tris != fmheader.num_tris) - Error ("%s: number of triangles (%d) doesn't match base frame (%d)\n", file1, num_tris, fmheader.num_tris); - -// -// allocate storage for the frame's vertices -// - ptrivert = fr->v; - - for (i=0 ; imins, fr->maxs); - -// -// 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 ; imins, fr->maxs); - - VectorAdd (ptrivert[index_xyz].vnorm.normalsum, normal, ptrivert[index_xyz].vnorm.normalsum); - ptrivert[index_xyz].vnorm.numnormals++; - } - } - -// -// calculate the vertex normals, match them to the template list, and store the -// index of the best match -// - for (i=0 ; i maxdot) - { - maxdot = dot; - maxdotindex = j; - } - } - - ptrivert[i].lightnormalindex = maxdotindex; - } - - free (ptri); -} - -/* -=============== -Cmd_Frame -=============== -*/ -void Cmd_FMFrame (void) -{ - while (ScriptTokenAvailable()) - { - GetScriptToken (false); - if (g_skipmodel) - continue; - if (g_release || g_archive) - { - fmheader.num_frames = 1; // don't skip the writeout - continue; - } - - H_printf("#define FRAME_%-16s\t%i\n", token, fmheader.num_frames); - - if((g_skelModel.type != SKEL_NULL) || (g_skelModel.references != REF_NULL)) - { - GrabModelTransform(token); - } - - GrabFrame (token); - - if(g_skelModel.type != SKEL_NULL) - { - GrabSkeletalFrame(token); - } - - if(g_skelModel.references != REF_NULL) - { - GrabReferencedFrame(token); - } - - // need to add the up and dir points to the frame bounds here - // using AddPointToBounds (ptrivert[index_xyz].v, fr->mins, fr->maxs); - // then remove fudge in determining scale on frame write out - } -} - -/* -=============== -Cmd_Skin - -Skins aren't actually stored in the file, only a reference -is saved out to the header file. -=============== -*/ -void Cmd_FMSkin (void) -{ - byte *palette; - byte *pixels; - int width, height; - byte *cropped; - int y; - char name[1024], savename[1024], transname[1024], extension[256]; - miptex32_t *qtex32; - int size; - FILE *FH; - qboolean TrueColor; - - GetScriptToken (false); - - if (fmheader.num_skins == MAX_FM_SKINS) - Error ("fmheader.num_skins == MAX_FM_SKINS"); - - if (g_skipmodel) - return; - - sprintf (name, "%s/%s", cdarchive, token); - strcpy (name, ExpandPathAndArchive( name ) ); -// sprintf (name, "%s/%s.lbm", cddir, token); - - if (ScriptTokenAvailable()) - { - GetScriptToken (false); - sprintf (g_skins[fmheader.num_skins], "!%s", token); - sprintf (savename, "%s!%s", g_outputDir, token); - sprintf (transname, "%s!%s_a.pcx", gamedir, token); - } - else - { - sprintf (g_skins[fmheader.num_skins], "%s/!%s", cdpartial, token); - sprintf (savename, "%s/!%s", g_outputDir, token); - sprintf (transname, "%s/!%s_a.pcx", cddir, token); - } - - fmheader.num_skins++; - - if (g_skipmodel || g_release || g_archive) - return; - - // load the image - printf ("loading %s\n", name); - ExtractFileExtension (name, extension); - if (extension[0] == 0) - { - strcat(name, ".pcx"); - } - - - TrueColor = LoadAnyImage (name, &pixels, &palette, &width, &height); -// RemapZero (pixels, palette, width, height); - - // crop it to the proper size - - if (!TrueColor) - { - cropped = (byte *) SafeMalloc (fmheader.skinwidth*fmheader.skinheight, "Cmd_FMSkin"); - for (y=0 ; y= 3); -// figure out the best plane projections - DOsvdPlane ((float*)vertices, num, (float *)&n, (float *)&base); - - if (DotProduct(aveNorm,n) < 0.0f) - { - VectorScale(n, -1.0f, n); - } - VectorNormalize(n,n); - if (fabs(n[2]) < .57) - { - CrossProduct( zaxis, n, crossvect); - VectorCopy(crossvect, u); - } - else - { - CrossProduct( yaxis, n, crossvect); - VectorCopy(crossvect, u); - } - VectorNormalize(u,u); - CrossProduct( n, u, crossvect); - VectorCopy(crossvect, v); - VectorNormalize(v,v); - - num = 0; - - for ( j = 0; j < 3; j++) - { - groupMin[j] = 1e30f; - groupMax[j] = -1e30f; - } - - for ( j = 0; j < numtris; j++) - { - for ( k = 0; k < 3; k++) - { - VectorCopy(grouptris[j].verts[k],v0); - VectorSubtract(v0, base, v0); - uvw[0] = DotProduct(v0, u); - uvw[1] = DotProduct(v0, v); - uvw[2] = DotProduct(v0, n); - VectorCopy(uvw,uvs[num]); - num++; - for ( l = 0; l < 3; l++) - { - if (uvw[l] < groupMin[l]) - { - groupMin[l] = uvw[l]; - } - if (uvw[l] > groupMax[l]) - { - groupMax[l] = uvw[l]; - } - } - } - } - - xwidth = ceil(0 - groupMin[0]) + 2; // move right of origin and avoid overlap - ywidth = ceil(0 - groupMin[1]) + 2; // move "above" origin - - for ( j=0; j < numverts; j++) - { - uFinal[finalcount] = uvs[j][0] + xwidth + xbase; - vFinal[finalcount] = uvs[j][1] + ywidth; - if (uFinal[finalcount] < uvwMin[0]) - { - uvwMin[0] = uFinal[finalcount]; - } - if (uFinal[finalcount] > uvwMax[0]) - { - uvwMax[0] = uFinal[finalcount]; - } - if (vFinal[finalcount] < uvwMin[1]) - { - uvwMin[1] = vFinal[finalcount]; - } - if (vFinal[finalcount] > uvwMax[1]) - { - uvwMax[1] = vFinal[finalcount]; - } - finalcount++; - } - - fprintf(grpfile,"svdPlaned Group min: ( %f , %f )\n",groupMin[0] + xwidth + xbase, groupMin[1] + ywidth); - fprintf(grpfile,"svdPlaned Group max: ( %f , %f )\n",groupMax[0] + xwidth + xbase, groupMax[1] + ywidth); - - finalcount = finalstart; - - for ( count = 0; count < numverts; count++) - { - fprintf(grpfile,"Vertex %d: ( %f , %f , %f )\n",count,vertices[count][0],vertices[count][1],vertices[count][2]); - fprintf(grpfile,"svdPlaned: ( %f , %f )\n",uFinal[finalcount],vFinal[finalcount++]); - } - - finalstart = finalcount; - - fprintf(grpfile,"\n"); - - free(vertices); - free(uvs); - free(grouptris); - - xbase += ceil(groupMax[0] - groupMin[0]) + 2; - - } - - fprintf(grpfile,"Global Min ( %f , %f )\n",uvwMin[0],uvwMin[1]); - fprintf(grpfile,"Global Max ( %f , %f )\n",uvwMax[0],uvwMax[1]); - - - ScaleTris(uvwMin, uvwMax, width, height, uFinal, vFinal, finalcount); - - for (k = 0; k < finalcount; k++) - { - fprintf(grpfile, "scaled vertex %d: ( %f , %f )\n",k,uFinal[k],vFinal[k]); - } - - // i've got the array of vertices in uFinal and vFinal. Now I need to write them and draw lines - - datasize = width * height*sizeof(unsigned char); - newpic = (unsigned char*)SafeMalloc(datasize, "NewGen"); - memset(newpic,0,datasize); - memset(pic_palette,0,sizeof(pic_palette)); - pic_palette[767] = pic_palette[766] = pic_palette[765] = 255; - - k = 0; - while (k < finalcount) - { - NewDrawLine(uFinal[k], vFinal[k], uFinal[k+1], vFinal[k+1], newpic, width, height); - k++; - NewDrawLine(uFinal[k], vFinal[k], uFinal[k+1], vFinal[k+1], newpic, width, height); - k++; - NewDrawLine(uFinal[k], vFinal[k], uFinal[k-2], vFinal[k-2], newpic, width, height); - k++; - fprintf(grpfile, "output tri with verts %d, %d, %d", k-2, k-1, k); - } - - WritePCXfile (OutputName, newpic, width, height, pic_palette); - - fclose(grpfile); - - free(todo); - free(done); - free(triangles); - free(newpic); - return; -} -void NewDrawLine(int x1, int y1, int x2, int y2, unsigned char* picture, int width, int height) -{ - long dx, dy; - long adx, ady; - long count; - float xfrac, yfrac, xstep, ystep; - unsigned long sx, sy; - float u, v; - - dx = x2 - x1; - dy = y2 - y1; - adx = abs(dx); - ady = abs(dy); - - count = adx > ady ? adx : ady; - count++; - - if(count > 300) - { - printf("Bad count\n"); - return; // don't ever hang up on bad data - } - - xfrac = x1; - yfrac = y1; - - xstep = (float)dx/count; - ystep = (float)dy/count; - - switch(LineType) - { - case LINE_NORMAL: - do - { - if(xfrac < width && yfrac < height) - { - picture[(long)yfrac*width+(long)xfrac] = LineColor; - } - xfrac += xstep; - yfrac += ystep; - count--; - } while (count > 0); - break; - case LINE_FAT: - do - { - for (u=-0.1 ; u<=0.9 ; u+=0.999) - { - for (v=-0.1 ; v<=0.9 ; v+=0.999) - { - sx = xfrac+u; - sy = yfrac+v; - if(sx < width && sy < height) - { - picture[sy*width+sx] = LineColor; - } - } - } - xfrac += xstep; - yfrac += ystep; - count--; - } while (count > 0); - break; - case LINE_DOTTED: - do - { - if(count&1 && xfrac < width && - yfrac < height) - { - picture[(long)yfrac*width+(long)xfrac] = LineColor; - } - xfrac += xstep; - yfrac += ystep; - count--; - } while (count > 0); - break; - default: - Error("Unknown %d.\n", LineType); - } -} -*/ -void ScaleTris( vec3_t min, vec3_t max, int Width, int Height, float* u, float* v, int verts) -{ - - int i; - float hscale, vscale; - float scale; - - hscale = max[0]; - vscale = max[1]; - - hscale = (Width-2) / max[0]; - vscale = (Height-2) / max[1]; - - scale = hscale; - if (scale > vscale) - { - scale = vscale; - } - for ( i = 0; i 32) - { - Error ("Degrees of freedom out of range: %d",groups[num_groups].degrees); - } -} - -void Cmd_FMEndGroup (void) -{ - groups[num_groups].num_frames = fmheader.num_frames - groups[num_groups].start_frame; - - if(num_groups < MAX_GROUPS - 1) - { - num_groups++; - } - else - { - Error("Number of compression groups exceded: %i\n", MAX_GROUPS); - } -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/icon1.ico b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/icon1.ico deleted file mode 100644 index 8f441941..00000000 Binary files a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/icon1.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/images.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/images.c deleted file mode 100644 index 49f5cd27..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/images.c +++ /dev/null @@ -1,1397 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" - -#ifdef _WIN32 - #include -#endif - -#include - -#if 1 - extern char *g_outputDir; -#endif // _QDATA - -char mip_prefix[1024]; // directory to dump the textures in - -qboolean colormap_issued; -byte colormap_palette[768]; - -unsigned total_x = 0; -unsigned total_y = 0; -unsigned total_textures = 0; - -#define MAX_IMAGE_SIZE 512 - -#if 0 -/* -============== -RemapZero - -Replaces all 0 bytes in an image with the closest palette entry. -This is because NT won't let us change index 0, so any palette -animation leaves those pixels untouched. -============== -*/ -void RemapZero (byte *pixels, byte *palette, int width, int height) -{ - int i, c; - int alt_zero; - int value, best; - - alt_zero = 0; - best = 9999999; - for (i=1 ; i<255 ; i++) - { - value = palette[i*3+0]+palette[i*3+1]+palette[i*3+2]; - if (value < best) - { - best = value; - alt_zero = i; - } - } - - c = width*height; - for (i=0 ; i> 16; - palette_g[i] = (palette[i] & 0x0000ff00) >> 8; - palette_b[i] = (palette[i] & 0x000000ff); - } - - for(i=0;i biggest_delta) - continue; - dg = abs(palette_g[i] - g); - if (dg > biggest_delta) - continue; - db = abs(palette_b[i] - b); - if (db > biggest_delta) - continue; - - dist = dr * dr + dg * dg + db * db; - if (dist < min_dist) - { - min_dist = dist; - min_index = i; - if (min_dist == 0) break; - - dist = dr; - if (dg > dist) dist = dg; - if (db > dist) dist = db; - if (dist < biggest_delta) - biggest_delta = dist; - } - } - - last_place++; - if (last_place >= MAX_LAST) - last_place = 0; - - last_r[last_place] = r; - last_g[last_place] = g; - last_b[last_place] = b; - last_i[last_place] = min_index; - - return min_index; -} - - -void GL_ResampleTexture8P (byte *in, int inwidth, int inheight, byte *out, - int outwidth, int outheight, palette_t *palette) -{ - int i, j; - byte *inrow, *inrow2; - unsigned frac, fracstep; - unsigned p1[1024], p2[1024], *p1p, *p2p; - palette_t *c1,*c2,*c3,*c4; - unsigned r,g,b; - - fracstep = inwidth*0x10000/outwidth; - - frac = fracstep>>2; - for (i=0 ; i>16; - frac += fracstep; - } - frac = 3*(fracstep>>2); - for (i=0 ; i>16; - frac += fracstep; - } - - cached = 0; - - for (i=0 ; ir + (unsigned)c2->r + (unsigned)c3->r + (unsigned)c4->r)>>2; - g = ((unsigned)c1->g + (unsigned)c2->g + (unsigned)c3->g + (unsigned)c4->g)>>2; - b = ((unsigned)c1->b + (unsigned)c2->b + (unsigned)c3->b + (unsigned)c4->b)>>2; - - *out++ = ConvertTrueColorToPal(r,g,b); - } - } -} - -void GL_MipMap8P(byte *out, byte *in, int width, int height, palette_t *palette) -{ - int i, j; - palette_t *c1,*c2,*c3,*c4; - unsigned r,g,b; - - cached = 0; - memset(out, 0, 256 * 256); - width <<= 1; - height <<= 1; - - for (i = 0; i < height; i += 2, in += width) - { - for (j = 0; j < width; j += 2) - { - c1 = &palette[in[0]]; - c3 = &palette[in[width]]; - in++; - c2 = &palette[in[0]]; - c4 = &palette[in[width]]; - in++; - - r = ((unsigned)c1->r + (unsigned)c2->r + (unsigned)c3->r + (unsigned)c4->r) >> 2; - g = ((unsigned)c1->g + (unsigned)c2->g + (unsigned)c3->g + (unsigned)c4->g) >> 2; - b = ((unsigned)c1->b + (unsigned)c2->b + (unsigned)c3->b + (unsigned)c4->b) >> 2; - - *out++ = ConvertTrueColorToPal(r, g, b); - } - } -} - - -miptex_t *CreateMip(byte *data, unsigned width, unsigned height, byte *palette, int *FinalSize, qboolean mip) -{ - int scaled_width, scaled_height; - int i,j,r,g,b; - byte intensitytable[256]; - byte scaled[256*256]; - byte out[256*256]; - int miplevel; - miptex_t *mp; - byte *pos; - int size; - - for (i=0 ; i<256 ; i++) - { - j = i * intensity_value; - if (j > 255) - j = 255; - intensitytable[i] = j; - } - - for (scaled_width = 1 ; scaled_width < width ; scaled_width<<=1) - ; - if (1 && scaled_width > width && 1) - scaled_width >>= 1; - for (scaled_height = 1 ; scaled_height < height ; scaled_height<<=1) - ; - if (1 && scaled_height > height && 1) - scaled_height >>= 1; - - // don't ever bother with >256 textures - if (scaled_width > 256) - scaled_width = 256; - if (scaled_height > 256) - scaled_height = 256; - - if (scaled_width < 1) - scaled_width = 1; - if (scaled_height < 1) - scaled_height = 1; - - size = sizeof(*mp) + (scaled_width*scaled_height*3); - mp = (miptex_t *)SafeMalloc(size, "CreateMip"); - memset(mp,0,size); - - mp->version = MIP_VERSION; - - for(i=j=0;i<256;i++,j+=3) - { - mp->palette[i].r = r = intensitytable[palette[j]]; - mp->palette[i].g = g = intensitytable[palette[j+1]]; - mp->palette[i].b = b = intensitytable[palette[j+2]]; - image_pal[i] = 0xff000000 | (r<<16) | (g<<8) | (b); - } - - PrepareConvert(image_pal); - - if (scaled_width == width && scaled_height == height) - { - memcpy (scaled, data, width*height); - } - else - GL_ResampleTexture8P (data, width, height, scaled, scaled_width, scaled_height, mp->palette); - - pos = (byte *)(mp + 1); - miplevel = 0; - - while ((scaled_width >= 1 || scaled_height >= 1) && (miplevel <= MIPLEVELS-1) && (!miplevel || mip)) - { - if (scaled_width < 1) - scaled_width = 1; - if (scaled_height < 1) - scaled_height = 1; - - if(miplevel > 0) - GL_MipMap8P(out, (byte *)scaled, scaled_width, scaled_height, mp->palette); - else - memcpy(out, scaled, 256 * 256); - - mp->width[miplevel] = scaled_width; - mp->height[miplevel] = scaled_height; - mp->offsets[miplevel] = pos - ((byte *)(mp)); - memcpy(pos, out, scaled_width * scaled_height); - memcpy(scaled, out, 256 * 256); - pos += scaled_width * scaled_height; - - scaled_width >>= 1; - scaled_height >>= 1; - - miplevel++; - } - - *FinalSize = pos - ((byte *)(mp)); - - return mp; -} - - -void GL_ResampleTexture (unsigned *in, int inwidth, int inheight, unsigned *out, int outwidth, int outheight) -{ - int i, j; - unsigned *inrow, *inrow2; - unsigned frac, fracstep; - unsigned p1[1024], p2[1024]; - byte *pix1, *pix2, *pix3, *pix4; - - fracstep = inwidth*0x10000/outwidth; - - frac = fracstep>>2; - for (i=0 ; i>16); - frac += fracstep; - } - frac = 3*(fracstep>>2); - for (i=0 ; i>16); - frac += fracstep; - } - - for (i=0 ; i> 1; - for (j=0 ; j>2; - ((byte *)(out+j))[1] = (pix1[1] + pix2[1] + pix3[1] + pix4[1])>>2; - ((byte *)(out+j))[2] = (pix1[2] + pix2[2] + pix3[2] + pix4[2])>>2; - ((byte *)(out+j))[3] = (pix1[3] + pix2[3] + pix3[3] + pix4[3])>>2; - } - } -} - -void GL_MipMap (byte *out, byte *in, int width, int height) -{ - int i, j; - - width <<=3; - height <<= 1; - for (i=0 ; i>2; - out[1] = (in[1] + in[5] + in[width+1] + in[width+5])>>2; - out[2] = (in[2] + in[6] + in[width+2] + in[width+6])>>2; - out[3] = (in[3] + in[7] + in[width+3] + in[width+7])>>2; - } - } -} - -miptex32_t *CreateMip32(unsigned *data, unsigned width, unsigned height, int *FinalSize, qboolean mip) -{ - int scaled_width, scaled_height; - unsigned scaled[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; - unsigned out[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; - int miplevel; - miptex32_t *mp; - byte *pos; - int size; - paletteRGBA_t *test; - - for (scaled_width = 1 ; scaled_width < width ; scaled_width<<=1) - ; - if (1 && scaled_width > width && 1) - scaled_width >>= 1; - for (scaled_height = 1 ; scaled_height < height ; scaled_height<<=1) - ; - if (1 && scaled_height > height && 1) - scaled_height >>= 1; - - // don't ever bother with >256 textures - if (scaled_width > MAX_IMAGE_SIZE) - scaled_width = MAX_IMAGE_SIZE; - if (scaled_height > MAX_IMAGE_SIZE) - scaled_height = MAX_IMAGE_SIZE; - - if (scaled_width < 1) - scaled_width = 1; - if (scaled_height < 1) - scaled_height = 1; - - size = sizeof(*mp) + (scaled_width*scaled_height*3*4); - mp = (miptex32_t *)SafeMalloc(size, "CreateMip"); - memset(mp,0,size); - - mp->version = MIP32_VERSION; - - size = width*height; - test = (paletteRGBA_t *)data; - while(size) - { - if (test->a != 255) - { - mp->flags |= LittleLong(SURF_ALPHA_TEXTURE); - break; - } - - size--; - test++; - } - - if (scaled_width == width && scaled_height == height) - { - memcpy (scaled, data, width*height*4); - } - else - GL_ResampleTexture (data, width, height, scaled, scaled_width, scaled_height); - - pos = (byte *)(mp + 1); - miplevel = 0; - - while ((scaled_width >= 1 || scaled_height >= 1) && (miplevel <= MIPLEVELS-1) && (!miplevel || mip)) - { - if (scaled_width < 1) - scaled_width = 1; - if (scaled_height < 1) - scaled_height = 1; - - if (miplevel > 0) - { - GL_MipMap((byte *)out, (byte *)scaled, scaled_width, scaled_height); - } - else - { - memcpy(out, scaled, MAX_IMAGE_SIZE * MAX_IMAGE_SIZE * 4); - } - - mp->width[miplevel] = scaled_width; - mp->height[miplevel] = scaled_height; - mp->offsets[miplevel] = pos - ((byte *)(mp)); - memcpy(pos, out, scaled_width * scaled_height * 4); - memcpy(scaled, out, MAX_IMAGE_SIZE * MAX_IMAGE_SIZE * 4); - pos += scaled_width * scaled_height * 4; - - scaled_width >>= 1; - scaled_height >>= 1; - - miplevel++; - } - - *FinalSize = pos - ((byte *)(mp)); - - return mp; -} - -/* -============== -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]; - - GetScriptToken (false); - - if (token[0] == '/' || token[0] == '\\') - sprintf (savename, "%s%s.pcx", gamedir, token+1); - else - sprintf (savename, "%spics/%s.pcx", gamedir, 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; - } - - GetScriptToken (false); - xl = atoi (token); - GetScriptToken (false); - yl = atoi (token); - GetScriptToken (false); - w = atoi (token); - GetScriptToken (false); - 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 = (byte *) SafeMalloc (w*h, "Cmd_Grab"); - for (y=0 ; ybyteimagewidth || yl+h>byteimageheight) - Error ("GrabPic: Bad size: %i, %i, %i, %i",xl,yl,w,h); - - // crop it to the proper size - cropped = (byte *) SafeMalloc (w*h, "Cmd_Raw"); - for (y=0 ; y 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 = true; - - 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 -must be multiples of sixteen -SURF_WINDOW -============== -*/ - -void Cmd_Mip (void) -{ - int xl,yl,xh,yh,w,h; - byte *dest, *source; - int flags, value, contents; - mipparm_t *mp; - char lumpname[128]; - char altname[128]; - char animname[128]; - char damagename[128]; - byte buffer[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; - unsigned bufferl[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; - materialtype_t *mat; - char filename[1024]; - unsigned *destl, *sourcel; - int linedelta, x, y; - int size; - miptex_t *qtex; - miptex32_t *qtex32; - float scale_x, scale_y; - int mip_scale; - // detail texturing - char dt_name[128]; - float dt_scale_x, dt_scale_y; - float dt_u, dt_v; - float dt_alpha; - int dt_src_blend_mode, dt_dst_blend_mode; - int flags2; - - - GetScriptToken (false); - strcpy (lumpname, token); - - GetScriptToken (false); - xl = atoi (token); - GetScriptToken (false); - yl = atoi (token); - GetScriptToken (false); - w = atoi (token); - GetScriptToken (false); - h = atoi (token); - - total_x += w; - total_y += h; - total_textures++; - - if ( (w & 15) || (h & 15) ) - Error ("line %i: miptex sizes must be multiples of 16", scriptline); - - flags = 0; - flags2 = 0; - contents = 0; - value = 0; - mip_scale = 0; - - altname[0] = animname[0] = damagename[0] = 0; - - scale_x = scale_y = 0.5; - - // detail texturing - dt_name[0] = 0; - dt_scale_x = dt_scale_y = 0.0; - dt_u = dt_v = 0.0; - dt_alpha = 0.0; - dt_src_blend_mode = dt_dst_blend_mode = 0; - - // get optional flags and values - while (ScriptTokenAvailable ()) - { - GetScriptToken (false); - - for (mp=mipparms ; mp->name ; mp++) - { - if (!strcmp(mp->name, token)) - { - switch (mp->type) - { - case pt_animvalue: - GetScriptToken (false); // specify the next animation frame - strcpy (animname, token); - break; - case pt_altnamevalue: - GetScriptToken (false); // specify the alternate texture - strcpy (altname, token); - break; - case pt_damagenamevalue: - GetScriptToken (false); // specify the damage texture - strcpy (damagename, token); - break; - case pt_flags: - flags |= mp->flags; - break; - case pt_contents: - contents |= mp->flags; - break; - case pt_flagvalue: - flags |= mp->flags; - GetScriptToken (false); // specify the light value - value = atoi(token); - break; - case pt_materialvalue: - GetScriptToken(false); - for (mat=materialtypes ; mat->name ; mat++) - { - if (!strcmp(mat->name, token)) - { - // assumes SURF_MATERIAL is in top 8 bits - flags = (flags & 0x0FFFFFF) | (mat->value << 24); - break; - } - } - break; - case pt_scale: - GetScriptToken (false); // specify the x scale - scale_x = atof(token); - GetScriptToken (false); // specify the y scale - scale_y = atof(token); - break; - - case pt_mip: - mip_scale = 1; - break; - - case pt_detailer: - flags2 |= MIP32_DETAILER_FLAG2; - break; - - case pt_nomip: - flags2 |= MIP32_NOMIP_FLAG2; - break; - - case pt_detail: - GetScriptToken(false); - strcpy(dt_name, token); - GetScriptToken(false); - dt_scale_x = atof(token); - GetScriptToken(false); - dt_scale_y = atof(token); - GetScriptToken(false); - dt_u = atof(token); - GetScriptToken(false); - dt_v = atof(token); - GetScriptToken(false); - dt_alpha = atof(token); - GetScriptToken(false); - for (mp=mipparms ; mp->name ; mp++) - { - if (!strcmp(mp->name, token)) - { - if (mp->type == pt_gl) - { - dt_src_blend_mode = mp->flags; - break; - } - } - } - if (!mp->name) - { - Error ("line %i: invalid gl blend mode %s", scriptline, token); - } - GetScriptToken (false); - for (mp=mipparms ; mp->name ; mp++) - { - if (!strcmp(mp->name, token)) - { - if (mp->type == pt_gl) - { - dt_dst_blend_mode = mp->flags; - break; - } - } - } - if (!mp->name) - { - Error ("line %i: invalid gl blend mode %s", scriptline, token); - } - break; - } - break; - } - } - if (!mp->name) - Error ("line %i: unknown parm %s", scriptline, token); - } - - if (g_release) - return; // textures are only released by $maps - - xh = xl+w; - yh = yl+h; - if (xh*yh > MAX_IMAGE_SIZE*MAX_IMAGE_SIZE) - { - Error("line %i image %s: image is too big!", scriptline, lumpname); - } - - if (TrueColorImage) - { - if (xl >= longimagewidth || xh > longimagewidth || - yl >= longimageheight || yh > longimageheight) - { - Error ("line %i image %s: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, lumpname, xl,yl,w,h,longimagewidth,longimageheight); - } - - sourcel = longimage + (yl*longimagewidth) + xl; - destl = bufferl; - linedelta = (longimagewidth - w); - - for (y=yl ; yflags |= LittleLong(flags); - qtex32->flags2 |= LittleLong(flags2); - qtex32->contents = LittleLong(contents); - qtex32->value = LittleLong(value); - qtex32->scale_x = scale_x; - qtex32->scale_y = scale_y; - qtex32->mip_scale = mip_scale; - sprintf (qtex32->name, "%s/%s", mip_prefix, lumpname); - if (animname[0]) - { - sprintf (qtex32->animname, "%s/%s", mip_prefix, animname); - } - if (altname[0]) - { - sprintf (qtex32->altname, "%s/%s", mip_prefix, altname); - } - if (damagename[0]) - { - sprintf (qtex32->damagename, "%s/%s", mip_prefix, damagename); - } - if (dt_name[0] & ((flags2 & MIP32_DETAILER_FLAG2) == 0)) - { - sprintf (qtex32->dt_name, "%s/%s", mip_prefix, dt_name); - qtex32->dt_scale_x = dt_scale_x; - qtex32->dt_scale_y = dt_scale_y; - qtex32->dt_u = dt_u; - qtex32->dt_v = dt_v; - qtex32->dt_alpha = dt_alpha; - qtex32->dt_src_blend_mode = dt_src_blend_mode; - qtex32->dt_dst_blend_mode = dt_dst_blend_mode; - } - - // - // write it out - // - sprintf (filename, "%stextures/%s/%s.m32", g_outputDir, mip_prefix, lumpname); - if(qtex32->flags & (SURF_ALPHA_TEXTURE)) - printf ("writing %s with ALPHA\n", filename); - else - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex32, size); - - free (qtex32); - } - else - { - if (xl >= byteimagewidth || xh > byteimagewidth || - yl >= byteimageheight || yh > byteimageheight) - { - Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); - } - - source = byteimage + yl*byteimagewidth + xl; - dest = buffer; - linedelta = byteimagewidth - w; - - for (y=yl ; yflags = LittleLong(flags); - qtex->contents = LittleLong(contents); - qtex->value = LittleLong(value); - sprintf (qtex->name, "%s/%s", mip_prefix, lumpname); - if (animname[0]) - sprintf (qtex->animname, "%s/%s", mip_prefix, animname); - - // - // write it out - // - sprintf (filename, "%stextures/%s/%s.m8", g_outputDir, mip_prefix, lumpname); - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex, size); - - free (qtex); - } -} - -/* -=============== -Cmd_Mippal -=============== -*/ -void Cmd_Mippal (void) -{ - colormap_issued = true; - if (g_release) - return; - - memcpy (colormap_palette, lbmpalette, 768); - - BuildPalmap(); -} - - -/* -=============== -Cmd_Mipdir -=============== -*/ -void Cmd_Mipdir (void) -{ - char filename[1024]; - - GetScriptToken (false); - strcpy (mip_prefix, token); - // create the directory if needed - sprintf (filename, "%stextures", g_outputDir); - Q_mkdir (filename); - sprintf (filename, "%stextures/%s", g_outputDir, mip_prefix); - Q_mkdir (filename); -} - - -/* -============================================================================= - -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; - - GetScriptToken (false); - - 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", gamedir, 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/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/jointed.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/jointed.c deleted file mode 100644 index 4d78a792..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/jointed.c +++ /dev/null @@ -1,572 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#include "token.h" -#include "joints.h" -#include "angles.h" -#include "inout.h" - -char *SKEL_ROOT_NAMES[] = -{ - "RAVEN_SPINE" -}; - -char *SKEL_NAMES[] = -{ - "RAVEN_WAIST1", - "RAVEN_WAIST2", - "RAVEN_NECK" -}; - -int NAME_OFFSETS[] = -{ - 0 -}; - -int numJointsForSkeleton[] = -{ - NUM_JOINTS_RAVEN, - NUM_JOINTS_BOX -}; - -float g_scaling[3]; -float g_rotation[3]; -float g_translation[3]; - -//========================================================================== -// -// LoadHRCClustered -// -//========================================================================== - -static void LoadHRCClustered(char *fileName, int **clusterList, int *num_verts, int skelType) -{ - int i, j; - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - - TK_Beyond(TK_CLUSTERS); - - while(TK_Search(TK_CLUSTER_NAME) != TK_EOF) - { - TK_Require(TK_STRING); - - for( i = 0; i < numJointsForSkeleton[skelType]; ++i) - { - if(stricmp(tk_String, SKEL_NAMES[NAME_OFFSETS[skelType]+i]) == 0) - { - i = -i + numJointsForSkeleton[skelType] - 1; - - TK_BeyondRequire(TK_NUM_CLUSTER_VERTICES, TK_INTNUMBER); - - num_verts[i+1] = tk_IntNumber; - - clusterList[i] = (int *) SafeMalloc(num_verts[i+1]*sizeof(int), "LoadHRCClustered"); - assert(clusterList[i]); - // currently this function is only called by LoadTriangleListClustered, which in turn is only - // called by Cmd_Base in qdata. This is where the only call to free for this memory is being made. - - TK_Beyond(TK_LBRACE); - - for(j = 0; j < num_verts[i+1]; ++j) - { - TK_Require(TK_INTNUMBER); - clusterList[i][j] = tk_IntNumber; - TK_Fetch(); - } - - break; - } - } - } - - num_verts[0] = numJointsForSkeleton[skelType]; -} - -static void LoadHRCGlobals(char *fileName) -{ - int i; - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - TK_Beyond(TK_MODEL); - - TK_Beyond(TK_SCALING); - for(i = 0; i < 3; i++) - { - TK_Require(TK_FLOATNUMBER); - g_scaling[i] = tk_FloatNumber; - TK_Fetch(); - } - - TK_Beyond(TK_ROTATION); - for(i = 0; i < 3; i++) - { - TK_Require(TK_FLOATNUMBER); - g_rotation[i] = tk_FloatNumber; - TK_Fetch(); - } - - TK_Beyond(TK_TRANSLATION); - for(i = 0; i < 3; i++) - { - TK_Require(TK_FLOATNUMBER); - g_translation[i] = tk_FloatNumber; - TK_Fetch(); - } -} - -static void ParseVec3(vec3_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void ParseRotation3(vec3_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = -tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void ParseTranslation3(vec3_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void LoadHRCJointList(char *fileName, QDataJoint_t *jointList, int skelType) -{ -#define MAX_STACK 64 - int i, j; - vec3_t curTranslation[MAX_STACK], curRotation[MAX_STACK], curScale[MAX_STACK]; - int curCorrespondingJoint[MAX_STACK]; - int currentStack = 0, stackSize; - int baseJoint; - float cx, sx, cy, sy, cz, sz; - float rx, ry, rz; - float x2, y2, z2; - - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - - TK_Beyond(TK_MODEL); - TK_Beyond(TK_MODEL); - -/* while(1) - { - TK_Beyond(TK_MODEL); - TK_BeyondRequire(TK_NAME, TK_STRING); - - if(_stricmp(tk_String, SKEL_ROOT_NAMES[skelType]) == 0) - break; - }*/ - - TK_Beyond(TK_SCALING); - - ParseVec3(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3(curRotation[currentStack]); - - TK_Beyond(TK_TRANSLATION); - - ParseVec3(curTranslation[currentStack]); - - // account for global model translation - curTranslation[currentStack][1] += g_translation[0]; - curTranslation[currentStack][2] += g_translation[1]; - curTranslation[currentStack][0] += g_translation[2]; - - ++currentStack; - - for(i = 0; i < NUM_JOINTS_RAVEN; ++i) - { - while(1) - { - TK_Beyond(TK_MODEL); - -// TK_BeyondRequire(TK_NAME, TK_STRING); - -// if(_stricmp(tk_String, SKEL_NAMES[NAME_OFFSETS[skelType]+i]) == 0) - break; - - TK_Beyond(TK_SCALING); - - ParseVec3(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3(curRotation[currentStack]); - - TK_Beyond(TK_TRANSLATION); - - ParseVec3(curTranslation[currentStack]); - - curCorrespondingJoint[currentStack] = -1; - - ++currentStack; - } - - TK_Beyond(TK_SCALING); - - ParseVec3(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3(curRotation[currentStack]); - - jointList[i].rotation[1] = curRotation[currentStack][1]; - jointList[i].rotation[2] = curRotation[currentStack][2]; - jointList[i].rotation[0] = curRotation[currentStack][0]; - - TK_Beyond(TK_TRANSLATION); - - ParseVec3(curTranslation[currentStack]); - - jointList[i].placement.origin[1] = curTranslation[currentStack][1]; - jointList[i].placement.origin[2] = curTranslation[currentStack][2]; - jointList[i].placement.origin[0] = curTranslation[currentStack][0]; - - jointList[i].placement.direction[1] = 7.5; - jointList[i].placement.direction[2] = 0.0; - jointList[i].placement.direction[0] = 0.0; - - jointList[i].placement.up[1] = 0.0; - jointList[i].placement.up[2] = 7.5; - jointList[i].placement.up[0] = 0.0; - - curCorrespondingJoint[currentStack] = i; - - ++currentStack; - } - - stackSize = currentStack; - - for(i = 0; i < NUM_JOINTS_RAVEN; ++i) - { - rx = jointList[i].rotation[0]*ANGLE_TO_RAD; - ry = jointList[i].rotation[1]*ANGLE_TO_RAD; - rz = jointList[i].rotation[2]*ANGLE_TO_RAD; - - cx = cos(rx); - sx = sin(rx); - - cy = cos(ry); - sy = sin(ry); - - cz = cos(rz); - sz = sin(rz); - - // y-axis rotation for direction - x2 = jointList[i].placement.direction[0]*cy+jointList[i].placement.direction[2]*sy; - z2 = -jointList[i].placement.direction[0]*sy+jointList[i].placement.direction[2]*cy; - jointList[i].placement.direction[0] = x2; - jointList[i].placement.direction[2] = z2; - - // y-axis rotation for up - x2 = jointList[i].placement.up[0]*cy+jointList[i].placement.up[2]*sy; - z2 = -jointList[i].placement.up[0]*sy+jointList[i].placement.up[2]*cy; - jointList[i].placement.up[0] = x2; - jointList[i].placement.up[2] = z2; - - // z-axis rotation for direction - x2 = jointList[i].placement.direction[0]*cz-jointList[i].placement.direction[1]*sz; - y2 = jointList[i].placement.direction[0]*sz+jointList[i].placement.direction[1]*cz; - jointList[i].placement.direction[0] = x2; - jointList[i].placement.direction[1] = y2; - - // z-axis rotation for up - x2 = jointList[i].placement.up[0]*cz-jointList[i].placement.up[1]*sz; - y2 = jointList[i].placement.up[0]*sz+jointList[i].placement.up[1]*cz; - jointList[i].placement.up[0] = x2; - jointList[i].placement.up[1] = y2; - - // x-axis rotation for direction vector - y2 = jointList[i].placement.direction[1]*cx-jointList[i].placement.direction[2]*sx; - z2 = jointList[i].placement.direction[1]*sx+jointList[i].placement.direction[2]*cx; - jointList[i].placement.direction[1] = y2; - jointList[i].placement.direction[2] = z2; - - // x-axis rotation for up vector - y2 = jointList[i].placement.up[1]*cx-jointList[i].placement.up[2]*sx; - z2 = jointList[i].placement.up[1]*sx+jointList[i].placement.up[2]*cx; - jointList[i].placement.up[1] = y2; - jointList[i].placement.up[2] = z2; - - // translate to position in model - jointList[i].placement.direction[0] += jointList[i].placement.origin[0]; - jointList[i].placement.direction[1] += jointList[i].placement.origin[1]; - jointList[i].placement.direction[2] += jointList[i].placement.origin[2]; - - // translate to position in model - jointList[i].placement.up[0] += jointList[i].placement.origin[0]; - jointList[i].placement.up[1] += jointList[i].placement.origin[1]; - jointList[i].placement.up[2] += jointList[i].placement.origin[2]; - } - - baseJoint = NUM_JOINTS_RAVEN; - - for(i = stackSize/*NUM_JOINTS_RAVEN*/ - 1; i > 0; --i) - { - - rx = curRotation[i-1][0]*ANGLE_TO_RAD; - ry = curRotation[i-1][1]*ANGLE_TO_RAD; - rz = curRotation[i-1][2]*ANGLE_TO_RAD; - - cx = cos(rx); - sx = sin(rx); - - cy = cos(ry); - sy = sin(ry); - - cz = cos(rz); - sz = sin(rz); - - for(j = i-1; j < stackSize-1; ++j) - { - // y-axis rotation for origin - x2 = jointList[j].placement.origin[0]*cy+jointList[j].placement.origin[2]*sy; - z2 = -jointList[j].placement.origin[0]*sy+jointList[j].placement.origin[2]*cy; - jointList[j].placement.origin[0] = x2; - jointList[j].placement.origin[2] = z2; - - // y-axis rotation for direction - x2 = jointList[j].placement.direction[0]*cy+jointList[j].placement.direction[2]*sy; - z2 = -jointList[j].placement.direction[0]*sy+jointList[j].placement.direction[2]*cy; - jointList[j].placement.direction[0] = x2; - jointList[j].placement.direction[2] = z2; - - // y-axis rotation for up - x2 = jointList[j].placement.up[0]*cy+jointList[j].placement.up[2]*sy; - z2 = -jointList[j].placement.up[0]*sy+jointList[j].placement.up[2]*cy; - jointList[j].placement.up[0] = x2; - jointList[j].placement.up[2] = z2; - - // z-axis rotation for origin - x2 = jointList[j].placement.origin[0]*cz-jointList[j].placement.origin[1]*sz; - y2 = jointList[j].placement.origin[0]*sz+jointList[j].placement.origin[1]*cz; - jointList[j].placement.origin[0] = x2; - jointList[j].placement.origin[1] = y2; - - // z-axis rotation for direction - x2 = jointList[j].placement.direction[0]*cz-jointList[j].placement.direction[1]*sz; - y2 = jointList[j].placement.direction[0]*sz+jointList[j].placement.direction[1]*cz; - jointList[j].placement.direction[0] = x2; - jointList[j].placement.direction[1] = y2; - - // z-axis rotation for up - x2 = jointList[j].placement.up[0]*cz-jointList[j].placement.up[1]*sz; - y2 = jointList[j].placement.up[0]*sz+jointList[j].placement.up[1]*cz; - jointList[j].placement.up[0] = x2; - jointList[j].placement.up[1] = y2; - - // x-axis rotation for origin - y2 = jointList[j].placement.origin[1]*cx-jointList[j].placement.origin[2]*sx; - z2 = jointList[j].placement.origin[1]*sx+jointList[j].placement.origin[2]*cx; - jointList[j].placement.origin[1] = y2; - jointList[j].placement.origin[2] = z2; - - // x-axis rotation for direction vector - y2 = jointList[j].placement.direction[1]*cx-jointList[j].placement.direction[2]*sx; - z2 = jointList[j].placement.direction[1]*sx+jointList[j].placement.direction[2]*cx; - jointList[j].placement.direction[1] = y2; - jointList[j].placement.direction[2] = z2; - - // x-axis rotation for up vector - y2 = jointList[j].placement.up[1]*cx-jointList[j].placement.up[2]*sx; - z2 = jointList[j].placement.up[1]*sx+jointList[j].placement.up[2]*cx; - jointList[j].placement.up[1] = y2; - jointList[j].placement.up[2] = z2; - - if(curCorrespondingJoint[j+1] != -1) - { - // translate origin - jointList[j].placement.origin[0] += curTranslation[i-1][0]; - jointList[j].placement.origin[1] += curTranslation[i-1][1]; - jointList[j].placement.origin[2] += curTranslation[i-1][2]; - - // translate back to local coord - jointList[j].placement.direction[0] += curTranslation[i-1][0]; - jointList[j].placement.direction[1] += curTranslation[i-1][1]; - jointList[j].placement.direction[2] += curTranslation[i-1][2]; - - // translate back to local coord - jointList[j].placement.up[0] += curTranslation[i-1][0]; - jointList[j].placement.up[1] += curTranslation[i-1][1]; - jointList[j].placement.up[2] += curTranslation[i-1][2]; - } - } - } -} - -void LoadGlobals(char *fileName) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - - LoadHRCGlobals(InputFileName); - - printf(" - assuming .HRC\n"); - return; - } - - Error("\n Could not open file '%s':\n" - "No HRC match.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { - printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRCGlobals(fileName); - return; - } - } - - Error("Could not open file '%s':\n",fileName); - } -} - -void LoadClusters(char *fileName, int **clusterList, int *num_verts, int skelType) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - - LoadHRCClustered(InputFileName, clusterList, num_verts, skelType); - - printf(" - assuming .HRC\n"); - return; - } - - Error("\n Could not open file '%s':\n" - "No HRC match.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { - printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRCClustered(fileName, clusterList, num_verts, skelType); - return; - } - } - - Error("Could not open file '%s':\n",fileName); - } -} - -void LoadJointList(char *fileName, QDataJoint_t *jointList, int skelType) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - - LoadHRCJointList(InputFileName, jointList, skelType); - - printf(" - assuming .HRC\n"); - return; - } - - Error("\n Could not open file '%s':\n" - "No HRC.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { - printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRCJointList(fileName, jointList, skelType); - - return; - } - } - - Error("Could not open file '%s':\n",fileName); - } -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/jointed.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/jointed.h deleted file mode 100644 index d0736c1f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/jointed.h +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright (C) 1999-2006 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 _JOINTED_H -#define _JOINTED_H - -#include "joints.h" - -void LoadGlobals(char *fileName); -void LoadClusters(char *fileName, int **clusterList, int *num_verts, int skel_type); -void LoadJointList(char *fileName, struct QDataJoint_s *jointList, int num_verts); - -#define NUM_CLUSTERS 8 - -#define NOT_JOINTED -1 - -#endif //_JOINTED_H diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/joints.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/joints.h deleted file mode 100644 index c08dee10..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/joints.h +++ /dev/null @@ -1,144 +0,0 @@ -/* -Copyright (C) 1999-2006 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 JOINTS_H -#define JOINTS_H - -#ifdef _HERETIC2_ -#include "angles.h" -#endif - -//typedef float vec3_t[3]; -//typedef unsigned char byte; - -#ifndef _WIN32 -#define stricmp strcasecmp -#define strcmpi strcasecmp -#endif - -typedef struct Placement_s -{ - vec3_t origin; - vec3_t direction; - vec3_t up; -} Placement_t; - -#if 1 -typedef struct QDataJoint_s -{ - Placement_t placement; - vec3_t rotation; -} QDataJoint_t; -#endif - -typedef struct ArrayedListNode_s -{ - int data; - int next; - int inUse; -} ArrayedListNode_t; - -#define ARRAYEDLISTNODE_NULL -1 - -typedef struct JointAngles_s -{ - float angles[3]; - int children; - int created; -} JointAngles_t; - -typedef struct JointAngles2_s -{ - float angles[3]; - int children; - int changed[3]; - int inUse; -} JointAngles2_t; - -#define MAX_MODELJOINTS 256 -#define MAX_MODELJOINTNODES 255 - -extern JointAngles_t jointAngles[MAX_MODELJOINTS]; -extern JointAngles2_t jointAngles2[MAX_MODELJOINTS]; - -extern ArrayedListNode_t jointAngleNodes[MAX_MODELJOINTNODES]; - -// Skeletal structures enums -enum { - SKEL_RAVEN = 0, - SKEL_BOX, - NUM_SKELETONS -}; - -// Raven Skeletal structures enums -enum { - RAVEN_WAIST1 = 0, - RAVEN_WAIST2 = 1, - RAVEN_HEAD = 2, - NUM_JOINTS_RAVEN -}; - -// Box Skeletal structures enums -enum { - BOX_CENTER = 0, - NUM_JOINTS_BOX -}; - -extern int numJointsForSkeleton[]; -extern char *RAVEN_SKEL_NAMES[]; - -#define J_NEW_SKELETON 0x00001000 -#define J_YAW_CHANGED 0x00002000 -#define J_PITCH_CHANGED 0x00004000 -#define J_ROLL_CHANGED 0x00008000 -#define MAX_JOINTS 0x00000fff -/* -inline int GetFreeNode(ArrayedListNode_t *nodeArray, int max) -{ // yeah, I know this is a sucky, inefficient way to do this, but I didn't feel like taking the time to write a real resource manager in C - int i; - - for(i = 0; i < max; ++i) - { - if(!nodeArray[i].inUse) - { - nodeArray[i].inUse = 1; - return i; - } - } - - assert(0); - return -1; -} - -inline void FreeNode(ArrayedListNode_t *nodeArray, int index) -{ - nodeArray[index].inUse = 0; -} -*/ -int CreateSkeleton(int structure); -void CreateSkeletonAtIndex(int structure, int index); -void FreeSkeleton(int structure, int index); -void SetJointAngle(int jointIndex, int angleIndex, float angle); -float ModifyJointAngle(int jointIndex, int angleIndex, float deltaAngle); -int ZeroJointAngle(int jointIndex, int angleIndex, float angVel); -int ApplyAngVelToJoint(int jointIndex, int angleIndex, float angVel, float destAng); - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/models.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/models.c deleted file mode 100644 index 27145b70..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/models.c +++ /dev/null @@ -1,2050 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" -#include -#include "jointed.h" -#include "fmodel.h" - -//================================================================= - -typedef struct -{ - int numnormals; - vec3_t normalsum; -} vertexnormals_t; - -typedef struct -{ - vec3_t v; - int lightnormalindex; -} trivert_t; - -typedef struct -{ - vec3_t mins, maxs; - char name[16]; - trivert_t v[MAX_VERTS]; - QDataJoint_t joints[NUM_CLUSTERS]; // ,this -} frame_t; - -// ,and all of this should get out of here, need to use new stuff in fmodels instead - -typedef struct IntListNode_s -{ - int data; - struct IntListNode_s *next; -} IntListNode_t; // gaak - -typedef struct -{ - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this -} PartialAliasFrame_t; - -int jointed; -int clustered; - -int *clusters[NUM_CLUSTERS]; -IntListNode_t *vertLists[NUM_CLUSTERS]; -int num_verts[NUM_CLUSTERS + 1]; -int new_num_verts[NUM_CLUSTERS + 1]; - -// end that - -//================================================================ - -frame_t g_frames[MAX_FRAMES]; -//frame_t *g_frames; - -static dmdl_t model; - - -float scale_up; // set by $scale -vec3_t adjust; // set by $origin -int g_fixedwidth, g_fixedheight; // set by $skinsize - - -// -// base frame info -// -dstvert_t base_st[MAX_VERTS]; -dtriangle_t triangles[MAX_TRIANGLES]; - -static int triangle_st[MAX_TRIANGLES][3][2]; - -// the command list holds counts, s/t values, and xyz indexes -// that are valid for every frame -int commands[16384]; -int numcommands; -int numglverts; -int used[MAX_TRIANGLES]; - -char g_skins[MAX_MD2SKINS][64]; - -char cdarchive[1024]; -char cdpartial[1024]; -char cddir[1024]; - -char modelname[64]; // empty unless $modelname issued (players) - -extern char *g_outputDir; - -#define NUMVERTEXNORMALS 162 - -float avertexnormals[NUMVERTEXNORMALS][3] = -{ - #include "anorms.h" -}; - -unsigned char pic[SKINPAGE_HEIGHT*SKINPAGE_WIDTH], pic_palette[768]; - -FILE *headerouthandle = NULL; - -//============================================================== - -/* -=============== -ClearModel -=============== -*/ -static void ClearModel (void) -{ - memset (&model, 0, sizeof(model)); - - modelname[0] = 0; - jointed = NOT_JOINTED; - clustered = 0; - scale_up = 1.0; - VectorCopy (vec3_origin, adjust); - g_fixedwidth = g_fixedheight = 0; - g_skipmodel = false; -} - - -void H_printf(char *fmt, ...) -{ - va_list argptr; - char name[1024]; - - if (!headerouthandle) - { - sprintf (name, "%s/tris.h", cddir); - headerouthandle = SafeOpenWrite (name); - fprintf(headerouthandle, "// %s\n\n", cddir); - fprintf(headerouthandle, "// This file generated by qdata - Do NOT Modify\n\n"); - } - - va_start (argptr, fmt); - vfprintf (headerouthandle, fmt, argptr); - va_end (argptr); -} - -#if 1 -/* -============ -WriteModelFile -============ -*/ -void WriteCommonModelFile (FILE *modelouthandle, PartialAliasFrame_t *outFrames) -{ - int i; - dmdl_t modeltemp; - int j, k; - frame_t *in; - daliasframe_t *out; - byte buffer[MAX_VERTS*4+128]; - float v; - int c_on, c_off; - - model.version = ALIAS_VERSION; - model.framesize = (int)&((daliasframe_t *)0)->verts[model.num_xyz]; - model.num_glcmds = numcommands; - model.ofs_skins = sizeof(dmdl_t); - model.ofs_st = model.ofs_skins + model.num_skins * MAX_SKINNAME; - model.ofs_tris = model.ofs_st + model.num_st*sizeof(dstvert_t); - model.ofs_frames = model.ofs_tris + model.num_tris*sizeof(dtriangle_t); - model.ofs_glcmds = model.ofs_frames + model.num_frames*model.framesize; - model.ofs_end = model.ofs_glcmds + model.num_glcmds*sizeof(int); - // - // write out the model header - // - for (i=0 ; iname, in->name); - for (j=0 ; j<3 ; j++) - { - out->scale[j] = (in->maxs[j] - in->mins[j])/255; - out->translate[j] = in->mins[j]; - - if(outFrames) - { - outFrames[i].scale[j] = out->scale[j]; - outFrames[i].translate[j] = out->translate[j]; - } - } - - for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; - - for (k=0 ; k<3 ; k++) - { - // scale to byte values & min/max check - v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); - - // clamp, so rounding doesn't wrap from 255.6 to 0 - if (v > 255.0) - v = 255.0; - if (v < 0) - v = 0; - out->verts[j].v[k] = v; - } - } - - for (j=0 ; j<3 ; j++) - { - out->scale[j] = LittleFloat (out->scale[j]); - out->translate[j] = LittleFloat (out->translate[j]); - } - - SafeWrite (modelouthandle, out, model.framesize); - } - - // - // write out glcmds - // - SafeWrite (modelouthandle, commands, numcommands*4); -} - -/* -============ -WriteModelFile -============ -*/ -void WriteModelFile (FILE *modelouthandle) -{ - model.ident = IDALIASHEADER; - - WriteCommonModelFile(modelouthandle, NULL); -} - -/* -============ -WriteJointedModelFile -============ -*/ -void WriteJointedModelFile (FILE *modelouthandle) -{ - int i; - int j, k; - frame_t *in; - float v; - IntListNode_t *current, *toFree; - PartialAliasFrame_t outFrames[MAX_FRAMES]; - - model.ident = IDJOINTEDALIASHEADER; - - WriteCommonModelFile(modelouthandle, outFrames); - - // Skeletal Type - SafeWrite(modelouthandle, &jointed, sizeof(int)); - - // number of joints - SafeWrite(modelouthandle, &numJointsForSkeleton[jointed], sizeof(int)); - - // number of verts in each cluster - SafeWrite(modelouthandle, &new_num_verts[1], sizeof(int)*numJointsForSkeleton[jointed]); - - // cluster verts - for(i = 0; i < new_num_verts[0]; ++i) - { - current = vertLists[i]; - while(current) - { - SafeWrite (modelouthandle, ¤t->data, sizeof(int)); - toFree = current; - current = current->next; - free(toFree); // freeing of memory allocated in ReplaceClusterIndex called in Cmd_Base - } - } - - for (i=0 ; ijoints[j].placement.origin[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // clamp, so rounding doesn't wrap from 255.6 to 0 - if (v > 255.0) - { - v = 255.0; - } - - if (v < 0) - { - v = 0; - } - - // write out origin as a float (there's only a few per model, so it's not really - // a size issue) - SafeWrite (modelouthandle, &v, sizeof(float)); - } - - for (k=0 ; k<3 ; k++) - { - v = Q_rint ( (in->joints[j].placement.direction[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // clamp, so rounding doesn't wrap from 255.6 to 0 - if (v > 255.0) - { - v = 255.0; - } - - if (v < 0) - { - v = 0; - } - - // write out origin as a float (there's only a few per model, so it's not really - // a size issue) - SafeWrite (modelouthandle, &v, sizeof(float)); - } - - for (k=0 ; k<3 ; k++) - { - v = Q_rint ( (in->joints[j].placement.up[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); - - // clamp, so rounding doesn't wrap from 255.6 to 0 - if (v > 255.0) - { - v = 255.0; - } - - if (v < 0) - { - v = 0; - } - - // write out origin as a float (there's only a few per model, so it's not really - // a size issue) - SafeWrite (modelouthandle, &v, sizeof(float)); - } - } - } -} -#else -/* -============ -WriteModelFile -============ -*/ -static void WriteModelFile (FILE *modelouthandle) -{ - int i; - dmdl_t modeltemp; - int j, k; - frame_t *in; - daliasframe_t *out; - byte buffer[MAX_VERTS*4+128]; - float v; - int c_on, c_off; - - model.ident = IDALIASHEADER; - model.version = ALIAS_VERSION; - model.framesize = (int)&((daliasframe_t *)0)->verts[model.num_xyz]; - model.num_glcmds = numcommands; - model.ofs_skins = sizeof(dmdl_t); - model.ofs_st = model.ofs_skins + model.num_skins * MAX_SKINNAME; - model.ofs_tris = model.ofs_st + model.num_st*sizeof(dstvert_t); - model.ofs_frames = model.ofs_tris + model.num_tris*sizeof(dtriangle_t); - model.ofs_glcmds = model.ofs_frames + model.num_frames*model.framesize; - model.ofs_end = model.ofs_glcmds + model.num_glcmds*4; - - // - // write out the model header - // - for (i=0 ; iname, in->name); - for (j=0 ; j<3 ; j++) - { - out->scale[j] = (in->maxs[j] - in->mins[j])/255; - out->translate[j] = in->mins[j]; - } - - for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; - - for (k=0 ; k<3 ; k++) - { - // scale to byte values & min/max check - v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); - - // clamp, so rounding doesn't wrap from 255.6 to 0 - if (v > 255.0) - v = 255.0; - if (v < 0) - v = 0; - out->verts[j].v[k] = v; - } - } - - for (j=0 ; j<3 ; j++) - { - out->scale[j] = LittleFloat (out->scale[j]); - out->translate[j] = LittleFloat (out->translate[j]); - } - - SafeWrite (modelouthandle, out, model.framesize); - } - - // - // write out glcmds - // - SafeWrite (modelouthandle, commands, numcommands*4); -} -#endif - -/* -=============== -FinishModel -=============== -*/ -void FinishModel (void) -{ - FILE *modelouthandle; - int i; - char name[1024]; - - if (!model.num_frames) - return; - -// -// copy to release directory tree if doing a release build -// - if (g_release) - { - if (modelname[0]) - sprintf (name, "%s", modelname); - else - sprintf (name, "%s/tris.md2", cdpartial); - ReleaseFile (name); - - for (i=0 ; iindex_xyz[(startv)%3]; - strip_xyz[1] = last->index_xyz[(startv+1)%3]; - strip_xyz[2] = last->index_xyz[(startv+2)%3]; - strip_st[0] = last->index_st[(startv)%3]; - strip_st[1] = last->index_st[(startv+1)%3]; - strip_st[2] = last->index_st[(startv+2)%3]; - - strip_tris[0] = starttri; - stripcount = 1; - - m1 = last->index_xyz[(startv+2)%3]; - st1 = last->index_st[(startv+2)%3]; - m2 = last->index_xyz[(startv+1)%3]; - st2 = last->index_st[(startv+1)%3]; - - // look for a matching triangle -nexttri: - for (j=starttri+1, check=&triangles[starttri+1] - ; jindex_xyz[k] != m1) - continue; - if (check->index_st[k] != st1) - continue; - if (check->index_xyz[ (k+1)%3 ] != m2) - continue; - if (check->index_st[ (k+1)%3 ] != st2) - continue; - - // this is the next part of the fan - - // if we can't use this triangle, this tristrip is done - if (used[j]) - goto done; - - // the new edge - if (stripcount & 1) - { - m2 = check->index_xyz[ (k+2)%3 ]; - st2 = check->index_st[ (k+2)%3 ]; - } - else - { - m1 = check->index_xyz[ (k+2)%3 ]; - st1 = check->index_st[ (k+2)%3 ]; - } - - strip_xyz[stripcount+2] = check->index_xyz[ (k+2)%3 ]; - strip_st[stripcount+2] = check->index_st[ (k+2)%3 ]; - strip_tris[stripcount] = j; - stripcount++; - - used[j] = 2; - goto nexttri; - } - } -done: - - // clear the temp used flags - for (j=starttri+1 ; jindex_xyz[(startv)%3]; - strip_xyz[1] = last->index_xyz[(startv+1)%3]; - strip_xyz[2] = last->index_xyz[(startv+2)%3]; - strip_st[0] = last->index_st[(startv)%3]; - strip_st[1] = last->index_st[(startv+1)%3]; - strip_st[2] = last->index_st[(startv+2)%3]; - - strip_tris[0] = starttri; - stripcount = 1; - - m1 = last->index_xyz[(startv+0)%3]; - st1 = last->index_st[(startv+0)%3]; - m2 = last->index_xyz[(startv+2)%3]; - st2 = last->index_st[(startv+2)%3]; - - - // look for a matching triangle -nexttri: - for (j=starttri+1, check=&triangles[starttri+1] - ; jindex_xyz[k] != m1) - continue; - if (check->index_st[k] != st1) - continue; - if (check->index_xyz[ (k+1)%3 ] != m2) - continue; - if (check->index_st[ (k+1)%3 ] != st2) - continue; - - // this is the next part of the fan - - // if we can't use this triangle, this tristrip is done - if (used[j]) - goto done; - - // the new edge - m2 = check->index_xyz[ (k+2)%3 ]; - st2 = check->index_st[ (k+2)%3 ]; - - strip_xyz[stripcount+2] = m2; - strip_st[stripcount+2] = st2; - strip_tris[stripcount] = j; - stripcount++; - - used[j] = 2; - goto nexttri; - } - } -done: - - // clear the temp used flags - for (j=starttri+1 ; j bestlen) - { - besttype = type; - bestlen = len; - for (j=0 ; j= 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_fixedwidth / 2; - iheight = g_fixedheight; - - s_scale = (float)(iwidth-4) / width; - t_scale = (float)(iheight-4) / height; - } - -// -// determine which side of each triangle to map the texture to -// - for (i=0 ; i 0) - { - basex = iwidth + 2; - } - else - { - basex = 2; - } - basey = 2; - - for (j=0 ; j<3 ; j++) - { - pbasevert = ptri[i].verts[j]; - - triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); - triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); - } - } - -// make the width a multiple of 4; some hardware requires this, and it ensures -// dword alignment for each scan - swidth = iwidth*2; - model.skinwidth = (swidth + 3) & ~3; - model.skinheight = iheight; -} -#endif - -//========================================================================== -// -// DrawScreen -// -//========================================================================== - -void DrawScreen(float s_scale, float t_scale, float iwidth, float iheight) -{ - int i; - byte *scrpos; - char buffer[256]; - - // Divider - scrpos = &pic[(INFO_Y-2)*SKINPAGE_WIDTH]; - for(i = 0; i < SKINPAGE_WIDTH; i++) - { - *scrpos++ = 255; - } - - sprintf(buffer, "GENSKIN: "); - DrawTextChar(16, INFO_Y, buffer); - - sprintf(buffer, "( %03d * %03d ) SCALE %f %f, SKINWIDTH %d," - " SKINHEIGHT %d", (int)ScaleWidth, (int)ScaleHeight, s_scale, t_scale, (int)iwidth*2, (int)iheight); - DrawTextChar(80, INFO_Y, buffer); -} - -/* -============ -BuildST - -Builds the triangle_st array for the base frame and -model.skinwidth / model.skinheight - - FIXME: allow this to be loaded from a file for - arbitrary mappings -============ -*/ -void BuildST (triangle_t *ptri, int numtri, qboolean DrawSkin) -{ - int i, j; - int width, height, iwidth, iheight, swidth; - float basex, basey; - float scale; - vec3_t mins, maxs; - float *pbasevert; - vec3_t vtemp1, vtemp2, normal; - float s_scale, t_scale; - float scWidth; - float scHeight; - - // - // find bounds of all the verts on the base frame - // - ClearBounds (mins, maxs); - - for (i=0 ; i= scHeight) - { - scale = scHeight/height; - } - - iwidth = ceil(width*scale)+4; - iheight = ceil(height*scale)+4; - - s_scale = (float)(iwidth-4) / width; - t_scale = (float)(iheight-4) / height; - t_scale = s_scale; - - if (DrawSkin) - DrawScreen(s_scale, t_scale, iwidth, iheight); - - -/* if (!g_fixedwidth) - { // old style - scale = 8; - if (width*scale >= 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_fixedwidth / 2; - iheight = g_fixedheight; - - s_scale = (float)(iwidth-4) / width; - t_scale = (float)(iheight-4) / height; - }*/ - -// -// determine which side of each triangle to map the texture to -// - for (i=0 ; i 0) - { - basex = iwidth + 2; - } - else - { - basex = 2; - } - basey = 2; - - for (j=0 ; j<3 ; j++) - { - pbasevert = ptri[i].verts[j]; - - triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); - triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); - } - } - - DrawLine(triangle_st[i][0][0], triangle_st[i][0][1], - triangle_st[i][1][0], triangle_st[i][1][1]); - DrawLine(triangle_st[i][1][0], triangle_st[i][1][1], - triangle_st[i][2][0], triangle_st[i][2][1]); - DrawLine(triangle_st[i][2][0], triangle_st[i][2][1], - triangle_st[i][0][0], triangle_st[i][0][1]); - } - -// make the width a multiple of 4; some hardware requires this, and it ensures -// dword alignment for each scan - - swidth = iwidth*2; - model.skinwidth = (swidth + 3) & ~3; - model.skinheight = iheight; -} - - -static void ReplaceClusterIndex(int newIndex, int oldindex, int **clusters, - IntListNode_t **vertLists, int *num_verts, int *new_num_verts) -{ - int i, j; - IntListNode_t *next; - - for(j = 0; j < num_verts[0]; ++j) - { - for(i = 0; i < num_verts[j+1]; ++i) - { - if(clusters[j][i] == oldindex) - { - ++new_num_verts[j+1]; - - next = vertLists[j]; - - vertLists[j] = (IntListNode_t *) SafeMalloc(sizeof(IntListNode_t), "ReplaceClusterIndex"); - // Currently freed in WriteJointedModelFile only - - vertLists[j]->data = newIndex; - vertLists[j]->next = next; - } - } - } -} - -/* -================= -Cmd_Base -================= -*/ -void Cmd_Base (void) -{ - vec3_t base_xyz[MAX_VERTS]; - triangle_t *ptri; - int i, j, k; -#if 1 -#else - int time1; -#endif - char file1[1024]; - char file2[1024]; - - GetScriptToken (false); - - if (g_skipmodel || g_release || g_archive) - return; - - printf ("---------------------\n"); -#if 1 - sprintf (file1, "%s/%s", cdpartial, token); - printf ("%s ", file1); - - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s", cddir, token); -#else - sprintf (file1, "%s/%s.%s", cdarchive, token, trifileext); - printf ("%s\n", file1); - - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s.%s", cddir, token, trifileext); - - time1 = FileTime (file1); - if (time1 == -1) - Error ("%s doesn't exist", file1); -#endif -// -// load the base triangles -// - if (do3ds) - Load3DSTriangleList (file1, &ptri, &model.num_tris, NULL, NULL); - else - LoadTriangleList (file1, &ptri, &model.num_tris, NULL, NULL); - - - GetScriptToken (false); - sprintf (file2, "%s/%s.pcx", cddir, token); -// sprintf (trans_file, "%s/!%s_a.pcx", cddir, token); - - printf ("skin: %s\n", file2); - Load256Image (file2, &BasePixels, &BasePalette, &BaseWidth, &BaseHeight); - - if (BaseWidth != SKINPAGE_WIDTH || BaseHeight != SKINPAGE_HEIGHT) - { - if (g_allow_newskin) - { - ScaleWidth = BaseWidth; - ScaleHeight = BaseHeight; - } - else - { - Error("Invalid skin page size: (%d,%d) should be (%d,%d)", - BaseWidth,BaseHeight,SKINPAGE_WIDTH,SKINPAGE_HEIGHT); - } - } - else - { - ScaleWidth = (float)ExtractNumber(BasePixels, ENCODED_WIDTH_X, - ENCODED_WIDTH_Y); - ScaleHeight = (float)ExtractNumber(BasePixels, ENCODED_HEIGHT_X, - ENCODED_HEIGHT_Y); - } - -// -// get the ST values -// - BuildST (ptri, model.num_tris,false); - -// -// run through all the base triangles, storing each unique vertex in the -// base vertex list and setting the indirect triangles to point to the base -// vertices -// - for (i=0 ; i= '0' && *s <= '9') - s--; - - strcpy (suffix, s+1); - strcpy (base, frame); - base[s-frame+1] = 0; - - sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "hrc"); - time1 = FileTime (file1); - if (time1 != -1) - { - sprintf (retname, "%s%s.%s", base, suffix, "hrc"); - return retname; - } - - sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "asc"); - time1 = FileTime (file1); - if (time1 != -1) - { - sprintf (retname, "%s%s.%s", base, suffix, "asc"); - return retname; - } - - sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "tri"); - time1 = FileTime (file1); - if (time1 != -1) - { - sprintf (retname, "%s%s.%s", base, suffix, "tri"); - return retname; - } - - sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "3ds"); - time1 = FileTime (file1); - if (time1 != -1) - { - sprintf (retname, "%s%s.%s", base, suffix, "3ds"); - return retname; - } - - sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "htr"); - time1 = FileTime (file1); - if (time1 != -1) - { - sprintf (retname, "%s%s.%s", base, suffix, "htr"); - return retname; - } - - // check for 'run.1' - sprintf (file1, "%s/%s.%s",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; -} - -/* -=============== -GrabFrame -=============== -*/ -static void GrabFrame (char *frame) -{ - triangle_t *ptri; - int i, j; - trivert_t *ptrivert; - int num_tris; - char file1[1024]; - frame_t *fr; - vertexnormals_t vnorms[MAX_VERTS]; - int index_xyz; - char *framefile; - - // the frame 'run1' will be looked for as either - // run.1 or run1.tri, so the new alias sequence save - // feature an be used - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - - printf ("grabbing %s ", file1); - - if (model.num_frames >= MAX_FRAMES) - Error ("model.num_frames >= MAX_FRAMES"); - fr = &g_frames[model.num_frames]; - model.num_frames++; - - strcpy (fr->name, frame); - -// -// load the frame -// - if (do3ds) - Load3DSTriangleList (file1, &ptri, &num_tris, NULL, NULL); - else - LoadTriangleList (file1, &ptri, &num_tris, NULL, NULL); - - if (num_tris != model.num_tris) - Error ("%s: number of triangles doesn't match base frame\n", file1); - -// -// allocate storage for the frame's vertices -// - ptrivert = fr->v; - - for (i=0 ; imins, fr->maxs); - -// -// 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 ; imins, fr->maxs); - - VectorAdd (vnorms[index_xyz].normalsum, normal, vnorms[index_xyz].normalsum); - vnorms[index_xyz].numnormals++; - } - } - -// -// calculate the vertex normals, match them to the template list, and store the -// index of the best match -// - for (i=0 ; i maxdot) - { - maxdot = dot; - maxdotindex = j; - } - } - - ptrivert[i].lightnormalindex = maxdotindex; - } - - free (ptri); -} - -/* -=============== -GrabJointedFrame -=============== -*/ -void GrabJointedFrame(char *frame) -{ - char file1[1024]; - char *framefile; - frame_t *fr; - - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - - printf ("grabbing %s\n", file1); - - fr = &g_frames[model.num_frames - 1]; // last frame read in - - LoadJointList(file1, fr->joints, jointed); -} - -/* -=============== -GrabGlobals -=============== -*/ -void GrabGlobals(char *frame) -{ - char file1[1024]; - char *framefile; - frame_t *fr; - - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - - printf ("grabbing %s\n", file1); - - fr = &g_frames[model.num_frames - 1]; // last frame read in - - LoadGlobals(file1); -} - -/* -=============== -Cmd_Frame -=============== -*/ -void Cmd_Frame (void) -{ - while (ScriptTokenAvailable()) - { - GetScriptToken (false); - if (g_skipmodel) - continue; - if (g_release || g_archive) - { - model.num_frames = 1; // don't skip the writeout - continue; - } - - H_printf("#define FRAME_%-16s\t%i\n", token, model.num_frames); - - GrabFrame (token); - } -} - -/* -=============== -Cmd_Skin - -Skins aren't actually stored in the file, only a reference -is saved out to the header file. -=============== -*/ -void Cmd_Skin (void) -{ - byte *palette; - byte *pixels; - int width, height; - byte *cropped; - int y; - char name[1024], savename[1024]; - - GetScriptToken (false); - - if (model.num_skins == MAX_MD2SKINS) - Error ("model.num_skins == MAX_MD2SKINS"); - - if (g_skipmodel) - return; - -#if 1 - sprintf (name, "%s/%s.pcx", cddir, token); - sprintf (savename, "%s/!%s.pcx", g_outputDir, token); - sprintf (g_skins[model.num_skins], "%s/!%s.pcx", cdpartial, token); -#else - sprintf (name, "%s/%s.lbm", cdarchive, token); - strcpy (name, ExpandPathAndArchive( name ) ); -// sprintf (name, "%s/%s.lbm", cddir, token); - - if (ScriptTokenAvailable()) - { - GetScriptToken (false); - sprintf (g_skins[model.num_skins], "%s.pcx", token); - sprintf (savename, "%s%s.pcx", g_outputDir, g_skins[model.num_skins]); - } - else - { - sprintf (savename, "%s/%s.pcx", g_outputDir, token); - sprintf (g_skins[model.num_skins], "%s/%s.pcx", cdpartial, token); - } -#endif - - model.num_skins++; - - if (g_skipmodel || g_release || g_archive) - return; - - // load the image - printf ("loading %s\n", name); - Load256Image (name, &pixels, &palette, &width, &height); -// RemapZero (pixels, palette, width, height); - - // crop it to the proper size - cropped = (byte *) SafeMalloc (model.skinwidth*model.skinheight, "Cmd_Skin"); - for (y=0 ; y= longimagewidth || xh > longimagewidth || - yl >= longimageheight || yh > longimageheight) - { - Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,longimagewidth,longimageheight); - } - - sourcel = longimage + (yl*longimagewidth) + xl; - destl = bufferl; - linedelta = (longimagewidth - w); - - for (y=yl ; yflags |= LittleLong(flags); - qtex32->contents = contents; - qtex32->value = value; - qtex32->scale_x = scale_x; - qtex32->scale_y = scale_y; - sprintf (qtex32->name, "%s/%s", pic_prefix, lumpname); - if (animname[0]) - sprintf (qtex32->animname, "%s/%s", pic_prefix, animname); - - // - // write it out - // - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex32, size); - - free (qtex32); - } - else - { - sprintf (filename, "%spics/%s/%s.m8", g_outputDir, pic_prefix, lumpname); - if (g_release) - return; // textures are only released by $maps - - xh = xl+w; - yh = yl+h; - - if (xl >= byteimagewidth || xh > byteimagewidth || - yl >= byteimageheight || yh > byteimageheight) - { - Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); - } - - source = byteimage + yl*byteimagewidth + xl; - dest = buffer; - linedelta = byteimagewidth - w; - - for (y=yl ; yflags = flags; - qtex->contents = contents; - qtex->value = value; - sprintf (qtex->name, "%s/%s", pic_prefix, lumpname); - if (animname[0]) - sprintf (qtex->animname, "%s/%s", pic_prefix, animname); - - // - // write it out - // - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex, size); - - free (qtex); - } -} - - -/* -=============== -Cmd_picdir -=============== -*/ -void Cmd_Picdir (void) -{ - char filename[1024]; - - GetScriptToken (false); - strcpy (pic_prefix, token); - // create the directory if needed - sprintf (filename, "%sPics", g_outputDir); - Q_mkdir (filename); - sprintf (filename, "%sPics/%s", g_outputDir, pic_prefix); - Q_mkdir (filename); -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/angles.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/angles.h deleted file mode 100644 index 1a722dab..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/angles.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// Angles in radians - -#define ANGLE_0 0.0F -#define ANGLE_1 0.017453292F -#define ANGLE_5 0.087266462F -#define ANGLE_10 0.174532925F -#define ANGLE_15 0.261799387F -#define ANGLE_20 0.392699081F -#define ANGLE_30 0.523598775F -#define ANGLE_45 0.785398163F -#define ANGLE_60 1.047197551F -#define ANGLE_72 1.256637061F -#define ANGLE_90 1.570796327F -#define ANGLE_120 2.094395102F -#define ANGLE_135 2.35619449F -#define ANGLE_144 2.513274123F -#define ANGLE_180 3.141592653F -#define ANGLE_225 3.926990817F -#define ANGLE_270 4.71238898F -#define ANGLE_315 5.497787144F -#define ANGLE_360 6.283185307F - -// Angles in degrees - -#define DEGREE_0 0.0F -#define DEGREE_180 180.0F -#define DEGREE_45 (DEGREE_180 / 4.0F) -#define DEGREE_90 (DEGREE_180 / 2.0F) -#define DEGREE_135 (DEGREE_90 + DEGREE_45) -#define DEGREE_270 (DEGREE_180 + DEGREE_90) -#define DEGREE_360 (DEGREE_180 * 2.0F) - -#define DEGREE_225 (DEGREE_180 + DEGREE_45) -#define DEGREE_315 (DEGREE_270 + DEGREE_45) - -#define DEGREE_30 (DEGREE_180 / 6.0F) -#define DEGREE_60 (DEGREE_180 / 3.0F) -#define DEGREE_120 (DEGREE_360 / 3.0F) - -#define DEGREE_1 (DEGREE_180 / 180.0F) -#define DEGREE_5 (DEGREE_180 / 36.0F) -#define DEGREE_10 (DEGREE_180 / 18.0F) -#define DEGREE_15 (DEGREE_180 / 12.0F) -#define DEGREE_20 (DEGREE_180 / 8.0F) - -// Conversion routines - -#define ANGLE_TO_RAD ANGLE_1 -#define RAD_TO_ANGLE (180.0F / ANGLE_180) - -#define SHORT_TO_ANGLE (360.0/65536) - - -#pragma warning(disable : 4305) // 'initializing' : truncation from 'const double ' to 'float ' - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/arrayedlist.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/arrayedlist.h deleted file mode 100644 index c04d669f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/arrayedlist.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright (C) 1999-2006 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 _ARRAYEDLIST_H -#define _ARRAYEDLIST_H - -#include - -typedef struct ArrayedListNode_s -{ - int data; - int next; - int inUse; -} ArrayedListNode_t; - -#define ARRAYEDLISTNODE_NULL -1 - -static -#ifdef _WIN32 - _inline -#else - inline -#endif - int GetFreeNode(ArrayedListNode_t *nodeArray, int max) -{ - int i; - - for(i = 0; i < max; ++i) - { - if(!nodeArray[i].inUse) - { - nodeArray[i].inUse = 1; - return i; - } - } - - assert(0); - return -1; -} - -static -#ifdef _WIN32 - _inline -#else - inline -#endif -void FreeNode(ArrayedListNode_t *nodeArray, int index) -{ - nodeArray[index].inUse = 0; -} - -#endif //_ARRAYEDLIST_H - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/flex.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/flex.h deleted file mode 100644 index 0b231cbf..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/flex.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// Generic flexible format - -typedef struct -{ - char ident[32]; - int version; - int size; -} header_t; - -void WriteHeader(FILE *, char *, int, int, void *); - -// end diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/fmodel.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/fmodel.h deleted file mode 100644 index ee198fff..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/fmodel.h +++ /dev/null @@ -1,202 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - - -/* -======================================================================== - -.FM triangle flexible model file format - -======================================================================== -*/ - -#ifndef __FMODEL_HEADER -#define __FMODEL_HEADER - -#include "bspfile.h" - -//typedef unsigned char byte; -//typedef int qboolean; -//typedef float vec3_t[3]; - -#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 // also defined in game/qshared.h - - -#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) - -extern byte *BasePalette; -extern byte *BasePixels,*TransPixels; -extern int BaseWidth, BaseHeight, TransWidth, TransHeight; -extern int ScaleWidth, ScaleHeight; - -int ExtractNumber(byte *pic, int x, int y); -void DrawTextChar(int x, int y, char *text); -void DrawLine(int x1, int y1, int x2, int y2); - -// the glcmd format: -// a positive integer starts a tristrip command, followed by that many -// vertex structures. -// a negative integer starts a trifan command, followed by -x vertexes -// a zero indicates the end of the command list. -// a vertex consists of a floating point s, a floating point t, -// and an integer vertex index. - - -// Initial Header -#define FM_HEADER_NAME "header" -#define FM_HEADER_VER 2 - -typedef struct -{ - int skinwidth; - int skinheight; - int framesize; // byte size of each frame - - int num_skins; - int num_xyz; - int num_st; // greater than num_xyz for seams - int num_tris; - int num_glcmds; // dwords in strip/fan command list - int num_frames; - int num_mesh_nodes; -} fmheader_t; - - -// Skin Header -#define FM_SKIN_NAME "skin" -#define FM_SKIN_VER 1 - - -// ST Coord Header -#define FM_ST_NAME "st coord" -#define FM_ST_VER 1 - -typedef struct -{ - short s; - short t; -} fmstvert_t; - - -// Tri Header -#define FM_TRI_NAME "tris" -#define FM_TRI_VER 1 - -typedef struct -{ - short index_xyz[3]; - short index_st[3]; -} fmtriangle_t; - - -// Frame Header -#define FM_FRAME_NAME "frames" -#define FM_FRAME_VER 1 - -// Frame for compression, just the names -#define FM_SHORT_FRAME_NAME "short frames" -#define FM_SHORT_FRAME_VER 1 - -// Normals for compressed frames -#define FM_NORMAL_NAME "normals" -#define FM_NORMAL_VER 1 - -// Compressed Frame Data -#define FM_COMP_NAME "comp data" -#define FM_COMP_VER 1 - -// GL Cmds Header -#define FM_GLCMDS_NAME "glcmds" -#define FM_GLCMDS_VER 1 - - -// Mesh Nodes Header -#define FM_MESH_NAME "mesh nodes" -#define FM_MESH_VER 3 - -// Skeleton Header -#define FM_SKELETON_NAME "skeleton" -#define FM_SKELETON_VER 1 - -// References Header -#define FM_REFERENCES_NAME "references" -#define FM_REFERENCES_VER 1 - -typedef struct -{ - - union - { - - byte tris[MAX_FM_TRIANGLES>>3]; - - struct { - short *triIndicies; - int num_tris; - }; - - }; - - byte verts[MAX_FM_VERTS>>3]; - short start_glcmds, num_glcmds; -} fmmeshnode_t; - -//================================================================= - -// Frame info -typedef struct -{ - byte v[3]; // scaled byte to fit in frame mins/maxs - byte lightnormalindex; -} fmtrivertx_t; - -typedef struct -{ - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name from grabbing - fmtrivertx_t verts[1]; // variable sized -} fmaliasframe_t; - - -#endif // #define __FMODEL_HEADER diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/h2common.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/h2common.h deleted file mode 100644 index a7f6587d..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/h2common.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright (C) 1999-2006 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 H2COMMON_H -#define H2COMMON_H - #define H2COMMON_API -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/placement.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/placement.h deleted file mode 100644 index 4db2c55b..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/placement.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright (C) 1999-2006 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 PLACEMENT_H -#define PLACEMENT_H - -#include "q_typedef.h" - -//typedef float vec3_t[3]; - -typedef struct Placement_s -{ - vec3_t origin; - vec3_t direction; - vec3_t up; -} Placement_t; - -#endif - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/q_typedef.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/q_typedef.h deleted file mode 100644 index 02f9a459..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/q_typedef.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -Copyright (C) 1999-2006 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_TYPEDEF_H -#define Q_TYPEDEF_H - -typedef float vec_t; -typedef vec_t vec2_t[2]; -typedef vec_t vec3_t[3]; -typedef double vec3d_t[3]; -typedef vec_t vec5_t[5]; - -typedef float matrix3_t[3][3]; -typedef float matrix3d_t[3][3]; - -typedef int fixed4_t; -typedef int fixed8_t; -typedef int fixed16_t; - -typedef unsigned char byte; - -#ifndef __cplusplus -typedef enum {false, true} qboolean; -#else -typedef int qboolean; -#endif - -typedef struct edict_s edict_t; - -typedef struct paletteRGBA_s -{ - union - { - struct - { - byte r,g,b,a; - }; - unsigned c; - byte c_array[4]; - }; -} paletteRGBA_t; - -#endif - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/qfiles.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/qfiles.h deleted file mode 100644 index d71eaf2b..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/qfiles.h +++ /dev/null @@ -1,604 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - - -// -// qfiles.h: quake file formats -// This file must be identical in the quake and utils directories -// - -/* -======================================================================== - -The .pak files are just a linear collapse of a directory tree - -======================================================================== -*/ - -#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P') - -typedef struct -{ - char name[56]; - int filepos, filelen; -} dpackfile_t; - -typedef struct -{ - int ident; // == IDPAKHEADER - int dirofs; - int dirlen; -} dpackheader_t; - -#define MAX_FILES_IN_PACK 6144 - - -/* -======================================================================== - -PCX files are used for as many images as possible - -======================================================================== -*/ - -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; - -/* -======================================================================== - -.MD2 compressed triangle model file format - -======================================================================== -*/ -#define IDCOMPRESSEDALIASHEADER (('2'<<24)+('C'<<16)+('D'<<8)+'I') - -/* -======================================================================== - -.MD2 compressed triangle model file format - -======================================================================== -*/ -#define IDJOINTEDALIASHEADER (('2'<<24)+('J'<<16)+('D'<<8)+'I') - -/* -======================================================================== - -.MD2 triangle model file format - -======================================================================== -*/ - -#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I') -#define ALIAS_VERSION 8 - -#define MAX_TRIANGLES 4096 -#define MAX_VERTS 2048 -#define MAX_FRAMES 512 -#define MAX_MD2SKINS 64 -#define MAX_SKINNAME 64 - -typedef struct -{ - short s; - short t; -} dstvert_t; - -typedef struct -{ - short index_xyz[3]; - short index_st[3]; -} dtriangle_t; - -typedef struct -{ - union - { - struct - { - byte v[3]; // scaled byte to fit in frame mins/maxs - byte lightnormalindex; - }; - - int vert; - }; -} dtrivertx_t; - -#define DTRIVERTX_V0 0 -#define DTRIVERTX_V1 1 -#define DTRIVERTX_V2 2 -#define DTRIVERTX_LNI 3 -#define DTRIVERTX_SIZE 4 - -typedef struct -{ - float scale[3]; // multiply byte verts by this - float translate[3]; // then add this - char name[16]; // frame name from grabbing - dtrivertx_t verts[1]; // variable sized -} daliasframe_t; - - -// the glcmd format: -// a positive integer starts a tristrip command, followed by that many -// vertex structures. -// a negative integer starts a trifan command, followed by -x vertexes -// a zero indicates the end of the command list. -// a vertex consists of a floating point s, a floating point t, -// and an integer vertex index. - - -typedef struct -{ - int ident; - int version; - - int skinwidth; - int skinheight; - int framesize; // byte size of each frame - - int num_skins; - int num_xyz; - int num_st; // greater than num_xyz for seams - int num_tris; - int num_glcmds; // dwords in strip/fan command list - int num_frames; - - int ofs_skins; // each skin is a MAX_SKINNAME string - int ofs_st; // byte offset from start for stverts - int ofs_tris; // offset for dtriangles - int ofs_frames; // offset for first frame - int ofs_glcmds; - int ofs_end; // end of file - -} dmdl_t; - -// compressed model -typedef struct dcompmdl_s -{ - dmdl_t header; - short CompressedFrameSize; - short UniqueVerts; - short *remap; - float *translate; // then add this - float *scale; // multiply byte verts by this - char *mat; - char *frames; - char *base; - float *ctranslate; - float *cscale; - char data[1]; -} dcompmdl_t; - -typedef struct -{ - dcompmdl_t compModInfo; - int rootCluster; - int skeletalType; - struct ModelSkeleton_s *skeletons; -} JointedModel_t; - -/* -======================================================================== - -.BK file format - -======================================================================== -*/ - -#define IDBOOKHEADER (('K'<<24)+('O'<<16)+('O'<<8)+'B') -#define BOOK_VERSION 2 - -typedef struct bookframe_s -{ - int x; - int y; - int w; - int h; - char name[MAX_SKINNAME]; // name of gfx file -} bookframe_t; - -typedef struct bookheader_s -{ - unsigned int ident; - unsigned int version; - int num_segments; - int total_w; - int total_h; -} bookheader_t; - -typedef struct book_s -{ - bookheader_t bheader; - bookframe_t bframes[MAX_MD2SKINS]; -} book_t; - -/* -======================================================================== - -.SP2 sprite file format - -======================================================================== -*/ - -#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I') - // little-endian "IDS2" -#define SPRITE_VERSION 2 - -typedef struct -{ - int width, height; - int origin_x, origin_y; // raster coordinates inside pic - char name[MAX_SKINNAME]; // name of pcx file -} dsprframe_t; - -typedef struct { - int ident; - int version; - int numframes; - dsprframe_t frames[1]; // variable sized -} dsprite_t; - -/* -============================================================================== - - .M8 texture file format - -============================================================================== -*/ - -typedef struct palette_s -{ - union - { - struct - { - byte r,g,b; - }; - }; -} palette_t; - -#define MIP_VERSION 2 -#define PAL_SIZE 256 -#define MIPLEVELS 16 - -typedef struct miptex_s -{ - int version; - char name[32]; - unsigned width[MIPLEVELS], height[MIPLEVELS]; - unsigned offsets[MIPLEVELS]; // four mip maps stored - char animname[32]; // next frame in animation chain - palette_t palette[PAL_SIZE]; - int flags; - int contents; - int value; -} miptex_t; - - - -#define MIP32_VERSION 4 - -typedef struct miptex32_s -{ - int version; - char name[128]; - char altname[128]; // texture substitution - char animname[128]; // next frame in animation chain - char damagename[128]; // image that should be shown when damaged - unsigned width[MIPLEVELS], height[MIPLEVELS]; - unsigned offsets[MIPLEVELS]; - int flags; - int contents; - int value; - float scale_x, scale_y; - int mip_scale; - - // detail texturing info - char dt_name[128]; // detailed texture name - float dt_scale_x, dt_scale_y; - float dt_u, dt_v; - float dt_alpha; - int dt_src_blend_mode, dt_dst_blend_mode; - - int unused[20]; // future expansion to maintain compatibility with h2 -} miptex32_t; - - -/* -============================================================================== - - .BSP file format - -============================================================================== -*/ - -#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') - // little-endian "IBSP" - -#define BSPVERSION 38 - - -// upper design bounds -// leaffaces, leafbrushes, planes, and verts are still bounded by -// 16 bit short limits -#define MAX_MAP_MODELS 1024 -//#define MAX_MAP_BRUSHES 8192 // Quake 2 original -#define MAX_MAP_BRUSHES 10240 -#define MAX_MAP_ENTITIES 2048 -#define MAX_MAP_ENTSTRING 0x40000 -#define MAX_MAP_TEXINFO 8192 - -#define MAX_MAP_AREAS 256 -#define MAX_MAP_AREAPORTALS 1024 -#define MAX_MAP_PLANES 65536 -#define MAX_MAP_NODES 65536 -#define MAX_MAP_BRUSHSIDES 65536 -#define MAX_MAP_LEAFS 65536 -#define MAX_MAP_VERTS 65536 -#define MAX_MAP_FACES 65536 -#define MAX_MAP_LEAFFACES 65536 -#define MAX_MAP_LEAFBRUSHES 65536 -#define MAX_MAP_PORTALS 65536 -#define MAX_MAP_EDGES 128000 -#define MAX_MAP_SURFEDGES 256000 -#define MAX_MAP_LIGHTING 0x200000 -#define MAX_MAP_VISIBILITY 0x180000 - -// key / value pair sizes - -#define MAX_KEY 32 -#define MAX_VALUE 1024 - -//============================================================================= - -typedef struct -{ - int fileofs, filelen; -} lump_t; - -#define LUMP_ENTITIES 0 -#define LUMP_PLANES 1 -#define LUMP_VERTEXES 2 -#define LUMP_VISIBILITY 3 -#define LUMP_NODES 4 -#define LUMP_TEXINFO 5 -#define LUMP_FACES 6 -#define LUMP_LIGHTING 7 -#define LUMP_LEAFS 8 -#define LUMP_LEAFFACES 9 -#define LUMP_LEAFBRUSHES 10 -#define LUMP_EDGES 11 -#define LUMP_SURFEDGES 12 -#define LUMP_MODELS 13 -#define LUMP_BRUSHES 14 -#define LUMP_BRUSHSIDES 15 -#define LUMP_POP 16 -#define LUMP_AREAS 17 -#define LUMP_AREAPORTALS 18 -#define HEADER_LUMPS 19 - -typedef struct -{ - int ident; - int version; - lump_t lumps[HEADER_LUMPS]; -} dheader_t; - -typedef struct -{ - float mins[3], maxs[3]; - float origin[3]; // for sounds or lights - int headnode; - int firstface, numfaces; // submodels just draw faces - // without walking the bsp tree -} dmodel_t; - - -typedef struct -{ - float point[3]; -} dvertex_t; - - -// 0-2 are axial planes -#define PLANE_X 0 -#define PLANE_Y 1 -#define PLANE_Z 2 - -// 3-5 are non-axial planes snapped to the nearest -#define PLANE_ANYX 3 -#define PLANE_ANYY 4 -#define PLANE_ANYZ 5 - -// planes (x&~1) and (x&~1)+1 are allways opposites - -typedef struct -{ - float normal[3]; - float dist; - int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate -} dplane_t; - - -// contents flags are seperate bits -// a given brush can contribute multiple content bits -// multiple brushes can be in a single leaf - -// These definitions also need to be in q_shared.h! - -// ************************************************************************************************ -// CONTENTS_XXX -// ------------ -// Contents flags. -// ************************************************************************************************ - -// Lower bits are stronger, and will eat weaker brushes completely. - -#define CONTENTS_SOLID 0x00000001 // An eye is never valid in a solid. -#define CONTENTS_WINDOW 0x00000002 // Translucent, but not watery. -#define CONTENTS_AUX 0x00000004 -#define CONTENTS_LAVA 0x00000008 -#define CONTENTS_SLIME 0x00000010 -#define CONTENTS_WATER 0x00000020 -#define CONTENTS_MIST 0x00000040 -#define LAST_VISIBLE_CONTENTS CONTENTS_MIST - -// Remaining contents are non-visible, and don't eat brushes. - -#define CONTENTS_AREAPORTAL 0x00008000 -#define CONTENTS_PLAYERCLIP 0x00010000 -#define CONTENTS_MONSTERCLIP 0x00020000 - -// Currents can be added to any other contents, and may be mixed. - -#define CONTENTS_CURRENT_0 0x00040000 -#define CONTENTS_CURRENT_90 0x00080000 -#define CONTENTS_CURRENT_180 0x00100000 -#define CONTENTS_CURRENT_270 0x00200000 -#define CONTENTS_CURRENT_UP 0x00400000 -#define CONTENTS_CURRENT_DOWN 0x00800000 -#define CONTENTS_ORIGIN 0x01000000 // Removed before bsping an entity. -#define CONTENTS_MONSTER 0x02000000 // Should never be on a brush, only in game. -#define CONTENTS_DEADMONSTER 0x04000000 -#define CONTENTS_DETAIL 0x08000000 // Brushes to be added after vis leaves. -#define CONTENTS_TRANSLUCENT 0x10000000 // Auto set if any surface has transparency. -#define CONTENTS_LADDER 0x20000000 -#define CONTENTS_CAMERANOBLOCK 0x40000000 // Camera LOS ignores any brushes with this flag. - -typedef struct -{ - int planenum; - int children[2]; // negative numbers are -(leafs+1), not nodes - short mins[3]; // for frustom culling - short maxs[3]; - unsigned short firstface; - unsigned short numfaces; // counting both sides -} dnode_t; - - -typedef struct texinfo_s -{ - float vecs[2][4]; // [s/t][xyz offset] - int flags; // miptex flags + overrides - int value; // light emission, etc - char texture[32]; // texture name (textures/*.wal) - int nexttexinfo; // for animations, -1 = end of chain -} texinfo_t; - - -// note that edge 0 is never used, because negative edge nums are used for -// counterclockwise use of the edge in a face -typedef struct -{ - unsigned short v[2]; // vertex numbers -} dedge_t; - -#define MAXLIGHTMAPS 4 -typedef struct -{ - unsigned short planenum; - short side; - - int firstedge; // we must support > 64k edges - short numedges; - short texinfo; - -// lighting info - byte styles[MAXLIGHTMAPS]; - int lightofs; // start of [numstyles*surfsize] samples -} dface_t; - -typedef struct -{ - int contents; // OR of all brushes (not needed?) - - short cluster; - short area; - - short mins[3]; // for frustum culling - short maxs[3]; - - unsigned short firstleafface; - unsigned short numleaffaces; - - unsigned short firstleafbrush; - unsigned short numleafbrushes; -} dleaf_t; - -typedef struct -{ - unsigned short planenum; // facing out of the leaf - short texinfo; -} dbrushside_t; - -typedef struct -{ - int firstside; - int numsides; - int contents; -} dbrush_t; - -#define ANGLE_UP -1 -#define ANGLE_DOWN -2 - - -// the visibility lump consists of a header with a count, then -// byte offsets for the PVS and PHS of each cluster, then the raw -// compressed bit vectors -#define DVIS_PVS 0 -#define DVIS_PHS 1 -typedef struct -{ - int numclusters; - int bitofs[8][2]; // bitofs[numclusters][2] -} dvis_t; - -// each area has a list of portals that lead into other areas -// when portals are closed, other areas may not be visible or -// hearable even if the vis info says that it should be -typedef struct -{ - int portalnum; - int otherarea; -} dareaportal_t; - -typedef struct -{ - int numareaportals; - int firstareaportal; -} darea_t; - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.c deleted file mode 100644 index ddad0fe4..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.c +++ /dev/null @@ -1,124 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "reference.h" -#include "arrayedlist.h" -#include "resourcemanager.h" -#include "skeletons.h" - -char *referenceRootNames[] = -{ - "elf_Lhandroot",//0 - "elf_Rhandroot", - "elf_Rfootroot", - "elf_Lfootroot", - "elf_Bstaffroot", - "elf_bladeroot", - "elf_hellroot", - "StaffBone",//7 - "SwordBone", - "SpearBone", - "RFootBone", - "LFootBone", - "hp_backroot",//12 - "hp_staffroot", - "hp_lhandroot", - "hp_rhandroot", - "hp_rfootroot", - "hp_lfootroot", - "staffroot",//18 - "rfootroot", - "lfootroot", - "rhandroot", - "lhandroot", - "leyeroot", - "reyeroot" -}; - -int referenceRootNameOffsets[NUM_REFERENCED] = -{ - 0, // CORVUS - 7, // INSECT - 12, // HIGH PRIESTESS - 18, // MORCALAVIN -}; - -int numReferences[NUM_REFERENCED] = -{ - NUM_REFERENCES_CORVUS, - NUM_REFERENCES_INSECT, - NUM_REFERENCES_PRIESTESS, - NUM_REFERENCES_MORK, -}; - -int corvusJointIDs[NUM_REFERENCES_CORVUS] = -{ - CORVUS_UPPERBACK, - CORVUS_UPPERBACK, - -1, - -1, - CORVUS_UPPERBACK, - CORVUS_UPPERBACK, - CORVUS_UPPERBACK, -}; - -int *jointIDs[NUM_REFERENCED] = -{ - corvusJointIDs, -}; - -static ResourceManager_t ReferenceMngr; - -void InitReferenceMngr() -{ -#define REFERENCE_BLOCK_SIZE 8 - char *dummystr = NULL; - - ResMngr_Con(&ReferenceMngr, sizeof(LERPedReferences_t), REFERENCE_BLOCK_SIZE, dummystr); -} - -void ReleaseReferenceMngr() -{ - ResMngr_Des(&ReferenceMngr); -} - -LERPedReferences_t *LERPedReferences_new(int init_refType) -{ - LERPedReferences_t *newRefs; - - newRefs = ResMngr_AllocateResource(&ReferenceMngr, sizeof(*newRefs)); - newRefs->refType = init_refType; - newRefs->jointIDs = jointIDs[init_refType]; - newRefs->lastUpdate = -(REF_MINCULLTIME*2.0); - - memset(newRefs->references, 0, MAX_REFPOINTS*sizeof(Reference_t)); - memset(newRefs->oldReferences, 0, MAX_REFPOINTS*sizeof(Reference_t)); - - return newRefs; -} - -void LERPedReferences_delete(LERPedReferences_t *toDelete) -{ - ResMngr_DeallocateResource(&ReferenceMngr, toDelete, sizeof(*toDelete)); -} - -// end diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.h deleted file mode 100644 index ace3678b..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -Copyright (C) 1999-2006 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 REFERENCE_H -#define REFERENCE_H - -#include "placement.h" - -#define MAX_REFPOINTS 16 -#define REF_MINCULLTIME 1.0 - -typedef struct Reference_s -{ - int activecount; - Placement_t placement; -} Reference_t; - -typedef struct LERPedReferences_s -{ - int refType; - int *jointIDs; - float lastUpdate; - Reference_t references[MAX_REFPOINTS]; - Reference_t oldReferences[MAX_REFPOINTS]; -} LERPedReferences_t; - -// Reference Types -enum { - REF_NULL = -1, - REF_CORVUS,//0 - REF_INSECT,//1 - REF_PRIESTESS,//2 - REF_MORK,//3 - NUM_REFERENCED//4 -}; - -// Corvus Reference Points -enum { - CORVUS_LEFTHAND,//0 - CORVUS_RIGHTHAND, - CORVUS_LEFTFOOT, - CORVUS_RIGHTFOOT, - CORVUS_STAFF, - CORVUS_BLADE, - CORVUS_HELL_HEAD, - NUM_REFERENCES_CORVUS//7 -}; - -// Tchekrik Reference Points -enum { - INSECT_STAFF,//0 - INSECT_SWORD, - INSECT_SPEAR, - INSECT_RIGHTFOOT, - INSECT_LEFTFOOT, - NUM_REFERENCES_INSECT//5 -}; - -// High Priestess Reference Points -enum { - PRIESTESS_BACK,//0 - PRIESTESS_STAFF, - PRIESTESS_LHAND, - PRIESTESS_RHAND, - PRIESTESS_RFOOT, - PRIESTESS_LFOOT, - NUM_REFERENCES_PRIESTESS//6 -}; - -// Morcalavin Reference Points -enum -{ - MORK_STAFFREF,//0 - MORK_RFOOTREF,//1 - MORK_LFOOTREF,//2 - MORK_RHANDREF,//3 - MORK_LHANDREF,//4 - MORK_LEYEREF,//5 - MORK_REYEREF,//6 - NUM_REFERENCES_MORK//7 -}; - -#define CORVUS_LIMBS_MASK ((1 << CORVUS_LEFTHAND) | (1 << CORVUS_RIGHTHAND) | (1 << CORVUS_LEFTFOOT) | (1 << CORVUS_RIGHTFOOT)) -#define CORVUS_WEAPON_MASK ((1 << CORVUS_STAFF) | (1 << CORVUS_BLADE) | (1 << CORVUS_HELL_HEAD)) -#define CORVUS_MASK (CORVUS_LIMBS_MASK | CORVUS_WEAPON_MASK) - -#define INSECT_MASK ((1 << INSECT_STAFF) | (1 << INSECT_SWORD) | (1 << INSECT_SPEAR) | (1 << INSECT_RIGHTFOOT) | (1 << INSECT_LEFTFOOT)) - -#define PRIESTESS_MASK ((1 << PRIESTESS_BACK) | (1 << PRIESTESS_STAFF) | (1 << PRIESTESS_LHAND) | (1 << PRIESTESS_RHAND) | (1 << PRIESTESS_RFOOT) | (1 << PRIESTESS_LFOOT)) - -#define MORK_MASK ((1 << MORK_STAFFREF) | (1 << MORK_RFOOTREF) | (1 << MORK_LFOOTREF) | (1 << MORK_RHANDREF) | (1 << MORK_LHANDREF) | (1 << MORK_LEYEREF) | (1 << MORK_REYEREF)) - -extern char *referenceRootNames[]; -extern int referenceRootNameOffsets[]; -extern int numReferences[]; - -void EnableRefPoints(LERPedReferences_t *refInfo, int mask); -void DisableRefPoints(LERPedReferences_t *refInfo, int mask); - -void InitReferenceMngr(); -void ReleaseReferenceMngr(); - -LERPedReferences_t *LERPedReferences_new(int init_refType); -void LERPedReferences_delete(LERPedReferences_t *toDelete); - -#endif - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.c deleted file mode 100644 index ef5613df..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.c +++ /dev/null @@ -1,159 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - - -// -// ResourceManager.c -// - -#include -#include "resourcemanager.h" -#include - -typedef struct ResMngr_Block_s -{ - char *start; - unsigned int size; - struct ResMngr_Block_s *next; -} ResMngr_Block_t; - -static void ResMngr_CreateBlock(ResourceManager_t *resource) -{ - unsigned int _blockSize; - char *block; - char **current; - ResMngr_Block_t *temp; - unsigned int i; - - _blockSize = resource->nodeSize * resource->resPerBlock; - - block = malloc(_blockSize); - - assert(block); - - temp = malloc(sizeof(*temp)); - - temp->start = block; - temp->size = _blockSize; - temp->next = resource->blockList; - - resource->blockList = temp; - - resource->free = (char **)(block); - - current = resource->free; - - for(i = 1; i < resource->resPerBlock; ++i) - { - // set current->next to point to next node - *current = (char *)(current) + resource->nodeSize; - - // set current node to current->next - current = (char **)(*current); - } - - *current = NULL; -} - -H2COMMON_API void ResMngr_Con(ResourceManager_t *resource, size_t init_resSize, unsigned int init_resPerBlock, char *resman_name) -{ - resource->resSize = init_resSize; - - resource->resPerBlock = init_resPerBlock; - - resource->nodeSize = resource->resSize + sizeof(*resource->free); - - resource->blockList = NULL; - - resource->numResourcesAllocated = 0; - - ResMngr_CreateBlock(resource); -} - -H2COMMON_API void ResMngr_Des(ResourceManager_t *resource) -{ - ResMngr_Block_t *toDelete; - -#if 0 - if (resource->numResourcesAllocated) - { - char mess[100]; - sprintf(mess,"Potential memory leak %d bytes unfreed\n",resource->resSize*resource->numResourcesAllocated); - OutputDebugString(mess); - } -#endif - - while(resource->blockList) - { - toDelete = resource->blockList; - resource->blockList = resource->blockList->next; - free(toDelete->start); - free(toDelete); - } -} - -H2COMMON_API void *ResMngr_AllocateResource(ResourceManager_t *resource, size_t size) -{ - char **toPop; - - assert(size == resource->resSize); - - ++resource->numResourcesAllocated; - - assert(resource->free); // constructor not called; possibly due to a static object - // containing a static ResourceManagerFastLarge member being - // constructed before its own static members - - toPop = resource->free; - - // set unallocated to the next node and check for NULL (end of list) - if(!(resource->free = (char **)(*resource->free))) - { // if at end create new block - ResMngr_CreateBlock(resource); - } - - // set next to NULL - *toPop = NULL; - - // return the resource for the node - return (void *)(toPop + 1); -} - -H2COMMON_API void ResMngr_DeallocateResource(ResourceManager_t *resource, void *toDeallocate, size_t size) -{ - char **toPush; - - assert(size == resource->resSize); - - --resource->numResourcesAllocated; - - toPush = (char **)(toDeallocate) - 1; - - assert(resource->free); // see same assert at top of AllocateResource - - // set toPop->next to current unallocated front - *toPush = (char *)(resource->free); - - // set unallocated to the node removed from allocated - resource->free = toPush; -} - -// end diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.h deleted file mode 100644 index e267ecd5..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// ResourceManager.h -// - -#include "h2common.h" -#include // needed here for size_t - -typedef struct ResourceManager_s -{ - size_t resSize; - unsigned int resPerBlock; - unsigned int nodeSize; - struct ResMngr_Block_s *blockList; - char **free; - char *ResMan_Name; - - unsigned numResourcesAllocated; - -} ResourceManager_t; - -extern H2COMMON_API void ResMngr_Con(ResourceManager_t *resource, size_t init_resSize, unsigned int init_resPerBlock, char *resman_name); -extern H2COMMON_API void ResMngr_Des(ResourceManager_t *resource); -extern H2COMMON_API void *ResMngr_AllocateResource(ResourceManager_t *resource, size_t size); -extern H2COMMON_API void ResMngr_DeallocateResource(ResourceManager_t *resource, void *toDeallocate, size_t size); - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.c deleted file mode 100644 index 1da0b4f1..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.c +++ /dev/null @@ -1,232 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// -// Skeletons.c -// - -#include "skeletons.h" - -char *skeletonRootNames[] = -{ - "RAVEN_ROOT", - "BOX_ROOT", - "BEETLE_ROOT", - "ELFLORD_ROOT", - "PLAGUELF_ROOT", - "ELF_BACKROOT", -}; - -int skeletonRNameOffsets[] = -{ - 0, // RAVEN - 1, // BOX - 2, // BEETLE - 3, // ELFLORD - 4, // PLAGUE ELF - 5, // CORVUS -}; - -char *skeletonJointNames[] = -{ - "RAVEN_LOWERBACK", // 0 - "RAVEN_UPPERBACK", - "RAVEN_NECK", - "BOX_CENTER", // 3 - "BEETLE_NECK", // 4 - "BEETLE_HEAD", - "PLAGUELF_BACKB", // 6 - "PLAGUELF_BACKC", - "PLAGUELF_NECK", - "ELF_BACKB", // 9 - "ELF_BACKC", - "ELF_NECKB", -}; - -int skeletonNameOffsets[] = -{ - 0, // RAVEN - 3, // BOX - 4, // BEETLE - -1, // ELFLORD - 6, // PLAGUE ELF - 9, // CORVUS -}; - -char *skeletonEffectorNames[] = -{ - "BEETLE_EYES", // 0 - "CORVUS_EYES", // 1 -}; - -int skeletonENameOffsets[] = -{ - -1, // RAVEN - -1, // BOX - 0, // BEETLE - -1, // ELFLORD - 1, // PLAGUE ELF -}; - -int numJointsInSkeleton[] = -{ - NUM_JOINTS_RAVEN, - NUM_JOINTS_BOX, - NUM_JOINTS_BEETLE, - NUM_JOINTS_ELFLORD, - NUM_JOINTS_PLAGUE_ELF, - NUM_JOINTS_CORVUS, -}; - -int numNodesInSkeleton[] = -{ - 2, // RAVEN - 0, // BOX - 1, // BEETLE - -1, // ELFLORD - 2, // PLAGUE ELF - 2, // CORVUS -}; - -void CreateRavenSkel(void *g_skeletalJoints, size_t jointSize, struct ArrayedListNode_s *g_jointNodes, int root); -void CreateBoxSkel(void *g_skeletalJoints, size_t jointSize, struct ArrayedListNode_s *g_jointNodes, int root); -void CreateBeetleSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex); -void CreateElfLordSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex); -void CreatePlagueElfSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex); - -CreateSkeleton_t SkeletonCreators[NUM_SKELETONS] = -{ - CreateRavenSkel, - CreateBoxSkel, - CreateBeetleSkel, - CreateElfLordSkel, - CreatePlagueElfSkel, - CreatePlagueElfSkel, // Corvus has the same structure as the Plague Elf -}; - -void CreateRavenSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) -{ - char *root; - int *children; - int nodeIndex; - - root = (char *)g_skeletalJoints + rootIndex * jointSize; - - children = (int *)(root + RAVEN_HEAD * jointSize); - *children = ARRAYEDLISTNODE_NULL; - - nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); - - children = (int *)(root + RAVEN_UPPERBACK * jointSize); - *children = nodeIndex; - - g_jointNodes[nodeIndex].data = rootIndex + RAVEN_HEAD; - g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; - - nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); - - children = (int *)(root + RAVEN_LOWERBACK * jointSize); - *children = nodeIndex; - - g_jointNodes[nodeIndex].data = rootIndex + RAVEN_UPPERBACK; - g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; -} - -void CreateBoxSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) -{ - char *root; - int *children; - - root = (char *)g_skeletalJoints + rootIndex * jointSize; - - children = (int *)(root + RAVEN_HEAD * jointSize); - *children = ARRAYEDLISTNODE_NULL; -} - -void CreateBeetleSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) -{ - char *root; - int *children; - int nodeIndex; - - root = (char *)g_skeletalJoints + rootIndex * jointSize; - - children = (int *)(root + BEETLE_HEAD * jointSize); - *children = ARRAYEDLISTNODE_NULL; - - nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); - - children = (int *)(root + BEETLE_NECK * jointSize); - *children = nodeIndex; - - g_jointNodes[nodeIndex].data = rootIndex + BEETLE_HEAD; - g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; -} - -void CreateElfLordSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) -{ - char *root; - int *children; - int nodeIndex; - - root = (char *)g_skeletalJoints + rootIndex * jointSize; - - children = (int *)(root + BEETLE_HEAD * jointSize); - *children = ARRAYEDLISTNODE_NULL; - - nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); - - children = (int *)(root + BEETLE_NECK * jointSize); - *children = nodeIndex; - - g_jointNodes[nodeIndex].data = rootIndex + BEETLE_HEAD; - g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; -} - -void CreatePlagueElfSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) -{ - char *root; - int *children; - int nodeIndex; - - root = (char *)g_skeletalJoints + rootIndex * jointSize; - - children = (int *)(root + PLAGUE_ELF_HEAD * jointSize); - *children = ARRAYEDLISTNODE_NULL; - - nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); - - children = (int *)(root + PLAGUE_ELF_UPPERBACK * jointSize); - *children = nodeIndex; - - g_jointNodes[nodeIndex].data = rootIndex + PLAGUE_ELF_HEAD; - g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; - - nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); - - children = (int *)(root + PLAGUE_ELF_LOWERBACK * jointSize); - *children = nodeIndex; - - g_jointNodes[nodeIndex].data = rootIndex + PLAGUE_ELF_UPPERBACK; - g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.h deleted file mode 100644 index b36c12ed..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.h +++ /dev/null @@ -1,107 +0,0 @@ -/* -Copyright (C) 1999-2006 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 // for size_t -#include "arrayedlist.h" - -#define JN_YAW_CHANGED 0x00000001 -#define JN_PITCH_CHANGED 0x00000002 -#define JN_ROLL_CHANGED 0x00000004 - -// Skeleton types -enum { - SKEL_NULL = -1, - SKEL_RAVEN = 0, - SKEL_BOX, - SKEL_BEETLE, - SKEL_ELFLORD, - SKEL_PLAGUE_ELF, - SKEL_CORVUS, - NUM_SKELETONS -}; - -// Raven Skeletal joints -enum { - RAVEN_LOWERBACK = 0, - RAVEN_UPPERBACK, - RAVEN_HEAD, - NUM_JOINTS_RAVEN -}; - -// Box Skeletal joints -enum { - BOX_CENTER = 0, - NUM_JOINTS_BOX -}; - -// Beetle Skeletal joints -enum { - BEETLE_NECK = 0, - BEETLE_HEAD, - NUM_JOINTS_BEETLE -}; - -// Elflord Skeletal joints -enum { - ELFLORD_, - ELFLORD__, - NUM_JOINTS_ELFLORD -}; - -// Plague Elf Skeletal joints -enum { - PLAGUE_ELF_LOWERBACK, - PLAGUE_ELF_UPPERBACK, - PLAGUE_ELF_HEAD, - NUM_JOINTS_PLAGUE_ELF -}; - -// Corvus Skeletal joints -enum { - CORVUS_LOWERBACK, - CORVUS_UPPERBACK, - CORVUS_HEAD, - NUM_JOINTS_CORVUS -}; - -#define NO_SWAP_FRAME -1 -#define NULL_ROOT_JOINT -1 - -#define MAX_ARRAYED_SKELETAL_JOINTS 255 // has max of 65,535 (if this remains at 255, net code can be changed to reflect) -#define MAX_ARRAYED_JOINT_NODES (MAX_ARRAYED_SKELETAL_JOINTS - 1) - -#define MAX_JOINTS_PER_SKELETON 8 // arbitrary small number -#define MAX_JOINT_NODES_PER_SKELETON (MAX_JOINTS_PER_SKELETON - 1) - -extern char *skeletonRootNames[]; -extern int skeletonRNameOffsets[]; -extern char *skeletonJointNames[]; -extern int skeletonNameOffsets[]; -extern int numJointsInSkeleton[]; -extern char *skeletonEffectorNames[]; -extern int skeletonENameOffsets[]; -extern int numNodesInSkeleton[]; - -typedef void (*CreateSkeleton_t)(void *skeletalJoints, size_t jointSize, struct ArrayedListNode_s *jointNodes, int rootIndex); - -extern CreateSkeleton_t SkeletonCreators[NUM_SKELETONS]; - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_fmodel.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_fmodel.h deleted file mode 100644 index 7ec6570c..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_fmodel.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -Copyright (C) 1999-2006 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 FMODEL_H -#define FMODEL_H -#include "fmodel.h" -#endif -#include "qd_skeletons.h" - -typedef struct -{ - int numnormals; - vec3_t normalsum; -} fmvertexnormals_t; - -typedef struct -{ - vec3_t v; - int lightnormalindex; - fmvertexnormals_t vnorm; -} fmtrivert_t; - -#define FRAME_NAME_LEN (16) - -typedef struct -{ - vec3_t mins, maxs; - char name[FRAME_NAME_LEN]; - fmtrivert_t v[MAX_FM_VERTS]; - struct QD_SkeletalJoint_s joints[NUM_CLUSTERS]; - struct QD_SkeletalJoint_s references[NUM_REFERENCES]; -} fmframe_t; - -extern fmframe_t g_frames[MAX_FM_FRAMES]; - -extern fmheader_t fmheader; -extern char cdarchive[1024]; // set by $fmcd -extern char cdpartial[1024]; // set by $fmcd -extern char cddir[1024]; // set by $fmcd - -void GrabFrame (char *frame); -void H_printf(char *fmt, ...); -char *FindFrameFile (char *frame); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.c deleted file mode 100644 index 43395c8c..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.c +++ /dev/null @@ -1,1291 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qd_skeletons.h" -#include "skeletons.h" -#include "qd_fmodel.h" -#include "angles.h" -#include "token.h" -#include "qdata.h" -#include "reference.h" - -#include -#include -#include - - -// We're assuming no more than 16 reference points, with no more than 32 characters in the name -char RefPointNameList[REF_MAX_POINTS][REF_MAX_STRLEN]; -int RefPointNum = 0; - -Skeletalfmheader_t g_skelModel; - -void ClearSkeletalModel() -{ - g_skelModel.type = SKEL_NULL; - g_skelModel.clustered = false; - g_skelModel.references = REF_NULL; -} - -//========================================================================== -// -// LoadHRCClustered -// -//========================================================================== - -// Places the null terminated src string into the dest string less any trailing digits or underscores -void StripTrailingDigits(char *src, char *dest) -{ -#ifndef NDEBUG - int max = SKELETAL_NAME_MAX; // should be sufficient for inteded use on names from hrc files -#endif - int i = 0; - - while(src[i] != '\0') - { - ++i; -#ifndef NDEBUG - assert(i < max); -#endif - } - - while((src[--i] >= '0' && src[i] <= '9') || src[i] == '_') - { - - } - - memcpy(dest, src, ++i); - - dest[i] = '\0'; -} - -static void LoadHRCClustered(char *fileName, int **clusterList, int *num_verts, int skelType) -{ - extern void HandleHRCModel(triangle_t **triList, int *triangleCount, - mesh_node_t **nodesList, int *num_mesh_nodes, int ActiveNode, int Depth); - - extern mesh_node_t *pmnodes; - - triangle_t *triList; -// mesh_node_t *nodesList; - int num_mesh_nodes = 0, triangleCount = 0; - -#if 0 - int i; - int j, numVerts; - char stripped[SKELETAL_NAME_MAX]; - - for( i = 1; i < numJointsInSkeleton[skelType] + 1; ++i) - { - num_verts[i] = 0; - } - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - - TK_Beyond(TK_CLUSTERS); - - while(TK_Search(TK_CLUSTER_NAME) != TK_EOF) - { - TK_Require(TK_STRING); - - StripTrailingDigits(tk_String, stripped); - - for( i = 0; i < numJointsInSkeleton[skelType]; ++i) - { - if(stricmp(stripped, skeletonJointNames[skeletonNameOffsets[skelType]+i]) == 0) - { - i = -i + numJointsInSkeleton[skelType] - 1; - - TK_BeyondRequire(TK_NUM_CLUSTER_VERTICES, TK_INTNUMBER); - - numVerts = tk_IntNumber; - - if(!num_verts[i+1]) // first set of verts for cluster - { - clusterList[i] = SafeMalloc(numVerts*sizeof(int), "LoadHRCClustered"); - assert(clusterList[i]); - } - else // any later sets of verts need to copy current - { - int *temp; - - temp = SafeMalloc((num_verts[i+1]+numVerts)*sizeof(int), "LoadHRCClustered"); - assert(temp); - - memcpy(temp + numVerts, clusterList[i], num_verts[i+1]*sizeof(int)); - - free(clusterList[i]); - - clusterList[i] = temp; - } - - // currently this function is only called by LoadModelClusters. - // Apparently the matching free has disappeared, - // should probably be free at the end of FMCmd_Base - - TK_Beyond(TK_LBRACE); - - for(j = 0; j < numVerts; ++j) - { - TK_Require(TK_INTNUMBER); - clusterList[i][j] = tk_IntNumber; - TK_Fetch(); - } - - num_verts[i+1] += numVerts; - - break; - } - } - } - - num_verts[0] = numJointsInSkeleton[skelType]; -#endif - -#if 1 // get the index number localized to the root -// for( i = 1; i < numJointsInSkeleton[skelType] + 1; ++i) -// { -// g_skelModel.num_verts[i] = 0; -// } - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - - // prime it - TK_Beyond(TK_MODEL); - - triList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); - memset(triList,0,MAXTRIANGLES*sizeof(triangle_t)); -// nodesList = SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); - pmnodes = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); - - memset(pmnodes, 0, MAX_FM_MESH_NODES * sizeof(mesh_node_t)); - - // this should eventually use a stripped down version of this - HandleHRCModel(&triList, &triangleCount, &pmnodes, &num_mesh_nodes, 0, 0); - -// free(nodesList); - free(triList); - - num_verts[0] = numJointsInSkeleton[skelType]; -#endif -} - -void ReadHRCClusterList(mesh_node_t *meshNode, int baseIndex) -{ - int i, j, numVerts; - tokenType_t nextToken; - char stripped[SKELETAL_NAME_MAX]; - - meshNode->clustered = true; - - nextToken = TK_Get(TK_CLUSTER_NAME); - - while (nextToken == TK_CLUSTER_NAME) - { - TK_FetchRequire(TK_STRING); - - StripTrailingDigits(tk_String, stripped); - - for( i = 0; i < numJointsInSkeleton[g_skelModel.type]; ++i) - { - if(stricmp(stripped, skeletonJointNames[skeletonNameOffsets[g_skelModel.type]+i]) == 0) - { - i = -i + numJointsInSkeleton[g_skelModel.type] - 1; - - TK_BeyondRequire(TK_NUM_CLUSTER_VERTICES, TK_INTNUMBER); - - numVerts = tk_IntNumber; - - if(!baseIndex) - { - meshNode->clusters[i] = (int *) SafeMalloc(numVerts*sizeof(int), "ReadHRCClusterList"); - assert(meshNode->clusters[i]); - } - else - { - int *temp; - - temp = meshNode->clusters[i]; - meshNode->clusters[i] = (int *) SafeMalloc((meshNode->num_verts[i+1]+numVerts)*sizeof(int), "ReadHRCClusterList"); - assert(meshNode->clusters[i]); - - memcpy(meshNode->clusters[i], temp, meshNode->num_verts[i+1]*sizeof(int)); - free(temp); - } - - // currently this function is only called by LoadModelClusters. - // Apparently the matching free has disappeared, - // should probably be free at the end of FMCmd_Base - - TK_Beyond(TK_LBRACE); - - for(j = 0; j < numVerts; ++j) - { - TK_Require(TK_INTNUMBER); - meshNode->clusters[i][baseIndex+j] = tk_IntNumber+baseIndex; - TK_Fetch(); - } - - if(baseIndex) - { - meshNode->num_verts[i+1] += numVerts; - } - else - { - meshNode->num_verts[i+1] = numVerts; - } - - break; - } - } - - TK_BeyondRequire(TK_CLUSTER_STATE, TK_INTNUMBER); - nextToken = TK_Fetch(); - } -} - -static void LoadHRCGlobals(char *fileName) -{ - int i; - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - TK_Beyond(TK_MODEL); - - TK_Beyond(TK_SCALING); - for(i = 0; i < 3; i++) - { - TK_Require(TK_FLOATNUMBER); - g_skelModel.scaling[i] = tk_FloatNumber; - TK_Fetch(); - } - - TK_Beyond(TK_ROTATION); - for(i = 0; i < 3; i++) - { - TK_Require(TK_FLOATNUMBER); - g_skelModel.rotation[i] = tk_FloatNumber; - TK_Fetch(); - } - - TK_Beyond(TK_TRANSLATION); - for(i = 0; i < 3; i++) - { - TK_Require(TK_FLOATNUMBER); - g_skelModel.translation[i] = tk_FloatNumber; - TK_Fetch(); - } -} - -static void ParseVec3(vec3_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void ParseVec3d(vec3d_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void ParseRotation3(vec3_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void ParseRotation3d(vec3d_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void ParseTranslation3(vec3_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void ParseTranslation3d(vec3d_t in) -{ - TK_Require(TK_FLOATNUMBER); - in[1] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[2] = tk_FloatNumber; - TK_FetchRequire(TK_FLOATNUMBER); - in[0] = tk_FloatNumber; -} - -static void LoadHRCJointList(char *fileName, QD_SkeletalJoint_t *jointList, int skelType) -{ -#define MAX_STACK 64 - int i, j; - vec3d_t curTranslation[MAX_STACK], curRotation[MAX_STACK], curScale[MAX_STACK]; - int curCorrespondingJoint[MAX_STACK]; - int currentStack = 0, stackSize; - double cx, sx, cy, sy, cz, sz; - double rx, ry, rz; - double x2, y2, z2; - char stripped[SKELETAL_NAME_MAX]; - Placement_d_t *placement; - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - - TK_Beyond(TK_MODEL); - - while(TK_Search(TK_NAME) != TK_EOF) - { - TK_Require(TK_STRING); - - StripTrailingDigits(tk_String, stripped); - - if(stricmp(stripped, skeletonRootNames[skeletonRNameOffsets[skelType]]) == 0) - { - break; - } - } - - if(tk_Token == TK_EOF) - { - Error("Bone Chain Root: %s not found\n", skeletonRootNames[skeletonRNameOffsets[skelType]]); - return; - } - - TK_Beyond(TK_SCALING); - - ParseVec3d(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3d(curRotation[currentStack]); - - TK_Beyond(TK_TRANSLATION); - - ParseVec3d(curTranslation[currentStack]); - - // account for global model translation - curTranslation[currentStack][1] += g_skelModel.translation[0]; - curTranslation[currentStack][2] += g_skelModel.translation[1]; - curTranslation[currentStack][0] += g_skelModel.translation[2]; - - curCorrespondingJoint[currentStack] = -1; - - ++currentStack; - - for(i = 0; i < numJointsInSkeleton[skelType]; ++i) - { - while(1) - { - TK_Beyond(TK_MODEL); - - TK_BeyondRequire(TK_NAME, TK_STRING); - - StripTrailingDigits(tk_String, stripped); - - if(stricmp(stripped, skeletonJointNames[skeletonNameOffsets[skelType]+i]) == 0) - break; - - TK_Beyond(TK_SCALING); - - ParseVec3d(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3d(curRotation[currentStack]); - - TK_Beyond(TK_TRANSLATION); - - ParseVec3d(curTranslation[currentStack]); - - curCorrespondingJoint[currentStack] = -1; - - ++currentStack; - } - - TK_Beyond(TK_SCALING); - - ParseVec3d(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3d(curRotation[currentStack]); - - jointList[i].rotation[1] = curRotation[currentStack][1]; - jointList[i].rotation[2] = curRotation[currentStack][2]; - jointList[i].rotation[0] = curRotation[currentStack][0]; - - TK_Beyond(TK_TRANSLATION); - - ParseVec3d(curTranslation[currentStack]); - -// jointList[i].placement.origin[1] = curTranslation[currentStack][1]; -// jointList[i].placement.origin[2] = curTranslation[currentStack][2]; -// jointList[i].placement.origin[0] = curTranslation[currentStack][0]; - - jointList[i].placement.origin[1] = 0.0; - jointList[i].placement.origin[2] = 0.0; - jointList[i].placement.origin[0] = 0.0; - - jointList[i].placement.direction[1] = 20.0; - jointList[i].placement.direction[2] = 0.0; - jointList[i].placement.direction[0] = 0.0; - - jointList[i].placement.up[1] = 0.0; - jointList[i].placement.up[2] = 20.0; - jointList[i].placement.up[0] = 0.0; - - curCorrespondingJoint[currentStack] = i; - - ++currentStack; - } - - stackSize = currentStack; - -#if 0 - // rotate the direction and up vectors to correspond to the rotation - for(i = 0; i < numJointsInSkeleton[skelType]; ++i) - { - rx = jointList[i].rotation[0]*ANGLE_TO_RAD; - ry = jointList[i].rotation[1]*ANGLE_TO_RAD; - rz = jointList[i].rotation[2]*ANGLE_TO_RAD; - - cx = cos(rx); - sx = sin(rx); - - cy = cos(ry); - sy = sin(ry); - - cz = cos(rz); - sz = sin(rz); - - // y-axis rotation for direction - x2 = jointList[i].placement.direction[0]*cy+jointList[i].placement.direction[2]*sy; - z2 = -jointList[i].placement.direction[0]*sy+jointList[i].placement.direction[2]*cy; - jointList[i].placement.direction[0] = x2; - jointList[i].placement.direction[2] = z2; - - // y-axis rotation for up - x2 = jointList[i].placement.up[0]*cy+jointList[i].placement.up[2]*sy; - z2 = -jointList[i].placement.up[0]*sy+jointList[i].placement.up[2]*cy; - jointList[i].placement.up[0] = x2; - jointList[i].placement.up[2] = z2; - - // z-axis rotation for direction - x2 = jointList[i].placement.direction[0]*cz-jointList[i].placement.direction[1]*sz; - y2 = jointList[i].placement.direction[0]*sz+jointList[i].placement.direction[1]*cz; - jointList[i].placement.direction[0] = x2; - jointList[i].placement.direction[1] = y2; - - // z-axis rotation for up - x2 = jointList[i].placement.up[0]*cz-jointList[i].placement.up[1]*sz; - y2 = jointList[i].placement.up[0]*sz+jointList[i].placement.up[1]*cz; - jointList[i].placement.up[0] = x2; - jointList[i].placement.up[1] = y2; - - // x-axis rotation for direction vector - y2 = jointList[i].placement.direction[1]*cx-jointList[i].placement.direction[2]*sx; - z2 = jointList[i].placement.direction[1]*sx+jointList[i].placement.direction[2]*cx; - jointList[i].placement.direction[1] = y2; - jointList[i].placement.direction[2] = z2; - - // x-axis rotation for up vector - y2 = jointList[i].placement.up[1]*cx-jointList[i].placement.up[2]*sx; - z2 = jointList[i].placement.up[1]*sx+jointList[i].placement.up[2]*cx; - jointList[i].placement.up[1] = y2; - jointList[i].placement.up[2] = z2; - - // translate direction to a point in the model - jointList[i].placement.direction[0] += jointList[i].placement.origin[0]; - jointList[i].placement.direction[1] += jointList[i].placement.origin[1]; - jointList[i].placement.direction[2] += jointList[i].placement.origin[2]; - - // translate up to a point in the model - jointList[i].placement.up[0] += jointList[i].placement.origin[0]; - jointList[i].placement.up[1] += jointList[i].placement.origin[1]; - jointList[i].placement.up[2] += jointList[i].placement.origin[2]; - } -#endif - - for(i = stackSize - 1; i >= 0; --i) - { - rx = curRotation[i][0]*ANGLE_TO_RAD; - ry = curRotation[i][1]*ANGLE_TO_RAD; - rz = curRotation[i][2]*ANGLE_TO_RAD; - - cx = cos(rx); - sx = sin(rx); - - cy = cos(ry); - sy = sin(ry); - - cz = cos(rz); - sz = sin(rz); - -#if 1 - for(j = i; j < stackSize; ++j) - { - if(curCorrespondingJoint[j] != -1) - { - placement = &jointList[curCorrespondingJoint[j]].placement; - - // y-axis rotation for origin - x2 = placement->origin[0]*cy+placement->origin[2]*sy; - z2 = -placement->origin[0]*sy+placement->origin[2]*cy; - placement->origin[0] = x2; - placement->origin[2] = z2; - - // y-axis rotation for direction - x2 = placement->direction[0]*cy+placement->direction[2]*sy; - z2 = -placement->direction[0]*sy+placement->direction[2]*cy; - placement->direction[0] = x2; - placement->direction[2] = z2; - - // y-axis rotation for up - x2 = placement->up[0]*cy+placement->up[2]*sy; - z2 = -placement->up[0]*sy+placement->up[2]*cy; - placement->up[0] = x2; - placement->up[2] = z2; - - // z-axis rotation for origin - x2 = placement->origin[0]*cz-placement->origin[1]*sz; - y2 = placement->origin[0]*sz+placement->origin[1]*cz; - placement->origin[0] = x2; - placement->origin[1] = y2; - - // z-axis rotation for direction - x2 = placement->direction[0]*cz-placement->direction[1]*sz; - y2 = placement->direction[0]*sz+placement->direction[1]*cz; - placement->direction[0] = x2; - placement->direction[1] = y2; - - // z-axis rotation for up - x2 = placement->up[0]*cz-placement->up[1]*sz; - y2 = placement->up[0]*sz+placement->up[1]*cz; - placement->up[0] = x2; - placement->up[1] = y2; - - // x-axis rotation for origin - y2 = placement->origin[1]*cx-placement->origin[2]*sx; - z2 = placement->origin[1]*sx+placement->origin[2]*cx; - placement->origin[1] = y2; - placement->origin[2] = z2; - - // x-axis rotation for direction vector - y2 = placement->direction[1]*cx-placement->direction[2]*sx; - z2 = placement->direction[1]*sx+placement->direction[2]*cx; - placement->direction[1] = y2; - placement->direction[2] = z2; - - // x-axis rotation for up vector - y2 = placement->up[1]*cx-placement->up[2]*sx; - z2 = placement->up[1]*sx+placement->up[2]*cx; - placement->up[1] = y2; - placement->up[2] = z2; - - // translate origin - placement->origin[0] += curTranslation[i][0]; - placement->origin[1] += curTranslation[i][1]; - placement->origin[2] += curTranslation[i][2]; - - // translate back to local coord - placement->direction[0] += curTranslation[i][0]; - placement->direction[1] += curTranslation[i][1]; - placement->direction[2] += curTranslation[i][2]; - - // translate back to local coord - placement->up[0] += curTranslation[i][0]; - placement->up[1] += curTranslation[i][1]; - placement->up[2] += curTranslation[i][2]; - } - } -#else - // This screwed up and needs to be sorted out!!! - // The stack info needs to be written too instead of the jointList for j > numJoints for Skeleton - for(j = i-1; j < stackSize-1; ++j) - { - // y-axis rotation for origin - x2 = jointList[j].placement.origin[0]*cy+jointList[j].placement.origin[2]*sy; - z2 = -jointList[j].placement.origin[0]*sy+jointList[j].placement.origin[2]*cy; - jointList[j].placement.origin[0] = x2; - jointList[j].placement.origin[2] = z2; - - // y-axis rotation for direction - x2 = jointList[j].placement.direction[0]*cy+jointList[j].placement.direction[2]*sy; - z2 = -jointList[j].placement.direction[0]*sy+jointList[j].placement.direction[2]*cy; - jointList[j].placement.direction[0] = x2; - jointList[j].placement.direction[2] = z2; - - // y-axis rotation for up - x2 = jointList[j].placement.up[0]*cy+jointList[j].placement.up[2]*sy; - z2 = -jointList[j].placement.up[0]*sy+jointList[j].placement.up[2]*cy; - jointList[j].placement.up[0] = x2; - jointList[j].placement.up[2] = z2; - - // z-axis rotation for origin - x2 = jointList[j].placement.origin[0]*cz-jointList[j].placement.origin[1]*sz; - y2 = jointList[j].placement.origin[0]*sz+jointList[j].placement.origin[1]*cz; - jointList[j].placement.origin[0] = x2; - jointList[j].placement.origin[1] = y2; - - // z-axis rotation for direction - x2 = jointList[j].placement.direction[0]*cz-jointList[j].placement.direction[1]*sz; - y2 = jointList[j].placement.direction[0]*sz+jointList[j].placement.direction[1]*cz; - jointList[j].placement.direction[0] = x2; - jointList[j].placement.direction[1] = y2; - - // z-axis rotation for up - x2 = jointList[j].placement.up[0]*cz-jointList[j].placement.up[1]*sz; - y2 = jointList[j].placement.up[0]*sz+jointList[j].placement.up[1]*cz; - jointList[j].placement.up[0] = x2; - jointList[j].placement.up[1] = y2; - - // x-axis rotation for origin - y2 = jointList[j].placement.origin[1]*cx-jointList[j].placement.origin[2]*sx; - z2 = jointList[j].placement.origin[1]*sx+jointList[j].placement.origin[2]*cx; - jointList[j].placement.origin[1] = y2; - jointList[j].placement.origin[2] = z2; - - // x-axis rotation for direction vector - y2 = jointList[j].placement.direction[1]*cx-jointList[j].placement.direction[2]*sx; - z2 = jointList[j].placement.direction[1]*sx+jointList[j].placement.direction[2]*cx; - jointList[j].placement.direction[1] = y2; - jointList[j].placement.direction[2] = z2; - - // x-axis rotation for up vector - y2 = jointList[j].placement.up[1]*cx-jointList[j].placement.up[2]*sx; - z2 = jointList[j].placement.up[1]*sx+jointList[j].placement.up[2]*cx; - jointList[j].placement.up[1] = y2; - jointList[j].placement.up[2] = z2; - - if(curCorrespondingJoint[j+1] != -1) - { - // translate origin - jointList[j].placement.origin[0] += curTranslation[i-1][0]; - jointList[j].placement.origin[1] += curTranslation[i-1][1]; - jointList[j].placement.origin[2] += curTranslation[i-1][2]; - - // translate back to local coord - jointList[j].placement.direction[0] += curTranslation[i-1][0]; - jointList[j].placement.direction[1] += curTranslation[i-1][1]; - jointList[j].placement.direction[2] += curTranslation[i-1][2]; - - // translate back to local coord - jointList[j].placement.up[0] += curTranslation[i-1][0]; - jointList[j].placement.up[1] += curTranslation[i-1][1]; - jointList[j].placement.up[2] += curTranslation[i-1][2]; - } - } -#endif - } -} - -void LoadModelTransform(char *fileName) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - - LoadHRCGlobals(InputFileName); - - printf(" - assuming .HRC\n"); - return; - } - - Error("\n Could not open file '%s':\n" - "No HRC match.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { -// printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRCGlobals(fileName); - return; - } - } - - Error("Could not open file '%s':\n",fileName); - } -} - -void LoadModelClusters(char *fileName, int **clusterList, int *num_verts, int skelType) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - - LoadHRCClustered(InputFileName, clusterList, num_verts, skelType); - - printf(" - assuming .HRC\n"); - return; - } - - Error("\n Could not open file '%s':\n" - "No HRC match.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { -// printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRCClustered(fileName, clusterList, num_verts, skelType); - return; - } - } - - Error("Could not open file '%s':\n",fileName); - } -} - -void LoadSkeleton(char *fileName, QD_SkeletalJoint_t *jointList, int skelType) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - - LoadHRCJointList(InputFileName, jointList, skelType); - - printf(" - assuming .HRC\n"); - return; - } - - Error("\n Could not open file '%s':\n" - "No HRC.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { -// printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRCJointList(fileName, jointList, skelType); - - return; - } - } - - Error("Could not open file '%s':\n",fileName); - } -} - -/* -=============== -GrabSkeletalFrame -=============== -*/ -void GrabSkeletalFrame(char *frame) -{ - char file1[1024]; - char *framefile; - fmframe_t *fr; - - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - - printf ("Grabbing Skeletal Frame %s\n", file1); - - fr = &g_frames[fmheader.num_frames - 1]; // last frame read in - - LoadSkeleton(file1, fr->joints, g_skelModel.type); -} - -/* -=============== -GrabModelTransform -=============== -*/ -void GrabModelTransform(char *frame) -{ - char file1[1024]; - char *framefile; - fmframe_t *fr; - - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - -// printf ("grabbing %s\n", file1); - - fr = &g_frames[fmheader.num_frames - 1]; // last frame read in - - LoadModelTransform(file1); -} - -void Cmd_FMCluster() -{ - char file1[1024]; - - GetScriptToken (false); - - printf ("---------------------\n"); - sprintf (file1, "%s/%s", cdpartial, token); - printf ("%s\n", file1); - - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s", cddir, token); - - g_skelModel.clustered = -1; - - LoadModelClusters(file1, (int **)&g_skelModel.clusters, (int *)&g_skelModel.num_verts, g_skelModel.type); - - g_skelModel.new_num_verts[0] = g_skelModel.num_verts[0]; - - g_skelModel.clustered = true; -} - -void Cmd_FMSkeleton() -{ - GetScriptToken (false); - g_skelModel.type = atoi(token); -} - -void Cmd_FMSkeletalFrame() -{ - while (ScriptTokenAvailable()) - { - GetScriptToken (false); - if (g_skipmodel) - { - GetScriptToken (false); - continue; - } - if (g_release || g_archive) - { - fmheader.num_frames = 1; // don't skip the writeout - GetScriptToken (false); - continue; - } - - H_printf("#define FRAME_%-16s\t%i\n", token, fmheader.num_frames); - - GrabModelTransform (token); - GrabFrame (token); - GrabSkeletalFrame (token); - - // need to add the up and dir points to the frame bounds here - // using AddPointToBounds (ptrivert[index_xyz].v, fr->mins, fr->maxs); - // then remove fudge in determining scale on frame write out - } -} - -static void LoadHRCReferences(char *fileName, fmframe_t *fr) -{ -#define MAX_STACK 64 - int i, j, k; - vec3d_t curTranslation[MAX_STACK], curRotation[MAX_STACK]; - int curCorrespondingJoint[MAX_STACK]; - int currentStack, stackSize; - double cx, sx, cy, sy, cz, sz; - double rx, ry, rz; - double x2, y2, z2; - char stripped[SKELETAL_NAME_MAX]; - Placement_d_t *placement; - int refnum; - - TK_OpenSource(fileName); - TK_FetchRequire(TK_HRCH); - TK_FetchRequire(TK_COLON); - TK_FetchRequire(TK_SOFTIMAGE); - - if (RefPointNum <= 0) - { // There were no labels indicated in the QDT, so use the hard-coded stuff. - refnum = numReferences[g_skelModel.references]; - } - else - { - refnum = RefPointNum; - } - - for(k = 0; k < refnum; ++k) - { - currentStack = 0; - - // Load the root to get translation and initial rotation -// TK_Beyond(TK_MODEL); - - while(TK_Search(TK_NAME) != TK_EOF) - { - TK_Require(TK_STRING); - - StripTrailingDigits(tk_String, stripped); - - if (RefPointNum == 0) - { // Hard coded refpoint labels - if(stricmp(stripped, - referenceRootNames[referenceRootNameOffsets[g_skelModel.references]+k]) == 0) - { - break; - } - } - else - { // labels indicated by the QDT - if(stricmp(stripped, RefPointNameList[k]) == 0) - { - break; - } - } - } - - if(tk_Token == TK_EOF) - { - if (RefPointNum == 0) - { // Hard coded refpoint labels - Error("Bone Chain Root: %s not found\n", referenceRootNames[referenceRootNameOffsets[g_skelModel.references]]); - } - else - { // labels indicated by the QDT - Error("Bone Chain Root: %s not found\n", RefPointNameList[k]); - } - return; - } - -// TK_Beyond(TK_SCALING); - -// ParseVec3d(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3d(curRotation[currentStack]); - - TK_Beyond(TK_TRANSLATION); - - ParseVec3d(curTranslation[currentStack]); - - // account for global model translation - curTranslation[currentStack][1] += g_skelModel.translation[0]; - curTranslation[currentStack][2] += g_skelModel.translation[1]; - curTranslation[currentStack][0] += g_skelModel.translation[2]; - - curCorrespondingJoint[currentStack] = -1; - -// rjr - this one not needed, as there is also a stack increment 20 lines below??? -// ++currentStack; - - // Load the joint to get orientation - TK_Beyond(TK_MODEL); - -// TK_Beyond(TK_SCALING); - -// ParseVec3d(curScale[currentStack]); - - TK_Beyond(TK_ROTATION); - - ParseRotation3d(curRotation[currentStack]); - -// TK_Beyond(TK_TRANSLATION); - -// ParseVec3d(curTranslation[currentStack]); - - fr->references[k].placement.origin[1] = 0.0; - fr->references[k].placement.origin[2] = 0.0; - fr->references[k].placement.origin[0] = 0.0; - - fr->references[k].placement.direction[1] = 20.0; - fr->references[k].placement.direction[2] = 0.0; - fr->references[k].placement.direction[0] = 0.0; - - fr->references[k].placement.up[1] = 0.0; - fr->references[k].placement.up[2] = 20.0; - fr->references[k].placement.up[0] = 0.0; - - curCorrespondingJoint[currentStack] = k; - - ++currentStack; - - stackSize = currentStack; - - for(i = stackSize - 1; i >= 0; --i) - { - rx = curRotation[i][0]*ANGLE_TO_RAD; - ry = curRotation[i][1]*ANGLE_TO_RAD; - rz = curRotation[i][2]*ANGLE_TO_RAD; - - cx = cos(rx); - sx = sin(rx); - - cy = cos(ry); - sy = sin(ry); - - cz = cos(rz); - sz = sin(rz); - - for(j = i; j < stackSize; ++j) - { - if(curCorrespondingJoint[j] != -1) - { - placement = &fr->references[curCorrespondingJoint[j]].placement; - - // y-axis rotation for origin - x2 = placement->origin[0]*cy+placement->origin[2]*sy; - z2 = -placement->origin[0]*sy+placement->origin[2]*cy; - placement->origin[0] = x2; - placement->origin[2] = z2; - - // y-axis rotation for direction - x2 = placement->direction[0]*cy+placement->direction[2]*sy; - z2 = -placement->direction[0]*sy+placement->direction[2]*cy; - placement->direction[0] = x2; - placement->direction[2] = z2; - - // y-axis rotation for up - x2 = placement->up[0]*cy+placement->up[2]*sy; - z2 = -placement->up[0]*sy+placement->up[2]*cy; - placement->up[0] = x2; - placement->up[2] = z2; - - // z-axis rotation for origin - x2 = placement->origin[0]*cz-placement->origin[1]*sz; - y2 = placement->origin[0]*sz+placement->origin[1]*cz; - placement->origin[0] = x2; - placement->origin[1] = y2; - - // z-axis rotation for direction - x2 = placement->direction[0]*cz-placement->direction[1]*sz; - y2 = placement->direction[0]*sz+placement->direction[1]*cz; - placement->direction[0] = x2; - placement->direction[1] = y2; - - // z-axis rotation for up - x2 = placement->up[0]*cz-placement->up[1]*sz; - y2 = placement->up[0]*sz+placement->up[1]*cz; - placement->up[0] = x2; - placement->up[1] = y2; - - // x-axis rotation for origin - y2 = placement->origin[1]*cx-placement->origin[2]*sx; - z2 = placement->origin[1]*sx+placement->origin[2]*cx; - placement->origin[1] = y2; - placement->origin[2] = z2; - - // x-axis rotation for direction vector - y2 = placement->direction[1]*cx-placement->direction[2]*sx; - z2 = placement->direction[1]*sx+placement->direction[2]*cx; - placement->direction[1] = y2; - placement->direction[2] = z2; - - // x-axis rotation for up vector - y2 = placement->up[1]*cx-placement->up[2]*sx; - z2 = placement->up[1]*sx+placement->up[2]*cx; - placement->up[1] = y2; - placement->up[2] = z2; - - // translate origin - placement->origin[0] += curTranslation[i][0]; - placement->origin[1] += curTranslation[i][1]; - placement->origin[2] += curTranslation[i][2]; - - // translate back to local coord - placement->direction[0] += curTranslation[i][0]; - placement->direction[1] += curTranslation[i][1]; - placement->direction[2] += curTranslation[i][2]; - - // translate back to local coord - placement->up[0] += curTranslation[i][0]; - placement->up[1] += curTranslation[i][1]; - placement->up[2] += curTranslation[i][2]; - - } - } - } - printf("%f, %f, %f\n", placement->origin[0], placement->origin[1], placement->origin[2]); - } - printf("\n"); -} - -void Cmd_FMReferenced() -{ - int i; - - GetScriptToken (false); - g_skelModel.references = atoi(token); - - // Guess what? Now, we now want a list of strings to look for here instead of a hard-coded list - for (i=0; i 0) - { - printf("Searching for %d different reference points.\n", RefPointNum); - } - else - { - printf("Using built-in reference points.\n"); - } - -} - -void LoadReferences(char *fileName, fmframe_t *fr) -{ - FILE *file1; - int dot = '.'; - char *dotstart; - char InputFileName[256]; - - dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? - - if (!dotstart) - { - strcpy(InputFileName, fileName); - strcat(InputFileName, ".hrc"); - if((file1 = fopen(InputFileName, "rb")) != NULL) - { - fclose(file1); - - LoadHRCReferences(InputFileName, fr); - - printf(" - assuming .HRC\n"); - return; - } - - Error("\n Could not open file '%s':\n" - "No HRC.\n", fileName); - } - else - { - if((file1 = fopen(fileName, "rb")) != NULL) - { - printf("\n"); - fclose(file1); - if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) - { - LoadHRCReferences(fileName, fr); - - return; - } - } - - Error("Could not open file '%s':\n",fileName); - } -} - -void GrabReferencedFrame(char *frame) -{ - char file1[1024]; - char *framefile; - fmframe_t *fr; - - framefile = FindFrameFile (frame); - - sprintf (file1, "%s/%s", cdarchive, framefile); - ExpandPathAndArchive (file1); - - sprintf (file1, "%s/%s",cddir, framefile); - - printf ("Grabbing Referenced %s\n", file1); - - fr = &g_frames[fmheader.num_frames - 1]; // last frame read in - - LoadReferences(file1, fr); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.h deleted file mode 100644 index b6ff7bcd..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -Copyright (C) 1999-2006 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 QD_SKELETONS_H -#define QD_SKELETONS_H - -#include "placement.h" - - -typedef struct Placement_d_s -{ - vec3d_t origin; - vec3d_t direction; - vec3d_t up; -} Placement_d_t; - -typedef struct QD_SkeletalJoint_s -{ - Placement_d_t placement; - vec3d_t rotation; -} QD_SkeletalJoint_t; - -#define NUM_CLUSTERS 8 - -typedef struct IntListNode_s -{ - int data; - struct IntListNode_s *next; -} IntListNode_t; // gaak - -typedef struct Skeletalfmheader_s -{ - int type; - int clustered; - int references; - - int *clusters[NUM_CLUSTERS]; - IntListNode_t *vertLists[NUM_CLUSTERS]; - int num_verts[NUM_CLUSTERS + 1]; - int new_num_verts[NUM_CLUSTERS + 1]; - - float scaling[3]; - float rotation[3]; - float translation[3]; -} Skeletalfmheader_t; - -#define SKELETAL_NAME_MAX 32 - -extern Skeletalfmheader_t g_skelModel; - -void ClearSkeletalModel(); -void GrabModelTransform(char *frame); -void GrabSkeletalFrame(char *frame); -void GrabReferencedFrame(char *frame); - -// Reference Stuff -#define NUM_REFERENCES 8 - -#define REF_MAX_POINTS 16 -#define REF_MAX_STRLEN 32 - -// We're assuming no more than 16 reference points, with no more than 32 characters in the name -extern char RefPointNameList[REF_MAX_POINTS][REF_MAX_STRLEN]; -extern int RefPointNum; - -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qdata.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qdata.c deleted file mode 100644 index 0a939b16..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/qdata.c +++ /dev/null @@ -1,735 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" -#include "md4.h" - -void TK_Init(); - -qboolean g_compress_pak; -qboolean g_release; // don't grab, copy output data to new tree -qboolean g_pak; // if true, copy to pak instead of release -char g_releasedir[1024]; // c:\quake2\baseq2, etc -qboolean g_archive; // don't grab, copy source data to new tree -qboolean do3ds; -char g_only[256]; // if set, only grab this cd -qboolean g_skipmodel; // set true when a cd is not g_only -int g_forcemodel = MODEL_AUTO; -qboolean g_verbose = false; -qboolean g_allow_newskin = true; -qboolean g_ignoreTriUV = false; -qboolean g_publishOutput = false; - -char *ext_3ds = "3ds"; -char *ext_tri= "tri"; -char *trifileext; - -char g_materialFile[256] = "none"; // default for Heretic2 -char *g_outputDir; -extern char *g_publishDir; - -extern qboolean g_nomkdir; - -/* -======================================================= - - PAK FILES - -======================================================= -*/ - -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; - - - -/* -============== -BeginPak -============== -*/ -void BeginPak (char *outname) -{ - if (!g_pak) - return; - - pakfile = SafeOpenWrite (outname); - - // leave space for header - SafeWrite (pakfile, &pakheader, sizeof(pakheader)); - - pf = pfiles; -} - - -/* -============== -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) -{ - int len; - byte *buf; - char source[1024]; - char dest[1024]; - - if (!g_release) - return; - - sprintf (source, "%s%s", gamedir, filename); - - if (!g_pak) - { // copy it - sprintf (dest, "%s/%s", g_releasedir, filename); - printf ("copying to %s\n", dest); - QCopyFile (source, dest); - return; - } - - // pak it - printf ("paking %s\n", filename); - if (strlen(filename) >= sizeof(pf->name)) - Error ("Filename too long for pak: %s", filename); - - len = LoadFile (source, (void **)&buf); - - // segment moved to old.c - - strcpy (pf->name, filename); - pf->filepos = LittleLong(ftell(pakfile)); - pf->filelen = LittleLong(len); - pf++; - - SafeWrite (pakfile, buf, len); - - free (buf); -} - - -/* -============== -FinishPak -============== -*/ -void FinishPak (void) -{ - int dirlen; - int d; - int i; - unsigned checksum; - - if (!g_pak) - return; - - pakheader.id[0] = 'P'; - pakheader.id[1] = 'A'; - pakheader.id[2] = 'C'; - pakheader.id[3] = 'K'; - dirlen = (byte *)pf - (byte *)pfiles; - pakheader.dirofs = LittleLong(ftell(pakfile)); - pakheader.dirlen = LittleLong(dirlen); - - checksum = Com_BlockChecksum ( (void *)pfiles, dirlen ); - - SafeWrite (pakfile, pfiles, dirlen); - - i = ftell (pakfile); - - fseek (pakfile, 0, SEEK_SET); - SafeWrite (pakfile, &pakheader, sizeof(pakheader)); - fclose (pakfile); - - d = pf - pfiles; - printf ("%i files packed in %i bytes\n",d, i); - printf ("checksum: 0x%x\n", checksum); -} - - -/* -=============== -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) -{ - GetScriptToken (false); - 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 -#ifdef NeXT -#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 ; id_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) -{ - GetScriptToken (false); - 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 width height\n"); - } - return 0; - } -*/ else if (!strcmpi(argv[i], "-genskin")) - { - i++; - if (i < argc-3) - { - GenSkin(argv[i],argv[i+1],atol(argv[i+2]),atol(argv[i+3])); - } - else - { - printf("qdata -genskin \n"); - } - return 0; - - } - else if (!strcmpi(argv[i], "-noopts")) - { - g_no_opimizations = true; - printf("not performing optimizations\n"); - } - else if (!strcmpi(argv[i], "-md2")) - { - g_forcemodel = MODEL_MD2; - } - else if (!strcmpi(argv[i], "-fm")) - { - g_forcemodel = MODEL_FM; - } - else if (!strcmpi(argv[i], "-verbose")) - { - g_verbose = true; - } - else if (!strcmpi(argv[i], "-oldskin")) - { - g_allow_newskin = false; - } - else if (!strcmpi(argv[i], "-ignoreUV")) - { - g_ignoreTriUV = true; - } - else if (!strcmpi(argv[i], "-publish")) - { - g_publishOutput = true; - } - else if (!strcmpi(argv[i], "-nomkdir")) - { - g_nomkdir = true; - } - else if (argv[i][0] == '-') - Error ("Unknown option \"%s\"", argv[i]); - else - break; - } - - if (i >= argc) - { - Error ("usage: qdata [-archive ]\n" - " [-release ]\n" - " [-base ]\n" - " [-compress]\n" - " [-pak ]\n" - " [-only ]\n" - " [-keypress]\n" - " [-3ds]\n" - " [-materialfile ]\n" - " [-noopts]\n" - " [-md2]\n" - " [-fm]\n" - " [-verbose]\n" - " [-ignoreUV]\n" - " [-oldskin]\n" - " [-publish]\n" - " [-nomkdir]\n" - " file.qdt\n" - "or\n" - " qdata -genskin "); - } - - if (do3ds) - trifileext = ext_3ds; - else - trifileext = ext_tri; - - for ( ; i -#include -#include -#include -#include - -#include "cmdlib.h" -#include "inout.h" -#include "scriplib.h" -#include "mathlib.h" -#include "trilib.h" -#include "lbmlib.h" -#include "her2_threads.h" -#include "l3dslib.h" -#include "bspfile.h" - -#ifndef _WIN32 -#define stricmp strcasecmp -#define strcmpi strcasecmp -#endif - - -#define MODEL_AUTO 0 -#define MODEL_MD2 1 -#define MODEL_FM 2 - -// Model cover functions (to allow the forcing of a model type) -void MODELCMD_Modelname (int modeltype); -void MODELCMD_Cd (int modeltype); -void MODELCMD_Origin (int modeltype); -void MODELCMD_Jointed (int modeltype); -void MODELCMD_Cluster (int modeltype); -void MODELCMD_Base (int modeltype); -void MODELCMD_BaseST (int modeltype); -void MODELCMD_ScaleUp (int modeltype); -void MODELCMD_Frame (int modeltype); -void MODELCMD_Skin (int modeltype); -void MODELCMD_Skinsize (int modeltype); -void MODELCMD_Skeleton (int modeltype); -void MODELCMD_SkeletalFrame (int modeltype); -void MODELCMD_BeginGroup(int modeltype); -void MODELCMD_EndGroup(int modeltype); -void MODELCMD_Referenced(int modeltype); -void MODELCMD_NodeOrder(int modeltype); - -void Cmd_Modelname (void); -void Cmd_Base (void); -void Cmd_Cd (void); -void Cmd_Origin (void); -void Cmd_ScaleUp (void); -void Cmd_Frame (void); -void Cmd_Skin (void); -void Cmd_Skinsize (void); -void FinishModel (void); -void Cmd_Cluster (void); - -// Flexible Models -//void Cmd_FMModelname (void); -void Cmd_FMBase (qboolean GetST); -void Cmd_FMCd (void); -//void Cmd_FMOrigin (void); -void Cmd_FMCluster(); -void Cmd_FMSkeleton(); -//void Cmd_FMScaleUp (void); -void Cmd_FMFrame (void); -void Cmd_FMSkeletalFrame(); -void Cmd_FMSkin (void); -//void Cmd_FMSkinsize (void); -void Cmd_FMBeginGroup(void); -void Cmd_FMEndGroup(void); -void Cmd_FMReferenced(); -void Cmd_FMNodeOrder(void); -void FMFinishModel (void); -void GenSkin(char *ModelFile, char *OutputName, int Width, int Height); -void NewGen (char *ModelFile, char *OutputName, int width, int height); - - -void Cmd_Inverse16Table( void ); - -void Cmd_SpriteName (void); -void Cmd_Load (void); -void Cmd_SpriteFrame (void); -void Cmd_Sprdir (void); -void FinishSprite (void); - -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_Alphalight (void); - -void Cmd_Picdir (void); -void Cmd_Pic (void); - -void Cmd_Bookdir (void); -void Cmd_Book (void); - -void Cmd_TextureMix (void); - -void Cmd_Video (void); - -//void RemapZero (byte *pixels, byte *palette, int width, int height); - -void ReleaseFile (char *filename); - -extern byte *byteimage, *lbmpalette; -extern int byteimagewidth, byteimageheight; -extern qboolean TrueColorImage; -extern unsigned *longimage; -extern int longimagewidth, longimageheight; - -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_no_opimizations; -extern int g_forcemodel; -extern qboolean g_verbose; -extern qboolean g_allow_newskin; -extern qboolean g_ignoreTriUV; //from qdata.c -extern qboolean g_dokeypress; - -extern char *trifileext; - -extern char g_materialFile[256]; - -extern unsigned total_x; -extern unsigned total_y; -extern unsigned total_textures; - -miptex_t *CreateMip(byte *data, unsigned width, unsigned height, byte *palette, int *FinalSize, qboolean mip); -miptex32_t *CreateMip32(unsigned *data, unsigned width, unsigned height, int *FinalSize, qboolean mip); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/resource.h b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/resource.h deleted file mode 100644 index 14e2fb5b..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/resource.h +++ /dev/null @@ -1,18 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Developer Studio generated include file. -// Used by Script1.rc -// -#define IDI_ICON1 101 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NO_MFC 1 -#define _APS_3D_CONTROLS 1 -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1000 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/script1.aps b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/script1.aps deleted file mode 100644 index 6650b67c..00000000 Binary files a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/script1.aps and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/script1.rc b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/script1.rc deleted file mode 100644 index 7d053745..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/script1.rc +++ /dev/null @@ -1,115 +0,0 @@ -//Microsoft Developer Studio generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (U.S.) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -#ifdef _WIN32 -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_ICON1 ICON DISCARDABLE "icon1.ico" - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -#ifndef _MAC -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x1L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904b0" - BEGIN - VALUE "Comments", "Heavily modified from original ID tool\0" - VALUE "CompanyName", "Raven Software\0" - VALUE "FileDescription", "qdata\0" - VALUE "FileVersion", "2.0\0" - VALUE "InternalName", "qdata\0" - VALUE "LegalCopyright", "Copyright © 1998\0" - VALUE "OriginalFilename", "qdata.exe\0" - VALUE "ProductName", "Raven Software qdata\0" - VALUE "ProductVersion", "2.0\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1200 - END -END - -#endif // !_MAC - -#endif // English (U.S.) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/sprites.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/sprites.c deleted file mode 100644 index bd9d8bf2..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/sprites.c +++ /dev/null @@ -1,349 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" - -#define MAX_SPRFRAMES MAX_MD2SKINS - -dsprite_t sprite; -dsprframe_t frames[MAX_SPRFRAMES]; - -byte *byteimage, *lbmpalette; -int byteimagewidth, byteimageheight; - -qboolean TrueColorImage; -unsigned *longimage; -int longimagewidth, longimageheight; - -char spritename[1024]; - - -void FinishSprite (void); -void Cmd_Spritename (void); - -char spr_prefix[1024]; -char pic_prefix[1024]; - -extern char *g_outputDir; - - -/* -============== -FinishSprite -============== -*/ -void FinishSprite (void) -{ - FILE *spriteouthandle; - int i, curframe; - dsprite_t spritetemp; - char savename[1024]; - - if (sprite.numframes == 0) - return; - - if (!strlen(spritename)) - Error ("Didn't name sprite file"); - - sprintf (savename, "%sSprites/%s/%s.sp2", g_outputDir, spr_prefix, spritename); - - if (g_release) - { - char name[1024]; - - sprintf (name, "%s.sp2", spritename); - ReleaseFile (name); - spritename[0] = 0; // clear for a new sprite - sprite.numframes = 0; - return; - } - - - printf ("saving in %s\n", savename); - CreatePath (savename); - spriteouthandle = SafeOpenWrite (savename); - - -// -// write out the sprite header -// - spritetemp.ident = LittleLong (IDSPRITEHEADER); - spritetemp.version = LittleLong (SPRITE_VERSION); - spritetemp.numframes = LittleLong (sprite.numframes); - - SafeWrite (spriteouthandle, &spritetemp, 12); - -// -// write out the frames -// - curframe = 0; - - for (i=0 ; i 256) || (h > 256)) - Error ("Sprite has a dimension longer than 256"); - - xh = xl+w; - yh = yl+h; - - if (sprite.numframes >= MAX_SPRFRAMES) - Error ("Too many frames; increase MAX_SPRFRAMES\n"); - - pframe = &frames[sprite.numframes]; - pframe->width = w; - pframe->height = h; - pframe->origin_x = ox; - pframe->origin_y = oy; - - if (g_release) - { - ReleaseFile (pframe->name); - return; - } - - if (TrueColorImage) - { - sprintf (filename, "%ssprites/%s/%s_%i.m32", g_outputDir, spr_prefix, spritename, sprite.numframes); - sprintf (pframe->name, "%s/%s_%i.m32", spr_prefix, spritename, sprite.numframes); - - if (g_release) - return; // textures are only released by $maps - - xh = xl+w; - yh = yl+h; - - if (xl >= longimagewidth || xh > longimagewidth || - yl >= longimageheight || yh > longimageheight) - { - Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,longimagewidth,longimageheight); - } - - sourcel = longimage + (yl*longimagewidth) + xl; - destl = bufferl; - linedelta = (longimagewidth - w); - - for (y=yl ; ycontents = 0; - qtex32->value = 0; - strcpy(qtex32->name, pframe->name); - // - // write it out - // - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex32, size); - - free (qtex32); - } - else - { - sprintf (filename, "%ssprites/%s/%s_%i.m8", g_outputDir, spr_prefix, spritename, sprite.numframes); - sprintf (pframe->name, "%s/%s_%i.m8", spr_prefix, spritename, sprite.numframes); - - if (g_release) - return; // textures are only released by $maps - - xh = xl+w; - yh = yl+h; - - if (xl >= byteimagewidth || xh > byteimagewidth || - yl >= byteimageheight || yh > byteimageheight) - { - Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); - } - - source = byteimage + yl*byteimagewidth + xl; - dest = buffer; - linedelta = byteimagewidth - w; - - for (y=yl ; yflags = 0; - qtex->contents = 0; - qtex->value = 0; - strcpy(qtex->name, pframe->name); - // - // write it out - // - printf ("writing %s\n", filename); - SaveFile (filename, (byte *)qtex, size); - - free (qtex); - } - - sprite.numframes++; -} - - -/* -============== -Cmd_SpriteName -============== -*/ -void Cmd_SpriteName (void) -{ - if (sprite.numframes) - FinishSprite (); - - GetScriptToken (false); - strcpy (spritename, token); - memset (&sprite, 0, sizeof(sprite)); - memset (&frames, 0, sizeof(frames)); -} - - -/* -=============== -Cmd_Sprdir -=============== -*/ -void Cmd_Sprdir (void) -{ - char filename[1024]; - - GetScriptToken (false); - strcpy (spr_prefix, token); - // create the directory if needed - sprintf (filename, "%sSprites", g_outputDir); - Q_mkdir (filename); - sprintf (filename, "%sSprites/%s", g_outputDir, spr_prefix); - Q_mkdir (filename); -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/svdcmp.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/svdcmp.c deleted file mode 100644 index 04ac7230..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/svdcmp.c +++ /dev/null @@ -1,490 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#include -#include -#include - -static double at,bt,ct; -#define PYTHAG(a,b) ((at=fabs(a)) > (bt=fabs(b)) ? \ - (ct=bt/at,at*sqrt(1.0+ct*ct)) : (bt ? (ct=at/bt,bt*sqrt(1.0+ct*ct)): 0.0)) - - static double maxarg1,maxarg2; -#define MAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\ - (maxarg1) : (maxarg2)) -#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) - -void ntrerror(char *s) -{ - printf("%s\n",s); - exit(1); -} - -double *allocVect(int sz) -{ - double *ret; - - ret = calloc(sizeof(double), (size_t)sz); - return ret; -} - -void freeVect(double *ret) -{ - free(ret); -} - -double **allocMatrix(int r,int c) -{ - double **ret; - - ret = calloc(sizeof(double), (size_t)(r*c)); - return ret; -} - -void freeMatrix(double **ret,int r) -{ - free(ret); -} - -void svdcmp(double** a, int m, int n, double* w, double** v) -{ - int flag,i,its,j,jj,k,l,nm; - double c,f,h,s,x,y,z; - double anorm=0.0,g=0.0,scale=0.0; - double *rv1; - void nrerror(); - - if (m < n) ntrerror("SVDCMP: You must augment A with extra zero rows"); - rv1=allocVect(n); - for (i=1;i<=n;i++) { - l=i+1; - rv1[i]=scale*g; - g=s=scale=0.0; - if (i <= m) { - for (k=i;k<=m;k++) scale += fabs(a[k][i]); - if (scale) { - for (k=i;k<=m;k++) { - a[k][i] /= scale; - s += a[k][i]*a[k][i]; - } - f=a[i][i]; - g = -SIGN(sqrt(s),f); - h=f*g-s; - a[i][i]=f-g; - if (i != n) { - for (j=l;j<=n;j++) { - for (s=0.0,k=i;k<=m;k++) s += a[k][i]*a[k][j]; - f=s/h; - for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; - } - } - for (k=i;k<=m;k++) a[k][i] *= scale; - } - } - w[i]=scale*g; - g=s=scale=0.0; - if (i <= m && i != n) { - for (k=l;k<=n;k++) scale += fabs(a[i][k]); - if (scale) { - for (k=l;k<=n;k++) { - a[i][k] /= scale; - s += a[i][k]*a[i][k]; - } - f=a[i][l]; - g = -SIGN(sqrt(s),f); - h=f*g-s; - a[i][l]=f-g; - for (k=l;k<=n;k++) rv1[k]=a[i][k]/h; - if (i != m) { - for (j=l;j<=m;j++) { - for (s=0.0,k=l;k<=n;k++) s += a[j][k]*a[i][k]; - for (k=l;k<=n;k++) a[j][k] += s*rv1[k]; - } - } - for (k=l;k<=n;k++) a[i][k] *= scale; - } - } - anorm=MAX(anorm,(fabs(w[i])+fabs(rv1[i]))); - } - for (i=n;i>=1;i--) { - if (i < n) { - if (g) { - for (j=l;j<=n;j++) - v[j][i]=(a[i][j]/a[i][l])/g; - for (j=l;j<=n;j++) { - for (s=0.0,k=l;k<=n;k++) s += a[i][k]*v[k][j]; - for (k=l;k<=n;k++) v[k][j] += s*v[k][i]; - } - } - for (j=l;j<=n;j++) v[i][j]=v[j][i]=0.0; - } - v[i][i]=1.0; - g=rv1[i]; - l=i; - } - for (i=n;i>=1;i--) { - l=i+1; - g=w[i]; - if (i < n) - for (j=l;j<=n;j++) a[i][j]=0.0; - if (g) { - g=1.0/g; - if (i != n) { - for (j=l;j<=n;j++) { - for (s=0.0,k=l;k<=m;k++) s += a[k][i]*a[k][j]; - f=(s/a[i][i])*g; - for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; - } - } - for (j=i;j<=m;j++) a[j][i] *= g; - } else { - for (j=i;j<=m;j++) a[j][i]=0.0; - } - ++a[i][i]; - } - for (k=n;k>=1;k--) { - for (its=1;its<=30;its++) { - flag=1; - for (l=k;l>=1;l--) { - nm=l-1; - if (fabs(rv1[l])+anorm == anorm) { - flag=0; - break; - } - if (fabs(w[nm])+anorm == anorm) break; - } - if (flag) { - c=0.0; - s=1.0; - for (i=l;i<=k;i++) { - f=s*rv1[i]; - if (fabs(f)+anorm != anorm) { - g=w[i]; - h=PYTHAG(f,g); - w[i]=h; - h=1.0/h; - c=g*h; - s=(-f*h); - for (j=1;j<=m;j++) { - y=a[j][nm]; - z=a[j][i]; - a[j][nm]=y*c+z*s; - a[j][i]=z*c-y*s; - } - } - } - } - z=w[k]; - if (l == k) { - if (z < 0.0) { - w[k] = -z; - for (j=1;j<=n;j++) v[j][k]=(-v[j][k]); - } - break; - } - if (its == 30) ntrerror("No convergence in 30 SVDCMP iterations"); - x=w[l]; - nm=k-1; - y=w[nm]; - g=rv1[nm]; - h=rv1[k]; - f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y); - g=PYTHAG(f,1.0); - f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x; - c=s=1.0; - for (j=l;j<=nm;j++) { - i=j+1; - g=rv1[i]; - y=w[i]; - h=s*g; - g=c*g; - z=PYTHAG(f,h); - rv1[j]=z; - c=f/z; - s=h/z; - f=x*c+g*s; - g=g*c-x*s; - h=y*s; - y=y*c; - for (jj=1;jj<=n;jj++) { - x=v[jj][j]; - z=v[jj][i]; - v[jj][j]=x*c+z*s; - v[jj][i]=z*c-x*s; - } - z=PYTHAG(f,h); - w[j]=z; - if (z) { - z=1.0/z; - c=f*z; - s=h*z; - } - f=(c*g)+(s*y); - x=(c*y)-(s*g); - for (jj=1;jj<=m;jj++) { - y=a[jj][j]; - z=a[jj][i]; - a[jj][j]=y*c+z*s; - a[jj][i]=z*c-y*s; - } - } - rv1[l]=0.0; - rv1[k]=f; - w[k]=x; - } - } - freeVect(rv1); -} - - - -void svbksb(double** u, double* w, double** v,int m, int n, double* b, double* x) -{ - int jj,j,i; - double s,*tmp; - tmp=allocVect(n); - for (j=1;j<=n;j++) - { - s=0.0; - if (w[j]) - { - for (i=1;i<=m;i++) - s += u[i][j]*b[i]; - s /= w[j]; - } - tmp[j]=s; - } - for (j=1;j<=n;j++) - { - s=0.0; - for (jj=1;jj<=n;jj++) - s += v[j][jj]*tmp[jj]; - x[j]=s; - } - freeVect(tmp); -} - -#undef SIGN -#undef MAX -#undef PYTHAG - - -#if 1 -void DOsvd(float *a,float *res,float *comp,float *values,int nframes,int framesize,int compressedsize) -{ - int usedfs; - int *remap; - int i,j; - double **da; - double **v; - double *w; - int DOFerr; - float mx; - int bestat; - - if (nframes>framesize) - usedfs=nframes; - else - usedfs=framesize; - - da=allocMatrix(usedfs,nframes); - v=allocMatrix(nframes,nframes); - w=allocVect(nframes); - - DOFerr = 0; //false - for (i=0;imx) - { - mx=(float) fabs(w[i+1]); - bestat=i; - } - } - - if(mx>0) - { - remap[bestat]=j; - } - else - { - DOFerr = 1; //true - } - } - - if(DOFerr) - { - printf("Warning: To many degrees of freedom! File size may increase\n"); - - for (i=0;imx) - { - mx=fabs(w[i+1]); - bestat=i; - } - } - assert(mx>-.5f); - remap[bestat]=j; - } - // josh **DO NOT** put your dof>nframes mod here - for (i=0;i=3); - base[0]=pnts[0]; - base[1]=pnts[1]; - base[2]=pnts[2]; - for (i=1;i> 5 ) & 63 ) << 2; - b[0] = ( ( color >> 11 ) & 31 ) << 3; - - for ( i = 0; i < 256; i++ ) - { - r[1] = ( d_8to24table[i] >> 0 ) & 0xFF; - g[1] = ( d_8to24table[i] >> 8 ) & 0xFF; - b[1] = ( d_8to24table[i] >> 16 ) & 0xFF; - - d = ( r[1] - r[0] ) * ( r[1] - r[0] ) + - ( g[1] - g[0] ) * ( g[1] - g[0] ) + - ( b[1] - b[0] ) * ( b[1] - b[0] ); - - if ( d < closest_distance_so_far ) - { - closest_distance_so_far = d; - closest_so_far = i; - } - } - - return closest_so_far; -} -*/ - -extern byte BestColor( int, int, int, int, int ); - -void Inverse16_BuildTable( void ) -{ - int i; - - /* - ** create the 16-to-8 table - */ - for ( i = 0; i < 65536; i++ ) - { - int r = i & 31; - int g = ( i >> 5 ) & 63; - int b = ( i >> 11 ) & 31; - - r <<= 3; - g <<= 2; - b <<= 3; - - inverse16to8table[i] = BestColor( r, g, b, 0, 255 ); - } -} - -void Alphalight_Thread (int i) -{ - int j; - float r, g, b; - float mr, mg, mb, ma; - float distortion, bestdistortion; - float v; - - r = (i>>10) * (1.0/16); - g = ((i>>5)&31) * (1.0/16); - b = (i&31) * (1.0/16); - - bestdistortion = 999999; - for (j=0 ; j<16*16*16*16 ; j++) - { - mr = (j>>12) * (1.0/16); - mg = ((j>>8)&15) * (1.0/16); - mb = ((j>>4)&15) * (1.0/16); - ma = (j&15) * (1.0/16); - - v = r * 0.5 - (mr*ma + 0.5*(1.0-ma)); - distortion = v*v; - v = g * 0.5 - (mg*ma + 0.5*(1.0-ma)); - distortion += v*v; - v = b * 0.5 - (mb*ma + 0.5*(1.0-ma)); - distortion += v*v; - - distortion *= 1.0 + ma*4; - - if (distortion < bestdistortion) - { - bestdistortion = distortion; - alphamap[i] = j; - } - } -} - -void Cmd_Alphalight (void) -{ - char savename[1024]; - - GetScriptToken (false); - - if (g_release) - { - ReleaseFile (token); - return; - } - - sprintf (savename, "%s%s", gamedir, token); - printf ("Building alphalight table...\n"); - - RunThreadsOnIndividual (32*32*32, true, Alphalight_Thread); - - SaveFile (savename, (byte *)alphamap, sizeof(alphamap)); -} - - -void Cmd_Inverse16Table( void ) -{ - char savename[1024]; - - if ( g_release ) - { - sprintf (savename, "pics/16to8.dat"); - ReleaseFile( savename ); - return; - } - - sprintf (savename, "%spics/16to8.dat", gamedir); - printf ("Building inverse 16-to-8 table...\n"); - - Inverse16_BuildTable(); - - SaveFile( savename, (byte *) inverse16to8table, sizeof( inverse16to8table ) ); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/tmix.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/tmix.c deleted file mode 100644 index ac1b2f30..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/tmix.c +++ /dev/null @@ -1,698 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "qdata.h" -#include "flex.h" - -#define MAXFILES 2048 - -typedef struct -{ - int x; - int y; - int w; - int h; - int cw; - int ch; - int rw; - int index; - int depth; - int col; - int baseline; - char name[128]; -} Coords; - -int filenum; -int valid; -Coords in[MAXFILES]; -Coords out; -char outscript[256]; -char sourcedir[256]; -char outusage[256]; -char root[32]; - -int destsize = 0; -byte *pixels = NULL; // Buffer to load image -long *outpixels = NULL; // Buffer to store combined textures -long *usagemap = NULL; // Buffer of usage map -void *bmptemp = NULL; // Buffer of usage map -byte *map = NULL; - -int xcharsize; -int ycharsize; -int dosort = 0; -int missed = 0; -int overlap = 0; -int nobaseline = 0; -int percent; - -////////////////////////////////////////////////// -// Setting the char based usage map // -////////////////////////////////////////////////// - -byte TryPlace(Coords *coord) -{ - int x, y; - byte entry = 0; - byte *mapitem; - - mapitem = map + (coord->x / xcharsize) + ((coord->y / ycharsize) * out.cw); - - for (y = 0; y < coord->ch; y++, mapitem += out.cw - coord->cw) - { - for (x = 0; x < coord->cw; x++) - { - if (entry |= *mapitem++ & 8) - { - return(entry); - } - } - } - return(entry); -} - -void SetMap(Coords *coord) -{ - int x, y; - byte *mapitem; - - mapitem = map + (coord->x / xcharsize) + ((coord->y / ycharsize) * out.cw); - - for (y = 0; y < coord->ch; y++, mapitem += out.cw - coord->cw) - for (x = 0; x < coord->cw; x++) - *mapitem++ |= 8; -} - -////////////////////////////////////////////////// -// Setting the pixel based usage map // -////////////////////////////////////////////////// - -void CheckOverlap(Coords *coord) -{ - int x; - int y; - long *dest; - - x = coord->x; - y = coord->y; - - dest = (long *)(usagemap + x + (y * out.w)); - - for (y = 0; y < coord->h; y++, dest += out.w - coord->w) - { - for (x = 0; x < coord->w; x++) - { - if (*dest++) - { - overlap++; - return; - } - } - } -} - -void SetUsageMap(Coords *coord) -{ - int x; - int y; - long *dest; - - x = coord->x; - y = coord->y; - - dest = (long *)(usagemap + x + (y * out.w)); - - for (y = 0; y < coord->h; y++, dest += out.w - coord->w) - { - for (x = 0; x < coord->w; x++) - { - *dest++ = coord->col; - } - } -} - -////////////////////////////////////////////////// -// Flips the BMP image to the correct way up // -////////////////////////////////////////////////// - -void CopyLine(byte *dest, byte *src, int size) -{ - int x; - - for (x = 0; x < size; x++) - *dest++ = *src++; -} - -/****************************************************/ -/* Printing headers etc */ -/****************************************************/ - -void RemoveLeading(char *name) -{ - int i; - char temp[128]; - - for(i = strlen(name) - 1; i > 0; i--) - { - if((name[i] == '\\') || (name[i] == '/')) - { - strcpy(temp, name + i + 1); - strcpy(name, temp); - return; - } - } -} - -void RemoveExt(char *name) -{ - while ((*name != '.') && *name) - name++; - *name = 0; -} - -/****************************************************/ -/* Misc calcualtions */ -/****************************************************/ - -int TotalArea() -{ - int i; - int total = 0; - - for (i = 0; i < (filenum + 2); i++) - total += in[i].w * in[i].h; - - return(total); -} - -/****************************************************/ -/* Setup and checking of all info */ -/****************************************************/ - -void InitVars() -{ - filenum = 0; - valid = 0; - dosort = 0; - missed = 0; - overlap = 0; - nobaseline = 0; - - memset(outscript, 0, sizeof(outscript)); - memset(outscript, 0, sizeof(sourcedir)); - memset(outscript, 0, sizeof(outusage)); - memset(outscript, 0, sizeof(root)); - - memset(in, 0, sizeof(in)); - memset(&out, 0, sizeof(out)); -} -void Cleanup() -{ - if (pixels) - free(pixels); - if (usagemap) - free(usagemap); - if (outpixels) - free(outpixels); - if (bmptemp) - free(bmptemp); - if (map) - free(map); -} - -typedef struct glxy_s -{ - float xl, yt, xr, yb; - int w, h, baseline; -} glxy_t; - -int SaveScript(char *name) -{ - FILE *fp; - int i, j; - glxy_t buff; - - if(fp = fopen(name, "wb")) - { - for (j = 0; j < filenum; j++) - { - for (i = 0; i < filenum; i++) - { - if (in[i].index == j) - { - if (in[i].depth) - { - buff.xl = (float)in[i].x / (float)out.w; - buff.yt = (float)in[i].y / (float)out.h; - buff.xr = ((float)in[i].w + (float)in[i].x) / (float)out.w; - buff.yb = ((float)in[i].h + (float)in[i].y) / (float)out.h; - buff.w = in[i].w; - buff.h = in[i].h; - buff.baseline = in[i].baseline; - } - else - { - memset(&buff, 0, sizeof(glxy_t)); - } - fwrite(&buff, 1, sizeof(glxy_t), fp); - i = filenum; - } - } - } - fclose(fp); - return(true); - } - else - return(false); -} - -int GetScriptInfo(char *name) -{ - FILE *fp; - char buffer[256]; - char tempbuff[256]; - char delims[] = {" \t,\n"}; - - printf("Opening script file %s.\n", name); - - if (fp = fopen(name, "r")) - { - while(fgets(buffer, 256, fp)) - { - if (strncmp(buffer, "//", 2) && strncmp(buffer, "\n", 1)) - { - strupr(buffer); - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "OUTPUT") == 0) - { - strcpy(out.name, strtok(NULL, delims)); - strlwr(out.name); - } - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "SOURCEDIR") == 0) - { - strcpy(tempbuff, strtok(NULL, delims)); - strcpy(sourcedir, ExpandPathAndArchive(tempbuff)); - } - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "DOSORT") == 0) - dosort = 1; - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "XCHARSIZE") == 0) - xcharsize = strtol(strtok(NULL, delims), NULL, 0); - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "YCHARSIZE") == 0) - ycharsize = strtol(strtok(NULL, delims), NULL, 0); - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "OUTSCRIPT") == 0) - { - strcpy(outscript, strtok(NULL, delims)); - strlwr(outscript); - } - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "OUTUSAGE") == 0) - strcpy(outusage, strtok(NULL, delims)); - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "POS") == 0) - { - out.w = strtol(strtok(NULL, delims), NULL, 0); - out.h = strtol(strtok(NULL, delims), NULL, 0); - } - - strcpy(tempbuff, buffer); - if (strcmp(strtok(tempbuff, delims), "FILE") == 0) - { - strcpy(in[filenum].name, strtok(NULL, delims)); - in[filenum].x = strtol(strtok(NULL, delims), NULL, 0); - in[filenum].y = strtol(strtok(NULL, delims), NULL, 0); - in[filenum].col = strtol(strtok(NULL, delims), NULL, 0); - filenum++; - } - } - } - fclose(fp); - return(true); - } - else - { - printf("ERROR : Could not open script file.\n"); - return(false); - } -} - -int CheckVars() -{ - int i; - - if (out.name[0] == 0) - { - printf("ERROR : No output name specified.\n"); - return(false); - } - if ((out.w <= 0) || (out.h <= 0)) - { - printf("ERROR : Invalid VRAM coordinates.\n"); - return(false); - } - if (filenum == 0) - { - printf("ERROR : No input files specified.\n"); - return(false); - } - for (i = 0; i < filenum; i++) - if (in[i].name[0] == 0) - { - printf("ERROR : Input filename invalid.\n"); - return(false); - } - return(true); -} - -// Makes sure texture is totally within the output area - -int CheckCoords(Coords *coord) -{ - if ((coord->x + coord->w) > out.w) - return(false); - if ((coord->y + coord->h) > out.h) - return(false); - - return(true); -} -// Gets the width, height, palette width and palette height of each BMP file - -int GetFileDimensions() -{ - int i; - int width, height; - char name[128]; - - for (i = 0; i < filenum; i++) - { - in[i].index = i; - - strcpy(name, sourcedir); - strcat(name, in[i].name); - printf("Getting file dimensions, file : %s \r", in[i].name); - if(FileExists(name)) - { - LoadAnyImage(name, NULL, NULL, &width, &height); - in[i].depth = 32; - in[i].rw = width; - in[i].w = width; // makes it width in - in[i].h = height; - in[i].cw = (in[i].w + (xcharsize - 1)) / xcharsize; - in[i].ch = (in[i].h + (ycharsize - 1)) / ycharsize; - - if (!CheckCoords(&in[i]) && (in[i].x >= 0)) - { - printf("Error : texture %s out of bounds.\n", in[i].name); - return(false); - } - valid++; - } - else - { - in[i].depth = 0; - in[i].x = -1; - in[i].y = -1; - in[i].w = 0; - in[i].h = 0; - } - } - printf("\n\n"); - return(true); -} - -// Sorts files into order for optimal space finding -// Fixed position ones first, followed by the others in descending size -// The theory being that it is easier to find space for smaller textures. -// size = (width + height) -// For space finding it is easier to place a 32x32 than a 128x2 - -#define WEIGHT 0x8000 - -void Swap(Coords *a, Coords *b) -{ - Coords c; - - c = *a; - *a = *b; - *b = c; -} - -void SortInNames() -{ - int i, j; - int largest, largcount; - int size; - - printf("Sorting filenames by size.\n\n"); - - for (j = 0; j < filenum; j++) - { - largest = -1; - largcount = -1; - - for (i = j; i < filenum; i++) - { - if (in[i].depth) - { - size = in[i].w + in[i].h; - - if ((in[i].x < 0) && (size > largest)) - { - largcount = i; - largest = size; - } - } - } - if ((largcount >= 0) && (largcount != j)) - Swap(&in[j], &in[largcount]); - } -} - -int SetVars(char *name) -{ - if (!GetScriptInfo(name)) - return(false); - - if (!CheckVars()) - return(false); - - destsize = out.w * out.h; - - out.cw = out.w / xcharsize; - out.ch = out.h / ycharsize; - - if ((usagemap = (long *)SafeMalloc(destsize * 4, "")) == NULL) - return(false); - if ((outpixels = (long *)SafeMalloc(destsize * 4, "")) == NULL) - return(false); - if ((bmptemp = (void *)SafeMalloc(destsize * 4, "")) == NULL) - return(false); - if ((map = (byte *)SafeMalloc(destsize / (xcharsize * ycharsize), "")) == NULL) - return(false); - - if (GetFileDimensions() == false) - return(false); - - if (dosort) - SortInNames(); - - return(true); -} -/****************************************************/ -/* Actual copying routines */ -/****************************************************/ - -int FindCoords(Coords *coord) -{ - int tx, ty; - - if (coord->x >= 0) - { - SetMap(coord); - return(true); - } - else - { - for (ty = 0; ty < out.ch; ty++) - { - for (tx = 0; tx < out.cw; tx++) - { - coord->x = (tx * xcharsize); - coord->y = (ty * ycharsize); - - if (CheckCoords(coord) && !TryPlace(coord)) - { - SetMap(coord); - return(true); - } - } - } - } - coord->x = -1; - coord->y = -1; - - return(false); -} - -void CheckBaseline(int i) -{ - int y; - long *pix; - - in[i].baseline = -1; - pix = (long *)pixels; - - for(y = 0; y < in[i].h; y++, pix += in[i].w) - { - if((*pix & 0x00ffffff) == 0x00ff00ff) - { - in[i].baseline = y; - break; - } - } - pix = (long *)pixels; - for(y = 0; y < in[i].w * in[i].h; y++, pix++) - { - if((*pix & 0x00ffffff) == 0x00ff00ff) - { - *pix = 0; - } - } - - if(in[i].baseline == -1) - { - printf("\nERROR : %s has no baseline\n", in[i].name); - nobaseline++; - } -} - -void CopyToMain32(Coords *coord) -{ - int x; - int y; - long *source; - long *dest; - - x = coord->x; - y = coord->y; - - source = (long *)pixels; - dest = (long *)(outpixels + x + (y * out.w)); - - for (y = 0; y < coord->h; y++, dest += out.w - coord->w) - { - for (x = 0; x < coord->w; x++) - { - *dest++ = *source++; - } - } -} - -void CreateMain() -{ - int i, count; - int width, height; - char name[128]; - - for (i = 0, count = 0; i < filenum; i++) - { - if (in[i].depth) - { - printf("\rProcessing %d of %d (%d missed, %d overlapping, %d nobase)\r", count + 1, valid, missed, overlap, nobaseline); - count++; - if (!FindCoords(&in[i])) - missed++; - else - { - strcpy(name, sourcedir); - strcat(name, in[i].name); - LoadAnyImage(name, &pixels, NULL, &width, &height); - CheckBaseline(i); - CheckOverlap(&in[i]); - CopyToMain32(&in[i]); - SetUsageMap(&in[i]); - } - } - } -} - -void Cmd_TextureMix() -{ - miptex32_t *qtex32; - char filename[1024]; - int size; - - InitVars(); - - GetScriptToken (false); - - strcpy(root, token); - RemoveExt(root); - RemoveLeading(root); - - strcpy(filename, ExpandPathAndArchive(token)); - if (SetVars(filename)) - { - // Create combined texture - percent = ((TotalArea() * 100) / (out.w * out.h)); - printf("Total area consumed : %d%%\n", percent); - printf("Texture resolution : %dx%d pixels.\n", xcharsize, ycharsize); - CreateMain(); - - // Save image as m32 - sprintf (filename, "%spics/misc/%s.m32", gamedir, out.name); - qtex32 = CreateMip32((unsigned *)outpixels, out.w, out.h, &size, false); - - qtex32->contents = 0; - qtex32->value = 0; - qtex32->scale_x = 1.0; - qtex32->scale_y = 1.0; - sprintf (qtex32->name, "misc/%s", out.name); - - printf ("\n\nwriting %s\n", filename); - SaveFile (filename, (byte *)qtex32, size); - free (qtex32); - - // Save out script file - sprintf (filename, "%spics/misc/%s.fnt", gamedir, outscript); - printf("Writing %s as script file\n", filename); - if (!SaveScript(filename)) - { - printf("Unable to save output script.\n"); - } - } - printf("Everythings groovy.\n"); - Cleanup(); -} - -// end - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/video.c b/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/video.c deleted file mode 100644 index 181a9735..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake2/qdata_heretic2/video.c +++ /dev/null @@ -1,1149 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -// To do - -// Sound error handling (when sound too short) -// rle b4 huffing -// adpcm encoding of sound - -#if 0 -#include "qdata.h" -#include "flex.h" -#include "fc.h" -#include "adpcm.h" - -#define MIN_REPT 15 -#define MAX_REPT 0 -#define HUF_TOKENS (256 + MAX_REPT) - -#define BLOCKSIZE 8 - -#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h -#define SQRT2 1.414213562 - -typedef struct hnode_s -{ - int count; - qboolean used; - int children[2]; -} hnode_t; - -typedef struct -{ - int rate; - int width; - int channels; - int loopstart; - int samples; - int dataofs; // chunk starts this many bytes from file start -} wavinfo_t; - -// These weren`t picked out my ass.... -// They were defined at http://www.rahul.net/jfm/dct.html -// However, I think he plucked them out of his ass..... - -float Quantise[BLOCKSIZE * BLOCKSIZE]; - -float LUT_Quantise[BLOCKSIZE * BLOCKSIZE] = -{ - 16.0F/16.0F, 11.0F/16.0F, 10.0F/16.0F, 16.0F/16.0F, 24.0F/16.0F, 40.0F/16.0F, 51.0F/16.0F, 61.0F/16.0F, - 12.0F/16.0F, 13.0F/16.0F, 14.0F/16.0F, 19.0F/16.0F, 26.0F/16.0F, 58.0F/16.0F, 60.0F/16.0F, 55.0F/16.0F, - 14.0F/16.0F, 13.0F/16.0F, 16.0F/16.0F, 24.0F/16.0F, 40.0F/16.0F, 57.0F/16.0F, 69.0F/16.0F, 56.0F/16.0F, - 14.0F/16.0F, 17.0F/16.0F, 22.0F/16.0F, 29.0F/16.0F, 51.0F/16.0F, 87.0F/16.0F, 80.0F/16.0F, 62.0F/16.0F, - 18.0F/16.0F, 22.0F/16.0F, 37.0F/16.0F, 56.0F/16.0F, 68.0F/16.0F,109.0F/16.0F,103.0F/16.0F, 77.0F/16.0F, - 24.0F/16.0F, 35.0F/16.0F, 55.0F/16.0F, 64.0F/16.0F, 81.0F/16.0F,104.0F/16.0F,113.0F/16.0F, 92.0F/16.0F, - 49.0F/16.0F, 64.0F/16.0F, 78.0F/16.0F, 87.0F/16.0F,103.0F/16.0F,121.0F/16.0F,120.0F/16.0F,101.0F/16.0F, - 72.0F/16.0F, 92.0F/16.0F, 95.0F/16.0F, 98.0F/16.0F,112.0F/16.0F,100.0F/16.0F,103.0F/16.0F, 99.0F/16.0F -}; - -int LUT_ZZ[BLOCKSIZE * BLOCKSIZE] = -{ - 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 -}; - -char base[32]; - -byte *soundtrack; - -byte scaled[256][HUF_TOKENS]; -unsigned int charbits1[256][HUF_TOKENS]; -int charbitscount1[256][HUF_TOKENS]; -hnode_t hnodes1[256][HUF_TOKENS * 2]; -int numhnodes1[256]; -int order0counts[256]; -int numhnodes; -hnode_t hnodes[512]; -unsigned charbits[256]; -int charbitscount[256]; - -CineHead_t cinehead; - -byte *data_p; -byte *iff_end; -byte *last_chunk; -byte *iff_data; -int iff_chunk_len; - -float dctbase[BLOCKSIZE][BLOCKSIZE]; -float red[BLOCKSIZE * BLOCKSIZE]; -float green[BLOCKSIZE * BLOCKSIZE]; -float blue[BLOCKSIZE * BLOCKSIZE]; -float temp[BLOCKSIZE * BLOCKSIZE]; - -wavinfo_t wavinfo; -adpcm_t adpcm; - -/* -=============================================================================== - -WAV loading - -=============================================================================== -*/ - -/* Intel ADPCM step variation table */ -static int indexTable[16] = -{ - -1, -1, -1, -1, 2, 4, 6, 8, - -1, -1, -1, -1, 2, 4, 6, 8, -}; - -static int stepsizeTable[89] = -{ - 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, - 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, - 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, - 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, - 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, - 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, - 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, - 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, - 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 -}; - -#if 0 -static void adpcm_decoder(char *indata, short *outdata, int len, adpcm_state_t *state) -{ - signed char *inp; /* Input buffer pointer */ - short *outp; /* output buffer pointer */ - int sign; /* Current adpcm sign bit */ - int delta; /* Current adpcm output value */ - int step; /* Stepsize */ - int valpred; /* Predicted value */ - int vpdiff; /* Current change to valpred */ - int index; /* Current step change index */ - int inputbuffer; /* place to keep next 4-bit value */ - int bufferstep; /* toggle between inputbuffer/input */ - - outp = outdata; - inp = (signed char *)indata; - - valpred = state->valprev; - index = state->index; - step = stepsizeTable[index]; - - bufferstep = 0; - - for(; len > 0; len--) - { - /* Step 1 - get the delta value */ - if (bufferstep) - delta = inputbuffer & 0xf; - else - { - inputbuffer = *inp++; - delta = (inputbuffer >> 4) & 0xf; - } - bufferstep = !bufferstep; - - /* Step 2 - Find new index value (for later) */ - index += indexTable[delta]; - if(index < 0) - index = 0; - if(index > 88) - index = 88; - - /* Step 3 - Separate sign and magnitude */ - sign = delta & 8; - delta = delta & 7; - - /* Step 4 - Compute difference and new predicted value */ - /* - ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment - ** in adpcm_coder. - */ - vpdiff = step >> 3; - if(delta & 4) - vpdiff += step; - if(delta & 2) - vpdiff += step>>1; - if(delta & 1) - vpdiff += step>>2; - - if (sign) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 5 - clamp output value */ - if (valpred > 32767) - valpred = 32767; - else if (valpred < -32768) - valpred = -32768; - - /* Step 6 - Update step value */ - step = stepsizeTable[index]; - - /* Step 7 - Output value */ - *outp++ = valpred; - } - - state->valprev = valpred; - state->index = index; -} -#endif - -void adpcm_coder(short *inp, adpcm_t *adpcm) -{ - int val; /* Current input sample value */ - int sign; /* Current adpcm sign bit */ - int delta; /* Current adpcm output value */ - int diff; /* Difference between val and valprev */ - int step; /* Stepsize */ - int valpred; /* Predicted output value */ - int vpdiff; /* Current change to valpred */ - int index; /* Current step change index */ - int outputbuffer; /* place to keep previous 4-bit value */ - int bufferstep; /* toggle between outputbuffer/output */ - adpcm_state_t *state; - char *outp; - int len; - - state = &adpcm->state; - len = state->count; - outp = adpcm->adpcm; - - valpred = state->in_valprev; - index = state->in_index; - step = stepsizeTable[index]; - - bufferstep = 1; - while(len--) - { - val = *inp++; - - /* Step 1 - compute difference with previous value */ - diff = val - valpred; - sign = (diff < 0) ? 8 : 0; - if (sign) - diff = -diff; - - /* Step 2 - Divide and clamp */ - /* Note: - ** This code *approximately* computes: - ** delta = diff*4/step; - ** vpdiff = (delta+0.5)*step/4; - ** but in shift step bits are dropped. The net result of this is - ** that even if you have fast mul/div hardware you cannot put it to - ** good use since the fixup would be too expensive. - */ - delta = 0; - vpdiff = (step >> 3); - - if (diff >= step) - { - delta = 4; - diff -= step; - vpdiff += step; - } - step >>= 1; - if (diff >= step) - { - delta |= 2; - diff -= step; - vpdiff += step; - } - step >>= 1; - if (diff >= step) - { - delta |= 1; - vpdiff += step; - } - - /* Step 3 - Update previous value */ - if (sign) - valpred -= vpdiff; - else - valpred += vpdiff; - - /* Step 4 - Clamp previous value to 16 bits */ - if (valpred > 32767) - valpred = 32767; - else if (valpred < -32768) - valpred = -32768; - - /* Step 5 - Assemble value, update index and step values */ - delta |= sign; - - index += indexTable[delta]; - if (index < 0) - index = 0; - if (index > 88) - index = 88; - step = stepsizeTable[index]; - - /* Step 6 - Output value */ - if (bufferstep) - outputbuffer = (delta << 4) & 0xf0; - else - *outp++ = (delta & 0x0f) | outputbuffer; - - bufferstep = !bufferstep; - } - - /* Output last step, if needed */ - if(!bufferstep) - *outp++ = outputbuffer; - - state->out_valprev = valpred; - state->out_index = index; -} - -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 = *(long *)data_p; - data_p += 4; - if(iff_chunk_len < 0) - { - data_p = NULL; - return; - } - - 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 = *(long *)data_p; - data_p += 4; - 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; - - FindChunk("fmt "); - if(!data_p) - { - printf("Missing fmt chunk\n"); - return(info); - } - data_p += 8; - format = *(short *)data_p; - data_p += 2; - if (format != 1) - { - printf("Microsoft PCM format only\n"); - return(info); - } - - info.channels = *(short *)data_p; - data_p += 2; - info.rate = *(long *)data_p; - data_p += 4; - data_p += 6; - info.width = *(short *)data_p / 8; - data_p += 2; - -// get cue chunk - FindChunk("cue "); - if(data_p) - { - data_p += 32; - info.loopstart = *(long *)data_p; - data_p += 4; - -// if the next chunk is a LIST chunk, look for a cue length marker - FindNextChunk ("LIST"); - if(data_p) - { -// this is not a proper parse, but it works with cooledit... - if (!strncmp (data_p + 28, "mark", 4)) - { - data_p += 24; - i = *(long *)data_p; // samples in loop - data_p += 4; - 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 = *(long *)data_p; - data_p += 4; - - 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() -{ - char name[1024]; - FILE *f; - int len; - - soundtrack = NULL; - sprintf (name, "%svideo/%s/%s.wav", gamedir, base, base); - printf ("\nLoading sound : %s\n", name); - f = fopen (name, "rb"); - if (!f) - { - printf ("\nNo soundtrack for %s\n", base); - return; - } - len = Q_filelength(f); - soundtrack = SafeMalloc(len, "LoadSoundtrack"); - fread(soundtrack, 1, len, f); - fclose(f); - - wavinfo = GetWavinfo(name, soundtrack, len); - adpcm.state.out_valprev = 0; - adpcm.state.out_index = 0; -} - -// ================== -// WriteSound -// ================== - -int WriteSound(FILE *output, int frame, int numframes) -{ - int start, end; - int count; - int empty = 0; - int width; - char *work; - - width = wavinfo.width * wavinfo.channels; - start = ((frame * wavinfo.rate / 14) + 31) & 0xffffffe0; // start sample - end = (((frame + numframes) * wavinfo.rate / 14) + 31) & 0xffffffe0; // end sample - count = end - start; - - work = soundtrack + wavinfo.dataofs + (start * width); - adpcm.state.count = count * wavinfo.channels; // Number of samples - adpcm.state.in_valprev = adpcm.state.out_valprev; - adpcm.state.in_index = adpcm.state.out_index; - adpcm_coder((short *)work, &adpcm); - WriteHeader(output, FC_SOUND_22KMADPCM, FC_ADPCM_VERSION, (adpcm.state.count / 2) + sizeof(adpcm_state_t), (char *)&adpcm); - return(count / 2); -} -// ============================== -// Basic run length encoder -// ============================== - -char *RLEZZ(char *in, char *out) -{ - int srun; - char count; - int idx = 0; - - while(idx < 64) - { - srun = idx; // Start of run - - while(idx < 63) - { - if(in[LUT_ZZ[idx]] != in[LUT_ZZ[idx + 1]]) - break; - idx++; - } - count = (char)(idx - srun); // count of repeated bytes - - if(!count) - { - while(idx < 63) - { - if(in[LUT_ZZ[idx]] == in[LUT_ZZ[idx + 1]]) - break; - idx++; - } - if(idx == 63) - idx++; - - count = (char)(idx - srun); // count of unique bytes - *out++ = count; - while(count--) - *out++ = in[LUT_ZZ[srun++]]; - } - else - { - *out++ = -(count + 1); - *out++ = in[LUT_ZZ[idx]]; - idx++; - } - } - return(out); -} - -// ============================== -// Discrete Cosine Transformation -// ============================== - -void init_base(float quant) -{ - int y, x; - - for(y = 0; y < BLOCKSIZE; y++) - for(x = 0; x < BLOCKSIZE; x++) - { - if(y == 0) - dctbase[y][x] = 1; - else - dctbase[y][x] = SQRT2 * cos(((x * 2 + 1) * y * M_PI) / (BLOCKSIZE * 2)); - } - - for(y = 0; y < BLOCKSIZE * BLOCKSIZE; y++) - Quantise[y] = LUT_Quantise[y] / quant; -} - -void SplitComponents(byte *src, int width, int height) -{ - int i, j; - float *tr = red; - float *tg = green; - float *tb = blue; - - for(i = 0; i < BLOCKSIZE; i++, src += (width - BLOCKSIZE) * 4) - for(j = 0; j < BLOCKSIZE; j++) - { - *tr++ = ((float)*src++) - 128.0F; - *tg++ = ((float)*src++) - 128.0F; - *tb++ = ((float)*src++) - 128.0F; - src++; - } -} - -void transferH(float *src, float *dst) -{ - int y, dx, dy; - float sum; - float *work; - - for(y = 0; y < BLOCKSIZE; y++, src += BLOCKSIZE) - { - for(dy = 0; dy < BLOCKSIZE; dy++) - { - sum = 0; - work = src; - for(dx = 0; dx < BLOCKSIZE; dx++, work++) - sum += dctbase[dy][dx] * *work; - - *dst++ = sum / BLOCKSIZE; - } - } -} - -void transferV(float *src, float *dst) -{ - int x, dy, fy; - float sum; - float *work; - - for(x = 0; x < BLOCKSIZE; x++, src++, dst++) - { - for(fy = 0; fy < BLOCKSIZE; fy++) - { - sum = 0; - work = src; - for(dy = 0; dy < BLOCKSIZE; dy++, work += BLOCKSIZE) - sum += dctbase[fy][dy] * *work; - - dst[fy * BLOCKSIZE] = sum / BLOCKSIZE; - } - } -} - -char *Combine(byte *dst, float *p, float *q) -{ - int i, j; - byte rlesrc[BLOCKSIZE * BLOCKSIZE]; - int c; - byte *work; - - work = rlesrc; - for(j = 0; j < BLOCKSIZE; j++) - for(i = 0; i < BLOCKSIZE; i++) - { - c = (int)((*p++ / *q++) + 128.5F); - c -= 128; - - if(c < -128) - c = -128; - if(c > 127) - c = 127; - - *work++ = (char)c; - } - - dst = RLEZZ(rlesrc, dst); - return(dst); -} - -char *CombineComponents(char *dst, int width, int height) -{ - dst = Combine(dst, red, Quantise); - dst = Combine(dst, green, Quantise); - dst = Combine(dst, blue, Quantise); - return(dst); -} - -void DCT(cblock_t *out, cblock_t in, int width, int height) -{ - int x, y; - char *cursrc; - char *curdst; - - curdst = out->data; - for(y = 0; y < height; y += BLOCKSIZE) - for(x = 0; x < width; x += BLOCKSIZE) - { - cursrc = in.data + ((y * width) + x) * 4; - SplitComponents(cursrc, width, height); - transferH(red, temp); - transferV(temp, red); - transferH(green, temp); - transferV(temp, green); - transferH(blue, temp); - transferV(temp, blue); - curdst = CombineComponents(curdst, width, height); - } - out->count = curdst - out->data; -} - -// ================== -// 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); -} - -// ================== -// 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); -} - -// ================== -// 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; - - 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; - } - } -} - -// ================== -// Huffman1_Build -// ================== - -void Huffman1_Build() -{ - 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; -// easy to overflow 32 bits here! - for(j = 0; j < HUF_TOKENS; j++) - { - 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); - } -} - -// ================== -// 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 = SafeMalloc((in.count * 2) + 1024 + 4, "Huffman"); - memset(out_p, 0, (in.count * 2) + 1024 + 4); - - // leave space for compressed count - out_p += 4; - // write count - *(long *)out_p = in.count; - out_p += 4; - - // 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; - // 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; - } - } - out_p += (outbits + 7) >> 3; - out.count = out_p - out.data; - - out_p = out.data; - *(long *)out_p = out.count; - return(out); -} -// =================== -// LoadFrame -// =================== - -void LoadFrame(cblock_t *out, char *base, int frame) -{ - cblock_t in; - int width, height; - char name[1024]; - FILE *f; - - in.data = NULL; - in.count = -1; - sprintf (name, "%svideo/%s/%s%04i.tga", gamedir, base, base, frame); - - f = fopen(name, "rb"); - if (!f) - { - out->data = NULL; - return; - } - fclose (f); - - LoadTGA(name, &in.data, &width, &height); - if((width != cinehead.Width) || (height != cinehead.Height)) - { - free(in.data); - printf("Invalid picture size\n"); - out->data = NULL; - return; - } - out->data = SafeMalloc(width * height * 3, "LoadFrame"); // rle could possibly expand file so this not 100% safe (however DCT should force a lot of compression) - DCT(out, in, width, height); - free(in.data); -} - -// ================================== -// Cmd_Video -// -// video -// ================================== - -void Cmd_Video() -{ - char savename[256]; - char name[256]; - FILE *output; - int frame; - int width, height; - cblock_t in, huffman; - int size; - float dctconst; - int maxsize, ssize; - int min_rle_size, warnings; - int ave_image, ave_sound; - - GetScriptToken(false); - strcpy(base, token); - if (g_release) - return; - - GetScriptToken(false); - dctconst = atof(token); - GetScriptToken(false); - maxsize = atoi(token); - - sprintf (savename, "%svideo/%s.cin", gamedir, base); - - // clear stuff - memset(charbits1, 0, sizeof(charbits1)); - memset(charbitscount1, 0, sizeof(charbitscount1)); - memset(hnodes1, 0, sizeof(hnodes1)); - memset(numhnodes1, 0, sizeof(numhnodes1)); - memset(order0counts, 0, sizeof(order0counts)); - - // load the entire sound wav file if present - LoadSoundtrack(); - - cinehead.SndRate = wavinfo.rate; - cinehead.SndWidth = wavinfo.width; - cinehead.SndChannels = wavinfo.channels; - - sprintf(name, "%svideo/%s/%s0000.tga", gamedir, base, base); - printf("Loading sequence : %s\n", name); - printf("DCT constant : %f\n", dctconst); - - LoadTGA (name, NULL, &width, &height); - - output = fopen (savename, "wb"); - if (!output) - Error ("Can't open %s", savename); - - if((width % BLOCKSIZE) || (height % BLOCKSIZE)) - Error("Width and height must be a multiple of %d", BLOCKSIZE); - - cinehead.Width = width; - cinehead.Height = height; - init_base(dctconst); - - // build the dictionary - printf("Counting : "); - min_rle_size = 0; - for (frame = 0; ; frame++) - { - printf("."); - LoadFrame(&in, base, frame); - if(!in.data) - break; - Huffman1_Count(in); - if(in.count > min_rle_size) - min_rle_size = in.count; - free(in.data); - } - printf ("\n"); - cinehead.NumFrames = frame; - printf("Num Frames : %d\n", frame); - cinehead.MaxRleSize = (min_rle_size + 0x1f) & 0xfffffe0; - cinehead.MaxSndSize = ((4 * wavinfo.rate * wavinfo.channels / 14) + 0x1f) & 0xffffffe0; - - WriteHeader(output, FC_HEADER_NAME, FC_HEADER_VERSION, sizeof(CineHead_t), &cinehead); - - // build nodes and write counts - Huffman1_Build(); - WriteHeader(output, FC_HUFFBITS_NAME, FC_HUFFBITS_VERSION, sizeof(scaled), scaled); - WriteHeader(output, FC_QUANT_NAME, FC_QUANT_VERSION, sizeof(Quantise), Quantise); - - ave_image = 0; - ave_sound = 0; - warnings = 0; - // compress it with the dictionary - if(soundtrack) - { - ssize = WriteSound(output, frame, 4); - ave_sound += ssize; - } - - for (frame = 0; frame < cinehead.NumFrames; frame++) - { - // save some sound samples - printf ("Packing : ", frame); - LoadFrame(&in, base, frame); - - // save the image - huffman = Huffman1(in); - printf ("%d bytes rle, %d bytes huffman", in.count, huffman.count); - size = (huffman.count + 3) & 0xfffffffc; // round up to longwords - if(size > maxsize) - { - printf(" ** WARNING **"); - warnings++; - } - printf("\n"); - ave_image += huffman.count; - - WriteHeader(output, FC_IMAGE_NAME, FC_IMAGE_VERSION, size, huffman.data); - if(soundtrack) - { - ssize = WriteSound(output, frame + 4, 1); - ave_sound += ssize; - } - - free (in.data); - free (huffman.data); - } - printf("\nTotal size: %d (headers + %d image + %d sound)\n", ftell(output), ave_image, ave_sound); - printf("Data rate : %d bytes per sec (image and sound)\n", (ave_image + ave_sound) / cinehead.NumFrames); - printf("Cin created ok with %d warnings.\n", warnings); - fclose (output); - - if (soundtrack) - free (soundtrack); -} -#endif - -void Cmd_Video() -{ -} - -// end - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/common/aselib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/aselib.c deleted file mode 100644 index 980e7266..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/aselib.c +++ /dev/null @@ -1,965 +0,0 @@ -/* -Copyright (C) 1999-2006 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", token ); - } -} - -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/misc/mediasource/extra/netradiant-src/tools/quake3/common/aselib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/aselib.h deleted file mode 100644 index 299e6053..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/aselib.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/bspfile.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/bspfile.c deleted file mode 100644 index 828d0938..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/bspfile.c +++ /dev/null @@ -1,706 +0,0 @@ -/* -Copyright (C) 1999-2006 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 ; inext ) { - 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/bspfile.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/bspfile.h deleted file mode 100644 index ad70bae5..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/bspfile.h +++ /dev/null @@ -1,121 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/cmdlib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/cmdlib.c deleted file mode 100644 index 5168d233..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/cmdlib.c +++ /dev/null @@ -1,1179 +0,0 @@ -/* -Copyright (C) 1999-2006 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 < (int) 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 < (int) 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 || 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 (!*gamedir) - Error ("ExpandGamePath called without gamedir 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 - if(!getcwd (out, 256)) *out = 0; - strcat (out, "/"); -#endif - while ( out[i] != 0 ) - { - if ( out[i] == '\\' ) - out[i] = '/'; - i++; - } -} - - -void Q_mkdir (const char *path) -{ - char parentbuf[256]; - const char *p = NULL; - int retry = 2; - while(retry--) - { -#ifdef WIN32 - const char *q = NULL; - if (_mkdir (path) != -1) - return; - if(errno == ENOENT) - { - p = strrchr(path, '/'); - q = strrchr(path, '\\'); - if(q && (!p || q < p)) - p = q; - } -#else - if (mkdir (path, 0777) != -1) - return; - if(errno == ENOENT) - p = strrchr(path, '/'); -#endif - if(p) - { - strncpy(parentbuf, path, sizeof(parentbuf)); - if((int) (p - path) < (int) sizeof(parentbuf)) - { - parentbuf[p - path] = 0; - Sys_Printf ("mkdir: %s: creating parent %s first\n", path, parentbuf); - Q_mkdir(parentbuf); - continue; - } - } - break; - } - 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 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/cmdlib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/cmdlib.h deleted file mode 100644 index 37890b46..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/cmdlib.h +++ /dev/null @@ -1,168 +0,0 @@ -/* -Copyright (C) 1999-2006 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 - - -#ifdef PATH_MAX -#define MAX_OS_PATH PATH_MAX -#else -#define MAX_OS_PATH 1024 -#endif -#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, ... ) -#ifdef __GNUC__ -__attribute__((noreturn)) -#endif -; -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/misc/mediasource/extra/netradiant-src/tools/quake3/common/imagelib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/imagelib.c deleted file mode 100644 index 31e31850..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/imagelib.c +++ /dev/null @@ -1,1249 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "inout.h" -#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 (countbpwidth) - 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 ; ydata; - - 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 */ - runLength = 0; - 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 ; iid_length, t->colormap_type, t->image_type, t->colormap_index, t->colormap_length, t->colormap_size, t->x_origin, t->y_origin, t->width, t->height, t->pixel_size, t->attributes); -} - -/* -============= -LoadTGABuffer -============= -*/ -void LoadTGABuffer (const byte *f, const byte *enddata, byte **pic, int *width, int *height) -{ - int x, y, row_inc, compressed, readpixelcount, red, green, blue, alpha, runlen, pindex, alphabits, image_width, image_height; - byte *pixbuf, *image_rgba; - const byte *fin; - unsigned char *p; - TargaHeader targa_header; - unsigned char palette[256*4]; - - *pic = NULL; - - // abort if it is too small to parse - if (enddata - f < 19) - return; - - targa_header.id_length = f[0]; - targa_header.colormap_type = f[1]; - targa_header.image_type = f[2]; - - targa_header.colormap_index = f[3] + f[4] * 256; - targa_header.colormap_length = f[5] + f[6] * 256; - targa_header.colormap_size = f[7]; - targa_header.x_origin = f[8] + f[9] * 256; - targa_header.y_origin = f[10] + f[11] * 256; - targa_header.width = image_width = f[12] + f[13] * 256; - targa_header.height = image_height = f[14] + f[15] * 256; - - targa_header.pixel_size = f[16]; - targa_header.attributes = f[17]; - - // advance to end of header - fin = f + 18; - - // skip TARGA image comment (usually 0 bytes) - fin += targa_header.id_length; - - // read/skip the colormap if present (note: according to the TARGA spec it - // can be present even on truecolor or greyscale images, just not used by - // the image data) - if (targa_header.colormap_type) - { - if (targa_header.colormap_length > 256) - { - TargaError(&targa_header, "LoadTGA: only up to 256 colormap_length supported\n"); - return; - } - if (targa_header.colormap_index) - { - TargaError(&targa_header, "LoadTGA: colormap_index not supported\n"); - return; - } - if (targa_header.colormap_size == 24) - { - for (x = 0;x < targa_header.colormap_length;x++) - { - palette[x*4+2] = *fin++; - palette[x*4+1] = *fin++; - palette[x*4+0] = *fin++; - palette[x*4+3] = 255; - } - } - else if (targa_header.colormap_size == 32) - { - for (x = 0;x < targa_header.colormap_length;x++) - { - palette[x*4+2] = *fin++; - palette[x*4+1] = *fin++; - palette[x*4+0] = *fin++; - palette[x*4+3] = *fin++; - } - } - else - { - TargaError(&targa_header, "LoadTGA: Only 32 and 24 bit colormap_size supported\n"); - return; - } - } - - // check our pixel_size restrictions according to image_type - if (targa_header.image_type == 2 || targa_header.image_type == 10) - { - if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32) - { - TargaError(&targa_header, "LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n"); - return; - } - } - else if (targa_header.image_type == 1 || targa_header.image_type == 9) - { - if (targa_header.pixel_size != 8) - { - TargaError(&targa_header, "LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n"); - return; - } - } - else if (targa_header.image_type == 3 || targa_header.image_type == 11) - { - if (targa_header.pixel_size != 8) - { - TargaError(&targa_header, "LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n"); - return; - } - } - else - { - TargaError(&targa_header, "LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported"); - return; - } - - if (targa_header.attributes & 0x10) - { - TargaError(&targa_header, "LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n"); - return; - } - - // number of attribute bits per pixel, we only support 0 or 8 - alphabits = targa_header.attributes & 0x0F; - if (alphabits != 8 && alphabits != 0) - { - TargaError(&targa_header, "LoadTGA: only 0 or 8 attribute (alpha) bits supported\n"); - return; - } - - image_rgba = safe_malloc(image_width * image_height * 4); - if (!image_rgba) - { - Sys_Printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height); - return; - } - - // If bit 5 of attributes isn't set, the image has been stored from bottom to top - if ((targa_header.attributes & 0x20) == 0) - { - pixbuf = image_rgba + (image_height - 1)*image_width*4; - row_inc = -image_width*4*2; - } - else - { - pixbuf = image_rgba; - row_inc = 0; - } - - compressed = targa_header.image_type == 9 || targa_header.image_type == 10 || targa_header.image_type == 11; - x = 0; - y = 0; - red = green = blue = alpha = 255; - while (y < image_height) - { - // decoder is mostly the same whether it's compressed or not - readpixelcount = 1000000; - runlen = 1000000; - if (compressed && fin < enddata) - { - runlen = *fin++; - // high bit indicates this is an RLE compressed run - if (runlen & 0x80) - readpixelcount = 1; - runlen = 1 + (runlen & 0x7f); - } - - while((runlen--) && y < image_height) - { - if (readpixelcount > 0) - { - readpixelcount--; - red = green = blue = alpha = 255; - if (fin < enddata) - { - switch(targa_header.image_type) - { - case 1: - case 9: - // colormapped - pindex = *fin++; - if (pindex >= targa_header.colormap_length) - pindex = 0; // error - p = palette + pindex * 4; - red = p[0]; - green = p[1]; - blue = p[2]; - alpha = p[3]; - break; - case 2: - case 10: - // BGR or BGRA - blue = *fin++; - if (fin < enddata) - green = *fin++; - if (fin < enddata) - red = *fin++; - if (targa_header.pixel_size == 32 && fin < enddata) - alpha = *fin++; - break; - case 3: - case 11: - // greyscale - red = green = blue = *fin++; - break; - } - if (!alphabits) - alpha = 255; - } - } - *pixbuf++ = red; - *pixbuf++ = green; - *pixbuf++ = blue; - *pixbuf++ = alpha; - x++; - if (x == image_width) - { - // end of line, advance to next - x = 0; - y++; - pixbuf += row_inc; - } - } - } - - *pic = image_rgba; - if (width) - *width = image_width; - if (height) - *height = image_height; -} - - -/* -============= -LoadTGA -============= -*/ -void LoadTGA (const char *name, byte **pixels, int *width, int *height) -{ - byte *buffer; - int nLen; - // - // load the file - // - nLen = vfsLoadFile ( name, (void **)&buffer, 0); - if (nLen == -1) - { - Error ("Couldn't read %s", name); - } - - LoadTGABuffer(buffer, buffer + nLen, 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>8; - buffer[14] = height&255; - buffer[15] = height>>8; - buffer[16] = 8; // pixel size - - f = fopen (filename, "wb"); - fwrite (buffer, 1, 18, f); - fwrite (data, 1, width * height, f); - fclose (f); -} - -/* -============================================================================ - -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/misc/mediasource/extra/netradiant-src/tools/quake3/common/imagelib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/imagelib.h deleted file mode 100644 index 2371b48a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/imagelib.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright (C) 1999-2006 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 ( const byte *buffer, const byte* enddata, byte **pic, int *width, int *height); -void WriteTGA (const char *filename, byte *data, int width, int height); -void WriteTGAGray (const char *filename, byte *data, int width, int height); - -void Load32BitImage (const char *name, unsigned **pixels, int *width, int *height); - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/common/inout.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/inout.c deleted file mode 100644 index 9f7005ad..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/inout.c +++ /dev/null @@ -1,375 +0,0 @@ -/* -Copyright (C) 1999-2006 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, (xmlChar*)"point"); - xmlNodeSetContent (ret, (xmlChar*)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 < (int)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, (xmlChar*)"select"); - xmlNodeSetContent (node, (xmlChar*)buf); - level[0] = (int)'0' + (bError ? SYS_ERR : SYS_WRN) ; - level[1] = 0; - xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&level); - // a 'select' information - sprintf (buf, "%i %i", entitynum, brushnum); - select = xmlNewNode (NULL, (xmlChar*)"brush"); - xmlNodeSetContent (select, (xmlChar*)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, (xmlChar*)"pointmsg"); - xmlNodeSetContent (node, (xmlChar*)msg); - level[0] = (int)'0' + SYS_ERR; - level[1] = 0; - xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&level); - // a 'point' node - sprintf (buf, "%g %g %g", pt[0], pt[1], pt[2]); - point = xmlNewNode (NULL, (xmlChar*)"point"); - xmlNodeSetContent (point, (xmlChar*)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, (xmlChar*)"windingmsg"); - xmlNodeSetContent (node, (xmlChar*)msg); - level[0] = (int)'0' + SYS_ERR; - level[1] = 0; - xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&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, (xmlChar*)"winding"); - xmlNodeSetContent (winding, (xmlChar*)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(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("%s", 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((xmlChar*)"1.0"); - doc->children = xmlNewDocRawNode(doc, NULL, (xmlChar*)"q3map_feedback", NULL); - bGotXML = qtrue; - } - node = xmlNewNode (NULL, (xmlChar*)"message"); - { - gchar* utf8 = g_locale_to_utf8(buf, -1, NULL, NULL, NULL); - xmlNodeSetContent(node, (xmlChar*)utf8); - g_free(utf8); - } - level[0] = (int)'0' + flag; - level[1] = 0; - xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&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/misc/mediasource/extra/netradiant-src/tools/quake3/common/inout.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/inout.h deleted file mode 100644 index c60b0b85..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/inout.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -Copyright (C) 1999-2006 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" -#include "mathlib.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/misc/mediasource/extra/netradiant-src/tools/quake3/common/l3dslib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/l3dslib.c deleted file mode 100644 index 3030b0bf..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/l3dslib.c +++ /dev/null @@ -1,301 +0,0 @@ -/* -Copyright (C) 1999-2006 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 MAXVERTS) - Error ("Error: Too many vertices"); - - for (i=0 ; i MAXTRIANGLES) - Error ("Error: Too many triangles"); - - for (i=0 ; i 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/l3dslib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/l3dslib.h deleted file mode 100644 index bac2433b..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/l3dslib.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/md4.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/md4.c deleted file mode 100644 index 7c2c9be4..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/md4.c +++ /dev/null @@ -1,227 +0,0 @@ -/* - mdfour.c - - An implementation of MD4 designed for use in the samba SMB - authentication protocol - - Copyright (C) 1997-1998 Andrew Tridgell - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - - See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to: - - Free Software Foundation, Inc. - 59 Temple Place - Suite 330 - Boston, MA 02111-1307, USA - - $Id: mdfour.c 7689 2007-11-12 14:28:40Z divverent $ -*/ - -#include /* XoXus: needed for memset call */ -#include "md4.h" - -/* NOTE: This code makes no attempt to be fast! - - It assumes that a int is at least 32 bits long -*/ - -static struct mdfour *m; - -#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)) -#ifdef LARGE_INT32 -#define lshift(x,s) ((((x)<<(s))&0xFFFFFFFF) | (((x)>>(32-(s)))&0xFFFFFFFF)) -#else -#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) -#endif - -#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) -#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) -#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) - -/* this applies md4 to 64 byte chunks */ -static void mdfour64(uint32 *M) -{ - int j; - uint32 AA, BB, CC, DD; - uint32 X[16]; - uint32 A,B,C,D; - - for (j=0;j<16;j++) - X[j] = M[j]; - - A = m->A; B = m->B; C = m->C; D = m->D; - AA = A; BB = B; CC = C; DD = D; - - ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); - ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); - ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); - ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); - ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); - ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); - ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); - ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); - - ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); - ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); - ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); - ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); - ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); - ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); - ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); - ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); - - ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); - ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); - ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); - ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); - ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); - ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); - ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); - ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); - - A += AA; B += BB; C += CC; D += DD; - -#ifdef LARGE_INT32 - A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; - C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; -#endif - - for (j=0;j<16;j++) - X[j] = 0; - - m->A = A; m->B = B; m->C = C; m->D = D; -} - -static void copy64(uint32 *M, unsigned char *in) -{ - int i; - - for (i=0;i<16;i++) - M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | - (in[i*4+1]<<8) | (in[i*4+0]<<0); -} - -static void copy4(unsigned char *out,uint32 x) -{ - out[0] = x&0xFF; - out[1] = (x>>8)&0xFF; - out[2] = (x>>16)&0xFF; - out[3] = (x>>24)&0xFF; -} - -void mdfour_begin(struct mdfour *md) -{ - md->A = 0x67452301; - md->B = 0xefcdab89; - md->C = 0x98badcfe; - md->D = 0x10325476; - md->totalN = 0; -} - - -static void mdfour_tail(unsigned char *in, int n) -{ - unsigned char buf[128]; - uint32 M[16]; - uint32 b; - - m->totalN += n; - - b = m->totalN * 8; - - memset(buf, 0, 128); - if (n) memcpy(buf, in, n); - buf[n] = 0x80; - - if (n <= 55) { - copy4(buf+56, b); - copy64(M, buf); - mdfour64(M); - } else { - copy4(buf+120, b); - copy64(M, buf); - mdfour64(M); - copy64(M, buf+64); - mdfour64(M); - } -} - -void mdfour_update(struct mdfour *md, unsigned char *in, int n) -{ - uint32 M[16]; - -// start of edit by Forest 'LordHavoc' Hale -// commented out to prevent crashing when length is 0 -// if (n == 0) mdfour_tail(in, n); -// end of edit by Forest 'LordHavoc' Hale - - m = md; - - while (n >= 64) { - copy64(M, in); - mdfour64(M); - in += 64; - n -= 64; - m->totalN += 64; - } - - mdfour_tail(in, n); -} - - -void mdfour_result(struct mdfour *md, unsigned char *out) -{ - m = md; - - copy4(out, m->A); - copy4(out+4, m->B); - copy4(out+8, m->C); - copy4(out+12, m->D); -} - - -void mdfour(unsigned char *out, unsigned char *in, int n) -{ - struct mdfour md; - mdfour_begin(&md); - mdfour_update(&md, in, n); - mdfour_result(&md, out); -} - -/////////////////////////////////////////////////////////////// -// MD4-based checksum utility functions -// -// Copyright (C) 2000 Jeff Teunissen -// -// Author: Jeff Teunissen -// Date: 01 Jan 2000 - -unsigned Com_BlockChecksum (void *buffer, int length) -{ - int digest[4]; - unsigned val; - - mdfour ( (unsigned char *) digest, (unsigned char *) buffer, length ); - - val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; - - return val; -} - -void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) -{ - mdfour ( outbuf, (unsigned char *) buffer, len ); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/common/md4.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/md4.h deleted file mode 100644 index 4373c2c9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/md4.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - mdfour.h - - an implementation of MD4 designed for use in the SMB authentication - protocol - - Copyright (C) Andrew Tridgell 1997-1998 - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. - - See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to: - - Free Software Foundation, Inc. - 59 Temple Place - Suite 330 - Boston, MA 02111-1307, USA -*/ - -#ifndef _MDFOUR_H -#define _MDFOUR_H - -#ifndef int32 -#define int32 int -#endif - -#if SIZEOF_INT > 4 -#define LARGE_INT32 -#endif - -#ifndef uint32 -#define uint32 unsigned int32 -#endif - -struct mdfour { - uint32 A, B, C, D; - uint32 totalN; -}; - -void mdfour_begin(struct mdfour *md); // old: MD4Init -void mdfour_update(struct mdfour *md, unsigned char *in, int n); //old: MD4Update -void mdfour_result(struct mdfour *md, unsigned char *out); // old: MD4Final -void mdfour(unsigned char *out, unsigned char *in, int n); - -unsigned Com_BlockChecksum (void *buffer, int length); -void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf); - -#endif // _MDFOUR_H - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/common/mutex.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/mutex.c deleted file mode 100644 index 38a383d6..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/mutex.c +++ /dev/null @@ -1,197 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/mutex.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/mutex.h deleted file mode 100644 index aa929923..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/mutex.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/polylib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/polylib.c deleted file mode 100644 index 34dd173e..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/polylib.c +++ /dev/null @@ -1,1109 +0,0 @@ -/* -Copyright (C) 1999-2006 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 ; inumpoints ; 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; -} - -/* -============= -AllocWindingAccu -============= -*/ -winding_accu_t *AllocWindingAccu(int points) -{ - winding_accu_t *w; - int s; - - if (points >= MAX_POINTS_ON_WINDING) - Error("AllocWindingAccu failed: MAX_POINTS_ON_WINDING exceeded"); - - if (numthreads == 1) - { - // At the time of this writing, these statistics were not used in any way. - 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_accu_t) * 3 * points + sizeof(int); - w = safe_malloc(s); - memset(w, 0, s); - return w; -} - -/* -============= -FreeWinding -============= -*/ -void FreeWinding (winding_t *w) -{ - if (!w) Error("FreeWinding: winding is NULL"); - - if (*(unsigned *)w == 0xdeaddead) - Error ("FreeWinding: freed a freed winding"); - *(unsigned *)w = 0xdeaddead; - - if (numthreads == 1) - c_active_windings--; - free (w); -} - -/* -============= -FreeWindingAccu -============= -*/ -void FreeWindingAccu(winding_accu_t *w) -{ - if (!w) Error("FreeWindingAccu: winding is NULL"); - - if (*((unsigned *) w) == 0xdeaddead) - Error("FreeWindingAccu: 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; i++) - VectorAdd (w->p[i], center, center); - - scale = 1.0/w->numpoints; - VectorScale (center, scale, center); -} - -/* -================= -BaseWindingForPlaneAccu -================= -*/ -winding_accu_t *BaseWindingForPlaneAccu(vec3_t normal, vec_t dist) -{ - // The goal in this function is to replicate the behavior of the original BaseWindingForPlane() - // function (see below) but at the same time increasing accuracy substantially. - - // The original code gave a preference for the vup vector to start out as (0, 0, 1), unless the - // normal had a dominant Z value, in which case vup started out as (1, 0, 0). After that, vup - // was "bent" [along the plane defined by normal and vup] to become perpendicular to normal. - // After that the vright vector was computed as the cross product of vup and normal. - - // I'm constructing the winding polygon points in a fashion similar to the method used in the - // original function. Orientation is the same. The size of the winding polygon, however, is - // variable in this function (depending on the angle of normal), and is larger (by about a factor - // of 2) than the winding polygon in the original function. - - int x, i; - vec_t max, v; - vec3_accu_t vright, vup, org, normalAccu; - winding_accu_t *w; - - // One of the components of normal must have a magnitiude greater than this value, - // otherwise normal is not a unit vector. This is a little bit of inexpensive - // partial error checking we can do. - max = 0.56; // 1 / sqrt(1^2 + 1^2 + 1^2) = 0.577350269 - - x = -1; - for (i = 0; i < 3; i++) { - v = (vec_t) fabs(normal[i]); - if (v > max) { - x = i; - max = v; - } - } - if (x == -1) Error("BaseWindingForPlaneAccu: no dominant axis found because normal is too short"); - - switch (x) { - case 0: // Fall through to next case. - case 1: - vright[0] = (vec_accu_t) -normal[1]; - vright[1] = (vec_accu_t) normal[0]; - vright[2] = 0; - break; - case 2: - vright[0] = 0; - vright[1] = (vec_accu_t) -normal[2]; - vright[2] = (vec_accu_t) normal[1]; - break; - } - - // vright and normal are now perpendicular; you can prove this by taking their - // dot product and seeing that it's always exactly 0 (with no error). - - // NOTE: vright is NOT a unit vector at this point. vright will have length - // not exceeding 1.0. The minimum length that vright can achieve happens when, - // for example, the Z and X components of the normal input vector are equal, - // and when normal's Y component is zero. In that case Z and X of the normal - // vector are both approximately 0.70711. The resulting vright vector in this - // case will have a length of 0.70711. - - // We're relying on the fact that MAX_WORLD_COORD is a power of 2 to keep - // our calculation precise and relatively free of floating point error. - // [However, the code will still work fine if that's not the case.] - VectorScaleAccu(vright, ((vec_accu_t) MAX_WORLD_COORD) * 4.0, vright); - - // At time time of this writing, MAX_WORLD_COORD was 65536 (2^16). Therefore - // the length of vright at this point is at least 185364. In comparison, a - // corner of the world at location (65536, 65536, 65536) is distance 113512 - // away from the origin. - - VectorCopyRegularToAccu(normal, normalAccu); - CrossProductAccu(normalAccu, vright, vup); - - // vup now has length equal to that of vright. - - VectorScaleAccu(normalAccu, (vec_accu_t) dist, org); - - // org is now a point on the plane defined by normal and dist. Furthermore, - // org, vright, and vup are pairwise perpendicular. Now, the 4 vectors - // { (+-)vright + (+-)vup } have length that is at least sqrt(185364^2 + 185364^2), - // which is about 262144. That length lies outside the world, since the furthest - // point in the world has distance 113512 from the origin as mentioned above. - // Also, these 4 vectors are perpendicular to the org vector. So adding them - // to org will only increase their length. Therefore the 4 points defined below - // all lie outside of the world. Furthermore, it can be easily seen that the - // edges connecting these 4 points (in the winding_accu_t below) lie completely - // outside the world. sqrt(262144^2 + 262144^2)/2 = 185363, which is greater than - // 113512. - - w = AllocWindingAccu(4); - - VectorSubtractAccu(org, vright, w->p[0]); - VectorAddAccu(w->p[0], vup, w->p[0]); - - VectorAddAccu(org, vright, w->p[1]); - VectorAddAccu(w->p[1], vup, w->p[1]); - - VectorAddAccu(org, vright, w->p[2]); - VectorSubtractAccu(w->p[2], vup, w->p[2]); - - VectorSubtractAccu(org, vright, w->p[3]); - VectorSubtractAccu(w->p[3], vup, w->p[3]); - - w->numpoints = 4; - - return w; -} - -/* -================= -BaseWindingForPlane - -Original BaseWindingForPlane() function that has serious accuracy problems. Here is why. -The base winding is computed as a rectangle with very large coordinates. These coordinates -are in the range 2^17 or 2^18. "Epsilon" (meaning the distance between two adjacent numbers) -at these magnitudes in 32 bit floating point world is about 0.02. So for example, if things -go badly (by bad luck), then the whole plane could be shifted by 0.02 units (its distance could -be off by that much). Then if we were to compute the winding of this plane and another of -the brush's planes met this winding at a very acute angle, that error could multiply to around -0.1 or more when computing the final vertex coordinates of the winding. 0.1 is a very large -error, and can lead to all sorts of disappearing triangle problems. -================= -*/ -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); - - // LordHavoc: this has to use *2 because otherwise some created points may - // be inside the world (think of a diagonal case), and any brush with such - // points should be removed, failure to detect such cases is disasterous - VectorScale (vup, MAX_WORLD_COORD*2, vup); - VectorScale (vright, MAX_WORLD_COORD*2, 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) -{ - size_t size; - winding_t *c; - - if (!w) Error("CopyWinding: winding is NULL"); - - c = AllocWinding (w->numpoints); - size = (size_t)((winding_t *)NULL)->p[w->numpoints]; - memcpy (c, w, size); - return c; -} - -/* -================== -CopyWindingAccuIncreaseSizeAndFreeOld -================== -*/ -winding_accu_t *CopyWindingAccuIncreaseSizeAndFreeOld(winding_accu_t *w) -{ - int i; - winding_accu_t *c; - - if (!w) Error("CopyWindingAccuIncreaseSizeAndFreeOld: winding is NULL"); - - c = AllocWindingAccu(w->numpoints + 1); - c->numpoints = w->numpoints; - for (i = 0; i < c->numpoints; i++) - { - VectorCopyAccu(w->p[i], c->p[i]); - } - FreeWindingAccu(w); - return c; -} - -/* -================== -CopyWindingAccuToRegular -================== -*/ -winding_t *CopyWindingAccuToRegular(winding_accu_t *w) -{ - int i; - winding_t *c; - - if (!w) Error("CopyWindingAccuToRegular: winding is NULL"); - - c = AllocWinding(w->numpoints); - c->numpoints = w->numpoints; - for (i = 0; i < c->numpoints; i++) - { - VectorCopyAccuToRegular(w->p[i], c->p[i]); - } - return c; -} - -/* -================== -ReverseWinding -================== -*/ -winding_t *ReverseWinding (winding_t *w) -{ - int i; - winding_t *c; - - c = AllocWinding (w->numpoints); - for (i=0 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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"); -} - - -/* -============= -ChopWindingInPlaceAccu -============= -*/ -void ChopWindingInPlaceAccu(winding_accu_t **inout, vec3_t normal, vec_t dist, vec_t crudeEpsilon) -{ - vec_accu_t fineEpsilon; - winding_accu_t *in; - int counts[3]; - int i, j; - vec_accu_t dists[MAX_POINTS_ON_WINDING + 1]; - int sides[MAX_POINTS_ON_WINDING + 1]; - int maxpts; - winding_accu_t *f; - vec_accu_t *p1, *p2; - vec_accu_t w; - vec3_accu_t mid, normalAccu; - - // We require at least a very small epsilon. It's a good idea for several reasons. - // First, we will be dividing by a potentially very small distance below. We don't - // want that distance to be too small; otherwise, things "blow up" with little accuracy - // due to the division. (After a second look, the value w below is in range (0,1), but - // graininess problem remains.) Second, Having minimum epsilon also prevents the following - // situation. Say for example we have a perfect octagon defined by the input winding. - // Say our chopping plane (defined by normal and dist) is essentially the same plane - // that the octagon is sitting on. Well, due to rounding errors, it may be that point - // 1 of the octagon might be in front, point 2 might be in back, point 3 might be in - // front, point 4 might be in back, and so on. So we could end up with a very ugly- - // looking chopped winding, and this might be undesirable, and would at least lead to - // a possible exhaustion of MAX_POINTS_ON_WINDING. It's better to assume that points - // very very close to the plane are on the plane, using an infinitesimal epsilon amount. - - // Now, the original ChopWindingInPlace() function used a vec_t-based winding_t. - // So this minimum epsilon is quite similar to casting the higher resolution numbers to - // the lower resolution and comparing them in the lower resolution mode. We explicitly - // choose the minimum epsilon as something around the vec_t epsilon of one because we - // want the resolution of vec_accu_t to have a large resolution around the epsilon. - // Some of that leftover resolution even goes away after we scale to points far away. - - // Here is a further discussion regarding the choice of smallestEpsilonAllowed. - // In the 32 float world (we can assume vec_t is that), the "epsilon around 1.0" is - // 0.00000011921. In the 64 bit float world (we can assume vec_accu_t is that), the - // "epsilon around 1.0" is 0.00000000000000022204. (By the way these two epsilons - // are defined as VEC_SMALLEST_EPSILON_AROUND_ONE VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE - // respectively.) If you divide the first by the second, you get approximately - // 536,885,246. Dividing that number by 200,000 (a typical base winding coordinate) - // gives 2684. So in other words, if our smallestEpsilonAllowed was chosen as exactly - // VEC_SMALLEST_EPSILON_AROUND_ONE, you would be guaranteed at least 2000 "ticks" in - // 64-bit land inside of the epsilon for all numbers we're dealing with. - - static const vec_accu_t smallestEpsilonAllowed = ((vec_accu_t) VEC_SMALLEST_EPSILON_AROUND_ONE) * 0.5; - if (crudeEpsilon < smallestEpsilonAllowed) fineEpsilon = smallestEpsilonAllowed; - else fineEpsilon = (vec_accu_t) crudeEpsilon; - - in = *inout; - counts[0] = counts[1] = counts[2] = 0; - VectorCopyRegularToAccu(normal, normalAccu); - - for (i = 0; i < in->numpoints; i++) - { - dists[i] = DotProductAccu(in->p[i], normalAccu) - dist; - if (dists[i] > fineEpsilon) sides[i] = SIDE_FRONT; - else if (dists[i] < -fineEpsilon) sides[i] = SIDE_BACK; - else sides[i] = SIDE_ON; - counts[sides[i]]++; - } - sides[i] = sides[0]; - dists[i] = dists[0]; - - // I'm wondering if whatever code that handles duplicate planes is robust enough - // that we never get a case where two nearly equal planes result in 2 NULL windings - // due to the 'if' statement below. TODO: Investigate this. - if (!counts[SIDE_FRONT]) { - FreeWindingAccu(in); - *inout = NULL; - return; - } - if (!counts[SIDE_BACK]) { - return; // Winding is unmodified. - } - - // NOTE: The least number of points that a winding can have at this point is 2. - // In that case, one point is SIDE_FRONT and the other is SIDE_BACK. - - maxpts = counts[SIDE_FRONT] + 2; // We dynamically expand if this is too small. - f = AllocWindingAccu(maxpts); - - for (i = 0; i < in->numpoints; i++) - { - p1 = in->p[i]; - - if (sides[i] == SIDE_ON || sides[i] == SIDE_FRONT) - { - if (f->numpoints >= MAX_POINTS_ON_WINDING) - Error("ChopWindingInPlaceAccu: MAX_POINTS_ON_WINDING"); - if (f->numpoints >= maxpts) // This will probably never happen. - { - Sys_FPrintf(SYS_VRB, "WARNING: estimate on chopped winding size incorrect (no problem)\n"); - f = CopyWindingAccuIncreaseSizeAndFreeOld(f); - maxpts++; - } - VectorCopyAccu(p1, f->p[f->numpoints]); - f->numpoints++; - if (sides[i] == SIDE_ON) continue; - } - if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) - { - continue; - } - - // Generate a split point. - p2 = in->p[((i + 1) == in->numpoints) ? 0 : (i + 1)]; - - // The divisor's absolute value is greater than the dividend's absolute value. - // w is in the range (0,1). - w = dists[i] / (dists[i] - dists[i + 1]); - - for (j = 0; j < 3; j++) - { - // Avoid round-off error when possible. Check axis-aligned normal. - if (normal[j] == 1) mid[j] = dist; - else if (normal[j] == -1) mid[j] = -dist; - else mid[j] = p1[j] + (w * (p2[j] - p1[j])); - } - if (f->numpoints >= MAX_POINTS_ON_WINDING) - Error("ChopWindingInPlaceAccu: MAX_POINTS_ON_WINDING"); - if (f->numpoints >= maxpts) // This will probably never happen. - { - Sys_FPrintf(SYS_VRB, "WARNING: estimate on chopped winding size incorrect (no problem)\n"); - f = CopyWindingAccuIncreaseSizeAndFreeOld(f); - maxpts++; - } - VectorCopyAccu(mid, f->p[f->numpoints]); - f->numpoints++; - } - - FreeWindingAccu(in); - *inout = f; -} - -/* -============= -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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; jnumpoints ; 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 ; inumpoints ; 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/polylib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/polylib.h deleted file mode 100644 index 1f4495d9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/polylib.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -Copyright (C) 1999-2006 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 512 - -// 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); - - -/////////////////////////////////////////////////////////////////////////////////////// -// Below is double-precision stuff. This was initially needed by the base winding code -// in q3map2 brush processing. -/////////////////////////////////////////////////////////////////////////////////////// - -typedef struct -{ - int numpoints; - vec3_accu_t p[4]; // variable sized -} winding_accu_t; - -winding_accu_t *BaseWindingForPlaneAccu(vec3_t normal, vec_t dist); -void ChopWindingInPlaceAccu(winding_accu_t **w, vec3_t normal, vec_t dist, vec_t epsilon); -winding_t *CopyWindingAccuToRegular(winding_accu_t *w); -void FreeWindingAccu(winding_accu_t *w); diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/common/polyset.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/polyset.h deleted file mode 100644 index 12993999..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/polyset.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/qfiles.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/qfiles.h deleted file mode 100644 index 29e94978..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/qfiles.h +++ /dev/null @@ -1,489 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/qthreads.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/qthreads.h deleted file mode 100644 index ab806030..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/qthreads.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/scriplib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/scriplib.c deleted file mode 100644 index 47196e53..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/scriplib.c +++ /dev/null @@ -1,409 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/scriplib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/scriplib.h deleted file mode 100644 index 1e3f2c31..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/scriplib.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/surfaceflags.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/surfaceflags.h deleted file mode 100644 index d7ab2ba7..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/surfaceflags.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/threads.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/threads.c deleted file mode 100644 index 7f404a4f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/threads.c +++ /dev/null @@ -1,634 +0,0 @@ -/* -Copyright (C) 1999-2006 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 = 40*dispatch / workcount; - if(f < oldf) - { - Sys_Printf("warning: progress went backwards (should never happen)\n"); - oldf = f; - } - while(f > oldf) - { - ++oldf; - if (pacifier) - { - if(oldf % 4 == 0) - Sys_Printf("%i", f / 4); - else - Sys_Printf ("."); - 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 - -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 -#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 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_attr_t attr; - pthread_t work_threads[MAX_THREADS]; - size_t stacksize; - - int start, end; - int i=0, status=0; - - start = I_FloatTime (); - pacifier = showpacifier; - - dispatch = 0; - oldf = -1; - workcount = workcnt; - - pthread_attr_init(&attr); - if(pthread_attr_setstacksize(&attr, 8388608) != 0) - { - stacksize = 0; - pthread_attr_getstacksize(&attr, &stacksize); - Sys_Printf("Could not set a per-thread stack size of 8 MB, using only %.2f MB\n", stacksize / 1048576.0); - } - - 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 (pthread_mutexattr_settype(&mattrib, PTHREAD_MUTEX_ERRORCHECK) != 0) - Error ("pthread_mutexattr_settype failed"); - recursive_mutex_init(mattrib); - - for (i=0 ; i -#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 ; iverts[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/misc/mediasource/extra/netradiant-src/tools/quake3/common/trilib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/trilib.h deleted file mode 100644 index 89dcf764..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/trilib.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/unzip.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/unzip.c deleted file mode 100644 index 1e2be2be..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/unzip.c +++ /dev/null @@ -1,4609 +0,0 @@ -/* -Copyright (C) 1999-2006 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; - - if(fread( &v, sizeof(v), 1, fin ) != 1) - return UNZ_EOF; - - *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; - - if(fread( &v, sizeof(v), 1, fin ) != 1) - return UNZ_EOF; - - *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 ? (uInt)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 */ - r.base = 0; - } - 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/unzip.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/unzip.h deleted file mode 100644 index 5cbfce93..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/unzip.h +++ /dev/null @@ -1,321 +0,0 @@ -/* -Copyright (C) 1999-2006 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/vfs.c b/misc/mediasource/extra/netradiant-src/tools/quake3/common/vfs.c deleted file mode 100644 index 86a749c7..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/vfs.c +++ /dev/null @@ -1,396 +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 -#include -#include - -#include "cmdlib.h" -#include "mathlib.h" -#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+1]; -static int g_numDirs; -char g_strForbiddenDirs[VFS_MAXDIRS][PATH_MAX+1]; -int g_numForbiddenDirs = 0; -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; - int j; - - for(j = 0; j < g_numForbiddenDirs; ++j) - { - if(!Q_stricmp(path, g_strForbiddenDirs[j]) - || (strlen(path) > strlen(g_strForbiddenDirs[j]) && path[strlen(path) - strlen(g_strForbiddenDirs[j]) - 1] == '/' && !Q_stricmp(path + strlen(path) - strlen(g_strForbiddenDirs[j]), g_strForbiddenDirs[j]))) - break; - } - if(j < g_numForbiddenDirs) - return; - - if (g_numDirs == VFS_MAXDIRS) - return; - - Sys_Printf ("VFS Init: %s\n", path); - - strncpy (g_strDirs[g_numDirs], path, PATH_MAX); - g_strDirs[g_numDirs][PATH_MAX] = 0; - 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; - - for(j = 0; j < g_numForbiddenDirs; ++j) - if(!Q_stricmp(name, g_strForbiddenDirs[j])) - break; - if(j < g_numForbiddenDirs) - continue; - - dirlist = g_strdup(name); - - { - char *ext = strrchr (dirlist, '.'); - - if(ext && !Q_stricmp(ext, ".pk3dir")) - { - if (g_numDirs == VFS_MAXDIRS) - continue; - snprintf(g_strDirs[g_numDirs], PATH_MAX, "%s/%s", path, name); - g_strDirs[g_numDirs][PATH_MAX] = '\0'; - vfsFixDOSName (g_strDirs[g_numDirs]); - vfsAddSlash (g_strDirs[g_numDirs]); - ++g_numDirs; - } - - 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) - { - fclose(f); - return -1; - } - - if(fread (*bufferptr, 1, len, f) != (size_t) len) - { - fclose(f); - return -1; - } - 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) - { - fclose(f); - return -1; - } - - if(fread (*bufferptr, 1, len, f) != (size_t) len) - { - fclose(f); - return -1; - } - 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/misc/mediasource/extra/netradiant-src/tools/quake3/common/vfs.h b/misc/mediasource/extra/netradiant-src/tools/quake3/common/vfs.h deleted file mode 100644 index 93731a1e..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/common/vfs.h +++ /dev/null @@ -1,58 +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_ - -// to get PATH_MAX -#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 - -#define VFS_MAXDIRS 64 - -void vfsInitDirectory (const char *path); -void vfsShutdown (); -int vfsGetFileCount (const char *filename); -int vfsLoadFile (const char *filename, void **buffer, int index); - -extern char g_strForbiddenDirs[VFS_MAXDIRS][PATH_MAX+1]; -extern int g_numForbiddenDirs; - -#endif // _VFS_H_ diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/.cvswrappers b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/.cvswrappers deleted file mode 100644 index 2ea7d171..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/.cvswrappers +++ /dev/null @@ -1,2 +0,0 @@ -*.dsp -m 'COPY' -k 'b' -*.dsw -m 'COPY' -k 'b' diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/3dslib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/3dslib.c deleted file mode 100644 index e2012c70..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/3dslib.c +++ /dev/null @@ -1,651 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/3dslib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/3dslib.h deleted file mode 100644 index 406fe2d7..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/3dslib.h +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -{ - 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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/compress.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/compress.c deleted file mode 100644 index fdf9043a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/compress.c +++ /dev/null @@ -1,771 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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 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>8)&255; - *out_p++ = (in.count>>16)&255; - *out_p++ = (in.count>>24)&255; - - // write head index - for (i=0 ; i>8)&255; - *out_p++ = (i>>16)&255; - *out_p++ = (i>>24)&255; - - // write the L column - for (i=0 ; i 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 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>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 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) - max = in.count - i; - - start = lzss_head[val]; - while (start != -1 && start >= i-BACK_WINDOW) - { - // count match length - for (j=0 ; 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 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<>3] |= 1<<(outbits&7); - } - else - { // output a phrase - outbits++; // leave a 0 bit to mark phrase - for (j=0 ; j>3] |= 1<<(outbits&7); - for (j=0 ; j>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 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 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 max) - max = hnodes1[i][j].count; - } - if (max == 0) - max = 1; - total = 0; - for (j=0 ; j 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>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<>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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/images.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/images.c deleted file mode 100644 index 5009ae38..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/images.c +++ /dev/null @@ -1,486 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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 ; ybyteimagewidth || 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 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 -#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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/md3lib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/md3lib.h deleted file mode 100644 index fbf48b57..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/md3lib.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "../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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/models.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/models.c deleted file mode 100644 index b87dc625..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/models.c +++ /dev/null @@ -1,2155 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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 ; fshaders[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; iverts[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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/oldstuff.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/oldstuff.c deleted file mode 100644 index 045c67e7..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/oldstuff.c +++ /dev/null @@ -1,151 +0,0 @@ -/* -Copyright (C) 1999-2006 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 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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/p3dlib.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/p3dlib.c deleted file mode 100644 index 3ccdfbe1..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/p3dlib.c +++ /dev/null @@ -1,345 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/p3dlib.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/p3dlib.h deleted file mode 100644 index 1bd63078..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/p3dlib.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - - -#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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/polyset.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/polyset.c deleted file mode 100644 index cdb0cda7..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/polyset.c +++ /dev/null @@ -1,273 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/q3data.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/q3data.c deleted file mode 100644 index 81f4ae61..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/q3data.c +++ /dev/null @@ -1,666 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -*/ - -#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 ; id_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] [-dump ] [-release ] [-only ] [-3dsconvert ] [-verbose] [file.qdt]"); - - for ( ; i -#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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/stripper.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/stripper.c deleted file mode 100644 index 76fc96b3..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/stripper.c +++ /dev/null @@ -1,303 +0,0 @@ -/* -Copyright (C) 1999-2006 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 -#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/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/video.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/video.c deleted file mode 100644 index afabdeb9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3data/video.c +++ /dev/null @@ -1,1153 +0,0 @@ -/* -Copyright (C) 1999-2006 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 "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 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/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/.patchsets b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/.patchsets deleted file mode 100644 index 70846872..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/.patchsets +++ /dev/null @@ -1,3 +0,0 @@ -master = https://zerowing.idsoftware.com/svn/radiant/GtkRadiant/trunk/tools/quake3/q3map2 -revisions_applied = 1-321 - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/branch-manager b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/branch-manager deleted file mode 100644 index 2fd5a8fd..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/branch-manager +++ /dev/null @@ -1,344 +0,0 @@ -#!/usr/bin/perl - -use strict; -use warnings; - -sub OutputOf($@) -{ - my ($cmd, @args) = @_; - $cmd =~ s/#(\d)/"\$ARG$1"/g; - $ENV{"ARG$_"} = $args[$_-1] - for 1..@args; - - open my $fh, '-|', $cmd - or die "popen $cmd: $!"; - - $ENV{"ARG$_"} = '' - for 1..@args; - - undef local $/; - my $ret = <$fh>; - close $fh; - - return $ret; -} - -my %conf = -( - master => '', - revisions_applied => '' -); -my @revisions_applied = (); # array of [first, last] ranges - -sub LoadSettings() -{ - open my $fh, '<', ".patchsets" - or return; - while(<$fh>) - { - chomp; - /^([^=]*?)\s*=\s*(.*?)$/s - or next; - die "Invalid config item: $1 (allowed: @{[sort keys %conf]})" - if not exists $conf{$1}; - $conf{$1} = $2; - } - - @revisions_applied = map { /^(\d+)-(\d+)$/s or die "Invalid revision spec $_"; [$1, $2]; } split /,/, $conf{revisions_applied}; -} - -sub WriteSettings() -{ - $conf{revisions_applied} = join ',', map { "$_->[0]-$_->[1]" } @revisions_applied; - - open my $fh, '>', ".patchsets" - or die "writing settings: $!"; - for(sort keys %conf) - { - print $fh "$_ = $conf{$_}\n"; - } -} - -sub AddPatch($$) -{ - my ($first, $last) = @_; - die "Invalid range" if $first > $last; - - my @rev = sort { $a->[0] <=> $b->[0] } (@revisions_applied, [$first, $last]); - - my $i = 0; - while($i < @rev - 1) - { - my $a = $rev[$i][0]; - my $b = $rev[$i][1]; - my $c = $rev[$i+1][0]; - my $d = $rev[$i+1][1]; - - if($b >= $c) - { - die "overlapping patch: $a-$b overlaps $c-$d"; - } - if($b == $c - 1) - { - splice @rev, $i, 2, [$a, $d]; - next; - } - ++$i; - } - - @revisions_applied = @rev; -} - -sub RemovePatch($$) -{ - my ($first, $last) = @_; - die "Invalid range" if $first > $last; - - my @rev = sort { $a->[0] <=> $b->[0] } (@revisions_applied); - - my $i = 0; - while($i < @rev) - { - my $a = $rev[$i][0]; - my $b = $rev[$i][1]; - - if($first >= $a && $last <= $b) - { - # this is the range - my @replacement; - - if($first == $a && $last == $b) - { - @replacement = (); - } - elsif($first == $a) - { - @replacement = ([$last + 1, $b]); - } - elsif($last == $b) - { - @replacement = ([$a, $first - 1]); - } - else - { - @replacement = ([$a, $first - 1], [$last + 1, $b]); - } - splice @rev, $i, 1, @replacement; - @revisions_applied = @rev; - return; - } - } - - die "could not remove range: not in set"; -} - -sub GetUnappliedRanges($) -{ - my ($lastrev) = @_; - my @unapplied = (); - - my $cur = 0; - for(@revisions_applied) - { - my ($a, $b) = @$_; - if($a - 1 >= $cur + 1) - { - push @unapplied, [$cur + 1, $a - 1]; - } - $cur = $b; - } - if($lastrev >= $cur + 1) - { - push @unapplied, [$cur + 1, $lastrev]; - } - return @unapplied; -} - -sub GetMasterRev() -{ - my $svninfo = OutputOf 'svn info #1', $conf{master}; - $svninfo =~ /^Last Changed Rev: (\d+)$/m - or die "could not get svn info"; - return $1; -} - -sub GetLog($$) -{ - my ($first, $last) = @_; - my $log = OutputOf 'svn log -r#1:#2 #3', $first, $last, $conf{master}; - $log =~ s/^-*$//gm; - $log =~ s/\n+/\n/gs; - $log =~ s/^\n//s; - $log =~ s/\n$//s; - return $log; -} - -sub GetDiff($$) -{ - my ($first, $last) = @_; - return OutputOf 'svn diff -r#1:#2 #3', $first-1, $last, $conf{master}; -} - -my ($cmd, @args) = @ARGV; -$cmd = 'help' if not defined $cmd; - -if($cmd eq 'info') -{ - LoadSettings(); - for(@revisions_applied) - { - my ($a, $b) = @$_; - print "Applied: $a to $b\n"; - } - for(GetUnappliedRanges(GetMasterRev())) - { - my ($a, $b) = @$_; - print "Unapplied: $a to $b\n"; - } -} -elsif($cmd eq 'unmerged-diff') -{ - LoadSettings(); - my @autoadd = (); - for(GetUnappliedRanges(GetMasterRev())) - { - my ($a, $b) = @$_; - my $log = GetLog $a, $b; - if($log eq '') - { - push @autoadd, [$a, $b]; - next; - } - $log =~ s/^/ /gm; - print "Unapplied: $a to $b\n"; - print "$log\n"; - print GetDiff $a, $b; - print "\n"; - } - for(@autoadd) - { - my ($a, $b) = @$_; - print "Autofilled revision hole $a to $b\n"; - AddPatch $a, $b; - } - WriteSettings() if @autoadd; -} -elsif($cmd eq 'unmerged') -{ - LoadSettings(); - my @autoadd = (); - for(GetUnappliedRanges(GetMasterRev())) - { - my ($a, $b) = @$_; - my $log = GetLog $a, $b; - if($log eq '') - { - push @autoadd, [$a, $b]; - next; - } - $log =~ s/^/ /gm; - print "Unapplied: $a to $b\n"; - print "$log\n\n"; - } - for(@autoadd) - { - my ($a, $b) = @$_; - print "Autofilled revision hole $a to $b\n"; - AddPatch $a, $b; - } - WriteSettings() if @autoadd; -} -elsif($cmd eq 'merge') -{ - my ($first, $last, $force) = @args; - die "Usage: $0 merge first last [--force]" - if not defined $first; - $last = $first if not defined $last; - - die "Usage: $0 merge first last" - if "$first$last" =~ /[^0-9]/; - - die "There is an uncommitted merge" - if -f '.commitmsg' and $force ne '--force'; - - LoadSettings(); - AddPatch $first, $last; - - print OutputOf 'svn merge -r#1:#2 #3', ($first - 1), $last, $conf{master}; - print "You may also want to run $0 unmerged to fill possible revision holes\n"; - print "Make sure there are no conflicts, then run $0 commit\n"; - print "To abort, use $0 revert\n"; - - open my $fh, '>>', '.commitmsg' - or die "open .commitmsg"; - print $fh GetLog $first, $last; - print $fh "\n"; - close $fh; - - WriteSettings(); -} -elsif($cmd eq 'undo') -{ - my ($first, $last, $force) = @args; - die "Usage: $0 undo first last" - if not defined $first; - $last = $first if not defined $last; - - die "Usage: $0 merge first last" - if "$first$last" =~ /[^0-9]/; - - die "There is an uncommitted merge" - if -f '.commitmsg' and $force ne '--force'; - - LoadSettings(); - RemovePatch $first, $last; - - print OutputOf 'svn merge -r#2:#1 #3', ($first - 1), $last, $conf{master}; - print "Make sure there are no conflicts, then run $0 commit\n"; - print "To abort, use $0 revert\n"; - - open my $fh, '>>', '.commitmsg' - or die "open .commitmsg"; - print $fh "undo the following merge:\n", GetLog $first, $last; - close $fh; - - WriteSettings(); -} -elsif($cmd eq 'commit') -{ - system 'vim .commitmsg'; - print "Hit Enter if OK to commit, Ctrl-C otherwise...\n"; - my $ok = ; - if(!system 'svn commit -F .commitmsg') - { - unlink '.commitmsg'; - } -} -elsif($cmd eq 'revert') -{ - if(!system 'svn revert -R .') - { - unlink '.commitmsg'; - } -} -elsif($cmd eq 'init') -{ - my ($master, $rev) = @args; - $conf{master} = $master; - @revisions_applied = [1, $rev]; - WriteSettings(); -} -else -{ - print <side = side; - sideRef->next = next; - return sideRef; -} - - - -/* -CountBrushList() -counts the number of brushes in a brush linked list -*/ - -int CountBrushList( brush_t *brushes ) -{ - int c = 0; - - - /* count brushes */ - for( ; brushes != NULL; brushes = brushes->next ) - c++; - return c; -} - - - -/* -AllocBrush() -allocates a new brush -*/ - -brush_t *AllocBrush( int numSides ) -{ - brush_t *bb; - size_t c; - - - /* allocate and clear */ - if( numSides <= 0 ) - Error( "AllocBrush called with numsides = %d", numSides ); - c = (size_t)&(((brush_t*) 0)->sides[ numSides ]); - bb = safe_malloc( c ); - memset( bb, 0, c ); - if( numthreads == 1 ) - numActiveBrushes++; - - /* return it */ - return bb; -} - - - -/* -FreeBrush() -frees a single brush and all sides/windings -*/ - -void FreeBrush( brush_t *b ) -{ - int i; - - - /* error check */ - if( *((unsigned int*) b) == 0xFEFEFEFE ) - { - Sys_FPrintf( SYS_VRB, "WARNING: Attempt to free an already freed brush!\n" ); - return; - } - - /* free brush sides */ - for( i = 0; i < b->numsides; i++ ) - if( b->sides[i].winding != NULL ) - FreeWinding( b->sides[ i ].winding ); - - /* ydnar: overwrite it */ - memset( b, 0xFE, (size_t)&(((brush_t*) 0)->sides[ b->numsides ]) ); - *((unsigned int*) b) = 0xFEFEFEFE; - - /* free it */ - free( b ); - if( numthreads == 1 ) - numActiveBrushes--; -} - - - -/* -FreeBrushList() -frees a linked list of brushes -*/ - -void FreeBrushList( brush_t *brushes ) -{ - brush_t *next; - - - /* walk brush list */ - for( ; brushes != NULL; brushes = next ) - { - next = brushes->next; - FreeBrush( brushes ); - } -} - - - -/* -CopyBrush() -duplicates the brush, sides, and windings -*/ - -brush_t *CopyBrush( brush_t *brush ) -{ - brush_t *newBrush; - size_t size; - int i; - - - /* copy brush */ - size = (size_t)&(((brush_t*) 0)->sides[ brush->numsides ]); - newBrush = AllocBrush( brush->numsides ); - memcpy( newBrush, brush, size ); - - /* ydnar: nuke linked list */ - newBrush->next = NULL; - - /* copy sides */ - for( i = 0; i < brush->numsides; i++ ) - { - if( brush->sides[ i ].winding != NULL ) - newBrush->sides[ i ].winding = CopyWinding( brush->sides[ i ].winding ); - } - - /* return it */ - return newBrush; -} - - - - -/* -BoundBrush() -sets the mins/maxs based on the windings -returns false if the brush doesn't enclose a valid volume -*/ - -qboolean BoundBrush( brush_t *brush ) -{ - int i, j; - winding_t *w; - - - ClearBounds( brush->mins, brush->maxs ); - for( i = 0; i < brush->numsides; i++ ) - { - w = brush->sides[ i ].winding; - if( w == NULL ) - continue; - for( j = 0; j < w->numpoints; j++ ) - AddPointToBounds( w->p[ j ], brush->mins, brush->maxs ); - } - - for( i = 0; i < 3; i++ ) - { - if( brush->mins[ i ] < MIN_WORLD_COORD || brush->maxs[ i ] > MAX_WORLD_COORD || brush->mins[i] >= brush->maxs[ i ] ) - return qfalse; - } - - return qtrue; -} - - - - -/* -SnapWeldVector() - ydnar -welds two vec3_t's into a third, taking into account nearest-to-integer -instead of averaging -*/ - -#define SNAP_EPSILON 0.01 - -void SnapWeldVector( vec3_t a, vec3_t b, vec3_t out ) -{ - int i; - vec_t ai, bi, outi; - - - /* dummy check */ - if( a == NULL || b == NULL || out == NULL ) - return; - - /* do each element */ - for( i = 0; i < 3; i++ ) - { - /* round to integer */ - ai = Q_rint( a[ i ] ); - bi = Q_rint( a[ i ] ); - - /* prefer exact integer */ - if( ai == a[ i ] ) - out[ i ] = a[ i ]; - else if( bi == b[ i ] ) - out[ i ] = b[ i ]; - - /* use nearest */ - else if( fabs( ai - a[ i ] ) < fabs( bi < b[ i ] ) ) - out[ i ] = a[ i ]; - else - out[ i ] = b[ i ]; - - /* snap */ - outi = Q_rint( out[ i ] ); - if( fabs( outi - out[ i ] ) <= SNAP_EPSILON ) - out[ i ] = outi; - } -} - -/* -================== -SnapWeldVectorAccu - -Welds two vectors into a third, taking into account nearest-to-integer -instead of averaging. -================== -*/ -void SnapWeldVectorAccu(vec3_accu_t a, vec3_accu_t b, vec3_accu_t out) -{ - // I'm just preserving what I think was the intended logic of the original - // SnapWeldVector(). I'm not actually sure where this function should even - // be used. I'd like to know which kinds of problems this function addresses. - - // TODO: I thought we're snapping all coordinates to nearest 1/8 unit? - // So what is natural about snapping to the nearest integer? Maybe we should - // be snapping to the nearest 1/8 unit instead? - - int i; - vec_accu_t ai, bi, ad, bd; - - if (a == NULL || b == NULL || out == NULL) - Error("SnapWeldVectorAccu: NULL argument"); - - for (i = 0; i < 3; i++) - { - ai = Q_rintAccu(a[i]); - bi = Q_rintAccu(b[i]); - ad = fabs(ai - a[i]); - bd = fabs(bi - b[i]); - - if (ad < bd) - { - if (ad < SNAP_EPSILON) out[i] = ai; - else out[i] = a[i]; - } - else - { - if (bd < SNAP_EPSILON) out[i] = bi; - else out[i] = b[i]; - } - } -} - -/* -FixWinding() - ydnar -removes degenerate edges from a winding -returns qtrue if the winding is valid -*/ - -#define DEGENERATE_EPSILON 0.1 - -qboolean FixWinding( winding_t *w ) -{ - qboolean valid = qtrue; - int i, j, k; - vec3_t vec; - float dist; - - - /* dummy check */ - if( !w ) - return qfalse; - - /* check all verts */ - for( i = 0; i < w->numpoints; i++ ) - { - /* don't remove points if winding is a triangle */ - if( w->numpoints == 3 ) - return valid; - - /* get second point index */ - j = (i + 1) % w->numpoints; - - /* degenerate edge? */ - VectorSubtract( w->p[ i ], w->p[ j ], vec ); - dist = VectorLength( vec ); - if( dist < DEGENERATE_EPSILON ) - { - valid = qfalse; - //Sys_FPrintf( SYS_VRB, "WARNING: Degenerate winding edge found, fixing...\n" ); - - /* create an average point (ydnar 2002-01-26: using nearest-integer weld preference) */ - SnapWeldVector( w->p[ i ], w->p[ j ], vec ); - VectorCopy( vec, w->p[ i ] ); - //VectorAdd( w->p[ i ], w->p[ j ], vec ); - //VectorScale( vec, 0.5, w->p[ i ] ); - - /* move the remaining verts */ - for( k = i + 2; k < w->numpoints; k++ ) - { - VectorCopy( w->p[ k ], w->p[ k - 1 ] ); - } - w->numpoints--; - } - } - - /* one last check and return */ - if( w->numpoints < 3 ) - valid = qfalse; - return valid; -} - -/* -================== -FixWindingAccu - -Removes degenerate edges (edges that are too short) from a winding. -Returns qtrue if the winding has been altered by this function. -Returns qfalse if the winding is untouched by this function. - -It's advised that you check the winding after this function exits to make -sure it still has at least 3 points. If that is not the case, the winding -cannot be considered valid. The winding may degenerate to one or two points -if the some of the winding's points are close together. -================== -*/ -qboolean FixWindingAccu(winding_accu_t *w) -{ - int i, j, k; - vec3_accu_t vec; - vec_accu_t dist; - qboolean done, altered; - - if (w == NULL) Error("FixWindingAccu: NULL argument"); - - altered = qfalse; - - while (qtrue) - { - if (w->numpoints < 2) break; // Don't remove the only remaining point. - done = qtrue; - for (i = 0; i < w->numpoints; i++) - { - j = (((i + 1) == w->numpoints) ? 0 : (i + 1)); - - VectorSubtractAccu(w->p[i], w->p[j], vec); - dist = VectorLengthAccu(vec); - if (dist < DEGENERATE_EPSILON) - { - // TODO: I think the "snap weld vector" was written before - // some of the math precision fixes, and its purpose was - // probably to address math accuracy issues. We can think - // about changing the logic here. Maybe once plane distance - // gets 64 bits, we can look at it then. - SnapWeldVectorAccu(w->p[i], w->p[j], vec); - VectorCopyAccu(vec, w->p[i]); - for (k = j + 1; k < w->numpoints; k++) - { - VectorCopyAccu(w->p[k], w->p[k - 1]); - } - w->numpoints--; - altered = qtrue; - // The only way to finish off fixing the winding consistently and - // accurately is by fixing the winding all over again. For example, - // the point at index i and the point at index i-1 could now be - // less than the epsilon distance apart. There are too many special - // case problems we'd need to handle if we didn't start from the - // beginning. - done = qfalse; - break; // This will cause us to return to the "while" loop. - } - } - if (done) break; - } - - return altered; -} - - -/* -CreateBrushWindings() -makes basewindigs for sides and mins/maxs for the brush -returns false if the brush doesn't enclose a valid volume -*/ - -qboolean CreateBrushWindings( brush_t *brush ) -{ - int i, j; -#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES - winding_accu_t *w; -#else - winding_t *w; -#endif - side_t *side; - plane_t *plane; - - - /* walk the list of brush sides */ - for( i = 0; i < brush->numsides; i++ ) - { - /* get side and plane */ - side = &brush->sides[ i ]; - plane = &mapplanes[ side->planenum ]; - - /* make huge winding */ -#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES - w = BaseWindingForPlaneAccu(plane->normal, plane->dist); -#else - w = BaseWindingForPlane( plane->normal, plane->dist ); -#endif - - /* walk the list of brush sides */ - for( j = 0; j < brush->numsides && w != NULL; j++ ) - { - if( i == j ) - continue; - if( brush->sides[ j ].planenum == (brush->sides[ i ].planenum ^ 1) ) - continue; /* back side clipaway */ - if( brush->sides[ j ].bevel ) - continue; - plane = &mapplanes[ brush->sides[ j ].planenum ^ 1 ]; -#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES - ChopWindingInPlaceAccu(&w, plane->normal, plane->dist, 0); -#else - ChopWindingInPlace( &w, plane->normal, plane->dist, 0 ); // CLIP_EPSILON ); -#endif - - /* ydnar: fix broken windings that would generate trifans */ -#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES - // I think it's better to FixWindingAccu() once after we chop with all planes - // so that error isn't multiplied. There is nothing natural about welding - // the points unless they are the final endpoints. ChopWindingInPlaceAccu() - // is able to handle all kinds of degenerate windings. -#else - FixWinding( w ); -#endif - } - - /* set side winding */ -#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES - if (w != NULL) - { - FixWindingAccu(w); - if (w->numpoints < 3) - { - FreeWindingAccu(w); - w = NULL; - } - } - side->winding = (w ? CopyWindingAccuToRegular(w) : NULL); - if (w) FreeWindingAccu(w); -#else - side->winding = w; -#endif - } - - /* find brush bounds */ - return BoundBrush( brush ); -} - - - - -/* -================== -BrushFromBounds - -Creates a new axial brush -================== -*/ -brush_t *BrushFromBounds (vec3_t mins, vec3_t maxs) -{ - brush_t *b; - int i; - vec3_t normal; - vec_t dist; - - b = AllocBrush (6); - b->numsides = 6; - for (i=0 ; i<3 ; i++) - { - VectorClear (normal); - normal[i] = 1; - dist = maxs[i]; - b->sides[i].planenum = FindFloatPlane (normal, dist, 1, (vec3_t*) &maxs ); - - normal[i] = -1; - dist = -mins[i]; - b->sides[3+i].planenum = FindFloatPlane (normal, dist, 1, (vec3_t*) &mins ); - } - - CreateBrushWindings (b); - - return b; -} - -/* -================== -BrushVolume - -================== -*/ -vec_t BrushVolume (brush_t *brush) -{ - int i; - winding_t *w; - vec3_t corner; - vec_t d, area, volume; - plane_t *plane; - - if (!brush) - return 0; - - // grab the first valid point as the corner - - w = NULL; - for (i=0 ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (w) - break; - } - if (!w) - return 0; - VectorCopy (w->p[0], corner); - - // make tetrahedrons to all other faces - - volume = 0; - for ( ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (!w) - continue; - plane = &mapplanes[brush->sides[i].planenum]; - d = -(DotProduct (corner, plane->normal) - plane->dist); - area = WindingArea (w); - volume += d*area; - } - - volume /= 3; - return volume; -} - - - -/* -WriteBSPBrushMap() -writes a map with the split bsp brushes -*/ - -void WriteBSPBrushMap( char *name, brush_t *list ) -{ - FILE *f; - side_t *s; - int i; - winding_t *w; - - - /* note it */ - Sys_Printf( "Writing %s\n", name ); - - /* open the map file */ - f = fopen( name, "wb" ); - if( f == NULL ) - Error( "Can't write %s\b", name ); - - fprintf (f, "{\n\"classname\" \"worldspawn\"\n"); - - for ( ; list ; list=list->next ) - { - fprintf (f, "{\n"); - for (i=0,s=list->sides ; inumsides ; i++,s++) - { - // TODO: See if we can use a smaller winding to prevent resolution loss. - // Is WriteBSPBrushMap() used only to decompile maps? - w = BaseWindingForPlane (mapplanes[s->planenum].normal, mapplanes[s->planenum].dist); - - fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]); - fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]); - fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]); - - fprintf (f, "notexture 0 0 0 1 1\n" ); - FreeWinding (w); - } - fprintf (f, "}\n"); - } - fprintf (f, "}\n"); - - fclose (f); - -} - - - -/* -FilterBrushIntoTree_r() -adds brush reference to any intersecting bsp leafnode -*/ - -int FilterBrushIntoTree_r( brush_t *b, node_t *node ) -{ - brush_t *front, *back; - int c; - - - /* dummy check */ - if( b == NULL ) - return 0; - - /* add it to the leaf list */ - if( node->planenum == PLANENUM_LEAF ) - { - /* something somewhere is hammering brushlist */ - b->next = node->brushlist; - node->brushlist = b; - - /* classify the leaf by the structural brush */ - if( !b->detail ) - { - if( b->opaque ) - { - node->opaque = qtrue; - node->areaportal = qfalse; - } - else if( b->compileFlags & C_AREAPORTAL ) - { - if( !node->opaque ) - node->areaportal = qtrue; - } - } - - return 1; - } - - /* split it by the node plane */ - c = b->numsides; - SplitBrush( b, node->planenum, &front, &back ); - FreeBrush( b ); - - c = 0; - c += FilterBrushIntoTree_r( front, node->children[ 0 ] ); - c += FilterBrushIntoTree_r( back, node->children[ 1 ] ); - - return c; -} - - - -/* -FilterDetailBrushesIntoTree -fragment all the detail brushes into the structural leafs -*/ - -void FilterDetailBrushesIntoTree( entity_t *e, tree_t *tree ) -{ - brush_t *b, *newb; - int r; - int c_unique, c_clusters; - int i; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- FilterDetailBrushesIntoTree ---\n" ); - - /* walk the list of brushes */ - c_unique = 0; - c_clusters = 0; - for( b = e->brushes; b; b = b->next ) - { - if( !b->detail ) - continue; - c_unique++; - newb = CopyBrush( b ); - r = FilterBrushIntoTree_r( newb, tree->headnode ); - c_clusters += r; - - /* mark all sides as visible so drawsurfs are created */ - if( r ) - { - for( i = 0; i < b->numsides; i++ ) - { - if( b->sides[ i ].winding ) - b->sides[ i ].visible = qtrue; - } - } - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d detail brushes\n", c_unique ); - Sys_FPrintf( SYS_VRB, "%9d cluster references\n", c_clusters ); -} - -/* -===================== -FilterStructuralBrushesIntoTree - -Mark the leafs as opaque and areaportals -===================== -*/ -void FilterStructuralBrushesIntoTree( entity_t *e, tree_t *tree ) { - brush_t *b, *newb; - int r; - int c_unique, c_clusters; - int i; - - Sys_FPrintf (SYS_VRB, "--- FilterStructuralBrushesIntoTree ---\n"); - - c_unique = 0; - c_clusters = 0; - for ( b = e->brushes ; b ; b = b->next ) { - if ( b->detail ) { - continue; - } - c_unique++; - newb = CopyBrush( b ); - r = FilterBrushIntoTree_r( newb, tree->headnode ); - c_clusters += r; - - // mark all sides as visible so drawsurfs are created - if ( r ) { - for ( i = 0 ; i < b->numsides ; i++ ) { - if ( b->sides[i].winding ) { - b->sides[i].visible = qtrue; - } - } - } - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d structural brushes\n", c_unique ); - Sys_FPrintf( SYS_VRB, "%9d cluster references\n", c_clusters ); -} - - - -/* -================ -AllocTree -================ -*/ -tree_t *AllocTree (void) -{ - tree_t *tree; - - tree = safe_malloc(sizeof(*tree)); - memset (tree, 0, sizeof(*tree)); - ClearBounds (tree->mins, tree->maxs); - - return tree; -} - -/* -================ -AllocNode -================ -*/ -node_t *AllocNode (void) -{ - node_t *node; - - node = safe_malloc(sizeof(*node)); - memset (node, 0, sizeof(*node)); - - return node; -} - - -/* -================ -WindingIsTiny - -Returns true if the winding would be crunched out of -existance by the vertex snapping. -================ -*/ -#define EDGE_LENGTH 0.2 -qboolean WindingIsTiny (winding_t *w) -{ -/* - if (WindingArea (w) < 1) - return qtrue; - return qfalse; -*/ - int i, j; - vec_t len; - vec3_t delta; - int edges; - - edges = 0; - for (i=0 ; inumpoints ; i++) - { - j = i == w->numpoints - 1 ? 0 : i+1; - VectorSubtract (w->p[j], w->p[i], delta); - len = VectorLength (delta); - if (len > EDGE_LENGTH) - { - if (++edges == 3) - return qfalse; - } - } - return qtrue; -} - -/* -================ -WindingIsHuge - -Returns true if the winding still has one of the points -from basewinding for plane -================ -*/ -qboolean WindingIsHuge (winding_t *w) -{ - int i, j; - - for (i=0 ; inumpoints ; i++) - { - for (j=0 ; j<3 ; j++) - if (w->p[i][j] <= MIN_WORLD_COORD || w->p[i][j] >= MAX_WORLD_COORD) - return qtrue; - } - return qfalse; -} - -//============================================================ - -/* -================== -BrushMostlyOnSide - -================== -*/ -int BrushMostlyOnSide (brush_t *brush, plane_t *plane) -{ - int i, j; - winding_t *w; - vec_t d, max; - int side; - - max = 0; - side = PSIDE_FRONT; - for (i=0 ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (!w) - continue; - for (j=0 ; jnumpoints ; j++) - { - d = DotProduct (w->p[j], plane->normal) - plane->dist; - if (d > max) - { - max = d; - side = PSIDE_FRONT; - } - if (-d > max) - { - max = -d; - side = PSIDE_BACK; - } - } - } - return side; -} - - - -/* -SplitBrush() -generates two new brushes, leaving the original unchanged -*/ - -void SplitBrush( brush_t *brush, int planenum, brush_t **front, brush_t **back ) -{ - brush_t *b[2]; - int i, j; - winding_t *w, *cw[2], *midwinding; - plane_t *plane, *plane2; - side_t *s, *cs; - float d, d_front, d_back; - - - *front = NULL; - *back = NULL; - plane = &mapplanes[planenum]; - - // check all points - d_front = d_back = 0; - for (i=0 ; inumsides ; i++) - { - w = brush->sides[i].winding; - if (!w) - continue; - for (j=0 ; jnumpoints ; j++) - { - d = DotProduct (w->p[j], plane->normal) - plane->dist; - if (d > 0 && d > d_front) - d_front = d; - if (d < 0 && d < d_back) - d_back = d; - } - } - - if (d_front < 0.1) // PLANESIDE_EPSILON) - { // only on back - *back = CopyBrush( brush ); - return; - } - - if (d_back > -0.1) // PLANESIDE_EPSILON) - { // only on front - *front = CopyBrush( brush ); - return; - } - - // create a new winding from the split plane - w = BaseWindingForPlane (plane->normal, plane->dist); - for (i=0 ; inumsides && w ; i++) - { - plane2 = &mapplanes[brush->sides[i].planenum ^ 1]; - ChopWindingInPlace (&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON); - } - - if (!w || WindingIsTiny (w) ) - { // the brush isn't really split - int side; - - side = BrushMostlyOnSide (brush, plane); - if (side == PSIDE_FRONT) - *front = CopyBrush (brush); - if (side == PSIDE_BACK) - *back = CopyBrush (brush); - return; - } - - if( WindingIsHuge( w ) ) - Sys_FPrintf( SYS_VRB,"WARNING: huge winding\n" ); - - midwinding = w; - - // split it for real - - for (i=0 ; i<2 ; i++) - { - b[i] = AllocBrush (brush->numsides+1); - memcpy( b[i], brush, sizeof( brush_t ) - sizeof( brush->sides ) ); - b[i]->numsides = 0; - b[i]->next = NULL; - b[i]->original = brush->original; - } - - // split all the current windings - - for (i=0 ; inumsides ; i++) - { - s = &brush->sides[i]; - w = s->winding; - if (!w) - continue; - ClipWindingEpsilon (w, plane->normal, plane->dist, - 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]); - for (j=0 ; j<2 ; j++) - { - if (!cw[j]) - continue; - cs = &b[j]->sides[b[j]->numsides]; - b[j]->numsides++; - *cs = *s; - cs->winding = cw[j]; - } - } - - - // see if we have valid polygons on both sides - for (i=0 ; i<2 ; i++) - { - if (b[i]->numsides < 3 || !BoundBrush (b[i])) - { - if (b[i]->numsides >= 3) - Sys_FPrintf (SYS_VRB,"bogus brush after clip\n"); - FreeBrush (b[i]); - b[i] = NULL; - } - } - - if ( !(b[0] && b[1]) ) - { - if (!b[0] && !b[1]) - Sys_FPrintf (SYS_VRB,"split removed brush\n"); - else - Sys_FPrintf (SYS_VRB,"split not on both sides\n"); - if (b[0]) - { - FreeBrush (b[0]); - *front = CopyBrush (brush); - } - if (b[1]) - { - FreeBrush (b[1]); - *back = CopyBrush (brush); - } - return; - } - - // add the midwinding to both sides - for (i=0 ; i<2 ; i++) - { - cs = &b[i]->sides[b[i]->numsides]; - b[i]->numsides++; - - cs->planenum = planenum^i^1; - cs->shaderInfo = NULL; - if (i==0) - cs->winding = CopyWinding (midwinding); - else - cs->winding = midwinding; - } - - { - vec_t v1; - int i; - - - for (i=0 ; i<2 ; i++) - { - v1 = BrushVolume (b[i]); - if (v1 < 1.0) - { - FreeBrush (b[i]); - b[i] = NULL; - // Sys_FPrintf (SYS_VRB,"tiny volume after clip\n"); - } - } - } - - *front = b[0]; - *back = b[1]; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/brush_primit.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/brush_primit.c deleted file mode 100644 index 4a0d2520..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/brush_primit.c +++ /dev/null @@ -1,81 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define BRUSH_PRIMIT_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* ------------------------------------------------------------------------------- - -functions - -------------------------------------------------------------------------------- */ - -/* -ComputeAxisBase() -computes the base texture axis for brush primitive texturing -note: ComputeAxisBase here and in editor code must always BE THE SAME! -warning: special case behaviour of atan2( y, x ) <-> atan( y / x ) might not be the same everywhere when x == 0 -rotation by (0,RotY,RotZ) assigns X to normal -*/ - -void ComputeAxisBase( vec3_t normal, vec3_t texX, vec3_t texY ) -{ - vec_t RotY, RotZ; - - - /* do some cleaning */ - if( fabs( normal[ 0 ] ) < 1e-6 ) - normal[ 0 ]= 0.0f; - if( fabs( normal[ 1 ] ) < 1e-6 ) - normal[ 1 ]=0.0f; - if( fabs( normal[ 2 ] ) < 1e-6 ) - normal[ 2 ] = 0.0f; - - /* compute the two rotations around y and z to rotate x to normal */ - RotY = -atan2( normal[ 2 ], sqrt( normal[ 1 ] * normal[ 1 ] + normal[ 0 ] * normal[ 0 ]) ); - RotZ = atan2( normal[ 1 ], normal[ 0 ] ); - - /* rotate (0,1,0) and (0,0,1) to compute texX and texY */ - texX[ 0 ] = -sin( RotZ ); - texX[ 1 ] = cos( RotZ ); - texX[ 2 ] = 0; - - /* the texY vector is along -z (t texture coorinates axis) */ - texY[ 0 ] = -sin( RotY ) * cos( RotZ ); - texY[ 1 ] = -sin( RotY ) * sin( RotZ ); - texY[ 2 ] = -cos( RotY ); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bsp.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bsp.c deleted file mode 100644 index 79019792..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bsp.c +++ /dev/null @@ -1,990 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define BSP_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* ------------------------------------------------------------------------------- - -functions - -------------------------------------------------------------------------------- */ - -/* -ProcessAdvertisements() -copies advertisement info into the BSP structures -*/ - -static void ProcessAdvertisements( void ) { - int i; - const char* className; - const char* modelKey; - int modelNum; - bspModel_t* adModel; - bspDrawSurface_t* adSurface; - - Sys_FPrintf( SYS_VRB, "--- ProcessAdvertisements ---\n" ); - - for( i = 0; i < numEntities; i++ ) { - - /* is an advertisement? */ - className = ValueForKey( &entities[ i ], "classname" ); - - if( !Q_stricmp( "advertisement", className ) ) { - - modelKey = ValueForKey( &entities[ i ], "model" ); - - if( strlen( modelKey ) > MAX_QPATH - 1 ) { - Error( "Model Key for entity exceeds ad struct string length." ); - } else { - if( numBSPAds < MAX_MAP_ADVERTISEMENTS ) { - bspAds[numBSPAds].cellId = IntForKey( &entities[ i ], "cellId" ); - strncpy( bspAds[numBSPAds].model, modelKey, sizeof( bspAds[numBSPAds].model ) ); - - modelKey++; - modelNum = atoi( modelKey ); - adModel = &bspModels[modelNum]; - - if( adModel->numBSPSurfaces != 1 ) { - Error( "Ad cell id %d has more than one surface.", bspAds[numBSPAds].cellId ); - } - - adSurface = &bspDrawSurfaces[adModel->firstBSPSurface]; - - // store the normal for use at run time.. all ad verts are assumed to - // have identical normals (because they should be a simple rectangle) - // so just use the first vert's normal - VectorCopy( bspDrawVerts[adSurface->firstVert].normal, bspAds[numBSPAds].normal ); - - // store the ad quad for quick use at run time - if( adSurface->surfaceType == MST_PATCH ) { - int v0 = adSurface->firstVert + adSurface->patchHeight - 1; - int v1 = adSurface->firstVert + adSurface->numVerts - 1; - int v2 = adSurface->firstVert + adSurface->numVerts - adSurface->patchWidth; - int v3 = adSurface->firstVert; - VectorCopy( bspDrawVerts[v0].xyz, bspAds[numBSPAds].rect[0] ); - VectorCopy( bspDrawVerts[v1].xyz, bspAds[numBSPAds].rect[1] ); - VectorCopy( bspDrawVerts[v2].xyz, bspAds[numBSPAds].rect[2] ); - VectorCopy( bspDrawVerts[v3].xyz, bspAds[numBSPAds].rect[3] ); - } else { - Error( "Ad cell %d has an unsupported Ad Surface type.", bspAds[numBSPAds].cellId ); - } - - numBSPAds++; - } else { - Error( "Maximum number of map advertisements exceeded." ); - } - } - } - } - - Sys_FPrintf( SYS_VRB, "%9d in-game advertisements\n", numBSPAds ); -} - -/* -SetCloneModelNumbers() - ydnar -sets the model numbers for brush entities -*/ - -static void SetCloneModelNumbers( void ) -{ - int i, j; - int models; - char modelValue[ 10 ]; - const char *value, *value2, *value3; - - - /* start with 1 (worldspawn is model 0) */ - models = 1; - for( i = 1; i < numEntities; i++ ) - { - /* only entities with brushes or patches get a model number */ - if( entities[ i ].brushes == NULL && entities[ i ].patches == NULL ) - continue; - - /* is this a clone? */ - value = ValueForKey( &entities[ i ], "_ins" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ i ], "_instance" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ i ], "_clone" ); - if( value[ 0 ] != '\0' ) - continue; - - /* add the model key */ - sprintf( modelValue, "*%d", models ); - SetKeyValue( &entities[ i ], "model", modelValue ); - - /* increment model count */ - models++; - } - - /* fix up clones */ - for( i = 1; i < numEntities; i++ ) - { - /* only entities with brushes or patches get a model number */ - if( entities[ i ].brushes == NULL && entities[ i ].patches == NULL ) - continue; - - /* is this a clone? */ - value = ValueForKey( &entities[ i ], "_ins" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ i ], "_instance" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ i ], "_clone" ); - if( value[ 0 ] == '\0' ) - continue; - - /* find an entity with matching clone name */ - for( j = 0; j < numEntities; j++ ) - { - /* is this a clone parent? */ - value2 = ValueForKey( &entities[ j ], "_clonename" ); - if( value2[ 0 ] == '\0' ) - continue; - - /* do they match? */ - if( strcmp( value, value2 ) == 0 ) - { - /* get the model num */ - value3 = ValueForKey( &entities[ j ], "model" ); - if( value3[ 0 ] == '\0' ) - { - Sys_Printf( "WARNING: Cloned entity %s referenced entity without model\n", value2 ); - continue; - } - models = atoi( &value2[ 1 ] ); - - /* add the model key */ - sprintf( modelValue, "*%d", models ); - SetKeyValue( &entities[ i ], "model", modelValue ); - - /* nuke the brushes/patches for this entity (fixme: leak!) */ - entities[ i ].brushes = NULL; - entities[ i ].patches = NULL; - } - } - } -} - - - -/* -FixBrushSides() - ydnar -matches brushsides back to their appropriate drawsurface and shader -*/ - -static void FixBrushSides( entity_t *e ) -{ - int i; - mapDrawSurface_t *ds; - sideRef_t *sideRef; - bspBrushSide_t *side; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- FixBrushSides ---\n" ); - - /* walk list of drawsurfaces */ - for( i = e->firstDrawSurf; i < numMapDrawSurfs; i++ ) - { - /* get surface and try to early out */ - ds = &mapDrawSurfs[ i ]; - if( ds->outputNum < 0 ) - continue; - - /* walk sideref list */ - for( sideRef = ds->sideRef; sideRef != NULL; sideRef = sideRef->next ) - { - /* get bsp brush side */ - if( sideRef->side == NULL || sideRef->side->outputNum < 0 ) - continue; - side = &bspBrushSides[ sideRef->side->outputNum ]; - - /* set drawsurface */ - side->surfaceNum = ds->outputNum; - //% Sys_FPrintf( SYS_VRB, "DS: %7d Side: %7d ", ds->outputNum, sideRef->side->outputNum ); - - /* set shader */ - if( strcmp( bspShaders[ side->shaderNum ].shader, ds->shaderInfo->shader ) ) - { - //% Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", bspShaders[ side->shaderNum ].shader, ds->shaderInfo->shader ); - side->shaderNum = EmitShader( ds->shaderInfo->shader, &ds->shaderInfo->contentFlags, &ds->shaderInfo->surfaceFlags ); - } - } - } -} - - - -/* -ProcessWorldModel() -creates a full bsp + surfaces for the worldspawn entity -*/ - -void ProcessWorldModel( void ) -{ - int i, s; - entity_t *e; - tree_t *tree; - face_t *faces; - qboolean ignoreLeaks, leaked; - xmlNodePtr polyline, leaknode; - char level[ 2 ], shader[ 1024 ]; - const char *value; - - /* sets integer blockSize from worldspawn "_blocksize" key if it exists */ - value = ValueForKey( &entities[ 0 ], "_blocksize" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ 0 ], "blocksize" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ 0 ], "chopsize" ); /* sof2 */ - if( value[ 0 ] != '\0' ) - { - /* scan 3 numbers */ - s = sscanf( value, "%d %d %d", &blockSize[ 0 ], &blockSize[ 1 ], &blockSize[ 2 ] ); - - /* handle legacy case */ - if( s == 1 ) - { - blockSize[ 1 ] = blockSize[ 0 ]; - blockSize[ 2 ] = blockSize[ 0 ]; - } - } - Sys_Printf( "block size = { %d %d %d }\n", blockSize[ 0 ], blockSize[ 1 ], blockSize[ 2 ] ); - - /* sof2: ignore leaks? */ - value = ValueForKey( &entities[ 0 ], "_ignoreleaks" ); /* ydnar */ - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ 0 ], "ignoreleaks" ); - if( value[ 0 ] == '1' ) - ignoreLeaks = qtrue; - else - ignoreLeaks = qfalse; - - /* begin worldspawn model */ - BeginModel(); - e = &entities[ 0 ]; - e->firstDrawSurf = 0; - - /* ydnar: gs mods */ - ClearMetaTriangles(); - - /* check for patches with adjacent edges that need to lod together */ - PatchMapDrawSurfs( e ); - - /* build an initial bsp tree using all of the sides of all of the structural brushes */ - faces = MakeStructuralBSPFaceList( entities[ 0 ].brushes ); - tree = FaceBSP( faces ); - MakeTreePortals( tree ); - FilterStructuralBrushesIntoTree( e, tree ); - - /* see if the bsp is completely enclosed */ - if( FloodEntities( tree ) || ignoreLeaks ) - { - /* rebuild a better bsp tree using only the sides that are visible from the inside */ - FillOutside( tree->headnode ); - - /* chop the sides to the convex hull of their visible fragments, giving us the smallest polygons */ - ClipSidesIntoTree( e, tree ); - - /* build a visible face tree */ - faces = MakeVisibleBSPFaceList( entities[ 0 ].brushes ); - FreeTree( tree ); - tree = FaceBSP( faces ); - MakeTreePortals( tree ); - FilterStructuralBrushesIntoTree( e, tree ); - leaked = qfalse; - - /* ydnar: flood again for skybox */ - if( skyboxPresent ) - FloodEntities( tree ); - } - else - { - Sys_FPrintf( SYS_NOXML, "**********************\n" ); - Sys_FPrintf( SYS_NOXML, "******* leaked *******\n" ); - Sys_FPrintf( SYS_NOXML, "**********************\n" ); - polyline = LeakFile( tree ); - leaknode = xmlNewNode( NULL, (xmlChar*)"message" ); - xmlNodeSetContent( leaknode, (xmlChar*)"MAP LEAKED\n" ); - xmlAddChild( leaknode, polyline ); - level[0] = (int) '0' + SYS_ERR; - level[1] = 0; - xmlSetProp( leaknode, (xmlChar*)"level", (xmlChar*) &level ); - xml_SendNode( leaknode ); - if( leaktest ) - { - Sys_Printf ("--- MAP LEAKED, ABORTING LEAKTEST ---\n"); - exit( 0 ); - } - leaked = qtrue; - - /* chop the sides to the convex hull of their visible fragments, giving us the smallest polygons */ - ClipSidesIntoTree( e, tree ); - } - - /* save out information for visibility processing */ - NumberClusters( tree ); - if( !leaked ) - WritePortalFile( tree ); - - /* flood from entities */ - FloodAreas( tree ); - - /* create drawsurfs for triangle models */ - AddTriangleModels( e ); - - /* create drawsurfs for surface models */ - AddEntitySurfaceModels( e ); - - /* generate bsp brushes from map brushes */ - EmitBrushes( e->brushes, &e->firstBrush, &e->numBrushes ); - - /* add references to the detail brushes */ - FilterDetailBrushesIntoTree( e, tree ); - - /* drawsurfs that cross fog boundaries will need to be split along the fog boundary */ - if( !nofog ) - FogDrawSurfaces( e ); - - /* subdivide each drawsurf as required by shader tesselation */ - if( !nosubdivide ) - SubdivideFaceSurfaces( e, tree ); - - /* add in any vertexes required to fix t-junctions */ - if( !notjunc ) - FixTJunctions( e ); - - /* ydnar: classify the surfaces */ - ClassifyEntitySurfaces( e ); - - /* ydnar: project decals */ - MakeEntityDecals( e ); - - /* ydnar: meta surfaces */ - MakeEntityMetaTriangles( e ); - SmoothMetaTriangles(); - FixMetaTJunctions(); - MergeMetaTriangles(); - - /* ydnar: debug portals */ - if( debugPortals ) - MakeDebugPortalSurfs( tree ); - - /* ydnar: fog hull */ - value = ValueForKey( &entities[ 0 ], "_foghull" ); - if( value[ 0 ] != '\0' ) - { - sprintf( shader, "textures/%s", value ); - MakeFogHullSurfs( e, tree, shader ); - } - - /* ydnar: bug 645: do flares for lights */ - for( i = 0; i < numEntities && emitFlares; i++ ) - { - entity_t *light, *target; - const char *value, *flareShader; - vec3_t origin, targetOrigin, normal, color; - int lightStyle; - - - /* get light */ - light = &entities[ i ]; - value = ValueForKey( light, "classname" ); - if( !strcmp( value, "light" ) ) - { - /* get flare shader */ - flareShader = ValueForKey( light, "_flareshader" ); - value = ValueForKey( light, "_flare" ); - if( flareShader[ 0 ] != '\0' || value[ 0 ] != '\0' ) - { - /* get specifics */ - GetVectorForKey( light, "origin", origin ); - GetVectorForKey( light, "_color", color ); - lightStyle = IntForKey( light, "_style" ); - if( lightStyle == 0 ) - lightStyle = IntForKey( light, "style" ); - - /* handle directional spotlights */ - value = ValueForKey( light, "target" ); - if( value[ 0 ] != '\0' ) - { - /* get target light */ - target = FindTargetEntity( value ); - if( target != NULL ) - { - GetVectorForKey( target, "origin", targetOrigin ); - VectorSubtract( targetOrigin, origin, normal ); - VectorNormalize( normal, normal ); - } - } - else - //% VectorClear( normal ); - VectorSet( normal, 0, 0, -1 ); - - /* create the flare surface (note shader defaults automatically) */ - DrawSurfaceForFlare( mapEntityNum, origin, normal, color, flareShader, lightStyle ); - } - } - } - - /* add references to the final drawsurfs in the apropriate clusters */ - FilterDrawsurfsIntoTree( e, tree ); - - /* match drawsurfaces back to original brushsides (sof2) */ - FixBrushSides( e ); - - /* finish */ - EndModel( e, tree->headnode ); - FreeTree( tree ); -} - - - -/* -ProcessSubModel() -creates bsp + surfaces for other brush models -*/ - -void ProcessSubModel( void ) -{ - entity_t *e; - tree_t *tree; - brush_t *b, *bc; - node_t *node; - - - /* start a brush model */ - BeginModel(); - e = &entities[ mapEntityNum ]; - e->firstDrawSurf = numMapDrawSurfs; - - /* ydnar: gs mods */ - ClearMetaTriangles(); - - /* check for patches with adjacent edges that need to lod together */ - PatchMapDrawSurfs( e ); - - /* allocate a tree */ - node = AllocNode(); - node->planenum = PLANENUM_LEAF; - tree = AllocTree(); - tree->headnode = node; - - /* add the sides to the tree */ - ClipSidesIntoTree( e, tree ); - - /* ydnar: create drawsurfs for triangle models */ - AddTriangleModels( e ); - - /* create drawsurfs for surface models */ - AddEntitySurfaceModels( e ); - - /* generate bsp brushes from map brushes */ - EmitBrushes( e->brushes, &e->firstBrush, &e->numBrushes ); - - /* just put all the brushes in headnode */ - for( b = e->brushes; b; b = b->next ) - { - bc = CopyBrush( b ); - bc->next = node->brushlist; - node->brushlist = bc; - } - - /* subdivide each drawsurf as required by shader tesselation */ - if( !nosubdivide ) - SubdivideFaceSurfaces( e, tree ); - - /* add in any vertexes required to fix t-junctions */ - if( !notjunc ) - FixTJunctions( e ); - - /* ydnar: classify the surfaces and project lightmaps */ - ClassifyEntitySurfaces( e ); - - /* ydnar: project decals */ - MakeEntityDecals( e ); - - /* ydnar: meta surfaces */ - MakeEntityMetaTriangles( e ); - SmoothMetaTriangles(); - FixMetaTJunctions(); - MergeMetaTriangles(); - - /* add references to the final drawsurfs in the apropriate clusters */ - FilterDrawsurfsIntoTree( e, tree ); - - /* match drawsurfaces back to original brushsides (sof2) */ - FixBrushSides( e ); - - /* finish */ - EndModel( e, node ); - FreeTree( tree ); -} - - - -/* -ProcessModels() -process world + other models into the bsp -*/ - -void ProcessModels( void ) -{ - qboolean oldVerbose; - entity_t *entity; - - - /* preserve -v setting */ - oldVerbose = verbose; - - /* start a new bsp */ - BeginBSPFile(); - - /* create map fogs */ - CreateMapFogs(); - - /* walk entity list */ - for( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ ) - { - /* get entity */ - entity = &entities[ mapEntityNum ]; - if( entity->brushes == NULL && entity->patches == NULL ) - continue; - - /* process the model */ - Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels ); - if( mapEntityNum == 0 ) - ProcessWorldModel(); - else - ProcessSubModel(); - - /* potentially turn off the deluge of text */ - verbose = verboseEntities; - } - - /* restore -v setting */ - verbose = oldVerbose; - - /* write fogs */ - EmitFogs(); - - /* vortex: emit meta stats */ - EmitMetaStats(); -} - - - -/* -OnlyEnts() -this is probably broken unless teamed with a radiant version that preserves entity order -*/ - -void OnlyEnts( void ) -{ - char out[ 1024 ]; - - char save_cmdline[1024], save_version[1024]; - const char *p; - - /* note it */ - Sys_Printf( "--- OnlyEnts ---\n" ); - - sprintf( out, "%s.bsp", source ); - LoadBSPFile( out ); - - ParseEntities(); - p = ValueForKey(&entities[0], "_q3map2_cmdline"); - strncpy(save_cmdline, p, sizeof(save_cmdline)); - save_cmdline[sizeof(save_cmdline)-1] = 0; - p = ValueForKey(&entities[0], "_q3map2_version"); - strncpy(save_version, p, sizeof(save_version)); - save_version[sizeof(save_version)-1] = 0; - - numEntities = 0; - - LoadShaderInfo(); - LoadMapFile( name, qfalse, qfalse ); - SetModelNumbers(); - SetLightStyles(); - - if(*save_cmdline) - SetKeyValue(&entities[0], "_q3map2_cmdline", save_cmdline); - if(*save_version) - SetKeyValue(&entities[0], "_q3map2_version", save_version); - - numBSPEntities = numEntities; - UnparseEntities(); - - WriteBSPFile( out ); -} - - - -/* -BSPMain() - ydnar -handles creation of a bsp from a map file -*/ - -int BSPMain( int argc, char **argv ) -{ - int i; - char path[ 1024 ], tempSource[ 1024 ]; - qboolean onlyents = qfalse; - - - /* note it */ - Sys_Printf( "--- BSP ---\n" ); - - SetDrawSurfacesBuffer(); - mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); - memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); - numMapDrawSurfs = 0; - - tempSource[ 0 ] = '\0'; - globalCelShader[0] = 0; - - /* set standard game flags */ - maxSurfaceVerts = game->maxSurfaceVerts; - maxSurfaceIndexes = game->maxSurfaceIndexes; - emitFlares = game->emitFlares; - - /* process arguments */ - for( i = 1; i < (argc - 1); i++ ) - { - if( !strcmp( argv[ i ], "-onlyents" ) ) - { - Sys_Printf( "Running entity-only compile\n" ); - onlyents = qtrue; - } - else if( !strcmp( argv[ i ], "-tempname" ) ) - strcpy( tempSource, argv[ ++i ] ); - else if( !strcmp( argv[ i ], "-tmpout" ) ) - strcpy( outbase, "/tmp" ); - else if( !strcmp( argv[ i ], "-nowater" ) ) - { - Sys_Printf( "Disabling water\n" ); - nowater = qtrue; - } - else if( !strcmp( argv[ i ], "-nodetail" ) ) - { - Sys_Printf( "Ignoring detail brushes\n") ; - nodetail = qtrue; - } - else if( !strcmp( argv[ i ], "-fulldetail" ) ) - { - Sys_Printf( "Turning detail brushes into structural brushes\n" ); - fulldetail = qtrue; - } - else if( !strcmp( argv[ i ], "-nofog" ) ) - { - Sys_Printf( "Fog volumes disabled\n" ); - nofog = qtrue; - } - else if( !strcmp( argv[ i ], "-nosubdivide" ) ) - { - Sys_Printf( "Disabling brush face subdivision\n" ); - nosubdivide = qtrue; - } - else if( !strcmp( argv[ i ], "-leaktest" ) ) - { - Sys_Printf( "Leaktest enabled\n" ); - leaktest = qtrue; - } - else if( !strcmp( argv[ i ], "-verboseentities" ) ) - { - Sys_Printf( "Verbose entities enabled\n" ); - verboseEntities = qtrue; - } - else if( !strcmp( argv[ i ], "-nocurves" ) ) - { - Sys_Printf( "Ignoring curved surfaces (patches)\n" ); - noCurveBrushes = qtrue; - } - else if( !strcmp( argv[ i ], "-notjunc" ) ) - { - Sys_Printf( "T-junction fixing disabled\n" ); - notjunc = qtrue; - } - else if( !strcmp( argv[ i ], "-fakemap" ) ) - { - Sys_Printf( "Generating fakemap.map\n" ); - fakemap = qtrue; - } - else if( !strcmp( argv[ i ], "-samplesize" ) ) - { - sampleSize = atoi( argv[ i + 1 ] ); - if( sampleSize < 1 ) - sampleSize = 1; - i++; - Sys_Printf( "Lightmap sample size set to %dx%d units\n", sampleSize, sampleSize ); - } - else if( !strcmp( argv[ i ], "-minsamplesize" ) ) - { - minSampleSize = atoi( argv[ i + 1 ] ); - if( minSampleSize < 1 ) - minSampleSize = 1; - i++; - Sys_Printf( "Minimum lightmap sample size set to %dx%d units\n", minSampleSize, minSampleSize ); - } - else if( !strcmp( argv[ i ], "-custinfoparms") ) - { - Sys_Printf( "Custom info parms enabled\n" ); - useCustomInfoParms = qtrue; - } - - /* sof2 args */ - else if( !strcmp( argv[ i ], "-rename" ) ) - { - Sys_Printf( "Appending _bsp suffix to misc_model shaders (SOF2)\n" ); - renameModelShaders = qtrue; - } - - /* ydnar args */ - else if( !strcmp( argv[ i ], "-ne" ) ) - { - normalEpsilon = atof( argv[ i + 1 ] ); - i++; - Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon ); - } - else if( !strcmp( argv[ i ], "-de" ) ) - { - distanceEpsilon = atof( argv[ i + 1 ] ); - i++; - Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon ); - } - else if( !strcmp( argv[ i ], "-mv" ) ) - { - maxLMSurfaceVerts = atoi( argv[ i + 1 ] ); - if( maxLMSurfaceVerts < 3 ) - maxLMSurfaceVerts = 3; - if( maxLMSurfaceVerts > maxSurfaceVerts ) - maxSurfaceVerts = maxLMSurfaceVerts; - i++; - Sys_Printf( "Maximum lightmapped surface vertex count set to %d\n", maxLMSurfaceVerts ); - } - else if( !strcmp( argv[ i ], "-mi" ) ) - { - maxSurfaceIndexes = atoi( argv[ i + 1 ] ); - if( maxSurfaceIndexes < 3 ) - maxSurfaceIndexes = 3; - i++; - Sys_Printf( "Maximum per-surface index count set to %d\n", maxSurfaceIndexes ); - } - else if( !strcmp( argv[ i ], "-np" ) ) - { - npDegrees = atof( argv[ i + 1 ] ); - if( npDegrees < 0.0f ) - shadeAngleDegrees = 0.0f; - else if( npDegrees > 0.0f ) - Sys_Printf( "Forcing nonplanar surfaces with a breaking angle of %f degrees\n", npDegrees ); - i++; - } - else if( !strcmp( argv[ i ], "-snap" ) ) - { - bevelSnap = atoi( argv[ i + 1 ]); - if( bevelSnap < 0 ) - bevelSnap = 0; - i++; - if( bevelSnap > 0 ) - Sys_Printf( "Snapping brush bevel planes to %d units\n", bevelSnap ); - } - else if( !strcmp( argv[ i ], "-texrange" ) ) - { - texRange = atoi( argv[ i + 1 ]); - if( texRange < 0 ) - texRange = 0; - i++; - Sys_Printf( "Limiting per-surface texture range to %d texels\n", texRange ); - } - else if( !strcmp( argv[ i ], "-nohint" ) ) - { - Sys_Printf( "Hint brushes disabled\n" ); - noHint = qtrue; - } - else if( !strcmp( argv[ i ], "-flat" ) ) - { - Sys_Printf( "Flatshading enabled\n" ); - flat = qtrue; - } - else if( !strcmp( argv[ i ], "-celshader" ) ) - { - ++i; - if(argv[i][0]) - sprintf( globalCelShader, "textures/%s", argv[ i ] ); - else - *globalCelShader = 0; - Sys_Printf( "Global cel shader set to \"%s\"\n", globalCelShader ); - } - else if( !strcmp( argv[ i ], "-meta" ) ) - { - Sys_Printf( "Creating meta surfaces from brush faces\n" ); - meta = qtrue; - } - else if( !strcmp( argv[ i ], "-patchmeta" ) ) - { - Sys_Printf( "Creating meta surfaces from patches\n" ); - patchMeta = qtrue; - } - else if( !strcmp( argv[ i ], "-flares" ) ) - { - Sys_Printf( "Flare surfaces enabled\n" ); - emitFlares = qtrue; - } - else if( !strcmp( argv[ i ], "-noflares" ) ) - { - Sys_Printf( "Flare surfaces disabled\n" ); - emitFlares = qfalse; - } - else if( !strcmp( argv[ i ], "-skyfix" ) ) - { - Sys_Printf( "GL_CLAMP sky fix/hack/workaround enabled\n" ); - skyFixHack = qtrue; - } - else if( !strcmp( argv[ i ], "-debugsurfaces" ) ) - { - Sys_Printf( "emitting debug surfaces\n" ); - debugSurfaces = qtrue; - } - else if( !strcmp( argv[ i ], "-debuginset" ) ) - { - Sys_Printf( "Debug surface triangle insetting enabled\n" ); - debugInset = qtrue; - } - else if( !strcmp( argv[ i ], "-debugportals" ) ) - { - Sys_Printf( "Debug portal surfaces enabled\n" ); - debugPortals = qtrue; - } - else if( !strcmp( argv[ i ], "-altsplit" ) ) - { - Sys_Printf( "Alternate BSP splitting (by 27) enabled\n" ); - bspAlternateSplitWeights = qtrue; - } - else if( !strcmp( argv[ i ], "-deep" ) ) - { - Sys_Printf( "Deep BSP tree generation enabled\n" ); - deepBSP = qtrue; - } - else if( !strcmp( argv[ i ], "-maxarea" ) ) - { - Sys_Printf( "Max Area face surface generation enabled\n" ); - maxAreaFaceSurface = qtrue; - } - else if( !strcmp( argv[ i ], "-bsp" ) ) - Sys_Printf( "-bsp argument unnecessary\n" ); - else - { - Sys_Printf( "WARNING: Unknown option \"%s\"\n", argv[ i ] ); - } - } - - /* fixme: print more useful usage here */ - if( i != (argc - 1) ) - Error( "usage: q3map [options] mapfile" ); - - /* copy source name */ - strcpy( source, ExpandArg( argv[ i ] ) ); - StripExtension( source ); - - /* ydnar: set default sample size */ - SetDefaultSampleSize( sampleSize ); - - /* delete portal, line and surface files */ - sprintf( path, "%s.prt", source ); - remove( path ); - sprintf( path, "%s.lin", source ); - remove( path ); - //% sprintf( path, "%s.srf", source ); /* ydnar */ - //% remove( path ); - - /* expand mapname */ - strcpy( name, ExpandArg( argv[ i ] ) ); - if( strcmp( name + strlen( name ) - 4, ".reg" ) ) - { - /* if we are doing a full map, delete the last saved region map */ - sprintf( path, "%s.reg", source ); - remove( path ); - DefaultExtension( name, ".map" ); /* might be .reg */ - } - - /* if onlyents, just grab the entites and resave */ - if( onlyents ) - { - OnlyEnts(); - return 0; - } - - /* load shaders */ - LoadShaderInfo(); - - /* load original file from temp spot in case it was renamed by the editor on the way in */ - if( strlen( tempSource ) > 0 ) - LoadMapFile( tempSource, qfalse, qfalse ); - else - LoadMapFile( name, qfalse, qfalse ); - - /* div0: inject command line parameters */ - InjectCommandLine(argv, 1, argc - 1); - - /* ydnar: decal setup */ - ProcessDecals(); - - /* ydnar: cloned brush model entities */ - SetCloneModelNumbers(); - - /* process world and submodels */ - ProcessModels(); - - /* set light styles from targetted light entities */ - SetLightStyles(); - - /* process in game advertisements */ - ProcessAdvertisements(); - - /* finish and write bsp */ - EndBSPFile(qtrue); - - /* remove temp map source file if appropriate */ - if( strlen( tempSource ) > 0) - remove( tempSource ); - - /* return to sender */ - return 0; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_abstract.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_abstract.c deleted file mode 100644 index ef78160f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_abstract.c +++ /dev/null @@ -1,934 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define BSPFILE_ABSTRACT_C - - - -/* dependencies */ -#include "q3map2.h" - - - - -/* ------------------------------------------------------------------------------- - -this file was copied out of the common directory in order to not break -compatibility with the q3map 1.x tree. it was moved out in order to support -the raven bsp format (RBSP) used in soldier of fortune 2 and jedi knight 2. - -since each game has its own set of particular features, the data structures -below no longer directly correspond to the binary format of a particular game. - -the translation will be done at bsp load/save time to keep any sort of -special-case code messiness out of the rest of the program. - -------------------------------------------------------------------------------- */ - - - -/* FIXME: remove the functions below that handle memory management of bsp file chunks */ - -int numBSPDrawVertsBuffer = 0; -void IncDrawVerts() -{ - numBSPDrawVerts++; - - if(bspDrawVerts == 0) - { - numBSPDrawVertsBuffer = 1024; - - bspDrawVerts = safe_malloc_info(sizeof(bspDrawVert_t) * numBSPDrawVertsBuffer, "IncDrawVerts"); - - } - else if(numBSPDrawVerts > numBSPDrawVertsBuffer) - { - numBSPDrawVertsBuffer *= 3; // multiply by 1.5 - numBSPDrawVertsBuffer /= 2; - - bspDrawVerts = realloc(bspDrawVerts, sizeof(bspDrawVert_t) * numBSPDrawVertsBuffer); - - if(!bspDrawVerts) - Error( "realloc() failed (IncDrawVerts)"); - } - - memset(bspDrawVerts + (numBSPDrawVerts - 1), 0, sizeof(bspDrawVert_t)); -} - -void SetDrawVerts(int n) -{ - if(bspDrawVerts != 0) - free(bspDrawVerts); - - numBSPDrawVerts = n; - numBSPDrawVertsBuffer = numBSPDrawVerts; - - bspDrawVerts = safe_malloc_info(sizeof(bspDrawVert_t) * numBSPDrawVertsBuffer, "IncDrawVerts"); - - memset(bspDrawVerts, 0, n * sizeof(bspDrawVert_t)); -} - -int numBSPDrawSurfacesBuffer = 0; -void SetDrawSurfacesBuffer() -{ - if(bspDrawSurfaces != 0) - free(bspDrawSurfaces); - - numBSPDrawSurfacesBuffer = MAX_MAP_DRAW_SURFS; - - bspDrawSurfaces = safe_malloc_info(sizeof(bspDrawSurface_t) * numBSPDrawSurfacesBuffer, "IncDrawSurfaces"); - - memset(bspDrawSurfaces, 0, MAX_MAP_DRAW_SURFS * sizeof(bspDrawVert_t)); -} - -void SetDrawSurfaces(int n) -{ - if(bspDrawSurfaces != 0) - free(bspDrawSurfaces); - - numBSPDrawSurfaces = n; - numBSPDrawSurfacesBuffer = numBSPDrawSurfaces; - - bspDrawSurfaces = safe_malloc_info(sizeof(bspDrawSurface_t) * numBSPDrawSurfacesBuffer, "IncDrawSurfaces"); - - memset(bspDrawSurfaces, 0, n * sizeof(bspDrawVert_t)); -} - -void BSPFilesCleanup() -{ - if(bspDrawVerts != 0) - free(bspDrawVerts); - if(bspDrawSurfaces != 0) - free(bspDrawSurfaces); - if(bspLightBytes != 0) - free(bspLightBytes); - if(bspGridPoints != 0) - free(bspGridPoints); -} - - - - - - -/* -SwapBlock() -if all values are 32 bits, this can be used to swap everything -*/ - -void SwapBlock( int *block, int size ) -{ - int i; - - - /* dummy check */ - if( block == NULL ) - return; - - /* swap */ - size >>= 2; - for( i = 0; i < size; i++ ) - block[ i ] = LittleLong( block[ i ] ); -} - - - -/* -SwapBSPFile() -byte swaps all data in the abstract bsp -*/ - -void SwapBSPFile( void ) -{ - int i, j; - - - /* models */ - SwapBlock( (int*) bspModels, numBSPModels * sizeof( bspModels[ 0 ] ) ); - - /* shaders (don't swap the name) */ - for( i = 0; i < numBSPShaders ; i++ ) - { - bspShaders[ i ].contentFlags = LittleLong( bspShaders[ i ].contentFlags ); - bspShaders[ i ].surfaceFlags = LittleLong( bspShaders[ i ].surfaceFlags ); - } - - /* planes */ - SwapBlock( (int*) bspPlanes, numBSPPlanes * sizeof( bspPlanes[ 0 ] ) ); - - /* nodes */ - SwapBlock( (int*) bspNodes, numBSPNodes * sizeof( bspNodes[ 0 ] ) ); - - /* leafs */ - SwapBlock( (int*) bspLeafs, numBSPLeafs * sizeof( bspLeafs[ 0 ] ) ); - - /* leaffaces */ - SwapBlock( (int*) bspLeafSurfaces, numBSPLeafSurfaces * sizeof( bspLeafSurfaces[ 0 ] ) ); - - /* leafbrushes */ - SwapBlock( (int*) bspLeafBrushes, numBSPLeafBrushes * sizeof( bspLeafBrushes[ 0 ] ) ); - - // brushes - SwapBlock( (int*) bspBrushes, numBSPBrushes * sizeof( bspBrushes[ 0 ] ) ); - - // brushsides - SwapBlock( (int*) bspBrushSides, numBSPBrushSides * sizeof( bspBrushSides[ 0 ] ) ); - - // vis - ((int*) &bspVisBytes)[ 0 ] = LittleLong( ((int*) &bspVisBytes)[ 0 ] ); - ((int*) &bspVisBytes)[ 1 ] = LittleLong( ((int*) &bspVisBytes)[ 1 ] ); - - /* drawverts (don't swap colors) */ - for( i = 0; i < numBSPDrawVerts; i++ ) - { - bspDrawVerts[ i ].xyz[ 0 ] = LittleFloat( bspDrawVerts[ i ].xyz[ 0 ] ); - bspDrawVerts[ i ].xyz[ 1 ] = LittleFloat( bspDrawVerts[ i ].xyz[ 1 ] ); - bspDrawVerts[ i ].xyz[ 2 ] = LittleFloat( bspDrawVerts[ i ].xyz[ 2 ] ); - bspDrawVerts[ i ].normal[ 0 ] = LittleFloat( bspDrawVerts[ i ].normal[ 0 ] ); - bspDrawVerts[ i ].normal[ 1 ] = LittleFloat( bspDrawVerts[ i ].normal[ 1 ] ); - bspDrawVerts[ i ].normal[ 2 ] = LittleFloat( bspDrawVerts[ i ].normal[ 2 ] ); - bspDrawVerts[ i ].st[ 0 ] = LittleFloat( bspDrawVerts[ i ].st[ 0 ] ); - bspDrawVerts[ i ].st[ 1 ] = LittleFloat( bspDrawVerts[ i ].st[ 1 ] ); - for( j = 0; j < MAX_LIGHTMAPS; j++ ) - { - bspDrawVerts[ i ].lightmap[ j ][ 0 ] = LittleFloat( bspDrawVerts[ i ].lightmap[ j ][ 0 ] ); - bspDrawVerts[ i ].lightmap[ j ][ 1 ] = LittleFloat( bspDrawVerts[ i ].lightmap[ j ][ 1 ] ); - } - } - - /* drawindexes */ - SwapBlock( (int*) bspDrawIndexes, numBSPDrawIndexes * sizeof( bspDrawIndexes[0] ) ); - - /* drawsurfs */ - /* note: rbsp files (and hence q3map2 abstract bsp) have byte lightstyles index arrays, this follows sof2map convention */ - SwapBlock( (int*) bspDrawSurfaces, numBSPDrawSurfaces * sizeof( bspDrawSurfaces[ 0 ] ) ); - - /* fogs */ - for( i = 0; i < numBSPFogs; i++ ) - { - bspFogs[ i ].brushNum = LittleLong( bspFogs[ i ].brushNum ); - bspFogs[ i ].visibleSide = LittleLong( bspFogs[ i ].visibleSide ); - } - - /* advertisements */ - for( i = 0; i < numBSPAds; i++ ) - { - bspAds[ i ].cellId = LittleLong( bspAds[ i ].cellId ); - bspAds[ i ].normal[ 0 ] = LittleFloat( bspAds[ i ].normal[ 0 ] ); - bspAds[ i ].normal[ 1 ] = LittleFloat( bspAds[ i ].normal[ 1 ] ); - bspAds[ i ].normal[ 2 ] = LittleFloat( bspAds[ i ].normal[ 2 ] ); - - for( j = 0; j < 4; j++ ) - { - bspAds[ i ].rect[j][ 0 ] = LittleFloat( bspAds[ i ].rect[j][ 0 ] ); - bspAds[ i ].rect[j][ 1 ] = LittleFloat( bspAds[ i ].rect[j][ 1 ] ); - bspAds[ i ].rect[j][ 2 ] = LittleFloat( bspAds[ i ].rect[j][ 2 ] ); - } - - //bspAds[ i ].model[ MAX_QPATH ]; - } -} - - - -/* -GetLumpElements() -gets the number of elements in a bsp lump -*/ - -int GetLumpElements( bspHeader_t *header, int lump, int size ) -{ - /* check for odd size */ - if( header->lumps[ lump ].length % size ) - { - if( force ) - { - Sys_Printf( "WARNING: GetLumpElements: odd lump size (%d) in lump %d\n", header->lumps[ lump ].length, lump ); - return 0; - } - else - Error( "GetLumpElements: odd lump size (%d) in lump %d", header->lumps[ lump ].length, lump ); - } - - /* return element count */ - return header->lumps[ lump ].length / size; -} - - - -/* -GetLump() -returns a pointer to the specified lump -*/ - -void *GetLump( bspHeader_t *header, int lump ) -{ - return (void*)( (byte*) header + header->lumps[ lump ].offset); -} - - - -/* -CopyLump() -copies a bsp file lump into a destination buffer -*/ - -int CopyLump( bspHeader_t *header, int lump, void *dest, int size ) -{ - int length, offset; - - - /* get lump length and offset */ - length = header->lumps[ lump ].length; - offset = header->lumps[ lump ].offset; - - /* handle erroneous cases */ - if( length == 0 ) - return 0; - if( length % size ) - { - if( force ) - { - Sys_Printf( "WARNING: CopyLump: odd lump size (%d) in lump %d\n", length, lump ); - return 0; - } - else - Error( "CopyLump: odd lump size (%d) in lump %d", length, lump ); - } - - /* copy block of memory and return */ - memcpy( dest, (byte*) header + offset, length ); - return length / size; -} - -int CopyLump_Allocate( bspHeader_t *header, int lump, void **dest, int size, int *allocationVariable ) -{ - /* get lump length and offset */ - *allocationVariable = header->lumps[ lump ].length / size; - *dest = realloc(*dest, size * *allocationVariable); - return CopyLump(header, lump, *dest, size); -} - - -/* -AddLump() -adds a lump to an outgoing bsp file -*/ - -void AddLump( FILE *file, bspHeader_t *header, int lumpNum, const void *data, int length ) -{ - bspLump_t *lump; - - - /* add lump to bsp file header */ - lump = &header->lumps[ lumpNum ]; - lump->offset = LittleLong( ftell( file ) ); - lump->length = LittleLong( length ); - - /* write lump to file */ - SafeWrite( file, data, (length + 3) & ~3 ); -} - - - -/* -LoadBSPFile() -loads a bsp file into memory -*/ - -void LoadBSPFile( const char *filename ) -{ - /* dummy check */ - if( game == NULL || game->load == NULL ) - Error( "LoadBSPFile: unsupported BSP file format" ); - - /* load it, then byte swap the in-memory version */ - game->load( filename ); - SwapBSPFile(); -} - - - -/* -WriteBSPFile() -writes a bsp file -*/ - -void WriteBSPFile( const char *filename ) -{ - char tempname[ 1024 ]; - time_t tm; - - - /* dummy check */ - if( game == NULL || game->write == NULL ) - Error( "WriteBSPFile: unsupported BSP file format" ); - - /* make fake temp name so existing bsp file isn't damaged in case write process fails */ - time( &tm ); - sprintf( tempname, "%s.%08X", filename, (int) tm ); - - /* byteswap, write the bsp, then swap back so it can be manipulated further */ - SwapBSPFile(); - game->write( tempname ); - SwapBSPFile(); - - /* replace existing bsp file */ - remove( filename ); - rename( tempname, filename ); -} - - - -/* -PrintBSPFileSizes() -dumps info about current file -*/ - -void PrintBSPFileSizes( void ) -{ - /* parse entities first */ - if( numEntities <= 0 ) - ParseEntities(); - - /* note that this is abstracted */ - Sys_Printf( "Abstracted BSP file components (*actual sizes may differ)\n" ); - - /* print various and sundry bits */ - Sys_Printf( "%9d models %9d\n", - numBSPModels, (int) (numBSPModels * sizeof( bspModel_t )) ); - Sys_Printf( "%9d shaders %9d\n", - numBSPShaders, (int) (numBSPShaders * sizeof( bspShader_t )) ); - Sys_Printf( "%9d brushes %9d\n", - numBSPBrushes, (int) (numBSPBrushes * sizeof( bspBrush_t )) ); - Sys_Printf( "%9d brushsides %9d *\n", - numBSPBrushSides, (int) (numBSPBrushSides * sizeof( bspBrushSide_t )) ); - Sys_Printf( "%9d fogs %9d\n", - numBSPFogs, (int) (numBSPFogs * sizeof( bspFog_t ) ) ); - Sys_Printf( "%9d planes %9d\n", - numBSPPlanes, (int) (numBSPPlanes * sizeof( bspPlane_t )) ); - Sys_Printf( "%9d entdata %9d\n", - numEntities, bspEntDataSize ); - Sys_Printf( "\n"); - - Sys_Printf( "%9d nodes %9d\n", - numBSPNodes, (int) (numBSPNodes * sizeof( bspNode_t)) ); - Sys_Printf( "%9d leafs %9d\n", - numBSPLeafs, (int) (numBSPLeafs * sizeof( bspLeaf_t )) ); - Sys_Printf( "%9d leafsurfaces %9d\n", - numBSPLeafSurfaces, (int) (numBSPLeafSurfaces * sizeof( *bspLeafSurfaces )) ); - Sys_Printf( "%9d leafbrushes %9d\n", - numBSPLeafBrushes, (int) (numBSPLeafBrushes * sizeof( *bspLeafBrushes )) ); - Sys_Printf( "\n"); - - Sys_Printf( "%9d drawsurfaces %9d *\n", - numBSPDrawSurfaces, (int) (numBSPDrawSurfaces * sizeof( *bspDrawSurfaces )) ); - Sys_Printf( "%9d drawverts %9d *\n", - numBSPDrawVerts, (int) (numBSPDrawVerts * sizeof( *bspDrawVerts )) ); - Sys_Printf( "%9d drawindexes %9d\n", - numBSPDrawIndexes, (int) (numBSPDrawIndexes * sizeof( *bspDrawIndexes )) ); - Sys_Printf( "\n"); - - Sys_Printf( "%9d lightmaps %9d\n", - numBSPLightBytes / (game->lightmapSize * game->lightmapSize * 3), numBSPLightBytes ); - Sys_Printf( "%9d lightgrid %9d *\n", - numBSPGridPoints, (int) (numBSPGridPoints * sizeof( *bspGridPoints )) ); - Sys_Printf( " visibility %9d\n", - numBSPVisBytes ); -} - - - -/* ------------------------------------------------------------------------------- - -entity data handling - -------------------------------------------------------------------------------- */ - - -/* -StripTrailing() -strips low byte chars off the end of a string -*/ - -void StripTrailing( char *e ) -{ - char *s; - - - s = e + strlen( e ) - 1; - while( s >= e && *s <= 32 ) - { - *s = 0; - s--; - } -} - - - -/* -ParseEpair() -parses a single quoted "key" "value" pair into an epair struct -*/ - -epair_t *ParseEPair( void ) -{ - epair_t *e; - - - /* allocate and clear new epair */ - e = safe_malloc( sizeof( epair_t ) ); - memset( e, 0, sizeof( epair_t ) ); - - /* handle key */ - if( strlen( token ) >= (MAX_KEY - 1) ) - Error( "ParseEPair: token too long" ); - - e->key = copystring( token ); - GetToken( qfalse ); - - /* handle value */ - 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 it */ - return e; -} - - - -/* -ParseEntity() -parses an entity's epairs -*/ - -qboolean ParseEntity( void ) -{ - epair_t *e; - - - /* dummy check */ - if( !GetToken( qtrue ) ) - return qfalse; - if( strcmp( token, "{" ) ) - Error( "ParseEntity: { not found" ); - if( numEntities == MAX_MAP_ENTITIES ) - Error( "numEntities == MAX_MAP_ENTITIES" ); - - /* create new entity */ - mapEnt = &entities[ numEntities ]; - numEntities++; - - /* parse */ - while( 1 ) - { - if( !GetToken( qtrue ) ) - Error( "ParseEntity: EOF without closing brace" ); - if( !EPAIR_STRCMP( token, "}" ) ) - break; - e = ParseEPair(); - e->next = mapEnt->epairs; - mapEnt->epairs = e; - } - - /* return to sender */ - return qtrue; -} - - - -/* -ParseEntities() -parses the bsp entity data string into entities -*/ - -void ParseEntities( void ) -{ - numEntities = 0; - ParseFromMemory( bspEntData, bspEntDataSize ); - while( ParseEntity() ); - - /* ydnar: set number of bsp entities in case a map is loaded on top */ - numBSPEntities = numEntities; -} - -/* - * must be called before UnparseEntities - */ -void InjectCommandLine(char **argv, int beginArgs, int endArgs) -{ - const char *previousCommandLine; - char newCommandLine[1024]; - const char *inpos; - char *outpos = newCommandLine; - char *sentinel = newCommandLine + sizeof(newCommandLine) - 1; - int i; - - previousCommandLine = ValueForKey(&entities[0], "_q3map2_cmdline"); - if(previousCommandLine && *previousCommandLine) - { - inpos = previousCommandLine; - while(outpos != sentinel && *inpos) - *outpos++ = *inpos++; - if(outpos != sentinel) - *outpos++ = ';'; - if(outpos != sentinel) - *outpos++ = ' '; - } - - for(i = beginArgs; i < endArgs; ++i) - { - if(outpos != sentinel && i != beginArgs) - *outpos++ = ' '; - inpos = argv[i]; - while(outpos != sentinel && *inpos) - if(*inpos != '\\' && *inpos != '"' && *inpos != ';' && (unsigned char) *inpos >= ' ') - *outpos++ = *inpos++; - } - - *outpos = 0; - SetKeyValue(&entities[0], "_q3map2_cmdline", newCommandLine); - SetKeyValue(&entities[0], "_q3map2_version", Q3MAP_VERSION); -} - -/* -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 ) -{ - int i; - char *buf, *end; - epair_t *ep; - char line[ 2048 ]; - char key[ 1024 ], value[ 1024 ]; - const char *value2; - - - /* setup */ - AUTOEXPAND_BY_REALLOC(bspEntData, 0, allocatedBSPEntData, 1024); - buf = bspEntData; - end = buf; - *end = 0; - - - /* run through entity list */ - for( i = 0; i < numBSPEntities && i < numEntities; i++ ) - { - { - int sz = end - buf; - AUTOEXPAND_BY_REALLOC(bspEntData, sz + 65536, allocatedBSPEntData, 1024); - buf = bspEntData; - end = buf + sz; - } - - /* get epair */ - ep = entities[ i ].epairs; - if( ep == NULL ) - continue; /* ent got removed */ - - /* ydnar: certain entities get stripped from bsp file */ - value2 = ValueForKey( &entities[ i ], "classname" ); - if( !Q_stricmp( value2, "misc_model" ) || - !Q_stricmp( value2, "_decal" ) || - !Q_stricmp( value2, "_skybox" ) ) - continue; - - /* add beginning brace */ - strcat( end, "{\n" ); - end += 2; - - /* walk epair list */ - for( ep = entities[ i ].epairs; ep != NULL; ep = ep->next ) - { - /* copy and clean */ - strcpy( key, ep->key ); - StripTrailing( key ); - strcpy( value, ep->value ); - StripTrailing( value ); - - /* add to buffer */ - sprintf( line, "\"%s\" \"%s\"\n", key, value ); - strcat( end, line ); - end += strlen( line ); - } - - /* add trailing brace */ - strcat( end,"}\n" ); - end += 2; - - /* check for overflow */ - if( end > buf + allocatedBSPEntData ) - Error( "Entity text too long" ); - } - - /* set size */ - bspEntDataSize = end - buf + 1; -} - - - -/* -PrintEntity() -prints an entity's epairs to the console -*/ - -void PrintEntity( const entity_t *ent ) -{ - epair_t *ep; - - - Sys_Printf( "------- entity %p -------\n", ent ); - for( ep = ent->epairs; ep != NULL; ep = ep->next ) - Sys_Printf( "%s = %s\n", ep->key, ep->value ); - -} - - - -/* -SetKeyValue() -sets an epair in an entity -*/ - -void SetKeyValue( entity_t *ent, const char *key, const char *value ) -{ - epair_t *ep; - - - /* check for existing epair */ - for( ep = ent->epairs; ep != NULL; ep = ep->next ) - { - if( !EPAIR_STRCMP( ep->key, key ) ) - { - free( ep->value ); - ep->value = copystring( value ); - return; - } - } - - /* create new epair */ - ep = safe_malloc( sizeof( *ep ) ); - ep->next = ent->epairs; - ent->epairs = ep; - ep->key = copystring( key ); - ep->value = copystring( value ); -} - -/* -KeyExists() -returns true if entity has this key -*/ - -qboolean KeyExists( const entity_t *ent, const char *key ) -{ - epair_t *ep; - - /* walk epair list */ - for( ep = ent->epairs; ep != NULL; ep = ep->next ) - { - if( !EPAIR_STRCMP( ep->key, key ) ) - return qtrue; - } - - /* no match */ - return qfalse; -} - -/* -ValueForKey() -gets the value for an entity key -*/ - -const char *ValueForKey( const entity_t *ent, const char *key ) -{ - epair_t *ep; - - - /* dummy check */ - if( ent == NULL ) - return ""; - - /* walk epair list */ - for( ep = ent->epairs; ep != NULL; ep = ep->next ) - { - if( !EPAIR_STRCMP( ep->key, key ) ) - return ep->value; - } - - /* if no match, return empty string */ - return ""; -} - - - -/* -IntForKey() -gets the integer point value for an entity key -*/ - -int IntForKey( const entity_t *ent, const char *key ) -{ - const char *k; - - - k = ValueForKey( ent, key ); - return atoi( k ); -} - - - -/* -FloatForKey() -gets the floating point value for an entity key -*/ - -vec_t FloatForKey( const entity_t *ent, const char *key ) -{ - const char *k; - - - k = ValueForKey( ent, key ); - return atof( k ); -} - - - -/* -GetVectorForKey() -gets a 3-element vector value for an entity key -*/ - -void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ) -{ - const char *k; - double v1, v2, v3; - - - /* get value */ - k = ValueForKey( ent, key ); - - /* scanf into doubles, then assign, so it is vec_t size independent */ - v1 = v2 = v3 = 0.0; - sscanf( k, "%lf %lf %lf", &v1, &v2, &v3 ); - vec[ 0 ] = v1; - vec[ 1 ] = v2; - vec[ 2 ] = v3; -} - - - -/* -FindTargetEntity() -finds an entity target -*/ - -entity_t *FindTargetEntity( const char *target ) -{ - int i; - const char *n; - - - /* walk entity list */ - for( i = 0; i < numEntities; i++ ) - { - n = ValueForKey( &entities[ i ], "targetname" ); - if ( !strcmp( n, target ) ) - return &entities[ i ]; - } - - /* nada */ - return NULL; -} - - - -/* -GetEntityShadowFlags() - ydnar -gets an entity's shadow flags -note: does not set them to defaults if the keys are not found! -*/ - -void GetEntityShadowFlags( const entity_t *ent, const entity_t *ent2, int *castShadows, int *recvShadows ) -{ - const char *value; - - /* get cast shadows */ - if( castShadows != NULL ) - { - value = ValueForKey( ent, "_castShadows" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( ent, "_cs" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( ent2, "_castShadows" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( ent2, "_cs" ); - if( value[ 0 ] != '\0' ) - *castShadows = atoi( value ); - } - - /* receive */ - if( recvShadows != NULL ) - { - value = ValueForKey( ent, "_receiveShadows" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( ent, "_rs" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( ent2, "_receiveShadows" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( ent2, "_rs" ); - if( value[ 0 ] != '\0' ) - *recvShadows = atoi( value ); - } - - /* vortex: game-specific default eneity keys */ - value = ValueForKey( ent, "classname" ); - if (!Q_stricmp( game->magic, "dq" ) || !Q_stricmp( game->magic, "prophecy" ) ) - { - /* vortex: deluxe quake default shadow flags */ - if (!Q_stricmp( value, "func_wall" ) ) - { - if( recvShadows != NULL ) - *recvShadows = 1; - if( castShadows != NULL ) - *castShadows = 1; - } - } -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_ibsp.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_ibsp.c deleted file mode 100644 index 77ffd704..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_ibsp.c +++ /dev/null @@ -1,593 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define BSPFILE_IBSP_C - - - -/* dependencies */ -#include "q3map2.h" - - - - -/* ------------------------------------------------------------------------------- - -this file handles translating the bsp file format used by quake 3, rtcw, and ef -into the abstracted bsp file used by q3map2. - -------------------------------------------------------------------------------- */ - -/* constants */ -#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 LUMP_ADVERTISEMENTS 17 -#define HEADER_LUMPS 18 - - -/* types */ -typedef struct -{ - char ident[ 4 ]; - int version; - - bspLump_t lumps[ HEADER_LUMPS ]; -} -ibspHeader_t; - - - -/* brush sides */ -typedef struct -{ - int planeNum; - int shaderNum; -} -ibspBrushSide_t; - - -static void CopyBrushSidesLump( ibspHeader_t *header ) -{ - int i; - ibspBrushSide_t *in; - bspBrushSide_t *out; - - - /* get count */ - numBSPBrushSides = GetLumpElements( (bspHeader_t*) header, LUMP_BRUSHSIDES, sizeof( *in ) ); - - /* copy */ - in = GetLump( (bspHeader_t*) header, LUMP_BRUSHSIDES ); - for( i = 0; i < numBSPBrushSides; i++ ) - { - AUTOEXPAND_BY_REALLOC(bspBrushSides, i, allocatedBSPBrushSides, 1024); - out = &bspBrushSides[i]; - out->planeNum = in->planeNum; - out->shaderNum = in->shaderNum; - out->surfaceNum = -1; - in++; - } -} - - -static void AddBrushSidesLump( FILE *file, ibspHeader_t *header ) -{ - int i, size; - bspBrushSide_t *in; - ibspBrushSide_t *buffer, *out; - - - /* allocate output buffer */ - size = numBSPBrushSides * sizeof( *buffer ); - buffer = safe_malloc( size ); - memset( buffer, 0, size ); - - /* convert */ - in = bspBrushSides; - out = buffer; - for( i = 0; i < numBSPBrushSides; i++ ) - { - out->planeNum = in->planeNum; - out->shaderNum = in->shaderNum; - in++; - out++; - } - - /* write lump */ - AddLump( file, (bspHeader_t*) header, LUMP_BRUSHSIDES, buffer, size ); - - /* free buffer */ - free( buffer ); -} - - - -/* drawsurfaces */ -typedef struct ibspDrawSurface_s -{ - 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 ]; - - int patchWidth; - int patchHeight; -} -ibspDrawSurface_t; - - -static void CopyDrawSurfacesLump( ibspHeader_t *header ) -{ - int i, j; - ibspDrawSurface_t *in; - bspDrawSurface_t *out; - - - /* get count */ - numBSPDrawSurfaces = GetLumpElements( (bspHeader_t*) header, LUMP_SURFACES, sizeof( *in ) ); - SetDrawSurfaces( numBSPDrawSurfaces ); - - /* copy */ - in = GetLump( (bspHeader_t*) header, LUMP_SURFACES ); - out = bspDrawSurfaces; - for( i = 0; i < numBSPDrawSurfaces; i++ ) - { - out->shaderNum = in->shaderNum; - out->fogNum = in->fogNum; - out->surfaceType = in->surfaceType; - out->firstVert = in->firstVert; - out->numVerts = in->numVerts; - out->firstIndex = in->firstIndex; - out->numIndexes = in->numIndexes; - - out->lightmapStyles[ 0 ] = LS_NORMAL; - out->vertexStyles[ 0 ] = LS_NORMAL; - out->lightmapNum[ 0 ] = in->lightmapNum; - out->lightmapX[ 0 ] = in->lightmapX; - out->lightmapY[ 0 ] = in->lightmapY; - - for( j = 1; j < MAX_LIGHTMAPS; j++ ) - { - out->lightmapStyles[ j ] = LS_NONE; - out->vertexStyles[ j ] = LS_NONE; - out->lightmapNum[ j ] = -3; - out->lightmapX[ j ] = 0; - out->lightmapY[ j ] = 0; - } - - out->lightmapWidth = in->lightmapWidth; - out->lightmapHeight = in->lightmapHeight; - - VectorCopy( in->lightmapOrigin, out->lightmapOrigin ); - VectorCopy( in->lightmapVecs[ 0 ], out->lightmapVecs[ 0 ] ); - VectorCopy( in->lightmapVecs[ 1 ], out->lightmapVecs[ 1 ] ); - VectorCopy( in->lightmapVecs[ 2 ], out->lightmapVecs[ 2 ] ); - - out->patchWidth = in->patchWidth; - out->patchHeight = in->patchHeight; - - in++; - out++; - } -} - - -static void AddDrawSurfacesLump( FILE *file, ibspHeader_t *header ) -{ - int i, size; - bspDrawSurface_t *in; - ibspDrawSurface_t *buffer, *out; - - - /* allocate output buffer */ - size = numBSPDrawSurfaces * sizeof( *buffer ); - buffer = safe_malloc( size ); - memset( buffer, 0, size ); - - /* convert */ - in = bspDrawSurfaces; - out = buffer; - for( i = 0; i < numBSPDrawSurfaces; i++ ) - { - out->shaderNum = in->shaderNum; - out->fogNum = in->fogNum; - out->surfaceType = in->surfaceType; - out->firstVert = in->firstVert; - out->numVerts = in->numVerts; - out->firstIndex = in->firstIndex; - out->numIndexes = in->numIndexes; - - out->lightmapNum = in->lightmapNum[ 0 ]; - out->lightmapX = in->lightmapX[ 0 ]; - out->lightmapY = in->lightmapY[ 0 ]; - out->lightmapWidth = in->lightmapWidth; - out->lightmapHeight = in->lightmapHeight; - - VectorCopy( in->lightmapOrigin, out->lightmapOrigin ); - VectorCopy( in->lightmapVecs[ 0 ], out->lightmapVecs[ 0 ] ); - VectorCopy( in->lightmapVecs[ 1 ], out->lightmapVecs[ 1 ] ); - VectorCopy( in->lightmapVecs[ 2 ], out->lightmapVecs[ 2 ] ); - - out->patchWidth = in->patchWidth; - out->patchHeight = in->patchHeight; - - in++; - out++; - } - - /* write lump */ - AddLump( file, (bspHeader_t*) header, LUMP_SURFACES, buffer, size ); - - /* free buffer */ - free( buffer ); -} - - - -/* drawverts */ -typedef struct -{ - vec3_t xyz; - float st[ 2 ]; - float lightmap[ 2 ]; - vec3_t normal; - byte color[ 4 ]; -} -ibspDrawVert_t; - - -static void CopyDrawVertsLump( ibspHeader_t *header ) -{ - int i; - ibspDrawVert_t *in; - bspDrawVert_t *out; - - - /* get count */ - numBSPDrawVerts = GetLumpElements( (bspHeader_t*) header, LUMP_DRAWVERTS, sizeof( *in ) ); - SetDrawVerts( numBSPDrawVerts ); - - /* copy */ - in = GetLump( (bspHeader_t*) header, LUMP_DRAWVERTS ); - out = bspDrawVerts; - for( i = 0; i < numBSPDrawVerts; i++ ) - { - VectorCopy( in->xyz, out->xyz ); - out->st[ 0 ] = in->st[ 0 ]; - out->st[ 1 ] = in->st[ 1 ]; - - out->lightmap[ 0 ][ 0 ] = in->lightmap[ 0 ]; - out->lightmap[ 0 ][ 1 ] = in->lightmap[ 1 ]; - - VectorCopy( in->normal, out->normal ); - - out->color[ 0 ][ 0 ] = in->color[ 0 ]; - out->color[ 0 ][ 1 ] = in->color[ 1 ]; - out->color[ 0 ][ 2 ] = in->color[ 2 ]; - out->color[ 0 ][ 3 ] = in->color[ 3 ]; - - in++; - out++; - } -} - - -static void AddDrawVertsLump( FILE *file, ibspHeader_t *header ) -{ - int i, size; - bspDrawVert_t *in; - ibspDrawVert_t *buffer, *out; - - - /* allocate output buffer */ - size = numBSPDrawVerts * sizeof( *buffer ); - buffer = safe_malloc( size ); - memset( buffer, 0, size ); - - /* convert */ - in = bspDrawVerts; - out = buffer; - for( i = 0; i < numBSPDrawVerts; i++ ) - { - VectorCopy( in->xyz, out->xyz ); - out->st[ 0 ] = in->st[ 0 ]; - out->st[ 1 ] = in->st[ 1 ]; - - out->lightmap[ 0 ] = in->lightmap[ 0 ][ 0 ]; - out->lightmap[ 1 ] = in->lightmap[ 0 ][ 1 ]; - - VectorCopy( in->normal, out->normal ); - - out->color[ 0 ] = in->color[ 0 ][ 0 ]; - out->color[ 1 ] = in->color[ 0 ][ 1 ]; - out->color[ 2 ] = in->color[ 0 ][ 2 ]; - out->color[ 3 ] = in->color[ 0 ][ 3 ]; - - in++; - out++; - } - - /* write lump */ - AddLump( file, (bspHeader_t*) header, LUMP_DRAWVERTS, buffer, size ); - - /* free buffer */ - free( buffer ); -} - - - -/* light grid */ -typedef struct -{ - byte ambient[ 3 ]; - byte directed[ 3 ]; - byte latLong[ 2 ]; -} -ibspGridPoint_t; - - -static void CopyLightGridLumps( ibspHeader_t *header ) -{ - int i, j; - ibspGridPoint_t *in; - bspGridPoint_t *out; - - - /* get count */ - numBSPGridPoints = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTGRID, sizeof( *in ) ); - - /* allocate buffer */ - bspGridPoints = safe_malloc( numBSPGridPoints * sizeof( *bspGridPoints ) ); - memset( bspGridPoints, 0, numBSPGridPoints * sizeof( *bspGridPoints ) ); - - /* copy */ - in = GetLump( (bspHeader_t*) header, LUMP_LIGHTGRID ); - out = bspGridPoints; - for( i = 0; i < numBSPGridPoints; i++ ) - { - for( j = 0; j < MAX_LIGHTMAPS; j++ ) - { - VectorCopy( in->ambient, out->ambient[ j ] ); - VectorCopy( in->directed, out->directed[ j ] ); - out->styles[ j ] = LS_NONE; - } - - out->styles[ 0 ] = LS_NORMAL; - - out->latLong[ 0 ] = in->latLong[ 0 ]; - out->latLong[ 1 ] = in->latLong[ 1 ]; - - in++; - out++; - } -} - - -static void AddLightGridLumps( FILE *file, ibspHeader_t *header ) -{ - int i; - bspGridPoint_t *in; - ibspGridPoint_t *buffer, *out; - - - /* dummy check */ - if( bspGridPoints == NULL ) - return; - - /* allocate temporary buffer */ - buffer = safe_malloc( numBSPGridPoints * sizeof( *out ) ); - - /* convert */ - in = bspGridPoints; - out = buffer; - for( i = 0; i < numBSPGridPoints; i++ ) - { - VectorCopy( in->ambient[ 0 ], out->ambient ); - VectorCopy( in->directed[ 0 ], out->directed ); - - out->latLong[ 0 ] = in->latLong[ 0 ]; - out->latLong[ 1 ] = in->latLong[ 1 ]; - - in++; - out++; - } - - /* write lumps */ - AddLump( file, (bspHeader_t*) header, LUMP_LIGHTGRID, buffer, (numBSPGridPoints * sizeof( *out )) ); - - /* free buffer (ydnar 2002-10-22: [bug 641] thanks Rap70r! */ - free( buffer ); -} - -/* -LoadIBSPFile() -loads a quake 3 bsp file into memory -*/ - -void LoadIBSPFile( const char *filename ) -{ - ibspHeader_t *header; - - - /* load the file header */ - LoadFile( filename, (void**) &header ); - - /* swap the header (except the first 4 bytes) */ - SwapBlock( (int*) ((byte*) header + sizeof( int )), sizeof( *header ) - sizeof( int ) ); - - /* make sure it matches the format we're trying to load */ - if( force == qfalse && *((int*) header->ident) != *((int*) game->bspIdent) ) - Error( "%s is not a %s file", filename, game->bspIdent ); - if( force == qfalse && header->version != game->bspVersion ) - Error( "%s is version %d, not %d", filename, header->version, game->bspVersion ); - - /* load/convert lumps */ - numBSPShaders = CopyLump_Allocate( (bspHeader_t*) header, LUMP_SHADERS, (void **) &bspShaders, sizeof( bspShader_t ), &allocatedBSPShaders ); - - numBSPModels = CopyLump_Allocate( (bspHeader_t*) header, LUMP_MODELS, (void **) &bspModels, sizeof( bspModel_t ), &allocatedBSPModels ); - - numBSPPlanes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_PLANES, (void **) &bspPlanes, sizeof( bspPlane_t ), &allocatedBSPPlanes ); - - numBSPLeafs = CopyLump( (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, sizeof( bspLeaf_t ) ); // TODO fix overflow - - numBSPNodes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_NODES, (void **) &bspNodes, sizeof( bspNode_t ), &allocatedBSPNodes ); - - numBSPLeafSurfaces = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFSURFACES, (void **) &bspLeafSurfaces, sizeof( bspLeafSurfaces[ 0 ] ), &allocatedBSPLeafSurfaces ); - - numBSPLeafBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFBRUSHES, (void **) &bspLeafBrushes, sizeof( bspLeafBrushes[ 0 ] ), &allocatedBSPLeafBrushes ); - - numBSPBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_BRUSHES, (void **) &bspBrushes, sizeof( bspBrush_t ), &allocatedBSPLeafBrushes ); - - CopyBrushSidesLump( header ); - - CopyDrawVertsLump( header ); - - CopyDrawSurfacesLump( header ); - - numBSPFogs = CopyLump( (bspHeader_t*) header, LUMP_FOGS, bspFogs, sizeof( bspFog_t ) ); // TODO fix overflow - - numBSPDrawIndexes = CopyLump( (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, sizeof( bspDrawIndexes[ 0 ] ) ); - - numBSPVisBytes = CopyLump( (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, 1 ); // TODO fix overflow - - numBSPLightBytes = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTMAPS, 1 ); // TODO change to CopyLump_Allocate - bspLightBytes = safe_malloc( numBSPLightBytes ); - CopyLump( (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, 1 ); - - bspEntDataSize = CopyLump_Allocate( (bspHeader_t*) header, LUMP_ENTITIES, (void **) &bspEntData, 1, &allocatedBSPEntData); - - CopyLightGridLumps( header ); - - /* advertisements */ - if(header->version == 47) // quake live's bsp version - numBSPAds = CopyLump( (bspHeader_t*) header, LUMP_ADVERTISEMENTS, bspAds, sizeof( bspAdvertisement_t ) ); - else - numBSPAds = 0; - - /* free the file buffer */ - free( header ); -} - - - -/* -WriteIBSPFile() -writes an id bsp file -*/ - -void WriteIBSPFile( const char *filename ) -{ - ibspHeader_t outheader, *header; - FILE *file; - time_t t; - char marker[ 1024 ]; - int size; - - - /* set header */ - header = &outheader; - memset( header, 0, sizeof( *header ) ); - - //% Swapfile(); - - /* set up header */ - *((int*) (bspHeader_t*) header->ident) = *((int*) game->bspIdent); - header->version = LittleLong( game->bspVersion ); - - /* write initial header */ - file = SafeOpenWrite( filename ); - SafeWrite( file, (bspHeader_t*) header, sizeof( *header ) ); /* overwritten later */ - - /* add marker lump */ - time( &t ); - sprintf( marker, "I LOVE MY Q3MAP2 %s on %s)", Q3MAP_VERSION, asctime( localtime( &t ) ) ); - AddLump( file, (bspHeader_t*) header, 0, marker, strlen( marker ) + 1 ); - - /* add lumps */ - AddLump( file, (bspHeader_t*) header, LUMP_SHADERS, bspShaders, numBSPShaders * sizeof( bspShader_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_PLANES, bspPlanes, numBSPPlanes * sizeof( bspPlane_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, numBSPLeafs * sizeof( bspLeaf_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_NODES, bspNodes, numBSPNodes * sizeof( bspNode_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_BRUSHES, bspBrushes, numBSPBrushes*sizeof( bspBrush_t ) ); - AddBrushSidesLump( file, header ); - AddLump( file, (bspHeader_t*) header, LUMP_LEAFSURFACES, bspLeafSurfaces, numBSPLeafSurfaces * sizeof( bspLeafSurfaces[ 0 ] ) ); - AddLump( file, (bspHeader_t*) header, LUMP_LEAFBRUSHES, bspLeafBrushes, numBSPLeafBrushes * sizeof( bspLeafBrushes[ 0 ] ) ); - AddLump( file, (bspHeader_t*) header, LUMP_MODELS, bspModels, numBSPModels * sizeof( bspModel_t ) ); - AddDrawVertsLump( file, header ); - AddDrawSurfacesLump( file, header ); - AddLump( file, (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, numBSPVisBytes ); - AddLump( file, (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, numBSPLightBytes ); - AddLightGridLumps( file, header ); - AddLump( file, (bspHeader_t*) header, LUMP_ENTITIES, bspEntData, bspEntDataSize ); - AddLump( file, (bspHeader_t*) header, LUMP_FOGS, bspFogs, numBSPFogs * sizeof( bspFog_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, numBSPDrawIndexes * sizeof( bspDrawIndexes[ 0 ] ) ); - - /* advertisements */ - AddLump( file, (bspHeader_t*) header, LUMP_ADVERTISEMENTS, bspAds, numBSPAds * sizeof( bspAdvertisement_t ) ); - - /* emit bsp size */ - size = ftell( file ); - Sys_Printf( "Wrote %.1f MB (%d bytes)\n", (float) size / (1024 * 1024), size ); - - /* write the completed header */ - fseek( file, 0, SEEK_SET ); - SafeWrite( file, header, sizeof( *header ) ); - - /* close the file */ - fclose( file ); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_rbsp.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_rbsp.c deleted file mode 100644 index 79f177ea..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/bspfile_rbsp.c +++ /dev/null @@ -1,340 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define BSPFILE_RBSP_C - - - -/* dependencies */ -#include "q3map2.h" - - - - -/* ------------------------------------------------------------------------------- - -this file handles translating the bsp file format used by quake 3, rtcw, and ef -into the abstracted bsp file used by q3map2. - -------------------------------------------------------------------------------- */ - -/* constants */ -#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 LUMP_LIGHTARRAY 17 -#define HEADER_LUMPS 18 - - -/* types */ -typedef struct -{ - char ident[ 4 ]; - int version; - - bspLump_t lumps[ HEADER_LUMPS ]; -} -rbspHeader_t; - - - -/* light grid */ -#define MAX_MAP_GRID 0xffff -#define MAX_MAP_GRIDARRAY 0x100000 -#define LG_EPSILON 4 - - -static void CopyLightGridLumps( rbspHeader_t *header ) -{ - int i; - unsigned short *inArray; - bspGridPoint_t *in, *out; - - - /* get count */ - numBSPGridPoints = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTARRAY, sizeof( *inArray ) ); - - /* allocate buffer */ - bspGridPoints = safe_malloc( numBSPGridPoints * sizeof( *bspGridPoints ) ); - memset( bspGridPoints, 0, numBSPGridPoints * sizeof( *bspGridPoints ) ); - - /* copy */ - inArray = GetLump( (bspHeader_t*) header, LUMP_LIGHTARRAY ); - in = GetLump( (bspHeader_t*) header, LUMP_LIGHTGRID ); - out = bspGridPoints; - for( i = 0; i < numBSPGridPoints; i++ ) - { - memcpy( out, &in[ *inArray ], sizeof( *in ) ); - inArray++; - out++; - } -} - - -static void AddLightGridLumps( FILE *file, rbspHeader_t *header ) -{ - int i, j, k, c, d; - int numGridPoints, maxGridPoints; - bspGridPoint_t *gridPoints, *in, *out; - int numGridArray; - unsigned short *gridArray; - qboolean bad; - - - /* allocate temporary buffers */ - maxGridPoints = (numBSPGridPoints < MAX_MAP_GRID) ? numBSPGridPoints : MAX_MAP_GRID; - gridPoints = safe_malloc( maxGridPoints * sizeof( *gridPoints ) ); - gridArray = safe_malloc( numBSPGridPoints * sizeof( *gridArray ) ); - - /* zero out */ - numGridPoints = 0; - numGridArray = numBSPGridPoints; - - /* for each bsp grid point, find an approximate twin */ - Sys_Printf( "Storing lightgrid: %d points\n", numBSPGridPoints ); - for( i = 0; i < numGridArray; i++ ) - { - /* get points */ - in = &bspGridPoints[ i ]; - - /* walk existing list */ - for( j = 0; j < numGridPoints; j++ ) - { - /* get point */ - out = &gridPoints[ j ]; - - /* compare styles */ - if( *((unsigned int*) in->styles) != *((unsigned int*) out->styles) ) - continue; - - /* compare direction */ - d = abs( in->latLong[ 0 ] - out->latLong[ 0 ] ); - if( d < (255 - LG_EPSILON) && d > LG_EPSILON ) - continue; - d = abs( in->latLong[ 1 ] - out->latLong[ 1 ] ); - if( d < 255 - LG_EPSILON && d > LG_EPSILON ) - continue; - - /* compare light */ - bad = qfalse; - for( k = 0; (k < MAX_LIGHTMAPS && bad == qfalse); k++ ) - { - for( c = 0; c < 3; c++ ) - { - if( abs( (int) in->ambient[ k ][ c ] - (int) out->ambient[ k ][ c ]) > LG_EPSILON || - abs( (int) in->directed[ k ][ c ] - (int) out->directed[ k ][ c ]) > LG_EPSILON ) - { - bad = qtrue; - break; - } - } - } - - /* failure */ - if( bad ) - continue; - - /* this sample is ok */ - break; - } - - /* set sample index */ - gridArray[ i ] = (unsigned short) j; - - /* if no sample found, add a new one */ - if( j >= numGridPoints && numGridPoints < maxGridPoints ) - { - out = &gridPoints[ numGridPoints++ ]; - memcpy( out, in, sizeof( *in ) ); - } - } - - /* swap array */ - for( i = 0; i < numGridArray; i++ ) - gridArray[ i ] = LittleShort( gridArray[ i ] ); - - /* write lumps */ - AddLump( file, (bspHeader_t*) header, LUMP_LIGHTGRID, gridPoints, (numGridPoints * sizeof( *gridPoints )) ); - AddLump( file, (bspHeader_t*) header, LUMP_LIGHTARRAY, gridArray, (numGridArray * sizeof( *gridArray )) ); - - /* free buffers */ - free( gridPoints ); - free( gridArray ); -} - - - -/* -LoadRBSPFile() -loads a raven bsp file into memory -*/ - -void LoadRBSPFile( const char *filename ) -{ - rbspHeader_t *header; - - - /* load the file header */ - LoadFile( filename, (void**) &header ); - - /* swap the header (except the first 4 bytes) */ - SwapBlock( (int*) ((byte*) header + sizeof( int )), sizeof( *header ) - sizeof( int ) ); - - /* make sure it matches the format we're trying to load */ - if( force == qfalse && *((int*) header->ident) != *((int*) game->bspIdent) ) - Error( "%s is not a %s file", filename, game->bspIdent ); - if( force == qfalse && header->version != game->bspVersion ) - Error( "%s is version %d, not %d", filename, header->version, game->bspVersion ); - - /* load/convert lumps */ - numBSPShaders = CopyLump_Allocate( (bspHeader_t*) header, LUMP_SHADERS, (void **) &bspShaders, sizeof( bspShader_t ), &allocatedBSPShaders ); - - numBSPModels = CopyLump_Allocate( (bspHeader_t*) header, LUMP_MODELS, (void **) &bspModels, sizeof( bspModel_t ), &allocatedBSPModels ); - - numBSPPlanes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_PLANES, (void **) &bspPlanes, sizeof( bspPlane_t ), &allocatedBSPPlanes ); - - numBSPLeafs = CopyLump( (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, sizeof( bspLeaf_t ) ); - - numBSPNodes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_NODES, (void **) &bspNodes, sizeof( bspNode_t ), &allocatedBSPNodes ); - - numBSPLeafSurfaces = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFSURFACES, (void **) &bspLeafSurfaces, sizeof( bspLeafSurfaces[ 0 ] ), &allocatedBSPLeafSurfaces ); - - numBSPLeafBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFBRUSHES, (void **) &bspLeafBrushes, sizeof( bspLeafBrushes[ 0 ] ), &allocatedBSPLeafBrushes ); - - numBSPBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_BRUSHES, (void **) &bspBrushes, sizeof( bspBrush_t ), &allocatedBSPLeafBrushes ); - - numBSPBrushSides = CopyLump_Allocate( (bspHeader_t*) header, LUMP_BRUSHSIDES, (void **) &bspBrushSides, sizeof( bspBrushSide_t ), &allocatedBSPBrushSides ); - - numBSPDrawVerts = GetLumpElements( (bspHeader_t*) header, LUMP_DRAWVERTS, sizeof( bspDrawVerts[ 0 ] ) ); - SetDrawVerts( numBSPDrawVerts ); - CopyLump( (bspHeader_t*) header, LUMP_DRAWVERTS, bspDrawVerts, sizeof( bspDrawVerts[ 0 ] ) ); - - numBSPDrawSurfaces = GetLumpElements( (bspHeader_t*) header, LUMP_SURFACES, sizeof( bspDrawSurfaces[ 0 ] ) ); - SetDrawSurfaces( numBSPDrawSurfaces ); - CopyLump( (bspHeader_t*) header, LUMP_SURFACES, bspDrawSurfaces, sizeof( bspDrawSurfaces[ 0 ] ) ); - - numBSPFogs = CopyLump( (bspHeader_t*) header, LUMP_FOGS, bspFogs, sizeof( bspFogs[ 0 ] ) ); - - numBSPDrawIndexes = CopyLump( (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, sizeof( bspDrawIndexes[ 0 ] ) ); - - numBSPVisBytes = CopyLump( (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, 1 ); - - numBSPLightBytes = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTMAPS, 1 ); - bspLightBytes = safe_malloc( numBSPLightBytes ); - CopyLump( (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, 1 ); - - bspEntDataSize = CopyLump_Allocate( (bspHeader_t*) header, LUMP_ENTITIES, (void **) &bspEntData, 1, &allocatedBSPEntData); - - CopyLightGridLumps( header ); - - /* free the file buffer */ - free( header ); -} - - - -/* -WriteRBSPFile() -writes a raven bsp file -*/ - -void WriteRBSPFile( const char *filename ) -{ - rbspHeader_t outheader, *header; - FILE *file; - time_t t; - char marker[ 1024 ]; - int size; - - - /* set header */ - header = &outheader; - memset( header, 0, sizeof( *header ) ); - - //% Swapfile(); - - /* set up header */ - *((int*) (bspHeader_t*) header->ident) = *((int*) game->bspIdent); - header->version = LittleLong( game->bspVersion ); - - /* write initial header */ - file = SafeOpenWrite( filename ); - SafeWrite( file, (bspHeader_t*) header, sizeof( *header ) ); /* overwritten later */ - - /* add marker lump */ - time( &t ); - sprintf( marker, "I LOVE MY Q3MAP2 %s on %s)", Q3MAP_VERSION, asctime( localtime( &t ) ) ); - AddLump( file, (bspHeader_t*) header, 0, marker, strlen( marker ) + 1 ); - - /* add lumps */ - AddLump( file, (bspHeader_t*) header, LUMP_SHADERS, bspShaders, numBSPShaders * sizeof( bspShader_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_PLANES, bspPlanes, numBSPPlanes * sizeof( bspPlane_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, numBSPLeafs * sizeof( bspLeaf_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_NODES, bspNodes, numBSPNodes * sizeof( bspNode_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_BRUSHES, bspBrushes, numBSPBrushes*sizeof( bspBrush_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_BRUSHSIDES, bspBrushSides, numBSPBrushSides * sizeof( bspBrushSides[ 0 ] ) ); - AddLump( file, (bspHeader_t*) header, LUMP_LEAFSURFACES, bspLeafSurfaces, numBSPLeafSurfaces * sizeof( bspLeafSurfaces[ 0 ] ) ); - AddLump( file, (bspHeader_t*) header, LUMP_LEAFBRUSHES, bspLeafBrushes, numBSPLeafBrushes * sizeof( bspLeafBrushes[ 0 ] ) ); - AddLump( file, (bspHeader_t*) header, LUMP_MODELS, bspModels, numBSPModels * sizeof( bspModel_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_DRAWVERTS, bspDrawVerts, numBSPDrawVerts * sizeof( bspDrawVerts[ 0 ] ) ); - AddLump( file, (bspHeader_t*) header, LUMP_SURFACES, bspDrawSurfaces, numBSPDrawSurfaces * sizeof( bspDrawSurfaces[ 0 ] ) ); - AddLump( file, (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, numBSPVisBytes ); - AddLump( file, (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, numBSPLightBytes ); - AddLightGridLumps( file, header ); - AddLump( file, (bspHeader_t*) header, LUMP_ENTITIES, bspEntData, bspEntDataSize ); - AddLump( file, (bspHeader_t*) header, LUMP_FOGS, bspFogs, numBSPFogs * sizeof( bspFog_t ) ); - AddLump( file, (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, numBSPDrawIndexes * sizeof( bspDrawIndexes[ 0 ] ) ); - - /* emit bsp size */ - size = ftell( file ); - Sys_Printf( "Wrote %.1f MB (%d bytes)\n", (float) size / (1024 * 1024), size ); - - /* write the completed header */ - fseek( file, 0, SEEK_SET ); - SafeWrite( file, header, sizeof( *header ) ); - - /* close the file */ - fclose( file ); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/changelog.q3map1 b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/changelog.q3map1 deleted file mode 100644 index 21b0cb99..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/changelog.q3map1 +++ /dev/null @@ -1,371 +0,0 @@ -Old Q3Map 1.x and Early Q3Map2 Changelog (Chronological Order) - -- FILE IS STATIC. IF YOU MAKE CHANGES, UPDATE CHANGELOG.Q3MAP2 - - - -Date Version Notes ----------------------------------------------------------------- -2001-12-03 1.2 (ydnar) Alpha Initial version (win32) - -2001-12-03 1.2 (ydnar 2) Alpha Tolerance expanded - (more brush faces caught) - -2001-12-04 1.2 (ydnar 3) Alpha Detail faces inside other - detail brushes now culled, - Small against large detail - faces also culled. - -2001-12-04 1.2 (ydnar 4) Alpha djbob found a bug where - coincident caulk faces - were causing textured - faces to be caulked. Fixed. - -2001-12-04 1.2 (ydnar 7) Alpha 5 and 6 were internal test - versions. This version - takes into account extra - surface info, so coplanar - clip brushes no longer - cull away textured sides. - -2001-12-22 1.2 (ydnar 8) Alpha Optimized light. Lighting - for most maps should now - be measurable in minutes - as opposed to hours. - -2001-12-24 1.2 (ydnar 9) Alpha Fixed light. It is still - faster, but to enable - "blinding fast" mode, - you must supply the -fast - switch on the commandline - after -light. Fast mode - should be approximately - 2x as fast as build 8. - -2001-12-24 1.2 (ydnar 10) Alpha Grid lighting is now - optimized. Not as much - as I would like, but - a distance^2 cull before - traces on EVERY SINGLE - SURFACE LIGHT IN THE MAP - certainly speeds things - the fuck up. -fast not - necessary to see this - optimization. Also added - the -cheap switch to - limit light contributions - to a point when it exceeds - 255 in R, G, and B. This - *may* cause artifacts. - Test away... - -2001-12-24 1.2 (ydnar 11) Alpha Now using PVS data (vis). - Well constructed and - hinted maps should now - see a bit of a speedup. - Lights in the void are - also now removed as a - byproduct. - -2001-12-24 1.2 (ydnar 12) Alpha Fixed bug that caused - vlight to crash. - -2001-12-27 1.2 (ydnar 13) Alpha - Fixed broken PVS check. - - Cheap now supresses sun - Sun trace skipped if - sample is "cheapened." - - Experimental -smooth - option for subsampling - shadow edges. - - Experimental radiosity - code. Will probably crash. - - Other minor optimizations. - -2001-12-27 1.2 (ydnar 14) Alpha Build 13 always subsampled, - making it slower. Fixed. - -2001-12-28 1.2 (ydnar 15) Alpha Bad windings from edge- or - vertex- manipulated brushes - no longer created. Vertex - lighting on func_* with - an origin now works. - Radiosity should be more - stable (but not fully - correct yet). Light - envelopes now properly - calculated for entities - with origins. - -2001-12-28 1.2 (ydnar 16) Alpha Un-vised maps will now light. - -2001-12-30 1.2 (ydnar 17) Alpha Radiosity. Use q3map_bounce - in shaders to specify - amount of light to reflect. - Use -bounce N after -light - to enable radiosity. Use - -dump to emit radiosity - lights as a prefab. - -2001-12-31 1.2 (ydnar 18) Alpha Normalization release. New - features include -fastgrid, - -cheapgrid, and -fastbounce. - Running with -fastgrid and - -cheapgrid will produce - results identical to normal - q3map (with the lightgrid - being a little darker). - Also added q3map_nofast to - shaders to override -fast - switch for a surface light. - -2002-01-01 1.2 (ydnar 19) Alpha Fixed an odd vertex lighting - bug (thanks Quakin) that was - causing sun to leak to brush - faces when using r_vertexlight - ingame. Changed a little bit - of the default behavior, so - test with vertex lighting - and with terrain. Minor - shader changes might be - necessary to get some maps to - look as before. - -2002-01-01 1.2 (ydnar 20) Alpha Colored alpha shadows. Some - minor optimizations in - shadow tracing. Should be - slightly faster than 19. - -2002-01-02 1.2 (ydnar 21) Alpha Set up colored shadows - properly to use - surfaceparm lightfilter. - Shaders must use this parm - to have colored shadows. - Can be used with alphashadow - as well. - -2002-01-04 1.2.1-y1 (nightly) This version is all new, - based off the official - GtkRadiant tree, which has - all the previous enhancements. - New features include colored - lightgrid tracing through - lightfilter shaders, and - surfaceparm lightgrid, for - large/space maps with large - volumes. Also fixed are - potential broken brush - winding radiosity crashes. - Maybe. - -2002-01-05 1.2.1-y2 (nightly) Merged latest CVS. Removed - bug where ambient was getting - calculated into the radiosity - solution for every pass, - leading to overbright maps - in a hurry. Also removed - the bad PTPFF reporting, - as it only caused problems - with radiosity in a big way. - Sue me. - -2002-01-05 1.2.1-y3 (nightly) I really suck. Sample color - now properly cleared to 0 - when bouncing. - -2002-01-07 1.2.1-y4 (nightly) Particle Studio generated - brush faces should no longer - be culled. I no longer cull - faces that are autosprite. - Added -bouncegrid to have - radiosity add to lightgrid. - -2002-01-08 1.2.1-y5 (nightly) Same as y4, but compiled with - full optimizations. Should - be 10-25% faster in all, - including BSP and vis - stages. - -2002-01-09 1.2.1-y6 (nightly) Brushfaces with polygonoffset - in their shader will no longer - be faceculled. - -2002-01-11 1.2.1-y7 (nightly) Increased stack size for threads - to 4MB on Win32 to (hopefully) - elminate stack overflow - crash with radiosity. Also - made subdivision use the heap - to lessen the stack load. Fixed - bug where q3map_bounce was not - being used in shader parsing. - Redid some of the divide math - to work in 0-255 instead of - 0-256. - -2002-01-11 1.2.1-y8 (nightly) More Win32 threading - crutches. Eat me, Bill. - -2002-01-15 1.2.1-y9 RR2DO2 noticed a stupid bug - in my PVS code. Fixed it, - so the PVS light opts work as - they should. Lighting is - faster. Also got rid of some - redundant square roots from - the raytracing, speeding up - lighting another ~25%. - -2002-01-20 1.2.1-y10 Fixed a potential crash bug - with maps with 0 lights. Also - changed how lightmaps are - projected onto patches that - lie in a single plane (bevel - endcaps, floors, etc). Shadows - now work properly on them. - -2002-01-22 1.2.1-y11 Fixed a divide-by-zero crash - with maps with no lights or - no tracing. Also added - code to make brush/patch - vertex lighting more closely - resemble lightmap, even on - less-than-perfect maps. And - -light is faster, too...about - 25% on q3dm17. 34->25 seconds. - -2002-01-24 1.2.1-y12 Completely rewrote the path - argument handling. Should find - the Quake 3 dir and other - dirs properly now. Needs to - be tested on Linux though. - Also made lights linear by - default when run with -game - wolf. This is to match the - Gray Matter q3map and - entity definition. - -2002-01-28 1.2.4-y1 Merged from 1.2.4-nightly CVS - sources. Fog sparklies gone. - -nopatchfix so vlight works - properly again. Cleaned up - paths processing some more, - including Linux stuff. Added - _lightmapscale entity key. - Brought -game wolf lighting - to parity with GM tools. - RR2DO2's PCX loading fix. A - bunch of other useful fun shit. - -2002-01-29 1.2.4-y2 Fixed a bug in RR2DO2's PCX fix. - Fixed a stupid bug in lightmap - dimension bounds checking (thanks - Laerth). - -2002-01-29 1.2.4-y3 Now will detect (and report to - GtkRadiant) all degenerate patches - like those created by capping a - cone. - -2002-02-23 2.0.0-a1 thru a3 Rewrote about 30% of the code. - Lots of cool new shit. - -2002-02-24 2.0.0-a4 thru a8 Terrain fix (thx Pointy), patches - are no longer circus colored, more - terrain texturing fixes. - -2002-02-26 2.0.0-a10 thru a11 Adjacent coplanar surfaces now - will share lightmaps. This prevents - most wierd edge cases with filter - and speeds things up a bit. Patches - too. - -2002-02-27 2.0.0-a12 More lightmap fixes for non-planar - surfaces. Bugfixes in allocation/ - compression of lightmaps as well. - -2002-03-02 2.0.0-a13 Fixed some surface light bugs, - adjusted the occluded-luxel finding - code, and amped the radiosity. Other - fixes to RTCW lighting code (better - angle attenuation on linear lights). - -2002-03-04 2.0.0-a14 Vertex light should now be near- - perfect on clean (and mostly on not- - so-clean) maps. Unlit maps will no - longer have tri-fanned brush faces - with random vertex colors. VLight is - now totally gone (reverts to -light). - -2002-03-06 2.0.0-a15 Relaxed the planar check, should now - classify all slightly-off plane brush - face metasurfaces as planar. Triangle - checking much more stringent as well. - -2002-03-11 2.0.0-a16 Vis crash gone. Lightmap allocation - now sorted by shader to minimize - shader count (and lessen chance for - RTCW shader substitution bug). Hit - big quarter-century also. - -2002-03-12 2.0.0-a17 Dammit. - -2002-03-12 2.0.0-a18 Hunting phantom lights... - -2002-03-16 2.0.0-a19 Fogclip and _celshader. Check the - extras folder... - -2002-03-18 2.0.0-b1-rc1 Beta release candidate. Fixed the - stupid phantom light bug finally. - Tricked out the sun tracing a wee - bit as well, should be a little - faster + more accurate. Other little - bits fixed up as well. Thanks to K, - {wf}ShadowSpawn and RR2DO2 for their - help tracking these last bugs down. - -2002-03-19 2.0.0-b1-rc2 Increased some maximums, and got - rid of some cruft. - -2002-03-22 2.0.0-b1-rc3 Some minor optimizations. - -2002-03-30 2.0.0-b1-rc5 Now with fur (see extras/fur.shader). - -2002-04-01 2.0.0-b1-rc6 Enhanced with baby seal technology. - -2002-05-01 2.0.1 OK, better late than never. Fixed the - alphashadow = 255 = transparent bug. - -2002-06-24 2.1.0-b1 Added _foghull functionality. Works - like terrain "_shader" where - you don't need "textures/" prefix. - Also added q3map_normalmap. See - NVIDIA's website for Photoshop filter - to generate normalmaps from grayscale - heightmaps. This makes lightmaps - look bumpmapped. Currently 50% broken. - -2002-07-06 2.2.0-b1 Empty epairs now stripped from map, - fixing Wolfenstein crash bug. Func_* - entities are now fogged properly. - Sort of. This will be enhanced later. - Added the .srf file to store all the - extra crap I was hiding in the BSP. - It's an editable text file that - -light uses, so you can change the - samplesize w/o recompiling the map - (just -light'ing it). Changed color - normalization to clamping, because - it looks better. Other stuff got - fixed as well. - -2002-07-08 2.2.0-b2 thru b11 Test versions. Thanks jer and jet! - -2002-07-09 2.2.0-b12 Larger-than-life lightmaps are now - supported, up to 1024x1024. Add - q3map_lightmapSize H W to a shader - to use. Lightmaps are stored in - maps/{mapname}/_lm_NNN.tga and a - shader script q3map_{mapname}.shader - is generated. Also added - q3map_lightmapGamma N.N. Use a - value of 2.0 to simulate - r_overBrightBits 1 and - r_mapOverBrightBits 2 on external - lightmap images. diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/changelog.q3map2.txt b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/changelog.q3map2.txt deleted file mode 100644 index d58c0242..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/changelog.q3map2.txt +++ /dev/null @@ -1,709 +0,0 @@ -Q3Map2 Version History + Changelog (Reverse Chronological Order) - -2.5.16 (2004-10-18) - -- New: -fixaas mode to reassociate an AAS file with a changed BSP -- New: -nostyles switch on light phase disabling lightstyles -- Using libmhash cryptographic hashing library instead of md5lib - - -2.5.15 (2004-07-08) - -- New: q3map_rgbGen, q3map_rgbMod or q3map_colorGen, q3map_colorMod -- New: q3map_alphaGen const (like q3map_alphaMod set) -- New: q3map_noVertexLight to suppress overwriting of vertex rgb -- q3map_backShader now works again, can be used instead of - q3map_cloneShader + q3map_invert on the target shader -- q3map_alphaMod volume brushes in func_group entities will now only - affect that entity's surfaces -- q3map_clipModel now works on trans/nonsolid shaders, allowing - simplified clipping surfaces in models -- Fixed bug in alphaMod code where only the first vertex was being - modded (thanks Ratty) -- Vis exits instead of crashing with divide-by-zero when there are - no portals on simple box maps -- All of a surface's lightmaps must be solid or not solid, fixing - ST coord problem with non-Raven games using lightstyles -- Reverted a change in the meta code which was causing lightmap coord - overflows and ugly self-shadowing errors on surface boundaries -- Any use of lightstyles automatically sets -nocollapse to reduce - total shader counts -- Tenebrae lightmap size changed to 512x512 - - -2.5.14 (2004-04-09) - -- New: -dirty mode courtesy of RaP7oR (dirtmapping/ambient occlusion) -- New: q3map_skyLight code using more uniform angular distribution about - the sky hemisphere -- New: q3map_alphaMod set N.N -- New: q3map_alphaMod scale N.N -- New: q3map_alphaMod volume - applies all other q3map_alphaMod directives - to each vertex inside a brush textured with this shader, allowing large - faded scrolling fire shaders, waterfalls, marquees, explicit dotProduct - terrain blending control, etc. -- Fixed a bug in alphaMod code where the type of the first alphaMod was - being used for all subsequent alphaMods -- Lowered vertex-lit surface limits to 999 verts, 1000 was breaking Quake 3 -- Tightened up solid lightmap tolerances -- Fixed bug in solid lightmap code where lightmap SD coords were being - incorrectly set - - -2.5.13 (2004-03-03) - -- New: -convert -format to convert between different BSP formats. - Example, to convert a Jedi Academy map to Enemy Territory: - -game ja -convert -format et -- New: -game etut support for Urban Terror on Enemy Territory -- New: -analyze mode for reverse engineering a BSP format -- New: -compensate N.N (default 1.0) for descaling lightmap/vertex/grid - data to compensate for ingame overbrighting. 4.0 is a good value for - Quake 3 if used in combination with -gamma 2.2 -- New: compensate/gamma per-game setting -- New: -light -cpma argument for "classic" (sic) vertex lighting -- Replaced malloc() with stack allocation in IlluminateRawLightmap for - most small/medium lightmap calculations -- Misc cleanups in q3map2.h -- Support for non-128x128 lightmaps -- The -meta process will now generate surfaces with more than 64 - verts that have non-lightmapped shaders -- Extended lightmap size tolerance to 2x for merging meta triangles in - maps with aggressive lightmapscale. Sorry kids! -- Moved surface finish pass (celshading, cloning) to final surface pass. - This should fix a bug involving fog/tesselation/celshading/cloning -- Solid-color lightmaps (within 1/255 in RGB) are detected and replaced - with a single pixel lightmap, saving space - - -2.5.12 (2004-01-18) - -- New: -dark option for dark lightmap/brush seams in -light (Unreal 1-ish) -- New: spawnflags 4 on misc_model entities makes them forcemeta/lightmapped - unless explicitly set as vertex lit in their shader(s). This can be - combined with spawnflags 2 (solid) as spawnflags 6 -- New: -gamma N.N switch sets lightmap/vertex gamma value for more - realistic lighting, instead of using high ambient/minlight. Default - is 1.0 (linear ramp), good values are between 1.5 and 2.2 -- Changed q3map_lightmapGamma N.N to q3map_lightmapBrightness N.N, to - better match its intended function -- Ported to VS.NET 2003 and GtkRadiant 1.5 (spog_branch) -- Fixed bug in _skybox maps where sunlight was leaking through brushes. - Thanks pjw! -- Fixed bug in ASE loader where models without submodels/submaterials - would not load properly. -- Fixed bug where q3map_tcGen was not being applied to models -- Optimized MergeMetaTriangles a bit -- Added KOR's fix to raytracer -- -bouncegrid no longer affects the lightgrid dir -- Added feature to PicoModel where spaces in material names in 3DS, ASE - and LWO models will mark the end of the shader name, so you can have - "textures/foo/bar 1" and "textures/foo/bar 2" in Lightwave, and both - surfaces will map to "textures/foo/bar" - - -2.5.11 (2003-12-01) - -- New: added support for _skybox entities to generate "portal sky" - surfaces in games w/o native support (Quake 3). _skybox entities have - 3 keys: _scale (default 64), and angle/angles (for rotation of the - skybox relative to the map) -- New: added -skyfix switch to BSP phase as a workaround hack for - the black GL_CLAMP border on skybox edges on ATI (and newer nvidia) - video cards. Note: unnecessary in ET or JA -- New: Added _anglescale to light entities for scaling angle attenuation. - Use a small value (< 1.0) to lessen the angle attenuation, and a high - value (> 1.0) for sharper, more faceted lighting -- New: Added _lightmapscale support to misc_model entities -- Custom shaders (external lightmaps, styles) will not be generated - if the find/replace text cannot be found -- Tightened up light culling epsilon from 1.0 to 0.125 to stop certain - surface lights from being incorrectly culled (thanks RasputiN!) -- Fixed bug where small 3 and 4 sided brush faces were getting fanned, - adding triangle/vertex counts -- Moved to Visual Studio .NET, with aggressive optimizations enabled -- Cleaned up missing image warnings -- Parsing images out of shader stages if not found explicit/implicitly -- Loads Enemy Territory implicitMap images if editor/light image not found - - -2.5.10 (2003-10-22) - -- New: Lightwave model support (beta) courtesy of RR2DO2 -- New: Heretic 2 FM model support courtesy of Nurail -- Re-enabled vertex cache friendly triangle reordering with fix -- Disabled triangle reordering on certain surfaces, including autosprite - shaders due to visual errors -- Fixed bug in radiosity where sorting of lights by style took forever. - Thanks ReBoOT! -- Fixed bug in sun lighting code where maps too far off the origin would - not be properly it by sun or sky light. Thanks MindLink! -- Entity causing a leak will be printed and selected in Radiant if BSP - monitoring is enabled. Requested by heeen -- Fixed odd bug causing 10x slowdown in lighting in some maps. Should - be back to 2.5.7 performance. Also fixed a couple old bugs related to - autosprite shader (point) lights and backsplash lights not being styled - or setup correctly - - -2.5.9 (2003-10-12) - -- Disabled triangle reordering for now (crashing on some maps) - - -2.5.8 (2003-10-02) - -- New: Added two new sun parameters: angular deviation (width of the sun in - degrees) and sampling count (jitters). This allows for decent approximation - of penumbra "half-shadow" effects from sunlight with 16+ samples. These - parameters are accessible for entity lights (including spots and suns) via - these entity keys: _deviance and _samples. To use in shaders, use the new - q3map_sunExt -- New: q3map_lightmapFilterRadius for light-emitting shaders. - Put *after* any q3map_sun directives or else your sun will be filtered. This - is good for eliminating the "stadium lighting" effect from q3map_skyLight. - Also usable as an entity key: _filterradius or _filter -- New: Quake 2 MD2 model support in PicoModel for misc_model entities - (thanks to Nurail!) -- Re-enabled vertex-cache-aware triangle reordering. Will probably have a - negligible effect on rendering performance, but can't hurt -- Added short-circuit to raytracer: any empty nodes (including children) are - ignored on sun traces -- Added BSP file size printout -- Filtering of any kind now disables adaptive supersampling on a per-light, - per-ightmap basis -- Fixed another _minlight <-> styled light interaction bug (thanks pjw!) - - -2.5.7 (2003-08-31) - -- New: Jedi Academy support via -game ja -- New: DDS (DXT1/3/5) texture support for future games -- Re-enabled q3map_surfaceModel support, and the 'oriented' flag works as well -- Re-enabled (fixed, really) large external lightmap support -- Fixed a bug in the model code that would cause a crash if an uninvertable - matrix was created -- Fixed a bug in Mathlib m4x4_t code where the tolerance for a singular matrix - was too low and crapping out on small (scaled down) matrices -- Fixed bug in divide-by-zero on lightmap efficiency calculation -- Added -force switch, allows unsupported BSP formats to (try) to be loaded - - -2.5.6 (2003-08-15) - -- New: can convert BSP files to MAP files via -convert -format map. Note: not - perfect by any means, as certain pieces of data are irretrievably lost, such - as func_group entities (including terrain specifics), brush face texturing - info, and light/misc_model entities with Q3Map2-generated BSPs - - -2.5.5 - -- New: -scale N.N mode to scale the BSP -- New: -light -lomem switch to supress trace BSP optimization. This - feature trades lighting performance for decreased memory usage -- New: Added negative light support (note: will not darken below _minlight value) - might screw up radiosity, haven't tested much. Should work with entity - lights, shader lights, sun/sky lights and radiosity. Lightfilter shadows - tint negative lights too, so the end effect is subtraction of the color -- New: Lightstyle support for non-Raven (JK2/SOF2) games, including Quake 3, - RTCW, ET, EF. Only works with lightmapped surfaces, use with care -- Fixed long standing terrain texturing bug, should produce exact desired - results all of the time now. May require fixing alphamaps that were - kludged together to accomodate this bug on existing maps -- Fixed bug (huh, wtf) causing misc_model surfaces to not be fogged -- Fixed bug where fog brushes wouldn't fog surfaces if a global map fog - shader was present -- Fixed bug where -patchmeta surfaces were being ignored for raytracing -- Fixed long-standing bug where twosided surfaces were not correctly - bouncing light. You can now have a foggy glass window that re-emits - bright light with q3map_bounce 3.0 or so -- Fixed really stupid bug in radiosity with bouncing styled lights -- Stripping .map and appending .bsp in -info mode -- Fixed bug where tesselated brush face surfaces were not being fogged -- Twosided surfaces (using cull disable/twosided/none) are now lit twosided -- Added tighter tolerance for alphashadow/lightfilter shadowing to raytracer - which fixed problem with double shadows from tracing near triangle seams -- Brush entities should now be properly fogged. Really. -- Styled lightmaps are no longer affected by _minlight (doh) - - -2.5.4 (2003-04-01) - -- New: q3map_tessSize support for JK2/SOF2 -- New: -lightmapsize N argument -- Fixed bug where switched styled lights weren't working correctly in SOF2/JK2 -- Fixed bug where external lightmaps with generated shaders were referencing - the wrong lightmap -- Fixed bug causing lightgrid brushes to be ignored -- Added variable sphere around trace sample points to inhibit occluder geometry - - -2.5.3 (2003-03-06) - -- New: SOF2/JK2 light styles now supported -- New: q3map_lightStyle N to set shader lightstyles -- New: Tenebrae 2 support via -game tenebrae -- New: -light -deluxe and -debugdeluxe for Tenebrae "deluxemap" static - lighting algorithm -- Light envelopes now properly clipped to the PVS -- q3map_vertexScale re-enabled (scales vertex lighting per-shader) -- Minor bug in brush bevel code corrected -- Brushes from func_group entities are correctly sorted on insertion -- Fixed a couple misc warnings to print "percent" instead of "%" -- Added -custinfoparms support to -light mode to suppress warnings -- _minlight, _minvertexlight and _mingridlight order independent, and now - allow for values of 0 - - -2.5.2 (2003-02-17) - -- Fixed crash bugs with global map fog -- Model loading really only warns once now - - -2.5.1 (2003-02-17) (Splash Damage internal release) - -- Added more Hella-Fast juice to light code. Overall should be 35% faster -- Refactored surface portion of raytracer code for less memory usage -- Changed UVW epsilon in raytracer to catch more edge cases -- Removed bounds check on occluded luxel finding, was causing more problems - than it was solving -- Adaptive antialiasing code now ignores unmapped luxels for better shadow - edges and higher performance -- Brushes in the BSP are now sorted opaque first -- Fixed Really Stupid bug causing MapRawLightmap to take about 4x as long -- Added optimization to make MapRawLightmap 2x as fast -- New non-sucky quadrilateral subdivision of patches for MapRawLightmap -- Patches with < 90 degrees of curvature are now box-lightmapped -- Patch vertex normals now correctly stored, fixing bug in 2.5.0 -- Prints warning if map with < 10% detail brushes is detected - - -2.5.0 (2003-02-14) (Splash Damage internal release) - -RAYTRACING AND SHADOW CALCULATION -- New raytracing code. Rewrote the raytracer to maximize efficiency on modern - "caulk-hull" maps. Uses triangle intercept code written by SPoG, based on code - by Tomas Moller and Ben Trumbore (Journal of Graphics Tools, 2(1):21-28, 1997) - and a biased octree leaf subdivision scheme by Y.T. -- Shadows (casting and receiving) are now controllable per-entity - New entity keys: "_castShadows" or "_cs" and "_receiveShadows" or "_rc" - Values: 0 = no shadows, 1 = worldspawn shadows, > 1 explicit shadow group, - negative values imply no worldspawn shadow interation. - *Entities, including model2 and RTCW misc_gamemodels can now cast shadows* - -RADIOSITY -- Bumped up default and smallest radiosity patch size. Performance should be - approximately 4x with a small quality tradeoff -- Radiosity patches now trace to centroid of triangle, and not bounds center -- Radiosity and surface lights are now nudged around a bit if in solid -- Radiosity light generation code is now thread-safe -- Radiosity -dump files now .map instead of .pfb -- Poorly worded "q3map_bounce" renamed to "q3map_bounceScale" (old still works) -- New -bounceonly switch to store only bounced light in the BSP (for Tenebrae) - -MISC LIGHTING -- Optimized case where light and sample are coplanar -- Forcing nudged luxels to stay within lightmap surfaces' bounds - -CURVED SURFACES -- New -subdivisions N argument, works with -patchmeta and -light for setting - patch level-of-detail. Default value is 8, use 4 to simulate default Q3 -- All patch tesselation code changed to create x-patterned tesselation for - better lighting -- Storing patch LOD info in the .srf file for better patch light/shadows - -FOG -- Reworked fog code to fix bad interation with fog and clipped models - -MODELS -- Entities with attached MD3/ASE misc_models now have their bounds correctly set -- Attached misc_models now support q3map_clipModel for solidity -- Missing models will only warn once, rather than spew errors - -MISC -- Metasurface merging no longer folds nonplanar triangles into planar surfaces - and vice-versa * -- Fixed Really Stupid Bug where entity numbering was not loaded by lighting code - resulting in lightmaps merging across entity boundaries * - -* Might result in slightly larger BSP. For maximum efficiency, ungroup - func_group entities before doing a final compile - -TODO -+ Document new shadow stuff -+ Merge adjacent light-casting triangles into convex windings - - -2.3.38 (2003-02-07) - -- New lighting code, return of Smoove-B. Intelligently antialises shadow edges - when you use the new -samples N switch. Get -extra quality in 1/3 the time -- New lightmap filtering code. Now using a proper 0.25/0.5/1.0 filter kernel. - Also operates on individual lightsources, so per-lightsource filter/kernel - settings are now possible -- New -patchmeta fixes, now does stitching and adaptive subdivision. - Thanks Sock! -- Nonsolid patches will no longer be in the BSP when run with -patchmeta -- Misc fog fixes, including q3map_noFog support in maps with global _fog - support (SOF2/JK2) -- Now stripping misc_model entities from the BSP -- Fixed disappearing face bug that's been present since 2.3.36. - Thanks Shadowspawn! - - -2.3.37 (2003-01-24) - -- Building from GtkRadiant CVS trunk -- Added new brush bevel code by MrElusive to fix lingering aas problems (sweet!) -- Added -snap N arg to BSP phase for axial bevel plane snapping to reduce - clipped model plane count (note: will muck with above, use with care) -- Patches in terrain entities should now have proper vertex alpha set -- Fixed bug in fur code where fur was being limited to 2 layers (thanks pazur) -- Reduced vertexlight search area to a reasonable size to keep vertex lighting - times down - - -2.3.36 (2003-01-15) - -- Plane hashing re-enabled (I suck) -- Plane hashing optimized (faster parsing of larger maps) -- Plane finding accuracy code enabled -- New ASE clipping code - + With above should be 10-50% faster - + Should generate 33% fewer planes - + Generates mostly-axial 5-sided polyhedra instead of pyramids, - for tighter 2-sided clipping -- New -light args: - + -scale N -- scales all lightsources (area, radiosity, point, sky) - + -sky[scale] N -- scales sky lights (q3map_skylight, q3map_sunlight) -- Changed fur code to scale fur offset based on original vertex alpha - - -2.3.35 (2003-01-14) - -- PicoModel now inverts ASE T coordinate -- BSP to ASE converter now inverts T coordinate -- Disabling 2.3.34 triangle optimization code until I find out why it crashes -- Fixed Conscript-q3map2 to use stack_size ld flags directly on Darwin/OS X -- Added Conscript-q3map2 to q3map2.dsp for easier Win32 edit, *nix target - - -2.3.34 (2003-01-08) - -- Building from merged GtkRadiant 1.2 -> 1.3 merged codebase -- IMPORTANT NEW CHANGE: Light entities are now STRIPPED from the BSP file. - They are re-read in by -light from the MAP file. This has two consequences: - + It is no longer necessary to re-BSP & re-vis a map in order to change - lighting. You can just change lights in the map file and run -light. - + Slightly smaller BSP file, due to fewer entities - + Faster loading time, as the game code doesn't have to deal with them -- Added new -ne (normal epsilon) and -de (distance epsilon) for tuning precision - of plane snapping to correct potential AAS/BSP issues -- Using latest PicoModel, with support for RTCW MDC models -- Surfaces per raw lightmap are now sorted by shader name, which should give - slightly better lightmap efficiency and lower in-game shader counts -- Adjusted model code to use correct m4x4_t code & angles key -- Minor bugfix in patch color gradient calculation code -- Silenced erroneous areaportal warning spew -- q3map_tcGen now works on model surfaces -- Using default radiosity subdivide of 256 again (should make radiosity faster) -- Enabled byte-swapping code so Q3Map2 can be compiled/run on little-endian - architectures (Mac OS X) - - -2.3.33 (2002-12-08) - -- Added new -bouncescale argument for radiosity scaling -- Added -pointscale and -areascale for consistent naming -- Radiosity patch subdivision code enhanced -- Hint portals split the BSP first (higher priority) -- Antiportal and areaportal faces split the BSP last, to minimize errors -- Areaportals work internally like hint and antiportals, so they no longer need - to be full brushes (the other sides can be skip) -- External lightmaps are now named "lm_NNNN.tga" in the maps/mapname dir -- Cleaned up some of -light argument processing -- Planar surfaces w/o lightmaps will no longer be tagged as MST_TRIANGLE_SOUP - (this fixes problems with Particle Studio particles dropping out of view) - - -2.3.32 (2002-11-30) - -- GtkRadiant (1.2.11) integration -- Added epsilon to texture plane choose code to eliminate numerical - inconsistencies on brush faces slanted at 45 degree angles (bug 637) -- Fixed bug in lightmap export after lighting when map contains 0 BSP lightmaps -- Adjusted some light tracing constants to fix certain brush/patch seam shadows -- Tinkered with skylight code again -- Fixed bug where lightgrid would be black if level was compiled with -nogrid -- Fixed -approx code to work in floating-point space, using _minlight -- Fixed bug where vertex light code was using invalid pvs data to create - light list for surface, leading to incorrect vertex lighting -- Fixed related bug in anti-light-leak code that was causing brush faces to go - black (bug 694) -- New: _minlight sets _minvertexlight and (new) _mingridlight automatically -- New: _mingridlight key to set minimum grid lighting - - -2.3.31 (2002-11-21) - -- Stitching the edges of lightmaps on patches that wrap around (cyls and cones) - so the seam is no longer visible -- The -patchmeta switch works better now, the patches are still stored in the - BSP for collision, but are pre-tesselated into nonplanar meta surfaces for - more efficient rendering -- Better, more uniform lightmap sample position finding on patch meshes -- Moved q3map_tcMod and q3map_alphaMod processing to the final phase -- New: q3map_skylight AMOUNT ITERATIONS to replace surfacelight on sky surfaces - for much faster and more uniform sky illumination - - -2.3.30 (Splash Damage internal release) - -- Fixed bug in PicoModel ASE material parsing code -- Fixed a few seam/lightmap precision/projection errors -- Increased MAX_SHADER FILES to 1024 and fixed overrun error when more than that - number of shaders was listed in shaderlist.txt -- Increased a few compiler maximums for larger maps -- New: -np N switch on BSP phase, works like -shadeangle, in that it forces all - planar shaders to be nonplanar with the shading angle specified -- New: -nohint switch on BSP phase, omits hint brushes from compile for testing -- New: -debugaxis switch on light mode. Colors lightmaps based on their lightmap - axis (which direction the lightmap was projected on) -- New: -debugorigin switch on light mode. Colors lightmaps based on the luxel - origin relative to the raw lightmap's bounding box -- New: -debugcluster switch on light mode. Colors lightmaps based on the pvs - cluster the luxel falls into -- New: -convert switch to convert BSP to ASE file (experimental) -- New: q3map_lightmapmergable directive to allow terrain to be mapped onto a - single lightmap page for seamless terrain shadows - - -2.3.29 (2002-11-03) - -- Merged with latest CVS, fixed minor issues with matrix order -- Fixed minor Sys_FPrintf/Sys_Printf substitution typo in Q3Map2 -- Expanded debug colors to 12 for debugging surface meshes -- PicoModel: fixed ASE loader to support > 1 texture coordinate per-vertex, - so more models supported correctly, also loading vertex normals -- PicoModel: md3 shader names are now cleaned. Suffixes (such as .tga or .jpg) - are stripped, and \ path separators are changed to / -- New: Add :q3map to the end of any shader name, and it will be interpreted as - the named shader minus :q3map. Example: - textures/shaderlab/concrete:q3map -> textures/shaderlab/concrete - One potential use is the -approx feature to collapse lightmapped surfaces - into vertexlit surfaces, saving lightmap space/memory -- New: q3map_clipModel -- does what you think it does, sort of. This code ix - really experimental, and should *only* be used on large models such as terrain - (not small decorative models). This code will be evolving. Note: the shader's - surfaceparms are inherited by the magic clip brush, so if you have nonsolid - in your model's shader that uses q3map_clipModel, then the brush will also - be nonsolid - - -2.3.28 (2002-11-01) - -- Bug 654 (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=654): - Fixed problem where brush faces, drawsurfaces, and surfaceparms weren't living - together in perfect harmony (terrain surfaceparms now inherited by brushes) -- Nodraw fog works now, albeit when you're underneath, surfaces above don't get - fogged properly. Could be good for foggy water where you want the above-water - portions to only be occluded by the water surface -- Bug 656 (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=656): - Number of lightgrid points displayed (byte size is currently out of proportion - due to internal storage format) when Q3Map is called with the -info switch -- Fixed wack surface merging bug where code would attempt to merge triangles not - adjacent to the current set, causing bad lightmap projections on nonplanar - surfaces -- Fixed tiny 1-character bug in 2d lightmap texture allocator where adjacent - luxels were being checked for occlusion rather than the actual source luxel - - -2.3.27 (2002-10-31) Happy Halloween! - -- Fixed minor bug in scriplib bugfix where the last character in a file wasn't - being read. -- Fixed bug where 0-area or bogus triangles were causing crash in MapRawLightmap - if they used a shader with a normalmap (thanks ShadowSpawn) -- Fixed bug where lightmaps were getting hosed levelwide on a prerelease version - of 2.3.27 -- Fixed bug where lightmaps were getting knackered on models and certain patches -- Merged latest PicoModel version from seaw0lf, adding support for ASE and WF OBJ - models (preliminary) -- Increased MAX_MAP_PLANES to 0x40000 (~256k) - -Known issues: -- Lightmap projection and surface merging on large ASE models sometimes flakes -- Surface to brush surfaceparm propogation doesn't work properly with large - metasurfaces: http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=654 - - -2.3.26 (2002-10-27) - -- Now using GtkRadiant's libpng and zlib config (linked as DLLs) -- Fixed bug in script parser where repeat calls to GetToken() were causing - memory corruption -- Fixed SOF2 -rename bug -- When using -game sof2 or -game jk2, the -flares argument is implied -- Added -noflares argument to disable the above behavior -- Added support for flares on entities. Use one of the following keys: - "_flare" "1" -- use default flare (different for each game) - "_flareshader" "path/to/flareshader" -- use a specific flare shader - Note: This only matters in SOF2/JK2 now. Make a light targetted (a spotlight) - to get it to aim the correct direction, otherwise it defaults to pointing - downward. You cannot have omnidirectional flares -- Lightgrid size is automatically increased to accomodate large maps. The - MAX_MAP_LIGHTGRID error will never happen again - - -2.3.25 (2002-10-22) - -- Go Giants! -- Fixed bug where Q3Map would crash on writing the BSP after the light stage. - Thanks to Rap7or (#q3map) and loon8 (Q3W forums) [bug 641] -- Fixed bug where surface lights were not affecting the light grid properly. - Thanks to Shadowspawn and djbob [bug 642] -- NEW: Added -faster support to lightgrid calculations while fixing previous bug -- NEW: Changed it so the BSP file is written to a temp file first, then renamed. - This should prevent BSP file corruption on crashes during writes - - -2.3.24 (2002-10-20) - -- Fixed numerous outstanding bugs and issues. -- Normal interpolation is now improved. It's slightly slower, but more 'correct' - in cases where you have 10 triangles in one plane and 1 triangle in another - meeting up and the 10 triangles were over-affecting the average. Only new - identical normals are averaged now. This change affects phong shading, meta - surfaces, and PicoModel -- PicoModel up to version 0.7.6, BSD license, better 3DS model support -- PicoModel library now fixes broken normals on MD3 and 3DS models -- Bumpmapping code is improved. The correct tangent vectors per-triangle are - now calculated so the bumpmaps are consistent with regards to light direction -- Metasurface merging code optimized. Should be about 100x as fast on complex - maps or maps using models with high triangle counts -- Vertexlight code tweaked a bit -- Triangle/winding orders now more consistent. Tesselated surfaces will have - a uniform triangle ordering (thanks RR2DO2) -- NEW: "vertexDeform move" now parsed and surfaces are merged into the - appropriate BSP leaves they may enter into (thanks to Bart Vrijkorte) -- NEW: shader command: q3map_alphaMod. Currently takes a single form: - q3map_alphaMod dotproduct ( NX NY NZ ) - where NX NY NZ are a unit normal (length of 1.0) specifying direction. - An example use would be snow in a shader's 2nd pass, using alphaFunc or - blendFunc: - q3map_alphaMod dotproduct ( 0 0 1 ) // surfaces facing upwards have snow - (idea contributed by RR2DO2) - - -2.3.23 (2002-10-18) - -- In my haste to release the previous version, I neglected to give credit where - it was due. Seaw0lf had as much (probably more) to do with the new model - loading library (PicoModel). Because of his efforts, you can load 3DS models - and use them in misc_model entities. -- PicoModel model library up to version 0.7. Improved 3DS support, more stable. -- Surface models still not reenabled. Soon. :) -- You can now remap a misc_model's shaders like this: - Key "_remapNN" "the/model/shader;the/real/shader" - This works just like TA terrain vertexRemapShader key. You can also supply a - * glob for the source shader if you want all your model's shaders to use the - specified shader: - "_remap" "*;models/mapobjects/tree/bark" - - -2.3.22 (2002-10-16) - -- Moving to sensible Linux-style versioning. -- The misc_model code has been completely rewritten, breaking surface models. - Surface models will reappear in the next release, once the new model API has - stablized. -- New: MD3 and 3D Studio 3DS models now natively supported. -- The misc_model "angles" key now supported. Values: "pitch yaw roll" in keeping - with standard Quake 3 angles order. -- Models scaled with "modelscale_vec" now have proper normal scaling/rotation - (thanks SPOG). -- Models can now be lightmapped. -- Models can now have > 1000 vertexes per surface. -- For best results for above, add the following to models' shaders: - q3map_splotchfix - q3map_nonplanar -- 3DS models' MATERIAL NAMES ARE THE FINAL Q3 SHADER NAMES. YOU HAVE BEEN WARNED. -- Models are generally 13373R. :) - - -2.3.0-a21 (2002-10-02) - -- Fixed a stack of really stupid bugs in the lightgrid code. Should be faster - and more predictable now. -- SOF2/JK2 lightgrid now compiled. This is the first version of Q3Map2 that can - compile full, release-worthy SOF2 and JK2 maps. -- SOF2/JK2 damageshader and damagable brush faces should work correctly now. - - -2.3.0-a20 (2002-09-26) - -- SOF2/JK2 worldspawn "fog" (and "_fog") shader key support for levelwide fog -- SOF2/JK2 light "scale" key to scale light brightness -- SOF2/JK2 -rename function for _bsp and _rmg_bsp shader renaming - - -2.3.0-a19 (2002-09-24) - -- Shaders can now be subclassed (Q3Map relavant portions only, such as - surfaceparms, lighting, texture projection, etc). To subclass an existing - shader, add "q3map_baseshader X" where X is the name of the base shader. -- Preliminary auto-model distribution over surfaces. You can now have things - like grass and tree models automatically distributed across your terrain - or other surfaces. To wit: - - q3map_surfacemodel models/mapobjects/tree2/tree2.md3 64 0.001 0.5 4.0 0 360 1 - - q3map_surfacemodel - - - The last flag is 1 or 0, and sets whether the model gets fitted to the - orientation of the surface. Not functional yet. See screenshots page for - shots of this in action. - - -2.3.0-a18 (2002-09-21) - -- misc_models can now be attached to any brush model entity. Just target the - brush entity with the misc_model (select model, then entity, hit Ctrl+K) -- q3map_tcMod translate (or shift or offset) -- q3map_tcMod rotate (rotates around origin, not center) -- q3map_tcMod scale -- Metasurface merging now much, much better. Merges into roughly rectangular or - square areas wherever possible -- q3map_terrain no longer sets Z-axis lightmap projection. It must be set in - the terrain layer shaders if you want previous behavior -- Worlspawn _blocksize key now supports 3 elements for setting X Y and Z splits - independently of each other (use a value of 0 for no splits on that axis) -- Misc bugfixes - - -2.3.0-a1 through 2.3.0-a17 (2002-07 through 2002-09-20) - -- Elite Force support (via -game ef) -- SOF2 and JK2 support (via -game sof2 or -game jk2) -- All new image handling with PNG support -- q3map_lightimage specifies image for radiosity and lighting -- External lightmaps, set using q3map_lightmapsize . Up to - 1024 x 1024 supported. -- q3map_lightmapGamma sets the brightness scale of a lightmap -- q3map_lightmapsampleoffset to fix glitches in lightmapped terrain -- Tons more features and bugfixes. See the forum threads for details/screenshots -- Two new surfaceparms, "antiportal" and "skip," and associated shaders, for - allowing the mapper to more cleanly set up visibility data -- Lightmaps will always have square texels now (no more stretching) -- Vertex light improvements -- Light grid improvements -- q3map_lightrgb support for RTCW - - - - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_ase.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_ase.c deleted file mode 100644 index 56262311..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_ase.c +++ /dev/null @@ -1,437 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define CONVERT_ASE_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -ConvertSurface() -converts a bsp drawsurface to an ase chunk -*/ - -int numLightmapsASE = 0; -static void ConvertSurface( FILE *f, bspModel_t *model, int modelNum, bspDrawSurface_t *ds, int surfaceNum, vec3_t origin ) -{ - int i, v, face, a, b, c; - bspDrawVert_t *dv; - vec3_t normal; - char name[ 1024 ]; - - - /* ignore patches for now */ - if( ds->surfaceType != MST_PLANAR && ds->surfaceType != MST_TRIANGLE_SOUP ) - return; - - /* print object header for each dsurf */ - sprintf( name, "mat%dmodel%dsurf%d", ds->shaderNum, modelNum, surfaceNum ); - fprintf( f, "*GEOMOBJECT\t{\r\n" ); - fprintf( f, "\t*NODE_NAME\t\"%s\"\r\n", name ); - fprintf( f, "\t*NODE_TM\t{\r\n" ); - fprintf( f, "\t\t*NODE_NAME\t\"%s\"\r\n", name ); - fprintf( f, "\t\t*INHERIT_POS\t0\t0\t0\r\n" ); - fprintf( f, "\t\t*INHERIT_ROT\t0\t0\t0\r\n" ); - fprintf( f, "\t\t*INHERIT_SCL\t0\t0\t0\r\n" ); - fprintf( f, "\t\t*TM_ROW0\t1.0\t0\t0\r\n" ); - fprintf( f, "\t\t*TM_ROW1\t0\t1.0\t0\r\n" ); - fprintf( f, "\t\t*TM_ROW2\t0\t0\t1.0\r\n" ); - fprintf( f, "\t\t*TM_ROW3\t0\t0\t0\r\n" ); - fprintf( f, "\t\t*TM_POS\t%f\t%f\t%f\r\n", origin[ 0 ], origin[ 1 ], origin[ 2 ] ); - fprintf( f, "\t}\r\n" ); - - /* print mesh header */ - fprintf( f, "\t*MESH\t{\r\n" ); - fprintf( f, "\t\t*TIMEVALUE\t0\r\n" ); - fprintf( f, "\t\t*MESH_NUMVERTEX\t%d\r\n", ds->numVerts ); - fprintf( f, "\t\t*MESH_NUMFACES\t%d\r\n", ds->numIndexes / 3 ); - switch( ds->surfaceType ) - { - case MST_PLANAR: - fprintf( f, "\t\t*COMMENT\t\"SURFACETYPE\tMST_PLANAR\"\r\n" ); - break; - case MST_TRIANGLE_SOUP: - fprintf( f, "\t\t*COMMENT\t\"SURFACETYPE\tMST_TRIANGLE_SOUP\"\r\n" ); - break; - } - - /* export vertex xyz */ - fprintf( f, "\t\t*MESH_VERTEX_LIST\t{\r\n" ); - for( i = 0; i < ds->numVerts; i++ ) - { - v = i + ds->firstVert; - dv = &bspDrawVerts[ v ]; - fprintf( f, "\t\t\t*MESH_VERTEX\t%d\t%f\t%f\t%f\r\n", i, dv->xyz[ 0 ], dv->xyz[ 1 ], dv->xyz[ 2 ] ); - } - fprintf( f, "\t\t}\r\n" ); - - /* export vertex normals */ - fprintf( f, "\t\t*MESH_NORMALS\t{\r\n" ); - for( i = 0; i < ds->numIndexes; i += 3 ) - { - face = (i / 3); - a = bspDrawIndexes[ i + ds->firstIndex ]; - b = bspDrawIndexes[ i + ds->firstIndex + 1 ]; - c = bspDrawIndexes[ i + ds->firstIndex + 2 ]; - VectorCopy( bspDrawVerts[ a ].normal, normal ); - VectorAdd( normal, bspDrawVerts[ b ].normal, normal ); - VectorAdd( normal, bspDrawVerts[ c ].normal, normal ); - if( VectorNormalize( normal, normal ) ) - fprintf( f, "\t\t\t*MESH_FACENORMAL\t%d\t%f\t%f\t%f\r\n", face, normal[ 0 ], normal[ 1 ], normal[ 2 ] ); - } - for( i = 0; i < ds->numVerts; i++ ) - { - v = i + ds->firstVert; - dv = &bspDrawVerts[ v ]; - fprintf( f, "\t\t\t*MESH_VERTEXNORMAL\t%d\t%f\t%f\t%f\r\n", i, dv->normal[ 0 ], dv->normal[ 1 ], dv->normal[ 2 ] ); - } - fprintf( f, "\t\t}\r\n" ); - - /* export faces */ - fprintf( f, "\t\t*MESH_FACE_LIST\t{\r\n" ); - for( i = 0; i < ds->numIndexes; i += 3 ) - { - face = (i / 3); - a = bspDrawIndexes[ i + ds->firstIndex ]; - c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; - b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; - fprintf( f, "\t\t\t*MESH_FACE\t%d\tA:\t%d\tB:\t%d\tC:\t%d\tAB:\t1\tBC:\t1\tCA:\t1\t*MESH_SMOOTHING\t0\t*MESH_MTLID\t0\r\n", - face, a, b, c ); - } - fprintf( f, "\t\t}\r\n" ); - - /* export vertex st */ - fprintf( f, "\t\t*MESH_NUMTVERTEX\t%d\r\n", ds->numVerts ); - fprintf( f, "\t\t*MESH_TVERTLIST\t{\r\n" ); - for( i = 0; i < ds->numVerts; i++ ) - { - v = i + ds->firstVert; - dv = &bspDrawVerts[ v ]; - fprintf( f, "\t\t\t*MESH_TVERT\t%d\t%f\t%f\t%f\r\n", i, dv->st[ 0 ], (1.0 - dv->st[ 1 ]), 1.0f ); - } - fprintf( f, "\t\t}\r\n" ); - - /* export texture faces */ - fprintf( f, "\t\t*MESH_NUMTVFACES\t%d\r\n", ds->numIndexes / 3 ); - fprintf( f, "\t\t*MESH_TFACELIST\t{\r\n" ); - for( i = 0; i < ds->numIndexes; i += 3 ) - { - face = (i / 3); - a = bspDrawIndexes[ i + ds->firstIndex ]; - c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; - b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; - fprintf( f, "\t\t\t*MESH_TFACE\t%d\t%d\t%d\t%d\r\n", face, a, b, c ); - } - fprintf( f, "\t\t}\r\n" ); - - /* print mesh footer */ - fprintf( f, "\t}\r\n" ); - - /* print object footer */ - fprintf( f, "\t*PROP_MOTIONBLUR\t0\r\n" ); - fprintf( f, "\t*PROP_CASTSHADOW\t1\r\n" ); - fprintf( f, "\t*PROP_RECVSHADOW\t1\r\n" ); - if(lightmapsAsTexcoord) - { - if(ds->lightmapNum[0] >= 0 && ds->lightmapNum[0] + deluxemap < numLightmapsASE) - fprintf( f, "\t*MATERIAL_REF\t%d\r\n", ds->lightmapNum[0] + deluxemap ); - else - Sys_Printf( "WARNING: lightmap %d out of range, not exporting\n", ds->lightmapNum[0] + deluxemap ); - } - else - fprintf( f, "\t*MATERIAL_REF\t%d\r\n", ds->shaderNum ); - fprintf( f, "}\r\n" ); -} - - - -/* -ConvertModel() -exports a bsp model to an ase chunk -*/ - -static void ConvertModel( FILE *f, bspModel_t *model, int modelNum, vec3_t origin ) -{ - int i, s; - bspDrawSurface_t *ds; - - - /* go through each drawsurf in the model */ - for( i = 0; i < model->numBSPSurfaces; i++ ) - { - s = i + model->firstBSPSurface; - ds = &bspDrawSurfaces[ s ]; - ConvertSurface( f, model, modelNum, ds, s, origin ); - } -} - - - -/* -ConvertShader() -exports a bsp shader to an ase chunk -*/ - -/* - *MATERIAL 0 { - *MATERIAL_NAME "models/test/rock16l" - *MATERIAL_CLASS "Standard" - *MATERIAL_AMBIENT 0.5882 0.5882 0.5882 - *MATERIAL_DIFFUSE 0.5882 0.5882 0.5882 - *MATERIAL_SPECULAR 0.5882 0.5882 0.5882 - *MATERIAL_SHINE 0.0000 - *MATERIAL_SHINESTRENGTH 0.0000 - *MATERIAL_TRANSPARENCY 0.0000 - *MATERIAL_WIRESIZE 1.0000 - *MATERIAL_SHADING Phong - *MATERIAL_XP_FALLOFF 0.0000 - *MATERIAL_SELFILLUM 0.0000 - *MATERIAL_FALLOFF In - *MATERIAL_XP_TYPE Filter - *MAP_DIFFUSE { - *MAP_NAME "Map #2" - *MAP_CLASS "Bitmap" - *MAP_SUBNO 1 - *MAP_AMOUNT 1.0000 - *BITMAP "models/test/rock16l" - *MAP_TYPE Screen - *UVW_U_OFFSET 0.0000 - *UVW_V_OFFSET 0.0000 - *UVW_U_TILING 1.0000 - *UVW_V_TILING 1.0000 - *UVW_ANGLE 0.0000 - *UVW_BLUR 1.0000 - *UVW_BLUR_OFFSET 0.0000 - *UVW_NOUSE_AMT 1.0000 - *UVW_NOISE_SIZE 1.0000 - *UVW_NOISE_LEVEL 1 - *UVW_NOISE_PHASE 0.0000 - *BITMAP_FILTER Pyramidal - } - } -*/ - -static void ConvertShader( FILE *f, bspShader_t *shader, int shaderNum ) -{ - shaderInfo_t *si; - char *c, filename[ 1024 ]; - - - /* get shader */ - si = ShaderInfoForShader( shader->shader ); - if( si == NULL ) - { - Sys_Printf( "WARNING: NULL shader in BSP\n" ); - return; - } - - /* set bitmap filename */ - if( si->shaderImage->filename[ 0 ] != '*' ) - strcpy( filename, si->shaderImage->filename ); - else - sprintf( filename, "%s.tga", si->shader ); - for( c = filename; *c != '\0'; c++ ) - if( *c == '/' ) - *c = '\\'; - - /* print shader info */ - fprintf( f, "\t*MATERIAL\t%d\t{\r\n", shaderNum ); - fprintf( f, "\t\t*MATERIAL_NAME\t\"%s\"\r\n", shader->shader ); - fprintf( f, "\t\t*MATERIAL_CLASS\t\"Standard\"\r\n" ); - fprintf( f, "\t\t*MATERIAL_DIFFUSE\t%f\t%f\t%f\r\n", si->color[ 0 ], si->color[ 1 ], si->color[ 2 ] ); - fprintf( f, "\t\t*MATERIAL_SHADING Phong\r\n" ); - - /* print map info */ - fprintf( f, "\t\t*MAP_DIFFUSE\t{\r\n" ); - fprintf( f, "\t\t\t*MAP_NAME\t\"%s\"\r\n", shader->shader ); - fprintf( f, "\t\t\t*MAP_CLASS\t\"Bitmap\"\r\n"); - fprintf( f, "\t\t\t*MAP_SUBNO\t1\r\n" ); - fprintf( f, "\t\t\t*MAP_AMOUNT\t1.0\r\n" ); - fprintf( f, "\t\t\t*MAP_TYPE\tScreen\r\n" ); - if(shadersAsBitmap) - fprintf( f, "\t\t\t*BITMAP\t\"%s\"\r\n", shader->shader ); - else - fprintf( f, "\t\t\t*BITMAP\t\"..\\%s\"\r\n", filename ); - fprintf( f, "\t\t\t*BITMAP_FILTER\tPyramidal\r\n" ); - fprintf( f, "\t\t}\r\n" ); - - fprintf( f, "\t}\r\n" ); -} -static void ConvertLightmap( FILE *f, const char *base, int lightmapNum ) -{ - /* print shader info */ - fprintf( f, "\t*MATERIAL\t%d\t{\r\n", lightmapNum ); - fprintf( f, "\t\t*MATERIAL_NAME\t\"lm_%04d\"\r\n", lightmapNum ); - fprintf( f, "\t\t*MATERIAL_CLASS\t\"Standard\"\r\n" ); - fprintf( f, "\t\t*MATERIAL_DIFFUSE\t1\t1\t1\r\n"); - fprintf( f, "\t\t*MATERIAL_SHADING Phong\r\n" ); - - /* print map info */ - if(lightmapNum >= 0) - { - fprintf( f, "\t\t*MAP_DIFFUSE\t{\r\n" ); - fprintf( f, "\t\t\t*MAP_NAME\t\"lm_%04d\"\r\n", lightmapNum ); - fprintf( f, "\t\t\t*MAP_CLASS\t\"Bitmap\"\r\n"); - fprintf( f, "\t\t\t*MAP_SUBNO\t1\r\n" ); - fprintf( f, "\t\t\t*MAP_AMOUNT\t1.0\r\n" ); - fprintf( f, "\t\t\t*MAP_TYPE\tScreen\r\n" ); - fprintf( f, "\t\t\t*BITMAP\t\"%s\\lm_%04d.tga\"\r\n", base, lightmapNum ); - fprintf( f, "\t\t\t*BITMAP_FILTER\tPyramidal\r\n" ); - fprintf( f, "\t\t}\r\n" ); - } - - fprintf( f, "\t}\r\n" ); -} - - - -/* -ConvertBSPToASE() -exports an 3d studio ase file from the bsp -*/ - -int ConvertBSPToASE( char *bspName ) -{ - int i, modelNum; - FILE *f; - bspShader_t *shader; - bspModel_t *model; - entity_t *e; - vec3_t origin; - const char *key; - char name[ 1024 ], base[ 1024 ], dirname[ 1024 ]; - - - /* note it */ - Sys_Printf( "--- Convert BSP to ASE ---\n" ); - - /* create the ase filename from the bsp name */ - strcpy( dirname, bspName ); - StripExtension( dirname ); - strcpy( name, bspName ); - StripExtension( name ); - strcat( name, ".ase" ); - Sys_Printf( "writing %s\n", name ); - - ExtractFileBase( bspName, base ); - - /* open it */ - f = fopen( name, "wb" ); - if( f == NULL ) - Error( "Open failed on %s\n", name ); - - /* print header */ - fprintf( f, "*3DSMAX_ASCIIEXPORT\t200\r\n" ); - fprintf( f, "*COMMENT\t\"Generated by Q3Map2 (ydnar) -convert -format ase\"\r\n" ); - fprintf( f, "*SCENE\t{\r\n" ); - fprintf( f, "\t*SCENE_FILENAME\t\"%s.bsp\"\r\n", base ); - fprintf( f, "\t*SCENE_FIRSTFRAME\t0\r\n" ); - fprintf( f, "\t*SCENE_LASTFRAME\t100\r\n" ); - fprintf( f, "\t*SCENE_FRAMESPEED\t30\r\n" ); - fprintf( f, "\t*SCENE_TICKSPERFRAME\t160\r\n" ); - fprintf( f, "\t*SCENE_BACKGROUND_STATIC\t0.0000\t0.0000\t0.0000\r\n" ); - fprintf( f, "\t*SCENE_AMBIENT_STATIC\t0.0000\t0.0000\t0.0000\r\n" ); - fprintf( f, "}\r\n" ); - - /* print materials */ - fprintf( f, "*MATERIAL_LIST\t{\r\n" ); - if(lightmapsAsTexcoord) - { - int lightmapCount; - for( lightmapCount = 0; lightmapCount < numBSPLightmaps; lightmapCount++ ) - ; - for( ; ; lightmapCount++ ) - { - char buf[1024]; - FILE *tmp; - snprintf(buf, sizeof(buf), "%s/lm_%04d.tga", dirname, lightmapCount); - buf[sizeof(buf) - 1] = 0; - tmp = fopen(buf, "rb"); - if(!tmp) - break; - fclose(tmp); - } - fprintf( f, "\t*MATERIAL_COUNT\t%d\r\n", lightmapCount ); - for( i = 0; i < lightmapCount; i++ ) - ConvertLightmap( f, base, i ); - numLightmapsASE = lightmapCount; - } - else - { - fprintf( f, "\t*MATERIAL_COUNT\t%d\r\n", numBSPShaders ); - for( i = 0; i < numBSPShaders; i++ ) - { - shader = &bspShaders[ i ]; - ConvertShader( f, shader, i ); - } - } - fprintf( f, "}\r\n" ); - - /* walk entity list */ - for( i = 0; i < numEntities; i++ ) - { - /* get entity and model */ - e = &entities[ i ]; - if( i == 0 ) - modelNum = 0; - else - { - key = ValueForKey( e, "model" ); - if( key[ 0 ] != '*' ) - continue; - modelNum = atoi( key + 1 ); - } - model = &bspModels[ modelNum ]; - - /* get entity origin */ - key = ValueForKey( e, "origin" ); - if( key[ 0 ] == '\0' ) - VectorClear( origin ); - else - GetVectorForKey( e, "origin", origin ); - - /* convert model */ - ConvertModel( f, model, modelNum, origin ); - } - - /* close the file and return */ - fclose( f ); - - /* return to sender */ - return 0; -} - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_map.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_map.c deleted file mode 100644 index 0f37665d..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_map.c +++ /dev/null @@ -1,860 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define CONVERT_MAP_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -ConvertBrush() -exports a map brush -*/ - -#define SNAP_FLOAT_TO_INT 4 -#define SNAP_INT_TO_FLOAT (1.0 / SNAP_FLOAT_TO_INT) - -typedef vec_t vec2_t[2]; - -static vec_t Det3x3(vec_t a00, vec_t a01, vec_t a02, - vec_t a10, vec_t a11, vec_t a12, - vec_t a20, vec_t a21, vec_t a22) -{ - return - a00 * (a11 * a22 - a12 * a21) - - a01 * (a10 * a22 - a12 * a20) - + a02 * (a10 * a21 - a11 * a20); -} - -void GetBestSurfaceTriangleMatchForBrushside(side_t *buildSide, bspDrawVert_t *bestVert[3]) -{ - bspDrawSurface_t *s; - int i; - int t; - vec_t best = 0; - vec_t thisarea; - vec3_t normdiff; - vec3_t v1v0, v2v0, norm; - bspDrawVert_t *vert[3]; - winding_t *polygon; - plane_t *buildPlane = &mapplanes[buildSide->planenum]; - int matches = 0; - - // first, start out with NULLs - bestVert[0] = bestVert[1] = bestVert[2] = NULL; - - // brute force through all surfaces - for(s = bspDrawSurfaces; s != bspDrawSurfaces + numBSPDrawSurfaces; ++s) - { - if(s->surfaceType != MST_PLANAR && s->surfaceType != MST_TRIANGLE_SOUP) - continue; - if(strcmp(buildSide->shaderInfo->shader, bspShaders[s->shaderNum].shader)) - continue; - for(t = 0; t + 3 <= s->numIndexes; t += 3) - { - vert[0] = &bspDrawVerts[s->firstVert + bspDrawIndexes[s->firstIndex + t + 0]]; - vert[1] = &bspDrawVerts[s->firstVert + bspDrawIndexes[s->firstIndex + t + 1]]; - vert[2] = &bspDrawVerts[s->firstVert + bspDrawIndexes[s->firstIndex + t + 2]]; - if(s->surfaceType == MST_PLANAR && VectorCompare(vert[0]->normal, vert[1]->normal) && VectorCompare(vert[1]->normal, vert[2]->normal)) - { - VectorSubtract(vert[0]->normal, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; - VectorSubtract(vert[1]->normal, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; - VectorSubtract(vert[2]->normal, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; - } - else - { - // this is more prone to roundoff errors, but with embedded - // models, there is no better way - VectorSubtract(vert[1]->xyz, vert[0]->xyz, v1v0); - VectorSubtract(vert[2]->xyz, vert[0]->xyz, v2v0); - CrossProduct(v2v0, v1v0, norm); - VectorNormalize(norm, norm); - VectorSubtract(norm, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; - } - if(abs(DotProduct(vert[0]->xyz, buildPlane->normal) - buildPlane->dist) >= distanceEpsilon) continue; - if(abs(DotProduct(vert[1]->xyz, buildPlane->normal) - buildPlane->dist) >= distanceEpsilon) continue; - if(abs(DotProduct(vert[2]->xyz, buildPlane->normal) - buildPlane->dist) >= distanceEpsilon) continue; - // Okay. Correct surface type, correct shader, correct plane. Let's start with the business... - polygon = CopyWinding(buildSide->winding); - for(i = 0; i < 3; ++i) - { - // 0: 1, 2 - // 1: 2, 0 - // 2; 0, 1 - vec3_t *v1 = &vert[(i+1)%3]->xyz; - vec3_t *v2 = &vert[(i+2)%3]->xyz; - vec3_t triNormal; - vec_t triDist; - vec3_t sideDirection; - // we now need to generate triNormal and triDist so that they represent the plane spanned by normal and (v2 - v1). - VectorSubtract(*v2, *v1, sideDirection); - CrossProduct(sideDirection, buildPlane->normal, triNormal); - triDist = DotProduct(*v1, triNormal); - ChopWindingInPlace(&polygon, triNormal, triDist, distanceEpsilon); - if(!polygon) - goto exwinding; - } - thisarea = WindingArea(polygon); - if(thisarea > 0) - ++matches; - if(thisarea > best) - { - best = thisarea; - bestVert[0] = vert[0]; - bestVert[1] = vert[1]; - bestVert[2] = vert[2]; - } - FreeWinding(polygon); -exwinding: - ; - } - } - //if(strncmp(buildSide->shaderInfo->shader, "textures/common/", 16)) - // fprintf(stderr, "brushside with %s: %d matches (%f area)\n", buildSide->shaderInfo->shader, matches, best); -} - -#define FRAC(x) ((x) - floor(x)) -static void ConvertOriginBrush( FILE *f, int num, vec3_t origin, qboolean brushPrimitives ) -{ - int originSize = 256; - - char pattern[6][7][3] = { - { "+++", "+-+", "-++", "- ", " + ", " - ", "- " }, - { "+++", "-++", "++-", "- ", " +", "+ ", " +" }, - { "+++", "++-", "+-+", " - ", " +", " - ", " +" }, - { "---", "+--", "-+-", "- ", " + ", " - ", "+ " }, - { "---", "--+", "+--", "- ", " +", "- ", " +" }, - { "---", "-+-", "--+", " - ", " +", " + ", " +" } - }; - int i; -#define S(a,b,c) (pattern[a][b][c] == '+' ? +1 : pattern[a][b][c] == '-' ? -1 : 0) - - /* start brush */ - fprintf( f, "\t// brush %d\n", num ); - fprintf( f, "\t{\n" ); - if(brushPrimitives) - { - fprintf( f, "\tbrushDef\n" ); - fprintf( f, "\t{\n" ); - } - /* print brush side */ - /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ - - for(i = 0; i < 6; ++i) - { - if(brushPrimitives) - { - fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", - origin[0] + 8 * S(i,0,0), origin[1] + 8 * S(i,0,1), origin[2] + 8 * S(i,0,2), - origin[0] + 8 * S(i,1,0), origin[1] + 8 * S(i,1,1), origin[2] + 8 * S(i,1,2), - origin[0] + 8 * S(i,2,0), origin[1] + 8 * S(i,2,1), origin[2] + 8 * S(i,2,2), - 1.0f/16.0f, 0.0f, FRAC((S(i,5,0) * origin[0] + S(i,5,1) * origin[1] + S(i,5,2) * origin[2]) / 16.0 + 0.5), - 0.0f, 1.0f/16.0f, FRAC((S(i,6,0) * origin[0] + S(i,6,1) * origin[1] + S(i,6,2) * origin[2]) / 16.0 + 0.5), - "common/origin", - 0 - ); - } - else - { - fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", - origin[0] + 8 * S(i,0,0), origin[1] + 8 * S(i,0,1), origin[2] + 8 * S(i,0,2), - origin[0] + 8 * S(i,1,0), origin[1] + 8 * S(i,1,1), origin[2] + 8 * S(i,1,2), - origin[0] + 8 * S(i,2,0), origin[1] + 8 * S(i,2,1), origin[2] + 8 * S(i,2,2), - "common/origin", - FRAC((S(i,3,0) * origin[0] + S(i,3,1) * origin[1] + S(i,3,2) * origin[2]) / 16.0 + 0.5) * originSize, - FRAC((S(i,4,0) * origin[0] + S(i,4,1) * origin[1] + S(i,4,2) * origin[2]) / 16.0 + 0.5) * originSize, - 0.0f, 16.0 / originSize, 16.0 / originSize, - 0 - ); - } - } -#undef S - - /* end brush */ - if(brushPrimitives) - fprintf( f, "\t}\n" ); - fprintf( f, "\t}\n\n" ); -} - -static void ConvertBrush( FILE *f, int num, bspBrush_t *brush, vec3_t origin, qboolean brushPrimitives ) -{ - int i, j; - bspBrushSide_t *side; - side_t *buildSide; - bspShader_t *shader; - char *texture; - bspPlane_t *plane; - plane_t *buildPlane; - vec3_t pts[ 3 ]; - bspDrawVert_t *vert[3]; - int valid; - - - /* start brush */ - fprintf( f, "\t// brush %d\n", num ); - fprintf( f, "\t{\n" ); - if(brushPrimitives) - { - fprintf( f, "\tbrushDef\n" ); - fprintf( f, "\t{\n" ); - } - - /* clear out build brush */ - for( i = 0; i < buildBrush->numsides; i++ ) - { - buildSide = &buildBrush->sides[ i ]; - if( buildSide->winding != NULL ) - { - FreeWinding( buildSide->winding ); - buildSide->winding = NULL; - } - } - buildBrush->numsides = 0; - - /* iterate through bsp brush sides */ - for( i = 0; i < brush->numSides; i++ ) - { - /* get side */ - side = &bspBrushSides[ brush->firstSide + i ]; - - /* get shader */ - if( side->shaderNum < 0 || side->shaderNum >= numBSPShaders ) - continue; - shader = &bspShaders[ side->shaderNum ]; - //if( !Q_stricmp( shader->shader, "default" ) || !Q_stricmp( shader->shader, "noshader" ) ) - // continue; - - /* get plane */ - plane = &bspPlanes[ side->planeNum ]; - - /* add build side */ - buildSide = &buildBrush->sides[ buildBrush->numsides ]; - buildBrush->numsides++; - - /* tag it */ - buildSide->shaderInfo = ShaderInfoForShader( shader->shader ); - buildSide->planenum = side->planeNum; - buildSide->winding = NULL; - } - - /* make brush windings */ - if( !CreateBrushWindings( buildBrush ) ) - { - Sys_Printf( "CreateBrushWindings failed\n" ); - return; - } - - /* iterate through build brush sides */ - for( i = 0; i < buildBrush->numsides; i++ ) - { - /* get build side */ - buildSide = &buildBrush->sides[ i ]; - - /* get plane */ - buildPlane = &mapplanes[ buildSide->planenum ]; - - /* dummy check */ - if( buildSide->shaderInfo == NULL || buildSide->winding == NULL ) - continue; - - // st-texcoords -> texMat block - // start out with dummy - VectorSet(buildSide->texMat[0], 1/32.0, 0, 0); - VectorSet(buildSide->texMat[1], 0, 1/32.0, 0); - - // find surface for this side (by brute force) - // surface format: - // - meshverts point in pairs of three into verts - // - (triangles) - // - find the triangle that has most in common with our side - GetBestSurfaceTriangleMatchForBrushside(buildSide, vert); - valid = 0; - - /* get texture name */ - if( !Q_strncasecmp( buildSide->shaderInfo->shader, "textures/", 9 ) ) - texture = buildSide->shaderInfo->shader + 9; - else - texture = buildSide->shaderInfo->shader; - - /* get plane points and offset by origin */ - for( j = 0; j < 3; j++ ) - { - VectorAdd( buildSide->winding->p[ j ], origin, pts[ j ] ); - //% pts[ j ][ 0 ] = SNAP_INT_TO_FLOAT * floor( pts[ j ][ 0 ] * SNAP_FLOAT_TO_INT + 0.5f ); - //% pts[ j ][ 1 ] = SNAP_INT_TO_FLOAT * floor( pts[ j ][ 1 ] * SNAP_FLOAT_TO_INT + 0.5f ); - //% pts[ j ][ 2 ] = SNAP_INT_TO_FLOAT * floor( pts[ j ][ 2 ] * SNAP_FLOAT_TO_INT + 0.5f ); - } - - if(vert[0] && vert[1] && vert[2]) - { - if(brushPrimitives) - { - int i; - vec3_t texX, texY; - vec2_t xyI, xyJ, xyK; - vec2_t stI, stJ, stK; - vec_t D, D0, D1, D2; - - ComputeAxisBase(buildPlane->normal, texX, texY); - - xyI[0] = DotProduct(vert[0]->xyz, texX); - xyI[1] = DotProduct(vert[0]->xyz, texY); - xyJ[0] = DotProduct(vert[1]->xyz, texX); - xyJ[1] = DotProduct(vert[1]->xyz, texY); - xyK[0] = DotProduct(vert[2]->xyz, texX); - xyK[1] = DotProduct(vert[2]->xyz, texY); - stI[0] = vert[0]->st[0]; stI[1] = vert[0]->st[1]; - stJ[0] = vert[1]->st[0]; stJ[1] = vert[1]->st[1]; - stK[0] = vert[2]->st[0]; stK[1] = vert[2]->st[1]; - - // - solve linear equations: - // - (x, y) := xyz . (texX, texY) - // - st[i] = texMat[i][0]*x + texMat[i][1]*y + texMat[i][2] - // (for three vertices) - D = Det3x3( - xyI[0], xyI[1], 1, - xyJ[0], xyJ[1], 1, - xyK[0], xyK[1], 1 - ); - if(D != 0) - { - for(i = 0; i < 2; ++i) - { - D0 = Det3x3( - stI[i], xyI[1], 1, - stJ[i], xyJ[1], 1, - stK[i], xyK[1], 1 - ); - D1 = Det3x3( - xyI[0], stI[i], 1, - xyJ[0], stJ[i], 1, - xyK[0], stK[i], 1 - ); - D2 = Det3x3( - xyI[0], xyI[1], stI[i], - xyJ[0], xyJ[1], stJ[i], - xyK[0], xyK[1], stK[i] - ); - VectorSet(buildSide->texMat[i], D0 / D, D1 / D, D2 / D); - } - valid = 1; - } - else - fprintf(stderr, "degenerate triangle found when solving texMat equations for\n(%f %f %f) (%f %f %f) (%f %f %f)\n( %f %f %f )\n( %f %f %f ) -> ( %f %f )\n( %f %f %f ) -> ( %f %f )\n( %f %f %f ) -> ( %f %f )\n", - buildPlane->normal[0], buildPlane->normal[1], buildPlane->normal[2], - vert[0]->normal[0], vert[0]->normal[1], vert[0]->normal[2], - texX[0], texX[1], texX[2], texY[0], texY[1], texY[2], - vert[0]->xyz[0], vert[0]->xyz[1], vert[0]->xyz[2], xyI[0], xyI[1], - vert[1]->xyz[0], vert[1]->xyz[1], vert[1]->xyz[2], xyJ[0], xyJ[1], - vert[2]->xyz[0], vert[2]->xyz[1], vert[2]->xyz[2], xyK[0], xyK[1] - ); - - /* print brush side */ - /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ - fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - buildSide->texMat[0][0], buildSide->texMat[0][1], FRAC(buildSide->texMat[0][2]), - buildSide->texMat[1][0], buildSide->texMat[1][1], FRAC(buildSide->texMat[1][2]), - texture, - // DEBUG: valid ? 0 : C_DETAIL - 0 - ); - } - else - { - // invert QuakeTextureVecs - int i; - vec3_t vecs[2]; - int sv, tv; - vec2_t stI, stJ, stK; - vec3_t sts[2]; - vec2_t shift, scale; - vec_t rotate; - vec_t D, D0, D1, D2; - - TextureAxisFromPlane(buildPlane, vecs[0], vecs[1]); - if (vecs[0][0]) - sv = 0; - else if (vecs[0][1]) - sv = 1; - else - sv = 2; - if (vecs[1][0]) - tv = 0; - else if (vecs[1][1]) - tv = 1; - else - tv = 2; - - stI[0] = vert[0]->st[0] * buildSide->shaderInfo->shaderWidth; stI[1] = vert[0]->st[1] * buildSide->shaderInfo->shaderHeight; - stJ[0] = vert[1]->st[0] * buildSide->shaderInfo->shaderWidth; stJ[1] = vert[1]->st[1] * buildSide->shaderInfo->shaderHeight; - stK[0] = vert[2]->st[0] * buildSide->shaderInfo->shaderWidth; stK[1] = vert[2]->st[1] * buildSide->shaderInfo->shaderHeight; - - D = Det3x3( - vert[0]->xyz[sv], vert[0]->xyz[tv], 1, - vert[1]->xyz[sv], vert[1]->xyz[tv], 1, - vert[2]->xyz[sv], vert[2]->xyz[tv], 1 - ); - if(D != 0) - { - for(i = 0; i < 2; ++i) - { - D0 = Det3x3( - stI[i], vert[0]->xyz[tv], 1, - stJ[i], vert[1]->xyz[tv], 1, - stK[i], vert[2]->xyz[tv], 1 - ); - D1 = Det3x3( - vert[0]->xyz[sv], stI[i], 1, - vert[1]->xyz[sv], stJ[i], 1, - vert[2]->xyz[sv], stK[i], 1 - ); - D2 = Det3x3( - vert[0]->xyz[sv], vert[0]->xyz[tv], stI[i], - vert[1]->xyz[sv], vert[1]->xyz[tv], stJ[i], - vert[2]->xyz[sv], vert[2]->xyz[tv], stK[i] - ); - VectorSet(sts[i], D0 / D, D1 / D, D2 / D); - } - valid = 1; - } - else - fprintf(stderr, "degenerate triangle found when solving texDef equations\n"); // FIXME add stuff here - - // now we must solve: - // // now we must invert: - // ang = rotate / 180 * Q_PI; - // sinv = sin(ang); - // cosv = cos(ang); - // ns = cosv * vecs[0][sv]; - // nt = sinv * vecs[0][sv]; - // vecsrotscaled[0][sv] = ns / scale[0]; - // vecsrotscaled[0][tv] = nt / scale[0]; - // ns = -sinv * vecs[1][tv]; - // nt = cosv * vecs[1][tv]; - // vecsrotscaled[1][sv] = ns / scale[1]; - // vecsrotscaled[1][tv] = nt / scale[1]; - scale[0] = 1.0/sqrt(sts[0][0] * sts[0][0] + sts[0][1] * sts[0][1]); - scale[1] = 1.0/sqrt(sts[1][0] * sts[1][0] + sts[1][1] * sts[1][1]); - rotate = atan2(sts[0][1] * vecs[0][sv] - sts[1][0] * vecs[1][tv], sts[0][0] * vecs[0][sv] + sts[1][1] * vecs[1][tv]) * (180.0f / Q_PI); - shift[0] = buildSide->shaderInfo->shaderWidth * FRAC(sts[0][2] / buildSide->shaderInfo->shaderWidth); - shift[1] = buildSide->shaderInfo->shaderHeight * FRAC(sts[1][2] / buildSide->shaderInfo->shaderHeight); - - /* print brush side */ - /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ - fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - texture, - shift[0], shift[1], rotate, scale[0], scale[1], - // DEBUG: valid ? 0 : C_DETAIL - 0 - ); - } - } - else - { - vec3_t vecs[ 2 ]; - if(strncmp(buildSide->shaderInfo->shader, "textures/common/", 16)) - if(strcmp(buildSide->shaderInfo->shader, "noshader")) - if(strcmp(buildSide->shaderInfo->shader, "default")) - { - fprintf(stderr, "no matching triangle for brushside using %s (hopefully nobody can see this side anyway)\n", buildSide->shaderInfo->shader); - texture = "common/WTF"; - } - - MakeNormalVectors( buildPlane->normal, vecs[ 0 ], vecs[ 1 ] ); - VectorMA( vec3_origin, buildPlane->dist, buildPlane->normal, pts[ 0 ] ); - VectorMA( pts[ 0 ], 256.0f, vecs[ 0 ], pts[ 1 ] ); - VectorMA( pts[ 0 ], 256.0f, vecs[ 1 ], pts[ 2 ] ); - if(brushPrimitives) - { - fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - 1.0f/16.0f, 0.0f, 0.0f, - 0.0f, 1.0f/16.0f, 0.0f, - texture, - // DEBUG: valid ? 0 : C_DETAIL - 0 - ); - } - else - { - fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - texture, - 0.0f, 0.0f, 0.0f, 0.25f, 0.25f, - // DEBUG: valid ? 0 : C_DETAIL - 0 - ); - } - } - } - - /* end brush */ - if(brushPrimitives) - { - fprintf( f, "\t}\n" ); - } - fprintf( f, "\t}\n\n" ); -} -#undef FRAC - -#if 0 - /* iterate through the brush sides (ignore the first 6 bevel planes) */ - for( i = 0; i < brush->numSides; i++ ) - { - /* get side */ - side = &bspBrushSides[ brush->firstSide + i ]; - - /* get shader */ - if( side->shaderNum < 0 || side->shaderNum >= numBSPShaders ) - continue; - shader = &bspShaders[ side->shaderNum ]; - if( !Q_stricmp( shader->shader, "default" ) || !Q_stricmp( shader->shader, "noshader" ) ) - continue; - - /* get texture name */ - if( !Q_strncasecmp( shader->shader, "textures/", 9 ) ) - texture = shader->shader + 9; - else - texture = shader->shader; - - /* get plane */ - plane = &bspPlanes[ side->planeNum ]; - - /* make plane points */ - { - vec3_t vecs[ 2 ]; - - - MakeNormalVectors( plane->normal, vecs[ 0 ], vecs[ 1 ] ); - VectorMA( vec3_origin, plane->dist, plane->normal, pts[ 0 ] ); - VectorMA( pts[ 0 ], 256.0f, vecs[ 0 ], pts[ 1 ] ); - VectorMA( pts[ 0 ], 256.0f, vecs[ 1 ], pts[ 2 ] ); - } - - /* offset by origin */ - for( j = 0; j < 3; j++ ) - VectorAdd( pts[ j ], origin, pts[ j ] ); - - /* print brush side */ - /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ - fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s 0 0 0 0.5 0.5 0 0 0\n", - pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], - pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], - pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], - texture ); - } -#endif - - - -/* -ConvertPatch() -converts a bsp patch to a map patch - - { - patchDef2 - { - base_wall/concrete - ( 9 3 0 0 0 ) - ( - ( ( 168 168 -192 0 2 ) ( 168 168 -64 0 1 ) ( 168 168 64 0 0 ) ... ) - ... - ) - } - } - -*/ - -static void ConvertPatch( FILE *f, int num, bspDrawSurface_t *ds, vec3_t origin ) -{ - int x, y; - bspShader_t *shader; - char *texture; - bspDrawVert_t *dv; - vec3_t xyz; - - - /* only patches */ - if( ds->surfaceType != MST_PATCH ) - return; - - /* get shader */ - if( ds->shaderNum < 0 || ds->shaderNum >= numBSPShaders ) - return; - shader = &bspShaders[ ds->shaderNum ]; - - /* get texture name */ - if( !Q_strncasecmp( shader->shader, "textures/", 9 ) ) - texture = shader->shader + 9; - else - texture = shader->shader; - - /* start patch */ - fprintf( f, "\t// patch %d\n", num ); - fprintf( f, "\t{\n" ); - fprintf( f, "\t\tpatchDef2\n" ); - fprintf( f, "\t\t{\n" ); - fprintf( f, "\t\t\t%s\n", texture ); - fprintf( f, "\t\t\t( %d %d 0 0 0 )\n", ds->patchWidth, ds->patchHeight ); - fprintf( f, "\t\t\t(\n" ); - - /* iterate through the verts */ - for( x = 0; x < ds->patchWidth; x++ ) - { - /* start row */ - fprintf( f, "\t\t\t\t(" ); - - /* iterate through the row */ - for( y = 0; y < ds->patchHeight; y++ ) - { - /* get vert */ - dv = &bspDrawVerts[ ds->firstVert + (y * ds->patchWidth) + x ]; - - /* offset it */ - VectorAdd( origin, dv->xyz, xyz ); - - /* print vertex */ - fprintf( f, " ( %f %f %f %f %f )", xyz[ 0 ], xyz[ 1 ], xyz[ 2 ], dv->st[ 0 ], dv->st[ 1 ] ); - } - - /* end row */ - fprintf( f, " )\n" ); - } - - /* end patch */ - fprintf( f, "\t\t\t)\n" ); - fprintf( f, "\t\t}\n" ); - fprintf( f, "\t}\n\n" ); -} - - - -/* -ConvertModel() -exports a bsp model to a map file -*/ - -static void ConvertModel( FILE *f, bspModel_t *model, int modelNum, vec3_t origin, qboolean brushPrimitives ) -{ - int i, num; - bspBrush_t *brush; - bspDrawSurface_t *ds; - - - /* convert bsp planes to map planes */ - nummapplanes = numBSPPlanes; - AUTOEXPAND_BY_REALLOC(mapplanes, nummapplanes, allocatedmapplanes, 1024); - for( i = 0; i < numBSPPlanes; i++ ) - { - VectorCopy( bspPlanes[ i ].normal, mapplanes[ i ].normal ); - mapplanes[ i ].dist = bspPlanes[ i ].dist; - mapplanes[ i ].type = PlaneTypeForNormal( mapplanes[ i ].normal ); - mapplanes[ i ].hash_chain = 0; - } - - /* allocate a build brush */ - buildBrush = AllocBrush( 512 ); - buildBrush->entityNum = 0; - buildBrush->original = buildBrush; - - if(origin[0] != 0 || origin[1] != 0 || origin[2] != 0) - ConvertOriginBrush(f, -1, origin, brushPrimitives); - - /* go through each brush in the model */ - for( i = 0; i < model->numBSPBrushes; i++ ) - { - num = i + model->firstBSPBrush; - brush = &bspBrushes[ num ]; - ConvertBrush( f, num, brush, origin, brushPrimitives ); - } - - /* free the build brush */ - free( buildBrush ); - - /* go through each drawsurf in the model */ - for( i = 0; i < model->numBSPSurfaces; i++ ) - { - num = i + model->firstBSPSurface; - ds = &bspDrawSurfaces[ num ]; - - /* we only love patches */ - if( ds->surfaceType == MST_PATCH ) - ConvertPatch( f, num, ds, origin ); - } -} - - - -/* -ConvertEPairs() -exports entity key/value pairs to a map file -*/ - -static void ConvertEPairs( FILE *f, entity_t *e, qboolean skip_origin ) -{ - epair_t *ep; - - - /* walk epairs */ - for( ep = e->epairs; ep != NULL; ep = ep->next ) - { - /* ignore empty keys/values */ - if( ep->key[ 0 ] == '\0' || ep->value[ 0 ] == '\0' ) - continue; - - /* ignore model keys with * prefixed values */ - if( !Q_stricmp( ep->key, "model" ) && ep->value[ 0 ] == '*' ) - continue; - - /* ignore origin keys if skip_origin is set */ - if( skip_origin && !Q_stricmp( ep->key, "origin" ) ) - continue; - - /* emit the epair */ - fprintf( f, "\t\"%s\" \"%s\"\n", ep->key, ep->value ); - } -} - - - -/* -ConvertBSPToMap() -exports an quake map file from the bsp -*/ - -int ConvertBSPToMap_Ext( char *bspName, qboolean brushPrimitives ) -{ - int i, modelNum; - FILE *f; - bspModel_t *model; - entity_t *e; - vec3_t origin; - const char *value; - char name[ 1024 ], base[ 1024 ]; - - - /* note it */ - Sys_Printf( "--- Convert BSP to MAP ---\n" ); - - /* create the bsp filename from the bsp name */ - strcpy( name, bspName ); - StripExtension( name ); - strcat( name, "_converted.map" ); - Sys_Printf( "writing %s\n", name ); - - ExtractFileBase( bspName, base ); - strcat( base, ".bsp" ); - - /* open it */ - f = fopen( name, "wb" ); - if( f == NULL ) - Error( "Open failed on %s\n", name ); - - /* print header */ - fprintf( f, "// Generated by Q3Map2 (ydnar) -convert -format map\n" ); - - /* walk entity list */ - for( i = 0; i < numEntities; i++ ) - { - /* get entity */ - e = &entities[ i ]; - - /* start entity */ - fprintf( f, "// entity %d\n", i ); - fprintf( f, "{\n" ); - - /* get model num */ - if( i == 0 ) - modelNum = 0; - else - { - value = ValueForKey( e, "model" ); - if( value[ 0 ] == '*' ) - modelNum = atoi( value + 1 ); - else - modelNum = -1; - } - - /* export keys */ - ConvertEPairs( f, e, modelNum >= 0 ); - fprintf( f, "\n" ); - - /* only handle bsp models */ - if( modelNum >= 0 ) - { - /* get model */ - model = &bspModels[ modelNum ]; - - /* get entity origin */ - value = ValueForKey( e, "origin" ); - if( value[ 0 ] == '\0' ) - VectorClear( origin ); - else - GetVectorForKey( e, "origin", origin ); - - /* convert model */ - ConvertModel( f, model, modelNum, origin, brushPrimitives ); - } - - /* end entity */ - fprintf( f, "}\n\n" ); - } - - /* close the file and return */ - fclose( f ); - - /* return to sender */ - return 0; -} - -int ConvertBSPToMap( char *bspName ) -{ - return ConvertBSPToMap_Ext(bspName, qfalse); -} - -int ConvertBSPToMap_BP( char *bspName ) -{ - return ConvertBSPToMap_Ext(bspName, qtrue); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_obj.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_obj.c deleted file mode 100644 index 08e75e11..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/convert_obj.c +++ /dev/null @@ -1,328 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define CONVERT_ASE_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -ConvertSurface() -converts a bsp drawsurface to an obj chunk -*/ - -int firstLightmap = 0; -int lastLightmap = -1; -static void ConvertLightmapToMTL( FILE *f, const char *base, int lightmapNum ); - -int objVertexCount = 0; -int objLastShaderNum = -1; -static void ConvertSurfaceToOBJ( FILE *f, bspModel_t *model, int modelNum, bspDrawSurface_t *ds, int surfaceNum, vec3_t origin ) -{ - int i, v, face, a, b, c; - bspDrawVert_t *dv; - - /* ignore patches for now */ - if( ds->surfaceType != MST_PLANAR && ds->surfaceType != MST_TRIANGLE_SOUP ) - return; - - fprintf(f, "g mat%dmodel%dsurf%d\r\n", ds->shaderNum, modelNum, surfaceNum); - switch( ds->surfaceType ) - { - case MST_PLANAR: - fprintf( f, "# SURFACETYPE MST_PLANAR\r\n" ); - break; - case MST_TRIANGLE_SOUP: - fprintf( f, "# SURFACETYPE MST_TRIANGLE_SOUP\r\n" ); - break; - } - - /* export shader */ - if(lightmapsAsTexcoord) - { - if(objLastShaderNum != ds->lightmapNum[0]) - { - fprintf(f, "usemtl lm_%04d\r\n", ds->lightmapNum[0] + deluxemap); - objLastShaderNum = ds->lightmapNum[0] + deluxemap; - } - if(ds->lightmapNum[0] + deluxemap < firstLightmap) - { - Sys_Printf( "WARNING: lightmap %d out of range (exporting anyway)\n", ds->lightmapNum[0] + deluxemap ); - firstLightmap = ds->lightmapNum[0] + deluxemap; - } - if(ds->lightmapNum[0] > lastLightmap) - { - Sys_Printf( "WARNING: lightmap %d out of range (exporting anyway)\n", ds->lightmapNum[0] + deluxemap ); - lastLightmap = ds->lightmapNum[0] + deluxemap; - } - } - else - { - if(objLastShaderNum != ds->shaderNum) - { - fprintf(f, "usemtl %s\r\n", bspShaders[ds->shaderNum].shader); - objLastShaderNum = ds->shaderNum; - } - } - - /* export vertex */ - for( i = 0; i < ds->numVerts; i++ ) - { - v = i + ds->firstVert; - dv = &bspDrawVerts[ v ]; - fprintf(f, "# vertex %d\r\n", i + objVertexCount + 1); - fprintf(f, "v %f %f %f\r\n", dv->xyz[ 0 ], dv->xyz[ 1 ], dv->xyz[ 2 ]); - fprintf(f, "vn %f %f %f\r\n", dv->normal[ 0 ], dv->normal[ 1 ], dv->normal[ 2 ]); - if(lightmapsAsTexcoord) - fprintf(f, "vt %f %f\r\n", dv->lightmap[0][0], 1.0 - dv->lightmap[0][1]); - else - fprintf(f, "vt %f %f\r\n", dv->st[ 0 ], 1.0 - dv->st[ 1 ]); - } - - /* export faces */ - for( i = 0; i < ds->numIndexes; i += 3 ) - { - face = (i / 3); - a = bspDrawIndexes[ i + ds->firstIndex ]; - c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; - b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; - fprintf(f, "f %d/%d/%d %d/%d/%d %d/%d/%d\r\n", - a + objVertexCount + 1, a + objVertexCount + 1, a + objVertexCount + 1, - b + objVertexCount + 1, b + objVertexCount + 1, b + objVertexCount + 1, - c + objVertexCount + 1, c + objVertexCount + 1, c + objVertexCount + 1 - ); - } - - objVertexCount += ds->numVerts; -} - - - -/* -ConvertModel() -exports a bsp model to an ase chunk -*/ - -static void ConvertModelToOBJ( FILE *f, bspModel_t *model, int modelNum, vec3_t origin ) -{ - int i, s; - bspDrawSurface_t *ds; - - - /* go through each drawsurf in the model */ - for( i = 0; i < model->numBSPSurfaces; i++ ) - { - s = i + model->firstBSPSurface; - ds = &bspDrawSurfaces[ s ]; - ConvertSurfaceToOBJ( f, model, modelNum, ds, s, origin ); - } -} - - - -/* -ConvertShader() -exports a bsp shader to an ase chunk -*/ - -static void ConvertShaderToMTL( FILE *f, bspShader_t *shader, int shaderNum ) -{ - shaderInfo_t *si; - char *c, filename[ 1024 ]; - - - /* get shader */ - si = ShaderInfoForShader( shader->shader ); - if( si == NULL ) - { - Sys_Printf( "WARNING: NULL shader in BSP\n" ); - return; - } - - /* set bitmap filename */ - if( si->shaderImage->filename[ 0 ] != '*' ) - strcpy( filename, si->shaderImage->filename ); - else - sprintf( filename, "%s.tga", si->shader ); - - /* blender hates this, so let's not do it - for( c = filename; *c != '\0'; c++ ) - if( *c == '/' ) - *c = '\\'; - */ - - /* print shader info */ - fprintf( f, "newmtl %s\r\n", shader->shader ); - fprintf( f, "Kd %f %f %f\r\n", si->color[ 0 ], si->color[ 1 ], si->color[ 2 ] ); - if(shadersAsBitmap) - fprintf( f, "map_Kd %s\r\n", shader->shader ); - else - /* blender hates this, so let's not do it - fprintf( f, "map_Kd ..\\%s\r\n", filename ); - */ - fprintf( f, "map_Kd ../%s\r\n", filename ); -} - -static void ConvertLightmapToMTL( FILE *f, const char *base, int lightmapNum ) -{ - /* print shader info */ - fprintf( f, "newmtl lm_%04d\r\n", lightmapNum ); - if(lightmapNum >= 0) - /* blender hates this, so let's not do it - fprintf( f, "map_Kd %s\\lm_%04d.tga\r\n", base, lightmapNum ); - */ - fprintf( f, "map_Kd %s/lm_%04d.tga\r\n", base, lightmapNum ); -} - - - -/* -ConvertBSPToASE() -exports an 3d studio ase file from the bsp -*/ - -int ConvertBSPToOBJ( char *bspName ) -{ - int i, modelNum; - FILE *f, *fmtl; - bspShader_t *shader; - bspModel_t *model; - entity_t *e; - vec3_t origin; - const char *key; - char name[ 1024 ], base[ 1024 ], mtlname[ 1024 ], dirname[ 1024 ]; - - - /* note it */ - Sys_Printf( "--- Convert BSP to OBJ ---\n" ); - - /* create the ase filename from the bsp name */ - strcpy( dirname, bspName ); - StripExtension( dirname ); - strcpy( name, bspName ); - StripExtension( name ); - strcat( name, ".obj" ); - Sys_Printf( "writing %s\n", name ); - strcpy( mtlname, bspName ); - StripExtension( mtlname ); - strcat( mtlname, ".mtl" ); - Sys_Printf( "writing %s\n", mtlname ); - - ExtractFileBase( bspName, base ); - - /* open it */ - f = fopen( name, "wb" ); - if( f == NULL ) - Error( "Open failed on %s\n", name ); - fmtl = fopen( mtlname, "wb" ); - if( fmtl == NULL ) - Error( "Open failed on %s\n", mtlname ); - - /* print header */ - fprintf( f, "o %s\r\n", base ); - fprintf( f, "# Generated by Q3Map2 (ydnar) -convert -format obj\r\n" ); - fprintf( f, "mtllib %s.mtl\r\n", base ); - - fprintf( fmtl, "# Generated by Q3Map2 (ydnar) -convert -format obj\r\n" ); - if(lightmapsAsTexcoord) - { - int lightmapCount; - for( lightmapCount = 0; lightmapCount < numBSPLightmaps; lightmapCount++ ) - ; - for( ; ; lightmapCount++ ) - { - char buf[1024]; - FILE *tmp; - snprintf(buf, sizeof(buf), "%s/lm_%04d.tga", dirname, lightmapCount); - buf[sizeof(buf) - 1] = 0; - tmp = fopen(buf, "rb"); - if(!tmp) - break; - fclose(tmp); - } - lastLightmap = lightmapCount - 1; - } - else - { - for( i = 0; i < numBSPShaders; i++ ) - { - shader = &bspShaders[ i ]; - ConvertShaderToMTL( fmtl, shader, i ); - } - } - - /* walk entity list */ - for( i = 0; i < numEntities; i++ ) - { - /* get entity and model */ - e = &entities[ i ]; - if( i == 0 ) - modelNum = 0; - else - { - key = ValueForKey( e, "model" ); - if( key[ 0 ] != '*' ) - continue; - modelNum = atoi( key + 1 ); - } - model = &bspModels[ modelNum ]; - - /* get entity origin */ - key = ValueForKey( e, "origin" ); - if( key[ 0 ] == '\0' ) - VectorClear( origin ); - else - GetVectorForKey( e, "origin", origin ); - - /* convert model */ - ConvertModelToOBJ( f, model, modelNum, origin ); - } - - if(lightmapsAsTexcoord) - { - for( i = firstLightmap; i <= lastLightmap; i++ ) - ConvertLightmapToMTL( fmtl, base, i ); - } - - /* close the file and return */ - fclose( f ); - fclose( fmtl ); - - /* return to sender */ - return 0; -} - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/decals.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/decals.c deleted file mode 100644 index a130334f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/decals.c +++ /dev/null @@ -1,906 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define DECALS_C - - - -/* dependencies */ -#include "q3map2.h" - - - -#define MAX_PROJECTORS 1024 - -typedef struct decalProjector_s -{ - shaderInfo_t *si; - vec3_t mins, maxs; - vec3_t center; - float radius, radius2; - int numPlanes; /* either 5 or 6, for quad or triangle projectors */ - vec4_t planes[ 6 ]; - vec4_t texMat[ 2 ]; -} -decalProjector_t; - -static int numProjectors = 0; -static decalProjector_t projectors[ MAX_PROJECTORS ]; - -static int numDecalSurfaces = 0; - -static vec3_t entityOrigin; - - - -/* -DVectorNormalize() -normalizes a vector, returns the length, operates using doubles -*/ - -typedef double dvec_t; -typedef dvec_t dvec3_t[ 3 ]; - -dvec_t DVectorNormalize( dvec3_t in, dvec3_t out ) -{ - dvec_t len, ilen; - - - len = (dvec_t) sqrt( in[ 0 ] * in[ 0 ] + in[ 1 ] * in[ 1 ] + in[ 2 ] * in[ 2 ] ); - if( len == 0.0 ) - { - VectorClear( out ); - return 0.0; - } - - ilen = 1.0 / len; - out[ 0 ] = in[ 0 ] * ilen; - out[ 1 ] = in[ 1 ] * ilen; - out[ 2 ] = in[ 2 ] * ilen; - - return len; -} - - - -/* -MakeTextureMatrix() -generates a texture projection matrix for a triangle -returns qfalse if a texture matrix cannot be created -*/ - -#define Vector2Subtract(a,b,c) ((c)[ 0 ] = (a)[ 0 ] - (b)[ 0 ], (c)[ 1 ] = (a)[ 1 ] - (b)[ 1 ]) - -static qboolean MakeTextureMatrix( decalProjector_t *dp, vec4_t projection, bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *c ) -{ - int i, j; - double bb, s, t, d; - dvec3_t pa, pb, pc; - dvec3_t bary, xyz; - dvec3_t vecs[ 3 ], axis[ 3 ], lengths; - - - /* project triangle onto plane of projection */ - d = DotProduct( a->xyz, projection ) - projection[ 3 ]; - VectorMA( a->xyz, -d, projection, pa ); - d = DotProduct( b->xyz, projection ) - projection[ 3 ]; - VectorMA( b->xyz, -d, projection, pb ); - d = DotProduct( c->xyz, projection ) - projection[ 3 ]; - VectorMA( c->xyz, -d, projection, pc ); - - /* two methods */ - #if 1 - { - /* old code */ - - /* calculate barycentric basis for the triangle */ - bb = (b->st[ 0 ] - a->st[ 0 ]) * (c->st[ 1 ] - a->st[ 1 ]) - (c->st[ 0 ] - a->st[ 0 ]) * (b->st[ 1 ] - a->st[ 1 ]); - if( fabs( bb ) < 0.00000001 ) - return qfalse; - - /* calculate texture origin */ - #if 0 - s = 0.0; - t = 0.0; - bary[ 0 ] = ((b->st[ 0 ] - s) * (c->st[ 1 ] - t) - (c->st[ 0 ] - s) * (b->st[ 1 ] - t)) / bb; - bary[ 1 ] = ((c->st[ 0 ] - s) * (a->st[ 1 ] - t) - (a->st[ 0 ] - s) * (c->st[ 1 ] - t)) / bb; - bary[ 2 ] = ((a->st[ 0 ] - s) * (b->st[ 1 ] - t) - (b->st[ 0 ] - s) * (a->st[ 1 ] - t)) / bb; - - origin[ 0 ] = bary[ 0 ] * pa[ 0 ] + bary[ 1 ] * pb[ 0 ] + bary[ 2 ] * pc[ 0 ]; - origin[ 1 ] = bary[ 0 ] * pa[ 1 ] + bary[ 1 ] * pb[ 1 ] + bary[ 2 ] * pc[ 1 ]; - origin[ 2 ] = bary[ 0 ] * pa[ 2 ] + bary[ 1 ] * pb[ 2 ] + bary[ 2 ] * pc[ 2 ]; - #endif - - /* calculate s vector */ - s = a->st[ 0 ] + 1.0; - t = a->st[ 1 ] + 0.0; - bary[ 0 ] = ((b->st[ 0 ] - s) * (c->st[ 1 ] - t) - (c->st[ 0 ] - s) * (b->st[ 1 ] - t)) / bb; - bary[ 1 ] = ((c->st[ 0 ] - s) * (a->st[ 1 ] - t) - (a->st[ 0 ] - s) * (c->st[ 1 ] - t)) / bb; - bary[ 2 ] = ((a->st[ 0 ] - s) * (b->st[ 1 ] - t) - (b->st[ 0 ] - s) * (a->st[ 1 ] - t)) / bb; - - xyz[ 0 ] = bary[ 0 ] * pa[ 0 ] + bary[ 1 ] * pb[ 0 ] + bary[ 2 ] * pc[ 0 ]; - xyz[ 1 ] = bary[ 0 ] * pa[ 1 ] + bary[ 1 ] * pb[ 1 ] + bary[ 2 ] * pc[ 1 ]; - xyz[ 2 ] = bary[ 0 ] * pa[ 2 ] + bary[ 1 ] * pb[ 2 ] + bary[ 2 ] * pc[ 2 ]; - - //% VectorSubtract( xyz, origin, vecs[ 0 ] ); - VectorSubtract( xyz, pa, vecs[ 0 ] ); - - /* calculate t vector */ - s = a->st[ 0 ] + 0.0; - t = a->st[ 1 ] + 1.0; - bary[ 0 ] = ((b->st[ 0 ] - s) * (c->st[ 1 ] - t) - (c->st[ 0 ] - s) * (b->st[ 1 ] - t)) / bb; - bary[ 1 ] = ((c->st[ 0 ] - s) * (a->st[ 1 ] - t) - (a->st[ 0 ] - s) * (c->st[ 1 ] - t)) / bb; - bary[ 2 ] = ((a->st[ 0 ] - s) * (b->st[ 1 ] - t) - (b->st[ 0 ] - s) * (a->st[ 1 ] - t)) / bb; - - xyz[ 0 ] = bary[ 0 ] * pa[ 0 ] + bary[ 1 ] * pb[ 0 ] + bary[ 2 ] * pc[ 0 ]; - xyz[ 1 ] = bary[ 0 ] * pa[ 1 ] + bary[ 1 ] * pb[ 1 ] + bary[ 2 ] * pc[ 1 ]; - xyz[ 2 ] = bary[ 0 ] * pa[ 2 ] + bary[ 1 ] * pb[ 2 ] + bary[ 2 ] * pc[ 2 ]; - - //% VectorSubtract( xyz, origin, vecs[ 1 ] ); - VectorSubtract( xyz, pa, vecs[ 1 ] ); - - /* calcuate r vector */ - VectorScale( projection, -1.0, vecs[ 2 ] ); - - /* calculate transform axis */ - for( i = 0; i < 3; i++ ) - lengths[ i ] = DVectorNormalize( vecs[ i ], axis[ i ] ); - for( i = 0; i < 2; i++ ) - for( j = 0; j < 3; j++ ) - dp->texMat[ i ][ j ] = lengths[ i ] > 0.0 ? (axis[ i ][ j ] / lengths[ i ]) : 0.0; - //% dp->texMat[ i ][ j ] = fabs( vecs[ i ][ j ] ) > 0.0 ? (1.0 / vecs[ i ][ j ]) : 0.0; - //% dp->texMat[ i ][ j ] = axis[ i ][ j ] > 0.0 ? (1.0 / axis[ i ][ j ]) : 0.0; - - /* calculalate translation component */ - dp->texMat[ 0 ][ 3 ] = a->st[ 0 ] - DotProduct( a->xyz, dp->texMat[ 0 ] ); - dp->texMat[ 1 ][ 3 ] = a->st[ 1 ] - DotProduct( a->xyz, dp->texMat[ 1 ] ); - } - #else - { - int k; - dvec3_t origin, deltas[ 3 ]; - double texDeltas[ 3 ][ 2 ]; - double delta, texDelta; - - - /* new code */ - - /* calculate deltas */ - VectorSubtract( pa, pb, deltas[ 0 ] ); - VectorSubtract( pa, pc, deltas[ 1 ] ); - VectorSubtract( pb, pc, deltas[ 2 ] ); - Vector2Subtract( a->st, b->st, texDeltas[ 0 ] ); - Vector2Subtract( a->st, c->st, texDeltas[ 1 ] ); - Vector2Subtract( b->st, c->st, texDeltas[ 2 ] ); - - /* walk st */ - for( i = 0; i < 2; i++ ) - { - /* walk xyz */ - for( j = 0; j < 3; j++ ) - { - /* clear deltas */ - delta = 0.0; - texDelta = 0.0; - - /* walk deltas */ - for( k = 0; k < 3; k++ ) - { - if( fabs( deltas[ k ][ j ] ) > delta && - fabs( texDeltas[ k ][ i ] ) > texDelta ) - { - delta = deltas[ k ][ j ]; - texDelta = texDeltas[ k ][ i ]; - } - } - - /* set texture matrix component */ - if( fabs( delta ) > 0.0 ) - dp->texMat[ i ][ j ] = texDelta / delta; - else - dp->texMat[ i ][ j ] = 0.0; - } - - /* set translation component */ - dp->texMat[ i ][ 3 ] = a->st[ i ] - DotProduct( pa, dp->texMat[ i ] ); - } - } - #endif - - /* debug code */ - #if 1 - Sys_Printf( "Mat: [ %f %f %f %f ] [ %f %f %f %f ] Theta: %f (%f)\n", - dp->texMat[ 0 ][ 0 ], dp->texMat[ 0 ][ 1 ], dp->texMat[ 0 ][ 2 ], dp->texMat[ 0 ][ 3 ], - dp->texMat[ 1 ][ 0 ], dp->texMat[ 1 ][ 1 ], dp->texMat[ 1 ][ 2 ], dp->texMat[ 1 ][ 3 ], - RAD2DEG( acos( DotProduct( dp->texMat[ 0 ], dp->texMat[ 1 ] ) ) ), - RAD2DEG( acos( DotProduct( axis[ 0 ], axis[ 1 ] ) ) ) ); - - Sys_Printf( "XYZ: %f %f %f ST: %f %f ST(t): %f %f\n", - a->xyz[ 0 ], a->xyz[ 1 ], a->xyz[ 2 ], - a->st[ 0 ], a->st[ 1 ], - DotProduct( a->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ], DotProduct( a->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ] ); - #endif - - /* test texture matrix */ - s = DotProduct( a->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; - t = DotProduct( a->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; - if( fabs( s - a->st[ 0 ] ) > 0.01 || fabs( t - a->st[ 1 ] ) > 0.01 ) - { - Sys_Printf( "Bad texture matrix! (A) (%f, %f) != (%f, %f)\n", - s, t, a->st[ 0 ], a->st[ 1 ] ); - //% return qfalse; - } - s = DotProduct( b->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; - t = DotProduct( b->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; - if( fabs( s - b->st[ 0 ] ) > 0.01 || fabs( t - b->st[ 1 ] ) > 0.01 ) - { - Sys_Printf( "Bad texture matrix! (B) (%f, %f) != (%f, %f)\n", - s, t, b->st[ 0 ], b->st[ 1 ] ); - //% return qfalse; - } - s = DotProduct( c->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; - t = DotProduct( c->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; - if( fabs( s - c->st[ 0 ] ) > 0.01 || fabs( t - c->st[ 1 ] ) > 0.01 ) - { - Sys_Printf( "Bad texture matrix! (C) (%f, %f) != (%f, %f)\n", - s, t, c->st[ 0 ], c->st[ 1 ] ); - //% return qfalse; - } - - /* disco */ - return qtrue; -} - - - -/* -TransformDecalProjector() -transforms a decal projector -note: non-normalized axes will screw up the plane transform -*/ - -static void TransformDecalProjector( decalProjector_t *in, vec3_t axis[ 3 ], vec3_t origin, decalProjector_t *out ) -{ - int i; - - - /* copy misc stuff */ - out->si = in->si; - out->numPlanes = in->numPlanes; - - /* translate bounding box and sphere (note: rotated projector bounding box will be invalid!) */ - VectorSubtract( in->mins, origin, out->mins ); - VectorSubtract( in->maxs, origin, out->maxs ); - VectorSubtract( in->center, origin, out->center ); - out->radius = in->radius; - out->radius2 = in->radius2; - - /* translate planes */ - for( i = 0; i < in->numPlanes; i++ ) - { - out->planes[ i ][ 0 ] = DotProduct( in->planes[ i ], axis[ 0 ] ); - out->planes[ i ][ 1 ] = DotProduct( in->planes[ i ], axis[ 1 ] ); - out->planes[ i ][ 2 ] = DotProduct( in->planes[ i ], axis[ 2 ] ); - out->planes[ i ][ 3 ] = in->planes[ i ][ 3 ] - DotProduct( out->planes[ i ], origin ); - } - - /* translate texture matrix */ - for( i = 0; i < 2; i++ ) - { - out->texMat[ i ][ 0 ] = DotProduct( in->texMat[ i ], axis[ 0 ] ); - out->texMat[ i ][ 1 ] = DotProduct( in->texMat[ i ], axis[ 1 ] ); - out->texMat[ i ][ 2 ] = DotProduct( in->texMat[ i ], axis[ 2 ] ); - out->texMat[ i ][ 3 ] = in->texMat[ i ][ 3 ] + DotProduct( out->texMat[ i ], origin ); - } -} - - - -/* -MakeDecalProjector() -creates a new decal projector from a triangle -*/ - -static int MakeDecalProjector( shaderInfo_t *si, vec4_t projection, float distance, int numVerts, bspDrawVert_t **dv ) -{ - int i, j; - decalProjector_t *dp; - vec3_t xyz; - - - /* dummy check */ - if( numVerts != 3 && numVerts != 4 ) - return -1; - - /* limit check */ - if( numProjectors >= MAX_PROJECTORS ) - { - Sys_Printf( "WARNING: MAX_PROJECTORS (%d) exceeded, no more decal projectors available.\n", MAX_PROJECTORS ); - return -2; - } - - /* create a new projector */ - dp = &projectors[ numProjectors ]; - memset( dp, 0, sizeof( *dp ) ); - - /* basic setup */ - dp->si = si; - dp->numPlanes = numVerts + 2; - - /* make texture matrix */ - if( !MakeTextureMatrix( dp, projection, dv[ 0 ], dv[ 1 ], dv[ 2 ] ) ) - return -1; - - /* bound the projector */ - ClearBounds( dp->mins, dp->maxs ); - for( i = 0; i < numVerts; i++ ) - { - AddPointToBounds( dv[ i ]->xyz, dp->mins, dp->maxs ); - VectorMA( dv[ i ]->xyz, distance, projection, xyz ); - AddPointToBounds( xyz, dp->mins, dp->maxs ); - } - - /* make bouding sphere */ - VectorAdd( dp->mins, dp->maxs, dp->center ); - VectorScale( dp->center, 0.5f, dp->center ); - VectorSubtract( dp->maxs, dp->center, xyz ); - dp->radius = VectorLength( xyz ); - dp->radius2 = dp->radius * dp->radius; - - /* make the front plane */ - if( !PlaneFromPoints( dp->planes[ 0 ], dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) ) - return -1; - - /* make the back plane */ - VectorSubtract( vec3_origin, dp->planes[ 0 ], dp->planes[ 1 ] ); - VectorMA( dv[ 0 ]->xyz, distance, projection, xyz ); - dp->planes[ 1 ][ 3 ] = DotProduct( xyz, dp->planes[ 1 ] ); - - /* make the side planes */ - for( i = 0; i < numVerts; i++ ) - { - j = (i + 1) % numVerts; - VectorMA( dv[ i ]->xyz, distance, projection, xyz ); - if( !PlaneFromPoints( dp->planes[ i + 2 ], dv[ j ]->xyz, dv[ i ]->xyz, xyz ) ) - return -1; - } - - /* return ok */ - numProjectors++; - return numProjectors - 1; -} - - - -/* -ProcessDecals() -finds all decal entities and creates decal projectors -*/ - -#define PLANAR_EPSILON 0.5f - -void ProcessDecals( void ) -{ - int i, j, x, y, pw[ 5 ], r, iterations; - float distance; - vec4_t projection, plane; - vec3_t origin, target, delta; - entity_t *e, *e2; - parseMesh_t *p; - mesh_t *mesh, *subdivided; - bspDrawVert_t *dv[ 4 ]; - const char *value; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- ProcessDecals ---\n" ); - - /* walk entity list */ - for( i = 0; i < numEntities; i++ ) - { - /* get entity */ - e = &entities[ i ]; - value = ValueForKey( e, "classname" ); - if( Q_stricmp( value, "_decal" ) ) - continue; - - /* any patches? */ - if( e->patches == NULL ) - { - Sys_Printf( "WARNING: Decal entity without any patch meshes, ignoring.\n" ); - e->epairs = NULL; /* fixme: leak! */ - continue; - } - - /* find target */ - value = ValueForKey( e, "target" ); - e2 = FindTargetEntity( value ); - - /* no target? */ - if( e2 == NULL ) - { - Sys_Printf( "WARNING: Decal entity without a valid target, ignoring.\n" ); - continue; - } - - /* walk entity patches */ - for( p = e->patches; p != NULL; p = e->patches ) - { - /* setup projector */ - if( VectorCompare( e->origin, vec3_origin ) ) - { - VectorAdd( p->eMins, p->eMaxs, origin ); - VectorScale( origin, 0.5f, origin ); - } - else - VectorCopy( e->origin, origin ); - - VectorCopy( e2->origin, target ); - VectorSubtract( target, origin, delta ); - - /* setup projection plane */ - distance = VectorNormalize( delta, projection ); - projection[ 3 ] = DotProduct( origin, projection ); - - /* create projectors */ - if( distance > 0.125f ) - { - /* tesselate the patch */ - iterations = IterationsForCurve( p->longestCurve, patchSubdivisions ); - subdivided = SubdivideMesh2( p->mesh, iterations ); - - /* fit it to the curve and remove colinear verts on rows/columns */ - PutMeshOnCurve( *subdivided ); - mesh = RemoveLinearMeshColumnsRows( subdivided ); - FreeMesh( subdivided ); - - /* offset by projector origin */ - for( j = 0; j < (mesh->width * mesh->height); j++ ) - VectorAdd( mesh->verts[ j ].xyz, e->origin, mesh->verts[ j ].xyz ); - - /* iterate through the mesh quads */ - for( y = 0; y < (mesh->height - 1); y++ ) - { - for( x = 0; x < (mesh->width - 1); x++ ) - { - /* set indexes */ - pw[ 0 ] = x + (y * mesh->width); - pw[ 1 ] = x + ((y + 1) * mesh->width); - pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); - pw[ 3 ] = x + 1 + (y * mesh->width); - pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ - - /* set radix */ - r = (x + y) & 1; - - /* get drawverts */ - dv[ 0 ] = &mesh->verts[ pw[ r + 0 ] ]; - dv[ 1 ] = &mesh->verts[ pw[ r + 1 ] ]; - dv[ 2 ] = &mesh->verts[ pw[ r + 2 ] ]; - dv[ 3 ] = &mesh->verts[ pw[ r + 3 ] ]; - - /* planar? (nuking this optimization as it doesn't work on non-rectangular quads) */ - plane[ 0 ] = 0.0f; /* stupid msvc */ - if( 0 && PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) && - fabs( DotProduct( dv[ 1 ]->xyz, plane ) - plane[ 3 ] ) <= PLANAR_EPSILON ) - { - /* make a quad projector */ - MakeDecalProjector( p->shaderInfo, projection, distance, 4, dv ); - } - else - { - /* make first triangle */ - MakeDecalProjector( p->shaderInfo, projection, distance, 3, dv ); - - /* make second triangle */ - dv[ 1 ] = dv[ 2 ]; - dv[ 2 ] = dv[ 3 ]; - MakeDecalProjector( p->shaderInfo, projection, distance, 3, dv ); - } - } - } - - /* clean up */ - free( mesh ); - } - - /* remove patch from entity (fixme: leak!) */ - e->patches = p->next; - - /* push patch to worldspawn (enable this to debug projectors) */ - #if 0 - p->next = entities[ 0 ].patches; - entities[ 0 ].patches = p; - #endif - } - } - - /* emit some stats */ - Sys_FPrintf( SYS_VRB, "%9d decal projectors\n", numProjectors ); -} - - - -/* -ProjectDecalOntoWinding() -projects a decal onto a winding -*/ - -static void ProjectDecalOntoWinding( decalProjector_t *dp, mapDrawSurface_t *ds, winding_t *w ) -{ - int i, j; - float d, d2, alpha; - winding_t *front, *back; - mapDrawSurface_t *ds2; - bspDrawVert_t *dv; - vec4_t plane; - - - /* dummy check */ - if( w->numpoints < 3 ) - { - FreeWinding( w ); - return; - } - - /* offset by entity origin */ - for( i = 0; i < w->numpoints; i++ ) - VectorAdd( w->p[ i ], entityOrigin, w->p[ i ] ); - - /* make a plane from the winding */ - if( !PlaneFromPoints( plane, w->p[ 0 ], w->p[ 1 ], w->p[ 2 ] ) ) - { - FreeWinding( w ); - return; - } - - /* backface check */ - d = DotProduct( dp->planes[ 0 ], plane ); - if( d < -0.0001f ) - { - FreeWinding( w ); - return; - } - - /* walk list of planes */ - for( i = 0; i < dp->numPlanes; i++ ) - { - /* chop winding by the plane */ - ClipWindingEpsilon( w, dp->planes[ i ], dp->planes[ i ][ 3 ], 0.0625f, &front, &back ); - FreeWinding( w ); - - /* lose the front fragment */ - if( front != NULL ) - FreeWinding( front ); - - /* if nothing left in back, then bail */ - if( back == NULL ) - return; - - /* reset winding */ - w = back; - } - - /* nothing left? */ - if( w == NULL || w->numpoints < 3 ) - return; - - /* add to counts */ - numDecalSurfaces++; - - /* make a new surface */ - ds2 = AllocDrawSurface( SURFACE_DECAL ); - - /* set it up */ - ds2->entityNum = ds->entityNum; - ds2->castShadows = ds->castShadows; - ds2->recvShadows = ds->recvShadows; - ds2->shaderInfo = dp->si; - ds2->fogNum = ds->fogNum; /* why was this -1? */ - ds2->lightmapScale = ds->lightmapScale; - ds2->shadeAngleDegrees = ds->shadeAngleDegrees; - ds2->numVerts = w->numpoints; - ds2->verts = safe_malloc( ds2->numVerts * sizeof( *ds2->verts ) ); - memset( ds2->verts, 0, ds2->numVerts * sizeof( *ds2->verts ) ); - - /* set vertexes */ - for( i = 0; i < ds2->numVerts; i++ ) - { - /* get vertex */ - dv = &ds2->verts[ i ]; - - /* set alpha */ - d = DotProduct( w->p[ i ], dp->planes[ 0 ] ) - dp->planes[ 0 ][ 3 ]; - d2 = DotProduct( w->p[ i ], dp->planes[ 1 ] ) - dp->planes[ 1 ][ 3 ]; - alpha = 255.0f * d2 / (d + d2); - if( alpha > 255 ) - alpha = 255; - else if( alpha < 0 ) - alpha = 0; - - /* set misc */ - VectorSubtract( w->p[ i ], entityOrigin, dv->xyz ); - VectorCopy( plane, dv->normal ); - dv->st[ 0 ] = DotProduct( dv->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; - dv->st[ 1 ] = DotProduct( dv->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; - - /* set color */ - for( j = 0; j < MAX_LIGHTMAPS; j++ ) - { - dv->color[ j ][ 0 ] = 255; - dv->color[ j ][ 1 ] = 255; - dv->color[ j ][ 2 ] = 255; - dv->color[ j ][ 3 ] = alpha; - } - } -} - - - -/* -ProjectDecalOntoFace() -projects a decal onto a brushface surface -*/ - -static void ProjectDecalOntoFace( decalProjector_t *dp, mapDrawSurface_t *ds ) -{ - vec4_t plane; - float d; - winding_t *w; - - - /* dummy check */ - if( ds->sideRef == NULL || ds->sideRef->side == NULL ) - return; - - /* backface check */ - if( ds->planar ) - { - VectorCopy( mapplanes[ ds->planeNum ].normal, plane ); - plane[ 3 ] = mapplanes[ ds->planeNum ].dist + DotProduct( plane, entityOrigin ); - d = DotProduct( dp->planes[ 0 ], plane ); - if( d < -0.0001f ) - return; - } - - /* generate decal */ - w = WindingFromDrawSurf( ds ); - ProjectDecalOntoWinding( dp, ds, w ); -} - - - -/* -ProjectDecalOntoPatch() -projects a decal onto a patch surface -*/ - -static void ProjectDecalOntoPatch( decalProjector_t *dp, mapDrawSurface_t *ds ) -{ - int x, y, pw[ 5 ], r, iterations; - vec4_t plane; - float d; - mesh_t src, *mesh, *subdivided; - winding_t *w; - - - /* backface check */ - if( ds->planar ) - { - VectorCopy( mapplanes[ ds->planeNum ].normal, plane ); - plane[ 3 ] = mapplanes[ ds->planeNum ].dist + DotProduct( plane, entityOrigin ); - d = DotProduct( dp->planes[ 0 ], plane ); - if( d < -0.0001f ) - return; - } - - /* tesselate the patch */ - src.width = ds->patchWidth; - src.height = ds->patchHeight; - src.verts = ds->verts; - iterations = IterationsForCurve( ds->longestCurve, patchSubdivisions ); - subdivided = SubdivideMesh2( src, iterations ); - - /* fit it to the curve and remove colinear verts on rows/columns */ - PutMeshOnCurve( *subdivided ); - mesh = RemoveLinearMeshColumnsRows( subdivided ); - FreeMesh( subdivided ); - - /* iterate through the mesh quads */ - for( y = 0; y < (mesh->height - 1); y++ ) - { - for( x = 0; x < (mesh->width - 1); x++ ) - { - /* set indexes */ - pw[ 0 ] = x + (y * mesh->width); - pw[ 1 ] = x + ((y + 1) * mesh->width); - pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); - pw[ 3 ] = x + 1 + (y * mesh->width); - pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ - - /* set radix */ - r = (x + y) & 1; - - /* generate decal for first triangle */ - w = AllocWinding( 3 ); - w->numpoints = 3; - VectorCopy( mesh->verts[ pw[ r + 0 ] ].xyz, w->p[ 0 ] ); - VectorCopy( mesh->verts[ pw[ r + 1 ] ].xyz, w->p[ 1 ] ); - VectorCopy( mesh->verts[ pw[ r + 2 ] ].xyz, w->p[ 2 ] ); - ProjectDecalOntoWinding( dp, ds, w ); - - /* generate decal for second triangle */ - w = AllocWinding( 3 ); - w->numpoints = 3; - VectorCopy( mesh->verts[ pw[ r + 0 ] ].xyz, w->p[ 0 ] ); - VectorCopy( mesh->verts[ pw[ r + 2 ] ].xyz, w->p[ 1 ] ); - VectorCopy( mesh->verts[ pw[ r + 3 ] ].xyz, w->p[ 2 ] ); - ProjectDecalOntoWinding( dp, ds, w ); - } - } - - /* clean up */ - free( mesh ); -} - - - -/* -ProjectDecalOntoTriangles() -projects a decal onto a triangle surface -*/ - -static void ProjectDecalOntoTriangles( decalProjector_t *dp, mapDrawSurface_t *ds ) -{ - int i; - vec4_t plane; - float d; - winding_t *w; - - - /* triangle surfaces without shaders don't get marks by default */ - if( ds->type == SURFACE_TRIANGLES && ds->shaderInfo->shaderText == NULL ) - return; - - /* backface check */ - if( ds->planar ) - { - VectorCopy( mapplanes[ ds->planeNum ].normal, plane ); - plane[ 3 ] = mapplanes[ ds->planeNum ].dist + DotProduct( plane, entityOrigin ); - d = DotProduct( dp->planes[ 0 ], plane ); - if( d < -0.0001f ) - return; - } - - /* iterate through triangles */ - for( i = 0; i < ds->numIndexes; i += 3 ) - { - /* generate decal */ - w = AllocWinding( 3 ); - w->numpoints = 3; - VectorCopy( ds->verts[ ds->indexes[ i ] ].xyz, w->p[ 0 ] ); - VectorCopy( ds->verts[ ds->indexes[ i + 1 ] ].xyz, w->p[ 1 ] ); - VectorCopy( ds->verts[ ds->indexes[ i + 2 ] ].xyz, w->p[ 2 ] ); - ProjectDecalOntoWinding( dp, ds, w ); - } -} - - - -/* -MakeEntityDecals() -projects decals onto world surfaces -*/ - -void MakeEntityDecals( entity_t *e ) -{ - int i, j, k, f, fOld, start; - decalProjector_t dp; - mapDrawSurface_t *ds; - vec3_t identityAxis[ 3 ] = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- MakeEntityDecals ---\n" ); - - /* set entity origin */ - VectorCopy( e->origin, entityOrigin ); - - /* transform projector instead of geometry */ - VectorClear( entityOrigin ); - - /* init pacifier */ - fOld = -1; - start = I_FloatTime(); - - /* walk the list of decal projectors */ - for( i = 0; i < numProjectors; i++ ) - { - /* print pacifier */ - f = 10 * i / numProjectors; - if( f != fOld ) - { - fOld = f; - Sys_FPrintf( SYS_VRB, "%d...", f ); - } - - /* get projector */ - TransformDecalProjector( &projectors[ i ], identityAxis, e->origin, &dp ); - - /* walk the list of surfaces in the entity */ - for( j = e->firstDrawSurf; j < numMapDrawSurfs; j++ ) - { - /* get surface */ - ds = &mapDrawSurfs[ j ]; - if( ds->numVerts <= 0 ) - continue; - - /* ignore autosprite or nomarks */ - if( ds->shaderInfo->autosprite || (ds->shaderInfo->compileFlags & C_NOMARKS) ) - continue; - - /* bounds check */ - for( k = 0; k < 3; k++ ) - if( ds->mins[ k ] >= (dp.center[ k ] + dp.radius) || - ds->maxs[ k ] <= (dp.center[ k ] - dp.radius) ) - break; - if( k < 3 ) - continue; - - /* switch on type */ - switch( ds->type ) - { - case SURFACE_FACE: - ProjectDecalOntoFace( &dp, ds ); - break; - - case SURFACE_PATCH: - ProjectDecalOntoPatch( &dp, ds ); - break; - - case SURFACE_TRIANGLES: - case SURFACE_FORCED_META: - case SURFACE_META: - ProjectDecalOntoTriangles( &dp, ds ); - break; - - default: - break; - } - } - } - - /* print time */ - Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) ); - - /* emit some stats */ - Sys_FPrintf( SYS_VRB, "%9d decal surfaces\n", numDecalSurfaces ); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/facebsp.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/facebsp.c deleted file mode 100644 index 9291f564..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/facebsp.c +++ /dev/null @@ -1,528 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define FACEBSP_C - - - -/* dependencies */ -#include "q3map2.h" - - - -int c_faceLeafs; - - -/* -================ -AllocBspFace -================ -*/ -face_t *AllocBspFace( void ) { - face_t *f; - - f = safe_malloc(sizeof(*f)); - memset( f, 0, sizeof(*f) ); - - return f; -} - - - -/* -================ -FreeBspFace -================ -*/ -void FreeBspFace( face_t *f ) { - if ( f->w ) { - FreeWinding( f->w ); - } - free( f ); -} - - - -/* -SelectSplitPlaneNum() -finds the best split plane for this node -*/ - -static void SelectSplitPlaneNum( node_t *node, face_t *list, int *splitPlaneNum, int *compileFlags ) -{ - face_t *split; - face_t *check; - face_t *bestSplit; - int splits, facing, front, back; - int side; - plane_t *plane; - int value, bestValue; - int i; - vec3_t normal; - float dist; - int planenum; - float sizeBias; - - //int frontC,backC,splitsC,facingC; - - - /* ydnar: set some defaults */ - *splitPlaneNum = -1; /* leaf */ - *compileFlags = 0; - - /* ydnar 2002-06-24: changed this to split on z-axis as well */ - /* ydnar 2002-09-21: changed blocksize to be a vector, so mappers can specify a 3 element value */ - - /* if it is crossing a block boundary, force a split */ - for( i = 0; i < 3; i++ ) - { - if( blockSize[ i ] <= 0 ) - continue; - dist = blockSize[ i ] * (floor( node->mins[ i ] / blockSize[ i ] ) + 1); - if( node->maxs[ i ] > dist ) - { - VectorClear( normal ); - normal[ i ] = 1; - planenum = FindFloatPlane( normal, dist, 0, NULL ); - *splitPlaneNum = planenum; - return; - } - } - - /* pick one of the face planes */ - bestValue = -99999; - bestSplit = list; - - - // div0: this check causes detail/structural mixes - //for( split = list; split; split = split->next ) - // split->checked = qfalse; - - for( split = list; split; split = split->next ) - { - //if ( split->checked ) - // continue; - - plane = &mapplanes[ split->planenum ]; - splits = 0; - facing = 0; - front = 0; - back = 0; - for ( check = list ; check ; check = check->next ) { - if ( check->planenum == split->planenum ) { - facing++; - //check->checked = qtrue; // won't need to test this plane again - continue; - } - side = WindingOnPlaneSide( check->w, plane->normal, plane->dist ); - if ( side == SIDE_CROSS ) { - splits++; - } else if ( side == SIDE_FRONT ) { - front++; - } else if ( side == SIDE_BACK ) { - back++; - } - } - - if(bspAlternateSplitWeights) - { - // from 27 - - //Bigger is better - sizeBias=WindingArea(split->w); - - //Base score = 20000 perfectly balanced - value = 20000-(abs(front-back)); - value -= plane->counter;// If we've already used this plane sometime in the past try not to use it again - value -= facing ; // if we're going to have alot of other surfs use this plane, we want to get it in quickly. - value -= splits*5; //more splits = bad - value += sizeBias*10; //We want a huge score bias based on plane size - } - else - { - value = 5*facing - 5*splits; // - abs(front-back); - if ( plane->type < 3 ) { - value+=5; // axial is better - } - } - - value += split->priority; // prioritize hints higher - - if ( value > bestValue ) { - bestValue = value; - bestSplit = split; - //frontC=front; - //backC=back; - //splitsC=splits; - //facingC=facing; - } - } - - /* nothing, we have a leaf */ - if( bestValue == -99999 ) - return; - - //Sys_FPrintf (SYS_VRB, "F: %d B:%d S:%d FA:%ds\n",frontC,backC,splitsC,facingC ); - - /* set best split data */ - *splitPlaneNum = bestSplit->planenum; - *compileFlags = bestSplit->compileFlags; - -#if 0 - if(bestSplit->compileFlags & C_DETAIL) - for( split = list; split; split = split->next ) - if(!(split->compileFlags & C_DETAIL)) - Sys_FPrintf(SYS_ERR, "DON'T DO SUCH SPLITS (1)\n"); - if((node->compileFlags & C_DETAIL) && !(bestSplit->compileFlags & C_DETAIL)) - Sys_FPrintf(SYS_ERR, "DON'T DO SUCH SPLITS (2)\n"); -#endif - - if (*splitPlaneNum>-1) mapplanes[ *splitPlaneNum ].counter++; -} - - - -/* -CountFaceList() -counts bsp faces in the linked list -*/ - -int CountFaceList( face_t *list ) -{ - int c; - - - c = 0; - for( ; list != NULL; list = list->next ) - c++; - return c; -} - - - -/* -BuildFaceTree_r() -recursively builds the bsp, splitting on face planes -*/ - -void BuildFaceTree_r( node_t *node, face_t *list ) -{ - face_t *split; - face_t *next; - int side; - plane_t *plane; - face_t *newFace; - face_t *childLists[2]; - winding_t *frontWinding, *backWinding; - int i; - int splitPlaneNum, compileFlags; - qboolean isstruct = qfalse; - - - /* count faces left */ - i = CountFaceList( list ); - - /* select the best split plane */ - SelectSplitPlaneNum( node, list, &splitPlaneNum, &compileFlags ); - - /* if we don't have any more faces, this is a node */ - if ( splitPlaneNum == -1 ) - { - node->planenum = PLANENUM_LEAF; - node->has_structural_children = qfalse; - c_faceLeafs++; - return; - } - - /* partition the list */ - node->planenum = splitPlaneNum; - node->compileFlags = compileFlags; - node->has_structural_children = !(compileFlags & C_DETAIL) && !node->opaque; - plane = &mapplanes[ splitPlaneNum ]; - childLists[0] = NULL; - childLists[1] = NULL; - - for( split = list; split; split = next ) - { - /* set next */ - next = split->next; - - /* don't split by identical plane */ - if( split->planenum == node->planenum ) - { - FreeBspFace( split ); - continue; - } - - if(!(split->compileFlags & C_DETAIL)) - isstruct = 1; - - /* determine which side the face falls on */ - side = WindingOnPlaneSide( split->w, plane->normal, plane->dist ); - - /* switch on side */ - if( side == SIDE_CROSS ) - { - ClipWindingEpsilon( split->w, plane->normal, plane->dist, CLIP_EPSILON * 2, - &frontWinding, &backWinding ); - if( frontWinding ) { - newFace = AllocBspFace(); - newFace->w = frontWinding; - newFace->next = childLists[0]; - newFace->planenum = split->planenum; - newFace->priority = split->priority; - newFace->compileFlags = split->compileFlags; - childLists[0] = newFace; - } - if( backWinding ) { - newFace = AllocBspFace(); - newFace->w = backWinding; - newFace->next = childLists[1]; - newFace->planenum = split->planenum; - newFace->priority = split->priority; - newFace->compileFlags = split->compileFlags; - childLists[1] = newFace; - } - FreeBspFace( split ); - } else if ( side == SIDE_FRONT ) { - split->next = childLists[0]; - childLists[0] = split; - } else if ( side == SIDE_BACK ) { - split->next = childLists[1]; - childLists[1] = split; - } - } - - - // recursively process children - for ( i = 0 ; i < 2 ; i++ ) { - node->children[i] = AllocNode(); - node->children[i]->parent = node; - VectorCopy( node->mins, node->children[i]->mins ); - VectorCopy( node->maxs, node->children[i]->maxs ); - } - - for ( i = 0 ; i < 3 ; i++ ) { - if ( plane->normal[i] == 1 ) { - node->children[0]->mins[i] = plane->dist; - node->children[1]->maxs[i] = plane->dist; - break; - } - } - -#if 0 - if((node->compileFlags & C_DETAIL) && isstruct) - Sys_FPrintf(SYS_ERR, "I am detail, my child is structural, this is a wtf1\n", node->has_structural_children); -#endif - - for ( i = 0 ; i < 2 ; i++ ) { - BuildFaceTree_r ( node->children[i], childLists[i]); - node->has_structural_children |= node->children[i]->has_structural_children; - } - -#if 0 - if((node->compileFlags & C_DETAIL) && !(node->children[0]->compileFlags & C_DETAIL) && node->children[0]->planenum != PLANENUM_LEAF) - Sys_FPrintf(SYS_ERR, "I am detail, my child is structural\n", node->has_structural_children); - if((node->compileFlags & C_DETAIL) && isstruct) - Sys_FPrintf(SYS_ERR, "I am detail, my child is structural, this is a wtf2\n", node->has_structural_children); -#endif -} - - -/* -================ -FaceBSP - -List will be freed before returning -================ -*/ -tree_t *FaceBSP( face_t *list ) { - tree_t *tree; - face_t *face; - int i; - int count; - - Sys_FPrintf (SYS_VRB, "--- FaceBSP ---\n" ); - - tree = AllocTree (); - - count = 0; - for( face = list; face != NULL; face = face->next ) - { - count++; - for( i = 0; i < face->w->numpoints; i++ ) - { - AddPointToBounds( face->w->p[ i ], tree->mins, tree->maxs ); - } - } - Sys_FPrintf( SYS_VRB, "%9d faces\n", count ); - - for( i = 0; i < nummapplanes; i++) - { - mapplanes[ i ].counter=0; - } - - tree->headnode = AllocNode(); - VectorCopy( tree->mins, tree->headnode->mins ); - VectorCopy( tree->maxs, tree->headnode->maxs ); - c_faceLeafs = 0; - - BuildFaceTree_r ( tree->headnode, list ); - - Sys_FPrintf( SYS_VRB, "%9d leafs\n", c_faceLeafs ); - - return tree; -} - - - -/* -MakeStructuralBSPFaceList() -get structural brush faces -*/ - -face_t *MakeStructuralBSPFaceList( brush_t *list ) -{ - brush_t *b; - int i; - side_t *s; - winding_t *w; - face_t *f, *flist; - - - flist = NULL; - for( b = list; b != NULL; b = b->next ) - { - if( !deepBSP && b->detail ) - continue; - - for( i = 0; i < b->numsides; i++ ) - { - /* get side and winding */ - s = &b->sides[ i ]; - w = s->winding; - if( w == NULL ) - continue; - - /* ydnar: skip certain faces */ - if( s->compileFlags & C_SKIP ) - continue; - - /* allocate a face */ - f = AllocBspFace(); - f->w = CopyWinding( w ); - f->planenum = s->planenum & ~1; - f->compileFlags = s->compileFlags; /* ydnar */ - if(b->detail) - f->compileFlags |= C_DETAIL; - - /* ydnar: set priority */ - f->priority = 0; - if( f->compileFlags & C_HINT ) - f->priority += HINT_PRIORITY; - if( f->compileFlags & C_ANTIPORTAL ) - f->priority += ANTIPORTAL_PRIORITY; - if( f->compileFlags & C_AREAPORTAL ) - f->priority += AREAPORTAL_PRIORITY; - if( f->compileFlags & C_DETAIL ) - f->priority += DETAIL_PRIORITY; - - /* get next face */ - f->next = flist; - flist = f; - } - } - - return flist; -} - - - -/* -MakeVisibleBSPFaceList() -get visible brush faces -*/ - -face_t *MakeVisibleBSPFaceList( brush_t *list ) -{ - brush_t *b; - int i; - side_t *s; - winding_t *w; - face_t *f, *flist; - - - flist = NULL; - for( b = list; b != NULL; b = b->next ) - { - if( !deepBSP && b->detail ) - continue; - - for( i = 0; i < b->numsides; i++ ) - { - /* get side and winding */ - s = &b->sides[ i ]; - w = s->visibleHull; - if( w == NULL ) - continue; - - /* ydnar: skip certain faces */ - if( s->compileFlags & C_SKIP ) - continue; - - /* allocate a face */ - f = AllocBspFace(); - f->w = CopyWinding( w ); - f->planenum = s->planenum & ~1; - f->compileFlags = s->compileFlags; /* ydnar */ - if(b->detail) - f->compileFlags |= C_DETAIL; - - /* ydnar: set priority */ - f->priority = 0; - if( f->compileFlags & C_HINT ) - f->priority += HINT_PRIORITY; - if( f->compileFlags & C_ANTIPORTAL ) - f->priority += ANTIPORTAL_PRIORITY; - if( f->compileFlags & C_AREAPORTAL ) - f->priority += AREAPORTAL_PRIORITY; - if( f->compileFlags & C_DETAIL ) - f->priority += DETAIL_PRIORITY; - - /* get next face */ - f->next = flist; - flist = f; - } - } - - return flist; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/fog.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/fog.c deleted file mode 100644 index c9ee6e25..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/fog.c +++ /dev/null @@ -1,803 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define FOG_C - - - -/* dependencies */ -#include "q3map2.h" - - - -int numFogFragments; -int numFogPatchFragments; - - - -/* -DrawSurfToMesh() -converts a patch drawsurface to a mesh_t -*/ - -mesh_t *DrawSurfToMesh( mapDrawSurface_t *ds ) -{ - mesh_t *m; - - - m = safe_malloc( sizeof( *m ) ); - m->width = ds->patchWidth; - m->height = ds->patchHeight; - m->verts = safe_malloc( sizeof(m->verts[ 0 ]) * m->width * m->height ); - memcpy( m->verts, ds->verts, sizeof(m->verts[ 0 ]) * m->width * m->height ); - - return m; -} - - - -/* -SplitMeshByPlane() -chops a mesh by a plane -*/ - -void SplitMeshByPlane( mesh_t *in, vec3_t normal, float dist, mesh_t **front, mesh_t **back ) -{ - int w, h, split; - float d[MAX_PATCH_SIZE][MAX_PATCH_SIZE]; - bspDrawVert_t *dv, *v1, *v2; - int c_front, c_back, c_on; - mesh_t *f, *b; - int i; - float frac; - int frontAprox, backAprox; - - for ( i = 0 ; i < 2 ; i++ ) { - dv = in->verts; - c_front = 0; - c_back = 0; - c_on = 0; - for ( h = 0 ; h < in->height ; h++ ) { - for ( w = 0 ; w < in->width ; w++, dv++ ) { - d[h][w] = DotProduct( dv->xyz, normal ) - dist; - if ( d[h][w] > ON_EPSILON ) { - c_front++; - } else if ( d[h][w] < -ON_EPSILON ) { - c_back++; - } else { - c_on++; - } - } - } - - *front = NULL; - *back = NULL; - - if ( !c_front ) { - *back = in; - return; - } - if ( !c_back ) { - *front = in; - return; - } - - // find a split point - split = -1; - for ( w = 0 ; w < in->width -1 ; w++ ) { - if ( ( d[0][w] < 0 ) != ( d[0][w+1] < 0 ) ) { - if ( split == -1 ) { - split = w; - break; - } - } - } - - if ( split == -1 ) { - if ( i == 1 ) { - Sys_FPrintf (SYS_VRB, "No crossing points in patch\n"); - *front = in; - return; - } - - in = TransposeMesh( in ); - InvertMesh( in ); - continue; - } - - // make sure the split point stays the same for all other rows - for ( h = 1 ; h < in->height ; h++ ) { - for ( w = 0 ; w < in->width -1 ; w++ ) { - if ( ( d[h][w] < 0 ) != ( d[h][w+1] < 0 ) ) { - if ( w != split ) { - Sys_Printf( "multiple crossing points for patch -- can't clip\n"); - *front = in; - return; - } - } - } - if ( ( d[h][split] < 0 ) == ( d[h][split+1] < 0 ) ) { - Sys_Printf( "differing crossing points for patch -- can't clip\n"); - *front = in; - return; - } - } - - break; - } - - - // create two new meshes - f = safe_malloc( sizeof( *f ) ); - f->width = split + 2; - if ( ! (f->width & 1) ) { - f->width++; - frontAprox = 1; - } else { - frontAprox = 0; - } - if ( f->width > MAX_PATCH_SIZE ) { - Error( "MAX_PATCH_SIZE after split"); - } - f->height = in->height; - f->verts = safe_malloc( sizeof(f->verts[0]) * f->width * f->height ); - - b = safe_malloc( sizeof( *b ) ); - b->width = in->width - split; - if ( ! (b->width & 1) ) { - b->width++; - backAprox = 1; - } else { - backAprox = 0; - } - if ( b->width > MAX_PATCH_SIZE ) { - Error( "MAX_PATCH_SIZE after split"); - } - b->height = in->height; - b->verts = safe_malloc( sizeof(b->verts[0]) * b->width * b->height ); - - if ( d[0][0] > 0 ) { - *front = f; - *back = b; - } else { - *front = b; - *back = f; - } - - // distribute the points - for ( w = 0 ; w < in->width ; w++ ) { - for ( h = 0 ; h < in->height ; h++ ) { - if ( w <= split ) { - f->verts[ h * f->width + w ] = in->verts[ h * in->width + w ]; - } else { - b->verts[ h * b->width + w - split + backAprox ] = in->verts[ h * in->width + w ]; - } - } - } - - // clip the crossing line - for ( h = 0; h < in->height; h++ ) - { - dv = &f->verts[ h * f->width + split + 1 ]; - v1 = &in->verts[ h * in->width + split ]; - v2 = &in->verts[ h * in->width + split + 1 ]; - - frac = d[h][split] / ( d[h][split] - d[h][split+1] ); - - /* interpolate */ - //% for( i = 0; i < 10; i++ ) - //% dv->xyz[ i ] = v1->xyz[ i ] + frac * (v2->xyz[ i ] - v1->xyz[ i ]); - //% dv->xyz[10] = 0; // set all 4 colors to 0 - LerpDrawVertAmount( v1, v2, frac, dv ); - - if ( frontAprox ) { - f->verts[ h * f->width + split + 2 ] = *dv; - } - b->verts[ h * b->width ] = *dv; - if ( backAprox ) { - b->verts[ h * b->width + 1 ] = *dv; - } - } - - /* -PrintMesh( in ); -Sys_Printf("\n"); -PrintMesh( f ); -Sys_Printf("\n"); -PrintMesh( b ); -Sys_Printf("\n"); - */ - - FreeMesh( in ); -} - - -/* -ChopPatchSurfaceByBrush() -chops a patch up by a fog brush -*/ - -qboolean ChopPatchSurfaceByBrush( entity_t *e, mapDrawSurface_t *ds, brush_t *b ) -{ - int i, j; - side_t *s; - plane_t *plane; - mesh_t *outside[MAX_BRUSH_SIDES]; - int numOutside; - mesh_t *m, *front, *back; - mapDrawSurface_t *newds; - - m = DrawSurfToMesh( ds ); - numOutside = 0; - - // only split by the top and bottom planes to avoid - // some messy patch clipping issues - - for ( i = 4 ; i <= 5 ; i++ ) { - s = &b->sides[ i ]; - plane = &mapplanes[ s->planenum ]; - - SplitMeshByPlane( m, plane->normal, plane->dist, &front, &back ); - - if ( !back ) { - // nothing actually contained inside - for ( j = 0 ; j < numOutside ; j++ ) { - FreeMesh( outside[j] ); - } - return qfalse; - } - m = back; - - if ( front ) { - if ( numOutside == MAX_BRUSH_SIDES ) { - Error( "MAX_BRUSH_SIDES" ); - } - outside[ numOutside ] = front; - numOutside++; - } - } - - /* all of outside fragments become seperate drawsurfs */ - numFogPatchFragments += numOutside; - for( i = 0; i < numOutside; i++ ) - { - /* transpose and invert the chopped patch (fixes potential crash. fixme: why?) */ - outside[ i ] = TransposeMesh( outside[ i ] ); - InvertMesh( outside[ i ] ); - - /* ydnar: do this the hacky right way */ - newds = AllocDrawSurface( SURFACE_PATCH ); - memcpy( newds, ds, sizeof( *ds ) ); - newds->patchWidth = outside[ i ]->width; - newds->patchHeight = outside[ i ]->height; - newds->numVerts = outside[ i ]->width * outside[ i ]->height; - newds->verts = safe_malloc( newds->numVerts * sizeof( *newds->verts ) ); - memcpy( newds->verts, outside[ i ]->verts, newds->numVerts * sizeof( *newds->verts ) ); - - /* free the source mesh */ - FreeMesh( outside[ i ] ); - } - - /* only rejigger this patch if it was chopped */ - //% Sys_Printf( "Inside: %d x %d\n", m->width, m->height ); - if( numOutside > 0 ) - { - /* transpose and invert the chopped patch (fixes potential crash. fixme: why?) */ - m = TransposeMesh( m ); - InvertMesh( m ); - - /* replace ds with m */ - ds->patchWidth = m->width; - ds->patchHeight = m->height; - ds->numVerts = m->width * m->height; - free( ds->verts ); - ds->verts = safe_malloc( ds->numVerts * sizeof( *ds->verts ) ); - memcpy( ds->verts, m->verts, ds->numVerts * sizeof( *ds->verts ) ); - } - - /* free the source mesh and return */ - FreeMesh( m ); - return qtrue; -} - - - -/* -WindingFromDrawSurf() -creates a winding from a surface's verts -*/ - -winding_t *WindingFromDrawSurf( mapDrawSurface_t *ds ) -{ - winding_t *w; - int i; - - // we use the first point of the surface, maybe something more clever would be useful - // (actually send the whole draw surface would be cool?) - if( ds->numVerts >= MAX_POINTS_ON_WINDING ) - { - int max = ds->numVerts; - vec3_t p[256]; - - if(max > 256) - max = 256; - - for ( i = 0 ; i < max ; i++ ) { - VectorCopy( ds->verts[i].xyz, p[i] ); - } - - xml_Winding( "WindingFromDrawSurf failed: MAX_POINTS_ON_WINDING exceeded", p, max, qtrue ); - } - - w = AllocWinding( ds->numVerts ); - w->numpoints = ds->numVerts; - for ( i = 0 ; i < ds->numVerts ; i++ ) { - VectorCopy( ds->verts[i].xyz, w->p[i] ); - } - return w; -} - - - -/* -ChopFaceSurfaceByBrush() -chops up a face drawsurface by a fog brush, with a potential fragment left inside -*/ - -qboolean ChopFaceSurfaceByBrush( entity_t *e, mapDrawSurface_t *ds, brush_t *b ) -{ - int i, j; - side_t *s; - plane_t *plane; - winding_t *w; - winding_t *front, *back; - winding_t *outside[ MAX_BRUSH_SIDES ]; - int numOutside; - mapDrawSurface_t *newds; - - - /* dummy check */ - if( ds->sideRef == NULL || ds->sideRef->side == NULL ) - return qfalse; - - /* initial setup */ - w = WindingFromDrawSurf( ds ); - numOutside = 0; - - /* chop by each brush side */ - for( i = 0; i < b->numsides; i++ ) - { - /* get brush side and plane */ - s = &b->sides[ i ]; - plane = &mapplanes[ s->planenum ]; - - /* handle coplanar outfacing (don't fog) */ - if( ds->sideRef->side->planenum == s->planenum ) - return qfalse; - - /* handle coplanar infacing (keep inside) */ - if( (ds->sideRef->side->planenum ^ 1) == s->planenum ) - continue; - - /* general case */ - ClipWindingEpsilon( w, plane->normal, plane->dist, ON_EPSILON, &front, &back ); - FreeWinding( w ); - - if( back == NULL ) - { - /* nothing actually contained inside */ - for( j = 0; j < numOutside; j++ ) - FreeWinding( outside[ j ] ); - return qfalse; - } - - if( front != NULL ) - { - if( numOutside == MAX_BRUSH_SIDES ) - Error( "MAX_BRUSH_SIDES" ); - outside[ numOutside ] = front; - numOutside++; - } - - w = back; - } - - /* fixme: celshaded surface fragment errata */ - - /* all of outside fragments become seperate drawsurfs */ - numFogFragments += numOutside; - s = ds->sideRef->side; - for( i = 0; i < numOutside; i++ ) - { - newds = DrawSurfaceForSide( e, ds->mapBrush, s, outside[ i ] ); - newds->fogNum = ds->fogNum; - FreeWinding( outside[ i ] ); - } - - /* ydnar: the old code neglected to snap to 0.125 for the fragment - inside the fog brush, leading to sparklies. this new code does - the right thing and uses the original surface's brush side */ - - /* build a drawsurf for it */ - newds = DrawSurfaceForSide( e, ds->mapBrush, s, w ); - if( newds == NULL ) - return qfalse; - - /* copy new to original */ - ClearSurface( ds ); - memcpy( ds, newds, sizeof( mapDrawSurface_t ) ); - - /* didn't really add a new drawsurface... :) */ - numMapDrawSurfs--; - - /* return ok */ - return qtrue; -} - - - -/* -FogDrawSurfaces() -call after the surface list has been pruned, before tjunction fixing -*/ - -void FogDrawSurfaces( entity_t *e ) -{ - int i, j, k, fogNum; - fog_t *fog; - mapDrawSurface_t *ds; - vec3_t mins, maxs; - int fogged, numFogged; - int numBaseDrawSurfs; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "----- FogDrawSurfs -----\n" ); - - /* reset counters */ - numFogged = 0; - numFogFragments = 0; - - /* walk fog list */ - for( fogNum = 0; fogNum < numMapFogs; fogNum++ ) - { - /* get fog */ - fog = &mapFogs[ fogNum ]; - - /* clip each surface into this, but don't clip any of the resulting fragments to the same brush */ - numBaseDrawSurfs = numMapDrawSurfs; - for( i = 0; i < numBaseDrawSurfs; i++ ) - { - /* get the drawsurface */ - ds = &mapDrawSurfs[ i ]; - - /* no fog? */ - if( ds->shaderInfo->noFog ) - continue; - - /* global fog doesn't have a brush */ - if( fog->brush == NULL ) - { - /* don't re-fog already fogged surfaces */ - if( ds->fogNum >= 0 ) - continue; - fogged = 1; - } - else - { - /* find drawsurface bounds */ - ClearBounds( mins, maxs ); - for( j = 0; j < ds->numVerts; j++ ) - AddPointToBounds( ds->verts[ j ].xyz, mins, maxs ); - - /* check against the fog brush */ - for( k = 0; k < 3; k++ ) - { - if( mins[ k ] > fog->brush->maxs[ k ] ) - break; - if( maxs[ k ] < fog->brush->mins[ k ] ) - break; - } - - /* no intersection? */ - if( k < 3 ) - continue; - - /* ydnar: gs mods: handle the various types of surfaces */ - switch( ds->type ) - { - /* handle brush faces */ - case SURFACE_FACE: - fogged = ChopFaceSurfaceByBrush( e, ds, fog->brush ); - break; - - /* handle patches */ - case SURFACE_PATCH: - fogged = ChopPatchSurfaceByBrush( e, ds, fog->brush ); - break; - - /* handle triangle surfaces (fixme: split triangle surfaces) */ - case SURFACE_TRIANGLES: - case SURFACE_FORCED_META: - case SURFACE_META: - fogged = 1; - break; - - /* no fogging */ - default: - fogged = 0; - break; - } - } - - /* is this surface fogged? */ - if( fogged ) - { - numFogged += fogged; - ds->fogNum = fogNum; - } - } - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d fog polygon fragments\n", numFogFragments ); - Sys_FPrintf( SYS_VRB, "%9d fog patch fragments\n", numFogPatchFragments ); - Sys_FPrintf( SYS_VRB, "%9d fogged drawsurfs\n", numFogged ); -} - - - -/* -FogForPoint() - ydnar -gets the fog number for a point in space -*/ - -int FogForPoint( vec3_t point, float epsilon ) -{ - int fogNum, i, j; - float dot; - qboolean inside; - brush_t *brush; - plane_t *plane; - - - /* start with bogus fog num */ - fogNum = defaultFogNum; - - /* walk the list of fog volumes */ - for( i = 0; i < numMapFogs; i++ ) - { - /* sof2: global fog doesn't reference a brush */ - if( mapFogs[ i ].brush == NULL ) - { - fogNum = i; - continue; - } - - /* get fog brush */ - brush = mapFogs[ i ].brush; - - /* check point against all planes */ - inside = qtrue; - for( j = 0; j < brush->numsides && inside; j++ ) - { - plane = &mapplanes[ brush->sides[ j ].planenum ]; /* note usage of map planes here */ - dot = DotProduct( point, plane->normal ); - dot -= plane->dist; - if( dot > epsilon ) - inside = qfalse; - } - - /* if inside, return the fog num */ - if( inside ) - { - //% Sys_Printf( "FogForPoint: %f, %f, %f in fog %d\n", point[ 0 ], point[ 1 ], point[ 2 ], i ); - return i; - } - } - - /* if the point made it this far, it's not inside any fog volumes (or inside global fog) */ - return fogNum; -} - - - -/* -FogForBounds() - ydnar -gets the fog number for a bounding box -*/ - -int FogForBounds( vec3_t mins, vec3_t maxs, float epsilon ) -{ - int fogNum, i, j; - float highMin, lowMax, volume, bestVolume; - vec3_t fogMins, fogMaxs, overlap; - brush_t *brush; - - - /* start with bogus fog num */ - fogNum = defaultFogNum; - - /* init */ - bestVolume = 0.0f; - - /* walk the list of fog volumes */ - for( i = 0; i < numMapFogs; i++ ) - { - /* sof2: global fog doesn't reference a brush */ - if( mapFogs[ i ].brush == NULL ) - { - fogNum = i; - continue; - } - - /* get fog brush */ - brush = mapFogs[ i ].brush; - - /* get bounds */ - fogMins[ 0 ] = brush->mins[ 0 ] - epsilon; - fogMins[ 1 ] = brush->mins[ 1 ] - epsilon; - fogMins[ 2 ] = brush->mins[ 2 ] - epsilon; - fogMaxs[ 0 ] = brush->maxs[ 0 ] + epsilon; - fogMaxs[ 1 ] = brush->maxs[ 1 ] + epsilon; - fogMaxs[ 2 ] = brush->maxs[ 2 ] + epsilon; - - /* check against bounds */ - for( j = 0; j < 3; j++ ) - { - if( mins[ j ] > fogMaxs[ j ] || maxs[ j ] < fogMins[ j ] ) - break; - highMin = mins[ j ] > fogMins[ j ] ? mins[ j ] : fogMins[ j ]; - lowMax = maxs[ j ] < fogMaxs[ j ] ? maxs[ j ] : fogMaxs[ j ]; - overlap[ j ] = lowMax - highMin; - if( overlap[ j ] < 1.0f ) - overlap[ j ] = 1.0f; - } - - /* no overlap */ - if( j < 3 ) - continue; - - /* get volume */ - volume = overlap[ 0 ] * overlap[ 1 ] * overlap[ 2 ]; - - /* test against best volume */ - if( volume > bestVolume ) - { - bestVolume = volume; - fogNum = i; - } - } - - /* if the point made it this far, it's not inside any fog volumes (or inside global fog) */ - return fogNum; -} - - - -/* -CreateMapFogs() - ydnar -generates a list of map fogs -*/ - -void CreateMapFogs( void ) -{ - int i; - entity_t *entity; - brush_t *brush; - fog_t *fog; - vec3_t invFogDir; - const char *globalFog; - - - /* skip? */ - if( nofog ) - return; - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- CreateMapFogs ---\n" ); - - /* walk entities */ - for( i = 0; i < numEntities; i++ ) - { - /* get entity */ - entity = &entities[ i ]; - - /* walk entity brushes */ - for( brush = entity->brushes; brush != NULL; brush = brush->next ) - { - /* ignore non-fog brushes */ - if( brush->contentShader->fogParms == qfalse ) - continue; - - /* test limit */ - if( numMapFogs >= MAX_MAP_FOGS ) - Error( "Exceeded MAX_MAP_FOGS (%d)", MAX_MAP_FOGS ); - - /* set up fog */ - fog = &mapFogs[ numMapFogs++ ]; - fog->si = brush->contentShader; - fog->brush = brush; - fog->visibleSide = -1; - - /* if shader specifies an explicit direction, then find a matching brush side with an opposed normal */ - if( VectorLength( fog->si->fogDir ) ) - { - /* flip it */ - VectorScale( fog->si->fogDir, -1.0f, invFogDir ); - - /* find the brush side */ - for( i = 0; i < brush->numsides; i++ ) - { - if( VectorCompare( invFogDir, mapplanes[ brush->sides[ i ].planenum ].normal ) ) - { - fog->visibleSide = i; - //% Sys_Printf( "Brush num: %d Side num: %d\n", fog->brushNum, fog->visibleSide ); - break; - } - } - } - } - } - - /* ydnar: global fog */ - globalFog = ValueForKey( &entities[ 0 ], "_fog" ); - if( globalFog[ 0 ] == '\0' ) - globalFog = ValueForKey( &entities[ 0 ], "fog" ); - if( globalFog[ 0 ] != '\0' ) - { - /* test limit */ - if( numMapFogs >= MAX_MAP_FOGS ) - Error( "Exceeded MAX_MAP_FOGS (%d) trying to add global fog", MAX_MAP_FOGS ); - - /* note it */ - Sys_FPrintf( SYS_VRB, "Map has global fog shader %s\n", globalFog ); - - /* set up fog */ - fog = &mapFogs[ numMapFogs++ ]; - fog->si = ShaderInfoForShader( globalFog ); - if( fog->si == NULL ) - Error( "Invalid shader \"%s\" referenced trying to add global fog", globalFog ); - fog->brush = NULL; - fog->visibleSide = -1; - - /* set as default fog */ - defaultFogNum = numMapFogs - 1; - - /* mark all worldspawn brushes as fogged */ - for( brush = entities[ 0 ].brushes; brush != NULL; brush = brush->next ) - ApplySurfaceParm( "fog", &brush->contentFlags, NULL, &brush->compileFlags ); - } - - /* emit some stats */ - Sys_FPrintf( SYS_VRB, "%9d fogs\n", numMapFogs ); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game__null.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game__null.h deleted file mode 100644 index c2f24849..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game__null.h +++ /dev/null @@ -1,98 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME__NULL_H -#define GAME__NULL_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags -are in game_quake3.h - -------------------------------------------------------------------------------- */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - NULL, /* -game x */ - NULL, /* default base game data dir */ - NULL, /* unix home sub-dir */ - NULL, /* magic path word */ - NULL, /* shader directory */ - 0, /* max lightmapped surface verts */ - 0, /* max surface verts */ - 0, /* max surface indexes */ - qfalse, /* flares */ - NULL, /* default flare shader */ - qfalse, /* wolf lighting model? */ - 0, /* lightmap width/height */ - 0, /* lightmap gamma */ - 0, /* lightmap exposure */ - 0, /* lightmap compensate */ - 0, /* lightgrid scale */ - 0, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 0, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 0, /* minimap size */ - 0, /* minimap sharpener */ - 0, /* minimap border */ - qfalse, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - NULL, /* minimap name format */ - NULL, /* bsp file prefix */ - 0, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - NULL, /* bsp load function */ - NULL, /* bsp write function */ - - { - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_darkplaces.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_darkplaces.h deleted file mode 100644 index e91fdb76..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_darkplaces.h +++ /dev/null @@ -1,150 +0,0 @@ -/* ------------------------------------------------------------------------------- - -Copyright (C) 1999-2006 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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_DARKPLACES_H -#define GAME_DARKPLACES_H - -/* content and surface flags get form quake3 */ - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "darkplaces", /* -game x */ - "id1", /* default base game data dir */ - ".darkplaces ", /* unix home sub-dir */ - "darkplaces", /* magic path word */ - "scripts", /* shader directory */ - 999, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 200.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 0.3f, /* lightgrid scale */ - 0.6f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qtrue, /* disable shader lightstyles hack */ - qtrue, /* keep light entities on bsp */ - 4, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_dq.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_dq.h deleted file mode 100644 index 97d2d6d5..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_dq.h +++ /dev/null @@ -1,150 +0,0 @@ -/* ------------------------------------------------------------------------------- - -Copyright (C) 1999-2006 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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_DQ_H -#define GAME_DQ_H - -/* content and surface flags get form quake3 */ - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "dq", /* -game x */ - "basedq", /* default base game data dir */ - ".dq", /* unix home sub-dir */ - "dq", /* magic path word */ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.2f, /* lightmap gamma */ - 200.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 0.3f, /* lightgrid scale */ - 0.6f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qtrue, /* disable shader lightstyles hack */ - qtrue, /* keep light entities on bsp */ - 4, /* default patchMeta subdivisions tolerance */ - qtrue, /* patch casting enabled */ - qtrue, /* compile deluxemaps */ - 1, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_ef.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_ef.h deleted file mode 100644 index 84ea664c..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_ef.h +++ /dev/null @@ -1,210 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_EF_H -#define GAME_EF_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* game flags */ -#define E_CONT_SOLID 1 /* an eye is never valid in a solid */ -#define E_CONT_LAVA 8 -#define E_CONT_SLIME 16 -#define E_CONT_WATER 32 -#define E_CONT_FOG 64 -#define E_CONT_LADDER 128 /* elite force ladder contents */ - -#define E_CONT_AREAPORTAL 0x8000 - -#define E_CONT_PLAYERCLIP 0x10000 -#define E_CONT_MONSTERCLIP 0x20000 -#define E_CONT_SHOTCLIP 0x40000 /* elite force shot clip */ -#define E_CONT_ITEM 0x80000 -#define E_CONT_CLUSTERPORTAL 0x100000 -#define E_CONT_DONOTENTER 0x200000 -#define E_CONT_BOTCLIP 0x400000 - -#define E_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ - -#define E_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ -#define E_CONT_CORPSE 0x4000000 -#define E_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ -#define E_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ -#define E_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ -#define E_CONT_TRIGGER 0x40000000 -#define E_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ - -#define E_SURF_NODAMAGE 0x1 /* never give falling damage */ -#define E_SURF_SLICK 0x2 /* effects game physics */ -#define E_SURF_SKY 0x4 /* lighting from environment map */ -#define E_SURF_LADDER 0x8 -#define E_SURF_NOIMPACT 0x10 /* don't make missile explosions */ -#define E_SURF_NOMARKS 0x20 /* don't leave missile marks */ -#define E_SURF_FLESH 0x40 /* make flesh sounds and effects */ -#define E_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ -#define E_SURF_HINT 0x100 /* make a primary bsp splitter */ -#define E_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ -#define E_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ -#define E_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ -#define E_SURF_METALSTEPS 0x1000 /* clanking footsteps */ -#define E_SURF_NOSTEPS 0x2000 /* no footstep sounds */ -#define E_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ -#define E_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ -#define E_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ -#define E_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ -#define E_SURF_FORCEFIELD 0x40000 /* elite force forcefield brushes */ - -/* ydnar flags */ -#define E_SURF_VERTEXLIT (E_SURF_POINTLIGHT | E_SURF_NOLIGHTMAP) - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "ef", /* -game x */ - "baseef", /* default base game data dir */ - ".ef", /* unix home sub-dir */ - "elite", /* magic path word */ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", E_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", E_CONT_ORIGIN, E_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", E_CONT_AREAPORTAL, E_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", E_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", E_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", E_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, E_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, E_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, E_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, E_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, E_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, E_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, E_CONT_SOLID, E_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", E_CONT_TRIGGER, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", E_CONT_WATER, E_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", E_CONT_SLIME, E_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", E_CONT_LAVA, E_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", E_CONT_PLAYERCLIP, E_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", E_CONT_MONSTERCLIP, E_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "shotclip", E_CONT_SHOTCLIP, E_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", E_CONT_NODROP, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", E_CONT_CLUSTERPORTAL, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", E_CONT_DONOTENTER, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", E_CONT_BOTCLIP, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", E_CONT_FOG, E_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, E_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, E_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, E_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, E_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", E_CONT_LADDER, E_CONT_SOLID, E_SURF_LADDER, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodamage", 0, 0, E_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, E_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, E_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, E_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, E_SURF_NODLIGHT, 0, 0, 0 }, - { "forcefield", 0, 0, E_SURF_FORCEFIELD, 0, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_etut.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_etut.h deleted file mode 100644 index 8add5bbe..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_etut.h +++ /dev/null @@ -1,280 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_ETUT_H -#define GAME_ETUT_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* game flags */ -#define U_CONT_SOLID 1 /* an eye is never valid in a solid */ -#define U_CONT_LAVA 8 -#define U_CONT_SLIME 16 -#define U_CONT_WATER 32 -#define U_CONT_FOG 64 - -#define U_CONT_AREAPORTAL 0x8000 - -#define U_CONT_PLAYERCLIP 0x10000 -#define U_CONT_MONSTERCLIP 0x20000 -#define U_CONT_TELEPORTER 0x40000 -#define U_CONT_JUMPPAD 0x80000 -#define U_CONT_CLUSTERPORTAL 0x100000 -#define U_CONT_DONOTENTER 0x200000 -#define U_CONT_BOTCLIP 0x400000 - -#define U_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ - -#define U_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ -#define U_CONT_CORPSE 0x4000000 -#define U_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ -#define U_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ -#define U_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ -#define U_CONT_TRIGGER 0x40000000 -#define U_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ - -#define U_SURF_NODAMAGE 0x1 /* never give falling damage */ -#define U_SURF_SLICK 0x2 /* effects game physics */ -#define U_SURF_SKY 0x4 /* lighting from environment map */ -#define U_SURF_LADDER 0x8 -#define U_SURF_NOIMPACT 0x10 /* don't make missile explosions */ -#define U_SURF_NOMARKS 0x20 /* don't leave missile marks */ -#define U_SURF_FLESH 0x40 /* make flesh sounds and effects */ -#define U_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ -#define U_SURF_HINT 0x100 /* make a primary bsp splitter */ -#define U_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ -#define U_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ -#define U_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ -#define U_SURF_METALSTEPS 0x1000 /* clanking footsteps */ -#define U_SURF_NOSTEPS 0x2000 /* no footstep sounds */ -#define U_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ -#define U_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ -#define U_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ -#define U_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ -#define U_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ - -/* ydnar flags */ -#define U_SURF_VERTEXLIT (U_SURF_POINTLIGHT | U_SURF_NOLIGHTMAP) - -/* materials */ -#define U_MAT_MASK 0xFFF00000 /* mask to get the material type */ - -#define U_MAT_NONE 0x00000000 -#define U_MAT_TIN 0x00100000 -#define U_MAT_ALUMINUM 0x00200000 -#define U_MAT_IRON 0x00300000 -#define U_MAT_TITANIUM 0x00400000 -#define U_MAT_STEEL 0x00500000 -#define U_MAT_BRASS 0x00600000 -#define U_MAT_COPPER 0x00700000 -#define U_MAT_CEMENT 0x00800000 -#define U_MAT_ROCK 0x00900000 -#define U_MAT_GRAVEL 0x00A00000 -#define U_MAT_PAVEMENT 0x00B00000 -#define U_MAT_BRICK 0x00C00000 -#define U_MAT_CLAY 0x00D00000 -#define U_MAT_GRASS 0x00E00000 -#define U_MAT_DIRT 0x00F00000 -#define U_MAT_MUD 0x01000000 -#define U_MAT_SNOW 0x01100000 -#define U_MAT_ICE 0x01200000 -#define U_MAT_SAND 0x01300000 -#define U_MAT_CERAMICTILE 0x01400000 -#define U_MAT_LINOLEUM 0x01500000 -#define U_MAT_RUG 0x01600000 -#define U_MAT_PLASTER 0x01700000 -#define U_MAT_PLASTIC 0x01800000 -#define U_MAT_CARDBOARD 0x01900000 -#define U_MAT_HARDWOOD 0x01A00000 -#define U_MAT_SOFTWOOD 0x01B00000 -#define U_MAT_PLANK 0x01C00000 -#define U_MAT_GLASS 0x01D00000 -#define U_MAT_WATER 0x01E00000 -#define U_MAT_STUCCO 0x01F00000 - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "etut", /* -game x */ - "etut", /* default base game data dir */ - ".etwolf", /* unix home sub-dir */ - "et", /* magic path word */ - "scripts", /* shader directory */ - 1024, /* max lightmapped surface verts */ - 1024, /* max surface verts */ - 6144, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 2.2f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 47, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", U_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", U_CONT_ORIGIN, U_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", U_CONT_AREAPORTAL, U_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", U_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", U_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", U_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, U_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, U_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, U_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, U_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, U_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, U_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, U_CONT_SOLID, U_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", U_CONT_TRIGGER, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", U_CONT_WATER, U_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", U_CONT_SLIME, U_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", U_CONT_LAVA, U_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", U_CONT_PLAYERCLIP, U_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", U_CONT_MONSTERCLIP, U_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", U_CONT_NODROP, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", U_CONT_CLUSTERPORTAL, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", U_CONT_DONOTENTER, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", U_CONT_BOTCLIP, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", U_CONT_FOG, U_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, U_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, U_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, U_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, U_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, U_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, U_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, U_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, U_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, U_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, U_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, U_SURF_DUST, 0, 0, 0 }, - - - /* materials */ - { "*mat_none", 0, 0, U_MAT_NONE, U_MAT_MASK, 0, 0 }, - { "*mat_tin", 0, 0, U_MAT_TIN, U_MAT_MASK, 0, 0 }, - { "*mat_aluminum", 0, 0, U_MAT_ALUMINUM, U_MAT_MASK, 0, 0 }, - { "*mat_iron", 0, 0, U_MAT_IRON, U_MAT_MASK, 0, 0 }, - { "*mat_titanium", 0, 0, U_MAT_TITANIUM, U_MAT_MASK, 0, 0 }, - { "*mat_steel", 0, 0, U_MAT_STEEL, U_MAT_MASK, 0, 0 }, - { "*mat_brass", 0, 0, U_MAT_BRASS, U_MAT_MASK, 0, 0 }, - { "*mat_copper", 0, 0, U_MAT_COPPER, U_MAT_MASK, 0, 0 }, - { "*mat_cement", 0, 0, U_MAT_CEMENT, U_MAT_MASK, 0, 0 }, - { "*mat_rock", 0, 0, U_MAT_ROCK, U_MAT_MASK, 0, 0 }, - { "*mat_gravel", 0, 0, U_MAT_GRAVEL, U_MAT_MASK, 0, 0 }, - { "*mat_pavement", 0, 0, U_MAT_PAVEMENT, U_MAT_MASK, 0, 0 }, - { "*mat_brick", 0, 0, U_MAT_BRICK, U_MAT_MASK, 0, 0 }, - { "*mat_clay", 0, 0, U_MAT_CLAY, U_MAT_MASK, 0, 0 }, - { "*mat_grass", 0, 0, U_MAT_GRASS, U_MAT_MASK, 0, 0 }, - { "*mat_dirt", 0, 0, U_MAT_DIRT, U_MAT_MASK, 0, 0 }, - { "*mat_mud", 0, 0, U_MAT_MUD, U_MAT_MASK, 0, 0 }, - { "*mat_snow", 0, 0, U_MAT_SNOW, U_MAT_MASK, 0, 0 }, - { "*mat_ice", 0, 0, U_MAT_ICE, U_MAT_MASK, 0, 0 }, - { "*mat_sand", 0, 0, U_MAT_SAND, U_MAT_MASK, 0, 0 }, - { "*mat_ceramic", 0, 0, U_MAT_CERAMICTILE, U_MAT_MASK, 0, 0 }, - { "*mat_ceramictile", 0, 0, U_MAT_CERAMICTILE, U_MAT_MASK, 0, 0 }, - { "*mat_linoleum", 0, 0, U_MAT_LINOLEUM, U_MAT_MASK, 0, 0 }, - { "*mat_rug", 0, 0, U_MAT_RUG, U_MAT_MASK, 0, 0 }, - { "*mat_plaster", 0, 0, U_MAT_PLASTER, U_MAT_MASK, 0, 0 }, - { "*mat_plastic", 0, 0, U_MAT_PLASTIC, U_MAT_MASK, 0, 0 }, - { "*mat_cardboard", 0, 0, U_MAT_CARDBOARD, U_MAT_MASK, 0, 0 }, - { "*mat_hardwood", 0, 0, U_MAT_HARDWOOD, U_MAT_MASK, 0, 0 }, - { "*mat_softwood", 0, 0, U_MAT_SOFTWOOD, U_MAT_MASK, 0, 0 }, - { "*mat_plank", 0, 0, U_MAT_PLANK, U_MAT_MASK, 0, 0 }, - { "*mat_glass", 0, 0, U_MAT_GLASS, U_MAT_MASK, 0, 0 }, - { "*mat_water", 0, 0, U_MAT_WATER, U_MAT_MASK, 0, 0 }, - { "*mat_stucco", 0, 0, U_MAT_STUCCO, U_MAT_MASK, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_ja.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_ja.h deleted file mode 100644 index 3d25129e..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_ja.h +++ /dev/null @@ -1,204 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_JA_H -#define GAME_JA_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* this file must be included *after* game_sof2.h and game_jk2.h because they share defines! */ - -#define JA_CONT_INSIDE 0x10000000 /* jedi academy 'inside' */ -#define JA_SURF_FORCESIGHT 0x02000000 /* jedi academy 'forcesight' */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "ja", /* -game x */ - "base", /* default base game data dir */ - ".ja", /* unix home sub-dir */ - "GameData", /* magic path word */ - "shaders", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qtrue, /* flares */ - "gfx/misc/flare", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "RBSP", /* bsp file prefix */ - 1, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadRBSPFile, /* bsp load function */ - WriteRBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", S_CONT_SOLID | S_CONT_OPAQUE, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", 0, S_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", S_CONT_TRANSLUCENT, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", S_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", S_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", 0, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, 0, 0, C_HINT, 0 }, - { "nodraw", 0, 0, S_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, 0, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, 0, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, 0, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, 0, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, S_CONT_SOLID, 0, 0, 0, C_SOLID }, - { "nonopaque", 0, S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, 0 }, /* setting trans ok? */ - - { "trigger", S_CONT_TRIGGER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", S_CONT_WATER, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", S_CONT_SLIME, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", S_CONT_LAVA, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "shotclip", S_CONT_SHOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* setting trans/detail ok? */ - { "playerclip", S_CONT_PLAYERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", S_CONT_MONSTERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", S_CONT_NODROP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "terrain", S_CONT_TERRAIN, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "ladder", S_CONT_LADDER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "abseil", S_CONT_ABSEIL, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "outside", S_CONT_OUTSIDE, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "botclip", S_CONT_BOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "fog", S_CONT_FOG, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_FOG | C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* nonopaque? */ - { "sky", 0, 0, S_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, S_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, S_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, S_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "nodamage", 0, 0, S_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, S_SURF_METALSTEPS, 0, 0, 0 }, - { "nosteps", 0, 0, S_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, S_SURF_NODLIGHT, 0, 0, 0 }, - { "nomiscents", 0, 0, S_SURF_NOMISCENTS, 0, 0, 0 }, - { "forcefield", 0, 0, S_SURF_FORCEFIELD, 0, 0, 0 }, - - /* jedi academy */ - { "inside", JA_CONT_INSIDE, 0, 0, 0, 0, 0 }, - { "forcesight", 0, 0, JA_SURF_FORCESIGHT, 0, 0, 0 }, - - /* materials */ - { "*mat_none", 0, 0, S_MAT_NONE, S_MAT_MASK, 0, 0 }, - { "*mat_solidwood", 0, 0, S_MAT_SOLIDWOOD, S_MAT_MASK, 0, 0 }, - { "*mat_hollowwood", 0, 0, S_MAT_HOLLOWWOOD, S_MAT_MASK, 0, 0 }, - { "*mat_solidmetal", 0, 0, S_MAT_SOLIDMETAL, S_MAT_MASK, 0, 0 }, - { "*mat_hollowmetal", 0, 0, S_MAT_HOLLOWMETAL, S_MAT_MASK, 0, 0 }, - { "*mat_shortgrass", 0, 0, S_MAT_SHORTGRASS, S_MAT_MASK, 0, 0 }, - { "*mat_longgrass", 0, 0, S_MAT_LONGGRASS, S_MAT_MASK, 0, 0 }, - { "*mat_dirt", 0, 0, S_MAT_DIRT, S_MAT_MASK, 0, 0 }, - { "*mat_sand", 0, 0, S_MAT_SAND, S_MAT_MASK, 0, 0 }, - { "*mat_gravel", 0, 0, S_MAT_GRAVEL, S_MAT_MASK, 0, 0 }, - { "*mat_glass", 0, 0, S_MAT_GLASS, S_MAT_MASK, 0, 0 }, - { "*mat_concrete", 0, 0, S_MAT_CONCRETE, S_MAT_MASK, 0, 0 }, - { "*mat_marble", 0, 0, S_MAT_MARBLE, S_MAT_MASK, 0, 0 }, - { "*mat_water", 0, 0, S_MAT_WATER, S_MAT_MASK, 0, 0 }, - { "*mat_snow", 0, 0, S_MAT_SNOW, S_MAT_MASK, 0, 0 }, - { "*mat_ice", 0, 0, S_MAT_ICE, S_MAT_MASK, 0, 0 }, - { "*mat_flesh", 0, 0, S_MAT_FLESH, S_MAT_MASK, 0, 0 }, - { "*mat_mud", 0, 0, S_MAT_MUD, S_MAT_MASK, 0, 0 }, - { "*mat_bpglass", 0, 0, S_MAT_BPGLASS, S_MAT_MASK, 0, 0 }, - { "*mat_dryleaves", 0, 0, S_MAT_DRYLEAVES, S_MAT_MASK, 0, 0 }, - { "*mat_greenleaves", 0, 0, S_MAT_GREENLEAVES, S_MAT_MASK, 0, 0 }, - { "*mat_fabric", 0, 0, S_MAT_FABRIC, S_MAT_MASK, 0, 0 }, - { "*mat_canvas", 0, 0, S_MAT_CANVAS, S_MAT_MASK, 0, 0 }, - { "*mat_rock", 0, 0, S_MAT_ROCK, S_MAT_MASK, 0, 0 }, - { "*mat_rubber", 0, 0, S_MAT_RUBBER, S_MAT_MASK, 0, 0 }, - { "*mat_plastic", 0, 0, S_MAT_PLASTIC, S_MAT_MASK, 0, 0 }, - { "*mat_tiles", 0, 0, S_MAT_TILES, S_MAT_MASK, 0, 0 }, - { "*mat_carpet", 0, 0, S_MAT_CARPET, S_MAT_MASK, 0, 0 }, - { "*mat_plaster", 0, 0, S_MAT_PLASTER, S_MAT_MASK, 0, 0 }, - { "*mat_shatterglass", 0, 0, S_MAT_SHATTERGLASS, S_MAT_MASK, 0, 0 }, - { "*mat_armor", 0, 0, S_MAT_ARMOR, S_MAT_MASK, 0, 0 }, - { "*mat_computer", 0, 0, S_MAT_COMPUTER, S_MAT_MASK, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_jk2.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_jk2.h deleted file mode 100644 index 056baf01..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_jk2.h +++ /dev/null @@ -1,198 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_JK2_H -#define GAME_JK2_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* this file must be included *after* game_sof2.h because it shares defines! */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "jk2", /* -game x */ - "base", /* default base game data dir */ - ".jk2", /* unix home sub-dir */ - "GameData", /* magic path word */ - "shaders", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qtrue, /* flares */ - "gfx/misc/flare", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "RBSP", /* bsp file prefix */ - 1, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadRBSPFile, /* bsp load function */ - WriteRBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", S_CONT_SOLID | S_CONT_OPAQUE, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", 0, S_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", S_CONT_TRANSLUCENT, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", S_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", S_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", 0, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, 0, 0, C_HINT, 0 }, - { "nodraw", 0, 0, S_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, 0, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, 0, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, 0, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, 0, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, S_CONT_SOLID, 0, 0, 0, C_SOLID }, - { "nonopaque", 0, S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, 0 }, /* setting trans ok? */ - - { "trigger", S_CONT_TRIGGER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", S_CONT_WATER, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", S_CONT_SLIME, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", S_CONT_LAVA, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "shotclip", S_CONT_SHOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* setting trans/detail ok? */ - { "playerclip", S_CONT_PLAYERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", S_CONT_MONSTERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", S_CONT_NODROP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "terrain", S_CONT_TERRAIN, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "ladder", S_CONT_LADDER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "abseil", S_CONT_ABSEIL, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "outside", S_CONT_OUTSIDE, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "botclip", S_CONT_BOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "fog", S_CONT_FOG, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_FOG | C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* nonopaque? */ - { "sky", 0, 0, S_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, S_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, S_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, S_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "nodamage", 0, 0, S_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, S_SURF_METALSTEPS, 0, 0, 0 }, - { "nosteps", 0, 0, S_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, S_SURF_NODLIGHT, 0, 0, 0 }, - { "nomiscents", 0, 0, S_SURF_NOMISCENTS, 0, 0, 0 }, - { "forcefield", 0, 0, S_SURF_FORCEFIELD, 0, 0, 0 }, - - - /* materials */ - { "*mat_none", 0, 0, S_MAT_NONE, S_MAT_MASK, 0, 0 }, - { "*mat_solidwood", 0, 0, S_MAT_SOLIDWOOD, S_MAT_MASK, 0, 0 }, - { "*mat_hollowwood", 0, 0, S_MAT_HOLLOWWOOD, S_MAT_MASK, 0, 0 }, - { "*mat_solidmetal", 0, 0, S_MAT_SOLIDMETAL, S_MAT_MASK, 0, 0 }, - { "*mat_hollowmetal", 0, 0, S_MAT_HOLLOWMETAL, S_MAT_MASK, 0, 0 }, - { "*mat_shortgrass", 0, 0, S_MAT_SHORTGRASS, S_MAT_MASK, 0, 0 }, - { "*mat_longgrass", 0, 0, S_MAT_LONGGRASS, S_MAT_MASK, 0, 0 }, - { "*mat_dirt", 0, 0, S_MAT_DIRT, S_MAT_MASK, 0, 0 }, - { "*mat_sand", 0, 0, S_MAT_SAND, S_MAT_MASK, 0, 0 }, - { "*mat_gravel", 0, 0, S_MAT_GRAVEL, S_MAT_MASK, 0, 0 }, - { "*mat_glass", 0, 0, S_MAT_GLASS, S_MAT_MASK, 0, 0 }, - { "*mat_concrete", 0, 0, S_MAT_CONCRETE, S_MAT_MASK, 0, 0 }, - { "*mat_marble", 0, 0, S_MAT_MARBLE, S_MAT_MASK, 0, 0 }, - { "*mat_water", 0, 0, S_MAT_WATER, S_MAT_MASK, 0, 0 }, - { "*mat_snow", 0, 0, S_MAT_SNOW, S_MAT_MASK, 0, 0 }, - { "*mat_ice", 0, 0, S_MAT_ICE, S_MAT_MASK, 0, 0 }, - { "*mat_flesh", 0, 0, S_MAT_FLESH, S_MAT_MASK, 0, 0 }, - { "*mat_mud", 0, 0, S_MAT_MUD, S_MAT_MASK, 0, 0 }, - { "*mat_bpglass", 0, 0, S_MAT_BPGLASS, S_MAT_MASK, 0, 0 }, - { "*mat_dryleaves", 0, 0, S_MAT_DRYLEAVES, S_MAT_MASK, 0, 0 }, - { "*mat_greenleaves", 0, 0, S_MAT_GREENLEAVES, S_MAT_MASK, 0, 0 }, - { "*mat_fabric", 0, 0, S_MAT_FABRIC, S_MAT_MASK, 0, 0 }, - { "*mat_canvas", 0, 0, S_MAT_CANVAS, S_MAT_MASK, 0, 0 }, - { "*mat_rock", 0, 0, S_MAT_ROCK, S_MAT_MASK, 0, 0 }, - { "*mat_rubber", 0, 0, S_MAT_RUBBER, S_MAT_MASK, 0, 0 }, - { "*mat_plastic", 0, 0, S_MAT_PLASTIC, S_MAT_MASK, 0, 0 }, - { "*mat_tiles", 0, 0, S_MAT_TILES, S_MAT_MASK, 0, 0 }, - { "*mat_carpet", 0, 0, S_MAT_CARPET, S_MAT_MASK, 0, 0 }, - { "*mat_plaster", 0, 0, S_MAT_PLASTER, S_MAT_MASK, 0, 0 }, - { "*mat_shatterglass", 0, 0, S_MAT_SHATTERGLASS, S_MAT_MASK, 0, 0 }, - { "*mat_armor", 0, 0, S_MAT_ARMOR, S_MAT_MASK, 0, 0 }, - { "*mat_computer", 0, 0, S_MAT_COMPUTER, S_MAT_MASK, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_nexuiz.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_nexuiz.h deleted file mode 100644 index 4d496c33..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_nexuiz.h +++ /dev/null @@ -1,159 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_NEXUIZ_H -#define GAME_NEXUIZ_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags -are in game_quake3.h - -------------------------------------------------------------------------------- */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "nexuiz", /* -game x */ - "data", /* default base game data dir */ - ".nexuiz", /* unix home sub-dir */ - "nexuiz", /* magic path word */ - "scripts", /* shader directory */ - 999, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qtrue, /* disable shader lightstyles hack */ - qtrue, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 1.0f/66.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "../gfx/%s_mini.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_prophecy.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_prophecy.h deleted file mode 100644 index 60e299d3..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_prophecy.h +++ /dev/null @@ -1,150 +0,0 @@ -/* ------------------------------------------------------------------------------- - -Copyright (C) 1999-2006 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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_PROPHECY_H -#define GAME_PROPHECY_H - -/* content and surface flags get form quake3 */ - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "prophecy", /* -game x */ - "base", /* default base game data dir */ - ".prophecy", /* unix home sub-dir */ - "prophecy", /* magic path word */ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 200.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 0.4f, /* lightgrid scale */ - 0.6f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qtrue, /* disable shader lightstyles hack */ - qtrue, /* keep light entities on bsp */ - 4, /* default patchMeta subdivisions tolerance */ - qtrue, /* patch casting enabled */ - qtrue, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_qfusion.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_qfusion.h deleted file mode 100644 index 7645ad0a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_qfusion.h +++ /dev/null @@ -1,211 +0,0 @@ -/* ------------------------------------------------------------------------------- - -This code is based on source provided under the terms of the Id Software -LIMITED USE SOFTWARE LICENSE AGREEMENT, a copy of which is included with the -GtkRadiant sources (see LICENSE_ID). If you did not receive a copy of -LICENSE_ID, please contact Id Software immediately at info@idsoftware.com. - -All changes and additions to the original source which have been developed by -other contributors (see CONTRIBUTORS) are provided under the terms of the -license the contributors choose (see LICENSE), to the extent permitted by the -LICENSE_ID. If you did not receive a copy of the contributor license, -please contact the GtkRadiant maintainers at info@gtkradiant.com immediately. - -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. - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_QFUSION_H -#define GAME_QFUSION_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* game flags */ -#define F_CONT_SOLID 1 /* an eye is never valid in a solid */ -#define F_CONT_LAVA 8 -#define F_CONT_SLIME 16 -#define F_CONT_WATER 32 -#define F_CONT_FOG 64 - -#define F_CONT_AREAPORTAL 0x8000 - -#define F_CONT_PLAYERCLIP 0x10000 -#define F_CONT_MONSTERCLIP 0x20000 -#define F_CONT_TELEPORTER 0x40000 -#define F_CONT_JUMPPAD 0x80000 -#define F_CONT_CLUSTERPORTAL 0x100000 -#define F_CONT_DONOTENTER 0x200000 -#define F_CONT_BOTCLIP 0x400000 - -#define F_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ - -#define F_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ -#define F_CONT_CORPSE 0x4000000 -#define F_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ -#define F_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ -#define F_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ -#define F_CONT_TRIGGER 0x40000000 -#define F_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ - -#define F_SURF_NODAMAGE 0x1 /* never give falling damage */ -#define F_SURF_SLICK 0x2 /* effects game physics */ -#define F_SURF_SKY 0x4 /* lighting from environment map */ -#define F_SURF_LADDER 0x8 -#define F_SURF_NOIMPACT 0x10 /* don't make missile explosions */ -#define F_SURF_NOMARKS 0x20 /* don't leave missile marks */ -#define F_SURF_FLESH 0x40 /* make flesh sounds and effects */ -#define F_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ -#define F_SURF_HINT 0x100 /* make a primary bsp splitter */ -#define F_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ -#define F_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ -#define F_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ -#define F_SURF_METALSTEPS 0x1000 /* clanking footsteps */ -#define F_SURF_NOSTEPS 0x2000 /* no footstep sounds */ -#define F_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ -#define F_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ -#define F_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ -#define F_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ -#define F_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ - -/* ydnar flags */ -#define F_SURF_VERTEXLIT (F_SURF_POINTLIGHT | F_SURF_NOLIGHTMAP) - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "qfusion", /* -game x */ - "baseq3", /* default base game data dir */ - ".q3a", /* unix home sub-dir */ - "quake", /* magic path word */ - "scripts", /* shader directory */ - 2048, /* max lightmapped surface verts */ - 2048, /* max surface verts */ - 12288, /* max surface indexes */ - qtrue, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 512, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qtrue, /* light angle attenuation uses half-lambert curve */ - qtrue, /* disable shader lightstyles hack */ - qtrue, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qtrue, /* patch casting enabled */ - qtrue, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 256, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_WHITE, /* minimap mode */ - "../minimaps/%s.tga", /* minimap name format */ - "FBSP", /* bsp file prefix */ - 1, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadRBSPFile, /* bsp load function */ - WriteRBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", F_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", F_CONT_ORIGIN, F_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", F_CONT_AREAPORTAL, F_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", F_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", F_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", F_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, F_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, F_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, F_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, F_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, F_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, F_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, F_CONT_SOLID, F_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", F_CONT_TRIGGER, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", F_CONT_WATER, F_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", F_CONT_SLIME, F_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", F_CONT_LAVA, F_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", F_CONT_PLAYERCLIP, F_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", F_CONT_MONSTERCLIP, F_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", F_CONT_NODROP, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", F_CONT_CLUSTERPORTAL, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", F_CONT_DONOTENTER, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", F_CONT_BOTCLIP, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", F_CONT_FOG, F_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, F_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, F_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, F_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, F_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, F_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, F_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, F_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, F_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, F_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, F_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, F_SURF_DUST, 0, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_quake3.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_quake3.h deleted file mode 100644 index 98d4c4b8..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_quake3.h +++ /dev/null @@ -1,207 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_QUAKE3_H -#define GAME_QUAKE3_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* game flags */ -#define Q_CONT_SOLID 1 /* an eye is never valid in a solid */ -#define Q_CONT_LAVA 8 -#define Q_CONT_SLIME 16 -#define Q_CONT_WATER 32 -#define Q_CONT_FOG 64 - -#define Q_CONT_AREAPORTAL 0x8000 - -#define Q_CONT_PLAYERCLIP 0x10000 -#define Q_CONT_MONSTERCLIP 0x20000 -#define Q_CONT_TELEPORTER 0x40000 -#define Q_CONT_JUMPPAD 0x80000 -#define Q_CONT_CLUSTERPORTAL 0x100000 -#define Q_CONT_DONOTENTER 0x200000 -#define Q_CONT_BOTCLIP 0x400000 - -#define Q_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ - -#define Q_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ -#define Q_CONT_CORPSE 0x4000000 -#define Q_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ -#define Q_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ -#define Q_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ -#define Q_CONT_TRIGGER 0x40000000 -#define Q_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ - -#define Q_SURF_NODAMAGE 0x1 /* never give falling damage */ -#define Q_SURF_SLICK 0x2 /* effects game physics */ -#define Q_SURF_SKY 0x4 /* lighting from environment map */ -#define Q_SURF_LADDER 0x8 -#define Q_SURF_NOIMPACT 0x10 /* don't make missile explosions */ -#define Q_SURF_NOMARKS 0x20 /* don't leave missile marks */ -#define Q_SURF_FLESH 0x40 /* make flesh sounds and effects */ -#define Q_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ -#define Q_SURF_HINT 0x100 /* make a primary bsp splitter */ -#define Q_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ -#define Q_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ -#define Q_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ -#define Q_SURF_METALSTEPS 0x1000 /* clanking footsteps */ -#define Q_SURF_NOSTEPS 0x2000 /* no footstep sounds */ -#define Q_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ -#define Q_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ -#define Q_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ -#define Q_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ -#define Q_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ - -/* ydnar flags */ -#define Q_SURF_VERTEXLIT (Q_SURF_POINTLIGHT | Q_SURF_NOLIGHTMAP) - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "quake3", /* -game x */ - "baseq3", /* default base game data dir */ - ".q3a", /* unix home sub-dir */ - "quake", /* magic path word */ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_quakelive.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_quakelive.h deleted file mode 100644 index 1a509272..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_quakelive.h +++ /dev/null @@ -1,159 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_QUAKELIVE_H -#define GAME_QUAKELIVE_H - - - -/* ------------------------------------------------------------------------------- - -no content and surface flags here -they are the same as Quake 3's -(this file must be included AFTER game_quake3.h) - -------------------------------------------------------------------------------- */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "quakelive", /* -game x */ - "baseq3", /* default base game data dir (FIXME what does quake live really use?) */ - ".q3a", /* unix home sub-dir (FIXME what does quake live really use?) */ - "quake", /* magic path word (FIXME where does quake live install to?) */ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 47, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_reaction.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_reaction.h deleted file mode 100644 index c81e7245..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_reaction.h +++ /dev/null @@ -1,194 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_REACTION_H -#define GAME_REACTION_H - - - -/* ------------------------------------------------------------------------------- - -inherit content and surface flags from game_quake3.h -(this file must be included AFTER game_quake3.h) - -Additional surface flags follow. These were given to me (Rambetter) by TTI from the Reaction team. -Note that some of these values have more than one bit set. I'm not sure how Reaction is using these -bits, but this is what I got from TTI. - -------------------------------------------------------------------------------- */ - -#define REACTION_SURF_GRAVEL 0x80000 -#define REACTION_SURF_WOOD 0x81000 -#define REACTION_SURF_CARPET 0x100000 -#define REACTION_SURF_METAL2 0x101000 -#define REACTION_SURF_GLASS 0x180000 -#define REACTION_SURF_GRASS 0x181000 -#define REACTION_SURF_SNOW 0x200000 -#define REACTION_SURF_MUD 0x201000 -#define REACTION_SURF_WOOD2 0x280000 -#define REACTION_SURF_HARDMETAL 0x281000 -#define REACTION_SURF_LEAVES 0x300000 -#define REACTION_SURF_CEMENT 0x301000 -#define REACTION_SURF_MARBLE 0x380000 -#define REACTION_SURF_SNOW2 0x381000 -#define REACTION_SURF_HARDSTEPS 0x400000 -#define REACTION_SURF_SAND 0x401000 - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "reaction", /* -game x */ - "Boomstick", /* default base game data dir */ - ".Reaction", /* unix home sub-dir */ - "reaction", /* magic path word */ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - { "rq3_gravel", 0, 0, REACTION_SURF_GRAVEL, 0, 0, 0 }, - { "rq3_wood", 0, 0, REACTION_SURF_WOOD, 0, 0, 0 }, - { "rq3_carpet", 0, 0, REACTION_SURF_CARPET, 0, 0, 0 }, - { "rq3_metal2", 0, 0, REACTION_SURF_METAL2, 0, 0, 0 }, - { "rq3_glass", 0, 0, REACTION_SURF_GLASS, 0, 0, 0 }, - { "rq3_grass", 0, 0, REACTION_SURF_GRASS, 0, 0, 0 }, - { "rq3_snow", 0, 0, REACTION_SURF_SNOW, 0, 0, 0 }, - { "rq3_mud", 0, 0, REACTION_SURF_MUD, 0, 0, 0 }, - { "rq3_wood2", 0, 0, REACTION_SURF_WOOD2, 0, 0, 0 }, - { "rq3_hardmetal", 0, 0, REACTION_SURF_HARDMETAL, 0, 0, 0 }, - { "rq3_leaves", 0, 0, REACTION_SURF_LEAVES, 0, 0, 0 }, - { "rq3_cement", 0, 0, REACTION_SURF_CEMENT, 0, 0, 0 }, - { "rq3_marble", 0, 0, REACTION_SURF_MARBLE, 0, 0, 0 }, - { "rq3_snow2", 0, 0, REACTION_SURF_SNOW2, 0, 0, 0 }, - { "rq3_hardsteps", 0, 0, REACTION_SURF_HARDSTEPS, 0, 0, 0 }, - { "rq3_sand", 0, 0, REACTION_SURF_SAND, 0, 0, 0 }, - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_sof2.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_sof2.h deleted file mode 100644 index 931ec69c..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_sof2.h +++ /dev/null @@ -1,273 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_SOF2_H -#define GAME_SOF2_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* thanks to the gracious fellows at raven */ -#define S_CONT_SOLID 0x00000001 /* Default setting. An eye is never valid in a solid */ -#define S_CONT_LAVA 0x00000002 -#define S_CONT_WATER 0x00000004 -#define S_CONT_FOG 0x00000008 -#define S_CONT_PLAYERCLIP 0x00000010 -#define S_CONT_MONSTERCLIP 0x00000020 -#define S_CONT_BOTCLIP 0x00000040 -#define S_CONT_SHOTCLIP 0x00000080 -#define S_CONT_BODY 0x00000100 /* should never be on a brush, only in game */ -#define S_CONT_CORPSE 0x00000200 /* should never be on a brush, only in game */ -#define S_CONT_TRIGGER 0x00000400 -#define S_CONT_NODROP 0x00000800 /* don't leave bodies or items (death fog, lava) */ -#define S_CONT_TERRAIN 0x00001000 /* volume contains terrain data */ -#define S_CONT_LADDER 0x00002000 -#define S_CONT_ABSEIL 0x00004000 /* used like ladder to define where an NPC can abseil */ -#define S_CONT_OPAQUE 0x00008000 /* defaults to on, when off, solid can be seen through */ -#define S_CONT_OUTSIDE 0x00010000 /* volume is considered to be in the outside (i.e. not indoors) */ -#define S_CONT_SLIME 0x00020000 /* don't be fooled. it may SAY "slime" but it really means "projectileclip" */ -#define S_CONT_LIGHTSABER 0x00040000 -#define S_CONT_TELEPORTER 0x00080000 -#define S_CONT_ITEM 0x00100000 -#define S_CONT_DETAIL 0x08000000 /* brushes not used for the bsp */ -#define S_CONT_TRANSLUCENT 0x80000000 /* don't consume surface fragments inside */ - -#define S_SURF_SKY 0x00002000 /* lighting from environment map */ -#define S_SURF_SLICK 0x00004000 /* affects game physics */ -#define S_SURF_METALSTEPS 0x00008000 /* chc needs this since we use same tools */ -#define S_SURF_FORCEFIELD 0x00010000 /* chc */ -#define S_SURF_NODAMAGE 0x00040000 /* never give falling damage */ -#define S_SURF_NOIMPACT 0x00080000 /* don't make missile explosions */ -#define S_SURF_NOMARKS 0x00100000 /* don't leave missile marks */ -#define S_SURF_NODRAW 0x00200000 /* don't generate a drawsurface at all */ -#define S_SURF_NOSTEPS 0x00400000 /* no footstep sounds */ -#define S_SURF_NODLIGHT 0x00800000 /* don't dlight even if solid (solid lava, skies) */ -#define S_SURF_NOMISCENTS 0x01000000 /* no client models allowed on this surface */ - -#define S_SURF_PATCH 0x80000000 /* mark this face as a patch(editor only) */ - -/* materials */ -#define S_MAT_BITS 5 -#define S_MAT_MASK 0x1f /* mask to get the material type */ - -#define S_MAT_NONE 0 /* for when the artist hasn't set anything up =) */ -#define S_MAT_SOLIDWOOD 1 /* freshly cut timber */ -#define S_MAT_HOLLOWWOOD 2 /* termite infested creaky wood */ -#define S_MAT_SOLIDMETAL 3 /* solid girders */ -#define S_MAT_HOLLOWMETAL 4 /* hollow metal machines */ -#define S_MAT_SHORTGRASS 5 /* manicured lawn */ -#define S_MAT_LONGGRASS 6 /* long jungle grass */ -#define S_MAT_DIRT 7 /* hard mud */ -#define S_MAT_SAND 8 /* sandy beach */ -#define S_MAT_GRAVEL 9 /* lots of small stones */ -#define S_MAT_GLASS 10 -#define S_MAT_CONCRETE 11 /* hardened concrete pavement */ -#define S_MAT_MARBLE 12 /* marble floors */ -#define S_MAT_WATER 13 /* light covering of water on a surface */ -#define S_MAT_SNOW 14 /* freshly laid snow */ -#define S_MAT_ICE 15 /* packed snow/solid ice */ -#define S_MAT_FLESH 16 /* hung meat, corpses in the world */ -#define S_MAT_MUD 17 /* wet soil */ -#define S_MAT_BPGLASS 18 /* bulletproof glass */ -#define S_MAT_DRYLEAVES 19 /* dried up leaves on the floor */ -#define S_MAT_GREENLEAVES 20 /* fresh leaves still on a tree */ -#define S_MAT_FABRIC 21 /* Cotton sheets */ -#define S_MAT_CANVAS 22 /* tent material */ -#define S_MAT_ROCK 23 -#define S_MAT_RUBBER 24 /* hard tire like rubber */ -#define S_MAT_PLASTIC 25 -#define S_MAT_TILES 26 /* tiled floor */ -#define S_MAT_CARPET 27 /* lush carpet */ -#define S_MAT_PLASTER 28 /* drywall style plaster */ -#define S_MAT_SHATTERGLASS 29 /* glass with the Crisis Zone style shattering */ -#define S_MAT_ARMOR 30 /* body armor */ -#define S_MAT_COMPUTER 31 /* computers/electronic equipment */ -#define S_MAT_LAST 32 /* number of materials */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "sof2", /* -game x */ - "base", /* default base game data dir */ - ".sof2", /* unix home sub-dir */ - "soldier", /* magic path word */ - "shaders", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qtrue, /* flares */ - "gfx/misc/lens_flare", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "RBSP", /* bsp file prefix */ - 1, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadRBSPFile, /* bsp load function */ - WriteRBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", S_CONT_SOLID | S_CONT_OPAQUE, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", 0, S_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", S_CONT_TRANSLUCENT, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", S_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", S_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", 0, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, 0, 0, C_HINT, 0 }, - { "nodraw", 0, 0, S_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, 0, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, 0, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, 0, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, 0, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, S_CONT_SOLID, 0, 0, 0, C_SOLID }, - { "nonopaque", 0, S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, 0 }, /* setting trans ok? */ - - { "trigger", S_CONT_TRIGGER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", S_CONT_WATER, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", S_CONT_SLIME, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", S_CONT_LAVA, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "shotclip", S_CONT_SHOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* setting trans/detail ok? */ - { "playerclip", S_CONT_PLAYERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", S_CONT_MONSTERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", S_CONT_NODROP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "terrain", S_CONT_TERRAIN, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "ladder", S_CONT_LADDER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "abseil", S_CONT_ABSEIL, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "outside", S_CONT_OUTSIDE, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "botclip", S_CONT_BOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - - { "fog", S_CONT_FOG, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_FOG | C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* nonopaque? */ - { "sky", 0, 0, S_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, S_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, S_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, S_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "nodamage", 0, 0, S_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, S_SURF_METALSTEPS, 0, 0, 0 }, - { "nosteps", 0, 0, S_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, S_SURF_NODLIGHT, 0, 0, 0 }, - { "nomiscents", 0, 0, S_SURF_NOMISCENTS, 0, 0, 0 }, - { "forcefield", 0, 0, S_SURF_FORCEFIELD, 0, 0, 0 }, - - - /* materials */ - { "*mat_none", 0, 0, S_MAT_NONE, S_MAT_MASK, 0, 0 }, - { "*mat_solidwood", 0, 0, S_MAT_SOLIDWOOD, S_MAT_MASK, 0, 0 }, - { "*mat_hollowwood", 0, 0, S_MAT_HOLLOWWOOD, S_MAT_MASK, 0, 0 }, - { "*mat_solidmetal", 0, 0, S_MAT_SOLIDMETAL, S_MAT_MASK, 0, 0 }, - { "*mat_hollowmetal", 0, 0, S_MAT_HOLLOWMETAL, S_MAT_MASK, 0, 0 }, - { "*mat_shortgrass", 0, 0, S_MAT_SHORTGRASS, S_MAT_MASK, 0, 0 }, - { "*mat_longgrass", 0, 0, S_MAT_LONGGRASS, S_MAT_MASK, 0, 0 }, - { "*mat_dirt", 0, 0, S_MAT_DIRT, S_MAT_MASK, 0, 0 }, - { "*mat_sand", 0, 0, S_MAT_SAND, S_MAT_MASK, 0, 0 }, - { "*mat_gravel", 0, 0, S_MAT_GRAVEL, S_MAT_MASK, 0, 0 }, - { "*mat_glass", 0, 0, S_MAT_GLASS, S_MAT_MASK, 0, 0 }, - { "*mat_concrete", 0, 0, S_MAT_CONCRETE, S_MAT_MASK, 0, 0 }, - { "*mat_marble", 0, 0, S_MAT_MARBLE, S_MAT_MASK, 0, 0 }, - { "*mat_water", 0, 0, S_MAT_WATER, S_MAT_MASK, 0, 0 }, - { "*mat_snow", 0, 0, S_MAT_SNOW, S_MAT_MASK, 0, 0 }, - { "*mat_ice", 0, 0, S_MAT_ICE, S_MAT_MASK, 0, 0 }, - { "*mat_flesh", 0, 0, S_MAT_FLESH, S_MAT_MASK, 0, 0 }, - { "*mat_mud", 0, 0, S_MAT_MUD, S_MAT_MASK, 0, 0 }, - { "*mat_bpglass", 0, 0, S_MAT_BPGLASS, S_MAT_MASK, 0, 0 }, - { "*mat_dryleaves", 0, 0, S_MAT_DRYLEAVES, S_MAT_MASK, 0, 0 }, - { "*mat_greenleaves", 0, 0, S_MAT_GREENLEAVES, S_MAT_MASK, 0, 0 }, - { "*mat_fabric", 0, 0, S_MAT_FABRIC, S_MAT_MASK, 0, 0 }, - { "*mat_canvas", 0, 0, S_MAT_CANVAS, S_MAT_MASK, 0, 0 }, - { "*mat_rock", 0, 0, S_MAT_ROCK, S_MAT_MASK, 0, 0 }, - { "*mat_rubber", 0, 0, S_MAT_RUBBER, S_MAT_MASK, 0, 0 }, - { "*mat_plastic", 0, 0, S_MAT_PLASTIC, S_MAT_MASK, 0, 0 }, - { "*mat_tiles", 0, 0, S_MAT_TILES, S_MAT_MASK, 0, 0 }, - { "*mat_carpet", 0, 0, S_MAT_CARPET, S_MAT_MASK, 0, 0 }, - { "*mat_plaster", 0, 0, S_MAT_PLASTER, S_MAT_MASK, 0, 0 }, - { "*mat_shatterglass", 0, 0, S_MAT_SHATTERGLASS, S_MAT_MASK, 0, 0 }, - { "*mat_armor", 0, 0, S_MAT_ARMOR, S_MAT_MASK, 0, 0 }, - { "*mat_computer", 0, 0, S_MAT_COMPUTER, S_MAT_MASK, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_t.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_t.h deleted file mode 100644 index 5eec9063..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_t.h +++ /dev/null @@ -1,34 +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 -*/ - -/* ydnar: for -game support */ -typedef struct game_s -{ - char *arg; /* -game matches this */ - char *gamePath; /* main game data dir */ - char *homeBasePath; /* home sub-dir on unix */ - char *magic; /* magic word for figuring out base path */ - qboolean wolfLight; /* when true, lights work like wolf q3map */ - int bspVersion; /* BSP version to use */ -} -game_t; - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_tenebrae.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_tenebrae.h deleted file mode 100644 index ab312158..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_tenebrae.h +++ /dev/null @@ -1,208 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_TENEBRAE_H -#define GAME_TENEBRAE_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* game flags */ -#define T_CONT_SOLID 1 /* an eye is never valid in a solid */ -#define T_CONT_LAVA 8 -#define T_CONT_SLIME 16 -#define T_CONT_WATER 32 -#define T_CONT_FOG 64 - -#define T_CONT_AREAPORTAL 0x8000 - -#define T_CONT_PLAYERCLIP 0x10000 -#define T_CONT_MONSTERCLIP 0x20000 -#define T_CONT_TELEPORTER 0x40000 -#define T_CONT_JUMPPAD 0x80000 -#define T_CONT_CLUSTERPORTAL 0x100000 -#define T_CONT_DONOTENTER 0x200000 -#define T_CONT_BOTCLIP 0x400000 - -#define T_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ - -#define T_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ -#define T_CONT_CORPSE 0x4000000 -#define T_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ -#define T_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ -#define T_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ -#define T_CONT_TRIGGER 0x40000000 -#define T_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ - -#define T_SURF_NODAMAGE 0x1 /* never give falling damage */ -#define T_SURF_SLICK 0x2 /* effects game physics */ -#define T_SURF_SKY 0x4 /* lighting from environment map */ -#define T_SURF_LADDER 0x8 -#define T_SURF_NOIMPACT 0x10 /* don't make missile explosions */ -#define T_SURF_NOMARKS 0x20 /* don't leave missile marks */ -#define T_SURF_FLESH 0x40 /* make flesh sounds and effects */ -#define T_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ -#define T_SURF_HINT 0x100 /* make a primary bsp splitter */ -#define T_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ -#define T_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ -#define T_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ -#define T_SURF_METALSTEPS 0x1000 /* clanking footsteps */ -#define T_SURF_NOSTEPS 0x2000 /* no footstep sounds */ -#define T_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ -#define T_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ -#define T_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ -#define T_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ -#define T_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ - -/* ydnar flags */ -#define T_SURF_VERTEXLIT (T_SURF_POINTLIGHT | T_SURF_NOLIGHTMAP) - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "tenebrae", /* -game x */ - "base", /* default base game data dir */ - ".tenebrae", /* unix home sub-dir */ - "tenebrae", /* magic path word */ - "scripts", /* shader directory */ - 1024, /* max lightmapped surface verts */ - 1024, /* max surface verts */ - 6144, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 512, /* lightmap width/height */ - 2.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qtrue, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qtrue, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", T_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", T_CONT_ORIGIN, T_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", T_CONT_AREAPORTAL, T_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", T_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", T_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", T_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, T_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, T_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, T_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, T_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, T_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, T_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, T_CONT_SOLID, T_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", T_CONT_TRIGGER, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", T_CONT_WATER, T_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", T_CONT_SLIME, T_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", T_CONT_LAVA, T_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", T_CONT_PLAYERCLIP, T_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", T_CONT_MONSTERCLIP, T_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", T_CONT_NODROP, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", T_CONT_CLUSTERPORTAL, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", T_CONT_DONOTENTER, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", T_CONT_BOTCLIP, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", T_CONT_FOG, T_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, T_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, T_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, T_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, T_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, T_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, T_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, T_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, T_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, T_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, T_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, T_SURF_DUST, 0, 0, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_tremulous.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_tremulous.h deleted file mode 100644 index 5d422629..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_tremulous.h +++ /dev/null @@ -1,176 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - -/* Tremulous support, by LinuxManMikeC */ - - -/* marker */ -#ifndef GAME_TREMULOUS_H -#define GAME_TREMULOUS_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - also uses defines from game_quake3.h - -------------------------------------------------------------------------------- */ -#define TREM_CONT_NOALIENBUILD 0x1000 -#define TREM_CONT_NOHUMANBUILD 0x2000 -#define TREM_CONT_NOBUILD 0x4000 - -#define TREM_SURF_NOALIENBUILDSURFACE 0x80000 -#define TREM_SURF_NOHUMANBUILDSURFACE 0x100000 -#define TREM_SURF_NOBUILDSURFACE 0x200000 - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "tremulous", /* -game x */ - "base", /* default base game data dir */ - ".tremulous", /* unix home sub-dir */ - "tremulous", /* magic path word - think this is right for trem*/ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - - /* tremulous */ - {"noalienbuild", TREM_CONT_NOALIENBUILD,0,0,0,0,0}, - {"nohumanbuild", TREM_CONT_NOHUMANBUILD,0,0,0,0,0}, - {"nobuild", TREM_CONT_NOBUILD,0,0,0,0,0}, - - {"noalienbuildsurface", 0,0,TREM_SURF_NOALIENBUILDSURFACE,0,0,0}, - {"nohumanbuildsurface", 0,0,TREM_SURF_NOHUMANBUILDSURFACE,0,0,0}, - {"nobuildsurface", 0,0,TREM_SURF_NOBUILDSURFACE,0,0,0}, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_wolf.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_wolf.h deleted file mode 100644 index 157bfe3a..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_wolf.h +++ /dev/null @@ -1,254 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_WOLF_H -#define GAME_WOLF_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* game flags */ -#define W_CONT_SOLID 1 /* an eye is never valid in a solid */ -#define W_CONT_LAVA 8 -#define W_CONT_SLIME 16 -#define W_CONT_WATER 32 -#define W_CONT_FOG 64 - -#define W_CONT_MISSILECLIP 0x80 /* wolf ranged missile blocking */ -#define W_CONT_ITEM 0x100 /* wolf item contents */ -#define W_CONT_AI_NOSIGHT 0x1000 /* wolf ai sight blocking */ -#define W_CONT_CLIPSHOT 0x2000 /* wolf shot clip */ -#define W_CONT_AREAPORTAL 0x8000 - -#define W_CONT_PLAYERCLIP 0x10000 -#define W_CONT_MONSTERCLIP 0x20000 -#define W_CONT_TELEPORTER 0x40000 -#define W_CONT_JUMPPAD 0x80000 -#define W_CONT_CLUSTERPORTAL 0x100000 -#define W_CONT_DONOTENTER 0x200000 -#define W_CONT_DONOTENTER_LARGE 0x400000 /* wolf dne */ - -#define W_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ - -#define W_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ -#define W_CONT_CORPSE 0x4000000 -#define W_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ -#define W_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ -#define W_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ -#define W_CONT_TRIGGER 0x40000000 -#define W_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ - -#define W_SURF_NODAMAGE 0x1 /* never give falling damage */ -#define W_SURF_SLICK 0x2 /* effects game physics */ -#define W_SURF_SKY 0x4 /* lighting from environment map */ -#define W_SURF_LADDER 0x8 -#define W_SURF_NOIMPACT 0x10 /* don't make missile explosions */ -#define W_SURF_NOMARKS 0x20 /* don't leave missile marks */ -#define W_SURF_CERAMIC 0x40 /* wolf ceramic material */ -#define W_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ -#define W_SURF_HINT 0x100 /* make a primary bsp splitter */ -#define W_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ -#define W_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ -#define W_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ -#define W_SURF_METAL 0x1000 /* wolf metal material */ -#define W_SURF_NOSTEPS 0x2000 /* no footstep sounds */ -#define W_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ -#define W_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ -#define W_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ -#define W_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ -#define W_SURF_WOOD 0x40000 /* wolf wood material */ -#define W_SURF_GRASS 0x80000 /* wolf grass material */ -#define W_SURF_GRAVEL 0x100000 /* wolf gravel material */ -#define W_SURF_GLASS 0x200000 /* wolf glass material */ -#define W_SURF_SNOW 0x400000 /* wolf snow material */ -#define W_SURF_ROOF 0x800000 /* wolf roof material */ -#define W_SURF_RUBBLE 0x1000000 /* wolf rubble material */ -#define W_SURF_CARPET 0x2000000 /* wolf carpet material */ - -#define W_SURF_MONSTERSLICK 0x4000000 /* wolf npc slick surface */ -#define W_SURF_MONSLICK_W 0x8000000 /* wolf slide bodies west */ -#define W_SURF_MONSLICK_N 0x10000000 /* wolf slide bodies north */ -#define W_SURF_MONSLICK_E 0x20000000 /* wolf slide bodies east */ -#define W_SURF_MONSLICK_S 0x40000000 /* wolf slide bodies south */ - -/* ydnar flags */ -#define W_SURF_VERTEXLIT (W_SURF_POINTLIGHT | W_SURF_NOLIGHTMAP) - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "wolf", /* -game x */ - "main", /* default base game data dir */ - ".wolf", /* unix home sub-dir */ - "wolf", /* magic path word */ - "scripts", /* shader directory */ - 64, /* max lightmapped surface verts */ - 999, /* max surface verts */ - 6000, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qtrue, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 47, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", W_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", W_CONT_ORIGIN, W_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", W_CONT_AREAPORTAL, W_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", W_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", W_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", W_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, W_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, W_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, W_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, W_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, W_CONT_SOLID, W_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", W_CONT_TRIGGER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", W_CONT_WATER, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slag", W_CONT_SLIME, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", W_CONT_LAVA, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", W_CONT_PLAYERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", W_CONT_MONSTERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "clipmissile", W_CONT_MISSILECLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "clipshot", W_CONT_CLIPSHOT, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", W_CONT_NODROP, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", W_CONT_CLUSTERPORTAL, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "nonotenterlarge",W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", W_CONT_FOG, W_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, W_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, W_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, W_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, W_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, W_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, W_SURF_NODAMAGE, 0, 0, 0 }, - { "nosteps", 0, 0, W_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, W_SURF_NODLIGHT, 0, 0, 0 }, - - - /* materials */ - { "metal", 0, 0, W_SURF_METAL, 0, 0, 0 }, - { "metalsteps", 0, 0, W_SURF_METAL, 0, 0, 0 }, - { "glass", 0, 0, W_SURF_GLASS, 0, 0, 0 }, - { "ceramic", 0, 0, W_SURF_CERAMIC, 0, 0, 0 }, - { "woodsteps", 0, 0, W_SURF_WOOD, 0, 0, 0 }, - { "grasssteps", 0, 0, W_SURF_GRASS, 0, 0, 0 }, - { "gravelsteps", 0, 0, W_SURF_GRAVEL, 0, 0, 0 }, - { "rubble", 0, 0, W_SURF_RUBBLE, 0, 0, 0 }, - { "carpetsteps", 0, 0, W_SURF_CARPET, 0, 0, 0 }, - { "snowsteps", 0, 0, W_SURF_SNOW, 0, 0, 0 }, - { "roofsteps", 0, 0, W_SURF_ROOF, 0, 0, 0 }, - - - /* ai */ - { "ai_nosight", W_CONT_AI_NOSIGHT, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - /* ydnar: experimental until bits are confirmed! */ - { "ai_nopass", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "ai_nopasslarge", W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - - /* sliding bodies */ - { "monsterslick", 0, 0, W_SURF_MONSTERSLICK, 0, C_TRANSLUCENT, 0 }, - { "monsterslicknorth", 0, 0, W_SURF_MONSLICK_N, 0, C_TRANSLUCENT, 0 }, - { "monsterslickeast", 0, 0, W_SURF_MONSLICK_E, 0, C_TRANSLUCENT, 0 }, - { "monsterslicksouth", 0, 0, W_SURF_MONSLICK_S, 0, C_TRANSLUCENT, 0 }, - { "monsterslickwest", 0, 0, W_SURF_MONSLICK_W, 0, C_TRANSLUCENT, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_wolfet.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_wolfet.h deleted file mode 100644 index 3495f0dc..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_wolfet.h +++ /dev/null @@ -1,193 +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 - ----------------------------------------------------------------------------------- - -Support for Wolfenstein: Enemy Territory by ydnar@splashdamage.com - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_WOLFET_H -#define GAME_WOLFET_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags - -------------------------------------------------------------------------------- */ - -/* this file must be included *after* game_wolf.h because it shares defines! */ - -#define W_SURF_SPLASH 0x00000040 /* enemy territory water splash surface */ -#define W_SURF_LANDMINE 0x80000000 /* enemy territory 'landminable' surface */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "et", /* -game x */ - "etmain", /* default base game data dir */ - ".etwolf", /* unix home sub-dir */ - "et", /* magic path word */ - "scripts", /* shader directory */ - 1024, /* max lightmapped surface verts */ - 1024, /* max surface verts */ - 6144, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qtrue, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qfalse, /* disable shader lightstyles hack */ - qfalse, /* keep light entities on bsp */ - 8, /* default patchMeta subdivisions tolerance */ - qfalse, /* patch casting enabled */ - qfalse, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 0.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "%s.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 47, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", W_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - - /* compiler */ - { "origin", W_CONT_ORIGIN, W_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", W_CONT_AREAPORTAL, W_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", W_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", W_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", W_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, W_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, W_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, W_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, W_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - - /* game */ - { "nonsolid", 0, W_CONT_SOLID, W_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", W_CONT_TRIGGER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", W_CONT_WATER, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slag", W_CONT_SLIME, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", W_CONT_LAVA, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", W_CONT_PLAYERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", W_CONT_MONSTERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "clipmissile", W_CONT_MISSILECLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "clipshot", W_CONT_CLIPSHOT, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", W_CONT_NODROP, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", W_CONT_CLUSTERPORTAL, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "nonotenterlarge",W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", W_CONT_FOG, W_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, W_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, W_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, W_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, W_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, W_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, W_SURF_NODAMAGE, 0, 0, 0 }, - { "nosteps", 0, 0, W_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, W_SURF_NODLIGHT, 0, 0, 0 }, - - /* wolf et landmine-able surface */ - { "landmine", 0, 0, W_SURF_LANDMINE, 0, 0, 0 }, - - /* materials */ - { "metal", 0, 0, W_SURF_METAL, 0, 0, 0 }, - { "metalsteps", 0, 0, W_SURF_METAL, 0, 0, 0 }, - { "glass", 0, 0, W_SURF_GLASS, 0, 0, 0 }, - { "splash", 0, 0, W_SURF_SPLASH, 0, 0, 0 }, - { "woodsteps", 0, 0, W_SURF_WOOD, 0, 0, 0 }, - { "grasssteps", 0, 0, W_SURF_GRASS, 0, 0, 0 }, - { "gravelsteps", 0, 0, W_SURF_GRAVEL, 0, 0, 0 }, - { "rubble", 0, 0, W_SURF_RUBBLE, 0, 0, 0 }, - { "carpetsteps", 0, 0, W_SURF_CARPET, 0, 0, 0 }, - { "snowsteps", 0, 0, W_SURF_SNOW, 0, 0, 0 }, - { "roofsteps", 0, 0, W_SURF_ROOF, 0, 0, 0 }, - - - /* ai */ - { "ai_nosight", W_CONT_AI_NOSIGHT, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - /* ydnar: experimental until bits are confirmed! */ - { "ai_nopass", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "ai_nopasslarge", W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - - /* sliding bodies */ - { "monsterslick", 0, 0, W_SURF_MONSTERSLICK, 0, C_TRANSLUCENT, 0 }, - { "monsterslicknorth", 0, 0, W_SURF_MONSLICK_N, 0, C_TRANSLUCENT, 0 }, - { "monsterslickeast", 0, 0, W_SURF_MONSLICK_E, 0, C_TRANSLUCENT, 0 }, - { "monsterslicksouth", 0, 0, W_SURF_MONSLICK_S, 0, C_TRANSLUCENT, 0 }, - { "monsterslickwest", 0, 0, W_SURF_MONSLICK_W, 0, C_TRANSLUCENT, 0 }, - - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_xonotic.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_xonotic.h deleted file mode 100644 index 568c263e..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/game_xonotic.h +++ /dev/null @@ -1,155 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef GAME_XONOTIC_H -#define GAME_XONOTIC_H - - - -/* ------------------------------------------------------------------------------- - -content and surface flags -are in game_quake3.h - -------------------------------------------------------------------------------- */ - - - -/* ------------------------------------------------------------------------------- - -game_t struct - -------------------------------------------------------------------------------- */ - -{ - "xonotic", /* -game x */ - "data", /* default base game data dir */ - ".xonotic", /* unix home sub-dir */ - "xonotic", /* magic path word */ - "scripts", /* shader directory */ - 1048575, /* max lightmapped surface verts */ - 1048575, /* max surface verts */ - 1048575, /* max surface indexes */ - qfalse, /* flares */ - "flareshader", /* default flare shader */ - qfalse, /* wolf lighting model? */ - 128, /* lightmap width/height */ - 1.0f, /* lightmap gamma */ - 1.0f, /* lightmap exposure */ - 1.0f, /* lightmap compensate */ - 1.0f, /* lightgrid scale */ - 1.0f, /* lightgrid ambient scale */ - qfalse, /* light angle attenuation uses half-lambert curve */ - qtrue, /* disable shader lightstyles hack */ - qtrue, /* keep light entities on bsp */ - 4, /* default patchMeta subdivisions tolerance */ - qtrue, /* patch casting enabled */ - qtrue, /* compile deluxemaps */ - 0, /* deluxemaps default mode */ - 512, /* minimap size */ - 1.0f, /* minimap sharpener */ - 1.0f/66.0f, /* minimap border */ - qtrue, /* minimap keep aspect */ - MINIMAP_MODE_GRAY, /* minimap mode */ - "../gfx/%s_mini.tga", /* minimap name format */ - "IBSP", /* bsp file prefix */ - 46, /* bsp file version */ - qfalse, /* cod-style lump len/ofs order */ - LoadIBSPFile, /* bsp load function */ - WriteIBSPFile, /* bsp write function */ - - { - /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ - - /* default */ - { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, - - /* ydnar */ - { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, - { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, - { "skip", 0, 0, 0, 0, C_SKIP, 0 }, - - /* compiler */ - { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, - { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, - { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, - { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, - { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, - { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, - { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, - - { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, - { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, - { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, - - /* game */ - { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, - - { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, - - { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, - { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, - - { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, - { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, - - { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, - - { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, - { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, - { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, - { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, - { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, - { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, - { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, - { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, - { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, - - /* null */ - { NULL, 0, 0, 0, 0, 0, 0 } - } -} - - - -/* end marker */ -#endif - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/image.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/image.c deleted file mode 100644 index 929b15d9..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/image.c +++ /dev/null @@ -1,492 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define IMAGE_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* ------------------------------------------------------------------------------- - -this file contains image pool management with reference counting. note: it isn't -reentrant, so only call it from init/shutdown code or wrap calls in a mutex - -------------------------------------------------------------------------------- */ - -/* -LoadDDSBuffer() -loads a dxtc (1, 3, 5) dds buffer into a valid rgba image -*/ - -static void LoadDDSBuffer( byte *buffer, int size, byte **pixels, int *width, int *height ) -{ - int w, h; - ddsPF_t pf; - - - /* dummy check */ - if( buffer == NULL || size <= 0 || pixels == NULL || width == NULL || height == NULL ) - return; - - /* null out */ - *pixels = 0; - *width = 0; - *height = 0; - - /* get dds info */ - if( DDSGetInfo( (ddsBuffer_t*) buffer, &w, &h, &pf ) ) - { - Sys_Printf( "WARNING: Invalid DDS texture\n" ); - return; - } - - /* only certain types of dds textures are supported */ - if( pf != DDS_PF_ARGB8888 && pf != DDS_PF_DXT1 && pf != DDS_PF_DXT3 && pf != DDS_PF_DXT5 ) - { - Sys_Printf( "WARNING: Only DDS texture formats ARGB8888, DXT1, DXT3, and DXT5 are supported (%d)\n", pf ); - return; - } - - /* create image pixel buffer */ - *width = w; - *height = h; - *pixels = safe_malloc( w * h * 4 ); - - /* decompress the dds texture */ - DDSDecompress( (ddsBuffer_t*) buffer, *pixels ); -} - - - -/* -PNGReadData() -callback function for libpng to read from a memory buffer -note: this function is a total hack, as it reads/writes the png struct directly! -*/ - -typedef struct pngBuffer_s -{ - byte *buffer; - png_size_t size, offset; -} -pngBuffer_t; - -void PNGReadData( png_struct *png, png_byte *buffer, png_size_t size ) -{ - pngBuffer_t *pb = (pngBuffer_t*) png_get_io_ptr( png ); - - - if( (pb->offset + size) > pb->size ) - size = (pb->size - pb->offset); - memcpy( buffer, &pb->buffer[ pb->offset ], size ); - pb->offset += size; - //% Sys_Printf( "Copying %d bytes from 0x%08X to 0x%08X (offset: %d of %d)\n", size, &pb->buffer[ pb->offset ], buffer, pb->offset, pb->size ); -} - - - -/* -LoadPNGBuffer() -loads a png file buffer into a valid rgba image -*/ - -static void LoadPNGBuffer( byte *buffer, int size, byte **pixels, int *width, int *height ) -{ - png_struct *png; - png_info *info, *end; - pngBuffer_t pb; - int bitDepth, colorType, channels; - png_uint_32 w, h, i; - byte **rowPointers; - - - /* dummy check */ - if( buffer == NULL || size <= 0 || pixels == NULL || width == NULL || height == NULL ) - return; - - /* null out */ - *pixels = 0; - *width = 0; - *height = 0; - - /* determine if this is a png file */ - if( png_sig_cmp( buffer, 0, 8 ) != 0 ) - { - Sys_Printf( "WARNING: Invalid PNG file\n" ); - return; - } - - /* create png structs */ - png = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL ); - if( png == NULL ) - { - Sys_Printf( "WARNING: Unable to create PNG read struct\n" ); - return; - } - - info = png_create_info_struct( png ); - if( info == NULL ) - { - Sys_Printf( "WARNING: Unable to create PNG info struct\n" ); - png_destroy_read_struct( &png, NULL, NULL ); - return; - } - - end = png_create_info_struct( png ); - if( end == NULL ) - { - Sys_Printf( "WARNING: Unable to create PNG end info struct\n" ); - png_destroy_read_struct( &png, &info, NULL ); - return; - } - - /* set read callback */ - pb.buffer = buffer; - pb.size = size; - pb.offset = 0; - png_set_read_fn( png, &pb, PNGReadData ); - png->io_ptr = &pb; /* hack! */ - - /* set error longjmp */ - if( setjmp( png->jmpbuf ) ) - { - Sys_Printf( "WARNING: An error occurred reading PNG image\n" ); - png_destroy_read_struct( &png, &info, &end ); - return; - } - - /* fixme: add proper i/o stuff here */ - - /* read png info */ - png_read_info( png, info ); - - /* read image header chunk */ - png_get_IHDR( png, info, - &w, &h, &bitDepth, &colorType, NULL, NULL, NULL ); - - /* read number of channels */ - channels = png_get_channels( png, info ); - - /* the following will probably bork on certain types of png images, but hey... */ - - /* force indexed/gray/trans chunk to rgb */ - if( (colorType == PNG_COLOR_TYPE_PALETTE && bitDepth <= 8) || - (colorType == PNG_COLOR_TYPE_GRAY && bitDepth <= 8) || - png_get_valid( png, info, PNG_INFO_tRNS ) ) - png_set_expand( png ); - - /* strip 16bpc -> 8bpc */ - if( bitDepth == 16 ) - png_set_strip_16( png ); - - /* pad rgb to rgba */ - if( bitDepth == 8 && colorType == PNG_COLOR_TYPE_RGB) - png_set_filler( png, 255, PNG_FILLER_AFTER ); - - /* create image pixel buffer */ - *width = w; - *height = h; - *pixels = safe_malloc( w * h * 4 ); - - /* create row pointers */ - rowPointers = safe_malloc( h * sizeof( byte* ) ); - for( i = 0; i < h; i++ ) - rowPointers[ i ] = *pixels + (i * w * 4); - - /* read the png */ - png_read_image( png, rowPointers ); - - /* clean up */ - free( rowPointers ); - png_destroy_read_struct( &png, &info, &end ); - -} - - - -/* -ImageInit() -implicitly called by every function to set up image list -*/ - -static void ImageInit( void ) -{ - int i; - - - if( numImages <= 0 ) - { - /* clear images (fixme: this could theoretically leak) */ - memset( images, 0, sizeof( images ) ); - - /* generate *bogus image */ - images[ 0 ].name = safe_malloc( strlen( DEFAULT_IMAGE ) + 1 ); - strcpy( images[ 0 ].name, DEFAULT_IMAGE ); - images[ 0 ].filename = safe_malloc( strlen( DEFAULT_IMAGE ) + 1 ); - strcpy( images[ 0 ].filename, DEFAULT_IMAGE ); - images[ 0 ].width = 64; - images[ 0 ].height = 64; - images[ 0 ].refCount = 1; - images[ 0 ].pixels = safe_malloc( 64 * 64 * 4 ); - for( i = 0; i < (64 * 64 * 4); i++ ) - images[ 0 ].pixels[ i ] = 255; - } -} - - - -/* -ImageFree() -frees an rgba image -*/ - -void ImageFree( image_t *image ) -{ - /* dummy check */ - if( image == NULL ) - return; - - /* decrement refcount */ - image->refCount--; - - /* free? */ - if( image->refCount <= 0 ) - { - if( image->name != NULL ) - free( image->name ); - image->name = NULL; - if( image->filename != NULL ) - free( image->filename ); - image->filename = NULL; - free( image->pixels ); - image->width = 0; - image->height = 0; - numImages--; - } -} - - - -/* -ImageFind() -finds an existing rgba image and returns a pointer to the image_t struct or NULL if not found -*/ - -image_t *ImageFind( const char *filename ) -{ - int i; - char name[ 1024 ]; - - - /* init */ - ImageInit(); - - /* dummy check */ - if( filename == NULL || filename[ 0 ] == '\0' ) - return NULL; - - /* strip file extension off name */ - strcpy( name, filename ); - StripExtension( name ); - - /* search list */ - for( i = 0; i < MAX_IMAGES; i++ ) - { - if( images[ i ].name != NULL && !strcmp( name, images[ i ].name ) ) - return &images[ i ]; - } - - /* no matching image found */ - return NULL; -} - - - -/* -ImageLoad() -loads an rgba image and returns a pointer to the image_t struct or NULL if not found -*/ - -image_t *ImageLoad( const char *filename ) -{ - int i; - image_t *image; - char name[ 1024 ]; - int size; - byte *buffer = NULL; - qboolean alphaHack = qfalse; - - - /* init */ - ImageInit(); - - /* dummy check */ - if( filename == NULL || filename[ 0 ] == '\0' ) - return NULL; - - /* strip file extension off name */ - strcpy( name, filename ); - StripExtension( name ); - - /* try to find existing image */ - image = ImageFind( name ); - if( image != NULL ) - { - image->refCount++; - return image; - } - - /* none found, so find first non-null image */ - image = NULL; - for( i = 0; i < MAX_IMAGES; i++ ) - { - if( images[ i ].name == NULL ) - { - image = &images[ i ]; - break; - } - } - - /* too many images? */ - if( image == NULL ) - Error( "MAX_IMAGES (%d) exceeded, there are too many image files referenced by the map.", MAX_IMAGES ); - - /* set it up */ - image->name = safe_malloc( strlen( name ) + 1 ); - strcpy( image->name, name ); - - /* attempt to load tga */ - StripExtension( name ); - strcat( name, ".tga" ); - size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); - if( size > 0 ) - LoadTGABuffer( buffer, buffer + size, &image->pixels, &image->width, &image->height ); - else - { - /* attempt to load png */ - StripExtension( name ); - strcat( name, ".png" ); - size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); - if( size > 0 ) - LoadPNGBuffer( buffer, size, &image->pixels, &image->width, &image->height ); - else - { - /* attempt to load jpg */ - StripExtension( name ); - strcat( name, ".jpg" ); - size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); - if( size > 0 ) - { - if( LoadJPGBuff( buffer, size, &image->pixels, &image->width, &image->height ) == -1 && image->pixels != NULL ) - Sys_Printf( "WARNING: LoadJPGBuff: %s\n", (unsigned char*) image->pixels ); - alphaHack = qtrue; - } - else - { - /* attempt to load dds */ - StripExtension( name ); - strcat( name, ".dds" ); - size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); - if( size > 0 ) - { - LoadDDSBuffer( buffer, size, &image->pixels, &image->width, &image->height ); - - /* debug code */ - #if 1 - { - ddsPF_t pf; - DDSGetInfo( (ddsBuffer_t*) buffer, NULL, NULL, &pf ); - Sys_Printf( "pf = %d\n", pf ); - if( image->width > 0 ) - { - StripExtension( name ); - strcat( name, "_converted.tga" ); - WriteTGA( "C:\\games\\quake3\\baseq3\\textures\\rad\\dds_converted.tga", image->pixels, image->width, image->height ); - } - } - #endif - } - } - } - } - - /* free file buffer */ - free( buffer ); - - /* make sure everything's kosher */ - if( size <= 0 || image->width <= 0 || image->height <= 0 || image->pixels == NULL ) - { - //% Sys_Printf( "size = %d width = %d height = %d pixels = 0x%08x (%s)\n", - //% size, image->width, image->height, image->pixels, name ); - free( image->name ); - image->name = NULL; - return NULL; - } - - /* set filename */ - image->filename = safe_malloc( strlen( name ) + 1 ); - strcpy( image->filename, name ); - - /* set count */ - image->refCount = 1; - numImages++; - - if(alphaHack) - { - StripExtension( name ); - strcat( name, "_alpha.jpg" ); - size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); - if( size > 0 ) - { - unsigned char *pixels; - int width, height; - if( LoadJPGBuff( buffer, size, &pixels, &width, &height ) == -1 && pixels != NULL ) - Sys_Printf( "WARNING: LoadJPGBuff: %s\n", (unsigned char*) image->pixels ); - if(pixels && width == image->width && height == image->height) - { - int i; - for(i = 0; i < width*height; ++i) - image->pixels[4*i+3] = pixels[4*i+2]; // copy alpha from blue channel - } - free(pixels); - free(buffer); - } - } - - /* return the image */ - return image; -} - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/leakfile.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/leakfile.c deleted file mode 100644 index fc5a3191..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/leakfile.c +++ /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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define LEAKFILE_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -============================================================================== - -LEAK FILE GENERATION - -Save out name.line for qe3 to read -============================================================================== -*/ - - -/* -============= -LeakFile - -Finds the shortest possible chain of portals -that leads from the outside leaf to a specifically -occupied leaf - -TTimo: builds a polyline xml node -============= -*/ -xmlNodePtr LeakFile (tree_t *tree) -{ - vec3_t mid; - FILE *linefile; - char filename[1024]; - node_t *node; - int count; - xmlNodePtr xml_node, point; - - if (!tree->outside_node.occupied) - return NULL; - - Sys_FPrintf (SYS_VRB,"--- LeakFile ---\n"); - - // - // write the points to the file - // - sprintf (filename, "%s.lin", source); - linefile = fopen (filename, "w"); - if (!linefile) - Error ("Couldn't open %s\n", filename); - - xml_node = xmlNewNode (NULL, (xmlChar*)"polyline"); - - count = 0; - node = &tree->outside_node; - while (node->occupied > 1) - { - int next; - portal_t *p, *nextportal = NULL; - node_t *nextnode = NULL; - int s; - - // find the best portal exit - next = node->occupied; - for (p=node->portals ; p ; p = p->next[!s]) - { - s = (p->nodes[0] == node); - if (p->nodes[s]->occupied - && p->nodes[s]->occupied < next) - { - nextportal = p; - nextnode = p->nodes[s]; - next = nextnode->occupied; - } - } - node = nextnode; - WindingCenter (nextportal->winding, mid); - fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); - point = xml_NodeForVec(mid); - xmlAddChild(xml_node, point); - count++; - } - // add the occupant center - GetVectorForKey (node->occupant, "origin", mid); - - fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); - point = xml_NodeForVec(mid); - xmlAddChild(xml_node, point); - Sys_FPrintf( SYS_VRB, "%9d point linefile\n", count+1); - - fclose (linefile); - - return xml_node; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light.c deleted file mode 100644 index 9323b8c8..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light.c +++ /dev/null @@ -1,2877 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define LIGHT_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -CreateSunLight() - ydnar -this creates a sun light -*/ - -static void CreateSunLight( sun_t *sun ) -{ - int i; - float photons, d, angle, elevation, da, de; - vec3_t direction; - light_t *light; - - - /* dummy check */ - if( sun == NULL ) - return; - - /* fixup */ - if( sun->numSamples < 1 ) - sun->numSamples = 1; - - /* set photons */ - photons = sun->photons / sun->numSamples; - - /* create the right number of suns */ - for( i = 0; i < sun->numSamples; i++ ) - { - /* calculate sun direction */ - if( i == 0 ) - VectorCopy( sun->direction, direction ); - else - { - /* - sun->direction[ 0 ] = cos( angle ) * cos( elevation ); - sun->direction[ 1 ] = sin( angle ) * cos( elevation ); - sun->direction[ 2 ] = sin( elevation ); - - xz_dist = sqrt( x*x + z*z ) - latitude = atan2( xz_dist, y ) * RADIANS - longitude = atan2( x, z ) * RADIANS - */ - - d = sqrt( sun->direction[ 0 ] * sun->direction[ 0 ] + sun->direction[ 1 ] * sun->direction[ 1 ] ); - angle = atan2( sun->direction[ 1 ], sun->direction[ 0 ] ); - elevation = atan2( sun->direction[ 2 ], d ); - - /* jitter the angles (loop to keep random sample within sun->deviance steridians) */ - do - { - da = (Random() * 2.0f - 1.0f) * sun->deviance; - de = (Random() * 2.0f - 1.0f) * sun->deviance; - } - while( (da * da + de * de) > (sun->deviance * sun->deviance) ); - angle += da; - elevation += de; - - /* debug code */ - //% Sys_Printf( "%d: Angle: %3.4f Elevation: %3.3f\n", sun->numSamples, (angle / Q_PI * 180.0f), (elevation / Q_PI * 180.0f) ); - - /* create new vector */ - direction[ 0 ] = cos( angle ) * cos( elevation ); - direction[ 1 ] = sin( angle ) * cos( elevation ); - direction[ 2 ] = sin( elevation ); - } - - /* create a light */ - numSunLights++; - light = safe_malloc( sizeof( *light ) ); - memset( light, 0, sizeof( *light ) ); - light->next = lights; - lights = light; - - /* initialize the light */ - light->flags = LIGHT_SUN_DEFAULT; - light->type = EMIT_SUN; - light->fade = 1.0f; - light->falloffTolerance = falloffTolerance; - light->filterRadius = sun->filterRadius / sun->numSamples; - light->style = noStyles ? LS_NORMAL : sun->style; - - /* set the light's position out to infinity */ - VectorMA( vec3_origin, (MAX_WORLD_COORD * 8.0f), direction, light->origin ); /* MAX_WORLD_COORD * 2.0f */ - - /* set the facing to be the inverse of the sun direction */ - VectorScale( direction, -1.0, light->normal ); - light->dist = DotProduct( light->origin, light->normal ); - - /* set color and photons */ - VectorCopy( sun->color, light->color ); - light->photons = photons * skyScale; - } - - /* another sun? */ - if( sun->next != NULL ) - CreateSunLight( sun->next ); -} - - - -/* -CreateSkyLights() - ydnar -simulates sky light with multiple suns -*/ - -static void CreateSkyLights( vec3_t color, float value, int iterations, float filterRadius, int style ) -{ - int i, j, numSuns; - int angleSteps, elevationSteps; - float angle, elevation; - float angleStep, elevationStep; - float step, start; - sun_t sun; - - - /* dummy check */ - if( value <= 0.0f || iterations < 2 ) - return; - - /* calculate some stuff */ - step = 2.0f / (iterations - 1); - start = -1.0f; - - /* basic sun setup */ - VectorCopy( color, sun.color ); - sun.deviance = 0.0f; - sun.filterRadius = filterRadius; - sun.numSamples = 1; - sun.style = noStyles ? LS_NORMAL : style; - sun.next = NULL; - - /* setup */ - elevationSteps = iterations - 1; - angleSteps = elevationSteps * 4; - angle = 0.0f; - elevationStep = DEG2RAD( 90.0f / iterations ); /* skip elevation 0 */ - angleStep = DEG2RAD( 360.0f / angleSteps ); - - /* calc individual sun brightness */ - numSuns = angleSteps * elevationSteps + 1; - sun.photons = value / numSuns; - - /* iterate elevation */ - elevation = elevationStep * 0.5f; - angle = 0.0f; - for( i = 0, elevation = elevationStep * 0.5f; i < elevationSteps; i++ ) - { - /* iterate angle */ - for( j = 0; j < angleSteps; j++ ) - { - /* create sun */ - sun.direction[ 0 ] = cos( angle ) * cos( elevation ); - sun.direction[ 1 ] = sin( angle ) * cos( elevation ); - sun.direction[ 2 ] = sin( elevation ); - CreateSunLight( &sun ); - - /* move */ - angle += angleStep; - } - - /* move */ - elevation += elevationStep; - angle += angleStep / elevationSteps; - } - - /* create vertical sun */ - VectorSet( sun.direction, 0.0f, 0.0f, 1.0f ); - CreateSunLight( &sun ); - - /* short circuit */ - return; -} - - - -/* -CreateEntityLights() -creates lights from light entities -*/ - -void CreateEntityLights( void ) -{ - int i, j; - light_t *light, *light2; - entity_t *e, *e2; - const char *name; - const char *target; - vec3_t dest; - const char *_color; - float intensity, scale, deviance, filterRadius; - int spawnflags, flags, numSamples; - qboolean junior; - - - /* go throught entity list and find lights */ - for( i = 0; i < numEntities; i++ ) - { - /* get entity */ - e = &entities[ i ]; - name = ValueForKey( e, "classname" ); - - /* ydnar: check for lightJunior */ - if( Q_strncasecmp( name, "lightJunior", 11 ) == 0 ) - junior = qtrue; - else if( Q_strncasecmp( name, "light", 5 ) == 0 ) - junior = qfalse; - else - continue; - - /* lights with target names (and therefore styles) are only parsed from BSP */ - target = ValueForKey( e, "targetname" ); - if( target[ 0 ] != '\0' && i >= numBSPEntities ) - continue; - - /* create a light */ - numPointLights++; - light = safe_malloc( sizeof( *light ) ); - memset( light, 0, sizeof( *light ) ); - light->next = lights; - lights = light; - - /* handle spawnflags */ - spawnflags = IntForKey( e, "spawnflags" ); - - /* ydnar: quake 3+ light behavior */ - if( wolfLight == qfalse ) - { - /* set default flags */ - flags = LIGHT_Q3A_DEFAULT; - - /* linear attenuation? */ - if( spawnflags & 1 ) - { - flags |= LIGHT_ATTEN_LINEAR; - flags &= ~LIGHT_ATTEN_ANGLE; - } - - /* no angle attenuate? */ - if( spawnflags & 2 ) - flags &= ~LIGHT_ATTEN_ANGLE; - } - - /* ydnar: wolf light behavior */ - else - { - /* set default flags */ - flags = LIGHT_WOLF_DEFAULT; - - /* inverse distance squared attenuation? */ - if( spawnflags & 1 ) - { - flags &= ~LIGHT_ATTEN_LINEAR; - flags |= LIGHT_ATTEN_ANGLE; - } - - /* angle attenuate? */ - if( spawnflags & 2 ) - flags |= LIGHT_ATTEN_ANGLE; - } - - /* other flags (borrowed from wolf) */ - - /* wolf dark light? */ - if( (spawnflags & 4) || (spawnflags & 8) ) - flags |= LIGHT_DARK; - - /* nogrid? */ - if( spawnflags & 16 ) - flags &= ~LIGHT_GRID; - - /* junior? */ - if( junior ) - { - flags |= LIGHT_GRID; - flags &= ~LIGHT_SURFACES; - } - - /* vortex: unnormalized? */ - if (spawnflags & 32) - flags |= LIGHT_UNNORMALIZED; - - /* vortex: distance atten? */ - if (spawnflags & 64) - flags |= LIGHT_ATTEN_DISTANCE; - - /* store the flags */ - light->flags = flags; - - /* ydnar: set fade key (from wolf) */ - light->fade = 1.0f; - if( light->flags & LIGHT_ATTEN_LINEAR ) - { - light->fade = FloatForKey( e, "fade" ); - if( light->fade == 0.0f ) - light->fade = 1.0f; - } - - /* ydnar: set angle scaling (from vlight) */ - light->angleScale = FloatForKey( e, "_anglescale" ); - if( light->angleScale != 0.0f ) - light->flags |= LIGHT_ATTEN_ANGLE; - - /* set origin */ - GetVectorForKey( e, "origin", light->origin); - light->style = IntForKey( e, "_style" ); - if( light->style == LS_NORMAL ) - light->style = IntForKey( e, "style" ); - if( light->style < LS_NORMAL || light->style >= LS_NONE ) - Error( "Invalid lightstyle (%d) on entity %d", light->style, i ); - - if( light->style != LS_NORMAL ) { - Sys_FPrintf (SYS_WRN, "WARNING: Styled light found targeting %s\n **", target ); - } - - /* set light intensity */ - intensity = FloatForKey( e, "_light" ); - if( intensity == 0.0f ) - intensity = FloatForKey( e, "light" ); - if( intensity == 0.0f) - intensity = 300.0f; - - /* ydnar: set light scale (sof2) */ - scale = FloatForKey( e, "scale" ); - if( scale == 0.0f ) - scale = 1.0f; - intensity *= scale; - - /* ydnar: get deviance and samples */ - deviance = FloatForKey( e, "_deviance" ); - if( deviance == 0.0f ) - deviance = FloatForKey( e, "_deviation" ); - if( deviance == 0.0f ) - deviance = FloatForKey( e, "_jitter" ); - numSamples = IntForKey( e, "_samples" ); - if( deviance < 0.0f || numSamples < 1 ) - { - deviance = 0.0f; - numSamples = 1; - } - intensity /= numSamples; - - /* ydnar: get filter radius */ - filterRadius = FloatForKey( e, "_filterradius" ); - if( filterRadius == 0.0f ) - filterRadius = FloatForKey( e, "_filteradius" ); - if( filterRadius == 0.0f ) - filterRadius = FloatForKey( e, "_filter" ); - if( filterRadius < 0.0f ) - filterRadius = 0.0f; - light->filterRadius = filterRadius; - - /* set light color */ - _color = ValueForKey( e, "_color" ); - if( _color && _color[ 0 ] ) - { - sscanf( _color, "%f %f %f", &light->color[ 0 ], &light->color[ 1 ], &light->color[ 2 ] ); - if (!(light->flags & LIGHT_UNNORMALIZED)) - { - ColorNormalize( light->color, light->color ); - } - } - else - light->color[ 0 ] = light->color[ 1 ] = light->color[ 2 ] = 1.0f; - - light->extraDist = FloatForKey( e, "_extradist" ); - if(light->extraDist == 0.0f) - light->extraDist = extraDist; - - intensity = intensity * pointScale; - light->photons = intensity; - - light->type = EMIT_POINT; - - /* set falloff threshold */ - light->falloffTolerance = falloffTolerance / numSamples; - - /* lights with a target will be spotlights */ - target = ValueForKey( e, "target" ); - if( target[ 0 ] ) - { - float radius; - float dist; - sun_t sun; - const char *_sun; - - - /* get target */ - e2 = FindTargetEntity( target ); - if( e2 == NULL ) - { - Sys_Printf( "WARNING: light at (%i %i %i) has missing target\n", - (int) light->origin[ 0 ], (int) light->origin[ 1 ], (int) light->origin[ 2 ] ); - } - else - { - /* not a point light */ - numPointLights--; - numSpotLights++; - - /* make a spotlight */ - GetVectorForKey( e2, "origin", dest ); - VectorSubtract( dest, light->origin, light->normal ); - dist = VectorNormalize( light->normal, light->normal ); - radius = FloatForKey( e, "radius" ); - if( !radius ) - radius = 64; - if( !dist ) - dist = 64; - light->radiusByDist = (radius + 16) / dist; - light->type = EMIT_SPOT; - - /* ydnar: wolf mods: spotlights always use nonlinear + angle attenuation */ - light->flags &= ~LIGHT_ATTEN_LINEAR; - light->flags |= LIGHT_ATTEN_ANGLE; - light->fade = 1.0f; - - /* ydnar: is this a sun? */ - _sun = ValueForKey( e, "_sun" ); - if( _sun[ 0 ] == '1' ) - { - /* not a spot light */ - numSpotLights--; - - /* unlink this light */ - lights = light->next; - - /* make a sun */ - VectorScale( light->normal, -1.0f, sun.direction ); - VectorCopy( light->color, sun.color ); - sun.photons = (intensity / pointScale); - sun.deviance = deviance / 180.0f * Q_PI; - sun.numSamples = numSamples; - sun.style = noStyles ? LS_NORMAL : light->style; - sun.next = NULL; - - /* make a sun light */ - CreateSunLight( &sun ); - - /* free original light */ - free( light ); - light = NULL; - - /* skip the rest of this love story */ - continue; - } - } - } - - /* jitter the light */ - for( j = 1; j < numSamples; j++ ) - { - /* create a light */ - light2 = safe_malloc( sizeof( *light ) ); - memcpy( light2, light, sizeof( *light ) ); - light2->next = lights; - lights = light2; - - /* add to counts */ - if( light->type == EMIT_SPOT ) - numSpotLights++; - else - numPointLights++; - - /* jitter it */ - light2->origin[ 0 ] = light->origin[ 0 ] + (Random() * 2.0f - 1.0f) * deviance; - light2->origin[ 1 ] = light->origin[ 1 ] + (Random() * 2.0f - 1.0f) * deviance; - light2->origin[ 2 ] = light->origin[ 2 ] + (Random() * 2.0f - 1.0f) * deviance; - } - } -} - - - -/* -CreateSurfaceLights() - ydnar -this hijacks the radiosity code to generate surface lights for first pass -*/ - -#define APPROX_BOUNCE 1.0f - -void CreateSurfaceLights( void ) -{ - int i; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - shaderInfo_t *si; - light_t *light; - float subdivide; - vec3_t origin; - clipWork_t cw; - const char *nss; - - - /* get sun shader supressor */ - nss = ValueForKey( &entities[ 0 ], "_noshadersun" ); - - /* walk the list of surfaces */ - for( i = 0; i < numBSPDrawSurfaces; i++ ) - { - /* get surface and other bits */ - ds = &bspDrawSurfaces[ i ]; - info = &surfaceInfos[ i ]; - si = info->si; - - /* sunlight? */ - if( si->sun != NULL && nss[ 0 ] != '1' ) - { - Sys_FPrintf( SYS_VRB, "Sun: %s\n", si->shader ); - CreateSunLight( si->sun ); - si->sun = NULL; /* FIXME: leak! */ - } - - /* sky light? */ - if( si->skyLightValue > 0.0f ) - { - Sys_FPrintf( SYS_VRB, "Sky: %s\n", si->shader ); - CreateSkyLights( si->color, si->skyLightValue, si->skyLightIterations, si->lightFilterRadius, si->lightStyle ); - si->skyLightValue = 0.0f; /* FIXME: hack! */ - } - - /* try to early out */ - if( si->value <= 0 ) - continue; - - /* autosprite shaders become point lights */ - if( si->autosprite ) - { - /* create an average xyz */ - VectorAdd( info->mins, info->maxs, origin ); - VectorScale( origin, 0.5f, origin ); - - /* create a light */ - light = safe_malloc( sizeof( *light ) ); - memset( light, 0, sizeof( *light ) ); - light->next = lights; - lights = light; - - /* set it up */ - light->flags = LIGHT_Q3A_DEFAULT; - light->type = EMIT_POINT; - light->photons = si->value * pointScale; - light->fade = 1.0f; - light->si = si; - VectorCopy( origin, light->origin ); - VectorCopy( si->color, light->color ); - light->falloffTolerance = falloffTolerance; - light->style = si->lightStyle; - - /* add to point light count and continue */ - numPointLights++; - continue; - } - - /* get subdivision amount */ - if( si->lightSubdivide > 0 ) - subdivide = si->lightSubdivide; - else - subdivide = defaultLightSubdivide; - - /* switch on type */ - switch( ds->surfaceType ) - { - case MST_PLANAR: - case MST_TRIANGLE_SOUP: - RadLightForTriangles( i, 0, info->lm, si, APPROX_BOUNCE, subdivide, &cw ); - break; - - case MST_PATCH: - RadLightForPatch( i, 0, info->lm, si, APPROX_BOUNCE, subdivide, &cw ); - break; - - default: - break; - } - } -} - - - -/* -SetEntityOrigins() -find the offset values for inline models -*/ - -void SetEntityOrigins( void ) -{ - int i, j, k, f; - entity_t *e; - vec3_t origin; - const char *key; - int modelnum; - bspModel_t *dm; - bspDrawSurface_t *ds; - - - /* ydnar: copy drawverts into private storage for nefarious purposes */ - yDrawVerts = safe_malloc( numBSPDrawVerts * sizeof( bspDrawVert_t ) ); - memcpy( yDrawVerts, bspDrawVerts, numBSPDrawVerts * sizeof( bspDrawVert_t ) ); - - /* set the entity origins */ - for( i = 0; i < numEntities; i++ ) - { - /* get entity and model */ - e = &entities[ i ]; - key = ValueForKey( e, "model" ); - if( key[ 0 ] != '*' ) - continue; - modelnum = atoi( key + 1 ); - dm = &bspModels[ modelnum ]; - - /* get entity origin */ - key = ValueForKey( e, "origin" ); - if( key[ 0 ] == '\0' ) - continue; - GetVectorForKey( e, "origin", origin ); - - /* set origin for all surfaces for this model */ - for( j = 0; j < dm->numBSPSurfaces; j++ ) - { - /* get drawsurf */ - ds = &bspDrawSurfaces[ dm->firstBSPSurface + j ]; - - /* set its verts */ - for( k = 0; k < ds->numVerts; k++ ) - { - f = ds->firstVert + k; - VectorAdd( origin, bspDrawVerts[ f ].xyz, yDrawVerts[ f ].xyz ); - } - } - } -} - - - -/* -PointToPolygonFormFactor() -calculates the area over a point/normal hemisphere a winding covers -ydnar: fixme: there has to be a faster way to calculate this -without the expensive per-vert sqrts and transcendental functions -ydnar 2002-09-30: added -faster switch because only 19% deviance > 10% -between this and the approximation -*/ - -#define ONE_OVER_2PI 0.159154942f //% (1.0f / (2.0f * 3.141592657f)) - -float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w ) -{ - vec3_t triVector, triNormal; - int i, j; - vec3_t dirs[ MAX_POINTS_ON_WINDING ]; - float total; - float dot, angle, facing; - - - /* this is expensive */ - for( i = 0; i < w->numpoints; i++ ) - { - VectorSubtract( w->p[ i ], point, dirs[ i ] ); - VectorNormalize( dirs[ i ], dirs[ i ] ); - } - - /* duplicate first vertex to avoid mod operation */ - VectorCopy( dirs[ 0 ], dirs[ i ] ); - - /* calculcate relative area */ - total = 0.0f; - for( i = 0; i < w->numpoints; i++ ) - { - /* get a triangle */ - j = i + 1; - dot = DotProduct( dirs[ i ], dirs[ j ] ); - - /* roundoff can cause slight creep, which gives an IND from acos */ - if( dot > 1.0f ) - dot = 1.0f; - else if( dot < -1.0f ) - dot = -1.0f; - - /* get the angle */ - angle = acos( dot ); - - CrossProduct( dirs[ i ], dirs[ j ], triVector ); - if( VectorNormalize( triVector, triNormal ) < 0.0001f ) - continue; - - facing = DotProduct( normal, triNormal ); - total += facing * angle; - - /* ydnar: this was throwing too many errors with radiosity + crappy maps. ignoring it. */ - if( total > 6.3f || total < -6.3f ) - return 0.0f; - } - - /* now in the range of 0 to 1 over the entire incoming hemisphere */ - //% total /= (2.0f * 3.141592657f); - total *= ONE_OVER_2PI; - return total; -} - - - -/* -LightContributionTosample() -determines the amount of light reaching a sample (luxel or vertex) from a given light -*/ - -int LightContributionToSample( trace_t *trace ) -{ - light_t *light; - float angle; - float add; - float dist; - float addDeluxe = 0.0f, addDeluxeBounceScale = 0.25f; - qboolean angledDeluxe = qtrue; - float colorBrightness; - qboolean doAddDeluxe = qtrue; - - /* get light */ - light = trace->light; - - /* clear color */ - trace->forceSubsampling = 0.0f; /* to make sure */ - VectorClear( trace->color ); - VectorClear( trace->colorNoShadow ); - VectorClear( trace->directionContribution ); - - colorBrightness = RGBTOGRAY( light->color ) * ( 1.0f/255.0f ); - - /* ydnar: early out */ - if( !(light->flags & LIGHT_SURFACES) || light->envelope <= 0.0f ) - return 0; - - /* do some culling checks */ - if( light->type != EMIT_SUN ) - { - /* MrE: if the light is behind the surface */ - if( trace->twoSided == qfalse ) - if( DotProduct( light->origin, trace->normal ) - DotProduct( trace->origin, trace->normal ) < 0.0f ) - return 0; - - /* ydnar: test pvs */ - if( !ClusterVisible( trace->cluster, light->cluster ) ) - return 0; - } - - /* exact point to polygon form factor */ - if( light->type == EMIT_AREA ) - { - float factor; - float d; - vec3_t pushedOrigin; - - /* project sample point into light plane */ - d = DotProduct( trace->origin, light->normal ) - light->dist; - if( d < 3.0f ) - { - /* sample point behind plane? */ - if( !(light->flags & LIGHT_TWOSIDED) && d < -1.0f ) - return 0; - - /* sample plane coincident? */ - if( d > -3.0f && DotProduct( trace->normal, light->normal ) > 0.9f ) - return 0; - } - - /* nudge the point so that it is clearly forward of the light */ - /* so that surfaces meeting a light emitter don't get black edges */ - if( d > -8.0f && d < 8.0f ) - VectorMA( trace->origin, (8.0f - d), light->normal, pushedOrigin ); - else - VectorCopy( trace->origin, pushedOrigin ); - - /* get direction and distance */ - VectorCopy( light->origin, trace->end ); - dist = SetupTrace( trace ); - if( dist >= light->envelope ) - return 0; - - /* ptpff approximation */ - if( faster ) - { - /* angle attenuation */ - angle = DotProduct( trace->normal, trace->direction ); - - /* twosided lighting */ - if( trace->twoSided && angle < 0 ) - { - angle = -angle; - - /* no deluxemap contribution from "other side" light */ - doAddDeluxe = qfalse; - } - - /* attenuate */ - angle *= -DotProduct( light->normal, trace->direction ); - if( angle == 0.0f ) - return 0; - else if( angle < 0.0f && - (trace->twoSided || (light->flags & LIGHT_TWOSIDED)) ) - { - angle = -angle; - - /* no deluxemap contribution from "other side" light */ - doAddDeluxe = qfalse; - } - - /* clamp the distance to prevent super hot spots */ - dist = sqrt(dist * dist + light->extraDist * light->extraDist); - if( dist < 16.0f ) - dist = 16.0f; - - add = light->photons / (dist * dist) * angle; - - if( deluxemap ) - { - if( angledDeluxe ) - addDeluxe = light->photons / (dist * dist) * angle; - else - addDeluxe = light->photons / (dist * dist); - } - } - else - { - /* calculate the contribution */ - factor = PointToPolygonFormFactor( pushedOrigin, trace->normal, light->w ); - if( factor == 0.0f ) - return 0; - else if( factor < 0.0f ) - { - /* twosided lighting */ - if( trace->twoSided || (light->flags & LIGHT_TWOSIDED) ) - { - factor = -factor; - - /* push light origin to other side of the plane */ - VectorMA( light->origin, -2.0f, light->normal, trace->end ); - dist = SetupTrace( trace ); - if( dist >= light->envelope ) - return 0; - - /* no deluxemap contribution from "other side" light */ - doAddDeluxe = qfalse; - } - else - return 0; - } - - /* also don't deluxe if the direction is on the wrong side */ - if(DotProduct(trace->normal, trace->direction) < 0) - { - /* no deluxemap contribution from "other side" light */ - doAddDeluxe = qfalse; - } - - /* ydnar: moved to here */ - add = factor * light->add; - - if( deluxemap ) - addDeluxe = add; - } - } - - /* point/spot lights */ - else if( light->type == EMIT_POINT || light->type == EMIT_SPOT ) - { - /* get direction and distance */ - VectorCopy( light->origin, trace->end ); - dist = SetupTrace( trace ); - if( dist >= light->envelope ) - return 0; - - /* clamp the distance to prevent super hot spots */ - dist = sqrt(dist * dist + light->extraDist * light->extraDist); - if( dist < 16.0f ) - dist = 16.0f; - - /* angle attenuation */ - if( light->flags & LIGHT_ATTEN_ANGLE ) - { - /* standard Lambert attenuation */ - float dot = DotProduct( trace->normal, trace->direction ); - - /* twosided lighting */ - if( trace->twoSided && dot < 0 ) - { - dot = -dot; - - /* no deluxemap contribution from "other side" light */ - doAddDeluxe = qfalse; - } - - /* jal: optional half Lambert attenuation (http://developer.valvesoftware.com/wiki/Half_Lambert) */ - if( lightAngleHL ) - { - if( dot > 0.001f ) // skip coplanar - { - if( dot > 1.0f ) dot = 1.0f; - dot = ( dot * 0.5f ) + 0.5f; - dot *= dot; - } - else - dot = 0; - } - - angle = dot; - } - else - angle = 1.0f; - - if( light->angleScale != 0.0f ) - { - angle /= light->angleScale; - if( angle > 1.0f ) - angle = 1.0f; - } - - /* attenuate */ - if( light->flags & LIGHT_ATTEN_LINEAR ) - { - add = angle * light->photons * linearScale - (dist * light->fade); - if( add < 0.0f ) - add = 0.0f; - - if( deluxemap ) - { - if( angledDeluxe ) - addDeluxe = angle * light->photons * linearScale - (dist * light->fade); - else - addDeluxe = light->photons * linearScale - (dist * light->fade); - - if( addDeluxe < 0.0f ) - addDeluxe = 0.0f; - } - } - else - { - add = (light->photons / (dist * dist)) * angle; - if( add < 0.0f ) - add = 0.0f; - - if( deluxemap ) - { - if( angledDeluxe ) - addDeluxe = (light->photons / (dist * dist)) * angle; - else - addDeluxe = (light->photons / (dist * dist)); - } - - if( addDeluxe < 0.0f ) - addDeluxe = 0.0f; - } - - /* handle spotlights */ - if( light->type == EMIT_SPOT ) - { - float distByNormal, radiusAtDist, sampleRadius; - vec3_t pointAtDist, distToSample; - - /* do cone calculation */ - distByNormal = -DotProduct( trace->displacement, light->normal ); - if( distByNormal < 0.0f ) - return 0; - VectorMA( light->origin, distByNormal, light->normal, pointAtDist ); - radiusAtDist = light->radiusByDist * distByNormal; - VectorSubtract( trace->origin, pointAtDist, distToSample ); - sampleRadius = VectorLength( distToSample ); - - /* outside the cone */ - if( sampleRadius >= radiusAtDist ) - return 0; - - /* attenuate */ - if( sampleRadius > (radiusAtDist - 32.0f) ) - { - add *= ((radiusAtDist - sampleRadius) / 32.0f); - if( add < 0.0f ) - add = 0.0f; - - addDeluxe *= ((radiusAtDist - sampleRadius) / 32.0f); - - if( addDeluxe < 0.0f ) - addDeluxe = 0.0f; - } - } - } - - /* ydnar: sunlight */ - else if( light->type == EMIT_SUN ) - { - /* get origin and direction */ - VectorAdd( trace->origin, light->origin, trace->end ); - dist = SetupTrace( trace ); - - /* angle attenuation */ - if( light->flags & LIGHT_ATTEN_ANGLE ) - { - /* standard Lambert attenuation */ - float dot = DotProduct( trace->normal, trace->direction ); - - /* twosided lighting */ - if( trace->twoSided && dot < 0 ) - { - dot = -dot; - - /* no deluxemap contribution from "other side" light */ - doAddDeluxe = qfalse; - } - - /* jal: optional half Lambert attenuation (http://developer.valvesoftware.com/wiki/Half_Lambert) */ - if( lightAngleHL ) - { - if( dot > 0.001f ) // skip coplanar - { - if( dot > 1.0f ) dot = 1.0f; - dot = ( dot * 0.5f ) + 0.5f; - dot *= dot; - } - else - dot = 0; - } - - angle = dot; - } - else - angle = 1.0f; - - /* attenuate */ - add = light->photons * angle; - - if( deluxemap ) - { - if( angledDeluxe ) - addDeluxe = light->photons * angle; - else - addDeluxe = light->photons; - - if( addDeluxe < 0.0f ) - addDeluxe = 0.0f; - } - - if( add <= 0.0f ) - return 0; - - /* VorteX: set noShadow color */ - VectorScale(light->color, add, trace->colorNoShadow); - - addDeluxe *= colorBrightness; - - if( bouncing ) - { - addDeluxe *= addDeluxeBounceScale; - if( addDeluxe < 0.00390625f ) - addDeluxe = 0.00390625f; - } - - VectorScale( trace->direction, addDeluxe, trace->directionContribution ); - - /* setup trace */ - trace->testAll = qtrue; - VectorScale( light->color, add, trace->color ); - - /* trace to point */ - if( trace->testOcclusion && !trace->forceSunlight ) - { - /* trace */ - TraceLine( trace ); - trace->forceSubsampling *= add; - if( !(trace->compileFlags & C_SKY) || trace->opaque ) - { - VectorClear( trace->color ); - VectorClear( trace->directionContribution ); - - return -1; - } - } - - /* return to sender */ - return 1; - } - else - Error("Light of undefined type!"); - - /* VorteX: set noShadow color */ - VectorScale(light->color, add, trace->colorNoShadow); - - /* ydnar: changed to a variable number */ - if( add <= 0.0f || (add <= light->falloffTolerance && (light->flags & LIGHT_FAST_ACTUAL)) ) - return 0; - - addDeluxe *= colorBrightness; - - /* hack land: scale down the radiosity contribution to light directionality. - Deluxemaps fusion many light directions into one. In a rtl process all lights - would contribute individually to the bump map, so several light sources together - would make it more directional (example: a yellow and red lights received from - opposing sides would light one side in red and the other in blue, adding - the effect of 2 directions applied. In the deluxemapping case, this 2 lights would - neutralize each other making it look like having no direction. - Same thing happens with radiosity. In deluxemapping case the radiosity contribution - is modifying the direction applied from directional lights, making it go closer and closer - to the surface normal the bigger is the amount of radiosity received. - So, for preserving the directional lights contributions, we scale down the radiosity - contribution. It's a hack, but there's a reason behind it */ - if( bouncing ) - { - addDeluxe *= addDeluxeBounceScale; - /* better NOT increase it beyond the original value - if( addDeluxe < 0.00390625f ) - addDeluxe = 0.00390625f; - */ - } - - if(doAddDeluxe) - { - VectorScale( trace->direction, addDeluxe, trace->directionContribution ); - } - - /* setup trace */ - trace->testAll = qfalse; - VectorScale( light->color, add, trace->color ); - - /* raytrace */ - TraceLine( trace ); - trace->forceSubsampling *= add; - if( trace->passSolid || trace->opaque ) - { - VectorClear( trace->color ); - VectorClear( trace->directionContribution ); - - return -1; - } - - /* return to sender */ - return 1; -} - - - -/* -LightingAtSample() -determines the amount of light reaching a sample (luxel or vertex) -*/ - -void LightingAtSample( trace_t *trace, byte styles[ MAX_LIGHTMAPS ], vec3_t colors[ MAX_LIGHTMAPS ] ) -{ - int i, lightmapNum; - - - /* clear colors */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - VectorClear( colors[ lightmapNum ] ); - - /* ydnar: normalmap */ - if( normalmap ) - { - colors[ 0 ][ 0 ] = (trace->normal[ 0 ] + 1.0f) * 127.5f; - colors[ 0 ][ 1 ] = (trace->normal[ 1 ] + 1.0f) * 127.5f; - colors[ 0 ][ 2 ] = (trace->normal[ 2 ] + 1.0f) * 127.5f; - return; - } - - /* ydnar: don't bounce ambient all the time */ - if( !bouncing ) - VectorCopy( ambientColor, colors[ 0 ] ); - - /* ydnar: trace to all the list of lights pre-stored in tw */ - for( i = 0; i < trace->numLights && trace->lights[ i ] != NULL; i++ ) - { - /* set light */ - trace->light = trace->lights[ i ]; - - /* style check */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - if( styles[ lightmapNum ] == trace->light->style || - styles[ lightmapNum ] == LS_NONE ) - break; - } - - /* max of MAX_LIGHTMAPS (4) styles allowed to hit a sample */ - if( lightmapNum >= MAX_LIGHTMAPS ) - continue; - - /* sample light */ - LightContributionToSample( trace ); - if( trace->color[ 0 ] == 0.0f && trace->color[ 1 ] == 0.0f && trace->color[ 2 ] == 0.0f ) - continue; - - /* handle negative light */ - if( trace->light->flags & LIGHT_NEGATIVE ) - VectorScale( trace->color, -1.0f, trace->color ); - - /* set style */ - styles[ lightmapNum ] = trace->light->style; - - /* add it */ - VectorAdd( colors[ lightmapNum ], trace->color, colors[ lightmapNum ] ); - - /* cheap mode */ - if( cheap && - colors[ 0 ][ 0 ] >= 255.0f && - colors[ 0 ][ 1 ] >= 255.0f && - colors[ 0 ][ 2 ] >= 255.0f ) - break; - } -} - - - -/* -LightContributionToPoint() -for a given light, how much light/color reaches a given point in space (with no facing) -note: this is similar to LightContributionToSample() but optimized for omnidirectional sampling -*/ - -int LightContributionToPoint( trace_t *trace ) -{ - light_t *light; - float add, dist; - - - /* get light */ - light = trace->light; - - /* clear color */ - VectorClear( trace->color ); - - /* ydnar: early out */ - if( !(light->flags & LIGHT_GRID) || light->envelope <= 0.0f ) - return qfalse; - - /* is this a sun? */ - if( light->type != EMIT_SUN ) - { - /* sun only? */ - if( sunOnly ) - return qfalse; - - /* test pvs */ - if( !ClusterVisible( trace->cluster, light->cluster ) ) - return qfalse; - } - - /* ydnar: check origin against light's pvs envelope */ - if( trace->origin[ 0 ] > light->maxs[ 0 ] || trace->origin[ 0 ] < light->mins[ 0 ] || - trace->origin[ 1 ] > light->maxs[ 1 ] || trace->origin[ 1 ] < light->mins[ 1 ] || - trace->origin[ 2 ] > light->maxs[ 2 ] || trace->origin[ 2 ] < light->mins[ 2 ] ) - { - gridBoundsCulled++; - return qfalse; - } - - /* set light origin */ - if( light->type == EMIT_SUN ) - VectorAdd( trace->origin, light->origin, trace->end ); - else - VectorCopy( light->origin, trace->end ); - - /* set direction */ - dist = SetupTrace( trace ); - - /* test envelope */ - if( dist > light->envelope ) - { - gridEnvelopeCulled++; - return qfalse; - } - - /* ptpff approximation */ - if( light->type == EMIT_AREA && faster ) - { - /* clamp the distance to prevent super hot spots */ - dist = sqrt(dist * dist + light->extraDist * light->extraDist); - if( dist < 16.0f ) - dist = 16.0f; - - /* attenuate */ - add = light->photons / (dist * dist); - } - - /* exact point to polygon form factor */ - else if( light->type == EMIT_AREA ) - { - float factor, d; - vec3_t pushedOrigin; - - - /* see if the point is behind the light */ - d = DotProduct( trace->origin, light->normal ) - light->dist; - if( !(light->flags & LIGHT_TWOSIDED) && d < -1.0f ) - return qfalse; - - /* nudge the point so that it is clearly forward of the light */ - /* so that surfaces meeting a light emiter don't get black edges */ - if( d > -8.0f && d < 8.0f ) - VectorMA( trace->origin, (8.0f - d), light->normal, pushedOrigin ); - else - VectorCopy( trace->origin, pushedOrigin ); - - /* calculate the contribution (ydnar 2002-10-21: [bug 642] bad normal calc) */ - factor = PointToPolygonFormFactor( pushedOrigin, trace->direction, light->w ); - if( factor == 0.0f ) - return qfalse; - else if( factor < 0.0f ) - { - if( light->flags & LIGHT_TWOSIDED ) - factor = -factor; - else - return qfalse; - } - - /* ydnar: moved to here */ - add = factor * light->add; - } - - /* point/spot lights */ - else if( light->type == EMIT_POINT || light->type == EMIT_SPOT ) - { - /* clamp the distance to prevent super hot spots */ - dist = sqrt(dist * dist + light->extraDist * light->extraDist); - if( dist < 16.0f ) - dist = 16.0f; - - /* attenuate */ - if( light->flags & LIGHT_ATTEN_LINEAR ) - { - add = light->photons * linearScale - (dist * light->fade); - if( add < 0.0f ) - add = 0.0f; - } - else - add = light->photons / (dist * dist); - - /* handle spotlights */ - if( light->type == EMIT_SPOT ) - { - float distByNormal, radiusAtDist, sampleRadius; - vec3_t pointAtDist, distToSample; - - - /* do cone calculation */ - distByNormal = -DotProduct( trace->displacement, light->normal ); - if( distByNormal < 0.0f ) - return qfalse; - VectorMA( light->origin, distByNormal, light->normal, pointAtDist ); - radiusAtDist = light->radiusByDist * distByNormal; - VectorSubtract( trace->origin, pointAtDist, distToSample ); - sampleRadius = VectorLength( distToSample ); - - /* outside the cone */ - if( sampleRadius >= radiusAtDist ) - return qfalse; - - /* attenuate */ - if( sampleRadius > (radiusAtDist - 32.0f) ) - add *= ((radiusAtDist - sampleRadius) / 32.0f); - } - } - - /* ydnar: sunlight */ - else if( light->type == EMIT_SUN ) - { - /* attenuate */ - add = light->photons; - if( add <= 0.0f ) - return qfalse; - - /* setup trace */ - trace->testAll = qtrue; - VectorScale( light->color, add, trace->color ); - - /* trace to point */ - if( trace->testOcclusion && !trace->forceSunlight ) - { - /* trace */ - TraceLine( trace ); - if( !(trace->compileFlags & C_SKY) || trace->opaque ) - { - VectorClear( trace->color ); - return -1; - } - } - - /* return to sender */ - return qtrue; - } - - /* unknown light type */ - else - return qfalse; - - /* ydnar: changed to a variable number */ - if( add <= 0.0f || (add <= light->falloffTolerance && (light->flags & LIGHT_FAST_ACTUAL)) ) - return qfalse; - - /* setup trace */ - trace->testAll = qfalse; - VectorScale( light->color, add, trace->color ); - - /* trace */ - TraceLine( trace ); - if( trace->passSolid ) - { - VectorClear( trace->color ); - return qfalse; - } - - /* we have a valid sample */ - return qtrue; -} - - - -/* -TraceGrid() -grid samples are for quickly determining the lighting -of dynamically placed entities in the world -*/ - -#define MAX_CONTRIBUTIONS 32768 - -typedef struct -{ - vec3_t dir; - vec3_t color; - vec3_t ambient; - int style; -} -contribution_t; - -void TraceGrid( int num ) -{ - int i, j, x, y, z, mod, numCon, numStyles; - float d, step; - vec3_t baseOrigin, cheapColor, color, thisdir; - rawGridPoint_t *gp; - bspGridPoint_t *bgp; - contribution_t contributions[ MAX_CONTRIBUTIONS ]; - trace_t trace; - - /* get grid points */ - gp = &rawGridPoints[ num ]; - bgp = &bspGridPoints[ num ]; - - /* get grid origin */ - mod = num; - z = mod / (gridBounds[ 0 ] * gridBounds[ 1 ]); - mod -= z * (gridBounds[ 0 ] * gridBounds[ 1 ]); - y = mod / gridBounds[ 0 ]; - mod -= y * gridBounds[ 0 ]; - x = mod; - - trace.origin[ 0 ] = gridMins[ 0 ] + x * gridSize[ 0 ]; - trace.origin[ 1 ] = gridMins[ 1 ] + y * gridSize[ 1 ]; - trace.origin[ 2 ] = gridMins[ 2 ] + z * gridSize[ 2 ]; - - /* set inhibit sphere */ - if( gridSize[ 0 ] > gridSize[ 1 ] && gridSize[ 0 ] > gridSize[ 2 ] ) - trace.inhibitRadius = gridSize[ 0 ] * 0.5f; - else if( gridSize[ 1 ] > gridSize[ 0 ] && gridSize[ 1 ] > gridSize[ 2 ] ) - trace.inhibitRadius = gridSize[ 1 ] * 0.5f; - else - trace.inhibitRadius = gridSize[ 2 ] * 0.5f; - - /* find point cluster */ - trace.cluster = ClusterForPointExt( trace.origin, GRID_EPSILON ); - if( trace.cluster < 0 ) - { - /* try to nudge the origin around to find a valid point */ - VectorCopy( trace.origin, baseOrigin ); - for( step = 0; (step += 0.005) <= 1.0; ) - { - VectorCopy( baseOrigin, trace.origin ); - trace.origin[ 0 ] += step * (Random() - 0.5) * gridSize[0]; - trace.origin[ 1 ] += step * (Random() - 0.5) * gridSize[1]; - trace.origin[ 2 ] += step * (Random() - 0.5) * gridSize[2]; - - /* ydnar: changed to find cluster num */ - trace.cluster = ClusterForPointExt( trace.origin, VERTEX_EPSILON ); - if( trace.cluster >= 0 ) - break; - } - - /* can't find a valid point at all */ - if( step > 1.0 ) - return; - } - - /* setup trace */ - trace.testOcclusion = !noTrace; - trace.forceSunlight = qfalse; - trace.recvShadows = WORLDSPAWN_RECV_SHADOWS; - trace.numSurfaces = 0; - trace.surfaces = NULL; - trace.numLights = 0; - trace.lights = NULL; - - /* clear */ - numCon = 0; - VectorClear( cheapColor ); - - /* trace to all the lights, find the major light direction, and divide the - total light between that along the direction and the remaining in the ambient */ - for( trace.light = lights; trace.light != NULL; trace.light = trace.light->next ) - { - float addSize; - - - /* sample light */ - if( !LightContributionToPoint( &trace ) ) - continue; - - /* handle negative light */ - if( trace.light->flags & LIGHT_NEGATIVE ) - VectorScale( trace.color, -1.0f, trace.color ); - - /* add a contribution */ - VectorCopy( trace.color, contributions[ numCon ].color ); - VectorCopy( trace.direction, contributions[ numCon ].dir ); - VectorClear( contributions[ numCon ].ambient ); - contributions[ numCon ].style = trace.light->style; - numCon++; - - /* push average direction around */ - addSize = VectorLength( trace.color ); - VectorMA( gp->dir, addSize, trace.direction, gp->dir ); - - /* stop after a while */ - if( numCon >= (MAX_CONTRIBUTIONS - 1) ) - break; - - /* ydnar: cheap mode */ - VectorAdd( cheapColor, trace.color, cheapColor ); - if( cheapgrid && cheapColor[ 0 ] >= 255.0f && cheapColor[ 1 ] >= 255.0f && cheapColor[ 2 ] >= 255.0f ) - break; - } - - /////// Floodlighting for point ////////////////// - //do our floodlight ambient occlusion loop, and add a single contribution based on the brightest dir - if( floodlighty ) - { - int k; - float addSize, f; - vec3_t dir = { 0, 0, 1 }; - float ambientFrac = 0.25f; - - trace.testOcclusion = qtrue; - trace.forceSunlight = qfalse; - trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; - trace.testAll = qtrue; - - for( k = 0; k < 2; k++ ) - { - if( k == 0 ) // upper hemisphere - { - trace.normal[0] = 0; - trace.normal[1] = 0; - trace.normal[2] = 1; - } - else //lower hemisphere - { - trace.normal[0] = 0; - trace.normal[1] = 0; - trace.normal[2] = -1; - } - - f = FloodLightForSample( &trace, floodlightDistance, floodlight_lowquality ); - - /* add a fraction as pure ambient, half as top-down direction */ - contributions[ numCon ].color[0]= floodlightRGB[0] * floodlightIntensity * f * ( 1.0f - ambientFrac ); - contributions[ numCon ].color[1]= floodlightRGB[1] * floodlightIntensity * f * ( 1.0f - ambientFrac ); - contributions[ numCon ].color[2]= floodlightRGB[2] * floodlightIntensity * f * ( 1.0f - ambientFrac ); - - contributions[ numCon ].ambient[0]= floodlightRGB[0] * floodlightIntensity * f * ambientFrac; - contributions[ numCon ].ambient[1]= floodlightRGB[1] * floodlightIntensity * f * ambientFrac; - contributions[ numCon ].ambient[2]= floodlightRGB[2] * floodlightIntensity * f * ambientFrac; - - contributions[ numCon ].dir[0] = dir[0]; - contributions[ numCon ].dir[1] = dir[1]; - contributions[ numCon ].dir[2] = dir[2]; - - contributions[ numCon ].style = 0; - - /* push average direction around */ - addSize = VectorLength( contributions[ numCon ].color ); - VectorMA( gp->dir, addSize, dir, gp->dir ); - - numCon++; - } - } - ///////////////////// - - /* normalize to get primary light direction */ - VectorNormalize( gp->dir, thisdir ); - - /* now that we have identified the primary light direction, - go back and separate all the light into directed and ambient */ - - numStyles = 1; - for( i = 0; i < numCon; i++ ) - { - /* get relative directed strength */ - d = DotProduct( contributions[ i ].dir, thisdir ); - /* we map 1 to gridDirectionality, and 0 to gridAmbientDirectionality */ - d = gridAmbientDirectionality + d * (gridDirectionality - gridAmbientDirectionality); - if( d < 0.0f ) - d = 0.0f; - - /* find appropriate style */ - for( j = 0; j < numStyles; j++ ) - { - if( gp->styles[ j ] == contributions[ i ].style ) - break; - } - - /* style not found? */ - if( j >= numStyles ) - { - /* add a new style */ - if( numStyles < MAX_LIGHTMAPS ) - { - gp->styles[ numStyles ] = contributions[ i ].style; - bgp->styles[ numStyles ] = contributions[ i ].style; - numStyles++; - //% Sys_Printf( "(%d, %d) ", num, contributions[ i ].style ); - } - - /* fallback */ - else - j = 0; - } - - /* add the directed color */ - VectorMA( gp->directed[ j ], d, contributions[ i ].color, gp->directed[ j ] ); - - /* ambient light will be at 1/4 the value of directed light */ - /* (ydnar: nuke this in favor of more dramatic lighting?) */ - /* (PM: how about actually making it work? d=1 when it got here for single lights/sun :P */ -// d = 0.25f; - /* (Hobbes: always setting it to .25 is hardly any better) */ - d = 0.25f * (1.0f - d); - VectorMA( gp->ambient[ j ], d, contributions[ i ].color, gp->ambient[ j ] ); - - VectorAdd( gp->ambient[ j ], contributions[ i ].ambient, gp->ambient[ j ] ); - -/* - * div0: - * the total light average = ambient value + 0.25 * sum of all directional values - * we can also get the total light average as 0.25 * the sum of all contributions - * - * 0.25 * sum(contribution_i) == ambient + 0.25 * sum(d_i contribution_i) - * - * THIS YIELDS: - * ambient == 0.25 * sum((1 - d_i) contribution_i) - * - * So, 0.25f * (1.0f - d) IS RIGHT. If you want to tune it, tune d BEFORE. - */ - } - - - /* store off sample */ - for( i = 0; i < MAX_LIGHTMAPS; i++ ) - { -#if 0 - /* do some fudging to keep the ambient from being too low (2003-07-05: 0.25 -> 0.125) */ - if( !bouncing ) - VectorMA( gp->ambient[ i ], 0.125f, gp->directed[ i ], gp->ambient[ i ] ); -#endif - - /* set minimum light and copy off to bytes */ - VectorCopy( gp->ambient[ i ], color ); - for( j = 0; j < 3; j++ ) - if( color[ j ] < minGridLight[ j ] ) - color[ j ] = minGridLight[ j ]; - - /* vortex: apply gridscale and gridambientscale here */ - ColorToBytes( color, bgp->ambient[ i ], gridScale*gridAmbientScale ); - ColorToBytes( gp->directed[ i ], bgp->directed[ i ], gridScale ); - } - - /* debug code */ - #if 0 - //% Sys_FPrintf( SYS_VRB, "%10d %10d %10d ", &gp->ambient[ 0 ][ 0 ], &gp->ambient[ 0 ][ 1 ], &gp->ambient[ 0 ][ 2 ] ); - Sys_FPrintf( SYS_VRB, "%9d Amb: (%03.1f %03.1f %03.1f) Dir: (%03.1f %03.1f %03.1f)\n", - num, - gp->ambient[ 0 ][ 0 ], gp->ambient[ 0 ][ 1 ], gp->ambient[ 0 ][ 2 ], - gp->directed[ 0 ][ 0 ], gp->directed[ 0 ][ 1 ], gp->directed[ 0 ][ 2 ] ); - #endif - - /* store direction */ - NormalToLatLong( thisdir, bgp->latLong ); -} - - - -/* -SetupGrid() -calculates the size of the lightgrid and allocates memory -*/ - -void SetupGrid( void ) -{ - int i, j; - vec3_t maxs, oldGridSize; - const char *value; - char temp[ 64 ]; - - - /* don't do this if not grid lighting */ - if( noGridLighting ) - return; - - /* ydnar: set grid size */ - value = ValueForKey( &entities[ 0 ], "gridsize" ); - if( value[ 0 ] != '\0' ) - sscanf( value, "%f %f %f", &gridSize[ 0 ], &gridSize[ 1 ], &gridSize[ 2 ] ); - - /* quantize it */ - VectorCopy( gridSize, oldGridSize ); - for( i = 0; i < 3; i++ ) - gridSize[ i ] = gridSize[ i ] >= 8.0f ? floor( gridSize[ i ] ) : 8.0f; - - /* ydnar: increase gridSize until grid count is smaller than max allowed */ - numRawGridPoints = MAX_MAP_LIGHTGRID + 1; - j = 0; - while( numRawGridPoints > MAX_MAP_LIGHTGRID ) - { - /* get world bounds */ - for( i = 0; i < 3; i++ ) - { - gridMins[ i ] = gridSize[ i ] * ceil( bspModels[ 0 ].mins[ i ] / gridSize[ i ] ); - maxs[ i ] = gridSize[ i ] * floor( bspModels[ 0 ].maxs[ i ] / gridSize[ i ] ); - gridBounds[ i ] = (maxs[ i ] - gridMins[ i ]) / gridSize[ i ] + 1; - } - - /* set grid size */ - numRawGridPoints = gridBounds[ 0 ] * gridBounds[ 1 ] * gridBounds[ 2 ]; - - /* increase grid size a bit */ - if( numRawGridPoints > MAX_MAP_LIGHTGRID ) - gridSize[ j++ % 3 ] += 16.0f; - } - - /* print it */ - Sys_Printf( "Grid size = { %1.0f, %1.0f, %1.0f }\n", gridSize[ 0 ], gridSize[ 1 ], gridSize[ 2 ] ); - - /* different? */ - if( !VectorCompare( gridSize, oldGridSize ) ) - { - sprintf( temp, "%.0f %.0f %.0f", gridSize[ 0 ], gridSize[ 1 ], gridSize[ 2 ] ); - SetKeyValue( &entities[ 0 ], "gridsize", (const char*) temp ); - Sys_FPrintf( SYS_VRB, "Storing adjusted grid size\n" ); - } - - /* 2nd variable. fixme: is this silly? */ - numBSPGridPoints = numRawGridPoints; - - /* allocate lightgrid */ - rawGridPoints = safe_malloc( numRawGridPoints * sizeof( *rawGridPoints ) ); - memset( rawGridPoints, 0, numRawGridPoints * sizeof( *rawGridPoints ) ); - - if( bspGridPoints != NULL ) - free( bspGridPoints ); - bspGridPoints = safe_malloc( numBSPGridPoints * sizeof( *bspGridPoints ) ); - memset( bspGridPoints, 0, numBSPGridPoints * sizeof( *bspGridPoints ) ); - - /* clear lightgrid */ - for( i = 0; i < numRawGridPoints; i++ ) - { - VectorCopy( ambientColor, rawGridPoints[ i ].ambient[ j ] ); - rawGridPoints[ i ].styles[ 0 ] = LS_NORMAL; - bspGridPoints[ i ].styles[ 0 ] = LS_NORMAL; - for( j = 1; j < MAX_LIGHTMAPS; j++ ) - { - rawGridPoints[ i ].styles[ j ] = LS_NONE; - bspGridPoints[ i ].styles[ j ] = LS_NONE; - } - } - - /* note it */ - Sys_Printf( "%9d grid points\n", numRawGridPoints ); -} - - - -/* -LightWorld() -does what it says... -*/ - -void LightWorld( void ) -{ - vec3_t color; - float f; - int b, bt; - qboolean minVertex, minGrid; - const char *value; - - - /* ydnar: smooth normals */ - if( shade ) - { - Sys_Printf( "--- SmoothNormals ---\n" ); - SmoothNormals(); - } - - /* determine the number of grid points */ - Sys_Printf( "--- SetupGrid ---\n" ); - SetupGrid(); - - /* find the optional minimum lighting values */ - GetVectorForKey( &entities[ 0 ], "_color", color ); - if( VectorLength( color ) == 0.0f ) - VectorSet( color, 1.0, 1.0, 1.0 ); - - /* ambient */ - f = FloatForKey( &entities[ 0 ], "_ambient" ); - if( f == 0.0f ) - f = FloatForKey( &entities[ 0 ], "ambient" ); - VectorScale( color, f, ambientColor ); - - /* minvertexlight */ - minVertex = qfalse; - value = ValueForKey( &entities[ 0 ], "_minvertexlight" ); - if( value[ 0 ] != '\0' ) - { - minVertex = qtrue; - f = atof( value ); - VectorScale( color, f, minVertexLight ); - } - - /* mingridlight */ - minGrid = qfalse; - value = ValueForKey( &entities[ 0 ], "_mingridlight" ); - if( value[ 0 ] != '\0' ) - { - minGrid = qtrue; - f = atof( value ); - VectorScale( color, f, minGridLight ); - } - - /* minlight */ - value = ValueForKey( &entities[ 0 ], "_minlight" ); - if( value[ 0 ] != '\0' ) - { - f = atof( value ); - VectorScale( color, f, minLight ); - if( minVertex == qfalse ) - VectorScale( color, f, minVertexLight ); - if( minGrid == qfalse ) - VectorScale( color, f, minGridLight ); - } - - /* create world lights */ - Sys_FPrintf( SYS_VRB, "--- CreateLights ---\n" ); - CreateEntityLights(); - CreateSurfaceLights(); - Sys_Printf( "%9d point lights\n", numPointLights ); - Sys_Printf( "%9d spotlights\n", numSpotLights ); - Sys_Printf( "%9d diffuse (area) lights\n", numDiffuseLights ); - Sys_Printf( "%9d sun/sky lights\n", numSunLights ); - - /* calculate lightgrid */ - if( !noGridLighting ) - { - /* ydnar: set up light envelopes */ - SetupEnvelopes( qtrue, fastgrid ); - - Sys_Printf( "--- TraceGrid ---\n" ); - inGrid = qtrue; - RunThreadsOnIndividual( numRawGridPoints, qtrue, TraceGrid ); - inGrid = qfalse; - Sys_Printf( "%d x %d x %d = %d grid\n", - gridBounds[ 0 ], gridBounds[ 1 ], gridBounds[ 2 ], numBSPGridPoints ); - - /* ydnar: emit statistics on light culling */ - Sys_FPrintf( SYS_VRB, "%9d grid points envelope culled\n", gridEnvelopeCulled ); - Sys_FPrintf( SYS_VRB, "%9d grid points bounds culled\n", gridBoundsCulled ); - } - - /* slight optimization to remove a sqrt */ - subdivideThreshold *= subdivideThreshold; - - /* map the world luxels */ - Sys_Printf( "--- MapRawLightmap ---\n" ); - RunThreadsOnIndividual( numRawLightmaps, qtrue, MapRawLightmap ); - Sys_Printf( "%9d luxels\n", numLuxels ); - Sys_Printf( "%9d luxels mapped\n", numLuxelsMapped ); - Sys_Printf( "%9d luxels occluded\n", numLuxelsOccluded ); - - /* dirty them up */ - if( dirty ) - { - Sys_Printf( "--- DirtyRawLightmap ---\n" ); - RunThreadsOnIndividual( numRawLightmaps, qtrue, DirtyRawLightmap ); - } - - /* floodlight pass */ - FloodlightRawLightmaps(); - - /* ydnar: set up light envelopes */ - SetupEnvelopes( qfalse, fast ); - - /* light up my world */ - lightsPlaneCulled = 0; - lightsEnvelopeCulled = 0; - lightsBoundsCulled = 0; - lightsClusterCulled = 0; - - Sys_Printf( "--- IlluminateRawLightmap ---\n" ); - RunThreadsOnIndividual( numRawLightmaps, qtrue, IlluminateRawLightmap ); - Sys_Printf( "%9d luxels illuminated\n", numLuxelsIlluminated ); - - StitchSurfaceLightmaps(); - - Sys_Printf( "--- IlluminateVertexes ---\n" ); - RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, IlluminateVertexes ); - Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated ); - - /* ydnar: emit statistics on light culling */ - Sys_FPrintf( SYS_VRB, "%9d lights plane culled\n", lightsPlaneCulled ); - Sys_FPrintf( SYS_VRB, "%9d lights envelope culled\n", lightsEnvelopeCulled ); - Sys_FPrintf( SYS_VRB, "%9d lights bounds culled\n", lightsBoundsCulled ); - Sys_FPrintf( SYS_VRB, "%9d lights cluster culled\n", lightsClusterCulled ); - - /* radiosity */ - b = 1; - bt = bounce; - while( bounce > 0 ) - { - /* store off the bsp between bounces */ - StoreSurfaceLightmaps(); - UnparseEntities(); - Sys_Printf( "Writing %s\n", source ); - WriteBSPFile( source ); - - /* note it */ - Sys_Printf( "\n--- Radiosity (bounce %d of %d) ---\n", b, bt ); - - /* flag bouncing */ - bouncing = qtrue; - VectorClear( ambientColor ); - floodlighty = qfalse; - - /* generate diffuse lights */ - RadFreeLights(); - RadCreateDiffuseLights(); - - /* setup light envelopes */ - SetupEnvelopes( qfalse, fastbounce ); - if( numLights == 0 ) - { - Sys_Printf( "No diffuse light to calculate, ending radiosity.\n" ); - break; - } - - /* add to lightgrid */ - if( bouncegrid ) - { - gridEnvelopeCulled = 0; - gridBoundsCulled = 0; - - Sys_Printf( "--- BounceGrid ---\n" ); - inGrid = qtrue; - RunThreadsOnIndividual( numRawGridPoints, qtrue, TraceGrid ); - inGrid = qfalse; - Sys_FPrintf( SYS_VRB, "%9d grid points envelope culled\n", gridEnvelopeCulled ); - Sys_FPrintf( SYS_VRB, "%9d grid points bounds culled\n", gridBoundsCulled ); - } - - /* light up my world */ - lightsPlaneCulled = 0; - lightsEnvelopeCulled = 0; - lightsBoundsCulled = 0; - lightsClusterCulled = 0; - - Sys_Printf( "--- IlluminateRawLightmap ---\n" ); - RunThreadsOnIndividual( numRawLightmaps, qtrue, IlluminateRawLightmap ); - Sys_Printf( "%9d luxels illuminated\n", numLuxelsIlluminated ); - Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated ); - - StitchSurfaceLightmaps(); - - Sys_Printf( "--- IlluminateVertexes ---\n" ); - RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, IlluminateVertexes ); - Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated ); - - /* ydnar: emit statistics on light culling */ - Sys_FPrintf( SYS_VRB, "%9d lights plane culled\n", lightsPlaneCulled ); - Sys_FPrintf( SYS_VRB, "%9d lights envelope culled\n", lightsEnvelopeCulled ); - Sys_FPrintf( SYS_VRB, "%9d lights bounds culled\n", lightsBoundsCulled ); - Sys_FPrintf( SYS_VRB, "%9d lights cluster culled\n", lightsClusterCulled ); - - /* interate */ - bounce--; - b++; - } -} - - - -/* -LightMain() -main routine for light processing -*/ - -int LightMain( int argc, char **argv ) -{ - int i; - float f; - char mapSource[ 1024 ]; - const char *value; - int lightmapMergeSize = 0; - qboolean lightSamplesInsist = qfalse; - - - /* note it */ - Sys_Printf( "--- Light ---\n" ); - Sys_Printf( "--- ProcessGameSpecific ---\n" ); - - /* set standard game flags */ - wolfLight = game->wolfLight; - if (wolfLight == qtrue) - Sys_Printf( " lightning model: wolf\n" ); - else - Sys_Printf( " lightning model: quake3\n" ); - - lmCustomSize = game->lightmapSize; - Sys_Printf( " lightmap size: %d x %d pixels\n", lmCustomSize, lmCustomSize ); - - lightmapGamma = game->lightmapGamma; - Sys_Printf( " lightning gamma: %f\n", lightmapGamma ); - - lightmapCompensate = game->lightmapCompensate; - Sys_Printf( " lightning compensation: %f\n", lightmapCompensate ); - - lightmapExposure = game->lightmapExposure; - Sys_Printf( " lightning exposure: %f\n", lightmapExposure ); - - gridScale = game->gridScale; - Sys_Printf( " lightgrid scale: %f\n", gridScale ); - - gridAmbientScale = game->gridAmbientScale; - Sys_Printf( " lightgrid ambient scale: %f\n", gridAmbientScale ); - - lightAngleHL = game->lightAngleHL; - if( lightAngleHL ) - Sys_Printf( " half lambert light angle attenuation enabled \n" ); - - noStyles = game->noStyles; - if (noStyles == qtrue) - Sys_Printf( " shader lightstyles hack: disabled\n" ); - else - Sys_Printf( " shader lightstyles hack: enabled\n" ); - - keepLights = game->keepLights; - if (keepLights == qtrue) - Sys_Printf( " keep lights: enabled\n" ); - else - Sys_Printf( " keep lights: disabled\n" ); - - patchShadows = game->patchShadows; - if (patchShadows == qtrue) - Sys_Printf( " patch shadows: enabled\n" ); - else - Sys_Printf( " patch shadows: disabled\n" ); - - deluxemap = game->deluxeMap; - deluxemode = game->deluxeMode; - if (deluxemap == qtrue) - { - if (deluxemode) - Sys_Printf( " deluxemapping: enabled with tangentspace deluxemaps\n" ); - else - Sys_Printf( " deluxemapping: enabled with modelspace deluxemaps\n" ); - } - else - Sys_Printf( " deluxemapping: disabled\n" ); - - Sys_Printf( "--- ProcessCommandLine ---\n" ); - - /* process commandline arguments */ - for( i = 1; i < (argc - 1); i++ ) - { - /* lightsource scaling */ - if( !strcmp( argv[ i ], "-point" ) || !strcmp( argv[ i ], "-pointscale" ) ) - { - f = atof( argv[ i + 1 ] ); - pointScale *= f; - Sys_Printf( "Point (entity) light scaled by %f to %f\n", f, pointScale ); - i++; - } - - else if( !strcmp( argv[ i ], "-area" ) || !strcmp( argv[ i ], "-areascale" ) ) - { - f = atof( argv[ i + 1 ] ); - areaScale *= f; - Sys_Printf( "Area (shader) light scaled by %f to %f\n", f, areaScale ); - i++; - } - - else if( !strcmp( argv[ i ], "-sky" ) || !strcmp( argv[ i ], "-skyscale" ) ) - { - f = atof( argv[ i + 1 ] ); - skyScale *= f; - Sys_Printf( "Sky/sun light scaled by %f to %f\n", f, skyScale ); - i++; - } - - else if( !strcmp( argv[ i ], "-bouncescale" ) ) - { - f = atof( argv[ i + 1 ] ); - bounceScale *= f; - Sys_Printf( "Bounce (radiosity) light scaled by %f to %f\n", f, bounceScale ); - i++; - } - - else if( !strcmp( argv[ i ], "-scale" ) ) - { - f = atof( argv[ i + 1 ] ); - pointScale *= f; - areaScale *= f; - skyScale *= f; - bounceScale *= f; - Sys_Printf( "All light scaled by %f\n", f ); - i++; - } - - else if( !strcmp( argv[ i ], "-gridscale" ) ) - { - f = atof( argv[ i + 1 ] ); - Sys_Printf( "Grid lightning scaled by %f\n", f ); - gridScale *= f; - i++; - } - - else if( !strcmp( argv[ i ], "-gridambientscale" ) ) - { - f = atof( argv[ i + 1 ] ); - Sys_Printf( "Grid ambient lightning scaled by %f\n", f ); - gridAmbientScale *= f; - i++; - } - - else if( !strcmp( argv[ i ], "-griddirectionality" ) ) - { - f = atof( argv[ i + 1 ] ); - if(f > 1) f = 1; - if(f < gridAmbientDirectionality) gridAmbientDirectionality = f; - Sys_Printf( "Grid directionality is %f\n", f ); - gridDirectionality = f; - i++; - } - - else if( !strcmp( argv[ i ], "-gridambientdirectionality" ) ) - { - f = atof( argv[ i + 1 ] ); - if(f < -1) f = -1; - if(f > gridDirectionality) gridDirectionality = f; - Sys_Printf( "Grid ambient directionality is %f\n", f ); - gridAmbientDirectionality = f; - i++; - } - - else if( !strcmp( argv[ i ], "-gamma" ) ) - { - f = atof( argv[ i + 1 ] ); - lightmapGamma = f; - Sys_Printf( "Lighting gamma set to %f\n", lightmapGamma ); - i++; - } - - else if( !strcmp( argv[ i ], "-exposure" ) ) - { - f = atof( argv[ i + 1 ] ); - lightmapExposure = f; - Sys_Printf( "Lighting exposure set to %f\n", lightmapExposure ); - i++; - } - - else if( !strcmp( argv[ i ], "-compensate" ) ) - { - f = atof( argv[ i + 1 ] ); - if( f <= 0.0f ) - f = 1.0f; - lightmapCompensate = f; - Sys_Printf( "Lighting compensation set to 1/%f\n", lightmapCompensate ); - i++; - } - - /* ydnar switches */ - else if( !strcmp( argv[ i ], "-bounce" ) ) - { - bounce = atoi( argv[ i + 1 ] ); - if( bounce < 0 ) - bounce = 0; - else if( bounce > 0 ) - Sys_Printf( "Radiosity enabled with %d bounce(s)\n", bounce ); - i++; - } - - else if( !strcmp( argv[ i ], "-supersample" ) || !strcmp( argv[ i ], "-super" ) ) - { - superSample = atoi( argv[ i + 1 ] ); - if( superSample < 1 ) - superSample = 1; - else if( superSample > 1 ) - Sys_Printf( "Ordered-grid supersampling enabled with %d sample(s) per lightmap texel\n", (superSample * superSample) ); - i++; - } - - else if( !strcmp( argv[ i ], "-randomsamples" ) ) - { - lightRandomSamples = qtrue; - Sys_Printf( "Random sampling enabled\n", lightRandomSamples ); - } - - else if( !strcmp( argv[ i ], "-samples" ) ) - { - if(*argv[i+1] == '+') - lightSamplesInsist = qtrue; - else - lightSamplesInsist = qfalse; - lightSamples = atoi( argv[ i + 1 ] ); - if( lightSamples < 1 ) - lightSamples = 1; - else if( lightSamples > 1 ) - Sys_Printf( "Adaptive supersampling enabled with %d sample(s) per lightmap texel\n", lightSamples ); - i++; - } - - else if( !strcmp( argv[ i ], "-samplessearchboxsize" ) ) - { - lightSamplesSearchBoxSize = atoi( argv[ i + 1 ] ); - if( lightSamplesSearchBoxSize <= 0 ) - lightSamplesSearchBoxSize = 1; - if( lightSamplesSearchBoxSize > 4 ) - lightSamplesSearchBoxSize = 4; /* more makes no sense */ - else if( lightSamplesSearchBoxSize != 1 ) - Sys_Printf( "Adaptive supersampling uses %f times the normal search box size\n", lightSamplesSearchBoxSize ); - i++; - } - - else if( !strcmp( argv[ i ], "-filter" ) ) - { - filter = qtrue; - Sys_Printf( "Lightmap filtering enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-dark" ) ) - { - dark = qtrue; - Sys_Printf( "Dark lightmap seams enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-shadeangle" ) ) - { - shadeAngleDegrees = atof( argv[ i + 1 ] ); - if( shadeAngleDegrees < 0.0f ) - shadeAngleDegrees = 0.0f; - else if( shadeAngleDegrees > 0.0f ) - { - shade = qtrue; - Sys_Printf( "Phong shading enabled with a breaking angle of %f degrees\n", shadeAngleDegrees ); - } - i++; - } - - else if( !strcmp( argv[ i ], "-thresh" ) ) - { - subdivideThreshold = atof( argv[ i + 1 ] ); - if( subdivideThreshold < 0 ) - subdivideThreshold = DEFAULT_SUBDIVIDE_THRESHOLD; - else - Sys_Printf( "Subdivision threshold set at %.3f\n", subdivideThreshold ); - i++; - } - - else if( !strcmp( argv[ i ], "-approx" ) ) - { - approximateTolerance = atoi( argv[ i + 1 ] ); - if( approximateTolerance < 0 ) - approximateTolerance = 0; - else if( approximateTolerance > 0 ) - Sys_Printf( "Approximating lightmaps within a byte tolerance of %d\n", approximateTolerance ); - i++; - } - else if( !strcmp( argv[ i ], "-deluxe" ) || !strcmp( argv[ i ], "-deluxemap" ) ) - { - deluxemap = qtrue; - Sys_Printf( "Generating deluxemaps for average light direction\n" ); - } - else if( !strcmp( argv[ i ], "-deluxemode" )) - { - deluxemode = atoi( argv[ i + 1 ] ); - if (deluxemode == 0 || deluxemode > 1 || deluxemode < 0) - { - Sys_Printf( "Generating modelspace deluxemaps\n" ); - deluxemode = 0; - } - else - Sys_Printf( "Generating tangentspace deluxemaps\n" ); - i++; - } - else if( !strcmp( argv[ i ], "-nodeluxe" ) || !strcmp( argv[ i ], "-nodeluxemap" ) ) - { - deluxemap = qfalse; - Sys_Printf( "Disabling generating of deluxemaps for average light direction\n" ); - } - else if( !strcmp( argv[ i ], "-external" ) ) - { - externalLightmaps = qtrue; - Sys_Printf( "Storing all lightmaps externally\n" ); - } - - else if( !strcmp( argv[ i ], "-lightmapsize" ) ) - { - lmCustomSize = atoi( argv[ i + 1 ] ); - - /* must be a power of 2 and greater than 2 */ - if( ((lmCustomSize - 1) & lmCustomSize) || lmCustomSize < 2 ) - { - Sys_Printf( "WARNING: Lightmap size must be a power of 2, greater or equal to 2 pixels.\n" ); - lmCustomSize = game->lightmapSize; - } - i++; - Sys_Printf( "Default lightmap size set to %d x %d pixels\n", lmCustomSize, lmCustomSize ); - - /* enable external lightmaps */ - if( lmCustomSize != game->lightmapSize ) - { - externalLightmaps = qtrue; - Sys_Printf( "Storing all lightmaps externally\n" ); - } - } - - else if( !strcmp( argv[ i ], "-rawlightmapsizelimit" ) ) - { - lmLimitSize = atoi( argv[ i + 1 ] ); - - i++; - Sys_Printf( "Raw lightmap size limit set to %d x %d pixels\n", lmLimitSize, lmLimitSize ); - } - - else if( !strcmp( argv[ i ], "-lightmapdir" ) ) - { - lmCustomDir = argv[i + 1]; - i++; - Sys_Printf( "Lightmap directory set to %s\n", lmCustomDir ); - externalLightmaps = qtrue; - Sys_Printf( "Storing all lightmaps externally\n" ); - } - - /* ydnar: add this to suppress warnings */ - else if( !strcmp( argv[ i ], "-custinfoparms") ) - { - Sys_Printf( "Custom info parms enabled\n" ); - useCustomInfoParms = qtrue; - } - - else if( !strcmp( argv[ i ], "-wolf" ) ) - { - /* -game should already be set */ - wolfLight = qtrue; - Sys_Printf( "Enabling Wolf lighting model (linear default)\n" ); - } - - else if( !strcmp( argv[ i ], "-q3" ) ) - { - /* -game should already be set */ - wolfLight = qfalse; - Sys_Printf( "Enabling Quake 3 lighting model (nonlinear default)\n" ); - } - - else if( !strcmp( argv[ i ], "-extradist" ) ) - { - extraDist = atof( argv[ i + 1 ] ); - if( extraDist < 0 ) - extraDist = 0; - i++; - Sys_Printf( "Default extra radius set to %f units\n", extraDist ); - } - - else if( !strcmp( argv[ i ], "-sunonly" ) ) - { - sunOnly = qtrue; - Sys_Printf( "Only computing sunlight\n" ); - } - - else if( !strcmp( argv[ i ], "-bounceonly" ) ) - { - bounceOnly = qtrue; - Sys_Printf( "Storing bounced light (radiosity) only\n" ); - } - - else if( !strcmp( argv[ i ], "-nocollapse" ) ) - { - noCollapse = qtrue; - Sys_Printf( "Identical lightmap collapsing disabled\n" ); - } - - else if( !strcmp( argv[ i ], "-nolightmapsearch" ) ) - { - lightmapSearchBlockSize = 1; - Sys_Printf( "No lightmap searching - all lightmaps will be sequential\n" ); - } - - else if( !strcmp( argv[ i ], "-lightmapsearchpower" ) ) - { - lightmapMergeSize = (game->lightmapSize << atoi(argv[i+1])); - ++i; - Sys_Printf( "Restricted lightmap searching enabled - optimize for lightmap merge power %d (size %d)\n", atoi(argv[i]), lightmapMergeSize ); - } - - else if( !strcmp( argv[ i ], "-lightmapsearchblocksize" ) ) - { - lightmapSearchBlockSize = atoi(argv[i+1]); - ++i; - Sys_Printf( "Restricted lightmap searching enabled - block size set to %d\n", lightmapSearchBlockSize ); - } - - else if( !strcmp( argv[ i ], "-shade" ) ) - { - shade = qtrue; - Sys_Printf( "Phong shading enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-bouncegrid") ) - { - bouncegrid = qtrue; - if( bounce > 0 ) - Sys_Printf( "Grid lighting with radiosity enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-smooth" ) ) - { - lightSamples = EXTRA_SCALE; - Sys_Printf( "The -smooth argument is deprecated, use \"-samples 2\" instead\n" ); - } - - else if( !strcmp( argv[ i ], "-fast" ) ) - { - fast = qtrue; - fastgrid = qtrue; - fastbounce = qtrue; - Sys_Printf( "Fast mode enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-faster" ) ) - { - faster = qtrue; - fast = qtrue; - fastgrid = qtrue; - fastbounce = qtrue; - Sys_Printf( "Faster mode enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-fastgrid" ) ) - { - fastgrid = qtrue; - Sys_Printf( "Fast grid lighting enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-fastbounce" ) ) - { - fastbounce = qtrue; - Sys_Printf( "Fast bounce mode enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-cheap" ) ) - { - cheap = qtrue; - cheapgrid = qtrue; - Sys_Printf( "Cheap mode enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-cheapgrid" ) ) - { - cheapgrid = qtrue; - Sys_Printf( "Cheap grid mode enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-normalmap" ) ) - { - normalmap = qtrue; - Sys_Printf( "Storing normal map instead of lightmap\n" ); - } - - else if( !strcmp( argv[ i ], "-trisoup" ) ) - { - trisoup = qtrue; - Sys_Printf( "Converting brush faces to triangle soup\n" ); - } - - else if( !strcmp( argv[ i ], "-debug" ) ) - { - debug = qtrue; - Sys_Printf( "Lightmap debugging enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-debugsurfaces" ) || !strcmp( argv[ i ], "-debugsurface" ) ) - { - debugSurfaces = qtrue; - Sys_Printf( "Lightmap surface debugging enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-debugunused" ) ) - { - debugUnused = qtrue; - Sys_Printf( "Unused luxel debugging enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-debugaxis" ) ) - { - debugAxis = qtrue; - Sys_Printf( "Lightmap axis debugging enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-debugcluster" ) ) - { - debugCluster = qtrue; - Sys_Printf( "Luxel cluster debugging enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-debugorigin" ) ) - { - debugOrigin = qtrue; - Sys_Printf( "Luxel origin debugging enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-debugdeluxe" ) ) - { - deluxemap = qtrue; - debugDeluxemap = qtrue; - Sys_Printf( "Deluxemap debugging enabled\n" ); - } - - else if( !strcmp( argv[ i ], "-export" ) ) - { - exportLightmaps = qtrue; - Sys_Printf( "Exporting lightmaps\n" ); - } - - else if( !strcmp(argv[ i ], "-notrace" )) - { - noTrace = qtrue; - Sys_Printf( "Shadow occlusion disabled\n" ); - } - else if( !strcmp(argv[ i ], "-patchshadows" ) ) - { - patchShadows = qtrue; - Sys_Printf( "Patch shadow casting enabled\n" ); - } - else if( !strcmp( argv[ i ], "-extra" ) ) - { - superSample = EXTRA_SCALE; /* ydnar */ - Sys_Printf( "The -extra argument is deprecated, use \"-super 2\" instead\n" ); - } - else if( !strcmp( argv[ i ], "-extrawide" ) ) - { - superSample = EXTRAWIDE_SCALE; /* ydnar */ - filter = qtrue; /* ydnar */ - Sys_Printf( "The -extrawide argument is deprecated, use \"-filter [-super 2]\" instead\n"); - } - else if( !strcmp( argv[ i ], "-samplesize" ) ) - { - sampleSize = atoi( argv[ i + 1 ] ); - if( sampleSize < 1 ) - sampleSize = 1; - i++; - Sys_Printf( "Default lightmap sample size set to %dx%d units\n", sampleSize, sampleSize ); - } - else if( !strcmp( argv[ i ], "-minsamplesize" ) ) - { - minSampleSize = atoi( argv[ i + 1 ] ); - if( minSampleSize < 1 ) - minSampleSize = 1; - i++; - Sys_Printf( "Minimum lightmap sample size set to %dx%d units\n", minSampleSize, minSampleSize ); - } - else if( !strcmp( argv[ i ], "-samplescale" ) ) - { - sampleScale = atoi( argv[ i + 1 ] ); - i++; - Sys_Printf( "Lightmaps sample scale set to %d\n", sampleScale); - } - else if( !strcmp( argv[ i ], "-novertex" ) ) - { - noVertexLighting = qtrue; - Sys_Printf( "Disabling vertex lighting\n" ); - } - else if( !strcmp( argv[ i ], "-nogrid" ) ) - { - noGridLighting = qtrue; - Sys_Printf( "Disabling grid lighting\n" ); - } - else if( !strcmp( argv[ i ], "-border" ) ) - { - lightmapBorder = qtrue; - Sys_Printf( "Adding debug border to lightmaps\n" ); - } - else if( !strcmp( argv[ i ], "-nosurf" ) ) - { - noSurfaces = qtrue; - Sys_Printf( "Not tracing against surfaces\n" ); - } - else if( !strcmp( argv[ i ], "-dump" ) ) - { - dump = qtrue; - Sys_Printf( "Dumping radiosity lights into numbered prefabs\n" ); - } - else if( !strcmp( argv[ i ], "-lomem" ) ) - { - loMem = qtrue; - Sys_Printf( "Enabling low-memory (potentially slower) lighting mode\n" ); - } - else if( !strcmp( argv[ i ], "-lightanglehl" ) ) - { - if( ( atoi( argv[ i + 1 ] ) != 0 ) != lightAngleHL ) - { - lightAngleHL = ( atoi( argv[ i + 1 ] ) != 0 ); - if( lightAngleHL ) - Sys_Printf( "Enabling half lambert light angle attenuation\n" ); - else - Sys_Printf( "Disabling half lambert light angle attenuation\n" ); - } - } - else if( !strcmp( argv[ i ], "-nostyle" ) || !strcmp( argv[ i ], "-nostyles" ) ) - { - noStyles = qtrue; - Sys_Printf( "Disabling lightstyles\n" ); - } - else if( !strcmp( argv[ i ], "-style" ) || !strcmp( argv[ i ], "-styles" ) ) - { - noStyles = qfalse; - Sys_Printf( "Enabling lightstyles\n" ); - } - else if( !strcmp( argv[ i ], "-keeplights" )) - { - keepLights = qtrue; - Sys_Printf( "Leaving light entities on map after compile\n" ); - } - else if( !strcmp( argv[ i ], "-cpma" ) ) - { - cpmaHack = qtrue; - Sys_Printf( "Enabling Challenge Pro Mode Asstacular Vertex Lighting Mode (tm)\n" ); - } - else if( !strcmp( argv[ i ], "-floodlight" ) ) - { - floodlighty = qtrue; - Sys_Printf( "FloodLighting enabled\n" ); - } - else if( !strcmp( argv[ i ], "-debugnormals" ) ) - { - debugnormals = qtrue; - Sys_Printf( "DebugNormals enabled\n" ); - } - else if( !strcmp( argv[ i ], "-lowquality" ) ) - { - floodlight_lowquality = qtrue; - Sys_Printf( "Low Quality FloodLighting enabled\n" ); - } - - /* r7: dirtmapping */ - else if( !strcmp( argv[ i ], "-dirty" ) ) - { - dirty = qtrue; - Sys_Printf( "Dirtmapping enabled\n" ); - } - else if( !strcmp( argv[ i ], "-dirtdebug" ) || !strcmp( argv[ i ], "-debugdirt" ) ) - { - dirtDebug = qtrue; - Sys_Printf( "Dirtmap debugging enabled\n" ); - } - else if( !strcmp( argv[ i ], "-dirtmode" ) ) - { - dirtMode = atoi( argv[ i + 1 ] ); - if( dirtMode != 0 && dirtMode != 1 ) - dirtMode = 0; - if( dirtMode == 1 ) - Sys_Printf( "Enabling randomized dirtmapping\n" ); - else - Sys_Printf( "Enabling ordered dir mapping\n" ); - i++; - } - else if( !strcmp( argv[ i ], "-dirtdepth" ) ) - { - dirtDepth = atof( argv[ i + 1 ] ); - if( dirtDepth <= 0.0f ) - dirtDepth = 128.0f; - Sys_Printf( "Dirtmapping depth set to %.1f\n", dirtDepth ); - i++; - } - else if( !strcmp( argv[ i ], "-dirtscale" ) ) - { - dirtScale = atof( argv[ i + 1 ] ); - if( dirtScale <= 0.0f ) - dirtScale = 1.0f; - Sys_Printf( "Dirtmapping scale set to %.1f\n", dirtScale ); - i++; - } - else if( !strcmp( argv[ i ], "-dirtgain" ) ) - { - dirtGain = atof( argv[ i + 1 ] ); - if( dirtGain <= 0.0f ) - dirtGain = 1.0f; - Sys_Printf( "Dirtmapping gain set to %.1f\n", dirtGain ); - i++; - } - else if( !strcmp( argv[ i ], "-trianglecheck" ) ) - { - lightmapTriangleCheck = qtrue; - } - else if( !strcmp( argv[ i ], "-extravisnudge" ) ) - { - lightmapExtraVisClusterNudge = qtrue; - } - else if( !strcmp( argv[ i ], "-fill" ) ) - { - lightmapFill = qtrue; - Sys_Printf( "Filling lightmap colors from surrounding pixels to improve JPEG compression\n" ); - } - /* unhandled args */ - else - { - Sys_Printf( "WARNING: Unknown argument \"%s\"\n", argv[ i ] ); - } - - } - - /* fix up samples count */ - if(lightRandomSamples) - { - if(!lightSamplesInsist) - { - /* approximately match -samples in quality */ - switch(lightSamples) - { - /* somewhat okay */ - case 1: - case 2: - lightSamples = 16; - Sys_Printf( "Adaptive supersampling preset enabled with %d random sample(s) per lightmap texel\n", lightSamples ); - break; - - /* good */ - case 3: - lightSamples = 64; - Sys_Printf( "Adaptive supersampling preset enabled with %d random sample(s) per lightmap texel\n", lightSamples ); - break; - - /* perfect */ - case 4: - lightSamples = 256; - Sys_Printf( "Adaptive supersampling preset enabled with %d random sample(s) per lightmap texel\n", lightSamples ); - break; - - default: break; - } - } - } - - /* fix up lightmap search power */ - if(lightmapMergeSize) - { - lightmapSearchBlockSize = (lightmapMergeSize / lmCustomSize) * (lightmapMergeSize / lmCustomSize); - if(lightmapSearchBlockSize < 1) - lightmapSearchBlockSize = 1; - - Sys_Printf( "Restricted lightmap searching enabled - block size adjusted to %d\n", lightmapSearchBlockSize ); - } - - /* clean up map name */ - strcpy( source, ExpandArg( argv[ i ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - strcpy( mapSource, ExpandArg( argv[ i ] ) ); - StripExtension( mapSource ); - DefaultExtension( mapSource, ".map" ); - - /* ydnar: set default sample size */ - SetDefaultSampleSize( sampleSize ); - - /* ydnar: handle shaders */ - BeginMapShaderFile( source ); - LoadShaderInfo(); - - /* note loading */ - Sys_Printf( "Loading %s\n", source ); - - /* ydnar: load surface file */ - LoadSurfaceExtraFile( source ); - - /* load bsp file */ - LoadBSPFile( source ); - - /* parse bsp entities */ - ParseEntities(); - - /* inject command line parameters */ - InjectCommandLine(argv, 0, argc - 1); - - /* load map file */ - value = ValueForKey( &entities[ 0 ], "_keepLights" ); - if( value[ 0 ] != '1' ) - LoadMapFile( mapSource, qtrue, qfalse ); - - /* set the entity/model origins and init yDrawVerts */ - SetEntityOrigins(); - - /* ydnar: set up optimization */ - SetupBrushes(); - SetupDirt(); - SetupFloodLight(); - SetupSurfaceLightmaps(); - - /* initialize the surface facet tracing */ - SetupTraceNodes(); - - /* light the world */ - LightWorld(); - - /* ydnar: store off lightmaps */ - StoreSurfaceLightmaps(); - - /* write out the bsp */ - UnparseEntities(); - Sys_Printf( "Writing %s\n", source ); - WriteBSPFile( source ); - - /* ydnar: export lightmaps */ - if( exportLightmaps && !externalLightmaps ) - ExportLightmaps(); - - /* return to sender */ - return 0; -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_bounce.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_bounce.c deleted file mode 100644 index 7db00613..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_bounce.c +++ /dev/null @@ -1,959 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define LIGHT_BOUNCE_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* functions */ - -/* -RadFreeLights() -deletes any existing lights, freeing up memory for the next bounce -*/ - -void RadFreeLights( void ) -{ - light_t *light, *next; - - - /* delete lights */ - for( light = lights; light; light = next ) - { - next = light->next; - if( light->w != NULL ) - FreeWinding( light->w ); - free( light ); - } - numLights = 0; - lights = NULL; -} - - - -/* -RadClipWindingEpsilon() -clips a rad winding by a plane -based off the regular clip winding code -*/ - -static void RadClipWindingEpsilon( radWinding_t *in, vec3_t normal, vec_t dist, - vec_t epsilon, radWinding_t *front, radWinding_t *back, clipWork_t *cw ) -{ - vec_t *dists; - int *sides; - int counts[ 3 ]; - vec_t dot; /* ydnar: changed from static b/c of threading */ /* VC 4.2 optimizer bug if not static? */ - int i, j, k; - radVert_t *v1, *v2, mid; - int maxPoints; - - - /* crutch */ - dists = cw->dists; - sides = cw->sides; - - /* clear counts */ - counts[ 0 ] = counts[ 1 ] = counts[ 2 ] = 0; - - /* determine sides for each point */ - for( i = 0; i < in->numVerts; i++ ) - { - dot = DotProduct( in->verts[ i ].xyz, 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 ]; - - /* clear front and back */ - front->numVerts = back->numVerts = 0; - - /* handle all on one side cases */ - if( counts[ 0 ] == 0 ) - { - memcpy( back, in, sizeof( radWinding_t ) ); - return; - } - if( counts[ 1 ] == 0 ) - { - memcpy( front, in, sizeof( radWinding_t ) ); - return; - } - - /* setup windings */ - maxPoints = in->numVerts + 4; - - /* do individual verts */ - for( i = 0; i < in->numVerts; i++ ) - { - /* do simple vertex copies first */ - v1 = &in->verts[ i ]; - - if( sides[ i ] == SIDE_ON ) - { - memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) ); - memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) ); - continue; - } - - if( sides[ i ] == SIDE_FRONT ) - memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) ); - - if( sides[ i ] == SIDE_BACK ) - memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) ); - - if( sides[ i + 1 ] == SIDE_ON || sides[ i + 1 ] == sides[ i ] ) - continue; - - /* generate a split vertex */ - v2 = &in->verts[ (i + 1) % in->numVerts ]; - - dot = dists[ i ] / (dists[ i ] - dists[ i + 1 ]); - - /* average vertex values */ - for( j = 0; j < 4; j++ ) - { - /* color */ - if( j < 4 ) - { - for( k = 0; k < MAX_LIGHTMAPS; k++ ) - mid.color[ k ][ j ] = v1->color[ k ][ j ] + dot * (v2->color[ k ][ j ] - v1->color[ k ][ j ]); - } - - /* xyz, normal */ - if( j < 3 ) - { - mid.xyz[ j ] = v1->xyz[ j ] + dot * (v2->xyz[ j ] - v1->xyz[ j ]); - mid.normal[ j ] = v1->normal[ j ] + dot * (v2->normal[ j ] - v1->normal[ j ]); - } - - /* st, lightmap */ - if( j < 2 ) - { - mid.st[ j ] = v1->st[ j ] + dot * (v2->st[ j ] - v1->st[ j ]); - for( k = 0; k < MAX_LIGHTMAPS; k++ ) - mid.lightmap[ k ][ j ] = v1->lightmap[ k ][ j ] + dot * (v2->lightmap[ k ][ j ] - v1->lightmap[ k ][ j ]); - } - } - - /* normalize the averaged normal */ - VectorNormalize( mid.normal, mid.normal ); - - /* copy the midpoint to both windings */ - memcpy( &front->verts[ front->numVerts++ ], &mid, sizeof( radVert_t ) ); - memcpy( &back->verts[ back->numVerts++ ], &mid, sizeof( radVert_t ) ); - } - - /* error check */ - if( front->numVerts > maxPoints || front->numVerts > maxPoints ) - Error( "RadClipWindingEpsilon: points exceeded estimate" ); - if( front->numVerts > MAX_POINTS_ON_WINDING || front->numVerts > MAX_POINTS_ON_WINDING ) - Error( "RadClipWindingEpsilon: MAX_POINTS_ON_WINDING" ); -} - - - - - -/* -RadSampleImage() -samples a texture image for a given color -returns qfalse if pixels are bad -*/ - -qboolean RadSampleImage( byte *pixels, int width, int height, float st[ 2 ], float color[ 4 ] ) -{ - float sto[ 2 ]; - int x, y; - - - /* clear color first */ - color[ 0 ] = color[ 1 ] = color[ 2 ] = color[ 3 ] = 255; - - /* dummy check */ - if( pixels == NULL || width < 1 || height < 1 ) - return qfalse; - - /* bias st */ - sto[ 0 ] = st[ 0 ]; - while( sto[ 0 ] < 0.0f ) - sto[ 0 ] += 1.0f; - sto[ 1 ] = st[ 1 ]; - while( sto[ 1 ] < 0.0f ) - sto[ 1 ] += 1.0f; - - /* get offsets */ - x = ((float) width * sto[ 0 ]) + 0.5f; - x %= width; - y = ((float) height * sto[ 1 ]) + 0.5f; - y %= height; - - /* get pixel */ - pixels += (y * width * 4) + (x * 4); - VectorCopy( pixels, color ); - color[ 3 ] = pixels[ 3 ]; - return qtrue; -} - - - -/* -RadSample() -samples a fragment's lightmap or vertex color and returns an -average color and a color gradient for the sample -*/ - -#define MAX_SAMPLES 150 -#define SAMPLE_GRANULARITY 6 - -static void RadSample( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si, radWinding_t *rw, vec3_t average, vec3_t gradient, int *style ) -{ - int i, j, k, l, v, x, y, samples; - vec3_t color, mins, maxs; - vec4_t textureColor; - float alpha, alphaI, bf; - vec3_t blend; - float st[ 2 ], lightmap[ 2 ], *radLuxel; - radVert_t *rv[ 3 ]; - - - /* initial setup */ - ClearBounds( mins, maxs ); - VectorClear( average ); - VectorClear( gradient ); - alpha = 0; - - /* dummy check */ - if( rw == NULL || rw->numVerts < 3 ) - return; - - /* start sampling */ - samples = 0; - - /* sample vertex colors if no lightmap or this is the initial pass */ - if( lm == NULL || lm->radLuxels[ lightmapNum ] == NULL || bouncing == qfalse ) - { - for( samples = 0; samples < rw->numVerts; samples++ ) - { - /* multiply by texture color */ - if( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, rw->verts[ samples ].st, textureColor ) ) - { - VectorCopy( si->averageColor, textureColor ); - textureColor[ 4 ] = 255.0f; - } - for( i = 0; i < 3; i++ ) - color[ i ] = (textureColor[ i ] / 255) * (rw->verts[ samples ].color[ lightmapNum ][ i ] / 255.0f); - - AddPointToBounds( color, mins, maxs ); - VectorAdd( average, color, average ); - - /* get alpha */ - alpha += (textureColor[ 3 ] / 255.0f) * (rw->verts[ samples ].color[ lightmapNum ][ 3 ] / 255.0f); - } - - /* set style */ - *style = ds->vertexStyles[ lightmapNum ]; - } - - /* sample lightmap */ - else - { - /* fracture the winding into a fan (including degenerate tris) */ - for( v = 1; v < (rw->numVerts - 1) && samples < MAX_SAMPLES; v++ ) - { - /* get a triangle */ - rv[ 0 ] = &rw->verts[ 0 ]; - rv[ 1 ] = &rw->verts[ v ]; - rv[ 2 ] = &rw->verts[ v + 1 ]; - - /* this code is embarassing (really should just rasterize the triangle) */ - for( i = 1; i < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; i++ ) - { - for( j = 1; j < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; j++ ) - { - for( k = 1; k < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; k++ ) - { - /* create a blend vector (barycentric coordinates) */ - blend[ 0 ] = i; - blend[ 1 ] = j; - blend[ 2 ] = k; - bf = (1.0 / (blend[ 0 ] + blend[ 1 ] + blend[ 2 ])); - VectorScale( blend, bf, blend ); - - /* create a blended sample */ - st[ 0 ] = st[ 1 ] = 0.0f; - lightmap[ 0 ] = lightmap[ 1 ] = 0.0f; - alphaI = 0.0f; - for( l = 0; l < 3; l++ ) - { - st[ 0 ] += (rv[ l ]->st[ 0 ] * blend[ l ]); - st[ 1 ] += (rv[ l ]->st[ 1 ] * blend[ l ]); - lightmap[ 0 ] += (rv[ l ]->lightmap[ lightmapNum ][ 0 ] * blend[ l ]); - lightmap[ 1 ] += (rv[ l ]->lightmap[ lightmapNum ][ 1 ] * blend[ l ]); - alphaI += (rv[ l ]->color[ lightmapNum ][ 3 ] * blend[ l ]); - } - - /* get lightmap xy coords */ - x = lightmap[ 0 ] / (float) superSample; - y = lightmap[ 1 ] / (float) superSample; - if( x < 0 ) - x = 0; - else if ( x >= lm->w ) - x = lm->w - 1; - if( y < 0 ) - y = 0; - else if ( y >= lm->h ) - y = lm->h - 1; - - /* get radiosity luxel */ - radLuxel = RAD_LUXEL( lightmapNum, x, y ); - - /* ignore unlit/unused luxels */ - if( radLuxel[ 0 ] < 0.0f ) - continue; - - /* inc samples */ - samples++; - - /* multiply by texture color */ - if( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, st, textureColor ) ) - { - VectorCopy( si->averageColor, textureColor ); - textureColor[ 4 ] = 255; - } - for( i = 0; i < 3; i++ ) - color[ i ] = (textureColor[ i ] / 255) * (radLuxel[ i ] / 255); - - AddPointToBounds( color, mins, maxs ); - VectorAdd( average, color, average ); - - /* get alpha */ - alpha += (textureColor[ 3 ] / 255) * (alphaI / 255); - } - } - } - } - - /* set style */ - *style = ds->lightmapStyles[ lightmapNum ]; - } - - /* any samples? */ - if( samples <= 0 ) - return; - - /* average the color */ - VectorScale( average, (1.0 / samples), average ); - - /* create the color gradient */ - //% VectorSubtract( maxs, mins, delta ); - - /* new: color gradient will always be 0-1.0, expressed as the range of light relative to overall light */ - //% gradient[ 0 ] = maxs[ 0 ] > 0.0f ? (maxs[ 0 ] - mins[ 0 ]) / maxs[ 0 ] : 0.0f; - //% gradient[ 1 ] = maxs[ 1 ] > 0.0f ? (maxs[ 1 ] - mins[ 1 ]) / maxs[ 1 ] : 0.0f; - //% gradient[ 2 ] = maxs[ 2 ] > 0.0f ? (maxs[ 2 ] - mins[ 2 ]) / maxs[ 2 ] : 0.0f; - - /* newer: another contrast function */ - for( i = 0; i < 3; i++ ) - gradient[ i ] = (maxs[ i ] - mins[ i ]) * maxs[ i ]; -} - - - -/* -RadSubdivideDiffuseLight() -subdivides a radiosity winding until it is smaller than subdivide, then generates an area light -*/ - -#define RADIOSITY_MAX_GRADIENT 0.75f //% 0.25f -#define RADIOSITY_VALUE 500.0f -#define RADIOSITY_MIN 0.0001f -#define RADIOSITY_CLIP_EPSILON 0.125f - -static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si, - float scale, float subdivide, qboolean original, radWinding_t *rw, clipWork_t *cw ) -{ - int i, style = 0; - float dist, area, value; - vec3_t mins, maxs, normal, d1, d2, cross, color, gradient; - light_t *light, *splash; - winding_t *w; - - - /* dummy check */ - if( rw == NULL || rw->numVerts < 3 ) - return; - - /* get bounds for winding */ - ClearBounds( mins, maxs ); - for( i = 0; i < rw->numVerts; i++ ) - AddPointToBounds( rw->verts[ i ].xyz, mins, maxs ); - - /* subdivide if necessary */ - for( i = 0; i < 3; i++ ) - { - if( maxs[ i ] - mins[ i ] > subdivide ) - { - radWinding_t front, back; - - - /* make axial plane */ - VectorClear( normal ); - normal[ i ] = 1; - dist = (maxs[ i ] + mins[ i ]) * 0.5f; - - /* clip the winding */ - RadClipWindingEpsilon( rw, normal, dist, RADIOSITY_CLIP_EPSILON, &front, &back, cw ); - - /* recurse */ - RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qfalse, &front, cw ); - RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qfalse, &back, cw ); - return; - } - } - - /* check area */ - area = 0.0f; - for( i = 2; i < rw->numVerts; i++ ) - { - VectorSubtract( rw->verts[ i - 1 ].xyz, rw->verts[ 0 ].xyz, d1 ); - VectorSubtract( rw->verts[ i ].xyz, rw->verts[ 0 ].xyz, d2 ); - CrossProduct( d1, d2, cross ); - area += 0.5f * VectorLength( cross ); - } - if( area < 1.0f || area > 20000000.0f ) - return; - - /* more subdivision may be necessary */ - if( bouncing ) - { - /* get color sample for the surface fragment */ - RadSample( lightmapNum, ds, lm, si, rw, color, gradient, &style ); - - /* if color gradient is too high, subdivide again */ - if( subdivide > minDiffuseSubdivide && - (gradient[ 0 ] > RADIOSITY_MAX_GRADIENT || gradient[ 1 ] > RADIOSITY_MAX_GRADIENT || gradient[ 2 ] > RADIOSITY_MAX_GRADIENT) ) - { - RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, (subdivide / 2.0f), qfalse, rw, cw ); - return; - } - } - - /* create a regular winding and an average normal */ - w = AllocWinding( rw->numVerts ); - w->numpoints = rw->numVerts; - VectorClear( normal ); - for( i = 0; i < rw->numVerts; i++ ) - { - VectorCopy( rw->verts[ i ].xyz, w->p[ i ] ); - VectorAdd( normal, rw->verts[ i ].normal, normal ); - } - VectorScale( normal, (1.0f / rw->numVerts), normal ); - if( VectorNormalize( normal, normal ) == 0.0f ) - return; - - /* early out? */ - if( bouncing && VectorLength( color ) < RADIOSITY_MIN ) - return; - - /* debug code */ - //% Sys_Printf( "Size: %d %d %d\n", (int) (maxs[ 0 ] - mins[ 0 ]), (int) (maxs[ 1 ] - mins[ 1 ]), (int) (maxs[ 2 ] - mins[ 2 ]) ); - //% Sys_Printf( "Grad: %f %f %f\n", gradient[ 0 ], gradient[ 1 ], gradient[ 2 ] ); - - /* increment counts */ - numDiffuseLights++; - switch( ds->surfaceType ) - { - case MST_PLANAR: - numBrushDiffuseLights++; - break; - - case MST_TRIANGLE_SOUP: - numTriangleDiffuseLights++; - break; - - case MST_PATCH: - numPatchDiffuseLights++; - break; - } - - /* create a light */ - light = safe_malloc( sizeof( *light ) ); - memset( light, 0, sizeof( *light ) ); - - /* attach it */ - ThreadLock(); - light->next = lights; - lights = light; - ThreadUnlock(); - - /* initialize the light */ - light->flags = LIGHT_AREA_DEFAULT; - light->type = EMIT_AREA; - light->si = si; - light->fade = 1.0f; - light->w = w; - - /* set falloff threshold */ - light->falloffTolerance = falloffTolerance; - - /* bouncing light? */ - if( !bouncing ) - { - /* handle first-pass lights in normal q3a style */ - value = si->value; - light->photons = value * area * areaScale; - light->add = value * formFactorValueScale * areaScale; - VectorCopy( si->color, light->color ); - VectorScale( light->color, light->add, light->emitColor ); - light->style = noStyles ? LS_NORMAL : si->lightStyle; - if( light->style < LS_NORMAL || light->style >= LS_NONE ) - light->style = LS_NORMAL; - - /* set origin */ - VectorAdd( mins, maxs, light->origin ); - VectorScale( light->origin, 0.5f, light->origin ); - - /* nudge it off the plane a bit */ - VectorCopy( normal, light->normal ); - VectorMA( light->origin, 1.0f, light->normal, light->origin ); - light->dist = DotProduct( light->origin, normal ); - - /* optionally create a point splashsplash light for first pass */ - if( original && si->backsplashFraction > 0 ) - { - /* allocate a new point light */ - splash = safe_malloc( sizeof( *splash ) ); - memset( splash, 0, sizeof( *splash ) ); - splash->next = lights; - lights = splash; - - /* set it up */ - splash->flags = LIGHT_Q3A_DEFAULT; - splash->type = EMIT_POINT; - splash->photons = light->photons * si->backsplashFraction; - splash->fade = 1.0f; - splash->si = si; - VectorMA( light->origin, si->backsplashDistance, normal, splash->origin ); - VectorCopy( si->color, splash->color ); - splash->falloffTolerance = falloffTolerance; - splash->style = noStyles ? LS_NORMAL : light->style; - - /* add to counts */ - numPointLights++; - } - } - else - { - /* handle bounced light (radiosity) a little differently */ - value = RADIOSITY_VALUE * si->bounceScale * 0.375f; - light->photons = value * area * bounceScale; - light->add = value * formFactorValueScale * bounceScale; - VectorCopy( color, light->color ); - VectorScale( light->color, light->add, light->emitColor ); - light->style = noStyles ? LS_NORMAL : style; - if( light->style < LS_NORMAL || light->style >= LS_NONE ) - light->style = LS_NORMAL; - - /* set origin */ - WindingCenter( w, light->origin ); - - /* nudge it off the plane a bit */ - VectorCopy( normal, light->normal ); - VectorMA( light->origin, 1.0f, light->normal, light->origin ); - light->dist = DotProduct( light->origin, normal ); - } - - /* emit light from both sides? */ - if( si->compileFlags & C_FOG || si->twoSided ) - light->flags |= LIGHT_TWOSIDED; - - //% Sys_Printf( "\nAL: C: (%6f, %6f, %6f) [%6f] N: (%6f, %6f, %6f) %s\n", - //% light->color[ 0 ], light->color[ 1 ], light->color[ 2 ], light->add, - //% light->normal[ 0 ], light->normal[ 1 ], light->normal[ 2 ], - //% light->si->shader ); -} - - - -/* -RadLightForTriangles() -creates unbounced diffuse lights for triangle soup (misc_models, etc) -*/ - -void RadLightForTriangles( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ) -{ - int i, j, k, v; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - float *radVertexLuxel; - radWinding_t rw; - - - /* get surface */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* each triangle is a potential emitter */ - rw.numVerts = 3; - for( i = 0; i < ds->numIndexes; i += 3 ) - { - /* copy each vert */ - for( j = 0; j < 3; j++ ) - { - /* get vertex index and rad vertex luxel */ - v = ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ]; - - /* get most everything */ - memcpy( &rw.verts[ j ], &yDrawVerts[ v ], sizeof( bspDrawVert_t ) ); - - /* fix colors */ - for( k = 0; k < MAX_LIGHTMAPS; k++ ) - { - radVertexLuxel = RAD_VERTEX_LUXEL( k, ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ] ); - VectorCopy( radVertexLuxel, rw.verts[ j ].color[ k ] ); - rw.verts[ j ].color[ k ][ 3 ] = yDrawVerts[ v ].color[ k ][ 3 ]; - } - } - - /* subdivide into area lights */ - RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw ); - } -} - - - -/* -RadLightForPatch() -creates unbounced diffuse lights for patches -*/ - -#define PLANAR_EPSILON 0.1f - -void RadLightForPatch( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ) -{ - int i, x, y, v, t, pw[ 5 ], r; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - bspDrawVert_t *bogus; - bspDrawVert_t *dv[ 4 ]; - mesh_t src, *subdivided, *mesh; - float *radVertexLuxel; - float dist; - vec4_t plane; - qboolean planar; - radWinding_t rw; - - - /* get surface */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* construct a bogus vert list with color index stuffed into color[ 0 ] */ - bogus = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) ); - memcpy( bogus, &yDrawVerts[ ds->firstVert ], ds->numVerts * sizeof( bspDrawVert_t ) ); - for( i = 0; i < ds->numVerts; i++ ) - bogus[ i ].color[ 0 ][ 0 ] = i; - - /* build a subdivided mesh identical to shadow facets for this patch */ - /* this MUST MATCH FacetsForPatch() identically! */ - src.width = ds->patchWidth; - src.height = ds->patchHeight; - src.verts = bogus; - //% subdivided = SubdivideMesh( src, 8, 512 ); - subdivided = SubdivideMesh2( src, info->patchIterations ); - PutMeshOnCurve( *subdivided ); - //% MakeMeshNormals( *subdivided ); - mesh = RemoveLinearMeshColumnsRows( subdivided ); - FreeMesh( subdivided ); - free( bogus ); - - /* FIXME: build interpolation table into color[ 1 ] */ - - /* fix up color indexes */ - for( i = 0; i < (mesh->width * mesh->height); i++ ) - { - dv[ 0 ] = &mesh->verts[ i ]; - if( dv[ 0 ]->color[ 0 ][ 0 ] >= ds->numVerts ) - dv[ 0 ]->color[ 0 ][ 0 ] = ds->numVerts - 1; - } - - /* iterate through the mesh quads */ - for( y = 0; y < (mesh->height - 1); y++ ) - { - for( x = 0; x < (mesh->width - 1); x++ ) - { - /* set indexes */ - pw[ 0 ] = x + (y * mesh->width); - pw[ 1 ] = x + ((y + 1) * mesh->width); - pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); - pw[ 3 ] = x + 1 + (y * mesh->width); - pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ - - /* set radix */ - r = (x + y) & 1; - - /* get drawverts */ - dv[ 0 ] = &mesh->verts[ pw[ r + 0 ] ]; - dv[ 1 ] = &mesh->verts[ pw[ r + 1 ] ]; - dv[ 2 ] = &mesh->verts[ pw[ r + 2 ] ]; - dv[ 3 ] = &mesh->verts[ pw[ r + 3 ] ]; - - /* planar? */ - planar = PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ); - if( planar ) - { - dist = DotProduct( dv[ 1 ]->xyz, plane ) - plane[ 3 ]; - if( fabs( dist ) > PLANAR_EPSILON ) - planar = qfalse; - } - - /* generate a quad */ - if( planar ) - { - rw.numVerts = 4; - for( v = 0; v < 4; v++ ) - { - /* get most everything */ - memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) ); - - /* fix colors */ - for( i = 0; i < MAX_LIGHTMAPS; i++ ) - { - radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] ); - VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] ); - rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ]; - } - } - - /* subdivide into area lights */ - RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw ); - } - - /* generate 2 tris */ - else - { - rw.numVerts = 3; - for( t = 0; t < 2; t++ ) - { - for( v = 0; v < 3 + t; v++ ) - { - /* get "other" triangle (stupid hacky logic, but whatevah) */ - if( v == 1 && t == 1 ) - v++; - - /* get most everything */ - memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) ); - - /* fix colors */ - for( i = 0; i < MAX_LIGHTMAPS; i++ ) - { - radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] ); - VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] ); - rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ]; - } - } - - /* subdivide into area lights */ - RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw ); - } - } - } - } - - /* free the mesh */ - FreeMesh( mesh ); -} - - - - -/* -RadLight() -creates unbounced diffuse lights for a given surface -*/ - -void RadLight( int num ) -{ - int lightmapNum; - float scale, subdivide; - int contentFlags, surfaceFlags, compileFlags; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - rawLightmap_t *lm; - shaderInfo_t *si; - clipWork_t cw; - - - /* get drawsurface, lightmap, and shader info */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - lm = info->lm; - si = info->si; - scale = si->bounceScale; - - /* find nodraw bit */ - contentFlags = surfaceFlags = compileFlags = 0; - ApplySurfaceParm( "nodraw", &contentFlags, &surfaceFlags, &compileFlags ); - - // jal : avoid bouncing on trans surfaces - ApplySurfaceParm( "trans", &contentFlags, &surfaceFlags, &compileFlags ); - - /* early outs? */ - if( scale <= 0.0f || (si->compileFlags & C_SKY) || si->autosprite || - (bspShaders[ ds->shaderNum ].contentFlags & contentFlags) || (bspShaders[ ds->shaderNum ].surfaceFlags & surfaceFlags) || - (si->compileFlags & compileFlags) ) - return; - - /* determine how much we need to chop up the surface */ - if( si->lightSubdivide ) - subdivide = si->lightSubdivide; - else - subdivide = diffuseSubdivide; - - /* inc counts */ - numDiffuseSurfaces++; - - /* iterate through styles (this could be more efficient, yes) */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* switch on type */ - if( ds->lightmapStyles[ lightmapNum ] != LS_NONE && ds->lightmapStyles[ lightmapNum ] != LS_UNUSED ) - { - switch( ds->surfaceType ) - { - case MST_PLANAR: - case MST_TRIANGLE_SOUP: - RadLightForTriangles( num, lightmapNum, lm, si, scale, subdivide, &cw ); - break; - - case MST_PATCH: - RadLightForPatch( num, lightmapNum, lm, si, scale, subdivide, &cw ); - break; - - default: - break; - } - } - } -} - - - -/* -RadCreateDiffuseLights() -creates lights for unbounced light on surfaces in the bsp -*/ - -int iterations = 0; - -void RadCreateDiffuseLights( void ) -{ - /* startup */ - Sys_FPrintf( SYS_VRB, "--- RadCreateDiffuseLights ---\n" ); - numDiffuseSurfaces = 0; - numDiffuseLights = 0; - numBrushDiffuseLights = 0; - numTriangleDiffuseLights = 0; - numPatchDiffuseLights = 0; - numAreaLights = 0; - - /* hit every surface (threaded) */ - RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, RadLight ); - - /* dump the lights generated to a file */ - if( dump ) - { - char dumpName[ 1024 ], ext[ 64 ]; - FILE *file; - light_t *light; - - strcpy( dumpName, source ); - StripExtension( dumpName ); - sprintf( ext, "_bounce_%03d.map", iterations ); - strcat( dumpName, ext ); - file = fopen( dumpName, "wb" ); - Sys_Printf( "Writing %s...\n", dumpName ); - if( file ) - { - for( light = lights; light; light = light->next ) - { - fprintf( file, - "{\n" - "\"classname\" \"light\"\n" - "\"light\" \"%d\"\n" - "\"origin\" \"%.0f %.0f %.0f\"\n" - "\"_color\" \"%.3f %.3f %.3f\"\n" - "}\n", - - (int) light->add, - - light->origin[ 0 ], - light->origin[ 1 ], - light->origin[ 2 ], - - light->color[ 0 ], - light->color[ 1 ], - light->color[ 2 ] ); - } - fclose( file ); - } - } - - /* increment */ - iterations++; - - /* print counts */ - Sys_Printf( "%8d diffuse surfaces\n", numDiffuseSurfaces ); - Sys_FPrintf( SYS_VRB, "%8d total diffuse lights\n", numDiffuseLights ); - Sys_FPrintf( SYS_VRB, "%8d brush diffuse lights\n", numBrushDiffuseLights ); - Sys_FPrintf( SYS_VRB, "%8d patch diffuse lights\n", numPatchDiffuseLights ); - Sys_FPrintf( SYS_VRB, "%8d triangle diffuse lights\n", numTriangleDiffuseLights ); -} - - - - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_shadows.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_shadows.c deleted file mode 100644 index d482bbca..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_shadows.c +++ /dev/null @@ -1,124 +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 -*/ - -#define LIGHT_SHADOWS_C - -#include "light.h" -#include "inout.h" - - - -/* ------------------------------------------------------------------------------- - -ydnar: this code deals with shadow volume bsps - -------------------------------------------------------------------------------- */ - -typedef struct shadowNode_s -{ - vec4_t plane; - int children[ 2 ]; -} -shadowNode_t; - -int numShadowNodes; -shadowNode_t *shadowNodes; - - - -/* -AddShadow() -adds a shadow, returning the index into the shadow list -*/ - - - -/* -MakeShadowFromPoints() -creates a shadow volume from 4 points (the first being the light origin) -*/ - - - -/* -SetupShadows() -sets up the shadow volumes for all lights in the world -*/ - -void SetupShadows( void ) -{ - int i, j, s; - light_t *light; - dleaf_t *leaf; - dsurface_t *ds; - surfaceInfo_t *info; - shaderInfo_t *si; - byte *tested; - - - /* early out for weird cases where there are no lights */ - if( lights == NULL ) - return; - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- SetupShadows ---\n" ); - - /* allocate a surface test list */ - tested = safe_malloc( numDrawSurfaces / 8 + 1 ); - - /* walk the list of lights */ - for( light = lights; light != NULL; light = light->next ) - { - /* do some early out testing */ - if( light->cluster < 0 ) - continue; - - /* clear surfacetest list */ - memset( tested, 0, numDrawSurfaces / 8 + 1 ); - - /* walk the bsp leaves */ - for( i = 0, leaf = dleafs; i < numleafs; i++, leaf++ ) - { - /* in pvs? */ - if( ClusterVisible( light->cluster, leaf->cluster ) == qfalse ) - continue; - - /* walk the surface list for this leaf */ - for( j = 0; j < leaf->numLeafSurfaces; j++ ) - { - /* don't filter a surface more than once */ - s = dleafsurfaces[ leaf->firstLeafSurface + j ]; - if( tested[ s >> 3 ] & (1 << (s & 7)) ) - continue; - tested[ s >> 3 ] |= (1 << (s & 7)); - - /* get surface and info */ - ds = &drawSurfaces[ s ]; - info = &surfaceInfos[ s ]; - si = info->si; - - /* don't create shadow volumes from translucent surfaces */ - if( si->contents & CONTENTS_TRANSLUCENT ) - continue; - } - } - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_trace.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_trace.c deleted file mode 100644 index 8e79244e..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_trace.c +++ /dev/null @@ -1,1752 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define LIGHT_TRACE_C - - - -/* dependencies */ -#include "q3map2.h" - - -/* dependencies */ -#include "q3map2.h" - - - -#define Vector2Copy( a, b ) ((b)[ 0 ] = (a)[ 0 ], (b)[ 1 ] = (a)[ 1 ]) -#define Vector4Copy( a, b ) ((b)[ 0 ] = (a)[ 0 ], (b)[ 1 ] = (a)[ 1 ], (b)[ 2 ] = (a)[ 2 ], (b)[ 3 ] = (a)[ 3 ]) - -#define MAX_NODE_ITEMS 5 -#define MAX_NODE_TRIANGLES 5 -#define MAX_TRACE_DEPTH 32 -#define MIN_NODE_SIZE 32.0f - -#define GROW_TRACE_INFOS 32768 //% 4096 -#define GROW_TRACE_WINDINGS 65536 //% 32768 -#define GROW_TRACE_TRIANGLES 131072 //% 32768 -#define GROW_TRACE_NODES 16384 //% 16384 -#define GROW_NODE_ITEMS 16 //% 256 - -#define MAX_TW_VERTS 24 // vortex: increased from 12 to 24 for ability co compile some insane maps with large curve count - -#define TRACE_ON_EPSILON 0.1f - -#define TRACE_LEAF -1 -#define TRACE_LEAF_SOLID -2 - -typedef struct traceVert_s -{ - vec3_t xyz; - float st[ 2 ]; -} -traceVert_t; - -typedef struct traceInfo_s -{ - shaderInfo_t *si; - int surfaceNum, castShadows, skipGrid; -} -traceInfo_t; - -typedef struct traceWinding_s -{ - vec4_t plane; - int infoNum, numVerts; - traceVert_t v[ MAX_TW_VERTS ]; -} -traceWinding_t; - -typedef struct traceTriangle_s -{ - vec3_t edge1, edge2; - int infoNum; - traceVert_t v[ 3 ]; -} -traceTriangle_t; - -typedef struct traceNode_s -{ - int type; - vec4_t plane; - vec3_t mins, maxs; - int children[ 2 ]; - int numItems, maxItems; - int *items; -} -traceNode_t; - - -int noDrawContentFlags, noDrawSurfaceFlags, noDrawCompileFlags; - -int numTraceInfos = 0, maxTraceInfos = 0, firstTraceInfo = 0; -traceInfo_t *traceInfos = NULL; - -int numTraceWindings = 0, maxTraceWindings = 0, deadWinding = -1; -traceWinding_t *traceWindings = NULL; - -int numTraceTriangles = 0, maxTraceTriangles = 0, deadTriangle = -1; -traceTriangle_t *traceTriangles = NULL; - -int headNodeNum = 0, skyboxNodeNum = 0, maxTraceDepth = 0, numTraceLeafNodes = 0; -int numTraceNodes = 0, maxTraceNodes = 0; -traceNode_t *traceNodes = NULL; - - - -/* ------------------------------------------------------------------------------- - -allocation and list management - -------------------------------------------------------------------------------- */ - -/* -AddTraceInfo() - ydnar -adds a trace info structure to the pool -*/ - -static int AddTraceInfo( traceInfo_t *ti ) -{ - int num; - void *temp; - - - /* find an existing info */ - for( num = firstTraceInfo; num < numTraceInfos; num++ ) - { - if( traceInfos[ num ].si == ti->si && - traceInfos[ num ].surfaceNum == ti->surfaceNum && - traceInfos[ num ].castShadows == ti->castShadows && - traceInfos[ num ].skipGrid == ti->skipGrid ) - return num; - } - - /* enough space? */ - if( numTraceInfos >= maxTraceInfos ) - { - /* allocate more room */ - maxTraceInfos += GROW_TRACE_INFOS; - temp = safe_malloc( maxTraceInfos * sizeof( *traceInfos ) ); - if( traceInfos != NULL ) - { - memcpy( temp, traceInfos, numTraceInfos * sizeof( *traceInfos ) ); - free( traceInfos ); - } - traceInfos = (traceInfo_t*) temp; - } - - /* add the info */ - memcpy( &traceInfos[ num ], ti, sizeof( *traceInfos ) ); - if( num == numTraceInfos ) - numTraceInfos++; - - /* return the ti number */ - return num; -} - - - -/* -AllocTraceNode() - ydnar -allocates a new trace node -*/ - -static int AllocTraceNode( void ) -{ - traceNode_t *temp; - - - /* enough space? */ - if( numTraceNodes >= maxTraceNodes ) - { - /* reallocate more room */ - maxTraceNodes += GROW_TRACE_NODES; - temp = safe_malloc( maxTraceNodes * sizeof( traceNode_t ) ); - if( traceNodes != NULL ) - { - memcpy( temp, traceNodes, numTraceNodes * sizeof( traceNode_t ) ); - free( traceNodes ); - } - traceNodes = temp; - } - - /* add the node */ - memset( &traceNodes[ numTraceNodes ], 0, sizeof( traceNode_t ) ); - traceNodes[ numTraceNodes ].type = TRACE_LEAF; - ClearBounds( traceNodes[ numTraceNodes ].mins, traceNodes[ numTraceNodes ].maxs ); - - /* Sys_Printf("alloc node %d\n", numTraceNodes); */ - - numTraceNodes++; - - /* return the count */ - return (numTraceNodes - 1); -} - - - -/* -AddTraceWinding() - ydnar -adds a winding to the raytracing pool -*/ - -static int AddTraceWinding( traceWinding_t *tw ) -{ - int num; - void *temp; - - - /* check for a dead winding */ - if( deadWinding >= 0 && deadWinding < numTraceWindings ) - num = deadWinding; - else - { - /* put winding at the end of the list */ - num = numTraceWindings; - - /* enough space? */ - if( numTraceWindings >= maxTraceWindings ) - { - /* allocate more room */ - maxTraceWindings += GROW_TRACE_WINDINGS; - temp = safe_malloc( maxTraceWindings * sizeof( *traceWindings ) ); - if( traceWindings != NULL ) - { - memcpy( temp, traceWindings, numTraceWindings * sizeof( *traceWindings ) ); - free( traceWindings ); - } - traceWindings = (traceWinding_t*) temp; - } - } - - /* add the winding */ - memcpy( &traceWindings[ num ], tw, sizeof( *traceWindings ) ); - if( num == numTraceWindings ) - numTraceWindings++; - deadWinding = -1; - - /* return the winding number */ - return num; -} - - - -/* -AddTraceTriangle() - ydnar -adds a triangle to the raytracing pool -*/ - -static int AddTraceTriangle( traceTriangle_t *tt ) -{ - int num; - void *temp; - - - /* check for a dead triangle */ - if( deadTriangle >= 0 && deadTriangle < numTraceTriangles ) - num = deadTriangle; - else - { - /* put triangle at the end of the list */ - num = numTraceTriangles; - - /* enough space? */ - if( numTraceTriangles >= maxTraceTriangles ) - { - /* allocate more room */ - maxTraceTriangles += GROW_TRACE_TRIANGLES; - temp = safe_malloc( maxTraceTriangles * sizeof( *traceTriangles ) ); - if( traceTriangles != NULL ) - { - memcpy( temp, traceTriangles, numTraceTriangles * sizeof( *traceTriangles ) ); - free( traceTriangles ); - } - traceTriangles = (traceTriangle_t*) temp; - } - } - - /* find vectors for two edges sharing the first vert */ - VectorSubtract( tt->v[ 1 ].xyz, tt->v[ 0 ].xyz, tt->edge1 ); - VectorSubtract( tt->v[ 2 ].xyz, tt->v[ 0 ].xyz, tt->edge2 ); - - /* add the triangle */ - memcpy( &traceTriangles[ num ], tt, sizeof( *traceTriangles ) ); - if( num == numTraceTriangles ) - numTraceTriangles++; - deadTriangle = -1; - - /* return the triangle number */ - return num; -} - - - -/* -AddItemToTraceNode() - ydnar -adds an item reference (winding or triangle) to a trace node -*/ - -static int AddItemToTraceNode( traceNode_t *node, int num ) -{ - void *temp; - - - /* dummy check */ - if( num < 0 ) - return -1; - - /* enough space? */ - if( node->numItems >= node->maxItems ) - { - /* allocate more room */ - if( node == traceNodes ) - node->maxItems *= 2; - else - node->maxItems += GROW_NODE_ITEMS; - if( node->maxItems <= 0 ) - node->maxItems = GROW_NODE_ITEMS; - temp = safe_malloc( node->maxItems * sizeof( *node->items ) ); - if( node->items != NULL ) - { - memcpy( temp, node->items, node->numItems * sizeof( *node->items ) ); - free( node->items ); - } - node->items = (int*) temp; - } - - /* add the poly */ - node->items[ node->numItems ] = num; - node->numItems++; - - /* return the count */ - return (node->numItems - 1); -} - - - - -/* ------------------------------------------------------------------------------- - -trace node setup - -------------------------------------------------------------------------------- */ - -/* -SetupTraceNodes_r() - ydnar -recursively create the initial trace node structure from the bsp tree -*/ - -static int SetupTraceNodes_r( int bspNodeNum ) -{ - int i, nodeNum, bspLeafNum, newNode; - bspPlane_t *plane; - bspNode_t *bspNode; - - - /* get bsp node and plane */ - bspNode = &bspNodes[ bspNodeNum ]; - plane = &bspPlanes[ bspNode->planeNum ]; - - /* allocate a new trace node */ - nodeNum = AllocTraceNode(); - - /* setup trace node */ - traceNodes[ nodeNum ].type = PlaneTypeForNormal( plane->normal ); - VectorCopy( plane->normal, traceNodes[ nodeNum ].plane ); - traceNodes[ nodeNum ].plane[ 3 ] = plane->dist; - - /* setup children */ - for( i = 0; i < 2; i++ ) - { - /* leafnode */ - if( bspNode->children[ i ] < 0 ) - { - bspLeafNum = -bspNode->children[ i ] - 1; - - /* new code */ - newNode = AllocTraceNode(); - traceNodes[ nodeNum ].children[ i ] = newNode; - /* have to do this separately, as gcc first executes LHS, then RHS, and if a realloc took place, this fails */ - - if( bspLeafs[ bspLeafNum ].cluster == -1 ) - traceNodes[ traceNodes[ nodeNum ].children[ i ] ].type = TRACE_LEAF_SOLID; - } - - /* normal node */ - else - { - newNode = SetupTraceNodes_r( bspNode->children[ i ] ); - traceNodes[ nodeNum ].children[ i ] = newNode; - } - - if(traceNodes[ nodeNum ].children[ i ] == 0) - Error( "Invalid tracenode allocated" ); - } - - /* Sys_Printf("node %d children: %d %d\n", nodeNum, traceNodes[ nodeNum ].children[0], traceNodes[ nodeNum ].children[1]); */ - - /* return node number */ - return nodeNum; -} - - - -/* -ClipTraceWinding() - ydnar -clips a trace winding against a plane into one or two parts -*/ - -#define TW_ON_EPSILON 0.25f - -void ClipTraceWinding( traceWinding_t *tw, vec4_t plane, traceWinding_t *front, traceWinding_t *back ) -{ - int i, j, k; - int sides[ MAX_TW_VERTS ], counts[ 3 ] = { 0, 0, 0 }; - float dists[ MAX_TW_VERTS ]; - float frac; - traceVert_t *a, *b, mid; - - - /* clear front and back */ - front->numVerts = 0; - back->numVerts = 0; - - /* classify points */ - for( i = 0; i < tw->numVerts; i++ ) - { - dists[ i ] = DotProduct( tw->v[ i ].xyz, plane ) - plane[ 3 ]; - if( dists[ i ] < -TW_ON_EPSILON ) - sides[ i ] = SIDE_BACK; - else if( dists[ i ] > TW_ON_EPSILON ) - sides[ i ] = SIDE_FRONT; - else - sides[ i ] = SIDE_ON; - counts[ sides[ i ] ]++; - } - - /* entirely on front? */ - if( counts[ SIDE_BACK ] == 0 ) - memcpy( front, tw, sizeof( *front ) ); - - /* entirely on back? */ - else if( counts[ SIDE_FRONT ] == 0 ) - memcpy( back, tw, sizeof( *back ) ); - - /* straddles the plane */ - else - { - /* setup front and back */ - memcpy( front, tw, sizeof( *front ) ); - front->numVerts = 0; - memcpy( back, tw, sizeof( *back ) ); - back->numVerts = 0; - - /* split the winding */ - for( i = 0; i < tw->numVerts; i++ ) - { - /* radix */ - j = (i + 1) % tw->numVerts; - - /* get verts */ - a = &tw->v[ i ]; - b = &tw->v[ j ]; - - /* handle points on the splitting plane */ - switch( sides[ i ] ) - { - case SIDE_FRONT: - if( front->numVerts >= MAX_TW_VERTS ) - Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); - front->v[ front->numVerts++ ] = *a; - break; - - case SIDE_BACK: - if( back->numVerts >= MAX_TW_VERTS ) - Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); - back->v[ back->numVerts++ ] = *a; - break; - - case SIDE_ON: - if( front->numVerts >= MAX_TW_VERTS || back->numVerts >= MAX_TW_VERTS ) - Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); - front->v[ front->numVerts++ ] = *a; - back->v[ back->numVerts++ ] = *a; - continue; - } - - /* check next point to see if we need to split the edge */ - if( sides[ j ] == SIDE_ON || sides[ j ] == sides[ i ] ) - continue; - - /* check limit */ - if( front->numVerts >= MAX_TW_VERTS || back->numVerts >= MAX_TW_VERTS ) - Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); - - /* generate a split point */ - frac = dists[ i ] / (dists[ i ] - dists[ j ]); - for( k = 0; k < 3; k++ ) - { - /* minimize fp precision errors */ - if( plane[ k ] == 1.0f ) - mid.xyz[ k ] = plane[ 3 ]; - else if( plane[ k ] == -1.0f ) - mid.xyz[ k ] = -plane[ 3 ]; - else - mid.xyz[ k ] = a->xyz[ k ] + frac * (b->xyz[ k ] - a->xyz[ k ]); - } - /* set texture coordinates */ - mid.st[ 0 ] = a->st[ 0 ] + frac * (b->st[ 0 ] - a->st[ 0 ]); - mid.st[ 1 ] = a->st[ 1 ] + frac * (b->st[ 1 ] - a->st[ 1 ]); - - /* copy midpoint to front and back polygons */ - front->v[ front->numVerts++ ] = mid; - back->v[ back->numVerts++ ] = mid; - } - } -} - - - -/* -FilterTraceWindingIntoNodes_r() - ydnar -filters a trace winding into the raytracing tree -*/ - -static void FilterTraceWindingIntoNodes_r( traceWinding_t *tw, int nodeNum ) -{ - int num; - vec4_t plane1, plane2, reverse; - traceNode_t *node; - traceWinding_t front, back; - - - /* don't filter if passed a bogus node (solid, etc) */ - if( nodeNum < 0 || nodeNum >= numTraceNodes ) - return; - - /* get node */ - node = &traceNodes[ nodeNum ]; - - /* is this a decision node? */ - if( node->type >= 0 ) - { - /* create winding plane if necessary, filtering out bogus windings as well */ - if( nodeNum == headNodeNum ) - { - if( !PlaneFromPoints( tw->plane, tw->v[ 0 ].xyz, tw->v[ 1 ].xyz, tw->v[ 2 ].xyz ) ) - return; - } - - /* validate the node */ - if( node->children[ 0 ] == 0 || node->children[ 1 ] == 0 ) - Error( "Invalid tracenode: %d", nodeNum ); - - /* get node plane */ - Vector4Copy( node->plane, plane1 ); - - /* get winding plane */ - Vector4Copy( tw->plane, plane2 ); - - /* invert surface plane */ - VectorSubtract( vec3_origin, plane2, reverse ); - reverse[ 3 ] = -plane2[ 3 ]; - - /* front only */ - if( DotProduct( plane1, plane2 ) > 0.999f && fabs( plane1[ 3 ] - plane2[ 3 ] ) < 0.001f ) - { - FilterTraceWindingIntoNodes_r( tw, node->children[ 0 ] ); - return; - } - - /* back only */ - if( DotProduct( plane1, reverse ) > 0.999f && fabs( plane1[ 3 ] - reverse[ 3 ] ) < 0.001f ) - { - FilterTraceWindingIntoNodes_r( tw, node->children[ 1 ] ); - return; - } - - /* clip the winding by node plane */ - ClipTraceWinding( tw, plane1, &front, &back ); - - /* filter by node plane */ - if( front.numVerts >= 3 ) - FilterTraceWindingIntoNodes_r( &front, node->children[ 0 ] ); - if( back.numVerts >= 3 ) - FilterTraceWindingIntoNodes_r( &back, node->children[ 1 ] ); - - /* return to caller */ - return; - } - - /* add winding to leaf node */ - num = AddTraceWinding( tw ); - AddItemToTraceNode( node, num ); -} - - - -/* -SubdivideTraceNode_r() - ydnar -recursively subdivides a tracing node until it meets certain size and complexity criteria -*/ - -static void SubdivideTraceNode_r( int nodeNum, int depth ) -{ - int i, j, count, num, frontNum, backNum, type; - vec3_t size; - float dist; - double average[ 3 ]; - traceNode_t *node, *frontNode, *backNode; - traceWinding_t *tw, front, back; - - - /* dummy check */ - if( nodeNum < 0 || nodeNum >= numTraceNodes ) - return; - - /* get node */ - node = &traceNodes[ nodeNum ]; - - /* runaway recursion check */ - if( depth >= MAX_TRACE_DEPTH ) - { - //% Sys_Printf( "Depth: (%d items)\n", node->numItems ); - numTraceLeafNodes++; - return; - } - depth++; - - /* is this a decision node? */ - if( node->type >= 0 ) - { - /* subdivide children */ - frontNum = node->children[ 0 ]; - backNum = node->children[ 1 ]; - SubdivideTraceNode_r( frontNum, depth ); - SubdivideTraceNode_r( backNum, depth ); - return; - } - - /* bound the node */ - ClearBounds( node->mins, node->maxs ); - VectorClear( average ); - count = 0; - for( i = 0; i < node->numItems; i++ ) - { - /* get winding */ - tw = &traceWindings[ node->items[ i ] ]; - - /* walk its verts */ - for( j = 0; j < tw->numVerts; j++ ) - { - AddPointToBounds( tw->v[ j ].xyz, node->mins, node->maxs ); - average[ 0 ] += tw->v[ j ].xyz[ 0 ]; - average[ 1 ] += tw->v[ j ].xyz[ 1 ]; - average[ 2 ] += tw->v[ j ].xyz[ 2 ]; - count++; - } - } - - /* check triangle limit */ - //% if( node->numItems <= MAX_NODE_ITEMS ) - if( (count - (node->numItems * 2)) < MAX_NODE_TRIANGLES ) - { - //% Sys_Printf( "Limit: (%d triangles)\n", (count - (node->numItems * 2)) ); - numTraceLeafNodes++; - return; - } - - /* the largest dimension of the bounding box will be the split axis */ - VectorSubtract( node->maxs, node->mins, size ); - if( size[ 0 ] >= size[ 1 ] && size[ 0 ] >= size[ 2 ] ) - type = PLANE_X; - else if( size[ 1 ] >= size[ 0 ] && size[ 1 ] >= size[ 2 ] ) - type = PLANE_Y; - else - type = PLANE_Z; - - /* don't split small nodes */ - if( size[ type ] <= MIN_NODE_SIZE ) - { - //% Sys_Printf( "Limit: %f %f %f (%d items)\n", size[ 0 ], size[ 1 ], size[ 2 ], node->numItems ); - numTraceLeafNodes++; - return; - } - - /* set max trace depth */ - if( depth > maxTraceDepth ) - maxTraceDepth = depth; - - /* snap the average */ - dist = floor( average[ type ] / count ); - - /* dummy check it */ - if( dist <= node->mins[ type ] || dist >= node->maxs[ type ] ) - dist = floor( 0.5f * (node->mins[ type ] + node->maxs[ type ]) ); - - /* allocate child nodes */ - frontNum = AllocTraceNode(); - backNum = AllocTraceNode(); - - /* reset pointers */ - node = &traceNodes[ nodeNum ]; - frontNode = &traceNodes[ frontNum ]; - backNode = &traceNodes[ backNum ]; - - /* attach children */ - node->type = type; - node->plane[ type ] = 1.0f; - node->plane[ 3 ] = dist; - node->children[ 0 ] = frontNum; - node->children[ 1 ] = backNum; - - /* setup front node */ - frontNode->maxItems = (node->maxItems >> 1); - frontNode->items = safe_malloc( frontNode->maxItems * sizeof( *frontNode->items ) ); - - /* setup back node */ - backNode->maxItems = (node->maxItems >> 1); - backNode->items = safe_malloc( backNode->maxItems * sizeof( *backNode->items ) ); - - /* filter windings into child nodes */ - for( i = 0; i < node->numItems; i++ ) - { - /* get winding */ - tw = &traceWindings[ node->items[ i ] ]; - - /* clip the winding by the new split plane */ - ClipTraceWinding( tw, node->plane, &front, &back ); - - /* kill the existing winding */ - if( front.numVerts >= 3 || back.numVerts >= 3 ) - deadWinding = node->items[ i ]; - - /* add front winding */ - if( front.numVerts >= 3 ) - { - num = AddTraceWinding( &front ); - AddItemToTraceNode( frontNode, num ); - } - - /* add back winding */ - if( back.numVerts >= 3 ) - { - num = AddTraceWinding( &back ); - AddItemToTraceNode( backNode, num ); - } - } - - /* free original node winding list */ - node->numItems = 0; - node->maxItems = 0; - free( node->items ); - node->items = NULL; - - /* check children */ - if( frontNode->numItems <= 0 ) - { - frontNode->maxItems = 0; - free( frontNode->items ); - frontNode->items = NULL; - } - - if( backNode->numItems <= 0 ) - { - backNode->maxItems = 0; - free( backNode->items ); - backNode->items = NULL; - } - - /* subdivide children */ - SubdivideTraceNode_r( frontNum, depth ); - SubdivideTraceNode_r( backNum, depth ); -} - - - -/* -TriangulateTraceNode_r() -optimizes the tracing data by changing trace windings into triangles -*/ - -static int TriangulateTraceNode_r( int nodeNum ) -{ - int i, j, num, frontNum, backNum, numWindings, *windings; - traceNode_t *node; - traceWinding_t *tw; - traceTriangle_t tt; - - - /* dummy check */ - if( nodeNum < 0 || nodeNum >= numTraceNodes ) - return 0; - - /* get node */ - node = &traceNodes[ nodeNum ]; - - /* is this a decision node? */ - if( node->type >= 0 ) - { - /* triangulate children */ - frontNum = node->children[ 0 ]; - backNum = node->children[ 1 ]; - node->numItems = TriangulateTraceNode_r( frontNum ); - node->numItems += TriangulateTraceNode_r( backNum ); - return node->numItems; - } - - /* empty node? */ - if( node->numItems == 0 ) - { - node->maxItems = 0; - if( node->items != NULL ) - free( node->items ); - return node->numItems; - } - - /* store off winding data */ - numWindings = node->numItems; - windings = node->items; - - /* clear it */ - node->numItems = 0; - node->maxItems = numWindings * 2; - node->items = safe_malloc( node->maxItems * sizeof( tt ) ); - - /* walk winding list */ - for( i = 0; i < numWindings; i++ ) - { - /* get winding */ - tw = &traceWindings[ windings[ i ] ]; - - /* initial setup */ - tt.infoNum = tw->infoNum; - tt.v[ 0 ] = tw->v[ 0 ]; - - /* walk vertex list */ - for( j = 1; j + 1 < tw->numVerts; j++ ) - { - /* set verts */ - tt.v[ 1 ] = tw->v[ j ]; - tt.v[ 2 ] = tw->v[ j + 1 ]; - - /* find vectors for two edges sharing the first vert */ - VectorSubtract( tt.v[ 1 ].xyz, tt.v[ 0 ].xyz, tt.edge1 ); - VectorSubtract( tt.v[ 2 ].xyz, tt.v[ 0 ].xyz, tt.edge2 ); - - /* add it to the node */ - num = AddTraceTriangle( &tt ); - AddItemToTraceNode( node, num ); - } - } - - /* free windings */ - if( windings != NULL ) - free( windings ); - - /* return item count */ - return node->numItems; -} - - - -/* ------------------------------------------------------------------------------- - -shadow casting item setup (triangles, patches, entities) - -------------------------------------------------------------------------------- */ - -/* -PopulateWithBSPModel() - ydnar -filters a bsp model's surfaces into the raytracing tree -*/ - -static void PopulateWithBSPModel( bspModel_t *model, m4x4_t transform ) -{ - int i, j, x, y, pw[ 5 ], r, nodeNum; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - bspDrawVert_t *verts; - int *indexes; - mesh_t srcMesh, *mesh, *subdivided; - traceInfo_t ti; - traceWinding_t tw; - - - /* dummy check */ - if( model == NULL || transform == NULL ) - return; - - /* walk the list of surfaces in this model and fill out the info structs */ - for( i = 0; i < model->numBSPSurfaces; i++ ) - { - /* get surface and info */ - ds = &bspDrawSurfaces[ model->firstBSPSurface + i ]; - info = &surfaceInfos[ model->firstBSPSurface + i ]; - if( info->si == NULL ) - continue; - - /* no shadows */ - if( !info->castShadows ) - continue; - - /* patchshadows? */ - if( ds->surfaceType == MST_PATCH && patchShadows == qfalse ) - continue; - - /* some surfaces in the bsp might have been tagged as nodraw, with a bogus shader */ - if( (bspShaders[ ds->shaderNum ].contentFlags & noDrawContentFlags) || - (bspShaders[ ds->shaderNum ].surfaceFlags & noDrawSurfaceFlags) ) - continue; - - /* translucent surfaces that are neither alphashadow or lightfilter don't cast shadows */ - if( (info->si->compileFlags & C_NODRAW) ) - continue; - if( (info->si->compileFlags & C_TRANSLUCENT) && - !(info->si->compileFlags & C_ALPHASHADOW) && - !(info->si->compileFlags & C_LIGHTFILTER) ) - continue; - - /* setup trace info */ - ti.si = info->si; - ti.castShadows = info->castShadows; - ti.surfaceNum = model->firstBSPBrush + i; - ti.skipGrid = (ds->surfaceType == MST_PATCH); - - /* choose which node (normal or skybox) */ - if( info->parentSurfaceNum >= 0 ) - { - nodeNum = skyboxNodeNum; - - /* sky surfaces in portal skies are ignored */ - if( info->si->compileFlags & C_SKY ) - continue; - } - else - nodeNum = headNodeNum; - - /* setup trace winding */ - memset( &tw, 0, sizeof( tw ) ); - tw.infoNum = AddTraceInfo( &ti ); - tw.numVerts = 3; - - /* switch on type */ - switch( ds->surfaceType ) - { - /* handle patches */ - case MST_PATCH: - /* subdivide the surface */ - srcMesh.width = ds->patchWidth; - srcMesh.height = ds->patchHeight; - srcMesh.verts = &bspDrawVerts[ ds->firstVert ]; - //% subdivided = SubdivideMesh( srcMesh, 8, 512 ); - subdivided = SubdivideMesh2( srcMesh, info->patchIterations ); - - /* fit it to the curve and remove colinear verts on rows/columns */ - PutMeshOnCurve( *subdivided ); - mesh = RemoveLinearMeshColumnsRows( subdivided ); - FreeMesh( subdivided ); - - /* set verts */ - verts = mesh->verts; - - /* subdivide each quad to place the models */ - for( y = 0; y < (mesh->height - 1); y++ ) - { - for( x = 0; x < (mesh->width - 1); x++ ) - { - /* set indexes */ - pw[ 0 ] = x + (y * mesh->width); - pw[ 1 ] = x + ((y + 1) * mesh->width); - pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); - pw[ 3 ] = x + 1 + (y * mesh->width); - pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ - - /* set radix */ - r = (x + y) & 1; - - /* make first triangle */ - VectorCopy( verts[ pw[ r + 0 ] ].xyz, tw.v[ 0 ].xyz ); - Vector2Copy( verts[ pw[ r + 0 ] ].st, tw.v[ 0 ].st ); - VectorCopy( verts[ pw[ r + 1 ] ].xyz, tw.v[ 1 ].xyz ); - Vector2Copy( verts[ pw[ r + 1 ] ].st, tw.v[ 1 ].st ); - VectorCopy( verts[ pw[ r + 2 ] ].xyz, tw.v[ 2 ].xyz ); - Vector2Copy( verts[ pw[ r + 2 ] ].st, tw.v[ 2 ].st ); - m4x4_transform_point( transform, tw.v[ 0 ].xyz ); - m4x4_transform_point( transform, tw.v[ 1 ].xyz ); - m4x4_transform_point( transform, tw.v[ 2 ].xyz ); - FilterTraceWindingIntoNodes_r( &tw, nodeNum ); - - /* make second triangle */ - VectorCopy( verts[ pw[ r + 0 ] ].xyz, tw.v[ 0 ].xyz ); - Vector2Copy( verts[ pw[ r + 0 ] ].st, tw.v[ 0 ].st ); - VectorCopy( verts[ pw[ r + 2 ] ].xyz, tw.v[ 1 ].xyz ); - Vector2Copy( verts[ pw[ r + 2 ] ].st, tw.v[ 1 ].st ); - VectorCopy( verts[ pw[ r + 3 ] ].xyz, tw.v[ 2 ].xyz ); - Vector2Copy( verts[ pw[ r + 3 ] ].st, tw.v[ 2 ].st ); - m4x4_transform_point( transform, tw.v[ 0 ].xyz ); - m4x4_transform_point( transform, tw.v[ 1 ].xyz ); - m4x4_transform_point( transform, tw.v[ 2 ].xyz ); - FilterTraceWindingIntoNodes_r( &tw, nodeNum ); - } - } - - /* free the subdivided mesh */ - FreeMesh( mesh ); - break; - - /* handle triangle surfaces */ - case MST_TRIANGLE_SOUP: - case MST_PLANAR: - /* set verts and indexes */ - verts = &bspDrawVerts[ ds->firstVert ]; - indexes = &bspDrawIndexes[ ds->firstIndex ]; - - /* walk the triangle list */ - for( j = 0; j < ds->numIndexes; j += 3 ) - { - VectorCopy( verts[ indexes[ j ] ].xyz, tw.v[ 0 ].xyz ); - Vector2Copy( verts[ indexes[ j ] ].st, tw.v[ 0 ].st ); - VectorCopy( verts[ indexes[ j + 1 ] ].xyz, tw.v[ 1 ].xyz ); - Vector2Copy( verts[ indexes[ j + 1 ] ].st, tw.v[ 1 ].st ); - VectorCopy( verts[ indexes[ j + 2 ] ].xyz, tw.v[ 2 ].xyz ); - Vector2Copy( verts[ indexes[ j + 2 ] ].st, tw.v[ 2 ].st ); - m4x4_transform_point( transform, tw.v[ 0 ].xyz ); - m4x4_transform_point( transform, tw.v[ 1 ].xyz ); - m4x4_transform_point( transform, tw.v[ 2 ].xyz ); - FilterTraceWindingIntoNodes_r( &tw, nodeNum ); - } - break; - - /* other surface types do not cast shadows */ - default: - break; - } - } -} - - - -/* -PopulateWithPicoModel() - ydnar -filters a picomodel's surfaces into the raytracing tree -*/ - -static void PopulateWithPicoModel( int castShadows, picoModel_t *model, m4x4_t transform ) -{ - int i, j, k, numSurfaces, numIndexes; - picoSurface_t *surface; - picoShader_t *shader; - picoVec_t *xyz, *st; - picoIndex_t *indexes; - traceInfo_t ti; - traceWinding_t tw; - - - /* dummy check */ - if( model == NULL || transform == NULL ) - return; - - /* get info */ - numSurfaces = PicoGetModelNumSurfaces( model ); - - /* walk the list of surfaces in this model and fill out the info structs */ - for( i = 0; i < numSurfaces; i++ ) - { - /* get surface */ - surface = PicoGetModelSurface( model, i ); - if( surface == NULL ) - continue; - - /* only handle triangle surfaces initially (fixme: support patches) */ - if( PicoGetSurfaceType( surface ) != PICO_TRIANGLES ) - continue; - - /* get shader (fixme: support shader remapping) */ - shader = PicoGetSurfaceShader( surface ); - if( shader == NULL ) - continue; - ti.si = ShaderInfoForShader( PicoGetShaderName( shader ) ); - if( ti.si == NULL ) - continue; - - /* translucent surfaces that are neither alphashadow or lightfilter don't cast shadows */ - if( (ti.si->compileFlags & C_NODRAW) ) - continue; - if( (ti.si->compileFlags & C_TRANSLUCENT) && - !(ti.si->compileFlags & C_ALPHASHADOW) && - !(ti.si->compileFlags & C_LIGHTFILTER) ) - continue; - - /* setup trace info */ - ti.castShadows = castShadows; - ti.surfaceNum = -1; - ti.skipGrid = qtrue; // also ignore picomodels when skipping patches - - /* setup trace winding */ - memset( &tw, 0, sizeof( tw ) ); - tw.infoNum = AddTraceInfo( &ti ); - tw.numVerts = 3; - - /* get info */ - numIndexes = PicoGetSurfaceNumIndexes( surface ); - indexes = PicoGetSurfaceIndexes( surface, 0 ); - - /* walk the triangle list */ - for( j = 0; j < numIndexes; j += 3, indexes += 3 ) - { - for( k = 0; k < 3; k++ ) - { - xyz = PicoGetSurfaceXYZ( surface, indexes[ k ] ); - st = PicoGetSurfaceST( surface, 0, indexes[ k ] ); - VectorCopy( xyz, tw.v[ k ].xyz ); - Vector2Copy( st, tw.v[ k ].st ); - m4x4_transform_point( transform, tw.v[ k ].xyz ); - } - FilterTraceWindingIntoNodes_r( &tw, headNodeNum ); - } - } -} - - - -/* -PopulateTraceNodes() - ydnar -fills the raytracing tree with world and entity occluders -*/ - -static void PopulateTraceNodes( void ) -{ - int i, m, frame, castShadows; - float temp; - entity_t *e; - const char *value; - picoModel_t *model; - vec3_t origin, scale, angles; - m4x4_t transform; - - - /* add worldspawn triangles */ - m4x4_identity( transform ); - PopulateWithBSPModel( &bspModels[ 0 ], transform ); - - /* walk each entity list */ - for( i = 1; i < numEntities; i++ ) - { - /* get entity */ - e = &entities[ i ]; - - /* get shadow flags */ - castShadows = ENTITY_CAST_SHADOWS; - GetEntityShadowFlags( e, NULL, &castShadows, NULL ); - - /* early out? */ - if( !castShadows ) - continue; - - /* get entity origin */ - GetVectorForKey( e, "origin", origin ); - - /* get scale */ - scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = 1.0f; - temp = FloatForKey( e, "modelscale" ); - if( temp != 0.0f ) - scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp; - value = ValueForKey( e, "modelscale_vec" ); - if( value[ 0 ] != '\0' ) - sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] ); - - /* get "angle" (yaw) or "angles" (pitch yaw roll) */ - angles[ 0 ] = angles[ 1 ] = angles[ 2 ] = 0.0f; - angles[ 2 ] = FloatForKey( e, "angle" ); - value = ValueForKey( e, "angles" ); - if( value[ 0 ] != '\0' ) - sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ); - - /* set transform matrix (thanks spog) */ - m4x4_identity( transform ); - m4x4_pivoted_transform_by_vec3( transform, origin, angles, eXYZ, scale, vec3_origin ); - - /* hack: Stable-1_2 and trunk have differing row/column major matrix order - this transpose is necessary with Stable-1_2 - uncomment the following line with old m4x4_t (non 1.3/spog_branch) code */ - //% m4x4_transpose( transform ); - - /* get model */ - value = ValueForKey( e, "model" ); - - /* switch on model type */ - switch( value[ 0 ] ) - { - /* no model */ - case '\0': - break; - - /* bsp model */ - case '*': - m = atoi( &value[ 1 ] ); - if( m <= 0 || m >= numBSPModels ) - continue; - PopulateWithBSPModel( &bspModels[ m ], transform ); - break; - - /* external model */ - default: - frame = IntForKey( e, "_frame" ); - model = LoadModel( value, frame ); - if( model == NULL ) - continue; - PopulateWithPicoModel( castShadows, model, transform ); - continue; - } - - /* get model2 */ - value = ValueForKey( e, "model2" ); - - /* switch on model type */ - switch( value[ 0 ] ) - { - /* no model */ - case '\0': - break; - - /* bsp model */ - case '*': - m = atoi( &value[ 1 ] ); - if( m <= 0 || m >= numBSPModels ) - continue; - PopulateWithBSPModel( &bspModels[ m ], transform ); - break; - - /* external model */ - default: - frame = IntForKey( e, "_frame2" ); - model = LoadModel( value, frame ); - if( model == NULL ) - continue; - PopulateWithPicoModel( castShadows, model, transform ); - continue; - } - } -} - - - - -/* ------------------------------------------------------------------------------- - -trace initialization - -------------------------------------------------------------------------------- */ - -/* -SetupTraceNodes() - ydnar -creates a balanced bsp with axis-aligned splits for efficient raytracing -*/ - -void SetupTraceNodes( void ) -{ - /* note it */ - Sys_FPrintf( SYS_VRB, "--- SetupTraceNodes ---\n" ); - - /* find nodraw bit */ - noDrawContentFlags = noDrawSurfaceFlags = noDrawCompileFlags = 0; - ApplySurfaceParm( "nodraw", &noDrawContentFlags, &noDrawSurfaceFlags, &noDrawCompileFlags ); - - /* create the baseline raytracing tree from the bsp tree */ - headNodeNum = SetupTraceNodes_r( 0 ); - - /* create outside node for skybox surfaces */ - skyboxNodeNum = AllocTraceNode(); - - /* populate the tree with triangles from the world and shadow casting entities */ - PopulateTraceNodes(); - - /* create the raytracing bsp */ - if( loMem == qfalse ) - { - SubdivideTraceNode_r( headNodeNum, 0 ); - SubdivideTraceNode_r( skyboxNodeNum, 0 ); - } - - /* create triangles from the trace windings */ - TriangulateTraceNode_r( headNodeNum ); - TriangulateTraceNode_r( skyboxNodeNum ); - - /* emit some stats */ - //% Sys_FPrintf( SYS_VRB, "%9d original triangles\n", numOriginalTriangles ); - Sys_FPrintf( SYS_VRB, "%9d trace windings (%.2fMB)\n", numTraceWindings, (float) (numTraceWindings * sizeof( *traceWindings )) / (1024.0f * 1024.0f) ); - Sys_FPrintf( SYS_VRB, "%9d trace triangles (%.2fMB)\n", numTraceTriangles, (float) (numTraceTriangles * sizeof( *traceTriangles )) / (1024.0f * 1024.0f) ); - Sys_FPrintf( SYS_VRB, "%9d trace nodes (%.2fMB)\n", numTraceNodes, (float) (numTraceNodes * sizeof( *traceNodes )) / (1024.0f * 1024.0f) ); - Sys_FPrintf( SYS_VRB, "%9d leaf nodes (%.2fMB)\n", numTraceLeafNodes, (float) (numTraceLeafNodes * sizeof( *traceNodes )) / (1024.0f * 1024.0f) ); - //% Sys_FPrintf( SYS_VRB, "%9d average triangles per leaf node\n", numTraceTriangles / numTraceLeafNodes ); - Sys_FPrintf( SYS_VRB, "%9d average windings per leaf node\n", numTraceWindings / (numTraceLeafNodes + 1) ); - Sys_FPrintf( SYS_VRB, "%9d max trace depth\n", maxTraceDepth ); - - /* free trace windings */ - free( traceWindings ); - numTraceWindings = 0; - maxTraceWindings = 0; - deadWinding = -1; - - /* debug code: write out trace triangles to an alias obj file */ - #if 0 - { - int i, j; - FILE *file; - char filename[ 1024 ]; - traceWinding_t *tw; - - - /* open the file */ - strcpy( filename, source ); - StripExtension( filename ); - strcat( filename, ".lin" ); - Sys_Printf( "Opening light trace file %s...\n", filename ); - file = fopen( filename, "w" ); - if( file == NULL ) - Error( "Error opening %s for writing", filename ); - - /* walk node list */ - for( i = 0; i < numTraceWindings; i++ ) - { - tw = &traceWindings[ i ]; - for( j = 0; j < tw->numVerts + 1; j++ ) - fprintf( file, "%f %f %f\n", - tw->v[ j % tw->numVerts ].xyz[ 0 ], tw->v[ j % tw->numVerts ].xyz[ 1 ], tw->v[ j % tw->numVerts ].xyz[ 2 ] ); - } - - /* close it */ - fclose( file ); - } - #endif -} - - - -/* ------------------------------------------------------------------------------- - -raytracer - -------------------------------------------------------------------------------- */ - -/* -TraceTriangle() -based on code written by william 'spog' joseph -based on code originally written by tomas moller and ben trumbore, journal of graphics tools, 2(1):21-28, 1997 -*/ - -#define BARY_EPSILON 0.01f -#define ASLF_EPSILON 0.0001f /* so to not get double shadows */ -#define COPLANAR_EPSILON 0.25f //% 0.000001f -#define NEAR_SHADOW_EPSILON 1.5f //% 1.25f -#define SELF_SHADOW_EPSILON 0.5f - -qboolean TraceTriangle( traceInfo_t *ti, traceTriangle_t *tt, trace_t *trace ) -{ - int i; - float tvec[ 3 ], pvec[ 3 ], qvec[ 3 ]; - float det, invDet, depth; - float u, v, w, s, t; - int is, it; - byte *pixel; - float shadow; - shaderInfo_t *si; - - - /* don't double-trace against sky */ - si = ti->si; - if( trace->compileFlags & si->compileFlags & C_SKY ) - return qfalse; - - /* receive shadows from worldspawn group only */ - if( trace->recvShadows == 1 ) - { - if( ti->castShadows != 1 ) - return qfalse; - } - - /* receive shadows from same group and worldspawn group */ - else if( trace->recvShadows > 1 ) - { - if( ti->castShadows != 1 && abs( ti->castShadows ) != abs( trace->recvShadows ) ) - return qfalse; - //% Sys_Printf( "%d:%d ", tt->castShadows, trace->recvShadows ); - } - - /* receive shadows from the same group only (< 0) */ - else - { - if( abs( ti->castShadows ) != abs( trace->recvShadows ) ) - return qfalse; - } - - /* skip patches when doing the grid (FIXME this is an ugly hack) */ - if( inGrid ) - { - if (ti->skipGrid) - return qfalse; - } - - /* begin calculating determinant - also used to calculate u parameter */ - CrossProduct( trace->direction, tt->edge2, pvec ); - - /* if determinant is near zero, trace lies in plane of triangle */ - det = DotProduct( tt->edge1, pvec ); - - /* the non-culling branch */ - if( fabs( det ) < COPLANAR_EPSILON ) - return qfalse; - invDet = 1.0f / det; - - /* calculate distance from first vertex to ray origin */ - VectorSubtract( trace->origin, tt->v[ 0 ].xyz, tvec ); - - /* calculate u parameter and test bounds */ - u = DotProduct( tvec, pvec ) * invDet; - if( u < -BARY_EPSILON || u > (1.0f + BARY_EPSILON) ) - return qfalse; - - /* prepare to test v parameter */ - CrossProduct( tvec, tt->edge1, qvec ); - - /* calculate v parameter and test bounds */ - v = DotProduct( trace->direction, qvec ) * invDet; - if( v < -BARY_EPSILON || (u + v) > (1.0f + BARY_EPSILON) ) - return qfalse; - - /* calculate t (depth) */ - depth = DotProduct( tt->edge2, qvec ) * invDet; - if( depth <= trace->inhibitRadius || depth >= trace->distance ) - return qfalse; - - /* if hitpoint is really close to trace origin (sample point), then check for self-shadowing */ - if( depth <= SELF_SHADOW_EPSILON ) - { - /* don't self-shadow */ - for( i = 0; i < trace->numSurfaces; i++ ) - { - if( ti->surfaceNum == trace->surfaces[ i ] ) - return qfalse; - } - } - - /* stack compile flags */ - trace->compileFlags |= si->compileFlags; - - /* don't trace against sky */ - if( si->compileFlags & C_SKY ) - return qfalse; - - /* most surfaces are completely opaque */ - if( !(si->compileFlags & (C_ALPHASHADOW | C_LIGHTFILTER)) || - si->lightImage == NULL || si->lightImage->pixels == NULL ) - { - VectorMA( trace->origin, depth, trace->direction, trace->hit ); - VectorClear( trace->color ); - trace->opaque = qtrue; - return qtrue; - } - - /* force subsampling because the lighting is texture dependent */ - trace->forceSubsampling = 1.0; - - /* try to avoid double shadows near triangle seams */ - if( u < -ASLF_EPSILON || u > (1.0f + ASLF_EPSILON) || - v < -ASLF_EPSILON || (u + v) > (1.0f + ASLF_EPSILON) ) - return qfalse; - - /* calculate w parameter */ - w = 1.0f - (u + v); - - /* calculate st from uvw (barycentric) coordinates */ - s = w * tt->v[ 0 ].st[ 0 ] + u * tt->v[ 1 ].st[ 0 ] + v * tt->v[ 2 ].st[ 0 ]; - t = w * tt->v[ 0 ].st[ 1 ] + u * tt->v[ 1 ].st[ 1 ] + v * tt->v[ 2 ].st[ 1 ]; - s = s - floor( s ); - t = t - floor( t ); - is = s * si->lightImage->width; - it = t * si->lightImage->height; - - /* get pixel */ - pixel = si->lightImage->pixels + 4 * (it * si->lightImage->width + is); - - /* ydnar: color filter */ - if( si->compileFlags & C_LIGHTFILTER ) - { - /* filter by texture color */ - trace->color[ 0 ] *= ((1.0f / 255.0f) * pixel[ 0 ]); - trace->color[ 1 ] *= ((1.0f / 255.0f) * pixel[ 1 ]); - trace->color[ 2 ] *= ((1.0f / 255.0f) * pixel[ 2 ]); - } - - /* ydnar: alpha filter */ - if( si->compileFlags & C_ALPHASHADOW ) - { - /* filter by inverse texture alpha */ - shadow = (1.0f / 255.0f) * (255 - pixel[ 3 ]); - trace->color[ 0 ] *= shadow; - trace->color[ 1 ] *= shadow; - trace->color[ 2 ] *= shadow; - } - - /* check filter for opaque */ - if( trace->color[ 0 ] <= 0.001f && trace->color[ 1 ] <= 0.001f && trace->color[ 2 ] <= 0.001f ) - { - VectorClear( trace->color ); - VectorMA( trace->origin, depth, trace->direction, trace->hit ); - trace->opaque = qtrue; - return qtrue; - } - - /* continue tracing */ - return qfalse; -} - - - -/* -TraceWinding() - ydnar -temporary hack -*/ - -qboolean TraceWinding( traceWinding_t *tw, trace_t *trace ) -{ - int i; - traceTriangle_t tt; - - - /* initial setup */ - tt.infoNum = tw->infoNum; - tt.v[ 0 ] = tw->v[ 0 ]; - - /* walk vertex list */ - for( i = 1; i + 1 < tw->numVerts; i++ ) - { - /* set verts */ - tt.v[ 1 ] = tw->v[ i ]; - tt.v[ 2 ] = tw->v[ i + 1 ]; - - /* find vectors for two edges sharing the first vert */ - VectorSubtract( tt.v[ 1 ].xyz, tt.v[ 0 ].xyz, tt.edge1 ); - VectorSubtract( tt.v[ 2 ].xyz, tt.v[ 0 ].xyz, tt.edge2 ); - - /* trace it */ - if( TraceTriangle( &traceInfos[ tt.infoNum ], &tt, trace ) ) - return qtrue; - } - - /* done */ - return qfalse; -} - - - - -/* -TraceLine_r() -returns qtrue if something is hit and tracing can stop -*/ - -static qboolean TraceLine_r( int nodeNum, vec3_t origin, vec3_t end, trace_t *trace ) -{ - traceNode_t *node; - int side; - float front, back, frac; - vec3_t mid; - qboolean r; - - - /* bogus node number means solid, end tracing unless testing all */ - if( nodeNum < 0 ) - { - VectorCopy( origin, trace->hit ); - trace->passSolid = qtrue; - return qtrue; - } - - /* get node */ - node = &traceNodes[ nodeNum ]; - - /* solid? */ - if( node->type == TRACE_LEAF_SOLID ) - { - VectorCopy( origin, trace->hit ); - trace->passSolid = qtrue; - return qtrue; - } - - /* leafnode? */ - if( node->type < 0 ) - { - /* note leaf and return */ - if( node->numItems > 0 && trace->numTestNodes < MAX_TRACE_TEST_NODES ) - trace->testNodes[ trace->numTestNodes++ ] = nodeNum; - return qfalse; - } - - /* ydnar 2003-09-07: don't test branches of the bsp with nothing in them when testall is enabled */ - if( trace->testAll && node->numItems == 0 ) - return qfalse; - - /* classify beginning and end points */ - switch( node->type ) - { - case PLANE_X: - front = origin[ 0 ] - node->plane[ 3 ]; - back = end[ 0 ] - node->plane[ 3 ]; - break; - - case PLANE_Y: - front = origin[ 1 ] - node->plane[ 3 ]; - back = end[ 1 ] - node->plane[ 3 ]; - break; - - case PLANE_Z: - front = origin[ 2 ] - node->plane[ 3 ]; - back = end[ 2 ] - node->plane[ 3 ]; - break; - - default: - front = DotProduct( origin, node->plane ) - node->plane[ 3 ]; - back = DotProduct( end, node->plane ) - node->plane[ 3 ]; - break; - } - - /* entirely in front side? */ - if( front >= -TRACE_ON_EPSILON && back >= -TRACE_ON_EPSILON ) - return TraceLine_r( node->children[ 0 ], origin, end, trace ); - - /* entirely on back side? */ - if( front < TRACE_ON_EPSILON && back < TRACE_ON_EPSILON ) - return TraceLine_r( node->children[ 1 ], origin, end, trace ); - - /* select side */ - side = front < 0; - - /* calculate intercept point */ - frac = front / (front - back); - mid[ 0 ] = origin[ 0 ] + (end[ 0 ] - origin[ 0 ]) * frac; - mid[ 1 ] = origin[ 1 ] + (end[ 1 ] - origin[ 1 ]) * frac; - mid[ 2 ] = origin[ 2 ] + (end[ 2 ] - origin[ 2 ]) * frac; - - /* fixme: check inhibit radius, then solid nodes and ignore */ - - /* set trace hit here */ - //% VectorCopy( mid, trace->hit ); - - /* trace first side */ - r = TraceLine_r( node->children[ side ], origin, mid, trace ); - if( r ) - return r; - - /* trace other side */ - return TraceLine_r( node->children[ !side ], mid, end, trace ); -} - - - -/* -TraceLine() - ydnar -rewrote this function a bit :) -*/ - -void TraceLine( trace_t *trace ) -{ - int i, j; - traceNode_t *node; - traceTriangle_t *tt; - traceInfo_t *ti; - - - /* setup output (note: this code assumes the input data is completely filled out) */ - trace->passSolid = qfalse; - trace->opaque = qfalse; - trace->compileFlags = 0; - trace->numTestNodes = 0; - - /* early outs */ - if( !trace->recvShadows || !trace->testOcclusion || trace->distance <= 0.00001f ) - return; - - /* trace through nodes */ - TraceLine_r( headNodeNum, trace->origin, trace->end, trace ); - if( trace->passSolid && !trace->testAll ) - { - trace->opaque = qtrue; - return; - } - - /* skip surfaces? */ - if( noSurfaces ) - return; - - /* testall means trace through sky */ - if( trace->testAll && trace->numTestNodes < MAX_TRACE_TEST_NODES && - trace->compileFlags & C_SKY && - (trace->numSurfaces == 0 || surfaceInfos[ trace->surfaces[ 0 ] ].childSurfaceNum < 0) ) - { - //% trace->testNodes[ trace->numTestNodes++ ] = skyboxNodeNum; - TraceLine_r( skyboxNodeNum, trace->origin, trace->end, trace ); - } - - /* walk node list */ - for( i = 0; i < trace->numTestNodes; i++ ) - { - /* get node */ - node = &traceNodes[ trace->testNodes[ i ] ]; - - /* walk node item list */ - for( j = 0; j < node->numItems; j++ ) - { - tt = &traceTriangles[ node->items[ j ] ]; - ti = &traceInfos[ tt->infoNum ]; - if( TraceTriangle( ti, tt, trace ) ) - return; - //% if( TraceWinding( &traceWindings[ node->items[ j ] ], trace ) ) - //% return; - } - } -} - - - -/* -SetupTrace() - ydnar -sets up certain trace values -*/ - -float SetupTrace( trace_t *trace ) -{ - VectorSubtract( trace->end, trace->origin, trace->displacement ); - trace->distance = VectorNormalize( trace->displacement, trace->direction ); - VectorCopy( trace->origin, trace->hit ); - return trace->distance; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_ydnar.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_ydnar.c deleted file mode 100644 index f60e6645..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/light_ydnar.c +++ /dev/null @@ -1,4434 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define LIGHT_YDNAR_C - - - -/* dependencies */ -#include "q3map2.h" - - - - -/* -ColorToBytes() -ydnar: moved to here 2001-02-04 -*/ - -void ColorToBytes( const float *color, byte *colorBytes, float scale ) -{ - int i; - float max, gamma; - vec3_t sample; - float inv, dif; - - - /* ydnar: scaling necessary for simulating r_overbrightBits on external lightmaps */ - if( scale <= 0.0f ) - scale = 1.0f; - - /* make a local copy */ - VectorScale( color, scale, sample ); - - /* muck with it */ - gamma = 1.0f / lightmapGamma; - for( i = 0; i < 3; i++ ) - { - /* handle negative light */ - if( sample[ i ] < 0.0f ) - { - sample[ i ] = 0.0f; - continue; - } - - /* gamma */ - sample[ i ] = pow( sample[ i ] / 255.0f, gamma ) * 255.0f; - } - - if (lightmapExposure == 1) - { - /* clamp with color normalization */ - max = sample[ 0 ]; - if( sample[ 1 ] > max ) - max = sample[ 1 ]; - if( sample[ 2 ] > max ) - max = sample[ 2 ]; - if( max > 255.0f ) - VectorScale( sample, (255.0f / max), sample ); - } - else - { - if (lightmapExposure==0) - { - lightmapExposure=1.0f; - } - inv=1.f/lightmapExposure; - //Exposure - - max = sample[ 0 ]; - if( sample[ 1 ] > max ) - max = sample[ 1 ]; - if( sample[ 2 ] > max ) - max = sample[ 2 ]; - - dif = (1- exp(-max * inv) ) * 255; - - if (max >0) - { - dif = dif / max; - } - else - { - dif = 0; - } - - for (i=0;i<3;i++) - { - sample[i]*=dif; - } - } - - - /* compensate for ingame overbrighting/bitshifting */ - VectorScale( sample, (1.0f / lightmapCompensate), sample ); - - /* store it off */ - colorBytes[ 0 ] = sample[ 0 ]; - colorBytes[ 1 ] = sample[ 1 ]; - colorBytes[ 2 ] = sample[ 2 ]; -} - - - -/* ------------------------------------------------------------------------------- - -this section deals with phong shading (normal interpolation across brush faces) - -------------------------------------------------------------------------------- */ - -/* -SmoothNormals() -smooths together coincident vertex normals across the bsp -*/ - -#define MAX_SAMPLES 256 -#define THETA_EPSILON 0.000001 -#define EQUAL_NORMAL_EPSILON 0.01 - -void SmoothNormals( void ) -{ - int i, j, k, f, cs, numVerts, numVotes, fOld, start; - float shadeAngle, defaultShadeAngle, maxShadeAngle, dot, testAngle; - bspDrawSurface_t *ds; - shaderInfo_t *si; - float *shadeAngles; - byte *smoothed; - vec3_t average, diff; - int indexes[ MAX_SAMPLES ]; - vec3_t votes[ MAX_SAMPLES ]; - - - /* allocate shade angle table */ - shadeAngles = safe_malloc( numBSPDrawVerts * sizeof( float ) ); - memset( shadeAngles, 0, numBSPDrawVerts * sizeof( float ) ); - - /* allocate smoothed table */ - cs = (numBSPDrawVerts / 8) + 1; - smoothed = safe_malloc( cs ); - memset( smoothed, 0, cs ); - - /* set default shade angle */ - defaultShadeAngle = DEG2RAD( shadeAngleDegrees ); - maxShadeAngle = 0; - - /* run through every surface and flag verts belonging to non-lightmapped surfaces - and set per-vertex smoothing angle */ - for( i = 0; i < numBSPDrawSurfaces; i++ ) - { - /* get drawsurf */ - ds = &bspDrawSurfaces[ i ]; - - /* get shader for shade angle */ - si = surfaceInfos[ i ].si; - if( si->shadeAngleDegrees ) - shadeAngle = DEG2RAD( si->shadeAngleDegrees ); - else - shadeAngle = defaultShadeAngle; - if( shadeAngle > maxShadeAngle ) - maxShadeAngle = shadeAngle; - - /* flag its verts */ - for( j = 0; j < ds->numVerts; j++ ) - { - f = ds->firstVert + j; - shadeAngles[ f ] = shadeAngle; - if( ds->surfaceType == MST_TRIANGLE_SOUP ) - smoothed[ f >> 3 ] |= (1 << (f & 7)); - } - - /* ydnar: optional force-to-trisoup */ - if( trisoup && ds->surfaceType == MST_PLANAR ) - { - ds->surfaceType = MST_TRIANGLE_SOUP; - ds->lightmapNum[ 0 ] = -3; - } - } - - /* bail if no surfaces have a shade angle */ - if( maxShadeAngle == 0 ) - { - free( shadeAngles ); - free( smoothed ); - return; - } - - /* init pacifier */ - fOld = -1; - start = I_FloatTime(); - - /* go through the list of vertexes */ - for( i = 0; i < numBSPDrawVerts; i++ ) - { - /* print pacifier */ - f = 10 * i / numBSPDrawVerts; - if( f != fOld ) - { - fOld = f; - Sys_Printf( "%i...", f ); - } - - /* already smoothed? */ - if( smoothed[ i >> 3 ] & (1 << (i & 7)) ) - continue; - - /* clear */ - VectorClear( average ); - numVerts = 0; - numVotes = 0; - - /* build a table of coincident vertexes */ - for( j = i; j < numBSPDrawVerts && numVerts < MAX_SAMPLES; j++ ) - { - /* already smoothed? */ - if( smoothed[ j >> 3 ] & (1 << (j & 7)) ) - continue; - - /* test vertexes */ - if( VectorCompare( yDrawVerts[ i ].xyz, yDrawVerts[ j ].xyz ) == qfalse ) - continue; - - /* use smallest shade angle */ - shadeAngle = (shadeAngles[ i ] < shadeAngles[ j ] ? shadeAngles[ i ] : shadeAngles[ j ]); - - /* check shade angle */ - dot = DotProduct( bspDrawVerts[ i ].normal, bspDrawVerts[ j ].normal ); - if( dot > 1.0 ) - dot = 1.0; - else if( dot < -1.0 ) - dot = -1.0; - testAngle = acos( dot ) + THETA_EPSILON; - if( testAngle >= shadeAngle ) - { - //Sys_Printf( "F(%3.3f >= %3.3f) ", RAD2DEG( testAngle ), RAD2DEG( shadeAngle ) ); - continue; - } - //Sys_Printf( "P(%3.3f < %3.3f) ", RAD2DEG( testAngle ), RAD2DEG( shadeAngle ) ); - - /* add to the list */ - indexes[ numVerts++ ] = j; - - /* flag vertex */ - smoothed[ j >> 3 ] |= (1 << (j & 7)); - - /* see if this normal has already been voted */ - for( k = 0; k < numVotes; k++ ) - { - VectorSubtract( bspDrawVerts[ j ].normal, votes[ k ], diff ); - if( fabs( diff[ 0 ] ) < EQUAL_NORMAL_EPSILON && - fabs( diff[ 1 ] ) < EQUAL_NORMAL_EPSILON && - fabs( diff[ 2 ] ) < EQUAL_NORMAL_EPSILON ) - break; - } - - /* add a new vote? */ - if( k == numVotes && numVotes < MAX_SAMPLES ) - { - VectorAdd( average, bspDrawVerts[ j ].normal, average ); - VectorCopy( bspDrawVerts[ j ].normal, votes[ numVotes ] ); - numVotes++; - } - } - - /* don't average for less than 2 verts */ - if( numVerts < 2 ) - continue; - - /* average normal */ - if( VectorNormalize( average, average ) > 0 ) - { - /* smooth */ - for( j = 0; j < numVerts; j++ ) - VectorCopy( average, yDrawVerts[ indexes[ j ] ].normal ); - } - } - - /* free the tables */ - free( shadeAngles ); - free( smoothed ); - - /* print time */ - Sys_Printf( " (%i)\n", (int) (I_FloatTime() - start) ); -} - - - -/* ------------------------------------------------------------------------------- - -this section deals with phong shaded lightmap tracing - -------------------------------------------------------------------------------- */ - -/* 9th rewrite (recursive subdivision of a lightmap triangle) */ - -/* -CalcTangentVectors() -calculates the st tangent vectors for normalmapping -*/ - -static qboolean CalcTangentVectors( int numVerts, bspDrawVert_t **dv, vec3_t *stv, vec3_t *ttv ) -{ - int i; - float bb, s, t; - vec3_t bary; - - - /* calculate barycentric basis for the triangle */ - bb = (dv[ 1 ]->st[ 0 ] - dv[ 0 ]->st[ 0 ]) * (dv[ 2 ]->st[ 1 ] - dv[ 0 ]->st[ 1 ]) - (dv[ 2 ]->st[ 0 ] - dv[ 0 ]->st[ 0 ]) * (dv[ 1 ]->st[ 1 ] - dv[ 0 ]->st[ 1 ]); - if( fabs( bb ) < 0.00000001f ) - return qfalse; - - /* do each vertex */ - for( i = 0; i < numVerts; i++ ) - { - /* calculate s tangent vector */ - s = dv[ i ]->st[ 0 ] + 10.0f; - t = dv[ i ]->st[ 1 ]; - bary[ 0 ] = ((dv[ 1 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t) - (dv[ 2 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t)) / bb; - bary[ 1 ] = ((dv[ 2 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t) - (dv[ 0 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t)) / bb; - bary[ 2 ] = ((dv[ 0 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t) - (dv[ 1 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t)) / bb; - - stv[ i ][ 0 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 0 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 0 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 0 ]; - stv[ i ][ 1 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 1 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 1 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 1 ]; - stv[ i ][ 2 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 2 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 2 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 2 ]; - - VectorSubtract( stv[ i ], dv[ i ]->xyz, stv[ i ] ); - VectorNormalize( stv[ i ], stv[ i ] ); - - /* calculate t tangent vector */ - s = dv[ i ]->st[ 0 ]; - t = dv[ i ]->st[ 1 ] + 10.0f; - bary[ 0 ] = ((dv[ 1 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t) - (dv[ 2 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t)) / bb; - bary[ 1 ] = ((dv[ 2 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t) - (dv[ 0 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t)) / bb; - bary[ 2 ] = ((dv[ 0 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t) - (dv[ 1 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t)) / bb; - - ttv[ i ][ 0 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 0 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 0 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 0 ]; - ttv[ i ][ 1 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 1 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 1 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 1 ]; - ttv[ i ][ 2 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 2 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 2 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 2 ]; - - VectorSubtract( ttv[ i ], dv[ i ]->xyz, ttv[ i ] ); - VectorNormalize( ttv[ i ], ttv[ i ] ); - - /* debug code */ - //% Sys_FPrintf( SYS_VRB, "%d S: (%f %f %f) T: (%f %f %f)\n", i, - //% stv[ i ][ 0 ], stv[ i ][ 1 ], stv[ i ][ 2 ], ttv[ i ][ 0 ], ttv[ i ][ 1 ], ttv[ i ][ 2 ] ); - } - - /* return to caller */ - return qtrue; -} - - - - -/* -PerturbNormal() -perterbs the normal by the shader's normalmap in tangent space -*/ - -static void PerturbNormal( bspDrawVert_t *dv, shaderInfo_t *si, vec3_t pNormal, vec3_t stv[ 3 ], vec3_t ttv[ 3 ] ) -{ - int i; - vec4_t bump; - - - /* passthrough */ - VectorCopy( dv->normal, pNormal ); - - /* sample normalmap */ - if( RadSampleImage( si->normalImage->pixels, si->normalImage->width, si->normalImage->height, dv->st, bump ) == qfalse ) - return; - - /* remap sampled normal from [0,255] to [-1,-1] */ - for( i = 0; i < 3; i++ ) - bump[ i ] = (bump[ i ] - 127.0f) * (1.0f / 127.5f); - - /* scale tangent vectors and add to original normal */ - VectorMA( dv->normal, bump[ 0 ], stv[ 0 ], pNormal ); - VectorMA( pNormal, bump[ 1 ], ttv[ 0 ], pNormal ); - VectorMA( pNormal, bump[ 2 ], dv->normal, pNormal ); - - /* renormalize and return */ - VectorNormalize( pNormal, pNormal ); -} - - - -/* -MapSingleLuxel() -maps a luxel for triangle bv at -*/ - -#define NUDGE 0.5f -#define BOGUS_NUDGE -99999.0f - -static int MapSingleLuxel( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv, vec4_t plane, float pass, vec3_t stv[ 3 ], vec3_t ttv[ 3 ], vec3_t worldverts[ 3 ] ) -{ - int i, x, y, numClusters, *clusters, pointCluster, *cluster; - float *luxel, *origin, *normal, d, lightmapSampleOffset; - shaderInfo_t *si; - vec3_t pNormal; - vec3_t vecs[ 3 ]; - vec3_t nudged; - vec3_t cverts[ 3 ]; - vec3_t temp; - vec4_t sideplane, hostplane; - vec3_t origintwo; - int j, next; - float e; - float *nudge; - static float nudges[][ 2 ] = - { - //%{ 0, 0 }, /* try center first */ - { -NUDGE, 0 }, /* left */ - { NUDGE, 0 }, /* right */ - { 0, NUDGE }, /* up */ - { 0, -NUDGE }, /* down */ - { -NUDGE, NUDGE }, /* left/up */ - { NUDGE, -NUDGE }, /* right/down */ - { NUDGE, NUDGE }, /* right/up */ - { -NUDGE, -NUDGE }, /* left/down */ - { BOGUS_NUDGE, BOGUS_NUDGE } - }; - - - /* find luxel xy coords (fixme: subtract 0.5?) */ - x = dv->lightmap[ 0 ][ 0 ]; - y = dv->lightmap[ 0 ][ 1 ]; - if( x < 0 ) - x = 0; - else if( x >= lm->sw ) - x = lm->sw - 1; - if( y < 0 ) - y = 0; - else if( y >= lm->sh ) - y = lm->sh - 1; - - /* set shader and cluster list */ - if( info != NULL ) - { - si = info->si; - numClusters = info->numSurfaceClusters; - clusters = &surfaceClusters[ info->firstSurfaceCluster ]; - } - else - { - si = NULL; - numClusters = 0; - clusters = NULL; - } - - /* get luxel, origin, cluster, and normal */ - luxel = SUPER_LUXEL( 0, x, y ); - origin = SUPER_ORIGIN( x, y ); - normal = SUPER_NORMAL( x, y ); - cluster = SUPER_CLUSTER( x, y ); - - /* don't attempt to remap occluded luxels for planar surfaces */ - if( (*cluster) == CLUSTER_OCCLUDED && lm->plane != NULL ) - return (*cluster); - - /* only average the normal for premapped luxels */ - else if( (*cluster) >= 0 ) - { - /* do bumpmap calculations */ - if( stv != NULL ) - PerturbNormal( dv, si, pNormal, stv, ttv ); - else - VectorCopy( dv->normal, pNormal ); - - /* add the additional normal data */ - VectorAdd( normal, pNormal, normal ); - luxel[ 3 ] += 1.0f; - return (*cluster); - } - - /* otherwise, unmapped luxels (*cluster == CLUSTER_UNMAPPED) will have their full attributes calculated */ - - /* get origin */ - - /* axial lightmap projection */ - if( lm->vecs != NULL ) - { - /* calculate an origin for the sample from the lightmap vectors */ - VectorCopy( lm->origin, origin ); - for( i = 0; i < 3; i++ ) - { - /* add unless it's the axis, which is taken care of later */ - if( i == lm->axisNum ) - continue; - origin[ i ] += (x * lm->vecs[ 0 ][ i ]) + (y * lm->vecs[ 1 ][ i ]); - } - - /* project the origin onto the plane */ - d = DotProduct( origin, plane ) - plane[ 3 ]; - d /= plane[ lm->axisNum ]; - origin[ lm->axisNum ] -= d; - } - - /* non axial lightmap projection (explicit xyz) */ - else - VectorCopy( dv->xyz, origin ); - - ////////////////////// - //27's test to make sure samples stay within the triangle boundaries - //1) Test the sample origin to see if it lays on the wrong side of any edge (x/y) - //2) if it does, nudge it onto the correct side. - - if (worldverts!=NULL && lightmapTriangleCheck) - { - for (j=0;j<3;j++) - { - VectorCopy(worldverts[j],cverts[j]); - } - PlaneFromPoints(hostplane,cverts[0],cverts[1],cverts[2]); - - for (j=0;j<3;j++) - { - for (i=0;i<3;i++) - { - //build plane using 2 edges and a normal - next=(i+1)%3; - - VectorCopy(cverts[next],temp); - VectorAdd(temp,hostplane,temp); - PlaneFromPoints(sideplane,cverts[i],cverts[ next ], temp); - - //planetest sample point - e=DotProduct(origin,sideplane); - e=e-sideplane[3]; - if (e>0) - { - //we're bad. - //VectorClear(origin); - //Move the sample point back inside triangle bounds - origin[0]-=sideplane[0]*(e+1); - origin[1]-=sideplane[1]*(e+1); - origin[2]-=sideplane[2]*(e+1); -#ifdef DEBUG_27_1 - VectorClear(origin); -#endif - } - } - } - } - - //////////////////////// - - /* planar surfaces have precalculated lightmap vectors for nudging */ - if( lm->plane != NULL ) - { - VectorCopy( lm->vecs[ 0 ], vecs[ 0 ] ); - VectorCopy( lm->vecs[ 1 ], vecs[ 1 ] ); - VectorCopy( lm->plane, vecs[ 2 ] ); - } - - /* non-planar surfaces must calculate them */ - else - { - if( plane != NULL ) - VectorCopy( plane, vecs[ 2 ] ); - else - VectorCopy( dv->normal, vecs[ 2 ] ); - MakeNormalVectors( vecs[ 2 ], vecs[ 0 ], vecs[ 1 ] ); - } - - /* push the origin off the surface a bit */ - if( si != NULL ) - lightmapSampleOffset = si->lightmapSampleOffset; - else - lightmapSampleOffset = DEFAULT_LIGHTMAP_SAMPLE_OFFSET; - if( lm->axisNum < 0 ) - VectorMA( origin, lightmapSampleOffset, vecs[ 2 ], origin ); - else if( vecs[ 2 ][ lm->axisNum ] < 0.0f ) - origin[ lm->axisNum ] -= lightmapSampleOffset; - else - origin[ lm->axisNum ] += lightmapSampleOffset; - - VectorCopy(origin,origintwo); - if(lightmapExtraVisClusterNudge) - { - origintwo[0]+=vecs[2][0]; - origintwo[1]+=vecs[2][1]; - origintwo[2]+=vecs[2][2]; - } - - /* get cluster */ - pointCluster = ClusterForPointExtFilter( origintwo, LUXEL_EPSILON, numClusters, clusters ); - - /* another retarded hack, storing nudge count in luxel[ 1 ] */ - luxel[ 1 ] = 0.0f; - - /* point in solid? (except in dark mode) */ - if( pointCluster < 0 && dark == qfalse ) - { - /* nudge the the location around */ - nudge = nudges[ 0 ]; - while( nudge[ 0 ] > BOGUS_NUDGE && pointCluster < 0 ) - { - /* nudge the vector around a bit */ - for( i = 0; i < 3; i++ ) - { - /* set nudged point*/ - nudged[ i ] = origintwo[ i ] + (nudge[ 0 ] * vecs[ 0 ][ i ]) + (nudge[ 1 ] * vecs[ 1 ][ i ]); - } - nudge += 2; - - /* get pvs cluster */ - pointCluster = ClusterForPointExtFilter( nudged, LUXEL_EPSILON, numClusters, clusters ); //% + 0.625 ); - if( pointCluster >= 0 ) - VectorCopy( nudged, origin ); - luxel[ 1 ] += 1.0f; - } - } - - /* as a last resort, if still in solid, try drawvert origin offset by normal (except in dark mode) */ - if( pointCluster < 0 && si != NULL && dark == qfalse ) - { - VectorMA( dv->xyz, lightmapSampleOffset, dv->normal, nudged ); - pointCluster = ClusterForPointExtFilter( nudged, LUXEL_EPSILON, numClusters, clusters ); - if( pointCluster >= 0 ) - VectorCopy( nudged, origin ); - luxel[ 1 ] += 1.0f; - } - - /* valid? */ - if( pointCluster < 0 ) - { - (*cluster) = CLUSTER_OCCLUDED; - VectorClear( origin ); - VectorClear( normal ); - numLuxelsOccluded++; - return (*cluster); - } - - /* debug code */ - //% Sys_Printf( "%f %f %f\n", origin[ 0 ], origin[ 1 ], origin[ 2 ] ); - - /* do bumpmap calculations */ - if( stv ) - PerturbNormal( dv, si, pNormal, stv, ttv ); - else - VectorCopy( dv->normal, pNormal ); - - /* store the cluster and normal */ - (*cluster) = pointCluster; - VectorCopy( pNormal, normal ); - - /* store explicit mapping pass and implicit mapping pass */ - luxel[ 0 ] = pass; - luxel[ 3 ] = 1.0f; - - /* add to count */ - numLuxelsMapped++; - - /* return ok */ - return (*cluster); -} - - - -/* -MapTriangle_r() -recursively subdivides a triangle until its edges are shorter -than the distance between two luxels (thanks jc :) -*/ - -static void MapTriangle_r( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 3 ], vec4_t plane, vec3_t stv[ 3 ], vec3_t ttv[ 3 ], vec3_t worldverts[ 3 ] ) -{ - bspDrawVert_t mid, *dv2[ 3 ]; - int max; - - - /* map the vertexes */ - #if 0 - MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv ); - MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv ); - MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv ); - #endif - - /* subdivide calc */ - { - int i; - float *a, *b, dx, dy, dist, maxDist; - - - /* find the longest edge and split it */ - max = -1; - maxDist = 0; - for( i = 0; i < 3; i++ ) - { - /* get verts */ - a = dv[ i ]->lightmap[ 0 ]; - b = dv[ (i + 1) % 3 ]->lightmap[ 0 ]; - - /* get dists */ - dx = a[ 0 ] - b[ 0 ]; - dy = a[ 1 ] - b[ 1 ]; - dist = (dx * dx) + (dy * dy); //% sqrt( (dx * dx) + (dy * dy) ); - - /* longer? */ - if( dist > maxDist ) - { - maxDist = dist; - max = i; - } - } - - /* try to early out */ - if( max < 0 || maxDist <= subdivideThreshold ) /* ydnar: was i < 0 instead of max < 0 (?) */ - return; - } - - /* split the longest edge and map it */ - LerpDrawVert( dv[ max ], dv[ (max + 1) % 3 ], &mid ); - MapSingleLuxel( lm, info, &mid, plane, 1, stv, ttv, worldverts ); - - /* push the point up a little bit to account for fp creep (fixme: revisit this) */ - //% VectorMA( mid.xyz, 2.0f, mid.normal, mid.xyz ); - - /* recurse to first triangle */ - VectorCopy( dv, dv2 ); - dv2[ max ] = ∣ - MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts ); - - /* recurse to second triangle */ - VectorCopy( dv, dv2 ); - dv2[ (max + 1) % 3 ] = ∣ - MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts ); -} - - - -/* -MapTriangle() -seed function for MapTriangle_r() -requires a cw ordered triangle -*/ - -static qboolean MapTriangle( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 3 ], qboolean mapNonAxial ) -{ - int i; - vec4_t plane; - vec3_t *stv, *ttv, stvStatic[ 3 ], ttvStatic[ 3 ]; - vec3_t worldverts[ 3 ]; - - - /* get plane if possible */ - if( lm->plane != NULL ) - { - VectorCopy( lm->plane, plane ); - plane[ 3 ] = lm->plane[ 3 ]; - } - - /* otherwise make one from the points */ - else if( PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) == qfalse ) - return qfalse; - - /* check to see if we need to calculate texture->world tangent vectors */ - if( info->si->normalImage != NULL && CalcTangentVectors( 3, dv, stvStatic, ttvStatic ) ) - { - stv = stvStatic; - ttv = ttvStatic; - } - else - { - stv = NULL; - ttv = NULL; - } - - VectorCopy( dv[ 0 ]->xyz, worldverts[ 0 ] ); - VectorCopy( dv[ 1 ]->xyz, worldverts[ 1 ] ); - VectorCopy( dv[ 2 ]->xyz, worldverts[ 2 ] ); - - /* map the vertexes */ - MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv, worldverts ); - MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv, worldverts ); - MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv, worldverts ); - - /* 2002-11-20: prefer axial triangle edges */ - if( mapNonAxial ) - { - /* subdivide the triangle */ - MapTriangle_r( lm, info, dv, plane, stv, ttv, worldverts ); - return qtrue; - } - - for( i = 0; i < 3; i++ ) - { - float *a, *b; - bspDrawVert_t *dv2[ 3 ]; - - - /* get verts */ - a = dv[ i ]->lightmap[ 0 ]; - b = dv[ (i + 1) % 3 ]->lightmap[ 0 ]; - - /* make degenerate triangles for mapping edges */ - if( fabs( a[ 0 ] - b[ 0 ] ) < 0.01f || fabs( a[ 1 ] - b[ 1 ] ) < 0.01f ) - { - dv2[ 0 ] = dv[ i ]; - dv2[ 1 ] = dv[ (i + 1) % 3 ]; - dv2[ 2 ] = dv[ (i + 1) % 3 ]; - - /* map the degenerate triangle */ - MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts ); - } - } - - return qtrue; -} - - - -/* -MapQuad_r() -recursively subdivides a quad until its edges are shorter -than the distance between two luxels -*/ - -static void MapQuad_r( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 4 ], vec4_t plane, vec3_t stv[ 4 ], vec3_t ttv[ 4 ] ) -{ - bspDrawVert_t mid[ 2 ], *dv2[ 4 ]; - int max; - - - /* subdivide calc */ - { - int i; - float *a, *b, dx, dy, dist, maxDist; - - - /* find the longest edge and split it */ - max = -1; - maxDist = 0; - for( i = 0; i < 4; i++ ) - { - /* get verts */ - a = dv[ i ]->lightmap[ 0 ]; - b = dv[ (i + 1) % 4 ]->lightmap[ 0 ]; - - /* get dists */ - dx = a[ 0 ] - b[ 0 ]; - dy = a[ 1 ] - b[ 1 ]; - dist = (dx * dx) + (dy * dy); //% sqrt( (dx * dx) + (dy * dy) ); - - /* longer? */ - if( dist > maxDist ) - { - maxDist = dist; - max = i; - } - } - - /* try to early out */ - if( max < 0 || maxDist <= subdivideThreshold ) - return; - } - - /* we only care about even/odd edges */ - max &= 1; - - /* split the longest edges */ - LerpDrawVert( dv[ max ], dv[ (max + 1) % 4 ], &mid[ 0 ] ); - LerpDrawVert( dv[ max + 2 ], dv[ (max + 3) % 4 ], &mid[ 1 ] ); - - /* map the vertexes */ - MapSingleLuxel( lm, info, &mid[ 0 ], plane, 1, stv, ttv, NULL ); - MapSingleLuxel( lm, info, &mid[ 1 ], plane, 1, stv, ttv, NULL ); - - /* 0 and 2 */ - if( max == 0 ) - { - /* recurse to first quad */ - dv2[ 0 ] = dv[ 0 ]; - dv2[ 1 ] = &mid[ 0 ]; - dv2[ 2 ] = &mid[ 1 ]; - dv2[ 3 ] = dv[ 3 ]; - MapQuad_r( lm, info, dv2, plane, stv, ttv ); - - /* recurse to second quad */ - dv2[ 0 ] = &mid[ 0 ]; - dv2[ 1 ] = dv[ 1 ]; - dv2[ 2 ] = dv[ 2 ]; - dv2[ 3 ] = &mid[ 1 ]; - MapQuad_r( lm, info, dv2, plane, stv, ttv ); - } - - /* 1 and 3 */ - else - { - /* recurse to first quad */ - dv2[ 0 ] = dv[ 0 ]; - dv2[ 1 ] = dv[ 1 ]; - dv2[ 2 ] = &mid[ 0 ]; - dv2[ 3 ] = &mid[ 1 ]; - MapQuad_r( lm, info, dv2, plane, stv, ttv ); - - /* recurse to second quad */ - dv2[ 0 ] = &mid[ 1 ]; - dv2[ 1 ] = &mid[ 0 ]; - dv2[ 2 ] = dv[ 2 ]; - dv2[ 3 ] = dv[ 3 ]; - MapQuad_r( lm, info, dv2, plane, stv, ttv ); - } -} - - - -/* -MapQuad() -seed function for MapQuad_r() -requires a cw ordered triangle quad -*/ - -#define QUAD_PLANAR_EPSILON 0.5f - -static qboolean MapQuad( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 4 ] ) -{ - float dist; - vec4_t plane; - vec3_t *stv, *ttv, stvStatic[ 4 ], ttvStatic[ 4 ]; - - - /* get plane if possible */ - if( lm->plane != NULL ) - { - VectorCopy( lm->plane, plane ); - plane[ 3 ] = lm->plane[ 3 ]; - } - - /* otherwise make one from the points */ - else if( PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) == qfalse ) - return qfalse; - - /* 4th point must fall on the plane */ - dist = DotProduct( plane, dv[ 3 ]->xyz ) - plane[ 3 ]; - if( fabs( dist ) > QUAD_PLANAR_EPSILON ) - return qfalse; - - /* check to see if we need to calculate texture->world tangent vectors */ - if( info->si->normalImage != NULL && CalcTangentVectors( 4, dv, stvStatic, ttvStatic ) ) - { - stv = stvStatic; - ttv = ttvStatic; - } - else - { - stv = NULL; - ttv = NULL; - } - - /* map the vertexes */ - MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv, NULL ); - MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv, NULL ); - MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv, NULL ); - MapSingleLuxel( lm, info, dv[ 3 ], plane, 1, stv, ttv, NULL ); - - /* subdivide the quad */ - MapQuad_r( lm, info, dv, plane, stv, ttv ); - return qtrue; -} - - - -/* -MapRawLightmap() -maps the locations, normals, and pvs clusters for a raw lightmap -*/ - -#define VectorDivide( in, d, out ) VectorScale( in, (1.0f / (d)), out ) //% (out)[ 0 ] = (in)[ 0 ] / (d), (out)[ 1 ] = (in)[ 1 ] / (d), (out)[ 2 ] = (in)[ 2 ] / (d) - -void MapRawLightmap( int rawLightmapNum ) -{ - int n, num, i, x, y, sx, sy, pw[ 5 ], r, *cluster, mapNonAxial; - float *luxel, *origin, *normal, samples, radius, pass; - rawLightmap_t *lm; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - mesh_t src, *subdivided, *mesh; - bspDrawVert_t *verts, *dv[ 4 ], fake; - - - /* bail if this number exceeds the number of raw lightmaps */ - if( rawLightmapNum >= numRawLightmaps ) - return; - - /* get lightmap */ - lm = &rawLightmaps[ rawLightmapNum ]; - - /* ----------------------------------------------------------------- - map referenced surfaces onto the raw lightmap - ----------------------------------------------------------------- */ - - /* walk the list of surfaces on this raw lightmap */ - for( n = 0; n < lm->numLightSurfaces; n++ ) - { - /* with > 1 surface per raw lightmap, clear occluded */ - if( n > 0 ) - { - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - if( *cluster < 0 ) - *cluster = CLUSTER_UNMAPPED; - } - } - } - - /* get surface */ - num = lightSurfaces[ lm->firstLightSurface + n ]; - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* bail if no lightmap to calculate */ - if( info->lm != lm ) - { - Sys_Printf( "!" ); - continue; - } - - /* map the surface onto the lightmap origin/cluster/normal buffers */ - switch( ds->surfaceType ) - { - case MST_PLANAR: - /* get verts */ - verts = yDrawVerts + ds->firstVert; - - /* map the triangles */ - for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ ) - { - for( i = 0; i < ds->numIndexes; i += 3 ) - { - dv[ 0 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i ] ]; - dv[ 1 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 1 ] ]; - dv[ 2 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 2 ] ]; - MapTriangle( lm, info, dv, mapNonAxial ); - } - } - break; - - case MST_PATCH: - /* make a mesh from the drawsurf */ - src.width = ds->patchWidth; - src.height = ds->patchHeight; - src.verts = &yDrawVerts[ ds->firstVert ]; - //% subdivided = SubdivideMesh( src, 8, 512 ); - subdivided = SubdivideMesh2( src, info->patchIterations ); - - /* fit it to the curve and remove colinear verts on rows/columns */ - PutMeshOnCurve( *subdivided ); - mesh = RemoveLinearMeshColumnsRows( subdivided ); - FreeMesh( subdivided ); - - /* get verts */ - verts = mesh->verts; - - /* debug code */ - #if 0 - if( lm->plane ) - { - Sys_Printf( "Planar patch: [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f]\n", - lm->plane[ 0 ], lm->plane[ 1 ], lm->plane[ 2 ], - lm->vecs[ 0 ][ 0 ], lm->vecs[ 0 ][ 1 ], lm->vecs[ 0 ][ 2 ], - lm->vecs[ 1 ][ 0 ], lm->vecs[ 1 ][ 1 ], lm->vecs[ 1 ][ 2 ] ); - } - #endif - - /* map the mesh quads */ - #if 0 - - for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ ) - { - for( y = 0; y < (mesh->height - 1); y++ ) - { - for( x = 0; x < (mesh->width - 1); x++ ) - { - /* set indexes */ - pw[ 0 ] = x + (y * mesh->width); - pw[ 1 ] = x + ((y + 1) * mesh->width); - pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); - pw[ 3 ] = x + 1 + (y * mesh->width); - pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ - - /* set radix */ - r = (x + y) & 1; - - /* get drawverts and map first triangle */ - dv[ 0 ] = &verts[ pw[ r + 0 ] ]; - dv[ 1 ] = &verts[ pw[ r + 1 ] ]; - dv[ 2 ] = &verts[ pw[ r + 2 ] ]; - MapTriangle( lm, info, dv, mapNonAxial ); - - /* get drawverts and map second triangle */ - dv[ 0 ] = &verts[ pw[ r + 0 ] ]; - dv[ 1 ] = &verts[ pw[ r + 2 ] ]; - dv[ 2 ] = &verts[ pw[ r + 3 ] ]; - MapTriangle( lm, info, dv, mapNonAxial ); - } - } - } - - #else - - for( y = 0; y < (mesh->height - 1); y++ ) - { - for( x = 0; x < (mesh->width - 1); x++ ) - { - /* set indexes */ - pw[ 0 ] = x + (y * mesh->width); - pw[ 1 ] = x + ((y + 1) * mesh->width); - pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); - pw[ 3 ] = x + 1 + (y * mesh->width); - pw[ 4 ] = pw[ 0 ]; - - /* set radix */ - r = (x + y) & 1; - - /* attempt to map quad first */ - dv[ 0 ] = &verts[ pw[ r + 0 ] ]; - dv[ 1 ] = &verts[ pw[ r + 1 ] ]; - dv[ 2 ] = &verts[ pw[ r + 2 ] ]; - dv[ 3 ] = &verts[ pw[ r + 3 ] ]; - if( MapQuad( lm, info, dv ) ) - continue; - - for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ ) - { - /* get drawverts and map first triangle */ - dv[ 1 ] = &verts[ pw[ r + 1 ] ]; - dv[ 2 ] = &verts[ pw[ r + 2 ] ]; - MapTriangle( lm, info, dv, mapNonAxial ); - - /* get drawverts and map second triangle */ - dv[ 1 ] = &verts[ pw[ r + 2 ] ]; - dv[ 2 ] = &verts[ pw[ r + 3 ] ]; - MapTriangle( lm, info, dv, mapNonAxial ); - } - } - } - - #endif - - /* free the mesh */ - FreeMesh( mesh ); - break; - - default: - break; - } - } - - /* ----------------------------------------------------------------- - average and clean up luxel normals - ----------------------------------------------------------------- */ - - /* walk the luxels */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - luxel = SUPER_LUXEL( 0, x, y ); - normal = SUPER_NORMAL( x, y ); - cluster = SUPER_CLUSTER( x, y ); - - /* only look at mapped luxels */ - if( *cluster < 0 ) - continue; - - /* the normal data could be the sum of multiple samples */ - if( luxel[ 3 ] > 1.0f ) - VectorNormalize( normal, normal ); - - /* mark this luxel as having only one normal */ - luxel[ 3 ] = 1.0f; - } - } - - /* non-planar surfaces stop here */ - if( lm->plane == NULL ) - return; - - /* ----------------------------------------------------------------- - map occluded or unuxed luxels - ----------------------------------------------------------------- */ - - /* walk the luxels */ - radius = floor( superSample / 2 ); - radius = radius > 0 ? radius : 1.0f; - radius += 1.0f; - for( pass = 2.0f; pass <= radius; pass += 1.0f ) - { - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - luxel = SUPER_LUXEL( 0, x, y ); - normal = SUPER_NORMAL( x, y ); - cluster = SUPER_CLUSTER( x, y ); - - /* only look at unmapped luxels */ - if( *cluster != CLUSTER_UNMAPPED ) - continue; - - /* divine a normal and origin from neighboring luxels */ - VectorClear( fake.xyz ); - VectorClear( fake.normal ); - fake.lightmap[ 0 ][ 0 ] = x; //% 0.0001 + x; - fake.lightmap[ 0 ][ 1 ] = y; //% 0.0001 + y; - samples = 0.0f; - for( sy = (y - 1); sy <= (y + 1); sy++ ) - { - if( sy < 0 || sy >= lm->sh ) - continue; - - for( sx = (x - 1); sx <= (x + 1); sx++ ) - { - if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) - continue; - - /* get neighboring luxel */ - luxel = SUPER_LUXEL( 0, sx, sy ); - origin = SUPER_ORIGIN( sx, sy ); - normal = SUPER_NORMAL( sx, sy ); - cluster = SUPER_CLUSTER( sx, sy ); - - /* only consider luxels mapped in previous passes */ - if( *cluster < 0 || luxel[ 0 ] >= pass ) - continue; - - /* add its distinctiveness to our own */ - VectorAdd( fake.xyz, origin, fake.xyz ); - VectorAdd( fake.normal, normal, fake.normal ); - samples += luxel[ 3 ]; - } - } - - /* any samples? */ - if( samples == 0.0f ) - continue; - - /* average */ - VectorDivide( fake.xyz, samples, fake.xyz ); - //% VectorDivide( fake.normal, samples, fake.normal ); - if( VectorNormalize( fake.normal, fake.normal ) == 0.0f ) - continue; - - /* map the fake vert */ - MapSingleLuxel( lm, NULL, &fake, lm->plane, pass, NULL, NULL, NULL ); - } - } - } - - /* ----------------------------------------------------------------- - average and clean up luxel normals - ----------------------------------------------------------------- */ - - /* walk the luxels */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - luxel = SUPER_LUXEL( 0, x, y ); - normal = SUPER_NORMAL( x, y ); - cluster = SUPER_CLUSTER( x, y ); - - /* only look at mapped luxels */ - if( *cluster < 0 ) - continue; - - /* the normal data could be the sum of multiple samples */ - if( luxel[ 3 ] > 1.0f ) - VectorNormalize( normal, normal ); - - /* mark this luxel as having only one normal */ - luxel[ 3 ] = 1.0f; - } - } - - /* debug code */ - #if 0 - Sys_Printf( "\n" ); - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - vec3_t mins, maxs; - - - cluster = SUPER_CLUSTER( x, y ); - origin = SUPER_ORIGIN( x, y ); - normal = SUPER_NORMAL( x, y ); - luxel = SUPER_LUXEL( x, y ); - - if( *cluster < 0 ) - continue; - - /* check if within the bounding boxes of all surfaces referenced */ - ClearBounds( mins, maxs ); - for( n = 0; n < lm->numLightSurfaces; n++ ) - { - int TOL; - info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + n ] ]; - TOL = info->sampleSize + 2; - AddPointToBounds( info->mins, mins, maxs ); - AddPointToBounds( info->maxs, mins, maxs ); - if( origin[ 0 ] > (info->mins[ 0 ] - TOL) && origin[ 0 ] < (info->maxs[ 0 ] + TOL) && - origin[ 1 ] > (info->mins[ 1 ] - TOL) && origin[ 1 ] < (info->maxs[ 1 ] + TOL) && - origin[ 2 ] > (info->mins[ 2 ] - TOL) && origin[ 2 ] < (info->maxs[ 2 ] + TOL) ) - break; - } - - /* inside? */ - if( n < lm->numLightSurfaces ) - continue; - - /* report bogus origin */ - Sys_Printf( "%6d [%2d,%2d] (%4d): XYZ(%+4.1f %+4.1f %+4.1f) LO(%+4.1f %+4.1f %+4.1f) HI(%+4.1f %+4.1f %+4.1f) <%3.0f>\n", - rawLightmapNum, x, y, *cluster, - origin[ 0 ], origin[ 1 ], origin[ 2 ], - mins[ 0 ], mins[ 1 ], mins[ 2 ], - maxs[ 0 ], maxs[ 1 ], maxs[ 2 ], - luxel[ 3 ] ); - } - } - #endif -} - - - -/* -SetupDirt() -sets up dirtmap (ambient occlusion) -*/ - -#define DIRT_CONE_ANGLE 88 /* degrees */ -#define DIRT_NUM_ANGLE_STEPS 16 -#define DIRT_NUM_ELEVATION_STEPS 3 -#define DIRT_NUM_VECTORS (DIRT_NUM_ANGLE_STEPS * DIRT_NUM_ELEVATION_STEPS) - -static vec3_t dirtVectors[ DIRT_NUM_VECTORS ]; -static int numDirtVectors = 0; - -void SetupDirt( void ) -{ - int i, j; - float angle, elevation, angleStep, elevationStep; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- SetupDirt ---\n" ); - - /* calculate angular steps */ - angleStep = DEG2RAD( 360.0f / DIRT_NUM_ANGLE_STEPS ); - elevationStep = DEG2RAD( DIRT_CONE_ANGLE / DIRT_NUM_ELEVATION_STEPS ); - - /* iterate angle */ - angle = 0.0f; - for( i = 0, angle = 0.0f; i < DIRT_NUM_ANGLE_STEPS; i++, angle += angleStep ) - { - /* iterate elevation */ - for( j = 0, elevation = elevationStep * 0.5f; j < DIRT_NUM_ELEVATION_STEPS; j++, elevation += elevationStep ) - { - dirtVectors[ numDirtVectors ][ 0 ] = sin( elevation ) * cos( angle ); - dirtVectors[ numDirtVectors ][ 1 ] = sin( elevation ) * sin( angle ); - dirtVectors[ numDirtVectors ][ 2 ] = cos( elevation ); - numDirtVectors++; - } - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d dirtmap vectors\n", numDirtVectors ); -} - - -/* -DirtForSample() -calculates dirt value for a given sample -*/ - -float DirtForSample( trace_t *trace ) -{ - int i; - float gatherDirt, outDirt, angle, elevation, ooDepth; - vec3_t normal, worldUp, myUp, myRt, temp, direction, displacement; - - - /* dummy check */ - if( !dirty ) - return 1.0f; - if( trace == NULL || trace->cluster < 0 ) - return 0.0f; - - /* setup */ - gatherDirt = 0.0f; - ooDepth = 1.0f / dirtDepth; - VectorCopy( trace->normal, normal ); - - /* check if the normal is aligned to the world-up */ - if( normal[ 0 ] == 0.0f && normal[ 1 ] == 0.0f && ( normal[ 2 ] == 1.0f || normal[ 2 ] == -1.0f ) ) - { - if( normal[ 2 ] == 1.0f ) - { - VectorSet( myRt, 1.0f, 0.0f, 0.0f ); - VectorSet( myUp, 0.0f, 1.0f, 0.0f ); - } - else if( normal[ 2 ] == -1.0f ) - { - VectorSet( myRt, -1.0f, 0.0f, 0.0f ); - VectorSet( myUp, 0.0f, 1.0f, 0.0f ); - } - } - else - { - VectorSet( worldUp, 0.0f, 0.0f, 1.0f ); - CrossProduct( normal, worldUp, myRt ); - VectorNormalize( myRt, myRt ); - CrossProduct( myRt, normal, myUp ); - VectorNormalize( myUp, myUp ); - } - - /* 1 = random mode, 0 (well everything else) = non-random mode */ - if( dirtMode == 1 ) - { - /* iterate */ - for( i = 0; i < numDirtVectors; i++ ) - { - /* get random vector */ - angle = Random() * DEG2RAD( 360.0f ); - elevation = Random() * DEG2RAD( DIRT_CONE_ANGLE ); - temp[ 0 ] = cos( angle ) * sin( elevation ); - temp[ 1 ] = sin( angle ) * sin( elevation ); - temp[ 2 ] = cos( elevation ); - - /* transform into tangent space */ - direction[ 0 ] = myRt[ 0 ] * temp[ 0 ] + myUp[ 0 ] * temp[ 1 ] + normal[ 0 ] * temp[ 2 ]; - direction[ 1 ] = myRt[ 1 ] * temp[ 0 ] + myUp[ 1 ] * temp[ 1 ] + normal[ 1 ] * temp[ 2 ]; - direction[ 2 ] = myRt[ 2 ] * temp[ 0 ] + myUp[ 2 ] * temp[ 1 ] + normal[ 2 ] * temp[ 2 ]; - - /* set endpoint */ - VectorMA( trace->origin, dirtDepth, direction, trace->end ); - SetupTrace( trace ); - - /* trace */ - TraceLine( trace ); - if( trace->opaque && !(trace->compileFlags & C_SKY) ) - { - VectorSubtract( trace->hit, trace->origin, displacement ); - gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); - } - } - } - else - { - /* iterate through ordered vectors */ - for( i = 0; i < numDirtVectors; i++ ) - { - /* transform vector into tangent space */ - direction[ 0 ] = myRt[ 0 ] * dirtVectors[ i ][ 0 ] + myUp[ 0 ] * dirtVectors[ i ][ 1 ] + normal[ 0 ] * dirtVectors[ i ][ 2 ]; - direction[ 1 ] = myRt[ 1 ] * dirtVectors[ i ][ 0 ] + myUp[ 1 ] * dirtVectors[ i ][ 1 ] + normal[ 1 ] * dirtVectors[ i ][ 2 ]; - direction[ 2 ] = myRt[ 2 ] * dirtVectors[ i ][ 0 ] + myUp[ 2 ] * dirtVectors[ i ][ 1 ] + normal[ 2 ] * dirtVectors[ i ][ 2 ]; - - /* set endpoint */ - VectorMA( trace->origin, dirtDepth, direction, trace->end ); - SetupTrace( trace ); - - /* trace */ - TraceLine( trace ); - if( trace->opaque ) - { - VectorSubtract( trace->hit, trace->origin, displacement ); - gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); - } - } - } - - /* direct ray */ - VectorMA( trace->origin, dirtDepth, normal, trace->end ); - SetupTrace( trace ); - - /* trace */ - TraceLine( trace ); - if( trace->opaque ) - { - VectorSubtract( trace->hit, trace->origin, displacement ); - gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); - } - - /* early out */ - if( gatherDirt <= 0.0f ) - return 1.0f; - - /* apply gain (does this even do much? heh) */ - outDirt = pow( gatherDirt / (numDirtVectors + 1), dirtGain ); - if( outDirt > 1.0f ) - outDirt = 1.0f; - - /* apply scale */ - outDirt *= dirtScale; - if( outDirt > 1.0f ) - outDirt = 1.0f; - - /* return to sender */ - return 1.0f - outDirt; -} - - - -/* -DirtyRawLightmap() -calculates dirty fraction for each luxel -*/ - -void DirtyRawLightmap( int rawLightmapNum ) -{ - int i, x, y, sx, sy, *cluster; - float *origin, *normal, *dirt, *dirt2, average, samples; - rawLightmap_t *lm; - surfaceInfo_t *info; - trace_t trace; - qboolean noDirty; - - - /* bail if this number exceeds the number of raw lightmaps */ - if( rawLightmapNum >= numRawLightmaps ) - return; - - /* get lightmap */ - lm = &rawLightmaps[ rawLightmapNum ]; - - /* setup trace */ - trace.testOcclusion = qtrue; - trace.forceSunlight = qfalse; - trace.recvShadows = lm->recvShadows; - trace.numSurfaces = lm->numLightSurfaces; - trace.surfaces = &lightSurfaces[ lm->firstLightSurface ]; - trace.inhibitRadius = 0.0f; - trace.testAll = qfalse; - - /* twosided lighting (may or may not be a good idea for lightmapped stuff) */ - trace.twoSided = qfalse; - for( i = 0; i < trace.numSurfaces; i++ ) - { - /* get surface */ - info = &surfaceInfos[ trace.surfaces[ i ] ]; - - /* check twosidedness */ - if( info->si->twoSided ) - { - trace.twoSided = qtrue; - break; - } - } - - noDirty = qfalse; - for( i = 0; i < trace.numSurfaces; i++ ) - { - /* get surface */ - info = &surfaceInfos[ trace.surfaces[ i ] ]; - - /* check twosidedness */ - if( info->si->noDirty ) - { - noDirty = qtrue; - break; - } - } - - /* gather dirt */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - cluster = SUPER_CLUSTER( x, y ); - origin = SUPER_ORIGIN( x, y ); - normal = SUPER_NORMAL( x, y ); - dirt = SUPER_DIRT( x, y ); - - /* set default dirt */ - *dirt = 0.0f; - - /* only look at mapped luxels */ - if( *cluster < 0 ) - continue; - - /* don't apply dirty on this surface */ - if( noDirty ) - { - *dirt = 1.0f; - continue; - } - - /* copy to trace */ - trace.cluster = *cluster; - VectorCopy( origin, trace.origin ); - VectorCopy( normal, trace.normal ); - - /* get dirt */ - *dirt = DirtForSample( &trace ); - } - } - - /* testing no filtering */ - //% return; - - /* filter dirt */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - cluster = SUPER_CLUSTER( x, y ); - dirt = SUPER_DIRT( x, y ); - - /* filter dirt by adjacency to unmapped luxels */ - average = *dirt; - samples = 1.0f; - for( sy = (y - 1); sy <= (y + 1); sy++ ) - { - if( sy < 0 || sy >= lm->sh ) - continue; - - for( sx = (x - 1); sx <= (x + 1); sx++ ) - { - if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) - continue; - - /* get neighboring luxel */ - cluster = SUPER_CLUSTER( sx, sy ); - dirt2 = SUPER_DIRT( sx, sy ); - if( *cluster < 0 || *dirt2 <= 0.0f ) - continue; - - /* add it */ - average += *dirt2; - samples += 1.0f; - } - - /* bail */ - if( samples <= 0.0f ) - break; - } - - /* bail */ - if( samples <= 0.0f ) - continue; - - /* scale dirt */ - *dirt = average / samples; - } - } -} - - - -/* -SubmapRawLuxel() -calculates the pvs cluster, origin, normal of a sub-luxel -*/ - -static qboolean SubmapRawLuxel( rawLightmap_t *lm, int x, int y, float bx, float by, int *sampleCluster, vec3_t sampleOrigin, vec3_t sampleNormal ) -{ - int i, *cluster, *cluster2; - float *origin, *origin2, *normal; //% , *normal2; - vec3_t originVecs[ 2 ]; //% , normalVecs[ 2 ]; - - - /* calulate x vector */ - if( (x < (lm->sw - 1) && bx >= 0.0f) || (x == 0 && bx <= 0.0f) ) - { - cluster = SUPER_CLUSTER( x, y ); - origin = SUPER_ORIGIN( x, y ); - //% normal = SUPER_NORMAL( x, y ); - cluster2 = SUPER_CLUSTER( x + 1, y ); - origin2 = *cluster2 < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x + 1, y ); - //% normal2 = *cluster2 < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x + 1, y ); - } - else if( (x > 0 && bx <= 0.0f) || (x == (lm->sw - 1) && bx >= 0.0f) ) - { - cluster = SUPER_CLUSTER( x - 1, y ); - origin = *cluster < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x - 1, y ); - //% normal = *cluster < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x - 1, y ); - cluster2 = SUPER_CLUSTER( x, y ); - origin2 = SUPER_ORIGIN( x, y ); - //% normal2 = SUPER_NORMAL( x, y ); - } - else - { - Error( "Spurious lightmap S vector\n" ); - } - - VectorSubtract( origin2, origin, originVecs[ 0 ] ); - //% VectorSubtract( normal2, normal, normalVecs[ 0 ] ); - - /* calulate y vector */ - if( (y < (lm->sh - 1) && bx >= 0.0f) || (y == 0 && bx <= 0.0f) ) - { - cluster = SUPER_CLUSTER( x, y ); - origin = SUPER_ORIGIN( x, y ); - //% normal = SUPER_NORMAL( x, y ); - cluster2 = SUPER_CLUSTER( x, y + 1 ); - origin2 = *cluster2 < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x, y + 1 ); - //% normal2 = *cluster2 < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x, y + 1 ); - } - else if( (y > 0 && bx <= 0.0f) || (y == (lm->sh - 1) && bx >= 0.0f) ) - { - cluster = SUPER_CLUSTER( x, y - 1 ); - origin = *cluster < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x, y - 1 ); - //% normal = *cluster < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x, y - 1 ); - cluster2 = SUPER_CLUSTER( x, y ); - origin2 = SUPER_ORIGIN( x, y ); - //% normal2 = SUPER_NORMAL( x, y ); - } - else - Sys_Printf( "WARNING: Spurious lightmap T vector\n" ); - - VectorSubtract( origin2, origin, originVecs[ 1 ] ); - //% VectorSubtract( normal2, normal, normalVecs[ 1 ] ); - - /* calculate new origin */ - //% VectorMA( origin, bx, originVecs[ 0 ], sampleOrigin ); - //% VectorMA( sampleOrigin, by, originVecs[ 1 ], sampleOrigin ); - for( i = 0; i < 3; i++ ) - sampleOrigin[ i ] = sampleOrigin[ i ] + (bx * originVecs[ 0 ][ i ]) + (by * originVecs[ 1 ][ i ]); - - /* get cluster */ - *sampleCluster = ClusterForPointExtFilter( sampleOrigin, (LUXEL_EPSILON * 2), lm->numLightClusters, lm->lightClusters ); - if( *sampleCluster < 0 ) - return qfalse; - - /* calculate new normal */ - //% VectorMA( normal, bx, normalVecs[ 0 ], sampleNormal ); - //% VectorMA( sampleNormal, by, normalVecs[ 1 ], sampleNormal ); - //% if( VectorNormalize( sampleNormal, sampleNormal ) <= 0.0f ) - //% return qfalse; - normal = SUPER_NORMAL( x, y ); - VectorCopy( normal, sampleNormal ); - - /* return ok */ - return qtrue; -} - - -/* -SubsampleRawLuxel_r() -recursively subsamples a luxel until its color gradient is low enough or subsampling limit is reached -*/ - -static void SubsampleRawLuxel_r( rawLightmap_t *lm, trace_t *trace, vec3_t sampleOrigin, int x, int y, float bias, float *lightLuxel, float *lightDeluxel ) -{ - int b, samples, mapped, lighted; - int cluster[ 4 ]; - vec4_t luxel[ 4 ]; - vec3_t deluxel[ 3 ]; - vec3_t origin[ 4 ], normal[ 4 ]; - float biasDirs[ 4 ][ 2 ] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { -1.0f, 1.0f }, { 1.0f, 1.0f } }; - vec3_t color, direction, total; - - - /* limit check */ - if( lightLuxel[ 3 ] >= lightSamples ) - return; - - /* setup */ - VectorClear( total ); - mapped = 0; - lighted = 0; - - /* make 2x2 subsample stamp */ - for( b = 0; b < 4; b++ ) - { - /* set origin */ - VectorCopy( sampleOrigin, origin[ b ] ); - - /* calculate position */ - if( !SubmapRawLuxel( lm, x, y, (bias * biasDirs[ b ][ 0 ]), (bias * biasDirs[ b ][ 1 ]), &cluster[ b ], origin[ b ], normal[ b ] ) ) - { - cluster[ b ] = -1; - continue; - } - mapped++; - - /* increment sample count */ - luxel[ b ][ 3 ] = lightLuxel[ 3 ] + 1.0f; - - /* setup trace */ - trace->cluster = *cluster; - VectorCopy( origin[ b ], trace->origin ); - VectorCopy( normal[ b ], trace->normal ); - - /* sample light */ - - LightContributionToSample( trace ); - if(trace->forceSubsampling > 1.0f) - { - /* alphashadow: we subsample as deep as we can */ - ++lighted; - ++mapped; - ++mapped; - } - - /* add to totals (fixme: make contrast function) */ - VectorCopy( trace->color, luxel[ b ] ); - if(lightDeluxel) - { - VectorCopy( trace->directionContribution, deluxel[ b ] ); - } - VectorAdd( total, trace->color, total ); - if( (luxel[ b ][ 0 ] + luxel[ b ][ 1 ] + luxel[ b ][ 2 ]) > 0.0f ) - lighted++; - } - - /* subsample further? */ - if( (lightLuxel[ 3 ] + 1.0f) < lightSamples && - (total[ 0 ] > 4.0f || total[ 1 ] > 4.0f || total[ 2 ] > 4.0f) && - lighted != 0 && lighted != mapped ) - { - for( b = 0; b < 4; b++ ) - { - if( cluster[ b ] < 0 ) - continue; - SubsampleRawLuxel_r( lm, trace, origin[ b ], x, y, (bias * 0.5f), luxel[ b ], lightDeluxel ? deluxel[ b ] : NULL ); - } - } - - /* average */ - //% VectorClear( color ); - //% samples = 0; - VectorCopy( lightLuxel, color ); - if(lightDeluxel) - { - VectorCopy( lightDeluxel, direction ); - } - samples = 1; - for( b = 0; b < 4; b++ ) - { - if( cluster[ b ] < 0 ) - continue; - VectorAdd( color, luxel[ b ], color ); - if(lightDeluxel) - { - VectorAdd( direction, deluxel[ b ], direction ); - } - samples++; - } - - /* add to luxel */ - if( samples > 0 ) - { - /* average */ - color[ 0 ] /= samples; - color[ 1 ] /= samples; - color[ 2 ] /= samples; - - /* add to color */ - VectorCopy( color, lightLuxel ); - lightLuxel[ 3 ] += 1.0f; - - if(lightDeluxel) - { - direction[ 0 ] /= samples; - direction[ 1 ] /= samples; - direction[ 2 ] /= samples; - VectorCopy( direction, lightDeluxel ); - } - } -} - -/* A mostly Gaussian-like bounded random distribution (sigma is expected standard deviation) */ -static void GaussLikeRandom(float sigma, float *x, float *y) -{ - float r; - r = Random() * 2 * Q_PI; - *x = sigma * 2.73861278752581783822 * cos(r); - *y = sigma * 2.73861278752581783822 * sin(r); - r = Random(); - r = 1 - sqrt(r); - r = 1 - sqrt(r); - *x *= r; - *y *= r; -} -static void RandomSubsampleRawLuxel( rawLightmap_t *lm, trace_t *trace, vec3_t sampleOrigin, int x, int y, float bias, float *lightLuxel, float *lightDeluxel ) -{ - int b, mapped; - int cluster; - vec3_t origin, normal; - vec3_t total, totaldirection; - float dx, dy; - - VectorClear( total ); - VectorClear( totaldirection ); - mapped = 0; - for(b = 0; b < lightSamples; ++b) - { - /* set origin */ - VectorCopy( sampleOrigin, origin ); - GaussLikeRandom(bias, &dx, &dy); - - /* calculate position */ - if( !SubmapRawLuxel( lm, x, y, dx, dy, &cluster, origin, normal ) ) - { - cluster = -1; - continue; - } - mapped++; - - trace->cluster = cluster; - VectorCopy( origin, trace->origin ); - VectorCopy( normal, trace->normal ); - - LightContributionToSample( trace ); - VectorAdd( total, trace->color, total ); - if(lightDeluxel) - { - VectorAdd( totaldirection, trace->directionContribution, totaldirection ); - } - } - - /* add to luxel */ - if( mapped > 0 ) - { - /* average */ - lightLuxel[ 0 ] = total[ 0 ] / mapped; - lightLuxel[ 1 ] = total[ 1 ] / mapped; - lightLuxel[ 2 ] = total[ 2 ] / mapped; - - if(lightDeluxel) - { - lightDeluxel[ 0 ] = totaldirection[ 0 ] / mapped; - lightDeluxel[ 1 ] = totaldirection[ 1 ] / mapped; - lightDeluxel[ 2 ] = totaldirection[ 2 ] / mapped; - } - } -} - - - -/* -IlluminateRawLightmap() -illuminates the luxels -*/ - -#define STACK_LL_SIZE (SUPER_LUXEL_SIZE * 64 * 64) -#define LIGHT_LUXEL( x, y ) (lightLuxels + ((((y) * lm->sw) + (x)) * SUPER_LUXEL_SIZE)) -#define LIGHT_DELUXEL( x, y ) (lightDeluxels + ((((y) * lm->sw) + (x)) * SUPER_DELUXEL_SIZE)) - -void IlluminateRawLightmap( int rawLightmapNum ) -{ - int i, t, x, y, sx, sy, size, luxelFilterRadius, lightmapNum; - int *cluster, *cluster2, mapped, lighted, totalLighted; - size_t llSize, ldSize; - rawLightmap_t *lm; - surfaceInfo_t *info; - qboolean filterColor, filterDir; - float brightness; - float *origin, *normal, *dirt, *luxel, *luxel2, *deluxel, *deluxel2; - unsigned char *flag; - float *lightLuxels, *lightDeluxels, *lightLuxel, *lightDeluxel, samples, filterRadius, weight; - vec3_t color, direction, averageColor, averageDir, total, temp, temp2; - float tests[ 4 ][ 2 ] = { { 0.0f, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }; - trace_t trace; - float stackLightLuxels[ STACK_LL_SIZE ]; - - - /* bail if this number exceeds the number of raw lightmaps */ - if( rawLightmapNum >= numRawLightmaps ) - return; - - /* get lightmap */ - lm = &rawLightmaps[ rawLightmapNum ]; - - /* setup trace */ - trace.testOcclusion = !noTrace; - trace.forceSunlight = qfalse; - trace.recvShadows = lm->recvShadows; - trace.numSurfaces = lm->numLightSurfaces; - trace.surfaces = &lightSurfaces[ lm->firstLightSurface ]; - trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; - - /* twosided lighting (may or may not be a good idea for lightmapped stuff) */ - trace.twoSided = qfalse; - for( i = 0; i < trace.numSurfaces; i++ ) - { - /* get surface */ - info = &surfaceInfos[ trace.surfaces[ i ] ]; - - /* check twosidedness */ - if( info->si->twoSided ) - { - trace.twoSided = qtrue; - break; - } - } - - /* create a culled light list for this raw lightmap */ - CreateTraceLightsForBounds( lm->mins, lm->maxs, lm->plane, lm->numLightClusters, lm->lightClusters, LIGHT_SURFACES, &trace ); - - /* ----------------------------------------------------------------- - fill pass - ----------------------------------------------------------------- */ - - /* set counts */ - numLuxelsIlluminated += (lm->sw * lm->sh); - - /* test debugging state */ - if( debugSurfaces || debugAxis || debugCluster || debugOrigin || dirtDebug || normalmap ) - { - /* debug fill the luxels */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - - /* only fill mapped luxels */ - if( *cluster < 0 ) - continue; - - /* get particulars */ - luxel = SUPER_LUXEL( 0, x, y ); - origin = SUPER_ORIGIN( x, y ); - normal = SUPER_NORMAL( x, y ); - - /* color the luxel with raw lightmap num? */ - if( debugSurfaces ) - VectorCopy( debugColors[ rawLightmapNum % 12 ], luxel ); - - /* color the luxel with lightmap axis? */ - else if( debugAxis ) - { - luxel[ 0 ] = (lm->axis[ 0 ] + 1.0f) * 127.5f; - luxel[ 1 ] = (lm->axis[ 1 ] + 1.0f) * 127.5f; - luxel[ 2 ] = (lm->axis[ 2 ] + 1.0f) * 127.5f; - } - - /* color the luxel with luxel cluster? */ - else if( debugCluster ) - VectorCopy( debugColors[ *cluster % 12 ], luxel ); - - /* color the luxel with luxel origin? */ - else if( debugOrigin ) - { - VectorSubtract( lm->maxs, lm->mins, temp ); - VectorScale( temp, (1.0f / 255.0f), temp ); - VectorSubtract( origin, lm->mins, temp2 ); - luxel[ 0 ] = lm->mins[ 0 ] + (temp[ 0 ] * temp2[ 0 ]); - luxel[ 1 ] = lm->mins[ 1 ] + (temp[ 1 ] * temp2[ 1 ]); - luxel[ 2 ] = lm->mins[ 2 ] + (temp[ 2 ] * temp2[ 2 ]); - } - - /* color the luxel with the normal */ - else if( normalmap ) - { - luxel[ 0 ] = (normal[ 0 ] + 1.0f) * 127.5f; - luxel[ 1 ] = (normal[ 1 ] + 1.0f) * 127.5f; - luxel[ 2 ] = (normal[ 2 ] + 1.0f) * 127.5f; - } - - /* otherwise clear it */ - else - VectorClear( luxel ); - - /* add to counts */ - luxel[ 3 ] = 1.0f; - } - } - } - else - { - /* allocate temporary per-light luxel storage */ - llSize = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); - ldSize = lm->sw * lm->sh * SUPER_DELUXEL_SIZE * sizeof( float ); - if( llSize <= (STACK_LL_SIZE * sizeof( float )) ) - lightLuxels = stackLightLuxels; - else - lightLuxels = safe_malloc( llSize ); - if(deluxemap) - lightDeluxels = safe_malloc( ldSize ); - else - lightDeluxels = NULL; - - /* clear luxels */ - //% memset( lm->superLuxels[ 0 ], 0, llSize ); - - /* set ambient color */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - luxel = SUPER_LUXEL( 0, x, y ); - normal = SUPER_NORMAL( x, y ); - deluxel = SUPER_DELUXEL( x, y ); - - /* blacken unmapped clusters */ - if( *cluster < 0 ) - VectorClear( luxel ); - - /* set ambient */ - else - { - VectorCopy( ambientColor, luxel ); - if( deluxemap ) - { - brightness = RGBTOGRAY( ambientColor ) * ( 1.0f/255.0f ); - - // use AT LEAST this amount of contribution from ambient for the deluxemap, fixes points that receive ZERO light - if(brightness < 0.00390625f) - brightness = 0.00390625f; - - VectorScale( normal, brightness, deluxel ); - } - luxel[ 3 ] = 1.0f; - } - } - } - - /* clear styled lightmaps */ - size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); - for( lightmapNum = 1; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - if( lm->superLuxels[ lightmapNum ] != NULL ) - memset( lm->superLuxels[ lightmapNum ], 0, size ); - } - - /* debugging code */ - //% if( trace.numLights <= 0 ) - //% Sys_Printf( "Lightmap %9d: 0 lights, axis: %.2f, %.2f, %.2f\n", rawLightmapNum, lm->axis[ 0 ], lm->axis[ 1 ], lm->axis[ 2 ] ); - - /* walk light list */ - for( i = 0; i < trace.numLights; i++ ) - { - /* setup trace */ - trace.light = trace.lights[ i ]; - - /* style check */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - if( lm->styles[ lightmapNum ] == trace.light->style || - lm->styles[ lightmapNum ] == LS_NONE ) - break; - } - - /* max of MAX_LIGHTMAPS (4) styles allowed to hit a surface/lightmap */ - if( lightmapNum >= MAX_LIGHTMAPS ) - { - Sys_Printf( "WARNING: Hit per-surface style limit (%d)\n", MAX_LIGHTMAPS ); - continue; - } - - /* setup */ - memset( lightLuxels, 0, llSize ); - if(deluxemap) - memset( lightDeluxels, 0, ldSize ); - totalLighted = 0; - - /* determine filter radius */ - filterRadius = lm->filterRadius > trace.light->filterRadius - ? lm->filterRadius - : trace.light->filterRadius; - if( filterRadius < 0.0f ) - filterRadius = 0.0f; - - /* set luxel filter radius */ - luxelFilterRadius = superSample * filterRadius / lm->sampleSize; - if( luxelFilterRadius == 0 && (filterRadius > 0.0f || filter) ) - luxelFilterRadius = 1; - - /* allocate sampling flags storage */ - if((lightSamples > 1 || lightRandomSamples) && luxelFilterRadius == 0) - { - size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( unsigned char ); - if(lm->superFlags == NULL) - lm->superFlags = safe_malloc( size ); - memset( (void *) lm->superFlags, 0, size ); - } - - /* initial pass, one sample per luxel */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - if( *cluster < 0 ) - continue; - - /* get particulars */ - lightLuxel = LIGHT_LUXEL( x, y ); - lightDeluxel = LIGHT_DELUXEL( x, y ); - origin = SUPER_ORIGIN( x, y ); - normal = SUPER_NORMAL( x, y ); - flag = SUPER_FLAG( x, y ); - -#if 0 - ////////// 27's temp hack for testing edge clipping //// - if( origin[0]==0 && origin[1]==0 && origin[2]==0 ) - { - lightLuxel[ 1 ] = 255; - lightLuxel[ 3 ] = 1.0f; - totalLighted++; - } - else -#endif - { - /* set contribution count */ - lightLuxel[ 3 ] = 1.0f; - - /* setup trace */ - trace.cluster = *cluster; - VectorCopy( origin, trace.origin ); - VectorCopy( normal, trace.normal ); - - /* get light for this sample */ - LightContributionToSample( &trace ); - VectorCopy( trace.color, lightLuxel ); - - /* add the contribution to the deluxemap */ - if( deluxemap ) - { - VectorCopy( trace.directionContribution, lightDeluxel ); - } - - /* check for evilness */ - if(trace.forceSubsampling > 1.0f && (lightSamples > 1 || lightRandomSamples) && luxelFilterRadius == 0) - { - totalLighted++; - *flag |= FLAG_FORCE_SUBSAMPLING; /* force */ - } - /* add to count */ - else if( trace.color[ 0 ] || trace.color[ 1 ] || trace.color[ 2 ] ) - totalLighted++; - } - } - } - - /* don't even bother with everything else if nothing was lit */ - if( totalLighted == 0 ) - continue; - - /* secondary pass, adaptive supersampling (fixme: use a contrast function to determine if subsampling is necessary) */ - /* 2003-09-27: changed it so filtering disamples supersampling, as it would waste time */ - if( (lightSamples > 1 || lightRandomSamples) && luxelFilterRadius == 0 ) - { - /* walk luxels */ - for( y = 0; y < (lm->sh - 1); y++ ) - { - for( x = 0; x < (lm->sw - 1); x++ ) - { - /* setup */ - mapped = 0; - lighted = 0; - VectorClear( total ); - - /* test 2x2 stamp */ - for( t = 0; t < 4; t++ ) - { - /* set sample coords */ - sx = x + tests[ t ][ 0 ]; - sy = y + tests[ t ][ 1 ]; - - /* get cluster */ - cluster = SUPER_CLUSTER( sx, sy ); - if( *cluster < 0 ) - continue; - mapped++; - - /* get luxel */ - flag = SUPER_FLAG( sx, sy ); - if(*flag & FLAG_FORCE_SUBSAMPLING) - { - /* force a lighted/mapped discrepancy so we subsample */ - ++lighted; - ++mapped; - ++mapped; - } - lightLuxel = LIGHT_LUXEL( sx, sy ); - VectorAdd( total, lightLuxel, total ); - if( (lightLuxel[ 0 ] + lightLuxel[ 1 ] + lightLuxel[ 2 ]) > 0.0f ) - lighted++; - } - - /* if total color is under a certain amount, then don't bother subsampling */ - if( total[ 0 ] <= 4.0f && total[ 1 ] <= 4.0f && total[ 2 ] <= 4.0f ) - continue; - - /* if all 4 pixels are either in shadow or light, then don't subsample */ - if( lighted != 0 && lighted != mapped ) - { - for( t = 0; t < 4; t++ ) - { - /* set sample coords */ - sx = x + tests[ t ][ 0 ]; - sy = y + tests[ t ][ 1 ]; - - /* get luxel */ - cluster = SUPER_CLUSTER( sx, sy ); - if( *cluster < 0 ) - continue; - flag = SUPER_FLAG( sx, sy ); - if(*flag & FLAG_ALREADY_SUBSAMPLED) // already subsampled - continue; - lightLuxel = LIGHT_LUXEL( sx, sy ); - lightDeluxel = LIGHT_DELUXEL( sx, sy ); - origin = SUPER_ORIGIN( sx, sy ); - - /* only subsample shadowed luxels */ - //% if( (lightLuxel[ 0 ] + lightLuxel[ 1 ] + lightLuxel[ 2 ]) <= 0.0f ) - //% continue; - - /* subsample it */ - if(lightRandomSamples) - RandomSubsampleRawLuxel( lm, &trace, origin, sx, sy, 0.5f * lightSamplesSearchBoxSize, lightLuxel, deluxemap ? lightDeluxel : NULL ); - else - SubsampleRawLuxel_r( lm, &trace, origin, sx, sy, 0.25f * lightSamplesSearchBoxSize, lightLuxel, deluxemap ? lightDeluxel : NULL ); - - *flag |= FLAG_ALREADY_SUBSAMPLED; - - /* debug code to colorize subsampled areas to yellow */ - //% luxel = SUPER_LUXEL( lightmapNum, sx, sy ); - //% VectorSet( luxel, 255, 204, 0 ); - } - } - } - } - } - - /* tertiary pass, apply dirt map (ambient occlusion) */ - if( 0 && dirty ) - { - /* walk luxels */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - if( *cluster < 0 ) - continue; - - /* get particulars */ - lightLuxel = LIGHT_LUXEL( x, y ); - dirt = SUPER_DIRT( x, y ); - - /* scale light value */ - VectorScale( lightLuxel, *dirt, lightLuxel ); - } - } - } - - /* allocate sampling lightmap storage */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - { - /* allocate sampling lightmap storage */ - size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); - lm->superLuxels[ lightmapNum ] = safe_malloc( size ); - memset( lm->superLuxels[ lightmapNum ], 0, size ); - } - - /* set style */ - if( lightmapNum > 0 ) - { - lm->styles[ lightmapNum ] = trace.light->style; - //% Sys_Printf( "Surface %6d has lightstyle %d\n", rawLightmapNum, trace.light->style ); - } - - /* copy to permanent luxels */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster and origin */ - cluster = SUPER_CLUSTER( x, y ); - if( *cluster < 0 ) - continue; - origin = SUPER_ORIGIN( x, y ); - - /* filter? */ - if( luxelFilterRadius ) - { - /* setup */ - VectorClear( averageColor ); - VectorClear( averageDir ); - samples = 0.0f; - - /* cheaper distance-based filtering */ - for( sy = (y - luxelFilterRadius); sy <= (y + luxelFilterRadius); sy++ ) - { - if( sy < 0 || sy >= lm->sh ) - continue; - - for( sx = (x - luxelFilterRadius); sx <= (x + luxelFilterRadius); sx++ ) - { - if( sx < 0 || sx >= lm->sw ) - continue; - - /* get particulars */ - cluster = SUPER_CLUSTER( sx, sy ); - if( *cluster < 0 ) - continue; - lightLuxel = LIGHT_LUXEL( sx, sy ); - lightDeluxel = LIGHT_DELUXEL( sx, sy ); - - /* create weight */ - weight = (abs( sx - x ) == luxelFilterRadius ? 0.5f : 1.0f); - weight *= (abs( sy - y ) == luxelFilterRadius ? 0.5f : 1.0f); - - /* scale luxel by filter weight */ - VectorScale( lightLuxel, weight, color ); - VectorAdd( averageColor, color, averageColor ); - if(deluxemap) - { - VectorScale( lightDeluxel, weight, direction ); - VectorAdd( averageDir, direction, averageDir ); - } - samples += weight; - } - } - - /* any samples? */ - if( samples <= 0.0f ) - continue; - - /* scale into luxel */ - luxel = SUPER_LUXEL( lightmapNum, x, y ); - luxel[ 3 ] = 1.0f; - - /* handle negative light */ - if( trace.light->flags & LIGHT_NEGATIVE ) - { - luxel[ 0 ] -= averageColor[ 0 ] / samples; - luxel[ 1 ] -= averageColor[ 1 ] / samples; - luxel[ 2 ] -= averageColor[ 2 ] / samples; - } - - /* handle normal light */ - else - { - luxel[ 0 ] += averageColor[ 0 ] / samples; - luxel[ 1 ] += averageColor[ 1 ] / samples; - luxel[ 2 ] += averageColor[ 2 ] / samples; - } - - if(deluxemap) - { - /* scale into luxel */ - deluxel = SUPER_DELUXEL( x, y ); - deluxel[ 0 ] += averageDir[ 0 ] / samples; - deluxel[ 1 ] += averageDir[ 1 ] / samples; - deluxel[ 2 ] += averageDir[ 2 ] / samples; - } - } - - /* single sample */ - else - { - /* get particulars */ - lightLuxel = LIGHT_LUXEL( x, y ); - lightDeluxel = LIGHT_DELUXEL( x, y ); - luxel = SUPER_LUXEL( lightmapNum, x, y ); - deluxel = SUPER_DELUXEL( x, y ); - - /* handle negative light */ - if( trace.light->flags & LIGHT_NEGATIVE ) - VectorScale( averageColor, -1.0f, averageColor ); - - /* add color */ - luxel[ 3 ] = 1.0f; - - /* handle negative light */ - if( trace.light->flags & LIGHT_NEGATIVE ) - VectorSubtract( luxel, lightLuxel, luxel ); - - /* handle normal light */ - else - VectorAdd( luxel, lightLuxel, luxel ); - - if(deluxemap) - { - VectorAdd( deluxel, lightDeluxel, deluxel ); - } - } - } - } - } - - /* free temporary luxels */ - if( lightLuxels != stackLightLuxels ) - free( lightLuxels ); - - if(deluxemap) - free( lightDeluxels ); - } - - /* free light list */ - FreeTraceLights( &trace ); - - /* floodlight pass */ - if( floodlighty ) - FloodlightIlluminateLightmap(lm); - - if (debugnormals) - { - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - //% if( *cluster < 0 ) - //% continue; - - /* get particulars */ - luxel = SUPER_LUXEL( lightmapNum, x, y ); - normal = SUPER_NORMAL ( x, y ); - - luxel[0]=(normal[0]*127)+127; - luxel[1]=(normal[1]*127)+127; - luxel[2]=(normal[2]*127)+127; - } - } - } - } - - /* ----------------------------------------------------------------- - dirt pass - ----------------------------------------------------------------- */ - - if( dirty ) - { - /* walk lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - - /* apply dirt to each luxel */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - //% if( *cluster < 0 ) // TODO why not do this check? These pixels should be zero anyway - //% continue; - - /* get particulars */ - luxel = SUPER_LUXEL( lightmapNum, x, y ); - dirt = SUPER_DIRT( x, y ); - - /* apply dirt */ - VectorScale( luxel, *dirt, luxel ); - - /* debugging */ - if( dirtDebug ) - VectorSet( luxel, *dirt * 255.0f, *dirt * 255.0f, *dirt * 255.0f ); - } - } - } - } - - /* ----------------------------------------------------------------- - filter pass - ----------------------------------------------------------------- */ - - /* walk lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - - /* average occluded luxels from neighbors */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get particulars */ - cluster = SUPER_CLUSTER( x, y ); - luxel = SUPER_LUXEL( lightmapNum, x, y ); - deluxel = SUPER_DELUXEL( x, y ); - normal = SUPER_NORMAL( x, y ); - - /* determine if filtering is necessary */ - filterColor = qfalse; - filterDir = qfalse; - if( *cluster < 0 || - (lm->splotchFix && (luxel[ 0 ] <= ambientColor[ 0 ] || luxel[ 1 ] <= ambientColor[ 1 ] || luxel[ 2 ] <= ambientColor[ 2 ])) ) - filterColor = qtrue; - - if( deluxemap && lightmapNum == 0 && (*cluster < 0 || filter) ) - filterDir = qtrue; - - if( !filterColor && !filterDir ) - continue; - - /* choose seed amount */ - VectorClear( averageColor ); - VectorClear( averageDir ); - samples = 0.0f; - - /* walk 3x3 matrix */ - for( sy = (y - 1); sy <= (y + 1); sy++ ) - { - if( sy < 0 || sy >= lm->sh ) - continue; - - for( sx = (x - 1); sx <= (x + 1); sx++ ) - { - if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) - continue; - - /* get neighbor's particulars */ - cluster2 = SUPER_CLUSTER( sx, sy ); - luxel2 = SUPER_LUXEL( lightmapNum, sx, sy ); - deluxel2 = SUPER_DELUXEL( sx, sy ); - - /* ignore unmapped/unlit luxels */ - if( *cluster2 < 0 || luxel2[ 3 ] == 0.0f || - (lm->splotchFix && VectorCompare( luxel2, ambientColor )) ) - continue; - - /* add its distinctiveness to our own */ - VectorAdd( averageColor, luxel2, averageColor ); - samples += luxel2[ 3 ]; - if( filterDir ) - VectorAdd( averageDir, deluxel2, averageDir ); - } - } - - /* fall through */ - if( samples <= 0.0f ) - continue; - - /* dark lightmap seams */ - if( dark ) - { - if( lightmapNum == 0 ) - VectorMA( averageColor, 2.0f, ambientColor, averageColor ); - samples += 2.0f; - } - - /* average it */ - if( filterColor ) - { - VectorDivide( averageColor, samples, luxel ); - luxel[ 3 ] = 1.0f; - } - if( filterDir ) - VectorDivide( averageDir, samples, deluxel ); - - /* set cluster to -3 */ - if( *cluster < 0 ) - *cluster = CLUSTER_FLOODED; - } - } - } - - -#if 0 - // audit pass - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - for( y = 0; y < lm->sh; y++ ) - for( x = 0; x < lm->sw; x++ ) - { - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - luxel = SUPER_LUXEL( lightmapNum, x, y ); - deluxel = SUPER_DELUXEL( x, y ); - if(!luxel || !deluxel || !cluster) - { - Sys_FPrintf(SYS_VRB, "WARNING: I got NULL'd.\n"); - continue; - } - else if(*cluster < 0) - { - // unmapped pixel - // should have neither deluxemap nor lightmap - if(deluxel[3]) - Sys_FPrintf(SYS_VRB, "WARNING: I have written deluxe to an unmapped luxel. Sorry.\n"); - } - else - { - // mapped pixel - // should have both deluxemap and lightmap - if(deluxel[3]) - Sys_FPrintf(SYS_VRB, "WARNING: I forgot to write deluxe to a mapped luxel. Sorry.\n"); - } - } - } -#endif -} - - - -/* -IlluminateVertexes() -light the surface vertexes -*/ - -#define VERTEX_NUDGE 4.0f - -void IlluminateVertexes( int num ) -{ - int i, x, y, z, x1, y1, z1, sx, sy, radius, maxRadius, *cluster; - int lightmapNum, numAvg; - float samples, *vertLuxel, *radVertLuxel, *luxel, dirt; - vec3_t origin, temp, temp2, colors[ MAX_LIGHTMAPS ], avgColors[ MAX_LIGHTMAPS ]; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - rawLightmap_t *lm; - bspDrawVert_t *verts; - trace_t trace; - float floodLightAmount; - vec3_t floodColor; - - - /* get surface, info, and raw lightmap */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - lm = info->lm; - - /* ----------------------------------------------------------------- - illuminate the vertexes - ----------------------------------------------------------------- */ - - /* calculate vertex lighting for surfaces without lightmaps */ - if( lm == NULL || cpmaHack ) - { - /* setup trace */ - trace.testOcclusion = (cpmaHack && lm != NULL) ? qfalse : !noTrace; - trace.forceSunlight = info->si->forceSunlight; - trace.recvShadows = info->recvShadows; - trace.numSurfaces = 1; - trace.surfaces = # - trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; - - /* twosided lighting */ - trace.twoSided = info->si->twoSided; - - /* make light list for this surface */ - CreateTraceLightsForSurface( num, &trace ); - - /* setup */ - verts = yDrawVerts + ds->firstVert; - numAvg = 0; - memset( avgColors, 0, sizeof( avgColors ) ); - - /* walk the surface verts */ - for( i = 0; i < ds->numVerts; i++ ) - { - /* get vertex luxel */ - radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); - - /* color the luxel with raw lightmap num? */ - if( debugSurfaces ) - VectorCopy( debugColors[ num % 12 ], radVertLuxel ); - - /* color the luxel with luxel origin? */ - else if( debugOrigin ) - { - VectorSubtract( info->maxs, info->mins, temp ); - VectorScale( temp, (1.0f / 255.0f), temp ); - VectorSubtract( origin, lm->mins, temp2 ); - radVertLuxel[ 0 ] = info->mins[ 0 ] + (temp[ 0 ] * temp2[ 0 ]); - radVertLuxel[ 1 ] = info->mins[ 1 ] + (temp[ 1 ] * temp2[ 1 ]); - radVertLuxel[ 2 ] = info->mins[ 2 ] + (temp[ 2 ] * temp2[ 2 ]); - } - - /* color the luxel with the normal */ - else if( normalmap ) - { - radVertLuxel[ 0 ] = (verts[ i ].normal[ 0 ] + 1.0f) * 127.5f; - radVertLuxel[ 1 ] = (verts[ i ].normal[ 1 ] + 1.0f) * 127.5f; - radVertLuxel[ 2 ] = (verts[ i ].normal[ 2 ] + 1.0f) * 127.5f; - } - - /* illuminate the vertex */ - else - { - /* clear vertex luxel */ - VectorSet( radVertLuxel, -1.0f, -1.0f, -1.0f ); - - /* try at initial origin */ - trace.cluster = ClusterForPointExtFilter( verts[ i ].xyz, VERTEX_EPSILON, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ] ); - if( trace.cluster >= 0 ) - { - /* setup trace */ - VectorCopy( verts[ i ].xyz, trace.origin ); - VectorCopy( verts[ i ].normal, trace.normal ); - - /* r7 dirt */ - if( dirty && !bouncing ) - dirt = DirtForSample( &trace ); - else - dirt = 1.0f; - - /* jal: floodlight */ - floodLightAmount = 0.0f; - VectorClear( floodColor ); - if( floodlighty && !bouncing ) - { - floodLightAmount = floodlightIntensity * FloodLightForSample( &trace, floodlightDistance, floodlight_lowquality ); - VectorScale( floodlightRGB, floodLightAmount, floodColor ); - } - - /* trace */ - LightingAtSample( &trace, ds->vertexStyles, colors ); - - /* store */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* r7 dirt */ - VectorScale( colors[ lightmapNum ], dirt, colors[ lightmapNum ] ); - - /* jal: floodlight */ - VectorAdd( colors[ lightmapNum ], floodColor, colors[ lightmapNum ] ); - - /* store */ - radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - VectorCopy( colors[ lightmapNum ], radVertLuxel ); - VectorAdd( avgColors[ lightmapNum ], colors[ lightmapNum ], colors[ lightmapNum ] ); - } - } - - /* is this sample bright enough? */ - radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); - if( radVertLuxel[ 0 ] <= ambientColor[ 0 ] && - radVertLuxel[ 1 ] <= ambientColor[ 1 ] && - radVertLuxel[ 2 ] <= ambientColor[ 2 ] ) - { - /* nudge the sample point around a bit */ - for( x = 0; x < 5; x++ ) - { - /* two's complement 0, 1, -1, 2, -2, etc */ - x1 = ((x >> 1) ^ (x & 1 ? -1 : 0)) + (x & 1); - - for( y = 0; y < 5; y++ ) - { - y1 = ((y >> 1) ^ (y & 1 ? -1 : 0)) + (y & 1); - - for( z = 0; z < 5; z++ ) - { - z1 = ((z >> 1) ^ (z & 1 ? -1 : 0)) + (z & 1); - - /* nudge origin */ - trace.origin[ 0 ] = verts[ i ].xyz[ 0 ] + (VERTEX_NUDGE * x1); - trace.origin[ 1 ] = verts[ i ].xyz[ 1 ] + (VERTEX_NUDGE * y1); - trace.origin[ 2 ] = verts[ i ].xyz[ 2 ] + (VERTEX_NUDGE * z1); - - /* try at nudged origin */ - trace.cluster = ClusterForPointExtFilter( origin, VERTEX_EPSILON, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ] ); - if( trace.cluster < 0 ) - continue; - - /* r7 dirt */ - if( dirty && !bouncing ) - dirt = DirtForSample( &trace ); - else - dirt = 1.0f; - - /* jal: floodlight */ - floodLightAmount = 0.0f; - VectorClear( floodColor ); - if( floodlighty && !bouncing ) - { - floodLightAmount = floodlightIntensity * FloodLightForSample( &trace, floodlightDistance, floodlight_lowquality ); - VectorScale( floodlightRGB, floodLightAmount, floodColor ); - } - - /* trace */ - LightingAtSample( &trace, ds->vertexStyles, colors ); - - /* store */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* r7 dirt */ - VectorScale( colors[ lightmapNum ], dirt, colors[ lightmapNum ] ); - - /* jal: floodlight */ - VectorAdd( colors[ lightmapNum ], floodColor, colors[ lightmapNum ] ); - - /* store */ - radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - VectorCopy( colors[ lightmapNum ], radVertLuxel ); - } - - /* bright enough? */ - radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); - if( radVertLuxel[ 0 ] > ambientColor[ 0 ] || - radVertLuxel[ 1 ] > ambientColor[ 1 ] || - radVertLuxel[ 2 ] > ambientColor[ 2 ] ) - x = y = z = 1000; - } - } - } - } - - /* add to average? */ - radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); - if( radVertLuxel[ 0 ] > ambientColor[ 0 ] || - radVertLuxel[ 1 ] > ambientColor[ 1 ] || - radVertLuxel[ 2 ] > ambientColor[ 2 ] ) - { - numAvg++; - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - VectorAdd( avgColors[ lightmapNum ], radVertLuxel, avgColors[ lightmapNum ] ); - } - } - } - - /* another happy customer */ - numVertsIlluminated++; - } - - /* set average color */ - if( numAvg > 0 ) - { - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - VectorScale( avgColors[ lightmapNum ], (1.0f / numAvg), avgColors[ lightmapNum ] ); - } - else - { - VectorCopy( ambientColor, avgColors[ 0 ] ); - } - - /* clean up and store vertex color */ - for( i = 0; i < ds->numVerts; i++ ) - { - /* get vertex luxel */ - radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); - - /* store average in occluded vertexes */ - if( radVertLuxel[ 0 ] < 0.0f ) - { - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - VectorCopy( avgColors[ lightmapNum ], radVertLuxel ); - - /* debug code */ - //% VectorSet( radVertLuxel, 255.0f, 0.0f, 0.0f ); - } - } - - /* store it */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* get luxels */ - vertLuxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - - /* store */ - if( bouncing || bounce == 0 || !bounceOnly ) - VectorAdd( vertLuxel, radVertLuxel, vertLuxel ); - if( !info->si->noVertexLight ) - ColorToBytes( vertLuxel, verts[ i ].color[ lightmapNum ], info->si->vertexScale ); - } - } - - /* free light list */ - FreeTraceLights( &trace ); - - /* return to sender */ - return; - } - - /* ----------------------------------------------------------------- - reconstitute vertex lighting from the luxels - ----------------------------------------------------------------- */ - - /* set styles from lightmap */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - ds->vertexStyles[ lightmapNum ] = lm->styles[ lightmapNum ]; - - /* get max search radius */ - maxRadius = lm->sw; - maxRadius = maxRadius > lm->sh ? maxRadius : lm->sh; - - /* walk the surface verts */ - verts = yDrawVerts + ds->firstVert; - for( i = 0; i < ds->numVerts; i++ ) - { - /* do each lightmap */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - - /* get luxel coords */ - x = verts[ i ].lightmap[ lightmapNum ][ 0 ]; - y = verts[ i ].lightmap[ lightmapNum ][ 1 ]; - if( x < 0 ) - x = 0; - else if( x >= lm->sw ) - x = lm->sw - 1; - if( y < 0 ) - y = 0; - else if( y >= lm->sh ) - y = lm->sh - 1; - - /* get vertex luxels */ - vertLuxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); - - /* color the luxel with the normal? */ - if( normalmap ) - { - radVertLuxel[ 0 ] = (verts[ i ].normal[ 0 ] + 1.0f) * 127.5f; - radVertLuxel[ 1 ] = (verts[ i ].normal[ 1 ] + 1.0f) * 127.5f; - radVertLuxel[ 2 ] = (verts[ i ].normal[ 2 ] + 1.0f) * 127.5f; - } - - /* color the luxel with surface num? */ - else if( debugSurfaces ) - VectorCopy( debugColors[ num % 12 ], radVertLuxel ); - - /* divine color from the superluxels */ - else - { - /* increasing radius */ - VectorClear( radVertLuxel ); - samples = 0.0f; - for( radius = 0; radius < maxRadius && samples <= 0.0f; radius++ ) - { - /* sample within radius */ - for( sy = (y - radius); sy <= (y + radius); sy++ ) - { - if( sy < 0 || sy >= lm->sh ) - continue; - - for( sx = (x - radius); sx <= (x + radius); sx++ ) - { - if( sx < 0 || sx >= lm->sw ) - continue; - - /* get luxel particulars */ - luxel = SUPER_LUXEL( lightmapNum, sx, sy ); - cluster = SUPER_CLUSTER( sx, sy ); - if( *cluster < 0 ) - continue; - - /* testing: must be brigher than ambient color */ - //% if( luxel[ 0 ] <= ambientColor[ 0 ] || luxel[ 1 ] <= ambientColor[ 1 ] || luxel[ 2 ] <= ambientColor[ 2 ] ) - //% continue; - - /* add its distinctiveness to our own */ - VectorAdd( radVertLuxel, luxel, radVertLuxel ); - samples += luxel[ 3 ]; - } - } - } - - /* any color? */ - if( samples > 0.0f ) - VectorDivide( radVertLuxel, samples, radVertLuxel ); - else - VectorCopy( ambientColor, radVertLuxel ); - } - - /* store into floating point storage */ - VectorAdd( vertLuxel, radVertLuxel, vertLuxel ); - numVertsIlluminated++; - - /* store into bytes (for vertex approximation) */ - if( !info->si->noVertexLight ) - ColorToBytes( vertLuxel, verts[ i ].color[ lightmapNum ], 1.0f ); - } - } -} - - - -/* ------------------------------------------------------------------------------- - -light optimization (-fast) - -creates a list of lights that will affect a surface and stores it in tw -this is to optimize surface lighting by culling out as many of the -lights in the world as possible from further calculation - -------------------------------------------------------------------------------- */ - -/* -SetupBrushes() -determines opaque brushes in the world and find sky shaders for sunlight calculations -*/ - -void SetupBrushes( void ) -{ - int i, j, b, compileFlags; - qboolean inside; - bspBrush_t *brush; - bspBrushSide_t *side; - bspShader_t *shader; - shaderInfo_t *si; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- SetupBrushes ---\n" ); - - /* allocate */ - if( opaqueBrushes == NULL ) - opaqueBrushes = safe_malloc( numBSPBrushes / 8 + 1 ); - - /* clear */ - memset( opaqueBrushes, 0, numBSPBrushes / 8 + 1 ); - numOpaqueBrushes = 0; - - /* walk the list of worldspawn brushes */ - for( i = 0; i < bspModels[ 0 ].numBSPBrushes; i++ ) - { - /* get brush */ - b = bspModels[ 0 ].firstBSPBrush + i; - brush = &bspBrushes[ b ]; - - /* check all sides */ - inside = qtrue; - compileFlags = 0; - for( j = 0; j < brush->numSides && inside; j++ ) - { - /* do bsp shader calculations */ - side = &bspBrushSides[ brush->firstSide + j ]; - shader = &bspShaders[ side->shaderNum ]; - - /* get shader info */ - si = ShaderInfoForShader( shader->shader ); - if( si == NULL ) - continue; - - /* or together compile flags */ - compileFlags |= si->compileFlags; - } - - /* determine if this brush is opaque to light */ - if( !(compileFlags & C_TRANSLUCENT) ) - { - opaqueBrushes[ b >> 3 ] |= (1 << (b & 7)); - numOpaqueBrushes++; - maxOpaqueBrush = i; - } - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d opaque brushes\n", numOpaqueBrushes ); -} - - - -/* -ClusterVisible() -determines if two clusters are visible to each other using the PVS -*/ - -qboolean ClusterVisible( int a, int b ) -{ - int portalClusters, leafBytes; - byte *pvs; - - - /* dummy check */ - if( a < 0 || b < 0 ) - return qfalse; - - /* early out */ - if( a == b ) - return qtrue; - - /* not vised? */ - if( numBSPVisBytes <=8 ) - return qtrue; - - /* get pvs data */ - portalClusters = ((int *) bspVisBytes)[ 0 ]; - leafBytes = ((int*) bspVisBytes)[ 1 ]; - pvs = bspVisBytes + VIS_HEADER_SIZE + (a * leafBytes); - - /* check */ - if( (pvs[ b >> 3 ] & (1 << (b & 7))) ) - return qtrue; - return qfalse; -} - - - -/* -PointInLeafNum_r() -borrowed from vlight.c -*/ - -int PointInLeafNum_r( vec3_t point, int nodenum ) -{ - int leafnum; - vec_t dist; - bspNode_t *node; - bspPlane_t *plane; - - - while( nodenum >= 0 ) - { - node = &bspNodes[ nodenum ]; - plane = &bspPlanes[ node->planeNum ]; - dist = DotProduct( point, plane->normal ) - plane->dist; - if( dist > 0.1 ) - nodenum = node->children[ 0 ]; - else if( dist < -0.1 ) - nodenum = node->children[ 1 ]; - else - { - leafnum = PointInLeafNum_r( point, node->children[ 0 ] ); - if( bspLeafs[ leafnum ].cluster != -1 ) - return leafnum; - nodenum = node->children[ 1 ]; - } - } - - leafnum = -nodenum - 1; - return leafnum; -} - - - -/* -PointInLeafnum() -borrowed from vlight.c -*/ - -int PointInLeafNum( vec3_t point ) -{ - return PointInLeafNum_r( point, 0 ); -} - - - -/* -ClusterVisibleToPoint() - ydnar -returns qtrue if point can "see" cluster -*/ - -qboolean ClusterVisibleToPoint( vec3_t point, int cluster ) -{ - int pointCluster; - - - /* get leafNum for point */ - pointCluster = ClusterForPoint( point ); - if( pointCluster < 0 ) - return qfalse; - - /* check pvs */ - return ClusterVisible( pointCluster, cluster ); -} - - - -/* -ClusterForPoint() - ydnar -returns the pvs cluster for point -*/ - -int ClusterForPoint( vec3_t point ) -{ - int leafNum; - - - /* get leafNum for point */ - leafNum = PointInLeafNum( point ); - if( leafNum < 0 ) - return -1; - - /* return the cluster */ - return bspLeafs[ leafNum ].cluster; -} - - - -/* -ClusterForPointExt() - ydnar -also takes brushes into account for occlusion testing -*/ - -int ClusterForPointExt( vec3_t point, float epsilon ) -{ - int i, j, b, leafNum, cluster; - float dot; - qboolean inside; - int *brushes, numBSPBrushes; - bspLeaf_t *leaf; - bspBrush_t *brush; - bspPlane_t *plane; - - - /* get leaf for point */ - leafNum = PointInLeafNum( point ); - if( leafNum < 0 ) - return -1; - leaf = &bspLeafs[ leafNum ]; - - /* get the cluster */ - cluster = leaf->cluster; - if( cluster < 0 ) - return -1; - - /* transparent leaf, so check point against all brushes in the leaf */ - brushes = &bspLeafBrushes[ leaf->firstBSPLeafBrush ]; - numBSPBrushes = leaf->numBSPLeafBrushes; - for( i = 0; i < numBSPBrushes; i++ ) - { - /* get parts */ - b = brushes[ i ]; - if( b > maxOpaqueBrush ) - continue; - brush = &bspBrushes[ b ]; - if( !(opaqueBrushes[ b >> 3 ] & (1 << (b & 7))) ) - continue; - - /* check point against all planes */ - inside = qtrue; - for( j = 0; j < brush->numSides && inside; j++ ) - { - plane = &bspPlanes[ bspBrushSides[ brush->firstSide + j ].planeNum ]; - dot = DotProduct( point, plane->normal ); - dot -= plane->dist; - if( dot > epsilon ) - inside = qfalse; - } - - /* if inside, return bogus cluster */ - if( inside ) - return -1 - b; - } - - /* if the point made it this far, it's not inside any opaque brushes */ - return cluster; -} - - - -/* -ClusterForPointExtFilter() - ydnar -adds cluster checking against a list of known valid clusters -*/ - -int ClusterForPointExtFilter( vec3_t point, float epsilon, int numClusters, int *clusters ) -{ - int i, cluster; - - - /* get cluster for point */ - cluster = ClusterForPointExt( point, epsilon ); - - /* check if filtering is necessary */ - if( cluster < 0 || numClusters <= 0 || clusters == NULL ) - return cluster; - - /* filter */ - for( i = 0; i < numClusters; i++ ) - { - if( cluster == clusters[ i ] || ClusterVisible( cluster, clusters[ i ] ) ) - return cluster; - } - - /* failed */ - return -1; -} - - - -/* -ShaderForPointInLeaf() - ydnar -checks a point against all brushes in a leaf, returning the shader of the brush -also sets the cumulative surface and content flags for the brush hit -*/ - -int ShaderForPointInLeaf( vec3_t point, int leafNum, float epsilon, int wantContentFlags, int wantSurfaceFlags, int *contentFlags, int *surfaceFlags ) -{ - int i, j; - float dot; - qboolean inside; - int *brushes, numBSPBrushes; - bspLeaf_t *leaf; - bspBrush_t *brush; - bspBrushSide_t *side; - bspPlane_t *plane; - bspShader_t *shader; - int allSurfaceFlags, allContentFlags; - - - /* clear things out first */ - *surfaceFlags = 0; - *contentFlags = 0; - - /* get leaf */ - if( leafNum < 0 ) - return -1; - leaf = &bspLeafs[ leafNum ]; - - /* transparent leaf, so check point against all brushes in the leaf */ - brushes = &bspLeafBrushes[ leaf->firstBSPLeafBrush ]; - numBSPBrushes = leaf->numBSPLeafBrushes; - for( i = 0; i < numBSPBrushes; i++ ) - { - /* get parts */ - brush = &bspBrushes[ brushes[ i ] ]; - - /* check point against all planes */ - inside = qtrue; - allSurfaceFlags = 0; - allContentFlags = 0; - for( j = 0; j < brush->numSides && inside; j++ ) - { - side = &bspBrushSides[ brush->firstSide + j ]; - plane = &bspPlanes[ side->planeNum ]; - dot = DotProduct( point, plane->normal ); - dot -= plane->dist; - if( dot > epsilon ) - inside = qfalse; - else - { - shader = &bspShaders[ side->shaderNum ]; - allSurfaceFlags |= shader->surfaceFlags; - allContentFlags |= shader->contentFlags; - } - } - - /* handle if inside */ - if( inside ) - { - /* if there are desired flags, check for same and continue if they aren't matched */ - if( wantContentFlags && !(wantContentFlags & allContentFlags) ) - continue; - if( wantSurfaceFlags && !(wantSurfaceFlags & allSurfaceFlags) ) - continue; - - /* store the cumulative flags and return the brush shader (which is mostly useless) */ - *surfaceFlags = allSurfaceFlags; - *contentFlags = allContentFlags; - return brush->shaderNum; - } - } - - /* if the point made it this far, it's not inside any brushes */ - return -1; -} - - - -/* -ChopBounds() -chops a bounding box by the plane defined by origin and normal -returns qfalse if the bounds is entirely clipped away - -this is not exactly the fastest way to do this... -*/ - -qboolean ChopBounds( vec3_t mins, vec3_t maxs, vec3_t origin, vec3_t normal ) -{ - /* FIXME: rewrite this so it doesn't use bloody brushes */ - return qtrue; -} - - - -/* -SetupEnvelopes() -calculates each light's effective envelope, -taking into account brightness, type, and pvs. -*/ - -#define LIGHT_EPSILON 0.125f -#define LIGHT_NUDGE 2.0f - -void SetupEnvelopes( qboolean forGrid, qboolean fastFlag ) -{ - int i, x, y, z, x1, y1, z1; - light_t *light, *light2, **owner; - bspLeaf_t *leaf; - vec3_t origin, dir, mins, maxs; - float radius, intensity; - light_t *buckets[ 256 ]; - - - /* early out for weird cases where there are no lights */ - if( lights == NULL ) - return; - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- SetupEnvelopes%s ---\n", fastFlag ? " (fast)" : "" ); - - /* count lights */ - numLights = 0; - numCulledLights = 0; - owner = &lights; - while( *owner != NULL ) - { - /* get light */ - light = *owner; - - /* handle negative lights */ - if( light->photons < 0.0f || light->add < 0.0f ) - { - light->photons *= -1.0f; - light->add *= -1.0f; - light->flags |= LIGHT_NEGATIVE; - } - - /* sunlight? */ - if( light->type == EMIT_SUN ) - { - /* special cased */ - light->cluster = 0; - light->envelope = MAX_WORLD_COORD * 8.0f; - VectorSet( light->mins, MIN_WORLD_COORD * 8.0f, MIN_WORLD_COORD * 8.0f, MIN_WORLD_COORD * 8.0f ); - VectorSet( light->maxs, MAX_WORLD_COORD * 8.0f, MAX_WORLD_COORD * 8.0f, MAX_WORLD_COORD * 8.0f ); - } - - /* everything else */ - else - { - /* get pvs cluster for light */ - light->cluster = ClusterForPointExt( light->origin, LIGHT_EPSILON ); - - /* invalid cluster? */ - if( light->cluster < 0 ) - { - /* nudge the sample point around a bit */ - for( x = 0; x < 4; x++ ) - { - /* two's complement 0, 1, -1, 2, -2, etc */ - x1 = ((x >> 1) ^ (x & 1 ? -1 : 0)) + (x & 1); - - for( y = 0; y < 4; y++ ) - { - y1 = ((y >> 1) ^ (y & 1 ? -1 : 0)) + (y & 1); - - for( z = 0; z < 4; z++ ) - { - z1 = ((z >> 1) ^ (z & 1 ? -1 : 0)) + (z & 1); - - /* nudge origin */ - origin[ 0 ] = light->origin[ 0 ] + (LIGHT_NUDGE * x1); - origin[ 1 ] = light->origin[ 1 ] + (LIGHT_NUDGE * y1); - origin[ 2 ] = light->origin[ 2 ] + (LIGHT_NUDGE * z1); - - /* try at nudged origin */ - light->cluster = ClusterForPointExt( origin, LIGHT_EPSILON ); - if( light->cluster < 0 ) - continue; - - /* set origin */ - VectorCopy( origin, light->origin ); - } - } - } - } - - /* only calculate for lights in pvs and outside of opaque brushes */ - if( light->cluster >= 0 ) - { - /* set light fast flag */ - if( fastFlag ) - light->flags |= LIGHT_FAST_TEMP; - else - light->flags &= ~LIGHT_FAST_TEMP; - if( light->si && light->si->noFast ) - light->flags &= ~(LIGHT_FAST | LIGHT_FAST_TEMP); - - /* clear light envelope */ - light->envelope = 0; - - /* handle area lights */ - if( exactPointToPolygon && light->type == EMIT_AREA && light->w != NULL ) - { - /* ugly hack to calculate extent for area lights, but only done once */ - VectorScale( light->normal, -1.0f, dir ); - for( radius = 100.0f; radius < 130000.0f && light->envelope == 0; radius += 10.0f ) - { - float factor; - - VectorMA( light->origin, radius, light->normal, origin ); - factor = PointToPolygonFormFactor( origin, dir, light->w ); - if( factor < 0.0f ) - factor *= -1.0f; - if( (factor * light->add) <= light->falloffTolerance ) - light->envelope = radius; - } - - /* check for fast mode */ - if( !(light->flags & LIGHT_FAST) && !(light->flags & LIGHT_FAST_TEMP) ) - light->envelope = MAX_WORLD_COORD * 8.0f; - intensity = light->photons; /* hopefully not used */ - } - else - { - radius = 0.0f; - intensity = light->photons; - } - - /* other calcs */ - if( light->envelope <= 0.0f ) - { - /* solve distance for non-distance lights */ - if( !(light->flags & LIGHT_ATTEN_DISTANCE) ) - light->envelope = MAX_WORLD_COORD * 8.0f; - - /* solve distance for linear lights */ - else if( (light->flags & LIGHT_ATTEN_LINEAR ) ) - //% light->envelope = ((intensity / light->falloffTolerance) * linearScale - 1 + radius) / light->fade; - light->envelope = ((intensity * linearScale) - light->falloffTolerance) / light->fade; - - /* - add = angle * light->photons * linearScale - (dist * light->fade); - T = (light->photons * linearScale) - (dist * light->fade); - T + (dist * light->fade) = (light->photons * linearScale); - dist * light->fade = (light->photons * linearScale) - T; - dist = ((light->photons * linearScale) - T) / light->fade; - */ - - /* solve for inverse square falloff */ - else - light->envelope = sqrt( intensity / light->falloffTolerance ) + radius; - - /* - add = light->photons / (dist * dist); - T = light->photons / (dist * dist); - T * (dist * dist) = light->photons; - dist = sqrt( light->photons / T ); - */ - } - - /* chop radius against pvs */ - { - /* clear bounds */ - ClearBounds( mins, maxs ); - - /* check all leaves */ - for( i = 0; i < numBSPLeafs; i++ ) - { - /* get test leaf */ - leaf = &bspLeafs[ i ]; - - /* in pvs? */ - if( leaf->cluster < 0 ) - continue; - if( ClusterVisible( light->cluster, leaf->cluster ) == qfalse ) /* ydnar: thanks Arnout for exposing my stupid error (this never failed before) */ - continue; - - /* add this leafs bbox to the bounds */ - VectorCopy( leaf->mins, origin ); - AddPointToBounds( origin, mins, maxs ); - VectorCopy( leaf->maxs, origin ); - AddPointToBounds( origin, mins, maxs ); - } - - /* test to see if bounds encompass light */ - for( i = 0; i < 3; i++ ) - { - if( mins[ i ] > light->origin[ i ] || maxs[ i ] < light->origin[ i ] ) - { - //% Sys_Printf( "WARNING: Light PVS bounds (%.0f, %.0f, %.0f) -> (%.0f, %.0f, %.0f)\ndo not encompass light %d (%f, %f, %f)\n", - //% mins[ 0 ], mins[ 1 ], mins[ 2 ], - //% maxs[ 0 ], maxs[ 1 ], maxs[ 2 ], - //% numLights, light->origin[ 0 ], light->origin[ 1 ], light->origin[ 2 ] ); - AddPointToBounds( light->origin, mins, maxs ); - } - } - - /* chop the bounds by a plane for area lights and spotlights */ - if( light->type == EMIT_AREA || light->type == EMIT_SPOT ) - ChopBounds( mins, maxs, light->origin, light->normal ); - - /* copy bounds */ - VectorCopy( mins, light->mins ); - VectorCopy( maxs, light->maxs ); - - /* reflect bounds around light origin */ - //% VectorMA( light->origin, -1.0f, origin, origin ); - VectorScale( light->origin, 2, origin ); - VectorSubtract( origin, maxs, origin ); - AddPointToBounds( origin, mins, maxs ); - //% VectorMA( light->origin, -1.0f, mins, origin ); - VectorScale( light->origin, 2, origin ); - VectorSubtract( origin, mins, origin ); - AddPointToBounds( origin, mins, maxs ); - - /* calculate spherical bounds */ - VectorSubtract( maxs, light->origin, dir ); - radius = (float) VectorLength( dir ); - - /* if this radius is smaller than the envelope, then set the envelope to it */ - if( radius < light->envelope ) - { - light->envelope = radius; - //% Sys_FPrintf( SYS_VRB, "PVS Cull (%d): culled\n", numLights ); - } - //% else - //% Sys_FPrintf( SYS_VRB, "PVS Cull (%d): failed (%8.0f > %8.0f)\n", numLights, radius, light->envelope ); - } - - /* add grid/surface only check */ - if( forGrid ) - { - if( !(light->flags & LIGHT_GRID) ) - light->envelope = 0.0f; - } - else - { - if( !(light->flags & LIGHT_SURFACES) ) - light->envelope = 0.0f; - } - } - - /* culled? */ - if( light->cluster < 0 || light->envelope <= 0.0f ) - { - /* debug code */ - //% Sys_Printf( "Culling light: Cluster: %d Envelope: %f\n", light->cluster, light->envelope ); - - /* delete the light */ - numCulledLights++; - *owner = light->next; - if( light->w != NULL ) - free( light->w ); - free( light ); - continue; - } - } - - /* square envelope */ - light->envelope2 = (light->envelope * light->envelope); - - /* increment light count */ - numLights++; - - /* set next light */ - owner = &((**owner).next); - } - - /* bucket sort lights by style */ - memset( buckets, 0, sizeof( buckets ) ); - light2 = NULL; - for( light = lights; light != NULL; light = light2 ) - { - /* get next light */ - light2 = light->next; - - /* filter into correct bucket */ - light->next = buckets[ light->style ]; - buckets[ light->style ] = light; - - /* if any styled light is present, automatically set nocollapse */ - if( light->style != LS_NORMAL ) - noCollapse = qtrue; - } - - /* filter back into light list */ - lights = NULL; - for( i = 255; i >= 0; i-- ) - { - light2 = NULL; - for( light = buckets[ i ]; light != NULL; light = light2 ) - { - light2 = light->next; - light->next = lights; - lights = light; - } - } - - /* emit some statistics */ - Sys_Printf( "%9d total lights\n", numLights ); - Sys_Printf( "%9d culled lights\n", numCulledLights ); -} - - - -/* -CreateTraceLightsForBounds() -creates a list of lights that affect the given bounding box and pvs clusters (bsp leaves) -*/ - -void CreateTraceLightsForBounds( vec3_t mins, vec3_t maxs, vec3_t normal, int numClusters, int *clusters, int flags, trace_t *trace ) -{ - int i; - light_t *light; - vec3_t origin, dir, nullVector = { 0.0f, 0.0f, 0.0f }; - float radius, dist, length; - - - /* potential pre-setup */ - if( numLights == 0 ) - SetupEnvelopes( qfalse, fast ); - - /* debug code */ - //% Sys_Printf( "CTWLFB: (%4.1f %4.1f %4.1f) (%4.1f %4.1f %4.1f)\n", mins[ 0 ], mins[ 1 ], mins[ 2 ], maxs[ 0 ], maxs[ 1 ], maxs[ 2 ] ); - - /* allocate the light list */ - trace->lights = safe_malloc( sizeof( light_t* ) * (numLights + 1) ); - trace->numLights = 0; - - /* calculate spherical bounds */ - VectorAdd( mins, maxs, origin ); - VectorScale( origin, 0.5f, origin ); - VectorSubtract( maxs, origin, dir ); - radius = (float) VectorLength( dir ); - - /* get length of normal vector */ - if( normal != NULL ) - length = VectorLength( normal ); - else - { - normal = nullVector; - length = 0; - } - - /* test each light and see if it reaches the sphere */ - /* note: the attenuation code MUST match LightingAtSample() */ - for( light = lights; light; light = light->next ) - { - /* check zero sized envelope */ - if( light->envelope <= 0 ) - { - lightsEnvelopeCulled++; - continue; - } - - /* check flags */ - if( !(light->flags & flags) ) - continue; - - /* sunlight skips all this nonsense */ - if( light->type != EMIT_SUN ) - { - /* sun only? */ - if( sunOnly ) - continue; - - /* check against pvs cluster */ - if( numClusters > 0 && clusters != NULL ) - { - for( i = 0; i < numClusters; i++ ) - { - if( ClusterVisible( light->cluster, clusters[ i ] ) ) - break; - } - - /* fixme! */ - if( i == numClusters ) - { - lightsClusterCulled++; - continue; - } - } - - /* if the light's bounding sphere intersects with the bounding sphere then this light needs to be tested */ - VectorSubtract( light->origin, origin, dir ); - dist = VectorLength( dir ); - dist -= light->envelope; - dist -= radius; - if( dist > 0 ) - { - lightsEnvelopeCulled++; - continue; - } - - /* check bounding box against light's pvs envelope (note: this code never eliminated any lights, so disabling it) */ - #if 0 - skip = qfalse; - for( i = 0; i < 3; i++ ) - { - if( mins[ i ] > light->maxs[ i ] || maxs[ i ] < light->mins[ i ] ) - skip = qtrue; - } - if( skip ) - { - lightsBoundsCulled++; - continue; - } - #endif - } - - /* planar surfaces (except twosided surfaces) have a couple more checks */ - if( length > 0.0f && trace->twoSided == qfalse ) - { - /* lights coplanar with a surface won't light it */ - if( !(light->flags & LIGHT_TWOSIDED) && DotProduct( light->normal, normal ) > 0.999f ) - { - lightsPlaneCulled++; - continue; - } - - /* check to see if light is behind the plane */ - if( DotProduct( light->origin, normal ) - DotProduct( origin, normal ) < -1.0f ) - { - lightsPlaneCulled++; - continue; - } - } - - /* add this light */ - trace->lights[ trace->numLights++ ] = light; - } - - /* make last night null */ - trace->lights[ trace->numLights ] = NULL; -} - - - -void FreeTraceLights( trace_t *trace ) -{ - if( trace->lights != NULL ) - free( trace->lights ); -} - - - -/* -CreateTraceLightsForSurface() -creates a list of lights that can potentially affect a drawsurface -*/ - -void CreateTraceLightsForSurface( int num, trace_t *trace ) -{ - int i; - vec3_t mins, maxs, normal; - bspDrawVert_t *dv; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - - - /* dummy check */ - if( num < 0 ) - return; - - /* get drawsurface and info */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* get the mins/maxs for the dsurf */ - ClearBounds( mins, maxs ); - VectorCopy( bspDrawVerts[ ds->firstVert ].normal, normal ); - for( i = 0; i < ds->numVerts; i++ ) - { - dv = &yDrawVerts[ ds->firstVert + i ]; - AddPointToBounds( dv->xyz, mins, maxs ); - if( !VectorCompare( dv->normal, normal ) ) - VectorClear( normal ); - } - - /* create the lights for the bounding box */ - CreateTraceLightsForBounds( mins, maxs, normal, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ], LIGHT_SURFACES, trace ); -} - -///////////////////////////////////////////////////////////// - -#define FLOODLIGHT_CONE_ANGLE 88 /* degrees */ -#define FLOODLIGHT_NUM_ANGLE_STEPS 16 -#define FLOODLIGHT_NUM_ELEVATION_STEPS 4 -#define FLOODLIGHT_NUM_VECTORS (FLOODLIGHT_NUM_ANGLE_STEPS * FLOODLIGHT_NUM_ELEVATION_STEPS) - -static vec3_t floodVectors[ FLOODLIGHT_NUM_VECTORS ]; -static int numFloodVectors = 0; - -void SetupFloodLight( void ) -{ - int i, j; - float angle, elevation, angleStep, elevationStep; - const char *value; - double v1,v2,v3,v4,v5,v6; - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- SetupFloodLight ---\n" ); - - /* calculate angular steps */ - angleStep = DEG2RAD( 360.0f / FLOODLIGHT_NUM_ANGLE_STEPS ); - elevationStep = DEG2RAD( FLOODLIGHT_CONE_ANGLE / FLOODLIGHT_NUM_ELEVATION_STEPS ); - - /* iterate angle */ - angle = 0.0f; - for( i = 0, angle = 0.0f; i < FLOODLIGHT_NUM_ANGLE_STEPS; i++, angle += angleStep ) - { - /* iterate elevation */ - for( j = 0, elevation = elevationStep * 0.5f; j < FLOODLIGHT_NUM_ELEVATION_STEPS; j++, elevation += elevationStep ) - { - floodVectors[ numFloodVectors ][ 0 ] = sin( elevation ) * cos( angle ); - floodVectors[ numFloodVectors ][ 1 ] = sin( elevation ) * sin( angle ); - floodVectors[ numFloodVectors ][ 2 ] = cos( elevation ); - numFloodVectors++; - } - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d numFloodVectors\n", numFloodVectors ); - - /* floodlight */ - value = ValueForKey( &entities[ 0 ], "_floodlight" ); - - if( value[ 0 ] != '\0' ) - { - v1=v2=v3=0; - v4=floodlightDistance; - v5=floodlightIntensity; - v6=floodlightDirectionScale; - - sscanf( value, "%lf %lf %lf %lf %lf %lf", &v1, &v2, &v3, &v4, &v5); - - floodlightRGB[0]=v1; - floodlightRGB[1]=v2; - floodlightRGB[2]=v3; - - if (VectorLength(floodlightRGB)==0) - { - VectorSet(floodlightRGB,240,240,255); - } - - if (v4<1) v4=1024; - if (v5<1) v5=128; - if (v6<0) v6=1; - - floodlightDistance=v4; - floodlightIntensity=v5; - floodlightDirectionScale=v6; - - floodlighty = qtrue; - Sys_Printf( "FloodLighting enabled via worldspawn _floodlight key.\n" ); - } - else - { - VectorSet(floodlightRGB,240,240,255); - //floodlighty = qtrue; - //Sys_Printf( "FloodLighting enabled via worldspawn _floodlight key.\n" ); - } - VectorNormalize(floodlightRGB,floodlightRGB); -} - -/* -FloodLightForSample() -calculates floodlight value for a given sample -once again, kudos to the dirtmapping coder -*/ - -float FloodLightForSample( trace_t *trace , float floodLightDistance, qboolean floodLightLowQuality) -{ - int i; - float d; - float contribution; - int sub = 0; - float gatherLight, outLight; - vec3_t normal, worldUp, myUp, myRt, direction, displacement; - float dd; - int vecs = 0; - - gatherLight=0; - /* dummy check */ - //if( !dirty ) - // return 1.0f; - if( trace == NULL || trace->cluster < 0 ) - return 0.0f; - - - /* setup */ - dd = floodLightDistance; - VectorCopy( trace->normal, normal ); - - /* check if the normal is aligned to the world-up */ - if( normal[ 0 ] == 0.0f && normal[ 1 ] == 0.0f && ( normal[ 2 ] == 1.0f || normal[ 2 ] == -1.0f ) ) - { - if( normal[ 2 ] == 1.0f ) - { - VectorSet( myRt, 1.0f, 0.0f, 0.0f ); - VectorSet( myUp, 0.0f, 1.0f, 0.0f ); - } - else if( normal[ 2 ] == -1.0f ) - { - VectorSet( myRt, -1.0f, 0.0f, 0.0f ); - VectorSet( myUp, 0.0f, 1.0f, 0.0f ); - } - } - else - { - VectorSet( worldUp, 0.0f, 0.0f, 1.0f ); - CrossProduct( normal, worldUp, myRt ); - VectorNormalize( myRt, myRt ); - CrossProduct( myRt, normal, myUp ); - VectorNormalize( myUp, myUp ); - } - - /* vortex: optimise floodLightLowQuality a bit */ - if ( floodLightLowQuality == qtrue ) - { - /* iterate through ordered vectors */ - for( i = 0; i < numFloodVectors; i++ ) - if (rand()%10 != 0 ) continue; - } - else - { - /* iterate through ordered vectors */ - for( i = 0; i < numFloodVectors; i++ ) - { - vecs++; - - /* transform vector into tangent space */ - direction[ 0 ] = myRt[ 0 ] * floodVectors[ i ][ 0 ] + myUp[ 0 ] * floodVectors[ i ][ 1 ] + normal[ 0 ] * floodVectors[ i ][ 2 ]; - direction[ 1 ] = myRt[ 1 ] * floodVectors[ i ][ 0 ] + myUp[ 1 ] * floodVectors[ i ][ 1 ] + normal[ 1 ] * floodVectors[ i ][ 2 ]; - direction[ 2 ] = myRt[ 2 ] * floodVectors[ i ][ 0 ] + myUp[ 2 ] * floodVectors[ i ][ 1 ] + normal[ 2 ] * floodVectors[ i ][ 2 ]; - - /* set endpoint */ - VectorMA( trace->origin, dd, direction, trace->end ); - - //VectorMA( trace->origin, 1, direction, trace->origin ); - - SetupTrace( trace ); - /* trace */ - TraceLine( trace ); - contribution=1; - - if ( trace->compileFlags & C_SKY || trace->compileFlags & C_TRANSLUCENT ) - { - contribution=1.0f; - } - else if ( trace->opaque ) - { - VectorSubtract( trace->hit, trace->origin, displacement ); - d=VectorLength( displacement ); - - // d=trace->distance; - //if (d>256) gatherDirt+=1; - contribution=d/dd; - if (contribution>1) contribution=1.0f; - - //gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); - } - - gatherLight+=contribution; - } - } - - /* early out */ - if( gatherLight <= 0.0f ) - return 0.0f; - - sub=vecs; - - if (sub<1) sub=1; - gatherLight/=(sub); - - outLight=gatherLight; - if( outLight > 1.0f ) - outLight = 1.0f; - - /* return to sender */ - return outLight; -} - -/* -FloodLightRawLightmap -lighttracer style ambient occlusion light hack. -Kudos to the dirtmapping author for most of this source. -VorteX: modified to floodlight up custom surfaces (q3map_floodLight) -VorteX: fixed problems with deluxemapping -*/ - -// floodlight pass on a lightmap -void FloodLightRawLightmapPass( rawLightmap_t *lm , vec3_t lmFloodLightRGB, float lmFloodLightIntensity, float lmFloodLightDistance, qboolean lmFloodLightLowQuality, float floodlightDirectionScale) -{ - int i, x, y, *cluster; - float *origin, *normal, *floodlight, floodLightAmount; - surfaceInfo_t *info; - trace_t trace; - // int sx, sy; - // float samples, average, *floodlight2; - - memset(&trace,0,sizeof(trace_t)); - - /* setup trace */ - trace.testOcclusion = qtrue; - trace.forceSunlight = qfalse; - trace.twoSided = qtrue; - trace.recvShadows = lm->recvShadows; - trace.numSurfaces = lm->numLightSurfaces; - trace.surfaces = &lightSurfaces[ lm->firstLightSurface ]; - trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; - trace.testAll = qfalse; - trace.distance = 1024; - - /* twosided lighting (may or may not be a good idea for lightmapped stuff) */ - //trace.twoSided = qfalse; - for( i = 0; i < trace.numSurfaces; i++ ) - { - /* get surface */ - info = &surfaceInfos[ trace.surfaces[ i ] ]; - - /* check twosidedness */ - if( info->si->twoSided ) - { - trace.twoSided = qtrue; - break; - } - } - - /* gather floodlight */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - cluster = SUPER_CLUSTER( x, y ); - origin = SUPER_ORIGIN( x, y ); - normal = SUPER_NORMAL( x, y ); - floodlight = SUPER_FLOODLIGHT( x, y ); - - /* set default dirt */ - *floodlight = 0.0f; - - /* only look at mapped luxels */ - if( *cluster < 0 ) - continue; - - /* copy to trace */ - trace.cluster = *cluster; - VectorCopy( origin, trace.origin ); - VectorCopy( normal, trace.normal ); - - /* get floodlight */ - floodLightAmount = FloodLightForSample( &trace , lmFloodLightDistance, lmFloodLightLowQuality)*lmFloodLightIntensity; - - /* add floodlight */ - floodlight[0] += lmFloodLightRGB[0]*floodLightAmount; - floodlight[1] += lmFloodLightRGB[1]*floodLightAmount; - floodlight[2] += lmFloodLightRGB[2]*floodLightAmount; - floodlight[3] += floodlightDirectionScale; - } - } - - /* testing no filtering */ - return; - -#if 0 - - /* filter "dirt" */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - cluster = SUPER_CLUSTER( x, y ); - floodlight = SUPER_FLOODLIGHT(x, y ); - - /* filter dirt by adjacency to unmapped luxels */ - average = *floodlight; - samples = 1.0f; - for( sy = (y - 1); sy <= (y + 1); sy++ ) - { - if( sy < 0 || sy >= lm->sh ) - continue; - - for( sx = (x - 1); sx <= (x + 1); sx++ ) - { - if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) - continue; - - /* get neighboring luxel */ - cluster = SUPER_CLUSTER( sx, sy ); - floodlight2 = SUPER_FLOODLIGHT( sx, sy ); - if( *cluster < 0 || *floodlight2 <= 0.0f ) - continue; - - /* add it */ - average += *floodlight2; - samples += 1.0f; - } - - /* bail */ - if( samples <= 0.0f ) - break; - } - - /* bail */ - if( samples <= 0.0f ) - continue; - - /* scale dirt */ - *floodlight = average / samples; - } - } -#endif -} - -void FloodLightRawLightmap( int rawLightmapNum ) -{ - rawLightmap_t *lm; - - /* bail if this number exceeds the number of raw lightmaps */ - if( rawLightmapNum >= numRawLightmaps ) - return; - /* get lightmap */ - lm = &rawLightmaps[ rawLightmapNum ]; - - /* global pass */ - if (floodlighty && floodlightIntensity) - FloodLightRawLightmapPass(lm, floodlightRGB, floodlightIntensity, floodlightDistance, floodlight_lowquality, floodlightDirectionScale); - - /* custom pass */ - if (lm->floodlightIntensity) - { - FloodLightRawLightmapPass(lm, lm->floodlightRGB, lm->floodlightIntensity, lm->floodlightDistance, qfalse, lm->floodlightDirectionScale); - numSurfacesFloodlighten += 1; - } -} - -void FloodlightRawLightmaps() -{ - Sys_Printf( "--- FloodlightRawLightmap ---\n" ); - numSurfacesFloodlighten = 0; - RunThreadsOnIndividual( numRawLightmaps, qtrue, FloodLightRawLightmap ); - Sys_Printf( "%9d custom lightmaps floodlighted\n", numSurfacesFloodlighten ); -} - -/* -FloodLightIlluminate() -illuminate floodlight into lightmap luxels -*/ - -void FloodlightIlluminateLightmap( rawLightmap_t *lm ) -{ - float *luxel, *floodlight, *deluxel, *normal; - int *cluster; - float brightness; - int x, y, lightmapNum; - - /* walk lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - - /* apply floodlight to each luxel */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get floodlight */ - floodlight = SUPER_FLOODLIGHT( x, y ); - if (!floodlight[0] && !floodlight[1] && !floodlight[2]) - continue; - - /* get cluster */ - cluster = SUPER_CLUSTER( x, y ); - - /* only process mapped luxels */ - if( *cluster < 0 ) - continue; - - /* get particulars */ - luxel = SUPER_LUXEL( lightmapNum, x, y ); - deluxel = SUPER_DELUXEL( x, y ); - - /* add to lightmap */ - luxel[0]+=floodlight[0]; - luxel[1]+=floodlight[1]; - luxel[2]+=floodlight[2]; - - if (luxel[3]==0) luxel[3]=1; - - /* add to deluxemap */ - if (deluxemap && floodlight[3] > 0) - { - vec3_t lightvector; - - normal = SUPER_NORMAL( x, y ); - brightness = RGBTOGRAY( floodlight ) * ( 1.0f/255.0f ) * floodlight[3]; - - // use AT LEAST this amount of contribution from ambient for the deluxemap, fixes points that receive ZERO light - if(brightness < 0.00390625f) - brightness = 0.00390625f; - - VectorScale( normal, brightness, lightvector ); - VectorAdd( deluxel, lightvector, deluxel ); - } - } - } - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/lightmaps.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/lightmaps.c deleted file mode 100644 index 13f5c533..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/lightmaps.c +++ /dev/null @@ -1,119 +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 "qbsp.h" - - -/* - - Lightmap allocation has to be done after all flood filling and - visible surface determination. - -*/ - -int numSortShaders; -mapDrawSurface_t **surfsOnShader; -int allocatedSurfsOnShader; - - -int allocated[ LIGHTMAP_WIDTH ]; - -int numLightmaps = 1; -int c_exactLightmap = 0; -int c_planarPatch = 0; -int c_nonplanarLightmap = 0; - - -void PrepareNewLightmap( void ) { - memset( allocated, 0, sizeof( allocated ) ); - numLightmaps++; -} - -/* -=============== -AllocLMBlock - -returns a texture number and the position inside it -=============== -*/ -qboolean AllocLMBlock (int w, int h, int *x, int *y) -{ - int i, j; - int best, best2; - - best = LIGHTMAP_HEIGHT; - - for ( i=0 ; i <= LIGHTMAP_WIDTH-w ; i++ ) { - best2 = 0; - - for (j=0 ; j= best) { - break; - } - if (allocated[i+j] > best2) { - best2 = allocated[i+j]; - } - } - if (j == w) { // this is a valid spot - *x = i; - *y = best = best2; - } - } - - if (best + h > LIGHTMAP_HEIGHT) { - return qfalse; - } - - for (i=0 ; i> 8; - buffer[ 14 ] = height & 255; - buffer[ 15 ] = height >> 8; - buffer[ 16 ] = 24; - - /* swap rgb to bgr */ - c = (width * height * 3) + 18; - for( i = 18; i < c; i += 3 ) - { - buffer[ i ] = data[ i - 18 + 2 ]; /* blue */ - buffer[ i + 1 ] = data[ i - 18 + 1 ]; /* green */ - buffer[ i + 2 ] = data[ i - 18 + 0 ]; /* red */ - } - - /* write it and free the buffer */ - file = fopen( filename, "wb" ); - if( file == NULL ) - Error( "Unable to open %s for writing", filename ); - - /* flip vertically? */ - if( flip ) - { - fwrite( buffer, 1, 18, file ); - for( in = buffer + ((height - 1) * width * 3) + 18; in >= buffer; in -= (width * 3) ) - fwrite( in, 1, (width * 3), file ); - } - else - fwrite( buffer, 1, c, file ); - - /* close the file */ - fclose( file ); - free( buffer ); -} - - - -/* -ExportLightmaps() -exports the lightmaps as a list of numbered tga images -*/ - -void ExportLightmaps( void ) -{ - int i; - char dirname[ 1024 ], filename[ 1024 ]; - byte *lightmap; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- ExportLightmaps ---\n"); - - /* do some path mangling */ - strcpy( dirname, source ); - StripExtension( dirname ); - - /* sanity check */ - if( bspLightBytes == NULL ) - { - Sys_Printf( "WARNING: No BSP lightmap data\n" ); - return; - } - - /* make a directory for the lightmaps */ - Q_mkdir( dirname ); - - /* iterate through the lightmaps */ - for( i = 0, lightmap = bspLightBytes; lightmap < (bspLightBytes + numBSPLightBytes); i++, lightmap += (game->lightmapSize * game->lightmapSize * 3) ) - { - /* write a tga image out */ - sprintf( filename, "%s/lightmap_%04d.tga", dirname, i ); - Sys_Printf( "Writing %s\n", filename ); - WriteTGA24( filename, lightmap, game->lightmapSize, game->lightmapSize, qfalse ); - } -} - - - -/* -ExportLightmapsMain() -exports the lightmaps as a list of numbered tga images -*/ - -int ExportLightmapsMain( int argc, char **argv ) -{ - /* arg checking */ - if( argc < 1 ) - { - Sys_Printf( "Usage: q3map -export [-v] \n" ); - return 0; - } - - /* do some path mangling */ - strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - - /* load the bsp */ - Sys_Printf( "Loading %s\n", source ); - LoadBSPFile( source ); - - /* export the lightmaps */ - ExportLightmaps(); - - /* return to sender */ - return 0; -} - - - -/* -ImportLightmapsMain() -imports the lightmaps from a list of numbered tga images -*/ - -int ImportLightmapsMain( int argc, char **argv ) -{ - int i, x, y, len, width, height; - char dirname[ 1024 ], filename[ 1024 ]; - byte *lightmap, *buffer, *pixels, *in, *out; - - - /* arg checking */ - if( argc < 1 ) - { - Sys_Printf( "Usage: q3map -import [-v] \n" ); - return 0; - } - - /* do some path mangling */ - strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - - /* load the bsp */ - Sys_Printf( "Loading %s\n", source ); - LoadBSPFile( source ); - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- ImportLightmaps ---\n"); - - /* do some path mangling */ - strcpy( dirname, source ); - StripExtension( dirname ); - - /* sanity check */ - if( bspLightBytes == NULL ) - Error( "No lightmap data" ); - - /* make a directory for the lightmaps */ - Q_mkdir( dirname ); - - /* iterate through the lightmaps */ - for( i = 0, lightmap = bspLightBytes; lightmap < (bspLightBytes + numBSPLightBytes); i++, lightmap += (game->lightmapSize * game->lightmapSize * 3) ) - { - /* read a tga image */ - sprintf( filename, "%s/lightmap_%04d.tga", dirname, i ); - Sys_Printf( "Loading %s\n", filename ); - buffer = NULL; - len = vfsLoadFile( filename, (void*) &buffer, -1 ); - if( len < 0 ) - { - Sys_Printf( "WARNING: Unable to load image %s\n", filename ); - continue; - } - - /* parse file into an image */ - pixels = NULL; - LoadTGABuffer( buffer, buffer + len, &pixels, &width, &height ); - free( buffer ); - - /* sanity check it */ - if( pixels == NULL ) - { - Sys_Printf( "WARNING: Unable to load image %s\n", filename ); - continue; - } - if( width != game->lightmapSize || height != game->lightmapSize ) - Sys_Printf( "WARNING: Image %s is not the right size (%d, %d) != (%d, %d)\n", - filename, width, height, game->lightmapSize, game->lightmapSize ); - - /* copy the pixels */ - in = pixels; - for( y = 1; y <= game->lightmapSize; y++ ) - { - out = lightmap + ((game->lightmapSize - y) * game->lightmapSize * 3); - for( x = 0; x < game->lightmapSize; x++, in += 4, out += 3 ) - VectorCopy( in, out ); - } - - /* free the image */ - free( pixels ); - } - - /* write the bsp */ - Sys_Printf( "writing %s\n", source ); - WriteBSPFile( source ); - - /* return to sender */ - return 0; -} - - - -/* ------------------------------------------------------------------------------- - -this section deals with projecting a lightmap onto a raw drawsurface - -------------------------------------------------------------------------------- */ - -/* -CompareLightSurface() -compare function for qsort() -*/ - -static int CompareLightSurface( const void *a, const void *b ) -{ - shaderInfo_t *asi, *bsi; - - - /* get shaders */ - asi = surfaceInfos[ *((const int*) a) ].si; - bsi = surfaceInfos[ *((const int*) b) ].si; - - /* dummy check */ - if( asi == NULL ) - return -1; - if( bsi == NULL ) - return 1; - - /* compare shader names */ - return strcmp( asi->shader, bsi->shader ); -} - - - -/* -FinishRawLightmap() -allocates a raw lightmap's necessary buffers -*/ - -void FinishRawLightmap( rawLightmap_t *lm ) -{ - int i, j, c, size, *sc; - float is; - surfaceInfo_t *info; - - - /* sort light surfaces by shader name */ - qsort( &lightSurfaces[ lm->firstLightSurface ], lm->numLightSurfaces, sizeof( int ), CompareLightSurface ); - - /* count clusters */ - lm->numLightClusters = 0; - for( i = 0; i < lm->numLightSurfaces; i++ ) - { - /* get surface info */ - info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + i ] ]; - - /* add surface clusters */ - lm->numLightClusters += info->numSurfaceClusters; - } - - /* allocate buffer for clusters and copy */ - lm->lightClusters = safe_malloc( lm->numLightClusters * sizeof( *lm->lightClusters ) ); - c = 0; - for( i = 0; i < lm->numLightSurfaces; i++ ) - { - /* get surface info */ - info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + i ] ]; - - /* add surface clusters */ - for( j = 0; j < info->numSurfaceClusters; j++ ) - lm->lightClusters[ c++ ] = surfaceClusters[ info->firstSurfaceCluster + j ]; - } - - /* set styles */ - lm->styles[ 0 ] = LS_NORMAL; - for( i = 1; i < MAX_LIGHTMAPS; i++ ) - lm->styles[ i ] = LS_NONE; - - /* set supersampling size */ - lm->sw = lm->w * superSample; - lm->sh = lm->h * superSample; - - /* add to super luxel count */ - numRawSuperLuxels += (lm->sw * lm->sh); - - /* manipulate origin/vecs for supersampling */ - if( superSample > 1 && lm->vecs != NULL ) - { - /* calc inverse supersample */ - is = 1.0f / superSample; - - /* scale the vectors and shift the origin */ - #if 1 - /* new code that works for arbitrary supersampling values */ - VectorMA( lm->origin, -0.5, lm->vecs[ 0 ], lm->origin ); - VectorMA( lm->origin, -0.5, lm->vecs[ 1 ], lm->origin ); - VectorScale( lm->vecs[ 0 ], is, lm->vecs[ 0 ] ); - VectorScale( lm->vecs[ 1 ], is, lm->vecs[ 1 ] ); - VectorMA( lm->origin, is, lm->vecs[ 0 ], lm->origin ); - VectorMA( lm->origin, is, lm->vecs[ 1 ], lm->origin ); - #else - /* old code that only worked with a value of 2 */ - VectorScale( lm->vecs[ 0 ], is, lm->vecs[ 0 ] ); - VectorScale( lm->vecs[ 1 ], is, lm->vecs[ 1 ] ); - VectorMA( lm->origin, -is, lm->vecs[ 0 ], lm->origin ); - VectorMA( lm->origin, -is, lm->vecs[ 1 ], lm->origin ); - #endif - } - - /* allocate bsp lightmap storage */ - size = lm->w * lm->h * BSP_LUXEL_SIZE * sizeof( float ); - if( lm->bspLuxels[ 0 ] == NULL ) - lm->bspLuxels[ 0 ] = safe_malloc( size ); - memset( lm->bspLuxels[ 0 ], 0, size ); - - /* allocate radiosity lightmap storage */ - if( bounce ) - { - size = lm->w * lm->h * RAD_LUXEL_SIZE * sizeof( float ); - if( lm->radLuxels[ 0 ] == NULL ) - lm->radLuxels[ 0 ] = safe_malloc( size ); - memset( lm->radLuxels[ 0 ], 0, size ); - } - - /* allocate sampling lightmap storage */ - size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); - if( lm->superLuxels[ 0 ] == NULL ) - lm->superLuxels[ 0 ] = safe_malloc( size ); - memset( lm->superLuxels[ 0 ], 0, size ); - - /* allocate origin map storage */ - size = lm->sw * lm->sh * SUPER_ORIGIN_SIZE * sizeof( float ); - if( lm->superOrigins == NULL ) - lm->superOrigins = safe_malloc( size ); - memset( lm->superOrigins, 0, size ); - - /* allocate normal map storage */ - size = lm->sw * lm->sh * SUPER_NORMAL_SIZE * sizeof( float ); - if( lm->superNormals == NULL ) - lm->superNormals = safe_malloc( size ); - memset( lm->superNormals, 0, size ); - - /* allocate floodlight map storage */ - size = lm->sw * lm->sh * SUPER_FLOODLIGHT_SIZE * sizeof( float ); - if( lm->superFloodLight == NULL ) - lm->superFloodLight = safe_malloc( size ); - memset( lm->superFloodLight, 0, size ); - - /* allocate cluster map storage */ - size = lm->sw * lm->sh * sizeof( int ); - if( lm->superClusters == NULL ) - lm->superClusters = safe_malloc( size ); - size = lm->sw * lm->sh; - sc = lm->superClusters; - for( i = 0; i < size; i++ ) - (*sc++) = CLUSTER_UNMAPPED; - - /* deluxemap allocation */ - if( deluxemap ) - { - /* allocate sampling deluxel storage */ - size = lm->sw * lm->sh * SUPER_DELUXEL_SIZE * sizeof( float ); - if( lm->superDeluxels == NULL ) - lm->superDeluxels = safe_malloc( size ); - memset( lm->superDeluxels, 0, size ); - - /* allocate bsp deluxel storage */ - size = lm->w * lm->h * BSP_DELUXEL_SIZE * sizeof( float ); - if( lm->bspDeluxels == NULL ) - lm->bspDeluxels = safe_malloc( size ); - memset( lm->bspDeluxels, 0, size ); - } - - /* add to count */ - numLuxels += (lm->sw * lm->sh); -} - - - -/* -AddPatchToRawLightmap() -projects a lightmap for a patch surface -since lightmap calculation for surfaces is now handled in a general way (light_ydnar.c), -it is no longer necessary for patch verts to fall exactly on a lightmap sample -based on AllocateLightmapForPatch() -*/ - -qboolean AddPatchToRawLightmap( int num, rawLightmap_t *lm ) -{ - bspDrawSurface_t *ds; - surfaceInfo_t *info; - int x, y; - bspDrawVert_t *verts, *a, *b; - vec3_t delta; - mesh_t src, *subdivided, *mesh; - float sBasis, tBasis, s, t; - float length, widthTable[ MAX_EXPANDED_AXIS ], heightTable[ MAX_EXPANDED_AXIS ]; - - - /* patches finish a raw lightmap */ - lm->finished = qtrue; - - /* get surface and info */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* make a temporary mesh from the drawsurf */ - src.width = ds->patchWidth; - src.height = ds->patchHeight; - src.verts = &yDrawVerts[ ds->firstVert ]; - //% subdivided = SubdivideMesh( src, 8, 512 ); - subdivided = SubdivideMesh2( src, info->patchIterations ); - - /* fit it to the curve and remove colinear verts on rows/columns */ - PutMeshOnCurve( *subdivided ); - mesh = RemoveLinearMeshColumnsRows( subdivided ); - FreeMesh( subdivided ); - - /* find the longest distance on each row/column */ - verts = mesh->verts; - memset( widthTable, 0, sizeof( widthTable ) ); - memset( heightTable, 0, sizeof( heightTable ) ); - for( y = 0; y < mesh->height; y++ ) - { - for( x = 0; x < mesh->width; x++ ) - { - /* get width */ - if( x + 1 < mesh->width ) - { - a = &verts[ (y * mesh->width) + x ]; - b = &verts[ (y * mesh->width) + x + 1 ]; - VectorSubtract( a->xyz, b->xyz, delta ); - length = VectorLength( delta ); - if( length > widthTable[ x ] ) - widthTable[ x ] = length; - } - - /* get height */ - if( y + 1 < mesh->height ) - { - a = &verts[ (y * mesh->width) + x ]; - b = &verts[ ((y + 1) * mesh->width) + x ]; - VectorSubtract( a->xyz, b->xyz, delta ); - length = VectorLength( delta ); - if( length > heightTable[ y ] ) - heightTable[ y ] = length; - } - } - } - - /* determine lightmap width */ - length = 0; - for( x = 0; x < (mesh->width - 1); x++ ) - length += widthTable[ x ]; - lm->w = ceil( length / lm->sampleSize ) + 1; - if( lm->w < ds->patchWidth ) - lm->w = ds->patchWidth; - if( lm->w > lm->customWidth ) - lm->w = lm->customWidth; - sBasis = (float) (lm->w - 1) / (float) (ds->patchWidth - 1); - - /* determine lightmap height */ - length = 0; - for( y = 0; y < (mesh->height - 1); y++ ) - length += heightTable[ y ]; - lm->h = ceil( length / lm->sampleSize ) + 1; - if( lm->h < ds->patchHeight ) - lm->h = ds->patchHeight; - if( lm->h > lm->customHeight ) - lm->h = lm->customHeight; - tBasis = (float) (lm->h - 1) / (float) (ds->patchHeight - 1); - - /* free the temporary mesh */ - FreeMesh( mesh ); - - /* set the lightmap texture coordinates in yDrawVerts */ - lm->wrap[ 0 ] = qtrue; - lm->wrap[ 1 ] = qtrue; - verts = &yDrawVerts[ ds->firstVert ]; - for( y = 0; y < ds->patchHeight; y++ ) - { - t = (tBasis * y) + 0.5f; - for( x = 0; x < ds->patchWidth; x++ ) - { - s = (sBasis * x) + 0.5f; - verts[ (y * ds->patchWidth) + x ].lightmap[ 0 ][ 0 ] = s * superSample; - verts[ (y * ds->patchWidth) + x ].lightmap[ 0 ][ 1 ] = t * superSample; - - if( y == 0 && !VectorCompare( verts[ x ].xyz, verts[ ((ds->patchHeight - 1) * ds->patchWidth) + x ].xyz ) ) - lm->wrap[ 1 ] = qfalse; - } - - if( !VectorCompare( verts[ (y * ds->patchWidth) ].xyz, verts[ (y * ds->patchWidth) + (ds->patchWidth - 1) ].xyz ) ) - lm->wrap[ 0 ] = qfalse; - } - - /* debug code: */ - //% Sys_Printf( "wrap S: %d wrap T: %d\n", lm->wrap[ 0 ], lm->wrap[ 1 ] ); - //% if( lm->w > (ds->lightmapWidth & 0xFF) || lm->h > (ds->lightmapHeight & 0xFF) ) - //% Sys_Printf( "Patch lightmap: (%3d %3d) > (%3d, %3d)\n", lm->w, lm->h, ds->lightmapWidth & 0xFF, ds->lightmapHeight & 0xFF ); - //% ds->lightmapWidth = lm->w | (ds->lightmapWidth & 0xFFFF0000); - //% ds->lightmapHeight = lm->h | (ds->lightmapHeight & 0xFFFF0000); - - /* add to counts */ - numPatchesLightmapped++; - - /* return */ - return qtrue; -} - - - -/* -AddSurfaceToRawLightmap() -projects a lightmap for a surface -based on AllocateLightmapForSurface() -*/ - -qboolean AddSurfaceToRawLightmap( int num, rawLightmap_t *lm ) -{ - bspDrawSurface_t *ds, *ds2; - surfaceInfo_t *info, *info2; - int num2, n, i, axisNum; - float s, t, d, len, sampleSize; - vec3_t mins, maxs, origin, faxis, size, exactSize, delta, normalized, vecs[ 2 ]; - vec4_t plane; - bspDrawVert_t *verts; - - - /* get surface and info */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* add the surface to the raw lightmap */ - lightSurfaces[ numLightSurfaces++ ] = num; - lm->numLightSurfaces++; - - /* does this raw lightmap already have any surfaces? */ - if( lm->numLightSurfaces > 1 ) - { - /* surface and raw lightmap must have the same lightmap projection axis */ - if( VectorCompare( info->axis, lm->axis ) == qfalse ) - return qfalse; - - /* match identical attributes */ - if( info->sampleSize != lm->sampleSize || - info->entityNum != lm->entityNum || - info->recvShadows != lm->recvShadows || - info->si->lmCustomWidth != lm->customWidth || - info->si->lmCustomHeight != lm->customHeight || - info->si->lmBrightness != lm->brightness || - info->si->lmFilterRadius != lm->filterRadius || - info->si->splotchFix != lm->splotchFix ) - return qfalse; - - /* surface bounds must intersect with raw lightmap bounds */ - for( i = 0; i < 3; i++ ) - { - if( info->mins[ i ] > lm->maxs[ i ] ) - return qfalse; - if( info->maxs[ i ] < lm->mins[ i ] ) - return qfalse; - } - - /* plane check (fixme: allow merging of nonplanars) */ - if( info->si->lmMergable == qfalse ) - { - if( info->plane == NULL || lm->plane == NULL ) - return qfalse; - - /* compare planes */ - for( i = 0; i < 4; i++ ) - if( fabs( info->plane[ i ] - lm->plane[ i ] ) > EQUAL_EPSILON ) - return qfalse; - } - - /* debug code hacking */ - //% if( lm->numLightSurfaces > 1 ) - //% return qfalse; - } - - /* set plane */ - if( info->plane == NULL ) - lm->plane = NULL; - - /* add surface to lightmap bounds */ - AddPointToBounds( info->mins, lm->mins, lm->maxs ); - AddPointToBounds( info->maxs, lm->mins, lm->maxs ); - - /* check to see if this is a non-planar patch */ - if( ds->surfaceType == MST_PATCH && - lm->axis[ 0 ] == 0.0f && lm->axis[ 1 ] == 0.0f && lm->axis[ 2 ] == 0.0f ) - return AddPatchToRawLightmap( num, lm ); - - /* start with initially requested sample size */ - sampleSize = lm->sampleSize; - - /* round to the lightmap resolution */ - for( i = 0; i < 3; i++ ) - { - exactSize[ i ] = lm->maxs[ i ] - lm->mins[ i ]; - mins[ i ] = sampleSize * floor( lm->mins[ i ] / sampleSize ); - maxs[ i ] = sampleSize * ceil( lm->maxs[ i ] / sampleSize ); - size[ i ] = (maxs[ i ] - mins[ i ]) / sampleSize + 1.0f; - - /* hack (god this sucks) */ - if( size[ i ] > lm->customWidth || size[ i ] > lm->customHeight || (lmLimitSize && size[i] > lmLimitSize)) - { - i = -1; - sampleSize += 1.0f; - } - } - - if(sampleSize != lm->sampleSize && lmLimitSize == 0) - { - Sys_FPrintf(SYS_VRB,"WARNING: surface at (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) too large for desired samplesize/lightmapsize/lightmapscale combination, increased samplesize from %d to %d\n", - info->mins[0], - info->mins[1], - info->mins[2], - info->maxs[0], - info->maxs[1], - info->maxs[2], - lm->sampleSize, - (int) sampleSize); - } - - /* set actual sample size */ - lm->actualSampleSize = sampleSize; - - /* fixme: copy rounded mins/maxes to lightmap record? */ - if( lm->plane == NULL ) - { - VectorCopy( mins, lm->mins ); - VectorCopy( maxs, lm->maxs ); - VectorCopy( mins, origin ); - } - - /* set lightmap origin */ - VectorCopy( lm->mins, origin ); - - /* make absolute axis */ - faxis[ 0 ] = fabs( lm->axis[ 0 ] ); - faxis[ 1 ] = fabs( lm->axis[ 1 ] ); - faxis[ 2 ] = fabs( lm->axis[ 2 ] ); - - /* clear out lightmap vectors */ - memset( vecs, 0, sizeof( vecs ) ); - - /* classify the plane (x y or z major) (ydnar: biased to z axis projection) */ - if( faxis[ 2 ] >= faxis[ 0 ] && faxis[ 2 ] >= faxis[ 1 ] ) - { - axisNum = 2; - lm->w = size[ 0 ]; - lm->h = size[ 1 ]; - vecs[ 0 ][ 0 ] = 1.0f / sampleSize; - vecs[ 1 ][ 1 ] = 1.0f / sampleSize; - } - else if( faxis[ 0 ] >= faxis[ 1 ] && faxis[ 0 ] >= faxis[ 2 ] ) - { - axisNum = 0; - lm->w = size[ 1 ]; - lm->h = size[ 2 ]; - vecs[ 0 ][ 1 ] = 1.0f / sampleSize; - vecs[ 1 ][ 2 ] = 1.0f / sampleSize; - } - else - { - axisNum = 1; - lm->w = size[ 0 ]; - lm->h = size[ 2 ]; - vecs[ 0 ][ 0 ] = 1.0f / sampleSize; - vecs[ 1 ][ 2 ] = 1.0f / sampleSize; - } - - /* check for bogus axis */ - if( faxis[ axisNum ] == 0.0f ) - { - Sys_Printf( "WARNING: ProjectSurfaceLightmap: Chose a 0 valued axis\n" ); - lm->w = lm->h = 0; - return qfalse; - } - - /* store the axis number in the lightmap */ - lm->axisNum = axisNum; - - /* walk the list of surfaces on this raw lightmap */ - for( n = 0; n < lm->numLightSurfaces; n++ ) - { - /* get surface */ - num2 = lightSurfaces[ lm->firstLightSurface + n ]; - ds2 = &bspDrawSurfaces[ num2 ]; - info2 = &surfaceInfos[ num2 ]; - verts = &yDrawVerts[ ds2->firstVert ]; - - /* set the lightmap texture coordinates in yDrawVerts in [0, superSample * lm->customWidth] space */ - for( i = 0; i < ds2->numVerts; i++ ) - { - VectorSubtract( verts[ i ].xyz, origin, delta ); - s = DotProduct( delta, vecs[ 0 ] ) + 0.5f; - t = DotProduct( delta, vecs[ 1 ] ) + 0.5f; - verts[ i ].lightmap[ 0 ][ 0 ] = s * superSample; - verts[ i ].lightmap[ 0 ][ 1 ] = t * superSample; - - if( s > (float) lm->w || t > (float) lm->h ) - { - Sys_FPrintf( SYS_VRB, "WARNING: Lightmap texture coords out of range: S %1.4f > %3d || T %1.4f > %3d\n", - s, lm->w, t, lm->h ); - } - } - } - - /* get first drawsurface */ - num2 = lightSurfaces[ lm->firstLightSurface ]; - ds2 = &bspDrawSurfaces[ num2 ]; - info2 = &surfaceInfos[ num2 ]; - verts = &yDrawVerts[ ds2->firstVert ]; - - /* calculate lightmap origin */ - if( VectorLength( ds2->lightmapVecs[ 2 ] ) ) - VectorCopy( ds2->lightmapVecs[ 2 ], plane ); - else - VectorCopy( lm->axis, plane ); - plane[ 3 ] = DotProduct( verts[ 0 ].xyz, plane ); - - VectorCopy( origin, lm->origin ); - d = DotProduct( lm->origin, plane ) - plane[ 3 ]; - d /= plane[ axisNum ]; - lm->origin[ axisNum ] -= d; - - /* legacy support */ - VectorCopy( lm->origin, ds->lightmapOrigin ); - - /* for planar surfaces, create lightmap vectors for st->xyz conversion */ - if( VectorLength( ds->lightmapVecs[ 2 ] ) || 1 ) /* ydnar: can't remember what exactly i was thinking here... */ - { - /* allocate space for the vectors */ - lm->vecs = safe_malloc( 3 * sizeof( vec3_t ) ); - memset( lm->vecs, 0, 3 * sizeof( vec3_t ) ); - VectorCopy( ds->lightmapVecs[ 2 ], lm->vecs[ 2 ] ); - - /* project stepped lightmap blocks and subtract to get planevecs */ - for( i = 0; i < 2; i++ ) - { - len = VectorNormalize( vecs[ i ], normalized ); - VectorScale( normalized, (1.0 / len), lm->vecs[ i ] ); - d = DotProduct( lm->vecs[ i ], plane ); - d /= plane[ axisNum ]; - lm->vecs[ i ][ axisNum ] -= d; - } - } - else - { - /* lightmap vectors are useless on a non-planar surface */ - lm->vecs = NULL; - } - - /* add to counts */ - if( ds->surfaceType == MST_PATCH ) - { - numPatchesLightmapped++; - if( lm->plane != NULL ) - numPlanarPatchesLightmapped++; - } - else - { - if( lm->plane != NULL ) - numPlanarsLightmapped++; - else - numNonPlanarsLightmapped++; - } - - /* return */ - return qtrue; -} - - - -/* -CompareSurfaceInfo() -compare function for qsort() -*/ - -static int CompareSurfaceInfo( const void *a, const void *b ) -{ - surfaceInfo_t *aInfo, *bInfo; - int i; - - - /* get surface info */ - aInfo = &surfaceInfos[ *((const int*) a) ]; - bInfo = &surfaceInfos[ *((const int*) b) ]; - - /* model first */ - if( aInfo->modelindex < bInfo->modelindex ) - return 1; - else if( aInfo->modelindex > bInfo->modelindex ) - return -1; - - /* then lightmap status */ - if( aInfo->hasLightmap < bInfo->hasLightmap ) - return 1; - else if( aInfo->hasLightmap > bInfo->hasLightmap ) - return -1; - - /* 27: then shader! */ - if (aInfo->si < bInfo->si) - return 1; - else if (aInfo->si > bInfo->si) - return -1; - - - /* then lightmap sample size */ - if( aInfo->sampleSize < bInfo->sampleSize ) - return 1; - else if( aInfo->sampleSize > bInfo->sampleSize ) - return -1; - - /* then lightmap axis */ - for( i = 0; i < 3; i++ ) - { - if( aInfo->axis[ i ] < bInfo->axis[ i ] ) - return 1; - else if( aInfo->axis[ i ] > bInfo->axis[ i ] ) - return -1; - } - - /* then plane */ - if( aInfo->plane == NULL && bInfo->plane != NULL ) - return 1; - else if( aInfo->plane != NULL && bInfo->plane == NULL ) - return -1; - else if( aInfo->plane != NULL && bInfo->plane != NULL ) - { - for( i = 0; i < 4; i++ ) - { - if( aInfo->plane[ i ] < bInfo->plane[ i ] ) - return 1; - else if( aInfo->plane[ i ] > bInfo->plane[ i ] ) - return -1; - } - } - - /* then position in world */ - for( i = 0; i < 3; i++ ) - { - if( aInfo->mins[ i ] < bInfo->mins[ i ] ) - return 1; - else if( aInfo->mins[ i ] > bInfo->mins[ i ] ) - return -1; - } - - /* these are functionally identical (this should almost never happen) */ - return 0; -} - - - -/* -SetupSurfaceLightmaps() -allocates lightmaps for every surface in the bsp that needs one -this depends on yDrawVerts being allocated -*/ - -void SetupSurfaceLightmaps( void ) -{ - int i, j, k, s,num, num2; - bspModel_t *model; - bspLeaf_t *leaf; - bspDrawSurface_t *ds, *ds2; - surfaceInfo_t *info, *info2; - rawLightmap_t *lm; - qboolean added; - vec3_t mapSize, entityOrigin; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- SetupSurfaceLightmaps ---\n"); - - /* determine supersample amount */ - if( superSample < 1 ) - superSample = 1; - else if( superSample > 8 ) - { - Sys_Printf( "WARNING: Insane supersampling amount (%d) detected.\n", superSample ); - superSample = 8; - } - - /* clear map bounds */ - ClearBounds( mapMins, mapMaxs ); - - /* allocate a list of surface clusters */ - numSurfaceClusters = 0; - maxSurfaceClusters = numBSPLeafSurfaces; - surfaceClusters = safe_malloc( maxSurfaceClusters * sizeof( *surfaceClusters ) ); - memset( surfaceClusters, 0, maxSurfaceClusters * sizeof( *surfaceClusters ) ); - - /* allocate a list for per-surface info */ - surfaceInfos = safe_malloc( numBSPDrawSurfaces * sizeof( *surfaceInfos ) ); - memset( surfaceInfos, 0, numBSPDrawSurfaces * sizeof( *surfaceInfos ) ); - for( i = 0; i < numBSPDrawSurfaces; i++ ) - surfaceInfos[ i ].childSurfaceNum = -1; - - /* allocate a list of surface indexes to be sorted */ - sortSurfaces = safe_malloc( numBSPDrawSurfaces * sizeof( int ) ); - memset( sortSurfaces, 0, numBSPDrawSurfaces * sizeof( int ) ); - - /* walk each model in the bsp */ - for( i = 0; i < numBSPModels; i++ ) - { - /* get model */ - model = &bspModels[ i ]; - - /* walk the list of surfaces in this model and fill out the info structs */ - for( j = 0; j < model->numBSPSurfaces; j++ ) - { - /* make surface index */ - num = model->firstBSPSurface + j; - - /* copy index to sort list */ - sortSurfaces[ num ] = num; - - /* get surface and info */ - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* set entity origin */ - if( ds->numVerts > 0 ) - VectorSubtract( yDrawVerts[ ds->firstVert ].xyz, bspDrawVerts[ ds->firstVert ].xyz, entityOrigin ); - else - VectorClear( entityOrigin ); - - /* basic setup */ - info->modelindex = i; - info->lm = NULL; - info->plane = NULL; - info->firstSurfaceCluster = numSurfaceClusters; - - /* get extra data */ - info->si = GetSurfaceExtraShaderInfo( num ); - if( info->si == NULL ) - info->si = ShaderInfoForShader( bspShaders[ ds->shaderNum ].shader ); - info->parentSurfaceNum = GetSurfaceExtraParentSurfaceNum( num ); - info->entityNum = GetSurfaceExtraEntityNum( num ); - info->castShadows = GetSurfaceExtraCastShadows( num ); - info->recvShadows = GetSurfaceExtraRecvShadows( num ); - info->sampleSize = GetSurfaceExtraSampleSize( num ); - info->longestCurve = GetSurfaceExtraLongestCurve( num ); - info->patchIterations = IterationsForCurve( info->longestCurve, patchSubdivisions ); - GetSurfaceExtraLightmapAxis( num, info->axis ); - - /* mark parent */ - if( info->parentSurfaceNum >= 0 ) - surfaceInfos[ info->parentSurfaceNum ].childSurfaceNum = j; - - /* determine surface bounds */ - ClearBounds( info->mins, info->maxs ); - for( k = 0; k < ds->numVerts; k++ ) - { - AddPointToBounds( yDrawVerts[ ds->firstVert + k ].xyz, mapMins, mapMaxs ); - AddPointToBounds( yDrawVerts[ ds->firstVert + k ].xyz, info->mins, info->maxs ); - } - - /* find all the bsp clusters the surface falls into */ - for( k = 0; k < numBSPLeafs; k++ ) - { - /* get leaf */ - leaf = &bspLeafs[ k ]; - - /* test bbox */ - if( leaf->mins[ 0 ] > info->maxs[ 0 ] || leaf->maxs[ 0 ] < info->mins[ 0 ] || - leaf->mins[ 1 ] > info->maxs[ 1 ] || leaf->maxs[ 1 ] < info->mins[ 1 ] || - leaf->mins[ 2 ] > info->maxs[ 2 ] || leaf->maxs[ 2 ] < info->mins[ 2 ] ) - continue; - - /* test leaf surfaces */ - for( s = 0; s < leaf->numBSPLeafSurfaces; s++ ) - { - if( bspLeafSurfaces[ leaf->firstBSPLeafSurface + s ] == num ) - { - if( numSurfaceClusters >= maxSurfaceClusters ) - Error( "maxSurfaceClusters exceeded" ); - surfaceClusters[ numSurfaceClusters ] = leaf->cluster; - numSurfaceClusters++; - info->numSurfaceClusters++; - } - } - } - - /* determine if surface is planar */ - if( VectorLength( ds->lightmapVecs[ 2 ] ) > 0.0f ) - { - /* make a plane */ - info->plane = safe_malloc( 4 * sizeof( float ) ); - VectorCopy( ds->lightmapVecs[ 2 ], info->plane ); - info->plane[ 3 ] = DotProduct( yDrawVerts[ ds->firstVert ].xyz, info->plane ); - } - - /* determine if surface requires a lightmap */ - if( ds->surfaceType == MST_TRIANGLE_SOUP || - ds->surfaceType == MST_FOLIAGE || - (info->si->compileFlags & C_VERTEXLIT) ) - numSurfsVertexLit++; - else - { - numSurfsLightmapped++; - info->hasLightmap = qtrue; - } - } - } - - /* find longest map distance */ - VectorSubtract( mapMaxs, mapMins, mapSize ); - maxMapDistance = VectorLength( mapSize ); - - /* sort the surfaces info list */ - qsort( sortSurfaces, numBSPDrawSurfaces, sizeof( int ), CompareSurfaceInfo ); - - /* allocate a list of surfaces that would go into raw lightmaps */ - numLightSurfaces = 0; - lightSurfaces = safe_malloc( numSurfsLightmapped * sizeof( int ) ); - memset( lightSurfaces, 0, numSurfsLightmapped * sizeof( int ) ); - - /* allocate a list of raw lightmaps */ - numRawSuperLuxels = 0; - numRawLightmaps = 0; - rawLightmaps = safe_malloc( numSurfsLightmapped * sizeof( *rawLightmaps ) ); - memset( rawLightmaps, 0, numSurfsLightmapped * sizeof( *rawLightmaps ) ); - - /* walk the list of sorted surfaces */ - for( i = 0; i < numBSPDrawSurfaces; i++ ) - { - /* get info and attempt early out */ - num = sortSurfaces[ i ]; - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - if( info->hasLightmap == qfalse || info->lm != NULL || info->parentSurfaceNum >= 0 ) - continue; - - /* allocate a new raw lightmap */ - lm = &rawLightmaps[ numRawLightmaps ]; - numRawLightmaps++; - - /* set it up */ - lm->splotchFix = info->si->splotchFix; - lm->firstLightSurface = numLightSurfaces; - lm->numLightSurfaces = 0; - /* vortex: multiply lightmap sample size by -samplescale */ - if (sampleScale > 0) - lm->sampleSize = info->sampleSize*sampleScale; - else - lm->sampleSize = info->sampleSize; - lm->actualSampleSize = lm->sampleSize; - lm->entityNum = info->entityNum; - lm->recvShadows = info->recvShadows; - lm->brightness = info->si->lmBrightness; - lm->filterRadius = info->si->lmFilterRadius; - VectorCopy(info->si->floodlightRGB, lm->floodlightRGB); - lm->floodlightDistance = info->si->floodlightDistance; - lm->floodlightIntensity = info->si->floodlightIntensity; - lm->floodlightDirectionScale = info->si->floodlightDirectionScale; - VectorCopy( info->axis, lm->axis ); - lm->plane = info->plane; - VectorCopy( info->mins, lm->mins ); - VectorCopy( info->maxs, lm->maxs ); - - lm->customWidth = info->si->lmCustomWidth; - lm->customHeight = info->si->lmCustomHeight; - - /* add the surface to the raw lightmap */ - AddSurfaceToRawLightmap( num, lm ); - info->lm = lm; - - /* do an exhaustive merge */ - added = qtrue; - while( added ) - { - /* walk the list of surfaces again */ - added = qfalse; - for( j = i + 1; j < numBSPDrawSurfaces && lm->finished == qfalse; j++ ) - { - /* get info and attempt early out */ - num2 = sortSurfaces[ j ]; - ds2 = &bspDrawSurfaces[ num2 ]; - info2 = &surfaceInfos[ num2 ]; - if( info2->hasLightmap == qfalse || info2->lm != NULL ) - continue; - - /* add the surface to the raw lightmap */ - if( AddSurfaceToRawLightmap( num2, lm ) ) - { - info2->lm = lm; - added = qtrue; - } - else - { - /* back up one */ - lm->numLightSurfaces--; - numLightSurfaces--; - } - } - } - - /* finish the lightmap and allocate the various buffers */ - FinishRawLightmap( lm ); - } - - /* allocate vertex luxel storage */ - for( k = 0; k < MAX_LIGHTMAPS; k++ ) - { - vertexLuxels[ k ] = safe_malloc( numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); - memset( vertexLuxels[ k ], 0, numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); - radVertexLuxels[ k ] = safe_malloc( numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); - memset( radVertexLuxels[ k ], 0, numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); - } - - /* emit some stats */ - Sys_FPrintf( SYS_VRB, "%9d surfaces\n", numBSPDrawSurfaces ); - Sys_FPrintf( SYS_VRB, "%9d raw lightmaps\n", numRawLightmaps ); - Sys_FPrintf( SYS_VRB, "%9d surfaces vertex lit\n", numSurfsVertexLit ); - Sys_FPrintf( SYS_VRB, "%9d surfaces lightmapped\n", numSurfsLightmapped ); - Sys_FPrintf( SYS_VRB, "%9d planar surfaces lightmapped\n", numPlanarsLightmapped ); - Sys_FPrintf( SYS_VRB, "%9d non-planar surfaces lightmapped\n", numNonPlanarsLightmapped ); - Sys_FPrintf( SYS_VRB, "%9d patches lightmapped\n", numPatchesLightmapped ); - Sys_FPrintf( SYS_VRB, "%9d planar patches lightmapped\n", numPlanarPatchesLightmapped ); -} - - - -/* -StitchSurfaceLightmaps() -stitches lightmap edges -2002-11-20 update: use this func only for stitching nonplanar patch lightmap seams -*/ - -#define MAX_STITCH_CANDIDATES 32 -#define MAX_STITCH_LUXELS 64 - -void StitchSurfaceLightmaps( void ) -{ - int i, j, x, y, x2, y2, *cluster, *cluster2, - numStitched, numCandidates, numLuxels, f, fOld, start; - rawLightmap_t *lm, *a, *b, *c[ MAX_STITCH_CANDIDATES ]; - float *luxel, *luxel2, *origin, *origin2, *normal, *normal2, - sampleSize, average[ 3 ], totalColor, ootc, *luxels[ MAX_STITCH_LUXELS ]; - - - /* disabled for now */ - return; - - /* note it */ - Sys_Printf( "--- StitchSurfaceLightmaps ---\n"); - - /* init pacifier */ - fOld = -1; - start = I_FloatTime(); - - /* walk the list of raw lightmaps */ - numStitched = 0; - for( i = 0; i < numRawLightmaps; i++ ) - { - /* print pacifier */ - f = 10 * i / numRawLightmaps; - if( f != fOld ) - { - fOld = f; - Sys_Printf( "%i...", f ); - } - - /* get lightmap a */ - a = &rawLightmaps[ i ]; - - /* walk rest of lightmaps */ - numCandidates = 0; - for( j = i + 1; j < numRawLightmaps && numCandidates < MAX_STITCH_CANDIDATES; j++ ) - { - /* get lightmap b */ - b = &rawLightmaps[ j ]; - - /* test bounding box */ - if( a->mins[ 0 ] > b->maxs[ 0 ] || a->maxs[ 0 ] < b->mins[ 0 ] || - a->mins[ 1 ] > b->maxs[ 1 ] || a->maxs[ 1 ] < b->mins[ 1 ] || - a->mins[ 2 ] > b->maxs[ 2 ] || a->maxs[ 2 ] < b->mins[ 2 ] ) - continue; - - /* add candidate */ - c[ numCandidates++ ] = b; - } - - /* walk luxels */ - for( y = 0; y < a->sh; y++ ) - { - for( x = 0; x < a->sw; x++ ) - { - /* ignore unmapped/unlit luxels */ - lm = a; - cluster = SUPER_CLUSTER( x, y ); - if( *cluster == CLUSTER_UNMAPPED ) - continue; - luxel = SUPER_LUXEL( 0, x, y ); - if( luxel[ 3 ] <= 0.0f ) - continue; - - /* get particulars */ - origin = SUPER_ORIGIN( x, y ); - normal = SUPER_NORMAL( x, y ); - - /* walk candidate list */ - for( j = 0; j < numCandidates; j++ ) - { - /* get candidate */ - b = c[ j ]; - lm = b; - - /* set samplesize to the smaller of the pair */ - sampleSize = 0.5f * (a->actualSampleSize < b->actualSampleSize ? a->actualSampleSize : b->actualSampleSize); - - /* test bounding box */ - if( origin[ 0 ] < (b->mins[ 0 ] - sampleSize) || (origin[ 0 ] > b->maxs[ 0 ] + sampleSize) || - origin[ 1 ] < (b->mins[ 1 ] - sampleSize) || (origin[ 1 ] > b->maxs[ 1 ] + sampleSize) || - origin[ 2 ] < (b->mins[ 2 ] - sampleSize) || (origin[ 2 ] > b->maxs[ 2 ] + sampleSize) ) - continue; - - /* walk candidate luxels */ - VectorClear( average ); - numLuxels = 0; - totalColor = 0.0f; - for( y2 = 0; y2 < b->sh && numLuxels < MAX_STITCH_LUXELS; y2++ ) - { - for( x2 = 0; x2 < b->sw && numLuxels < MAX_STITCH_LUXELS; x2++ ) - { - /* ignore same luxels */ - if( a == b && abs( x - x2 ) <= 1 && abs( y - y2 ) <= 1 ) - continue; - - /* ignore unmapped/unlit luxels */ - cluster2 = SUPER_CLUSTER( x2, y2 ); - if( *cluster2 == CLUSTER_UNMAPPED ) - continue; - luxel2 = SUPER_LUXEL( 0, x2, y2 ); - if( luxel2[ 3 ] <= 0.0f ) - continue; - - /* get particulars */ - origin2 = SUPER_ORIGIN( x2, y2 ); - normal2 = SUPER_NORMAL( x2, y2 ); - - /* test normal */ - if( DotProduct( normal, normal2 ) < 0.5f ) - continue; - - /* test bounds */ - if( fabs( origin[ 0 ] - origin2[ 0 ] ) > sampleSize || - fabs( origin[ 1 ] - origin2[ 1 ] ) > sampleSize || - fabs( origin[ 2 ] - origin2[ 2 ] ) > sampleSize ) - continue; - - /* add luxel */ - //% VectorSet( luxel2, 255, 0, 255 ); - luxels[ numLuxels++ ] = luxel2; - VectorAdd( average, luxel2, average ); - totalColor += luxel2[ 3 ]; - } - } - - /* early out */ - if( numLuxels == 0 ) - continue; - - /* scale average */ - ootc = 1.0f / totalColor; - VectorScale( average, ootc, luxel ); - luxel[ 3 ] = 1.0f; - numStitched++; - } - } - } - } - - /* emit statistics */ - Sys_Printf( " (%i)\n", (int) (I_FloatTime() - start) ); - Sys_FPrintf( SYS_VRB, "%9d luxels stitched\n", numStitched ); -} - - - -/* -CompareBSPLuxels() -compares two surface lightmaps' bsp luxels, ignoring occluded luxels -*/ - -#define SOLID_EPSILON 0.0625 -#define LUXEL_TOLERANCE 0.0025 -#define LUXEL_COLOR_FRAC 0.001302083 /* 1 / 3 / 256 */ - -static qboolean CompareBSPLuxels( rawLightmap_t *a, int aNum, rawLightmap_t *b, int bNum ) -{ - rawLightmap_t *lm; - int x, y; - double delta, total, rd, gd, bd; - float *aLuxel, *bLuxel; - - - /* styled lightmaps will never be collapsed to non-styled lightmaps when there is _minlight */ - if( (minLight[ 0 ] || minLight[ 1 ] || minLight[ 2 ]) && - ((aNum == 0 && bNum != 0) || (aNum != 0 && bNum == 0)) ) - return qfalse; - - /* basic tests */ - if( a->customWidth != b->customWidth || a->customHeight != b->customHeight || - a->brightness != b->brightness || - a->solid[ aNum ] != b->solid[ bNum ] || - a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) - return qfalse; - - /* compare solid color lightmaps */ - if( a->solid[ aNum ] && b->solid[ bNum ] ) - { - /* get deltas */ - rd = fabs( a->solidColor[ aNum ][ 0 ] - b->solidColor[ bNum ][ 0 ] ); - gd = fabs( a->solidColor[ aNum ][ 1 ] - b->solidColor[ bNum ][ 1 ] ); - bd = fabs( a->solidColor[ aNum ][ 2 ] - b->solidColor[ bNum ][ 2 ] ); - - /* compare color */ - if( rd > SOLID_EPSILON || gd > SOLID_EPSILON|| bd > SOLID_EPSILON ) - return qfalse; - - /* okay */ - return qtrue; - } - - /* compare nonsolid lightmaps */ - if( a->w != b->w || a->h != b->h ) - return qfalse; - - /* compare luxels */ - delta = 0.0; - total = 0.0; - for( y = 0; y < a->h; y++ ) - { - for( x = 0; x < a->w; x++ ) - { - /* increment total */ - total += 1.0; - - /* get luxels */ - lm = a; aLuxel = BSP_LUXEL( aNum, x, y ); - lm = b; bLuxel = BSP_LUXEL( bNum, x, y ); - - /* ignore unused luxels */ - if( aLuxel[ 0 ] < 0 || bLuxel[ 0 ] < 0 ) - continue; - - /* get deltas */ - rd = fabs( aLuxel[ 0 ] - bLuxel[ 0 ] ); - gd = fabs( aLuxel[ 1 ] - bLuxel[ 1 ] ); - bd = fabs( aLuxel[ 2 ] - bLuxel[ 2 ] ); - - /* 2003-09-27: compare individual luxels */ - if( rd > 3.0 || gd > 3.0 || bd > 3.0 ) - return qfalse; - - /* compare (fixme: take into account perceptual differences) */ - delta += rd * LUXEL_COLOR_FRAC; - delta += gd * LUXEL_COLOR_FRAC; - delta += bd * LUXEL_COLOR_FRAC; - - /* is the change too high? */ - if( total > 0.0 && ((delta / total) > LUXEL_TOLERANCE) ) - return qfalse; - } - } - - /* made it this far, they must be identical (or close enough) */ - return qtrue; -} - - - -/* -MergeBSPLuxels() -merges two surface lightmaps' bsp luxels, overwriting occluded luxels -*/ - -static qboolean MergeBSPLuxels( rawLightmap_t *a, int aNum, rawLightmap_t *b, int bNum ) -{ - rawLightmap_t *lm; - int x, y; - float luxel[ 3 ], *aLuxel, *bLuxel; - - - /* basic tests */ - if( a->customWidth != b->customWidth || a->customHeight != b->customHeight || - a->brightness != b->brightness || - a->solid[ aNum ] != b->solid[ bNum ] || - a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) - return qfalse; - - /* compare solid lightmaps */ - if( a->solid[ aNum ] && b->solid[ bNum ] ) - { - /* average */ - VectorAdd( a->solidColor[ aNum ], b->solidColor[ bNum ], luxel ); - VectorScale( luxel, 0.5f, luxel ); - - /* copy to both */ - VectorCopy( luxel, a->solidColor[ aNum ] ); - VectorCopy( luxel, b->solidColor[ bNum ] ); - - /* return to sender */ - return qtrue; - } - - /* compare nonsolid lightmaps */ - if( a->w != b->w || a->h != b->h ) - return qfalse; - - /* merge luxels */ - for( y = 0; y < a->h; y++ ) - { - for( x = 0; x < a->w; x++ ) - { - /* get luxels */ - lm = a; aLuxel = BSP_LUXEL( aNum, x, y ); - lm = b; bLuxel = BSP_LUXEL( bNum, x, y ); - - /* handle occlusion mismatch */ - if( aLuxel[ 0 ] < 0.0f ) - VectorCopy( bLuxel, aLuxel ); - else if( bLuxel[ 0 ] < 0.0f ) - VectorCopy( aLuxel, bLuxel ); - else - { - /* average */ - VectorAdd( aLuxel, bLuxel, luxel ); - VectorScale( luxel, 0.5f, luxel ); - - /* debugging code */ - //% luxel[ 2 ] += 64.0f; - - /* copy to both */ - VectorCopy( luxel, aLuxel ); - VectorCopy( luxel, bLuxel ); - } - } - } - - /* done */ - return qtrue; -} - - - -/* -ApproximateLuxel() -determines if a single luxel is can be approximated with the interpolated vertex rgba -*/ - -static qboolean ApproximateLuxel( rawLightmap_t *lm, bspDrawVert_t *dv ) -{ - int i, x, y, d, lightmapNum; - float *luxel; - vec3_t color, vertexColor; - byte cb[ 4 ], vcb[ 4 ]; - - - /* find luxel xy coords */ - x = dv->lightmap[ 0 ][ 0 ] / superSample; - y = dv->lightmap[ 0 ][ 1 ] / superSample; - if( x < 0 ) - x = 0; - else if( x >= lm->w ) - x = lm->w - 1; - if( y < 0 ) - y = 0; - else if( y >= lm->h ) - y = lm->h - 1; - - /* walk list */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->styles[ lightmapNum ] == LS_NONE ) - continue; - - /* get luxel */ - luxel = BSP_LUXEL( lightmapNum, x, y ); - - /* ignore occluded luxels */ - if( luxel[ 0 ] < 0.0f || luxel[ 1 ] < 0.0f || luxel[ 2 ] < 0.0f ) - return qtrue; - - /* copy, set min color and compare */ - VectorCopy( luxel, color ); - VectorCopy( dv->color[ 0 ], vertexColor ); - - /* styles are not affected by minlight */ - if( lightmapNum == 0 ) - { - for( i = 0; i < 3; i++ ) - { - /* set min color */ - if( color[ i ] < minLight[ i ] ) - color[ i ] = minLight[ i ]; - if( vertexColor[ i ] < minLight[ i ] ) /* note NOT minVertexLight */ - vertexColor[ i ] = minLight[ i ]; - } - } - - /* set to bytes */ - ColorToBytes( color, cb, 1.0f ); - ColorToBytes( vertexColor, vcb, 1.0f ); - - /* compare */ - for( i = 0; i < 3; i++ ) - { - d = cb[ i ] - vcb[ i ]; - if( d < 0 ) - d *= -1; - if( d > approximateTolerance ) - return qfalse; - } - } - - /* close enough for the girls i date */ - return qtrue; -} - - - -/* -ApproximateTriangle() -determines if a single triangle can be approximated with vertex rgba -*/ - -static qboolean ApproximateTriangle_r( rawLightmap_t *lm, bspDrawVert_t *dv[ 3 ] ) -{ - bspDrawVert_t mid, *dv2[ 3 ]; - int max; - - - /* approximate the vertexes */ - if( ApproximateLuxel( lm, dv[ 0 ] ) == qfalse ) - return qfalse; - if( ApproximateLuxel( lm, dv[ 1 ] ) == qfalse ) - return qfalse; - if( ApproximateLuxel( lm, dv[ 2 ] ) == qfalse ) - return qfalse; - - /* subdivide calc */ - { - int i; - float dx, dy, dist, maxDist; - - - /* find the longest edge and split it */ - max = -1; - maxDist = 0; - for( i = 0; i < 3; i++ ) - { - dx = dv[ i ]->lightmap[ 0 ][ 0 ] - dv[ (i + 1) % 3 ]->lightmap[ 0 ][ 0 ]; - dy = dv[ i ]->lightmap[ 0 ][ 1 ] - dv[ (i + 1) % 3 ]->lightmap[ 0 ][ 1 ]; - dist = sqrt( (dx * dx) + (dy * dy) ); - if( dist > maxDist ) - { - maxDist = dist; - max = i; - } - } - - /* try to early out */ - if( i < 0 || maxDist < subdivideThreshold ) - return qtrue; - } - - /* split the longest edge and map it */ - LerpDrawVert( dv[ max ], dv[ (max + 1) % 3 ], &mid ); - if( ApproximateLuxel( lm, &mid ) == qfalse ) - return qfalse; - - /* recurse to first triangle */ - VectorCopy( dv, dv2 ); - dv2[ max ] = ∣ - if( ApproximateTriangle_r( lm, dv2 ) == qfalse ) - return qfalse; - - /* recurse to second triangle */ - VectorCopy( dv, dv2 ); - dv2[ (max + 1) % 3 ] = ∣ - return ApproximateTriangle_r( lm, dv2 ); -} - - - -/* -ApproximateLightmap() -determines if a raw lightmap can be approximated sufficiently with vertex colors -*/ - -static qboolean ApproximateLightmap( rawLightmap_t *lm ) -{ - int n, num, i, x, y, pw[ 5 ], r; - bspDrawSurface_t *ds; - surfaceInfo_t *info; - mesh_t src, *subdivided, *mesh; - bspDrawVert_t *verts, *dv[ 3 ]; - qboolean approximated; - - - /* approximating? */ - if( approximateTolerance <= 0 ) - return qfalse; - - /* test for jmonroe */ - #if 0 - /* don't approx lightmaps with styled twins */ - if( lm->numStyledTwins > 0 ) - return qfalse; - - /* don't approx lightmaps with styles */ - for( i = 1; i < MAX_LIGHTMAPS; i++ ) - { - if( lm->styles[ i ] != LS_NONE ) - return qfalse; - } - #endif - - /* assume reduced until shadow detail is found */ - approximated = qtrue; - - /* walk the list of surfaces on this raw lightmap */ - for( n = 0; n < lm->numLightSurfaces; n++ ) - { - /* get surface */ - num = lightSurfaces[ lm->firstLightSurface + n ]; - ds = &bspDrawSurfaces[ num ]; - info = &surfaceInfos[ num ]; - - /* assume not-reduced initially */ - info->approximated = qfalse; - - /* bail if lightmap doesn't match up */ - if( info->lm != lm ) - continue; - - /* bail if not vertex lit */ - if( info->si->noVertexLight ) - continue; - - /* assume that surfaces whose bounding boxes is smaller than 2x samplesize will be forced to vertex */ - if( (info->maxs[ 0 ] - info->mins[ 0 ]) <= (2.0f * info->sampleSize) && - (info->maxs[ 1 ] - info->mins[ 1 ]) <= (2.0f * info->sampleSize) && - (info->maxs[ 2 ] - info->mins[ 2 ]) <= (2.0f * info->sampleSize) ) - { - info->approximated = qtrue; - numSurfsVertexForced++; - continue; - } - - /* handle the triangles */ - switch( ds->surfaceType ) - { - case MST_PLANAR: - /* get verts */ - verts = yDrawVerts + ds->firstVert; - - /* map the triangles */ - info->approximated = qtrue; - for( i = 0; i < ds->numIndexes && info->approximated; i += 3 ) - { - dv[ 0 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i ] ]; - dv[ 1 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 1 ] ]; - dv[ 2 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 2 ] ]; - info->approximated = ApproximateTriangle_r( lm, dv ); - } - break; - - case MST_PATCH: - /* make a mesh from the drawsurf */ - src.width = ds->patchWidth; - src.height = ds->patchHeight; - src.verts = &yDrawVerts[ ds->firstVert ]; - //% subdivided = SubdivideMesh( src, 8, 512 ); - subdivided = SubdivideMesh2( src, info->patchIterations ); - - /* fit it to the curve and remove colinear verts on rows/columns */ - PutMeshOnCurve( *subdivided ); - mesh = RemoveLinearMeshColumnsRows( subdivided ); - FreeMesh( subdivided ); - - /* get verts */ - verts = mesh->verts; - - /* map the mesh quads */ - info->approximated = qtrue; - for( y = 0; y < (mesh->height - 1) && info->approximated; y++ ) - { - for( x = 0; x < (mesh->width - 1) && info->approximated; x++ ) - { - /* set indexes */ - pw[ 0 ] = x + (y * mesh->width); - pw[ 1 ] = x + ((y + 1) * mesh->width); - pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); - pw[ 3 ] = x + 1 + (y * mesh->width); - pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ - - /* set radix */ - r = (x + y) & 1; - - /* get drawverts and map first triangle */ - dv[ 0 ] = &verts[ pw[ r + 0 ] ]; - dv[ 1 ] = &verts[ pw[ r + 1 ] ]; - dv[ 2 ] = &verts[ pw[ r + 2 ] ]; - info->approximated = ApproximateTriangle_r( lm, dv ); - - /* get drawverts and map second triangle */ - dv[ 0 ] = &verts[ pw[ r + 0 ] ]; - dv[ 1 ] = &verts[ pw[ r + 2 ] ]; - dv[ 2 ] = &verts[ pw[ r + 3 ] ]; - if( info->approximated ) - info->approximated = ApproximateTriangle_r( lm, dv ); - } - } - - /* free the mesh */ - FreeMesh( mesh ); - break; - - default: - break; - } - - /* reduced? */ - if( info->approximated == qfalse ) - approximated = qfalse; - else - numSurfsVertexApproximated++; - } - - /* return */ - return approximated; -} - - - -/* -TestOutLightmapStamp() -tests a stamp on a given lightmap for validity -*/ - -static qboolean TestOutLightmapStamp( rawLightmap_t *lm, int lightmapNum, outLightmap_t *olm, int x, int y ) -{ - int sx, sy, ox, oy, offset; - float *luxel; - - - /* bounds check */ - if( x < 0 || y < 0 || (x + lm->w) > olm->customWidth || (y + lm->h) > olm->customHeight ) - return qfalse; - - /* solid lightmaps test a 1x1 stamp */ - if( lm->solid[ lightmapNum ] ) - { - offset = (y * olm->customWidth) + x; - if( olm->lightBits[ offset >> 3 ] & (1 << (offset & 7)) ) - return qfalse; - return qtrue; - } - - /* test the stamp */ - for( sy = 0; sy < lm->h; sy++ ) - { - for( sx = 0; sx < lm->w; sx++ ) - { - /* get luxel */ - luxel = BSP_LUXEL( lightmapNum, sx, sy ); - if( luxel[ 0 ] < 0.0f ) - continue; - - /* get bsp lightmap coords and test */ - ox = x + sx; - oy = y + sy; - offset = (oy * olm->customWidth) + ox; - if( olm->lightBits[ offset >> 3 ] & (1 << (offset & 7)) ) - return qfalse; - } - } - - /* stamp is empty */ - return qtrue; -} - - - -/* -SetupOutLightmap() -sets up an output lightmap -*/ - -static void SetupOutLightmap( rawLightmap_t *lm, outLightmap_t *olm ) -{ - /* dummy check */ - if( lm == NULL || olm == NULL ) - return; - - /* is this a "normal" bsp-stored lightmap? */ - if( (lm->customWidth == game->lightmapSize && lm->customHeight == game->lightmapSize) || externalLightmaps ) - { - olm->lightmapNum = numBSPLightmaps; - numBSPLightmaps++; - - /* lightmaps are interleaved with light direction maps */ - if( deluxemap ) - numBSPLightmaps++; - } - else - olm->lightmapNum = -3; - - /* set external lightmap number */ - olm->extLightmapNum = -1; - - /* set it up */ - olm->numLightmaps = 0; - olm->customWidth = lm->customWidth; - olm->customHeight = lm->customHeight; - olm->freeLuxels = olm->customWidth * olm->customHeight; - olm->numShaders = 0; - - /* allocate buffers */ - olm->lightBits = safe_malloc( (olm->customWidth * olm->customHeight / 8) + 8 ); - memset( olm->lightBits, 0, (olm->customWidth * olm->customHeight / 8) + 8 ); - olm->bspLightBytes = safe_malloc( olm->customWidth * olm->customHeight * 3 ); - memset( olm->bspLightBytes, 0, olm->customWidth * olm->customHeight * 3 ); - if( deluxemap ) - { - olm->bspDirBytes = safe_malloc( olm->customWidth * olm->customHeight * 3 ); - memset( olm->bspDirBytes, 0, olm->customWidth * olm->customHeight * 3 ); - } -} - - - -/* -FindOutLightmaps() -for a given surface lightmap, find output lightmap pages and positions for it -*/ - -#define LIGHTMAP_RESERVE_COUNT 1 -static void FindOutLightmaps( rawLightmap_t *lm ) -{ - int i, j, k, lightmapNum, xMax, yMax, x, y, sx, sy, ox, oy, offset; - outLightmap_t *olm; - surfaceInfo_t *info; - float *luxel, *deluxel; - vec3_t color, direction; - byte *pixel; - qboolean ok; - - - /* set default lightmap number (-3 = LIGHTMAP_BY_VERTEX) */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - lm->outLightmapNums[ lightmapNum ] = -3; - - /* can this lightmap be approximated with vertex color? */ - if( ApproximateLightmap( lm ) ) - return; - - /* walk list */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - if( lm->styles[ lightmapNum ] == LS_NONE ) - continue; - - /* don't store twinned lightmaps */ - if( lm->twins[ lightmapNum ] != NULL ) - continue; - - /* if this is a styled lightmap, try some normalized locations first */ - ok = qfalse; - if( lightmapNum > 0 && outLightmaps != NULL ) - { - /* loop twice */ - for( j = 0; j < 2; j++ ) - { - /* try identical position */ - for( i = 0; i < numOutLightmaps; i++ ) - { - /* get the output lightmap */ - olm = &outLightmaps[ i ]; - - /* simple early out test */ - if( olm->freeLuxels < lm->used ) - continue; - - /* don't store non-custom raw lightmaps on custom bsp lightmaps */ - if( olm->customWidth != lm->customWidth || - olm->customHeight != lm->customHeight ) - continue; - - /* try identical */ - if( j == 0 ) - { - x = lm->lightmapX[ 0 ]; - y = lm->lightmapY[ 0 ]; - ok = TestOutLightmapStamp( lm, lightmapNum, olm, x, y ); - } - - /* try shifting */ - else - { - for( sy = -1; sy <= 1; sy++ ) - { - for( sx = -1; sx <= 1; sx++ ) - { - x = lm->lightmapX[ 0 ] + sx * (olm->customWidth >> 1); //% lm->w; - y = lm->lightmapY[ 0 ] + sy * (olm->customHeight >> 1); //% lm->h; - ok = TestOutLightmapStamp( lm, lightmapNum, olm, x, y ); - - if( ok ) - break; - } - - if( ok ) - break; - } - } - - if( ok ) - break; - } - - if( ok ) - break; - } - } - - /* try normal placement algorithm */ - if( ok == qfalse ) - { - /* reset origin */ - x = 0; - y = 0; - - /* walk the list of lightmap pages */ - if(lightmapSearchBlockSize <= 0 || numOutLightmaps < LIGHTMAP_RESERVE_COUNT) - i = 0; - else - i = ((numOutLightmaps - LIGHTMAP_RESERVE_COUNT) / lightmapSearchBlockSize) * lightmapSearchBlockSize; - for( ; i < numOutLightmaps; i++ ) - { - /* get the output lightmap */ - olm = &outLightmaps[ i ]; - - /* simple early out test */ - if( olm->freeLuxels < lm->used ) - continue; - - /* don't store non-custom raw lightmaps on custom bsp lightmaps */ - if( olm->customWidth != lm->customWidth || - olm->customHeight != lm->customHeight ) - continue; - - /* set maxs */ - if( lm->solid[ lightmapNum ] ) - { - xMax = olm->customWidth; - yMax = olm->customHeight; - } - else - { - xMax = (olm->customWidth - lm->w) + 1; - yMax = (olm->customHeight - lm->h) + 1; - } - - /* walk the origin around the lightmap */ - for( y = 0; y < yMax; y++ ) - { - for( x = 0; x < xMax; x++ ) - { - /* find a fine tract of lauhnd */ - ok = TestOutLightmapStamp( lm, lightmapNum, olm, x, y ); - - if( ok ) - break; - } - - if( ok ) - break; - } - - if( ok ) - break; - - /* reset x and y */ - x = 0; - y = 0; - } - } - - /* no match? */ - if( ok == qfalse ) - { - /* allocate LIGHTMAP_RESERVE_COUNT new output lightmaps */ - numOutLightmaps += LIGHTMAP_RESERVE_COUNT; - olm = safe_malloc( numOutLightmaps * sizeof( outLightmap_t ) ); - if( outLightmaps != NULL && numOutLightmaps > LIGHTMAP_RESERVE_COUNT ) - { - memcpy( olm, outLightmaps, (numOutLightmaps - LIGHTMAP_RESERVE_COUNT) * sizeof( outLightmap_t ) ); - free( outLightmaps ); - } - outLightmaps = olm; - - /* initialize both out lightmaps */ - for(k = numOutLightmaps - LIGHTMAP_RESERVE_COUNT; k < numOutLightmaps; ++k) - SetupOutLightmap( lm, &outLightmaps[ k ] ); - - /* set out lightmap */ - i = numOutLightmaps - LIGHTMAP_RESERVE_COUNT; - olm = &outLightmaps[ i ]; - - /* set stamp xy origin to the first surface lightmap */ - if( lightmapNum > 0 ) - { - x = lm->lightmapX[ 0 ]; - y = lm->lightmapY[ 0 ]; - } - } - - /* if this is a style-using lightmap, it must be exported */ - if( lightmapNum > 0 && game->load != LoadRBSPFile ) - olm->extLightmapNum = 0; - - /* add the surface lightmap to the bsp lightmap */ - lm->outLightmapNums[ lightmapNum ] = i; - lm->lightmapX[ lightmapNum ] = x; - lm->lightmapY[ lightmapNum ] = y; - olm->numLightmaps++; - - /* add shaders */ - for( i = 0; i < lm->numLightSurfaces; i++ ) - { - /* get surface info */ - info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + i ] ]; - - /* test for shader */ - for( j = 0; j < olm->numShaders; j++ ) - { - if( olm->shaders[ j ] == info->si ) - break; - } - - /* if it doesn't exist, add it */ - if( j >= olm->numShaders && olm->numShaders < MAX_LIGHTMAP_SHADERS ) - { - olm->shaders[ olm->numShaders ] = info->si; - olm->numShaders++; - numLightmapShaders++; - } - } - - /* set maxs */ - if( lm->solid[ lightmapNum ] ) - { - xMax = 1; - yMax = 1; - } - else - { - xMax = lm->w; - yMax = lm->h; - } - - /* mark the bits used */ - for( y = 0; y < yMax; y++ ) - { - for( x = 0; x < xMax; x++ ) - { - /* get luxel */ - luxel = BSP_LUXEL( lightmapNum, x, y ); - deluxel = BSP_DELUXEL( x, y ); - if( luxel[ 0 ] < 0.0f && !lm->solid[ lightmapNum ]) - continue; - - /* set minimum light */ - if( lm->solid[ lightmapNum ] ) - { - if( debug ) - VectorSet( color, 255.0f, 0.0f, 0.0f ); - else - VectorCopy( lm->solidColor[ lightmapNum ], color ); - } - else - VectorCopy( luxel, color ); - - /* styles are not affected by minlight */ - if( lightmapNum == 0 ) - { - for( i = 0; i < 3; i++ ) - { - if( color[ i ] < minLight[ i ] ) - color[ i ] = minLight[ i ]; - } - } - - /* get bsp lightmap coords */ - ox = x + lm->lightmapX[ lightmapNum ]; - oy = y + lm->lightmapY[ lightmapNum ]; - offset = (oy * olm->customWidth) + ox; - - /* flag pixel as used */ - olm->lightBits[ offset >> 3 ] |= (1 << (offset & 7)); - olm->freeLuxels--; - - /* store color */ - pixel = olm->bspLightBytes + (((oy * olm->customWidth) + ox) * 3); - ColorToBytes( color, pixel, lm->brightness ); - - /* store direction */ - if( deluxemap ) - { - /* normalize average light direction */ - pixel = olm->bspDirBytes + (((oy * olm->customWidth) + ox) * 3); - VectorScale( deluxel, 1000.0f, direction ); - VectorNormalize( direction, direction ); - VectorScale( direction, 127.5f, direction ); - for( i = 0; i < 3; i++ ) - pixel[ i ] = (byte)( 127.5f + direction[ i ] ); - } - } - } - } -} - - - -/* -CompareRawLightmap() -compare function for qsort() -*/ - -static int CompareRawLightmap( const void *a, const void *b ) -{ - rawLightmap_t *alm, *blm; - surfaceInfo_t *aInfo, *bInfo; - int i, min, diff; - - - /* get lightmaps */ - alm = &rawLightmaps[ *((const int*) a) ]; - blm = &rawLightmaps[ *((const int*) b) ]; - - /* get min number of surfaces */ - min = (alm->numLightSurfaces < blm->numLightSurfaces ? alm->numLightSurfaces : blm->numLightSurfaces); - - /* iterate */ - for( i = 0; i < min; i++ ) - { - /* get surface info */ - aInfo = &surfaceInfos[ lightSurfaces[ alm->firstLightSurface + i ] ]; - bInfo = &surfaceInfos[ lightSurfaces[ blm->firstLightSurface + i ] ]; - - /* compare shader names */ - diff = strcmp( aInfo->si->shader, bInfo->si->shader ); - if( diff != 0 ) - return diff; - } - - /* test style count */ - diff = 0; - for( i = 0; i < MAX_LIGHTMAPS; i++ ) - diff += blm->styles[ i ] - alm->styles[ i ]; - if( diff ) - return diff; - - /* compare size */ - diff = (blm->w * blm->h) - (alm->w * alm->h); - if( diff != 0 ) - return diff; - - /* must be equivalent */ - return 0; -} - -void FillOutLightmap(outLightmap_t *olm) -{ - int x, y; - int ofs; - vec3_t dir_sum, light_sum; - int cnt, filled; - byte *lightBitsNew = NULL; - byte *lightBytesNew = NULL; - byte *dirBytesNew = NULL; - - lightBitsNew = safe_malloc((olm->customWidth * olm->customHeight + 8) / 8); - lightBytesNew = safe_malloc(olm->customWidth * olm->customHeight * 3); - if(deluxemap) - dirBytesNew = safe_malloc(olm->customWidth * olm->customHeight * 3); - - /* - memset(olm->lightBits, 0, (olm->customWidth * olm->customHeight + 8) / 8); - olm->lightBits[0] |= 1; - olm->lightBits[(10 * olm->customWidth + 30) >> 3] |= 1 << ((10 * olm->customWidth + 30) & 7); - memset(olm->bspLightBytes, 0, olm->customWidth * olm->customHeight * 3); - olm->bspLightBytes[0] = 255; - olm->bspLightBytes[(10 * olm->customWidth + 30) * 3 + 2] = 255; - */ - - memcpy(lightBitsNew, olm->lightBits, (olm->customWidth * olm->customHeight + 8) / 8); - memcpy(lightBytesNew, olm->bspLightBytes, olm->customWidth * olm->customHeight * 3); - if(deluxemap) - memcpy(dirBytesNew, olm->bspDirBytes, olm->customWidth * olm->customHeight * 3); - - for(;;) - { - filled = 0; - for(y = 0; y < olm->customHeight; ++y) - { - for(x = 0; x < olm->customWidth; ++x) - { - ofs = y * olm->customWidth + x; - if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ - continue; - cnt = 0; - VectorClear(dir_sum); - VectorClear(light_sum); - - /* try all four neighbors */ - ofs = ((y + olm->customHeight - 1) % olm->customHeight) * olm->customWidth + x; - if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ - { - ++cnt; - VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); - if(deluxemap) - VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); - } - - ofs = ((y + 1) % olm->customHeight) * olm->customWidth + x; - if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ - { - ++cnt; - VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); - if(deluxemap) - VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); - } - - ofs = y * olm->customWidth + (x + olm->customWidth - 1) % olm->customWidth; - if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ - { - ++cnt; - VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); - if(deluxemap) - VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); - } - - ofs = y * olm->customWidth + (x + 1) % olm->customWidth; - if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ - { - ++cnt; - VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); - if(deluxemap) - VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); - } - - if(cnt) - { - ++filled; - ofs = y * olm->customWidth + x; - lightBitsNew[ofs >> 3] |= (1 << (ofs & 7)); - VectorScale(light_sum, 1.0/cnt, lightBytesNew + ofs * 3); - if(deluxemap) - VectorScale(dir_sum, 1.0/cnt, dirBytesNew + ofs * 3); - } - } - } - - if(!filled) - break; - - memcpy(olm->lightBits, lightBitsNew, (olm->customWidth * olm->customHeight + 8) / 8); - memcpy(olm->bspLightBytes, lightBytesNew, olm->customWidth * olm->customHeight * 3); - if(deluxemap) - memcpy(olm->bspDirBytes, dirBytesNew, olm->customWidth * olm->customHeight * 3); - } - - free(lightBitsNew); - free(lightBytesNew); - if(deluxemap) - free(dirBytesNew); -} - -/* -StoreSurfaceLightmaps() -stores the surface lightmaps into the bsp as byte rgb triplets -*/ - -void StoreSurfaceLightmaps( void ) -{ - int i, j, k, x, y, lx, ly, sx, sy, *cluster, mappedSamples; - int style, size, lightmapNum, lightmapNum2; - float *normal, *luxel, *bspLuxel, *bspLuxel2, *radLuxel, samples, occludedSamples; - vec3_t sample, occludedSample, dirSample, colorMins, colorMaxs; - float *deluxel, *bspDeluxel, *bspDeluxel2; - byte *lb; - int numUsed, numTwins, numTwinLuxels, numStored; - float lmx, lmy, efficiency; - vec3_t color; - bspDrawSurface_t *ds, *parent, dsTemp; - surfaceInfo_t *info; - rawLightmap_t *lm, *lm2; - outLightmap_t *olm; - bspDrawVert_t *dv, *ydv, *dvParent; - char dirname[ 1024 ], filename[ 1024 ]; - shaderInfo_t *csi; - char lightmapName[ 128 ]; - const char *rgbGenValues[ 256 ]; - const char *alphaGenValues[ 256 ]; - - - /* note it */ - Sys_Printf( "--- StoreSurfaceLightmaps ---\n"); - - /* setup */ - if(lmCustomDir) - { - strcpy( dirname, lmCustomDir ); - } - else - { - strcpy( dirname, source ); - StripExtension( dirname ); - } - memset( rgbGenValues, 0, sizeof( rgbGenValues ) ); - memset( alphaGenValues, 0, sizeof( alphaGenValues ) ); - - /* ----------------------------------------------------------------- - average the sampled luxels into the bsp luxels - ----------------------------------------------------------------- */ - - /* note it */ - Sys_Printf( "Subsampling..." ); - - /* walk the list of raw lightmaps */ - numUsed = 0; - numTwins = 0; - numTwinLuxels = 0; - numSolidLightmaps = 0; - for( i = 0; i < numRawLightmaps; i++ ) - { - /* get lightmap */ - lm = &rawLightmaps[ i ]; - - /* walk individual lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early outs */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - - /* allocate bsp luxel storage */ - if( lm->bspLuxels[ lightmapNum ] == NULL ) - { - size = lm->w * lm->h * BSP_LUXEL_SIZE * sizeof( float ); - lm->bspLuxels[ lightmapNum ] = safe_malloc( size ); - memset( lm->bspLuxels[ lightmapNum ], 0, size ); - } - - /* allocate radiosity lightmap storage */ - if( bounce ) - { - size = lm->w * lm->h * RAD_LUXEL_SIZE * sizeof( float ); - if( lm->radLuxels[ lightmapNum ] == NULL ) - lm->radLuxels[ lightmapNum ] = safe_malloc( size ); - memset( lm->radLuxels[ lightmapNum ], 0, size ); - } - - /* average supersampled luxels */ - for( y = 0; y < lm->h; y++ ) - { - for( x = 0; x < lm->w; x++ ) - { - /* subsample */ - samples = 0.0f; - occludedSamples = 0.0f; - mappedSamples = 0; - VectorClear( sample ); - VectorClear( occludedSample ); - VectorClear( dirSample ); - for( ly = 0; ly < superSample; ly++ ) - { - for( lx = 0; lx < superSample; lx++ ) - { - /* sample luxel */ - sx = x * superSample + lx; - sy = y * superSample + ly; - luxel = SUPER_LUXEL( lightmapNum, sx, sy ); - deluxel = SUPER_DELUXEL( sx, sy ); - normal = SUPER_NORMAL( sx, sy ); - cluster = SUPER_CLUSTER( sx, sy ); - - /* sample deluxemap */ - if( deluxemap && lightmapNum == 0 ) - VectorAdd( dirSample, deluxel, dirSample ); - - /* keep track of used/occluded samples */ - if( *cluster != CLUSTER_UNMAPPED ) - mappedSamples++; - - /* handle lightmap border? */ - if( lightmapBorder && (sx == 0 || sx == (lm->sw - 1) || sy == 0 || sy == (lm->sh - 1) ) && luxel[ 3 ] > 0.0f ) - { - VectorSet( sample, 255.0f, 0.0f, 0.0f ); - samples += 1.0f; - } - - /* handle debug */ - else if( debug && *cluster < 0 ) - { - if( *cluster == CLUSTER_UNMAPPED ) - VectorSet( luxel, 255, 204, 0 ); - else if( *cluster == CLUSTER_OCCLUDED ) - VectorSet( luxel, 255, 0, 255 ); - else if( *cluster == CLUSTER_FLOODED ) - VectorSet( luxel, 0, 32, 255 ); - VectorAdd( occludedSample, luxel, occludedSample ); - occludedSamples += 1.0f; - } - - /* normal luxel handling */ - else if( luxel[ 3 ] > 0.0f ) - { - /* handle lit or flooded luxels */ - if( *cluster > 0 || *cluster == CLUSTER_FLOODED ) - { - VectorAdd( sample, luxel, sample ); - samples += luxel[ 3 ]; - } - - /* handle occluded or unmapped luxels */ - else - { - VectorAdd( occludedSample, luxel, occludedSample ); - occludedSamples += luxel[ 3 ]; - } - - /* handle style debugging */ - if( debug && lightmapNum > 0 && x < 2 && y < 2 ) - { - VectorCopy( debugColors[ 0 ], sample ); - samples = 1; - } - } - } - } - - /* only use occluded samples if necessary */ - if( samples <= 0.0f ) - { - VectorCopy( occludedSample, sample ); - samples = occludedSamples; - } - - /* get luxels */ - luxel = SUPER_LUXEL( lightmapNum, x, y ); - deluxel = SUPER_DELUXEL( x, y ); - - /* store light direction */ - if( deluxemap && lightmapNum == 0 ) - VectorCopy( dirSample, deluxel ); - - /* store the sample back in super luxels */ - if( samples > 0.01f ) - { - VectorScale( sample, (1.0f / samples), luxel ); - luxel[ 3 ] = 1.0f; - } - - /* if any samples were mapped in any way, store ambient color */ - else if( mappedSamples > 0 ) - { - if( lightmapNum == 0 ) - VectorCopy( ambientColor, luxel ); - else - VectorClear( luxel ); - luxel[ 3 ] = 1.0f; - } - - /* store a bogus value to be fixed later */ - else - { - VectorClear( luxel ); - luxel[ 3 ] = -1.0f; - } - } - } - - /* setup */ - lm->used = 0; - ClearBounds( colorMins, colorMaxs ); - - /* clean up and store into bsp luxels */ - for( y = 0; y < lm->h; y++ ) - { - for( x = 0; x < lm->w; x++ ) - { - /* get luxels */ - luxel = SUPER_LUXEL( lightmapNum, x, y ); - deluxel = SUPER_DELUXEL( x, y ); - - /* copy light direction */ - if( deluxemap && lightmapNum == 0 ) - VectorCopy( deluxel, dirSample ); - - /* is this a valid sample? */ - if( luxel[ 3 ] > 0.0f ) - { - VectorCopy( luxel, sample ); - samples = luxel[ 3 ]; - numUsed++; - lm->used++; - - /* fix negative samples */ - for( j = 0; j < 3; j++ ) - { - if( sample[ j ] < 0.0f ) - sample[ j ] = 0.0f; - } - } - else - { - /* nick an average value from the neighbors */ - VectorClear( sample ); - VectorClear( dirSample ); - samples = 0.0f; - - /* fixme: why is this disabled?? */ - for( sy = (y - 1); sy <= (y + 1); sy++ ) - { - if( sy < 0 || sy >= lm->h ) - continue; - - for( sx = (x - 1); sx <= (x + 1); sx++ ) - { - if( sx < 0 || sx >= lm->w || (sx == x && sy == y) ) - continue; - - /* get neighbor's particulars */ - luxel = SUPER_LUXEL( lightmapNum, sx, sy ); - if( luxel[ 3 ] < 0.0f ) - continue; - VectorAdd( sample, luxel, sample ); - samples += luxel[ 3 ]; - } - } - - /* no samples? */ - if( samples == 0.0f ) - { - VectorSet( sample, -1.0f, -1.0f, -1.0f ); - samples = 1.0f; - } - else - { - numUsed++; - lm->used++; - - /* fix negative samples */ - for( j = 0; j < 3; j++ ) - { - if( sample[ j ] < 0.0f ) - sample[ j ] = 0.0f; - } - } - } - - /* scale the sample */ - VectorScale( sample, (1.0f / samples), sample ); - - /* store the sample in the radiosity luxels */ - if( bounce > 0 ) - { - radLuxel = RAD_LUXEL( lightmapNum, x, y ); - VectorCopy( sample, radLuxel ); - - /* if only storing bounced light, early out here */ - if( bounceOnly && !bouncing ) - continue; - } - - /* store the sample in the bsp luxels */ - bspLuxel = BSP_LUXEL( lightmapNum, x, y ); - bspDeluxel = BSP_DELUXEL( x, y ); - - VectorAdd( bspLuxel, sample, bspLuxel ); - if( deluxemap && lightmapNum == 0 ) - VectorAdd( bspDeluxel, dirSample, bspDeluxel ); - - /* add color to bounds for solid checking */ - if( samples > 0.0f ) - AddPointToBounds( bspLuxel, colorMins, colorMaxs ); - } - } - - /* set solid color */ - lm->solid[ lightmapNum ] = qfalse; - VectorAdd( colorMins, colorMaxs, lm->solidColor[ lightmapNum ] ); - VectorScale( lm->solidColor[ lightmapNum ], 0.5f, lm->solidColor[ lightmapNum ] ); - - /* nocollapse prevents solid lightmaps */ - if( noCollapse == qfalse ) - { - /* check solid color */ - VectorSubtract( colorMaxs, colorMins, sample ); - if( (sample[ 0 ] <= SOLID_EPSILON && sample[ 1 ] <= SOLID_EPSILON && sample[ 2 ] <= SOLID_EPSILON) || - (lm->w <= 2 && lm->h <= 2) ) /* small lightmaps get forced to solid color */ - { - /* set to solid */ - VectorCopy( colorMins, lm->solidColor[ lightmapNum ] ); - lm->solid[ lightmapNum ] = qtrue; - numSolidLightmaps++; - } - - /* if all lightmaps aren't solid, then none of them are solid */ - if( lm->solid[ lightmapNum ] != lm->solid[ 0 ] ) - { - for( y = 0; y < MAX_LIGHTMAPS; y++ ) - { - if( lm->solid[ y ] ) - numSolidLightmaps--; - lm->solid[ y ] = qfalse; - } - } - } - - /* wrap bsp luxels if necessary */ - if( lm->wrap[ 0 ] ) - { - for( y = 0; y < lm->h; y++ ) - { - bspLuxel = BSP_LUXEL( lightmapNum, 0, y ); - bspLuxel2 = BSP_LUXEL( lightmapNum, lm->w - 1, y ); - VectorAdd( bspLuxel, bspLuxel2, bspLuxel ); - VectorScale( bspLuxel, 0.5f, bspLuxel ); - VectorCopy( bspLuxel, bspLuxel2 ); - if( deluxemap && lightmapNum == 0 ) - { - bspDeluxel = BSP_DELUXEL( 0, y ); - bspDeluxel2 = BSP_DELUXEL( lm->w - 1, y ); - VectorAdd( bspDeluxel, bspDeluxel2, bspDeluxel ); - VectorScale( bspDeluxel, 0.5f, bspDeluxel ); - VectorCopy( bspDeluxel, bspDeluxel2 ); - } - } - } - if( lm->wrap[ 1 ] ) - { - for( x = 0; x < lm->w; x++ ) - { - bspLuxel = BSP_LUXEL( lightmapNum, x, 0 ); - bspLuxel2 = BSP_LUXEL( lightmapNum, x, lm->h - 1 ); - VectorAdd( bspLuxel, bspLuxel2, bspLuxel ); - VectorScale( bspLuxel, 0.5f, bspLuxel ); - VectorCopy( bspLuxel, bspLuxel2 ); - if( deluxemap && lightmapNum == 0 ) - { - bspDeluxel = BSP_DELUXEL( x, 0 ); - bspDeluxel2 = BSP_DELUXEL( x, lm->h - 1 ); - VectorAdd( bspDeluxel, bspDeluxel2, bspDeluxel ); - VectorScale( bspDeluxel, 0.5f, bspDeluxel ); - VectorCopy( bspDeluxel, bspDeluxel2 ); - } - } - } - } - } - - /* ----------------------------------------------------------------- - convert modelspace deluxemaps to tangentspace - ----------------------------------------------------------------- */ - /* note it */ - if( !bouncing ) - { - if( deluxemap && deluxemode == 1) - { - vec3_t worldUp, myNormal, myTangent, myBinormal; - float dist; - - Sys_Printf( "converting..." ); - - for( i = 0; i < numRawLightmaps; i++ ) - { - /* get lightmap */ - lm = &rawLightmaps[ i ]; - - /* walk lightmap samples */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get normal and deluxel */ - normal = SUPER_NORMAL(x, y); - cluster = SUPER_CLUSTER(x, y); - bspDeluxel = BSP_DELUXEL( x, y ); - deluxel = SUPER_DELUXEL( x, y ); - - /* get normal */ - VectorSet( myNormal, normal[0], normal[1], normal[2] ); - - /* get tangent vectors */ - if( myNormal[ 0 ] == 0.0f && myNormal[ 1 ] == 0.0f ) - { - if( myNormal[ 2 ] == 1.0f ) - { - VectorSet( myTangent, 1.0f, 0.0f, 0.0f ); - VectorSet( myBinormal, 0.0f, 1.0f, 0.0f ); - } - else if( myNormal[ 2 ] == -1.0f ) - { - VectorSet( myTangent, -1.0f, 0.0f, 0.0f ); - VectorSet( myBinormal, 0.0f, 1.0f, 0.0f ); - } - } - else - { - VectorSet( worldUp, 0.0f, 0.0f, 1.0f ); - CrossProduct( myNormal, worldUp, myTangent ); - VectorNormalize( myTangent, myTangent ); - CrossProduct( myTangent, myNormal, myBinormal ); - VectorNormalize( myBinormal, myBinormal ); - } - - /* project onto plane */ - dist = -DotProduct(myTangent, myNormal); - VectorMA(myTangent, dist, myNormal, myTangent); - dist = -DotProduct(myBinormal, myNormal); - VectorMA(myBinormal, dist, myNormal, myBinormal); - - /* renormalize */ - VectorNormalize( myTangent, myTangent ); - VectorNormalize( myBinormal, myBinormal ); - - /* convert modelspace deluxel to tangentspace */ - dirSample[0] = bspDeluxel[0]; - dirSample[1] = bspDeluxel[1]; - dirSample[2] = bspDeluxel[2]; - VectorNormalize(dirSample, dirSample); - - /* fix tangents to world matrix */ - if (myNormal[0] > 0 || myNormal[1] < 0 || myNormal[2] < 0) - VectorNegate(myTangent, myTangent); - - /* build tangentspace vectors */ - bspDeluxel[0] = DotProduct(dirSample, myTangent); - bspDeluxel[1] = DotProduct(dirSample, myBinormal); - bspDeluxel[2] = DotProduct(dirSample, myNormal); - } - } - } - } - } - - /* ----------------------------------------------------------------- - blend lightmaps - ----------------------------------------------------------------- */ - -#ifdef sdfsdfwq312323 - /* note it */ - Sys_Printf( "blending..." ); - - for( i = 0; i < numRawLightmaps; i++ ) - { - vec3_t myColor; - float myBrightness; - - /* get lightmap */ - lm = &rawLightmaps[ i ]; - - /* walk individual lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early outs */ - if( lm->superLuxels[ lightmapNum ] == NULL ) - continue; - - /* walk lightmap samples */ - for( y = 0; y < lm->sh; y++ ) - { - for( x = 0; x < lm->sw; x++ ) - { - /* get luxel */ - bspLuxel = BSP_LUXEL( lightmapNum, x, y ); - - /* get color */ - VectorNormalize(bspLuxel, myColor); - myBrightness = VectorLength(bspLuxel); - myBrightness *= (1 / 127.0f); - myBrightness = myBrightness*myBrightness; - myBrightness *= 127.0f; - VectorScale(myColor, myBrightness, bspLuxel); - } - } - } - } -#endif - - /* ----------------------------------------------------------------- - collapse non-unique lightmaps - ----------------------------------------------------------------- */ - - if( noCollapse == qfalse && deluxemap == qfalse ) - { - /* note it */ - Sys_Printf( "collapsing..." ); - - /* set all twin refs to null */ - for( i = 0; i < numRawLightmaps; i++ ) - { - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - rawLightmaps[ i ].twins[ lightmapNum ] = NULL; - rawLightmaps[ i ].twinNums[ lightmapNum ] = -1; - rawLightmaps[ i ].numStyledTwins = 0; - } - } - - /* walk the list of raw lightmaps */ - for( i = 0; i < numRawLightmaps; i++ ) - { - /* get lightmap */ - lm = &rawLightmaps[ i ]; - - /* walk lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early outs */ - if( lm->bspLuxels[ lightmapNum ] == NULL || - lm->twins[ lightmapNum ] != NULL ) - continue; - - /* find all lightmaps that are virtually identical to this one */ - for( j = i + 1; j < numRawLightmaps; j++ ) - { - /* get lightmap */ - lm2 = &rawLightmaps[ j ]; - - /* walk lightmaps */ - for( lightmapNum2 = 0; lightmapNum2 < MAX_LIGHTMAPS; lightmapNum2++ ) - { - /* early outs */ - if( lm2->bspLuxels[ lightmapNum2 ] == NULL || - lm2->twins[ lightmapNum2 ] != NULL ) - continue; - - /* compare them */ - if( CompareBSPLuxels( lm, lightmapNum, lm2, lightmapNum2 ) ) - { - /* merge and set twin */ - if( MergeBSPLuxels( lm, lightmapNum, lm2, lightmapNum2 ) ) - { - lm2->twins[ lightmapNum2 ] = lm; - lm2->twinNums[ lightmapNum2 ] = lightmapNum; - numTwins++; - numTwinLuxels += (lm->w * lm->h); - - /* count styled twins */ - if( lightmapNum > 0 ) - lm->numStyledTwins++; - } - } - } - } - } - } - } - - /* ----------------------------------------------------------------- - sort raw lightmaps by shader - ----------------------------------------------------------------- */ - - /* note it */ - Sys_Printf( "sorting..." ); - - /* allocate a new sorted list */ - if( sortLightmaps == NULL ) - sortLightmaps = safe_malloc( numRawLightmaps * sizeof( int ) ); - - /* fill it out and sort it */ - for( i = 0; i < numRawLightmaps; i++ ) - sortLightmaps[ i ] = i; - qsort( sortLightmaps, numRawLightmaps, sizeof( int ), CompareRawLightmap ); - - /* ----------------------------------------------------------------- - allocate output lightmaps - ----------------------------------------------------------------- */ - - /* note it */ - Sys_Printf( "allocating..." ); - - /* kill all existing output lightmaps */ - if( outLightmaps != NULL ) - { - for( i = 0; i < numOutLightmaps; i++ ) - { - free( outLightmaps[ i ].lightBits ); - free( outLightmaps[ i ].bspLightBytes ); - } - free( outLightmaps ); - outLightmaps = NULL; - } - - numLightmapShaders = 0; - numOutLightmaps = 0; - numBSPLightmaps = 0; - numExtLightmaps = 0; - - /* find output lightmap */ - for( i = 0; i < numRawLightmaps; i++ ) - { - lm = &rawLightmaps[ sortLightmaps[ i ] ]; - FindOutLightmaps( lm ); - } - - /* set output numbers in twinned lightmaps */ - for( i = 0; i < numRawLightmaps; i++ ) - { - /* get lightmap */ - lm = &rawLightmaps[ sortLightmaps[ i ] ]; - - /* walk lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* get twin */ - lm2 = lm->twins[ lightmapNum ]; - if( lm2 == NULL ) - continue; - lightmapNum2 = lm->twinNums[ lightmapNum ]; - - /* find output lightmap from twin */ - lm->outLightmapNums[ lightmapNum ] = lm2->outLightmapNums[ lightmapNum2 ]; - lm->lightmapX[ lightmapNum ] = lm2->lightmapX[ lightmapNum2 ]; - lm->lightmapY[ lightmapNum ] = lm2->lightmapY[ lightmapNum2 ]; - } - } - - /* ----------------------------------------------------------------- - store output lightmaps - ----------------------------------------------------------------- */ - - /* note it */ - Sys_Printf( "storing..." ); - - /* count the bsp lightmaps and allocate space */ - if( bspLightBytes != NULL ) - free( bspLightBytes ); - if( numBSPLightmaps == 0 || externalLightmaps ) - { - numBSPLightBytes = 0; - bspLightBytes = NULL; - } - else - { - numBSPLightBytes = (numBSPLightmaps * game->lightmapSize * game->lightmapSize * 3); - bspLightBytes = safe_malloc( numBSPLightBytes ); - memset( bspLightBytes, 0, numBSPLightBytes ); - } - - /* walk the list of output lightmaps */ - for( i = 0; i < numOutLightmaps; i++ ) - { - /* get output lightmap */ - olm = &outLightmaps[ i ]; - - /* fill output lightmap */ - if(lightmapFill) - FillOutLightmap(olm); - - /* is this a valid bsp lightmap? */ - if( olm->lightmapNum >= 0 && !externalLightmaps ) - { - /* copy lighting data */ - lb = bspLightBytes + (olm->lightmapNum * game->lightmapSize * game->lightmapSize * 3); - memcpy( lb, olm->bspLightBytes, game->lightmapSize * game->lightmapSize * 3 ); - - /* copy direction data */ - if( deluxemap ) - { - lb = bspLightBytes + ((olm->lightmapNum + 1) * game->lightmapSize * game->lightmapSize * 3); - memcpy( lb, olm->bspDirBytes, game->lightmapSize * game->lightmapSize * 3 ); - } - } - - /* external lightmap? */ - if( olm->lightmapNum < 0 || olm->extLightmapNum >= 0 || externalLightmaps ) - { - /* make a directory for the lightmaps */ - Q_mkdir( dirname ); - - /* set external lightmap number */ - olm->extLightmapNum = numExtLightmaps; - - /* write lightmap */ - sprintf( filename, "%s/" EXTERNAL_LIGHTMAP, dirname, numExtLightmaps ); - Sys_FPrintf( SYS_VRB, "\nwriting %s", filename ); - WriteTGA24( filename, olm->bspLightBytes, olm->customWidth, olm->customHeight, qtrue ); - numExtLightmaps++; - - /* write deluxemap */ - if( deluxemap ) - { - sprintf( filename, "%s/" EXTERNAL_LIGHTMAP, dirname, numExtLightmaps ); - Sys_FPrintf( SYS_VRB, "\nwriting %s", filename ); - WriteTGA24( filename, olm->bspDirBytes, olm->customWidth, olm->customHeight, qtrue ); - numExtLightmaps++; - - if( debugDeluxemap ) - olm->extLightmapNum++; - } - } - } - - if( numExtLightmaps > 0 ) - Sys_Printf( "\n" ); - - /* delete unused external lightmaps */ - for( i = numExtLightmaps; i; i++ ) - { - /* determine if file exists */ - sprintf( filename, "%s/" EXTERNAL_LIGHTMAP, dirname, i ); - if( !FileExists( filename ) ) - break; - - /* delete it */ - remove( filename ); - } - - /* ----------------------------------------------------------------- - project the lightmaps onto the bsp surfaces - ----------------------------------------------------------------- */ - - /* note it */ - Sys_Printf( "projecting..." ); - - /* walk the list of surfaces */ - for( i = 0; i < numBSPDrawSurfaces; i++ ) - { - /* get the surface and info */ - ds = &bspDrawSurfaces[ i ]; - info = &surfaceInfos[ i ]; - lm = info->lm; - olm = NULL; - - /* handle surfaces with identical parent */ - if( info->parentSurfaceNum >= 0 ) - { - /* preserve original data and get parent */ - parent = &bspDrawSurfaces[ info->parentSurfaceNum ]; - memcpy( &dsTemp, ds, sizeof( *ds ) ); - - /* overwrite child with parent data */ - memcpy( ds, parent, sizeof( *ds ) ); - - /* restore key parts */ - ds->fogNum = dsTemp.fogNum; - ds->firstVert = dsTemp.firstVert; - ds->firstIndex = dsTemp.firstIndex; - memcpy( ds->lightmapVecs, dsTemp.lightmapVecs, sizeof( dsTemp.lightmapVecs ) ); - - /* set vertex data */ - dv = &bspDrawVerts[ ds->firstVert ]; - dvParent = &bspDrawVerts[ parent->firstVert ]; - for( j = 0; j < ds->numVerts; j++ ) - { - memcpy( dv[ j ].lightmap, dvParent[ j ].lightmap, sizeof( dv[ j ].lightmap ) ); - memcpy( dv[ j ].color, dvParent[ j ].color, sizeof( dv[ j ].color ) ); - } - - /* skip the rest */ - continue; - } - - /* handle vertex lit or approximated surfaces */ - else if( lm == NULL || lm->outLightmapNums[ 0 ] < 0 ) - { - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - ds->lightmapNum[ lightmapNum ] = -3; - ds->lightmapStyles[ lightmapNum ] = ds->vertexStyles[ lightmapNum ]; - } - } - - /* handle lightmapped surfaces */ - else - { - /* walk lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* set style */ - ds->lightmapStyles[ lightmapNum ] = lm->styles[ lightmapNum ]; - - /* handle unused style */ - if( lm->styles[ lightmapNum ] == LS_NONE || lm->outLightmapNums[ lightmapNum ] < 0 ) - { - ds->lightmapNum[ lightmapNum ] = -3; - continue; - } - - /* get output lightmap */ - olm = &outLightmaps[ lm->outLightmapNums[ lightmapNum ] ]; - - /* set bsp lightmap number */ - ds->lightmapNum[ lightmapNum ] = olm->lightmapNum; - - /* deluxemap debugging makes the deluxemap visible */ - if( deluxemap && debugDeluxemap && lightmapNum == 0 ) - ds->lightmapNum[ lightmapNum ]++; - - /* calc lightmap origin in texture space */ - lmx = (float) lm->lightmapX[ lightmapNum ] / (float) olm->customWidth; - lmy = (float) lm->lightmapY[ lightmapNum ] / (float) olm->customHeight; - - /* calc lightmap st coords */ - dv = &bspDrawVerts[ ds->firstVert ]; - ydv = &yDrawVerts[ ds->firstVert ]; - for( j = 0; j < ds->numVerts; j++ ) - { - if( lm->solid[ lightmapNum ] ) - { - dv[ j ].lightmap[ lightmapNum ][ 0 ] = lmx + (0.5f / (float) olm->customWidth); - dv[ j ].lightmap[ lightmapNum ][ 1 ] = lmy + (0.5f / (float) olm->customWidth); - } - else - { - dv[ j ].lightmap[ lightmapNum ][ 0 ] = lmx + (ydv[ j ].lightmap[ 0 ][ 0 ] / (superSample * olm->customWidth)); - dv[ j ].lightmap[ lightmapNum ][ 1 ] = lmy + (ydv[ j ].lightmap[ 0 ][ 1 ] / (superSample * olm->customHeight)); - } - } - } - } - - /* store vertex colors */ - dv = &bspDrawVerts[ ds->firstVert ]; - for( j = 0; j < ds->numVerts; j++ ) - { - /* walk lightmaps */ - for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* handle unused style */ - if( ds->vertexStyles[ lightmapNum ] == LS_NONE ) - VectorClear( color ); - else - { - /* get vertex color */ - luxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + j ); - VectorCopy( luxel, color ); - - /* set minimum light */ - if( lightmapNum == 0 ) - { - for( k = 0; k < 3; k++ ) - if( color[ k ] < minVertexLight[ k ] ) - color[ k ] = minVertexLight[ k ]; - } - } - - /* store to bytes */ - if( !info->si->noVertexLight ) - ColorToBytes( color, dv[ j ].color[ lightmapNum ], info->si->vertexScale ); - } - } - - /* surfaces with styled lightmaps and a style marker get a custom generated shader (fixme: make this work with external lightmaps) */ - if( olm != NULL && lm != NULL && lm->styles[ 1 ] != LS_NONE && game->load != LoadRBSPFile ) //% info->si->styleMarker > 0 ) - { - qboolean dfEqual; - char key[ 32 ], styleStage[ 512 ], styleStages[ 4096 ], rgbGen[ 128 ], alphaGen[ 128 ]; - - - /* setup */ - sprintf( styleStages, "\n\t// Q3Map2 custom lightstyle stage(s)\n" ); - dv = &bspDrawVerts[ ds->firstVert ]; - - /* depthFunc equal? */ - if( info->si->styleMarker == 2 || info->si->implicitMap == IM_MASKED ) - dfEqual = qtrue; - else - dfEqual = qfalse; - - /* generate stages for styled lightmaps */ - for( lightmapNum = 1; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) - { - /* early out */ - style = lm->styles[ lightmapNum ]; - if( style == LS_NONE || lm->outLightmapNums[ lightmapNum ] < 0 ) - continue; - - /* get output lightmap */ - olm = &outLightmaps[ lm->outLightmapNums[ lightmapNum ] ]; - - /* lightmap name */ - if( lm->outLightmapNums[ lightmapNum ] == lm->outLightmapNums[ 0 ] ) - strcpy( lightmapName, "$lightmap" ); - else - sprintf( lightmapName, "maps/%s/" EXTERNAL_LIGHTMAP, mapName, olm->extLightmapNum ); - - /* get rgbgen string */ - if( rgbGenValues[ style ] == NULL ) - { - sprintf( key, "_style%drgbgen", style ); - rgbGenValues[ style ] = ValueForKey( &entities[ 0 ], key ); - if( rgbGenValues[ style ][ 0 ] == '\0' ) - rgbGenValues[ style ] = "wave noise 0.5 1 0 5.37"; - } - rgbGen[ 0 ] = '\0'; - if( rgbGenValues[ style ][ 0 ] != '\0' ) - sprintf( rgbGen, "\t\trgbGen %s // style %d\n", rgbGenValues[ style ], style ); - else - rgbGen[ 0 ] = '\0'; - - /* get alphagen string */ - if( alphaGenValues[ style ] == NULL ) - { - sprintf( key, "_style%dalphagen", style ); - alphaGenValues[ style ] = ValueForKey( &entities[ 0 ], key ); - } - if( alphaGenValues[ style ][ 0 ] != '\0' ) - sprintf( alphaGen, "\t\talphaGen %s // style %d\n", alphaGenValues[ style ], style ); - else - alphaGen[ 0 ] = '\0'; - - /* calculate st offset */ - lmx = dv[ 0 ].lightmap[ lightmapNum ][ 0 ] - dv[ 0 ].lightmap[ 0 ][ 0 ]; - lmy = dv[ 0 ].lightmap[ lightmapNum ][ 1 ] - dv[ 0 ].lightmap[ 0 ][ 1 ]; - - /* create additional stage */ - if( lmx == 0.0f && lmy == 0.0f ) - { - sprintf( styleStage, "\t{\n" - "\t\tmap %s\n" /* lightmap */ - "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" - "%s" /* depthFunc equal */ - "%s" /* rgbGen */ - "%s" /* alphaGen */ - "\t\ttcGen lightmap\n" - "\t}\n", - lightmapName, - (dfEqual ? "\t\tdepthFunc equal\n" : ""), - rgbGen, - alphaGen ); - } - else - { - sprintf( styleStage, "\t{\n" - "\t\tmap %s\n" /* lightmap */ - "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" - "%s" /* depthFunc equal */ - "%s" /* rgbGen */ - "%s" /* alphaGen */ - "\t\ttcGen lightmap\n" - "\t\ttcMod transform 1 0 0 1 %1.5f %1.5f\n" /* st offset */ - "\t}\n", - lightmapName, - (dfEqual ? "\t\tdepthFunc equal\n" : ""), - rgbGen, - alphaGen, - lmx, lmy ); - - } - - /* concatenate */ - strcat( styleStages, styleStage ); - } - - /* create custom shader */ - if( info->si->styleMarker == 2 ) - csi = CustomShader( info->si, "q3map_styleMarker2", styleStages ); - else - csi = CustomShader( info->si, "q3map_styleMarker", styleStages ); - - /* emit remap command */ - //% EmitVertexRemapShader( csi->shader, info->si->shader ); - - /* store it */ - //% Sys_Printf( "Emitting: %s (%d", csi->shader, strlen( csi->shader ) ); - ds->shaderNum = EmitShader( csi->shader, &bspShaders[ ds->shaderNum ].contentFlags, &bspShaders[ ds->shaderNum ].surfaceFlags ); - //% Sys_Printf( ")\n" ); - } - - /* devise a custom shader for this surface (fixme: make this work with light styles) */ - else if( olm != NULL && lm != NULL && !externalLightmaps && - (olm->customWidth != game->lightmapSize || olm->customHeight != game->lightmapSize) ) - { - /* get output lightmap */ - olm = &outLightmaps[ lm->outLightmapNums[ 0 ] ]; - - /* do some name mangling */ - sprintf( lightmapName, "maps/%s/" EXTERNAL_LIGHTMAP, mapName, olm->extLightmapNum ); - - /* create custom shader */ - csi = CustomShader( info->si, "$lightmap", lightmapName ); - - /* store it */ - //% Sys_Printf( "Emitting: %s (%d", csi->shader, strlen( csi->shader ) ); - ds->shaderNum = EmitShader( csi->shader, &bspShaders[ ds->shaderNum ].contentFlags, &bspShaders[ ds->shaderNum ].surfaceFlags ); - //% Sys_Printf( ")\n" ); - } - - /* use the normal plain-jane shader */ - else - ds->shaderNum = EmitShader( info->si->shader, &bspShaders[ ds->shaderNum ].contentFlags, &bspShaders[ ds->shaderNum ].surfaceFlags ); - } - - /* finish */ - Sys_Printf( "done.\n" ); - - /* calc num stored */ - numStored = numBSPLightBytes / 3; - efficiency = (numStored <= 0) - ? 0 - : (float) numUsed / (float) numStored; - - /* print stats */ - Sys_Printf( "%9d luxels used\n", numUsed ); - Sys_Printf( "%9d luxels stored (%3.2f percent efficiency)\n", numStored, efficiency * 100.0f ); - Sys_Printf( "%9d solid surface lightmaps\n", numSolidLightmaps ); - Sys_Printf( "%9d identical surface lightmaps, using %d luxels\n", numTwins, numTwinLuxels ); - Sys_Printf( "%9d vertex forced surfaces\n", numSurfsVertexForced ); - Sys_Printf( "%9d vertex approximated surfaces\n", numSurfsVertexApproximated ); - Sys_Printf( "%9d BSP lightmaps\n", numBSPLightmaps ); - Sys_Printf( "%9d total lightmaps\n", numOutLightmaps ); - Sys_Printf( "%9d unique lightmap/shader combinations\n", numLightmapShaders ); - - /* write map shader file */ - WriteMapShaderFile(); -} - - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/listen.pl b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/listen.pl deleted file mode 100644 index 6101a767..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/listen.pl +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/perl -w - -use IO::Socket; -use Net::hostent; - -my $port = shift || 13131; - -my $server = IO::Socket::INET->new( - Proto => 'tcp', - LocalPort => $port, - Listen => SOMAXCONN, - Reuse => 1 ) - || die "can't setup server"; -print "[Q3Map2 listener $0 is now active on port $port]\n"; - -while( $client = $server->accept() ) -{ - - $client->autoflush( 1 ); - - $hostinfo = gethostbyaddr( $client->peeraddr ); - printf "[Connect from %s]\n\n", $hostinfo ? $hostinfo->name : $client->peerhost; - - #ask the client for a command - print $client "[server]\$"; - my $text = ""; - while( <$client> ) - { - $text .= $_; - while( $text =~ s|]*>([^<]+)|| ) - { - my $msg = $1; - - # fix xml ents - $msg =~ s|<|<|g; - $msg =~ s|>|>|g; - $msg =~ s|"|"|g;#" - $msg =~ s|'|'|g;#' - - print $msg; - } - } - - printf "\n[Disconnected: %s]\n\n", $hostinfo ? $hostinfo->name : $client->peerhost; - close $client; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/main.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/main.c deleted file mode 100644 index 074a4a43..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/main.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 - -------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define MAIN_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -Random() -returns a pseudorandom number between 0 and 1 -*/ - -vec_t Random( void ) -{ - return (vec_t) rand() / RAND_MAX; -} - - - -/* -ExitQ3Map() -cleanup routine -*/ - -static void ExitQ3Map( void ) -{ - BSPFilesCleanup(); - if( mapDrawSurfs != NULL ) - free( mapDrawSurfs ); -} - - - -/* minimap stuff */ - -typedef struct minimap_s -{ - bspModel_t *model; - int width; - int height; - int samples; - float *sample_offsets; - float sharpen_boxmult; - float sharpen_centermult; - float boost; - float *data1f; - float *sharpendata1f; - vec3_t mins, size; -} -minimap_t; -static minimap_t minimap; - -qboolean BrushIntersectionWithLine(bspBrush_t *brush, vec3_t start, vec3_t dir, float *t_in, float *t_out) -{ - int i; - qboolean in = qfalse, out = qfalse; - bspBrushSide_t *sides = &bspBrushSides[brush->firstSide]; - - for(i = 0; i < brush->numSides; ++i) - { - bspPlane_t *p = &bspPlanes[sides[i].planeNum]; - float sn = DotProduct(start, p->normal); - float dn = DotProduct(dir, p->normal); - if(dn == 0) - { - if(sn > p->dist) - return qfalse; // outside! - } - else - { - float t = (p->dist - sn) / dn; - if(dn < 0) - { - if(!in || t > *t_in) - { - *t_in = t; - in = qtrue; - // as t_in can only increase, and t_out can only decrease, early out - if(out && *t_in >= *t_out) - return qfalse; - } - } - else - { - if(!out || t < *t_out) - { - *t_out = t; - out = qtrue; - // as t_in can only increase, and t_out can only decrease, early out - if(in && *t_in >= *t_out) - return qfalse; - } - } - } - } - return in && out; -} - -static float MiniMapSample(float x, float y) -{ - vec3_t org, dir; - int i, bi; - float t0, t1; - float samp; - bspBrush_t *b; - bspBrushSide_t *s; - int cnt; - - org[0] = x; - org[1] = y; - org[2] = 0; - dir[0] = 0; - dir[1] = 0; - dir[2] = 1; - - cnt = 0; - samp = 0; - for(i = 0; i < minimap.model->numBSPBrushes; ++i) - { - bi = minimap.model->firstBSPBrush + i; - if(opaqueBrushes[bi >> 3] & (1 << (bi & 7))) - { - b = &bspBrushes[bi]; - - // sort out mins/maxs of the brush - s = &bspBrushSides[b->firstSide]; - if(x < -bspPlanes[s[0].planeNum].dist) - continue; - if(x > +bspPlanes[s[1].planeNum].dist) - continue; - if(y < -bspPlanes[s[2].planeNum].dist) - continue; - if(y > +bspPlanes[s[3].planeNum].dist) - continue; - - if(BrushIntersectionWithLine(b, org, dir, &t0, &t1)) - { - samp += t1 - t0; - ++cnt; - } - } - } - - return samp; -} - -void RandomVector2f(float v[2]) -{ - do - { - v[0] = 2 * Random() - 1; - v[1] = 2 * Random() - 1; - } - while(v[0] * v[0] + v[1] * v[1] > 1); -} - -static void MiniMapRandomlySupersampled(int y) -{ - int x, i; - float *p = &minimap.data1f[y * minimap.width]; - float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height); - float dx = minimap.size[0] / (float) minimap.width; - float dy = minimap.size[1] / (float) minimap.height; - float uv[2]; - float thisval; - - for(x = 0; x < minimap.width; ++x) - { - float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width); - float val = 0; - - for(i = 0; i < minimap.samples; ++i) - { - RandomVector2f(uv); - thisval = MiniMapSample( - xmin + (uv[0] + 0.5) * dx, /* exaggerated random pattern for better results */ - ymin + (uv[1] + 0.5) * dy /* exaggerated random pattern for better results */ - ); - val += thisval; - } - val /= minimap.samples * minimap.size[2]; - *p++ = val; - } -} - -static void MiniMapSupersampled(int y) -{ - int x, i; - float *p = &minimap.data1f[y * minimap.width]; - float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height); - float dx = minimap.size[0] / (float) minimap.width; - float dy = minimap.size[1] / (float) minimap.height; - - for(x = 0; x < minimap.width; ++x) - { - float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width); - float val = 0; - - for(i = 0; i < minimap.samples; ++i) - { - float thisval = MiniMapSample( - xmin + minimap.sample_offsets[2*i+0] * dx, - ymin + minimap.sample_offsets[2*i+1] * dy - ); - val += thisval; - } - val /= minimap.samples * minimap.size[2]; - *p++ = val; - } -} - -static void MiniMapNoSupersampling(int y) -{ - int x; - float *p = &minimap.data1f[y * minimap.width]; - float ymin = minimap.mins[1] + minimap.size[1] * ((y + 0.5) / (float) minimap.height); - - for(x = 0; x < minimap.width; ++x) - { - float xmin = minimap.mins[0] + minimap.size[0] * ((x + 0.5) / (float) minimap.width); - *p++ = MiniMapSample(xmin, ymin) / minimap.size[2]; - } -} - -static void MiniMapSharpen(int y) -{ - int x; - qboolean up = (y > 0); - qboolean down = (y < minimap.height - 1); - float *p = &minimap.data1f[y * minimap.width]; - float *q = &minimap.sharpendata1f[y * minimap.width]; - - for(x = 0; x < minimap.width; ++x) - { - qboolean left = (x > 0); - qboolean right = (x < minimap.width - 1); - float val = p[0] * minimap.sharpen_centermult; - - if(left && up) - val += p[-1 -minimap.width] * minimap.sharpen_boxmult; - if(left && down) - val += p[-1 +minimap.width] * minimap.sharpen_boxmult; - if(right && up) - val += p[+1 -minimap.width] * minimap.sharpen_boxmult; - if(right && down) - val += p[+1 +minimap.width] * minimap.sharpen_boxmult; - - if(left) - val += p[-1] * minimap.sharpen_boxmult; - if(right) - val += p[+1] * minimap.sharpen_boxmult; - if(up) - val += p[-minimap.width] * minimap.sharpen_boxmult; - if(down) - val += p[+minimap.width] * minimap.sharpen_boxmult; - - ++p; - *q++ = val; - } -} - -static void MiniMapContrastBoost(int y) -{ - int x; - float *q = &minimap.data1f[y * minimap.width]; - for(x = 0; x < minimap.width; ++x) - { - *q = *q * minimap.boost / ((minimap.boost - 1) * *q + 1); - ++q; - } -} - -void MiniMapMakeMinsMaxs(vec3_t mins_in, vec3_t maxs_in, float border, qboolean keepaspect) -{ - vec3_t mins, maxs, extend; - VectorCopy(mins_in, mins); - VectorCopy(maxs_in, maxs); - - // line compatible to nexuiz mapinfo - Sys_Printf("size %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]); - - if(keepaspect) - { - VectorSubtract(maxs, mins, extend); - if(extend[1] > extend[0]) - { - mins[0] -= (extend[1] - extend[0]) * 0.5; - maxs[0] += (extend[1] - extend[0]) * 0.5; - } - else - { - mins[1] -= (extend[0] - extend[1]) * 0.5; - maxs[1] += (extend[0] - extend[1]) * 0.5; - } - } - - /* border: amount of black area around the image */ - /* input: border, 1-2*border, border but we need border/(1-2*border) */ - - VectorSubtract(maxs, mins, extend); - VectorScale(extend, border / (1 - 2 * border), extend); - - VectorSubtract(mins, extend, mins); - VectorAdd(maxs, extend, maxs); - - VectorCopy(mins, minimap.mins); - VectorSubtract(maxs, mins, minimap.size); - - // line compatible to nexuiz mapinfo - Sys_Printf("size_texcoords %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]); -} - -/* -MiniMapSetupBrushes() -determines solid non-sky brushes in the world -*/ - -void MiniMapSetupBrushes( void ) -{ - int i, b, compileFlags; - bspBrush_t *brush; - bspShader_t *shader; - shaderInfo_t *si; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- MiniMapSetupBrushes ---\n" ); - - /* allocate */ - if( opaqueBrushes == NULL ) - opaqueBrushes = safe_malloc( numBSPBrushes / 8 + 1 ); - - /* clear */ - memset( opaqueBrushes, 0, numBSPBrushes / 8 + 1 ); - numOpaqueBrushes = 0; - - /* walk the list of worldspawn brushes */ - for( i = 0; i < minimap.model->numBSPBrushes; i++ ) - { - /* get brush */ - b = minimap.model->firstBSPBrush + i; - brush = &bspBrushes[ b ]; - -#if 0 - /* check all sides */ - compileFlags = 0; - for( j = 0; j < brush->numSides; j++ ) - { - /* do bsp shader calculations */ - side = &bspBrushSides[ brush->firstSide + j ]; - shader = &bspShaders[ side->shaderNum ]; - - /* get shader info */ - si = ShaderInfoForShader( shader->shader ); - if( si == NULL ) - continue; - - /* or together compile flags */ - compileFlags |= si->compileFlags; - } -#else - shader = &bspShaders[ brush->shaderNum ]; - si = ShaderInfoForShader( shader->shader ); - if( si == NULL ) - compileFlags = 0; - else - compileFlags = si->compileFlags; -#endif - - /* determine if this brush is solid */ - if( (compileFlags & (C_SOLID | C_SKY)) == C_SOLID ) - { - opaqueBrushes[ b >> 3 ] |= (1 << (b & 7)); - numOpaqueBrushes++; - maxOpaqueBrush = i; - } - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d solid brushes\n", numOpaqueBrushes ); -} - -qboolean MiniMapEvaluateSampleOffsets(int *bestj, int *bestk, float *bestval) -{ - float val, dx, dy; - int j, k; - - *bestj = *bestk = -1; - *bestval = 3; /* max possible val is 2 */ - - for(j = 0; j < minimap.samples; ++j) - for(k = j + 1; k < minimap.samples; ++k) - { - dx = minimap.sample_offsets[2*j+0] - minimap.sample_offsets[2*k+0]; - dy = minimap.sample_offsets[2*j+1] - minimap.sample_offsets[2*k+1]; - if(dx > +0.5) dx -= 1; - if(dx < -0.5) dx += 1; - if(dy > +0.5) dy -= 1; - if(dy < -0.5) dy += 1; - val = dx * dx + dy * dy; - if(val < *bestval) - { - *bestj = j; - *bestk = k; - *bestval = val; - } - } - - return *bestval < 3; -} - -void MiniMapMakeSampleOffsets() -{ - int i, j, k, jj, kk; - float val, valj, valk, sx, sy, rx, ry; - - Sys_Printf( "Generating good sample offsets (this may take a while)...\n" ); - - /* start with entirely random samples */ - for(i = 0; i < minimap.samples; ++i) - { - minimap.sample_offsets[2*i+0] = Random(); - minimap.sample_offsets[2*i+1] = Random(); - } - - for(i = 0; i < 1000; ++i) - { - if(MiniMapEvaluateSampleOffsets(&j, &k, &val)) - { - sx = minimap.sample_offsets[2*j+0]; - sy = minimap.sample_offsets[2*j+1]; - minimap.sample_offsets[2*j+0] = rx = Random(); - minimap.sample_offsets[2*j+1] = ry = Random(); - if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valj)) - valj = -1; - minimap.sample_offsets[2*j+0] = sx; - minimap.sample_offsets[2*j+1] = sy; - - sx = minimap.sample_offsets[2*k+0]; - sy = minimap.sample_offsets[2*k+1]; - minimap.sample_offsets[2*k+0] = rx; - minimap.sample_offsets[2*k+1] = ry; - if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valk)) - valk = -1; - minimap.sample_offsets[2*k+0] = sx; - minimap.sample_offsets[2*k+1] = sy; - - if(valj > valk) - { - if(valj > val) - { - /* valj is the greatest */ - minimap.sample_offsets[2*j+0] = rx; - minimap.sample_offsets[2*j+1] = ry; - i = -1; - } - else - { - /* valj is the greater and it is useless - forget it */ - } - } - else - { - if(valk > val) - { - /* valk is the greatest */ - minimap.sample_offsets[2*k+0] = rx; - minimap.sample_offsets[2*k+1] = ry; - i = -1; - } - else - { - /* valk is the greater and it is useless - forget it */ - } - } - } - else - break; - } -} - -void MergeRelativePath(char *out, const char *absolute, const char *relative) -{ - const char *endpos = absolute + strlen(absolute); - while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\')) - --endpos; - while(relative[0] == '.' && relative[1] == '.' && (relative[2] == '/' || relative[2] == '\\')) - { - relative += 3; - while(endpos != absolute) - { - --endpos; - if(*endpos == '/' || *endpos == '\\') - break; - } - while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\')) - --endpos; - } - memcpy(out, absolute, endpos - absolute); - out[endpos - absolute] = '/'; - strcpy(out + (endpos - absolute + 1), relative); -} - -int MiniMapBSPMain( int argc, char **argv ) -{ - char minimapFilename[1024]; - char basename[1024]; - char path[1024]; - char relativeMinimapFilename[1024]; - float minimapSharpen; - float border; - byte *data4b, *p; - float *q; - int x, y; - int i; - miniMapMode_t mode; - vec3_t mins, maxs; - qboolean keepaspect; - - /* arg checking */ - if( argc < 2 ) - { - Sys_Printf( "Usage: q3map [-v] -minimap [-size n] [-sharpen f] [-samples n | -random n] [-o filename.tga] [-minmax Xmin Ymin Zmin Xmax Ymax Zmax] \n" ); - return 0; - } - - /* load the BSP first */ - strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - Sys_Printf( "Loading %s\n", source ); - BeginMapShaderFile( source ); - LoadShaderInfo(); - LoadBSPFile( source ); - - minimap.model = &bspModels[0]; - VectorCopy(minimap.model->mins, mins); - VectorCopy(minimap.model->maxs, maxs); - - *minimapFilename = 0; - minimapSharpen = game->miniMapSharpen; - minimap.width = minimap.height = game->miniMapSize; - border = game->miniMapBorder; - keepaspect = game->miniMapKeepAspect; - mode = game->miniMapMode; - - minimap.samples = 1; - minimap.sample_offsets = NULL; - minimap.boost = 1.0; - - /* process arguments */ - for( i = 1; i < (argc - 1); i++ ) - { - if( !strcmp( argv[ i ], "-size" ) ) - { - minimap.width = minimap.height = atoi(argv[i + 1]); - i++; - Sys_Printf( "Image size set to %i\n", minimap.width ); - } - else if( !strcmp( argv[ i ], "-sharpen" ) ) - { - minimapSharpen = atof(argv[i + 1]); - i++; - Sys_Printf( "Sharpening coefficient set to %f\n", minimapSharpen ); - } - else if( !strcmp( argv[ i ], "-samples" ) ) - { - minimap.samples = atoi(argv[i + 1]); - i++; - Sys_Printf( "Samples set to %i\n", minimap.samples ); - if(minimap.sample_offsets) - free(minimap.sample_offsets); - minimap.sample_offsets = malloc(2 * sizeof(*minimap.sample_offsets) * minimap.samples); - MiniMapMakeSampleOffsets(); - } - else if( !strcmp( argv[ i ], "-random" ) ) - { - minimap.samples = atoi(argv[i + 1]); - i++; - Sys_Printf( "Random samples set to %i\n", minimap.samples ); - if(minimap.sample_offsets) - free(minimap.sample_offsets); - minimap.sample_offsets = NULL; - } - else if( !strcmp( argv[ i ], "-border" ) ) - { - border = atof(argv[i + 1]); - i++; - Sys_Printf( "Border set to %f\n", border ); - } - else if( !strcmp( argv[ i ], "-keepaspect" ) ) - { - keepaspect = qtrue; - Sys_Printf( "Keeping aspect ratio by letterboxing\n", border ); - } - else if( !strcmp( argv[ i ], "-nokeepaspect" ) ) - { - keepaspect = qfalse; - Sys_Printf( "Not keeping aspect ratio\n", border ); - } - else if( !strcmp( argv[ i ], "-o" ) ) - { - strcpy(minimapFilename, argv[i + 1]); - i++; - Sys_Printf( "Output file name set to %s\n", minimapFilename ); - } - else if( !strcmp( argv[ i ], "-minmax" ) && i < (argc - 7) ) - { - mins[0] = atof(argv[i + 1]); - mins[1] = atof(argv[i + 2]); - mins[2] = atof(argv[i + 3]); - maxs[0] = atof(argv[i + 4]); - maxs[1] = atof(argv[i + 5]); - maxs[2] = atof(argv[i + 6]); - i += 6; - Sys_Printf( "Map mins/maxs overridden\n" ); - } - else if( !strcmp( argv[ i ], "-gray" ) ) - { - mode = MINIMAP_MODE_GRAY; - Sys_Printf( "Writing as white-on-black image\n" ); - } - else if( !strcmp( argv[ i ], "-black" ) ) - { - mode = MINIMAP_MODE_BLACK; - Sys_Printf( "Writing as black alpha image\n" ); - } - else if( !strcmp( argv[ i ], "-white" ) ) - { - mode = MINIMAP_MODE_WHITE; - Sys_Printf( "Writing as white alpha image\n" ); - } - else if( !strcmp( argv[ i ], "-boost" ) ) - { - minimap.boost = atof(argv[i + 1]); - i++; - Sys_Printf( "Contrast boost set to %f\n", minimap.boost ); - } - } - - MiniMapMakeMinsMaxs(mins, maxs, border, keepaspect); - - if(!*minimapFilename) - { - ExtractFileBase(source, basename); - ExtractFilePath(source, path); - sprintf(relativeMinimapFilename, game->miniMapNameFormat, basename); - MergeRelativePath(minimapFilename, path, relativeMinimapFilename); - Sys_Printf("Output file name automatically set to %s\n", minimapFilename); - } - ExtractFilePath(minimapFilename, path); - Q_mkdir(path); - - if(minimapSharpen >= 0) - { - minimap.sharpen_centermult = 8 * minimapSharpen + 1; - minimap.sharpen_boxmult = -minimapSharpen; - } - - minimap.data1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f)); - data4b = safe_malloc(minimap.width * minimap.height * 4); - if(minimapSharpen >= 0) - minimap.sharpendata1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f)); - - MiniMapSetupBrushes(); - - if(minimap.samples <= 1) - { - Sys_Printf( "\n--- MiniMapNoSupersampling (%d) ---\n", minimap.height ); - RunThreadsOnIndividual(minimap.height, qtrue, MiniMapNoSupersampling); - } - else - { - if(minimap.sample_offsets) - { - Sys_Printf( "\n--- MiniMapSupersampled (%d) ---\n", minimap.height ); - RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSupersampled); - } - else - { - Sys_Printf( "\n--- MiniMapRandomlySupersampled (%d) ---\n", minimap.height ); - RunThreadsOnIndividual(minimap.height, qtrue, MiniMapRandomlySupersampled); - } - } - - if(minimap.boost != 1.0) - { - Sys_Printf( "\n--- MiniMapContrastBoost (%d) ---\n", minimap.height ); - RunThreadsOnIndividual(minimap.height, qtrue, MiniMapContrastBoost); - } - - if(minimap.sharpendata1f) - { - Sys_Printf( "\n--- MiniMapSharpen (%d) ---\n", minimap.height ); - RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSharpen); - q = minimap.sharpendata1f; - } - else - { - q = minimap.data1f; - } - - Sys_Printf( "\nConverting..."); - - switch(mode) - { - case MINIMAP_MODE_GRAY: - p = data4b; - for(y = 0; y < minimap.height; ++y) - for(x = 0; x < minimap.width; ++x) - { - byte b; - float v = *q++; - if(v < 0) v = 0; - if(v > 255.0/256.0) v = 255.0/256.0; - b = v * 256; - *p++ = b; - } - Sys_Printf( " writing to %s...", minimapFilename ); - WriteTGAGray(minimapFilename, data4b, minimap.width, minimap.height); - break; - case MINIMAP_MODE_BLACK: - p = data4b; - for(y = 0; y < minimap.height; ++y) - for(x = 0; x < minimap.width; ++x) - { - byte b; - float v = *q++; - if(v < 0) v = 0; - if(v > 255.0/256.0) v = 255.0/256.0; - b = v * 256; - *p++ = 0; - *p++ = 0; - *p++ = 0; - *p++ = b; - } - Sys_Printf( " writing to %s...", minimapFilename ); - WriteTGA(minimapFilename, data4b, minimap.width, minimap.height); - break; - case MINIMAP_MODE_WHITE: - p = data4b; - for(y = 0; y < minimap.height; ++y) - for(x = 0; x < minimap.width; ++x) - { - byte b; - float v = *q++; - if(v < 0) v = 0; - if(v > 255.0/256.0) v = 255.0/256.0; - b = v * 256; - *p++ = 255; - *p++ = 255; - *p++ = 255; - *p++ = b; - } - Sys_Printf( " writing to %s...", minimapFilename ); - WriteTGA(minimapFilename, data4b, minimap.width, minimap.height); - break; - } - - Sys_Printf( " done.\n" ); - - /* return to sender */ - return 0; -} - - - - - -/* -MD4BlockChecksum() -calculates an md4 checksum for a block of data -*/ - -static int MD4BlockChecksum( void *buffer, int length ) -{ - return Com_BlockChecksum(buffer, length); -} - -/* -FixAAS() -resets an aas checksum to match the given BSP -*/ - -int FixAAS( int argc, char **argv ) -{ - int length, checksum; - void *buffer; - FILE *file; - char aas[ 1024 ], **ext; - char *exts[] = - { - ".aas", - "_b0.aas", - "_b1.aas", - NULL - }; - - - /* arg checking */ - if( argc < 2 ) - { - Sys_Printf( "Usage: q3map -fixaas [-v] \n" ); - return 0; - } - - /* do some path mangling */ - strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - - /* note it */ - Sys_Printf( "--- FixAAS ---\n" ); - - /* load the bsp */ - Sys_Printf( "Loading %s\n", source ); - length = LoadFile( source, &buffer ); - - /* create bsp checksum */ - Sys_Printf( "Creating checksum...\n" ); - checksum = LittleLong( MD4BlockChecksum( buffer, length ) ); - - /* write checksum to aas */ - ext = exts; - while( *ext ) - { - /* mangle name */ - strcpy( aas, source ); - StripExtension( aas ); - strcat( aas, *ext ); - Sys_Printf( "Trying %s\n", aas ); - ext++; - - /* fix it */ - file = fopen( aas, "r+b" ); - if( !file ) - continue; - if( fwrite( &checksum, 4, 1, file ) != 1 ) - Error( "Error writing checksum to %s", aas ); - fclose( file ); - } - - /* return to sender */ - return 0; -} - - - -/* -AnalyzeBSP() - ydnar -analyzes a Quake engine BSP file -*/ - -typedef struct abspHeader_s -{ - char ident[ 4 ]; - int version; - - bspLump_t lumps[ 1 ]; /* unknown size */ -} -abspHeader_t; - -typedef struct abspLumpTest_s -{ - int radix, minCount; - char *name; -} -abspLumpTest_t; - -int AnalyzeBSP( int argc, char **argv ) -{ - abspHeader_t *header; - int size, i, version, offset, length, lumpInt, count; - char ident[ 5 ]; - void *lump; - float lumpFloat; - char lumpString[ 1024 ], source[ 1024 ]; - qboolean lumpSwap = qfalse; - abspLumpTest_t *lumpTest; - static abspLumpTest_t lumpTests[] = - { - { sizeof( bspPlane_t ), 6, "IBSP LUMP_PLANES" }, - { sizeof( bspBrush_t ), 1, "IBSP LUMP_BRUSHES" }, - { 8, 6, "IBSP LUMP_BRUSHSIDES" }, - { sizeof( bspBrushSide_t ), 6, "RBSP LUMP_BRUSHSIDES" }, - { sizeof( bspModel_t ), 1, "IBSP LUMP_MODELS" }, - { sizeof( bspNode_t ), 2, "IBSP LUMP_NODES" }, - { sizeof( bspLeaf_t ), 1, "IBSP LUMP_LEAFS" }, - { 104, 3, "IBSP LUMP_DRAWSURFS" }, - { 44, 3, "IBSP LUMP_DRAWVERTS" }, - { 4, 6, "IBSP LUMP_DRAWINDEXES" }, - { 128 * 128 * 3, 1, "IBSP LUMP_LIGHTMAPS" }, - { 256 * 256 * 3, 1, "IBSP LUMP_LIGHTMAPS (256 x 256)" }, - { 512 * 512 * 3, 1, "IBSP LUMP_LIGHTMAPS (512 x 512)" }, - { 0, 0, NULL } - }; - - - /* arg checking */ - if( argc < 1 ) - { - Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] \n" ); - return 0; - } - - /* process arguments */ - for( i = 1; i < (argc - 1); i++ ) - { - /* -format map|ase|... */ - if( !strcmp( argv[ i ], "-lumpswap" ) ) - { - Sys_Printf( "Swapped lump structs enabled\n" ); - lumpSwap = qtrue; - } - } - - /* clean up map name */ - strcpy( source, ExpandArg( argv[ i ] ) ); - Sys_Printf( "Loading %s\n", source ); - - /* load the file */ - size = LoadFile( source, (void**) &header ); - if( size == 0 || header == NULL ) - { - Sys_Printf( "Unable to load %s.\n", source ); - return -1; - } - - /* analyze ident/version */ - memcpy( ident, header->ident, 4 ); - ident[ 4 ] = '\0'; - version = LittleLong( header->version ); - - Sys_Printf( "Identity: %s\n", ident ); - Sys_Printf( "Version: %d\n", version ); - Sys_Printf( "---------------------------------------\n" ); - - /* analyze each lump */ - for( i = 0; i < 100; i++ ) - { - /* call of duty swapped lump pairs */ - if( lumpSwap ) - { - offset = LittleLong( header->lumps[ i ].length ); - length = LittleLong( header->lumps[ i ].offset ); - } - - /* standard lump pairs */ - else - { - offset = LittleLong( header->lumps[ i ].offset ); - length = LittleLong( header->lumps[ i ].length ); - } - - /* extract data */ - lump = (byte*) header + offset; - lumpInt = LittleLong( (int) *((int*) lump) ); - lumpFloat = LittleFloat( (float) *((float*) lump) ); - memcpy( lumpString, (char*) lump, (length < sizeof(lumpString) ? length : sizeof(lumpString)-1) ); - lumpString[ sizeof(lumpString)-1 ] = '\0'; - - /* print basic lump info */ - Sys_Printf( "Lump: %d\n", i ); - Sys_Printf( "Offset: %d bytes\n", offset ); - Sys_Printf( "Length: %d bytes\n", length ); - - /* only operate on valid lumps */ - if( length > 0 ) - { - /* print data in 4 formats */ - Sys_Printf( "As hex: %08X\n", lumpInt ); - Sys_Printf( "As int: %d\n", lumpInt ); - Sys_Printf( "As float: %f\n", lumpFloat ); - Sys_Printf( "As string: %s\n", lumpString ); - - /* guess lump type */ - if( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' ) - Sys_Printf( "Type guess: IBSP LUMP_ENTITIES\n" ); - else if( strstr( lumpString, "textures/" ) ) - Sys_Printf( "Type guess: IBSP LUMP_SHADERS\n" ); - else - { - /* guess based on size/count */ - for( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ ) - { - if( (length % lumpTest->radix) != 0 ) - continue; - count = length / lumpTest->radix; - if( count < lumpTest->minCount ) - continue; - Sys_Printf( "Type guess: %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix ); - } - } - } - - Sys_Printf( "---------------------------------------\n" ); - - /* end of file */ - if( offset + length >= size ) - break; - } - - /* last stats */ - Sys_Printf( "Lump count: %d\n", i + 1 ); - Sys_Printf( "File size: %d bytes\n", size ); - - /* return to caller */ - return 0; -} - - - -/* -BSPInfo() -emits statistics about the bsp file -*/ - -int BSPInfo( int count, char **fileNames ) -{ - int i; - char source[ 1024 ], ext[ 64 ]; - int size; - FILE *f; - - - /* dummy check */ - if( count < 1 ) - { - Sys_Printf( "No files to dump info for.\n"); - return -1; - } - - /* enable info mode */ - infoMode = qtrue; - - /* walk file list */ - for( i = 0; i < count; i++ ) - { - Sys_Printf( "---------------------------------\n" ); - - /* mangle filename and get size */ - strcpy( source, fileNames[ i ] ); - ExtractFileExtension( source, ext ); - if( !Q_stricmp( ext, "map" ) ) - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - f = fopen( source, "rb" ); - if( f ) - { - size = Q_filelength (f); - fclose( f ); - } - else - size = 0; - - /* load the bsp file and print lump sizes */ - Sys_Printf( "%s\n", source ); - LoadBSPFile( source ); - PrintBSPFileSizes(); - - /* print sizes */ - Sys_Printf( "\n" ); - Sys_Printf( " total %9d\n", size ); - Sys_Printf( " %9d KB\n", size / 1024 ); - Sys_Printf( " %9d MB\n", size / (1024 * 1024) ); - - Sys_Printf( "---------------------------------\n" ); - } - - /* return count */ - return i; -} - - -static void ExtrapolateTexcoords(const float *axyz, const float *ast, const float *bxyz, const float *bst, const float *cxyz, const float *cst, const float *axyz_new, float *ast_out, const float *bxyz_new, float *bst_out, const float *cxyz_new, float *cst_out) -{ - vec4_t scoeffs, tcoeffs; - float md; - m4x4_t solvematrix; - - vec3_t norm; - vec3_t dab, dac; - VectorSubtract(bxyz, axyz, dab); - VectorSubtract(cxyz, axyz, dac); - CrossProduct(dab, dac, norm); - - // assume: - // s = f(x, y, z) - // s(v + norm) = s(v) when n ortho xyz - - // s(v) = DotProduct(v, scoeffs) + scoeffs[3] - - // solve: - // scoeffs * (axyz, 1) == ast[0] - // scoeffs * (bxyz, 1) == bst[0] - // scoeffs * (cxyz, 1) == cst[0] - // scoeffs * (norm, 0) == 0 - // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0] - solvematrix[0] = axyz[0]; - solvematrix[4] = axyz[1]; - solvematrix[8] = axyz[2]; - solvematrix[12] = 1; - solvematrix[1] = bxyz[0]; - solvematrix[5] = bxyz[1]; - solvematrix[9] = bxyz[2]; - solvematrix[13] = 1; - solvematrix[2] = cxyz[0]; - solvematrix[6] = cxyz[1]; - solvematrix[10] = cxyz[2]; - solvematrix[14] = 1; - solvematrix[3] = norm[0]; - solvematrix[7] = norm[1]; - solvematrix[11] = norm[2]; - solvematrix[15] = 0; - - md = m4_det(solvematrix); - if(md*md < 1e-10) - { - Sys_Printf("Cannot invert some matrix, some texcoords aren't extrapolated!"); - return; - } - - m4x4_invert(solvematrix); - - scoeffs[0] = ast[0]; - scoeffs[1] = bst[0]; - scoeffs[2] = cst[0]; - scoeffs[3] = 0; - m4x4_transform_vec4(solvematrix, scoeffs); - tcoeffs[0] = ast[1]; - tcoeffs[1] = bst[1]; - tcoeffs[2] = cst[1]; - tcoeffs[3] = 0; - m4x4_transform_vec4(solvematrix, tcoeffs); - - ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3]; - ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3]; - bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3]; - bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3]; - cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3]; - cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3]; -} - -/* -ScaleBSPMain() -amaze and confuse your enemies with wierd scaled maps! -*/ - -int ScaleBSPMain( int argc, char **argv ) -{ - int i, j; - float f, a; - vec3_t scale; - vec3_t vec; - char str[ 1024 ]; - int uniform, axis; - qboolean texscale; - float *old_xyzst = NULL; - float spawn_ref = 0; - - - /* arg checking */ - if( argc < 3 ) - { - Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref ] \n" ); - return 0; - } - - texscale = qfalse; - for(i = 1; i < argc-2; ++i) - { - if(!strcmp(argv[i], "-tex")) - { - texscale = qtrue; - } - else if(!strcmp(argv[i], "-spawn_ref")) - { - spawn_ref = atof(argv[i+1]); - ++i; - } - else - break; - } - - /* get scale */ - // if(argc-2 >= i) // always true - scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] ); - if(argc-3 >= i) - scale[1] = scale[0] = atof( argv[ argc - 3 ] ); - if(argc-4 >= i) - scale[0] = atof( argv[ argc - 4 ] ); - - uniform = ((scale[0] == scale[1]) && (scale[1] == scale[2])); - - if( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f ) - { - Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref ] \n" ); - Sys_Printf( "Non-zero scale value required.\n" ); - return 0; - } - - /* do some path mangling */ - strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); - StripExtension( source ); - DefaultExtension( source, ".bsp" ); - - /* load the bsp */ - Sys_Printf( "Loading %s\n", source ); - LoadBSPFile( source ); - ParseEntities(); - - /* note it */ - Sys_Printf( "--- ScaleBSP ---\n" ); - Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities ); - - /* scale entity keys */ - for( i = 0; i < numBSPEntities && i < numEntities; i++ ) - { - /* scale origin */ - GetVectorForKey( &entities[ i ], "origin", vec ); - if( (vec[ 0 ] || vec[ 1 ] || vec[ 2 ]) ) - { - if(!strncmp(ValueForKey(&entities[i], "classname"), "info_player_", 12)) - vec[2] += spawn_ref; - vec[0] *= scale[0]; - vec[1] *= scale[1]; - vec[2] *= scale[2]; - if(!strncmp(ValueForKey(&entities[i], "classname"), "info_player_", 12)) - vec[2] -= spawn_ref; - sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); - SetKeyValue( &entities[ i ], "origin", str ); - } - - a = FloatForKey( &entities[ i ], "angle" ); - if(a == -1 || a == -2) // z scale - axis = 2; - else if(fabs(sin(DEG2RAD(a))) < 0.707) - axis = 0; - else - axis = 1; - - /* scale door lip */ - f = FloatForKey( &entities[ i ], "lip" ); - if( f ) - { - f *= scale[axis]; - sprintf( str, "%f", f ); - SetKeyValue( &entities[ i ], "lip", str ); - } - - /* scale plat height */ - f = FloatForKey( &entities[ i ], "height" ); - if( f ) - { - f *= scale[2]; - sprintf( str, "%f", f ); - SetKeyValue( &entities[ i ], "height", str ); - } - - // TODO maybe allow a definition file for entities to specify which values are scaled how? - } - - /* scale models */ - for( i = 0; i < numBSPModels; i++ ) - { - bspModels[ i ].mins[0] *= scale[0]; - bspModels[ i ].mins[1] *= scale[1]; - bspModels[ i ].mins[2] *= scale[2]; - bspModels[ i ].maxs[0] *= scale[0]; - bspModels[ i ].maxs[1] *= scale[1]; - bspModels[ i ].maxs[2] *= scale[2]; - } - - /* scale nodes */ - for( i = 0; i < numBSPNodes; i++ ) - { - bspNodes[ i ].mins[0] *= scale[0]; - bspNodes[ i ].mins[1] *= scale[1]; - bspNodes[ i ].mins[2] *= scale[2]; - bspNodes[ i ].maxs[0] *= scale[0]; - bspNodes[ i ].maxs[1] *= scale[1]; - bspNodes[ i ].maxs[2] *= scale[2]; - } - - /* scale leafs */ - for( i = 0; i < numBSPLeafs; i++ ) - { - bspLeafs[ i ].mins[0] *= scale[0]; - bspLeafs[ i ].mins[1] *= scale[1]; - bspLeafs[ i ].mins[2] *= scale[2]; - bspLeafs[ i ].maxs[0] *= scale[0]; - bspLeafs[ i ].maxs[1] *= scale[1]; - bspLeafs[ i ].maxs[2] *= scale[2]; - } - - if(texscale) - { - Sys_Printf("Using texture unlocking (and probably breaking texture alignment a lot)\n"); - old_xyzst = safe_malloc(sizeof(*old_xyzst) * numBSPDrawVerts * 5); - for(i = 0; i < numBSPDrawVerts; i++) - { - old_xyzst[5*i+0] = bspDrawVerts[i].xyz[0]; - old_xyzst[5*i+1] = bspDrawVerts[i].xyz[1]; - old_xyzst[5*i+2] = bspDrawVerts[i].xyz[2]; - old_xyzst[5*i+3] = bspDrawVerts[i].st[0]; - old_xyzst[5*i+4] = bspDrawVerts[i].st[1]; - } - } - - /* scale drawverts */ - for( i = 0; i < numBSPDrawVerts; i++ ) - { - bspDrawVerts[i].xyz[0] *= scale[0]; - bspDrawVerts[i].xyz[1] *= scale[1]; - bspDrawVerts[i].xyz[2] *= scale[2]; - bspDrawVerts[i].normal[0] /= scale[0]; - bspDrawVerts[i].normal[1] /= scale[1]; - bspDrawVerts[i].normal[2] /= scale[2]; - VectorNormalize(bspDrawVerts[i].normal, bspDrawVerts[i].normal); - } - - if(texscale) - { - for(i = 0; i < numBSPDrawSurfaces; i++) - { - switch(bspDrawSurfaces[i].surfaceType) - { - case SURFACE_FACE: - case SURFACE_META: - if(bspDrawSurfaces[i].numIndexes % 3) - Error("Not a triangulation!"); - for(j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3) - { - int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j+1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j+2] + bspDrawSurfaces[i].firstVert; - bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic]; - float *oa = &old_xyzst[ia*5], *ob = &old_xyzst[ib*5], *oc = &old_xyzst[ic*5]; - // extrapolate: - // a->xyz -> oa - // b->xyz -> ob - // c->xyz -> oc - ExtrapolateTexcoords( - &oa[0], &oa[3], - &ob[0], &ob[3], - &oc[0], &oc[3], - a->xyz, a->st, - b->xyz, b->st, - c->xyz, c->st); - } - break; - } - } - } - - /* scale planes */ - if(uniform) - { - for( i = 0; i < numBSPPlanes; i++ ) - { - bspPlanes[ i ].dist *= scale[0]; - } - } - else - { - for( i = 0; i < numBSPPlanes; i++ ) - { - bspPlanes[ i ].normal[0] /= scale[0]; - bspPlanes[ i ].normal[1] /= scale[1]; - bspPlanes[ i ].normal[2] /= scale[2]; - f = 1/VectorLength(bspPlanes[i].normal); - VectorScale(bspPlanes[i].normal, f, bspPlanes[i].normal); - bspPlanes[ i ].dist *= f; - } - } - - /* scale gridsize */ - GetVectorForKey( &entities[ 0 ], "gridsize", vec ); - if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f ) - VectorCopy( gridSize, vec ); - vec[0] *= scale[0]; - vec[1] *= scale[1]; - vec[2] *= scale[2]; - sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); - SetKeyValue( &entities[ 0 ], "gridsize", str ); - - /* inject command line parameters */ - InjectCommandLine(argv, 0, argc - 1); - - /* write the bsp */ - UnparseEntities(); - StripExtension( source ); - DefaultExtension( source, "_s.bsp" ); - Sys_Printf( "Writing %s\n", source ); - WriteBSPFile( source ); - - /* return to sender */ - return 0; -} - - -/* -PseudoCompileBSP() -a stripped down ProcessModels -*/ -void PseudoCompileBSP(qboolean need_tree) -{ - int models; - char modelValue[10]; - entity_t *entity; - face_t *faces; - tree_t *tree; - node_t *node; - brush_t *brush; - side_t *side; - int i; - - SetDrawSurfacesBuffer(); - mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); - memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); - numMapDrawSurfs = 0; - - BeginBSPFile(); - models = 1; - for( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ ) - { - /* get entity */ - entity = &entities[ mapEntityNum ]; - if( entity->brushes == NULL && entity->patches == NULL ) - continue; - - if(mapEntityNum != 0) - { - sprintf( modelValue, "*%d", models++); - SetKeyValue(entity, "model", modelValue); - } - - /* process the model */ - Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels ); - BeginModel(); - - entity->firstDrawSurf = numMapDrawSurfs; - - ClearMetaTriangles(); - PatchMapDrawSurfs(entity); - - if(mapEntityNum == 0 && need_tree) - { - faces = MakeStructuralBSPFaceList(entities[0].brushes); - tree = FaceBSP(faces); - node = tree->headnode; - } - else - { - node = AllocNode(); - node->planenum = PLANENUM_LEAF; - tree = AllocTree(); - tree->headnode = node; - } - - /* a minimized ClipSidesIntoTree */ - for( brush = entity->brushes; brush; brush = brush->next ) - { - /* walk the brush sides */ - for( i = 0; i < brush->numsides; i++ ) - { - /* get side */ - side = &brush->sides[ i ]; - if( side->winding == NULL ) - continue; - /* shader? */ - if( side->shaderInfo == NULL ) - continue; - /* save this winding as a visible surface */ - DrawSurfaceForSide(entity, brush, side, side->winding); - } - } - - if(meta) - { - ClassifyEntitySurfaces(entity); - MakeEntityDecals(entity); - MakeEntityMetaTriangles(entity); - SmoothMetaTriangles(); - MergeMetaTriangles(); - } - FilterDrawsurfsIntoTree(entity, tree); - - FilterStructuralBrushesIntoTree(entity, tree); - FilterDetailBrushesIntoTree(entity, tree); - - EmitBrushes(entity->brushes, &entity->firstBrush, &entity->numBrushes ); - EndModel(entity, node); - } - EndBSPFile(qfalse); -} - -/* -ConvertBSPMain() -main argument processing function for bsp conversion -*/ - -int ConvertBSPMain( int argc, char **argv ) -{ - int i; - int (*convertFunc)( char * ); - game_t *convertGame; - char ext[1024]; - qboolean map_allowed, force_bsp, force_map; - - - /* set default */ - convertFunc = ConvertBSPToASE; - convertGame = NULL; - map_allowed = qfalse; - force_bsp = qfalse; - force_map = qfalse; - - /* arg checking */ - if( argc < 1 ) - { - Sys_Printf( "Usage: q3map -convert -format [-shadesasbitmap|-lightmapsastexcoord|-deluxemapsastexcoord] [-readbsp|-readmap [-meta|-patchmeta]] \n" ); - return 0; - } - - /* process arguments */ - for( i = 1; i < (argc - 1); i++ ) - { - /* -format map|ase|... */ - if( !strcmp( argv[ i ], "-format" ) ) - { - i++; - if( !Q_stricmp( argv[ i ], "ase" ) ) - { - convertFunc = ConvertBSPToASE; - map_allowed = qfalse; - } - else if( !Q_stricmp( argv[ i ], "obj" ) ) - { - convertFunc = ConvertBSPToOBJ; - map_allowed = qfalse; - } - else if( !Q_stricmp( argv[ i ], "map_bp" ) ) - { - convertFunc = ConvertBSPToMap_BP; - map_allowed = qtrue; - } - else if( !Q_stricmp( argv[ i ], "map" ) ) - { - convertFunc = ConvertBSPToMap; - map_allowed = qtrue; - } - else - { - convertGame = GetGame( argv[ i ] ); - map_allowed = qfalse; - if( convertGame == NULL ) - Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] ); - } - } - else if( !strcmp( argv[ i ], "-ne" ) ) - { - normalEpsilon = atof( argv[ i + 1 ] ); - i++; - Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon ); - } - else if( !strcmp( argv[ i ], "-de" ) ) - { - distanceEpsilon = atof( argv[ i + 1 ] ); - i++; - Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon ); - } - else if( !strcmp( argv[ i ], "-shadersasbitmap" ) ) - shadersAsBitmap = qtrue; - else if( !strcmp( argv[ i ], "-lightmapsastexcoord" ) ) - lightmapsAsTexcoord = qtrue; - else if( !strcmp( argv[ i ], "-deluxemapsastexcoord" ) ) - { - lightmapsAsTexcoord = qtrue; - deluxemap = qtrue; - } - else if( !strcmp( argv[ i ], "-readbsp" ) ) - force_bsp = qtrue; - else if( !strcmp( argv[ i ], "-readmap" ) ) - force_map = qtrue; - else if( !strcmp( argv[ i ], "-meta" ) ) - meta = qtrue; - else if( !strcmp( argv[ i ], "-patchmeta" ) ) - { - meta = qtrue; - patchMeta = qtrue; - } - } - - LoadShaderInfo(); - - /* clean up map name */ - strcpy(source, ExpandArg(argv[i])); - ExtractFileExtension(source, ext); - - if(!map_allowed && !force_map) - force_bsp = qtrue; - - if(force_map || (!force_bsp && !Q_stricmp(ext, "map") && map_allowed)) - { - if(!map_allowed) - Sys_Printf("WARNING: the requested conversion should not be done from .map files. Compile a .bsp first.\n"); - StripExtension(source); - DefaultExtension(source, ".map"); - Sys_Printf("Loading %s\n", source); - LoadMapFile(source, qfalse, convertGame == NULL); - PseudoCompileBSP(convertGame != NULL); - } - else - { - StripExtension(source); - DefaultExtension(source, ".bsp"); - Sys_Printf("Loading %s\n", source); - LoadBSPFile(source); - ParseEntities(); - } - - /* bsp format convert? */ - if( convertGame != NULL ) - { - /* set global game */ - game = convertGame; - - /* write bsp */ - StripExtension( source ); - DefaultExtension( source, "_c.bsp" ); - Sys_Printf( "Writing %s\n", source ); - WriteBSPFile( source ); - - /* return to sender */ - return 0; - } - - /* normal convert */ - return convertFunc( source ); -} - - - -/* -main() -q3map mojo... -*/ - -int main( int argc, char **argv ) -{ - int i, r; - double start, end; - - - /* we want consistent 'randomness' */ - srand( 0 ); - - /* start timer */ - start = I_FloatTime(); - - /* this was changed to emit version number over the network */ - printf( Q3MAP_VERSION "\n" ); - - /* set exit call */ - atexit( ExitQ3Map ); - - /* read general options first */ - for( i = 1; i < argc; i++ ) - { - /* -connect */ - if( !strcmp( argv[ i ], "-connect" ) ) - { - argv[ i ] = NULL; - i++; - Broadcast_Setup( argv[ i ] ); - argv[ i ] = NULL; - } - - /* verbose */ - else if( !strcmp( argv[ i ], "-v" ) ) - { - if(!verbose) - { - verbose = qtrue; - argv[ i ] = NULL; - } - } - - /* force */ - else if( !strcmp( argv[ i ], "-force" ) ) - { - force = qtrue; - argv[ i ] = NULL; - } - - /* patch subdivisions */ - else if( !strcmp( argv[ i ], "-subdivisions" ) ) - { - argv[ i ] = NULL; - i++; - patchSubdivisions = atoi( argv[ i ] ); - argv[ i ] = NULL; - if( patchSubdivisions <= 0 ) - patchSubdivisions = 1; - } - - /* threads */ - else if( !strcmp( argv[ i ], "-threads" ) ) - { - argv[ i ] = NULL; - i++; - numthreads = atoi( argv[ i ] ); - argv[ i ] = NULL; - } - } - - /* init model library */ - PicoInit(); - PicoSetMallocFunc( safe_malloc ); - PicoSetFreeFunc( free ); - PicoSetPrintFunc( PicoPrintFunc ); - PicoSetLoadFileFunc( PicoLoadFileFunc ); - PicoSetFreeFileFunc( free ); - - /* set number of threads */ - ThreadSetDefault(); - - /* generate sinusoid jitter table */ - for( i = 0; i < MAX_JITTERS; i++ ) - { - jitters[ i ] = sin( i * 139.54152147 ); - //% Sys_Printf( "Jitter %4d: %f\n", i, jitters[ i ] ); - } - - /* we print out two versions, q3map's main version (since it evolves a bit out of GtkRadiant) - and we put the GtkRadiant version to make it easy to track with what version of Radiant it was built with */ - - Sys_Printf( "Q3Map - v1.0r (c) 1999 Id Software Inc.\n" ); - Sys_Printf( "Q3Map (ydnar) - v" Q3MAP_VERSION "\n" ); - Sys_Printf( "NetRadiant - v" RADIANT_VERSION " " __DATE__ " " __TIME__ "\n" ); - Sys_Printf( "%s\n", Q3MAP_MOTD ); - - /* ydnar: new path initialization */ - InitPaths( &argc, argv ); - - /* set game options */ - if (!patchSubdivisions) - patchSubdivisions = game->patchSubdivisions; - - /* check if we have enough options left to attempt something */ - if( argc < 2 ) - Error( "Usage: %s [general options] [options] mapfile", argv[ 0 ] ); - - /* fixaas */ - if( !strcmp( argv[ 1 ], "-fixaas" ) ) - r = FixAAS( argc - 1, argv + 1 ); - - /* analyze */ - else if( !strcmp( argv[ 1 ], "-analyze" ) ) - r = AnalyzeBSP( argc - 1, argv + 1 ); - - /* info */ - else if( !strcmp( argv[ 1 ], "-info" ) ) - r = BSPInfo( argc - 2, argv + 2 ); - - /* vis */ - else if( !strcmp( argv[ 1 ], "-vis" ) ) - r = VisMain( argc - 1, argv + 1 ); - - /* light */ - else if( !strcmp( argv[ 1 ], "-light" ) ) - r = LightMain( argc - 1, argv + 1 ); - - /* vlight */ - else if( !strcmp( argv[ 1 ], "-vlight" ) ) - { - Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" ); - argv[ 1 ] = "-fast"; /* eek a hack */ - r = LightMain( argc, argv ); - } - - /* ydnar: lightmap export */ - else if( !strcmp( argv[ 1 ], "-export" ) ) - r = ExportLightmapsMain( argc - 1, argv + 1 ); - - /* ydnar: lightmap import */ - else if( !strcmp( argv[ 1 ], "-import" ) ) - r = ImportLightmapsMain( argc - 1, argv + 1 ); - - /* ydnar: bsp scaling */ - else if( !strcmp( argv[ 1 ], "-scale" ) ) - r = ScaleBSPMain( argc - 1, argv + 1 ); - - /* ydnar: bsp conversion */ - else if( !strcmp( argv[ 1 ], "-convert" ) ) - r = ConvertBSPMain( argc - 1, argv + 1 ); - - /* div0: minimap */ - else if( !strcmp( argv[ 1 ], "-minimap" ) ) - r = MiniMapBSPMain(argc - 1, argv + 1); - - /* ydnar: otherwise create a bsp */ - else - r = BSPMain( argc, argv ); - - /* emit time */ - end = I_FloatTime(); - Sys_Printf( "%9.0f seconds elapsed\n", end - start ); - - /* shut down connection */ - Broadcast_Shutdown(); - - /* return any error code */ - return r; -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/map.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/map.c deleted file mode 100644 index 95bb3d1f..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/map.c +++ /dev/null @@ -1,1925 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define MAP_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* FIXME: remove these vars */ - -/* undefine to make plane finding use linear sort (note: really slow) */ -#define USE_HASHING -#define PLANE_HASHES 8192 - -int planehash[ PLANE_HASHES ]; - -int c_boxbevels; -int c_edgebevels; -int c_areaportals; -int c_detail; -int c_structural; - - - -/* -PlaneEqual() -ydnar: replaced with variable epsilon for djbob -*/ - -qboolean PlaneEqual( plane_t *p, vec3_t normal, vec_t dist ) -{ - float ne, de; - - - /* get local copies */ - ne = normalEpsilon; - de = distanceEpsilon; - - /* compare */ - // We check equality of each component since we're using '<', not '<=' - // (the epsilons may be zero). We want to use '<' intead of '<=' to be - // consistent with the true meaning of "epsilon", and also because other - // parts of the code uses this inequality. - if ((p->dist == dist || fabs(p->dist - dist) < de) && - (p->normal[0] == normal[0] || fabs(p->normal[0] - normal[0]) < ne) && - (p->normal[1] == normal[1] || fabs(p->normal[1] - normal[1]) < ne) && - (p->normal[2] == normal[2] || fabs(p->normal[2] - normal[2]) < ne)) - return qtrue; - - /* different */ - return qfalse; -} - - - -/* -AddPlaneToHash() -*/ - -void AddPlaneToHash( plane_t *p ) -{ - int hash; - - - hash = (PLANE_HASHES - 1) & (int) fabs( p->dist ); - - p->hash_chain = planehash[hash]; - planehash[hash] = p - mapplanes + 1; -} - -/* -================ -CreateNewFloatPlane -================ -*/ -int CreateNewFloatPlane (vec3_t normal, vec_t dist) -{ - plane_t *p, temp; - - if (VectorLength(normal) < 0.5) - { - Sys_Printf( "FloatPlane: bad normal\n"); - return -1; - } - - // create a new plane - AUTOEXPAND_BY_REALLOC(mapplanes, nummapplanes+1, allocatedmapplanes, 1024); - - p = &mapplanes[nummapplanes]; - VectorCopy (normal, p->normal); - p->dist = dist; - p->type = (p+1)->type = PlaneTypeForNormal (p->normal); - - VectorSubtract (vec3_origin, normal, (p+1)->normal); - (p+1)->dist = -dist; - - nummapplanes += 2; - - // allways put axial planes facing positive first - if (p->type < 3) - { - if (p->normal[0] < 0 || p->normal[1] < 0 || p->normal[2] < 0) - { - // flip order - temp = *p; - *p = *(p+1); - *(p+1) = temp; - - AddPlaneToHash (p); - AddPlaneToHash (p+1); - return nummapplanes - 1; - } - } - - AddPlaneToHash (p); - AddPlaneToHash (p+1); - return nummapplanes - 2; -} - - - -/* -SnapNormal() -Snaps a near-axial normal vector. -Returns qtrue if and only if the normal was adjusted. -*/ - -qboolean SnapNormal( vec3_t normal ) -{ -#if Q3MAP2_EXPERIMENTAL_SNAP_NORMAL_FIX - int i; - qboolean adjusted = qfalse; - - // A change from the original SnapNormal() is that we snap each - // component that's close to 0. So for example if a normal is - // (0.707, 0.707, 0.0000001), it will get snapped to lie perfectly in the - // XY plane (its Z component will be set to 0 and its length will be - // normalized). The original SnapNormal() didn't snap such vectors - it - // only snapped vectors that were near a perfect axis. - - for (i = 0; i < 3; i++) - { - if (normal[i] != 0.0 && -normalEpsilon < normal[i] && normal[i] < normalEpsilon) - { - normal[i] = 0.0; - adjusted = qtrue; - } - } - - if (adjusted) - { - VectorNormalize(normal, normal); - return qtrue; - } - return qfalse; -#else - int i; - - // I would suggest that you uncomment the following code and look at the - // results: - - /* - Sys_Printf("normalEpsilon is %f\n", normalEpsilon); - for (i = 0;; i++) - { - normal[0] = 1.0; - normal[1] = 0.0; - normal[2] = i * 0.000001; - VectorNormalize(normal, normal); - if (1.0 - normal[0] >= normalEpsilon) { - Sys_Printf("(%f %f %f)\n", normal[0], normal[1], normal[2]); - Error("SnapNormal: test completed"); - } - } - */ - - // When the normalEpsilon is 0.00001, the loop will break out when normal is - // (0.999990 0.000000 0.004469). In other words, this is the vector closest - // to axial that will NOT be snapped. Anything closer will be snaped. Now, - // 0.004469 is close to 1/225. The length of a circular quarter-arc of radius - // 1 is PI/2, or about 1.57. And 0.004469/1.57 is about 0.0028, or about - // 1/350. Expressed a different way, 1/350 is also about 0.26/90. - // This means is that a normal with an angle that is within 1/4 of a degree - // from axial will be "snapped". My belief is that the person who wrote the - // code below did not intend it this way. I think the person intended that - // the epsilon be measured against the vector components close to 0, not 1.0. - // I think the logic should be: if 2 of the normal components are within - // epsilon of 0, then the vector can be snapped to be perfectly axial. - // We may consider adjusting the epsilon to a larger value when we make this - // code fix. - - for( i = 0; i < 3; i++ ) - { - if( fabs( normal[ i ] - 1 ) < normalEpsilon ) - { - VectorClear( normal ); - normal[ i ] = 1; - return qtrue; - } - if( fabs( normal[ i ] - -1 ) < normalEpsilon ) - { - VectorClear( normal ); - normal[ i ] = -1; - return qtrue; - } - } - return qfalse; -#endif -} - - - -/* -SnapPlane() -snaps a plane to normal/distance epsilons -*/ - -void SnapPlane( vec3_t normal, vec_t *dist, vec3_t center ) -{ -// SnapPlane disabled by LordHavoc because it often messes up collision -// brushes made from triangles of embedded models, and it has little effect -// on anything else (axial planes are usually derived from snapped points) -/* - SnapPlane reenabled by namespace because of multiple reports of - q3map2-crashes which were triggered by this patch. -*/ - SnapNormal( normal ); - - // TODO: Rambetter has some serious comments here as well. First off, - // in the case where a normal is non-axial, there is nothing special - // about integer distances. I would think that snapping a distance might - // make sense for axial normals, but I'm not so sure about snapping - // non-axial normals. A shift by 0.01 in a plane, multiplied by a clipping - // against another plane that is 5 degrees off, and we introduce 0.1 error - // easily. A 0.1 error in a vertex is where problems start to happen, such - // as disappearing triangles. - - // Second, assuming we have snapped the normal above, let's say that the - // plane we just snapped was defined for some points that are actually - // quite far away from normal * dist. Well, snapping the normal in this - // case means that we've just moved those points by potentially many units! - // Therefore, if we are going to snap the normal, we need to know the - // points we're snapping for so that the plane snaps with those points in - // mind (points remain close to the plane). - - // I would like to know exactly which problems SnapPlane() is trying to - // solve so that we can better engineer it (I'm not saying that SnapPlane() - // should be removed altogether). Fix all this snapping code at some point! - - if( fabs( *dist - Q_rint( *dist ) ) < distanceEpsilon ) - *dist = Q_rint( *dist ); -} - -/* -SnapPlaneImproved() -snaps a plane to normal/distance epsilons, improved code -*/ -void SnapPlaneImproved(vec3_t normal, vec_t *dist, int numPoints, const vec3_t *points) -{ - int i; - vec3_t center; - vec_t distNearestInt; - - if (SnapNormal(normal)) - { - if (numPoints > 0) - { - // Adjust the dist so that the provided points don't drift away. - VectorClear(center); - for (i = 0; i < numPoints; i++) - { - VectorAdd(center, points[i], center); - } - for (i = 0; i < 3; i++) { center[i] = center[i] / numPoints; } - *dist = DotProduct(normal, center); - } - } - - if (VectorIsOnAxis(normal)) - { - // Only snap distance if the normal is an axis. Otherwise there - // is nothing "natural" about snapping the distance to an integer. - distNearestInt = Q_rint(*dist); - if (-distanceEpsilon < *dist - distNearestInt && *dist - distNearestInt < distanceEpsilon) - { - *dist = distNearestInt; - } - } -} - - - -/* -FindFloatPlane() -ydnar: changed to allow a number of test points to be supplied that -must be within an epsilon distance of the plane -*/ - -int FindFloatPlane( vec3_t innormal, vec_t dist, int numPoints, vec3_t *points ) // NOTE: this has a side effect on the normal. Good or bad? - -#ifdef USE_HASHING - -{ - int i, j, hash, h; - int pidx; - plane_t *p; - vec_t d; - vec3_t normal; - - VectorCopy(innormal, normal); -#if Q3MAP2_EXPERIMENTAL_SNAP_PLANE_FIX - SnapPlaneImproved(normal, &dist, numPoints, (const vec3_t *) points); -#else - SnapPlane( normal, &dist ); -#endif - /* hash the plane */ - hash = (PLANE_HASHES - 1) & (int) fabs( dist ); - - /* search the border bins as well */ - for( i = -1; i <= 1; i++ ) - { - h = (hash + i) & (PLANE_HASHES - 1); - for( pidx = planehash[ h ] - 1; pidx != -1; pidx = mapplanes[pidx].hash_chain - 1 ) - { - p = &mapplanes[pidx]; - - /* do standard plane compare */ - if( !PlaneEqual( p, normal, dist ) ) - continue; - - /* ydnar: uncomment the following line for old-style plane finding */ - //% return p - mapplanes; - - /* ydnar: test supplied points against this plane */ - for( j = 0; j < numPoints; j++ ) - { - // NOTE: When dist approaches 2^16, the resolution of 32 bit floating - // point number is greatly decreased. The distanceEpsilon cannot be - // very small when world coordinates extend to 2^16. Making the - // dot product here in 64 bit land will not really help the situation - // because the error will already be carried in dist. - d = DotProduct( points[ j ], p->normal ) - p->dist; - d = fabs(d); - if (d != 0.0 && d >= distanceEpsilon) - break; // Point is too far from plane. - } - - /* found a matching plane */ - if( j >= numPoints ) - return p - mapplanes; - } - } - - /* none found, so create a new one */ - return CreateNewFloatPlane( normal, dist ); -} - -#else - -{ - int i; - plane_t *p; - vec3_t normal; - - VectorCopy(innormal, normal); -#if Q3MAP2_EXPERIMENTAL_SNAP_PLANE_FIX - SnapPlaneImproved(normal, &dist, numPoints, (const vec3_t *) points); -#else - SnapPlane( normal, &dist ); -#endif - for( i = 0, p = mapplanes; i < nummapplanes; i++, p++ ) - { - if( !PlaneEqual( p, normal, dist ) ) - continue; - - /* ydnar: uncomment the following line for old-style plane finding */ - //% return i; - - /* ydnar: test supplied points against this plane */ - for( j = 0; j < numPoints; j++ ) - { - d = DotProduct( points[ j ], p->normal ) - p->dist; - if( fabs( d ) > distanceEpsilon ) - break; - } - - /* found a matching plane */ - if( j >= numPoints ) - return i; - // TODO: Note that the non-USE_HASHING code does not compute epsilons - // for the provided points. It should do that. I think this code - // is unmaintained because nobody sets USE_HASHING to off. - } - - return CreateNewFloatPlane( normal, dist ); -} - -#endif - - - -/* -MapPlaneFromPoints() -takes 3 points and finds the plane they lie in -*/ - -int MapPlaneFromPoints( vec3_t *p ) -{ -#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES - vec3_accu_t paccu[3]; - vec3_accu_t t1, t2, normalAccu; - vec3_t normal; - vec_t dist; - - VectorCopyRegularToAccu(p[0], paccu[0]); - VectorCopyRegularToAccu(p[1], paccu[1]); - VectorCopyRegularToAccu(p[2], paccu[2]); - - VectorSubtractAccu(paccu[0], paccu[1], t1); - VectorSubtractAccu(paccu[2], paccu[1], t2); - CrossProductAccu(t1, t2, normalAccu); - VectorNormalizeAccu(normalAccu, normalAccu); - // TODO: A 32 bit float for the plane distance isn't enough resolution - // if the plane is 2^16 units away from the origin (the "epsilon" approaches - // 0.01 in that case). - dist = (vec_t) DotProductAccu(paccu[0], normalAccu); - VectorCopyAccuToRegular(normalAccu, normal); - - return FindFloatPlane(normal, dist, 3, p); -#else - vec3_t t1, t2, normal; - vec_t dist; - - - /* calc plane normal */ - VectorSubtract( p[ 0 ], p[ 1 ], t1 ); - VectorSubtract( p[ 2 ], p[ 1 ], t2 ); - CrossProduct( t1, t2, normal ); - VectorNormalize( normal, normal ); - - /* calc plane distance */ - dist = DotProduct( p[ 0 ], normal ); - - /* store the plane */ - return FindFloatPlane( normal, dist, 3, p ); -#endif -} - - - -/* -SetBrushContents() -the content flags and compile flags on all sides of a brush should be the same -*/ - -void SetBrushContents( brush_t *b ) -{ - int contentFlags, compileFlags; - side_t *s; - int i; - qboolean mixed; - - - /* get initial compile flags from first side */ - s = &b->sides[ 0 ]; - contentFlags = s->contentFlags; - compileFlags = s->compileFlags; - b->contentShader = s->shaderInfo; - mixed = qfalse; - - /* get the content/compile flags for every side in the brush */ - for( i = 1; i < b->numsides; i++, s++ ) - { - s = &b->sides[ i ]; - if( s->shaderInfo == NULL ) - continue; - if( s->contentFlags != contentFlags || s->compileFlags != compileFlags ) - mixed = qtrue; - - contentFlags |= s->contentFlags; - compileFlags |= s->compileFlags; - } - - /* ydnar: getting rid of this stupid warning */ - //% if( mixed ) - //% Sys_FPrintf( SYS_VRB,"Entity %i, Brush %i: mixed face contentFlags\n", b->entitynum, b->brushnum ); - - /* check for detail & structural */ - if( (compileFlags & C_DETAIL) && (compileFlags & C_STRUCTURAL) ) - { - xml_Select( "Mixed detail and structural (defaulting to structural)", mapEnt->mapEntityNum, entitySourceBrushes, qfalse ); - compileFlags &= ~C_DETAIL; - } - - /* the fulldetail flag will cause detail brushes to be treated like normal brushes */ - if( fulldetail ) - compileFlags &= ~C_DETAIL; - - /* all translucent brushes that aren't specifically made structural will be detail */ - if( (compileFlags & C_TRANSLUCENT) && !(compileFlags & C_STRUCTURAL) ) - compileFlags |= C_DETAIL; - - /* detail? */ - if( compileFlags & C_DETAIL ) - { - c_detail++; - b->detail = qtrue; - } - else - { - c_structural++; - b->detail = qfalse; - } - - /* opaque? */ - if( compileFlags & C_TRANSLUCENT ) - b->opaque = qfalse; - else - b->opaque = qtrue; - - /* areaportal? */ - if( compileFlags & C_AREAPORTAL ) - c_areaportals++; - - /* set brush flags */ - b->contentFlags = contentFlags; - b->compileFlags = compileFlags; -} - - - -/* -AddBrushBevels() -adds any additional planes necessary to allow the brush being -built to be expanded against axial bounding boxes -ydnar 2003-01-20: added mrelusive fixes -*/ - -void AddBrushBevels( void ) -{ - int axis, dir; - int i, j, k, l, order; - side_t sidetemp; - side_t *s, *s2; - winding_t *w, *w2; - vec3_t normal; - float dist; - vec3_t vec, vec2; - float d, minBack; - - // - // add the axial planes - // - order = 0; - for ( axis = 0; axis < 3; axis++ ) { - for ( dir = -1; dir <= 1; dir += 2, order++ ) { - // see if the plane is allready present - for ( i = 0, s = buildBrush->sides; i < buildBrush->numsides; i++, s++ ) - { - /* ydnar: testing disabling of mre code */ - #if 0 - if ( dir > 0 ) { - if ( mapplanes[s->planenum].normal[axis] >= 0.9999f ) { - break; - } - } - else { - if ( mapplanes[s->planenum].normal[axis] <= -0.9999f ) { - break; - } - } - #else - if( (dir > 0 && mapplanes[ s->planenum ].normal[ axis ] == 1.0f ) || - (dir < 0 && mapplanes[ s->planenum ].normal[ axis ] == -1.0f) ) - break; - #endif - } - - if ( i == buildBrush->numsides ) { - // add a new side - if ( buildBrush->numsides == MAX_BUILD_SIDES ) { - xml_Select( "MAX_BUILD_SIDES", buildBrush->entityNum, buildBrush->brushNum, qtrue); - } - memset( s, 0, sizeof( *s ) ); - buildBrush->numsides++; - VectorClear (normal); - normal[axis] = dir; - - if( dir == 1 ) - { - /* ydnar: adding bevel plane snapping for fewer bsp planes */ - if( bevelSnap > 0 ) - dist = floor( buildBrush->maxs[ axis ] / bevelSnap ) * bevelSnap; - else - dist = buildBrush->maxs[ axis ]; - } - else - { - /* ydnar: adding bevel plane snapping for fewer bsp planes */ - if( bevelSnap > 0 ) - dist = -ceil( buildBrush->mins[ axis ] / bevelSnap ) * bevelSnap; - else - dist = -buildBrush->mins[ axis ]; - } - - s->planenum = FindFloatPlane( normal, dist, 0, NULL ); - s->contentFlags = buildBrush->sides[ 0 ].contentFlags; - s->bevel = qtrue; - c_boxbevels++; - } - - // if the plane is not in it canonical order, swap it - if ( i != order ) { - sidetemp = buildBrush->sides[order]; - buildBrush->sides[order] = buildBrush->sides[i]; - buildBrush->sides[i] = sidetemp; - } - } - } - - // - // add the edge bevels - // - if ( buildBrush->numsides == 6 ) { - return; // pure axial - } - - // test the non-axial plane edges - for ( i = 6; i < buildBrush->numsides; i++ ) { - s = buildBrush->sides + i; - w = s->winding; - if ( !w ) { - continue; - } - for ( j = 0; j < w->numpoints; j++) { - k = (j+1)%w->numpoints; - VectorSubtract( w->p[j], w->p[k], vec ); - if ( VectorNormalize( vec, vec ) < 0.5f ) { - continue; - } - SnapNormal( vec ); - for ( k = 0; k < 3; k++ ) { - if ( vec[k] == -1.0f || vec[k] == 1.0f || (vec[k] == 0.0f && vec[(k+1)%3] == 0.0f) ) { - break; // axial - } - } - if ( k != 3 ) { - continue; // only test non-axial edges - } - - /* debug code */ - //% Sys_Printf( "-------------\n" ); - - // try the six possible slanted axials from this edge - for ( axis = 0; axis < 3; axis++ ) { - for ( dir = -1; dir <= 1; dir += 2 ) { - // construct a plane - VectorClear( vec2 ); - vec2[axis] = dir; - CrossProduct( vec, vec2, normal ); - if ( VectorNormalize( normal, normal ) < 0.5f ) { - continue; - } - dist = DotProduct( w->p[j], normal ); - - // if all the points on all the sides are - // behind this plane, it is a proper edge bevel - for ( k = 0; k < buildBrush->numsides; k++ ) { - - // if this plane has allready been used, skip it - if ( PlaneEqual( &mapplanes[buildBrush->sides[k].planenum], normal, dist ) ) { - break; - } - - w2 = buildBrush->sides[k].winding; - if ( !w2 ) { - continue; - } - minBack = 0.0f; - for ( l = 0; l < w2->numpoints; l++ ) { - d = DotProduct( w2->p[l], normal ) - dist; - if ( d > 0.1f ) { - break; // point in front - } - if ( d < minBack ) { - minBack = d; - } - } - // if some point was at the front - if ( l != w2->numpoints ) { - break; - } - - // if no points at the back then the winding is on the bevel plane - if ( minBack > -0.1f ) { - //% Sys_Printf( "On bevel plane\n" ); - break; - } - } - - if ( k != buildBrush->numsides ) { - continue; // wasn't part of the outer hull - } - - /* debug code */ - //% Sys_Printf( "n = %f %f %f\n", normal[ 0 ], normal[ 1 ], normal[ 2 ] ); - - // add this plane - if( buildBrush->numsides == MAX_BUILD_SIDES ) { - xml_Select( "MAX_BUILD_SIDES", buildBrush->entityNum, buildBrush->brushNum, qtrue); - } - s2 = &buildBrush->sides[buildBrush->numsides]; - buildBrush->numsides++; - memset( s2, 0, sizeof( *s2 ) ); - - s2->planenum = FindFloatPlane( normal, dist, 1, &w->p[ j ] ); - s2->contentFlags = buildBrush->sides[0].contentFlags; - s2->bevel = qtrue; - c_edgebevels++; - } - } - } - } -} - - - -/* -FinishBrush() -produces a final brush based on the buildBrush->sides array -and links it to the current entity -*/ - -static void MergeOrigin(entity_t *ent, vec3_t origin) -{ - vec3_t adjustment; - char string[128]; - - /* we have not parsed the brush completely yet... */ - GetVectorForKey( ent, "origin", ent->origin ); - - VectorMA(origin, -1, ent->originbrush_origin, adjustment); - VectorAdd(adjustment, ent->origin, ent->origin); - VectorCopy(origin, ent->originbrush_origin); - - sprintf(string, "%f %f %f", ent->origin[0], ent->origin[1], ent->origin[2]); - SetKeyValue(ent, "origin", string); -} - -brush_t *FinishBrush( qboolean noCollapseGroups ) -{ - brush_t *b; - - - /* create windings for sides and bounds for brush */ - if ( !CreateBrushWindings( buildBrush ) ) - return NULL; - - /* origin brushes are removed, but they set the rotation origin for the rest of the brushes in the entity. - after the entire entity is parsed, the planenums and texinfos will be adjusted for the origin brush */ - if( buildBrush->compileFlags & C_ORIGIN ) - { - vec3_t origin; - - Sys_Printf( "Entity %i, Brush %i: origin brush detected\n", - mapEnt->mapEntityNum, entitySourceBrushes ); - - if( numEntities == 1 ) - { - Sys_Printf( "Entity %i, Brush %i: origin brushes not allowed in world\n", - mapEnt->mapEntityNum, entitySourceBrushes ); - return NULL; - } - - VectorAdd (buildBrush->mins, buildBrush->maxs, origin); - VectorScale (origin, 0.5, origin); - - MergeOrigin(&entities[ numEntities - 1 ], origin); - - /* don't keep this brush */ - return NULL; - } - - /* determine if the brush is an area portal */ - if( buildBrush->compileFlags & C_AREAPORTAL ) - { - if( numEntities != 1 ) - { - Sys_Printf ("Entity %i, Brush %i: areaportals only allowed in world\n", numEntities - 1, entitySourceBrushes ); - return NULL; - } - } - - /* add bevel planes */ - if(!noCollapseGroups) - AddBrushBevels(); - - /* keep it */ - b = CopyBrush( buildBrush ); - - /* set map entity and brush numbering */ - b->entityNum = mapEnt->mapEntityNum; - b->brushNum = entitySourceBrushes; - - /* set original */ - b->original = b; - - /* link opaque brushes to head of list, translucent brushes to end */ - if( b->opaque || mapEnt->lastBrush == NULL ) - { - b->next = mapEnt->brushes; - mapEnt->brushes = b; - if( mapEnt->lastBrush == NULL ) - mapEnt->lastBrush = b; - } - else - { - b->next = NULL; - mapEnt->lastBrush->next = b; - mapEnt->lastBrush = b; - } - - /* link colorMod volume brushes to the entity directly */ - if( b->contentShader != NULL && - b->contentShader->colorMod != NULL && - b->contentShader->colorMod->type == CM_VOLUME ) - { - b->nextColorModBrush = mapEnt->colorModBrushes; - mapEnt->colorModBrushes = b; - } - - /* return to sender */ - return b; -} - - - -/* -TextureAxisFromPlane() -determines best orthagonal axis to project a texture onto a wall -(must be identical in radiant!) -*/ - -vec3_t baseaxis[18] = -{ - {0,0,1}, {1,0,0}, {0,-1,0}, // floor - {0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling - {1,0,0}, {0,1,0}, {0,0,-1}, // west wall - {-1,0,0}, {0,1,0}, {0,0,-1}, // east wall - {0,1,0}, {1,0,0}, {0,0,-1}, // south wall - {0,-1,0}, {1,0,0}, {0,0,-1} // north wall -}; - -void TextureAxisFromPlane( plane_t *pln, vec3_t xv, vec3_t yv ) -{ - int bestaxis; - vec_t dot,best; - int i; - - best = 0; - bestaxis = 0; - - for (i=0 ; i<6 ; i++) - { - dot = DotProduct (pln->normal, baseaxis[i*3]); - if( dot > best + 0.0001f ) /* ydnar: bug 637 fix, suggested by jmonroe */ - { - best = dot; - bestaxis = i; - } - } - - VectorCopy (baseaxis[bestaxis*3+1], xv); - VectorCopy (baseaxis[bestaxis*3+2], yv); -} - - - -/* -QuakeTextureVecs() -creates world-to-texture mapping vecs for crappy quake plane arrangements -*/ - -void QuakeTextureVecs( plane_t *plane, vec_t shift[ 2 ], vec_t rotate, vec_t scale[ 2 ], vec_t mappingVecs[ 2 ][ 4 ] ) -{ - vec3_t vecs[2]; - int sv, tv; - vec_t ang, sinv, cosv; - vec_t ns, nt; - int i, j; - - - TextureAxisFromPlane(plane, vecs[0], vecs[1]); - - if (!scale[0]) - scale[0] = 1; - if (!scale[1]) - scale[1] = 1; - - // rotate axis - if (rotate == 0) - { sinv = 0 ; cosv = 1; } - else if (rotate == 90) - { sinv = 1 ; cosv = 0; } - else if (rotate == 180) - { sinv = 0 ; cosv = -1; } - else if (rotate == 270) - { sinv = -1 ; cosv = 0; } - else - { - ang = rotate / 180 * Q_PI; - sinv = sin(ang); - cosv = cos(ang); - } - - if (vecs[0][0]) - sv = 0; - else if (vecs[0][1]) - sv = 1; - else - sv = 2; - - if (vecs[1][0]) - tv = 0; - else if (vecs[1][1]) - tv = 1; - else - tv = 2; - - for (i=0 ; i<2 ; i++) { - ns = cosv * vecs[i][sv] - sinv * vecs[i][tv]; - nt = sinv * vecs[i][sv] + cosv * vecs[i][tv]; - vecs[i][sv] = ns; - vecs[i][tv] = nt; - } - - for (i=0 ; i<2 ; i++) - for (j=0 ; j<3 ; j++) - mappingVecs[i][j] = vecs[i][j] / scale[i]; - - mappingVecs[0][3] = shift[0]; - mappingVecs[1][3] = shift[1]; -} - - - -/* -ParseRawBrush() -parses the sides into buildBrush->sides[], nothing else. -no validation, back plane removal, etc. - -Timo - 08/26/99 -added brush epairs parsing ( ignoring actually ) -Timo - 08/04/99 -added exclusive brush primitive parsing -Timo - 08/08/99 -support for old brush format back in -NOTE: it would be "cleaner" to have seperate functions to parse between old and new brushes -*/ - -static void ParseRawBrush( qboolean onlyLights ) -{ - side_t *side; - vec3_t planePoints[ 3 ]; - int planenum; - shaderInfo_t *si; - vec_t shift[ 2 ]; - vec_t rotate = 0; - vec_t scale[ 2 ]; - char name[ MAX_QPATH ]; - char shader[ MAX_QPATH ]; - int flags; - - - /* initial setup */ - buildBrush->numsides = 0; - buildBrush->detail = qfalse; - - /* bp */ - if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) - MatchToken( "{" ); - - /* parse sides */ - while( 1 ) - { - if( !GetToken( qtrue ) ) - break; - if( !strcmp( token, "}" ) ) - break; - - /* ttimo : bp: here we may have to jump over brush epairs (only used in editor) */ - if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) - { - while( 1 ) - { - if( strcmp( token, "(" ) ) - GetToken( qfalse ); - else - break; - GetToken( qtrue ); - } - } - UnGetToken(); - - /* test side count */ - if( buildBrush->numsides >= MAX_BUILD_SIDES ) - xml_Select( "MAX_BUILD_SIDES", buildBrush->entityNum, buildBrush->brushNum, qtrue ); - - /* add side */ - side = &buildBrush->sides[ buildBrush->numsides ]; - memset( side, 0, sizeof( *side ) ); - buildBrush->numsides++; - - /* read the three point plane definition */ - Parse1DMatrix( 3, planePoints[ 0 ] ); - Parse1DMatrix( 3, planePoints[ 1 ] ); - Parse1DMatrix( 3, planePoints[ 2 ] ); - - /* bp: read the texture matrix */ - if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) - Parse2DMatrix( 2, 3, (float*) side->texMat ); - - /* read shader name */ - GetToken( qfalse ); - strcpy( name, token ); - - /* bp */ - if( g_bBrushPrimit == BPRIMIT_OLDBRUSHES ) - { - GetToken( qfalse ); - shift[ 0 ] = atof( token ); - GetToken( qfalse ); - shift[ 1 ] = atof( token ); - GetToken( qfalse ); - rotate = atof( token ); - GetToken( qfalse ); - scale[ 0 ] = atof( token ); - GetToken( qfalse ); - scale[ 1 ] = atof( token ); - } - - /* set default flags and values */ - sprintf( shader, "textures/%s", name ); - if( onlyLights ) - si = &shaderInfo[ 0 ]; - else - si = ShaderInfoForShader( shader ); - side->shaderInfo = si; - side->surfaceFlags = si->surfaceFlags; - side->contentFlags = si->contentFlags; - side->compileFlags = si->compileFlags; - side->value = si->value; - - /* ydnar: gs mods: bias texture shift */ - if( si->globalTexture == qfalse ) - { - shift[ 0 ] -= (floor( shift[ 0 ] / si->shaderWidth ) * si->shaderWidth); - shift[ 1 ] -= (floor( shift[ 1 ] / si->shaderHeight ) * si->shaderHeight); - } - - /* - historically, there are 3 integer values at the end of a brushside line in a .map file. - in quake 3, the only thing that mattered was the first of these three values, which - was previously the content flags. and only then did a single bit matter, the detail - bit. because every game has its own special flags for specifying detail, the - traditionally game-specified CONTENTS_DETAIL flag was overridden for Q3Map 2.3.0 - by C_DETAIL, defined in q3map2.h. the value is exactly as it was before, but - is stored in compileFlags, as opposed to contentFlags, for multiple-game - portability. :sigh: - */ - - if( TokenAvailable() ) - { - /* get detail bit from map content flags */ - GetToken( qfalse ); - flags = atoi( token ); - if( flags & C_DETAIL ) - side->compileFlags |= C_DETAIL; - - /* historical */ - GetToken( qfalse ); - //% td.flags = atoi( token ); - GetToken( qfalse ); - //% td.value = atoi( token ); - } - - /* find the plane number */ - planenum = MapPlaneFromPoints( planePoints ); - side->planenum = planenum; - - /* bp: get the texture mapping for this texturedef / plane combination */ - if( g_bBrushPrimit == BPRIMIT_OLDBRUSHES ) - QuakeTextureVecs( &mapplanes[ planenum ], shift, rotate, scale, side->vecs ); - } - - /* bp */ - if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) - { - UnGetToken(); - MatchToken( "}" ); - MatchToken( "}" ); - } -} - - - -/* -RemoveDuplicateBrushPlanes -returns false if the brush has a mirrored set of planes, -meaning it encloses no volume. -also removes planes without any normal -*/ - -qboolean RemoveDuplicateBrushPlanes( brush_t *b ) -{ - int i, j, k; - side_t *sides; - - sides = b->sides; - - for ( i = 1 ; i < b->numsides ; i++ ) { - - // check for a degenerate plane - if ( sides[i].planenum == -1) { - xml_Select( "degenerate plane", b->entityNum, b->brushNum, qfalse ); - // remove it - for ( k = i + 1 ; k < b->numsides ; k++ ) { - sides[k-1] = sides[k]; - } - b->numsides--; - i--; - continue; - } - - // check for duplication and mirroring - for ( j = 0 ; j < i ; j++ ) { - if ( sides[i].planenum == sides[j].planenum ) { - xml_Select( "duplicate plane", b->entityNum, b->brushNum, qfalse ); - // remove the second duplicate - for ( k = i + 1 ; k < b->numsides ; k++ ) { - sides[k-1] = sides[k]; - } - b->numsides--; - i--; - break; - } - - if ( sides[i].planenum == (sides[j].planenum ^ 1) ) { - // mirror plane, brush is invalid - xml_Select( "mirrored plane", b->entityNum, b->brushNum, qfalse ); - return qfalse; - } - } - } - return qtrue; -} - - - -/* -ParseBrush() -parses a brush out of a map file and sets it up -*/ - -static void ParseBrush( qboolean onlyLights, qboolean noCollapseGroups ) -{ - brush_t *b; - - - /* parse the brush out of the map */ - ParseRawBrush( onlyLights ); - - /* only go this far? */ - if( onlyLights ) - return; - - /* set some defaults */ - buildBrush->portalareas[ 0 ] = -1; - buildBrush->portalareas[ 1 ] = -1; - buildBrush->entityNum = numMapEntities - 1; - buildBrush->brushNum = entitySourceBrushes; - - /* if there are mirrored planes, the entire brush is invalid */ - if( !RemoveDuplicateBrushPlanes( buildBrush ) ) - return; - - /* get the content for the entire brush */ - SetBrushContents( buildBrush ); - - /* allow detail brushes to be removed */ - if( nodetail && (buildBrush->compileFlags & C_DETAIL) ) - { - //% FreeBrush( buildBrush ); - return; - } - - /* allow liquid brushes to be removed */ - if( nowater && (buildBrush->compileFlags & C_LIQUID ) ) - { - //% FreeBrush( buildBrush ); - return; - } - - /* ydnar: allow hint brushes to be removed */ - if( noHint && (buildBrush->compileFlags & C_HINT) ) - { - //% FreeBrush( buildBrush ); - return; - } - - /* finish the brush */ - b = FinishBrush(noCollapseGroups); -} - - - -/* -MoveBrushesToWorld() -takes all of the brushes from the current entity and -adds them to the world's brush list -(used by func_group) -*/ - -void AdjustBrushesForOrigin( entity_t *ent ); -void MoveBrushesToWorld( entity_t *ent ) -{ - brush_t *b, *next; - parseMesh_t *pm; - - /* we need to undo the common/origin adjustment, and instead shift them by the entity key origin */ - VectorScale(ent->origin, -1, ent->originbrush_origin); - AdjustBrushesForOrigin(ent); - VectorClear(ent->originbrush_origin); - - /* move brushes */ - for( b = ent->brushes; b != NULL; b = next ) - { - /* get next brush */ - next = b->next; - - /* link opaque brushes to head of list, translucent brushes to end */ - if( b->opaque || entities[ 0 ].lastBrush == NULL ) - { - b->next = entities[ 0 ].brushes; - entities[ 0 ].brushes = b; - if( entities[ 0 ].lastBrush == NULL ) - entities[ 0 ].lastBrush = b; - } - else - { - b->next = NULL; - entities[ 0 ].lastBrush->next = b; - entities[ 0 ].lastBrush = b; - } - } - ent->brushes = NULL; - - /* ydnar: move colormod brushes */ - if( ent->colorModBrushes != NULL ) - { - for( b = ent->colorModBrushes; b->nextColorModBrush != NULL; b = b->nextColorModBrush ); - - b->nextColorModBrush = entities[ 0 ].colorModBrushes; - entities[ 0 ].colorModBrushes = ent->colorModBrushes; - - ent->colorModBrushes = NULL; - } - - /* move patches */ - if( ent->patches != NULL ) - { - for( pm = ent->patches; pm->next != NULL; pm = pm->next ); - - pm->next = entities[ 0 ].patches; - entities[ 0 ].patches = ent->patches; - - ent->patches = NULL; - } -} - - - -/* -AdjustBrushesForOrigin() -*/ - -void AdjustBrushesForOrigin( entity_t *ent ) -{ - - int i; - side_t *s; - vec_t newdist; - brush_t *b; - parseMesh_t *p; - - /* walk brush list */ - for( b = ent->brushes; b != NULL; b = b->next ) - { - /* offset brush planes */ - for( i = 0; i < b->numsides; i++) - { - /* get brush side */ - s = &b->sides[ i ]; - - /* offset side plane */ - newdist = mapplanes[ s->planenum ].dist - DotProduct( mapplanes[ s->planenum ].normal, ent->originbrush_origin ); - - /* find a new plane */ - s->planenum = FindFloatPlane( mapplanes[ s->planenum ].normal, newdist, 0, NULL ); - } - - /* rebuild brush windings (ydnar: just offsetting the winding above should be fine) */ - CreateBrushWindings( b ); - } - - /* walk patch list */ - for( p = ent->patches; p != NULL; p = p->next ) - { - for( i = 0; i < (p->mesh.width * p->mesh.height); i++ ) - VectorSubtract( p->mesh.verts[ i ].xyz, ent->originbrush_origin, p->mesh.verts[ i ].xyz ); - } -} - - - -/* -SetEntityBounds() - ydnar -finds the bounds of an entity's brushes (necessary for terrain-style generic metashaders) -*/ - -void SetEntityBounds( entity_t *e ) -{ - int i; - brush_t *b; - parseMesh_t *p; - vec3_t mins, maxs; - const char *value; - - - - - /* walk the entity's brushes/patches and determine bounds */ - ClearBounds( mins, maxs ); - for( b = e->brushes; b; b = b->next ) - { - AddPointToBounds( b->mins, mins, maxs ); - AddPointToBounds( b->maxs, mins, maxs ); - } - for( p = e->patches; p; p = p->next ) - { - for( i = 0; i < (p->mesh.width * p->mesh.height); i++ ) - AddPointToBounds( p->mesh.verts[ i ].xyz, mins, maxs ); - } - - /* try to find explicit min/max key */ - value = ValueForKey( e, "min" ); - if( value[ 0 ] != '\0' ) - GetVectorForKey( e, "min", mins ); - value = ValueForKey( e, "max" ); - if( value[ 0 ] != '\0' ) - GetVectorForKey( e, "max", maxs ); - - /* store the bounds */ - for( b = e->brushes; b; b = b->next ) - { - VectorCopy( mins, b->eMins ); - VectorCopy( maxs, b->eMaxs ); - } - for( p = e->patches; p; p = p->next ) - { - VectorCopy( mins, p->eMins ); - VectorCopy( maxs, p->eMaxs ); - } -} - - - -/* -LoadEntityIndexMap() - ydnar -based on LoadAlphaMap() from terrain.c, a little more generic -*/ - -void LoadEntityIndexMap( entity_t *e ) -{ - int i, size, numLayers, w, h; - const char *value, *indexMapFilename, *shader; - char ext[ MAX_QPATH ], offset[ 4096 ], *search, *space; - byte *pixels; - unsigned int *pixels32; - indexMap_t *im; - brush_t *b; - parseMesh_t *p; - - - /* this only works with bmodel ents */ - if( e->brushes == NULL && e->patches == NULL ) - return; - - /* determine if there is an index map (support legacy "alphamap" key as well) */ - value = ValueForKey( e, "_indexmap" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( e, "alphamap" ); - if( value[ 0 ] == '\0' ) - return; - indexMapFilename = value; - - /* get number of layers (support legacy "layers" key as well) */ - value = ValueForKey( e, "_layers" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( e, "layers" ); - if( value[ 0 ] == '\0' ) - { - Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" has missing \"_layers\" or \"layers\" key\n", indexMapFilename ); - Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); - return; - } - numLayers = atoi( value ); - if( numLayers < 1 ) - { - Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" has < 1 layer (%d)\n", indexMapFilename, numLayers ); - Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); - return; - } - - /* get base shader name (support legacy "shader" key as well) */ - value = ValueForKey( mapEnt, "_shader" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( e, "shader" ); - if( value[ 0 ] == '\0' ) - { - Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" has missing \"_shader\" or \"shader\" key\n", indexMapFilename ); - Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); - return; - } - shader = value; - - /* note it */ - Sys_FPrintf( SYS_VRB, "Entity %d (%s) has shader index map \"%s\"\n", mapEnt->mapEntityNum, ValueForKey( e, "classname" ), indexMapFilename ); - - /* get index map file extension */ - ExtractFileExtension( indexMapFilename, ext ); - - /* handle tga image */ - if( !Q_stricmp( ext, "tga" ) ) - { - /* load it */ - Load32BitImage( indexMapFilename, &pixels32, &w, &h ); - - /* convert to bytes */ - size = w * h; - pixels = safe_malloc( size ); - for( i = 0; i < size; i++ ) - { - pixels[ i ] = ((pixels32[ i ] & 0xFF) * numLayers) / 256; - if( pixels[ i ] >= numLayers ) - pixels[ i ] = numLayers - 1; - } - - /* free the 32 bit image */ - free( pixels32 ); - } - else - { - /* load it */ - Load256Image( indexMapFilename, &pixels, NULL, &w, &h ); - - /* debug code */ - //% Sys_Printf( "-------------------------------" ); - - /* fix up out-of-range values */ - size = w * h; - for( i = 0; i < size; i++ ) - { - if( pixels[ i ] >= numLayers ) - pixels[ i ] = numLayers - 1; - - /* debug code */ - //% if( (i % w) == 0 ) - //% Sys_Printf( "\n" ); - //% Sys_Printf( "%c", pixels[ i ] + '0' ); - } - - /* debug code */ - //% Sys_Printf( "\n-------------------------------\n" ); - } - - /* the index map must be at least 2x2 pixels */ - if( w < 2 || h < 2 ) - { - Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" is smaller than 2x2 pixels\n", indexMapFilename ); - Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); - free( pixels ); - return; - } - - /* create a new index map */ - im = safe_malloc( sizeof( *im ) ); - memset( im, 0, sizeof( *im ) ); - - /* set it up */ - im->w = w; - im->h = h; - im->numLayers = numLayers; - strcpy( im->name, indexMapFilename ); - strcpy( im->shader, shader ); - im->pixels = pixels; - - /* get height offsets */ - value = ValueForKey( mapEnt, "_offsets" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( e, "offsets" ); - if( value[ 0 ] != '\0' ) - { - /* value is a space-seperated set of numbers */ - strcpy( offset, value ); - search = offset; - - /* get each value */ - for( i = 0; i < 256 && *search != '\0'; i++ ) - { - space = strstr( search, " " ); - if( space != NULL ) - *space = '\0'; - im->offsets[ i ] = atof( search ); - if( space == NULL ) - break; - search = space + 1; - } - } - - /* store the index map in every brush/patch in the entity */ - for( b = e->brushes; b != NULL; b = b->next ) - b->im = im; - for( p = e->patches; p != NULL; p = p->next ) - p->im = im; -} - - - - - - - -/* -ParseMapEntity() -parses a single entity out of a map file -*/ - -static qboolean ParseMapEntity( qboolean onlyLights, qboolean noCollapseGroups ) -{ - epair_t *ep; - const char *classname, *value; - float lightmapScale, shadeAngle; - int lightmapSampleSize; - char shader[ MAX_QPATH ]; - shaderInfo_t *celShader = NULL; - brush_t *brush; - parseMesh_t *patch; - qboolean funcGroup; - int castShadows, recvShadows; - - - /* eof check */ - if( !GetToken( qtrue ) ) - return qfalse; - - /* conformance check */ - if( strcmp( token, "{" ) ) - { - Sys_Printf( "WARNING: ParseEntity: { not found, found %s on line %d - last entity was at: <%4.2f, %4.2f, %4.2f>...\n" - "Continuing to process map, but resulting BSP may be invalid.\n", - token, scriptline, entities[ numEntities ].origin[ 0 ], entities[ numEntities ].origin[ 1 ], entities[ numEntities ].origin[ 2 ] ); - return qfalse; - } - - /* range check */ - if( numEntities >= MAX_MAP_ENTITIES ) - Error( "numEntities == MAX_MAP_ENTITIES" ); - - /* setup */ - entitySourceBrushes = 0; - mapEnt = &entities[ numEntities ]; - numEntities++; - memset( mapEnt, 0, sizeof( *mapEnt ) ); - - /* ydnar: true entity numbering */ - mapEnt->mapEntityNum = numMapEntities; - numMapEntities++; - - /* loop */ - while( 1 ) - { - /* get initial token */ - if( !GetToken( qtrue ) ) - { - Sys_Printf( "WARNING: ParseEntity: EOF without closing brace\n" - "Continuing to process map, but resulting BSP may be invalid.\n" ); - return qfalse; - } - - if( !strcmp( token, "}" ) ) - break; - - if( !strcmp( token, "{" ) ) - { - /* parse a brush or patch */ - if( !GetToken( qtrue ) ) - break; - - /* check */ - if( !strcmp( token, "patchDef2" ) ) - { - numMapPatches++; - ParsePatch( onlyLights ); - } - else if( !strcmp( token, "terrainDef" ) ) - { - //% ParseTerrain(); - Sys_Printf( "WARNING: Terrain entity parsing not supported in this build.\n" ); /* ydnar */ - } - else if( !strcmp( token, "brushDef" ) ) - { - if( g_bBrushPrimit == BPRIMIT_OLDBRUSHES ) - Error( "Old brush format not allowed in new brush format map" ); - g_bBrushPrimit = BPRIMIT_NEWBRUSHES; - - /* parse brush primitive */ - ParseBrush( onlyLights, noCollapseGroups ); - } - else - { - if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) - Error( "New brush format not allowed in old brush format map" ); - g_bBrushPrimit = BPRIMIT_OLDBRUSHES; - - /* parse old brush format */ - UnGetToken(); - ParseBrush( onlyLights, noCollapseGroups ); - } - entitySourceBrushes++; - } - else - { - /* parse a key / value pair */ - ep = ParseEPair(); - - /* ydnar: 2002-07-06 fixed wolf bug with empty epairs */ - if( ep->key[ 0 ] != '\0' && ep->value[ 0 ] != '\0' ) - { - ep->next = mapEnt->epairs; - mapEnt->epairs = ep; - } - } - } - - /* ydnar: get classname */ - classname = ValueForKey( mapEnt, "classname" ); - - /* ydnar: only lights? */ - if( onlyLights && Q_strncasecmp( classname, "light", 5 ) ) - { - numEntities--; - return qtrue; - } - - /* ydnar: determine if this is a func_group */ - if( !Q_stricmp( "func_group", classname ) ) - funcGroup = qtrue; - else - funcGroup = qfalse; - - /* worldspawn (and func_groups) default to cast/recv shadows in worldspawn group */ - if( funcGroup || mapEnt->mapEntityNum == 0 ) - { - //% Sys_Printf( "World: %d\n", mapEnt->mapEntityNum ); - castShadows = WORLDSPAWN_CAST_SHADOWS; - recvShadows = WORLDSPAWN_RECV_SHADOWS; - } - - /* other entities don't cast any shadows, but recv worldspawn shadows */ - else - { - //% Sys_Printf( "Entity: %d\n", mapEnt->mapEntityNum ); - castShadows = ENTITY_CAST_SHADOWS; - recvShadows = ENTITY_RECV_SHADOWS; - } - - /* get explicit shadow flags */ - GetEntityShadowFlags( mapEnt, NULL, &castShadows, &recvShadows ); - - /* vortex: added _ls key (short name of lightmapscale) */ - /* ydnar: get lightmap scaling value for this entity */ - lightmapScale = 0.0f; - if( strcmp( "", ValueForKey( mapEnt, "lightmapscale" ) ) || - strcmp( "", ValueForKey( mapEnt, "_lightmapscale" ) ) || - strcmp( "", ValueForKey( mapEnt, "_ls" ) ) ) - { - /* get lightmap scale from entity */ - lightmapScale = FloatForKey( mapEnt, "lightmapscale" ); - if( lightmapScale <= 0.0f ) - lightmapScale = FloatForKey( mapEnt, "_lightmapscale" ); - if( lightmapScale <= 0.0f ) - lightmapScale = FloatForKey( mapEnt, "_ls" ); - if( lightmapScale < 0.0f ) - lightmapScale = 0.0f; - if( lightmapScale > 0.0f ) - Sys_Printf( "Entity %d (%s) has lightmap scale of %.4f\n", mapEnt->mapEntityNum, classname, lightmapScale ); - } - - /* ydnar: get cel shader :) for this entity */ - value = ValueForKey( mapEnt, "_celshader" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ 0 ], "_celshader" ); - if( value[ 0 ] != '\0' ) - { - if(strcmp(value, "none")) - { - sprintf( shader, "textures/%s", value ); - celShader = ShaderInfoForShader( shader ); - Sys_Printf( "Entity %d (%s) has cel shader %s\n", mapEnt->mapEntityNum, classname, celShader->shader ); - } - else - { - celShader = NULL; - } - } - else - celShader = (*globalCelShader ? ShaderInfoForShader(globalCelShader) : NULL); - - /* jal : entity based _shadeangle */ - shadeAngle = 0.0f; - if ( strcmp( "", ValueForKey( mapEnt, "_shadeangle" ) ) ) - shadeAngle = FloatForKey( mapEnt, "_shadeangle" ); - /* vortex' aliases */ - else if ( strcmp( "", ValueForKey( mapEnt, "_smoothnormals" ) ) ) - shadeAngle = FloatForKey( mapEnt, "_smoothnormals" ); - else if ( strcmp( "", ValueForKey( mapEnt, "_sn" ) ) ) - shadeAngle = FloatForKey( mapEnt, "_sn" ); - else if ( strcmp( "", ValueForKey( mapEnt, "_smooth" ) ) ) - shadeAngle = FloatForKey( mapEnt, "_smooth" ); - - if( shadeAngle < 0.0f ) - shadeAngle = 0.0f; - - if( shadeAngle > 0.0f ) - Sys_Printf( "Entity %d (%s) has shading angle of %.4f\n", mapEnt->mapEntityNum, classname, shadeAngle ); - - /* jal : entity based _samplesize */ - lightmapSampleSize = 0; - if ( strcmp( "", ValueForKey( mapEnt, "_lightmapsamplesize" ) ) ) - lightmapSampleSize = IntForKey( mapEnt, "_lightmapsamplesize" ); - else if ( strcmp( "", ValueForKey( mapEnt, "_samplesize" ) ) ) - lightmapSampleSize = IntForKey( mapEnt, "_samplesize" ); - - if( lightmapSampleSize < 0 ) - lightmapSampleSize = 0; - - if( lightmapSampleSize > 0 ) - Sys_Printf( "Entity %d (%s) has lightmap sample size of %d\n", mapEnt->mapEntityNum, classname, lightmapSampleSize ); - - /* attach stuff to everything in the entity */ - for( brush = mapEnt->brushes; brush != NULL; brush = brush->next ) - { - brush->entityNum = mapEnt->mapEntityNum; - brush->castShadows = castShadows; - brush->recvShadows = recvShadows; - brush->lightmapSampleSize = lightmapSampleSize; - brush->lightmapScale = lightmapScale; - brush->celShader = celShader; - brush->shadeAngleDegrees = shadeAngle; - } - - for( patch = mapEnt->patches; patch != NULL; patch = patch->next ) - { - patch->entityNum = mapEnt->mapEntityNum; - patch->castShadows = castShadows; - patch->recvShadows = recvShadows; - patch->lightmapSampleSize = lightmapSampleSize; - patch->lightmapScale = lightmapScale; - patch->celShader = celShader; - } - - /* ydnar: gs mods: set entity bounds */ - SetEntityBounds( mapEnt ); - - /* ydnar: gs mods: load shader index map (equivalent to old terrain alphamap) */ - LoadEntityIndexMap( mapEnt ); - - /* get entity origin and adjust brushes */ - GetVectorForKey( mapEnt, "origin", mapEnt->origin ); - if( mapEnt->originbrush_origin[ 0 ] || mapEnt->originbrush_origin[ 1 ] || mapEnt->originbrush_origin[ 2 ] ) - AdjustBrushesForOrigin( mapEnt ); - - /* group_info entities are just for editor grouping (fixme: leak!) */ - if( !noCollapseGroups && !Q_stricmp( "group_info", classname ) ) - { - numEntities--; - return qtrue; - } - - /* group entities are just for editor convenience, toss all brushes into worldspawn */ - if( !noCollapseGroups && funcGroup ) - { - MoveBrushesToWorld( mapEnt ); - numEntities--; - return qtrue; - } - - /* done */ - return qtrue; -} - - - -/* -LoadMapFile() -loads a map file into a list of entities -*/ - -void LoadMapFile( char *filename, qboolean onlyLights, qboolean noCollapseGroups ) -{ - FILE *file; - brush_t *b; - int oldNumEntities = 0, numMapBrushes; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- LoadMapFile ---\n" ); - Sys_Printf( "Loading %s\n", filename ); - - /* hack */ - file = SafeOpenRead( filename ); - fclose( file ); - - /* load the map file */ - LoadScriptFile( filename, -1 ); - - /* setup */ - if( onlyLights ) - oldNumEntities = numEntities; - else - numEntities = 0; - - /* initial setup */ - numMapDrawSurfs = 0; - c_detail = 0; - g_bBrushPrimit = BPRIMIT_UNDEFINED; - - /* allocate a very large temporary brush for building the brushes as they are loaded */ - buildBrush = AllocBrush( MAX_BUILD_SIDES ); - - /* parse the map file */ - while( ParseMapEntity( onlyLights, noCollapseGroups ) ); - - /* light loading */ - if( onlyLights ) - { - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d light entities\n", numEntities - oldNumEntities ); - } - else - { - /* set map bounds */ - ClearBounds( mapMins, mapMaxs ); - for( b = entities[ 0 ].brushes; b; b = b->next ) - { - AddPointToBounds( b->mins, mapMins, mapMaxs ); - AddPointToBounds( b->maxs, mapMins, mapMaxs ); - } - - /* get brush counts */ - numMapBrushes = CountBrushList( entities[ 0 ].brushes ); - if( (float) c_detail / (float) numMapBrushes < 0.10f && numMapBrushes > 500 ) - Sys_Printf( "WARNING: Over 90 percent structural map detected. Compile time may be adversely affected.\n" ); - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d total world brushes\n", numMapBrushes ); - Sys_FPrintf( SYS_VRB, "%9d detail brushes\n", c_detail ); - Sys_FPrintf( SYS_VRB, "%9d patches\n", numMapPatches); - Sys_FPrintf( SYS_VRB, "%9d boxbevels\n", c_boxbevels); - Sys_FPrintf( SYS_VRB, "%9d edgebevels\n", c_edgebevels); - Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities ); - Sys_FPrintf( SYS_VRB, "%9d planes\n", nummapplanes); - Sys_Printf( "%9d areaportals\n", c_areaportals); - Sys_Printf( "Size: %5.0f, %5.0f, %5.0f to %5.0f, %5.0f, %5.0f\n", - mapMins[ 0 ], mapMins[ 1 ], mapMins[ 2 ], - mapMaxs[ 0 ], mapMaxs[ 1 ], mapMaxs[ 2 ]); - - /* write bogus map */ - if( fakemap ) - WriteBSPBrushMap( "fakemap.map", entities[ 0 ].brushes ); - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/mesh.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/mesh.c deleted file mode 100644 index 288525cf..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/mesh.c +++ /dev/null @@ -1,826 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define MESH_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -LerpDrawVert() -returns an 50/50 interpolated vert -*/ - -void LerpDrawVert( bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *out ) -{ - int k; - - - out->xyz[ 0 ] = 0.5 * (a->xyz[ 0 ] + b->xyz[ 0 ]); - out->xyz[ 1 ] = 0.5 * (a->xyz[ 1 ] + b->xyz[ 1 ]); - out->xyz[ 2 ] = 0.5 * (a->xyz[ 2 ] + b->xyz[ 2 ]); - - out->st[ 0 ] = 0.5 * (a->st[ 0 ] + b->st[ 0 ]); - out->st[ 1 ] = 0.5 * (a->st[ 1 ] + b->st[ 1 ]); - - for( k = 0; k < MAX_LIGHTMAPS; k++ ) - { - out->lightmap[ k ][ 0 ] = 0.5f * (a->lightmap[ k ][ 0 ] + b->lightmap[ k ][ 0 ]); - out->lightmap[ k ][ 1 ] = 0.5f * (a->lightmap[ k ][ 1 ] + b->lightmap[ k ][ 1 ]); - out->color[ k ][ 0 ] = (a->color[ k ][ 0 ] + b->color[ k ][ 0 ]) >> 1; - out->color[ k ][ 1 ] = (a->color[ k ][ 1 ] + b->color[ k ][ 1 ]) >> 1; - out->color[ k ][ 2 ] = (a->color[ k ][ 2 ] + b->color[ k ][ 2 ]) >> 1; - out->color[ k ][ 3 ] = (a->color[ k ][ 3 ] + b->color[ k ][ 3 ]) >> 1; - } - - /* ydnar: added normal interpolation */ - out->normal[ 0 ] = 0.5f * (a->normal[ 0 ] + b->normal[ 0 ]); - out->normal[ 1 ] = 0.5f * (a->normal[ 1 ] + b->normal[ 1 ]); - out->normal[ 2 ] = 0.5f * (a->normal[ 2 ] + b->normal[ 2 ]); - - /* if the interpolant created a bogus normal, just copy the normal from a */ - if( VectorNormalize( out->normal, out->normal ) == 0 ) - VectorCopy( a->normal, out->normal ); -} - - - -/* -LerpDrawVertAmount() -returns a biased interpolated vert -*/ - -void LerpDrawVertAmount( bspDrawVert_t *a, bspDrawVert_t *b, float amount, bspDrawVert_t *out ) -{ - int k; - - - out->xyz[ 0 ] = a->xyz[ 0 ] + amount * (b->xyz[ 0 ] - a->xyz[ 0 ]); - out->xyz[ 1 ] = a->xyz[ 1 ] + amount * (b->xyz[ 1 ] - a->xyz[ 1 ]); - out->xyz[ 2 ] = a->xyz[ 2 ] + amount * (b->xyz[ 2 ] - a->xyz[ 2 ]); - - out->st[ 0 ] = a->st[ 0 ] + amount * (b->st[ 0 ] - a->st[ 0 ]); - out->st[ 1 ] = a->st[ 1 ] + amount * (b->st[ 1 ] - a->st[ 1 ]); - - for( k = 0; k < MAX_LIGHTMAPS; k++ ) - { - out->lightmap[ k ][ 0 ] = a->lightmap[ k ][ 0 ] + amount * (b->lightmap[ k ][ 0 ] - a->lightmap[ k ][ 0 ]); - out->lightmap[ k ][ 1 ] = a->lightmap[ k ][ 1 ] + amount * (b->lightmap[ k ][ 1 ] - a->lightmap[ k ][ 1 ]); - out->color[ k ][ 0 ] = a->color[ k ][ 0 ] + amount * (b->color[ k ][ 0 ] - a->color[ k ][ 0 ]); - out->color[ k ][ 1 ] = a->color[ k ][ 1 ] + amount * (b->color[ k ][ 1 ] - a->color[ k ][ 1 ]); - out->color[ k ][ 2 ] = a->color[ k ][ 2 ] + amount * (b->color[ k ][ 2 ] - a->color[ k ][ 2 ]); - out->color[ k ][ 3 ] = a->color[ k ][ 3 ] + amount * (b->color[ k ][ 3 ] - a->color[ k ][ 3 ]); - } - - out->normal[ 0 ] = a->normal[ 0 ] + amount * (b->normal[ 0 ] - a->normal[ 0 ]); - out->normal[ 1 ] = a->normal[ 1 ] + amount * (b->normal[ 1 ] - a->normal[ 1 ]); - out->normal[ 2 ] = a->normal[ 2 ] + amount * (b->normal[ 2 ] - a->normal[ 2 ]); - - /* if the interpolant created a bogus normal, just copy the normal from a */ - if( VectorNormalize( out->normal, out->normal ) == 0 ) - VectorCopy( a->normal, out->normal ); -} - - -void FreeMesh( mesh_t *m ) { - free( m->verts ); - free( m ); -} - -void PrintMesh( mesh_t *m ) { - int i, j; - - for ( i = 0 ; i < m->height ; i++ ) { - for ( j = 0 ; j < m->width ; j++ ) { - Sys_Printf("(%5.2f %5.2f %5.2f) " - , m->verts[i*m->width+j].xyz[0] - , m->verts[i*m->width+j].xyz[1] - , m->verts[i*m->width+j].xyz[2] ); - } - Sys_Printf("\n"); - } -} - - -mesh_t *CopyMesh( mesh_t *mesh ) { - mesh_t *out; - int size; - - out = safe_malloc( sizeof( *out ) ); - out->width = mesh->width; - out->height = mesh->height; - - size = out->width * out->height * sizeof( *out->verts ); - out->verts = safe_malloc( size ); - memcpy( out->verts, mesh->verts, size ); - - return out; -} - - -/* -TransposeMesh() -returns a transposed copy of the mesh, freeing the original -*/ - -mesh_t *TransposeMesh( mesh_t *in ) { - int w, h; - mesh_t *out; - - out = safe_malloc( sizeof( *out ) ); - out->width = in->height; - out->height = in->width; - out->verts = safe_malloc( out->width * out->height * sizeof( bspDrawVert_t ) ); - - for ( h = 0 ; h < in->height ; h++ ) { - for ( w = 0 ; w < in->width ; w++ ) { - out->verts[ w * in->height + h ] = in->verts[ h * in->width + w ]; - } - } - - FreeMesh( in ); - - return out; -} - -void InvertMesh( mesh_t *in ) { - int w, h; - bspDrawVert_t temp; - - for ( h = 0 ; h < in->height ; h++ ) { - for ( w = 0 ; w < in->width / 2 ; w++ ) { - temp = in->verts[ h * in->width + w ]; - in->verts[ h * in->width + w ] = in->verts[ h * in->width + in->width - 1 - w ]; - in->verts[ h * in->width + in->width - 1 - w ] = temp; - } - } -} - -/* -================= -MakeMeshNormals - -================= -*/ -void MakeMeshNormals( mesh_t in ) -{ - int i, j, k, dist; - vec3_t normal; - vec3_t sum; - int count; - vec3_t base; - vec3_t delta; - int x, y; - bspDrawVert_t *dv; - vec3_t around[8], temp; - qboolean good[8]; - qboolean wrapWidth, wrapHeight; - float len; - int neighbors[8][2] = - { - {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} - }; - - - wrapWidth = qfalse; - for ( i = 0 ; i < in.height ; i++ ) { - VectorSubtract( in.verts[i*in.width].xyz, - in.verts[i*in.width+in.width-1].xyz, delta ); - len = VectorLength( delta ); - if ( len > 1.0 ) { - break; - } - } - if ( i == in.height ) { - wrapWidth = qtrue; - } - - wrapHeight = qfalse; - for ( i = 0 ; i < in.width ; i++ ) { - VectorSubtract( in.verts[i].xyz, - in.verts[i + (in.height-1)*in.width].xyz, delta ); - len = VectorLength( delta ); - if ( len > 1.0 ) { - break; - } - } - if ( i == in.width) { - wrapHeight = qtrue; - } - - - for ( i = 0 ; i < in.width ; i++ ) { - for ( j = 0 ; j < in.height ; j++ ) { - count = 0; - dv = &in.verts[j*in.width+i]; - VectorCopy( dv->xyz, base ); - for ( k = 0 ; k < 8 ; k++ ) { - VectorClear( around[k] ); - good[k] = qfalse; - - for ( dist = 1 ; dist <= 3 ; dist++ ) { - x = i + neighbors[k][0] * dist; - y = j + neighbors[k][1] * dist; - if ( wrapWidth ) { - if ( x < 0 ) { - x = in.width - 1 + x; - } else if ( x >= in.width ) { - x = 1 + x - in.width; - } - } - if ( wrapHeight ) { - if ( y < 0 ) { - y = in.height - 1 + y; - } else if ( y >= in.height ) { - y = 1 + y - in.height; - } - } - - if ( x < 0 || x >= in.width || y < 0 || y >= in.height ) { - break; // edge of patch - } - VectorSubtract( in.verts[y*in.width+x].xyz, base, temp ); - if ( VectorNormalize( temp, temp ) == 0 ) { - continue; // degenerate edge, get more dist - } else { - good[k] = qtrue; - VectorCopy( temp, around[k] ); - break; // good edge - } - } - } - - VectorClear( sum ); - for ( k = 0 ; k < 8 ; k++ ) { - if ( !good[k] || !good[(k+1)&7] ) { - continue; // didn't get two points - } - CrossProduct( around[(k+1)&7], around[k], normal ); - if ( VectorNormalize( normal, normal ) == 0 ) { - continue; - } - VectorAdd( normal, sum, sum ); - count++; - } - if ( count == 0 ) { -//Sys_Printf("bad normal\n"); - count = 1; - } - VectorNormalize( sum, dv->normal ); - } - } -} - -/* -PutMeshOnCurve() -drops the aproximating points onto the curve -ydnar: fixme: make this use LerpDrawVert() rather than this complicated mess -*/ - -void PutMeshOnCurve( mesh_t in ) { - int i, j, l, m; - float prev, next; - - - // put all the aproximating points on the curve - for ( i = 0 ; i < in.width ; i++ ) { - for ( j = 1 ; j < in.height ; j += 2 ) { - for ( l = 0 ; l < 3 ; l++ ) { - prev = ( in.verts[j*in.width+i].xyz[l] + in.verts[(j+1)*in.width+i].xyz[l] ) * 0.5; - next = ( in.verts[j*in.width+i].xyz[l] + in.verts[(j-1)*in.width+i].xyz[l] ) * 0.5; - in.verts[j*in.width+i].xyz[l] = ( prev + next ) * 0.5; - - /* ydnar: interpolating st coords */ - if( l < 2 ) - { - prev = ( in.verts[j*in.width+i].st[l] + in.verts[(j+1)*in.width+i].st[l] ) * 0.5; - next = ( in.verts[j*in.width+i].st[l] + in.verts[(j-1)*in.width+i].st[l] ) * 0.5; - in.verts[j*in.width+i].st[l] = ( prev + next ) * 0.5; - - for( m = 0; m < MAX_LIGHTMAPS; m++ ) - { - prev = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[(j+1)*in.width+i].lightmap[ m ][l] ) * 0.5; - next = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[(j-1)*in.width+i].lightmap[ m ][l] ) * 0.5; - in.verts[j*in.width+i].lightmap[ m ][l] = ( prev + next ) * 0.5; - } - } - } - } - } - - for ( j = 0 ; j < in.height ; j++ ) { - for ( i = 1 ; i < in.width ; i += 2 ) { - for ( l = 0 ; l < 3 ; l++ ) { - prev = ( in.verts[j*in.width+i].xyz[l] + in.verts[j*in.width+i+1].xyz[l] ) * 0.5; - next = ( in.verts[j*in.width+i].xyz[l] + in.verts[j*in.width+i-1].xyz[l] ) * 0.5; - in.verts[j*in.width+i].xyz[l] = ( prev + next ) * 0.5; - - /* ydnar: interpolating st coords */ - if( l < 2 ) - { - prev = ( in.verts[j*in.width+i].st[l] + in.verts[j*in.width+i+1].st[l] ) * 0.5; - next = ( in.verts[j*in.width+i].st[l] + in.verts[j*in.width+i-1].st[l] ) * 0.5; - in.verts[j*in.width+i].st[l] = ( prev + next ) * 0.5; - - for( m = 0; m < MAX_LIGHTMAPS; m++ ) - { - prev = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[j*in.width+i+1].lightmap[ m ][l] ) * 0.5; - next = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[j*in.width+i-1].lightmap[ m ][l] ) * 0.5; - in.verts[j*in.width+i].lightmap[ m ][l] = ( prev + next ) * 0.5; - } - } - } - } - } -} - - -/* -================= -SubdivideMesh - -================= -*/ -mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ) -{ - int i, j, k, l; - bspDrawVert_t prev, next, mid; - vec3_t prevxyz, nextxyz, midxyz; - vec3_t delta; - float len; - mesh_t out; - - /* ydnar: static for os x */ - MAC_STATIC bspDrawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS]; - - - out.width = in.width; - out.height = in.height; - - for ( i = 0 ; i < in.width ; i++ ) { - for ( j = 0 ; j < in.height ; j++ ) { - expand[j][i] = in.verts[j*in.width+i]; - } - } - - // horizontal subdivisions - for ( j = 0 ; j + 2 < out.width ; j += 2 ) { - // check subdivided midpoints against control points - for ( i = 0 ; i < out.height ; i++ ) { - for ( l = 0 ; l < 3 ; l++ ) { - prevxyz[l] = expand[i][j+1].xyz[l] - expand[i][j].xyz[l]; - nextxyz[l] = expand[i][j+2].xyz[l] - expand[i][j+1].xyz[l]; - midxyz[l] = (expand[i][j].xyz[l] + expand[i][j+1].xyz[l] * 2 - + expand[i][j+2].xyz[l] ) * 0.25; - } - - // if the span length is too long, force a subdivision - if ( VectorLength( prevxyz ) > minLength - || VectorLength( nextxyz ) > minLength ) { - break; - } - - // see if this midpoint is off far enough to subdivide - VectorSubtract( expand[i][j+1].xyz, midxyz, delta ); - len = VectorLength( delta ); - if ( len > maxError ) { - break; - } - } - - if ( out.width + 2 >= MAX_EXPANDED_AXIS ) { - break; // can't subdivide any more - } - - if ( i == out.height ) { - continue; // didn't need subdivision - } - - // insert two columns and replace the peak - out.width += 2; - - for ( i = 0 ; i < out.height ; i++ ) { - LerpDrawVert( &expand[i][j], &expand[i][j+1], &prev ); - LerpDrawVert( &expand[i][j+1], &expand[i][j+2], &next ); - LerpDrawVert( &prev, &next, &mid ); - - for ( k = out.width - 1 ; k > j + 3 ; k-- ) { - expand[i][k] = expand[i][k-2]; - } - expand[i][j + 1] = prev; - expand[i][j + 2] = mid; - expand[i][j + 3] = next; - } - - // back up and recheck this set again, it may need more subdivision - j -= 2; - - } - - // vertical subdivisions - for ( j = 0 ; j + 2 < out.height ; j += 2 ) { - // check subdivided midpoints against control points - for ( i = 0 ; i < out.width ; i++ ) { - for ( l = 0 ; l < 3 ; l++ ) { - prevxyz[l] = expand[j+1][i].xyz[l] - expand[j][i].xyz[l]; - nextxyz[l] = expand[j+2][i].xyz[l] - expand[j+1][i].xyz[l]; - midxyz[l] = (expand[j][i].xyz[l] + expand[j+1][i].xyz[l] * 2 - + expand[j+2][i].xyz[l] ) * 0.25; - } - - // if the span length is too long, force a subdivision - if ( VectorLength( prevxyz ) > minLength - || VectorLength( nextxyz ) > minLength ) { - break; - } - // see if this midpoint is off far enough to subdivide - VectorSubtract( expand[j+1][i].xyz, midxyz, delta ); - len = VectorLength( delta ); - if ( len > maxError ) { - break; - } - } - - if ( out.height + 2 >= MAX_EXPANDED_AXIS ) { - break; // can't subdivide any more - } - - if ( i == out.width ) { - continue; // didn't need subdivision - } - - // insert two columns and replace the peak - out.height += 2; - - for ( i = 0 ; i < out.width ; i++ ) { - LerpDrawVert( &expand[j][i], &expand[j+1][i], &prev ); - LerpDrawVert( &expand[j+1][i], &expand[j+2][i], &next ); - LerpDrawVert( &prev, &next, &mid ); - - for ( k = out.height - 1 ; k > j + 3 ; k-- ) { - expand[k][i] = expand[k-2][i]; - } - expand[j+1][i] = prev; - expand[j+2][i] = mid; - expand[j+3][i] = next; - } - - // back up and recheck this set again, it may need more subdivision - j -= 2; - - } - - // collapse the verts - - out.verts = &expand[0][0]; - for ( i = 1 ; i < out.height ; i++ ) { - memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(bspDrawVert_t) ); - } - - return CopyMesh(&out); -} - - - -/* -IterationsForCurve() - ydnar -given a curve of a certain length, return the number of subdivision iterations -note: this is affected by subdivision amount -*/ - -int IterationsForCurve( float len, int subdivisions ) -{ - int iterations, facets; - - - /* calculate the number of subdivisions */ - for( iterations = 0; iterations < 3; iterations++ ) - { - facets = subdivisions * 16 * pow( 2, iterations ); - if( facets >= len ) - break; - } - - /* return to caller */ - return iterations; -} - - -/* -SubdivideMesh2() - ydnar -subdivides each mesh quad a specified number of times -*/ - -mesh_t *SubdivideMesh2( mesh_t in, int iterations ) -{ - int i, j, k; - bspDrawVert_t prev, next, mid; - mesh_t out; - - /* ydnar: static for os x */ - MAC_STATIC bspDrawVert_t expand[ MAX_EXPANDED_AXIS ][ MAX_EXPANDED_AXIS ]; - - - /* initial setup */ - out.width = in.width; - out.height = in.height; - for( i = 0; i < in.width; i++ ) - { - for( j = 0; j < in.height; j++ ) - expand[ j ][ i ] = in.verts[ j * in.width + i ]; - } - - /* keep chopping */ - for( ; iterations > 0; iterations-- ) - { - /* horizontal subdivisions */ - for( j = 0; j + 2 < out.width; j += 4 ) - { - /* check size limit */ - if( out.width + 2 >= MAX_EXPANDED_AXIS ) - break; - - /* insert two columns and replace the peak */ - out.width += 2; - for( i = 0; i < out.height; i++ ) - { - LerpDrawVert( &expand[ i ][ j ], &expand[ i ][ j + 1 ], &prev ); - LerpDrawVert( &expand[ i ][ j + 1 ], &expand[ i ][ j + 2 ], &next ); - LerpDrawVert( &prev, &next, &mid ); - - for ( k = out.width - 1 ; k > j + 3; k-- ) - expand [ i ][ k ] = expand[ i ][ k - 2 ]; - expand[ i ][ j + 1 ] = prev; - expand[ i ][ j + 2 ] = mid; - expand[ i ][ j + 3 ] = next; - } - - } - - /* vertical subdivisions */ - for ( j = 0; j + 2 < out.height; j += 4 ) - { - /* check size limit */ - if( out.height + 2 >= MAX_EXPANDED_AXIS ) - break; - - /* insert two columns and replace the peak */ - out.height += 2; - for( i = 0; i < out.width; i++ ) - { - LerpDrawVert( &expand[ j ][ i ], &expand[ j + 1 ][ i ], &prev ); - LerpDrawVert( &expand[ j + 1 ][ i ], &expand[ j + 2 ][ i ], &next ); - LerpDrawVert( &prev, &next, &mid ); - - for( k = out.height - 1; k > j + 3; k-- ) - expand[ k ][ i ] = expand[ k - 2 ][ i ]; - expand[ j + 1 ][ i ] = prev; - expand[ j + 2 ][ i ] = mid; - expand[ j + 3 ][ i ] = next; - } - } - } - - /* collapse the verts */ - out.verts = &expand[ 0 ][ 0 ]; - for( i = 1; i < out.height; i++ ) - memmove( &out.verts[ i * out.width ], expand[ i ], out.width * sizeof( bspDrawVert_t ) ); - - /* return to sender */ - return CopyMesh( &out ); -} - - - - - - - -/* -================ -ProjectPointOntoVector -================ -*/ -void ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj ) -{ - vec3_t pVec, vec; - - VectorSubtract( point, vStart, pVec ); - VectorSubtract( vEnd, vStart, vec ); - VectorNormalize( vec, vec ); - // project onto the directional vector for this segment - VectorMA( vStart, DotProduct( pVec, vec ), vec, vProj ); -} - -/* -================ -RemoveLinearMeshColumsRows -================ -*/ -mesh_t *RemoveLinearMeshColumnsRows( mesh_t *in ) { - int i, j, k; - float len, maxLength; - vec3_t proj, dir; - mesh_t out; - - /* ydnar: static for os x */ - MAC_STATIC bspDrawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS]; - - - out.width = in->width; - out.height = in->height; - - for ( i = 0 ; i < in->width ; i++ ) { - for ( j = 0 ; j < in->height ; j++ ) { - expand[j][i] = in->verts[j*in->width+i]; - } - } - - for ( j = 1 ; j < out.width - 1; j++ ) { - maxLength = 0; - for ( i = 0 ; i < out.height ; i++ ) { - ProjectPointOntoVector(expand[i][j].xyz, expand[i][j-1].xyz, expand[i][j+1].xyz, proj); - VectorSubtract(expand[i][j].xyz, proj, dir); - len = VectorLength(dir); - if (len > maxLength) { - maxLength = len; - } - } - if (maxLength < 0.1) - { - out.width--; - for ( i = 0 ; i < out.height ; i++ ) { - for (k = j; k < out.width; k++) { - expand[i][k] = expand[i][k+1]; - } - } - j--; - } - } - for ( j = 1 ; j < out.height - 1; j++ ) { - maxLength = 0; - for ( i = 0 ; i < out.width ; i++ ) { - ProjectPointOntoVector(expand[j][i].xyz, expand[j-1][i].xyz, expand[j+1][i].xyz, proj); - VectorSubtract(expand[j][i].xyz, proj, dir); - len = VectorLength(dir); - if (len > maxLength) { - maxLength = len; - } - } - if (maxLength < 0.1) - { - out.height--; - for ( i = 0 ; i < out.width ; i++ ) { - for (k = j; k < out.height; k++) { - expand[k][i] = expand[k+1][i]; - } - } - j--; - } - } - // collapse the verts - out.verts = &expand[0][0]; - for ( i = 1 ; i < out.height ; i++ ) { - memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(bspDrawVert_t) ); - } - - return CopyMesh(&out); -} - - - -/* -================= -SubdivideMeshQuads -================= -*/ -mesh_t *SubdivideMeshQuads( mesh_t *in, float minLength, int maxsize, int *widthtable, int *heighttable ) -{ - int i, j, k, w, h, maxsubdivisions, subdivisions; - vec3_t dir; - float length, maxLength, amount; - mesh_t out; - bspDrawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS]; - - out.width = in->width; - out.height = in->height; - - for ( i = 0 ; i < in->width ; i++ ) { - for ( j = 0 ; j < in->height ; j++ ) { - expand[j][i] = in->verts[j*in->width+i]; - } - } - - if (maxsize > MAX_EXPANDED_AXIS) - Error("SubdivideMeshQuads: maxsize > MAX_EXPANDED_AXIS"); - - // horizontal subdivisions - - maxsubdivisions = (maxsize - in->width) / (in->width - 1); - - for ( w = 0, j = 0 ; w < in->width - 1; w++, j += subdivisions + 1) { - maxLength = 0; - for ( i = 0 ; i < out.height ; i++ ) { - VectorSubtract(expand[i][j+1].xyz, expand[i][j].xyz, dir); - length = VectorLength( dir ); - if (length > maxLength) { - maxLength = length; - } - } - - subdivisions = (int) (maxLength / minLength); - if (subdivisions > maxsubdivisions) - subdivisions = maxsubdivisions; - - widthtable[w] = subdivisions + 1; - if (subdivisions <= 0) - continue; - - out.width += subdivisions; - - for ( i = 0 ; i < out.height ; i++ ) { - for ( k = out.width - 1 ; k > j + subdivisions; k-- ) { - expand[i][k] = expand[i][k-subdivisions]; - } - for (k = 1; k <= subdivisions; k++) - { - amount = (float) k / (subdivisions + 1); - LerpDrawVertAmount(&expand[i][j], &expand[i][j+subdivisions+1], amount, &expand[i][j+k]); - } - } - } - - maxsubdivisions = (maxsize - in->height) / (in->height - 1); - - for ( h = 0, j = 0 ; h < in->height - 1; h++, j += subdivisions + 1) { - maxLength = 0; - for ( i = 0 ; i < out.width ; i++ ) { - VectorSubtract(expand[j+1][i].xyz, expand[j][i].xyz, dir); - length = VectorLength( dir ); - if (length > maxLength) { - maxLength = length; - } - } - - subdivisions = (int) (maxLength / minLength); - if (subdivisions > maxsubdivisions) - subdivisions = maxsubdivisions; - - heighttable[h] = subdivisions + 1; - if (subdivisions <= 0) - continue; - - out.height += subdivisions; - - for ( i = 0 ; i < out.width ; i++ ) { - for ( k = out.height - 1 ; k > j + subdivisions; k-- ) { - expand[k][i] = expand[k-subdivisions][i]; - } - for (k = 1; k <= subdivisions; k++) - { - amount = (float) k / (subdivisions + 1); - LerpDrawVertAmount(&expand[j][i], &expand[j+subdivisions+1][i], amount, &expand[j+k][i]); - } - } - } - - // collapse the verts - out.verts = &expand[0][0]; - for ( i = 1 ; i < out.height ; i++ ) { - memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(bspDrawVert_t) ); - } - - return CopyMesh(&out); -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/model.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/model.c deleted file mode 100644 index a56134c8..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/model.c +++ /dev/null @@ -1,904 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define MODEL_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -PicoPrintFunc() -callback for picomodel.lib -*/ - -void PicoPrintFunc( int level, const char *str ) -{ - if( str == NULL ) - return; - switch( level ) - { - case PICO_NORMAL: - Sys_Printf( "%s\n", str ); - break; - - case PICO_VERBOSE: - Sys_FPrintf( SYS_VRB, "%s\n", str ); - break; - - case PICO_WARNING: - Sys_Printf( "WARNING: %s\n", str ); - break; - - case PICO_ERROR: - Sys_Printf( "ERROR: %s\n", str ); - break; - - case PICO_FATAL: - Error( "ERROR: %s\n", str ); - break; - } -} - - - -/* -PicoLoadFileFunc() -callback for picomodel.lib -*/ - -void PicoLoadFileFunc( const char *name, byte **buffer, int *bufSize ) -{ - *bufSize = vfsLoadFile( name, (void**) buffer, 0 ); -} - - - -/* -FindModel() - ydnar -finds an existing picoModel and returns a pointer to the picoModel_t struct or NULL if not found -*/ - -picoModel_t *FindModel( const char *name, int frame ) -{ - int i; - - - /* init */ - if( numPicoModels <= 0 ) - memset( picoModels, 0, sizeof( picoModels ) ); - - /* dummy check */ - if( name == NULL || name[ 0 ] == '\0' ) - return NULL; - - /* search list */ - for( i = 0; i < MAX_MODELS; i++ ) - { - if( picoModels[ i ] != NULL && - !strcmp( PicoGetModelName( picoModels[ i ] ), name ) && - PicoGetModelFrameNum( picoModels[ i ] ) == frame ) - return picoModels[ i ]; - } - - /* no matching picoModel found */ - return NULL; -} - - - -/* -LoadModel() - ydnar -loads a picoModel and returns a pointer to the picoModel_t struct or NULL if not found -*/ - -picoModel_t *LoadModel( const char *name, int frame ) -{ - int i; - picoModel_t *model, **pm; - - - /* init */ - if( numPicoModels <= 0 ) - memset( picoModels, 0, sizeof( picoModels ) ); - - /* dummy check */ - if( name == NULL || name[ 0 ] == '\0' ) - return NULL; - - /* try to find existing picoModel */ - model = FindModel( name, frame ); - if( model != NULL ) - return model; - - /* none found, so find first non-null picoModel */ - pm = NULL; - for( i = 0; i < MAX_MODELS; i++ ) - { - if( picoModels[ i ] == NULL ) - { - pm = &picoModels[ i ]; - break; - } - } - - /* too many picoModels? */ - if( pm == NULL ) - Error( "MAX_MODELS (%d) exceeded, there are too many model files referenced by the map.", MAX_MODELS ); - - /* attempt to parse model */ - *pm = PicoLoadModel( name, frame ); - - /* if loading failed, make a bogus model to silence the rest of the warnings */ - if( *pm == NULL ) - { - /* allocate a new model */ - *pm = PicoNewModel(); - if( *pm == NULL ) - return NULL; - - /* set data */ - PicoSetModelName( *pm, name ); - PicoSetModelFrameNum( *pm, frame ); - } - - /* debug code */ - #if 0 - { - int numSurfaces, numVertexes; - picoSurface_t *ps; - - - Sys_Printf( "Model %s\n", name ); - numSurfaces = PicoGetModelNumSurfaces( *pm ); - for( i = 0; i < numSurfaces; i++ ) - { - ps = PicoGetModelSurface( *pm, i ); - numVertexes = PicoGetSurfaceNumVertexes( ps ); - Sys_Printf( "Surface %d has %d vertexes\n", i, numVertexes ); - } - } - #endif - - /* set count */ - if( *pm != NULL ) - numPicoModels++; - - /* return the picoModel */ - return *pm; -} - - - -/* -InsertModel() - ydnar -adds a picomodel into the bsp -*/ - -void InsertModel( const char *name, int skin, int frame, m4x4_t transform, remap_t *remap, shaderInfo_t *celShader, int eNum, int castShadows, int recvShadows, int spawnFlags, float lightmapScale, int lightmapSampleSize, float shadeAngle ) -{ - int i, j, k, s, numSurfaces; - m4x4_t identity, nTransform; - picoModel_t *model; - picoShader_t *shader; - picoSurface_t *surface; - shaderInfo_t *si; - mapDrawSurface_t *ds; - bspDrawVert_t *dv; - char *picoShaderName; - char shaderName[ MAX_QPATH ]; - picoVec_t *xyz, *normal, *st; - byte *color; - picoIndex_t *indexes; - remap_t *rm, *glob; - skinfile_t *sf, *sf2; - double normalEpsilon_save; - double distanceEpsilon_save; - char skinfilename[ MAX_QPATH ]; - char *skinfilecontent; - int skinfilesize; - char *skinfileptr, *skinfilenextptr; - - - /* get model */ - model = LoadModel( name, frame ); - if( model == NULL ) - return; - - /* load skin file */ - snprintf(skinfilename, sizeof(skinfilename), "%s_%d.skin", name, skin); - skinfilename[sizeof(skinfilename)-1] = 0; - skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0); - if(skinfilesize < 0 && skin != 0) - { - /* fallback to skin 0 if invalid */ - snprintf(skinfilename, sizeof(skinfilename), "%s_0.skin", name); - skinfilename[sizeof(skinfilename)-1] = 0; - skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0); - if(skinfilesize >= 0) - Sys_Printf( "Skin %d of %s does not exist, using 0 instead\n", skin, name ); - } - sf = NULL; - if(skinfilesize >= 0) - { - Sys_Printf( "Using skin %d of %s\n", skin, name ); - int pos; - for(skinfileptr = skinfilecontent; *skinfileptr; skinfileptr = skinfilenextptr) - { - // for fscanf - char format[64]; - - skinfilenextptr = strchr(skinfileptr, '\r'); - if(skinfilenextptr) - { - *skinfilenextptr++ = 0; - } - else - { - skinfilenextptr = strchr(skinfileptr, '\n'); - if(skinfilenextptr) - *skinfilenextptr++ = 0; - else - skinfilenextptr = skinfileptr + strlen(skinfileptr); - } - - /* create new item */ - sf2 = sf; - sf = safe_malloc( sizeof( *sf ) ); - sf->next = sf2; - - sprintf(format, "replace %%%ds %%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1); - if(sscanf(skinfileptr, format, sf->name, sf->to) == 2) - continue; - sprintf(format, " %%%d[^, ] ,%%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1); - if((pos = sscanf(skinfileptr, format, sf->name, sf->to)) == 2) - continue; - - /* invalid input line -> discard sf struct */ - Sys_Printf( "Discarding skin directive in %s: %s\n", skinfilename, skinfileptr ); - free(sf); - sf = sf2; - } - free(skinfilecontent); - } - - /* handle null matrix */ - if( transform == NULL ) - { - m4x4_identity( identity ); - transform = identity; - } - - /* hack: Stable-1_2 and trunk have differing row/column major matrix order - this transpose is necessary with Stable-1_2 - uncomment the following line with old m4x4_t (non 1.3/spog_branch) code */ - //% m4x4_transpose( transform ); - - /* create transform matrix for normals */ - memcpy( nTransform, transform, sizeof( m4x4_t ) ); - if( m4x4_invert( nTransform ) ) - Sys_FPrintf( SYS_VRB, "WARNING: Can't invert model transform matrix, using transpose instead\n" ); - m4x4_transpose( nTransform ); - - /* fix bogus lightmap scale */ - if( lightmapScale <= 0.0f ) - lightmapScale = 1.0f; - - /* fix bogus shade angle */ - if( shadeAngle <= 0.0f ) - shadeAngle = 0.0f; - - /* each surface on the model will become a new map drawsurface */ - numSurfaces = PicoGetModelNumSurfaces( model ); - //% Sys_FPrintf( SYS_VRB, "Model %s has %d surfaces\n", name, numSurfaces ); - for( s = 0; s < numSurfaces; s++ ) - { - /* get surface */ - surface = PicoGetModelSurface( model, s ); - if( surface == NULL ) - continue; - - /* only handle triangle surfaces initially (fixme: support patches) */ - if( PicoGetSurfaceType( surface ) != PICO_TRIANGLES ) - continue; - - /* allocate a surface (ydnar: gs mods) */ - ds = AllocDrawSurface( SURFACE_TRIANGLES ); - ds->entityNum = eNum; - ds->castShadows = castShadows; - ds->recvShadows = recvShadows; - - /* get shader name */ - shader = PicoGetSurfaceShader( surface ); - if( shader == NULL ) - picoShaderName = ""; - else - picoShaderName = PicoGetShaderName( shader ); - - /* handle .skin file */ - if(sf) - { - picoShaderName = NULL; - for(sf2 = sf; sf2 != NULL; sf2 = sf2->next) - { - if( !Q_stricmp( surface->name, sf2->name ) ) - { - Sys_FPrintf( SYS_VRB, "Skin file: mapping %s to %s\n", surface->name, sf2->to ); - picoShaderName = sf2->to; - break; - } - } - if(!picoShaderName) - { - Sys_FPrintf( SYS_VRB, "Skin file: not mapping %s\n", surface->name ); - continue; - } - } - - /* handle shader remapping */ - glob = NULL; - for( rm = remap; rm != NULL; rm = rm->next ) - { - if( rm->from[ 0 ] == '*' && rm->from[ 1 ] == '\0' ) - glob = rm; - else if( !Q_stricmp( picoShaderName, rm->from ) ) - { - Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", picoShaderName, rm->to ); - picoShaderName = rm->to; - glob = NULL; - break; - } - } - - if( glob != NULL ) - { - Sys_FPrintf( SYS_VRB, "Globbing %s to %s\n", picoShaderName, glob->to ); - picoShaderName = glob->to; - } - - /* shader renaming for sof2 */ - if( renameModelShaders ) - { - strcpy( shaderName, picoShaderName ); - StripExtension( shaderName ); - if( spawnFlags & 1 ) - strcat( shaderName, "_RMG_BSP" ); - else - strcat( shaderName, "_BSP" ); - si = ShaderInfoForShader( shaderName ); - } - else - si = ShaderInfoForShader( picoShaderName ); - - /* set shader */ - ds->shaderInfo = si; - - /* force to meta? */ - if( (si != NULL && si->forceMeta) || (spawnFlags & 4) ) /* 3rd bit */ - ds->type = SURFACE_FORCED_META; - - /* fix the surface's normals (jal: conditioned by shader info) */ - if( !(spawnFlags & 64) && ( shadeAngle == 0.0f || ds->type != SURFACE_FORCED_META ) ) - PicoFixSurfaceNormals( surface ); - - /* set sample size */ - if( lightmapSampleSize > 0.0f ) - ds->sampleSize = lightmapSampleSize; - - /* set lightmap scale */ - if( lightmapScale > 0.0f ) - ds->lightmapScale = lightmapScale; - - /* set shading angle */ - if( shadeAngle > 0.0f ) - ds->shadeAngleDegrees = shadeAngle; - - /* set particulars */ - ds->numVerts = PicoGetSurfaceNumVertexes( surface ); - ds->verts = safe_malloc( ds->numVerts * sizeof( ds->verts[ 0 ] ) ); - memset( ds->verts, 0, ds->numVerts * sizeof( ds->verts[ 0 ] ) ); - - ds->numIndexes = PicoGetSurfaceNumIndexes( surface ); - ds->indexes = safe_malloc( ds->numIndexes * sizeof( ds->indexes[ 0 ] ) ); - memset( ds->indexes, 0, ds->numIndexes * sizeof( ds->indexes[ 0 ] ) ); - - /* copy vertexes */ - for( i = 0; i < ds->numVerts; i++ ) - { - /* get vertex */ - dv = &ds->verts[ i ]; - - /* xyz and normal */ - xyz = PicoGetSurfaceXYZ( surface, i ); - VectorCopy( xyz, dv->xyz ); - m4x4_transform_point( transform, dv->xyz ); - - normal = PicoGetSurfaceNormal( surface, i ); - VectorCopy( normal, dv->normal ); - m4x4_transform_normal( nTransform, dv->normal ); - VectorNormalize( dv->normal, dv->normal ); - - /* ydnar: tek-fu celshading support for flat shaded shit */ - if( flat ) - { - dv->st[ 0 ] = si->stFlat[ 0 ]; - dv->st[ 1 ] = si->stFlat[ 1 ]; - } - - /* ydnar: gs mods: added support for explicit shader texcoord generation */ - else if( si->tcGen ) - { - /* project the texture */ - dv->st[ 0 ] = DotProduct( si->vecs[ 0 ], dv->xyz ); - dv->st[ 1 ] = DotProduct( si->vecs[ 1 ], dv->xyz ); - } - - /* normal texture coordinates */ - else - { - st = PicoGetSurfaceST( surface, 0, i ); - dv->st[ 0 ] = st[ 0 ]; - dv->st[ 1 ] = st[ 1 ]; - } - - /* set lightmap/color bits */ - color = PicoGetSurfaceColor( surface, 0, i ); - for( j = 0; j < MAX_LIGHTMAPS; j++ ) - { - dv->lightmap[ j ][ 0 ] = 0.0f; - dv->lightmap[ j ][ 1 ] = 0.0f; - if(spawnFlags & 32) // spawnflag 32: model color -> alpha hack - { - dv->color[ j ][ 0 ] = 255.0f; - dv->color[ j ][ 1 ] = 255.0f; - dv->color[ j ][ 2 ] = 255.0f; - dv->color[ j ][ 3 ] = RGBTOGRAY( color ); - } - else - { - dv->color[ j ][ 0 ] = color[ 0 ]; - dv->color[ j ][ 1 ] = color[ 1 ]; - dv->color[ j ][ 2 ] = color[ 2 ]; - dv->color[ j ][ 3 ] = color[ 3 ]; - } - } - } - - /* copy indexes */ - indexes = PicoGetSurfaceIndexes( surface, 0 ); - for( i = 0; i < ds->numIndexes; i++ ) - ds->indexes[ i ] = indexes[ i ]; - - /* set cel shader */ - ds->celShader = celShader; - - /* ydnar: giant hack land: generate clipping brushes for model triangles */ - if( si->clipModel || (spawnFlags & 2) ) /* 2nd bit */ - { - vec3_t points[ 4 ], backs[ 3 ]; - vec4_t plane, reverse, pa, pb, pc; - - - /* temp hack */ - if( !si->clipModel && !(si->compileFlags & C_SOLID) ) - continue; - - /* walk triangle list */ - for( i = 0; i < ds->numIndexes; i += 3 ) - { - /* overflow hack */ - AUTOEXPAND_BY_REALLOC(mapplanes, (nummapplanes+64) << 1, allocatedmapplanes, 1024); - - /* make points and back points */ - for( j = 0; j < 3; j++ ) - { - /* get vertex */ - dv = &ds->verts[ ds->indexes[ i + j ] ]; - - /* copy xyz */ - VectorCopy( dv->xyz, points[ j ] ); - } - - VectorCopy( points[0], points[3] ); // for cyclic usage - - /* make plane for triangle */ - // div0: add some extra spawnflags: - // 0: snap normals to axial planes for extrusion - // 8: extrude with the original normals - // 16: extrude only with up/down normals (ideal for terrain) - // 24: extrude by distance zero (may need engine changes) - if( PlaneFromPoints( plane, points[ 0 ], points[ 1 ], points[ 2 ] ) ) - { - vec3_t bestNormal; - float backPlaneDistance = 2; - - if(spawnFlags & 8) // use a DOWN normal - { - if(spawnFlags & 16) - { - // 24: normal as is, and zero width (broken) - VectorCopy(plane, bestNormal); - } - else - { - // 8: normal as is - VectorCopy(plane, bestNormal); - } - } - else - { - if(spawnFlags & 16) - { - // 16: UP/DOWN normal - VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1)); - } - else - { - // 0: axial normal - if(fabs(plane[0]) > fabs(plane[1])) // x>y - if(fabs(plane[1]) > fabs(plane[2])) // x>y, y>z - VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0); - else // x>y, z>=y - if(fabs(plane[0]) > fabs(plane[2])) // x>z, z>=y - VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0); - else // z>=x, x>y - VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1)); - else // y>=x - if(fabs(plane[1]) > fabs(plane[2])) // y>z, y>=x - VectorSet(bestNormal, 0, (plane[1] >= 0 ? 1 : -1), 0); - else // z>=y, y>=x - VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1)); - } - } - - /* build a brush */ - buildBrush = AllocBrush( 48 ); - buildBrush->entityNum = mapEntityNum; - buildBrush->original = buildBrush; - buildBrush->contentShader = si; - buildBrush->compileFlags = si->compileFlags; - buildBrush->contentFlags = si->contentFlags; - normalEpsilon_save = normalEpsilon; - distanceEpsilon_save = distanceEpsilon; - if(si->compileFlags & C_STRUCTURAL) // allow forced structural brushes here - { - buildBrush->detail = qfalse; - - // only allow EXACT matches when snapping for these (this is mostly for caulk brushes inside a model) - if(normalEpsilon > 0) - normalEpsilon = 0; - if(distanceEpsilon > 0) - distanceEpsilon = 0; - } - else - buildBrush->detail = qtrue; - - /* regenerate back points */ - for( j = 0; j < 3; j++ ) - { - /* get vertex */ - dv = &ds->verts[ ds->indexes[ i + j ] ]; - - // shift by some units - VectorMA(dv->xyz, -64.0f, bestNormal, backs[j]); // 64 prevents roundoff errors a bit - } - - /* make back plane */ - VectorScale( plane, -1.0f, reverse ); - reverse[ 3 ] = -plane[ 3 ]; - if((spawnFlags & 24) != 24) - reverse[3] += DotProduct(bestNormal, plane) * backPlaneDistance; - // that's at least sqrt(1/3) backPlaneDistance, unless in DOWN mode; in DOWN mode, we are screwed anyway if we encounter a plane that's perpendicular to the xy plane) - - if( PlaneFromPoints( pa, points[ 2 ], points[ 1 ], backs[ 1 ] ) && - PlaneFromPoints( pb, points[ 1 ], points[ 0 ], backs[ 0 ] ) && - PlaneFromPoints( pc, points[ 0 ], points[ 2 ], backs[ 2 ] ) ) - { - /* set up brush sides */ - buildBrush->numsides = 5; - buildBrush->sides[ 0 ].shaderInfo = si; - for( j = 1; j < buildBrush->numsides; j++ ) - buildBrush->sides[ j ].shaderInfo = NULL; // don't emit these faces as draw surfaces, should make smaller BSPs; hope this works - - buildBrush->sides[ 0 ].planenum = FindFloatPlane( plane, plane[ 3 ], 3, points ); - buildBrush->sides[ 1 ].planenum = FindFloatPlane( pa, pa[ 3 ], 2, &points[ 1 ] ); // pa contains points[1] and points[2] - buildBrush->sides[ 2 ].planenum = FindFloatPlane( pb, pb[ 3 ], 2, &points[ 0 ] ); // pb contains points[0] and points[1] - buildBrush->sides[ 3 ].planenum = FindFloatPlane( pc, pc[ 3 ], 2, &points[ 2 ] ); // pc contains points[2] and points[0] (copied to points[3] - buildBrush->sides[ 4 ].planenum = FindFloatPlane( reverse, reverse[ 3 ], 3, backs ); - } - else - { - free(buildBrush); - continue; - } - - normalEpsilon = normalEpsilon_save; - distanceEpsilon = distanceEpsilon_save; - - /* add to entity */ - if( CreateBrushWindings( buildBrush ) ) - { - AddBrushBevels(); - //% EmitBrushes( buildBrush, NULL, NULL ); - buildBrush->next = entities[ mapEntityNum ].brushes; - entities[ mapEntityNum ].brushes = buildBrush; - entities[ mapEntityNum ].numBrushes++; - } - else - free( buildBrush ); - } - } - } - } -} - - - -/* -AddTriangleModels() -adds misc_model surfaces to the bsp -*/ - -void AddTriangleModels( entity_t *e ) -{ - int num, frame, skin, castShadows, recvShadows, spawnFlags; - entity_t *e2; - const char *targetName; - const char *target, *model, *value; - char shader[ MAX_QPATH ]; - shaderInfo_t *celShader; - float temp, baseLightmapScale, lightmapScale; - float shadeAngle; - int lightmapSampleSize; - vec3_t origin, scale, angles; - m4x4_t transform; - epair_t *ep; - remap_t *remap, *remap2; - char *split; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- AddTriangleModels ---\n" ); - - /* get current brush entity targetname */ - if( e == entities ) - targetName = ""; - else - { - targetName = ValueForKey( e, "targetname" ); - - /* misc_model entities target non-worldspawn brush model entities */ - if( targetName[ 0 ] == '\0' ) - return; - } - - /* get lightmap scale */ - /* vortex: added _ls key (short name of lightmapscale) */ - baseLightmapScale = 0.0f; - if( strcmp( "", ValueForKey( e, "lightmapscale" ) ) || - strcmp( "", ValueForKey( e, "_lightmapscale" ) ) || - strcmp( "", ValueForKey( e, "_ls" ) ) ) - { - baseLightmapScale = FloatForKey( e, "lightmapscale" ); - if( baseLightmapScale <= 0.0f ) - baseLightmapScale = FloatForKey( e, "_lightmapscale" ); - if( baseLightmapScale <= 0.0f ) - baseLightmapScale = FloatForKey( e, "_ls" ); - if( baseLightmapScale < 0.0f ) - baseLightmapScale = 0.0f; - if( baseLightmapScale > 0.0f ) - Sys_Printf( "World Entity has lightmap scale of %.4f\n", baseLightmapScale ); - } - - - /* walk the entity list */ - for( num = 1; num < numEntities; num++ ) - { - /* get e2 */ - e2 = &entities[ num ]; - - /* convert misc_models into raw geometry */ - if( Q_stricmp( "misc_model", ValueForKey( e2, "classname" ) ) ) - continue; - - /* ydnar: added support for md3 models on non-worldspawn models */ - target = ValueForKey( e2, "target" ); - if( strcmp( target, targetName ) ) - continue; - - /* get model name */ - model = ValueForKey( e2, "model" ); - if( model[ 0 ] == '\0' ) - { - Sys_Printf( "WARNING: misc_model at %i %i %i without a model key\n", - (int) origin[ 0 ], (int) origin[ 1 ], (int) origin[ 2 ] ); - continue; - } - - /* get model frame */ - frame = IntForKey( e2, "_frame" ); - - /* worldspawn (and func_groups) default to cast/recv shadows in worldspawn group */ - if( e == entities ) - { - castShadows = WORLDSPAWN_CAST_SHADOWS; - recvShadows = WORLDSPAWN_RECV_SHADOWS; - } - - /* other entities don't cast any shadows, but recv worldspawn shadows */ - else - { - castShadows = ENTITY_CAST_SHADOWS; - recvShadows = ENTITY_RECV_SHADOWS; - } - - /* get explicit shadow flags */ - GetEntityShadowFlags( e2, e, &castShadows, &recvShadows ); - - /* get spawnflags */ - spawnFlags = IntForKey( e2, "spawnflags" ); - - /* get origin */ - GetVectorForKey( e2, "origin", origin ); - VectorSubtract( origin, e->origin, origin ); /* offset by parent */ - - /* get scale */ - scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = 1.0f; - temp = FloatForKey( e2, "modelscale" ); - if( temp != 0.0f ) - scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp; - value = ValueForKey( e2, "modelscale_vec" ); - if( value[ 0 ] != '\0' ) - sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] ); - - /* get "angle" (yaw) or "angles" (pitch yaw roll) */ - angles[ 0 ] = angles[ 1 ] = angles[ 2 ] = 0.0f; - angles[ 2 ] = FloatForKey( e2, "angle" ); - value = ValueForKey( e2, "angles" ); - if( value[ 0 ] != '\0' ) - sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ); - - /* set transform matrix (thanks spog) */ - m4x4_identity( transform ); - m4x4_pivoted_transform_by_vec3( transform, origin, angles, eXYZ, scale, vec3_origin ); - - /* get shader remappings */ - remap = NULL; - for( ep = e2->epairs; ep != NULL; ep = ep->next ) - { - /* look for keys prefixed with "_remap" */ - if( ep->key != NULL && ep->value != NULL && - ep->key[ 0 ] != '\0' && ep->value[ 0 ] != '\0' && - !Q_strncasecmp( ep->key, "_remap", 6 ) ) - { - /* create new remapping */ - remap2 = remap; - remap = safe_malloc( sizeof( *remap ) ); - remap->next = remap2; - strcpy( remap->from, ep->value ); - - /* split the string */ - split = strchr( remap->from, ';' ); - if( split == NULL ) - { - Sys_Printf( "WARNING: Shader _remap key found in misc_model without a ; character\n" ); - free( remap ); - remap = remap2; - continue; - } - - /* store the split */ - *split = '\0'; - strcpy( remap->to, (split + 1) ); - - /* note it */ - //% Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", remap->from, remap->to ); - } - } - - /* ydnar: cel shader support */ - value = ValueForKey( e2, "_celshader" ); - if( value[ 0 ] == '\0' ) - value = ValueForKey( &entities[ 0 ], "_celshader" ); - if( value[ 0 ] != '\0' ) - { - sprintf( shader, "textures/%s", value ); - celShader = ShaderInfoForShader( shader ); - } - else - celShader = *globalCelShader ? ShaderInfoForShader(globalCelShader) : NULL; - - /* jal : entity based _samplesize */ - lightmapSampleSize = 0; - if ( strcmp( "", ValueForKey( e2, "_lightmapsamplesize" ) ) ) - lightmapSampleSize = IntForKey( e2, "_lightmapsamplesize" ); - else if ( strcmp( "", ValueForKey( e2, "_samplesize" ) ) ) - lightmapSampleSize = IntForKey( e2, "_samplesize" ); - - if( lightmapSampleSize < 0 ) - lightmapSampleSize = 0; - - if( lightmapSampleSize > 0.0f ) - Sys_Printf( "misc_model has lightmap sample size of %.d\n", lightmapSampleSize ); - - /* get lightmap scale */ - /* vortex: added _ls key (short name of lightmapscale) */ - lightmapScale = 0.0f; - if( strcmp( "", ValueForKey( e2, "lightmapscale" ) ) || - strcmp( "", ValueForKey( e2, "_lightmapscale" ) ) || - strcmp( "", ValueForKey( e2, "_ls" ) ) ) - { - lightmapScale = FloatForKey( e2, "lightmapscale" ); - if( lightmapScale <= 0.0f ) - lightmapScale = FloatForKey( e2, "_lightmapscale" ); - if( lightmapScale <= 0.0f ) - lightmapScale = FloatForKey( e2, "_ls" ); - if( lightmapScale < 0.0f ) - lightmapScale = 0.0f; - if( lightmapScale > 0.0f ) - Sys_Printf( "misc_model has lightmap scale of %.4f\n", lightmapScale ); - } - - /* jal : entity based _shadeangle */ - shadeAngle = 0.0f; - if ( strcmp( "", ValueForKey( e2, "_shadeangle" ) ) ) - shadeAngle = FloatForKey( e2, "_shadeangle" ); - /* vortex' aliases */ - else if ( strcmp( "", ValueForKey( e2, "_smoothnormals" ) ) ) - shadeAngle = FloatForKey( e2, "_smoothnormals" ); - else if ( strcmp( "", ValueForKey( e2, "_sn" ) ) ) - shadeAngle = FloatForKey( e2, "_sn" ); - else if ( strcmp( "", ValueForKey( e2, "_smooth" ) ) ) - shadeAngle = FloatForKey( e2, "_smooth" ); - - if( shadeAngle < 0.0f ) - shadeAngle = 0.0f; - - if( shadeAngle > 0.0f ) - Sys_Printf( "misc_model has shading angle of %.4f\n", shadeAngle ); - - skin = IntForKey(e2, "skin"); - - /* insert the model */ - InsertModel( model, skin, frame, transform, remap, celShader, mapEntityNum, castShadows, recvShadows, spawnFlags, lightmapScale, lightmapSampleSize, shadeAngle ); - - /* free shader remappings */ - while( remap != NULL ) - { - remap2 = remap->next; - free( remap ); - remap = remap2; - } - } -} diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/patch.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/patch.c deleted file mode 100644 index 9cd707e2..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/patch.c +++ /dev/null @@ -1,524 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define PATCH_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -ExpandLongestCurve() - ydnar -finds length of quadratic curve specified and determines if length is longer than the supplied max -*/ - -#define APPROX_SUBDIVISION 8 - -static void ExpandLongestCurve( float *longestCurve, vec3_t a, vec3_t b, vec3_t c ) -{ - int i; - float t, len; - vec3_t ab, bc, ac, pt, last, delta; - - - /* calc vectors */ - VectorSubtract( b, a, ab ); - if( VectorNormalize( ab, ab ) < 0.125f ) - return; - VectorSubtract( c, b, bc ); - if( VectorNormalize( bc, bc ) < 0.125f ) - return; - VectorSubtract( c, a, ac ); - if( VectorNormalize( ac, ac ) < 0.125f ) - return; - - /* if all 3 vectors are the same direction, then this edge is linear, so we ignore it */ - if( DotProduct( ab, bc ) > 0.99f && DotProduct( ab, ac ) > 0.99f ) - return; - - /* recalculate vectors */ - VectorSubtract( b, a, ab ); - VectorSubtract( c, b, bc ); - - /* determine length */ - VectorCopy( a, last ); - for( i = 0, len = 0.0f, t = 0.0f; i < APPROX_SUBDIVISION; i++, t += (1.0f / APPROX_SUBDIVISION) ) - { - /* calculate delta */ - delta[ 0 ] = ((1.0f - t) * ab[ 0 ]) + (t * bc[ 0 ]); - delta[ 1 ] = ((1.0f - t) * ab[ 1 ]) + (t * bc[ 1 ]); - delta[ 2 ] = ((1.0f - t) * ab[ 2 ]) + (t * bc[ 2 ]); - - /* add to first point and calculate pt-pt delta */ - VectorAdd( a, delta, pt ); - VectorSubtract( pt, last, delta ); - - /* add it to length and store last point */ - len += VectorLength( delta ); - VectorCopy( pt, last ); - } - - /* longer? */ - if( len > *longestCurve ) - *longestCurve = len; -} - - - -/* -ExpandMaxIterations() - ydnar -determines how many iterations a quadratic curve needs to be subdivided with to fit the specified error -*/ - -static void ExpandMaxIterations( int *maxIterations, int maxError, vec3_t a, vec3_t b, vec3_t c ) -{ - int i, j; - vec3_t prev, next, mid, delta, delta2; - float len, len2; - int numPoints, iterations; - vec3_t points[ MAX_EXPANDED_AXIS ]; - - - /* initial setup */ - numPoints = 3; - VectorCopy( a, points[ 0 ] ); - VectorCopy( b, points[ 1 ] ); - VectorCopy( c, points[ 2 ] ); - - /* subdivide */ - for( i = 0; i + 2 < numPoints; i += 2 ) - { - /* check subdivision limit */ - if( numPoints + 2 >= MAX_EXPANDED_AXIS ) - break; - - /* calculate new curve deltas */ - for( j = 0; j < 3; j++ ) - { - prev[ j ] = points[ i + 1 ][ j ] - points[ i ][ j ]; - next[ j ] = points[ i + 2 ][ j ] - points[ i + 1 ][ j ]; - mid[ j ] = (points[ i ][ j ] + points[ i + 1 ][ j ] * 2.0f + points[ i + 2 ][ j ]) * 0.25f; - } - - /* see if this midpoint is off far enough to subdivide */ - VectorSubtract( points[ i + 1 ], mid, delta ); - len = VectorLength( delta ); - if( len < maxError ) - continue; - - /* subdivide */ - numPoints += 2; - - /* create new points */ - for( j = 0; j < 3; j++ ) - { - prev[ j ] = 0.5f * (points[ i ][ j ] + points[ i + 1 ][ j ]); - next[ j ] = 0.5f * (points[ i + 1 ][ j ] + points[ i + 2 ][ j ]); - mid[ j ] = 0.5f * (prev[ j ] + next[ j ]); - } - - /* push points out */ - for( j = numPoints - 1; j > i + 3; j-- ) - VectorCopy( points[ j - 2 ], points[ j ] ); - - /* insert new points */ - VectorCopy( prev, points[ i + 1 ] ); - VectorCopy( mid, points[ i + 2 ] ); - VectorCopy( next, points[ i + 3 ] ); - - /* back up and recheck this set again, it may need more subdivision */ - i -= 2; - } - - /* put the line on the curve */ - for( i = 1; i < numPoints; i += 2 ) - { - for( j = 0; j < 3; j++ ) - { - prev[ j ] = 0.5f * (points[ i ][ j ] + points[ i + 1 ][ j ] ); - next[ j ] = 0.5f * (points[ i ][ j ] + points[ i - 1 ][ j ] ); - points[ i ][ j ] = 0.5f * (prev[ j ] + next[ j ]); - } - } - - /* eliminate linear sections */ - for( i = 0; i + 2 < numPoints; i++ ) - { - /* create vectors */ - VectorSubtract( points[ i + 1 ], points[ i ], delta ); - len = VectorNormalize( delta, delta ); - VectorSubtract( points[ i + 2 ], points[ i + 1 ], delta2 ); - len2 = VectorNormalize( delta2, delta2 ); - - /* if either edge is degenerate, then eliminate it */ - if( len < 0.0625f || len2 < 0.0625f || DotProduct( delta, delta2 ) >= 1.0f ) - { - for( j = i + 1; j + 1 < numPoints; j++ ) - VectorCopy( points[ j + 1 ], points[ j ] ); - numPoints--; - continue; - } - } - - /* the number of iterations is 2^(points - 1) - 1 */ - numPoints >>= 1; - iterations = 0; - while( numPoints > 1 ) - { - numPoints >>= 1; - iterations++; - } - - /* more? */ - if( iterations > *maxIterations ) - *maxIterations = iterations; -} - - - -/* -ParsePatch() -creates a mapDrawSurface_t from the patch text -*/ - -void ParsePatch( qboolean onlyLights ) -{ - vec_t info[ 5 ]; - int i, j, k; - parseMesh_t *pm; - char texture[ MAX_QPATH ]; - char shader[ MAX_QPATH ]; - mesh_t m; - bspDrawVert_t *verts; - epair_t *ep; - vec4_t delta, delta2, delta3; - qboolean degenerate; - float longestCurve; - int maxIterations; - - MatchToken( "{" ); - - /* get texture */ - GetToken( qtrue ); - strcpy( texture, token ); - - Parse1DMatrix( 5, info ); - m.width = info[0]; - m.height = info[1]; - m.verts = verts = safe_malloc( m.width * m.height * sizeof( m.verts[0] ) ); - - if( m.width < 0 || m.width > MAX_PATCH_SIZE || m.height < 0 || m.height > MAX_PATCH_SIZE ) - Error( "ParsePatch: bad size" ); - - MatchToken( "(" ); - for( j = 0; j < m.width ; j++ ) - { - MatchToken( "(" ); - for( i = 0; i < m.height ; i++ ) - { - Parse1DMatrix( 5, verts[ i * m.width + j ].xyz ); - - /* ydnar: fix colors */ - for( k = 0; k < MAX_LIGHTMAPS; k++ ) - { - verts[ i * m.width + j ].color[ k ][ 0 ] = 255; - verts[ i * m.width + j ].color[ k ][ 1 ] = 255; - verts[ i * m.width + j ].color[ k ][ 2 ] = 255; - verts[ i * m.width + j ].color[ k ][ 3 ] = 255; - } - } - MatchToken( ")" ); - } - MatchToken( ")" ); - - // if brush primitives format, we may have some epairs to ignore here - GetToken(qtrue); - if (g_bBrushPrimit!=BPRIMIT_OLDBRUSHES && strcmp(token,"}")) - { - // NOTE: we leak that! - ep = ParseEPair(); - } - else - UnGetToken(); - - MatchToken( "}" ); - MatchToken( "}" ); - - /* short circuit */ - if( noCurveBrushes || onlyLights ) - return; - - - /* ydnar: delete and warn about degenerate patches */ - j = (m.width * m.height); - VectorClear( delta ); - delta[ 3 ] = 0; - degenerate = qtrue; - - /* find first valid vector */ - for( i = 1; i < j && delta[ 3 ] == 0; i++ ) - { - VectorSubtract( m.verts[ 0 ].xyz, m.verts[ i ].xyz, delta ); - delta[ 3 ] = VectorNormalize( delta, delta ); - } - - /* secondary degenerate test */ - if( delta[ 3 ] == 0 ) - degenerate = qtrue; - else - { - /* if all vectors match this or are zero, then this is a degenerate patch */ - for( i = 1; i < j && degenerate == qtrue; i++ ) - { - VectorSubtract( m.verts[ 0 ].xyz, m.verts[ i ].xyz, delta2 ); - delta2[ 3 ] = VectorNormalize( delta2, delta2 ); - if( delta2[ 3 ] != 0 ) - { - /* create inverse vector */ - VectorCopy( delta2, delta3 ); - delta3[ 3 ] = delta2[ 3 ]; - VectorInverse( delta3 ); - - /* compare */ - if( VectorCompare( delta, delta2 ) == qfalse && VectorCompare( delta, delta3 ) == qfalse ) - degenerate = qfalse; - } - } - } - - /* warn and select degenerate patch */ - if( degenerate ) - { - xml_Select( "degenerate patch", mapEnt->mapEntityNum, entitySourceBrushes, qfalse ); - free( m.verts ); - return; - } - - /* find longest curve on the mesh */ - longestCurve = 0.0f; - maxIterations = 0; - for( j = 0; j + 2 < m.width; j += 2 ) - { - for( i = 0; i + 2 < m.height; i += 2 ) - { - ExpandLongestCurve( &longestCurve, verts[ i * m.width + j ].xyz, verts[ i * m.width + (j + 1) ].xyz, verts[ i * m.width + (j + 2) ].xyz ); /* row */ - ExpandLongestCurve( &longestCurve, verts[ i * m.width + j ].xyz, verts[ (i + 1) * m.width + j ].xyz, verts[ (i + 2) * m.width + j ].xyz ); /* col */ - ExpandMaxIterations( &maxIterations, patchSubdivisions, verts[ i * m.width + j ].xyz, verts[ i * m.width + (j + 1) ].xyz, verts[ i * m.width + (j + 2) ].xyz ); /* row */ - ExpandMaxIterations( &maxIterations, patchSubdivisions, verts[ i * m.width + j ].xyz, verts[ (i + 1) * m.width + j ].xyz, verts[ (i + 2) * m.width + j ].xyz ); /* col */ - } - } - - /* allocate patch mesh */ - pm = safe_malloc( sizeof( *pm ) ); - memset( pm, 0, sizeof( *pm ) ); - - /* ydnar: add entity/brush numbering */ - pm->entityNum = mapEnt->mapEntityNum; - pm->brushNum = entitySourceBrushes; - - /* set shader */ - sprintf( shader, "textures/%s", texture ); - pm->shaderInfo = ShaderInfoForShader( shader ); - - /* set mesh */ - pm->mesh = m; - - /* set longest curve */ - pm->longestCurve = longestCurve; - pm->maxIterations = maxIterations; - - /* link to the entity */ - pm->next = mapEnt->patches; - mapEnt->patches = pm; -} - - - -/* -GrowGroup_r() -recursively adds patches to a lod group -*/ - -static void GrowGroup_r( parseMesh_t *pm, int patchNum, int patchCount, parseMesh_t **meshes, byte *bordering, byte *group ) -{ - int i; - const byte *row; - - - /* early out check */ - if( group[ patchNum ] ) - return; - - - /* set it */ - group[ patchNum ] = 1; - row = bordering + patchNum * patchCount; - - /* check maximums */ - if( meshes[ patchNum ]->longestCurve > pm->longestCurve ) - pm->longestCurve = meshes[ patchNum ]->longestCurve; - if( meshes[ patchNum ]->maxIterations > pm->maxIterations ) - pm->maxIterations = meshes[ patchNum ]->maxIterations; - - /* walk other patches */ - for( i = 0; i < patchCount; i++ ) - { - if( row[ i ] ) - GrowGroup_r( pm, i, patchCount, meshes, bordering, group ); - } -} - - -/* -PatchMapDrawSurfs() -any patches that share an edge need to choose their -level of detail as a unit, otherwise the edges would -pull apart. -*/ - -void PatchMapDrawSurfs( entity_t *e ) -{ - int i, j, k, l, c1, c2; - parseMesh_t *pm; - parseMesh_t *check, *scan; - mapDrawSurface_t *ds; - int patchCount, groupCount; - bspDrawVert_t *v1, *v2; - vec3_t bounds[ 2 ]; - byte *bordering; - - /* ydnar: mac os x fails with these if not static */ - MAC_STATIC parseMesh_t *meshes[ MAX_MAP_DRAW_SURFS ]; - MAC_STATIC qb_t grouped[ MAX_MAP_DRAW_SURFS ]; - MAC_STATIC byte group[ MAX_MAP_DRAW_SURFS ]; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- PatchMapDrawSurfs ---\n" ); - - patchCount = 0; - for ( pm = e->patches ; pm ; pm = pm->next ) { - meshes[patchCount] = pm; - patchCount++; - } - - if ( !patchCount ) { - return; - } - bordering = safe_malloc( patchCount * patchCount ); - memset( bordering, 0, patchCount * patchCount ); - - // build the bordering matrix - for ( k = 0 ; k < patchCount ; k++ ) { - bordering[k*patchCount+k] = 1; - - for ( l = k+1 ; l < patchCount ; l++ ) { - check = meshes[k]; - scan = meshes[l]; - c1 = scan->mesh.width * scan->mesh.height; - v1 = scan->mesh.verts; - - for ( i = 0 ; i < c1 ; i++, v1++ ) { - c2 = check->mesh.width * check->mesh.height; - v2 = check->mesh.verts; - for ( j = 0 ; j < c2 ; j++, v2++ ) { - if ( fabs( v1->xyz[0] - v2->xyz[0] ) < 1.0 - && fabs( v1->xyz[1] - v2->xyz[1] ) < 1.0 - && fabs( v1->xyz[2] - v2->xyz[2] ) < 1.0 ) { - break; - } - } - if ( j != c2 ) { - break; - } - } - if ( i != c1 ) { - // we have a connection - bordering[k*patchCount+l] = - bordering[l*patchCount+k] = 1; - } else { - // no connection - bordering[k*patchCount+l] = - bordering[l*patchCount+k] = 0; - } - - } - } - - /* build groups */ - memset( grouped, 0, patchCount ); - groupCount = 0; - for ( i = 0; i < patchCount; i++ ) - { - /* get patch */ - scan = meshes[ i ]; - - /* start a new group */ - if( !grouped[ i ] ) - groupCount++; - - /* recursively find all patches that belong in the same group */ - memset( group, 0, patchCount ); - GrowGroup_r( scan, i, patchCount, meshes, bordering, group ); - - /* bound them */ - ClearBounds( bounds[ 0 ], bounds[ 1 ] ); - for( j = 0; j < patchCount; j++ ) - { - if ( group[ j ] ) - { - grouped[ j ] = qtrue; - check = meshes[ j ]; - c1 = check->mesh.width * check->mesh.height; - v1 = check->mesh.verts; - for( k = 0; k < c1; k++, v1++ ) - AddPointToBounds( v1->xyz, bounds[ 0 ], bounds[ 1 ] ); - } - } - - /* debug code */ - //% Sys_Printf( "Longest curve: %f Iterations: %d\n", scan->longestCurve, scan->maxIterations ); - - /* create drawsurf */ - scan->grouped = qtrue; - ds = DrawSurfaceForMesh( e, scan, NULL ); /* ydnar */ - VectorCopy( bounds[ 0 ], ds->bounds[ 0 ] ); - VectorCopy( bounds[ 1 ], ds->bounds[ 1 ] ); - } - - /* emit some statistics */ - Sys_FPrintf( SYS_VRB, "%9d patches\n", patchCount ); - Sys_FPrintf( SYS_VRB, "%9d patch LOD groups\n", groupCount ); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/path_init.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/path_init.c deleted file mode 100644 index 83383e22..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/path_init.c +++ /dev/null @@ -1,507 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define PATH_INIT_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* path support */ -#define MAX_BASE_PATHS 10 -#define MAX_GAME_PATHS 10 - -char *homePath; -char installPath[ MAX_OS_PATH ]; - -int numBasePaths; -char *basePaths[ MAX_BASE_PATHS ]; -int numGamePaths; -char *gamePaths[ MAX_GAME_PATHS ]; -char *homeBasePath = NULL; - - -/* -some of this code is based off the original q3map port from loki -and finds various paths. moved here from bsp.c for clarity. -*/ - -/* -PathLokiGetHomeDir() -gets the user's home dir (for ~/.q3a) -*/ - -char *LokiGetHomeDir( void ) -{ - #ifndef Q_UNIX - return NULL; - #else - char *home; - uid_t id; - struct passwd *pwd; - - - /* get the home environment variable */ - home = getenv( "HOME" ); - if( home == NULL ) - { - /* do some more digging */ - id = getuid(); - setpwent(); - while( (pwd = getpwent()) != NULL ) - { - if( pwd->pw_uid == id ) - { - home = pwd->pw_dir; - break; - } - } - endpwent(); - } - - /* return it */ - return home; - #endif -} - - - -/* -PathLokiInitPaths() -initializes some paths on linux/os x -*/ - -void LokiInitPaths( char *argv0 ) -{ - #ifndef Q_UNIX - /* this is kinda crap, but hey */ - strcpy( installPath, "../" ); - #else - char temp[ MAX_OS_PATH ]; - char last0[ 2 ]; - char *home; - char *path; - char *last; - qboolean found; - - - /* get home dir */ - home = LokiGetHomeDir(); - if( home == NULL ) - home = "."; - - /* do some path divining */ - strcpy( temp, argv0 ); - if( strrchr( argv0, '/' ) ) - argv0 = strrchr( argv0, '/' ) + 1; - else - { - /* get path environment variable */ - path = getenv( "PATH" ); - - /* minor setup */ - last = last0; - last[ 0 ] = path[ 0 ]; - last[ 1 ] = '\0'; - found = qfalse; - - /* go through each : segment of path */ - while( last[ 0 ] != '\0' && found == qfalse ) - { - /* null out temp */ - temp[ 0 ] = '\0'; - - /* find next chunk */ - last = strchr( path, ':' ); - if( last == NULL ) - last = path + strlen( path ); - - /* found home dir candidate */ - if( *path == '~' ) - { - strcpy( temp, home ); - path++; - } - - /* concatenate */ - if( last > (path + 1) ) - { - strncat( temp, path, (last - path) ); - strcat( temp, "/" ); - } - strcat( temp, "./" ); - strcat( temp, argv0 ); - - /* verify the path */ - if( access( temp, X_OK ) == 0 ) - found++; - path = last + 1; - } - } - - /* flake */ - if( realpath( temp, installPath ) ) - { - /* q3map is in "tools/" */ - *(strrchr( installPath, '/' )) = '\0'; - *(strrchr( installPath, '/' ) + 1) = '\0'; - } - - /* set home path */ - homePath = home; - #endif -} - - - -/* -CleanPath() - ydnar -cleans a dos path \ -> / -*/ - -void CleanPath( char *path ) -{ - while( *path ) - { - if( *path == '\\' ) - *path = '/'; - path++; - } -} - - - -/* -GetGame() - ydnar -gets the game_t based on a -game argument -returns NULL if no match found -*/ - -game_t *GetGame( char *arg ) -{ - int i; - - - /* dummy check */ - if( arg == NULL || arg[ 0 ] == '\0' ) - return NULL; - - /* joke */ - if( !Q_stricmp( arg, "quake1" ) || - !Q_stricmp( arg, "quake2" ) || - !Q_stricmp( arg, "unreal" ) || - !Q_stricmp( arg, "ut2k3" ) || - !Q_stricmp( arg, "dn3d" ) || - !Q_stricmp( arg, "dnf" ) || - !Q_stricmp( arg, "hl" ) ) - { - Sys_Printf( "April fools, silly rabbit!\n" ); - exit( 0 ); - } - - /* test it */ - i = 0; - while( games[ i ].arg != NULL ) - { - if( Q_stricmp( arg, games[ i ].arg ) == 0 ) - return &games[ i ]; - i++; - } - - /* no matching game */ - return NULL; -} - - - -/* -AddBasePath() - ydnar -adds a base path to the list -*/ - -void AddBasePath( char *path ) -{ - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' || numBasePaths >= MAX_BASE_PATHS ) - return; - - /* add it to the list */ - basePaths[ numBasePaths ] = safe_malloc( strlen( path ) + 1 ); - strcpy( basePaths[ numBasePaths ], path ); - CleanPath( basePaths[ numBasePaths ] ); - numBasePaths++; -} - - - -/* -AddHomeBasePath() - ydnar -adds a base path to the beginning of the list, prefixed by ~/ -*/ - -void AddHomeBasePath( char *path ) -{ - #ifdef Q_UNIX - int i; - char temp[ MAX_OS_PATH ]; - - - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' ) - return; - - /* make a hole */ - for( i = (MAX_BASE_PATHS - 2); i >= 0; i-- ) - basePaths[ i + 1 ] = basePaths[ i ]; - - /* concatenate home dir and path */ - sprintf( temp, "%s/%s", homePath, path ); - - /* add it to the list */ - basePaths[ 0 ] = safe_malloc( strlen( temp ) + 1 ); - strcpy( basePaths[ 0 ], temp ); - CleanPath( basePaths[ 0 ] ); - numBasePaths++; - #endif -} - - - -/* -AddGamePath() - ydnar -adds a game path to the list -*/ - -void AddGamePath( char *path ) -{ - int i; - - /* dummy check */ - if( path == NULL || path[ 0 ] == '\0' || numGamePaths >= MAX_GAME_PATHS ) - return; - - /* add it to the list */ - gamePaths[ numGamePaths ] = safe_malloc( strlen( path ) + 1 ); - strcpy( gamePaths[ numGamePaths ], path ); - CleanPath( gamePaths[ numGamePaths ] ); - numGamePaths++; - - /* don't add it if it's already there */ - for (i = 0; i < numGamePaths - 1; i++) - { - if (strcmp(gamePaths[i], gamePaths[numGamePaths - 1]) == 0) - { - free(gamePaths[numGamePaths - 1]); - gamePaths[numGamePaths - 1] = NULL; - numGamePaths--; - break; - } - } - -} - - - - -/* -InitPaths() - ydnar -cleaned up some of the path initialization code from bsp.c -will remove any arguments it uses -*/ - -void InitPaths( int *argc, char **argv ) -{ - int i, j, k, len, len2; - char temp[ MAX_OS_PATH ]; - - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- InitPaths ---\n" ); - - /* get the install path for backup */ - LokiInitPaths( argv[ 0 ] ); - - /* set game to default (q3a) */ - game = &games[ 0 ]; - numBasePaths = 0; - numGamePaths = 0; - - /* parse through the arguments and extract those relevant to paths */ - for( i = 0; i < *argc; i++ ) - { - /* check for null */ - if( argv[ i ] == NULL ) - continue; - - /* -game */ - if( strcmp( argv[ i ], "-game" ) == 0 ) - { - if( ++i >= *argc ) - Error( "Out of arguments: No game specified after %s", argv[ i - 1 ] ); - argv[ i - 1 ] = NULL; - game = GetGame( argv[ i ] ); - if( game == NULL ) - game = &games[ 0 ]; - argv[ i ] = NULL; - } - - /* -fs_forbiddenpath */ - else if( strcmp( argv[ i ], "-fs_forbiddenpath" ) == 0 ) - { - if( ++i >= *argc ) - Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); - argv[ i - 1 ] = NULL; - if(g_numForbiddenDirs < VFS_MAXDIRS) - { - strncpy(g_strForbiddenDirs[g_numForbiddenDirs], argv[i], PATH_MAX); - g_strForbiddenDirs[g_numForbiddenDirs][PATH_MAX] = 0; - ++g_numForbiddenDirs; - } - argv[ i ] = NULL; - } - - /* -fs_basepath */ - else if( strcmp( argv[ i ], "-fs_basepath" ) == 0 ) - { - if( ++i >= *argc ) - Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); - argv[ i - 1 ] = NULL; - AddBasePath( argv[ i ] ); - argv[ i ] = NULL; - } - - /* -fs_game */ - else if( strcmp( argv[ i ], "-fs_game" ) == 0 ) - { - if( ++i >= *argc ) - Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); - argv[ i - 1 ] = NULL; - AddGamePath( argv[ i ] ); - argv[ i ] = NULL; - } - - /* -fs_nohomebase */ - else if( strcmp( argv[ i ], "-fs_homebase" ) == 0 ) - { - if( ++i >= *argc ) - Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); - argv[ i - 1 ] = NULL; - homeBasePath = argv[i]; - argv[ i ] = NULL; - } - } - - /* remove processed arguments */ - for( i = 0, j = 0, k = 0; i < *argc && j < *argc; i++, j++ ) - { - for( ; j < *argc && argv[ j ] == NULL; j++ ); - argv[ i ] = argv[ j ]; - if( argv[ i ] != NULL ) - k++; - } - *argc = k; - - /* add standard game path */ - AddGamePath( game->gamePath ); - - /* if there is no base path set, figure it out */ - if( numBasePaths == 0 ) - { - /* this is another crappy replacement for SetQdirFromPath() */ - len2 = strlen( game->magic ); - for( i = 0; i < *argc && numBasePaths == 0; i++ ) - { - /* extract the arg */ - strcpy( temp, argv[ i ] ); - CleanPath( temp ); - len = strlen( temp ); - Sys_FPrintf( SYS_VRB, "Searching for \"%s\" in \"%s\" (%d)...\n", game->magic, temp, i ); - - /* this is slow, but only done once */ - for( j = 0; j < (len - len2); j++ ) - { - /* check for the game's magic word */ - if( Q_strncasecmp( &temp[ j ], game->magic, len2 ) == 0 ) - { - /* now find the next slash and nuke everything after it */ - while( temp[ ++j ] != '/' && temp[ j ] != '\0' ); - temp[ j ] = '\0'; - - /* add this as a base path */ - AddBasePath( temp ); - break; - } - } - } - - /* add install path */ - if( numBasePaths == 0 ) - AddBasePath( installPath ); - - /* check again */ - if( numBasePaths == 0 ) - Error( "Failed to find a valid base path." ); - } - - /* this only affects unix */ - if(homeBasePath) - AddHomeBasePath( homeBasePath ); - else - AddHomeBasePath( game->homeBasePath ); - - /* initialize vfs paths */ - if( numBasePaths > MAX_BASE_PATHS ) - numBasePaths = MAX_BASE_PATHS; - if( numGamePaths > MAX_GAME_PATHS ) - numGamePaths = MAX_GAME_PATHS; - - /* walk the list of game paths */ - for( j = 0; j < numGamePaths; j++ ) - { - /* walk the list of base paths */ - for( i = 0; i < numBasePaths; i++ ) - { - /* create a full path and initialize it */ - sprintf( temp, "%s/%s/", basePaths[ i ], gamePaths[ j ] ); - vfsInitDirectory( temp ); - } - } - - /* done */ - Sys_Printf( "\n" ); -} - - - - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/portals.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/portals.c deleted file mode 100644 index 2efc1db4..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/portals.c +++ /dev/null @@ -1,981 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define PORTALS_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* ydnar: to fix broken portal windings */ -extern qboolean FixWinding( winding_t *w ); - - -int c_active_portals; -int c_peak_portals; -int c_boundary; -int c_boundary_sides; - -/* -=========== -AllocPortal -=========== -*/ -portal_t *AllocPortal (void) -{ - portal_t *p; - - if (numthreads == 1) - c_active_portals++; - if (c_active_portals > c_peak_portals) - c_peak_portals = c_active_portals; - - p = safe_malloc (sizeof(portal_t)); - memset (p, 0, sizeof(portal_t)); - - return p; -} - -void FreePortal (portal_t *p) -{ - if (p->winding) - FreeWinding (p->winding); - if (numthreads == 1) - c_active_portals--; - free (p); -} - - - -/* -PortalPassable -returns true if the portal has non-opaque leafs on both sides -*/ - -qboolean PortalPassable( portal_t *p ) -{ - /* is this to global outside leaf? */ - if( !p->onnode ) - return qfalse; - - /* this should never happen */ - if( p->nodes[ 0 ]->planenum != PLANENUM_LEAF || - p->nodes[ 1 ]->planenum != PLANENUM_LEAF ) - Error( "Portal_EntityFlood: not a leaf" ); - - /* ydnar: added antiportal to supress portal generation for visibility blocking */ - if( p->compileFlags & C_ANTIPORTAL ) - return qfalse; - - /* both leaves on either side of the portal must be passable */ - if( p->nodes[ 0 ]->opaque == qfalse && p->nodes[ 1 ]->opaque == qfalse ) - return qtrue; - - /* otherwise this isn't a passable portal */ - return qfalse; -} - - - - -int c_tinyportals; -int c_badportals; /* ydnar */ - -/* -============= -AddPortalToNodes -============= -*/ -void AddPortalToNodes (portal_t *p, node_t *front, node_t *back) -{ - if (p->nodes[0] || p->nodes[1]) - Error ("AddPortalToNode: allready included"); - - p->nodes[0] = front; - p->next[0] = front->portals; - front->portals = p; - - p->nodes[1] = back; - p->next[1] = back->portals; - back->portals = p; -} - - -/* -============= -RemovePortalFromNode -============= -*/ -void RemovePortalFromNode (portal_t *portal, node_t *l) -{ - portal_t **pp, *t; - -// remove reference to the current portal - pp = &l->portals; - while (1) - { - t = *pp; - if (!t) - Error ("RemovePortalFromNode: portal not in leaf"); - - if ( t == portal ) - break; - - if (t->nodes[0] == l) - pp = &t->next[0]; - else if (t->nodes[1] == l) - pp = &t->next[1]; - else - Error ("RemovePortalFromNode: portal not bounding leaf"); - } - - if (portal->nodes[0] == l) - { - *pp = portal->next[0]; - portal->nodes[0] = NULL; - } - else if (portal->nodes[1] == l) - { - *pp = portal->next[1]; - portal->nodes[1] = NULL; - } -} - -//============================================================================ - -void PrintPortal (portal_t *p) -{ - int i; - winding_t *w; - - w = p->winding; - for (i=0 ; inumpoints ; i++) - Sys_Printf ("(%5.0f,%5.0f,%5.0f)\n",w->p[i][0] - , w->p[i][1], w->p[i][2]); -} - -/* -================ -MakeHeadnodePortals - -The created portals will face the global outside_node -================ -*/ -#define SIDESPACE 8 -void MakeHeadnodePortals (tree_t *tree) -{ - vec3_t bounds[2]; - int i, j, n; - portal_t *p, *portals[6]; - plane_t bplanes[6], *pl; - node_t *node; - - node = tree->headnode; - -// pad with some space so there will never be null volume leafs - for (i=0 ; i<3 ; i++) - { - bounds[0][i] = tree->mins[i] - SIDESPACE; - bounds[1][i] = tree->maxs[i] + SIDESPACE; - if ( bounds[0][i] >= bounds[1][i] ) { - Error( "Backwards tree volume" ); - } - } - - tree->outside_node.planenum = PLANENUM_LEAF; - tree->outside_node.brushlist = NULL; - tree->outside_node.portals = NULL; - tree->outside_node.opaque = qfalse; - - for (i=0 ; i<3 ; i++) - for (j=0 ; j<2 ; j++) - { - n = j*3 + i; - - p = AllocPortal (); - portals[n] = p; - - pl = &bplanes[n]; - memset (pl, 0, sizeof(*pl)); - if (j) - { - pl->normal[i] = -1; - pl->dist = -bounds[j][i]; - } - else - { - pl->normal[i] = 1; - pl->dist = bounds[j][i]; - } - p->plane = *pl; - p->winding = BaseWindingForPlane (pl->normal, pl->dist); - AddPortalToNodes (p, node, &tree->outside_node); - } - -// clip the basewindings by all the other planes - for (i=0 ; i<6 ; i++) - { - for (j=0 ; j<6 ; j++) - { - if (j == i) - continue; - ChopWindingInPlace (&portals[i]->winding, bplanes[j].normal, bplanes[j].dist, ON_EPSILON); - } - } -} - -//=================================================== - - -/* -================ -BaseWindingForNode -================ -*/ -#define BASE_WINDING_EPSILON 0.001 -#define SPLIT_WINDING_EPSILON 0.001 - -winding_t *BaseWindingForNode (node_t *node) -{ - winding_t *w; - node_t *n; - plane_t *plane; - vec3_t normal; - vec_t dist; - - w = BaseWindingForPlane (mapplanes[node->planenum].normal - , mapplanes[node->planenum].dist); - - // clip by all the parents - for (n=node->parent ; n && w ; ) - { - plane = &mapplanes[n->planenum]; - - if (n->children[0] == node) - { // take front - ChopWindingInPlace (&w, plane->normal, plane->dist, BASE_WINDING_EPSILON); - } - else - { // take back - VectorSubtract (vec3_origin, plane->normal, normal); - dist = -plane->dist; - ChopWindingInPlace (&w, normal, dist, BASE_WINDING_EPSILON); - } - node = n; - n = n->parent; - } - - return w; -} - -//============================================================ - -/* -================== -MakeNodePortal - -create the new portal by taking the full plane winding for the cutting plane -and clipping it by all of parents of this node -================== -*/ -void MakeNodePortal (node_t *node) -{ - portal_t *new_portal, *p; - winding_t *w; - vec3_t normal; - float dist; - int side; - - w = BaseWindingForNode (node); - - // clip the portal by all the other portals in the node - for (p = node->portals ; p && w; p = p->next[side]) - { - if (p->nodes[0] == node) - { - side = 0; - VectorCopy (p->plane.normal, normal); - dist = p->plane.dist; - } - else if (p->nodes[1] == node) - { - side = 1; - VectorSubtract (vec3_origin, p->plane.normal, normal); - dist = -p->plane.dist; - } - else - Error ("CutNodePortals_r: mislinked portal"); - - ChopWindingInPlace (&w, normal, dist, CLIP_EPSILON); - } - - if (!w) - { - return; - } - - - /* ydnar: adding this here to fix degenerate windings */ - #if 0 - if( FixWinding( w ) == qfalse ) - { - c_badportals++; - FreeWinding( w ); - return; - } - #endif - - if (WindingIsTiny (w)) - { - c_tinyportals++; - FreeWinding (w); - return; - } - - new_portal = AllocPortal (); - new_portal->plane = mapplanes[node->planenum]; - new_portal->onnode = node; - new_portal->winding = w; - new_portal->compileFlags = node->compileFlags; - AddPortalToNodes (new_portal, node->children[0], node->children[1]); -} - - -/* -============== -SplitNodePortals - -Move or split the portals that bound node so that the node's -children have portals instead of node. -============== -*/ -void SplitNodePortals (node_t *node) -{ - portal_t *p, *next_portal, *new_portal; - node_t *f, *b, *other_node; - int side; - plane_t *plane; - winding_t *frontwinding, *backwinding; - - plane = &mapplanes[node->planenum]; - f = node->children[0]; - b = node->children[1]; - - for (p = node->portals ; p ; p = next_portal) - { - if (p->nodes[0] == node) - side = 0; - else if (p->nodes[1] == node) - side = 1; - else - Error ("SplitNodePortals: mislinked portal"); - next_portal = p->next[side]; - - other_node = p->nodes[!side]; - RemovePortalFromNode (p, p->nodes[0]); - RemovePortalFromNode (p, p->nodes[1]); - -// -// cut the portal into two portals, one on each side of the cut plane -// - ClipWindingEpsilon (p->winding, plane->normal, plane->dist, - SPLIT_WINDING_EPSILON, &frontwinding, &backwinding); - - if (frontwinding && WindingIsTiny(frontwinding)) - { - if (!f->tinyportals) - VectorCopy(frontwinding->p[0], f->referencepoint); - f->tinyportals++; - if (!other_node->tinyportals) - VectorCopy(frontwinding->p[0], other_node->referencepoint); - other_node->tinyportals++; - - FreeWinding (frontwinding); - frontwinding = NULL; - c_tinyportals++; - } - - if (backwinding && WindingIsTiny(backwinding)) - { - if (!b->tinyportals) - VectorCopy(backwinding->p[0], b->referencepoint); - b->tinyportals++; - if (!other_node->tinyportals) - VectorCopy(backwinding->p[0], other_node->referencepoint); - other_node->tinyportals++; - - FreeWinding (backwinding); - backwinding = NULL; - c_tinyportals++; - } - - if (!frontwinding && !backwinding) - { // tiny windings on both sides - continue; - } - - if (!frontwinding) - { - FreeWinding (backwinding); - if (side == 0) - AddPortalToNodes (p, b, other_node); - else - AddPortalToNodes (p, other_node, b); - continue; - } - if (!backwinding) - { - FreeWinding (frontwinding); - if (side == 0) - AddPortalToNodes (p, f, other_node); - else - AddPortalToNodes (p, other_node, f); - continue; - } - - // the winding is split - new_portal = AllocPortal (); - *new_portal = *p; - new_portal->winding = backwinding; - FreeWinding (p->winding); - p->winding = frontwinding; - - if (side == 0) - { - AddPortalToNodes (p, f, other_node); - AddPortalToNodes (new_portal, b, other_node); - } - else - { - AddPortalToNodes (p, other_node, f); - AddPortalToNodes (new_portal, other_node, b); - } - } - - node->portals = NULL; -} - - -/* -================ -CalcNodeBounds -================ -*/ -void CalcNodeBounds (node_t *node) -{ - portal_t *p; - int s; - int i; - - // calc mins/maxs for both leafs and nodes - ClearBounds (node->mins, node->maxs); - for (p = node->portals ; p ; p = p->next[s]) - { - s = (p->nodes[1] == node); - for (i=0 ; iwinding->numpoints ; i++) - AddPointToBounds (p->winding->p[i], node->mins, node->maxs); - } -} - -/* -================== -MakeTreePortals_r -================== -*/ -void MakeTreePortals_r (node_t *node) -{ - int i; - - CalcNodeBounds (node); - if (node->mins[0] >= node->maxs[0]) - { - Sys_Printf ("WARNING: node without a volume\n"); - Sys_Printf("node has %d tiny portals\n", node->tinyportals); - Sys_Printf("node reference point %1.2f %1.2f %1.2f\n", node->referencepoint[0], - node->referencepoint[1], - node->referencepoint[2]); - } - - for (i=0 ; i<3 ; i++) - { - if (node->mins[i] < MIN_WORLD_COORD || node->maxs[i] > MAX_WORLD_COORD) - { - if(node->portals && node->portals->winding) - xml_Winding("WARNING: Node With Unbounded Volume", node->portals->winding->p, node->portals->winding->numpoints, qfalse); - - break; - } - } - if (node->planenum == PLANENUM_LEAF) - return; - - MakeNodePortal (node); - SplitNodePortals (node); - - MakeTreePortals_r (node->children[0]); - MakeTreePortals_r (node->children[1]); -} - -/* -================== -MakeTreePortals -================== -*/ -void MakeTreePortals (tree_t *tree) -{ - Sys_FPrintf (SYS_VRB, "--- MakeTreePortals ---\n"); - MakeHeadnodePortals (tree); - MakeTreePortals_r (tree->headnode); - Sys_FPrintf( SYS_VRB, "%9d tiny portals\n", c_tinyportals ); - Sys_FPrintf( SYS_VRB, "%9d bad portals\n", c_badportals ); /* ydnar */ -} - -/* -========================================================= - -FLOOD ENTITIES - -========================================================= -*/ - -int c_floodedleafs; - -/* -============= -FloodPortals_r -============= -*/ - -void FloodPortals_r( node_t *node, int dist, qboolean skybox ) -{ - int s; - portal_t *p; - - - if( skybox ) - node->skybox = skybox; - - if( node->occupied || node->opaque ) - return; - - c_floodedleafs++; - node->occupied = dist; - - for( p = node->portals; p; p = p->next[ s ] ) - { - s = (p->nodes[ 1 ] == node); - FloodPortals_r( p->nodes[ !s ], dist + 1, skybox ); - } -} - - - -/* -============= -PlaceOccupant -============= -*/ - -qboolean PlaceOccupant( node_t *headnode, vec3_t origin, entity_t *occupant, qboolean skybox ) -{ - vec_t d; - node_t *node; - plane_t *plane; - - - // find the leaf to start in - node = headnode; - while( node->planenum != PLANENUM_LEAF ) - { - plane = &mapplanes[ node->planenum ]; - d = DotProduct( origin, plane->normal ) - plane->dist; - if( d >= 0 ) - node = node->children[ 0 ]; - else - node = node->children[ 1 ]; - } - - if( node->opaque ) - return qfalse; - node->occupant = occupant; - node->skybox = skybox; - - FloodPortals_r( node, 1, skybox ); - - return qtrue; -} - -/* -============= -FloodEntities - -Marks all nodes that can be reached by entites -============= -*/ - -qboolean FloodEntities( tree_t *tree ) -{ - int i, s; - vec3_t origin, offset, scale, angles; - qboolean r, inside, tripped, skybox; - node_t *headnode; - entity_t *e; - const char *value; - - - headnode = tree->headnode; - Sys_FPrintf( SYS_VRB,"--- FloodEntities ---\n" ); - inside = qfalse; - tree->outside_node.occupied = 0; - - tripped = qfalse; - c_floodedleafs = 0; - for( i = 1; i < numEntities; i++ ) - { - /* get entity */ - e = &entities[ i ]; - - /* get origin */ - GetVectorForKey( e, "origin", origin ); - - /* as a special case, allow origin-less entities */ - if( VectorCompare( origin, vec3_origin ) ) - continue; - - /* also allow bmodel entities outside, as they could be on a moving path that will go into the map */ - if( e->brushes != NULL || e->patches != NULL ) - continue; - - /* handle skybox entities */ - value = ValueForKey( e, "classname" ); - if( !Q_stricmp( value, "_skybox" ) ) - { - skybox = qtrue; - skyboxPresent = qtrue; - - /* invert origin */ - VectorScale( origin, -1.0f, offset ); - - /* get scale */ - VectorSet( scale, 64.0f, 64.0f, 64.0f ); - value = ValueForKey( e, "_scale" ); - if( value[ 0 ] != '\0' ) - { - s = sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] ); - if( s == 1 ) - { - scale[ 1 ] = scale[ 0 ]; - scale[ 2 ] = scale[ 0 ]; - } - } - - /* get "angle" (yaw) or "angles" (pitch yaw roll) */ - VectorClear( angles ); - angles[ 2 ] = FloatForKey( e, "angle" ); - value = ValueForKey( e, "angles" ); - if( value[ 0 ] != '\0' ) - sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ); - - /* set transform matrix (thanks spog) */ - m4x4_identity( skyboxTransform ); - m4x4_pivoted_transform_by_vec3( skyboxTransform, offset, angles, eXYZ, scale, origin ); - } - else - skybox = qfalse; - - /* nudge off floor */ - origin[ 2 ] += 1; - - /* debugging code */ - //% if( i == 1 ) - //% origin[ 2 ] += 4096; - - /* find leaf */ - r = PlaceOccupant( headnode, origin, e, skybox ); - if( r ) - inside = qtrue; - if( !r ) - { - Sys_Printf( "Entity %i, Brush %i: Entity in solid\n", e->mapEntityNum, 0); - } - else if( tree->outside_node.occupied && !tripped ) - { - xml_Select( "Entity leaked", e->mapEntityNum, 0, qfalse ); - tripped = qtrue; - } - } - - Sys_FPrintf( SYS_VRB, "%9d flooded leafs\n", c_floodedleafs ); - - if( !inside ) - Sys_FPrintf( SYS_VRB, "no entities in open -- no filling\n" ); - else if( tree->outside_node.occupied ) - Sys_FPrintf( SYS_VRB, "entity reached from outside -- no filling\n" ); - - return (qboolean) (inside && !tree->outside_node.occupied); -} - -/* -========================================================= - -FLOOD AREAS - -========================================================= -*/ - -int c_areas; - - - -/* -FloodAreas_r() -floods through leaf portals to tag leafs with an area -*/ - -void FloodAreas_r( node_t *node ) -{ - int s; - portal_t *p; - brush_t *b; - - - if( node->areaportal ) - { - if( node->area == -1 ) - node->area = c_areas; - - /* this node is part of an area portal brush */ - b = node->brushlist->original; - - /* if the current area has already touched this portal, we are done */ - if( b->portalareas[ 0 ] == c_areas || b->portalareas[ 1 ] == c_areas ) - return; - - // note the current area as bounding the portal - if( b->portalareas[ 1 ] != -1 ) - { - Sys_Printf( "WARNING: areaportal brush %i touches > 2 areas\n", b->brushNum ); - return; - } - if( b->portalareas[ 0 ] != -1 ) - b->portalareas[ 1 ] = c_areas; - else - b->portalareas[ 0 ] = c_areas; - - return; - } - - if( node->area != -1 ) - return; - if( node->cluster == -1 ) - return; - - node->area = c_areas; - - /* ydnar: skybox nodes set the skybox area */ - if( node->skybox ) - skyboxArea = c_areas; - - for( p = node->portals; p; p = p->next[ s ] ) - { - s = (p->nodes[1] == node); - - /* ydnar: allow areaportal portals to block area flow */ - if( p->compileFlags & C_AREAPORTAL ) - continue; - - if( !PortalPassable( p ) ) - continue; - - FloodAreas_r( p->nodes[ !s ] ); - } -} - -/* -============= -FindAreas_r - -Just decend the tree, and for each node that hasn't had an -area set, flood fill out from there -============= -*/ -void FindAreas_r( node_t *node ) -{ - if( node->planenum != PLANENUM_LEAF ) - { - FindAreas_r( node->children[ 0 ] ); - FindAreas_r( node->children[ 1 ] ); - return; - } - - if( node->opaque || node->areaportal || node->area != -1 ) - return; - - FloodAreas_r( node ); - c_areas++; -} - -/* -============= -CheckAreas_r -============= -*/ -void CheckAreas_r (node_t *node) -{ - brush_t *b; - - if (node->planenum != PLANENUM_LEAF) - { - CheckAreas_r (node->children[0]); - CheckAreas_r (node->children[1]); - return; - } - - if (node->opaque) - return; - - if (node->cluster != -1) - if (node->area == -1) - Sys_Printf("WARNING: cluster %d has area set to -1\n", node->cluster); - if (node->areaportal) - { - b = node->brushlist->original; - - // check if the areaportal touches two areas - if (b->portalareas[0] == -1 || b->portalareas[1] == -1) - Sys_Printf ("WARNING: areaportal brush %i doesn't touch two areas\n", b->brushNum); - } -} - - - -/* -FloodSkyboxArea_r() - ydnar -sets all nodes with the skybox area to skybox -*/ - -void FloodSkyboxArea_r( node_t *node ) -{ - if( skyboxArea < 0 ) - return; - - if( node->planenum != PLANENUM_LEAF ) - { - FloodSkyboxArea_r( node->children[ 0 ] ); - FloodSkyboxArea_r( node->children[ 1 ] ); - return; - } - - if( node->opaque || node->area != skyboxArea ) - return; - - node->skybox = qtrue; -} - - - -/* -FloodAreas() -mark each leaf with an area, bounded by C_AREAPORTAL -*/ - -void FloodAreas( tree_t *tree ) -{ - Sys_FPrintf( SYS_VRB,"--- FloodAreas ---\n" ); - FindAreas_r( tree->headnode ); - - /* ydnar: flood all skybox nodes */ - FloodSkyboxArea_r( tree->headnode ); - - /* check for areaportal brushes that don't touch two areas */ - /* ydnar: fix this rather than just silence the warnings */ - //% CheckAreas_r( tree->headnode ); - - Sys_FPrintf( SYS_VRB, "%9d areas\n", c_areas ); -} - - - -//====================================================== - -int c_outside; -int c_inside; -int c_solid; - -void FillOutside_r (node_t *node) -{ - if (node->planenum != PLANENUM_LEAF) - { - FillOutside_r (node->children[0]); - FillOutside_r (node->children[1]); - return; - } - - // anything not reachable by an entity - // can be filled away - if (!node->occupied) { - if ( !node->opaque ) { - c_outside++; - node->opaque = qtrue; - } else { - c_solid++; - } - } else { - c_inside++; - } - -} - -/* -============= -FillOutside - -Fill all nodes that can't be reached by entities -============= -*/ -void FillOutside (node_t *headnode) -{ - c_outside = 0; - c_inside = 0; - c_solid = 0; - Sys_FPrintf( SYS_VRB,"--- FillOutside ---\n" ); - FillOutside_r( headnode ); - Sys_FPrintf( SYS_VRB,"%9d solid leafs\n", c_solid ); - Sys_Printf( "%9d leafs filled\n", c_outside ); - Sys_FPrintf( SYS_VRB, "%9d inside leafs\n", c_inside ); -} - - -//============================================================== - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/prtfile.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/prtfile.c deleted file mode 100644 index 2f10c7c0..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/prtfile.c +++ /dev/null @@ -1,386 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define PRTFILE_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -============================================================================== - -PORTAL FILE GENERATION - -Save out name.prt for qvis to read -============================================================================== -*/ - - -#define PORTALFILE "PRT1" - -FILE *pf; -int num_visclusters; // clusters the player can be in -int num_visportals; -int num_solidfaces; - -void WriteFloat (FILE *f, vec_t v) -{ - if ( fabs(v - Q_rint(v)) < 0.001 ) - fprintf (f,"%i ",(int)Q_rint(v)); - else - fprintf (f,"%f ",v); -} - -void CountVisportals_r(node_t *node) -{ - int s; - portal_t *p; - winding_t *w; - - // decision node - if (node->planenum != PLANENUM_LEAF) { - CountVisportals_r (node->children[0]); - CountVisportals_r (node->children[1]); - return; - } - - if (node->opaque) { - return; - } - - for (p = node->portals ; p ; p=p->next[s]) - { - w = p->winding; - s = (p->nodes[1] == node); - if (w && p->nodes[0] == node) - { - if (!PortalPassable(p)) - continue; - if(p->nodes[0]->cluster == p->nodes[1]->cluster) - continue; - ++num_visportals; - } - } -} - -/* -================= -WritePortalFile_r -================= -*/ -void WritePortalFile_r (node_t *node) -{ - int i, s; - portal_t *p; - winding_t *w; - vec3_t normal; - vec_t dist; - - // decision node - if (node->planenum != PLANENUM_LEAF) { - WritePortalFile_r (node->children[0]); - WritePortalFile_r (node->children[1]); - return; - } - - if (node->opaque) { - return; - } - - for (p = node->portals ; p ; p=p->next[s]) - { - w = p->winding; - s = (p->nodes[1] == node); - if (w && p->nodes[0] == node) - { - if (!PortalPassable(p)) - continue; - if(p->nodes[0]->cluster == p->nodes[1]->cluster) - continue; - --num_visportals; - // write out to the file - - // sometimes planes get turned around when they are very near - // the changeover point between different axis. interpret the - // plane the same way vis will, and flip the side orders if needed - // FIXME: is this still relevent? - WindingPlane (w, normal, &dist); - - if ( DotProduct (p->plane.normal, normal) < 0.99 ) - { // backwards... - fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[1]->cluster, p->nodes[0]->cluster); - } - else - fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[0]->cluster, p->nodes[1]->cluster); - - /* ydnar: added this change to make antiportals work */ - if( p->compileFlags & C_HINT ) - fprintf( pf, "1 " ); - else - fprintf( pf, "0 " ); - - /* write the winding */ - for (i=0 ; inumpoints ; i++) - { - fprintf (pf,"("); - WriteFloat (pf, w->p[i][0]); - WriteFloat (pf, w->p[i][1]); - WriteFloat (pf, w->p[i][2]); - fprintf (pf,") "); - } - fprintf (pf,"\n"); - } - } - -} - -void CountSolidFaces_r (node_t *node) -{ - int s; - portal_t *p; - winding_t *w; - - // decision node - if (node->planenum != PLANENUM_LEAF) { - CountSolidFaces_r (node->children[0]); - CountSolidFaces_r (node->children[1]); - return; - } - - if (node->opaque) { - return; - } - - for (p = node->portals ; p ; p=p->next[s]) - { - w = p->winding; - s = (p->nodes[1] == node); - if (w) - { - if (PortalPassable(p)) - continue; - if(p->nodes[0]->cluster == p->nodes[1]->cluster) - continue; - // write out to the file - - ++num_solidfaces; - } - } -} - -/* -================= -WriteFaceFile_r -================= -*/ -void WriteFaceFile_r (node_t *node) -{ - int i, s; - portal_t *p; - winding_t *w; - - // decision node - if (node->planenum != PLANENUM_LEAF) { - WriteFaceFile_r (node->children[0]); - WriteFaceFile_r (node->children[1]); - return; - } - - if (node->opaque) { - return; - } - - for (p = node->portals ; p ; p=p->next[s]) - { - w = p->winding; - s = (p->nodes[1] == node); - if (w) - { - if (PortalPassable(p)) - continue; - if(p->nodes[0]->cluster == p->nodes[1]->cluster) - continue; - // write out to the file - - if (p->nodes[0] == node) - { - fprintf (pf,"%i %i ",w->numpoints, p->nodes[0]->cluster); - for (i=0 ; inumpoints ; i++) - { - fprintf (pf,"("); - WriteFloat (pf, w->p[i][0]); - WriteFloat (pf, w->p[i][1]); - WriteFloat (pf, w->p[i][2]); - fprintf (pf,") "); - } - fprintf (pf,"\n"); - } - else - { - fprintf (pf,"%i %i ",w->numpoints, p->nodes[1]->cluster); - for (i = w->numpoints-1; i >= 0; i--) - { - fprintf (pf,"("); - WriteFloat (pf, w->p[i][0]); - WriteFloat (pf, w->p[i][1]); - WriteFloat (pf, w->p[i][2]); - fprintf (pf,") "); - } - fprintf (pf,"\n"); - } - } - } -} - -/* -================ -NumberLeafs_r -================ -*/ -void NumberLeafs_r (node_t *node, int c) -{ -#if 0 - portal_t *p; -#endif - if ( node->planenum != PLANENUM_LEAF ) { - // decision node - node->cluster = -99; - - if(node->has_structural_children) - { -#if 0 - if(c >= 0) - Sys_FPrintf (SYS_ERR,"THIS CANNOT HAPPEN\n"); -#endif - NumberLeafs_r (node->children[0], c); - NumberLeafs_r (node->children[1], c); - } - else - { - if(c < 0) - c = num_visclusters++; - NumberLeafs_r (node->children[0], c); - NumberLeafs_r (node->children[1], c); - } - return; - } - - node->area = -1; - - if ( node->opaque ) { - // solid block, viewpoint never inside - node->cluster = -1; - return; - } - - if(c < 0) - c = num_visclusters++; - - node->cluster = c; - -#if 0 - // count the portals - for (p = node->portals ; p ; ) - { - if (p->nodes[0] == node) // only write out from first leaf - { - if (PortalPassable(p)) - num_visportals++; - else - num_solidfaces++; - p = p->next[0]; - } - else - { - if (!PortalPassable(p)) - num_solidfaces++; - p = p->next[1]; - } - } -#endif -} - - -/* -================ -NumberClusters -================ -*/ -void NumberClusters(tree_t *tree) { - num_visclusters = 0; - num_visportals = 0; - num_solidfaces = 0; - - Sys_FPrintf (SYS_VRB,"--- NumberClusters ---\n"); - - // set the cluster field in every leaf and count the total number of portals - NumberLeafs_r (tree->headnode, -1); - CountVisportals_r (tree->headnode); - CountSolidFaces_r (tree->headnode); - - Sys_FPrintf( SYS_VRB, "%9d visclusters\n", num_visclusters ); - Sys_FPrintf( SYS_VRB, "%9d visportals\n", num_visportals ); - Sys_FPrintf( SYS_VRB, "%9d solidfaces\n", num_solidfaces ); -} - -/* -================ -WritePortalFile -================ -*/ -void WritePortalFile (tree_t *tree) -{ - char filename[1024]; - - Sys_FPrintf (SYS_VRB,"--- WritePortalFile ---\n"); - - // write the file - sprintf (filename, "%s.prt", source); - Sys_Printf ("writing %s\n", filename); - pf = fopen (filename, "w"); - if (!pf) - Error ("Error opening %s", filename); - - fprintf (pf, "%s\n", PORTALFILE); - fprintf (pf, "%i\n", num_visclusters); - fprintf (pf, "%i\n", num_visportals); - fprintf (pf, "%i\n", num_solidfaces); - - WritePortalFile_r(tree->headnode); - WriteFaceFile_r(tree->headnode); - - fclose (pf); -} - diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.h b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.h deleted file mode 100644 index e912d15b..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.h +++ /dev/null @@ -1,2540 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#ifndef Q3MAP2_H -#define Q3MAP2_H - - - -/* version */ -#ifndef Q3MAP_VERSION -#error no Q3MAP_VERSION defined -#endif -#define Q3MAP_MOTD "Your map saw the pretty lights from q3map2's BFG" - - - - -/* ------------------------------------------------------------------------------- - -dependencies - -------------------------------------------------------------------------------- */ - -/* platform-specific */ -#if defined( __linux__ ) || defined( __APPLE__ ) - #define Q_UNIX -#endif - -#ifdef Q_UNIX - #include - #include - #include -#endif - -#ifdef WIN32 - #include -#endif - - -/* general */ -#include "version.h" /* ttimo: might want to guard that if built outside of the GtkRadiant tree */ - -#include "cmdlib.h" -#include "mathlib.h" -#include "md5lib.h" -#include "ddslib.h" - -#include "picomodel.h" - -#include "scriplib.h" -#include "polylib.h" -#include "imagelib.h" -#include "qthreads.h" -#include "inout.h" -#include "vfs.h" -#include "png.h" -#include "md4.h" -#include "radiant_jpeglib.h" -#include - - - -/* ------------------------------------------------------------------------------- - -port-related hacks - -------------------------------------------------------------------------------- */ - -#define MAC_STATIC_HACK 0 -#if defined( __APPLE__ ) && MAC_STATIC_HACK - #define MAC_STATIC static -#else - #define MAC_STATIC -#endif - -#if 1 - #ifdef WIN32 - #define Q_stricmp stricmp - #define Q_strncasecmp strnicmp - #else - #define Q_stricmp strcasecmp - #define Q_strncasecmp strncasecmp - #endif -#endif - -/* macro version */ -#define VectorMA( a, s, b, c ) ((c)[ 0 ] = (a)[ 0 ] + (s) * (b)[ 0 ], (c)[ 1 ] = (a)[ 1 ] + (s) * (b)[ 1 ], (c)[ 2 ] = (a)[ 2 ] + (s) * (b)[ 2 ]) - - - -/* ------------------------------------------------------------------------------- - -constants - -------------------------------------------------------------------------------- */ - -/* temporary hacks and tests (please keep off in SVN to prevent anyone's legacy map from screwing up) */ -/* 2011-01-10 TTimo says we should turn these on in SVN, so turning on now */ -#define Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES 1 -#define Q3MAP2_EXPERIMENTAL_SNAP_NORMAL_FIX 1 -#define Q3MAP2_EXPERIMENTAL_SNAP_PLANE_FIX 1 - -/* general */ -#define MAX_QPATH 64 - -#define MAX_IMAGES 512 -#define DEFAULT_IMAGE "*default" - -#define MAX_MODELS 512 - -#define DEF_BACKSPLASH_FRACTION 0.05f /* 5% backsplash by default */ -#define DEF_BACKSPLASH_DISTANCE 23 - -#define DEF_RADIOSITY_BOUNCE 1.0f /* ydnar: default to 100% re-emitted light */ - -#define MAX_SHADER_INFO 8192 -#define MAX_CUST_SURFACEPARMS 64 - -#define SHADER_MAX_VERTEXES 1000 -#define SHADER_MAX_INDEXES (6 * SHADER_MAX_VERTEXES) - -#define MAX_JITTERS 256 - - -/* epair parsing (note case-sensitivity directive) */ -#define CASE_INSENSITIVE_EPAIRS 1 - -#if CASE_INSENSITIVE_EPAIRS - #define EPAIR_STRCMP Q_stricmp -#else - #define EPAIR_STRCMP strcmp -#endif - - -/* ydnar: compiler flags, because games have widely varying content/surface flags */ -#define C_SOLID 0x00000001 -#define C_TRANSLUCENT 0x00000002 -#define C_STRUCTURAL 0x00000004 -#define C_HINT 0x00000008 -#define C_NODRAW 0x00000010 -#define C_LIGHTGRID 0x00000020 -#define C_ALPHASHADOW 0x00000040 -#define C_LIGHTFILTER 0x00000080 -#define C_VERTEXLIT 0x00000100 -#define C_LIQUID 0x00000200 -#define C_FOG 0x00000400 -#define C_SKY 0x00000800 -#define C_ORIGIN 0x00001000 -#define C_AREAPORTAL 0x00002000 -#define C_ANTIPORTAL 0x00004000 /* like hint, but doesn't generate portals */ -#define C_SKIP 0x00008000 /* like hint, but skips this face (doesn't split bsp) */ -#define C_NOMARKS 0x00010000 /* no decals */ -#define C_DETAIL 0x08000000 /* THIS MUST BE THE SAME AS IN RADIANT! */ - - -/* shadow flags */ -#define WORLDSPAWN_CAST_SHADOWS 1 -#define WORLDSPAWN_RECV_SHADOWS 1 -#define ENTITY_CAST_SHADOWS 0 -#define ENTITY_RECV_SHADOWS 1 - - -/* bsp */ -#define MAX_PATCH_SIZE 32 -#define MAX_BRUSH_SIDES 1024 -#define MAX_BUILD_SIDES 1024 - -#define MAX_EXPANDED_AXIS 128 - -#define CLIP_EPSILON 0.1f -#define PLANESIDE_EPSILON 0.001f -#define PLANENUM_LEAF -1 - -#define HINT_PRIORITY 1000 /* ydnar: force hint splits first and antiportal/areaportal splits last */ -#define ANTIPORTAL_PRIORITY -1000 -#define AREAPORTAL_PRIORITY -1000 -#define DETAIL_PRIORITY -3000 - -#define PSIDE_FRONT 1 -#define PSIDE_BACK 2 -#define PSIDE_BOTH (PSIDE_FRONT | PSIDE_BACK) -#define PSIDE_FACING 4 - -#define BPRIMIT_UNDEFINED 0 -#define BPRIMIT_OLDBRUSHES 1 -#define BPRIMIT_NEWBRUSHES 2 - - -/* vis */ -#define VIS_HEADER_SIZE 8 - -#define SEPERATORCACHE /* seperator caching helps a bit */ - -#define PORTALFILE "PRT1" - -#define MAX_PORTALS 0x20000 /* same as MAX_MAP_PORTALS */ -#define MAX_SEPERATORS MAX_POINTS_ON_WINDING -#define MAX_POINTS_ON_FIXED_WINDING 24 /* ydnar: increased this from 12 at the expense of more memory */ -#define MAX_PORTALS_ON_LEAF 1024 - - -/* light */ -#define EMIT_POINT 0 -#define EMIT_AREA 1 -#define EMIT_SPOT 2 -#define EMIT_SUN 3 - -#define LIGHT_ATTEN_LINEAR 1 -#define LIGHT_ATTEN_ANGLE 2 -#define LIGHT_ATTEN_DISTANCE 4 -#define LIGHT_TWOSIDED 8 -#define LIGHT_GRID 16 -#define LIGHT_SURFACES 32 -#define LIGHT_DARK 64 /* probably never use this */ -#define LIGHT_FAST 256 -#define LIGHT_FAST_TEMP 512 -#define LIGHT_FAST_ACTUAL (LIGHT_FAST | LIGHT_FAST_TEMP) -#define LIGHT_NEGATIVE 1024 -#define LIGHT_UNNORMALIZED 2048 /* vortex: do not normalize _color */ - -#define LIGHT_SUN_DEFAULT (LIGHT_ATTEN_ANGLE | LIGHT_GRID | LIGHT_SURFACES) -#define LIGHT_AREA_DEFAULT (LIGHT_ATTEN_ANGLE | LIGHT_ATTEN_DISTANCE | LIGHT_GRID | LIGHT_SURFACES) /* q3a and wolf are the same */ -#define LIGHT_Q3A_DEFAULT (LIGHT_ATTEN_ANGLE | LIGHT_ATTEN_DISTANCE | LIGHT_GRID | LIGHT_SURFACES | LIGHT_FAST) -#define LIGHT_WOLF_DEFAULT (LIGHT_ATTEN_LINEAR | LIGHT_ATTEN_DISTANCE | LIGHT_GRID | LIGHT_SURFACES | LIGHT_FAST) - -#define MAX_TRACE_TEST_NODES 256 -#define DEFAULT_INHIBIT_RADIUS 1.5f - -#define LUXEL_EPSILON 0.125f -#define VERTEX_EPSILON -0.125f -#define GRID_EPSILON 0.0f - -#define DEFAULT_LIGHTMAP_SAMPLE_SIZE 16 -#define DEFAULT_LIGHTMAP_MIN_SAMPLE_SIZE 0 -#define DEFAULT_LIGHTMAP_SAMPLE_OFFSET 1.0f -#define DEFAULT_SUBDIVIDE_THRESHOLD 1.0f - -#define EXTRA_SCALE 2 /* -extrawide = -super 2 */ -#define EXTRAWIDE_SCALE 2 /* -extrawide = -super 2 -filter */ - -#define CLUSTER_UNMAPPED -1 -#define CLUSTER_OCCLUDED -2 -#define CLUSTER_FLOODED -3 - -#define VERTEX_LUXEL_SIZE 3 -#define BSP_LUXEL_SIZE 3 -#define RAD_LUXEL_SIZE 3 -#define SUPER_LUXEL_SIZE 4 -#define SUPER_FLAG_SIZE 4 -#define FLAG_FORCE_SUBSAMPLING 1 -#define FLAG_ALREADY_SUBSAMPLED 2 -#define SUPER_ORIGIN_SIZE 3 -#define SUPER_NORMAL_SIZE 4 -#define SUPER_DELUXEL_SIZE 3 -#define BSP_DELUXEL_SIZE 3 -#define SUPER_FLOODLIGHT_SIZE 4 - -#define VERTEX_LUXEL( s, v ) (vertexLuxels[ s ] + ((v) * VERTEX_LUXEL_SIZE)) -#define RAD_VERTEX_LUXEL( s, v )(radVertexLuxels[ s ] + ((v) * VERTEX_LUXEL_SIZE)) -#define BSP_LUXEL( s, x, y ) (lm->bspLuxels[ s ] + ((((y) * lm->w) + (x)) * BSP_LUXEL_SIZE)) -#define RAD_LUXEL( s, x, y ) (lm->radLuxels[ s ] + ((((y) * lm->w) + (x)) * RAD_LUXEL_SIZE)) -#define SUPER_LUXEL( s, x, y ) (lm->superLuxels[ s ] + ((((y) * lm->sw) + (x)) * SUPER_LUXEL_SIZE)) -#define SUPER_FLAG( x, y ) (lm->superFlags + ((((y) * lm->sw) + (x)) * SUPER_FLAG_SIZE)) -#define SUPER_DELUXEL( x, y ) (lm->superDeluxels + ((((y) * lm->sw) + (x)) * SUPER_DELUXEL_SIZE)) -#define BSP_DELUXEL( x, y ) (lm->bspDeluxels + ((((y) * lm->w) + (x)) * BSP_DELUXEL_SIZE)) -#define SUPER_CLUSTER( x, y ) (lm->superClusters + (((y) * lm->sw) + (x))) -#define SUPER_ORIGIN( x, y ) (lm->superOrigins + ((((y) * lm->sw) + (x)) * SUPER_ORIGIN_SIZE)) -#define SUPER_NORMAL( x, y ) (lm->superNormals + ((((y) * lm->sw) + (x)) * SUPER_NORMAL_SIZE)) -#define SUPER_DIRT( x, y ) (lm->superNormals + ((((y) * lm->sw) + (x)) * SUPER_NORMAL_SIZE) + 3) /* stash dirtyness in normal[ 3 ] */ -#define SUPER_FLOODLIGHT( x, y ) (lm->superFloodLight + ((((y) * lm->sw) + (x)) * SUPER_FLOODLIGHT_SIZE) ) - - - -/* ------------------------------------------------------------------------------- - -abstracted bsp file - -------------------------------------------------------------------------------- */ - -#define EXTERNAL_LIGHTMAP "lm_%04d.tga" - -#define MAX_LIGHTMAPS 4 /* RBSP */ -#define MAX_LIGHT_STYLES 64 -#define MAX_SWITCHED_LIGHTS 32 -#define LS_NORMAL 0x00 -#define LS_UNUSED 0xFE -#define LS_NONE 0xFF - -#define MAX_LIGHTMAP_SHADERS 256 - -/* ok to increase these at the expense of more memory */ -#define MAX_MAP_ENTITIES 0x1000 //% 0x800 /* ydnar */ -#define MAX_MAP_ENTSTRING 0x80000 //% 0x40000 /* ydnar */ - -#define MAX_MAP_AREAS 0x100 /* MAX_MAP_AREA_BYTES in q_shared must match! */ -#define MAX_MAP_FOGS 30 //& 0x100 /* RBSP (32 - world fog - goggles) */ -#define MAX_MAP_LEAFS 0x20000 -#define MAX_MAP_PORTALS 0x20000 -#define MAX_MAP_LIGHTING 0x800000 -#define MAX_MAP_LIGHTGRID 0x100000 //% 0x800000 /* ydnar: set to points, not bytes */ -#define MAX_MAP_VISCLUSTERS 0x4000 // <= MAX_MAP_LEAFS -#define MAX_MAP_VISIBILITY (VIS_HEADER_SIZE + MAX_MAP_VISCLUSTERS * (((MAX_MAP_VISCLUSTERS + 63) & ~63) >> 3)) - -#define MAX_MAP_DRAW_SURFS 0x20000 -#define MAX_MAP_DRAW_INDEXES 0x80000 - -#define MAX_MAP_ADVERTISEMENTS 30 - -/* 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 void (*bspFunc)( const char * ); - - -typedef struct -{ - int offset, length; -} -bspLump_t; - - -typedef struct -{ - char ident[ 4 ]; - int version; - - bspLump_t lumps[ 100 ]; /* theoretical maximum # of bsp lumps */ -} -bspHeader_t; - - -typedef struct -{ - float mins[ 3 ], maxs[ 3 ]; - int firstBSPSurface, numBSPSurfaces; - int firstBSPBrush, numBSPBrushes; -} -bspModel_t; - - -typedef struct -{ - char shader[ MAX_QPATH ]; - int surfaceFlags; - int contentFlags; -} -bspShader_t; - - -/* planes x^1 is allways the opposite of plane x */ - -typedef struct -{ - float normal[ 3 ]; - float dist; -} -bspPlane_t; - - -typedef struct -{ - int planeNum; - int children[ 2 ]; /* negative numbers are -(leafs+1), not nodes */ - int mins[ 3 ]; /* for frustom culling */ - int maxs[ 3 ]; -} -bspNode_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 firstBSPLeafSurface; - int numBSPLeafSurfaces; - - int firstBSPLeafBrush; - int numBSPLeafBrushes; -} -bspLeaf_t; - - -typedef struct -{ - int planeNum; /* positive plane side faces out of the leaf */ - int shaderNum; - int surfaceNum; /* RBSP */ -} -bspBrushSide_t; - - -typedef struct -{ - int firstSide; - int numSides; - int shaderNum; /* the shader that determines the content flags */ -} -bspBrush_t; - - -typedef struct -{ - char shader[ MAX_QPATH ]; - int brushNum; - int visibleSide; /* the brush side that ray tests need to clip against (-1 == none) */ -} -bspFog_t; - - -typedef struct -{ - vec3_t xyz; - float st[ 2 ]; - float lightmap[ MAX_LIGHTMAPS ][ 2 ]; /* RBSP */ - vec3_t normal; - byte color[ MAX_LIGHTMAPS ][ 4 ]; /* RBSP */ -} -bspDrawVert_t; - - -typedef enum -{ - MST_BAD, - MST_PLANAR, - MST_PATCH, - MST_TRIANGLE_SOUP, - MST_FLARE, - MST_FOLIAGE -} -bspSurfaceType_t; - - -typedef struct bspGridPoint_s -{ - byte ambient[ MAX_LIGHTMAPS ][ 3 ]; - byte directed[ MAX_LIGHTMAPS ][ 3 ]; - byte styles[ MAX_LIGHTMAPS ]; - byte latLong[ 2 ]; -} -bspGridPoint_t; - - -typedef struct -{ - int shaderNum; - int fogNum; - int surfaceType; - - int firstVert; - int numVerts; - - int firstIndex; - int numIndexes; - - byte lightmapStyles[ MAX_LIGHTMAPS ]; /* RBSP */ - byte vertexStyles[ MAX_LIGHTMAPS ]; /* RBSP */ - int lightmapNum[ MAX_LIGHTMAPS ]; /* RBSP */ - int lightmapX[ MAX_LIGHTMAPS ], lightmapY[ MAX_LIGHTMAPS ]; /* RBSP */ - int lightmapWidth, lightmapHeight; - - vec3_t lightmapOrigin; - vec3_t lightmapVecs[ 3 ]; /* on patches, [ 0 ] and [ 1 ] are lodbounds */ - - int patchWidth; - int patchHeight; -} -bspDrawSurface_t; - - -/* advertisements */ -typedef struct { - int cellId; - vec3_t normal; - vec3_t rect[4]; - char model[ MAX_QPATH ]; -} bspAdvertisement_t; - - -/* ------------------------------------------------------------------------------- - -general types - -------------------------------------------------------------------------------- */ - -/* ydnar: for smaller structs */ -typedef unsigned char qb_t; - - -/* ydnar: for q3map_tcMod */ -typedef float tcMod_t[ 3 ][ 3 ]; - - -/* ydnar: for multiple game support */ -typedef struct surfaceParm_s -{ - char *name; - int contentFlags, contentFlagsClear; - int surfaceFlags, surfaceFlagsClear; - int compileFlags, compileFlagsClear; -} -surfaceParm_t; - -typedef enum -{ - MINIMAP_MODE_GRAY, - MINIMAP_MODE_BLACK, - MINIMAP_MODE_WHITE -} -miniMapMode_t; - -typedef struct game_s -{ - char *arg; /* -game matches this */ - char *gamePath; /* main game data dir */ - char *homeBasePath; /* home sub-dir on unix */ - char *magic; /* magic word for figuring out base path */ - char *shaderPath; /* shader directory */ - int maxLMSurfaceVerts; /* default maximum meta surface verts */ - int maxSurfaceVerts; /* default maximum surface verts */ - int maxSurfaceIndexes; /* default maximum surface indexes (tris * 3) */ - qboolean emitFlares; /* when true, emit flare surfaces */ - char *flareShader; /* default flare shader (MUST BE SET) */ - qboolean wolfLight; /* when true, lights work like wolf q3map */ - int lightmapSize; /* bsp lightmap width/height */ - float lightmapGamma; /* default lightmap gamma */ - float lightmapExposure; /* default lightmap exposure */ - float lightmapCompensate; /* default lightmap compensate value */ - float gridScale; /* vortex: default lightgrid scale (affects both directional and ambient spectres) */ - float gridAmbientScale; /* vortex: default lightgrid ambient spectre scale */ - qboolean lightAngleHL; /* jal: use half-lambert curve for light angle attenuation */ - qboolean noStyles; /* use lightstyles hack or not */ - qboolean keepLights; /* keep light entities on bsp */ - int patchSubdivisions; /* default patch subdivisions tolerance */ - qboolean patchShadows; /* patch casting enabled */ - qboolean deluxeMap; /* compile deluxemaps */ - int deluxeMode; /* deluxemap mode (0 - modelspace, 1 - tangentspace with renormalization, 2 - tangentspace without renormalization) */ - int miniMapSize; /* minimap size */ - float miniMapSharpen; /* minimap sharpening coefficient */ - float miniMapBorder; /* minimap border amount */ - qboolean miniMapKeepAspect; /* minimap keep aspect ratio by letterboxing */ - miniMapMode_t miniMapMode; /* minimap mode */ - char *miniMapNameFormat; /* minimap name format */ - char *bspIdent; /* 4-letter bsp file prefix */ - int bspVersion; /* bsp version to use */ - qboolean lumpSwap; /* cod-style len/ofs order */ - bspFunc load, write; /* load/write function pointers */ - surfaceParm_t surfaceParms[ 128 ]; /* surfaceparm array */ -} -game_t; - - -typedef struct image_s -{ - char *name, *filename; - int refCount; - int width, height; - byte *pixels; -} -image_t; - - -typedef struct sun_s -{ - struct sun_s *next; - vec3_t direction, color; - float photons, deviance, filterRadius; - int numSamples, style; -} -sun_t; - - -typedef struct surfaceModel_s -{ - struct surfaceModel_s *next; - char model[ MAX_QPATH ]; - float density, odds; - float minScale, maxScale; - float minAngle, maxAngle; - qboolean oriented; -} -surfaceModel_t; - - -/* ydnar/sd: foliage stuff for wolf et (engine-supported optimization of the above) */ -typedef struct foliage_s -{ - struct foliage_s *next; - char model[ MAX_QPATH ]; - float scale, density, odds; - qboolean inverseAlpha; -} -foliage_t; - -typedef struct foliageInstance_s -{ - vec3_t xyz, normal; -} -foliageInstance_t; - - -typedef struct remap_s -{ - struct remap_s *next; - char from[ 1024 ]; - char to[ MAX_QPATH ]; -} -remap_t; - -typedef struct skinfile_s -{ - struct skinfile_s *next; - char name[ 1024 ]; - char to[ MAX_QPATH ]; -} -skinfile_t; - - -/* wingdi.h hack, it's the same: 0 */ -#undef CM_NONE - -typedef enum -{ - CM_NONE, - CM_VOLUME, - CM_COLOR_SET, - CM_ALPHA_SET, - CM_COLOR_SCALE, - CM_ALPHA_SCALE, - CM_COLOR_DOT_PRODUCT, - CM_ALPHA_DOT_PRODUCT, - CM_COLOR_DOT_PRODUCT_SCALE, - CM_ALPHA_DOT_PRODUCT_SCALE, - CM_COLOR_DOT_PRODUCT_2, - CM_ALPHA_DOT_PRODUCT_2, - CM_COLOR_DOT_PRODUCT_2_SCALE, - CM_ALPHA_DOT_PRODUCT_2_SCALE -} -colorModType_t; - - -typedef struct colorMod_s -{ - struct colorMod_s *next; - colorModType_t type; - vec_t data[ 16 ]; -} -colorMod_t; - - -typedef enum -{ - IM_NONE, - IM_OPAQUE, - IM_MASKED, - IM_BLEND -} -implicitMap_t; - - -typedef struct shaderInfo_s -{ - char shader[ MAX_QPATH ]; - int surfaceFlags; - int contentFlags; - int compileFlags; - float value; /* light value */ - - char *flareShader; /* for light flares */ - char *damageShader; /* ydnar: sof2 damage shader name */ - char *backShader; /* for surfaces that generate different front and back passes */ - char *cloneShader; /* ydnar: for cloning of a surface */ - char *remapShader; /* ydnar: remap a shader in final stage */ - char *deprecateShader; /* vortex: shader is deprecated and replaced by this on use */ - - surfaceModel_t *surfaceModel; /* ydnar: for distribution of models */ - foliage_t *foliage; /* ydnar/splash damage: wolf et foliage */ - - float subdivisions; /* from a "tesssize xxx" */ - float backsplashFraction; /* floating point value, usually 0.05 */ - float backsplashDistance; /* default 16 */ - float lightSubdivide; /* default 999 */ - float lightFilterRadius; /* ydnar: lightmap filtering/blurring radius for lights created by this shader (default: 0) */ - - int lightmapSampleSize; /* lightmap sample size */ - float lightmapSampleOffset; /* ydnar: lightmap sample offset (default: 1.0) */ - - float bounceScale; /* ydnar: radiosity re-emission [0,1.0+] */ - float offset; /* ydnar: offset in units */ - float shadeAngleDegrees; /* ydnar: breaking angle for smooth shading (degrees) */ - - vec3_t mins, maxs; /* ydnar: for particle studio vertexDeform move support */ - - qb_t legacyTerrain; /* ydnar: enable legacy terrain crutches */ - qb_t indexed; /* ydnar: attempt to use indexmap (terrain alphamap style) */ - qb_t forceMeta; /* ydnar: force metasurface path */ - qb_t noClip; /* ydnar: don't clip into bsp, preserve original face winding */ - qb_t noFast; /* ydnar: supress fast lighting for surfaces with this shader */ - qb_t invert; /* ydnar: reverse facing */ - qb_t nonplanar; /* ydnar: for nonplanar meta surface merging */ - qb_t tcGen; /* ydnar: has explicit texcoord generation */ - vec3_t vecs[ 2 ]; /* ydnar: explicit texture vectors for [0,1] texture space */ - tcMod_t mod; /* ydnar: q3map_tcMod matrix for djbob :) */ - vec3_t lightmapAxis; /* ydnar: explicit lightmap axis projection */ - colorMod_t *colorMod; /* ydnar: q3map_rgb/color/alpha/Set/Mod support */ - - int furNumLayers; /* ydnar: number of fur layers */ - float furOffset; /* ydnar: offset of each layer */ - float furFade; /* ydnar: alpha fade amount per layer */ - - qb_t splotchFix; /* ydnar: filter splotches on lightmaps */ - - qb_t hasPasses; /* false if the shader doesn't define any rendering passes */ - qb_t globalTexture; /* don't normalize texture repeats */ - qb_t twoSided; /* cull none */ - qb_t autosprite; /* autosprite shaders will become point lights instead of area lights */ - qb_t polygonOffset; /* ydnar: don't face cull this or against this */ - qb_t patchShadows; /* have patches casting shadows when using -light for this surface */ - qb_t vertexShadows; /* shadows will be casted at this surface even when vertex lit */ - qb_t forceSunlight; /* force sun light at this surface even tho we might not calculate shadows in vertex lighting */ - qb_t notjunc; /* don't use this surface for tjunction fixing */ - qb_t fogParms; /* ydnar: has fogparms */ - qb_t noFog; /* ydnar: supress fogging */ - qb_t clipModel; /* ydnar: solid model hack */ - qb_t noVertexLight; /* ydnar: leave vertex color alone */ - qb_t noDirty; /* jal: do not apply the dirty pass to this surface */ - - byte styleMarker; /* ydnar: light styles hack */ - - float vertexScale; /* vertex light scale */ - - char skyParmsImageBase[ MAX_QPATH ]; /* ydnar: for skies */ - - char editorImagePath[ MAX_QPATH ]; /* use this image to generate texture coordinates */ - char lightImagePath[ MAX_QPATH ]; /* use this image to generate color / averageColor */ - char normalImagePath[ MAX_QPATH ]; /* ydnar: normalmap image for bumpmapping */ - - implicitMap_t implicitMap; /* ydnar: enemy territory implicit shaders */ - char implicitImagePath[ MAX_QPATH ]; - - image_t *shaderImage; - image_t *lightImage; - image_t *normalImage; - - float skyLightValue; /* ydnar */ - int skyLightIterations; /* ydnar */ - sun_t *sun; /* ydnar */ - - vec3_t color; /* normalized color */ - vec3_t averageColor; - byte lightStyle; - - /* vortex: per-surface floodlight */ - float floodlightDirectionScale; - vec3_t floodlightRGB; - float floodlightIntensity; - float floodlightDistance; - - qb_t lmMergable; /* ydnar */ - int lmCustomWidth, lmCustomHeight; /* ydnar */ - float lmBrightness; /* ydnar */ - float lmFilterRadius; /* ydnar: lightmap filtering/blurring radius for this shader (default: 0) */ - - int shaderWidth, shaderHeight; /* ydnar */ - float stFlat[ 2 ]; - - vec3_t fogDir; /* ydnar */ - - char *shaderText; /* ydnar */ - qb_t custom; - qb_t finished; -} -shaderInfo_t; - - - -/* ------------------------------------------------------------------------------- - -bsp structures - -------------------------------------------------------------------------------- */ - -typedef struct face_s -{ - struct face_s *next; - int planenum; - int priority; - //qboolean checked; - int compileFlags; - winding_t *w; -} -face_t; - - -typedef struct plane_s -{ - vec3_t normal; - vec_t dist; - int type; - int counter; - int hash_chain; -} -plane_t; - - -typedef struct side_s -{ - int planenum; - - int outputNum; /* set when the side is written to the file list */ - - float texMat[ 2 ][ 3 ]; /* brush primitive texture matrix */ - float vecs[ 2 ][ 4 ]; /* old-style texture coordinate mapping */ - - winding_t *winding; - winding_t *visibleHull; /* convex hull of all visible fragments */ - - shaderInfo_t *shaderInfo; - - int contentFlags; /* from shaderInfo */ - int surfaceFlags; /* from shaderInfo */ - int compileFlags; /* from shaderInfo */ - int value; /* from shaderInfo */ - - qboolean visible; /* choose visble planes first */ - qboolean bevel; /* don't ever use for bsp splitting, and don't bother making windings for it */ - qboolean culled; /* ydnar: face culling */ -} -side_t; - - -typedef struct sideRef_s -{ - struct sideRef_s *next; - side_t *side; -} -sideRef_t; - - -/* ydnar: generic index mapping for entities (natural extension of terrain texturing) */ -typedef struct indexMap_s -{ - int w, h, numLayers; - char name[ MAX_QPATH ], shader[ MAX_QPATH ]; - float offsets[ 256 ]; - byte *pixels; -} -indexMap_t; - - -typedef struct brush_s -{ - struct brush_s *next; - struct brush_s *nextColorModBrush; /* ydnar: colorMod volume brushes go here */ - struct brush_s *original; /* chopped up brushes will reference the originals */ - - int entityNum, brushNum;/* editor numbering */ - int outputNum; /* set when the brush is written to the file list */ - - /* ydnar: for shadowcasting entities */ - int castShadows; - int recvShadows; - - shaderInfo_t *contentShader; - shaderInfo_t *celShader; /* :) */ - - /* ydnar: gs mods */ - int lightmapSampleSize; /* jal : entity based _lightmapsamplesize */ - float lightmapScale; - float shadeAngleDegrees; /* jal : entity based _shadeangle */ - vec3_t eMins, eMaxs; - indexMap_t *im; - - int contentFlags; - int compileFlags; /* ydnar */ - qboolean detail; - qboolean opaque; - - int portalareas[ 2 ]; - - vec3_t mins, maxs; - int numsides; - - side_t sides[ 6 ]; /* variably sized */ -} -brush_t; - - -typedef struct fog_s -{ - shaderInfo_t *si; - brush_t *brush; - int visibleSide; /* the brush side that ray tests need to clip against (-1 == none) */ -} -fog_t; - - -typedef struct -{ - int width, height; - bspDrawVert_t *verts; -} -mesh_t; - - -typedef struct parseMesh_s -{ - struct parseMesh_s *next; - - int entityNum, brushNum; /* ydnar: editor numbering */ - - /* ydnar: for shadowcasting entities */ - int castShadows; - int recvShadows; - - mesh_t mesh; - shaderInfo_t *shaderInfo; - shaderInfo_t *celShader; /* :) */ - - /* ydnar: gs mods */ - int lightmapSampleSize; /* jal : entity based _lightmapsamplesize */ - float lightmapScale; - vec3_t eMins, eMaxs; - indexMap_t *im; - - /* grouping */ - qboolean grouped; - float longestCurve; - int maxIterations; -} -parseMesh_t; - - -/* - ydnar: the drawsurf struct was extended to allow for: - - non-convex planar surfaces - - non-planar brushface surfaces - - lightmapped terrain - - planar patches -*/ - -typedef enum -{ - /* ydnar: these match up exactly with bspSurfaceType_t */ - SURFACE_BAD, - SURFACE_FACE, - SURFACE_PATCH, - SURFACE_TRIANGLES, - SURFACE_FLARE, - SURFACE_FOLIAGE, /* wolf et */ - - /* ydnar: compiler-relevant surface types */ - SURFACE_FORCED_META, - SURFACE_META, - SURFACE_FOGHULL, - SURFACE_DECAL, - SURFACE_SHADER, - - NUM_SURFACE_TYPES -} -surfaceType_t; - -char *surfaceTypes[ NUM_SURFACE_TYPES ] -#ifndef MAIN_C - ; -#else - = - { - "SURFACE_BAD", - "SURFACE_FACE", - "SURFACE_PATCH", - "SURFACE_TRIANGLES", - "SURFACE_FLARE", - "SURFACE_FOLIAGE", - "SURFACE_FORCED_META", - "SURFACE_META", - "SURFACE_FOGHULL", - "SURFACE_DECAL", - "SURFACE_SHADER" - }; -#endif - - -/* ydnar: this struct needs an overhaul (again, heh) */ -typedef struct mapDrawSurface_s -{ - surfaceType_t type; - qboolean planar; - int outputNum; /* ydnar: to match this sort of thing up */ - - qboolean fur; /* ydnar: this is kind of a hack, but hey... */ - qboolean skybox; /* ydnar: yet another fun hack */ - qboolean backSide; /* ydnar: q3map_backShader support */ - - struct mapDrawSurface_s *parent; /* ydnar: for cloned (skybox) surfaces to share lighting data */ - struct mapDrawSurface_s *clone; /* ydnar: for cloned surfaces */ - struct mapDrawSurface_s *cel; /* ydnar: for cloned cel surfaces */ - - shaderInfo_t *shaderInfo; - shaderInfo_t *celShader; - brush_t *mapBrush; - parseMesh_t *mapMesh; - sideRef_t *sideRef; - - int fogNum; - - int numVerts; /* vertexes and triangles */ - bspDrawVert_t *verts; - int numIndexes; - int *indexes; - - int planeNum; - vec3_t lightmapOrigin; /* also used for flares */ - vec3_t lightmapVecs[ 3 ]; /* also used for flares */ - int lightStyle; /* used for flares */ - - /* ydnar: per-surface (per-entity, actually) lightmap sample size scaling */ - float lightmapScale; - - /* jal: per-surface (per-entity, actually) shadeangle */ - float shadeAngleDegrees; - - /* ydnar: surface classification */ - vec3_t mins, maxs; - vec3_t lightmapAxis; - int sampleSize; - - /* ydnar: shadow group support */ - int castShadows, recvShadows; - - /* ydnar: texture coordinate range monitoring for hardware with limited texcoord precision (in texel space) */ - float bias[ 2 ]; - int texMins[ 2 ], texMaxs[ 2 ], texRange[ 2 ]; - - /* ydnar: for patches */ - float longestCurve; - int maxIterations; - int patchWidth, patchHeight; - vec3_t bounds[ 2 ]; - - /* ydnar/sd: for foliage */ - int numFoliageInstances; - - /* ydnar: editor/useful numbering */ - int entityNum; - int surfaceNum; -} -mapDrawSurface_t; - - -typedef struct drawSurfRef_s -{ - struct drawSurfRef_s *nextRef; - int outputNum; -} -drawSurfRef_t; - - -/* ydnar: metasurfaces are constructed from lists of metatriangles so they can be merged in the best way */ -typedef struct metaTriangle_s -{ - shaderInfo_t *si; - side_t *side; - int entityNum, surfaceNum, planeNum, fogNum, sampleSize, castShadows, recvShadows; - float shadeAngleDegrees; - vec4_t plane; - vec3_t lightmapAxis; - int indexes[ 3 ]; -} -metaTriangle_t; - - -typedef struct epair_s -{ - struct epair_s *next; - char *key, *value; -} -epair_t; - - -typedef struct -{ - vec3_t origin; - brush_t *brushes, *lastBrush, *colorModBrushes; - parseMesh_t *patches; - int mapEntityNum, firstDrawSurf; - int firstBrush, numBrushes; /* only valid during BSP compile */ - epair_t *epairs; - vec3_t originbrush_origin; -} -entity_t; - - -typedef struct node_s -{ - /* both leafs and nodes */ - int planenum; /* -1 = leaf node */ - struct node_s *parent; - vec3_t mins, maxs; /* valid after portalization */ - brush_t *volume; /* one for each leaf/node */ - - /* nodes only */ - side_t *side; /* the side that created the node */ - struct node_s *children[ 2 ]; - int compileFlags; /* ydnar: hint, antiportal */ - int tinyportals; - vec3_t referencepoint; - - /* leafs only */ - qboolean opaque; /* view can never be inside */ - qboolean areaportal; - qboolean skybox; /* ydnar: a skybox leaf */ - qboolean sky; /* ydnar: a sky leaf */ - int cluster; /* for portalfile writing */ - int area; /* for areaportals */ - brush_t *brushlist; /* fragments of all brushes in this leaf */ - drawSurfRef_t *drawSurfReferences; - - int occupied; /* 1 or greater can reach entity */ - entity_t *occupant; /* for leak file testing */ - - struct portal_s *portals; /* also on nodes during construction */ - - qboolean has_structural_children; -} -node_t; - - -typedef struct portal_s -{ - plane_t plane; - node_t *onnode; /* NULL = outside box */ - node_t *nodes[ 2 ]; /* [ 0 ] = front side of plane */ - struct portal_s *next[ 2 ]; - winding_t *winding; - - qboolean sidefound; /* false if ->side hasn't been checked */ - int compileFlags; /* from original face that caused the split */ - side_t *side; /* NULL = non-visible */ -} -portal_t; - - -typedef struct -{ - node_t *headnode; - node_t outside_node; - vec3_t mins, maxs; -} -tree_t; - - - -/* ------------------------------------------------------------------------------- - -vis structures - -------------------------------------------------------------------------------- */ - -typedef struct -{ - vec3_t normal; - float dist; -} -visPlane_t; - - -typedef struct -{ - int numpoints; - vec3_t points[ MAX_POINTS_ON_FIXED_WINDING ]; /* variable sized */ -} -fixedWinding_t; - - -typedef struct passage_s -{ - struct passage_s *next; - byte cansee[ 1 ]; /* all portals that can be seen through this passage */ -} passage_t; - - -typedef enum -{ - stat_none, - stat_working, - stat_done -} -vstatus_t; - - -typedef struct -{ - int num; - qboolean hint; /* true if this portal was created from a hint splitter */ - qboolean removed; - visPlane_t plane; /* normal pointing into neighbor */ - int leaf; /* neighbor */ - - vec3_t origin; /* for fast clip testing */ - float radius; - - fixedWinding_t *winding; - vstatus_t status; - byte *portalfront; /* [portals], preliminary */ - byte *portalflood; /* [portals], intermediate */ - byte *portalvis; /* [portals], final */ - - int nummightsee; /* bit count on portalflood for sort */ - passage_t *passages; /* there are just as many passages as there */ - /* are portals in the leaf this portal leads */ -} -vportal_t; - - -typedef struct leaf_s -{ - int numportals; - int merged; - vportal_t *portals[MAX_PORTALS_ON_LEAF]; -} -leaf_t; - - -typedef struct pstack_s -{ - byte mightsee[ MAX_PORTALS / 8 ]; - struct pstack_s *next; - leaf_t *leaf; - vportal_t *portal; /* portal exiting */ - fixedWinding_t *source; - fixedWinding_t *pass; - - fixedWinding_t windings[ 3 ]; /* source, pass, temp in any order */ - int freewindings[ 3 ]; - - visPlane_t portalplane; - int depth; -#ifdef SEPERATORCACHE - visPlane_t seperators[ 2 ][ MAX_SEPERATORS ]; - int numseperators[ 2 ]; -#endif -} -pstack_t; - - -typedef struct -{ - vportal_t *base; - int c_chains; - pstack_t pstack_head; -} -threaddata_t; - - - -/* ------------------------------------------------------------------------------- - -light structures - -------------------------------------------------------------------------------- */ - -/* ydnar: new light struct with flags */ -typedef struct light_s -{ - struct light_s *next; - - int type; - int flags; /* ydnar: condensed all the booleans into one flags int */ - shaderInfo_t *si; - - vec3_t origin; - vec3_t normal; /* for surfaces, spotlights, and suns */ - float dist; /* plane location along normal */ - - float photons; - int style; - vec3_t color; - float radiusByDist; /* for spotlights */ - float fade; /* ydnar: from wolf, for linear lights */ - float angleScale; /* ydnar: stolen from vlight for K */ - float extraDist; /* "extra dimension" distance of the light, to kill hot spots */ - - float add; /* ydnar: used for area lights */ - float envelope; /* ydnar: units until falloff < tolerance */ - float envelope2; /* ydnar: envelope squared (tiny optimization) */ - vec3_t mins, maxs; /* ydnar: pvs envelope */ - int cluster; /* ydnar: cluster light falls into */ - - winding_t *w; - vec3_t emitColor; /* full out-of-gamut value */ - - float falloffTolerance; /* ydnar: minimum attenuation threshold */ - float filterRadius; /* ydnar: lightmap filter radius in world units, 0 == default */ -} -light_t; - - -typedef struct -{ - /* constant input */ - qboolean testOcclusion, forceSunlight, testAll; - int recvShadows; - - int numSurfaces; - int *surfaces; - - int numLights; - light_t **lights; - - qboolean twoSided; - - /* per-sample input */ - int cluster; - vec3_t origin, normal; - vec_t inhibitRadius; /* sphere in which occluding geometry is ignored */ - - /* per-light input */ - light_t *light; - vec3_t end; - - /* calculated input */ - vec3_t displacement, direction; - vec_t distance; - - /* input and output */ - vec3_t color; /* starts out at full color, may be reduced if transparent surfaces are crossed */ - vec3_t colorNoShadow; /* result color with no shadow casting */ - vec3_t directionContribution; /* result contribution to the deluxe map */ - - /* output */ - vec3_t hit; - int compileFlags; /* for determining surface compile flags traced through */ - qboolean passSolid; - qboolean opaque; - vec_t forceSubsampling; /* needs subsampling (alphashadow), value = max color contribution possible from it */ - - /* working data */ - int numTestNodes; - int testNodes[ MAX_TRACE_TEST_NODES ]; -} -trace_t; - - - -/* must be identical to bspDrawVert_t except for float color! */ -typedef struct -{ - vec3_t xyz; - float st[ 2 ]; - float lightmap[ MAX_LIGHTMAPS ][ 2 ]; - vec3_t normal; - float color[ MAX_LIGHTMAPS ][ 4 ]; -} -radVert_t; - - -typedef struct -{ - int numVerts; - radVert_t verts[ MAX_POINTS_ON_WINDING ]; -} -radWinding_t; - - -/* crutch for poor local allocations in win32 smp */ -typedef struct -{ - vec_t dists[ MAX_POINTS_ON_WINDING + 4 ]; - int sides[ MAX_POINTS_ON_WINDING + 4 ]; -} -clipWork_t; - - -/* ydnar: new lightmap handling code */ -typedef struct outLightmap_s -{ - int lightmapNum, extLightmapNum; - int customWidth, customHeight; - int numLightmaps; - int freeLuxels; - int numShaders; - shaderInfo_t *shaders[ MAX_LIGHTMAP_SHADERS ]; - byte *lightBits; - byte *bspLightBytes; - byte *bspDirBytes; -} -outLightmap_t; - - -typedef struct rawLightmap_s -{ - qboolean finished, splotchFix, wrap[ 2 ]; - int customWidth, customHeight; - float brightness; - float filterRadius; - - int firstLightSurface, numLightSurfaces; /* index into lightSurfaces */ - int numLightClusters, *lightClusters; - - int sampleSize, actualSampleSize, axisNum; - - /* vortex: per-surface floodlight */ - float floodlightDirectionScale; - vec3_t floodlightRGB; - float floodlightIntensity; - float floodlightDistance; - - int entityNum; - int recvShadows; - vec3_t mins, maxs, axis, origin, *vecs; - float *plane; - int w, h, sw, sh, used; - - qboolean solid[ MAX_LIGHTMAPS ]; - vec3_t solidColor[ MAX_LIGHTMAPS ]; - - int numStyledTwins; - struct rawLightmap_s *twins[ MAX_LIGHTMAPS ]; - - int outLightmapNums[ MAX_LIGHTMAPS ]; - int twinNums[ MAX_LIGHTMAPS ]; - int lightmapX[ MAX_LIGHTMAPS ], lightmapY[ MAX_LIGHTMAPS ]; - byte styles[ MAX_LIGHTMAPS ]; - float *bspLuxels[ MAX_LIGHTMAPS ]; - float *radLuxels[ MAX_LIGHTMAPS ]; - float *superLuxels[ MAX_LIGHTMAPS ]; - unsigned char *superFlags; - float *superOrigins; - float *superNormals; - int *superClusters; - - float *superDeluxels; /* average light direction */ - float *bspDeluxels; - float *superFloodLight; -} -rawLightmap_t; - - -typedef struct rawGridPoint_s -{ - vec3_t ambient[ MAX_LIGHTMAPS ]; - vec3_t directed[ MAX_LIGHTMAPS ]; - vec3_t dir; - byte styles[ MAX_LIGHTMAPS ]; -} -rawGridPoint_t; - - -typedef struct surfaceInfo_s -{ - int modelindex; - shaderInfo_t *si; - rawLightmap_t *lm; - int parentSurfaceNum, childSurfaceNum; - int entityNum, castShadows, recvShadows, sampleSize, patchIterations; - float longestCurve; - float *plane; - vec3_t axis, mins, maxs; - qboolean hasLightmap, approximated; - int firstSurfaceCluster, numSurfaceClusters; -} -surfaceInfo_t; - -/* ------------------------------------------------------------------------------- - -prototypes - -------------------------------------------------------------------------------- */ - -/* main.c */ -vec_t Random( void ); -int BSPInfo( int count, char **fileNames ); -int ScaleBSPMain( int argc, char **argv ); -int ConvertMain( int argc, char **argv ); - - -/* path_init.c */ -game_t *GetGame( char *arg ); -void InitPaths( int *argc, char **argv ); - - -/* bsp.c */ -int BSPMain( int argc, char **argv ); - - -/* convert_map.c */ -int ConvertBSPToMap( char *bspName ); -int ConvertBSPToMap_BP( char *bspName ); - - -/* convert_ase.c */ -int ConvertBSPToASE( char *bspName ); - -/* convert_obj.c */ -int ConvertBSPToOBJ( char *bspName ); - - -/* brush.c */ -sideRef_t *AllocSideRef( side_t *side, sideRef_t *next ); -int CountBrushList( brush_t *brushes ); -brush_t *AllocBrush( int numsides ); -void FreeBrush( brush_t *brushes ); -void FreeBrushList( brush_t *brushes ); -brush_t *CopyBrush( brush_t *brush ); -qboolean BoundBrush( brush_t *brush ); -qboolean CreateBrushWindings( brush_t *brush ); -brush_t *BrushFromBounds( vec3_t mins, vec3_t maxs ); -vec_t BrushVolume( brush_t *brush ); -void WriteBSPBrushMap( char *name, brush_t *list ); - -void FilterDetailBrushesIntoTree( entity_t *e, tree_t *tree ); -void FilterStructuralBrushesIntoTree( entity_t *e, tree_t *tree ); - -int BoxOnPlaneSide( vec3_t mins, vec3_t maxs, plane_t *plane ); -qboolean WindingIsTiny( winding_t *w ); - -void SplitBrush( brush_t *brush, int planenum, brush_t **front, brush_t **back); - -tree_t *AllocTree( void ); -node_t *AllocNode( void ); - - -/* mesh.c */ -void LerpDrawVert( bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *out ); -void LerpDrawVertAmount( bspDrawVert_t *a, bspDrawVert_t *b, float amount, bspDrawVert_t *out ); -void FreeMesh( mesh_t *m ); -mesh_t *CopyMesh( mesh_t *mesh ); -void PrintMesh( mesh_t *m ); -mesh_t *TransposeMesh( mesh_t *in ); -void InvertMesh( mesh_t *m ); -mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ); -int IterationsForCurve( float len, int subdivisions ); -mesh_t *SubdivideMesh2( mesh_t in, int iterations ); -mesh_t *SubdivideMeshQuads( mesh_t *in, float minLength, int maxsize, int *widthtable, int *heighttable ); -mesh_t *RemoveLinearMeshColumnsRows( mesh_t *in ); -void MakeMeshNormals( mesh_t in ); -void PutMeshOnCurve( mesh_t in ); - -void MakeNormalVectors( vec3_t forward, vec3_t right, vec3_t up ); - - -/* map.c */ -void LoadMapFile( char *filename, qboolean onlyLights, qboolean noCollapseGroups ); -int FindFloatPlane( vec3_t normal, vec_t dist, int numPoints, vec3_t *points ); -int PlaneTypeForNormal( vec3_t normal ); -void AddBrushBevels( void ); -brush_t *FinishBrush(qboolean noCollapseGroups); - - -/* portals.c */ -void MakeHeadnodePortals( tree_t *tree ); -void MakeNodePortal( node_t *node ); -void SplitNodePortals( node_t *node ); - -qboolean PortalPassable( portal_t *p ); - -qboolean FloodEntities( tree_t *tree ); -void FillOutside( node_t *headnode); -void FloodAreas( tree_t *tree); -face_t *VisibleFaces( entity_t *e, tree_t *tree ); -void FreePortal( portal_t *p ); - -void MakeTreePortals( tree_t *tree ); - - -/* leakfile.c */ -xmlNodePtr LeakFile( tree_t *tree ); - - -/* prtfile.c */ -void NumberClusters( tree_t *tree ); -void WritePortalFile( tree_t *tree ); - - -/* writebsp.c */ -void SetModelNumbers( void ); -void SetLightStyles( void ); - -int EmitShader( const char *shader, int *contentFlags, int *surfaceFlags ); - -void BeginBSPFile( void ); -void EndBSPFile( qboolean do_write ); -void EmitBrushes( brush_t *brushes, int *firstBrush, int *numBrushes ); -void EmitFogs( void ); - -void BeginModel( void ); -void EndModel( entity_t *e, node_t *headnode ); - - -/* tree.c */ -void FreeTree( tree_t *tree ); -void FreeTree_r( node_t *node ); -void PrintTree_r( node_t *node, int depth ); -void FreeTreePortals_r( node_t *node ); - - -/* patch.c */ -void ParsePatch( qboolean onlyLights ); -mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ); -void PatchMapDrawSurfs( entity_t *e ); -void TriangulatePatchSurface( entity_t *e , mapDrawSurface_t *ds ); - - -/* tjunction.c */ -void FixTJunctions( entity_t *e ); - - -/* fog.c */ -winding_t *WindingFromDrawSurf( mapDrawSurface_t *ds ); -void FogDrawSurfaces( entity_t *e ); -int FogForPoint( vec3_t point, float epsilon ); -int FogForBounds( vec3_t mins, vec3_t maxs, float epsilon ); -void CreateMapFogs( void ); - - -/* facebsp.c */ -face_t *MakeStructuralBSPFaceList( brush_t *list ); -face_t *MakeVisibleBSPFaceList( brush_t *list ); -tree_t *FaceBSP( face_t *list ); - - -/* model.c */ -void PicoPrintFunc( int level, const char *str ); -void PicoLoadFileFunc( const char *name, byte **buffer, int *bufSize ); -picoModel_t *FindModel( const char *name, int frame ); -picoModel_t *LoadModel( const char *name, int frame ); -void InsertModel( const char *name, int skin, int frame, m4x4_t transform, remap_t *remap, shaderInfo_t *celShader, int eNum, int castShadows, int recvShadows, int spawnFlags, float lightmapScale, int lightmapSampleSize, float shadeAngle ); -void AddTriangleModels( entity_t *e ); - - -/* surface.c */ -mapDrawSurface_t *AllocDrawSurface( surfaceType_t type ); -void FinishSurface( mapDrawSurface_t *ds ); -void StripFaceSurface( mapDrawSurface_t *ds ); -void MaxAreaFaceSurface( mapDrawSurface_t *ds ); -qboolean CalcSurfaceTextureRange( mapDrawSurface_t *ds ); -qboolean CalcLightmapAxis( vec3_t normal, vec3_t axis ); -void ClassifySurfaces( int numSurfs, mapDrawSurface_t *ds ); -void ClassifyEntitySurfaces( entity_t *e ); -void TidyEntitySurfaces( entity_t *e ); -mapDrawSurface_t *CloneSurface( mapDrawSurface_t *src, shaderInfo_t *si ); -mapDrawSurface_t *MakeCelSurface( mapDrawSurface_t *src, shaderInfo_t *si ); -qboolean IsTriangleDegenerate( bspDrawVert_t *points, int a, int b, int c ); -void ClearSurface( mapDrawSurface_t *ds ); -void AddEntitySurfaceModels( entity_t *e ); -mapDrawSurface_t *DrawSurfaceForSide( entity_t *e, brush_t *b, side_t *s, winding_t *w ); -mapDrawSurface_t *DrawSurfaceForMesh( entity_t *e, parseMesh_t *p, mesh_t *mesh ); -mapDrawSurface_t *DrawSurfaceForFlare( int entNum, vec3_t origin, vec3_t normal, vec3_t color, const char *flareShader, int lightStyle ); -mapDrawSurface_t *DrawSurfaceForShader( char *shader ); -void ClipSidesIntoTree( entity_t *e, tree_t *tree ); -void MakeDebugPortalSurfs( tree_t *tree ); -void MakeFogHullSurfs( entity_t *e, tree_t *tree, char *shader ); -void SubdivideFaceSurfaces( entity_t *e, tree_t *tree ); -void AddEntitySurfaceModels( entity_t *e ); -int AddSurfaceModels( mapDrawSurface_t *ds ); -void FilterDrawsurfsIntoTree( entity_t *e, tree_t *tree ); -void EmitPatchSurface( entity_t *e, mapDrawSurface_t *ds ); -void EmitTriangleSurface( mapDrawSurface_t *ds ); - - -/* surface_fur.c */ -void Fur( mapDrawSurface_t *src ); - - -/* surface_foliage.c */ -void Foliage( mapDrawSurface_t *src ); - - -/* ydnar: surface_meta.c */ -void ClearMetaTriangles( void ); -int FindMetaTriangle( metaTriangle_t *src, bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *c, int planeNum ); -void MakeEntityMetaTriangles( entity_t *e ); -void FixMetaTJunctions( void ); -void SmoothMetaTriangles( void ); -void MergeMetaTriangles( void ); -void EmitMetaStats(); // vortex: print meta statistics even in no-verbose mode - - -/* surface_extra.c */ -void SetDefaultSampleSize( int sampleSize ); - -void SetSurfaceExtra( mapDrawSurface_t *ds, int num ); - -shaderInfo_t *GetSurfaceExtraShaderInfo( int num ); -int GetSurfaceExtraParentSurfaceNum( int num ); -int GetSurfaceExtraEntityNum( int num ); -int GetSurfaceExtraCastShadows( int num ); -int GetSurfaceExtraRecvShadows( int num ); -int GetSurfaceExtraSampleSize( int num ); -int GetSurfaceExtraMinSampleSize( int num ); -float GetSurfaceExtraLongestCurve( int num ); -void GetSurfaceExtraLightmapAxis( int num, vec3_t lightmapAxis ); - -void WriteSurfaceExtraFile( const char *path ); -void LoadSurfaceExtraFile( const char *path ); - - -/* decals.c */ -void ProcessDecals( void ); -void MakeEntityDecals( entity_t *e ); - -/* map.c */ -void TextureAxisFromPlane( plane_t *pln, vec3_t xv, vec3_t yv ); - -/* brush_primit.c */ -void ComputeAxisBase( vec3_t normal, vec3_t texX, vec3_t texY); - - -/* vis.c */ -fixedWinding_t *NewFixedWinding( int points ); -int VisMain( int argc, char **argv ); - -/* visflow.c */ -int CountBits( byte *bits, int numbits ); -void PassageFlow( int portalnum ); -void CreatePassages( int portalnum ); -void PassageMemory( void ); -void BasePortalVis( int portalnum ); -void BetterPortalVis( int portalnum ); -void PortalFlow( int portalnum ); -void PassagePortalFlow( int portalnum ); - - - -/* light.c */ -float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w ); -int LightContributionToSample( trace_t *trace ); -void LightingAtSample( trace_t *trace, byte styles[ MAX_LIGHTMAPS ], vec3_t colors[ MAX_LIGHTMAPS ] ); -int LightContributionToPoint( trace_t *trace ); -int LightMain( int argc, char **argv ); - - -/* light_trace.c */ -void SetupTraceNodes( void ); -void TraceLine( trace_t *trace ); -float SetupTrace( trace_t *trace ); - - -/* light_bounce.c */ -qboolean RadSampleImage( byte *pixels, int width, int height, float st[ 2 ], float color[ 4 ] ); -void RadLightForTriangles( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ); -void RadLightForPatch( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ); -void RadCreateDiffuseLights( void ); -void RadFreeLights(); - - -/* light_ydnar.c */ -void ColorToBytes( const float *color, byte *colorBytes, float scale ); -void SmoothNormals( void ); - -void MapRawLightmap( int num ); - -void SetupDirt(); -float DirtForSample( trace_t *trace ); -void DirtyRawLightmap( int num ); - -void SetupFloodLight(); -void FloodlightRawLightmaps(); -void FloodlightIlluminateLightmap( rawLightmap_t *lm ); -float FloodLightForSample( trace_t *trace , float floodLightDistance, qboolean floodLightLowQuality); -void FloodLightRawLightmap( int num ); - -void IlluminateRawLightmap( int num ); -void IlluminateVertexes( int num ); - -void SetupBrushes( void ); -void SetupClusters( void ); -qboolean ClusterVisible( int a, int b ); -qboolean ClusterVisibleToPoint( vec3_t point, int cluster ); -int ClusterForPoint( vec3_t point ); -int ClusterForPointExt( vec3_t point, float epsilon ); -int ClusterForPointExtFilter( vec3_t point, float epsilon, int numClusters, int *clusters ); -int ShaderForPointInLeaf( vec3_t point, int leafNum, float epsilon, int wantContentFlags, int wantSurfaceFlags, int *contentFlags, int *surfaceFlags ); -void SetupEnvelopes( qboolean forGrid, qboolean fastFlag ); -void FreeTraceLights( trace_t *trace ); -void CreateTraceLightsForBounds( vec3_t mins, vec3_t maxs, vec3_t normal, int numClusters, int *clusters, int flags, trace_t *trace ); -void CreateTraceLightsForSurface( int num, trace_t *trace ); - - -/* lightmaps_ydnar.c */ -void ExportLightmaps( void ); - -int ExportLightmapsMain( int argc, char **argv ); -int ImportLightmapsMain( int argc, char **argv ); - -void SetupSurfaceLightmaps( void ); -void StitchSurfaceLightmaps( void ); -void StoreSurfaceLightmaps( void ); - - -/* image.c */ -void ImageFree( image_t *image ); -image_t *ImageFind( const char *filename ); -image_t *ImageLoad( const char *filename ); - - -/* shaders.c */ -void ColorMod( colorMod_t *am, int numVerts, bspDrawVert_t *drawVerts ); - -void TCMod( tcMod_t mod, float st[ 2 ] ); -void TCModIdentity( tcMod_t mod ); -void TCModMultiply( tcMod_t a, tcMod_t b, tcMod_t out ); -void TCModTranslate( tcMod_t mod, float s, float t ); -void TCModScale( tcMod_t mod, float s, float t ); -void TCModRotate( tcMod_t mod, float euler ); - -qboolean ApplySurfaceParm( char *name, int *contentFlags, int *surfaceFlags, int *compileFlags ); - -void BeginMapShaderFile( const char *mapFile ); -void WriteMapShaderFile( void ); -shaderInfo_t *CustomShader( shaderInfo_t *si, char *find, char *replace ); -void EmitVertexRemapShader( char *from, char *to ); - -void LoadShaderInfo( void ); -shaderInfo_t *ShaderInfoForShader( const char *shader ); - - -/* bspfile_abstract.c */ -void SetGridPoints( int n ); -void SetDrawVerts( int n ); -void IncDrawVerts(); -void SetDrawSurfaces(int n); -void SetDrawSurfacesBuffer(); -void BSPFilesCleanup(); - -void SwapBlock( int *block, int size ); - -int GetLumpElements( bspHeader_t *header, int lump, int size ); -void *GetLump( bspHeader_t *header, int lump ); -int CopyLump( bspHeader_t *header, int lump, void *dest, int size ); -int CopyLump_Allocate( bspHeader_t *header, int lump, void **dest, int size, int *allocationVariable ); -void AddLump( FILE *file, bspHeader_t *header, int lumpNum, const void *data, int length ); - -void LoadBSPFile( const char *filename ); -void WriteBSPFile( const char *filename ); -void PrintBSPFileSizes( void ); - -epair_t *ParseEPair( void ); -void ParseEntities( void ); -void UnparseEntities( void ); -void PrintEntity( const entity_t *ent ); -void SetKeyValue( entity_t *ent, const char *key, const char *value ); -qboolean KeyExists( const entity_t *ent, const char *key ); /* VorteX: check if key exists */ -const char *ValueForKey( const entity_t *ent, const char *key ); -int IntForKey( const entity_t *ent, const char *key ); -vec_t FloatForKey( const entity_t *ent, const char *key ); -void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ); -entity_t *FindTargetEntity( const char *target ); -void GetEntityShadowFlags( const entity_t *ent, const entity_t *ent2, int *castShadows, int *recvShadows ); -void InjectCommandLine(char **argv, int beginArgs, int endArgs); - - - -/* bspfile_ibsp.c */ -void LoadIBSPFile( const char *filename ); -void WriteIBSPFile( const char *filename ); - - -/* bspfile_rbsp.c */ -void LoadRBSPFile( const char *filename ); -void WriteRBSPFile( const char *filename ); - - - -/* ------------------------------------------------------------------------------- - -bsp/general global variables - -------------------------------------------------------------------------------- */ - -#ifdef MAIN_C - #define Q_EXTERN - #define Q_ASSIGN( a ) = a -#else - #define Q_EXTERN extern - #define Q_ASSIGN( a ) -#endif - -/* game support */ -Q_EXTERN game_t games[] -#ifndef MAIN_C - ; -#else - = - { - #include "game_quake3.h" - , - #include "game_quakelive.h"/* most be after game_quake3.h as they share defines! */ - , - #include "game_nexuiz.h"/* most be after game_quake3.h as they share defines! */ - , - #include "game_xonotic.h"/* most be after game_quake3.h as they share defines! */ - , - #include "game_tremulous.h" /*LinuxManMikeC: must be after game_quake3.h, depends on #define's set in it */ - , - #include "game_tenebrae.h" - , - #include "game_wolf.h" - , - #include "game_wolfet.h"/* most be after game_wolf.h as they share defines! */ - , - #include "game_etut.h" - , - #include "game_ef.h" - , - #include "game_sof2.h" - , - #include "game_jk2.h" /* most be after game_sof2.h as they share defines! */ - , - #include "game_ja.h" /* most be after game_jk2.h as they share defines! */ - , - #include "game_qfusion.h" /* qfusion game */ - , - #include "game_reaction.h" /* must be after game_quake3.h */ - , - #include "game_darkplaces.h" /* vortex: darkplaces q1 engine */ - , - #include "game_dq.h" /* vortex: deluxe quake game ( darkplaces q1 engine) */ - , - #include "game_prophecy.h" /* vortex: prophecy game ( darkplaces q1 engine) */ - , - #include "game__null.h" /* null game (must be last item) */ - }; -#endif -Q_EXTERN game_t *game Q_ASSIGN( &games[ 0 ] ); - - -/* general */ -Q_EXTERN int numImages Q_ASSIGN( 0 ); -Q_EXTERN image_t images[ MAX_IMAGES ]; - -Q_EXTERN int numPicoModels Q_ASSIGN( 0 ); -Q_EXTERN picoModel_t *picoModels[ MAX_MODELS ]; - -Q_EXTERN shaderInfo_t *shaderInfo Q_ASSIGN( NULL ); -Q_EXTERN int numShaderInfo Q_ASSIGN( 0 ); -Q_EXTERN int numVertexRemaps Q_ASSIGN( 0 ); - -Q_EXTERN surfaceParm_t custSurfaceParms[ MAX_CUST_SURFACEPARMS ]; -Q_EXTERN int numCustSurfaceParms Q_ASSIGN( 0 ); - -Q_EXTERN char mapName[ MAX_QPATH ]; /* ydnar: per-map custom shaders for larger lightmaps */ -Q_EXTERN char mapShaderFile[ 1024 ]; -Q_EXTERN qboolean warnImage Q_ASSIGN( qtrue ); - -/* ydnar: sinusoid samples */ -Q_EXTERN float jitters[ MAX_JITTERS ]; - - -/* commandline arguments */ -Q_EXTERN qboolean verbose; -Q_EXTERN qboolean verboseEntities Q_ASSIGN( qfalse ); -Q_EXTERN qboolean force Q_ASSIGN( qfalse ); -Q_EXTERN qboolean infoMode Q_ASSIGN( qfalse ); -Q_EXTERN qboolean useCustomInfoParms Q_ASSIGN( qfalse ); -Q_EXTERN qboolean noprune Q_ASSIGN( qfalse ); -Q_EXTERN qboolean leaktest Q_ASSIGN( qfalse ); -Q_EXTERN qboolean nodetail Q_ASSIGN( qfalse ); -Q_EXTERN qboolean nosubdivide Q_ASSIGN( qfalse ); -Q_EXTERN qboolean notjunc Q_ASSIGN( qfalse ); -Q_EXTERN qboolean fulldetail Q_ASSIGN( qfalse ); -Q_EXTERN qboolean nowater Q_ASSIGN( qfalse ); -Q_EXTERN qboolean noCurveBrushes Q_ASSIGN( qfalse ); -Q_EXTERN qboolean fakemap Q_ASSIGN( qfalse ); -Q_EXTERN qboolean coplanar Q_ASSIGN( qfalse ); -Q_EXTERN qboolean nofog Q_ASSIGN( qfalse ); -Q_EXTERN qboolean noHint Q_ASSIGN( qfalse ); /* ydnar */ -Q_EXTERN qboolean renameModelShaders Q_ASSIGN( qfalse ); /* ydnar */ -Q_EXTERN qboolean skyFixHack Q_ASSIGN( qfalse ); /* ydnar */ -Q_EXTERN qboolean bspAlternateSplitWeights Q_ASSIGN( qfalse ); /* 27 */ -Q_EXTERN qboolean deepBSP Q_ASSIGN( qfalse ); /* div0 */ -Q_EXTERN qboolean maxAreaFaceSurface Q_ASSIGN( qfalse ); /* divVerent */ - -Q_EXTERN int patchSubdivisions Q_ASSIGN( 8 ); /* ydnar: -patchmeta subdivisions */ - -Q_EXTERN int maxLMSurfaceVerts Q_ASSIGN( 64 ); /* ydnar */ -Q_EXTERN int maxSurfaceVerts Q_ASSIGN( 999 ); /* ydnar */ -Q_EXTERN int maxSurfaceIndexes Q_ASSIGN( 6000 ); /* ydnar */ -Q_EXTERN float npDegrees Q_ASSIGN( 0.0f ); /* ydnar: nonplanar degrees */ -Q_EXTERN int bevelSnap Q_ASSIGN( 0 ); /* ydnar: bevel plane snap */ -Q_EXTERN int texRange Q_ASSIGN( 0 ); -Q_EXTERN qboolean flat Q_ASSIGN( qfalse ); -Q_EXTERN qboolean meta Q_ASSIGN( qfalse ); -Q_EXTERN qboolean patchMeta Q_ASSIGN( qfalse ); -Q_EXTERN qboolean emitFlares Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugSurfaces Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugInset Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugPortals Q_ASSIGN( qfalse ); -Q_EXTERN qboolean lightmapTriangleCheck Q_ASSIGN(qfalse); -Q_EXTERN qboolean lightmapExtraVisClusterNudge Q_ASSIGN(qfalse); -Q_EXTERN qboolean lightmapFill Q_ASSIGN(qfalse); - -#if Q3MAP2_EXPERIMENTAL_SNAP_NORMAL_FIX -// Increasing the normalEpsilon to compensate for new logic in SnapNormal(), where -// this epsilon is now used to compare against 0 components instead of the 1 or -1 -// components. Unfortunately, normalEpsilon is also used in PlaneEqual(). So changing -// this will affect anything that calls PlaneEqual() as well (which are, at the time -// of this writing, FindFloatPlane() and AddBrushBevels()). -Q_EXTERN double normalEpsilon Q_ASSIGN(0.00005); -#else -Q_EXTERN double normalEpsilon Q_ASSIGN( 0.00001 ); -#endif - -#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES -// NOTE: This distanceEpsilon is too small if parts of the map are at maximum world -// extents (in the range of plus or minus 2^16). The smallest epsilon at values -// close to 2^16 is about 0.007, which is greater than distanceEpsilon. Therefore, -// maps should be constrained to about 2^15, otherwise slightly undesirable effects -// may result. The 0.01 distanceEpsilon used previously is just too coarse in my -// opinion. The real fix for this problem is to have 64 bit distances and then make -// this epsilon even smaller, or to constrain world coordinates to plus minus 2^15 -// (or even 2^14). -Q_EXTERN double distanceEpsilon Q_ASSIGN(0.005); -#else -Q_EXTERN double distanceEpsilon Q_ASSIGN( 0.01 ); -#endif - - -/* bsp */ -Q_EXTERN int numMapEntities Q_ASSIGN( 0 ); - -Q_EXTERN int blockSize[ 3 ] /* should be the same as in radiant */ -#ifndef MAIN_C - ; -#else - = { 1024, 1024, 1024 }; -#endif - -Q_EXTERN char name[ 1024 ]; -Q_EXTERN char source[ 1024 ]; -Q_EXTERN char outbase[ 32 ]; - -Q_EXTERN int sampleSize; /* lightmap sample size in units */ -Q_EXTERN int minSampleSize; /* minimum sample size to use at all */ -Q_EXTERN int sampleScale; /* vortex: lightmap sample scale (ie quality)*/ - -Q_EXTERN int mapEntityNum Q_ASSIGN( 0 ); - -Q_EXTERN int entitySourceBrushes; - -Q_EXTERN plane_t *mapplanes Q_ASSIGN(NULL); /* mapplanes[ num ^ 1 ] will always be the mirror or mapplanes[ num ] */ -Q_EXTERN int nummapplanes Q_ASSIGN(0); /* nummapplanes will always be even */ -Q_EXTERN int allocatedmapplanes Q_ASSIGN(0); -Q_EXTERN int numMapPatches; -Q_EXTERN vec3_t mapMins, mapMaxs; - -Q_EXTERN int defaultFogNum Q_ASSIGN( -1 ); /* ydnar: cleaner fog handling */ -Q_EXTERN int numMapFogs Q_ASSIGN( 0 ); -Q_EXTERN fog_t mapFogs[ MAX_MAP_FOGS ]; - -Q_EXTERN entity_t *mapEnt; -Q_EXTERN brush_t *buildBrush; -Q_EXTERN int numActiveBrushes; -Q_EXTERN int g_bBrushPrimit; - -Q_EXTERN int numStrippedLights Q_ASSIGN( 0 ); - - -/* surface stuff */ -Q_EXTERN mapDrawSurface_t *mapDrawSurfs Q_ASSIGN( NULL ); -Q_EXTERN int numMapDrawSurfs; - -Q_EXTERN int numSurfacesByType[ NUM_SURFACE_TYPES ]; -Q_EXTERN int numClearedSurfaces; -Q_EXTERN int numStripSurfaces; -Q_EXTERN int numMaxAreaSurfaces; -Q_EXTERN int numFanSurfaces; -Q_EXTERN int numMergedSurfaces; -Q_EXTERN int numMergedVerts; - -Q_EXTERN int numRedundantIndexes; - -Q_EXTERN int numSurfaceModels Q_ASSIGN( 0 ); - -Q_EXTERN byte debugColors[ 12 ][ 3 ] -#ifndef MAIN_C - ; -#else - = - { - { 255, 0, 0 }, - { 192, 128, 128 }, - { 255, 255, 0 }, - { 192, 192, 128 }, - { 0, 255, 255 }, - { 128, 192, 192 }, - { 0, 0, 255 }, - { 128, 128, 192 }, - { 255, 0, 255 }, - { 192, 128, 192 }, - { 0, 255, 0 }, - { 128, 192, 128 } - }; -#endif - -Q_EXTERN qboolean skyboxPresent Q_ASSIGN( qfalse ); -Q_EXTERN int skyboxArea Q_ASSIGN( -1 ); -Q_EXTERN m4x4_t skyboxTransform; - - - -/* ------------------------------------------------------------------------------- - -vis global variables - -------------------------------------------------------------------------------- */ - -/* commandline arguments */ -Q_EXTERN qboolean fastvis; -Q_EXTERN qboolean noPassageVis; -Q_EXTERN qboolean passageVisOnly; -Q_EXTERN qboolean mergevis; -Q_EXTERN qboolean mergevisportals; -Q_EXTERN qboolean nosort; -Q_EXTERN qboolean saveprt; -Q_EXTERN qboolean hint; /* ydnar */ -Q_EXTERN char inbase[ MAX_QPATH ]; -Q_EXTERN char globalCelShader[ MAX_QPATH ]; - -Q_EXTERN float farPlaneDist; /* rr2do2, rf, mre, ydnar all contributed to this one... */ - -Q_EXTERN int numportals; -Q_EXTERN int portalclusters; - -Q_EXTERN vportal_t *portals; -Q_EXTERN leaf_t *leafs; - -Q_EXTERN vportal_t *faces; -Q_EXTERN leaf_t *faceleafs; - -Q_EXTERN int numfaces; - -Q_EXTERN int c_portaltest, c_portalpass, c_portalcheck; -Q_EXTERN int c_portalskip, c_leafskip; -Q_EXTERN int c_vistest, c_mighttest; -Q_EXTERN int c_chains; - -Q_EXTERN byte *vismap, *vismap_p, *vismap_end; - -Q_EXTERN int testlevel; - -Q_EXTERN byte *uncompressed; - -Q_EXTERN int leafbytes, leaflongs; -Q_EXTERN int portalbytes, portallongs; - -Q_EXTERN vportal_t *sorted_portals[ MAX_MAP_PORTALS * 2 ]; - - - -/* ------------------------------------------------------------------------------- - -light global variables - -------------------------------------------------------------------------------- */ - -/* commandline arguments */ -Q_EXTERN qboolean wolfLight Q_ASSIGN( qfalse ); -Q_EXTERN float extraDist Q_ASSIGN( 0.0f ); -Q_EXTERN qboolean loMem Q_ASSIGN( qfalse ); -Q_EXTERN qboolean noStyles Q_ASSIGN( qfalse ); -Q_EXTERN qboolean keepLights Q_ASSIGN( qfalse ); - -Q_EXTERN int sampleSize Q_ASSIGN( DEFAULT_LIGHTMAP_SAMPLE_SIZE ); -Q_EXTERN int minSampleSize Q_ASSIGN( DEFAULT_LIGHTMAP_MIN_SAMPLE_SIZE ); -Q_EXTERN qboolean noVertexLighting Q_ASSIGN( qfalse ); -Q_EXTERN qboolean noGridLighting Q_ASSIGN( qfalse ); - -Q_EXTERN qboolean noTrace Q_ASSIGN( qfalse ); -Q_EXTERN qboolean noSurfaces Q_ASSIGN( qfalse ); -Q_EXTERN qboolean patchShadows Q_ASSIGN( qfalse ); -Q_EXTERN qboolean cpmaHack Q_ASSIGN( qfalse ); - -Q_EXTERN qboolean deluxemap Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugDeluxemap Q_ASSIGN( qfalse ); -Q_EXTERN int deluxemode Q_ASSIGN( 0 ); /* deluxemap format (0 - modelspace, 1 - tangentspace with renormalization, 2 - tangentspace without renormalization) */ - -Q_EXTERN qboolean fast Q_ASSIGN( qfalse ); -Q_EXTERN qboolean faster Q_ASSIGN( qfalse ); -Q_EXTERN qboolean fastgrid Q_ASSIGN( qfalse ); -Q_EXTERN qboolean fastbounce Q_ASSIGN( qfalse ); -Q_EXTERN qboolean cheap Q_ASSIGN( qfalse ); -Q_EXTERN qboolean cheapgrid Q_ASSIGN( qfalse ); -Q_EXTERN int bounce Q_ASSIGN( 0 ); -Q_EXTERN qboolean bounceOnly Q_ASSIGN( qfalse ); -Q_EXTERN qboolean bouncing Q_ASSIGN( qfalse ); -Q_EXTERN qboolean bouncegrid Q_ASSIGN( qfalse ); -Q_EXTERN qboolean normalmap Q_ASSIGN( qfalse ); -Q_EXTERN qboolean trisoup Q_ASSIGN( qfalse ); -Q_EXTERN qboolean shade Q_ASSIGN( qfalse ); -Q_EXTERN float shadeAngleDegrees Q_ASSIGN( 0.0f ); -Q_EXTERN int superSample Q_ASSIGN( 0 ); -Q_EXTERN int lightSamples Q_ASSIGN( 1 ); -Q_EXTERN qboolean lightRandomSamples Q_ASSIGN( qfalse ); -Q_EXTERN int lightSamplesSearchBoxSize Q_ASSIGN( 1 ); -Q_EXTERN qboolean filter Q_ASSIGN( qfalse ); -Q_EXTERN qboolean dark Q_ASSIGN( qfalse ); -Q_EXTERN qboolean sunOnly Q_ASSIGN( qfalse ); -Q_EXTERN int approximateTolerance Q_ASSIGN( 0 ); -Q_EXTERN qboolean noCollapse Q_ASSIGN( qfalse ); -Q_EXTERN int lightmapSearchBlockSize Q_ASSIGN( 0 ); -Q_EXTERN qboolean exportLightmaps Q_ASSIGN( qfalse ); -Q_EXTERN qboolean externalLightmaps Q_ASSIGN( qfalse ); -Q_EXTERN int lmCustomSize Q_ASSIGN( LIGHTMAP_WIDTH ); -Q_EXTERN char * lmCustomDir Q_ASSIGN( NULL ); -Q_EXTERN int lmLimitSize Q_ASSIGN( 0 ); - -Q_EXTERN qboolean dirty Q_ASSIGN( qfalse ); -Q_EXTERN qboolean dirtDebug Q_ASSIGN( qfalse ); -Q_EXTERN int dirtMode Q_ASSIGN( 0 ); -Q_EXTERN float dirtDepth Q_ASSIGN( 128.0f ); -Q_EXTERN float dirtScale Q_ASSIGN( 1.0f ); -Q_EXTERN float dirtGain Q_ASSIGN( 1.0f ); - -/* 27: floodlighting */ -Q_EXTERN qboolean debugnormals Q_ASSIGN( qfalse ); -Q_EXTERN qboolean floodlighty Q_ASSIGN( qfalse ); -Q_EXTERN qboolean floodlight_lowquality Q_ASSIGN( qfalse ); -Q_EXTERN vec3_t floodlightRGB; -Q_EXTERN float floodlightIntensity Q_ASSIGN( 512.0f ); -Q_EXTERN float floodlightDistance Q_ASSIGN( 1024.0f ); -Q_EXTERN float floodlightDirectionScale Q_ASSIGN( 1.0f ); - -Q_EXTERN qboolean dump Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debug Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugUnused Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugAxis Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugCluster Q_ASSIGN( qfalse ); -Q_EXTERN qboolean debugOrigin Q_ASSIGN( qfalse ); -Q_EXTERN qboolean lightmapBorder Q_ASSIGN( qfalse ); - -/* longest distance across the map */ -Q_EXTERN float maxMapDistance Q_ASSIGN( 0 ); - -/* for run time tweaking of light sources */ -Q_EXTERN float pointScale Q_ASSIGN( 7500.0f ); -Q_EXTERN float areaScale Q_ASSIGN( 0.25f ); -Q_EXTERN float skyScale Q_ASSIGN( 1.0f ); -Q_EXTERN float bounceScale Q_ASSIGN( 0.25f ); - -/* jal: alternative angle attenuation curve */ -Q_EXTERN qboolean lightAngleHL Q_ASSIGN( qfalse ); - -/* vortex: gridscale and gridambientscale */ -Q_EXTERN float gridScale Q_ASSIGN( 1.0f ); -Q_EXTERN float gridAmbientScale Q_ASSIGN( 1.0f ); -Q_EXTERN float gridDirectionality Q_ASSIGN( 1.0f ); -Q_EXTERN float gridAmbientDirectionality Q_ASSIGN( 0.0f ); -Q_EXTERN qboolean inGrid Q_ASSIGN(0); - -/* ydnar: lightmap gamma/compensation */ -Q_EXTERN float lightmapGamma Q_ASSIGN( 1.0f ); -Q_EXTERN float lightmapExposure Q_ASSIGN( 1.0f ); -Q_EXTERN float lightmapCompensate Q_ASSIGN( 1.0f ); - -/* ydnar: for runtime tweaking of falloff tolerance */ -Q_EXTERN float falloffTolerance Q_ASSIGN( 1.0f ); -Q_EXTERN qboolean exactPointToPolygon Q_ASSIGN( qtrue ); -Q_EXTERN float formFactorValueScale Q_ASSIGN( 3.0f ); -Q_EXTERN float linearScale Q_ASSIGN( 1.0f / 8000.0f ); - -// for .ase conversion -Q_EXTERN qboolean shadersAsBitmap Q_ASSIGN( qfalse ); -Q_EXTERN qboolean lightmapsAsTexcoord Q_ASSIGN( qfalse ); - -Q_EXTERN light_t *lights; -Q_EXTERN int numPointLights; -Q_EXTERN int numSpotLights; -Q_EXTERN int numSunLights; -Q_EXTERN int numAreaLights; - -/* ydnar: for luxel placement */ -Q_EXTERN int numSurfaceClusters, maxSurfaceClusters; -Q_EXTERN int *surfaceClusters; - -/* ydnar: for radiosity */ -Q_EXTERN int numDiffuseLights; -Q_EXTERN int numBrushDiffuseLights; -Q_EXTERN int numTriangleDiffuseLights; -Q_EXTERN int numPatchDiffuseLights; - -/* ydnar: general purpose extra copy of drawvert list */ -Q_EXTERN bspDrawVert_t *yDrawVerts; - -/* ydnar: for tracing statistics */ -Q_EXTERN int minSurfacesTested; -Q_EXTERN int maxSurfacesTested; -Q_EXTERN int totalSurfacesTested; -Q_EXTERN int totalTraces; - -Q_EXTERN FILE *dumpFile; - -Q_EXTERN int c_visible, c_occluded; -Q_EXTERN int c_subsampled; /* ydnar */ - -Q_EXTERN int defaultLightSubdivide Q_ASSIGN( 999 ); - -Q_EXTERN vec3_t ambientColor; -Q_EXTERN vec3_t minLight, minVertexLight, minGridLight; - -Q_EXTERN int *entitySurface; -Q_EXTERN vec3_t *surfaceOrigin; - -Q_EXTERN vec3_t sunDirection; -Q_EXTERN vec3_t sunLight; - -/* tracing */ -Q_EXTERN int c_totalTrace; -Q_EXTERN int c_cullTrace, c_testTrace; -Q_EXTERN int c_testFacets; - -/* ydnar: light optimization */ -Q_EXTERN float subdivideThreshold Q_ASSIGN( DEFAULT_SUBDIVIDE_THRESHOLD ); - -Q_EXTERN int numOpaqueBrushes, maxOpaqueBrush; -Q_EXTERN byte *opaqueBrushes; - -Q_EXTERN int numLights; -Q_EXTERN int numCulledLights; - -Q_EXTERN int gridBoundsCulled; -Q_EXTERN int gridEnvelopeCulled; - -Q_EXTERN int lightsBoundsCulled; -Q_EXTERN int lightsEnvelopeCulled; -Q_EXTERN int lightsPlaneCulled; -Q_EXTERN int lightsClusterCulled; - -/* ydnar: radiosity */ -Q_EXTERN float diffuseSubdivide Q_ASSIGN( 256.0f ); -Q_EXTERN float minDiffuseSubdivide Q_ASSIGN( 64.0f ); -Q_EXTERN int numDiffuseSurfaces Q_ASSIGN( 0 ); - -/* ydnar: list of surface information necessary for lightmap calculation */ -Q_EXTERN surfaceInfo_t *surfaceInfos Q_ASSIGN( NULL ); - -/* ydnar: sorted list of surfaces */ -Q_EXTERN int *sortSurfaces Q_ASSIGN( NULL ); - -/* clumps of surfaces that share a raw lightmap */ -Q_EXTERN int numLightSurfaces Q_ASSIGN( 0 ); -Q_EXTERN int *lightSurfaces Q_ASSIGN( NULL ); - -/* raw lightmaps */ -Q_EXTERN int numRawSuperLuxels Q_ASSIGN( 0 ); -Q_EXTERN int numRawLightmaps Q_ASSIGN( 0 ); -Q_EXTERN rawLightmap_t *rawLightmaps Q_ASSIGN( NULL ); -Q_EXTERN int *sortLightmaps Q_ASSIGN( NULL ); - -/* vertex luxels */ -Q_EXTERN float *vertexLuxels[ MAX_LIGHTMAPS ]; -Q_EXTERN float *radVertexLuxels[ MAX_LIGHTMAPS ]; - -/* bsp lightmaps */ -Q_EXTERN int numLightmapShaders Q_ASSIGN( 0 ); -Q_EXTERN int numSolidLightmaps Q_ASSIGN( 0 ); -Q_EXTERN int numOutLightmaps Q_ASSIGN( 0 ); -Q_EXTERN int numBSPLightmaps Q_ASSIGN( 0 ); -Q_EXTERN int numExtLightmaps Q_ASSIGN( 0 ); -Q_EXTERN outLightmap_t *outLightmaps Q_ASSIGN( NULL ); - -/* vortex: per surface floodlight statictics */ -Q_EXTERN int numSurfacesFloodlighten Q_ASSIGN( 0 ); - -/* grid points */ -Q_EXTERN int numRawGridPoints Q_ASSIGN( 0 ); -Q_EXTERN rawGridPoint_t *rawGridPoints Q_ASSIGN( NULL ); - -Q_EXTERN int numSurfsVertexLit Q_ASSIGN( 0 ); -Q_EXTERN int numSurfsVertexForced Q_ASSIGN( 0 ); -Q_EXTERN int numSurfsVertexApproximated Q_ASSIGN( 0 ); -Q_EXTERN int numSurfsLightmapped Q_ASSIGN( 0 ); -Q_EXTERN int numPlanarsLightmapped Q_ASSIGN( 0 ); -Q_EXTERN int numNonPlanarsLightmapped Q_ASSIGN( 0 ); -Q_EXTERN int numPatchesLightmapped Q_ASSIGN( 0 ); -Q_EXTERN int numPlanarPatchesLightmapped Q_ASSIGN( 0 ); - -Q_EXTERN int numLuxels Q_ASSIGN( 0 ); -Q_EXTERN int numLuxelsMapped Q_ASSIGN( 0 ); -Q_EXTERN int numLuxelsOccluded Q_ASSIGN( 0 ); -Q_EXTERN int numLuxelsIlluminated Q_ASSIGN( 0 ); -Q_EXTERN int numVertsIlluminated Q_ASSIGN( 0 ); - -/* lightgrid */ -Q_EXTERN vec3_t gridMins; -Q_EXTERN int gridBounds[ 3 ]; -Q_EXTERN vec3_t gridSize -#ifndef MAIN_C - ; -#else - = { 64, 64, 128 }; -#endif - - - -/* ------------------------------------------------------------------------------- - -abstracted bsp globals - -------------------------------------------------------------------------------- */ - -Q_EXTERN int numEntities Q_ASSIGN( 0 ); -Q_EXTERN int numBSPEntities Q_ASSIGN( 0 ); -Q_EXTERN entity_t entities[ MAX_MAP_ENTITIES ]; - -Q_EXTERN int numBSPModels Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPModels Q_ASSIGN( 0 ); -Q_EXTERN bspModel_t* bspModels Q_ASSIGN(NULL); - -Q_EXTERN int numBSPShaders Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPShaders Q_ASSIGN( 0 ); -Q_EXTERN bspShader_t* bspShaders Q_ASSIGN(0); - -Q_EXTERN int bspEntDataSize Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPEntData Q_ASSIGN( 0 ); -Q_EXTERN char *bspEntData Q_ASSIGN(0); - -Q_EXTERN int numBSPLeafs Q_ASSIGN( 0 ); -Q_EXTERN bspLeaf_t bspLeafs[ MAX_MAP_LEAFS ]; - -Q_EXTERN int numBSPPlanes Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPPlanes Q_ASSIGN(0); -Q_EXTERN bspPlane_t *bspPlanes; - -Q_EXTERN int numBSPNodes Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPNodes Q_ASSIGN( 0 ); -Q_EXTERN bspNode_t* bspNodes Q_ASSIGN(NULL); - -Q_EXTERN int numBSPLeafSurfaces Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPLeafSurfaces Q_ASSIGN( 0 ); -Q_EXTERN int* bspLeafSurfaces Q_ASSIGN(NULL); - -Q_EXTERN int numBSPLeafBrushes Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPLeafBrushes Q_ASSIGN( 0 ); -Q_EXTERN int* bspLeafBrushes Q_ASSIGN(NULL); - -Q_EXTERN int numBSPBrushes Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPBrushes Q_ASSIGN( 0 ); -Q_EXTERN bspBrush_t* bspBrushes Q_ASSIGN(NULL); - -Q_EXTERN int numBSPBrushSides Q_ASSIGN( 0 ); -Q_EXTERN int allocatedBSPBrushSides Q_ASSIGN( 0 ); -Q_EXTERN bspBrushSide_t* bspBrushSides Q_ASSIGN(NULL); - -Q_EXTERN int numBSPLightBytes Q_ASSIGN( 0 ); -Q_EXTERN byte *bspLightBytes Q_ASSIGN( NULL ); - -//% Q_EXTERN int numBSPGridPoints Q_ASSIGN( 0 ); -//% Q_EXTERN byte *bspGridPoints Q_ASSIGN( NULL ); - -Q_EXTERN int numBSPGridPoints Q_ASSIGN( 0 ); -Q_EXTERN bspGridPoint_t *bspGridPoints Q_ASSIGN( NULL ); - -Q_EXTERN int numBSPVisBytes Q_ASSIGN( 0 ); -Q_EXTERN byte bspVisBytes[ MAX_MAP_VISIBILITY ]; - -Q_EXTERN int numBSPDrawVerts Q_ASSIGN( 0 ); -Q_EXTERN bspDrawVert_t *bspDrawVerts Q_ASSIGN( NULL ); - -Q_EXTERN int numBSPDrawIndexes Q_ASSIGN( 0 ); -Q_EXTERN int bspDrawIndexes[ MAX_MAP_DRAW_INDEXES ]; - -Q_EXTERN int numBSPDrawSurfaces Q_ASSIGN( 0 ); -Q_EXTERN bspDrawSurface_t *bspDrawSurfaces Q_ASSIGN( NULL ); - -Q_EXTERN int numBSPFogs Q_ASSIGN( 0 ); -Q_EXTERN bspFog_t bspFogs[ MAX_MAP_FOGS ]; - -Q_EXTERN int numBSPAds Q_ASSIGN( 0 ); -Q_EXTERN bspAdvertisement_t bspAds[ MAX_MAP_ADVERTISEMENTS ]; - -#define AUTOEXPAND_BY_REALLOC(ptr, reqitem, allocated, def) \ - do \ - { \ - if(reqitem >= allocated) \ - { \ - if(allocated == 0) \ - allocated = def; \ - while(reqitem >= allocated && allocated) \ - allocated *= 2; \ - if(!allocated || allocated > 2147483647 / (int)sizeof(*ptr)) \ - { \ - Error(#ptr " over 2 GB"); \ - } \ - ptr = realloc(ptr, sizeof(*ptr) * allocated); \ - if(!ptr) \ - Error(#ptr " out of memory"); \ - } \ - } \ - while(0) - -#define AUTOEXPAND_BY_REALLOC_BSP(suffix, def) AUTOEXPAND_BY_REALLOC(bsp##suffix, numBSP##suffix, allocatedBSP##suffix, def) - -/* end marker */ -#endif diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.ico b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.ico deleted file mode 100644 index 4fe56fa6..00000000 Binary files a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.ico and /dev/null differ diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.rc b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.rc deleted file mode 100644 index bc120375..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2.rc +++ /dev/null @@ -1 +0,0 @@ -101 ICON DISCARDABLE "q3map2.ico" diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2_fsr_newfiles/q3map2_fsr_svn158.patch b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2_fsr_newfiles/q3map2_fsr_svn158.patch deleted file mode 100644 index 0df87e49..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/q3map2_fsr_newfiles/q3map2_fsr_svn158.patch +++ /dev/null @@ -1,19 +0,0 @@ -Index: light.c -=================================================================== ---- light.c (revision 158) -+++ light.c (working copy) -@@ -357,12 +365,13 @@ - intensity *= scale; - - /* ydnar: get deviance and samples */ -+ /* VorteX: now set start value for _samples when _deviance is found */ - deviance = FloatForKey( e, "_deviance" ); - if( deviance == 0.0f ) - deviance = FloatForKey( e, "_deviation" ); - if( deviance == 0.0f ) - deviance = FloatForKey( e, "_jitter" ); -- numSamples = IntForKey( e, "_samples" ); -+ numSamples = max(IntForKey( e, "_samples" ), deviance); - if( deviance < 0.0f || numSamples < 1 ) - { - deviance = 0.0f; diff --git a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/shaders.c b/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/shaders.c deleted file mode 100644 index 3bf6cbe1..00000000 --- a/misc/mediasource/extra/netradiant-src/tools/quake3/q3map2/shaders.c +++ /dev/null @@ -1,2153 +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 - ----------------------------------------------------------------------------------- - -This code has been altered significantly from its original form, to support -several games based on the Quake III Arena engine, in the form of "Q3Map2." - -------------------------------------------------------------------------------- */ - - - -/* marker */ -#define SHADERS_C - - - -/* dependencies */ -#include "q3map2.h" - - - -/* -ColorMod() -routines for dealing with vertex color/alpha modification -*/ - -void ColorMod( colorMod_t *cm, int numVerts, bspDrawVert_t *drawVerts ) -{ - int i, j, k; - float c; - vec4_t mult, add; - bspDrawVert_t *dv; - colorMod_t *cm2; - - - /* dummy check */ - if( cm == NULL || numVerts < 1 || drawVerts == NULL ) - return; - - - /* walk vertex list */ - for( i = 0; i < numVerts; i++ ) - { - /* get vertex */ - dv = &drawVerts[ i ]; - - /* walk colorMod list */ - for( cm2 = cm; cm2 != NULL; cm2 = cm2->next ) - { - /* default */ - VectorSet( mult, 1.0f, 1.0f, 1.0f ); - mult[ 3 ] = 1.0f; - VectorSet( add, 0.0f, 0.0f, 0.0f ); - mult[ 3 ] = 0.0f; - - /* switch on type */ - switch( cm2->type ) - { - case CM_COLOR_SET: - VectorClear( mult ); - VectorScale( cm2->data, 255.0f, add ); - break; - - case CM_ALPHA_SET: - mult[ 3 ] = 0.0f; - add[ 3 ] = cm2->data[ 0 ] * 255.0f; - break; - - case CM_COLOR_SCALE: - VectorCopy( cm2->data, mult ); - break; - - case CM_ALPHA_SCALE: - mult[ 3 ] = cm2->data[ 0 ]; - break; - - case CM_COLOR_DOT_PRODUCT: - c = DotProduct( dv->normal, cm2->data ); - VectorSet( mult, c, c, c ); - break; - - case CM_COLOR_DOT_PRODUCT_SCALE: - c = DotProduct( dv->normal, cm2->data ); - c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); - VectorSet( mult, c, c, c ); - break; - - case CM_ALPHA_DOT_PRODUCT: - mult[ 3 ] = DotProduct( dv->normal, cm2->data ); - break; - - case CM_ALPHA_DOT_PRODUCT_SCALE: - c = DotProduct( dv->normal, cm2->data ); - c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); - mult[ 3 ] = c; - break; - - case CM_COLOR_DOT_PRODUCT_2: - c = DotProduct( dv->normal, cm2->data ); - c *= c; - VectorSet( mult, c, c, c ); - break; - - case CM_COLOR_DOT_PRODUCT_2_SCALE: - c = DotProduct( dv->normal, cm2->data ); - c *= c; - c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); - VectorSet( mult, c, c, c ); - break; - - case CM_ALPHA_DOT_PRODUCT_2: - mult[ 3 ] = DotProduct( dv->normal, cm2->data ); - mult[ 3 ] *= mult[ 3 ]; - break; - - case CM_ALPHA_DOT_PRODUCT_2_SCALE: - c = DotProduct( dv->normal, cm2->data ); - c *= c; - c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); - mult[ 3 ] = c; - break; - - default: - break; - } - - /* apply mod */ - for( j = 0; j < MAX_LIGHTMAPS; j++ ) - { - for( k = 0; k < 4; k++ ) - { - c = (mult[ k ] * dv->color[ j ][ k ]) + add[ k ]; - if( c < 0 ) - c = 0; - else if( c > 255 ) - c = 255; - dv->color[ j ][ k ] = c; - } - } - } - } -} - - - -/* -TCMod*() -routines for dealing with a 3x3 texture mod matrix -*/ - -void TCMod( tcMod_t mod, float st[ 2 ] ) -{ - float old[ 2 ]; - - - old[ 0 ] = st[ 0 ]; - old[ 1 ] = st[ 1 ]; - st[ 0 ] = (mod[ 0 ][ 0 ] * old[ 0 ]) + (mod[ 0 ][ 1 ] * old[ 1 ]) + mod[ 0 ][ 2 ]; - st[ 1 ] = (mod[ 1 ][ 0 ] * old[ 0 ]) + (mod[ 1 ][ 1 ] * old[ 1 ]) + mod[ 1 ][ 2 ]; -} - - -void TCModIdentity( tcMod_t mod ) -{ - mod[ 0 ][ 0 ] = 1.0f; mod[ 0 ][ 1 ] = 0.0f; mod[ 0 ][ 2 ] = 0.0f; - mod[ 1 ][ 0 ] = 0.0f; mod[ 1 ][ 1 ] = 1.0f; mod[ 1 ][ 2 ] = 0.0f; - mod[ 2 ][ 0 ] = 0.0f; mod[ 2 ][ 1 ] = 0.0f; mod[ 2 ][ 2 ] = 1.0f; /* this row is only used for multiples, not transformation */ -} - - -void TCModMultiply( tcMod_t a, tcMod_t b, tcMod_t out ) -{ - int i; - - - for( i = 0; i < 3; i++ ) - { - out[ i ][ 0 ] = (a[ i ][ 0 ] * b[ 0 ][ 0 ]) + (a[ i ][ 1 ] * b[ 1 ][ 0 ]) + (a[ i ][ 2 ] * b[ 2 ][ 0 ]); - out[ i ][ 1 ] = (a[ i ][ 0 ] * b[ 0 ][ 1 ]) + (a[ i ][ 1 ] * b[ 1 ][ 1 ]) + (a[ i ][ 2 ] * b[ 2 ][ 1 ]); - out[ i ][ 2 ] = (a[ i ][ 0 ] * b[ 0 ][ 2 ]) + (a[ i ][ 1 ] * b[ 1 ][ 2 ]) + (a[ i ][ 2 ] * b[ 2 ][ 2 ]); - } -} - - -void TCModTranslate( tcMod_t mod, float s, float t ) -{ - mod[ 0 ][ 2 ] += s; - mod[ 1 ][ 2 ] += t; -} - - -void TCModScale( tcMod_t mod, float s, float t ) -{ - mod[ 0 ][ 0 ] *= s; - mod[ 1 ][ 1 ] *= t; -} - - -void TCModRotate( tcMod_t mod, float euler ) -{ - tcMod_t old, temp; - float radians, sinv, cosv; - - - memcpy( old, mod, sizeof( tcMod_t ) ); - TCModIdentity( temp ); - - radians = euler / 180 * Q_PI; - sinv = sin( radians ); - cosv = cos( radians ); - - temp[ 0 ][ 0 ] = cosv; temp[ 0 ][ 1 ] = -sinv; - temp[ 1 ][ 0 ] = sinv; temp[ 1 ][ 1 ] = cosv; - - TCModMultiply( old, temp, mod ); -} - - - -/* -ApplySurfaceParm() - ydnar -applies a named surfaceparm to the supplied flags -*/ - -qboolean ApplySurfaceParm( char *name, int *contentFlags, int *surfaceFlags, int *compileFlags ) -{ - int i, fake; - surfaceParm_t *sp; - - - /* dummy check */ - if( name == NULL ) - name = ""; - if( contentFlags == NULL ) - contentFlags = &fake; - if( surfaceFlags == NULL ) - surfaceFlags = &fake; - if( compileFlags == NULL ) - compileFlags = &fake; - - /* walk the current game's surfaceparms */ - sp = game->surfaceParms; - while( sp->name != NULL ) - { - /* match? */ - if( !Q_stricmp( name, sp->name ) ) - { - /* clear and set flags */ - *contentFlags &= ~(sp->contentFlagsClear); - *contentFlags |= sp->contentFlags; - *surfaceFlags &= ~(sp->surfaceFlagsClear); - *surfaceFlags |= sp->surfaceFlags; - *compileFlags &= ~(sp->compileFlagsClear); - *compileFlags |= sp->compileFlags; - - /* return ok */ - return qtrue; - } - - /* next */ - sp++; - } - - /* check custom info parms */ - for( i = 0; i < numCustSurfaceParms; i++ ) - { - /* get surfaceparm */ - sp = &custSurfaceParms[ i ]; - - /* match? */ - if( !Q_stricmp( name, sp->name ) ) - { - /* clear and set flags */ - *contentFlags &= ~(sp->contentFlagsClear); - *contentFlags |= sp->contentFlags; - *surfaceFlags &= ~(sp->surfaceFlagsClear); - *surfaceFlags |= sp->surfaceFlags; - *compileFlags &= ~(sp->compileFlagsClear); - *compileFlags |= sp->compileFlags; - - /* return ok */ - return qtrue; - } - } - - /* no matching surfaceparm found */ - return qfalse; -} - - - -/* -BeginMapShaderFile() - ydnar -erases and starts a new map shader script -*/ - -void BeginMapShaderFile( const char *mapFile ) -{ - char base[ 1024 ]; - int len; - - - /* dummy check */ - mapName[ 0 ] = '\0'; - mapShaderFile[ 0 ] = '\0'; - if( mapFile == NULL || mapFile[ 0 ] == '\0' ) - return; - - /* copy map name */ - strcpy( base, mapFile ); - StripExtension( base ); - - /* extract map name */ - len = strlen( base ) - 1; - while( len > 0 && base[ len ] != '/' && base[ len ] != '\\' ) - len--; - strcpy( mapName, &base[ len + 1 ] ); - base[ len ] = '\0'; - if( len <= 0 ) - return; - - /* append ../scripts/q3map2_.shader */ - sprintf( mapShaderFile, "%s/../%s/q3map2_%s.shader", base, game->shaderPath, mapName ); - Sys_FPrintf( SYS_VRB, "Map has shader script %s\n", mapShaderFile ); - - /* remove it */ - remove( mapShaderFile ); - - /* stop making warnings about missing images */ - warnImage = qfalse; -} - - - -/* -WriteMapShaderFile() - ydnar -writes a shader to the map shader script -*/ - -void WriteMapShaderFile( void ) -{ - FILE *file; - shaderInfo_t *si; - int i, num; - - - /* dummy check */ - if( mapShaderFile[ 0 ] == '\0' ) - return; - - /* are there any custom shaders? */ - for( i = 0, num = 0; i < numShaderInfo; i++ ) - { - if( shaderInfo[ i ].custom ) - break; - } - if( i == numShaderInfo ) - return; - - /* note it */ - Sys_FPrintf( SYS_VRB, "--- WriteMapShaderFile ---\n"); - Sys_FPrintf( SYS_VRB, "Writing %s", mapShaderFile ); - - /* open shader file */ - file = fopen( mapShaderFile, "w" ); - if( file == NULL ) - { - Sys_Printf( "WARNING: Unable to open map shader file %s for writing\n", mapShaderFile ); - return; - } - - /* print header */ - fprintf( file, - "// Custom shader file for %s.bsp\n" - "// Generated by Q3Map2 (ydnar)\n" - "// Do not edit! This file is overwritten on recompiles.\n\n", - mapName ); - - /* walk the shader list */ - for( i = 0, num = 0; i < numShaderInfo; i++ ) - { - /* get the shader and print it */ - si = &shaderInfo[ i ]; - if( si->custom == qfalse || si->shaderText == NULL || si->shaderText[ 0 ] == '\0' ) - continue; - num++; - - /* print it to the file */ - fprintf( file, "%s%s\n", si->shader, si->shaderText ); - //Sys_Printf( "%s%s\n", si->shader, si->shaderText ); /* FIXME: remove debugging code */ - - Sys_FPrintf( SYS_VRB, "." ); - } - - /* close the shader */ - fflush( file ); - fclose( file ); - - Sys_FPrintf( SYS_VRB, "\n" ); - - /* print some stats */ - Sys_Printf( "%9d custom shaders emitted\n", num ); -} - - - -/* -CustomShader() - ydnar -sets up a custom map shader -*/ - -shaderInfo_t *CustomShader( shaderInfo_t *si, char *find, char *replace ) -{ - shaderInfo_t *csi; - char shader[ MAX_QPATH ]; - char *s; - int loc; - byte digest[ 16 ]; - char *srcShaderText, temp[ 8192 ], shaderText[ 8192 ]; /* ydnar: fixme (make this bigger?) */ - - - /* dummy check */ - if( si == NULL ) - return ShaderInfoForShader( "default" ); - - /* default shader text source */ - srcShaderText = si->shaderText; - - /* et: implicitMap */ - if( si->implicitMap == IM_OPAQUE ) - { - srcShaderText = temp; - sprintf( temp, "\n" - "{ // Q3Map2 defaulted (implicitMap)\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t}\n" - "\tq3map_styleMarker\n" - "\t{\n" - "\t\tmap %s\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t\trgbGen identity\n" - "\t}\n" - "}\n", - si->implicitImagePath ); - } - - /* et: implicitMask */ - else if( si->implicitMap == IM_MASKED ) - { - srcShaderText = temp; - sprintf( temp, "\n" - "{ // Q3Map2 defaulted (implicitMask)\n" - "\tcull none\n" - "\t{\n" - "\t\tmap %s\n" - "\t\talphaFunc GE128\n" - "\t\tdepthWrite\n" - "\t}\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t\tdepthFunc equal\n" - "\t}\n" - "\tq3map_styleMarker\n" - "\t{\n" - "\t\tmap %s\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t\tdepthFunc equal\n" - "\t\trgbGen identity\n" - "\t}\n" - "}\n", - si->implicitImagePath, - si->implicitImagePath ); - } - - /* et: implicitBlend */ - else if( si->implicitMap == IM_BLEND ) - { - srcShaderText = temp; - sprintf( temp, "\n" - "{ // Q3Map2 defaulted (implicitBlend)\n" - "\tcull none\n" - "\t{\n" - "\t\tmap %s\n" - "\t\tblendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA\n" - "\t}\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t}\n" - "\tq3map_styleMarker\n" - "}\n", - si->implicitImagePath ); - } - - /* default shader text */ - else if( srcShaderText == NULL ) - { - srcShaderText = temp; - sprintf( temp, "\n" - "{ // Q3Map2 defaulted\n" - "\t{\n" - "\t\tmap $lightmap\n" - "\t\trgbGen identity\n" - "\t}\n" - "\tq3map_styleMarker\n" - "\t{\n" - "\t\tmap %s.tga\n" - "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" - "\t\trgbGen identity\n" - "\t}\n" - "}\n", - si->shader ); - } - - /* error check */ - if( (strlen( mapName ) + 1 + 32) > MAX_QPATH ) - Error( "Custom shader name length (%d) exceeded. Shorten your map name.\n", MAX_QPATH ); - - /* do some bad find-replace */ - s = strstr( srcShaderText, find ); - if( s == NULL ) - //% strcpy( shaderText, srcShaderText ); - return si; /* testing just using the existing shader if this fails */ - else - { - /* substitute 'find' with 'replace' */ - loc = s - srcShaderText; - strcpy( shaderText, srcShaderText ); - shaderText[ loc ] = '\0'; - strcat( shaderText, replace ); - strcat( shaderText, &srcShaderText[ loc + strlen( find ) ] ); - } - - /* make md4 hash of the shader text */ - Com_BlockFullChecksum(shaderText, strlen(shaderText), digest); - - /* mangle hash into a shader name */ - sprintf( shader, "%s/%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", mapName, - digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], - digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ], digest[ 15 ] ); - - /* get shader */ - csi = ShaderInfoForShader( shader ); - - /* might be a preexisting shader */ - if( csi->custom ) - return csi; - - /* clone the existing shader and rename */ - memcpy( csi, si, sizeof( shaderInfo_t ) ); - strcpy( csi->shader, shader ); - csi->custom = qtrue; - - /* store new shader text */ - csi->shaderText = safe_malloc( strlen( shaderText ) + 1 ); - strcpy( csi->shaderText, shaderText ); /* LEAK! */ - - /* return it */ - return csi; -} - - - -/* -EmitVertexRemapShader() -adds a vertexremapshader key/value pair to worldspawn -*/ - -void EmitVertexRemapShader( char *from, char *to ) -{ - byte digest[ 16 ]; - char key[ 64 ], value[ 256 ]; - - - /* dummy check */ - if( from == NULL || from[ 0 ] == '\0' || - to == NULL || to[ 0 ] == '\0' ) - return; - - /* build value */ - sprintf( value, "%s;%s", from, to ); - - /* make md4 hash */ - Com_BlockFullChecksum(value, strlen(value), digest); - - /* make key (this is annoying, as vertexremapshader is precisely 17 characters, - which is one too long, so we leave off the last byte of the md5 digest) */ - sprintf( key, "vertexremapshader%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", - digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], - digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ] ); /* no: digest[ 15 ] */ - - /* add key/value pair to worldspawn */ - SetKeyValue( &entities[ 0 ], key, value ); -} - - - -/* -AllocShaderInfo() -allocates and initializes a new shader -*/ - -static shaderInfo_t *AllocShaderInfo( void ) -{ - shaderInfo_t *si; - - - /* allocate? */ - if( shaderInfo == NULL ) - { - shaderInfo = safe_malloc( sizeof( shaderInfo_t ) * MAX_SHADER_INFO ); - numShaderInfo = 0; - } - - /* bounds check */ - if( numShaderInfo == MAX_SHADER_INFO ) - Error( "MAX_SHADER_INFO exceeded. Remove some PK3 files or shader scripts from shaderlist.txt and try again." ); - si = &shaderInfo[ numShaderInfo ]; - numShaderInfo++; - - /* ydnar: clear to 0 first */ - memset( si, 0, sizeof( shaderInfo_t ) ); - - /* set defaults */ - ApplySurfaceParm( "default", &si->contentFlags, &si->surfaceFlags, &si->compileFlags ); - - si->backsplashFraction = DEF_BACKSPLASH_FRACTION; - si->backsplashDistance = DEF_BACKSPLASH_DISTANCE; - - si->bounceScale = DEF_RADIOSITY_BOUNCE; - - si->lightStyle = LS_NORMAL; - - si->polygonOffset = qfalse; - - si->shadeAngleDegrees = 0.0f; - si->lightmapSampleSize = 0; - si->lightmapSampleOffset = DEFAULT_LIGHTMAP_SAMPLE_OFFSET; - si->patchShadows = qfalse; - si->vertexShadows = qtrue; /* ydnar: changed default behavior */ - si->forceSunlight = qfalse; - si->vertexScale = 1.0; - si->notjunc = qfalse; - - /* ydnar: set texture coordinate transform matrix to identity */ - TCModIdentity( si->mod ); - - /* ydnar: lightmaps can now be > 128x128 in certain games or an externally generated tga */ - si->lmCustomWidth = lmCustomSize; - si->lmCustomHeight = lmCustomSize; - - /* return to sender */ - return si; -} - - - -/* -FinishShader() - ydnar -sets a shader's width and height among other things -*/ - -void FinishShader( shaderInfo_t *si ) -{ - int x, y; - float st[ 2 ], o[ 2 ], dist, bestDist; - vec4_t color, bestColor, delta; - - - /* don't double-dip */ - if( si->finished ) - return; - - /* if they're explicitly set, copy from image size */ - if( si->shaderWidth == 0 && si->shaderHeight == 0 ) - { - si->shaderWidth = si->shaderImage->width; - si->shaderHeight = si->shaderImage->height; - } - - /* legacy terrain has explicit image-sized texture projection */ - if( si->legacyTerrain && si->tcGen == qfalse ) - { - /* set xy texture projection */ - si->tcGen = qtrue; - VectorSet( si->vecs[ 0 ], (1.0f / (si->shaderWidth * 0.5f)), 0, 0 ); - VectorSet( si->vecs[ 1 ], 0, (1.0f / (si->shaderHeight * 0.5f)), 0 ); - } - - /* find pixel coordinates best matching the average color of the image */ - bestDist = 99999999; - o[ 0 ] = 1.0f / si->shaderImage->width; - o[ 1 ] = 1.0f / si->shaderImage->height; - for( y = 0, st[ 1 ] = 0.0f; y < si->shaderImage->height; y++, st[ 1 ] += o[ 1 ] ) - { - for( x = 0, st[ 0 ] = 0.0f; x < si->shaderImage->width; x++, st[ 0 ] += o[ 0 ] ) - { - /* sample the shader image */ - RadSampleImage( si->shaderImage->pixels, si->shaderImage->width, si->shaderImage->height, st, color ); - - /* determine error squared */ - VectorSubtract( color, si->averageColor, delta ); - delta[ 3 ] = color[ 3 ] - si->averageColor[ 3 ]; - dist = delta[ 0 ] * delta[ 0 ] + delta[ 1 ] * delta[ 1 ] + delta[ 2 ] * delta[ 2 ] + delta[ 3 ] * delta[ 3 ]; - if( dist < bestDist ) - { - VectorCopy( color, bestColor ); - bestColor[ 3 ] = color[ 3 ]; - si->stFlat[ 0 ] = st[ 0 ]; - si->stFlat[ 1 ] = st[ 1 ]; - } - } - } - - /* set to finished */ - si->finished = qtrue; -} - - - -/* -LoadShaderImages() -loads a shader's images -ydnar: image.c made this a bit simpler -*/ - -static void LoadShaderImages( shaderInfo_t *si ) -{ - int i, count; - float color[ 4 ]; - - - /* nodraw shaders don't need images */ - if( si->compileFlags & C_NODRAW ) - si->shaderImage = ImageLoad( DEFAULT_IMAGE ); - else - { - /* try to load editor image first */ - si->shaderImage = ImageLoad( si->editorImagePath ); - - /* then try shadername */ - if( si->shaderImage == NULL ) - si->shaderImage = ImageLoad( si->shader ); - - /* then try implicit image path (note: new behavior!) */ - if( si->shaderImage == NULL ) - si->shaderImage = ImageLoad( si->implicitImagePath ); - - /* then try lightimage (note: new behavior!) */ - if( si->shaderImage == NULL ) - si->shaderImage = ImageLoad( si->lightImagePath ); - - /* otherwise, use default image */ - if( si->shaderImage == NULL ) - { - si->shaderImage = ImageLoad( DEFAULT_IMAGE ); - if( warnImage && strcmp( si->shader, "noshader" ) ) - Sys_Printf( "WARNING: Couldn't find image for shader %s\n", si->shader ); - } - - /* load light image */ - si->lightImage = ImageLoad( si->lightImagePath ); - - /* load normalmap image (ok if this is NULL) */ - si->normalImage = ImageLoad( si->normalImagePath ); - if( si->normalImage != NULL ) - { - Sys_FPrintf( SYS_VRB, "Shader %s has\n" - " NM %s\n", si->shader, si->normalImagePath ); - } - } - - /* if no light image, use shader image */ - if( si->lightImage == NULL ) - si->lightImage = ImageLoad( si->shaderImage->name ); - - /* create default and average colors */ - count = si->lightImage->width * si->lightImage->height; - VectorClear( color ); - color[ 3 ] = 0.0f; - for( i = 0; i < count; i++ ) - { - color[ 0 ] += si->lightImage->pixels[ i * 4 + 0 ]; - color[ 1 ] += si->lightImage->pixels[ i * 4 + 1 ]; - color[ 2 ] += si->lightImage->pixels[ i * 4 + 2 ]; - color[ 3 ] += si->lightImage->pixels[ i * 4 + 3 ]; - } - - if( VectorLength( si->color ) <= 0.0f ) - { - ColorNormalize( color, si->color ); - VectorScale( color, (1.0f / count), si->averageColor ); - } - else - { - VectorCopy( si->color, si->averageColor ); - } -} - - - -/* -ShaderInfoForShader() -finds a shaderinfo for a named shader -*/ - -#define MAX_SHADER_DEPRECATION_DEPTH 16 - -shaderInfo_t *ShaderInfoForShader( const char *shaderName ) -{ - int i; - int deprecationDepth; - shaderInfo_t *si; - char shader[ MAX_QPATH ]; - - /* dummy check */ - if( shaderName == NULL || shaderName[ 0 ] == '\0' ) - { - Sys_Printf( "WARNING: Null or empty shader name\n" ); - shaderName = "missing"; - } - - /* strip off extension */ - strcpy( shader, shaderName ); - StripExtension( shader ); - - /* search for it */ - deprecationDepth = 0; - for( i = 0; i < numShaderInfo; i++ ) - { - si = &shaderInfo[ i ]; - if( !Q_stricmp( shader, si->shader ) ) - { - /* check if shader is deprecated */ - if (deprecationDepth < MAX_SHADER_DEPRECATION_DEPTH && si->deprecateShader && si->deprecateShader[ 0 ] ) - { - /* override name */ - strcpy( shader, si->deprecateShader ); - StripExtension( shader ); - /* increase deprecation depth */ - deprecationDepth++; - if (deprecationDepth == MAX_SHADER_DEPRECATION_DEPTH) - Sys_Printf("WARNING: Max deprecation depth of %i is reached on shader '%s'\n", MAX_SHADER_DEPRECATION_DEPTH, shader); - /* search again from beginning */ - i = -1; - continue; - } - - /* load image if necessary */ - if( si->finished == qfalse ) - { - LoadShaderImages( si ); - FinishShader( si ); - } - - /* return it */ - return si; - } - } - - /* allocate a default shader */ - si = AllocShaderInfo(); - strcpy( si->shader, shader ); - LoadShaderImages( si ); - FinishShader( si ); - - /* return it */ - return si; -} - - - -/* -GetTokenAppend() - ydnar -gets a token and appends its text to the specified buffer -*/ - -static int oldScriptLine = 0; -static int tabDepth = 0; - -qboolean GetTokenAppend( char *buffer, qboolean crossline ) -{ - qboolean r; - int i; - - - /* get the token */ - r = GetToken( crossline ); - if( r == qfalse || buffer == NULL || token[ 0 ] == '\0' ) - return r; - - /* pre-tabstops */ - if( token[ 0 ] == '}' ) - tabDepth--; - - /* append? */ - if( oldScriptLine != scriptline ) - { - strcat( buffer, "\n" ); - for( i = 0; i < tabDepth; i++ ) - strcat( buffer, "\t" ); - } - else - strcat( buffer, " " ); - oldScriptLine = scriptline; - strcat( buffer, token ); - - /* post-tabstops */ - if( token[ 0 ] == '{' ) - tabDepth++; - - /* return */ - return r; -} - - -void Parse1DMatrixAppend( char *buffer, int x, vec_t *m ) -{ - int i; - - - if( !GetTokenAppend( buffer, qtrue ) || strcmp( token, "(" ) ) - Error( "Parse1DMatrixAppend(): line %d: ( not found!", scriptline ); - for( i = 0; i < x; i++ ) - { - if( !GetTokenAppend( buffer, qfalse ) ) - Error( "Parse1DMatrixAppend(): line %d: Number not found!", scriptline ); - m[ i ] = atof( token ); - } - if( !GetTokenAppend( buffer, qtrue ) || strcmp( token, ")" ) ) - Error( "Parse1DMatrixAppend(): line %d: ) not found!", scriptline ); -} - - - - -/* -ParseShaderFile() -parses a shader file into discrete shaderInfo_t -*/ - -static void ParseShaderFile( const char *filename ) -{ - int i, val; - shaderInfo_t *si; - char *suffix, temp[ 1024 ]; - char shaderText[ 8192 ]; /* ydnar: fixme (make this bigger?) */ - - - /* init */ - si = NULL; - shaderText[ 0 ] = '\0'; - - /* load the shader */ - LoadScriptFile( filename, 0 ); - - /* tokenize it */ - while( 1 ) - { - /* copy shader text to the shaderinfo */ - if( si != NULL && shaderText[ 0 ] != '\0' ) - { - strcat( shaderText, "\n" ); - si->shaderText = safe_malloc( strlen( shaderText ) + 1 ); - strcpy( si->shaderText, shaderText ); - //% if( VectorLength( si->vecs[ 0 ] ) ) - //% Sys_Printf( "%s\n", shaderText ); - } - - /* ydnar: clear shader text buffer */ - shaderText[ 0 ] = '\0'; - - /* test for end of file */ - if( !GetToken( qtrue ) ) - break; - - /* shader name is initial token */ - si = AllocShaderInfo(); - strcpy( si->shader, token ); - - /* ignore ":q3map" suffix */ - suffix = strstr( si->shader, ":q3map" ); - if( suffix != NULL ) - *suffix = '\0'; - - /* handle { } section */ - if( !GetTokenAppend( shaderText, qtrue ) ) - break; - if( strcmp( token, "{" ) ) - { - if( si != NULL ) - Error( "ParseShaderFile(): %s, line %d: { not found!\nFound instead: %s\nLast known shader: %s", - filename, scriptline, token, si->shader ); - else - Error( "ParseShaderFile(): %s, line %d: { not found!\nFound instead: %s", - filename, scriptline, token ); - } - - while( 1 ) - { - /* get the next token */ - if( !GetTokenAppend( shaderText, qtrue ) ) - break; - if( !strcmp( token, "}" ) ) - break; - - - /* ----------------------------------------------------------------- - shader stages (passes) - ----------------------------------------------------------------- */ - - /* parse stage directives */ - if( !strcmp( token, "{" ) ) - { - si->hasPasses = qtrue; - while( 1 ) - { - if( !GetTokenAppend( shaderText, qtrue ) ) - break; - if( !strcmp( token, "}" ) ) - break; - - /* only care about images if we don't have a editor/light image */ - if( si->editorImagePath[ 0 ] == '\0' && si->lightImagePath[ 0 ] == '\0' && si->implicitImagePath[ 0 ] == '\0' ) - { - /* digest any images */ - if( !Q_stricmp( token, "map" ) || - !Q_stricmp( token, "clampMap" ) || - !Q_stricmp( token, "animMap" ) || - !Q_stricmp( token, "clampAnimMap" ) || - !Q_stricmp( token, "clampMap" ) || - !Q_stricmp( token, "mapComp" ) || - !Q_stricmp( token, "mapNoComp" ) ) - { - /* skip one token for animated stages */ - if( !Q_stricmp( token, "animMap" ) || !Q_stricmp( token, "clampAnimMap" ) ) - GetTokenAppend( shaderText, qfalse ); - - /* get an image */ - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '*' && token[ 0 ] != '$' ) - { - strcpy( si->lightImagePath, token ); - DefaultExtension( si->lightImagePath, ".tga" ); - - /* debug code */ - //% Sys_FPrintf( SYS_VRB, "Deduced shader image: %s\n", si->lightImagePath ); - } - } - } - } - } - - - /* ----------------------------------------------------------------- - surfaceparm * directives - ----------------------------------------------------------------- */ - - /* match surfaceparm */ - else if( !Q_stricmp( token, "surfaceparm" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( ApplySurfaceParm( token, &si->contentFlags, &si->surfaceFlags, &si->compileFlags ) == qfalse ) - Sys_Printf( "WARNING: Unknown surfaceparm: \"%s\"\n", token ); - } - - - /* ----------------------------------------------------------------- - game-related shader directives - ----------------------------------------------------------------- */ - - /* ydnar: fogparms (for determining fog volumes) */ - else if( !Q_stricmp( token, "fogparms" ) ) - si->fogParms = qtrue; - - /* ydnar: polygonoffset (for no culling) */ - else if( !Q_stricmp( token, "polygonoffset" ) ) - si->polygonOffset = qtrue; - - /* tesssize is used to force liquid surfaces to subdivide */ - else if( !Q_stricmp( token, "tessSize" ) || !Q_stricmp( token, "q3map_tessSize" ) /* sof2 */ ) - { - GetTokenAppend( shaderText, qfalse ); - si->subdivisions = atof( token ); - } - - /* cull none will set twoSided (ydnar: added disable too) */ - else if ( !Q_stricmp( token, "cull" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "disable" ) || !Q_stricmp( token, "twosided" ) ) - si->twoSided = qtrue; - } - - /* deformVertexes autosprite[ 2 ] - we catch this so autosprited surfaces become point - lights instead of area lights */ - else if( !Q_stricmp( token, "deformVertexes" ) ) - { - GetTokenAppend( shaderText, qfalse ); - - /* deformVertexes autosprite(2) */ - if( !Q_strncasecmp( token, "autosprite", 10 ) ) - { - /* set it as autosprite and detail */ - si->autosprite = qtrue; - ApplySurfaceParm( "detail", &si->contentFlags, &si->surfaceFlags, &si->compileFlags ); - - /* ydnar: gs mods: added these useful things */ - si->noClip = qtrue; - si->notjunc = qtrue; - } - - /* deformVertexes move (ydnar: for particle studio support) */ - if( !Q_stricmp( token, "move") ) - { - vec3_t amt, mins, maxs; - float base, amp; - - - /* get move amount */ - GetTokenAppend( shaderText, qfalse ); amt[ 0 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); amt[ 1 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); amt[ 2 ] = atof( token ); - - /* skip func */ - GetTokenAppend( shaderText, qfalse ); - - /* get base and amplitude */ - GetTokenAppend( shaderText, qfalse ); base = atof( token ); - GetTokenAppend( shaderText, qfalse ); amp = atof( token ); - - /* calculate */ - VectorScale( amt, base, mins ); - VectorMA( mins, amp, amt, maxs ); - VectorAdd( si->mins, mins, si->mins ); - VectorAdd( si->maxs, maxs, si->maxs ); - } - } - - /* light (old-style flare specification) */ - else if( !Q_stricmp( token, "light" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->flareShader = game->flareShader; - } - - /* ydnar: damageShader (sof2 mods) */ - else if( !Q_stricmp( token, "damageShader" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { - si->damageShader = safe_malloc( strlen( token ) + 1 ); - strcpy( si->damageShader, token ); - } - GetTokenAppend( shaderText, qfalse ); /* don't do anything with health */ - } - - /* ydnar: enemy territory implicit shaders */ - else if( !Q_stricmp( token, "implicitMap" ) ) - { - si->implicitMap = IM_OPAQUE; - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] == '-' && token[ 1 ] == '\0' ) - sprintf( si->implicitImagePath, "%s.tga", si->shader ); - else - strcpy( si->implicitImagePath, token ); - } - - else if( !Q_stricmp( token, "implicitMask" ) ) - { - si->implicitMap = IM_MASKED; - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] == '-' && token[ 1 ] == '\0' ) - sprintf( si->implicitImagePath, "%s.tga", si->shader ); - else - strcpy( si->implicitImagePath, token ); - } - - else if( !Q_stricmp( token, "implicitBlend" ) ) - { - si->implicitMap = IM_MASKED; - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] == '-' && token[ 1 ] == '\0' ) - sprintf( si->implicitImagePath, "%s.tga", si->shader ); - else - strcpy( si->implicitImagePath, token ); - } - - - /* ----------------------------------------------------------------- - image directives - ----------------------------------------------------------------- */ - - /* qer_editorimage */ - else if( !Q_stricmp( token, "qer_editorImage" ) ) - { - GetTokenAppend( shaderText, qfalse ); - strcpy( si->editorImagePath, token ); - DefaultExtension( si->editorImagePath, ".tga" ); - } - - /* ydnar: q3map_normalimage (bumpmapping normal map) */ - else if( !Q_stricmp( token, "q3map_normalImage" ) ) - { - GetTokenAppend( shaderText, qfalse ); - strcpy( si->normalImagePath, token ); - DefaultExtension( si->normalImagePath, ".tga" ); - } - - /* q3map_lightimage */ - else if( !Q_stricmp( token, "q3map_lightImage" ) ) - { - GetTokenAppend( shaderText, qfalse ); - strcpy( si->lightImagePath, token ); - DefaultExtension( si->lightImagePath, ".tga" ); - } - - /* ydnar: skyparms */ - else if( !Q_stricmp( token, "skyParms" ) ) - { - /* get image base */ - GetTokenAppend( shaderText, qfalse ); - - /* ignore bogus paths */ - if( Q_stricmp( token, "-" ) && Q_stricmp( token, "full" ) ) - { - strcpy( si->skyParmsImageBase, token ); - - /* use top image as sky light image */ - if( si->lightImagePath[ 0 ] == '\0' ) - sprintf( si->lightImagePath, "%s_up.tga", si->skyParmsImageBase ); - } - - /* skip rest of line */ - GetTokenAppend( shaderText, qfalse ); - GetTokenAppend( shaderText, qfalse ); - } - - /* ----------------------------------------------------------------- - q3map_* directives - ----------------------------------------------------------------- */ - - /* q3map_sun - color will be normalized, so it doesn't matter what range you use - intensity falls off with angle but not distance 100 is a fairly bright sun - degree of 0 = from the east, 90 = north, etc. altitude of 0 = sunrise/set, 90 = noon - ydnar: sof2map has bareword 'sun' token, so we support that as well */ - else if( !Q_stricmp( token, "sun" ) /* sof2 */ || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) ) - { - float a, b; - sun_t *sun; - qboolean ext; - - - /* ydnar: extended sun directive? */ - if( !Q_stricmp( token, "q3map_sunext" ) ) - ext = qtrue; - - /* allocate sun */ - sun = safe_malloc( sizeof( *sun ) ); - memset( sun, 0, sizeof( *sun ) ); - - /* set style */ - sun->style = si->lightStyle; - - /* get color */ - GetTokenAppend( shaderText, qfalse ); - sun->color[ 0 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); - sun->color[ 1 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); - sun->color[ 2 ] = atof( token ); - - /* normalize it */ - VectorNormalize( sun->color, sun->color ); - - /* scale color by brightness */ - GetTokenAppend( shaderText, qfalse ); - sun->photons = atof( token ); - - /* get sun angle/elevation */ - GetTokenAppend( shaderText, qfalse ); - a = atof( token ); - a = a / 180.0f * Q_PI; - - GetTokenAppend( shaderText, qfalse ); - b = atof( token ); - b = b / 180.0f * Q_PI; - - sun->direction[ 0 ] = cos( a ) * cos( b ); - sun->direction[ 1 ] = sin( a ) * cos( b ); - sun->direction[ 2 ] = sin( b ); - - /* get filter radius from shader */ - sun->filterRadius = si->lightFilterRadius; - - /* ydnar: get sun angular deviance/samples */ - if( ext && TokenAvailable() ) - { - GetTokenAppend( shaderText, qfalse ); - sun->deviance = atof( token ); - sun->deviance = sun->deviance / 180.0f * Q_PI; - - GetTokenAppend( shaderText, qfalse ); - sun->numSamples = atoi( token ); - } - - /* store sun */ - sun->next = si->sun; - si->sun = sun; - - /* apply sky surfaceparm */ - ApplySurfaceParm( "sky", &si->contentFlags, &si->surfaceFlags, &si->compileFlags ); - - /* don't process any more tokens on this line */ - continue; - } - - /* match q3map_ */ - else if( !Q_strncasecmp( token, "q3map_", 6 ) ) - { - /* ydnar: q3map_baseShader (inherit this shader's parameters) */ - if( !Q_stricmp( token, "q3map_baseShader" ) ) - { - shaderInfo_t *si2; - qboolean oldWarnImage; - - - /* get shader */ - GetTokenAppend( shaderText, qfalse ); - //% Sys_FPrintf( SYS_VRB, "Shader %s has base shader %s\n", si->shader, token ); - oldWarnImage = warnImage; - warnImage = qfalse; - si2 = ShaderInfoForShader( token ); - warnImage = oldWarnImage; - - /* subclass it */ - if( si2 != NULL ) - { - /* preserve name */ - strcpy( temp, si->shader ); - - /* copy shader */ - memcpy( si, si2, sizeof( *si ) ); - - /* restore name and set to unfinished */ - strcpy( si->shader, temp ); - si->shaderWidth = 0; - si->shaderHeight = 0; - si->finished = qfalse; - } - } - - /* ydnar: q3map_surfacemodel */ - else if( !Q_stricmp( token, "q3map_surfacemodel" ) ) - { - surfaceModel_t *model; - - /* allocate new model and attach it */ - model = safe_malloc( sizeof( *model ) ); - memset( model, 0, sizeof( *model ) ); - model->next = si->surfaceModel; - si->surfaceModel = model; - - /* get parameters */ - GetTokenAppend( shaderText, qfalse ); - strcpy( model->model, token ); - - GetTokenAppend( shaderText, qfalse ); - model->density = atof( token ); - GetTokenAppend( shaderText, qfalse ); - model->odds = atof( token ); - - GetTokenAppend( shaderText, qfalse ); - model->minScale = atof( token ); - GetTokenAppend( shaderText, qfalse ); - model->maxScale = atof( token ); - - GetTokenAppend( shaderText, qfalse ); - model->minAngle = atof( token ); - GetTokenAppend( shaderText, qfalse ); - model->maxAngle = atof( token ); - - GetTokenAppend( shaderText, qfalse ); - model->oriented = (token[ 0 ] == '1' ? qtrue : qfalse); - } - - /* ydnar/sd: q3map_foliage */ - else if( !Q_stricmp( token, "q3map_foliage" ) ) - { - foliage_t *foliage; - - - /* allocate new foliage struct and attach it */ - foliage = safe_malloc( sizeof( *foliage ) ); - memset( foliage, 0, sizeof( *foliage ) ); - foliage->next = si->foliage; - si->foliage = foliage; - - /* get parameters */ - GetTokenAppend( shaderText, qfalse ); - strcpy( foliage->model, token ); - - GetTokenAppend( shaderText, qfalse ); - foliage->scale = atof( token ); - GetTokenAppend( shaderText, qfalse ); - foliage->density = atof( token ); - GetTokenAppend( shaderText, qfalse ); - foliage->odds = atof( token ); - GetTokenAppend( shaderText, qfalse ); - foliage->inverseAlpha = atoi( token ); - } - - /* ydnar: q3map_bounce (fraction of light to re-emit during radiosity passes) */ - else if( !Q_stricmp( token, "q3map_bounce" ) || !Q_stricmp( token, "q3map_bounceScale" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->bounceScale = atof( token ); - } - - /* ydnar/splashdamage: q3map_skyLight */ - else if( !Q_stricmp( token, "q3map_skyLight" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->skyLightValue = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->skyLightIterations = atoi( token ); - - /* clamp */ - if( si->skyLightValue < 0.0f ) - si->skyLightValue = 0.0f; - if( si->skyLightIterations < 2 ) - si->skyLightIterations = 2; - } - - /* q3map_surfacelight */ - else if( !Q_stricmp( token, "q3map_surfacelight" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->value = atof( token ); - } - - /* q3map_lightStyle (sof2/jk2 lightstyle) */ - else if( !Q_stricmp( token, "q3map_lightStyle" ) ) - { - GetTokenAppend( shaderText, qfalse ); - val = atoi( token ); - if( val < 0 ) - val = 0; - else if( val > LS_NONE ) - val = LS_NONE; - si->lightStyle = val; - } - - /* wolf: q3map_lightRGB */ - else if( !Q_stricmp( token, "q3map_lightRGB" ) ) - { - VectorClear( si->color ); - GetTokenAppend( shaderText, qfalse ); - si->color[ 0 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->color[ 1 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->color[ 2 ] = atof( token ); - ColorNormalize( si->color, si->color ); - } - - /* q3map_lightSubdivide */ - else if( !Q_stricmp( token, "q3map_lightSubdivide" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->lightSubdivide = atoi( token ); - } - - /* q3map_backsplash */ - else if( !Q_stricmp( token, "q3map_backsplash" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->backsplashFraction = atof( token ) * 0.01f; - GetTokenAppend( shaderText, qfalse ); - si->backsplashDistance = atof( token ); - } - - /* q3map_floodLight */ - else if( !Q_stricmp( token, "q3map_floodLight" ) ) - { - /* get color */ - GetTokenAppend( shaderText, qfalse ); - si->floodlightRGB[ 0 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->floodlightRGB[ 1 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->floodlightRGB[ 2 ] = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->floodlightDistance = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->floodlightIntensity = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->floodlightDirectionScale = atof( token ); - } - - /* jal: q3map_nodirty : skip dirty */ - else if( !Q_stricmp( token, "q3map_nodirty" ) ) - { - si->noDirty = qtrue; - } - - /* q3map_lightmapSampleSize */ - else if( !Q_stricmp( token, "q3map_lightmapSampleSize" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->lightmapSampleSize = atoi( token ); - } - - /* q3map_lightmapSampleOffset */ - else if( !Q_stricmp( token, "q3map_lightmapSampleOffset" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->lightmapSampleOffset = atof( token ); - } - - /* ydnar: q3map_lightmapFilterRadius */ - else if( !Q_stricmp( token, "q3map_lightmapFilterRadius" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->lmFilterRadius = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->lightFilterRadius = atof( token ); - } - - /* ydnar: q3map_lightmapAxis [xyz] */ - else if( !Q_stricmp( token, "q3map_lightmapAxis" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( !Q_stricmp( token, "x" ) ) - VectorSet( si->lightmapAxis, 1, 0, 0 ); - else if( !Q_stricmp( token, "y" ) ) - VectorSet( si->lightmapAxis, 0, 1, 0 ); - else if( !Q_stricmp( token, "z" ) ) - VectorSet( si->lightmapAxis, 0, 0, 1 ); - else - { - Sys_Printf( "WARNING: Unknown value for lightmap axis: %s\n", token ); - VectorClear( si->lightmapAxis ); - } - } - - /* ydnar: q3map_lightmapSize (for autogenerated shaders + external tga lightmaps) */ - else if( !Q_stricmp( token, "q3map_lightmapSize" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->lmCustomWidth = atoi( token ); - GetTokenAppend( shaderText, qfalse ); - si->lmCustomHeight = atoi( token ); - - /* must be a power of 2 */ - if( ((si->lmCustomWidth - 1) & si->lmCustomWidth) || - ((si->lmCustomHeight - 1) & si->lmCustomHeight) ) - { - Sys_Printf( "WARNING: Non power-of-two lightmap size specified (%d, %d)\n", - si->lmCustomWidth, si->lmCustomHeight ); - si->lmCustomWidth = lmCustomSize; - si->lmCustomHeight = lmCustomSize; - } - } - - /* ydnar: q3map_lightmapBrightness N (for autogenerated shaders + external tga lightmaps) */ - else if( !Q_stricmp( token, "q3map_lightmapBrightness" ) || !Q_stricmp( token, "q3map_lightmapGamma" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->lmBrightness = atof( token ); - if( si->lmBrightness < 0 ) - si->lmBrightness = 1.0; - } - - /* q3map_vertexScale (scale vertex lighting by this fraction) */ - else if( !Q_stricmp( token, "q3map_vertexScale" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->vertexScale = atof( token ); - } - - /* q3map_noVertexLight */ - else if( !Q_stricmp( token, "q3map_noVertexLight" ) ) - { - si->noVertexLight = qtrue; - } - - /* q3map_flare[Shader] */ - else if( !Q_stricmp( token, "q3map_flare" ) || !Q_stricmp( token, "q3map_flareShader" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { - si->flareShader = safe_malloc( strlen( token ) + 1 ); - strcpy( si->flareShader, token ); - } - } - - /* q3map_backShader */ - else if( !Q_stricmp( token, "q3map_backShader" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { - si->backShader = safe_malloc( strlen( token ) + 1 ); - strcpy( si->backShader, token ); - } - } - - /* ydnar: q3map_cloneShader */ - else if ( !Q_stricmp( token, "q3map_cloneShader" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { - si->cloneShader = safe_malloc( strlen( token ) + 1 ); - strcpy( si->cloneShader, token ); - } - } - - /* q3map_remapShader */ - else if( !Q_stricmp( token, "q3map_remapShader" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { - si->remapShader = safe_malloc( strlen( token ) + 1 ); - strcpy( si->remapShader, token ); - } - } - - /* q3map_deprecateShader */ - else if( !Q_stricmp( token, "q3map_deprecateShader" ) ) - { - GetTokenAppend( shaderText, qfalse ); - if( token[ 0 ] != '\0' ) - { - - si->deprecateShader = safe_malloc( strlen( token ) + 1 ); - strcpy( si->deprecateShader, token ); - } - } - - /* ydnar: q3map_offset */ - else if( !Q_stricmp( token, "q3map_offset" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->offset = atof( token ); - } - - /* ydnar: q3map_fur */ - else if( !Q_stricmp( token, "q3map_fur" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->furNumLayers = atoi( token ); - GetTokenAppend( shaderText, qfalse ); - si->furOffset = atof( token ); - GetTokenAppend( shaderText, qfalse ); - si->furFade = atof( token ); - } - - /* ydnar: gs mods: legacy support for terrain/terrain2 shaders */ - else if( !Q_stricmp( token, "q3map_terrain" ) ) - { - /* team arena terrain is assumed to be nonplanar, with full normal averaging, - passed through the metatriangle surface pipeline, with a lightmap axis on z */ - si->legacyTerrain = qtrue; - si->noClip = qtrue; - si->notjunc = qtrue; - si->indexed = qtrue; - si->nonplanar = qtrue; - si->forceMeta = qtrue; - si->shadeAngleDegrees = 179.0f; - //% VectorSet( si->lightmapAxis, 0, 0, 1 ); /* ydnar 2002-09-21: turning this off for better lightmapping of cliff faces */ - } - - /* ydnar: picomodel: q3map_forceMeta (forces brush faces and/or triangle models to go through the metasurface pipeline) */ - else if( !Q_stricmp( token, "q3map_forceMeta" ) ) - { - si->forceMeta = qtrue; - } - - /* ydnar: gs mods: q3map_shadeAngle */ - else if( !Q_stricmp( token, "q3map_shadeAngle" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->shadeAngleDegrees = atof( token ); - } - - /* ydnar: q3map_textureSize (substitute for q3map_lightimage derivation for terrain) */ - else if( !Q_stricmp( token, "q3map_textureSize" ) ) - { - GetTokenAppend( shaderText, qfalse ); - si->shaderWidth = atoi( token ); - GetTokenAppend( shaderText, qfalse ); - si->shaderHeight = atoi( token ); - } - - /* ydnar: gs mods: q3map_tcGen + + +

Xonotic Mapping Wiki

+ + diff --git a/misc/mediasource/netradiant-src/download-gamepacks.sh b/misc/mediasource/netradiant-src/download-gamepacks.sh new file mode 100644 index 00000000..2d6c1b78 --- /dev/null +++ b/misc/mediasource/netradiant-src/download-gamepacks.sh @@ -0,0 +1,160 @@ +#!/bin/sh + +# Usage: +# sh download-gamepack.sh +# LICENSEFILTER=GPL BATCH=1 sh download-gamepack.sh + +: ${GIT:=git} +: ${SVN:=svn} +: ${WGET:=wget} +: ${ECHO:=echo} +: ${MKDIR:=mkdir} +: ${RM_R:=rm -f -r} +: ${MV:=mv} +: ${UNZIPPER:=unzip} + +set -e + +extra_urls() +{ + if [ -f "$1/extra-urls.txt" ]; then + while IFS=" " read -r FILE URL; do + $WGET -O "$1/$FILE" "$URL" + done < "$1/extra-urls.txt" + fi +} + +pack() +{ + pack=$1; shift + license=$1; shift + sourcetype=$1; shift + source=$1; shift + + if [ -d "games/$pack" ]; then + $ECHO "Updating $pack..." + case "$sourcetype" in + svn) + $SVN update "games/$pack" "$@" || true + ;; + zip1) + $RM_R zipdownload + $MKDIR zipdownload + cd zipdownload + $WGET "$source" "$@" || true + $UNZIPPER *.zip || true + cd .. + $RM_R "games/$pack" + $MKDIR "games/$pack" + $MV zipdownload/*/* "games/$pack/" || true + $RM_R zipdownload + ;; + gitdir) + $RM_R "games/$pack" + cd games + $GIT archive --remote="$source" --prefix="$pack/" "$2":"$1" | tar xvf - || true + cd .. + ;; + git) + cd "games/$pack" + $GIT pull || true + cd ../.. + ;; + esac + extra_urls "games/$pack" + return + fi + + $ECHO + $ECHO "Available pack: $pack" + $ECHO " License: $license" + $ECHO " Download via $sourcetype from $source" + $ECHO + case " $PACKFILTER " in + " ") + ;; + *" $pack "*) + ;; + *) + $ECHO "Pack $pack rejected because it is not in PACKFILTER." + return + ;; + esac + case " $LICENSEFILTER " in + " ") + ;; + *" $license "*) + ;; + *) + $ECHO "Pack $pack rejected because its license is not in LICENSEFILTER." + return + ;; + esac + case "$BATCH" in + '') + while :; do + $ECHO "Download this pack? (y/n)" + read -r P + case "$P" in + y*) + break + ;; + n*) + return + ;; + esac + done + ;; + *) + ;; + esac + + $ECHO "Downloading $pack..." + case "$sourcetype" in + svn) + $SVN checkout "$source" "games/$pack" "$@" || true + ;; + zip1) + $RM_R zipdownload + $MKDIR zipdownload + cd zipdownload + $WGET "$source" "$@" || true + $UNZIPPER *.zip || true + cd .. + $MKDIR "games/$pack" + $MV zipdownload/*/* "games/$pack/" || true + $RM_R zipdownload + ;; + gitdir) + cd games + $GIT archive --remote="$source" --prefix="$pack/" "$2":"$1" | tar xvf - || true + cd .. + ;; + git) + cd games + $GIT clone "$source" "$pack" || true + cd .. + ;; + esac + extra_urls "games/$pack" + good=false + for D in "games/$pack"/*.game; do + if [ -d "$D" ]; then + good=true + fi + done + $good || rm -rf "$D" +} + +mkdir -p games +pack DarkPlacesPack GPL svn https://zerowing.idsoftware.com/svn/radiant.gamepacks/DarkPlacesPack/branches/1.5/ +pack NexuizPack GPL gitdir git://git.icculus.org/divverent/nexuiz.git misc/netradiant-NexuizPack master +pack OpenArenaPack unknown zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/OpenArenaPack.zip +pack Q3Pack proprietary svn https://zerowing.idsoftware.com/svn/radiant.gamepacks/Q3Pack/trunk/ -r29 +pack Quake2Pack proprietary zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/Quake2Pack.zip +pack Quake2WorldPack GPL svn svn://jdolan.dyndns.org/quake2world/trunk/gtkradiant +pack QuakePack proprietary zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/QuakePack.zip +pack TremulousPack proprietary zip1 http://ingar.satgnu.net/files/gtkradiant/gamepacks/TremulousPack.zip +pack UFOAIPack proprietary svn https://zerowing.idsoftware.com/svn/radiant.gamepacks/UFOAIPack/branches/1.5/ +pack WarsowPack GPL svn https://svn.bountysource.com/wswpack/trunk/netradiant/games/WarsowPack/ +pack XonoticPack GPL git git://git.xonotic.org/xonotic/netradiant-xonoticpack.git diff --git a/misc/mediasource/netradiant-src/gen.readme b/misc/mediasource/netradiant-src/gen.readme new file mode 100644 index 00000000..4b735df4 --- /dev/null +++ b/misc/mediasource/netradiant-src/gen.readme @@ -0,0 +1,4 @@ +Dummy file for gen.dsp + +gen.dsp is used with MSVC to generate include/version.h and include/aboutmsg.h +you need python installed and configured to make this work diff --git a/misc/mediasource/netradiant-src/gendox b/misc/mediasource/netradiant-src/gendox new file mode 100644 index 00000000..c25663fb --- /dev/null +++ b/misc/mediasource/netradiant-src/gendox @@ -0,0 +1,150 @@ +#!/bin/bash +# +# Shell script to make doxygen documentation by specifying a target directory +# on the command line +# +# Gef (gefdavis@dingoblue.net.au) -- August 2001 + +# TODO: +# - Dynamic ChangeLog (page gets updated with each commit) +# - Have the ability to specify server dox or local dox, which will then +# change the content on the main page +# - Incorporate a scaled gtkradiant splash image into the pages + +#------------------------------------------------------------------------ +# Set some variables +#------------------------------------------------------------------------ +# WORKINGDIR=`pwd`; +RETVAL=0; +TARGETSTRING=''; +EXTRAS_PATH="./Doxygen_files"; +CONFIG_OUTPUT="$EXTRAS_PATH/genConf"; +DOXYCONFIG="./DoxyConfig"; +DOXYFILE="$EXTRAS_PATH/Doxyfile"; +NEWDOXYFILE="$EXTRAS_PATH/genDoxyfile"; +declare -a TARGETLIST[$#]; +COUNTER=0; +TARGETCOUNT=0; +QUIETMODE=0; +# added -k command line option to kill running doxygen procs +KILLON=0 + +#------------------------------------------------------------------------ +# load the functions +#------------------------------------------------------------------------ +if [ -f "$EXTRAS_PATH/gendoxfunctions" ] ; then + . $EXTRAS_PATH/gendoxfunctions +else + echo -e "Missing critical files...\n"; + exit 1; +fi + +#------------------------------------------------------------------------ +# parse the command line options +#------------------------------------------------------------------------ +COMLINE="$*"; +OPTCOUNT="$#"; +parse_commandline; +if [ $RETVAL -gt 0 ] ; then + echo -e "Exiting."; + exit $RETVAL; +fi + + +if [ $KILLON -gt 0 ] ; then + PIDOF_DOXYGEN=`pidof -x doxygen` + MYPID=$$ + + if [ -z "$PIDOF_DOXYGEN" ] ; then + [ $QUIETMODE -gt 0 ] || echo -e " * Killing other doxygen pids"; + killall -q -9 doxygen + else + [ $QUIETMODE -gt 0 ] || echo -e " * Killing other doxygen pids"; + kill -9 $PIDOF_DOXYGEN &> /dev/null + fi + + [ $QUIETMODE -gt 0 ] || echo -e " * Cleaning up gendox pids"; + killall -q -9 `pidof -x gendox | sed -e s/$MYPID//` &> /dev/null + +fi + +# If the output dir hasn't been set yet... +#if [ -z "$OUTPUTDIR" ] ; then +# OUTPUTDIR="../$(basename `pwd`)-doxygen"; +#fi + +#------------------------------------------------------------------------ +# execute some functions to determine stuff(c) +# Get the perl path (either from the config file, or find it) +#------------------------------------------------------------------------ +get_perlpath; +if [ X"$PERLPATH" == "X" ] ; then + echo -e "\nError: A working install of perl is needed to use doxygen"; + exit 2; +fi +[ $QUIETMODE -gt 0 ] || echo -e " -> Set PERL_PATH to: $PERLPATH"; + +get_dotpath; +[ $QUIETMODE -gt 0 ] || echo -e " -> Set HAVE_DOT to: $HAVEDOT"; +if [ X"$HAVEDOT" == "XYes" ] ; then + [ $QUIETMODE -gt 0 ] || echo -e " -> Set DOT_PATH to: $DOTPATH"; +fi + +get_language; +[ $QUIETMODE -gt 0 ] || echo -e " -> Set OUTPUT_LANGUAGE to: $OUPUTLANGUAGE"; + +get_projectname; +[ $QUIETMODE -gt 0 ] || echo -e " -> Set PROJECT_NAME to: $PROJECTNAME"; + +get_version; +[ $QUIETMODE -gt 0 ] || echo -e " -> Set PROJECT_NUMBER to: $VERSION"; +#------------------------------------------------------------------------ +# Got everything we need, now write the DoxyConfig file and run doxygen +#------------------------------------------------------------------------ + +# Clean up first +clean_up; + +# Put the images & reference pages in the right place +move_stuff; +if [ $RETVAL -ge 666 ] ; then + exit 666; +fi + +# Generate the config file +gen_doxyconfig; +if [ $RETVAL -gt 0 ] ; then + echo -e "Error: You are missing critical files." + exit RETVAL; +fi + +# build the reference page and the index +build_extra_html; + +# Generate documentation +RETVAL=0; +run_doxygen; +if [ $RETVAL -gt 0 ] ; then + echo -e "Doxygen error: returned $RETVAL"; + echo -e " Check doxygen.log for details"; +elif [ $RETVAL -lt 0 ] ; then + echo -e "Doxygen error: Doxygen returned $RETVAL"; +fi + +# if the log file is empty, remove it +if [ ! -s ./doxygen.log ] ; then + rm -f ./doxygen.log +fi + +#------------------------------------------------------------------------ +# Done. +#------------------------------------------------------------------------ +[ $QUIETMODE -gt 0 ] || echo -e "Finished..."; +[ $QUIETMODE -gt 0 ] || echo -e "Duration: $SECONDS seconds\n"; + +# echo -e "** Removing output while in debug mode **"; +# echo -e "** Output dir: $OUTPUTDIR **\n"; +# rm -rf $OUTPUTDIR + +exit 0; + diff --git a/misc/mediasource/netradiant-src/generic_cpp.py b/misc/mediasource/netradiant-src/generic_cpp.py new file mode 100644 index 00000000..62d51ed9 --- /dev/null +++ b/misc/mediasource/netradiant-src/generic_cpp.py @@ -0,0 +1,40 @@ +# Copyright (C) 2001-2006 William Joseph. +# 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 + + +import os +import sys + +def svnAddText(filename): + os.system("svn add " + filename); + os.system("svn ps svn:eol-style native " + filename); + +def createCPPTemplate(filename, name): + file = open(filename, "wt") + file.write("\n") + file.write("#include \"" + name + ".h\"\n") + file.write("\n") + file.close() + +if __name__ == "__main__": + name = sys.argv[1] + location = sys.argv[2] + filename = os.path.join(location, name + ".cpp") + createCPPTemplate(filename, name) + svnAddText(filename) diff --git a/misc/mediasource/netradiant-src/generic_h.py b/misc/mediasource/netradiant-src/generic_h.py new file mode 100644 index 00000000..9f8b7e98 --- /dev/null +++ b/misc/mediasource/netradiant-src/generic_h.py @@ -0,0 +1,41 @@ +# Copyright (C) 2001-2006 William Joseph. +# 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 + + +import os +import sys + +def svnAddText(filename): + os.system("svn add " + filename); + os.system("svn ps svn:eol-style native " + filename); + +def createHeaderTemplate(filename, name): + file = open(filename, "wt") + file.write("\n") + file.write("#if !defined(_INCLUDED_" + name.upper() + "_H_)\n") + file.write("#define _INCLUDED_" + name.upper() + "_H_\n") + file.write("\n") + file.write("#endif\n") + +if __name__ == "__main__": + name = sys.argv[1] + location = sys.argv[2] + filename = os.path.join(location, name + ".h") + createHeaderTemplate(filename, name) + svnAddText(filename) diff --git a/misc/mediasource/netradiant-src/generic_module.py b/misc/mediasource/netradiant-src/generic_module.py new file mode 100644 index 00000000..e055e8fa --- /dev/null +++ b/misc/mediasource/netradiant-src/generic_module.py @@ -0,0 +1,59 @@ +# Copyright (C) 2001-2006 William Joseph. +# 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 + + +import os +import sys + +def svnAddText(filename): + os.system("svn add " + filename); + os.system("svn ps svn:eol-style native " + filename); + +def createHeaderTemplate(filename, name): + file = open(filename, "wt") + file.write("\n") + file.write("#if !defined(INCLUDED_" + name.upper() + "_H)\n") + file.write("#define INCLUDED_" + name.upper() + "_H\n") + file.write("\n") + file.write("#endif\n") + +def createCPPTemplate(filename, name): + file = open(filename, "wt") + file.write("\n") + file.write("#include \"" + name + ".h\"\n") + file.write("\n") + file.close() + +if __name__ == "__main__": + if not len(sys.argv) == 2: + print "usage: " + sys.argv[0] + " " + + path = sys.argv[1] + name = os.path.split(path)[1]; + + h = os.path.normpath(path + ".h") + print "writing " + h; + createHeaderTemplate(h, name) + svnAddText(h) + + cpp = os.path.normpath(path + ".cpp") + print "writing " + cpp; + createCPPTemplate(cpp, name) + svnAddText(cpp) + diff --git a/misc/mediasource/netradiant-src/icons/h2data.ico b/misc/mediasource/netradiant-src/icons/h2data.ico new file mode 100644 index 00000000..8f441941 Binary files /dev/null and b/misc/mediasource/netradiant-src/icons/h2data.ico differ diff --git a/misc/mediasource/netradiant-src/icons/q2map.ico b/misc/mediasource/netradiant-src/icons/q2map.ico new file mode 100644 index 00000000..5c508c91 Binary files /dev/null and b/misc/mediasource/netradiant-src/icons/q2map.ico differ diff --git a/misc/mediasource/netradiant-src/icons/q3data.ico b/misc/mediasource/netradiant-src/icons/q3data.ico new file mode 100644 index 00000000..8f441941 Binary files /dev/null and b/misc/mediasource/netradiant-src/icons/q3data.ico differ diff --git a/misc/mediasource/netradiant-src/icons/q3map2.ico b/misc/mediasource/netradiant-src/icons/q3map2.ico new file mode 100644 index 00000000..4fe56fa6 Binary files /dev/null and b/misc/mediasource/netradiant-src/icons/q3map2.ico differ diff --git a/misc/mediasource/netradiant-src/icons/qdata3.ico b/misc/mediasource/netradiant-src/icons/qdata3.ico new file mode 100644 index 00000000..8f441941 Binary files /dev/null and b/misc/mediasource/netradiant-src/icons/qdata3.ico differ diff --git a/misc/mediasource/netradiant-src/icons/radiant-src.png b/misc/mediasource/netradiant-src/icons/radiant-src.png new file mode 100644 index 00000000..720e9857 Binary files /dev/null and b/misc/mediasource/netradiant-src/icons/radiant-src.png differ diff --git a/misc/mediasource/netradiant-src/icons/radiant.ico b/misc/mediasource/netradiant-src/icons/radiant.ico new file mode 100644 index 00000000..d377f825 Binary files /dev/null and b/misc/mediasource/netradiant-src/icons/radiant.ico differ diff --git a/misc/mediasource/netradiant-src/include/aboutmsg.default b/misc/mediasource/netradiant-src/include/aboutmsg.default new file mode 100644 index 00000000..0f536453 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/aboutmsg.default @@ -0,0 +1 @@ +Custom build based on trunk \ No newline at end of file diff --git a/misc/mediasource/netradiant-src/include/aboutmsg.h b/misc/mediasource/netradiant-src/include/aboutmsg.h new file mode 100644 index 00000000..8b5acc2c --- /dev/null +++ b/misc/mediasource/netradiant-src/include/aboutmsg.h @@ -0,0 +1,4 @@ +// Makefile appends preprocessor flags instead now +#ifndef RADIANT_ABOUTMSG +#error no RADIANT_ABOUTMSG defined +#endif diff --git a/misc/mediasource/netradiant-src/include/cullable.cpp b/misc/mediasource/netradiant-src/include/cullable.cpp new file mode 100644 index 00000000..352ea5d6 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/cullable.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "cullable.h" + diff --git a/misc/mediasource/netradiant-src/include/cullable.h b/misc/mediasource/netradiant-src/include/cullable.h new file mode 100644 index 00000000..8e3c71bc --- /dev/null +++ b/misc/mediasource/netradiant-src/include/cullable.h @@ -0,0 +1,71 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_CULLABLE_H) +#define INCLUDED_CULLABLE_H + +#include "generic/constant.h" + +template class BasicVector3; +typedef BasicVector3 Vector3; +class Plane3; +class Matrix4; +class AABB; +class Segment; + +template class EnumeratedValue; +struct VolumeIntersection; +typedef EnumeratedValue VolumeIntersectionValue; + +class VolumeTest +{ +public: + + /// \brief Returns true if \p point intersects volume. + virtual bool TestPoint(const Vector3& point) const = 0; + /// \brief Returns true if \p segment intersects volume. + virtual bool TestLine(const Segment& segment) const = 0; + /// \brief Returns true if \p plane faces towards volume. + virtual bool TestPlane(const Plane3& plane) const = 0; + /// \brief Returns true if \p plane transformed by \p localToWorld faces the viewer. + virtual bool TestPlane(const Plane3& plane, const Matrix4& localToWorld) const = 0; + /// \brief Returns the intersection of \p aabb and volume. + virtual VolumeIntersectionValue TestAABB(const AABB& aabb) const = 0; + /// \brief Returns the intersection of \p aabb transformed by \p localToWorld and volume. + virtual VolumeIntersectionValue TestAABB(const AABB& aabb, const Matrix4& localToWorld) const = 0; + + virtual bool fill() const = 0; + + virtual const Matrix4& GetViewport() const = 0; + virtual const Matrix4& GetProjection() const = 0; + virtual const Matrix4& GetModelview() const = 0; +}; + +class Cullable +{ +public: + STRING_CONSTANT(Name, "Cullable"); + + virtual VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const = 0; +}; + + +#endif diff --git a/misc/mediasource/netradiant-src/include/editable.cpp b/misc/mediasource/netradiant-src/include/editable.cpp new file mode 100644 index 00000000..bcd04d8a --- /dev/null +++ b/misc/mediasource/netradiant-src/include/editable.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "editable.h" + diff --git a/misc/mediasource/netradiant-src/include/editable.h b/misc/mediasource/netradiant-src/include/editable.h new file mode 100644 index 00000000..9e9bac04 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/editable.h @@ -0,0 +1,60 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_EDITABLE_H) +#define INCLUDED_EDITABLE_H + +template class BasicVector3; +typedef BasicVector3 Vector3; +template class BasicVector4; +typedef BasicVector4 Vector4; +class Matrix4; +typedef Vector4 Quaternion; + +#include "scenelib.h" + +class Editable +{ +public: + STRING_CONSTANT(Name, "Editable"); + + virtual const Matrix4& getLocalPivot() const = 0; +}; + +inline Editable* Node_getEditable(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +class Snappable +{ +public: + STRING_CONSTANT(Name, "Snappable"); + + virtual void snapto(float snap) = 0; +}; + +inline Snappable* Node_getSnappable(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/iarchive.cpp b/misc/mediasource/netradiant-src/include/iarchive.cpp new file mode 100644 index 00000000..b975bf05 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iarchive.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "iarchive.h" + diff --git a/misc/mediasource/netradiant-src/include/iarchive.h b/misc/mediasource/netradiant-src/include/iarchive.h new file mode 100644 index 00000000..b3f21016 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iarchive.h @@ -0,0 +1,162 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IARCHIVE_H) +#define INCLUDED_IARCHIVE_H + +#include +#include "generic/constant.h" + +class InputStream; + +/// \brief A file opened in binary mode. +class ArchiveFile +{ +public: + /// \brief Destroys the file object. + virtual void release() = 0; + /// \brief Returns the size of the file data in bytes. + virtual std::size_t size() const = 0; + /// \brief Returns the path to this file (relative to the filesystem root) + virtual const char* getName() const = 0; + /// \brief Returns the stream associated with this file. + /// Subsequent calls return the same stream. + /// The stream may be read forwards until it is exhausted. + /// The stream remains valid for the lifetime of the file. + virtual InputStream& getInputStream() = 0; +}; + +class TextInputStream; + +/// \brief A file opened in text mode. +class ArchiveTextFile +{ +public: + /// \brief Destroys the file object. + virtual void release() = 0; + /// \brief Returns the stream associated with this file. + /// Subsequent calls return the same stream. + /// The stream may be read forwards until it is exhausted. + /// The stream remains valid for the lifetime of the file. + virtual TextInputStream& getInputStream() = 0; +}; + +class ScopedArchiveFile +{ + ArchiveFile& m_file; +public: + ScopedArchiveFile(ArchiveFile& file) : m_file(file) + { + } + ~ScopedArchiveFile() + { + m_file.release(); + } +}; + +class CustomArchiveVisitor; + +class Archive +{ +public: + + class Visitor + { + public: + virtual void visit(const char* name) = 0; + }; + + typedef CustomArchiveVisitor VisitorFunc; + + enum EMode + { + eFiles = 0x01, + eDirectories = 0x02, + eFilesAndDirectories = 0x03, + }; + + /// \brief Destroys the archive object. + /// Any unreleased file object associated with the archive remains valid. */ + virtual void release() = 0; + /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. + /// Name comparisons are case-insensitive. + virtual ArchiveFile* openFile(const char* name) = 0; + /// \brief Returns a new object associated with the file identified by \p name, or 0 if the file cannot be opened. + /// Name comparisons are case-insensitive. + virtual ArchiveTextFile* openTextFile(const char* name) = 0; + /// Returns true if the file identified by \p name can be opened. + /// Name comparisons are case-insensitive. + virtual bool containsFile(const char* name) = 0; + /// \brief Performs a depth-first traversal of the archive tree starting at \p root. + /// Traverses the entire tree if \p root is "". + /// When a file is encountered, calls \c visitor.file passing the file name. + /// When a directory is encountered, calls \c visitor.directory passing the directory name. + /// Skips the directory if \c visitor.directory returned true. + /// Root comparisons are case-insensitive. + /// Names are mixed-case. + virtual void forEachFile(VisitorFunc visitor, const char* root) = 0; +}; + +class CustomArchiveVisitor +{ + Archive::Visitor* m_visitor; + Archive::EMode m_mode; + std::size_t m_depth; +public: + CustomArchiveVisitor(Archive::Visitor& visitor, Archive::EMode mode, std::size_t depth) + : m_visitor(&visitor), m_mode(mode), m_depth(depth) + { + } + void file(const char* name) + { + if((m_mode & Archive::eFiles) != 0) + m_visitor->visit(name); + } + bool directory(const char* name, std::size_t depth) + { + if((m_mode & Archive::eDirectories) != 0) + m_visitor->visit(name); + if(depth == m_depth) + return true; + return false; + } +}; + +typedef Archive* (*PFN_OPENARCHIVE) (const char* name); + +class _QERArchiveTable +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "archive"); + + PFN_OPENARCHIVE m_pfnOpenArchive; +}; + +template +class Modules; +typedef Modules<_QERArchiveTable> ArchiveModules; + +template +class ModulesRef; +typedef ModulesRef<_QERArchiveTable> ArchiveModulesRef; + +#endif diff --git a/misc/mediasource/netradiant-src/include/ibrush.cpp b/misc/mediasource/netradiant-src/include/ibrush.cpp new file mode 100644 index 00000000..05dc91ef --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ibrush.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "ibrush.h" + diff --git a/misc/mediasource/netradiant-src/include/ibrush.h b/misc/mediasource/netradiant-src/include/ibrush.h new file mode 100644 index 00000000..ddc82559 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ibrush.h @@ -0,0 +1,127 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IBRUSH_H) +#define INCLUDED_IBRUSH_H + +#include "generic/constant.h" +#include "generic/callback.h" +#include "generic/vector.h" +#include "itexdef.h" + +namespace scene +{ + class Node; +} + +#if 0 +class IBrushFace +{ +public: + virtual const char* GetShader() const = 0; + virtual void SetShader(const char* name) = 0; + virtual const TextureProjection& GetTexdef() const = 0; + virtual void GetTexdef(TextureProjection& projection) const = 0; + virtual void SetTexdef(const TextureProjection& projection) = 0; + virtual void GetFlags(ContentsFlagsValue& flags) const = 0; + virtual void SetFlags(const ContentsFlagsValue& flags) = 0; + virtual void ShiftTexdef(float s, float t) = 0; + virtual void ScaleTexdef(float s, float t) = 0; + virtual void RotateTexdef(float angle) = 0; + virtual void FitTexture(float s_repeat, float t_repeat) = 0; + virtual bool isDetail() const = 0; + virtual void setDetail(bool detail) = 0; +}; + +class IBrush +{ +public: + STRING_CONSTANT(Name, "IBrush"); + virtual void reserve(std::size_t count) = 0; + virtual void clear() = 0; + virtual void copy(const IBrush& other) = 0; + virtual IBrushFace* addPlane(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection) = 0; + virtual const AABB& localAABB() const = 0; + virtual void removeEmptyFaces() = 0; +}; + +class IBrushFaceInstance +{ +public: + virtual IBrushFace& getFace() = 0; + virtual const IBrushFace& getFace() const = 0; + virtual bool isSelected() const = 0; + virtual void setSelected(SelectionSystem::EComponentMode mode, bool select) const = 0; +}; + +class IBrushInstance +{ +public: + STRING_CONSTANT(Name, "IBrushInstance"); + virtual void forEachFaceInstance(const BrushInstanceVisitor& visitor) = 0; +}; +#endif + +class _QERFaceData +{ +public: + _QERFaceData() : m_shader(""), contents(0), flags(0), value(0) + { + } + Vector3 m_p0; + Vector3 m_p1; + Vector3 m_p2; + texdef_t m_texdef; + const char* m_shader; + int contents; + int flags; + int value; +}; + +typedef Callback1 BrushFaceDataCallback; + +class BrushCreator +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "brush"); + virtual scene::Node& createBrush() = 0; + virtual bool useAlternativeTextureProjection() const = 0; + virtual void Brush_forEachFace(scene::Node& brush, const BrushFaceDataCallback& callback) = 0; + virtual bool Brush_addFace(scene::Node& brush, const _QERFaceData& faceData) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalBrushModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalBrushModuleRef; + +inline BrushCreator& GlobalBrushCreator() +{ + return GlobalBrushModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/icamera.cpp b/misc/mediasource/netradiant-src/include/icamera.cpp new file mode 100644 index 00000000..436e93a9 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/icamera.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 1999-2006 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 "icamera.h" + diff --git a/misc/mediasource/netradiant-src/include/icamera.h b/misc/mediasource/netradiant-src/include/icamera.h new file mode 100644 index 00000000..c98fdc06 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/icamera.h @@ -0,0 +1,67 @@ +/* +Copyright (C) 1999-2006 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: +// camera interface +// + +#if !defined(INCLUDED_ICAMERA_H) +#define INCLUDED_ICAMERA_H + +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +class Matrix4; + +class CameraView +{ +public: + virtual void setModelview(const Matrix4& modelview) = 0; + virtual void setFieldOfView(float fieldOfView) = 0; +}; + +class CameraModel +{ +public: + STRING_CONSTANT(Name, "CameraModel"); + virtual void setCameraView(CameraView* view, const Callback& disconnect) = 0; +}; + +template class BasicVector3; +typedef BasicVector3 Vector3; + +typedef void (* PFN_GETCAMERA) ( Vector3& origin, Vector3& angles ); +typedef void (* PFN_SETCAMERA) ( const Vector3& origin, const Vector3& angles ); +typedef void (* PFN_GETCAMWINDOWEXTENTS) ( int *x, int *y, int *width, int *height ); + +struct _QERCameraTable +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "camera"); + + PFN_GETCAMERA m_pfnGetCamera; + PFN_SETCAMERA m_pfnSetCamera; + PFN_GETCAMWINDOWEXTENTS m_pfnGetCamWindowExtents; +}; + +#endif diff --git a/misc/mediasource/netradiant-src/include/idatastream.cpp b/misc/mediasource/netradiant-src/include/idatastream.cpp new file mode 100644 index 00000000..fff02b57 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/idatastream.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "idatastream.h" + diff --git a/misc/mediasource/netradiant-src/include/idatastream.h b/misc/mediasource/netradiant-src/include/idatastream.h new file mode 100644 index 00000000..c5a28a25 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/idatastream.h @@ -0,0 +1,83 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IDATASTREAM_H) +#define INCLUDED_IDATASTREAM_H + +#include + +class StreamBase +{ +public: + typedef std::size_t size_type; + typedef unsigned char byte_type; +}; + +/// \brief A read-only byte-stream. +class InputStream : public StreamBase +{ +public: + /// \brief Attempts to read the next \p length bytes from the stream to \p buffer. + /// Returns the number of bytes actually stored in \p buffer. + virtual size_type read(byte_type* buffer, size_type length) = 0; +}; + +/// \brief A write-only byte-stream. +class OutputStream : public StreamBase +{ +public: + /// \brief Attempts to write \p length bytes to the stream from \p buffer. + /// Returns the number of bytes actually read from \p buffer. + virtual size_type write(const byte_type* buffer, size_type length) = 0; +}; + +class SeekableStream +{ +public: + typedef int offset_type; + typedef std::size_t position_type; + + enum seekdir + { + beg, + cur, + end, + }; + + /// \brief Sets the current \p position of the stream relative to the start. + virtual position_type seek(position_type position) = 0; + /// \brief Sets the current \p position of the stream relative to either the start, end or current position. + virtual position_type seek(offset_type offset, seekdir direction) = 0; + /// \brief Returns the current position of the stream. + virtual position_type tell() const = 0; +}; + +/// \brief A seekable read-only byte-stream. +class SeekableInputStream : public InputStream, public SeekableStream +{ +}; + +/// \brief A seekable write-only byte-stream. +class SeekableOutputStream : public OutputStream, public SeekableStream +{ +}; + +#endif diff --git a/misc/mediasource/netradiant-src/include/ieclass.cpp b/misc/mediasource/netradiant-src/include/ieclass.cpp new file mode 100644 index 00000000..461edd53 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ieclass.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 1999-2006 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 "ieclass.h" + diff --git a/misc/mediasource/netradiant-src/include/ieclass.h b/misc/mediasource/netradiant-src/include/ieclass.h new file mode 100644 index 00000000..89b86ca9 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ieclass.h @@ -0,0 +1,118 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +/// \file ieclass.h +/// \brief Entity Class definition loader API. + + +#if !defined(INCLUDED_IECLASS_H) +#define INCLUDED_IECLASS_H + +#include "generic/constant.h" + +#define MAX_FLAGS 16 + +// eclass show flags + +#define ECLASS_LIGHT 0x00000001 +#define ECLASS_ANGLE 0x00000002 +#define ECLASS_PATH 0x00000004 +#define ECLASS_MISCMODEL 0x00000008 + +class Shader; + +class EntityClass; +class ListAttributeType; + +class EntityClassCollector +{ +public: + virtual void insert(EntityClass* eclass) = 0; + virtual void insert(const char* name, const ListAttributeType& list) + { + } +}; + +struct EntityClassScanner +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "eclass"); + + void (*scanFile)(EntityClassCollector& collector, const char* filename); + const char* (*getExtension)(); +}; + +#include "modulesystem.h" + +template +class ModuleRef; +typedef ModuleRef EClassModuleRef; + +template +class Modules; +typedef Modules EClassModules; + +template +class ModulesRef; +typedef ModulesRef EClassModulesRef; + + + + + + +class EntityClassVisitor +{ +public: + virtual void visit(EntityClass* eclass) = 0; +}; + +class ModuleObserver; + + +struct EntityClassManager +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "eclassmanager"); + + EntityClass* (*findOrInsert)(const char* name, bool has_brushes); + const ListAttributeType* (*findListType)(const char* name); + void (*forEach)(EntityClassVisitor& visitor); + void (*attach)(ModuleObserver& observer); + void (*detach)(ModuleObserver& observer); + void (*realise)(); + void (*unrealise)(); +}; + +template +class GlobalModule; +typedef GlobalModule GlobalEntityClassManagerModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalEntityClassManagerModuleRef; + +inline EntityClassManager& GlobalEntityClassManager() +{ + return GlobalEntityClassManagerModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/ientity.cpp b/misc/mediasource/netradiant-src/include/ientity.cpp new file mode 100644 index 00000000..0a2eef32 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ientity.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "ientity.h" + diff --git a/misc/mediasource/netradiant-src/include/ientity.h b/misc/mediasource/netradiant-src/include/ientity.h new file mode 100644 index 00000000..c74ed7c6 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ientity.h @@ -0,0 +1,154 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IENTITY_H) +#define INCLUDED_IENTITY_H + +#include "generic/constant.h" + +#include "string/string.h" +#include "scenelib.h" + +class EntityClass; + +typedef Callback1 KeyObserver; + +class EntityKeyValue +{ +public: + virtual const char* c_str() const = 0; + virtual void assign(const char* other) = 0; + virtual void attach(const KeyObserver& observer) = 0; + virtual void detach(const KeyObserver& observer) = 0; +}; + +class Entity +{ +public: + STRING_CONSTANT(Name, "Entity"); + + class Observer + { + public: + virtual void insert(const char* key, EntityKeyValue& value) = 0; + virtual void erase(const char* key, EntityKeyValue& value) = 0; + virtual void clear() { }; + }; + + class Visitor + { + public: + virtual void visit(const char* key, const char* value) = 0; + }; + + virtual const EntityClass& getEntityClass() const = 0; + virtual void forEachKeyValue(Visitor& visitor) const = 0; + virtual void setKeyValue(const char* key, const char* value) = 0; + virtual const char* getKeyValue(const char* key) const = 0; + virtual bool isContainer() const = 0; + virtual void attach(Observer& observer) = 0; + virtual void detach(Observer& observer) = 0; +}; + +class EntityCopyingVisitor : public Entity::Visitor +{ + Entity& m_entity; +public: + EntityCopyingVisitor(Entity& entity) + : m_entity(entity) + { + } + + void visit(const char* key, const char* value) + { + if(!string_equal(key, "classname")) + { + m_entity.setKeyValue(key, value); + } + } +}; + +inline Entity* Node_getEntity(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + + +template +class Stack; +template +class Reference; + +namespace scene +{ + class Node; +} + +typedef Reference NodeReference; + +namespace scene +{ + typedef Stack Path; +} + +class Counter; + +class EntityCreator +{ +public: + INTEGER_CONSTANT(Version, 2); + STRING_CONSTANT(Name, "entity"); + + virtual scene::Node& createEntity(EntityClass* eclass) = 0; + + typedef void (*KeyValueChangedFunc)(); + virtual void setKeyValueChangedFunc(KeyValueChangedFunc func) = 0; + + virtual void setCounter(Counter* counter) = 0; + + virtual void connectEntities(const scene::Path& e1, const scene::Path& e2, int index) = 0; + + virtual void setLightRadii(bool lightRadii) = 0; + virtual bool getLightRadii() = 0; + virtual void setShowNames(bool showNames) = 0; + virtual bool getShowNames() = 0; + virtual void setShowAngles(bool showAngles) = 0; + virtual bool getShowAngles() = 0; + + virtual void printStatistics() const = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalEntityModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalEntityModuleRef; + +inline EntityCreator& GlobalEntityCreator() +{ + return GlobalEntityModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/ifilesystem.cpp b/misc/mediasource/netradiant-src/include/ifilesystem.cpp new file mode 100644 index 00000000..d941113c --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ifilesystem.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "ifilesystem.h" + diff --git a/misc/mediasource/netradiant-src/include/ifilesystem.h b/misc/mediasource/netradiant-src/include/ifilesystem.h new file mode 100644 index 00000000..ed9e99fd --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ifilesystem.h @@ -0,0 +1,133 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IFILESYSTEM_H) +#define INCLUDED_IFILESYSTEM_H + +#include +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +typedef Callback1 ArchiveNameCallback; +typedef Callback1 FileNameCallback; + +class ArchiveFile; +class ArchiveTextFile; +class Archive; + +class ModuleObserver; + +typedef struct _GSList GSList; + +/// The Virtual File System. +class VirtualFileSystem +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "VFS"); + + /// \brief Adds a root search \p path. + /// Called before \c initialise. + virtual void initDirectory(const char *path) = 0; + /// \brief Initialises the filesystem. + /// Called after all root search paths have been added. + virtual void initialise() = 0; + /// \brief Shuts down the filesystem. + virtual void shutdown() = 0; + + /// \brief Returns the file identified by \p filename opened in binary mode, or 0 if not found. + /// The caller must \c release() the file returned if it is not 0. + virtual ArchiveFile* openFile(const char* filename) = 0; + /// \brief Returns the file identified by \p filename opened in text mode, or 0 if not found. + /// The caller must \c release() the file returned if it is not 0. + virtual ArchiveTextFile* openTextFile(const char* filename) = 0; + + /// \brief Opens the file identified by \p filename and reads it into \p buffer, or sets *\p buffer to 0 if not found. + /// Returns the size of the buffer allocated, or undefined value if *\p buffer is 0; + /// The caller must free the allocated buffer by calling \c freeFile + /// \deprecated Deprecated - use \c openFile. + virtual std::size_t loadFile(const char *filename, void **buffer) = 0; + /// \brief Frees the buffer returned by \c loadFile. + /// \deprecated Deprecated. + virtual void freeFile(void *p) = 0; + + /// \brief Calls \p callback for each directory under \p basedir. + virtual void forEachDirectory(const char* basedir, const FileNameCallback& callback, std::size_t depth = 1) = 0; + /// \brief Calls \p callback for each file under \p basedir matching \p extension. + /// Use "*" as \p extension to match all file extensions. + virtual void forEachFile(const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth = 1) = 0; + + /// \brief Returns a list containing the relative names of all the directories under \p basedir. + /// The caller must free the returned list by calling \c clearFileDirList; + /// \deprecated Deprecated - use \c forEachDirectory. + virtual GSList* getDirList(const char *basedir) = 0; + /// \brief Returns a list containing the relative names of the files under \p basedir (\p extension can be "*" for all files). + /// The caller must free the returned list by calling \c clearFileDirList. + /// \deprecated Deprecated - use \c forEachFile. + virtual GSList* getFileList(const char *basedir, const char *extension) = 0; + /// \brief Frees the \p list returned from \c getDirList or \c getFileList. + /// \deprecated Deprecated. + virtual void clearFileDirList(GSList **list) = 0; + + /// \brief Returns the absolute filename for a relative \p name, or "" if not found. + virtual const char* findFile(const char* name) = 0; + /// \brief Returns the filesystem root for an absolute \p name, or "" if not found. + /// This can be used to convert an absolute name to a relative name. + virtual const char* findRoot(const char* name) = 0; + + /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the filesystem is initialised or shut down. + virtual void attach(ModuleObserver& observer) = 0; + /// \brief Detach an \p observer previously-attached by calling \c attach. + virtual void detach(ModuleObserver& observer) = 0; + + virtual Archive* getArchive(const char* archiveName, bool pakonly=true) = 0; + virtual void forEachArchive(const ArchiveNameCallback& callback, bool pakonly=true, bool reverse=false) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalFileSystemModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalFileSystemModuleRef; + +inline VirtualFileSystem& GlobalFileSystem() +{ + return GlobalFileSystemModule::getTable(); +} + + +/// \deprecated Use \c openFile. +inline int vfsLoadFile(const char* filename, void** buffer, int index = 0) +{ + return static_cast(GlobalFileSystem().loadFile(filename, buffer)); +}; + +/// \deprecated Deprecated. +inline void vfsFreeFile(void* p) +{ + GlobalFileSystem().freeFile(p); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/ifiletypes.cpp b/misc/mediasource/netradiant-src/include/ifiletypes.cpp new file mode 100644 index 00000000..1d151586 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ifiletypes.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "ifiletypes.h" + diff --git a/misc/mediasource/netradiant-src/include/ifiletypes.h b/misc/mediasource/netradiant-src/include/ifiletypes.h new file mode 100644 index 00000000..0d061d2b --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ifiletypes.h @@ -0,0 +1,79 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IFILETYPES_H) +#define INCLUDED_IFILETYPES_H + +#include "generic/constant.h" + +class filetype_t +{ +public: + filetype_t() + : name(""), pattern("") + { + } + filetype_t(const char* _name, const char* _pattern, bool _can_load = true, bool _can_import = true, bool _can_save = true) + : name(_name), pattern(_pattern), can_load(_can_load), can_import(_can_import), can_save(_can_save) + { + } + const char* name; + const char* pattern; + bool can_load; + bool can_import; + bool can_save; +}; + + +class IFileTypeList +{ +public: + virtual void addType(const char* moduleName, filetype_t type) = 0; +}; + +class IFileTypeRegistry +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "filetypes"); + + virtual void addType(const char* moduleType, const char* moduleName, filetype_t type) = 0; + virtual void getTypeList(const char* moduleType, IFileTypeList* typelist, bool want_load = false, bool want_import = false, bool want_save = false) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalFiletypesModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalFiletypesModuleRef; + +inline IFileTypeRegistry& GlobalFiletypes() +{ + return GlobalFiletypesModule::getTable(); +} + + + +#endif diff --git a/misc/mediasource/netradiant-src/include/ifilter.cpp b/misc/mediasource/netradiant-src/include/ifilter.cpp new file mode 100644 index 00000000..1472a935 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ifilter.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "ifilter.h" + diff --git a/misc/mediasource/netradiant-src/include/ifilter.h b/misc/mediasource/netradiant-src/include/ifilter.h new file mode 100644 index 00000000..3da2f1d6 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ifilter.h @@ -0,0 +1,89 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IFILTER_H) +#define INCLUDED_IFILTER_H + +#include "generic/constant.h" + +enum +{ + EXCLUDE_WORLD = 0x00000001, + EXCLUDE_ENT = 0x00000002, + EXCLUDE_CURVES = 0x00000004, + EXCLUDE_TRANSLUCENT = 0x00000008, + EXCLUDE_LIQUIDS = 0x00000010, + EXCLUDE_CAULK = 0x00000020, + EXCLUDE_CLIP = 0x00000040, + EXCLUDE_PATHS = 0x00000080, + EXCLUDE_LIGHTS = 0x00000100, + EXCLUDE_DETAILS = 0x00000200, + EXCLUDE_HINTSSKIPS = 0x00000400, + EXCLUDE_MODELS = 0x00000800, + EXCLUDE_AREAPORTALS = 0x00001000, + EXCLUDE_TRIGGERS = 0x00002000, + EXCLUDE_CLUSTERPORTALS = 0x00004000, + EXCLUDE_TERRAIN = 0x00008000, + EXCLUDE_LIGHTGRID = 0x00010000, + EXCLUDE_STRUCTURAL = 0x00020000, + EXCLUDE_BOTCLIP = 0x00040000, + EXCLUDE_VISPORTALS = 0x00080000, + EXCLUDE_DECALS = 0x00100000, +}; + +class Filter +{ +public: + virtual void setActive(bool active) = 0; +}; + +class Filterable +{ +public: + virtual void updateFiltered() = 0; +}; + +class FilterSystem +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "filters"); + virtual void addFilter(Filter& filter, int mask) = 0; + virtual void registerFilterable(Filterable& filterable) = 0; + virtual void unregisterFilterable(Filterable& filterable) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalFilterModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalFilterModuleRef; + +inline FilterSystem& GlobalFilterSystem() +{ + return GlobalFilterModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/igl.cpp b/misc/mediasource/netradiant-src/include/igl.cpp new file mode 100644 index 00000000..170022ee --- /dev/null +++ b/misc/mediasource/netradiant-src/include/igl.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "igl.h" + diff --git a/misc/mediasource/netradiant-src/include/igl.h b/misc/mediasource/netradiant-src/include/igl.h new file mode 100644 index 00000000..35174967 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/igl.h @@ -0,0 +1,2834 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IGL_H) +#define INCLUDED_IGL_H + +#include +#include +#include "generic/constant.h" + +#if defined(WIN32) +#define QGL_DLLEXPORT __stdcall +#else +#define QGL_DLLEXPORT +#endif + +typedef unsigned int GLenum; +typedef unsigned char GLboolean; +typedef unsigned int GLbitfield; +typedef signed char GLbyte; +typedef short GLshort; +typedef int GLint; +typedef int GLsizei; +typedef unsigned char GLubyte; +typedef unsigned short GLushort; +typedef unsigned int GLuint; +typedef float GLfloat; +typedef float GLclampf; +typedef double GLdouble; +typedef double GLclampd; +typedef void GLvoid; + +#if !defined(GL_VERSION_1_1) +#define GL_VERSION_1_1 1 + +#define GL_ZERO 0 +#define GL_ONE 1 +#define GL_TRUE 1 +#define GL_FALSE 0 +#define GL_POINTS 0x0000 +#define GL_LINES 0x0001 +#define GL_LINE_LOOP 0x0002 +#define GL_LINE_STRIP 0x0003 +#define GL_TRIANGLES 0x0004 +#define GL_TRIANGLE_STRIP 0x0005 +#define GL_TRIANGLE_FAN 0x0006 +#define GL_QUADS 0x0007 +#define GL_QUAD_STRIP 0x0008 +#define GL_POLYGON 0x0009 +#define GL_ACCUM 0x0100 +#define GL_LOAD 0x0101 +#define GL_RETURN 0x0102 +#define GL_MULT 0x0103 +#define GL_ADD 0x0104 +#define GL_NEVER 0x0200 +#define GL_LESS 0x0201 +#define GL_EQUAL 0x0202 +#define GL_LEQUAL 0x0203 +#define GL_GREATER 0x0204 +#define GL_NOTEQUAL 0x0205 +#define GL_GEQUAL 0x0206 +#define GL_ALWAYS 0x0207 +#define GL_SRC_COLOR 0x0300 +#define GL_ONE_MINUS_SRC_COLOR 0x0301 +#define GL_SRC_ALPHA 0x0302 +#define GL_ONE_MINUS_SRC_ALPHA 0x0303 +#define GL_DST_ALPHA 0x0304 +#define GL_ONE_MINUS_DST_ALPHA 0x0305 +#define GL_DST_COLOR 0x0306 +#define GL_ONE_MINUS_DST_COLOR 0x0307 +#define GL_SRC_ALPHA_SATURATE 0x0308 +#define GL_BYTE 0x1400 +#define GL_UNSIGNED_BYTE 0x1401 +#define GL_SHORT 0x1402 +#define GL_UNSIGNED_SHORT 0x1403 +#define GL_INT 0x1404 +#define GL_UNSIGNED_INT 0x1405 +#define GL_FLOAT 0x1406 +#define GL_2_BYTES 0x1407 +#define GL_3_BYTES 0x1408 +#define GL_4_BYTES 0x1409 +#define GL_DOUBLE 0x140A +#define GL_NONE 0 +#define GL_FRONT_LEFT 0x0400 +#define GL_FRONT_RIGHT 0x0401 +#define GL_BACK_LEFT 0x0402 +#define GL_BACK_RIGHT 0x0403 +#define GL_FRONT 0x0404 +#define GL_BACK 0x0405 +#define GL_LEFT 0x0406 +#define GL_RIGHT 0x0407 +#define GL_FRONT_AND_BACK 0x0408 +#define GL_AUX0 0x0409 +#define GL_AUX1 0x040A +#define GL_AUX2 0x040B +#define GL_AUX3 0x040C +#define GL_NO_ERROR 0 +#define GL_INVALID_ENUM 0x0500 +#define GL_INVALID_VALUE 0x0501 +#define GL_INVALID_OPERATION 0x0502 +#define GL_STACK_OVERFLOW 0x0503 +#define GL_STACK_UNDERFLOW 0x0504 +#define GL_OUT_OF_MEMORY 0x0505 +#define GL_2D 0x0600 +#define GL_3D 0x0601 +#define GL_3D_COLOR 0x0602 +#define GL_3D_COLOR_TEXTURE 0x0603 +#define GL_4D_COLOR_TEXTURE 0x0604 +#define GL_PASS_THROUGH_TOKEN 0x0700 +#define GL_POINT_TOKEN 0x0701 +#define GL_LINE_TOKEN 0x0702 +#define GL_POLYGON_TOKEN 0x0703 +#define GL_BITMAP_TOKEN 0x0704 +#define GL_DRAW_PIXEL_TOKEN 0x0705 +#define GL_COPY_PIXEL_TOKEN 0x0706 +#define GL_LINE_RESET_TOKEN 0x0707 +#define GL_EXP 0x0800 +#define GL_EXP2 0x0801 +#define GL_CW 0x0900 +#define GL_CCW 0x0901 +#define GL_COEFF 0x0A00 +#define GL_ORDER 0x0A01 +#define GL_DOMAIN 0x0A02 +#define GL_CURRENT_COLOR 0x0B00 +#define GL_CURRENT_INDEX 0x0B01 +#define GL_CURRENT_NORMAL 0x0B02 +#define GL_CURRENT_TEXTURE_COORDS 0x0B03 +#define GL_CURRENT_RASTER_COLOR 0x0B04 +#define GL_CURRENT_RASTER_INDEX 0x0B05 +#define GL_CURRENT_RASTER_TEXTURE_COORDS 0x0B06 +#define GL_CURRENT_RASTER_POSITION 0x0B07 +#define GL_CURRENT_RASTER_POSITION_VALID 0x0B08 +#define GL_CURRENT_RASTER_DISTANCE 0x0B09 +#define GL_POINT_SMOOTH 0x0B10 +#define GL_POINT_SIZE 0x0B11 +#define GL_POINT_SIZE_RANGE 0x0B12 +#define GL_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_LINE_SMOOTH 0x0B20 +#define GL_LINE_WIDTH 0x0B21 +#define GL_LINE_WIDTH_RANGE 0x0B22 +#define GL_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_LINE_STIPPLE 0x0B24 +#define GL_LINE_STIPPLE_PATTERN 0x0B25 +#define GL_LINE_STIPPLE_REPEAT 0x0B26 +#define GL_LIST_MODE 0x0B30 +#define GL_MAX_LIST_NESTING 0x0B31 +#define GL_LIST_BASE 0x0B32 +#define GL_LIST_INDEX 0x0B33 +#define GL_POLYGON_MODE 0x0B40 +#define GL_POLYGON_SMOOTH 0x0B41 +#define GL_POLYGON_STIPPLE 0x0B42 +#define GL_EDGE_FLAG 0x0B43 +#define GL_CULL_FACE 0x0B44 +#define GL_CULL_FACE_MODE 0x0B45 +#define GL_FRONT_FACE 0x0B46 +#define GL_LIGHTING 0x0B50 +#define GL_LIGHT_MODEL_LOCAL_VIEWER 0x0B51 +#define GL_LIGHT_MODEL_TWO_SIDE 0x0B52 +#define GL_LIGHT_MODEL_AMBIENT 0x0B53 +#define GL_SHADE_MODEL 0x0B54 +#define GL_COLOR_MATERIAL_FACE 0x0B55 +#define GL_COLOR_MATERIAL_PARAMETER 0x0B56 +#define GL_COLOR_MATERIAL 0x0B57 +#define GL_FOG 0x0B60 +#define GL_FOG_INDEX 0x0B61 +#define GL_FOG_DENSITY 0x0B62 +#define GL_FOG_START 0x0B63 +#define GL_FOG_END 0x0B64 +#define GL_FOG_MODE 0x0B65 +#define GL_FOG_COLOR 0x0B66 +#define GL_DEPTH_RANGE 0x0B70 +#define GL_DEPTH_TEST 0x0B71 +#define GL_DEPTH_WRITEMASK 0x0B72 +#define GL_DEPTH_CLEAR_VALUE 0x0B73 +#define GL_DEPTH_FUNC 0x0B74 +#define GL_ACCUM_CLEAR_VALUE 0x0B80 +#define GL_STENCIL_TEST 0x0B90 +#define GL_STENCIL_CLEAR_VALUE 0x0B91 +#define GL_STENCIL_FUNC 0x0B92 +#define GL_STENCIL_VALUE_MASK 0x0B93 +#define GL_STENCIL_FAIL 0x0B94 +#define GL_STENCIL_PASS_DEPTH_FAIL 0x0B95 +#define GL_STENCIL_PASS_DEPTH_PASS 0x0B96 +#define GL_STENCIL_REF 0x0B97 +#define GL_STENCIL_WRITEMASK 0x0B98 +#define GL_MATRIX_MODE 0x0BA0 +#define GL_NORMALIZE 0x0BA1 +#define GL_VIEWPORT 0x0BA2 +#define GL_MODELVIEW_STACK_DEPTH 0x0BA3 +#define GL_PROJECTION_STACK_DEPTH 0x0BA4 +#define GL_TEXTURE_STACK_DEPTH 0x0BA5 +#define GL_MODELVIEW_MATRIX 0x0BA6 +#define GL_PROJECTION_MATRIX 0x0BA7 +#define GL_TEXTURE_MATRIX 0x0BA8 +#define GL_ATTRIB_STACK_DEPTH 0x0BB0 +#define GL_CLIENT_ATTRIB_STACK_DEPTH 0x0BB1 +#define GL_ALPHA_TEST 0x0BC0 +#define GL_ALPHA_TEST_FUNC 0x0BC1 +#define GL_ALPHA_TEST_REF 0x0BC2 +#define GL_DITHER 0x0BD0 +#define GL_BLEND_DST 0x0BE0 +#define GL_BLEND_SRC 0x0BE1 +#define GL_BLEND 0x0BE2 +#define GL_LOGIC_OP_MODE 0x0BF0 +#define GL_INDEX_LOGIC_OP 0x0BF1 +#define GL_COLOR_LOGIC_OP 0x0BF2 +#define GL_AUX_BUFFERS 0x0C00 +#define GL_DRAW_BUFFER 0x0C01 +#define GL_READ_BUFFER 0x0C02 +#define GL_SCISSOR_BOX 0x0C10 +#define GL_SCISSOR_TEST 0x0C11 +#define GL_INDEX_CLEAR_VALUE 0x0C20 +#define GL_INDEX_WRITEMASK 0x0C21 +#define GL_COLOR_CLEAR_VALUE 0x0C22 +#define GL_COLOR_WRITEMASK 0x0C23 +#define GL_INDEX_MODE 0x0C30 +#define GL_RGBA_MODE 0x0C31 +#define GL_DOUBLEBUFFER 0x0C32 +#define GL_STEREO 0x0C33 +#define GL_RENDER_MODE 0x0C40 +#define GL_PERSPECTIVE_CORRECTION_HINT 0x0C50 +#define GL_POINT_SMOOTH_HINT 0x0C51 +#define GL_LINE_SMOOTH_HINT 0x0C52 +#define GL_POLYGON_SMOOTH_HINT 0x0C53 +#define GL_FOG_HINT 0x0C54 +#define GL_TEXTURE_GEN_S 0x0C60 +#define GL_TEXTURE_GEN_T 0x0C61 +#define GL_TEXTURE_GEN_R 0x0C62 +#define GL_TEXTURE_GEN_Q 0x0C63 +#define GL_PIXEL_MAP_I_TO_I 0x0C70 +#define GL_PIXEL_MAP_S_TO_S 0x0C71 +#define GL_PIXEL_MAP_I_TO_R 0x0C72 +#define GL_PIXEL_MAP_I_TO_G 0x0C73 +#define GL_PIXEL_MAP_I_TO_B 0x0C74 +#define GL_PIXEL_MAP_I_TO_A 0x0C75 +#define GL_PIXEL_MAP_R_TO_R 0x0C76 +#define GL_PIXEL_MAP_G_TO_G 0x0C77 +#define GL_PIXEL_MAP_B_TO_B 0x0C78 +#define GL_PIXEL_MAP_A_TO_A 0x0C79 +#define GL_PIXEL_MAP_I_TO_I_SIZE 0x0CB0 +#define GL_PIXEL_MAP_S_TO_S_SIZE 0x0CB1 +#define GL_PIXEL_MAP_I_TO_R_SIZE 0x0CB2 +#define GL_PIXEL_MAP_I_TO_G_SIZE 0x0CB3 +#define GL_PIXEL_MAP_I_TO_B_SIZE 0x0CB4 +#define GL_PIXEL_MAP_I_TO_A_SIZE 0x0CB5 +#define GL_PIXEL_MAP_R_TO_R_SIZE 0x0CB6 +#define GL_PIXEL_MAP_G_TO_G_SIZE 0x0CB7 +#define GL_PIXEL_MAP_B_TO_B_SIZE 0x0CB8 +#define GL_PIXEL_MAP_A_TO_A_SIZE 0x0CB9 +#define GL_UNPACK_SWAP_BYTES 0x0CF0 +#define GL_UNPACK_LSB_FIRST 0x0CF1 +#define GL_UNPACK_ROW_LENGTH 0x0CF2 +#define GL_UNPACK_SKIP_ROWS 0x0CF3 +#define GL_UNPACK_SKIP_PIXELS 0x0CF4 +#define GL_UNPACK_ALIGNMENT 0x0CF5 +#define GL_PACK_SWAP_BYTES 0x0D00 +#define GL_PACK_LSB_FIRST 0x0D01 +#define GL_PACK_ROW_LENGTH 0x0D02 +#define GL_PACK_SKIP_ROWS 0x0D03 +#define GL_PACK_SKIP_PIXELS 0x0D04 +#define GL_PACK_ALIGNMENT 0x0D05 +#define GL_MAP_COLOR 0x0D10 +#define GL_MAP_STENCIL 0x0D11 +#define GL_INDEX_SHIFT 0x0D12 +#define GL_INDEX_OFFSET 0x0D13 +#define GL_RED_SCALE 0x0D14 +#define GL_RED_BIAS 0x0D15 +#define GL_ZOOM_X 0x0D16 +#define GL_ZOOM_Y 0x0D17 +#define GL_GREEN_SCALE 0x0D18 +#define GL_GREEN_BIAS 0x0D19 +#define GL_BLUE_SCALE 0x0D1A +#define GL_BLUE_BIAS 0x0D1B +#define GL_ALPHA_SCALE 0x0D1C +#define GL_ALPHA_BIAS 0x0D1D +#define GL_DEPTH_SCALE 0x0D1E +#define GL_DEPTH_BIAS 0x0D1F +#define GL_MAX_EVAL_ORDER 0x0D30 +#define GL_MAX_LIGHTS 0x0D31 +#define GL_MAX_CLIP_PLANES 0x0D32 +#define GL_MAX_TEXTURE_SIZE 0x0D33 +#define GL_MAX_PIXEL_MAP_TABLE 0x0D34 +#define GL_MAX_ATTRIB_STACK_DEPTH 0x0D35 +#define GL_MAX_MODELVIEW_STACK_DEPTH 0x0D36 +#define GL_MAX_NAME_STACK_DEPTH 0x0D37 +#define GL_MAX_PROJECTION_STACK_DEPTH 0x0D38 +#define GL_MAX_TEXTURE_STACK_DEPTH 0x0D39 +#define GL_MAX_VIEWPORT_DIMS 0x0D3A +#define GL_MAX_CLIENT_ATTRIB_STACK_DEPTH 0x0D3B +#define GL_SUBPIXEL_BITS 0x0D50 +#define GL_INDEX_BITS 0x0D51 +#define GL_RED_BITS 0x0D52 +#define GL_GREEN_BITS 0x0D53 +#define GL_BLUE_BITS 0x0D54 +#define GL_ALPHA_BITS 0x0D55 +#define GL_DEPTH_BITS 0x0D56 +#define GL_STENCIL_BITS 0x0D57 +#define GL_ACCUM_RED_BITS 0x0D58 +#define GL_ACCUM_GREEN_BITS 0x0D59 +#define GL_ACCUM_BLUE_BITS 0x0D5A +#define GL_ACCUM_ALPHA_BITS 0x0D5B +#define GL_NAME_STACK_DEPTH 0x0D70 +#define GL_AUTO_NORMAL 0x0D80 +#define GL_MAP1_COLOR_4 0x0D90 +#define GL_MAP1_INDEX 0x0D91 +#define GL_MAP1_NORMAL 0x0D92 +#define GL_MAP1_TEXTURE_COORD_1 0x0D93 +#define GL_MAP1_TEXTURE_COORD_2 0x0D94 +#define GL_MAP1_TEXTURE_COORD_3 0x0D95 +#define GL_MAP1_TEXTURE_COORD_4 0x0D96 +#define GL_MAP1_VERTEX_3 0x0D97 +#define GL_MAP1_VERTEX_4 0x0D98 +#define GL_MAP2_COLOR_4 0x0DB0 +#define GL_MAP2_INDEX 0x0DB1 +#define GL_MAP2_NORMAL 0x0DB2 +#define GL_MAP2_TEXTURE_COORD_1 0x0DB3 +#define GL_MAP2_TEXTURE_COORD_2 0x0DB4 +#define GL_MAP2_TEXTURE_COORD_3 0x0DB5 +#define GL_MAP2_TEXTURE_COORD_4 0x0DB6 +#define GL_MAP2_VERTEX_3 0x0DB7 +#define GL_MAP2_VERTEX_4 0x0DB8 +#define GL_MAP1_GRID_DOMAIN 0x0DD0 +#define GL_MAP1_GRID_SEGMENTS 0x0DD1 +#define GL_MAP2_GRID_DOMAIN 0x0DD2 +#define GL_MAP2_GRID_SEGMENTS 0x0DD3 +#define GL_TEXTURE_1D 0x0DE0 +#define GL_TEXTURE_2D 0x0DE1 +#define GL_FEEDBACK_BUFFER_POINTER 0x0DF0 +#define GL_FEEDBACK_BUFFER_SIZE 0x0DF1 +#define GL_FEEDBACK_BUFFER_TYPE 0x0DF2 +#define GL_SELECTION_BUFFER_POINTER 0x0DF3 +#define GL_SELECTION_BUFFER_SIZE 0x0DF4 +#define GL_TEXTURE_WIDTH 0x1000 +#define GL_TEXTURE_HEIGHT 0x1001 +#define GL_TEXTURE_INTERNAL_FORMAT 0x1003 +#define GL_TEXTURE_BORDER_COLOR 0x1004 +#define GL_TEXTURE_BORDER 0x1005 +#define GL_DONT_CARE 0x1100 +#define GL_FASTEST 0x1101 +#define GL_NICEST 0x1102 +#define GL_LIGHT0 0x4000 +#define GL_LIGHT1 0x4001 +#define GL_LIGHT2 0x4002 +#define GL_LIGHT3 0x4003 +#define GL_LIGHT4 0x4004 +#define GL_LIGHT5 0x4005 +#define GL_LIGHT6 0x4006 +#define GL_LIGHT7 0x4007 +#define GL_AMBIENT 0x1200 +#define GL_DIFFUSE 0x1201 +#define GL_SPECULAR 0x1202 +#define GL_POSITION 0x1203 +#define GL_SPOT_DIRECTION 0x1204 +#define GL_SPOT_EXPONENT 0x1205 +#define GL_SPOT_CUTOFF 0x1206 +#define GL_CONSTANT_ATTENUATION 0x1207 +#define GL_LINEAR_ATTENUATION 0x1208 +#define GL_QUADRATIC_ATTENUATION 0x1209 +#define GL_COMPILE 0x1300 +#define GL_COMPILE_AND_EXECUTE 0x1301 +#define GL_CLEAR 0x1500 +#define GL_AND 0x1501 +#define GL_AND_REVERSE 0x1502 +#define GL_COPY 0x1503 +#define GL_AND_INVERTED 0x1504 +#define GL_NOOP 0x1505 +#define GL_XOR 0x1506 +#define GL_OR 0x1507 +#define GL_NOR 0x1508 +#define GL_EQUIV 0x1509 +#define GL_INVERT 0x150A +#define GL_OR_REVERSE 0x150B +#define GL_COPY_INVERTED 0x150C +#define GL_OR_INVERTED 0x150D +#define GL_NAND 0x150E +#define GL_SET 0x150F +#define GL_EMISSION 0x1600 +#define GL_SHININESS 0x1601 +#define GL_AMBIENT_AND_DIFFUSE 0x1602 +#define GL_COLOR_INDEXES 0x1603 +#define GL_MODELVIEW 0x1700 +#define GL_PROJECTION 0x1701 +#define GL_TEXTURE 0x1702 +#define GL_COLOR 0x1800 +#define GL_DEPTH 0x1801 +#define GL_STENCIL 0x1802 +#define GL_COLOR_INDEX 0x1900 +#define GL_STENCIL_INDEX 0x1901 +#define GL_DEPTH_COMPONENT 0x1902 +#define GL_RED 0x1903 +#define GL_GREEN 0x1904 +#define GL_BLUE 0x1905 +#define GL_ALPHA 0x1906 +#define GL_RGB 0x1907 +#define GL_RGBA 0x1908 +#define GL_LUMINANCE 0x1909 +#define GL_LUMINANCE_ALPHA 0x190A +#define GL_BITMAP 0x1A00 +#define GL_POINT 0x1B00 +#define GL_LINE 0x1B01 +#define GL_FILL 0x1B02 +#define GL_RENDER 0x1C00 +#define GL_FEEDBACK 0x1C01 +#define GL_SELECT 0x1C02 +#define GL_FLAT 0x1D00 +#define GL_SMOOTH 0x1D01 +#define GL_KEEP 0x1E00 +#define GL_REPLACE 0x1E01 +#define GL_INCR 0x1E02 +#define GL_DECR 0x1E03 +#define GL_VENDOR 0x1F00 +#define GL_RENDERER 0x1F01 +#define GL_VERSION 0x1F02 +#define GL_EXTENSIONS 0x1F03 +#define GL_S 0x2000 +#define GL_T 0x2001 +#define GL_R 0x2002 +#define GL_Q 0x2003 +#define GL_MODULATE 0x2100 +#define GL_DECAL 0x2101 +#define GL_TEXTURE_ENV_MODE 0x2200 +#define GL_TEXTURE_ENV_COLOR 0x2201 +#define GL_TEXTURE_ENV 0x2300 +#define GL_EYE_LINEAR 0x2400 +#define GL_OBJECT_LINEAR 0x2401 +#define GL_SPHERE_MAP 0x2402 +#define GL_TEXTURE_GEN_MODE 0x2500 +#define GL_OBJECT_PLANE 0x2501 +#define GL_EYE_PLANE 0x2502 +#define GL_NEAREST 0x2600 +#define GL_LINEAR 0x2601 +#define GL_NEAREST_MIPMAP_NEAREST 0x2700 +#define GL_LINEAR_MIPMAP_NEAREST 0x2701 +#define GL_NEAREST_MIPMAP_LINEAR 0x2702 +#define GL_LINEAR_MIPMAP_LINEAR 0x2703 +#define GL_TEXTURE_MAG_FILTER 0x2800 +#define GL_TEXTURE_MIN_FILTER 0x2801 +#define GL_TEXTURE_WRAP_S 0x2802 +#define GL_TEXTURE_WRAP_T 0x2803 +#define GL_CLAMP 0x2900 +#define GL_REPEAT 0x2901 +#define GL_CLIP_PLANE0 0x3000 +#define GL_CLIP_PLANE1 0x3001 +#define GL_CLIP_PLANE2 0x3002 +#define GL_CLIP_PLANE3 0x3003 +#define GL_CLIP_PLANE4 0x3004 +#define GL_CLIP_PLANE5 0x3005 +#define GL_CURRENT_BIT 0x00000001 +#define GL_POINT_BIT 0x00000002 +#define GL_LINE_BIT 0x00000004 +#define GL_POLYGON_BIT 0x00000008 +#define GL_POLYGON_STIPPLE_BIT 0x00000010 +#define GL_PIXEL_MODE_BIT 0x00000020 +#define GL_LIGHTING_BIT 0x00000040 +#define GL_FOG_BIT 0x00000080 +#define GL_DEPTH_BUFFER_BIT 0x00000100 +#define GL_ACCUM_BUFFER_BIT 0x00000200 +#define GL_STENCIL_BUFFER_BIT 0x00000400 +#define GL_VIEWPORT_BIT 0x00000800 +#define GL_TRANSFORM_BIT 0x00001000 +#define GL_ENABLE_BIT 0x00002000 +#define GL_COLOR_BUFFER_BIT 0x00004000 +#define GL_HINT_BIT 0x00008000 +#define GL_EVAL_BIT 0x00010000 +#define GL_LIST_BIT 0x00020000 +#define GL_TEXTURE_BIT 0x00040000 +#define GL_SCISSOR_BIT 0x00080000 +#define GL_ALL_ATTRIB_BITS 0x000fffff +#define GL_CLIENT_PIXEL_STORE_BIT 0x00000001 +#define GL_CLIENT_VERTEX_ARRAY_BIT 0x00000002 +#define GL_CLIENT_ALL_ATTRIB_BITS 0xffffffff +#define GL_POLYGON_OFFSET_UNITS 0x2A00 +#define GL_POLYGON_OFFSET_POINT 0x2A01 +#define GL_POLYGON_OFFSET_LINE 0x2A02 +#define GL_POLYGON_OFFSET_FILL 0x8037 +#define GL_POLYGON_OFFSET_FACTOR 0x8038 +#define GL_ALPHA4 0x803B +#define GL_ALPHA8 0x803C +#define GL_ALPHA12 0x803D +#define GL_ALPHA16 0x803E +#define GL_LUMINANCE4 0x803F +#define GL_LUMINANCE8 0x8040 +#define GL_LUMINANCE12 0x8041 +#define GL_LUMINANCE16 0x8042 +#define GL_LUMINANCE4_ALPHA4 0x8043 +#define GL_LUMINANCE6_ALPHA2 0x8044 +#define GL_LUMINANCE8_ALPHA8 0x8045 +#define GL_LUMINANCE12_ALPHA4 0x8046 +#define GL_LUMINANCE12_ALPHA12 0x8047 +#define GL_LUMINANCE16_ALPHA16 0x8048 +#define GL_INTENSITY 0x8049 +#define GL_INTENSITY4 0x804A +#define GL_INTENSITY8 0x804B +#define GL_INTENSITY12 0x804C +#define GL_INTENSITY16 0x804D +#define GL_R3_G3_B2 0x2A10 +#define GL_RGB4 0x804F +#define GL_RGB5 0x8050 +#define GL_RGB8 0x8051 +#define GL_RGB10 0x8052 +#define GL_RGB12 0x8053 +#define GL_RGB16 0x8054 +#define GL_RGBA2 0x8055 +#define GL_RGBA4 0x8056 +#define GL_RGB5_A1 0x8057 +#define GL_RGBA8 0x8058 +#define GL_RGB10_A2 0x8059 +#define GL_RGBA12 0x805A +#define GL_RGBA16 0x805B +#define GL_TEXTURE_RED_SIZE 0x805C +#define GL_TEXTURE_GREEN_SIZE 0x805D +#define GL_TEXTURE_BLUE_SIZE 0x805E +#define GL_TEXTURE_ALPHA_SIZE 0x805F +#define GL_TEXTURE_LUMINANCE_SIZE 0x8060 +#define GL_TEXTURE_INTENSITY_SIZE 0x8061 +#define GL_PROXY_TEXTURE_1D 0x8063 +#define GL_PROXY_TEXTURE_2D 0x8064 +#define GL_TEXTURE_PRIORITY 0x8066 +#define GL_TEXTURE_RESIDENT 0x8067 +#define GL_TEXTURE_BINDING_1D 0x8068 +#define GL_TEXTURE_BINDING_2D 0x8069 +#define GL_VERTEX_ARRAY 0x8074 +#define GL_NORMAL_ARRAY 0x8075 +#define GL_COLOR_ARRAY 0x8076 +#define GL_INDEX_ARRAY 0x8077 +#define GL_TEXTURE_COORD_ARRAY 0x8078 +#define GL_EDGE_FLAG_ARRAY 0x8079 +#define GL_VERTEX_ARRAY_SIZE 0x807A +#define GL_VERTEX_ARRAY_TYPE 0x807B +#define GL_VERTEX_ARRAY_STRIDE 0x807C +#define GL_NORMAL_ARRAY_TYPE 0x807E +#define GL_NORMAL_ARRAY_STRIDE 0x807F +#define GL_COLOR_ARRAY_SIZE 0x8081 +#define GL_COLOR_ARRAY_TYPE 0x8082 +#define GL_COLOR_ARRAY_STRIDE 0x8083 +#define GL_INDEX_ARRAY_TYPE 0x8085 +#define GL_INDEX_ARRAY_STRIDE 0x8086 +#define GL_TEXTURE_COORD_ARRAY_SIZE 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE 0x808A +#define GL_EDGE_FLAG_ARRAY_STRIDE 0x808C +#define GL_VERTEX_ARRAY_POINTER 0x808E +#define GL_NORMAL_ARRAY_POINTER 0x808F +#define GL_COLOR_ARRAY_POINTER 0x8090 +#define GL_INDEX_ARRAY_POINTER 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER 0x8093 +#define GL_V2F 0x2A20 +#define GL_V3F 0x2A21 +#define GL_C4UB_V2F 0x2A22 +#define GL_C4UB_V3F 0x2A23 +#define GL_C3F_V3F 0x2A24 +#define GL_N3F_V3F 0x2A25 +#define GL_C4F_N3F_V3F 0x2A26 +#define GL_T2F_V3F 0x2A27 +#define GL_T4F_V4F 0x2A28 +#define GL_T2F_C4UB_V3F 0x2A29 +#define GL_T2F_C3F_V3F 0x2A2A +#define GL_T2F_N3F_V3F 0x2A2B +#define GL_T2F_C4F_N3F_V3F 0x2A2C +#define GL_T4F_C4F_N3F_V4F 0x2A2D + +#define glAccum GlobalOpenGL().m_glAccum +#define glAlphaFunc GlobalOpenGL().m_glAlphaFunc +#define glAreTexturesResident GlobalOpenGL().m_glAreTexturesResident +#define glArrayElement GlobalOpenGL().m_glArrayElement +#define glBegin GlobalOpenGL().m_glBegin +#define glBindTexture GlobalOpenGL().m_glBindTexture +#define glBitmap GlobalOpenGL().m_glBitmap +#define glBlendFunc GlobalOpenGL().m_glBlendFunc +#define glCallList GlobalOpenGL().m_glCallList +#define glCallLists GlobalOpenGL().m_glCallLists +#define glClear GlobalOpenGL().m_glClear +#define glClearAccum GlobalOpenGL().m_glClearAccum +#define glClearColor GlobalOpenGL().m_glClearColor +#define glClearDepth GlobalOpenGL().m_glClearDepth +#define glClearIndex GlobalOpenGL().m_glClearIndex +#define glClearStencil GlobalOpenGL().m_glClearStencil +#define glClipPlane GlobalOpenGL().m_glClipPlane +#define glColor3b GlobalOpenGL().m_glColor3b +#define glColor3bv GlobalOpenGL().m_glColor3bv +#define glColor3d GlobalOpenGL().m_glColor3d +#define glColor3dv GlobalOpenGL().m_glColor3dv +#define glColor3f GlobalOpenGL().m_glColor3f +#define glColor3fv GlobalOpenGL().m_glColor3fv +#define glColor3i GlobalOpenGL().m_glColor3i +#define glColor3iv GlobalOpenGL().m_glColor3iv +#define glColor3s GlobalOpenGL().m_glColor3s +#define glColor3sv GlobalOpenGL().m_glColor3sv +#define glColor3ub GlobalOpenGL().m_glColor3ub +#define glColor3ubv GlobalOpenGL().m_glColor3ubv +#define glColor3ui GlobalOpenGL().m_glColor3ui +#define glColor3uiv GlobalOpenGL().m_glColor3uiv +#define glColor3us GlobalOpenGL().m_glColor3us +#define glColor3usv GlobalOpenGL().m_glColor3usv +#define glColor4b GlobalOpenGL().m_glColor4b +#define glColor4bv GlobalOpenGL().m_glColor4bv +#define glColor4d GlobalOpenGL().m_glColor4d +#define glColor4dv GlobalOpenGL().m_glColor4dv +#define glColor4f GlobalOpenGL().m_glColor4f +#define glColor4fv GlobalOpenGL().m_glColor4fv +#define glColor4i GlobalOpenGL().m_glColor4i +#define glColor4iv GlobalOpenGL().m_glColor4iv +#define glColor4s GlobalOpenGL().m_glColor4s +#define glColor4sv GlobalOpenGL().m_glColor4sv +#define glColor4ub GlobalOpenGL().m_glColor4ub +#define glColor4ubv GlobalOpenGL().m_glColor4ubv +#define glColor4ui GlobalOpenGL().m_glColor4ui +#define glColor4uiv GlobalOpenGL().m_glColor4uiv +#define glColor4us GlobalOpenGL().m_glColor4us +#define glColor4usv GlobalOpenGL().m_glColor4usv +#define glColorMask GlobalOpenGL().m_glColorMask +#define glColorMaterial GlobalOpenGL().m_glColorMaterial +#define glColorPointer GlobalOpenGL().m_glColorPointer +#define glCopyPixels GlobalOpenGL().m_glCopyPixels +#define glCopyTexImage1D GlobalOpenGL().m_glCopyTexImage1D +#define glCopyTexImage2D GlobalOpenGL().m_glCopyTexImage2D +#define glCopyTexSubImage1D GlobalOpenGL().m_glCopyTexSubImage1D +#define glCopyTexSubImage2D GlobalOpenGL().m_glCopyTexSubImage2D +#define glCullFace GlobalOpenGL().m_glCullFace +#define glDeleteLists GlobalOpenGL().m_glDeleteLists +#define glDeleteTextures GlobalOpenGL().m_glDeleteTextures +#define glDepthFunc GlobalOpenGL().m_glDepthFunc +#define glDepthMask GlobalOpenGL().m_glDepthMask +#define glDepthRange GlobalOpenGL().m_glDepthRange +#define glDisable GlobalOpenGL().m_glDisable +#define glDisableClientState GlobalOpenGL().m_glDisableClientState +#define glDrawArrays GlobalOpenGL().m_glDrawArrays +#define glDrawBuffer GlobalOpenGL().m_glDrawBuffer +#define glDrawElements GlobalOpenGL().m_glDrawElements +#define glDrawPixels GlobalOpenGL().m_glDrawPixels +#define glEdgeFlag GlobalOpenGL().m_glEdgeFlag +#define glEdgeFlagPointer GlobalOpenGL().m_glEdgeFlagPointer +#define glEdgeFlagv GlobalOpenGL().m_glEdgeFlagv +#define glEnable GlobalOpenGL().m_glEnable +#define glEnableClientState GlobalOpenGL().m_glEnableClientState +#define glEnd GlobalOpenGL().m_glEnd +#define glEndList GlobalOpenGL().m_glEndList +#define glEvalCoord1d GlobalOpenGL().m_glEvalCoord1d +#define glEvalCoord1dv GlobalOpenGL().m_glEvalCoord1dv +#define glEvalCoord1f GlobalOpenGL().m_glEvalCoord1f +#define glEvalCoord1fv GlobalOpenGL().m_glEvalCoord1fv +#define glEvalCoord2d GlobalOpenGL().m_glEvalCoord2d +#define glEvalCoord2dv GlobalOpenGL().m_glEvalCoord2dv +#define glEvalCoord2f GlobalOpenGL().m_glEvalCoord2f +#define glEvalCoord2fv GlobalOpenGL().m_glEvalCoord2fv +#define glEvalMesh1 GlobalOpenGL().m_glEvalMesh1 +#define glEvalMesh2 GlobalOpenGL().m_glEvalMesh2 +#define glEvalPoint1 GlobalOpenGL().m_glEvalPoint1 +#define glEvalPoint2 GlobalOpenGL().m_glEvalPoint2 +#define glFeedbackBuffer GlobalOpenGL().m_glFeedbackBuffer +#define glFinish GlobalOpenGL().m_glFinish +#define glFlush GlobalOpenGL().m_glFlush +#define glFogf GlobalOpenGL().m_glFogf +#define glFogfv GlobalOpenGL().m_glFogfv +#define glFogi GlobalOpenGL().m_glFogi +#define glFogiv GlobalOpenGL().m_glFogiv +#define glFrontFace GlobalOpenGL().m_glFrontFace +#define glFrustum GlobalOpenGL().m_glFrustum +#define glGenLists GlobalOpenGL().m_glGenLists +#define glGenTextures GlobalOpenGL().m_glGenTextures +#define glGetBooleanv GlobalOpenGL().m_glGetBooleanv +#define glGetClipPlane GlobalOpenGL().m_glGetClipPlane +#define glGetDoublev GlobalOpenGL().m_glGetDoublev +#define glGetError GlobalOpenGL().m_glGetError +#define glGetFloatv GlobalOpenGL().m_glGetFloatv +#define glGetIntegerv GlobalOpenGL().m_glGetIntegerv +#define glGetLightfv GlobalOpenGL().m_glGetLightfv +#define glGetLightiv GlobalOpenGL().m_glGetLightiv +#define glGetMapdv GlobalOpenGL().m_glGetMapdv +#define glGetMapfv GlobalOpenGL().m_glGetMapfv +#define glGetMapiv GlobalOpenGL().m_glGetMapiv +#define glGetMaterialfv GlobalOpenGL().m_glGetMaterialfv +#define glGetMaterialiv GlobalOpenGL().m_glGetMaterialiv +#define glGetPixelMapfv GlobalOpenGL().m_glGetPixelMapfv +#define glGetPixelMapuiv GlobalOpenGL().m_glGetPixelMapuiv +#define glGetPixelMapusv GlobalOpenGL().m_glGetPixelMapusv +#define glGetPointerv GlobalOpenGL().m_glGetPointerv +#define glGetPolygonStipple GlobalOpenGL().m_glGetPolygonStipple +#define glGetString GlobalOpenGL().m_glGetString +#define glGetTexEnvfv GlobalOpenGL().m_glGetTexEnvfv +#define glGetTexEnviv GlobalOpenGL().m_glGetTexEnviv +#define glGetTexGendv GlobalOpenGL().m_glGetTexGendv +#define glGetTexGenfv GlobalOpenGL().m_glGetTexGenfv +#define glGetTexGeniv GlobalOpenGL().m_glGetTexGeniv +#define glGetTexImage GlobalOpenGL().m_glGetTexImage +#define glGetTexLevelParameterfv GlobalOpenGL().m_glGetTexLevelParameter +#define glGetTexLevelParameteriv GlobalOpenGL().m_glGetTexLevelParameteriv +#define glGetTexParameterfv GlobalOpenGL().m_glGetTexParameterfv +#define glGetTexParameteriv GlobalOpenGL().m_glGetTexParameteriv +#define glHint GlobalOpenGL().m_glHint +#define glIndexMask GlobalOpenGL().m_glIndexMask +#define glIndexPointer GlobalOpenGL().m_glIndexPointer +#define glIndexd GlobalOpenGL().m_glIndexd +#define glIndexdv GlobalOpenGL().m_glIndexdv +#define glIndexf GlobalOpenGL().m_glIndexf +#define glIndexfv GlobalOpenGL().m_glIndexfv +#define glIndexi GlobalOpenGL().m_glIndexi +#define glIndexiv GlobalOpenGL().m_glIndexiv +#define glIndexs GlobalOpenGL().m_glIndexs +#define glIndexsv GlobalOpenGL().m_glIndexsv +#define glIndexub GlobalOpenGL().m_glIndexub +#define glIndexubv GlobalOpenGL().m_glIndexubv +#define glInitNames GlobalOpenGL().m_glInitNames +#define glInterleavedArrays GlobalOpenGL().m_glInterleavedArrays +#define glIsEnabled GlobalOpenGL().m_glIsEnabled +#define glIsList GlobalOpenGL().m_glIsList +#define glIsTexture GlobalOpenGL().m_glIsTexture +#define glLightModelf GlobalOpenGL().m_glLightModelf +#define glLightModelfv GlobalOpenGL().m_glLightModelfv +#define glLightModeli GlobalOpenGL().m_glLightModeli +#define glLightModeliv GlobalOpenGL().m_glLightModeliv +#define glLightf GlobalOpenGL().m_glLightf +#define glLightfv GlobalOpenGL().m_glLightfv +#define glLighti GlobalOpenGL().m_glLighti +#define glLightiv GlobalOpenGL().m_glLightiv +#define glLineStipple GlobalOpenGL().m_glLineStipple +#define glLineWidth GlobalOpenGL().m_glLineWidth +#define glListBase GlobalOpenGL().m_glListBase +#define glLoadIdentity GlobalOpenGL().m_glLoadIdentity +#define glLoadMatrixd GlobalOpenGL().m_glLoadMatrixd +#define glLoadMatrixf GlobalOpenGL().m_glLoadMatrixf +#define glLoadName GlobalOpenGL().m_glLoadName +#define glLogicOp GlobalOpenGL().m_glLogicOp +#define glMap1d GlobalOpenGL().m_glMap1d +#define glMap1f GlobalOpenGL().m_glMap1f +#define glMap2d GlobalOpenGL().m_glMap2d +#define glMap2f GlobalOpenGL().m_glMap2f +#define glMapGrid1d GlobalOpenGL().m_glMapGrid1d +#define glMapGrid1f GlobalOpenGL().m_glMapGrid1f +#define glMapGrid2d GlobalOpenGL().m_glMapGrid2d +#define glMapGrid2f GlobalOpenGL().m_glMapGrid2f +#define glMaterialf GlobalOpenGL().m_glMaterialf +#define glMaterialfv GlobalOpenGL().m_glMaterialfv +#define glMateriali GlobalOpenGL().m_glMateriali +#define glMaterialiv GlobalOpenGL().m_glMaterialiv +#define glMatrixMode GlobalOpenGL().m_glMatrixMode +#define glMultMatrixd GlobalOpenGL().m_glMultMatrixd +#define glMultMatrixf GlobalOpenGL().m_glMultMatrixf +#define glNewList GlobalOpenGL().m_glNewList +#define glNormal3b GlobalOpenGL().m_glNormal3b +#define glNormal3bv GlobalOpenGL().m_glNormal3bv +#define glNormal3d GlobalOpenGL().m_glNormal3d +#define glNormal3dv GlobalOpenGL().m_glNormal3dv +#define glNormal3f GlobalOpenGL().m_glNormal3f +#define glNormal3fv GlobalOpenGL().m_glNormal3fv +#define glNormal3i GlobalOpenGL().m_glNormal3i +#define glNormal3iv GlobalOpenGL().m_glNormal3iv +#define glNormal3s GlobalOpenGL().m_glNormal3s +#define glNormal3sv GlobalOpenGL().m_glNormal3sv +#define glNormalPointer GlobalOpenGL().m_glNormalPointer +#define glOrtho GlobalOpenGL().m_glOrtho +#define glPassThrough GlobalOpenGL().m_glPassThrough +#define glPixelMapfv GlobalOpenGL().m_glPixelMapfv +#define glPixelMapuiv GlobalOpenGL().m_glPixelMapuiv +#define glPixelMapusv GlobalOpenGL().m_glPixelMapusv +#define glPixelStoref GlobalOpenGL().m_glPixelStoref +#define glPixelStorei GlobalOpenGL().m_glPixelStorei +#define glPixelTransferf GlobalOpenGL().m_glPixelTransferf +#define glPixelTransferi GlobalOpenGL().m_glPixelTransferi +#define glPixelZoom GlobalOpenGL().m_glPixelZoom +#define glPointSize GlobalOpenGL().m_glPointSize +#define glPolygonMode GlobalOpenGL().m_glPolygonMode +#define glPolygonOffset GlobalOpenGL().m_glPolygonOffset +#define glPolygonStipple GlobalOpenGL().m_glPolygonStipple +#define glPopAttrib GlobalOpenGL().m_glPopAttrib +#define glPopClientAttrib GlobalOpenGL().m_glPopClientAttrib +#define glPopMatrix GlobalOpenGL().m_glPopMatrix +#define glPopName GlobalOpenGL().m_glPopName +#define glPrioritizeTextures GlobalOpenGL().m_glPrioritizeTextures +#define glPushAttrib GlobalOpenGL().m_glPushAttrib +#define glPushClientAttrib GlobalOpenGL().m_glPushClientAttrib +#define glPushMatrix GlobalOpenGL().m_glPushMatrix +#define glPushName GlobalOpenGL().m_glPushName +#define glRasterPos2d GlobalOpenGL().m_glRasterPos2d +#define glRasterPos2dv GlobalOpenGL().m_glRasterPos2dv +#define glRasterPos2f GlobalOpenGL().m_glRasterPos2f +#define glRasterPos2fv GlobalOpenGL().m_glRasterPos2fv +#define glRasterPos2i GlobalOpenGL().m_glRasterPos2i +#define glRasterPos2iv GlobalOpenGL().m_glRasterPos2iv +#define glRasterPos2s GlobalOpenGL().m_glRasterPos2s +#define glRasterPos2sv GlobalOpenGL().m_glRasterPos2sv +#define glRasterPos3d GlobalOpenGL().m_glRasterPos3d +#define glRasterPos3dv GlobalOpenGL().m_glRasterPos3dv +#define glRasterPos3f GlobalOpenGL().m_glRasterPos3f +#define glRasterPos3fv GlobalOpenGL().m_glRasterPos3fv +#define glRasterPos3i GlobalOpenGL().m_glRasterPos3i +#define glRasterPos3iv GlobalOpenGL().m_glRasterPos3iv +#define glRasterPos3s GlobalOpenGL().m_glRasterPos3s +#define glRasterPos3sv GlobalOpenGL().m_glRasterPos3sv +#define glRasterPos4d GlobalOpenGL().m_glRasterPos4d +#define glRasterPos4dv GlobalOpenGL().m_glRasterPos4dv +#define glRasterPos4f GlobalOpenGL().m_glRasterPos4f +#define glRasterPos4fv GlobalOpenGL().m_glRasterPos4fv +#define glRasterPos4i GlobalOpenGL().m_glRasterPos4i +#define glRasterPos4iv GlobalOpenGL().m_glRasterPos4iv +#define glRasterPos4s GlobalOpenGL().m_glRasterPos4s +#define glRasterPos4sv GlobalOpenGL().m_glRasterPos4sv +#define glReadBuffer GlobalOpenGL().m_glReadBuffer +#define glReadPixels GlobalOpenGL().m_glReadPixels +#define glRectd GlobalOpenGL().m_glRectd +#define glRectdv GlobalOpenGL().m_glRectdv +#define glRectf GlobalOpenGL().m_glRectf +#define glRectfv GlobalOpenGL().m_glRectfv +#define glRecti GlobalOpenGL().m_glRecti +#define glRectiv GlobalOpenGL().m_glRectiv +#define glRects GlobalOpenGL().m_glRects +#define glRectsv GlobalOpenGL().m_glRectsv +#define glRenderMode GlobalOpenGL().m_glRenderMode +#define glRotated GlobalOpenGL().m_glRotated +#define glRotatef GlobalOpenGL().m_glRotatef +#define glScaled GlobalOpenGL().m_glScaled +#define glScalef GlobalOpenGL().m_glScalef +#define glScissor GlobalOpenGL().m_glScissor +#define glSelectBuffer GlobalOpenGL().m_glSelectBuffer +#define glShadeModel GlobalOpenGL().m_glShadeModel +#define glStencilFunc GlobalOpenGL().m_glStencilFunc +#define glStencilMask GlobalOpenGL().m_glStencilMask +#define glStencilOp GlobalOpenGL().m_glStencilOp +#define glTexCoord1d GlobalOpenGL().m_glTexCoord1d +#define glTexCoord1dv GlobalOpenGL().m_glTexCoord1dv +#define glTexCoord1f GlobalOpenGL().m_glTexCoord1f +#define glTexCoord1fv GlobalOpenGL().m_glTexCoord1fv +#define glTexCoord1i GlobalOpenGL().m_glTexCoord1i +#define glTexCoord1iv GlobalOpenGL().m_glTexCoord1iv +#define glTexCoord1s GlobalOpenGL().m_glTexCoord1s +#define glTexCoord1sv GlobalOpenGL().m_glTexCoord1sv +#define glTexCoord2d GlobalOpenGL().m_glTexCoord2d +#define glTexCoord2dv GlobalOpenGL().m_glTexCoord2dv +#define glTexCoord2f GlobalOpenGL().m_glTexCoord2f +#define glTexCoord2fv GlobalOpenGL().m_glTexCoord2fv +#define glTexCoord2i GlobalOpenGL().m_glTexCoord2i +#define glTexCoord2iv GlobalOpenGL().m_glTexCoord2iv +#define glTexCoord2s GlobalOpenGL().m_glTexCoord2s +#define glTexCoord2sv GlobalOpenGL().m_glTexCoord2sv +#define glTexCoord3d GlobalOpenGL().m_glTexCoord3d +#define glTexCoord3dv GlobalOpenGL().m_glTexCoord3dv +#define glTexCoord3f GlobalOpenGL().m_glTexCoord3f +#define glTexCoord3fv GlobalOpenGL().m_glTexCoord3fv +#define glTexCoord3i GlobalOpenGL().m_glTexCoord3i +#define glTexCoord3iv GlobalOpenGL().m_glTexCoord3iv +#define glTexCoord3s GlobalOpenGL().m_glTexCoord3s +#define glTexCoord3sv GlobalOpenGL().m_glTexCoord3sv +#define glTexCoord4d GlobalOpenGL().m_glTexCoord4d +#define glTexCoord4dv GlobalOpenGL().m_glTexCoord4dv +#define glTexCoord4f GlobalOpenGL().m_glTexCoord4f +#define glTexCoord4fv GlobalOpenGL().m_glTexCoord4fv +#define glTexCoord4i GlobalOpenGL().m_glTexCoord4i +#define glTexCoord4iv GlobalOpenGL().m_glTexCoord4iv +#define glTexCoord4s GlobalOpenGL().m_glTexCoord4s +#define glTexCoord4sv GlobalOpenGL().m_glTexCoord4sv +#define glTexCoordPointer GlobalOpenGL().m_glTexCoordPointer +#define glTexEnvf GlobalOpenGL().m_glTexEnvf +#define glTexEnvfv GlobalOpenGL().m_glTexEnvfv +#define glTexEnvi GlobalOpenGL().m_glTexEnvi +#define glTexEnviv GlobalOpenGL().m_glTexEnviv +#define glTexGend GlobalOpenGL().m_glTexGend +#define glTexGendv GlobalOpenGL().m_glTexGendv +#define glTexGenf GlobalOpenGL().m_glTexGenf +#define glTexGenfv GlobalOpenGL().m_glTexGenfv +#define glTexGeni GlobalOpenGL().m_glTexGeni +#define glTexGeniv GlobalOpenGL().m_glTexGeniv +#define glTexImage1D GlobalOpenGL().m_glTexImage1D +#define glTexImage2D GlobalOpenGL().m_glTexImage2D +#define glTexParameterf GlobalOpenGL().m_glTexParameterf +#define glTexParameterfv GlobalOpenGL().m_glTexParameterfv +#define glTexParameteri GlobalOpenGL().m_glTexParameteri +#define glTexParameteriv GlobalOpenGL().m_glTexParameteriv +#define glTexSubImage1D GlobalOpenGL().m_glTexSubImage1D +#define glTexSubImage2D GlobalOpenGL().m_glTexSubImage2D +#define glTranslated GlobalOpenGL().m_glTranslated +#define glTranslatef GlobalOpenGL().m_glTranslatef +#define glVertex2d GlobalOpenGL().m_glVertex2d +#define glVertex2dv GlobalOpenGL().m_glVertex2dv +#define glVertex2f GlobalOpenGL().m_glVertex2f +#define glVertex2fv GlobalOpenGL().m_glVertex2fv +#define glVertex2i GlobalOpenGL().m_glVertex2i +#define glVertex2iv GlobalOpenGL().m_glVertex2iv +#define glVertex2s GlobalOpenGL().m_glVertex2s +#define glVertex2sv GlobalOpenGL().m_glVertex2sv +#define glVertex3d GlobalOpenGL().m_glVertex3d +#define glVertex3dv GlobalOpenGL().m_glVertex3dv +#define glVertex3f GlobalOpenGL().m_glVertex3f +#define glVertex3fv GlobalOpenGL().m_glVertex3fv +#define glVertex3i GlobalOpenGL().m_glVertex3i +#define glVertex3iv GlobalOpenGL().m_glVertex3iv +#define glVertex3s GlobalOpenGL().m_glVertex3s +#define glVertex3sv GlobalOpenGL().m_glVertex3sv +#define glVertex4d GlobalOpenGL().m_glVertex4d +#define glVertex4dv GlobalOpenGL().m_glVertex4dv +#define glVertex4f GlobalOpenGL().m_glVertex4f +#define glVertex4fv GlobalOpenGL().m_glVertex4fv +#define glVertex4i GlobalOpenGL().m_glVertex4i +#define glVertex4iv GlobalOpenGL().m_glVertex4iv +#define glVertex4s GlobalOpenGL().m_glVertex4s +#define glVertex4sv GlobalOpenGL().m_glVertex4sv +#define glVertexPointer GlobalOpenGL().m_glVertexPointer +#define glViewport GlobalOpenGL().m_glViewport + +#endif + + +#if !defined(GL_EXT_vertex_array) +#define GL_EXT_vertex_array 1 + +#define GL_VERTEX_ARRAY_EXT 0x8074 +#define GL_NORMAL_ARRAY_EXT 0x8075 +#define GL_COLOR_ARRAY_EXT 0x8076 +#define GL_INDEX_ARRAY_EXT 0x8077 +#define GL_TEXTURE_COORD_ARRAY_EXT 0x8078 +#define GL_EDGE_FLAG_ARRAY_EXT 0x8079 +#define GL_VERTEX_ARRAY_SIZE_EXT 0x807A +#define GL_VERTEX_ARRAY_TYPE_EXT 0x807B +#define GL_VERTEX_ARRAY_STRIDE_EXT 0x807C +#define GL_VERTEX_ARRAY_COUNT_EXT 0x807D +#define GL_NORMAL_ARRAY_TYPE_EXT 0x807E +#define GL_NORMAL_ARRAY_STRIDE_EXT 0x807F +#define GL_NORMAL_ARRAY_COUNT_EXT 0x8080 +#define GL_COLOR_ARRAY_SIZE_EXT 0x8081 +#define GL_COLOR_ARRAY_TYPE_EXT 0x8082 +#define GL_COLOR_ARRAY_STRIDE_EXT 0x8083 +#define GL_COLOR_ARRAY_COUNT_EXT 0x8084 +#define GL_INDEX_ARRAY_TYPE_EXT 0x8085 +#define GL_INDEX_ARRAY_STRIDE_EXT 0x8086 +#define GL_INDEX_ARRAY_COUNT_EXT 0x8087 +#define GL_TEXTURE_COORD_ARRAY_SIZE_EXT 0x8088 +#define GL_TEXTURE_COORD_ARRAY_TYPE_EXT 0x8089 +#define GL_TEXTURE_COORD_ARRAY_STRIDE_EXT 0x808A +#define GL_TEXTURE_COORD_ARRAY_COUNT_EXT 0x808B +#define GL_EDGE_FLAG_ARRAY_STRIDE_EXT 0x808C +#define GL_EDGE_FLAG_ARRAY_COUNT_EXT 0x808D +#define GL_VERTEX_ARRAY_POINTER_EXT 0x808E +#define GL_NORMAL_ARRAY_POINTER_EXT 0x808F +#define GL_COLOR_ARRAY_POINTER_EXT 0x8090 +#define GL_INDEX_ARRAY_POINTER_EXT 0x8091 +#define GL_TEXTURE_COORD_ARRAY_POINTER_EXT 0x8092 +#define GL_EDGE_FLAG_ARRAY_POINTER_EXT 0x8093 +#define GL_DOUBLE_EXT GL_DOUBLE + +#endif + + +#if !defined(GL_EXT_bgra) +#define GL_EXT_bgra 1 + +#define GL_BGR_EXT 0x80E0 +#define GL_BGRA_EXT 0x80E1 + +#endif + + +#if !defined(GL_EXT_paletted_texture) +#define GL_EXT_paletted_texture 1 + +#define GL_COLOR_TABLE_FORMAT_EXT 0x80D8 +#define GL_COLOR_TABLE_WIDTH_EXT 0x80D9 +#define GL_COLOR_TABLE_RED_SIZE_EXT 0x80DA +#define GL_COLOR_TABLE_GREEN_SIZE_EXT 0x80DB +#define GL_COLOR_TABLE_BLUE_SIZE_EXT 0x80DC +#define GL_COLOR_TABLE_ALPHA_SIZE_EXT 0x80DD +#define GL_COLOR_TABLE_LUMINANCE_SIZE_EXT 0x80DE +#define GL_COLOR_TABLE_INTENSITY_SIZE_EXT 0x80DF + +#define GL_COLOR_INDEX1_EXT 0x80E2 +#define GL_COLOR_INDEX2_EXT 0x80E3 +#define GL_COLOR_INDEX4_EXT 0x80E4 +#define GL_COLOR_INDEX8_EXT 0x80E5 +#define GL_COLOR_INDEX12_EXT 0x80E6 +#define GL_COLOR_INDEX16_EXT 0x80E7 + +#define GL_LOGIC_OP GL_INDEX_LOGIC_OP +#define GL_TEXTURE_COMPONENTS GL_TEXTURE_INTERNAL_FORMAT + +#endif + +#if !defined(GL_ARB_multitexture) +#define GL_ARB_multitexture 1 + +#define GL_TEXTURE0_ARB 0x84C0 +#define GL_TEXTURE1_ARB 0x84C1 +#define GL_TEXTURE2_ARB 0x84C2 +#define GL_TEXTURE3_ARB 0x84C3 +#define GL_TEXTURE4_ARB 0x84C4 +#define GL_TEXTURE5_ARB 0x84C5 +#define GL_TEXTURE6_ARB 0x84C6 +#define GL_TEXTURE7_ARB 0x84C7 +#define GL_TEXTURE8_ARB 0x84C8 +#define GL_TEXTURE9_ARB 0x84C9 +#define GL_TEXTURE10_ARB 0x84CA +#define GL_TEXTURE11_ARB 0x84CB +#define GL_TEXTURE12_ARB 0x84CC +#define GL_TEXTURE13_ARB 0x84CD +#define GL_TEXTURE14_ARB 0x84CE +#define GL_TEXTURE15_ARB 0x84CF +#define GL_TEXTURE16_ARB 0x84D0 +#define GL_TEXTURE17_ARB 0x84D1 +#define GL_TEXTURE18_ARB 0x84D2 +#define GL_TEXTURE19_ARB 0x84D3 +#define GL_TEXTURE20_ARB 0x84D4 +#define GL_TEXTURE21_ARB 0x84D5 +#define GL_TEXTURE22_ARB 0x84D6 +#define GL_TEXTURE23_ARB 0x84D7 +#define GL_TEXTURE24_ARB 0x84D8 +#define GL_TEXTURE25_ARB 0x84D9 +#define GL_TEXTURE26_ARB 0x84DA +#define GL_TEXTURE27_ARB 0x84DB +#define GL_TEXTURE28_ARB 0x84DC +#define GL_TEXTURE29_ARB 0x84DD +#define GL_TEXTURE30_ARB 0x84DE +#define GL_TEXTURE31_ARB 0x84DF +#define GL_ACTIVE_TEXTURE_ARB 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE_ARB 0x84E1 +#define GL_MAX_TEXTURE_UNITS_ARB 0x84E2 + +#define glActiveTextureARB GlobalOpenGL().m_glActiveTextureARB +#define glClientActiveTextureARB GlobalOpenGL().m_glClientActiveTextureARB +#define glMultiTexCoord1dARB GlobalOpenGL().m_glMultiTexCoord1dARB +#define glMultiTexCoord1dvARB GlobalOpenGL().m_glMultiTexCoord1dvARB +#define glMultiTexCoord1fARB GlobalOpenGL().m_glMultiTexCoord1fARB +#define glMultiTexCoord1fvARB GlobalOpenGL().m_glMultiTexCoord1fvARB +#define glMultiTexCoord1iARB GlobalOpenGL().m_glMultiTexCoord1iARB +#define glMultiTexCoord1ivARB GlobalOpenGL().m_glMultiTexCoord1ivARB +#define glMultiTexCoord1sARB GlobalOpenGL().m_glMultiTexCoord1sARB +#define glMultiTexCoord1svARB GlobalOpenGL().m_glMultiTexCoord1svARB +#define glMultiTexCoord2dARB GlobalOpenGL().m_glMultiTexCoord2dARB +#define glMultiTexCoord2dvARB GlobalOpenGL().m_glMultiTexCoord2dvARB +#define glMultiTexCoord2fARB GlobalOpenGL().m_glMultiTexCoord2fARB +#define glMultiTexCoord2fvARB GlobalOpenGL().m_glMultiTexCoord2fvARB +#define glMultiTexCoord2iARB GlobalOpenGL().m_glMultiTexCoord2iARB +#define glMultiTexCoord2ivARB GlobalOpenGL().m_glMultiTexCoord2ivARB +#define glMultiTexCoord2sARB GlobalOpenGL().m_glMultiTexCoord2sARB +#define glMultiTexCoord2svARB GlobalOpenGL().m_glMultiTexCoord2svARB +#define glMultiTexCoord3dARB GlobalOpenGL().m_glMultiTexCoord3dARB +#define glMultiTexCoord3dvARB GlobalOpenGL().m_glMultiTexCoord3dvARB +#define glMultiTexCoord3fARB GlobalOpenGL().m_glMultiTexCoord3fARB +#define glMultiTexCoord3fvARB GlobalOpenGL().m_glMultiTexCoord3fvARB +#define glMultiTexCoord3iARB GlobalOpenGL().m_glMultiTexCoord3iARB +#define glMultiTexCoord3ivARB GlobalOpenGL().m_glMultiTexCoord3ivARB +#define glMultiTexCoord3sARB GlobalOpenGL().m_glMultiTexCoord3sARB +#define glMultiTexCoord3svARB GlobalOpenGL().m_glMultiTexCoord3svARB +#define glMultiTexCoord4dARB GlobalOpenGL().m_glMultiTexCoord4dARB +#define glMultiTexCoord4dvARB GlobalOpenGL().m_glMultiTexCoord4dvARB +#define glMultiTexCoord4fARB GlobalOpenGL().m_glMultiTexCoord4fARB +#define glMultiTexCoord4fvARB GlobalOpenGL().m_glMultiTexCoord4fvARB +#define glMultiTexCoord4iARB GlobalOpenGL().m_glMultiTexCoord4iARB +#define glMultiTexCoord4ivARB GlobalOpenGL().m_glMultiTexCoord4ivARB +#define glMultiTexCoord4sARB GlobalOpenGL().m_glMultiTexCoord4sARB +#define glMultiTexCoord4svARB GlobalOpenGL().m_glMultiTexCoord4svARB + +#endif + + +// EXT_texture_compression_s3tc +#if !defined(GL_EXT_texture_compression_s3tc) +#define GL_EXT_texture_compression_s3tc 1 + +#define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 +#define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 +#define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 +#define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 + +#endif + + +// ARB_texture_compression +#if !defined(GL_ARB_texture_compression) +#define GL_ARB_texture_compression 1 + +#define GL_COMPRESSED_ALPHA_ARB 0x84E9 +#define GL_COMPRESSED_LUMINANCE_ARB 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA_ARB 0x84EB +#define GL_COMPRESSED_INTENSITY_ARB 0x84EC +#define GL_COMPRESSED_RGB_ARB 0x84ED +#define GL_COMPRESSED_RGBA_ARB 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT_ARB 0x84EF +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB 0x86A0 +#define GL_TEXTURE_COMPRESSED_ARB 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS_ARB 0x86A3 + +#define glCompressedTexImage3DARB GlobalOpenGL().m_glCompressedTexImage3DARB +#define glCompressedTexImage2DARB GlobalOpenGL().m_glCompressedTexImage2DARB +#define glCompressedTexImage1DARB GlobalOpenGL().m_glCompressedTexImage1DARB +#define glCompressedTexSubImage3DARB GlobalOpenGL().m_glCompressedTexSubImage3DARB +#define glCompressedTexSubImage2DARB GlobalOpenGL().m_glCompressedTexSubImage2DARB +#define glCompressedTexSubImage1DARB GlobalOpenGL().m_glCompressedTexSubImage1DARB +#define glGetCompressedTexImageARB GlobalOpenGL().m_glGetCompressedTexImageARB + +#endif + + +// GL 1.2 + +#if !defined(GL_VERSION_1_2) + +#define GL_SMOOTH_POINT_SIZE_RANGE 0x0B12 +#define GL_SMOOTH_POINT_SIZE_GRANULARITY 0x0B13 +#define GL_SMOOTH_LINE_WIDTH_RANGE 0x0B22 +#define GL_SMOOTH_LINE_WIDTH_GRANULARITY 0x0B23 +#define GL_UNSIGNED_BYTE_3_3_2 0x8032 +#define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 +#define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 +#define GL_UNSIGNED_INT_8_8_8_8 0x8035 +#define GL_UNSIGNED_INT_10_10_10_2 0x8036 +#define GL_RESCALE_NORMAL 0x803A +#define GL_TEXTURE_BINDING_3D 0x806A +#define GL_PACK_SKIP_IMAGES 0x806B +#define GL_PACK_IMAGE_HEIGHT 0x806C +#define GL_UNPACK_SKIP_IMAGES 0x806D +#define GL_UNPACK_IMAGE_HEIGHT 0x806E +#define GL_TEXTURE_3D 0x806F +#define GL_PROXY_TEXTURE_3D 0x8070 +#define GL_TEXTURE_DEPTH 0x8071 +#define GL_TEXTURE_WRAP_R 0x8072 +#define GL_MAX_3D_TEXTURE_SIZE 0x8073 +#define GL_BGR 0x80E0 +#define GL_BGRA 0x80E1 +#define GL_MAX_ELEMENTS_VERTICES 0x80E8 +#define GL_MAX_ELEMENTS_INDICES 0x80E9 +#define GL_CLAMP_TO_EDGE 0x812F +#define GL_TEXTURE_MIN_LOD 0x813A +#define GL_TEXTURE_MAX_LOD 0x813B +#define GL_TEXTURE_BASE_LEVEL 0x813C +#define GL_TEXTURE_MAX_LEVEL 0x813D +#define GL_LIGHT_MODEL_COLOR_CONTROL 0x81F8 +#define GL_SINGLE_COLOR 0x81F9 +#define GL_SEPARATE_SPECULAR_COLOR 0x81FA +#define GL_UNSIGNED_BYTE_2_3_3_REV 0x8362 +#define GL_UNSIGNED_SHORT_5_6_5 0x8363 +#define GL_UNSIGNED_SHORT_5_6_5_REV 0x8364 +#define GL_UNSIGNED_SHORT_4_4_4_4_REV 0x8365 +#define GL_UNSIGNED_SHORT_1_5_5_5_REV 0x8366 +#define GL_UNSIGNED_INT_8_8_8_8_REV 0x8367 +#define GL_UNSIGNED_INT_2_10_10_10_REV 0x8368 +#define GL_ALIASED_POINT_SIZE_RANGE 0x846D +#define GL_ALIASED_LINE_WIDTH_RANGE 0x846E + +#define glCopyTexSubImage3D GlobalOpenGL().m_glCopyTexSubImage3D +#define glDrawRangeElements GlobalOpenGL().m_glDrawRangeElements +#define glTexImage3D GlobalOpenGL().m_glTexImage3D +#define glTexSubImage3D GlobalOpenGL().m_glTexSubImage3D + +#endif + + +// GL 1.3 + +#if !defined(GL_VERSION_1_3) +#define GL_VERSION_1_3 1 + +#define GL_MULTISAMPLE 0x809D +#define GL_SAMPLE_ALPHA_TO_COVERAGE 0x809E +#define GL_SAMPLE_ALPHA_TO_ONE 0x809F +#define GL_SAMPLE_COVERAGE 0x80A0 +#define GL_SAMPLE_BUFFERS 0x80A8 +#define GL_SAMPLES 0x80A9 +#define GL_SAMPLE_COVERAGE_VALUE 0x80AA +#define GL_SAMPLE_COVERAGE_INVERT 0x80AB +#define GL_CLAMP_TO_BORDER 0x812D +#define GL_TEXTURE0 0x84C0 +#define GL_TEXTURE1 0x84C1 +#define GL_TEXTURE2 0x84C2 +#define GL_TEXTURE3 0x84C3 +#define GL_TEXTURE4 0x84C4 +#define GL_TEXTURE5 0x84C5 +#define GL_TEXTURE6 0x84C6 +#define GL_TEXTURE7 0x84C7 +#define GL_TEXTURE8 0x84C8 +#define GL_TEXTURE9 0x84C9 +#define GL_TEXTURE10 0x84CA +#define GL_TEXTURE11 0x84CB +#define GL_TEXTURE12 0x84CC +#define GL_TEXTURE13 0x84CD +#define GL_TEXTURE14 0x84CE +#define GL_TEXTURE15 0x84CF +#define GL_TEXTURE16 0x84D0 +#define GL_TEXTURE17 0x84D1 +#define GL_TEXTURE18 0x84D2 +#define GL_TEXTURE19 0x84D3 +#define GL_TEXTURE20 0x84D4 +#define GL_TEXTURE21 0x84D5 +#define GL_TEXTURE22 0x84D6 +#define GL_TEXTURE23 0x84D7 +#define GL_TEXTURE24 0x84D8 +#define GL_TEXTURE25 0x84D9 +#define GL_TEXTURE26 0x84DA +#define GL_TEXTURE27 0x84DB +#define GL_TEXTURE28 0x84DC +#define GL_TEXTURE29 0x84DD +#define GL_TEXTURE30 0x84DE +#define GL_TEXTURE31 0x84DF +#define GL_ACTIVE_TEXTURE 0x84E0 +#define GL_CLIENT_ACTIVE_TEXTURE 0x84E1 +#define GL_MAX_TEXTURE_UNITS 0x84E2 +#define GL_TRANSPOSE_MODELVIEW_MATRIX 0x84E3 +#define GL_TRANSPOSE_PROJECTION_MATRIX 0x84E4 +#define GL_TRANSPOSE_TEXTURE_MATRIX 0x84E5 +#define GL_TRANSPOSE_COLOR_MATRIX 0x84E6 +#define GL_SUBTRACT 0x84E7 +#define GL_COMPRESSED_ALPHA 0x84E9 +#define GL_COMPRESSED_LUMINANCE 0x84EA +#define GL_COMPRESSED_LUMINANCE_ALPHA 0x84EB +#define GL_COMPRESSED_INTENSITY 0x84EC +#define GL_COMPRESSED_RGB 0x84ED +#define GL_COMPRESSED_RGBA 0x84EE +#define GL_TEXTURE_COMPRESSION_HINT 0x84EF +#define GL_NORMAL_MAP 0x8511 +#define GL_REFLECTION_MAP 0x8512 +#define GL_TEXTURE_CUBE_MAP 0x8513 +#define GL_TEXTURE_BINDING_CUBE_MAP 0x8514 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_X 0x8515 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_X 0x8516 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Y 0x8517 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Y 0x8518 +#define GL_TEXTURE_CUBE_MAP_POSITIVE_Z 0x8519 +#define GL_TEXTURE_CUBE_MAP_NEGATIVE_Z 0x851A +#define GL_PROXY_TEXTURE_CUBE_MAP 0x851B +#define GL_MAX_CUBE_MAP_TEXTURE_SIZE 0x851C +#define GL_COMBINE 0x8570 +#define GL_COMBINE_RGB 0x8571 +#define GL_COMBINE_ALPHA 0x8572 +#define GL_RGB_SCALE 0x8573 +#define GL_ADD_SIGNED 0x8574 +#define GL_INTERPOLATE 0x8575 +#define GL_CONSTANT 0x8576 +#define GL_PRIMARY_COLOR 0x8577 +#define GL_PREVIOUS 0x8578 +#define GL_SOURCE0_RGB 0x8580 +#define GL_SOURCE1_RGB 0x8581 +#define GL_SOURCE2_RGB 0x8582 +#define GL_SOURCE0_ALPHA 0x8588 +#define GL_SOURCE1_ALPHA 0x8589 +#define GL_SOURCE2_ALPHA 0x858A +#define GL_OPERAND0_RGB 0x8590 +#define GL_OPERAND1_RGB 0x8591 +#define GL_OPERAND2_RGB 0x8592 +#define GL_OPERAND0_ALPHA 0x8598 +#define GL_OPERAND1_ALPHA 0x8599 +#define GL_OPERAND2_ALPHA 0x859A +#define GL_TEXTURE_COMPRESSED_IMAGE_SIZE 0x86A0 +#define GL_TEXTURE_COMPRESSED 0x86A1 +#define GL_NUM_COMPRESSED_TEXTURE_FORMATS 0x86A2 +#define GL_COMPRESSED_TEXTURE_FORMATS 0x86A3 +#define GL_DOT3_RGB 0x86AE +#define GL_DOT3_RGBA 0x86AF +#define GL_MULTISAMPLE_BIT 0x20000000 + +#define glActiveTexture GlobalOpenGL().m_glActiveTexture +#define glClientActiveTexture GlobalOpenGL().m_glClientActiveTexture +#define glCompressedTexImage1D GlobalOpenGL().m_glCompressedTexImage1D +#define glCompressedTexImage2D GlobalOpenGL().m_glCompressedTexImage2D +#define glCompressedTexImage3D GlobalOpenGL().m_glCompressedTexImage3D +#define glCompressedTexSubImage1D GlobalOpenGL().m_glCompressedTexSubImage1D +#define glCompressedTexSubImage2D GlobalOpenGL().m_glCompressedTexSubImage2D +#define glCompressedTexSubImage3D GlobalOpenGL().m_glCompressedTexSubImage3D +#define glGetCompressedTexImage GlobalOpenGL().m_glGetCompressedTexImage +#define glLoadTransposeMatrixd GlobalOpenGL().m_glLoadTransposeMatrixd +#define glLoadTransposeMatrixf GlobalOpenGL().m_glLoadTransposeMatrixf +#define glMultTransposeMatrixd GlobalOpenGL().m_glMultTransposeMatrixd +#define glMultTransposeMatrixf GlobalOpenGL().m_glMultTransposeMatrixf +#define glMultiTexCoord1d GlobalOpenGL().m_glMultiTexCoord1d +#define glMultiTexCoord1dv GlobalOpenGL().m_glMultiTexCoord1dv +#define glMultiTexCoord1f GlobalOpenGL().m_glMultiTexCoord1f +#define glMultiTexCoord1fv GlobalOpenGL().m_glMultiTexCoord1fv +#define glMultiTexCoord1i GlobalOpenGL().m_glMultiTexCoord1i +#define glMultiTexCoord1iv GlobalOpenGL().m_glMultiTexCoord1iv +#define glMultiTexCoord1s GlobalOpenGL().m_glMultiTexCoord1s +#define glMultiTexCoord1sv GlobalOpenGL().m_glMultiTexCoord1sv +#define glMultiTexCoord2d GlobalOpenGL().m_glMultiTexCoord2d +#define glMultiTexCoord2dv GlobalOpenGL().m_glMultiTexCoord2dv +#define glMultiTexCoord2f GlobalOpenGL().m_glMultiTexCoord2f +#define glMultiTexCoord2fv GlobalOpenGL().m_glMultiTexCoord2fv +#define glMultiTexCoord2i GlobalOpenGL().m_glMultiTexCoord2i +#define glMultiTexCoord2iv GlobalOpenGL().m_glMultiTexCoord2iv +#define glMultiTexCoord2s GlobalOpenGL().m_glMultiTexCoord2s +#define glMultiTexCoord2sv GlobalOpenGL().m_glMultiTexCoord2sv +#define glMultiTexCoord3d GlobalOpenGL().m_glMultiTexCoord3d +#define glMultiTexCoord3dv GlobalOpenGL().m_glMultiTexCoord3dv +#define glMultiTexCoord3f GlobalOpenGL().m_glMultiTexCoord3f +#define glMultiTexCoord3fv GlobalOpenGL().m_glMultiTexCoord3fv +#define glMultiTexCoord3i GlobalOpenGL().m_glMultiTexCoord3i +#define glMultiTexCoord3iv GlobalOpenGL().m_glMultiTexCoord3iv +#define glMultiTexCoord3s GlobalOpenGL().m_glMultiTexCoord3s +#define glMultiTexCoord3sv GlobalOpenGL().m_glMultiTexCoord3sv +#define glMultiTexCoord4d GlobalOpenGL().m_glMultiTexCoord4d +#define glMultiTexCoord4dv GlobalOpenGL().m_glMultiTexCoord4dv +#define glMultiTexCoord4f GlobalOpenGL().m_glMultiTexCoord4f +#define glMultiTexCoord4fv GlobalOpenGL().m_glMultiTexCoord4fv +#define glMultiTexCoord4i GlobalOpenGL().m_glMultiTexCoord4i +#define glMultiTexCoord4iv GlobalOpenGL().m_glMultiTexCoord4iv +#define glMultiTexCoord4s GlobalOpenGL().m_glMultiTexCoord4s +#define glMultiTexCoord4sv GlobalOpenGL().m_glMultiTexCoord4sv +#define glSampleCoverage GlobalOpenGL().m_glSampleCoverage + +#endif + + +// GL 1.4 +#if !defined(GL_VERSION_1_4) +#define GL_VERSION_1_4 1 + +#define GL_BLEND_DST_RGB 0x80C8 +#define GL_BLEND_SRC_RGB 0x80C9 +#define GL_BLEND_DST_ALPHA 0x80CA +#define GL_BLEND_SRC_ALPHA 0x80CB +#define GL_POINT_SIZE_MIN 0x8126 +#define GL_POINT_SIZE_MAX 0x8127 +#define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 +#define GL_POINT_DISTANCE_ATTENUATION 0x8129 +#define GL_GENERATE_MIPMAP 0x8191 +#define GL_GENERATE_MIPMAP_HINT 0x8192 +#define GL_DEPTH_COMPONENT16 0x81A5 +#define GL_DEPTH_COMPONENT24 0x81A6 +#define GL_DEPTH_COMPONENT32 0x81A7 +#define GL_MIRRORED_REPEAT 0x8370 +#define GL_FOG_COORDINATE_SOURCE 0x8450 +#define GL_FOG_COORDINATE 0x8451 +#define GL_FRAGMENT_DEPTH 0x8452 +#define GL_CURRENT_FOG_COORDINATE 0x8453 +#define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 +#define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 +#define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 +#define GL_FOG_COORDINATE_ARRAY 0x8457 +#define GL_COLOR_SUM 0x8458 +#define GL_CURRENT_SECONDARY_COLOR 0x8459 +#define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A +#define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B +#define GL_SECONDARY_COLOR_ARRAY_STRIDE 0x845C +#define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D +#define GL_SECONDARY_COLOR_ARRAY 0x845E +#define GL_MAX_TEXTURE_LOD_BIAS 0x84FD +#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE +#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF +#define GL_TEXTURE_FILTER_CONTROL 0x8500 +#define GL_TEXTURE_LOD_BIAS 0x8501 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#define GL_TEXTURE_DEPTH_SIZE 0x884A +#define GL_DEPTH_TEXTURE_MODE 0x884B +#define GL_TEXTURE_COMPARE_MODE 0x884C +#define GL_TEXTURE_COMPARE_FUNC 0x884D +#define GL_COMPARE_R_TO_TEXTURE 0x884E + +#define glBlendColor GlobalOpenGL().m_glBlendColor +#define glBlendEquation GlobalOpenGL().m_glBlendEquation +#define glBlendFuncSeparate GlobalOpenGL().m_glBlendFuncSeparate +#define glFogCoordPointer GlobalOpenGL().m_glFogCoordPointer +#define glFogCoordd GlobalOpenGL().m_glFogCoordd +#define glFogCoorddv GlobalOpenGL().m_glFogCoorddv +#define glFogCoordf GlobalOpenGL().m_glFogCoordf +#define glFogCoordfv GlobalOpenGL().m_glFogCoordfv +#define glMultiDrawArrays GlobalOpenGL().m_glMultiDrawArrays +#define glMultiDrawElements GlobalOpenGL().m_glMultiDrawElements +#define glPointParameterf GlobalOpenGL().m_glPointParameterf +#define glPointParameterfv GlobalOpenGL().m_glPointParameterfv +#define glSecondaryColor3b GlobalOpenGL().m_glSecondaryColor3b +#define glSecondaryColor3bv GlobalOpenGL().m_glSecondaryColor3bv +#define glSecondaryColor3d GlobalOpenGL().m_glSecondaryColor3d +#define glSecondaryColor3dv GlobalOpenGL().m_glSecondaryColor3dv +#define glSecondaryColor3f GlobalOpenGL().m_glSecondaryColor3f +#define glSecondaryColor3fv GlobalOpenGL().m_glSecondaryColor3fv +#define glSecondaryColor3i GlobalOpenGL().m_glSecondaryColor3i +#define glSecondaryColor3iv GlobalOpenGL().m_glSecondaryColor3iv +#define glSecondaryColor3s GlobalOpenGL().m_glSecondaryColor3s +#define glSecondaryColor3sv GlobalOpenGL().m_glSecondaryColor3sv +#define glSecondaryColor3ub GlobalOpenGL().m_glSecondaryColor3ub +#define glSecondaryColor3ubv GlobalOpenGL().m_glSecondaryColor3ubv +#define glSecondaryColor3ui GlobalOpenGL().m_glSecondaryColor3ui +#define glSecondaryColor3uiv GlobalOpenGL().m_glSecondaryColor3uiv +#define glSecondaryColor3us GlobalOpenGL().m_glSecondaryColor3us +#define glSecondaryColor3usv GlobalOpenGL().m_glSecondaryColor3usv +#define glSecondaryColorPointer GlobalOpenGL().m_glSecondaryColorPointer +#define glWindowPos2d GlobalOpenGL().m_glWindowPos2d +#define glWindowPos2dv GlobalOpenGL().m_glWindowPos2dv +#define glWindowPos2f GlobalOpenGL().m_glWindowPos2f +#define glWindowPos2fv GlobalOpenGL().m_glWindowPos2fv +#define glWindowPos2i GlobalOpenGL().m_glWindowPos2i +#define glWindowPos2iv GlobalOpenGL().m_glWindowPos2iv +#define glWindowPos2s GlobalOpenGL().m_glWindowPos2s +#define glWindowPos2sv GlobalOpenGL().m_glWindowPos2sv +#define glWindowPos3d GlobalOpenGL().m_glWindowPos3d +#define glWindowPos3dv GlobalOpenGL().m_glWindowPos3dv +#define glWindowPos3f GlobalOpenGL().m_glWindowPos3f +#define glWindowPos3fv GlobalOpenGL().m_glWindowPos3fv +#define glWindowPos3i GlobalOpenGL().m_glWindowPos3i +#define glWindowPos3iv GlobalOpenGL().m_glWindowPos3iv +#define glWindowPos3s GlobalOpenGL().m_glWindowPos3s +#define glWindowPos3sv GlobalOpenGL().m_glWindowPos3sv + +#endif + + +// GL 1.5 +#if !defined(GL_VERSION_1_5) +#define GL_VERSION_1_5 1 + +#define GL_FOG_COORD GL_FOG_COORDINATE +#define GL_FOG_COORD_ARRAY GL_FOG_COORDINATE_ARRAY +#define GL_SRC0_RGB GL_SOURCE0_RGB +#define GL_FOG_COORD_ARRAY_POINTER GL_FOG_COORDINATE_ARRAY_POINTER +#define GL_FOG_COORD_SOURCE GL_FOG_COORDINATE_SOURCE +#define GL_FOG_COORD_ARRAY_TYPE GL_FOG_COORDINATE_ARRAY_TYPE +#define GL_SRC1_ALPHA GL_SOURCE1_ALPHA +#define GL_CURRENT_FOG_COORD GL_CURRENT_FOG_COORDINATE +#define GL_FOG_COORD_ARRAY_STRIDE GL_FOG_COORDINATE_ARRAY_STRIDE +#define GL_SRC0_ALPHA GL_SOURCE0_ALPHA +#define GL_SRC1_RGB GL_SOURCE1_RGB +#define GL_FOG_COORD_ARRAY_BUFFER_BINDING GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING +#define GL_SRC2_ALPHA GL_SOURCE2_ALPHA +#define GL_SRC2_RGB GL_SOURCE2_RGB +#define GL_BUFFER_SIZE 0x8764 +#define GL_BUFFER_USAGE 0x8765 +#define GL_QUERY_COUNTER_BITS 0x8864 +#define GL_CURRENT_QUERY 0x8865 +#define GL_QUERY_RESULT 0x8866 +#define GL_QUERY_RESULT_AVAILABLE 0x8867 +#define GL_ARRAY_BUFFER 0x8892 +#define GL_ELEMENT_ARRAY_BUFFER 0x8893 +#define GL_ARRAY_BUFFER_BINDING 0x8894 +#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895 +#define GL_VERTEX_ARRAY_BUFFER_BINDING 0x8896 +#define GL_NORMAL_ARRAY_BUFFER_BINDING 0x8897 +#define GL_COLOR_ARRAY_BUFFER_BINDING 0x8898 +#define GL_INDEX_ARRAY_BUFFER_BINDING 0x8899 +#define GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING 0x889A +#define GL_EDGE_FLAG_ARRAY_BUFFER_BINDING 0x889B +#define GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING 0x889C +#define GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING 0x889D +#define GL_WEIGHT_ARRAY_BUFFER_BINDING 0x889E +#define GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING 0x889F +#define GL_READ_ONLY 0x88B8 +#define GL_WRITE_ONLY 0x88B9 +#define GL_READ_WRITE 0x88BA +#define GL_BUFFER_ACCESS 0x88BB +#define GL_BUFFER_MAPPED 0x88BC +#define GL_BUFFER_MAP_POINTER 0x88BD +#define GL_STREAM_DRAW 0x88E0 +#define GL_STREAM_READ 0x88E1 +#define GL_STREAM_COPY 0x88E2 +#define GL_STATIC_DRAW 0x88E4 +#define GL_STATIC_READ 0x88E5 +#define GL_STATIC_COPY 0x88E6 +#define GL_DYNAMIC_DRAW 0x88E8 +#define GL_DYNAMIC_READ 0x88E9 +#define GL_DYNAMIC_COPY 0x88EA +#define GL_SAMPLES_PASSED 0x8914 + +typedef std::ptrdiff_t GLsizeiptr; +typedef std::ptrdiff_t GLintptr; + +#define glBeginQuery GlobalOpenGL().m_glBeginQuery +#define glBindBuffer GlobalOpenGL().m_glBindBuffer +#define glBufferData GlobalOpenGL().m_glBufferData +#define glBufferSubData GlobalOpenGL().m_glBufferSubData +#define glDeleteBuffers GlobalOpenGL().m_glDeleteBuffers +#define glDeleteQueries GlobalOpenGL().m_glDeleteQueries +#define glEndQuery GlobalOpenGL().m_glEndQuery +#define glGenBuffers GlobalOpenGL().m_glGenBuffers +#define glGenQueries GlobalOpenGL().m_glGenQueries +#define glGetBufferParameteriv GlobalOpenGL().m_glGetBufferParameteriv +#define glGetBufferPointerv GlobalOpenGL().m_glGetBufferPointerv +#define glGetBufferSubData GlobalOpenGL().m_glGetBufferSubData +#define glGetQueryObjectiv GlobalOpenGL().m_glGetQueryObjectiv +#define glGetQueryObjectuiv GlobalOpenGL().m_glGetQueryObjectuiv +#define glGetQueryiv GlobalOpenGL().m_glGetQueryiv +#define glIsBuffer GlobalOpenGL().m_glIsBuffer +#define glIsQuery GlobalOpenGL().m_glIsQuery +#define glMapBuffer GlobalOpenGL().m_glMapBuffer +#define glUnmapBuffer GlobalOpenGL().m_glUnmapBuffer + +#endif + + +// GL_ARB_vertex_program +#if !defined(GL_ARB_vertex_program) +#define GL_ARB_vertex_program + +#define GL_VERTEX_PROGRAM_ARB 0x8620 +#define GL_VERTEX_PROGRAM_POINT_SIZE_ARB 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_ARB 0x8643 +#define GL_COLOR_SUM_ARB 0x8458 +#define GL_PROGRAM_FORMAT_ASCII_ARB 0x8875 +#define GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB 0x8622 +#define GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB 0x8623 +#define GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB 0x8624 +#define GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB 0x8625 +#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB 0x886A +#define GL_CURRENT_VERTEX_ATTRIB_ARB 0x8626 +#define GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB 0x8645 +#define GL_PROGRAM_LENGTH_ARB 0x8627 +#define GL_PROGRAM_FORMAT_ARB 0x8876 +#define GL_PROGRAM_BINDING_ARB 0x8677 +#define GL_PROGRAM_INSTRUCTIONS_ARB 0x88A0 +#define GL_MAX_PROGRAM_INSTRUCTIONS_ARB 0x88A1 +#define GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A2 +#define GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB 0x88A3 +#define GL_PROGRAM_TEMPORARIES_ARB 0x88A4 +#define GL_MAX_PROGRAM_TEMPORARIES_ARB 0x88A5 +#define GL_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A6 +#define GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB 0x88A7 +#define GL_PROGRAM_PARAMETERS_ARB 0x88A8 +#define GL_MAX_PROGRAM_PARAMETERS_ARB 0x88A9 +#define GL_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AA +#define GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB 0x88AB +#define GL_PROGRAM_ATTRIBS_ARB 0x88AC +#define GL_MAX_PROGRAM_ATTRIBS_ARB 0x88AD +#define GL_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AE +#define GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB 0x88AF +#define GL_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B0 +#define GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB 0x88B1 +#define GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B2 +#define GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB 0x88B3 +#define GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB 0x88B4 +#define GL_MAX_PROGRAM_ENV_PARAMETERS_ARB 0x88B5 +#define GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB 0x88B6 +#define GL_PROGRAM_STRING_ARB 0x8628 +#define GL_PROGRAM_ERROR_POSITION_ARB 0x864B +#define GL_CURRENT_MATRIX_ARB 0x8641 +#define GL_TRANSPOSE_CURRENT_MATRIX_ARB 0x88B7 +#define GL_CURRENT_MATRIX_STACK_DEPTH_ARB 0x8640 +#define GL_MAX_VERTEX_ATTRIBS_ARB 0x8869 +#define GL_MAX_PROGRAM_MATRICES_ARB 0x862F +#define GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB 0x862E +#define GL_PROGRAM_ERROR_STRING_ARB 0x8874 +#define GL_MATRIX0_ARB 0x88C0 +#define GL_MATRIX1_ARB 0x88C1 +#define GL_MATRIX2_ARB 0x88C2 +#define GL_MATRIX3_ARB 0x88C3 +#define GL_MATRIX4_ARB 0x88C4 +#define GL_MATRIX5_ARB 0x88C5 +#define GL_MATRIX6_ARB 0x88C6 +#define GL_MATRIX7_ARB 0x88C7 +#define GL_MATRIX8_ARB 0x88C8 +#define GL_MATRIX9_ARB 0x88C9 +#define GL_MATRIX10_ARB 0x88CA +#define GL_MATRIX11_ARB 0x88CB +#define GL_MATRIX12_ARB 0x88CC +#define GL_MATRIX13_ARB 0x88CD +#define GL_MATRIX14_ARB 0x88CE +#define GL_MATRIX15_ARB 0x88CF +#define GL_MATRIX16_ARB 0x88D0 +#define GL_MATRIX17_ARB 0x88D1 +#define GL_MATRIX18_ARB 0x88D2 +#define GL_MATRIX19_ARB 0x88D3 +#define GL_MATRIX20_ARB 0x88D4 +#define GL_MATRIX21_ARB 0x88D5 +#define GL_MATRIX22_ARB 0x88D6 +#define GL_MATRIX23_ARB 0x88D7 +#define GL_MATRIX24_ARB 0x88D8 +#define GL_MATRIX25_ARB 0x88D9 +#define GL_MATRIX26_ARB 0x88DA +#define GL_MATRIX27_ARB 0x88DB +#define GL_MATRIX28_ARB 0x88DC +#define GL_MATRIX29_ARB 0x88DD +#define GL_MATRIX30_ARB 0x88DE +#define GL_MATRIX31_ARB 0x88DF + +#define glVertexAttrib1sARB GlobalOpenGL().m_glVertexAttrib1sARB +#define glVertexAttrib1fARB GlobalOpenGL().m_glVertexAttrib1fARB +#define glVertexAttrib1dARB GlobalOpenGL().m_glVertexAttrib1dARB +#define glVertexAttrib2sARB GlobalOpenGL().m_glVertexAttrib2sARB +#define glVertexAttrib2fARB GlobalOpenGL().m_glVertexAttrib2fARB +#define glVertexAttrib2dARB GlobalOpenGL().m_glVertexAttrib2dARB +#define glVertexAttrib3sARB GlobalOpenGL().m_glVertexAttrib3sARB +#define glVertexAttrib3fARB GlobalOpenGL().m_glVertexAttrib3fARB +#define glVertexAttrib3dARB GlobalOpenGL().m_glVertexAttrib3dARB +#define glVertexAttrib4sARB GlobalOpenGL().m_glVertexAttrib4sARB +#define glVertexAttrib4fARB GlobalOpenGL().m_glVertexAttrib4fARB +#define glVertexAttrib4dARB GlobalOpenGL().m_glVertexAttrib4dARB +#define glVertexAttrib4NubARB GlobalOpenGL().m_glVertexAttrib4NubARB +#define glVertexAttrib1svARB GlobalOpenGL().m_glVertexAttrib1svARB +#define glVertexAttrib1fvARB GlobalOpenGL().m_glVertexAttrib1fvARB +#define glVertexAttrib1dvARB GlobalOpenGL().m_glVertexAttrib1dvARB +#define glVertexAttrib2svARB GlobalOpenGL().m_glVertexAttrib2svARB +#define glVertexAttrib2fvARB GlobalOpenGL().m_glVertexAttrib2fvARB +#define glVertexAttrib2dvARB GlobalOpenGL().m_glVertexAttrib2dvARB +#define glVertexAttrib3svARB GlobalOpenGL().m_glVertexAttrib3svARB +#define glVertexAttrib3fvARB GlobalOpenGL().m_glVertexAttrib3fvARB +#define glVertexAttrib3dvARB GlobalOpenGL().m_glVertexAttrib3dvARB +#define glVertexAttrib4bvARB GlobalOpenGL().m_glVertexAttrib4bvARB +#define glVertexAttrib4svARB GlobalOpenGL().m_glVertexAttrib4svARB +#define glVertexAttrib4ivARB GlobalOpenGL().m_glVertexAttrib4ivARB +#define glVertexAttrib4ubvARB GlobalOpenGL().m_glVertexAttrib4ubvARB +#define glVertexAttrib4usvARB GlobalOpenGL().m_glVertexAttrib4usvARB +#define glVertexAttrib4uivARB GlobalOpenGL().m_glVertexAttrib4uivARB +#define glVertexAttrib4fvARB GlobalOpenGL().m_glVertexAttrib4fvARB +#define glVertexAttrib4dvARB GlobalOpenGL().m_glVertexAttrib4dvARB +#define glVertexAttrib4NbvARB GlobalOpenGL().m_glVertexAttrib4NbvARB +#define glVertexAttrib4NsvARB GlobalOpenGL().m_glVertexAttrib4NsvARB +#define glVertexAttrib4NivARB GlobalOpenGL().m_glVertexAttrib4NivARB +#define glVertexAttrib4NubvARB GlobalOpenGL().m_glVertexAttrib4NubvARB +#define glVertexAttrib4NusvARB GlobalOpenGL().m_glVertexAttrib4NusvARB +#define glVertexAttrib4NuivARB GlobalOpenGL().m_glVertexAttrib4NuivARB +#define glVertexAttribPointerARB GlobalOpenGL().m_glVertexAttribPointerARB +#define glEnableVertexAttribArrayARB GlobalOpenGL().m_glEnableVertexAttribArrayARB +#define glDisableVertexAttribArrayARB GlobalOpenGL().m_glDisableVertexAttribArrayARB +#define glProgramStringARB GlobalOpenGL().m_glProgramStringARB +#define glBindProgramARB GlobalOpenGL().m_glBindProgramARB +#define glDeleteProgramsARB GlobalOpenGL().m_glDeleteProgramsARB +#define glGenProgramsARB GlobalOpenGL().m_glGenProgramsARB +#define glProgramEnvParameter4dARB GlobalOpenGL().m_glProgramEnvParameter4dARB +#define glProgramEnvParameter4dvARB GlobalOpenGL().m_glProgramEnvParameter4dvARB +#define glProgramEnvParameter4fARB GlobalOpenGL().m_glProgramEnvParameter4fARB +#define glProgramEnvParameter4fvARB GlobalOpenGL().m_glProgramEnvParameter4fvARB +#define glProgramLocalParameter4dARB GlobalOpenGL().m_glProgramLocalParameter4dARB +#define glProgramLocalParameter4dvARB GlobalOpenGL().m_glProgramLocalParameter4dvARB +#define glProgramLocalParameter4fARB GlobalOpenGL().m_glProgramLocalParameter4fARB +#define glProgramLocalParameter4fvARB GlobalOpenGL().m_glProgramLocalParameter4fvARB +#define glGetProgramEnvParameterdvARB GlobalOpenGL().m_glGetProgramEnvParameterdvARB +#define glGetProgramEnvParameterfvARB GlobalOpenGL().m_glGetProgramEnvParameterfvARB +#define glGetProgramLocalParameterdvARB GlobalOpenGL().m_glGetProgramLocalParameterdvARB +#define glGetProgramLocalParameterfvARB GlobalOpenGL().m_glGetProgramLocalParameterfvARB +#define glGetProgramivARB GlobalOpenGL().m_glGetProgramivARB +#define glGetProgramStringARB GlobalOpenGL().m_glGetProgramStringARB +#define glGetVertexAttribdvARB GlobalOpenGL().m_glGetVertexAttribdvARB +#define glGetVertexAttribfvARB GlobalOpenGL().m_glGetVertexAttribfvARB +#define glGetVertexAttribivARB GlobalOpenGL().m_glGetVertexAttribivARB +#define glGetVertexAttribPointervARB GlobalOpenGL().m_glGetVertexAttribPointervARB +#define glIsProgramARB GlobalOpenGL().m_glIsProgramARB + +#endif + + +// GL_ARB_fragment_program +#if !defined(GL_ARB_fragment_program) +#define GL_ARB_fragment_program 1 + +#define GL_FRAGMENT_PROGRAM_ARB 0x8804 +#define GL_PROGRAM_ALU_INSTRUCTIONS_ARB 0x8805 +#define GL_PROGRAM_TEX_INSTRUCTIONS_ARB 0x8806 +#define GL_PROGRAM_TEX_INDIRECTIONS_ARB 0x8807 +#define GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x8808 +#define GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x8809 +#define GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x880A +#define GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB 0x880B +#define GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB 0x880C +#define GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB 0x880D +#define GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB 0x880E +#define GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB 0x880F +#define GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB 0x8810 +#define GL_MAX_TEXTURE_COORDS_ARB 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_ARB 0x8872 + +#endif + + +// GL_ARB_shader_objects +#if !defined(GL_ARB_shader_objects) +#define GL_ARB_shader_objects 1 + +#define GL_PROGRAM_OBJECT_ARB 0x8B40 +#define GL_SHADER_OBJECT_ARB 0x8B48 +#define GL_OBJECT_TYPE_ARB 0x8B4E +#define GL_OBJECT_SUBTYPE_ARB 0x8B4F +#define GL_FLOAT_VEC2_ARB 0x8B50 +#define GL_FLOAT_VEC3_ARB 0x8B51 +#define GL_FLOAT_VEC4_ARB 0x8B52 +#define GL_INT_VEC2_ARB 0x8B53 +#define GL_INT_VEC3_ARB 0x8B54 +#define GL_INT_VEC4_ARB 0x8B55 +#define GL_BOOL_ARB 0x8B56 +#define GL_BOOL_VEC2_ARB 0x8B57 +#define GL_BOOL_VEC3_ARB 0x8B58 +#define GL_BOOL_VEC4_ARB 0x8B59 +#define GL_FLOAT_MAT2_ARB 0x8B5A +#define GL_FLOAT_MAT3_ARB 0x8B5B +#define GL_FLOAT_MAT4_ARB 0x8B5C +#define GL_SAMPLER_1D_ARB 0x8B5D +#define GL_SAMPLER_2D_ARB 0x8B5E +#define GL_SAMPLER_3D_ARB 0x8B5F +#define GL_SAMPLER_CUBE_ARB 0x8B60 +#define GL_SAMPLER_1D_SHADOW_ARB 0x8B61 +#define GL_SAMPLER_2D_SHADOW_ARB 0x8B62 +#define GL_SAMPLER_2D_RECT_ARB 0x8B63 +#define GL_SAMPLER_2D_RECT_SHADOW_ARB 0x8B64 +#define GL_OBJECT_DELETE_STATUS_ARB 0x8B80 +#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 +#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 +#define GL_OBJECT_VALIDATE_STATUS_ARB 0x8B83 +#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 +#define GL_OBJECT_ATTACHED_OBJECTS_ARB 0x8B85 +#define GL_OBJECT_ACTIVE_UNIFORMS_ARB 0x8B86 +#define GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB 0x8B87 +#define GL_OBJECT_SHADER_SOURCE_LENGTH_ARB 0x8B88 + +#define glDeleteObjectARB GlobalOpenGL().m_glDeleteObjectARB +#define glGetHandleARB GlobalOpenGL().m_glGetHandleARB +#define glDetachObjectARB GlobalOpenGL().m_glDetachObjectARB +#define glCreateShaderObjectARB GlobalOpenGL().m_glCreateShaderObjectARB +#define glShaderSourceARB GlobalOpenGL().m_glShaderSourceARB +#define glCompileShaderARB GlobalOpenGL().m_glCompileShaderARB +#define glCreateProgramObjectARB GlobalOpenGL().m_glCreateProgramObjectARB +#define glAttachObjectARB GlobalOpenGL().m_glAttachObjectARB +#define glLinkProgramARB GlobalOpenGL().m_glLinkProgramARB +#define glUseProgramObjectARB GlobalOpenGL().m_glUseProgramObjectARB +#define glValidateProgramARB GlobalOpenGL().m_glValidateProgramARB +#define glUniform1fARB GlobalOpenGL().m_glUniform1fARB +#define glUniform2fARB GlobalOpenGL().m_glUniform2fARB +#define glUniform3fARB GlobalOpenGL().m_glUniform3fARB +#define glUniform4fARB GlobalOpenGL().m_glUniform4fARB +#define glUniform1iARB GlobalOpenGL().m_glUniform1iARB +#define glUniform2iARB GlobalOpenGL().m_glUniform2iARB +#define glUniform3iARB GlobalOpenGL().m_glUniform3iARB +#define glUniform4iARB GlobalOpenGL().m_glUniform4iARB +#define glUniform1fvARB GlobalOpenGL().m_glUniform1fvARB +#define glUniform2fvARB GlobalOpenGL().m_glUniform2fvARB +#define glUniform3fvARB GlobalOpenGL().m_glUniform3fvARB +#define glUniform4fvARB GlobalOpenGL().m_glUniform4fvARB +#define glUniform1ivARB GlobalOpenGL().m_glUniform1ivARB +#define glUniform2ivARB GlobalOpenGL().m_glUniform2ivARB +#define glUniform3ivARB GlobalOpenGL().m_glUniform3ivARB +#define glUniform4ivARB GlobalOpenGL().m_glUniform4ivARB +#define glUniformMatrix2fvARB GlobalOpenGL().m_glUniformMatrix2fvARB +#define glUniformMatrix3fvARB GlobalOpenGL().m_glUniformMatrix3fvARB +#define glUniformMatrix4fvARB GlobalOpenGL().m_glUniformMatrix4fvARB +#define glGetObjectParameterfvARB GlobalOpenGL().m_glGetObjectParameterfvARB +#define glGetObjectParameterivARB GlobalOpenGL().m_glGetObjectParameterivARB +#define glGetInfoLogARB GlobalOpenGL().m_glGetInfoLogARB +#define glGetAttachedObjectsARB GlobalOpenGL().m_glGetAttachedObjectsARB +#define glGetUniformLocationARB GlobalOpenGL().m_glGetUniformLocationARB +#define glGetActiveUniformARB GlobalOpenGL().m_glGetActiveUniformARB +#define glGetUniformfvARB GlobalOpenGL().m_glGetUniformfvARB +#define glGetUniformivARB GlobalOpenGL().m_glGetUniformivARB +#define glGetShaderSourceARB GlobalOpenGL().m_glGetShaderSourceARB + +typedef char GLcharARB; +typedef unsigned int GLhandleARB; + +#endif + +// GL_ARB_vertex_shader +#if !defined(GL_ARB_vertex_shader) +#define GL_ARB_vertex_shader 1 + +#define GL_VERTEX_SHADER_ARB 0x8B31 +#define GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB 0x8B4A +#define GL_MAX_VARYING_FLOATS_ARB 0x8B4B +#define GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB 0x8B4C +#define GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB 0x8B4D +#define GL_OBJECT_ACTIVE_ATTRIBUTES_ARB 0x8B89 +#define GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB 0x8B8A + +#if 0 +#define glVertexAttrib1fARB GlobalOpenGL().m_glVertexAttrib1fARB +#define glVertexAttrib1sARB GlobalOpenGL().m_glVertexAttrib1sARB +#define glVertexAttrib1dARB GlobalOpenGL().m_glVertexAttrib1dARB +#define glVertexAttrib2fARB GlobalOpenGL().m_glVertexAttrib2fARB +#define glVertexAttrib2sARB GlobalOpenGL().m_glVertexAttrib2sARB +#define glVertexAttrib2dARB GlobalOpenGL().m_glVertexAttrib2dARB +#define glVertexAttrib3fARB GlobalOpenGL().m_glVertexAttrib3fARB +#define glVertexAttrib3sARB GlobalOpenGL().m_glVertexAttrib3sARB +#define glVertexAttrib3dARB GlobalOpenGL().m_glVertexAttrib3dARB +#define glVertexAttrib4fARB GlobalOpenGL().m_glVertexAttrib4fARB +#define glVertexAttrib4sARB GlobalOpenGL().m_glVertexAttrib4sARB +#define glVertexAttrib4dARB GlobalOpenGL().m_glVertexAttrib4dARB +#define glVertexAttrib4NubARB GlobalOpenGL().m_glVertexAttrib4NubARB +#define glVertexAttrib1fvARB GlobalOpenGL().m_glVertexAttrib1fvARB +#define glVertexAttrib1svARB GlobalOpenGL().m_glVertexAttrib1svARB +#define glVertexAttrib1dvARB GlobalOpenGL().m_glVertexAttrib1dvARB +#define glVertexAttrib2fvARB GlobalOpenGL().m_glVertexAttrib2fvARB +#define glVertexAttrib2svARB GlobalOpenGL().m_glVertexAttrib2svARB +#define glVertexAttrib2dvARB GlobalOpenGL().m_glVertexAttrib2dvARB +#define glVertexAttrib3fvARB GlobalOpenGL().m_glVertexAttrib3fvARB +#define glVertexAttrib3svARB GlobalOpenGL().m_glVertexAttrib3svARB +#define glVertexAttrib3dvARB GlobalOpenGL().m_glVertexAttrib3dvARB +#define glVertexAttrib4fvARB GlobalOpenGL().m_glVertexAttrib4fvARB +#define glVertexAttrib4svARB GlobalOpenGL().m_glVertexAttrib4svARB +#define glVertexAttrib4dvARB GlobalOpenGL().m_glVertexAttrib4dvARB +#define glVertexAttrib4ivARB GlobalOpenGL().m_glVertexAttrib4ivARB +#define glVertexAttrib4bvARB GlobalOpenGL().m_glVertexAttrib4bvARB +#define glVertexAttrib4ubvARB GlobalOpenGL().m_glVertexAttrib4ubvARB +#define glVertexAttrib4usvARB GlobalOpenGL().m_glVertexAttrib4usvARB +#define glVertexAttrib4uivARB GlobalOpenGL().m_glVertexAttrib4uivARB +#define glVertexAttrib4NbvARB GlobalOpenGL().m_glVertexAttrib4NbvARB +#define glVertexAttrib4NsvARB GlobalOpenGL().m_glVertexAttrib4NsvARB +#define glVertexAttrib4NivARB GlobalOpenGL().m_glVertexAttrib4NivARB +#define glVertexAttrib4NubvARB GlobalOpenGL().m_glVertexAttrib4NubvARB +#define glVertexAttrib4NusvARB GlobalOpenGL().m_glVertexAttrib4NusvARB +#define glVertexAttrib4NuivARB GlobalOpenGL().m_glVertexAttrib4NuivARB +#define glVertexAttribPointerARB GlobalOpenGL().m_glVertexAttribPointerARB +#define glEnableVertexAttribArrayARB GlobalOpenGL().m_glEnableVertexAttribArrayARB +#define glDisableVertexAttribArrayARB GlobalOpenGL().m_glDisableVertexAttribArrayARB +#endif +#define glBindAttribLocationARB GlobalOpenGL().m_glBindAttribLocationARB +#define glGetActiveAttribARB GlobalOpenGL().m_glGetActiveAttribARB +#define glGetAttribLocationARB GlobalOpenGL().m_glGetAttribLocationARB +#if 0 +#define glGetVertexAttribdvARB GlobalOpenGL().m_glGetVertexAttribdvARB +#define glGetVertexAttribfvARB GlobalOpenGL().m_glGetVertexAttribfvARB +#define glGetVertexAttribivARB GlobalOpenGL().m_glGetVertexAttribivARB +#define glGetVertexAttribPointervARB GlobalOpenGL().m_glGetVertexAttribPointervARB +#endif +#endif + + + +// GL_ARB_fragment_shader +#if !defined(GL_ARB_fragment_shader) +#define GL_ARB_fragment_shader 1 + +#define GL_FRAGMENT_SHADER_ARB 0x8B30 +#define GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB 0x8B49 +#define GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB 0x8B8B + +#endif + + +// GL_ARB_shading_language_100 +#if !defined(GL_ARB_shading_language_100) +#define GL_ARB_shading_language_100 1 + +#define GL_SHADING_LANGUAGE_VERSION_ARB 0x8B8C + +#endif + + +// GL_NV_vertex_program2 +#if !defined(GL_NV_vertex_program) +#define GL_NV_vertex_program 1 + +#define GL_VERTEX_PROGRAM_NV 0x8620 +#define GL_VERTEX_STATE_PROGRAM_NV 0x8621 +#define GL_ATTRIB_ARRAY_SIZE_NV 0x8623 +#define GL_ATTRIB_ARRAY_STRIDE_NV 0x8624 +#define GL_ATTRIB_ARRAY_TYPE_NV 0x8625 +#define GL_CURRENT_ATTRIB_NV 0x8626 +#define GL_PROGRAM_LENGTH_NV 0x8627 +#define GL_PROGRAM_STRING_NV 0x8628 +#define GL_MODELVIEW_PROJECTION_NV 0x8629 +#define GL_IDENTITY_NV 0x862A +#define GL_INVERSE_NV 0x862B +#define GL_TRANSPOSE_NV 0x862C +#define GL_INVERSE_TRANSPOSE_NV 0x862D +#define GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV 0x862E +#define GL_MAX_TRACK_MATRICES_NV 0x862F +#define GL_MATRIX0_NV 0x8630 +#define GL_MATRIX1_NV 0x8631 +#define GL_MATRIX2_NV 0x8632 +#define GL_MATRIX3_NV 0x8633 +#define GL_MATRIX4_NV 0x8634 +#define GL_MATRIX5_NV 0x8635 +#define GL_MATRIX6_NV 0x8636 +#define GL_MATRIX7_NV 0x8637 +#define GL_CURRENT_MATRIX_STACK_DEPTH_NV 0x8640 +#define GL_CURRENT_MATRIX_NV 0x8641 +#define GL_VERTEX_PROGRAM_POINT_SIZE_NV 0x8642 +#define GL_VERTEX_PROGRAM_TWO_SIDE_NV 0x8643 +#define GL_PROGRAM_PARAMETER_NV 0x8644 +#define GL_ATTRIB_ARRAY_POINTER_NV 0x8645 +#define GL_PROGRAM_TARGET_NV 0x8646 +#define GL_PROGRAM_RESIDENT_NV 0x8647 +#define GL_TRACK_MATRIX_NV 0x8648 +#define GL_TRACK_MATRIX_TRANSFORM_NV 0x8649 +#define GL_VERTEX_PROGRAM_BINDING_NV 0x864A +#define GL_PROGRAM_ERROR_POSITION_NV 0x864B +#define GL_VERTEX_ATTRIB_ARRAY0_NV 0x8650 +#define GL_VERTEX_ATTRIB_ARRAY1_NV 0x8651 +#define GL_VERTEX_ATTRIB_ARRAY2_NV 0x8652 +#define GL_VERTEX_ATTRIB_ARRAY3_NV 0x8653 +#define GL_VERTEX_ATTRIB_ARRAY4_NV 0x8654 +#define GL_VERTEX_ATTRIB_ARRAY5_NV 0x8655 +#define GL_VERTEX_ATTRIB_ARRAY6_NV 0x8656 +#define GL_VERTEX_ATTRIB_ARRAY7_NV 0x8657 +#define GL_VERTEX_ATTRIB_ARRAY8_NV 0x8658 +#define GL_VERTEX_ATTRIB_ARRAY9_NV 0x8659 +#define GL_VERTEX_ATTRIB_ARRAY10_NV 0x865A +#define GL_VERTEX_ATTRIB_ARRAY11_NV 0x865B +#define GL_VERTEX_ATTRIB_ARRAY12_NV 0x865C +#define GL_VERTEX_ATTRIB_ARRAY13_NV 0x865D +#define GL_VERTEX_ATTRIB_ARRAY14_NV 0x865E +#define GL_VERTEX_ATTRIB_ARRAY15_NV 0x865F +#define GL_MAP1_VERTEX_ATTRIB0_4_NV 0x8660 +#define GL_MAP1_VERTEX_ATTRIB1_4_NV 0x8661 +#define GL_MAP1_VERTEX_ATTRIB2_4_NV 0x8662 +#define GL_MAP1_VERTEX_ATTRIB3_4_NV 0x8663 +#define GL_MAP1_VERTEX_ATTRIB4_4_NV 0x8664 +#define GL_MAP1_VERTEX_ATTRIB5_4_NV 0x8665 +#define GL_MAP1_VERTEX_ATTRIB6_4_NV 0x8666 +#define GL_MAP1_VERTEX_ATTRIB7_4_NV 0x8667 +#define GL_MAP1_VERTEX_ATTRIB8_4_NV 0x8668 +#define GL_MAP1_VERTEX_ATTRIB9_4_NV 0x8669 +#define GL_MAP1_VERTEX_ATTRIB10_4_NV 0x866A +#define GL_MAP1_VERTEX_ATTRIB11_4_NV 0x866B +#define GL_MAP1_VERTEX_ATTRIB12_4_NV 0x866C +#define GL_MAP1_VERTEX_ATTRIB13_4_NV 0x866D +#define GL_MAP1_VERTEX_ATTRIB14_4_NV 0x866E +#define GL_MAP1_VERTEX_ATTRIB15_4_NV 0x866F +#define GL_MAP2_VERTEX_ATTRIB0_4_NV 0x8670 +#define GL_MAP2_VERTEX_ATTRIB1_4_NV 0x8671 +#define GL_MAP2_VERTEX_ATTRIB2_4_NV 0x8672 +#define GL_MAP2_VERTEX_ATTRIB3_4_NV 0x8673 +#define GL_MAP2_VERTEX_ATTRIB4_4_NV 0x8674 +#define GL_MAP2_VERTEX_ATTRIB5_4_NV 0x8675 +#define GL_MAP2_VERTEX_ATTRIB6_4_NV 0x8676 +#define GL_MAP2_VERTEX_ATTRIB7_4_NV 0x8677 +#define GL_MAP2_VERTEX_ATTRIB8_4_NV 0x8678 +#define GL_MAP2_VERTEX_ATTRIB9_4_NV 0x8679 +#define GL_MAP2_VERTEX_ATTRIB10_4_NV 0x867A +#define GL_MAP2_VERTEX_ATTRIB11_4_NV 0x867B +#define GL_MAP2_VERTEX_ATTRIB12_4_NV 0x867C +#define GL_MAP2_VERTEX_ATTRIB13_4_NV 0x867D +#define GL_MAP2_VERTEX_ATTRIB14_4_NV 0x867E +#define GL_MAP2_VERTEX_ATTRIB15_4_NV 0x867F + +#define glAreProgramsResidentNV GlobalOpenGL().m_glAreProgramsResidentNV +#define glBindProgramNV GlobalOpenGL().m_glBindProgramNV +#define glDeleteProgramsNV GlobalOpenGL().m_glDeleteProgramsNV +#define glExecuteProgramNV GlobalOpenGL().m_glExecuteProgramNV +#define glGenProgramsNV GlobalOpenGL().m_glGenProgramsNV +#define glGetProgramParameterdvNV GlobalOpenGL().m_glGetProgramParameterdvNV +#define glGetProgramParameterfvNV GlobalOpenGL().m_glGetProgramParameterfvNV +#define glGetProgramivNV GlobalOpenGL().m_glGetProgramivNV +#define glGetProgramStringNV GlobalOpenGL().m_glGetProgramStringNV +#define glGetTrackMatrixivNV GlobalOpenGL().m_glGetTrackMatrixivNV +#define glGetVertexAttribdvNV GlobalOpenGL().m_glGetVertexAttribdvNV +#define glGetVertexAttribfvNV GlobalOpenGL().m_glGetVertexAttribfvNV +#define glGetVertexAttribivNV GlobalOpenGL().m_glGetVertexAttribivNV +#define glGetVertexAttribPointervNV GlobalOpenGL().m_glGetVertexAttribPointervNV +#define glIsProgramNV GlobalOpenGL().m_glIsProgramNV +#define glLoadProgramNV GlobalOpenGL().m_glLoadProgramNV +#define glProgramParameter4fNV GlobalOpenGL().m_glProgramParameter4fNV +#define glProgramParameter4fvNV GlobalOpenGL().m_glProgramParameter4fvNV +#define glProgramParameters4fvNV GlobalOpenGL().m_glProgramParameters4fvNV +#define glRequestResidentProgramsNV GlobalOpenGL().m_glRequestResidentProgramsNV +#define glTrackMatrixNV GlobalOpenGL().m_glTrackMatrixNV +#define glVertexAttribPointerNV GlobalOpenGL().m_glVertexAttribPointerNV +#define glVertexAttrib1fNV GlobalOpenGL().m_glVertexAttrib1fNV +#define glVertexAttrib1fvNV GlobalOpenGL().m_glVertexAttrib1fvNV +#define glVertexAttrib2fNV GlobalOpenGL().m_glVertexAttrib2fNV +#define glVertexAttrib2fvNV GlobalOpenGL().m_glVertexAttrib2fvNV +#define glVertexAttrib3fNV GlobalOpenGL().m_glVertexAttrib3fNV +#define glVertexAttrib3fvNV GlobalOpenGL().m_glVertexAttrib3fvNV +#define glVertexAttrib4fNV GlobalOpenGL().m_glVertexAttrib4fNV +#define glVertexAttrib4fvNV GlobalOpenGL().m_glVertexAttrib4fvNV +#define glVertexAttribs1fvNV GlobalOpenGL().m_glVertexAttribs1fvNV +#define glVertexAttribs2fvNV GlobalOpenGL().m_glVertexAttribs2fvNV +#define glVertexAttribs3fvNV GlobalOpenGL().m_glVertexAttribs3fvNV +#define glVertexAttribs4fvNV GlobalOpenGL().m_glVertexAttribs4fvNV + +#endif + + +// GL_NV_fragment_program +#if !defined(GL_NV_fragment_program) + +#define GL_NV_fragment_program 1 + +#define GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV 0x8868 +#define GL_FRAGMENT_PROGRAM_NV 0x8870 +#define GL_MAX_TEXTURE_COORDS_NV 0x8871 +#define GL_MAX_TEXTURE_IMAGE_UNITS_NV 0x8872 +#define GL_FRAGMENT_PROGRAM_BINDING_NV 0x8873 +#define GL_PROGRAM_ERROR_STRING_NV 0x8874 + +#define glProgramNamedParameter4fNV GlobalOpenGL().m_glProgramNamedParameter4fNV +#define glProgramNamedParameter4fvNV GlobalOpenGL().m_glProgramNamedParameter4fvNV +#define glGetProgramNamedParameterfvNV GlobalOpenGL().m_glGetProgramNamedParameterfvNV + +#endif + +#include "gtkutil/glfont.h" + +/// \brief A module which wraps a runtime-binding of the standard OpenGL functions. +/// Provides convenience functions for querying availabiliy of extensions, rendering text and error-checking. +struct OpenGLBinding +{ + INTEGER_CONSTANT(Version, 2); + STRING_CONSTANT(Name, "qgl"); + + /// \brief OpenGL version, extracted from the GL_VERSION string. + int major_version, minor_version; + + /// \brief Is true if the global shared OpenGL context is valid. + bool contextValid; + + OpenGLBinding() : contextValid(false) + { + } + + /// \brief Asserts that there no OpenGL errors have occurred since the last call to glGetError. + void (*assertNoErrors)(const char *file, int line); + + GLFont *m_font; // MUST be set! + + /// \brief Renders \p string at the current raster-position of the current context. + void drawString(const char* string) const + { + m_font->printString(string); + } + + /// \brief Renders \p character at the current raster-position of the current context. + void drawChar(char character) const + { + char s[2]; + s[0] = character; + s[1] = 0; + drawString(s); + } + + + // GL 1.1 + void (QGL_DLLEXPORT *m_glAccum)(GLenum op, GLfloat value); + void (QGL_DLLEXPORT *m_glAlphaFunc)(GLenum func, GLclampf ref); + GLboolean (QGL_DLLEXPORT *m_glAreTexturesResident)(GLsizei n, const GLuint *textures, GLboolean *residences); + void (QGL_DLLEXPORT *m_glArrayElement)(GLint i); + void (QGL_DLLEXPORT *m_glBegin)(GLenum mode); + void (QGL_DLLEXPORT *m_glBindTexture)(GLenum target, GLuint texture); + void (QGL_DLLEXPORT *m_glBitmap)(GLsizei width, GLsizei height, GLfloat xorig, GLfloat yorig, GLfloat xmove, GLfloat ymove, const GLubyte *bitmap); + void (QGL_DLLEXPORT *m_glBlendFunc)(GLenum sfactor, GLenum dfactor); + void (QGL_DLLEXPORT *m_glCallList)(GLuint list); + void (QGL_DLLEXPORT *m_glCallLists)(GLsizei n, GLenum type, const GLvoid *lists); + void (QGL_DLLEXPORT *m_glClear)(GLbitfield mask); + void (QGL_DLLEXPORT *m_glClearAccum)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); + void (QGL_DLLEXPORT *m_glClearColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); + void (QGL_DLLEXPORT *m_glClearDepth)(GLclampd depth); + void (QGL_DLLEXPORT *m_glClearIndex)(GLfloat c); + void (QGL_DLLEXPORT *m_glClearStencil)(GLint s); + void (QGL_DLLEXPORT *m_glClipPlane)(GLenum plane, const GLdouble *equation); + void (QGL_DLLEXPORT *m_glColor3b)(GLbyte red, GLbyte green, GLbyte blue); + void (QGL_DLLEXPORT *m_glColor3bv)(const GLbyte *v); + void (QGL_DLLEXPORT *m_glColor3d)(GLdouble red, GLdouble green, GLdouble blue); + void (QGL_DLLEXPORT *m_glColor3dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glColor3f)(GLfloat red, GLfloat green, GLfloat blue); + void (QGL_DLLEXPORT *m_glColor3fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glColor3i)(GLint red, GLint green, GLint blue); + void (QGL_DLLEXPORT *m_glColor3iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glColor3s)(GLshort red, GLshort green, GLshort blue); + void (QGL_DLLEXPORT *m_glColor3sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glColor3ub)(GLubyte red, GLubyte green, GLubyte blue); + void (QGL_DLLEXPORT *m_glColor3ubv)(const GLubyte *v); + void (QGL_DLLEXPORT *m_glColor3ui)(GLuint red, GLuint green, GLuint blue); + void (QGL_DLLEXPORT *m_glColor3uiv)(const GLuint *v); + void (QGL_DLLEXPORT *m_glColor3us)(GLushort red, GLushort green, GLushort blue); + void (QGL_DLLEXPORT *m_glColor3usv)(const GLushort *v); + void (QGL_DLLEXPORT *m_glColor4b)(GLbyte red, GLbyte green, GLbyte blue, GLbyte alpha); + void (QGL_DLLEXPORT *m_glColor4bv)(const GLbyte *v); + void (QGL_DLLEXPORT *m_glColor4d)(GLdouble red, GLdouble green, GLdouble blue, GLdouble alpha); + void (QGL_DLLEXPORT *m_glColor4dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glColor4f)(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha); + void (QGL_DLLEXPORT *m_glColor4fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glColor4i)(GLint red, GLint green, GLint blue, GLint alpha); + void (QGL_DLLEXPORT *m_glColor4iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glColor4s)(GLshort red, GLshort green, GLshort blue, GLshort alpha); + void (QGL_DLLEXPORT *m_glColor4sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glColor4ub)(GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha); + void (QGL_DLLEXPORT *m_glColor4ubv)(const GLubyte *v); + void (QGL_DLLEXPORT *m_glColor4ui)(GLuint red, GLuint green, GLuint blue, GLuint alpha); + void (QGL_DLLEXPORT *m_glColor4uiv)(const GLuint *v); + void (QGL_DLLEXPORT *m_glColor4us)(GLushort red, GLushort green, GLushort blue, GLushort alpha); + void (QGL_DLLEXPORT *m_glColor4usv)(const GLushort *v); + void (QGL_DLLEXPORT *m_glColorMask)(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); + void (QGL_DLLEXPORT *m_glColorMaterial)(GLenum face, GLenum mode); + void (QGL_DLLEXPORT *m_glColorPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glCopyPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum type); + void (QGL_DLLEXPORT *m_glCopyTexImage1D)(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLint border); + void (QGL_DLLEXPORT *m_glCopyTexImage2D)(GLenum target, GLint level, GLenum internalFormat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); + void (QGL_DLLEXPORT *m_glCopyTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLint x, GLint y, GLsizei width); + void (QGL_DLLEXPORT *m_glCopyTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); + void (QGL_DLLEXPORT *m_glCullFace)(GLenum mode); + void (QGL_DLLEXPORT *m_glDeleteLists)(GLuint list, GLsizei range); + void (QGL_DLLEXPORT *m_glDeleteTextures)(GLsizei n, const GLuint *textures); + void (QGL_DLLEXPORT *m_glDepthFunc)(GLenum func); + void (QGL_DLLEXPORT *m_glDepthMask)(GLboolean flag); + void (QGL_DLLEXPORT *m_glDepthRange)(GLclampd zNear, GLclampd zFar); + void (QGL_DLLEXPORT *m_glDisable)(GLenum cap); + void (QGL_DLLEXPORT *m_glDisableClientState)(GLenum array); + void (QGL_DLLEXPORT *m_glDrawArrays)(GLenum mode, GLint first, GLsizei count); + void (QGL_DLLEXPORT *m_glDrawBuffer)(GLenum mode); + void (QGL_DLLEXPORT *m_glDrawElements)(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices); + void (QGL_DLLEXPORT *m_glDrawPixels)(GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); + void (QGL_DLLEXPORT *m_glEdgeFlag)(GLboolean flag); + void (QGL_DLLEXPORT *m_glEdgeFlagPointer)(GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glEdgeFlagv)(const GLboolean *flag); + void (QGL_DLLEXPORT *m_glEnable)(GLenum cap); + void (QGL_DLLEXPORT *m_glEnableClientState)(GLenum array); + void (QGL_DLLEXPORT *m_glEnd)(void); + void (QGL_DLLEXPORT *m_glEndList)(void); + void (QGL_DLLEXPORT *m_glEvalCoord1d)(GLdouble u); + void (QGL_DLLEXPORT *m_glEvalCoord1dv)(const GLdouble *u); + void (QGL_DLLEXPORT *m_glEvalCoord1f)(GLfloat u); + void (QGL_DLLEXPORT *m_glEvalCoord1fv)(const GLfloat *u); + void (QGL_DLLEXPORT *m_glEvalCoord2d)(GLdouble u, GLdouble v); + void (QGL_DLLEXPORT *m_glEvalCoord2dv)(const GLdouble *u); + void (QGL_DLLEXPORT *m_glEvalCoord2f)(GLfloat u, GLfloat v); + void (QGL_DLLEXPORT *m_glEvalCoord2fv)(const GLfloat *u); + void (QGL_DLLEXPORT *m_glEvalMesh1)(GLenum mode, GLint i1, GLint i2); + void (QGL_DLLEXPORT *m_glEvalMesh2)(GLenum mode, GLint i1, GLint i2, GLint j1, GLint j2); + void (QGL_DLLEXPORT *m_glEvalPoint1)(GLint i); + void (QGL_DLLEXPORT *m_glEvalPoint2)(GLint i, GLint j); + void (QGL_DLLEXPORT *m_glFeedbackBuffer)(GLsizei size, GLenum type, GLfloat *buffer); + void (QGL_DLLEXPORT *m_glFinish)(void); + void (QGL_DLLEXPORT *m_glFlush)(void); + void (QGL_DLLEXPORT *m_glFogf)(GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glFogfv)(GLenum pname, const GLfloat *params); + void (QGL_DLLEXPORT *m_glFogi)(GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glFogiv)(GLenum pname, const GLint *params); + void (QGL_DLLEXPORT *m_glFrontFace)(GLenum mode); + void (QGL_DLLEXPORT *m_glFrustum)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); + GLuint (QGL_DLLEXPORT *m_glGenLists)(GLsizei range); + void (QGL_DLLEXPORT *m_glGenTextures)(GLsizei n, GLuint *textures); + void (QGL_DLLEXPORT *m_glGetBooleanv)(GLenum pname, GLboolean *params); + void (QGL_DLLEXPORT *m_glGetClipPlane)(GLenum plane, GLdouble *equation); + void (QGL_DLLEXPORT *m_glGetDoublev)(GLenum pname, GLdouble *params); + GLenum (QGL_DLLEXPORT *m_glGetError)(void); + void (QGL_DLLEXPORT *m_glGetFloatv)(GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetIntegerv)(GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetLightfv)(GLenum light, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetLightiv)(GLenum light, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetMapdv)(GLenum target, GLenum query, GLdouble *v); + void (QGL_DLLEXPORT *m_glGetMapfv)(GLenum target, GLenum query, GLfloat *v); + void (QGL_DLLEXPORT *m_glGetMapiv)(GLenum target, GLenum query, GLint *v); + void (QGL_DLLEXPORT *m_glGetMaterialfv)(GLenum face, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetMaterialiv)(GLenum face, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetPixelMapfv)(GLenum map, GLfloat *values); + void (QGL_DLLEXPORT *m_glGetPixelMapuiv)(GLenum map, GLuint *values); + void (QGL_DLLEXPORT *m_glGetPixelMapusv)(GLenum map, GLushort *values); + void (QGL_DLLEXPORT *m_glGetPointerv)(GLenum pname, GLvoid* *params); + void (QGL_DLLEXPORT *m_glGetPolygonStipple)(GLubyte *mask); + const GLubyte * (QGL_DLLEXPORT *m_glGetString)(GLenum name); + void (QGL_DLLEXPORT *m_glGetTexEnvfv)(GLenum target, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetTexEnviv)(GLenum target, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetTexGendv)(GLenum coord, GLenum pname, GLdouble *params); + void (QGL_DLLEXPORT *m_glGetTexGenfv)(GLenum coord, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetTexGeniv)(GLenum coord, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetTexImage)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *pixels); + void (QGL_DLLEXPORT *m_glGetTexLevelParameterfv)(GLenum target, GLint level, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetTexLevelParameteriv)(GLenum target, GLint level, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetTexParameterfv)(GLenum target, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetTexParameteriv)(GLenum target, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glHint)(GLenum target, GLenum mode); + void (QGL_DLLEXPORT *m_glIndexMask)(GLuint mask); + void (QGL_DLLEXPORT *m_glIndexPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glIndexd)(GLdouble c); + void (QGL_DLLEXPORT *m_glIndexdv)(const GLdouble *c); + void (QGL_DLLEXPORT *m_glIndexf)(GLfloat c); + void (QGL_DLLEXPORT *m_glIndexfv)(const GLfloat *c); + void (QGL_DLLEXPORT *m_glIndexi)(GLint c); + void (QGL_DLLEXPORT *m_glIndexiv)(const GLint *c); + void (QGL_DLLEXPORT *m_glIndexs)(GLshort c); + void (QGL_DLLEXPORT *m_glIndexsv)(const GLshort *c); + void (QGL_DLLEXPORT *m_glIndexub)(GLubyte c); + void (QGL_DLLEXPORT *m_glIndexubv)(const GLubyte *c); + void (QGL_DLLEXPORT *m_glInitNames)(void); + void (QGL_DLLEXPORT *m_glInterleavedArrays)(GLenum format, GLsizei stride, const GLvoid *pointer); + GLboolean (QGL_DLLEXPORT *m_glIsEnabled)(GLenum cap); + GLboolean (QGL_DLLEXPORT *m_glIsList)(GLuint list); + GLboolean (QGL_DLLEXPORT *m_glIsTexture)(GLuint texture); + void (QGL_DLLEXPORT *m_glLightModelf)(GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glLightModelfv)(GLenum pname, const GLfloat *params); + void (QGL_DLLEXPORT *m_glLightModeli)(GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glLightModeliv)(GLenum pname, const GLint *params); + void (QGL_DLLEXPORT *m_glLightf)(GLenum light, GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glLightfv)(GLenum light, GLenum pname, const GLfloat *params); + void (QGL_DLLEXPORT *m_glLighti)(GLenum light, GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glLightiv)(GLenum light, GLenum pname, const GLint *params); + void (QGL_DLLEXPORT *m_glLineStipple)(GLint factor, GLushort pattern); + void (QGL_DLLEXPORT *m_glLineWidth)(GLfloat width); + void (QGL_DLLEXPORT *m_glListBase)(GLuint base); + void (QGL_DLLEXPORT *m_glLoadIdentity)(void); + void (QGL_DLLEXPORT *m_glLoadMatrixd)(const GLdouble *m); + void (QGL_DLLEXPORT *m_glLoadMatrixf)(const GLfloat *m); + void (QGL_DLLEXPORT *m_glLoadName)(GLuint name); + void (QGL_DLLEXPORT *m_glLogicOp)(GLenum opcode); + void (QGL_DLLEXPORT *m_glMap1d)(GLenum target, GLdouble u1, GLdouble u2, GLint stride, GLint order, const GLdouble *points); + void (QGL_DLLEXPORT *m_glMap1f)(GLenum target, GLfloat u1, GLfloat u2, GLint stride, GLint order, const GLfloat *points); + void (QGL_DLLEXPORT *m_glMap2d)(GLenum target, GLdouble u1, GLdouble u2, GLint ustride, GLint uorder, GLdouble v1, GLdouble v2, GLint vstride, GLint vorder, const GLdouble *points); + void (QGL_DLLEXPORT *m_glMap2f)(GLenum target, GLfloat u1, GLfloat u2, GLint ustride, GLint uorder, GLfloat v1, GLfloat v2, GLint vstride, GLint vorder, const GLfloat *points); + void (QGL_DLLEXPORT *m_glMapGrid1d)(GLint un, GLdouble u1, GLdouble u2); + void (QGL_DLLEXPORT *m_glMapGrid1f)(GLint un, GLfloat u1, GLfloat u2); + void (QGL_DLLEXPORT *m_glMapGrid2d)(GLint un, GLdouble u1, GLdouble u2, GLint vn, GLdouble v1, GLdouble v2); + void (QGL_DLLEXPORT *m_glMapGrid2f)(GLint un, GLfloat u1, GLfloat u2, GLint vn, GLfloat v1, GLfloat v2); + void (QGL_DLLEXPORT *m_glMaterialf)(GLenum face, GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glMaterialfv)(GLenum face, GLenum pname, const GLfloat *params); + void (QGL_DLLEXPORT *m_glMateriali)(GLenum face, GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glMaterialiv)(GLenum face, GLenum pname, const GLint *params); + void (QGL_DLLEXPORT *m_glMatrixMode)(GLenum mode); + void (QGL_DLLEXPORT *m_glMultMatrixd)(const GLdouble *m); + void (QGL_DLLEXPORT *m_glMultMatrixf)(const GLfloat *m); + void (QGL_DLLEXPORT *m_glNewList)(GLuint list, GLenum mode); + void (QGL_DLLEXPORT *m_glNormal3b)(GLbyte nx, GLbyte ny, GLbyte nz); + void (QGL_DLLEXPORT *m_glNormal3bv)(const GLbyte *v); + void (QGL_DLLEXPORT *m_glNormal3d)(GLdouble nx, GLdouble ny, GLdouble nz); + void (QGL_DLLEXPORT *m_glNormal3dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glNormal3f)(GLfloat nx, GLfloat ny, GLfloat nz); + void (QGL_DLLEXPORT *m_glNormal3fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glNormal3i)(GLint nx, GLint ny, GLint nz); + void (QGL_DLLEXPORT *m_glNormal3iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glNormal3s)(GLshort nx, GLshort ny, GLshort nz); + void (QGL_DLLEXPORT *m_glNormal3sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glNormalPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glOrtho)(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar); + void (QGL_DLLEXPORT *m_glPassThrough)(GLfloat token); + void (QGL_DLLEXPORT *m_glPixelMapfv)(GLenum map, GLsizei mapsize, const GLfloat *values); + void (QGL_DLLEXPORT *m_glPixelMapuiv)(GLenum map, GLsizei mapsize, const GLuint *values); + void (QGL_DLLEXPORT *m_glPixelMapusv)(GLenum map, GLsizei mapsize, const GLushort *values); + void (QGL_DLLEXPORT *m_glPixelStoref)(GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glPixelStorei)(GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glPixelTransferf)(GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glPixelTransferi)(GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glPixelZoom)(GLfloat xfactor, GLfloat yfactor); + void (QGL_DLLEXPORT *m_glPointSize)(GLfloat size); + void (QGL_DLLEXPORT *m_glPolygonMode)(GLenum face, GLenum mode); + void (QGL_DLLEXPORT *m_glPolygonOffset)(GLfloat factor, GLfloat units); + void (QGL_DLLEXPORT *m_glPolygonStipple)(const GLubyte *mask); + void (QGL_DLLEXPORT *m_glPopAttrib)(void); + void (QGL_DLLEXPORT *m_glPopClientAttrib)(void); + void (QGL_DLLEXPORT *m_glPopMatrix)(void); + void (QGL_DLLEXPORT *m_glPopName)(void); + void (QGL_DLLEXPORT *m_glPrioritizeTextures)(GLsizei n, const GLuint *textures, const GLclampf *priorities); + void (QGL_DLLEXPORT *m_glPushAttrib)(GLbitfield mask); + void (QGL_DLLEXPORT *m_glPushClientAttrib)(GLbitfield mask); + void (QGL_DLLEXPORT *m_glPushMatrix)(void); + void (QGL_DLLEXPORT *m_glPushName)(GLuint name); + void (QGL_DLLEXPORT *m_glRasterPos2d)(GLdouble x, GLdouble y); + void (QGL_DLLEXPORT *m_glRasterPos2dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glRasterPos2f)(GLfloat x, GLfloat y); + void (QGL_DLLEXPORT *m_glRasterPos2fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glRasterPos2i)(GLint x, GLint y); + void (QGL_DLLEXPORT *m_glRasterPos2iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glRasterPos2s)(GLshort x, GLshort y); + void (QGL_DLLEXPORT *m_glRasterPos2sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glRasterPos3d)(GLdouble x, GLdouble y, GLdouble z); + void (QGL_DLLEXPORT *m_glRasterPos3dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glRasterPos3f)(GLfloat x, GLfloat y, GLfloat z); + void (QGL_DLLEXPORT *m_glRasterPos3fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glRasterPos3i)(GLint x, GLint y, GLint z); + void (QGL_DLLEXPORT *m_glRasterPos3iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glRasterPos3s)(GLshort x, GLshort y, GLshort z); + void (QGL_DLLEXPORT *m_glRasterPos3sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glRasterPos4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); + void (QGL_DLLEXPORT *m_glRasterPos4dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glRasterPos4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void (QGL_DLLEXPORT *m_glRasterPos4fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glRasterPos4i)(GLint x, GLint y, GLint z, GLint w); + void (QGL_DLLEXPORT *m_glRasterPos4iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glRasterPos4s)(GLshort x, GLshort y, GLshort z, GLshort w); + void (QGL_DLLEXPORT *m_glRasterPos4sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glReadBuffer)(GLenum mode); + void (QGL_DLLEXPORT *m_glReadPixels)(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid *pixels); + void (QGL_DLLEXPORT *m_glRectd)(GLdouble x1, GLdouble y1, GLdouble x2, GLdouble y2); + void (QGL_DLLEXPORT *m_glRectdv)(const GLdouble *v1, const GLdouble *v2); + void (QGL_DLLEXPORT *m_glRectf)(GLfloat x1, GLfloat y1, GLfloat x2, GLfloat y2); + void (QGL_DLLEXPORT *m_glRectfv)(const GLfloat *v1, const GLfloat *v2); + void (QGL_DLLEXPORT *m_glRecti)(GLint x1, GLint y1, GLint x2, GLint y2); + void (QGL_DLLEXPORT *m_glRectiv)(const GLint *v1, const GLint *v2); + void (QGL_DLLEXPORT *m_glRects)(GLshort x1, GLshort y1, GLshort x2, GLshort y2); + void (QGL_DLLEXPORT *m_glRectsv)(const GLshort *v1, const GLshort *v2); + GLint (QGL_DLLEXPORT *m_glRenderMode)(GLenum mode); + void (QGL_DLLEXPORT *m_glRotated)(GLdouble anm_gle, GLdouble x, GLdouble y, GLdouble z); + void (QGL_DLLEXPORT *m_glRotatef)(GLfloat anm_gle, GLfloat x, GLfloat y, GLfloat z); + void (QGL_DLLEXPORT *m_glScaled)(GLdouble x, GLdouble y, GLdouble z); + void (QGL_DLLEXPORT *m_glScalef)(GLfloat x, GLfloat y, GLfloat z); + void (QGL_DLLEXPORT *m_glScissor)(GLint x, GLint y, GLsizei width, GLsizei height); + void (QGL_DLLEXPORT *m_glSelectBuffer)(GLsizei size, GLuint *buffer); + void (QGL_DLLEXPORT *m_glShadeModel)(GLenum mode); + void (QGL_DLLEXPORT *m_glStencilFunc)(GLenum func, GLint ref, GLuint mask); + void (QGL_DLLEXPORT *m_glStencilMask)(GLuint mask); + void (QGL_DLLEXPORT *m_glStencilOp)(GLenum fail, GLenum zfail, GLenum zpass); + void (QGL_DLLEXPORT *m_glTexCoord1d)(GLdouble s); + void (QGL_DLLEXPORT *m_glTexCoord1dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glTexCoord1f)(GLfloat s); + void (QGL_DLLEXPORT *m_glTexCoord1fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glTexCoord1i)(GLint s); + void (QGL_DLLEXPORT *m_glTexCoord1iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glTexCoord1s)(GLshort s); + void (QGL_DLLEXPORT *m_glTexCoord1sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glTexCoord2d)(GLdouble s, GLdouble t); + void (QGL_DLLEXPORT *m_glTexCoord2dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glTexCoord2f)(GLfloat s, GLfloat t); + void (QGL_DLLEXPORT *m_glTexCoord2fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glTexCoord2i)(GLint s, GLint t); + void (QGL_DLLEXPORT *m_glTexCoord2iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glTexCoord2s)(GLshort s, GLshort t); + void (QGL_DLLEXPORT *m_glTexCoord2sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glTexCoord3d)(GLdouble s, GLdouble t, GLdouble r); + void (QGL_DLLEXPORT *m_glTexCoord3dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glTexCoord3f)(GLfloat s, GLfloat t, GLfloat r); + void (QGL_DLLEXPORT *m_glTexCoord3fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glTexCoord3i)(GLint s, GLint t, GLint r); + void (QGL_DLLEXPORT *m_glTexCoord3iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glTexCoord3s)(GLshort s, GLshort t, GLshort r); + void (QGL_DLLEXPORT *m_glTexCoord3sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glTexCoord4d)(GLdouble s, GLdouble t, GLdouble r, GLdouble q); + void (QGL_DLLEXPORT *m_glTexCoord4dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glTexCoord4f)(GLfloat s, GLfloat t, GLfloat r, GLfloat q); + void (QGL_DLLEXPORT *m_glTexCoord4fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glTexCoord4i)(GLint s, GLint t, GLint r, GLint q); + void (QGL_DLLEXPORT *m_glTexCoord4iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glTexCoord4s)(GLshort s, GLshort t, GLshort r, GLshort q); + void (QGL_DLLEXPORT *m_glTexCoord4sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glTexCoordPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glTexEnvf)(GLenum target, GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glTexEnvfv)(GLenum target, GLenum pname, const GLfloat *params); + void (QGL_DLLEXPORT *m_glTexEnvi)(GLenum target, GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glTexEnviv)(GLenum target, GLenum pname, const GLint *params); + void (QGL_DLLEXPORT *m_glTexGend)(GLenum coord, GLenum pname, GLdouble param); + void (QGL_DLLEXPORT *m_glTexGendv)(GLenum coord, GLenum pname, const GLdouble *params); + void (QGL_DLLEXPORT *m_glTexGenf)(GLenum coord, GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glTexGenfv)(GLenum coord, GLenum pname, const GLfloat *params); + void (QGL_DLLEXPORT *m_glTexGeni)(GLenum coord, GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glTexGeniv)(GLenum coord, GLenum pname, const GLint *params); +#if defined(MACVERSION) && MACVERSION > 15 + //Snow Leopard 16, Leopard 15, Tiger 14, Panther 13, ... + void (QGL_DLLEXPORT *m_glTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + void (QGL_DLLEXPORT *m_glTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +#else + void (QGL_DLLEXPORT *m_glTexImage1D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + void (QGL_DLLEXPORT *m_glTexImage2D)(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *pixels); +#endif + void (QGL_DLLEXPORT *m_glTexParameterf)(GLenum target, GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glTexParameterfv)(GLenum target, GLenum pname, const GLfloat *params); + void (QGL_DLLEXPORT *m_glTexParameteri)(GLenum target, GLenum pname, GLint param); + void (QGL_DLLEXPORT *m_glTexParameteriv)(GLenum target, GLenum pname, const GLint *params); + void (QGL_DLLEXPORT *m_glTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLenum type, const GLvoid *pixels); + void (QGL_DLLEXPORT *m_glTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *pixels); + void (QGL_DLLEXPORT *m_glTranslated)(GLdouble x, GLdouble y, GLdouble z); + void (QGL_DLLEXPORT *m_glTranslatef)(GLfloat x, GLfloat y, GLfloat z); + void (QGL_DLLEXPORT *m_glVertex2d)(GLdouble x, GLdouble y); + void (QGL_DLLEXPORT *m_glVertex2dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertex2f)(GLfloat x, GLfloat y); + void (QGL_DLLEXPORT *m_glVertex2fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertex2i)(GLint x, GLint y); + void (QGL_DLLEXPORT *m_glVertex2iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glVertex2s)(GLshort x, GLshort y); + void (QGL_DLLEXPORT *m_glVertex2sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glVertex3d)(GLdouble x, GLdouble y, GLdouble z); + void (QGL_DLLEXPORT *m_glVertex3dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertex3f)(GLfloat x, GLfloat y, GLfloat z); + void (QGL_DLLEXPORT *m_glVertex3fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertex3i)(GLint x, GLint y, GLint z); + void (QGL_DLLEXPORT *m_glVertex3iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glVertex3s)(GLshort x, GLshort y, GLshort z); + void (QGL_DLLEXPORT *m_glVertex3sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glVertex4d)(GLdouble x, GLdouble y, GLdouble z, GLdouble w); + void (QGL_DLLEXPORT *m_glVertex4dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertex4f)(GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void (QGL_DLLEXPORT *m_glVertex4fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertex4i)(GLint x, GLint y, GLint z, GLint w); + void (QGL_DLLEXPORT *m_glVertex4iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glVertex4s)(GLshort x, GLshort y, GLshort z, GLshort w); + void (QGL_DLLEXPORT *m_glVertex4sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexPointer)(GLint size, GLenum type, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glViewport)(GLint x, GLint y, GLsizei width, GLsizei height); + + // GL_ARB_multitexture + bool support_ARB_multitexture; + bool ARB_multitexture() + { + return support_ARB_multitexture; + } + void (QGL_DLLEXPORT *m_glActiveTextureARB)(GLenum texture); + void (QGL_DLLEXPORT *m_glClientActiveTextureARB)(GLenum texture); + void (QGL_DLLEXPORT *m_glMultiTexCoord1dARB)(GLenum target, GLdouble s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1dvARB)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord1fARB)(GLenum target, GLfloat s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1fvARB)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord1iARB)(GLenum target, GLint s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1ivARB)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord1sARB)(GLenum target, GLshort s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1svARB)(GLenum target, const GLshort *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2dARB)(GLenum target, GLdouble s); + void (QGL_DLLEXPORT *m_glMultiTexCoord2dvARB)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2fARB)(GLenum target, GLfloat s); + void (QGL_DLLEXPORT *m_glMultiTexCoord2fvARB)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2iARB)(GLenum target, GLint s); + void (QGL_DLLEXPORT *m_glMultiTexCoord2ivARB)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2sARB)(GLenum target, GLshort s); + void (QGL_DLLEXPORT *m_glMultiTexCoord2svARB)(GLenum target, const GLshort *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3dARB)(GLenum target, GLdouble s); + void (QGL_DLLEXPORT *m_glMultiTexCoord3dvARB)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3fARB)(GLenum target, GLfloat s); + void (QGL_DLLEXPORT *m_glMultiTexCoord3fvARB)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3iARB)(GLenum target, GLint s); + void (QGL_DLLEXPORT *m_glMultiTexCoord3ivARB)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3sARB)(GLenum target, GLshort s); + void (QGL_DLLEXPORT *m_glMultiTexCoord3svARB)(GLenum target, const GLshort *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4dARB)(GLenum target, GLdouble s); + void (QGL_DLLEXPORT *m_glMultiTexCoord4dvARB)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4fARB)(GLenum target, GLfloat s); + void (QGL_DLLEXPORT *m_glMultiTexCoord4fvARB)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4iARB)(GLenum target, GLint s); + void (QGL_DLLEXPORT *m_glMultiTexCoord4ivARB)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4sARB)(GLenum target, GLshort s); + void (QGL_DLLEXPORT *m_glMultiTexCoord4svARB)(GLenum target, const GLshort *v); + + // ARB_texture_compression + bool support_ARB_texture_compression; + bool ARB_texture_compression() + { + return support_ARB_texture_compression; + } + void (QGL_DLLEXPORT *m_glCompressedTexImage3DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data); + void (QGL_DLLEXPORT *m_glCompressedTexImage2DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data); + void (QGL_DLLEXPORT *m_glCompressedTexImage1DARB)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid* data); + void (QGL_DLLEXPORT *m_glCompressedTexSubImage3DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data); + void (QGL_DLLEXPORT *m_glCompressedTexSubImage2DARB)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data); + void (QGL_DLLEXPORT *m_glCompressedTexSubImage1DARB)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid* data); + void (QGL_DLLEXPORT *m_glGetCompressedTexImageARB)(GLenum target, GLint lod, GLvoid* img); + + // EXT_texture_compression_s3tc + bool support_EXT_texture_compression_s3tc; + bool EXT_texture_compression_s3tc() + { + return support_EXT_texture_compression_s3tc; + } + + // GL 1.2 + bool support_GL_1_2; + bool GL_1_2() + { + return support_GL_1_2; + } + void (QGL_DLLEXPORT *m_glCopyTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height); + void (QGL_DLLEXPORT *m_glDrawRangeElements)(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid *indices); + void (QGL_DLLEXPORT *m_glTexImage3D)(GLenum target, GLint level, GLint internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid *pixels); + void (QGL_DLLEXPORT *m_glTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid *pixels); + + // GL 1.3 + bool support_GL_1_3; + bool GL_1_3() + { + return support_GL_1_3; + } + void (QGL_DLLEXPORT *m_glActiveTexture)(GLenum texture); + void (QGL_DLLEXPORT *m_glClientActiveTexture)(GLenum texture); + void (QGL_DLLEXPORT *m_glCompressedTexImage1D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLint border, GLsizei imageSize, const GLvoid *data); + void (QGL_DLLEXPORT *m_glCompressedTexImage2D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid *data); + void (QGL_DLLEXPORT *m_glCompressedTexImage3D)(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid *data); + void (QGL_DLLEXPORT *m_glCompressedTexSubImage1D)(GLenum target, GLint level, GLint xoffset, GLsizei width, GLenum format, GLsizei imageSize, const GLvoid *data); + void (QGL_DLLEXPORT *m_glCompressedTexSubImage2D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid *data); + void (QGL_DLLEXPORT *m_glCompressedTexSubImage3D)(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid *data); + void (QGL_DLLEXPORT *m_glGetCompressedTexImage)(GLenum target, GLint lod, GLvoid *img); + void (QGL_DLLEXPORT *m_glLoadTransposeMatrixd)(const GLdouble m[16]); + void (QGL_DLLEXPORT *m_glLoadTransposeMatrixf)(const GLfloat m[16]); + void (QGL_DLLEXPORT *m_glMultTransposeMatrixd)(const GLdouble m[16]); + void (QGL_DLLEXPORT *m_glMultTransposeMatrixf)(const GLfloat m[16]); + void (QGL_DLLEXPORT *m_glMultiTexCoord1d)(GLenum target, GLdouble s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1dv)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord1f)(GLenum target, GLfloat s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1fv)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord1i)(GLenum target, GLint s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1iv)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord1s)(GLenum target, GLshort s); + void (QGL_DLLEXPORT *m_glMultiTexCoord1sv)(GLenum target, const GLshort *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2d)(GLenum target, GLdouble s, GLdouble t); + void (QGL_DLLEXPORT *m_glMultiTexCoord2dv)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2f)(GLenum target, GLfloat s, GLfloat t); + void (QGL_DLLEXPORT *m_glMultiTexCoord2fv)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2i)(GLenum target, GLint s, GLint t); + void (QGL_DLLEXPORT *m_glMultiTexCoord2iv)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord2s)(GLenum target, GLshort s, GLshort t); + void (QGL_DLLEXPORT *m_glMultiTexCoord2sv)(GLenum target, const GLshort *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3d)(GLenum target, GLdouble s, GLdouble t, GLdouble r); + void (QGL_DLLEXPORT *m_glMultiTexCoord3dv)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3f)(GLenum target, GLfloat s, GLfloat t, GLfloat r); + void (QGL_DLLEXPORT *m_glMultiTexCoord3fv)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3i)(GLenum target, GLint s, GLint t, GLint r); + void (QGL_DLLEXPORT *m_glMultiTexCoord3iv)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord3s)(GLenum target, GLshort s, GLshort t, GLshort r); + void (QGL_DLLEXPORT *m_glMultiTexCoord3sv)(GLenum target, const GLshort *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4d)(GLenum target, GLdouble s, GLdouble t, GLdouble r, GLdouble q); + void (QGL_DLLEXPORT *m_glMultiTexCoord4dv)(GLenum target, const GLdouble *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4f)(GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q); + void (QGL_DLLEXPORT *m_glMultiTexCoord4fv)(GLenum target, const GLfloat *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4i)(GLenum target, GLint s, GLint t, GLint r, GLint q); + void (QGL_DLLEXPORT *m_glMultiTexCoord4iv)(GLenum target, const GLint *v); + void (QGL_DLLEXPORT *m_glMultiTexCoord4s)(GLenum target, GLshort s, GLshort t, GLshort r, GLshort q); + void (QGL_DLLEXPORT *m_glMultiTexCoord4sv)(GLenum target, const GLshort *v); + void (QGL_DLLEXPORT *m_glSampleCoverage)(GLclampf value, GLboolean invert); + + // GL 1.4 + bool support_GL_1_4; + bool GL_1_4() + { + return support_GL_1_4; + } + void (QGL_DLLEXPORT *m_glBlendColor)(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); + void (QGL_DLLEXPORT *m_glBlendEquation)(GLenum mode); + void (QGL_DLLEXPORT *m_glBlendFuncSeparate)(GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha); + void (QGL_DLLEXPORT *m_glFogCoordPointer)(GLenum type, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glFogCoordd)(GLdouble coord); + void (QGL_DLLEXPORT *m_glFogCoorddv)(const GLdouble *coord); + void (QGL_DLLEXPORT *m_glFogCoordf)(GLfloat coord); + void (QGL_DLLEXPORT *m_glFogCoordfv)(const GLfloat *coord); + void (QGL_DLLEXPORT *m_glMultiDrawArrays)(GLenum mode, GLint *first, GLsizei *count, GLsizei primcount); + void (QGL_DLLEXPORT *m_glMultiDrawElements)(GLenum mode, GLsizei *count, GLenum type, const GLvoid **indices, GLsizei primcount); + void (QGL_DLLEXPORT *m_glPointParameterf)(GLenum pname, GLfloat param); + void (QGL_DLLEXPORT *m_glPointParameterfv)(GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glSecondaryColor3b)(GLbyte red, GLbyte green, GLbyte blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3bv)(const GLbyte *v); + void (QGL_DLLEXPORT *m_glSecondaryColor3d)(GLdouble red, GLdouble green, GLdouble blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3dv)(const GLdouble *v); + void (QGL_DLLEXPORT *m_glSecondaryColor3f)(GLfloat red, GLfloat green, GLfloat blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3fv)(const GLfloat *v); + void (QGL_DLLEXPORT *m_glSecondaryColor3i)(GLint red, GLint green, GLint blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3iv)(const GLint *v); + void (QGL_DLLEXPORT *m_glSecondaryColor3s)(GLshort red, GLshort green, GLshort blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3sv)(const GLshort *v); + void (QGL_DLLEXPORT *m_glSecondaryColor3ub)(GLubyte red, GLubyte green, GLubyte blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3ubv)(const GLubyte *v); + void (QGL_DLLEXPORT *m_glSecondaryColor3ui)(GLuint red, GLuint green, GLuint blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3uiv)(const GLuint *v); + void (QGL_DLLEXPORT *m_glSecondaryColor3us)(GLushort red, GLushort green, GLushort blue); + void (QGL_DLLEXPORT *m_glSecondaryColor3usv)(const GLushort *v); + void (QGL_DLLEXPORT *m_glSecondaryColorPointer)(GLint size, GLenum type, GLsizei stride, GLvoid *pointer); + void (QGL_DLLEXPORT *m_glWindowPos2d)(GLdouble x, GLdouble y); + void (QGL_DLLEXPORT *m_glWindowPos2dv)(const GLdouble *p); + void (QGL_DLLEXPORT *m_glWindowPos2f)(GLfloat x, GLfloat y); + void (QGL_DLLEXPORT *m_glWindowPos2fv)(const GLfloat *p); + void (QGL_DLLEXPORT *m_glWindowPos2i)(GLint x, GLint y); + void (QGL_DLLEXPORT *m_glWindowPos2iv)(const GLint *p); + void (QGL_DLLEXPORT *m_glWindowPos2s)(GLshort x, GLshort y); + void (QGL_DLLEXPORT *m_glWindowPos2sv)(const GLshort *p); + void (QGL_DLLEXPORT *m_glWindowPos3d)(GLdouble x, GLdouble y, GLdouble z); + void (QGL_DLLEXPORT *m_glWindowPos3dv)(const GLdouble *p); + void (QGL_DLLEXPORT *m_glWindowPos3f)(GLfloat x, GLfloat y, GLfloat z); + void (QGL_DLLEXPORT *m_glWindowPos3fv)(const GLfloat *p); + void (QGL_DLLEXPORT *m_glWindowPos3i)(GLint x, GLint y, GLint z); + void (QGL_DLLEXPORT *m_glWindowPos3iv)(const GLint *p); + void (QGL_DLLEXPORT *m_glWindowPos3s)(GLshort x, GLshort y, GLshort z); + void (QGL_DLLEXPORT *m_glWindowPos3sv)(const GLshort *p); + + // GL 1.5 + bool support_GL_1_5; + bool GL_1_5() + { + return support_GL_1_5; + } + void (QGL_DLLEXPORT *m_glBeginQuery)(GLenum target, GLuint id); + void (QGL_DLLEXPORT *m_glBindBuffer)(GLenum target, GLuint buffer); + void (QGL_DLLEXPORT *m_glBufferData)(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage); + void (QGL_DLLEXPORT *m_glBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data); + void (QGL_DLLEXPORT *m_glDeleteBuffers)(GLsizei n, const GLuint* buffers); + void (QGL_DLLEXPORT *m_glDeleteQueries)(GLsizei n, const GLuint* ids); + void (QGL_DLLEXPORT *m_glEndQuery)(GLenum target); + void (QGL_DLLEXPORT *m_glGenBuffers)(GLsizei n, GLuint* buffers); + void (QGL_DLLEXPORT *m_glGenQueries)(GLsizei n, GLuint* ids); + void (QGL_DLLEXPORT *m_glGetBufferParameteriv)(GLenum target, GLenum pname, GLint* params); + void (QGL_DLLEXPORT *m_glGetBufferPointerv)(GLenum target, GLenum pname, GLvoid** params); + void (QGL_DLLEXPORT *m_glGetBufferSubData)(GLenum target, GLintptr offset, GLsizeiptr size, GLvoid* data); + void (QGL_DLLEXPORT *m_glGetQueryObjectiv)(GLuint id, GLenum pname, GLint* params); + void (QGL_DLLEXPORT *m_glGetQueryObjectuiv)(GLuint id, GLenum pname, GLuint* params); + void (QGL_DLLEXPORT *m_glGetQueryiv)(GLenum target, GLenum pname, GLint params); + GLboolean (QGL_DLLEXPORT *m_glIsBuffer)(GLuint buffer); + GLboolean (QGL_DLLEXPORT *m_glIsQuery)(GLuint id); + GLvoid* (QGL_DLLEXPORT *m_glMapBuffer)(GLenum target, GLenum access); + GLboolean (QGL_DLLEXPORT *m_glUnmapBuffer)(GLenum target); + + // GL_ARB_vertex_program + bool support_ARB_vertex_program; + bool ARB_vertex_program() + { + return support_ARB_vertex_program; + } + void (QGL_DLLEXPORT *m_glVertexAttrib1sARB)(GLuint index, GLshort x); + void (QGL_DLLEXPORT *m_glVertexAttrib1fARB)(GLuint index, GLfloat x); + void (QGL_DLLEXPORT *m_glVertexAttrib1dARB)(GLuint index, GLdouble x); + void (QGL_DLLEXPORT *m_glVertexAttrib2sARB)(GLuint index, GLshort x, GLshort y); + void (QGL_DLLEXPORT *m_glVertexAttrib2fARB)(GLuint index, GLfloat x, GLfloat y); + void (QGL_DLLEXPORT *m_glVertexAttrib2dARB)(GLuint index, GLdouble x, GLdouble y); + void (QGL_DLLEXPORT *m_glVertexAttrib3sARB)(GLuint index, GLshort x, GLshort y, GLshort z); + void (QGL_DLLEXPORT *m_glVertexAttrib3fARB)(GLuint index, GLfloat x, GLfloat y, GLfloat z); + void (QGL_DLLEXPORT *m_glVertexAttrib3dARB)(GLuint index, GLdouble x, GLdouble y, GLdouble z); + void (QGL_DLLEXPORT *m_glVertexAttrib4sARB)(GLuint index, GLshort x, GLshort y, GLshort z, GLshort w); + void (QGL_DLLEXPORT *m_glVertexAttrib4fARB)(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void (QGL_DLLEXPORT *m_glVertexAttrib4dARB)(GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); + void (QGL_DLLEXPORT *m_glVertexAttrib4NubARB)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); + void (QGL_DLLEXPORT *m_glVertexAttrib1svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib1fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib1dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib2svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib2fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib2dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib3svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib3fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib3dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4bvARB)(GLuint index, const GLbyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4ivARB)(GLuint index, const GLint *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4ubvARB)(GLuint index, const GLubyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4usvARB)(GLuint index, const GLushort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4uivARB)(GLuint index, const GLuint *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NbvARB)(GLuint index, const GLbyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NsvARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NivARB)(GLuint index, const GLint *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NubvARB)(GLuint index, const GLubyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NusvARB)(GLuint index, const GLushort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NuivARB)(GLuint index, const GLuint *v); + void (QGL_DLLEXPORT *m_glVertexAttribPointerARB)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB)(GLuint index); + void (QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB)(GLuint index); + void (QGL_DLLEXPORT *m_glProgramStringARB)(GLenum target, GLenum format, GLsizei len, const GLvoid *string); + void (QGL_DLLEXPORT *m_glBindProgramARB)(GLenum target, GLuint program); + void (QGL_DLLEXPORT *m_glDeleteProgramsARB)(GLsizei n, const GLuint *programs); + void (QGL_DLLEXPORT *m_glGenProgramsARB)(GLsizei n, GLuint *programs); + void (QGL_DLLEXPORT *m_glProgramEnvParameter4dARB)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); + void (QGL_DLLEXPORT *m_glProgramEnvParameter4dvARB)(GLenum target, GLuint index, const GLdouble *params); + void (QGL_DLLEXPORT *m_glProgramEnvParameter4fARB)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void (QGL_DLLEXPORT *m_glProgramEnvParameter4fvARB)(GLenum target, GLuint index, const GLfloat *params); + void (QGL_DLLEXPORT *m_glProgramLocalParameter4dARB)(GLenum target, GLuint index, GLdouble x, GLdouble y, GLdouble z, GLdouble w); + void (QGL_DLLEXPORT *m_glProgramLocalParameter4dvARB)(GLenum target, GLuint index, const GLdouble *params); + void (QGL_DLLEXPORT *m_glProgramLocalParameter4fARB)(GLenum target, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void (QGL_DLLEXPORT *m_glProgramLocalParameter4fvARB)(GLenum target, GLuint index, const GLfloat *params); + void (QGL_DLLEXPORT *m_glGetProgramEnvParameterdvARB)(GLenum target, GLuint index, GLdouble *params); + void (QGL_DLLEXPORT *m_glGetProgramEnvParameterfvARB)(GLenum target, GLuint index, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetProgramLocalParameterdvARB)(GLenum target, GLuint index, GLdouble *params); + void (QGL_DLLEXPORT *m_glGetProgramLocalParameterfvARB)(GLenum target, GLuint index, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetProgramivARB)(GLenum target, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetProgramStringARB)(GLenum target, GLenum pname, GLvoid *string); + void (QGL_DLLEXPORT *m_glGetVertexAttribdvARB)(GLuint index, GLenum pname, GLdouble *params); + void (QGL_DLLEXPORT *m_glGetVertexAttribfvARB)(GLuint index, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetVertexAttribivARB)(GLuint index, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetVertexAttribPointervARB)(GLuint index, GLenum pname, GLvoid **pointer); + GLboolean (QGL_DLLEXPORT *m_glIsProgramARB)(GLuint program); + + // GL_ARB_fragment_program + bool support_ARB_fragment_program; + bool ARB_fragment_program() + { + return support_ARB_fragment_program; + } + + // GL_ARB_shader_objects + bool support_ARB_shader_objects; + bool ARB_shader_objects() + { + return support_ARB_shader_objects; + } + void (QGL_DLLEXPORT *m_glDeleteObjectARB)(GLhandleARB obj); + GLhandleARB (QGL_DLLEXPORT *m_glGetHandleARB)(GLenum pname); + void (QGL_DLLEXPORT *m_glDetachObjectARB)(GLhandleARB containerObj, GLhandleARB attachedObj); + GLhandleARB (QGL_DLLEXPORT *m_glCreateShaderObjectARB)(GLenum shaderType); + void (QGL_DLLEXPORT *m_glShaderSourceARB)(GLhandleARB shaderObj, GLsizei count, const GLcharARB **string, const GLint *length); + void (QGL_DLLEXPORT *m_glCompileShaderARB)(GLhandleARB shaderObj); + GLhandleARB (QGL_DLLEXPORT *m_glCreateProgramObjectARB)(void); + void (QGL_DLLEXPORT *m_glAttachObjectARB)(GLhandleARB containerObj, GLhandleARB obj); + void (QGL_DLLEXPORT *m_glLinkProgramARB)(GLhandleARB programObj); + void (QGL_DLLEXPORT *m_glUseProgramObjectARB)(GLhandleARB programObj); + void (QGL_DLLEXPORT *m_glValidateProgramARB)(GLhandleARB programObj); + void (QGL_DLLEXPORT *m_glUniform1fARB)(GLint location, GLfloat v0); + void (QGL_DLLEXPORT *m_glUniform2fARB)(GLint location, GLfloat v0, GLfloat v1); + void (QGL_DLLEXPORT *m_glUniform3fARB)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2); + void (QGL_DLLEXPORT *m_glUniform4fARB)(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); + void (QGL_DLLEXPORT *m_glUniform1iARB)(GLint location, GLint v0); + void (QGL_DLLEXPORT *m_glUniform2iARB)(GLint location, GLint v0, GLint v1); + void (QGL_DLLEXPORT *m_glUniform3iARB)(GLint location, GLint v0, GLint v1, GLint v2); + void (QGL_DLLEXPORT *m_glUniform4iARB)(GLint location, GLint v0, GLint v1, GLint v2, GLint v3); + void (QGL_DLLEXPORT *m_glUniform1fvARB)(GLint location, GLsizei count, const GLfloat *value); + void (QGL_DLLEXPORT *m_glUniform2fvARB)(GLint location, GLsizei count, const GLfloat *value); + void (QGL_DLLEXPORT *m_glUniform3fvARB)(GLint location, GLsizei count, const GLfloat *value); + void (QGL_DLLEXPORT *m_glUniform4fvARB)(GLint location, GLsizei count, const GLfloat *value); + void (QGL_DLLEXPORT *m_glUniform1ivARB)(GLint location, GLsizei count, const GLint *value); + void (QGL_DLLEXPORT *m_glUniform2ivARB)(GLint location, GLsizei count, const GLint *value); + void (QGL_DLLEXPORT *m_glUniform3ivARB)(GLint location, GLsizei count, const GLint *value); + void (QGL_DLLEXPORT *m_glUniform4ivARB)(GLint location, GLsizei count, const GLint *value); + void (QGL_DLLEXPORT *m_glUniformMatrix2fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); + void (QGL_DLLEXPORT *m_glUniformMatrix3fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); + void (QGL_DLLEXPORT *m_glUniformMatrix4fvARB)(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); + void (QGL_DLLEXPORT *m_glGetObjectParameterfvARB)(GLhandleARB obj, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetObjectParameterivARB)(GLhandleARB obj, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetInfoLogARB)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *infoLog); + void (QGL_DLLEXPORT *m_glGetAttachedObjectsARB)(GLhandleARB containerObj, GLsizei maxCount, GLsizei *count, GLhandleARB *obj); + GLint (QGL_DLLEXPORT *m_glGetUniformLocationARB)(GLhandleARB programObj, const GLcharARB *name); + void (QGL_DLLEXPORT *m_glGetActiveUniformARB)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); + void (QGL_DLLEXPORT *m_glGetUniformfvARB)(GLhandleARB programObj, GLint location, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetUniformivARB)(GLhandleARB programObj, GLint location, GLint *params); + void (QGL_DLLEXPORT *m_glGetShaderSourceARB)(GLhandleARB obj, GLsizei maxLength, GLsizei *length, GLcharARB *source); + + // GL_ARB_vertex_shader + bool support_ARB_vertex_shader; + bool ARB_vertex_shader() + { + return support_ARB_vertex_shader; + } +#if 0 + void (QGL_DLLEXPORT *m_glVertexAttrib1fARB)(GLuint index, GLfloat v0); + void (QGL_DLLEXPORT *m_glVertexAttrib1sARB)(GLuint index, GLshort v0); + void (QGL_DLLEXPORT *m_glVertexAttrib1dARB)(GLuint index, GLdouble v0); + void (QGL_DLLEXPORT *m_glVertexAttrib2fARB)(GLuint index, GLfloat v0, GLfloat v1); + void (QGL_DLLEXPORT *m_glVertexAttrib2sARB)(GLuint index, GLshort v0, GLshort v1); + void (QGL_DLLEXPORT *m_glVertexAttrib2dARB)(GLuint index, GLdouble v0, GLdouble v1); + void (QGL_DLLEXPORT *m_glVertexAttrib3fARB)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2); + void (QGL_DLLEXPORT *m_glVertexAttrib3sARB)(GLuint index, GLshort v0, GLshort v1, GLshort v2); + void (QGL_DLLEXPORT *m_glVertexAttrib3dARB)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2); + void (QGL_DLLEXPORT *m_glVertexAttrib4fARB)(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); + void (QGL_DLLEXPORT *m_glVertexAttrib4sARB)(GLuint index, GLshort v0, GLshort v1, GLshort v2, GLshort v3); + void (QGL_DLLEXPORT *m_glVertexAttrib4dARB)(GLuint index, GLdouble v0, GLdouble v1, GLdouble v2, GLdouble v3); + void (QGL_DLLEXPORT *m_glVertexAttrib4NubARB)(GLuint index, GLubyte x, GLubyte y, GLubyte z, GLubyte w); + void (QGL_DLLEXPORT *m_glVertexAttrib1fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib1svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib1dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib2fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib2svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib2dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib3fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib3svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib3dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4fvARB)(GLuint index, const GLfloat *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4svARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4dvARB)(GLuint index, const GLdouble *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4ivARB)(GLuint index, const GLint *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4bvARB)(GLuint index, const GLbyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4ubvARB)(GLuint index, const GLubyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4usvARB)(GLuint index, const GLushort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4uivARB)(GLuint index, const GLuint *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NbvARB)(GLuint index, const GLbyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NsvARB)(GLuint index, const GLshort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NivARB)(GLuint index, const GLint *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NubvARB)(GLuint index, const GLubyte *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NusvARB)(GLuint index, const GLushort *v); + void (QGL_DLLEXPORT *m_glVertexAttrib4NuivARB)(GLuint index, const GLuint *v); + void (QGL_DLLEXPORT *m_glVertexAttribPointerARB)(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid *pointer); + void (QGL_DLLEXPORT *m_glEnableVertexAttribArrayARB)(GLuint index); + void (QGL_DLLEXPORT *m_glDisableVertexAttribArrayARB)(GLuint index); +#endif + void (QGL_DLLEXPORT *m_glBindAttribLocationARB)(GLhandleARB programObj, GLuint index, const GLcharARB *name); + void (QGL_DLLEXPORT *m_glGetActiveAttribARB)(GLhandleARB programObj, GLuint index, GLsizei maxLength, GLsizei *length, GLint *size, GLenum *type, GLcharARB *name); + GLint (QGL_DLLEXPORT *m_glGetAttribLocationARB)(GLhandleARB programObj, const GLcharARB *name); +#if 0 + void (QGL_DLLEXPORT *m_glGetVertexAttribdvARB)(GLuint index, GLenum pname, GLdouble *params); + void (QGL_DLLEXPORT *m_glGetVertexAttribfvARB)(GLuint index, GLenum pname, GLfloat *params); + void (QGL_DLLEXPORT *m_glGetVertexAttribivARB)(GLuint index, GLenum pname, GLint *params); + void (QGL_DLLEXPORT *m_glGetVertexAttribPointervARB)(GLuint index, GLenum pname, GLvoid **pointer); +#endif + + // ARB_fragment_shader + bool support_ARB_fragment_shader; + bool ARB_fragment_shader() + { + return support_ARB_fragment_shader; + } + + // ARB_shading_language_100 + bool support_ARB_shading_language_100; + bool ARB_shading_language_100() + { + return support_ARB_shading_language_100; + } + + // GL_NV_vertex_program2 + bool support_NV_vertex_program2; + bool NV_vertex_program2() + { + return support_NV_vertex_program2; + } + GLboolean (QGL_DLLEXPORT* m_glAreProgramsResidentNV)(GLsizei, const GLuint *, GLboolean *); + void (QGL_DLLEXPORT* m_glBindProgramNV)(GLenum, GLuint); + void (QGL_DLLEXPORT* m_glDeleteProgramsNV)(GLsizei, const GLuint *); + void (QGL_DLLEXPORT* m_glExecuteProgramNV)(GLenum, GLuint, const GLfloat *); + void (QGL_DLLEXPORT* m_glGenProgramsNV)(GLsizei, GLuint *); + void (QGL_DLLEXPORT* m_glGetProgramParameterdvNV)(GLenum, GLuint, GLenum, GLdouble *); + void (QGL_DLLEXPORT* m_glGetProgramParameterfvNV)(GLenum, GLuint, GLenum, GLfloat *); + void (QGL_DLLEXPORT* m_glGetProgramivNV)(GLuint, GLenum, GLint *); + void (QGL_DLLEXPORT* m_glGetProgramStringNV)(GLuint, GLenum, GLubyte *); + void (QGL_DLLEXPORT* m_glGetTrackMatrixivNV)(GLenum, GLuint, GLenum, GLint *); + void (QGL_DLLEXPORT* m_glGetVertexAttribdvNV)(GLuint, GLenum, GLdouble *); + void (QGL_DLLEXPORT* m_glGetVertexAttribfvNV)(GLuint, GLenum, GLfloat *); + void (QGL_DLLEXPORT* m_glGetVertexAttribivNV)(GLuint, GLenum, GLint *); + void (QGL_DLLEXPORT* m_glGetVertexAttribPointervNV)(GLuint, GLenum, GLvoid* *); + GLboolean (QGL_DLLEXPORT* m_glIsProgramNV)(GLuint); + void (QGL_DLLEXPORT* m_glLoadProgramNV)(GLenum, GLuint, GLsizei, const GLubyte *); + void (QGL_DLLEXPORT* m_glProgramParameter4fNV)(GLenum, GLuint, GLfloat, GLfloat, GLfloat, GLfloat); + void (QGL_DLLEXPORT* m_glProgramParameter4fvNV)(GLenum, GLuint, const GLfloat *); + void (QGL_DLLEXPORT* m_glProgramParameters4fvNV)(GLenum, GLuint, GLuint, const GLfloat *); + void (QGL_DLLEXPORT* m_glRequestResidentProgramsNV)(GLsizei, const GLuint *); + void (QGL_DLLEXPORT* m_glTrackMatrixNV)(GLenum, GLuint, GLenum, GLenum); + void (QGL_DLLEXPORT* m_glVertexAttribPointerNV)(GLuint, GLint, GLenum, GLsizei, const GLvoid *); + void (QGL_DLLEXPORT* m_glVertexAttrib1fNV)(GLuint, GLfloat); + void (QGL_DLLEXPORT* m_glVertexAttrib1fvNV)(GLuint, const GLfloat *); + void (QGL_DLLEXPORT* m_glVertexAttrib2fNV)(GLuint, GLfloat, GLfloat); + void (QGL_DLLEXPORT* m_glVertexAttrib2fvNV)(GLuint, const GLfloat *); + void (QGL_DLLEXPORT* m_glVertexAttrib3fNV)(GLuint, GLfloat, GLfloat, GLfloat); + void (QGL_DLLEXPORT* m_glVertexAttrib3fvNV)(GLuint, const GLfloat *); + void (QGL_DLLEXPORT* m_glVertexAttrib4fNV)(GLuint, GLfloat, GLfloat, GLfloat, GLfloat); + void (QGL_DLLEXPORT* m_glVertexAttrib4fvNV)(GLuint, const GLfloat *); + void (QGL_DLLEXPORT* m_glVertexAttribs1fvNV)(GLuint, GLsizei, const GLfloat *); + void (QGL_DLLEXPORT* m_glVertexAttribs2fvNV)(GLuint, GLsizei, const GLfloat *); + void (QGL_DLLEXPORT* m_glVertexAttribs3fvNV)(GLuint, GLsizei, const GLfloat *); + void (QGL_DLLEXPORT* m_glVertexAttribs4fvNV)(GLuint, GLsizei, const GLfloat *); + + // GL_NV_fragment_program + bool support_NV_fragment_program; + bool NV_fragment_program() + { + return support_NV_fragment_program; + } + void (QGL_DLLEXPORT* m_glProgramNamedParameter4fNV)(GLuint, GLsizei, const GLubyte *, GLfloat, GLfloat, GLfloat, GLfloat); + void (QGL_DLLEXPORT* m_glProgramNamedParameter4fvNV)(GLuint, GLsizei, const GLubyte *, const GLfloat *); + void (QGL_DLLEXPORT* m_glGetProgramNamedParameterfvNV)(GLuint, GLsizei, const GLubyte *, GLfloat *); +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalOpenGLModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalOpenGLModuleRef; + +inline OpenGLBinding& GlobalOpenGL() +{ + return GlobalOpenGLModule::getTable(); +} + +#if defined(_DEBUG) +#define GlobalOpenGL_debugAssertNoErrors() GlobalOpenGL().assertNoErrors(__FILE__, __LINE__) +#else +#define GlobalOpenGL_debugAssertNoErrors() +#endif + + +#endif diff --git a/misc/mediasource/netradiant-src/include/iglrender.cpp b/misc/mediasource/netradiant-src/include/iglrender.cpp new file mode 100644 index 00000000..26d66ae0 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iglrender.cpp @@ -0,0 +1,3 @@ + +#include "iglrender.h" + diff --git a/misc/mediasource/netradiant-src/include/iglrender.h b/misc/mediasource/netradiant-src/include/iglrender.h new file mode 100644 index 00000000..76216026 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iglrender.h @@ -0,0 +1,130 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IGLRENDER_H) +#define INCLUDED_IGLRENDER_H + +#include "igl.h" +#include "generic/vector.h" +class AABB; +class Matrix4; + + +class GLProgram +{ +public: + virtual void enable() = 0; + virtual void disable() = 0; + virtual void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) = 0; +}; + +class OpenGLFogState +{ +public: + OpenGLFogState() : mode(GL_EXP), density(0), start(0), end(0), index(0), colour(1, 1, 1, 1) + { + } + GLenum mode; + GLfloat density; + GLfloat start; + GLfloat end; + GLint index; + Vector4 colour; +}; + +//! A collection of opengl state information. +class OpenGLState +{ +public: + enum ESort + { + eSortFirst = 0, + eSortOpaque = 1, + eSortMultiFirst = 2, + eSortMultiLast = 1023, + eSortOverbrighten = 1024, + eSortFullbright = 1025, + eSortHighlight = 1026, + eSortTranslucent = 1027, + eSortOverlayFirst = 1028, + eSortOverlayLast = 2047, + eSortControlFirst = 2048, + eSortControlLast = 3071, + eSortGUI0 = 3072, + eSortGUI1 = 3073, + eSortLast = 4096, + }; + + unsigned int m_state; + std::size_t m_sort; + GLint m_texture; + GLint m_texture1; + GLint m_texture2; + GLint m_texture3; + GLint m_texture4; + GLint m_texture5; + GLint m_texture6; + GLint m_texture7; + Vector4 m_colour; + GLenum m_blend_src, m_blend_dst; + GLenum m_depthfunc; + GLenum m_alphafunc; + GLfloat m_alpharef; + GLfloat m_linewidth; + GLfloat m_pointsize; + GLint m_linestipple_factor; + GLushort m_linestipple_pattern; + OpenGLFogState m_fog; + GLProgram* m_program; + + OpenGLState() : m_program(0) + { + } +}; + +class OpenGLStateLibrary +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "openglshaderlibrary"); + + virtual void getDefaultState(OpenGLState& state) const = 0; + + virtual void insert(const char* name, const OpenGLState& state) = 0; + virtual void erase(const char* name) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalOpenGLStateLibraryModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalOpenGLStateLibraryModuleRef; + +inline OpenGLStateLibrary& GlobalOpenGLStateLibrary() +{ + return GlobalOpenGLStateLibraryModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/igtkgl.cpp b/misc/mediasource/netradiant-src/include/igtkgl.cpp new file mode 100644 index 00000000..1180d547 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/igtkgl.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "igtkgl.h" + diff --git a/misc/mediasource/netradiant-src/include/igtkgl.h b/misc/mediasource/netradiant-src/include/igtkgl.h new file mode 100644 index 00000000..6a0a631f --- /dev/null +++ b/misc/mediasource/netradiant-src/include/igtkgl.h @@ -0,0 +1,43 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IGTKGL_H) +#define INCLUDED_IGTKGL_H + +#include "generic/constant.h" + +typedef struct _GtkWidget GtkWidget; +typedef int gint; +typedef gint gboolean; + +struct _QERGtkGLTable +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "gtkgl"); + + GtkWidget* (*glwidget_new)(gboolean zbufffer); + void (*glwidget_swap_buffers)(GtkWidget* widget); + gboolean(*glwidget_make_current)(GtkWidget* widget); + void (*glwidget_destroy_context)(GtkWidget* widget); + void (*glwidget_create_context)(GtkWidget* widget); +}; + +#endif diff --git a/misc/mediasource/netradiant-src/include/iimage.cpp b/misc/mediasource/netradiant-src/include/iimage.cpp new file mode 100644 index 00000000..a95ab6d3 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iimage.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "iimage.h" + diff --git a/misc/mediasource/netradiant-src/include/iimage.h b/misc/mediasource/netradiant-src/include/iimage.h new file mode 100644 index 00000000..f6020bd8 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iimage.h @@ -0,0 +1,75 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IIMAGE_H) +#define INCLUDED_IIMAGE_H + +#include "generic/constant.h" + +typedef unsigned char byte; + +class Image +{ +public: + virtual void release() = 0; + virtual byte* getRGBAPixels() const = 0; + virtual unsigned int getWidth() const = 0; + virtual unsigned int getHeight() const = 0; + + virtual int getSurfaceFlags() const + { + return 0; + } + virtual int getContentFlags() const + { + return 0; + } + virtual int getValue() const + { + return 0; + } +}; + +class ArchiveFile; + +struct _QERPlugImageTable +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "image"); + + /// Read an image from the file. + /// Returns 0 if the image could not be read. + Image* (*loadImage)(ArchiveFile& file); +}; + +template +class ModuleRef; +typedef ModuleRef<_QERPlugImageTable> ImageModuleRef; + +template +class Modules; +typedef Modules<_QERPlugImageTable> ImageModules; + +template +class ModulesRef; +typedef ModulesRef<_QERPlugImageTable> ImageModulesRef; + +#endif // _IIMAGE_H diff --git a/misc/mediasource/netradiant-src/include/imap.cpp b/misc/mediasource/netradiant-src/include/imap.cpp new file mode 100644 index 00000000..0b363b5e --- /dev/null +++ b/misc/mediasource/netradiant-src/include/imap.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "imap.h" + diff --git a/misc/mediasource/netradiant-src/include/imap.h b/misc/mediasource/netradiant-src/include/imap.h new file mode 100644 index 00000000..c97a2ff2 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/imap.h @@ -0,0 +1,82 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IMAP_H) +#define INCLUDED_IMAP_H + +#include "generic/constant.h" + +class Tokeniser; +class TokenWriter; + +/// \brief A node whose state can be imported from a token stream. +class MapImporter +{ +public: + STRING_CONSTANT(Name, "MapImporter"); + + virtual bool importTokens(Tokeniser& tokeniser) = 0; +}; + +/// \brief A node whose state can be exported to a token stream. +class MapExporter +{ +public: + STRING_CONSTANT(Name, "MapExporter"); + + virtual void exportTokens(TokenWriter& writer) const = 0; +}; + +#include "iscenegraph.h" + +class EntityCreator; + +class TextInputStream; +class TextOutputStream; + + +typedef void(*GraphTraversalFunc)(scene::Node& root, const scene::Traversable::Walker& walker); + +/// \brief A module that reads and writes a map in a specific format. +class MapFormat +{ +public: + INTEGER_CONSTANT(Version, 2); + STRING_CONSTANT(Name, "map"); + mutable bool wrongFormat; + + /// \brief Read a map graph into \p root from \p outputStream, using \p entityTable to create entities. + virtual void readGraph(scene::Node& root, TextInputStream& inputStream, EntityCreator& entityTable) const = 0; + /// \brief Write the map graph obtained by applying \p traverse to \p root into \p outputStream. + virtual void writeGraph(scene::Node& root, GraphTraversalFunc traverse, TextOutputStream& outputStream) const = 0; +}; + + +template +class Modules; +typedef Modules MapModules; + +template +class ModulesRef; +typedef ModulesRef MapModulesRef; + + +#endif diff --git a/misc/mediasource/netradiant-src/include/imodel.cpp b/misc/mediasource/netradiant-src/include/imodel.cpp new file mode 100644 index 00000000..081dccac --- /dev/null +++ b/misc/mediasource/netradiant-src/include/imodel.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "imodel.h" + diff --git a/misc/mediasource/netradiant-src/include/imodel.h b/misc/mediasource/netradiant-src/include/imodel.h new file mode 100644 index 00000000..aa040d63 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/imodel.h @@ -0,0 +1,50 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IMODEL_H) +#define INCLUDED_IMODEL_H + +#include "generic/constant.h" + +namespace scene +{ + class Node; +} + +class ArchiveFile; + +class ModelLoader +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "model"); + virtual scene::Node& loadModel(ArchiveFile& file) = 0; +}; + +template +class Modules; +typedef Modules ModelModules; + +template +class ModulesRef; +typedef ModulesRef ModelModulesRef; + +#endif /* _IMODEL_H_ */ diff --git a/misc/mediasource/netradiant-src/include/ipatch.cpp b/misc/mediasource/netradiant-src/include/ipatch.cpp new file mode 100644 index 00000000..940a1bed --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ipatch.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "ipatch.h" + diff --git a/misc/mediasource/netradiant-src/include/ipatch.h b/misc/mediasource/netradiant-src/include/ipatch.h new file mode 100644 index 00000000..48ce39b5 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ipatch.h @@ -0,0 +1,292 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IPATCH_H) +#define INCLUDED_IPATCH_H + +#include "generic/constant.h" +#include "generic/vector.h" + +namespace scene +{ + class Node; +} + +template +class ArrayReference +{ + std::size_t m_size; + Element* m_data; +public: + typedef Element value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + ArrayReference() + : m_size(0), m_data(0) + { + } + ArrayReference(std::size_t size, Element* data) + : m_size(size), m_data(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; + } +}; + +#if 0 +template +class MatrixIterator +{ + Element* m_position; + + void increment() + { + ++m_position; + } + +public: + typedef std::bidirectional_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; + + MatrixIterator(Element* position) : m_position(position) + { + } + + Element* position() + { + return m_position; + } + + bool operator==(const MatrixIterator& other) const + { + return m_position == other.m_position; + } + bool operator!=(const MatrixIterator& other) const + { + return !operator==(other); + } + MatrixIterator& operator++() + { + increment(); + return *this; + } + MatrixIterator operator++(int) + { + MatrixIterator tmp = *this; + increment(); + return tmp; + } + value_type& operator*() const + { + return m_position->m_value; + } + value_type* operator->() const + { + return &(operator*()); + } +}; +#endif + +template +class Matrix +{ + std::size_t m_x, m_y; + Element* m_data; +public: + typedef Element value_type; + typedef value_type* iterator; + typedef const value_type* const_iterator; + + Matrix() + : m_x(0), m_y(0), m_data(0) + { + } + Matrix(std::size_t x, std::size_t y, Element* data) + : m_x(x), m_y(y), m_data(data) + { + } + + iterator begin() + { + return m_data; + } + const_iterator begin() const + { + return m_data; + } + iterator end() + { + return m_data + size(); + } + const_iterator end() const + { + return m_data + 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& operator()(std::size_t x, std::size_t y) + { +#if defined(_DEBUG) + ASSERT_MESSAGE(x < m_x && y < m_y, "array index out of bounds"); +#endif + return m_data[x * m_y + y]; + } + const value_type& operator()(std::size_t x, std::size_t y) const + { +#if defined(_DEBUG) + ASSERT_MESSAGE(x < m_x && y < m_y, "array index out of bounds"); +#endif + return m_data[x * m_y + y]; + } + value_type* data() + { + return m_data; + } + const value_type* data() const + { + return m_data; + } + std::size_t x() const + { + return m_x; + } + std::size_t y() const + { + return m_y; + } + std::size_t size() const + { + return m_x * m_y; + } + bool empty() const + { + return m_x == 0; + } +}; + +class PatchControl +{ +public: + Vector3 m_vertex; + Vector2 m_texcoord; +}; + +typedef Matrix PatchControlMatrix; + + +class PatchCreator +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "patch"); + virtual scene::Node& createPatch() = 0; + virtual void Patch_undoSave(scene::Node& patch) const = 0; + virtual void Patch_resize(scene::Node& patch, std::size_t width, std::size_t height) const = 0; + virtual PatchControlMatrix Patch_getControlPoints(scene::Node& patch) const = 0; + virtual void Patch_controlPointsChanged(scene::Node& patch) const = 0; + virtual const char* Patch_getShader(scene::Node& patch) const = 0; + virtual void Patch_setShader(scene::Node& patch, const char* shader) const = 0; +}; + +#include "modulesystem.h" + +template +class ModuleRef; +typedef ModuleRef PatchModuleRef; + +template +class GlobalModule; +typedef GlobalModule GlobalPatchModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalPatchModuleRef; + +inline PatchCreator& GlobalPatchCreator() +{ + return GlobalPatchModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/iplugin.cpp b/misc/mediasource/netradiant-src/include/iplugin.cpp new file mode 100644 index 00000000..ebfc591f --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iplugin.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 1999-2006 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 "iplugin.h" + diff --git a/misc/mediasource/netradiant-src/include/iplugin.h b/misc/mediasource/netradiant-src/include/iplugin.h new file mode 100644 index 00000000..af713a7d --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iplugin.h @@ -0,0 +1,53 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_IPLUGIN_H) +#define INCLUDED_IPLUGIN_H + +#include "generic/constant.h" + +typedef const char* (* PFN_QERPLUG_INIT) (void* hApp, void* pMainWidget); +typedef const char* (* PFN_QERPLUG_GETNAME)(); +typedef const char* (* PFN_QERPLUG_GETCOMMANDLIST)(); +typedef const char* (* PFN_QERPLUG_GETCOMMANDTITLELIST)(); +typedef void (* PFN_QERPLUG_DISPATCH) (const char* p, float* vMin, float* vMax, bool bSingleBrush); + +struct _QERPluginTable +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "plugin"); + + PFN_QERPLUG_INIT m_pfnQERPlug_Init; + PFN_QERPLUG_GETNAME m_pfnQERPlug_GetName; + PFN_QERPLUG_GETCOMMANDLIST m_pfnQERPlug_GetCommandList; + PFN_QERPLUG_GETCOMMANDTITLELIST m_pfnQERPlug_GetCommandTitleList; + PFN_QERPLUG_DISPATCH m_pfnQERPlug_Dispatch; +}; + +template +class Modules; +typedef Modules<_QERPluginTable> PluginModules; + +template +class ModulesRef; +typedef ModulesRef<_QERPluginTable> PluginModulesRef; + +#endif diff --git a/misc/mediasource/netradiant-src/include/ireference.cpp b/misc/mediasource/netradiant-src/include/ireference.cpp new file mode 100644 index 00000000..844e95be --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ireference.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "ireference.h" + diff --git a/misc/mediasource/netradiant-src/include/ireference.h b/misc/mediasource/netradiant-src/include/ireference.h new file mode 100644 index 00000000..e97df794 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ireference.h @@ -0,0 +1,78 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IREFERENCE_H) +#define INCLUDED_IREFERENCE_H + +#include "generic/constant.h" + +namespace scene +{ + class Node; +} + +class ModuleObserver; + +class Resource +{ +public: + virtual bool load() = 0; + virtual bool save() = 0; + virtual void flush() = 0; + virtual void refresh() = 0; + virtual scene::Node* getNode() = 0; + virtual void setNode(scene::Node* node) = 0; + virtual void attach(ModuleObserver& observer) = 0; + virtual void detach(ModuleObserver& observer) = 0; + virtual void realise() = 0; + virtual void unrealise() = 0; +}; + +class EntityCreator; + +class ReferenceCache +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "reference"); + + virtual Resource* capture(const char* path) = 0; + virtual void release(const char* path) = 0; + + virtual void setEntityCreator(EntityCreator& entityCreator) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalReferenceModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalReferenceModuleRef; + +inline ReferenceCache& GlobalReferenceCache() +{ + return GlobalReferenceModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/irender.cpp b/misc/mediasource/netradiant-src/include/irender.cpp new file mode 100644 index 00000000..c0fec667 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/irender.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "irender.h" + diff --git a/misc/mediasource/netradiant-src/include/irender.h b/misc/mediasource/netradiant-src/include/irender.h new file mode 100644 index 00000000..d9c40b6f --- /dev/null +++ b/misc/mediasource/netradiant-src/include/irender.h @@ -0,0 +1,177 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IRENDER_H) +#define INCLUDED_IRENDER_H + +#include "generic/constant.h" +#include "generic/callbackfwd.h" + + +// Rendering states to sort by. +// Higher bits have the most effect - slowest state changes should be highest. + +const unsigned int RENDER_DEFAULT = 0; +const unsigned int RENDER_LINESTIPPLE = 1 << 0; // glEnable(GL_LINE_STIPPLE) +const unsigned int RENDER_LINESMOOTH = 1 << 1; // glEnable(GL_LINE_SMOOTH) +const unsigned int RENDER_POLYGONSTIPPLE = 1 << 2; // glEnable(GL_POLYGON_STIPPLE) +const unsigned int RENDER_POLYGONSMOOTH = 1 << 3; // glEnable(GL_POLYGON_SMOOTH) +const unsigned int RENDER_ALPHATEST = 1 << 4; // glEnable(GL_ALPHA_TEST) +const unsigned int RENDER_DEPTHTEST = 1 << 5; // glEnable(GL_DEPTH_TEST) +const unsigned int RENDER_DEPTHWRITE = 1 << 6; // glDepthMask(GL_TRUE) +const unsigned int RENDER_COLOURWRITE = 1 << 7; // glColorMask(GL_TRUE; GL_TRUE; GL_TRUE; GL_TRUE) +const unsigned int RENDER_CULLFACE = 1 << 8; // glglEnable(GL_CULL_FACE) +const unsigned int RENDER_SCALED = 1 << 9; // glEnable(GL_NORMALIZE) +const unsigned int RENDER_SMOOTH = 1 << 10; // glShadeModel +const unsigned int RENDER_FOG = 1 << 11; // glEnable(GL_FOG) +const unsigned int RENDER_LIGHTING = 1 << 12; // glEnable(GL_LIGHTING) +const unsigned int RENDER_BLEND = 1 << 13; // glEnable(GL_BLEND) +const unsigned int RENDER_OFFSETLINE = 1 << 14; // glEnable(GL_POLYGON_OFFSET_LINE) +const unsigned int RENDER_FILL = 1 << 15; // glPolygonMode +const unsigned int RENDER_COLOURARRAY = 1 << 16; // glEnableClientState(GL_COLOR_ARRAY) +const unsigned int RENDER_COLOURCHANGE = 1 << 17; // render() is allowed to call glColor*() +const unsigned int RENDER_TEXTURE = 1 << 18; // glEnable(GL_TEXTURE_2D) +const unsigned int RENDER_BUMP = 1 << 19; +const unsigned int RENDER_PROGRAM = 1 << 20; +const unsigned int RENDER_SCREEN = 1 << 21; +const unsigned int RENDER_OVERRIDE = 1 << 22; +typedef unsigned int RenderStateFlags; + + +class AABB; +class Matrix4; + +template class BasicVector3; +typedef BasicVector3 Vector3; + +class Shader; + +class RendererLight +{ +public: + virtual Shader* getShader() const = 0; + virtual const AABB& aabb() const = 0; + virtual bool testAABB(const AABB& other) const = 0; + virtual const Matrix4& rotation() const = 0; + virtual const Vector3& offset() const = 0; + virtual const Vector3& colour() const = 0; + virtual bool isProjected() const = 0; + virtual const Matrix4& projection() const = 0; +}; + +class LightCullable +{ +public: + virtual bool testLight(const RendererLight& light) const = 0; + virtual void insertLight(const RendererLight& light) + { + } + virtual void clearLights() + { + } +}; + +class Renderable; +typedef Callback1 RenderableCallback; + +typedef Callback1 RendererLightCallback; + +class LightList +{ +public: + virtual void evaluateLights() const = 0; + virtual void lightsChanged() const = 0; + virtual void forEachLight(const RendererLightCallback& callback) const = 0; +}; + +const int c_attr_TexCoord0 = 1; +const int c_attr_Tangent = 3; +const int c_attr_Binormal = 4; + +class OpenGLRenderable +{ +public: + virtual void render(RenderStateFlags state) const = 0; +}; + +class Matrix4; +struct qtexture_t; +class ModuleObserver; + +#include "generic/vector.h" + +class Shader +{ +public: + virtual void addRenderable(const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights = 0) = 0; + virtual void incrementUsed() = 0; + virtual void decrementUsed() = 0; + virtual void attach(ModuleObserver& observer) = 0; + virtual void detach(ModuleObserver& observer) = 0; + virtual qtexture_t& getTexture() const = 0; + virtual unsigned int getFlags() const = 0; +}; + +class ShaderCache +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "renderstate"); + + virtual Shader* capture(const char* name) = 0; + virtual void release(const char* name) = 0; + /*! Render all Shader objects. */ + virtual void render(RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer = Vector3(0, 0, 0)) = 0; + + virtual void realise() = 0; + virtual void unrealise() = 0; + + virtual bool lightingSupported() const = 0; + virtual bool useShaderLanguage() const = 0; + + virtual const LightList& attach(LightCullable& cullable) = 0; + virtual void detach(LightCullable& cullable) = 0; + virtual void changed(LightCullable& cullable) = 0; + virtual void attach(RendererLight& light) = 0; + virtual void detach(RendererLight& light) = 0; + virtual void changed(RendererLight& light) = 0; + + virtual void attachRenderable(const Renderable& renderable) = 0; + virtual void detachRenderable(const Renderable& renderable) = 0; + virtual void forEachRenderable(const RenderableCallback& callback) const = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalShaderCacheModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalShaderCacheModuleRef; + +inline ShaderCache& GlobalShaderCache() +{ + return GlobalShaderCacheModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/iscenegraph.cpp b/misc/mediasource/netradiant-src/include/iscenegraph.cpp new file mode 100644 index 00000000..6b7b450e --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iscenegraph.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "iscenegraph.h" + diff --git a/misc/mediasource/netradiant-src/include/iscenegraph.h b/misc/mediasource/netradiant-src/include/iscenegraph.h new file mode 100644 index 00000000..18e50f77 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iscenegraph.h @@ -0,0 +1,221 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (INCLUDED_ISCENEGRAPH_H) +#define INCLUDED_ISCENEGRAPH_H + +#include +#include "generic/constant.h" +#include "signal/signalfwd.h" + +template +class Stack; +template +class Reference; + +namespace scene +{ + class Instance; + const Instance* const nullInstancePointer = 0; + inline const Instance& nullInstance() + { + return *nullInstancePointer; + } + + class Node; + const Node* const nullNodePointer = 0; + inline const Node& nullNode() + { + return *nullNodePointer; + } +} + +typedef Reference NodeReference; + +typedef std::size_t TypeId; + +const TypeId NODETYPEID_MAX = 64; +const TypeId NODETYPEID_NONE = NODETYPEID_MAX; + +const TypeId INSTANCETYPEID_MAX = 64; +const TypeId INSTANCETYPEID_NONE = INSTANCETYPEID_MAX; + +namespace scene +{ + /// \brief A unique key to an instance of a node in the scene-graph. + typedef Stack Path; + + /// \brief A scene-graph - a Directed Acyclic Graph (DAG). + /// + /// - Each node may refer to zero or more 'child' nodes (directed). + /// - A node may never have itself as one of its ancestors (acyclic). + /// - Each node may have more than one 'parent', thus having more than one 'instance' in the graph. + /// - Each instance is uniquely identified by the list of its ancestors plus itself, known as a 'path'. + class Graph + { + public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "scenegraph"); + + class Walker + { + public: + /// \brief Called before traversing the first child-instance of 'instance'. If the return value is false, the children of the current instance are not traversed. + virtual bool pre(const Path& path, Instance& instance) const = 0; + /// \brief Called after traversing the last child-instance of 'instance'. + virtual void post(const Path& path, Instance& instance) const + { + } + }; + + /// \brief Returns the root-node of the graph. + virtual Node& root() = 0; + /// \brief Sets the root-node of the graph to be 'node'. + virtual void insert_root(Node& root) = 0; + /// \brief Clears the root-node of the graph. + virtual void erase_root() = 0; + /// \brief Traverses all nodes in the graph depth-first, starting from the root node. + virtual void traverse(const Walker& walker) = 0; + /// \brief Traverses all nodes in the graph depth-first, starting from 'start'. + virtual void traverse_subgraph(const Walker& walker, const Path& start) = 0; + /// \brief Returns the instance at the location identified by 'path', or 0 if it does not exist. + virtual scene::Instance* find(const Path& path) = 0; + + /// \brief Invokes all scene-changed callbacks. Called when any part of the scene changes the way it will appear when the scene is rendered. + /// \todo Move to a separate class. + virtual void sceneChanged() = 0; + /// \brief Add a \p callback to be invoked when the scene changes. + /// \todo Move to a separate class. + virtual void addSceneChangedCallback(const SignalHandler& handler) = 0; + + /// \brief Invokes all bounds-changed callbacks. Called when the bounds of any instance in the scene change. + /// \todo Move to a separate class. + virtual void boundsChanged() = 0; + /// \brief Add a \p callback to be invoked when the bounds of any instance in the scene change. + virtual SignalHandlerId addBoundsChangedCallback(const SignalHandler& boundsChanged) = 0; + /// \brief Remove a \p callback to be invoked when the bounds of any instance in the scene change. + virtual void removeBoundsChangedCallback(SignalHandlerId id) = 0; + + virtual TypeId getNodeTypeId(const char* name) = 0; + virtual TypeId getInstanceTypeId(const char* name) = 0; + }; + + class Traversable + { + public: + STRING_CONSTANT(Name, "scene::Traversable"); + + class Observer + { + public: + /// \brief Called when a node is added to the container. + virtual void insert(Node& node) = 0; + /// \brief Called when a node is removed from the container. + virtual void erase(Node& node) = 0; + }; + + class Walker + { + public: + /// \brief Called before traversing the first child-node of 'node'. If the return value is false, the children of the current node are not traversed. + virtual bool pre(Node& node) const = 0; + /// \brief Called after traversing the last child-node of 'node'. + virtual void post(Node& node) const + { + } + }; + /// \brief Adds a node to the container. + virtual void insert(Node& node) = 0; + /// \brief Removes a node from the container. + virtual void erase(Node& node) = 0; + /// \brief Traverses the subgraphs rooted at each node in the container, depth-first. + virtual void traverse(const Walker& walker) = 0; + /// \brief Returns true if the container contains no nodes. + virtual bool empty() const = 0; + }; + + class Instantiable + { + public: + STRING_CONSTANT(Name, "scene::Instantiable"); + + class Observer + { + public: + /// \brief Called when an instance is added to the container. + virtual void insert(scene::Instance* instance) = 0; + /// \brief Called when an instance is removed from the container. + virtual void erase(scene::Instance* instance) = 0; + }; + + class Visitor + { + public: + virtual void visit(Instance& instance) const = 0; + }; + + /// \brief Returns a new instance uniquely identified by 'path'. + virtual scene::Instance* create(const scene::Path& path, scene::Instance* parent) = 0; + /// \brief Calls Visitor::visit(instance) for each instance in the container. + virtual void forEachInstance(const Visitor& visitor) = 0; + /// \brief Adds an instance to the container. + virtual void insert(Observer* observer, const Path& path, scene::Instance* instance) = 0; + /// \brief Returns an instance removed from the container. + virtual scene::Instance* erase(Observer* observer, const Path& path) = 0; + }; + + class Cloneable + { + public: + STRING_CONSTANT(Name, "scene::Cloneable"); + + /// \brief Returns a copy of itself. + virtual scene::Node& clone() const = 0; + }; +} + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalSceneGraphModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalSceneGraphModuleRef; + +inline scene::Graph& GlobalSceneGraph() +{ + return GlobalSceneGraphModule::getTable(); +} + +inline void AddSceneChangeCallback(const SignalHandler& handler) +{ + GlobalSceneGraph().addSceneChangedCallback(handler); +} +inline void SceneChangeNotify() +{ + GlobalSceneGraph().sceneChanged(); +} + + + +#endif diff --git a/misc/mediasource/netradiant-src/include/iscriplib.cpp b/misc/mediasource/netradiant-src/include/iscriplib.cpp new file mode 100644 index 00000000..4de7c3f9 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iscriplib.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "iscriplib.h" + diff --git a/misc/mediasource/netradiant-src/include/iscriplib.h b/misc/mediasource/netradiant-src/include/iscriplib.h new file mode 100644 index 00000000..98d85c27 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iscriplib.h @@ -0,0 +1,85 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ISCRIPLIB_H) +#define INCLUDED_ISCRIPLIB_H + +/// \file iscriplib.h +/// \brief Token input/output stream module. + +#include +#include "generic/constant.h" + +#define MAXTOKEN 1024 + +class Tokeniser +{ +public: + virtual void release() = 0; + virtual void nextLine() = 0; + virtual const char* getToken() = 0; + virtual void ungetToken() = 0; + virtual std::size_t getLine() const = 0; + virtual std::size_t getColumn() const = 0; +}; + +class TextInputStream; + +class TokenWriter +{ +public: + virtual void release() = 0; + virtual void nextLine() = 0; + virtual void writeToken(const char* token) = 0; + virtual void writeString(const char* string) = 0; + virtual void writeInteger(int i) = 0; + virtual void writeUnsigned(std::size_t i) = 0; + virtual void writeFloat(double f) = 0; +}; + +class TextOutputStream; + +struct _QERScripLibTable +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "scriptlib"); + + Tokeniser& (* m_pfnNewScriptTokeniser)(TextInputStream& istream); + Tokeniser& (* m_pfnNewSimpleTokeniser)(TextInputStream& istream); + TokenWriter& (* m_pfnNewSimpleTokenWriter)(TextOutputStream& ostream); +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule<_QERScripLibTable> GlobalScripLibModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef<_QERScripLibTable> GlobalScripLibModuleRef; + +inline _QERScripLibTable& GlobalScriptLibrary() +{ + return GlobalScripLibModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/iselection.cpp b/misc/mediasource/netradiant-src/include/iselection.cpp new file mode 100644 index 00000000..2438d313 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iselection.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "iselection.h" + diff --git a/misc/mediasource/netradiant-src/include/iselection.h b/misc/mediasource/netradiant-src/include/iselection.h new file mode 100644 index 00000000..ec32561e --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iselection.h @@ -0,0 +1,145 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ISELECTION_H) +#define INCLUDED_ISELECTION_H + +#include +#include "generic/constant.h" +#include "generic/callbackfwd.h" +#include "signal/signalfwd.h" + +class Renderer; +class View; + +class Selectable +{ +public: + STRING_CONSTANT(Name, "Selectable"); + + virtual void setSelected(bool select) = 0; + virtual bool isSelected() const = 0; +}; + +namespace scene +{ + class Instance; +}; + +class InstanceSelectionObserver +{ +public: + virtual void onSelectedChanged(scene::Instance& instance) = 0; +}; + +template class BasicVector3; +typedef BasicVector3 Vector3; +template class BasicVector4; +typedef BasicVector4 Vector4; +class Matrix4; +typedef Vector4 Quaternion; + +typedef Callback1 SelectionChangeCallback; +typedef SignalHandler1 SelectionChangeHandler; + +class SelectionSystem +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "selection"); + + enum EMode + { + eEntity, + ePrimitive, + eComponent, + }; + + enum EComponentMode + { + eDefault, + eVertex, + eEdge, + eFace, + }; + + enum EManipulatorMode + { + eTranslate, + eRotate, + eScale, + eDrag, + eClip, + }; + + virtual void SetMode(EMode mode) = 0; + virtual EMode Mode() const = 0; + virtual void SetComponentMode(EComponentMode mode) = 0; + virtual EComponentMode ComponentMode() const = 0; + virtual void SetManipulatorMode(EManipulatorMode mode) = 0; + virtual EManipulatorMode ManipulatorMode() const = 0; + + virtual SelectionChangeCallback getObserver(EMode mode) = 0; + virtual std::size_t countSelected() const = 0; + virtual std::size_t countSelectedComponents() const = 0; + virtual void onSelectedChanged(scene::Instance& instance, const Selectable& selectable) = 0; + virtual void onComponentSelection(scene::Instance& instance, const Selectable& selectable) = 0; + virtual scene::Instance& ultimateSelected() const = 0; + virtual scene::Instance& penultimateSelected() const = 0; + virtual void setSelectedAll(bool selected) = 0; + virtual void setSelectedAllComponents(bool selected) = 0; + + class Visitor + { + public: + virtual void visit(scene::Instance& instance) const = 0; + }; + virtual void foreachSelected(const Visitor& visitor) const = 0; + virtual void foreachSelectedComponent(const Visitor& visitor) const = 0; + + virtual void addSelectionChangeCallback(const SelectionChangeHandler& handler) = 0; + + virtual void NudgeManipulator(const Vector3& nudge, const Vector3& view) = 0; + + virtual void translateSelected(const Vector3& translation) = 0; + virtual void rotateSelected(const Quaternion& rotation) = 0; + virtual void scaleSelected(const Vector3& scaling) = 0; + + virtual void pivotChanged() const = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalSelectionModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalSelectionModuleRef; + +inline SelectionSystem& GlobalSelectionSystem() +{ + return GlobalSelectionModule::getTable(); +} + + +#endif diff --git a/misc/mediasource/netradiant-src/include/ishaders.cpp b/misc/mediasource/netradiant-src/include/ishaders.cpp new file mode 100644 index 00000000..bf380198 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ishaders.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 1999-2006 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 "ishaders.h" + diff --git a/misc/mediasource/netradiant-src/include/ishaders.h b/misc/mediasource/netradiant-src/include/ishaders.h new file mode 100644 index 00000000..928dd1de --- /dev/null +++ b/misc/mediasource/netradiant-src/include/ishaders.h @@ -0,0 +1,195 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_ISHADERS_H) +#define INCLUDED_ISHADERS_H + +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +enum +{ + QER_TRANS = 1 << 0, + QER_NOCARVE = 1 << 1, + QER_NODRAW = 1 << 2, + QER_NONSOLID = 1 << 3, + QER_WATER = 1 << 4, + QER_LAVA = 1 << 5, + QER_FOG = 1 << 6, + QER_ALPHATEST = 1 << 7, + QER_CULL = 1 << 8, + QER_AREAPORTAL = 1 << 9, + QER_CLIP = 1 << 10, + QER_BOTCLIP = 1 << 11, +}; + +struct qtexture_t; + +template class BasicVector3; +typedef BasicVector3 Vector3; +typedef Vector3 Colour3; + +typedef unsigned char BlendFactor; +const BlendFactor BLEND_ZERO = 0; +const BlendFactor BLEND_ONE = 1; +const BlendFactor BLEND_SRC_COLOUR = 2; +const BlendFactor BLEND_ONE_MINUS_SRC_COLOUR = 3; +const BlendFactor BLEND_SRC_ALPHA = 4; +const BlendFactor BLEND_ONE_MINUS_SRC_ALPHA = 5; +const BlendFactor BLEND_DST_COLOUR = 6; +const BlendFactor BLEND_ONE_MINUS_DST_COLOUR = 7; +const BlendFactor BLEND_DST_ALPHA = 8; +const BlendFactor BLEND_ONE_MINUS_DST_ALPHA = 9; +const BlendFactor BLEND_SRC_ALPHA_SATURATE = 10; + +class BlendFunc +{ +public: + BlendFunc(BlendFactor src, BlendFactor dst) : m_src(src), m_dst(dst) + { + } + BlendFactor m_src; + BlendFactor m_dst; +}; + +class ShaderLayer +{ +public: + virtual qtexture_t* texture() const = 0; + virtual BlendFunc blendFunc() const = 0; + virtual bool clampToBorder() const = 0; + virtual float alphaTest() const = 0; +}; + +typedef Callback1 ShaderLayerCallback; + + +class IShader +{ +public: + enum EAlphaFunc + { + eAlways, + eEqual, + eLess, + eGreater, + eLEqual, + eGEqual, + }; + enum ECull + { + eCullNone, + eCullBack, + }; + // Increment the number of references to this object + virtual void IncRef() = 0; + // Decrement the reference count + virtual void DecRef() = 0; + // get/set the qtexture_t* Radiant uses to represent this shader object + virtual qtexture_t* getTexture() const = 0; + virtual qtexture_t* getDiffuse() const = 0; + virtual qtexture_t* getBump() const = 0; + virtual qtexture_t* getSpecular() const = 0; + // get shader name + virtual const char* getName() const = 0; + virtual bool IsInUse() const = 0; + virtual void SetInUse(bool bInUse) = 0; + // get the editor flags (QER_NOCARVE QER_TRANS) + virtual int getFlags() const = 0; + // get the transparency value + virtual float getTrans() const = 0; + // test if it's a true shader, or a default shader created to wrap around a texture + virtual bool IsDefault() const = 0; + // get the alphaFunc + virtual void getAlphaFunc(EAlphaFunc *func, float *ref) = 0; + virtual BlendFunc getBlendFunc() const = 0; + // get the cull type + virtual ECull getCull() = 0; + // get shader file name (ie the file where this one is defined) + virtual const char* getShaderFileName() const = 0; + + virtual const ShaderLayer* firstLayer() const = 0; + virtual void forEachLayer(const ShaderLayerCallback& layer) const = 0; + + virtual qtexture_t* lightFalloffImage() const = 0; +}; + +typedef struct _GSList GSList; +typedef Callback1 ShaderNameCallback; + +class ModuleObserver; + +class ShaderSystem +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "shaders"); + // NOTE: shader and texture names used must be full path. + // Shaders usable as textures have prefix equal to getTexturePrefix() + + virtual void realise() = 0; + virtual void unrealise() = 0; + virtual void refresh() = 0; + // activate the shader for a given name and return it + // will return the default shader if name is not found + virtual IShader* getShaderForName(const char* name) = 0; + + virtual void foreachShaderName(const ShaderNameCallback& callback) = 0; + + // iterate over the list of active shaders + virtual void beginActiveShadersIterator() = 0; + virtual bool endActiveShadersIterator() = 0; + virtual IShader* dereferenceActiveShadersIterator() = 0; + virtual void incrementActiveShadersIterator() = 0; + + virtual void setActiveShadersChangedNotify(const Callback& notify) = 0; + + virtual void attach(ModuleObserver& observer) = 0; + virtual void detach(ModuleObserver& observer) = 0; + + virtual void setLightingEnabled(bool enabled) = 0; + + virtual const char* getTexturePrefix() const = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalShadersModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalShadersModuleRef; + +inline ShaderSystem& GlobalShaderSystem() +{ + return GlobalShadersModule::getTable(); +} + + +#define QERApp_Shader_ForName GlobalShaderSystem().getShaderForName +#define QERApp_ActiveShaders_IteratorBegin GlobalShaderSystem().beginActiveShadersIterator +#define QERApp_ActiveShaders_IteratorAtEnd GlobalShaderSystem().endActiveShadersIterator +#define QERApp_ActiveShaders_IteratorCurrent GlobalShaderSystem().dereferenceActiveShadersIterator +#define QERApp_ActiveShaders_IteratorIncrement GlobalShaderSystem().incrementActiveShadersIterator + +#endif diff --git a/misc/mediasource/netradiant-src/include/itexdef.cpp b/misc/mediasource/netradiant-src/include/itexdef.cpp new file mode 100644 index 00000000..1973c960 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itexdef.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "itexdef.h" + diff --git a/misc/mediasource/netradiant-src/include/itexdef.h b/misc/mediasource/netradiant-src/include/itexdef.h new file mode 100644 index 00000000..a299843b --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itexdef.h @@ -0,0 +1,42 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (INCLUDED_ITEXDEF_H) +#define INCLUDED_ITEXDEF_H + +class texdef_t +{ +public: + float shift[2]; + float rotate; + float scale[2]; + + texdef_t() + { + shift[0] = 0; + shift[1] = 0; + rotate = 0; + scale[0] = 1; + scale[1] = 1; + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/include/itextstream.cpp b/misc/mediasource/netradiant-src/include/itextstream.cpp new file mode 100644 index 00000000..c93ae35a --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itextstream.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "itextstream.h" + diff --git a/misc/mediasource/netradiant-src/include/itextstream.h b/misc/mediasource/netradiant-src/include/itextstream.h new file mode 100644 index 00000000..891336e7 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itextstream.h @@ -0,0 +1,114 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ITEXTSTREAM_H) +#define INCLUDED_ITEXTSTREAM_H + +/// \file +/// \brief Text-stream interfaces. + +#include +#include "generic/static.h" + +/// \brief A read-only character-stream. +class TextInputStream +{ +public: + /// \brief Attempts to read the next \p length characters from the stream to \p buffer. + /// Returns the number of characters actually stored in \p buffer. + virtual std::size_t read(char* buffer, std::size_t length) = 0; +}; + +/// \brief A write-only character-stream. +class TextOutputStream +{ +public: + /// \brief Attempts to write \p length characters to the stream from \p buffer. + /// Returns the number of characters actually read from \p buffer. + virtual std::size_t write(const char* buffer, std::size_t length) = 0; +}; + +/// \brief Calls the overloaded function ostream_write() to perform text formatting specific to the type being written. +/*! Note that ostream_write() is not globally defined - it must be defined once for each type supported.\n +To support writing a custom type MyClass to any kind of text-output-stream with operator<<: +\code +template +TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const MyClass& myClass) +{ + return ostream << myClass.getName() << ' ' << myClass.getText(); +} +\endcode +Expressing this as a template allows it to be used directly with any concrete text-output-stream type, not just the abstract TextOutputStream\n +\n +This overload writes a single character to any text-output-stream - ostream_write(TextOutputStreamType& ostream, char c). +*/ +template +inline TextOutputStream& operator<<(TextOutputStream& ostream, const T& t) +{ + return ostream_write(ostream, t); +} + +class NullOutputStream : public TextOutputStream +{ +public: + std::size_t write(const char*, std::size_t length) + { + return length; + } +}; + +class OutputStreamHolder +{ + NullOutputStream m_nullOutputStream; + TextOutputStream* m_outputStream; +public: + OutputStreamHolder() + : m_outputStream(&m_nullOutputStream) + { + } + void setOutputStream(TextOutputStream& outputStream) + { + m_outputStream = &outputStream; + } + TextOutputStream& getOutputStream() + { + return *m_outputStream; + } +}; + +typedef Static GlobalOutputStream; + +/// \brief Returns the global output stream. Used to display messages to the user. +inline TextOutputStream& globalOutputStream() +{ + return GlobalOutputStream::instance().getOutputStream(); +} + +class ErrorStreamHolder : public OutputStreamHolder {}; +typedef Static GlobalErrorStream; + +/// \brief Returns the global error stream. Used to display error messages to the user. +inline TextOutputStream& globalErrorStream() +{ + return GlobalErrorStream::instance().getOutputStream(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/itextures.cpp b/misc/mediasource/netradiant-src/include/itextures.cpp new file mode 100644 index 00000000..26e2bf6d --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itextures.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "itextures.h" + diff --git a/misc/mediasource/netradiant-src/include/itextures.h b/misc/mediasource/netradiant-src/include/itextures.h new file mode 100644 index 00000000..368e7b76 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itextures.h @@ -0,0 +1,92 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ITEXTURES_H) +#define INCLUDED_ITEXTURES_H + +#include "iimage.h" +#include "generic/constant.h" + +struct qtexture_t; + +class LoadImageCallback +{ + typedef Image* (*LoadFunc)(void* environment, const char* name); +public: + void* m_environment; + LoadFunc m_func; + + LoadImageCallback(void* environment, LoadFunc func) : m_environment(environment), m_func(func) + { + } + Image* loadImage(const char* name) const + { + return m_func(m_environment, name); + } +}; + +inline bool operator==(const LoadImageCallback& self, const LoadImageCallback& other) +{ + return self.m_environment == other.m_environment && self.m_func == other.m_func; +} +inline bool operator<(const LoadImageCallback& self, const LoadImageCallback& other) +{ + return self.m_environment < other.m_environment || + (!(other.m_environment < self.m_environment) && self.m_func < other.m_func); +} + +class TexturesCacheObserver +{ +public: + virtual void unrealise() = 0; + virtual void realise() = 0; +}; + +class TexturesCache +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "textures"); + virtual LoadImageCallback defaultLoader() const = 0; + virtual Image* loadImage(const char* name) = 0; + virtual qtexture_t* capture(const char* name) = 0; + virtual qtexture_t* capture(const LoadImageCallback& load, const char* name) = 0; + virtual void release(qtexture_t* texture) = 0; + virtual void attach(TexturesCacheObserver& observer) = 0; + virtual void detach(TexturesCacheObserver& observer) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalTexturesModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalTexturesModuleRef; + +inline TexturesCache& GlobalTexturesCache() +{ + return GlobalTexturesModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/itoolbar.cpp b/misc/mediasource/netradiant-src/include/itoolbar.cpp new file mode 100644 index 00000000..2c989b6a --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itoolbar.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 1999-2006 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 "itoolbar.h" + diff --git a/misc/mediasource/netradiant-src/include/itoolbar.h b/misc/mediasource/netradiant-src/include/itoolbar.h new file mode 100644 index 00000000..350e5a5f --- /dev/null +++ b/misc/mediasource/netradiant-src/include/itoolbar.h @@ -0,0 +1,66 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_IPLUGTOOLBAR_H) +#define INCLUDED_IPLUGTOOLBAR_H + +#include +#include "generic/constant.h" + +class IToolbarButton +{ +public: + enum EType + { + eSpace, + eButton, + eToggleButton, + eRadioButton, + }; + + virtual const char* getImage() const = 0; + virtual const char* getText() const = 0; + virtual const char* getTooltip() const = 0; + virtual EType getType() const = 0; + virtual void activate() const = 0; +}; + +typedef std::size_t (* PFN_TOOLBARBUTTONCOUNT)(); +typedef const IToolbarButton* (* PFN_GETTOOLBARBUTTON)(std::size_t index); + +struct _QERPlugToolbarTable +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "toolbar"); + + PFN_TOOLBARBUTTONCOUNT m_pfnToolbarButtonCount; + PFN_GETTOOLBARBUTTON m_pfnGetToolbarButton; +}; + +template +class Modules; +typedef Modules<_QERPlugToolbarTable> ToolbarModules; + +template +class ModulesRef; +typedef ModulesRef<_QERPlugToolbarTable> ToolbarModulesRef; + +#endif diff --git a/misc/mediasource/netradiant-src/include/iundo.cpp b/misc/mediasource/netradiant-src/include/iundo.cpp new file mode 100644 index 00000000..49b96b03 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iundo.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "iundo.h" + diff --git a/misc/mediasource/netradiant-src/include/iundo.h b/misc/mediasource/netradiant-src/include/iundo.h new file mode 100644 index 00000000..4dcbad85 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/iundo.h @@ -0,0 +1,110 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_IUNDO_H) +#define INCLUDED_IUNDO_H + +/// \file +/// \brief The undo-system interface. Uses the 'memento' pattern. + +#include +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +class UndoMemento +{ +public: + virtual void release() = 0; +}; + +class Undoable +{ +public: + virtual UndoMemento* exportState() const = 0; + virtual void importState(const UndoMemento* state) = 0; +}; + +class UndoObserver +{ +public: + virtual void save(Undoable* undoable) = 0; +}; + +class UndoTracker +{ +public: + virtual void clear() = 0; + virtual void begin() = 0; + virtual void undo() = 0; + virtual void redo() = 0; +}; + +class UndoSystem +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "undo"); + + virtual UndoObserver* observer(Undoable* undoable) = 0; + virtual void release(Undoable* undoable) = 0; + + virtual std::size_t size() const = 0; + virtual void start() = 0; + virtual void finish(const char* command) = 0; + virtual void undo() = 0; + virtual void redo() = 0; + virtual void clear() = 0; + + virtual void trackerAttach(UndoTracker& tracker) = 0; + virtual void trackerDetach(UndoTracker& tracker) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalUndoModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalUndoModuleRef; + +inline UndoSystem& GlobalUndoSystem() +{ + return GlobalUndoModule::getTable(); +} + +class UndoableCommand +{ + const char* m_command; +public: + UndoableCommand(const char* command) : m_command(command) + { + GlobalUndoSystem().start(); + } + ~UndoableCommand() + { + GlobalUndoSystem().finish(m_command); + } +}; + + +#endif diff --git a/misc/mediasource/netradiant-src/include/mapfile.cpp b/misc/mediasource/netradiant-src/include/mapfile.cpp new file mode 100644 index 00000000..1065f591 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/mapfile.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "mapfile.h" + diff --git a/misc/mediasource/netradiant-src/include/mapfile.h b/misc/mediasource/netradiant-src/include/mapfile.h new file mode 100644 index 00000000..e53d79c1 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/mapfile.h @@ -0,0 +1,76 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_MAPFILE_H) +#define INCLUDED_MAPFILE_H + +#include + +#include "iscenegraph.h" +#include "generic/callbackfwd.h" + +const std::size_t MAPFILE_MAX_CHANGES = std::numeric_limits::max(); + +class MapFile +{ +public: + STRING_CONSTANT(Name, "MapFile"); + + virtual void save() = 0; + virtual bool saved() const = 0; + virtual void changed() = 0; + virtual void setChangedCallback(const Callback& changed) = 0; + virtual std::size_t changes() const = 0; +}; + +#include "scenelib.h" + +inline MapFile* Node_getMapFile(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +template +inline MapFile* path_find_mapfile(Iterator first, Iterator last) +{ + Iterator i = last; + for(;;) + { + --i; + + MapFile* map = Node_getMapFile(*i); + if(map != 0) + { + return map; + } + + if(i == first) + { + break; + } + } + ERROR_MESSAGE("failed to find parent mapfile for path"); + return 0; +} + + + +#endif diff --git a/misc/mediasource/netradiant-src/include/modelskin.cpp b/misc/mediasource/netradiant-src/include/modelskin.cpp new file mode 100644 index 00000000..6d34f272 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/modelskin.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "modelskin.h" + diff --git a/misc/mediasource/netradiant-src/include/modelskin.h b/misc/mediasource/netradiant-src/include/modelskin.h new file mode 100644 index 00000000..c01b5f30 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/modelskin.h @@ -0,0 +1,92 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_MODELSKIN_H) +#define INCLUDED_MODELSKIN_H + +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +class SkinRemap +{ +public: + const char* m_from; + const char* m_to; + SkinRemap(const char* from, const char* to) : m_from(from), m_to(to) + { + } +}; + +typedef Callback1 SkinRemapCallback; +class ModuleObserver; + +class ModelSkin +{ +public: + STRING_CONSTANT(Name, "ModelSkin"); + /// \brief Attach an \p observer whose realise() and unrealise() methods will be called when the skin is loaded or unloaded. + virtual void attach(ModuleObserver& observer) = 0; + /// \brief Detach an \p observer previously-attached by calling \c attach. + virtual void detach(ModuleObserver& observer) = 0; + /// \brief Returns true if this skin is currently loaded. + virtual bool realised() const = 0; + /// \brief Returns the shader identifier that \p name remaps to, or "" if not found or not realised. + virtual const char* getRemap(const char* name) const = 0; + /// \brief Calls \p callback for each remap pair. Has no effect if not realised. + virtual void forEachRemap(const SkinRemapCallback& callback) const = 0; +}; + +class SkinnedModel +{ +public: + STRING_CONSTANT(Name, "SkinnedModel"); + /// \brief Instructs the skinned model to update its skin. + virtual void skinChanged() = 0; +}; + +class ModelSkinCache +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "modelskin"); + /// \brief Increments the reference count of and returns a reference to the skin uniquely identified by 'name'. + virtual ModelSkin& capture(const char* name) = 0; + /// \brief Decrements the reference-count of the skin uniquely identified by 'name'. + virtual void release(const char* name) = 0; +}; + + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalModelSkinCacheModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalModelSkinCacheModuleRef; + +inline ModelSkinCache& GlobalModelSkinCache() +{ + return GlobalModelSkinCacheModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/moduleobserver.cpp b/misc/mediasource/netradiant-src/include/moduleobserver.cpp new file mode 100644 index 00000000..fa26f8d9 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/moduleobserver.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "moduleobserver.h" + diff --git a/misc/mediasource/netradiant-src/include/moduleobserver.h b/misc/mediasource/netradiant-src/include/moduleobserver.h new file mode 100644 index 00000000..e218b4aa --- /dev/null +++ b/misc/mediasource/netradiant-src/include/moduleobserver.h @@ -0,0 +1,32 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_MODULEOBSERVER_H) +#define INCLUDED_MODULEOBSERVER_H + +class ModuleObserver +{ +public: + virtual void unrealise() = 0; + virtual void realise() = 0; +}; + +#endif diff --git a/misc/mediasource/netradiant-src/include/modulesystem.cpp b/misc/mediasource/netradiant-src/include/modulesystem.cpp new file mode 100644 index 00000000..6b7a27c9 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/modulesystem.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "modulesystem.h" + diff --git a/misc/mediasource/netradiant-src/include/modulesystem.h b/misc/mediasource/netradiant-src/include/modulesystem.h new file mode 100644 index 00000000..0378cc1d --- /dev/null +++ b/misc/mediasource/netradiant-src/include/modulesystem.h @@ -0,0 +1,265 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_MODULESYSTEM_H) +#define INCLUDED_MODULESYSTEM_H + +#include "generic/static.h" +#include "debugging/debugging.h" + +#if defined(WIN32) +#ifdef MINGW32 +#define RADIANT_DLLEXPORT __declspec(dllexport) +#define RADIANT_DLLIMPORT __declspec(dllimport) +#else +#define RADIANT_DLLEXPORT __stdcall +#define RADIANT_DLLIMPORT __stdcall +#endif +#else +#define RADIANT_DLLEXPORT +#define RADIANT_DLLIMPORT +#endif + + +class Module +{ +public: + virtual void capture() = 0; + virtual void release() = 0; + virtual void* getTable() = 0; +}; + +inline void* Module_getTable(Module& module) +{ + return module.getTable(); +} + +class TextOutputStream; +class DebugMessageHandler; + +class ModuleServer +{ +public: + class Visitor + { + public: + virtual void visit(const char* name, Module& module) const = 0; + }; + + virtual void setError(bool error) = 0; + virtual bool getError() const = 0; + + virtual TextOutputStream& getOutputStream() = 0; + virtual TextOutputStream& getErrorStream() = 0; + virtual DebugMessageHandler& getDebugMessageHandler() = 0; + + virtual void registerModule(const char* type, int version, const char* name, Module& module) = 0; + virtual Module* findModule(const char* type, int version, const char* name) const = 0; + virtual void foreachModule(const char* type, int version, const Visitor& visitor) = 0; +}; + +class ModuleServerHolder +{ + ModuleServer* m_server; +public: + ModuleServerHolder() + : m_server(0) + { + } + void set(ModuleServer& server) + { + m_server = &server; + } + ModuleServer& get() + { + return *m_server; + } +}; + +typedef Static GlobalModuleServer; + +inline ModuleServer& globalModuleServer() +{ + return GlobalModuleServer::instance().get(); +} + + +inline void initialiseModule(ModuleServer& server) +{ + GlobalErrorStream::instance().setOutputStream(server.getErrorStream()); + GlobalOutputStream::instance().setOutputStream(server.getOutputStream()); + GlobalDebugMessageHandler::instance().setHandler(server.getDebugMessageHandler()); + GlobalModuleServer::instance().set(server); +} + + + +template +class Modules +{ +public: + class Visitor + { + public: + virtual void visit(const char* name, const Type& table) const = 0; + }; + + virtual Type* findModule(const char* name) = 0; + virtual void foreachModule(const Visitor& visitor) = 0; +}; + +#include "debugging/debugging.h" + +template +class ModuleRef +{ + Module* m_module; + Type* m_table; +public: + ModuleRef(const char* name) : m_table(0) + { + if(!globalModuleServer().getError()) + { + m_module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); + if(m_module == 0) + { + globalModuleServer().setError(true); + globalErrorStream() << "ModuleRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; + } + else + { + m_module->capture(); + if(!globalModuleServer().getError()) + { + m_table = static_cast(m_module->getTable()); + } + } + } + } + ~ModuleRef() + { + if(m_module != 0) + { + m_module->release(); + } + } + Type* getTable() + { +#if defined(_DEBUG) + ASSERT_MESSAGE(m_table != 0, "ModuleRef::getTable: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " - module-reference used without being initialised"); +#endif + return m_table; + } +}; + +template +class SingletonModuleRef +{ + Module* m_module; + Type* m_table; +public: + + SingletonModuleRef() + : m_module(0), m_table(0) + { + } + + bool initialised() const + { + return m_module != 0; + } + + void initialise(const char* name) + { + m_module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); + if(m_module == 0) + { + globalModuleServer().setError(true); + globalErrorStream() << "SingletonModuleRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; + } + } + + Type* getTable() + { +#if defined(_DEBUG) + ASSERT_MESSAGE(m_table != 0, "SingletonModuleRef::getTable: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " - module-reference used without being initialised"); +#endif + return m_table; + } + void capture() + { + if(initialised()) + { + m_module->capture(); + m_table = static_cast(m_module->getTable()); + } + } + void release() + { + if(initialised()) + { + m_module->release(); + } + } +}; + +template +class GlobalModule +{ + static SingletonModuleRef m_instance; +public: + static SingletonModuleRef& instance() + { + return m_instance; + } + static Type& getTable() + { + return *m_instance.getTable(); + } +}; + +template +SingletonModuleRef GlobalModule::m_instance; + + +template +class GlobalModuleRef +{ +public: + GlobalModuleRef(const char* name = "*") + { + if(!globalModuleServer().getError()) + { + GlobalModule::instance().initialise(name); + } + GlobalModule::instance().capture(); + } + ~GlobalModuleRef() + { + GlobalModule::instance().release(); + } + Type& getTable() + { + return GlobalModule::getTable(); + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/include/nameable.cpp b/misc/mediasource/netradiant-src/include/nameable.cpp new file mode 100644 index 00000000..f401626c --- /dev/null +++ b/misc/mediasource/netradiant-src/include/nameable.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "nameable.h" + diff --git a/misc/mediasource/netradiant-src/include/nameable.h b/misc/mediasource/netradiant-src/include/nameable.h new file mode 100644 index 00000000..8e1357a4 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/nameable.h @@ -0,0 +1,41 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_NAMEABLE_H) +#define INCLUDED_NAMEABLE_H + +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +typedef Callback1 NameCallback; + +class Nameable +{ +public: + STRING_CONSTANT(Name, "Nameable"); + + virtual const char* name() const = 0; + virtual void attach(const NameCallback& callback) = 0; + virtual void detach(const NameCallback& callback) = 0; +}; + + +#endif diff --git a/misc/mediasource/netradiant-src/include/namespace.cpp b/misc/mediasource/netradiant-src/include/namespace.cpp new file mode 100644 index 00000000..2f322fda --- /dev/null +++ b/misc/mediasource/netradiant-src/include/namespace.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "namespace.h" + diff --git a/misc/mediasource/netradiant-src/include/namespace.h b/misc/mediasource/netradiant-src/include/namespace.h new file mode 100644 index 00000000..30367bfd --- /dev/null +++ b/misc/mediasource/netradiant-src/include/namespace.h @@ -0,0 +1,63 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_NAMESPACE_H) +#define INCLUDED_NAMESPACE_H + +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +typedef Callback1 NameCallback; +typedef Callback1 NameCallbackCallback; + +class Namespace +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "namespace"); + virtual void attach(const NameCallback& setName, const NameCallbackCallback& attachObserver) = 0; + virtual void detach(const NameCallback& setName, const NameCallbackCallback& detachObserver) = 0; + virtual void makeUnique(const char* name, const NameCallback& setName) const = 0; +}; + +class Namespaced +{ +public: + STRING_CONSTANT(Name, "Namespaced"); + + virtual void setNamespace(Namespace& space) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalNamespaceModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalNamespaceModuleRef; + +inline Namespace& GlobalNamespace() +{ + return GlobalNamespaceModule::getTable(); +} +#endif diff --git a/misc/mediasource/netradiant-src/include/preferencesystem.cpp b/misc/mediasource/netradiant-src/include/preferencesystem.cpp new file mode 100644 index 00000000..a5fecd4d --- /dev/null +++ b/misc/mediasource/netradiant-src/include/preferencesystem.cpp @@ -0,0 +1,206 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 0 + +#include "preferencesystem.h" +#include "preferencedictionary.h" + +#include "xml/xmlparser.h" +#include "xml/xmlwriter.h" + + +void LoadPrefs(PreferenceDictionary& preferences, const char* filename) +{ + TextFileInputStream file(filename); + if(!file.failed()) + { + XMLStreamParser parser(file); + XMLPreferenceDictionaryImporter importer(preferences); + parser.exportXML(importer); + } + else + { + // error + } +} + +void SavePrefs(PreferenceDictionary& preferences, const char* filename) +{ + TextFileOutputStream file(filename); + if(!file.failed()) + { + XMLStreamWriter writer(file); + XMLPreferenceDictionaryExporter exporter(preferences, "1"); + exporter.exportXML(writer); + } + else + { + // error + } +} + + +class StringPreference +{ +public: + class Observer + { + public: + virtual void onChanged() = 0; + }; + +private: + CopiedString m_string; + Observer& m_observer; +public: + StringPreference(Observer& observer) + : m_observer(observer) + { + } + void importString(const char* value) + { + m_string = value; + m_observer.onChanged(); + } + typedef MemberCaller1 ImportStringCaller; + void exportString(StringImportCallback& importer) + { + importer(m_string.c_str()); + } + typedef MemberCaller1 ExportStringCaller; +}; + +inline void int_export(int i, StringImportCallback& importer) +{ + char buffer[16]; + sprintf(buffer, "%d", i); + importer(buffer); +} + +inline int int_import(const char* value) +{ + return atoi(value); +} + +class IntPreference +{ +public: + class Observer + { + public: + virtual void onChanged() = 0; + }; + +private: + int m_int; + Observer& m_observer; +public: + + IntPreference(Observer& observer) + : m_observer(observer) + { + } + void importString(const char* value) + { + m_int = int_import(value); + m_observer.onChanged(); + } + typedef MemberCaller1 ImportStringCaller; + void exportString(StringImportCallback& importer) + { + int_export(m_int, importer); + } + typedef MemberCaller1 ExportStringCaller; +}; + +class IntPreferenceImporter +{ + int& m_i; +public: + + IntPreferenceImporter(int& i) + : m_i(i) + { + } + void importString(const char* value) + { + m_i = int_import(value); + } +}; + + +class TestPrefs +{ +public: + TestPrefs() + { + PreferenceDictionary preferences; + + class StringObserver : public StringPreference::Observer + { + public: + void onChanged() + { + int bleh = 0; + } + } string_observer; + StringPreference string1(string_observer); + string1.importString("twenty-three"); + + class IntObserver : public IntPreference::Observer + { + public: + void onChanged() + { + int bleh = 0; + } + + } int_observer; + IntPreference int1(int_observer); + int1.importString("23"); + + preferences.registerPreference("string1", StringPreference::ImportStringCaller(string1), StringPreference::ExportStringCaller(string1)); + preferences.registerPreference("int1", IntPreference::ImportStringCaller(int1), IntPreference::ExportStringCaller(int1)); + + LoadPrefs(preferences, "test.pref"); + SavePrefs(preferences, "test.pref"); + + } +}; + +#if 0 +TestPrefs g_TestPrefs; +#endif + +void readpref(PreferenceDictionary& preferences, int& int_variable) +{ + PreferenceDictionary::iterator i = preferences.find("int_variable"); + IntPreferenceImporter importer(int_variable); + (*i).second.exporter().exportString(importer); +} + +void writepref(PreferenceDictionary& preferences, int& int_variable) +{ + PreferenceDictionary::iterator i = preferences.find("int_variable"); + int_export(int_variable, (*i).second.importer()); +} +#endif diff --git a/misc/mediasource/netradiant-src/include/preferencesystem.h b/misc/mediasource/netradiant-src/include/preferencesystem.h new file mode 100644 index 00000000..f5ebae1d --- /dev/null +++ b/misc/mediasource/netradiant-src/include/preferencesystem.h @@ -0,0 +1,56 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_PREFERENCESYSTEM_H) +#define INCLUDED_PREFERENCESYSTEM_H + +#include "generic/constant.h" +#include "generic/callbackfwd.h" + +typedef Callback1 StringImportCallback; +typedef Callback1 StringExportCallback; + +class PreferenceSystem +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "preferences"); + + virtual void registerPreference(const char* name, const StringImportCallback& importer, const StringExportCallback& exporter) = 0; +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule GlobalPreferenceSystemModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef GlobalPreferenceSystemModuleRef; + +inline PreferenceSystem& GlobalPreferenceSystem() +{ + return GlobalPreferenceSystemModule::getTable(); +} + + +#endif diff --git a/misc/mediasource/netradiant-src/include/qerplugin.cpp b/misc/mediasource/netradiant-src/include/qerplugin.cpp new file mode 100644 index 00000000..dd209319 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/qerplugin.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 1999-2006 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 "qerplugin.h" + diff --git a/misc/mediasource/netradiant-src/include/qerplugin.h b/misc/mediasource/netradiant-src/include/qerplugin.h new file mode 100644 index 00000000..cac311ab --- /dev/null +++ b/misc/mediasource/netradiant-src/include/qerplugin.h @@ -0,0 +1,178 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// QERadiant PlugIns +// +// + +#ifndef __QERPLUGIN_H__ +#define __QERPLUGIN_H__ + +#include "generic/constant.h" + + +// ======================================== +// GTK+ helper functions + +// NOTE: parent can be 0 in all functions but it's best to set them + +// this API does not depend on gtk+ or glib +typedef struct _GtkWidget GtkWidget; + +enum EMessageBoxType +{ + eMB_OK, + eMB_OKCANCEL, + eMB_YESNO, + eMB_YESNOCANCEL, + eMB_NOYES, +}; + +enum EMessageBoxIcon +{ + eMB_ICONDEFAULT, + eMB_ICONERROR, + eMB_ICONWARNING, + eMB_ICONQUESTION, + eMB_ICONASTERISK, +}; + +enum EMessageBoxReturn +{ + eIDOK, + eIDCANCEL, + eIDYES, + eIDNO, +}; + +// simple Message Box, see above for the 'type' flags + +typedef EMessageBoxReturn (* PFN_QERAPP_MESSAGEBOX) (GtkWidget *parent, const char* text, const char* caption/* = "NetRadiant"*/, EMessageBoxType type/* = eMB_OK*/, EMessageBoxIcon icon/* = eMB_ICONDEFAULT*/); + +// file and directory selection functions return null if the user hits cancel +// - 'title' is the dialog title (can be null) +// - 'path' is used to set the initial directory (can be null) +// - 'pattern': the first pattern is for the win32 mode, then comes the Gtk pattern list, see Radiant source for samples +typedef const char* (* PFN_QERAPP_FILEDIALOG) (GtkWidget *parent, bool open, const char* title, const char* path/* = 0*/, const char* pattern/* = 0*/, bool want_load/* = false*/, bool want_import/* = false*/, bool want_save/* = false*/); + +// returns a gchar* string that must be g_free'd by the user +typedef char* (* PFN_QERAPP_DIRDIALOG) (GtkWidget *parent, const char* title/* = "Choose Directory"*/, const char* path/* = 0*/); + +// return true if the user closed the dialog with 'Ok' +// 'color' is used to set the initial value and store the selected value +template class BasicVector3; +typedef BasicVector3 Vector3; +typedef bool (* PFN_QERAPP_COLORDIALOG) (GtkWidget *parent, Vector3& color, + const char* title/* = "Choose Color"*/); + +// load a .bmp file and create a GtkImage widget from it +// NOTE: 'filename' is relative to /plugins/bitmaps/ +typedef struct _GtkImage GtkImage; +typedef GtkImage* (* PFN_QERAPP_NEWIMAGE) (const char* filename); + +// ======================================== + +namespace scene +{ + class Node; +} + +class ModuleObserver; + +#include "signal/signalfwd.h" +#include "windowobserver.h" +#include "generic/vector.h" + +typedef SignalHandler3 MouseEventHandler; +typedef SignalFwd::handler_id_type MouseEventHandlerId; + +enum VIEWTYPE +{ + YZ = 0, + XZ = 1, + XY = 2 +}; + +// the radiant core API +struct _QERFuncTable_1 +{ + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, "radiant"); + + const char* (*getEnginePath)(); + const char* (*getLocalRcPath)(); + const char* (*getGameToolsPath)(); + const char* (*getAppPath)(); + const char* (*getSettingsPath)(); + const char* (*getMapsPath)(); + + const char* (*getGameName)(); + const char* (*getGameMode)(); + + const char* (*getMapName)(); + scene::Node& (*getMapWorldEntity)(); + float (*getGridSize)(); + + const char* (*getGameDescriptionKeyValue)(const char* key); + const char* (*getRequiredGameDescriptionKeyValue)(const char* key); + + void (*attachGameToolsPathObserver)(ModuleObserver& observer); + void (*detachGameToolsPathObserver)(ModuleObserver& observer); + void (*attachEnginePathObserver)(ModuleObserver& observer); + void (*detachEnginePathObserver)(ModuleObserver& observer); + void (*attachGameNameObserver)(ModuleObserver& observer); + void (*detachGameNameObserver)(ModuleObserver& observer); + void (*attachGameModeObserver)(ModuleObserver& observer); + void (*detachGameModeObserver)(ModuleObserver& observer); + + SignalHandlerId (*XYWindowDestroyed_connect)(const SignalHandler& handler); + void (*XYWindowDestroyed_disconnect)(SignalHandlerId id); + MouseEventHandlerId (*XYWindowMouseDown_connect)(const MouseEventHandler& handler); + void (*XYWindowMouseDown_disconnect)(MouseEventHandlerId id); + VIEWTYPE (*XYWindow_getViewType)(); + Vector3 (*XYWindow_windowToWorld)(const WindowVector& position); + const char* (*TextureBrowser_getSelectedShader)(); + + // GTK+ functions + PFN_QERAPP_MESSAGEBOX m_pfnMessageBox; + PFN_QERAPP_FILEDIALOG m_pfnFileDialog; + PFN_QERAPP_DIRDIALOG m_pfnDirDialog; + PFN_QERAPP_COLORDIALOG m_pfnColorDialog; + PFN_QERAPP_NEWIMAGE m_pfnNewImage; + +}; + +#include "modulesystem.h" + +template +class GlobalModule; +typedef GlobalModule<_QERFuncTable_1> GlobalRadiantModule; + +template +class GlobalModuleRef; +typedef GlobalModuleRef<_QERFuncTable_1> GlobalRadiantModuleRef; + +inline _QERFuncTable_1& GlobalRadiant() +{ + return GlobalRadiantModule::getTable(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/include/renderable.cpp b/misc/mediasource/netradiant-src/include/renderable.cpp new file mode 100644 index 00000000..9ca3673f --- /dev/null +++ b/misc/mediasource/netradiant-src/include/renderable.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "renderable.h" + diff --git a/misc/mediasource/netradiant-src/include/renderable.h b/misc/mediasource/netradiant-src/include/renderable.h new file mode 100644 index 00000000..de573910 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/renderable.h @@ -0,0 +1,76 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_RENDERABLE_H) +#define INCLUDED_RENDERABLE_H + +#include "generic/constant.h" + +class Shader; +class OpenGLRenderable; +class LightList; +class Matrix4; + +class Renderer +{ +public: + enum EHighlightMode + { + eFace = 1 << 0, + /*! Full highlighting. */ + ePrimitive = 1 << 1, + }; + + enum EStyle + { + eWireframeOnly, + eFullMaterials, + }; + + virtual void PushState() = 0; + virtual void PopState() = 0; + virtual void SetState(Shader* state, EStyle mode) = 0; + virtual const EStyle getStyle() const = 0; + virtual void Highlight(EHighlightMode mode, bool bEnable = true) = 0; + virtual void setLights(const LightList& lights) + { + } + virtual void addRenderable(const OpenGLRenderable& renderable, const Matrix4& world) = 0; +}; + +class VolumeTest; + +class Renderable +{ +public: + STRING_CONSTANT(Name, "Renderable"); + + virtual void renderSolid(Renderer& renderer, const VolumeTest& volume) const = 0; + virtual void renderWireframe(Renderer& renderer, const VolumeTest& volume) const = 0; + virtual void renderComponents(Renderer&, const VolumeTest&) const + { + } + virtual void viewChanged() const + { + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/include/selectable.cpp b/misc/mediasource/netradiant-src/include/selectable.cpp new file mode 100644 index 00000000..206bebe4 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/selectable.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "selectable.h" + diff --git a/misc/mediasource/netradiant-src/include/selectable.h b/misc/mediasource/netradiant-src/include/selectable.h new file mode 100644 index 00000000..fffcfe29 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/selectable.h @@ -0,0 +1,305 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_SELECTABLE_H) +#define INCLUDED_SELECTABLE_H + +#include + +#include "generic/vector.h" +#include "scenelib.h" +#include "generic/callbackfwd.h" + +class SelectionIntersection +{ + float m_depth; + float m_distance; +public: + SelectionIntersection() : m_depth(1), m_distance(2) + { + } + SelectionIntersection(float depth, float distance) : m_depth(depth), m_distance(distance) + { + } + bool operator<(const SelectionIntersection& other) const + { + if(m_distance != other.m_distance) + { + return m_distance < other.m_distance; + } + if(m_depth != other.m_depth) + { + return m_depth < other.m_depth; + } + return false; + } + bool equalEpsilon(const SelectionIntersection& other, float distanceEpsilon, float depthEpsilon) const + { + return float_equal_epsilon(m_distance, other.m_distance, distanceEpsilon) + && float_equal_epsilon(m_depth, other.m_depth, depthEpsilon); + } + float depth() const + { + return m_depth; + } + bool valid() const + { + return depth() < 1; + } +}; + +// returns true if self is closer than other +inline bool SelectionIntersection_closer(const SelectionIntersection& self, const SelectionIntersection& other) +{ + return self < other; +} + +// assigns other to best if other is closer than best +inline void assign_if_closer(SelectionIntersection& best, const SelectionIntersection& other) +{ + if(SelectionIntersection_closer(other, best)) + { + best = other; + } +} + + + + +class VertexPointer +{ + typedef const unsigned char* byte_pointer; +public: + typedef float elem_type; + typedef const elem_type* pointer; + typedef const elem_type& reference; + + class iterator + { + public: + iterator() {} + iterator(byte_pointer vertices, std::size_t stride) + : m_iter(vertices), m_stride(stride) {} + + bool operator==(const iterator& other) const + { + return m_iter == other.m_iter; + } + bool operator!=(const iterator& other) const + { + return !operator==(other); + } + + iterator operator+(std::size_t i) + { + return iterator(m_iter + i * m_stride, m_stride); + } + iterator operator+=(std::size_t i) + { + m_iter += i * m_stride; + return *this; + } + iterator& operator++() + { + m_iter += m_stride; + return *this; + } + iterator operator++(int) + { + iterator tmp = *this; + m_iter += m_stride; + return tmp; + } + reference operator*() const + { + return *reinterpret_cast(m_iter); + } + private: + byte_pointer m_iter; + std::size_t m_stride; + }; + + VertexPointer(pointer vertices, std::size_t stride) + : m_vertices(reinterpret_cast(vertices)), m_stride(stride) {} + + iterator begin() const + { + return iterator(m_vertices, m_stride); + } + + reference operator[](std::size_t i) const + { + return *reinterpret_cast(m_vertices + m_stride*i); + } + +private: + byte_pointer m_vertices; + std::size_t m_stride; +}; + +class IndexPointer +{ +public: + typedef unsigned int index_type; + typedef const index_type* pointer; + + class iterator + { + public: + iterator(pointer iter) : m_iter(iter) {} + + bool operator==(const iterator& other) const + { + return m_iter == other.m_iter; + } + bool operator!=(const iterator& other) const + { + return !operator==(other); + } + + iterator operator+(std::size_t i) + { + return m_iter + i; + } + iterator operator+=(std::size_t i) + { + return m_iter += i; + } + iterator operator++() + { + return ++m_iter; + } + iterator operator++(int) + { + return m_iter++; + } + const index_type& operator*() const + { + return *m_iter; + } + private: + void increment() + { + ++m_iter; + } + pointer m_iter; + }; + + IndexPointer(pointer indices, std::size_t count) + : m_indices(indices), m_finish(indices + count) {} + + iterator begin() const + { + return m_indices; + } + iterator end() const + { + return m_finish; + } + +private: + pointer m_indices; + pointer m_finish; +}; + +template class BasicVector3; +typedef BasicVector3 Vector3; +class Matrix4; +class VolumeTest; + +class SelectionTest +{ +public: + virtual void BeginMesh(const Matrix4& localToWorld, bool twoSided = false) = 0; + virtual const VolumeTest& getVolume() const = 0; + virtual const Vector3& getNear() const = 0; + virtual const Vector3& getFar() const = 0; + virtual void TestPoint(const Vector3& point, SelectionIntersection& best) = 0; + virtual void TestPolygon(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; + virtual void TestLineLoop(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; + virtual void TestLineStrip(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; + virtual void TestLines(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) = 0; + virtual void TestTriangles(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; + virtual void TestQuads(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; + virtual void TestQuadStrip(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) = 0; +}; + +class Selectable; + +class Selector +{ +public: + virtual void pushSelectable(Selectable& selectable) = 0; + virtual void popSelectable() = 0; + virtual void addIntersection(const SelectionIntersection& intersection) = 0; +}; + +inline void Selector_add(Selector& selector, Selectable& selectable) +{ + selector.pushSelectable(selectable); + selector.addIntersection(SelectionIntersection(0, 0)); + selector.popSelectable(); +} + +inline void Selector_add(Selector& selector, Selectable& selectable, const SelectionIntersection& intersection) +{ + selector.pushSelectable(selectable); + selector.addIntersection(intersection); + selector.popSelectable(); +} + + +class VolumeTest; +class SelectionTestable +{ +public: + STRING_CONSTANT(Name, "SelectionTestable"); + + virtual void testSelect(Selector& selector, SelectionTest& test) = 0; +}; + +inline SelectionTestable* Instance_getSelectionTestable(scene::Instance& instance) +{ + return InstanceTypeCast::cast(instance); +} + + +class Plane3; +typedef Callback1 PlaneCallback; + +class SelectedPlanes +{ +public: + virtual bool contains(const Plane3& plane) const = 0; +}; + +class PlaneSelectable +{ +public: + STRING_CONSTANT(Name, "PlaneSelectable"); + + virtual void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) = 0; + virtual void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) = 0; +}; + + + +#endif diff --git a/misc/mediasource/netradiant-src/include/stream_version.h b/misc/mediasource/netradiant-src/include/stream_version.h new file mode 100644 index 00000000..17ce6339 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/stream_version.h @@ -0,0 +1,3 @@ +// version defines for q3map stream +#define Q3MAP_STREAM_VERSION "1" + diff --git a/misc/mediasource/netradiant-src/include/version.h b/misc/mediasource/netradiant-src/include/version.h new file mode 100644 index 00000000..47134512 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/version.h @@ -0,0 +1,10 @@ +// Makefile appends preprocessor flags instead now +#ifndef RADIANT_VERSION +#error no RADIANT_VERSION defined +#endif +#ifndef RADIANT_MAJOR_VERSION +#error no RADIANT_MAJOR_VERSION defined +#endif +#ifndef RADIANT_MINOR_VERSION +#error no RADIANT_MINOR_VERSION defined +#endif diff --git a/misc/mediasource/netradiant-src/include/warnings.h b/misc/mediasource/netradiant-src/include/warnings.h new file mode 100644 index 00000000..66415614 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/warnings.h @@ -0,0 +1,31 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (INCLUDED_WARNINGS_H) +#define INCLUDED_WARNINGS_H + +#if _MSC_VER > 1000 && defined(WIN32) +#pragma warning(disable:4355) // 'this' : used in base member initializer list +#pragma warning(disable:4503) // '[symbol]' : decorated name length exceeded, name was truncated +#endif + +#endif + diff --git a/misc/mediasource/netradiant-src/include/windowobserver.cpp b/misc/mediasource/netradiant-src/include/windowobserver.cpp new file mode 100644 index 00000000..2e59b8c0 --- /dev/null +++ b/misc/mediasource/netradiant-src/include/windowobserver.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "windowobserver.h" + diff --git a/misc/mediasource/netradiant-src/include/windowobserver.h b/misc/mediasource/netradiant-src/include/windowobserver.h new file mode 100644 index 00000000..99fc03da --- /dev/null +++ b/misc/mediasource/netradiant-src/include/windowobserver.h @@ -0,0 +1,91 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_WINDOWOBSERVER_H) +#define INCLUDED_WINDOWOBSERVER_H + +template class BitFieldValue; +struct ModifierEnumeration; +typedef BitFieldValue ModifierFlags; + +template class EnumeratedValue; +struct ButtonEnumeration; +typedef EnumeratedValue ButtonIdentifier; + + +#include "generic/bitfield.h" + +struct ModifierEnumeration +{ + enum Value + { + SHIFT = 0, + CONTROL = 1, + ALT = 2 + }; +}; + +typedef BitFieldValue ModifierFlags; + +const ModifierFlags c_modifierNone; +const ModifierFlags c_modifierShift(ModifierEnumeration::SHIFT); +const ModifierFlags c_modifierControl(ModifierEnumeration::CONTROL); +const ModifierFlags c_modifierAlt(ModifierEnumeration::ALT); + +#include "generic/enumeration.h" + +struct ButtonEnumeration +{ + enum Value + { + INVALID = 0, + LEFT = 1, + MIDDLE = 3, + RIGHT = 2 + }; +}; + +typedef EnumeratedValue ButtonIdentifier; + +const ButtonIdentifier c_buttonInvalid(ButtonEnumeration::INVALID); +const ButtonIdentifier c_buttonLeft(ButtonEnumeration::LEFT); +const ButtonIdentifier c_buttonMiddle(ButtonEnumeration::MIDDLE); +const ButtonIdentifier c_buttonRight(ButtonEnumeration::RIGHT); + + +template +class BasicVector2; +typedef BasicVector2 Vector2; +typedef Vector2 WindowVector; + +class WindowObserver +{ +public: + virtual void release() = 0; + virtual void onSizeChanged(int width, int height) = 0; + virtual void onMouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) = 0; + virtual void onMouseUp(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) = 0; + virtual void onMouseMotion(const WindowVector& position, ModifierFlags modifiers) = 0; + virtual void onModifierDown(ModifierFlags modifier) = 0; + virtual void onModifierUp(ModifierFlags modifier) = 0; +}; + +#endif diff --git a/misc/mediasource/netradiant-src/install-dlls.sh b/misc/mediasource/netradiant-src/install-dlls.sh new file mode 100644 index 00000000..f83e3862 --- /dev/null +++ b/misc/mediasource/netradiant-src/install-dlls.sh @@ -0,0 +1,193 @@ +#!/bin/sh + +set -ex + +: ${WHICHDLL:=which} +: ${GTKDIR:=/gtk} +: ${CP:=cp} +: ${CAT:=cat} +: ${MKDIR:=mkdir -p} +: ${INSTALLDIR:=.} + +for DLL in \ + freetype6.dll \ + intl.dll \ + libatk-1.0-0.dll \ + libcairo-2.dll \ + libexpat-1.dll \ + libfontconfig-1.dll \ + libgdkglext-win32-1.0-0.dll \ + libgdk_pixbuf-2.0-0.dll \ + libgdk-win32-2.0-0.dll \ + libgio-2.0-0.dll \ + libglib-2.0-0.dll \ + libgmodule-2.0-0.dll \ + libgobject-2.0-0.dll \ + libgthread-2.0-0.dll \ + libgtkglext-win32-1.0-0.dll \ + libgtk-win32-2.0-0.dll \ + libpango-1.0-0.dll \ + libpangocairo-1.0-0.dll \ + libpangoft2-1.0-0.dll \ + libpangowin32-1.0-0.dll \ + libpng14-14.dll \ + libxml2-2.dll \ + zlib1.dll \ +; do + $CP "`$WHICHDLL $DLL`" $INSTALLDIR/ +done + +$MKDIR $INSTALLDIR/etc/fonts +$CAT > $INSTALLDIR/etc/fonts/fonts.conf < + + + + + + + + + WINDOWSFONTDIR + + ~/.fonts + + + + + mono + + + monospace + + + + + + + sans serif + + + sans-serif + + + + + + + sans + + + sans-serif + + + + + conf.d + + + + WINDOWSTEMPDIR_FONTCONFIG_CACHE + ~/.fontconfig + + + + + 0x0020 + 0x00A0 + 0x00AD + 0x034F + 0x0600 + 0x0601 + 0x0602 + 0x0603 + 0x06DD + 0x070F + 0x115F + 0x1160 + 0x1680 + 0x17B4 + 0x17B5 + 0x180E + 0x2000 + 0x2001 + 0x2002 + 0x2003 + 0x2004 + 0x2005 + 0x2006 + 0x2007 + 0x2008 + 0x2009 + 0x200A + 0x200B + 0x200C + 0x200D + 0x200E + 0x200F + 0x2028 + 0x2029 + 0x202A + 0x202B + 0x202C + 0x202D + 0x202E + 0x202F + 0x205F + 0x2060 + 0x2061 + 0x2062 + 0x2063 + 0x206A + 0x206B + 0x206C + 0x206D + 0x206E + 0x206F + 0x2800 + 0x3000 + 0x3164 + 0xFEFF + 0xFFA0 + 0xFFF9 + 0xFFFA + 0xFFFB + + + + 30 + + + + +EOF diff --git a/misc/mediasource/netradiant-src/install-dylibs.sh b/misc/mediasource/netradiant-src/install-dylibs.sh new file mode 100644 index 00000000..798a7d14 --- /dev/null +++ b/misc/mediasource/netradiant-src/install-dylibs.sh @@ -0,0 +1,71 @@ +#!/bin/sh + +set -ex + +: ${OTOOL:=otool} +: ${CP:=cp} +: ${INSTALLDIR:=.} +: ${EXE:=ppc} +: ${MACLIBDIR:=/sw/lib} +: ${CAT:=cat} + + +finkgetdeps() +{ + otool -L "$1" | grep "$MACLIBDIR" | while read -r LIB STUFF; do + [ -z "${LIB##*:}" ] && continue # first line + [ -f "$INSTALLDIR/${LIB##*/}" ] && continue + cp -vL "$LIB" "$INSTALLDIR" + finkgetdeps "$LIB" + done +} + + +finkgetdeps "$INSTALLDIR/radiant.$EXE" +echo Warning: this only works if only ONE version of gtk-2.0 and pango is installed + +for LIB in "$MACLIBDIR"/gtk-2.0/*/loaders/libpixbufloader-bmp.so; do + LAST=$LIB +done +cp -L "$LAST" "$INSTALLDIR" +finkgetdeps "$LAST" + +for LIB in "$MACLIBDIR"/pango/*/modules/pango-basic-fc.so; do + LAST=$LIB +done +cp -L "$LAST" "$INSTALLDIR" +finkgetdeps "$LAST" + +for LIB in "$MACLIBDIR"/pango/*/modules/pango-basic-x.so; do + LAST=$LIB +done +cp -L "$LAST" "$INSTALLDIR" +finkgetdeps "$LAST" + +cp -L "$MACLIBDIR"/../etc/fonts/fonts.conf "$INSTALLDIR" +cp -L "$MACLIBDIR"/../etc/fonts/fonts.dtd "$INSTALLDIR" +cp -L "$MACLIBDIR"/../etc/gtk-2.0/gdk-pixbuf.loaders "$INSTALLDIR" +cp -L "$MACLIBDIR"/../etc/pango/pangorc "$INSTALLDIR" + +$CAT > "$INSTALLDIR/../netradiant.sh" < +class SingleByteInputStream +{ + typedef typename InputStreamType::byte_type byte_type; + + InputStreamType& m_inputStream; + byte_type m_buffer[SIZE]; + byte_type* m_cur; + byte_type* m_end; + +public: + + SingleByteInputStream(InputStreamType& inputStream) : m_inputStream(inputStream), m_cur(m_buffer + SIZE), m_end(m_cur) + { + } + bool readByte(byte_type& b) + { + if(m_cur == m_end) + { + if(m_end != m_buffer + SIZE) + { + return false; + } + + m_end = m_buffer + m_inputStream.read(m_buffer, SIZE); + 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/misc/mediasource/netradiant-src/libs/bytebool.cpp b/misc/mediasource/netradiant-src/libs/bytebool.cpp new file mode 100644 index 00000000..036061fe --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/bytebool.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 1999-2006 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 "bytebool.h" diff --git a/misc/mediasource/netradiant-src/libs/bytebool.h b/misc/mediasource/netradiant-src/libs/bytebool.h new file mode 100644 index 00000000..4009c2dd --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/bytebool.h @@ -0,0 +1,32 @@ +/* +Copyright (C) 1999-2006 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 __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/misc/mediasource/netradiant-src/libs/bytestreamutils.cpp b/misc/mediasource/netradiant-src/libs/bytestreamutils.cpp new file mode 100644 index 00000000..f9b8ddca --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/bytestreamutils.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "bytestreamutils.h" diff --git a/misc/mediasource/netradiant-src/libs/bytestreamutils.h b/misc/mediasource/netradiant-src/libs/bytestreamutils.h new file mode 100644 index 00000000..aad7d7e4 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/bytestreamutils.h @@ -0,0 +1,129 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_BYTESTREAMUTILS_H) +#define INCLUDED_BYTESTREAMUTILS_H + +#if defined(__GNUC__) + +#define _ISOC9X_SOURCE 1 +#define _ISOC99_SOURCE 1 + +#define __USE_ISOC9X 1 +#define __USE_ISOC99 1 + +#include + +#endif + +#include + +// if C99 is unavailable, fall back to the types most likely to be the right sizes +#if !defined(int16_t) +typedef signed short int16_t; +#endif +#if !defined(uint16_t) +typedef unsigned short uint16_t; +#endif +#if !defined(int32_t) +typedef signed int int32_t; +#endif +#if !defined(uint32_t) +typedef unsigned int uint32_t; +#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/misc/mediasource/netradiant-src/libs/character.cpp b/misc/mediasource/netradiant-src/libs/character.cpp new file mode 100644 index 00000000..ab8969b6 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/character.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "character.h" + diff --git a/misc/mediasource/netradiant-src/libs/character.h b/misc/mediasource/netradiant-src/libs/character.h new file mode 100644 index 00000000..1e6d3b16 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/character.h @@ -0,0 +1,47 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/cmdlib.h b/misc/mediasource/netradiant-src/libs/cmdlib.h new file mode 100644 index 00000000..8961bd2a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/cmdlib.h @@ -0,0 +1,103 @@ +/* +Copyright (C) 1999-2006 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, bool waitfor); + +// 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/misc/mediasource/netradiant-src/libs/cmdlib/.cvswrappers b/misc/mediasource/netradiant-src/libs/cmdlib/.cvswrappers new file mode 100644 index 00000000..ed97d402 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/cmdlib/.cvswrappers @@ -0,0 +1,3 @@ +*.dsp -m 'COPY' -k 'b' +*.dsw -m 'COPY' -k 'b' +*.scc -m 'COPY' -k 'b' diff --git a/misc/mediasource/netradiant-src/libs/cmdlib/cmdlib.cpp b/misc/mediasource/netradiant-src/libs/cmdlib/cmdlib.cpp new file mode 100644 index 00000000..f6ace0fe --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/cmdlib/cmdlib.cpp @@ -0,0 +1,140 @@ +/* +Copyright (C) 1999-2006 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" + + +#if defined (POSIX) + +#include +#include +#include + +bool Q_Exec(const char *cmd, char *cmdline, const char *, bool, bool waitfor) +{ + char fullcmd[2048]; + char *pCmd; + pid_t pid; +#ifdef _DEBUG + printf("Q_Exec damnit\n"); +#endif + switch ((pid = fork())) + { + default: + if(waitfor) + waitpid(pid, NULL, 0); + break; + 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; +} + +#elif defined(WIN32) + +#include + +// NOTE TTimo windows is VERY nitpicky about the syntax in CreateProcess +bool Q_Exec(const char *cmd, char *cmdline, const char *execdir, bool bCreateConsole, bool waitfor) +{ + 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 + )) + { + if(waitfor) + WaitForSingleObject(ProcessInformation.hProcess, INFINITE); + return true; + } + return false; +} + +#endif + diff --git a/misc/mediasource/netradiant-src/libs/container/array.cpp b/misc/mediasource/netradiant-src/libs/container/array.cpp new file mode 100644 index 00000000..378a2e76 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/array.cpp @@ -0,0 +1,39 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/container/array.h b/misc/mediasource/netradiant-src/libs/container/array.h new file mode 100644 index 00000000..de444fd8 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/array.h @@ -0,0 +1,197 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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) + { + if(other.size() == size()) + { + std::copy(other.begin(), other.end(), begin()); + } + else + { + 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/misc/mediasource/netradiant-src/libs/container/cache.cpp b/misc/mediasource/netradiant-src/libs/container/cache.cpp new file mode 100644 index 00000000..a704287e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/cache.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "cache.h" diff --git a/misc/mediasource/netradiant-src/libs/container/cache.h b/misc/mediasource/netradiant-src/libs/container/cache.h new file mode 100644 index 00000000..8c594b88 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/cache.h @@ -0,0 +1,206 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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. +/// \param CreationPolicy Must define 'Cached* construct(const Key&)' and 'void destroy(Cached*)'. The lifetime of the \c Key passed to 'construct' is guaranteed to be longer than the subsequent matched call to 'destroy'. +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) + { +#if 0 + Element& elem = m_map[key]; + if(elem.increment() == 1) + { + elem.set(CreationPolicy::construct(key)); + } + return elem; +#else + iterator i = m_map.insert(key, Element()); + if((*i).value.increment() == 1) + { + (*i).value.set(CreationPolicy::construct((*i).key)); + } + return (*i).value; +#endif + } +#else + value_type& capture(const Key& key) + { + iterator i = m_map.find(key); + if(i == m_map.end()) + { + i = m_map.insert(key, Element()); + (*i).value.set(CreationPolicy::construct((*i).key)); + } + (*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/misc/mediasource/netradiant-src/libs/container/container.cpp b/misc/mediasource/netradiant-src/libs/container/container.cpp new file mode 100644 index 00000000..627e0c88 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/container.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "container.h" + diff --git a/misc/mediasource/netradiant-src/libs/container/container.h b/misc/mediasource/netradiant-src/libs/container/container.h new file mode 100644 index 00000000..b6d75841 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/container.h @@ -0,0 +1,393 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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); + } +} + +template +class ReferencePair +{ + Type* m_first; + Type* m_second; +public: + ReferencePair() : m_first(0), m_second(0) + { + } + void attach(Type& t) + { + ASSERT_MESSAGE(m_first == 0 || m_second == 0, "ReferencePair::insert: pointer already exists"); + if(m_first == 0) + { + m_first = &t; + } + else if(m_second == 0) + { + m_second = &t; + } + } + void detach(Type& t) + { + ASSERT_MESSAGE(m_first == &t || m_second == &t, "ReferencePair::erase: pointer not found"); + if(m_first == &t) + { + m_first = 0; + } + else if(m_second == &t) + { + m_second = 0; + } + } + template + void forEach(const Functor& functor) + { + if(m_second != 0) + { + functor(*m_second); + } + if(m_first != 0) + { + functor(*m_first); + } + } +}; + + +#endif diff --git a/misc/mediasource/netradiant-src/libs/container/hashfunc.cpp b/misc/mediasource/netradiant-src/libs/container/hashfunc.cpp new file mode 100644 index 00000000..20569cd1 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/hashfunc.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "hashfunc.h" diff --git a/misc/mediasource/netradiant-src/libs/container/hashfunc.h b/misc/mediasource/netradiant-src/libs/container/hashfunc.h new file mode 100644 index 00000000..a4ec5fee --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/hashfunc.h @@ -0,0 +1,434 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_CONTAINER_HASHFUNC_H) +#define INCLUDED_CONTAINER_HASHFUNC_H + +#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)); + } +}; + +// lookup2.c +// By Bob Jenkins, 1996. bob_jenkins@burtleburtle.net. You may use this +// code any way you wish, private, educational, or commercial. It's free. + +#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 RawStringHash +{ + typedef hash_t hash_type; + hash_type operator()(const char* string) const + { + return string_hash(string); + } +}; + +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/misc/mediasource/netradiant-src/libs/container/hashtable.cpp b/misc/mediasource/netradiant-src/libs/container/hashtable.cpp new file mode 100644 index 00000000..e4d02c93 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/hashtable.cpp @@ -0,0 +1,65 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/container/hashtable.h b/misc/mediasource/netradiant-src/libs/container/hashtable.h new file mode 100644 index 00000000..88d672cf --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/hashtable.h @@ -0,0 +1,474 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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() const + { + return static_cast(next); + } + BucketNode* getPrev() const + { + 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*() const + { + return m_node->m_value; + } + value_type* operator->() const + { + 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. + 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) + { + 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/misc/mediasource/netradiant-src/libs/container/stack.cpp b/misc/mediasource/netradiant-src/libs/container/stack.cpp new file mode 100644 index 00000000..3a7c7ce2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/stack.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "stack.h" + diff --git a/misc/mediasource/netradiant-src/libs/container/stack.h b/misc/mediasource/netradiant-src/libs/container/stack.h new file mode 100644 index 00000000..d83674c3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/container/stack.h @@ -0,0 +1,239 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/convert.cpp b/misc/mediasource/netradiant-src/libs/convert.cpp new file mode 100644 index 00000000..0e73aef7 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/convert.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "convert.h" + diff --git a/misc/mediasource/netradiant-src/libs/convert.h b/misc/mediasource/netradiant-src/libs/convert.h new file mode 100644 index 00000000..f7f4f992 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/convert.h @@ -0,0 +1,305 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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.first; p != convert.m_range.last;) + { + 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.first; p != convert.m_range.last; ++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/misc/mediasource/netradiant-src/libs/ddslib.h b/misc/mediasource/netradiant-src/libs/ddslib.h new file mode 100644 index 00000000..3f5f124c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/ddslib.h @@ -0,0 +1,250 @@ +/* ----------------------------------------------------------------------------- + +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/misc/mediasource/netradiant-src/libs/ddslib/ddslib.c b/misc/mediasource/netradiant-src/libs/ddslib/ddslib.c new file mode 100644 index 00000000..424faeea --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/ddslib/ddslib.c @@ -0,0 +1,781 @@ +/* ----------------------------------------------------------------------------- + +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*) ((char *) 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*) ((char *) 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*) ((char *) 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/misc/mediasource/netradiant-src/libs/debugging/debugging.cpp b/misc/mediasource/netradiant-src/libs/debugging/debugging.cpp new file mode 100644 index 00000000..23784950 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/debugging/debugging.cpp @@ -0,0 +1,28 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "debugging.h" + +void TEST_ASSERT() +{ + ERROR_MESSAGE("test"); + ASSERT_NOTNULL(0); +} diff --git a/misc/mediasource/netradiant-src/libs/debugging/debugging.h b/misc/mediasource/netradiant-src/libs/debugging/debugging.h new file mode 100644 index 00000000..4c03e9d7 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/debugging/debugging.h @@ -0,0 +1,137 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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 STR(x) #x +#define STR2(x) STR(x) +#define FILE_LINE __FILE__ ":" STR2(__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) do{\ +if(!(condition))\ +{\ + globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nassertion failure: " << message << "\n";\ + if(!globalDebugMessageHandler().handleMessage()) { DEBUGGER_BREAKPOINT(); }\ +}} while(0) + +/// \brief Sends a \p message to the current debug-message-handler text-output-stream. +#define ERROR_MESSAGE(message) do{\ +globalDebugMessageHandler().getOutputStream() << FILE_LINE "\nruntime error: " << message << "\n";\ +if(!globalDebugMessageHandler().handleMessage()) { DEBUGGER_BREAKPOINT(); }} while(0) + +#define ASSERT_NOTNULL(ptr) ASSERT_MESSAGE(ptr != 0, "pointer \"" #ptr "\" is null") + +#else + +#define ASSERT_MESSAGE(condition, message) +#define ERROR_MESSAGE(message) +#define ASSERT_NOTNULL(ptr) + +#endif + +#endif diff --git a/misc/mediasource/netradiant-src/libs/dragplanes.cpp b/misc/mediasource/netradiant-src/libs/dragplanes.cpp new file mode 100644 index 00000000..9c7e18f8 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/dragplanes.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "dragplanes.h" + diff --git a/misc/mediasource/netradiant-src/libs/dragplanes.h b/misc/mediasource/netradiant-src/libs/dragplanes.h new file mode 100644 index 00000000..a8b54dc1 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/dragplanes.h @@ -0,0 +1,259 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_DRAGPLANES_H) +#define INCLUDED_DRAGPLANES_H + +#include "selectable.h" +#include "selectionlib.h" +#include "math/aabb.h" +#include "math/line.h" + +// local must be a pure rotation +inline Vector3 translation_to_local(const Vector3& translation, const Matrix4& local) +{ + return matrix4_get_translation_vec3( + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3(matrix4_transposed(local), translation), + local + ) + ); +} + +// local must be a pure rotation +inline Vector3 translation_from_local(const Vector3& translation, const Matrix4& local) +{ + return matrix4_get_translation_vec3( + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3(local, translation), + matrix4_transposed(local) + ) + ); +} + +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 + AABB m_bounds; + + 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, const Matrix4& rotation = g_matrix4_identity) + { + Line line(test.getNear(), test.getFar()); + Vector3 corners[8]; + aabb_corners_oriented(aabb, rotation, corners); + + Plane3 planes[6]; + aabb_planes_oriented(aabb, rotation, 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); + selectedPlaneCallback(planes[5]); + //globalOutputStream() << "bottom\n"; + } + + m_bounds = aabb; + } + void selectReversedPlanes(const AABB& aabb, Selector& selector, const SelectedPlanes& selectedPlanes, const Matrix4& rotation = g_matrix4_identity) + { + Plane3 planes[6]; + aabb_planes_oriented(aabb, rotation, 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); + } + } + AABB evaluateResize(const Vector3& translation) const + { + Vector3 min = m_bounds.origin - m_bounds.extents; + Vector3 max = m_bounds.origin + m_bounds.extents; + if(m_bounds.extents[0] != 0) + { + if(m_selectable_right.isSelected()) + { + max[0] += translation[0]; + //globalOutputStream() << "moving right\n"; + } + if(m_selectable_left.isSelected()) + { + min[0] += translation[0]; + //globalOutputStream() << "moving left\n"; + } + } + if(m_bounds.extents[1] != 0) + { + if(m_selectable_front.isSelected()) + { + max[1] += translation[1]; + //globalOutputStream() << "moving front\n"; + } + if(m_selectable_back.isSelected()) + { + min[1] += translation[1]; + //globalOutputStream() << "moving back\n"; + } + } + if(m_bounds.extents[2] != 0) + { + if(m_selectable_top.isSelected()) + { + max[2] += translation[2]; + //globalOutputStream() << "moving top\n"; + } + if(m_selectable_bottom.isSelected()) + { + min[2] += translation[2]; + //globalOutputStream() << "moving bottom\n"; + } + } + + return AABB(vector3_mid(min, max), vector3_scaled(vector3_subtracted(max, min), 0.5)); + } + AABB evaluateResize(const Vector3& translation, const Matrix4& rotation) const + { + AABB aabb(evaluateResize(translation_to_local(translation, rotation))); + aabb.origin = m_bounds.origin + translation_from_local(aabb.origin - m_bounds.origin, rotation); + return aabb; + } + Matrix4 evaluateTransform(const Vector3& translation) const + { + AABB aabb(evaluateResize(translation)); + Vector3 scale( + m_bounds.extents[0] != 0 ? aabb.extents[0] / m_bounds.extents[0] : 1, + m_bounds.extents[1] != 0 ? aabb.extents[1] / m_bounds.extents[1] : 1, + m_bounds.extents[2] != 0 ? aabb.extents[2] / m_bounds.extents[2] : 1 + ); + + Matrix4 matrix(matrix4_translation_for_vec3(aabb.origin - m_bounds.origin)); + matrix4_pivoted_scale_by_vec3(matrix, scale, m_bounds.origin); + + return matrix; + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/libs/eclasslib.cpp b/misc/mediasource/netradiant-src/libs/eclasslib.cpp new file mode 100644 index 00000000..a320bc26 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/eclasslib.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 1999-2006 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 "eclasslib.h" diff --git a/misc/mediasource/netradiant-src/libs/eclasslib.h b/misc/mediasource/netradiant-src/libs/eclasslib.h new file mode 100644 index 00000000..7bee547b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/eclasslib.h @@ -0,0 +1,341 @@ +/* +Copyright (C) 1999-2006 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 (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/misc/mediasource/netradiant-src/libs/entitylib.cpp b/misc/mediasource/netradiant-src/libs/entitylib.cpp new file mode 100644 index 00000000..385d0f2e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/entitylib.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "entitylib.h" diff --git a/misc/mediasource/netradiant-src/libs/entitylib.h b/misc/mediasource/netradiant-src/libs/entitylib.h new file mode 100644 index 00000000..667adf72 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/entitylib.h @@ -0,0 +1,756 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (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/pooledstring.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_forward, const Vector3& direction_left, const Vector3& direction_up) +{ + Vector3 endpoint(vector3_added(origin, vector3_scaled(direction_forward, 32.0))); + + Vector3 tip1(vector3_added(vector3_added(endpoint, vector3_scaled(direction_forward, -8.0)), vector3_scaled(direction_up, -4.0))); + Vector3 tip2(vector3_added(tip1, vector3_scaled(direction_up, 8.0))); + Vector3 tip3(vector3_added(vector3_added(endpoint, vector3_scaled(direction_forward, -8.0)), vector3_scaled(direction_left, -4.0))); + Vector3 tip4(vector3_added(tip3, vector3_scaled(direction_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]) +{ + unsigned int indices[26] = { + 0, 1, 1, 2, 2, 3, 3, 0, + 4, 5, 5, 6, 6, 7, 7, 4, + 0, 4, 1, 5, 2, 6, 3, 7, + // 0, 6, 1, 7, 2, 4, 3, 5 // X cross + 1, 7 // diagonal line (connect mins to maxs corner) + }; +#if 1 + glVertexPointer(3, GL_FLOAT, 0, points); + glDrawElements(GL_LINES, sizeof(indices)/sizeof(indices[0]), GL_UNSIGNED_INT, indices); +#else + glBegin(GL_LINES); + for(std::size_t i = 0; i < sizeof(indices)/sizeof(indices[0]); ++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); + } +}; + + +/// \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 : public EntityKeyValue +{ + 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; + + static StringPool& getPool() + { + return Static::instance(); + } +private: + static EntityCreator::KeyValueChangedFunc m_entityKeyValueChanged; + static Counter* m_counter; + + EntityClass* m_eclass; + + class KeyContext{}; + typedef Static KeyPool; + typedef PooledString Key; + 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()); + } + + Key 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: + bool m_isContainer; + + EntityKeyValues(EntityClass* eclass) : + m_eclass(eclass), + m_undo(m_keyValues, UndoImportCaller(*this)), + m_instanced(false), + m_observerMutex(false), + m_isContainer(!eclass->fixedsize) + { + } + EntityKeyValues(const EntityKeyValues& other) : + Entity(other), + m_eclass(&other.getEntityClass()), + m_undo(m_keyValues, UndoImportCaller(*this)), + m_instanced(false), + m_observerMutex(false), + m_isContainer(other.m_isContainer) + { + 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() + { + for(Observers::iterator i = m_observers.begin(); i != m_observers.end();) + { + // post-increment to allow current element to be removed safely + (*i++)->clear(); + } + 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); + } + + bool isContainer() const + { + return m_isContainer; + } +}; + +/// \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/misc/mediasource/netradiant-src/libs/entityxml.cpp b/misc/mediasource/netradiant-src/libs/entityxml.cpp new file mode 100644 index 00000000..175c4818 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/entityxml.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "entityxml.h" diff --git a/misc/mediasource/netradiant-src/libs/entityxml.h b/misc/mediasource/netradiant-src/libs/entityxml.h new file mode 100644 index 00000000..50df739b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/entityxml.h @@ -0,0 +1,108 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/fs_filesystem.cpp b/misc/mediasource/netradiant-src/libs/fs_filesystem.cpp new file mode 100644 index 00000000..f0820982 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/fs_filesystem.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "fs_filesystem.h" diff --git a/misc/mediasource/netradiant-src/libs/fs_filesystem.h b/misc/mediasource/netradiant-src/libs/fs_filesystem.h new file mode 100644 index 00000000..0c22a4b3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/fs_filesystem.h @@ -0,0 +1,183 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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(StringRange range) + : m_path(range), 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() : m_file(0) + { + } + 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; + typedef Entry entry_type; + + iterator begin() + { + return m_entries.begin(); + } + iterator end() + { + return m_entries.end(); + } + + /// \brief Returns the file at \p path. + /// Creates all directories below \p path if they do not exist. + /// O(log n) on average. + entry_type& operator[](const Path& path) + { + { + const char* end = path_remove_directory(path.c_str()); + while(end[0] != '\0') + { + Path dir(StringRange(path.c_str(), end)); + m_entries.insert(value_type(dir, Entry(0))); + end = path_remove_directory(end); + } + } + + return m_entries[path]; + } + + /// \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/misc/mediasource/netradiant-src/libs/fs_path.cpp b/misc/mediasource/netradiant-src/libs/fs_path.cpp new file mode 100644 index 00000000..5cd36406 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/fs_path.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "fs_path.h" diff --git a/misc/mediasource/netradiant-src/libs/fs_path.h b/misc/mediasource/netradiant-src/libs/fs_path.h new file mode 100644 index 00000000..df409ef0 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/fs_path.h @@ -0,0 +1,92 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/generic/arrayrange.cpp b/misc/mediasource/netradiant-src/libs/generic/arrayrange.cpp new file mode 100644 index 00000000..b04ba068 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/arrayrange.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "arrayrange.h" + diff --git a/misc/mediasource/netradiant-src/libs/generic/arrayrange.h b/misc/mediasource/netradiant-src/libs/generic/arrayrange.h new file mode 100644 index 00000000..a05489a1 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/arrayrange.h @@ -0,0 +1,74 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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 first, Iterator last) + : first(first), last(last) + { + } + Iterator first; + Iterator last; +}; + +template +inline ArrayRange makeArrayRange(Element* first, Element* last) +{ + return ArrayRange(first, last); +} + +template +struct ArrayConstRange +{ + typedef const Element* Iterator; + ArrayConstRange(Iterator first, Iterator last) + : first(first), last(last) + { + } + Iterator first; + Iterator last; +}; + +template +inline ArrayConstRange makeArrayRange(const Element* first, const Element* last) +{ + return ArrayConstRange(first, last); +} + +#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))) + +typedef ArrayRange StringRange; + +#endif diff --git a/misc/mediasource/netradiant-src/libs/generic/bitfield.cpp b/misc/mediasource/netradiant-src/libs/generic/bitfield.cpp new file mode 100644 index 00000000..96d15c9c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/bitfield.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "bitfield.h" + diff --git a/misc/mediasource/netradiant-src/libs/generic/bitfield.h b/misc/mediasource/netradiant-src/libs/generic/bitfield.h new file mode 100644 index 00000000..652f0539 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/bitfield.h @@ -0,0 +1,133 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/generic/callback.cpp b/misc/mediasource/netradiant-src/libs/generic/callback.cpp new file mode 100644 index 00000000..2344830a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/callback.cpp @@ -0,0 +1,285 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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 + +namespace +{ + class A1 + { + }; + class A2 + { + }; + class A3 + { + }; + class A4 + { + }; + + class Test + { + public: + void test0() + { + } + typedef Member Test0; + typedef MemberCaller Test0Caller; + void test0const() const + { + } + typedef ConstMember Test0Const; + typedef ConstMemberCaller Test0ConstCaller; + void test1(A1) + { + } + typedef Member1 Test1; + typedef MemberCaller1 Test1Caller; + void test1const(A1) const + { + } + typedef ConstMember1 Test1Const; + typedef ConstMemberCaller1 Test1ConstCaller; + void test2(A1, A2) + { + } + typedef Member2 Test2; + void test2const(A1, A2) const + { + } + typedef ConstMember2 Test2Const; + void test3(A1, A2, A3) + { + } + typedef Member3 Test3; + void test3const(A1, A2, A3) const + { + } + typedef ConstMember3 Test3Const; + }; + + void test0free() + { + } + typedef FreeCaller<&test0free> Test0FreeCaller; + void test1free(A1) + { + } + typedef FreeCaller1 Test1FreeCaller; + void test2free(A1, A2) + { + } + typedef Function2 Test2Free; + void test3free(A1, A2, A3) + { + } + typedef Function3 Test3Free; + + + void test0(Test& test) + { + } + typedef ReferenceCaller Test0Caller; + + void test0const(const Test& test) + { + } + typedef ConstReferenceCaller Test0ConstCaller; + + void test0p(Test* test) + { + } + typedef PointerCaller Test0PCaller; + + void test0constp(const Test* test) + { + } + typedef ConstPointerCaller Test0ConstPCaller; + + void test1(Test& test, A1) + { + } + typedef ReferenceCaller1 Test1Caller; + + void test1const(const Test& test, A1) + { + } + typedef ConstReferenceCaller1 Test1ConstCaller; + + void test1p(Test* test, A1) + { + } + typedef PointerCaller1 Test1PCaller; + + void test1constp(const Test* test, A1) + { + } + typedef ConstPointerCaller1 Test1ConstPCaller; + + void test2(Test& test, A1, A2) + { + } + typedef Function3 Test2; + + void test3(Test& test, A1, A2, A3) + { + } + typedef Function4 Test3; + + void instantiate() + { + Test test; + const Test& testconst = test; + { + Callback a = Test0FreeCaller(); + Callback b = Test::Test0Caller(test); + b = makeCallback0(Test::Test0(), test); + Callback c = Test::Test0ConstCaller(testconst); + c = makeCallback0(Test::Test0Const(), test); + Callback d = Test0Caller(test); + Callback e = Test0ConstCaller(testconst); + Callback f = Test0PCaller(&test); + Callback g = Test0ConstPCaller(&testconst); + a(); + bool u = a != b; + } + { + typedef Callback1 TestCallback1; + TestCallback1 a = Test1FreeCaller(); + TestCallback1 b = Test::Test1Caller(test); + b = makeCallback1(Test::Test1(), test); + TestCallback1 c = Test::Test1ConstCaller(testconst); + c = makeCallback1(Test::Test1Const(), test); + TestCallback1 d = Test1Caller(test); + TestCallback1 e = Test1ConstCaller(testconst); + TestCallback1 f = Test1PCaller(&test); + TestCallback1 g = Test1ConstPCaller(&testconst); + a(A1()); + bool u = a != b; + } + { + typedef Callback2 TestCallback2; + TestCallback2 a = makeStatelessCallback2(Test2Free()); + TestCallback2 b = makeCallback2(Test2(), test); + TestCallback2 c = makeCallback2(Test::Test2(), test); + TestCallback2 d = makeCallback2(Test::Test2Const(), test); + a(A1(), A2()); + bool u = a != b; + } + { + typedef Callback3 TestCallback3; + TestCallback3 a = makeStatelessCallback3(Test3Free()); + TestCallback3 b = makeCallback3(Test3(), test); + TestCallback3 c = makeCallback3(Test::Test3(), test); + TestCallback3 d = makeCallback3(Test::Test3Const(), test); + a(A1(), A2(), A3()); + bool u = a != b; + } + } +} diff --git a/misc/mediasource/netradiant-src/libs/generic/callback.h b/misc/mediasource/netradiant-src/libs/generic/callback.h new file mode 100644 index 00000000..7141da4a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/callback.h @@ -0,0 +1,670 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GENERIC_CLOSURE_H) +#define INCLUDED_GENERIC_CLOSURE_H + +/// \file +/// \brief Type-safe techniques for binding the first argument of an opaque callback. + +#include +#include "functional.h" +#include "callbackfwd.h" + +template +inline void* convertToOpaque(Type* t) +{ + return t; +} +template +inline void* convertToOpaque(const Type* t) +{ + return const_cast(t); +} +template +inline void* convertToOpaque(Type& t) +{ + return &t; +} +template +inline void* convertToOpaque(const Type& t) +{ + return const_cast(&t); +} + + +template +class ConvertFromOpaque +{ +}; + +template +class ConvertFromOpaque +{ +public: + static Type& apply(void* p) + { + return *static_cast(p); + } +}; + +template +class ConvertFromOpaque +{ +public: + static const Type& apply(void* p) + { + return *static_cast(p); + } +}; + + +template +class ConvertFromOpaque +{ +public: + static Type* apply(void* p) + { + return static_cast(p); + } +}; + +template +class ConvertFromOpaque +{ +public: + static const Type* apply(void* p) + { + return static_cast(p); + } +}; + +template +class BindFirstOpaque +{ + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; +public: + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque(FirstBound firstBound) : firstBound(firstBound) + { + } + result_type operator()() const + { + return Caller::call(firstBound); + } + FirstBound getBound() const + { + return firstBound; + } + static result_type thunk(void* environment) + { + return Caller::call(ConvertFromOpaque::apply(environment)); + } + void* getEnvironment() const + { + return convertToOpaque(firstBound); + } +}; + +template +class BindFirstOpaque1 +{ + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; +public: + typedef typename Caller::second_argument_type first_argument_type; + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque1(FirstBound firstBound) : firstBound(firstBound) + { + } + result_type operator()(first_argument_type a1) const + { + return Caller::call(firstBound, a1); + } + FirstBound getBound() const + { + return firstBound; + } + static result_type thunk(void* environment, first_argument_type a1) + { + return Caller::call(ConvertFromOpaque::apply(environment), a1); + } + void* getEnvironment() const + { + return convertToOpaque(firstBound); + } +}; + +template +class BindFirstOpaque2 +{ + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; +public: + typedef typename Caller::second_argument_type first_argument_type; + typedef typename Caller::third_argument_type second_argument_type; + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque2(FirstBound firstBound) : firstBound(firstBound) + { + } + result_type operator()(first_argument_type a1, second_argument_type a2) const + { + return Caller::call(firstBound, a1, a2); + } + FirstBound getBound() const + { + return firstBound; + } + static result_type thunk(void* environment, first_argument_type a1, second_argument_type a2) + { + return Caller::call(ConvertFromOpaque::apply(environment), a1, a2); + } + void* getEnvironment() const + { + return convertToOpaque(firstBound); + } +}; + +template +class BindFirstOpaque3 +{ + typedef typename Caller::first_argument_type FirstBound; + FirstBound firstBound; +public: + typedef typename Caller::second_argument_type first_argument_type; + typedef typename Caller::third_argument_type second_argument_type; + typedef typename Caller::fourth_argument_type third_argument_type; + typedef typename Caller::result_type result_type; + explicit BindFirstOpaque3(FirstBound firstBound) : firstBound(firstBound) + { + } + result_type operator()(first_argument_type a1, second_argument_type a2, third_argument_type a3) const + { + return Caller::call(firstBound, a1, a2, a3); + } + FirstBound getBound() const + { + return firstBound; + } + static result_type thunk(void* environment, first_argument_type a1, second_argument_type a2, third_argument_type a3) + { + return Caller::call(ConvertFromOpaque::apply(environment), a1, a2, a3); + } + void* getEnvironment() const + { + return convertToOpaque(firstBound); + } +}; + +template +class CallbackBase +{ + void* m_environment; + Thunk_ m_thunk; +public: + typedef Thunk_ Thunk; + CallbackBase(void* environment, Thunk function) : m_environment(environment), m_thunk(function) + { + } + void* getEnvironment() const + { + return m_environment; + } + Thunk getThunk() const + { + return m_thunk; + } +}; + +template +inline bool operator==(const CallbackBase& self, const CallbackBase& other) +{ + return self.getEnvironment() == other.getEnvironment() && self.getThunk() == other.getThunk(); +} +template +inline bool operator!=(const CallbackBase& self, const CallbackBase& other) +{ + return !(self == other); +} +template +inline bool operator<(const CallbackBase& self, const CallbackBase& 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. +/// +/// Use with the callback constructors MemberCaller, ConstMemberCaller, ReferenceCaller, ConstReferenceCaller, PointerCaller, ConstPointerCaller and FreeCaller. +template +class Callback0 : public CallbackBase +{ + typedef CallbackBase Base; + static Result nullThunk(void*) + { + } + +public: + typedef Result result_type; + + Callback0() : Base(0, nullThunk) + { + } + template + Callback0(const BindFirstOpaque& caller) : Base(caller.getEnvironment(), BindFirstOpaque::thunk) + { + } + Callback0(void* environment, typename Base::Thunk function) : Base(environment, function) + { + } + result_type operator()() const + { + return Base::getThunk()(Base::getEnvironment()); + } +}; + +template +inline Callback0 makeCallback0(const Caller& caller, typename Caller::first_argument_type callee) +{ + return Callback0(BindFirstOpaque(callee)); +} +template +inline Callback0 makeStatelessCallback0(const Caller& caller) +{ + return makeCallback0(Caller0To1(), 0); +} + +typedef Callback0 Callback; + + + +/// \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 : public CallbackBase +{ + typedef CallbackBase Base; + static Result nullThunk(void*, FirstArgument) + { + } + +public: + typedef FirstArgument first_argument_type; + typedef Result result_type; + + Callback1() : Base(0, nullThunk) + { + } + template + Callback1(const BindFirstOpaque1& caller) : Base(caller.getEnvironment(), BindFirstOpaque1::thunk) + { + } + Callback1(void* environment, typename Base::Thunk function) : Base(environment, function) + { + } + result_type operator()(FirstArgument firstArgument) const + { + return Base::getThunk()(Base::getEnvironment(), firstArgument); + } +}; + +template +inline Callback1 makeCallback1(const Caller& caller, typename Caller::first_argument_type callee) +{ + return Callback1(BindFirstOpaque1(callee)); +} +template +inline Callback1 makeStatelessCallback1(const Caller& caller) +{ + return makeCallback1(Caller1To2(), 0); +} + + +/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and two other arguments. +/// +template +class Callback2 : public CallbackBase +{ + typedef CallbackBase Base; + static Result nullThunk(void*, FirstArgument, SecondArgument) + { + } + +public: + typedef FirstArgument first_argument_type; + typedef SecondArgument second_argument_type; + typedef Result result_type; + + Callback2() : Base(0, nullThunk) + { + } + template + Callback2(const BindFirstOpaque2& caller) : Base(caller.getEnvironment(), BindFirstOpaque2::thunk) + { + } + Callback2(void* environment, typename Base::Thunk function) : Base(environment, function) + { + } + result_type operator()(FirstArgument firstArgument, SecondArgument secondArgument) const + { + return Base::getThunk()(Base::getEnvironment(), firstArgument, secondArgument); + } +}; + +template +inline Callback2< + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type +> makeCallback2(const Caller& caller, typename Caller::first_argument_type callee) +{ + return Callback2< + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type + >(BindFirstOpaque2(callee)); +} +template +inline Callback2< + typename Caller::first_argument_type, + typename Caller::second_argument_type, + typename Caller::result_type +> makeStatelessCallback2(const Caller& caller) +{ + return makeCallback2(Caller2To3(), 0); +} + + +/// \brief Combines a void pointer with a pointer to a function which operates on a void pointer and three other arguments. +/// +template +class Callback3 : public CallbackBase +{ + typedef CallbackBase Base; + static Result nullThunk(void*, FirstArgument, SecondArgument, ThirdArgument) + { + } + +public: + typedef FirstArgument first_argument_type; + typedef SecondArgument second_argument_type; + typedef ThirdArgument third_argument_type; + typedef Result result_type; + + Callback3() : Base(0, nullThunk) + { + } + template + Callback3(const BindFirstOpaque3& caller) : Base(caller.getEnvironment(), BindFirstOpaque3::thunk) + { + } + Callback3(void* environment, typename Base::Thunk function) : Base(environment, function) + { + } + result_type operator()(FirstArgument firstArgument, SecondArgument secondArgument, ThirdArgument thirdArgument) const + { + return Base::getThunk()(Base::getEnvironment(), firstArgument, secondArgument, thirdArgument); + } +}; + +template +inline Callback3< + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::result_type +> makeCallback3(const Caller& caller, typename Caller::first_argument_type callee) +{ + return Callback3< + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::fourth_argument_type, + typename Caller::result_type + >(BindFirstOpaque3(callee)); +} +template +inline Callback3< + typename Caller::first_argument_type, + typename Caller::second_argument_type, + typename Caller::third_argument_type, + typename Caller::result_type +> makeStatelessCallback3(const Caller& caller) +{ + return makeCallback3(Caller3To4(), 0); +} + + +/// \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 : public BindFirstOpaque< Member > +{ +public: + MemberCaller(Environment& environment) : BindFirstOpaque< Member >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque< ConstMember > +{ +public: + ConstMemberCaller(const Environment& environment) : BindFirstOpaque< ConstMember >(environment) + { + } +}; + +/// \brief Forms a Callback from a non-const Environment reference and a const Environment member-function which takes one argument. +template +class MemberCaller1 : public BindFirstOpaque1< Member1 > +{ +public: + MemberCaller1(Environment& environment) : BindFirstOpaque1< Member1 >(environment) + { + } +}; + +/// \brief Forms a Callback from a const Environment reference and a const Environment member-function which takes one argument. +template +class ConstMemberCaller1 : public BindFirstOpaque1< ConstMember1 > +{ +public: + ConstMemberCaller1(const Environment& environment) : BindFirstOpaque1< ConstMember1 >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque< Function1 > +{ +public: + ReferenceCaller(Environment& environment) : BindFirstOpaque< Function1 >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque< Function1 > +{ +public: + ConstReferenceCaller(const Environment& environment) : BindFirstOpaque< Function1 >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque1< Function2 > +{ +public: + ReferenceCaller1(Environment& environment) : BindFirstOpaque1< Function2 >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque1< Function2 > +{ +public: + ConstReferenceCaller1(const Environment& environment) : BindFirstOpaque1< Function2 >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque< Function1 > +{ +public: + PointerCaller(Environment* environment) : BindFirstOpaque< Function1 >(environment) + { + } +}; + +/// \brief Forms a Callback from a const Environment pointer and a free function which operates on a const Environment pointer. +template +class ConstPointerCaller : public BindFirstOpaque< Function1 > +{ +public: + ConstPointerCaller(const Environment* environment) : BindFirstOpaque< Function1 >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque1< Function2 > +{ +public: + PointerCaller1(Environment* environment) : BindFirstOpaque1< Function2 >(environment) + { + } +}; + +/// \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 : public BindFirstOpaque1< Function2 > +{ +public: + ConstPointerCaller1(const Environment* environment) : BindFirstOpaque1< Function2 >(environment) + { + } +}; + +/// \brief Forms a Callback from a free function which takes no arguments. +template +class FreeCaller : public BindFirstOpaque< Caller0To1< Function0 > > +{ +public: + FreeCaller() : BindFirstOpaque< Caller0To1< Function0 > >(0) + { + } +}; + +/// \brief Forms a Callback from a free function which takes a single argument. +template +class FreeCaller1 : public BindFirstOpaque1< Caller1To2< Function1 > > +{ +public: + FreeCaller1() : BindFirstOpaque1< Caller1To2< Function1 > >(0) + { + } +}; + + +/// \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)); +} + + +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; + + +#endif diff --git a/misc/mediasource/netradiant-src/libs/generic/callbackfwd.cpp b/misc/mediasource/netradiant-src/libs/generic/callbackfwd.cpp new file mode 100644 index 00000000..a2faa664 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/callbackfwd.cpp @@ -0,0 +1,3 @@ + +#include "callbackfwd.h" + diff --git a/misc/mediasource/netradiant-src/libs/generic/callbackfwd.h b/misc/mediasource/netradiant-src/libs/generic/callbackfwd.h new file mode 100644 index 00000000..f89f9090 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/callbackfwd.h @@ -0,0 +1,18 @@ + +#if !defined(INCLUDED_CALLBACKFWD_H) +#define INCLUDED_CALLBACKFWD_H + +template +class Callback0; +typedef Callback0 Callback; + +template +class Callback1; + +template +class Callback2; + +template +class Callback3; + +#endif diff --git a/misc/mediasource/netradiant-src/libs/generic/constant.cpp b/misc/mediasource/netradiant-src/libs/generic/constant.cpp new file mode 100644 index 00000000..ff54c9cc --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/constant.cpp @@ -0,0 +1,40 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "constant.h" + +#if defined(_DEBUG) || defined(DOXYGEN) + +namespace ExampleConstant +{ + class Bleh + { + public: + + STRING_CONSTANT(Name, "Bleh"); + INTEGER_CONSTANT(Version, 1); + }; + + int version = Bleh::Version(); + const char* name = Bleh::Name(); +} + +#endif diff --git a/misc/mediasource/netradiant-src/libs/generic/constant.h b/misc/mediasource/netradiant-src/libs/generic/constant.h new file mode 100644 index 00000000..42b2fa5d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/constant.h @@ -0,0 +1,50 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GENERIC_CONSTANT_H) +#define INCLUDED_GENERIC_CONSTANT_H + +/// \file +/// \brief Language extensions for constants that are guaranteed to be evaluated at compile-time. + +/// \brief A compile-time-constant as a type. +template +struct ConstantWrapper +{ + typedef typename Type::Value Value; + operator Value() const + { + return Type::evaluate(); + } +}; +template +inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const ConstantWrapper& c) +{ + return ostream_write(ostream, typename Type::Value(c)); +} + +#define TYPE_CONSTANT(name, value, type) struct name##_CONSTANT_ { typedef type Value; static Value evaluate() { return value; } }; typedef ConstantWrapper name +#define STRING_CONSTANT(name, value) TYPE_CONSTANT(name, value, const char*) +#define INTEGER_CONSTANT(name, value) TYPE_CONSTANT(name, value, int) + +STRING_CONSTANT(EmptyString, ""); + +#endif diff --git a/misc/mediasource/netradiant-src/libs/generic/enumeration.cpp b/misc/mediasource/netradiant-src/libs/generic/enumeration.cpp new file mode 100644 index 00000000..4591fda9 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/enumeration.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "enumeration.h" + diff --git a/misc/mediasource/netradiant-src/libs/generic/enumeration.h b/misc/mediasource/netradiant-src/libs/generic/enumeration.h new file mode 100644 index 00000000..31e43052 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/enumeration.h @@ -0,0 +1,60 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/generic/functional.cpp b/misc/mediasource/netradiant-src/libs/generic/functional.cpp new file mode 100644 index 00000000..4717c8e2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/functional.cpp @@ -0,0 +1,3 @@ + +#include "functional.h" + diff --git a/misc/mediasource/netradiant-src/libs/generic/functional.h b/misc/mediasource/netradiant-src/libs/generic/functional.h new file mode 100644 index 00000000..bd253486 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/functional.h @@ -0,0 +1,313 @@ + +#if !defined(INCLUDED_FUNCTIONAL_H) +#define INCLUDED_FUNCTIONAL_H + +template +class Member +{ +public: + typedef Object& first_argument_type; + typedef R result_type; + static result_type call(first_argument_type object) + { + return (object.*member)(); + } +}; + +template +class ConstMember +{ +public: + typedef const Object& first_argument_type; + typedef R result_type; + static result_type call(first_argument_type object) + { + return (object.*member)(); + } +}; + +template +class Member1 +{ +public: + typedef Object& first_argument_type; + typedef A1 second_argument_type; + typedef R result_type; + static result_type call(first_argument_type object, second_argument_type a1) + { + return (object.*member)(a1); + } +}; + +template +class ConstMember1 +{ +public: + typedef const Object& first_argument_type; + typedef A1 second_argument_type; + typedef R result_type; + static result_type call(first_argument_type object, second_argument_type a1) + { + return (object.*member)(a1); + } +}; + +template +class Member2 +{ +public: + typedef Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef R result_type; + static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3) + { + return (object.*member)(a2, a3); + } +}; + +template +class ConstMember2 +{ +public: + typedef const Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef R result_type; + static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3) + { + return (object.*member)(a2, a3); + } +}; + +template +class Member3 +{ +public: + typedef Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef A4 fourth_argument_type; + typedef R result_type; + static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) + { + return (object.*member)(a2, a3, a4); + } +}; + +template +class ConstMember3 +{ +public: + typedef const Object& first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef A4 fourth_argument_type; + typedef R result_type; + static result_type call(first_argument_type object, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) + { + return (object.*member)(a2, a3, a4); + } +}; + +template +class Function0 +{ +public: + typedef R result_type; + static result_type call() + { + return (func)(); + } +}; + +template +class Function1 +{ +public: + typedef A1 first_argument_type; + typedef R result_type; + static result_type call(first_argument_type a1) + { + return (func)(a1); + } +}; + +template +class Function2 +{ +public: + typedef A1 first_argument_type; + typedef A2 second_argument_type; + typedef R result_type; + static result_type call(first_argument_type a1, second_argument_type a2) + { + return (func)(a1, a2); + } +}; + +template +class Function3 +{ +public: + typedef A1 first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef R result_type; + static result_type call(first_argument_type a1, second_argument_type a2, third_argument_type a3) + { + return (func)(a1, a2, a3); + } +}; + +template +class Function4 +{ +public: + typedef A1 first_argument_type; + typedef A2 second_argument_type; + typedef A3 third_argument_type; + typedef A4 fourth_argument_type; + typedef R result_type; + static result_type call(first_argument_type a1, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) + { + return (func)(a1, a2, a3, a4); + } +}; + +template +class Caller0To1 +{ +public: + typedef FirstArgument first_argument_type; + typedef typename Caller::result_type result_type; + static result_type call(first_argument_type) + { + return Caller::call(); + } +}; + +template +class Caller1To2 +{ +public: + typedef FirstArgument first_argument_type; + typedef typename Caller::first_argument_type second_argument_type; + typedef typename Caller::result_type result_type; + static result_type call(first_argument_type, second_argument_type a2) + { + return Caller::call(a2); + } +}; + +template +class Caller2To3 +{ +public: + typedef FirstArgument first_argument_type; + typedef typename Caller::first_argument_type second_argument_type; + typedef typename Caller::second_argument_type third_argument_type; + typedef typename Caller::result_type result_type; + static result_type call(first_argument_type, second_argument_type a2, third_argument_type a3) + { + return Caller::call(a2, a3); + } +}; + +template +class Caller3To4 +{ +public: + typedef FirstArgument first_argument_type; + typedef typename Caller::first_argument_type second_argument_type; + typedef typename Caller::second_argument_type third_argument_type; + typedef typename Caller::third_argument_type fourth_argument_type; + typedef typename Caller::result_type result_type; + static result_type call(first_argument_type, second_argument_type a2, third_argument_type a3, fourth_argument_type a4) + { + return Caller::call(a2, a3, a4); + } +}; + +template +class FunctorInvoke +{ +public: + typedef typename Functor::result_type result_type; + inline result_type operator()(Functor functor) + { + return functor(); + } +}; + +template +class Functor1Invoke +{ + typename Functor::first_argument_type a1; +public: + typedef typename Functor::first_argument_type first_argument_type; + typedef typename Functor::result_type result_type; + Functor1Invoke(first_argument_type a1) : a1(a1) + { + } + inline result_type operator()(Functor functor) + { + return functor(a1); + } +}; + +template +class Functor2Invoke +{ + typename Functor::first_argument_type a1; + typename Functor::second_argument_type a2; +public: + typedef typename Functor::first_argument_type first_argument_type; + typedef typename Functor::second_argument_type second_argument_type; + typedef typename Functor::result_type result_type; + Functor2Invoke(first_argument_type a1, second_argument_type a2) + : a1(a1), a2(a2) + { + } + inline result_type operator()(Functor functor) + { + return functor(a1, a2); + } +}; + +template +class Functor3Invoke +{ + typename Functor::first_argument_type a1; + typename Functor::second_argument_type a2; + typename Functor::third_argument_type a3; +public: + typedef typename Functor::first_argument_type first_argument_type; + typedef typename Functor::second_argument_type second_argument_type; + typedef typename Functor::third_argument_type third_argument_type; + typedef typename Functor::result_type result_type; + Functor3Invoke(first_argument_type a1, second_argument_type a2, third_argument_type a3) + : a1(a1), a2(a2), a3(a3) + { + } + inline result_type operator()(Functor functor) + { + return functor(a1, a2, a3); + } +}; + +template +class TypeEqual +{ +public: + typedef False type; +}; +template +class TypeEqual +{ +public: + typedef True type; +}; + + +#endif diff --git a/misc/mediasource/netradiant-src/libs/generic/object.cpp b/misc/mediasource/netradiant-src/libs/generic/object.cpp new file mode 100644 index 00000000..a6ed31c0 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/object.cpp @@ -0,0 +1,41 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/generic/object.h b/misc/mediasource/netradiant-src/libs/generic/object.h new file mode 100644 index 00000000..ec8e7262 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/object.h @@ -0,0 +1,98 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/generic/reference.cpp b/misc/mediasource/netradiant-src/libs/generic/reference.cpp new file mode 100644 index 00000000..c09cad82 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/reference.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "reference.h" diff --git a/misc/mediasource/netradiant-src/libs/generic/reference.h b/misc/mediasource/netradiant-src/libs/generic/reference.h new file mode 100644 index 00000000..62e2c238 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/reference.h @@ -0,0 +1,115 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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) + { + } + 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) + { + } + 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/misc/mediasource/netradiant-src/libs/generic/referencecounted.cpp b/misc/mediasource/netradiant-src/libs/generic/referencecounted.cpp new file mode 100644 index 00000000..757e08d8 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/referencecounted.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "referencecounted.h" diff --git a/misc/mediasource/netradiant-src/libs/generic/referencecounted.h b/misc/mediasource/netradiant-src/libs/generic/referencecounted.h new file mode 100644 index 00000000..e761cccc --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/referencecounted.h @@ -0,0 +1,207 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/generic/static.cpp b/misc/mediasource/netradiant-src/libs/generic/static.cpp new file mode 100644 index 00000000..ecd539f3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/static.cpp @@ -0,0 +1,133 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/generic/static.h b/misc/mediasource/netradiant-src/libs/generic/static.h new file mode 100644 index 00000000..81691827 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/static.h @@ -0,0 +1,151 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GENERIC_STATIC_H) +#define INCLUDED_GENERIC_STATIC_H + +/// \file +/// \brief Template techniques for instantiating singletons. + +#include + +class Null +{ +}; + +/// \brief A singleton which is statically initialised. +/// +/// \param Type The singleton object type. +/// \param Type The type distinguishing this instance from others of the same 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. +/// \param Type The type distinguishing this instance from others of the same 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. +/// \param Type The type distinguishing this instance from others of the same 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. +/// \param Type The type distinguishing this instance from others of the same type. +/// +/// \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/misc/mediasource/netradiant-src/libs/generic/vector.cpp b/misc/mediasource/netradiant-src/libs/generic/vector.cpp new file mode 100644 index 00000000..83765dcb --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/vector.cpp @@ -0,0 +1,3 @@ + +#include "vector.h" + diff --git a/misc/mediasource/netradiant-src/libs/generic/vector.h b/misc/mediasource/netradiant-src/libs/generic/vector.h new file mode 100644 index 00000000..6e6f74e2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/generic/vector.h @@ -0,0 +1,259 @@ + +#if !defined(INCLUDED_VECTOR_H) +#define INCLUDED_VECTOR_H + +#include + +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]; + } + + Element* data() + { + return m_elements; + } + const Element* data() const + { + return m_elements; + } +}; + +/// \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]; + } + + Element* data() + { + return m_elements; + } + const Element* data() const + { + return m_elements; + } +}; + +/// \brief A 4-element vector. +template +class BasicVector4 +{ + Element m_elements[4]; +public: + + BasicVector4() + { + } + BasicVector4(Element x_, Element y_, Element z_, Element w_) + { + x() = x_; + y() = y_; + z() = z_; + w() = w_; + } + BasicVector4(const BasicVector3& self, Element w_) + { + x() = self.x(); + y() = self.y(); + z() = self.z(); + w() = w_; + } + + 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]; + } + Element& w() + { + return m_elements[3]; + } + const Element& w() const + { + return m_elements[3]; + } + + Element index(std::size_t i) const + { + return m_elements[i]; + } + Element& index(std::size_t i) + { + return m_elements[i]; + } + Element operator[](std::size_t i) const + { + return m_elements[i]; + } + Element& operator[](std::size_t i) + { + return m_elements[i]; + } + + Element* data() + { + return m_elements; + } + const Element* data() const + { + return m_elements; + } +}; + +template +inline BasicVector3 vector3_from_array(const Element* array) +{ + return BasicVector3(array[0], array[1], array[2]); +} + +template +inline Element* vector3_to_array(BasicVector3& self) +{ + return self.data(); +} +template +inline const Element* vector3_to_array(const BasicVector3& self) +{ + return self.data(); +} + +template +inline Element* vector4_to_array(BasicVector4& self) +{ + return self.data(); +} +template +inline const Element* vector4_to_array(const BasicVector4& self) +{ + return self.data(); +} + +template +inline BasicVector3& vector4_to_vector3(BasicVector4& self) +{ + return *reinterpret_cast*>(vector4_to_array(self)); +} +template +inline const BasicVector3& vector4_to_vector3(const BasicVector4& self) +{ + return *reinterpret_cast*>(vector4_to_array(self)); +} + +/// \brief A 2-element vector stored in single-precision floating-point. +typedef BasicVector2 Vector2; + +/// \brief A 3-element vector stored in single-precision floating-point. +typedef BasicVector3 Vector3; + +/// \brief A 4-element vector stored in single-precision floating-point. +typedef BasicVector4 Vector4; + + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/accelerator.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/accelerator.cpp new file mode 100644 index 00000000..214cc36c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/accelerator.cpp @@ -0,0 +1,662 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "accelerator.h" + +#include "debugging/debugging.h" + +#include +#include +#include +#include + +#include "generic/callback.h" +#include "generic/bitfield.h" +#include "string/string.h" + +#include "pointer.h" +#include "closure.h" + +#include + + + +const char* global_keys_find(unsigned int key) +{ + const char *s; + if(key == 0) + return ""; + s = gdk_keyval_name(key); + if(!s) + return ""; + return s; +} + +unsigned int global_keys_find(const char* name) +{ + guint k; + if(!name || !*name) + return 0; + k = gdk_keyval_from_name(name); + if(k == GDK_VoidSymbol) + return 0; + return k; +} + +void accelerator_write(const Accelerator& accelerator, TextOutputStream& ostream) +{ +#if 0 + if(accelerator.modifiers & GDK_SHIFT_MASK) + { + ostream << "Shift + "; + } + if(accelerator.modifiers & GDK_MOD1_MASK) + { + ostream << "Alt + "; + } + if(accelerator.modifiers & GDK_CONTROL_MASK) + { + ostream << "Control + "; + } + + const char* keyName = global_keys_find(accelerator.key); + if(!string_empty(keyName)) + { + ostream << keyName; + } + else + { + ostream << static_cast(accelerator.key); + } +#endif + ostream << gtk_accelerator_get_label(accelerator.key, accelerator.modifiers); +} + +typedef std::map AcceleratorMap; +typedef std::set AcceleratorSet; + +bool accelerator_map_insert(AcceleratorMap& acceleratorMap, Accelerator accelerator, const Callback& callback) +{ + if(accelerator.key != 0) + { + return acceleratorMap.insert(AcceleratorMap::value_type(accelerator, callback)).second; + } + return true; +} + +bool accelerator_map_erase(AcceleratorMap& acceleratorMap, Accelerator accelerator) +{ + if(accelerator.key != 0) + { + AcceleratorMap::iterator i = acceleratorMap.find(accelerator); + if(i == acceleratorMap.end()) + { + return false; + } + acceleratorMap.erase(i); + } + return true; +} + +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; +} + + +GClosure* accel_group_add_accelerator(GtkAccelGroup* group, Accelerator accelerator, const Callback& callback); +void accel_group_remove_accelerator(GtkAccelGroup* group, Accelerator accelerator); + +AcceleratorMap g_queuedAcceleratorsAdd; +AcceleratorSet g_queuedAcceleratorsRemove; + +void globalQueuedAccelerators_add(Accelerator accelerator, const Callback& callback) +{ + if(!g_queuedAcceleratorsAdd.insert(AcceleratorMap::value_type(accelerator, callback)).second) + { + globalErrorStream() << "globalQueuedAccelerators_add: accelerator already queued: " << accelerator << "\n"; + } +} + +void globalQueuedAccelerators_remove(Accelerator accelerator) +{ + if(g_queuedAcceleratorsAdd.erase(accelerator) == 0) + { + if(!g_queuedAcceleratorsRemove.insert(accelerator).second) + { + globalErrorStream() << "globalQueuedAccelerators_remove: accelerator already queued: " << accelerator << "\n"; + } + } +} + +void globalQueuedAccelerators_commit() +{ + for(AcceleratorSet::const_iterator i = g_queuedAcceleratorsRemove.begin(); i != g_queuedAcceleratorsRemove.end(); ++i) + { + //globalOutputStream() << "removing: " << (*i).first << "\n"; + accel_group_remove_accelerator(global_accel, *i); + } + g_queuedAcceleratorsRemove.clear(); + for(AcceleratorMap::const_iterator i = g_queuedAcceleratorsAdd.begin(); i != g_queuedAcceleratorsAdd.end(); ++i) + { + //globalOutputStream() << "adding: " << (*i).first << "\n"; + accel_group_add_accelerator(global_accel, (*i).first, (*i).second); + } + g_queuedAcceleratorsAdd.clear(); +} + +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) +{ + //globalOutputStream() << "special_accelerators_add: " << makeQuoted(accelerator) << "\n"; + if(!accelerator_map_insert(g_special_accelerators, accelerator, callback)) + { + globalErrorStream() << "special_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; + } +} +void special_accelerators_remove(Accelerator accelerator) +{ + //globalOutputStream() << "special_accelerators_remove: " << makeQuoted(accelerator) << "\n"; + if(!accelerator_map_erase(g_special_accelerators, accelerator)) + { + globalErrorStream() << "special_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; + } +} + +void keydown_accelerators_add(Accelerator accelerator, const Callback& callback) +{ + //globalOutputStream() << "keydown_accelerators_add: " << makeQuoted(accelerator) << "\n"; + if(!accelerator_map_insert(g_keydown_accelerators, accelerator, callback)) + { + globalErrorStream() << "keydown_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; + } +} +void keydown_accelerators_remove(Accelerator accelerator) +{ + //globalOutputStream() << "keydown_accelerators_remove: " << makeQuoted(accelerator) << "\n"; + if(!accelerator_map_erase(g_keydown_accelerators, accelerator)) + { + globalErrorStream() << "keydown_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; + } +} + +void keyup_accelerators_add(Accelerator accelerator, const Callback& callback) +{ + //globalOutputStream() << "keyup_accelerators_add: " << makeQuoted(accelerator) << "\n"; + if(!accelerator_map_insert(g_keyup_accelerators, accelerator, callback)) + { + globalErrorStream() << "keyup_accelerators_add: already exists: " << makeQuoted(accelerator) << "\n"; + } +} +void keyup_accelerators_remove(Accelerator accelerator) +{ + //globalOutputStream() << "keyup_accelerators_remove: " << makeQuoted(accelerator) << "\n"; + if(!accelerator_map_erase(g_keyup_accelerators, accelerator)) + { + globalErrorStream() << "keyup_accelerators_remove: not found: " << makeQuoted(accelerator) << "\n"; + } +} + + +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() << "global_accel_connect: " << makeQuoted(accelerator) << "\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)) + { + //globalOutputStream() << "global_accel_disconnect: " << makeQuoted(accelerator) << "\n"; + 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 + //globalOutputStream() << "queued for add: " << accelerator << "\n"; + globalQueuedAccelerators_add(accelerator, callback); + return 0; + } + return accel_group_add_accelerator(global_accel, accelerator, callback); +} +void global_accel_group_remove_accelerator(Accelerator accelerator) +{ + if(!global_accel_enabled()) + { + //globalOutputStream() << "queued for remove: " << accelerator << "\n"; + globalQueuedAccelerators_remove(accelerator); + return; + } + 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) +{ + gboolean b = gtk_window_propagate_key_event(window, event); + return b; +} + +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 global_accel_group_connect(const Accelerator& accelerator, const Callback& callback) +{ + if(accelerator.key != 0) + { + global_accel_group_add_accelerator(accelerator, callback); + } +} + +void global_accel_group_disconnect(const Accelerator& accelerator, const Callback& callback) +{ + if(accelerator.key != 0) + { + global_accel_group_remove_accelerator(accelerator); + } +} + + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/accelerator.h b/misc/mediasource/netradiant-src/libs/gtkutil/accelerator.h new file mode 100644 index 00000000..4e441b21 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/accelerator.h @@ -0,0 +1,154 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_ACCELERATOR_H) +#define INCLUDED_GTKUTIL_ACCELERATOR_H + +#include +#include +#include + +#include "generic/callback.h" + +// ignore numlock +#define ALLOWED_MODIFIERS (~(GDK_MOD2_MASK | GDK_LOCK_MASK | GDK_MOD3_MASK | GDK_MOD4_MASK | GDK_MOD5_MASK)) + +struct Accelerator +{ + Accelerator(guint _key) + : key(gdk_keyval_to_upper(_key)), modifiers((GdkModifierType)0) + { + } + Accelerator(guint _key, GdkModifierType _modifiers) + : key(gdk_keyval_to_upper(_key)), modifiers((GdkModifierType) (_modifiers & ALLOWED_MODIFIERS)) + { + } + Accelerator(const Accelerator &src) + : key(gdk_keyval_to_upper(src.key)), modifiers((GdkModifierType) (src.modifiers & ALLOWED_MODIFIERS)) + { + } + bool operator<(const Accelerator& other) const + { + guint k1 = key; + guint k2 = other.key; + int mod1 = modifiers & ALLOWED_MODIFIERS; + int mod2 = other.modifiers & ALLOWED_MODIFIERS; + return k1 < k2 || (!(k2 < k1) && mod1 < mod2); + } + bool operator==(const Accelerator& other) const + { + guint k1 = key; + guint k2 = other.key; + int mod1 = modifiers & ALLOWED_MODIFIERS; + int mod2 = other.modifiers & ALLOWED_MODIFIERS; + return k1 == k2 && mod1 == mod2; + } + Accelerator &operator=(const Accelerator& other) + { + key = other.key; + modifiers = (GdkModifierType) (other.modifiers & ALLOWED_MODIFIERS); + return *this; + } + guint key; + GdkModifierType modifiers; +}; + +inline Accelerator accelerator_null() +{ + return Accelerator(0, (GdkModifierType)0); +} + +const char* global_keys_find(unsigned int key); +unsigned int global_keys_find(const char* name); + +class TextOutputStream; +void accelerator_write(const Accelerator& accelerator, TextOutputStream& ostream); + +template +TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const Accelerator& accelerator) +{ + accelerator_write(accelerator, ostream); + return ostream; +} + +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 global_accel_group_connect(const Accelerator& accelerator, const Callback& callback); +void global_accel_group_disconnect(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/misc/mediasource/netradiant-src/libs/gtkutil/button.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/button.cpp new file mode 100644 index 00000000..0356ba39 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/button.cpp @@ -0,0 +1,137 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/gtkutil/button.h b/misc/mediasource/netradiant-src/libs/gtkutil/button.h new file mode 100644 index 00000000..69ddac4b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/button.h @@ -0,0 +1,44 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_BUTTON_H) +#define INCLUDED_GTKUTIL_BUTTON_H + +#include "generic/callbackfwd.h" + +typedef struct _GtkButton GtkButton; +typedef struct _GtkToggleButton GtkToggleButton; +typedef struct _GtkRadioButton GtkRadioButton; +typedef int gint; +typedef gint gboolean; +typedef unsigned int guint; + +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/misc/mediasource/netradiant-src/libs/gtkutil/clipboard.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/clipboard.cpp new file mode 100644 index 00000000..f7b9466a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/clipboard.cpp @@ -0,0 +1,162 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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(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(); + } +} + +#else + +#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); +} + + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/clipboard.h b/misc/mediasource/netradiant-src/libs/gtkutil/clipboard.h new file mode 100644 index 00000000..1589a66a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/clipboard.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/closure.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/closure.cpp new file mode 100644 index 00000000..4926d994 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/closure.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "closure.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/closure.h b/misc/mediasource/netradiant-src/libs/gtkutil/closure.h new file mode 100644 index 00000000..9a74b95e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/closure.h @@ -0,0 +1,77 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/container.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/container.cpp new file mode 100644 index 00000000..627e0c88 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/container.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "container.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/container.h b/misc/mediasource/netradiant-src/libs/gtkutil/container.h new file mode 100644 index 00000000..c41478ba --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/container.h @@ -0,0 +1,43 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/cursor.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/cursor.cpp new file mode 100644 index 00000000..2c4225a2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/cursor.cpp @@ -0,0 +1,97 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "cursor.h" + +#include "stream/textstream.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(GtkWindow* window, int *x, int *y) +{ + POINT pos; + GetCursorPos(&pos); + ScreenToClient((HWND)GDK_WINDOW_HWND(GTK_WIDGET(window)->window), &pos); + *x = pos.x; + *y = pos.y; +} + +void Sys_SetCursorPos(GtkWindow* window, int x, int y) +{ + POINT pos; + pos.x = x; + pos.y = y; + ClientToScreen((HWND)GDK_WINDOW_HWND(GTK_WIDGET(window)->window), &pos); + SetCursorPos(pos.x, pos.y); +} + +#else + +#include + +void Sys_GetCursorPos(GtkWindow* window, int *x, int *y) +{ + gdk_display_get_pointer(gdk_display_get_default(), 0, x, y, 0); +} + +void Sys_SetCursorPos(GtkWindow* window, int x, int y) +{ + XWarpPointer(GDK_DISPLAY(), None, GDK_ROOT_WINDOW(), 0, 0, 0, 0, x, y); +} + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/cursor.h b/misc/mediasource/netradiant-src/libs/gtkutil/cursor.h new file mode 100644 index 00000000..eadae085 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/cursor.h @@ -0,0 +1,193 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_CURSOR_H) +#define INCLUDED_GTKUTIL_CURSOR_H + +#include +#include +#include +#include + +#include "debugging/debugging.h" + +typedef struct _GdkCursor GdkCursor; +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; + +GdkCursor* create_blank_cursor(); +void blank_cursor(GtkWidget* widget); +void default_cursor(GtkWidget* widget); +void Sys_GetCursorPos(GtkWindow* window, int *x, int *y); +void Sys_SetCursorPos(GtkWindow* window, 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(GTK_WINDOW(widget), ¤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(GTK_WINDOW(widget), self->recorded_x, self->recorded_y); + self->m_function(dx, dy, event->state, self->m_data); + } + return FALSE; + } + + void freeze_pointer(GtkWindow* window, MotionDeltaFunction function, void* data) + { + ASSERT_MESSAGE(m_function == 0, "can't freeze pointer"); + + 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); + + GdkCursor* cursor = create_blank_cursor(); + //GdkGrabStatus status = + gdk_pointer_grab(GTK_WIDGET(window)->window, TRUE, mask, 0, cursor, GDK_CURRENT_TIME); + gdk_cursor_unref(cursor); + + Sys_GetCursorPos(window, &recorded_x, &recorded_y); + + Sys_SetCursorPos(window, 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(GtkWindow* window) + { + g_signal_handler_disconnect(G_OBJECT(window), handle_motion); + + m_function = 0; + m_data = 0; + + Sys_SetCursorPos(window, recorded_x, recorded_y); + + gdk_pointer_ungrab(GDK_CURRENT_TIME); + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/dialog.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/dialog.cpp new file mode 100644 index 00000000..0f95e9ae --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/dialog.cpp @@ -0,0 +1,303 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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.first; i != names.last; ++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/misc/mediasource/netradiant-src/libs/gtkutil/dialog.h b/misc/mediasource/netradiant-src/libs/gtkutil/dialog.h new file mode 100644 index 00000000..150404a2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/dialog.h @@ -0,0 +1,145 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/entry.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/entry.cpp new file mode 100644 index 00000000..9c3c1553 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/entry.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "entry.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/entry.h b/misc/mediasource/netradiant-src/libs/gtkutil/entry.h new file mode 100644 index 00000000..82957d29 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/entry.h @@ -0,0 +1,63 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/filechooser.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/filechooser.cpp new file mode 100644 index 00000000..2246b57b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/filechooser.cpp @@ -0,0 +1,305 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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)); + } +}; + + +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, bool want_load, bool want_import, bool want_save) +{ + filetype_t type; + + if(pattern == 0) + { + pattern = "*"; + } + + FileTypeList typelist; + GlobalFiletypes().getTypeList(pattern, &typelist, want_load, want_import, want_save); + + 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)); + if(filter != 0) // no filter set? some file-chooser implementations may allow the user to set no filter, which we treat as 'all files' + { + 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; +} + +const char* file_dialog(GtkWidget* parent, bool open, const char* title, const char* path, const char* pattern, bool want_load, bool want_import, bool want_save) +{ + for(;;) + { + const char* file = file_dialog_show(parent, open, title, path, pattern, want_load, want_import, want_save); + + if(open + || file == 0 + || !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/misc/mediasource/netradiant-src/libs/gtkutil/filechooser.h b/misc/mediasource/netradiant-src/libs/gtkutil/filechooser.h new file mode 100644 index 00000000..3789321e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/filechooser.h @@ -0,0 +1,38 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_FILECHOOSER_H) +#define INCLUDED_GTKUTIL_FILECHOOSER_H + +/// \file +/// GTK+ file-chooser dialogs. + +typedef struct _GtkWidget GtkWidget; +const char* file_dialog(GtkWidget *parent, bool open, const char* title, const char* path = 0, const char* pattern = 0, bool want_load = false, bool want_import = false, bool want_save = false); + + +/// \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/misc/mediasource/netradiant-src/libs/gtkutil/frame.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/frame.cpp new file mode 100644 index 00000000..026de650 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/frame.cpp @@ -0,0 +1,35 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/gtkutil/frame.h b/misc/mediasource/netradiant-src/libs/gtkutil/frame.h new file mode 100644 index 00000000..12305db2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/frame.h @@ -0,0 +1,29 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/glfont.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/glfont.cpp new file mode 100644 index 00000000..a3eac91d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/glfont.cpp @@ -0,0 +1,354 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "glfont.h" +#include "igl.h" + +// generic string printing with call lists +class GLFontCallList: public GLFont +{ + GLuint m_displayList; + int m_pixelHeight; + int m_pixelAscent; + int m_pixelDescent; + public: + GLFontCallList(GLuint displayList, int asc, int desc, int pixelHeight) : m_displayList(displayList), m_pixelHeight(pixelHeight), m_pixelAscent(asc), m_pixelDescent(desc) + { + } + virtual ~GLFontCallList() + { + glDeleteLists(m_displayList, 256); + } + void printString(const char *s) + { + GlobalOpenGL().m_glListBase(m_displayList); + GlobalOpenGL().m_glCallLists(GLsizei(strlen(s)), GL_UNSIGNED_BYTE, reinterpret_cast(s)); + } + virtual int getPixelAscent() const + { + return m_pixelAscent; + } + virtual int getPixelDescent() const + { + return m_pixelDescent; + } + virtual int getPixelHeight() const + { + return m_pixelHeight; + } +}; + +#ifdef _WIN32 + #include +#endif +#include "debugging/debugging.h" + +// LordHavoc: this is code for direct Xlib bitmap character fetching, as an +// alternative to requiring gtkglarea, it was created due to a lack of this +// package on SuSE 9.x but this package is now commonly shipping in Linux +// distributions so this code may be unnecessary, feel free however to enable +// it when building packages for distros that do not ship with that package, +// or if you just prefer less dependencies... +#if 0 + +#include +#include +#include + +GLFont *glfont_create(const char* font_string) +{ + GLuint font_list_base; + XFontStruct *fontInfo; + Display *dpy = GDK_DISPLAY (); + unsigned int i, first, last, firstrow, lastrow; + int maxchars; + int firstbitmap; + + fontInfo = XLoadQueryFont (dpy, "-*-fixed-*-*-*-*-8-*-*-*-*-*-*-*"); + if (fontInfo == NULL) + { + // try to load other fonts + fontInfo = XLoadQueryFont (dpy, "-*-fixed-*-*-*-*-*-*-*-*-*-*-*-*"); + + // any font will do ! + if (fontInfo == NULL) + fontInfo = XLoadQueryFont(dpy, "-*-*-*-*-*-*-*-*-*-*-*-*-*-*"); + + if (fontInfo == NULL) + ERROR_MESSAGE("couldn't create font"); + } + + first = (int)fontInfo->min_char_or_byte2; + last = (int)fontInfo->max_char_or_byte2; + firstrow = (int)fontInfo->min_byte1; + lastrow = (int)fontInfo->max_byte1; + /* + * How many chars in the charset + */ + maxchars = 256 * lastrow + last; + font_list_base = glGenLists(maxchars+1); + if (font_list_base == 0) + { + ERROR_MESSAGE( "couldn't create font" ); + } + + /* + * Get offset to first char in the charset + */ + firstbitmap = 256 * firstrow + first; + /* + * for each row of chars, call glXUseXFont to build the bitmaps. + */ + + for(i=firstrow; i<=lastrow; i++) + { + glXUseXFont(fontInfo->fid, firstbitmap, last-first+1, font_list_base+firstbitmap); + firstbitmap += 256; + } + +/* *height = fontInfo->ascent + fontInfo->descent; + *width = fontInfo->max_bounds.width; */ + return new GLFontCallList(font_list_base, fontInfo->ascent, fontInfo->descent, fontInfo->ascent + fontInfo->descent); +} + +#elif 0 + +#include + +GLFont *glfont_create(const char* font_string) +{ + GLuint font_list_base = glGenLists (256); + gint font_height = 0, font_ascent = 0, font_descent = 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) + { + pango_font_description_free (font_desc); + font_desc = pango_font_description_from_string ("fixed 8"); + font = gdk_gl_font_use_pango_font (font_desc, 0, 256, font_list_base); + } + + if(font == 0) + { + pango_font_description_free (font_desc); + font_desc = pango_font_description_from_string ("courier new 8"); + 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_ascent = pango_font_metrics_get_ascent (font_metrics); + font_descent = pango_font_metrics_get_descent (font_metrics); + font_height = font_ascent + font_descent; + + font_ascent = PANGO_PIXELS (font_ascent); + font_descent = PANGO_PIXELS (font_descent); + font_height = PANGO_PIXELS (font_height); + + pango_font_metrics_unref (font_metrics); + } + + pango_font_description_free (font_desc); + + // fix for pango/gtkglext metrix bug + if(font_height > 256) + font_height = 16; + + return new GLFontCallList(font_list_base, font_ascent, font_descent, font_height); +} +#else + +// new font code ripped from ZeroRadiant + +#include +#include + +class GLFontInternal: public GLFont +{ + const char *font_string; + int font_height; + int font_ascent; + int font_descent; + int y_offset_bitmap_render_pango_units; + PangoContext *ft2_context; + PangoFontMap *fontmap; + + public: + GLFontInternal(const char *_font_string): font_string(_font_string) + { + PangoFontDescription *font_desc; + PangoLayout *layout; + PangoRectangle log_rect; + int font_ascent_pango_units; + int font_descent_pango_units; + +#if !PANGO_VERSION_CHECK(1,22,0) + ft2_context = pango_ft2_get_context(72, 72); +#else + fontmap = pango_ft2_font_map_new(); + pango_ft2_font_map_set_resolution(PANGO_FT2_FONT_MAP(fontmap), 72, 72); + ft2_context = pango_font_map_create_context(fontmap); +#endif + + font_desc = pango_font_description_from_string(font_string); + //pango_font_description_set_size(font_desc, 10 * PANGO_SCALE); + pango_context_set_font_description(ft2_context, font_desc); + pango_font_description_free(font_desc); + // TODO fallback to fixed 8, courier new 8 + + layout = pango_layout_new(ft2_context); + +#ifdef FONT_SIZE_WORKAROUND + pango_layout_set_width(layout, -1); // -1 no wrapping. All text on one line. + pango_layout_set_text(layout, "The quick brown fox jumped over the lazy sleeping dog's back then sat on a tack.", -1); // -1 null-terminated string. +#endif + +#if !PANGO_VERSION_CHECK(1,22,0) + PangoLayoutIter *iter; + iter = pango_layout_get_iter(layout); + font_ascent_pango_units = pango_layout_iter_get_baseline(iter); + pango_layout_iter_free(iter); +#else + font_ascent_pango_units = pango_layout_get_baseline(layout); +#endif + pango_layout_get_extents(layout, NULL, &log_rect); + g_object_unref(G_OBJECT(layout)); + font_descent_pango_units = log_rect.height - font_ascent_pango_units; + + font_ascent = PANGO_PIXELS_CEIL(font_ascent_pango_units); + font_descent = PANGO_PIXELS_CEIL(font_descent_pango_units); + font_height = font_ascent + font_descent; + y_offset_bitmap_render_pango_units = (font_ascent * PANGO_SCALE) - font_ascent_pango_units; + } + + virtual ~GLFontInternal() + { + g_object_unref(G_OBJECT(ft2_context)); + g_object_unref(G_OBJECT(fontmap)); + } + + // Renders the input text at the current location with the current color. + // The X position of the current location is used to place the left edge of the text image, + // where the text image bounds are defined as the logical extents of the line of text. + // The Y position of the current location is used to place the bottom of the text image. + // You should offset the Y position by the amount returned by gtk_glwidget_font_descent() + // if you want to place the baseline of the text image at the current Y position. + // Note: A problem with this function is that if the lower left corner of the text falls + // just a hair outside of the viewport (meaning the current raster position is invalid), + // then no text will be rendered. The solution to this is a very hacky one. You can search + // Google for "glDrawPixels clipping". + virtual void printString(const char *s) + { + // The idea for this code initially came from the font-pangoft2.c example that comes with GtkGLExt. + + PangoLayout *layout; + PangoRectangle log_rect; + FT_Bitmap bitmap; + unsigned char *begin_bitmap_buffer; + GLfloat color[4]; + GLint previous_unpack_alignment; + GLboolean previous_blend_enabled; + GLint previous_blend_func_src; + GLint previous_blend_func_dst; + GLfloat previous_red_bias; + GLfloat previous_green_bias; + GLfloat previous_blue_bias; + GLfloat previous_alpha_scale; + + layout = pango_layout_new(ft2_context); + pango_layout_set_width(layout, -1); // -1 no wrapping. All text on one line. + pango_layout_set_text(layout, s, -1); // -1 null-terminated string. + pango_layout_get_extents(layout, NULL, &log_rect); + + if (log_rect.width > 0 && log_rect.height > 0) { + bitmap.rows = font_ascent + font_descent; + bitmap.width = PANGO_PIXELS_CEIL(log_rect.width); + bitmap.pitch = -bitmap.width; // Rendering it "upside down" for OpenGL. + begin_bitmap_buffer = (unsigned char *) g_malloc(bitmap.rows * bitmap.width); + memset(begin_bitmap_buffer, 0, bitmap.rows * bitmap.width); + bitmap.buffer = begin_bitmap_buffer + (bitmap.rows - 1) * bitmap.width; // See pitch above. + bitmap.num_grays = 0xff; + bitmap.pixel_mode = FT_PIXEL_MODE_GRAY; + pango_ft2_render_layout_subpixel(&bitmap, layout, -log_rect.x, + y_offset_bitmap_render_pango_units); + GlobalOpenGL().m_glGetFloatv(GL_CURRENT_COLOR, color); + + // Save state. I didn't see any OpenGL push/pop operations for these. + // Question: Is saving/restoring this state necessary? Being safe. + GlobalOpenGL().m_glGetIntegerv(GL_UNPACK_ALIGNMENT, &previous_unpack_alignment); + previous_blend_enabled = GlobalOpenGL().m_glIsEnabled(GL_BLEND); + GlobalOpenGL().m_glGetIntegerv(GL_BLEND_SRC, &previous_blend_func_src); + GlobalOpenGL().m_glGetIntegerv(GL_BLEND_DST, &previous_blend_func_dst); + GlobalOpenGL().m_glGetFloatv(GL_RED_BIAS, &previous_red_bias); + GlobalOpenGL().m_glGetFloatv(GL_GREEN_BIAS, &previous_green_bias); + GlobalOpenGL().m_glGetFloatv(GL_BLUE_BIAS, &previous_blue_bias); + GlobalOpenGL().m_glGetFloatv(GL_ALPHA_SCALE, &previous_alpha_scale); + + GlobalOpenGL().m_glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + GlobalOpenGL().m_glEnable(GL_BLEND); + GlobalOpenGL().m_glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + GlobalOpenGL().m_glPixelTransferf(GL_RED_BIAS, color[0]); + GlobalOpenGL().m_glPixelTransferf(GL_GREEN_BIAS, color[1]); + GlobalOpenGL().m_glPixelTransferf(GL_BLUE_BIAS, color[2]); + GlobalOpenGL().m_glPixelTransferf(GL_ALPHA_SCALE, color[3]); + + GlobalOpenGL().m_glDrawPixels(bitmap.width, bitmap.rows, + GL_ALPHA, GL_UNSIGNED_BYTE, begin_bitmap_buffer); + g_free(begin_bitmap_buffer); + + // Restore state in reverse order of how we set it. + GlobalOpenGL().m_glPixelTransferf(GL_ALPHA_SCALE, previous_alpha_scale); + GlobalOpenGL().m_glPixelTransferf(GL_BLUE_BIAS, previous_blue_bias); + GlobalOpenGL().m_glPixelTransferf(GL_GREEN_BIAS, previous_green_bias); + GlobalOpenGL().m_glPixelTransferf(GL_RED_BIAS, previous_red_bias); + GlobalOpenGL().m_glBlendFunc(previous_blend_func_src, previous_blend_func_dst); + if (!previous_blend_enabled) { GlobalOpenGL().m_glDisable(GL_BLEND); } + GlobalOpenGL().m_glPixelStorei(GL_UNPACK_ALIGNMENT, previous_unpack_alignment); + } + + g_object_unref(G_OBJECT(layout)); + } + + virtual int getPixelAscent() const + { + return font_ascent; + } + virtual int getPixelDescent() const + { + return font_descent; + } + virtual int getPixelHeight() const + { + return font_height; + } +}; + +GLFont *glfont_create(const char* font_string) +{ + return new GLFontInternal(font_string); +} + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/glfont.h b/misc/mediasource/netradiant-src/libs/gtkutil/glfont.h new file mode 100644 index 00000000..0d1e0000 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/glfont.h @@ -0,0 +1,42 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_GLFONT_H) +#define INCLUDED_GTKUTIL_GLFONT_H + +typedef unsigned int GLuint; + +class GLFont +{ + public: + virtual int getPixelHeight() const = 0; + virtual int getPixelAscent() const = 0; + virtual int getPixelDescent() const = 0; + virtual void printString(const char *s) = 0; + virtual ~GLFont() + { + } +}; + +GLFont *glfont_create(const char* font_string); +// release with delete + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/glwidget.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/glwidget.cpp new file mode 100644 index 00000000..cda5366a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/glwidget.cpp @@ -0,0 +1,274 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 +*/ + +// 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/misc/mediasource/netradiant-src/libs/gtkutil/glwidget.h b/misc/mediasource/netradiant-src/libs/gtkutil/glwidget.h new file mode 100644 index 00000000..235b0908 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/glwidget.h @@ -0,0 +1,39 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/idledraw.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/idledraw.cpp new file mode 100644 index 00000000..47d432ca --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/idledraw.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "idledraw.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/idledraw.h b/misc/mediasource/netradiant-src/libs/gtkutil/idledraw.h new file mode 100644 index 00000000..48081237 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/idledraw.h @@ -0,0 +1,69 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/image.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/image.cpp new file mode 100644 index 00000000..66e61d1e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/image.cpp @@ -0,0 +1,96 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/gtkutil/image.h b/misc/mediasource/netradiant-src/libs/gtkutil/image.h new file mode 100644 index 00000000..bd865142 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/image.h @@ -0,0 +1,36 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/menu.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/menu.cpp new file mode 100644 index 00000000..86be24e7 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/menu.cpp @@ -0,0 +1,311 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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) +{ + 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) +{ + 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/misc/mediasource/netradiant-src/libs/gtkutil/menu.h b/misc/mediasource/netradiant-src/libs/gtkutil/menu.h new file mode 100644 index 00000000..a394d823 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/menu.h @@ -0,0 +1,58 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_MENU_H) +#define INCLUDED_GTKUTIL_MENU_H + +#include "generic/callbackfwd.h" + +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/misc/mediasource/netradiant-src/libs/gtkutil/messagebox.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/messagebox.cpp new file mode 100644 index 00000000..4c430ed3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/messagebox.cpp @@ -0,0 +1,213 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/gtkutil/messagebox.h b/misc/mediasource/netradiant-src/libs/gtkutil/messagebox.h new file mode 100644 index 00000000..8806a3bd --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/messagebox.h @@ -0,0 +1,31 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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 = "NetRadiant", EMessageBoxType type = eMB_OK, EMessageBoxIcon icon = eMB_ICONDEFAULT); + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/nonmodal.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/nonmodal.cpp new file mode 100644 index 00000000..6252e2dd --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/nonmodal.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "nonmodal.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/nonmodal.h b/misc/mediasource/netradiant-src/libs/gtkutil/nonmodal.h new file mode 100644 index 00000000..eed4be37 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/nonmodal.h @@ -0,0 +1,186 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/paned.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/paned.cpp new file mode 100644 index 00000000..db0c308b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/paned.cpp @@ -0,0 +1,100 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/gtkutil/paned.h b/misc/mediasource/netradiant-src/libs/gtkutil/paned.h new file mode 100644 index 00000000..578a3c5d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/paned.h @@ -0,0 +1,29 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/pointer.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/pointer.cpp new file mode 100644 index 00000000..2c36d2d7 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/pointer.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "pointer.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/pointer.h b/misc/mediasource/netradiant-src/libs/gtkutil/pointer.h new file mode 100644 index 00000000..c8294467 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/pointer.h @@ -0,0 +1,40 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/toolbar.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/toolbar.cpp new file mode 100644 index 00000000..194aff2d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/toolbar.cpp @@ -0,0 +1,78 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/gtkutil/toolbar.h b/misc/mediasource/netradiant-src/libs/gtkutil/toolbar.h new file mode 100644 index 00000000..9bf847d2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/toolbar.h @@ -0,0 +1,38 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_TOOLBAR_H) +#define INCLUDED_GTKUTIL_TOOLBAR_H + +#include "generic/callbackfwd.h" + +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/misc/mediasource/netradiant-src/libs/gtkutil/widget.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/widget.cpp new file mode 100644 index 00000000..62a1b6ca --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/widget.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "widget.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/widget.h b/misc/mediasource/netradiant-src/libs/gtkutil/widget.h new file mode 100644 index 00000000..225fccf4 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/widget.h @@ -0,0 +1,190 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GTKUTIL_WIDGET_H) +#define INCLUDED_GTKUTIL_WIDGET_H + +#include +#include +#include "generic/callback.h" +#include "warnings.h" +#include "debugging/debugging.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); +} + +class WidgetFocusPrinter +{ + const char* m_name; + + static gboolean focus_in(GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self) + { + globalOutputStream() << self->m_name << " takes focus\n"; + return FALSE; + } + static gboolean focus_out(GtkWidget *widget, GdkEventFocus *event, WidgetFocusPrinter* self) + { + globalOutputStream() << self->m_name << " loses focus\n"; + return FALSE; + } +public: + WidgetFocusPrinter(const char* name) : m_name(name) + { + } + void connect(GtkWidget* widget) + { + g_signal_connect(G_OBJECT(widget), "focus_in_event", G_CALLBACK(focus_in), this); + g_signal_connect(G_OBJECT(widget), "focus_out_event", G_CALLBACK(focus_out), this); + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/window.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/window.cpp new file mode 100644 index 00000000..5d465531 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/window.cpp @@ -0,0 +1,170 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/gtkutil/window.h b/misc/mediasource/netradiant-src/libs/gtkutil/window.h new file mode 100644 index 00000000..5ab1e500 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/window.h @@ -0,0 +1,174 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/gtkutil/xorrectangle.cpp b/misc/mediasource/netradiant-src/libs/gtkutil/xorrectangle.cpp new file mode 100644 index 00000000..d968337d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/xorrectangle.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "xorrectangle.h" + diff --git a/misc/mediasource/netradiant-src/libs/gtkutil/xorrectangle.h b/misc/mediasource/netradiant-src/libs/gtkutil/xorrectangle.h new file mode 100644 index 00000000..0d89203e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/gtkutil/xorrectangle.h @@ -0,0 +1,125 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (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/misc/mediasource/netradiant-src/libs/imagelib.cpp b/misc/mediasource/netradiant-src/libs/imagelib.cpp new file mode 100644 index 00000000..5c205f63 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/imagelib.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "imagelib.h" + diff --git a/misc/mediasource/netradiant-src/libs/imagelib.h b/misc/mediasource/netradiant-src/libs/imagelib.h new file mode 100644 index 00000000..5a1afa67 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/imagelib.h @@ -0,0 +1,152 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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, int 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/misc/mediasource/netradiant-src/libs/instancelib.cpp b/misc/mediasource/netradiant-src/libs/instancelib.cpp new file mode 100644 index 00000000..053ac73b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/instancelib.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "instancelib.h" diff --git a/misc/mediasource/netradiant-src/libs/instancelib.h b/misc/mediasource/netradiant-src/libs/instancelib.h new file mode 100644 index 00000000..9ff32e6d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/instancelib.h @@ -0,0 +1,193 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (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 InstanceSet : 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(), "InstanceSet::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(), "InstanceSet::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; +}; + +template +inline void InstanceSet_forEach(InstanceSet& instances, const Functor& functor) +{ + for(InstanceSet::iterator i = instances.begin(), end = instances.end(); i != end; ++i) + { + functor(*(*i).second); + } +} + +template +class InstanceEvaluateTransform +{ +public: + inline void operator()(scene::Instance& instance) const + { + InstanceTypeCast::cast(instance)->evaluateTransform(); + } +}; + +template +class InstanceSetEvaluateTransform +{ +public: + static void apply(InstanceSet& instances) + { + InstanceSet_forEach(instances, InstanceEvaluateTransform()); + } + typedef ReferenceCaller::apply> Caller; +}; + +#endif diff --git a/misc/mediasource/netradiant-src/libs/jpeg6/.cvswrappers b/misc/mediasource/netradiant-src/libs/jpeg6/.cvswrappers new file mode 100644 index 00000000..ed97d402 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/.cvswrappers @@ -0,0 +1,3 @@ +*.dsp -m 'COPY' -k 'b' +*.dsw -m 'COPY' -k 'b' +*.scc -m 'COPY' -k 'b' diff --git a/misc/mediasource/netradiant-src/libs/jpeg6/README b/misc/mediasource/netradiant-src/libs/jpeg6/README new file mode 100644 index 00000000..86cc2066 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/README @@ -0,0 +1,385 @@ +The Independent JPEG Group's JPEG software +========================================== + +README for release 6b of 27-Mar-1998 +==================================== + +This distribution contains the sixth public release of the Independent JPEG +Group's free JPEG software. You are welcome to redistribute this software and +to use it for any purpose, subject to the conditions under LEGAL ISSUES, below. + +Serious users of this software (particularly those incorporating it into +larger programs) should contact IJG at jpeg-info@uunet.uu.net to be added to +our electronic mailing list. Mailing list members are notified of updates +and have a chance to participate in technical discussions, etc. + +This software is the work of Tom Lane, Philip Gladstone, Jim Boucher, +Lee Crocker, Julian Minguillon, Luis Ortiz, George Phillips, Davide Rossi, +Guido Vollbeding, Ge' Weijers, and other members of the Independent JPEG +Group. + +IJG is not affiliated with the official ISO JPEG standards committee. + + +DOCUMENTATION ROADMAP +===================== + +This file contains the following sections: + +OVERVIEW General description of JPEG and the IJG software. +LEGAL ISSUES Copyright, lack of warranty, terms of distribution. +REFERENCES Where to learn more about JPEG. +ARCHIVE LOCATIONS Where to find newer versions of this software. +RELATED SOFTWARE Other stuff you should get. +FILE FORMAT WARS Software *not* to get. +TO DO Plans for future IJG releases. + +Other documentation files in the distribution are: + +User documentation: + install.doc How to configure and install the IJG software. + usage.doc Usage instructions for cjpeg, djpeg, jpegtran, + rdjpgcom, and wrjpgcom. + *.1 Unix-style man pages for programs (same info as usage.doc). + wizard.doc Advanced usage instructions for JPEG wizards only. + change.log Version-to-version change highlights. +Programmer and internal documentation: + libjpeg.doc How to use the JPEG library in your own programs. + example.c Sample code for calling the JPEG library. + structure.doc Overview of the JPEG library's internal structure. + filelist.doc Road map of IJG files. + coderules.doc Coding style rules --- please read if you contribute code. + +Please read at least the files install.doc and usage.doc. Useful information +can also be found in the JPEG FAQ (Frequently Asked Questions) article. See +ARCHIVE LOCATIONS below to find out where to obtain the FAQ article. + +If you want to understand how the JPEG code works, we suggest reading one or +more of the REFERENCES, then looking at the documentation files (in roughly +the order listed) before diving into the code. + + +OVERVIEW +======== + +This package contains C software to implement JPEG image compression and +decompression. JPEG (pronounced "jay-peg") is a standardized compression +method for full-color and gray-scale images. JPEG is intended for compressing +"real-world" scenes; line drawings, cartoons and other non-realistic images +are not its strong suit. JPEG is lossy, meaning that the output image is not +exactly identical to the input image. Hence you must not use JPEG if you +have to have identical output bits. However, on typical photographic images, +very good compression levels can be obtained with no visible change, and +remarkably high compression levels are possible if you can tolerate a +low-quality image. For more details, see the references, or just experiment +with various compression settings. + +This software implements JPEG baseline, extended-sequential, and progressive +compression processes. Provision is made for supporting all variants of these +processes, although some uncommon parameter settings aren't implemented yet. +For legal reasons, we are not distributing code for the arithmetic-coding +variants of JPEG; see LEGAL ISSUES. We have made no provision for supporting +the hierarchical or lossless processes defined in the standard. + +We provide a set of library routines for reading and writing JPEG image files, +plus two sample applications "cjpeg" and "djpeg", which use the library to +perform conversion between JPEG and some other popular image file formats. +The library is intended to be reused in other applications. + +In order to support file conversion and viewing software, we have included +considerable functionality beyond the bare JPEG coding/decoding capability; +for example, the color quantization modules are not strictly part of JPEG +decoding, but they are essential for output to colormapped file formats or +colormapped displays. These extra functions can be compiled out of the +library if not required for a particular application. We have also included +"jpegtran", a utility for lossless transcoding between different JPEG +processes, and "rdjpgcom" and "wrjpgcom", two simple applications for +inserting and extracting textual comments in JFIF files. + +The emphasis in designing this software has been on achieving portability and +flexibility, while also making it fast enough to be useful. In particular, +the software is not intended to be read as a tutorial on JPEG. (See the +REFERENCES section for introductory material.) Rather, it is intended to +be reliable, portable, industrial-strength code. We do not claim to have +achieved that goal in every aspect of the software, but we strive for it. + +We welcome the use of this software as a component of commercial products. +No royalty is required, but we do ask for an acknowledgement in product +documentation, as described under LEGAL ISSUES. + + +LEGAL ISSUES +============ + +In plain English: + +1. We don't promise that this software works. (But if you find any bugs, + please let us know!) +2. You can use this software for whatever you want. You don't have to pay us. +3. You may not pretend that you wrote this software. If you use it in a + program, you must acknowledge somewhere in your documentation that + you've used the IJG code. + +In legalese: + +The authors make NO WARRANTY or representation, either express or implied, +with respect to this software, its quality, accuracy, merchantability, or +fitness for a particular purpose. This software is provided "AS IS", and you, +its user, assume the entire risk as to its quality and accuracy. + +This software is copyright (C) 1991-1998, Thomas G. Lane. +All Rights Reserved except as specified below. + +Permission is hereby granted to use, copy, modify, and distribute this +software (or portions thereof) for any purpose, without fee, subject to these +conditions: +(1) If any part of the source code for this software is distributed, then this +README file must be included, with this copyright and no-warranty notice +unaltered; and any additions, deletions, or changes to the original files +must be clearly indicated in accompanying documentation. +(2) If only executable code is distributed, then the accompanying +documentation must state that "this software is based in part on the work of +the Independent JPEG Group". +(3) Permission for use of this software is granted only if the user accepts +full responsibility for any undesirable consequences; the authors accept +NO LIABILITY for damages of any kind. + +These conditions apply to any software derived from or based on the IJG code, +not just to the unmodified library. If you use our work, you ought to +acknowledge us. + +Permission is NOT granted for the use of any IJG author's name or company name +in advertising or publicity relating to this software or products derived from +it. This software may be referred to only as "the Independent JPEG Group's +software". + +We specifically permit and encourage the use of this software as the basis of +commercial products, provided that all warranty or liability claims are +assumed by the product vendor. + + +ansi2knr.c is included in this distribution by permission of L. Peter Deutsch, +sole proprietor of its copyright holder, Aladdin Enterprises of Menlo Park, CA. +ansi2knr.c is NOT covered by the above copyright and conditions, but instead +by the usual distribution terms of the Free Software Foundation; principally, +that you must include source code if you redistribute it. (See the file +ansi2knr.c for full details.) However, since ansi2knr.c is not needed as part +of any program generated from the IJG code, this does not limit you more than +the foregoing paragraphs do. + +The Unix configuration script "configure" was produced with GNU Autoconf. +It is copyright by the Free Software Foundation but is freely distributable. +The same holds for its supporting scripts (config.guess, config.sub, +ltconfig, ltmain.sh). Another support script, install-sh, is copyright +by M.I.T. but is also freely distributable. + +It appears that the arithmetic coding option of the JPEG spec is covered by +patents owned by IBM, AT&T, and Mitsubishi. Hence arithmetic coding cannot +legally be used without obtaining one or more licenses. For this reason, +support for arithmetic coding has been removed from the free JPEG software. +(Since arithmetic coding provides only a marginal gain over the unpatented +Huffman mode, it is unlikely that very many implementations will support it.) +So far as we are aware, there are no patent restrictions on the remaining +code. + +The IJG distribution formerly included code to read and write GIF files. +To avoid entanglement with the Unisys LZW patent, GIF reading support has +been removed altogether, and the GIF writer has been simplified to produce +"uncompressed GIFs". This technique does not use the LZW algorithm; the +resulting GIF files are larger than usual, but are readable by all standard +GIF decoders. + +We are required to state that + "The Graphics Interchange Format(c) is the Copyright property of + CompuServe Incorporated. GIF(sm) is a Service Mark property of + CompuServe Incorporated." + + +REFERENCES +========== + +We highly recommend reading one or more of these references before trying to +understand the innards of the JPEG software. + +The best short technical introduction to the JPEG compression algorithm is + Wallace, Gregory K. "The JPEG Still Picture Compression Standard", + Communications of the ACM, April 1991 (vol. 34 no. 4), pp. 30-44. +(Adjacent articles in that issue discuss MPEG motion picture compression, +applications of JPEG, and related topics.) If you don't have the CACM issue +handy, a PostScript file containing a revised version of Wallace's article is +available at ftp://ftp.uu.net/graphics/jpeg/wallace.ps.gz. The file (actually +a preprint for an article that appeared in IEEE Trans. Consumer Electronics) +omits the sample images that appeared in CACM, but it includes corrections +and some added material. Note: the Wallace article is copyright ACM and IEEE, +and it may not be used for commercial purposes. + +A somewhat less technical, more leisurely introduction to JPEG can be found in +"The Data Compression Book" by Mark Nelson and Jean-loup Gailly, published by +M&T Books (New York), 2nd ed. 1996, ISBN 1-55851-434-1. This book provides +good explanations and example C code for a multitude of compression methods +including JPEG. It is an excellent source if you are comfortable reading C +code but don't know much about data compression in general. The book's JPEG +sample code is far from industrial-strength, but when you are ready to look +at a full implementation, you've got one here... + +The best full description of JPEG is the textbook "JPEG Still Image Data +Compression Standard" by William B. Pennebaker and Joan L. Mitchell, published +by Van Nostrand Reinhold, 1993, ISBN 0-442-01272-1. Price US$59.95, 638 pp. +The book includes the complete text of the ISO JPEG standards (DIS 10918-1 +and draft DIS 10918-2). This is by far the most complete exposition of JPEG +in existence, and we highly recommend it. + +The JPEG standard itself is not available electronically; you must order a +paper copy through ISO or ITU. (Unless you feel a need to own a certified +official copy, we recommend buying the Pennebaker and Mitchell book instead; +it's much cheaper and includes a great deal of useful explanatory material.) +In the USA, copies of the standard may be ordered from ANSI Sales at (212) +642-4900, or from Global Engineering Documents at (800) 854-7179. (ANSI +doesn't take credit card orders, but Global does.) It's not cheap: as of +1992, ANSI was charging $95 for Part 1 and $47 for Part 2, plus 7% +shipping/handling. The standard is divided into two parts, Part 1 being the +actual specification, while Part 2 covers compliance testing methods. Part 1 +is titled "Digital Compression and Coding of Continuous-tone Still Images, +Part 1: Requirements and guidelines" and has document numbers ISO/IEC IS +10918-1, ITU-T T.81. Part 2 is titled "Digital Compression and Coding of +Continuous-tone Still Images, Part 2: Compliance testing" and has document +numbers ISO/IEC IS 10918-2, ITU-T T.83. + +Some extensions to the original JPEG standard are defined in JPEG Part 3, +a newer ISO standard numbered ISO/IEC IS 10918-3 and ITU-T T.84. IJG +currently does not support any Part 3 extensions. + +The JPEG standard does not specify all details of an interchangeable file +format. For the omitted details we follow the "JFIF" conventions, revision +1.02. A copy of the JFIF spec is available from: + Literature Department + C-Cube Microsystems, Inc. + 1778 McCarthy Blvd. + Milpitas, CA 95035 + phone (408) 944-6300, fax (408) 944-6314 +A PostScript version of this document is available by FTP at +ftp://ftp.uu.net/graphics/jpeg/jfif.ps.gz. There is also a plain text +version at ftp://ftp.uu.net/graphics/jpeg/jfif.txt.gz, but it is missing +the figures. + +The TIFF 6.0 file format specification can be obtained by FTP from +ftp://ftp.sgi.com/graphics/tiff/TIFF6.ps.gz. The JPEG incorporation scheme +found in the TIFF 6.0 spec of 3-June-92 has a number of serious problems. +IJG does not recommend use of the TIFF 6.0 design (TIFF Compression tag 6). +Instead, we recommend the JPEG design proposed by TIFF Technical Note #2 +(Compression tag 7). Copies of this Note can be obtained from ftp.sgi.com or +from ftp://ftp.uu.net/graphics/jpeg/. It is expected that the next revision +of the TIFF spec will replace the 6.0 JPEG design with the Note's design. +Although IJG's own code does not support TIFF/JPEG, the free libtiff library +uses our library to implement TIFF/JPEG per the Note. libtiff is available +from ftp://ftp.sgi.com/graphics/tiff/. + + +ARCHIVE LOCATIONS +================= + +The "official" archive site for this software is ftp.uu.net (Internet +address 192.48.96.9). The most recent released version can always be found +there in directory graphics/jpeg. This particular version will be archived +as ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz. If you don't have +direct Internet access, UUNET's archives are also available via UUCP; contact +help@uunet.uu.net for information on retrieving files that way. + +Numerous Internet sites maintain copies of the UUNET files. However, only +ftp.uu.net is guaranteed to have the latest official version. + +You can also obtain this software in DOS-compatible "zip" archive format from +the SimTel archives (ftp://ftp.simtel.net/pub/simtelnet/msdos/graphics/), or +on CompuServe in the Graphics Support forum (GO CIS:GRAPHSUP), library 12 +"JPEG Tools". Again, these versions may sometimes lag behind the ftp.uu.net +release. + +The JPEG FAQ (Frequently Asked Questions) article is a useful source of +general information about JPEG. It is updated constantly and therefore is +not included in this distribution. The FAQ is posted every two weeks to +Usenet newsgroups comp.graphics.misc, news.answers, and other groups. +It is available on the World Wide Web at http://www.faqs.org/faqs/jpeg-faq/ +and other news.answers archive sites, including the official news.answers +archive at rtfm.mit.edu: ftp://rtfm.mit.edu/pub/usenet/news.answers/jpeg-faq/. +If you don't have Web or FTP access, send e-mail to mail-server@rtfm.mit.edu +with body + send usenet/news.answers/jpeg-faq/part1 + send usenet/news.answers/jpeg-faq/part2 + + +RELATED SOFTWARE +================ + +Numerous viewing and image manipulation programs now support JPEG. (Quite a +few of them use this library to do so.) The JPEG FAQ described above lists +some of the more popular free and shareware viewers, and tells where to +obtain them on Internet. + +If you are on a Unix machine, we highly recommend Jef Poskanzer's free +PBMPLUS software, which provides many useful operations on PPM-format image +files. In particular, it can convert PPM images to and from a wide range of +other formats, thus making cjpeg/djpeg considerably more useful. The latest +version is distributed by the NetPBM group, and is available from numerous +sites, notably ftp://wuarchive.wustl.edu/graphics/graphics/packages/NetPBM/. +Unfortunately PBMPLUS/NETPBM is not nearly as portable as the IJG software is; +you are likely to have difficulty making it work on any non-Unix machine. + +A different free JPEG implementation, written by the PVRG group at Stanford, +is available from ftp://havefun.stanford.edu/pub/jpeg/. This program +is designed for research and experimentation rather than production use; +it is slower, harder to use, and less portable than the IJG code, but it +is easier to read and modify. Also, the PVRG code supports lossless JPEG, +which we do not. (On the other hand, it doesn't do progressive JPEG.) + + +FILE FORMAT WARS +================ + +Some JPEG programs produce files that are not compatible with our library. +The root of the problem is that the ISO JPEG committee failed to specify a +concrete file format. Some vendors "filled in the blanks" on their own, +creating proprietary formats that no one else could read. (For example, none +of the early commercial JPEG implementations for the Macintosh were able to +exchange compressed files.) + +The file format we have adopted is called JFIF (see REFERENCES). This format +has been agreed to by a number of major commercial JPEG vendors, and it has +become the de facto standard. JFIF is a minimal or "low end" representation. +We recommend the use of TIFF/JPEG (TIFF revision 6.0 as modified by TIFF +Technical Note #2) for "high end" applications that need to record a lot of +additional data about an image. TIFF/JPEG is fairly new and not yet widely +supported, unfortunately. + +The upcoming JPEG Part 3 standard defines a file format called SPIFF. +SPIFF is interoperable with JFIF, in the sense that most JFIF decoders should +be able to read the most common variant of SPIFF. SPIFF has some technical +advantages over JFIF, but its major claim to fame is simply that it is an +official standard rather than an informal one. At this point it is unclear +whether SPIFF will supersede JFIF or whether JFIF will remain the de-facto +standard. IJG intends to support SPIFF once the standard is frozen, but we +have not decided whether it should become our default output format or not. +(In any case, our decoder will remain capable of reading JFIF indefinitely.) + +Various proprietary file formats incorporating JPEG compression also exist. +We have little or no sympathy for the existence of these formats. Indeed, +one of the original reasons for developing this free software was to help +force convergence on common, open format standards for JPEG files. Don't +use a proprietary file format! + + +TO DO +===== + +The major thrust for v7 will probably be improvement of visual quality. +The current method for scaling the quantization tables is known not to be +very good at low Q values. We also intend to investigate block boundary +smoothing, "poor man's variable quantization", and other means of improving +quality-vs-file-size performance without sacrificing compatibility. + +In future versions, we are considering supporting some of the upcoming JPEG +Part 3 extensions --- principally, variable quantization and the SPIFF file +format. + +As always, speeding things up is of great interest. + +Please send bug reports, offers of help, etc. to jpeg-info@uunet.uu.net. diff --git a/misc/mediasource/netradiant-src/libs/jpeg6/jchuff.h b/misc/mediasource/netradiant-src/libs/jpeg6/jchuff.h new file mode 100644 index 00000000..f43d571d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jchuff.h @@ -0,0 +1,34 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jcomapi.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jcomapi.cpp new file mode 100644 index 00000000..df3302cb --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jcomapi.cpp @@ -0,0 +1,94 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jconfig.h b/misc/mediasource/netradiant-src/libs/jpeg6/jconfig.h new file mode 100644 index 00000000..7d2f733b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jconfig.h @@ -0,0 +1,41 @@ +/* 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/misc/mediasource/netradiant-src/libs/jpeg6/jdapimin.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdapimin.cpp new file mode 100644 index 00000000..c5c3be32 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdapimin.cpp @@ -0,0 +1,400 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdapistd.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdapistd.cpp new file mode 100644 index 00000000..22da01b3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdapistd.cpp @@ -0,0 +1,275 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdatasrc.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdatasrc.cpp new file mode 100644 index 00000000..9bb30dbe --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdatasrc.cpp @@ -0,0 +1,189 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdcoefct.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdcoefct.cpp new file mode 100644 index 00000000..4b371313 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdcoefct.cpp @@ -0,0 +1,725 @@ +/* + * 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< 0 && pred >= (1<= 0) { + pred = (int) (((Q10<<7) + num) / (Q10<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (int) (((Q20<<7) + num) / (Q20<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (int) (((Q11<<7) + num) / (Q11<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<= 0) { + pred = (int) (((Q02<<7) + num) / (Q02<<8)); + if (Al > 0 && pred >= (1< 0 && pred >= (1<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/misc/mediasource/netradiant-src/libs/jpeg6/jdcolor.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdcolor.cpp new file mode 100644 index 00000000..50e66f26 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdcolor.cpp @@ -0,0 +1,367 @@ +/* + * 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<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/misc/mediasource/netradiant-src/libs/jpeg6/jdct.h b/misc/mediasource/netradiant-src/libs/jpeg6/jdct.h new file mode 100644 index 00000000..3ce790bc --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdct.h @@ -0,0 +1,176 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jddctmgr.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jddctmgr.cpp new file mode 100644 index 00000000..5267ade9 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jddctmgr.cpp @@ -0,0 +1,270 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdhuff.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdhuff.cpp new file mode 100644 index 00000000..025d5187 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdhuff.cpp @@ -0,0 +1,574 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdhuff.h b/misc/mediasource/netradiant-src/libs/jpeg6/jdhuff.h new file mode 100644 index 00000000..d375c781 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdhuff.h @@ -0,0 +1,202 @@ +/* + * 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< 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/misc/mediasource/netradiant-src/libs/jpeg6/jdinput.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdinput.cpp new file mode 100644 index 00000000..f48307d0 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdinput.cpp @@ -0,0 +1,381 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdmainct.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdmainct.cpp new file mode 100644 index 00000000..d445649f --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdmainct.cpp @@ -0,0 +1,512 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdmarker.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdmarker.cpp new file mode 100644 index 00000000..b897b507 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdmarker.cpp @@ -0,0 +1,1052 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdmaster.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdmaster.cpp new file mode 100644 index 00000000..6d38f604 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdmaster.cpp @@ -0,0 +1,558 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdpostct.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdpostct.cpp new file mode 100644 index 00000000..e8b934cc --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdpostct.cpp @@ -0,0 +1,290 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdsample.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdsample.cpp new file mode 100644 index 00000000..f53ceaf3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdsample.cpp @@ -0,0 +1,478 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jdtrans.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jdtrans.cpp new file mode 100644 index 00000000..3f05ae37 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jdtrans.cpp @@ -0,0 +1,122 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jerror.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jerror.cpp new file mode 100644 index 00000000..dda71a56 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jerror.cpp @@ -0,0 +1,233 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jerror.h b/misc/mediasource/netradiant-src/libs/jpeg6/jerror.h new file mode 100644 index 00000000..86a36c70 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jerror.h @@ -0,0 +1,278 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jfdctflt.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jfdctflt.cpp new file mode 100644 index 00000000..785e93ef --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jfdctflt.cpp @@ -0,0 +1,168 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jidctflt.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jidctflt.cpp new file mode 100644 index 00000000..82d1e61d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jidctflt.cpp @@ -0,0 +1,241 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jinclude.h b/misc/mediasource/netradiant-src/libs/jpeg6/jinclude.h new file mode 100644 index 00000000..0a4f1514 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jinclude.h @@ -0,0 +1,91 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jmemmgr.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jmemmgr.cpp new file mode 100644 index 00000000..9862e2f8 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jmemmgr.cpp @@ -0,0 +1,1115 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jmemnobs.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jmemnobs.cpp new file mode 100644 index 00000000..df0abb0c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jmemnobs.cpp @@ -0,0 +1,103 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jmemsys.h b/misc/mediasource/netradiant-src/libs/jpeg6/jmemsys.h new file mode 100644 index 00000000..033d29a7 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jmemsys.h @@ -0,0 +1,182 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jmorecfg.h b/misc/mediasource/netradiant-src/libs/jpeg6/jmorecfg.h new file mode 100644 index 00000000..e14f31bd --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jmorecfg.h @@ -0,0 +1,348 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jpegint.h b/misc/mediasource/netradiant-src/libs/jpeg6/jpegint.h new file mode 100644 index 00000000..ab5bee2c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jpegint.h @@ -0,0 +1,388 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jpgload.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jpgload.cpp new file mode 100644 index 00000000..fa3523ed --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jpgload.cpp @@ -0,0 +1,200 @@ +/* +Copyright (C) 1999-2006 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 "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; + int i; + + // 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. + */ + + if( cinfo.output_components != 1 && cinfo.output_components != 3 && cinfo.output_components != 4 ) + { + *pic = const_cast(reinterpret_cast("Non-Y/RGB/RGBA 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*4; + + 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 ); + + // we convert downwards to not overwrite values we want to read later + switch(cinfo.output_components) + { + case 4: + // clear all the alphas to 255 + for(i = cinfo.output_width; i-- > 0; ) + { + bbuf[i*4+3] = 255; + } + break; + case 3: + // expand 3 to 4 + for(i = cinfo.output_width; i-- > 0; ) + { + bbuf[i*4+3] = 255; + bbuf[i*4+2] = bbuf[i*3+2]; + bbuf[i*4+1] = bbuf[i*3+1]; + bbuf[i*4+0] = bbuf[i*3+0]; + } + break; + case 1: + // expand 1 to 4 + for(i = cinfo.output_width; i-- > 0; ) + { + bbuf[i*4+3] = 255; + bbuf[i*4+2] = bbuf[i]; + bbuf[i*4+1] = bbuf[i]; + bbuf[i*4+0] = bbuf[i]; + } + break; + } + } + + /* 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/misc/mediasource/netradiant-src/libs/jpeg6/jutils.cpp b/misc/mediasource/netradiant-src/libs/jpeg6/jutils.cpp new file mode 100644 index 00000000..549648de --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jutils.cpp @@ -0,0 +1,175 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeg6/jversion.h b/misc/mediasource/netradiant-src/libs/jpeg6/jversion.h new file mode 100644 index 00000000..f2f1b8da --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeg6/jversion.h @@ -0,0 +1,14 @@ +/* + * 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/misc/mediasource/netradiant-src/libs/jpeglib.h b/misc/mediasource/netradiant-src/libs/jpeglib.h new file mode 100644 index 00000000..f5b59010 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/jpeglib.h @@ -0,0 +1,1123 @@ +/* +Copyright (C) 1999-2006 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 (WIN32) + +#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/misc/mediasource/netradiant-src/libs/l_net/l_net.c b/misc/mediasource/netradiant-src/libs/l_net/l_net.c new file mode 100644 index 00000000..ca730d03 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/l_net/l_net.c @@ -0,0 +1,626 @@ +/* +Copyright (C) 1999-2006 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(const char *str, ...) +{ + va_list argptr; + char text[4096]; + + va_start (argptr,str); + vsprintf (text, str, argptr); + va_end (argptr); + + printf(text); +} +#else +void WinPrint(const 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); +#else + 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(const 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 + memcpy(&msg->data[msg->size], string, strlen(string) + 1); + 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->read + 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 ((size_t) l < sizeof(string)-1); + string[l] = 0; + return string; +} //end of the function NMSG_ReadString diff --git a/misc/mediasource/netradiant-src/libs/l_net/l_net.h b/misc/mediasource/netradiant-src/libs/l_net/l_net.h new file mode 100644 index 00000000..6c548334 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/l_net/l_net.h @@ -0,0 +1,127 @@ +/* +Copyright (C) 1999-2006 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; + +void WinPrint(const char *format, ...); + +//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(const 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 +const char *WINS_ErrorMessage(int error); + +#ifdef __cplusplus +} +#endif diff --git a/misc/mediasource/netradiant-src/libs/l_net/l_net_berkley.c b/misc/mediasource/netradiant-src/libs/l_net/l_net_berkley.c new file mode 100644 index 00000000..edc06fa1 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/l_net/l_net_berkley.c @@ -0,0 +1,770 @@ +/* +Copyright (C) 1999-2006 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 +#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: - +//=========================================================================== +const 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; +/* + 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) +{ + socklen_t 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) +{ + socklen_t 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; + ret = 0; + + 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) +{ + socklen_t 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/misc/mediasource/netradiant-src/libs/l_net/l_net_wins.c b/misc/mediasource/netradiant-src/libs/l_net/l_net_wins.c new file mode 100644 index 00000000..1b365da0 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/l_net/l_net_wins.c @@ -0,0 +1,783 @@ +/* +Copyright (C) 1999-2006 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} +}; + +//=========================================================================== +// +// Parameter: - +// Returns: - +// Changes Globals: - +//=========================================================================== +const 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/misc/mediasource/netradiant-src/libs/l_net/l_net_wins.h b/misc/mediasource/netradiant-src/libs/l_net/l_net_wins.h new file mode 100644 index 00000000..ad1b41fb --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/l_net/l_net_wins.h @@ -0,0 +1,52 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/libs/maplib.cpp b/misc/mediasource/netradiant-src/libs/maplib.cpp new file mode 100644 index 00000000..80504f1d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/maplib.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "maplib.h" diff --git a/misc/mediasource/netradiant-src/libs/maplib.h b/misc/mediasource/netradiant-src/libs/maplib.h new file mode 100644 index 00000000..6a2d5cea --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/maplib.h @@ -0,0 +1,282 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (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; + InstanceSet m_instances; + typedef SelectableInstance Instance; + NameableString m_name; + UndoFileChangeTracker m_changeTracker; +public: + typedef LazyStatic StaticTypeCasts; + + scene::Traversable& get(NullType) + { + return m_traverse; + } + TransformNode& 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/misc/mediasource/netradiant-src/libs/math/aabb.cpp b/misc/mediasource/netradiant-src/libs/math/aabb.cpp new file mode 100644 index 00000000..8bed2209 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/aabb.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "aabb.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/aabb.h b/misc/mediasource/netradiant-src/libs/math/aabb.h new file mode 100644 index 00000000..1341a340 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/aabb.h @@ -0,0 +1,331 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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< IntegralConstant<0> >::apply(aabb, point); + AABBExtend< IntegralConstant<1> >::apply(aabb, point); + AABBExtend< IntegralConstant<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< IntegralConstant<0> >::apply(aabb, other); + AABBExtend< IntegralConstant<1> >::apply(aabb, other); + AABBExtend< IntegralConstant<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< IntegralConstant<0> >(aabb, point) + && aabb_intersects_point_dimension< IntegralConstant<1> >(aabb, point) + && aabb_intersects_point_dimension< IntegralConstant<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< IntegralConstant<0> >(aabb, other) + && aabb_intersects_aabb_dimension< IntegralConstant<1> >(aabb, other) + && aabb_intersects_aabb_dimension< IntegralConstant<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_corners_oriented(const AABB& aabb, const Matrix4& rotation, Vector3 corners[8]) +{ + Vector3 x = vector4_to_vector3(rotation.x()) * aabb.extents.x(); + Vector3 y = vector4_to_vector3(rotation.y()) * aabb.extents.y(); + Vector3 z = vector4_to_vector3(rotation.z()) * aabb.extents.z(); + + corners[0] = aabb.origin + -x + y + z; + corners[1] = aabb.origin + x + y + z; + corners[2] = aabb.origin + x + -y + z; + corners[3] = aabb.origin + -x + -y + z; + corners[4] = aabb.origin + -x + y + -z; + corners[5] = aabb.origin + x + y + -z; + corners[6] = aabb.origin + x + -y + -z; + corners[7] = aabb.origin + -x + -y + -z; +} + +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])); +} + +inline void aabb_planes_oriented(const AABB& aabb, const Matrix4& rotation, Plane3 planes[6]) +{ + double x = vector3_dot(vector4_to_vector3(rotation.x()), aabb.origin); + double y = vector3_dot(vector4_to_vector3(rotation.y()), aabb.origin); + double z = vector3_dot(vector4_to_vector3(rotation.z()), aabb.origin); + + planes[0] = Plane3(vector4_to_vector3(rotation.x()), x + aabb.extents[0]); + planes[1] = Plane3(-vector4_to_vector3(rotation.x()), -(x - aabb.extents[0])); + planes[2] = Plane3(vector4_to_vector3(rotation.y()), y + aabb.extents[1]); + planes[3] = Plane3(-vector4_to_vector3(rotation.y()), -(y - aabb.extents[1])); + planes[4] = Plane3(vector4_to_vector3(rotation.z()), z + aabb.extents[2]); + planes[5] = Plane3(-vector4_to_vector3(rotation.z()), -(z - 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/misc/mediasource/netradiant-src/libs/math/curve.cpp b/misc/mediasource/netradiant-src/libs/math/curve.cpp new file mode 100644 index 00000000..dd2bc0e3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/curve.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "curve.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/curve.h b/misc/mediasource/netradiant-src/libs/math/curve.h new file mode 100644 index 00000000..9000734c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/curve.h @@ -0,0 +1,273 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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 IntegralConstant<0> Zero; +typedef IntegralConstant<1> One; +typedef IntegralConstant<2> Two; +typedef IntegralConstant<3> Three; +typedef IntegralConstant<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/misc/mediasource/netradiant-src/libs/math/expression.cpp b/misc/mediasource/netradiant-src/libs/math/expression.cpp new file mode 100644 index 00000000..5fc8d051 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/expression.cpp @@ -0,0 +1,243 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/math/expression.h b/misc/mediasource/netradiant-src/libs/math/expression.h new file mode 100644 index 00000000..c609bb16 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/expression.h @@ -0,0 +1,617 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (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 IntegralConstant<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 IntegralConstant<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< IntegralConstant >::apply(first, second) + ); + } + }; + + template<> + struct eval_dot< IntegralConstant<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< IntegralConstant >::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< IntegralConstant >::apply(first) + ); + } + }; + + template<> + struct eval_squared< IntegralConstant<0> > + { + static value_type apply(const First& first) + { + return squared(first.eval(0)); + } + }; + + value_type eval() const + { + return eval_squared< IntegralConstant >::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 IntegralConstant<4> dimension0; + typedef IntegralConstant<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 IntegralConstant<4> dimension0; + typedef IntegralConstant<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/misc/mediasource/netradiant-src/libs/math/frustum.cpp b/misc/mediasource/netradiant-src/libs/math/frustum.cpp new file mode 100644 index 00000000..84481e20 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/frustum.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "frustum.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/frustum.h b/misc/mediasource/netradiant-src/libs/math/frustum.h new file mode 100644 index 00000000..fe98db20 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/frustum.h @@ -0,0 +1,629 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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< IntegralConstant<0> >::compare(p)) +#define CLIP_X_GT_W(p) (Vector4ClipGT< IntegralConstant<0> >::compare(p)) +#define CLIP_Y_LT_W(p) (Vector4ClipLT< IntegralConstant<1> >::compare(p)) +#define CLIP_Y_GT_W(p) (Vector4ClipGT< IntegralConstant<1> >::compare(p)) +#define CLIP_Z_LT_W(p) (Vector4ClipLT< IntegralConstant<2> >::compare(p)) +#define CLIP_Z_GT_W(p) (Vector4ClipGT< IntegralConstant<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< IntegralConstant<0> > >::apply(clipped, clipped + count, buffer); + count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<0> > >::apply(buffer, buffer + count, clipped); + count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<1> > >::apply(clipped, clipped + count, buffer); + count = Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<1> > >::apply(buffer, buffer + count, clipped); + count = Vector4ClipPolygon< Vector4ClipLT< IntegralConstant<2> > >::apply(clipped, clipped + count, buffer); + return Vector4ClipPolygon< Vector4ClipGT< IntegralConstant<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/misc/mediasource/netradiant-src/libs/math/line.cpp b/misc/mediasource/netradiant-src/libs/math/line.cpp new file mode 100644 index 00000000..a0bdea1a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/line.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "line.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/line.h b/misc/mediasource/netradiant-src/libs/math/line.h new file mode 100644 index 00000000..26d58369 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/line.h @@ -0,0 +1,151 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/math/matrix.cpp b/misc/mediasource/netradiant-src/libs/math/matrix.cpp new file mode 100644 index 00000000..e3831647 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/matrix.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "matrix.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/matrix.h b/misc/mediasource/netradiant-src/libs/math/matrix.h new file mode 100644 index 00000000..b28c2688 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/matrix.h @@ -0,0 +1,1322 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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 direction 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 Matrix4 matrix4_affine_inverse(const Matrix4& self) +{ + Matrix4 result; + + // determinant of rotation submatrix + double det + = self[0] * ( self[5]*self[10] - self[9]*self[6] ) + - self[1] * ( self[4]*self[10] - self[8]*self[6] ) + + self[2] * ( self[4]*self[9] - self[8]*self[5] ); + + // throw exception here if (det*det < 1e-25) + + // invert rotation submatrix + det = 1.0 / det; + + result[0] = static_cast( (self[5]*self[10]- self[6]*self[9] )*det); + result[1] = static_cast(- (self[1]*self[10]- self[2]*self[9] )*det); + result[2] = static_cast( (self[1]*self[6] - self[2]*self[5] )*det); + result[3] = 0; + result[4] = static_cast(- (self[4]*self[10]- self[6]*self[8] )*det); + result[5] = static_cast( (self[0]*self[10]- self[2]*self[8] )*det); + result[6] = static_cast(- (self[0]*self[6] - self[2]*self[4] )*det); + result[7] = 0; + result[8] = static_cast( (self[4]*self[9] - self[5]*self[8] )*det); + result[9] = static_cast(- (self[0]*self[9] - self[1]*self[8] )*det); + result[10]= static_cast( (self[0]*self[5] - self[1]*self[4] )*det); + result[11] = 0; + + // multiply translation part by rotation + result[12] = - (self[12] * result[0] + + self[13] * result[4] + + self[14] * result[8]); + result[13] = - (self[12] * result[1] + + self[13] * result[5] + + self[14] * result[9]); + result[14] = - (self[12] * result[2] + + self[13] * result[6] + + self[14] * result[10]); + result[15] = 1; + + return result; +} + +inline void matrix4_affine_invert(Matrix4& self) +{ + self = matrix4_affine_inverse(self); +} + +/// \brief A compile-time-constant integer. +template +struct IntegralConstant +{ + enum unnamed_{ VALUE = VALUE_ }; +}; + +/// \brief A compile-time-constant row/column index into a 4x4 matrix. +template +class Matrix4Index +{ +public: + typedef IntegralConstant r; + typedef IntegralConstant c; + typedef IntegralConstant<(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 IntegralConstant<(Element <= 0) ? 1 : 0> x; + typedef IntegralConstant<(Element <= 1) ? 2 : 1> y; + typedef IntegralConstant<(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/misc/mediasource/netradiant-src/libs/math/pi.cpp b/misc/mediasource/netradiant-src/libs/math/pi.cpp new file mode 100644 index 00000000..34930192 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/pi.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "pi.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/pi.h b/misc/mediasource/netradiant-src/libs/math/pi.h new file mode 100644 index 00000000..9cc74c1b --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/pi.h @@ -0,0 +1,45 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/math/plane.cpp b/misc/mediasource/netradiant-src/libs/math/plane.cpp new file mode 100644 index 00000000..4182a175 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/plane.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "plane.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/plane.h b/misc/mediasource/netradiant-src/libs/math/plane.h new file mode 100644 index 00000000..af05db74 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/plane.h @@ -0,0 +1,153 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/math/quaternion.cpp b/misc/mediasource/netradiant-src/libs/math/quaternion.cpp new file mode 100644 index 00000000..6688368e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/quaternion.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "quaternion.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/quaternion.h b/misc/mediasource/netradiant-src/libs/math/quaternion.h new file mode 100644 index 00000000..d91ad62a --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/quaternion.h @@ -0,0 +1,327 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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_for_x(double angle) +{ + angle *= 0.5; + return Quaternion(static_cast(sin(angle)), 0, 0, static_cast(cos(angle))); +} + +inline Quaternion quaternion_for_y(double angle) +{ + angle *= 0.5; + return Quaternion(0, static_cast(sin(angle)), 0, static_cast(cos(angle))); +} + +inline Quaternion quaternion_for_z(double angle) +{ + angle *= 0.5; + return Quaternion(0, 0, static_cast(sin(angle)), 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/misc/mediasource/netradiant-src/libs/math/vector.cpp b/misc/mediasource/netradiant-src/libs/math/vector.cpp new file mode 100644 index 00000000..d72bd9e4 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/vector.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "vector.h" + diff --git a/misc/mediasource/netradiant-src/libs/math/vector.h b/misc/mediasource/netradiant-src/libs/math/vector.h new file mode 100644 index 00000000..075c58fe --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/math/vector.h @@ -0,0 +1,813 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_MATH_VECTOR_H) +#define INCLUDED_MATH_VECTOR_H + +/// \file +/// \brief Vector data types and related operations. + +#include "generic/vector.h" + +#if defined (_MSC_VER) + +inline int lrint (double flt) +{ + int i; + + _asm + { + fld flt + fistp i + }; + + return i; +} + +inline __int64 llrint(double f) +{ + return static_cast<__int64>(f + 0.5); +} + +#elif defined(__FreeBSD__) + +inline long lrint(double f) +{ + return static_cast(f + 0.5); +} + +inline long long llrint(double f) +{ + return static_cast(f + 0.5); +} + +#elif defined(__GNUC__) + + // lrint is part of ISO C99 +#define _ISOC9X_SOURCE 1 +#define _ISOC99_SOURCE 1 + +#define __USE_ISOC9X 1 +#define __USE_ISOC99 1 + +#else +#error "unsupported platform" +#endif + +#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 \p snap. +template +inline Element float_snapped(const Element& f, const OtherElement& snap) +{ + //return Element(float_to_integer(f / snap) * snap); + if(snap == 0) + return f; + return Element(llrint(f / snap) * snap); // llrint has more significant bits +} + +/// \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 +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); +} + +template +inline double vector2_length(const BasicVector2& self) +{ + return sqrt(vector2_length_squared(self)); +} + +template +inline double vector2_cross(const BasicVector2& self, const BasicVector2& other) +{ + return self.x() * other.y() - self.y() * other.x(); +} + +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 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 BasicVector3 operator-(const BasicVector3& self) +{ + return vector3_negated(self); +} + +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)) + ); +} + + + + +template +inline bool vector4_equal(const BasicVector4& self, const BasicVector4& other) +{ + return self.x() == other.x() && self.y() == other.y() && self.z() == other.z() && self.w() == other.w(); +} +template +inline bool operator==(const BasicVector4& self, const BasicVector4& other) +{ + return vector4_equal(self, other); +} +template +inline bool operator!=(const BasicVector4& self, const BasicVector4& other) +{ + return !vector4_equal(self, other); +} + +template +inline bool vector4_equal_epsilon(const BasicVector4& self, const BasicVector4& other, Element 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) + && float_equal_epsilon(self.w(), other.w(), epsilon); +} + +template +inline BasicVector4 vector4_added(const BasicVector4& self, const BasicVector4& other) +{ + return BasicVector4( + float(self.x() + other.x()), + float(self.y() + other.y()), + float(self.z() + other.z()), + float(self.w() + other.w()) + ); +} +template +inline BasicVector4 operator+(const BasicVector4& self, const BasicVector4& other) +{ + return vector4_added(self, other); +} +template +inline void vector4_add(BasicVector4& self, const BasicVector4& 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()); +} +template +inline void operator+=(BasicVector4& self, const BasicVector4& other) +{ + vector4_add(self, other); +} + +template +inline BasicVector4 vector4_subtracted(const BasicVector4& self, const BasicVector4& other) +{ + return BasicVector4( + float(self.x() - other.x()), + float(self.y() - other.y()), + float(self.z() - other.z()), + float(self.w() - other.w()) + ); +} +template +inline BasicVector4 operator-(const BasicVector4& self, const BasicVector4& other) +{ + return vector4_subtracted(self, other); +} +template +inline void vector4_subtract(BasicVector4& self, const BasicVector4& 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()); +} +template +inline void operator-=(BasicVector4& self, const BasicVector4& other) +{ + vector4_subtract(self, other); +} + +template +inline BasicVector4 vector4_scaled(const BasicVector4& self, const BasicVector4& other) +{ + return BasicVector4( + float(self.x() * other.x()), + float(self.y() * other.y()), + float(self.z() * other.z()), + float(self.w() * other.w()) + ); +} +template +inline BasicVector4 operator*(const BasicVector4& self, const BasicVector4& other) +{ + return vector4_scaled(self, other); +} +template +inline void vector4_scale(BasicVector4& self, const BasicVector4& 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()); +} +template +inline void operator*=(BasicVector4& self, const BasicVector4& other) +{ + vector4_scale(self, other); +} + +template +inline BasicVector4 vector4_scaled(const BasicVector4& self, OtherElement scale) +{ + return BasicVector4( + float(self.x() * scale), + float(self.y() * scale), + float(self.z() * scale), + float(self.w() * scale) + ); +} +template +inline BasicVector4 operator*(const BasicVector4& self, OtherElement scale) +{ + return vector4_scaled(self, scale); +} +template +inline void vector4_scale(BasicVector4& self, OtherElement scale) +{ + self.x() *= static_cast(scale); + self.y() *= static_cast(scale); + self.z() *= static_cast(scale); + self.w() *= static_cast(scale); +} +template +inline void operator*=(BasicVector4& self, OtherElement scale) +{ + vector4_scale(self, scale); +} + +template +inline BasicVector4 vector4_divided(const BasicVector4& self, OtherElement divisor) +{ + return BasicVector4( + float(self.x() / divisor), + float(self.y() / divisor), + float(self.z() / divisor), + float(self.w() / divisor) + ); +} +template +inline BasicVector4 operator/(const BasicVector4& self, OtherElement divisor) +{ + return vector4_divided(self, divisor); +} +template +inline void vector4_divide(BasicVector4& self, OtherElement divisor) +{ + self.x() /= divisor; + self.y() /= divisor; + self.z() /= divisor; + self.w() /= divisor; +} +template +inline void operator/=(BasicVector4& self, OtherElement divisor) +{ + vector4_divide(self, divisor); +} + +template +inline double vector4_dot(const BasicVector4& self, const BasicVector4& other) +{ + return self.x() * other.x() + self.y() * other.y() + self.z() * other.z() + self.w() * other.w(); +} + +template +inline BasicVector3 vector4_projected(const BasicVector4& self) +{ + return vector3_scaled(vector4_to_vector3(self), 1.0 / self[3]); +} + +#endif diff --git a/misc/mediasource/netradiant-src/libs/mathlib.h b/misc/mediasource/netradiant-src/libs/mathlib.h new file mode 100644 index 00000000..382933d7 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/mathlib.h @@ -0,0 +1,483 @@ +/* +Copyright (C) 1999-2006 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 +#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]; + +// Smallest positive value for vec_t such that 1.0 + VEC_SMALLEST_EPSILON_AROUND_ONE != 1.0. +// In the case of 32 bit floats (which is almost certainly the case), it's 0.00000011921. +// Don't forget that your epsilons should depend on the possible range of values, +// because for example adding VEC_SMALLEST_EPSILON_AROUND_ONE to 1024.0 will have no effect. +#define VEC_SMALLEST_EPSILON_AROUND_ONE FLT_EPSILON + +#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 RGBTOGRAY(x) ( (float)((x)[0]) * 0.2989f + (float)((x)[1]) * 0.5870f + (float)((x)[2]) * 0.1140f ) + +#define Q_rint(in) ((vec_t)floor(in+0.5)) + +qboolean VectorCompare (const vec3_t v1, const vec3_t v2); + +qboolean VectorIsOnAxis(vec3_t v); +qboolean VectorIsOnAxialPlane(vec3_t v); + +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); +// I need this define in order to test some of the regression tests from time to time. +// This define affect the precision of VectorNormalize() function only. +#define MATHLIB_VECTOR_NORMALIZE_PRECISION_FIX 1 +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); +/*! m4_det */ +float m4_det( m4x4_t mr ); +/*! 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); + + + +//////////////////////////////////////////////////////////////////////////////// +// Below is double-precision math stuff. This was initially needed by the new +// "base winding" code in q3map2 brush processing in order to fix the famous +// "disappearing triangles" issue. These definitions can be used wherever extra +// precision is needed. +//////////////////////////////////////////////////////////////////////////////// + +typedef double vec_accu_t; +typedef vec_accu_t vec3_accu_t[3]; + +// Smallest positive value for vec_accu_t such that 1.0 + VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE != 1.0. +// In the case of 64 bit doubles (which is almost certainly the case), it's 0.00000000000000022204. +// Don't forget that your epsilons should depend on the possible range of values, +// because for example adding VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE to 1024.0 will have no effect. +#define VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE DBL_EPSILON + +vec_accu_t VectorLengthAccu(const vec3_accu_t v); + +// I have a feeling it may be safer to break these #define functions out into actual functions +// in order to avoid accidental loss of precision. For example, say you call +// VectorScaleAccu(vec3_t, vec_t, vec3_accu_t). The scale would take place in 32 bit land +// and the result would be cast to 64 bit, which would cause total loss of precision when +// scaling by a large factor. +//#define DotProductAccu(x, y) ((x)[0] * (y)[0] + (x)[1] * (y)[1] + (x)[2] * (y)[2]) +//#define VectorSubtractAccu(a, b, c) ((c)[0] = (a)[0] - (b)[0], (c)[1] = (a)[1] - (b)[1], (c)[2] = (a)[2] - (b)[2]) +//#define VectorAddAccu(a, b, c) ((c)[0] = (a)[0] + (b)[0], (c)[1] = (a)[1] + (b)[1], (c)[2] = (a)[2] + (b)[2]) +//#define VectorCopyAccu(a, b) ((b)[0] = (a)[0], (b)[1] = (a)[1], (b)[2] = (a)[2]) +//#define VectorScaleAccu(a, b, c) ((c)[0] = (b) * (a)[0], (c)[1] = (b) * (a)[1], (c)[2] = (b) * (a)[2]) +//#define CrossProductAccu(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 Q_rintAccu(in) ((vec_accu_t) floor(in + 0.5)) + +vec_accu_t DotProductAccu(const vec3_accu_t a, const vec3_accu_t b); +void VectorSubtractAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); +void VectorAddAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); +void VectorCopyAccu(const vec3_accu_t in, vec3_accu_t out); +void VectorScaleAccu(const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out); +void CrossProductAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out); +vec_accu_t Q_rintAccu(vec_accu_t val); + +void VectorCopyAccuToRegular(const vec3_accu_t in, vec3_t out); +void VectorCopyRegularToAccu(const vec3_t in, vec3_accu_t out); +vec_accu_t VectorNormalizeAccu(const vec3_accu_t in, vec3_accu_t out); + +#ifdef __cplusplus +} +#endif + +#endif /* __MATHLIB__ */ diff --git a/misc/mediasource/netradiant-src/libs/mathlib/bbox.c b/misc/mediasource/netradiant-src/libs/mathlib/bbox.c new file mode 100644 index 00000000..e8dc8657 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/mathlib/bbox.c @@ -0,0 +1,462 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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; iorigin[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/misc/mediasource/netradiant-src/libs/mathlib/line.c b/misc/mediasource/netradiant-src/libs/mathlib/line.c new file mode 100644 index 00000000..41b868fb --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/mathlib/line.c @@ -0,0 +1,41 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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/misc/mediasource/netradiant-src/libs/mathlib/m4x4.c b/misc/mediasource/netradiant-src/libs/mathlib/m4x4.c new file mode 100644 index 00000000..3b114610 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/mathlib/m4x4.c @@ -0,0 +1,1878 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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= 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; + else + continue; + + for ( tj = 0; tj < 4; tj++ ) + { + if ( tj < j ) + jdst = tj; + else if ( tj > j ) + jdst = tj-1; + else + continue; + + 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 scale[r]) + { + scale[r] = (float)fabs(*p); + } + } + } + + for (c=0; c 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=0; r--) + { + f = aug[indx[r]]; + p = matrix + (indx[r]*N); + for(c=(r+1); c=0;i--) + { + temp = b[i]; + for(j=(i+1);j + +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, }; + +/* +================ +VectorIsOnAxis +================ +*/ +qboolean VectorIsOnAxis(vec3_t v) +{ + int i, zeroComponentCount; + + zeroComponentCount = 0; + for (i = 0; i < 3; i++) + { + if (v[i] == 0.0) + { + zeroComponentCount++; + } + } + + if (zeroComponentCount > 1) + { + // The zero vector will be on axis. + return qtrue; + } + + return qfalse; +} + +/* +================ +VectorIsOnAxialPlane +================ +*/ +qboolean VectorIsOnAxialPlane(vec3_t v) +{ + int i; + + for (i = 0; i < 3; i++) + { + if (v[i] == 0.0) + { + // The zero vector will be on axial plane. + return qtrue; + } + } + + return qfalse; +} + +/* +================ +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 ) { + +#if MATHLIB_VECTOR_NORMALIZE_PRECISION_FIX + + // The sqrt() function takes double as an input and returns double as an + // output according the the man pages on Debian and on FreeBSD. Therefore, + // I don't see a reason why using a double outright (instead of using the + // vec_accu_t alias for example) could possibly be frowned upon. + + double x, y, z, length; + + x = (double) in[0]; + y = (double) in[1]; + z = (double) in[2]; + + length = sqrt((x * x) + (y * y) + (z * z)); + if (length == 0) + { + VectorClear (out); + return 0; + } + + out[0] = (vec_t) (x / length); + out[1] = (vec_t) (y / length); + out[2] = (vec_t) (z / length); + + return (vec_t) length; + +#else + + 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; + +#endif + +} + +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 +#define INVALID_BOUNDS 99999 +void ClearBounds (vec3_t mins, vec3_t maxs) +{ + mins[0] = mins[1] = mins[2] = +INVALID_BOUNDS; + maxs[0] = maxs[1] = maxs[2] = -INVALID_BOUNDS; +} + +void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs) +{ + int i; + vec_t val; + + if(mins[0] == +INVALID_BOUNDS) + if(maxs[0] == -INVALID_BOUNDS) + { + VectorCopy(v, mins); + VectorCopy(v, maxs); + } + + 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]; + } +} + + +//////////////////////////////////////////////////////////////////////////////// +// Below is double-precision math stuff. This was initially needed by the new +// "base winding" code in q3map2 brush processing in order to fix the famous +// "disappearing triangles" issue. These definitions can be used wherever extra +// precision is needed. +//////////////////////////////////////////////////////////////////////////////// + +/* +================= +VectorLengthAccu +================= +*/ +vec_accu_t VectorLengthAccu(const vec3_accu_t v) +{ + return (vec_accu_t) sqrt((v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2])); +} + +/* +================= +DotProductAccu +================= +*/ +vec_accu_t DotProductAccu(const vec3_accu_t a, const vec3_accu_t b) +{ + return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]); +} + +/* +================= +VectorSubtractAccu +================= +*/ +void VectorSubtractAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) +{ + out[0] = a[0] - b[0]; + out[1] = a[1] - b[1]; + out[2] = a[2] - b[2]; +} + +/* +================= +VectorAddAccu +================= +*/ +void VectorAddAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) +{ + out[0] = a[0] + b[0]; + out[1] = a[1] + b[1]; + out[2] = a[2] + b[2]; +} + +/* +================= +VectorCopyAccu +================= +*/ +void VectorCopyAccu(const vec3_accu_t in, vec3_accu_t out) +{ + out[0] = in[0]; + out[1] = in[1]; + out[2] = in[2]; +} + +/* +================= +VectorScaleAccu +================= +*/ +void VectorScaleAccu(const vec3_accu_t in, vec_accu_t scaleFactor, vec3_accu_t out) +{ + out[0] = in[0] * scaleFactor; + out[1] = in[1] * scaleFactor; + out[2] = in[2] * scaleFactor; +} + +/* +================= +CrossProductAccu +================= +*/ +void CrossProductAccu(const vec3_accu_t a, const vec3_accu_t b, vec3_accu_t out) +{ + out[0] = (a[1] * b[2]) - (a[2] * b[1]); + out[1] = (a[2] * b[0]) - (a[0] * b[2]); + out[2] = (a[0] * b[1]) - (a[1] * b[0]); +} + +/* +================= +Q_rintAccu +================= +*/ +vec_accu_t Q_rintAccu(vec_accu_t val) +{ + return (vec_accu_t) floor(val + 0.5); +} + +/* +================= +VectorCopyAccuToRegular +================= +*/ +void VectorCopyAccuToRegular(const vec3_accu_t in, vec3_t out) +{ + out[0] = (vec_t) in[0]; + out[1] = (vec_t) in[1]; + out[2] = (vec_t) in[2]; +} + +/* +================= +VectorCopyRegularToAccu +================= +*/ +void VectorCopyRegularToAccu(const vec3_t in, vec3_accu_t out) +{ + out[0] = (vec_accu_t) in[0]; + out[1] = (vec_accu_t) in[1]; + out[2] = (vec_accu_t) in[2]; +} + +/* +================= +VectorNormalizeAccu +================= +*/ +vec_accu_t VectorNormalizeAccu(const vec3_accu_t in, vec3_accu_t out) +{ + // The sqrt() function takes double as an input and returns double as an + // output according the the man pages on Debian and on FreeBSD. Therefore, + // I don't see a reason why using a double outright (instead of using the + // vec_accu_t alias for example) could possibly be frowned upon. + + vec_accu_t length; + + length = (vec_accu_t) sqrt((in[0] * in[0]) + (in[1] * in[1]) + (in[2] * in[2])); + if (length == 0) + { + VectorClear(out); + return 0; + } + + out[0] = in[0] / length; + out[1] = in[1] / length; + out[2] = in[2] / length; + + return length; +} + + diff --git a/misc/mediasource/netradiant-src/libs/mathlib/ray.c b/misc/mediasource/netradiant-src/libs/mathlib/ray.c new file mode 100644 index 00000000..bea7c5c5 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/mathlib/ray.c @@ -0,0 +1,140 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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/misc/mediasource/netradiant-src/libs/md5lib.h b/misc/mediasource/netradiant-src/libs/md5lib.h new file mode 100644 index 00000000..f0aca115 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/md5lib.h @@ -0,0 +1,91 @@ +/* + 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/misc/mediasource/netradiant-src/libs/md5lib/md5lib.c b/misc/mediasource/netradiant-src/libs/md5lib/md5lib.c new file mode 100644 index 00000000..60b45148 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/md5lib/md5lib.c @@ -0,0 +1,395 @@ +/* + 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/misc/mediasource/netradiant-src/libs/memory/allocator.cpp b/misc/mediasource/netradiant-src/libs/memory/allocator.cpp new file mode 100644 index 00000000..17fbdaca --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/memory/allocator.cpp @@ -0,0 +1,80 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "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/misc/mediasource/netradiant-src/libs/memory/allocator.h b/misc/mediasource/netradiant-src/libs/memory/allocator.h new file mode 100644 index 00000000..c513d708 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/memory/allocator.h @@ -0,0 +1,336 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/moduleobservers.cpp b/misc/mediasource/netradiant-src/libs/moduleobservers.cpp new file mode 100644 index 00000000..a2d51f7d --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/moduleobservers.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "moduleobservers.h" + diff --git a/misc/mediasource/netradiant-src/libs/moduleobservers.h b/misc/mediasource/netradiant-src/libs/moduleobservers.h new file mode 100644 index 00000000..cd3bb1ef --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/moduleobservers.h @@ -0,0 +1,64 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/modulesystem/moduleregistry.cpp b/misc/mediasource/netradiant-src/libs/modulesystem/moduleregistry.cpp new file mode 100644 index 00000000..9841f797 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/modulesystem/moduleregistry.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "moduleregistry.h" + diff --git a/misc/mediasource/netradiant-src/libs/modulesystem/moduleregistry.h b/misc/mediasource/netradiant-src/libs/modulesystem/moduleregistry.h new file mode 100644 index 00000000..bd39cb06 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/modulesystem/moduleregistry.h @@ -0,0 +1,65 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/modulesystem/modulesmap.cpp b/misc/mediasource/netradiant-src/libs/modulesystem/modulesmap.cpp new file mode 100644 index 00000000..4edfc701 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/modulesystem/modulesmap.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "modulesmap.h" diff --git a/misc/mediasource/netradiant-src/libs/modulesystem/modulesmap.h b/misc/mediasource/netradiant-src/libs/modulesystem/modulesmap.h new file mode 100644 index 00000000..dfc2ea45 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/modulesystem/modulesmap.h @@ -0,0 +1,152 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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(const 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) const + { + 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(typename Type::Name(), typename Type::Version(), visitor); + } + else + { + StringTokeniser tokeniser(names); + for(;;) + { + const char* name = tokeniser.getToken(); + if(string_empty(name)) + { + break; + } + Module* module = globalModuleServer().findModule(typename Type::Name(), typename Type::Version(), name); + if(module == 0) + { + globalModuleServer().setError(true); + globalErrorStream() << "ModulesRef::initialise: type=" << makeQuoted(typename Type::Name()) << " version=" << makeQuoted(typename Type::Version()) << " name=" << makeQuoted(name) << " - not found\n"; + break; + } + else + { + m_modules.insert(name, *module); + } + } + } + } + } + ModulesMap& get() + { + return m_modules; + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/libs/modulesystem/singletonmodule.cpp b/misc/mediasource/netradiant-src/libs/modulesystem/singletonmodule.cpp new file mode 100644 index 00000000..866c24fa --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/modulesystem/singletonmodule.cpp @@ -0,0 +1,48 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "singletonmodule.h" +#include "generic/constant.h" + +class NullType +{ +public: + INTEGER_CONSTANT(Version, 1); + STRING_CONSTANT(Name, ""); +}; + +class NullModule +{ +public: + typedef NullType Type; + STRING_CONSTANT(Name, ""); + void* getTable() + { + return NULL; + } +}; + +void TEST_SINGLETONMODULE() +{ + SingletonModule null; + null.capture(); + null.release(); +} diff --git a/misc/mediasource/netradiant-src/libs/modulesystem/singletonmodule.h b/misc/mediasource/netradiant-src/libs/modulesystem/singletonmodule.h new file mode 100644 index 00000000..f68587b7 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/modulesystem/singletonmodule.h @@ -0,0 +1,150 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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 typename API::Name(); + } + + API* constructAPI(Dependencies& dependencies) + { + return new API; + } + void destroyAPI(API* api) + { + delete api; + } +}; + +template +class DependenciesAPIConstructor +{ +public: + const char* getName() + { + return typename API::Name(); + } + + 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(typename Type::Name(), typename 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: '" << typename 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: '" << typename Type::Name() << "' '" << APIConstructor::getName() << "'\n"; + } + else + { + globalOutputStream() << "Module Dependencies Failed: '" << typename 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/misc/mediasource/netradiant-src/libs/os/dir.cpp b/misc/mediasource/netradiant-src/libs/os/dir.cpp new file mode 100644 index 00000000..a775e5bd --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/os/dir.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "dir.h" + diff --git a/misc/mediasource/netradiant-src/libs/os/dir.h b/misc/mediasource/netradiant-src/libs/os/dir.h new file mode 100644 index 00000000..bdb385e1 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/os/dir.h @@ -0,0 +1,75 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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/misc/mediasource/netradiant-src/libs/os/file.cpp b/misc/mediasource/netradiant-src/libs/os/file.cpp new file mode 100644 index 00000000..766638f9 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/os/file.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "file.h" + diff --git a/misc/mediasource/netradiant-src/libs/os/file.h b/misc/mediasource/netradiant-src/libs/os/file.h new file mode 100644 index 00000000..b1290760 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/os/file.h @@ -0,0 +1,152 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(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 +#define access(path, mode) _access(path, mode) +#else +#include // access() +#endif + +#include // rename(), remove() +#include // stat() +#include // this is included by stat.h on win32 +#include +#include + +#include "debugging/debugging.h" + +/// \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) +{ + ASSERT_MESSAGE(from != 0 && to != 0, "file_move: invalid path"); + 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) +{ + ASSERT_MESSAGE(path != 0, "file_remove: invalid 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) +{ + ASSERT_MESSAGE(path != 0, "file_accessible: invalid path"); + 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) +{ + ASSERT_MESSAGE(path != 0, "file_is_directory: invalid 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) +{ + ASSERT_MESSAGE(path != 0, "file_size: invalid 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) +{ + ASSERT_MESSAGE(path != 0, "file_modified: invalid path"); + struct stat st; + if(stat(path, &st) == -1) + { + return c_invalidFileTime; + } + return st.st_mtime; +} + + + +#endif diff --git a/misc/mediasource/netradiant-src/libs/os/path.cpp b/misc/mediasource/netradiant-src/libs/os/path.cpp new file mode 100644 index 00000000..ab03e1d2 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/os/path.cpp @@ -0,0 +1,22 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "path.h" diff --git a/misc/mediasource/netradiant-src/libs/os/path.h b/misc/mediasource/netradiant-src/libs/os/path.h new file mode 100644 index 00000000..082b56fa --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/os/path.h @@ -0,0 +1,283 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (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(POSIX) + 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/misc/mediasource/netradiant-src/libs/picomodel.h b/misc/mediasource/netradiant-src/libs/picomodel.h new file mode 100644 index 00000000..1e6f8920 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel.h @@ -0,0 +1,351 @@ +/* ----------------------------------------------------------------------------- + +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 ]; +}; + + +/* 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 \ + const char *fileName, const void *buffer, int bufSize + +#define PM_PARAMS_LOAD \ + const char *fileName, int frameNum, const void *buffer, int bufSize + +#define PM_PARAMS_CANSAVE \ + void + +#define PM_PARAMS_SAVE \ + const 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)( const 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( const 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, const char *fileName ); + +/* 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, const char *name ); +void PicoSetModelFileName( picoModel_t *model, const 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* smoothingGroup); + +/* end marker */ +#ifdef __cplusplus +} +#endif + +#endif diff --git a/misc/mediasource/netradiant-src/libs/picomodel/lwo/clip.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/clip.c new file mode 100644 index 00000000..d83ea61f --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/clip.c @@ -0,0 +1,278 @@ +/* +====================================================================== +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/misc/mediasource/netradiant-src/libs/picomodel/lwo/envelope.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/envelope.c new file mode 100644 index 00000000..3720a8eb --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/envelope.c @@ -0,0 +1,600 @@ +/* +====================================================================== +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 = NULL; + 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/misc/mediasource/netradiant-src/libs/picomodel/lwo/list.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/list.c new file mode 100644 index 00000000..d337296c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/list.c @@ -0,0 +1,101 @@ +/* +====================================================================== +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/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwio.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwio.c new file mode 100644 index 00000000..63e9af76 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwio.c @@ -0,0 +1,442 @@ +/* +====================================================================== +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( (const char *) 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/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwo2.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwo2.c new file mode 100644 index 00000000..56c756c3 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwo2.c @@ -0,0 +1,308 @@ +/* +====================================================================== +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( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ) +{ + lwObject *object; + lwLayer *layer; + lwNode *node; + unsigned int id, formsize, type; + int i, rlen, 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; + } + + /* 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 <= (unsigned int) (_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( const 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/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwo2.h b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwo2.h new file mode 100644 index 00000000..e5b96115 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwo2.h @@ -0,0 +1,651 @@ +/* +====================================================================== +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( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); +int lwValidateObject( const 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( const char *filename, picoMemStream_t *fp, unsigned int *failID, int *failpos ); +int lwValidateObject5( const 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/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwob.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwob.c new file mode 100644 index 00000000..f12e3a36 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/lwob.c @@ -0,0 +1,740 @@ +/* +====================================================================== +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 = NULL; + lwPlugin *shdr = NULL; + 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: + if(!tex) goto Fail; + flags = getU2( fp ); + + i = -1; + if ( flags & 1 ) i = 0; + if ( flags & 2 ) i = 1; + if ( flags & 4 ) i = 2; + if(i < 0) goto Fail; + 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: + if(!tex) goto Fail; + for ( i = 0; i < 3; i++ ) + tex->tmap.size.val[ i ] = getF4( fp ); + break; + + case ID_TCTR: + if(!tex) goto Fail; + for ( i = 0; i < 3; i++ ) + tex->tmap.center.val[ i ] = getF4( fp ); + break; + + case ID_TFAL: + if(!tex) goto Fail; + for ( i = 0; i < 3; i++ ) + tex->tmap.falloff.val[ i ] = getF4( fp ); + break; + + case ID_TVEL: + if(!tex) goto Fail; + 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) goto Fail; + if ( tex->type == ID_PROC ) + for ( i = 0; i < 3; i++ ) + tex->param.proc.value[ i ] = getU1( fp ) / 255.0f; + break; + + case ID_TVAL: + if(!tex) goto Fail; + tex->param.proc.value[ 0 ] = getI2( fp ) / 256.0f; + break; + + case ID_TAMP: + if(!tex) goto Fail; + if ( tex->type == ID_IMAP ) + tex->param.imap.amplitude.val = getF4( fp ); + break; + + case ID_TIMG: + if(!tex) goto Fail; + s = getS0( fp ); + tex->param.imap.cindex = add_clip( s, &obj->clip, &obj->nclips ); + break; + + case ID_TAAS: + if(!tex) goto Fail; + tex->param.imap.aa_strength = getF4( fp ); + tex->param.imap.aas_flags = 1; + break; + + case ID_TREF: + if(!tex) goto Fail; + tex->tmap.ref_object = getbytes( fp, sz ); + break; + + case ID_TOPC: + if(!tex) goto Fail; + tex->opacity.val = getF4( fp ); + break; + + case ID_TFP0: + if(!tex) goto Fail; + if ( tex->type == ID_IMAP ) + tex->param.imap.wrapw.val = getF4( fp ); + break; + + case ID_TFP1: + if(!tex) goto Fail; + 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: + if(!shdr) goto Fail; + 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 * ) (size_t) 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( const 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 <= (unsigned int) (_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( const 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/misc/mediasource/netradiant-src/libs/picomodel/lwo/pntspols.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/pntspols.c new file mode 100644 index 00000000..31475819 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/pntspols.c @@ -0,0 +1,537 @@ +/* +====================================================================== +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 = ( size_t ) 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 * ) (size_t) 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/misc/mediasource/netradiant-src/libs/picomodel/lwo/surface.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/surface.c new file mode 100644 index 00000000..6b2bbe62 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/surface.c @@ -0,0 +1,1005 @@ +/* +====================================================================== +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/misc/mediasource/netradiant-src/libs/picomodel/lwo/vecmath.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/vecmath.c new file mode 100644 index 00000000..eaa1e8fc --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/vecmath.c @@ -0,0 +1,37 @@ +/* +====================================================================== +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/misc/mediasource/netradiant-src/libs/picomodel/lwo/vmap.c b/misc/mediasource/netradiant-src/libs/picomodel/lwo/vmap.c new file mode 100644 index 00000000..69f87cf9 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/lwo/vmap.c @@ -0,0 +1,243 @@ +/* +====================================================================== +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/misc/mediasource/netradiant-src/libs/picomodel/picointernal.c b/misc/mediasource/netradiant-src/libs/picomodel/picointernal.c new file mode 100644 index 00000000..f08a9962 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/picointernal.c @@ -0,0 +1,1356 @@ +/* ----------------------------------------------------------------------------- + +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 )( const 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( const 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 + */ +const char *_pico_stristr( const 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; poscursor == 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( const 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 = (const char *) buffer; + p->cursor = (const char *) 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; + const 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( const 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/misc/mediasource/netradiant-src/libs/picomodel/picointernal.h b/misc/mediasource/netradiant-src/libs/picomodel/picointernal.h new file mode 100644 index 00000000..10769e33 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/picointernal.h @@ -0,0 +1,206 @@ +/* ----------------------------------------------------------------------------- + +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 +{ + const char *buffer; + int bufSize; + char *token; + int tokenSize; + int tokenMax; + const char *cursor; + const char *max; + int curLine; +} +picoParser_t; + +typedef struct picoMemStream_s +{ + const picoByte_t *buffer; + int bufSize; + const 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)( const 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( const 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, ... ); +const char *_pico_stristr( const 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( const 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( const 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/misc/mediasource/netradiant-src/libs/picomodel/picomodel.c b/misc/mediasource/netradiant-src/libs/picomodel/picomodel.c new file mode 100644 index 00000000..aed467ca --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/picomodel.c @@ -0,0 +1,2285 @@ +/* ----------------------------------------------------------------------------- + +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)( const 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, const 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( const 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, const char *fileName ) +{ + 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'; + + model = PicoModuleLoadModel(module, fileName, buffer, bufSize, frameNum); + + if(model != 0) + { + _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, const 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, const 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; + + + /* 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; + +#define THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL 1 + +void _pico_triangles_generate_weighted_normals(picoIndexIter_t first, picoIndexIter_t end, picoVec3_t* xyz, picoVec3_t* normals) +{ + for(; first != end; first += 3) + { +#if (THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL) + 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 ); + } +#endif + { + int j = 0; + for(; j < 3; ++j) + { + float* normal = normals[*(first + j)]; +#if (!THE_CROSSPRODUCTS_OF_ANY_PAIR_OF_EDGES_OF_A_GIVEN_TRIANGLE_ARE_EQUAL) + picoVec3_t weightedNormal; + { + float* a = xyz[*(first + ((j + 0) % 3))]; + float* b = xyz[*(first + ((j + 1) % 3))]; + float* c = xyz[*(first + ((j + 2) % 3))]; + picoVec3_t ba, ca; + _pico_subtract_vec( b, a, ba ); + _pico_subtract_vec( c, a, ca ); + _pico_cross_vec( ca, ba, weightedNormal ); + } +#endif + _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) + { + 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); + + _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 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 ) + { + 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 ); + } + + /* 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 = 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/misc/mediasource/netradiant-src/libs/picomodel/picomodules.c b/misc/mediasource/netradiant-src/libs/picomodel/picomodules.c new file mode 100644 index 00000000..59a6a9ee --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/picomodules.c @@ -0,0 +1,94 @@ +/* ----------------------------------------------------------------------------- + +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/misc/mediasource/netradiant-src/libs/picomodel/pm_3ds.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_3ds.c new file mode 100644 index 00000000..5ec21bf6 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_3ds.c @@ -0,0 +1,775 @@ +/* ----------------------------------------------------------------------------- + +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; ilen)) + 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; isurface,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; isurface, (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; isurface == 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; ishader ) + { + 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 *)_pico_alloc(bufSize); + memcpy(pers.bufptr, buffer, bufSize); + 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/misc/mediasource/netradiant-src/libs/picomodel/pm_ase.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_ase.c new file mode 100644 index 00000000..31c448e6 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_ase.c @@ -0,0 +1,1190 @@ +/* ----------------------------------------------------------------------------- + +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. + +----------------------------------------------------------------------------- */ + + +/* 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; + + /* create pico parser */ + p = _pico_new_parser( (const 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; + picoVec3_t normal; + 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; +}; +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 void _ase_submit_triangles( picoModel_t* model , aseMaterial_t* materials , aseVertex_t* vertices, aseTexCoord_t* texcoords, aseColor_t* colors, aseFace_t* faces, int numFaces ) +{ + aseFacesIter_t i = faces, end = faces + numFaces; + 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; + } + + { + picoVec3_t* xyz[3]; + picoVec3_t* normal[3]; + picoVec2_t* st[3]; + picoColor_t* color[3]; + picoIndex_t smooth[3]; + int j; + /* we pull the data from the vertex, color and texcoord arrays using the face index data */ + for ( j = 0 ; j < 3 ; j ++ ) + { + xyz[j] = &vertices[(*i).indices[j]].xyz; + normal[j] = &vertices[(*i).indices[j]].normal; + 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] = (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 ); + } + } +} + +static void shadername_convert(char* shaderName) +{ + /* unix-style path separators */ + char* s = shaderName; + for(; *s != '\0'; ++s) + { + if(*s == '\\') + { + *s = '/'; + } + } +} + + +/* _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; + + 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( (const 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); + _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)); + } + 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++; + } + /* 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"); + if (!_pico_parse_vec( p,vertices[index].normal )) + _ase_error_return("Vertex parse error"); + } + /* 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" )) + { + _pico_parse_int ( p , &faces[index].smoothingGroup ); + } + 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("Texture Vertex parse error"); + + /* get uv vertex index */ + if (!_pico_parse_int( p,&index ) || index >= numTextureVertices) + _ase_error_return("Texture vertex parse error"); + + /* get uv vertex s */ + if (!_pico_parse_float( p,&texcoords[index].texcoord[0] )) + _ase_error_return("Texture vertex parse error"); + + /* get uv vertex t */ + if (!_pico_parse_float( p,&texcoords[index].texcoord[1] )) + _ase_error_return("Texture 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; + } + /* 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 = NULL; + 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 ); + shadername_convert(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 */ + shadername_convert(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 ); + + /* extract shadername from bitmap path */ + if(mapname != NULL) + { + char* p = mapname; + + /* convert to shader-name format */ + shadername_convert(mapname); + { + /* remove extension */ + char* last_period = strrchr(p, '.'); + if(last_period != NULL) + { + *last_period = '\0'; + } + } + + /* find shader path */ + for(; *p != '\0'; ++p) + { + if(_pico_strnicmp(p, "models/", 7) == 0 || _pico_strnicmp(p, "textures/", 9) == 0) + { + 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); + _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/misc/mediasource/netradiant-src/libs/picomodel/pm_fm.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_fm.c new file mode 100644 index 00000000..1065160e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_fm.c @@ -0,0 +1,695 @@ +/* ----------------------------------------------------------------------------- + +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, *bb0; + int fm_file_pos; + + bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); + memcpy(bb, buffer, bufSize); + + // 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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 + _pico_free(bb0); + 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, *bb0; + picoModel_t *picoModel; + picoSurface_t *picoSurface; + picoShader_t *picoShader; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; + + + bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); + memcpy(bb, buffer, bufSize); + + // 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"); + _pico_free(bb0); + return NULL; + } + + if( _pico_little_long( fm.fm_header_hdr->version ) != FM_HEADERCHUNKVER ) + { + _pico_printf( PICO_WARNING, "FM Header Version incorrect\n"); + _pico_free(bb0); + 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"); + _pico_free(bb0); + return NULL; + } + + if( _pico_little_long( fm.fm_skin_hdr->version ) != FM_SKINCHUNKVER ) + { + _pico_printf( PICO_WARNING, "FM Skin Version incorrect\n"); + _pico_free(bb0); + 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"); + _pico_free(bb0); + return NULL; + } + + if( _pico_little_long( fm.fm_st_hdr->version ) != FM_STCOORDCHUNKVER ) + { + _pico_printf( PICO_WARNING, "FM ST Version incorrect\n"); + _pico_free(bb0); + 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"); + _pico_free(bb0); + return NULL; + } + + if( _pico_little_long( fm.fm_tri_hdr->version ) != FM_TRISCHUNKVER ) + { + _pico_printf( PICO_WARNING, "FM Tri Version incorrect\n"); + _pico_free(bb0); + 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"); + _pico_free(bb0); + return NULL; + } + + if( _pico_little_long( fm.fm_frame_hdr->version ) != FM_FRAMESCHUNKVER ) + { + _pico_printf( PICO_WARNING, "FM Frame Version incorrect\n"); + _pico_free(bb0); + 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 ); + _pico_free(bb0); + return NULL; + } + + if( frameNum < 0 || frameNum >= fm_head->numFrames ) + { + _pico_printf( PICO_ERROR, "Invalid or out-of-range FM frame specified" ); + _pico_free(bb0); + 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, (const 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" ); + _pico_free(bb0); + 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 ); + _pico_free(bb0); + 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 ); + _pico_free(bb0); + 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; inumXYZ; 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; inumTris; 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; inumXYZ; 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; inumXYZ; 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; inumTris; 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; iverts[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; inumXYZ; 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 */ + _pico_free(bb0); + 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/misc/mediasource/netradiant-src/libs/picomodel/pm_fm.h b/misc/mediasource/netradiant-src/libs/picomodel/pm_fm.h new file mode 100644 index 00000000..3fd5148e --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_fm.h @@ -0,0 +1,367 @@ +/* ----------------------------------------------------------------------------- + +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/misc/mediasource/netradiant-src/libs/picomodel/pm_lwo.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_lwo.c new file mode 100644 index 00000000..09cdde9c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_lwo.c @@ -0,0 +1,445 @@ +/* ----------------------------------------------------------------------------- + +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( (const 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[ 256 ]; + 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( (const 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/misc/mediasource/netradiant-src/libs/picomodel/pm_md2.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_md2.c new file mode 100644 index 00000000..d53f7029 --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_md2.c @@ -0,0 +1,672 @@ +/* ----------------------------------------------------------------------------- + +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 ) +{ + const md2_t *md2; + + /* sanity check */ + if( (size_t) bufSize < ( sizeof( *md2 ) * 2) ) + return PICO_PMV_ERROR_SIZE; + + /* set as md2 */ + md2 = (const md2_t*) buffer; + + /* check md2 magic */ + if( *((const int*) md2->magic) != *((const 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, *bb0; + picoModel_t *picoModel; + picoSurface_t *picoSurface; + picoShader_t *picoShader; + picoVec3_t xyz, normal; + picoVec2_t st; + picoColor_t color; + + + /* set as md2 */ + bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); + memcpy(bb, buffer, bufSize); + md2 = (md2_t*) bb; + + /* check ident and version */ + if( *((const int*) md2->magic) != *((const 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 ); + _pico_free(bb0); + 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 ); + _pico_free(bb0); + return NULL; + } + + if( frameNum < 0 || frameNum >= md2->numFrames ) + { + _pico_printf( PICO_ERROR, "Invalid or out-of-range MD2 frame specified" ); + _pico_free(bb0); + 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, (const char *) (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" ); + _pico_free(bb0); + 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 ); + _pico_free(bb0); + 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 ); + _pico_free(bb0); + 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; inumXYZ; 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; inumTris; 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; inumXYZ; 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; iverts[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; inumXYZ; 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 */ + _pico_free(bb0); + 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/misc/mediasource/netradiant-src/libs/picomodel/pm_md3.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_md3.c new file mode 100644 index 00000000..b22704da --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_md3.c @@ -0,0 +1,430 @@ +/* ----------------------------------------------------------------------------- + +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 ) +{ + const md3_t *md3; + + + /* sanity check */ + if( (size_t) bufSize < ( sizeof( *md3 ) * 2) ) + return PICO_PMV_ERROR_SIZE; + + /* set as md3 */ + md3 = (const md3_t*) buffer; + + /* check md3 magic */ + if( *((const int*) md3->magic) != *((const 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, *bb0; + 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 */ + bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); + memcpy(bb, buffer, bufSize); + md3 = (md3_t*) bb; + + /* 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) */ + _pico_free(bb0); + 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" ); + _pico_free(bb0); + return NULL; + } + + if( frameNum < 0 || frameNum >= md3->numFrames ) + { + _pico_printf( PICO_ERROR, "Invalid or out-of-range MD3 frame specified" ); + _pico_free(bb0); + 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" ); + _pico_free(bb0); + 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 */ + _pico_free(bb0); + 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 ); + _pico_free(bb0); + 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 */ + _pico_free(bb0); + 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/misc/mediasource/netradiant-src/libs/picomodel/pm_mdc.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_mdc.c new file mode 100644 index 00000000..d1243b2c --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_mdc.c @@ -0,0 +1,755 @@ +/* ----------------------------------------------------------------------------- + +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 ) +{ + const mdc_t *mdc; + + + /* sanity check */ + if( (size_t) bufSize < ( sizeof( *mdc ) * 2) ) + return PICO_PMV_ERROR_SIZE; + + /* set as mdc */ + mdc = (const mdc_t*) buffer; + + /* check mdc magic */ + if( *((const int*) mdc->magic) != *((const 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, *bb0; + mdc_t *mdc; + mdcSurface_t *surface; + mdcShader_t *shader; + mdcTexCoord_t *texCoord; + mdcFrame_t *frame; + mdcTriangle_t *triangle; + mdcVertex_t *vertex; + mdcXyzCompressed_t *vertexComp = NULL; + short *mdcShort, *mdcCompVert = NULL; + 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 */ + bb0 = bb = (picoByte_t*) _pico_alloc(bufSize); + memcpy(bb, buffer, bufSize); + mdc = (mdc_t*) bb; + + /* 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) */ + _pico_free(bb0); + 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" ); + _pico_free(bb0); + return NULL; + } + + if( frameNum < 0 || frameNum >= mdc->numFrames ) + { + _pico_printf( PICO_ERROR, "Invalid or out-of-range MDC frame specified" ); + _pico_free(bb0); + 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" ); + _pico_free(bb0); + 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 */ + _pico_free(bb0); + 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 ); + _pico_free(bb0); + 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 */ + _pico_free(bb0); + 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/misc/mediasource/netradiant-src/libs/picomodel/pm_ms3d.c b/misc/mediasource/netradiant-src/libs/picomodel/pm_ms3d.c new file mode 100644 index 00000000..8626beed --- /dev/null +++ b/misc/mediasource/netradiant-src/libs/picomodel/pm_ms3d.c @@ -0,0 +1,497 @@ +/* ----------------------------------------------------------------------------- + +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 ) +{ + const TMsHeader *hdr; + + + /* sanity check */ + if ((size_t) bufSize < sizeof(TMsHeader)) + return PICO_PMV_ERROR_SIZE; + + /* get ms3d header */ + hdr = (const 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, *bufptr0; + 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 ); + + bufptr0 = bufptr = (picoByte_t*) _pico_alloc(bufSize); + memcpy(bufptr, buffer, bufSize); + /* skip header */ + bufptr += 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; ixyz[ 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; iflags = _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 ); + _pico_free(bufptr0); + 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 + + TexTool plugin for Q3Radiant - documentation +
+ + +TexTool plugin for Q3Radiant
+
Introduction +

TexTool is a set of texture tools for Q3Radiant. It was designed to help fine-tuning texture placement +on brushes and patches.

+Warning: +

The plugin needs brush primitives texture coordinates to operate. If this feature is not enabled in your project +settings you'll only be able to edit patches.

+
Basic use +

It's a "drag-n-drop control points" interface. Select a single face on a brush ( with shift+ctrl+left mouse clic), +or a patch, and do Plugins > Q3 Texture Tools > Go.... You can select points and move them... if you are editing +a brush face, you can rotate the shape by clicking on an anchor point first, then dragging another point.

+
+ + + + + +TexTool screenshot + +
+ +

There are also a few misc keys to help you. You can + +right clic + move the mouse to change the point of view +and use + +Inser and + +Suppr to zoom in/out. + + + + + +
+ +


+Appendix: keyboard shortcuts +

You can use the following keyboard shortcuts:

+

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + KEY
+
+ + usage
+
ESC
+
cancel the changes and hide TexTool window
+
RETURN
+
validate changes into the editor (also resets the view)
+
INSERT
+
zoom in
+
SUPPR
+
zoom out
+
RIGHT CLIC+MOVE
+
move the view
+
LEFT CLIC+MOVE
+
grab a control point and move it
+
RIGHT CLIC
+
drop down menu
+

+

Feedback, enhancements bugs etc. to timo@qeradiant.com

+

+ + + diff --git a/misc/mediasource/netradiant-src/plugins/textool/StdAfx.cpp b/misc/mediasource/netradiant-src/plugins/textool/StdAfx.cpp new file mode 100644 index 00000000..1b6e3d3c --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/textool/StdAfx.cpp @@ -0,0 +1,28 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// stdafx.cpp : source file that includes just the standard includes +// stdafx.obj will contain the pre-compiled type information + +#include "stdafx.h" + +// TODO: reference any additional headers you need in STDAFX.H +// and not in this file diff --git a/misc/mediasource/netradiant-src/plugins/textool/StdAfx.h b/misc/mediasource/netradiant-src/plugins/textool/StdAfx.h new file mode 100644 index 00000000..f23eeafd --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/textool/StdAfx.h @@ -0,0 +1,154 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// stdafx.h +// precompiled headers + +// standard headers +#include +#include +#include +#include + +#if !defined(WIN32) + +// Necessary for proper boolean type declaration +#include "qertypes.h" + +typedef void* HMODULE; +typedef void* LPVOID; +typedef char* LPCSTR; + +#define MB_OK 0x00000000L +#define MB_OKCANCEL 0x00000001L +#define MB_ABORTRETRYIGNORE 0x00000002L +#define MB_YESNOCANCEL 0x00000003L +#define MB_YESNO 0x00000004L +#define MB_RETRYCANCEL 0x00000005L + + +#define MB_ICONHAND 0x00000010L +#define MB_ICONQUESTION 0x00000020L +#define MB_ICONEXCLAMATION 0x00000030L +#define MB_ICONASTERISK 0x00000040L + +#define MB_USERICON 0x00000080L +#define MB_ICONWARNING MB_ICONEXCLAMATION +#define MB_ICONERROR MB_ICONHAND +#define MB_ICONINFORMATION MB_ICONASTERISK +#define MB_ICONSTOP MB_ICONHAND + +#define MB_TYPEMASK 0x0000000FL +#define MB_ICONMASK 0x000000F0L +#define MB_DEFMASK 0x00000F00L +#define MB_MODEMASK 0x00003000L +#define MB_MISCMASK 0x0000C000L + +#define IDOK 1 +#define IDCANCEL 2 +#define IDABORT 3 +#define IDRETRY 4 +#define IDIGNORE 5 +#define IDYES 6 +#define IDNO 7 + +typedef struct tagRECT +{ + long left; + long top; + long right; + long bottom; +} RECT, *PRECT, *LPRECT; + +#endif // __linux__ + +// plugin +// FIXME TTimo: drop this +extern "C" void Sys_Printf (char *text, ...); + +#include "synapse.h" +#include "iplugin.h" +#include "qerplugin.h" +#include "mathlib.h" +#include "igl.h" +#include "iselectedface.h" +#include "isurfaceplugin.h" +#include "iui.h" + +// internals +// the implementation of a IWindowListener interface to use with the native UI +// TODO: move in it's own set of files? +// NOTE: I'm not too sure about the bool flags being any use.. they are supposed to tell if we handle the event or not +class CWindowListener : public IWindowListener +{ + int refCount; +public: + // Increment the number of references to this object + void IncRef () { refCount++; } + // Decrement the reference count + void DecRef () { if ( --refCount <= 0 ) delete this; } + // IWindowListener --------------------------------------- + bool OnLButtonDown(guint32 nFlags, double x, double y); + bool OnMButtonDown(guint32 nFlags, double x, double y) { return false; } + bool OnRButtonDown(guint32 nFlags, double x, double y); + bool OnLButtonUp(guint32 nFlags, double x, double y); + bool OnMButtonUp(guint32 nFlags, double x, double y) { return false; } + bool OnRButtonUp(guint32 nFlags, double x, double y); + bool OnMouseMove(guint32 nFlags, double x, double y); + bool OnKeyPressed(char *s); + bool Paint(); + void Close(); +}; + +#include "2DView.h" +typedef struct +{ + float data[MAX_POINTS_ON_WINDING][2]; +} CtrlPts_t; +#include "ControlPointsManager.h" + +extern OpenGLBinding g_QglTable; +extern _QERFuncTable_1 g_FuncTable; +// prefs globals +// NOTE: these are used by the CControlPointsManager classes, not very C++ish +extern bool g_bPrefsUpdateCameraView; +extern _QERSelectedFaceTable g_SelectedFaceTable; +extern _QERFaceData g_CancelFaceData; + +#define Sys_Printf g_FuncTable.m_pfnSysPrintf +#define Sys_FPrintf g_FuncTable.m_pfnSysFPrintf + +// call to validate the current changes into the editor +extern void Textool_Validate(); +extern void Textool_Cancel(); + +class CSynapseClientTexTool : public CSynapseClient +{ +public: + // CSynapseClient API + bool RequestAPI(APIDescriptor_t *pAPI); + const char* GetInfo(); + + CSynapseClientTexTool() { } + virtual ~CSynapseClientTexTool() { } +}; + +extern IWindow *g_pToolWnd; diff --git a/misc/mediasource/netradiant-src/plugins/textool/TexTool.cpp b/misc/mediasource/netradiant-src/plugins/textool/TexTool.cpp new file mode 100644 index 00000000..9ba7b01b --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/textool/TexTool.cpp @@ -0,0 +1,962 @@ +/* +Copyright (C) 1999-2006 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: +// main plugin implementation +// texturing tools for Radiant +// + +#include "StdAfx.h" + +static void dialog_button_callback (GtkWidget *widget, gpointer data) +{ + GtkWidget *parent; + int *loop, *ret; + + parent = gtk_widget_get_toplevel (widget); + loop = (int*)g_object_get_data (G_OBJECT (parent), "loop"); + ret = (int*)g_object_get_data (G_OBJECT (parent), "ret"); + + *loop = 0; + *ret = gpointer_to_int (data); +} + +static gint dialog_delete_callback (GtkWidget *widget, GdkEvent* event, gpointer data) +{ + int *loop; + + gtk_widget_hide (widget); + loop = (int*)g_object_get_data (G_OBJECT (widget), "loop"); + *loop = 0; + + return TRUE; +} + +int DoMessageBox (const char* lpText, const char* lpCaption, guint32 uType) +{ + GtkWidget *window, *w, *vbox, *hbox; + int mode = (uType & MB_TYPEMASK), ret, loop = 1; + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_signal_connect (GTK_OBJECT (window), "delete_event", + GTK_SIGNAL_FUNC (dialog_delete_callback), NULL); + gtk_signal_connect (GTK_OBJECT (window), "destroy", + GTK_SIGNAL_FUNC (gtk_widget_destroy), NULL); + gtk_window_set_title (GTK_WINDOW (window), lpCaption); + gtk_container_border_width (GTK_CONTAINER (window), 10); + g_object_set_data (G_OBJECT (window), "loop", &loop); + g_object_set_data (G_OBJECT (window), "ret", &ret); + gtk_widget_realize (window); + + vbox = gtk_vbox_new (FALSE, 10); + gtk_container_add (GTK_CONTAINER (window), vbox); + gtk_widget_show (vbox); + + w = gtk_label_new (lpText); + gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); + gtk_label_set_justify (GTK_LABEL (w), GTK_JUSTIFY_LEFT); + gtk_widget_show (w); + + w = gtk_hseparator_new (); + gtk_box_pack_start (GTK_BOX (vbox), w, FALSE, FALSE, 2); + gtk_widget_show (w); + + hbox = gtk_hbox_new (FALSE, 10); + gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 2); + gtk_widget_show (hbox); + + if (mode == MB_OK) + { + w = gtk_button_new_with_label ("Ok"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); + GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); + gtk_widget_grab_default (w); + gtk_widget_show (w); + ret = IDOK; + } + else if (mode == MB_OKCANCEL) + { + w = gtk_button_new_with_label ("Ok"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDOK)); + GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); + gtk_widget_grab_default (w); + gtk_widget_show (w); + + w = gtk_button_new_with_label ("Cancel"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); + gtk_widget_show (w); + ret = IDCANCEL; + } + else if (mode == MB_YESNOCANCEL) + { + w = gtk_button_new_with_label ("Yes"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); + GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); + gtk_widget_grab_default (w); + gtk_widget_show (w); + + w = gtk_button_new_with_label ("No"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); + gtk_widget_show (w); + + w = gtk_button_new_with_label ("Cancel"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDCANCEL)); + gtk_widget_show (w); + ret = IDCANCEL; + } + else /* if (mode == MB_YESNO) */ + { + w = gtk_button_new_with_label ("Yes"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDYES)); + GTK_WIDGET_SET_FLAGS (w, GTK_CAN_DEFAULT); + gtk_widget_grab_default (w); + gtk_widget_show (w); + + w = gtk_button_new_with_label ("No"); + gtk_box_pack_start (GTK_BOX (hbox), w, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT (w), "clicked", + GTK_SIGNAL_FUNC (dialog_button_callback), GINT_TO_POINTER (IDNO)); + gtk_widget_show (w); + ret = IDNO; + } + + gtk_widget_show (window); + gtk_grab_add (window); + + while (loop) + gtk_main_iteration (); + + gtk_grab_remove (window); + gtk_widget_destroy (window); + + return ret; +} + +// Radiant function table +_QERFuncTable_1 g_FuncTable; + +// plugin name +const char *PLUGIN_NAME = "Q3 Texture Tools"; + +// commands in the menu +const char *PLUGIN_COMMANDS = "About...;Go..."; + +// cast to GtkWidget* +void *g_pMainWnd; +IWindow *g_pToolWnd = NULL; // handle to the window +CWindowListener g_Listen; + +// plugin interfaces --------------------------- +bool g_bQglInitDone = false; +OpenGLBinding g_QglTable; +bool g_bSelectedFaceInitDone = false; +_QERSelectedFaceTable g_SelectedFaceTable; +bool g_bUITable = false; +_QERUITable g_UITable; + +// selected face ------------------------------- +// we use this one to commit / read with Radiant +_QERFaceData g_SelectedFaceData; +// g_pSelectedFaceWindings gets allocated with MAX_POINTS_ON_WINDING at plugin startup ( QERPlug_Init ) +winding_t *g_pSelectedFaceWinding = NULL; +const float g_ViewportRatio = 1.2f; +// usefull class to manage the 2D view +C2DView g_2DView; +// control points to move the polygon +CControlPointsManagerBFace g_ControlPointsBFace; +// tells if a face is selected and we have something to render in the TexWindow +bool g_bTexViewReady = false; +// data for texture work +int g_NumPoints; +CtrlPts_t g_WorkWinding; +// reference _QERFaceData we use on Cancel, and for Commit +_QERFaceData g_CancelFaceData; + +// patches ------------------------------------- +bool g_bPatch = false; +//++timo we use this one to grab selected patchMesh_t +// FIXME: update when there's a real interface to read/write patches +bool g_bSurfaceTableInitDone = false; +_QERAppSurfaceTable g_SurfaceTable; +CControlPointsManagerPatch g_ControlPointsPatch; +// data for texture work +patchMesh_t* g_pPatch; +// we only use ctrl[][].st in this one +patchMesh_t g_WorkPatch; +// copy of initial g_pPatch for Cancel situation +patchMesh_t g_CancelPatch; + +// --------------------------------------------- +// holds the manager we are currently using +CControlPointsManager *g_pManager = NULL; + +// --------------------------------------------- +// globals flags for user preferences +//++timo TODO: this should be retrieved from the Editor's .INI prefs in a dedicated interface +// update camera view during manipulation ? +bool g_bPrefsUpdateCameraView = true; + +// misc ---------------------------------------- +bool g_bHelp = false; +//++timo FIXME: used to close the plugin window if InitTexView fails +// it's dirty, only use is to prevent infinite loop in DialogProc +bool g_bClosing = false; + +const char *PLUGIN_ABOUT = "Texture Tools for Radiant\n\n" + "Gtk port by Leonardo Zide (leo@lokigames.com)\n" + "Original version by Timothee \"TTimo\" Besset (timo@qeradiant.com)"; + +extern "C" void* WINAPI QERPlug_GetFuncTable () +{ + return &g_FuncTable; +} + +const char* QERPlug_Init (void* hApp, void *pWidget) +{ + int size; + GtkWidget* pMainWidget = static_cast(pWidget); + + g_pMainWnd = pMainWidget; + memset(&g_FuncTable, 0, sizeof(_QERFuncTable_1)); + g_FuncTable.m_nSize = sizeof(_QERFuncTable_1); + size = (int)((winding_t *)0)->points[MAX_POINTS_ON_WINDING]; + g_pSelectedFaceWinding = (winding_t *)malloc( size ); + memset( g_pSelectedFaceWinding, 0, size ); + return "Texture tools for Radiant"; +} + +const char* QERPlug_GetName() +{ + return (char*)PLUGIN_NAME; +} + +const char* QERPlug_GetCommandList() +{ + return PLUGIN_COMMANDS; +} + +char *TranslateString (char *buf) +{ + static char buf2[32768]; + int i, l; + char *out; + + l = strlen(buf); + out = buf2; + for (i=0 ; igetHeight(); + g_2DView.m_rect.right = hwndDlg->getWidth(); + + // we need to draw this area, now compute a bigger area so the texture scale is the same along X and Y + // compute box shape in XY space, let's say X <-> S we'll get a ratio for Y: + if (!g_bPatch) + { + g_SelectedFaceTable.m_pfnGetTextureSize( 0, TexSize ); + } + else + { + TexSize[0] = g_pPatch->d_texture->width; + TexSize[1] = g_pPatch->d_texture->height; + } + // we want a texture with the same X / Y ratio + // compute XY space / window size ratio + float SSize = (float)fabs( g_2DView.m_Maxs[0] - g_2DView.m_Mins[0] ); + float TSize = (float)fabs( g_2DView.m_Maxs[1] - g_2DView.m_Mins[1] ); + float XSize = TexSize[0] * SSize; + float YSize = TexSize[1] * TSize; + float RatioX = XSize / (float)abs( g_2DView.m_rect.left - g_2DView.m_rect.right ); + float RatioY = YSize / (float)abs( g_2DView.m_rect.top - g_2DView.m_rect.bottom ); + if ( RatioX > RatioY ) + { + YSize = (float)abs( g_2DView.m_rect.top - g_2DView.m_rect.bottom ) * RatioX; + TSize = YSize / (float)TexSize[1]; + } + else + { + XSize = (float)abs( g_2DView.m_rect.left - g_2DView.m_rect.right ) * RatioY; + SSize = XSize / (float)TexSize[0]; + } + g_2DView.m_Mins[0] = g_2DView.m_Center[0] - 0.5f * SSize; + g_2DView.m_Maxs[0] = g_2DView.m_Center[0] + 0.5f * SSize; + g_2DView.m_Mins[1] = g_2DView.m_Center[1] - 0.5f * TSize; + g_2DView.m_Maxs[1] = g_2DView.m_Center[1] + 0.5f * TSize; +} + +// call this one each time we need to re-init +//++timo TODO: re-init objects state, g_2DView and g_ControlPointsManager +void InitTexView( IWindow* hwndDlg ) +{ + // size of the texture we are working on + int TexSize[2]; + g_bTexViewReady = false; + if (g_SelectedFaceTable.m_pfnGetSelectedFaceCount() != 0) + { + g_SelectedFaceTable.m_pfnGetFaceInfo( 0, &g_SelectedFaceData, g_pSelectedFaceWinding ); + g_bPatch = false; + int i; + // we have something selected + // setup: compute BBox for the winding ( in ST space ) + //++timo FIXME: move this in a C2DView member ? used as well for patches + g_2DView.m_Mins[0] = +9999.0f; g_2DView.m_Mins[1] = +9999.0f; + g_2DView.m_Maxs[0] = -9999.0f; g_2DView.m_Maxs[1] = -9999.0f; + for ( i=0; inumpoints; i++ ) + { + if ( g_pSelectedFaceWinding->points[i][3] < g_2DView.m_Mins[0] ) + g_2DView.m_Mins[0] = g_pSelectedFaceWinding->points[i][3]; + if ( g_pSelectedFaceWinding->points[i][3] > g_2DView.m_Maxs[0] ) + g_2DView.m_Maxs[0] = g_pSelectedFaceWinding->points[i][3]; + if ( g_pSelectedFaceWinding->points[i][4] < g_2DView.m_Mins[1] ) + g_2DView.m_Mins[1] = g_pSelectedFaceWinding->points[i][4]; + if ( g_pSelectedFaceWinding->points[i][4] > g_2DView.m_Maxs[1] ) + g_2DView.m_Maxs[1] = g_pSelectedFaceWinding->points[i][4]; + } + // NOTE: FitView will read and init TexSize + FitView( hwndDlg, TexSize ); + // now init the work tables + g_NumPoints = g_pSelectedFaceWinding->numpoints; + for ( i=0; ipoints[i][3]; + g_WorkWinding.data[i][1] = g_pSelectedFaceWinding->points[i][4]; + } + g_ControlPointsBFace.Init( g_NumPoints, &g_WorkWinding, &g_2DView, TexSize, &g_SelectedFaceData, &g_QglTable ); + // init snap-to-grid + float fTexStep[2]; + fTexStep[0] = 1.0f / float(TexSize[0]); + fTexStep[1] = 1.0f / float(TexSize[1]); + g_2DView.SetGrid( fTexStep[0], fTexStep[1] ); + g_pManager = &g_ControlPointsBFace; + // prepare the "Cancel" data + memcpy( &g_CancelFaceData, &g_SelectedFaceData, sizeof(_QERFaceData) ); + // we are done + g_bTexViewReady = true; + } + else if ( g_SurfaceTable.m_pfnAnyPatchesSelected()) + { + g_pPatch = g_SurfaceTable.m_pfnGetSelectedPatch(); + g_bPatch = true; + int i,j; + // compute BBox for all patch points + g_2DView.m_Mins[0] = +9999.0f; g_2DView.m_Mins[1] = +9999.0f; + g_2DView.m_Maxs[0] = -9999.0f; g_2DView.m_Maxs[1] = -9999.0f; + for ( i=0; iwidth; i++ ) + { + for ( j=0; jheight; j++ ) + { + if ( g_pPatch->ctrl[i][j].st[0] < g_2DView.m_Mins[0] ) + g_2DView.m_Mins[0] = g_pPatch->ctrl[i][j].st[0]; + if ( g_pPatch->ctrl[i][j].st[0] > g_2DView.m_Maxs[0] ) + g_2DView.m_Maxs[0] = g_pPatch->ctrl[i][j].st[0]; + if ( g_pPatch->ctrl[i][j].st[1] < g_2DView.m_Mins[1] ) + g_2DView.m_Mins[1] = g_pPatch->ctrl[i][j].st[1]; + if ( g_pPatch->ctrl[i][j].st[1] > g_2DView.m_Maxs[1] ) + g_2DView.m_Maxs[1] = g_pPatch->ctrl[i][j].st[1]; + } + } + FitView( hwndDlg, TexSize); + // init the work tables + g_WorkPatch = *g_pPatch; + g_ControlPointsPatch.Init( &g_WorkPatch, &g_2DView, &g_QglTable, g_pPatch ); + // init snap-to-grid + float fTexStep[2]; + fTexStep[0] = 1.0f / float(TexSize[0]); + fTexStep[1] = 1.0f / float(TexSize[1]); + g_2DView.SetGrid( fTexStep[0], fTexStep[1] ); + g_pManager = &g_ControlPointsPatch; + // prepare the "cancel" data + g_CancelPatch = *g_pPatch; + // we are done + g_bTexViewReady = true; + } +} + +void Textool_Validate() +{ + // validate current situation into the main view + g_pManager->Commit( ); + // for a brush face we have an aditionnal step + if (!g_bPatch) + { + // tell Radiant to update (will also send update windows messages ) + g_SelectedFaceTable.m_pfnSetFaceInfo( 0, &g_SelectedFaceData ); + } + else + { + // ask to rebuild the patch display data + g_pPatch->bDirty = true; + // send a repaint to the camera window as well + g_FuncTable.m_pfnSysUpdateWindows( W_CAMERA ); + } + // we'll need to update after that as well: + g_bTexViewReady = false; + // send a repaint message + g_pToolWnd->Redraw (); +} + +void Textool_Cancel() +{ + if (!g_bPatch) + { + // tell Radiant to update (will also send update windows messages ) + g_SelectedFaceTable.m_pfnSetFaceInfo( 0, &g_CancelFaceData ); + } + else + { + *g_pPatch = g_CancelPatch; + g_pPatch->bDirty = true; + g_FuncTable.m_pfnSysUpdateWindows( W_CAMERA ); + } + // do not call destroy, decref it + g_pToolWnd->DecRef(); + g_pToolWnd = NULL; +} + +static void DoExpose () +{ + int i,j; + + g_2DView.PreparePaint(); + g_QglTable.m_pfn_qglColor3f(1, 1, 1); + // draw the texture background + g_QglTable.m_pfn_qglPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); + if (!g_bPatch) + { + g_QglTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, g_SelectedFaceTable.m_pfnGetTextureNumber(0) ); + } + else + { + g_QglTable.m_pfn_qglBindTexture( GL_TEXTURE_2D, g_pPatch->d_texture->texture_number ); + } + + g_QglTable.m_pfn_qglEnable( GL_TEXTURE_2D ); + g_QglTable.m_pfn_qglBegin( GL_QUADS ); + g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Mins[0], g_2DView.m_Mins[1] ); + g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Mins[0], g_2DView.m_Mins[1] ); + g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Maxs[0], g_2DView.m_Mins[1] ); + g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Maxs[0], g_2DView.m_Mins[1] ); + g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Maxs[0], g_2DView.m_Maxs[1] ); + g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Maxs[0], g_2DView.m_Maxs[1] ); + g_QglTable.m_pfn_qglTexCoord2f( g_2DView.m_Mins[0], g_2DView.m_Maxs[1] ); + g_QglTable.m_pfn_qglVertex2f( g_2DView.m_Mins[0], g_2DView.m_Maxs[1] ); + g_QglTable.m_pfn_qglEnd(); + g_QglTable.m_pfn_qglDisable( GL_TEXTURE_2D ); + + if (!g_bPatch) + { + g_QglTable.m_pfn_qglBegin( GL_LINE_LOOP ); + for ( i=0; iwidth; i++ ) + for ( j=0; jheight; j++ ) + { + if ( i < g_pPatch->width-1 ) + { + g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i][j].st[0], g_WorkPatch.ctrl[i][j].st[1] ); + g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i+1][j].st[0], g_WorkPatch.ctrl[i+1][j].st[1] ); + } + + if ( j < g_pPatch->height-1 ) + { + g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i][j].st[0], g_WorkPatch.ctrl[i][j].st[1] ); + g_QglTable.m_pfn_qglVertex2f( g_WorkPatch.ctrl[i][j+1].st[0], g_WorkPatch.ctrl[i][j+1].st[1] ); + } + } + g_QglTable.m_pfn_qglEnd(); + } + + // let the control points manager render + g_pManager->render( ); +} + +static bool CanProcess () +{ + if (!g_bTexViewReady && !g_bClosing) + { + InitTexView (g_pToolWnd); + + if (!g_bTexViewReady) + { + g_bClosing = true; + DoMessageBox ("You must have brush primitives activated in your project settings and\n" + "have a patch or a single face selected to use the TexTool plugin.\n" + "See plugins/TexToolHelp for documentation.", "TexTool plugin", MB_ICONERROR | MB_OK); + // decref, this will destroy + g_pToolWnd->DecRef(); + g_pToolWnd = NULL; + return 0; + } + else + g_bClosing = false; + } + else if (!g_bTexViewReady && g_bClosing) + { + return 0; + } + + return 1; +} + +#if 0 +static void button_press (GtkWidget *widget, GdkEventButton *event, gpointer data) +{ + if (CanProcess ()) + { + switch (event->button) + { + case 1: + g_pManager->OnLButtonDown (event->x, event->y); break; + case 3: + g_2DView.OnRButtonDown (event->x, event->y); break; + } + } +} + +static void button_release (GtkWidget *widget, GdkEventButton *event, gpointer data) +{ + if (CanProcess ()) + { + switch (event->button) + { + case 1: + g_pManager->OnLButtonUp (event->x, event->y); break; + case 3: + g_2DView.OnRButtonUp (event->x, event->y); break; + } + } +} + +static void motion (GtkWidget *widget, GdkEventMotion *event, gpointer data) +{ + if (CanProcess ()) + { + if (g_2DView.OnMouseMove (event->x, event->y)) + return; + + if (g_pManager->OnMouseMove (event->x, event->y)) + return; + } +} + +static gint expose (GtkWidget *widget, GdkEventExpose *event, gpointer data) +{ + if (event->count > 0) + return TRUE; + + if (!CanProcess ()) + return TRUE; + + if (g_bTexViewReady) + { + g_2DView.m_rect.bottom = widget->allocation.height; + g_2DView.m_rect.right = widget->allocation.width; + + if (!g_QglTable.m_pfn_glwidget_make_current (g_pToolWidget)) + { + Sys_Printf("TexTool: glMakeCurrent failed\n"); + return TRUE; + } + + DoExpose (); + + g_QglTable.m_pfn_glwidget_swap_buffers (g_pToolWidget); + } + + return TRUE; +} + +static gint keypress (GtkWidget* widget, GdkEventKey* event, gpointer data) +{ + unsigned int code = gdk_keyval_to_upper(event->keyval); + + if (code == GDK_Escape) + { + gtk_widget_destroy (g_pToolWnd); + g_pToolWnd = NULL; + return TRUE; + } + + if (CanProcess ()) + { + if (g_2DView.OnKeyDown (code)) + return FALSE; + + if (code == GDK_Return) + { + Textool_Validate(); + return FALSE; + } + } + + return TRUE; +} + +static gint close (GtkWidget *widget, GdkEvent* event, gpointer data) +{ + gtk_widget_destroy (widget); + g_pToolWnd = NULL; + + return TRUE; +} + +static GtkWidget* CreateOpenGLWidget () +{ + g_pToolWidget = g_QglTable.m_pfn_glwidget_new (FALSE, g_QglTable.m_pfn_GetQeglobalsGLWidget ()); + + gtk_widget_set_events (g_pToolWidget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_KEY_PRESS_MASK | + GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK); + + // Connect signal handlers + gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "expose_event", GTK_SIGNAL_FUNC (expose), NULL); + gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "motion_notify_event", + GTK_SIGNAL_FUNC (motion), NULL); + gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "button_press_event", + GTK_SIGNAL_FUNC (button_press), NULL); + gtk_signal_connect (GTK_OBJECT (g_pToolWidget), "button_release_event", + GTK_SIGNAL_FUNC (button_release), NULL); + + gtk_signal_connect (GTK_OBJECT (g_pToolWnd), "delete_event", GTK_SIGNAL_FUNC (close), NULL); + gtk_signal_connect (GTK_OBJECT (g_pToolWnd), "key_press_event", + GTK_SIGNAL_FUNC (keypress), NULL); + + return g_pToolWidget; +} +#endif + +#if 0 +static void DoPaint () +{ + if (!CanProcess ()) + return; + + if (g_bTexViewReady) + { + g_2DView.m_rect.bottom = g_pToolWnd->getHeight(); + g_2DView.m_rect.right = g_pToolWnd->getWidth(); + + // set GL_PROJECTION + g_2DView.PreparePaint(); + // render the objects + // the master is not rendered the same way, draw over a unified texture background + g_2DView.TextureBackground(g_DrawObjects[0].pObject->getTextureNumber()); + if (g_nDrawObjects >= 1) + { + int i; + for (i=1;iPrepareModelView(g_DrawObjects[i].pTopo); + g_DrawObjects[i].pObject->RenderAuxiliary(); + } + } + // draw the polygon outline and control points + g_DrawObjects[0].pObject->PrepareModelView(NULL); + g_DrawObjects[0].pObject->RenderUI(); + } +} +#endif + +bool CWindowListener::OnLButtonDown(guint32 nFlags, double x, double y) +{ + if (CanProcess()) + { + g_pManager->OnLButtonDown((int)x, (int)y); + return true; + } + return false; +} + +bool CWindowListener::OnRButtonDown(guint32 nFlags, double x, double y) +{ + if (CanProcess()) + { + g_2DView.OnRButtonDown ((int)x, (int)y); + return true; + } + return false; +} + +bool CWindowListener::OnLButtonUp(guint32 nFlags, double x, double y) +{ + if (CanProcess()) + { + g_pManager->OnLButtonUp((int)x, (int)y); + return true; + } + return false; +} + +bool CWindowListener::OnRButtonUp(guint32 nFlags, double x, double y) +{ + if (CanProcess()) + { + g_2DView.OnRButtonUp ((int)x, (int)y); + return true; + } + return false; +} + +bool CWindowListener::OnMouseMove(guint32 nFlags, double x, double y) +{ + if (CanProcess ()) + { + if (g_2DView.OnMouseMove ((int)x, (int)y)) + return true; + + g_pManager->OnMouseMove((int)x, (int)y); + return true; + } + return false; +} + +// the widget is closing +void CWindowListener::Close() +{ + g_pToolWnd = NULL; +} + +bool CWindowListener::Paint() +{ + if (!CanProcess ()) + return false; + + if (g_bTexViewReady) + DoExpose(); + + return true; +} + +bool CWindowListener::OnKeyPressed(char *s) +{ + if (!strcmp(s,"Escape")) + { + Textool_Cancel(); + return TRUE; + } + if (CanProcess ()) + { + if (g_2DView.OnKeyDown (s)) + return TRUE; + + if (!strcmp(s,"Return")) + { + Textool_Validate(); + return TRUE; + } + } + return FALSE; +} + +extern "C" void QERPlug_Dispatch(const char* p, vec3_t vMin, vec3_t vMax, bool bSingleBrush) +{ + #if 0 + // if it's the first call, perhaps we need some additional init steps + if (!g_bQglInitDone) + { + g_QglTable.m_nSize = sizeof(OpenGLBinding); + if ( g_FuncTable.m_pfnRequestInterface( QERQglTable_GUID, static_cast(&g_QglTable) ) ) + { + g_bQglInitDone = true; + } + else + { + Sys_Printf("TexTool plugin: OpenGLBinding interface request failed\n"); + return; + } + } + + if (!g_bSelectedFaceInitDone) + { + g_SelectedFaceTable.m_nSize = sizeof(_QERSelectedFaceTable); + if (g_FuncTable.m_pfnRequestInterface (QERSelectedFaceTable_GUID, + static_cast(&g_SelectedFaceTable))) + { + g_bSelectedFaceInitDone = true; + } + else + { + Sys_Printf("TexTool plugin: _QERSelectedFaceTable interface request failed\n"); + return; + } + } + + if (!g_bSurfaceTableInitDone) + { + g_SurfaceTable.m_nSize = sizeof(_QERAppSurfaceTable); + if ( g_FuncTable.m_pfnRequestInterface( QERAppSurfaceTable_GUID, static_cast(&g_SurfaceTable) ) ) + { + g_bSurfaceTableInitDone = true; + } + else + { + Sys_Printf("TexTool plugin: _QERAppSurfaceTable interface request failed\n"); + return; + } + } + + if (!g_bUITable) + { + g_UITable.m_nSize = sizeof(_QERUITable); + if ( g_FuncTable.m_pfnRequestInterface( QERUI_GUID, static_cast(&g_UITable) ) ) + { + g_bUITable = true; + } + else + { + Sys_Printf("TexTool plugin: _QERUITable interface request failed\n"); + return; + } + } + #endif + + if (!strcmp(p, "About...")) + { + DoMessageBox (PLUGIN_ABOUT, "About ...", MB_OK ); + } + else if (!strcmp(p, "Go...")) + { + if (!g_pToolWnd) + { + g_pToolWnd = g_UITable.m_pfnCreateGLWindow(); + g_pToolWnd->setSizeParm(300,300); + g_pToolWnd->setName("TexTool"); + // g_Listener is a static class, we need to bump the refCount to avoid premature release problems + g_Listen.IncRef(); + // setListener will incRef on the listener too + g_pToolWnd->setListener(&g_Listen); + if (!g_pToolWnd->Show()) + { + DoMessageBox ("Error creating texture tools window!", "TexTool plugin", MB_ICONERROR | MB_OK); + return; + } + } + + g_bTexViewReady = false; + g_bClosing = false; + } + else if (!strcmp(p, "Help...")) + { + if (!g_bHelp) + DoMessageBox ("Select a brush face (ctrl+shift+left mouse) or a patch, and hit Go...\n" + "See tutorials for more", "TexTool plugin", MB_OK ); + else + DoMessageBox ("Are you kidding me ?", "TexTool plugin", MB_OK ); + g_bHelp = true; + } +} + +// ============================================================================= +// SYNAPSE + +CSynapseServer* g_pSynapseServer = NULL; +CSynapseClientTexTool g_SynapseClient; + +extern "C" CSynapseClient* SYNAPSE_DLL_EXPORT Synapse_EnumerateInterfaces (const char *version, CSynapseServer *pServer) +{ + if (strcmp(version, SYNAPSE_VERSION)) + { + Syn_Printf("ERROR: synapse API version mismatch: should be '" SYNAPSE_VERSION "', got '%s'\n", version); + return NULL; + } + g_pSynapseServer = pServer; + g_pSynapseServer->IncRef(); + Set_Syn_Printf(g_pSynapseServer->Get_Syn_Printf()); + + g_SynapseClient.AddAPI(PLUGIN_MAJOR, "textool", sizeof(_QERPluginTable)); + g_SynapseClient.AddAPI(RADIANT_MAJOR, NULL, sizeof(g_FuncTable), SYN_REQUIRE, &g_FuncTable); + g_SynapseClient.AddAPI(QGL_MAJOR, NULL, sizeof(g_QglTable), SYN_REQUIRE, &g_QglTable); + g_SynapseClient.AddAPI(SELECTEDFACE_MAJOR, NULL, sizeof(g_SelectedFaceTable), SYN_REQUIRE, &g_SelectedFaceTable); + + return &g_SynapseClient; +} + +bool CSynapseClientTexTool::RequestAPI(APIDescriptor_t *pAPI) +{ + if (!strcmp(pAPI->major_name, PLUGIN_MAJOR)) + { + _QERPluginTable *pTable = static_cast<_QERPluginTable*>(pAPI->mpTable); + pTable->m_pfnQERPlug_Init = QERPlug_Init; + pTable->m_pfnQERPlug_GetName = QERPlug_GetName; + pTable->m_pfnQERPlug_GetCommandList = QERPlug_GetCommandList; + pTable->m_pfnQERPlug_Dispatch = QERPlug_Dispatch; + return true; + } + + Syn_Printf("ERROR: RequestAPI( '%s' ) not found in '%s'\n", pAPI->major_name, GetInfo()); + return false; +} + +#include "version.h" + +const char* CSynapseClientTexTool::GetInfo() +{ + return "Texture Tools plugin built " __DATE__ " " RADIANT_VERSION; +} diff --git a/misc/mediasource/netradiant-src/plugins/textool/TexTool.def b/misc/mediasource/netradiant-src/plugins/textool/TexTool.def new file mode 100644 index 00000000..95cbb273 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/textool/TexTool.def @@ -0,0 +1,12 @@ +; TexTool.def : Declares the module parameters for the DLL. + +LIBRARY "TexTool" +DESCRIPTION 'TexTool Windows Dynamic Link Library' + +EXPORTS + ; Explicit exports can go here + QERPlug_Init @1 + QERPlug_GetName @2 + QERPlug_GetCommandList @3 + QERPlug_Dispatch @4 + QERPlug_GetFuncTable @5 diff --git a/misc/mediasource/netradiant-src/plugins/textool/TexTool.rc b/misc/mediasource/netradiant-src/plugins/textool/TexTool.rc new file mode 100644 index 00000000..69d0eaf5 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/textool/TexTool.rc @@ -0,0 +1,136 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Neutral resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Dialog +// + +IDD_DIALOG2 DIALOGEX 0, 0, 290, 206 +STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME +EXSTYLE WS_EX_TOOLWINDOW +FONT 8, "MS Sans Serif" +BEGIN +END + + +///////////////////////////////////////////////////////////////////////////// +// +// DESIGNINFO +// + +#ifdef APSTUDIO_INVOKED +GUIDELINES DESIGNINFO DISCARDABLE +BEGIN + IDD_DIALOG2, DIALOG + BEGIN + LEFTMARGIN, 7 + RIGHTMARGIN, 283 + TOPMARGIN, 7 + BOTTOMMARGIN, 199 + END +END +#endif // APSTUDIO_INVOKED + +#endif // Neutral resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Menu +// + +IDR_DROP_MENU MENU DISCARDABLE +BEGIN + POPUP "Drop" + BEGIN + MENUITEM "Validate (RETURN)", ID_DROP_VALIDATE + MENUITEM "Zoom in (INSERT)", ID_DROP_ZOOMIN + MENUITEM "Zoom out (SUPPR)", ID_DROP_ZOOMOUT + MENUITEM "Cancel (ESC)", ID_DROP_CANCEL + END +END + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + +///////////////////////////////////////////////////////////////////////////// +// French (France) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_FRA) +#ifdef _WIN32 +LANGUAGE LANG_FRENCH, SUBLANG_FRENCH +#pragma code_page(1252) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // French (France) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/misc/mediasource/netradiant-src/plugins/textool/changelog.txt b/misc/mediasource/netradiant-src/plugins/textool/changelog.txt new file mode 100644 index 00000000..9d660cbc --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/textool/changelog.txt @@ -0,0 +1,8 @@ +11/19/99 +first usable version +here is the TODO-list for next release, ( most certainly a wish list ) + +- TODO: add hooks with the selected face and selected patch data. tell the plugin when selected face +or selected patch has changed. +the hooks should use a generic interface inside Radiant for "observers" +- TODO: add other usefull texturing tools, if designers come up with good ideas \ No newline at end of file diff --git a/misc/mediasource/netradiant-src/plugins/textool/resource.h b/misc/mediasource/netradiant-src/plugins/textool/resource.h new file mode 100644 index 00000000..85ba8d7d --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/textool/resource.h @@ -0,0 +1,23 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by TexTool.rc +// +#define IDUNDO 3 +#define IDD_DIALOG 101 +#define IDD_DIALOG2 102 +#define IDR_DROP_MENU 103 +#define ID_DROP_VALIDATE 40001 +#define ID_DROP_ZOOMIN 40002 +#define ID_DROP_ZOOMOUT 40003 +#define ID_DROP_CANCEL 40004 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 104 +#define _APS_NEXT_COMMAND_VALUE 40005 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/misc/mediasource/netradiant-src/plugins/vfspk3/archive.cpp b/misc/mediasource/netradiant-src/plugins/vfspk3/archive.cpp new file mode 100644 index 00000000..9147f8f0 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/vfspk3/archive.cpp @@ -0,0 +1,178 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "archive.h" + +#include "idatastream.h" +#include "iarchive.h" + +#include +#include +#include + +#include "stream/filestream.h" +#include "stream/textfilestream.h" +#include "string/string.h" +#include "os/path.h" +#include "os/file.h" +#include "os/dir.h" +#include "archivelib.h" +#include "fs_path.h" + +#include "vfspk3.h" + + +class DirectoryArchive : public Archive +{ + CopiedString m_root; +public: + DirectoryArchive(const char* root) : m_root(root) + { + } + + void release() + { + delete this; + } + virtual ArchiveFile* openFile(const char* name) + { + UnixPath path(m_root.c_str()); + path.push_filename(name); + DirectoryArchiveFile* file = new DirectoryArchiveFile(name, path.c_str()); + if(!file->failed()) + { + return file; + } + file->release(); + return 0; + } + virtual ArchiveTextFile* openTextFile(const char* name) + { + UnixPath path(m_root.c_str()); + path.push_filename(name); + DirectoryArchiveTextFile* file = new DirectoryArchiveTextFile(name, path.c_str()); + if(!file->failed()) + { + return file; + } + file->release(); + return 0; + } + virtual bool containsFile(const char* name) + { + UnixPath path(m_root.c_str()); + path.push_filename(name); + return file_readable(path.c_str()); + } + virtual void forEachFile(VisitorFunc visitor, const char* root) + { + std::vector dirs; + UnixPath path(m_root.c_str()); + path.push(root); + dirs.push_back(directory_open(path.c_str())); + + while(!dirs.empty() && directory_good(dirs.back())) + { + const char* name = directory_read_and_increment(dirs.back()); + + if(name == 0) + { + directory_close(dirs.back()); + dirs.pop_back(); + path.pop(); + } + else if(!string_equal(name, ".") && !string_equal(name, "..")) + { + path.push_filename(name); + + bool is_directory = file_is_directory(path.c_str()); + + if(!is_directory) + visitor.file(path_make_relative(path.c_str(), m_root.c_str())); + + path.pop(); + + if(is_directory) + { + path.push(name); + + if(!visitor.directory(path_make_relative(path.c_str(), m_root.c_str()), dirs.size())) + dirs.push_back(directory_open(path.c_str())); + else + path.pop(); + } + } + } + } +}; + +Archive* OpenArchive(const char* name) +{ + return new DirectoryArchive(name); +} + +#if 0 + +class TestArchive +{ + class TestVisitor : public Archive::IVisitor + { + public: + virtual void visit(const char* name) + { + int bleh = 0; + } + }; +public: + void test1() + { + Archive* archive = OpenArchive("d:/quake/id1/"); + ArchiveFile* file = archive->openFile("quake101.wad"); + if(file != 0) + { + char buffer[1024]; + file->getInputStream().read(buffer, 1024); + file->release(); + } + TestVisitor visitor; + archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 0), ""); + archive->release(); + } + void test2() + { + Archive* archive = OpenArchive("d:/gtkradiant_root/baseq3/"); + TestVisitor visitor; + archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 2), ""); + archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFiles, 1), "textures"); + archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eDirectories, 1), "textures"); + archive->forEachFile(Archive::VisitorFunc(&visitor, Archive::eFilesAndDirectories, 1), "textures"); + archive->release(); + } + TestArchive() + { + test1(); + test2(); + } +}; + +TestArchive g_test; + +#endif diff --git a/misc/mediasource/netradiant-src/plugins/vfspk3/archive.h b/misc/mediasource/netradiant-src/plugins/vfspk3/archive.h new file mode 100644 index 00000000..09874c37 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/vfspk3/archive.h @@ -0,0 +1,29 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ARCHIVE_H) +#define INCLUDED_ARCHIVE_H + +#include "iarchive.h" + +const _QERArchiveTable* GetArchiveTable(ArchiveModules& archiveModules, const char* type); + +#endif diff --git a/misc/mediasource/netradiant-src/plugins/vfspk3/vfs.cpp b/misc/mediasource/netradiant-src/plugins/vfspk3/vfs.cpp new file mode 100644 index 00000000..b47942ba --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/vfspk3/vfs.cpp @@ -0,0 +1,742 @@ +/* +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 "vfs.h" + +#include +#include +#include +#include +#include + +#include "qerplugin.h" +#include "idatastream.h" +#include "iarchive.h" +ArchiveModules& FileSystemQ3API_getArchiveModules(); +#include "ifilesystem.h" + +#include "generic/callback.h" +#include "string/string.h" +#include "stream/stringstream.h" +#include "os/path.h" +#include "moduleobservers.h" + + +#define VFS_MAXDIRS 64 + +#if defined(WIN32) +#define PATH_MAX 260 +#endif + +#define gamemode_get GlobalRadiant().getGameMode + + + +// ============================================================================= +// Global variables + +Archive* OpenArchive(const char* name); + +struct archive_entry_t +{ + CopiedString name; + Archive* archive; + bool is_pakfile; +}; + +#include + +typedef std::list archives_t; + +static archives_t g_archives; +static char g_strDirs[VFS_MAXDIRS][PATH_MAX+1]; +static int g_numDirs; +static char g_strForbiddenDirs[VFS_MAXDIRS][PATH_MAX+1]; +static int g_numForbiddenDirs = 0; +static bool g_bUsePak = true; + +ModuleObservers g_observers; + +// ============================================================================= +// Static functions + +static void AddSlash (char *str) +{ + std::size_t n = strlen (str); + if (n > 0) + { + if (str[n-1] != '\\' && str[n-1] != '/') + { + globalErrorStream() << "WARNING: directory path does not end with separator: " << str << "\n"; + strcat (str, "/"); + } + } +} + +static void FixDOSName (char *src) +{ + if (src == 0 || strchr(src, '\\') == 0) + return; + + globalErrorStream() << "WARNING: invalid path separator '\\': " << src << "\n"; + + while (*src) + { + if (*src == '\\') + *src = '/'; + src++; + } +} + + + +const _QERArchiveTable* GetArchiveTable(ArchiveModules& archiveModules, const char* ext) +{ + StringOutputStream tmp(16); + tmp << LowerCase(ext); + return archiveModules.findModule(tmp.c_str()); +} +static void InitPakFile (ArchiveModules& archiveModules, const char *filename) +{ + const _QERArchiveTable* table = GetArchiveTable(archiveModules, path_get_extension(filename)); + + if(table != 0) + { + archive_entry_t entry; + entry.name = filename; + + entry.archive = table->m_pfnOpenArchive(filename); + entry.is_pakfile = true; + g_archives.push_back(entry); + globalOutputStream() << " pak file: " << filename << "\n"; + } +} + +inline void pathlist_prepend_unique(GSList*& pathlist, char* path) +{ + if(g_slist_find_custom(pathlist, path, (GCompareFunc)path_compare) == 0) + { + pathlist = g_slist_prepend(pathlist, path); + } + else + { + g_free(path); + } +} + +class DirectoryListVisitor : public Archive::Visitor +{ + GSList*& m_matches; + const char* m_directory; +public: + DirectoryListVisitor(GSList*& matches, const char* directory) + : m_matches(matches), m_directory(directory) + {} + void visit(const char* name) + { + const char* subname = path_make_relative(name, m_directory); + if(subname != name) + { + if(subname[0] == '/') + ++subname; + char* dir = g_strdup(subname); + char* last_char = dir + strlen(dir); + if(last_char != dir && *(--last_char) == '/') + *last_char = '\0'; + pathlist_prepend_unique(m_matches, dir); + } + } +}; + +class FileListVisitor : public Archive::Visitor +{ + GSList*& m_matches; + const char* m_directory; + const char* m_extension; +public: + FileListVisitor(GSList*& matches, const char* directory, const char* extension) + : m_matches(matches), m_directory(directory), m_extension(extension) + {} + void visit(const char* name) + { + const char* subname = path_make_relative(name, m_directory); + if(subname != name) + { + if(subname[0] == '/') + ++subname; + if(m_extension[0] == '*' || extension_equal(path_get_extension(subname), m_extension)) + pathlist_prepend_unique(m_matches, g_strdup (subname)); + } + } +}; + +static GSList* GetListInternal (const char *refdir, const char *ext, bool directories, std::size_t depth) +{ + GSList* files = 0; + + ASSERT_MESSAGE(refdir[strlen(refdir) - 1] == '/', "search path does not end in '/'"); + + if(directories) + { + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + DirectoryListVisitor visitor(files, refdir); + (*i).archive->forEachFile(Archive::VisitorFunc(visitor, Archive::eDirectories, depth), refdir); + } + } + else + { + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + FileListVisitor visitor(files, refdir, ext); + (*i).archive->forEachFile(Archive::VisitorFunc(visitor, Archive::eFiles, depth), refdir); + } + } + + files = g_slist_reverse(files); + + return files; +} + +inline int ascii_to_upper(int c) +{ + if (c >= 'a' && c <= 'z') + { + return c - ('a' - 'A'); + } + return c; +} + +/*! +This behaves identically to stricmp(a,b), except that ASCII chars +[\]^`_ come AFTER alphabet chars instead of before. This is because +it converts all alphabet chars to uppercase before comparison, +while stricmp converts them to lowercase. +*/ +static int string_compare_nocase_upper(const char* a, const char* b) +{ + for(;;) + { + int c1 = ascii_to_upper(*a++); + int c2 = ascii_to_upper(*b++); + + if (c1 < c2) + { + return -1; // a < b + } + if (c1 > c2) + { + return 1; // a > b + } + if(c1 == 0) + { + return 0; // a == b + } + } +} + +// Arnout: note - sort pakfiles in reverse order. This ensures that +// later pakfiles override earlier ones. This because the vfs module +// returns a filehandle to the first file it can find (while it should +// return the filehandle to the file in the most overriding pakfile, the +// last one in the list that is). + +//!\todo Analyse the code in rtcw/q3 to see which order it sorts pak files. +class PakLess +{ +public: + bool operator()(const CopiedString& self, const CopiedString& other) const + { + return string_compare_nocase_upper(self.c_str(), other.c_str()) > 0; + } +}; + +typedef std::set Archives; + +// ============================================================================= +// Global functions + +// reads all pak files from a dir +void InitDirectory(const char* directory, ArchiveModules& archiveModules) +{ + int j; + + g_numForbiddenDirs = 0; + StringTokeniser st(GlobalRadiant().getGameDescriptionKeyValue("forbidden_paths"), " "); + for(j = 0; j < VFS_MAXDIRS; ++j) + { + const char *t = st.getToken(); + if(string_empty(t)) + break; + strncpy(g_strForbiddenDirs[g_numForbiddenDirs], t, PATH_MAX); + g_strForbiddenDirs[g_numForbiddenDirs][PATH_MAX] = '\0'; + ++g_numForbiddenDirs; + } + + for(j = 0; j < g_numForbiddenDirs; ++j) + { + if(!string_compare_nocase_upper(directory, g_strForbiddenDirs[j]) + || (string_length(directory) > string_length(g_strForbiddenDirs[j]) && directory[string_length(directory) - string_length(g_strForbiddenDirs[j]) - 1] == '/' && !string_compare_nocase_upper(directory + string_length(directory) - string_length(g_strForbiddenDirs[j]), g_strForbiddenDirs[j]))) + break; + } + if(j < g_numForbiddenDirs) + { + printf("Directory %s matched by forbidden dirs, removed\n", directory); + return; + } + + if (g_numDirs == VFS_MAXDIRS) + return; + + strncpy(g_strDirs[g_numDirs], directory, PATH_MAX); + g_strDirs[g_numDirs][PATH_MAX] = '\0'; + FixDOSName (g_strDirs[g_numDirs]); + AddSlash (g_strDirs[g_numDirs]); + + const char* path = g_strDirs[g_numDirs]; + + g_numDirs++; + + { + archive_entry_t entry; + entry.name = path; + entry.archive = OpenArchive(path); + entry.is_pakfile = false; + g_archives.push_back(entry); + } + + if (g_bUsePak) + { + GDir* dir = g_dir_open (path, 0, 0); + + if (dir != 0) + { + globalOutputStream() << "vfs directory: " << path << "\n"; + + const char* ignore_prefix = ""; + const char* override_prefix = ""; + + { + // See if we are in "sp" or "mp" mapping mode + const char* gamemode = gamemode_get(); + + if (strcmp (gamemode, "sp") == 0) + { + ignore_prefix = "mp_"; + override_prefix = "sp_"; + } + else if (strcmp (gamemode, "mp") == 0) + { + ignore_prefix = "sp_"; + override_prefix = "mp_"; + } + } + + Archives archives; + Archives archivesOverride; + for(;;) + { + const char* name = g_dir_read_name(dir); + if(name == 0) + break; + + for(j = 0; j < g_numForbiddenDirs; ++j) + if(!string_compare_nocase_upper(name, g_strForbiddenDirs[j])) + break; + if(j < g_numForbiddenDirs) + continue; + + const char *ext = strrchr (name, '.'); + + if(ext && !string_compare_nocase_upper(ext, ".pk3dir")) + { + if (g_numDirs == VFS_MAXDIRS) + continue; + snprintf(g_strDirs[g_numDirs], PATH_MAX, "%s%s/", path, name); + g_strDirs[g_numDirs][PATH_MAX] = '\0'; + FixDOSName (g_strDirs[g_numDirs]); + AddSlash (g_strDirs[g_numDirs]); + g_numDirs++; + + { + archive_entry_t entry; + entry.name = g_strDirs[g_numDirs-1]; + entry.archive = OpenArchive(g_strDirs[g_numDirs-1]); + entry.is_pakfile = false; + g_archives.push_back(entry); + } + } + + if ((ext == 0) || *(++ext) == '\0' || GetArchiveTable(archiveModules, ext) == 0) + continue; + + // using the same kludge as in engine to ensure consistency + if(!string_empty(ignore_prefix) && strncmp(name, ignore_prefix, strlen(ignore_prefix)) == 0) + { + continue; + } + if(!string_empty(override_prefix) && strncmp(name, override_prefix, strlen(override_prefix)) == 0) + { + archivesOverride.insert(name); + continue; + } + + archives.insert(name); + } + + g_dir_close (dir); + + // add the entries to the vfs + for(Archives::iterator i = archivesOverride.begin(); i != archivesOverride.end(); ++i) + { + char filename[PATH_MAX]; + strcpy(filename, path); + strcat(filename, (*i).c_str()); + InitPakFile(archiveModules, filename); + } + for(Archives::iterator i = archives.begin(); i != archives.end(); ++i) + { + char filename[PATH_MAX]; + strcpy(filename, path); + strcat(filename, (*i).c_str()); + InitPakFile(archiveModules, filename); + } + } + else + { + globalErrorStream() << "vfs directory not found: " << path << "\n"; + } + } +} + +// frees all memory that we allocated +// FIXME TTimo this should be improved so that we can shutdown and restart the VFS without exiting Radiant? +// (for instance when modifying the project settings) +void Shutdown() +{ + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + (*i).archive->release(); + } + g_archives.clear(); + + g_numDirs = 0; + g_numForbiddenDirs = 0; +} + +#define VFS_SEARCH_PAK 0x1 +#define VFS_SEARCH_DIR 0x2 + +int GetFileCount (const char *filename, int flag) +{ + int count = 0; + char fixed[PATH_MAX+1]; + + strncpy(fixed, filename, PATH_MAX); + fixed[PATH_MAX] = '\0'; + FixDOSName (fixed); + + if(!flag) + flag = VFS_SEARCH_PAK | VFS_SEARCH_DIR; + + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + if((*i).is_pakfile && (flag & VFS_SEARCH_PAK) != 0 + || !(*i).is_pakfile && (flag & VFS_SEARCH_DIR) != 0) + { + if((*i).archive->containsFile(fixed)) + ++count; + } + } + + return count; +} + +ArchiveFile* OpenFile(const char* filename) +{ + ASSERT_MESSAGE(strchr(filename, '\\') == 0, "path contains invalid separator '\\': \"" << filename << "\""); + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + ArchiveFile* file = (*i).archive->openFile(filename); + if(file != 0) + { + return file; + } + } + + return 0; +} + +ArchiveTextFile* OpenTextFile(const char* filename) +{ + ASSERT_MESSAGE(strchr(filename, '\\') == 0, "path contains invalid separator '\\': \"" << filename << "\""); + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + ArchiveTextFile* file = (*i).archive->openTextFile(filename); + if(file != 0) + { + return file; + } + } + + return 0; +} + +// NOTE: when loading a file, you have to allocate one extra byte and set it to \0 +std::size_t LoadFile (const char *filename, void **bufferptr, int index) +{ + char fixed[PATH_MAX+1]; + + strncpy (fixed, filename, PATH_MAX); + fixed[PATH_MAX] = '\0'; + FixDOSName (fixed); + + ArchiveFile* file = OpenFile(fixed); + + if(file != 0) + { + *bufferptr = malloc (file->size()+1); + // we need to end the buffer with a 0 + ((char*) (*bufferptr))[file->size()] = 0; + + std::size_t length = file->getInputStream().read((InputStream::byte_type*)*bufferptr, file->size()); + file->release(); + return length; + } + + *bufferptr = 0; + return 0; +} + +void FreeFile (void *p) +{ + free(p); +} + +GSList* GetFileList (const char *dir, const char *ext, std::size_t depth) +{ + return GetListInternal (dir, ext, false, depth); +} + +GSList* GetDirList (const char *dir, std::size_t depth) +{ + return GetListInternal (dir, 0, true, depth); +} + +void ClearFileDirList (GSList **lst) +{ + while (*lst) + { + g_free ((*lst)->data); + *lst = g_slist_remove (*lst, (*lst)->data); + } +} + +const char* FindFile(const char* relative) +{ + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + if((*i).archive->containsFile(relative)) + { + return (*i).name.c_str(); + } + } + + return ""; +} + +const char* FindPath(const char* absolute) +{ + const char *best = ""; + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + if(string_length((*i).name.c_str()) > string_length(best)) + if(path_equal_n(absolute, (*i).name.c_str(), string_length((*i).name.c_str()))) + best = (*i).name.c_str(); + } + + return best; +} + + +class Quake3FileSystem : public VirtualFileSystem +{ +public: + void initDirectory(const char *path) + { + InitDirectory(path, FileSystemQ3API_getArchiveModules()); + } + void initialise() + { + globalOutputStream() << "filesystem initialised\n"; + g_observers.realise(); + } + void shutdown() + { + g_observers.unrealise(); + globalOutputStream() << "filesystem shutdown\n"; + Shutdown(); + } + + int getFileCount(const char *filename, int flags) + { + return GetFileCount(filename, flags); + } + ArchiveFile* openFile(const char* filename) + { + return OpenFile(filename); + } + ArchiveTextFile* openTextFile(const char* filename) + { + return OpenTextFile(filename); + } + std::size_t loadFile(const char *filename, void **buffer) + { + return LoadFile(filename, buffer, 0); + } + void freeFile(void *p) + { + FreeFile(p); + } + + void forEachDirectory(const char* basedir, const FileNameCallback& callback, std::size_t depth) + { + GSList* list = GetDirList(basedir, depth); + + for(GSList* i = list; i != 0; i = g_slist_next(i)) + { + callback(reinterpret_cast((*i).data)); + } + + ClearFileDirList(&list); + } + void forEachFile(const char* basedir, const char* extension, const FileNameCallback& callback, std::size_t depth) + { + GSList* list = GetFileList(basedir, extension, depth); + + for(GSList* i = list; i != 0; i = g_slist_next(i)) + { + const char* name = reinterpret_cast((*i).data); + if(extension_equal(path_get_extension(name), extension)) + { + callback(name); + } + } + + ClearFileDirList(&list); + } + GSList* getDirList(const char *basedir) + { + return GetDirList(basedir, 1); + } + GSList* getFileList(const char *basedir, const char *extension) + { + return GetFileList(basedir, extension, 1); + } + void clearFileDirList(GSList **lst) + { + ClearFileDirList(lst); + } + + const char* findFile(const char *name) + { + return FindFile(name); + } + const char* findRoot(const char *name) + { + return FindPath(name); + } + + void attach(ModuleObserver& observer) + { + g_observers.attach(observer); + } + void detach(ModuleObserver& observer) + { + g_observers.detach(observer); + } + + Archive* getArchive(const char* archiveName, bool pakonly) + { + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + if(pakonly && !(*i).is_pakfile) + continue; + + if(path_equal((*i).name.c_str(), archiveName)) + return (*i).archive; + } + return 0; + } + void forEachArchive(const ArchiveNameCallback& callback, bool pakonly, bool reverse) + { + if (reverse) + g_archives.reverse(); + + for(archives_t::iterator i = g_archives.begin(); i != g_archives.end(); ++i) + { + if(pakonly && !(*i).is_pakfile) + continue; + + callback((*i).name.c_str()); + } + + if (reverse) + g_archives.reverse(); + } +}; + +Quake3FileSystem g_Quake3FileSystem; + +void FileSystem_Init() +{ +} + +void FileSystem_Shutdown() +{ +} + +VirtualFileSystem& GetFileSystem() +{ + return g_Quake3FileSystem; +} diff --git a/misc/mediasource/netradiant-src/plugins/vfspk3/vfs.h b/misc/mediasource/netradiant-src/plugins/vfspk3/vfs.h new file mode 100644 index 00000000..3fe10791 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/vfspk3/vfs.h @@ -0,0 +1,39 @@ +/* +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. +*/ + +#if !defined(INCLUDED_VFS_H) +#define INCLUDED_VFS_H + +void FileSystem_Init(); +void FileSystem_Shutdown(); +class VirtualFileSystem; +VirtualFileSystem& GetFileSystem(); + +#endif diff --git a/misc/mediasource/netradiant-src/plugins/vfspk3/vfspk3.cpp b/misc/mediasource/netradiant-src/plugins/vfspk3/vfspk3.cpp new file mode 100644 index 00000000..e7fca372 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/vfspk3/vfspk3.cpp @@ -0,0 +1,85 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "vfspk3.h" + +#include "qerplugin.h" +#include "iarchive.h" +#include "ifilesystem.h" + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/modulesmap.h" + +#include "vfs.h" + +class FileSystemDependencies : public GlobalRadiantModuleRef +{ + ArchiveModulesRef m_archive_modules; +public: + FileSystemDependencies() : + m_archive_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("archivetypes")) + { + } + ArchiveModules& getArchiveModules() + { + return m_archive_modules.get(); + } +}; + +class FileSystemQ3API +{ + VirtualFileSystem* m_filesystemq3; +public: + typedef VirtualFileSystem Type; + STRING_CONSTANT(Name, "*"); + + FileSystemQ3API() + { + FileSystem_Init(); + m_filesystemq3 = &GetFileSystem(); + } + ~FileSystemQ3API() + { + FileSystem_Shutdown(); + } + VirtualFileSystem* getTable() + { + return m_filesystemq3; + } +}; + +typedef SingletonModule FileSystemQ3Module; + +FileSystemQ3Module g_FileSystemQ3Module; + +ArchiveModules& FileSystemQ3API_getArchiveModules() +{ + return g_FileSystemQ3Module.getDependencies().getArchiveModules(); +} + + + +extern "C" void RADIANT_DLLEXPORT Radiant_RegisterModules(ModuleServer& server) +{ + initialiseModule(server); + + g_FileSystemQ3Module.selfRegister(); +} diff --git a/misc/mediasource/netradiant-src/plugins/vfspk3/vfspk3.h b/misc/mediasource/netradiant-src/plugins/vfspk3/vfspk3.h new file mode 100644 index 00000000..8710fd13 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/vfspk3/vfspk3.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_VFSPK3_H) +#define INCLUDED_VFSPK3_H + +#endif diff --git a/misc/mediasource/netradiant-src/plugins/vfspk3/vfsq3.def b/misc/mediasource/netradiant-src/plugins/vfspk3/vfsq3.def new file mode 100644 index 00000000..885ffeb9 --- /dev/null +++ b/misc/mediasource/netradiant-src/plugins/vfspk3/vfsq3.def @@ -0,0 +1,7 @@ +; vfsq3.def : Declares the module parameters for the DLL. + +LIBRARY "VFSQ3" + +EXPORTS + ; Explicit exports can go here + Radiant_RegisterModules @1 diff --git a/misc/mediasource/netradiant-src/radiant/autosave.cpp b/misc/mediasource/netradiant-src/radiant/autosave.cpp new file mode 100644 index 00000000..febe95af --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/autosave.cpp @@ -0,0 +1,224 @@ +/* +Copyright (C) 1999-2006 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 "autosave.h" + +#include "os/file.h" +#include "os/path.h" +#include "cmdlib.h" +#include "stream/stringstream.h" +#include "gtkutil/messagebox.h" +#include "scenelib.h" +#include "mapfile.h" + +#include "map.h" +#include "mainframe.h" +#include "qe3.h" +#include "preferences.h" + + +#if defined(WIN32) +#define PATH_MAX 260 +#endif + + +bool DoesFileExist(const char* name, std::size_t& size) +{ + if(file_exists(name)) + { + size += file_size(name); + return true; + } + return false; +} + +void Map_Snapshot() +{ + // we need to do the following + // 1. make sure the snapshot directory exists (create it if it doesn't) + // 2. find out what the lastest save is based on number + // 3. inc that and save the map + const char* path = Map_Name(g_map); + const char* name = path_get_filename_start(path); + + StringOutputStream snapshotsDir(256); + snapshotsDir << StringRange(path, name) << "snapshots"; + + if(file_exists(snapshotsDir.c_str()) || Q_mkdir(snapshotsDir.c_str())) + { + std::size_t lSize = 0; + StringOutputStream strNewPath(256); + strNewPath << snapshotsDir.c_str() << '/' << name; + + StringOutputStream snapshotFilename(256); + + for(int nCount = 0; ; ++nCount) + { + // The original map's filename is "/." + // The snapshot's filename will be "/snapshots/.." + const char* end = path_get_filename_base_end(strNewPath.c_str()); + snapshotFilename << StringRange(strNewPath.c_str(), end) << '.' << nCount << end; + + if(!DoesFileExist(snapshotFilename.c_str(), lSize)) + { + break; + } + + snapshotFilename.clear(); + } + + // save in the next available slot + Map_SaveFile(snapshotFilename.c_str()); + + if (lSize > 50 * 1024 * 1024) // total size of saves > 50 mb + { + globalOutputStream() << "The snapshot files in " << snapshotsDir.c_str() << " total more than 50 megabytes. You might consider cleaning up."; + } + } + else + { + StringOutputStream strMsg(256); + strMsg << "Snapshot save failed.. unabled to create directory\n" << snapshotsDir.c_str(); + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), strMsg.c_str()); + } +} +/* +=============== +QE_CheckAutoSave + +If five minutes have passed since making a change +and the map hasn't been saved, save it out. +=============== +*/ + +bool g_AutoSave_Enabled = true; +int m_AutoSave_Frequency = 5; +bool g_SnapShots_Enabled = false; + +namespace +{ + time_t s_start = 0; + std::size_t s_changes = 0; +} + +void AutoSave_clear() +{ + s_changes = 0; +} + +scene::Node& Map_Node() +{ + return GlobalSceneGraph().root(); +} + +void QE_CheckAutoSave( void ) +{ + if(!Map_Valid(g_map) || !ScreenUpdates_Enabled()) + { + return; + } + + time_t now; + time(&now); + + if(s_start == 0 || s_changes == Node_getMapFile(Map_Node())->changes()) + { + s_start = now; + } + + if((now - s_start) > (60 * m_AutoSave_Frequency)) + { + s_start = now; + s_changes = Node_getMapFile(Map_Node())->changes(); + + if (g_AutoSave_Enabled) + { + const char* strMsg = g_SnapShots_Enabled ? "Autosaving snapshot..." : "Autosaving..."; + globalOutputStream() << strMsg << "\n"; + //Sys_Status(strMsg); + + // only snapshot if not working on a default map + if (g_SnapShots_Enabled && !Map_Unnamed(g_map)) + { + Map_Snapshot(); + } + else + { + if(Map_Unnamed(g_map)) + { + StringOutputStream autosave(256); + autosave << g_qeglobals.m_userGamePath.c_str() << "maps/"; + Q_mkdir(autosave.c_str()); + autosave << "autosave.map"; + Map_SaveFile(autosave.c_str()); + } + else + { + const char* name = Map_Name(g_map); + const char* extension = path_get_filename_base_end(name); + StringOutputStream autosave(256); + autosave << StringRange(name, extension) << ".autosave" << extension; + Map_SaveFile(autosave.c_str()); + } + } + } + else + { + globalOutputStream() << "Autosave skipped...\n"; + //Sys_Status ("Autosave skipped..."); + } + } +} + +void Autosave_constructPreferences(PreferencesPage& page) +{ + GtkWidget* autosave_enabled = page.appendCheckBox("Autosave", "Enable Autosave", g_AutoSave_Enabled); + GtkWidget* autosave_frequency = page.appendSpinner("Autosave Frequency (minutes)", m_AutoSave_Frequency, 1, 1, 60); + Widget_connectToggleDependency(autosave_frequency, autosave_enabled); + page.appendCheckBox("", "Save Snapshots", g_SnapShots_Enabled); +} +void Autosave_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Autosave", "Autosave Preferences")); + Autosave_constructPreferences(page); +} +void Autosave_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + + +#include "preferencesystem.h" +#include "stringio.h" + +void Autosave_Construct() +{ + GlobalPreferenceSystem().registerPreference("Autosave", BoolImportStringCaller(g_AutoSave_Enabled), BoolExportStringCaller(g_AutoSave_Enabled)); + GlobalPreferenceSystem().registerPreference("AutosaveMinutes", IntImportStringCaller(m_AutoSave_Frequency), IntExportStringCaller(m_AutoSave_Frequency)); + GlobalPreferenceSystem().registerPreference("Snapshots", BoolImportStringCaller(g_SnapShots_Enabled), BoolExportStringCaller(g_SnapShots_Enabled)); + + Autosave_registerPreferencesPage(); +} + +void Autosave_Destroy() +{ +} + diff --git a/misc/mediasource/netradiant-src/radiant/autosave.h b/misc/mediasource/netradiant-src/radiant/autosave.h new file mode 100644 index 00000000..730ef2e1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/autosave.h @@ -0,0 +1,35 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_AUTOSAVE_H) +#define INCLUDED_AUTOSAVE_H + +extern bool g_SnapShots_Enabled; + +void AutoSave_clear(); +void QE_CheckAutoSave( void ); +void Map_Snapshot(); + +void Autosave_Construct(); +void Autosave_Destroy(); + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brush.cpp b/misc/mediasource/netradiant-src/radiant/brush.cpp new file mode 100644 index 00000000..2593ac55 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brush.cpp @@ -0,0 +1,419 @@ +/* +Copyright (C) 1999-2006 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 "brush.h" +#include "signal/signal.h" + +Signal0 g_brushTextureChangedCallbacks; + +void Brush_addTextureChangedCallback(const SignalHandler& handler) +{ + g_brushTextureChangedCallbacks.connectLast(handler); +} + +void Brush_textureChanged() +{ + g_brushTextureChangedCallbacks(); +} + +QuantiseFunc Face::m_quantise; +EBrushType Face::m_type; +EBrushType FacePlane::m_type; +bool g_brush_texturelock_enabled = true; + +EBrushType Brush::m_type; +double Brush::m_maxWorldCoord = 0; +Shader* Brush::m_state_point; +Shader* BrushClipPlane::m_state = 0; +Shader* BrushInstance::m_state_selpoint; +Counter* BrushInstance::m_counter = 0; + +FaceInstanceSet g_SelectedFaceInstances; + + +struct SListNode +{ + SListNode* m_next; +}; + +class ProximalVertex +{ +public: + const SListNode* m_vertices; + + ProximalVertex(const SListNode* next) + : m_vertices(next) + { + } + + bool operator<(const ProximalVertex& other) const + { + if(!(operator==(other))) + { + return m_vertices < other.m_vertices; + } + return false; + } + bool operator==(const ProximalVertex& other) const + { + const SListNode* v = m_vertices; + std::size_t DEBUG_LOOP = 0; + do + { + if(v == other.m_vertices) + return true; + v = v->m_next; + //ASSERT_MESSAGE(DEBUG_LOOP < c_brush_maxFaces, "infinite loop"); + if(!(DEBUG_LOOP < c_brush_maxFaces)) + { + break; + } + ++DEBUG_LOOP; + } + while(v != m_vertices); + return false; + } +}; + +typedef Array ProximalVertexArray; +std::size_t ProximalVertexArray_index(const ProximalVertexArray& array, const ProximalVertex& vertex) +{ + return vertex.m_vertices - array.data(); +} + + + +inline bool Brush_isBounded(const Brush& brush) +{ + for(Brush::const_iterator i = brush.begin(); i != brush.end(); ++i) + { + if(!(*i)->is_bounded()) + { + return false; + } + } + return true; +} + +void Brush::buildBRep() +{ + bool degenerate = buildWindings(); + + std::size_t faces_size = 0; + std::size_t faceVerticesCount = 0; + for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + if((*i)->contributes()) + { + ++faces_size; + } + faceVerticesCount += (*i)->getWinding().numpoints; + } + + if(degenerate || faces_size < 4 || faceVerticesCount != (faceVerticesCount>>1)<<1) // sum of vertices for each face of a valid polyhedron is always even + { + m_uniqueVertexPoints.resize(0); + + vertex_clear(); + edge_clear(); + + m_edge_indices.resize(0); + m_edge_faces.resize(0); + + m_faceCentroidPoints.resize(0); + m_uniqueEdgePoints.resize(0); + m_uniqueVertexPoints.resize(0); + + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->getWinding().resize(0); + } + } + else + { + { + typedef std::vector FaceVertices; + FaceVertices faceVertices; + faceVertices.reserve(faceVerticesCount); + + { + for(std::size_t i = 0; i != m_faces.size(); ++i) + { + for(std::size_t j = 0; j < m_faces[i]->getWinding().numpoints; ++j) + { + faceVertices.push_back(FaceVertexId(i, j)); + } + } + } + + IndexBuffer uniqueEdgeIndices; + typedef VertexBuffer UniqueEdges; + UniqueEdges uniqueEdges; + + uniqueEdgeIndices.reserve(faceVertices.size()); + uniqueEdges.reserve(faceVertices.size()); + + { + ProximalVertexArray edgePairs; + edgePairs.resize(faceVertices.size()); + + { + for(std::size_t i=0; i inserter(uniqueEdges); + for(ProximalVertexArray::iterator i = edgePairs.begin(); i != edgePairs.end(); ++i) + { + uniqueEdgeIndices.insert(inserter.insert(ProximalVertex(&(*i)))); + } + } + + { + edge_clear(); + m_select_edges.reserve(uniqueEdges.size()); + for(UniqueEdges::iterator i = uniqueEdges.begin(); i != uniqueEdges.end(); ++i) + { + edge_push_back(faceVertices[ProximalVertexArray_index(edgePairs, *i)]); + } + } + + { + m_edge_faces.resize(uniqueEdges.size()); + for(std::size_t i=0; igetWinding()[faceVertex.getVertex()].adjacent); + } + } + + { + m_uniqueEdgePoints.resize(uniqueEdges.size()); + for(std::size_t i=0; igetWinding(); + Vector3 edge = vector3_mid(w[faceVertex.getVertex()].vertex, w[Winding_next(w, faceVertex.getVertex())].vertex); + m_uniqueEdgePoints[i] = pointvertex_for_windingpoint(edge, colour_vertex); + } + } + + } + + + IndexBuffer uniqueVertexIndices; + typedef VertexBuffer UniqueVertices; + UniqueVertices uniqueVertices; + + uniqueVertexIndices.reserve(faceVertices.size()); + uniqueVertices.reserve(faceVertices.size()); + + { + ProximalVertexArray vertexRings; + vertexRings.resize(faceVertices.size()); + + { + for(std::size_t i=0; i inserter(uniqueVertices); + for(ProximalVertexArray::iterator i = vertexRings.begin(); i != vertexRings.end(); ++i) + { + uniqueVertexIndices.insert(inserter.insert(ProximalVertex(&(*i)))); + } + } + + { + vertex_clear(); + m_select_vertices.reserve(uniqueVertices.size()); + for(UniqueVertices::iterator i = uniqueVertices.begin(); i != uniqueVertices.end(); ++i) + { + vertex_push_back(faceVertices[ProximalVertexArray_index(vertexRings, (*i))]); + } + } + + { + m_uniqueVertexPoints.resize(uniqueVertices.size()); + for(std::size_t i=0; igetWinding(); + m_uniqueVertexPoints[i] = pointvertex_for_windingpoint(winding[faceVertex.getVertex()].vertex, colour_vertex); + } + } + } + + if((uniqueVertices.size() + faces_size) - uniqueEdges.size() != 2) + { + globalErrorStream() << "Final B-Rep: inconsistent vertex count\n"; + } + +#if BRUSH_CONNECTIVITY_DEBUG + if((uniqueVertices.size() + faces_size) - uniqueEdges.size() != 2) + { + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + std::size_t faceIndex = std::distance(m_faces.begin(), i); + + if(!(*i)->contributes()) + { + globalOutputStream() << "face: " << Unsigned(faceIndex) << " does not contribute\n"; + } + + Winding_printConnectivity((*i)->getWinding()); + } + } +#endif + + // edge-index list for wireframe rendering + { + m_edge_indices.resize(uniqueEdgeIndices.size()); + + for(std::size_t i=0, count=0; igetWinding(); + for(std::size_t j = 0; j < winding.numpoints; ++j) + { + const RenderIndex edge_index = uniqueEdgeIndices[count+j]; + + m_edge_indices[edge_index].first = uniqueVertexIndices[count + j]; + m_edge_indices[edge_index].second = uniqueVertexIndices[count + Winding_next(winding, j)]; + } + count += winding.numpoints; + } + } + } + + { + m_faceCentroidPoints.resize(m_faces.size()); + for(std::size_t i=0; iconstruct_centroid(); + m_faceCentroidPoints[i] = pointvertex_for_windingpoint(m_faces[i]->centroid(), colour_vertex); + } + } + } +} + + +class FaceFilterWrapper : public Filter +{ + FaceFilter& m_filter; + bool m_active; + bool m_invert; +public: + FaceFilterWrapper(FaceFilter& filter, bool invert) : + m_filter(filter), + m_invert(invert) + { + } + void setActive(bool active) + { + m_active = active; + } + bool active() + { + return m_active; + } + bool filter(const Face& face) + { + return m_invert ^ m_filter.filter(face); + } +}; + + +typedef std::list FaceFilters; +FaceFilters g_faceFilters; + +void add_face_filter(FaceFilter& filter, int mask, bool invert) +{ + g_faceFilters.push_back(FaceFilterWrapper(filter, invert)); + GlobalFilterSystem().addFilter(g_faceFilters.back(), mask); +} + +bool face_filtered(Face& face) +{ + for(FaceFilters::iterator i = g_faceFilters.begin(); i != g_faceFilters.end(); ++i) + { + if((*i).active() && (*i).filter(face)) + { + return true; + } + } + return false; +} + + +class BrushFilterWrapper : public Filter +{ + bool m_active; + bool m_invert; + BrushFilter& m_filter; +public: + BrushFilterWrapper(BrushFilter& filter, bool invert) : m_invert(invert), m_filter(filter) + { + } + void setActive(bool active) + { + m_active = active; + } + bool active() + { + return m_active; + } + bool filter(const Brush& brush) + { + return m_invert ^ m_filter.filter(brush); + } +}; + + +typedef std::list BrushFilters; +BrushFilters g_brushFilters; + +void add_brush_filter(BrushFilter& filter, int mask, bool invert) +{ + g_brushFilters.push_back(BrushFilterWrapper(filter, invert)); + GlobalFilterSystem().addFilter(g_brushFilters.back(), mask); +} + +bool brush_filtered(Brush& brush) +{ + for(BrushFilters::iterator i = g_brushFilters.begin(); i != g_brushFilters.end(); ++i) + { + if((*i).active() && (*i).filter(brush)) + { + return true; + } + } + return false; +} + + diff --git a/misc/mediasource/netradiant-src/radiant/brush.h b/misc/mediasource/netradiant-src/radiant/brush.h new file mode 100644 index 00000000..158077fd --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brush.h @@ -0,0 +1,4230 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_BRUSH_H) +#define INCLUDED_BRUSH_H + +/// \file +/// \brief The brush primitive. +/// +/// A collection of planes that define a convex polyhedron. +/// The Boundary-Representation of this primitive is a manifold polygonal mesh. +/// Each face polygon is represented by a list of vertices in a \c Winding. +/// Each vertex is associated with another face that is adjacent to the edge +/// formed by itself and the next vertex in the winding. This information can +/// be used to find edge-pairs and vertex-rings. + + +#include "debugging/debugging.h" + +#include "itexdef.h" +#include "iundo.h" +#include "iselection.h" +#include "irender.h" +#include "imap.h" +#include "ibrush.h" +#include "igl.h" +#include "ifilter.h" +#include "nameable.h" +#include "moduleobserver.h" + +#include + +#include "cullable.h" +#include "renderable.h" +#include "selectable.h" +#include "editable.h" +#include "mapfile.h" + +#include "math/frustum.h" +#include "selectionlib.h" +#include "render.h" +#include "texturelib.h" +#include "container/container.h" +#include "generic/bitfield.h" +#include "signal/signalfwd.h" + +#include "winding.h" +#include "brush_primit.h" + +const unsigned int BRUSH_DETAIL_FLAG = 27; +const unsigned int BRUSH_DETAIL_MASK = (1 << BRUSH_DETAIL_FLAG); + +enum EBrushType +{ + eBrushTypeQuake, + eBrushTypeQuake2, + eBrushTypeQuake3, + eBrushTypeQuake3BP, + eBrushTypeDoom3, + eBrushTypeQuake4, + eBrushTypeHalfLife, +}; + + +#define BRUSH_CONNECTIVITY_DEBUG 0 +#define BRUSH_DEGENERATE_DEBUG 0 + +template +inline TextOuputStreamType& ostream_write(TextOuputStreamType& ostream, const Matrix4& m) +{ + return ostream << "(" << m[0] << " " << m[1] << " " << m[2] << " " << m[3] << ", " + << m[4] << " " << m[5] << " " << m[6] << " " << m[7] << ", " + << m[8] << " " << m[9] << " " << m[10] << " " << m[11] << ", " + << m[12] << " " << m[13] << " " << m[14] << " " << m[15] << ")"; +} + +inline void print_vector3(const Vector3& v) +{ + globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n"; +} + +inline void print_3x3(const Matrix4& m) +{ + globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) " + << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) " + << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n"; +} + + + +inline bool texdef_sane(const texdef_t& texdef) +{ + return fabs(texdef.shift[0]) < (1 << 16) + && fabs(texdef.shift[1]) < (1 << 16); +} + +inline void Winding_DrawWireframe(const Winding& winding) +{ + glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex); + glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints)); +} + +inline void Winding_Draw(const Winding& winding, const Vector3& normal, RenderStateFlags state) +{ + glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex); + + if((state & RENDER_BUMP) != 0) + { + Vector3 normals[c_brush_maxFaces]; + typedef Vector3* Vector3Iter; + for(Vector3Iter i = normals, end = normals + winding.numpoints; i != end; ++i) + { + *i = normal; + } + if(GlobalShaderCache().useShaderLanguage()) + { + glNormalPointer(GL_FLOAT, sizeof(Vector3), normals); + glVertexAttribPointerARB(c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord); + glVertexAttribPointerARB(c_attr_Tangent, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent); + glVertexAttribPointerARB(c_attr_Binormal, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent); + } + else + { + glVertexAttribPointerARB(11, 3, GL_FLOAT, 0, sizeof(Vector3), normals); + glVertexAttribPointerARB(8, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord); + glVertexAttribPointerARB(9, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent); + glVertexAttribPointerARB(10, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent); + } + } + else + { + if (state & RENDER_LIGHTING) + { + Vector3 normals[c_brush_maxFaces]; + typedef Vector3* Vector3Iter; + for(Vector3Iter i = normals, last = normals + winding.numpoints; i != last; ++i) + { + *i = normal; + } + glNormalPointer(GL_FLOAT, sizeof(Vector3), normals); + } + + if (state & RENDER_TEXTURE) + { + glTexCoordPointer(2, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->texcoord); + } + } +#if 0 + if (state & RENDER_FILL) + { + glDrawArrays(GL_TRIANGLE_FAN, 0, GLsizei(winding.numpoints)); + } + else + { + glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints)); + } +#else + glDrawArrays(GL_POLYGON, 0, GLsizei(winding.numpoints)); +#endif + +#if 0 + const Winding& winding = winding; + + if(state & RENDER_FILL) + { + glBegin(GL_POLYGON); + } + else + { + glBegin(GL_LINE_LOOP); + } + + if (state & RENDER_LIGHTING) + glNormal3fv(normal); + + for(int i = 0; i < winding.numpoints; ++i) + { + if (state & RENDER_TEXTURE) + glTexCoord2fv(&winding.points[i][3]); + glVertex3fv(winding.points[i]); + } + glEnd(); +#endif +} + + +#include "shaderlib.h" + +typedef DoubleVector3 PlanePoints[3]; + +inline bool planepts_equal(const PlanePoints planepts, const PlanePoints other) +{ + return planepts[0] == other[0] && planepts[1] == other[1] && planepts[2] == other[2]; +} + +inline void planepts_assign(PlanePoints planepts, const PlanePoints other) +{ + planepts[0] = other[0]; + planepts[1] = other[1]; + planepts[2] = other[2]; +} + +inline void planepts_quantise(PlanePoints planepts, double snap) +{ + vector3_snap(planepts[0], snap); + vector3_snap(planepts[1], snap); + vector3_snap(planepts[2], snap); +} + +inline float vector3_max_component(const Vector3& vec3) +{ + return std::max(fabsf(vec3[0]), std::max(fabsf(vec3[1]), fabsf(vec3[2]))); +} + +inline void edge_snap(Vector3& edge, double snap) +{ + float scale = static_cast(ceil(fabs(snap / vector3_max_component(edge)))); + if(scale > 0.0f) + { + vector3_scale(edge, scale); + } + vector3_snap(edge, snap); +} + +inline void planepts_snap(PlanePoints planepts, double snap) +{ + Vector3 edge01(vector3_subtracted(planepts[1], planepts[0])); + Vector3 edge12(vector3_subtracted(planepts[2], planepts[1])); + Vector3 edge20(vector3_subtracted(planepts[0], planepts[2])); + + double length_squared_01 = vector3_dot(edge01, edge01); + double length_squared_12 = vector3_dot(edge12, edge12); + double length_squared_20 = vector3_dot(edge20, edge20); + + vector3_snap(planepts[0], snap); + + if(length_squared_01 < length_squared_12) + { + if(length_squared_12 < length_squared_20) + { + edge_snap(edge01, snap); + edge_snap(edge12, snap); + planepts[1] = vector3_added(planepts[0], edge01); + planepts[2] = vector3_added(planepts[1], edge12); + } + else + { + edge_snap(edge20, snap); + edge_snap(edge01, snap); + planepts[1] = vector3_added(planepts[0], edge20); + planepts[2] = vector3_added(planepts[1], edge01); + } + } + else + { + if(length_squared_01 < length_squared_20) + { + edge_snap(edge01, snap); + edge_snap(edge12, snap); + planepts[1] = vector3_added(planepts[0], edge01); + planepts[2] = vector3_added(planepts[1], edge12); + } + else + { + edge_snap(edge12, snap); + edge_snap(edge20, snap); + planepts[1] = vector3_added(planepts[0], edge12); + planepts[2] = vector3_added(planepts[1], edge20); + } + } +} + +inline PointVertex pointvertex_for_planept(const DoubleVector3& point, const Colour4b& colour) +{ + return PointVertex( + Vertex3f( + static_cast(point.x()), + static_cast(point.y()), + static_cast(point.z()) + ), + colour + ); +} + +inline PointVertex pointvertex_for_windingpoint(const Vector3& point, const Colour4b& colour) +{ + return PointVertex( + vertex3f_for_vector3(point), + colour + ); +} + +inline bool check_plane_is_integer(const PlanePoints& planePoints) +{ + return !float_is_integer(planePoints[0][0]) + || !float_is_integer(planePoints[0][1]) + || !float_is_integer(planePoints[0][2]) + || !float_is_integer(planePoints[1][0]) + || !float_is_integer(planePoints[1][1]) + || !float_is_integer(planePoints[1][2]) + || !float_is_integer(planePoints[2][0]) + || !float_is_integer(planePoints[2][1]) + || !float_is_integer(planePoints[2][2]); +} + +inline void brush_check_shader(const char* name) +{ + if(!shader_valid(name)) + { + globalErrorStream() << "brush face has invalid texture name: '" << name << "'\n"; + } +} + +class FaceShaderObserver +{ +public: + virtual void realiseShader() = 0; + virtual void unrealiseShader() = 0; +}; + +class FaceShaderObserverRealise +{ +public: + void operator()(FaceShaderObserver& observer) const + { + observer.realiseShader(); + } +}; + +class FaceShaderObserverUnrealise +{ +public: + void operator()(FaceShaderObserver& observer) const + { + observer.unrealiseShader(); + } +}; + +typedef ReferencePair FaceShaderObserverPair; + + +class ContentsFlagsValue +{ +public: + ContentsFlagsValue() + { + } + ContentsFlagsValue(int surfaceFlags, int contentFlags, int value, bool specified) : + m_surfaceFlags(surfaceFlags), + m_contentFlags(contentFlags), + m_value(value), + m_specified(specified) + { + } + int m_surfaceFlags; + int m_contentFlags; + int m_value; + bool m_specified; +}; + +inline void ContentsFlagsValue_assignMasked(ContentsFlagsValue& flags, const ContentsFlagsValue& other) +{ + bool detail = bitfield_enabled(flags.m_contentFlags, BRUSH_DETAIL_MASK); + flags = other; + if(detail) + { + flags.m_contentFlags = bitfield_enable(flags.m_contentFlags, BRUSH_DETAIL_MASK); + } + else + { + flags.m_contentFlags = bitfield_disable(flags.m_contentFlags, BRUSH_DETAIL_MASK); + } +} + + +class FaceShader : public ModuleObserver +{ +public: + class SavedState + { + public: + CopiedString m_shader; + ContentsFlagsValue m_flags; + + SavedState(const FaceShader& faceShader) + { + m_shader = faceShader.getShader(); + m_flags = faceShader.m_flags; + } + + void exportState(FaceShader& faceShader) const + { + faceShader.setShader(m_shader.c_str()); + faceShader.setFlags(m_flags); + } + }; + + CopiedString m_shader; + Shader* m_state; + ContentsFlagsValue m_flags; + FaceShaderObserverPair m_observers; + bool m_instanced; + bool m_realised; + + FaceShader(const char* shader, const ContentsFlagsValue& flags = ContentsFlagsValue(0, 0, 0, false)) : + m_shader(shader), + m_state(0), + m_flags(flags), + m_instanced(false), + m_realised(false) + { + captureShader(); + } + ~FaceShader() + { + releaseShader(); + } + // copy-construction not supported + FaceShader(const FaceShader& other); + + void instanceAttach() + { + m_instanced = true; + m_state->incrementUsed(); + } + void instanceDetach() + { + m_state->decrementUsed(); + m_instanced = false; + } + + void captureShader() + { + ASSERT_MESSAGE(m_state == 0, "shader cannot be captured"); + brush_check_shader(m_shader.c_str()); + m_state = GlobalShaderCache().capture(m_shader.c_str()); + m_state->attach(*this); + } + void releaseShader() + { + ASSERT_MESSAGE(m_state != 0, "shader cannot be released"); + m_state->detach(*this); + GlobalShaderCache().release(m_shader.c_str()); + m_state = 0; + } + + void realise() + { + ASSERT_MESSAGE(!m_realised, "FaceTexdef::realise: already realised"); + m_realised = true; + m_observers.forEach(FaceShaderObserverRealise()); + } + void unrealise() + { + ASSERT_MESSAGE(m_realised, "FaceTexdef::unrealise: already unrealised"); + m_observers.forEach(FaceShaderObserverUnrealise()); + m_realised = false; + } + + void attach(FaceShaderObserver& observer) + { + m_observers.attach(observer); + if(m_realised) + { + observer.realiseShader(); + } + } + + void detach(FaceShaderObserver& observer) + { + if(m_realised) + { + observer.unrealiseShader(); + } + m_observers.detach(observer); + } + + const char* getShader() const + { + return m_shader.c_str(); + } + void setShader(const char* name) + { + if(m_instanced) + { + m_state->decrementUsed(); + } + releaseShader(); + m_shader = name; + captureShader(); + if(m_instanced) + { + m_state->incrementUsed(); + } + } + ContentsFlagsValue getFlags() const + { + ASSERT_MESSAGE(m_realised, "FaceShader::getFlags: flags not valid when unrealised"); + if(!m_flags.m_specified) + { + return ContentsFlagsValue( + m_state->getTexture().surfaceFlags, + m_state->getTexture().contentFlags, + m_state->getTexture().value, + true + ); + } + return m_flags; + } + void setFlags(const ContentsFlagsValue& flags) + { + ASSERT_MESSAGE(m_realised, "FaceShader::setFlags: flags not valid when unrealised"); + ContentsFlagsValue_assignMasked(m_flags, flags); + } + + Shader* state() const + { + return m_state; + } + + std::size_t width() const + { + if(m_realised) + { + return m_state->getTexture().width; + } + return 1; + } + std::size_t height() const + { + if(m_realised) + { + return m_state->getTexture().height; + } + return 1; + } + unsigned int shaderFlags() const + { + if(m_realised) + { + return m_state->getFlags(); + } + return 0; + } +}; + + + + +class FaceTexdef : public FaceShaderObserver +{ + // not copyable + FaceTexdef(const FaceTexdef& other); + // not assignable + FaceTexdef& operator=(const FaceTexdef& other); +public: + class SavedState + { + public: + TextureProjection m_projection; + + SavedState(const FaceTexdef& faceTexdef) + { + m_projection = faceTexdef.m_projection; + } + + void exportState(FaceTexdef& faceTexdef) const + { + Texdef_Assign(faceTexdef.m_projection, m_projection); + } + }; + + FaceShader& m_shader; + TextureProjection m_projection; + bool m_projectionInitialised; + bool m_scaleApplied; + + FaceTexdef( + FaceShader& shader, + const TextureProjection& projection, + bool projectionInitialised = true + ) : + m_shader(shader), + m_projection(projection), + m_projectionInitialised(projectionInitialised), + m_scaleApplied(false) + { + m_shader.attach(*this); + } + ~FaceTexdef() + { + m_shader.detach(*this); + } + + void addScale() + { + ASSERT_MESSAGE(!m_scaleApplied, "texture scale aready added"); + m_scaleApplied = true; + m_projection.m_brushprimit_texdef.addScale(m_shader.width(), m_shader.height()); + } + void removeScale() + { + ASSERT_MESSAGE(m_scaleApplied, "texture scale aready removed"); + m_scaleApplied = false; + m_projection.m_brushprimit_texdef.removeScale(m_shader.width(), m_shader.height()); + } + + void realiseShader() + { + if(m_projectionInitialised && !m_scaleApplied) + { + addScale(); + } + } + void unrealiseShader() + { + if(m_projectionInitialised && m_scaleApplied) + { + removeScale(); + } + } + + void setTexdef(const TextureProjection& projection) + { + removeScale(); + Texdef_Assign(m_projection, projection); + addScale(); + } + + void shift(float s, float t) + { + ASSERT_MESSAGE(texdef_sane(m_projection.m_texdef), "FaceTexdef::shift: bad texdef"); + removeScale(); + Texdef_Shift(m_projection, s, t); + addScale(); + } + + void scale(float s, float t) + { + removeScale(); + Texdef_Scale(m_projection, s, t); + addScale(); + } + + void rotate(float angle) + { + removeScale(); + Texdef_Rotate(m_projection, angle); + addScale(); + } + + void fit(const Vector3& normal, const Winding& winding, float s_repeat, float t_repeat) + { + Texdef_FitTexture(m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat); + } + + void emitTextureCoordinates(Winding& winding, const Vector3& normal, const Matrix4& localToWorld) + { + Texdef_EmitTextureCoordinates(m_projection, m_shader.width(), m_shader.height(), winding, normal, localToWorld); + } + + void transform(const Plane3& plane, const Matrix4& matrix) + { + removeScale(); + Texdef_transformLocked(m_projection, m_shader.width(), m_shader.height(), plane, matrix); + addScale(); + } + + TextureProjection normalised() const + { + brushprimit_texdef_t tmp(m_projection.m_brushprimit_texdef); + tmp.removeScale(m_shader.width(), m_shader.height()); + return TextureProjection(m_projection.m_texdef, tmp, m_projection.m_basis_s, m_projection.m_basis_t); + } + void setBasis(const Vector3& normal) + { + Matrix4 basis; + Normal_GetTransform(normal, basis); + m_projection.m_basis_s = Vector3(basis.xx(), basis.yx(), basis.zx()); + m_projection.m_basis_t = Vector3(-basis.xy(), -basis.yy(), -basis.zy()); + } +}; + +inline void planepts_print(const PlanePoints& planePoints, TextOutputStream& ostream) +{ + ostream << "( " << planePoints[0][0] << " " << planePoints[0][1] << " " << planePoints[0][2] << " ) " + << "( " << planePoints[1][0] << " " << planePoints[1][1] << " " << planePoints[1][2] << " ) " + << "( " << planePoints[2][0] << " " << planePoints[2][1] << " " << planePoints[2][2] << " )"; +} + + +inline Plane3 Plane3_applyTranslation(const Plane3& plane, const Vector3& translation) +{ + Plane3 tmp(plane3_translated(Plane3(plane.normal(), -plane.dist()), translation)); + return Plane3(tmp.normal(), -tmp.dist()); +} + +inline Plane3 Plane3_applyTransform(const Plane3& plane, const Matrix4& matrix) +{ + Plane3 tmp(plane3_transformed(Plane3(plane.normal(), -plane.dist()), matrix)); + return Plane3(tmp.normal(), -tmp.dist()); +} + +class FacePlane +{ + PlanePoints m_planepts; + Plane3 m_planeCached; + Plane3 m_plane; +public: + Vector3 m_funcStaticOrigin; + + static EBrushType m_type; + + static bool isDoom3Plane() + { + return FacePlane::m_type == eBrushTypeDoom3 || FacePlane::m_type == eBrushTypeQuake4; + } + + class SavedState + { + public: + PlanePoints m_planepts; + Plane3 m_plane; + + SavedState(const FacePlane& facePlane) + { + if(facePlane.isDoom3Plane()) + { + m_plane = facePlane.m_plane; + } + else + { + planepts_assign(m_planepts, facePlane.planePoints()); + } + } + + void exportState(FacePlane& facePlane) const + { + if(facePlane.isDoom3Plane()) + { + facePlane.m_plane = m_plane; + facePlane.updateTranslated(); + } + else + { + planepts_assign(facePlane.planePoints(), m_planepts); + facePlane.MakePlane(); + } + } + }; + + FacePlane() : m_funcStaticOrigin(0, 0, 0) + { + } + FacePlane(const FacePlane& other) : m_funcStaticOrigin(0, 0, 0) + { + if(!isDoom3Plane()) + { + planepts_assign(m_planepts, other.m_planepts); + MakePlane(); + } + else + { + m_plane = other.m_plane; + updateTranslated(); + } + } + + void MakePlane() + { + if(!isDoom3Plane()) + { +#if 0 + if(check_plane_is_integer(m_planepts)) + { + globalErrorStream() << "non-integer planepts: "; + planepts_print(m_planepts, globalErrorStream()); + globalErrorStream() << "\n"; + } +#endif + m_planeCached = plane3_for_points(m_planepts); + } + } + + void reverse() + { + if(!isDoom3Plane()) + { + vector3_swap(m_planepts[0], m_planepts[2]); + MakePlane(); + } + else + { + m_planeCached = plane3_flipped(m_plane); + updateSource(); + } + } + void transform(const Matrix4& matrix, bool mirror) + { + if(!isDoom3Plane()) + { + +#if 0 + bool off = check_plane_is_integer(planePoints()); +#endif + + matrix4_transform_point(matrix, m_planepts[0]); + matrix4_transform_point(matrix, m_planepts[1]); + matrix4_transform_point(matrix, m_planepts[2]); + + if(mirror) + { + reverse(); + } + +#if 0 + if(check_plane_is_integer(planePoints())) + { + if(!off) + { + globalErrorStream() << "caused by transform\n"; + } + } +#endif + MakePlane(); + } + else + { + m_planeCached = Plane3_applyTransform(m_planeCached, matrix); + updateSource(); + } + } + void offset(float offset) + { + if(!isDoom3Plane()) + { + Vector3 move(vector3_scaled(m_planeCached.normal(), -offset)); + + vector3_subtract(m_planepts[0], move); + vector3_subtract(m_planepts[1], move); + vector3_subtract(m_planepts[2], move); + + MakePlane(); + } + else + { + m_planeCached.d += offset; + updateSource(); + } + } + + void updateTranslated() + { + m_planeCached = Plane3_applyTranslation(m_plane, m_funcStaticOrigin); + } + void updateSource() + { + m_plane = Plane3_applyTranslation(m_planeCached, vector3_negated(m_funcStaticOrigin)); + } + + + PlanePoints& planePoints() + { + return m_planepts; + } + const PlanePoints& planePoints() const + { + return m_planepts; + } + const Plane3& plane3() const + { + return m_planeCached; + } + void setDoom3Plane(const Plane3& plane) + { + m_plane = plane; + updateTranslated(); + } + const Plane3& getDoom3Plane() const + { + return m_plane; + } + + void copy(const FacePlane& other) + { + if(!isDoom3Plane()) + { + planepts_assign(m_planepts, other.m_planepts); + MakePlane(); + } + else + { + m_planeCached = other.m_plane; + updateSource(); + } + } + void copy(const Vector3& p0, const Vector3& p1, const Vector3& p2) + { + if(!isDoom3Plane()) + { + m_planepts[0] = p0; + m_planepts[1] = p1; + m_planepts[2] = p2; + MakePlane(); + } + else + { + m_planeCached = plane3_for_points(p2, p1, p0); + updateSource(); + } + } +}; + +inline void Winding_testSelect(Winding& winding, SelectionTest& test, SelectionIntersection& best) +{ + test.TestPolygon(VertexPointer(reinterpret_cast(&winding.points.data()->vertex), sizeof(WindingVertex)), winding.numpoints, best); +} + +const double GRID_MIN = 0.125; + +inline double quantiseInteger(double f) +{ + return float_to_integer(f); +} + +inline double quantiseFloating(double f) +{ + return float_snapped(f, 1.f / (1 << 16)); +} + +typedef double (*QuantiseFunc)(double f); + +class Face; + +class FaceFilter +{ +public: + virtual bool filter(const Face& face) const = 0; +}; + +bool face_filtered(Face& face); +void add_face_filter(FaceFilter& filter, int mask, bool invert = false); + +void Brush_addTextureChangedCallback(const SignalHandler& callback); +void Brush_textureChanged(); + + +extern bool g_brush_texturelock_enabled; + +class FaceObserver +{ +public: + virtual void planeChanged() = 0; + virtual void connectivityChanged() = 0; + virtual void shaderChanged() = 0; + virtual void evaluateTransform() = 0; +}; + +class Face : +public OpenGLRenderable, +public Filterable, +public Undoable, +public FaceShaderObserver +{ + std::size_t m_refcount; + + class SavedState : public UndoMemento + { + public: + FacePlane::SavedState m_planeState; + FaceTexdef::SavedState m_texdefState; + FaceShader::SavedState m_shaderState; + + SavedState(const Face& face) : m_planeState(face.getPlane()), m_texdefState(face.getTexdef()), m_shaderState(face.getShader()) + { + } + + void exportState(Face& face) const + { + m_planeState.exportState(face.getPlane()); + m_shaderState.exportState(face.getShader()); + m_texdefState.exportState(face.getTexdef()); + } + + void release() + { + delete this; + } + }; + +public: + static QuantiseFunc m_quantise; + static EBrushType m_type; + + PlanePoints m_move_planepts; + PlanePoints m_move_planeptsTransformed; +private: + FacePlane m_plane; + FacePlane m_planeTransformed; + FaceShader m_shader; + FaceTexdef m_texdef; + TextureProjection m_texdefTransformed; + + Winding m_winding; + Vector3 m_centroid; + bool m_filtered; + + FaceObserver* m_observer; + UndoObserver* m_undoable_observer; + MapFile* m_map; + + // assignment not supported + Face& operator=(const Face& other); + // copy-construction not supported + Face(const Face& other); + +public: + + Face(FaceObserver* observer) : + m_refcount(0), + m_shader(texdef_name_default()), + m_texdef(m_shader, TextureProjection(), false), + m_filtered(false), + m_observer(observer), + m_undoable_observer(0), + m_map(0) + { + m_shader.attach(*this); + m_plane.copy(Vector3(0, 0, 0), Vector3(64, 0, 0), Vector3(0, 64, 0)); + m_texdef.setBasis(m_plane.plane3().normal()); + planeChanged(); + } + Face( + const Vector3& p0, + const Vector3& p1, + const Vector3& p2, + const char* shader, + const TextureProjection& projection, + FaceObserver* observer + ) : + m_refcount(0), + m_shader(shader), + m_texdef(m_shader, projection), + m_observer(observer), + m_undoable_observer(0), + m_map(0) + { + m_shader.attach(*this); + m_plane.copy(p0, p1, p2); + m_texdef.setBasis(m_plane.plane3().normal()); + planeChanged(); + updateFiltered(); + } + Face(const Face& other, FaceObserver* observer) : + m_refcount(0), + m_shader(other.m_shader.getShader(), other.m_shader.m_flags), + m_texdef(m_shader, other.getTexdef().normalised()), + m_observer(observer), + m_undoable_observer(0), + m_map(0) + { + m_shader.attach(*this); + m_plane.copy(other.m_plane); + planepts_assign(m_move_planepts, other.m_move_planepts); + m_texdef.setBasis(m_plane.plane3().normal()); + planeChanged(); + updateFiltered(); + } + ~Face() + { + m_shader.detach(*this); + } + + void planeChanged() + { + revertTransform(); + m_observer->planeChanged(); + } + + void realiseShader() + { + m_observer->shaderChanged(); + } + void unrealiseShader() + { + } + + void instanceAttach(MapFile* map) + { + m_shader.instanceAttach(); + m_map = map; + m_undoable_observer = GlobalUndoSystem().observer(this); + GlobalFilterSystem().registerFilterable(*this); + } + void instanceDetach(MapFile* map) + { + GlobalFilterSystem().unregisterFilterable(*this); + m_undoable_observer = 0; + GlobalUndoSystem().release(this); + m_map = 0; + m_shader.instanceDetach(); + } + + void render(RenderStateFlags state) const + { + Winding_Draw(m_winding, m_planeTransformed.plane3().normal(), state); + } + + void updateFiltered() + { + m_filtered = face_filtered(*this); + } + bool isFiltered() const + { + return m_filtered; + } + + void undoSave() + { + if(m_map != 0) + { + m_map->changed(); + } + if(m_undoable_observer != 0) + { + m_undoable_observer->save(this); + } + } + + // undoable + UndoMemento* exportState() const + { + return new SavedState(*this); + } + void importState(const UndoMemento* data) + { + undoSave(); + + static_cast(data)->exportState(*this); + + planeChanged(); + m_observer->connectivityChanged(); + texdefChanged(); + m_observer->shaderChanged(); + updateFiltered(); + } + + void IncRef() + { + ++m_refcount; + } + void DecRef() + { + if(--m_refcount == 0) + delete this; + } + + void flipWinding() + { + m_plane.reverse(); + planeChanged(); + } + + bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const + { + return volume.TestPlane(Plane3(plane3().normal(), -plane3().dist()), localToWorld); + } + + void render(Renderer& renderer, const Matrix4& localToWorld) const + { + renderer.SetState(m_shader.state(), Renderer::eFullMaterials); + renderer.addRenderable(*this, localToWorld); + } + + void transform(const Matrix4& matrix, bool mirror) + { + if(g_brush_texturelock_enabled) + Texdef_transformLocked(m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix); + + m_planeTransformed.transform(matrix, mirror); + +#if 0 + ASSERT_MESSAGE(projectionaxis_for_normal(normal) == projectionaxis_for_normal(plane3().normal()), "bleh"); +#endif + m_observer->planeChanged(); + + if(g_brush_texturelock_enabled) + Brush_textureChanged(); + } + + void assign_planepts(const PlanePoints planepts) + { + m_planeTransformed.copy(planepts[0], planepts[1], planepts[2]); + m_observer->planeChanged(); + } + + /// \brief Reverts the transformable state of the brush to identity. + void revertTransform() + { + m_planeTransformed = m_plane; + planepts_assign(m_move_planeptsTransformed, m_move_planepts); + m_texdefTransformed = m_texdef.m_projection; + } + void freezeTransform() + { + undoSave(); + m_plane = m_planeTransformed; + planepts_assign(m_move_planepts, m_move_planeptsTransformed); + m_texdef.m_projection = m_texdefTransformed; + } + + void update_move_planepts_vertex(std::size_t index, PlanePoints planePoints) + { + std::size_t numpoints = getWinding().numpoints; + ASSERT_MESSAGE(index < numpoints, "update_move_planepts_vertex: invalid index"); + + std::size_t opposite = Winding_Opposite(getWinding(), index); + std::size_t adjacent = Winding_wrap(getWinding(), opposite+numpoints-1); + planePoints[0] = getWinding()[opposite].vertex; + planePoints[1] = getWinding()[index].vertex; + planePoints[2] = getWinding()[adjacent].vertex; + // winding points are very inaccurate, so they must be quantised before using them to generate the face-plane + planepts_quantise(planePoints, GRID_MIN); + } + + void snapto(float snap) + { + if(contributes()) + { +#if 0 + ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane before snap to grid"); + planepts_snap(m_plane.planePoints(), snap); + ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane after snap to grid"); +#else + PlanePoints planePoints; + update_move_planepts_vertex(0, planePoints); + vector3_snap(planePoints[0], snap); + vector3_snap(planePoints[1], snap); + vector3_snap(planePoints[2], snap); + assign_planepts(planePoints); + freezeTransform(); +#endif + SceneChangeNotify(); + if(!plane3_valid(m_plane.plane3())) + { + globalErrorStream() << "WARNING: invalid plane after snap to grid\n"; + } + } + } + + void testSelect(SelectionTest& test, SelectionIntersection& best) + { + Winding_testSelect(m_winding, test, best); + } + + void testSelect_centroid(SelectionTest& test, SelectionIntersection& best) + { + test.TestPoint(m_centroid, best); + } + + void shaderChanged() + { + EmitTextureCoordinates(); + Brush_textureChanged(); + m_observer->shaderChanged(); + updateFiltered(); + planeChanged(); + SceneChangeNotify(); + } + + const char* GetShader() const + { + return m_shader.getShader(); + } + void SetShader(const char* name) + { + undoSave(); + m_shader.setShader(name); + shaderChanged(); + } + + void revertTexdef() + { + m_texdefTransformed = m_texdef.m_projection; + } + void texdefChanged() + { + revertTexdef(); + EmitTextureCoordinates(); + Brush_textureChanged(); + } + + void GetTexdef(TextureProjection& projection) const + { + projection = m_texdef.normalised(); + } + void SetTexdef(const TextureProjection& projection) + { + undoSave(); + m_texdef.setTexdef(projection); + texdefChanged(); + } + + void GetFlags(ContentsFlagsValue& flags) const + { + flags = m_shader.getFlags(); + } + void SetFlags(const ContentsFlagsValue& flags) + { + undoSave(); + m_shader.setFlags(flags); + m_observer->shaderChanged(); + updateFiltered(); + } + + void ShiftTexdef(float s, float t) + { + undoSave(); + m_texdef.shift(s, t); + texdefChanged(); + } + + void ScaleTexdef(float s, float t) + { + undoSave(); + m_texdef.scale(s, t); + texdefChanged(); + } + + void RotateTexdef(float angle) + { + undoSave(); + m_texdef.rotate(angle); + texdefChanged(); + } + + void FitTexture(float s_repeat, float t_repeat) + { + undoSave(); + m_texdef.fit(m_plane.plane3().normal(), m_winding, s_repeat, t_repeat); + texdefChanged(); + } + + void EmitTextureCoordinates() + { + Texdef_EmitTextureCoordinates(m_texdefTransformed, m_shader.width(), m_shader.height(), m_winding, plane3().normal(), g_matrix4_identity); + } + + + const Vector3& centroid() const + { + return m_centroid; + } + + void construct_centroid() + { + Winding_Centroid(m_winding, plane3(), m_centroid); + } + + const Winding& getWinding() const + { + return m_winding; + } + Winding& getWinding() + { + return m_winding; + } + + const Plane3& plane3() const + { + m_observer->evaluateTransform(); + return m_planeTransformed.plane3(); + } + FacePlane& getPlane() + { + return m_plane; + } + const FacePlane& getPlane() const + { + return m_plane; + } + FaceTexdef& getTexdef() + { + return m_texdef; + } + const FaceTexdef& getTexdef() const + { + return m_texdef; + } + FaceShader& getShader() + { + return m_shader; + } + const FaceShader& getShader() const + { + return m_shader; + } + + bool isDetail() const + { + return (m_shader.m_flags.m_contentFlags & BRUSH_DETAIL_MASK) != 0; + } + void setDetail(bool detail) + { + undoSave(); + if(detail && !isDetail()) + { + m_shader.m_flags.m_contentFlags |= BRUSH_DETAIL_MASK; + } + else if(!detail && isDetail()) + { + m_shader.m_flags.m_contentFlags &= ~BRUSH_DETAIL_MASK; + } + m_observer->shaderChanged(); + } + + bool contributes() const + { + return m_winding.numpoints > 2; + } + bool is_bounded() const + { + for(Winding::const_iterator i = m_winding.begin(); i != m_winding.end(); ++i) + { + if((*i).adjacent == c_brush_maxFaces) + { + return false; + } + } + return true; + } +}; + + +class FaceVertexId +{ + std::size_t m_face; + std::size_t m_vertex; + +public: + FaceVertexId(std::size_t face, std::size_t vertex) + : m_face(face), m_vertex(vertex) + { + } + + std::size_t getFace() const + { + return m_face; + } + std::size_t getVertex() const + { + return m_vertex; + } +}; + +typedef std::size_t faceIndex_t; + +struct EdgeRenderIndices +{ + RenderIndex first; + RenderIndex second; + + EdgeRenderIndices() + : first(0), second(0) + { + } + EdgeRenderIndices(const RenderIndex _first, const RenderIndex _second) + : first(_first), second(_second) + { + } +}; + +struct EdgeFaces +{ + faceIndex_t first; + faceIndex_t second; + + EdgeFaces() + : first(c_brush_maxFaces), second(c_brush_maxFaces) + { + } + EdgeFaces(const faceIndex_t _first, const faceIndex_t _second) + : first(_first), second(_second) + { + } +}; + +class RenderableWireframe : public OpenGLRenderable +{ +public: + void render(RenderStateFlags state) const + { +#if 1 + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices->colour); + glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices->vertex); + glDrawElements(GL_LINES, GLsizei(m_size<<1), RenderIndexTypeID, m_faceVertex.data()); +#else + glBegin(GL_LINES); + for(std::size_t i = 0; i < m_size; ++i) + { + glVertex3fv(&m_vertices[m_faceVertex[i].first].vertex.x); + glVertex3fv(&m_vertices[m_faceVertex[i].second].vertex.x); + } + glEnd(); +#endif + } + + Array m_faceVertex; + std::size_t m_size; + const PointVertex* m_vertices; +}; + +class Brush; +typedef std::vector brush_vector_t; + +class BrushFilter +{ +public: + virtual bool filter(const Brush& brush) const = 0; +}; + +bool brush_filtered(Brush& brush); +void add_brush_filter(BrushFilter& filter, int mask, bool invert = false); + + +/// \brief Returns true if 'self' takes priority when building brush b-rep. +inline bool plane3_inside(const Plane3& self, const Plane3& other, bool selfIsLater) +{ + if(vector3_equal_epsilon(self.normal(), other.normal(), 0.001)) + { + // same plane? prefer the one with smaller index + if(self.dist() == other.dist()) + return selfIsLater; + return self.dist() < other.dist(); + } + return true; +} + +typedef SmartPointer FaceSmartPointer; +typedef std::vector Faces; + +/// \brief Returns the unique-id of the edge adjacent to \p faceVertex in the edge-pair for the set of \p faces. +inline FaceVertexId next_edge(const Faces& faces, FaceVertexId faceVertex) +{ + std::size_t adjacent_face = faces[faceVertex.getFace()]->getWinding()[faceVertex.getVertex()].adjacent; + std::size_t adjacent_vertex = Winding_FindAdjacent(faces[adjacent_face]->getWinding(), faceVertex.getFace()); + + ASSERT_MESSAGE(adjacent_vertex != c_brush_maxFaces, "connectivity data invalid"); + if(adjacent_vertex == c_brush_maxFaces) + { + return faceVertex; + } + + return FaceVertexId(adjacent_face, adjacent_vertex); +} + +/// \brief Returns the unique-id of the vertex adjacent to \p faceVertex in the vertex-ring for the set of \p faces. +inline FaceVertexId next_vertex(const Faces& faces, FaceVertexId faceVertex) +{ + FaceVertexId nextEdge = next_edge(faces, faceVertex); + return FaceVertexId(nextEdge.getFace(), Winding_next(faces[nextEdge.getFace()]->getWinding(), nextEdge.getVertex())); +} + +class SelectableEdge +{ + Vector3 getEdge() const + { + const Winding& winding = getFace().getWinding(); + return vector3_mid(winding[m_faceVertex.getVertex()].vertex, winding[Winding_next(winding, m_faceVertex.getVertex())].vertex); + } + +public: + Faces& m_faces; + FaceVertexId m_faceVertex; + + SelectableEdge(Faces& faces, FaceVertexId faceVertex) + : m_faces(faces), m_faceVertex(faceVertex) + { + } + SelectableEdge& operator=(const SelectableEdge& other) + { + m_faceVertex = other.m_faceVertex; + return *this; + } + + Face& getFace() const + { + return *m_faces[m_faceVertex.getFace()]; + } + + void testSelect(SelectionTest& test, SelectionIntersection& best) + { + test.TestPoint(getEdge(), best); + } +}; + +class SelectableVertex +{ + Vector3 getVertex() const + { + return getFace().getWinding()[m_faceVertex.getVertex()].vertex; + } + +public: + Faces& m_faces; + FaceVertexId m_faceVertex; + + SelectableVertex(Faces& faces, FaceVertexId faceVertex) + : m_faces(faces), m_faceVertex(faceVertex) + { + } + SelectableVertex& operator=(const SelectableVertex& other) + { + m_faceVertex = other.m_faceVertex; + return *this; + } + + Face& getFace() const + { + return *m_faces[m_faceVertex.getFace()]; + } + + void testSelect(SelectionTest& test, SelectionIntersection& best) + { + test.TestPoint(getVertex(), best); + } +}; + +class BrushObserver +{ +public: + virtual void reserve(std::size_t size) = 0; + virtual void clear() = 0; + virtual void push_back(Face& face) = 0; + virtual void pop_back() = 0; + virtual void erase(std::size_t index) = 0; + virtual void connectivityChanged() = 0; + + virtual void edge_clear() = 0; + virtual void edge_push_back(SelectableEdge& edge) = 0; + + virtual void vertex_clear() = 0; + virtual void vertex_push_back(SelectableVertex& vertex) = 0; + + virtual void DEBUG_verify() const = 0; +}; + +class BrushVisitor +{ +public: + virtual void visit(Face& face) const = 0; +}; + +class Brush : + public TransformNode, + public Bounded, + public Cullable, + public Snappable, + public Undoable, + public FaceObserver, + public Filterable, + public Nameable, + public BrushDoom3 +{ +private: + scene::Node* m_node; + typedef UniqueSet Observers; + Observers m_observers; + UndoObserver* m_undoable_observer; + MapFile* m_map; + + // state + Faces m_faces; + // ---- + + // cached data compiled from state + Array m_faceCentroidPoints; + RenderablePointArray m_render_faces; + + Array m_uniqueVertexPoints; + typedef std::vector SelectableVertices; + SelectableVertices m_select_vertices; + RenderablePointArray m_render_vertices; + + Array m_uniqueEdgePoints; + typedef std::vector SelectableEdges; + SelectableEdges m_select_edges; + RenderablePointArray m_render_edges; + + Array m_edge_indices; + Array m_edge_faces; + + AABB m_aabb_local; + // ---- + + Callback m_evaluateTransform; + Callback m_boundsChanged; + + mutable bool m_planeChanged; // b-rep evaluation required + mutable bool m_transformChanged; // transform evaluation required + // ---- + +public: + STRING_CONSTANT(Name, "Brush"); + + Callback m_lightsChanged; + + // static data + static Shader* m_state_point; + // ---- + + static EBrushType m_type; + static double m_maxWorldCoord; + + Brush(scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : + m_node(&node), + m_undoable_observer(0), + m_map(0), + m_render_faces(m_faceCentroidPoints, GL_POINTS), + m_render_vertices(m_uniqueVertexPoints, GL_POINTS), + m_render_edges(m_uniqueEdgePoints, GL_POINTS), + m_evaluateTransform(evaluateTransform), + m_boundsChanged(boundsChanged), + m_planeChanged(false), + m_transformChanged(false) + { + planeChanged(); + } + Brush(const Brush& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : + m_node(&node), + m_undoable_observer(0), + m_map(0), + m_render_faces(m_faceCentroidPoints, GL_POINTS), + m_render_vertices(m_uniqueVertexPoints, GL_POINTS), + m_render_edges(m_uniqueEdgePoints, GL_POINTS), + m_evaluateTransform(evaluateTransform), + m_boundsChanged(boundsChanged), + m_planeChanged(false), + m_transformChanged(false) + { + copy(other); + } + Brush(const Brush& other) : + TransformNode(other), + Bounded(other), + Cullable(other), + Snappable(), + Undoable(other), + FaceObserver(other), + Filterable(other), + Nameable(other), + BrushDoom3(other), + m_node(0), + m_undoable_observer(0), + m_map(0), + m_render_faces(m_faceCentroidPoints, GL_POINTS), + m_render_vertices(m_uniqueVertexPoints, GL_POINTS), + m_render_edges(m_uniqueEdgePoints, GL_POINTS), + m_planeChanged(false), + m_transformChanged(false) + { + copy(other); + } + ~Brush() + { + ASSERT_MESSAGE(m_observers.empty(), "Brush::~Brush: observers still attached"); + } + + // assignment not supported + Brush& operator=(const Brush& other); + + void setDoom3GroupOrigin(const Vector3& origin) + { + //globalOutputStream() << "func_static origin before: " << m_funcStaticOrigin << " after: " << origin << "\n"; + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->getPlane().m_funcStaticOrigin = origin; + (*i)->getPlane().updateTranslated(); + (*i)->planeChanged(); + } + planeChanged(); + } + + void attach(BrushObserver& observer) + { + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + observer.push_back(*(*i)); + } + + for(SelectableEdges::iterator i = m_select_edges.begin(); i !=m_select_edges.end(); ++i) + { + observer.edge_push_back(*i); + } + + for(SelectableVertices::iterator i = m_select_vertices.begin(); i != m_select_vertices.end(); ++i) + { + observer.vertex_push_back(*i); + } + + m_observers.insert(&observer); + } + void detach(BrushObserver& observer) + { + m_observers.erase(&observer); + } + + void forEachFace(const BrushVisitor& visitor) const + { + for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + visitor.visit(*(*i)); + } + } + + void forEachFace_instanceAttach(MapFile* map) const + { + for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->instanceAttach(map); + } + } + void forEachFace_instanceDetach(MapFile* map) const + { + for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->instanceDetach(map); + } + } + + InstanceCounter m_instanceCounter; + void instanceAttach(const scene::Path& path) + { + if(++m_instanceCounter.m_count == 1) + { + m_map = path_find_mapfile(path.begin(), path.end()); + m_undoable_observer = GlobalUndoSystem().observer(this); + GlobalFilterSystem().registerFilterable(*this); + forEachFace_instanceAttach(m_map); + } + else + { + ASSERT_MESSAGE(path_find_mapfile(path.begin(), path.end()) == m_map, "node is instanced across more than one file"); + } + } + void instanceDetach(const scene::Path& path) + { + if(--m_instanceCounter.m_count == 0) + { + forEachFace_instanceDetach(m_map); + GlobalFilterSystem().unregisterFilterable(*this); + m_map = 0; + m_undoable_observer = 0; + GlobalUndoSystem().release(this); + } + } + + // nameable + const char* name() const + { + return "brush"; + } + void attach(const NameCallback& callback) + { + } + void detach(const NameCallback& callback) + { + } + + // filterable + void updateFiltered() + { + if(m_node != 0) + { + if(brush_filtered(*this)) + { + m_node->enable(scene::Node::eFiltered); + } + else + { + m_node->disable(scene::Node::eFiltered); + } + } + } + + // observer + void planeChanged() + { + m_planeChanged = true; + aabbChanged(); + m_lightsChanged(); + } + void shaderChanged() + { + updateFiltered(); + planeChanged(); + } + + void evaluateBRep() const + { + if(m_planeChanged) + { + m_planeChanged = false; + const_cast(this)->buildBRep(); + } + } + + void transformChanged() + { + m_transformChanged = true; + planeChanged(); + } + typedef MemberCaller TransformChangedCaller; + + void evaluateTransform() + { + if(m_transformChanged) + { + m_transformChanged = false; + revertTransform(); + m_evaluateTransform(); + } + } + const Matrix4& localToParent() const + { + return g_matrix4_identity; + } + void aabbChanged() + { + m_boundsChanged(); + } + const AABB& localAABB() const + { + evaluateBRep(); + return m_aabb_local; + } + + VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const + { + return test.TestAABB(m_aabb_local, localToWorld); + } + + void renderComponents(SelectionSystem::EComponentMode mode, Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + switch(mode) + { + case SelectionSystem::eVertex: + renderer.addRenderable(m_render_vertices, localToWorld); + break; + case SelectionSystem::eEdge: + renderer.addRenderable(m_render_edges, localToWorld); + break; + case SelectionSystem::eFace: + renderer.addRenderable(m_render_faces, localToWorld); + break; + default: + break; + } + } + + void transform(const Matrix4& matrix) + { + bool mirror = matrix4_handedness(matrix) == MATRIX4_LEFTHANDED; + + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->transform(matrix, mirror); + } + } + void snapto(float snap) + { + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->snapto(snap); + } + } + void revertTransform() + { + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->revertTransform(); + } + } + void freezeTransform() + { + for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i) + { + (*i)->freezeTransform(); + } + } + + /// \brief Returns the absolute index of the \p faceVertex. + std::size_t absoluteIndex(FaceVertexId faceVertex) + { + std::size_t index = 0; + for(std::size_t i = 0; i < faceVertex.getFace(); ++i) + { + index += m_faces[i]->getWinding().numpoints; + } + return index + faceVertex.getVertex(); + } + + void appendFaces(const Faces& other) + { + clear(); + for(Faces::const_iterator i = other.begin(); i != other.end(); ++i) + { + push_back(*i); + } + } + + /// \brief The undo memento for a brush stores only the list of face references - the faces are not copied. + class BrushUndoMemento : public UndoMemento + { + public: + BrushUndoMemento(const Faces& faces) : m_faces(faces) + { + } + void release() + { + delete this; + } + + Faces m_faces; + }; + + void undoSave() + { + if(m_map != 0) + { + m_map->changed(); + } + if(m_undoable_observer != 0) + { + m_undoable_observer->save(this); + } + } + + UndoMemento* exportState() const + { + return new BrushUndoMemento(m_faces); + } + + void importState(const UndoMemento* state) + { + undoSave(); + appendFaces(static_cast(state)->m_faces); + planeChanged(); + + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->DEBUG_verify(); + } + } + + bool isDetail() + { + return !m_faces.empty() && m_faces.front()->isDetail(); + } + + /// \brief Appends a copy of \p face to the end of the face list. + Face* addFace(const Face& face) + { + if(m_faces.size() == c_brush_maxFaces) + { + return 0; + } + undoSave(); + push_back(FaceSmartPointer(new Face(face, this))); + m_faces.back()->setDetail(isDetail()); + planeChanged(); + return m_faces.back(); + } + + /// \brief Appends a new face constructed from the parameters to the end of the face list. + Face* addPlane(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection) + { + if(m_faces.size() == c_brush_maxFaces) + { + return 0; + } + undoSave(); + push_back(FaceSmartPointer(new Face(p0, p1, p2, shader, projection, this))); + m_faces.back()->setDetail(isDetail()); + planeChanged(); + return m_faces.back(); + } + + static void constructStatic(EBrushType type) + { + m_type = type; + Face::m_type = type; + FacePlane::m_type = type; + + g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_QUAKE; + if(m_type == eBrushTypeQuake3BP || m_type == eBrushTypeDoom3 || m_type == eBrushTypeQuake4) + { + g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_BRUSHPRIMITIVES; + // g_brush_texturelock_enabled = true; // bad idea, this overrides user setting + } + else if(m_type == eBrushTypeHalfLife) + { + g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_HALFLIFE; + // g_brush_texturelock_enabled = true; // bad idea, this overrides user setting + } + + Face::m_quantise = (m_type == eBrushTypeQuake) ? quantiseInteger : quantiseFloating; + + m_state_point = GlobalShaderCache().capture("$POINT"); + } + static void destroyStatic() + { + GlobalShaderCache().release("$POINT"); + } + + std::size_t DEBUG_size() + { + return m_faces.size(); + } + + typedef Faces::const_iterator const_iterator; + + const_iterator begin() const + { + return m_faces.begin(); + } + const_iterator end() const + { + return m_faces.end(); + } + + Face* back() + { + return m_faces.back(); + } + const Face* back() const + { + return m_faces.back(); + } + void reserve(std::size_t count) + { + m_faces.reserve(count); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->reserve(count); + } + } + void push_back(Faces::value_type face) + { + m_faces.push_back(face); + if(m_instanceCounter.m_count != 0) + { + m_faces.back()->instanceAttach(m_map); + } + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->push_back(*face); + (*i)->DEBUG_verify(); + } + } + void pop_back() + { + if(m_instanceCounter.m_count != 0) + { + m_faces.back()->instanceDetach(m_map); + } + m_faces.pop_back(); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->pop_back(); + (*i)->DEBUG_verify(); + } + } + void erase(std::size_t index) + { + if(m_instanceCounter.m_count != 0) + { + m_faces[index]->instanceDetach(m_map); + } + m_faces.erase(m_faces.begin() + index); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->erase(index); + (*i)->DEBUG_verify(); + } + } + void connectivityChanged() + { + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->connectivityChanged(); + } + } + + + void clear() + { + undoSave(); + if(m_instanceCounter.m_count != 0) + { + forEachFace_instanceDetach(m_map); + } + m_faces.clear(); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->clear(); + (*i)->DEBUG_verify(); + } + } + std::size_t size() const + { + return m_faces.size(); + } + bool empty() const + { + return m_faces.empty(); + } + + /// \brief Returns true if any face of the brush contributes to the final B-Rep. + bool hasContributingFaces() const + { + for(const_iterator i = begin(); i != end(); ++i) + { + if((*i)->contributes()) + { + return true; + } + } + return false; + } + + /// \brief Removes faces that do not contribute to the brush. This is useful for cleaning up after CSG operations on the brush. + /// Note: removal of empty faces is not performed during direct brush manipulations, because it would make a manipulation irreversible if it created an empty face. + void removeEmptyFaces() + { + evaluateBRep(); + + { + std::size_t i = 0; + while(i < m_faces.size()) + { + if(!m_faces[i]->contributes()) + { + erase(i); + planeChanged(); + } + else + { + ++i; + } + } + } + } + + /// \brief Constructs \p winding from the intersection of \p plane with the other planes of the brush. + void windingForClipPlane(Winding& winding, const Plane3& plane) const + { + FixedWinding buffer[2]; + bool swap = false; + + // get a poly that covers an effectively infinite area + Winding_createInfinite(buffer[swap], plane, m_maxWorldCoord + 1); + + // chop the poly by all of the other faces + { + for (std::size_t i = 0; i < m_faces.size(); ++i) + { + const Face& clip = *m_faces[i]; + + if(plane3_equal(clip.plane3(), plane) + || !plane3_valid(clip.plane3()) || !plane_unique(i) + || plane3_opposing(plane, clip.plane3())) + { + continue; + } + + buffer[!swap].clear(); + +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "clip vs face: " << i << "\n"; +#endif + + { + // flip the plane, because we want to keep the back side + Plane3 clipPlane(vector3_negated(clip.plane3().normal()), -clip.plane3().dist()); + Winding_Clip(buffer[swap], plane, clipPlane, i, buffer[!swap]); + } + +#if BRUSH_CONNECTIVITY_DEBUG + for(FixedWinding::Points::iterator k = buffer[!swap].points.begin(), j = buffer[!swap].points.end() - 1; k != buffer[!swap].points.end(); j = k, ++k) + { + if(vector3_length_squared(vector3_subtracted((*k).vertex, (*j).vertex)) < 1) + { + globalOutputStream() << "v: " << std::distance(buffer[!swap].points.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n"; + } + } +#endif + + //ASSERT_MESSAGE(buffer[!swap].numpoints != 1, "created single-point winding"); + + swap = !swap; + } + } + + Winding_forFixedWinding(winding, buffer[swap]); + +#if BRUSH_CONNECTIVITY_DEBUG + Winding_printConnectivity(winding); + + for(Winding::iterator i = winding.begin(), j = winding.end() - 1; i != winding.end(); j = i, ++i) + { + if(vector3_length_squared(vector3_subtracted((*i).vertex, (*j).vertex)) < 1) + { + globalOutputStream() << "v: " << std::distance(winding.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n"; + } + } +#endif + } + + void update_wireframe(RenderableWireframe& wire, const bool* faces_visible) const + { + wire.m_faceVertex.resize(m_edge_indices.size()); + wire.m_vertices = m_uniqueVertexPoints.data(); + wire.m_size = 0; + for(std::size_t i = 0; i < m_edge_faces.size(); ++i) + { + if(faces_visible[m_edge_faces[i].first] + || faces_visible[m_edge_faces[i].second]) + { + wire.m_faceVertex[wire.m_size++] = m_edge_indices[i]; + } + } + } + + + void update_faces_wireframe(Array& wire, const bool* faces_visible) const + { + std::size_t count = 0; + for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i) + { + if(faces_visible[i]) + { + ++count; + } + } + + wire.resize(count); + Array::iterator p = wire.begin(); + for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i) + { + if(faces_visible[i]) + { + *p++ = m_faceCentroidPoints[i]; + } + } + } + + /// \brief Makes this brush a deep-copy of the \p other. + void copy(const Brush& other) + { + for(Faces::const_iterator i = other.m_faces.begin(); i != other.m_faces.end(); ++i) + { + addFace(*(*i)); + } + planeChanged(); + } + +private: + void edge_push_back(FaceVertexId faceVertex) + { + m_select_edges.push_back(SelectableEdge(m_faces, faceVertex)); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->edge_push_back(m_select_edges.back()); + } + } + void edge_clear() + { + m_select_edges.clear(); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->edge_clear(); + } + } + void vertex_push_back(FaceVertexId faceVertex) + { + m_select_vertices.push_back(SelectableVertex(m_faces, faceVertex)); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->vertex_push_back(m_select_vertices.back()); + } + } + void vertex_clear() + { + m_select_vertices.clear(); + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->vertex_clear(); + } + } + + /// \brief Returns true if the face identified by \p index is preceded by another plane that takes priority over it. + bool plane_unique(std::size_t index) const + { + // duplicate plane + for(std::size_t i = 0; i < m_faces.size(); ++i) + { + if(index != i && !plane3_inside(m_faces[index]->plane3(), m_faces[i]->plane3(), index < i)) + { + return false; + } + } + return true; + } + + /// \brief Removes edges that are smaller than the tolerance used when generating brush windings. + void removeDegenerateEdges() + { + for (std::size_t i = 0; i < m_faces.size(); ++i) + { + Winding& winding = m_faces[i]->getWinding(); + for(Winding::iterator j = winding.begin(); j != winding.end();) + { + std::size_t index = std::distance(winding.begin(), j); + std::size_t next = Winding_next(winding, index); + if(Edge_isDegenerate(winding[index].vertex, winding[next].vertex)) + { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate edge adjacent to " << winding[index].adjacent << "\n"; +#endif + Winding& other = m_faces[winding[index].adjacent]->getWinding(); + std::size_t adjacent = Winding_FindAdjacent(other, i); + if(adjacent != c_brush_maxFaces) + { + other.erase(other.begin() + adjacent); + } + winding.erase(j); + } + else + { + ++j; + } + } + } + } + + /// \brief Invalidates faces that have only two vertices in their winding, while preserving edge-connectivity information. + void removeDegenerateFaces() + { + // save adjacency info for degenerate faces + for (std::size_t i = 0; i < m_faces.size(); ++i) + { + Winding& degen = m_faces[i]->getWinding(); + + if(degen.numpoints == 2) + { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate winding adjacent to " << degen[0].adjacent << ", " << degen[1].adjacent << "\n"; +#endif + // this is an "edge" face, where the plane touches the edge of the brush + { + Winding& winding = m_faces[degen[0].adjacent]->getWinding(); + std::size_t index = Winding_FindAdjacent(winding, i); + if(index != c_brush_maxFaces) + { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << degen[0].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[1].adjacent << "\n"; +#endif + winding[index].adjacent = degen[1].adjacent; + } + } + + { + Winding& winding = m_faces[degen[1].adjacent]->getWinding(); + std::size_t index = Winding_FindAdjacent(winding, i); + if(index != c_brush_maxFaces) + { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << degen[1].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[0].adjacent << "\n"; +#endif + winding[index].adjacent = degen[0].adjacent; + } + } + + degen.resize(0); + } + } + } + + /// \brief Removes edges that have the same adjacent-face as their immediate neighbour. + void removeDuplicateEdges() + { + // verify face connectivity graph + for(std::size_t i = 0; i < m_faces.size(); ++i) + { + //if(m_faces[i]->contributes()) + { + Winding& winding = m_faces[i]->getWinding(); + for(std::size_t j = 0; j != winding.numpoints;) + { + std::size_t next = Winding_next(winding, j); + if(winding[j].adjacent == winding[next].adjacent) + { +#if BRUSH_DEGENERATE_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": removed duplicate edge adjacent to face " << winding[j].adjacent << "\n"; +#endif + winding.erase(winding.begin() + next); + } + else + { + ++j; + } + } + } + } + } + + /// \brief Removes edges that do not have a matching pair in their adjacent-face. + void verifyConnectivityGraph() + { + // verify face connectivity graph + for(std::size_t i = 0; i < m_faces.size(); ++i) + { + //if(m_faces[i]->contributes()) + { + Winding& winding = m_faces[i]->getWinding(); + for(Winding::iterator j = winding.begin(); j != winding.end();) + { +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": adjacent to face " << (*j).adjacent << "\n"; +#endif + // remove unidirectional graph edges + if((*j).adjacent == c_brush_maxFaces + || Winding_FindAdjacent(m_faces[(*j).adjacent]->getWinding(), i) == c_brush_maxFaces) + { +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "Brush::buildWindings: face " << i << ": removing unidirectional connectivity graph edge adjacent to face " << (*j).adjacent << "\n"; +#endif + winding.erase(j); + } + else + { + ++j; + } + } + } + } + } + + /// \brief Returns true if the brush is a finite volume. A brush without a finite volume extends past the maximum world bounds and is not valid. + bool isBounded() + { + for(const_iterator i = begin(); i != end(); ++i) + { + if(!(*i)->is_bounded()) + { + return false; + } + } + return true; + } + + /// \brief Constructs the polygon windings for each face of the brush. Also updates the brush bounding-box and face texture-coordinates. + bool buildWindings() + { + + { + m_aabb_local = AABB(); + + for (std::size_t i = 0; i < m_faces.size(); ++i) + { + Face& f = *m_faces[i]; + + if(!plane3_valid(f.plane3()) || !plane_unique(i)) + { + f.getWinding().resize(0); + } + else + { +#if BRUSH_CONNECTIVITY_DEBUG + globalOutputStream() << "face: " << i << "\n"; +#endif + windingForClipPlane(f.getWinding(), f.plane3()); + + // update brush bounds + const Winding& winding = f.getWinding(); + for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i) + { + aabb_extend_by_point_safe(m_aabb_local, (*i).vertex); + } + + // update texture coordinates + f.EmitTextureCoordinates(); + } + } + } + + bool degenerate = !isBounded(); + + if(!degenerate) + { + // clean up connectivity information. + // these cleanups must be applied in a specific order. + removeDegenerateEdges(); + removeDegenerateFaces(); + removeDuplicateEdges(); + verifyConnectivityGraph(); + } + + return degenerate; + } + + /// \brief Constructs the face windings and updates anything that depends on them. + void buildBRep(); +}; + + + +class FaceInstance; + +class FaceInstanceSet +{ + typedef SelectionList FaceInstances; + FaceInstances m_faceInstances; +public: + void insert(FaceInstance& faceInstance) + { + m_faceInstances.append(faceInstance); + } + void erase(FaceInstance& faceInstance) + { + m_faceInstances.erase(faceInstance); + } + + template + void foreach(Functor functor) + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + functor(*(*i)); + } + } + + bool empty() const + { + return m_faceInstances.empty(); + } + FaceInstance& last() const + { + return m_faceInstances.back(); + } +}; + +extern FaceInstanceSet g_SelectedFaceInstances; + +typedef std::list VertexSelection; + +inline VertexSelection::iterator VertexSelection_find(VertexSelection& self, std::size_t value) +{ + return std::find(self.begin(), self.end(), value); +} + +inline VertexSelection::const_iterator VertexSelection_find(const VertexSelection& self, std::size_t value) +{ + return std::find(self.begin(), self.end(), value); +} + +inline VertexSelection::iterator VertexSelection_insert(VertexSelection& self, std::size_t value) +{ + VertexSelection::iterator i = VertexSelection_find(self, value); + if(i == self.end()) + { + self.push_back(value); + return --self.end(); + } + return i; +} +inline void VertexSelection_erase(VertexSelection& self, std::size_t value) +{ + VertexSelection::iterator i = VertexSelection_find(self, value); + if(i != self.end()) + { + self.erase(i); + } +} + +inline bool triangle_reversed(std::size_t x, std::size_t y, std::size_t z) +{ + return !((x < y && y < z) || (z < x && x < y) || (y < z && z < x)); +} +template +inline Vector3 triangle_cross(const BasicVector3& x, const BasicVector3 y, const BasicVector3& z) +{ + return vector3_cross(y - x, z - x); +} +template +inline bool triangles_same_winding(const BasicVector3& x1, const BasicVector3 y1, const BasicVector3& z1, const BasicVector3& x2, const BasicVector3 y2, const BasicVector3& z2) +{ + return vector3_dot(triangle_cross(x1, y1, z1), triangle_cross(x2, y2, z2)) > 0; +} + + +typedef const Plane3* PlanePointer; +typedef PlanePointer* PlanesIterator; + +class VectorLightList : public LightList +{ + typedef std::vector Lights; + Lights m_lights; +public: + void addLight(const RendererLight& light) + { + m_lights.push_back(&light); + } + void clear() + { + m_lights.clear(); + } + void evaluateLights() const + { + } + void lightsChanged() const + { + } + void forEachLight(const RendererLightCallback& callback) const + { + for(Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i) + { + callback(*(*i)); + } + } +}; + +class FaceInstance +{ + Face* m_face; + ObservedSelectable m_selectable; + ObservedSelectable m_selectableVertices; + ObservedSelectable m_selectableEdges; + SelectionChangeCallback m_selectionChanged; + + VertexSelection m_vertexSelection; + VertexSelection m_edgeSelection; + +public: + mutable VectorLightList m_lights; + + FaceInstance(Face& face, const SelectionChangeCallback& observer) : + m_face(&face), + m_selectable(SelectedChangedCaller(*this)), + m_selectableVertices(observer), + m_selectableEdges(observer), + m_selectionChanged(observer) + { + } + FaceInstance(const FaceInstance& other) : + m_face(other.m_face), + m_selectable(SelectedChangedCaller(*this)), + m_selectableVertices(other.m_selectableVertices), + m_selectableEdges(other.m_selectableEdges), + m_selectionChanged(other.m_selectionChanged) + { + } + FaceInstance& operator=(const FaceInstance& other) + { + m_face = other.m_face; + return *this; + } + + Face& getFace() + { + return *m_face; + } + const Face& getFace() const + { + return *m_face; + } + + void selectedChanged(const Selectable& selectable) + { + if(selectable.isSelected()) + { + g_SelectedFaceInstances.insert(*this); + } + else + { + g_SelectedFaceInstances.erase(*this); + } + m_selectionChanged(selectable); + } + typedef MemberCaller1 SelectedChangedCaller; + + bool selectedVertices() const + { + return !m_vertexSelection.empty(); + } + bool selectedEdges() const + { + return !m_edgeSelection.empty(); + } + bool isSelected() const + { + return m_selectable.isSelected(); + } + + bool selectedComponents() const + { + return selectedVertices() || selectedEdges() || isSelected(); + } + bool selectedComponents(SelectionSystem::EComponentMode mode) const + { + switch(mode) + { + case SelectionSystem::eVertex: + return selectedVertices(); + case SelectionSystem::eEdge: + return selectedEdges(); + case SelectionSystem::eFace: + return isSelected(); + default: + return false; + } + } + void setSelected(SelectionSystem::EComponentMode mode, bool select) + { + switch(mode) + { + case SelectionSystem::eFace: + m_selectable.setSelected(select); + break; + case SelectionSystem::eVertex: + ASSERT_MESSAGE(!select, "select-all not supported"); + + m_vertexSelection.clear(); + m_selectableVertices.setSelected(false); + break; + case SelectionSystem::eEdge: + ASSERT_MESSAGE(!select, "select-all not supported"); + + m_edgeSelection.clear(); + m_selectableEdges.setSelected(false); + break; + default: + break; + } + } + + template + void SelectedVertices_foreach(Functor functor) const + { + for(VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i) + { + std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i); + if(index != c_brush_maxFaces) + { + functor(getFace().getWinding()[index].vertex); + } + } + } + template + void SelectedEdges_foreach(Functor functor) const + { + for(VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i) + { + std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i); + if(index != c_brush_maxFaces) + { + const Winding& winding = getFace().getWinding(); + std::size_t adjacent = Winding_next(winding, index); + functor(vector3_mid(winding[index].vertex, winding[adjacent].vertex)); + } + } + } + template + void SelectedFaces_foreach(Functor functor) const + { + if(isSelected()) + { + functor(centroid()); + } + } + + template + void SelectedComponents_foreach(Functor functor) const + { + SelectedVertices_foreach(functor); + SelectedEdges_foreach(functor); + SelectedFaces_foreach(functor); + } + + void iterate_selected(AABB& aabb) const + { + SelectedComponents_foreach(AABBExtendByPoint(aabb)); + } + + class RenderablePointVectorPushBack + { + RenderablePointVector& m_points; + public: + RenderablePointVectorPushBack(RenderablePointVector& points) : m_points(points) + { + } + void operator()(const Vector3& point) const + { + const Colour4b colour_selected(0, 0, 255, 255); + m_points.push_back(pointvertex_for_windingpoint(point, colour_selected)); + } + }; + + void iterate_selected(RenderablePointVector& points) const + { + SelectedComponents_foreach(RenderablePointVectorPushBack(points)); + } + + bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const + { + return m_face->intersectVolume(volume, localToWorld); + } + + void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + if(!m_face->isFiltered() && m_face->contributes() && intersectVolume(volume, localToWorld)) + { + renderer.PushState(); + if(selectedComponents()) + { + renderer.Highlight(Renderer::eFace); + } + m_face->render(renderer, localToWorld); + renderer.PopState(); + } + } + + void testSelect(SelectionTest& test, SelectionIntersection& best) + { + if(!m_face->isFiltered()) + { + m_face->testSelect(test, best); + } + } + void testSelect(Selector& selector, SelectionTest& test) + { + SelectionIntersection best; + testSelect(test, best); + if(best.valid()) + { + Selector_add(selector, m_selectable, best); + } + } + void testSelect_centroid(Selector& selector, SelectionTest& test) + { + if(m_face->contributes() && !m_face->isFiltered()) + { + SelectionIntersection best; + m_face->testSelect_centroid(test, best); + if(best.valid()) + { + Selector_add(selector, m_selectable, best); + } + } + } + + void selectPlane(Selector& selector, const Line& line, PlanesIterator first, PlanesIterator last, const PlaneCallback& selectedPlaneCallback) + { + for(Winding::const_iterator i = getFace().getWinding().begin(); i != getFace().getWinding().end(); ++i) + { + Vector3 v(vector3_subtracted(line_closest_point(line, (*i).vertex), (*i).vertex)); + double dot = vector3_dot(getFace().plane3().normal(), v); + if(dot <= 0) + { + return; + } + } + + Selector_add(selector, m_selectable); + + selectedPlaneCallback(getFace().plane3()); + } + void selectReversedPlane(Selector& selector, const SelectedPlanes& selectedPlanes) + { + if(selectedPlanes.contains(plane3_flipped(getFace().plane3()))) + { + Selector_add(selector, m_selectable); + } + } + + void transformComponents(const Matrix4& matrix) + { + if(isSelected()) + { + m_face->transform(matrix, false); + } + if(selectedVertices()) + { + if(m_vertexSelection.size() == 1) + { + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); + m_face->assign_planepts(m_face->m_move_planeptsTransformed); + } + else if(m_vertexSelection.size() == 2) + { + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]); + m_face->assign_planepts(m_face->m_move_planeptsTransformed); + } + else if(m_vertexSelection.size() >= 3) + { + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]); + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]); + m_face->assign_planepts(m_face->m_move_planeptsTransformed); + } + } + if(selectedEdges()) + { + if(m_edgeSelection.size() == 1) + { + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]); + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); + m_face->assign_planepts(m_face->m_move_planeptsTransformed); + } + else if(m_edgeSelection.size() >= 2) + { + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]); + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]); + matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]); + m_face->assign_planepts(m_face->m_move_planeptsTransformed); + } + } + } + + void snapto(float snap) + { + m_face->snapto(snap); + } + + void snapComponents(float snap) + { + if(isSelected()) + { + snapto(snap); + } + if(selectedVertices()) + { + vector3_snap(m_face->m_move_planepts[0], snap); + vector3_snap(m_face->m_move_planepts[1], snap); + vector3_snap(m_face->m_move_planepts[2], snap); + m_face->assign_planepts(m_face->m_move_planepts); + planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts); + m_face->freezeTransform(); + } + if(selectedEdges()) + { + vector3_snap(m_face->m_move_planepts[0], snap); + vector3_snap(m_face->m_move_planepts[1], snap); + vector3_snap(m_face->m_move_planepts[2], snap); + m_face->assign_planepts(m_face->m_move_planepts); + planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts); + m_face->freezeTransform(); + } + } + void update_move_planepts_vertex(std::size_t index) + { + m_face->update_move_planepts_vertex(index, m_face->m_move_planepts); + } + void update_move_planepts_vertex2(std::size_t index, std::size_t other) + { + const std::size_t numpoints = m_face->getWinding().numpoints; + ASSERT_MESSAGE(index < numpoints, "select_vertex: invalid index"); + + const std::size_t opposite = Winding_Opposite(m_face->getWinding(), index, other); + + if(triangle_reversed(index, other, opposite)) + { + std::swap(index, other); + } + + ASSERT_MESSAGE( + triangles_same_winding( + m_face->getWinding()[opposite].vertex, + m_face->getWinding()[index].vertex, + m_face->getWinding()[other].vertex, + m_face->getWinding()[0].vertex, + m_face->getWinding()[1].vertex, + m_face->getWinding()[2].vertex + ), + "update_move_planepts_vertex2: error" + ); + + m_face->m_move_planepts[0] = m_face->getWinding()[opposite].vertex; + m_face->m_move_planepts[1] = m_face->getWinding()[index].vertex; + m_face->m_move_planepts[2] = m_face->getWinding()[other].vertex; + planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate + } + void update_selection_vertex() + { + if(m_vertexSelection.size() == 0) + { + m_selectableVertices.setSelected(false); + } + else + { + m_selectableVertices.setSelected(true); + + if(m_vertexSelection.size() == 1) + { + std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin()); + + if(index != c_brush_maxFaces) + { + update_move_planepts_vertex(index); + } + } + else if(m_vertexSelection.size() == 2) + { + std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin()); + std::size_t other = Winding_FindAdjacent(getFace().getWinding(), *(++m_vertexSelection.begin())); + + if(index != c_brush_maxFaces + && other != c_brush_maxFaces) + { + update_move_planepts_vertex2(index, other); + } + } + } + } + void select_vertex(std::size_t index, bool select) + { + if(select) + { + VertexSelection_insert(m_vertexSelection, getFace().getWinding()[index].adjacent); + } + else + { + VertexSelection_erase(m_vertexSelection, getFace().getWinding()[index].adjacent); + } + + SceneChangeNotify(); + update_selection_vertex(); + } + + bool selected_vertex(std::size_t index) const + { + return VertexSelection_find(m_vertexSelection, getFace().getWinding()[index].adjacent) != m_vertexSelection.end(); + } + + void update_move_planepts_edge(std::size_t index) + { + std::size_t numpoints = m_face->getWinding().numpoints; + ASSERT_MESSAGE(index < numpoints, "select_edge: invalid index"); + + std::size_t adjacent = Winding_next(m_face->getWinding(), index); + std::size_t opposite = Winding_Opposite(m_face->getWinding(), index); + m_face->m_move_planepts[0] = m_face->getWinding()[index].vertex; + m_face->m_move_planepts[1] = m_face->getWinding()[adjacent].vertex; + m_face->m_move_planepts[2] = m_face->getWinding()[opposite].vertex; + planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate + } + void update_selection_edge() + { + if(m_edgeSelection.size() == 0) + { + m_selectableEdges.setSelected(false); + } + else + { + m_selectableEdges.setSelected(true); + + if(m_edgeSelection.size() == 1) + { + std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_edgeSelection.begin()); + + if(index != c_brush_maxFaces) + { + update_move_planepts_edge(index); + } + } + } + } + void select_edge(std::size_t index, bool select) + { + if(select) + { + VertexSelection_insert(m_edgeSelection, getFace().getWinding()[index].adjacent); + } + else + { + VertexSelection_erase(m_edgeSelection, getFace().getWinding()[index].adjacent); + } + + SceneChangeNotify(); + update_selection_edge(); + } + + bool selected_edge(std::size_t index) const + { + return VertexSelection_find(m_edgeSelection, getFace().getWinding()[index].adjacent) != m_edgeSelection.end(); + } + + const Vector3& centroid() const + { + return m_face->centroid(); + } + + void connectivityChanged() + { + // This occurs when a face is added or removed. + // The current vertex and edge selections no longer valid and must be cleared. + m_vertexSelection.clear(); + m_selectableVertices.setSelected(false); + m_edgeSelection.clear(); + m_selectableEdges.setSelected(false); + } +}; + +class BrushClipPlane : public OpenGLRenderable +{ + Plane3 m_plane; + Winding m_winding; + static Shader* m_state; +public: + static void constructStatic() + { + m_state = GlobalShaderCache().capture("$CLIPPER_OVERLAY"); + } + static void destroyStatic() + { + GlobalShaderCache().release("$CLIPPER_OVERLAY"); + } + + void setPlane(const Brush& brush, const Plane3& plane) + { + m_plane = plane; + if(plane3_valid(m_plane)) + { + brush.windingForClipPlane(m_winding, m_plane); + } + else + { + m_winding.resize(0); + } + } + + void render(RenderStateFlags state) const + { + if((state & RENDER_FILL) != 0) + { + Winding_Draw(m_winding, m_plane.normal(), state); + } + else + { + Winding_DrawWireframe(m_winding); + + // also draw a line indicating the direction of the cut + Vector3 lineverts[2]; + Winding_Centroid(m_winding, m_plane, lineverts[0]); + lineverts[1] = vector3_added(lineverts[0], vector3_scaled(m_plane.normal(), Brush::m_maxWorldCoord * 4)); + + glVertexPointer(3, GL_FLOAT, sizeof(Vector3), &lineverts[0]); + glDrawArrays(GL_LINES, 0, GLsizei(2)); + } + } + + void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + renderer.SetState(m_state, Renderer::eWireframeOnly); + renderer.SetState(m_state, Renderer::eFullMaterials); + renderer.addRenderable(*this, localToWorld); + } +}; + +inline void Face_addLight(const FaceInstance& face, const Matrix4& localToWorld, const RendererLight& light) +{ + const Plane3& facePlane = face.getFace().plane3(); + const Vector3& origin = light.aabb().origin; + Plane3 tmp(plane3_transformed(Plane3(facePlane.normal(), -facePlane.dist()), localToWorld)); + if(!plane3_test_point(tmp, origin) + || !plane3_test_point(tmp, vector3_added(origin, light.offset()))) + { + face.m_lights.addLight(light); + } +} + + + +typedef std::vector FaceInstances; + +class EdgeInstance : public Selectable +{ + FaceInstances& m_faceInstances; + SelectableEdge* m_edge; + + void select_edge(bool select) + { + FaceVertexId faceVertex = m_edge->m_faceVertex; + m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select); + faceVertex = next_edge(m_edge->m_faces, faceVertex); + m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select); + } + bool selected_edge() const + { + FaceVertexId faceVertex = m_edge->m_faceVertex; + if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex())) + { + return false; + } + faceVertex = next_edge(m_edge->m_faces, faceVertex); + if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex())) + { + return false; + } + + return true; + } + +public: + EdgeInstance(FaceInstances& faceInstances, SelectableEdge& edge) + : m_faceInstances(faceInstances), m_edge(&edge) + { + } + EdgeInstance& operator=(const EdgeInstance& other) + { + m_edge = other.m_edge; + return *this; + } + + void setSelected(bool select) + { + select_edge(select); + } + bool isSelected() const + { + return selected_edge(); + } + + + void testSelect(Selector& selector, SelectionTest& test) + { + SelectionIntersection best; + m_edge->testSelect(test, best); + if(best.valid()) + { + Selector_add(selector, *this, best); + } + } +}; + +class VertexInstance : public Selectable +{ + FaceInstances& m_faceInstances; + SelectableVertex* m_vertex; + + void select_vertex(bool select) + { + FaceVertexId faceVertex = m_vertex->m_faceVertex; + do + { + m_faceInstances[faceVertex.getFace()].select_vertex(faceVertex.getVertex(), select); + faceVertex = next_vertex(m_vertex->m_faces, faceVertex); + } + while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace()); + } + bool selected_vertex() const + { + FaceVertexId faceVertex = m_vertex->m_faceVertex; + do + { + if(!m_faceInstances[faceVertex.getFace()].selected_vertex(faceVertex.getVertex())) + { + return false; + } + faceVertex = next_vertex(m_vertex->m_faces, faceVertex); + } + while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace()); + return true; + } + +public: + VertexInstance(FaceInstances& faceInstances, SelectableVertex& vertex) + : m_faceInstances(faceInstances), m_vertex(&vertex) + { + } + VertexInstance& operator=(const VertexInstance& other) + { + m_vertex = other.m_vertex; + return *this; + } + + void setSelected(bool select) + { + select_vertex(select); + } + bool isSelected() const + { + return selected_vertex(); + } + + void testSelect(Selector& selector, SelectionTest& test) + { + SelectionIntersection best; + m_vertex->testSelect(test, best); + if(best.valid()) + { + Selector_add(selector, *this, best); + } + } +}; + +class BrushInstanceVisitor +{ +public: + virtual void visit(FaceInstance& face) const = 0; +}; + +class BrushInstance : +public BrushObserver, +public scene::Instance, +public Selectable, +public Renderable, +public SelectionTestable, +public ComponentSelectionTestable, +public ComponentEditable, +public ComponentSnappable, +public PlaneSelectable, +public LightCullable +{ + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts() + { + InstanceStaticCast::install(m_casts); + InstanceContainedCast::install(m_casts); + InstanceContainedCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceIdentityCast::install(m_casts); + InstanceContainedCast::install(m_casts); + } + InstanceTypeCastTable& get() + { + return m_casts; + } + }; + + + Brush& m_brush; + + FaceInstances m_faceInstances; + + typedef std::vector EdgeInstances; + EdgeInstances m_edgeInstances; + typedef std::vector VertexInstances; + VertexInstances m_vertexInstances; + + ObservedSelectable m_selectable; + + mutable RenderableWireframe m_render_wireframe; + mutable RenderablePointVector m_render_selected; + mutable AABB m_aabb_component; + mutable Array m_faceCentroidPointsCulled; + RenderablePointArray m_render_faces_wireframe; + mutable bool m_viewChanged; // requires re-evaluation of view-dependent cached data + + BrushClipPlane m_clipPlane; + + static Shader* m_state_selpoint; + + const LightList* m_lightList; + + TransformModifier m_transform; + + BrushInstance(const BrushInstance& other); // NOT COPYABLE + BrushInstance& operator=(const BrushInstance& other); // NOT ASSIGNABLE +public: + static Counter* m_counter; + + typedef LazyStatic StaticTypeCasts; + + void lightsChanged() + { + m_lightList->lightsChanged(); + } + typedef MemberCaller LightsChangedCaller; + + STRING_CONSTANT(Name, "BrushInstance"); + + BrushInstance(const scene::Path& path, scene::Instance* parent, Brush& brush) : + Instance(path, parent, this, StaticTypeCasts::instance().get()), + m_brush(brush), + m_selectable(SelectedChangedCaller(*this)), + m_render_selected(GL_POINTS), + m_render_faces_wireframe(m_faceCentroidPointsCulled, GL_POINTS), + m_viewChanged(false), + m_transform(Brush::TransformChangedCaller(m_brush), ApplyTransformCaller(*this)) + { + m_brush.instanceAttach(Instance::path()); + m_brush.attach(*this); + m_counter->increment(); + + m_lightList = &GlobalShaderCache().attach(*this); + m_brush.m_lightsChanged = LightsChangedCaller(*this); ///\todo Make this work with instancing. + + Instance::setTransformChangedCallback(LightsChangedCaller(*this)); + } + ~BrushInstance() + { + Instance::setTransformChangedCallback(Callback()); + + m_brush.m_lightsChanged = Callback(); + GlobalShaderCache().detach(*this); + + m_counter->decrement(); + m_brush.detach(*this); + m_brush.instanceDetach(Instance::path()); + } + + Brush& getBrush() + { + return m_brush; + } + const Brush& getBrush() const + { + return m_brush; + } + + Bounded& get(NullType) + { + return m_brush; + } + Cullable& get(NullType) + { + return m_brush; + } + Transformable& get(NullType) + { + return m_transform; + } + + void selectedChanged(const Selectable& selectable) + { + GlobalSelectionSystem().getObserver(SelectionSystem::ePrimitive)(selectable); + GlobalSelectionSystem().onSelectedChanged(*this, selectable); + + Instance::selectedChanged(); + } + typedef MemberCaller1 SelectedChangedCaller; + + void selectedChangedComponent(const Selectable& selectable) + { + GlobalSelectionSystem().getObserver(SelectionSystem::eComponent)(selectable); + GlobalSelectionSystem().onComponentSelection(*this, selectable); + } + typedef MemberCaller1 SelectedChangedComponentCaller; + + const BrushInstanceVisitor& forEachFaceInstance(const BrushInstanceVisitor& visitor) + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + visitor.visit(*i); + } + return visitor; + } + + static void constructStatic() + { + m_state_selpoint = GlobalShaderCache().capture("$SELPOINT"); + } + static void destroyStatic() + { + GlobalShaderCache().release("$SELPOINT"); + } + + void clear() + { + m_faceInstances.clear(); + } + void reserve(std::size_t size) + { + m_faceInstances.reserve(size); + } + + void push_back(Face& face) + { + m_faceInstances.push_back(FaceInstance(face, SelectedChangedComponentCaller(*this))); + } + void pop_back() + { + ASSERT_MESSAGE(!m_faceInstances.empty(), "erasing invalid element"); + m_faceInstances.pop_back(); + } + void erase(std::size_t index) + { + ASSERT_MESSAGE(index < m_faceInstances.size(), "erasing invalid element"); + m_faceInstances.erase(m_faceInstances.begin() + index); + } + void connectivityChanged() + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).connectivityChanged(); + } + } + + void edge_clear() + { + m_edgeInstances.clear(); + } + void edge_push_back(SelectableEdge& edge) + { + m_edgeInstances.push_back(EdgeInstance(m_faceInstances, edge)); + } + + void vertex_clear() + { + m_vertexInstances.clear(); + } + void vertex_push_back(SelectableVertex& vertex) + { + m_vertexInstances.push_back(VertexInstance(m_faceInstances, vertex)); + } + + void DEBUG_verify() const + { + ASSERT_MESSAGE(m_faceInstances.size() == m_brush.DEBUG_size(), "FATAL: mismatch"); + } + + bool isSelected() const + { + return m_selectable.isSelected(); + } + void setSelected(bool select) + { + m_selectable.setSelected(select); + } + + void update_selected() const + { + m_render_selected.clear(); + for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + if((*i).getFace().contributes()) + { + (*i).iterate_selected(m_render_selected); + } + } + } + + void evaluateViewDependent(const VolumeTest& volume, const Matrix4& localToWorld) const + { + if(m_viewChanged) + { + m_viewChanged = false; + + bool faces_visible[c_brush_maxFaces]; + { + bool* j = faces_visible; + for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i, ++j) + { + *j = (*i).intersectVolume(volume, localToWorld); + } + } + + m_brush.update_wireframe(m_render_wireframe, faces_visible); + m_brush.update_faces_wireframe(m_faceCentroidPointsCulled, faces_visible); + } + } + + void renderComponentsSelected(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + m_brush.evaluateBRep(); + + update_selected(); + if(!m_render_selected.empty()) + { + renderer.Highlight(Renderer::ePrimitive, false); + renderer.SetState(m_state_selpoint, Renderer::eWireframeOnly); + renderer.SetState(m_state_selpoint, Renderer::eFullMaterials); + renderer.addRenderable(m_render_selected, localToWorld); + } + } + + void renderComponents(Renderer& renderer, const VolumeTest& volume) const + { + m_brush.evaluateBRep(); + + const Matrix4& localToWorld = Instance::localToWorld(); + + renderer.SetState(m_brush.m_state_point, Renderer::eWireframeOnly); + renderer.SetState(m_brush.m_state_point, Renderer::eFullMaterials); + + if(volume.fill() && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace) + { + evaluateViewDependent(volume, localToWorld); + renderer.addRenderable(m_render_faces_wireframe, localToWorld); + } + else + { + m_brush.renderComponents(GlobalSelectionSystem().ComponentMode(), renderer, volume, localToWorld); + } + } + + void renderClipPlane(Renderer& renderer, const VolumeTest& volume) const + { + if(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip && isSelected()) + { + m_clipPlane.render(renderer, volume, localToWorld()); + } + } + + void renderCommon(Renderer& renderer, const VolumeTest& volume) const + { + bool componentMode = GlobalSelectionSystem().Mode() == SelectionSystem::eComponent; + + if(componentMode && isSelected()) + { + renderComponents(renderer, volume); + } + + if(parentSelected()) + { + if(!componentMode) + { + renderer.Highlight(Renderer::eFace); + } + renderer.Highlight(Renderer::ePrimitive); + } + } + + void renderSolid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + //renderCommon(renderer, volume); + + m_lightList->evaluateLights(); + + for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + renderer.setLights((*i).m_lights); + (*i).render(renderer, volume, localToWorld); + } + + renderComponentsSelected(renderer, volume, localToWorld); + } + + void renderWireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + //renderCommon(renderer, volume); + + evaluateViewDependent(volume, localToWorld); + + if(m_render_wireframe.m_size != 0) + { + renderer.addRenderable(m_render_wireframe, localToWorld); + } + + renderComponentsSelected(renderer, volume, localToWorld); + } + + void renderSolid(Renderer& renderer, const VolumeTest& volume) const + { + m_brush.evaluateBRep(); + + renderClipPlane(renderer, volume); + + renderSolid(renderer, volume, localToWorld()); + } + + void renderWireframe(Renderer& renderer, const VolumeTest& volume) const + { + m_brush.evaluateBRep(); + + renderClipPlane(renderer, volume); + + renderWireframe(renderer, volume, localToWorld()); + } + + void viewChanged() const + { + m_viewChanged = true; + } + + void testSelect(Selector& selector, SelectionTest& test) + { + test.BeginMesh(localToWorld()); + + SelectionIntersection best; + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).testSelect(test, best); + } + if(best.valid()) + { + selector.addIntersection(best); + } + } + + bool isSelectedComponents() const + { + for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + if((*i).selectedComponents()) + { + return true; + } + } + return false; + } + void setSelectedComponents(bool select, SelectionSystem::EComponentMode mode) + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).setSelected(mode, select); + } + } + void testSelectComponents(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) + { + test.BeginMesh(localToWorld()); + + switch(mode) + { + case SelectionSystem::eVertex: + { + for(VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i) + { + (*i).testSelect(selector, test); + } + } + break; + case SelectionSystem::eEdge: + { + for(EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i) + { + (*i).testSelect(selector, test); + } + } + break; + case SelectionSystem::eFace: + { + if(test.getVolume().fill()) + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).testSelect(selector, test); + } + } + else + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).testSelect_centroid(selector, test); + } + } + } + break; + default: + break; + } + } + + void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) + { + test.BeginMesh(localToWorld()); + + PlanePointer brushPlanes[c_brush_maxFaces]; + PlanesIterator j = brushPlanes; + + for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i) + { + *j++ = &(*i)->plane3(); + } + + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).selectPlane(selector, Line(test.getNear(), test.getFar()), brushPlanes, j, selectedPlaneCallback); + } + } + void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).selectReversedPlane(selector, selectedPlanes); + } + } + + + void transformComponents(const Matrix4& matrix) + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).transformComponents(matrix); + } + } + const AABB& getSelectedComponentsBounds() const + { + m_aabb_component = AABB(); + + for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).iterate_selected(m_aabb_component); + } + + return m_aabb_component; + } + + void snapComponents(float snap) + { + for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).snapComponents(snap); + } + } + void evaluateTransform() + { + Matrix4 matrix(m_transform.calculateTransform()); + //globalOutputStream() << "matrix: " << matrix << "\n"; + + if(m_transform.getType() == TRANSFORM_PRIMITIVE) + { + m_brush.transform(matrix); + } + else + { + transformComponents(matrix); + } + } + void applyTransform() + { + m_brush.revertTransform(); + evaluateTransform(); + m_brush.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; + + void setClipPlane(const Plane3& plane) + { + m_clipPlane.setPlane(m_brush, plane); + } + + bool testLight(const RendererLight& light) const + { + return light.testAABB(worldAABB()); + } + void insertLight(const RendererLight& light) + { + const Matrix4& localToWorld = Instance::localToWorld(); + for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + Face_addLight(*i, localToWorld, light); + } + } + void clearLights() + { + for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i) + { + (*i).m_lights.clear(); + } + } +}; + +inline BrushInstance* Instance_getBrush(scene::Instance& instance) +{ + return InstanceTypeCast::cast(instance); +} + + +template +class BrushSelectedVisitor : public SelectionSystem::Visitor +{ + const Functor& m_functor; +public: + BrushSelectedVisitor(const Functor& functor) : m_functor(functor) + { + } + void visit(scene::Instance& instance) const + { + BrushInstance* brush = Instance_getBrush(instance); + if(brush != 0) + { + m_functor(*brush); + } + } +}; + +template +inline const Functor& Scene_forEachSelectedBrush(const Functor& functor) +{ + GlobalSelectionSystem().foreachSelected(BrushSelectedVisitor(functor)); + return functor; +} + +template +class BrushVisibleSelectedVisitor : public SelectionSystem::Visitor +{ + const Functor& m_functor; +public: + BrushVisibleSelectedVisitor(const Functor& functor) : m_functor(functor) + { + } + void visit(scene::Instance& instance) const + { + BrushInstance* brush = Instance_getBrush(instance); + if(brush != 0 + && instance.path().top().get().visible()) + { + m_functor(*brush); + } + } +}; + +template +inline const Functor& Scene_forEachVisibleSelectedBrush(const Functor& functor) +{ + GlobalSelectionSystem().foreachSelected(BrushVisibleSelectedVisitor(functor)); + return functor; +} + +class BrushForEachFace +{ + const BrushInstanceVisitor& m_visitor; +public: + BrushForEachFace(const BrushInstanceVisitor& visitor) : m_visitor(visitor) + { + } + void operator()(BrushInstance& brush) const + { + brush.forEachFaceInstance(m_visitor); + } +}; + +template +class FaceInstanceVisitFace : public BrushInstanceVisitor +{ + const Functor& functor; +public: + FaceInstanceVisitFace(const Functor& functor) + : functor(functor) + { + } + void visit(FaceInstance& face) const + { + functor(face.getFace()); + } +}; + +template +inline const Functor& Brush_forEachFace(BrushInstance& brush, const Functor& functor) +{ + brush.forEachFaceInstance(FaceInstanceVisitFace(functor)); + return functor; +} + +template +class FaceVisitAll : public BrushVisitor +{ + const Functor& functor; +public: + FaceVisitAll(const Functor& functor) + : functor(functor) + { + } + void visit(Face& face) const + { + functor(face); + } +}; + +template +inline const Functor& Brush_forEachFace(const Brush& brush, const Functor& functor) +{ + brush.forEachFace(FaceVisitAll(functor)); + return functor; +} + +template +inline const Functor& Brush_forEachFace(Brush& brush, const Functor& functor) +{ + brush.forEachFace(FaceVisitAll(functor)); + return functor; +} + +template +class FaceInstanceVisitAll : public BrushInstanceVisitor +{ + const Functor& functor; +public: + FaceInstanceVisitAll(const Functor& functor) + : functor(functor) + { + } + void visit(FaceInstance& face) const + { + functor(face); + } +}; + +template +inline const Functor& Brush_ForEachFaceInstance(BrushInstance& brush, const Functor& functor) +{ + brush.forEachFaceInstance(FaceInstanceVisitAll(functor)); + return functor; +} + +template +inline const Functor& Scene_forEachBrush(scene::Graph& graph, const Functor& functor) +{ + graph.traverse(InstanceWalker< InstanceApply >(functor)); + return functor; +} + +template +class InstanceIfVisible : public Functor +{ +public: + InstanceIfVisible(const Functor& functor) : Functor(functor) + { + } + void operator()(scene::Instance& instance) + { + if(instance.path().top().get().visible()) + { + Functor::operator()(instance); + } + } +}; + +template +class BrushVisibleWalker : public scene::Graph::Walker +{ + const Functor& m_functor; +public: + BrushVisibleWalker(const Functor& functor) : m_functor(functor) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + BrushInstance* brush = Instance_getBrush(instance); + if(brush != 0) + { + m_functor(*brush); + } + } + return true; + } +}; + +template +inline const Functor& Scene_forEachVisibleBrush(scene::Graph& graph, const Functor& functor) +{ + graph.traverse(BrushVisibleWalker(functor)); + return functor; +} + +template +inline const Functor& Scene_ForEachBrush_ForEachFace(scene::Graph& graph, const Functor& functor) +{ + Scene_forEachBrush(graph, BrushForEachFace(FaceInstanceVisitFace(functor))); + return functor; +} + +// d1223m +template +inline const Functor& Scene_ForEachBrush_ForEachFaceInstance(scene::Graph& graph, const Functor& functor) +{ + Scene_forEachBrush(graph, BrushForEachFace(FaceInstanceVisitAll(functor))); + return functor; +} + +template +inline const Functor& Scene_ForEachSelectedBrush_ForEachFace(scene::Graph& graph, const Functor& functor) +{ + Scene_forEachSelectedBrush(BrushForEachFace(FaceInstanceVisitFace(functor))); + return functor; +} + +template +inline const Functor& Scene_ForEachSelectedBrush_ForEachFaceInstance(scene::Graph& graph, const Functor& functor) +{ + Scene_forEachSelectedBrush(BrushForEachFace(FaceInstanceVisitAll(functor))); + return functor; +} + +template +class FaceVisitorWrapper +{ + const Functor& functor; +public: + FaceVisitorWrapper(const Functor& functor) : functor(functor) + { + } + + void operator()(FaceInstance& faceInstance) const + { + functor(faceInstance.getFace()); + } +}; + +template +inline const Functor& Scene_ForEachSelectedBrushFace(scene::Graph& graph, const Functor& functor) +{ + g_SelectedFaceInstances.foreach(FaceVisitorWrapper(functor)); + return functor; +} + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brush_primit.cpp b/misc/mediasource/netradiant-src/radiant/brush_primit.cpp new file mode 100644 index 00000000..02b821dd --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brush_primit.cpp @@ -0,0 +1,1466 @@ +/* +Copyright (C) 1999-2006 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 "brush_primit.h" + +#include "debugging/debugging.h" + +#include "itexdef.h" +#include "itextures.h" + +#include + +#include "stringio.h" +#include "texturelib.h" +#include "math/matrix.h" +#include "math/plane.h" +#include "math/aabb.h" + +#include "winding.h" +#include "preferences.h" + + +/*! +\brief Construct a transform from XYZ space to ST space (3d to 2d). +This will be one of three axis-aligned spaces, depending on the surface normal. +NOTE: could also be done by swapping values. +*/ +void Normal_GetTransform(const Vector3& normal, Matrix4& transform) +{ + switch (projectionaxis_for_normal(normal)) + { + case eProjectionAxisZ: + transform[0] = 1; + transform[1] = 0; + transform[2] = 0; + + transform[4] = 0; + transform[5] = 1; + transform[6] = 0; + + transform[8] = 0; + transform[9] = 0; + transform[10] = 1; + break; + case eProjectionAxisY: + transform[0] = 1; + transform[1] = 0; + transform[2] = 0; + + transform[4] = 0; + transform[5] = 0; + transform[6] = -1; + + transform[8] = 0; + transform[9] = 1; + transform[10] = 0; + break; + case eProjectionAxisX: + transform[0] = 0; + transform[1] = 0; + transform[2] = 1; + + transform[4] = 1; + transform[5] = 0; + transform[6] = 0; + + transform[8] = 0; + transform[9] = 1; + transform[10] = 0; + break; + } + transform[3] = transform[7] = transform[11] = transform[12] = transform[13] = transform[14] = 0; + transform[15] = 1; +} + +/*! +\brief Construct a transform in ST space from the texdef. +Transforms constructed from quake's texdef format are (-shift)*(1/scale)*(-rotate) with x translation sign flipped. +This would really make more sense if it was inverseof(shift*rotate*scale).. oh well. +*/ +inline void Texdef_toTransform(const texdef_t& texdef, float width, float height, Matrix4& transform) +{ + double inverse_scale[2]; + + // transform to texdef shift/scale/rotate + inverse_scale[0] = 1 / (texdef.scale[0] * width); + inverse_scale[1] = 1 / (texdef.scale[1] * -height); + transform[12] = texdef.shift[0] / width; + transform[13] = -texdef.shift[1] / -height; + double c = cos(degrees_to_radians(-texdef.rotate)); + double s = sin(degrees_to_radians(-texdef.rotate)); + transform[0] = static_cast(c * inverse_scale[0]); + transform[1] = static_cast(s * inverse_scale[1]); + transform[4] = static_cast(-s * inverse_scale[0]); + transform[5] = static_cast(c * inverse_scale[1]); + transform[2] = transform[3] = transform[6] = transform[7] = transform[8] = transform[9] = transform[11] = transform[14] = 0; + transform[10] = transform[15] = 1; +} + +inline void BPTexdef_toTransform(const brushprimit_texdef_t& bp_texdef, Matrix4& transform) +{ + transform = g_matrix4_identity; + transform.xx() = bp_texdef.coords[0][0]; + transform.yx() = bp_texdef.coords[0][1]; + transform.tx() = bp_texdef.coords[0][2]; + transform.xy() = bp_texdef.coords[1][0]; + transform.yy() = bp_texdef.coords[1][1]; + transform.ty() = bp_texdef.coords[1][2]; +} + +inline void Texdef_toTransform(const TextureProjection& projection, float width, float height, Matrix4& transform) +{ + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + BPTexdef_toTransform(projection.m_brushprimit_texdef, transform); + } + else + { + Texdef_toTransform(projection.m_texdef, width, height, transform); + } +} + +// handles degenerate cases, just in case library atan2 doesn't +inline double arctangent_yx(double y, double x) +{ + if(fabs(x) > 1.0E-6) + { + return atan2(y, x); + } + else if(y > 0) + { + return c_half_pi; + } + else + { + return -c_half_pi; + } +} + +inline void Texdef_fromTransform(texdef_t& texdef, float width, float height, const Matrix4& transform) +{ + texdef.scale[0] = static_cast((1.0 / vector2_length(Vector2(transform[0], transform[4]))) / width); + texdef.scale[1] = static_cast((1.0 / vector2_length(Vector2(transform[1], transform[5]))) / height); + + texdef.rotate = static_cast(-radians_to_degrees(arctangent_yx(-transform[4], transform[0]))); + + if(texdef.rotate == -180.0f) + { + texdef.rotate = 180.0f; + } + + texdef.shift[0] = transform[12] * width; + texdef.shift[1] = transform[13] * height; + + // If the 2d cross-product of the x and y axes is positive, one of the axes has a negative scale. + if(vector2_cross(Vector2(transform[0], transform[4]), Vector2(transform[1], transform[5])) > 0) + { + if(texdef.rotate >= 180.0f) + { + texdef.rotate -= 180.0f; + texdef.scale[0] = -texdef.scale[0]; + } + else + { + texdef.scale[1] = -texdef.scale[1]; + } + } + //globalOutputStream() << "fromTransform: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n"; +} + +inline void BPTexdef_fromTransform(brushprimit_texdef_t& bp_texdef, const Matrix4& transform) +{ + bp_texdef.coords[0][0] = transform.xx(); + bp_texdef.coords[0][1] = transform.yx(); + bp_texdef.coords[0][2] = transform.tx(); + bp_texdef.coords[1][0] = transform.xy(); + bp_texdef.coords[1][1] = transform.yy(); + bp_texdef.coords[1][2] = transform.ty(); +} + +inline void Texdef_fromTransform(TextureProjection& projection, float width, float height, const Matrix4& transform) +{ + ASSERT_MESSAGE((transform[0] != 0 || transform[4] != 0) + && (transform[1] != 0 || transform[5] != 0), "invalid texture matrix"); + + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + BPTexdef_fromTransform(projection.m_brushprimit_texdef, transform); + } + else + { + Texdef_fromTransform(projection.m_texdef, width, height, transform); + } +} + +inline void Texdef_normalise(texdef_t& texdef, float width, float height) +{ + // it may be useful to also normalise the rotation here, if this function is used elsewhere. + texdef.shift[0] = float_mod(texdef.shift[0], width); + texdef.shift[1] = float_mod(texdef.shift[1], height); + //globalOutputStream() << "normalise: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n"; +} + +inline void BPTexdef_normalise(brushprimit_texdef_t& bp_texdef, float width, float height) +{ + bp_texdef.coords[0][2] = float_mod(bp_texdef.coords[0][2], width); + bp_texdef.coords[1][2] = float_mod(bp_texdef.coords[1][2], height); +} + +/// \brief Normalise \p projection for a given texture \p width and \p height. +/// +/// All texture-projection translation (shift) values are congruent modulo the dimensions of the texture. +/// This function normalises shift values to the smallest positive congruent values. +void Texdef_normalise(TextureProjection& projection, float width, float height) +{ + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + BPTexdef_normalise(projection.m_brushprimit_texdef, width, height); + } + else + { + Texdef_normalise(projection.m_texdef, width, height); + } +} + +void ComputeAxisBase(const Vector3& normal, Vector3& texS, Vector3& texT); + +inline void DebugAxisBase(const Vector3& normal) +{ + Vector3 x, y; + ComputeAxisBase(normal, x, y); + globalOutputStream() << "BP debug: " << x << y << normal << "\n"; +} + +void Texdef_basisForNormal(const TextureProjection& projection, const Vector3& normal, Matrix4& basis) +{ + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + basis = g_matrix4_identity; + ComputeAxisBase(normal, vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y())); + vector4_to_vector3(basis.z()) = normal; + matrix4_transpose(basis); + //DebugAxisBase(normal); + } + else if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) + { + basis = g_matrix4_identity; + vector4_to_vector3(basis.x()) = projection.m_basis_s; + vector4_to_vector3(basis.y()) = vector3_negated(projection.m_basis_t); + vector4_to_vector3(basis.z()) = vector3_normalised(vector3_cross(vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y()))); + matrix4_multiply_by_matrix4(basis, matrix4_rotation_for_z_degrees(-projection.m_texdef.rotate)); + //globalOutputStream() << "debug: " << projection.m_basis_s << projection.m_basis_t << normal << "\n"; + matrix4_transpose(basis); + } + else + { + Normal_GetTransform(normal, basis); + } +} + +void Texdef_EmitTextureCoordinates(const TextureProjection& projection, std::size_t width, std::size_t height, Winding& w, const Vector3& normal, const Matrix4& localToWorld) +{ + if(w.numpoints < 3) + { + return; + } + //globalOutputStream() << "normal: " << normal << "\n"; + + Matrix4 local2tex; + Texdef_toTransform(projection, (float)width, (float)height, local2tex); + //globalOutputStream() << "texdef: " << static_cast(local2tex.x()) << static_cast(local2tex.y()) << "\n"; + +#if 0 + { + TextureProjection tmp; + Texdef_fromTransform(tmp, (float)width, (float)height, local2tex); + Matrix4 tmpTransform; + Texdef_toTransform(tmp, (float)width, (float)height, tmpTransform); + ASSERT_MESSAGE(matrix4_equal_epsilon(local2tex, tmpTransform, 0.0001f), "bleh"); + } +#endif + + { + Matrix4 xyz2st; + // we don't care if it's not normalised... + Texdef_basisForNormal(projection, matrix4_transformed_direction(localToWorld, normal), xyz2st); + //globalOutputStream() << "basis: " << static_cast(xyz2st.x()) << static_cast(xyz2st.y()) << static_cast(xyz2st.z()) << "\n"; + matrix4_multiply_by_matrix4(local2tex, xyz2st); + } + + Vector3 tangent(vector3_normalised(vector4_to_vector3(matrix4_transposed(local2tex).x()))); + Vector3 bitangent(vector3_normalised(vector4_to_vector3(matrix4_transposed(local2tex).y()))); + + matrix4_multiply_by_matrix4(local2tex, localToWorld); + + for(Winding::iterator i = w.begin(); i != w.end(); ++i) + { + Vector3 texcoord = matrix4_transformed_point(local2tex, (*i).vertex); + (*i).texcoord[0] = texcoord[0]; + (*i).texcoord[1] = texcoord[1]; + + (*i).tangent = tangent; + (*i).bitangent = bitangent; + } +} + +/*! +\brief Provides the axis-base of the texture ST space for this normal, +as they had been transformed to world XYZ space. +*/ +void TextureAxisFromNormal(const Vector3& normal, Vector3& s, Vector3& t) +{ + switch (projectionaxis_for_normal(normal)) + { + case eProjectionAxisZ: + s[0] = 1; + s[1] = 0; + s[2] = 0; + + t[0] = 0; + t[1] = -1; + t[2] = 0; + + break; + case eProjectionAxisY: + s[0] = 1; + s[1] = 0; + s[2] = 0; + + t[0] = 0; + t[1] = 0; + t[2] = -1; + + break; + case eProjectionAxisX: + s[0] = 0; + s[1] = 1; + s[2] = 0; + + t[0] = 0; + t[1] = 0; + t[2] = -1; + + break; + } +} + +void Texdef_Assign(texdef_t& td, const texdef_t& other) +{ + td = other; +} + +void Texdef_Shift(texdef_t& td, float s, float t) +{ + td.shift[0] += s; + td.shift[1] += t; +} + +void Texdef_Scale(texdef_t& td, float s, float t) +{ + td.scale[0] += s; + td.scale[1] += t; +} + +void Texdef_Rotate(texdef_t& td, float angle) +{ + td.rotate += angle; + td.rotate = static_cast(float_to_integer(td.rotate) % 360); +} + +// NOTE: added these from Ritual's Q3Radiant +void ClearBounds(Vector3& mins, Vector3& maxs) +{ + mins[0] = mins[1] = mins[2] = 99999; + maxs[0] = maxs[1] = maxs[2] = -99999; +} + +void AddPointToBounds(const Vector3& v, Vector3& mins, Vector3& maxs) +{ + int i; + float val; + + for (i=0 ; i<3 ; i++) + { + val = v[i]; + if (val < mins[i]) + mins[i] = val; + if (val > maxs[i]) + maxs[i] = val; + } +} + +template +inline BasicVector3 vector3_inverse(const BasicVector3& self) +{ + return BasicVector3( + Element(1.0 / self.x()), + Element(1.0 / self.y()), + Element(1.0 / self.z()) + ); +} + +// low level functions .. put in mathlib? +#define BPMatCopy(a,b) {b[0][0] = a[0][0]; b[0][1] = a[0][1]; b[0][2] = a[0][2]; b[1][0] = a[1][0]; b[1][1] = a[1][1]; b[1][2] = a[1][2];} +// apply a scale transformation to the BP matrix +#define BPMatScale(m,sS,sT) {m[0][0]*=sS; m[1][0]*=sS; m[0][1]*=sT; m[1][1]*=sT;} +// apply a translation transformation to a BP matrix +#define BPMatTranslate(m,s,t) {m[0][2] += m[0][0]*s + m[0][1]*t; m[1][2] += m[1][0]*s+m[1][1]*t;} +// 2D homogeneous matrix product C = A*B +void BPMatMul(float A[2][3], float B[2][3], float C[2][3]); +// apply a rotation (degrees) +void BPMatRotate(float A[2][3], float theta); +#ifdef _DEBUG +void BPMatDump(float A[2][3]); +#endif + +#ifdef _DEBUG +//#define DBG_BP +#endif + + +bp_globals_t g_bp_globals; +float g_texdef_default_scale; + +// compute a determinant using Sarrus rule +//++timo "inline" this with a macro +// NOTE : the three vectors are understood as columns of the matrix +inline float SarrusDet(const Vector3& a, const Vector3& b, const Vector3& c) +{ + return a[0]*b[1]*c[2]+b[0]*c[1]*a[2]+c[0]*a[1]*b[2] + -c[0]*b[1]*a[2]-a[1]*b[0]*c[2]-a[0]*b[2]*c[1]; +} + +// in many case we know three points A,B,C in two axis base B1 and B2 +// and we want the matrix M so that A(B1) = T * A(B2) +// NOTE: 2D homogeneous space stuff +// NOTE: we don't do any check to see if there's a solution or we have a particular case .. need to make sure before calling +// NOTE: the third coord of the A,B,C point is ignored +// NOTE: see the commented out section to fill M and D +//++timo TODO: update the other members to use this when possible +void MatrixForPoints( Vector3 M[3], Vector3 D[2], brushprimit_texdef_t *T ) +{ +// Vector3 M[3]; // columns of the matrix .. easier that way (the indexing is not standard! it's column-line .. later computations are easier that way) + float det; +// Vector3 D[2]; + M[2][0]=1.0f; M[2][1]=1.0f; M[2][2]=1.0f; +#if 0 + // fill the data vectors + M[0][0]=A2[0]; M[0][1]=B2[0]; M[0][2]=C2[0]; + M[1][0]=A2[1]; M[1][1]=B2[1]; M[1][2]=C2[1]; + M[2][0]=1.0f; M[2][1]=1.0f; M[2][2]=1.0f; + D[0][0]=A1[0]; + D[0][1]=B1[0]; + D[0][2]=C1[0]; + D[1][0]=A1[1]; + D[1][1]=B1[1]; + D[1][2]=C1[1]; +#endif + // solve + det = SarrusDet( M[0], M[1], M[2] ); + T->coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det; + T->coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det; + T->coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det; + T->coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det; + T->coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det; + T->coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det; +} + +//++timo replace everywhere texX by texS etc. ( ----> and in q3map !) +// NOTE : ComputeAxisBase here and in q3map code must always BE THE SAME ! +// WARNING : special case behaviour of atan2(y,x) <-> atan(y/x) might not be the same everywhere when x == 0 +// rotation by (0,RotY,RotZ) assigns X to normal +void ComputeAxisBase(const Vector3& normal, Vector3& texS, Vector3& texT) +{ +#if 1 + const Vector3 up(0, 0, 1); + const Vector3 down(0, 0, -1); + + if(vector3_equal_epsilon(normal, up, float(1e-6))) + { + texS = Vector3(0, 1, 0); + texT = Vector3(1, 0, 0); + } + else if(vector3_equal_epsilon(normal, down, float(1e-6))) + { + texS = Vector3(0, 1, 0); + texT = Vector3(-1, 0, 0); + } + else + { + texS = vector3_normalised(vector3_cross(normal, up)); + texT = vector3_normalised(vector3_cross(normal, texS)); + vector3_negate(texS); + } + +#else + float RotY,RotZ; + // do some cleaning + /* + if (fabs(normal[0])<1e-6) + normal[0]=0.0f; + if (fabs(normal[1])<1e-6) + normal[1]=0.0f; + if (fabs(normal[2])<1e-6) + normal[2]=0.0f; + */ + RotY=-atan2(normal[2],sqrt(normal[1]*normal[1]+normal[0]*normal[0])); + RotZ=atan2(normal[1],normal[0]); + // rotate (0,1,0) and (0,0,1) to compute texS and texT + texS[0]=-sin(RotZ); + texS[1]=cos(RotZ); + texS[2]=0; + // the texT vector is along -Z ( T texture coorinates axis ) + texT[0]=-sin(RotY)*cos(RotZ); + texT[1]=-sin(RotY)*sin(RotZ); + texT[2]=-cos(RotY); +#endif +} + +#if 0 // texdef conversion +void FaceToBrushPrimitFace(face_t *f) +{ + Vector3 texX,texY; + Vector3 proj; + // ST of (0,0) (1,0) (0,1) + float ST[3][5]; // [ point index ] [ xyz ST ] + //++timo not used as long as brushprimit_texdef and texdef are static +/* f->brushprimit_texdef.contents=f->texdef.contents; + f->brushprimit_texdef.flags=f->texdef.flags; + f->brushprimit_texdef.value=f->texdef.value; + strcpy(f->brushprimit_texdef.name,f->texdef.name); */ +#ifdef DBG_BP + if ( f->plane.normal[0]==0.0f && f->plane.normal[1]==0.0f && f->plane.normal[2]==0.0f ) + { + globalOutputStream() << "Warning : f->plane.normal is (0,0,0) in FaceToBrushPrimitFace\n"; + } + // check d_texture + if (!f->d_texture) + { + globalOutputStream() << "Warning : f.d_texture is 0 in FaceToBrushPrimitFace\n"; + return; + } +#endif + // compute axis base + ComputeAxisBase(f->plane.normal,texX,texY); + // compute projection vector + VectorCopy(f->plane.normal,proj); + VectorScale(proj,f->plane.dist,proj); + // (0,0) in plane axis base is (0,0,0) in world coordinates + projection on the affine plane + // (1,0) in plane axis base is texX in world coordinates + projection on the affine plane + // (0,1) in plane axis base is texY in world coordinates + projection on the affine plane + // use old texture code to compute the ST coords of these points + VectorCopy(proj,ST[0]); + EmitTextureCoordinates(ST[0], f->pShader->getTexture(), f); + VectorCopy(texX,ST[1]); + VectorAdd(ST[1],proj,ST[1]); + EmitTextureCoordinates(ST[1], f->pShader->getTexture(), f); + VectorCopy(texY,ST[2]); + VectorAdd(ST[2],proj,ST[2]); + EmitTextureCoordinates(ST[2], f->pShader->getTexture(), f); + // compute texture matrix + f->brushprimit_texdef.coords[0][2]=ST[0][3]; + f->brushprimit_texdef.coords[1][2]=ST[0][4]; + f->brushprimit_texdef.coords[0][0]=ST[1][3]-f->brushprimit_texdef.coords[0][2]; + f->brushprimit_texdef.coords[1][0]=ST[1][4]-f->brushprimit_texdef.coords[1][2]; + f->brushprimit_texdef.coords[0][1]=ST[2][3]-f->brushprimit_texdef.coords[0][2]; + f->brushprimit_texdef.coords[1][1]=ST[2][4]-f->brushprimit_texdef.coords[1][2]; +} + +// compute texture coordinates for the winding points +void EmitBrushPrimitTextureCoordinates(face_t * f, Winding * w) +{ + Vector3 texX,texY; + float x,y; + // compute axis base + ComputeAxisBase(f->plane.normal,texX,texY); + // in case the texcoords matrix is empty, build a default one + // same behaviour as if scale[0]==0 && scale[1]==0 in old code + if (f->brushprimit_texdef.coords[0][0]==0 && f->brushprimit_texdef.coords[1][0]==0 && f->brushprimit_texdef.coords[0][1]==0 && f->brushprimit_texdef.coords[1][1]==0) + { + f->brushprimit_texdef.coords[0][0] = 1.0f; + f->brushprimit_texdef.coords[1][1] = 1.0f; + ConvertTexMatWithQTexture( &f->brushprimit_texdef, 0, &f->brushprimit_texdef, f->pShader->getTexture() ); + } + int i; + for (i=0 ; ibrushprimit_texdef.coords[0][0]*x+f->brushprimit_texdef.coords[0][1]*y+f->brushprimit_texdef.coords[0][2]; + float T=f->brushprimit_texdef.coords[1][0]*x+f->brushprimit_texdef.coords[1][1]*y+f->brushprimit_texdef.coords[1][2]; + if ( fabs(S-w.point_at(i)[3])>1e-2 || fabs(T-w.point_at(i)[4])>1e-2 ) + { + if ( fabs(S-w.point_at(i)[3])>1e-4 || fabs(T-w.point_at(i)[4])>1e-4 ) + globalOutputStream() << "Warning : precision loss in brush -> brush primitive texture computation\n"; + else + globalOutputStream() << "Warning : brush -> brush primitive texture computation bug detected\n"; + } + } +#endif +#endif + w.point_at(i)[3]=f->brushprimit_texdef.coords[0][0]*x+f->brushprimit_texdef.coords[0][1]*y+f->brushprimit_texdef.coords[0][2]; + w.point_at(i)[4]=f->brushprimit_texdef.coords[1][0]*x+f->brushprimit_texdef.coords[1][1]*y+f->brushprimit_texdef.coords[1][2]; + } +} +#endif + +typedef float texmat_t[2][3]; + +void TexMat_Scale(texmat_t texmat, float s, float t) +{ + texmat[0][0] *= s; + texmat[0][1] *= s; + texmat[0][2] *= s; + texmat[1][0] *= t; + texmat[1][1] *= t; + texmat[1][2] *= t; +} + +void TexMat_Assign(texmat_t texmat, const texmat_t other) +{ + texmat[0][0] = other[0][0]; + texmat[0][1] = other[0][1]; + texmat[0][2] = other[0][2]; + texmat[1][0] = other[1][0]; + texmat[1][1] = other[1][1]; + texmat[1][2] = other[1][2]; +} + +void ConvertTexMatWithDimensions(const texmat_t texmat1, std::size_t w1, std::size_t h1, + texmat_t texmat2, std::size_t w2, std::size_t h2) +{ + TexMat_Assign(texmat2, texmat1); + TexMat_Scale(texmat2, static_cast(w1) / static_cast(w2), static_cast(h1) / static_cast(h2)); +} + +#if 0 +// convert a texture matrix between two qtexture_t +// if 0 for qtexture_t, basic 2x2 texture is assumed ( straight mapping between s/t coordinates and geometric coordinates ) +void ConvertTexMatWithQTexture( const float texMat1[2][3], const qtexture_t *qtex1, float texMat2[2][3], const qtexture_t *qtex2 ) +{ + ConvertTexMatWithDimensions(texMat1, (qtex1) ? qtex1->width : 2, (qtex1) ? qtex1->height : 2, + texMat2, (qtex2) ? qtex2->width : 2, (qtex2) ? qtex2->height : 2); +} + +void ConvertTexMatWithQTexture( const brushprimit_texdef_t *texMat1, const qtexture_t *qtex1, brushprimit_texdef_t *texMat2, const qtexture_t *qtex2 ) +{ + ConvertTexMatWithQTexture(texMat1->coords, qtex1, texMat2->coords, qtex2); +} +#endif + +// compute a fake shift scale rot representation from the texture matrix +// these shift scale rot values are to be understood in the local axis base +// Note: this code looks similar to Texdef_fromTransform, but the algorithm is slightly different. + +void TexMatToFakeTexCoords(const brushprimit_texdef_t& bp_texdef, texdef_t& texdef) +{ + texdef.scale[0] = static_cast(1.0 / vector2_length(Vector2(bp_texdef.coords[0][0], bp_texdef.coords[1][0]))); + texdef.scale[1] = static_cast(1.0 / vector2_length(Vector2(bp_texdef.coords[0][1], bp_texdef.coords[1][1]))); + + texdef.rotate = -static_cast(radians_to_degrees(arctangent_yx(bp_texdef.coords[1][0], bp_texdef.coords[0][0]))); + + texdef.shift[0] = -bp_texdef.coords[0][2]; + texdef.shift[1] = bp_texdef.coords[1][2]; + + // determine whether or not an axis is flipped using a 2d cross-product + double cross = vector2_cross(Vector2(bp_texdef.coords[0][0], bp_texdef.coords[0][1]), Vector2(bp_texdef.coords[1][0], bp_texdef.coords[1][1])); + if(cross < 0) + { + // This is a bit of a compromise when using BPs--since we don't know *which* axis was flipped, + // we pick one (rather arbitrarily) using the following convention: If the X-axis is between + // 0 and 180, we assume it's the Y-axis that flipped, otherwise we assume it's the X-axis and + // subtract out 180 degrees to compensate. + if(texdef.rotate >= 180.0f) + { + texdef.rotate -= 180.0f; + texdef.scale[0] = -texdef.scale[0]; + } + else + { + texdef.scale[1] = -texdef.scale[1]; + } + } +} + +// compute back the texture matrix from fake shift scale rot +void FakeTexCoordsToTexMat(const texdef_t& texdef, brushprimit_texdef_t& bp_texdef) +{ + double r = degrees_to_radians(-texdef.rotate); + double c = cos(r); + double s = sin(r); + double x = 1.0f / texdef.scale[0]; + double y = 1.0f / texdef.scale[1]; + bp_texdef.coords[0][0] = static_cast(x * c); + bp_texdef.coords[1][0] = static_cast(x * s); + bp_texdef.coords[0][1] = static_cast(y * -s); + bp_texdef.coords[1][1] = static_cast(y * c); + bp_texdef.coords[0][2] = -texdef.shift[0]; + bp_texdef.coords[1][2] = texdef.shift[1]; +} + +#if 0 // texture locking (brush primit) +// used for texture locking +// will move the texture according to a geometric vector +void ShiftTextureGeometric_BrushPrimit(face_t *f, Vector3& delta) +{ + Vector3 texS,texT; + float tx,ty; + Vector3 M[3]; // columns of the matrix .. easier that way + float det; + Vector3 D[2]; + // compute plane axis base ( doesn't change with translation ) + ComputeAxisBase( f->plane.normal, texS, texT ); + // compute translation vector in plane axis base + tx = vector3_dot( delta, texS ); + ty = vector3_dot( delta, texT ); + // fill the data vectors + M[0][0]=tx; M[0][1]=1.0f+tx; M[0][2]=tx; + M[1][0]=ty; M[1][1]=ty; M[1][2]=1.0f+ty; + M[2][0]=1.0f; M[2][1]=1.0f; M[2][2]=1.0f; + D[0][0]=f->brushprimit_texdef.coords[0][2]; + D[0][1]=f->brushprimit_texdef.coords[0][0]+f->brushprimit_texdef.coords[0][2]; + D[0][2]=f->brushprimit_texdef.coords[0][1]+f->brushprimit_texdef.coords[0][2]; + D[1][0]=f->brushprimit_texdef.coords[1][2]; + D[1][1]=f->brushprimit_texdef.coords[1][0]+f->brushprimit_texdef.coords[1][2]; + D[1][2]=f->brushprimit_texdef.coords[1][1]+f->brushprimit_texdef.coords[1][2]; + // solve + det = SarrusDet( M[0], M[1], M[2] ); + f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det; + f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det; + f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det; + f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det; + f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det; + f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det; +} + +// shift a texture (texture adjustments) along it's current texture axes +// x and y are geometric values, which we must compute as ST increments +// this depends on the texture size and the pixel/texel ratio +void ShiftTextureRelative_BrushPrimit( face_t *f, float x, float y) +{ + float s,t; + // as a ratio against texture size + // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors) + s = (x * 2.0) / (float)f->pShader->getTexture().width; + t = (y * 2.0) / (float)f->pShader->getTexture().height; + f->brushprimit_texdef.coords[0][2] -= s; + f->brushprimit_texdef.coords[1][2] -= t; +} +#endif + +// TTimo: FIXME: I don't like that, it feels broken +// (and it's likely that it's not used anymore) +// best fitted 2D vector is x.X+y.Y +void ComputeBest2DVector( Vector3& v, Vector3& X, Vector3& Y, int &x, int &y ) +{ + double sx,sy; + sx = vector3_dot( v, X ); + sy = vector3_dot( v, Y ); + if ( fabs(sy) > fabs(sx) ) + { + x = 0; + if ( sy > 0.0 ) + y = 1; + else + y = -1; + } + else + { + y = 0; + if ( sx > 0.0 ) + x = 1; + else + x = -1; + } +} + + +#if 0 // texdef conversion +void BrushPrimitFaceToFace(face_t *face) +{ + // we have parsed brush primitives and need conversion back to standard format + // NOTE: converting back is a quick hack, there's some information lost and we can't do anything about it + // FIXME: if we normalize the texture matrix to a standard 2x2 size, we end up with wrong scaling + // I tried various tweaks, no luck .. seems shifting is lost + brushprimit_texdef_t aux; + ConvertTexMatWithQTexture( &face->brushprimit_texdef, face->pShader->getTexture(), &aux, 0 ); + TexMatToFakeTexCoords( aux.coords, face->texdef.shift, &face->texdef.rotate, face->texdef.scale ); + face->texdef.scale[0]/=2.0; + face->texdef.scale[1]/=2.0; +} +#endif + + +#if 0 // texture locking (brush primit) +// TEXTURE LOCKING ----------------------------------------------------------------------------------------------------- +// (Relevant to the editor only?) + +// internally used for texture locking on rotation and flipping +// the general algorithm is the same for both lockings, it's only the geometric transformation part that changes +// so I wanted to keep it in a single function +// if there are more linear transformations that need the locking, going to a C++ or code pointer solution would be best +// (but right now I want to keep brush_primit.cpp striclty C) + +bool txlock_bRotation; + +// rotation locking params +int txl_nAxis; +float txl_fDeg; +Vector3 txl_vOrigin; + +// flip locking params +Vector3 txl_matrix[3]; +Vector3 txl_origin; + +void TextureLockTransformation_BrushPrimit(face_t *f) +{ + Vector3 Orig,texS,texT; // axis base of initial plane + // used by transformation algo + Vector3 temp; int j; + Vector3 vRotate; // rotation vector + + Vector3 rOrig,rvecS,rvecT; // geometric transformation of (0,0) (1,0) (0,1) { initial plane axis base } + Vector3 rNormal,rtexS,rtexT; // axis base for the transformed plane + Vector3 lOrig,lvecS,lvecT; // [2] are not used ( but usefull for debugging ) + Vector3 M[3]; + float det; + Vector3 D[2]; + + // compute plane axis base + ComputeAxisBase( f->plane.normal, texS, texT ); + VectorSet(Orig, 0.0f, 0.0f, 0.0f); + + // compute coordinates of (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) after transformation + // (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) <-> (0,0,0) texS texT ( expressed world axis base ) + // input: Orig, texS, texT (and the global locking params) + // ouput: rOrig, rvecS, rvecT, rNormal + if (txlock_bRotation) { + // rotation vector + VectorSet( vRotate, 0.0f, 0.0f, 0.0f ); + vRotate[txl_nAxis]=txl_fDeg; + VectorRotateOrigin ( Orig, vRotate, txl_vOrigin, rOrig ); + VectorRotateOrigin ( texS, vRotate, txl_vOrigin, rvecS ); + VectorRotateOrigin ( texT, vRotate, txl_vOrigin, rvecT ); + // compute normal of plane after rotation + VectorRotate ( f->plane.normal, vRotate, rNormal ); + } + else + { + for (j=0 ; j<3 ; j++) + rOrig[j] = vector3_dot(vector3_subtracted(Orig, txl_origin), txl_matrix[j]) + txl_origin[j]; + for (j=0 ; j<3 ; j++) + rvecS[j] = vector3_dot(vector3_subtracted(texS, txl_origin), txl_matrix[j]) + txl_origin[j]; + for (j=0 ; j<3 ; j++) + rvecT[j] = vector3_dot(vector3_subtracted(texT, txl_origin), txl_matrix[j]) + txl_origin[j]; + // we also need the axis base of the target plane, apply the transformation matrix to the normal too.. + for (j=0 ; j<3 ; j++) + rNormal[j] = vector3_dot(f->plane.normal, txl_matrix[j]); + } + + // compute rotated plane axis base + ComputeAxisBase( rNormal, rtexS, rtexT ); + // compute S/T coordinates of the three points in rotated axis base ( in M matrix ) + lOrig[0] = vector3_dot( rOrig, rtexS ); + lOrig[1] = vector3_dot( rOrig, rtexT ); + lvecS[0] = vector3_dot( rvecS, rtexS ); + lvecS[1] = vector3_dot( rvecS, rtexT ); + lvecT[0] = vector3_dot( rvecT, rtexS ); + lvecT[1] = vector3_dot( rvecT, rtexT ); + M[0][0] = lOrig[0]; M[1][0] = lOrig[1]; M[2][0] = 1.0f; + M[0][1] = lvecS[0]; M[1][1] = lvecS[1]; M[2][1] = 1.0f; + M[0][2] = lvecT[0]; M[1][2] = lvecT[1]; M[2][2] = 1.0f; + // fill data vector + D[0][0]=f->brushprimit_texdef.coords[0][2]; + D[0][1]=f->brushprimit_texdef.coords[0][0]+f->brushprimit_texdef.coords[0][2]; + D[0][2]=f->brushprimit_texdef.coords[0][1]+f->brushprimit_texdef.coords[0][2]; + D[1][0]=f->brushprimit_texdef.coords[1][2]; + D[1][1]=f->brushprimit_texdef.coords[1][0]+f->brushprimit_texdef.coords[1][2]; + D[1][2]=f->brushprimit_texdef.coords[1][1]+f->brushprimit_texdef.coords[1][2]; + // solve + det = SarrusDet( M[0], M[1], M[2] ); + f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det; + f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det; + f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det; + f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det; + f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det; + f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det; +} + +// texture locking +// called before the points on the face are actually rotated +void RotateFaceTexture_BrushPrimit(face_t *f, int nAxis, float fDeg, Vector3& vOrigin ) +{ + // this is a placeholder to call the general texture locking algorithm + txlock_bRotation = true; + txl_nAxis = nAxis; + txl_fDeg = fDeg; + VectorCopy(vOrigin, txl_vOrigin); + TextureLockTransformation_BrushPrimit(f); +} + +// compute the new brush primit texture matrix for a transformation matrix and a flip order flag (change plane orientation) +// this matches the select_matrix algo used in select.cpp +// this needs to be called on the face BEFORE any geometric transformation +// it will compute the texture matrix that will represent the same texture on the face after the geometric transformation is done +void ApplyMatrix_BrushPrimit(face_t *f, Vector3 matrix[3], Vector3& origin) +{ + // this is a placeholder to call the general texture locking algorithm + txlock_bRotation = false; + VectorCopy(matrix[0], txl_matrix[0]); + VectorCopy(matrix[1], txl_matrix[1]); + VectorCopy(matrix[2], txl_matrix[2]); + VectorCopy(origin, txl_origin); + TextureLockTransformation_BrushPrimit(f); +} +#endif + +// don't do C==A! +void BPMatMul(float A[2][3], float B[2][3], float C[2][3]) +{ + C[0][0] = A[0][0]*B[0][0]+A[0][1]*B[1][0]; + C[1][0] = A[1][0]*B[0][0]+A[1][1]*B[1][0]; + C[0][1] = A[0][0]*B[0][1]+A[0][1]*B[1][1]; + C[1][1] = A[1][0]*B[0][1]+A[1][1]*B[1][1]; + C[0][2] = A[0][0]*B[0][2]+A[0][1]*B[1][2]+A[0][2]; + C[1][2] = A[1][0]*B[0][2]+A[1][1]*B[1][2]+A[1][2]; +} + +void BPMatDump(float A[2][3]) +{ + globalOutputStream() << "" << A[0][0] + << " " << A[0][1] + << " " << A[0][2] + << "\n" << A[1][0] + << " " << A[1][2] + << " " << A[1][2] + << "\n0 0 1\n"; +} + +void BPMatRotate(float A[2][3], float theta) +{ + float m[2][3]; + float aux[2][3]; + memset(&m, 0, sizeof(float)*6); + m[0][0] = static_cast(cos(degrees_to_radians(theta))); + m[0][1] = static_cast(-sin(degrees_to_radians(theta))); + m[1][0] = -m[0][1]; + m[1][1] = m[0][0]; + BPMatMul(A, m, aux); + BPMatCopy(aux,A); +} + +#if 0 // camera-relative texture shift +// get the relative axes of the current texturing +void BrushPrimit_GetRelativeAxes(face_t *f, Vector3& vecS, Vector3& vecT) +{ + float vS[2],vT[2]; + // first we compute them as expressed in plane axis base + // BP matrix has coordinates of plane axis base expressed in geometric axis base + // so we use the line vectors + vS[0] = f->brushprimit_texdef.coords[0][0]; + vS[1] = f->brushprimit_texdef.coords[0][1]; + vT[0] = f->brushprimit_texdef.coords[1][0]; + vT[1] = f->brushprimit_texdef.coords[1][1]; + // now compute those vectors in geometric space + Vector3 texS, texT; // axis base of the plane (geometric) + ComputeAxisBase(f->plane.normal, texS, texT); + // vecS[] = vS[0].texS[] + vS[1].texT[] + // vecT[] = vT[0].texS[] + vT[1].texT[] + vecS[0] = vS[0]*texS[0] + vS[1]*texT[0]; + vecS[1] = vS[0]*texS[1] + vS[1]*texT[1]; + vecS[2] = vS[0]*texS[2] + vS[1]*texT[2]; + vecT[0] = vT[0]*texS[0] + vT[1]*texT[0]; + vecT[1] = vT[0]*texS[1] + vT[1]*texT[1]; + vecT[2] = vT[0]*texS[2] + vT[1]*texT[2]; +} + +// brush primitive texture adjustments, use the camera view to map adjustments +// ShiftTextureRelative_BrushPrimit ( s , t ) will shift relative to the texture +void ShiftTextureRelative_Camera(face_t *f, int x, int y) +{ + Vector3 vecS, vecT; + float XY[2]; // the values we are going to send for translation + float sgn[2]; // +1 or -1 + int axis[2]; + CamWnd* pCam; + + // get the two relative texture axes for the current texturing + BrushPrimit_GetRelativeAxes(f, vecS, vecT); + + // center point of the face, project it on the camera space + Vector3 C; + VectorClear(C); + int i; + for (i=0; iface_winding->numpoints; i++) + { + VectorAdd(C,f->face_winding->point_at(i),C); + } + VectorScale(C,1.0/f->face_winding->numpoints,C); + + pCam = g_pParentWnd->GetCamWnd(); + pCam->MatchViewAxes(C, vecS, axis[0], sgn[0]); + pCam->MatchViewAxes(C, vecT, axis[1], sgn[1]); + + // this happens when the two directions can't be mapped on two different directions on the screen + // then the move will occur against a single axis + // (i.e. the user is not positioned well enough to send understandable shift commands) + // NOTE: in most cases this warning is not very relevant because the user would use one of the two axes + // for which the solution is easy (the other one being unknown) + // so this warning could be removed + if (axis[0] == axis[1]) + globalOutputStream() << "Warning: degenerate in ShiftTextureRelative_Camera\n"; + + // compute the X Y geometric increments + // those geometric increments will be applied along the texture axes (the ones we computed above) + XY[0] = 0; + XY[1] = 0; + if (x!=0) + { + // moving right/left + XY[axis[0]] += sgn[0]*x; + } + if (y!=0) + { + XY[axis[1]] += sgn[1]*y; + } + // we worked out a move along vecS vecT, and we now it's geometric amplitude + // apply it + ShiftTextureRelative_BrushPrimit(f, XY[0], XY[1]); +} +#endif + + +void BPTexdef_Assign(brushprimit_texdef_t& bp_td, const brushprimit_texdef_t& bp_other) +{ + bp_td = bp_other; +} + +void BPTexdef_Shift(brushprimit_texdef_t& bp_td, float s, float t) +{ + // shift a texture (texture adjustments) along it's current texture axes + // x and y are geometric values, which we must compute as ST increments + // this depends on the texture size and the pixel/texel ratio + // as a ratio against texture size + // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors) + bp_td.coords[0][2] -= s; + bp_td.coords[1][2] += t; +} + +void BPTexdef_Scale(brushprimit_texdef_t& bp_td, float s, float t) +{ + // apply same scale as the spinner button of the surface inspector + texdef_t texdef; + // compute fake shift scale rot + TexMatToFakeTexCoords( bp_td, texdef ); + // update + texdef.scale[0] += s; + texdef.scale[1] += t; + // compute new normalized texture matrix + FakeTexCoordsToTexMat( texdef, bp_td ); +} + +void BPTexdef_Rotate(brushprimit_texdef_t& bp_td, float angle) +{ + // apply same scale as the spinner button of the surface inspector + texdef_t texdef; + // compute fake shift scale rot + TexMatToFakeTexCoords( bp_td, texdef ); + // update + texdef.rotate += angle; + // compute new normalized texture matrix + FakeTexCoordsToTexMat( texdef, bp_td ); +} + +void BPTexdef_Construct(brushprimit_texdef_t& bp_td, std::size_t width, std::size_t height) +{ + bp_td.coords[0][0] = 1.0f; + bp_td.coords[1][1] = 1.0f; + ConvertTexMatWithDimensions(bp_td.coords, 2, 2, bp_td.coords, width, height); +} + +void Texdef_Assign(TextureProjection& projection, const TextureProjection& other) +{ + if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + BPTexdef_Assign(projection.m_brushprimit_texdef, other.m_brushprimit_texdef); + } + else + { + Texdef_Assign(projection.m_texdef, other.m_texdef); + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) + { + projection.m_basis_s = other.m_basis_s; + projection.m_basis_t = other.m_basis_t; + } + } +} + +void Texdef_Shift(TextureProjection& projection, float s, float t) +{ + if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + BPTexdef_Shift(projection.m_brushprimit_texdef, s, t); + } + else + { + Texdef_Shift(projection.m_texdef, s, t); + } +} + +void Texdef_Scale(TextureProjection& projection, float s, float t) +{ + if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + BPTexdef_Scale(projection.m_brushprimit_texdef, s, t); + } + else + { + Texdef_Scale(projection.m_texdef, s, t); + } +} + +void Texdef_Rotate(TextureProjection& projection, float angle) +{ + if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + BPTexdef_Rotate(projection.m_brushprimit_texdef, angle); + } + else + { + Texdef_Rotate(projection.m_texdef, angle); + } +} + +void Texdef_FitTexture(TextureProjection& projection, std::size_t width, std::size_t height, const Vector3& normal, const Winding& w, float s_repeat, float t_repeat) +{ + if(w.numpoints < 3) + { + return; + } + + Matrix4 st2tex; + Texdef_toTransform(projection, (float)width, (float)height, st2tex); + + // the current texture transform + Matrix4 local2tex = st2tex; + { + Matrix4 xyz2st; + Texdef_basisForNormal(projection, normal, xyz2st); + matrix4_multiply_by_matrix4(local2tex, xyz2st); + } + + // the bounds of the current texture transform + AABB bounds; + for(Winding::const_iterator i = w.begin(); i != w.end(); ++i) + { + Vector3 texcoord = matrix4_transformed_point(local2tex, (*i).vertex); + aabb_extend_by_point_safe(bounds, texcoord); + } + bounds.origin.z() = 0; + bounds.extents.z() = 1; + + // the bounds of a perfectly fitted texture transform + AABB perfect(Vector3(s_repeat * 0.5, t_repeat * 0.5, 0), Vector3(s_repeat * 0.5, t_repeat * 0.5, 1)); + + // the difference between the current texture transform and the perfectly fitted transform + Matrix4 matrix(matrix4_translation_for_vec3(bounds.origin - perfect.origin)); + matrix4_pivoted_scale_by_vec3(matrix, bounds.extents / perfect.extents, perfect.origin); + matrix4_affine_invert(matrix); + + // apply the difference to the current texture transform + matrix4_premultiply_by_matrix4(st2tex, matrix); + + Texdef_fromTransform(projection, (float)width, (float)height, st2tex); + Texdef_normalise(projection, (float)width, (float)height); +} + +float Texdef_getDefaultTextureScale() +{ + return g_texdef_default_scale; +} + +void TexDef_Construct_Default(TextureProjection& projection) +{ + projection.m_texdef.scale[0] = Texdef_getDefaultTextureScale(); + projection.m_texdef.scale[1] = Texdef_getDefaultTextureScale(); + + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + FakeTexCoordsToTexMat(projection.m_texdef, projection.m_brushprimit_texdef); + } +} + + + +void ShiftScaleRotate_fromFace(texdef_t& shiftScaleRotate, const TextureProjection& projection) +{ + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + TexMatToFakeTexCoords(projection.m_brushprimit_texdef, shiftScaleRotate); + } + else + { + shiftScaleRotate = projection.m_texdef; + } +} + +void ShiftScaleRotate_toFace(const texdef_t& shiftScaleRotate, TextureProjection& projection) +{ + if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + // compute texture matrix + // the matrix returned must be understood as a qtexture_t with width=2 height=2 + FakeTexCoordsToTexMat( shiftScaleRotate, projection.m_brushprimit_texdef ); + } + else + { + projection.m_texdef = shiftScaleRotate; + } +} + + +inline void print_vector3(const Vector3& v) +{ + globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n"; +} + +inline void print_3x3(const Matrix4& m) +{ + globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) " + << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) " + << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n"; +} + + +inline Matrix4 matrix4_rotation_for_vector3(const Vector3& x, const Vector3& y, const Vector3& z) +{ + return Matrix4( + x.x(), x.y(), x.z(), 0, + y.x(), y.y(), y.z(), 0, + z.x(), z.y(), z.z(), 0, + 0, 0, 0, 1 + ); +} + +inline Matrix4 matrix4_swap_axes(const Vector3& from, const Vector3& to) +{ + if(from.x() != 0 && to.y() != 0) + { + return matrix4_rotation_for_vector3(to, from, g_vector3_axis_z); + } + + if(from.x() != 0 && to.z() != 0) + { + return matrix4_rotation_for_vector3(to, g_vector3_axis_y, from); + } + + if(from.y() != 0 && to.z() != 0) + { + return matrix4_rotation_for_vector3(g_vector3_axis_x, to, from); + } + + if(from.y() != 0 && to.x() != 0) + { + return matrix4_rotation_for_vector3(from, to, g_vector3_axis_z); + } + + if(from.z() != 0 && to.x() != 0) + { + return matrix4_rotation_for_vector3(from, g_vector3_axis_y, to); + } + + if(from.z() != 0 && to.y() != 0) + { + return matrix4_rotation_for_vector3(g_vector3_axis_x, from, to); + } + + ERROR_MESSAGE("unhandled axis swap case"); + + return g_matrix4_identity; +} + +inline Matrix4 matrix4_reflection_for_plane(const Plane3& plane) +{ + return Matrix4( + static_cast(1 - (2 * plane.a * plane.a)), + static_cast(-2 * plane.a * plane.b), + static_cast(-2 * plane.a * plane.c), + 0, + static_cast(-2 * plane.b * plane.a), + static_cast(1 - (2 * plane.b * plane.b)), + static_cast(-2 * plane.b * plane.c), + 0, + static_cast(-2 * plane.c * plane.a), + static_cast(-2 * plane.c * plane.b), + static_cast(1 - (2 * plane.c * plane.c)), + 0, + static_cast(-2 * plane.d * plane.a), + static_cast(-2 * plane.d * plane.b), + static_cast(-2 * plane.d * plane.c), + 1 + ); +} + +inline Matrix4 matrix4_reflection_for_plane45(const Plane3& plane, const Vector3& from, const Vector3& to) +{ + Vector3 first = from; + Vector3 second = to; + + if(vector3_dot(from, plane.normal()) > 0 == vector3_dot(to, plane.normal()) > 0) + { + first = vector3_negated(first); + second = vector3_negated(second); + } + +#if 0 + globalOutputStream() << "normal: "; + print_vector3(plane.normal()); + + globalOutputStream() << "from: "; + print_vector3(first); + + globalOutputStream() << "to: "; + print_vector3(second); +#endif + + Matrix4 swap = matrix4_swap_axes(first, second); + + Matrix4 tmp = matrix4_reflection_for_plane(plane); + + swap.tx() = -static_cast(-2 * plane.a * plane.d); + swap.ty() = -static_cast(-2 * plane.b * plane.d); + swap.tz() = -static_cast(-2 * plane.c * plane.d); + + return swap; +} + +void Texdef_transformLocked(TextureProjection& projection, std::size_t width, std::size_t height, const Plane3& plane, const Matrix4& identity2transformed) +{ + //globalOutputStream() << "identity2transformed: " << identity2transformed << "\n"; + + //globalOutputStream() << "plane.normal(): " << plane.normal() << "\n"; + + Vector3 normalTransformed(matrix4_transformed_direction(identity2transformed, plane.normal())); + + //globalOutputStream() << "normalTransformed: " << normalTransformed << "\n"; + + // identity: identity space + // transformed: transformation + // stIdentity: base st projection space before transformation + // stTransformed: base st projection space after transformation + // stOriginal: original texdef space + + // stTransformed2stOriginal = stTransformed -> transformed -> identity -> stIdentity -> stOriginal + + Matrix4 identity2stIdentity; + Texdef_basisForNormal(projection, plane.normal(), identity2stIdentity); + //globalOutputStream() << "identity2stIdentity: " << identity2stIdentity << "\n"; + + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE) + { + matrix4_transform_direction(identity2transformed, projection.m_basis_s); + matrix4_transform_direction(identity2transformed, projection.m_basis_t); + } + + Matrix4 transformed2stTransformed; + Texdef_basisForNormal(projection, normalTransformed, transformed2stTransformed); + + Matrix4 stTransformed2identity(matrix4_affine_inverse(matrix4_multiplied_by_matrix4(transformed2stTransformed, identity2transformed))); + + Vector3 originalProjectionAxis(vector4_to_vector3(matrix4_affine_inverse(identity2stIdentity).z())); + + Vector3 transformedProjectionAxis(vector4_to_vector3(stTransformed2identity.z())); + + Matrix4 stIdentity2stOriginal; + Texdef_toTransform(projection, (float)width, (float)height, stIdentity2stOriginal); + Matrix4 identity2stOriginal(matrix4_multiplied_by_matrix4(stIdentity2stOriginal, identity2stIdentity)); + + //globalOutputStream() << "originalProj: " << originalProjectionAxis << "\n"; + //globalOutputStream() << "transformedProj: " << transformedProjectionAxis << "\n"; + double dot = vector3_dot(originalProjectionAxis, transformedProjectionAxis); + //globalOutputStream() << "dot: " << dot << "\n"; + if(dot == 0) + { + // The projection axis chosen for the transformed normal is at 90 degrees + // to the transformed projection axis chosen for the original normal. + // This happens when the projection axis is ambiguous - e.g. for the plane + // 'X == Y' the projection axis could be either X or Y. + //globalOutputStream() << "flipped\n"; +#if 0 + globalOutputStream() << "projection off by 90\n"; + globalOutputStream() << "normal: "; + print_vector3(plane.normal()); + globalOutputStream() << "original projection: "; + print_vector3(originalProjectionAxis); + globalOutputStream() << "transformed projection: "; + print_vector3(transformedProjectionAxis); +#endif + + Matrix4 identityCorrected = matrix4_reflection_for_plane45(plane, originalProjectionAxis, transformedProjectionAxis); + + identity2stOriginal = matrix4_multiplied_by_matrix4(identity2stOriginal, identityCorrected); + } + + Matrix4 stTransformed2stOriginal = matrix4_multiplied_by_matrix4(identity2stOriginal, stTransformed2identity); + + Texdef_fromTransform(projection, (float)width, (float)height, stTransformed2stOriginal); + Texdef_normalise(projection, (float)width, (float)height); +} + +#if 1 +void Q3_to_matrix(const texdef_t& texdef, float width, float height, const Vector3& normal, Matrix4& matrix) +{ + Normal_GetTransform(normal, matrix); + + Matrix4 transform; + + Texdef_toTransform(texdef, width, height, transform); + + matrix4_multiply_by_matrix4(matrix, transform); +} + +void BP_from_matrix(brushprimit_texdef_t& bp_texdef, const Vector3& normal, const Matrix4& transform) +{ + Matrix4 basis; + basis = g_matrix4_identity; + ComputeAxisBase(normal, vector4_to_vector3(basis.x()), vector4_to_vector3(basis.y())); + vector4_to_vector3(basis.z()) = normal; + matrix4_transpose(basis); + matrix4_affine_invert(basis); + + Matrix4 basis2texture = matrix4_multiplied_by_matrix4(basis, transform); + + BPTexdef_fromTransform(bp_texdef, basis2texture); +} + +void Q3_to_BP(const texdef_t& texdef, float width, float height, const Vector3& normal, brushprimit_texdef_t& bp_texdef) +{ + Matrix4 matrix; + Q3_to_matrix(texdef, width, height, normal, matrix); + BP_from_matrix(bp_texdef, normal, matrix); +} +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brush_primit.h b/misc/mediasource/netradiant-src/radiant/brush_primit.h new file mode 100644 index 00000000..590fba94 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brush_primit.h @@ -0,0 +1,142 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_BRUSH_PRIMIT_H) +#define INCLUDED_BRUSH_PRIMIT_H + +#include "math/vector.h" +#include "itexdef.h" +#include "debugging/debugging.h" +// Timo +// new brush primitive texdef +struct brushprimit_texdef_t +{ + brushprimit_texdef_t() + { + coords[0][0] = 2.0f; + coords[0][1] = 0.f; + coords[0][2] = 0.f; + coords[1][0] = 0.f; + coords[1][1] = 2.0f; + coords[1][2] = 0.f; + } + void removeScale(std::size_t width, std::size_t height) + { +#if 1 + coords[0][0] *= width; + coords[0][1] *= width; + coords[0][2] *= width; + coords[1][0] *= height; + coords[1][1] *= height; + coords[1][2] *= height; +#endif + } + void addScale(std::size_t width, std::size_t height) + { +#if 1 + ASSERT_MESSAGE(width > 0, "shader-width is 0"); + ASSERT_MESSAGE(height > 0, "shader-height is 0"); + coords[0][0] /= width; + coords[0][1] /= width; + coords[0][2] /= width; + coords[1][0] /= height; + coords[1][1] /= height; + coords[1][2] /= height; +#endif + } + float coords[2][3]; +}; + +class TextureProjection +{ +public: + texdef_t m_texdef; + brushprimit_texdef_t m_brushprimit_texdef; + Vector3 m_basis_s; + Vector3 m_basis_t; + + TextureProjection() + { + } + TextureProjection( + const texdef_t& texdef, + const brushprimit_texdef_t& brushprimit_texdef, + const Vector3& basis_s, + const Vector3& basis_t + ) : + m_texdef(texdef), + m_brushprimit_texdef(brushprimit_texdef), + m_basis_s(basis_s), + m_basis_t(basis_t) + { + } +}; + +float Texdef_getDefaultTextureScale(); + +class texdef_t; +struct Winding; +template class BasicVector3; +typedef BasicVector3 Vector3; +template class BasicVector4; +typedef BasicVector4 Vector4; +typedef Vector4 Quaternion; +class Matrix4; +class Plane3; + +void Normal_GetTransform(const Vector3& normal, Matrix4& transform); + +void TexDef_Construct_Default(TextureProjection& projection); + +void Texdef_Assign(TextureProjection& projection, const TextureProjection& other); +void Texdef_Shift(TextureProjection& projection, float s, float t); +void Texdef_Scale(TextureProjection& projection, float s, float t); +void Texdef_Rotate(TextureProjection& projection, float angle); +void Texdef_FitTexture(TextureProjection& projection, std::size_t width, std::size_t height, const Vector3& normal, const Winding& w, float s_repeat, float t_repeat); +void Texdef_EmitTextureCoordinates(const TextureProjection& projection, std::size_t width, std::size_t height, Winding& w, const Vector3& normal, const Matrix4& localToWorld); + +void ShiftScaleRotate_fromFace(texdef_t& shiftScaleRotate, const TextureProjection& projection); +void ShiftScaleRotate_toFace(const texdef_t& shiftScaleRotate, TextureProjection& projection); + +void Texdef_transformLocked(TextureProjection& projection, std::size_t width, std::size_t height, const Plane3& plane, const Matrix4& transform); +void Texdef_normalise(TextureProjection& projection, float width, float height); + +enum TexdefTypeId +{ + TEXDEFTYPEID_QUAKE, + TEXDEFTYPEID_BRUSHPRIMITIVES, + TEXDEFTYPEID_HALFLIFE, +}; + +struct bp_globals_t +{ + // tells if we are internally using brush primitive (texture coordinates and map format) + // this is a shortcut for IntForKey( g_qeglobals.d_project_entity, "brush_primit" ) + // NOTE: must keep the two ones in sync + TexdefTypeId m_texdefTypeId; +}; + +extern bp_globals_t g_bp_globals; +extern float g_texdef_default_scale; + +void ComputeAxisBase(const Vector3& normal, Vector3& texS, Vector3& texT); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brushmanip.cpp b/misc/mediasource/netradiant-src/radiant/brushmanip.cpp new file mode 100644 index 00000000..ca367100 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushmanip.cpp @@ -0,0 +1,1571 @@ +/* +Copyright (C) 1999-2006 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 "brushmanip.h" + + +#include "gtkutil/widget.h" +#include "gtkutil/menu.h" +#include "gtkmisc.h" +#include "brushnode.h" +#include "map.h" +#include "texwindow.h" +#include "gtkdlgs.h" +#include "commands.h" +#include "mainframe.h" +#include "dialog.h" +#include "xywindow.h" +#include "preferences.h" + +#include + +void Brush_ConstructCuboid(Brush& brush, const AABB& bounds, const char* shader, const TextureProjection& projection) +{ + const unsigned char box[3][2] = { { 0, 1 }, { 2, 0 }, { 1, 2 } }; + Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); + Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); + + brush.clear(); + brush.reserve(6); + + { + for(int i=0; i < 3; ++i) + { + Vector3 planepts1(maxs); + Vector3 planepts2(maxs); + planepts2[box[i][0]] = mins[box[i][0]]; + planepts1[box[i][1]] = mins[box[i][1]]; + + brush.addPlane(maxs, planepts1, planepts2, shader, projection); + } + } + { + for(int i=0; i < 3; ++i) + { + Vector3 planepts1(mins); + Vector3 planepts2(mins); + planepts1[box[i][0]] = maxs[box[i][0]]; + planepts2[box[i][1]] = maxs[box[i][1]]; + + brush.addPlane(mins, planepts1, planepts2, shader, projection); + } + } +} + +inline float max_extent(const Vector3& extents) +{ + return std::max(std::max(extents[0], extents[1]), extents[2]); +} + +inline float max_extent_2d(const Vector3& extents, int axis) +{ + switch(axis) + { + case 0: + return std::max(extents[1], extents[2]); + case 1: + return std::max(extents[0], extents[2]); + default: + return std::max(extents[0], extents[1]); + } +} + +const std::size_t c_brushPrism_minSides = 3; +const std::size_t c_brushPrism_maxSides = c_brush_maxFaces - 2; +const char* const c_brushPrism_name = "brushPrism"; + +void Brush_ConstructPrism(Brush& brush, const AABB& bounds, std::size_t sides, int axis, const char* shader, const TextureProjection& projection) +{ + if(sides < c_brushPrism_minSides) + { + globalErrorStream() << c_brushPrism_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushPrism_minSides) << "\n"; + return; + } + if(sides > c_brushPrism_maxSides) + { + globalErrorStream() << c_brushPrism_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushPrism_maxSides) << "\n"; + return; + } + + brush.clear(); + brush.reserve(sides+2); + + Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); + Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); + + float radius = max_extent_2d(bounds.extents, axis); + const Vector3& mid = bounds.origin; + Vector3 planepts[3]; + + planepts[2][(axis+1)%3] = mins[(axis+1)%3]; + planepts[2][(axis+2)%3] = mins[(axis+2)%3]; + planepts[2][axis] = maxs[axis]; + planepts[1][(axis+1)%3] = maxs[(axis+1)%3]; + planepts[1][(axis+2)%3] = mins[(axis+2)%3]; + planepts[1][axis] = maxs[axis]; + planepts[0][(axis+1)%3] = maxs[(axis+1)%3]; + planepts[0][(axis+2)%3] = maxs[(axis+2)%3]; + planepts[0][axis] = maxs[axis]; + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + + planepts[0][(axis+1)%3] = mins[(axis+1)%3]; + planepts[0][(axis+2)%3] = mins[(axis+2)%3]; + planepts[0][axis] = mins[axis]; + planepts[1][(axis+1)%3] = maxs[(axis+1)%3]; + planepts[1][(axis+2)%3] = mins[(axis+2)%3]; + planepts[1][axis] = mins[axis]; + planepts[2][(axis+1)%3] = maxs[(axis+1)%3]; + planepts[2][(axis+2)%3] = maxs[(axis+2)%3]; + planepts[2][axis] = mins[axis]; + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + + for (std::size_t i=0 ; i(floor(mid[(axis+1)%3]+radius*cv+0.5)); + planepts[0][(axis+2)%3] = static_cast(floor(mid[(axis+2)%3]+radius*sv+0.5)); + planepts[0][axis] = mins[axis]; + + planepts[1][(axis+1)%3] = planepts[0][(axis+1)%3]; + planepts[1][(axis+2)%3] = planepts[0][(axis+2)%3]; + planepts[1][axis] = maxs[axis]; + + planepts[2][(axis+1)%3] = static_cast(floor(planepts[0][(axis+1)%3] - radius*sv + 0.5)); + planepts[2][(axis+2)%3] = static_cast(floor(planepts[0][(axis+2)%3] + radius*cv + 0.5)); + planepts[2][axis] = maxs[axis]; + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + } +} + +const std::size_t c_brushCone_minSides = 3; +const std::size_t c_brushCone_maxSides = 32; +const char* const c_brushCone_name = "brushCone"; + +void Brush_ConstructCone(Brush& brush, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) +{ + if(sides < c_brushCone_minSides) + { + globalErrorStream() << c_brushCone_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushCone_minSides) << "\n"; + return; + } + if(sides > c_brushCone_maxSides) + { + globalErrorStream() << c_brushCone_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushCone_maxSides) << "\n"; + return; + } + + brush.clear(); + brush.reserve(sides+1); + + Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); + Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); + + float radius = max_extent(bounds.extents); + const Vector3& mid = bounds.origin; + Vector3 planepts[3]; + + planepts[0][0] = mins[0];planepts[0][1] = mins[1];planepts[0][2] = mins[2]; + planepts[1][0] = maxs[0];planepts[1][1] = mins[1];planepts[1][2] = mins[2]; + planepts[2][0] = maxs[0];planepts[2][1] = maxs[1];planepts[2][2] = mins[2]; + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + + for (std::size_t i=0 ; i(floor(mid[0]+radius*cv+0.5)); + planepts[0][1] = static_cast(floor(mid[1]+radius*sv+0.5)); + planepts[0][2] = mins[2]; + + planepts[1][0] = mid[0]; + planepts[1][1] = mid[1]; + planepts[1][2] = maxs[2]; + + planepts[2][0] = static_cast(floor(planepts[0][0] - radius * sv + 0.5)); + planepts[2][1] = static_cast(floor(planepts[0][1] + radius * cv + 0.5)); + planepts[2][2] = maxs[2]; + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + } +} + +const std::size_t c_brushSphere_minSides = 3; +const std::size_t c_brushSphere_maxSides = 31; +const char* const c_brushSphere_name = "brushSphere"; + +void Brush_ConstructSphere(Brush& brush, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) +{ + if(sides < c_brushSphere_minSides) + { + globalErrorStream() << c_brushSphere_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushSphere_minSides) << "\n"; + return; + } + if(sides > c_brushSphere_maxSides) + { + globalErrorStream() << c_brushSphere_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushSphere_maxSides) << "\n"; + return; + } + + brush.clear(); + brush.reserve(sides*sides); + + float radius = max_extent(bounds.extents); + const Vector3& mid = bounds.origin; + Vector3 planepts[3]; + + double dt = 2 * c_pi / sides; + double dp = c_pi / sides; + for(std::size_t i=0; i < sides; i++) + { + for(std::size_t j=0;j < sides-1; j++) + { + double t = i * dt; + double p = float(j * dp - c_pi / 2); + + planepts[0] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t, p), radius)); + planepts[1] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t, p + dp), radius)); + planepts[2] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t + dt, p + dp), radius)); + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + } + } + + { + double p = (sides - 1) * dp - c_pi / 2; + for(std::size_t i = 0; i < sides; i++) + { + double t = i * dt; + + planepts[0] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t, p), radius)); + planepts[1] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t + dt, p + dp), radius)); + planepts[2] = vector3_added(mid, vector3_scaled(vector3_for_spherical(t + dt, p), radius)); + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + } + } +} + +const std::size_t c_brushRock_minSides = 10; +const std::size_t c_brushRock_maxSides = 1000; +const char* const c_brushRock_name = "brushRock"; + +void Brush_ConstructRock(Brush& brush, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) +{ + if(sides < c_brushRock_minSides) + { + globalErrorStream() << c_brushRock_name << ": sides " << Unsigned(sides) << ": too few sides, minimum is " << Unsigned(c_brushRock_minSides) << "\n"; + return; + } + if(sides > c_brushRock_maxSides) + { + globalErrorStream() << c_brushRock_name << ": sides " << Unsigned(sides) << ": too many sides, maximum is " << Unsigned(c_brushRock_maxSides) << "\n"; + return; + } + + brush.clear(); + brush.reserve(sides*sides); + + float radius = max_extent(bounds.extents); + const Vector3& mid = bounds.origin; + Vector3 planepts[3]; + + for(std::size_t j=0;j < sides; j++) + { + planepts[0][0] = rand() - (RAND_MAX/2); + planepts[0][1] = rand() - (RAND_MAX/2); + planepts[0][2] = rand() - (RAND_MAX/2); + vector3_normalise(planepts[0]); + + // find two vectors that are perpendicular to planepts[0] + ComputeAxisBase(planepts[0], planepts[1], planepts[2]); + + planepts[0] = vector3_added(mid, vector3_scaled(planepts[0], radius)); + planepts[1] = vector3_added(planepts[0], vector3_scaled(planepts[1], radius)); + planepts[2] = vector3_added(planepts[0], vector3_scaled(planepts[2], radius)); + +#if 0 + // make sure the orientation is right + if(vector3_dot(vector3_subtracted(planepts[0], mid), vector3_cross(vector3_subtracted(planepts[1], mid), vector3_subtracted(planepts[2], mid))) > 0) + { + Vector3 h; + h = planepts[1]; + planepts[1] = planepts[2]; + planepts[2] = h; + globalOutputStream() << "flip\n"; + } + else + globalOutputStream() << "no flip\n"; +#endif + + brush.addPlane(planepts[0], planepts[1], planepts[2], shader, projection); + } +} + +int GetViewAxis() +{ + switch(GlobalXYWnd_getCurrentViewType()) + { + case XY: + return 2; + case XZ: + return 1; + case YZ: + return 0; + } + return 2; +} + +void Brush_ConstructPrefab(Brush& brush, EBrushPrefab type, const AABB& bounds, std::size_t sides, const char* shader, const TextureProjection& projection) +{ + switch(type) + { + case eBrushCuboid: + { + UndoableCommand undo("brushCuboid"); + + Brush_ConstructCuboid(brush, bounds, shader, projection); + } + break; + case eBrushPrism: + { + int axis = GetViewAxis(); + StringOutputStream command; + command << c_brushPrism_name << " -sides " << Unsigned(sides) << " -axis " << axis; + UndoableCommand undo(command.c_str()); + + Brush_ConstructPrism(brush, bounds, sides, axis, shader, projection); + } + break; + case eBrushCone: + { + StringOutputStream command; + command << c_brushCone_name << " -sides " << Unsigned(sides); + UndoableCommand undo(command.c_str()); + + Brush_ConstructCone(brush, bounds, sides, shader, projection); + } + break; + case eBrushSphere: + { + StringOutputStream command; + command << c_brushSphere_name << " -sides " << Unsigned(sides); + UndoableCommand undo(command.c_str()); + + Brush_ConstructSphere(brush, bounds, sides, shader, projection); + } + break; + case eBrushRock: + { + StringOutputStream command; + command << c_brushRock_name << " -sides " << Unsigned(sides); + UndoableCommand undo(command.c_str()); + + Brush_ConstructRock(brush, bounds, sides, shader, projection); + } + break; + } +} + + +void ConstructRegionBrushes(scene::Node* brushes[6], const Vector3& region_mins, const Vector3& region_maxs) +{ + { + // set mins + Vector3 mins(region_mins[0]-32, region_mins[1]-32, region_mins[2]-32); + + // vary maxs + for(std::size_t i=0; i<3; i++) + { + Vector3 maxs(region_maxs[0]+32, region_maxs[1]+32, region_maxs[2]+32); + maxs[i] = region_mins[i]; + Brush_ConstructCuboid(*Node_getBrush(*brushes[i]), aabb_for_minmax(mins, maxs), texdef_name_default(), TextureProjection()); + } + } + + { + // set maxs + Vector3 maxs(region_maxs[0]+32, region_maxs[1]+32, region_maxs[2]+32); + + // vary mins + for(std::size_t i=0; i<3; i++) + { + Vector3 mins(region_mins[0]-32, region_mins[1]-32, region_mins[2]-32); + mins[i] = region_maxs[i]; + Brush_ConstructCuboid(*Node_getBrush(*brushes[i+3]), aabb_for_minmax(mins, maxs), texdef_name_default(), TextureProjection()); + } + } +} + + +class FaceSetTexdef +{ + const TextureProjection& m_projection; +public: + FaceSetTexdef(const TextureProjection& projection) : m_projection(projection) + { + } + void operator()(Face& face) const + { + face.SetTexdef(m_projection); + } +}; + +void Scene_BrushSetTexdef_Selected(scene::Graph& graph, const TextureProjection& projection) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetTexdef(projection)); + SceneChangeNotify(); +} + +void Scene_BrushSetTexdef_Component_Selected(scene::Graph& graph, const TextureProjection& projection) +{ + Scene_ForEachSelectedBrushFace(graph, FaceSetTexdef(projection)); + SceneChangeNotify(); +} + + +class FaceSetFlags +{ + const ContentsFlagsValue& m_projection; +public: + FaceSetFlags(const ContentsFlagsValue& flags) : m_projection(flags) + { + } + void operator()(Face& face) const + { + face.SetFlags(m_projection); + } +}; + +void Scene_BrushSetFlags_Selected(scene::Graph& graph, const ContentsFlagsValue& flags) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetFlags(flags)); + SceneChangeNotify(); +} + +void Scene_BrushSetFlags_Component_Selected(scene::Graph& graph, const ContentsFlagsValue& flags) +{ + Scene_ForEachSelectedBrushFace(graph, FaceSetFlags(flags)); + SceneChangeNotify(); +} + +class FaceShiftTexdef +{ + float m_s, m_t; +public: + FaceShiftTexdef(float s, float t) : m_s(s), m_t(t) + { + } + void operator()(Face& face) const + { + face.ShiftTexdef(m_s, m_t); + } +}; + +void Scene_BrushShiftTexdef_Selected(scene::Graph& graph, float s, float t) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceShiftTexdef(s, t)); + SceneChangeNotify(); +} + +void Scene_BrushShiftTexdef_Component_Selected(scene::Graph& graph, float s, float t) +{ + Scene_ForEachSelectedBrushFace(graph, FaceShiftTexdef(s, t)); + SceneChangeNotify(); +} + +class FaceScaleTexdef +{ + float m_s, m_t; +public: + FaceScaleTexdef(float s, float t) : m_s(s), m_t(t) + { + } + void operator()(Face& face) const + { + face.ScaleTexdef(m_s, m_t); + } +}; + +void Scene_BrushScaleTexdef_Selected(scene::Graph& graph, float s, float t) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceScaleTexdef(s, t)); + SceneChangeNotify(); +} + +void Scene_BrushScaleTexdef_Component_Selected(scene::Graph& graph, float s, float t) +{ + Scene_ForEachSelectedBrushFace(graph, FaceScaleTexdef(s, t)); + SceneChangeNotify(); +} + +class FaceRotateTexdef +{ + float m_angle; +public: + FaceRotateTexdef(float angle) : m_angle(angle) + { + } + void operator()(Face& face) const + { + face.RotateTexdef(m_angle); + } +}; + +void Scene_BrushRotateTexdef_Selected(scene::Graph& graph, float angle) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceRotateTexdef(angle)); + SceneChangeNotify(); +} + +void Scene_BrushRotateTexdef_Component_Selected(scene::Graph& graph, float angle) +{ + Scene_ForEachSelectedBrushFace(graph, FaceRotateTexdef(angle)); + SceneChangeNotify(); +} + + +class FaceSetShader +{ + const char* m_name; +public: + FaceSetShader(const char* name) : m_name(name) {} + void operator()(Face& face) const + { + face.SetShader(m_name); + } +}; + +void Scene_BrushSetShader_Selected(scene::Graph& graph, const char* name) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetShader(name)); + SceneChangeNotify(); +} + +void Scene_BrushSetShader_Component_Selected(scene::Graph& graph, const char* name) +{ + Scene_ForEachSelectedBrushFace(graph, FaceSetShader(name)); + SceneChangeNotify(); +} + +class FaceSetDetail +{ + bool m_detail; +public: + FaceSetDetail(bool detail) : m_detail(detail) + { + } + void operator()(Face& face) const + { + face.setDetail(m_detail); + } +}; + +void Scene_BrushSetDetail_Selected(scene::Graph& graph, bool detail) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceSetDetail(detail)); + SceneChangeNotify(); +} + +bool Face_FindReplaceShader(Face& face, const char* find, const char* replace) +{ + if(shader_equal(face.GetShader(), find)) + { + face.SetShader(replace); + return true; + } + return false; +} + +class FaceFindReplaceShader +{ + const char* m_find; + const char* m_replace; +public: + FaceFindReplaceShader(const char* find, const char* replace) : m_find(find), m_replace(replace) + { + } + void operator()(Face& face) const + { + Face_FindReplaceShader(face, m_find, m_replace); + } +}; + +class FaceFindShader +{ + const char* m_find; + const char* m_replace; +public: + FaceFindShader(const char* find) : m_find(find) + { + } + void operator()(FaceInstance& faceinst) const + { + if(shader_equal(faceinst.getFace().GetShader(), m_find)) + { + faceinst.setSelected(SelectionSystem::eFace, true); + } + } +}; + +bool DoingSearch(const char *repl) +{ + return (repl == NULL || (strcmp("textures/", repl)==0)); +} + +void Scene_BrushFindReplaceShader(scene::Graph& graph, const char* find, const char* replace) +{ + if (DoingSearch(replace)) + { + Scene_ForEachBrush_ForEachFaceInstance(graph, FaceFindShader(find)); + } + else + { + Scene_ForEachBrush_ForEachFace(graph, FaceFindReplaceShader(find, replace)); + } +} + +void Scene_BrushFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace) +{ + if (DoingSearch(replace)) + { + Scene_ForEachSelectedBrush_ForEachFaceInstance(graph, + FaceFindShader(find)); + } + else + { + Scene_ForEachSelectedBrush_ForEachFace(graph, + FaceFindReplaceShader(find, replace)); + } +} + +// TODO: find for components +// d1223m: dont even know what they are... +void Scene_BrushFindReplaceShader_Component_Selected(scene::Graph& graph, const char* find, const char* replace) +{ + if (DoingSearch(replace)) + { + + } + else + { + Scene_ForEachSelectedBrushFace(graph, FaceFindReplaceShader(find, replace)); + } +} + + +class FaceFitTexture +{ + float m_s_repeat, m_t_repeat; +public: + FaceFitTexture(float s_repeat, float t_repeat) : m_s_repeat(s_repeat), m_t_repeat(t_repeat) + { + } + void operator()(Face& face) const + { + face.FitTexture(m_s_repeat, m_t_repeat); + } +}; + +void Scene_BrushFitTexture_Selected(scene::Graph& graph, float s_repeat, float t_repeat) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceFitTexture(s_repeat, t_repeat)); + SceneChangeNotify(); +} + +void Scene_BrushFitTexture_Component_Selected(scene::Graph& graph, float s_repeat, float t_repeat) +{ + Scene_ForEachSelectedBrushFace(graph, FaceFitTexture(s_repeat, t_repeat)); + SceneChangeNotify(); +} + +TextureProjection g_defaultTextureProjection; +const TextureProjection& TextureTransform_getDefault() +{ + TexDef_Construct_Default(g_defaultTextureProjection); + return g_defaultTextureProjection; +} + +void Scene_BrushConstructPrefab(scene::Graph& graph, EBrushPrefab type, std::size_t sides, const char* shader) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); + + Brush* brush = Node_getBrush(path.top()); + if(brush != 0) + { + AABB bounds = brush->localAABB(); // copy bounds because the brush will be modified + Brush_ConstructPrefab(*brush, type, bounds, sides, shader, TextureTransform_getDefault()); + SceneChangeNotify(); + } + } +} + +void Scene_BrushResize_Selected(scene::Graph& graph, const AABB& bounds, const char* shader) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); + + Brush* brush = Node_getBrush(path.top()); + if(brush != 0) + { + Brush_ConstructCuboid(*brush, bounds, shader, TextureTransform_getDefault()); + SceneChangeNotify(); + } + } +} + +bool Brush_hasShader(const Brush& brush, const char* name) +{ + for(Brush::const_iterator i = brush.begin(); i != brush.end(); ++i) + { + if(shader_equal((*i)->GetShader(), name)) + { + return true; + } + } + return false; +} + +class BrushSelectByShaderWalker : public scene::Graph::Walker +{ + const char* m_name; +public: + BrushSelectByShaderWalker(const char* name) + : m_name(name) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Brush* brush = Node_getBrush(path.top()); + if(brush != 0 && Brush_hasShader(*brush, m_name)) + { + Instance_getSelectable(instance)->setSelected(true); + } + } + return true; + } +}; + +void Scene_BrushSelectByShader(scene::Graph& graph, const char* name) +{ + graph.traverse(BrushSelectByShaderWalker(name)); +} + +class FaceSelectByShader +{ + const char* m_name; +public: + FaceSelectByShader(const char* name) + : m_name(name) + { + } + void operator()(FaceInstance& face) const + { + printf("checking %s = %s\n", face.getFace().GetShader(), m_name); + if(shader_equal(face.getFace().GetShader(), m_name)) + { + face.setSelected(SelectionSystem::eFace, true); + } + } +}; + +void Scene_BrushSelectByShader_Component(scene::Graph& graph, const char* name) +{ + Scene_ForEachSelectedBrush_ForEachFaceInstance(graph, FaceSelectByShader(name)); +} + +class FaceGetTexdef +{ + TextureProjection& m_projection; + mutable bool m_done; +public: + FaceGetTexdef(TextureProjection& projection) + : m_projection(projection), m_done(false) + { + } + void operator()(Face& face) const + { + if(!m_done) + { + m_done = true; + face.GetTexdef(m_projection); + } + } +}; + + +void Scene_BrushGetTexdef_Selected(scene::Graph& graph, TextureProjection& projection) +{ + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceGetTexdef(projection)); +} + +void Scene_BrushGetTexdef_Component_Selected(scene::Graph& graph, TextureProjection& projection) +{ +#if 1 + if(!g_SelectedFaceInstances.empty()) + { + FaceInstance& faceInstance = g_SelectedFaceInstances.last(); + faceInstance.getFace().GetTexdef(projection); + } +#else + FaceGetTexdef visitor(projection); + Scene_ForEachSelectedBrushFace(graph, visitor); +#endif +} + +void Scene_BrushGetShaderSize_Component_Selected(scene::Graph& graph, size_t& width, size_t& height) +{ + if(!g_SelectedFaceInstances.empty()) + { + FaceInstance& faceInstance = g_SelectedFaceInstances.last(); + width = faceInstance.getFace().getShader().width(); + height = faceInstance.getFace().getShader().height(); + } +} + + +class FaceGetFlags +{ + ContentsFlagsValue& m_flags; + mutable bool m_done; +public: + FaceGetFlags(ContentsFlagsValue& flags) + : m_flags(flags), m_done(false) + { + } + void operator()(Face& face) const + { + if(!m_done) + { + m_done = true; + face.GetFlags(m_flags); + } + } +}; + + +void Scene_BrushGetFlags_Selected(scene::Graph& graph, ContentsFlagsValue& flags) +{ +#if 1 + if(GlobalSelectionSystem().countSelected() != 0) + { + BrushInstance* brush = Instance_getBrush(GlobalSelectionSystem().ultimateSelected()); + if(brush != 0) + { + Brush_forEachFace(*brush, FaceGetFlags(flags)); + } + } +#else + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceGetFlags(flags)); +#endif +} + +void Scene_BrushGetFlags_Component_Selected(scene::Graph& graph, ContentsFlagsValue& flags) +{ +#if 1 + if(!g_SelectedFaceInstances.empty()) + { + FaceInstance& faceInstance = g_SelectedFaceInstances.last(); + faceInstance.getFace().GetFlags(flags); + } +#else + Scene_ForEachSelectedBrushFace(graph, FaceGetFlags(flags)); +#endif +} + + +class FaceGetShader +{ + CopiedString& m_shader; + mutable bool m_done; +public: + FaceGetShader(CopiedString& shader) + : m_shader(shader), m_done(false) + { + } + void operator()(Face& face) const + { + if(!m_done) + { + m_done = true; + m_shader = face.GetShader(); + } + } +}; + +void Scene_BrushGetShader_Selected(scene::Graph& graph, CopiedString& shader) +{ +#if 1 + if(GlobalSelectionSystem().countSelected() != 0) + { + BrushInstance* brush = Instance_getBrush(GlobalSelectionSystem().ultimateSelected()); + if(brush != 0) + { + Brush_forEachFace(*brush, FaceGetShader(shader)); + } + } +#else + Scene_ForEachSelectedBrush_ForEachFace(graph, FaceGetShader(shader)); +#endif +} + +void Scene_BrushGetShader_Component_Selected(scene::Graph& graph, CopiedString& shader) +{ +#if 1 + if(!g_SelectedFaceInstances.empty()) + { + FaceInstance& faceInstance = g_SelectedFaceInstances.last(); + shader = faceInstance.getFace().GetShader(); + } +#else + FaceGetShader visitor(shader); + Scene_ForEachSelectedBrushFace(graph, visitor); +#endif +} + + +class filter_face_shader : public FaceFilter +{ + const char* m_shader; +public: + filter_face_shader(const char* shader) : m_shader(shader) + { + } + bool filter(const Face& face) const + { + return shader_equal(face.GetShader(), m_shader); + } +}; + +class filter_face_shader_prefix : public FaceFilter +{ + const char* m_prefix; +public: + filter_face_shader_prefix(const char* prefix) : m_prefix(prefix) + { + } + bool filter(const Face& face) const + { + return shader_equal_n(face.GetShader(), m_prefix, strlen(m_prefix)); + } +}; + +class filter_face_flags : public FaceFilter +{ + int m_flags; +public: + filter_face_flags(int flags) : m_flags(flags) + { + } + bool filter(const Face& face) const + { + return (face.getShader().shaderFlags() & m_flags) != 0; + } +}; + +class filter_face_contents : public FaceFilter +{ + int m_contents; +public: + filter_face_contents(int contents) : m_contents(contents) + { + } + bool filter(const Face& face) const + { + return (face.getShader().m_flags.m_contentFlags & m_contents) != 0; + } +}; + + + +class FaceFilterAny +{ + FaceFilter* m_filter; + bool& m_filtered; +public: + FaceFilterAny(FaceFilter* filter, bool& filtered) : m_filter(filter), m_filtered(filtered) + { + m_filtered = false; + } + void operator()(Face& face) const + { + if(m_filter->filter(face)) + { + m_filtered = true; + } + } +}; + +class filter_brush_any_face : public BrushFilter +{ + FaceFilter* m_filter; +public: + filter_brush_any_face(FaceFilter* filter) : m_filter(filter) + { + } + bool filter(const Brush& brush) const + { + bool filtered; + Brush_forEachFace(brush, FaceFilterAny(m_filter, filtered)); + return filtered; + } +}; + +class FaceFilterAll +{ + FaceFilter* m_filter; + bool& m_filtered; +public: + FaceFilterAll(FaceFilter* filter, bool& filtered) : m_filter(filter), m_filtered(filtered) + { + m_filtered = true; + } + void operator()(Face& face) const + { + if(!m_filter->filter(face)) + { + m_filtered = false; + } + } +}; + +class filter_brush_all_faces : public BrushFilter +{ + FaceFilter* m_filter; +public: + filter_brush_all_faces(FaceFilter* filter) : m_filter(filter) + { + } + bool filter(const Brush& brush) const + { + bool filtered; + Brush_forEachFace(brush, FaceFilterAll(m_filter, filtered)); + return filtered; + } +}; + + +filter_face_flags g_filter_face_clip(QER_CLIP); +filter_brush_all_faces g_filter_brush_clip(&g_filter_face_clip); + +filter_face_shader g_filter_face_clip_q2("textures/clip"); +filter_brush_all_faces g_filter_brush_clip_q2(&g_filter_face_clip_q2); + +filter_face_shader g_filter_face_weapclip("textures/common/weapclip"); +filter_brush_all_faces g_filter_brush_weapclip(&g_filter_face_weapclip); + +filter_face_shader g_filter_face_commonclip("textures/common/clip"); +filter_brush_all_faces g_filter_brush_commonclip(&g_filter_face_commonclip); + +filter_face_shader g_filter_face_fullclip("textures/common/fullclip"); +filter_brush_all_faces g_filter_brush_fullclip(&g_filter_face_fullclip); + +filter_face_shader g_filter_face_botclip("textures/common/botclip"); +filter_brush_all_faces g_filter_brush_botclip(&g_filter_face_botclip); + +filter_face_shader_prefix g_filter_face_caulk("textures/common/caulk"); +filter_brush_all_faces g_filter_brush_caulk(&g_filter_face_caulk); + +filter_face_shader_prefix g_filter_face_caulk_ja("textures/system/caulk"); +filter_brush_all_faces g_filter_brush_caulk_ja(&g_filter_face_caulk_ja); + +filter_face_shader_prefix g_filter_face_liquids("textures/liquids/"); +filter_brush_any_face g_filter_brush_liquids(&g_filter_face_liquids); + +filter_face_shader g_filter_face_hint("textures/common/hint"); +filter_brush_any_face g_filter_brush_hint(&g_filter_face_hint); + +filter_face_shader g_filter_face_hint_q2("textures/hint"); +filter_brush_any_face g_filter_brush_hint_q2(&g_filter_face_hint_q2); + +filter_face_shader g_filter_face_hint_ja("textures/system/hint"); +filter_brush_any_face g_filter_brush_hint_ja(&g_filter_face_hint_ja); + +filter_face_shader g_filter_face_areaportal("textures/common/areaportal"); +filter_brush_all_faces g_filter_brush_areaportal(&g_filter_face_areaportal); + +filter_face_shader g_filter_face_visportal("textures/editor/visportal"); +filter_brush_any_face g_filter_brush_visportal(&g_filter_face_visportal); + +filter_face_shader g_filter_face_clusterportal("textures/common/clusterportal"); +filter_brush_all_faces g_filter_brush_clusterportal(&g_filter_face_clusterportal); + +filter_face_shader g_filter_face_lightgrid("textures/common/lightgrid"); +filter_brush_all_faces g_filter_brush_lightgrid(&g_filter_face_lightgrid); + +filter_face_flags g_filter_face_translucent(QER_TRANS); +filter_brush_all_faces g_filter_brush_translucent(&g_filter_face_translucent); + +filter_face_contents g_filter_face_detail(BRUSH_DETAIL_MASK); +filter_brush_all_faces g_filter_brush_detail(&g_filter_face_detail); + +filter_face_shader_prefix g_filter_face_decals("textures/decals/"); +filter_brush_any_face g_filter_brush_decals(&g_filter_face_decals); + + +void BrushFilters_construct() +{ + add_brush_filter(g_filter_brush_clip, EXCLUDE_CLIP); + add_brush_filter(g_filter_brush_clip_q2, EXCLUDE_CLIP); + add_brush_filter(g_filter_brush_weapclip, EXCLUDE_CLIP); + add_brush_filter(g_filter_brush_fullclip, EXCLUDE_CLIP); + add_brush_filter(g_filter_brush_commonclip, EXCLUDE_CLIP); + add_brush_filter(g_filter_brush_botclip, EXCLUDE_BOTCLIP); + add_brush_filter(g_filter_brush_caulk, EXCLUDE_CAULK); + add_brush_filter(g_filter_brush_caulk_ja, EXCLUDE_CAULK); + add_face_filter(g_filter_face_caulk, EXCLUDE_CAULK); + add_face_filter(g_filter_face_caulk_ja, EXCLUDE_CAULK); + add_brush_filter(g_filter_brush_liquids, EXCLUDE_LIQUIDS); + add_brush_filter(g_filter_brush_hint, EXCLUDE_HINTSSKIPS); + add_brush_filter(g_filter_brush_hint_q2, EXCLUDE_HINTSSKIPS); + add_brush_filter(g_filter_brush_hint_ja, EXCLUDE_HINTSSKIPS); + add_brush_filter(g_filter_brush_clusterportal, EXCLUDE_CLUSTERPORTALS); + add_brush_filter(g_filter_brush_visportal, EXCLUDE_VISPORTALS); + add_brush_filter(g_filter_brush_areaportal, EXCLUDE_AREAPORTALS); + add_brush_filter(g_filter_brush_translucent, EXCLUDE_TRANSLUCENT); + add_brush_filter(g_filter_brush_detail, EXCLUDE_DETAILS); + add_brush_filter(g_filter_brush_detail, EXCLUDE_STRUCTURAL, true); + add_brush_filter(g_filter_brush_lightgrid, EXCLUDE_LIGHTGRID); + add_brush_filter(g_filter_brush_decals, EXCLUDE_DECALS); +} + +#if 0 + +void normalquantisation_draw() +{ + glPointSize(1); + glBegin(GL_POINTS); + for(std::size_t i = 0; i <= c_quantise_normal; ++i) + { + for(std::size_t j = 0; j <= c_quantise_normal; ++j) + { + Normal3f vertex(normal3f_normalised(Normal3f( + static_cast(c_quantise_normal - j - i), + static_cast(i), + static_cast(j) + ))); + VectorScale(normal3f_to_array(vertex), 64.f, normal3f_to_array(vertex)); + glVertex3fv(normal3f_to_array(vertex)); + vertex.x = -vertex.x; + glVertex3fv(normal3f_to_array(vertex)); + } + } + glEnd(); +} + +class RenderableNormalQuantisation : public OpenGLRenderable +{ +public: + void render(RenderStateFlags state) const + { + normalquantisation_draw(); + } +}; + +const float g_test_quantise_normal = 1.f / static_cast(1 << 3); + +class TestNormalQuantisation +{ + void check_normal(const Normal3f& normal, const Normal3f& other) + { + spherical_t spherical = spherical_from_normal3f(normal); + double longditude = RAD2DEG(spherical.longditude); + double latitude = RAD2DEG(spherical.latitude); + double x = cos(spherical.longditude) * sin(spherical.latitude); + double y = sin(spherical.longditude) * sin(spherical.latitude); + double z = cos(spherical.latitude); + + ASSERT_MESSAGE(normal3f_dot(normal, other) > 0.99, "bleh"); + } + + void test_normal(const Normal3f& normal) + { + Normal3f test = normal3f_from_spherical(spherical_from_normal3f(normal)); + check_normal(normal, test); + + EOctant octant = normal3f_classify_octant(normal); + Normal3f folded = normal3f_fold_octant(normal, octant); + ESextant sextant = normal3f_classify_sextant(folded); + folded = normal3f_fold_sextant(folded, sextant); + + double scale = static_cast(c_quantise_normal) / (folded.x + folded.y + folded.z); + + double zbits = folded.z * scale; + double ybits = folded.y * scale; + + std::size_t zbits_q = static_cast(zbits); + std::size_t ybits_q = static_cast(ybits); + + ASSERT_MESSAGE(zbits_q <= (c_quantise_normal / 8) * 3, "bleh"); + ASSERT_MESSAGE(ybits_q <= (c_quantise_normal / 2), "bleh"); + ASSERT_MESSAGE(zbits_q + ((c_quantise_normal / 2) - ybits_q) <= (c_quantise_normal / 2), "bleh"); + + std::size_t y_t = (zbits_q < (c_quantise_normal / 4)) ? ybits_q : (c_quantise_normal / 2) - ybits_q; + std::size_t z_t = (zbits_q < (c_quantise_normal / 4)) ? zbits_q : (c_quantise_normal / 2) - zbits_q; + std::size_t index = (c_quantise_normal / 4) * y_t + z_t; + ASSERT_MESSAGE(index <= (c_quantise_normal / 4)*(c_quantise_normal / 2), "bleh"); + + Normal3f tmp(c_quantise_normal - zbits_q - ybits_q, ybits_q, zbits_q); + tmp = normal3f_normalised(tmp); + + Normal3f unfolded = normal3f_unfold_octant(normal3f_unfold_sextant(tmp, sextant), octant); + + check_normal(normal, unfolded); + + double dot = normal3f_dot(normal, unfolded); + float length = VectorLength(normal3f_to_array(unfolded)); + float inv_length = 1 / length; + + Normal3f quantised = normal3f_quantised(normal); + check_normal(normal, quantised); + } + void test2(const Normal3f& normal, const Normal3f& other) + { + if(normal3f_quantised(normal) != normal3f_quantised(other)) + { + int bleh = 0; + } + } + + static Normal3f normalise(float x, float y, float z) + { + return normal3f_normalised(Normal3f(x, y, z)); + } + + float vec_rand() + { + return static_cast(rand() - (RAND_MAX/2)); + } + + Normal3f normal3f_rand() + { + return normalise(vec_rand(), vec_rand(), vec_rand()); + } + +public: + TestNormalQuantisation() + { + for(int i = 4096; i > 0; --i) + test_normal(normal3f_rand()); + + test_normal(normalise(1, 0, 0)); + test_normal(normalise(0, 1, 0)); + test_normal(normalise(0, 0, 1)); + test_normal(normalise(1, 1, 0)); + test_normal(normalise(1, 0, 1)); + test_normal(normalise(0, 1, 1)); + + test_normal(normalise(10000, 10000, 10000)); + test_normal(normalise(10000, 10000, 10001)); + test_normal(normalise(10000, 10000, 10002)); + test_normal(normalise(10000, 10000, 10010)); + test_normal(normalise(10000, 10000, 10020)); + test_normal(normalise(10000, 10000, 10030)); + test_normal(normalise(10000, 10000, 10100)); + test_normal(normalise(10000, 10000, 10101)); + test_normal(normalise(10000, 10000, 10102)); + test_normal(normalise(10000, 10000, 10200)); + test_normal(normalise(10000, 10000, 10201)); + test_normal(normalise(10000, 10000, 10202)); + test_normal(normalise(10000, 10000, 10203)); + test_normal(normalise(10000, 10000, 10300)); + + + test2(normalise(10000, 10000, 10000), normalise(10000, 10000, 10001)); + test2(normalise(10000, 10000, 10001), normalise(10000, 10001, 10000)); + } +}; + +TestNormalQuantisation g_testNormalQuantisation; + + +#endif + +#if 0 +class TestSelectableObserver : public observer_template +{ +public: + void notify(const Selectable& arguments) + { + bool bleh = arguments.isSelected(); + } +}; + +inline void test_bleh() +{ + TestSelectableObserver test; + ObservableSelectableInstance< SingleObservable< SelectionChangeCallback > > bleh; + bleh.attach(test); + bleh.setSelected(true); + bleh.detach(test); +} + +class TestBleh +{ +public: + TestBleh() + { + test_bleh(); + } +}; + +const TestBleh testbleh; +#endif + + +#if 0 +class TestRefcountedString +{ +public: + TestRefcountedString() + { + { + // copy construct + SmartString string1("string1"); + SmartString string2(string1); + SmartString string3(string2); + } + { + // refcounted assignment + SmartString string1("string1"); + SmartString string2("string2"); + string1 = string2; + } + { + // copy assignment + SmartString string1("string1"); + SmartString string2("string2"); + string1 = string2.c_str(); + } + { + // self-assignment + SmartString string1("string1"); + string1 = string1; + } + { + // self-assignment via another reference + SmartString string1("string1"); + SmartString string2(string1); + string1 = string2; + } + } +}; + +const TestRefcountedString g_testRefcountedString; + +#endif + +void Select_MakeDetail() +{ + UndoableCommand undo("brushSetDetail"); + Scene_BrushSetDetail_Selected(GlobalSceneGraph(), true); +} + +void Select_MakeStructural() +{ + UndoableCommand undo("brushClearDetail"); + Scene_BrushSetDetail_Selected(GlobalSceneGraph(), false); +} + +class BrushMakeSided +{ + std::size_t m_count; +public: + BrushMakeSided(std::size_t count) + : m_count(count) + { + } + void set() + { + Scene_BrushConstructPrefab(GlobalSceneGraph(), eBrushPrism, m_count, TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); + } + typedef MemberCaller SetCaller; +}; + + +BrushMakeSided g_brushmakesided3(3); +BrushMakeSided g_brushmakesided4(4); +BrushMakeSided g_brushmakesided5(5); +BrushMakeSided g_brushmakesided6(6); +BrushMakeSided g_brushmakesided7(7); +BrushMakeSided g_brushmakesided8(8); +BrushMakeSided g_brushmakesided9(9); + +inline int axis_for_viewtype(int viewtype) +{ + switch(viewtype) + { + case XY: + return 2; + case XZ: + return 1; + case YZ: + return 0; + } + return 2; +} + +class BrushPrefab +{ + EBrushPrefab m_type; +public: + BrushPrefab(EBrushPrefab type) + : m_type(type) + { + } + void set() + { + DoSides(m_type, axis_for_viewtype(GetViewAxis())); + } + typedef MemberCaller SetCaller; +}; + +BrushPrefab g_brushprism(eBrushPrism); +BrushPrefab g_brushcone(eBrushCone); +BrushPrefab g_brushsphere(eBrushSphere); +BrushPrefab g_brushrock(eBrushRock); + + +void FlipClip(); +void SplitClip(); +void Clip(); +void OnClipMode(bool enable); +bool ClipMode(); + + +void ClipSelected() +{ + if(ClipMode()) + { + UndoableCommand undo("clipperClip"); + Clip(); + } +} + +void SplitSelected() +{ + if(ClipMode()) + { + UndoableCommand undo("clipperSplit"); + SplitClip(); + } +} + +void FlipClipper() +{ + FlipClip(); +} + + +Callback g_texture_lock_status_changed; +BoolExportCaller g_texdef_movelock_caller(g_brush_texturelock_enabled); +ToggleItem g_texdef_movelock_item(g_texdef_movelock_caller); + +void Texdef_ToggleMoveLock() +{ + g_brush_texturelock_enabled = !g_brush_texturelock_enabled; + g_texdef_movelock_item.update(); + g_texture_lock_status_changed(); +} + + + + + +void Brush_registerCommands() +{ + GlobalToggles_insert("TogTexLock", FreeCaller(), ToggleItem::AddCallbackCaller(g_texdef_movelock_item), Accelerator('T', (GdkModifierType)GDK_SHIFT_MASK)); + + GlobalCommands_insert("BrushPrism", BrushPrefab::SetCaller(g_brushprism)); + GlobalCommands_insert("BrushCone", BrushPrefab::SetCaller(g_brushcone)); + GlobalCommands_insert("BrushSphere", BrushPrefab::SetCaller(g_brushsphere)); + GlobalCommands_insert("BrushRock", BrushPrefab::SetCaller(g_brushrock)); + + GlobalCommands_insert("Brush3Sided", BrushMakeSided::SetCaller(g_brushmakesided3), Accelerator('3', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Brush4Sided", BrushMakeSided::SetCaller(g_brushmakesided4), Accelerator('4', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Brush5Sided", BrushMakeSided::SetCaller(g_brushmakesided5), Accelerator('5', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Brush6Sided", BrushMakeSided::SetCaller(g_brushmakesided6), Accelerator('6', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Brush7Sided", BrushMakeSided::SetCaller(g_brushmakesided7), Accelerator('7', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Brush8Sided", BrushMakeSided::SetCaller(g_brushmakesided8), Accelerator('8', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Brush9Sided", BrushMakeSided::SetCaller(g_brushmakesided9), Accelerator('9', (GdkModifierType)GDK_CONTROL_MASK)); + + GlobalCommands_insert("ClipSelected", FreeCaller(), Accelerator(GDK_Return)); + GlobalCommands_insert("SplitSelected", FreeCaller(), Accelerator(GDK_Return, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("FlipClip", FreeCaller(), Accelerator(GDK_Return, (GdkModifierType)GDK_CONTROL_MASK)); + + GlobalCommands_insert("MakeDetail", FreeCaller(), Accelerator('M', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("MakeStructural", FreeCaller(), Accelerator('S', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); +} + +void Brush_constructMenu(GtkMenu* menu) +{ + create_menu_item_with_mnemonic(menu, "Prism...", "BrushPrism"); + create_menu_item_with_mnemonic(menu, "Cone...", "BrushCone"); + create_menu_item_with_mnemonic(menu, "Sphere...", "BrushSphere"); + create_menu_item_with_mnemonic(menu, "Rock...", "BrushRock"); + menu_separator (menu); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "CSG"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Make _Hollow", "CSGHollow"); + create_menu_item_with_mnemonic(menu_in_menu, "CSG _Subtract", "CSGSubtract"); + create_menu_item_with_mnemonic(menu_in_menu, "CSG _Merge", "CSGMerge"); + } + menu_separator(menu); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Clipper"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + + create_menu_item_with_mnemonic(menu_in_menu, "Clip selection", "ClipSelected"); + create_menu_item_with_mnemonic(menu_in_menu, "Split selection", "SplitSelected"); + create_menu_item_with_mnemonic(menu_in_menu, "Flip Clip orientation", "FlipClip"); + } + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Make detail", "MakeDetail"); + create_menu_item_with_mnemonic(menu, "Make structural", "MakeStructural"); + create_menu_item_with_mnemonic(menu, "Snap selection to _grid", "SnapToGrid"); + + create_check_menu_item_with_mnemonic(menu, "Texture Lock", "TogTexLock"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Copy Face Texture", "FaceCopyTexture"); + create_menu_item_with_mnemonic(menu, "Paste Face Texture", "FacePasteTexture"); + + command_connect_accelerator("Brush3Sided"); + command_connect_accelerator("Brush4Sided"); + command_connect_accelerator("Brush5Sided"); + command_connect_accelerator("Brush6Sided"); + command_connect_accelerator("Brush7Sided"); + command_connect_accelerator("Brush8Sided"); + command_connect_accelerator("Brush9Sided"); +} diff --git a/misc/mediasource/netradiant-src/radiant/brushmanip.h b/misc/mediasource/netradiant-src/radiant/brushmanip.h new file mode 100644 index 00000000..74ae68b4 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushmanip.h @@ -0,0 +1,82 @@ +/* +Copyright (C) 1999-2006 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 (INCLUDED_BRUSHWRAPPER_H) +#define INCLUDED_BRUSHWRAPPER_H + +#include +#include "string/stringfwd.h" +#include "generic/callbackfwd.h" + +enum EBrushPrefab +{ + eBrushCuboid, + eBrushPrism, + eBrushCone, + eBrushSphere, + eBrushRock, +}; + +class TextureProjection; +class ContentsFlagsValue; +namespace scene +{ + class Graph; +} +void Scene_BrushConstructPrefab(scene::Graph& graph, EBrushPrefab type, std::size_t sides, const char* shader); +class AABB; +void Scene_BrushResize_Selected(scene::Graph& graph, const AABB& bounds, const char* shader); +void Scene_BrushSetTexdef_Selected(scene::Graph& graph, const TextureProjection& projection); +void Scene_BrushSetTexdef_Component_Selected(scene::Graph& graph, const TextureProjection& projection); +void Scene_BrushGetTexdef_Selected(scene::Graph& graph, TextureProjection& projection); +void Scene_BrushGetTexdef_Component_Selected(scene::Graph& graph, TextureProjection& projection); +void Scene_BrushGetShaderSize_Component_Selected(scene::Graph& graph, size_t& width, size_t& height); +void Scene_BrushSetFlags_Selected(scene::Graph& graph, const ContentsFlagsValue& flags); +void Scene_BrushSetFlags_Component_Selected(scene::Graph& graph, const ContentsFlagsValue& flags); +void Scene_BrushGetFlags_Selected(scene::Graph& graph, ContentsFlagsValue& flags); +void Scene_BrushGetFlags_Component_Selected(scene::Graph& graph, ContentsFlagsValue& flags); +void Scene_BrushShiftTexdef_Selected(scene::Graph& graph, float s, float t); +void Scene_BrushShiftTexdef_Component_Selected(scene::Graph& graph, float s, float t); +void Scene_BrushScaleTexdef_Selected(scene::Graph& graph, float s, float t); +void Scene_BrushScaleTexdef_Component_Selected(scene::Graph& graph, float s, float t); +void Scene_BrushRotateTexdef_Selected(scene::Graph& graph, float angle); +void Scene_BrushRotateTexdef_Component_Selected(scene::Graph& graph, float angle); +void Scene_BrushSetShader_Selected(scene::Graph& graph, const char* name); +void Scene_BrushSetShader_Component_Selected(scene::Graph& graph, const char* name); +void Scene_BrushGetShader_Selected(scene::Graph& graph, CopiedString& shader); +void Scene_BrushGetShader_Component_Selected(scene::Graph& graph, CopiedString& shader); +void Scene_BrushFindReplaceShader(scene::Graph& graph, const char* find, const char* replace); +void Scene_BrushFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace); +void Scene_BrushFindReplaceShader_Component_Selected(scene::Graph& graph, const char* find, const char* replace); +void Scene_BrushSelectByShader(scene::Graph& graph, const char* name); +void Scene_BrushSelectByShader_Component(scene::Graph& graph, const char* name); +void Scene_BrushFitTexture_Selected(scene::Graph& graph, float s_repeat, float t_repeat); +void Scene_BrushFitTexture_Component_Selected(scene::Graph& graph, float s_repeat, float t_repeat); + +typedef struct _GtkMenu GtkMenu; +void Brush_constructMenu(GtkMenu* menu); + +extern Callback g_texture_lock_status_changed; + +void BrushFilters_construct(); +void Brush_registerCommands(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brushmodule.cpp b/misc/mediasource/netradiant-src/radiant/brushmodule.cpp new file mode 100644 index 00000000..21cec0ee --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushmodule.cpp @@ -0,0 +1,416 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "brushmodule.h" + +#include "qerplugin.h" + +#include "brushnode.h" +#include "brushmanip.h" + +#include "preferencesystem.h" +#include "stringio.h" + +#include "map.h" +#include "qe3.h" +#include "mainframe.h" +#include "preferences.h" + +LatchedBool g_useAlternativeTextureProjection(false, "Use alternative texture-projection"); +bool g_showAlternativeTextureProjectionOption = false; +bool g_brush_always_caulk; + +bool getTextureLockEnabled() +{ + return g_brush_texturelock_enabled; +} + +void Face_importSnapPlanes(bool value) +{ + Face::m_quantise = value ? quantiseInteger : quantiseFloating; +} +typedef FreeCaller1 FaceImportSnapPlanesCaller; + +void Face_exportSnapPlanes(const BoolImportCallback& importer) +{ + importer(Face::m_quantise == quantiseInteger); +} +typedef FreeCaller1 FaceExportSnapPlanesCaller; + +void Brush_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox( + "", "Snap planes to integer grid", + FaceImportSnapPlanesCaller(), + FaceExportSnapPlanesCaller() + ); + page.appendEntry( + "Default texture scale", + g_texdef_default_scale + ); + if(g_showAlternativeTextureProjectionOption) + { + page.appendCheckBox( + "", "Use alternative texture-projection", + LatchedBoolImportCaller(g_useAlternativeTextureProjection), + BoolExportCaller(g_useAlternativeTextureProjection.m_latched) + ); + } + // d1223m + page.appendCheckBox("", + "Always use caulk for new brushes", + g_brush_always_caulk + ); +} +void Brush_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Brush", "Brush Settings")); + Brush_constructPreferences(page); +} +void Brush_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + +void Brush_unlatchPreferences() +{ + Brush_toggleFormat(0); +} + +void Brush_toggleFormat(int i) +{ + if(g_showAlternativeTextureProjectionOption) + { + g_useAlternativeTextureProjection.m_value = g_useAlternativeTextureProjection.m_latched ^ i; + Brush::destroyStatic(); + Brush::constructStatic(g_useAlternativeTextureProjection.m_value ? eBrushTypeQuake3BP : eBrushTypeQuake3); + } +} + +int Brush_toggleFormatCount() +{ + if(g_showAlternativeTextureProjectionOption) + return 2; + return 1; +} + +void Brush_Construct(EBrushType type) +{ + if(type == eBrushTypeQuake3) + { + g_showAlternativeTextureProjectionOption = true; + + GlobalPreferenceSystem().registerPreference( + "AlternativeTextureProjection", + BoolImportStringCaller(g_useAlternativeTextureProjection.m_latched), + BoolExportStringCaller(g_useAlternativeTextureProjection.m_latched) + ); + g_useAlternativeTextureProjection.useLatched(); + + if(g_useAlternativeTextureProjection.m_value) + { + type = eBrushTypeQuake3BP; + } + + // d1223m + GlobalPreferenceSystem().registerPreference( + "BrushAlwaysCaulk", + BoolImportStringCaller(g_brush_always_caulk), + BoolExportStringCaller(g_brush_always_caulk)); + } + + Brush_registerCommands(); + Brush_registerPreferencesPage(); + + BrushFilters_construct(); + + BrushClipPlane::constructStatic(); + BrushInstance::constructStatic(); + Brush::constructStatic(type); + + Brush::m_maxWorldCoord = g_MaxWorldCoord; + BrushInstance::m_counter = &g_brushCount; + + g_texdef_default_scale = 0.5f; + const char* value = g_pGameDescription->getKeyValue("default_scale"); + if(!string_empty(value)) + { + float scale = static_cast(atof(value)); + if(scale != 0) + { + g_texdef_default_scale = scale; + } + else + { + globalErrorStream() << "error parsing \"default_scale\" attribute\n"; + } + } + + GlobalPreferenceSystem().registerPreference("TextureLock", BoolImportStringCaller(g_brush_texturelock_enabled), BoolExportStringCaller(g_brush_texturelock_enabled)); + GlobalPreferenceSystem().registerPreference("BrushSnapPlanes", makeBoolStringImportCallback(FaceImportSnapPlanesCaller()), makeBoolStringExportCallback(FaceExportSnapPlanesCaller())); + GlobalPreferenceSystem().registerPreference("TexdefDefaultScale", FloatImportStringCaller(g_texdef_default_scale), FloatExportStringCaller(g_texdef_default_scale)); + + GridStatus_getTextureLockEnabled = getTextureLockEnabled; + g_texture_lock_status_changed = FreeCaller(); +} + +void Brush_Destroy() +{ + Brush::m_maxWorldCoord = 0; + BrushInstance::m_counter = 0; + + Brush::destroyStatic(); + BrushInstance::destroyStatic(); + BrushClipPlane::destroyStatic(); +} + +void Brush_clipperColourChanged() +{ + BrushClipPlane::destroyStatic(); + BrushClipPlane::constructStatic(); +} + +void BrushFaceData_fromFace(const BrushFaceDataCallback& callback, Face& face) +{ + _QERFaceData faceData; + faceData.m_p0 = face.getPlane().planePoints()[0]; + faceData.m_p1 = face.getPlane().planePoints()[1]; + faceData.m_p2 = face.getPlane().planePoints()[2]; + faceData.m_shader = face.GetShader(); + faceData.m_texdef = face.getTexdef().m_projection.m_texdef; + faceData.contents = face.getShader().m_flags.m_contentFlags; + faceData.flags = face.getShader().m_flags.m_surfaceFlags; + faceData.value = face.getShader().m_flags.m_value; + callback(faceData); +} +typedef ConstReferenceCaller1 BrushFaceDataFromFaceCaller; +typedef Callback1 FaceCallback; + +class Quake3BrushCreator : public BrushCreator +{ +public: + scene::Node& createBrush() + { + return (new BrushNode)->node(); + } + bool useAlternativeTextureProjection() const + { + return g_useAlternativeTextureProjection.m_value; + } + void Brush_forEachFace(scene::Node& brush, const BrushFaceDataCallback& callback) + { + ::Brush_forEachFace(*Node_getBrush(brush), FaceCallback(BrushFaceDataFromFaceCaller(callback))); + } + bool Brush_addFace(scene::Node& brush, const _QERFaceData& faceData) + { + Node_getBrush(brush)->undoSave(); + return Node_getBrush(brush)->addPlane(faceData.m_p0, faceData.m_p1, faceData.m_p2, faceData.m_shader, TextureProjection(faceData.m_texdef, brushprimit_texdef_t(), Vector3(0, 0, 0), Vector3(0, 0, 0))) != 0; + } +}; + +Quake3BrushCreator g_Quake3BrushCreator; + +BrushCreator& GetBrushCreator() +{ + return g_Quake3BrushCreator; +} + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + + +class BrushDependencies : + public GlobalRadiantModuleRef, + public GlobalSceneGraphModuleRef, + public GlobalShaderCacheModuleRef, + public GlobalSelectionModuleRef, + public GlobalOpenGLModuleRef, + public GlobalUndoModuleRef, + public GlobalFilterModuleRef +{ +}; + +class BrushDoom3API : public TypeSystemRef +{ + BrushCreator* m_brushdoom3; +public: + typedef BrushCreator Type; + STRING_CONSTANT(Name, "doom3"); + + BrushDoom3API() + { + Brush_Construct(eBrushTypeDoom3); + + m_brushdoom3 = &GetBrushCreator(); + } + ~BrushDoom3API() + { + Brush_Destroy(); + } + BrushCreator* getTable() + { + return m_brushdoom3; + } +}; + +typedef SingletonModule BrushDoom3Module; +typedef Static StaticBrushDoom3Module; +StaticRegisterModule staticRegisterBrushDoom3(StaticBrushDoom3Module::instance()); + + +class BrushQuake4API : public TypeSystemRef +{ + BrushCreator* m_brushquake4; +public: + typedef BrushCreator Type; + STRING_CONSTANT(Name, "quake4"); + + BrushQuake4API() + { + Brush_Construct(eBrushTypeQuake4); + + m_brushquake4 = &GetBrushCreator(); + } + ~BrushQuake4API() + { + Brush_Destroy(); + } + BrushCreator* getTable() + { + return m_brushquake4; + } +}; + +typedef SingletonModule BrushQuake4Module; +typedef Static StaticBrushQuake4Module; +StaticRegisterModule staticRegisterBrushQuake4(StaticBrushQuake4Module::instance()); + + +class BrushQuake3API : public TypeSystemRef +{ + BrushCreator* m_brushquake3; +public: + typedef BrushCreator Type; + STRING_CONSTANT(Name, "quake3"); + + BrushQuake3API() + { + Brush_Construct(eBrushTypeQuake3); + + m_brushquake3 = &GetBrushCreator(); + } + ~BrushQuake3API() + { + Brush_Destroy(); + } + BrushCreator* getTable() + { + return m_brushquake3; + } +}; + +typedef SingletonModule BrushQuake3Module; +typedef Static StaticBrushQuake3Module; +StaticRegisterModule staticRegisterBrushQuake3(StaticBrushQuake3Module::instance()); + + +class BrushQuake2API : public TypeSystemRef +{ + BrushCreator* m_brushquake2; +public: + typedef BrushCreator Type; + STRING_CONSTANT(Name, "quake2"); + + BrushQuake2API() + { + Brush_Construct(eBrushTypeQuake2); + + m_brushquake2 = &GetBrushCreator(); + } + ~BrushQuake2API() + { + Brush_Destroy(); + } + BrushCreator* getTable() + { + return m_brushquake2; + } +}; + +typedef SingletonModule BrushQuake2Module; +typedef Static StaticBrushQuake2Module; +StaticRegisterModule staticRegisterBrushQuake2(StaticBrushQuake2Module::instance()); + + +class BrushQuake1API : public TypeSystemRef +{ + BrushCreator* m_brushquake1; +public: + typedef BrushCreator Type; + STRING_CONSTANT(Name, "quake"); + + BrushQuake1API() + { + Brush_Construct(eBrushTypeQuake); + + m_brushquake1 = &GetBrushCreator(); + } + ~BrushQuake1API() + { + Brush_Destroy(); + } + BrushCreator* getTable() + { + return m_brushquake1; + } +}; + +typedef SingletonModule BrushQuake1Module; +typedef Static StaticBrushQuake1Module; +StaticRegisterModule staticRegisterBrushQuake1(StaticBrushQuake1Module::instance()); + + +class BrushHalfLifeAPI : public TypeSystemRef +{ + BrushCreator* m_brushhalflife; +public: + typedef BrushCreator Type; + STRING_CONSTANT(Name, "halflife"); + + BrushHalfLifeAPI() + { + Brush_Construct(eBrushTypeHalfLife); + + m_brushhalflife = &GetBrushCreator(); + } + ~BrushHalfLifeAPI() + { + Brush_Destroy(); + } + BrushCreator* getTable() + { + return m_brushhalflife; + } +}; + +typedef SingletonModule BrushHalfLifeModule; +typedef Static StaticBrushHalfLifeModule; +StaticRegisterModule staticRegisterBrushHalfLife(StaticBrushHalfLifeModule::instance()); diff --git a/misc/mediasource/netradiant-src/radiant/brushmodule.h b/misc/mediasource/netradiant-src/radiant/brushmodule.h new file mode 100644 index 00000000..ac89a890 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushmodule.h @@ -0,0 +1,30 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_BRUSHMODULE_H) +#define INCLUDED_BRUSHMODULE_H + +void Brush_clipperColourChanged(); +void Brush_unlatchPreferences(); +int Brush_toggleFormatCount(); +void Brush_toggleFormat(int i); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brushnode.cpp b/misc/mediasource/netradiant-src/radiant/brushnode.cpp new file mode 100644 index 00000000..35f46877 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushnode.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "brushnode.h" + diff --git a/misc/mediasource/netradiant-src/radiant/brushnode.h b/misc/mediasource/netradiant-src/radiant/brushnode.h new file mode 100644 index 00000000..5e1465e3 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushnode.h @@ -0,0 +1,167 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_BRUSHNODE_H) +#define INCLUDED_BRUSHNODE_H + +#include "instancelib.h" +#include "brush.h" +#include "brushtokens.h" +#include "brushxml.h" + +class BrushNode : +public scene::Node::Symbiot, +public scene::Instantiable, +public scene::Cloneable +{ + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts() + { + NodeStaticCast::install(m_casts); + NodeStaticCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::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; + InstanceSet m_instances; + Brush m_brush; + BrushTokenImporter m_mapImporter; + BrushTokenExporter m_mapExporter; + BrushXMLImporter m_xmlImporter; + BrushXMLExporter m_xmlExporter; + +public: + + typedef LazyStatic StaticTypeCasts; + + Snappable& get(NullType) + { + return m_brush; + } + TransformNode& get(NullType) + { + return m_brush; + } + Brush& get(NullType) + { + return m_brush; + } + XMLImporter& get(NullType) + { + return m_xmlImporter; + } + XMLExporter& get(NullType) + { + return m_xmlExporter; + } + MapImporter& get(NullType) + { + return m_mapImporter; + } + MapExporter& get(NullType) + { + return m_mapExporter; + } + Nameable& get(NullType) + { + return m_brush; + } + BrushDoom3& get(NullType) + { + return m_brush; + } + + BrushNode() : + m_node(this, this, StaticTypeCasts::instance().get()), + m_brush(m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), + m_mapImporter(m_brush), + m_mapExporter(m_brush), + m_xmlImporter(m_brush), + m_xmlExporter(m_brush) + { + } + BrushNode(const BrushNode& other) : + scene::Node::Symbiot(other), + scene::Instantiable(other), + scene::Cloneable(other), + m_node(this, this, StaticTypeCasts::instance().get()), + m_brush(other.m_brush, m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), + m_mapImporter(m_brush), + m_mapExporter(m_brush), + m_xmlImporter(m_brush), + m_xmlExporter(m_brush) + { + } + void release() + { + delete this; + } + scene::Node& node() + { + return m_node; + } + + scene::Node& clone() const + { + return (new BrushNode(*this))->node(); + } + + scene::Instance* create(const scene::Path& path, scene::Instance* parent) + { + return new BrushInstance(path, parent, m_brush); + } + 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); + } + scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) + { + return m_instances.erase(observer, path); + } +}; + +inline Brush* Node_getBrush(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brushtokens.cpp b/misc/mediasource/netradiant-src/radiant/brushtokens.cpp new file mode 100644 index 00000000..e8674c98 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushtokens.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "brushtokens.h" + diff --git a/misc/mediasource/netradiant-src/radiant/brushtokens.h b/misc/mediasource/netradiant-src/radiant/brushtokens.h new file mode 100644 index 00000000..19d8c7b9 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushtokens.h @@ -0,0 +1,738 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_BRUSHTOKENS_H) +#define INCLUDED_BRUSHTOKENS_H + +#include "stringio.h" +#include "stream/stringstream.h" +#include "brush.h" + +inline bool FaceShader_importContentsFlagsValue(FaceShader& faceShader, Tokeniser& tokeniser) +{ + // parse the optional contents/flags/value + RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, faceShader.m_flags.m_contentFlags)); + RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, faceShader.m_flags.m_surfaceFlags)); + RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, faceShader.m_flags.m_value)); + return true; +} + +inline bool FaceTexdef_importTokens(FaceTexdef& texdef, Tokeniser& tokeniser) +{ + // parse texdef + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[0])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[1])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.rotate)); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[0])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[1])); + + ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_importTokens: bad texdef"); + return true; +} + +inline bool FaceTexdef_BP_importTokens(FaceTexdef& texdef, Tokeniser& tokeniser) +{ + // parse alternate texdef + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); + { + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[0][0])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[0][1])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[0][2])); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); + } + { + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[1][0])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[1][1])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_brushprimit_texdef.coords[1][2])); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); + } + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); + return true; +} + +inline bool FaceTexdef_HalfLife_importTokens(FaceTexdef& texdef, Tokeniser& tokeniser) +{ + // parse texdef + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "[")); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_s.x())); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_s.y())); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_s.z())); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[0])); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "]")); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "[")); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_t.x())); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_t.y())); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_basis_t.z())); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.shift[1])); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "]")); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.rotate)); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[0])); + RETURN_FALSE_IF_FAIL(Tokeniser_getFloat(tokeniser, texdef.m_projection.m_texdef.scale[1])); + + texdef.m_projection.m_texdef.rotate = -texdef.m_projection.m_texdef.rotate; + + ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_importTokens: bad texdef"); + return true; +} + +inline bool FacePlane_importTokens(FacePlane& facePlane, Tokeniser& tokeniser) +{ + // parse planepts + for(std::size_t i = 0; i<3; i++) + { + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); + for(std::size_t j = 0; j < 3; ++j) + { + RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, facePlane.planePoints()[i][j])); + } + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); + } + facePlane.MakePlane(); + return true; +} + +inline bool FacePlane_Doom3_importTokens(FacePlane& facePlane, Tokeniser& tokeniser) +{ + Plane3 plane; + // parse plane equation + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); + RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.a)); + RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.b)); + RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.c)); + RETURN_FALSE_IF_FAIL(Tokeniser_getDouble(tokeniser, plane.d)); + plane.d = -plane.d; + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); + + facePlane.setDoom3Plane(plane); + return true; +} + +inline bool FaceShader_Doom3_importTokens(FaceShader& faceShader, Tokeniser& tokeniser) +{ + const char *shader = tokeniser.getToken(); + if(shader == 0) + { + Tokeniser_unexpectedError(tokeniser, shader, "#shader-name"); + return false; + } + if(string_equal(shader, "_emptyname")) + { + shader = texdef_name_default(); + } + faceShader.setShader(shader); + return true; +} + +inline bool FaceShader_importTokens(FaceShader& faceShader, Tokeniser& tokeniser) +{ + const char* texture = tokeniser.getToken(); + if(texture == 0) + { + Tokeniser_unexpectedError(tokeniser, texture, "#texture-name"); + return false; + } + if(string_equal(texture, "NULL")) + { + faceShader.setShader(texdef_name_default()); + } + else + { + StringOutputStream shader(string_length(GlobalTexturePrefix_get()) + string_length(texture)); + shader << GlobalTexturePrefix_get() << texture; + faceShader.setShader(shader.c_str()); + } + return true; +} + + + + +class Doom3FaceTokenImporter +{ + Face& m_face; +public: + Doom3FaceTokenImporter(Face& face) : m_face(face) + { + } + bool importTokens(Tokeniser& tokeniser) + { + RETURN_FALSE_IF_FAIL(FacePlane_Doom3_importTokens(m_face.getPlane(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceTexdef_BP_importTokens(m_face.getTexdef(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_Doom3_importTokens(m_face.getShader(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); + + m_face.getTexdef().m_projectionInitialised = true; + m_face.getTexdef().m_scaleApplied = true; + + return true; + } +}; + +class Quake4FaceTokenImporter +{ + Face& m_face; +public: + Quake4FaceTokenImporter(Face& face) : m_face(face) + { + } + bool importTokens(Tokeniser& tokeniser) + { + RETURN_FALSE_IF_FAIL(FacePlane_Doom3_importTokens(m_face.getPlane(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceTexdef_BP_importTokens(m_face.getTexdef(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_Doom3_importTokens(m_face.getShader(), tokeniser)); + + m_face.getTexdef().m_projectionInitialised = true; + m_face.getTexdef().m_scaleApplied = true; + + return true; + } +}; + +class Quake2FaceTokenImporter +{ + Face& m_face; +public: + Quake2FaceTokenImporter(Face& face) : m_face(face) + { + } + bool importTokens(Tokeniser& tokeniser) + { + RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceTexdef_importTokens(m_face.getTexdef(), tokeniser)); + if(Tokeniser_nextTokenIsDigit(tokeniser)) + { + m_face.getShader().m_flags.m_specified = true; + RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); + } + m_face.getTexdef().m_scaleApplied = true; + return true; + } +}; + +class Quake3FaceTokenImporter +{ + Face& m_face; +public: + Quake3FaceTokenImporter(Face& face) : m_face(face) + { + } + bool importTokens(Tokeniser& tokeniser) + { + RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceTexdef_importTokens(m_face.getTexdef(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); + m_face.getTexdef().m_scaleApplied = true; + return true; + } +}; + +class Quake3BPFaceTokenImporter +{ + Face& m_face; +public: + Quake3BPFaceTokenImporter(Face& face) : m_face(face) + { + } + bool importTokens(Tokeniser& tokeniser) + { + RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceTexdef_BP_importTokens(m_face.getTexdef(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importContentsFlagsValue(m_face.getShader(), tokeniser)); + + m_face.getTexdef().m_projectionInitialised = true; + m_face.getTexdef().m_scaleApplied = true; + + return true; + } +}; + +class QuakeFaceTokenImporter +{ + Face& m_face; +public: + QuakeFaceTokenImporter(Face& face) : m_face(face) + { + } + bool importTokens(Tokeniser& tokeniser) + { + RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceTexdef_importTokens(m_face.getTexdef(), tokeniser)); + m_face.getTexdef().m_scaleApplied = true; + return true; + } +}; + +class HalfLifeFaceTokenImporter +{ + Face& m_face; +public: + HalfLifeFaceTokenImporter(Face& face) : m_face(face) + { + } + bool importTokens(Tokeniser& tokeniser) + { + RETURN_FALSE_IF_FAIL(FacePlane_importTokens(m_face.getPlane(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceShader_importTokens(m_face.getShader(), tokeniser)); + RETURN_FALSE_IF_FAIL(FaceTexdef_HalfLife_importTokens(m_face.getTexdef(), tokeniser)); + m_face.getTexdef().m_scaleApplied = true; + return true; + } +}; + + +inline void FacePlane_Doom3_exportTokens(const FacePlane& facePlane, TokenWriter& writer) +{ + // write plane equation + writer.writeToken("("); + writer.writeFloat(facePlane.getDoom3Plane().a); + writer.writeFloat(facePlane.getDoom3Plane().b); + writer.writeFloat(facePlane.getDoom3Plane().c); + writer.writeFloat(-facePlane.getDoom3Plane().d); + writer.writeToken(")"); +} + +inline void FacePlane_exportTokens(const FacePlane& facePlane, TokenWriter& writer) +{ + // write planepts + for(std::size_t i=0; i<3; i++) + { + writer.writeToken("("); + for(std::size_t j=0; j<3; j++) + { + writer.writeFloat(Face::m_quantise(facePlane.planePoints()[i][j])); + } + writer.writeToken(")"); + } +} + +inline void FaceTexdef_BP_exportTokens(const FaceTexdef& faceTexdef, TokenWriter& writer) +{ + // write alternate texdef + writer.writeToken("("); + { + writer.writeToken("("); + for(std::size_t i=0;i<3;i++) + { + writer.writeFloat(faceTexdef.m_projection.m_brushprimit_texdef.coords[0][i]); + } + writer.writeToken(")"); + } + { + writer.writeToken("("); + for(std::size_t i=0;i<3;i++) + { + writer.writeFloat(faceTexdef.m_projection.m_brushprimit_texdef.coords[1][i]); + } + writer.writeToken(")"); + } + writer.writeToken(")"); +} + +inline void FaceTexdef_exportTokens(const FaceTexdef& faceTexdef, TokenWriter& writer) +{ + ASSERT_MESSAGE(texdef_sane(faceTexdef.m_projection.m_texdef), "FaceTexdef_exportTokens: bad texdef"); + // write texdef + writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[0]); + writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[1]); + writer.writeFloat(faceTexdef.m_projection.m_texdef.rotate); + writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[0]); + writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[1]); +} + +inline void FaceTexdef_HalfLife_exportTokens(const FaceTexdef& faceTexdef, TokenWriter& writer) +{ + ASSERT_MESSAGE(texdef_sane(faceTexdef.m_projection.m_texdef), "FaceTexdef_exportTokens: bad texdef"); + // write texdef + writer.writeToken("["); + writer.writeFloat(faceTexdef.m_projection.m_basis_s.x()); + writer.writeFloat(faceTexdef.m_projection.m_basis_s.y()); + writer.writeFloat(faceTexdef.m_projection.m_basis_s.z()); + writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[0]); + writer.writeToken("]"); + writer.writeToken("["); + writer.writeFloat(faceTexdef.m_projection.m_basis_t.x()); + writer.writeFloat(faceTexdef.m_projection.m_basis_t.y()); + writer.writeFloat(faceTexdef.m_projection.m_basis_t.z()); + writer.writeFloat(faceTexdef.m_projection.m_texdef.shift[1]); + writer.writeToken("]"); + writer.writeFloat(-faceTexdef.m_projection.m_texdef.rotate); + writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[0]); + writer.writeFloat(faceTexdef.m_projection.m_texdef.scale[1]); +} + +inline void FaceShader_ContentsFlagsValue_exportTokens(const FaceShader& faceShader, TokenWriter& writer) +{ + // write surface flags + writer.writeInteger(faceShader.m_flags.m_contentFlags); + writer.writeInteger(faceShader.m_flags.m_surfaceFlags); + writer.writeInteger(faceShader.m_flags.m_value); +} + +inline void FaceShader_exportTokens(const FaceShader& faceShader, TokenWriter& writer) +{ + // write shader name + if(string_empty(shader_get_textureName(faceShader.getShader()))) + { + writer.writeToken("NULL"); + } + else + { + writer.writeToken(shader_get_textureName(faceShader.getShader())); + } +} + +inline void FaceShader_Doom3_exportTokens(const FaceShader& faceShader, TokenWriter& writer) +{ + // write shader name + if(string_empty(shader_get_textureName(faceShader.getShader()))) + { + writer.writeString("_emptyname"); + } + else + { + writer.writeString(faceShader.getShader()); + } +} + +class Doom3FaceTokenExporter +{ + const Face& m_face; +public: + Doom3FaceTokenExporter(const Face& face) : m_face(face) + { + } + void exportTokens(TokenWriter& writer) const + { + FacePlane_Doom3_exportTokens(m_face.getPlane(), writer); + FaceTexdef_BP_exportTokens(m_face.getTexdef(), writer); + FaceShader_Doom3_exportTokens(m_face.getShader(), writer); + FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); + writer.nextLine(); + } +}; + +class Quake4FaceTokenExporter +{ + const Face& m_face; +public: + Quake4FaceTokenExporter(const Face& face) : m_face(face) + { + } + void exportTokens(TokenWriter& writer) const + { + FacePlane_Doom3_exportTokens(m_face.getPlane(), writer); + FaceTexdef_BP_exportTokens(m_face.getTexdef(), writer); + FaceShader_Doom3_exportTokens(m_face.getShader(), writer); + writer.nextLine(); + } +}; + +class Quake2FaceTokenExporter +{ + const Face& m_face; +public: + Quake2FaceTokenExporter(const Face& face) : m_face(face) + { + } + void exportTokens(TokenWriter& writer) const + { + FacePlane_exportTokens(m_face.getPlane(), writer); + FaceShader_exportTokens(m_face.getShader(), writer); + FaceTexdef_exportTokens(m_face.getTexdef(), writer); + if(m_face.getShader().m_flags.m_specified || m_face.isDetail()) + { + FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); + } + writer.nextLine(); + } +}; + +class Quake3FaceTokenExporter +{ + const Face& m_face; +public: + Quake3FaceTokenExporter(const Face& face) : m_face(face) + { + } + void exportTokens(TokenWriter& writer) const + { + FacePlane_exportTokens(m_face.getPlane(), writer); + FaceShader_exportTokens(m_face.getShader(), writer); + FaceTexdef_exportTokens(m_face.getTexdef(), writer); + FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); + writer.nextLine(); + } +}; + +class Quake3BPFaceTokenExporter +{ + const Face& m_face; +public: + Quake3BPFaceTokenExporter(const Face& face) : m_face(face) + { + } + void exportTokens(TokenWriter& writer) const + { + FacePlane_exportTokens(m_face.getPlane(), writer); + FaceTexdef_BP_exportTokens(m_face.getTexdef(), writer); + FaceShader_exportTokens(m_face.getShader(), writer); + FaceShader_ContentsFlagsValue_exportTokens(m_face.getShader(), writer); + writer.nextLine(); + } +}; + +class QuakeFaceTokenExporter +{ + const Face& m_face; +public: + QuakeFaceTokenExporter(const Face& face) : m_face(face) + { + } + void exportTokens(TokenWriter& writer) const + { + FacePlane_exportTokens(m_face.getPlane(), writer); + FaceShader_exportTokens(m_face.getShader(), writer); + FaceTexdef_exportTokens(m_face.getTexdef(), writer); + writer.nextLine(); + } +}; + +class HalfLifeFaceTokenExporter +{ + const Face& m_face; +public: + HalfLifeFaceTokenExporter(const Face& face) : m_face(face) + { + } + void exportTokens(TokenWriter& writer) const + { + FacePlane_exportTokens(m_face.getPlane(), writer); + FaceShader_exportTokens(m_face.getShader(), writer); + FaceTexdef_HalfLife_exportTokens(m_face.getTexdef(), writer); + writer.nextLine(); + } +}; + + +class BrushTokenImporter : public MapImporter +{ + Brush& m_brush; + +public: + BrushTokenImporter(Brush& brush) : m_brush(brush) + { + } + bool importTokens(Tokeniser& tokeniser) + { + if(Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) + { + tokeniser.nextLine(); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "{")); + } + while(1) + { + // check for end of brush + tokeniser.nextLine(); + const char* token = tokeniser.getToken(); + if(string_equal(token, "}")) + { + break; + } + + tokeniser.ungetToken(); + + m_brush.push_back(FaceSmartPointer(new Face(&m_brush))); + + //!todo BP support + tokeniser.nextLine(); + + Face& face = *m_brush.back(); + + switch(Brush::m_type) + { + case eBrushTypeDoom3: + { + Doom3FaceTokenImporter importer(face); + RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); + } + break; + case eBrushTypeQuake4: + { + Quake4FaceTokenImporter importer(face); + RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); + } + break; + case eBrushTypeQuake2: + { + Quake2FaceTokenImporter importer(face); + RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); + } + break; + case eBrushTypeQuake3: + { + Quake3FaceTokenImporter importer(face); + RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); + } + break; + case eBrushTypeQuake3BP: + { + Quake3BPFaceTokenImporter importer(face); + RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); + } + break; + case eBrushTypeQuake: + { + QuakeFaceTokenImporter importer(face); + RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); + } + break; + case eBrushTypeHalfLife: + { + HalfLifeFaceTokenImporter importer(face); + RETURN_FALSE_IF_FAIL(importer.importTokens(tokeniser)); + } + break; + } + face.planeChanged(); + } + if(Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) + { + tokeniser.nextLine(); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "}")); + } + + m_brush.planeChanged(); + m_brush.shaderChanged(); + + return true; + } +}; + + +class BrushTokenExporter : public MapExporter +{ + const Brush& m_brush; + +public: + BrushTokenExporter(const Brush& brush) : m_brush(brush) + { + } + void exportTokens(TokenWriter& writer) const + { + m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. + + if(!m_brush.hasContributingFaces()) + { + return; + } + + writer.writeToken("{"); + writer.nextLine(); + + if(Brush::m_type == eBrushTypeQuake3BP) + { + writer.writeToken("brushDef"); + writer.nextLine(); + writer.writeToken("{"); + writer.nextLine(); + } + + if(Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) + { + writer.writeToken("brushDef3"); + writer.nextLine(); + writer.writeToken("{"); + writer.nextLine(); + } + + for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i) + { + const Face& face = *(*i); + + if(face.contributes()) + { + switch(Brush::m_type) + { + case eBrushTypeDoom3: + { + Doom3FaceTokenExporter exporter(face); + exporter.exportTokens(writer); + } + break; + case eBrushTypeQuake4: + { + Quake4FaceTokenExporter exporter(face); + exporter.exportTokens(writer); + } + break; + case eBrushTypeQuake2: + { + Quake2FaceTokenExporter exporter(face); + exporter.exportTokens(writer); + } + break; + case eBrushTypeQuake3: + { + Quake3FaceTokenExporter exporter(face); + exporter.exportTokens(writer); + } + break; + case eBrushTypeQuake3BP: + { + Quake3BPFaceTokenExporter exporter(face); + exporter.exportTokens(writer); + } + break; + case eBrushTypeQuake: + { + QuakeFaceTokenExporter exporter(face); + exporter.exportTokens(writer); + } + break; + case eBrushTypeHalfLife: + { + HalfLifeFaceTokenExporter exporter(face); + exporter.exportTokens(writer); + } + break; + } + } + } + + if(Brush::m_type == eBrushTypeQuake3BP || Brush::m_type == eBrushTypeDoom3 || Brush::m_type == eBrushTypeQuake4) + { + writer.writeToken("}"); + writer.nextLine(); + } + + writer.writeToken("}"); + writer.nextLine(); + } +}; + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/brushxml.cpp b/misc/mediasource/netradiant-src/radiant/brushxml.cpp new file mode 100644 index 00000000..ae18cf34 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushxml.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "brushxml.h" + diff --git a/misc/mediasource/netradiant-src/radiant/brushxml.h b/misc/mediasource/netradiant-src/radiant/brushxml.h new file mode 100644 index 00000000..afadc8a0 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/brushxml.h @@ -0,0 +1,457 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_BRUSHXML_H) +#define INCLUDED_BRUSHXML_H + +#include "stream/stringstream.h" +#include "xml/xmlelement.h" + +#include "brush.h" + +inline void FaceTexdef_BP_importXML(FaceTexdef& texdef, const char* xmlContent) +{ + StringTokeniser content(xmlContent); + + texdef.m_projection.m_brushprimit_texdef.coords[0][0] = static_cast(atof(content.getToken())); + texdef.m_projection.m_brushprimit_texdef.coords[0][1] = static_cast(atof(content.getToken())); + texdef.m_projection.m_brushprimit_texdef.coords[0][2] = static_cast(atof(content.getToken())); + texdef.m_projection.m_brushprimit_texdef.coords[1][0] = static_cast(atof(content.getToken())); + texdef.m_projection.m_brushprimit_texdef.coords[1][1] = static_cast(atof(content.getToken())); + texdef.m_projection.m_brushprimit_texdef.coords[1][2] = static_cast(atof(content.getToken())); +} +inline void FaceTexdef_importXML(FaceTexdef& texdef, const char* xmlContent) +{ + StringTokeniser content(xmlContent); + + texdef.m_projection.m_texdef.shift[0] = static_cast(atof(content.getToken())); + texdef.m_projection.m_texdef.shift[1] = static_cast(atof(content.getToken())); + texdef.m_projection.m_texdef.rotate = static_cast(atof(content.getToken())); + texdef.m_projection.m_texdef.scale[0] = static_cast(atof(content.getToken())); + texdef.m_projection.m_texdef.scale[1] = static_cast(atof(content.getToken())); + + ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_importXML: bad texdef"); +} + +inline void FacePlane_importXML(FacePlane& facePlane, const char* xmlContent) +{ + StringTokeniser content(xmlContent); + + for (int i = 0; i < 3; ++i) + { + for (int j = 0; j < 3; ++j) + { + facePlane.planePoints()[i][j] = atof(content.getToken()); + } + } + facePlane.MakePlane(); +} + + +class FaceXMLImporter +{ + struct xml_state_t + { + enum EState + { + eDefault, + ePlanePts, + eTexdef, + eBPMatrix, + eFlags, + eShader, + }; + + EState m_state; + StringOutputStream m_content; + + xml_state_t(EState state) + : m_state(state) + {} + + EState state() const + { + return m_state; + } + const char* content() const + { + return m_content.c_str(); + } + std::size_t write(const char* buffer, std::size_t length) + { + return m_content.write(buffer, length); + } + }; + + std::vector m_xml_state; + Face& m_face; +public: + FaceXMLImporter(Face& face) : m_face(face) + { + m_xml_state.push_back(xml_state_t::eDefault); + } + ~FaceXMLImporter() + { + m_face.planeChanged(); + } + + void pushElement(const XMLElement& element) + { + ASSERT_MESSAGE(m_xml_state.back().state() == xml_state_t::eDefault, "parse error"); + + if(strcmp(element.name(), "planepts") == 0) + { + m_xml_state.push_back(xml_state_t::ePlanePts); + } + else if(strcmp(element.name(), "texdef") == 0) + { + m_xml_state.push_back(xml_state_t::eTexdef); + } + else if(strcmp(element.name(), "bpmatrix") == 0) + { + m_xml_state.push_back(xml_state_t::eBPMatrix); + } + else if(strcmp(element.name(), "flags") == 0) + { + m_xml_state.push_back(xml_state_t::eFlags); + } + else if(strcmp(element.name(), "shader") == 0) + { + m_xml_state.push_back(xml_state_t::eShader); + } + } + void popElement(const char* name) + { + ASSERT_MESSAGE(m_xml_state.back().state() != xml_state_t::eDefault, "parse error"); + + switch(m_xml_state.back().state()) + { + case xml_state_t::ePlanePts: + { + FacePlane_importXML(m_face.getPlane(), m_xml_state.back().content()); + } + break; + case xml_state_t::eTexdef: + { + FaceTexdef_importXML(m_face.getTexdef(), m_xml_state.back().content()); + } + break; + case xml_state_t::eBPMatrix: + { + FaceTexdef_BP_importXML(m_face.getTexdef(), m_xml_state.back().content()); + } + break; + case xml_state_t::eFlags: + { + StringTokeniser content(m_xml_state.back().content()); + + m_face.getShader().m_flags.m_contentFlags = atoi(content.getToken()); + m_face.getShader().m_flags.m_surfaceFlags = atoi(content.getToken()); + m_face.getShader().m_flags.m_value = atoi(content.getToken()); + } + break; + case xml_state_t::eShader: + { + m_face.getShader().setShader(m_xml_state.back().content()); + } + break; + default: + break; + } + + m_xml_state.pop_back(); + } + std::size_t write(const char* data, std::size_t length) + { + ASSERT_MESSAGE(!m_xml_state.empty(), "parse error"); + return m_xml_state.back().write(data, length); + } +}; + + +inline void FaceTexdef_exportXML(const FaceTexdef& texdef, XMLImporter& importer) +{ + StaticElement element("texdef"); + importer.pushElement(element); + + ASSERT_MESSAGE(texdef_sane(texdef.m_projection.m_texdef), "FaceTexdef_exportXML: bad texdef"); + + importer << texdef.m_projection.m_texdef.shift[0] + << ' ' << texdef.m_projection.m_texdef.shift[1] + << ' ' << texdef.m_projection.m_texdef.rotate + << ' ' << texdef.m_projection.m_texdef.scale[0] + << ' ' << texdef.m_projection.m_texdef.scale[1]; + + importer.popElement(element.name()); +} +inline void FaceTexdef_BP_exportXML(const FaceTexdef& texdef, XMLImporter& importer) +{ + StaticElement element("texdef"); + importer.pushElement(element); + + for(int i = 0; i < 2; ++i) + { + for(int j = 0; j < 3; ++j) + { + importer << texdef.m_projection.m_brushprimit_texdef.coords[i][j] << ' '; + } + } + + importer.popElement(element.name()); +} +inline void FaceShader_ContentsFlagsValue_exportXML(const FaceShader& faceShader, XMLImporter& importer) +{ + StaticElement element("flags"); + importer.pushElement(element); + + { + importer << faceShader.m_flags.m_contentFlags + << ' ' << faceShader.m_flags.m_surfaceFlags + << ' ' << faceShader.m_flags.m_value; + } + + importer.popElement(element.name()); +} + +inline void FacePlane_exportXML(const FacePlane& facePlane, XMLImporter& importer) +{ + StaticElement element("planepts"); + importer.pushElement(element); + + { + // write planepts + for (int i=0 ; i<3 ; i++) + { + for (int j=0 ; j<3 ; j++) + { + importer << Face::m_quantise(facePlane.planePoints()[i][j]) << ' '; + } + } + } + + importer.popElement(element.name()); +} + +inline void FacePolygon_exportXML(const Winding& w, const BasicVector3& normal, XMLImporter& importer) +{ + DynamicElement element("polygon"); + + char tmp[32]; + + sprintf(tmp, "%f", normal.x()); + element.insertAttribute("nx", tmp); + + sprintf(tmp, "%f", normal.y()); + element.insertAttribute("ny", tmp); + + sprintf(tmp, "%f", normal.z()); + element.insertAttribute("nz", tmp); + + importer.pushElement(element); + + for(unsigned int i = 0; i < w.numpoints; ++i) + { + DynamicElement c("vertex"); + + sprintf(tmp, "%f", w.points[i].vertex.x()); + c.insertAttribute("x", tmp); + + sprintf(tmp, "%f", w.points[i].vertex.y()); + c.insertAttribute("y", tmp); + + sprintf(tmp, "%f", w.points[i].vertex.z()); + c.insertAttribute("z", tmp); + + sprintf(tmp, "%f", w.points[i].texcoord.x()); + c.insertAttribute("s", tmp); + + sprintf(tmp, "%f", w.points[i].texcoord.y()); + c.insertAttribute("t", tmp); + + importer.pushElement(c); + importer.popElement(c.name()); + } + + importer.popElement(element.name()); +} + +class FaceXMLExporter +{ + const Face& m_face; +public: + FaceXMLExporter(const Face& face) : m_face(face) + { + } + void exportXML(XMLImporter& importer) + { + bool bAlternateTexdef = (Face::m_type == eBrushTypeQuake3BP || Face::m_type == eBrushTypeDoom3 || Face::m_type == eBrushTypeQuake4); + + // write shader + { + StaticElement element("shader"); + importer.pushElement(element); + importer << m_face.getShader().getShader(); + importer.popElement(element.name()); + } + + FacePolygon_exportXML(m_face.getWinding(), m_face.getPlane().plane3().normal(), importer); + FacePlane_exportXML(m_face.getPlane(), importer); + + if(!bAlternateTexdef) + { + FaceTexdef_exportXML(m_face.getTexdef(), importer); + } + else + { + FaceTexdef_BP_exportXML(m_face.getTexdef(), importer); + } + + FaceShader_ContentsFlagsValue_exportXML(m_face.getShader(), importer); + } +}; + + +class BrushXMLImporter : public XMLImporter +{ + class xml_state_t + { + public: + enum EState + { + eDefault, + eBrush, + eFace, + }; + + private: + EState m_state; + + public: + xml_state_t(EState state) + : m_state(state) + { + } + EState state() const + { + return m_state; + } + }; + + std::vector m_xml_state; + char m_faceImporter[sizeof(FaceXMLImporter)]; + Brush& m_brush; + + FaceXMLImporter& faceImporter() + { + return *reinterpret_cast(m_faceImporter); + } + +public: + BrushXMLImporter(Brush& brush) : m_brush(brush) + { + m_xml_state.push_back(xml_state_t::eDefault); + } + void pushElement(const XMLElement& element) + { + switch(m_xml_state.back().state()) + { + case xml_state_t::eDefault: + ASSERT_MESSAGE(strcmp(element.name(), "brush") == 0, "parse error"); + m_xml_state.push_back(xml_state_t::eBrush); + break; + case xml_state_t::eBrush: + ASSERT_MESSAGE(strcmp(element.name(), "plane") == 0, "parse error"); + m_xml_state.push_back(xml_state_t::eFace); + m_brush.push_back(FaceSmartPointer(new Face(&m_brush))); + constructor(faceImporter(), makeReference(*m_brush.back())); + m_brush.planeChanged(); + m_brush.shaderChanged(); + break; + case xml_state_t::eFace: + m_xml_state.push_back(xml_state_t::eFace); + faceImporter().pushElement(element); + break; + } + } + void popElement(const char* name) + { + ASSERT_MESSAGE(!m_xml_state.empty(), "parse error"); + m_xml_state.pop_back(); + + switch(m_xml_state.back().state()) + { + case xml_state_t::eDefault: + break; + case xml_state_t::eBrush: + destructor(faceImporter()); + break; + case xml_state_t::eFace: + faceImporter().popElement(name); + break; + } + } + std::size_t write(const char* data, std::size_t length) + { + switch(m_xml_state.back().state()) + { + case xml_state_t::eFace: + return faceImporter().write(data, length); + break; + default: + break; + } + return length; + } +}; + +class BrushXMLExporter : public XMLExporter +{ + const Brush& m_brush; + +public: + BrushXMLExporter(const Brush& brush) : m_brush(brush) + { + } + void exportXML(XMLImporter& importer) + { + m_brush.evaluateBRep(); // ensure b-rep is up-to-date, so that non-contributing faces can be identified. + ASSERT_MESSAGE(m_brush.hasContributingFaces(), "exporting an empty brush"); + + const StaticElement brushElement("brush"); + importer.pushElement(brushElement); + + for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i) + { + if((*i)->contributes()) + { + const StaticElement element("plane"); + importer.pushElement(element); + FaceXMLExporter(*(*i)).exportXML(importer); + importer.popElement(element.name()); + } + } + + importer.popElement(brushElement.name()); + } +}; + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/build.cpp b/misc/mediasource/netradiant-src/radiant/build.cpp new file mode 100644 index 00000000..dcb23a28 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/build.cpp @@ -0,0 +1,1158 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "build.h" +#include "debugging/debugging.h" + +#include +#include +#include "stream/stringstream.h" +#include "versionlib.h" + +#include "mainframe.h" + +typedef std::map Variables; +Variables g_build_variables; + +void build_clear_variables() +{ + g_build_variables.clear(); +} + +void build_set_variable(const char* name, const char* value) +{ + g_build_variables[name] = value; +} + +const char* build_get_variable(const char* name) +{ + Variables::iterator i = g_build_variables.find(name); + if(i != g_build_variables.end()) + { + return (*i).second.c_str(); + } + globalErrorStream() << "undefined build variable: " << makeQuoted(name) << "\n"; + return ""; +} + +#include "xml/ixml.h" +#include "xml/xmlelement.h" + +class Evaluatable +{ +public: + virtual void evaluate(StringBuffer& output) = 0; + virtual void exportXML(XMLImporter& importer) = 0; +}; + +class VariableString : public Evaluatable +{ + CopiedString m_string; +public: + VariableString() : m_string() + { + } + VariableString(const char* string) : m_string(string) + { + } + const char* c_str() const + { + return m_string.c_str(); + } + void setString(const char* string) + { + m_string = string; + } + void evaluate(StringBuffer& output) + { + StringBuffer variable; + bool in_variable = false; + for(const char* i = m_string.c_str(); *i != '\0'; ++i) + { + if(!in_variable) + { + switch(*i) + { + case '[': + in_variable = true; + break; + default: + output.push_back(*i); + break; + } + } + else + { + switch(*i) + { + case ']': + in_variable = false; + output.push_string(build_get_variable(variable.c_str())); + variable.clear(); + break; + default: + variable.push_back(*i); + break; + } + } + } + } + void exportXML(XMLImporter& importer) + { + importer << c_str(); + } +}; + +class Conditional : public Evaluatable +{ + VariableString* m_test; +public: + Evaluatable* m_result; + Conditional(VariableString* test) : m_test(test) + { + } + ~Conditional() + { + delete m_test; + delete m_result; + } + void evaluate(StringBuffer& output) + { + StringBuffer buffer; + m_test->evaluate(buffer); + if(!string_empty(buffer.c_str())) + { + m_result->evaluate(output); + } + } + void exportXML(XMLImporter& importer) + { + StaticElement conditionElement("cond"); + conditionElement.insertAttribute("value", m_test->c_str()); + importer.pushElement(conditionElement); + m_result->exportXML(importer); + importer.popElement(conditionElement.name()); + } +}; + +typedef std::vector Evaluatables; + +class Tool : public Evaluatable +{ + Evaluatables m_evaluatables; +public: + ~Tool() + { + for(Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i) + { + delete (*i); + } + } + void push_back(Evaluatable* evaluatable) + { + m_evaluatables.push_back(evaluatable); + } + void evaluate(StringBuffer& output) + { + for(Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i) + { + (*i)->evaluate(output); + } + } + void exportXML(XMLImporter& importer) + { + for(Evaluatables::iterator i = m_evaluatables.begin(); i != m_evaluatables.end(); ++i) + { + (*i)->exportXML(importer); + } + } +}; + +#include "xml/ixml.h" + +class XMLElementParser : public TextOutputStream +{ +public: + virtual XMLElementParser& pushElement(const XMLElement& element) = 0; + virtual void popElement(const char* name) = 0; +}; + +class VariableStringXMLConstructor : public XMLElementParser +{ + StringBuffer m_buffer; + VariableString& m_variableString; +public: + VariableStringXMLConstructor(VariableString& variableString) : m_variableString(variableString) + { + } + ~VariableStringXMLConstructor() + { + m_variableString.setString(m_buffer.c_str()); + } + std::size_t write(const char* buffer, std::size_t length) + { + m_buffer.push_range(buffer, buffer + length); + return length; + } + XMLElementParser& pushElement(const XMLElement& element) + { + ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); + return *this; + } + void popElement(const char* name) + { + } +}; + +class ConditionalXMLConstructor : public XMLElementParser +{ + StringBuffer m_buffer; + Conditional& m_conditional; +public: + ConditionalXMLConstructor(Conditional& conditional) : m_conditional(conditional) + { + } + ~ConditionalXMLConstructor() + { + m_conditional.m_result = new VariableString(m_buffer.c_str()); + } + std::size_t write(const char* buffer, std::size_t length) + { + m_buffer.push_range(buffer, buffer + length); + return length; + } + XMLElementParser& pushElement(const XMLElement& element) + { + ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); + return *this; + } + void popElement(const char* name) + { + } +}; + +class ToolXMLConstructor : public XMLElementParser +{ + StringBuffer m_buffer; + Tool& m_tool; + ConditionalXMLConstructor* m_conditional; +public: + ToolXMLConstructor(Tool& tool) : m_tool(tool) + { + } + ~ToolXMLConstructor() + { + flush(); + } + std::size_t write(const char* buffer, std::size_t length) + { + m_buffer.push_range(buffer, buffer + length); + return length; + } + XMLElementParser& pushElement(const XMLElement& element) + { + if(string_equal(element.name(), "cond")) + { + flush(); + Conditional* conditional = new Conditional(new VariableString(element.attribute("value"))); + m_tool.push_back(conditional); + m_conditional = new ConditionalXMLConstructor(*conditional); + return *m_conditional; + } + else + { + ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); + return *this; + } + } + void popElement(const char* name) + { + if(string_equal(name, "cond")) + { + delete m_conditional; + } + } + + void flush() + { + if(!m_buffer.empty()) + { + m_tool.push_back(new VariableString(m_buffer.c_str())); + m_buffer.clear(); + } + } +}; + +typedef VariableString BuildCommand; +typedef std::list Build; + +class BuildXMLConstructor : public XMLElementParser +{ + VariableStringXMLConstructor* m_variableString; + Build& m_build; +public: + BuildXMLConstructor(Build& build) : m_build(build) + { + } + std::size_t write(const char* buffer, std::size_t length) + { + return length; + } + XMLElementParser& pushElement(const XMLElement& element) + { + if(string_equal(element.name(), "command")) + { + m_build.push_back(BuildCommand()); + m_variableString = new VariableStringXMLConstructor(m_build.back()); + return *m_variableString; + } + else + { + ERROR_MESSAGE("parse error: invalid element"); + return *this; + } + } + void popElement(const char* name) + { + delete m_variableString; + } +}; + +typedef std::pair BuildPair; + +class BuildPairEqual +{ + const char* m_name; +public: + BuildPairEqual(const char* name) : m_name(name) + { + } + bool operator()(const BuildPair& self) const + { + return string_equal(self.first.c_str(), m_name); + } +}; + +typedef std::list Project; + +Project::iterator Project_find(Project& project, const char* name) +{ + return std::find_if(project.begin(), project.end(), BuildPairEqual(name)); +} + +Project::iterator Project_find(Project& project, std::size_t index) +{ + Project::iterator i = project.begin(); + while(index-- != 0 && i != project.end()) + { + ++i; + } + return i; +} + +Build& project_find(Project& project, const char* build) +{ + Project::iterator i = Project_find(project, build); + ASSERT_MESSAGE(i != project.end(), "error finding build command"); + return (*i).second; +} + +Build::iterator Build_find(Build& build, std::size_t index) +{ + Build::iterator i = build.begin(); + while(index-- != 0 && i != build.end()) + { + ++i; + } + return i; +} + +typedef std::map Tools; + +class ProjectXMLConstructor : public XMLElementParser +{ + ToolXMLConstructor* m_tool; + BuildXMLConstructor* m_build; + Project& m_project; + Tools& m_tools; +public: + ProjectXMLConstructor(Project& project, Tools& tools) : m_project(project), m_tools(tools) + { + } + std::size_t write(const char* buffer, std::size_t length) + { + return length; + } + XMLElementParser& pushElement(const XMLElement& element) + { + if(string_equal(element.name(), "var")) + { + Tools::iterator i = m_tools.insert(Tools::value_type(element.attribute("name"), Tool())).first; + m_tool = new ToolXMLConstructor((*i).second); + return *m_tool; + } + else if(string_equal(element.name(), "build")) + { + m_project.push_back(Project::value_type(element.attribute("name"), Build())); + m_build = new BuildXMLConstructor(m_project.back().second); + return *m_build; + } + else + { + ERROR_MESSAGE("parse error: invalid element"); + return *this; + } + } + void popElement(const char* name) + { + if(string_equal(name, "var")) + { + delete m_tool; + } + else if(string_equal(name, "build")) + { + delete m_build; + } + } +}; + +class SkipAllParser : public XMLElementParser +{ +public: + std::size_t write(const char* buffer, std::size_t length) + { + return length; + } + XMLElementParser& pushElement(const XMLElement& element) + { + return *this; + } + void popElement(const char* name) + { + } +}; + +class RootXMLConstructor : public XMLElementParser +{ + CopiedString m_elementName; + XMLElementParser& m_parser; + SkipAllParser m_skip; + Version m_version; + bool m_compatible; +public: + RootXMLConstructor(const char* elementName, XMLElementParser& parser, const char* version) : + m_elementName(elementName), + m_parser(parser), + m_version(version_parse(version)), + m_compatible(false) + { + } + std::size_t write(const char* buffer, std::size_t length) + { + return length; + } + XMLElementParser& pushElement(const XMLElement& element) + { + if(string_equal(element.name(), m_elementName.c_str())) + { + Version dataVersion(version_parse(element.attribute("version"))); + if(version_compatible(m_version, dataVersion)) + { + m_compatible = true; + return m_parser; + } + else + { + return m_skip; + } + } + else + { + //ERROR_MESSAGE("parse error: invalid element \"" << element.name() << "\""); + return *this; + } + } + void popElement(const char* name) + { + } + + bool versionCompatible() const + { + return m_compatible; + } +}; + +namespace +{ + Project g_build_project; + Tools g_build_tools; + bool g_build_changed = false; +} + +void build_error_undefined_tool(const char* build, const char* tool) +{ + globalErrorStream() << "build " << makeQuoted(build) << " refers to undefined tool " << makeQuoted(tool) << '\n'; +} + +void project_verify(Project& project, Tools& tools) +{ +#if 0 + for(Project::iterator i = project.begin(); i != project.end(); ++i) + { + Build& build = (*i).second; + for(Build::iterator j = build.begin(); j != build.end(); ++j) + { + Tools::iterator k = tools.find((*j).first); + if(k == g_build_tools.end()) + { + build_error_undefined_tool((*i).first.c_str(), (*j).first.c_str()); + } + } + } +#endif +} + +void build_run(const char* name, CommandListener& listener) +{ + for(Tools::iterator i = g_build_tools.begin(); i != g_build_tools.end(); ++i) + { + StringBuffer output; + (*i).second.evaluate(output); + build_set_variable((*i).first.c_str(), output.c_str()); + } + + { + Project::iterator i = Project_find(g_build_project, name); + if(i != g_build_project.end()) + { + Build& build = (*i).second; + for(Build::iterator j = build.begin(); j != build.end(); ++j) + { + StringBuffer output; + (*j).evaluate(output); + listener.execute(output.c_str()); + } + } + else + { + globalErrorStream() << "build " << makeQuoted(name) << " not defined"; + } + } +} + + +typedef std::vector XMLElementStack; + +class XMLParser : public XMLImporter +{ + XMLElementStack m_stack; +public: + XMLParser(XMLElementParser& parser) + { + m_stack.push_back(&parser); + } + std::size_t write(const char* buffer, std::size_t length) + { + return m_stack.back()->write(buffer, length); + } + void pushElement(const XMLElement& element) + { + m_stack.push_back(&m_stack.back()->pushElement(element)); + } + void popElement(const char* name) + { + m_stack.pop_back(); + m_stack.back()->popElement(name); + } +}; + +#include "stream/textfilestream.h" +#include "xml/xmlparser.h" + +const char* const BUILDMENU_VERSION = "2.0"; + +bool build_commands_parse(const char* filename) +{ + TextFileInputStream projectFile(filename); + if(!projectFile.failed()) + { + ProjectXMLConstructor projectConstructor(g_build_project, g_build_tools); + RootXMLConstructor rootConstructor("project", projectConstructor, BUILDMENU_VERSION); + XMLParser importer(rootConstructor); + XMLStreamParser parser(projectFile); + parser.exportXML(importer); + + if(rootConstructor.versionCompatible()) + { + project_verify(g_build_project, g_build_tools); + + return true; + } + globalErrorStream() << "failed to parse build menu: " << makeQuoted(filename) << "\n"; + } + return false; +} + +void build_commands_clear() +{ + g_build_project.clear(); + g_build_tools.clear(); +} + +class BuildXMLExporter +{ + Build& m_build; +public: + BuildXMLExporter(Build& build) : m_build(build) + { + } + void exportXML(XMLImporter& importer) + { + importer << "\n"; + for(Build::iterator i = m_build.begin(); i != m_build.end(); ++i) + { + StaticElement commandElement("command"); + importer.pushElement(commandElement); + (*i).exportXML(importer); + importer.popElement(commandElement.name()); + importer << "\n"; + } + } +}; + +class ProjectXMLExporter +{ + Project& m_project; + Tools& m_tools; +public: + ProjectXMLExporter(Project& project, Tools& tools) : m_project(project), m_tools(tools) + { + } + void exportXML(XMLImporter& importer) + { + StaticElement projectElement("project"); + projectElement.insertAttribute("version", BUILDMENU_VERSION); + importer.pushElement(projectElement); + importer << "\n"; + + for(Tools::iterator i = m_tools.begin(); i != m_tools.end(); ++i) + { + StaticElement toolElement("var"); + toolElement.insertAttribute("name", (*i).first.c_str()); + importer.pushElement(toolElement); + (*i).second.exportXML(importer); + importer.popElement(toolElement.name()); + importer << "\n"; + } + for(Project::iterator i = m_project.begin(); i != m_project.end(); ++i) + { + StaticElement buildElement("build"); + buildElement.insertAttribute("name", (*i).first.c_str()); + importer.pushElement(buildElement); + BuildXMLExporter buildExporter((*i).second); + buildExporter.exportXML(importer); + importer.popElement(buildElement.name()); + importer << "\n"; + } + importer.popElement(projectElement.name()); + } +}; + +#include "xml/xmlwriter.h" + +void build_commands_write(const char* filename) +{ + TextFileOutputStream projectFile(filename); + if(!projectFile.failed()) + { + XMLStreamWriter writer(projectFile); + ProjectXMLExporter projectExporter(g_build_project, g_build_tools); + writer << "\n"; + projectExporter.exportXML(writer); + writer << "\n"; + } +} + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtkutil/dialog.h" +#include "gtkutil/closure.h" +#include "gtkutil/window.h" +#include "gtkdlgs.h" + +void Build_refreshMenu(GtkMenu* menu); + + +void BSPCommandList_Construct(GtkListStore* store, Project& project) +{ + gtk_list_store_clear(store); + + for(Project::iterator i = project.begin(); i != project.end(); ++i) + { + const char* buildName = (*i).first.c_str(); + + GtkTreeIter buildIter; + gtk_list_store_append(store, &buildIter); + gtk_list_store_set(store, &buildIter, 0, const_cast(buildName), -1); + } + + GtkTreeIter lastIter; + gtk_list_store_append(store, &lastIter); +} + +class ProjectList +{ +public: + Project& m_project; + GtkListStore* m_store; + bool m_changed; + ProjectList(Project& project) : m_project(project), m_changed(false) + { + } +}; + +gboolean project_cell_edited(GtkCellRendererText* cell, gchar* path_string, gchar* new_text, ProjectList* projectList) +{ + Project& project = projectList->m_project; + + GtkTreePath* path = gtk_tree_path_new_from_string(path_string); + + ASSERT_MESSAGE(gtk_tree_path_get_depth(path) == 1, "invalid path length"); + + GtkTreeIter iter; + gtk_tree_model_get_iter(GTK_TREE_MODEL(projectList->m_store), &iter, path); + + Project::iterator i = Project_find(project, gtk_tree_path_get_indices(path)[0]); + if(i != project.end()) + { + projectList->m_changed = true; + if(string_empty(new_text)) + { + project.erase(i); + Build_refreshMenu(g_bsp_menu); + + gtk_list_store_remove(projectList->m_store, &iter); + } + else + { + (*i).first = new_text; + Build_refreshMenu(g_bsp_menu); + + gtk_list_store_set(projectList->m_store, &iter, 0, new_text, -1); + } + } + else if(!string_empty(new_text)) + { + projectList->m_changed = true; + project.push_back(Project::value_type(new_text, Build())); + Build_refreshMenu(g_bsp_menu); + + gtk_list_store_set(projectList->m_store, &iter, 0, new_text, -1); + GtkTreeIter lastIter; + gtk_list_store_append(projectList->m_store, &lastIter); + } + + gtk_tree_path_free(path); + + return FALSE; +} + +gboolean project_key_press(GtkWidget* widget, GdkEventKey* event, ProjectList* projectList) +{ + Project& project = projectList->m_project; + + if(event->keyval == GDK_Delete) + { + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); + GtkTreeIter iter; + GtkTreeModel* model; + if(gtk_tree_selection_get_selected(selection, &model, &iter)) + { + GtkTreePath* path = gtk_tree_model_get_path(model, &iter); + Project::iterator x = Project_find(project, gtk_tree_path_get_indices(path)[0]); + gtk_tree_path_free(path); + + if(x != project.end()) + { + projectList->m_changed = true; + project.erase(x); + Build_refreshMenu(g_bsp_menu); + + gtk_list_store_remove(projectList->m_store, &iter); + } + } + } + return FALSE; +} + + +Build* g_current_build = 0; + +gboolean project_selection_changed(GtkTreeSelection* selection, GtkListStore* store) +{ + Project& project = g_build_project; + + gtk_list_store_clear(store); + + GtkTreeIter iter; + GtkTreeModel* model; + if(gtk_tree_selection_get_selected(selection, &model, &iter)) + { + GtkTreePath* path = gtk_tree_model_get_path(model, &iter); + Project::iterator x = Project_find(project, gtk_tree_path_get_indices(path)[0]); + gtk_tree_path_free(path); + + if(x != project.end()) + { + Build& build = (*x).second; + g_current_build = &build; + + for(Build::iterator i = build.begin(); i != build.end(); ++i) + { + GtkTreeIter commandIter; + gtk_list_store_append(store, &commandIter); + gtk_list_store_set(store, &commandIter, 0, const_cast((*i).c_str()), -1); + } + GtkTreeIter lastIter; + gtk_list_store_append(store, &lastIter); + } + else + { + g_current_build = 0; + } + } + else + { + g_current_build = 0; + } + + return FALSE; +} + +gboolean commands_cell_edited(GtkCellRendererText* cell, gchar* path_string, gchar* new_text, GtkListStore* store) +{ + if(g_current_build == 0) + { + return FALSE; + } + Build& build = *g_current_build; + + GtkTreePath* path = gtk_tree_path_new_from_string(path_string); + + ASSERT_MESSAGE(gtk_tree_path_get_depth(path) == 1, "invalid path length"); + + GtkTreeIter iter; + gtk_tree_model_get_iter(GTK_TREE_MODEL(store), &iter, path); + + Build::iterator i = Build_find(build, gtk_tree_path_get_indices(path)[0]); + if(i != build.end()) + { + g_build_changed = true; + (*i).setString(new_text); + + gtk_list_store_set(store, &iter, 0, new_text, -1); + } + else if(!string_empty(new_text)) + { + g_build_changed = true; + build.push_back(Build::value_type(VariableString(new_text))); + + gtk_list_store_set(store, &iter, 0, new_text, -1); + + GtkTreeIter lastIter; + gtk_list_store_append(store, &lastIter); + } + + gtk_tree_path_free(path); + + return FALSE; +} + +gboolean commands_key_press(GtkWidget* widget, GdkEventKey* event, GtkListStore* store) +{ + if(g_current_build == 0) + { + return FALSE; + } + Build& build = *g_current_build; + + if(event->keyval == GDK_Delete) + { + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(widget)); + GtkTreeIter iter; + GtkTreeModel* model; + if(gtk_tree_selection_get_selected(selection, &model, &iter)) + { + GtkTreePath* path = gtk_tree_model_get_path(model, &iter); + Build::iterator i = Build_find(build, gtk_tree_path_get_indices(path)[0]); + gtk_tree_path_free(path); + + if(i != build.end()) + { + g_build_changed = true; + build.erase(i); + + gtk_list_store_remove(store, &iter); + } + } + } + return FALSE; +} + + +GtkWindow* BuildMenuDialog_construct(ModalDialog& modal, ProjectList& projectList) +{ + GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Build Menu", G_CALLBACK(dialog_delete_callback), &modal, -1, 400); + + GtkWidget* buildView = 0; + + { + GtkTable* table1 = create_dialog_table(2, 2, 4, 4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(table1)); + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_table_attach(table1, GTK_WIDGET(vbox), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (GTK_FILL), 0, 0); + { + GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &modal); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + { + GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &modal); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + } + { + GtkFrame* frame = create_dialog_frame("Build menu"); + gtk_table_attach(table1, GTK_WIDGET(frame), 0, 1, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), 0, 0); + { + GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(scr)); + + { + GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING); + + GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); + + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + object_set_boolean_property(G_OBJECT(renderer), "editable", TRUE); + g_signal_connect(renderer, "edited", G_CALLBACK(project_cell_edited), &projectList); + + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, 0); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + + GtkTreeSelection* selection = gtk_tree_view_get_selection (GTK_TREE_VIEW(view)); + gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE); + + gtk_widget_show(view); + + buildView = view; + projectList.m_store = store; + gtk_container_add(GTK_CONTAINER (scr), view); + + g_signal_connect(G_OBJECT(view), "key_press_event", G_CALLBACK(project_key_press), &projectList); + + g_object_unref(G_OBJECT(store)); + } + } + } + { + GtkFrame* frame = create_dialog_frame("Commandline"); + gtk_table_attach(table1, GTK_WIDGET(frame), 0, 1, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), 0, 0); + { + GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(scr)); + + { + GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING); + + GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); + + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + object_set_boolean_property(G_OBJECT(renderer), "editable", TRUE); + g_signal_connect(renderer, "edited", G_CALLBACK(commands_cell_edited), store); + + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, 0); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + + GtkTreeSelection* selection = gtk_tree_view_get_selection (GTK_TREE_VIEW(view)); + gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE); + + gtk_widget_show(view); + + gtk_container_add(GTK_CONTAINER (scr), view); + + g_object_unref(G_OBJECT(store)); + + g_signal_connect(G_OBJECT(view), "key_press_event", G_CALLBACK(commands_key_press), store); + + g_signal_connect(G_OBJECT(gtk_tree_view_get_selection(GTK_TREE_VIEW(buildView))), "changed", G_CALLBACK(project_selection_changed), store); + } + } + } + } + + BSPCommandList_Construct(projectList.m_store, g_build_project); + + return window; +} + +namespace +{ + CopiedString g_buildMenu; +} + +void LoadBuildMenu(); + +void DoBuildMenu() +{ + ModalDialog modal; + + ProjectList projectList(g_build_project); + + GtkWindow* window = BuildMenuDialog_construct(modal, projectList); + + if(modal_dialog_show(window, modal) == eIDCANCEL) + { + build_commands_clear(); + LoadBuildMenu(); + + Build_refreshMenu(g_bsp_menu); + } + else if(projectList.m_changed) + { + g_build_changed = true; + } + + gtk_widget_destroy(GTK_WIDGET(window)); +} + + + +#include "gtkutil/menu.h" +#include "mainframe.h" +#include "preferences.h" +#include "qe3.h" + +typedef struct _GtkMenuItem GtkMenuItem; + +class BuildMenuItem +{ + const char* m_name; +public: + GtkMenuItem* m_item; + BuildMenuItem(const char* name, GtkMenuItem* item) + : m_name(name), m_item(item) + { + } + void run() + { + RunBSP(m_name); + } + typedef MemberCaller RunCaller; +}; + +typedef std::list BuildMenuItems; +BuildMenuItems g_BuildMenuItems; + + +GtkMenu* g_bsp_menu; + +void Build_constructMenu(GtkMenu* menu) +{ + for(Project::iterator i = g_build_project.begin(); i != g_build_project.end(); ++i) + { + g_BuildMenuItems.push_back(BuildMenuItem((*i).first.c_str(), 0)); + g_BuildMenuItems.back().m_item = create_menu_item_with_mnemonic(menu, (*i).first.c_str(), BuildMenuItem::RunCaller(g_BuildMenuItems.back())); + } +} + + +void Build_refreshMenu(GtkMenu* menu) +{ + for(BuildMenuItems::iterator i = g_BuildMenuItems.begin(); i != g_BuildMenuItems.end(); ++i) + { + gtk_container_remove(GTK_CONTAINER(menu), GTK_WIDGET((*i).m_item)); + } + + g_BuildMenuItems.clear(); + + Build_constructMenu(menu); +} + + +void LoadBuildMenu() +{ + if(string_empty(g_buildMenu.c_str()) || !build_commands_parse(g_buildMenu.c_str())) + { + { + StringOutputStream buffer(256); + buffer << GameToolsPath_get() << "default_build_menu.xml"; + + bool success = build_commands_parse(buffer.c_str()); + ASSERT_MESSAGE(success, "failed to parse default build commands: " << buffer.c_str()); + } + { + StringOutputStream buffer(256); + buffer << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/build_menu.xml"; + + g_buildMenu = buffer.c_str(); + } + } +} + +void SaveBuildMenu() +{ + if(g_build_changed) + { + g_build_changed = false; + build_commands_write(g_buildMenu.c_str()); + } +} + +#include "preferencesystem.h" +#include "stringio.h" + +void BuildMenu_Construct() +{ + GlobalPreferenceSystem().registerPreference("BuildMenu", CopiedStringImportStringCaller(g_buildMenu), CopiedStringExportStringCaller(g_buildMenu)); + LoadBuildMenu(); +} +void BuildMenu_Destroy() +{ + SaveBuildMenu(); +} diff --git a/misc/mediasource/netradiant-src/radiant/build.h b/misc/mediasource/netradiant-src/radiant/build.h new file mode 100644 index 00000000..3b3244d7 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/build.h @@ -0,0 +1,44 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_BUILD_H) +#define INCLUDED_BUILD_H + +void build_set_variable(const char* name, const char* value); +void build_clear_variables(); + +class CommandListener +{ +public: + virtual void execute(const char* command) = 0; +}; +void build_run(const char* name, CommandListener& listener); + +void DoBuildMenu(); + +void BuildMenu_Construct(); +void BuildMenu_Destroy(); + +typedef struct _GtkMenu GtkMenu; +void Build_constructMenu(GtkMenu* menu); +extern GtkMenu* g_bsp_menu; + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/camwindow.cpp b/misc/mediasource/netradiant-src/radiant/camwindow.cpp new file mode 100644 index 00000000..f0744e48 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/camwindow.cpp @@ -0,0 +1,2116 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Camera Window +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "camwindow.h" + +#include "debugging/debugging.h" + +#include "iscenegraph.h" +#include "irender.h" +#include "igl.h" +#include "icamera.h" +#include "cullable.h" +#include "renderable.h" +#include "preferencesystem.h" + +#include "signal/signal.h" +#include "container/array.h" +#include "scenelib.h" +#include "render.h" +#include "cmdlib.h" +#include "math/frustum.h" + +#include "gtkutil/widget.h" +#include "gtkutil/button.h" +#include "gtkutil/toolbar.h" +#include "gtkutil/glwidget.h" +#include "gtkutil/xorrectangle.h" +#include "gtkmisc.h" +#include "selection.h" +#include "mainframe.h" +#include "preferences.h" +#include "commands.h" +#include "xywindow.h" +#include "windowobservers.h" +#include "renderstate.h" + +#include "timer.h" + +Signal0 g_cameraMoved_callbacks; + +void AddCameraMovedCallback(const SignalHandler& handler) +{ + g_cameraMoved_callbacks.connectLast(handler); +} + +void CameraMovedNotify() +{ + g_cameraMoved_callbacks(); +} + + +struct camwindow_globals_private_t +{ + int m_nMoveSpeed; + bool m_bCamLinkSpeed; + int m_nAngleSpeed; + bool m_bCamInverseMouse; + bool m_bCamDiscrete; + bool m_bCubicClipping; + bool m_showStats; + int m_nStrafeMode; + + camwindow_globals_private_t() : + m_nMoveSpeed(100), + m_bCamLinkSpeed(true), + m_nAngleSpeed(3), + m_bCamInverseMouse(false), + m_bCamDiscrete(true), + m_bCubicClipping(true), + m_showStats(true), + m_nStrafeMode(0) + { + } + +}; + +camwindow_globals_private_t g_camwindow_globals_private; + + +const Matrix4 g_opengl2radiant( + 0, 0,-1, 0, + -1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 0, 1 +); + +const Matrix4 g_radiant2opengl( + 0,-1, 0, 0, + 0, 0, 1, 0, + -1, 0, 0, 0, + 0, 0, 0, 1 +); + +struct camera_t; +void Camera_mouseMove(camera_t& camera, int x, int y); + +enum camera_draw_mode +{ + cd_wire, + cd_solid, + cd_texture, + cd_lighting +}; + +struct camera_t +{ + int width, height; + + bool timing; + + Vector3 origin; + Vector3 angles; + + Vector3 color; // background + + Vector3 forward, right; // move matrix (TTimo: used to have up but it was not updated) + Vector3 vup, vpn, vright; // view matrix (taken from the modelview matrix) + + Matrix4 projection; + Matrix4 modelview; + + bool m_strafe; // true when in strafemode toggled by the ctrl-key + bool m_strafe_forward; // true when in strafemode by ctrl-key and shift is pressed for forward strafing + + unsigned int movementflags; // movement flags + Timer m_keycontrol_timer; + guint m_keymove_handler; + + + float fieldOfView; + + DeferredMotionDelta m_mouseMove; + + static void motionDelta(int x, int y, void* data) + { + Camera_mouseMove(*reinterpret_cast(data), x, y); + } + + View* m_view; + Callback m_update; + + static camera_draw_mode draw_mode; + + camera_t(View* view, const Callback& update) + : width(0), + height(0), + timing(false), + origin(0, 0, 0), + angles(0, 0, 0), + color(0, 0, 0), + movementflags(0), + m_keymove_handler(0), + fieldOfView(90.0f), + m_mouseMove(motionDelta, this), + m_view(view), + m_update(update) + { + } +}; + +camera_draw_mode camera_t::draw_mode = cd_texture; + +inline Matrix4 projection_for_camera(float near_z, float far_z, float fieldOfView, int width, int height) +{ + const float half_width = static_cast(near_z * tan(degrees_to_radians(fieldOfView * 0.5))); + const float half_height = half_width * (static_cast(height) / static_cast(width)); + + return matrix4_frustum( + -half_width, + half_width, + -half_height, + half_height, + near_z, + far_z + ); +} + +float Camera_getFarClipPlane(camera_t& camera) +{ + return (g_camwindow_globals_private.m_bCubicClipping)? pow(2.0, (g_camwindow_globals.m_nCubicScale + 7) / 2.0) : 32768.0f; +} + +void Camera_updateProjection(camera_t& camera) +{ + float farClip = Camera_getFarClipPlane(camera); + camera.projection = projection_for_camera(farClip / 4096.0f, farClip, camera.fieldOfView, camera.width, camera.height); + + camera.m_view->Construct(camera.projection, camera.modelview, camera.width, camera.height); +} + +void Camera_updateVectors(camera_t& camera) +{ + for (int i=0 ; i<3 ; i++) + { + camera.vright[i] = camera.modelview[(i<<2)+0]; + camera.vup[i] = camera.modelview[(i<<2)+1]; + camera.vpn[i] = camera.modelview[(i<<2)+2]; + } +} + +void Camera_updateModelview(camera_t& camera) +{ + camera.modelview = g_matrix4_identity; + + // roll, pitch, yaw + Vector3 radiant_eulerXYZ(0, -camera.angles[CAMERA_PITCH], camera.angles[CAMERA_YAW]); + + matrix4_translate_by_vec3(camera.modelview, camera.origin); + matrix4_rotate_by_euler_xyz_degrees(camera.modelview, radiant_eulerXYZ); + matrix4_multiply_by_matrix4(camera.modelview, g_radiant2opengl); + matrix4_affine_invert(camera.modelview); + + Camera_updateVectors(camera); + + camera.m_view->Construct(camera.projection, camera.modelview, camera.width, camera.height); +} + + +void Camera_Move_updateAxes(camera_t& camera) +{ + double ya = degrees_to_radians(camera.angles[CAMERA_YAW]); + + // the movement matrix is kept 2d + camera.forward[0] = static_cast(cos(ya)); + camera.forward[1] = static_cast(sin(ya)); + camera.forward[2] = 0; + camera.right[0] = camera.forward[1]; + camera.right[1] = -camera.forward[0]; +} + +void Camera_Freemove_updateAxes(camera_t& camera) +{ + camera.right = camera.vright; + camera.forward = vector3_negated(camera.vpn); +} + +const Vector3& Camera_getOrigin(camera_t& camera) +{ + return camera.origin; +} + +void Camera_setOrigin(camera_t& camera, const Vector3& origin) +{ + camera.origin = origin; + Camera_updateModelview(camera); + camera.m_update(); + CameraMovedNotify(); +} + +const Vector3& Camera_getAngles(camera_t& camera) +{ + return camera.angles; +} + +void Camera_setAngles(camera_t& camera, const Vector3& angles) +{ + camera.angles = angles; + Camera_updateModelview(camera); + camera.m_update(); + CameraMovedNotify(); +} + + +void Camera_FreeMove(camera_t& camera, int dx, int dy) +{ + // free strafe mode, toggled by the ctrl key with optional shift for forward movement + if(camera.m_strafe) + { + float strafespeed = 0.65f; + + if(g_camwindow_globals_private.m_bCamLinkSpeed) + { + strafespeed = (float)g_camwindow_globals_private.m_nMoveSpeed / 100; + } + + camera.origin -= camera.vright * strafespeed * dx; + if(camera.m_strafe_forward) + camera.origin += camera.vpn * strafespeed * dy; + else + camera.origin += camera.vup * strafespeed * dy; + } + else// free rotation + { + const float dtime = 0.1f; + + if (g_camwindow_globals_private.m_bCamInverseMouse) + camera.angles[CAMERA_PITCH] -= dy * dtime * g_camwindow_globals_private.m_nAngleSpeed; + else + camera.angles[CAMERA_PITCH] += dy * dtime * g_camwindow_globals_private.m_nAngleSpeed; + + camera.angles[CAMERA_YAW] += dx * dtime * g_camwindow_globals_private.m_nAngleSpeed; + + if (camera.angles[CAMERA_PITCH] > 90) + camera.angles[CAMERA_PITCH] = 90; + else if (camera.angles[CAMERA_PITCH] < -90) + camera.angles[CAMERA_PITCH] = -90; + + if (camera.angles[CAMERA_YAW] >= 360) + camera.angles[CAMERA_YAW] -=360; + else if (camera.angles[CAMERA_YAW] <= 0) + camera.angles[CAMERA_YAW] +=360; + } + + Camera_updateModelview(camera); + Camera_Freemove_updateAxes(camera); +} + +void Cam_MouseControl(camera_t& camera, int x, int y) +{ + int xl, xh; + int yl, yh; + float xf, yf; + + xf = (float)(x - camera.width/2) / (camera.width/2); + yf = (float)(y - camera.height/2) / (camera.height/2); + + xl = camera.width/3; + xh = xl*2; + yl = camera.height/3; + yh = yl*2; + + xf *= 1.0f - fabsf(yf); + if (xf < 0) + { + xf += 0.1f; + if (xf > 0) + xf = 0; + } + else + { + xf -= 0.1f; + if (xf < 0) + xf = 0; + } + + vector3_add(camera.origin, vector3_scaled(camera.forward, yf * 0.1f* g_camwindow_globals_private.m_nMoveSpeed)); + camera.angles[CAMERA_YAW] += xf * -0.1f * g_camwindow_globals_private.m_nAngleSpeed; + + Camera_updateModelview(camera); +} + +void Camera_mouseMove(camera_t& camera, int x, int y) +{ + //globalOutputStream() << "mousemove... "; + Camera_FreeMove(camera, -x, -y); + camera.m_update(); + CameraMovedNotify(); +} + +const unsigned int MOVE_NONE = 0; +const unsigned int MOVE_FORWARD = 1 << 0; +const unsigned int MOVE_BACK = 1 << 1; +const unsigned int MOVE_ROTRIGHT = 1 << 2; +const unsigned int MOVE_ROTLEFT = 1 << 3; +const unsigned int MOVE_STRAFERIGHT = 1 << 4; +const unsigned int MOVE_STRAFELEFT = 1 << 5; +const unsigned int MOVE_UP = 1 << 6; +const unsigned int MOVE_DOWN = 1 << 7; +const unsigned int MOVE_PITCHUP = 1 << 8; +const unsigned int MOVE_PITCHDOWN = 1 << 9; +const unsigned int MOVE_ALL = MOVE_FORWARD|MOVE_BACK|MOVE_ROTRIGHT|MOVE_ROTLEFT|MOVE_STRAFERIGHT|MOVE_STRAFELEFT|MOVE_UP|MOVE_DOWN|MOVE_PITCHUP|MOVE_PITCHDOWN; + +void Cam_KeyControl(camera_t& camera, float dtime) +{ + // Update angles + if (camera.movementflags & MOVE_ROTLEFT) + camera.angles[CAMERA_YAW] += 15 * dtime* g_camwindow_globals_private.m_nAngleSpeed; + if (camera.movementflags & MOVE_ROTRIGHT) + camera.angles[CAMERA_YAW] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed; + if (camera.movementflags & MOVE_PITCHUP) + { + camera.angles[CAMERA_PITCH] += 15 * dtime* g_camwindow_globals_private.m_nAngleSpeed; + if(camera.angles[CAMERA_PITCH] > 90) + camera.angles[CAMERA_PITCH] = 90; + } + if (camera.movementflags & MOVE_PITCHDOWN) + { + camera.angles[CAMERA_PITCH] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed; + if(camera.angles[CAMERA_PITCH] < -90) + camera.angles[CAMERA_PITCH] = -90; + } + + Camera_updateModelview(camera); + Camera_Freemove_updateAxes(camera); + + // Update position + if (camera.movementflags & MOVE_FORWARD) + vector3_add(camera.origin, vector3_scaled(camera.forward, dtime * g_camwindow_globals_private.m_nMoveSpeed)); + if (camera.movementflags & MOVE_BACK) + vector3_add(camera.origin, vector3_scaled(camera.forward, -dtime * g_camwindow_globals_private.m_nMoveSpeed)); + if (camera.movementflags & MOVE_STRAFELEFT) + vector3_add(camera.origin, vector3_scaled(camera.right, -dtime * g_camwindow_globals_private.m_nMoveSpeed)); + if (camera.movementflags & MOVE_STRAFERIGHT) + vector3_add(camera.origin, vector3_scaled(camera.right, dtime * g_camwindow_globals_private.m_nMoveSpeed)); + if (camera.movementflags & MOVE_UP) + vector3_add(camera.origin, vector3_scaled(g_vector3_axis_z, dtime * g_camwindow_globals_private.m_nMoveSpeed)); + if (camera.movementflags & MOVE_DOWN) + vector3_add(camera.origin, vector3_scaled(g_vector3_axis_z, -dtime * g_camwindow_globals_private.m_nMoveSpeed)); + + Camera_updateModelview(camera); +} + +void Camera_keyMove(camera_t& camera) +{ + camera.m_mouseMove.flush(); + + //globalOutputStream() << "keymove... "; + float time_seconds = camera.m_keycontrol_timer.elapsed_msec() / static_cast(msec_per_sec); + camera.m_keycontrol_timer.start(); + if(time_seconds > 0.05f) + { + time_seconds = 0.05f; // 20fps + } + Cam_KeyControl(camera, time_seconds * 5.0f); + + camera.m_update(); + CameraMovedNotify(); +} + +gboolean camera_keymove(gpointer data) +{ + Camera_keyMove(*reinterpret_cast(data)); + return TRUE; +} + +void Camera_setMovementFlags(camera_t& camera, unsigned int mask) +{ + if((~camera.movementflags & mask) != 0 && camera.movementflags == 0) + { + camera.m_keymove_handler = g_idle_add(camera_keymove, &camera); + } + camera.movementflags |= mask; +} +void Camera_clearMovementFlags(camera_t& camera, unsigned int mask) +{ + if((camera.movementflags & ~mask) == 0 && camera.movementflags != 0) + { + g_source_remove(camera.m_keymove_handler); + camera.m_keymove_handler = 0; + } + camera.movementflags &= ~mask; +} + +void Camera_MoveForward_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_FORWARD); +} +void Camera_MoveForward_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_FORWARD); +} +void Camera_MoveBack_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_BACK); +} +void Camera_MoveBack_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_BACK); +} + +void Camera_MoveLeft_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_STRAFELEFT); +} +void Camera_MoveLeft_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_STRAFELEFT); +} +void Camera_MoveRight_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_STRAFERIGHT); +} +void Camera_MoveRight_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_STRAFERIGHT); +} + +void Camera_MoveUp_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_UP); +} +void Camera_MoveUp_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_UP); +} +void Camera_MoveDown_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_DOWN); +} +void Camera_MoveDown_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_DOWN); +} + +void Camera_RotateLeft_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_ROTLEFT); +} +void Camera_RotateLeft_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_ROTLEFT); +} +void Camera_RotateRight_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_ROTRIGHT); +} +void Camera_RotateRight_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_ROTRIGHT); +} + +void Camera_PitchUp_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_PITCHUP); +} +void Camera_PitchUp_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_PITCHUP); +} +void Camera_PitchDown_KeyDown(camera_t& camera) +{ + Camera_setMovementFlags(camera, MOVE_PITCHDOWN); +} +void Camera_PitchDown_KeyUp(camera_t& camera) +{ + Camera_clearMovementFlags(camera, MOVE_PITCHDOWN); +} + + +typedef ReferenceCaller FreeMoveCameraMoveForwardKeyDownCaller; +typedef ReferenceCaller FreeMoveCameraMoveForwardKeyUpCaller; +typedef ReferenceCaller FreeMoveCameraMoveBackKeyDownCaller; +typedef ReferenceCaller FreeMoveCameraMoveBackKeyUpCaller; +typedef ReferenceCaller FreeMoveCameraMoveLeftKeyDownCaller; +typedef ReferenceCaller FreeMoveCameraMoveLeftKeyUpCaller; +typedef ReferenceCaller FreeMoveCameraMoveRightKeyDownCaller; +typedef ReferenceCaller FreeMoveCameraMoveRightKeyUpCaller; +typedef ReferenceCaller FreeMoveCameraMoveUpKeyDownCaller; +typedef ReferenceCaller FreeMoveCameraMoveUpKeyUpCaller; +typedef ReferenceCaller FreeMoveCameraMoveDownKeyDownCaller; +typedef ReferenceCaller FreeMoveCameraMoveDownKeyUpCaller; + + +#define SPEED_MOVE 32 +#define SPEED_TURN 22.5 +#define MIN_CAM_SPEED 10 +#define MAX_CAM_SPEED 610 +#define CAM_SPEED_STEP 50 + +void Camera_MoveForward_Discrete(camera_t& camera) +{ + Camera_Move_updateAxes(camera); + Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.forward, SPEED_MOVE))); +} +void Camera_MoveBack_Discrete(camera_t& camera) +{ + Camera_Move_updateAxes(camera); + Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.forward, -SPEED_MOVE))); +} + +void Camera_MoveUp_Discrete(camera_t& camera) +{ + Vector3 origin(Camera_getOrigin(camera)); + origin[2] += SPEED_MOVE; + Camera_setOrigin(camera, origin); +} +void Camera_MoveDown_Discrete(camera_t& camera) +{ + Vector3 origin(Camera_getOrigin(camera)); + origin[2] -= SPEED_MOVE; + Camera_setOrigin(camera, origin); +} + +void Camera_MoveLeft_Discrete(camera_t& camera) +{ + Camera_Move_updateAxes(camera); + Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.right, -SPEED_MOVE))); +} +void Camera_MoveRight_Discrete(camera_t& camera) +{ + Camera_Move_updateAxes(camera); + Camera_setOrigin(camera, vector3_added(Camera_getOrigin(camera), vector3_scaled(camera.right, SPEED_MOVE))); +} + +void Camera_RotateLeft_Discrete(camera_t& camera) +{ + Vector3 angles(Camera_getAngles(camera)); + angles[CAMERA_YAW] += SPEED_TURN; + Camera_setAngles(camera, angles); +} +void Camera_RotateRight_Discrete(camera_t& camera) +{ + Vector3 angles(Camera_getAngles(camera)); + angles[CAMERA_YAW] -= SPEED_TURN; + Camera_setAngles(camera, angles); +} + +void Camera_PitchUp_Discrete(camera_t& camera) +{ + Vector3 angles(Camera_getAngles(camera)); + angles[CAMERA_PITCH] += SPEED_TURN; + if (angles[CAMERA_PITCH] > 90) + angles[CAMERA_PITCH] = 90; + Camera_setAngles(camera, angles); +} +void Camera_PitchDown_Discrete(camera_t& camera) +{ + Vector3 angles(Camera_getAngles(camera)); + angles[CAMERA_PITCH] -= SPEED_TURN; + if (angles[CAMERA_PITCH] < -90) + angles[CAMERA_PITCH] = -90; + Camera_setAngles(camera, angles); +} + + +class RadiantCameraView : public CameraView +{ + camera_t& m_camera; + View* m_view; + Callback m_update; +public: + RadiantCameraView(camera_t& camera, View* view, const Callback& update) : m_camera(camera), m_view(view), m_update(update) + { + } + void update() + { + m_view->Construct(m_camera.projection, m_camera.modelview, m_camera.width, m_camera.height); + m_update(); + } + void setModelview(const Matrix4& modelview) + { + m_camera.modelview = modelview; + matrix4_multiply_by_matrix4(m_camera.modelview, g_radiant2opengl); + matrix4_affine_invert(m_camera.modelview); + Camera_updateVectors(m_camera); + update(); + } + void setFieldOfView(float fieldOfView) + { + float farClip = Camera_getFarClipPlane(m_camera); + m_camera.projection = projection_for_camera(farClip / 4096.0f, farClip, fieldOfView, m_camera.width, m_camera.height); + update(); + } +}; + + +void Camera_motionDelta(int x, int y, unsigned int state, void* data) +{ + camera_t* cam = reinterpret_cast(data); + + cam->m_mouseMove.motion_delta(x, y, state); + + switch(g_camwindow_globals_private.m_nStrafeMode) + { + case 0: + cam->m_strafe = (state & GDK_CONTROL_MASK) != 0; + if(cam->m_strafe) + cam->m_strafe_forward = (state & GDK_SHIFT_MASK) != 0; + else + cam->m_strafe_forward = false; + break; + case 1: + cam->m_strafe = (state & GDK_CONTROL_MASK) != 0 && (state & GDK_SHIFT_MASK) == 0; + cam->m_strafe_forward = false; + break; + case 2: + cam->m_strafe = (state & GDK_CONTROL_MASK) != 0 && (state & GDK_SHIFT_MASK) == 0; + cam->m_strafe_forward = cam->m_strafe; + break; + } +} + +class CamWnd +{ + View m_view; + camera_t m_Camera; + RadiantCameraView m_cameraview; +#if 0 + int m_PositionDragCursorX; + int m_PositionDragCursorY; +#endif + + guint m_freemove_handle_focusout; + + static Shader* m_state_select1; + static Shader* m_state_select2; + + FreezePointer m_freezePointer; + +public: + GtkWidget* m_gl_widget; + GtkWindow* m_parent; + + SelectionSystemWindowObserver* m_window_observer; + XORRectangle m_XORRectangle; + + DeferredDraw m_deferredDraw; + DeferredMotion m_deferred_motion; + + guint m_selection_button_press_handler; + guint m_selection_button_release_handler; + guint m_selection_motion_handler; + + guint m_freelook_button_press_handler; + + guint m_sizeHandler; + guint m_exposeHandler; + + CamWnd(); + ~CamWnd(); + + bool m_drawing; + void queue_draw() + { + //ASSERT_MESSAGE(!m_drawing, "CamWnd::queue_draw(): called while draw is already in progress"); + if(m_drawing) + { + return; + } + //globalOutputStream() << "queue... "; + m_deferredDraw.draw(); + } + void draw(); + + static void captureStates() + { + m_state_select1 = GlobalShaderCache().capture("$CAM_HIGHLIGHT"); + m_state_select2 = GlobalShaderCache().capture("$CAM_OVERLAY"); + } + static void releaseStates() + { + GlobalShaderCache().release("$CAM_HIGHLIGHT"); + GlobalShaderCache().release("$CAM_OVERLAY"); + } + + camera_t& getCamera() + { + return m_Camera; + }; + + void BenchMark(); + void Cam_ChangeFloor(bool up); + + void DisableFreeMove(); + void EnableFreeMove(); + bool m_bFreeMove; + + CameraView& getCameraView() + { + return m_cameraview; + } + +private: + void Cam_Draw(); +}; + +typedef MemberCaller CamWndQueueDraw; + +Shader* CamWnd::m_state_select1 = 0; +Shader* CamWnd::m_state_select2 = 0; + +CamWnd* NewCamWnd() +{ + return new CamWnd; +} +void DeleteCamWnd(CamWnd* camwnd) +{ + delete camwnd; +} + +void CamWnd_constructStatic() +{ + CamWnd::captureStates(); +} + +void CamWnd_destroyStatic() +{ + CamWnd::releaseStates(); +} + +static CamWnd* g_camwnd = 0; + +void GlobalCamera_setCamWnd(CamWnd& camwnd) +{ + g_camwnd = &camwnd; +} + + +GtkWidget* CamWnd_getWidget(CamWnd& camwnd) +{ + return camwnd.m_gl_widget; +} + +GtkWindow* CamWnd_getParent(CamWnd& camwnd) +{ + return camwnd.m_parent; +} + +ToggleShown g_camera_shown(true); + +void CamWnd_setParent(CamWnd& camwnd, GtkWindow* parent) +{ + camwnd.m_parent = parent; + g_camera_shown.connect(GTK_WIDGET(camwnd.m_parent)); +} + +void CamWnd_Update(CamWnd& camwnd) +{ + camwnd.queue_draw(); +} + + + +camwindow_globals_t g_camwindow_globals; + +const Vector3& Camera_getOrigin(CamWnd& camwnd) +{ + return Camera_getOrigin(camwnd.getCamera()); +} + +void Camera_setOrigin(CamWnd& camwnd, const Vector3& origin) +{ + Camera_setOrigin(camwnd.getCamera(), origin); +} + +const Vector3& Camera_getAngles(CamWnd& camwnd) +{ + return Camera_getAngles(camwnd.getCamera()); +} + +void Camera_setAngles(CamWnd& camwnd, const Vector3& angles) +{ + Camera_setAngles(camwnd.getCamera(), angles); +} + + +// ============================================================================= +// CamWnd class + +gboolean enable_freelook_button_press(GtkWidget* widget, GdkEventButton* event, CamWnd* camwnd) +{ + if(event->type == GDK_BUTTON_PRESS && event->button == 3) + { + camwnd->EnableFreeMove(); + return TRUE; + } + return FALSE; +} + +gboolean disable_freelook_button_press(GtkWidget* widget, GdkEventButton* event, CamWnd* camwnd) +{ + if(event->type == GDK_BUTTON_PRESS && event->button == 3) + { + camwnd->DisableFreeMove(); + return TRUE; + } + return FALSE; +} + +#if 0 +gboolean mousecontrol_button_press(GtkWidget* widget, GdkEventButton* event, CamWnd* camwnd) +{ + if(event->type == GDK_BUTTON_PRESS && event->button == 3) + { + Cam_MouseControl(camwnd->getCamera(), event->x, widget->allocation.height - 1 - event->y); + } + return FALSE; +} +#endif + +void camwnd_update_xor_rectangle(CamWnd& self, rect_t area) +{ + if(GTK_WIDGET_VISIBLE(self.m_gl_widget)) + { + self.m_XORRectangle.set(rectangle_from_area(area.min, area.max, self.getCamera().width, self.getCamera().height)); + } +} + + +gboolean selection_button_press(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) +{ + if(event->type == GDK_BUTTON_PRESS) + { + observer->onMouseDown(WindowVector_forDouble(event->x, event->y), button_for_button(event->button), modifiers_for_state(event->state)); + } + return FALSE; +} + +gboolean selection_button_release(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) +{ + if(event->type == GDK_BUTTON_RELEASE) + { + observer->onMouseUp(WindowVector_forDouble(event->x, event->y), button_for_button(event->button), modifiers_for_state(event->state)); + } + return FALSE; +} + +void selection_motion(gdouble x, gdouble y, guint state, void* data) +{ + //globalOutputStream() << "motion... "; + reinterpret_cast(data)->onMouseMotion(WindowVector_forDouble(x, y), modifiers_for_state(state)); +} + +inline WindowVector windowvector_for_widget_centre(GtkWidget* widget) +{ + return WindowVector(static_cast(widget->allocation.width / 2), static_cast(widget->allocation.height / 2)); +} + +gboolean selection_button_press_freemove(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) +{ + if(event->type == GDK_BUTTON_PRESS) + { + observer->onMouseDown(windowvector_for_widget_centre(widget), button_for_button(event->button), modifiers_for_state(event->state)); + } + return FALSE; +} + +gboolean selection_button_release_freemove(GtkWidget* widget, GdkEventButton* event, WindowObserver* observer) +{ + if(event->type == GDK_BUTTON_RELEASE) + { + observer->onMouseUp(windowvector_for_widget_centre(widget), button_for_button(event->button), modifiers_for_state(event->state)); + } + return FALSE; +} + +gboolean selection_motion_freemove(GtkWidget *widget, GdkEventMotion *event, WindowObserver* observer) +{ + observer->onMouseMotion(windowvector_for_widget_centre(widget), modifiers_for_state(event->state)); + return FALSE; +} + +gboolean wheelmove_scroll(GtkWidget* widget, GdkEventScroll* event, CamWnd* camwnd) +{ + if(event->direction == GDK_SCROLL_UP) + { + Camera_Freemove_updateAxes(camwnd->getCamera()); + Camera_setOrigin(*camwnd, vector3_added(Camera_getOrigin(*camwnd), vector3_scaled(camwnd->getCamera().forward, static_cast(g_camwindow_globals_private.m_nMoveSpeed)))); + } + else if(event->direction == GDK_SCROLL_DOWN) + { + Camera_Freemove_updateAxes(camwnd->getCamera()); + Camera_setOrigin(*camwnd, vector3_added(Camera_getOrigin(*camwnd), vector3_scaled(camwnd->getCamera().forward, -static_cast(g_camwindow_globals_private.m_nMoveSpeed)))); + } + + return FALSE; +} + +gboolean camera_size_allocate(GtkWidget* widget, GtkAllocation* allocation, CamWnd* camwnd) +{ + camwnd->getCamera().width = allocation->width; + camwnd->getCamera().height = allocation->height; + Camera_updateProjection(camwnd->getCamera()); + camwnd->m_window_observer->onSizeChanged(camwnd->getCamera().width, camwnd->getCamera().height); + camwnd->queue_draw(); + return FALSE; +} + +gboolean camera_expose(GtkWidget* widget, GdkEventExpose* event, gpointer data) +{ + reinterpret_cast(data)->draw(); + return FALSE; +} + +void KeyEvent_connect(const char* name) +{ + const KeyEvent& keyEvent = GlobalKeyEvents_find(name); + keydown_accelerators_add(keyEvent.m_accelerator, keyEvent.m_keyDown); + keyup_accelerators_add(keyEvent.m_accelerator, keyEvent.m_keyUp); +} + +void KeyEvent_disconnect(const char* name) +{ + const KeyEvent& keyEvent = GlobalKeyEvents_find(name); + keydown_accelerators_remove(keyEvent.m_accelerator); + keyup_accelerators_remove(keyEvent.m_accelerator); +} + +void CamWnd_registerCommands(CamWnd& camwnd) +{ + GlobalKeyEvents_insert("CameraForward", Accelerator(GDK_Up), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraBack", Accelerator(GDK_Down), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraLeft", Accelerator(GDK_Left), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraRight", Accelerator(GDK_Right), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraStrafeRight", Accelerator(GDK_period), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraStrafeLeft", Accelerator(GDK_comma), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraUp", Accelerator('D'), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraDown", Accelerator('C'), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraAngleDown", Accelerator('A'), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraAngleUp", Accelerator('Z'), + ReferenceCaller(camwnd.getCamera()), + ReferenceCaller(camwnd.getCamera()) + ); + + GlobalKeyEvents_insert("CameraFreeMoveForward", Accelerator(GDK_Up), + FreeMoveCameraMoveForwardKeyDownCaller(camwnd.getCamera()), + FreeMoveCameraMoveForwardKeyUpCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraFreeMoveBack", Accelerator(GDK_Down), + FreeMoveCameraMoveBackKeyDownCaller(camwnd.getCamera()), + FreeMoveCameraMoveBackKeyUpCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraFreeMoveLeft", Accelerator(GDK_Left), + FreeMoveCameraMoveLeftKeyDownCaller(camwnd.getCamera()), + FreeMoveCameraMoveLeftKeyUpCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraFreeMoveRight", Accelerator(GDK_Right), + FreeMoveCameraMoveRightKeyDownCaller(camwnd.getCamera()), + FreeMoveCameraMoveRightKeyUpCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraFreeMoveUp", Accelerator('D'), + FreeMoveCameraMoveUpKeyDownCaller(camwnd.getCamera()), + FreeMoveCameraMoveUpKeyUpCaller(camwnd.getCamera()) + ); + GlobalKeyEvents_insert("CameraFreeMoveDown", Accelerator('C'), + FreeMoveCameraMoveDownKeyDownCaller(camwnd.getCamera()), + FreeMoveCameraMoveDownKeyUpCaller(camwnd.getCamera()) + ); + + GlobalCommands_insert("CameraForward", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Up)); + GlobalCommands_insert("CameraBack", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Down)); + GlobalCommands_insert("CameraLeft", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Left)); + GlobalCommands_insert("CameraRight", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_Right)); + GlobalCommands_insert("CameraStrafeRight", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_period)); + GlobalCommands_insert("CameraStrafeLeft", ReferenceCaller(camwnd.getCamera()), Accelerator(GDK_comma)); + + GlobalCommands_insert("CameraUp", ReferenceCaller(camwnd.getCamera()), Accelerator('D')); + GlobalCommands_insert("CameraDown", ReferenceCaller(camwnd.getCamera()), Accelerator('C')); + GlobalCommands_insert("CameraAngleUp", ReferenceCaller(camwnd.getCamera()), Accelerator('A')); + GlobalCommands_insert("CameraAngleDown", ReferenceCaller(camwnd.getCamera()), Accelerator('Z')); +} + +void CamWnd_Move_Enable(CamWnd& camwnd) +{ + KeyEvent_connect("CameraForward"); + KeyEvent_connect("CameraBack"); + KeyEvent_connect("CameraLeft"); + KeyEvent_connect("CameraRight"); + KeyEvent_connect("CameraStrafeRight"); + KeyEvent_connect("CameraStrafeLeft"); + KeyEvent_connect("CameraUp"); + KeyEvent_connect("CameraDown"); + KeyEvent_connect("CameraAngleUp"); + KeyEvent_connect("CameraAngleDown"); +} + +void CamWnd_Move_Disable(CamWnd& camwnd) +{ + KeyEvent_disconnect("CameraForward"); + KeyEvent_disconnect("CameraBack"); + KeyEvent_disconnect("CameraLeft"); + KeyEvent_disconnect("CameraRight"); + KeyEvent_disconnect("CameraStrafeRight"); + KeyEvent_disconnect("CameraStrafeLeft"); + KeyEvent_disconnect("CameraUp"); + KeyEvent_disconnect("CameraDown"); + KeyEvent_disconnect("CameraAngleUp"); + KeyEvent_disconnect("CameraAngleDown"); +} + +void CamWnd_Move_Discrete_Enable(CamWnd& camwnd) +{ + command_connect_accelerator("CameraForward"); + command_connect_accelerator("CameraBack"); + command_connect_accelerator("CameraLeft"); + command_connect_accelerator("CameraRight"); + command_connect_accelerator("CameraStrafeRight"); + command_connect_accelerator("CameraStrafeLeft"); + command_connect_accelerator("CameraUp"); + command_connect_accelerator("CameraDown"); + command_connect_accelerator("CameraAngleUp"); + command_connect_accelerator("CameraAngleDown"); +} + +void CamWnd_Move_Discrete_Disable(CamWnd& camwnd) +{ + command_disconnect_accelerator("CameraForward"); + command_disconnect_accelerator("CameraBack"); + command_disconnect_accelerator("CameraLeft"); + command_disconnect_accelerator("CameraRight"); + command_disconnect_accelerator("CameraStrafeRight"); + command_disconnect_accelerator("CameraStrafeLeft"); + command_disconnect_accelerator("CameraUp"); + command_disconnect_accelerator("CameraDown"); + command_disconnect_accelerator("CameraAngleUp"); + command_disconnect_accelerator("CameraAngleDown"); +} + +void CamWnd_Move_Discrete_Import(CamWnd& camwnd, bool value) +{ + if(g_camwindow_globals_private.m_bCamDiscrete) + { + CamWnd_Move_Discrete_Disable(camwnd); + } + else + { + CamWnd_Move_Disable(camwnd); + } + + g_camwindow_globals_private.m_bCamDiscrete = value; + + if(g_camwindow_globals_private.m_bCamDiscrete) + { + CamWnd_Move_Discrete_Enable(camwnd); + } + else + { + CamWnd_Move_Enable(camwnd); + } +} + +void CamWnd_Move_Discrete_Import(bool value) +{ + if(g_camwnd != 0) + { + CamWnd_Move_Discrete_Import(*g_camwnd, value); + } + else + { + g_camwindow_globals_private.m_bCamDiscrete = value; + } +} + + + +void CamWnd_Add_Handlers_Move(CamWnd& camwnd) +{ + camwnd.m_selection_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(selection_button_press), camwnd.m_window_observer); + camwnd.m_selection_button_release_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_release_event", G_CALLBACK(selection_button_release), camwnd.m_window_observer); + camwnd.m_selection_motion_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "motion_notify_event", G_CALLBACK(DeferredMotion::gtk_motion), &camwnd.m_deferred_motion); + + camwnd.m_freelook_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(enable_freelook_button_press), &camwnd); + + if(g_camwindow_globals_private.m_bCamDiscrete) + { + CamWnd_Move_Discrete_Enable(camwnd); + } + else + { + CamWnd_Move_Enable(camwnd); + } +} + +void CamWnd_Remove_Handlers_Move(CamWnd& camwnd) +{ + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_press_handler); + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_release_handler); + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_motion_handler); + + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_freelook_button_press_handler); + + if(g_camwindow_globals_private.m_bCamDiscrete) + { + CamWnd_Move_Discrete_Disable(camwnd); + } + else + { + CamWnd_Move_Disable(camwnd); + } +} + +void CamWnd_Add_Handlers_FreeMove(CamWnd& camwnd) +{ + camwnd.m_selection_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(selection_button_press_freemove), camwnd.m_window_observer); + camwnd.m_selection_button_release_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_release_event", G_CALLBACK(selection_button_release_freemove), camwnd.m_window_observer); + camwnd.m_selection_motion_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "motion_notify_event", G_CALLBACK(selection_motion_freemove), camwnd.m_window_observer); + + camwnd.m_freelook_button_press_handler = g_signal_connect(G_OBJECT(camwnd.m_gl_widget), "button_press_event", G_CALLBACK(disable_freelook_button_press), &camwnd); + + KeyEvent_connect("CameraFreeMoveForward"); + KeyEvent_connect("CameraFreeMoveBack"); + KeyEvent_connect("CameraFreeMoveLeft"); + KeyEvent_connect("CameraFreeMoveRight"); + KeyEvent_connect("CameraFreeMoveUp"); + KeyEvent_connect("CameraFreeMoveDown"); +} + +void CamWnd_Remove_Handlers_FreeMove(CamWnd& camwnd) +{ + KeyEvent_disconnect("CameraFreeMoveForward"); + KeyEvent_disconnect("CameraFreeMoveBack"); + KeyEvent_disconnect("CameraFreeMoveLeft"); + KeyEvent_disconnect("CameraFreeMoveRight"); + KeyEvent_disconnect("CameraFreeMoveUp"); + KeyEvent_disconnect("CameraFreeMoveDown"); + + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_press_handler); + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_button_release_handler); + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_selection_motion_handler); + + g_signal_handler_disconnect(G_OBJECT(camwnd.m_gl_widget), camwnd.m_freelook_button_press_handler); +} + +CamWnd::CamWnd() : + m_view(true), + m_Camera(&m_view, CamWndQueueDraw(*this)), + m_cameraview(m_Camera, &m_view, ReferenceCaller(*this)), + m_gl_widget(glwidget_new(TRUE)), + m_window_observer(NewWindowObserver()), + m_XORRectangle(m_gl_widget), + m_deferredDraw(WidgetQueueDrawCaller(*m_gl_widget)), + m_deferred_motion(selection_motion, m_window_observer), + m_selection_button_press_handler(0), + m_selection_button_release_handler(0), + m_selection_motion_handler(0), + m_freelook_button_press_handler(0), + m_drawing(false) +{ + m_bFreeMove = false; + + GlobalWindowObservers_add(m_window_observer); + GlobalWindowObservers_connectWidget(m_gl_widget); + + m_window_observer->setRectangleDrawCallback(ReferenceCaller1(*this)); + m_window_observer->setView(m_view); + + gtk_widget_ref(m_gl_widget); + + gtk_widget_set_events(m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK); + GTK_WIDGET_SET_FLAGS (m_gl_widget, GTK_CAN_FOCUS); + + m_sizeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "size_allocate", G_CALLBACK(camera_size_allocate), this); + m_exposeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "expose_event", G_CALLBACK(camera_expose), this); + + Map_addValidCallback(g_map, DeferredDrawOnMapValidChangedCaller(m_deferredDraw)); + + CamWnd_registerCommands(*this); + + CamWnd_Add_Handlers_Move(*this); + + g_signal_connect(G_OBJECT(m_gl_widget), "scroll_event", G_CALLBACK(wheelmove_scroll), this); + + AddSceneChangeCallback(ReferenceCaller(*this)); + + PressedButtons_connect(g_pressedButtons, m_gl_widget); +} + +CamWnd::~CamWnd() +{ + if(m_bFreeMove) + { + DisableFreeMove(); + } + + CamWnd_Remove_Handlers_Move(*this); + + g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_sizeHandler); + g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_exposeHandler); + + gtk_widget_unref(m_gl_widget); + + m_window_observer->release(); +} + +class FloorHeightWalker : public scene::Graph::Walker +{ + float m_current; + float& m_bestUp; + float& m_bestDown; +public: + FloorHeightWalker(float current, float& bestUp, float& bestDown) : + m_current(current), m_bestUp(bestUp), m_bestDown(bestDown) + { + bestUp = g_MaxWorldCoord; + bestDown = -g_MaxWorldCoord; + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible() + && Node_isBrush(path.top())) // this node is a floor + { + const AABB& aabb = instance.worldAABB(); + float floorHeight = aabb.origin.z() + aabb.extents.z(); + if(floorHeight > m_current && floorHeight < m_bestUp) + { + m_bestUp = floorHeight; + } + if(floorHeight < m_current && floorHeight > m_bestDown) + { + m_bestDown = floorHeight; + } + } + return true; + } +}; + +void CamWnd::Cam_ChangeFloor(bool up) +{ + float current = m_Camera.origin[2] - 48; + float bestUp; + float bestDown; + GlobalSceneGraph().traverse(FloorHeightWalker(current, bestUp, bestDown)); + + if(up && bestUp != g_MaxWorldCoord) + { + current = bestUp; + } + if(!up && bestDown != -g_MaxWorldCoord) + { + current = bestDown; + } + + m_Camera.origin[2] = current + 48; + Camera_updateModelview(getCamera()); + CamWnd_Update(*this); + CameraMovedNotify(); +} + + +#if 0 + +// button_press + Sys_GetCursorPos(&m_PositionDragCursorX, &m_PositionDragCursorY); + +// motion + if ( (m_bFreeMove && (buttons == (RAD_CONTROL|RAD_SHIFT))) + || (!m_bFreeMove && (buttons == (RAD_RBUTTON|RAD_CONTROL))) ) + { + Cam_PositionDrag(); + CamWnd_Update(camwnd); + CameraMovedNotify(); + return; + } + +void CamWnd::Cam_PositionDrag() +{ + int x, y; + + Sys_GetCursorPos(GTK_WINDOW(m_gl_widget), &x, &y); + if (x != m_PositionDragCursorX || y != m_PositionDragCursorY) + { + x -= m_PositionDragCursorX; + vector3_add(m_Camera.origin, vector3_scaled(m_Camera.vright, x)); + y -= m_PositionDragCursorY; + m_Camera.origin[2] -= y; + Camera_updateModelview(); + CamWnd_Update(camwnd); + CameraMovedNotify(); + + Sys_SetCursorPos(GTK_WINDOW(m_parent), m_PositionDragCursorX, m_PositionDragCursorY); + } +} +#endif + + +// NOTE TTimo if there's an OS-level focus out of the application +// then we can release the camera cursor grab +static gboolean camwindow_freemove_focusout(GtkWidget* widget, GdkEventFocus* event, gpointer data) +{ + reinterpret_cast(data)->DisableFreeMove(); + return FALSE; +} + +void CamWnd::EnableFreeMove() +{ + //globalOutputStream() << "EnableFreeMove\n"; + + ASSERT_MESSAGE(!m_bFreeMove, "EnableFreeMove: free-move was already enabled"); + m_bFreeMove = true; + Camera_clearMovementFlags(getCamera(), MOVE_ALL); + + CamWnd_Remove_Handlers_Move(*this); + CamWnd_Add_Handlers_FreeMove(*this); + + gtk_window_set_focus(m_parent, m_gl_widget); + m_freemove_handle_focusout = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(camwindow_freemove_focusout), this); + m_freezePointer.freeze_pointer(m_parent, Camera_motionDelta, &m_Camera); + + CamWnd_Update(*this); +} + +void CamWnd::DisableFreeMove() +{ + //globalOutputStream() << "DisableFreeMove\n"; + + ASSERT_MESSAGE(m_bFreeMove, "DisableFreeMove: free-move was not enabled"); + m_bFreeMove = false; + Camera_clearMovementFlags(getCamera(), MOVE_ALL); + + CamWnd_Remove_Handlers_FreeMove(*this); + CamWnd_Add_Handlers_Move(*this); + + m_freezePointer.unfreeze_pointer(m_parent); + g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_freemove_handle_focusout); + + CamWnd_Update(*this); +} + + +#include "renderer.h" + +class CamRenderer: public Renderer +{ + struct state_type + { + state_type() : m_highlight(0), m_state(0), m_lights(0) + { + } + unsigned int m_highlight; + Shader* m_state; + const LightList* m_lights; + }; + + std::vector m_state_stack; + RenderStateFlags m_globalstate; + Shader* m_state_select0; + Shader* m_state_select1; + const Vector3& m_viewer; + +public: + CamRenderer(RenderStateFlags globalstate, Shader* select0, Shader* select1, const Vector3& viewer) : + m_globalstate(globalstate), + m_state_select0(select0), + m_state_select1(select1), + m_viewer(viewer) + { + ASSERT_NOTNULL(select0); + ASSERT_NOTNULL(select1); + m_state_stack.push_back(state_type()); + } + + void SetState(Shader* state, EStyle style) + { + ASSERT_NOTNULL(state); + if(style == eFullMaterials) + { + m_state_stack.back().m_state = state; + } + } + const EStyle getStyle() const + { + return eFullMaterials; + } + void PushState() + { + m_state_stack.push_back(m_state_stack.back()); + } + void PopState() + { + ASSERT_MESSAGE(!m_state_stack.empty(), "popping empty stack"); + m_state_stack.pop_back(); + } + void Highlight(EHighlightMode mode, bool bEnable = true) + { + (bEnable) + ? m_state_stack.back().m_highlight |= mode + : m_state_stack.back().m_highlight &= ~mode; + } + void setLights(const LightList& lights) + { + m_state_stack.back().m_lights = &lights; + } + void addRenderable(const OpenGLRenderable& renderable, const Matrix4& world) + { + if(m_state_stack.back().m_highlight & ePrimitive) + { + m_state_select0->addRenderable(renderable, world, m_state_stack.back().m_lights); + } + if(m_state_stack.back().m_highlight & eFace) + { + m_state_select1->addRenderable(renderable, world, m_state_stack.back().m_lights); + } + + m_state_stack.back().m_state->addRenderable(renderable, world, m_state_stack.back().m_lights); + } + + void render(const Matrix4& modelview, const Matrix4& projection) + { + GlobalShaderCache().render(m_globalstate, modelview, projection, m_viewer); + } +}; + +/* +============== +Cam_Draw +============== +*/ + +void ShowStatsToggle() +{ + g_camwindow_globals_private.m_showStats ^= 1; +} +typedef FreeCaller ShowStatsToggleCaller; + +void ShowStatsExport(const BoolImportCallback& importer) +{ + importer(g_camwindow_globals_private.m_showStats); +} +typedef FreeCaller1 ShowStatsExportCaller; + +ShowStatsExportCaller g_show_stats_caller; +BoolExportCallback g_show_stats_callback(g_show_stats_caller); +ToggleItem g_show_stats(g_show_stats_callback); + +void CamWnd::Cam_Draw() +{ + glViewport(0, 0, m_Camera.width, m_Camera.height); +#if 0 + GLint viewprt[4]; + glGetIntegerv (GL_VIEWPORT, viewprt); +#endif + + // enable depth buffer writes + glDepthMask(GL_TRUE); + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + + Vector3 clearColour(0, 0, 0); + if(m_Camera.draw_mode != cd_lighting) + { + clearColour = g_camwindow_globals.color_cameraback; + } + + glClearColor(clearColour[0], clearColour[1], clearColour[2], 0); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + + extern void Renderer_ResetStats(); + Renderer_ResetStats(); + extern void Cull_ResetStats(); + Cull_ResetStats(); + + glMatrixMode(GL_PROJECTION); + glLoadMatrixf(reinterpret_cast(&m_Camera.projection)); + + glMatrixMode(GL_MODELVIEW); + glLoadMatrixf(reinterpret_cast(&m_Camera.modelview)); + + + // one directional light source directly behind the viewer + { + GLfloat inverse_cam_dir[4], ambient[4], diffuse[4];//, material[4]; + + ambient[0] = ambient[1] = ambient[2] = 0.4f; + ambient[3] = 1.0f; + diffuse[0] = diffuse[1] = diffuse[2] = 0.4f; + diffuse[3] = 1.0f; + //material[0] = material[1] = material[2] = 0.8f; + //material[3] = 1.0f; + + inverse_cam_dir[0] = m_Camera.vpn[0]; + inverse_cam_dir[1] = m_Camera.vpn[1]; + inverse_cam_dir[2] = m_Camera.vpn[2]; + inverse_cam_dir[3] = 0; + + glLightfv(GL_LIGHT0, GL_POSITION, inverse_cam_dir); + + glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); + glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse); + + glEnable(GL_LIGHT0); + } + + + unsigned int globalstate = RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_ALPHATEST|RENDER_BLEND|RENDER_CULLFACE|RENDER_COLOURARRAY|RENDER_OFFSETLINE|RENDER_POLYGONSMOOTH|RENDER_LINESMOOTH|RENDER_FOG|RENDER_COLOURCHANGE; + switch (m_Camera.draw_mode) + { + case cd_wire: + break; + case cd_solid: + globalstate |= RENDER_FILL + | RENDER_LIGHTING + | RENDER_SMOOTH + | RENDER_SCALED; + break; + case cd_texture: + globalstate |= RENDER_FILL + | RENDER_LIGHTING + | RENDER_TEXTURE + | RENDER_SMOOTH + | RENDER_SCALED; + break; + case cd_lighting: + globalstate |= RENDER_FILL + | RENDER_LIGHTING + | RENDER_TEXTURE + | RENDER_SMOOTH + | RENDER_SCALED + | RENDER_BUMP + | RENDER_PROGRAM + | RENDER_SCREEN; + break; + default: + globalstate = 0; + break; + } + + if(!g_xywindow_globals.m_bNoStipple) + { + globalstate |= RENDER_LINESTIPPLE|RENDER_POLYGONSTIPPLE; + } + + { + CamRenderer renderer(globalstate, m_state_select2, m_state_select1, m_view.getViewer()); + + Scene_Render(renderer, m_view); + + renderer.render(m_Camera.modelview, m_Camera.projection); + } + + // prepare for 2d stuff + glColor4f(1, 1, 1, 1); + glDisable(GL_BLEND); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, (float)m_Camera.width, 0, (float)m_Camera.height, -100, 100); + glScalef(1, -1, 1); + glTranslatef(0, -(float)m_Camera.height, 0); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + if(GlobalOpenGL().GL_1_3()) + { + glClientActiveTexture(GL_TEXTURE0); + glActiveTexture(GL_TEXTURE0); + } + + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_NORMAL_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); + + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHTING); + glDisable(GL_COLOR_MATERIAL); + glDisable(GL_DEPTH_TEST); + glColor3f( 1.f, 1.f, 1.f ); + glLineWidth(1); + + // draw the crosshair + if (m_bFreeMove) + { + glBegin( GL_LINES ); + glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 6 ); + glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 2 ); + glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 6 ); + glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 2 ); + glVertex2f( (float)m_Camera.width / 2.f + 6, (float)m_Camera.height / 2.f ); + glVertex2f( (float)m_Camera.width / 2.f + 2, (float)m_Camera.height / 2.f ); + glVertex2f( (float)m_Camera.width / 2.f - 6, (float)m_Camera.height / 2.f ); + glVertex2f( (float)m_Camera.width / 2.f - 2, (float)m_Camera.height / 2.f ); + glEnd(); + } + + if(g_camwindow_globals_private.m_showStats) + { + glRasterPos3f(1.0f, static_cast(m_Camera.height) - GlobalOpenGL().m_font->getPixelDescent(), 0.0f); + extern const char* Renderer_GetStats(); + GlobalOpenGL().drawString(Renderer_GetStats()); + + glRasterPos3f(1.0f, static_cast(m_Camera.height) - GlobalOpenGL().m_font->getPixelDescent() - GlobalOpenGL().m_font->getPixelHeight(), 0.0f); + extern const char* Cull_GetStats(); + GlobalOpenGL().drawString(Cull_GetStats()); + } + + // bind back to the default texture so that we don't have problems + // elsewhere using/modifying texture maps between contexts + glBindTexture( GL_TEXTURE_2D, 0 ); +} + +void CamWnd::draw() +{ + m_drawing = true; + + //globalOutputStream() << "draw...\n"; + if (glwidget_make_current(m_gl_widget) != FALSE) + { + if(Map_Valid(g_map) && ScreenUpdates_Enabled()) + { + GlobalOpenGL_debugAssertNoErrors(); + Cam_Draw(); + GlobalOpenGL_debugAssertNoErrors(); + //qglFinish(); + + m_XORRectangle.set(rectangle_t()); + } + + glwidget_swap_buffers(m_gl_widget); + } + + m_drawing = false; +} + +void CamWnd::BenchMark() +{ + double dStart = Sys_DoubleTime(); + for (int i=0 ; i < 100 ; i++) + { + Vector3 angles; + angles[CAMERA_ROLL] = 0; + angles[CAMERA_PITCH] = 0; + angles[CAMERA_YAW] = static_cast(i * (360.0 / 100.0)); + Camera_setAngles(*this, angles); + } + double dEnd = Sys_DoubleTime(); + globalOutputStream() << FloatFormat(dEnd - dStart, 5, 2) << " seconds\n"; +} + + +void fill_view_camera_menu(GtkMenu* menu) +{ + create_check_menu_item_with_mnemonic(menu, "Camera View", "ToggleCamera"); +} + +void GlobalCamera_ResetAngles() +{ + CamWnd& camwnd = *g_camwnd; + Vector3 angles; + angles[CAMERA_ROLL] = angles[CAMERA_PITCH] = 0; + angles[CAMERA_YAW] = static_cast(22.5 * floor((Camera_getAngles(camwnd)[CAMERA_YAW]+11)/22.5)); + Camera_setAngles(camwnd, angles); +} + +void Camera_ChangeFloorUp() +{ + CamWnd& camwnd = *g_camwnd; + camwnd.Cam_ChangeFloor (true); +} + +void Camera_ChangeFloorDown() +{ + CamWnd& camwnd = *g_camwnd; + camwnd.Cam_ChangeFloor (false); +} + +void Camera_CubeIn() +{ + CamWnd& camwnd = *g_camwnd; + g_camwindow_globals.m_nCubicScale--; + if (g_camwindow_globals.m_nCubicScale < 1) + g_camwindow_globals.m_nCubicScale = 1; + Camera_updateProjection(camwnd.getCamera()); + CamWnd_Update(camwnd); + g_pParentWnd->SetGridStatus(); +} + +void Camera_CubeOut() +{ + CamWnd& camwnd = *g_camwnd; + g_camwindow_globals.m_nCubicScale++; + if (g_camwindow_globals.m_nCubicScale > 23) + g_camwindow_globals.m_nCubicScale = 23; + Camera_updateProjection(camwnd.getCamera()); + CamWnd_Update(camwnd); + g_pParentWnd->SetGridStatus(); +} + +bool Camera_GetFarClip() +{ + return g_camwindow_globals_private.m_bCubicClipping; +} + +BoolExportCaller g_getfarclip_caller(g_camwindow_globals_private.m_bCubicClipping); +ToggleItem g_getfarclip_item(g_getfarclip_caller); + +void Camera_SetFarClip(bool value) +{ + CamWnd& camwnd = *g_camwnd; + g_camwindow_globals_private.m_bCubicClipping = value; + g_getfarclip_item.update(); + Camera_updateProjection(camwnd.getCamera()); + CamWnd_Update(camwnd); +} + +void Camera_ToggleFarClip() +{ + Camera_SetFarClip(!Camera_GetFarClip()); +} + + +void CamWnd_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_toggle_button(toolbar, "Cubic clip the camera view (\\)", "view_cubicclipping.bmp", "ToggleCubicClip"); +} + +void CamWnd_registerShortcuts() +{ + toggle_add_accelerator("ToggleCubicClip"); + + if(g_pGameDescription->mGameType == "doom3") + { + command_connect_accelerator("TogglePreview"); + } + + command_connect_accelerator("CameraSpeedInc"); + command_connect_accelerator("CameraSpeedDec"); +} + + +void GlobalCamera_Benchmark() +{ + CamWnd& camwnd = *g_camwnd; + camwnd.BenchMark(); +} + +void GlobalCamera_Update() +{ + CamWnd& camwnd = *g_camwnd; + CamWnd_Update(camwnd); +} + +camera_draw_mode CamWnd_GetMode() +{ + return camera_t::draw_mode; +} +void CamWnd_SetMode(camera_draw_mode mode) +{ + ShaderCache_setBumpEnabled(mode == cd_lighting); + camera_t::draw_mode = mode; + if(g_camwnd != 0) + { + CamWnd_Update(*g_camwnd); + } +} + +void CamWnd_TogglePreview(void) +{ + // gametype must be doom3 for this function to work + // if the gametype is not doom3 something is wrong with the + // global command list or somebody else calls this function. + ASSERT_MESSAGE(g_pGameDescription->mGameType == "doom3", "CamWnd_TogglePreview called although mGameType is not doom3 compatible"); + + // switch between textured and lighting mode + CamWnd_SetMode((CamWnd_GetMode() == cd_lighting) ? cd_texture : cd_lighting); +} + + +CameraModel* g_camera_model = 0; + +void CamWnd_LookThroughCamera(CamWnd& camwnd) +{ + if(g_camera_model != 0) + { + CamWnd_Add_Handlers_Move(camwnd); + g_camera_model->setCameraView(0, Callback()); + g_camera_model = 0; + Camera_updateModelview(camwnd.getCamera()); + Camera_updateProjection(camwnd.getCamera()); + CamWnd_Update(camwnd); + } +} + +inline CameraModel* Instance_getCameraModel(scene::Instance& instance) +{ + return InstanceTypeCast::cast(instance); +} + +void CamWnd_LookThroughSelected(CamWnd& camwnd) +{ + if(g_camera_model != 0) + { + CamWnd_LookThroughCamera(camwnd); + } + + if(GlobalSelectionSystem().countSelected() != 0) + { + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); + CameraModel* cameraModel = Instance_getCameraModel(instance); + if(cameraModel != 0) + { + CamWnd_Remove_Handlers_Move(camwnd); + g_camera_model = cameraModel; + g_camera_model->setCameraView(&camwnd.getCameraView(), ReferenceCaller(camwnd)); + } + } +} + +void GlobalCamera_LookThroughSelected() +{ + CamWnd_LookThroughSelected(*g_camwnd); +} + +void GlobalCamera_LookThroughCamera() +{ + CamWnd_LookThroughCamera(*g_camwnd); +} + + +void RenderModeImport(int value) +{ + switch(value) + { + case 0: + CamWnd_SetMode(cd_wire); + break; + case 1: + CamWnd_SetMode(cd_solid); + break; + case 2: + CamWnd_SetMode(cd_texture); + break; + case 3: + CamWnd_SetMode(cd_lighting); + break; + default: + CamWnd_SetMode(cd_texture); + } +} +typedef FreeCaller1 RenderModeImportCaller; + +void RenderModeExport(const IntImportCallback& importer) +{ + switch(CamWnd_GetMode()) + { + case cd_wire: + importer(0); + break; + case cd_solid: + importer(1); + break; + case cd_texture: + importer(2); + break; + case cd_lighting: + importer(3); + break; + } +} +typedef FreeCaller1 RenderModeExportCaller; + +void Camera_constructPreferences(PreferencesPage& page) +{ + page.appendSlider("Movement Speed", g_camwindow_globals_private.m_nMoveSpeed, TRUE, 0, 0, 100, MIN_CAM_SPEED, MAX_CAM_SPEED, 1, 10); + page.appendCheckBox("", "Link strafe speed to movement speed", g_camwindow_globals_private.m_bCamLinkSpeed); + page.appendSlider("Rotation Speed", g_camwindow_globals_private.m_nAngleSpeed, TRUE, 0, 0, 3, 1, 180, 1, 10); + page.appendCheckBox("", "Invert mouse vertical axis", g_camwindow_globals_private.m_bCamInverseMouse); + page.appendCheckBox( + "", "Discrete movement", + FreeCaller1(), + BoolExportCaller(g_camwindow_globals_private.m_bCamDiscrete) + ); + page.appendCheckBox( + "", "Enable far-clip plane", + FreeCaller1(), + BoolExportCaller(g_camwindow_globals_private.m_bCubicClipping) + ); + + if(g_pGameDescription->mGameType == "doom3") + { + const char* render_mode[] = { "Wireframe", "Flatshade", "Textured", "Lighting" }; + + page.appendCombo( + "Render Mode", + STRING_ARRAY_RANGE(render_mode), + IntImportCallback(RenderModeImportCaller()), + IntExportCallback(RenderModeExportCaller()) + ); + } + else + { + const char* render_mode[] = { "Wireframe", "Flatshade", "Textured" }; + + page.appendCombo( + "Render Mode", + STRING_ARRAY_RANGE(render_mode), + IntImportCallback(RenderModeImportCaller()), + IntExportCallback(RenderModeExportCaller()) + ); + } + + const char* strafe_mode[] = { "Both", "Forward", "Up" }; + + page.appendCombo( + "Strafe Mode", + g_camwindow_globals_private.m_nStrafeMode, + STRING_ARRAY_RANGE(strafe_mode) + ); +} +void Camera_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Camera", "Camera View Preferences")); + Camera_constructPreferences(page); +} +void Camera_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + +#include "preferencesystem.h" +#include "stringio.h" +#include "dialog.h" + +typedef FreeCaller1 CamWndMoveDiscreteImportCaller; + +void CameraSpeed_increase() +{ + if(g_camwindow_globals_private.m_nMoveSpeed <= (MAX_CAM_SPEED - CAM_SPEED_STEP - 10)) + { + g_camwindow_globals_private.m_nMoveSpeed += CAM_SPEED_STEP; + } else { + g_camwindow_globals_private.m_nMoveSpeed = MAX_CAM_SPEED - 10; + } +} + +void CameraSpeed_decrease() +{ + if(g_camwindow_globals_private.m_nMoveSpeed >= (MIN_CAM_SPEED + CAM_SPEED_STEP)) + { + g_camwindow_globals_private.m_nMoveSpeed -= CAM_SPEED_STEP; + } else { + g_camwindow_globals_private.m_nMoveSpeed = MIN_CAM_SPEED; + } +} + +/// \brief Initialisation for things that have the same lifespan as this module. +void CamWnd_Construct() +{ + GlobalCommands_insert("CenterView", FreeCaller(), Accelerator(GDK_End)); + + GlobalToggles_insert("ToggleCubicClip", FreeCaller(), ToggleItem::AddCallbackCaller(g_getfarclip_item), Accelerator('\\', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("CubicClipZoomIn", FreeCaller(), Accelerator('[', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("CubicClipZoomOut", FreeCaller(), Accelerator(']', (GdkModifierType)GDK_CONTROL_MASK)); + + GlobalCommands_insert("UpFloor", FreeCaller(), Accelerator(GDK_Prior)); + GlobalCommands_insert("DownFloor", FreeCaller(), Accelerator(GDK_Next)); + + GlobalToggles_insert("ToggleCamera", ToggleShown::ToggleCaller(g_camera_shown), ToggleItem::AddCallbackCaller(g_camera_shown.m_item), Accelerator('C', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("LookThroughSelected", FreeCaller()); + GlobalCommands_insert("LookThroughCamera", FreeCaller()); + + if(g_pGameDescription->mGameType == "doom3") + { + GlobalCommands_insert("TogglePreview", FreeCaller(), Accelerator(GDK_F3)); + } + + GlobalCommands_insert("CameraSpeedInc", FreeCaller(), Accelerator(GDK_KP_Add, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("CameraSpeedDec", FreeCaller(), Accelerator(GDK_KP_Subtract, (GdkModifierType)GDK_SHIFT_MASK)); + + GlobalShortcuts_insert("CameraForward", Accelerator(GDK_Up)); + GlobalShortcuts_insert("CameraBack", Accelerator(GDK_Down)); + GlobalShortcuts_insert("CameraLeft", Accelerator(GDK_Left)); + GlobalShortcuts_insert("CameraRight", Accelerator(GDK_Right)); + GlobalShortcuts_insert("CameraStrafeRight", Accelerator(GDK_period)); + GlobalShortcuts_insert("CameraStrafeLeft", Accelerator(GDK_comma)); + + GlobalShortcuts_insert("CameraUp", Accelerator('D')); + GlobalShortcuts_insert("CameraDown", Accelerator('C')); + GlobalShortcuts_insert("CameraAngleUp", Accelerator('A')); + GlobalShortcuts_insert("CameraAngleDown", Accelerator('Z')); + + GlobalShortcuts_insert("CameraFreeMoveForward", Accelerator(GDK_Up)); + GlobalShortcuts_insert("CameraFreeMoveBack", Accelerator(GDK_Down)); + GlobalShortcuts_insert("CameraFreeMoveLeft", Accelerator(GDK_Left)); + GlobalShortcuts_insert("CameraFreeMoveRight", Accelerator(GDK_Right)); + + GlobalToggles_insert("ShowStats", ShowStatsToggleCaller(), ToggleItem::AddCallbackCaller(g_show_stats)); + + GlobalPreferenceSystem().registerPreference("ShowStats", BoolImportStringCaller(g_camwindow_globals_private.m_showStats), BoolExportStringCaller(g_camwindow_globals_private.m_showStats)); + GlobalPreferenceSystem().registerPreference("MoveSpeed", IntImportStringCaller(g_camwindow_globals_private.m_nMoveSpeed), IntExportStringCaller(g_camwindow_globals_private.m_nMoveSpeed)); + GlobalPreferenceSystem().registerPreference("CamLinkSpeed", BoolImportStringCaller(g_camwindow_globals_private.m_bCamLinkSpeed), BoolExportStringCaller(g_camwindow_globals_private.m_bCamLinkSpeed)); + GlobalPreferenceSystem().registerPreference("AngleSpeed", IntImportStringCaller(g_camwindow_globals_private.m_nAngleSpeed), IntExportStringCaller(g_camwindow_globals_private.m_nAngleSpeed)); + GlobalPreferenceSystem().registerPreference("CamInverseMouse", BoolImportStringCaller(g_camwindow_globals_private.m_bCamInverseMouse), BoolExportStringCaller(g_camwindow_globals_private.m_bCamInverseMouse)); + GlobalPreferenceSystem().registerPreference("CamDiscrete", makeBoolStringImportCallback(CamWndMoveDiscreteImportCaller()), BoolExportStringCaller(g_camwindow_globals_private.m_bCamDiscrete)); + GlobalPreferenceSystem().registerPreference("CubicClipping", BoolImportStringCaller(g_camwindow_globals_private.m_bCubicClipping), BoolExportStringCaller(g_camwindow_globals_private.m_bCubicClipping)); + GlobalPreferenceSystem().registerPreference("CubicScale", IntImportStringCaller(g_camwindow_globals.m_nCubicScale), IntExportStringCaller(g_camwindow_globals.m_nCubicScale)); + GlobalPreferenceSystem().registerPreference("SI_Colors4", Vector3ImportStringCaller(g_camwindow_globals.color_cameraback), Vector3ExportStringCaller(g_camwindow_globals.color_cameraback)); + GlobalPreferenceSystem().registerPreference("SI_Colors12", Vector3ImportStringCaller(g_camwindow_globals.color_selbrushes3d), Vector3ExportStringCaller(g_camwindow_globals.color_selbrushes3d)); + GlobalPreferenceSystem().registerPreference("CameraRenderMode", makeIntStringImportCallback(RenderModeImportCaller()), makeIntStringExportCallback(RenderModeExportCaller())); + GlobalPreferenceSystem().registerPreference("StrafeMode", IntImportStringCaller(g_camwindow_globals_private.m_nStrafeMode), IntExportStringCaller(g_camwindow_globals_private.m_nStrafeMode)); + + CamWnd_constructStatic(); + + Camera_registerPreferencesPage(); +} +void CamWnd_Destroy() +{ + CamWnd_destroyStatic(); +} diff --git a/misc/mediasource/netradiant-src/radiant/camwindow.h b/misc/mediasource/netradiant-src/radiant/camwindow.h new file mode 100644 index 00000000..2c8c59f7 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/camwindow.h @@ -0,0 +1,87 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_CAMWINDOW_H) +#define INCLUDED_CAMWINDOW_H + +#include "math/vector.h" +#include "signal/signalfwd.h" + +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; + +class CamWnd; +CamWnd* NewCamWnd(); +void DeleteCamWnd(CamWnd* camwnd); + +void AddCameraMovedCallback(const SignalHandler& handler); + +void CamWnd_Update(CamWnd& camwnd); + +GtkWidget* CamWnd_getWidget(CamWnd& camwnd); +void CamWnd_setParent(CamWnd& camwnd, GtkWindow* parent); + +void GlobalCamera_setCamWnd(CamWnd& camwnd); + +typedef struct _GtkMenu GtkMenu; +void fill_view_camera_menu(GtkMenu* menu); +typedef struct _GtkToolbar GtkToolbar; +void CamWnd_constructToolbar(GtkToolbar* toolbar); +void CamWnd_registerShortcuts(); + +void GlobalCamera_Benchmark(); + +const Vector3& Camera_getOrigin(CamWnd& camwnd); +void Camera_setOrigin(CamWnd& camwnd, const Vector3& origin); + +enum +{ + CAMERA_PITCH = 0, // up / down + CAMERA_YAW = 1, // left / right + CAMERA_ROLL = 2, // fall over +}; + +const Vector3& Camera_getAngles(CamWnd& camwnd); +void Camera_setAngles(CamWnd& camwnd, const Vector3& angles); + + +struct camwindow_globals_t +{ + Vector3 color_cameraback; + Vector3 color_selbrushes3d; + + int m_nCubicScale; + + camwindow_globals_t() : + color_cameraback(0.25f, 0.25f, 0.25f), + color_selbrushes3d(1.0f, 0.f, 0.f), + m_nCubicScale(13) + { + } + +}; + +extern camwindow_globals_t g_camwindow_globals; + +void CamWnd_Construct(); +void CamWnd_Destroy(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/clippertool.cpp b/misc/mediasource/netradiant-src/radiant/clippertool.cpp new file mode 100644 index 00000000..a49b7246 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/clippertool.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "clippertool.h" + diff --git a/misc/mediasource/netradiant-src/radiant/clippertool.h b/misc/mediasource/netradiant-src/radiant/clippertool.h new file mode 100644 index 00000000..6101f1a6 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/clippertool.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_CLIPPERTOOL_H) +#define INCLUDED_CLIPPERTOOL_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/commands.cpp b/misc/mediasource/netradiant-src/radiant/commands.cpp new file mode 100644 index 00000000..31720686 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/commands.cpp @@ -0,0 +1,644 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "commands.h" + +#include "debugging/debugging.h" +#include "warnings.h" + +#include +#include "string/string.h" +#include "versionlib.h" +#include "gtkutil/accelerator.h" +#include "gtkutil/messagebox.h" +#include +#include +#include "gtkmisc.h" + +typedef std::pair ShortcutValue; // accelerator, isRegistered +typedef std::map Shortcuts; + +void Shortcuts_foreach(Shortcuts& shortcuts, CommandVisitor& visitor) +{ + for(Shortcuts::iterator i = shortcuts.begin(); i != shortcuts.end(); ++i) + { + visitor.visit((*i).first.c_str(), (*i).second.first); + } +} + +Shortcuts g_shortcuts; + +const Accelerator& GlobalShortcuts_insert(const char* name, const Accelerator& accelerator) +{ + return (*g_shortcuts.insert(Shortcuts::value_type(name, ShortcutValue(accelerator, false))).first).second.first; +} + +void GlobalShortcuts_foreach(CommandVisitor& visitor) +{ + Shortcuts_foreach(g_shortcuts, visitor); +} + +void GlobalShortcuts_register(const char* name, int type) +{ + Shortcuts::iterator i = g_shortcuts.find(name); + if(i != g_shortcuts.end()) + { + (*i).second.second = type; + } +} + +void GlobalShortcuts_reportUnregistered() +{ + for(Shortcuts::iterator i = g_shortcuts.begin(); i != g_shortcuts.end(); ++i) + { + if((*i).second.first.key != 0 && !(*i).second.second) + { + globalOutputStream() << "shortcut not registered: " << (*i).first.c_str() << "\n"; + } + } +} + +typedef std::map Commands; + +Commands g_commands; + +void GlobalCommands_insert(const char* name, const Callback& callback, const Accelerator& accelerator) +{ + bool added = g_commands.insert(Commands::value_type(name, Command(callback, GlobalShortcuts_insert(name, accelerator)))).second; + ASSERT_MESSAGE(added, "command already registered: " << makeQuoted(name)); +} + +const Command& GlobalCommands_find(const char* command) +{ + Commands::iterator i = g_commands.find(command); + ASSERT_MESSAGE(i != g_commands.end(), "failed to lookup command " << makeQuoted(command)); + return (*i).second; +} + +typedef std::map Toggles; + + +Toggles g_toggles; + +void GlobalToggles_insert(const char* name, const Callback& callback, const BoolExportCallback& exportCallback, const Accelerator& accelerator) +{ + bool added = g_toggles.insert(Toggles::value_type(name, Toggle(callback, GlobalShortcuts_insert(name, accelerator), exportCallback))).second; + ASSERT_MESSAGE(added, "toggle already registered: " << makeQuoted(name)); +} +const Toggle& GlobalToggles_find(const char* name) +{ + Toggles::iterator i = g_toggles.find(name); + ASSERT_MESSAGE(i != g_toggles.end(), "failed to lookup toggle " << makeQuoted(name)); + return (*i).second; +} + +typedef std::map KeyEvents; + + +KeyEvents g_keyEvents; + +void GlobalKeyEvents_insert(const char* name, const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp) +{ + bool added = g_keyEvents.insert(KeyEvents::value_type(name, KeyEvent(GlobalShortcuts_insert(name, accelerator), keyDown, keyUp))).second; + ASSERT_MESSAGE(added, "command already registered: " << makeQuoted(name)); +} +const KeyEvent& GlobalKeyEvents_find(const char* name) +{ + KeyEvents::iterator i = g_keyEvents.find(name); + ASSERT_MESSAGE(i != g_keyEvents.end(), "failed to lookup keyEvent " << makeQuoted(name)); + return (*i).second; +} + + +void disconnect_accelerator(const char *name) +{ + Shortcuts::iterator i = g_shortcuts.find(name); + if(i != g_shortcuts.end()) + { + switch((*i).second.second) + { + case 1: + // command + command_disconnect_accelerator(name); + break; + case 2: + // toggle + toggle_remove_accelerator(name); + break; + } + } +} + +void connect_accelerator(const char *name) +{ + Shortcuts::iterator i = g_shortcuts.find(name); + if(i != g_shortcuts.end()) + { + switch((*i).second.second) + { + case 1: + // command + command_connect_accelerator(name); + break; + case 2: + // toggle + toggle_add_accelerator(name); + break; + } + } +} + + +#include + +#include +#include +#include +#include +#include + +#include "gtkutil/dialog.h" +#include "mainframe.h" + +#include "stream/textfilestream.h" +#include "stream/stringstream.h" + + +struct command_list_dialog_t : public ModalDialog +{ + command_list_dialog_t() + : m_close_button(*this, eIDCANCEL), m_list(NULL), m_command_iter(), m_model(NULL), m_waiting_for_key(false) + { + } + ModalDialogButton m_close_button; + + GtkTreeView *m_list; + GtkTreeIter m_command_iter; + GtkTreeModel *m_model; + bool m_waiting_for_key; +}; + +void accelerator_clear_button_clicked(GtkButton *btn, gpointer dialogptr) +{ + command_list_dialog_t &dialog = * (command_list_dialog_t *) dialogptr; + + if(dialog.m_waiting_for_key) + { + // just unhighlight, user wanted to cancel + dialog.m_waiting_for_key = false; + gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 2, false, -1); + gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), true); + dialog.m_model = NULL; + return; + } + + GtkTreeSelection *sel = gtk_tree_view_get_selection(dialog.m_list); + GtkTreeModel *model; + GtkTreeIter iter; + if(!gtk_tree_selection_get_selected(sel, &model, &iter)) + return; + + GValue val; + memset(&val, 0, sizeof(val)); + gtk_tree_model_get_value(GTK_TREE_MODEL(model), &iter, 0, &val); + const char *commandName = g_value_get_string(&val);; + + // clear the ACTUAL accelerator too! + disconnect_accelerator(commandName); + + Shortcuts::iterator thisShortcutIterator = g_shortcuts.find(commandName); + if(thisShortcutIterator == g_shortcuts.end()) + return; + thisShortcutIterator->second.first = accelerator_null(); + + gtk_list_store_set(GTK_LIST_STORE(model), &iter, 1, "", -1); + + g_value_unset(&val); +} + +void accelerator_edit_button_clicked(GtkButton *btn, gpointer dialogptr) +{ + command_list_dialog_t &dialog = * (command_list_dialog_t *) dialogptr; + + // 1. find selected row + GtkTreeSelection *sel = gtk_tree_view_get_selection(dialog.m_list); + GtkTreeModel *model; + GtkTreeIter iter; + if(!gtk_tree_selection_get_selected(sel, &model, &iter)) + return; + dialog.m_command_iter = iter; + dialog.m_model = model; + + // 2. disallow changing the row + //gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), false); + + // 3. highlight the row + gtk_list_store_set(GTK_LIST_STORE(model), &iter, 2, true, -1); + + // 4. grab keyboard focus + dialog.m_waiting_for_key = true; +} + +gboolean accelerator_window_key_press(GtkWidget *widget, GdkEventKey *event, gpointer dialogptr) +{ + command_list_dialog_t &dialog = * (command_list_dialog_t *) dialogptr; + + if(!dialog.m_waiting_for_key) + return false; + +#if 0 + if(event->is_modifier) + return false; +#else + switch(event->keyval) + { + case GDK_Shift_L: + case GDK_Shift_R: + case GDK_Control_L: + case GDK_Control_R: + case GDK_Caps_Lock: + case GDK_Shift_Lock: + case GDK_Meta_L: + case GDK_Meta_R: + case GDK_Alt_L: + case GDK_Alt_R: + case GDK_Super_L: + case GDK_Super_R: + case GDK_Hyper_L: + case GDK_Hyper_R: + return false; + } +#endif + + dialog.m_waiting_for_key = false; + + // 7. find the name of the accelerator + GValue val; + memset(&val, 0, sizeof(val)); + gtk_tree_model_get_value(GTK_TREE_MODEL(dialog.m_model), &dialog.m_command_iter, 0, &val); + const char *commandName = g_value_get_string(&val);; + Shortcuts::iterator thisShortcutIterator = g_shortcuts.find(commandName); + if(thisShortcutIterator == g_shortcuts.end()) + { + gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 2, false, -1); + gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), true); + return true; + } + + // 8. build an Accelerator + Accelerator newAccel(event->keyval, (GdkModifierType) event->state); + + // 8. verify the key is still free, show a dialog to ask what to do if not + class VerifyAcceleratorNotTaken : public CommandVisitor + { + const char *commandName; + const Accelerator &newAccel; + GtkWidget *widget; + GtkTreeModel *model; + public: + bool allow; + VerifyAcceleratorNotTaken(const char *name, const Accelerator &accelerator, GtkWidget *w, GtkTreeModel *m) : commandName(name), newAccel(accelerator), widget(w), model(m), allow(true) + { + } + void visit(const char* name, Accelerator& accelerator) + { + if(!strcmp(name, commandName)) + return; + if(!allow) + return; + if(accelerator.key == 0) + return; + if(accelerator == newAccel) + { + StringOutputStream msg; + msg << "The command " << name << " is already assigned to the key " << accelerator << ".\n\n" + << "Do you want to unassign " << name << " first?"; + EMessageBoxReturn r = gtk_MessageBox (widget, msg.c_str(), "Key already used", eMB_YESNOCANCEL); + if(r == eIDYES) + { + // clear the ACTUAL accelerator too! + disconnect_accelerator(name); + // delete the modifier + accelerator = accelerator_null(); + // empty the cell of the key binds dialog + GtkTreeIter i; + if(gtk_tree_model_get_iter_first(GTK_TREE_MODEL(model), &i)) + { + for(;;) + { + GValue val; + memset(&val, 0, sizeof(val)); + gtk_tree_model_get_value(GTK_TREE_MODEL(model), &i, 0, &val); + const char *thisName = g_value_get_string(&val);; + if(!strcmp(thisName, name)) + gtk_list_store_set(GTK_LIST_STORE(model), &i, 1, "", -1); + g_value_unset(&val); + if(!gtk_tree_model_iter_next(GTK_TREE_MODEL(model), &i)) + break; + } + } + } + else if(r == eIDCANCEL) + { + // aborted + allow = false; + } + } + } + } verify_visitor(commandName, newAccel, widget, dialog.m_model); + GlobalShortcuts_foreach(verify_visitor); + + gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 2, false, -1); + gtk_widget_set_sensitive(GTK_WIDGET(dialog.m_list), true); + + if(verify_visitor.allow) + { + // clear the ACTUAL accelerator first + disconnect_accelerator(commandName); + + thisShortcutIterator->second.first = newAccel; + + // write into the cell + StringOutputStream modifiers; + modifiers << newAccel; + gtk_list_store_set(GTK_LIST_STORE(dialog.m_model), &dialog.m_command_iter, 1, modifiers.c_str(), -1); + + // set the ACTUAL accelerator too! + connect_accelerator(commandName); + } + + g_value_unset(&val); + + dialog.m_model = NULL; + + return true; +} + +/* + GtkTreeIter row; + GValue val; + if(!model) {g_error("Unable to get model from cell renderer");} + gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(model), &row, path_string); + + gtk_tree_model_get_value(GTK_TREE_MODEL(model), &row, 0, &val); + const char *name = g_value_get_string(&val); + Shortcuts::iterator i = g_shortcuts.find(name); + if(i != g_shortcuts.end()) + { + accelerator_parse(i->second.first, new_text); + StringOutputStream modifiers; + modifiers << i->second.first; + gtk_list_store_set(GTK_LIST_STORE(model), &row, 1, modifiers.c_str(), -1); + } +}; +*/ + +void DoCommandListDlg() +{ + command_list_dialog_t dialog; + + GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Mapped Commands", dialog, -1, 400); + g_signal_connect(G_OBJECT(window), "key-press-event", (GCallback) accelerator_window_key_press, &dialog); + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel); + + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + + { + GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(scr), TRUE, TRUE, 0); + + { + GtkListStore* store = gtk_list_store_new(4, G_TYPE_STRING, G_TYPE_STRING, G_TYPE_BOOLEAN, G_TYPE_INT); + + GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + dialog.m_list = GTK_TREE_VIEW(view); + + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), false); // annoying + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Command", renderer, "text", 0, "weight-set", 2, "weight", 3, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + } + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Key", renderer, "text", 1, "weight-set", 2, "weight", 3, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + } + + gtk_widget_show(view); + gtk_container_add(GTK_CONTAINER (scr), view); + + { + // Initialize dialog + StringOutputStream path(256); + path << SettingsPath_get() << "commandlist.txt"; + globalOutputStream() << "Writing the command list to " << path.c_str() << "\n"; + class BuildCommandList : public CommandVisitor + { + TextFileOutputStream m_commandList; + GtkListStore* m_store; + public: + BuildCommandList(const char* filename, GtkListStore* store) : m_commandList(filename), m_store(store) + { + } + void visit(const char* name, Accelerator& accelerator) + { + StringOutputStream modifiers; + modifiers << accelerator; + + { + GtkTreeIter iter; + gtk_list_store_append(m_store, &iter); + gtk_list_store_set(m_store, &iter, 0, name, 1, modifiers.c_str(), 2, false, 3, 800, -1); + } + + if(!m_commandList.failed()) + { + int l = strlen(name); + m_commandList << name; + while(l++ < 25) + m_commandList << ' '; + m_commandList << modifiers.c_str() << '\n'; + } + } + } visitor(path.c_str(), store); + + GlobalShortcuts_foreach(visitor); + } + + g_object_unref(G_OBJECT(store)); + } + } + + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + GtkButton* editbutton = create_dialog_button("Edit", (GCallback) accelerator_edit_button_clicked, &dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(editbutton), FALSE, FALSE, 0); + + GtkButton* clearbutton = create_dialog_button("Clear", (GCallback) accelerator_clear_button_clicked, &dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(clearbutton), FALSE, FALSE, 0); + + GtkWidget *spacer = gtk_image_new(); + gtk_widget_show(spacer); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(spacer), TRUE, TRUE, 0); + + GtkButton* button = create_modal_dialog_button("Close", dialog.m_close_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_grab_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); + } + + modal_dialog_show(window, dialog); + gtk_widget_destroy(GTK_WIDGET(window)); +} + +#include "profile/profile.h" + +const char* const COMMANDS_VERSION = "1.0-gtk-accelnames"; + +void SaveCommandMap(const char* path) +{ + StringOutputStream strINI(256); + strINI << path << "shortcuts.ini"; + + TextFileOutputStream file(strINI.c_str()); + if(!file.failed()) + { + file << "[Version]\n"; + file << "number=" << COMMANDS_VERSION << "\n"; + file << "\n"; + file << "[Commands]\n"; + class WriteCommandMap : public CommandVisitor + { + TextFileOutputStream& m_file; + public: + WriteCommandMap(TextFileOutputStream& file) : m_file(file) + { + } + void visit(const char* name, Accelerator& accelerator) + { + m_file << name << "="; + + const char* key = gtk_accelerator_name(accelerator.key, accelerator.modifiers); + m_file << key; + m_file << "\n"; + } + } visitor(file); + GlobalShortcuts_foreach(visitor); + } +} + +const char* stringrange_find(const char* first, const char* last, char c) +{ + const char* p = strchr(first, '+'); + if(p == 0) + { + return last; + } + return p; +} + +class ReadCommandMap : public CommandVisitor +{ + const char* m_filename; + std::size_t m_count; +public: + ReadCommandMap(const char* filename) : m_filename(filename), m_count(0) + { + } + void visit(const char* name, Accelerator& accelerator) + { + char value[1024]; + if (read_var(m_filename, "Commands", name, value )) + { + if(string_empty(value)) + { + accelerator.key = 0; + accelerator.modifiers = (GdkModifierType)0; + return; + } + + gtk_accelerator_parse(value, &accelerator.key, &accelerator.modifiers); + accelerator = accelerator; // fix modifiers + + if(accelerator.key != 0) + { + ++m_count; + } + else + { + globalOutputStream() << "WARNING: failed to parse user command " << makeQuoted(name) << ": unknown key " << makeQuoted(value) << "\n"; + } + } + } + std::size_t count() const + { + return m_count; + } +}; + +void LoadCommandMap(const char* path) +{ + StringOutputStream strINI(256); + strINI << path << "shortcuts.ini"; + + FILE* f = fopen (strINI.c_str(), "r"); + if (f != 0) + { + fclose(f); + globalOutputStream() << "loading custom shortcuts list from " << makeQuoted(strINI.c_str()) << "\n"; + + Version version = version_parse(COMMANDS_VERSION); + Version dataVersion = { 0, 0 }; + + { + char value[1024]; + if(read_var(strINI.c_str(), "Version", "number", value)) + { + dataVersion = version_parse(value); + } + } + + if(version_compatible(version, dataVersion)) + { + globalOutputStream() << "commands import: data version " << dataVersion << " is compatible with code version " << version << "\n"; + ReadCommandMap visitor(strINI.c_str()); + GlobalShortcuts_foreach(visitor); + globalOutputStream() << "parsed " << Unsigned(visitor.count()) << " custom shortcuts\n"; + } + else + { + globalOutputStream() << "commands import: data version " << dataVersion << " is not compatible with code version " << version << "\n"; + } + } + else + { + globalOutputStream() << "failed to load custom shortcuts from " << makeQuoted(strINI.c_str()) << "\n"; + } +} diff --git a/misc/mediasource/netradiant-src/radiant/commands.h b/misc/mediasource/netradiant-src/radiant/commands.h new file mode 100644 index 00000000..677f0854 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/commands.h @@ -0,0 +1,54 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_COMMANDS_H) +#define INCLUDED_COMMANDS_H + +#include "gtkutil/accelerator.h" + + +const Accelerator& GlobalShortcuts_insert(const char* name, const Accelerator& accelerator); +void GlobalShortcuts_register(const char* name, int type); // 1 = command, 2 = toggle +void GlobalShortcuts_reportUnregistered(); + +class CommandVisitor +{ +public: + virtual void visit(const char* name, Accelerator& accelerator) = 0; +}; + +void GlobalCommands_insert(const char* name, const Callback& callback, const Accelerator& accelerator = accelerator_null()); +const Command& GlobalCommands_find(const char* name); + +void GlobalToggles_insert(const char* name, const Callback& callback, const BoolExportCallback& exportCallback, const Accelerator& accelerator = accelerator_null()); +const Toggle& GlobalToggles_find(const char* name); + +void GlobalKeyEvents_insert(const char* name, const Accelerator& accelerator, const Callback& keyDown, const Callback& keyUp); +const KeyEvent& GlobalKeyEvents_find(const char* name); + + +void DoCommandListDlg(); + +void LoadCommandMap(const char* path); +void SaveCommandMap(const char* path); + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/console.cpp b/misc/mediasource/netradiant-src/radiant/console.cpp new file mode 100644 index 00000000..cff963f2 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/console.cpp @@ -0,0 +1,274 @@ +/* +Copyright (C) 1999-2006 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 "console.h" + +#include +#include +#include +#include +#include + +#include "gtkutil/accelerator.h" +#include "gtkutil/messagebox.h" +#include "gtkutil/container.h" +#include "gtkutil/menu.h" +#include "gtkutil/nonmodal.h" +#include "stream/stringstream.h" +#include "convert.h" + +#include "version.h" +#include "aboutmsg.h" +#include "gtkmisc.h" +#include "mainframe.h" + +// handle to the console log file +namespace +{ + FILE* g_hLogFile; +} + +bool g_Console_enableLogging = false; + +// called whenever we need to open/close/check the console log file +void Sys_LogFile(bool enable) +{ + if (enable && !g_hLogFile) + { + // settings say we should be logging and we don't have a log file .. so create it + if(!SettingsPath_get()[0]) + return; // cannot open a log file yet + // open a file to log the console (if user prefs say so) + // the file handle is g_hLogFile + // the log file is erased + StringOutputStream name(256); + name << SettingsPath_get() << "radiant.log"; + g_hLogFile = fopen( name.c_str(), "w" ); + if (g_hLogFile != 0) + { + globalOutputStream() << "Started logging to " << name.c_str() << "\n"; + time_t localtime; + time(&localtime); + globalOutputStream() << "Today is: " << ctime(&localtime) + << "This is NetRadiant '" RADIANT_VERSION "' compiled " __DATE__ "\n" RADIANT_ABOUTMSG "\n"; + } + else + gtk_MessageBox (0, "Failed to create log file, check write permissions in Radiant directory.\n", + "Console logging", eMB_OK, eMB_ICONERROR ); + } + else if (!enable && g_hLogFile != 0) + { + // settings say we should not be logging but still we have an active logfile .. close it + time_t localtime; + time(&localtime); + globalOutputStream() << "Closing log file at " << ctime(&localtime) << "\n"; + fclose( g_hLogFile ); + g_hLogFile = 0; + } +} + +GtkWidget* g_console = 0; + +void console_clear() +{ + GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(g_console)); + gtk_text_buffer_set_text(buffer, "", -1); +} + +void console_populate_popup(GtkTextView* textview, GtkMenu* menu, gpointer user_data) +{ + menu_separator(menu); + + GtkWidget* item = gtk_menu_item_new_with_label ("Clear"); + g_signal_connect(G_OBJECT (item), "activate", G_CALLBACK(console_clear), 0); + gtk_widget_show (item); + container_add_widget(GTK_CONTAINER(menu), item); +} + +gboolean destroy_set_null(GtkWindow* widget, GtkWidget** p) +{ + *p = 0; + return FALSE; +} + +WidgetFocusPrinter g_consoleWidgetFocusPrinter("console"); + +GtkWidget* Console_constructWindow(GtkWindow* toplevel) +{ + GtkWidget* scr = gtk_scrolled_window_new (0, 0); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scr), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); + gtk_widget_show(scr); + + { + GtkWidget* text = gtk_text_view_new(); + gtk_widget_set_size_request(text, 0, -1); // allow shrinking + gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text), GTK_WRAP_WORD); + gtk_text_view_set_editable(GTK_TEXT_VIEW(text), FALSE); + gtk_container_add(GTK_CONTAINER (scr), text); + gtk_widget_show(text); + g_console = text; + + //globalExtendedASCIICharacterSet().print(); + + widget_connect_escape_clear_focus_widget(g_console); + + //g_consoleWidgetFocusPrinter.connect(g_console); + + g_signal_connect(G_OBJECT(g_console), "populate-popup", G_CALLBACK(console_populate_popup), 0); + g_signal_connect(G_OBJECT(g_console), "destroy", G_CALLBACK(destroy_set_null), &g_console); + } + + gtk_container_set_focus_chain(GTK_CONTAINER(scr), NULL); + + return scr; +} + +class GtkTextBufferOutputStream : public TextOutputStream +{ + GtkTextBuffer* textBuffer; + GtkTextIter* iter; + GtkTextTag* tag; +public: + GtkTextBufferOutputStream(GtkTextBuffer* textBuffer, GtkTextIter* iter, GtkTextTag* tag) : textBuffer(textBuffer), iter(iter), tag(tag) + { + } + std::size_t write(const char* buffer, std::size_t length) + { + gtk_text_buffer_insert_with_tags(textBuffer, iter, buffer, gint(length), tag, 0); + return length; + } +}; + +std::size_t Sys_Print(int level, const char* buf, std::size_t length) +{ + bool contains_newline = std::find(buf, buf+length, '\n') != buf+length; + + if(level == SYS_ERR) + { + Sys_LogFile(true); + } + + if (g_hLogFile != 0) + { + fwrite(buf, 1, length, g_hLogFile); + if(contains_newline) + { + fflush(g_hLogFile); + } + } + + if (level != SYS_NOCON) + { + if (g_console != 0) + { + GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(g_console)); + + GtkTextIter iter; + gtk_text_buffer_get_end_iter(buffer, &iter); + + static GtkTextMark* end = gtk_text_buffer_create_mark(buffer, "end", &iter, FALSE); + + const GdkColor yellow = { 0, 0xb0ff, 0xb0ff, 0x0000 }; + const GdkColor red = { 0, 0xffff, 0x0000, 0x0000 }; + + static GtkTextTag* error_tag = gtk_text_buffer_create_tag (buffer, "red_foreground", "foreground-gdk", &red, 0); + static GtkTextTag* warning_tag = gtk_text_buffer_create_tag (buffer, "yellow_foreground", "foreground-gdk", &yellow, 0); + static GtkTextTag* standard_tag = gtk_text_buffer_create_tag (buffer, "black_foreground", 0); + GtkTextTag* tag; + switch (level) + { + case SYS_WRN: + tag = warning_tag; + break; + case SYS_ERR: + tag = error_tag; + break; + case SYS_STD: + case SYS_VRB: + default: + tag = standard_tag; + break; + } + + + { + GtkTextBufferOutputStream textBuffer(buffer, &iter, tag); + if(!globalCharacterSet().isUTF8()) + { + BufferedTextOutputStream buffered(textBuffer); + buffered << StringRange(buf, buf + length); + } + else + { + textBuffer << StringRange(buf, buf + length); + } + } + + // update console widget immediatly if we're doing something time-consuming + if(contains_newline) + { + gtk_text_view_scroll_mark_onscreen(GTK_TEXT_VIEW(g_console), end); + + if(!ScreenUpdates_Enabled() && GTK_WIDGET_REALIZED(g_console)) + { + ScreenUpdates_process(); + } + } + } + } + return length; +} + + +class SysPrintOutputStream : public TextOutputStream +{ +public: + std::size_t write(const char* buffer, std::size_t length) + { + return Sys_Print(SYS_STD, buffer, length); + } +}; + +class SysPrintErrorStream : public TextOutputStream +{ +public: + std::size_t write(const char* buffer, std::size_t length) + { + return Sys_Print(SYS_ERR, buffer, length); + } +}; + +SysPrintOutputStream g_outputStream; + +TextOutputStream& getSysPrintOutputStream() +{ + return g_outputStream; +} + +SysPrintErrorStream g_errorStream; + +TextOutputStream& getSysPrintErrorStream() +{ + return g_errorStream; +} + + diff --git a/misc/mediasource/netradiant-src/radiant/console.h b/misc/mediasource/netradiant-src/radiant/console.h new file mode 100644 index 00000000..4e79782e --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/console.h @@ -0,0 +1,47 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_CONSOLE_H) +#define INCLUDED_CONSOLE_H + +#include + +#define SYS_VRB 0 ///< verbose support (on/off) +#define SYS_STD 1 ///< standard print level - this is the default +#define SYS_WRN 2 ///< warnings +#define SYS_ERR 3 ///< error +#define SYS_NOCON 4 ///< no console, only print to the file (useful whenever Sys_Printf and output IS the problem) + +std::size_t Sys_Print(int level, const char* buf, std::size_t length); +class TextOutputStream; +TextOutputStream& getSysPrintOutputStream(); +TextOutputStream& getSysPrintErrorStream(); + +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; +GtkWidget* Console_constructWindow(GtkWindow* toplevel); + +// will open/close the log file based on the parameter +void Sys_LogFile(bool enable); +extern bool g_Console_enableLogging; + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/csg.cpp b/misc/mediasource/netradiant-src/radiant/csg.cpp new file mode 100644 index 00000000..f30fb980 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/csg.cpp @@ -0,0 +1,692 @@ +/* +Copyright (C) 1999-2006 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 "csg.h" + +#include "debugging/debugging.h" + +#include + +#include "map.h" +#include "brushmanip.h" +#include "brushnode.h" +#include "grid.h" + +void Face_makeBrush(Face& face, const Brush& brush, brush_vector_t& out, float offset) +{ + if(face.contributes()) + { + out.push_back(new Brush(brush)); + Face* newFace = out.back()->addFace(face); + if(newFace != 0) + { + newFace->flipWinding(); + newFace->getPlane().offset(offset); + newFace->planeChanged(); + } + } +} + +class FaceMakeBrush +{ + const Brush& brush; + brush_vector_t& out; + float offset; +public: + FaceMakeBrush(const Brush& brush, brush_vector_t& out, float offset) + : brush(brush), out(out), offset(offset) + { + } + void operator()(Face& face) const + { + Face_makeBrush(face, brush, out, offset); + } +}; + +void Brush_makeHollow(const Brush& brush, brush_vector_t& out, float offset) +{ + Brush_forEachFace(brush, FaceMakeBrush(brush, out, offset)); +} + +class BrushHollowSelectedWalker : public scene::Graph::Walker +{ + float m_offset; +public: + BrushHollowSelectedWalker(float offset) + : m_offset(offset) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Brush* brush = Node_getBrush(path.top()); + if(brush != 0 + && Instance_getSelectable(instance)->isSelected() + && path.size() > 1) + { + brush_vector_t out; + Brush_makeHollow(*brush, out, m_offset); + for(brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i) + { + (*i)->removeEmptyFaces(); + NodeSmartReference node((new BrushNode())->node()); + Node_getBrush(node)->copy(*(*i)); + delete (*i); + Node_getTraversable(path.parent())->insert(node); + } + } + } + return true; + } +}; + +typedef std::list brushlist_t; + +class BrushGatherSelected : public scene::Graph::Walker +{ + brush_vector_t& m_brushlist; +public: + BrushGatherSelected(brush_vector_t& brushlist) + : m_brushlist(brushlist) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Brush* brush = Node_getBrush(path.top()); + if(brush != 0 + && Instance_getSelectable(instance)->isSelected()) + { + m_brushlist.push_back(brush); + } + } + return true; + } +}; + +class BrushDeleteSelected : public scene::Graph::Walker +{ +public: + bool pre(const scene::Path& path, scene::Instance& instance) const + { + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Brush* brush = Node_getBrush(path.top()); + if(brush != 0 + && Instance_getSelectable(instance)->isSelected() + && path.size() > 1) + { + Path_deleteTop(path); + } + } + } +}; + +void Scene_BrushMakeHollow_Selected(scene::Graph& graph) +{ + GlobalSceneGraph().traverse(BrushHollowSelectedWalker(GetGridSize())); + GlobalSceneGraph().traverse(BrushDeleteSelected()); +} + +/* +============= +CSG_MakeHollow +============= +*/ + +void CSG_MakeHollow (void) +{ + UndoableCommand undo("brushHollow"); + + Scene_BrushMakeHollow_Selected(GlobalSceneGraph()); + + SceneChangeNotify(); +} + +template +class RemoveReference +{ +public: + typedef Type type; +}; + +template +class RemoveReference +{ +public: + typedef Type type; +}; + +template +class Dereference +{ + const Functor& functor; +public: + typedef typename RemoveReference::type* first_argument_type; + typedef typename Functor::result_type result_type; + Dereference(const Functor& functor) : functor(functor) + { + } + result_type operator()(first_argument_type firstArgument) const + { + return functor(*firstArgument); + } +}; + +template +inline Dereference makeDereference(const Functor& functor) +{ + return Dereference(functor); +} + +typedef Face* FacePointer; +const FacePointer c_nullFacePointer = 0; + +template +Face* Brush_findIf(const Brush& brush, const Predicate& predicate) +{ + Brush::const_iterator i = std::find_if(brush.begin(), brush.end(), makeDereference(predicate)); + return i == brush.end() ? c_nullFacePointer : *i; // uses c_nullFacePointer instead of 0 because otherwise gcc 4.1 attempts conversion to int +} + +template +class BindArguments1 +{ + typedef typename Caller::second_argument_type FirstBound; + FirstBound firstBound; +public: + typedef typename Caller::result_type result_type; + typedef typename Caller::first_argument_type first_argument_type; + BindArguments1(FirstBound firstBound) + : firstBound(firstBound) + { + } + result_type operator()(first_argument_type firstArgument) const + { + return Caller::call(firstArgument, firstBound); + } +}; + +template +class BindArguments2 +{ + typedef typename Caller::second_argument_type FirstBound; + typedef typename Caller::third_argument_type SecondBound; + FirstBound firstBound; + SecondBound secondBound; +public: + typedef typename Caller::result_type result_type; + typedef typename Caller::first_argument_type first_argument_type; + BindArguments2(FirstBound firstBound, SecondBound secondBound) + : firstBound(firstBound), secondBound(secondBound) + { + } + result_type operator()(first_argument_type firstArgument) const + { + return Caller::call(firstArgument, firstBound, secondBound); + } +}; + +template +BindArguments2 bindArguments(const Caller& caller, FirstBound firstBound, SecondBound secondBound) +{ + return BindArguments2(firstBound, secondBound); +} + +inline bool Face_testPlane(const Face& face, const Plane3& plane, bool flipped) +{ + return face.contributes() && !Winding_TestPlane(face.getWinding(), plane, flipped); +} +typedef Function3 FaceTestPlane; + + + +/// \brief Returns true if +/// \li !flipped && brush is BACK or ON +/// \li flipped && brush is FRONT or ON +bool Brush_testPlane(const Brush& brush, const Plane3& plane, bool flipped) +{ + brush.evaluateBRep(); +#if 1 + for(Brush::const_iterator i(brush.begin()); i != brush.end(); ++i) + { + if(Face_testPlane(*(*i), plane, flipped)) + { + return false; + } + } + return true; +#else + return Brush_findIf(brush, bindArguments(FaceTestPlane(), makeReference(plane), flipped)) == 0; +#endif +} + +brushsplit_t Brush_classifyPlane(const Brush& brush, const Plane3& plane) +{ + brush.evaluateBRep(); + brushsplit_t split; + for(Brush::const_iterator i(brush.begin()); i != brush.end(); ++i) + { + if((*i)->contributes()) + { + split += Winding_ClassifyPlane((*i)->getWinding(), plane); + } + } + return split; +} + +bool Brush_subtract(const Brush& brush, const Brush& other, brush_vector_t& ret_fragments) +{ + if(aabb_intersects_aabb(brush.localAABB(), other.localAABB())) + { + brush_vector_t fragments; + fragments.reserve(other.size()); + Brush back(brush); + + for(Brush::const_iterator i(other.begin()); i != other.end(); ++i) + { + if((*i)->contributes()) + { + brushsplit_t split = Brush_classifyPlane(back, (*i)->plane3()); + if(split.counts[ePlaneFront] != 0 + && split.counts[ePlaneBack] != 0) + { + fragments.push_back(new Brush(back)); + Face* newFace = fragments.back()->addFace(*(*i)); + if(newFace != 0) + { + newFace->flipWinding(); + } + back.addFace(*(*i)); + } + else if(split.counts[ePlaneBack] == 0) + { + for(brush_vector_t::iterator i = fragments.begin(); i != fragments.end(); ++i) + { + delete(*i); + } + return false; + } + } + } + ret_fragments.insert(ret_fragments.end(), fragments.begin(), fragments.end()); + return true; + } + return false; +} + +class SubtractBrushesFromUnselected : public scene::Graph::Walker +{ + const brush_vector_t& m_brushlist; + std::size_t& m_before; + std::size_t& m_after; +public: + SubtractBrushesFromUnselected(const brush_vector_t& brushlist, std::size_t& before, std::size_t& after) + : m_brushlist(brushlist), m_before(before), m_after(after) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Brush* brush = Node_getBrush(path.top()); + if(brush != 0 + && !Instance_getSelectable(instance)->isSelected()) + { + brush_vector_t buffer[2]; + bool swap = false; + Brush* original = new Brush(*brush); + buffer[static_cast(swap)].push_back(original); + + { + for(brush_vector_t::const_iterator i(m_brushlist.begin()); i != m_brushlist.end(); ++i) + { + for(brush_vector_t::iterator j(buffer[static_cast(swap)].begin()); j != buffer[static_cast(swap)].end(); ++j) + { + if(Brush_subtract(*(*j), *(*i), buffer[static_cast(!swap)])) + { + delete (*j); + } + else + { + buffer[static_cast(!swap)].push_back((*j)); + } + } + buffer[static_cast(swap)].clear(); + swap = !swap; + } + } + + brush_vector_t& out = buffer[static_cast(swap)]; + + if(out.size() == 1 && out.back() == original) + { + delete original; + } + else + { + ++m_before; + for(brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i) + { + ++m_after; + NodeSmartReference node((new BrushNode())->node()); + (*i)->removeEmptyFaces(); + ASSERT_MESSAGE(!(*i)->empty(), "brush left with no faces after subtract"); + Node_getBrush(node)->copy(*(*i)); + delete (*i); + Node_getTraversable(path.parent())->insert(node); + } + Path_deleteTop(path); + } + } + } + } +}; + +void CSG_Subtract() +{ + brush_vector_t selected_brushes; + GlobalSceneGraph().traverse(BrushGatherSelected(selected_brushes)); + + if (selected_brushes.empty()) + { + globalOutputStream() << "CSG Subtract: No brushes selected.\n"; + } + else + { + globalOutputStream() << "CSG Subtract: Subtracting " << Unsigned(selected_brushes.size()) << " brushes.\n"; + + UndoableCommand undo("brushSubtract"); + + // subtract selected from unselected + std::size_t before = 0; + std::size_t after = 0; + GlobalSceneGraph().traverse(SubtractBrushesFromUnselected(selected_brushes, before, after)); + globalOutputStream() << "CSG Subtract: Result: " + << Unsigned(after) << " fragment" << (after == 1 ? "" : "s") + << " from " << Unsigned(before) << " brush" << (before == 1? "" : "es") << ".\n"; + + SceneChangeNotify(); + } +} + +class BrushSplitByPlaneSelected : public scene::Graph::Walker +{ + const Vector3& m_p0; + const Vector3& m_p1; + const Vector3& m_p2; + const char* m_shader; + const TextureProjection& m_projection; + EBrushSplit m_split; +public: + BrushSplitByPlaneSelected(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection, EBrushSplit split) + : m_p0(p0), m_p1(p1), m_p2(p2), m_shader(shader), m_projection(projection), m_split(split) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Brush* brush = Node_getBrush(path.top()); + if(brush != 0 + && Instance_getSelectable(instance)->isSelected()) + { + Plane3 plane(plane3_for_points(m_p0, m_p1, m_p2)); + if(plane3_valid(plane)) + { + brushsplit_t split = Brush_classifyPlane(*brush, m_split == eFront ? plane3_flipped(plane) : plane); + if(split.counts[ePlaneBack] && split.counts[ePlaneFront]) + { + // the plane intersects this brush + if(m_split == eFrontAndBack) + { + NodeSmartReference node((new BrushNode())->node()); + Brush* fragment = Node_getBrush(node); + fragment->copy(*brush); + Face* newFace = fragment->addPlane(m_p0, m_p1, m_p2, m_shader, m_projection); + if(newFace != 0 && m_split != eFront) + { + newFace->flipWinding(); + } + fragment->removeEmptyFaces(); + ASSERT_MESSAGE(!fragment->empty(), "brush left with no faces after split"); + + Node_getTraversable(path.parent())->insert(node); + { + scene::Path fragmentPath = path; + fragmentPath.top() = makeReference(node.get()); + selectPath(fragmentPath, true); + } + } + + Face* newFace = brush->addPlane(m_p0, m_p1, m_p2, m_shader, m_projection); + if(newFace != 0 && m_split == eFront) + { + newFace->flipWinding(); + } + brush->removeEmptyFaces(); + ASSERT_MESSAGE(!brush->empty(), "brush left with no faces after split"); + } + else + // the plane does not intersect this brush + if(m_split != eFrontAndBack && split.counts[ePlaneBack] != 0) + { + // the brush is "behind" the plane + Path_deleteTop(path); + } + } + } + } + } +}; + +void Scene_BrushSplitByPlane(scene::Graph& graph, const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, EBrushSplit split) +{ + TextureProjection projection; + TexDef_Construct_Default(projection); + graph.traverse(BrushSplitByPlaneSelected(p0, p1, p2, shader, projection, split)); + SceneChangeNotify(); +} + + +class BrushInstanceSetClipPlane : public scene::Graph::Walker +{ + Plane3 m_plane; +public: + BrushInstanceSetClipPlane(const Plane3& plane) + : m_plane(plane) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + BrushInstance* brush = Instance_getBrush(instance); + if(brush != 0 + && path.top().get().visible() + && brush->isSelected()) + { + BrushInstance& brushInstance = *brush; + brushInstance.setClipPlane(m_plane); + } + return true; + } +}; + +void Scene_BrushSetClipPlane(scene::Graph& graph, const Plane3& plane) +{ + graph.traverse(BrushInstanceSetClipPlane(plane)); +} + +/* +============= +CSG_Merge +============= +*/ +bool Brush_merge(Brush& brush, const brush_vector_t& in, bool onlyshape) +{ + // gather potential outer faces + + { + typedef std::vector Faces; + Faces faces; + for(brush_vector_t::const_iterator i(in.begin()); i != in.end(); ++i) + { + (*i)->evaluateBRep(); + for(Brush::const_iterator j((*i)->begin()); j != (*i)->end(); ++j) + { + if(!(*j)->contributes()) + { + continue; + } + + const Face& face1 = *(*j); + + bool skip = false; + // test faces of all input brushes + //!\todo SPEEDUP: Flag already-skip faces and only test brushes from i+1 upwards. + for(brush_vector_t::const_iterator k(in.begin()); !skip && k != in.end(); ++k) + { + if(k != i) // don't test a brush against itself + { + for(Brush::const_iterator l((*k)->begin()); !skip && l != (*k)->end(); ++l) + { + const Face& face2 = *(*l); + + // face opposes another face + if(plane3_opposing(face1.plane3(), face2.plane3())) + { + // skip opposing planes + skip = true; + break; + } + } + } + } + + // check faces already stored + for(Faces::const_iterator m = faces.begin(); !skip && m != faces.end(); ++m) + { + const Face& face2 = *(*m); + + // face equals another face + if (plane3_equal(face1.plane3(), face2.plane3())) + { + //if the texture/shader references should be the same but are not + if (!onlyshape && !shader_equal(face1.getShader().getShader(), face2.getShader().getShader())) + { + return false; + } + // skip duplicate planes + skip = true; + break; + } + + // face1 plane intersects face2 winding or vice versa + if (Winding_PlanesConcave(face1.getWinding(), face2.getWinding(), face1.plane3(), face2.plane3())) + { + // result would not be convex + return false; + } + } + + if(!skip) + { + faces.push_back(&face1); + } + } + } + for(Faces::const_iterator i = faces.begin(); i != faces.end(); ++i) + { + if(!brush.addFace(*(*i))) + { + // result would have too many sides + return false; + } + } + } + + brush.removeEmptyFaces(); + + return true; +} + +void CSG_Merge(void) +{ + brush_vector_t selected_brushes; + + // remove selected + GlobalSceneGraph().traverse(BrushGatherSelected(selected_brushes)); + + if (selected_brushes.empty()) + { + globalOutputStream() << "CSG Merge: No brushes selected.\n"; + return; + } + + if (selected_brushes.size() < 2) + { + globalOutputStream() << "CSG Merge: At least two brushes have to be selected.\n"; + return; + } + + globalOutputStream() << "CSG Merge: Merging " << Unsigned(selected_brushes.size()) << " brushes.\n"; + + UndoableCommand undo("brushMerge"); + + scene::Path merged_path = GlobalSelectionSystem().ultimateSelected().path(); + + NodeSmartReference node((new BrushNode())->node()); + Brush* brush = Node_getBrush(node); + // if the new brush would not be convex + if(!Brush_merge(*brush, selected_brushes, true)) + { + globalOutputStream() << "CSG Merge: Failed - result would not be convex.\n"; + } + else + { + ASSERT_MESSAGE(!brush->empty(), "brush left with no faces after merge"); + + // free the original brushes + GlobalSceneGraph().traverse(BrushDeleteSelected()); + + merged_path.pop(); + Node_getTraversable(merged_path.top())->insert(node); + merged_path.push(makeReference(node.get())); + + selectPath(merged_path, true); + + globalOutputStream() << "CSG Merge: Succeeded.\n"; + SceneChangeNotify(); + } +} diff --git a/misc/mediasource/netradiant-src/radiant/csg.h b/misc/mediasource/netradiant-src/radiant/csg.h new file mode 100644 index 00000000..867ab199 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/csg.h @@ -0,0 +1,46 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_CSG_H) +#define INCLUDED_CSG_H + +void CSG_MakeHollow (void); +void CSG_Subtract (void); +void CSG_Merge (void); + +namespace scene +{ + class Graph; +} +template class BasicVector3; +typedef BasicVector3 Vector3; +class Plane3; + +void Scene_BrushSetClipPlane(scene::Graph& graph, const Plane3& plane); +enum EBrushSplit +{ + eFront, + eBack, + eFrontAndBack, +}; +void Scene_BrushSplitByPlane(scene::Graph& graph, const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, EBrushSplit split); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/dialog.cpp b/misc/mediasource/netradiant-src/radiant/dialog.cpp new file mode 100644 index 00000000..d3e4dba1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/dialog.cpp @@ -0,0 +1,735 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Base dialog class, provides a way to run modal dialogs and +// set/get the widget values in member variables. +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "dialog.h" + +#include "debugging/debugging.h" + + +#include "mainframe.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "stream/stringstream.h" +#include "convert.h" +#include "gtkutil/dialog.h" +#include "gtkutil/button.h" +#include "gtkutil/entry.h" +#include "gtkutil/image.h" + +#include "gtkmisc.h" + + +GtkEntry* DialogEntry_new() +{ + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_widget_set_size_request(GTK_WIDGET(entry), 64, -1); + return entry; +} + +class DialogEntryRow +{ +public: + DialogEntryRow(GtkWidget* row, GtkEntry* entry) : m_row(row), m_entry(entry) + { + } + GtkWidget* m_row; + GtkEntry* m_entry; +}; + +DialogEntryRow DialogEntryRow_new(const char* name) +{ + GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); + gtk_widget_show(alignment); + + GtkEntry* entry = DialogEntry_new(); + gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(entry)); + + return DialogEntryRow(GTK_WIDGET(DialogRow_new(name, alignment)), entry); +} + + +GtkSpinButton* DialogSpinner_new(double value, double lower, double upper, int fraction) +{ + double step = 1.0 / double(fraction); + unsigned int digits = 0; + for(;fraction > 1; fraction /= 10) + { + ++digits; + } + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(value, lower, upper, step, 10, 0)), step, digits)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); + return spin; +} + +class DialogSpinnerRow +{ +public: + DialogSpinnerRow(GtkWidget* row, GtkSpinButton* spin) : m_row(row), m_spin(spin) + { + } + GtkWidget* m_row; + GtkSpinButton* m_spin; +}; + +DialogSpinnerRow DialogSpinnerRow_new(const char* name, double value, double lower, double upper, int fraction) +{ + GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); + gtk_widget_show(alignment); + + GtkSpinButton* spin = DialogSpinner_new(value, lower, upper, fraction); + gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(spin)); + + return DialogSpinnerRow(GTK_WIDGET(DialogRow_new(name, alignment)), spin); +} + + + +template< + typename Type_, + typename Other_, + void(*Import)(Type_&, Other_), + void(*Export)(Type_&, const Callback1&) +> +class ImportExport +{ +public: + typedef Type_ Type; + typedef Other_ Other; + + typedef ReferenceCaller1 ImportCaller; + typedef ReferenceCaller1&, Export> ExportCaller; +}; + +typedef ImportExport BoolImportExport; +typedef ImportExport IntImportExport; +typedef ImportExport SizeImportExport; +typedef ImportExport FloatImportExport; +typedef ImportExport StringImportExport; + + + +void BoolToggleImport(GtkToggleButton& widget, bool value) +{ + gtk_toggle_button_set_active(&widget, value); +} +void BoolToggleExport(GtkToggleButton& widget, const BoolImportCallback& importCallback) +{ + importCallback(gtk_toggle_button_get_active(&widget) != FALSE); +} +typedef ImportExport BoolToggleImportExport; + + +void IntRadioImport(GtkRadioButton& widget, int index) +{ + radio_button_set_active(&widget, index); +} +void IntRadioExport(GtkRadioButton& widget, const IntImportCallback& importCallback) +{ + importCallback(radio_button_get_active(&widget)); +} +typedef ImportExport IntRadioImportExport; + +void TextEntryImport(GtkEntry& widget, const char* text) +{ + gtk_entry_set_text(&widget, text); +} +void TextEntryExport(GtkEntry& widget, const StringImportCallback& importCallback) +{ + importCallback(gtk_entry_get_text(&widget)); +} +typedef ImportExport TextEntryImportExport; + + +void IntEntryImport(GtkEntry& widget, int value) +{ + entry_set_int(&widget, value); +} +void IntEntryExport(GtkEntry& widget, const IntImportCallback& importCallback) +{ + importCallback(atoi(gtk_entry_get_text (&widget))); +} +typedef ImportExport IntEntryImportExport; + + +void SizeEntryImport(GtkEntry& widget, std::size_t value) +{ + entry_set_int(&widget, int(value)); +} +void SizeEntryExport(GtkEntry& widget, const SizeImportCallback& importCallback) +{ + int value = atoi(gtk_entry_get_text(&widget)); + if(value < 0) + { + value = 0; + } + importCallback(value); +} +typedef ImportExport SizeEntryImportExport; + + +void FloatEntryImport(GtkEntry& widget, float value) +{ + entry_set_float(&widget, value); +} +void FloatEntryExport(GtkEntry& widget, const FloatImportCallback& importCallback) +{ + importCallback((float)atof(gtk_entry_get_text(&widget))); +} +typedef ImportExport FloatEntryImportExport; + + +void FloatSpinnerImport(GtkSpinButton& widget, float value) +{ + gtk_spin_button_set_value(&widget, value); +} +void FloatSpinnerExport(GtkSpinButton& widget, const FloatImportCallback& importCallback) +{ + importCallback(float(gtk_spin_button_get_value_as_float(&widget))); +} +typedef ImportExport FloatSpinnerImportExport; + + +void IntSpinnerImport(GtkSpinButton& widget, int value) +{ + gtk_spin_button_set_value(&widget, value); +} +void IntSpinnerExport(GtkSpinButton& widget, const IntImportCallback& importCallback) +{ + importCallback(gtk_spin_button_get_value_as_int(&widget)); +} +typedef ImportExport IntSpinnerImportExport; + + +void IntAdjustmentImport(GtkAdjustment& widget, int value) +{ + gtk_adjustment_set_value(&widget, value); +} +void IntAdjustmentExport(GtkAdjustment& widget, const IntImportCallback& importCallback) +{ + importCallback((int)gtk_adjustment_get_value(&widget)); +} +typedef ImportExport IntAdjustmentImportExport; + + +void IntComboImport(GtkComboBox& widget, int value) +{ + gtk_combo_box_set_active(&widget, value); +} +void IntComboExport(GtkComboBox& widget, const IntImportCallback& importCallback) +{ + importCallback(gtk_combo_box_get_active(&widget)); +} +typedef ImportExport IntComboImportExport; + + +template +class CallbackDialogData : public DLG_DATA +{ +public: + typedef Callback1 ImportCallback; + typedef Callback1 ExportCallback; + +private: + ImportCallback m_importWidget; + ExportCallback m_exportWidget; + ImportCallback m_importViewer; + ExportCallback m_exportViewer; + +public: + CallbackDialogData(const ImportCallback& importWidget, const ExportCallback& exportWidget, const ImportCallback& importViewer, const ExportCallback& exportViewer) + : m_importWidget(importWidget), m_exportWidget(exportWidget), m_importViewer(importViewer), m_exportViewer(exportViewer) + { + } + void release() + { + delete this; + } + void importData() const + { + m_exportViewer(m_importWidget); + } + void exportData() const + { + m_exportWidget(m_importViewer); + } +}; + +template +class AddData +{ + DialogDataList& m_data; +public: + AddData(DialogDataList& data) : m_data(data) + { + } + void apply(typename Widget::Type& widget, typename Viewer::Type& viewer) const + { + m_data.push_back( + new CallbackDialogData( + typename Widget::ImportCaller(widget), + typename Widget::ExportCaller(widget), + typename Viewer::ImportCaller(viewer), + typename Viewer::ExportCaller(viewer) + ) + ); + } +}; + +template +class AddCustomData +{ + DialogDataList& m_data; +public: + AddCustomData(DialogDataList& data) : m_data(data) + { + } + void apply( + typename Widget::Type& widget, + const Callback1& importViewer, + const Callback1&>& exportViewer + ) const + { + m_data.push_back( + new CallbackDialogData( + typename Widget::ImportCaller(widget), + typename Widget::ExportCaller(widget), + importViewer, + exportViewer + ) + ); + } +}; + +// ============================================================================= +// Dialog class + +Dialog::Dialog() : m_window(0), m_parent(0) +{ +} + +Dialog::~Dialog() +{ + for(DialogDataList::iterator i = m_data.begin(); i != m_data.end(); ++i) + { + (*i)->release(); + } + + ASSERT_MESSAGE(m_window == 0, "dialog window not destroyed"); +} + +void Dialog::ShowDlg() +{ + ASSERT_MESSAGE(m_window != 0, "dialog was not constructed"); + importData(); + gtk_widget_show(GTK_WIDGET(m_window)); +} + +void Dialog::HideDlg() +{ + ASSERT_MESSAGE(m_window != 0, "dialog was not constructed"); + exportData(); + gtk_widget_hide(GTK_WIDGET(m_window)); +} + +static gint delete_event_callback(GtkWidget *widget, GdkEvent* event, gpointer data) +{ + reinterpret_cast(data)->HideDlg(); + reinterpret_cast(data)->EndModal(eIDCANCEL); + return TRUE; +} + +void Dialog::Create() +{ + ASSERT_MESSAGE(m_window == 0, "dialog cannot be constructed"); + + m_window = BuildDialog(); + g_signal_connect(G_OBJECT(m_window), "delete_event", G_CALLBACK(delete_event_callback), this); +} + +void Dialog::Destroy() +{ + ASSERT_MESSAGE(m_window != 0, "dialog cannot be destroyed"); + + gtk_widget_destroy(GTK_WIDGET(m_window)); + m_window = 0; +} + + +void Dialog::AddBoolToggleData(GtkToggleButton& widget, const BoolImportCallback& importViewer, const BoolExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddIntRadioData(GtkRadioButton& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddTextEntryData(GtkEntry& widget, const StringImportCallback& importViewer, const StringExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddIntEntryData(GtkEntry& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddSizeEntryData(GtkEntry& widget, const SizeImportCallback& importViewer, const SizeExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddFloatEntryData(GtkEntry& widget, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddFloatSpinnerData(GtkSpinButton& widget, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddIntSpinnerData(GtkSpinButton& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddIntAdjustmentData(GtkAdjustment& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + +void Dialog::AddIntComboData(GtkComboBox& widget, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + AddCustomData(m_data).apply(widget, importViewer, exportViewer); +} + + +void Dialog::AddDialogData(GtkToggleButton& widget, bool& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkRadioButton& widget, int& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkEntry& widget, CopiedString& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkEntry& widget, int& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkEntry& widget, std::size_t& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkEntry& widget, float& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkSpinButton& widget, float& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkSpinButton& widget, int& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkAdjustment& widget, int& data) +{ + AddData(m_data).apply(widget, data); +} +void Dialog::AddDialogData(GtkComboBox& widget, int& data) +{ + AddData(m_data).apply(widget, data); +} + +void Dialog::exportData() +{ + for(DialogDataList::iterator i = m_data.begin(); i != m_data.end(); ++i) + { + (*i)->exportData(); + } +} + +void Dialog::importData() +{ + for(DialogDataList::iterator i = m_data.begin(); i != m_data.end(); ++i) + { + (*i)->importData(); + } +} + +void Dialog::EndModal (EMessageBoxReturn code) +{ + m_modal.loop = 0; + m_modal.ret = code; +} + +EMessageBoxReturn Dialog::DoModal() +{ + importData(); + + PreModal(); + + EMessageBoxReturn ret = modal_dialog_show(m_window, m_modal); + ASSERT_NOTNULL(m_window); + if(ret == eIDOK) + { + exportData(); + } + + gtk_widget_hide(GTK_WIDGET(m_window)); + + PostModal(m_modal.ret); + + return m_modal.ret; +} + + +GtkWidget* Dialog::addCheckBox(GtkWidget* vbox, const char* name, const char* flag, const BoolImportCallback& importViewer, const BoolExportCallback& exportViewer) +{ + GtkWidget* check = gtk_check_button_new_with_label(flag); + gtk_widget_show(check); + AddBoolToggleData(*GTK_TOGGLE_BUTTON(check), importViewer, exportViewer); + + DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(DialogRow_new(name, check))); + return check; +} + +GtkWidget* Dialog::addCheckBox(GtkWidget* vbox, const char* name, const char* flag, bool& data) +{ + return addCheckBox(vbox, name, flag, BoolImportCaller(data), BoolExportCaller(data)); +} + +void Dialog::addCombo(GtkWidget* vbox, const char* name, StringArrayRange values, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); + gtk_widget_show(alignment); + { + GtkWidget* combo = gtk_combo_box_new_text(); + + for(StringArrayRange::Iterator i = values.first; i != values.last; ++i) + { + gtk_combo_box_append_text(GTK_COMBO_BOX(combo), *i); + } + + AddIntComboData(*GTK_COMBO_BOX(combo), importViewer, exportViewer); + + gtk_widget_show (combo); + gtk_container_add(GTK_CONTAINER(alignment), combo); + } + + GtkTable* row = DialogRow_new(name, alignment); + DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); +} + +void Dialog::addCombo(GtkWidget* vbox, const char* name, int& data, StringArrayRange values) +{ + addCombo(vbox, name, values, IntImportCaller(data), IntExportCaller(data)); +} + +void Dialog::addSlider(GtkWidget* vbox, const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment) +{ +#if 0 + if(draw_value == FALSE) + { + GtkWidget* hbox2 = gtk_hbox_new (FALSE, 0); + gtk_widget_show (hbox2); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox2), FALSE, FALSE, 0); + { + GtkWidget* label = gtk_label_new (low); + gtk_widget_show (label); + gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, FALSE, 0); + } + { + GtkWidget* label = gtk_label_new (high); + gtk_widget_show (label); + gtk_box_pack_end (GTK_BOX (hbox2), label, FALSE, FALSE, 0); + } + } +#endif + + // adjustment + GtkObject* adj = gtk_adjustment_new(value, lower, upper, step_increment, page_increment, 0); + AddIntAdjustmentData(*GTK_ADJUSTMENT(adj), IntImportCaller(data), IntExportCaller(data)); + + // scale + GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 1.0, 0.0); + gtk_widget_show(alignment); + + GtkWidget* scale = gtk_hscale_new(GTK_ADJUSTMENT(adj)); + gtk_scale_set_value_pos(GTK_SCALE(scale), GTK_POS_LEFT); + gtk_widget_show(scale); + gtk_container_add(GTK_CONTAINER(alignment), scale); + + gtk_scale_set_draw_value(GTK_SCALE (scale), draw_value); + gtk_scale_set_digits(GTK_SCALE (scale), 0); + + GtkTable* row = DialogRow_new(name, alignment); + DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); +} + +void Dialog::addRadio(GtkWidget* vbox, const char* name, StringArrayRange names, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + GtkWidget* alignment = gtk_alignment_new(0.0, 0.5, 0.0, 0.0); + gtk_widget_show(alignment); + { + RadioHBox radioBox = RadioHBox_new(names); + gtk_container_add(GTK_CONTAINER(alignment), GTK_WIDGET(radioBox.m_hbox)); + AddIntRadioData(*GTK_RADIO_BUTTON(radioBox.m_radio), importViewer, exportViewer); + } + + GtkTable* row = DialogRow_new(name, alignment); + DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); +} + +void Dialog::addRadio(GtkWidget* vbox, const char* name, int& data, StringArrayRange names) +{ + addRadio(vbox, name, names, IntImportCaller(data), IntExportCaller(data)); +} + +void Dialog::addRadioIcons(GtkWidget* vbox, const char* name, StringArrayRange icons, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + GtkWidget* table = gtk_table_new (2, static_cast(icons.last - icons.first), FALSE); + gtk_widget_show (table); + + gtk_table_set_row_spacings (GTK_TABLE (table), 5); + gtk_table_set_col_spacings (GTK_TABLE (table), 5); + + GSList* group = 0; + GtkWidget* radio = 0; + for(StringArrayRange::Iterator icon = icons.first; icon != icons.last; ++icon) + { + guint pos = static_cast(icon - icons.first); + GtkImage* image = new_local_image(*icon); + gtk_widget_show(GTK_WIDGET(image)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(image), pos, pos+1, 0, 1, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + + radio = gtk_radio_button_new(group); + gtk_widget_show (radio); + gtk_table_attach (GTK_TABLE (table), radio, pos, pos+1, 1, 2, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + + group = gtk_radio_button_get_group(GTK_RADIO_BUTTON(radio)); + } + + AddIntRadioData(*GTK_RADIO_BUTTON(radio), importViewer, exportViewer); + + DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(DialogRow_new(name, table))); +} + +void Dialog::addRadioIcons(GtkWidget* vbox, const char* name, int& data, StringArrayRange icons) +{ + addRadioIcons(vbox, name, icons, IntImportCaller(data), IntExportCaller(data)); +} + +GtkWidget* Dialog::addIntEntry(GtkWidget* vbox, const char* name, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + DialogEntryRow row(DialogEntryRow_new(name)); + AddIntEntryData(*row.m_entry, importViewer, exportViewer); + DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); + return row.m_row; +} + +GtkWidget* Dialog::addSizeEntry(GtkWidget* vbox, const char* name, const SizeImportCallback& importViewer, const SizeExportCallback& exportViewer) +{ + DialogEntryRow row(DialogEntryRow_new(name)); + AddSizeEntryData(*row.m_entry, importViewer, exportViewer); + DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); + return row.m_row; +} + +GtkWidget* Dialog::addFloatEntry(GtkWidget* vbox, const char* name, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) +{ + DialogEntryRow row(DialogEntryRow_new(name)); + AddFloatEntryData(*row.m_entry, importViewer, exportViewer); + DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); + return row.m_row; +} + +GtkWidget* Dialog::addPathEntry(GtkWidget* vbox, const char* name, bool browse_directory, const StringImportCallback& importViewer, const StringExportCallback& exportViewer) +{ + PathEntry pathEntry = PathEntry_new(); + g_signal_connect(G_OBJECT(pathEntry.m_button), "clicked", G_CALLBACK(browse_directory ? button_clicked_entry_browse_directory : button_clicked_entry_browse_file), pathEntry.m_entry); + + AddTextEntryData(*GTK_ENTRY(pathEntry.m_entry), importViewer, exportViewer); + + GtkTable* row = DialogRow_new(name, GTK_WIDGET(pathEntry.m_frame)); + DialogVBox_packRow(GTK_VBOX(vbox), GTK_WIDGET(row)); + + return GTK_WIDGET(row); +} + +GtkWidget* Dialog::addPathEntry(GtkWidget* vbox, const char* name, CopiedString& data, bool browse_directory) +{ + return addPathEntry(vbox, name, browse_directory, StringImportCallback(StringImportCaller(data)), StringExportCallback(StringExportCaller(data))); +} + +GtkWidget* Dialog::addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const IntImportCallback& importViewer, const IntExportCallback& exportViewer) +{ + DialogSpinnerRow row(DialogSpinnerRow_new(name, value, lower, upper, 1)); + AddIntSpinnerData(*row.m_spin, importViewer, exportViewer); + DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); + return row.m_row; +} + +GtkWidget* Dialog::addSpinner(GtkWidget* vbox, const char* name, int& data, double value, double lower, double upper) +{ + return addSpinner(vbox, name, value, lower, upper, IntImportCallback(IntImportCaller(data)), IntExportCallback(IntExportCaller(data))); +} + +GtkWidget* Dialog::addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const FloatImportCallback& importViewer, const FloatExportCallback& exportViewer) +{ + DialogSpinnerRow row(DialogSpinnerRow_new(name, value, lower, upper, 10)); + AddFloatSpinnerData(*row.m_spin, importViewer, exportViewer); + DialogVBox_packRow(GTK_VBOX(vbox), row.m_row); + return row.m_row; +} diff --git a/misc/mediasource/netradiant-src/radiant/dialog.h b/misc/mediasource/netradiant-src/radiant/dialog.h new file mode 100644 index 00000000..444fe516 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/dialog.h @@ -0,0 +1,208 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_DIALOG_H) +#define INCLUDED_DIALOG_H + +#include + +#include "gtkutil/dialog.h" +#include "generic/callback.h" +#include "string/string.h" + +template +class ReferenceCaller1; + +inline void BoolImport(bool& self, bool value) +{ + self = value; +} +typedef ReferenceCaller1 BoolImportCaller; + +inline void BoolExport(bool& self, const BoolImportCallback& importCallback) +{ + importCallback(self); +} +typedef ReferenceCaller1 BoolExportCaller; + + +inline void IntImport(int& self, int value) +{ + self = value; +} +typedef ReferenceCaller1 IntImportCaller; + +inline void IntExport(int& self, const IntImportCallback& importCallback) +{ + importCallback(self); +} +typedef ReferenceCaller1 IntExportCaller; + + +inline void SizeImport(std::size_t& self, std::size_t value) +{ + self = value; +} +typedef ReferenceCaller1 SizeImportCaller; + +inline void SizeExport(std::size_t& self, const SizeImportCallback& importCallback) +{ + importCallback(self); +} +typedef ReferenceCaller1 SizeExportCaller; + + +inline void FloatImport(float& self, float value) +{ + self = value; +} +typedef ReferenceCaller1 FloatImportCaller; + +inline void FloatExport(float& self, const FloatImportCallback& importCallback) +{ + importCallback(self); +} +typedef ReferenceCaller1 FloatExportCaller; + + +inline void StringImport(CopiedString& self, const char* value) +{ + self = value; +} +typedef ReferenceCaller1 StringImportCaller; +inline void StringExport(CopiedString& self, const StringImportCallback& importCallback) +{ + importCallback(self.c_str()); +} +typedef ReferenceCaller1 StringExportCaller; + + +struct DLG_DATA +{ + virtual void release() = 0; + virtual void importData() const = 0; + virtual void exportData() const = 0; +}; + +typedef struct _GtkWindow GtkWindow; +typedef struct _GtkToggleButton GtkToggleButton; +typedef struct _GtkRadioButton GtkRadioButton; +typedef struct _GtkSpinButton GtkSpinButton; +typedef struct _GtkComboBox GtkComboBox; +typedef struct _GtkEntry GtkEntry; +typedef struct _GtkAdjustment GtkAdjustment; + +template +class CallbackDialogData; + +typedef std::list DialogDataList; + +class Dialog +{ + GtkWindow* m_window; + DialogDataList m_data; +public: + ModalDialog m_modal; + GtkWindow* m_parent; + + Dialog(); + virtual ~Dialog(); + + /*! + start modal dialog box + you need to use AddModalButton to select eIDOK eIDCANCEL buttons + */ + EMessageBoxReturn DoModal(); + void EndModal (EMessageBoxReturn code); + virtual GtkWindow* BuildDialog() = 0; + virtual void exportData(); + virtual void importData(); + virtual void PreModal() { }; + virtual void PostModal (EMessageBoxReturn code) { }; + virtual void ShowDlg(); + virtual void HideDlg(); + void Create(); + void Destroy(); + GtkWindow* GetWidget() + { + return m_window; + } + const GtkWindow* GetWidget() const + { + return m_window; + } + + GtkWidget* addCheckBox(GtkWidget* vbox, const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback); + GtkWidget* addCheckBox(GtkWidget* vbox, const char* name, const char* flag, bool& data); + void addCombo(GtkWidget* vbox, const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + void addCombo(GtkWidget* vbox, const char* name, int& data, StringArrayRange values); + void addSlider(GtkWidget* vbox, const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment); + void addRadio(GtkWidget* vbox, const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + void addRadio(GtkWidget* vbox, const char* name, int& data, StringArrayRange names); + void addRadioIcons(GtkWidget* vbox, const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + void addRadioIcons(GtkWidget* vbox, const char* name, int& data, StringArrayRange icons); + GtkWidget* addIntEntry(GtkWidget* vbox, const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + GtkWidget* addEntry(GtkWidget* vbox, const char* name, int& data) + { + return addIntEntry(vbox, name, IntImportCaller(data), IntExportCaller(data)); + } + GtkWidget* addSizeEntry(GtkWidget* vbox, const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback); + GtkWidget* addEntry(GtkWidget* vbox, const char* name, std::size_t& data) + { + return addSizeEntry(vbox, name, SizeImportCaller(data), SizeExportCaller(data)); + } + GtkWidget* addFloatEntry(GtkWidget* vbox, const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); + GtkWidget* addEntry(GtkWidget* vbox, const char* name, float& data) + { + return addFloatEntry(vbox, name, FloatImportCaller(data), FloatExportCaller(data)); + } + GtkWidget* addPathEntry(GtkWidget* vbox, const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback); + GtkWidget* addPathEntry(GtkWidget* vbox, const char* name, CopiedString& data, bool directory); + GtkWidget* addSpinner(GtkWidget* vbox, const char* name, int& data, double value, double lower, double upper); + GtkWidget* addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + GtkWidget* addSpinner(GtkWidget* vbox, const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); + +protected: + + void AddBoolToggleData(GtkToggleButton& object, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback); + void AddIntRadioData(GtkRadioButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + void AddTextEntryData(GtkEntry& object, const StringImportCallback& importCallback, const StringExportCallback& exportCallback); + void AddIntEntryData(GtkEntry& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + void AddSizeEntryData(GtkEntry& object, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback); + void AddFloatEntryData(GtkEntry& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); + void AddFloatSpinnerData(GtkSpinButton& object, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback); + void AddIntSpinnerData(GtkSpinButton& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + void AddIntAdjustmentData(GtkAdjustment& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + void AddIntComboData(GtkComboBox& object, const IntImportCallback& importCallback, const IntExportCallback& exportCallback); + + void AddDialogData(GtkToggleButton& object, bool& data); + void AddDialogData(GtkRadioButton& object, int& data); + void AddDialogData(GtkEntry& object, CopiedString& data); + void AddDialogData(GtkEntry& object, int& data); + void AddDialogData(GtkEntry& object, std::size_t& data); + void AddDialogData(GtkEntry& object, float& data); + void AddDialogData(GtkSpinButton& object, float& data); + void AddDialogData(GtkSpinButton& object, int& data); + void AddDialogData(GtkAdjustment& object, int& data); + void AddDialogData(GtkComboBox& object, int& data); +}; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/eclass.cpp b/misc/mediasource/netradiant-src/radiant/eclass.cpp new file mode 100644 index 00000000..edbf4156 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass.cpp @@ -0,0 +1,414 @@ +/* +Copyright (C) 1999-2006 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 "eclass.h" + +#include "debugging/debugging.h" + +#include + +#include "ifilesystem.h" + +#include "string/string.h" +#include "eclasslib.h" +#include "os/path.h" +#include "os/dir.h" +#include "stream/stringstream.h" +#include "moduleobservers.h" + +#include "cmdlib.h" + +#include "preferences.h" +#include "mainframe.h" + + +namespace +{ + typedef std::map EntityClasses; + EntityClasses g_entityClasses; + EntityClass *eclass_bad = 0; + char eclass_directory[1024]; + typedef std::map ListAttributeTypes; + ListAttributeTypes g_listTypes; +} + +EClassModules& EntityClassManager_getEClassModules(); + +/*! +implementation of the EClass manager API +*/ + +void CleanEntityList(EntityClasses& entityClasses) +{ + for(EntityClasses::iterator i = entityClasses.begin(); i != entityClasses.end(); ++i) + { + (*i).second->free((*i).second); + } + entityClasses.clear(); +} + +void Eclass_Clear() +{ + CleanEntityList(g_entityClasses); + g_listTypes.clear(); +} + +EntityClass* EClass_InsertSortedList(EntityClasses& entityClasses, EntityClass *entityClass) +{ + std::pair result = entityClasses.insert(EntityClasses::value_type(entityClass->name(), entityClass)); + if(!result.second) + { + entityClass->free(entityClass); + } + return (*result.first).second; +} + +EntityClass* Eclass_InsertAlphabetized (EntityClass *e) +{ + return EClass_InsertSortedList(g_entityClasses, e); +} + +void Eclass_forEach(EntityClassVisitor& visitor) +{ + for(EntityClasses::iterator i = g_entityClasses.begin(); i != g_entityClasses.end(); ++i) + { + visitor.visit((*i).second); + } +} + + +class RadiantEclassCollector : public EntityClassCollector +{ +public: + void insert(EntityClass* eclass) + { + Eclass_InsertAlphabetized(eclass); + } + void insert(const char* name, const ListAttributeType& list) + { + g_listTypes.insert(ListAttributeTypes::value_type(name, list)); + } +}; + +RadiantEclassCollector g_collector; + +const ListAttributeType* EntityClass_findListType(const char* name) +{ + ListAttributeTypes::iterator i = g_listTypes.find(name); + if(i != g_listTypes.end()) + { + return &(*i).second; + } + return 0; +} + + +class EntityClassFilterMode +{ +public: + bool filter_mp_sp; + const char* mp_ignore_prefix; + const char* sp_ignore_prefix; + + EntityClassFilterMode() : + filter_mp_sp(!string_empty(g_pGameDescription->getKeyValue("eclass_filter_gamemode"))), + mp_ignore_prefix(g_pGameDescription->getKeyValue("eclass_sp_prefix")), + sp_ignore_prefix(g_pGameDescription->getKeyValue("eclass_mp_prefix")) + { + if(string_empty(mp_ignore_prefix)) + { + mp_ignore_prefix = "sp_"; + } + if(string_empty(sp_ignore_prefix)) + { + sp_ignore_prefix = "mp_"; + } + } +}; + +class EntityClassesLoadFile +{ + const EntityClassScanner& scanner; + const char* m_directory; +public: + EntityClassesLoadFile(const EntityClassScanner& scanner, const char* directory) : scanner(scanner), m_directory(directory) + { + } + void operator()(const char* name) const + { + EntityClassFilterMode filterMode; + + if(filterMode.filter_mp_sp) + { + if(string_empty(GlobalRadiant().getGameMode()) || string_equal(GlobalRadiant().getGameMode(), "sp")) + { + if(string_equal_n(name, filterMode.sp_ignore_prefix, strlen(filterMode.sp_ignore_prefix))) + { + globalOutputStream() << "Ignoring '" << name << "'\n"; + return; + } + } + else + { + if(string_equal_n(name, filterMode.mp_ignore_prefix, strlen(filterMode.mp_ignore_prefix))) + { + globalOutputStream() << "Ignoring '" << name << "'\n"; + return; + } + } + } + + // for a given name, we grab the first .def in the vfs + // this allows to override baseq3/scripts/entities.def for instance + StringOutputStream relPath(256); + relPath << m_directory << name; + + scanner.scanFile(g_collector, relPath.c_str()); + } +}; + +struct PathLess +{ + bool operator()(const CopiedString& path, const CopiedString& other) const + { + return path_less(path.c_str(), other.c_str()); + } +}; + +typedef std::map Paths; + +class PathsInsert +{ + Paths& m_paths; + const char* m_directory; +public: + PathsInsert(Paths& paths, const char* directory) : m_paths(paths), m_directory(directory) + { + } + void operator()(const char* name) const + { + m_paths.insert(Paths::value_type(name, m_directory)); + } +}; + + +void EntityClassQuake3_constructDirectory(const char* directory, const char* extension, Paths& paths) +{ + globalOutputStream() << "EntityClass: searching " << makeQuoted(directory) << " for *." << extension << '\n'; + Directory_forEach(directory, matchFileExtension(extension, PathsInsert(paths, directory))); +} + + +void EntityClassQuake3_Construct() +{ + StringOutputStream baseDirectory(256); + StringOutputStream gameDirectory(256); + const char* basegame = GlobalRadiant().getRequiredGameDescriptionKeyValue("basegame"); + const char* gamename = GlobalRadiant().getGameName(); + baseDirectory << GlobalRadiant().getGameToolsPath() << basegame << '/'; + gameDirectory << GlobalRadiant().getGameToolsPath() << gamename << '/'; + + class LoadEntityDefinitionsVisitor : public EClassModules::Visitor + { + const char* baseDirectory; + const char* gameDirectory; + public: + LoadEntityDefinitionsVisitor(const char* baseDirectory, const char* gameDirectory) + : baseDirectory(baseDirectory), gameDirectory(gameDirectory) + { + } + void visit(const char* name, const EntityClassScanner& table) const + { + Paths paths; + EntityClassQuake3_constructDirectory(baseDirectory, table.getExtension(), paths); + if(!string_equal(baseDirectory, gameDirectory)) + { + EntityClassQuake3_constructDirectory(gameDirectory, table.getExtension(), paths); + } + + for(Paths::iterator i = paths.begin(); i != paths.end(); ++i) + { + EntityClassesLoadFile(table, (*i).second)((*i).first.c_str()); + } + } + }; + + EntityClassManager_getEClassModules().foreachModule(LoadEntityDefinitionsVisitor(baseDirectory.c_str(), gameDirectory.c_str())); +} + +EntityClass *Eclass_ForName(const char *name, bool has_brushes) +{ + ASSERT_NOTNULL(name); + + if(string_empty(name)) + { + return eclass_bad; + } + + EntityClasses::iterator i = g_entityClasses.find(name); + if(i != g_entityClasses.end() && string_equal((*i).first, name)) + { + return (*i).second; + } + + EntityClass* e = EntityClass_Create_Default(name, has_brushes); + return Eclass_InsertAlphabetized(e); +} + +class EntityClassQuake3 : public ModuleObserver +{ + std::size_t m_unrealised; + ModuleObservers m_observers; +public: + EntityClassQuake3() : m_unrealised(4) + { + } + void realise() + { + if(--m_unrealised == 0) + { + //globalOutputStream() << "Entity Classes: realise\n"; + EntityClassQuake3_Construct(); + m_observers.realise(); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + m_observers.unrealise(); + //globalOutputStream() << "Entity Classes: unrealise\n"; + Eclass_Clear(); + } + } + void attach(ModuleObserver& observer) + { + m_observers.attach(observer); + } + void detach(ModuleObserver& observer) + { + m_observers.detach(observer); + } +}; + +EntityClassQuake3 g_EntityClassQuake3; + +void EntityClass_attach(ModuleObserver& observer) +{ + g_EntityClassQuake3.attach(observer); +} +void EntityClass_detach(ModuleObserver& observer) +{ + g_EntityClassQuake3.detach(observer); +} + +void EntityClass_realise() +{ + g_EntityClassQuake3.realise(); +} +void EntityClass_unrealise() +{ + g_EntityClassQuake3.unrealise(); +} + +void EntityClassQuake3_construct() +{ + // start by creating the default unknown eclass + eclass_bad = EClass_Create("UNKNOWN_CLASS", Vector3(0.0f, 0.5f, 0.0f), ""); + + EntityClass_realise(); +} + +void EntityClassQuake3_destroy() +{ + EntityClass_unrealise(); + + eclass_bad->free(eclass_bad); +} + +#include "modulesystem/modulesmap.h" + +class EntityClassQuake3Dependencies : + public GlobalRadiantModuleRef, + public GlobalFileSystemModuleRef, + public GlobalShaderCacheModuleRef +{ + EClassModulesRef m_eclass_modules; +public: + EntityClassQuake3Dependencies() : + m_eclass_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclasstype")) + { + } + EClassModules& getEClassModules() + { + return m_eclass_modules.get(); + } +}; + +class EclassManagerAPI +{ + EntityClassManager m_eclassmanager; +public: + typedef EntityClassManager Type; + STRING_CONSTANT(Name, "quake3"); + + EclassManagerAPI() + { + EntityClassQuake3_construct(); + + m_eclassmanager.findOrInsert = &Eclass_ForName; + m_eclassmanager.findListType = &EntityClass_findListType; + m_eclassmanager.forEach = &Eclass_forEach; + m_eclassmanager.attach = &EntityClass_attach; + m_eclassmanager.detach = &EntityClass_detach; + m_eclassmanager.realise = &EntityClass_realise; + m_eclassmanager.unrealise = &EntityClass_unrealise; + + GlobalRadiant().attachGameToolsPathObserver(g_EntityClassQuake3); + GlobalRadiant().attachGameModeObserver(g_EntityClassQuake3); + GlobalRadiant().attachGameNameObserver(g_EntityClassQuake3); + } + ~EclassManagerAPI() + { + GlobalRadiant().detachGameNameObserver(g_EntityClassQuake3); + GlobalRadiant().detachGameModeObserver(g_EntityClassQuake3); + GlobalRadiant().detachGameToolsPathObserver(g_EntityClassQuake3); + + EntityClassQuake3_destroy(); + } + EntityClassManager* getTable() + { + return &m_eclassmanager; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule EclassManagerModule; +typedef Static StaticEclassManagerModule; +StaticRegisterModule staticRegisterEclassManager(StaticEclassManagerModule::instance()); + +EClassModules& EntityClassManager_getEClassModules() +{ + return StaticEclassManagerModule::instance().getDependencies().getEClassModules(); +} + diff --git a/misc/mediasource/netradiant-src/radiant/eclass.h b/misc/mediasource/netradiant-src/radiant/eclass.h new file mode 100644 index 00000000..48d52ba3 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_ECLASS_H) +#define INCLUDED_ECLASS_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/eclass_def.cpp b/misc/mediasource/netradiant-src/radiant/eclass_def.cpp new file mode 100644 index 00000000..01341ed5 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_def.cpp @@ -0,0 +1,407 @@ +/* +Copyright (C) 1999-2006 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 "eclass_def.h" + +#include "iscriplib.h" +#include "ifilesystem.h" +#include "iarchive.h" + +#include "eclasslib.h" +#include "stream/stringstream.h" +#include "stream/textfilestream.h" +#include "modulesystem/moduleregistry.h" +#include "os/path.h" + +const char* EClass_GetExtension() +{ + return "def"; +} +void Eclass_ScanFile (EntityClassCollector& collector, const char *filename); + + +#include "modulesystem/singletonmodule.h" + +class EntityClassDefDependencies : public GlobalShaderCacheModuleRef, public GlobalScripLibModuleRef +{ +}; + +class EclassDefAPI +{ + EntityClassScanner m_eclassdef; +public: + typedef EntityClassScanner Type; + STRING_CONSTANT(Name, "def"); + + EclassDefAPI() + { + m_eclassdef.scanFile = &Eclass_ScanFile; + m_eclassdef.getExtension = &EClass_GetExtension; + } + EntityClassScanner* getTable() + { + return &m_eclassdef; + } +}; + +typedef SingletonModule EclassDefModule; +typedef Static StaticEclassDefModule; +StaticRegisterModule staticRegisterEclassDef(StaticEclassDefModule::instance()); + + +#include "string/string.h" + +#include + + +char com_token[1024]; +bool com_eof; + +/* +============== +COM_Parse + +Parse a token out of a string +============== +*/ +const char *COM_Parse (const char *data) +{ + int c; + int len; + + len = 0; + com_token[0] = 0; + + if (!data) + return 0; + +// skip whitespace +skipwhite: + while ( (c = *data) <= ' ') + { + if (c == 0) + { + com_eof = true; + return 0; // 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; +} + +const char* Get_COM_Token() +{ + return com_token; +} + + +const char *debugname; + +void setSpecialLoad(EntityClass *e, const char* pWhat, CopiedString& p) +{ + // Hydra: removed some amazingly bad cstring usage, whoever wrote that + // needs to be taken out and shot. + + const char *pText = 0; + const char *where = 0; + + where = strstr(e->comments(),pWhat); + if (!where) + return; + + pText = where + strlen(pWhat); + if (*pText == '\"') + pText++; + + where = strchr(pText,'\"'); + if (where) + { + p = StringRange(pText, where); + } + else + { + p = pText; + } +} + +#include "eclasslib.h" + +/* + +the classname, color triple, and bounding box are parsed out of comments +A ? size means take the exact brush size. + +/ *QUAKED (0 0 0) ? +/ *QUAKED (0 0 0) (-8 -8 -8) (8 8 8) + +Flag names can follow the size description: + +/ *QUAKED func_door (0 .5 .8) ? START_OPEN STONE_SOUND DOOR_DONT_LINK GOLD_KEY SILVER_KEY + +*/ + +EntityClass *Eclass_InitFromText (const char *text) +{ + EntityClass* e = Eclass_Alloc(); + e->free = &Eclass_Free; + + // grab the name + text = COM_Parse (text); + e->m_name = Get_COM_Token(); + debugname = e->name(); + + { + // grab the color, reformat as texture name + int r = sscanf (text," (%f %f %f)", &e->color[0], &e->color[1], &e->color[2]); + if (r != 3) + return e; + eclass_capture_state(e); + } + + while (*text != ')') + { + if (!*text) { + return 0; + } + text++; + } + text++; + + // get the size + text = COM_Parse (text); + if (Get_COM_Token()[0] == '(') + { // parse the size as two vectors + e->fixedsize = true; + int r = sscanf (text,"%f %f %f) (%f %f %f)", &e->mins[0], &e->mins[1], &e->mins[2], + &e->maxs[0], &e->maxs[1], &e->maxs[2]); + if (r != 6) { + return 0; + } + + for (int i=0 ; i<2 ; i++) + { + while (*text != ')') + { + if (!*text) { + return 0; + } + text++; + } + text++; + } + } + + char parms[256]; + // get the flags + { + // copy to the first /n + char* p = parms; + while (*text && *text != '\n') + *p++ = *text++; + *p = 0; + text++; + } + + { + // any remaining words are parm flags + const char* p = parms; + for (std::size_t i=0 ; iflagnames[i], Get_COM_Token()); + } + } + + e->m_comments = text; + + setSpecialLoad(e, "model=", e->m_modelpath); + StringOutputStream buffer(string_length(e->m_modelpath.c_str())); + buffer << PathCleaned(e->m_modelpath.c_str()); + e->m_modelpath = buffer.c_str(); + + if(!e->fixedsize) + { + EntityClass_insertAttribute(*e, "angle", EntityClassAttribute("direction", "Direction", "0")); + } + else + { + EntityClass_insertAttribute(*e, "angle", EntityClassAttribute("angle", "Yaw Angle", "0")); + } + EntityClass_insertAttribute(*e, "model", EntityClassAttribute("model", "Model")); + EntityClass_insertAttribute(*e, "noise", EntityClassAttribute("sound", "Sound")); + + return e; +} + +void Eclass_ScanFile (EntityClassCollector& collector, const char *filename) +{ + EntityClass *e; + + TextFileInputStream inputFile(filename); + if(inputFile.failed()) + { + globalErrorStream() << "ScanFile: " << filename << " not found\n"; + return; + } + globalOutputStream() << "ScanFile: " << filename << "\n"; + + enum EParserState + { + eParseDefault, + eParseSolidus, + eParseComment, + eParseQuakeED, + eParseEntityClass, + eParseEntityClassEnd, + } state = eParseDefault; + const char* quakeEd = "QUAKED"; + const char* p = 0; + StringBuffer buffer; + SingleCharacterInputStream bufferedInput(inputFile); + for(;;) + { + char c; + if(!bufferedInput.readChar(c)) + { + break; + } + + switch(state) + { + case eParseDefault: + if(c == '/') + { + state = eParseSolidus; + } + break; + case eParseSolidus: + if(c == '/') + { + state = eParseComment; + } + else if(c == '*') + { + p = quakeEd; + state = eParseQuakeED; + } + break; + case eParseComment: + if(c == '\n') + { + state = eParseDefault; + } + break; + case eParseQuakeED: + if(c == *p) + { + if(*(++p) == '\0') + { + state = eParseEntityClass; + } + } + else + { + state = eParseDefault; + } + break; + case eParseEntityClass: + if(c == '*') + { + state = eParseEntityClassEnd; + } + else + { + buffer.push_back(c); + } + break; + case eParseEntityClassEnd: + if(c == '/') + { + e = Eclass_InitFromText(buffer.c_str()); + state = eParseDefault; + if (e) + collector.insert(e); + else + globalErrorStream() << "Error parsing: " << debugname << " in " << filename << "\n"; + + buffer.clear(); + state = eParseDefault; + } + else + { + buffer.push_back('*'); + buffer.push_back(c); + state = eParseEntityClass; + } + break; + } + } +} diff --git a/misc/mediasource/netradiant-src/radiant/eclass_def.h b/misc/mediasource/netradiant-src/radiant/eclass_def.h new file mode 100644 index 00000000..23a5ef4d --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_def.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_ECLASS_DEF_H) +#define INCLUDED_ECLASS_DEF_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/eclass_doom3.cpp b/misc/mediasource/netradiant-src/radiant/eclass_doom3.cpp new file mode 100644 index 00000000..217c4ec5 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_doom3.cpp @@ -0,0 +1,929 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "eclass_doom3.h" + +#include "debugging/debugging.h" + +#include + +#include "ifilesystem.h" +#include "iscriplib.h" +#include "iarchive.h" +#include "qerplugin.h" + +#include "generic/callback.h" +#include "string/string.h" +#include "eclasslib.h" +#include "os/path.h" +#include "os/dir.h" +#include "stream/stringstream.h" +#include "moduleobservers.h" +#include "stringio.h" + +class RawString +{ + const char* m_value; +public: + RawString(const char* value) : m_value(value) + { + } + const char* c_str() const + { + return m_value; + } +}; + +inline bool operator<(const RawString& self, const RawString& other) +{ + return string_less_nocase(self.c_str(), other.c_str()); +} + +typedef std::map EntityClasses; +EntityClasses g_EntityClassDoom3_classes; +EntityClass *g_EntityClassDoom3_bad = 0; + + +void EntityClassDoom3_clear() +{ + for(EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i) + { + (*i).second->free((*i).second); + } + g_EntityClassDoom3_classes.clear(); +} + +// entityClass will be inserted only if another of the same name does not already exist. +// if entityClass was inserted, the same object is returned, otherwise the already-existing object is returned. +EntityClass* EntityClassDoom3_insertUnique(EntityClass* entityClass) +{ + return (*g_EntityClassDoom3_classes.insert(EntityClasses::value_type(entityClass->name(), entityClass)).first).second; +} + +void EntityClassDoom3_forEach(EntityClassVisitor& visitor) +{ + for(EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i) + { + visitor.visit((*i).second); + } +} + +inline void printParseError(const char* message) +{ + globalErrorStream() << message; +} + +#define PARSE_RETURN_FALSE_IF_FAIL(expression) if(!(expression)) { printParseError(FILE_LINE "\nparse failed: " #expression "\n"); return false; } else + +bool EntityClassDoom3_parseToken(Tokeniser& tokeniser) +{ + const char* token = tokeniser.getToken(); + PARSE_RETURN_FALSE_IF_FAIL(token != 0); + return true; +} + +bool EntityClassDoom3_parseToken(Tokeniser& tokeniser, const char* string) +{ + const char* token = tokeniser.getToken(); + PARSE_RETURN_FALSE_IF_FAIL(token != 0); + return string_equal(token, string); +} + +bool EntityClassDoom3_parseString(Tokeniser& tokeniser, const char*& s) +{ + const char* token = tokeniser.getToken(); + PARSE_RETURN_FALSE_IF_FAIL(token != 0); + s = token; + return true; +} + +bool EntityClassDoom3_parseString(Tokeniser& tokeniser, CopiedString& s) +{ + const char* token = tokeniser.getToken(); + PARSE_RETURN_FALSE_IF_FAIL(token != 0); + s = token; + return true; +} + +bool EntityClassDoom3_parseString(Tokeniser& tokeniser, StringOutputStream& s) +{ + const char* token = tokeniser.getToken(); + PARSE_RETURN_FALSE_IF_FAIL(token != 0); + s << token; + return true; +} + +bool EntityClassDoom3_parseUnknown(Tokeniser& tokeniser) +{ + //const char* name = + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + + //globalOutputStream() << "parsing unknown block " << makeQuoted(name) << "\n"; + + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "{")); + tokeniser.nextLine(); + + std::size_t depth = 1; + for(;;) + { + const char* token; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); + if(string_equal(token, "}")) + { + if(--depth == 0) + { + tokeniser.nextLine(); + break; + } + } + else if(string_equal(token, "{")) + { + ++depth; + } + tokeniser.nextLine(); + } + return true; +} + + +class Model +{ +public: + bool m_resolved; + CopiedString m_mesh; + CopiedString m_skin; + CopiedString m_parent; + typedef std::map Anims; + Anims m_anims; + Model() : m_resolved(false) + { + } +}; + +typedef std::map Models; + +Models g_models; + +void Model_resolveInheritance(const char* name, Model& model) +{ + if(model.m_resolved == false) + { + model.m_resolved = true; + + if(!string_empty(model.m_parent.c_str())) + { + Models::iterator i = g_models.find(model.m_parent); + if(i == g_models.end()) + { + globalErrorStream() << "model " << name << " inherits unknown model " << model.m_parent.c_str() << "\n"; + } + else + { + Model_resolveInheritance((*i).first.c_str(), (*i).second); + model.m_mesh = (*i).second.m_mesh; + model.m_skin = (*i).second.m_skin; + } + } + } +} + +bool EntityClassDoom3_parseModel(Tokeniser& tokeniser) +{ + const char* name; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, name)); + + Model& model = g_models[name]; + + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "{")); + tokeniser.nextLine(); + + for(;;) + { + const char* parameter; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, parameter)); + if(string_equal(parameter, "}")) + { + tokeniser.nextLine(); + break; + } + else if(string_equal(parameter, "inherit")) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, model.m_parent)); + tokeniser.nextLine(); + } + else if(string_equal(parameter, "remove")) + { + //const char* remove = + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + tokeniser.nextLine(); + } + else if(string_equal(parameter, "mesh")) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, model.m_mesh)); + tokeniser.nextLine(); + } + else if(string_equal(parameter, "skin")) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, model.m_skin)); + tokeniser.nextLine(); + } + else if(string_equal(parameter, "offset")) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "(")); + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, ")")); + tokeniser.nextLine(); + } + else if(string_equal(parameter, "channel")) + { + //const char* channelName = + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "(")); + for(;;) + { + const char* end; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, end)); + if(string_equal(end, ")")) + { + tokeniser.nextLine(); + break; + } + } + } + else if(string_equal(parameter, "anim")) + { + CopiedString animName; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, animName)); + const char* animFile; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, animFile)); + model.m_anims.insert(Model::Anims::value_type(animName, animFile)); + + const char* token; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); + + while(string_equal(token, ",")) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, animFile)); + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); + } + + if(string_equal(token, "{")) + { + for(;;) + { + const char* end; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, end)); + if(string_equal(end, "}")) + { + tokeniser.nextLine(); + break; + } + tokeniser.nextLine(); + } + } + else + { + tokeniser.ungetToken(); + } + } + else + { + globalErrorStream() << "unknown model parameter: " << makeQuoted(parameter) << "\n"; + return false; + } + tokeniser.nextLine(); + } + return true; +} + +inline bool char_isSpaceOrTab(char c) +{ + return c == ' ' || c == '\t'; +} + +inline bool char_isNotSpaceOrTab(char c) +{ + return !char_isSpaceOrTab(c); +} + +template +inline const char* string_find_if(const char* string, Predicate predicate) +{ + for(; *string != 0; ++string) + { + if(predicate(*string)) + { + return string; + } + } + return string; +} + +inline const char* string_findFirstSpaceOrTab(const char* string) +{ + return string_find_if(string, char_isSpaceOrTab); +} + +inline const char* string_findFirstNonSpaceOrTab(const char* string) +{ + return string_find_if(string, char_isNotSpaceOrTab); +} + + +static bool EntityClass_parse(EntityClass& entityClass, Tokeniser& tokeniser) +{ + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, entityClass.m_name)); + + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser, "{")); + tokeniser.nextLine(); + + StringOutputStream usage(256); + StringOutputStream description(256); + CopiedString* currentDescription = 0; + StringOutputStream* currentString = 0; + + for(;;) + { + const char* key; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, key)); + + const char* last = string_findFirstSpaceOrTab(key); + CopiedString first(StringRange(key, last)); + + if(!string_empty(last)) + { + last = string_findFirstNonSpaceOrTab(last); + } + + if(currentString != 0 && string_equal(key, "\\")) + { + tokeniser.nextLine(); + *currentString << " "; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, *currentString)); + continue; + } + + if(currentDescription != 0) + { + *currentDescription = description.c_str(); + description.clear(); + currentDescription = 0; + } + currentString = 0; + + if(string_equal(key, "}")) + { + tokeniser.nextLine(); + break; + } + else if(string_equal(key, "model")) + { + const char* token; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); + entityClass.fixedsize = true; + StringOutputStream buffer(256); + buffer << PathCleaned(token); + entityClass.m_modelpath = buffer.c_str(); + } + else if(string_equal(key, "editor_color")) + { + const char* value; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); + if(!string_empty(value)) + { + entityClass.colorSpecified = true; + bool success = string_parse_vector3(value, entityClass.color); + ASSERT_MESSAGE(success, "editor_color: parse error"); + } + } + else if(string_equal(key, "editor_ragdoll")) + { + //bool ragdoll = atoi(tokeniser.getToken()) != 0; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + } + else if(string_equal(key, "editor_mins")) + { + entityClass.sizeSpecified = true; + const char* value; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); + if(!string_empty(value) && !string_equal(value, "?")) + { + entityClass.fixedsize = true; + bool success = string_parse_vector3(value, entityClass.mins); + ASSERT_MESSAGE(success, "editor_mins: parse error"); + } + } + else if(string_equal(key, "editor_maxs")) + { + entityClass.sizeSpecified = true; + const char* value; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); + if(!string_empty(value) && !string_equal(value, "?")) + { + entityClass.fixedsize = true; + bool success = string_parse_vector3(value, entityClass.maxs); + ASSERT_MESSAGE(success, "editor_maxs: parse error"); + } + } + else if(string_equal(key, "editor_usage")) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, usage)); + currentString = &usage; + } + else if(string_equal_n(key, "editor_usage", 12)) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, usage)); + currentString = &usage; + } + else if(string_equal(key, "editor_rotatable") + || string_equal(key, "editor_showangle") + || string_equal(key, "editor_showangles") // typo? in prey movables.def + || string_equal(key, "editor_mover") + || string_equal(key, "editor_model") + || string_equal(key, "editor_material") + || string_equal(key, "editor_combatnode") + || (!string_empty(last) && string_equal(first.c_str(), "editor_gui")) + || string_equal_n(key, "editor_copy", 11)) + { + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + } + else if(!string_empty(last) && (string_equal(first.c_str(), "editor_var") || string_equal(first.c_str(), "editor_string"))) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "string"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(!string_empty(last) && string_equal(first.c_str(), "editor_float")) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "string"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(!string_empty(last) && string_equal(first.c_str(), "editor_snd")) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "sound"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(!string_empty(last) && string_equal(first.c_str(), "editor_bool")) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "boolean"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(!string_empty(last) && string_equal(first.c_str(), "editor_int")) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "integer"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(!string_empty(last) && string_equal(first.c_str(), "editor_model")) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "model"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(!string_empty(last) && string_equal(first.c_str(), "editor_color")) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "color"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(!string_empty(last) && (string_equal(first.c_str(), "editor_material") || string_equal(first.c_str(), "editor_mat"))) + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, last).second; + attribute.m_type = "shader"; + currentDescription = &attribute.m_description; + currentString = &description; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, description)); + } + else if(string_equal(key, "inherit")) + { + entityClass.inheritanceResolved = false; + ASSERT_MESSAGE(entityClass.m_parent.empty(), "only one 'inherit' supported per entityDef"); + const char* token; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, token)); + entityClass.m_parent.push_back(token); + } + // begin quake4-specific keys + else if(string_equal(key, "editor_targetonsel")) + { + //const char* value = + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + } + else if(string_equal(key, "editor_menu")) + { + //const char* value = + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + } + else if(string_equal(key, "editor_ignore")) + { + //const char* value = + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + } + // end quake4-specific keys + // begin ignore prey (unknown/unused?) entity keys + else if(string_equal(key, "editor_light") + || string_equal(key, "editor_def def_debrisspawner") + || string_equal(key, "editor_def def_drop") + || string_equal(key, "editor_def def_guihand") + || string_equal(key, "editor_def def_mine")) + { + //const char* value = + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseToken(tokeniser)); + } + // end ignore prey entity keys + else + { + CopiedString tmp(key); + ASSERT_MESSAGE(!string_equal_n(key, "editor_", 7), "unsupported editor key: " << makeQuoted(key)); + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, key).second; + attribute.m_type = "string"; + const char* value; + PARSE_RETURN_FALSE_IF_FAIL(EntityClassDoom3_parseString(tokeniser, value)); + if(string_equal(value, "}")) // hack for quake4 powerups.def bug + { + globalErrorStream() << "entityDef " << makeQuoted(entityClass.m_name.c_str()) << " key " << makeQuoted(tmp.c_str()) << " has no value\n"; + break; + } + else + { + attribute.m_value = value; + } + } + tokeniser.nextLine(); + } + + entityClass.m_comments = usage.c_str(); + + if(string_equal(entityClass.m_name.c_str(), "light")) + { + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "light_radius").second; + attribute.m_type = "vector3"; + attribute.m_value = "300 300 300"; + } + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "light_center").second; + attribute.m_type = "vector3"; + } + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "noshadows").second; + attribute.m_type = "boolean"; + attribute.m_value = "0"; + } + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "nospecular").second; + attribute.m_type = "boolean"; + attribute.m_value = "0"; + } + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "nodiffuse").second; + attribute.m_type = "boolean"; + attribute.m_value = "0"; + } + { + EntityClassAttribute& attribute = EntityClass_insertAttribute(entityClass, "falloff").second; + attribute.m_type = "real"; + } + } + + return true; +} + +bool EntityClassDoom3_parseEntityDef(Tokeniser& tokeniser) +{ + EntityClass* entityClass = Eclass_Alloc(); + entityClass->free = &Eclass_Free; + + if(!EntityClass_parse(*entityClass, tokeniser)) + { + eclass_capture_state(entityClass); // finish constructing the entity so that it can be destroyed cleanly. + entityClass->free(entityClass); + return false; + } + + EntityClass* inserted = EntityClassDoom3_insertUnique(entityClass); + if(inserted != entityClass) + { + globalErrorStream() << "entityDef " << entityClass->name() << " is already defined, second definition ignored\n"; + eclass_capture_state(entityClass); // finish constructing the entity so that it can be destroyed cleanly. + entityClass->free(entityClass); + } + return true; +} + +bool EntityClassDoom3_parseBlock(Tokeniser& tokeniser, const char* blockType) +{ + if(string_equal(blockType, "entityDef")) + { + return EntityClassDoom3_parseEntityDef(tokeniser); + } + else if(string_equal(blockType, "model")) + { + return EntityClassDoom3_parseModel(tokeniser); + } + else + { + return EntityClassDoom3_parseUnknown(tokeniser); + } +} + +bool EntityClassDoom3_parse(TextInputStream& inputStream, const char* filename) +{ + Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser(inputStream); + + tokeniser.nextLine(); + + for(;;) + { + const char* blockType = tokeniser.getToken(); + if(blockType == 0) + { + return true; + } + CopiedString tmp(blockType); + if(!EntityClassDoom3_parseBlock(tokeniser, tmp.c_str())) + { + globalErrorStream() << GlobalFileSystem().findFile(filename) << filename << ":" << (unsigned int)tokeniser.getLine() << ": " << tmp.c_str() << " parse failed, skipping rest of file\n"; + return false; + } + } + + tokeniser.release(); +} + + +void EntityClassDoom3_loadFile(const char* filename) +{ + globalOutputStream() << "parsing entity classes from " << makeQuoted(filename) << "\n"; + + StringOutputStream fullname(256); + fullname << "def/" << filename; + + ArchiveTextFile* file = GlobalFileSystem().openTextFile(fullname.c_str()); + if(file != 0) + { + EntityClassDoom3_parse(file->getInputStream(), fullname.c_str()); + file->release(); + } +} + +EntityClass* EntityClassDoom3_findOrInsert(const char *name, bool has_brushes) +{ + ASSERT_NOTNULL(name); + + if(string_empty(name)) + { + return g_EntityClassDoom3_bad; + } + + EntityClasses::iterator i = g_EntityClassDoom3_classes.find(name); + if(i != g_EntityClassDoom3_classes.end() + //&& string_equal((*i).first, name) + ) + { + return (*i).second; + } + + EntityClass* e = EntityClass_Create_Default(name, has_brushes); + EntityClass* inserted = EntityClassDoom3_insertUnique(e); + ASSERT_MESSAGE(inserted == e, ""); + return inserted; +} + +const ListAttributeType* EntityClassDoom3_findListType(const char* name) +{ + return 0; +} + + +void EntityClass_resolveInheritance(EntityClass* derivedClass) +{ + if(derivedClass->inheritanceResolved == false) + { + derivedClass->inheritanceResolved = true; + EntityClasses::iterator i = g_EntityClassDoom3_classes.find(derivedClass->m_parent.front().c_str()); + if(i == g_EntityClassDoom3_classes.end()) + { + globalErrorStream() << "failed to find entityDef " << makeQuoted(derivedClass->m_parent.front().c_str()) << " inherited by " << makeQuoted(derivedClass->m_name.c_str()) << "\n"; + } + else + { + EntityClass* parentClass = (*i).second; + EntityClass_resolveInheritance(parentClass); + if(!derivedClass->colorSpecified) + { + derivedClass->colorSpecified = parentClass->colorSpecified; + derivedClass->color = parentClass->color; + } + if(!derivedClass->sizeSpecified) + { + derivedClass->sizeSpecified = parentClass->sizeSpecified; + derivedClass->mins = parentClass->mins; + derivedClass->maxs = parentClass->maxs; + derivedClass->fixedsize = parentClass->fixedsize; + } + + for(EntityClassAttributes::iterator j = parentClass->m_attributes.begin(); j != parentClass->m_attributes.end(); ++j) + { + EntityClass_insertAttribute(*derivedClass, (*j).first.c_str(), (*j).second); + } + } + } +} + +class EntityClassDoom3 : public ModuleObserver +{ + std::size_t m_unrealised; + ModuleObservers m_observers; +public: + EntityClassDoom3() : m_unrealised(2) + { + } + void realise() + { + if(--m_unrealised == 0) + { + globalOutputStream() << "searching vfs directory " << makeQuoted("def") << " for *.def\n"; + GlobalFileSystem().forEachFile("def/", "def", FreeCaller1()); + + { + for(Models::iterator i = g_models.begin(); i != g_models.end(); ++i) + { + Model_resolveInheritance((*i).first.c_str(), (*i).second); + } + } + { + for(EntityClasses::iterator i = g_EntityClassDoom3_classes.begin(); i != g_EntityClassDoom3_classes.end(); ++i) + { + EntityClass_resolveInheritance((*i).second); + if(!string_empty((*i).second->m_modelpath.c_str())) + { + Models::iterator j = g_models.find((*i).second->m_modelpath); + if(j != g_models.end()) + { + (*i).second->m_modelpath = (*j).second.m_mesh; + (*i).second->m_skin = (*j).second.m_skin; + } + } + eclass_capture_state((*i).second); + + StringOutputStream usage(256); + + usage << "-------- NOTES --------\n"; + + if(!string_empty((*i).second->m_comments.c_str())) + { + usage << (*i).second->m_comments.c_str() << "\n"; + } + + usage << "\n-------- KEYS --------\n"; + + for(EntityClassAttributes::iterator j = (*i).second->m_attributes.begin(); j != (*i).second->m_attributes.end(); ++j) + { + const char* name = EntityClassAttributePair_getName(*j); + const char* description = EntityClassAttributePair_getDescription(*j); + if(!string_equal(name, description)) + { + usage << EntityClassAttributePair_getName(*j) << " : " << EntityClassAttributePair_getDescription(*j) << "\n"; + } + } + + (*i).second->m_comments = usage.c_str(); + } + } + + m_observers.realise(); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + m_observers.unrealise(); + EntityClassDoom3_clear(); + } + } + void attach(ModuleObserver& observer) + { + m_observers.attach(observer); + } + void detach(ModuleObserver& observer) + { + m_observers.detach(observer); + } +}; + +EntityClassDoom3 g_EntityClassDoom3; + +void EntityClassDoom3_attach(ModuleObserver& observer) +{ + g_EntityClassDoom3.attach(observer); +} +void EntityClassDoom3_detach(ModuleObserver& observer) +{ + g_EntityClassDoom3.detach(observer); +} + +void EntityClassDoom3_realise() +{ + g_EntityClassDoom3.realise(); +} +void EntityClassDoom3_unrealise() +{ + g_EntityClassDoom3.unrealise(); +} + +void EntityClassDoom3_construct() +{ + GlobalFileSystem().attach(g_EntityClassDoom3); + + // start by creating the default unknown eclass + g_EntityClassDoom3_bad = EClass_Create("UNKNOWN_CLASS", Vector3(0.0f, 0.5f, 0.0f), ""); + + EntityClassDoom3_realise(); +} + +void EntityClassDoom3_destroy() +{ + EntityClassDoom3_unrealise(); + + g_EntityClassDoom3_bad->free(g_EntityClassDoom3_bad); + + GlobalFileSystem().detach(g_EntityClassDoom3); +} + +class EntityClassDoom3Dependencies : public GlobalFileSystemModuleRef, public GlobalShaderCacheModuleRef +{ +}; + +class EntityClassDoom3API +{ + EntityClassManager m_eclassmanager; +public: + typedef EntityClassManager Type; + STRING_CONSTANT(Name, "doom3"); + + EntityClassDoom3API() + { + EntityClassDoom3_construct(); + + m_eclassmanager.findOrInsert = &EntityClassDoom3_findOrInsert; + m_eclassmanager.findListType = &EntityClassDoom3_findListType; + m_eclassmanager.forEach = &EntityClassDoom3_forEach; + m_eclassmanager.attach = &EntityClassDoom3_attach; + m_eclassmanager.detach = &EntityClassDoom3_detach; + m_eclassmanager.realise = &EntityClassDoom3_realise; + m_eclassmanager.unrealise = &EntityClassDoom3_unrealise; + } + ~EntityClassDoom3API() + { + EntityClassDoom3_destroy(); + } + EntityClassManager* getTable() + { + return &m_eclassmanager; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule EntityClassDoom3Module; +typedef Static StaticEntityClassDoom3Module; +StaticRegisterModule staticRegisterEntityClassDoom3(StaticEntityClassDoom3Module::instance()); diff --git a/misc/mediasource/netradiant-src/radiant/eclass_doom3.h b/misc/mediasource/netradiant-src/radiant/eclass_doom3.h new file mode 100644 index 00000000..7c8169cb --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_doom3.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ECLASS_DOOM3_H) +#define INCLUDED_ECLASS_DOOM3_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/eclass_fgd.cpp b/misc/mediasource/netradiant-src/radiant/eclass_fgd.cpp new file mode 100644 index 00000000..6d5fb663 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_fgd.cpp @@ -0,0 +1,807 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "eclass_fgd.h" + +#include "debugging/debugging.h" + +#include + +#include "ifilesystem.h" +#include "iscriplib.h" +#include "qerplugin.h" + +#include "string/string.h" +#include "eclasslib.h" +#include "os/path.h" +#include "os/dir.h" +#include "stream/stringstream.h" +#include "moduleobservers.h" +#include "stringio.h" +#include "stream/textfilestream.h" + +namespace +{ + typedef std::map EntityClasses; + EntityClasses g_EntityClassFGD_classes; + typedef std::map BaseClasses; + BaseClasses g_EntityClassFGD_bases; + EntityClass *g_EntityClassFGD_bad = 0; + typedef std::map ListAttributeTypes; + ListAttributeTypes g_listTypesFGD; +} + + +void EntityClassFGD_clear() +{ + for(BaseClasses::iterator i = g_EntityClassFGD_bases.begin(); i != g_EntityClassFGD_bases.end(); ++i) + { + (*i).second->free((*i).second); + } + g_EntityClassFGD_bases.clear(); + g_listTypesFGD.clear(); +} + +EntityClass* EntityClassFGD_insertUniqueBase(EntityClass* entityClass) +{ + std::pair result = g_EntityClassFGD_bases.insert(BaseClasses::value_type(entityClass->name(), entityClass)); + if(!result.second) + { + globalErrorStream() << "duplicate base class: " << makeQuoted(entityClass->name()) << "\n"; + //eclass_capture_state(entityClass); + //entityClass->free(entityClass); + } + return (*result.first).second; +} + +EntityClass* EntityClassFGD_insertUnique(EntityClass* entityClass) +{ + EntityClassFGD_insertUniqueBase(entityClass); + std::pair result = g_EntityClassFGD_classes.insert(EntityClasses::value_type(entityClass->name(), entityClass)); + if(!result.second) + { + globalErrorStream() << "duplicate entity class: " << makeQuoted(entityClass->name()) << "\n"; + eclass_capture_state(entityClass); + entityClass->free(entityClass); + } + return (*result.first).second; +} + +void EntityClassFGD_forEach(EntityClassVisitor& visitor) +{ + for(EntityClasses::iterator i = g_EntityClassFGD_classes.begin(); i != g_EntityClassFGD_classes.end(); ++i) + { + visitor.visit((*i).second); + } +} + +inline bool EntityClassFGD_parseToken(Tokeniser& tokeniser, const char* token) +{ + return string_equal(tokeniser.getToken(), token); +} + +#define PARSE_ERROR "error parsing entity class definition" + +void EntityClassFGD_parseSplitString(Tokeniser& tokeniser, CopiedString& string) +{ + StringOutputStream buffer(256); + for(;;) + { + buffer << tokeniser.getToken(); + if(!string_equal(tokeniser.getToken(), "+")) + { + tokeniser.ungetToken(); + string = buffer.c_str(); + return; + } + } +} + +void EntityClassFGD_parseClass(Tokeniser& tokeniser, bool fixedsize, bool isBase) +{ + EntityClass* entityClass = Eclass_Alloc(); + entityClass->free = &Eclass_Free; + entityClass->fixedsize = fixedsize; + entityClass->inheritanceResolved = false; + entityClass->mins = Vector3(-8, -8, -8); + entityClass->maxs = Vector3(8, 8, 8); + + for(;;) + { + const char* property = tokeniser.getToken(); + if(string_equal(property, "=")) + { + break; + } + else if(string_equal(property, "base")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + for(;;) + { + const char* base = tokeniser.getToken(); + if(string_equal(base, ")")) + { + break; + } + else if(!string_equal(base, ",")) + { + entityClass->m_parent.push_back(base); + } + } + } + else if(string_equal(property, "size")) + { + entityClass->sizeSpecified = true; + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + Tokeniser_getFloat(tokeniser, entityClass->mins.x()); + Tokeniser_getFloat(tokeniser, entityClass->mins.y()); + Tokeniser_getFloat(tokeniser, entityClass->mins.z()); + const char* token = tokeniser.getToken(); + if(string_equal(token, ",")) + { + Tokeniser_getFloat(tokeniser, entityClass->maxs.x()); + Tokeniser_getFloat(tokeniser, entityClass->maxs.y()); + Tokeniser_getFloat(tokeniser, entityClass->maxs.z()); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + else + { + entityClass->maxs = entityClass->mins; + vector3_negate(entityClass->mins); + ASSERT_MESSAGE(string_equal(token, ")"), ""); + } + } + else if(string_equal(property, "color")) + { + entityClass->colorSpecified = true; + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + Tokeniser_getFloat(tokeniser, entityClass->color.x()); + entityClass->color.x() /= 256.0; + Tokeniser_getFloat(tokeniser, entityClass->color.y()); + entityClass->color.y() /= 256.0; + Tokeniser_getFloat(tokeniser, entityClass->color.z()); + entityClass->color.z() /= 256.0; + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + else if(string_equal(property, "iconsprite")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + StringOutputStream buffer(256); + buffer << PathCleaned(tokeniser.getToken()); + entityClass->m_modelpath = buffer.c_str(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + else if(string_equal(property, "sprite") + || string_equal(property, "decal") + // hl2 below + || string_equal(property, "overlay") + || string_equal(property, "light") + || string_equal(property, "keyframe") + || string_equal(property, "animator") + || string_equal(property, "quadbounds")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + // hl2 below + else if(string_equal(property, "sphere") + || string_equal(property, "sweptplayerhull") + || string_equal(property, "studio") + || string_equal(property, "studioprop") + || string_equal(property, "lightprop") + || string_equal(property, "lightcone") + || string_equal(property, "sidelist")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + if(string_equal(tokeniser.getToken(), ")")) + { + tokeniser.ungetToken(); + } + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + else if(string_equal(property, "line") + || string_equal(property, "cylinder")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + //const char* r = + tokeniser.getToken(); + //const char* g = + tokeniser.getToken(); + //const char* b = + tokeniser.getToken(); + for(;;) + { + if(string_equal(tokeniser.getToken(), ")")) + { + tokeniser.ungetToken(); + break; + } + //const char* name = + tokeniser.getToken(); + } + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + else if(string_equal(property, "wirebox")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + //const char* mins = + tokeniser.getToken(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ","), PARSE_ERROR); + //const char* maxs = + tokeniser.getToken(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + else if(string_equal(property, "halfgridsnap")) + { + } + else + { + ERROR_MESSAGE(PARSE_ERROR); + } + } + + entityClass->m_name = tokeniser.getToken(); + + if(!isBase) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); + + EntityClassFGD_parseSplitString(tokeniser, entityClass->m_comments); + } + + tokeniser.nextLine(); + + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "["), PARSE_ERROR); + + tokeniser.nextLine(); + + for(;;) + { + CopiedString key = tokeniser.getToken(); + if(string_equal(key.c_str(), "]")) + { + tokeniser.nextLine(); + break; + } + + if(string_equal_nocase(key.c_str(), "input") + || string_equal_nocase(key.c_str(), "output")) + { + const char* name = tokeniser.getToken(); + if(!string_equal(name, "(")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + //const char* type = + tokeniser.getToken(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + const char* descriptionSeparator = tokeniser.getToken(); + if(string_equal(descriptionSeparator, ":")) + { + CopiedString description; + EntityClassFGD_parseSplitString(tokeniser, description); + } + else + { + tokeniser.ungetToken(); + } + tokeniser.nextLine(); + continue; + } + } + + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + CopiedString type = tokeniser.getToken(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + + if(string_equal_nocase(type.c_str(), "flags")) + { + EntityClassAttribute attribute; + + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "="), PARSE_ERROR); + tokeniser.nextLine(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "["), PARSE_ERROR); + tokeniser.nextLine(); + for(;;) + { + const char* flag = tokeniser.getToken(); + if(string_equal(flag, "]")) + { + tokeniser.nextLine(); + break; + } + else + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); + //const char* name = + tokeniser.getToken(); + { + const char* defaultSeparator = tokeniser.getToken(); + if(string_equal(defaultSeparator, ":")) + { + tokeniser.getToken(); + { + const char* descriptionSeparator = tokeniser.getToken(); + if(string_equal(descriptionSeparator, ":")) + { + EntityClassFGD_parseSplitString(tokeniser, attribute.m_description); + } + else + { + tokeniser.ungetToken(); + } + } + } + else + { + tokeniser.ungetToken(); + } + } + } + tokeniser.nextLine(); + } + EntityClass_insertAttribute(*entityClass, key.c_str(), attribute); + } + else if(string_equal_nocase(type.c_str(), "choices")) + { + EntityClassAttribute attribute; + + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); + attribute.m_name = tokeniser.getToken(); + const char* valueSeparator = tokeniser.getToken(); + if(string_equal(valueSeparator, ":")) + { + const char* value = tokeniser.getToken(); + if(!string_equal(value, ":")) + { + attribute.m_value = value; + } + else + { + tokeniser.ungetToken(); + } + { + const char* descriptionSeparator = tokeniser.getToken(); + if(string_equal(descriptionSeparator, ":")) + { + EntityClassFGD_parseSplitString(tokeniser, attribute.m_description); + } + else + { + tokeniser.ungetToken(); + } + } + } + else + { + tokeniser.ungetToken(); + } + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "="), PARSE_ERROR); + tokeniser.nextLine(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "["), PARSE_ERROR); + tokeniser.nextLine(); + + StringOutputStream listTypeName(64); + listTypeName << entityClass->m_name.c_str() << "_" << attribute.m_name.c_str(); + attribute.m_type = listTypeName.c_str(); + + ListAttributeType& listType = g_listTypesFGD[listTypeName.c_str()]; + + for(;;) + { + const char* value = tokeniser.getToken(); + if(string_equal(value, "]")) + { + tokeniser.nextLine(); + break; + } + else + { + CopiedString tmp(value); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); + const char* name = tokeniser.getToken(); + listType.push_back(name, tmp.c_str()); + } + tokeniser.nextLine(); + } + + for(ListAttributeType::const_iterator i = listType.begin(); i != listType.end(); ++i) + { + if(string_equal(attribute.m_value.c_str(), (*i).first.c_str())) + { + attribute.m_value = (*i).second.c_str(); + } + } + + EntityClass_insertAttribute(*entityClass, key.c_str(), attribute); + } + else if(string_equal_nocase(type.c_str(), "decal")) + { + } + else if(string_equal_nocase(type.c_str(), "string") + || string_equal_nocase(type.c_str(), "integer") + || string_equal_nocase(type.c_str(), "studio") + || string_equal_nocase(type.c_str(), "sprite") + || string_equal_nocase(type.c_str(), "color255") + || string_equal_nocase(type.c_str(), "target_source") + || string_equal_nocase(type.c_str(), "target_destination") + || string_equal_nocase(type.c_str(), "sound") + // hl2 below + || string_equal_nocase(type.c_str(), "angle") + || string_equal_nocase(type.c_str(), "origin") + || string_equal_nocase(type.c_str(), "float") + || string_equal_nocase(type.c_str(), "node_dest") + || string_equal_nocase(type.c_str(), "filterclass") + || string_equal_nocase(type.c_str(), "vector") + || string_equal_nocase(type.c_str(), "sidelist") + || string_equal_nocase(type.c_str(), "material") + || string_equal_nocase(type.c_str(), "vecline") + || string_equal_nocase(type.c_str(), "axis") + || string_equal_nocase(type.c_str(), "npcclass") + || string_equal_nocase(type.c_str(), "target_name_or_class") + || string_equal_nocase(type.c_str(), "pointentityclass") + || string_equal_nocase(type.c_str(), "scene")) + { + if(!string_equal(tokeniser.getToken(), "readonly")) + { + tokeniser.ungetToken(); + } + + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ":"), PARSE_ERROR); + const char* attributeType = "string"; + if(string_equal_nocase(type.c_str(), "studio")) + { + attributeType = "model"; + } + + EntityClassAttribute attribute; + attribute.m_type = attributeType; + attribute.m_name = tokeniser.getToken(); + + const char* defaultSeparator = tokeniser.getToken(); + if(string_equal(defaultSeparator, ":")) + { + const char* value = tokeniser.getToken(); + if(!string_equal(value, ":")) + { + attribute.m_value = value; + } + else + { + tokeniser.ungetToken(); + } + + { + const char* descriptionSeparator = tokeniser.getToken(); + if(string_equal(descriptionSeparator, ":")) + { + EntityClassFGD_parseSplitString(tokeniser, attribute.m_description); + } + else + { + tokeniser.ungetToken(); + } + } + } + else + { + tokeniser.ungetToken(); + } + EntityClass_insertAttribute(*entityClass, key.c_str(), attribute); + } + else + { + ERROR_MESSAGE("unknown key type: " << makeQuoted(type.c_str())); + } + tokeniser.nextLine(); + } + + if(isBase) + { + EntityClassFGD_insertUniqueBase(entityClass); + } + else + { + EntityClassFGD_insertUnique(entityClass); + } +} + +void EntityClassFGD_loadFile(const char* filename); + +void EntityClassFGD_parse(TextInputStream& inputStream, const char* path) +{ + Tokeniser& tokeniser = GlobalScriptLibrary().m_pfnNewScriptTokeniser(inputStream); + + tokeniser.nextLine(); + + for(;;) + { + const char* blockType = tokeniser.getToken(); + if(blockType == 0) + { + break; + } + if(string_equal(blockType, "@SolidClass")) + { + EntityClassFGD_parseClass(tokeniser, false, false); + } + else if(string_equal(blockType, "@BaseClass")) + { + EntityClassFGD_parseClass(tokeniser, false, true); + } + else if(string_equal(blockType, "@PointClass") + // hl2 below + || string_equal(blockType, "@KeyFrameClass") + || string_equal(blockType, "@MoveClass") + || string_equal(blockType, "@FilterClass") + || string_equal(blockType, "@NPCClass")) + { + EntityClassFGD_parseClass(tokeniser, true, false); + } + // hl2 below + else if(string_equal(blockType, "@include")) + { + StringOutputStream includePath(256); + includePath << StringRange(path, path_get_filename_start(path)); + includePath << tokeniser.getToken(); + EntityClassFGD_loadFile(includePath.c_str()); + } + else if(string_equal(blockType, "@mapsize")) + { + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, "("), PARSE_ERROR); + //const char* min = + tokeniser.getToken(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ","), PARSE_ERROR); + //const char* max = + tokeniser.getToken(); + ASSERT_MESSAGE(EntityClassFGD_parseToken(tokeniser, ")"), PARSE_ERROR); + } + else + { + ERROR_MESSAGE("unknown block type: " << makeQuoted(blockType)); + } + } + + tokeniser.release(); +} + + +void EntityClassFGD_loadFile(const char* filename) +{ + TextFileInputStream file(filename); + if(!file.failed()) + { + globalOutputStream() << "parsing entity classes from " << makeQuoted(filename) << "\n"; + + EntityClassFGD_parse(file, filename); + } +} + +EntityClass* EntityClassFGD_findOrInsert(const char *name, bool has_brushes) +{ + ASSERT_NOTNULL(name); + + if(string_empty(name)) + { + return g_EntityClassFGD_bad; + } + + EntityClasses::iterator i = g_EntityClassFGD_classes.find(name); + if(i != g_EntityClassFGD_classes.end() + //&& string_equal((*i).first, name) + ) + { + return (*i).second; + } + + EntityClass* e = EntityClass_Create_Default(name, has_brushes); + return EntityClassFGD_insertUnique(e); +} + +const ListAttributeType* EntityClassFGD_findListType(const char *name) +{ + ListAttributeTypes::iterator i = g_listTypesFGD.find(name); + if(i != g_listTypesFGD.end()) + { + return &(*i).second; + } + return 0; + +} + + +void EntityClassFGD_resolveInheritance(EntityClass* derivedClass) +{ + if(derivedClass->inheritanceResolved == false) + { + derivedClass->inheritanceResolved = true; + for(StringList::iterator j = derivedClass->m_parent.begin(); j != derivedClass->m_parent.end(); ++j) + { + BaseClasses::iterator i = g_EntityClassFGD_bases.find((*j).c_str()); + if(i == g_EntityClassFGD_bases.end()) + { + globalErrorStream() << "failed to find entityDef " << makeQuoted((*j).c_str()) << " inherited by " << makeQuoted(derivedClass->m_name.c_str()) << "\n"; + } + else + { + EntityClass* parentClass = (*i).second; + EntityClassFGD_resolveInheritance(parentClass); + if(!derivedClass->colorSpecified) + { + derivedClass->colorSpecified = parentClass->colorSpecified; + derivedClass->color = parentClass->color; + } + if(!derivedClass->sizeSpecified) + { + derivedClass->sizeSpecified = parentClass->sizeSpecified; + derivedClass->mins = parentClass->mins; + derivedClass->maxs = parentClass->maxs; + } + + for(EntityClassAttributes::iterator k = parentClass->m_attributes.begin(); k != parentClass->m_attributes.end(); ++k) + { + EntityClass_insertAttribute(*derivedClass, (*k).first.c_str(), (*k).second); + } + } + } + } +} + +class EntityClassFGD : public ModuleObserver +{ + std::size_t m_unrealised; + ModuleObservers m_observers; +public: + EntityClassFGD() : m_unrealised(3) + { + } + void realise() + { + if(--m_unrealised == 0) + { + StringOutputStream filename(256); + filename << GlobalRadiant().getGameToolsPath() << GlobalRadiant().getGameName() << "/halflife.fgd"; + EntityClassFGD_loadFile(filename.c_str()); + + { + for(EntityClasses::iterator i = g_EntityClassFGD_classes.begin(); i != g_EntityClassFGD_classes.end(); ++i) + { + EntityClassFGD_resolveInheritance((*i).second); + if((*i).second->fixedsize && string_empty((*i).second->m_modelpath.c_str())) + { + if(!(*i).second->sizeSpecified) + { + globalErrorStream() << "size not specified for entity class: " << makeQuoted((*i).second->m_name.c_str()) << '\n'; + } + if(!(*i).second->colorSpecified) + { + globalErrorStream() << "color not specified for entity class: " << makeQuoted((*i).second->m_name.c_str()) << '\n'; + } + } + } + } + { + for(BaseClasses::iterator i = g_EntityClassFGD_bases.begin(); i != g_EntityClassFGD_bases.end(); ++i) + { + eclass_capture_state((*i).second); + } + } + + m_observers.realise(); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + m_observers.unrealise(); + EntityClassFGD_clear(); + } + } + void attach(ModuleObserver& observer) + { + m_observers.attach(observer); + } + void detach(ModuleObserver& observer) + { + m_observers.detach(observer); + } +}; + +EntityClassFGD g_EntityClassFGD; + +void EntityClassFGD_attach(ModuleObserver& observer) +{ + g_EntityClassFGD.attach(observer); +} +void EntityClassFGD_detach(ModuleObserver& observer) +{ + g_EntityClassFGD.detach(observer); +} + +void EntityClassFGD_realise() +{ + g_EntityClassFGD.realise(); +} +void EntityClassFGD_unrealise() +{ + g_EntityClassFGD.unrealise(); +} + +void EntityClassFGD_construct() +{ + // start by creating the default unknown eclass + g_EntityClassFGD_bad = EClass_Create("UNKNOWN_CLASS", Vector3(0.0f, 0.5f, 0.0f), ""); + + EntityClassFGD_realise(); +} + +void EntityClassFGD_destroy() +{ + EntityClassFGD_unrealise(); + + g_EntityClassFGD_bad->free(g_EntityClassFGD_bad); +} + +class EntityClassFGDDependencies : public GlobalFileSystemModuleRef, public GlobalShaderCacheModuleRef, public GlobalRadiantModuleRef +{ +}; + +class EntityClassFGDAPI +{ + EntityClassManager m_eclassmanager; +public: + typedef EntityClassManager Type; + STRING_CONSTANT(Name, "halflife"); + + EntityClassFGDAPI() + { + EntityClassFGD_construct(); + + m_eclassmanager.findOrInsert = &EntityClassFGD_findOrInsert; + m_eclassmanager.findListType = &EntityClassFGD_findListType; + m_eclassmanager.forEach = &EntityClassFGD_forEach; + m_eclassmanager.attach = &EntityClassFGD_attach; + m_eclassmanager.detach = &EntityClassFGD_detach; + m_eclassmanager.realise = &EntityClassFGD_realise; + m_eclassmanager.unrealise = &EntityClassFGD_unrealise; + + GlobalRadiant().attachGameToolsPathObserver(g_EntityClassFGD); + GlobalRadiant().attachGameNameObserver(g_EntityClassFGD); + } + ~EntityClassFGDAPI() + { + GlobalRadiant().detachGameNameObserver(g_EntityClassFGD); + GlobalRadiant().detachGameToolsPathObserver(g_EntityClassFGD); + + EntityClassFGD_destroy(); + } + EntityClassManager* getTable() + { + return &m_eclassmanager; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule EntityClassFGDModule; +typedef Static StaticEntityClassFGDModule; +StaticRegisterModule staticRegisterEntityClassFGD(StaticEntityClassFGDModule::instance()); diff --git a/misc/mediasource/netradiant-src/radiant/eclass_fgd.h b/misc/mediasource/netradiant-src/radiant/eclass_fgd.h new file mode 100644 index 00000000..f8540b39 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_fgd.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ECLASS_FGD_H) +#define INCLUDED_ECLASS_FGD_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/eclass_xml.cpp b/misc/mediasource/netradiant-src/radiant/eclass_xml.cpp new file mode 100644 index 00000000..5195b4e7 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_xml.cpp @@ -0,0 +1,610 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 +*/ + +///\file +///\brief EntityClass plugin that supports the .ent xml entity-definition format. +/// +/// the .ent xml format expresses entity-definitions. +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// the attributes of an entity type are defined like this: +/// +/// <[name of attribute type] +/// key="[entity key name]" +/// name="[name shown in gui]" +/// value="[default entity key value]" +/// >[comment text shown in gui] +/// +/// each attribute type has a specialised attribute-editor GUI +/// +/// currently-supported attribute types: +/// +/// string a string +/// array an array of strings - value is a semi-colon-delimited string +/// integer an integer value +/// boolean an integer - shows as a checkbox - true = non-zero +/// integer2 two integer values +/// integer3 three integer values +/// real3 three floating-point values +/// angle specialisation of real - Yaw angle +/// direction specialisation of real - Yaw angle, -1 = down, -2 = up +/// angles specialisation of real3 - Pitch Yaw Roll +/// color specialisation of real3 - RGB floating-point colour +/// target a string that uniquely identifies an entity or group of entities +/// targetname a string that uniquely identifies an entity or group of entities +/// sound the VFS path to a sound file +/// texture the VFS path to a texture file or a shader name +/// model the VFS path to a model file +/// skin the VFS path to a skin file +/// +/// +/// flag attributes define a flag in the "spawnflags" key: +/// +/// [comment text shown in gui] +/// +/// the default value for a flag bit is always 0. +/// +/// +/// List attributes have a set of valid values. +/// Create new list attribute types like this: +/// +/// +/// +/// +/// +/// +/// these can then be used as attribute types. +/// +/// +/// An attribute definition should specify a default value that corresponds +/// with the default value given by the game. If the default value is not +/// specified in the attribute definition, it is assumed to be an empty string. +/// +/// If the currently-selected entity in Radiant does not specify a value for +/// the key of an attribute, the default value from the attribute-definition +/// will be displayed in the attribute-editor and used when visualising the +/// entity in the preview windows. E.g. the Doom3 "light" entity has a +/// "light_radius" key. Light entities without a "light_radius" key are +/// displayed in Doom3 with a radius of 300. The default value for the +/// "light_radius" attribute definition should be specified as "300 300 300". +/// + + + + +#include "eclass_xml.h" + +#include "ieclass.h" +#include "irender.h" +#include "ifilesystem.h" +#include "iarchive.h" + +#include "xml/xmlparser.h" +#include "generic/object.h" +#include "generic/reference.h" +#include "stream/stringstream.h" +#include "stream/textfilestream.h" +#include "os/path.h" +#include "eclasslib.h" +#include "modulesystem/moduleregistry.h" +#include "stringio.h" + +#define PARSE_ERROR(elementName, name) makeQuoted(elementName) << " is not a valid child of " << makeQuoted(name) + +class IgnoreBreaks +{ +public: + const char* m_first; + const char* m_last; + IgnoreBreaks(const char* first, const char* last) : m_first(first), m_last(last) + { + } +}; + +template +TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const IgnoreBreaks& ignoreBreaks) +{ + for(const char* i = ignoreBreaks.m_first; i != ignoreBreaks.m_last; ++i) + { + if(*i != '\n') + { + ostream << *i; + } + } + return ostream; +} + +namespace +{ + +class TreeXMLImporter : public TextOutputStream +{ +public: + virtual TreeXMLImporter& pushElement(const XMLElement& element) = 0; + virtual void popElement(const char* name) = 0; +}; + +template +class Storage +{ + char m_storage[sizeof(Type)]; +public: + Type& get() + { + return *reinterpret_cast(m_storage); + } + const Type& get() const + { + return *reinterpret_cast(m_storage); + } +}; + +class BreakImporter : public TreeXMLImporter +{ +public: + BreakImporter(StringOutputStream& comment) + { + comment << '\n'; + } + static const char* name() + { + return "n"; + } + TreeXMLImporter& pushElement(const XMLElement& element) + { + ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); + return *this; + } + void popElement(const char* elementName) + { + ERROR_MESSAGE(PARSE_ERROR(elementName, name())); + } + std::size_t write(const char* data, std::size_t length) + { + return length; + } +}; + +class AttributeImporter : public TreeXMLImporter +{ + StringOutputStream& m_comment; + +public: + AttributeImporter(StringOutputStream& comment, EntityClass* entityClass, const XMLElement& element) : m_comment(comment) + { + const char* type = element.name(); + const char* key = element.attribute("key"); + const char* name = element.attribute("name"); + const char* value = element.attribute("value"); + + ASSERT_MESSAGE(!string_empty(key), "key attribute not specified"); + ASSERT_MESSAGE(!string_empty(name), "name attribute not specified"); + + if(string_equal(type, "flag")) + { + std::size_t bit = atoi(element.attribute("bit")); + ASSERT_MESSAGE(bit < MAX_FLAGS, "invalid flag bit"); + ASSERT_MESSAGE(string_empty(entityClass->flagnames[bit]), "non-unique flag bit"); + strcpy(entityClass->flagnames[bit], key); + } + + m_comment << key; + m_comment << " : "; + + EntityClass_insertAttribute(*entityClass, key, EntityClassAttribute(type, name, value)); + } + ~AttributeImporter() + { + } + TreeXMLImporter& pushElement(const XMLElement& element) + { + ERROR_MESSAGE(PARSE_ERROR(element.name(), "attribute")); + return *this; + } + void popElement(const char* elementName) + { + ERROR_MESSAGE(PARSE_ERROR(elementName, "attribute")); + } + std::size_t write(const char* data, std::size_t length) + { + return m_comment.write(data, length); + } +}; + +bool attributeSupported(const char* name) +{ + return string_equal(name, "real") + || string_equal(name, "integer") + || string_equal(name, "boolean") + || string_equal(name, "string") + || string_equal(name, "array") + || string_equal(name, "flag") + || string_equal(name, "real3") + || string_equal(name, "integer3") + || string_equal(name, "direction") + || string_equal(name, "angle") + || string_equal(name, "angles") + || string_equal(name, "color") + || string_equal(name, "target") + || string_equal(name, "targetname") + || string_equal(name, "sound") + || string_equal(name, "texture") + || string_equal(name, "model") + || string_equal(name, "skin") + || string_equal(name, "integer2"); +} + +typedef std::map ListAttributeTypes; + +bool listAttributeSupported(ListAttributeTypes& listTypes, const char* name) +{ + return listTypes.find(name) != listTypes.end(); +} + + +class ClassImporter : public TreeXMLImporter +{ + EntityClassCollector& m_collector; + EntityClass* m_eclass; + StringOutputStream m_comment; + Storage m_attribute; + ListAttributeTypes& m_listTypes; + +public: + ClassImporter(EntityClassCollector& collector, ListAttributeTypes& listTypes, const XMLElement& element) : m_collector(collector), m_listTypes(listTypes) + { + m_eclass = Eclass_Alloc(); + m_eclass->free = &Eclass_Free; + + const char* name = element.attribute("name"); + ASSERT_MESSAGE(!string_empty(name), "name attribute not specified for class"); + m_eclass->m_name = name; + + const char* color = element.attribute("color"); + ASSERT_MESSAGE(!string_empty(name), "color attribute not specified for class " << name); + string_parse_vector3(color, m_eclass->color); + eclass_capture_state(m_eclass); + + const char* model = element.attribute("model"); + if(!string_empty(model)) + { + StringOutputStream buffer(256); + buffer << PathCleaned(model); + m_eclass->m_modelpath = buffer.c_str(); + } + + const char* type = element.name(); + if(string_equal(type, "point")) + { + const char* box = element.attribute("box"); + ASSERT_MESSAGE(!string_empty(box), "box attribute not found for class " << name); + m_eclass->fixedsize = true; + string_parse_vector(box, &m_eclass->mins.x(), &m_eclass->mins.x() + 6); + } + } + ~ClassImporter() + { + m_eclass->m_comments = m_comment.c_str(); + m_collector.insert(m_eclass); + + for(ListAttributeTypes::iterator i = m_listTypes.begin(); i != m_listTypes.end(); ++i) + { + m_collector.insert((*i).first.c_str(), (*i).second); + } + } + static const char* name() + { + return "class"; + } + TreeXMLImporter& pushElement(const XMLElement& element) + { + if(attributeSupported(element.name()) || listAttributeSupported(m_listTypes, element.name())) + { + constructor(m_attribute.get(), makeReference(m_comment), m_eclass, element); + return m_attribute.get(); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); + return *this; + } + } + void popElement(const char* elementName) + { + if(attributeSupported(elementName) || listAttributeSupported(m_listTypes, elementName)) + { + destructor(m_attribute.get()); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(elementName, name())); + } + } + std::size_t write(const char* data, std::size_t length) + { + return m_comment.write(data, length); + } +}; + +class ItemImporter : public TreeXMLImporter +{ +public: + ItemImporter(ListAttributeType& list, const XMLElement& element) + { + const char* name = element.attribute("name"); + const char* value = element.attribute("value"); + list.push_back(name, value); + } + TreeXMLImporter& pushElement(const XMLElement& element) + { + ERROR_MESSAGE(PARSE_ERROR(element.name(), "item")); + return *this; + } + void popElement(const char* elementName) + { + ERROR_MESSAGE(PARSE_ERROR(elementName, "item")); + } + std::size_t write(const char* data, std::size_t length) + { + return length; + } +}; + +bool isItem(const char* name) +{ + return string_equal(name, "item"); +} + +class ListAttributeImporter : public TreeXMLImporter +{ + ListAttributeType* m_listType; + Storage m_item; +public: + ListAttributeImporter(ListAttributeTypes& listTypes, const XMLElement& element) + { + const char* name = element.attribute("name"); + m_listType = &listTypes[name]; + } + TreeXMLImporter& pushElement(const XMLElement& element) + { + if(isItem(element.name())) + { + constructor(m_item.get(), makeReference(*m_listType), element); + return m_item.get(); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(element.name(), "list")); + return *this; + } + } + void popElement(const char* elementName) + { + if(isItem(elementName)) + { + destructor(m_item.get()); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(elementName, "list")); + } + } + std::size_t write(const char* data, std::size_t length) + { + return length; + } +}; + +bool classSupported(const char* name) +{ + return string_equal(name, "group") + || string_equal(name, "point"); +} + +bool listSupported(const char* name) +{ + return string_equal(name, "list"); +} + +class ClassesImporter : public TreeXMLImporter +{ + EntityClassCollector& m_collector; + Storage m_class; + Storage m_list; + ListAttributeTypes m_listTypes; + +public: + ClassesImporter(EntityClassCollector& collector) : m_collector(collector) + { + } + static const char* name() + { + return "classes"; + } + TreeXMLImporter& pushElement(const XMLElement& element) + { + if(classSupported(element.name())) + { + constructor(m_class.get(), makeReference(m_collector), makeReference(m_listTypes), element); + return m_class.get(); + } + else if(listSupported(element.name())) + { + constructor(m_list.get(), makeReference(m_listTypes), element); + return m_list.get(); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); + return *this; + } + } + void popElement(const char* elementName) + { + if(classSupported(elementName)) + { + destructor(m_class.get()); + } + else if(listSupported(elementName)) + { + destructor(m_list.get()); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(elementName, name())); + } + } + std::size_t write(const char* data, std::size_t length) + { + return length; + } +}; + +class EclassXMLImporter : public TreeXMLImporter +{ + EntityClassCollector& m_collector; + Storage m_classes; + +public: + EclassXMLImporter(EntityClassCollector& collector) : m_collector(collector) + { + } + static const char* name() + { + return "classes"; + } + TreeXMLImporter& pushElement(const XMLElement& element) + { + if(string_equal(element.name(), ClassesImporter::name())) + { + constructor(m_classes.get(), makeReference(m_collector)); + return m_classes.get(); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(element.name(), name())); + return *this; + } + } + void popElement(const char* elementName) + { + if(string_equal(elementName, ClassesImporter::name())) + { + destructor(m_classes.get()); + } + else + { + ERROR_MESSAGE(PARSE_ERROR(elementName, name())); + } + } + std::size_t write(const char* data, std::size_t length) + { + return length; + } +}; + +class TreeXMLImporterStack : public XMLImporter +{ + std::vector< Reference > m_importers; +public: + TreeXMLImporterStack(TreeXMLImporter& importer) + { + m_importers.push_back(makeReference(importer)); + } + void pushElement(const XMLElement& element) + { + m_importers.push_back(makeReference(m_importers.back().get().pushElement(element))); + } + void popElement(const char* name) + { + m_importers.pop_back(); + m_importers.back().get().popElement(name); + } + std::size_t write(const char* buffer, std::size_t length) + { + return m_importers.back().get().write(buffer, length); + } +}; + + + +const char* GetExtension() +{ + return "ent"; +} +void ScanFile(EntityClassCollector& collector, const char *filename) +{ + TextFileInputStream inputFile(filename); + if(!inputFile.failed()) + { + XMLStreamParser parser(inputFile); + + EclassXMLImporter importer(collector); + TreeXMLImporterStack stack(importer); + parser.exportXML(stack); + } +} + + +} + +#include "modulesystem/singletonmodule.h" + +class EntityClassXMLDependencies : public GlobalFileSystemModuleRef, public GlobalShaderCacheModuleRef +{ +}; + +class EclassXMLAPI +{ + EntityClassScanner m_eclassxml; +public: + typedef EntityClassScanner Type; + STRING_CONSTANT(Name, "xml"); + + EclassXMLAPI() + { + m_eclassxml.scanFile = &ScanFile; + m_eclassxml.getExtension = &GetExtension; + } + EntityClassScanner* getTable() + { + return &m_eclassxml; + } +}; + +typedef SingletonModule EclassXMLModule; +typedef Static StaticEclassXMLModule; +StaticRegisterModule staticRegisterEclassXML(StaticEclassXMLModule::instance()); diff --git a/misc/mediasource/netradiant-src/radiant/eclass_xml.h b/misc/mediasource/netradiant-src/radiant/eclass_xml.h new file mode 100644 index 00000000..7884d0e8 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/eclass_xml.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ECLASS_XML_H) +#define INCLUDED_ECLASS_XML_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/entity.cpp b/misc/mediasource/netradiant-src/radiant/entity.cpp new file mode 100644 index 00000000..9478bda2 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/entity.cpp @@ -0,0 +1,665 @@ +/* +Copyright (C) 1999-2006 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 "entity.h" + +#include "ientity.h" +#include "iselection.h" +#include "imodel.h" +#include "ifilesystem.h" +#include "iundo.h" +#include "editable.h" + +#include "eclasslib.h" +#include "scenelib.h" +#include "os/path.h" +#include "os/file.h" +#include "stream/stringstream.h" +#include "stringio.h" + +#include "gtkutil/filechooser.h" +#include "gtkmisc.h" +#include "select.h" +#include "map.h" +#include "preferences.h" +#include "gtkdlgs.h" +#include "mainframe.h" +#include "qe3.h" +#include "commands.h" + +struct entity_globals_t +{ + Vector3 color_entity; + + entity_globals_t() : + color_entity(0.0f, 0.0f, 0.0f) + { + } +}; + +entity_globals_t g_entity_globals; + +class EntitySetKeyValueSelected : public scene::Graph::Walker +{ + const char* m_key; + const char* m_value; +public: + EntitySetKeyValueSelected(const char* key, const char* value) + : m_key(key), m_value(value) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + Entity* entity = Node_getEntity(path.top()); + if(entity != 0 + && (instance.childSelected() || Instance_getSelectable(instance)->isSelected())) + { + entity->setKeyValue(m_key, m_value); + } + } +}; + +class EntitySetClassnameSelected : public scene::Graph::Walker +{ + const char* m_classname; +public: + EntitySetClassnameSelected(const char* classname) + : m_classname(classname) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + Entity* entity = Node_getEntity(path.top()); + if(entity != 0 + && (instance.childSelected() || Instance_getSelectable(instance)->isSelected())) + { + NodeSmartReference node(GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert(m_classname, node_is_group(path.top())))); + + EntityCopyingVisitor visitor(*Node_getEntity(node)); + + entity->forEachKeyValue(visitor); + + NodeSmartReference child(path.top().get()); + NodeSmartReference parent(path.parent().get()); + Node_getTraversable(parent)->erase(child); + if(Node_getTraversable(child) != 0 + && Node_getTraversable(node) != 0 + && node_is_group(node)) + { + parentBrushes(child, node); + } + Node_getTraversable(parent)->insert(node); + } + } +}; + +void Scene_EntitySetKeyValue_Selected(const char* key, const char* value) +{ + GlobalSceneGraph().traverse(EntitySetKeyValueSelected(key, value)); +} + +void Scene_EntitySetClassname_Selected(const char* classname) +{ + GlobalSceneGraph().traverse(EntitySetClassnameSelected(classname)); +} + + +void Entity_ungroupSelected() +{ + if (GlobalSelectionSystem().countSelected() < 1) return; + + UndoableCommand undo("ungroupSelectedEntities"); + + scene::Path world_path(makeReference(GlobalSceneGraph().root())); + world_path.push(makeReference(Map_FindOrInsertWorldspawn(g_map))); + + scene::Instance &instance = GlobalSelectionSystem().ultimateSelected(); + scene::Path path = instance.path(); + + if (!Node_isEntity(path.top())) path.pop(); + + if(Node_getEntity(path.top()) != 0 + && node_is_group(path.top())) + { + if(world_path.top().get_pointer() != path.top().get_pointer()) + { + parentBrushes(path.top(), world_path.top()); + Path_deleteTop(path); + } + } +} + + +class EntityFindSelected : public scene::Graph::Walker +{ +public: + mutable const scene::Path *groupPath; + mutable scene::Instance *groupInstance; + EntityFindSelected(): groupPath(0), groupInstance(0) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + Entity* entity = Node_getEntity(path.top()); + if(entity != 0 + && Instance_getSelectable(instance)->isSelected() + && node_is_group(path.top()) + && !groupPath) + { + groupPath = &path; + groupInstance = &instance; + } + } +}; + +class EntityGroupSelected : public scene::Graph::Walker +{ + NodeSmartReference group, worldspawn; + //typedef std::pair DeletionPair; + //Stack deleteme; + public: + EntityGroupSelected(const scene::Path &p): group(p.top().get()), worldspawn(Map_FindOrInsertWorldspawn(g_map)) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + Selectable *selectable = Instance_getSelectable(instance); + if(selectable && selectable->isSelected()) + { + Entity* entity = Node_getEntity(path.top()); + if(entity == 0 && Node_isPrimitive(path.top())) + { + NodeSmartReference child(path.top().get()); + NodeSmartReference parent(path.parent().get()); + + if(path.size() >= 3 && parent != worldspawn) + { + NodeSmartReference parentparent(path[path.size() - 3].get()); + + Node_getTraversable(parent)->erase(child); + Node_getTraversable(group)->insert(child); + + if(Node_getTraversable(parent)->empty()) + { + //deleteme.push(DeletionPair(parentparent, parent)); + Node_getTraversable(parentparent)->erase(parent); + } + } + else + { + Node_getTraversable(parent)->erase(child); + Node_getTraversable(group)->insert(child); + } + } + } + } +}; + +void Entity_groupSelected() +{ + if (GlobalSelectionSystem().countSelected() < 1) return; + + UndoableCommand undo("groupSelectedEntities"); + + scene::Path world_path(makeReference(GlobalSceneGraph().root())); + world_path.push(makeReference(Map_FindOrInsertWorldspawn(g_map))); + + EntityFindSelected fse; + GlobalSceneGraph().traverse(fse); + if(fse.groupPath) + { + GlobalSceneGraph().traverse(EntityGroupSelected(*fse.groupPath)); + } + else + { + GlobalSceneGraph().traverse(EntityGroupSelected(world_path)); + } +} + + + +void Entity_connectSelected() +{ + if(GlobalSelectionSystem().countSelected() == 2) + { + GlobalEntityCreator().connectEntities( + GlobalSelectionSystem().penultimateSelected().path(), + GlobalSelectionSystem().ultimateSelected().path(), + 0 + ); + } + else + { + globalErrorStream() << "entityConnectSelected: exactly two instances must be selected\n"; + } +} + +void Entity_killconnectSelected() +{ + if(GlobalSelectionSystem().countSelected() == 2) + { + GlobalEntityCreator().connectEntities( + GlobalSelectionSystem().penultimateSelected().path(), + GlobalSelectionSystem().ultimateSelected().path(), + 1 + ); + } + else + { + globalErrorStream() << "entityKillConnectSelected: exactly two instances must be selected\n"; + } +} + +AABB Doom3Light_getBounds(const AABB& workzone) +{ + AABB aabb(workzone); + + Vector3 defaultRadius(300, 300, 300); + if(!string_parse_vector3(EntityClass_valueForKey(*GlobalEntityClassManager().findOrInsert("light", false), "light_radius"), defaultRadius)) + { + globalErrorStream() << "Doom3Light_getBounds: failed to parse default light radius\n"; + } + + if(aabb.extents[0] == 0) + { + aabb.extents[0] = defaultRadius[0]; + } + if(aabb.extents[1] == 0) + { + aabb.extents[1] = defaultRadius[1]; + } + if(aabb.extents[2] == 0) + { + aabb.extents[2] = defaultRadius[2]; + } + + if(aabb_valid(aabb)) + { + return aabb; + } + return AABB(Vector3(0, 0, 0), Vector3(64, 64, 64)); +} + +int g_iLastLightIntensity; + +void Entity_createFromSelection(const char* name, const Vector3& origin) +{ +#if 0 + if(string_equal_nocase(name, "worldspawn")) + { + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "Can't create an entity with worldspawn.", "info"); + return; + } +#endif + + EntityClass* entityClass = GlobalEntityClassManager().findOrInsert(name, true); + + bool isModel = (string_compare_nocase_n(name, "misc_", 5) == 0 && string_equal_nocase(name + string_length(name) - 5, "model")) // misc_*model (also misc_model) + || string_equal_nocase(name, "model_static") + || (GlobalSelectionSystem().countSelected() == 0 && string_equal_nocase(name, "func_static")); + + bool brushesSelected = Scene_countSelectedBrushes(GlobalSceneGraph()) != 0; + + if(!(entityClass->fixedsize || isModel) && !brushesSelected) + { + globalErrorStream() << "failed to create a group entity - no brushes are selected\n"; + return; + } + + AABB workzone(aabb_for_minmax(Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max)); + + + NodeSmartReference node(GlobalEntityCreator().createEntity(entityClass)); + + Node_getTraversable(GlobalSceneGraph().root())->insert(node); + + scene::Path entitypath(makeReference(GlobalSceneGraph().root())); + entitypath.push(makeReference(node.get())); + scene::Instance& instance = findInstance(entitypath); + + if(entityClass->fixedsize || (isModel && !brushesSelected)) + { + Select_Delete(); + + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + transform->setType(TRANSFORM_PRIMITIVE); + transform->setTranslation(origin); + transform->freezeTransform(); + } + + GlobalSelectionSystem().setSelectedAll(false); + + Instance_setSelected(instance, true); + } + else + { + if (g_pGameDescription->mGameType == "doom3") + { + Node_getEntity(node)->setKeyValue("model", Node_getEntity(node)->getKeyValue("name")); + } + + Scene_parentSelectedBrushesToEntity(GlobalSceneGraph(), node); + Scene_forEachChildSelectable(SelectableSetSelected(true), instance.path()); + } + + // tweaking: when right clic dropping a light entity, ask for light value in a custom dialog box + // see SF bug 105383 + + if (g_pGameDescription->mGameType == "hl") + { + // FIXME - Hydra: really we need a combined light AND color dialog for halflife. + if (string_equal_nocase(name, "light") + || string_equal_nocase(name, "light_environment") + || string_equal_nocase(name, "light_spot")) + { + int intensity = g_iLastLightIntensity; + + if (DoLightIntensityDlg (&intensity) == eIDOK) + { + g_iLastLightIntensity = intensity; + char buf[30]; + sprintf( buf, "255 255 255 %d", intensity ); + Node_getEntity(node)->setKeyValue("_light", buf); + } + } + } + else if(string_equal_nocase(name, "light")) + { + if(g_pGameDescription->mGameType != "doom3") + { + int intensity = g_iLastLightIntensity; + + if (DoLightIntensityDlg (&intensity) == eIDOK) + { + g_iLastLightIntensity = intensity; + char buf[10]; + sprintf( buf, "%d", intensity ); + Node_getEntity(node)->setKeyValue("light", buf); + } + } + else if(brushesSelected) // use workzone to set light position/size for doom3 lights, if there are brushes selected + { + AABB bounds(Doom3Light_getBounds(workzone)); + StringOutputStream key(64); + key << bounds.origin[0] << " " << bounds.origin[1] << " " << bounds.origin[2]; + Node_getEntity(node)->setKeyValue("origin", key.c_str()); + key.clear(); + key << bounds.extents[0] << " " << bounds.extents[1] << " " << bounds.extents[2]; + Node_getEntity(node)->setKeyValue("light_radius", key.c_str()); + } + } + + if(isModel) + { + const char* model = misc_model_dialog(GTK_WIDGET(MainFrame_getWindow())); + if(model != 0) + { + Node_getEntity(node)->setKeyValue("model", model); + } + } +} + +#if 0 +bool DoNormalisedColor(Vector3& color) +{ + if(!color_dialog(GTK_WIDGET(MainFrame_getWindow()), color)) + return false; + /* + ** scale colors so that at least one component is at 1.0F + */ + + float largest = 0.0F; + + if ( color[0] > largest ) + largest = color[0]; + if ( color[1] > largest ) + largest = color[1]; + if ( color[2] > largest ) + largest = color[2]; + + if ( largest == 0.0F ) + { + color[0] = 1.0F; + color[1] = 1.0F; + color[2] = 1.0F; + } + else + { + float scaler = 1.0F / largest; + + color[0] *= scaler; + color[1] *= scaler; + color[2] *= scaler; + } + + return true; +} +#endif + +void NormalizeColor(Vector3& color) +{ + // scale colors so that at least one component is at 1.0F + + float largest = 0.0F; + + if ( color[0] > largest ) + largest = color[0]; + if ( color[1] > largest ) + largest = color[1]; + if ( color[2] > largest ) + largest = color[2]; + + if ( largest == 0.0F ) + { + color[0] = 1.0F; + color[1] = 1.0F; + color[2] = 1.0F; + } + else + { + float scaler = 1.0F / largest; + + color[0] *= scaler; + color[1] *= scaler; + color[2] *= scaler; + } +} + +void Entity_normalizeColor() +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); + Entity* entity = Node_getEntity(path.top()); + + if(entity != 0) + { + const char* strColor = entity->getKeyValue("_color"); + if(!string_empty(strColor)) + { + Vector3 rgb; + if (string_parse_vector3(strColor, rgb)) + { + g_entity_globals.color_entity = rgb; + NormalizeColor(g_entity_globals.color_entity); + + char buffer[128]; + sprintf(buffer, "%g %g %g", g_entity_globals.color_entity[0], + g_entity_globals.color_entity[1], + g_entity_globals.color_entity[2]); + + Scene_EntitySetKeyValue_Selected("_color", buffer); + } + } + } + } +} + +void Entity_setColour() +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + bool normalize = false; + const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); + Entity* entity = Node_getEntity(path.top()); + + if(entity != 0) + { + const char* strColor = entity->getKeyValue("_color"); + if(!string_empty(strColor)) + { + Vector3 rgb; + if (string_parse_vector3(strColor, rgb)) + { + g_entity_globals.color_entity = rgb; + } + } + + if( g_pGameDescription->mGameType == "doom3" ) + normalize = false; + + if(color_dialog(GTK_WIDGET(MainFrame_getWindow()), g_entity_globals.color_entity)) + { + if( normalize ) + NormalizeColor(g_entity_globals.color_entity); + + char buffer[128]; + sprintf(buffer, "%g %g %g", g_entity_globals.color_entity[0], + g_entity_globals.color_entity[1], + g_entity_globals.color_entity[2]); + + Scene_EntitySetKeyValue_Selected("_color", buffer); + } + } + } +} + +const char* misc_model_dialog(GtkWidget* parent) +{ + StringOutputStream buffer(1024); + + buffer << g_qeglobals.m_userGamePath.c_str() << "models/"; + + if(!file_readable(buffer.c_str())) + { + // just go to fsmain + buffer.clear(); + buffer << g_qeglobals.m_userGamePath.c_str() << "/"; + } + + const char *filename = file_dialog (parent, TRUE, "Choose Model", buffer.c_str(), ModelLoader::Name()); + if (filename != 0) + { + // use VFS to get the correct relative path + const char* relative = path_make_relative(filename, GlobalFileSystem().findRoot(filename)); + if(relative == filename) + { + globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n"; + } + return relative; + } + return 0; +} + +void LightRadiiImport(EntityCreator& self, bool value) +{ + self.setLightRadii(value); +} +typedef ReferenceCaller1 LightRadiiImportCaller; + +void LightRadiiExport(EntityCreator& self, const BoolImportCallback& importer) +{ + importer(self.getLightRadii()); +} +typedef ReferenceCaller1 LightRadiiExportCaller; + +void Entity_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox( + "Show", "Light Radii", + LightRadiiImportCaller(GlobalEntityCreator()), + LightRadiiExportCaller(GlobalEntityCreator()) + ); +} +void Entity_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Entities", "Entity Display Preferences")); + Entity_constructPreferences(page); +} +void Entity_registerPreferencesPage() +{ + PreferencesDialog_addDisplayPage(FreeCaller1()); +} + + + +void Entity_constructMenu(GtkMenu* menu) +{ + create_menu_item_with_mnemonic(menu, "_Regroup", "GroupSelection"); + create_menu_item_with_mnemonic(menu, "_Ungroup", "UngroupSelection"); + create_menu_item_with_mnemonic(menu, "_Connect", "ConnectSelection"); + create_menu_item_with_mnemonic(menu, "_KillConnect", "KillConnectSelection"); + create_menu_item_with_mnemonic(menu, "_Select Color...", "EntityColor"); + create_menu_item_with_mnemonic(menu, "_Normalize Color...", "NormalizeColor"); +} + + + +#include "preferencesystem.h" +#include "stringio.h" + +void Entity_Construct() +{ + GlobalCommands_insert("EntityColor", FreeCaller(), Accelerator('K')); + GlobalCommands_insert("NormalizeColor", FreeCaller()); + GlobalCommands_insert("ConnectSelection", FreeCaller(), Accelerator('K', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("KillConnectSelection", FreeCaller(), Accelerator('K', (GdkModifierType)(GDK_SHIFT_MASK))); + GlobalCommands_insert("GroupSelection", FreeCaller()); + GlobalCommands_insert("UngroupSelection", FreeCaller()); + + GlobalPreferenceSystem().registerPreference("SI_Colors5", Vector3ImportStringCaller(g_entity_globals.color_entity), Vector3ExportStringCaller(g_entity_globals.color_entity)); + GlobalPreferenceSystem().registerPreference("LastLightIntensity", IntImportStringCaller(g_iLastLightIntensity), IntExportStringCaller(g_iLastLightIntensity)); + + Entity_registerPreferencesPage(); +} + +void Entity_Destroy() +{ +} + diff --git a/misc/mediasource/netradiant-src/radiant/entity.h b/misc/mediasource/netradiant-src/radiant/entity.h new file mode 100644 index 00000000..3e962178 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/entity.h @@ -0,0 +1,42 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_ENTITY_H) +#define INCLUDED_ENTITY_H + +template class BasicVector3; +typedef BasicVector3 Vector3; +void Entity_createFromSelection(const char* name, const Vector3& origin); + +void Scene_EntitySetKeyValue_Selected(const char* key, const char* value); +void Scene_EntitySetClassname_Selected(const char* classname); + + +typedef struct _GtkWidget GtkWidget; +const char* misc_model_dialog(GtkWidget* parent); + +typedef struct _GtkMenu GtkMenu; +void Entity_constructMenu(GtkMenu* menu); + +void Entity_Construct(); +void Entity_Destroy(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/entityinspector.cpp b/misc/mediasource/netradiant-src/radiant/entityinspector.cpp new file mode 100644 index 00000000..b5636780 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/entityinspector.cpp @@ -0,0 +1,1762 @@ +/* +Copyright (C) 1999-2006 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 "entityinspector.h" + +#include "debugging/debugging.h" + +#include "ientity.h" +#include "ifilesystem.h" +#include "imodel.h" +#include "iscenegraph.h" +#include "iselection.h" +#include "iundo.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "os/path.h" +#include "eclasslib.h" +#include "scenelib.h" +#include "generic/callback.h" +#include "os/file.h" +#include "stream/stringstream.h" +#include "moduleobserver.h" +#include "convert.h" +#include "stringio.h" + +#include "gtkutil/accelerator.h" +#include "gtkutil/dialog.h" +#include "gtkutil/filechooser.h" +#include "gtkutil/messagebox.h" +#include "gtkutil/nonmodal.h" +#include "gtkutil/button.h" +#include "gtkutil/entry.h" +#include "gtkutil/container.h" + +#include "qe3.h" +#include "gtkmisc.h" +#include "gtkdlgs.h" +#include "entity.h" +#include "mainframe.h" +#include "textureentry.h" + +GtkEntry* numeric_entry_new() +{ + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_widget_set_size_request(GTK_WIDGET(entry), 64, -1); + return entry; +} + +namespace +{ + typedef std::map KeyValues; + KeyValues g_selectedKeyValues; + KeyValues g_selectedDefaultKeyValues; +} + +const char* SelectedEntity_getValueForKey(const char* key) +{ + { + KeyValues::const_iterator i = g_selectedKeyValues.find(key); + if(i != g_selectedKeyValues.end()) + { + return (*i).second.c_str(); + } + } + { + KeyValues::const_iterator i = g_selectedDefaultKeyValues.find(key); + if(i != g_selectedDefaultKeyValues.end()) + { + return (*i).second.c_str(); + } + } + return ""; +} + +void Scene_EntitySetKeyValue_Selected_Undoable(const char* key, const char* value) +{ + StringOutputStream command(256); + command << "entitySetKeyValue -key " << makeQuoted(key) << " -value " << makeQuoted(value); + UndoableCommand undo(command.c_str()); + Scene_EntitySetKeyValue_Selected(key, value); +} + +class EntityAttribute +{ +public: + virtual GtkWidget* getWidget() const = 0; + virtual void update() = 0; + virtual void release() = 0; +}; + +class BooleanAttribute : public EntityAttribute +{ + CopiedString m_key; + GtkCheckButton* m_check; + + static gboolean toggled(GtkWidget *widget, BooleanAttribute* self) + { + self->apply(); + return FALSE; + } +public: + BooleanAttribute(const char* key) : + m_key(key), + m_check(0) + { + GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new()); + gtk_widget_show(GTK_WIDGET(check)); + + m_check = check; + + guint handler = g_signal_connect(G_OBJECT(check), "toggled", G_CALLBACK(toggled), this); + g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler)); + + update(); + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_check); + } + void release() + { + delete this; + } + void apply() + { + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_check)) ? "1" : "0"); + } + typedef MemberCaller ApplyCaller; + + void update() + { + const char* value = SelectedEntity_getValueForKey(m_key.c_str()); + if(!string_empty(value)) + { + toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(m_check), atoi(value) != 0); + } + else + { + toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(m_check), false); + } + } + typedef MemberCaller UpdateCaller; +}; + + +class StringAttribute : public EntityAttribute +{ + CopiedString m_key; + GtkEntry* m_entry; + NonModalEntry m_nonModal; +public: + StringAttribute(const char* key) : + m_key(key), + m_entry(0), + m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_widget_set_size_request(GTK_WIDGET(entry), 50, -1); + + m_entry = entry; + m_nonModal.connect(m_entry); + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_entry); + } + GtkEntry* getEntry() const + { + return m_entry; + } + + void release() + { + delete this; + } + void apply() + { + StringOutputStream value(64); + value << gtk_entry_get_text(m_entry); + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), value.c_str()); + } + typedef MemberCaller ApplyCaller; + + void update() + { + StringOutputStream value(64); + value << SelectedEntity_getValueForKey(m_key.c_str()); + gtk_entry_set_text(m_entry, value.c_str()); + } + typedef MemberCaller UpdateCaller; +}; + +class ShaderAttribute : public StringAttribute +{ +public: + ShaderAttribute(const char* key) : StringAttribute(key) + { + GlobalShaderEntryCompletion::instance().connect(StringAttribute::getEntry()); + } +}; + + +class ModelAttribute : public EntityAttribute +{ + CopiedString m_key; + BrowsedPathEntry m_entry; + NonModalEntry m_nonModal; +public: + ModelAttribute(const char* key) : + m_key(key), + m_entry(BrowseCaller(*this)), + m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) + { + m_nonModal.connect(m_entry.m_entry.m_entry); + } + void release() + { + delete this; + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_entry.m_entry.m_frame); + } + void apply() + { + StringOutputStream value(64); + value << gtk_entry_get_text(GTK_ENTRY(m_entry.m_entry.m_entry)); + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), value.c_str()); + } + typedef MemberCaller ApplyCaller; + void update() + { + StringOutputStream value(64); + value << SelectedEntity_getValueForKey(m_key.c_str()); + gtk_entry_set_text(GTK_ENTRY(m_entry.m_entry.m_entry), value.c_str()); + } + typedef MemberCaller UpdateCaller; + void browse(const BrowsedPathEntry::SetPathCallback& setPath) + { + const char *filename = misc_model_dialog(gtk_widget_get_toplevel(GTK_WIDGET(m_entry.m_entry.m_frame))); + + if(filename != 0) + { + setPath(filename); + apply(); + } + } + typedef MemberCaller1 BrowseCaller; +}; + +const char* browse_sound(GtkWidget* parent) +{ + StringOutputStream buffer(1024); + + buffer << g_qeglobals.m_userGamePath.c_str() << "sound/"; + + if(!file_readable(buffer.c_str())) + { + // just go to fsmain + buffer.clear(); + buffer << g_qeglobals.m_userGamePath.c_str() << "/"; + } + + const char* filename = file_dialog(parent, TRUE, "Open Wav File", buffer.c_str(), "sound"); + if(filename != 0) + { + const char* relative = path_make_relative(filename, GlobalFileSystem().findRoot(filename)); + if(relative == filename) + { + globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n"; + } + return relative; + } + return filename; +} + +class SoundAttribute : public EntityAttribute +{ + CopiedString m_key; + BrowsedPathEntry m_entry; + NonModalEntry m_nonModal; +public: + SoundAttribute(const char* key) : + m_key(key), + m_entry(BrowseCaller(*this)), + m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) + { + m_nonModal.connect(m_entry.m_entry.m_entry); + } + void release() + { + delete this; + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_entry.m_entry.m_frame); + } + void apply() + { + StringOutputStream value(64); + value << gtk_entry_get_text(GTK_ENTRY(m_entry.m_entry.m_entry)); + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), value.c_str()); + } + typedef MemberCaller ApplyCaller; + void update() + { + StringOutputStream value(64); + value << SelectedEntity_getValueForKey(m_key.c_str()); + gtk_entry_set_text(GTK_ENTRY(m_entry.m_entry.m_entry), value.c_str()); + } + typedef MemberCaller UpdateCaller; + void browse(const BrowsedPathEntry::SetPathCallback& setPath) + { + const char *filename = browse_sound(gtk_widget_get_toplevel(GTK_WIDGET(m_entry.m_entry.m_frame))); + + if(filename != 0) + { + setPath(filename); + apply(); + } + } + typedef MemberCaller1 BrowseCaller; +}; + +inline double angle_normalised(double angle) +{ + return float_mod(angle, 360.0); +} + +class AngleAttribute : public EntityAttribute +{ + CopiedString m_key; + GtkEntry* m_entry; + NonModalEntry m_nonModal; +public: + AngleAttribute(const char* key) : + m_key(key), + m_entry(0), + m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) + { + GtkEntry* entry = numeric_entry_new(); + m_entry = entry; + m_nonModal.connect(m_entry); + } + void release() + { + delete this; + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_entry); + } + void apply() + { + StringOutputStream angle(32); + angle << angle_normalised(entry_get_float(m_entry)); + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), angle.c_str()); + } + typedef MemberCaller ApplyCaller; + + void update() + { + const char* value = SelectedEntity_getValueForKey(m_key.c_str()); + if(!string_empty(value)) + { + StringOutputStream angle(32); + angle << angle_normalised(atof(value)); + gtk_entry_set_text(m_entry, angle.c_str()); + } + else + { + gtk_entry_set_text(m_entry, "0"); + } + } + typedef MemberCaller UpdateCaller; +}; + +namespace +{ + typedef const char* String; + const String buttons[] = { "up", "down", "z-axis" }; +} + +class DirectionAttribute : public EntityAttribute +{ + CopiedString m_key; + GtkEntry* m_entry; + NonModalEntry m_nonModal; + RadioHBox m_radio; + NonModalRadio m_nonModalRadio; + GtkHBox* m_hbox; +public: + DirectionAttribute(const char* key) : + m_key(key), + m_entry(0), + m_nonModal(ApplyCaller(*this), UpdateCaller(*this)), + m_radio(RadioHBox_new(STRING_ARRAY_RANGE(buttons))), + m_nonModalRadio(ApplyRadioCaller(*this)) + { + GtkEntry* entry = numeric_entry_new(); + m_entry = entry; + m_nonModal.connect(m_entry); + + m_nonModalRadio.connect(m_radio.m_radio); + + m_hbox = GTK_HBOX(gtk_hbox_new(FALSE, 4)); + gtk_widget_show(GTK_WIDGET(m_hbox)); + + gtk_box_pack_start(GTK_BOX(m_hbox), GTK_WIDGET(m_radio.m_hbox), TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(m_hbox), GTK_WIDGET(m_entry), TRUE, TRUE, 0); + } + void release() + { + delete this; + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_hbox); + } + void apply() + { + StringOutputStream angle(32); + angle << angle_normalised(entry_get_float(m_entry)); + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), angle.c_str()); + } + typedef MemberCaller ApplyCaller; + + void update() + { + const char* value = SelectedEntity_getValueForKey(m_key.c_str()); + if(!string_empty(value)) + { + float f = float(atof(value)); + if(f == -1) + { + gtk_widget_set_sensitive(GTK_WIDGET(m_entry), FALSE); + radio_button_set_active_no_signal(m_radio.m_radio, 0); + gtk_entry_set_text(m_entry, ""); + } + else if(f == -2) + { + gtk_widget_set_sensitive(GTK_WIDGET(m_entry), FALSE); + radio_button_set_active_no_signal(m_radio.m_radio, 1); + gtk_entry_set_text(m_entry, ""); + } + else + { + gtk_widget_set_sensitive(GTK_WIDGET(m_entry), TRUE); + radio_button_set_active_no_signal(m_radio.m_radio, 2); + StringOutputStream angle(32); + angle << angle_normalised(f); + gtk_entry_set_text(m_entry, angle.c_str()); + } + } + else + { + gtk_entry_set_text(m_entry, "0"); + } + } + typedef MemberCaller UpdateCaller; + + void applyRadio() + { + int index = radio_button_get_active(m_radio.m_radio); + if(index == 0) + { + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), "-1"); + } + else if(index == 1) + { + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), "-2"); + } + else if(index == 2) + { + apply(); + } + } + typedef MemberCaller ApplyRadioCaller; +}; + + +class AnglesEntry +{ +public: + GtkEntry* m_roll; + GtkEntry* m_pitch; + GtkEntry* m_yaw; + AnglesEntry() : m_roll(0), m_pitch(0), m_yaw(0) + { + } +}; + +typedef BasicVector3 DoubleVector3; + +class AnglesAttribute : public EntityAttribute +{ + CopiedString m_key; + AnglesEntry m_angles; + NonModalEntry m_nonModal; + GtkBox* m_hbox; +public: + AnglesAttribute(const char* key) : + m_key(key), + m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) + { + m_hbox = GTK_BOX(gtk_hbox_new(TRUE, 4)); + gtk_widget_show(GTK_WIDGET(m_hbox)); + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); + m_angles.m_pitch = entry; + m_nonModal.connect(m_angles.m_pitch); + } + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); + m_angles.m_yaw = entry; + m_nonModal.connect(m_angles.m_yaw); + } + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); + m_angles.m_roll = entry; + m_nonModal.connect(m_angles.m_roll); + } + } + void release() + { + delete this; + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_hbox); + } + void apply() + { + StringOutputStream angles(64); + angles << angle_normalised(entry_get_float(m_angles.m_pitch)) + << " " << angle_normalised(entry_get_float(m_angles.m_yaw)) + << " " << angle_normalised(entry_get_float(m_angles.m_roll)); + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), angles.c_str()); + } + typedef MemberCaller ApplyCaller; + + void update() + { + StringOutputStream angle(32); + const char* value = SelectedEntity_getValueForKey(m_key.c_str()); + if(!string_empty(value)) + { + DoubleVector3 pitch_yaw_roll; + if(!string_parse_vector3(value, pitch_yaw_roll)) + { + pitch_yaw_roll = DoubleVector3(0, 0, 0); + } + + angle << angle_normalised(pitch_yaw_roll.x()); + gtk_entry_set_text(m_angles.m_pitch, angle.c_str()); + angle.clear(); + + angle << angle_normalised(pitch_yaw_roll.y()); + gtk_entry_set_text(m_angles.m_yaw, angle.c_str()); + angle.clear(); + + angle << angle_normalised(pitch_yaw_roll.z()); + gtk_entry_set_text(m_angles.m_roll, angle.c_str()); + angle.clear(); + } + else + { + gtk_entry_set_text(m_angles.m_pitch, "0"); + gtk_entry_set_text(m_angles.m_yaw, "0"); + gtk_entry_set_text(m_angles.m_roll, "0"); + } + } + typedef MemberCaller UpdateCaller; +}; + +class Vector3Entry +{ +public: + GtkEntry* m_x; + GtkEntry* m_y; + GtkEntry* m_z; + Vector3Entry() : m_x(0), m_y(0), m_z(0) + { + } +}; + +class Vector3Attribute : public EntityAttribute +{ + CopiedString m_key; + Vector3Entry m_vector3; + NonModalEntry m_nonModal; + GtkBox* m_hbox; +public: + Vector3Attribute(const char* key) : + m_key(key), + m_nonModal(ApplyCaller(*this), UpdateCaller(*this)) + { + m_hbox = GTK_BOX(gtk_hbox_new(TRUE, 4)); + gtk_widget_show(GTK_WIDGET(m_hbox)); + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); + m_vector3.m_x = entry; + m_nonModal.connect(m_vector3.m_x); + } + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); + m_vector3.m_y = entry; + m_nonModal.connect(m_vector3.m_y); + } + { + GtkEntry* entry = numeric_entry_new(); + gtk_box_pack_start(m_hbox, GTK_WIDGET(entry), TRUE, TRUE, 0); + m_vector3.m_z = entry; + m_nonModal.connect(m_vector3.m_z); + } + } + void release() + { + delete this; + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_hbox); + } + void apply() + { + StringOutputStream vector3(64); + vector3 << entry_get_float(m_vector3.m_x) + << " " << entry_get_float(m_vector3.m_y) + << " " << entry_get_float(m_vector3.m_z); + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), vector3.c_str()); + } + typedef MemberCaller ApplyCaller; + + void update() + { + StringOutputStream buffer(32); + const char* value = SelectedEntity_getValueForKey(m_key.c_str()); + if(!string_empty(value)) + { + DoubleVector3 x_y_z; + if(!string_parse_vector3(value, x_y_z)) + { + x_y_z = DoubleVector3(0, 0, 0); + } + + buffer << x_y_z.x(); + gtk_entry_set_text(m_vector3.m_x, buffer.c_str()); + buffer.clear(); + + buffer << x_y_z.y(); + gtk_entry_set_text(m_vector3.m_y, buffer.c_str()); + buffer.clear(); + + buffer << x_y_z.z(); + gtk_entry_set_text(m_vector3.m_z, buffer.c_str()); + buffer.clear(); + } + else + { + gtk_entry_set_text(m_vector3.m_x, "0"); + gtk_entry_set_text(m_vector3.m_y, "0"); + gtk_entry_set_text(m_vector3.m_z, "0"); + } + } + typedef MemberCaller UpdateCaller; +}; + +class NonModalComboBox +{ + Callback m_changed; + guint m_changedHandler; + + static gboolean changed(GtkComboBox *widget, NonModalComboBox* self) + { + self->m_changed(); + return FALSE; + } + +public: + NonModalComboBox(const Callback& changed) : m_changed(changed), m_changedHandler(0) + { + } + void connect(GtkComboBox* combo) + { + m_changedHandler = g_signal_connect(G_OBJECT(combo), "changed", G_CALLBACK(changed), this); + } + void setActive(GtkComboBox* combo, int value) + { + g_signal_handler_disconnect(G_OBJECT(combo), m_changedHandler); + gtk_combo_box_set_active(combo, value); + connect(combo); + } +}; + +class ListAttribute : public EntityAttribute +{ + CopiedString m_key; + GtkComboBox* m_combo; + NonModalComboBox m_nonModal; + const ListAttributeType& m_type; +public: + ListAttribute(const char* key, const ListAttributeType& type) : + m_key(key), + m_combo(0), + m_nonModal(ApplyCaller(*this)), + m_type(type) + { + GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); + + for(ListAttributeType::const_iterator i = type.begin(); i != type.end(); ++i) + { + gtk_combo_box_append_text(GTK_COMBO_BOX(combo), (*i).first.c_str()); + } + + gtk_widget_show(GTK_WIDGET(combo)); + m_nonModal.connect(combo); + + m_combo = combo; + } + void release() + { + delete this; + } + GtkWidget* getWidget() const + { + return GTK_WIDGET(m_combo); + } + void apply() + { + Scene_EntitySetKeyValue_Selected_Undoable(m_key.c_str(), m_type[gtk_combo_box_get_active(m_combo)].second.c_str()); + } + typedef MemberCaller ApplyCaller; + + void update() + { + const char* value = SelectedEntity_getValueForKey(m_key.c_str()); + ListAttributeType::const_iterator i = m_type.findValue(value); + if(i != m_type.end()) + { + m_nonModal.setActive(m_combo, static_cast(std::distance(m_type.begin(), i))); + } + else + { + m_nonModal.setActive(m_combo, 0); + } + } + typedef MemberCaller UpdateCaller; +}; + + +namespace +{ + GtkWidget* g_entity_split1 = 0; + GtkWidget* g_entity_split2 = 0; + int g_entitysplit1_position; + int g_entitysplit2_position; + + bool g_entityInspector_windowConstructed = false; + + GtkTreeView* g_entityClassList; + GtkTextView* g_entityClassComment; + + GtkCheckButton* g_entitySpawnflagsCheck[MAX_FLAGS]; + + GtkEntry* g_entityKeyEntry; + GtkEntry* g_entityValueEntry; + + GtkListStore* g_entlist_store; + GtkListStore* g_entprops_store; + const EntityClass* g_current_flags = 0; + const EntityClass* g_current_comment = 0; + const EntityClass* g_current_attributes = 0; + + // the number of active spawnflags + int g_spawnflag_count; + // table: index, match spawnflag item to the spawnflag index (i.e. which bit) + int spawn_table[MAX_FLAGS]; + // we change the layout depending on how many spawn flags we need to display + // the table is a 4x4 in which we need to put the comment box g_entityClassComment and the spawn flags.. + GtkTable* g_spawnflagsTable; + + GtkVBox* g_attributeBox = 0; + typedef std::vector EntityAttributes; + EntityAttributes g_entityAttributes; +} + +void GlobalEntityAttributes_clear() +{ + for(EntityAttributes::iterator i = g_entityAttributes.begin(); i != g_entityAttributes.end(); ++i) + { + (*i)->release(); + } + g_entityAttributes.clear(); +} + +class GetKeyValueVisitor : public Entity::Visitor +{ + KeyValues& m_keyvalues; +public: + GetKeyValueVisitor(KeyValues& keyvalues) + : m_keyvalues(keyvalues) + { + } + + void visit(const char* key, const char* value) + { + m_keyvalues.insert(KeyValues::value_type(CopiedString(key), CopiedString(value))); + } + +}; + +void Entity_GetKeyValues(const Entity& entity, KeyValues& keyvalues, KeyValues& defaultValues) +{ + GetKeyValueVisitor visitor(keyvalues); + + entity.forEachKeyValue(visitor); + + const EntityClassAttributes& attributes = entity.getEntityClass().m_attributes; + + for(EntityClassAttributes::const_iterator i = attributes.begin(); i != attributes.end(); ++i) + { + defaultValues.insert(KeyValues::value_type((*i).first, (*i).second.m_value)); + } +} + +void Entity_GetKeyValues_Selected(KeyValues& keyvalues, KeyValues& defaultValues) +{ + class EntityGetKeyValues : public SelectionSystem::Visitor + { + KeyValues& m_keyvalues; + KeyValues& m_defaultValues; + mutable std::set m_visited; + public: + EntityGetKeyValues(KeyValues& keyvalues, KeyValues& defaultValues) + : m_keyvalues(keyvalues), m_defaultValues(defaultValues) + { + } + void visit(scene::Instance& instance) const + { + Entity* entity = Node_getEntity(instance.path().top()); + if(entity == 0 && instance.path().size() != 1) + { + entity = Node_getEntity(instance.path().parent()); + } + if(entity != 0 && m_visited.insert(entity).second) + { + Entity_GetKeyValues(*entity, m_keyvalues, m_defaultValues); + } + } + } visitor(keyvalues, defaultValues); + GlobalSelectionSystem().foreachSelected(visitor); +} + +const char* keyvalues_valueforkey(KeyValues& keyvalues, const char* key) +{ + KeyValues::iterator i = keyvalues.find(CopiedString(key)); + if(i != keyvalues.end()) + return (*i).second.c_str(); + return ""; +} + +class EntityClassListStoreAppend : public EntityClassVisitor +{ + GtkListStore* store; +public: + EntityClassListStoreAppend(GtkListStore* store_) : store(store_) + { + } + void visit(EntityClass* e) + { + GtkTreeIter iter; + gtk_list_store_append(store, &iter); + gtk_list_store_set(store, &iter, 0, e->name(), 1, e, -1); + } +}; + +void EntityClassList_fill() +{ + EntityClassListStoreAppend append(g_entlist_store); + GlobalEntityClassManager().forEach(append); +} + +void EntityClassList_clear() +{ + gtk_list_store_clear(g_entlist_store); +} + +void SetComment(EntityClass* eclass) +{ + if(eclass == g_current_comment) + return; + + g_current_comment = eclass; + + GtkTextBuffer* buffer = gtk_text_view_get_buffer(g_entityClassComment); + gtk_text_buffer_set_text(buffer, eclass->comments(), -1); +} + +void SurfaceFlags_setEntityClass(EntityClass* eclass) +{ + if(eclass == g_current_flags) + return; + + g_current_flags = eclass; + + int spawnflag_count = 0; + + { + // do a first pass to count the spawn flags, don't touch the widgets, we don't know in what state they are + for (int i=0 ; iflagnames[i] && eclass->flagnames[i][0] != 0 && strcmp(eclass->flagnames[i],"-")) + { + spawn_table[spawnflag_count] = i; + spawnflag_count++; + } + } + } + + // disable all remaining boxes + // NOTE: these boxes might not even be on display + { + for (int i = 0; i < g_spawnflag_count; ++i) + { + GtkWidget* widget = GTK_WIDGET(g_entitySpawnflagsCheck[i]); + gtk_label_set_text(GTK_LABEL(GTK_BIN(widget)->child), " "); + gtk_widget_hide(widget); + gtk_widget_ref(widget); + gtk_container_remove(GTK_CONTAINER(g_spawnflagsTable), widget); + } + } + + g_spawnflag_count = spawnflag_count; + + { + for (int i = 0; i < g_spawnflag_count; ++i) + { + GtkWidget* widget = GTK_WIDGET(g_entitySpawnflagsCheck[i]); + gtk_widget_show (widget); + + StringOutputStream str(16); + str << LowerCase(eclass->flagnames[spawn_table[i]]); + + gtk_table_attach(g_spawnflagsTable, widget, i%4, i%4+1, i/4, i/4+1, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(GTK_FILL), 0, 0); + gtk_widget_unref(widget); + + gtk_label_set_text(GTK_LABEL(GTK_BIN(widget)->child), str.c_str()); + } + } +} + +void EntityClassList_selectEntityClass(EntityClass* eclass) +{ + GtkTreeModel* model = GTK_TREE_MODEL(g_entlist_store); + GtkTreeIter iter; + for(gboolean good = gtk_tree_model_get_iter_first(model, &iter); good != FALSE; good = gtk_tree_model_iter_next(model, &iter)) + { + char* text; + gtk_tree_model_get(model, &iter, 0, &text, -1); + if (strcmp (text, eclass->name()) == 0) + { + GtkTreeView* view = g_entityClassList; + GtkTreePath* path = gtk_tree_model_get_path(model, &iter); + gtk_tree_selection_select_path(gtk_tree_view_get_selection(view), path); + if(GTK_WIDGET_REALIZED(view)) + { + gtk_tree_view_scroll_to_cell(view, path, 0, FALSE, 0, 0); + } + gtk_tree_path_free(path); + good = FALSE; + } + g_free(text); + } +} + +void EntityInspector_appendAttribute(const char* name, EntityAttribute& attribute) +{ + GtkTable* row = DialogRow_new(name, attribute.getWidget()); + DialogVBox_packRow(g_attributeBox, GTK_WIDGET(row)); +} + + +template +class StatelessAttributeCreator +{ +public: + static EntityAttribute* create(const char* name) + { + return new Attribute(name); + } +}; + +class EntityAttributeFactory +{ + typedef EntityAttribute* (*CreateFunc)(const char* name); + typedef std::map Creators; + Creators m_creators; +public: + EntityAttributeFactory() + { + m_creators.insert(Creators::value_type("string", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("color", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("integer", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("real", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("shader", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("boolean", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("angle", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("direction", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("angles", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("model", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("sound", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("vector3", &StatelessAttributeCreator::create)); + m_creators.insert(Creators::value_type("real3", &StatelessAttributeCreator::create)); + } + EntityAttribute* create(const char* type, const char* name) + { + Creators::iterator i = m_creators.find(type); + if(i != m_creators.end()) + { + return (*i).second(name); + } + const ListAttributeType* listType = GlobalEntityClassManager().findListType(type); + if(listType != 0) + { + return new ListAttribute(name, *listType); + } + return 0; + } +}; + +typedef Static GlobalEntityAttributeFactory; + +void EntityInspector_setEntityClass(EntityClass *eclass) +{ + EntityClassList_selectEntityClass(eclass); + SurfaceFlags_setEntityClass(eclass); + + if(eclass != g_current_attributes) + { + g_current_attributes = eclass; + + container_remove_all(GTK_CONTAINER(g_attributeBox)); + GlobalEntityAttributes_clear(); + + for(EntityClassAttributes::const_iterator i = eclass->m_attributes.begin(); i != eclass->m_attributes.end(); ++i) + { + EntityAttribute* attribute = GlobalEntityAttributeFactory::instance().create((*i).second.m_type.c_str(), (*i).first.c_str()); + if(attribute != 0) + { + g_entityAttributes.push_back(attribute); + EntityInspector_appendAttribute(EntityClassAttributePair_getName(*i), *g_entityAttributes.back()); + } + } + } +} + +void EntityInspector_updateSpawnflags() +{ + { + int f = atoi(SelectedEntity_getValueForKey("spawnflags")); + for (int i = 0; i < g_spawnflag_count; ++i) + { + int v = !!(f&(1<update(); + } +} + +class EntityInspectorDraw +{ + IdleDraw m_idleDraw; +public: + EntityInspectorDraw() : m_idleDraw(FreeCaller()) + { + } + void queueDraw() + { + m_idleDraw.queueDraw(); + } +}; + +EntityInspectorDraw g_EntityInspectorDraw; + + +void EntityInspector_keyValueChanged() +{ + g_EntityInspectorDraw.queueDraw(); +} +void EntityInspector_selectionChanged(const Selectable&) +{ + EntityInspector_keyValueChanged(); +} + +// Creates a new entity based on the currently selected brush and entity type. +// +void EntityClassList_createEntity() +{ + GtkTreeView* view = g_entityClassList; + + // find out what type of entity we are trying to create + GtkTreeModel* model; + GtkTreeIter iter; + if(gtk_tree_selection_get_selected(gtk_tree_view_get_selection(view), &model, &iter) == FALSE) + { + gtk_MessageBox(gtk_widget_get_toplevel(GTK_WIDGET(g_entityClassList)), "You must have a selected class to create an entity", "info"); + return; + } + + char* text; + gtk_tree_model_get(model, &iter, 0, &text, -1); + + { + StringOutputStream command; + command << "entityCreate -class " << text; + + UndoableCommand undo(command.c_str()); + + Entity_createFromSelection(text, g_vector3_identity); + } + g_free(text); +} + +void EntityInspector_applyKeyValue() +{ + // Get current selection text + StringOutputStream key(64); + key << gtk_entry_get_text(g_entityKeyEntry); + StringOutputStream value(64); + value << gtk_entry_get_text(g_entityValueEntry); + + + // TTimo: if you change the classname to worldspawn you won't merge back in the structural brushes but create a parasite entity + if (!strcmp(key.c_str(), "classname") && !strcmp(value.c_str(), "worldspawn")) + { + gtk_MessageBox(gtk_widget_get_toplevel(GTK_WIDGET(g_entityKeyEntry)), "Cannot change \"classname\" key back to worldspawn.", 0, eMB_OK ); + return; + } + + + // RR2DO2: we don't want spaces in entity keys + if (strstr( key.c_str(), " " )) + { + gtk_MessageBox(gtk_widget_get_toplevel(GTK_WIDGET(g_entityKeyEntry)), "No spaces are allowed in entity keys.", 0, eMB_OK ); + return; + } + + if(strcmp(key.c_str(), "classname") == 0) + { + StringOutputStream command; + command << "entitySetClass -class " << value.c_str(); + UndoableCommand undo(command.c_str()); + Scene_EntitySetClassname_Selected(value.c_str()); + } + else + { + Scene_EntitySetKeyValue_Selected_Undoable(key.c_str(), value.c_str()); + } +} + +void EntityInspector_clearKeyValue() +{ + // Get current selection text + StringOutputStream key(64); + key << gtk_entry_get_text(g_entityKeyEntry); + + if(strcmp(key.c_str(), "classname") != 0) + { + StringOutputStream command; + command << "entityDeleteKey -key " << key.c_str(); + UndoableCommand undo(command.c_str()); + Scene_EntitySetKeyValue_Selected(key.c_str(), ""); + } +} + +void EntityInspector_clearAllKeyValues() +{ + UndoableCommand undo("entityClear"); + + // remove all keys except classname + for(KeyValues::iterator i = g_selectedKeyValues.begin(); i != g_selectedKeyValues.end(); ++i) + { + if(strcmp((*i).first.c_str(), "classname") != 0) + { + Scene_EntitySetKeyValue_Selected((*i).first.c_str(), ""); + } + } +} + +// ============================================================================= +// callbacks + +static void EntityClassList_selection_changed(GtkTreeSelection* selection, gpointer data) +{ + GtkTreeModel* model; + GtkTreeIter selected; + if(gtk_tree_selection_get_selected(selection, &model, &selected)) + { + EntityClass* eclass; + gtk_tree_model_get(model, &selected, 1, &eclass, -1); + if(eclass != 0) + { + SetComment(eclass); + } + } +} + +static gint EntityClassList_button_press(GtkWidget *widget, GdkEventButton *event, gpointer data) +{ + if (event->type == GDK_2BUTTON_PRESS) + { + EntityClassList_createEntity(); + return TRUE; + } + return FALSE; +} + +static gint EntityClassList_keypress(GtkWidget* widget, GdkEventKey* event, gpointer data) +{ + unsigned int code = gdk_keyval_to_upper (event->keyval); + + if (event->keyval == GDK_Return) + { + EntityClassList_createEntity(); + return TRUE; + } + + // select the entity that starts with the key pressed + if (code <= 'Z' && code >= 'A') + { + GtkTreeView* view = g_entityClassList; + GtkTreeModel* model; + GtkTreeIter iter; + if(gtk_tree_selection_get_selected(gtk_tree_view_get_selection(view), &model, &iter) == FALSE + || gtk_tree_model_iter_next(model, &iter) == FALSE) + { + gtk_tree_model_get_iter_first(model, &iter); + } + + for(std::size_t count = gtk_tree_model_iter_n_children(model, 0); count > 0; --count) + { + char* text; + gtk_tree_model_get(model, &iter, 0, &text, -1); + + if (toupper (text[0]) == (int)code) + { + GtkTreePath* path = gtk_tree_model_get_path(model, &iter); + gtk_tree_selection_select_path(gtk_tree_view_get_selection(view), path); + if(GTK_WIDGET_REALIZED(view)) + { + gtk_tree_view_scroll_to_cell(view, path, 0, FALSE, 0, 0); + } + gtk_tree_path_free(path); + count = 1; + } + + g_free(text); + + if(gtk_tree_model_iter_next(model, &iter) == FALSE) + gtk_tree_model_get_iter_first(model, &iter); + } + + return TRUE; + } + return FALSE; +} + +static void EntityProperties_selection_changed(GtkTreeSelection* selection, gpointer data) +{ + // find out what type of entity we are trying to create + GtkTreeModel* model; + GtkTreeIter iter; + if(gtk_tree_selection_get_selected(selection, &model, &iter) == FALSE) + { + return; + } + + char* key; + char* val; + gtk_tree_model_get(model, &iter, 0, &key, 1, &val, -1); + + gtk_entry_set_text(g_entityKeyEntry, key); + gtk_entry_set_text(g_entityValueEntry, val); + + g_free(key); + g_free(val); +} + +static void SpawnflagCheck_toggled(GtkWidget *widget, gpointer data) +{ + EntityInspector_applySpawnflags(); +} + +static gint EntityEntry_keypress(GtkEntry* widget, GdkEventKey* event, gpointer data) +{ + if (event->keyval == GDK_Return) + { + if(widget == g_entityKeyEntry) + { + gtk_entry_set_text(g_entityValueEntry, ""); + gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(widget))), GTK_WIDGET(g_entityValueEntry)); + } + else + { + EntityInspector_applyKeyValue(); + } + return TRUE; + } + if (event->keyval == GDK_Escape) + { + gtk_window_set_focus(GTK_WINDOW(gtk_widget_get_toplevel(GTK_WIDGET(widget))), NULL); + return TRUE; + } + + return FALSE; +} + +void EntityInspector_destroyWindow(GtkWidget* widget, gpointer data) +{ + g_entitysplit1_position = gtk_paned_get_position(GTK_PANED(g_entity_split1)); + g_entitysplit2_position = gtk_paned_get_position(GTK_PANED(g_entity_split2)); + + g_entityInspector_windowConstructed = false; + GlobalEntityAttributes_clear(); +} + +GtkWidget* EntityInspector_constructWindow(GtkWindow* toplevel) +{ + GtkWidget* vbox = gtk_vbox_new(FALSE, 2); + gtk_widget_show (vbox); + gtk_container_set_border_width(GTK_CONTAINER (vbox), 2); + + g_signal_connect(G_OBJECT(vbox), "destroy", G_CALLBACK(EntityInspector_destroyWindow), 0); + + { + GtkWidget* split1 = gtk_vpaned_new(); + gtk_box_pack_start(GTK_BOX(vbox), split1, TRUE, TRUE, 0); + gtk_widget_show (split1); + + g_entity_split1 = split1; + + { + GtkWidget* split2 = gtk_vpaned_new(); + gtk_paned_add1 (GTK_PANED (split1), split2); + gtk_widget_show (split2); + + g_entity_split2 = split2; + + { + // class list + GtkWidget* scr = gtk_scrolled_window_new (0, 0); + gtk_widget_show (scr); + gtk_paned_add1 (GTK_PANED (split2), scr); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); + + { + GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_POINTER); + + GtkTreeView* view = GTK_TREE_VIEW(gtk_tree_view_new_with_model(GTK_TREE_MODEL(store))); + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), FALSE); + gtk_tree_view_set_headers_visible(view, FALSE); + g_signal_connect(G_OBJECT(view), "button_press_event", G_CALLBACK(EntityClassList_button_press), 0); + g_signal_connect(G_OBJECT(view), "key_press_event", G_CALLBACK(EntityClassList_keypress), 0); + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Key", renderer, "text", 0, 0); + gtk_tree_view_append_column(view, column); + } + + { + GtkTreeSelection* selection = gtk_tree_view_get_selection(view); + g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(EntityClassList_selection_changed), 0); + } + + gtk_widget_show(GTK_WIDGET(view)); + + gtk_container_add(GTK_CONTAINER(scr), GTK_WIDGET(view)); + + g_object_unref(G_OBJECT(store)); + g_entityClassList = view; + g_entlist_store = store; + } + } + + { + GtkWidget* scr = gtk_scrolled_window_new (0, 0); + gtk_widget_show (scr); + gtk_paned_add2 (GTK_PANED (split2), scr); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); + + { + GtkTextView* text = GTK_TEXT_VIEW(gtk_text_view_new()); + gtk_widget_set_size_request(GTK_WIDGET(text), 0, -1); // allow shrinking + gtk_text_view_set_wrap_mode(text, GTK_WRAP_WORD); + gtk_text_view_set_editable(text, FALSE); + gtk_widget_show(GTK_WIDGET(text)); + gtk_container_add(GTK_CONTAINER(scr), GTK_WIDGET(text)); + g_entityClassComment = text; + } + } + } + + { + GtkWidget* split2 = gtk_vpaned_new(); + gtk_paned_add2 (GTK_PANED (split1), split2); + gtk_widget_show(split2); + + { + GtkWidget* vbox2 = gtk_vbox_new (FALSE, 2); + gtk_widget_show (vbox2); + gtk_paned_pack1(GTK_PANED(split2), vbox2, FALSE, FALSE); + + { + // Spawnflags (4 colums wide max, or window gets too wide.) + GtkTable* table = GTK_TABLE(gtk_table_new(4, 4, FALSE)); + gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(table), FALSE, TRUE, 0); + gtk_widget_show(GTK_WIDGET(table)); + + g_spawnflagsTable = table; + + for (int i = 0; i < MAX_FLAGS; i++) + { + GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new_with_label("")); + gtk_widget_ref(GTK_WIDGET(check)); + g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(check), "toggled", G_CALLBACK(SpawnflagCheck_toggled), 0))); + g_entitySpawnflagsCheck[i] = check; + } + } + + { + // key/value list + GtkWidget* scr = gtk_scrolled_window_new (0, 0); + gtk_widget_show (scr); + gtk_box_pack_start (GTK_BOX (vbox2), scr, TRUE, TRUE, 0); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); + + { + GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_STRING); + + GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(view), FALSE); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, 0); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + } + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 1, 0); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + } + + { + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); + g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(EntityProperties_selection_changed), 0); + } + + gtk_widget_show(view); + + gtk_container_add(GTK_CONTAINER (scr), view); + + g_object_unref(G_OBJECT(store)); + + g_entprops_store = store; + } + } + + { + // key/value entry + GtkTable* table = GTK_TABLE(gtk_table_new(2, 2, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(table), FALSE, TRUE, 0); + gtk_table_set_row_spacings(table, 3); + gtk_table_set_col_spacings(table, 5); + + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_events(GTK_WIDGET(entry), GDK_KEY_PRESS_MASK); + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(EntityEntry_keypress), 0); + g_entityKeyEntry = entry; + } + + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_events(GTK_WIDGET(entry), GDK_KEY_PRESS_MASK); + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(EntityEntry_keypress), 0); + g_entityValueEntry = entry; + } + + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Value")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Key")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + } + + { + GtkBox* hbox = GTK_BOX(gtk_hbox_new(TRUE, 4)); + gtk_widget_show(GTK_WIDGET(hbox)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(hbox), FALSE, TRUE, 0); + + { + GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Clear All")); + gtk_widget_show(GTK_WIDGET(button)); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(EntityInspector_clearAllKeyValues), 0); + gtk_box_pack_start(hbox, GTK_WIDGET(button), TRUE, TRUE, 0); + } + { + GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Delete Key")); + gtk_widget_show(GTK_WIDGET(button)); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(EntityInspector_clearKeyValue), 0); + gtk_box_pack_start(hbox, GTK_WIDGET(button), TRUE, TRUE, 0); + } + } + } + + { + GtkWidget* scr = gtk_scrolled_window_new(0, 0); + gtk_widget_show(scr); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scr), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + + GtkWidget* viewport = gtk_viewport_new(0, 0); + gtk_widget_show(viewport); + gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE); + + g_attributeBox = GTK_VBOX(gtk_vbox_new(FALSE, 2)); + gtk_widget_show(GTK_WIDGET(g_attributeBox)); + + gtk_container_add(GTK_CONTAINER(viewport), GTK_WIDGET(g_attributeBox)); + gtk_container_add(GTK_CONTAINER(scr), viewport); + gtk_paned_pack2(GTK_PANED(split2), scr, FALSE, FALSE); + } + } + } + + + { + // show the sliders in any case + if(g_entitysplit2_position > 22) + { + gtk_paned_set_position (GTK_PANED(g_entity_split2), g_entitysplit2_position); + } else { + g_entitysplit2_position = 22; + gtk_paned_set_position (GTK_PANED(g_entity_split2), 22); + } + if((g_entitysplit1_position - g_entitysplit2_position) > 27) + { + gtk_paned_set_position (GTK_PANED(g_entity_split1), g_entitysplit1_position); + } else { + gtk_paned_set_position (GTK_PANED(g_entity_split1), g_entitysplit2_position + 27); + } + } + + g_entityInspector_windowConstructed = true; + EntityClassList_fill(); + + typedef FreeCaller1 EntityInspectorSelectionChangedCaller; + GlobalSelectionSystem().addSelectionChangeCallback(EntityInspectorSelectionChangedCaller()); + GlobalEntityCreator().setKeyValueChangedFunc(EntityInspector_keyValueChanged); + + // hack + gtk_container_set_focus_chain(GTK_CONTAINER(vbox), NULL); + + return vbox; +} + +class EntityInspector : public ModuleObserver +{ + std::size_t m_unrealised; +public: + EntityInspector() : m_unrealised(1) + { + } + void realise() + { + if(--m_unrealised == 0) + { + if(g_entityInspector_windowConstructed) + { + //globalOutputStream() << "Entity Inspector: realise\n"; + EntityClassList_fill(); + } + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + if(g_entityInspector_windowConstructed) + { + //globalOutputStream() << "Entity Inspector: unrealise\n"; + EntityClassList_clear(); + } + } + } +}; + +EntityInspector g_EntityInspector; + +#include "preferencesystem.h" +#include "stringio.h" + +void EntityInspector_construct() +{ + GlobalEntityClassManager().attach(g_EntityInspector); + + GlobalPreferenceSystem().registerPreference("EntitySplit1", IntImportStringCaller(g_entitysplit1_position), IntExportStringCaller(g_entitysplit1_position)); + GlobalPreferenceSystem().registerPreference("EntitySplit2", IntImportStringCaller(g_entitysplit2_position), IntExportStringCaller(g_entitysplit2_position)); + +} + +void EntityInspector_destroy() +{ + GlobalEntityClassManager().detach(g_EntityInspector); +} + diff --git a/misc/mediasource/netradiant-src/radiant/entityinspector.h b/misc/mediasource/netradiant-src/radiant/entityinspector.h new file mode 100644 index 00000000..62a69ab6 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/entityinspector.h @@ -0,0 +1,31 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_ENTITYINSPECTOR_H) +#define INCLUDED_ENTITYINSPECTOR_H + +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; +GtkWidget* EntityInspector_constructWindow(GtkWindow* parent); +void EntityInspector_construct(); +void EntityInspector_destroy(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/entitylist.cpp b/misc/mediasource/netradiant-src/radiant/entitylist.cpp new file mode 100644 index 00000000..e6944a6d --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/entitylist.cpp @@ -0,0 +1,430 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "entitylist.h" + +#include "iselection.h" + +#include +#include +#include +#include + +#include "string/string.h" +#include "scenelib.h" +#include "nameable.h" +#include "signal/isignal.h" +#include "generic/object.h" + +#include "gtkutil/widget.h" +#include "gtkutil/window.h" +#include "gtkutil/idledraw.h" +#include "gtkutil/accelerator.h" +#include "gtkutil/closure.h" + +#include "treemodel.h" + +void RedrawEntityList(); +typedef FreeCaller RedrawEntityListCaller; + +typedef struct _GtkTreeView GtkTreeView; + +class EntityList +{ +public: + enum EDirty + { + eDefault, + eSelection, + eInsertRemove, + }; + + EDirty m_dirty; + + IdleDraw m_idleDraw; + WindowPositionTracker m_positionTracker; + + GtkWindow* m_window; + GtkTreeView* m_tree_view; + GraphTreeModel* m_tree_model; + bool m_selection_disabled; + + EntityList() : + m_dirty(EntityList::eDefault), + m_idleDraw(RedrawEntityListCaller()), + m_window(0), + m_selection_disabled(false) + { + } + + bool visible() const + { + return GTK_WIDGET_VISIBLE(GTK_WIDGET(m_window)); + } +}; + +namespace +{ + EntityList* g_EntityList; + + inline EntityList& getEntityList() + { + ASSERT_NOTNULL(g_EntityList); + return *g_EntityList; + } +} + + +inline Nameable* Node_getNameable(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +const char* node_get_name(scene::Node& node) +{ + Nameable* nameable = Node_getNameable(node); + return (nameable != 0) + ? nameable->name() + : "node"; +} + +template +inline void gtk_tree_model_get_pointer(GtkTreeModel* model, GtkTreeIter* iter, gint column, value_type** pointer) +{ + GValue value = GValue_default(); + gtk_tree_model_get_value(model, iter, column, &value); + *pointer = (value_type*)g_value_get_pointer(&value); +} + + + +void entitylist_treeviewcolumn_celldatafunc(GtkTreeViewColumn* column, GtkCellRenderer* renderer, GtkTreeModel* model, GtkTreeIter* iter, gpointer data) +{ + scene::Node* node; + gtk_tree_model_get_pointer(model, iter, 0, &node); + scene::Instance* instance; + gtk_tree_model_get_pointer(model, iter, 1, &instance); + if(node != 0) + { + gtk_cell_renderer_set_fixed_size(renderer, -1, -1); + char* name = const_cast(node_get_name(*node)); + g_object_set(G_OBJECT(renderer), "text", name, "visible", TRUE, 0); + + //globalOutputStream() << "rendering cell " << makeQuoted(name) << "\n"; + GtkStyle* style = gtk_widget_get_style(GTK_WIDGET(getEntityList().m_tree_view)); + if(instance->childSelected()) + { + g_object_set(G_OBJECT(renderer), "cell-background-gdk", &style->base[GTK_STATE_ACTIVE], 0); + } + else + { + g_object_set(G_OBJECT(renderer), "cell-background-gdk", &style->base[GTK_STATE_NORMAL], 0); + } + } + else + { + gtk_cell_renderer_set_fixed_size(renderer, -1, 0); + g_object_set(G_OBJECT(renderer), "text", "", "visible", FALSE, 0); + } +} + +static gboolean entitylist_tree_select(GtkTreeSelection *selection, GtkTreeModel *model, GtkTreePath *path, gboolean path_currently_selected, gpointer data) +{ + GtkTreeIter iter; + gtk_tree_model_get_iter(model, &iter, path); + scene::Node* node; + gtk_tree_model_get_pointer(model, &iter, 0, &node); + scene::Instance* instance; + gtk_tree_model_get_pointer(model, &iter, 1, &instance); + Selectable* selectable = Instance_getSelectable(*instance); + + if(node == 0) + { + if(path_currently_selected != FALSE) + { + getEntityList().m_selection_disabled = true; + GlobalSelectionSystem().setSelectedAll(false); + getEntityList().m_selection_disabled = false; + } + } + else if(selectable != 0) + { + getEntityList().m_selection_disabled = true; + selectable->setSelected(path_currently_selected == FALSE); + getEntityList().m_selection_disabled = false; + return TRUE; + } + + return FALSE; +} + +static gboolean entitylist_tree_select_null(GtkTreeSelection *selection, GtkTreeModel *model, GtkTreePath *path, gboolean path_currently_selected, gpointer data) +{ + return TRUE; +} + +void EntityList_ConnectSignals(GtkTreeView* view) +{ + GtkTreeSelection* select = gtk_tree_view_get_selection(view); + gtk_tree_selection_set_select_function(select, entitylist_tree_select, NULL, 0); +} + +void EntityList_DisconnectSignals(GtkTreeView* view) +{ + GtkTreeSelection* select = gtk_tree_view_get_selection(view); + gtk_tree_selection_set_select_function(select, entitylist_tree_select_null, 0, 0); +} + + + +gboolean treemodel_update_selection(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, gpointer data) +{ + GtkTreeView* view = reinterpret_cast(data); + + scene::Instance* instance; + gtk_tree_model_get_pointer(model, iter, 1, &instance); + Selectable* selectable = Instance_getSelectable(*instance); + + if(selectable != 0) + { + GtkTreeSelection* selection = gtk_tree_view_get_selection(view); + if(selectable->isSelected()) + { + gtk_tree_selection_select_path(selection, path); + } + else + { + gtk_tree_selection_unselect_path(selection, path); + } + } + + return FALSE; +} + +void EntityList_UpdateSelection(GtkTreeModel* model, GtkTreeView* view) +{ + EntityList_DisconnectSignals(view); + gtk_tree_model_foreach(model, treemodel_update_selection, view); + EntityList_ConnectSignals(view); +} + + +void RedrawEntityList() +{ + switch(getEntityList().m_dirty) + { + case EntityList::eInsertRemove: + case EntityList::eSelection: + EntityList_UpdateSelection(GTK_TREE_MODEL(getEntityList().m_tree_model), getEntityList().m_tree_view); + default: + break; + } + getEntityList().m_dirty = EntityList::eDefault; +} + +void entitylist_queue_draw() +{ + getEntityList().m_idleDraw.queueDraw(); +} + +void EntityList_SelectionUpdate() +{ + if(getEntityList().m_selection_disabled) + return; + + if(getEntityList().m_dirty < EntityList::eSelection) + getEntityList().m_dirty = EntityList::eSelection; + entitylist_queue_draw(); +} + +void EntityList_SelectionChanged(const Selectable& selectable) +{ + EntityList_SelectionUpdate(); +} + +void entitylist_treeview_rowcollapsed(GtkTreeView* view, GtkTreeIter* iter, GtkTreePath* path, gpointer user_data) +{ +} + +void entitylist_treeview_row_expanded(GtkTreeView* view, GtkTreeIter* iter, GtkTreePath* path, gpointer user_data) +{ + EntityList_SelectionUpdate(); +} + + +void EntityList_SetShown(bool shown) +{ + widget_set_visible(GTK_WIDGET(getEntityList().m_window), shown); +} + +void EntityList_toggleShown() +{ + EntityList_SetShown(!getEntityList().visible()); +} + +gint graph_tree_model_compare_name(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b, gpointer user_data) +{ + scene::Node* first; + gtk_tree_model_get(model, a, 0, (gpointer*)&first, -1); + scene::Node* second; + gtk_tree_model_get(model, b, 0, (gpointer*)&second, -1); + int result = 0; + if(first != 0 && second != 0) + { + result = string_compare(node_get_name(*first), node_get_name(*second)); + } + if(result == 0) + { + return (first < second) ? -1 : (second < first) ? 1 : 0; + } + return result; +} + +extern GraphTreeModel* scene_graph_get_tree_model(); +void AttachEntityTreeModel() +{ + getEntityList().m_tree_model = scene_graph_get_tree_model(); + + gtk_tree_view_set_model(getEntityList().m_tree_view, GTK_TREE_MODEL(getEntityList().m_tree_model)); +} + +void DetachEntityTreeModel() +{ + getEntityList().m_tree_model = 0; + + gtk_tree_view_set_model(getEntityList().m_tree_view, 0); +} + +void EntityList_constructWindow(GtkWindow* main_window) +{ + ASSERT_MESSAGE(getEntityList().m_window == 0, "error"); + + GtkWindow* window = create_persistent_floating_window("Entity List", main_window); + + gtk_window_add_accel_group(window, global_accel); + + getEntityList().m_positionTracker.connect(window); + + + getEntityList().m_window = window; + + { + GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(scr)); + + { + GtkWidget* view = gtk_tree_view_new(); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); + + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new(); + gtk_tree_view_column_pack_start(column, renderer, TRUE); + gtk_tree_view_column_set_cell_data_func(column, renderer, entitylist_treeviewcolumn_celldatafunc, 0, 0); + + GtkTreeSelection* select = gtk_tree_view_get_selection (GTK_TREE_VIEW(view)); + gtk_tree_selection_set_mode(select, GTK_SELECTION_MULTIPLE); + + g_signal_connect(G_OBJECT(view), "row_expanded", G_CALLBACK(entitylist_treeview_row_expanded), 0); + g_signal_connect(G_OBJECT(view), "row_collapsed", G_CALLBACK(entitylist_treeview_rowcollapsed), 0); + + gtk_tree_view_append_column (GTK_TREE_VIEW (view), column); + + gtk_widget_show(view); + gtk_container_add (GTK_CONTAINER(scr), view); + getEntityList().m_tree_view = GTK_TREE_VIEW(view); + } + } + + EntityList_ConnectSignals(getEntityList().m_tree_view); + AttachEntityTreeModel(); +} + +void EntityList_destroyWindow() +{ + DetachEntityTreeModel(); + EntityList_DisconnectSignals(getEntityList().m_tree_view); + destroy_floating_window(getEntityList().m_window); +} + +#include "preferencesystem.h" + +#include "iselection.h" + +namespace +{ + scene::Node* nullNode = 0; +} + +class NullSelectedInstance : public scene::Instance, public Selectable +{ + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts() + { + InstanceStaticCast::install(m_casts); + } + InstanceTypeCastTable& get() + { + return m_casts; + } + }; + +public: + typedef LazyStatic StaticTypeCasts; + + NullSelectedInstance() : Instance(scene::Path(makeReference(*nullNode)), 0, this, StaticTypeCasts::instance().get()) + { + } + + void setSelected(bool select) + { + ERROR_MESSAGE("error"); + } + bool isSelected() const + { + return true; + } +}; + +typedef LazyStatic StaticNullSelectedInstance; + + +void EntityList_Construct() +{ + graph_tree_model_insert(scene_graph_get_tree_model(), StaticNullSelectedInstance::instance()); + + g_EntityList = new EntityList; + + getEntityList().m_positionTracker.setPosition(c_default_window_pos); + + GlobalPreferenceSystem().registerPreference("EntityInfoDlg", WindowPositionTrackerImportStringCaller(getEntityList().m_positionTracker), WindowPositionTrackerExportStringCaller(getEntityList().m_positionTracker)); + + typedef FreeCaller1 EntityListSelectionChangedCaller; + GlobalSelectionSystem().addSelectionChangeCallback(EntityListSelectionChangedCaller()); +} +void EntityList_Destroy() +{ + delete g_EntityList; + + graph_tree_model_erase(scene_graph_get_tree_model(), StaticNullSelectedInstance::instance()); +} diff --git a/misc/mediasource/netradiant-src/radiant/entitylist.h b/misc/mediasource/netradiant-src/radiant/entitylist.h new file mode 100644 index 00000000..cdad18db --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/entitylist.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ENTITYLIST_H) +#define INCLUDED_ENTITYLIST_H + +void EntityList_Construct(); +void EntityList_Destroy(); + +typedef struct _GtkWindow GtkWindow; +void EntityList_constructWindow(GtkWindow* main_window); +void EntityList_destroyWindow(); +void EntityList_toggleShown(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/environment.cpp b/misc/mediasource/netradiant-src/radiant/environment.cpp new file mode 100644 index 00000000..04033579 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/environment.cpp @@ -0,0 +1,312 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "environment.h" + +#include "stream/textstream.h" +#include "string/string.h" +#include "stream/stringstream.h" +#include "debugging/debugging.h" +#include "os/path.h" +#include "os/file.h" +#include "cmdlib.h" + +int g_argc; +char** g_argv; + +void args_init(int argc, char* argv[]) +{ + int i, j, k; + + for (i = 1; i < argc; i++) + { + for (k = i; k < argc; k++) + if (argv[k] != 0) + break; + + if (k > i) + { + k -= i; + for (j = i + k; j < argc; j++) + argv[j-k] = argv[j]; + argc -= k; + } + } + + g_argc = argc; + g_argv = argv; +} + +char *gamedetect_argv_buffer[1024]; +void gamedetect_found_game(char *game, char *path) +{ + int argc; + static char buf[128]; + + if(g_argv == gamedetect_argv_buffer) + return; + + globalOutputStream() << "Detected game " << game << " in " << path << "\n"; + + sprintf(buf, "-%s-EnginePath", game); + argc = 0; + gamedetect_argv_buffer[argc++] = "-global-gamefile"; + gamedetect_argv_buffer[argc++] = game; + gamedetect_argv_buffer[argc++] = buf; + gamedetect_argv_buffer[argc++] = path; + if((size_t) (argc + g_argc) >= sizeof(gamedetect_argv_buffer) / sizeof(*gamedetect_argv_buffer) - 1) + g_argc = sizeof(gamedetect_argv_buffer) / sizeof(*gamedetect_argv_buffer) - g_argc - 1; + memcpy(gamedetect_argv_buffer + 4, g_argv, sizeof(*gamedetect_argv_buffer) * g_argc); + g_argc += argc; + g_argv = gamedetect_argv_buffer; +} + +bool gamedetect_check_game(char *gamefile, const char *checkfile1, const char *checkfile2, char *buf /* must have 64 bytes free after bufpos */, int bufpos) +{ + buf[bufpos] = '/'; + + strcpy(buf + bufpos + 1, checkfile1); + globalOutputStream() << "Checking for a game file in " << buf << "\n"; + if(!file_exists(buf)) + return false; + + if(checkfile2) + { + strcpy(buf + bufpos + 1, checkfile2); + globalOutputStream() << "Checking for a game file in " << buf << "\n"; + if(!file_exists(buf)) + return false; + } + + buf[bufpos + 1] = 0; + gamedetect_found_game(gamefile, buf); + return true; +} + +void gamedetect() +{ + // if we're inside a Nexuiz install + // default to nexuiz.game (unless the user used an option to inhibit this) + bool nogamedetect = false; + int i; + for(i = 1; i < g_argc - 1; ++i) + if(g_argv[i][0] == '-') + { + if(!strcmp(g_argv[i], "-gamedetect")) + nogamedetect = !strcmp(g_argv[i+1], "false"); + ++i; + } + if(!nogamedetect) + { + static char buf[1024 + 64]; + strncpy(buf, environment_get_app_path(), sizeof(buf)); + buf[sizeof(buf) - 1 - 64] = 0; + if(!strlen(buf)) + return; + + char *p = buf + strlen(buf) - 1; // point directly on the slash of get_app_path + while(p != buf) + { + // TODO add more games to this + + // try to detect Nexuiz installs +#if defined(WIN32) + if(gamedetect_check_game("nexuiz.game", "data/common-spog.pk3", "nexuiz.exe", buf, p - buf)) +#elif defined(__APPLE__) + if(gamedetect_check_game("nexuiz.game", "data/common-spog.pk3", "Nexuiz.app/Contents/Info.plist", buf, p - buf)) +#else + if(gamedetect_check_game("nexuiz.game", "data/common-spog.pk3", "nexuiz-linux-glx.sh", buf, p - buf)) +#endif + return; + + // try to detect Q2World installs + if(gamedetect_check_game("q2w.game", "default/quake2world.version", NULL, buf, p - buf)) + return; + + // try to detect Warsow installs + if(gamedetect_check_game("warsow.game", "basewsw/dedicated_autoexec.cfg", NULL, buf, p - buf)) + return; + + // we found nothing + // go backwards + --p; + while(p != buf && *p != '/' && *p != '\\') + --p; + } + } +} + +namespace +{ + CopiedString home_path; + CopiedString app_path; +} + +const char* environment_get_home_path() +{ + return home_path.c_str(); +} + +const char* environment_get_app_path() +{ + return app_path.c_str(); +} + +bool portable_app_setup() +{ + StringOutputStream confdir(256); + confdir << app_path.c_str() << "settings/"; + if(file_exists(confdir.c_str())) + { + home_path = confdir.c_str(); + return true; + } + return false; +} + +#if defined(POSIX) + +#include +#include +#include + +#include + +const char* LINK_NAME = +#if defined (__linux__) + "/proc/self/exe" +#else // FreeBSD and OSX + "/proc/curproc/file" +#endif +; + +/// brief Returns the filename of the executable belonging to the current process, or 0 if not found. +char* getexename(char *buf) +{ + /* Now read the symbolic link */ + int ret = readlink(LINK_NAME, buf, PATH_MAX); + + if(ret == -1) + { + globalOutputStream() << "getexename: falling back to argv[0]: " << makeQuoted(g_argv[0]); + const char* path = realpath(g_argv[0], buf); + if(path == 0) + { + /* In case of an error, leave the handling up to the caller */ + return ""; + } + } + + /* Ensure proper NUL termination */ + buf[ret] = 0; + + /* delete the program name */ + *(strrchr(buf, '/')) = '\0'; + + // NOTE: we build app path with a trailing '/' + // it's a general convention in Radiant to have the slash at the end of directories + if (buf[strlen(buf)-1] != '/') + { + strcat(buf, "/"); + } + + return buf; +} + +void environment_init(int argc, char* argv[]) +{ + // Give away unnecessary root privileges. + // Important: must be done before calling gtk_init(). + char *loginname; + struct passwd *pw; + seteuid(getuid()); + if (geteuid() == 0 && (loginname = getlogin()) != 0 && + (pw = getpwnam(loginname)) != 0) + setuid(pw->pw_uid); + + args_init(argc, argv); + + { + char real[PATH_MAX]; + app_path = getexename(real); + ASSERT_MESSAGE(!string_empty(app_path.c_str()), "failed to deduce app path"); + } + + if(!portable_app_setup()) + { + StringOutputStream home(256); + home << DirectoryCleaned(g_get_home_dir()) << ".netradiant/"; + Q_mkdir(home.c_str()); + home_path = home.c_str(); + } + gamedetect(); +} + +#elif defined(WIN32) + +#include + +void environment_init(int argc, char* argv[]) +{ + args_init(argc, argv); + + { + // get path to the editor + char filename[MAX_PATH+1]; + GetModuleFileName(0, filename, MAX_PATH); + char* last_separator = strrchr(filename, '\\'); + if(last_separator != 0) + { + *(last_separator+1) = '\0'; + } + else + { + filename[0] = '\0'; + } + StringOutputStream app(256); + app << PathCleaned(filename); + app_path = app.c_str(); + } + + if(!portable_app_setup()) + { + char *appdata = getenv("APPDATA"); + StringOutputStream home(256); + if(!appdata || string_empty(appdata)) + { + ERROR_MESSAGE("Application Data folder not available.\n" + "Radiant will use C:\\ for user preferences.\n"); + home << "C:"; + } + else + { + home << PathCleaned(appdata); + } + home << "/NetRadiantSettings/"; + Q_mkdir(home.c_str()); + home_path = home.c_str(); + } + gamedetect(); +} + +#else +#error "unsupported platform" +#endif diff --git a/misc/mediasource/netradiant-src/radiant/environment.h b/misc/mediasource/netradiant-src/radiant/environment.h new file mode 100644 index 00000000..49d595e0 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/environment.h @@ -0,0 +1,32 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_ENVIRONMENT_H) +#define INCLUDED_ENVIRONMENT_H + +void environment_init(int argc, char* argv[]); +const char* environment_get_home_path(); +const char* environment_get_app_path(); + +extern int g_argc; +extern char** g_argv; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/error.cpp b/misc/mediasource/netradiant-src/radiant/error.cpp new file mode 100644 index 00000000..0ff75d1c --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/error.cpp @@ -0,0 +1,138 @@ +/* +Copyright (C) 1999-2006 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 "error.h" + +#include "debugging/debugging.h" +#include "igl.h" + +#include "gtkutil/messagebox.h" +#include "console.h" +#include "preferences.h" + + +#ifdef WIN32 +#define UNICODE +#include +#else +#include +#include +#endif + + + +/* +================= +Error + +For abnormal program terminations +================= +*/ + +/*! +\todo +FIXME the prompt wether to do prefs dialog, may not even be possible +if the crash happens before the game is loaded +*/ + +void Error (const char *error, ...) +{ + va_list argptr; + char text[4096]; + + va_start (argptr,error); + vsprintf (text, error,argptr); + va_end (argptr); + + strcat( text, "\n" ); + +#ifdef WIN32 + if (GetLastError() != 0) + { + LPVOID lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + 0, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPTSTR) &lpMsgBuf, + 0, + 0 + ); + strcat( text, "GetLastError: " ); + /* + Gtk will only crunch 0<=char<=127 + this is a bit hackish, but I didn't find useful functions in win32 API for this + http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=516 + */ + TCHAR *scan, *next = (TCHAR*)lpMsgBuf; + do + { + scan = next; + text[strlen(text)+1] = '\0'; + if ((scan[0] >= 0) && (scan[0] <= 127)) + text[strlen(text)] = char(scan[0]); + else + text[strlen(text)] = '?'; + next = CharNext(scan); + } while (next != scan); + strcat( text, "\n"); + LocalFree( lpMsgBuf ); + } +#else + if (errno != 0) + { + strcat( text, "errno: " ); + strcat( text, strerror (errno)); + strcat( text, "\n"); + } +#endif + + +#if 0 + // we need to have a current context to call glError() + if (g_glwindow_globals.d_glBase != 0) + { + // glGetError .. can record several errors, clears after calling + //++timo TODO: be able to deal with several errors if necessary, for now I'm just warning about pending error messages + // NOTE: forget that, most boards don't seem to follow the OpenGL standard + GLenum iGLError = glGetError(); + if (iGLError != GL_NO_ERROR) + { + // use our own gluErrorString + strcat( text, "gluErrorString: " ); + strcat( text, (char*)gluErrorString( iGLError ) ); + strcat( text, "\n" ); + } + } +#endif + + strcat (text, "An unrecoverable error has occured.\n"); + + ERROR_MESSAGE(text); + + // force close logging if necessary + Sys_LogFile(false); + + _exit (1); +} diff --git a/misc/mediasource/netradiant-src/radiant/error.h b/misc/mediasource/netradiant-src/radiant/error.h new file mode 100644 index 00000000..b114640a --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/error.h @@ -0,0 +1,27 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_ERROR_H) +#define INCLUDED_ERROR_H + +void Error(const char *error, ...); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/feedback.cpp b/misc/mediasource/netradiant-src/radiant/feedback.cpp new file mode 100644 index 00000000..9a847ce2 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/feedback.cpp @@ -0,0 +1,372 @@ +/* +Copyright (C) 1999-2006 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: +// classes used for describing geometry information from q3map feedback +// + +#include "feedback.h" + +#include "debugging/debugging.h" + +#include "igl.h" +#include "iselection.h" + +#include +#include +#include +#include +#include +#include + +#include "map.h" +#include "dialog.h" +#include "mainframe.h" + + +CDbgDlg g_DbgDlg; + +void Feedback_draw2D(VIEWTYPE viewType) +{ + g_DbgDlg.draw2D(viewType); +} + +void CSelectMsg::saxStartElement(message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) +{ + if(string_equal(reinterpret_cast(name), "select")) + { + // read the message + ESelectState = SELECT_MESSAGE; + } + else + { + // read the brush + ASSERT_MESSAGE(string_equal(reinterpret_cast(name), "brush"), "FEEDBACK PARSE ERROR"); + ASSERT_MESSAGE(ESelectState == SELECT_MESSAGE, "FEEDBACK PARSE ERROR"); + ESelectState = SELECT_BRUSH; + globalOutputStream() << message.c_str() << '\n'; + } +} + +void CSelectMsg::saxEndElement(message_info_t *ctx, const xmlChar *name) +{ + if(string_equal(reinterpret_cast(name), "select")) + { + } +} + +void CSelectMsg::saxCharacters(message_info_t *ctx, const xmlChar *ch, int len) +{ + if(ESelectState == SELECT_MESSAGE) + { + message.write(reinterpret_cast(ch), len); + } + else + { + brush.write(reinterpret_cast(ch), len); + } +} + +IGL2DWindow* CSelectMsg::Highlight() +{ + GlobalSelectionSystem().setSelectedAll(false); + int entitynum, brushnum; + if(sscanf(reinterpret_cast(brush.c_str()), "%i %i", &entitynum, &brushnum) == 2) + { + SelectBrush (entitynum, brushnum); + } + return 0; +} + +void CPointMsg::saxStartElement(message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) +{ + if(string_equal(reinterpret_cast(name), "pointmsg")) + { + // read the message + EPointState = POINT_MESSAGE; + } + else + { + // read the brush + ASSERT_MESSAGE(string_equal(reinterpret_cast(name), "point"), "FEEDBACK PARSE ERROR"); + ASSERT_MESSAGE(EPointState == POINT_MESSAGE, "FEEDBACK PARSE ERROR"); + EPointState = POINT_POINT; + globalOutputStream() << message.c_str() << '\n'; + } +} + +void CPointMsg::saxEndElement (message_info_t *ctx, const xmlChar *name) +{ + if(string_equal(reinterpret_cast(name), "pointmsg")) + { + } + else if(string_equal(reinterpret_cast(name), "point")) + { + sscanf(point.c_str(), "%g %g %g", &(pt[0]), &(pt[1]), &(pt[2])); + point.clear(); + } +} + +void CPointMsg::saxCharacters (message_info_t *ctx, const xmlChar *ch, int len) +{ + if(EPointState == POINT_MESSAGE) + { + message.write(reinterpret_cast(ch), len); + } + else + { + ASSERT_MESSAGE(EPointState == POINT_POINT, "FEEDBACK PARSE ERROR"); + point.write(reinterpret_cast(ch), len); + } +} + +IGL2DWindow* CPointMsg::Highlight() +{ + return this; +} + +void CPointMsg::DropHighlight() +{ +} + +void CPointMsg::Draw2D( VIEWTYPE vt ) +{ + int nDim1 = (vt == YZ) ? 1 : 0; + int nDim2 = (vt == XY) ? 1 : 2; + glPointSize(4); + glColor3f(1.0f,0.0f,0.0f); + glBegin (GL_POINTS); + glVertex2f (pt[nDim1], pt[nDim2]); + glEnd(); + glBegin (GL_LINE_LOOP); + glVertex2f (pt[nDim1]-8, pt[nDim2]-8); + glVertex2f (pt[nDim1]+8, pt[nDim2]-8); + glVertex2f (pt[nDim1]+8, pt[nDim2]+8); + glVertex2f (pt[nDim1]-8, pt[nDim2]+8); + glEnd(); +} + +void CWindingMsg::saxStartElement(message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) +{ + if(string_equal(reinterpret_cast(name), "windingmsg")) + { + // read the message + EPointState = WINDING_MESSAGE; + } + else + { + // read the brush + ASSERT_MESSAGE(string_equal(reinterpret_cast(name), "winding"), "FEEDBACK PARSE ERROR"); + ASSERT_MESSAGE(EPointState == WINDING_MESSAGE, "FEEDBACK PARSE ERROR"); + EPointState = WINDING_WINDING; + globalOutputStream() << message.c_str() << '\n'; + } +} + +void CWindingMsg::saxEndElement(message_info_t *ctx, const xmlChar *name) +{ + if(string_equal(reinterpret_cast(name), "windingmsg")) + { + } + else if(string_equal(reinterpret_cast(name), "winding")) + { + const char* c = winding.c_str(); + sscanf(c, "%i ", &numpoints); + + int i = 0; + for(; i < numpoints; i++) + { + c = strchr(c + 1, '('); + if(c) // even if we are given the number of points when the cycle begins .. don't trust it too much + sscanf(c, "(%g %g %g)", &wt[i][0], &wt[i][1], &wt[i][2]); + else + break; + } + numpoints = i; + } +} + +void CWindingMsg::saxCharacters(message_info_t *ctx, const xmlChar *ch, int len) +{ + if(EPointState == WINDING_MESSAGE) + { + message.write(reinterpret_cast(ch), len); + } + else + { + ASSERT_MESSAGE(EPointState == WINDING_WINDING, "FEEDBACK PARSE ERROR"); + winding.write(reinterpret_cast(ch), len); + } +} + +IGL2DWindow* CWindingMsg::Highlight() +{ + return this; +} + +void CWindingMsg::DropHighlight() +{ +} + +void CWindingMsg::Draw2D( VIEWTYPE vt ) +{ + int i; + + int nDim1 = (vt == YZ) ? 1 : 0; + int nDim2 = (vt == XY) ? 1 : 2; + glColor3f(1.0f,0.f,0.0f); + + glPointSize(4); + glBegin (GL_POINTS); + for(i = 0; i < numpoints; i++) + glVertex2f (wt[i][nDim1], wt[i][nDim2]); + glEnd(); + glPointSize(1); + + glEnable (GL_BLEND); + glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); + glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(0.133f,0.4f,1.0f,0.5f); + glBegin (GL_POLYGON); + for(i = 0; i < numpoints; i++) + glVertex2f (wt[i][nDim1], wt[i][nDim2]); + glEnd(); + glDisable (GL_BLEND); +} + +// triggered when the user selects an entry in the feedback box +static void feedback_selection_changed(GtkTreeSelection* selection, gpointer data) +{ + g_DbgDlg.DropHighlight(); + + GtkTreeModel* model; + GtkTreeIter selected; + if(gtk_tree_selection_get_selected(selection, &model, &selected)) + { + GtkTreePath* path = gtk_tree_model_get_path(model, &selected); + g_DbgDlg.SetHighlight(gtk_tree_path_get_indices(path)[0]); + gtk_tree_path_free(path); + } +} + +void CDbgDlg::DropHighlight() +{ + if(m_pHighlight != 0) + { + m_pHighlight->DropHighlight(); + m_pHighlight = 0; + m_pDraw2D = 0; + } +} + +void CDbgDlg::SetHighlight(gint row) +{ + ISAXHandler *h = GetElement(row); + if(h != NULL) + { + m_pDraw2D = h->Highlight(); + m_pHighlight = h; + } +} + +ISAXHandler *CDbgDlg::GetElement (std::size_t row) +{ + return static_cast(g_ptr_array_index(m_pFeedbackElements, gint(row))); +} + +void CDbgDlg::Init() +{ + DropHighlight(); + + // free all the ISAXHandler*, clean it + while (m_pFeedbackElements->len) + { + static_cast(g_ptr_array_index (m_pFeedbackElements, 0))->Release(); + g_ptr_array_remove_index (m_pFeedbackElements, 0); + } + + if(m_clist != NULL) + gtk_list_store_clear (m_clist); +} + +void CDbgDlg::Push (ISAXHandler *pHandler) +{ + // push in the list + g_ptr_array_add (m_pFeedbackElements, (void *)pHandler); + + if(GetWidget() == 0) + { + Create(); + } + + // put stuff in the list + gtk_list_store_clear (m_clist); + for(std::size_t i = 0; i < static_cast(m_pFeedbackElements->len); ++i) + { + GtkTreeIter iter; + gtk_list_store_append(m_clist, &iter); + gtk_list_store_set(m_clist, &iter, 0, GetElement(i)->getName(), -1); + } + + ShowDlg(); +} + +GtkWindow* CDbgDlg::BuildDialog() +{ + GtkWindow* window = create_floating_window("Q3Map debug window", MainFrame_getWindow()); + + GtkWidget* scr = gtk_scrolled_window_new (NULL, NULL); + gtk_widget_show (scr); + gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (scr)); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); + + { + GtkListStore* store = gtk_list_store_new(1, G_TYPE_STRING); + + GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", 0, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + } + + { + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); + gtk_tree_selection_set_mode(selection, GTK_SELECTION_BROWSE); + g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(feedback_selection_changed), NULL); + } + + gtk_widget_show(view); + + gtk_container_add(GTK_CONTAINER (scr), view); + + g_object_unref(G_OBJECT(store)); + + m_clist = store; + } + + return window; +} diff --git a/misc/mediasource/netradiant-src/radiant/feedback.h b/misc/mediasource/netradiant-src/radiant/feedback.h new file mode 100644 index 00000000..4d199bd4 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/feedback.h @@ -0,0 +1,186 @@ +/* +Copyright (C) 1999-2006 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: +// classes used for describing geometry information from q3map feedback +// + +#ifndef __Q3MAP_FEEDBACK__ +#define __Q3MAP_FEEDBACK__ + +#include "math/vector.h" +#include "stream/stringstream.h" +#include +#include "xmlstuff.h" +#include "dialog.h" +#include "xywindow.h" + +// we use these classes to let plugins draw inside the Radiant windows +// 2D window like YZ XZ XY +class IGL2DWindow +{ +public: + // Increment the number of references to this object + virtual void IncRef() = 0; + // Decrement the reference count + virtual void DecRef() = 0; + virtual void Draw2D( VIEWTYPE vt ) = 0; +}; + +// 3D window +class IGL3DWindow +{ +public: + // Increment the number of references to this object + virtual void IncRef() = 0; + // Decrement the reference count + virtual void DecRef() = 0; + virtual void Draw3D() = 0; +}; + +// a select message with a brush/entity select information +class CSelectMsg : public ISAXHandler +{ + enum { SELECT_MESSAGE, SELECT_BRUSH } ESelectState; + StringOutputStream message; + StringOutputStream brush; +public: + CSelectMsg() { ESelectState = SELECT_MESSAGE; } + // SAX interface + void saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs); + void saxEndElement (message_info_t *ctx, const xmlChar *name); + void saxCharacters (message_info_t *ctx, const xmlChar *ch, int len); + // for use in the dialog window + const char* getName() { return message.c_str(); } + IGL2DWindow* Highlight(); + void DropHighlight() { } +}; + +class CPointMsg : public ISAXHandler, public IGL2DWindow +{ + enum { POINT_MESSAGE, POINT_POINT } EPointState; + StringOutputStream message; + StringOutputStream point; + Vector3 pt; + int refCount; +public: + CPointMsg() { EPointState = POINT_MESSAGE; refCount = 0; } + // SAX interface + void Release() + { + delete this; + } + void saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs); + void saxEndElement (message_info_t *ctx, const xmlChar *name); + void saxCharacters (message_info_t *ctx, const xmlChar *ch, int len); + // for use in the dialog window + const char* getName() { return message.c_str(); } + IGL2DWindow* Highlight(); + void DropHighlight(); + + // IGL2DWindow interface -------------------------------- + // Increment the number of references to this object + void IncRef() { refCount++; } + // Decrement the reference count + void DecRef() { refCount--; if (refCount <= 0) delete this; } + void Draw2D( VIEWTYPE vt ); +}; + +class CWindingMsg : public ISAXHandler, public IGL2DWindow +{ + enum { WINDING_MESSAGE, WINDING_WINDING } EPointState; + StringOutputStream message; + StringOutputStream winding; + Vector3 wt[256]; + int numpoints; + int refCount; +public: + CWindingMsg() { EPointState = WINDING_MESSAGE; refCount = 0; numpoints = 0; } + // SAX interface + void Release() + { + delete this; + } + void saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs); + void saxEndElement (message_info_t *ctx, const xmlChar *name); + void saxCharacters (message_info_t *ctx, const xmlChar *ch, int len); + // for use in the dialog window + const char* getName() { return message.c_str(); } + IGL2DWindow* Highlight(); + void DropHighlight(); + + // IGL2DWindow interface -------------------------------- + // Increment the number of references to this object + void IncRef() { refCount++; } + // Decrement the reference count + void DecRef() { refCount--; if (refCount <= 0) delete this; } + void Draw2D( VIEWTYPE vt ); +}; + +typedef struct _GtkListStore GtkListStore; + +class CDbgDlg : public Dialog +{ + GPtrArray *m_pFeedbackElements; + // the list widget we use in the dialog + GtkListStore* m_clist; + ISAXHandler *m_pHighlight; + IGL2DWindow* m_pDraw2D; +public: + CDbgDlg() + { + m_pFeedbackElements = g_ptr_array_new(); + m_pHighlight = NULL; + m_pDraw2D = NULL; + } + // refresh items + void Push (ISAXHandler *); + // clean the debug window, release all ISAXHanlders we have + void Init(); + ISAXHandler *GetElement(std::size_t row); + void SetHighlight(gint row); + void DropHighlight(); + void draw2D(VIEWTYPE viewType) + { + if(m_pDraw2D != 0) + { + m_pDraw2D->Draw2D(viewType); + } + } + void destroyWindow() + { + if(GetWidget() != 0) + { + Destroy(); + } + } +// void HideDlg(); +protected: + GtkWindow* BuildDialog(); +}; + +extern CDbgDlg g_DbgDlg; + +void Feedback_draw2D(VIEWTYPE viewType); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/filetypes.cpp b/misc/mediasource/netradiant-src/radiant/filetypes.cpp new file mode 100644 index 00000000..11c0a272 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/filetypes.cpp @@ -0,0 +1,145 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "filetypes.h" + +#include "debugging/debugging.h" + +#include "ifiletypes.h" + +#include "string/string.h" +#include "os/path.h" +#include +#include + +class RadiantFileTypeRegistry : public IFileTypeRegistry +{ + struct filetype_copy_t + { + filetype_copy_t(const char* moduleName, const filetype_t other) + : m_moduleName(moduleName), m_name(other.name), m_pattern(other.pattern), m_can_load(other.can_load), m_can_import(other.can_import), m_can_save(other.can_save) + { + } + const char* getModuleName() const + { + return m_moduleName.c_str(); + } + filetype_t getType() const + { + return filetype_t(m_name.c_str(), m_pattern.c_str(), m_can_load, m_can_save, m_can_import); + } + bool m_can_load; + bool m_can_import; + bool m_can_save; + private: + CopiedString m_moduleName; + CopiedString m_name; + CopiedString m_pattern; + }; + typedef std::vector filetype_list_t; + std::map m_typelists; +public: + RadiantFileTypeRegistry() + { + addType("*", "*", filetype_t("All Files", "*.*")); + } + void addType(const char* moduleType, const char* moduleName, filetype_t type) + { + m_typelists[moduleType].push_back(filetype_copy_t(moduleName, type)); + } + void getTypeList(const char* moduleType, IFileTypeList* typelist, bool want_load, bool want_import, bool want_save) + { + filetype_list_t& list_ref = m_typelists[moduleType]; + for(filetype_list_t::iterator i = list_ref.begin(); i != list_ref.end(); ++i) + { + if(want_load && !(*i).m_can_load) return; + if(want_import && !(*i).m_can_import) return; + if(want_save && !(*i).m_can_save) return; + typelist->addType((*i).getModuleName(), (*i).getType()); + } + } +}; + +static RadiantFileTypeRegistry g_patterns; + +IFileTypeRegistry* GetFileTypeRegistry() +{ + return &g_patterns; +} + +const char* findModuleName(IFileTypeRegistry* registry, const char* moduleType, const char* extension) +{ + class SearchFileTypeList : public IFileTypeList + { + char m_pattern[128]; + const char* m_moduleName; + public: + SearchFileTypeList(const char* ext) + : m_moduleName("") + { + m_pattern[0] = '*'; + m_pattern[1] = '.'; + strncpy(m_pattern + 2, ext, 125); + m_pattern[127] = '\0'; + } + void addType(const char* moduleName, filetype_t type) + { + if(extension_equal(m_pattern, type.pattern)) + { + m_moduleName = moduleName; + } + } + + const char* getModuleName() + { + return m_moduleName; + } + } search(extension); + registry->getTypeList(moduleType, &search); + return search.getModuleName(); +} + + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class FiletypesAPI +{ + IFileTypeRegistry* m_filetypes; +public: + typedef IFileTypeRegistry Type; + STRING_CONSTANT(Name, "*"); + + FiletypesAPI() + { + m_filetypes = GetFileTypeRegistry(); + } + IFileTypeRegistry* getTable() + { + return m_filetypes; + } +}; + +typedef SingletonModule FiletypesModule; +typedef Static StaticFiletypesModule; +StaticRegisterModule staticRegisterFiletypes(StaticFiletypesModule::instance()); + + diff --git a/misc/mediasource/netradiant-src/radiant/filetypes.h b/misc/mediasource/netradiant-src/radiant/filetypes.h new file mode 100644 index 00000000..f924c793 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/filetypes.h @@ -0,0 +1,29 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_FILETYPES_H) +#define INCLUDED_FILETYPES_H + +class IFileTypeRegistry; +IFileTypeRegistry* GetFileTypeRegistry(); +const char* findModuleName(IFileTypeRegistry* registry, const char* moduleType, const char* extension); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/filters.cpp b/misc/mediasource/netradiant-src/radiant/filters.cpp new file mode 100644 index 00000000..235e2910 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/filters.cpp @@ -0,0 +1,323 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "filters.h" + +#include "debugging/debugging.h" + +#include "ifilter.h" + +#include "scenelib.h" + +#include +#include + +#include "gtkutil/widget.h" +#include "gtkutil/menu.h" +#include "gtkmisc.h" +#include "mainframe.h" +#include "commands.h" +#include "preferences.h" + +struct filters_globals_t +{ + std::size_t exclude; + + filters_globals_t() : + exclude(0) + { + } +}; + +filters_globals_t g_filters_globals; + +inline bool filter_active(int mask) +{ + return (g_filters_globals.exclude & mask) > 0; +} + +class FilterWrapper +{ +public: + FilterWrapper(Filter& filter, int mask) : m_filter(filter), m_mask(mask) + { + } + void update() + { + m_filter.setActive(filter_active(m_mask)); + } +private: + Filter& m_filter; + int m_mask; +}; + +typedef std::list Filters; +Filters g_filters; + +typedef std::set Filterables; +Filterables g_filterables; + +void UpdateFilters() +{ + { + for(Filters::iterator i = g_filters.begin(); i != g_filters.end(); ++i) + { + (*i).update(); + } + } + + { + for(Filterables::iterator i = g_filterables.begin(); i != g_filterables.end(); ++i) + { + (*i)->updateFiltered(); + } + } +} + + +class BasicFilterSystem : public FilterSystem +{ +public: + void addFilter(Filter& filter, int mask) + { + g_filters.push_back(FilterWrapper(filter, mask)); + g_filters.back().update(); + } + void registerFilterable(Filterable& filterable) + { + ASSERT_MESSAGE(g_filterables.find(&filterable) == g_filterables.end(), "filterable already registered"); + filterable.updateFiltered(); + g_filterables.insert(&filterable); + } + void unregisterFilterable(Filterable& filterable) + { + ASSERT_MESSAGE(g_filterables.find(&filterable) != g_filterables.end(), "filterable not registered"); + g_filterables.erase(&filterable); + } +}; + +BasicFilterSystem g_FilterSystem; + +FilterSystem& GetFilterSystem() +{ + return g_FilterSystem; +} + +void PerformFiltering() +{ + UpdateFilters(); + SceneChangeNotify(); +} + +class ToggleFilterFlag +{ + const unsigned int m_mask; +public: + ToggleItem m_item; + + ToggleFilterFlag(unsigned int mask) : m_mask(mask), m_item(ActiveCaller(*this)) + { + } + ToggleFilterFlag(const ToggleFilterFlag& other) : m_mask(other.m_mask), m_item(ActiveCaller(*this)) + { + } + void active(const BoolImportCallback& importCallback) + { + importCallback((g_filters_globals.exclude & m_mask) != 0); + } + typedef MemberCaller1 ActiveCaller; + void toggle() + { + g_filters_globals.exclude ^= m_mask; + m_item.update(); + PerformFiltering(); + } + void reset() + { + g_filters_globals.exclude = 0; + m_item.update(); + PerformFiltering(); + } + typedef MemberCaller ToggleCaller; +}; + + +typedef std::list ToggleFilterFlags; +ToggleFilterFlags g_filter_items; + +void add_filter_command(unsigned int flag, const char* command, const Accelerator& accelerator) +{ + g_filter_items.push_back(ToggleFilterFlag(flag)); + GlobalToggles_insert(command, ToggleFilterFlag::ToggleCaller(g_filter_items.back()), ToggleItem::AddCallbackCaller(g_filter_items.back().m_item), accelerator); +} + +void InvertFilters() +{ + std::list::iterator iter; + + for(iter = g_filter_items.begin(); iter != g_filter_items.end(); ++iter) + { + iter->toggle(); + } +} + +void ResetFilters() +{ + std::list::iterator iter; + + for(iter = g_filter_items.begin(); iter != g_filter_items.end(); ++iter) + { + iter->reset(); + } +} + +void Filters_constructMenu(GtkMenu* menu_in_menu) +{ + create_check_menu_item_with_mnemonic(menu_in_menu, "World", "FilterWorldBrushes"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Entities", "FilterEntities"); + if(g_pGameDescription->mGameType == "doom3") + { + create_check_menu_item_with_mnemonic(menu_in_menu, "Visportals", "FilterVisportals"); + } + else + { + create_check_menu_item_with_mnemonic(menu_in_menu, "Areaportals", "FilterAreaportals"); + } + create_check_menu_item_with_mnemonic(menu_in_menu, "Translucent", "FilterTranslucent"); + if(g_pGameDescription->mGameType != "doom3") + { + create_check_menu_item_with_mnemonic(menu_in_menu, "Liquids", "FilterLiquids"); + } + create_check_menu_item_with_mnemonic(menu_in_menu, "Caulk", "FilterCaulk"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Clips", "FilterClips"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Paths", "FilterPaths"); + if(g_pGameDescription->mGameType != "doom3") + { + create_check_menu_item_with_mnemonic(menu_in_menu, "Clusterportals", "FilterClusterportals"); + } + create_check_menu_item_with_mnemonic(menu_in_menu, "Lights", "FilterLights"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Structural", "FilterStructural"); + if(g_pGameDescription->mGameType != "doom3") + { + create_check_menu_item_with_mnemonic(menu_in_menu, "Lightgrid", "FilterLightgrid"); + } + create_check_menu_item_with_mnemonic(menu_in_menu, "Patches", "FilterPatches"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Details", "FilterDetails"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Hints", "FilterHintsSkips"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Models", "FilterModels"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Triggers", "FilterTriggers"); + if(g_pGameDescription->mGameType != "doom3") + { + create_check_menu_item_with_mnemonic(menu_in_menu, "Botclips", "FilterBotClips"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Decals", "FilterDecals"); + } + // filter manipulation + menu_separator(menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Invert filters", "InvertFilters"); + create_menu_item_with_mnemonic(menu_in_menu, "Reset filters", "ResetFilters"); +} + + +#include "preferencesystem.h" +#include "stringio.h" + +void ConstructFilters() +{ + GlobalPreferenceSystem().registerPreference("SI_Exclude", SizeImportStringCaller(g_filters_globals.exclude), SizeExportStringCaller(g_filters_globals.exclude)); + + GlobalCommands_insert("InvertFilters", FreeCaller()); + GlobalCommands_insert("ResetFilters", FreeCaller()); + + add_filter_command(EXCLUDE_WORLD, "FilterWorldBrushes", Accelerator('1', (GdkModifierType)GDK_MOD1_MASK)); + add_filter_command(EXCLUDE_ENT, "FilterEntities", Accelerator('2', (GdkModifierType)GDK_MOD1_MASK)); + if(g_pGameDescription->mGameType == "doom3") + { + add_filter_command(EXCLUDE_VISPORTALS, "FilterVisportals", Accelerator('3', (GdkModifierType)GDK_MOD1_MASK)); + } + else + { + add_filter_command(EXCLUDE_AREAPORTALS, "FilterAreaportals", Accelerator('3', (GdkModifierType)GDK_MOD1_MASK)); + } + add_filter_command(EXCLUDE_TRANSLUCENT, "FilterTranslucent", Accelerator('4', (GdkModifierType)GDK_MOD1_MASK)); + add_filter_command(EXCLUDE_LIQUIDS, "FilterLiquids", Accelerator('5', (GdkModifierType)GDK_MOD1_MASK)); + add_filter_command(EXCLUDE_CAULK, "FilterCaulk", Accelerator('6', (GdkModifierType)GDK_MOD1_MASK )); + add_filter_command(EXCLUDE_CLIP, "FilterClips", Accelerator('7', (GdkModifierType)GDK_MOD1_MASK)); + add_filter_command(EXCLUDE_PATHS, "FilterPaths", Accelerator('8', (GdkModifierType)GDK_MOD1_MASK)); + if(g_pGameDescription->mGameType != "doom3") + { + add_filter_command(EXCLUDE_CLUSTERPORTALS, "FilterClusterportals", Accelerator('9', (GdkModifierType)GDK_MOD1_MASK)); + } + add_filter_command(EXCLUDE_LIGHTS, "FilterLights", Accelerator('0', (GdkModifierType)GDK_MOD1_MASK)); + add_filter_command(EXCLUDE_STRUCTURAL, "FilterStructural", Accelerator('D', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + if(g_pGameDescription->mGameType != "doom3") + { + add_filter_command(EXCLUDE_LIGHTGRID, "FilterLightgrid", accelerator_null()); + } + add_filter_command(EXCLUDE_CURVES, "FilterPatches", Accelerator('P', (GdkModifierType)GDK_CONTROL_MASK)); + add_filter_command(EXCLUDE_DETAILS, "FilterDetails", Accelerator('D', (GdkModifierType)GDK_CONTROL_MASK)); + add_filter_command(EXCLUDE_HINTSSKIPS, "FilterHintsSkips", Accelerator('H', (GdkModifierType)GDK_CONTROL_MASK)); + add_filter_command(EXCLUDE_MODELS, "FilterModels", Accelerator('M', (GdkModifierType)GDK_SHIFT_MASK)); + add_filter_command(EXCLUDE_TRIGGERS, "FilterTriggers", Accelerator('T', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + if(g_pGameDescription->mGameType != "doom3") + { + add_filter_command(EXCLUDE_BOTCLIP, "FilterBotClips", Accelerator('M', (GdkModifierType)GDK_MOD1_MASK)); + add_filter_command(EXCLUDE_DECALS, "FilterDecals", Accelerator('D', (GdkModifierType)GDK_SHIFT_MASK)); + } + + PerformFiltering(); +} + +void DestroyFilters() +{ + g_filters.clear(); +} + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class FilterAPI +{ + FilterSystem* m_filter; +public: + typedef FilterSystem Type; + STRING_CONSTANT(Name, "*"); + + FilterAPI() + { + ConstructFilters(); + + m_filter = &GetFilterSystem(); + } + ~FilterAPI() + { + DestroyFilters(); + } + FilterSystem* getTable() + { + return m_filter; + } +}; + +typedef SingletonModule FilterModule; +typedef Static StaticFilterModule; +StaticRegisterModule staticRegisterFilter(StaticFilterModule::instance()); + + diff --git a/misc/mediasource/netradiant-src/radiant/filters.h b/misc/mediasource/netradiant-src/radiant/filters.h new file mode 100644 index 00000000..631cef84 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/filters.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_FILTERS_H) +#define INCLUDED_FILTERS_H + +typedef struct _GtkMenu GtkMenu; +void Filters_constructMenu(GtkMenu* menu_in_menu); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/findtexturedialog.cpp b/misc/mediasource/netradiant-src/radiant/findtexturedialog.cpp new file mode 100644 index 00000000..52891d80 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/findtexturedialog.cpp @@ -0,0 +1,301 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Find/Replace textures dialogs +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "findtexturedialog.h" + +#include "debugging/debugging.h" + +#include "ishaders.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtkutil/window.h" +#include "stream/stringstream.h" + +#include "commands.h" +#include "dialog.h" +#include "select.h" +#include "textureentry.h" + + + +class FindTextureDialog : public Dialog +{ + public: + static void setReplaceStr(const char* name); + static void setFindStr(const char* name); + static bool isOpen(); + static void show(); + typedef FreeCaller<&FindTextureDialog::show> ShowCaller; + static void updateTextures(const char* name); + + FindTextureDialog(); + virtual ~FindTextureDialog(); + GtkWindow* BuildDialog(); + + void constructWindow(GtkWindow* parent) + { + m_parent = parent; + Create(); + } + void destroyWindow() + { + Destroy(); + } + + + bool m_bSelectedOnly; + CopiedString m_strFind; + CopiedString m_strReplace; +}; + +FindTextureDialog g_FindTextureDialog; +static bool g_bFindActive = true; + +namespace +{ + void FindTextureDialog_apply() + { + StringOutputStream find(256); + StringOutputStream replace(256); + + find << "textures/" << g_FindTextureDialog.m_strFind.c_str(); + replace << "textures/" << g_FindTextureDialog.m_strReplace.c_str(); + FindReplaceTextures(find.c_str(), replace.c_str(), g_FindTextureDialog.m_bSelectedOnly); + } + + static void OnApply(GtkWidget* widget, gpointer data) + { + g_FindTextureDialog.exportData(); + FindTextureDialog_apply(); + } + + static void OnFind(GtkWidget* widget, gpointer data) + { + g_FindTextureDialog.exportData(); + FindTextureDialog_apply(); + } + + static void OnOK(GtkWidget* widget, gpointer data) + { + g_FindTextureDialog.exportData(); + FindTextureDialog_apply(); + g_FindTextureDialog.HideDlg(); + } + + static void OnClose(GtkWidget* widget, gpointer data) + { + g_FindTextureDialog.HideDlg(); + } + + + static gint find_focus_in (GtkWidget* widget, GdkEventFocus *event, gpointer data) + { + g_bFindActive = true; + return FALSE; + } + + static gint replace_focus_in (GtkWidget* widget, GdkEventFocus *event, gpointer data) + { + g_bFindActive = false; + return FALSE; + } +} + +// ============================================================================= +// FindTextureDialog class + +FindTextureDialog::FindTextureDialog() +{ + m_bSelectedOnly = FALSE; +} + +FindTextureDialog::~FindTextureDialog() +{ +} + +GtkWindow* FindTextureDialog::BuildDialog() +{ + GtkWidget* vbox, *hbox, *table, *label; + GtkWidget* button, *check, *entry; + + GtkWindow* dlg = create_floating_window("Find / Replace Texture(s)", m_parent); + + hbox = gtk_hbox_new (FALSE, 5); + gtk_widget_show (hbox); + gtk_container_add(GTK_CONTAINER(dlg), GTK_WIDGET(hbox)); + gtk_container_set_border_width (GTK_CONTAINER (hbox), 5); + + vbox = gtk_vbox_new (FALSE, 5); + gtk_widget_show (vbox); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + + table = gtk_table_new (2, 2, FALSE); + gtk_widget_show (table); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings (GTK_TABLE (table), 5); + gtk_table_set_col_spacings (GTK_TABLE (table), 5); + + label = gtk_label_new ("Find:"); + gtk_widget_show (label); + gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + + label = gtk_label_new ("Replace:"); + gtk_widget_show (label); + gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5); + + entry = gtk_entry_new(); + gtk_widget_show (entry); + gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(entry), "focus_in_event", + G_CALLBACK(find_focus_in), 0); + AddDialogData(*GTK_ENTRY(entry), m_strFind); + GlobalTextureEntryCompletion::instance().connect(GTK_ENTRY(entry)); + + entry = gtk_entry_new(); + gtk_widget_show (entry); + gtk_table_attach (GTK_TABLE (table), entry, 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND|GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(entry), "focus_in_event", + G_CALLBACK(replace_focus_in), 0); + AddDialogData(*GTK_ENTRY(entry), m_strReplace); + GlobalTextureEntryCompletion::instance().connect(GTK_ENTRY(entry)); + + check = gtk_check_button_new_with_label ("Within selected brushes only"); + gtk_widget_show (check); + gtk_box_pack_start(GTK_BOX(vbox), check, TRUE, TRUE, 0); + AddDialogData(*GTK_TOGGLE_BUTTON(check), m_bSelectedOnly); + + vbox = gtk_vbox_new (FALSE, 5); + gtk_widget_show (vbox); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); + + button = gtk_button_new_with_label ("Apply"); + gtk_widget_show (button); + gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnApply), 0); + gtk_widget_set_usize (button, 60, -2); + + button = gtk_button_new_with_label ("Close"); + gtk_widget_show (button); + gtk_box_pack_start(GTK_BOX(vbox), button, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnClose), 0); + gtk_widget_set_usize (button, 60, -2); + + return dlg; +} + +void FindTextureDialog::updateTextures(const char* name) +{ + if (isOpen()) + { + if (g_bFindActive) + { + setFindStr(name + 9); + } + else + { + setReplaceStr(name + 9); + } + } +} + +bool FindTextureDialog::isOpen() +{ + return GTK_WIDGET_VISIBLE(g_FindTextureDialog.GetWidget()) == TRUE; +} + +void FindTextureDialog::setFindStr(const char* name) +{ + g_FindTextureDialog.exportData(); + g_FindTextureDialog.m_strFind = name; + g_FindTextureDialog.importData(); +} + +void FindTextureDialog::setReplaceStr(const char* name) +{ + g_FindTextureDialog.exportData(); + g_FindTextureDialog.m_strReplace = name; + g_FindTextureDialog.importData(); +} + +void FindTextureDialog::show() +{ + g_FindTextureDialog.ShowDlg(); +} + + +void FindTextureDialog_constructWindow(GtkWindow* main_window) +{ + g_FindTextureDialog.constructWindow(main_window); +} + +void FindTextureDialog_destroyWindow() +{ + g_FindTextureDialog.destroyWindow(); +} + +bool FindTextureDialog_isOpen() +{ + return g_FindTextureDialog.isOpen(); +} + +void FindTextureDialog_selectTexture(const char* name) +{ + g_FindTextureDialog.updateTextures(name); +} + +void FindTextureDialog_Construct() +{ + GlobalCommands_insert("FindReplaceTextures", FindTextureDialog::ShowCaller()); +} + +void FindTextureDialog_Destroy() +{ +} + diff --git a/misc/mediasource/netradiant-src/radiant/findtexturedialog.h b/misc/mediasource/netradiant-src/radiant/findtexturedialog.h new file mode 100644 index 00000000..5535ec5d --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/findtexturedialog.h @@ -0,0 +1,34 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_FINDTEXTUREDIALOG_H) +#define INCLUDED_FINDTEXTUREDIALOG_H + +void FindTextureDialog_Construct(); +void FindTextureDialog_Destroy(); + +typedef struct _GtkWindow GtkWindow; +void FindTextureDialog_constructWindow(GtkWindow* main_window); +void FindTextureDialog_destroyWindow(); +bool FindTextureDialog_isOpen(); +void FindTextureDialog_selectTexture(const char* name); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/glwidget.cpp b/misc/mediasource/netradiant-src/radiant/glwidget.cpp new file mode 100644 index 00000000..47500097 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/glwidget.cpp @@ -0,0 +1,55 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "glwidget.h" + +#include "igtkgl.h" +#include "modulesystem.h" +#include "gtkutil/glwidget.h" + +class GtkGLAPI +{ + _QERGtkGLTable m_gtkgl; +public: + typedef _QERGtkGLTable Type; + STRING_CONSTANT(Name, "*"); + + GtkGLAPI() + { + m_gtkgl.glwidget_new = &glwidget_new; + m_gtkgl.glwidget_swap_buffers = &glwidget_swap_buffers; + m_gtkgl.glwidget_make_current = &glwidget_make_current; + m_gtkgl.glwidget_destroy_context = &glwidget_destroy_context; + m_gtkgl.glwidget_create_context = &glwidget_create_context; + } + _QERGtkGLTable* getTable() + { + return &m_gtkgl; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule GtkGLModule; +typedef Static StaticGtkGLModule; +StaticRegisterModule staticRegisterGtkGL(StaticGtkGLModule::instance()); + diff --git a/misc/mediasource/netradiant-src/radiant/glwidget.h b/misc/mediasource/netradiant-src/radiant/glwidget.h new file mode 100644 index 00000000..6d9ab361 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/glwidget.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GLWIDGET_H) +#define INCLUDED_GLWIDGET_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/grid.cpp b/misc/mediasource/netradiant-src/radiant/grid.cpp new file mode 100644 index 00000000..f25a0d92 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/grid.cpp @@ -0,0 +1,289 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "grid.h" + +#include +#include +#include + +#include "preferencesystem.h" + +#include "gtkutil/widget.h" +#include "signal/signal.h" +#include "stringio.h" + +#include "gtkmisc.h" +#include "commands.h" +#include "preferences.h" + + + +Signal0 g_gridChange_callbacks; + +void AddGridChangeCallback(const SignalHandler& handler) +{ + g_gridChange_callbacks.connectLast(handler); + handler(); +} + +void GridChangeNotify() +{ + g_gridChange_callbacks(); +} + +enum GridPower +{ + GRIDPOWER_0125 = -3, + GRIDPOWER_025 = -2, + GRIDPOWER_05 = -1, + GRIDPOWER_1 = 0, + GRIDPOWER_2 = 1, + GRIDPOWER_4 = 2, + GRIDPOWER_8 = 3, + GRIDPOWER_16 = 4, + GRIDPOWER_32 = 5, + GRIDPOWER_64 = 6, + GRIDPOWER_128 = 7, + GRIDPOWER_256 = 8, +}; + + +typedef const char* GridName; +// this must match the GridPower enumeration +const GridName g_gridnames[] = { + "0.125", + "0.25", + "0.5", + "1", + "2", + "4", + "8", + "16", + "32", + "64", + "128", + "256", +}; + +inline GridPower GridPower_forGridDefault(int gridDefault) +{ + return static_cast(gridDefault - 3); +} + +inline int GridDefault_forGridPower(GridPower gridPower) +{ + return gridPower + 3; +} + +int g_grid_default = GridDefault_forGridPower(GRIDPOWER_8); + +int g_grid_power = GridPower_forGridDefault(g_grid_default); + +bool g_grid_snap = true; + +int Grid_getPower() +{ + return g_grid_power; +} + +inline float GridSize_forGridPower(int gridPower) +{ + return pow(2.0f, gridPower); +} + +float g_gridsize = GridSize_forGridPower(g_grid_power); + +float GetSnapGridSize() +{ + return g_grid_snap ? g_gridsize : 0; +} + +float GetGridSize() +{ + return g_gridsize; +} + + +void setGridPower(GridPower power); + +class GridMenuItem +{ + GridPower m_id; + + GridMenuItem(const GridMenuItem& other); // NOT COPYABLE + GridMenuItem& operator=(const GridMenuItem& other); // NOT ASSIGNABLE +public: + ToggleItem m_item; + + GridMenuItem(GridPower id) : m_id(id), m_item(ExportCaller(*this)) + { + } + void set() + { + g_grid_power = m_id; + m_item.update(); + setGridPower(m_id); + } + typedef MemberCaller SetCaller; + void active(const BoolImportCallback& importCallback) + { + importCallback(g_grid_power == m_id); + } + typedef MemberCaller1 ExportCaller; +}; + +GridMenuItem g_gridMenu0125(GRIDPOWER_0125); +GridMenuItem g_gridMenu025(GRIDPOWER_025); +GridMenuItem g_gridMenu05(GRIDPOWER_05); +GridMenuItem g_gridMenu1(GRIDPOWER_1); +GridMenuItem g_gridMenu2(GRIDPOWER_2); +GridMenuItem g_gridMenu4(GRIDPOWER_4); +GridMenuItem g_gridMenu8(GRIDPOWER_8); +GridMenuItem g_gridMenu16(GRIDPOWER_16); +GridMenuItem g_gridMenu32(GRIDPOWER_32); +GridMenuItem g_gridMenu64(GRIDPOWER_64); +GridMenuItem g_gridMenu128(GRIDPOWER_128); +GridMenuItem g_gridMenu256(GRIDPOWER_256); + +void setGridPower(GridPower power) +{ + g_grid_snap = true; + g_gridsize = GridSize_forGridPower(power); + + g_gridMenu0125.m_item.update(); + g_gridMenu025.m_item.update(); + g_gridMenu05.m_item.update(); + g_gridMenu1.m_item.update(); + g_gridMenu2.m_item.update(); + g_gridMenu4.m_item.update(); + g_gridMenu8.m_item.update(); + g_gridMenu16.m_item.update(); + g_gridMenu32.m_item.update(); + g_gridMenu64.m_item.update(); + g_gridMenu128.m_item.update(); + g_gridMenu256.m_item.update(); + GridChangeNotify(); +} + +void GridPrev() +{ + g_grid_snap = true; + if(g_grid_power > GRIDPOWER_0125) + { + setGridPower(static_cast(--g_grid_power)); + } +} + +void GridNext() +{ + g_grid_snap = true; + if(g_grid_power < GRIDPOWER_256) + { + setGridPower(static_cast(++g_grid_power)); + } +} + +void ToggleGridSnap() +{ + g_grid_snap = !g_grid_snap; + GridChangeNotify(); +} + +void Grid_registerCommands() +{ + GlobalCommands_insert("GridDown", FreeCaller(), Accelerator('[')); + GlobalCommands_insert("GridUp", FreeCaller(), Accelerator(']')); + + GlobalCommands_insert("ToggleGridSnap", FreeCaller()); + + GlobalToggles_insert("SetGrid0.125", GridMenuItem::SetCaller(g_gridMenu0125), ToggleItem::AddCallbackCaller(g_gridMenu0125.m_item)); + GlobalToggles_insert("SetGrid0.25", GridMenuItem::SetCaller(g_gridMenu025), ToggleItem::AddCallbackCaller(g_gridMenu025.m_item)); + GlobalToggles_insert("SetGrid0.5", GridMenuItem::SetCaller(g_gridMenu05), ToggleItem::AddCallbackCaller(g_gridMenu05.m_item)); + GlobalToggles_insert("SetGrid1", GridMenuItem::SetCaller(g_gridMenu1), ToggleItem::AddCallbackCaller(g_gridMenu1.m_item), Accelerator('1')); + GlobalToggles_insert("SetGrid2", GridMenuItem::SetCaller(g_gridMenu2), ToggleItem::AddCallbackCaller(g_gridMenu2.m_item), Accelerator('2')); + GlobalToggles_insert("SetGrid4", GridMenuItem::SetCaller(g_gridMenu4), ToggleItem::AddCallbackCaller(g_gridMenu4.m_item), Accelerator('3')); + GlobalToggles_insert("SetGrid8", GridMenuItem::SetCaller(g_gridMenu8), ToggleItem::AddCallbackCaller(g_gridMenu8.m_item), Accelerator('4')); + GlobalToggles_insert("SetGrid16", GridMenuItem::SetCaller(g_gridMenu16), ToggleItem::AddCallbackCaller(g_gridMenu16.m_item), Accelerator('5')); + GlobalToggles_insert("SetGrid32", GridMenuItem::SetCaller(g_gridMenu32), ToggleItem::AddCallbackCaller(g_gridMenu32.m_item), Accelerator('6')); + GlobalToggles_insert("SetGrid64", GridMenuItem::SetCaller(g_gridMenu64), ToggleItem::AddCallbackCaller(g_gridMenu64.m_item), Accelerator('7')); + GlobalToggles_insert("SetGrid128", GridMenuItem::SetCaller(g_gridMenu128), ToggleItem::AddCallbackCaller(g_gridMenu128.m_item), Accelerator('8')); + GlobalToggles_insert("SetGrid256", GridMenuItem::SetCaller(g_gridMenu256), ToggleItem::AddCallbackCaller(g_gridMenu256.m_item), Accelerator('9')); +} + + +void Grid_constructMenu(GtkMenu* menu) +{ + create_check_menu_item_with_mnemonic(menu, "Grid0.125", "SetGrid0.125"); + create_check_menu_item_with_mnemonic(menu, "Grid0.25", "SetGrid0.25"); + create_check_menu_item_with_mnemonic(menu, "Grid0.5", "SetGrid0.5"); + create_check_menu_item_with_mnemonic(menu, "Grid1", "SetGrid1"); + create_check_menu_item_with_mnemonic(menu, "Grid2", "SetGrid2"); + create_check_menu_item_with_mnemonic(menu, "Grid4", "SetGrid4"); + create_check_menu_item_with_mnemonic(menu, "Grid8", "SetGrid8"); + create_check_menu_item_with_mnemonic(menu, "Grid16", "SetGrid16"); + create_check_menu_item_with_mnemonic(menu, "Grid32", "SetGrid32"); + create_check_menu_item_with_mnemonic(menu, "Grid64", "SetGrid64"); + create_check_menu_item_with_mnemonic(menu, "Grid128", "SetGrid128"); + create_check_menu_item_with_mnemonic(menu, "Grid256", "SetGrid256"); +} + +void Grid_registerShortcuts() +{ + command_connect_accelerator("ToggleGrid"); + command_connect_accelerator("GridDown"); + command_connect_accelerator("GridUp"); + command_connect_accelerator("ToggleGridSnap"); +} + +void Grid_constructPreferences(PreferencesPage& page) +{ + page.appendCombo( + "Default grid spacing", + g_grid_default, + ARRAY_RANGE(g_gridnames) + ); +} +void Grid_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Grid", "Grid Settings")); + Grid_constructPreferences(page); +} +void Grid_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + +void Grid_construct() +{ + Grid_registerPreferencesPage(); + + g_grid_default = GridDefault_forGridPower(GRIDPOWER_8); + + GlobalPreferenceSystem().registerPreference("GridDefault", IntImportStringCaller(g_grid_default), IntExportStringCaller(g_grid_default)); + + g_grid_power = GridPower_forGridDefault(g_grid_default); + g_gridsize = GridSize_forGridPower(g_grid_power); +} + +void Grid_destroy() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/grid.h b/misc/mediasource/netradiant-src/radiant/grid.h new file mode 100644 index 00000000..42dfd703 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/grid.h @@ -0,0 +1,42 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_GRID_H) +#define INCLUDED_GRID_H + +#include "signal/signalfwd.h" + +float GetSnapGridSize(); +float GetGridSize(); +int Grid_getPower(); + +void AddGridChangeCallback(const SignalHandler& handler); + +void Grid_registerCommands(); +typedef struct _GtkMenu GtkMenu; +void Grid_constructMenu(GtkMenu* menu); + +void Grid_registerShortcuts(); + +void Grid_construct(); +void Grid_destroy(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/groupdialog.cpp b/misc/mediasource/netradiant-src/radiant/groupdialog.cpp new file mode 100644 index 00000000..1b89cc2f --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/groupdialog.cpp @@ -0,0 +1,232 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Floating dialog that contains a notebook with at least Entities and Group tabs +// I merged the 2 MS Windows dialogs in a single class +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "groupdialog.h" + +#include "debugging/debugging.h" + +#include + +#include +#include +#include +#include + +#include "gtkutil/widget.h" +#include "gtkutil/accelerator.h" +#include "entityinspector.h" +#include "gtkmisc.h" +#include "multimon.h" +#include "console.h" +#include "commands.h" + + +#include +#include "gtkutil/window.h" + +class GroupDlg +{ +public: + GtkWidget* m_pNotebook; + GtkWindow* m_window; + + GroupDlg(); + void Create(GtkWindow* parent); + + void Show() + { + // workaround for strange gtk behaviour - modifying the contents of a window while it is not visible causes the window position to change without sending a configure_event + m_position_tracker.sync(m_window); + gtk_widget_show(GTK_WIDGET(m_window)); + } + void Hide() + { + gtk_widget_hide(GTK_WIDGET(m_window)); + } + + WindowPositionTracker m_position_tracker; +}; + +namespace +{ + GroupDlg g_GroupDlg; + + std::size_t g_current_page; + std::vector g_pages; +} + +void GroupDialog_updatePageTitle(GtkWindow* window, std::size_t pageIndex) +{ + if(pageIndex < g_pages.size()) + { + g_pages[pageIndex](PointerCaller1(window)); + } +} + +static gboolean switch_page(GtkNotebook *notebook, GtkNotebookPage *page, guint page_num, gpointer data) +{ + GroupDialog_updatePageTitle(GTK_WINDOW(data), page_num); + g_current_page = page_num; + + return FALSE; +} + +GroupDlg::GroupDlg() : m_window(0) +{ + m_position_tracker.setPosition(c_default_window_pos); +} + +void GroupDlg::Create(GtkWindow* parent) +{ + ASSERT_MESSAGE(m_window == 0, "dialog already created"); + + GtkWindow* window = create_persistent_floating_window("Entities", parent); + + global_accel_connect_window(window); + + window_connect_focus_in_clear_focus_widget(window); + + m_window = window; + +#ifdef WIN32 + if( g_multimon_globals.m_bStartOnPrimMon ) + { + WindowPosition pos(m_position_tracker.getPosition()); + PositionWindowOnPrimaryScreen(pos); + m_position_tracker.setPosition(pos); + } +#endif + m_position_tracker.connect(window); + + { + GtkWidget* notebook = gtk_notebook_new(); + gtk_widget_show(notebook); + gtk_container_add (GTK_CONTAINER (window), notebook); + gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_BOTTOM); + m_pNotebook = notebook; + + g_signal_connect(G_OBJECT(notebook), "switch_page", G_CALLBACK(switch_page), window); + } +} + + +GtkWidget* GroupDialog_addPage(const char* tabLabel, GtkWidget* widget, const StringExportCallback& title) +{ + GtkWidget* w = gtk_label_new(tabLabel); + gtk_widget_show(w); + GtkWidget* page = gtk_notebook_get_nth_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gtk_notebook_insert_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), widget, w, -1)); + g_pages.push_back(title); + + return page; +} + + +bool GroupDialog_isShown() +{ + return widget_is_visible(GTK_WIDGET(g_GroupDlg.m_window)); +} +void GroupDialog_setShown(bool shown) +{ + shown ? g_GroupDlg.Show() : g_GroupDlg.Hide(); +} +void GroupDialog_ToggleShow() +{ + GroupDialog_setShown(!GroupDialog_isShown()); +} + +void GroupDialog_constructWindow(GtkWindow* main_window) +{ + g_GroupDlg.Create(main_window); +} +void GroupDialog_destroyWindow() +{ + ASSERT_NOTNULL(g_GroupDlg.m_window); + destroy_floating_window(g_GroupDlg.m_window); + g_GroupDlg.m_window = 0; +} + + +GtkWindow* GroupDialog_getWindow() +{ + return g_GroupDlg.m_window; +} +void GroupDialog_show() +{ + g_GroupDlg.Show(); +} + +GtkWidget* GroupDialog_getPage() +{ + return gtk_notebook_get_nth_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gint(g_current_page)); +} + +void GroupDialog_setPage(GtkWidget* page) +{ + g_current_page = gtk_notebook_page_num(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), page); + gtk_notebook_set_current_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gint(g_current_page)); +} + +void GroupDialog_showPage(GtkWidget* page) +{ + if(GroupDialog_getPage() == page) + { + GroupDialog_ToggleShow(); + } + else + { + gtk_widget_show(GTK_WIDGET(g_GroupDlg.m_window)); + GroupDialog_setPage(page); + } +} + +void GroupDialog_cycle() +{ + g_current_page = (g_current_page + 1) % g_pages.size(); + gtk_notebook_set_current_page(GTK_NOTEBOOK(g_GroupDlg.m_pNotebook), gint(g_current_page)); +} + +void GroupDialog_updatePageTitle(GtkWidget* page) +{ + if(GroupDialog_getPage() == page) + { + GroupDialog_updatePageTitle(g_GroupDlg.m_window, g_current_page); + } +} + + +#include "preferencesystem.h" + +void GroupDialog_Construct() +{ + GlobalPreferenceSystem().registerPreference("EntityWnd", WindowPositionTrackerImportStringCaller(g_GroupDlg.m_position_tracker), WindowPositionTrackerExportStringCaller(g_GroupDlg.m_position_tracker)); + + GlobalCommands_insert("ViewEntityInfo", FreeCaller(), Accelerator('N')); +} +void GroupDialog_Destroy() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/groupdialog.h b/misc/mediasource/netradiant-src/radiant/groupdialog.h new file mode 100644 index 00000000..92caffab --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/groupdialog.h @@ -0,0 +1,48 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_GROUPDIALOG_H) +#define INCLUDED_GROUPDIALOG_H + +#include "generic/callback.h" + +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; + +void GroupDialog_Construct(); +void GroupDialog_Destroy(); + +void GroupDialog_constructWindow(GtkWindow* main_window); +void GroupDialog_destroyWindow(); +GtkWindow* GroupDialog_getWindow(); +void GroupDialog_show(); + +inline void RawStringExport(const char* string, const StringImportCallback& importer) +{ + importer(string); +} +typedef ConstPointerCaller1 RawStringExportCaller; +GtkWidget* GroupDialog_addPage(const char* tabLabel, GtkWidget* widget, const StringExportCallback& title); + +void GroupDialog_showPage(GtkWidget* page); +void GroupDialog_updatePageTitle(GtkWidget* page); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/gtkdlgs.cpp b/misc/mediasource/netradiant-src/radiant/gtkdlgs.cpp new file mode 100644 index 00000000..57ed278d --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/gtkdlgs.cpp @@ -0,0 +1,1105 @@ +/* +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. +*/ + +// +// Some small dialogs that don't need much +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "gtkdlgs.h" + +#include "debugging/debugging.h" +#include "version.h" +#include "aboutmsg.h" + +#include "igl.h" +#include "iscenegraph.h" +#include "iselection.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "os/path.h" +#include "math/aabb.h" +#include "container/array.h" +#include "generic/static.h" +#include "stream/stringstream.h" +#include "convert.h" +#include "gtkutil/messagebox.h" +#include "gtkutil/image.h" + +#include "gtkmisc.h" +#include "brushmanip.h" +#include "build.h" +#include "qe3.h" +#include "texwindow.h" +#include "xywindow.h" +#include "mainframe.h" +#include "preferences.h" +#include "url.h" +#include "cmdlib.h" + + + +// ============================================================================= +// Project settings dialog + +class GameComboConfiguration +{ +public: + const char* basegame_dir; + const char* basegame; + const char* known_dir; + const char* known; + const char* custom; + + GameComboConfiguration() : + basegame_dir(g_pGameDescription->getRequiredKeyValue("basegame")), + basegame(g_pGameDescription->getRequiredKeyValue("basegamename")), + known_dir(g_pGameDescription->getKeyValue("knowngame")), + known(g_pGameDescription->getKeyValue("knowngamename")), + custom(g_pGameDescription->getRequiredKeyValue("unknowngamename")) + { + } +}; + +typedef LazyStatic LazyStaticGameComboConfiguration; + +inline GameComboConfiguration& globalGameComboConfiguration() +{ + return LazyStaticGameComboConfiguration::instance(); +} + + +struct gamecombo_t +{ + gamecombo_t(int _game, const char* _fs_game, bool _sensitive) + : game(_game), fs_game(_fs_game), sensitive(_sensitive) + {} + int game; + const char* fs_game; + bool sensitive; +}; + +gamecombo_t gamecombo_for_dir(const char* dir) +{ + if(string_equal(dir, globalGameComboConfiguration().basegame_dir)) + { + return gamecombo_t(0, "", false); + } + else if(string_equal(dir, globalGameComboConfiguration().known_dir)) + { + return gamecombo_t(1, dir, false); + } + else + { + return gamecombo_t(string_empty(globalGameComboConfiguration().known_dir) ? 1 : 2, dir, true); + } +} + +gamecombo_t gamecombo_for_gamename(const char* gamename) +{ + if ((strlen(gamename) == 0) || !strcmp(gamename, globalGameComboConfiguration().basegame)) + { + return gamecombo_t(0, "", false); + } + else if (!strcmp(gamename, globalGameComboConfiguration().known)) + { + return gamecombo_t(1, globalGameComboConfiguration().known_dir, false); + } + else + { + return gamecombo_t(string_empty(globalGameComboConfiguration().known_dir) ? 1 : 2, "", true); + } +} + +inline void path_copy_clean(char* destination, const char* source) +{ + char* i = destination; + + while(*source != '\0') + { + *i++ = (*source == '\\') ? '/' : *source; + ++source; + } + + if(i != destination && *(i-1) != '/') + *(i++) = '/'; + + *i = '\0'; +} + + +struct GameCombo +{ + GtkComboBox* game_select; + GtkEntry* fsgame_entry; +}; + +gboolean OnSelchangeComboWhatgame(GtkWidget *widget, GameCombo* combo) +{ + const char *gamename; + { + GtkTreeIter iter; + gtk_combo_box_get_active_iter(combo->game_select, &iter); + gtk_tree_model_get(gtk_combo_box_get_model(combo->game_select), &iter, 0, (gpointer*)&gamename, -1); + } + + gamecombo_t gamecombo = gamecombo_for_gamename(gamename); + + gtk_entry_set_text(combo->fsgame_entry, gamecombo.fs_game); + gtk_widget_set_sensitive(GTK_WIDGET(combo->fsgame_entry), gamecombo.sensitive); + + return FALSE; +} + +class MappingMode +{ +public: + bool do_mapping_mode; + const char* sp_mapping_mode; + const char* mp_mapping_mode; + + MappingMode() : + do_mapping_mode(!string_empty(g_pGameDescription->getKeyValue("show_gamemode"))), + sp_mapping_mode("Single Player mapping mode"), + mp_mapping_mode("Multiplayer mapping mode") + { + } +}; + +typedef LazyStatic LazyStaticMappingMode; + +inline MappingMode& globalMappingMode() +{ + return LazyStaticMappingMode::instance(); +} + +class ProjectSettingsDialog +{ +public: + GameCombo game_combo; + GtkComboBox* gamemode_combo; +}; + +GtkWindow* ProjectSettingsDialog_construct(ProjectSettingsDialog& dialog, ModalDialog& modal) +{ + GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Project Settings", G_CALLBACK(dialog_delete_callback), &modal); + + { + GtkTable* table1 = create_dialog_table(1, 2, 4, 4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(table1)); + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_table_attach(table1, GTK_WIDGET(vbox), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (GTK_FILL), 0, 0); + { + GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &modal); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + { + GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &modal); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + } + { + GtkFrame* frame = create_dialog_frame("Project settings"); + gtk_table_attach(table1, GTK_WIDGET(frame), 0, 1, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (GTK_FILL), 0, 0); + { + GtkTable* table2 = create_dialog_table((globalMappingMode().do_mapping_mode) ? 4 : 3, 2, 4, 4, 4); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(table2)); + + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Select mod")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table2, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + } + { + dialog.game_combo.game_select = GTK_COMBO_BOX(gtk_combo_box_new_text()); + + gtk_combo_box_append_text(dialog.game_combo.game_select, globalGameComboConfiguration().basegame); + if(globalGameComboConfiguration().known[0] != '\0') + gtk_combo_box_append_text(dialog.game_combo.game_select, globalGameComboConfiguration().known); + gtk_combo_box_append_text(dialog.game_combo.game_select, globalGameComboConfiguration().custom); + + gtk_widget_show(GTK_WIDGET(dialog.game_combo.game_select)); + gtk_table_attach(table2, GTK_WIDGET(dialog.game_combo.game_select), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + g_signal_connect(G_OBJECT(dialog.game_combo.game_select), "changed", G_CALLBACK(OnSelchangeComboWhatgame), &dialog.game_combo); + } + + { + GtkLabel* label = GTK_LABEL(gtk_label_new("fs_game")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table2, GTK_WIDGET(label), 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table2, GTK_WIDGET(entry), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + dialog.game_combo.fsgame_entry = entry; + } + + if(globalMappingMode().do_mapping_mode) + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Mapping mode")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table2, GTK_WIDGET(label), 0, 1, 3, 4, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + + GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); + gtk_combo_box_append_text(combo, globalMappingMode().sp_mapping_mode); + gtk_combo_box_append_text(combo, globalMappingMode().mp_mapping_mode); + + gtk_widget_show(GTK_WIDGET(combo)); + gtk_table_attach(table2, GTK_WIDGET(combo), 1, 2, 3, 4, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + dialog.gamemode_combo = combo; + } + } + } + } + + // initialise the fs_game selection from the project settings into the dialog + const char* dir = gamename_get(); + gamecombo_t gamecombo = gamecombo_for_dir(dir); + + gtk_combo_box_set_active(dialog.game_combo.game_select, gamecombo.game); + gtk_entry_set_text(dialog.game_combo.fsgame_entry, gamecombo.fs_game); + gtk_widget_set_sensitive(GTK_WIDGET(dialog.game_combo.fsgame_entry), gamecombo.sensitive); + + if(globalMappingMode().do_mapping_mode) + { + const char *gamemode = gamemode_get(); + if (string_empty(gamemode) || string_equal(gamemode, "sp")) + { + gtk_combo_box_set_active(dialog.gamemode_combo, 0); + } + else + { + gtk_combo_box_set_active(dialog.gamemode_combo, 1); + } + } + + return window; +} + +void ProjectSettingsDialog_ok(ProjectSettingsDialog& dialog) +{ + const char* dir = gtk_entry_get_text(dialog.game_combo.fsgame_entry); + + const char* new_gamename = path_equal(dir, globalGameComboConfiguration().basegame_dir) + ? "" + : dir; + + if(!path_equal(new_gamename, gamename_get())) + { + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Changing Game Name"); + + EnginePath_Unrealise(); + + gamename_set(new_gamename); + + EnginePath_Realise(); + } + + if(globalMappingMode().do_mapping_mode) + { + // read from gamemode_combo + int active = gtk_combo_box_get_active(dialog.gamemode_combo); + if(active == -1 || active == 0) + { + gamemode_set("sp"); + } + else + { + gamemode_set("mp"); + } + } +} + +void DoProjectSettings() +{ + if(ConfirmModified("Edit Project Settings")) + { + ModalDialog modal; + ProjectSettingsDialog dialog; + + GtkWindow* window = ProjectSettingsDialog_construct(dialog, modal); + + if(modal_dialog_show(window, modal) == eIDOK) + { + ProjectSettingsDialog_ok(dialog); + } + + gtk_widget_destroy(GTK_WIDGET(window)); + } +} + +// ============================================================================= +// Arbitrary Sides dialog + +void DoSides (int type, int axis) +{ + ModalDialog dialog; + GtkEntry* sides_entry; + + GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Arbitrary sides", G_CALLBACK(dialog_delete_callback), &dialog); + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Sides:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(label), FALSE, FALSE, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(entry), FALSE, FALSE, 0); + sides_entry = entry; + gtk_widget_grab_focus(GTK_WIDGET(entry)); + } + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); + } + } + } + + if(modal_dialog_show(window, dialog) == eIDOK) + { + const char *str = gtk_entry_get_text(sides_entry); + + Scene_BrushConstructPrefab(GlobalSceneGraph(), (EBrushPrefab)type, atoi(str), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); + } + + gtk_widget_destroy(GTK_WIDGET(window)); +} + +// ============================================================================= +// About dialog (no program is complete without one) + +void about_button_changelog (GtkWidget *widget, gpointer data) +{ + StringOutputStream log(256); + log << AppPath_get() << "changelog.txt"; + OpenURL(log.c_str()); +} + +void about_button_credits (GtkWidget *widget, gpointer data) +{ + StringOutputStream cred(256); + cred << AppPath_get() << "credits.html"; + OpenURL(cred.c_str()); +} + +void DoAbout() +{ + ModalDialog dialog; + ModalDialogButton ok_button(dialog, eIDOK); + + GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "About NetRadiant", dialog); + + { + GtkVBox* vbox = create_dialog_vbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); + + { + GtkHBox* hbox = create_dialog_hbox(4); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, TRUE, 0); + + { + GtkVBox* vbox2 = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), TRUE, FALSE, 0); + { + GtkFrame* frame = create_dialog_frame(0, GTK_SHADOW_IN); + gtk_box_pack_start(GTK_BOX (vbox2), GTK_WIDGET(frame), FALSE, FALSE, 0); + { + GtkImage* image = new_local_image("logo.bmp"); + gtk_widget_show(GTK_WIDGET(image)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(image)); + } + } + } + + { + GtkLabel* label = GTK_LABEL(gtk_label_new("NetRadiant " RADIANT_VERSION "\n" + __DATE__ "\n\n" + RADIANT_ABOUTMSG "\n\n" + "By alientrap.org\n\n" + "This program is free software\n" + "licensed under the GNU GPL.\n\n" + "NetRadiant is unsupported, however\n" + "you may report your problems at\n" + "http://www.icculus.org/netradiant/" + )); + + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(label), FALSE, FALSE, 0); + gtk_misc_set_alignment(GTK_MISC(label), 1, 0.5); + gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); + } + + { + GtkVBox* vbox2 = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), FALSE, TRUE, 0); + { + GtkButton* button = create_modal_dialog_button("OK", ok_button); + gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); + } + { + GtkButton* button = create_dialog_button("Credits", G_CALLBACK(about_button_credits), 0); + gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); + } + { + GtkButton* button = create_dialog_button("Changelog", G_CALLBACK(about_button_changelog), 0); + gtk_box_pack_start (GTK_BOX (vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); + } + } + } + { + GtkFrame* frame = create_dialog_frame("OpenGL Properties"); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), FALSE, FALSE, 0); + { + GtkTable* table = create_dialog_table(3, 2, 4, 4, 4); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(table)); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Vendor:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Version:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Renderer:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new(reinterpret_cast(glGetString(GL_VENDOR)))); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new(reinterpret_cast(glGetString(GL_VERSION)))); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new(reinterpret_cast(glGetString(GL_RENDERER)))); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + } + { + GtkFrame* frame = create_dialog_frame("OpenGL Extensions"); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); + { + GtkScrolledWindow* sc_extensions = create_scrolled_window(GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS, 4); + gtk_container_add (GTK_CONTAINER (frame), GTK_WIDGET(sc_extensions)); + { + GtkWidget* text_extensions = gtk_text_view_new(); + gtk_text_view_set_editable(GTK_TEXT_VIEW(text_extensions), FALSE); + gtk_container_add (GTK_CONTAINER (sc_extensions), text_extensions); + GtkTextBuffer* buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_extensions)); + gtk_text_buffer_set_text(buffer, reinterpret_cast(glGetString(GL_EXTENSIONS)), -1); + gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_extensions), GTK_WRAP_WORD); + gtk_widget_show(text_extensions); + } + } + } + } + } + + modal_dialog_show(window, dialog); + + gtk_widget_destroy(GTK_WIDGET(window)); +} + +// ============================================================================= +// TextureLayout dialog + +EMessageBoxReturn DoTextureLayout (float *fx, float *fy) +{ + ModalDialog dialog; + ModalDialogButton ok_button(dialog, eIDOK); + ModalDialogButton cancel_button(dialog, eIDCANCEL); + GtkEntry* x; + GtkEntry* y; + + GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Patch texture layout", dialog); + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Texture will be fit across the patch based\n" + "on the x and y values given. Values of 1x1\n" + "will \"fit\" the texture. 2x2 will repeat\n" + "it twice, etc.")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), TRUE, TRUE, 0); + gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); + } + { + GtkTable* table = create_dialog_table(2, 2, 4, 4); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), TRUE, TRUE, 0); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Texture x:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Texture y:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + gtk_widget_grab_focus(GTK_WIDGET(entry)); + + x = entry; + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + y = entry; + } + } + } + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); + { + GtkButton* button = create_modal_dialog_button("OK", ok_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); + } + } + } + + // Initialize + gtk_entry_set_text(x, "4.0"); + gtk_entry_set_text(y, "4.0"); + + + EMessageBoxReturn ret = modal_dialog_show(window, dialog); + if (ret == eIDOK) + { + *fx = static_cast(atof(gtk_entry_get_text(x))); + *fy = static_cast(atof(gtk_entry_get_text(y))); + } + + gtk_widget_destroy(GTK_WIDGET(window)); + + return ret; +} + +// ============================================================================= +// Text Editor dialog + +// master window widget +static GtkWidget *text_editor = 0; +static GtkWidget *text_widget; // slave, text widget from the gtk editor + +static gint editor_delete (GtkWidget *widget, gpointer data) +{ + if (gtk_MessageBox (widget, "Close the shader editor ?", "Radiant", eMB_YESNO, eMB_ICONQUESTION) == eIDNO) + return TRUE; + + gtk_widget_hide (text_editor); + + return TRUE; +} + +static void editor_save (GtkWidget *widget, gpointer data) +{ + FILE *f = fopen ((char*)g_object_get_data (G_OBJECT (data), "filename"), "w"); + gpointer text = g_object_get_data (G_OBJECT (data), "text"); + + if (f == 0) + { + gtk_MessageBox (GTK_WIDGET(data), "Error saving file !"); + return; + } + + char *str = gtk_editable_get_chars (GTK_EDITABLE (text), 0, -1); + fwrite (str, 1, strlen (str), f); + fclose (f); +} + +static void editor_close (GtkWidget *widget, gpointer data) +{ + if (gtk_MessageBox (text_editor, "Close the shader editor ?", "Radiant", eMB_YESNO, eMB_ICONQUESTION) == eIDNO) + return; + + gtk_widget_hide (text_editor); +} + +static void CreateGtkTextEditor() +{ + GtkWidget *dlg; + GtkWidget *vbox, *hbox, *button, *scr, *text; + + dlg = gtk_window_new (GTK_WINDOW_TOPLEVEL); + + g_signal_connect(G_OBJECT(dlg), "delete_event", + G_CALLBACK(editor_delete), 0); + gtk_window_set_default_size (GTK_WINDOW (dlg), 600, 300); + + vbox = gtk_vbox_new (FALSE, 5); + gtk_widget_show (vbox); + gtk_container_add(GTK_CONTAINER(dlg), GTK_WIDGET(vbox)); + gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); + + scr = gtk_scrolled_window_new (0, 0); + gtk_widget_show (scr); + gtk_box_pack_start(GTK_BOX(vbox), scr, TRUE, TRUE, 0); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scr), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(scr), GTK_SHADOW_IN); + + text = gtk_text_view_new(); + gtk_container_add (GTK_CONTAINER (scr), text); + gtk_widget_show (text); + g_object_set_data (G_OBJECT (dlg), "text", text); + gtk_text_view_set_editable (GTK_TEXT_VIEW(text), TRUE); + + hbox = gtk_hbox_new (FALSE, 5); + gtk_widget_show (hbox); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, TRUE, 0); + + button = gtk_button_new_with_label ("Close"); + gtk_widget_show (button); + gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(editor_close), dlg); + gtk_widget_set_usize (button, 60, -2); + + button = gtk_button_new_with_label ("Save"); + gtk_widget_show (button); + gtk_box_pack_end (GTK_BOX (hbox), button, FALSE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(editor_save), dlg); + gtk_widget_set_usize (button, 60, -2); + + text_editor = dlg; + text_widget = text; +} + +static void DoGtkTextEditor (const char* filename, guint cursorpos) +{ + if (!text_editor) + CreateGtkTextEditor(); // build it the first time we need it + + // Load file + FILE *f = fopen (filename, "r"); + + if (f == 0) + { + globalOutputStream() << "Unable to load file " << filename << " in shader editor.\n"; + gtk_widget_hide (text_editor); + } + else + { + fseek (f, 0, SEEK_END); + int len = ftell (f); + void *buf = malloc (len); + void *old_filename; + + rewind (f); + fread (buf, 1, len, f); + + gtk_window_set_title (GTK_WINDOW (text_editor), filename); + + GtkTextBuffer* text_buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_widget)); + gtk_text_buffer_set_text(text_buffer, (char*)buf, len); + + old_filename = g_object_get_data (G_OBJECT (text_editor), "filename"); + if (old_filename) + free(old_filename); + g_object_set_data (G_OBJECT (text_editor), "filename", strdup (filename)); + + // trying to show later + gtk_widget_show (text_editor); + +#ifdef WIN32 + process_gui(); +#endif + + // only move the cursor if it's not exceeding the size.. + // NOTE: this is erroneous, cursorpos is the offset in bytes, not in characters + // len is the max size in bytes, not in characters either, but the character count is below that limit.. + // thinking .. the difference between character count and byte count would be only because of CR/LF? + { + GtkTextIter text_iter; + // character offset, not byte offset + gtk_text_buffer_get_iter_at_offset(text_buffer, &text_iter, cursorpos); + gtk_text_buffer_place_cursor(text_buffer, &text_iter); + } + +#ifdef WIN32 + gtk_widget_queue_draw(text_widget); +#endif + + free (buf); + fclose (f); + } +} + +// ============================================================================= +// Light Intensity dialog + +EMessageBoxReturn DoLightIntensityDlg (int *intensity) +{ + ModalDialog dialog; + GtkEntry* intensity_entry; + ModalDialogButton ok_button(dialog, eIDOK); + ModalDialogButton cancel_button(dialog, eIDCANCEL); + + GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Light intensity", dialog, -1, -1); + + GtkAccelGroup *accel_group = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel_group); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("ESC for default, ENTER to validate")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(entry), TRUE, TRUE, 0); + + gtk_widget_grab_focus(GTK_WIDGET(entry)); + + intensity_entry = entry; + } + } + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); + + { + GtkButton* button = create_modal_dialog_button("OK", ok_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); + } + { + GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Escape, (GdkModifierType)0, GTK_ACCEL_VISIBLE); + } + } + } + + char buf[16]; + sprintf (buf, "%d", *intensity); + gtk_entry_set_text(intensity_entry, buf); + + EMessageBoxReturn ret = modal_dialog_show(window, dialog); + if(ret == eIDOK) + *intensity = atoi (gtk_entry_get_text(intensity_entry)); + + gtk_widget_destroy(GTK_WIDGET(window)); + + return ret; +} + +// ============================================================================= +// Add new shader tag dialog + +EMessageBoxReturn DoShaderTagDlg (CopiedString* tag, char* title) +{ + ModalDialog dialog; + GtkEntry* textentry; + ModalDialogButton ok_button(dialog, eIDOK); + ModalDialogButton cancel_button(dialog, eIDCANCEL); + + GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), title, dialog, -1, -1); + + GtkAccelGroup *accel_group = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel_group); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + //GtkLabel* label = GTK_LABEL(gtk_label_new("Enter one ore more tags separated by spaces")); + GtkLabel* label = GTK_LABEL(gtk_label_new("ESC to cancel, ENTER to validate")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(entry), TRUE, TRUE, 0); + + gtk_widget_grab_focus(GTK_WIDGET(entry)); + + textentry = entry; + } + } + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); + + { + GtkButton* button = create_modal_dialog_button("OK", ok_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); + } + { + GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Escape, (GdkModifierType)0, GTK_ACCEL_VISIBLE); + } + } + } + + EMessageBoxReturn ret = modal_dialog_show(window, dialog); + if(ret == eIDOK) + { + *tag = gtk_entry_get_text(textentry); + } + + gtk_widget_destroy(GTK_WIDGET(window)); + + return ret; +} + +EMessageBoxReturn DoShaderInfoDlg (const char* name, const char* filename, char* title) +{ + ModalDialog dialog; + ModalDialogButton ok_button(dialog, eIDOK); + + GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), title, dialog, -1, -1); + + GtkAccelGroup *accel_group = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel_group); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("The selected shader")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new(name)); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("is located in file")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new(filename)); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, FALSE, 0); + } + { + GtkButton* button = create_modal_dialog_button("OK", ok_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); + } + } + } + + EMessageBoxReturn ret = modal_dialog_show(window, dialog); + + gtk_widget_destroy(GTK_WIDGET(window)); + + return ret; +} + + + +#ifdef WIN32 +#include +#endif + +#ifdef WIN32 + // use the file associations to open files instead of builtin Gtk editor +bool g_TextEditor_useWin32Editor = true; +#else + // custom shader editor +bool g_TextEditor_useCustomEditor = false; +CopiedString g_TextEditor_editorCommand(""); +#endif + +void DoTextEditor (const char* filename, int cursorpos) +{ +#ifdef WIN32 + if (g_TextEditor_useWin32Editor) + { + globalOutputStream() << "opening file '" << filename << "' (line " << cursorpos << " info ignored)\n"; + ShellExecute((HWND)GDK_WINDOW_HWND (GTK_WIDGET(MainFrame_getWindow())->window), "open", filename, 0, 0, SW_SHOW ); + return; + } +#else + // check if a custom editor is set + if(g_TextEditor_useCustomEditor && !g_TextEditor_editorCommand.empty()) + { + StringOutputStream strEditCommand(256); + strEditCommand << g_TextEditor_editorCommand.c_str() << " \"" << filename << "\""; + + globalOutputStream() << "Launching: " << strEditCommand.c_str() << "\n"; + // note: linux does not return false if the command failed so it will assume success + if (Q_Exec(0, const_cast(strEditCommand.c_str()), 0, true, false) == false) + { + globalOutputStream() << "Failed to execute " << strEditCommand.c_str() << ", using default\n"; + } + else + { + // the command (appeared) to run successfully, no need to do anything more + return; + } + } +#endif + + DoGtkTextEditor (filename, cursorpos); +} diff --git a/misc/mediasource/netradiant-src/radiant/gtkdlgs.h b/misc/mediasource/netradiant-src/radiant/gtkdlgs.h new file mode 100644 index 00000000..36989916 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/gtkdlgs.h @@ -0,0 +1,59 @@ +/* +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. +*/ + +#if !defined(INCLUDED_GTKDLGS_H) +#define INCLUDED_GTKDLGS_H + +#include "qerplugin.h" +#include "string/string.h" + +EMessageBoxReturn DoLightIntensityDlg (int *intensity); +EMessageBoxReturn DoShaderTagDlg (CopiedString *tag, char* title); +EMessageBoxReturn DoShaderInfoDlg (const char* name, const char* filename, char* title); +EMessageBoxReturn DoTextureLayout (float *fx, float *fy); +void DoTextEditor (const char* filename, int cursorpos); + +void DoProjectSettings(); + +void DoFind(); +void DoSides(int type, int axis); +void DoAbout(); + + +#ifdef WIN32 +extern bool g_TextEditor_useWin32Editor; +#else +#include "string/stringfwd.h" +extern bool g_TextEditor_useCustomEditor; +extern CopiedString g_TextEditor_editorCommand; +#endif + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/gtkmisc.cpp b/misc/mediasource/netradiant-src/radiant/gtkmisc.cpp new file mode 100644 index 00000000..fc28c5d7 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/gtkmisc.cpp @@ -0,0 +1,170 @@ +/* +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. +*/ + +// +// Small functions to help with GTK +// + +#include "gtkmisc.h" + +#include +#include + +#include "math/vector.h" +#include "os/path.h" + +#include "gtkutil/dialog.h" +#include "gtkutil/filechooser.h" +#include "gtkutil/menu.h" +#include "gtkutil/toolbar.h" +#include "commands.h" + + +// ============================================================================= +// Misc stuff + +void command_connect_accelerator(const char* name) +{ + const Command& command = GlobalCommands_find(name); + GlobalShortcuts_register(name, 1); + global_accel_group_connect(command.m_accelerator, command.m_callback); +} + +void command_disconnect_accelerator(const char* name) +{ + const Command& command = GlobalCommands_find(name); + global_accel_group_disconnect(command.m_accelerator, command.m_callback); +} + +void toggle_add_accelerator(const char* name) +{ + const Toggle& toggle = GlobalToggles_find(name); + GlobalShortcuts_register(name, 2); + global_accel_group_connect(toggle.m_command.m_accelerator, toggle.m_command.m_callback); +} + +void toggle_remove_accelerator(const char* name) +{ + const Toggle& toggle = GlobalToggles_find(name); + global_accel_group_disconnect(toggle.m_command.m_accelerator, toggle.m_command.m_callback); +} + +GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const char* commandName) +{ + GlobalShortcuts_register(commandName, 2); + const Toggle& toggle = GlobalToggles_find(commandName); + global_accel_group_connect(toggle.m_command.m_accelerator, toggle.m_command.m_callback); + return create_check_menu_item_with_mnemonic(menu, mnemonic, toggle); +} + +GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu* menu, const char *mnemonic, const char* commandName) +{ + GlobalShortcuts_register(commandName, 1); + const Command& command = GlobalCommands_find(commandName); + global_accel_group_connect(command.m_accelerator, command.m_callback); + return create_menu_item_with_mnemonic(menu, mnemonic, command); +} + +GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName) +{ + return toolbar_append_button(toolbar, description, icon, GlobalCommands_find(commandName)); +} + +GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName) +{ + return toolbar_append_toggle_button(toolbar, description, icon, GlobalToggles_find(commandName)); +} + +// ============================================================================= +// File dialog + +bool color_dialog (GtkWidget *parent, Vector3& color, const char* title) +{ + GtkWidget* dlg; + double clr[3]; + ModalDialog dialog; + + clr[0] = color[0]; + clr[1] = color[1]; + clr[2] = color[2]; + + dlg = gtk_color_selection_dialog_new (title); + gtk_color_selection_set_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), clr); + g_signal_connect(G_OBJECT(dlg), "delete_event", G_CALLBACK(dialog_delete_callback), &dialog); + g_signal_connect(G_OBJECT(GTK_COLOR_SELECTION_DIALOG(dlg)->ok_button), "clicked", G_CALLBACK(dialog_button_ok), &dialog); + g_signal_connect(G_OBJECT(GTK_COLOR_SELECTION_DIALOG(dlg)->cancel_button), "clicked", G_CALLBACK(dialog_button_cancel), &dialog); + + if (parent != 0) + gtk_window_set_transient_for (GTK_WINDOW (dlg), GTK_WINDOW (parent)); + + bool ok = modal_dialog_show(GTK_WINDOW(dlg), dialog) == eIDOK; + if(ok) + { + GdkColor gdkcolor; + gtk_color_selection_get_current_color (GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dlg)->colorsel), &gdkcolor); + clr[0] = gdkcolor.red / 65535.0; + clr[1] = gdkcolor.green / 65535.0; + clr[2] = gdkcolor.blue / 65535.0; + + color[0] = (float)clr[0]; + color[1] = (float)clr[1]; + color[2] = (float)clr[2]; + } + + gtk_widget_destroy(dlg); + + return ok; +} + +void button_clicked_entry_browse_file(GtkWidget* widget, GtkEntry* entry) +{ + const char *filename = file_dialog(gtk_widget_get_toplevel(widget), TRUE, "Choose File", gtk_entry_get_text(entry)); + + if(filename != 0) + { + gtk_entry_set_text(entry, filename); + } +} + +void button_clicked_entry_browse_directory(GtkWidget* widget, GtkEntry* entry) +{ + const char* text = gtk_entry_get_text(entry); + char *dir = dir_dialog(gtk_widget_get_toplevel(widget), "Choose Directory", path_is_absolute(text) ? text : "" ); + + if(dir != 0) + { + gchar* converted = g_filename_to_utf8(dir, -1, 0, 0, 0); + gtk_entry_set_text(entry, converted); + g_free(dir); + g_free(converted); + } +} + + diff --git a/misc/mediasource/netradiant-src/radiant/gtkmisc.h b/misc/mediasource/netradiant-src/radiant/gtkmisc.h new file mode 100644 index 00000000..c1ddf0b1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/gtkmisc.h @@ -0,0 +1,76 @@ +/* +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. +*/ + +#if !defined(INCLUDED_GTKMISC_H) +#define INCLUDED_GTKMISC_H + +#include + +inline void process_gui() +{ + while(gtk_events_pending()) + { + gtk_main_iteration(); + } +} + +void command_connect_accelerator(const char* commandName); +void command_disconnect_accelerator(const char* commandName); +void toggle_add_accelerator(const char* commandName); +void toggle_remove_accelerator(const char* name); + +typedef struct _GtkMenu GtkMenu; +typedef struct _GtkMenuItem GtkMenuItem; +typedef struct _GtkCheckMenuItem GtkCheckMenuItem; + +// this also sets up the shortcut using command_connect_accelerator +GtkMenuItem* create_menu_item_with_mnemonic(GtkMenu *menu, const char *mnemonic, const char* commandName); +// this also sets up the shortcut using command_connect_accelerator +GtkCheckMenuItem* create_check_menu_item_with_mnemonic(GtkMenu* menu, const char* mnemonic, const char* commandName); + +typedef struct _GtkButton GtkButton; +typedef struct _GtkToggleButton GtkToggleButton; +typedef struct _GtkToolbar GtkToolbar; + +// this DOES NOT set up the shortcut using command_connect_accelerator +GtkButton* toolbar_append_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName); +// this DOES NOT set up the shortcut using command_connect_accelerator +GtkToggleButton* toolbar_append_toggle_button(GtkToolbar* toolbar, const char* description, const char* icon, const char* commandName); + + +template class BasicVector3; +typedef BasicVector3 Vector3; +bool color_dialog (GtkWidget *parent, Vector3& color, const char* title = "Choose Color"); + +typedef struct _GtkEntry GtkEntry; +void button_clicked_entry_browse_file(GtkWidget* widget, GtkEntry* entry); +void button_clicked_entry_browse_directory(GtkWidget* widget, GtkEntry* entry); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/help.cpp b/misc/mediasource/netradiant-src/radiant/help.cpp new file mode 100644 index 00000000..363b1f0a --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/help.cpp @@ -0,0 +1,140 @@ +/* +Copyright (C) 1999-2006 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 "help.h" + +#include "debugging/debugging.h" + +#include +#include + +#include "libxml/parser.h" +#include "generic/callback.h" +#include "gtkutil/menu.h" +#include "stream/stringstream.h" +#include "os/file.h" + +#include "url.h" +#include "preferences.h" +#include "mainframe.h" + +/*! +the urls to fire up in the game packs help menus +*/ +namespace +{ + std::list mHelpURLs; +} + +/*! +needed for hooking in Gtk+ +*/ +void HandleHelpCommand(CopiedString& str) +{ + OpenURL(str.c_str()); +} + +void process_xlink(const char* filename, const char *menu_name, const char *base_url, GtkMenu *menu) +{ + if(file_exists(filename)) + { + xmlDocPtr pDoc = xmlParseFile(filename); + if (pDoc) + { + globalOutputStream() << "Processing .xlink file '" << filename << "'\n"; + // create sub menu + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic(menu, menu_name); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + // start walking the nodes, find the 'links' one + xmlNodePtr pNode = pDoc->children; + while (pNode && strcmp((const char*)pNode->name, "links")) + pNode=pNode->next; + if (pNode) + { + pNode = pNode->children; + while(pNode) + { + if(!strcmp((const char*)pNode->name, "item")) + { + // process the URL + CopiedString url; + + xmlChar* prop = xmlGetProp(pNode, reinterpret_cast("url")); + ASSERT_NOTNULL(prop); + if(strstr(reinterpret_cast(prop), "http://")) + { + // complete URL + url = reinterpret_cast(prop); + } + else + { + // relative URL + StringOutputStream full(256); + full << base_url << reinterpret_cast(prop); + url = full.c_str(); + } + + mHelpURLs.push_back(url); + + xmlFree(prop); + + prop = xmlGetProp(pNode, reinterpret_cast("name")); + ASSERT_NOTNULL(prop); + create_menu_item_with_mnemonic(menu_in_menu, reinterpret_cast(prop), ReferenceCaller(mHelpURLs.back())); + xmlFree(prop); + } + pNode=pNode->next; + } + } + xmlFreeDoc(pDoc); + } + else + { + globalOutputStream() << "'" << filename << "' parse failed\n"; + } + } + else + { + globalOutputStream() << "'" << filename << "' not found\n"; + } +} + +void create_game_help_menu(GtkMenu *menu) +{ + StringOutputStream filename(256); + filename << AppPath_get() << "global.xlink"; + process_xlink(filename.c_str(), "General", AppPath_get(), menu); + +#if 1 + filename.clear(); + filename << g_pGameDescription->mGameToolsPath.c_str() << "game.xlink"; + process_xlink(filename.c_str(), g_pGameDescription->getRequiredKeyValue("name"), g_pGameDescription->mGameToolsPath.c_str(), menu); +#else + for(std::list::iterator iGame = g_GamesDialog.mGames.begin(); iGame != g_GamesDialog.mGames.end(); ++iGame) + { + filename.clear(); + filename << (*iGame)->mGameToolsPath.c_str() << "game.xlink"; + process_xlink(filename.c_str(), (*iGame)->getRequiredKeyValue("name"), (*iGame)->mGameToolsPath.c_str(), menu); + } +#endif +} + diff --git a/misc/mediasource/netradiant-src/radiant/help.h b/misc/mediasource/netradiant-src/radiant/help.h new file mode 100644 index 00000000..02c6b14c --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/help.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_HELP_H) +#define INCLUDED_HELP_H + +typedef struct _GtkMenu GtkMenu; +void create_game_help_menu(GtkMenu *menu); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/image.cpp b/misc/mediasource/netradiant-src/radiant/image.cpp new file mode 100644 index 00000000..7495db68 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/image.cpp @@ -0,0 +1,70 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "image.h" + +#include "modulesystem.h" +#include "iimage.h" +#include "ifilesystem.h" +#include "iarchive.h" + +#include "generic/reference.h" +#include "os/path.h" +#include "stream/stringstream.h" + + +typedef Modules<_QERPlugImageTable> ImageModules; +ImageModules& Textures_getImageModules(); + +/// \brief Returns a new image for the first file matching \p name in one of the available texture formats, or 0 if no file is found. +Image* QERApp_LoadImage(void* environment, const char* name) +{ + Image* image = 0; + class LoadImageVisitor : public ImageModules::Visitor + { + const char* m_name; + Image*& m_image; + public: + LoadImageVisitor(const char* name, Image*& image) + : m_name(name), m_image(image) + { + } + void visit(const char* name, const _QERPlugImageTable& table) const + { + if(m_image == 0) + { + StringOutputStream fullname(256); + fullname << m_name << '.' << name; + ArchiveFile* file = GlobalFileSystem().openFile(fullname.c_str()); + if(file != 0) + { + m_image = table.loadImage(*file); + file->release(); + } + } + } + }; + + Textures_getImageModules().foreachModule(LoadImageVisitor(name, image)); + + return image; +} + diff --git a/misc/mediasource/netradiant-src/radiant/image.h b/misc/mediasource/netradiant-src/radiant/image.h new file mode 100644 index 00000000..3607c071 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/image.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (INCLUDED_IMAGE_H) +#define INCLUDED_IMAGE_H + +class Image; +Image* QERApp_LoadImage(void* environment, const char* name); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/main.cpp b/misc/mediasource/netradiant-src/radiant/main.cpp new file mode 100644 index 00000000..a7c22426 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/main.cpp @@ -0,0 +1,686 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +/*! \mainpage GtkRadiant Documentation Index + +\section intro_sec Introduction + +This documentation is generated from comments in the source code. + +\section links_sec Useful Links + +\link include/itextstream.h include/itextstream.h \endlink - Global output and error message streams, similar to std::cout and std::cerr. \n + +FileInputStream - similar to std::ifstream (binary mode) \n +FileOutputStream - similar to std::ofstream (binary mode) \n +TextFileInputStream - similar to std::ifstream (text mode) \n +TextFileOutputStream - similar to std::ofstream (text mode) \n +StringOutputStream - similar to std::stringstream \n + +\link string/string.h string/string.h \endlink - C-style string comparison and memory management. \n +\link os/path.h os/path.h \endlink - Path manipulation for radiant's standard path format \n +\link os/file.h os/file.h \endlink - OS file-system access. \n + +::CopiedString - automatic string memory management \n +Array - automatic array memory management \n +HashTable - generic hashtable, similar to std::hash_map \n + +\link math/vector.h math/vector.h \endlink - Vectors \n +\link math/matrix.h math/matrix.h \endlink - Matrices \n +\link math/quaternion.h math/quaternion.h \endlink - Quaternions \n +\link math/plane.h math/plane.h \endlink - Planes \n +\link math/aabb.h math/aabb.h \endlink - AABBs \n + +Callback MemberCaller FunctionCaller - callbacks similar to using boost::function with boost::bind \n +SmartPointer SmartReference - smart-pointer and smart-reference similar to Loki's SmartPtr \n + +\link generic/bitfield.h generic/bitfield.h \endlink - Type-safe bitfield \n +\link generic/enumeration.h generic/enumeration.h \endlink - Type-safe enumeration \n + +DefaultAllocator - Memory allocation using new/delete, compliant with std::allocator interface \n + +\link debugging/debugging.h debugging/debugging.h \endlink - Debugging macros \n + +*/ + +#include "main.h" + +#include "version.h" + +#include "debugging/debugging.h" + +#include "iundo.h" + +#include + +#include "cmdlib.h" +#include "os/file.h" +#include "os/path.h" +#include "stream/stringstream.h" +#include "stream/textfilestream.h" + +#include "gtkutil/messagebox.h" +#include "gtkutil/image.h" +#include "console.h" +#include "texwindow.h" +#include "map.h" +#include "mainframe.h" +#include "commands.h" +#include "preferences.h" +#include "environment.h" +#include "referencecache.h" +#include "stacktrace.h" + +#ifdef WIN32 +#include +#endif + +void show_splash(); +void hide_splash(); + +void error_redirect (const gchar *domain, GLogLevelFlags log_level, const gchar *message, gpointer user_data) +{ + gboolean in_recursion; + gboolean is_fatal; + char buf[256]; + + in_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0; + is_fatal = (log_level & G_LOG_FLAG_FATAL) != 0; + log_level = (GLogLevelFlags) (log_level & G_LOG_LEVEL_MASK); + + if (!message) + message = "(0) message"; + + if (domain) + strcpy (buf, domain); + else + strcpy (buf, "**"); + strcat (buf, "-"); + + switch (log_level) + { + case G_LOG_LEVEL_ERROR: + if (in_recursion) + strcat (buf, "ERROR (recursed) **: "); + else + strcat (buf, "ERROR **: "); + break; + case G_LOG_LEVEL_CRITICAL: + if (in_recursion) + strcat (buf, "CRITICAL (recursed) **: "); + else + strcat (buf, "CRITICAL **: "); + break; + case G_LOG_LEVEL_WARNING: + if (in_recursion) + strcat (buf, "WARNING (recursed) **: "); + else + strcat (buf, "WARNING **: "); + break; + case G_LOG_LEVEL_MESSAGE: + if (in_recursion) + strcat (buf, "Message (recursed): "); + else + strcat (buf, "Message: "); + break; + case G_LOG_LEVEL_INFO: + if (in_recursion) + strcat (buf, "INFO (recursed): "); + else + strcat (buf, "INFO: "); + break; + case G_LOG_LEVEL_DEBUG: + if (in_recursion) + strcat (buf, "DEBUG (recursed): "); + else + strcat (buf, "DEBUG: "); + break; + default: + /* we are used for a log level that is not defined by GLib itself, + * try to make the best out of it. + */ + if (in_recursion) + strcat (buf, "LOG (recursed:"); + else + strcat (buf, "LOG ("); + if (log_level) + { + gchar string[] = "0x00): "; + gchar *p = string + 2; + guint i; + + i = g_bit_nth_msf (log_level, -1); + *p = i >> 4; + p++; + *p = '0' + (i & 0xf); + if (*p > '9') + *p += 'A' - '9' - 1; + + strcat (buf, string); + } else + strcat (buf, "): "); + } + + strcat (buf, message); + if (is_fatal) + strcat (buf, "\naborting...\n"); + else + strcat (buf, "\n"); + + // spam it... + globalErrorStream() << buf << "\n"; + + // FIXME why are warnings is_fatal? +#ifndef _DEBUG + if(is_fatal) +#endif + ERROR_MESSAGE("GTK+ error: " << buf); +} + +#if defined (_DEBUG) && defined (WIN32) && defined (_MSC_VER) +#include "crtdbg.h" +#endif + +void crt_init() +{ +#if defined (_DEBUG) && defined (WIN32) && defined (_MSC_VER) + _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); +#endif +} + +class Lock +{ + bool m_locked; +public: + Lock() : m_locked(false) + { + } + void lock() + { + m_locked = true; + } + void unlock() + { + m_locked = false; + } + bool locked() const + { + return m_locked; + } +}; + +class ScopedLock +{ + Lock& m_lock; +public: + ScopedLock(Lock& lock) : m_lock(lock) + { + m_lock.lock(); + } + ~ScopedLock() + { + m_lock.unlock(); + } +}; + +class LineLimitedTextOutputStream : public TextOutputStream +{ + TextOutputStream& outputStream; + std::size_t count; +public: + LineLimitedTextOutputStream(TextOutputStream& outputStream, std::size_t count) + : outputStream(outputStream), count(count) + { + } + std::size_t write(const char* buffer, std::size_t length) + { + if(count != 0) + { + const char* p = buffer; + const char* end = buffer+length; + for(;;) + { + p = std::find(p, end, '\n'); + if(p == end) + { + break; + } + ++p; + if(--count == 0) + { + length = p - buffer; + break; + } + } + outputStream.write(buffer, length); + } + return length; + } +}; + +class PopupDebugMessageHandler : public DebugMessageHandler +{ + StringOutputStream m_buffer; + Lock m_lock; +public: + TextOutputStream& getOutputStream() + { + if(!m_lock.locked()) + { + return m_buffer; + } + return globalErrorStream(); + } + bool handleMessage() + { + getOutputStream() << "----------------\n"; + LineLimitedTextOutputStream outputStream(getOutputStream(), 24); + write_stack_trace(outputStream); + getOutputStream() << "----------------\n"; + globalErrorStream() << m_buffer.c_str(); + if(!m_lock.locked()) + { + ScopedLock lock(m_lock); +#if defined _DEBUG + m_buffer << "Break into the debugger?\n"; + bool handled = gtk_MessageBox(0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_YESNO, eMB_ICONERROR) == eIDNO; + m_buffer.clear(); + return handled; +#else + m_buffer << "Please report this error to the developers\n"; + gtk_MessageBox(0, m_buffer.c_str(), "Radiant - Runtime Error", eMB_OK, eMB_ICONERROR); + m_buffer.clear(); +#endif + } + return true; + } +}; + +typedef Static GlobalPopupDebugMessageHandler; + +void streams_init() +{ + GlobalErrorStream::instance().setOutputStream(getSysPrintErrorStream()); + GlobalOutputStream::instance().setOutputStream(getSysPrintOutputStream()); +} + +void paths_init() +{ + const char* home = environment_get_home_path(); + Q_mkdir(home); + + { + StringOutputStream path(256); + path << home << "1." << RADIANT_MAJOR_VERSION "." << RADIANT_MINOR_VERSION << '/'; + g_strSettingsPath = path.c_str(); + } + + Q_mkdir(g_strSettingsPath.c_str()); + + g_strAppPath = environment_get_app_path(); + + // radiant is installed in the parent dir of "tools/" + // NOTE: this is not very easy for debugging + // maybe add options to lookup in several places? + // (for now I had to create symlinks) + { + StringOutputStream path(256); + path << g_strAppPath.c_str() << "bitmaps/"; + BitmapsPath_set(path.c_str()); + } + + // we will set this right after the game selection is done + g_strGameToolsPath = g_strAppPath; +} + +bool check_version_file(const char* filename, const char* version) +{ + TextFileInputStream file(filename); + if(!file.failed()) + { + char buf[10]; + buf[file.read(buf, 9)] = '\0'; + + // chomp it (the hard way) + int chomp = 0; + while(buf[chomp] >= '0' && buf[chomp] <= '9') + chomp++; + buf[chomp] = '\0'; + + return string_equal(buf, version); + } + return false; +} + +bool check_version() +{ + // a safe check to avoid people running broken installations + // (otherwise, they run it, crash it, and blame us for not forcing them hard enough to pay attention while installing) + // make something idiot proof and someone will make better idiots, this may be overkill + // let's leave it disabled in debug mode in any case + // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=431 +#ifndef _DEBUG +#define CHECK_VERSION +#endif +#ifdef CHECK_VERSION + // locate and open RADIANT_MAJOR and RADIANT_MINOR + bool bVerIsGood = true; + { + StringOutputStream ver_file_name(256); + ver_file_name << AppPath_get() << "RADIANT_MAJOR"; + bVerIsGood = check_version_file(ver_file_name.c_str(), RADIANT_MAJOR_VERSION); + } + { + StringOutputStream ver_file_name(256); + ver_file_name << AppPath_get() << "RADIANT_MINOR"; + bVerIsGood = check_version_file(ver_file_name.c_str(), RADIANT_MINOR_VERSION); + } + + if (!bVerIsGood) + { + StringOutputStream msg(256); + msg << "This editor binary (" RADIANT_VERSION ") doesn't match what the latest setup has configured in this directory\n" + "Make sure you run the right/latest editor binary you installed\n" + << AppPath_get(); + gtk_MessageBox(0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONDEFAULT); + } + return bVerIsGood; +#else + return true; +#endif +} + +void create_global_pid() +{ + /*! + the global prefs loading / game selection dialog might fail for any reason we don't know about + we need to catch when it happens, to cleanup the stateful prefs which might be killing it + and to turn on console logging for lookup of the problem + this is the first part of the two step .pid system + http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297 + */ + StringOutputStream g_pidFile(256); ///< the global .pid file (only for global part of the startup) + + g_pidFile << SettingsPath_get() << "radiant.pid"; + + FILE *pid; + pid = fopen (g_pidFile.c_str(), "r"); + if (pid != 0) + { + fclose (pid); + + if (remove (g_pidFile.c_str()) == -1) + { + StringOutputStream msg(256); + msg << "WARNING: Could not delete " << g_pidFile.c_str(); + gtk_MessageBox (0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR ); + } + + // in debug, never prompt to clean registry, turn console logging auto after a failed start +#if !defined(_DEBUG) + StringOutputStream msg(256); + msg << "Radiant failed to start properly the last time it was run.\n" + "The failure may be related to current global preferences.\n" + "Do you want to reset global preferences to defaults?"; + + if (gtk_MessageBox (0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION) == eIDYES) + { + g_GamesDialog.Reset(); + } + + msg.clear(); + msg << "Logging console output to " << SettingsPath_get() << "radiant.log\nRefer to the log if Radiant fails to start again."; + + gtk_MessageBox (0, msg.c_str(), "Radiant - Console Log", eMB_OK); +#endif + + // set without saving, the class is not in a coherent state yet + // just do the value change and call to start logging, CGamesDialog will pickup when relevant + g_GamesDialog.m_bForceLogConsole = true; + Sys_LogFile(true); + } + + // create a primary .pid for global init run + pid = fopen (g_pidFile.c_str(), "w"); + if (pid) + fclose (pid); +} + +void remove_global_pid() +{ + StringOutputStream g_pidFile(256); + g_pidFile << SettingsPath_get() << "radiant.pid"; + + // close the primary + if (remove (g_pidFile.c_str()) == -1) + { + StringOutputStream msg(256); + msg << "WARNING: Could not delete " << g_pidFile.c_str(); + gtk_MessageBox (0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR ); + } +} + +/*! +now the secondary game dependant .pid file +http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297 +*/ +void create_local_pid() +{ + StringOutputStream g_pidGameFile(256); ///< the game-specific .pid file + g_pidGameFile << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/radiant-game.pid"; + + FILE *pid = fopen (g_pidGameFile.c_str(), "r"); + if (pid != 0) + { + fclose (pid); + if (remove (g_pidGameFile.c_str()) == -1) + { + StringOutputStream msg; + msg << "WARNING: Could not delete " << g_pidGameFile.c_str(); + gtk_MessageBox (0, msg.c_str(), "Radiant", eMB_OK, eMB_ICONERROR ); + } + + // in debug, never prompt to clean registry, turn console logging auto after a failed start +#if !defined(_DEBUG) + StringOutputStream msg; + msg << "Radiant failed to start properly the last time it was run.\n" + "The failure may be caused by current preferences.\n" + "Do you want to reset all preferences to defaults?"; + + if (gtk_MessageBox (0, msg.c_str(), "Radiant - Startup Failure", eMB_YESNO, eMB_ICONQUESTION) == eIDYES) + { + Preferences_Reset(); + } + + msg.clear(); + msg << "Logging console output to " << SettingsPath_get() << "radiant.log\nRefer to the log if Radiant fails to start again."; + + gtk_MessageBox (0, msg.c_str(), "Radiant - Console Log", eMB_OK); +#endif + + // force console logging on! (will go in prefs too) + g_GamesDialog.m_bForceLogConsole = true; + Sys_LogFile(true); + } + else + { + // create one, will remove right after entering message loop + pid = fopen (g_pidGameFile.c_str(), "w"); + if (pid) + fclose (pid); + } +} + + +/*! +now the secondary game dependant .pid file +http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=297 +*/ +void remove_local_pid() +{ + StringOutputStream g_pidGameFile(256); + g_pidGameFile << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << "/radiant-game.pid"; + remove(g_pidGameFile.c_str()); +} + +void user_shortcuts_init() +{ + StringOutputStream path(256); + path << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << '/'; + LoadCommandMap(path.c_str()); + SaveCommandMap(path.c_str()); +} + +void user_shortcuts_save() +{ + StringOutputStream path(256); + path << SettingsPath_get() << g_pGameDescription->mGameFile.c_str() << '/'; + SaveCommandMap(path.c_str()); +} + +int main (int argc, char* argv[]) +{ + crt_init(); + + streams_init(); + +#ifdef WIN32 + HMODULE lib; + lib = LoadLibrary("dwmapi.dll"); + if(lib != 0) + { + void (WINAPI *qDwmEnableComposition) (bool bEnable) = (void (WINAPI *) (bool bEnable)) GetProcAddress(lib, "DwmEnableComposition"); + if(qDwmEnableComposition) + qDwmEnableComposition(FALSE); + FreeLibrary(lib); + } +#endif + + gtk_disable_setlocale(); + gtk_init(&argc, &argv); + + // redirect Gtk warnings to the console + g_log_set_handler ("Gdk", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| + G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); + g_log_set_handler ("Gtk", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| + G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); + g_log_set_handler ("GtkGLExt", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| + G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); + g_log_set_handler ("GLib", (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| + G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); + g_log_set_handler (0, (GLogLevelFlags)(G_LOG_LEVEL_ERROR|G_LOG_LEVEL_CRITICAL|G_LOG_LEVEL_WARNING| + G_LOG_LEVEL_MESSAGE|G_LOG_LEVEL_INFO|G_LOG_LEVEL_DEBUG|G_LOG_FLAG_FATAL|G_LOG_FLAG_RECURSION), error_redirect, 0); + + GlobalDebugMessageHandler::instance().setHandler(GlobalPopupDebugMessageHandler::instance()); + + environment_init(argc, argv); + + paths_init(); + + if(!check_version()) + { + return EXIT_FAILURE; + } + + show_splash(); + + create_global_pid(); + + GlobalPreferences_Init(); + + g_GamesDialog.Init(); + + g_strGameToolsPath = g_pGameDescription->mGameToolsPath; + + remove_global_pid(); + + g_Preferences.Init(); // must occur before create_local_pid() to allow preferences to be reset + + create_local_pid(); + + // in a very particular post-.pid startup + // we may have the console turned on and want to keep it that way + // so we use a latching system + if (g_GamesDialog.m_bForceLogConsole) + { + Sys_LogFile(true); + g_Console_enableLogging = true; + g_GamesDialog.m_bForceLogConsole = false; + } + + + Radiant_Initialise(); + + global_accel_init(); + + user_shortcuts_init(); + + g_pParentWnd = 0; + g_pParentWnd = new MainFrame(); + + hide_splash(); + + if (g_bLoadLastMap && !g_strLastMap.empty()) + { + Map_LoadFile(g_strLastMap.c_str()); + } + else + { + Map_New(); + } + + // load up shaders now that we have the map loaded + // eviltypeguy + TextureBrowser_ShowStartupShaders(GlobalTextureBrowser()); + + + remove_local_pid(); + + gtk_main(); + + // avoid saving prefs when the app is minimized + if (g_pParentWnd->IsSleeping()) + { + globalOutputStream() << "Shutdown while sleeping, not saving prefs\n"; + g_preferences_globals.disable_ini = true; + } + + Map_Free(); + + if (!Map_Unnamed(g_map)) + { + g_strLastMap = Map_Name(g_map); + } + + delete g_pParentWnd; + + user_shortcuts_save(); + + global_accel_destroy(); + + Radiant_Shutdown(); + + // close the log file if any + Sys_LogFile(false); + + return EXIT_SUCCESS; +} + diff --git a/misc/mediasource/netradiant-src/radiant/main.h b/misc/mediasource/netradiant-src/radiant/main.h new file mode 100644 index 00000000..bda8f3da --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/main.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_MAIN_H) +#define INCLUDED_MAIN_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/mainframe.cpp b/misc/mediasource/netradiant-src/radiant/mainframe.cpp new file mode 100644 index 00000000..c8a739b6 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/mainframe.cpp @@ -0,0 +1,3601 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Main Window for Q3Radiant +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "mainframe.h" + +#include "debugging/debugging.h" +#include "version.h" + +#include "ifilesystem.h" +#include "iundo.h" +#include "ifilter.h" +#include "itoolbar.h" +#include "editable.h" +#include "ientity.h" +#include "ishaders.h" +#include "igl.h" +#include "moduleobserver.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "cmdlib.h" +#include "scenelib.h" +#include "stream/stringstream.h" +#include "signal/isignal.h" +#include "os/path.h" +#include "os/file.h" +#include "eclasslib.h" +#include "moduleobservers.h" + +#include "gtkutil/clipboard.h" +#include "gtkutil/container.h" +#include "gtkutil/frame.h" +#include "gtkutil/glfont.h" +#include "gtkutil/glwidget.h" +#include "gtkutil/image.h" +#include "gtkutil/menu.h" +#include "gtkutil/paned.h" +#include "gtkutil/widget.h" + +#include "autosave.h" +#include "build.h" +#include "brushmanip.h" +#include "brushmodule.h" +#include "camwindow.h" +#include "csg.h" +#include "commands.h" +#include "console.h" +#include "entity.h" +#include "entityinspector.h" +#include "entitylist.h" +#include "filters.h" +#include "findtexturedialog.h" +#include "grid.h" +#include "groupdialog.h" +#include "gtkdlgs.h" +#include "gtkmisc.h" +#include "help.h" +#include "map.h" +#include "mru.h" +#include "multimon.h" +#include "patchdialog.h" +#include "patchmanip.h" +#include "plugin.h" +#include "pluginmanager.h" +#include "pluginmenu.h" +#include "plugintoolbar.h" +#include "points.h" +#include "preferences.h" +#include "qe3.h" +#include "qgl.h" +#include "select.h" +#include "server.h" +#include "surfacedialog.h" +#include "textures.h" +#include "texwindow.h" +#include "url.h" +#include "xywindow.h" +#include "windowobservers.h" +#include "renderstate.h" +#include "feedback.h" +#include "referencecache.h" + + + +struct layout_globals_t +{ + WindowPosition m_position; + + + int nXYHeight; + int nXYWidth; + int nCamWidth; + int nCamHeight; + int nState; + + layout_globals_t() : + m_position(-1, -1, 640, 480), + + nXYHeight(300), + nXYWidth(300), + nCamWidth(200), + nCamHeight(200), + nState(GDK_WINDOW_STATE_MAXIMIZED) + { + } +}; + +layout_globals_t g_layout_globals; +glwindow_globals_t g_glwindow_globals; + + +// VFS +class VFSModuleObserver : public ModuleObserver +{ + std::size_t m_unrealised; +public: + VFSModuleObserver() : m_unrealised(1) + { + } + void realise() + { + if(--m_unrealised == 0) + { + QE_InitVFS(); + GlobalFileSystem().initialise(); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + GlobalFileSystem().shutdown(); + } + } +}; + +VFSModuleObserver g_VFSModuleObserver; + +void VFS_Construct() +{ + Radiant_attachHomePathsObserver(g_VFSModuleObserver); +} +void VFS_Destroy() +{ + Radiant_detachHomePathsObserver(g_VFSModuleObserver); +} + +// Home Paths + +void HomePaths_Realise() +{ +#if defined(POSIX) + const char* prefix = g_pGameDescription->getKeyValue("prefix"); + if(!string_empty(prefix)) + { + StringOutputStream path(256); + path << DirectoryCleaned(g_get_home_dir()) << prefix << "/"; + g_qeglobals.m_userEnginePath = path.c_str(); + Q_mkdir(g_qeglobals.m_userEnginePath.c_str()); + } + else +#endif + { + g_qeglobals.m_userEnginePath = EnginePath_get(); + } + + { + StringOutputStream path(256); + path << g_qeglobals.m_userEnginePath.c_str() << gamename_get() << '/'; + g_qeglobals.m_userGamePath = path.c_str(); + } + ASSERT_MESSAGE(!string_empty(g_qeglobals.m_userGamePath.c_str()), "HomePaths_Realise: user-game-path is empty"); + Q_mkdir(g_qeglobals.m_userGamePath.c_str()); +} + +ModuleObservers g_homePathObservers; + +void Radiant_attachHomePathsObserver(ModuleObserver& observer) +{ + g_homePathObservers.attach(observer); +} + +void Radiant_detachHomePathsObserver(ModuleObserver& observer) +{ + g_homePathObservers.detach(observer); +} + +class HomePathsModuleObserver : public ModuleObserver +{ + std::size_t m_unrealised; +public: + HomePathsModuleObserver() : m_unrealised(1) + { + } + void realise() + { + if(--m_unrealised == 0) + { + HomePaths_Realise(); + g_homePathObservers.realise(); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + g_homePathObservers.unrealise(); + } + } +}; + +HomePathsModuleObserver g_HomePathsModuleObserver; + +void HomePaths_Construct() +{ + Radiant_attachEnginePathObserver(g_HomePathsModuleObserver); +} +void HomePaths_Destroy() +{ + Radiant_detachEnginePathObserver(g_HomePathsModuleObserver); +} + + +// Engine Path + +CopiedString g_strEnginePath; +ModuleObservers g_enginePathObservers; +std::size_t g_enginepath_unrealised = 1; + +void Radiant_attachEnginePathObserver(ModuleObserver& observer) +{ + g_enginePathObservers.attach(observer); +} + +void Radiant_detachEnginePathObserver(ModuleObserver& observer) +{ + g_enginePathObservers.detach(observer); +} + + +void EnginePath_Realise() +{ + if(--g_enginepath_unrealised == 0) + { + g_enginePathObservers.realise(); + } +} + + +const char* EnginePath_get() +{ + ASSERT_MESSAGE(g_enginepath_unrealised == 0, "EnginePath_get: engine path not realised"); + return g_strEnginePath.c_str(); +} + +void EnginePath_Unrealise() +{ + if(++g_enginepath_unrealised == 1) + { + g_enginePathObservers.unrealise(); + } +} + +void setEnginePath(const char* path) +{ + StringOutputStream buffer(256); + buffer << DirectoryCleaned(path); + if(!path_equal(buffer.c_str(), g_strEnginePath.c_str())) + { +#if 0 + while(!ConfirmModified("Paths Changed")) + { + if(Map_Unnamed(g_map)) + { + Map_SaveAs(); + } + else + { + Map_Save(); + } + } + Map_RegionOff(); +#endif + + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Changing Engine Path"); + + EnginePath_Unrealise(); + + g_strEnginePath = buffer.c_str(); + + EnginePath_Realise(); + } +} + + +// App Path + +CopiedString g_strAppPath; ///< holds the full path of the executable + +const char* AppPath_get() +{ + return g_strAppPath.c_str(); +} + +/// the path to the local rc-dir +const char* LocalRcPath_get(void) +{ + static CopiedString rc_path; + if(rc_path.empty()) + { + StringOutputStream stream(256); + stream << GlobalRadiant().getSettingsPath() << g_pGameDescription->mGameFile.c_str() << "/"; + rc_path = stream.c_str(); + } + return rc_path.c_str(); +} + +/// directory for temp files +/// NOTE: on *nix this is were we check for .pid +CopiedString g_strSettingsPath; +const char* SettingsPath_get() +{ + return g_strSettingsPath.c_str(); +} + + +/*! +points to the game tools directory, for instance +C:/Program Files/Quake III Arena/GtkRadiant +(or other games) +this is one of the main variables that are configured by the game selection on startup +[GameToolsPath]/plugins +[GameToolsPath]/modules +and also q3map, bspc +*/ +CopiedString g_strGameToolsPath; ///< this is set by g_GamesDialog + +const char* GameToolsPath_get() +{ + return g_strGameToolsPath.c_str(); +} + +void EnginePathImport(CopiedString& self, const char* value) +{ + setEnginePath(value); +} +typedef ReferenceCaller1 EnginePathImportCaller; + +void Paths_constructPreferences(PreferencesPage& page) +{ + page.appendPathEntry("Engine Path", true, + StringImportCallback(EnginePathImportCaller(g_strEnginePath)), + StringExportCallback(StringExportCaller(g_strEnginePath)) + ); +} +void Paths_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Paths", "Path Settings")); + Paths_constructPreferences(page); +} +void Paths_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + + +class PathsDialog : public Dialog +{ +public: + GtkWindow* BuildDialog() + { + GtkFrame* frame = create_dialog_frame("Path settings", GTK_SHADOW_ETCHED_IN); + + GtkVBox* vbox2 = create_dialog_vbox(0, 4); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox2)); + + { + PreferencesPage preferencesPage(*this, GTK_WIDGET(vbox2)); + Paths_constructPreferences(preferencesPage); + } + + return create_simple_modal_dialog_window("Engine Path Not Found", m_modal, GTK_WIDGET(frame)); + } +}; + +PathsDialog g_PathsDialog; + +void EnginePath_verify() +{ + if(!file_exists(g_strEnginePath.c_str())) + { + g_PathsDialog.Create(); + g_PathsDialog.DoModal(); + g_PathsDialog.Destroy(); + } +} + +namespace +{ + CopiedString g_gamename; + CopiedString g_gamemode; + ModuleObservers g_gameNameObservers; + ModuleObservers g_gameModeObservers; +} + +void Radiant_attachGameNameObserver(ModuleObserver& observer) +{ + g_gameNameObservers.attach(observer); +} + +void Radiant_detachGameNameObserver(ModuleObserver& observer) +{ + g_gameNameObservers.detach(observer); +} + +const char* basegame_get() +{ + return g_pGameDescription->getRequiredKeyValue("basegame"); +} + +const char* gamename_get() +{ + const char* gamename = g_gamename.c_str(); + if(string_empty(gamename)) + { + return basegame_get(); + } + return gamename; +} + +void gamename_set(const char* gamename) +{ + if(!string_equal(gamename, g_gamename.c_str())) + { + g_gameNameObservers.unrealise(); + g_gamename = gamename; + g_gameNameObservers.realise(); + } +} + +void Radiant_attachGameModeObserver(ModuleObserver& observer) +{ + g_gameModeObservers.attach(observer); +} + +void Radiant_detachGameModeObserver(ModuleObserver& observer) +{ + g_gameModeObservers.detach(observer); +} + +const char* gamemode_get() +{ + return g_gamemode.c_str(); +} + +void gamemode_set(const char* gamemode) +{ + if(!string_equal(gamemode, g_gamemode.c_str())) + { + g_gameModeObservers.unrealise(); + g_gamemode = gamemode; + g_gameModeObservers.realise(); + } +} + +#include "os/dir.h" + +class CLoadModule +{ + const char* m_path; +public: + CLoadModule(const char* path) : m_path(path) + { + } + void operator()(const char* name) const + { + char fullname[1024]; + ASSERT_MESSAGE(strlen(m_path) + strlen(name) < 1024, ""); + strcpy(fullname, m_path); + strcat(fullname, name); + globalOutputStream() << "Found '" << fullname << "'\n"; + GlobalModuleServer_loadModule(fullname); + } +}; + +const char* const c_library_extension = +#if defined(WIN32) +"dll" +#elif defined (__APPLE__) +"dylib" +#elif defined(__linux__) || defined (__FreeBSD__) +"so" +#endif +; + +void Radiant_loadModules(const char* path) +{ + Directory_forEach(path, MatchFileExtension(c_library_extension, CLoadModule(path))); +} + +void Radiant_loadModulesFromRoot(const char* directory) +{ + { + StringOutputStream path(256); + path << directory << g_pluginsDir; + Radiant_loadModules(path.c_str()); + } + + if(!string_equal(g_pluginsDir, g_modulesDir)) + { + StringOutputStream path(256); + path << directory << g_modulesDir; + Radiant_loadModules(path.c_str()); + } +} + +//! Make COLOR_BRUSHES override worldspawn eclass colour. +void SetWorldspawnColour(const Vector3& colour) +{ + EntityClass* worldspawn = GlobalEntityClassManager().findOrInsert("worldspawn", true); + eclass_release_state(worldspawn); + worldspawn->color = colour; + eclass_capture_state(worldspawn); +} + + +class WorldspawnColourEntityClassObserver : public ModuleObserver +{ + std::size_t m_unrealised; +public: + WorldspawnColourEntityClassObserver() : m_unrealised(1) + { + } + void realise() + { + if(--m_unrealised == 0) + { + SetWorldspawnColour(g_xywindow_globals.color_brushes); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + } + } +}; + +WorldspawnColourEntityClassObserver g_WorldspawnColourEntityClassObserver; + + +ModuleObservers g_gameToolsPathObservers; + +void Radiant_attachGameToolsPathObserver(ModuleObserver& observer) +{ + g_gameToolsPathObservers.attach(observer); +} + +void Radiant_detachGameToolsPathObserver(ModuleObserver& observer) +{ + g_gameToolsPathObservers.detach(observer); +} + +void Radiant_Initialise() +{ + GlobalModuleServer_Initialise(); + + Radiant_loadModulesFromRoot(AppPath_get()); + + Preferences_Load(); + + bool success = Radiant_Construct(GlobalModuleServer_get()); + ASSERT_MESSAGE(success, "module system failed to initialise - see radiant.log for error messages"); + + g_gameToolsPathObservers.realise(); + g_gameModeObservers.realise(); + g_gameNameObservers.realise(); +} + +void Radiant_Shutdown() +{ + g_gameNameObservers.unrealise(); + g_gameModeObservers.unrealise(); + g_gameToolsPathObservers.unrealise(); + + if (!g_preferences_globals.disable_ini) + { + globalOutputStream() << "Start writing prefs\n"; + Preferences_Save(); + globalOutputStream() << "Done prefs\n"; + } + + Radiant_Destroy(); + + GlobalModuleServer_Shutdown(); +} + +void Exit() +{ + if(ConfirmModified("Exit Radiant")) + { + gtk_main_quit(); + } +} + + +void Undo() +{ + GlobalUndoSystem().undo(); + SceneChangeNotify(); +} + +void Redo() +{ + GlobalUndoSystem().redo(); + SceneChangeNotify(); +} + +void deleteSelection() +{ + UndoableCommand undo("deleteSelected"); + Select_Delete(); +} + +void Map_ExportSelected(TextOutputStream& ostream) +{ + Map_ExportSelected(ostream, Map_getFormat(g_map)); +} + +void Map_ImportSelected(TextInputStream& istream) +{ + Map_ImportSelected(istream, Map_getFormat(g_map)); +} + +void Selection_Copy() +{ + clipboard_copy(Map_ExportSelected); +} + +void Selection_Paste() +{ + clipboard_paste(Map_ImportSelected); +} + +void Copy() +{ + if(SelectedFaces_empty()) + { + Selection_Copy(); + } + else + { + SelectedFaces_copyTexture(); + } +} + +void Paste() +{ + if(SelectedFaces_empty()) + { + UndoableCommand undo("paste"); + + GlobalSelectionSystem().setSelectedAll(false); + Selection_Paste(); + } + else + { + SelectedFaces_pasteTexture(); + } +} + +void PasteToCamera() +{ + CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); + GlobalSelectionSystem().setSelectedAll(false); + + UndoableCommand undo("pasteToCamera"); + + Selection_Paste(); + + // Work out the delta + Vector3 mid; + Select_GetMid(mid); + Vector3 delta = vector3_subtracted(vector3_snapped(Camera_getOrigin(camwnd), GetSnapGridSize()), mid); + + // Move to camera + GlobalSelectionSystem().translateSelected(delta); +} + + +void ColorScheme_Original() +{ + TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); + + g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); + g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); + CamWnd_Update(*g_pParentWnd->GetCamWnd()); + + g_xywindow_globals.color_gridback = Vector3(1.0f, 1.0f, 1.0f); + g_xywindow_globals.color_gridminor = Vector3(0.75f, 0.75f, 0.75f); + g_xywindow_globals.color_gridmajor = Vector3(0.5f, 0.5f, 0.5f); + g_xywindow_globals.color_gridminor_alt = Vector3(0.5f, 0.0f, 0.0f); + g_xywindow_globals.color_gridmajor_alt = Vector3(1.0f, 0.0f, 0.0f); + g_xywindow_globals.color_gridblock = Vector3(0.0f, 0.0f, 1.0f); + g_xywindow_globals.color_gridtext = Vector3(0.0f, 0.0f, 0.0f); + g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); + g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); + g_xywindow_globals.color_brushes = Vector3(0.0f, 0.0f, 0.0f); + SetWorldspawnColour(g_xywindow_globals.color_brushes); + g_xywindow_globals.color_viewname = Vector3(0.5f, 0.0f, 0.75f); + XY_UpdateAllWindows(); +} + +void ColorScheme_QER() +{ + TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); + + g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); + g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); + CamWnd_Update(*g_pParentWnd->GetCamWnd()); + + g_xywindow_globals.color_gridback = Vector3(1.0f, 1.0f, 1.0f); + g_xywindow_globals.color_gridminor = Vector3(1.0f, 1.0f, 1.0f); + g_xywindow_globals.color_gridmajor = Vector3(0.5f, 0.5f, 0.5f); + g_xywindow_globals.color_gridblock = Vector3(0.0f, 0.0f, 1.0f); + g_xywindow_globals.color_gridtext = Vector3(0.0f, 0.0f, 0.0f); + g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); + g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); + g_xywindow_globals.color_brushes = Vector3(0.0f, 0.0f, 0.0f); + SetWorldspawnColour(g_xywindow_globals.color_brushes); + g_xywindow_globals.color_viewname = Vector3(0.5f, 0.0f, 0.75f); + XY_UpdateAllWindows(); +} + +void ColorScheme_Black() +{ + TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); + + g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); + g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); + CamWnd_Update(*g_pParentWnd->GetCamWnd()); + + g_xywindow_globals.color_gridback = Vector3(0.0f, 0.0f, 0.0f); + g_xywindow_globals.color_gridminor = Vector3(0.2f, 0.2f, 0.2f); + g_xywindow_globals.color_gridmajor = Vector3(0.3f, 0.5f, 0.5f); + g_xywindow_globals.color_gridblock = Vector3(0.0f, 0.0f, 1.0f); + g_xywindow_globals.color_gridtext = Vector3(1.0f, 1.0f, 1.0f); + g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); + g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); + g_xywindow_globals.color_brushes = Vector3(1.0f, 1.0f, 1.0f); + SetWorldspawnColour(g_xywindow_globals.color_brushes); + g_xywindow_globals.color_viewname = Vector3(0.7f, 0.7f, 0.0f); + XY_UpdateAllWindows(); +} + +/* ydnar: to emulate maya/max/lightwave color schemes */ +void ColorScheme_Ydnar() +{ + TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), Vector3(0.25f, 0.25f, 0.25f)); + + g_camwindow_globals.color_cameraback = Vector3(0.25f, 0.25f, 0.25f); + g_camwindow_globals.color_selbrushes3d = Vector3(1.0f, 0.0f, 0.0f); + CamWnd_Update(*g_pParentWnd->GetCamWnd()); + + g_xywindow_globals.color_gridback = Vector3(0.77f, 0.77f, 0.77f); + g_xywindow_globals.color_gridminor = Vector3(0.83f, 0.83f, 0.83f); + g_xywindow_globals.color_gridmajor = Vector3(0.89f, 0.89f, 0.89f); + g_xywindow_globals.color_gridblock = Vector3(1.0f, 1.0f, 1.0f); + g_xywindow_globals.color_gridtext = Vector3(0.0f, 0.0f, 0.0f); + g_xywindow_globals.color_selbrushes = Vector3(1.0f, 0.0f, 0.0f); + g_xywindow_globals.color_clipper = Vector3(0.0f, 0.0f, 1.0f); + g_xywindow_globals.color_brushes = Vector3(0.0f, 0.0f, 0.0f); + SetWorldspawnColour(g_xywindow_globals.color_brushes); + g_xywindow_globals.color_viewname = Vector3(0.5f, 0.0f, 0.75f); + XY_UpdateAllWindows(); +} + +typedef Callback1 GetColourCallback; +typedef Callback1 SetColourCallback; + +class ChooseColour +{ + GetColourCallback m_get; + SetColourCallback m_set; +public: + ChooseColour(const GetColourCallback& get, const SetColourCallback& set) + : m_get(get), m_set(set) + { + } + void operator()() + { + Vector3 colour; + m_get(colour); + color_dialog(GTK_WIDGET(MainFrame_getWindow()), colour); + m_set(colour); + } +}; + + + +void Colour_get(const Vector3& colour, Vector3& other) +{ + other = colour; +} +typedef ConstReferenceCaller1 ColourGetCaller; + +void Colour_set(Vector3& colour, const Vector3& other) +{ + colour = other; + SceneChangeNotify(); +} +typedef ReferenceCaller1 ColourSetCaller; + +void BrushColour_set(const Vector3& other) +{ + g_xywindow_globals.color_brushes = other; + SetWorldspawnColour(g_xywindow_globals.color_brushes); + SceneChangeNotify(); +} +typedef FreeCaller1 BrushColourSetCaller; + +void ClipperColour_set(const Vector3& other) +{ + g_xywindow_globals.color_clipper = other; + Brush_clipperColourChanged(); + SceneChangeNotify(); +} +typedef FreeCaller1 ClipperColourSetCaller; + +void TextureBrowserColour_get(Vector3& other) +{ + other = TextureBrowser_getBackgroundColour(GlobalTextureBrowser()); +} +typedef FreeCaller1 TextureBrowserColourGetCaller; + +void TextureBrowserColour_set(const Vector3& other) +{ + TextureBrowser_setBackgroundColour(GlobalTextureBrowser(), other); +} +typedef FreeCaller1 TextureBrowserColourSetCaller; + + +class ColoursMenu +{ +public: + ChooseColour m_textureback; + ChooseColour m_xyback; + ChooseColour m_gridmajor; + ChooseColour m_gridminor; + ChooseColour m_gridmajor_alt; + ChooseColour m_gridminor_alt; + ChooseColour m_gridtext; + ChooseColour m_gridblock; + ChooseColour m_cameraback; + ChooseColour m_brush; + ChooseColour m_selectedbrush; + ChooseColour m_selectedbrush3d; + ChooseColour m_clipper; + ChooseColour m_viewname; + + ColoursMenu() : + m_textureback(TextureBrowserColourGetCaller(), TextureBrowserColourSetCaller()), + m_xyback(ColourGetCaller(g_xywindow_globals.color_gridback), ColourSetCaller(g_xywindow_globals.color_gridback)), + m_gridmajor(ColourGetCaller(g_xywindow_globals.color_gridmajor), ColourSetCaller(g_xywindow_globals.color_gridmajor)), + m_gridminor(ColourGetCaller(g_xywindow_globals.color_gridminor), ColourSetCaller(g_xywindow_globals.color_gridminor)), + m_gridmajor_alt(ColourGetCaller(g_xywindow_globals.color_gridmajor_alt), ColourSetCaller(g_xywindow_globals.color_gridmajor_alt)), + m_gridminor_alt(ColourGetCaller(g_xywindow_globals.color_gridminor_alt), ColourSetCaller(g_xywindow_globals.color_gridminor_alt)), + m_gridtext(ColourGetCaller(g_xywindow_globals.color_gridtext), ColourSetCaller(g_xywindow_globals.color_gridtext)), + m_gridblock(ColourGetCaller(g_xywindow_globals.color_gridblock), ColourSetCaller(g_xywindow_globals.color_gridblock)), + m_cameraback(ColourGetCaller(g_camwindow_globals.color_cameraback), ColourSetCaller(g_camwindow_globals.color_cameraback)), + m_brush(ColourGetCaller(g_xywindow_globals.color_brushes), BrushColourSetCaller()), + m_selectedbrush(ColourGetCaller(g_xywindow_globals.color_selbrushes), ColourSetCaller(g_xywindow_globals.color_selbrushes)), + m_selectedbrush3d(ColourGetCaller(g_camwindow_globals.color_selbrushes3d), ColourSetCaller(g_camwindow_globals.color_selbrushes3d)), + m_clipper(ColourGetCaller(g_xywindow_globals.color_clipper), ClipperColourSetCaller()), + m_viewname(ColourGetCaller(g_xywindow_globals.color_viewname), ColourSetCaller(g_xywindow_globals.color_viewname)) + { + } +}; + +ColoursMenu g_ColoursMenu; + +GtkMenuItem* create_colours_menu() +{ + GtkMenuItem* colours_menu_item = new_sub_menu_item_with_mnemonic("Colors"); + GtkMenu* menu_in_menu = GTK_MENU(gtk_menu_item_get_submenu(colours_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + + GtkMenu* menu_3 = create_sub_menu_with_mnemonic(menu_in_menu, "Themes"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_3); + + create_menu_item_with_mnemonic(menu_3, "QE4 Original", "ColorSchemeOriginal"); + create_menu_item_with_mnemonic(menu_3, "Q3Radiant Original", "ColorSchemeQER"); + create_menu_item_with_mnemonic(menu_3, "Black and Green", "ColorSchemeBlackAndGreen"); + create_menu_item_with_mnemonic(menu_3, "Maya/Max/Lightwave Emulation", "ColorSchemeYdnar"); + + menu_separator(menu_in_menu); + + create_menu_item_with_mnemonic(menu_in_menu, "_Texture Background...", "ChooseTextureBackgroundColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Grid Background...", "ChooseGridBackgroundColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Grid Major...", "ChooseGridMajorColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Grid Minor...", "ChooseGridMinorColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Grid Major Small...", "ChooseSmallGridMajorColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Grid Minor Small...", "ChooseSmallGridMinorColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Grid Text...", "ChooseGridTextColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Grid Block...", "ChooseGridBlockColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Default Brush...", "ChooseBrushColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Camera Background...", "ChooseCameraBackgroundColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Selected Brush...", "ChooseSelectedBrushColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Selected Brush (Camera)...", "ChooseCameraSelectedBrushColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Clipper...", "ChooseClipperColor"); + create_menu_item_with_mnemonic(menu_in_menu, "Active View name...", "ChooseOrthoViewNameColor"); + + return colours_menu_item; +} + + +void Restart() +{ + PluginsMenu_clear(); + PluginToolbar_clear(); + + Radiant_Shutdown(); + Radiant_Initialise(); + + PluginsMenu_populate(); + + PluginToolbar_populate(); +} + + +void thunk_OnSleep() +{ + g_pParentWnd->OnSleep(); +} + +void OpenUpdateURL() +{ + // build the URL + StringOutputStream URL(256); + URL << "http://www.icculus.org/netradiant/?cmd=update&data=dlupdate&query_dlup=1"; +#ifdef WIN32 + URL << "&OS_dlup=1"; +#elif defined(__APPLE__) + URL << "&OS_dlup=2"; +#else + URL << "&OS_dlup=3"; +#endif + URL << "&Version_dlup=" RADIANT_VERSION; + g_GamesDialog.AddPacksURL(URL); + OpenURL(URL.c_str()); +} + +// open the Q3Rad manual +void OpenHelpURL() +{ + // at least on win32, AppPath + "docs/index.html" + StringOutputStream help(256); + help << AppPath_get() << "docs/index.html"; + OpenURL(help.c_str()); +} + +void OpenBugReportURL() +{ + OpenURL("http://www.icculus.org/netradiant/?cmd=bugs"); +} + + +GtkWidget* g_page_console; + +void Console_ToggleShow() +{ + GroupDialog_showPage(g_page_console); +} + +GtkWidget* g_page_entity; + +void EntityInspector_ToggleShow() +{ + GroupDialog_showPage(g_page_entity); +} + + + +void SetClipMode(bool enable); +void ModeChangeNotify(); + +typedef void(*ToolMode)(); +ToolMode g_currentToolMode = 0; +bool g_currentToolModeSupportsComponentEditing = false; +ToolMode g_defaultToolMode = 0; + + + +void SelectionSystem_DefaultMode() +{ + GlobalSelectionSystem().SetMode(SelectionSystem::ePrimitive); + GlobalSelectionSystem().SetComponentMode(SelectionSystem::eDefault); + ModeChangeNotify(); +} + + +bool EdgeMode() +{ + return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent + && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eEdge; +} + +bool VertexMode() +{ + return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent + && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex; +} + +bool FaceMode() +{ + return GlobalSelectionSystem().Mode() == SelectionSystem::eComponent + && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace; +} + +template +class BoolFunctionExport +{ +public: + static void apply(const BoolImportCallback& importCallback) + { + importCallback(BoolFunction()); + } +}; + +typedef FreeCaller1::apply> EdgeModeApplyCaller; +EdgeModeApplyCaller g_edgeMode_button_caller; +BoolExportCallback g_edgeMode_button_callback(g_edgeMode_button_caller); +ToggleItem g_edgeMode_button(g_edgeMode_button_callback); + +typedef FreeCaller1::apply> VertexModeApplyCaller; +VertexModeApplyCaller g_vertexMode_button_caller; +BoolExportCallback g_vertexMode_button_callback(g_vertexMode_button_caller); +ToggleItem g_vertexMode_button(g_vertexMode_button_callback); + +typedef FreeCaller1::apply> FaceModeApplyCaller; +FaceModeApplyCaller g_faceMode_button_caller; +BoolExportCallback g_faceMode_button_callback(g_faceMode_button_caller); +ToggleItem g_faceMode_button(g_faceMode_button_callback); + +void ComponentModeChanged() +{ + g_edgeMode_button.update(); + g_vertexMode_button.update(); + g_faceMode_button.update(); +} + +void ComponentMode_SelectionChanged(const Selectable& selectable) +{ + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent + && GlobalSelectionSystem().countSelected() == 0) + { + SelectionSystem_DefaultMode(); + ComponentModeChanged(); + } +} + +void SelectEdgeMode() +{ +#if 0 + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) + { + GlobalSelectionSystem().Select(false); + } +#endif + + if(EdgeMode()) + { + SelectionSystem_DefaultMode(); + } + else if(GlobalSelectionSystem().countSelected() != 0) + { + if(!g_currentToolModeSupportsComponentEditing) + { + g_defaultToolMode(); + } + + GlobalSelectionSystem().SetMode(SelectionSystem::eComponent); + GlobalSelectionSystem().SetComponentMode(SelectionSystem::eEdge); + } + + ComponentModeChanged(); + + ModeChangeNotify(); +} + +void SelectVertexMode() +{ +#if 0 + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) + { + GlobalSelectionSystem().Select(false); + } +#endif + + if(VertexMode()) + { + SelectionSystem_DefaultMode(); + } + else if(GlobalSelectionSystem().countSelected() != 0) + { + if(!g_currentToolModeSupportsComponentEditing) + { + g_defaultToolMode(); + } + + GlobalSelectionSystem().SetMode(SelectionSystem::eComponent); + GlobalSelectionSystem().SetComponentMode(SelectionSystem::eVertex); + } + + ComponentModeChanged(); + + ModeChangeNotify(); +} + +void SelectFaceMode() +{ +#if 0 + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) + { + GlobalSelectionSystem().Select(false); + } +#endif + + if(FaceMode()) + { + SelectionSystem_DefaultMode(); + } + else if(GlobalSelectionSystem().countSelected() != 0) + { + if(!g_currentToolModeSupportsComponentEditing) + { + g_defaultToolMode(); + } + + GlobalSelectionSystem().SetMode(SelectionSystem::eComponent); + GlobalSelectionSystem().SetComponentMode(SelectionSystem::eFace); + } + + ComponentModeChanged(); + + ModeChangeNotify(); +} + + +class CloneSelected : public scene::Graph::Walker +{ + bool doMakeUnique; + NodeSmartReference worldspawn; +public: + CloneSelected(bool d): doMakeUnique(d), worldspawn(Map_FindOrInsertWorldspawn(g_map)) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.size() == 1) + return true; + + // ignore worldspawn, but keep checking children + NodeSmartReference me(path.top().get()); + if(me == worldspawn) + return true; + + if(!path.top().get().isRoot()) + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected()) + { + return false; + } + } + + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + if(path.size() == 1) + return; + + // ignore worldspawn, but keep checking children + NodeSmartReference me(path.top().get()); + if(me == worldspawn) + return; + + if(!path.top().get().isRoot()) + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected()) + { + NodeSmartReference clone(Node_Clone(path.top())); + if(doMakeUnique) + Map_gatherNamespaced(clone); + Node_getTraversable(path.parent().get())->insert(clone); + } + } + } +}; + +void Scene_Clone_Selected(scene::Graph& graph, bool doMakeUnique) +{ + graph.traverse(CloneSelected(doMakeUnique)); + + Map_mergeClonedNames(); +} + +enum ENudgeDirection +{ + eNudgeUp = 1, + eNudgeDown = 3, + eNudgeLeft = 0, + eNudgeRight = 2, +}; + +struct AxisBase +{ + Vector3 x; + Vector3 y; + Vector3 z; + AxisBase(const Vector3& x_, const Vector3& y_, const Vector3& z_) + : x(x_), y(y_), z(z_) + { + } +}; + +AxisBase AxisBase_forViewType(VIEWTYPE viewtype) +{ + switch(viewtype) + { + case XY: + return AxisBase(g_vector3_axis_x, g_vector3_axis_y, g_vector3_axis_z); + case XZ: + return AxisBase(g_vector3_axis_x, g_vector3_axis_z, g_vector3_axis_y); + case YZ: + return AxisBase(g_vector3_axis_y, g_vector3_axis_z, g_vector3_axis_x); + } + + ERROR_MESSAGE("invalid viewtype"); + return AxisBase(Vector3(0, 0, 0), Vector3(0, 0, 0), Vector3(0, 0, 0)); +} + +Vector3 AxisBase_axisForDirection(const AxisBase& axes, ENudgeDirection direction) +{ + switch (direction) + { + case eNudgeLeft: + return vector3_negated(axes.x); + case eNudgeUp: + return axes.y; + case eNudgeRight: + return axes.x; + case eNudgeDown: + return vector3_negated(axes.y); + } + + ERROR_MESSAGE("invalid direction"); + return Vector3(0, 0, 0); +} + +void NudgeSelection(ENudgeDirection direction, float fAmount, VIEWTYPE viewtype) +{ + AxisBase axes(AxisBase_forViewType(viewtype)); + Vector3 view_direction(vector3_negated(axes.z)); + Vector3 nudge(vector3_scaled(AxisBase_axisForDirection(axes, direction), fAmount)); + GlobalSelectionSystem().NudgeManipulator(nudge, view_direction); +} + +void Selection_Clone() +{ + if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) + { + UndoableCommand undo("cloneSelected"); + + Scene_Clone_Selected(GlobalSceneGraph(), false); + + //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType()); + //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType()); + } +} + +void Selection_Clone_MakeUnique() +{ + if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) + { + UndoableCommand undo("cloneSelectedMakeUnique"); + + Scene_Clone_Selected(GlobalSceneGraph(), true); + + //NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType()); + //NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType()); + } +} + +// called when the escape key is used (either on the main window or on an inspector) +void Selection_Deselect() +{ + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) + { + if(GlobalSelectionSystem().countSelectedComponents() != 0) + { + GlobalSelectionSystem().setSelectedAllComponents(false); + } + else + { + SelectionSystem_DefaultMode(); + ComponentModeChanged(); + } + } + else + { + if(GlobalSelectionSystem().countSelectedComponents() != 0) + { + GlobalSelectionSystem().setSelectedAllComponents(false); + } + else + { + GlobalSelectionSystem().setSelectedAll(false); + } + } +} + + +void Selection_NudgeUp() +{ + UndoableCommand undo("nudgeSelectedUp"); + NudgeSelection(eNudgeUp, GetGridSize(), GlobalXYWnd_getCurrentViewType()); +} + +void Selection_NudgeDown() +{ + UndoableCommand undo("nudgeSelectedDown"); + NudgeSelection(eNudgeDown, GetGridSize(), GlobalXYWnd_getCurrentViewType()); +} + +void Selection_NudgeLeft() +{ + UndoableCommand undo("nudgeSelectedLeft"); + NudgeSelection(eNudgeLeft, GetGridSize(), GlobalXYWnd_getCurrentViewType()); +} + +void Selection_NudgeRight() +{ + UndoableCommand undo("nudgeSelectedRight"); + NudgeSelection(eNudgeRight, GetGridSize(), GlobalXYWnd_getCurrentViewType()); +} + + +void TranslateToolExport(const BoolImportCallback& importCallback) +{ + importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eTranslate); +} + +void RotateToolExport(const BoolImportCallback& importCallback) +{ + importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eRotate); +} + +void ScaleToolExport(const BoolImportCallback& importCallback) +{ + importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eScale); +} + +void DragToolExport(const BoolImportCallback& importCallback) +{ + importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eDrag); +} + +void ClipperToolExport(const BoolImportCallback& importCallback) +{ + importCallback(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip); +} + +FreeCaller1 g_translatemode_button_caller; +BoolExportCallback g_translatemode_button_callback(g_translatemode_button_caller); +ToggleItem g_translatemode_button(g_translatemode_button_callback); + +FreeCaller1 g_rotatemode_button_caller; +BoolExportCallback g_rotatemode_button_callback(g_rotatemode_button_caller); +ToggleItem g_rotatemode_button(g_rotatemode_button_callback); + +FreeCaller1 g_scalemode_button_caller; +BoolExportCallback g_scalemode_button_callback(g_scalemode_button_caller); +ToggleItem g_scalemode_button(g_scalemode_button_callback); + +FreeCaller1 g_dragmode_button_caller; +BoolExportCallback g_dragmode_button_callback(g_dragmode_button_caller); +ToggleItem g_dragmode_button(g_dragmode_button_callback); + +FreeCaller1 g_clipper_button_caller; +BoolExportCallback g_clipper_button_callback(g_clipper_button_caller); +ToggleItem g_clipper_button(g_clipper_button_callback); + +void ToolChanged() +{ + g_translatemode_button.update(); + g_rotatemode_button.update(); + g_scalemode_button.update(); + g_dragmode_button.update(); + g_clipper_button.update(); +} + +const char* const c_ResizeMode_status = "QE4 Drag Tool: move and resize objects"; + +void DragMode() +{ + if(g_currentToolMode == DragMode && g_defaultToolMode != DragMode) + { + g_defaultToolMode(); + } + else + { + g_currentToolMode = DragMode; + g_currentToolModeSupportsComponentEditing = true; + + OnClipMode(false); + + Sys_Status(c_ResizeMode_status); + GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eDrag); + ToolChanged(); + ModeChangeNotify(); + } +} + + +const char* const c_TranslateMode_status = "Translate Tool: translate objects and components"; + +void TranslateMode() +{ + if(g_currentToolMode == TranslateMode && g_defaultToolMode != TranslateMode) + { + g_defaultToolMode(); + } + else + { + g_currentToolMode = TranslateMode; + g_currentToolModeSupportsComponentEditing = true; + + OnClipMode(false); + + Sys_Status(c_TranslateMode_status); + GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eTranslate); + ToolChanged(); + ModeChangeNotify(); + } +} + +const char* const c_RotateMode_status = "Rotate Tool: rotate objects and components"; + +void RotateMode() +{ + if(g_currentToolMode == RotateMode && g_defaultToolMode != RotateMode) + { + g_defaultToolMode(); + } + else + { + g_currentToolMode = RotateMode; + g_currentToolModeSupportsComponentEditing = true; + + OnClipMode(false); + + Sys_Status(c_RotateMode_status); + GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eRotate); + ToolChanged(); + ModeChangeNotify(); + } +} + +const char* const c_ScaleMode_status = "Scale Tool: scale objects and components"; + +void ScaleMode() +{ + if(g_currentToolMode == ScaleMode && g_defaultToolMode != ScaleMode) + { + g_defaultToolMode(); + } + else + { + g_currentToolMode = ScaleMode; + g_currentToolModeSupportsComponentEditing = true; + + OnClipMode(false); + + Sys_Status(c_ScaleMode_status); + GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eScale); + ToolChanged(); + ModeChangeNotify(); + } +} + + +const char* const c_ClipperMode_status = "Clipper Tool: apply clip planes to objects"; + + +void ClipperMode() +{ + if(g_currentToolMode == ClipperMode && g_defaultToolMode != ClipperMode) + { + g_defaultToolMode(); + } + else + { + g_currentToolMode = ClipperMode; + g_currentToolModeSupportsComponentEditing = false; + + SelectionSystem_DefaultMode(); + + OnClipMode(true); + + Sys_Status(c_ClipperMode_status); + GlobalSelectionSystem().SetManipulatorMode(SelectionSystem::eClip); + ToolChanged(); + ModeChangeNotify(); + } +} + + +void Texdef_Rotate(float angle) +{ + StringOutputStream command; + command << "brushRotateTexture -angle " << angle; + UndoableCommand undo(command.c_str()); + Select_RotateTexture(angle); +} + +void Texdef_RotateClockwise() +{ + Texdef_Rotate(static_cast(fabs(g_si_globals.rotate))); +} + +void Texdef_RotateAntiClockwise() +{ + Texdef_Rotate(static_cast(-fabs(g_si_globals.rotate))); +} + +void Texdef_Scale(float x, float y) +{ + StringOutputStream command; + command << "brushScaleTexture -x " << x << " -y " << y; + UndoableCommand undo(command.c_str()); + Select_ScaleTexture(x, y); +} + +void Texdef_ScaleUp() +{ + Texdef_Scale(0, g_si_globals.scale[1]); +} + +void Texdef_ScaleDown() +{ + Texdef_Scale(0, -g_si_globals.scale[1]); +} + +void Texdef_ScaleLeft() +{ + Texdef_Scale(-g_si_globals.scale[0],0); +} + +void Texdef_ScaleRight() +{ + Texdef_Scale(g_si_globals.scale[0],0); +} + +void Texdef_Shift(float x, float y) +{ + StringOutputStream command; + command << "brushShiftTexture -x " << x << " -y " << y; + UndoableCommand undo(command.c_str()); + Select_ShiftTexture(x, y); +} + +void Texdef_ShiftLeft() +{ + Texdef_Shift(-g_si_globals.shift[0], 0); +} + +void Texdef_ShiftRight() +{ + Texdef_Shift(g_si_globals.shift[0], 0); +} + +void Texdef_ShiftUp() +{ + Texdef_Shift(0, g_si_globals.shift[1]); +} + +void Texdef_ShiftDown() +{ + Texdef_Shift(0, -g_si_globals.shift[1]); +} + + + +class SnappableSnapToGridSelected : public scene::Graph::Walker +{ + float m_snap; +public: + SnappableSnapToGridSelected(float snap) + : m_snap(snap) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Snappable* snappable = Node_getSnappable(path.top()); + if(snappable != 0 + && Instance_getSelectable(instance)->isSelected()) + { + snappable->snapto(m_snap); + } + } + return true; + } +}; + +void Scene_SnapToGrid_Selected(scene::Graph& graph, float snap) +{ + graph.traverse(SnappableSnapToGridSelected(snap)); +} + +class ComponentSnappableSnapToGridSelected : public scene::Graph::Walker +{ + float m_snap; +public: + ComponentSnappableSnapToGridSelected(float snap) + : m_snap(snap) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + ComponentSnappable* componentSnappable = Instance_getComponentSnappable(instance); + if(componentSnappable != 0 + && Instance_getSelectable(instance)->isSelected()) + { + componentSnappable->snapComponents(m_snap); + } + } + return true; + } +}; + +void Scene_SnapToGrid_Component_Selected(scene::Graph& graph, float snap) +{ + graph.traverse(ComponentSnappableSnapToGridSelected(snap)); +} + +void Selection_SnapToGrid() +{ + StringOutputStream command; + command << "snapSelected -grid " << GetGridSize(); + UndoableCommand undo(command.c_str()); + + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) + { + Scene_SnapToGrid_Component_Selected(GlobalSceneGraph(), GetGridSize()); + } + else + { + Scene_SnapToGrid_Selected(GlobalSceneGraph(), GetGridSize()); + } +} + + +static gint qe_every_second(gpointer data) +{ + GdkModifierType mask; + + gdk_window_get_pointer (0, 0, 0, &mask); + + if ((mask & (GDK_BUTTON1_MASK|GDK_BUTTON2_MASK|GDK_BUTTON3_MASK)) == 0) + { + QE_CheckAutoSave(); + } + + return TRUE; +} + +guint s_qe_every_second_id = 0; + +void EverySecondTimer_enable() +{ + if(s_qe_every_second_id == 0) + { + s_qe_every_second_id = gtk_timeout_add(1000, qe_every_second, 0); + } +} + +void EverySecondTimer_disable() +{ + if(s_qe_every_second_id != 0) + { + gtk_timeout_remove(s_qe_every_second_id); + s_qe_every_second_id = 0; + } +} + +gint window_realize_remove_decoration(GtkWidget* widget, gpointer data) +{ + gdk_window_set_decorations(widget->window, (GdkWMDecoration)(GDK_DECOR_ALL|GDK_DECOR_MENU|GDK_DECOR_MINIMIZE|GDK_DECOR_MAXIMIZE)); + return FALSE; +} + +class WaitDialog +{ +public: + GtkWindow* m_window; + GtkLabel* m_label; +}; + +WaitDialog create_wait_dialog(const char* title, const char* text) +{ + WaitDialog dialog; + + dialog.m_window = create_floating_window(title, MainFrame_getWindow()); + gtk_window_set_resizable(dialog.m_window, FALSE); + gtk_container_set_border_width(GTK_CONTAINER(dialog.m_window), 0); + gtk_window_set_position(dialog.m_window, GTK_WIN_POS_CENTER_ON_PARENT); + + g_signal_connect(G_OBJECT(dialog.m_window), "realize", G_CALLBACK(window_realize_remove_decoration), 0); + + { + dialog.m_label = GTK_LABEL(gtk_label_new(text)); + gtk_misc_set_alignment(GTK_MISC(dialog.m_label), 0.0, 0.5); + gtk_label_set_justify(dialog.m_label, GTK_JUSTIFY_LEFT); + gtk_widget_show(GTK_WIDGET(dialog.m_label)); + gtk_widget_set_size_request(GTK_WIDGET(dialog.m_label), 200, -1); + + gtk_container_add(GTK_CONTAINER(dialog.m_window), GTK_WIDGET(dialog.m_label)); + } + return dialog; +} + +namespace +{ + clock_t g_lastRedrawTime = 0; + const clock_t c_redrawInterval = clock_t(CLOCKS_PER_SEC / 10); + + bool redrawRequired() + { + clock_t currentTime = std::clock(); + if(currentTime - g_lastRedrawTime >= c_redrawInterval) + { + g_lastRedrawTime = currentTime; + return true; + } + return false; + } +} + +bool MainFrame_isActiveApp() +{ + //globalOutputStream() << "listing\n"; + GList* list = gtk_window_list_toplevels(); + for(GList* i = list; i != 0; i = g_list_next(i)) + { + //globalOutputStream() << "toplevel.. "; + if(gtk_window_is_active(GTK_WINDOW(i->data))) + { + //globalOutputStream() << "is active\n"; + return true; + } + //globalOutputStream() << "not active\n"; + } + return false; +} + +typedef std::list StringStack; +StringStack g_wait_stack; +WaitDialog g_wait; + +bool ScreenUpdates_Enabled() +{ + return g_wait_stack.empty(); +} + +void ScreenUpdates_process() +{ + if(redrawRequired() && GTK_WIDGET_VISIBLE(g_wait.m_window)) + { + process_gui(); + } +} + + +void ScreenUpdates_Disable(const char* message, const char* title) +{ + if(g_wait_stack.empty()) + { + EverySecondTimer_disable(); + + process_gui(); + + bool isActiveApp = MainFrame_isActiveApp(); + + g_wait = create_wait_dialog(title, message); + gtk_grab_add(GTK_WIDGET(g_wait.m_window)); + + if(isActiveApp) + { + gtk_widget_show(GTK_WIDGET(g_wait.m_window)); + ScreenUpdates_process(); + } + } + else if(GTK_WIDGET_VISIBLE(g_wait.m_window)) + { + gtk_label_set_text(g_wait.m_label, message); + ScreenUpdates_process(); + } + g_wait_stack.push_back(message); +} + +void ScreenUpdates_Enable() +{ + ASSERT_MESSAGE(!ScreenUpdates_Enabled(), "screen updates already enabled"); + g_wait_stack.pop_back(); + if(g_wait_stack.empty()) + { + EverySecondTimer_enable(); + //gtk_widget_set_sensitive(GTK_WIDGET(MainFrame_getWindow()), TRUE); + + gtk_grab_remove(GTK_WIDGET(g_wait.m_window)); + destroy_floating_window(g_wait.m_window); + g_wait.m_window = 0; + + //gtk_window_present(MainFrame_getWindow()); + } + else if(GTK_WIDGET_VISIBLE(g_wait.m_window)) + { + gtk_label_set_text(g_wait.m_label, g_wait_stack.back().c_str()); + ScreenUpdates_process(); + } +} + + + +void GlobalCamera_UpdateWindow() +{ + if(g_pParentWnd != 0) + { + CamWnd_Update(*g_pParentWnd->GetCamWnd()); + } +} + +void XY_UpdateWindow(MainFrame& mainframe) +{ + if(mainframe.GetXYWnd() != 0) + { + XYWnd_Update(*mainframe.GetXYWnd()); + } +} + +void XZ_UpdateWindow(MainFrame& mainframe) +{ + if(mainframe.GetXZWnd() != 0) + { + XYWnd_Update(*mainframe.GetXZWnd()); + } +} + +void YZ_UpdateWindow(MainFrame& mainframe) +{ + if(mainframe.GetYZWnd() != 0) + { + XYWnd_Update(*mainframe.GetYZWnd()); + } +} + +void XY_UpdateAllWindows(MainFrame& mainframe) +{ + XY_UpdateWindow(mainframe); + XZ_UpdateWindow(mainframe); + YZ_UpdateWindow(mainframe); +} + +void XY_UpdateAllWindows() +{ + if(g_pParentWnd != 0) + { + XY_UpdateAllWindows(*g_pParentWnd); + } +} + +void UpdateAllWindows() +{ + GlobalCamera_UpdateWindow(); + XY_UpdateAllWindows(); +} + + +void ModeChangeNotify() +{ + SceneChangeNotify(); +} + +void ClipperChangeNotify() +{ + GlobalCamera_UpdateWindow(); + XY_UpdateAllWindows(); +} + + +LatchedInt g_Layout_viewStyle(0, "Window Layout"); +LatchedBool g_Layout_enableDetachableMenus(true, "Detachable Menus"); +LatchedBool g_Layout_enablePatchToolbar(true, "Patch Toolbar"); +LatchedBool g_Layout_enablePluginToolbar(true, "Plugin Toolbar"); + + + +GtkMenuItem* create_file_menu() +{ + // File menu + GtkMenuItem* file_menu_item = new_sub_menu_item_with_mnemonic("_File"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(file_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + create_menu_item_with_mnemonic(menu, "_New Map", "NewMap"); + menu_separator(menu); + +#if 0 + //++timo temporary experimental stuff for sleep mode.. + create_menu_item_with_mnemonic(menu, "_Sleep", "Sleep"); + menu_separator(menu); + // end experimental +#endif + + create_menu_item_with_mnemonic(menu, "_Open...", "OpenMap"); + + create_menu_item_with_mnemonic(menu, "_Import...", "ImportMap"); + create_menu_item_with_mnemonic(menu, "_Save", "SaveMap"); + create_menu_item_with_mnemonic(menu, "Save _as...", "SaveMapAs"); + create_menu_item_with_mnemonic(menu, "Save s_elected...", "SaveSelected"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Save re_gion...", "SaveRegion"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "_Refresh models", "RefreshReferences"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Pro_ject settings...", "ProjectSettings"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "_Pointfile...", "TogglePointfile"); + menu_separator(menu); + MRU_constructMenu(menu); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Check for NetRadiant update (web)", "CheckForUpdate"); // FIXME + create_menu_item_with_mnemonic(menu, "E_xit", "Exit"); + + return file_menu_item; +} + +GtkMenuItem* create_edit_menu() +{ + // Edit menu + GtkMenuItem* edit_menu_item = new_sub_menu_item_with_mnemonic("_Edit"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(edit_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + create_menu_item_with_mnemonic(menu, "_Undo", "Undo"); + create_menu_item_with_mnemonic(menu, "_Redo", "Redo"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "_Copy", "Copy"); + create_menu_item_with_mnemonic(menu, "_Paste", "Paste"); + create_menu_item_with_mnemonic(menu, "P_aste To Camera", "PasteToCamera"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "_Duplicate", "CloneSelection"); + create_menu_item_with_mnemonic(menu, "Duplicate, make uni_que", "CloneSelectionAndMakeUnique"); + create_menu_item_with_mnemonic(menu, "D_elete", "DeleteSelection"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Pa_rent", "ParentSelection"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "C_lear Selection", "UnSelectSelection"); + create_menu_item_with_mnemonic(menu, "_Invert Selection", "InvertSelection"); + create_menu_item_with_mnemonic(menu, "Select i_nside", "SelectInside"); + create_menu_item_with_mnemonic(menu, "Select _touching", "SelectTouching"); + + GtkMenu* convert_menu = create_sub_menu_with_mnemonic(menu, "E_xpand Selection"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (convert_menu); + create_menu_item_with_mnemonic(convert_menu, "To Whole _Entities", "ExpandSelectionToEntities"); + + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Pre_ferences...", "Preferences"); + + return edit_menu_item; +} + +void fill_view_xy_top_menu(GtkMenu* menu) +{ + create_check_menu_item_with_mnemonic(menu, "XY (Top) View", "ToggleView"); +} + + +void fill_view_yz_side_menu(GtkMenu* menu) +{ + create_check_menu_item_with_mnemonic(menu, "YZ (Side) View", "ToggleSideView"); +} + + +void fill_view_xz_front_menu(GtkMenu* menu) +{ + create_check_menu_item_with_mnemonic(menu, "XZ (Front) View", "ToggleFrontView"); +} + + +GtkWidget* g_toggle_z_item = 0; +GtkWidget* g_toggle_console_item = 0; +GtkWidget* g_toggle_entity_item = 0; +GtkWidget* g_toggle_entitylist_item = 0; + +GtkMenuItem* create_view_menu(MainFrame::EViewStyle style) +{ + // View menu + GtkMenuItem* view_menu_item = new_sub_menu_item_with_mnemonic("Vie_w"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(view_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + if(style == MainFrame::eFloating) + { + fill_view_camera_menu(menu); + fill_view_xy_top_menu(menu); + fill_view_yz_side_menu(menu); + fill_view_xz_front_menu(menu); + } + if(style == MainFrame::eFloating || style == MainFrame::eSplit) + { + create_menu_item_with_mnemonic(menu, "Console View", "ToggleConsole"); + create_menu_item_with_mnemonic(menu, "Texture Browser", "ToggleTextures"); + create_menu_item_with_mnemonic(menu, "Entity Inspector", "ToggleEntityInspector"); + } + else + { + create_menu_item_with_mnemonic(menu, "Entity Inspector", "ViewEntityInfo"); + } + create_menu_item_with_mnemonic(menu, "_Surface Inspector", "SurfaceInspector"); + create_menu_item_with_mnemonic(menu, "Entity List", "EntityList"); + + menu_separator(menu); + { + GtkMenu* camera_menu = create_sub_menu_with_mnemonic (menu, "Camera"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (camera_menu); + create_menu_item_with_mnemonic(camera_menu, "_Center", "CenterView"); + create_menu_item_with_mnemonic(camera_menu, "_Up Floor", "UpFloor"); + create_menu_item_with_mnemonic(camera_menu, "_Down Floor", "DownFloor"); + menu_separator(camera_menu); + create_menu_item_with_mnemonic(camera_menu, "Far Clip Plane In", "CubicClipZoomIn"); + create_menu_item_with_mnemonic(camera_menu, "Far Clip Plane Out", "CubicClipZoomOut"); + menu_separator(camera_menu); + create_menu_item_with_mnemonic(camera_menu, "Next leak spot", "NextLeakSpot"); + create_menu_item_with_mnemonic(camera_menu, "Previous leak spot", "PrevLeakSpot"); + menu_separator(camera_menu); + create_menu_item_with_mnemonic(camera_menu, "Look Through Selected", "LookThroughSelected"); + create_menu_item_with_mnemonic(camera_menu, "Look Through Camera", "LookThroughCamera"); + } + menu_separator(menu); + { + GtkMenu* orthographic_menu = create_sub_menu_with_mnemonic(menu, "Orthographic"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (orthographic_menu); + if(style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating) + { + create_menu_item_with_mnemonic(orthographic_menu, "_Next (XY, YZ, XY)", "NextView"); + create_menu_item_with_mnemonic(orthographic_menu, "XY (Top)", "ViewTop"); + create_menu_item_with_mnemonic(orthographic_menu, "YZ", "ViewSide"); + create_menu_item_with_mnemonic(orthographic_menu, "XZ", "ViewFront"); + menu_separator(orthographic_menu); + } + + create_menu_item_with_mnemonic(orthographic_menu, "_XY 100%", "Zoom100"); + create_menu_item_with_mnemonic(orthographic_menu, "XY Zoom _In", "ZoomIn"); + create_menu_item_with_mnemonic(orthographic_menu, "XY Zoom _Out", "ZoomOut"); + } + + menu_separator(menu); + + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Show"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show _Angles", "ShowAngles"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show _Names", "ShowNames"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show Blocks", "ShowBlocks"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show C_oordinates", "ShowCoordinates"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show Window Outline", "ShowWindowOutline"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show Axes", "ShowAxes"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show Workzone", "ShowWorkzone"); + create_check_menu_item_with_mnemonic(menu_in_menu, "Show Stats", "ShowStats"); + } + + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Filter"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + Filters_constructMenu(menu_in_menu); + } + menu_separator(menu); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Hide/Show"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Hide Selected", "HideSelected"); + create_menu_item_with_mnemonic(menu_in_menu, "Show Hidden", "ShowHidden"); + } + menu_separator(menu); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Region"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "_Off", "RegionOff"); + create_menu_item_with_mnemonic(menu_in_menu, "_Set XY", "RegionSetXY"); + create_menu_item_with_mnemonic(menu_in_menu, "Set _Brush", "RegionSetBrush"); + create_menu_item_with_mnemonic(menu_in_menu, "Set Se_lected Brushes", "RegionSetSelection"); + } + + command_connect_accelerator("CenterXYView"); + + return view_menu_item; +} + +GtkMenuItem* create_selection_menu() +{ + // Selection menu + GtkMenuItem* selection_menu_item = new_sub_menu_item_with_mnemonic("M_odify"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(selection_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Components"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_check_menu_item_with_mnemonic(menu_in_menu, "_Edges", "DragEdges"); + create_check_menu_item_with_mnemonic(menu_in_menu, "_Vertices", "DragVertices"); + create_check_menu_item_with_mnemonic(menu_in_menu, "_Faces", "DragFaces"); + } + + menu_separator(menu); + + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic(menu, "Nudge"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Nudge Left", "SelectNudgeLeft"); + create_menu_item_with_mnemonic(menu_in_menu, "Nudge Right", "SelectNudgeRight"); + create_menu_item_with_mnemonic(menu_in_menu, "Nudge Up", "SelectNudgeUp"); + create_menu_item_with_mnemonic(menu_in_menu, "Nudge Down", "SelectNudgeDown"); + } + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Rotate"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Rotate X", "RotateSelectionX"); + create_menu_item_with_mnemonic(menu_in_menu, "Rotate Y", "RotateSelectionY"); + create_menu_item_with_mnemonic(menu_in_menu, "Rotate Z", "RotateSelectionZ"); + } + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Flip"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Flip _X", "MirrorSelectionX"); + create_menu_item_with_mnemonic(menu_in_menu, "Flip _Y", "MirrorSelectionY"); + create_menu_item_with_mnemonic(menu_in_menu, "Flip _Z", "MirrorSelectionZ"); + } + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Arbitrary rotation...", "ArbitraryRotation"); + create_menu_item_with_mnemonic(menu, "Arbitrary scale...", "ArbitraryScale"); + + return selection_menu_item; +} + +GtkMenuItem* create_bsp_menu() +{ + // BSP menu + GtkMenuItem* bsp_menu_item = new_sub_menu_item_with_mnemonic("_Build"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(bsp_menu_item)); + + if (g_Layout_enableDetachableMenus.m_value) + { + menu_tearoff(menu); + } + + create_menu_item_with_mnemonic(menu, "Customize...", "BuildMenuCustomize"); + + menu_separator(menu); + + Build_constructMenu(menu); + + g_bsp_menu = menu; + + return bsp_menu_item; +} + +GtkMenuItem* create_grid_menu() +{ + // Grid menu + GtkMenuItem* grid_menu_item = new_sub_menu_item_with_mnemonic("_Grid"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(grid_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + Grid_constructMenu(menu); + + return grid_menu_item; +} + +GtkMenuItem* create_misc_menu() +{ + // Misc menu + GtkMenuItem* misc_menu_item = new_sub_menu_item_with_mnemonic("M_isc"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(misc_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + +#if 0 + create_menu_item_with_mnemonic(menu, "_Benchmark", FreeCaller()); +#endif + gtk_container_add(GTK_CONTAINER(menu), GTK_WIDGET(create_colours_menu())); + + create_menu_item_with_mnemonic(menu, "Find brush...", "FindBrush"); + create_menu_item_with_mnemonic(menu, "Map Info...", "MapInfo"); + // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394 +// create_menu_item_with_mnemonic(menu, "_Print XY View", FreeCaller()); + create_menu_item_with_mnemonic(menu, "_Background select", FreeCaller()); + return misc_menu_item; +} + +GtkMenuItem* create_entity_menu() +{ + // Brush menu + GtkMenuItem* entity_menu_item = new_sub_menu_item_with_mnemonic("E_ntity"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(entity_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + Entity_constructMenu(menu); + + return entity_menu_item; +} + +GtkMenuItem* create_brush_menu() +{ + // Brush menu + GtkMenuItem* brush_menu_item = new_sub_menu_item_with_mnemonic("B_rush"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(brush_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + Brush_constructMenu(menu); + + return brush_menu_item; +} + +GtkMenuItem* create_patch_menu() +{ + // Curve menu + GtkMenuItem* patch_menu_item = new_sub_menu_item_with_mnemonic("_Curve"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(patch_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + { + menu_tearoff(menu); + } + + Patch_constructMenu(menu); + + return patch_menu_item; +} + +GtkMenuItem* create_help_menu() +{ + // Help menu + GtkMenuItem* help_menu_item = new_sub_menu_item_with_mnemonic("_Help"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(help_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + create_menu_item_with_mnemonic(menu, "Manual", "OpenManual"); + + // this creates all the per-game drop downs for the game pack helps + // it will take care of hooking the Sys_OpenURL calls etc. + create_game_help_menu(menu); + + create_menu_item_with_mnemonic(menu, "Bug report", FreeCaller()); + create_menu_item_with_mnemonic(menu, "Shortcuts list", FreeCaller()); + create_menu_item_with_mnemonic(menu, "_About", FreeCaller()); + + return help_menu_item; +} + +GtkMenuBar* create_main_menu(MainFrame::EViewStyle style) +{ + GtkMenuBar* menu_bar = GTK_MENU_BAR(gtk_menu_bar_new()); + gtk_widget_show(GTK_WIDGET(menu_bar)); + + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_file_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_edit_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_view_menu(style))); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_selection_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_bsp_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_grid_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_misc_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_entity_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_brush_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_patch_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_plugins_menu())); + gtk_container_add(GTK_CONTAINER(menu_bar), GTK_WIDGET(create_help_menu())); + + return menu_bar; +} + + +void PatchInspector_registerShortcuts() +{ + command_connect_accelerator("PatchInspector"); +} + +void Patch_registerShortcuts() +{ + command_connect_accelerator("InvertCurveTextureX"); + command_connect_accelerator("InvertCurveTextureY"); + command_connect_accelerator("IncPatchColumn"); + command_connect_accelerator("IncPatchRow"); + command_connect_accelerator("DecPatchColumn"); + command_connect_accelerator("DecPatchRow"); + command_connect_accelerator("NaturalizePatch"); + //command_connect_accelerator("CapCurrentCurve"); +} + +void Manipulators_registerShortcuts() +{ + toggle_add_accelerator("MouseRotate"); + toggle_add_accelerator("MouseTranslate"); + toggle_add_accelerator("MouseScale"); + toggle_add_accelerator("MouseDrag"); + toggle_add_accelerator("ToggleClipper"); +} + +void TexdefNudge_registerShortcuts() +{ + command_connect_accelerator("TexRotateClock"); + command_connect_accelerator("TexRotateCounter"); + command_connect_accelerator("TexScaleUp"); + command_connect_accelerator("TexScaleDown"); + command_connect_accelerator("TexScaleLeft"); + command_connect_accelerator("TexScaleRight"); + command_connect_accelerator("TexShiftUp"); + command_connect_accelerator("TexShiftDown"); + command_connect_accelerator("TexShiftLeft"); + command_connect_accelerator("TexShiftRight"); +} + +void SelectNudge_registerShortcuts() +{ + command_connect_accelerator("MoveSelectionDOWN"); + command_connect_accelerator("MoveSelectionUP"); + //command_connect_accelerator("SelectNudgeLeft"); + //command_connect_accelerator("SelectNudgeRight"); + //command_connect_accelerator("SelectNudgeUp"); + //command_connect_accelerator("SelectNudgeDown"); +} + +void SnapToGrid_registerShortcuts() +{ + command_connect_accelerator("SnapToGrid"); +} + +void SelectByType_registerShortcuts() +{ + command_connect_accelerator("SelectAllOfType"); +} + +void SurfaceInspector_registerShortcuts() +{ + command_connect_accelerator("FitTexture"); +} + + +void register_shortcuts() +{ + PatchInspector_registerShortcuts(); + Patch_registerShortcuts(); + Grid_registerShortcuts(); + XYWnd_registerShortcuts(); + CamWnd_registerShortcuts(); + Manipulators_registerShortcuts(); + SurfaceInspector_registerShortcuts(); + TexdefNudge_registerShortcuts(); + SelectNudge_registerShortcuts(); + SnapToGrid_registerShortcuts(); + SelectByType_registerShortcuts(); +} + +void File_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_button(toolbar, "Open an existing map (CTRL + O)", "file_open.bmp", "OpenMap"); + toolbar_append_button(toolbar, "Save the active map (CTRL + S)", "file_save.bmp", "SaveMap"); +} + +void UndoRedo_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_button(toolbar, "Undo (CTRL + Z)", "undo.bmp", "Undo"); + toolbar_append_button(toolbar, "Redo (CTRL + Y)", "redo.bmp", "Redo"); +} + +void RotateFlip_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_button(toolbar, "x-axis Flip", "brush_flipx.bmp", "MirrorSelectionX"); + toolbar_append_button(toolbar, "x-axis Rotate", "brush_rotatex.bmp", "RotateSelectionX"); + toolbar_append_button(toolbar, "y-axis Flip", "brush_flipy.bmp", "MirrorSelectionY"); + toolbar_append_button(toolbar, "y-axis Rotate", "brush_rotatey.bmp", "RotateSelectionY"); + toolbar_append_button(toolbar, "z-axis Flip", "brush_flipz.bmp", "MirrorSelectionZ"); + toolbar_append_button(toolbar, "z-axis Rotate", "brush_rotatez.bmp", "RotateSelectionZ"); +} + +void Select_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_button(toolbar, "Select touching", "selection_selecttouching.bmp", "SelectTouching"); + toolbar_append_button(toolbar, "Select inside", "selection_selectinside.bmp", "SelectInside"); +} + +void CSG_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_button(toolbar, "CSG Subtract (SHIFT + U)", "selection_csgsubtract.bmp", "CSGSubtract"); + toolbar_append_button(toolbar, "CSG Merge (CTRL + U)", "selection_csgmerge.bmp", "CSGMerge"); + toolbar_append_button(toolbar, "Hollow", "selection_makehollow.bmp", "CSGHollow"); +} + +void ComponentModes_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_toggle_button(toolbar, "Select Vertices (V)", "modify_vertices.bmp", "DragVertices"); + toolbar_append_toggle_button(toolbar, "Select Edges (E)", "modify_edges.bmp", "DragEdges"); + toolbar_append_toggle_button(toolbar, "Select Faces (F)", "modify_faces.bmp", "DragFaces"); +} + +void Clipper_constructToolbar(GtkToolbar* toolbar) +{ + + toolbar_append_toggle_button(toolbar, "Clipper (X)", "view_clipper.bmp", "ToggleClipper"); +} + +void XYWnd_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_button(toolbar, "Change views", "view_change.bmp", "NextView"); +} + +void Manipulators_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_toggle_button(toolbar, "Translate (W)", "select_mousetranslate.bmp", "MouseTranslate"); + toolbar_append_toggle_button(toolbar, "Rotate (R)", "select_mouserotate.bmp", "MouseRotate"); + toolbar_append_toggle_button(toolbar, "Scale", "select_mousescale.bmp", "MouseScale"); + toolbar_append_toggle_button(toolbar, "Resize (Q)", "select_mouseresize.bmp", "MouseDrag"); + + Clipper_constructToolbar(toolbar); +} + +GtkToolbar* create_main_toolbar(MainFrame::EViewStyle style) +{ + GtkToolbar* toolbar = GTK_TOOLBAR(gtk_toolbar_new()); + gtk_toolbar_set_orientation(toolbar, GTK_ORIENTATION_HORIZONTAL); + gtk_toolbar_set_style(toolbar, GTK_TOOLBAR_ICONS); + + gtk_widget_show(GTK_WIDGET(toolbar)); + + File_constructToolbar(toolbar); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + UndoRedo_constructToolbar(toolbar); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + RotateFlip_constructToolbar(toolbar); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + Select_constructToolbar(toolbar); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + CSG_constructToolbar(toolbar); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + ComponentModes_constructToolbar(toolbar); + + if(style == MainFrame::eRegular || style == MainFrame::eRegularLeft || style == MainFrame::eFloating) + { + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + XYWnd_constructToolbar(toolbar); + } + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + CamWnd_constructToolbar(toolbar); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + Manipulators_constructToolbar(toolbar); + + if (g_Layout_enablePatchToolbar.m_value) + { + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + Patch_constructToolbar(toolbar); + } + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + toolbar_append_toggle_button(toolbar, "Texture Lock (SHIFT +T)", "texture_lock.bmp", "TogTexLock"); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + + GtkButton* g_view_entities_button = toolbar_append_button(toolbar, "Entities (N)", "entities.bmp", "ToggleEntityInspector"); + GtkButton* g_view_console_button = toolbar_append_button(toolbar, "Console (O)", "console.bmp", "ToggleConsole"); + GtkButton* g_view_textures_button = toolbar_append_button(toolbar, "Texture Browser (T)", "texture_browser.bmp", "ToggleTextures"); + // TODO: call light inspector + //GtkButton* g_view_lightinspector_button = toolbar_append_button(toolbar, "Light Inspector", "lightinspector.bmp", "ToggleLightInspector"); + + gtk_toolbar_append_space (GTK_TOOLBAR (toolbar)); + GtkButton* g_refresh_models_button = toolbar_append_button(toolbar, "Refresh Models", "refresh_models.bmp", "RefreshReferences"); + + + // disable the console and texture button in the regular layouts + if(style == MainFrame::eRegular || style == MainFrame::eRegularLeft) + { + gtk_widget_set_sensitive(GTK_WIDGET(g_view_console_button), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(g_view_textures_button), FALSE); + } + + return toolbar; +} + +GtkWidget* create_main_statusbar(GtkWidget *pStatusLabel[c_count_status]) +{ + GtkTable* table = GTK_TABLE(gtk_table_new(1, c_count_status, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + + { + GtkLabel* label = GTK_LABEL(gtk_label_new ("Label")); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_misc_set_padding(GTK_MISC(label), 4, 2); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach_defaults(table, GTK_WIDGET(label), 0, 1, 0, 1); + pStatusLabel[c_command_status] = GTK_WIDGET(label); + } + + for(int i = 1; i < c_count_status; ++i) + { + GtkFrame* frame = GTK_FRAME(gtk_frame_new(0)); + gtk_widget_show(GTK_WIDGET(frame)); + gtk_table_attach_defaults(table, GTK_WIDGET(frame), i, i + 1, 0, 1); + gtk_frame_set_shadow_type(frame, GTK_SHADOW_IN); + + GtkLabel* label = GTK_LABEL(gtk_label_new ("Label")); + gtk_label_set_ellipsize( label, PANGO_ELLIPSIZE_END); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + gtk_misc_set_padding(GTK_MISC(label), 4, 2); + gtk_widget_show(GTK_WIDGET(label)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(label)); + pStatusLabel[i] = GTK_WIDGET(label); + } + + return GTK_WIDGET(table); +} + +#if 0 + + +WidgetFocusPrinter g_mainframeWidgetFocusPrinter("mainframe"); + +class WindowFocusPrinter +{ + const char* m_name; + + static gboolean frame_event(GtkWidget *widget, GdkEvent* event, WindowFocusPrinter* self) + { + globalOutputStream() << self->m_name << " frame_event\n"; + return FALSE; + } + static gboolean keys_changed(GtkWidget *widget, WindowFocusPrinter* self) + { + globalOutputStream() << self->m_name << " keys_changed\n"; + return FALSE; + } + static gboolean notify(GtkWindow* window, gpointer dummy, WindowFocusPrinter* self) + { + if(gtk_window_is_active(window)) + { + globalOutputStream() << self->m_name << " takes toplevel focus\n"; + } + else + { + globalOutputStream() << self->m_name << " loses toplevel focus\n"; + } + return FALSE; + } +public: + WindowFocusPrinter(const char* name) : m_name(name) + { + } + void connect(GtkWindow* toplevel_window) + { + g_signal_connect(G_OBJECT(toplevel_window), "notify::has_toplevel_focus", G_CALLBACK(notify), this); + g_signal_connect(G_OBJECT(toplevel_window), "notify::is_active", G_CALLBACK(notify), this); + g_signal_connect(G_OBJECT(toplevel_window), "keys_changed", G_CALLBACK(keys_changed), this); + g_signal_connect(G_OBJECT(toplevel_window), "frame_event", G_CALLBACK(frame_event), this); + } +}; + +WindowFocusPrinter g_mainframeFocusPrinter("mainframe"); + +#endif + +class MainWindowActive +{ + static gboolean notify(GtkWindow* window, gpointer dummy, MainWindowActive* self) + { + if(g_wait.m_window != 0 && gtk_window_is_active(window) && !GTK_WIDGET_VISIBLE(g_wait.m_window)) + { + gtk_widget_show(GTK_WIDGET(g_wait.m_window)); + } + + return FALSE; + } +public: + void connect(GtkWindow* toplevel_window) + { + g_signal_connect(G_OBJECT(toplevel_window), "notify::is-active", G_CALLBACK(notify), this); + } +}; + +MainWindowActive g_MainWindowActive; + +SignalHandlerId XYWindowDestroyed_connect(const SignalHandler& handler) +{ + return g_pParentWnd->GetXYWnd()->onDestroyed.connectFirst(handler); +} + +void XYWindowDestroyed_disconnect(SignalHandlerId id) +{ + g_pParentWnd->GetXYWnd()->onDestroyed.disconnect(id); +} + +MouseEventHandlerId XYWindowMouseDown_connect(const MouseEventHandler& handler) +{ + return g_pParentWnd->GetXYWnd()->onMouseDown.connectFirst(handler); +} + +void XYWindowMouseDown_disconnect(MouseEventHandlerId id) +{ + g_pParentWnd->GetXYWnd()->onMouseDown.disconnect(id); +} + +// ============================================================================= +// MainFrame class + +MainFrame* g_pParentWnd = 0; + +GtkWindow* MainFrame_getWindow() +{ + if(g_pParentWnd == 0) + { + return 0; + } + return g_pParentWnd->m_window; +} + +std::vector g_floating_windows; + +MainFrame::MainFrame() : m_window(0), m_idleRedrawStatusText(RedrawStatusTextCaller(*this)) +{ + m_pXYWnd = 0; + m_pCamWnd = 0; + m_pZWnd = 0; + m_pYZWnd = 0; + m_pXZWnd = 0; + m_pActiveXY = 0; + + for (int n = 0;n < c_count_status;n++) + { + m_pStatusLabel[n] = 0; + } + + m_bSleeping = false; + + Create(); +} + +MainFrame::~MainFrame() +{ + SaveWindowInfo(); + + gtk_widget_hide(GTK_WIDGET(m_window)); + + Shutdown(); + + for(std::vector::iterator i = g_floating_windows.begin(); i != g_floating_windows.end(); ++i) + { + gtk_widget_destroy(*i); + } + + gtk_widget_destroy(GTK_WIDGET(m_window)); +} + +void MainFrame::SetActiveXY(XYWnd* p) +{ + if (m_pActiveXY) + m_pActiveXY->SetActive(false); + + m_pActiveXY = p; + + if (m_pActiveXY) + m_pActiveXY->SetActive(true); + +} + +void MainFrame::ReleaseContexts() +{ +#if 0 + if (m_pXYWnd) + m_pXYWnd->DestroyContext(); + if (m_pYZWnd) + m_pYZWnd->DestroyContext(); + if (m_pXZWnd) + m_pXZWnd->DestroyContext(); + if (m_pCamWnd) + m_pCamWnd->DestroyContext(); + if (m_pTexWnd) + m_pTexWnd->DestroyContext(); + if (m_pZWnd) + m_pZWnd->DestroyContext(); +#endif +} + +void MainFrame::CreateContexts() +{ +#if 0 + if (m_pCamWnd) + m_pCamWnd->CreateContext(); + if (m_pXYWnd) + m_pXYWnd->CreateContext(); + if (m_pYZWnd) + m_pYZWnd->CreateContext(); + if (m_pXZWnd) + m_pXZWnd->CreateContext(); + if (m_pTexWnd) + m_pTexWnd->CreateContext(); + if (m_pZWnd) + m_pZWnd->CreateContext(); +#endif +} + +#ifdef _DEBUG +//#define DBG_SLEEP +#endif + +void MainFrame::OnSleep() +{ +#if 0 + m_bSleeping ^= 1; + if (m_bSleeping) + { + // useful when trying to debug crashes in the sleep code + globalOutputStream() << "Going into sleep mode..\n"; + + globalOutputStream() << "Dispatching sleep msg..."; + DispatchRadiantMsg (RADIANT_SLEEP); + globalOutputStream() << "Done.\n"; + + gtk_window_iconify(m_window); + GlobalSelectionSystem().setSelectedAll(false); + + GlobalShaderCache().unrealise(); + Shaders_Free(); + GlobalOpenGL_debugAssertNoErrors(); + ScreenUpdates_Disable(); + + // release contexts + globalOutputStream() << "Releasing contexts..."; + ReleaseContexts(); + globalOutputStream() << "Done.\n"; + } + else + { + globalOutputStream() << "Waking up\n"; + + gtk_window_deiconify(m_window); + + // create contexts + globalOutputStream() << "Creating contexts..."; + CreateContexts(); + globalOutputStream() << "Done.\n"; + + globalOutputStream() << "Making current on camera..."; + m_pCamWnd->MakeCurrent(); + globalOutputStream() << "Done.\n"; + + globalOutputStream() << "Reloading shaders..."; + Shaders_Load(); + GlobalShaderCache().realise(); + globalOutputStream() << "Done.\n"; + + ScreenUpdates_Enable(); + + globalOutputStream() << "Dispatching wake msg..."; + DispatchRadiantMsg (RADIANT_WAKEUP); + globalOutputStream() << "Done\n"; + } +#endif +} + + +GtkWindow* create_splash() +{ + GtkWindow* window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL)); + gtk_window_set_decorated(window, FALSE); + gtk_window_set_resizable(window, FALSE); + gtk_window_set_modal(window, TRUE); + gtk_window_set_default_size(window, -1, -1); + gtk_window_set_position(window, GTK_WIN_POS_CENTER); + gtk_container_set_border_width(GTK_CONTAINER(window), 0); + + GtkImage* image = new_local_image("splash.bmp"); + gtk_widget_show(GTK_WIDGET(image)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(image)); + + gtk_widget_set_size_request(GTK_WIDGET(window), -1, -1); + gtk_widget_show(GTK_WIDGET(window)); + + return window; +} + +static GtkWindow *splash_screen = 0; + +void show_splash() +{ + splash_screen = create_splash(); + + process_gui(); +} + +void hide_splash() +{ + gtk_widget_destroy(GTK_WIDGET(splash_screen)); +} + +WindowPositionTracker g_posCamWnd; +WindowPositionTracker g_posXYWnd; +WindowPositionTracker g_posXZWnd; +WindowPositionTracker g_posYZWnd; + +static gint mainframe_delete (GtkWidget *widget, GdkEvent *event, gpointer data) +{ + if(ConfirmModified("Exit Radiant")) + { + gtk_main_quit(); + } + + return TRUE; +} + +void MainFrame::Create() +{ + GtkWindow* window = GTK_WINDOW(gtk_window_new(GTK_WINDOW_TOPLEVEL)); + + GlobalWindowObservers_connectTopLevel(window); + + gtk_window_set_transient_for(splash_screen, window); + +#if !defined(WIN32) + { + GdkPixbuf* pixbuf = pixbuf_new_from_file_with_mask("bitmaps/icon.bmp"); + if(pixbuf != 0) + { + gtk_window_set_icon(window, pixbuf); + gdk_pixbuf_unref(pixbuf); + } + } +#endif + + gtk_widget_add_events(GTK_WIDGET(window), GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK | GDK_FOCUS_CHANGE_MASK); + g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(mainframe_delete), this); + + m_position_tracker.connect(window); + +#if 0 + g_mainframeWidgetFocusPrinter.connect(window); + g_mainframeFocusPrinter.connect(window); +#endif + + g_MainWindowActive.connect(window); + + GetPlugInMgr().Init(GTK_WIDGET(window)); + + GtkWidget* vbox = gtk_vbox_new (FALSE, 0); + gtk_container_add(GTK_CONTAINER(window), vbox); + gtk_widget_show(vbox); + + global_accel_connect_window(window); + + m_nCurrentStyle = (EViewStyle)g_Layout_viewStyle.m_value; + + register_shortcuts(); + + GtkMenuBar* main_menu = create_main_menu(CurrentStyle()); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(main_menu), FALSE, FALSE, 0); + + GtkToolbar* main_toolbar = create_main_toolbar(CurrentStyle()); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(main_toolbar), FALSE, FALSE, 0); + + GtkToolbar* plugin_toolbar = create_plugin_toolbar(); + if (!g_Layout_enablePluginToolbar.m_value) + { + gtk_widget_hide(GTK_WIDGET(plugin_toolbar)); + } + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(plugin_toolbar), FALSE, FALSE, 0); + + GtkWidget* main_statusbar = create_main_statusbar(m_pStatusLabel); + gtk_box_pack_end(GTK_BOX(vbox), main_statusbar, FALSE, TRUE, 2); + + GroupDialog_constructWindow(window); + g_page_entity = GroupDialog_addPage("Entities", EntityInspector_constructWindow(GroupDialog_getWindow()), RawStringExportCaller("Entities")); + + if(FloatingGroupDialog()) + { + g_page_console = GroupDialog_addPage("Console", Console_constructWindow(GroupDialog_getWindow()), RawStringExportCaller("Console")); + } + +#ifdef WIN32 + if( g_multimon_globals.m_bStartOnPrimMon ) + { + PositionWindowOnPrimaryScreen(g_layout_globals.m_position); + window_set_position(window, g_layout_globals.m_position); + } + else +#endif + if(g_layout_globals.nState & GDK_WINDOW_STATE_MAXIMIZED) + { + gtk_window_maximize(window); + WindowPosition default_position(-1, -1, 640, 480); + window_set_position(window, default_position); + } + else + { + window_set_position(window, g_layout_globals.m_position); + } + + m_window = window; + + gtk_widget_show(GTK_WIDGET(window)); + + if (CurrentStyle() == eRegular || CurrentStyle() == eRegularLeft) + { + { + GtkWidget* vsplit = gtk_vpaned_new(); + m_vSplit = vsplit; + gtk_box_pack_start(GTK_BOX(vbox), vsplit, TRUE, TRUE, 0); + gtk_widget_show (vsplit); + + // console + GtkWidget* console_window = Console_constructWindow(window); + gtk_paned_pack2(GTK_PANED(vsplit), console_window, FALSE, TRUE); + + { + GtkWidget* hsplit = gtk_hpaned_new(); + gtk_widget_show (hsplit); + m_hSplit = hsplit; + gtk_paned_add1(GTK_PANED(vsplit), hsplit); + + // xy + m_pXYWnd = new XYWnd(); + m_pXYWnd->SetViewType(XY); + GtkWidget* xy_window = GTK_WIDGET(create_framed_widget(m_pXYWnd->GetWidget())); + + { + GtkWidget* vsplit2 = gtk_vpaned_new(); + gtk_widget_show(vsplit2); + m_vSplit2 = vsplit2; + + if (CurrentStyle() == eRegular) + { + gtk_paned_add1(GTK_PANED(hsplit), xy_window); + gtk_paned_add2(GTK_PANED(hsplit), vsplit2); + } + else + { + gtk_paned_add1(GTK_PANED(hsplit), vsplit2); + gtk_paned_add2(GTK_PANED(hsplit), xy_window); + } + + + // camera + m_pCamWnd = NewCamWnd(); + GlobalCamera_setCamWnd(*m_pCamWnd); + CamWnd_setParent(*m_pCamWnd, window); + GtkFrame* camera_window = create_framed_widget(CamWnd_getWidget(*m_pCamWnd)); + + gtk_paned_add1(GTK_PANED(vsplit2), GTK_WIDGET(camera_window)); + + // textures + GtkFrame* texture_window = create_framed_widget(TextureBrowser_constructWindow(window)); + + gtk_paned_add2(GTK_PANED(vsplit2), GTK_WIDGET(texture_window)); + } + } + } + + gtk_paned_set_position(GTK_PANED(m_vSplit), g_layout_globals.nXYHeight); + + if (CurrentStyle() == eRegular) + { + gtk_paned_set_position(GTK_PANED(m_hSplit), g_layout_globals.nXYWidth); + } + else + { + gtk_paned_set_position(GTK_PANED(m_hSplit), g_layout_globals.nCamWidth); + } + + gtk_paned_set_position(GTK_PANED(m_vSplit2), g_layout_globals.nCamHeight); + } + else if (CurrentStyle() == eFloating) + { + { + GtkWindow* window = create_persistent_floating_window("Camera", m_window); + global_accel_connect_window(window); + g_posCamWnd.connect(window); + + gtk_widget_show(GTK_WIDGET(window)); + + m_pCamWnd = NewCamWnd(); + GlobalCamera_setCamWnd(*m_pCamWnd); + + { + GtkFrame* frame = create_framed_widget(CamWnd_getWidget(*m_pCamWnd)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); + } + CamWnd_setParent(*m_pCamWnd, window); + + g_floating_windows.push_back(GTK_WIDGET(window)); + } + + { + GtkWindow* window = create_persistent_floating_window(ViewType_getTitle(XY), m_window); + global_accel_connect_window(window); + g_posXYWnd.connect(window); + + m_pXYWnd = new XYWnd(); + m_pXYWnd->m_parent = window; + m_pXYWnd->SetViewType(XY); + + + { + GtkFrame* frame = create_framed_widget(m_pXYWnd->GetWidget()); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); + } + XY_Top_Shown_Construct(window); + + g_floating_windows.push_back(GTK_WIDGET(window)); + } + + { + GtkWindow* window = create_persistent_floating_window(ViewType_getTitle(XZ), m_window); + global_accel_connect_window(window); + g_posXZWnd.connect(window); + + m_pXZWnd = new XYWnd(); + m_pXZWnd->m_parent = window; + m_pXZWnd->SetViewType(XZ); + + { + GtkFrame* frame = create_framed_widget(m_pXZWnd->GetWidget()); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); + } + + XZ_Front_Shown_Construct(window); + + g_floating_windows.push_back(GTK_WIDGET(window)); + } + + { + GtkWindow* window = create_persistent_floating_window(ViewType_getTitle(YZ), m_window); + global_accel_connect_window(window); + g_posYZWnd.connect(window); + + m_pYZWnd = new XYWnd(); + m_pYZWnd->m_parent = window; + m_pYZWnd->SetViewType(YZ); + + { + GtkFrame* frame = create_framed_widget(m_pYZWnd->GetWidget()); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(frame)); + } + + YZ_Side_Shown_Construct(window); + + g_floating_windows.push_back(GTK_WIDGET(window)); + } + + { + GtkFrame* frame = create_framed_widget(TextureBrowser_constructWindow(GroupDialog_getWindow())); + g_page_textures = GroupDialog_addPage("Textures", GTK_WIDGET(frame), TextureBrowserExportTitleCaller()); + } + + GroupDialog_show(); + } + else // 4 way + { + m_pCamWnd = NewCamWnd(); + GlobalCamera_setCamWnd(*m_pCamWnd); + CamWnd_setParent(*m_pCamWnd, window); + + GtkWidget* camera = CamWnd_getWidget(*m_pCamWnd); + + m_pYZWnd = new XYWnd(); + m_pYZWnd->SetViewType(YZ); + + GtkWidget* yz = m_pYZWnd->GetWidget(); + + m_pXYWnd = new XYWnd(); + m_pXYWnd->SetViewType(XY); + + GtkWidget* xy = m_pXYWnd->GetWidget(); + + m_pXZWnd = new XYWnd(); + m_pXZWnd->SetViewType(XZ); + + GtkWidget* xz = m_pXZWnd->GetWidget(); + + GtkHPaned* split = create_split_views(camera, yz, xy, xz); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(split), TRUE, TRUE, 0); + + { + GtkFrame* frame = create_framed_widget(TextureBrowser_constructWindow(window)); + g_page_textures = GroupDialog_addPage("Textures", GTK_WIDGET(frame), TextureBrowserExportTitleCaller()); + } + } + + EntityList_constructWindow(window); + PreferencesDialog_constructWindow(window); + FindTextureDialog_constructWindow(window); + SurfaceInspector_constructWindow(window); + PatchInspector_constructWindow(window); + + SetActiveXY(m_pXYWnd); + + AddGridChangeCallback(SetGridStatusCaller(*this)); + AddGridChangeCallback(ReferenceCaller(*this)); + + g_defaultToolMode = DragMode; + g_defaultToolMode(); + SetStatusText(m_command_status, c_TranslateMode_status); + + EverySecondTimer_enable(); + + //GlobalShortcuts_reportUnregistered(); +} + +void MainFrame::SaveWindowInfo() +{ + if (!FloatingGroupDialog()) + { + g_layout_globals.nXYHeight = gtk_paned_get_position(GTK_PANED(m_vSplit)); + + if(CurrentStyle() != eRegular) + { + g_layout_globals.nCamWidth = gtk_paned_get_position(GTK_PANED(m_hSplit)); + } + else + { + g_layout_globals.nXYWidth = gtk_paned_get_position(GTK_PANED(m_hSplit)); + } + + g_layout_globals.nCamHeight = gtk_paned_get_position(GTK_PANED(m_vSplit2)); + } + + g_layout_globals.m_position = m_position_tracker.getPosition(); + + g_layout_globals.nState = gdk_window_get_state(GTK_WIDGET(m_window)->window); +} + +void MainFrame::Shutdown() +{ + EverySecondTimer_disable(); + + EntityList_destroyWindow(); + + delete m_pXYWnd; + m_pXYWnd = 0; + delete m_pYZWnd; + m_pYZWnd = 0; + delete m_pXZWnd; + m_pXZWnd = 0; + + TextureBrowser_destroyWindow(); + + DeleteCamWnd(m_pCamWnd); + m_pCamWnd = 0; + + PreferencesDialog_destroyWindow(); + SurfaceInspector_destroyWindow(); + FindTextureDialog_destroyWindow(); + PatchInspector_destroyWindow(); + + g_DbgDlg.destroyWindow(); + + // destroying group-dialog last because it may contain texture-browser + GroupDialog_destroyWindow(); +} + +void MainFrame::RedrawStatusText() +{ + gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_command_status]), m_command_status.c_str()); + gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_position_status]), m_position_status.c_str()); + gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_brushcount_status]), m_brushcount_status.c_str()); + gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_texture_status]), m_texture_status.c_str()); + gtk_label_set_text(GTK_LABEL(m_pStatusLabel[c_grid_status]), m_grid_status.c_str()); +} + +void MainFrame::UpdateStatusText() +{ + m_idleRedrawStatusText.queueDraw(); +} + +void MainFrame::SetStatusText(CopiedString& status_text, const char* pText) +{ + status_text = pText; + UpdateStatusText(); +} + +void Sys_Status(const char* status) +{ + if(g_pParentWnd != 0) + { + g_pParentWnd->SetStatusText (g_pParentWnd->m_command_status, status); + } +} + +int getRotateIncrement() +{ + return static_cast(g_si_globals.rotate); +} + +int getFarClipDistance() +{ + return g_camwindow_globals.m_nCubicScale; +} + +float (*GridStatus_getGridSize)() = GetGridSize; +int (*GridStatus_getRotateIncrement)() = getRotateIncrement; +int (*GridStatus_getFarClipDistance)() = getFarClipDistance; +bool (*GridStatus_getTextureLockEnabled)(); + +void MainFrame::SetGridStatus() +{ + StringOutputStream status(64); + const char* lock = (GridStatus_getTextureLockEnabled()) ? "ON" : "OFF"; + status << (GetSnapGridSize() > 0 ? "G:" : "g:") << GridStatus_getGridSize() + << " R:" << GridStatus_getRotateIncrement() + << " C:" << GridStatus_getFarClipDistance() + << " L:" << lock; + SetStatusText(m_grid_status, status.c_str()); +} + +void GridStatus_onTextureLockEnabledChanged() +{ + if(g_pParentWnd != 0) + { + g_pParentWnd->SetGridStatus(); + } +} + +void GlobalGL_sharedContextCreated() +{ + GLFont *g_font = NULL; + + // report OpenGL information + globalOutputStream() << "GL_VENDOR: " << reinterpret_cast(glGetString (GL_VENDOR)) << "\n"; + globalOutputStream() << "GL_RENDERER: " << reinterpret_cast(glGetString (GL_RENDERER)) << "\n"; + globalOutputStream() << "GL_VERSION: " << reinterpret_cast(glGetString (GL_VERSION)) << "\n"; + globalOutputStream() << "GL_EXTENSIONS: " << reinterpret_cast(glGetString (GL_EXTENSIONS)) << "\n"; + + QGL_sharedContextCreated(GlobalOpenGL()); + + ShaderCache_extensionsInitialised(); + + GlobalShaderCache().realise(); + Textures_Realise(); + +#ifdef WIN32 + /* win32 is dodgy here, just use courier new then */ + g_font = glfont_create("arial 9"); +#else + GtkSettings *settings = gtk_settings_get_default(); + gchar *fontname; + g_object_get(settings, "gtk-font-name", &fontname, NULL); + g_font = glfont_create(fontname); +#endif + + GlobalOpenGL().m_font = g_font; +} + +void GlobalGL_sharedContextDestroyed() +{ + Textures_Unrealise(); + GlobalShaderCache().unrealise(); + + QGL_sharedContextDestroyed(GlobalOpenGL()); +} + + +void Layout_constructPreferences(PreferencesPage& page) +{ + { + const char* layouts[] = { "window1.bmp", "window2.bmp", "window3.bmp", "window4.bmp" }; + page.appendRadioIcons( + "Window Layout", + STRING_ARRAY_RANGE(layouts), + LatchedIntImportCaller(g_Layout_viewStyle), + IntExportCaller(g_Layout_viewStyle.m_latched) + ); + } + page.appendCheckBox( + "", "Detachable Menus", + LatchedBoolImportCaller(g_Layout_enableDetachableMenus), + BoolExportCaller(g_Layout_enableDetachableMenus.m_latched) + ); + if (!string_empty(g_pGameDescription->getKeyValue("no_patch"))) + { + page.appendCheckBox( + "", "Patch Toolbar", + LatchedBoolImportCaller(g_Layout_enablePatchToolbar), + BoolExportCaller(g_Layout_enablePatchToolbar.m_latched) + ); + } + page.appendCheckBox( + "", "Plugin Toolbar", + LatchedBoolImportCaller(g_Layout_enablePluginToolbar), + BoolExportCaller(g_Layout_enablePluginToolbar.m_latched) + ); +} + +void Layout_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Layout", "Layout Preferences")); + Layout_constructPreferences(page); +} + +void Layout_registerPreferencesPage() +{ + PreferencesDialog_addInterfacePage(FreeCaller1()); +} + + +#include "preferencesystem.h" +#include "stringio.h" + +void MainFrame_Construct() +{ + GlobalCommands_insert("OpenManual", FreeCaller(), Accelerator(GDK_F1)); + + GlobalCommands_insert("Sleep", FreeCaller(), Accelerator('P', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("NewMap", FreeCaller()); + GlobalCommands_insert("OpenMap", FreeCaller(), Accelerator('O', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("ImportMap", FreeCaller()); + GlobalCommands_insert("SaveMap", FreeCaller(), Accelerator('S', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("SaveMapAs", FreeCaller()); + GlobalCommands_insert("SaveSelected", FreeCaller()); + GlobalCommands_insert("SaveRegion", FreeCaller()); + GlobalCommands_insert("RefreshReferences", FreeCaller()); + GlobalCommands_insert("ProjectSettings", FreeCaller()); + GlobalCommands_insert("CheckForUpdate", FreeCaller()); + GlobalCommands_insert("Exit", FreeCaller()); + + GlobalCommands_insert("Undo", FreeCaller(), Accelerator('Z', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Redo", FreeCaller(), Accelerator('Y', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Copy", FreeCaller(), Accelerator('C', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("Paste", FreeCaller(), Accelerator('V', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("PasteToCamera", FreeCaller(), Accelerator('V', (GdkModifierType)GDK_MOD1_MASK)); + GlobalCommands_insert("CloneSelection", FreeCaller(), Accelerator(GDK_space)); + GlobalCommands_insert("CloneSelectionAndMakeUnique", FreeCaller(), Accelerator(GDK_space, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("DeleteSelection", FreeCaller(), Accelerator(GDK_BackSpace)); + GlobalCommands_insert("ParentSelection", FreeCaller()); + GlobalCommands_insert("UnSelectSelection", FreeCaller(), Accelerator(GDK_Escape)); + GlobalCommands_insert("InvertSelection", FreeCaller(), Accelerator('I')); + GlobalCommands_insert("SelectInside", FreeCaller()); + GlobalCommands_insert("SelectTouching", FreeCaller()); + GlobalCommands_insert("ExpandSelectionToEntities", FreeCaller(), Accelerator('E', (GdkModifierType)(GDK_MOD1_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("Preferences", FreeCaller(), Accelerator('P')); + + GlobalCommands_insert("ToggleConsole", FreeCaller(), Accelerator('O')); + GlobalCommands_insert("ToggleEntityInspector", FreeCaller(), Accelerator('N')); + GlobalCommands_insert("EntityList", FreeCaller(), Accelerator('L')); + + GlobalCommands_insert("ShowHidden", FreeCaller(), Accelerator('H', (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("HideSelected", FreeCaller(), Accelerator('H')); + + GlobalToggles_insert("DragVertices", FreeCaller(), ToggleItem::AddCallbackCaller(g_vertexMode_button), Accelerator('V')); + GlobalToggles_insert("DragEdges", FreeCaller(), ToggleItem::AddCallbackCaller(g_edgeMode_button), Accelerator('E')); + GlobalToggles_insert("DragFaces", FreeCaller(), ToggleItem::AddCallbackCaller(g_faceMode_button), Accelerator('F')); + + GlobalCommands_insert("MirrorSelectionX", FreeCaller()); + GlobalCommands_insert("RotateSelectionX", FreeCaller()); + GlobalCommands_insert("MirrorSelectionY", FreeCaller()); + GlobalCommands_insert("RotateSelectionY", FreeCaller()); + GlobalCommands_insert("MirrorSelectionZ", FreeCaller()); + GlobalCommands_insert("RotateSelectionZ", FreeCaller()); + + GlobalCommands_insert("ArbitraryRotation", FreeCaller()); + GlobalCommands_insert("ArbitraryScale", FreeCaller()); + + GlobalCommands_insert("BuildMenuCustomize", FreeCaller()); + + GlobalCommands_insert("FindBrush", FreeCaller()); + + GlobalCommands_insert("MapInfo", FreeCaller(), Accelerator('M')); + + + GlobalToggles_insert("ToggleClipper", FreeCaller(), ToggleItem::AddCallbackCaller(g_clipper_button), Accelerator('X')); + + GlobalToggles_insert("MouseTranslate", FreeCaller(), ToggleItem::AddCallbackCaller(g_translatemode_button), Accelerator('W')); + GlobalToggles_insert("MouseRotate", FreeCaller(), ToggleItem::AddCallbackCaller(g_rotatemode_button), Accelerator('R')); + GlobalToggles_insert("MouseScale", FreeCaller(), ToggleItem::AddCallbackCaller(g_scalemode_button)); + GlobalToggles_insert("MouseDrag", FreeCaller(), ToggleItem::AddCallbackCaller(g_dragmode_button), Accelerator('Q')); + + GlobalCommands_insert("ColorSchemeOriginal", FreeCaller()); + GlobalCommands_insert("ColorSchemeQER", FreeCaller()); + GlobalCommands_insert("ColorSchemeBlackAndGreen", FreeCaller()); + GlobalCommands_insert("ColorSchemeYdnar", FreeCaller()); + GlobalCommands_insert("ChooseTextureBackgroundColor", makeCallback(g_ColoursMenu.m_textureback)); + GlobalCommands_insert("ChooseGridBackgroundColor", makeCallback(g_ColoursMenu.m_xyback)); + GlobalCommands_insert("ChooseGridMajorColor", makeCallback(g_ColoursMenu.m_gridmajor)); + GlobalCommands_insert("ChooseGridMinorColor", makeCallback(g_ColoursMenu.m_gridminor)); + GlobalCommands_insert("ChooseSmallGridMajorColor", makeCallback(g_ColoursMenu.m_gridmajor_alt)); + GlobalCommands_insert("ChooseSmallGridMinorColor", makeCallback(g_ColoursMenu.m_gridminor_alt)); + GlobalCommands_insert("ChooseGridTextColor", makeCallback(g_ColoursMenu.m_gridtext)); + GlobalCommands_insert("ChooseGridBlockColor", makeCallback(g_ColoursMenu.m_gridblock)); + GlobalCommands_insert("ChooseBrushColor", makeCallback(g_ColoursMenu.m_brush)); + GlobalCommands_insert("ChooseCameraBackgroundColor", makeCallback(g_ColoursMenu.m_cameraback)); + GlobalCommands_insert("ChooseSelectedBrushColor", makeCallback(g_ColoursMenu.m_selectedbrush)); + GlobalCommands_insert("ChooseCameraSelectedBrushColor", makeCallback(g_ColoursMenu.m_selectedbrush3d)); + GlobalCommands_insert("ChooseClipperColor", makeCallback(g_ColoursMenu.m_clipper)); + GlobalCommands_insert("ChooseOrthoViewNameColor", makeCallback(g_ColoursMenu.m_viewname)); + + + GlobalCommands_insert("CSGSubtract", FreeCaller(), Accelerator('U', (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("CSGMerge", FreeCaller(), Accelerator('U', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("CSGHollow", FreeCaller()); + + Grid_registerCommands(); + + GlobalCommands_insert("SnapToGrid", FreeCaller(), Accelerator('G', (GdkModifierType)GDK_CONTROL_MASK)); + + GlobalCommands_insert("SelectAllOfType", FreeCaller(), Accelerator('A', (GdkModifierType)GDK_SHIFT_MASK)); + + GlobalCommands_insert("TexRotateClock", FreeCaller(), Accelerator(GDK_Next, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("TexRotateCounter", FreeCaller(), Accelerator(GDK_Prior, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("TexScaleUp", FreeCaller(), Accelerator(GDK_Up, (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("TexScaleDown", FreeCaller(), Accelerator(GDK_Down, (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("TexScaleLeft", FreeCaller(), Accelerator(GDK_Left, (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("TexScaleRight", FreeCaller(), Accelerator(GDK_Right, (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("TexShiftUp", FreeCaller(), Accelerator(GDK_Up, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("TexShiftDown", FreeCaller(), Accelerator(GDK_Down, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("TexShiftLeft", FreeCaller(), Accelerator(GDK_Left, (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("TexShiftRight", FreeCaller(), Accelerator(GDK_Right, (GdkModifierType)GDK_SHIFT_MASK)); + + GlobalCommands_insert("MoveSelectionDOWN", FreeCaller(), Accelerator(GDK_KP_Subtract)); + GlobalCommands_insert("MoveSelectionUP", FreeCaller(), Accelerator(GDK_KP_Add)); + + GlobalCommands_insert("SelectNudgeLeft", FreeCaller(), Accelerator(GDK_Left, (GdkModifierType)GDK_MOD1_MASK)); + GlobalCommands_insert("SelectNudgeRight", FreeCaller(), Accelerator(GDK_Right, (GdkModifierType)GDK_MOD1_MASK)); + GlobalCommands_insert("SelectNudgeUp", FreeCaller(), Accelerator(GDK_Up, (GdkModifierType)GDK_MOD1_MASK)); + GlobalCommands_insert("SelectNudgeDown", FreeCaller(), Accelerator(GDK_Down, (GdkModifierType)GDK_MOD1_MASK)); + + Patch_registerCommands(); + XYShow_registerCommands(); + + typedef FreeCaller1 ComponentModeSelectionChangedCaller; + GlobalSelectionSystem().addSelectionChangeCallback(ComponentModeSelectionChangedCaller()); + + GlobalPreferenceSystem().registerPreference("DetachableMenus", BoolImportStringCaller(g_Layout_enableDetachableMenus.m_latched), BoolExportStringCaller(g_Layout_enableDetachableMenus.m_latched)); + GlobalPreferenceSystem().registerPreference("PatchToolBar", BoolImportStringCaller(g_Layout_enablePatchToolbar.m_latched), BoolExportStringCaller(g_Layout_enablePatchToolbar.m_latched)); + GlobalPreferenceSystem().registerPreference("PluginToolBar", BoolImportStringCaller(g_Layout_enablePluginToolbar.m_latched), BoolExportStringCaller(g_Layout_enablePluginToolbar.m_latched)); + GlobalPreferenceSystem().registerPreference("QE4StyleWindows", IntImportStringCaller(g_Layout_viewStyle.m_latched), IntExportStringCaller(g_Layout_viewStyle.m_latched)); + GlobalPreferenceSystem().registerPreference("XYHeight", IntImportStringCaller(g_layout_globals.nXYHeight), IntExportStringCaller(g_layout_globals.nXYHeight)); + GlobalPreferenceSystem().registerPreference("XYWidth", IntImportStringCaller(g_layout_globals.nXYWidth), IntExportStringCaller(g_layout_globals.nXYWidth)); + GlobalPreferenceSystem().registerPreference("CamWidth", IntImportStringCaller(g_layout_globals.nCamWidth), IntExportStringCaller(g_layout_globals.nCamWidth)); + GlobalPreferenceSystem().registerPreference("CamHeight", IntImportStringCaller(g_layout_globals.nCamHeight), IntExportStringCaller(g_layout_globals.nCamHeight)); + + GlobalPreferenceSystem().registerPreference("State", IntImportStringCaller(g_layout_globals.nState), IntExportStringCaller(g_layout_globals.nState)); + GlobalPreferenceSystem().registerPreference("PositionX", IntImportStringCaller(g_layout_globals.m_position.x), IntExportStringCaller(g_layout_globals.m_position.x)); + GlobalPreferenceSystem().registerPreference("PositionY", IntImportStringCaller(g_layout_globals.m_position.y), IntExportStringCaller(g_layout_globals.m_position.y)); + GlobalPreferenceSystem().registerPreference("Width", IntImportStringCaller(g_layout_globals.m_position.w), IntExportStringCaller(g_layout_globals.m_position.w)); + GlobalPreferenceSystem().registerPreference("Height", IntImportStringCaller(g_layout_globals.m_position.h), IntExportStringCaller(g_layout_globals.m_position.h)); + + GlobalPreferenceSystem().registerPreference("CamWnd", WindowPositionTrackerImportStringCaller(g_posCamWnd), WindowPositionTrackerExportStringCaller(g_posCamWnd)); + GlobalPreferenceSystem().registerPreference("XYWnd", WindowPositionTrackerImportStringCaller(g_posXYWnd), WindowPositionTrackerExportStringCaller(g_posXYWnd)); + GlobalPreferenceSystem().registerPreference("YZWnd", WindowPositionTrackerImportStringCaller(g_posYZWnd), WindowPositionTrackerExportStringCaller(g_posYZWnd)); + GlobalPreferenceSystem().registerPreference("XZWnd", WindowPositionTrackerImportStringCaller(g_posXZWnd), WindowPositionTrackerExportStringCaller(g_posXZWnd)); + + { + const char* ENGINEPATH_ATTRIBUTE = +#if defined(WIN32) + "enginepath_win32" +#elif defined(__linux__) || defined (__FreeBSD__) + "enginepath_linux" +#elif defined(__APPLE__) + "enginepath_macos" +#else +#error "unknown platform" +#endif + ; + StringOutputStream path(256); + path << DirectoryCleaned(g_pGameDescription->getRequiredKeyValue(ENGINEPATH_ATTRIBUTE)); + g_strEnginePath = path.c_str(); + } + + GlobalPreferenceSystem().registerPreference("EnginePath", CopiedStringImportStringCaller(g_strEnginePath), CopiedStringExportStringCaller(g_strEnginePath)); + + g_Layout_viewStyle.useLatched(); + g_Layout_enableDetachableMenus.useLatched(); + g_Layout_enablePatchToolbar.useLatched(); + g_Layout_enablePluginToolbar.useLatched(); + + Layout_registerPreferencesPage(); + Paths_registerPreferencesPage(); + + g_brushCount.setCountChangedCallback(FreeCaller()); + g_entityCount.setCountChangedCallback(FreeCaller()); + GlobalEntityCreator().setCounter(&g_entityCount); + + GLWidget_sharedContextCreated = GlobalGL_sharedContextCreated; + GLWidget_sharedContextDestroyed = GlobalGL_sharedContextDestroyed; + + GlobalEntityClassManager().attach(g_WorldspawnColourEntityClassObserver); +} + +void MainFrame_Destroy() +{ + GlobalEntityClassManager().detach(g_WorldspawnColourEntityClassObserver); + + GlobalEntityCreator().setCounter(0); + g_entityCount.setCountChangedCallback(Callback()); + g_brushCount.setCountChangedCallback(Callback()); +} + + +void GLWindow_Construct() +{ + GlobalPreferenceSystem().registerPreference("MouseButtons", IntImportStringCaller(g_glwindow_globals.m_nMouseType), IntExportStringCaller(g_glwindow_globals.m_nMouseType)); +} + +void GLWindow_Destroy() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/mainframe.h b/misc/mediasource/netradiant-src/radiant/mainframe.h new file mode 100644 index 00000000..5997abd3 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/mainframe.h @@ -0,0 +1,286 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_MAINFRAME_H) +#define INCLUDED_MAINFRAME_H + +#include "gtkutil/window.h" +#include "gtkutil/idledraw.h" +#include "gtkutil/widget.h" +#include "string/string.h" + +#include "qerplugin.h" + +class IPlugIn; +class IToolbarButton; + +class XYWnd; +class CamWnd; +class ZWnd; + +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; + +const int c_command_status = 0; +const int c_position_status = 1; +const int c_brushcount_status = 2; +const int c_texture_status = 3; +const int c_grid_status = 4; +const int c_count_status = 5; + +class MainFrame +{ +public: + enum EViewStyle + { + eRegular = 0, + eFloating = 1, + eSplit = 2, + eRegularLeft = 3, + }; + + MainFrame(); + ~MainFrame(); + + GtkWindow* m_window; + + CopiedString m_command_status; + CopiedString m_position_status; + CopiedString m_brushcount_status; + CopiedString m_texture_status; + CopiedString m_grid_status; +private: + + void Create(); + void SaveWindowInfo(); + void Shutdown(); + + GtkWidget* m_vSplit; + GtkWidget* m_hSplit; + GtkWidget* m_vSplit2; + + XYWnd* m_pXYWnd; + XYWnd* m_pYZWnd; + XYWnd* m_pXZWnd; + CamWnd* m_pCamWnd; + ZWnd* m_pZWnd; + XYWnd* m_pActiveXY; + + bool m_bSleeping; + + GtkWidget *m_pStatusLabel[c_count_status]; + + + EViewStyle m_nCurrentStyle; + WindowPositionTracker m_position_tracker; + + IdleDraw m_idleRedrawStatusText; + +public: + + bool IsSleeping() + { + return m_bSleeping; + } + void OnSleep(); + + void SetStatusText(CopiedString& status_text, const char* pText); + void UpdateStatusText(); + void RedrawStatusText(); + typedef MemberCaller RedrawStatusTextCaller; + + void SetGridStatus(); + typedef MemberCaller SetGridStatusCaller; + + void SetActiveXY(XYWnd* p); + XYWnd* ActiveXY() + { + return m_pActiveXY; + }; + XYWnd* GetXYWnd() + { + return m_pXYWnd; + } + XYWnd* GetXZWnd() + { + return m_pXZWnd; + } + XYWnd* GetYZWnd() + { + return m_pYZWnd; + } + ZWnd* GetZWnd() + { + return m_pZWnd; + } + CamWnd* GetCamWnd() + { + return m_pCamWnd; + } + + void ReleaseContexts(); + void CreateContexts(); + + EViewStyle CurrentStyle() + { + return m_nCurrentStyle; + }; + bool FloatingGroupDialog() + { + return CurrentStyle() == eFloating || CurrentStyle() == eSplit; + }; +}; + +extern MainFrame* g_pParentWnd; + +GtkWindow* MainFrame_getWindow(); + +enum EMouseButtonMode +{ + ETwoButton = 0, + EThreeButton = 1, +}; + +struct glwindow_globals_t +{ + int m_nMouseType; + + glwindow_globals_t() : + m_nMouseType(EThreeButton) + { + } +}; + +void GLWindow_Construct(); +void GLWindow_Destroy(); + +extern glwindow_globals_t g_glwindow_globals; +template +class LatchedValue; +typedef LatchedValue LatchedBool; +extern LatchedBool g_Layout_enableDetachableMenus; + +void deleteSelection(); + + +void Sys_Status(const char* status); + + +void ScreenUpdates_Disable(const char* message, const char* title); +void ScreenUpdates_Enable(); +bool ScreenUpdates_Enabled(); +void ScreenUpdates_process(); + +class ScopeDisableScreenUpdates +{ +public: + ScopeDisableScreenUpdates(const char* message, const char* title) + { + ScreenUpdates_Disable(message, title); + } + ~ScopeDisableScreenUpdates() + { + ScreenUpdates_Enable(); + } +}; + + +void EnginePath_Realise(); +void EnginePath_Unrealise(); + +class ModuleObserver; + +void Radiant_attachEnginePathObserver(ModuleObserver& observer); +void Radiant_detachEnginePathObserver(ModuleObserver& observer); + +void Radiant_attachGameToolsPathObserver(ModuleObserver& observer); +void Radiant_detachGameToolsPathObserver(ModuleObserver& observer); + +extern CopiedString g_strEnginePath; +void EnginePath_verify(); +const char* EnginePath_get(); +const char* QERApp_GetGamePath(); + +extern CopiedString g_strAppPath; +const char* AppPath_get(); + +extern CopiedString g_strSettingsPath; +const char* SettingsPath_get(); + +const char* LocalRcPath_get(void); + +const char* const g_pluginsDir = "plugins/"; ///< name of plugins directory, always sub-directory of toolspath +const char* const g_modulesDir = "modules/"; ///< name of modules directory, always sub-directory of toolspath + +extern CopiedString g_strGameToolsPath; +const char* GameToolsPath_get(); + +void Radiant_Initialise(); +void Radiant_Shutdown(); + +void SaveMapAs(); + + +void XY_UpdateAllWindows(); +void UpdateAllWindows(); + + +void ClipperChangeNotify(); + +void DefaultMode(); + +const char* basegame_get(); +const char* gamename_get(); +void gamename_set(const char* gamename); +void Radiant_attachGameNameObserver(ModuleObserver& observer); +void Radiant_detachGameNameObserver(ModuleObserver& observer); +const char* gamemode_get(); +void gamemode_set(const char* gamemode); +void Radiant_attachGameModeObserver(ModuleObserver& observer); +void Radiant_detachGameModeObserver(ModuleObserver& observer); + + + +void VFS_Construct(); +void VFS_Destroy(); + +void HomePaths_Construct(); +void HomePaths_Destroy(); +void Radiant_attachHomePathsObserver(ModuleObserver& observer); +void Radiant_detachHomePathsObserver(ModuleObserver& observer); + + +void MainFrame_Construct(); +void MainFrame_Destroy(); + + +extern float (*GridStatus_getGridSize)(); +extern int (*GridStatus_getRotateIncrement)(); +extern int (*GridStatus_getFarClipDistance)(); +extern bool (*GridStatus_getTextureLockEnabled)(); +void GridStatus_onTextureLockEnabledChanged(); + +SignalHandlerId XYWindowDestroyed_connect(const SignalHandler& handler); +void XYWindowDestroyed_disconnect(SignalHandlerId id); +MouseEventHandlerId XYWindowMouseDown_connect(const MouseEventHandler& handler); +void XYWindowMouseDown_disconnect(MouseEventHandlerId id); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/map.cpp b/misc/mediasource/netradiant-src/radiant/map.cpp new file mode 100644 index 00000000..57245990 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/map.cpp @@ -0,0 +1,2415 @@ +/* +Copyright (C) 1999-2006 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 "map.h" + +#include "debugging/debugging.h" + +#include "imap.h" +MapModules& ReferenceAPI_getMapModules(); +#include "iselection.h" +#include "iundo.h" +#include "ibrush.h" +#include "ifilter.h" +#include "ireference.h" +#include "ifiletypes.h" +#include "ieclass.h" +#include "irender.h" +#include "ientity.h" +#include "editable.h" +#include "ifilesystem.h" +#include "namespace.h" +#include "moduleobserver.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "scenelib.h" +#include "transformlib.h" +#include "selectionlib.h" +#include "instancelib.h" +#include "traverselib.h" +#include "maplib.h" +#include "eclasslib.h" +#include "cmdlib.h" +#include "stream/textfilestream.h" +#include "os/path.h" +#include "uniquenames.h" +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" +#include "stream/stringstream.h" +#include "signal/signal.h" + +#include "gtkutil/filechooser.h" +#include "timer.h" +#include "select.h" +#include "plugin.h" +#include "filetypes.h" +#include "gtkdlgs.h" +#include "entityinspector.h" +#include "points.h" +#include "qe3.h" +#include "camwindow.h" +#include "xywindow.h" +#include "mainframe.h" +#include "preferences.h" +#include "referencecache.h" +#include "mru.h" +#include "commands.h" +#include "autosave.h" +#include "brushmodule.h" +#include "brush.h" + +class NameObserver +{ + UniqueNames& m_names; + CopiedString m_name; + + void construct() + { + if(!empty()) + { + //globalOutputStream() << "construct " << makeQuoted(c_str()) << "\n"; + m_names.insert(name_read(c_str())); + } + } + void destroy() + { + if(!empty()) + { + //globalOutputStream() << "destroy " << makeQuoted(c_str()) << "\n"; + m_names.erase(name_read(c_str())); + } + } + + NameObserver& operator=(const NameObserver& other); +public: + NameObserver(UniqueNames& names) : m_names(names) + { + construct(); + } + NameObserver(const NameObserver& other) : m_names(other.m_names), m_name(other.m_name) + { + construct(); + } + ~NameObserver() + { + destroy(); + } + bool empty() const + { + return string_empty(c_str()); + } + const char* c_str() const + { + return m_name.c_str(); + } + void nameChanged(const char* name) + { + destroy(); + m_name = name; + construct(); + } + typedef MemberCaller1 NameChangedCaller; +}; + +class BasicNamespace : public Namespace +{ + typedef std::map Names; + Names m_names; + UniqueNames m_uniqueNames; +public: + ~BasicNamespace() + { + ASSERT_MESSAGE(m_names.empty(), "namespace: names still registered at shutdown"); + } + void attach(const NameCallback& setName, const NameCallbackCallback& attachObserver) + { + std::pair result = m_names.insert(Names::value_type(setName, m_uniqueNames)); + ASSERT_MESSAGE(result.second, "cannot attach name"); + attachObserver(NameObserver::NameChangedCaller((*result.first).second)); + //globalOutputStream() << "attach: " << reinterpret_cast(setName) << "\n"; + } + void detach(const NameCallback& setName, const NameCallbackCallback& detachObserver) + { + Names::iterator i = m_names.find(setName); + ASSERT_MESSAGE(i != m_names.end(), "cannot detach name"); + //globalOutputStream() << "detach: " << reinterpret_cast(setName) << "\n"; + detachObserver(NameObserver::NameChangedCaller((*i).second)); + m_names.erase(i); + } + + void makeUnique(const char* name, const NameCallback& setName) const + { + char buffer[1024]; + name_write(buffer, m_uniqueNames.make_unique(name_read(name))); + setName(buffer); + } + + void mergeNames(const BasicNamespace& other) const + { + typedef std::list SetNameCallbacks; + typedef std::map NameGroups; + NameGroups groups; + + UniqueNames uniqueNames(other.m_uniqueNames); + + for(Names::const_iterator i = m_names.begin(); i != m_names.end(); ++i) + { + groups[(*i).second.c_str()].push_back((*i).first); + } + + for(NameGroups::iterator i = groups.begin(); i != groups.end(); ++i) + { + name_t uniqueName(uniqueNames.make_unique(name_read((*i).first.c_str()))); + uniqueNames.insert(uniqueName); + + char buffer[1024]; + name_write(buffer, uniqueName); + + //globalOutputStream() << "renaming " << makeQuoted((*i).first.c_str()) << " to " << makeQuoted(buffer) << "\n"; + + SetNameCallbacks& setNameCallbacks = (*i).second; + + for(SetNameCallbacks::const_iterator j = setNameCallbacks.begin(); j != setNameCallbacks.end(); ++j) + { + (*j)(buffer); + } + } + } +}; + +BasicNamespace g_defaultNamespace; +BasicNamespace g_cloneNamespace; + +class NamespaceAPI +{ + Namespace* m_namespace; +public: + typedef Namespace Type; + STRING_CONSTANT(Name, "*"); + + NamespaceAPI() + { + m_namespace = &g_defaultNamespace; + } + Namespace* getTable() + { + return m_namespace; + } +}; + +typedef SingletonModule NamespaceModule; +typedef Static StaticNamespaceModule; +StaticRegisterModule staticRegisterDefaultNamespace(StaticNamespaceModule::instance()); + + +std::list g_cloned; + +inline Namespaced* Node_getNamespaced(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +void Node_gatherNamespaced(scene::Node& node) +{ + Namespaced* namespaced = Node_getNamespaced(node); + if(namespaced != 0) + { + g_cloned.push_back(namespaced); + } +} + +class GatherNamespaced : public scene::Traversable::Walker +{ +public: + bool pre(scene::Node& node) const + { + Node_gatherNamespaced(node); + return true; + } +}; + +void Map_gatherNamespaced(scene::Node& root) +{ + Node_traverseSubgraph(root, GatherNamespaced()); +} + +void Map_mergeClonedNames() +{ + for(std::list::const_iterator i = g_cloned.begin(); i != g_cloned.end(); ++i) + { + (*i)->setNamespace(g_cloneNamespace); + } + g_cloneNamespace.mergeNames(g_defaultNamespace); + for(std::list::const_iterator i = g_cloned.begin(); i != g_cloned.end(); ++i) + { + (*i)->setNamespace(g_defaultNamespace); + } + + g_cloned.clear(); +} + +class WorldNode +{ + scene::Node* m_node; +public: + WorldNode() + : m_node(0) + { + } + void set(scene::Node* node) + { + if(m_node != 0) + m_node->DecRef(); + m_node = node; + if(m_node != 0) + m_node->IncRef(); + } + scene::Node* get() const + { + return m_node; + } +}; + +class Map; +void Map_SetValid(Map& map, bool valid); +void Map_UpdateTitle(const Map& map); +void Map_SetWorldspawn(Map& map, scene::Node* node); + + +class Map : public ModuleObserver +{ +public: + CopiedString m_name; + Resource* m_resource; + bool m_valid; + + bool m_modified; + void (*m_modified_changed)(const Map&); + + Signal0 m_mapValidCallbacks; + + WorldNode m_world_node; // "classname" "worldspawn" ! + + Map() : m_resource(0), m_valid(false), m_modified_changed(Map_UpdateTitle) + { + } + + void realise() + { + if(m_resource != 0) + { + if(Map_Unnamed(*this)) + { + g_map.m_resource->setNode(NewMapRoot("").get_pointer()); + MapFile* map = Node_getMapFile(*g_map.m_resource->getNode()); + if(map != 0) + { + map->save(); + } + } + else + { + m_resource->load(); + } + + GlobalSceneGraph().insert_root(*m_resource->getNode()); + + AutoSave_clear(); + + Map_SetValid(g_map, true); + } + } + void unrealise() + { + if(m_resource != 0) + { + Map_SetValid(g_map, false); + Map_SetWorldspawn(g_map, 0); + + + GlobalUndoSystem().clear(); + + GlobalSceneGraph().erase_root(); + } + } +}; + +Map g_map; +Map* g_currentMap = 0; + +void Map_addValidCallback(Map& map, const SignalHandler& handler) +{ + map.m_mapValidCallbacks.connectLast(handler); +} + +bool Map_Valid(const Map& map) +{ + return map.m_valid; +} + +void Map_SetValid(Map& map, bool valid) +{ + map.m_valid = valid; + map.m_mapValidCallbacks(); +} + + +const char* Map_Name(const Map& map) +{ + return map.m_name.c_str(); +} + +bool Map_Unnamed(const Map& map) +{ + return string_equal(Map_Name(map), "unnamed.map"); +} + +inline const MapFormat& MapFormat_forFile(const char* filename) +{ + const char* moduleName = findModuleName(GetFileTypeRegistry(), MapFormat::Name(), path_get_extension(filename)); + MapFormat* format = Radiant_getMapModules().findModule(moduleName); + ASSERT_MESSAGE(format != 0, "map format not found for file " << makeQuoted(filename)); + return *format; +} + +const MapFormat& Map_getFormat(const Map& map) +{ + return MapFormat_forFile(Map_Name(map)); +} + + +bool Map_Modified(const Map& map) +{ + return map.m_modified; +} + +void Map_SetModified(Map& map, bool modified) +{ + if(map.m_modified ^ modified) + { + map.m_modified = modified; + + map.m_modified_changed(map); + } +} + +void Map_UpdateTitle(const Map& map) +{ + Sys_SetTitle(map.m_name.c_str(), Map_Modified(map)); +} + + + +scene::Node* Map_GetWorldspawn(const Map& map) +{ + return map.m_world_node.get(); +} + +void Map_SetWorldspawn(Map& map, scene::Node* node) +{ + map.m_world_node.set(node); +} + + +// TTimo +// need that in a variable, will have to tweak depending on the game +float g_MaxWorldCoord = 64*1024; +float g_MinWorldCoord = -64*1024; + +void AddRegionBrushes (void); +void RemoveRegionBrushes (void); + + +/* +================ +Map_Free +free all map elements, reinitialize the structures that depend on them +================ +*/ +void Map_Free() +{ + Pointfile_Clear(); + + g_map.m_resource->detach(g_map); + GlobalReferenceCache().release(g_map.m_name.c_str()); + g_map.m_resource = 0; + + FlushReferences(); + + g_currentMap = 0; + Brush_unlatchPreferences(); +} + +class EntityFindByClassname : public scene::Graph::Walker +{ + const char* m_name; + Entity*& m_entity; +public: + EntityFindByClassname(const char* name, Entity*& entity) : m_name(name), m_entity(entity) + { + m_entity = 0; + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(m_entity == 0) + { + Entity* entity = Node_getEntity(path.top()); + if(entity != 0 + && string_equal(m_name, entity->getKeyValue("classname"))) + { + m_entity = entity; + } + } + return true; + } +}; + +Entity* Scene_FindEntityByClass(const char* name) +{ + Entity* entity; + GlobalSceneGraph().traverse(EntityFindByClassname(name, entity)); + return entity; +} + +Entity *Scene_FindPlayerStart() +{ + typedef const char* StaticString; + StaticString strings[] = { + "info_player_start", + "info_player_deathmatch", + "team_CTF_redplayer", + "team_CTF_blueplayer", + "team_CTF_redspawn", + "team_CTF_bluespawn", + }; + typedef const StaticString* StaticStringIterator; + for(StaticStringIterator i = strings, end = strings+(sizeof(strings)/sizeof(StaticString)); i != end; ++i) + { + Entity* entity = Scene_FindEntityByClass(*i); + if(entity != 0) + { + return entity; + } + } + return 0; +} + +// +// move the view to a start position +// + + +void FocusViews(const Vector3& point, float angle) +{ + CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); + Camera_setOrigin(camwnd, point); + Vector3 angles(Camera_getAngles(camwnd)); + angles[CAMERA_PITCH] = 0; + angles[CAMERA_YAW] = angle; + Camera_setAngles(camwnd, angles); + + XYWnd* xywnd = g_pParentWnd->GetXYWnd(); + xywnd->SetOrigin(point); +} + +#include "stringio.h" + +void Map_StartPosition() +{ + Entity* entity = Scene_FindPlayerStart(); + + if (entity) + { + Vector3 origin; + string_parse_vector3(entity->getKeyValue("origin"), origin); + FocusViews(origin, string_read_float(entity->getKeyValue("angle"))); + } + else + { + FocusViews(g_vector3_identity, 0); + } +} + + +inline bool node_is_worldspawn(scene::Node& node) +{ + Entity* entity = Node_getEntity(node); + return entity != 0 && string_equal(entity->getKeyValue("classname"), "worldspawn"); +} + + +// use first worldspawn +class entity_updateworldspawn : public scene::Traversable::Walker +{ +public: + bool pre(scene::Node& node) const + { + if(node_is_worldspawn(node)) + { + if(Map_GetWorldspawn(g_map) == 0) + { + Map_SetWorldspawn(g_map, &node); + } + } + return false; + } +}; + +scene::Node* Map_FindWorldspawn(Map& map) +{ + Map_SetWorldspawn(map, 0); + + Node_getTraversable(GlobalSceneGraph().root())->traverse(entity_updateworldspawn()); + + return Map_GetWorldspawn(map); +} + + +class CollectAllWalker : public scene::Traversable::Walker +{ + scene::Node& m_root; + UnsortedNodeSet& m_nodes; +public: + CollectAllWalker(scene::Node& root, UnsortedNodeSet& nodes) : m_root(root), m_nodes(nodes) + { + } + bool pre(scene::Node& node) const + { + m_nodes.insert(NodeSmartReference(node)); + Node_getTraversable(m_root)->erase(node); + return false; + } +}; + +void Node_insertChildFirst(scene::Node& parent, scene::Node& child) +{ + UnsortedNodeSet nodes; + Node_getTraversable(parent)->traverse(CollectAllWalker(parent, nodes)); + Node_getTraversable(parent)->insert(child); + + for(UnsortedNodeSet::iterator i = nodes.begin(); i != nodes.end(); ++i) + { + Node_getTraversable(parent)->insert((*i)); + } +} + +scene::Node& createWorldspawn() +{ + NodeSmartReference worldspawn(GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert("worldspawn", true))); + Node_insertChildFirst(GlobalSceneGraph().root(), worldspawn); + return worldspawn; +} + +void Map_UpdateWorldspawn(Map& map) +{ + if(Map_FindWorldspawn(map) == 0) + { + Map_SetWorldspawn(map, &createWorldspawn()); + } +} + +scene::Node& Map_FindOrInsertWorldspawn(Map& map) +{ + Map_UpdateWorldspawn(map); + return *Map_GetWorldspawn(map); +} + + +class MapMergeAll : public scene::Traversable::Walker +{ + mutable scene::Path m_path; +public: + MapMergeAll(const scene::Path& root) + : m_path(root) + { + } + bool pre(scene::Node& node) const + { + Node_getTraversable(m_path.top())->insert(node); + m_path.push(makeReference(node)); + selectPath(m_path, true); + return false; + } + void post(scene::Node& node) const + { + m_path.pop(); + } +}; + +class MapMergeEntities : public scene::Traversable::Walker +{ + mutable scene::Path m_path; +public: + MapMergeEntities(const scene::Path& root) + : m_path(root) + { + } + bool pre(scene::Node& node) const + { + if(node_is_worldspawn(node)) + { + scene::Node* world_node = Map_FindWorldspawn(g_map); + if(world_node == 0) + { + Map_SetWorldspawn(g_map, &node); + Node_getTraversable(m_path.top().get())->insert(node); + m_path.push(makeReference(node)); + Node_getTraversable(node)->traverse(SelectChildren(m_path)); + } + else + { + m_path.push(makeReference(*world_node)); + Node_getTraversable(node)->traverse(MapMergeAll(m_path)); + } + } + else + { + Node_getTraversable(m_path.top())->insert(node); + m_path.push(makeReference(node)); + if(node_is_group(node)) + { + Node_getTraversable(node)->traverse(SelectChildren(m_path)); + } + else + { + selectPath(m_path, true); + } + } + return false; + } + void post(scene::Node& node) const + { + m_path.pop(); + } +}; + +class BasicContainer : public scene::Node::Symbiot +{ + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts() + { + NodeContainedCast::install(m_casts); + } + NodeTypeCastTable& get() + { + return m_casts; + } + }; + + scene::Node m_node; + TraversableNodeSet m_traverse; +public: + + typedef LazyStatic StaticTypeCasts; + + scene::Traversable& get(NullType) + { + return m_traverse; + } + + BasicContainer() : m_node(this, this, StaticTypeCasts::instance().get()) + { + } + void release() + { + delete this; + } + scene::Node& node() + { + return m_node; + } +}; + +/// Merges the map graph rooted at \p node into the global scene-graph. +void MergeMap(scene::Node& node) +{ + Node_getTraversable(node)->traverse(MapMergeEntities(scene::Path(makeReference(GlobalSceneGraph().root())))); +} +void Map_ImportSelected(TextInputStream& in, const MapFormat& format) +{ + NodeSmartReference node((new BasicContainer)->node()); + format.readGraph(node, in, GlobalEntityCreator()); + Map_gatherNamespaced(node); + Map_mergeClonedNames(); + MergeMap(node); +} + +inline scene::Cloneable* Node_getCloneable(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +inline scene::Node& node_clone(scene::Node& node) +{ + scene::Cloneable* cloneable = Node_getCloneable(node); + if(cloneable != 0) + { + return cloneable->clone(); + } + + return (new scene::NullNode)->node(); +} + +class CloneAll : public scene::Traversable::Walker +{ + mutable scene::Path m_path; +public: + CloneAll(scene::Node& root) + : m_path(makeReference(root)) + { + } + bool pre(scene::Node& node) const + { + if(node.isRoot()) + { + return false; + } + + m_path.push(makeReference(node_clone(node))); + m_path.top().get().IncRef(); + + return true; + } + void post(scene::Node& node) const + { + if(node.isRoot()) + { + return; + } + + Node_getTraversable(m_path.parent())->insert(m_path.top()); + + m_path.top().get().DecRef(); + m_path.pop(); + } +}; + +scene::Node& Node_Clone(scene::Node& node) +{ + scene::Node& clone = node_clone(node); + scene::Traversable* traversable = Node_getTraversable(node); + if(traversable != 0) + { + traversable->traverse(CloneAll(clone)); + } + return clone; +} + + +typedef std::map EntityBreakdown; + +class EntityBreakdownWalker : public scene::Graph::Walker +{ + EntityBreakdown& m_entitymap; +public: + EntityBreakdownWalker(EntityBreakdown& entitymap) + : m_entitymap(entitymap) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Entity* entity = Node_getEntity(path.top()); + if(entity != 0) + { + const EntityClass& eclass = entity->getEntityClass(); + if(m_entitymap.find(eclass.name()) == m_entitymap.end()) + { + m_entitymap[eclass.name()] = 1; + } + else ++m_entitymap[eclass.name()]; + } + return true; + } +}; + +void Scene_EntityBreakdown(EntityBreakdown& entitymap) +{ + GlobalSceneGraph().traverse(EntityBreakdownWalker(entitymap)); +} + + +WindowPosition g_posMapInfoWnd(c_default_window_pos); + +void DoMapInfo() +{ + ModalDialog dialog; + GtkEntry* brushes_entry; + GtkEntry* entities_entry; + GtkListStore* EntityBreakdownWalker; + + GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Map Info", G_CALLBACK(dialog_delete_callback), &dialog); + + window_set_position(window, g_posMapInfoWnd); + + { + GtkVBox* vbox = create_dialog_vbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); + + { + GtkHBox* hbox = create_dialog_hbox(4); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, TRUE, 0); + + { + GtkTable* table = create_dialog_table(2, 2, 4, 4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); + + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_entry_set_editable(entry, FALSE); + + brushes_entry = entry; + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_entry_set_editable(entry, FALSE); + + entities_entry = entry; + } + { + GtkWidget* label = gtk_label_new ("Total Brushes"); + gtk_widget_show (label); + gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkWidget* label = gtk_label_new ("Total Entities"); + gtk_widget_show (label); + gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + } + { + GtkVBox* vbox2 = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), FALSE, FALSE, 0); + + { + GtkButton* button = create_dialog_button("Close", G_CALLBACK(dialog_button_ok), &dialog); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(button), FALSE, FALSE, 0); + } + } + } + { + GtkWidget* label = gtk_label_new ("Entity breakdown"); + gtk_widget_show (label); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(label), FALSE, TRUE, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkScrolledWindow* scr = create_scrolled_window(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC, 4); + gtk_box_pack_start(GTK_BOX (vbox), GTK_WIDGET(scr), TRUE, TRUE, 0); + + { + GtkListStore* store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_STRING); + + GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + gtk_tree_view_set_headers_clickable(GTK_TREE_VIEW(view), TRUE); + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Entity", renderer, "text", 0, 0); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + gtk_tree_view_column_set_sort_column_id(column, 0); + } + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Count", renderer, "text", 1, 0); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + gtk_tree_view_column_set_sort_column_id(column, 1); + } + + gtk_widget_show(view); + + gtk_container_add(GTK_CONTAINER(scr), view); + + EntityBreakdownWalker = store; + } + } + } + + // Initialize fields + + { + EntityBreakdown entitymap; + Scene_EntityBreakdown(entitymap); + + for(EntityBreakdown::iterator i=entitymap.begin(); i != entitymap.end(); ++i) + { + char tmp[16]; + sprintf (tmp, "%u", Unsigned((*i).second)); + GtkTreeIter iter; + gtk_list_store_append(GTK_LIST_STORE(EntityBreakdownWalker), &iter); + gtk_list_store_set(GTK_LIST_STORE(EntityBreakdownWalker), &iter, 0, (*i).first.c_str(), 1, tmp, -1); + } + } + + g_object_unref(G_OBJECT(EntityBreakdownWalker)); + + char tmp[16]; + sprintf (tmp, "%u", Unsigned(g_brushCount.get())); + gtk_entry_set_text (GTK_ENTRY (brushes_entry), tmp); + sprintf (tmp, "%u", Unsigned(g_entityCount.get())); + gtk_entry_set_text (GTK_ENTRY (entities_entry), tmp); + + modal_dialog_show(window, dialog); + + // save before exit + window_get_position(window, g_posMapInfoWnd); + + gtk_widget_destroy(GTK_WIDGET(window)); +} + + + +class ScopeTimer +{ + Timer m_timer; + const char* m_message; +public: + ScopeTimer(const char* message) + : m_message(message) + { + m_timer.start(); + } + ~ScopeTimer() + { + double elapsed_time = m_timer.elapsed_msec() / 1000.f; + globalOutputStream() << m_message << " timer: " << FloatFormat(elapsed_time, 5, 2) << " second(s) elapsed\n"; + } +}; + +/* +================ +Map_LoadFile +================ +*/ + +void Map_LoadFile (const char *filename) +{ + globalOutputStream() << "Loading map from " << filename << "\n"; + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Map"); + + { + ScopeTimer timer("map load"); + + const MapFormat* format = NULL; + const char* moduleName = findModuleName(&GlobalFiletypes(), MapFormat::Name(), path_get_extension(filename)); + if(string_not_empty(moduleName)) + format = ReferenceAPI_getMapModules().findModule(moduleName); + + for(int i = 0; i < Brush_toggleFormatCount(); ++i) + { + if(i) + Map_Free(); + Brush_toggleFormat(i); + g_map.m_name = filename; + Map_UpdateTitle(g_map); + g_map.m_resource = GlobalReferenceCache().capture(g_map.m_name.c_str()); + if(format) + format->wrongFormat = false; + g_map.m_resource->attach(g_map); + if(format) + if(!format->wrongFormat) + break; + } + + Node_getTraversable(GlobalSceneGraph().root())->traverse(entity_updateworldspawn()); + } + + globalOutputStream() << "--- LoadMapFile ---\n"; + globalOutputStream() << g_map.m_name.c_str() << "\n"; + + globalOutputStream() << Unsigned(g_brushCount.get()) << " primitive\n"; + globalOutputStream() << Unsigned(g_entityCount.get()) << " entities\n"; + + //GlobalEntityCreator().printStatistics(); + + // + // move the view to a start position + // + Map_StartPosition(); + + g_currentMap = &g_map; +} + +class Excluder +{ +public: + virtual bool excluded(scene::Node& node) const = 0; +}; + +class ExcludeWalker : public scene::Traversable::Walker +{ + const scene::Traversable::Walker& m_walker; + const Excluder* m_exclude; + mutable bool m_skip; +public: + ExcludeWalker(const scene::Traversable::Walker& walker, const Excluder& exclude) + : m_walker(walker), m_exclude(&exclude), m_skip(false) + { + } + bool pre(scene::Node& node) const + { + if(m_exclude->excluded(node) || node.isRoot()) + { + m_skip = true; + return false; + } + else + { + m_walker.pre(node); + } + return true; + } + void post(scene::Node& node) const + { + if(m_skip) + { + m_skip = false; + } + else + { + m_walker.post(node); + } + } +}; + +class AnyInstanceSelected : public scene::Instantiable::Visitor +{ + bool& m_selected; +public: + AnyInstanceSelected(bool& selected) : m_selected(selected) + { + m_selected = false; + } + void visit(scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected()) + { + m_selected = true; + } + } +}; + +bool Node_instanceSelected(scene::Node& node) +{ + scene::Instantiable* instantiable = Node_getInstantiable(node); + ASSERT_NOTNULL(instantiable); + bool selected; + instantiable->forEachInstance(AnyInstanceSelected(selected)); + return selected; +} + +class SelectedDescendantWalker : public scene::Traversable::Walker +{ + bool& m_selected; +public: + SelectedDescendantWalker(bool& selected) : m_selected(selected) + { + m_selected = false; + } + + bool pre(scene::Node& node) const + { + if(node.isRoot()) + { + return false; + } + + if(Node_instanceSelected(node)) + { + m_selected = true; + } + + return true; + } +}; + +bool Node_selectedDescendant(scene::Node& node) +{ + bool selected; + Node_traverseSubgraph(node, SelectedDescendantWalker(selected)); + return selected; +} + +class SelectionExcluder : public Excluder +{ +public: + bool excluded(scene::Node& node) const + { + return !Node_selectedDescendant(node); + } +}; + +class IncludeSelectedWalker : public scene::Traversable::Walker +{ + const scene::Traversable::Walker& m_walker; + mutable std::size_t m_selected; + mutable bool m_skip; + + bool selectedParent() const + { + return m_selected != 0; + } +public: + IncludeSelectedWalker(const scene::Traversable::Walker& walker) + : m_walker(walker), m_selected(0), m_skip(false) + { + } + bool pre(scene::Node& node) const + { + // include node if: + // node is not a 'root' AND ( node is selected OR any child of node is selected OR any parent of node is selected ) + if(!node.isRoot() && (Node_selectedDescendant(node) || selectedParent())) + { + if(Node_instanceSelected(node)) + { + ++m_selected; + } + m_walker.pre(node); + return true; + } + else + { + m_skip = true; + return false; + } + } + void post(scene::Node& node) const + { + if(m_skip) + { + m_skip = false; + } + else + { + if(Node_instanceSelected(node)) + { + --m_selected; + } + m_walker.post(node); + } + } +}; + +void Map_Traverse_Selected(scene::Node& root, const scene::Traversable::Walker& walker) +{ + scene::Traversable* traversable = Node_getTraversable(root); + if(traversable != 0) + { +#if 0 + traversable->traverse(ExcludeWalker(walker, SelectionExcluder())); +#else + traversable->traverse(IncludeSelectedWalker(walker)); +#endif + } +} + +void Map_ExportSelected(TextOutputStream& out, const MapFormat& format) +{ + format.writeGraph(GlobalSceneGraph().root(), Map_Traverse_Selected, out); +} + +void Map_Traverse(scene::Node& root, const scene::Traversable::Walker& walker) +{ + scene::Traversable* traversable = Node_getTraversable(root); + if(traversable != 0) + { + traversable->traverse(walker); + } +} + +class RegionExcluder : public Excluder +{ +public: + bool excluded(scene::Node& node) const + { + return node.excluded(); + } +}; + +void Map_Traverse_Region(scene::Node& root, const scene::Traversable::Walker& walker) +{ + scene::Traversable* traversable = Node_getTraversable(root); + if(traversable != 0) + { + traversable->traverse(ExcludeWalker(walker, RegionExcluder())); + } +} + +bool Map_SaveRegion(const char *filename) +{ + AddRegionBrushes(); + + bool success = MapResource_saveFile(MapFormat_forFile(filename), GlobalSceneGraph().root(), Map_Traverse_Region, filename); + + RemoveRegionBrushes(); + + return success; +} + + +void Map_RenameAbsolute(const char* absolute) +{ + Resource* resource = GlobalReferenceCache().capture(absolute); + NodeSmartReference clone(NewMapRoot(path_make_relative(absolute, GlobalFileSystem().findRoot(absolute)))); + resource->setNode(clone.get_pointer()); + + { + //ScopeTimer timer("clone subgraph"); + Node_getTraversable(GlobalSceneGraph().root())->traverse(CloneAll(clone)); + } + + g_map.m_resource->detach(g_map); + GlobalReferenceCache().release(g_map.m_name.c_str()); + + g_map.m_resource = resource; + + g_map.m_name = absolute; + Map_UpdateTitle(g_map); + + g_map.m_resource->attach(g_map); +} + +void Map_Rename(const char* filename) +{ + if(!string_equal(g_map.m_name.c_str(), filename)) + { + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Saving Map"); + + Map_RenameAbsolute(filename); + + SceneChangeNotify(); + } + else + { + SaveReferences(); + } +} + +bool Map_Save() +{ + Pointfile_Clear(); + + ScopeTimer timer("map save"); + SaveReferences(); + return true; // assume success.. +} + +/* +=========== +Map_New + +=========== +*/ +void Map_New() +{ + //globalOutputStream() << "Map_New\n"; + + g_map.m_name = "unnamed.map"; + Map_UpdateTitle(g_map); + + { + g_map.m_resource = GlobalReferenceCache().capture(g_map.m_name.c_str()); +// ASSERT_MESSAGE(g_map.m_resource->getNode() == 0, "bleh"); + g_map.m_resource->attach(g_map); + + SceneChangeNotify(); + } + + FocusViews(g_vector3_identity, 0); + + g_currentMap = &g_map; +} + +extern void ConstructRegionBrushes(scene::Node* brushes[6], const Vector3& region_mins, const Vector3& region_maxs); + +void ConstructRegionStartpoint(scene::Node* startpoint, const Vector3& region_mins, const Vector3& region_maxs) +{ + /*! + \todo we need to make sure that the player start IS inside the region and bail out if it's not + the compiler will refuse to compile a map with a player_start somewhere in empty space.. + for now, let's just print an error + */ + + Vector3 vOrig(Camera_getOrigin(*g_pParentWnd->GetCamWnd())); + + for (int i=0 ; i<3 ; i++) + { + if (vOrig[i] > region_maxs[i] || vOrig[i] < region_mins[i]) + { + globalErrorStream() << "Camera is NOT in the region, it's likely that the region won't compile correctly\n"; + break; + } + } + + // write the info_playerstart + char sTmp[1024]; + sprintf(sTmp, "%d %d %d", (int)vOrig[0], (int)vOrig[1], (int)vOrig[2]); + Node_getEntity(*startpoint)->setKeyValue("origin", sTmp); + sprintf(sTmp, "%d", (int)Camera_getAngles(*g_pParentWnd->GetCamWnd())[CAMERA_YAW]); + Node_getEntity(*startpoint)->setKeyValue("angle", sTmp); +} + +/* +=========================================================== + + REGION + +=========================================================== +*/ +bool region_active; +Vector3 region_mins(g_MinWorldCoord, g_MinWorldCoord, g_MinWorldCoord); +Vector3 region_maxs(g_MaxWorldCoord, g_MaxWorldCoord, g_MaxWorldCoord); + +scene::Node* region_sides[6]; +scene::Node* region_startpoint = 0; + +/* +=========== +AddRegionBrushes +a regioned map will have temp walls put up at the region boundary +\todo TODO TTimo old implementation of region brushes + we still add them straight in the worldspawn and take them out after the map is saved + with the new implementation we should be able to append them in a temporary manner to the data we pass to the map module +=========== +*/ +void AddRegionBrushes (void) +{ + int i; + + for(i=0; i<6; i++) + { + region_sides[i] = &GlobalBrushCreator().createBrush(); + Node_getTraversable(Map_FindOrInsertWorldspawn(g_map))->insert(NodeSmartReference(*region_sides[i])); + } + + region_startpoint = &GlobalEntityCreator().createEntity(GlobalEntityClassManager().findOrInsert("info_player_start", false)); + + ConstructRegionBrushes(region_sides, region_mins, region_maxs); + ConstructRegionStartpoint(region_startpoint, region_mins, region_maxs); + + Node_getTraversable(GlobalSceneGraph().root())->insert(NodeSmartReference(*region_startpoint)); +} + +void RemoveRegionBrushes (void) +{ + for(std::size_t i=0; i<6; i++) + { + Node_getTraversable(*Map_GetWorldspawn(g_map))->erase(*region_sides[i]); + } + Node_getTraversable(GlobalSceneGraph().root())->erase(*region_startpoint); +} + +inline void exclude_node(scene::Node& node, bool exclude) +{ + exclude + ? node.enable(scene::Node::eExcluded) + : node.disable(scene::Node::eExcluded); +} + +class ExcludeAllWalker : public scene::Graph::Walker +{ + bool m_exclude; +public: + ExcludeAllWalker(bool exclude) + : m_exclude(exclude) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + exclude_node(path.top(), m_exclude); + + return true; + } +}; + +void Scene_Exclude_All(bool exclude) +{ + GlobalSceneGraph().traverse(ExcludeAllWalker(exclude)); +} + +bool Instance_isSelected(const scene::Instance& instance) +{ + const Selectable* selectable = Instance_getSelectable(instance); + return selectable != 0 && selectable->isSelected(); +} + +class ExcludeSelectedWalker : public scene::Graph::Walker +{ + bool m_exclude; +public: + ExcludeSelectedWalker(bool exclude) + : m_exclude(exclude) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + exclude_node(path.top(), (instance.isSelected() || instance.childSelected() || instance.parentSelected()) == m_exclude); + return true; + } +}; + +void Scene_Exclude_Selected(bool exclude) +{ + GlobalSceneGraph().traverse(ExcludeSelectedWalker(exclude)); +} + +class ExcludeRegionedWalker : public scene::Graph::Walker +{ + bool m_exclude; +public: + ExcludeRegionedWalker(bool exclude) + : m_exclude(exclude) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + exclude_node( + path.top(), + !( + ( + aabb_intersects_aabb( + instance.worldAABB(), + aabb_for_minmax(region_mins, region_maxs) + ) != 0 + ) ^ m_exclude + ) + ); + + return true; + } +}; + +void Scene_Exclude_Region(bool exclude) +{ + GlobalSceneGraph().traverse(ExcludeRegionedWalker(exclude)); +} + +/* +=========== +Map_RegionOff + +Other filtering options may still be on +=========== +*/ +void Map_RegionOff() +{ + region_active = false; + + region_maxs[0] = g_MaxWorldCoord - 64; + region_mins[0] = g_MinWorldCoord + 64; + region_maxs[1] = g_MaxWorldCoord - 64; + region_mins[1] = g_MinWorldCoord + 64; + region_maxs[2] = g_MaxWorldCoord - 64; + region_mins[2] = g_MinWorldCoord + 64; + + Scene_Exclude_All(false); +} + +void Map_ApplyRegion (void) +{ + region_active = true; + + Scene_Exclude_Region(false); +} + + +/* +======================== +Map_RegionSelectedBrushes +======================== +*/ +void Map_RegionSelectedBrushes (void) +{ + Map_RegionOff(); + + if(GlobalSelectionSystem().countSelected() != 0 + && GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) + { + region_active = true; + Select_GetBounds (region_mins, region_maxs); + + Scene_Exclude_Selected(false); + + GlobalSelectionSystem().setSelectedAll(false); + } +} + + +/* +=========== +Map_RegionXY +=========== +*/ +void Map_RegionXY(float x_min, float y_min, float x_max, float y_max) +{ + Map_RegionOff(); + + region_mins[0] = x_min; + region_maxs[0] = x_max; + region_mins[1] = y_min; + region_maxs[1] = y_max; + region_mins[2] = g_MinWorldCoord + 64; + region_maxs[2] = g_MaxWorldCoord - 64; + + Map_ApplyRegion(); +} + +void Map_RegionBounds(const AABB& bounds) +{ + Map_RegionOff(); + + region_mins = vector3_subtracted(bounds.origin, bounds.extents); + region_maxs = vector3_added(bounds.origin, bounds.extents); + + deleteSelection(); + + Map_ApplyRegion(); +} + +/* +=========== +Map_RegionBrush +=========== +*/ +void Map_RegionBrush (void) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); + Map_RegionBounds(instance.worldAABB()); + } +} + +// +//================ +//Map_ImportFile +//================ +// +bool Map_ImportFile(const char* filename) +{ + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Map"); + + bool success = false; + + if(extension_equal(path_get_extension(filename), "bsp")) + goto tryDecompile; + + { + const MapFormat* format = NULL; + const char* moduleName = findModuleName(&GlobalFiletypes(), MapFormat::Name(), path_get_extension(filename)); + if(string_not_empty(moduleName)) + format = ReferenceAPI_getMapModules().findModule(moduleName); + + if(format) + format->wrongFormat = false; + Resource* resource = GlobalReferenceCache().capture(filename); + resource->refresh(); // avoid loading old version if map has changed on disk since last import + if(!resource->load()) + { + GlobalReferenceCache().release(filename); + goto tryDecompile; + } + if(format) + if(format->wrongFormat) + { + GlobalReferenceCache().release(filename); + goto tryDecompile; + } + NodeSmartReference clone(NewMapRoot("")); + Node_getTraversable(*resource->getNode())->traverse(CloneAll(clone)); + Map_gatherNamespaced(clone); + Map_mergeClonedNames(); + MergeMap(clone); + success = true; + GlobalReferenceCache().release(filename); + } + + SceneChangeNotify(); + + return success; + +tryDecompile: + + const char *type = GlobalRadiant().getRequiredGameDescriptionKeyValue("q3map2_type"); + int n = string_length(path_get_extension(filename)); + if(n && (extension_equal(path_get_extension(filename), "bsp") || extension_equal(path_get_extension(filename), "map"))) + { + StringBuffer output; + output.push_string(AppPath_get()); + output.push_string("q3map2."); + output.push_string(RADIANT_EXECUTABLE); + output.push_string(" -v -game "); + output.push_string((type && *type) ? type : "quake3"); + output.push_string(" -fs_basepath \""); + output.push_string(EnginePath_get()); + output.push_string("\" -fs_game "); + output.push_string(gamename_get()); + output.push_string(" -convert -format "); + output.push_string(Brush::m_type == eBrushTypeQuake3BP ? "map_bp" : "map"); + output.push_string(" -readmap \""); + output.push_string(filename); + output.push_string("\""); + + // run + Q_Exec(NULL, output.c_str(), NULL, false, true); + + // rebuild filename as "filenamewithoutext_converted.map" + output.clear(); + output.push_range(filename, filename + string_length(filename) - (n + 1)); + output.push_string("_converted.map"); + filename = output.c_str(); + + // open + Resource* resource = GlobalReferenceCache().capture(filename); + resource->refresh(); // avoid loading old version if map has changed on disk since last import + if(!resource->load()) + { + GlobalReferenceCache().release(filename); + goto tryDecompile; + } + NodeSmartReference clone(NewMapRoot("")); + Node_getTraversable(*resource->getNode())->traverse(CloneAll(clone)); + Map_gatherNamespaced(clone); + Map_mergeClonedNames(); + MergeMap(clone); + success = true; + GlobalReferenceCache().release(filename); + } + + SceneChangeNotify(); + return success; +} + +/* +=========== +Map_SaveFile +=========== +*/ +bool Map_SaveFile(const char* filename) +{ + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Saving Map"); + return MapResource_saveFile(MapFormat_forFile(filename), GlobalSceneGraph().root(), Map_Traverse, filename); +} + +// +//=========== +//Map_SaveSelected +//=========== +// +// Saves selected world brushes and whole entities with partial/full selections +// +bool Map_SaveSelected(const char* filename) +{ + return MapResource_saveFile(MapFormat_forFile(filename), GlobalSceneGraph().root(), Map_Traverse_Selected, filename); +} + + +class ParentSelectedBrushesToEntityWalker : public scene::Graph::Walker +{ + scene::Node& m_parent; +public: + ParentSelectedBrushesToEntityWalker(scene::Node& parent) : m_parent(parent) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get_pointer() != &m_parent + && Node_isPrimitive(path.top())) + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected() + && path.size() > 1) + { + return false; + } + } + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get_pointer() != &m_parent + && Node_isPrimitive(path.top())) + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected() + && path.size() > 1) + { + scene::Node& parent = path.parent(); + if(&parent != &m_parent) + { + NodeSmartReference node(path.top().get()); + Node_getTraversable(parent)->erase(node); + Node_getTraversable(m_parent)->insert(node); + } + } + } + } +}; + +void Scene_parentSelectedBrushesToEntity(scene::Graph& graph, scene::Node& parent) +{ + graph.traverse(ParentSelectedBrushesToEntityWalker(parent)); +} + +class CountSelectedBrushes : public scene::Graph::Walker +{ + std::size_t& m_count; + mutable std::size_t m_depth; +public: + CountSelectedBrushes(std::size_t& count) : m_count(count), m_depth(0) + { + m_count = 0; + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(++m_depth != 1 && path.top().get().isRoot()) + { + return false; + } + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected() + && Node_isPrimitive(path.top())) + { + ++m_count; + } + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + --m_depth; + } +}; + +std::size_t Scene_countSelectedBrushes(scene::Graph& graph) +{ + std::size_t count; + graph.traverse(CountSelectedBrushes(count)); + return count; +} + +enum ENodeType +{ + eNodeUnknown, + eNodeMap, + eNodeEntity, + eNodePrimitive, +}; + +const char* nodetype_get_name(ENodeType type) +{ + if(type == eNodeMap) + return "map"; + if(type == eNodeEntity) + return "entity"; + if(type == eNodePrimitive) + return "primitive"; + return "unknown"; +} + +ENodeType node_get_nodetype(scene::Node& node) +{ + if(Node_isEntity(node)) + { + return eNodeEntity; + } + if(Node_isPrimitive(node)) + { + return eNodePrimitive; + } + return eNodeUnknown; +} + +bool contains_entity(scene::Node& node) +{ + return Node_getTraversable(node) != 0 && !Node_isBrush(node) && !Node_isPatch(node) && !Node_isEntity(node); +} + +bool contains_primitive(scene::Node& node) +{ + return Node_isEntity(node) && Node_getTraversable(node) != 0 && Node_getEntity(node)->isContainer(); +} + +ENodeType node_get_contains(scene::Node& node) +{ + if(contains_entity(node)) + { + return eNodeEntity; + } + if(contains_primitive(node)) + { + return eNodePrimitive; + } + return eNodeUnknown; +} + +void Path_parent(const scene::Path& parent, const scene::Path& child) +{ + ENodeType contains = node_get_contains(parent.top()); + ENodeType type = node_get_nodetype(child.top()); + + if(contains != eNodeUnknown && contains == type) + { + NodeSmartReference node(child.top().get()); + Path_deleteTop(child); + Node_getTraversable(parent.top())->insert(node); + SceneChangeNotify(); + } + else + { + globalErrorStream() << "failed - " << nodetype_get_name(type) << " cannot be parented to " << nodetype_get_name(contains) << " container.\n"; + } +} + +void Scene_parentSelected() +{ + UndoableCommand undo("parentSelected"); + + if(GlobalSelectionSystem().countSelected() > 1) + { + class ParentSelectedBrushesToEntityWalker : public SelectionSystem::Visitor + { + const scene::Path& m_parent; + public: + ParentSelectedBrushesToEntityWalker(const scene::Path& parent) : m_parent(parent) + { + } + void visit(scene::Instance& instance) const + { + if(&m_parent != &instance.path()) + { + Path_parent(m_parent, instance.path()); + } + } + }; + + ParentSelectedBrushesToEntityWalker visitor(GlobalSelectionSystem().ultimateSelected().path()); + GlobalSelectionSystem().foreachSelected(visitor); + } + else + { + globalOutputStream() << "failed - did not find two selected nodes.\n"; + } +} + + + +void NewMap() +{ + if (ConfirmModified("New Map")) + { + Map_RegionOff(); + Map_Free(); + Map_New(); + } +} + +CopiedString g_mapsPath; + +const char* getMapsPath() +{ + return g_mapsPath.c_str(); +} + +const char* map_open(const char* title) +{ + return file_dialog(GTK_WIDGET(MainFrame_getWindow()), TRUE, title, getMapsPath(), MapFormat::Name(), true, false, false); +} + +const char* map_import(const char* title) +{ + return file_dialog(GTK_WIDGET(MainFrame_getWindow()), TRUE, title, getMapsPath(), MapFormat::Name(), false, true, false); +} + +const char* map_save(const char* title) +{ + return file_dialog(GTK_WIDGET(MainFrame_getWindow()), FALSE, title, getMapsPath(), MapFormat::Name(), false, false, true); +} + +void OpenMap() +{ + if (!ConfirmModified("Open Map")) + return; + + const char* filename = map_open("Open Map"); + + if (filename != 0) + { + MRU_AddFile(filename); + Map_RegionOff(); + Map_Free(); + Map_LoadFile(filename); + } +} + +void ImportMap() +{ + const char* filename = map_import("Import Map"); + + if(filename != 0) + { + UndoableCommand undo("mapImport"); + Map_ImportFile(filename); + } +} + +bool Map_SaveAs() +{ + const char* filename = map_save("Save Map"); + + if(filename != 0) + { + MRU_AddFile(filename); + Map_Rename(filename); + return Map_Save(); + } + return false; +} + +void SaveMapAs() +{ + Map_SaveAs(); +} + +void SaveMap() +{ + if(Map_Unnamed(g_map)) + { + SaveMapAs(); + } + else if(Map_Modified(g_map)) + { + Map_Save(); + } +} + +void ExportMap() +{ + const char* filename = map_save("Export Selection"); + + if(filename != 0) + { + Map_SaveSelected(filename); + } +} + +void SaveRegion() +{ + const char* filename = map_save("Export Region"); + + if(filename != 0) + { + Map_SaveRegion(filename); + } +} + + +void RegionOff() +{ + Map_RegionOff(); + SceneChangeNotify(); +} + +void RegionXY() +{ + Map_RegionXY( + g_pParentWnd->GetXYWnd()->GetOrigin()[0] - 0.5f * g_pParentWnd->GetXYWnd()->Width() / g_pParentWnd->GetXYWnd()->Scale(), + g_pParentWnd->GetXYWnd()->GetOrigin()[1] - 0.5f * g_pParentWnd->GetXYWnd()->Height() / g_pParentWnd->GetXYWnd()->Scale(), + g_pParentWnd->GetXYWnd()->GetOrigin()[0] + 0.5f * g_pParentWnd->GetXYWnd()->Width() / g_pParentWnd->GetXYWnd()->Scale(), + g_pParentWnd->GetXYWnd()->GetOrigin()[1] + 0.5f * g_pParentWnd->GetXYWnd()->Height() / g_pParentWnd->GetXYWnd()->Scale() + ); + SceneChangeNotify(); +} + +void RegionBrush() +{ + Map_RegionBrush(); + SceneChangeNotify(); +} + +void RegionSelected() +{ + Map_RegionSelectedBrushes(); + SceneChangeNotify(); +} + + + + + +class BrushFindByIndexWalker : public scene::Traversable::Walker +{ + mutable std::size_t m_index; + scene::Path& m_path; +public: + BrushFindByIndexWalker(std::size_t index, scene::Path& path) + : m_index(index), m_path(path) + { + } + bool pre(scene::Node& node) const + { + if(Node_isPrimitive(node) && m_index-- == 0) + { + m_path.push(makeReference(node)); + } + return false; + } +}; + +class EntityFindByIndexWalker : public scene::Traversable::Walker +{ + mutable std::size_t m_index; + scene::Path& m_path; +public: + EntityFindByIndexWalker(std::size_t index, scene::Path& path) + : m_index(index), m_path(path) + { + } + bool pre(scene::Node& node) const + { + if(Node_isEntity(node) && m_index-- == 0) + { + m_path.push(makeReference(node)); + } + return false; + } +}; + +void Scene_FindEntityBrush(std::size_t entity, std::size_t brush, scene::Path& path) +{ + path.push(makeReference(GlobalSceneGraph().root())); + { + Node_getTraversable(path.top())->traverse(EntityFindByIndexWalker(entity, path)); + } + if(path.size() == 2) + { + scene::Traversable* traversable = Node_getTraversable(path.top()); + if(traversable != 0) + { + traversable->traverse(BrushFindByIndexWalker(brush, path)); + } + } +} + +inline bool Node_hasChildren(scene::Node& node) +{ + scene::Traversable* traversable = Node_getTraversable(node); + return traversable != 0 && !traversable->empty(); +} + +void SelectBrush (int entitynum, int brushnum) +{ + scene::Path path; + Scene_FindEntityBrush(entitynum, brushnum, path); + if(path.size() == 3 || (path.size() == 2 && !Node_hasChildren(path.top()))) + { + scene::Instance* instance = GlobalSceneGraph().find(path); + ASSERT_MESSAGE(instance != 0, "SelectBrush: path not found in scenegraph"); + Selectable* selectable = Instance_getSelectable(*instance); + ASSERT_MESSAGE(selectable != 0, "SelectBrush: path not selectable"); + selectable->setSelected(true); + g_pParentWnd->GetXYWnd()->PositionView(instance->worldAABB().origin); + } +} + + +class BrushFindIndexWalker : public scene::Graph::Walker +{ + mutable const scene::Node* m_node; + std::size_t& m_count; +public: + BrushFindIndexWalker(const scene::Node& node, std::size_t& count) + : m_node(&node), m_count(count) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(Node_isPrimitive(path.top())) + { + if(m_node == path.top().get_pointer()) + { + m_node = 0; + } + if(m_node) + { + ++m_count; + } + } + return true; + } +}; + +class EntityFindIndexWalker : public scene::Graph::Walker +{ + mutable const scene::Node* m_node; + std::size_t& m_count; +public: + EntityFindIndexWalker(const scene::Node& node, std::size_t& count) + : m_node(&node), m_count(count) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(Node_isEntity(path.top())) + { + if(m_node == path.top().get_pointer()) + { + m_node = 0; + } + if(m_node) + { + ++m_count; + } + } + return true; + } +}; + +static void GetSelectionIndex (int *ent, int *brush) +{ + std::size_t count_brush = 0; + std::size_t count_entity = 0; + if(GlobalSelectionSystem().countSelected() != 0) + { + const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path(); + + GlobalSceneGraph().traverse(BrushFindIndexWalker(path.top(), count_brush)); + GlobalSceneGraph().traverse(EntityFindIndexWalker(path.parent(), count_entity)); + } + *brush = int(count_brush); + *ent = int(count_entity); +} + +void DoFind() +{ + ModalDialog dialog; + GtkEntry* entity; + GtkEntry* brush; + + GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Find Brush", G_CALLBACK(dialog_delete_callback), &dialog); + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel); + + { + GtkVBox* vbox = create_dialog_vbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); + { + GtkTable* table = create_dialog_table(2, 2, 4, 4); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), TRUE, TRUE, 0); + { + GtkWidget* label = gtk_label_new ("Entity number"); + gtk_widget_show (label); + gtk_table_attach (GTK_TABLE (table), label, 0, 1, 0, 1, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new ("Brush number"); + gtk_widget_show (label); + gtk_table_attach (GTK_TABLE (table), label, 0, 1, 1, 2, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_grab_focus(GTK_WIDGET(entry)); + entity = entry; + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + brush = entry; + } + } + { + GtkHBox* hbox = create_dialog_hbox(4); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), TRUE, TRUE, 0); + { + GtkButton* button = create_dialog_button("Find", G_CALLBACK(dialog_button_ok), &dialog); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_dialog_button("Close", G_CALLBACK(dialog_button_cancel), &dialog); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); + } + } + } + + // Initialize dialog + char buf[16]; + int ent, br; + + GetSelectionIndex (&ent, &br); + sprintf (buf, "%i", ent); + gtk_entry_set_text(entity, buf); + sprintf (buf, "%i", br); + gtk_entry_set_text(brush, buf); + + if(modal_dialog_show(window, dialog) == eIDOK) + { + const char *entstr = gtk_entry_get_text(entity); + const char *brushstr = gtk_entry_get_text(brush); + SelectBrush (atoi(entstr), atoi(brushstr)); + } + + gtk_widget_destroy(GTK_WIDGET(window)); +} + +void Map_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox("", "Load last map on open", g_bLoadLastMap); +} + + +class MapEntityClasses : public ModuleObserver +{ + std::size_t m_unrealised; +public: + MapEntityClasses() : m_unrealised(1) + { + } + void realise() + { + if(--m_unrealised == 0) + { + if(g_map.m_resource != 0) + { + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Map"); + g_map.m_resource->realise(); + } + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + if(g_map.m_resource != 0) + { + g_map.m_resource->flush(); + g_map.m_resource->unrealise(); + } + } + } +}; + +MapEntityClasses g_MapEntityClasses; + + +class MapModuleObserver : public ModuleObserver +{ + std::size_t m_unrealised; +public: + MapModuleObserver() : m_unrealised(1) + { + } + void realise() + { + if(--m_unrealised == 0) + { + ASSERT_MESSAGE(!string_empty(g_qeglobals.m_userGamePath.c_str()), "maps_directory: user-game-path is empty"); + StringOutputStream buffer(256); + buffer << g_qeglobals.m_userGamePath.c_str() << "maps/"; + Q_mkdir(buffer.c_str()); + g_mapsPath = buffer.c_str(); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + g_mapsPath = ""; + } + } +}; + +MapModuleObserver g_MapModuleObserver; + +#include "preferencesystem.h" + +CopiedString g_strLastMap; +bool g_bLoadLastMap = false; + +void Map_Construct() +{ + GlobalCommands_insert("RegionOff", FreeCaller()); + GlobalCommands_insert("RegionSetXY", FreeCaller()); + GlobalCommands_insert("RegionSetBrush", FreeCaller()); + GlobalCommands_insert("RegionSetSelection", FreeCaller(), Accelerator('R', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + + GlobalPreferenceSystem().registerPreference("LastMap", CopiedStringImportStringCaller(g_strLastMap), CopiedStringExportStringCaller(g_strLastMap)); + GlobalPreferenceSystem().registerPreference("LoadLastMap", BoolImportStringCaller(g_bLoadLastMap), BoolExportStringCaller(g_bLoadLastMap)); + GlobalPreferenceSystem().registerPreference("MapInfoDlg", WindowPositionImportStringCaller(g_posMapInfoWnd), WindowPositionExportStringCaller(g_posMapInfoWnd)); + + PreferencesDialog_addSettingsPreferences(FreeCaller1()); + + GlobalEntityClassManager().attach(g_MapEntityClasses); + Radiant_attachHomePathsObserver(g_MapModuleObserver); +} + +void Map_Destroy() +{ + Radiant_detachHomePathsObserver(g_MapModuleObserver); + GlobalEntityClassManager().detach(g_MapEntityClasses); +} diff --git a/misc/mediasource/netradiant-src/radiant/map.h b/misc/mediasource/netradiant-src/radiant/map.h new file mode 100644 index 00000000..2529bd2c --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/map.h @@ -0,0 +1,173 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_MAP_H) +#define INCLUDED_MAP_H + +#include "iscenegraph.h" +#include "generic/callback.h" +#include "signal/signalfwd.h" +#include "string/stringfwd.h" + +class Map; +extern Map g_map; + +class MapFormat; + +void Map_addValidCallback(Map& map, const SignalHandler& handler); +bool Map_Valid(const Map& map); + +class DeferredDraw +{ + Callback m_draw; + bool m_defer; + bool m_deferred; +public: + DeferredDraw(const Callback& draw) : m_draw(draw), m_defer(false), m_deferred(false) + { + } + void defer() + { + m_defer = true; + } + void draw() + { + if(m_defer) + { + m_deferred = true; + } + else + { + m_draw(); + } + } + void flush() + { + if(m_defer && m_deferred) + { + m_draw(); + } + m_deferred = false; + m_defer = false; + } +}; + +inline void DeferredDraw_onMapValidChanged(DeferredDraw& self) +{ + if(Map_Valid(g_map)) + { + self.flush(); + } + else + { + self.defer(); + } +} +typedef ReferenceCaller DeferredDrawOnMapValidChangedCaller; + + + +const char* Map_Name(const Map& map); +const MapFormat& Map_getFormat(const Map& map); +bool Map_Unnamed(const Map& map); + + +namespace scene +{ + class Node; + class Graph; +} + +scene::Node* Map_GetWorldspawn(const Map& map); +scene::Node* Map_FindWorldspawn(Map& map); +scene::Node& Map_FindOrInsertWorldspawn(Map& map); + +template class BasicVector3; +typedef BasicVector3 Vector3; + +extern Vector3 region_mins, region_maxs; +extern bool region_active; + +// used to be #defines, multiple engine support suggests we should go towards dynamic +extern float g_MaxWorldCoord; +extern float g_MinWorldCoord; + +void Map_LoadFile(const char* filename); +bool Map_SaveFile(const char* filename); + +void Map_New(); +void Map_Free(); + +void Map_RegionOff(); + +bool Map_SaveRegion(const char* filename); + +class TextInputStream; +class TextOutputStream; + +void Map_ImportSelected(TextInputStream& in, const MapFormat& format); +void Map_ExportSelected(TextOutputStream& out, const MapFormat& format); + +bool Map_Modified(const Map& map); +void Map_SetModified(Map& map, bool modified); + +bool Map_Save(); +bool Map_SaveAs(); + +scene::Node& Node_Clone(scene::Node& node); + +void DoMapInfo(); + +void Scene_parentSelectedBrushesToEntity(scene::Graph& graph, scene::Node& parent); +std::size_t Scene_countSelectedBrushes(scene::Graph& graph); + +void Scene_parentSelected(); + +void OnUndoSizeChanged(); + +void NewMap(); +void OpenMap(); +void ImportMap(); +void SaveMapAs(); +void SaveMap(); +void ExportMap(); +void SaveRegion(); + + +void Map_Traverse(scene::Node& root, const scene::Traversable::Walker& walker); + + +void SelectBrush (int entitynum, int brushnum); + +extern CopiedString g_strLastMap; +extern bool g_bLoadLastMap; + +void Map_Construct(); +void Map_Destroy(); + + +void Map_gatherNamespaced(scene::Node& root); +void Map_mergeClonedNames(); + + +const char* getMapsPath(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/mru.cpp b/misc/mediasource/netradiant-src/radiant/mru.cpp new file mode 100644 index 00000000..2dd0da72 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/mru.cpp @@ -0,0 +1,253 @@ +/* +Copyright (C) 1999-2006 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 "mru.h" + +#include +#include +#include + +#include "os/file.h" +#include "generic/callback.h" +#include "stream/stringstream.h" +#include "convert.h" + +#include "gtkutil/menu.h" +#include "map.h" +#include "qe3.h" + +#define MRU_MAX 4 +namespace { + GtkMenuItem *MRU_items[MRU_MAX]; + std::size_t MRU_used; + typedef CopiedString MRU_filename_t; + MRU_filename_t MRU_filenames[MRU_MAX]; + typedef const char* MRU_key_t; + MRU_key_t MRU_keys[MRU_MAX] = { "File0", "File1", "File2", "File3" }; +} + +inline const char* MRU_GetText(std::size_t index) +{ + return MRU_filenames[index].c_str(); +} + +class EscapedMnemonic +{ + StringBuffer m_buffer; +public: + EscapedMnemonic(std::size_t capacity) : m_buffer(capacity) + { + m_buffer.push_back('_'); + } + const char* c_str() const + { + return m_buffer.c_str(); + } + void push_back(char c) // not escaped + { + m_buffer.push_back(c); + } + std::size_t write(const char* buffer, std::size_t length) + { + for(const char* end = buffer + length; buffer != end; ++buffer) + { + if(*buffer == '_') + { + m_buffer.push_back('_'); + } + + m_buffer.push_back(*buffer); + } + return length; + } +}; + +template +inline EscapedMnemonic& operator<<(EscapedMnemonic& ostream, const T& t) +{ + return ostream_write(ostream, t); +} + + +void MRU_updateWidget(std::size_t index, const char *filename) +{ + EscapedMnemonic mnemonic(64); + mnemonic << Unsigned(index + 1) << "- " << filename; + gtk_label_set_text_with_mnemonic(GTK_LABEL(gtk_bin_get_child(GTK_BIN(MRU_items[index]))), mnemonic.c_str()); +} + +void MRU_SetText(std::size_t index, const char *filename) +{ + MRU_filenames[index] = filename; + MRU_updateWidget(index, filename); +} + +void MRU_AddFile (const char *str) +{ + std::size_t i; + const char* text; + + // check if file is already in our list + for (i = 0; i < MRU_used; i++) + { + text = MRU_GetText (i); + + if (strcmp (text, str) == 0) + { + // reorder menu + for(; i > 0; i--) + MRU_SetText(i, MRU_GetText (i-1)); + + MRU_SetText(0, str); + + return; + } + } + + if (MRU_used < MRU_MAX) + MRU_used++; + + // move items down + for (i = MRU_used-1; i > 0; i--) + MRU_SetText (i, MRU_GetText (i-1)); + + MRU_SetText (0, str); + gtk_widget_set_sensitive(GTK_WIDGET(MRU_items[0]), TRUE); + gtk_widget_show(GTK_WIDGET(MRU_items[MRU_used-1])); +} + +void MRU_Init() +{ + if(MRU_used > MRU_MAX) + MRU_used = MRU_MAX; +} + +void MRU_AddWidget(GtkMenuItem *widget, std::size_t pos) +{ + if(pos < MRU_MAX) + { + MRU_items[pos] = widget; + if(pos < MRU_used) + { + MRU_updateWidget(pos, MRU_GetText(pos)); + gtk_widget_set_sensitive(GTK_WIDGET(MRU_items[0]), TRUE); + gtk_widget_show(GTK_WIDGET(MRU_items[pos])); + } + } +} + +void MRU_Activate (std::size_t index) +{ + char text[1024]; + strcpy(text, MRU_GetText(index)); + + if (file_readable(text)) //\todo Test 'map load succeeds' instead of 'file is readable'. + { + MRU_AddFile (text); + Map_RegionOff(); + Map_Free(); + Map_LoadFile (text); + } + else + { + MRU_used--; + + for (std::size_t i = index; i < MRU_used; i++) + MRU_SetText (i, MRU_GetText (i+1)); + + if (MRU_used == 0) + { + gtk_label_set_text(GTK_LABEL(GTK_BIN(MRU_items[0])->child), "Recent Files"); + gtk_widget_set_sensitive(GTK_WIDGET(MRU_items[0]), FALSE); + } + else + { + gtk_widget_hide(GTK_WIDGET(MRU_items[MRU_used])); + } + } +} + + +class LoadMRU +{ + std::size_t m_number; +public: + LoadMRU(std::size_t number) + : m_number(number) + { + } + void load() + { + if (ConfirmModified("Open Map")) + { + MRU_Activate(m_number - 1); + } + } +}; + +typedef MemberCaller LoadMRUCaller; + +LoadMRU g_load_mru1(1); +LoadMRU g_load_mru2(2); +LoadMRU g_load_mru3(3); +LoadMRU g_load_mru4(4); + +void MRU_constructMenu(GtkMenu* menu) +{ + { + GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_1", LoadMRUCaller(g_load_mru1)); + gtk_widget_set_sensitive(GTK_WIDGET(item), FALSE); + MRU_AddWidget(item, 0); + } + { + GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_2", LoadMRUCaller(g_load_mru2)); + gtk_widget_hide(GTK_WIDGET(item)); + MRU_AddWidget(item, 1); + } + { + GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_3", LoadMRUCaller(g_load_mru3)); + gtk_widget_hide(GTK_WIDGET(item)); + MRU_AddWidget(item, 2); + } + { + GtkMenuItem* item = create_menu_item_with_mnemonic(menu, "_4", LoadMRUCaller(g_load_mru4)); + gtk_widget_hide(GTK_WIDGET(item)); + MRU_AddWidget(item, 3); + } +} + +#include "preferencesystem.h" +#include "stringio.h" + +void MRU_Construct() +{ + GlobalPreferenceSystem().registerPreference("Count", SizeImportStringCaller(MRU_used), SizeExportStringCaller(MRU_used)); + + for(std::size_t i = 0; i != MRU_MAX; ++i) + { + GlobalPreferenceSystem().registerPreference(MRU_keys[i], CopiedStringImportStringCaller(MRU_filenames[i]), CopiedStringExportStringCaller(MRU_filenames[i])); + } + + MRU_Init(); +} +void MRU_Destroy() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/mru.h b/misc/mediasource/netradiant-src/radiant/mru.h new file mode 100644 index 00000000..010e99b7 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/mru.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_MRU_H) +#define INCLUDED_MRU_H + +void MRU_AddFile (const char *str); + +typedef struct _GtkMenu GtkMenu; +void MRU_constructMenu(GtkMenu* menu); + +void MRU_Construct(); +void MRU_Destroy(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/multimon.cpp b/misc/mediasource/netradiant-src/radiant/multimon.cpp new file mode 100644 index 00000000..acc756fd --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/multimon.cpp @@ -0,0 +1,108 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "multimon.h" + +#include "debugging/debugging.h" + +#include "gtkutil/window.h" +#include "preferences.h" + + +multimon_globals_t g_multimon_globals; + +LatchedBool g_Multimon_enableSysMenuPopups(false, "Floating windows sysmenu icons"); + +void MultiMonitor_constructPreferences(PreferencesPage& page) +{ + GtkWidget* primary_monitor = page.appendCheckBox("Multi Monitor", "Start on Primary Monitor", g_multimon_globals.m_bStartOnPrimMon); + GtkWidget* popup = page.appendCheckBox( + "", "Disable system menu on popup windows", + LatchedBoolImportCaller(g_Multimon_enableSysMenuPopups), + BoolExportCaller(g_Multimon_enableSysMenuPopups.m_latched) + ); + Widget_connectToggleDependency(popup, primary_monitor); +} + +#include "preferencesystem.h" +#include "stringio.h" + +#include + +namespace +{ + GdkRectangle primaryMonitor; +} + +void PositionWindowOnPrimaryScreen(WindowPosition& position) +{ + if( position.w >= primaryMonitor.width - 12 ) + { + position.w = primaryMonitor.width - 12; + } + if( position.h >= primaryMonitor.height - 24 ) + { + position.h = primaryMonitor.height - 48; + } + if( position.x <= primaryMonitor.x || position.x + position.w >= (primaryMonitor.x + primaryMonitor.width) - 12 ) + { + position.x = primaryMonitor.x + 6; + } + if( position.y <= primaryMonitor.y || position.y + position.h >= (primaryMonitor.y + primaryMonitor.height) - 48 ) + { + position.y = primaryMonitor.y + 24; + } +} + +void MultiMon_Construct() +{ + // detect multiple monitors + + GdkScreen* screen = gdk_display_get_default_screen(gdk_display_get_default()); + gint m = gdk_screen_get_n_monitors(screen); + globalOutputStream() << "default screen has " << m << " monitors\n"; + for(int j = 0; j != m; ++j) + { + GdkRectangle geom; + gdk_screen_get_monitor_geometry(screen, j, &geom); + globalOutputStream() << "monitor " << j << " geometry: " << geom.x << ", " << geom.y << ", " << geom.width << ", " << geom.height << "\n"; + if(j == 0) + { + // I am making the assumption that monitor 0 is always the primary monitor on win32. Tested on WinXP with gtk+-2.4. + primaryMonitor = geom; + } + } + + if(m > 1) + { + g_multimon_globals.m_bStartOnPrimMon = true; + } + + GlobalPreferenceSystem().registerPreference("StartOnPrimMon", BoolImportStringCaller(g_multimon_globals.m_bStartOnPrimMon), BoolExportStringCaller(g_multimon_globals.m_bStartOnPrimMon)); + GlobalPreferenceSystem().registerPreference("NoSysMenuPopups", BoolImportStringCaller(g_Multimon_enableSysMenuPopups.m_latched), BoolExportStringCaller(g_Multimon_enableSysMenuPopups.m_latched)); + + g_Multimon_enableSysMenuPopups.useLatched(); + + PreferencesDialog_addInterfacePreferences(FreeCaller1()); +} +void MultiMon_Destroy() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/multimon.h b/misc/mediasource/netradiant-src/radiant/multimon.h new file mode 100644 index 00000000..f14d3633 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/multimon.h @@ -0,0 +1,53 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_MULTIMON_H) +#define INCLUDED_MULTIMON_H + +struct WindowPosition; + +void PositionWindowOnPrimaryScreen(WindowPosition& position); + +struct multimon_globals_t +{ + bool m_bStartOnPrimMon; + + multimon_globals_t() : + m_bStartOnPrimMon(false) + { + } +}; + +extern multimon_globals_t g_multimon_globals; + +#if defined(WIN32) +void MultiMon_Construct(); +void MultiMon_Destroy(); +#else +inline void MultiMon_Construct() +{ +} +inline void MultiMon_Destroy() +{ +} +#endif + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/nullmodel.cpp b/misc/mediasource/netradiant-src/radiant/nullmodel.cpp new file mode 100644 index 00000000..ed2333b4 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/nullmodel.cpp @@ -0,0 +1,214 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "nullmodel.h" + +#include "debugging/debugging.h" + +#include "iscenegraph.h" +#include "irender.h" +#include "iselection.h" +#include "iundo.h" +#include "ientity.h" +#include "ireference.h" +#include "igl.h" +#include "cullable.h" +#include "renderable.h" +#include "selectable.h" + +#include "math/frustum.h" +#include "scenelib.h" +#include "instancelib.h" +#include "entitylib.h" + +class NullModel : +public Bounded, +public Cullable +{ + Shader* m_state; + AABB m_aabb_local; + RenderableSolidAABB m_aabb_solid; + RenderableWireframeAABB m_aabb_wire; +public: + NullModel() : m_aabb_local(Vector3(0, 0, 0), Vector3(8, 8, 8)), m_aabb_solid(m_aabb_local), m_aabb_wire(m_aabb_local) + { + m_state = GlobalShaderCache().capture(""); + } + ~NullModel() + { + GlobalShaderCache().release(""); + } + + VolumeIntersectionValue intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const + { + return volume.TestAABB(m_aabb_local, localToWorld); + } + + const AABB& localAABB() const + { + return m_aabb_local; + } + + void renderSolid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + renderer.SetState(m_state, Renderer::eFullMaterials); + renderer.addRenderable(m_aabb_solid, localToWorld); + } + void renderWireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + renderer.addRenderable(m_aabb_wire, localToWorld); + } + + void testSelect(Selector& selector, SelectionTest& test, const Matrix4& localToWorld) + { + test.BeginMesh(localToWorld); + + SelectionIntersection best; + aabb_testselect(m_aabb_local, test, best); + if(best.valid()) + { + selector.addIntersection(best); + } + } +}; + +class NullModelInstance : public scene::Instance, public Renderable, public SelectionTestable +{ + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts() + { + InstanceContainedCast::install(m_casts); + InstanceContainedCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + } + InstanceTypeCastTable& get() + { + return m_casts; + } + }; + + NullModel& m_nullmodel; +public: + + typedef LazyStatic StaticTypeCasts; + + Bounded& get(NullType) + { + return m_nullmodel; + } + Cullable& get(NullType) + { + return m_nullmodel; + } + + NullModelInstance(const scene::Path& path, scene::Instance* parent, NullModel& nullmodel) : + Instance(path, parent, this, StaticTypeCasts::instance().get()), + m_nullmodel(nullmodel) + { + } + + void renderSolid(Renderer& renderer, const VolumeTest& volume) const + { + m_nullmodel.renderSolid(renderer, volume, Instance::localToWorld()); + } + void renderWireframe(Renderer& renderer, const VolumeTest& volume) const + { + m_nullmodel.renderWireframe(renderer, volume, Instance::localToWorld()); + } + + void testSelect(Selector& selector, SelectionTest& test) + { + m_nullmodel.testSelect(selector, test, Instance::localToWorld()); + } +}; + +class NullModelNode : public scene::Node::Symbiot, public scene::Instantiable +{ + class TypeCasts + { + NodeTypeCastTable m_casts; + public: + TypeCasts() + { + NodeStaticCast::install(m_casts); + } + NodeTypeCastTable& get() + { + return m_casts; + } + }; + + + scene::Node m_node; + InstanceSet m_instances; + NullModel m_nullmodel; +public: + + typedef LazyStatic StaticTypeCasts; + + NullModelNode() : m_node(this, this, StaticTypeCasts::instance().get()) + { + m_node.m_isRoot = true; + } + + void release() + { + delete this; + } + scene::Node& node() + { + return m_node; + } + + scene::Instance* create(const scene::Path& path, scene::Instance* parent) + { + return new NullModelInstance(path, parent, m_nullmodel); + } + 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); + } + scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) + { + return m_instances.erase(observer, path); + } +}; + +NodeSmartReference NewNullModel() +{ + return NodeSmartReference((new NullModelNode)->node()); +} + +void NullModel_construct() +{ +} +void NullModel_destroy() +{ +} + diff --git a/misc/mediasource/netradiant-src/radiant/nullmodel.h b/misc/mediasource/netradiant-src/radiant/nullmodel.h new file mode 100644 index 00000000..2713fb08 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/nullmodel.h @@ -0,0 +1,37 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (INCLUDED_NULLMODEL_H) +#define INCLUDED_NULLMODEL_H + +namespace scene +{ + class Node; +} + +#include "generic/referencecounted.h" +typedef SmartReference > NodeSmartReference; +NodeSmartReference NewNullModel(); + +void NullModel_construct(); +void NullModel_destroy(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/parse.cpp b/misc/mediasource/netradiant-src/radiant/parse.cpp new file mode 100644 index 00000000..8e3fd5c0 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/parse.cpp @@ -0,0 +1,51 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "parse.h" + +#include "script/scripttokeniser.h" +#include "script/scripttokenwriter.h" + +class ScriptLibraryAPI +{ + _QERScripLibTable m_scriptlibrary; +public: + typedef _QERScripLibTable Type; + STRING_CONSTANT(Name, "*"); + + ScriptLibraryAPI() + { + m_scriptlibrary.m_pfnNewScriptTokeniser = &NewScriptTokeniser; + m_scriptlibrary.m_pfnNewSimpleTokeniser = &NewSimpleTokeniser; + m_scriptlibrary.m_pfnNewSimpleTokenWriter = &NewSimpleTokenWriter; + } + _QERScripLibTable* getTable() + { + return &m_scriptlibrary; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule ScriptLibraryModule; +typedef Static StaticScriptLibraryModule; +StaticRegisterModule staticRegisterScriptLibrary(StaticScriptLibraryModule::instance()); diff --git a/misc/mediasource/netradiant-src/radiant/parse.h b/misc/mediasource/netradiant-src/radiant/parse.h new file mode 100644 index 00000000..3e64113e --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/parse.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_PARSE_H) +#define INCLUDED_PARSE_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/patch.cpp b/misc/mediasource/netradiant-src/radiant/patch.cpp new file mode 100644 index 00000000..ac96240f --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patch.cpp @@ -0,0 +1,2919 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "patch.h" + +#include +#include "preferences.h" +#include "brush_primit.h" +#include "signal/signal.h" + + +Signal0 g_patchTextureChangedCallbacks; + +void Patch_addTextureChangedCallback(const SignalHandler& handler) +{ + g_patchTextureChangedCallbacks.connectLast(handler); +} + +void Patch_textureChanged() +{ + g_patchTextureChangedCallbacks(); +} + + +Shader* PatchInstance::m_state_selpoint; +Shader* Patch::m_state_ctrl; +Shader* Patch::m_state_lattice; +EPatchType Patch::m_type; + + +std::size_t MAX_PATCH_WIDTH = 0; +std::size_t MAX_PATCH_HEIGHT = 0; + +int g_PatchSubdivideThreshold = 4; + +void BezierCurveTree_Delete(BezierCurveTree *pCurve) +{ + if(pCurve) + { + BezierCurveTree_Delete(pCurve->left); + BezierCurveTree_Delete(pCurve->right); + delete pCurve; + } +} + +std::size_t BezierCurveTree_Setup(BezierCurveTree *pCurve, std::size_t index, std::size_t stride) +{ + if(pCurve) + { + if(pCurve->left && pCurve->right) + { + index = BezierCurveTree_Setup(pCurve->left, index, stride); + pCurve->index = index*stride; + index++; + index = BezierCurveTree_Setup(pCurve->right, index, stride); + } + else + { + pCurve->index = BEZIERCURVETREE_MAX_INDEX; + } + } + + return index; +} + +bool BezierCurve_IsCurved(BezierCurve *pCurve) +{ + Vector3 vTemp(vector3_subtracted(pCurve->right, pCurve->left)); + Vector3 v1(vector3_subtracted(pCurve->crd, pCurve->left)); + Vector3 v2(vector3_subtracted(pCurve->right, pCurve->crd)); + + if(vector3_equal(v1, g_vector3_identity) || vector3_equal(vTemp, v1)) // return 0 if 1->2 == 0 or 1->2 == 1->3 + return false; + + vector3_normalise(v1); + vector3_normalise(v2); + if(vector3_equal(v1, v2)) + return false; + + Vector3 v3(vTemp); + const double width = vector3_length(v3); + vector3_scale(v3, 1.0 / width); + + if(vector3_equal(v1, v3) && vector3_equal(v2, v3)) + return false; + + const double angle = acos(vector3_dot(v1, v2)) / c_pi; + + const double index = width * angle; + + if(index > static_cast(g_PatchSubdivideThreshold)) + return true; + return false; +} + +void BezierInterpolate(BezierCurve *pCurve) +{ + pCurve->left = vector3_mid(pCurve->left, pCurve->crd); + pCurve->right = vector3_mid(pCurve->crd, pCurve->right); + pCurve->crd = vector3_mid(pCurve->left, pCurve->right); +} + +const std::size_t PATCH_MAX_SUBDIVISION_DEPTH = 16; + +void BezierCurveTree_FromCurveList(BezierCurveTree *pTree, GSList *pCurveList, std::size_t depth = 0) +{ + GSList *pLeftList = 0; + GSList *pRightList = 0; + BezierCurve *pCurve, *pLeftCurve, *pRightCurve; + bool bSplit = false; + + for (GSList *l = pCurveList; l; l = l->next) + { + pCurve = (BezierCurve *)(l->data); + if(bSplit || BezierCurve_IsCurved(pCurve)) + { + bSplit = true; + pLeftCurve = new BezierCurve; + pRightCurve = new BezierCurve; + pLeftCurve->left = pCurve->left; + pRightCurve->right = pCurve->right; + BezierInterpolate(pCurve); + pLeftCurve->crd = pCurve->left; + pRightCurve->crd = pCurve->right; + pLeftCurve->right = pCurve->crd; + pRightCurve->left = pCurve->crd; + + pLeftList = g_slist_prepend(pLeftList, pLeftCurve); + pRightList = g_slist_prepend(pRightList, pRightCurve); + } + } + + if(pLeftList != 0 && pRightList != 0 && depth != PATCH_MAX_SUBDIVISION_DEPTH) + { + pTree->left = new BezierCurveTree; + pTree->right = new BezierCurveTree; + BezierCurveTree_FromCurveList(pTree->left, pLeftList, depth + 1); + BezierCurveTree_FromCurveList(pTree->right, pRightList, depth + 1); + + for(GSList* l = pLeftList; l != 0; l = g_slist_next(l)) + { + delete (BezierCurve*)l->data; + } + + for(GSList* l = pRightList; l != 0; l = g_slist_next(l)) + { + delete (BezierCurve*)l->data; + } + + g_slist_free(pLeftList); + g_slist_free(pRightList); + } + else + { + pTree->left = 0; + pTree->right = 0; + } +} + + +int Patch::m_CycleCapIndex = 0; + + +void Patch::setDims (std::size_t w, std::size_t h) +{ + if((w%2)==0) + w -= 1; + ASSERT_MESSAGE(w <= MAX_PATCH_WIDTH, "patch too wide"); + if(w > MAX_PATCH_WIDTH) + w = MAX_PATCH_WIDTH; + else if(w < MIN_PATCH_WIDTH) + w = MIN_PATCH_WIDTH; + + if((h%2)==0) + m_height -= 1; + ASSERT_MESSAGE(h <= MAX_PATCH_HEIGHT, "patch too tall"); + if(h > MAX_PATCH_HEIGHT) + h = MAX_PATCH_HEIGHT; + else if(h < MIN_PATCH_HEIGHT) + h = MIN_PATCH_HEIGHT; + + m_width = w; m_height = h; + + if(m_width * m_height != m_ctrl.size()) + { + m_ctrl.resize(m_width * m_height); + onAllocate(m_ctrl.size()); + } +} + +inline const Colour4b& colour_for_index(std::size_t i, std::size_t width) +{ + return (i%2 || (i/width)%2) ? colour_inside : colour_corner; +} + +inline bool float_valid(float f) +{ + return f == f; +} + +bool Patch::isValid() const +{ + if(!m_width || !m_height) + { + return false; + } + + for(const_iterator i = m_ctrl.begin(); i != m_ctrl.end(); ++i) + { + if(!float_valid((*i).m_vertex.x()) + || !float_valid((*i).m_vertex.y()) + || !float_valid((*i).m_vertex.z()) + || !float_valid((*i).m_texcoord.x()) + || !float_valid((*i).m_texcoord.y())) + { + globalErrorStream() << "patch has invalid control points\n"; + return false; + } + } + return true; +} + +void Patch::UpdateCachedData() +{ + m_ctrl_vertices.clear(); + m_lattice_indices.clear(); + + if(!isValid()) + { + m_tess.m_numStrips = 0; + m_tess.m_lenStrips = 0; + m_tess.m_nArrayHeight = 0; + m_tess.m_nArrayWidth = 0; + m_tess.m_curveTreeU.resize(0); + m_tess.m_curveTreeV.resize(0); + m_tess.m_indices.resize(0); + m_tess.m_vertices.resize(0); + m_tess.m_arrayHeight.resize(0); + m_tess.m_arrayWidth.resize(0); + m_aabb_local = AABB(); + return; + } + + BuildTesselationCurves(ROW); + BuildTesselationCurves(COL); + BuildVertexArray(); + AccumulateBBox(); + + IndexBuffer ctrl_indices; + + m_lattice_indices.reserve(((m_width * (m_height - 1)) + (m_height * (m_width - 1))) << 1); + ctrl_indices.reserve(m_ctrlTransformed.size()); + { + UniqueVertexBuffer inserter(m_ctrl_vertices); + for(iterator i = m_ctrlTransformed.begin(); i != m_ctrlTransformed.end(); ++i) + { + ctrl_indices.insert(inserter.insert(pointvertex_quantised(PointVertex(reinterpret_cast((*i).m_vertex), colour_for_index(i - m_ctrlTransformed.begin(), m_width))))); + } + } + { + for(IndexBuffer::iterator i = ctrl_indices.begin(); i != ctrl_indices.end(); ++i) + { + if(std::size_t(i - ctrl_indices.begin()) % m_width) + { + m_lattice_indices.insert(*(i - 1)); + m_lattice_indices.insert(*i); + } + if(std::size_t(i - ctrl_indices.begin()) >= m_width) + { + m_lattice_indices.insert(*(i - m_width)); + m_lattice_indices.insert(*i); + } + } + } + +#if 0 + { + Array::iterator first = m_tess.m_indices.begin(); + for(std::size_t s=0; s::iterator last = first + m_tess.m_lenStrips; + + for(Array::iterator i(first); i+2 != last; i += 2) + { + ArbitraryMeshTriangle_sumTangents(m_tess.m_vertices[*(i+0)], m_tess.m_vertices[*(i+1)], m_tess.m_vertices[*(i+2)]); + ArbitraryMeshTriangle_sumTangents(m_tess.m_vertices[*(i+2)], m_tess.m_vertices[*(i+1)], m_tess.m_vertices[*(i+3)]); + } + + first = last; + } + + for(Array::iterator i = m_tess.m_vertices.begin(); i != m_tess.m_vertices.end(); ++i) + { + vector3_normalise(reinterpret_cast((*i).tangent)); + vector3_normalise(reinterpret_cast((*i).bitangent)); + } + } +#endif + + SceneChangeNotify(); +} + +void Patch::InvertMatrix() +{ + undoSave(); + + PatchControlArray_invert(m_ctrl, m_width, m_height); + + controlPointsChanged(); +} + +void Patch::TransposeMatrix() +{ + undoSave(); + + { + Array tmp(m_width * m_height); + copy_ctrl(tmp.data(), m_ctrl.data(), m_ctrl.data() + m_width * m_height); + + PatchControlIter from = tmp.data(); + for(std::size_t h = 0; h != m_height; ++h) + { + PatchControlIter to = m_ctrl.data() + h; + for(std::size_t w = 0; w != m_width; ++w, ++from, to += m_height) + { + *to = *from; + } + } + } + + { + std::size_t tmp = m_width; + m_width = m_height; + m_height = tmp; + } + + controlPointsChanged(); +} + +void Patch::Redisperse(EMatrixMajor mt) +{ + std::size_t w, h, width, height, row_stride, col_stride; + PatchControl* p1, * p2, * p3; + + undoSave(); + + switch(mt) + { + case COL: + width = (m_width-1)>>1; + height = m_height; + col_stride = 1; + row_stride = m_width; + break; + case ROW: + width = (m_height-1)>>1; + height = m_width; + col_stride = m_width; + row_stride = 1; + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return; + } + + for(h=0;hm_vertex = vector3_mid(p1->m_vertex, p3->m_vertex); + p1 = p3; + } + } + + controlPointsChanged(); +} + +void Patch::Smooth(EMatrixMajor mt) +{ + std::size_t w, h, width, height, row_stride, col_stride; + bool wrap; + PatchControl* p1, * p2, * p3, * p2b; + + undoSave(); + + switch(mt) + { + case COL: + width = (m_width-1)>>1; + height = m_height; + col_stride = 1; + row_stride = m_width; + break; + case ROW: + width = (m_height-1)>>1; + height = m_width; + col_stride = m_width; + row_stride = 1; + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return; + } + + wrap = true; + for(h=0;hm_vertex << " and " << p2->m_vertex << "\n"; + if(vector3_length_squared(vector3_subtracted(p1->m_vertex, p2->m_vertex)) > 1.0) + { + //globalErrorStream() << "too far\n"; + wrap = false; + break; + } + } + + for(h=0;hm_vertex = vector3_mid(p1->m_vertex, p3->m_vertex); + p1 = p3; + } + if(wrap) + { + p1 = m_ctrl.data()+(h*row_stride)+(2*width-1)*col_stride; + p2 = m_ctrl.data()+(h*row_stride); + p2b = m_ctrl.data()+(h*row_stride)+(2*width)*col_stride; + p3 = m_ctrl.data()+(h*row_stride)+col_stride; + p2->m_vertex = p2b->m_vertex = vector3_mid(p1->m_vertex, p3->m_vertex); + } + } + + controlPointsChanged(); +} + +void Patch::InsertRemove(bool bInsert, bool bColumn, bool bFirst) +{ + undoSave(); + + if(bInsert) + { + if(bColumn && (m_width + 2 <= MAX_PATCH_WIDTH)) + InsertPoints(COL, bFirst); + else if(m_height + 2 <= MAX_PATCH_HEIGHT) + InsertPoints(ROW, bFirst); + } + else + { + if(bColumn && (m_width - 2 >= MIN_PATCH_WIDTH)) + RemovePoints(COL, bFirst); + else if(m_height - 2 >= MIN_PATCH_HEIGHT) + RemovePoints(ROW, bFirst); + } + + controlPointsChanged(); +} + +Patch* Patch::MakeCap(Patch* patch, EPatchCap eType, EMatrixMajor mt, bool bFirst) +{ + std::size_t i, width, height; + + switch(mt) + { + case ROW: + width = m_width; + height = m_height; + break; + case COL: + width = m_height; + height = m_width; + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return 0; + } + + Array p(width); + + std::size_t nIndex = (bFirst) ? 0 : height-1; + if(mt == ROW) + { + for (i=0; iConstructSeam(eType, p.data(), width); + return patch; +} + +void Patch::FlipTexture(int nAxis) +{ + undoSave(); + + for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) + { + (*i).m_texcoord[nAxis] = -(*i).m_texcoord[nAxis]; + } + + controlPointsChanged(); +} + +void Patch::TranslateTexture(float s, float t) +{ + undoSave(); + + s = -1 * s / m_state->getTexture().width; + t = t / m_state->getTexture().height; + + for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) + { + (*i).m_texcoord[0] += s; + (*i).m_texcoord[1] += t; + } + + controlPointsChanged(); +} + +void Patch::ScaleTexture(float s, float t) +{ + undoSave(); + + for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) + { + (*i).m_texcoord[0] *= s; + (*i).m_texcoord[1] *= t; + } + + controlPointsChanged(); +} + +void Patch::RotateTexture(float angle) +{ + undoSave(); + + const float s = static_cast(sin(degrees_to_radians(angle))); + const float c = static_cast(cos(degrees_to_radians(angle))); + + for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) + { + const float x = (*i).m_texcoord[0]; + const float y = (*i).m_texcoord[1]; + (*i).m_texcoord[0] = (x * c) - (y * s); + (*i).m_texcoord[1] = (y * c) + (x * s); + } + + controlPointsChanged(); +} + + +void Patch::SetTextureRepeat(float s, float t) +{ + std::size_t w, h; + float si, ti, sc, tc; + PatchControl *pDest; + + undoSave(); + + si = s / (float)(m_width - 1); + ti = t / (float)(m_height - 1); + + pDest = m_ctrl.data(); + for (h=0, tc = 0.0f; hm_texcoord[0] = sc; + pDest->m_texcoord[1] = tc; + pDest++; + } + } + + controlPointsChanged(); +} + +/* +void Patch::SetTextureInfo(texdef_t *pt) +{ + if(pt->getShift()[0] || pt->getShift()[1]) + TranslateTexture (pt->getShift()[0], pt->getShift()[1]); + else if(pt->getScale()[0] || pt->getScale()[1]) + { + if(pt->getScale()[0] == 0.0f) pt->setScale(0, 1.0f); + if(pt->getScale()[1] == 0.0f) pt->setScale(1, 1.0f); + ScaleTexture (pt->getScale()[0], pt->getScale()[1]); + } + else if(pt->rotate) + RotateTexture (pt->rotate); +} +*/ + +inline int texture_axis(const Vector3& normal) +{ + // axis dominance order: Z, X, Y + return (normal.x() >= normal.y()) ? (normal.x() > normal.z()) ? 0 : 2 : (normal.y() > normal.z()) ? 1 : 2; +} + +void Patch::CapTexture() +{ + const PatchControl& p1 = m_ctrl[m_width]; + const PatchControl& p2 = m_ctrl[m_width*(m_height-1)]; + const PatchControl& p3 = m_ctrl[(m_width*m_height)-1]; + + + Vector3 normal(g_vector3_identity); + + { + Vector3 tmp(vector3_cross( + vector3_subtracted(p2.m_vertex, m_ctrl[0].m_vertex), + vector3_subtracted(p3.m_vertex, m_ctrl[0].m_vertex) + )); + if(!vector3_equal(tmp, g_vector3_identity)) + { + vector3_add(normal, tmp); + } + } + { + Vector3 tmp(vector3_cross( + vector3_subtracted(p1.m_vertex, p3.m_vertex), + vector3_subtracted(m_ctrl[0].m_vertex, p3.m_vertex) + )); + if(!vector3_equal(tmp, g_vector3_identity)) + { + vector3_add(normal, tmp); + } + } + + ProjectTexture(texture_axis(normal)); +} + +// uses longest parallel chord to calculate texture coords for each row/col +void Patch::NaturalTexture() +{ + undoSave(); + + { + float fSize = (float)m_state->getTexture().width * Texdef_getDefaultTextureScale(); + + double texBest = 0; + double tex = 0; + PatchControl* pWidth = m_ctrl.data(); + for (std::size_t w=0; wm_texcoord[0] = static_cast(tex); + } + + if(w+1 == m_width) + break; + + { + PatchControl* pHeight = pWidth; + for (std::size_t h=0; hm_vertex, (pHeight+1)->m_vertex)); + double length = tex + (vector3_length(v) / fSize); + if(fabs(length) > texBest) texBest = length; + } + } + + tex=texBest; + } + } + + { + float fSize = -(float)m_state->getTexture().height * Texdef_getDefaultTextureScale(); + + double texBest = 0; + double tex = 0; + PatchControl* pHeight = m_ctrl.data(); + for (std::size_t h=0; hm_texcoord[1] = static_cast(tex); + } + + if(h+1 == m_height) + break; + + { + PatchControl* pWidth = pHeight; + for (std::size_t w=0; wm_vertex, (pWidth+m_width)->m_vertex)); + double length = tex + (vector3_length(v) / fSize); + if(fabs(length) > texBest) texBest = length; + } + } + + tex=texBest; + } + } + + controlPointsChanged(); +} + + + +// private: + +void Patch::AccumulateBBox() +{ + m_aabb_local = AABB(); + + for(PatchControlArray::iterator i = m_ctrlTransformed.begin(); i != m_ctrlTransformed.end(); ++i) + { + aabb_extend_by_point_safe(m_aabb_local, (*i).m_vertex); + } + + m_boundsChanged(); + m_lightsChanged(); +} + +void Patch::InsertPoints(EMatrixMajor mt, bool bFirst) +{ + std::size_t width, height, row_stride, col_stride; + + switch(mt) + { + case ROW: + col_stride = 1; + row_stride = m_width; + width = m_width; + height = m_height; + break; + case COL: + col_stride = m_width; + row_stride = 1; + width = m_height; + height = m_width; + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return; + } + + std::size_t pos = 0; + { + PatchControl* p1 = m_ctrl.data(); + /* + if(GlobalSelectionSystem().countSelected() != 0) + { + scene::Instance& instance = GlobalSelectionSystem().ultimateSelected(); + PatchInstance* patch = Instance_getPatch(instance); + patch->m_selectable.isSelected(); + } + */ + for(std::size_t w = 0; w != width; ++w, p1 += col_stride) + { + { + PatchControl* p2 = p1; + for(std::size_t h = 1; h < height; h += 2, p2 += 2 * row_stride) + { + if(0)//p2->m_selectable.isSelected()) + { + pos = h; + break; + } + } + if(pos != 0) + { + break; + } + } + + { + PatchControl* p2 = p1; + for(std::size_t h = 0; h < height; h += 2, p2 += 2 * row_stride) + { + if(0)//p2->m_selectable.isSelected()) + { + pos = h; + break; + } + } + if(pos != 0) + { + break; + } + } + } + } + + Array tmp(m_ctrl); + + std::size_t row_stride2, col_stride2; + switch(mt) + { + case ROW: + setDims(m_width, m_height+2); + col_stride2 = 1; + row_stride2 = m_width; + break; + case COL: + setDims(m_width+2, m_height); + col_stride2 = m_width; + row_stride2 = 1; + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return; + } + if(bFirst) + { + pos = height - 1; + } + else + { + pos = 2; + } + + if(pos >= height) + { + if(bFirst) + { + pos = height - 1; + } + else + { + pos = 2; + } + } + else if(pos == 0) + { + pos = 2; + } + else if(pos % 2) + { + ++pos; + } + + + for(std::size_t w = 0; w != width; ++w) + { + PatchControl* p1 = tmp.data() + (w*col_stride); + PatchControl* p2 = m_ctrl.data() + (w*col_stride2); + for(std::size_t h = 0; h != height; ++h, p2 += row_stride2, p1 += row_stride) + { + if(h == pos) + { + p2 += 2 * row_stride2; + } + *p2 = *p1; + } + + p1 = tmp.data() + (w*col_stride+pos*row_stride); + p2 = m_ctrl.data() + (w*col_stride2+pos*row_stride2); + + PatchControl* r2a = (p2+row_stride2); + PatchControl* r2b = (p2-row_stride2); + PatchControl* c2a = (p1-2*row_stride); + PatchControl* c2b = (p1-row_stride); + + // set two new row points + *(p2+2*row_stride2) = *p1; + *r2a = *c2b; + + for(std::size_t i = 0; i != 3; ++i) + { + r2a->m_vertex[i] = float_mid(c2b->m_vertex[i], p1->m_vertex[i]); + + r2b->m_vertex[i] = float_mid(c2a->m_vertex[i], c2b->m_vertex[i]); + + p2->m_vertex[i] = float_mid(r2a->m_vertex[i], r2b->m_vertex[i]); + } + for(std::size_t i = 0; i != 2; ++i) + { + r2a->m_texcoord[i] = float_mid(c2b->m_texcoord[i], p1->m_texcoord[i]); + + r2b->m_texcoord[i] = float_mid(c2a->m_texcoord[i], c2b->m_texcoord[i]); + + p2->m_texcoord[i] = float_mid(r2a->m_texcoord[i], r2b->m_texcoord[i]); + } + } +} + +void Patch::RemovePoints(EMatrixMajor mt, bool bFirst) +{ + std::size_t width, height, row_stride, col_stride; + + switch(mt) + { + case ROW: + col_stride = 1; + row_stride = m_width; + width = m_width; + height = m_height; + break; + case COL: + col_stride = m_width; + row_stride = 1; + width = m_height; + height = m_width; + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return; + } + + std::size_t pos = 0; + { + PatchControl* p1 = m_ctrl.data(); + for(std::size_t w = 0; w != width; ++w, p1 += col_stride) + { + { + PatchControl* p2 = p1; + for(std::size_t h=1; h < height; h += 2, p2 += 2 * row_stride) + { + if(0)//p2->m_selectable.isSelected()) + { + pos = h; + break; + } + } + if(pos != 0) + { + break; + } + } + + { + PatchControl* p2 = p1; + for(std::size_t h=0; h < height; h += 2, p2 += 2 * row_stride) + { + if(0)//p2->m_selectable.isSelected()) + { + pos = h; + break; + } + } + if(pos != 0) + { + break; + } + } + } + } + + Array tmp(m_ctrl); + + std::size_t row_stride2, col_stride2; + switch(mt) + { + case ROW: + setDims(m_width, m_height-2); + col_stride2 = 1; + row_stride2 = m_width; + break; + case COL: + setDims(m_width-2, m_height); + col_stride2 = m_width; + row_stride2 = 1; + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return; + } + if(bFirst) + { + pos=height-3; + } + else + { + pos=2; + } + if(pos >= height) + { + if(bFirst) + { + pos=height-3; + } + else + { + pos=2; + } + } + else if(pos == 0) + { + pos=2; + } + else if(pos > height - 3) + { + pos = height - 3; + } + else if(pos % 2) + { + ++pos; + } + + for(std::size_t w = 0; w != width; w++) + { + PatchControl* p1 = tmp.data() + (w*col_stride); + PatchControl* p2 = m_ctrl.data() + (w*col_stride2); + for(std::size_t h = 0; h != height; ++h, p2 += row_stride2, p1 += row_stride) + { + if(h == pos) + { + p1 += 2 * row_stride2; h += 2; + } + *p2 = *p1; + } + + p1 = tmp.data() + (w*col_stride+pos*row_stride); + p2 = m_ctrl.data() + (w*col_stride2+pos*row_stride2); + + for(std::size_t i=0; i<3; i++) + { + (p2-row_stride2)->m_vertex[i] = ((p1+2*row_stride)->m_vertex[i]+(p1-2*row_stride)->m_vertex[i]) * 0.5f; + + (p2-row_stride2)->m_vertex[i] = (p2-row_stride2)->m_vertex[i]+(2.0f * ((p1)->m_vertex[i]-(p2-row_stride2)->m_vertex[i])); + } + for(std::size_t i=0; i<2; i++) + { + (p2-row_stride2)->m_texcoord[i] = ((p1+2*row_stride)->m_texcoord[i]+(p1-2*row_stride)->m_texcoord[i]) * 0.5f; + + (p2-row_stride2)->m_texcoord[i] = (p2-row_stride2)->m_texcoord[i]+(2.0f * ((p1)->m_texcoord[i]-(p2-row_stride2)->m_texcoord[i])); + } + } +} + +void Patch::ConstructSeam(EPatchCap eType, Vector3* p, std::size_t width) +{ + switch(eType) + { + case eCapIBevel: + { + setDims(3, 3); + m_ctrl[0].m_vertex = p[0]; + m_ctrl[1].m_vertex = p[1]; + m_ctrl[2].m_vertex = p[1]; + m_ctrl[3].m_vertex = p[1]; + m_ctrl[4].m_vertex = p[1]; + m_ctrl[5].m_vertex = p[1]; + m_ctrl[6].m_vertex = p[2]; + m_ctrl[7].m_vertex = p[1]; + m_ctrl[8].m_vertex = p[1]; + } + break; + case eCapBevel: + { + setDims(3, 3); + Vector3 p3(vector3_added(p[2], vector3_subtracted(p[0], p[1]))); + m_ctrl[0].m_vertex = p3; + m_ctrl[1].m_vertex = p3; + m_ctrl[2].m_vertex = p[2]; + m_ctrl[3].m_vertex = p3; + m_ctrl[4].m_vertex = p3; + m_ctrl[5].m_vertex = p[1]; + m_ctrl[6].m_vertex = p3; + m_ctrl[7].m_vertex = p3; + m_ctrl[8].m_vertex = p[0]; + } + break; + case eCapEndCap: + { + Vector3 p5(vector3_mid(p[0], p[4])); + + setDims(3, 3); + m_ctrl[0].m_vertex = p[0]; + m_ctrl[1].m_vertex = p5; + m_ctrl[2].m_vertex = p[4]; + m_ctrl[3].m_vertex = p[1]; + m_ctrl[4].m_vertex = p[2]; + m_ctrl[5].m_vertex = p[3]; + m_ctrl[6].m_vertex = p[2]; + m_ctrl[7].m_vertex = p[2]; + m_ctrl[8].m_vertex = p[2]; + } + break; + case eCapIEndCap: + { + setDims(5, 3); + m_ctrl[0].m_vertex = p[4]; + m_ctrl[1].m_vertex = p[3]; + m_ctrl[2].m_vertex = p[2]; + m_ctrl[3].m_vertex = p[1]; + m_ctrl[4].m_vertex = p[0]; + m_ctrl[5].m_vertex = p[3]; + m_ctrl[6].m_vertex = p[3]; + m_ctrl[7].m_vertex = p[2]; + m_ctrl[8].m_vertex = p[1]; + m_ctrl[9].m_vertex = p[1]; + m_ctrl[10].m_vertex = p[3]; + m_ctrl[11].m_vertex = p[3]; + m_ctrl[12].m_vertex = p[2]; + m_ctrl[13].m_vertex = p[1]; + m_ctrl[14].m_vertex = p[1]; + } + break; + case eCapCylinder: + { + std::size_t mid = (width - 1) >> 1; + + bool degenerate = (mid % 2) != 0; + + std::size_t newHeight = mid + (degenerate ? 2 : 1); + + setDims(3, newHeight); + + if(degenerate) + { + ++mid; + for(std::size_t i = width; i != width + 2; ++i) + { + p[i] = p[width - 1]; + } + } + + { + PatchControl* pCtrl = m_ctrl.data(); + for(std::size_t i = 0; i != m_height; ++i, pCtrl += m_width) + { + pCtrl->m_vertex = p[i]; + } + } + { + PatchControl* pCtrl = m_ctrl.data() + 2; + std::size_t h = m_height - 1; + for(std::size_t i = 0; i != m_height; ++i, pCtrl += m_width) + { + pCtrl->m_vertex = p[h + (h - i)]; + } + } + + Redisperse(COL); + } + break; + default: + ERROR_MESSAGE("invalid patch-cap type"); + return; + } + CapTexture(); + controlPointsChanged(); +} + +void Patch::ProjectTexture(int nAxis) +{ + undoSave(); + + int s, t; + + switch (nAxis) + { + case 2: + s = 0; + t = 1; + break; + case 0: + s = 1; + t = 2; + break; + case 1: + s = 0; + t = 2; + break; + default: + ERROR_MESSAGE("invalid axis"); + return; + } + + float fWidth = 1 / (m_state->getTexture().width * Texdef_getDefaultTextureScale()); + float fHeight = 1 / (m_state->getTexture().height * -Texdef_getDefaultTextureScale()); + + for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) + { + (*i).m_texcoord[0] = (*i).m_vertex[s] * fWidth; + (*i).m_texcoord[1] = (*i).m_vertex[t] * fHeight; + } + + controlPointsChanged(); +} + +void Patch::constructPlane(const AABB& aabb, int axis, std::size_t width, std::size_t height) +{ + setDims(width, height); + + int x, y, z; + switch(axis) + { + case 2: x=0; y=1; z=2; break; + case 1: x=0; y=2; z=1; break; + case 0: x=1; y=2; z=0; break; + default: + ERROR_MESSAGE("invalid view-type"); + return; + } + + if(m_width < MIN_PATCH_WIDTH || m_width > MAX_PATCH_WIDTH) m_width = 3; + if(m_height < MIN_PATCH_HEIGHT || m_height > MAX_PATCH_HEIGHT) m_height = 3; + + Vector3 vStart; + vStart[x] = aabb.origin[x] - aabb.extents[x]; + vStart[y] = aabb.origin[y] - aabb.extents[y]; + vStart[z] = aabb.origin[z]; + + float xAdj = fabsf((vStart[x] - (aabb.origin[x] + aabb.extents[x])) / (float)(m_width - 1)); + float yAdj = fabsf((vStart[y] - (aabb.origin[y] + aabb.extents[y])) / (float)(m_height - 1)); + + Vector3 vTmp; + vTmp[z] = vStart[z]; + PatchControl* pCtrl = m_ctrl.data(); + + vTmp[y]=vStart[y]; + for (std::size_t h=0; hm_vertex = vTmp; + vTmp[x]+=xAdj; + } + vTmp[y]+=yAdj; + } + + NaturalTexture(); +} + +void Patch::ConstructPrefab(const AABB& aabb, EPatchPrefab eType, int axis, std::size_t width, std::size_t height) +{ + Vector3 vPos[3]; + + if(eType != ePlane) + { + vPos[0] = vector3_subtracted(aabb.origin, aabb.extents); + vPos[1] = aabb.origin; + vPos[2] = vector3_added(aabb.origin, aabb.extents); + } + + if(eType == ePlane) + { + constructPlane(aabb, axis, width, height); + } + else if(eType == eSqCylinder + || eType == eCylinder + || eType == eDenseCylinder + || eType == eVeryDenseCylinder + || eType == eCone + || eType == eSphere) + { + unsigned char *pIndex; + unsigned char pCylIndex[] = + { + 0, 0, + 1, 0, + 2, 0, + 2, 1, + 2, 2, + 1, 2, + 0, 2, + 0, 1, + 0, 0 + }; + + + PatchControl *pStart; + switch(eType) + { + case eSqCylinder: setDims(9, 3); + pStart = m_ctrl.data(); + break; + case eDenseCylinder: + case eVeryDenseCylinder: + case eCylinder: + setDims(9, 3); + pStart = m_ctrl.data() + 1; + break; + case eCone: setDims(9, 3); + pStart = m_ctrl.data() + 1; + break; + case eSphere: + setDims(9, 5); + pStart = m_ctrl.data() + (9+1); + break; + default: + ERROR_MESSAGE("this should be unreachable"); + return; + } + + for(std::size_t h=0; h<3; h++, pStart+=9) + { + pIndex = pCylIndex; + PatchControl* pCtrl = pStart; + for(std::size_t w=0; w<8; w++, pCtrl++) + { + pCtrl->m_vertex[0] = vPos[pIndex[0]][0]; + pCtrl->m_vertex[1] = vPos[pIndex[1]][1]; + pCtrl->m_vertex[2] = vPos[h][2]; + pIndex+=2; + } + } + + switch(eType) + { + case eSqCylinder: + { + PatchControl* pCtrl=m_ctrl.data(); + for(std::size_t h=0; h<3; h++, pCtrl+=9) + { + pCtrl[8].m_vertex = pCtrl[0].m_vertex; + } + } + break; + case eDenseCylinder: + case eVeryDenseCylinder: + case eCylinder: + { + PatchControl* pCtrl=m_ctrl.data(); + for (std::size_t h=0; h<3; h++, pCtrl+=9) + { + pCtrl[0].m_vertex = pCtrl[8].m_vertex; + } + } + break; + case eCone: + { + PatchControl* pCtrl=m_ctrl.data(); + for (std::size_t h=0; h<2; h++, pCtrl+=9) + { + pCtrl[0].m_vertex = pCtrl[8].m_vertex; + } + } + { + PatchControl* pCtrl=m_ctrl.data()+9*2; + for (std::size_t w=0; w<9; w++, pCtrl++) + { + pCtrl->m_vertex[0] = vPos[1][0]; + pCtrl->m_vertex[1] = vPos[1][1]; + pCtrl->m_vertex[2] = vPos[2][2]; + } + } + break; + case eSphere: + { + PatchControl* pCtrl=m_ctrl.data()+9; + for (std::size_t h=0; h<3; h++, pCtrl+=9) + { + pCtrl[0].m_vertex = pCtrl[8].m_vertex; + } + } + { + PatchControl* pCtrl = m_ctrl.data(); + for (std::size_t w=0; w<9; w++, pCtrl++) + { + pCtrl->m_vertex[0] = vPos[1][0]; + pCtrl->m_vertex[1] = vPos[1][1]; + pCtrl->m_vertex[2] = vPos[0][2]; + } + } + { + PatchControl* pCtrl = m_ctrl.data()+(9*4); + for (std::size_t w=0; w<9; w++, pCtrl++) + { + pCtrl->m_vertex[0] = vPos[1][0]; + pCtrl->m_vertex[1] = vPos[1][1]; + pCtrl->m_vertex[2] = vPos[2][2]; + } + } + break; + default: + ERROR_MESSAGE("this should be unreachable"); + return; + } + } + else if (eType == eBevel) + { + unsigned char *pIndex; + unsigned char pBevIndex[] = + { + 0, 0, + 2, 0, + 2, 2, + }; + + setDims(3, 3); + + PatchControl* pCtrl = m_ctrl.data(); + for(std::size_t h=0; h<3; h++) + { + pIndex=pBevIndex; + for(std::size_t w=0; w<3; w++, pIndex+=2, pCtrl++) + { + pCtrl->m_vertex[0] = vPos[pIndex[0]][0]; + pCtrl->m_vertex[1] = vPos[pIndex[1]][1]; + pCtrl->m_vertex[2] = vPos[h][2]; + } + } + } + else if(eType == eEndCap) + { + unsigned char *pIndex; + unsigned char pEndIndex[] = + { + 2, 0, + 2, 2, + 1, 2, + 0, 2, + 0, 0, + }; + + setDims(5, 3); + + PatchControl* pCtrl = m_ctrl.data(); + for(std::size_t h=0; h<3; h++) + { + pIndex=pEndIndex; + for(std::size_t w=0; w<5; w++, pIndex+=2, pCtrl++) + { + pCtrl->m_vertex[0] = vPos[pIndex[0]][0]; + pCtrl->m_vertex[1] = vPos[pIndex[1]][1]; + pCtrl->m_vertex[2] = vPos[h][2]; + } + } + } + + if(eType == eDenseCylinder) + { + InsertRemove(true, false, true); + } + + if(eType == eVeryDenseCylinder) + { + InsertRemove(true, false, false); + InsertRemove(true, false, true); + } + + NaturalTexture(); +} + +void Patch::RenderDebug(RenderStateFlags state) const +{ + for (std::size_t i = 0; inormal)); + glTexCoord2fv(texcoord2f_to_array((m_tess.m_vertices.data() + m_tess.m_indices[i*m_tess.m_lenStrips+j])->texcoord)); + glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + m_tess.m_indices[i*m_tess.m_lenStrips+j])->vertex)); + } + glEnd(); + } +} + +void RenderablePatchSolid::RenderNormals() const +{ + const std::size_t width = m_tess.m_numStrips+1; + const std::size_t height = m_tess.m_lenStrips>>1; + glBegin(GL_LINES); + for(std::size_t i=0;ivertex), + vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->normal), 8) + ) + ); + glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex)); + glVertex3fv(&vNormal[0]); + } + { + Vector3 vNormal( + vector3_added( + vertex3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->vertex), + vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->tangent), 8) + ) + ); + glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex)); + glVertex3fv(&vNormal[0]); + } + { + Vector3 vNormal( + vector3_added( + vertex3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->vertex), + vector3_scaled(normal3f_to_vector3((m_tess.m_vertices.data() + (j*width+i))->bitangent), 8) + ) + ); + glVertex3fv(vertex3f_to_array((m_tess.m_vertices.data() + (j*width+i))->vertex)); + glVertex3fv(&vNormal[0]); + } + } + } + glEnd(); +} + +#define DEGEN_0a 0x01 +#define DEGEN_1a 0x02 +#define DEGEN_2a 0x04 +#define DEGEN_0b 0x08 +#define DEGEN_1b 0x10 +#define DEGEN_2b 0x20 +#define SPLIT 0x40 +#define AVERAGE 0x80 + + +unsigned int subarray_get_degen(PatchControlIter subarray, std::size_t strideU, std::size_t strideV) +{ + unsigned int nDegen = 0; + const PatchControl* p1; + const PatchControl* p2; + + p1 = subarray; + p2 = p1 + strideU; + if(vector3_equal(p1->m_vertex, p2->m_vertex)) + nDegen |= DEGEN_0a; + p1 = p2; + p2 = p1 + strideU; + if(vector3_equal(p1->m_vertex, p2->m_vertex)) + nDegen |= DEGEN_0b; + + p1 = subarray + strideV; + p2 = p1 + strideU; + if(vector3_equal(p1->m_vertex, p2->m_vertex)) + nDegen |= DEGEN_1a; + p1 = p2; + p2 = p1 + strideU; + if(vector3_equal(p1->m_vertex, p2->m_vertex)) + nDegen |= DEGEN_1b; + + p1 = subarray + (strideV << 1); + p2 = p1 + strideU; + if(vector3_equal(p1->m_vertex, p2->m_vertex)) + nDegen |= DEGEN_2a; + p1 = p2; + p2 = p1 + strideU; + if(vector3_equal(p1->m_vertex, p2->m_vertex)) + nDegen |= DEGEN_2b; + + return nDegen; +} + + +inline void deCasteljau3(const Vector3& P0, const Vector3& P1, const Vector3& P2, Vector3& P01, Vector3& P12, Vector3& P012) +{ + P01 = vector3_mid(P0, P1); + P12 = vector3_mid(P1, P2); + P012 = vector3_mid(P01, P12); +} + +inline void BezierInterpolate3( const Vector3& start, Vector3& left, Vector3& mid, Vector3& right, const Vector3& end ) +{ + left = vector3_mid(start, mid); + right = vector3_mid(mid, end); + mid = vector3_mid(left, right); +} + +inline void BezierInterpolate2( const Vector2& start, Vector2& left, Vector2& mid, Vector2& right, const Vector2& end ) +{ + left[0]= float_mid(start[0], mid[0]); + left[1] = float_mid(start[1], mid[1]); + right[0] = float_mid(mid[0], end[0]); + right[1] = float_mid(mid[1], end[1]); + mid[0] = float_mid(left[0], right[0]); + mid[1] = float_mid(left[1], right[1]); +} + + +inline Vector2& texcoord_for_index(Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].texcoord); +} + +inline Vector3& vertex_for_index(Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].vertex); +} + +inline Vector3& normal_for_index(Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].normal); +} + +inline Vector3& tangent_for_index(Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].tangent); +} + +inline Vector3& bitangent_for_index(Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].bitangent); +} + +inline const Vector2& texcoord_for_index(const Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].texcoord); +} + +inline const Vector3& vertex_for_index(const Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].vertex); +} + +inline const Vector3& normal_for_index(const Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].normal); +} + +inline const Vector3& tangent_for_index(const Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].tangent); +} + +inline const Vector3& bitangent_for_index(const Array& vertices, std::size_t index) +{ + return reinterpret_cast(vertices[index].bitangent); +} + +#include "math/curve.h" + +inline PatchControl QuadraticBezier_evaluate(const PatchControl* firstPoint, double t) +{ + PatchControl result = { Vector3(0, 0, 0), Vector2(0, 0) }; + double denominator = 0; + + { + double weight = BernsteinPolynomial::apply(t); + vector3_add(result.m_vertex, vector3_scaled(firstPoint[0].m_vertex, weight)); + vector2_add(result.m_texcoord, vector2_scaled(firstPoint[0].m_texcoord, weight)); + denominator += weight; + } + { + double weight = BernsteinPolynomial::apply(t); + vector3_add(result.m_vertex, vector3_scaled(firstPoint[1].m_vertex, weight)); + vector2_add(result.m_texcoord, vector2_scaled(firstPoint[1].m_texcoord, weight)); + denominator += weight; + } + { + double weight = BernsteinPolynomial::apply(t); + vector3_add(result.m_vertex, vector3_scaled(firstPoint[2].m_vertex, weight)); + vector2_add(result.m_texcoord, vector2_scaled(firstPoint[2].m_texcoord, weight)); + denominator += weight; + } + + vector3_divide(result.m_vertex, denominator); + vector2_divide(result.m_texcoord, denominator); + return result; +} + +inline Vector3 vector3_linear_interpolated(const Vector3& a, const Vector3& b, double t) +{ + return vector3_added(vector3_scaled(a, 1.0 - t), vector3_scaled(b, t)); +} + +inline Vector2 vector2_linear_interpolated(const Vector2& a, const Vector2& b, double t) +{ + return vector2_added(vector2_scaled(a, 1.0 - t), vector2_scaled(b, t)); +} + +void normalise_safe(Vector3& normal) +{ + if(!vector3_equal(normal, g_vector3_identity)) + { + vector3_normalise(normal); + } +} + +inline void QuadraticBezier_evaluate(const PatchControl& a, const PatchControl& b, const PatchControl& c, double t, PatchControl& point, PatchControl& left, PatchControl& right) +{ + left.m_vertex = vector3_linear_interpolated(a.m_vertex, b.m_vertex, t); + left.m_texcoord = vector2_linear_interpolated(a.m_texcoord, b.m_texcoord, t); + right.m_vertex = vector3_linear_interpolated(b.m_vertex, c.m_vertex, t); + right.m_texcoord = vector2_linear_interpolated(b.m_texcoord, c.m_texcoord, t); + point.m_vertex = vector3_linear_interpolated(left.m_vertex, right.m_vertex, t); + point.m_texcoord = vector2_linear_interpolated(left.m_texcoord, right.m_texcoord, t); +} + +void Patch::TesselateSubMatrixFixed(ArbitraryMeshVertex* vertices, std::size_t strideX, std::size_t strideY, unsigned int nFlagsX, unsigned int nFlagsY, PatchControl* subMatrix[3][3]) +{ + double incrementU = 1.0 / m_subdivisions_x; + double incrementV = 1.0 / m_subdivisions_y; + const std::size_t width = m_subdivisions_x + 1; + const std::size_t height = m_subdivisions_y + 1; + + for(std::size_t i = 0; i != width; ++i) + { + double tU = (i + 1 == width) ? 1 : i * incrementU; + PatchControl pointX[3]; + PatchControl leftX[3]; + PatchControl rightX[3]; + QuadraticBezier_evaluate(*subMatrix[0][0], *subMatrix[0][1], *subMatrix[0][2], tU, pointX[0], leftX[0], rightX[0]); + QuadraticBezier_evaluate(*subMatrix[1][0], *subMatrix[1][1], *subMatrix[1][2], tU, pointX[1], leftX[1], rightX[1]); + QuadraticBezier_evaluate(*subMatrix[2][0], *subMatrix[2][1], *subMatrix[2][2], tU, pointX[2], leftX[2], rightX[2]); + + ArbitraryMeshVertex* p = vertices + i * strideX; + for(std::size_t j = 0; j != height; ++j) + { + if((j == 0 || j + 1 == height) && (i == 0 || i + 1 == width)) + { + } + else + { + double tV = (j + 1 == height) ? 1 : j * incrementV; + + PatchControl pointY[3]; + PatchControl leftY[3]; + PatchControl rightY[3]; + QuadraticBezier_evaluate(*subMatrix[0][0], *subMatrix[1][0], *subMatrix[2][0], tV, pointY[0], leftY[0], rightY[0]); + QuadraticBezier_evaluate(*subMatrix[0][1], *subMatrix[1][1], *subMatrix[2][1], tV, pointY[1], leftY[1], rightY[1]); + QuadraticBezier_evaluate(*subMatrix[0][2], *subMatrix[1][2], *subMatrix[2][2], tV, pointY[2], leftY[2], rightY[2]); + + PatchControl point; + PatchControl left; + PatchControl right; + QuadraticBezier_evaluate(pointX[0], pointX[1], pointX[2], tV, point, left, right); + PatchControl up; + PatchControl down; + QuadraticBezier_evaluate(pointY[0], pointY[1], pointY[2], tU, point, up, down); + + vertex3f_to_vector3(p->vertex) = point.m_vertex; + texcoord2f_to_vector2(p->texcoord) = point.m_texcoord; + + ArbitraryMeshVertex a, b, c; + + a.vertex = vertex3f_for_vector3(left.m_vertex); + a.texcoord = texcoord2f_for_vector2(left.m_texcoord); + b.vertex = vertex3f_for_vector3(right.m_vertex); + b.texcoord = texcoord2f_for_vector2(right.m_texcoord); + + if(i != 0) + { + c.vertex = vertex3f_for_vector3(up.m_vertex); + c.texcoord = texcoord2f_for_vector2(up.m_texcoord); + } + else + { + c.vertex = vertex3f_for_vector3(down.m_vertex); + c.texcoord = texcoord2f_for_vector2(down.m_texcoord); + } + + Vector3 normal = vector3_normalised(vector3_cross(right.m_vertex - left.m_vertex, up.m_vertex - down.m_vertex)); + + Vector3 tangent, bitangent; + ArbitraryMeshTriangle_calcTangents(a, b, c, tangent, bitangent); + vector3_normalise(tangent); + vector3_normalise(bitangent); + + if(((nFlagsX & AVERAGE) != 0 && i == 0) || ((nFlagsY & AVERAGE) != 0 && j == 0)) + { + normal3f_to_vector3(p->normal) = vector3_normalised(vector3_added(normal3f_to_vector3(p->normal), normal)); + normal3f_to_vector3(p->tangent) = vector3_normalised(vector3_added(normal3f_to_vector3(p->tangent), tangent)); + normal3f_to_vector3(p->bitangent) = vector3_normalised(vector3_added(normal3f_to_vector3(p->bitangent), bitangent)); + } + else + { + normal3f_to_vector3(p->normal) = normal; + normal3f_to_vector3(p->tangent) = tangent; + normal3f_to_vector3(p->bitangent) = bitangent; + } + } + + p += strideY; + } + } +} + +void Patch::TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY, + std::size_t offStartX, std::size_t offStartY, + std::size_t offEndX, std::size_t offEndY, + std::size_t nFlagsX, std::size_t nFlagsY, + Vector3& left, Vector3& mid, Vector3& right, + Vector2& texLeft, Vector2& texMid, Vector2& texRight, + bool bTranspose ) +{ + int newFlagsX, newFlagsY; + + Vector3 tmp; + Vector3 vertex_0_0, vertex_0_1, vertex_1_0, vertex_1_1, vertex_2_0, vertex_2_1; + Vector2 texTmp; + Vector2 texcoord_0_0, texcoord_0_1, texcoord_1_0, texcoord_1_1, texcoord_2_0, texcoord_2_1; + + { + // texcoords + + BezierInterpolate2( texcoord_for_index(m_tess.m_vertices, offStartX + offStartY), + texcoord_0_0, + texcoord_for_index(m_tess.m_vertices, BX->index + offStartY), + texcoord_0_1, + texcoord_for_index(m_tess.m_vertices, offEndX + offStartY) ); + + + BezierInterpolate2( texcoord_for_index(m_tess.m_vertices, offStartX + offEndY), + texcoord_2_0, + texcoord_for_index(m_tess.m_vertices, BX->index + offEndY), + texcoord_2_1, + texcoord_for_index(m_tess.m_vertices, offEndX + offEndY) ); + + texTmp = texMid; + + BezierInterpolate2(texLeft, + texcoord_1_0, + texTmp, + texcoord_1_1, + texRight); + + if(!BezierCurveTree_isLeaf(BY)) + { + texcoord_for_index(m_tess.m_vertices, BX->index + BY->index) = texTmp; + } + + + if(!BezierCurveTree_isLeaf(BX->left)) + { + texcoord_for_index(m_tess.m_vertices, BX->left->index + offStartY) = texcoord_0_0; + texcoord_for_index(m_tess.m_vertices, BX->left->index + offEndY) = texcoord_2_0; + + if(!BezierCurveTree_isLeaf(BY)) + { + texcoord_for_index(m_tess.m_vertices, BX->left->index + BY->index) = texcoord_1_0; + } + } + if(!BezierCurveTree_isLeaf(BX->right)) + { + texcoord_for_index(m_tess.m_vertices, BX->right->index + offStartY) = texcoord_0_1; + texcoord_for_index(m_tess.m_vertices, BX->right->index + offEndY) = texcoord_2_1; + + if(!BezierCurveTree_isLeaf(BY)) + { + texcoord_for_index(m_tess.m_vertices, BX->right->index + BY->index) = texcoord_1_1; + } + } + + + // verts + + BezierInterpolate3( vertex_for_index(m_tess.m_vertices, offStartX + offStartY), + vertex_0_0, + vertex_for_index(m_tess.m_vertices, BX->index + offStartY), + vertex_0_1, + vertex_for_index(m_tess.m_vertices, offEndX + offStartY) ); + + + BezierInterpolate3( vertex_for_index(m_tess.m_vertices, offStartX + offEndY), + vertex_2_0, + vertex_for_index(m_tess.m_vertices, BX->index + offEndY), + vertex_2_1, + vertex_for_index(m_tess.m_vertices, offEndX + offEndY) ); + + + tmp = mid; + + BezierInterpolate3( left, + vertex_1_0, + tmp, + vertex_1_1, + right ); + + if(!BezierCurveTree_isLeaf(BY)) + { + vertex_for_index(m_tess.m_vertices, BX->index + BY->index) = tmp; + } + + + if(!BezierCurveTree_isLeaf(BX->left)) + { + vertex_for_index(m_tess.m_vertices, BX->left->index + offStartY) = vertex_0_0; + vertex_for_index(m_tess.m_vertices, BX->left->index + offEndY) = vertex_2_0; + + if(!BezierCurveTree_isLeaf(BY)) + { + vertex_for_index(m_tess.m_vertices, BX->left->index + BY->index) = vertex_1_0; + } + } + if(!BezierCurveTree_isLeaf(BX->right)) + { + vertex_for_index(m_tess.m_vertices, BX->right->index + offStartY) = vertex_0_1; + vertex_for_index(m_tess.m_vertices, BX->right->index + offEndY) = vertex_2_1; + + if(!BezierCurveTree_isLeaf(BY)) + { + vertex_for_index(m_tess.m_vertices, BX->right->index + BY->index) = vertex_1_1; + } + } + + // normals + + if(nFlagsX & SPLIT) + { + ArbitraryMeshVertex a, b, c; + Vector3 tangentU; + + if(!(nFlagsX & DEGEN_0a) || !(nFlagsX & DEGEN_0b)) + { + tangentU = vector3_subtracted(vertex_0_1, vertex_0_0); + a.vertex = vertex3f_for_vector3(vertex_0_0); + a.texcoord = texcoord2f_for_vector2(texcoord_0_0); + c.vertex = vertex3f_for_vector3(vertex_0_1); + c.texcoord = texcoord2f_for_vector2(texcoord_0_1); + } + else if(!(nFlagsX & DEGEN_1a) || !(nFlagsX & DEGEN_1b)) + { + tangentU = vector3_subtracted(vertex_1_1, vertex_1_0); + a.vertex = vertex3f_for_vector3(vertex_1_0); + a.texcoord = texcoord2f_for_vector2(texcoord_1_0); + c.vertex = vertex3f_for_vector3(vertex_1_1); + c.texcoord = texcoord2f_for_vector2(texcoord_1_1); + } + else + { + tangentU = vector3_subtracted(vertex_2_1, vertex_2_0); + a.vertex = vertex3f_for_vector3(vertex_2_0); + a.texcoord = texcoord2f_for_vector2(texcoord_2_0); + c.vertex = vertex3f_for_vector3(vertex_2_1); + c.texcoord = texcoord2f_for_vector2(texcoord_2_1); + } + + Vector3 tangentV; + + if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_1a) && (nFlagsY & DEGEN_2a)) + { + tangentV = vector3_subtracted(vertex_for_index(m_tess.m_vertices, BX->index + offEndY), tmp); + b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offEndY].vertex; + b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offEndY].texcoord; + } + else + { + tangentV = vector3_subtracted(tmp, vertex_for_index(m_tess.m_vertices, BX->index + offStartY)); + b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offStartY].vertex; + b.texcoord = texcoord2f_for_vector2(texTmp); //m_tess.m_vertices[BX->index + offStartY].texcoord; + } + + + Vector3 normal, s, t; + ArbitraryMeshVertex& v = m_tess.m_vertices[offStartY + BX->index]; + Vector3& p = normal3f_to_vector3(v.normal); + Vector3& ps = normal3f_to_vector3(v.tangent); + Vector3& pt = normal3f_to_vector3(v.bitangent); + + if(bTranspose) + { + normal = vector3_cross(tangentV, tangentU); + } + else + { + normal = vector3_cross(tangentU, tangentV); + } + normalise_safe(normal); + + ArbitraryMeshTriangle_calcTangents(a, b, c, s, t); + normalise_safe(s); + normalise_safe(t); + + if(nFlagsX & AVERAGE) + { + p = vector3_normalised(vector3_added(p, normal)); + ps = vector3_normalised(vector3_added(ps, s)); + pt = vector3_normalised(vector3_added(pt, t)); + } + else + { + p = normal; + ps = s; + pt = t; + } + } + + { + ArbitraryMeshVertex a, b, c; + Vector3 tangentU; + + if(!(nFlagsX & DEGEN_2a) || !(nFlagsX & DEGEN_2b)) + { + tangentU = vector3_subtracted(vertex_2_1, vertex_2_0); + a.vertex = vertex3f_for_vector3(vertex_2_0); + a.texcoord = texcoord2f_for_vector2(texcoord_2_0); + c.vertex = vertex3f_for_vector3(vertex_2_1); + c.texcoord = texcoord2f_for_vector2(texcoord_2_1); + } + else if(!(nFlagsX & DEGEN_1a) || !(nFlagsX & DEGEN_1b)) + { + tangentU = vector3_subtracted(vertex_1_1, vertex_1_0); + a.vertex = vertex3f_for_vector3(vertex_1_0); + a.texcoord = texcoord2f_for_vector2(texcoord_1_0); + c.vertex = vertex3f_for_vector3(vertex_1_1); + c.texcoord = texcoord2f_for_vector2(texcoord_1_1); + } + else + { + tangentU = vector3_subtracted(vertex_0_1, vertex_0_0); + a.vertex = vertex3f_for_vector3(vertex_0_0); + a.texcoord = texcoord2f_for_vector2(texcoord_0_0); + c.vertex = vertex3f_for_vector3(vertex_0_1); + c.texcoord = texcoord2f_for_vector2(texcoord_0_1); + } + + Vector3 tangentV; + + if((nFlagsY & DEGEN_0b) && (nFlagsY & DEGEN_1b) && (nFlagsY & DEGEN_2b)) + { + tangentV = vector3_subtracted(tmp, vertex_for_index(m_tess.m_vertices, BX->index + offStartY)); + b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offStartY].vertex; + b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offStartY].texcoord; + } + else + { + tangentV = vector3_subtracted(vertex_for_index(m_tess.m_vertices, BX->index + offEndY), tmp); + b.vertex = vertex3f_for_vector3(tmp);//m_tess.m_vertices[BX->index + offEndY].vertex; + b.texcoord = texcoord2f_for_vector2(texTmp);//m_tess.m_vertices[BX->index + offEndY].texcoord; + } + + ArbitraryMeshVertex& v = m_tess.m_vertices[offEndY+BX->index]; + Vector3& p = normal3f_to_vector3(v.normal); + Vector3& ps = normal3f_to_vector3(v.tangent); + Vector3& pt = normal3f_to_vector3(v.bitangent); + + if(bTranspose) + { + p = vector3_cross(tangentV, tangentU); + } + else + { + p = vector3_cross(tangentU, tangentV); + } + normalise_safe(p); + + ArbitraryMeshTriangle_calcTangents(a, b, c, ps, pt); + normalise_safe(ps); + normalise_safe(pt); + } + } + + + newFlagsX = newFlagsY = 0; + + if((nFlagsX & DEGEN_0a) && (nFlagsX & DEGEN_0b)) + { + newFlagsX |= DEGEN_0a; + newFlagsX |= DEGEN_0b; + } + if((nFlagsX & DEGEN_1a) && (nFlagsX & DEGEN_1b)) + { + newFlagsX |= DEGEN_1a; + newFlagsX |= DEGEN_1b; + } + if((nFlagsX & DEGEN_2a) && (nFlagsX & DEGEN_2b)) + { + newFlagsX |= DEGEN_2a; + newFlagsX |= DEGEN_2b; + } + if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_1a) && (nFlagsY & DEGEN_2a)) + { + newFlagsY |= DEGEN_0a; + newFlagsY |= DEGEN_1a; + newFlagsY |= DEGEN_2a; + } + if((nFlagsY & DEGEN_0b) && (nFlagsY & DEGEN_1b) && (nFlagsY & DEGEN_2b)) + { + newFlagsY |= DEGEN_0b; + newFlagsY |= DEGEN_1b; + newFlagsY |= DEGEN_2b; + } + + + //if((nFlagsX & DEGEN_0a) && (nFlagsX & DEGEN_1a) && (nFlagsX & DEGEN_2a)) { newFlagsX |= DEGEN_0a; newFlagsX |= DEGEN_1a; newFlagsX |= DEGEN_2a; } + //if((nFlagsX & DEGEN_0b) && (nFlagsX & DEGEN_1b) && (nFlagsX & DEGEN_2b)) { newFlagsX |= DEGEN_0b; newFlagsX |= DEGEN_1b; newFlagsX |= DEGEN_2b; } + + newFlagsX |= (nFlagsX & SPLIT); + newFlagsX |= (nFlagsX & AVERAGE); + + if(!BezierCurveTree_isLeaf(BY)) + { + { + int nTemp = newFlagsY; + + if((nFlagsY & DEGEN_0a) && (nFlagsY & DEGEN_0b)) + { + newFlagsY |= DEGEN_0a; + newFlagsY |= DEGEN_0b; + } + newFlagsY |= (nFlagsY & SPLIT); + newFlagsY |= (nFlagsY & AVERAGE); + + Vector3& p = vertex_for_index(m_tess.m_vertices, BX->index+BY->index); + Vector3 vTemp(p); + + Vector2& p2 = texcoord_for_index(m_tess.m_vertices, BX->index+BY->index); + Vector2 stTemp(p2); + + TesselateSubMatrix( BY, BX->left, + offStartY, offStartX, + offEndY, BX->index, + newFlagsY, newFlagsX, + vertex_0_0, vertex_1_0, vertex_2_0, + texcoord_0_0, texcoord_1_0, texcoord_2_0, + !bTranspose ); + + newFlagsY = nTemp; + p = vTemp; + p2 = stTemp; + } + + if((nFlagsY & DEGEN_2a) && (nFlagsY & DEGEN_2b)) { newFlagsY |= DEGEN_2a; newFlagsY |= DEGEN_2b; } + + TesselateSubMatrix( BY, BX->right, + offStartY, BX->index, + offEndY, offEndX, + newFlagsY, newFlagsX, + vertex_0_1, vertex_1_1, vertex_2_1, + texcoord_0_1, texcoord_1_1, texcoord_2_1, + !bTranspose ); + } + else + { + if(!BezierCurveTree_isLeaf(BX->left)) + { + TesselateSubMatrix( BX->left, BY, + offStartX, offStartY, + BX->index, offEndY, + newFlagsX, newFlagsY, + left, vertex_1_0, tmp, + texLeft, texcoord_1_0, texTmp, + bTranspose ); + } + + if(!BezierCurveTree_isLeaf(BX->right)) + { + TesselateSubMatrix( BX->right, BY, + BX->index, offStartY, + offEndX, offEndY, + newFlagsX, newFlagsY, + tmp, vertex_1_1, right, + texTmp, texcoord_1_1, texRight, + bTranspose ); + } + } + +} + +void Patch::BuildTesselationCurves(EMatrixMajor major) +{ + std::size_t nArrayStride, length, cross, strideU, strideV; + switch(major) + { + case ROW: + nArrayStride = 1; + length = (m_width - 1) >> 1; + cross = m_height; + strideU = 1; + strideV = m_width; + + if(!m_patchDef3) + { + BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeU); + } + + break; + case COL: + nArrayStride = m_tess.m_nArrayWidth; + length = (m_height - 1) >> 1; + cross = m_width; + strideU = m_width; + strideV = 1; + + if(!m_patchDef3) + { + BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeV); + } + + break; + default: + ERROR_MESSAGE("neither row-major nor column-major"); + return; + } + + Array arrayLength(length); + Array pCurveTree(length); + + std::size_t nArrayLength = 1; + + if(m_patchDef3) + { + for(Array::iterator i = arrayLength.begin(); i != arrayLength.end(); ++i) + { + *i = Array::value_type((major == ROW) ? m_subdivisions_x : m_subdivisions_y); + nArrayLength += *i; + } + } + else + { + // create a list of the horizontal control curves in each column of sub-patches + // adaptively tesselate each horizontal control curve in the list + // create a binary tree representing the combined tesselation of the list + for(std::size_t i = 0; i != length; ++i) + { + PatchControl* p1 = m_ctrlTransformed.data() + (i * 2 * strideU); + GSList* pCurveList = 0; + for(std::size_t j = 0; j < cross; j += 2) + { + PatchControl* p2 = p1+strideV; + PatchControl* p3 = p2+strideV; + + // directly taken from one row of control points + { + BezierCurve* pCurve = new BezierCurve; + pCurve->crd = (p1+strideU)->m_vertex; + pCurve->left = p1->m_vertex; + pCurve->right = (p1+(strideU<<1))->m_vertex; + pCurveList = g_slist_prepend(pCurveList, pCurve); + } + + if(j+2 >= cross) + { + break; + } + + // interpolated from three columns of control points + { + BezierCurve* pCurve = new BezierCurve; + pCurve->crd = vector3_mid((p1+strideU)->m_vertex, (p3+strideU)->m_vertex); + pCurve->left = vector3_mid(p1->m_vertex, p3->m_vertex); + pCurve->right = vector3_mid((p1+(strideU<<1))->m_vertex, (p3+(strideU<<1))->m_vertex); + + pCurve->crd = vector3_mid(pCurve->crd, (p2+strideU)->m_vertex); + pCurve->left = vector3_mid(pCurve->left, p2->m_vertex); + pCurve->right = vector3_mid(pCurve->right, (p2+(strideU<<1))->m_vertex); + pCurveList = g_slist_prepend(pCurveList, pCurve); + } + + p1 = p3; + } + + pCurveTree[i] = new BezierCurveTree; + BezierCurveTree_FromCurveList(pCurveTree[i], pCurveList); + for(GSList* l = pCurveList; l != 0; l = g_slist_next(l)) + { + delete static_cast((*l).data); + } + g_slist_free(pCurveList); + + // set up array indices for binary tree + // accumulate subarray width + arrayLength[i] = Array::value_type(BezierCurveTree_Setup(pCurveTree[i], nArrayLength, nArrayStride) - (nArrayLength - 1)); + // accumulate total array width + nArrayLength += arrayLength[i]; + } + } + + switch(major) + { + case ROW: + m_tess.m_nArrayWidth = nArrayLength; + std::swap(m_tess.m_arrayWidth, arrayLength); + + if(!m_patchDef3) + { + std::swap(m_tess.m_curveTreeU, pCurveTree); + } + break; + case COL: + m_tess.m_nArrayHeight = nArrayLength; + std::swap(m_tess.m_arrayHeight, arrayLength); + + if(!m_patchDef3) + { + std::swap(m_tess.m_curveTreeV, pCurveTree); + } + break; + } +} + +inline void vertex_assign_ctrl(ArbitraryMeshVertex& vertex, const PatchControl& ctrl) +{ + vertex.vertex = vertex3f_for_vector3(ctrl.m_vertex); + vertex.texcoord = texcoord2f_for_vector2(ctrl.m_texcoord); +} + +inline void vertex_clear_normal(ArbitraryMeshVertex& vertex) +{ + vertex.normal = Normal3f(0, 0, 0); + vertex.tangent = Normal3f(0, 0, 0); + vertex.bitangent = Normal3f(0, 0, 0); +} + +inline void tangents_remove_degenerate(Vector3 tangents[6], Vector2 textureTangents[6], unsigned int flags) +{ + if(flags & DEGEN_0a) + { + const std::size_t i = + (flags & DEGEN_0b) + ? (flags & DEGEN_1a) + ? (flags & DEGEN_1b) + ? (flags & DEGEN_2a) + ? 5 + : 4 + : 3 + : 2 + : 1; + tangents[0] = tangents[i]; + textureTangents[0] = textureTangents[i]; + } + if(flags & DEGEN_0b) + { + const std::size_t i = + (flags & DEGEN_0a) + ? (flags & DEGEN_1b) + ? (flags & DEGEN_1a) + ? (flags & DEGEN_2b) + ? 4 + : 5 + : 2 + : 3 + : 0; + tangents[1] = tangents[i]; + textureTangents[1] = textureTangents[i]; + } + if(flags & DEGEN_2a) + { + const std::size_t i = + (flags & DEGEN_2b) + ? (flags & DEGEN_1a) + ? (flags & DEGEN_1b) + ? (flags & DEGEN_0a) + ? 1 + : 0 + : 3 + : 2 + : 5; + tangents[4] = tangents[i]; + textureTangents[4] = textureTangents[i]; + } + if(flags & DEGEN_2b) + { + const std::size_t i = + (flags & DEGEN_2a) + ? (flags & DEGEN_1b) + ? (flags & DEGEN_1a) + ? (flags & DEGEN_0b) + ? 0 + : 1 + : 2 + : 3 + : 4; + tangents[5] = tangents[i]; + textureTangents[5] = textureTangents[i]; + } +} + +void bestTangents00(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) +{ + if(fabs(dot + length) < 0.001) // opposing direction = degenerate + { + if(!(degenerateFlags & DEGEN_1a)) // if this tangent is degenerate we cannot use it + { + index0 = 2; + index1 = 0; + } + else if(!(degenerateFlags & DEGEN_0b)) + { + index0 = 0; + index1 = 1; + } + else + { + index0 = 1; + index1 = 0; + } + } + else if(fabs(dot - length) < 0.001) // same direction = degenerate + { + if(degenerateFlags & DEGEN_0b) + { + index0 = 0; + index1 = 1; + } + else + { + index0 = 1; + index1 = 0; + } + } +} + +void bestTangents01(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) +{ + if(fabs(dot - length) < 0.001) // same direction = degenerate + { + if(!(degenerateFlags & DEGEN_1a)) // if this tangent is degenerate we cannot use it + { + index0 = 2; + index1 = 1; + } + else if(!(degenerateFlags & DEGEN_2b)) + { + index0 = 4; + index1 = 0; + } + else + { + index0 = 5; + index1 = 1; + } + } + else if(fabs(dot + length) < 0.001) // opposing direction = degenerate + { + if(degenerateFlags & DEGEN_2b) + { + index0 = 4; + index1 = 0; + } + else + { + index0 = 5; + index1 = 1; + } + } +} + +void bestTangents10(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) +{ + if(fabs(dot - length) < 0.001) // same direction = degenerate + { + if(!(degenerateFlags & DEGEN_1b)) // if this tangent is degenerate we cannot use it + { + index0 = 3; + index1 = 4; + } + else if(!(degenerateFlags & DEGEN_0a)) + { + index0 = 1; + index1 = 5; + } + else + { + index0 = 0; + index1 = 4; + } + } + else if(fabs(dot + length) < 0.001) // opposing direction = degenerate + { + if(degenerateFlags & DEGEN_0a) + { + index0 = 1; + index1 = 5; + } + else + { + index0 = 0; + index1 = 4; + } + } +} + +void bestTangents11(unsigned int degenerateFlags, double dot, double length, std::size_t& index0, std::size_t& index1) +{ + if(fabs(dot + length) < 0.001) // opposing direction = degenerate + { + if(!(degenerateFlags & DEGEN_1b)) // if this tangent is degenerate we cannot use it + { + index0 = 3; + index1 = 5; + } + else if(!(degenerateFlags & DEGEN_2a)) + { + index0 = 5; + index1 = 4; + } + else + { + index0 = 4; + index1 = 5; + } + } + else if(fabs(dot - length) < 0.001) // same direction = degenerate + { + if(degenerateFlags & DEGEN_2a) + { + index0 = 5; + index1 = 4; + } + else + { + index0 = 4; + index1 = 5; + } + } +} + +void Patch::accumulateVertexTangentSpace(std::size_t index, Vector3 tangentX[6], Vector3 tangentY[6], Vector2 tangentS[6], Vector2 tangentT[6], std::size_t index0, std::size_t index1) +{ + { + Vector3 normal(vector3_cross(tangentX[index0], tangentY[index1])); + if(!vector3_equal(normal, g_vector3_identity)) + { + vector3_add(normal_for_index(m_tess.m_vertices, index), vector3_normalised(normal)); + } + } + + { + ArbitraryMeshVertex a, b, c; + a.vertex = Vertex3f(0, 0, 0); + a.texcoord = TexCoord2f(0, 0); + b.vertex = vertex3f_for_vector3(tangentX[index0]); + b.texcoord = texcoord2f_for_vector2(tangentS[index0]); + c.vertex = vertex3f_for_vector3(tangentY[index1]); + c.texcoord = texcoord2f_for_vector2(tangentT[index1]); + + Vector3 s, t; + ArbitraryMeshTriangle_calcTangents(a, b, c, s, t); + if(!vector3_equal(s, g_vector3_identity)) + { + vector3_add(tangent_for_index(m_tess.m_vertices, index), vector3_normalised(s)); + } + if(!vector3_equal(t, g_vector3_identity)) + { + vector3_add(bitangent_for_index(m_tess.m_vertices, index), vector3_normalised(t)); + } + } +} + +const std::size_t PATCH_MAX_VERTEX_ARRAY = 1048576; + +void Patch::BuildVertexArray() +{ + const std::size_t strideU = 1; + const std::size_t strideV = m_width; + + const std::size_t numElems = m_tess.m_nArrayWidth*m_tess.m_nArrayHeight; // total number of elements in vertex array + + const bool bWidthStrips = (m_tess.m_nArrayWidth >= m_tess.m_nArrayHeight); // decide if horizontal strips are longer than vertical + + + // allocate vertex, normal, texcoord and primitive-index arrays + m_tess.m_vertices.resize(numElems); + m_tess.m_indices.resize(m_tess.m_nArrayWidth *2 * (m_tess.m_nArrayHeight - 1)); + + // set up strip indices + if(bWidthStrips) + { + m_tess.m_numStrips = m_tess.m_nArrayHeight-1; + m_tess.m_lenStrips = m_tess.m_nArrayWidth*2; + + for(std::size_t i=0; i>1]); + const std::size_t offMidY = (m_patchDef3) ? 0 : m_tess.m_curveTreeV[j>>1]->index; + const std::size_t widthY = m_tess.m_arrayHeight[j>>1] * m_tess.m_nArrayWidth; + const std::size_t offEndY = offStartY + widthY; + + for(std::size_t i = 0, offStartX = 0; i+1 < m_width; i += 2, pCtrl += (strideU << 1)) + { + const bool leafX = (m_patchDef3) ? false : BezierCurveTree_isLeaf(m_tess.m_curveTreeU[i>>1]); + const std::size_t offMidX = (m_patchDef3) ? 0 : m_tess.m_curveTreeU[i>>1]->index; + const std::size_t widthX = m_tess.m_arrayWidth[i>>1]; + const std::size_t offEndX = offStartX + widthX; + + PatchControl *subMatrix[3][3]; + subMatrix[0][0] = pCtrl; + subMatrix[0][1] = subMatrix[0][0]+strideU; + subMatrix[0][2] = subMatrix[0][1]+strideU; + subMatrix[1][0] = subMatrix[0][0]+strideV; + subMatrix[1][1] = subMatrix[1][0]+strideU; + subMatrix[1][2] = subMatrix[1][1]+strideU; + subMatrix[2][0] = subMatrix[1][0]+strideV; + subMatrix[2][1] = subMatrix[2][0]+strideU; + subMatrix[2][2] = subMatrix[2][1]+strideU; + + // assign on-patch control points to vertex array + if(i == 0 && j == 0) + { + vertex_clear_normal(m_tess.m_vertices[offStartX + offStartY]); + } + vertex_assign_ctrl(m_tess.m_vertices[offStartX + offStartY], *subMatrix[0][0]); + if(j == 0) + { + vertex_clear_normal(m_tess.m_vertices[offEndX + offStartY]); + } + vertex_assign_ctrl(m_tess.m_vertices[offEndX + offStartY], *subMatrix[0][2]); + if(i == 0) + { + vertex_clear_normal(m_tess.m_vertices[offStartX + offEndY]); + } + vertex_assign_ctrl(m_tess.m_vertices[offStartX + offEndY], *subMatrix[2][0]); + + vertex_clear_normal(m_tess.m_vertices[offEndX + offEndY]); + vertex_assign_ctrl(m_tess.m_vertices[offEndX + offEndY], *subMatrix[2][2]); + + if(!m_patchDef3) + { + // assign remaining control points to vertex array + if(!leafX) + { + vertex_assign_ctrl(m_tess.m_vertices[offMidX + offStartY], *subMatrix[0][1]); + vertex_assign_ctrl(m_tess.m_vertices[offMidX + offEndY], *subMatrix[2][1]); + } + if(!leafY) + { + vertex_assign_ctrl(m_tess.m_vertices[offStartX + offMidY], *subMatrix[1][0]); + vertex_assign_ctrl(m_tess.m_vertices[offEndX + offMidY], *subMatrix[1][2]); + + if(!leafX) + { + vertex_assign_ctrl(m_tess.m_vertices[offMidX + offMidY], *subMatrix[1][1]); + } + } + } + + // test all 12 edges for degeneracy + unsigned int nFlagsX = subarray_get_degen(pCtrl, strideU, strideV); + unsigned int nFlagsY = subarray_get_degen(pCtrl, strideV, strideU); + Vector3 tangentX[6], tangentY[6]; + Vector2 tangentS[6], tangentT[6]; + + // set up tangents for each of the 12 edges if they were not degenerate + if(!(nFlagsX & DEGEN_0a)) + { + tangentX[0] = vector3_subtracted(subMatrix[0][1]->m_vertex, subMatrix[0][0]->m_vertex); + tangentS[0] = vector2_subtracted(subMatrix[0][1]->m_texcoord, subMatrix[0][0]->m_texcoord); + } + if(!(nFlagsX & DEGEN_0b)) + { + tangentX[1] = vector3_subtracted(subMatrix[0][2]->m_vertex, subMatrix[0][1]->m_vertex); + tangentS[1] = vector2_subtracted(subMatrix[0][2]->m_texcoord, subMatrix[0][1]->m_texcoord); + } + if(!(nFlagsX & DEGEN_1a)) + { + tangentX[2] = vector3_subtracted(subMatrix[1][1]->m_vertex, subMatrix[1][0]->m_vertex); + tangentS[2] = vector2_subtracted(subMatrix[1][1]->m_texcoord, subMatrix[1][0]->m_texcoord); + } + if(!(nFlagsX & DEGEN_1b)) + { + tangentX[3] = vector3_subtracted(subMatrix[1][2]->m_vertex, subMatrix[1][1]->m_vertex); + tangentS[3] = vector2_subtracted(subMatrix[1][2]->m_texcoord, subMatrix[1][1]->m_texcoord); + } + if(!(nFlagsX & DEGEN_2a)) + { + tangentX[4] = vector3_subtracted(subMatrix[2][1]->m_vertex, subMatrix[2][0]->m_vertex); + tangentS[4] = vector2_subtracted(subMatrix[2][1]->m_texcoord, subMatrix[2][0]->m_texcoord); + } + if(!(nFlagsX & DEGEN_2b)) + { + tangentX[5] = vector3_subtracted(subMatrix[2][2]->m_vertex, subMatrix[2][1]->m_vertex); + tangentS[5] = vector2_subtracted(subMatrix[2][2]->m_texcoord, subMatrix[2][1]->m_texcoord); + } + + if(!(nFlagsY & DEGEN_0a)) + { + tangentY[0] = vector3_subtracted(subMatrix[1][0]->m_vertex, subMatrix[0][0]->m_vertex); + tangentT[0] = vector2_subtracted(subMatrix[1][0]->m_texcoord, subMatrix[0][0]->m_texcoord); + } + if(!(nFlagsY & DEGEN_0b)) + { + tangentY[1] = vector3_subtracted(subMatrix[2][0]->m_vertex, subMatrix[1][0]->m_vertex); + tangentT[1] = vector2_subtracted(subMatrix[2][0]->m_texcoord, subMatrix[1][0]->m_texcoord); + } + if(!(nFlagsY & DEGEN_1a)) + { + tangentY[2] = vector3_subtracted(subMatrix[1][1]->m_vertex, subMatrix[0][1]->m_vertex); + tangentT[2] = vector2_subtracted(subMatrix[1][1]->m_texcoord, subMatrix[0][1]->m_texcoord); + } + if(!(nFlagsY & DEGEN_1b)) + { + tangentY[3] = vector3_subtracted(subMatrix[2][1]->m_vertex, subMatrix[1][1]->m_vertex); + tangentT[3] = vector2_subtracted(subMatrix[2][1]->m_texcoord, subMatrix[1][1]->m_texcoord); + } + if(!(nFlagsY & DEGEN_2a)) + { + tangentY[4] = vector3_subtracted(subMatrix[1][2]->m_vertex, subMatrix[0][2]->m_vertex); + tangentT[4] = vector2_subtracted(subMatrix[1][2]->m_texcoord, subMatrix[0][2]->m_texcoord); + } + if(!(nFlagsY & DEGEN_2b)) + { + tangentY[5] = vector3_subtracted(subMatrix[2][2]->m_vertex, subMatrix[1][2]->m_vertex); + tangentT[5] = vector2_subtracted(subMatrix[2][2]->m_texcoord, subMatrix[1][2]->m_texcoord); + } + + // set up remaining edge tangents by borrowing the tangent from the closest parallel non-degenerate edge + tangents_remove_degenerate(tangentX, tangentS, nFlagsX); + tangents_remove_degenerate(tangentY, tangentT, nFlagsY); + + { + // x=0, y=0 + std::size_t index = offStartX + offStartY; + std::size_t index0 = 0; + std::size_t index1 = 0; + + double dot = vector3_dot(tangentX[index0], tangentY[index1]); + double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]); + + bestTangents00(nFlagsX, dot, length, index0, index1); + + accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); + } + + { + // x=1, y=0 + std::size_t index = offEndX + offStartY; + std::size_t index0 = 1; + std::size_t index1 = 4; + + double dot = vector3_dot(tangentX[index0],tangentY[index1]); + double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]); + + bestTangents10(nFlagsX, dot, length, index0, index1); + + accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); + } + + { + // x=0, y=1 + std::size_t index = offStartX + offEndY; + std::size_t index0 = 4; + std::size_t index1 = 1; + + double dot = vector3_dot(tangentX[index0], tangentY[index1]); + double length = vector3_length(tangentX[index1]) * vector3_length(tangentY[index1]); + + bestTangents01(nFlagsX, dot, length, index0, index1); + + accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); + } + + { + // x=1, y=1 + std::size_t index = offEndX + offEndY; + std::size_t index0 = 5; + std::size_t index1 = 5; + + double dot = vector3_dot(tangentX[index0],tangentY[index1]); + double length = vector3_length(tangentX[index0]) * vector3_length(tangentY[index1]); + + bestTangents11(nFlagsX, dot, length, index0, index1); + + accumulateVertexTangentSpace(index, tangentX, tangentY, tangentS, tangentT, index0, index1); + } + + //normalise normals that won't be accumulated again + if(i!=0 || j!=0) + { + normalise_safe(normal_for_index(m_tess.m_vertices, offStartX + offStartY)); + normalise_safe(tangent_for_index(m_tess.m_vertices, offStartX + offStartY)); + normalise_safe(bitangent_for_index(m_tess.m_vertices, offStartX + offStartY)); + } + if(i+3 == m_width) + { + normalise_safe(normal_for_index(m_tess.m_vertices, offEndX + offStartY)); + normalise_safe(tangent_for_index(m_tess.m_vertices, offEndX + offStartY)); + normalise_safe(bitangent_for_index(m_tess.m_vertices, offEndX + offStartY)); + } + if(j+3 == m_height) + { + normalise_safe(normal_for_index(m_tess.m_vertices, offStartX + offEndY)); + normalise_safe(tangent_for_index(m_tess.m_vertices, offStartX + offEndY)); + normalise_safe(bitangent_for_index(m_tess.m_vertices, offStartX + offEndY)); + } + if(i+3 == m_width && j+3 == m_height) + { + normalise_safe(normal_for_index(m_tess.m_vertices, offEndX + offEndY)); + normalise_safe(tangent_for_index(m_tess.m_vertices, offEndX + offEndY)); + normalise_safe(bitangent_for_index(m_tess.m_vertices, offEndX + offEndY)); + } + + // set flags to average normals between shared edges + if(j != 0) + { + nFlagsX |= AVERAGE; + } + if(i != 0) + { + nFlagsY |= AVERAGE; + } + // set flags to save evaluating shared edges twice + nFlagsX |= SPLIT; + nFlagsY |= SPLIT; + + // if the patch is curved.. tesselate recursively + // use the relevant control curves for this sub-patch + if(m_patchDef3) + { + TesselateSubMatrixFixed(m_tess.m_vertices.data() + offStartX + offStartY, 1, m_tess.m_nArrayWidth, nFlagsX, nFlagsY, subMatrix); + } + else + { + if(!leafX) + { + TesselateSubMatrix( m_tess.m_curveTreeU[i>>1], m_tess.m_curveTreeV[j>>1], + offStartX, offStartY, offEndX, offEndY, // array offsets + nFlagsX, nFlagsY, + subMatrix[1][0]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[1][2]->m_vertex, + subMatrix[1][0]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[1][2]->m_texcoord, + false ); + } + else if(!leafY) + { + TesselateSubMatrix( m_tess.m_curveTreeV[j>>1], m_tess.m_curveTreeU[i>>1], + offStartY, offStartX, offEndY, offEndX, // array offsets + nFlagsY, nFlagsX, + subMatrix[0][1]->m_vertex, subMatrix[1][1]->m_vertex, subMatrix[2][1]->m_vertex, + subMatrix[0][1]->m_texcoord, subMatrix[1][1]->m_texcoord, subMatrix[2][1]->m_texcoord, + true ); + } + } + + offStartX = offEndX; + } + offStartY = offEndY; + } + } +} + + + +class PatchFilterWrapper : public Filter +{ + bool m_active; + bool m_invert; + PatchFilter& m_filter; +public: + PatchFilterWrapper(PatchFilter& filter, bool invert) : m_invert(invert), m_filter(filter) + { + } + void setActive(bool active) + { + m_active = active; + } + bool active() + { + return m_active; + } + bool filter(const Patch& patch) + { + return m_invert ^ m_filter.filter(patch); + } +}; + + +typedef std::list PatchFilters; +PatchFilters g_patchFilters; + +void add_patch_filter(PatchFilter& filter, int mask, bool invert) +{ + g_patchFilters.push_back(PatchFilterWrapper(filter, invert)); + GlobalFilterSystem().addFilter(g_patchFilters.back(), mask); +} + +bool patch_filtered(Patch& patch) +{ + for(PatchFilters::iterator i = g_patchFilters.begin(); i != g_patchFilters.end(); ++i) + { + if((*i).active() && (*i).filter(patch)) + { + return true; + } + } + return false; +} diff --git a/misc/mediasource/netradiant-src/radiant/patch.h b/misc/mediasource/netradiant-src/radiant/patch.h new file mode 100644 index 00000000..d55e712b --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patch.h @@ -0,0 +1,2071 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_PATCH_H) +#define INCLUDED_PATCH_H + +/// \file +/// \brief The patch primitive. +/// +/// A 2-dimensional matrix of vertices that define a quadratic bezier surface. +/// The Boundary-Representation of this primitive is a triangle mesh. +/// The surface is recursively tesselated until the angle between each triangle +/// edge is smaller than a specified tolerance. + + +#include "nameable.h" +#include "ifilter.h" +#include "imap.h" +#include "ipatch.h" +#include "cullable.h" +#include "renderable.h" +#include "editable.h" +#include "selectable.h" + +#include "debugging/debugging.h" + +#include +#include + +#include "math/frustum.h" +#include "string/string.h" +#include "stream/stringstream.h" +#include "stream/textstream.h" +#include "xml/xmlelement.h" +#include "scenelib.h" +#include "transformlib.h" +#include "instancelib.h" +#include "selectionlib.h" +#include "traverselib.h" +#include "render.h" +#include "stringio.h" +#include "shaderlib.h" +#include "generic/callback.h" +#include "signal/signalfwd.h" +#include "texturelib.h" +#include "xml/ixml.h" +#include "dragplanes.h" + +enum EPatchType +{ + ePatchTypeQuake3, + ePatchTypeDoom3, +}; + +extern int g_PatchSubdivideThreshold; + + +#define MIN_PATCH_WIDTH 3 +#define MIN_PATCH_HEIGHT 3 + +extern std::size_t MAX_PATCH_WIDTH; +extern std::size_t MAX_PATCH_HEIGHT; + +#define MAX_PATCH_ROWCTRL (((MAX_PATCH_WIDTH-1)-1)/2) +#define MAX_PATCH_COLCTRL (((MAX_PATCH_HEIGHT-1)-1)/2) + +enum EPatchCap +{ + eCapBevel, + eCapEndCap, + eCapIBevel, + eCapIEndCap, + eCapCylinder, +}; + +enum EPatchPrefab +{ + ePlane, + eBevel, + eEndCap, + eCylinder, + eDenseCylinder, + eVeryDenseCylinder, + eSqCylinder, + eCone, + eSphere, +}; + +enum EMatrixMajor +{ + ROW, COL, +}; + +struct BezierCurve +{ + Vector3 crd; + Vector3 left; + Vector3 right; +}; + +const std::size_t BEZIERCURVETREE_MAX_INDEX = std::size_t(1) << (std::numeric_limits::digits - 1); + +struct BezierCurveTree +{ + std::size_t index; + BezierCurveTree* left; + BezierCurveTree* right; +}; + +inline bool BezierCurveTree_isLeaf(const BezierCurveTree* node) +{ + return node->left == 0 && node->right == 0; +} + +void BezierCurveTree_Delete(BezierCurveTree *pCurve); + + +inline VertexPointer vertexpointer_arbitrarymeshvertex(const ArbitraryMeshVertex* array) +{ + return VertexPointer(VertexPointer::pointer(&array->vertex), sizeof(ArbitraryMeshVertex)); +} + +typedef PatchControl* PatchControlIter; +typedef const PatchControl* PatchControlConstIter; + +inline void copy_ctrl(PatchControlIter ctrl, PatchControlConstIter begin, PatchControlConstIter end) +{ + std::copy(begin, end, ctrl); +} + +const Colour4b colour_corner(0, 255, 0, 255); +const Colour4b colour_inside(255, 0, 255, 255); + +class Patch; + +class PatchFilter +{ +public: + virtual bool filter(const Patch& patch) const = 0; +}; + +bool patch_filtered(Patch& patch); +void add_patch_filter(PatchFilter& filter, int mask, bool invert = false); + +void Patch_addTextureChangedCallback(const SignalHandler& handler); +void Patch_textureChanged(); + +inline void BezierCurveTreeArray_deleteAll(Array& curveTrees) +{ + for(Array::iterator i = curveTrees.begin(); i != curveTrees.end(); ++i) + { + BezierCurveTree_Delete(*i); + } +} + +inline void PatchControlArray_invert(Array& ctrl, std::size_t width, std::size_t height) +{ + Array tmp(width); + + PatchControlIter from = ctrl.data() + (width * (height - 1)); + PatchControlIter to = ctrl.data(); + for(std::size_t h = 0; h != ((height - 1) >> 1); ++h, to += width, from -= width) + { + copy_ctrl(tmp.data(), to, to + width); + copy_ctrl(to, from, from + width); + copy_ctrl(from, tmp.data(), tmp.data() + width); + } +} + +class PatchTesselation +{ +public: + PatchTesselation() + : m_numStrips(0), m_lenStrips(0), m_nArrayWidth(0), m_nArrayHeight(0) + { + } + Array m_vertices; + Array m_indices; + std::size_t m_numStrips; + std::size_t m_lenStrips; + + Array m_arrayWidth; + std::size_t m_nArrayWidth; + Array m_arrayHeight; + std::size_t m_nArrayHeight; + + Array m_curveTreeU; + Array m_curveTreeV; +}; + +class RenderablePatchWireframe : public OpenGLRenderable +{ + PatchTesselation& m_tess; +public: + RenderablePatchWireframe(PatchTesselation& tess) : m_tess(tess) + { + } + void render(RenderStateFlags state) const + { + { + #if NV_DRIVER_BUG + glVertexPointer(3, GL_FLOAT, 0, 0); + glDrawArrays(GL_TRIANGLE_FAN, 0, 0); + #endif + + std::size_t n = 0; + glVertexPointer(3, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->vertex); + for(std::size_t i = 0; i <= m_tess.m_curveTreeV.size(); ++i) + { + glDrawArrays(GL_LINE_STRIP, GLint(n), GLsizei(m_tess.m_nArrayWidth)); + + if(i == m_tess.m_curveTreeV.size()) break; + + if(!BezierCurveTree_isLeaf(m_tess.m_curveTreeV[i])) + glDrawArrays(GL_LINE_STRIP, GLint(m_tess.m_curveTreeV[i]->index), GLsizei(m_tess.m_nArrayWidth)); + + n += (m_tess.m_arrayHeight[i]*m_tess.m_nArrayWidth); + + } + } + + { + const ArbitraryMeshVertex* p = m_tess.m_vertices.data(); + std::size_t n = m_tess.m_nArrayWidth * sizeof(ArbitraryMeshVertex); + for(std::size_t i = 0; i <= m_tess.m_curveTreeU.size(); ++i) + { + glVertexPointer(3, GL_FLOAT, GLsizei(n), &p->vertex); + glDrawArrays(GL_LINE_STRIP, 0, GLsizei(m_tess.m_nArrayHeight)); + + if(i == m_tess.m_curveTreeU.size()) break; + + if(!BezierCurveTree_isLeaf(m_tess.m_curveTreeU[i])) + { + glVertexPointer(3, GL_FLOAT, GLsizei(n), &(m_tess.m_vertices.data() + (m_tess.m_curveTreeU[i]->index))->vertex); + glDrawArrays(GL_LINE_STRIP, 0, GLsizei(m_tess.m_nArrayHeight)); + } + + p += m_tess.m_arrayWidth[i]; + } + } + } +}; + +class RenderablePatchFixedWireframe : public OpenGLRenderable +{ + PatchTesselation& m_tess; +public: + RenderablePatchFixedWireframe(PatchTesselation& tess) : m_tess(tess) + { + } + void render(RenderStateFlags state) const + { + glVertexPointer(3, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->vertex); + const RenderIndex* strip_indices = m_tess.m_indices.data(); + for(std::size_t i = 0; inormal); + glVertexAttribPointerARB(c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->texcoord); + glVertexAttribPointerARB(c_attr_Tangent, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->tangent); + glVertexAttribPointerARB(c_attr_Binormal, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->bitangent); + } + else + { + glVertexAttribPointerARB(11, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->normal); + glVertexAttribPointerARB(8, 2, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->texcoord); + glVertexAttribPointerARB(9, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->tangent); + glVertexAttribPointerARB(10, 3, GL_FLOAT, 0, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->bitangent); + } + } + else + { + glNormalPointer(GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->normal); + glTexCoordPointer(2, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->texcoord); + } + glVertexPointer(3, GL_FLOAT, sizeof(ArbitraryMeshVertex), &m_tess.m_vertices.data()->vertex); + const RenderIndex* strip_indices = m_tess.m_indices.data(); + for(std::size_t i = 0; i m_xml_state; + + typedef Array PatchControlArray; + + class SavedState : public UndoMemento + { + public: + SavedState( + std::size_t width, + std::size_t height, + const PatchControlArray& ctrl, + const char* shader, + bool patchDef3, + std::size_t subdivisions_x, + std::size_t subdivisions_y + ) : + m_width(width), + m_height(height), + m_shader(shader), + m_ctrl(ctrl), + m_patchDef3(patchDef3), + m_subdivisions_x(subdivisions_x), + m_subdivisions_y(subdivisions_y) + { + } + + void release() + { + delete this; + } + + std::size_t m_width, m_height; + CopiedString m_shader; + PatchControlArray m_ctrl; + bool m_patchDef3; + std::size_t m_subdivisions_x; + std::size_t m_subdivisions_y; + }; + +public: + class Observer + { + public: + virtual void allocate(std::size_t size) = 0; + }; + +private: + typedef UniqueSet Observers; + Observers m_observers; + + scene::Node* m_node; + + AABB m_aabb_local; // local bbox + + CopiedString m_shader; + Shader* m_state; + + std::size_t m_width; + std::size_t m_height; +public: + bool m_patchDef3; + std::size_t m_subdivisions_x; + std::size_t m_subdivisions_y; +private: + + UndoObserver* m_undoable_observer; + MapFile* m_map; + + // dynamically allocated array of control points, size is m_width*m_height + PatchControlArray m_ctrl; + PatchControlArray m_ctrlTransformed; + + PatchTesselation m_tess; + RenderablePatchSolid m_render_solid; + RenderablePatchWireframe m_render_wireframe; + RenderablePatchFixedWireframe m_render_wireframe_fixed; + + static Shader* m_state_ctrl; + static Shader* m_state_lattice; + VertexBuffer m_ctrl_vertices; + RenderableVertexBuffer m_render_ctrl; + IndexBuffer m_lattice_indices; + RenderableIndexBuffer m_render_lattice; + + bool m_bOverlay; + + bool m_transformChanged; + Callback m_evaluateTransform; + Callback m_boundsChanged; + + void construct() + { + m_bOverlay = false; + m_width = m_height = 0; + + m_patchDef3 = false; + m_subdivisions_x = 0; + m_subdivisions_y = 0; + + check_shader(); + captureShader(); + + m_xml_state.push_back(xml_state_t::eDefault); + } + +public: + Callback m_lightsChanged; + + static int m_CycleCapIndex;// = 0; + static EPatchType m_type; + + STRING_CONSTANT(Name, "Patch"); + + Patch(scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : + m_node(&node), + m_shader(texdef_name_default()), + m_state(0), + m_undoable_observer(0), + m_map(0), + m_render_solid(m_tess), + m_render_wireframe(m_tess), + m_render_wireframe_fixed(m_tess), + m_render_ctrl(GL_POINTS, m_ctrl_vertices), + m_render_lattice(GL_LINES, m_lattice_indices, m_ctrl_vertices), + m_transformChanged(false), + m_evaluateTransform(evaluateTransform), + m_boundsChanged(boundsChanged) + { + construct(); + } + Patch(const Patch& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) : + m_node(&node), + m_shader(texdef_name_default()), + m_state(0), + m_undoable_observer(0), + m_map(0), + m_render_solid(m_tess), + m_render_wireframe(m_tess), + m_render_wireframe_fixed(m_tess), + m_render_ctrl(GL_POINTS, m_ctrl_vertices), + m_render_lattice(GL_LINES, m_lattice_indices, m_ctrl_vertices), + m_transformChanged(false), + m_evaluateTransform(evaluateTransform), + m_boundsChanged(boundsChanged) + { + construct(); + + m_patchDef3 = other.m_patchDef3; + m_subdivisions_x = other.m_subdivisions_x; + m_subdivisions_y = other.m_subdivisions_y; + setDims(other.m_width, other.m_height); + copy_ctrl(m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data()+(m_width*m_height)); + SetShader(other.m_shader.c_str()); + controlPointsChanged(); + } + + Patch(const Patch& other) : + XMLImporter(other), + XMLExporter(other), + TransformNode(other), + Bounded(other), + Cullable(other), + Snappable(), + Undoable(other), + Filterable(other), + Nameable(other), + m_state(0), + m_undoable_observer(0), + m_map(0), + m_render_solid(m_tess), + m_render_wireframe(m_tess), + m_render_wireframe_fixed(m_tess), + m_render_ctrl(GL_POINTS, m_ctrl_vertices), + m_render_lattice(GL_LINES, m_lattice_indices, m_ctrl_vertices), + m_transformChanged(false), + m_evaluateTransform(other.m_evaluateTransform), + m_boundsChanged(other.m_boundsChanged) + { + m_bOverlay = false; + + m_patchDef3 = other.m_patchDef3; + m_subdivisions_x = other.m_subdivisions_x; + m_subdivisions_y = other.m_subdivisions_y; + setDims(other.m_width, other.m_height); + copy_ctrl(m_ctrl.data(), other.m_ctrl.data(), other.m_ctrl.data()+(m_width*m_height)); + SetShader(other.m_shader.c_str()); + controlPointsChanged(); + } + + ~Patch() + { + BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeU); + BezierCurveTreeArray_deleteAll(m_tess.m_curveTreeV); + + releaseShader(); + + ASSERT_MESSAGE(m_observers.empty(), "Patch::~Patch: observers still attached"); + } + + InstanceCounter m_instanceCounter; + void instanceAttach(const scene::Path& path) + { + if(++m_instanceCounter.m_count == 1) + { + m_state->incrementUsed(); + m_map = path_find_mapfile(path.begin(), path.end()); + m_undoable_observer = GlobalUndoSystem().observer(this); + GlobalFilterSystem().registerFilterable(*this); + } + else + { + ASSERT_MESSAGE(path_find_mapfile(path.begin(), path.end()) == m_map, "node is instanced across more than one file"); + } + } + void instanceDetach(const scene::Path& path) + { + if(--m_instanceCounter.m_count == 0) + { + m_map = 0; + m_undoable_observer = 0; + GlobalUndoSystem().release(this); + GlobalFilterSystem().unregisterFilterable(*this); + m_state->decrementUsed(); + } + } + + const char* name() const + { + return "patch"; + } + void attach(const NameCallback& callback) + { + } + void detach(const NameCallback& callback) + { + } + + void attach(Observer* observer) + { + observer->allocate(m_width * m_height); + + m_observers.insert(observer); + } + void detach(Observer* observer) + { + m_observers.erase(observer); + } + + void updateFiltered() + { + if(m_node != 0) + { + if(patch_filtered(*this)) + { + m_node->enable(scene::Node::eFiltered); + } + else + { + m_node->disable(scene::Node::eFiltered); + } + } + } + + void onAllocate(std::size_t size) + { + for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i) + { + (*i)->allocate(size); + } + } + + const Matrix4& localToParent() const + { + return g_matrix4_identity; + } + const AABB& localAABB() const + { + return m_aabb_local; + } + VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const + { + return test.TestAABB(m_aabb_local, localToWorld); + } + void render_solid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + renderer.SetState(m_state, Renderer::eFullMaterials); + renderer.addRenderable(m_render_solid, localToWorld); + } + void render_wireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + renderer.SetState(m_state, Renderer::eFullMaterials); + if(m_patchDef3) + { + renderer.addRenderable(m_render_wireframe_fixed, localToWorld); + } + else + { + renderer.addRenderable(m_render_wireframe, localToWorld); + } + } + + void render_component(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const + { + renderer.SetState(m_state_lattice, Renderer::eWireframeOnly); + renderer.SetState(m_state_lattice, Renderer::eFullMaterials); + renderer.addRenderable(m_render_lattice, localToWorld); + + renderer.SetState(m_state_ctrl, Renderer::eWireframeOnly); + renderer.SetState(m_state_ctrl, Renderer::eFullMaterials); + renderer.addRenderable(m_render_ctrl, localToWorld); + } + void testSelect(Selector& selector, SelectionTest& test) + { + SelectionIntersection best; + IndexPointer::index_type* pIndex = m_tess.m_indices.data(); + for(std::size_t s=0; s TransformChangedCaller; + + void evaluateTransform() + { + if(m_transformChanged) + { + m_transformChanged = false; + revertTransform(); + m_evaluateTransform(); + } + } + + void revertTransform() + { + m_ctrlTransformed = m_ctrl; + } + void freezeTransform() + { + undoSave(); + evaluateTransform(); + ASSERT_MESSAGE(m_ctrlTransformed.size() == m_ctrl.size(), "Patch::freeze: size mismatch"); + std::copy(m_ctrlTransformed.begin(), m_ctrlTransformed.end(), m_ctrl.begin()); + } + + void controlPointsChanged() + { + transformChanged(); + evaluateTransform(); + UpdateCachedData(); + } + bool isValid() const; + + void snapto(float snap) + { + undoSave(); + + for(PatchControlIter i = m_ctrl.data(); i != m_ctrl.data() + m_ctrl.size(); ++i) + { + vector3_snap((*i).m_vertex, snap); + } + + controlPointsChanged(); + } + + + + + void RenderDebug(RenderStateFlags state) const; + void RenderNormals(RenderStateFlags state) const; + + void pushElement(const XMLElement& element) + { + switch(m_xml_state.back().state()) + { + case xml_state_t::eDefault: + ASSERT_MESSAGE(string_equal(element.name(), "patch"), "parse error"); + m_xml_state.push_back(xml_state_t::ePatch); + break; + case xml_state_t::ePatch: + if(string_equal(element.name(), "matrix")) + { + setDims(atoi(element.attribute("width")), atoi(element.attribute("height"))); + m_xml_state.push_back(xml_state_t::eMatrix); + } + else if(string_equal(element.name(), "shader")) + { + m_xml_state.push_back(xml_state_t::eShader); + } + break; + default: + ERROR_MESSAGE("parse error"); + } + + } + void popElement(const char* name) + { + switch(m_xml_state.back().state()) + { + case xml_state_t::eDefault: + ERROR_MESSAGE("parse error"); + break; + case xml_state_t::ePatch: + break; + case xml_state_t::eMatrix: + { + StringTokeniser content(m_xml_state.back().content()); + + for(PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i) + { + (*i).m_vertex[0] = string_read_float(content.getToken()); + (*i).m_vertex[1] = string_read_float(content.getToken()); + (*i).m_vertex[2] = string_read_float(content.getToken()); + (*i).m_texcoord[0] = string_read_float(content.getToken()); + (*i).m_texcoord[1] = string_read_float(content.getToken()); + } + controlPointsChanged(); + } + break; + case xml_state_t::eShader: + { + SetShader(m_xml_state.back().content()); + } + break; + default: + ERROR_MESSAGE("parse error"); + } + + ASSERT_MESSAGE(!m_xml_state.empty(), "popping empty stack"); + m_xml_state.pop_back(); + } + std::size_t write(const char* buffer, std::size_t length) + { + switch(m_xml_state.back().state()) + { + case xml_state_t::eDefault: + break; + case xml_state_t::ePatch: + break; + case xml_state_t::eMatrix: + case xml_state_t::eShader: + return m_xml_state.back().write(buffer, length); + break; + default: + ERROR_MESSAGE("parse error"); + } + return length; + } + + void exportXML(XMLImporter& importer) + { + StaticElement patchElement("patch"); + importer.pushElement(patchElement); + + { + const StaticElement element("shader"); + importer.pushElement(element); + importer.write(m_shader.c_str(), strlen(m_shader.c_str())); + importer.popElement(element.name()); + } + + { + char width[16], height[16]; + sprintf(width, "%u", Unsigned(m_width)); + sprintf(height, "%u", Unsigned(m_height)); + StaticElement element("matrix"); + element.insertAttribute("width", width); + element.insertAttribute("height", height); + + importer.pushElement(element); + { + for(PatchControlIter i = m_ctrl.data(), end = m_ctrl.data() + m_ctrl.size(); i != end; ++i) + { + importer << (*i).m_vertex[0] + << ' ' << (*i).m_vertex[1] + << ' ' << (*i).m_vertex[2] + << ' ' << (*i).m_texcoord[0] + << ' ' << (*i).m_texcoord[1]; + } + } + importer.popElement(element.name()); + } + + importer.popElement(patchElement.name()); + } + + void UpdateCachedData(); + + const char *GetShader() const + { + return m_shader.c_str(); + } + void SetShader(const char* name) + { + ASSERT_NOTNULL(name); + + if(shader_equal(m_shader.c_str(), name)) + return; + + undoSave(); + + if(m_instanceCounter.m_count != 0) + { + m_state->decrementUsed(); + } + releaseShader(); + m_shader = name; + captureShader(); + if(m_instanceCounter.m_count != 0) + { + m_state->incrementUsed(); + } + + check_shader(); + Patch_textureChanged(); + } + int getShaderFlags() const + { + if(m_state != 0) + { + return m_state->getFlags(); + } + return 0; + } + + typedef PatchControl* iterator; + typedef const PatchControl* const_iterator; + + iterator begin() + { + return m_ctrl.data(); + } + const_iterator begin() const + { + return m_ctrl.data(); + } + iterator end() + { + return m_ctrl.data() + m_ctrl.size(); + } + const_iterator end() const + { + return m_ctrl.data() + m_ctrl.size(); + } + + PatchControlArray& getControlPoints() + { + return m_ctrl; + } + PatchControlArray& getControlPointsTransformed() + { + return m_ctrlTransformed; + } + + void setDims (std::size_t w, std::size_t h); + std::size_t getWidth() const + { + return m_width; + } + std::size_t getHeight() const + { + return m_height; + } + PatchControl& ctrlAt(std::size_t row, std::size_t col) + { + return m_ctrl[row*m_width+col]; + } + const PatchControl& ctrlAt(std::size_t row, std::size_t col) const + { + return m_ctrl[row*m_width+col]; + } + + void ConstructPrefab(const AABB& aabb, EPatchPrefab eType, int axis, std::size_t width = 3, std::size_t height = 3); + void constructPlane(const AABB& aabb, int axis, std::size_t width, std::size_t height); + void InvertMatrix(); + void TransposeMatrix(); + void Redisperse(EMatrixMajor mt); + void Smooth(EMatrixMajor mt); + void InsertRemove(bool bInsert, bool bColumn, bool bFirst); + Patch* MakeCap(Patch* patch, EPatchCap eType, EMatrixMajor mt, bool bFirst); + void ConstructSeam(EPatchCap eType, Vector3* p, std::size_t width); + + void FlipTexture(int nAxis); + void TranslateTexture(float s, float t); + void ScaleTexture(float s, float t); + void RotateTexture(float angle); + void SetTextureRepeat(float s, float t); // call with s=1 t=1 for FIT + void CapTexture(); + void NaturalTexture(); + void ProjectTexture(int nAxis); + + void undoSave() + { + if(m_map != 0) + { + m_map->changed(); + } + if(m_undoable_observer != 0) + { + m_undoable_observer->save(this); + } + } + + UndoMemento* exportState() const + { + return new SavedState(m_width, m_height, m_ctrl, m_shader.c_str(), m_patchDef3, m_subdivisions_x, m_subdivisions_y); + } + void importState(const UndoMemento* state) + { + undoSave(); + + const SavedState& other = *(static_cast(state)); + + // begin duplicate of SavedState copy constructor, needs refactoring + + // copy construct + { + m_width = other.m_width; + m_height = other.m_height; + SetShader(other.m_shader.c_str()); + m_ctrl = other.m_ctrl; + onAllocate(m_ctrl.size()); + m_patchDef3 = other.m_patchDef3; + m_subdivisions_x = other.m_subdivisions_x; + m_subdivisions_y = other.m_subdivisions_y; + } + + // end duplicate code + + Patch_textureChanged(); + + controlPointsChanged(); + } + + static void constructStatic(EPatchType type) + { + Patch::m_type = type; + Patch::m_state_ctrl = GlobalShaderCache().capture("$POINT"); + Patch::m_state_lattice = GlobalShaderCache().capture("$LATTICE"); + } + + static void destroyStatic() + { + GlobalShaderCache().release("$LATTICE"); + GlobalShaderCache().release("$POINT"); + } +private: + void captureShader() + { + m_state = GlobalShaderCache().capture(m_shader.c_str()); + } + + void releaseShader() + { + GlobalShaderCache().release(m_shader.c_str()); + } + + void check_shader() + { + if(!shader_valid(GetShader())) + { + globalErrorStream() << "patch has invalid texture name: '" << GetShader() << "'\n"; + } + } + + void InsertPoints(EMatrixMajor mt, bool bFirst); + void RemovePoints(EMatrixMajor mt, bool bFirst); + + void AccumulateBBox(); + + void TesselateSubMatrixFixed(ArbitraryMeshVertex* vertices, std::size_t strideX, std::size_t strideY, unsigned int nFlagsX, unsigned int nFlagsY, PatchControl* subMatrix[3][3]); + + // uses binary trees representing bezier curves to recursively tesselate a bezier sub-patch + void TesselateSubMatrix( const BezierCurveTree *BX, const BezierCurveTree *BY, + std::size_t offStartX, std::size_t offStartY, + std::size_t offEndX, std::size_t offEndY, + std::size_t nFlagsX, std::size_t nFlagsY, + Vector3& left, Vector3& mid, Vector3& right, + Vector2& texLeft, Vector2& texMid, Vector2& texRight, + bool bTranspose ); + + // tesselates the entire surface + void BuildTesselationCurves(EMatrixMajor major); + void accumulateVertexTangentSpace(std::size_t index, Vector3 tangentX[6], Vector3 tangentY[6], Vector2 tangentS[6], Vector2 tangentT[6], std::size_t index0, std::size_t index1); + void BuildVertexArray(); +}; + +inline bool Patch_importHeader(Patch& patch, Tokeniser& tokeniser) +{ + tokeniser.nextLine(); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "{")); + return true; +} + +inline bool Patch_importShader(Patch& patch, Tokeniser& tokeniser) +{ + // parse shader name + tokeniser.nextLine(); + const char* texture = tokeniser.getToken(); + if(texture == 0) + { + Tokeniser_unexpectedError(tokeniser, texture, "#texture-name"); + return false; + } + if(string_equal(texture, "NULL")) + { + patch.SetShader(texdef_name_default()); + } + else + { + StringOutputStream shader(string_length(GlobalTexturePrefix_get()) + string_length(texture)); + shader << GlobalTexturePrefix_get() << texture; + patch.SetShader(shader.c_str()); + } + return true; +} + +inline bool PatchDoom3_importShader(Patch& patch, Tokeniser& tokeniser) +{ + // parse shader name + tokeniser.nextLine(); + const char *shader = tokeniser.getToken(); + if(shader == 0) + { + Tokeniser_unexpectedError(tokeniser, shader, "#shader-name"); + return false; + } + if(string_equal(shader, "_emptyname")) + { + shader = texdef_name_default(); + } + patch.SetShader(shader); + return true; +} + +inline bool Patch_importParams(Patch& patch, Tokeniser& tokeniser) +{ + tokeniser.nextLine(); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); + + // parse matrix dimensions + { + std::size_t c, r; + RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, c)); + RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, r)); + + patch.setDims(c, r); + } + + if(patch.m_patchDef3) + { + RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, patch.m_subdivisions_x)); + RETURN_FALSE_IF_FAIL(Tokeniser_getSize(tokeniser, patch.m_subdivisions_y)); + } + + // ignore contents/flags/value + int tmp; + RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, tmp)); + RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, tmp)); + RETURN_FALSE_IF_FAIL(Tokeniser_getInteger(tokeniser, tmp)); + + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, ")")); + return true; +} + +inline bool Patch_importMatrix(Patch& patch, Tokeniser& tokeniser) +{ + // parse matrix + tokeniser.nextLine(); + RETURN_FALSE_IF_FAIL(Tokeniser_parseToken(tokeniser, "(")); + { + for(std::size_t c=0; cm_vertex, best); + if(best.valid()) + { + Selector_add(selector, m_selectable, best); + } + } + void snapto(float snap) + { + vector3_snap(m_ctrl->m_vertex, snap); + } +}; + + +class PatchInstance : +public Patch::Observer, +public scene::Instance, +public Selectable, +public Renderable, +public SelectionTestable, +public ComponentSelectionTestable, +public ComponentEditable, +public ComponentSnappable, +public PlaneSelectable, +public LightCullable +{ + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts() + { + InstanceStaticCast::install(m_casts); + InstanceContainedCast::install(m_casts); + InstanceContainedCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceStaticCast::install(m_casts); + InstanceIdentityCast::install(m_casts); + InstanceContainedCast::install(m_casts); + } + InstanceTypeCastTable& get() + { + return m_casts; + } + }; + + + Patch& m_patch; + typedef std::vector PatchControlInstances; + PatchControlInstances m_ctrl_instances; + + ObservedSelectable m_selectable; + + DragPlanes m_dragPlanes; + + mutable RenderablePointVector m_render_selected; + mutable AABB m_aabb_component; + + static Shader* m_state_selpoint; + + const LightList* m_lightList; + + TransformModifier m_transform; +public: + + typedef LazyStatic StaticTypeCasts; + + void lightsChanged() + { + m_lightList->lightsChanged(); + } + typedef MemberCaller LightsChangedCaller; + + STRING_CONSTANT(Name, "PatchInstance"); + + PatchInstance(const scene::Path& path, scene::Instance* parent, Patch& patch) : + Instance(path, parent, this, StaticTypeCasts::instance().get()), + m_patch(patch), + m_selectable(SelectedChangedCaller(*this)), + m_dragPlanes(SelectedChangedComponentCaller(*this)), + m_render_selected(GL_POINTS), + m_transform(Patch::TransformChangedCaller(m_patch), ApplyTransformCaller(*this)) + { + m_patch.instanceAttach(Instance::path()); + m_patch.attach(this); + + m_lightList = &GlobalShaderCache().attach(*this); + m_patch.m_lightsChanged = LightsChangedCaller(*this); + + Instance::setTransformChangedCallback(LightsChangedCaller(*this)); + } + ~PatchInstance() + { + Instance::setTransformChangedCallback(Callback()); + + m_patch.m_lightsChanged = Callback(); + GlobalShaderCache().detach(*this); + + m_patch.detach(this); + m_patch.instanceDetach(Instance::path()); + } + + void selectedChanged(const Selectable& selectable) + { + GlobalSelectionSystem().getObserver(SelectionSystem::ePrimitive)(selectable); + GlobalSelectionSystem().onSelectedChanged(*this, selectable); + + Instance::selectedChanged(); + } + typedef MemberCaller1 SelectedChangedCaller; + + void selectedChangedComponent(const Selectable& selectable) + { + GlobalSelectionSystem().getObserver(SelectionSystem::eComponent)(selectable); + GlobalSelectionSystem().onComponentSelection(*this, selectable); + } + typedef MemberCaller1 SelectedChangedComponentCaller; + + Patch& getPatch() + { + return m_patch; + } + Bounded& get(NullType) + { + return m_patch; + } + Cullable& get(NullType) + { + return m_patch; + } + Transformable& get(NullType) + { + return m_transform; + } + + static void constructStatic() + { + m_state_selpoint = GlobalShaderCache().capture("$SELPOINT"); + } + + static void destroyStatic() + { + GlobalShaderCache().release("$SELPOINT"); + } + + + void allocate(std::size_t size) + { + m_ctrl_instances.clear(); + m_ctrl_instances.reserve(size); + for(Patch::iterator i = m_patch.begin(); i != m_patch.end(); ++i) + { + m_ctrl_instances.push_back(PatchControlInstance(&(*i), SelectedChangedComponentCaller(*this))); + } + } + + void setSelected(bool select) + { + m_selectable.setSelected(select); + } + bool isSelected() const + { + return m_selectable.isSelected(); + } + + + void update_selected() const + { + m_render_selected.clear(); + Patch::iterator ctrl = m_patch.getControlPointsTransformed().begin(); + for(PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl) + { + if((*i).m_selectable.isSelected()) + { + const Colour4b colour_selected(0, 0, 255, 255); + m_render_selected.push_back(PointVertex(reinterpret_cast((*ctrl).m_vertex), colour_selected)); + } + } + } + +#if 0 + void render(Renderer& renderer, const VolumeTest& volume) const + { + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent + && m_selectable.isSelected()) + { + renderer.Highlight(Renderer::eFace, false); + + m_patch.render(renderer, volume, localToWorld()); + + if(GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex) + { + renderer.Highlight(Renderer::ePrimitive, false); + + m_patch.render_component(renderer, volume, localToWorld()); + + renderComponentsSelected(renderer, volume); + } + } + else + m_patch.render(renderer, volume, localToWorld()); + } +#endif + + void renderSolid(Renderer& renderer, const VolumeTest& volume) const + { + m_patch.evaluateTransform(); + renderer.setLights(*m_lightList); + m_patch.render_solid(renderer, volume, localToWorld()); + + renderComponentsSelected(renderer, volume); + } + + void renderWireframe(Renderer& renderer, const VolumeTest& volume) const + { + m_patch.evaluateTransform(); + m_patch.render_wireframe(renderer, volume, localToWorld()); + + renderComponentsSelected(renderer, volume); + } + + void renderComponentsSelected(Renderer& renderer, const VolumeTest& volume) const + { + m_patch.evaluateTransform(); + update_selected(); + if(!m_render_selected.empty()) + { + renderer.Highlight(Renderer::ePrimitive, false); + renderer.SetState(m_state_selpoint, Renderer::eWireframeOnly); + renderer.SetState(m_state_selpoint, Renderer::eFullMaterials); + renderer.addRenderable(m_render_selected, localToWorld()); + } + } + void renderComponents(Renderer& renderer, const VolumeTest& volume) const + { + m_patch.evaluateTransform(); + if(GlobalSelectionSystem().ComponentMode() == SelectionSystem::eVertex) + { + m_patch.render_component(renderer, volume, localToWorld()); + } + } + + void testSelect(Selector& selector, SelectionTest& test) + { + test.BeginMesh(localToWorld(), true); + m_patch.testSelect(selector, test); + } + + void selectCtrl(bool select) + { + for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) + { + (*i).m_selectable.setSelected(select); + } + } + bool isSelectedComponents() const + { + for(PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) + { + if((*i).m_selectable.isSelected()) + { + return true; + } + } + return false; + } + void setSelectedComponents(bool select, SelectionSystem::EComponentMode mode) + { + if(mode == SelectionSystem::eVertex) + { + selectCtrl(select); + } + else if(mode == SelectionSystem::eFace) + { + m_dragPlanes.setSelected(select); + } + } + const AABB& getSelectedComponentsBounds() const + { + m_aabb_component = AABB(); + + for(PatchControlInstances::const_iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) + { + if((*i).m_selectable.isSelected()) + { + aabb_extend_by_point_safe(m_aabb_component, (*i).m_ctrl->m_vertex); + } + } + + return m_aabb_component; + } + + void testSelectComponents(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) + { + test.BeginMesh(localToWorld()); + + switch(mode) + { + case SelectionSystem::eVertex: + { + for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) + { + (*i).testSelect(selector, test); + } + } + break; + default: + break; + } + } + + bool selectedVertices() + { + for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) + { + if((*i).m_selectable.isSelected()) + { + return true; + } + } + return false; + } + + void transformComponents(const Matrix4& matrix) + { + if(selectedVertices()) + { + PatchControlIter ctrl = m_patch.getControlPointsTransformed().begin(); + for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i, ++ctrl) + { + if((*i).m_selectable.isSelected()) + { + matrix4_transform_point(matrix, (*ctrl).m_vertex); + } + } + m_patch.UpdateCachedData(); + } + + if(m_dragPlanes.isSelected()) // this should only be true when the transform is a pure translation. + { + m_patch.transform(m_dragPlanes.evaluateTransform(vector4_to_vector3(matrix.t()))); + } + } + + + void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) + { + test.BeginMesh(localToWorld()); + + m_dragPlanes.selectPlanes(m_patch.localAABB(), selector, test, selectedPlaneCallback); + } + void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) + { + m_dragPlanes.selectReversedPlanes(m_patch.localAABB(), selector, selectedPlanes); + } + + + void snapComponents(float snap) + { + if(selectedVertices()) + { + m_patch.undoSave(); + for(PatchControlInstances::iterator i = m_ctrl_instances.begin(); i != m_ctrl_instances.end(); ++i) + { + if((*i).m_selectable.isSelected()) + { + (*i).snapto(snap); + } + } + m_patch.controlPointsChanged(); + } + } + + void evaluateTransform() + { + Matrix4 matrix(m_transform.calculateTransform()); + + if(m_transform.getType() == TRANSFORM_PRIMITIVE) + { + m_patch.transform(matrix); + } + else + { + transformComponents(matrix); + } + } + void applyTransform() + { + m_patch.revertTransform(); + evaluateTransform(); + m_patch.freezeTransform(); + } + typedef MemberCaller ApplyTransformCaller; + + + bool testLight(const RendererLight& light) const + { + return light.testAABB(worldAABB()); + } +}; + + +template +class PatchNode : + public scene::Node::Symbiot, + public scene::Instantiable, + public scene::Cloneable +{ + typedef PatchNode Self; + + class TypeCasts + { + InstanceTypeCastTable m_casts; + public: + TypeCasts() + { + NodeStaticCast::install(m_casts); + NodeStaticCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + NodeContainedCast::install(m_casts); + } + InstanceTypeCastTable& get() + { + return m_casts; + } + }; + + + scene::Node m_node; + InstanceSet m_instances; + Patch m_patch; + TokenImporter m_importMap; + TokenExporter m_exportMap; + +public: + + typedef LazyStatic StaticTypeCasts; + + Snappable& get(NullType) + { + return m_patch; + } + TransformNode& get(NullType) + { + return m_patch; + } + Patch& get(NullType) + { + return m_patch; + } + XMLImporter& get(NullType) + { + return m_patch; + } + XMLExporter& get(NullType) + { + return m_patch; + } + MapImporter& get(NullType) + { + return m_importMap; + } + MapExporter& get(NullType) + { + return m_exportMap; + } + Nameable& get(NullType) + { + return m_patch; + } + + PatchNode(bool patchDef3 = false) : + m_node(this, this, StaticTypeCasts::instance().get()), + m_patch(m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), + m_importMap(m_patch), + m_exportMap(m_patch) + { + m_patch.m_patchDef3 = patchDef3; + } + PatchNode(const PatchNode& other) : + scene::Node::Symbiot(other), + scene::Instantiable(other), + scene::Cloneable(other), + m_node(this, this, StaticTypeCasts::instance().get()), + m_patch(other.m_patch, m_node, InstanceSetEvaluateTransform::Caller(m_instances), InstanceSet::BoundsChangedCaller(m_instances)), + m_importMap(m_patch), + m_exportMap(m_patch) + { + } + void release() + { + delete this; + } + scene::Node& node() + { + return m_node; + } + Patch& get() + { + return m_patch; + } + const Patch& get() const + { + return m_patch; + } + + scene::Node& clone() const + { + return (new PatchNode(*this))->node(); + } + + scene::Instance* create(const scene::Path& path, scene::Instance* parent) + { + return new PatchInstance(path, parent, m_patch); + } + 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); + } + scene::Instance* erase(scene::Instantiable::Observer* observer, const scene::Path& path) + { + return m_instances.erase(observer, path); + } +}; + + + +typedef PatchNode PatchNodeQuake3; +typedef PatchNode PatchNodeDoom3; + +inline Patch* Node_getPatch(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +inline PatchInstance* Instance_getPatch(scene::Instance& instance) +{ + return InstanceTypeCast::cast(instance); +} + +template +class PatchSelectedVisitor : public SelectionSystem::Visitor +{ + const Functor& m_functor; +public: + PatchSelectedVisitor(const Functor& functor) : m_functor(functor) + { + } + void visit(scene::Instance& instance) const + { + PatchInstance* patch = Instance_getPatch(instance); + if(patch != 0) + { + m_functor(*patch); + } + } +}; + +template +inline void Scene_forEachSelectedPatch(const Functor& functor) +{ + GlobalSelectionSystem().foreachSelected(PatchSelectedVisitor(functor)); +} + + +template +class PatchVisibleSelectedVisitor : public SelectionSystem::Visitor +{ + const Functor& m_functor; +public: + PatchVisibleSelectedVisitor(const Functor& functor) : m_functor(functor) + { + } + void visit(scene::Instance& instance) const + { + PatchInstance* patch = Instance_getPatch(instance); + if(patch != 0 + && instance.path().top().get().visible()) + { + m_functor(*patch); + } + } +}; + +template +inline void Scene_forEachVisibleSelectedPatchInstance(const Functor& functor) +{ + GlobalSelectionSystem().foreachSelected(PatchVisibleSelectedVisitor(functor)); +} + +template +class PatchForEachWalker : public scene::Graph::Walker +{ + const Functor& m_functor; +public: + PatchForEachWalker(const Functor& functor) : m_functor(functor) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Patch* patch = Node_getPatch(path.top()); + if(patch != 0) + { + m_functor(*patch); + } + } + return true; + } +}; + +template +inline void Scene_forEachVisiblePatch(const Functor& functor) +{ + GlobalSceneGraph().traverse(PatchForEachWalker(functor)); +} + +template +class PatchForEachSelectedWalker : public scene::Graph::Walker +{ + const Functor& m_functor; +public: + PatchForEachSelectedWalker(const Functor& functor) : m_functor(functor) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Patch* patch = Node_getPatch(path.top()); + if(patch != 0 + && Instance_getSelectable(instance)->isSelected()) + { + m_functor(*patch); + } + } + return true; + } +}; + +template +inline void Scene_forEachVisibleSelectedPatch(const Functor& functor) +{ + GlobalSceneGraph().traverse(PatchForEachSelectedWalker(functor)); +} + +template +class PatchForEachInstanceWalker : public scene::Graph::Walker +{ + const Functor& m_functor; +public: + PatchForEachInstanceWalker(const Functor& functor) : m_functor(functor) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + PatchInstance* patch = Instance_getPatch(instance); + if(patch != 0) + { + m_functor(*patch); + } + } + return true; + } +}; + +template +inline void Scene_forEachVisiblePatchInstance(const Functor& functor) +{ + GlobalSceneGraph().traverse(PatchForEachInstanceWalker(functor)); +} + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/patchdialog.cpp b/misc/mediasource/netradiant-src/radiant/patchdialog.cpp new file mode 100644 index 00000000..b62b574e --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patchdialog.cpp @@ -0,0 +1,1218 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Patch Dialog +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "patchdialog.h" + +#include "itexdef.h" + +#include "debugging/debugging.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gtkutil/idledraw.h" +#include "gtkutil/entry.h" +#include "gtkutil/button.h" +#include "gtkutil/nonmodal.h" +#include "dialog.h" +#include "gtkdlgs.h" +#include "mainframe.h" +#include "patchmanip.h" +#include "patch.h" +#include "commands.h" +#include "preferences.h" +#include "signal/isignal.h" + + +#include + +// the increment we are using for the patch inspector (this is saved in the prefs) +struct pi_globals_t +{ + float shift[2]; + float scale[2]; + float rotate; + + pi_globals_t() + { + shift[0] = 8.0f; + shift[1] = 8.0f; + scale[0] = 0.5f; + scale[1] = 0.5f; + rotate = 45.0f; + } +}; + +pi_globals_t g_pi_globals; + +class PatchFixedSubdivisions +{ +public: + PatchFixedSubdivisions() : m_enabled(false), m_x(0), m_y(0) + { + } + PatchFixedSubdivisions(bool enabled, std::size_t x, std::size_t y) : m_enabled(enabled), m_x(x), m_y(y) + { + } + bool m_enabled; + std::size_t m_x; + std::size_t m_y; +}; + +void Patch_getFixedSubdivisions(const Patch& patch, PatchFixedSubdivisions& subdivisions) +{ + subdivisions.m_enabled = patch.m_patchDef3; + subdivisions.m_x = patch.m_subdivisions_x; + subdivisions.m_y = patch.m_subdivisions_y; +} + +const std::size_t MAX_PATCH_SUBDIVISIONS = 32; + +void Patch_setFixedSubdivisions(Patch& patch, const PatchFixedSubdivisions& subdivisions) +{ + patch.undoSave(); + + patch.m_patchDef3 = subdivisions.m_enabled; + patch.m_subdivisions_x = subdivisions.m_x; + patch.m_subdivisions_y = subdivisions.m_y; + + if(patch.m_subdivisions_x == 0) + { + patch.m_subdivisions_x = 4; + } + else if(patch.m_subdivisions_x > MAX_PATCH_SUBDIVISIONS) + { + patch.m_subdivisions_x = MAX_PATCH_SUBDIVISIONS; + } + if(patch.m_subdivisions_y == 0) + { + patch.m_subdivisions_y = 4; + } + else if(patch.m_subdivisions_y > MAX_PATCH_SUBDIVISIONS) + { + patch.m_subdivisions_y = MAX_PATCH_SUBDIVISIONS; + } + + SceneChangeNotify(); + Patch_textureChanged(); + patch.controlPointsChanged(); +} + +class PatchGetFixedSubdivisions +{ + PatchFixedSubdivisions& m_subdivisions; +public: + PatchGetFixedSubdivisions(PatchFixedSubdivisions& subdivisions) : m_subdivisions(subdivisions) + { + } + void operator()(Patch& patch) + { + Patch_getFixedSubdivisions(patch, m_subdivisions); + SceneChangeNotify(); + } +}; + +void Scene_PatchGetFixedSubdivisions(PatchFixedSubdivisions& subdivisions) +{ +#if 1 + if(GlobalSelectionSystem().countSelected() != 0) + { + Patch* patch = Node_getPatch(GlobalSelectionSystem().ultimateSelected().path().top()); + if(patch != 0) + { + Patch_getFixedSubdivisions(*patch, subdivisions); + } + } +#else + Scene_forEachVisibleSelectedPatch(PatchGetFixedSubdivisions(subdivisions)); +#endif +} + +class PatchSetFixedSubdivisions +{ + const PatchFixedSubdivisions& m_subdivisions; +public: + PatchSetFixedSubdivisions(const PatchFixedSubdivisions& subdivisions) : m_subdivisions(subdivisions) + { + } + void operator()(Patch& patch) const + { + Patch_setFixedSubdivisions(patch, m_subdivisions); + } +}; + +void Scene_PatchSetFixedSubdivisions(const PatchFixedSubdivisions& subdivisions) +{ + UndoableCommand command("patchSetFixedSubdivisions"); + Scene_forEachVisibleSelectedPatch(PatchSetFixedSubdivisions(subdivisions)); +} + +typedef struct _GtkCheckButton GtkCheckButton; + +class Subdivisions +{ +public: + GtkCheckButton* m_enabled; + GtkEntry* m_horizontal; + GtkEntry* m_vertical; + Subdivisions() : m_enabled(0), m_horizontal(0), m_vertical(0) + { + } + void update() + { + PatchFixedSubdivisions subdivisions; + Scene_PatchGetFixedSubdivisions(subdivisions); + + toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(m_enabled), subdivisions.m_enabled); + + if(subdivisions.m_enabled) + { + entry_set_int(m_horizontal, static_cast(subdivisions.m_x)); + entry_set_int(m_vertical, static_cast(subdivisions.m_y)); + gtk_widget_set_sensitive(GTK_WIDGET(m_horizontal), TRUE); + gtk_widget_set_sensitive(GTK_WIDGET(m_vertical), TRUE); + } + else + { + gtk_entry_set_text(m_horizontal, ""); + gtk_entry_set_text(m_vertical, ""); + gtk_widget_set_sensitive(GTK_WIDGET(m_horizontal), FALSE); + gtk_widget_set_sensitive(GTK_WIDGET(m_vertical), FALSE); + } + } + void cancel() + { + update(); + } + typedef MemberCaller CancelCaller; + void apply() + { + Scene_PatchSetFixedSubdivisions( + PatchFixedSubdivisions( + gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(m_enabled)) != FALSE, + static_cast(entry_get_int(m_horizontal)), + static_cast(entry_get_int(m_vertical)) + ) + ); + } + typedef MemberCaller ApplyCaller; + static void applyGtk(GtkToggleButton* toggle, Subdivisions* self) + { + self->apply(); + } +}; + +class PatchInspector : public Dialog +{ + GtkWindow* BuildDialog(); + Subdivisions m_subdivisions; + NonModalEntry m_horizontalSubdivisionsEntry; + NonModalEntry m_verticalSubdivisionsEntry; +public: + IdleDraw m_idleDraw; + WindowPositionTracker m_position_tracker; + + Patch *m_Patch; + + CopiedString m_strName; + float m_fS; + float m_fT; + float m_fX; + float m_fY; + float m_fZ; +/* float m_fHScale; + float m_fHShift; + float m_fRotate; + float m_fVScale; + float m_fVShift; */ + int m_nCol; + int m_nRow; + GtkComboBox *m_pRowCombo; + GtkComboBox *m_pColCombo; + std::size_t m_countRows; + std::size_t m_countCols; + + // turn on/off processing of the "changed" "value_changed" messages + // (need to turn off when we are feeding data in) + // NOTE: much more simple than blocking signals + bool m_bListenChanged; + + PatchInspector() : + m_horizontalSubdivisionsEntry(Subdivisions::ApplyCaller(m_subdivisions), Subdivisions::CancelCaller(m_subdivisions)), + m_verticalSubdivisionsEntry(Subdivisions::ApplyCaller(m_subdivisions), Subdivisions::CancelCaller(m_subdivisions)), + m_idleDraw(MemberCaller(*this)) + { + m_fS = 0.0f; + m_fT = 0.0f; + m_fX = 0.0f; + m_fY = 0.0f; + m_fZ = 0.0f; + m_nCol = 0; + m_nRow = 0; + m_countRows = 0; + m_countCols = 0; + m_Patch = 0; + m_bListenChanged = true; + + m_position_tracker.setPosition(c_default_window_pos); + } + + bool visible() + { + return GTK_WIDGET_VISIBLE(GetWidget()); + } + +// void UpdateInfo(); +// void SetPatchInfo(); + void GetPatchInfo(); + void UpdateSpinners(bool bUp, int nID); + // read the current patch on map and initialize m_fX m_fY accordingly + void UpdateRowColInfo(); + // sync the dialog our internal data structures + // depending on the flag it will read or write + // we use m_nCol m_nRow m_fX m_fY m_fZ m_fS m_fT m_strName + // (NOTE: this doesn't actually commit stuff to the map or read from it) + void importData(); + void exportData(); +}; + +PatchInspector g_PatchInspector; + +void PatchInspector_constructWindow(GtkWindow* main_window) +{ + g_PatchInspector.m_parent = main_window; + g_PatchInspector.Create(); +} +void PatchInspector_destroyWindow() +{ + g_PatchInspector.Destroy(); +} + +void PatchInspector_queueDraw() +{ + if(g_PatchInspector.visible()) + { + g_PatchInspector.m_idleDraw.queueDraw(); + } +} + +void DoPatchInspector() +{ + g_PatchInspector.GetPatchInfo(); + if (!g_PatchInspector.visible()) + g_PatchInspector.ShowDlg(); +} + +void PatchInspector_toggleShown() +{ + if (g_PatchInspector.visible()) + { + g_PatchInspector.m_Patch = 0; + g_PatchInspector.HideDlg(); + } + else + DoPatchInspector(); +} + + +// ============================================================================= +// static functions + +// memorize the current state (that is don't try to undo our do before changing something else) +static void OnApply (GtkWidget *widget, gpointer data) +{ + g_PatchInspector.exportData(); + if (g_PatchInspector.m_Patch != 0) + { + UndoableCommand command("patchSetTexture"); + g_PatchInspector.m_Patch->undoSave(); + + if (!texdef_name_valid(g_PatchInspector.m_strName.c_str())) + { + globalErrorStream() << "invalid texture name '" << g_PatchInspector.m_strName.c_str() << "'\n"; + g_PatchInspector.m_strName = texdef_name_default(); + } + g_PatchInspector.m_Patch->SetShader(g_PatchInspector.m_strName.c_str()); + + std::size_t r = g_PatchInspector.m_nRow; + std::size_t c = g_PatchInspector.m_nCol; + if(r < g_PatchInspector.m_Patch->getHeight() + && c < g_PatchInspector.m_Patch->getWidth()) + { + PatchControl& p = g_PatchInspector.m_Patch->ctrlAt(r,c); + p.m_vertex[0] = g_PatchInspector.m_fX; + p.m_vertex[1] = g_PatchInspector.m_fY; + p.m_vertex[2] = g_PatchInspector.m_fZ; + p.m_texcoord[0] = g_PatchInspector.m_fS; + p.m_texcoord[1] = g_PatchInspector.m_fT; + g_PatchInspector.m_Patch->controlPointsChanged(); + } + } +} + +static void OnSelchangeComboColRow (GtkWidget *widget, gpointer data) +{ + if (!g_PatchInspector.m_bListenChanged) + return; + // retrieve the current m_nRow and m_nCol, other params are not relevant + g_PatchInspector.exportData(); + // read the changed values ourselves + g_PatchInspector.UpdateRowColInfo(); + // now reflect our changes + g_PatchInspector.importData(); +} + +class PatchSetTextureRepeat +{ + float m_s, m_t; +public: + PatchSetTextureRepeat(float s, float t) : m_s(s), m_t(t) + { + } + void operator()(Patch& patch) const + { + patch.SetTextureRepeat(m_s, m_t); + } +}; + +void Scene_PatchTileTexture_Selected(scene::Graph& graph, float s, float t) +{ + Scene_forEachVisibleSelectedPatch(PatchSetTextureRepeat(s, t)); + SceneChangeNotify(); +} + +static void OnBtnPatchdetails (GtkWidget *widget, gpointer data) +{ + UndoableCommand command("patchCapTexture"); + + Scene_PatchCapTexture_Selected(GlobalSceneGraph()); +} + +static void OnBtnPatchfit (GtkWidget *widget, gpointer data) +{ + UndoableCommand command("patchFitTexture"); + + Scene_PatchTileTexture_Selected(GlobalSceneGraph(), 1, 1); +} + +static void OnBtnPatchnatural (GtkWidget *widget, gpointer data) +{ + UndoableCommand command("patchNaturalTexture"); + + Scene_PatchNaturalTexture_Selected(GlobalSceneGraph()); +} + +static void OnBtnPatchreset (GtkWidget *widget, gpointer data) +{ + float fx, fy; + if (DoTextureLayout (&fx, &fy) == eIDOK) + { + UndoableCommand command("patchTileTexture"); + Scene_PatchTileTexture_Selected(GlobalSceneGraph(), fx, fy); + } +} + +struct PatchRotateTexture +{ + float m_angle; +public: + PatchRotateTexture(float angle) : m_angle(angle) + { + } + void operator()(Patch& patch) const + { + patch.RotateTexture(m_angle); + } +}; + +void Scene_PatchRotateTexture_Selected(scene::Graph& graph, float angle) +{ + Scene_forEachVisibleSelectedPatch(PatchRotateTexture(angle)); +} + +class PatchScaleTexture +{ + float m_s, m_t; +public: + PatchScaleTexture(float s, float t) : m_s(s), m_t(t) + { + } + void operator()(Patch& patch) const + { + patch.ScaleTexture(m_s, m_t); + } +}; + +float Patch_convertScale(float scale) +{ + if(scale > 0) + { + return scale; + } + if(scale < 0) + { + return -1 / scale; + } + return 1; +} + +void Scene_PatchScaleTexture_Selected(scene::Graph& graph, float s, float t) +{ + Scene_forEachVisibleSelectedPatch(PatchScaleTexture(Patch_convertScale(s), Patch_convertScale(t))); +} + +class PatchTranslateTexture +{ + float m_s, m_t; +public: + PatchTranslateTexture(float s, float t) + : m_s(s), m_t(t) + { + } + void operator()(Patch& patch) const + { + patch.TranslateTexture(m_s, m_t); + } +}; + +void Scene_PatchTranslateTexture_Selected(scene::Graph& graph, float s, float t) +{ + Scene_forEachVisibleSelectedPatch(PatchTranslateTexture(s, t)); +} + +static void OnSpinChanged (GtkAdjustment *adj, gpointer data) +{ + texdef_t td; + + td.rotate = 0; + td.scale[0] = td.scale[1] = 0; + td.shift[0] = td.shift[1] = 0; + + if (adj->value == 0) + return; + + if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "hshift_adj")) + { + g_pi_globals.shift[0] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); + + if (adj->value > 0) + td.shift[0] = g_pi_globals.shift[0]; + else + td.shift[0] = -g_pi_globals.shift[0]; + } + else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "vshift_adj")) + { + g_pi_globals.shift[1] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); + + if (adj->value > 0) + td.shift[1] = g_pi_globals.shift[1]; + else + td.shift[1] = -g_pi_globals.shift[1]; + } + else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "hscale_adj")) + { + g_pi_globals.scale[0] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); + if (g_pi_globals.scale[0] == 0.0f) + return; + if (adj->value > 0) + td.scale[0] = g_pi_globals.scale[0]; + else + td.scale[0] = -g_pi_globals.scale[0]; + } + else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "vscale_adj")) + { + g_pi_globals.scale[1] = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); + if (g_pi_globals.scale[1] == 0.0f) + return; + if (adj->value > 0) + td.scale[1] = g_pi_globals.scale[1]; + else + td.scale[1] = -g_pi_globals.scale[1]; + } + else if (adj == g_object_get_data (G_OBJECT (g_PatchInspector.GetWidget()), "rotate_adj")) + { + g_pi_globals.rotate = static_cast(atof (gtk_entry_get_text (GTK_ENTRY (data)))); + + if (adj->value > 0) + td.rotate = g_pi_globals.rotate; + else + td.rotate = -g_pi_globals.rotate; + } + + adj->value = 0; + + // will scale shift rotate the patch accordingly + + + if (td.shift[0] || td.shift[1]) + { + UndoableCommand command("patchTranslateTexture"); + Scene_PatchTranslateTexture_Selected (GlobalSceneGraph(), td.shift[0], td.shift[1]); + } + else if (td.scale[0] || td.scale[1]) + { + UndoableCommand command("patchScaleTexture"); + Scene_PatchScaleTexture_Selected (GlobalSceneGraph(), td.scale[0], td.scale[1]); + } + else if (td.rotate) + { + UndoableCommand command("patchRotateTexture"); + Scene_PatchRotateTexture_Selected (GlobalSceneGraph(), td.rotate); + } + + // update the point-by-point view + OnSelchangeComboColRow(0,0); +} + +static gint OnDialogKey (GtkWidget* widget, GdkEventKey* event, gpointer data) +{ + if (event->keyval == GDK_Return) + { + OnApply (0, 0); + return TRUE; + } + else if (event->keyval == GDK_Escape) + { + g_PatchInspector.GetPatchInfo(); + return TRUE; + } + return FALSE; +} + +// ============================================================================= +// PatchInspector class + +GtkWindow* PatchInspector::BuildDialog() +{ + GtkWindow* window = create_floating_window("Patch Properties", m_parent); + + m_position_tracker.connect(window); + + global_accel_connect_window(window); + + window_connect_focus_in_clear_focus_widget(window); + + + { + GtkVBox* vbox = GTK_VBOX(gtk_vbox_new(FALSE, 5)); + gtk_container_set_border_width(GTK_CONTAINER(vbox), 5); + gtk_widget_show(GTK_WIDGET(vbox)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); + { + GtkHBox* hbox = GTK_HBOX(gtk_hbox_new(FALSE, 5)); + gtk_widget_show(GTK_WIDGET(hbox)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), TRUE, TRUE, 0); + { + GtkVBox* vbox2 = GTK_VBOX(gtk_vbox_new(FALSE, 0)); + gtk_container_set_border_width(GTK_CONTAINER(vbox2), 0); + gtk_widget_show(GTK_WIDGET(vbox2)); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox2), TRUE, TRUE, 0); + { + GtkFrame* frame = GTK_FRAME(gtk_frame_new("Details")); + gtk_widget_show(GTK_WIDGET(frame)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(frame), TRUE, TRUE, 0); + { + GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 5)); + gtk_container_set_border_width(GTK_CONTAINER(vbox3), 5); + gtk_widget_show(GTK_WIDGET(vbox3)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); + { + GtkTable* table = GTK_TABLE(gtk_table_new(2, 2, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings(table, 5); + gtk_table_set_col_spacings(table, 5); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Row:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Column:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 1, 2, 0, 1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); + g_signal_connect(G_OBJECT(combo), "changed", G_CALLBACK(OnSelchangeComboColRow), this); + AddDialogData(*combo, m_nRow); + + gtk_widget_show(GTK_WIDGET(combo)); + gtk_table_attach(table, GTK_WIDGET(combo), 0, 1, 1, 2, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(combo), 60, -1); + m_pRowCombo = combo; + } + + { + GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); + g_signal_connect(G_OBJECT(combo), "changed", G_CALLBACK(OnSelchangeComboColRow), this); + AddDialogData(*combo, m_nCol); + + gtk_widget_show(GTK_WIDGET(combo)); + gtk_table_attach(table, GTK_WIDGET(combo), 1, 2, 1, 2, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(combo), 60, -1); + m_pColCombo = combo; + } + } + GtkTable* table = GTK_TABLE(gtk_table_new(5, 2, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings(table, 5); + gtk_table_set_col_spacings(table, 5); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("X:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Y:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Z:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 2, 3, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("S:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 3, 4, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("T:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 4, 5, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 0, 1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + AddDialogData(*entry, m_fX); + + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + AddDialogData(*entry, m_fY); + + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 2, 3, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + AddDialogData(*entry, m_fZ); + + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 3, 4, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + AddDialogData(*entry, m_fS); + + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 4, 5, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + AddDialogData(*entry, m_fT); + + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); + } + } + } + if(g_pGameDescription->mGameType == "doom3") + { + GtkFrame* frame = GTK_FRAME(gtk_frame_new("Tesselation")); + gtk_widget_show(GTK_WIDGET(frame)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(frame), TRUE, TRUE, 0); + { + GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 5)); + gtk_container_set_border_width(GTK_CONTAINER(vbox3), 5); + gtk_widget_show(GTK_WIDGET(vbox3)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); + { + GtkTable* table = GTK_TABLE(gtk_table_new(3, 2, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings(table, 5); + gtk_table_set_col_spacings(table, 5); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Fixed")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new()); + gtk_widget_show(GTK_WIDGET(check)); + gtk_table_attach(table, GTK_WIDGET(check), 1, 2, 0, 1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + m_subdivisions.m_enabled = check; + guint handler_id = g_signal_connect(G_OBJECT(check), "toggled", G_CALLBACK(&Subdivisions::applyGtk), &m_subdivisions); + g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler_id)); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Horizontal")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 1, 2, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + m_subdivisions.m_horizontal = entry; + m_horizontalSubdivisionsEntry.connect(entry); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Vertical")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 2, 3, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 1, 2, 2, 3, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + m_subdivisions.m_vertical = entry; + m_verticalSubdivisionsEntry.connect(entry); + } + } + } + } + } + { + GtkFrame* frame = GTK_FRAME(gtk_frame_new("Texturing")); + gtk_widget_show(GTK_WIDGET(frame)); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(frame), TRUE, TRUE, 0); + { + GtkVBox* vbox2 = GTK_VBOX(gtk_vbox_new(FALSE, 5)); + gtk_widget_show(GTK_WIDGET(vbox2)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox2)); + gtk_container_set_border_width(GTK_CONTAINER(vbox2), 5); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Name:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(label), TRUE, TRUE, 0); + gtk_label_set_justify(label, GTK_JUSTIFY_LEFT); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + // gtk_entry_set_editable (GTK_ENTRY (entry), false); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(entry), TRUE, TRUE, 0); + AddDialogData(*entry, m_strName); + + g_signal_connect(G_OBJECT(entry), "key_press_event", G_CALLBACK(OnDialogKey), 0); + } + { + GtkTable* table = GTK_TABLE(gtk_table_new(5, 3, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings(table, 5); + gtk_table_set_col_spacings(table, 5); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Horizontal Shift Step")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 0, 1, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Vertical Shift Step")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 1, 2, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Horizontal Stretch Step")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 2, 3, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Vertical Stretch Step")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 3, 4, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Rotate Step")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 2, 3, 4, 5, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 0, 1, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + g_object_set_data(G_OBJECT(window), "hshift_entry", entry); + // we fill in this data, if no patch is selected the widgets are unmodified when the inspector is raised + // so we need to have at least one initialisation somewhere + entry_set_float(entry, g_pi_globals.shift[0]); + + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 1, 1, 0)); + g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); + g_object_set_data(G_OBJECT(window), "hshift_adj", adj); + + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 0, 1, + (GtkAttachOptions)(0), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); + GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 1, 2, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + entry_set_float(entry, g_pi_globals.shift[1]); + + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 1, 1, 0)); + g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); + g_object_set_data(G_OBJECT(window), "vshift_adj", adj); + + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 1, 2, + (GtkAttachOptions)(0), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); + GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 2, 3, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + entry_set_float(entry, g_pi_globals.scale[0]); + + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -1000, 1000, 1, 1, 0)); + g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); + g_object_set_data(G_OBJECT(window), "hscale_adj", adj); + + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 2, 3, + (GtkAttachOptions)(0), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); + GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 3, 4, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + entry_set_float(entry, g_pi_globals.scale[1]); + + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -1000, 1000, 1, 1, 0)); + g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); + g_object_set_data(G_OBJECT(window), "vscale_adj", adj); + + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 3, 4, + (GtkAttachOptions)(0), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); + GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(table, GTK_WIDGET(entry), 0, 1, 4, 5, + (GtkAttachOptions)(GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + entry_set_float(entry, g_pi_globals.rotate); + + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -1000, 1000, 1, 1, 0)); // NOTE: Arnout - this really should be 360 but can't change it anymore as it could break existing maps + g_signal_connect(G_OBJECT(adj), "value_changed", G_CALLBACK(OnSpinChanged), entry); + g_object_set_data(G_OBJECT(window), "rotate_adj", adj); + + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 4, 5, + (GtkAttachOptions)(0), + (GtkAttachOptions)(0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 10, -2); + GTK_WIDGET_UNSET_FLAGS(spin, GTK_CAN_FOCUS); + } + } + GtkHBox* hbox2 = GTK_HBOX(gtk_hbox_new(TRUE, 5)); + gtk_widget_show(GTK_WIDGET(hbox2)); + gtk_box_pack_start(GTK_BOX(vbox2), GTK_WIDGET(hbox2), TRUE, FALSE, 0); + { + GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("CAP")); + gtk_widget_show(GTK_WIDGET(button)); + gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchdetails), 0); + gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); + } + { + GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Set...")); + gtk_widget_show(GTK_WIDGET(button)); + gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchreset), 0); + gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); + } + { + GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Natural")); + gtk_widget_show(GTK_WIDGET(button)); + gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchnatural), 0); + gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); + } + { + GtkButton* button = GTK_BUTTON(gtk_button_new_with_label("Fit")); + gtk_widget_show(GTK_WIDGET(button)); + gtk_box_pack_end(GTK_BOX(hbox2), GTK_WIDGET(button), TRUE, FALSE, 0); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnPatchfit), 0); + gtk_widget_set_usize(GTK_WIDGET(button), 60, -1); + } + } + } + } + } + + return window; +} + +// sync the dialog our internal data structures +void PatchInspector::exportData() +{ + m_bListenChanged = false; + Dialog::exportData(); + m_bListenChanged = true; +} +void PatchInspector::importData() +{ + m_bListenChanged = false; + Dialog::importData(); + m_bListenChanged = true; +} + +// read the map and feed in the stuff to the dialog box +void PatchInspector::GetPatchInfo() +{ + if(g_pGameDescription->mGameType == "doom3") + { + m_subdivisions.update(); + } + + if(GlobalSelectionSystem().countSelected() == 0) + { + m_Patch = 0; + } + else + { + m_Patch = Node_getPatch(GlobalSelectionSystem().ultimateSelected().path().top()); + } + + if (m_Patch != 0) + { + m_strName = m_Patch->GetShader(); + + // fill in the numbers for Row / Col selection + m_bListenChanged = false; + + { + gtk_combo_box_set_active(m_pRowCombo, 0); + + for (std::size_t i = 0; i < m_countRows; ++i) + { + gtk_combo_box_remove_text(m_pRowCombo, gint(m_countRows - i - 1)); + } + + m_countRows = m_Patch->getHeight(); + for (std::size_t i = 0; i < m_countRows; ++i) + { + char buffer[16]; + sprintf(buffer, "%u", Unsigned(i)); + gtk_combo_box_append_text(m_pRowCombo, buffer); + } + + gtk_combo_box_set_active(m_pRowCombo, 0); + } + + { + gtk_combo_box_set_active(m_pColCombo, 0); + + for (std::size_t i = 0; i < m_countCols; ++i) + { + gtk_combo_box_remove_text(m_pColCombo, gint(m_countCols - i - 1)); + } + + m_countCols = m_Patch->getWidth(); + for (std::size_t i = 0; i < m_countCols; ++i) + { + char buffer[16]; + sprintf(buffer, "%u", Unsigned(i)); + gtk_combo_box_append_text(m_pColCombo, buffer); + } + + gtk_combo_box_set_active(m_pColCombo, 0); + } + + m_bListenChanged = true; + + } + else + { + //globalOutputStream() << "WARNING: no patch\n"; + } + // fill in our internal structs + m_nRow = 0; m_nCol = 0; + UpdateRowColInfo(); + // now update the dialog box + importData(); +} + +// read the current patch on map and initialize m_fX m_fY accordingly +// NOTE: don't call UpdateData in there, it's not meant for +void PatchInspector::UpdateRowColInfo() +{ + m_fX = m_fY = m_fZ = m_fS = m_fT = 0.0; + + if (m_Patch != 0) + { + // we rely on whatever active row/column has been set before we get called + std::size_t r = m_nRow; + std::size_t c = m_nCol; + if(r < m_Patch->getHeight() + && c < m_Patch->getWidth()) + { + const PatchControl& p = m_Patch->ctrlAt(r,c); + m_fX = p.m_vertex[0]; + m_fY = p.m_vertex[1]; + m_fZ = p.m_vertex[2]; + m_fS = p.m_texcoord[0]; + m_fT = p.m_texcoord[1]; + } + } +} + + +void PatchInspector_SelectionChanged(const Selectable& selectable) +{ + PatchInspector_queueDraw(); +} + + +#include "preferencesystem.h" + + +void PatchInspector_Construct() +{ + GlobalCommands_insert("PatchInspector", FreeCaller(), Accelerator('S', (GdkModifierType)GDK_SHIFT_MASK)); + + GlobalPreferenceSystem().registerPreference("PatchWnd", WindowPositionTrackerImportStringCaller(g_PatchInspector.m_position_tracker), WindowPositionTrackerExportStringCaller(g_PatchInspector.m_position_tracker)); + GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Scale1", FloatImportStringCaller(g_pi_globals.scale[0]), FloatExportStringCaller(g_pi_globals.scale[0])); + GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Scale2", FloatImportStringCaller(g_pi_globals.scale[1]), FloatExportStringCaller(g_pi_globals.scale[1])); + GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Shift1", FloatImportStringCaller(g_pi_globals.shift[0]), FloatExportStringCaller(g_pi_globals.shift[0])); + GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Shift2", FloatImportStringCaller(g_pi_globals.shift[1]), FloatExportStringCaller(g_pi_globals.shift[1])); + GlobalPreferenceSystem().registerPreference("SI_PatchTexdef_Rotate", FloatImportStringCaller(g_pi_globals.rotate), FloatExportStringCaller(g_pi_globals.rotate)); + + typedef FreeCaller1 PatchInspectorSelectionChangedCaller; + GlobalSelectionSystem().addSelectionChangeCallback(PatchInspectorSelectionChangedCaller()); + typedef FreeCaller PatchInspectorQueueDrawCaller; + Patch_addTextureChangedCallback(PatchInspectorQueueDrawCaller()); +} +void PatchInspector_Destroy() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/patchdialog.h b/misc/mediasource/netradiant-src/radiant/patchdialog.h new file mode 100644 index 00000000..61bcb07b --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patchdialog.h @@ -0,0 +1,43 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_PATCHDIALOG_H) +#define INCLUDED_PATCHDIALOG_H + +void PatchInspector_Construct(); +void PatchInspector_Destroy(); + +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; +void PatchInspector_constructWindow(GtkWindow* main_window); +void PatchInspector_destroyWindow(); + +namespace scene +{ + class Graph; +} + +void Scene_PatchTranslateTexture_Selected(scene::Graph& graph, float s, float t); +void Scene_PatchRotateTexture_Selected(scene::Graph& graph, float angle); +void Scene_PatchScaleTexture_Selected(scene::Graph& graph, float s, float t); + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/patchmanip.cpp b/misc/mediasource/netradiant-src/radiant/patchmanip.cpp new file mode 100644 index 00000000..b8bccee6 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patchmanip.cpp @@ -0,0 +1,1149 @@ +/* +Copyright (C) 1999-2006 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 "patchmanip.h" + +#include "debugging/debugging.h" + + +#include "iselection.h" +#include "ipatch.h" + +#include "math/vector.h" +#include "math/aabb.h" +#include "generic/callback.h" + +#include "gtkutil/menu.h" +#include "gtkutil/image.h" +#include "map.h" +#include "mainframe.h" +#include "commands.h" +#include "gtkmisc.h" +#include "gtkdlgs.h" +#include "texwindow.h" +#include "xywindow.h" +#include "select.h" +#include "patch.h" +#include "grid.h" + +PatchCreator* g_patchCreator = 0; + +void Scene_PatchConstructPrefab(scene::Graph& graph, const AABB aabb, const char* shader, EPatchPrefab eType, int axis, std::size_t width = 3, std::size_t height = 3) +{ + Select_Delete(); + GlobalSelectionSystem().setSelectedAll(false); + + NodeSmartReference node(g_patchCreator->createPatch()); + Node_getTraversable(Map_FindOrInsertWorldspawn(g_map))->insert(node); + + Patch* patch = Node_getPatch(node); + patch->SetShader(shader); + + patch->ConstructPrefab(aabb, eType, axis, width, height); + patch->controlPointsChanged(); + + { + scene::Path patchpath(makeReference(GlobalSceneGraph().root())); + patchpath.push(makeReference(*Map_GetWorldspawn(g_map))); + patchpath.push(makeReference(node.get())); + Instance_getSelectable(*graph.find(patchpath))->setSelected(true); + } +} + + +void Patch_makeCaps(Patch& patch, scene::Instance& instance, EPatchCap type, const char* shader) +{ + if((type == eCapEndCap || type == eCapIEndCap) + && patch.getWidth() != 5) + { + globalErrorStream() << "cannot create end-cap - patch width != 5\n"; + return; + } + if((type == eCapBevel || type == eCapIBevel) + && patch.getWidth() != 3 && patch.getWidth() != 5) + { + globalErrorStream() << "cannot create bevel-cap - patch width != 3\n"; + return; + } + if(type == eCapCylinder + && patch.getWidth() != 9) + { + globalErrorStream() << "cannot create cylinder-cap - patch width != 9\n"; + return; + } + + { + NodeSmartReference cap(g_patchCreator->createPatch()); + Node_getTraversable(instance.path().parent())->insert(cap); + + patch.MakeCap(Node_getPatch(cap), type, ROW, true); + Node_getPatch(cap)->SetShader(shader); + + scene::Path path(instance.path()); + path.pop(); + path.push(makeReference(cap.get())); + selectPath(path, true); + } + + { + NodeSmartReference cap(g_patchCreator->createPatch()); + Node_getTraversable(instance.path().parent())->insert(cap); + + patch.MakeCap(Node_getPatch(cap), type, ROW, false); + Node_getPatch(cap)->SetShader(shader); + + scene::Path path(instance.path()); + path.pop(); + path.push(makeReference(cap.get())); + selectPath(path, true); + } +} + +typedef std::vector InstanceVector; + +class PatchStoreInstance +{ + InstanceVector& m_instances; +public: + PatchStoreInstance(InstanceVector& instances) : m_instances(instances) + { + } + void operator()(PatchInstance& patch) const + { + m_instances.push_back(&patch); + } +}; + +enum ECapDialog { + PATCHCAP_BEVEL = 0, + PATCHCAP_ENDCAP, + PATCHCAP_INVERTED_BEVEL, + PATCHCAP_INVERTED_ENDCAP, + PATCHCAP_CYLINDER +}; + +EMessageBoxReturn DoCapDlg(ECapDialog *type); + +void Scene_PatchDoCap_Selected(scene::Graph& graph, const char* shader) +{ + ECapDialog nType; + + if(DoCapDlg(&nType) == eIDOK) + { + EPatchCap eType; + switch(nType) + { + case PATCHCAP_INVERTED_BEVEL: + eType = eCapIBevel; + break; + case PATCHCAP_BEVEL: + eType = eCapBevel; + break; + case PATCHCAP_INVERTED_ENDCAP: + eType = eCapIEndCap; + break; + case PATCHCAP_ENDCAP: + eType = eCapEndCap; + break; + case PATCHCAP_CYLINDER: + eType = eCapCylinder; + break; + default: + ERROR_MESSAGE("invalid patch cap type"); + return; + } + + InstanceVector instances; + Scene_forEachVisibleSelectedPatchInstance(PatchStoreInstance(instances)); + for(InstanceVector::const_iterator i = instances.begin(); i != instances.end(); ++i) + { + Patch_makeCaps(* Node_getPatch((*i)->path().top()), *(*i), eType, shader); + } + } +} + +Patch* Scene_GetUltimateSelectedVisiblePatch() +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + scene::Node& node = GlobalSelectionSystem().ultimateSelected().path().top(); + if(node.visible()) + { + return Node_getPatch(node); + } + } + return 0; +} + + +class PatchCapTexture +{ +public: + void operator()(Patch& patch) const + { + patch.ProjectTexture(Patch::m_CycleCapIndex); + } +}; + +void Scene_PatchCapTexture_Selected(scene::Graph& graph) +{ + Scene_forEachVisibleSelectedPatch(PatchCapTexture()); + Patch::m_CycleCapIndex = (Patch::m_CycleCapIndex == 0) ? 1 : (Patch::m_CycleCapIndex == 1) ? 2 : 0; + SceneChangeNotify(); +} + +class PatchFlipTexture +{ + int m_axis; +public: + PatchFlipTexture(int axis) : m_axis(axis) + { + } + void operator()(Patch& patch) const + { + patch.FlipTexture(m_axis); + } +}; + +void Scene_PatchFlipTexture_Selected(scene::Graph& graph, int axis) +{ + Scene_forEachVisibleSelectedPatch(PatchFlipTexture(axis)); +} + +class PatchNaturalTexture +{ +public: + void operator()(Patch& patch) const + { + patch.NaturalTexture(); + } +}; + +void Scene_PatchNaturalTexture_Selected(scene::Graph& graph) +{ + Scene_forEachVisibleSelectedPatch(PatchNaturalTexture()); + SceneChangeNotify(); +} + + +class PatchInsertRemove +{ + bool m_insert, m_column, m_first; +public: + PatchInsertRemove(bool insert, bool column, bool first) : m_insert(insert), m_column(column), m_first(first) + { + } + void operator()(Patch& patch) const + { + patch.InsertRemove(m_insert, m_column, m_first); + } +}; + +void Scene_PatchInsertRemove_Selected(scene::Graph& graph, bool bInsert, bool bColumn, bool bFirst) +{ + Scene_forEachVisibleSelectedPatch(PatchInsertRemove(bInsert, bColumn, bFirst)); +} + +class PatchInvertMatrix +{ +public: + void operator()(Patch& patch) const + { + patch.InvertMatrix(); + } +}; + +void Scene_PatchInvert_Selected(scene::Graph& graph) +{ + Scene_forEachVisibleSelectedPatch(PatchInvertMatrix()); +} + +class PatchRedisperse +{ + EMatrixMajor m_major; +public: + PatchRedisperse(EMatrixMajor major) : m_major(major) + { + } + void operator()(Patch& patch) const + { + patch.Redisperse(m_major); + } +}; + +void Scene_PatchRedisperse_Selected(scene::Graph& graph, EMatrixMajor major) +{ + Scene_forEachVisibleSelectedPatch(PatchRedisperse(major)); +} + +class PatchSmooth +{ + EMatrixMajor m_major; +public: + PatchSmooth(EMatrixMajor major) : m_major(major) + { + } + void operator()(Patch& patch) const + { + patch.Smooth(m_major); + } +}; + +void Scene_PatchSmooth_Selected(scene::Graph& graph, EMatrixMajor major) +{ + Scene_forEachVisibleSelectedPatch(PatchSmooth(major)); +} + +class PatchTransposeMatrix +{ +public: + void operator()(Patch& patch) const + { + patch.TransposeMatrix(); + } +}; + +void Scene_PatchTranspose_Selected(scene::Graph& graph) +{ + Scene_forEachVisibleSelectedPatch(PatchTransposeMatrix()); +} + +class PatchSetShader +{ + const char* m_name; +public: + PatchSetShader(const char* name) + : m_name(name) + { + } + void operator()(Patch& patch) const + { + patch.SetShader(m_name); + } +}; + +void Scene_PatchSetShader_Selected(scene::Graph& graph, const char* name) +{ + Scene_forEachVisibleSelectedPatch(PatchSetShader(name)); + SceneChangeNotify(); +} + +void Scene_PatchGetShader_Selected(scene::Graph& graph, CopiedString& name) +{ + Patch* patch = Scene_GetUltimateSelectedVisiblePatch(); + if(patch != 0) + { + name = patch->GetShader(); + } +} + +class PatchSelectByShader +{ + const char* m_name; +public: + inline PatchSelectByShader(const char* name) + : m_name(name) + { + } + void operator()(PatchInstance& patch) const + { + if(shader_equal(patch.getPatch().GetShader(), m_name)) + { + patch.setSelected(true); + } + } +}; + +void Scene_PatchSelectByShader(scene::Graph& graph, const char* name) +{ + Scene_forEachVisiblePatchInstance(PatchSelectByShader(name)); +} + + +class PatchFindReplaceShader +{ + const char* m_find; + const char* m_replace; +public: + PatchFindReplaceShader(const char* find, const char* replace) : m_find(find), m_replace(replace) + { + } + void operator()(Patch& patch) const + { + if(shader_equal(patch.GetShader(), m_find)) + { + patch.SetShader(m_replace); + } + } +}; + +void Scene_PatchFindReplaceShader(scene::Graph& graph, const char* find, const char* replace) +{ + Scene_forEachVisiblePatch(PatchFindReplaceShader(find, replace)); +} + +void Scene_PatchFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace) +{ + Scene_forEachVisibleSelectedPatch(PatchFindReplaceShader(find, replace)); +} + + +AABB PatchCreator_getBounds() +{ + AABB aabb(aabb_for_minmax(Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max)); + + float gridSize = GetGridSize(); + + if(aabb.extents[0] == 0) + { + aabb.extents[0] = gridSize; + } + if(aabb.extents[1] == 0) + { + aabb.extents[1] = gridSize; + } + if(aabb.extents[2] == 0) + { + aabb.extents[2] = gridSize; + } + + if(aabb_valid(aabb)) + { + return aabb; + } + return AABB(Vector3(0, 0, 0), Vector3(64, 64, 64)); +} + +void Patch_Cylinder() +{ + UndoableCommand undo("patchCreateCylinder"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eCylinder, GlobalXYWnd_getCurrentViewType()); +} + +void Patch_DenseCylinder() +{ + UndoableCommand undo("patchCreateDenseCylinder"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eDenseCylinder, GlobalXYWnd_getCurrentViewType()); +} + +void Patch_VeryDenseCylinder() +{ + UndoableCommand undo("patchCreateVeryDenseCylinder"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eVeryDenseCylinder, GlobalXYWnd_getCurrentViewType()); +} + +void Patch_SquareCylinder() +{ + UndoableCommand undo("patchCreateSquareCylinder"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eSqCylinder, GlobalXYWnd_getCurrentViewType()); +} + +void Patch_Endcap() +{ + UndoableCommand undo("patchCreateCaps"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eEndCap, GlobalXYWnd_getCurrentViewType()); +} + +void Patch_Bevel() +{ + UndoableCommand undo("patchCreateBevel"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eBevel, GlobalXYWnd_getCurrentViewType()); +} + +void Patch_Sphere() +{ + UndoableCommand undo("patchCreateSphere"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eSphere, GlobalXYWnd_getCurrentViewType()); +} + +void Patch_SquareBevel() +{ +} + +void Patch_SquareEndcap() +{ +} + +void Patch_Cone() +{ + UndoableCommand undo("patchCreateCone"); + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), eCone, GlobalXYWnd_getCurrentViewType()); +} + +void DoNewPatchDlg(); + +void Patch_Plane() +{ + UndoableCommand undo("patchCreatePlane"); + + DoNewPatchDlg(); +} + +void Patch_InsertInsertColumn() +{ + UndoableCommand undo("patchInsertColumns"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, true, false); +} + +void Patch_InsertAddColumn() +{ + UndoableCommand undo("patchAddColumns"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, true, true); +} + +void Patch_InsertInsertRow() +{ + UndoableCommand undo("patchInsertRows"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, false, false); +} + +void Patch_InsertAddRow() +{ + UndoableCommand undo("patchAddRows"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), true, false, true); +} + +void Patch_DeleteFirstColumn() +{ + UndoableCommand undo("patchDeleteFirstColumns"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, true, true); +} + +void Patch_DeleteLastColumn() +{ + UndoableCommand undo("patchDeleteLastColumns"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, true, false); +} + +void Patch_DeleteFirstRow() +{ + UndoableCommand undo("patchDeleteFirstRows"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, false, true); +} + +void Patch_DeleteLastRow() +{ + UndoableCommand undo("patchDeleteLastRows"); + + Scene_PatchInsertRemove_Selected(GlobalSceneGraph(), false, false, false); +} + +void Patch_Invert() +{ + UndoableCommand undo("patchInvert"); + + Scene_PatchInvert_Selected(GlobalSceneGraph()); +} + +void Patch_RedisperseRows() +{ + UndoableCommand undo("patchRedisperseRows"); + + Scene_PatchRedisperse_Selected(GlobalSceneGraph(), ROW); +} + +void Patch_RedisperseCols() +{ + UndoableCommand undo("patchRedisperseColumns"); + + Scene_PatchRedisperse_Selected(GlobalSceneGraph(), COL); +} + +void Patch_SmoothRows() +{ + UndoableCommand undo("patchSmoothRows"); + + Scene_PatchSmooth_Selected(GlobalSceneGraph(), ROW); +} + +void Patch_SmoothCols() +{ + UndoableCommand undo("patchSmoothColumns"); + + Scene_PatchSmooth_Selected(GlobalSceneGraph(), COL); +} + +void Patch_Transpose() +{ + UndoableCommand undo("patchTranspose"); + + Scene_PatchTranspose_Selected(GlobalSceneGraph()); +} + +void Patch_Cap() +{ + // FIXME: add support for patch cap creation + // Patch_CapCurrent(); + UndoableCommand undo("patchCreateCaps"); + + Scene_PatchDoCap_Selected(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); +} + +void Patch_CycleProjection() +{ + UndoableCommand undo("patchCycleUVProjectionAxis"); + + Scene_PatchCapTexture_Selected(GlobalSceneGraph()); +} + +///\todo Unfinished. +void Patch_OverlayOn() +{ +} + +///\todo Unfinished. +void Patch_OverlayOff() +{ +} + +void Patch_FlipTextureX() +{ + UndoableCommand undo("patchFlipTextureU"); + + Scene_PatchFlipTexture_Selected(GlobalSceneGraph(), 0); +} + +void Patch_FlipTextureY() +{ + UndoableCommand undo("patchFlipTextureV"); + + Scene_PatchFlipTexture_Selected(GlobalSceneGraph(), 1); +} + +void Patch_NaturalTexture() +{ + UndoableCommand undo("patchNaturalTexture"); + + Scene_PatchNaturalTexture_Selected(GlobalSceneGraph()); +} + + + + +#include "ifilter.h" + + +class filter_patch_all : public PatchFilter +{ +public: + bool filter(const Patch& patch) const + { + return true; + } +}; + +class filter_patch_shader : public PatchFilter +{ + const char* m_shader; +public: + filter_patch_shader(const char* shader) : m_shader(shader) + { + } + bool filter(const Patch& patch) const + { + return shader_equal(patch.GetShader(), m_shader); + } +}; + +class filter_patch_flags : public PatchFilter +{ + int m_flags; +public: + filter_patch_flags(int flags) : m_flags(flags) + { + } + bool filter(const Patch& patch) const + { + return (patch.getShaderFlags() & m_flags) != 0; + } +}; + + +filter_patch_all g_filter_patch_all; +filter_patch_shader g_filter_patch_clip("textures/common/clip"); +filter_patch_shader g_filter_patch_weapclip("textures/common/weapclip"); +filter_patch_flags g_filter_patch_translucent(QER_TRANS); + +void PatchFilters_construct() +{ + add_patch_filter(g_filter_patch_all, EXCLUDE_CURVES); + add_patch_filter(g_filter_patch_clip, EXCLUDE_CLIP); + add_patch_filter(g_filter_patch_weapclip, EXCLUDE_CLIP); + add_patch_filter(g_filter_patch_translucent, EXCLUDE_TRANSLUCENT); +} + + +#include "preferences.h" + +void Patch_constructPreferences(PreferencesPage& page) +{ + page.appendEntry("Patch Subdivide Threshold", g_PatchSubdivideThreshold); +} +void Patch_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Patches", "Patch Display Preferences")); + Patch_constructPreferences(page); +} +void Patch_registerPreferencesPage() +{ + PreferencesDialog_addDisplayPage(FreeCaller1()); +} + + +#include "preferencesystem.h" + +void PatchPreferences_construct() +{ + GlobalPreferenceSystem().registerPreference("Subdivisions", IntImportStringCaller(g_PatchSubdivideThreshold), IntExportStringCaller(g_PatchSubdivideThreshold)); +} + + +#include "generic/callback.h" + +void Patch_registerCommands() +{ + GlobalCommands_insert("InvertCurveTextureX", FreeCaller(), Accelerator('I', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("InvertCurveTextureY", FreeCaller(), Accelerator('I', (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("IncPatchColumn", FreeCaller(), Accelerator(GDK_KP_Add, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("IncPatchRow", FreeCaller(), Accelerator(GDK_KP_Add, (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("DecPatchColumn", FreeCaller(), Accelerator(GDK_KP_Subtract, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("DecPatchRow", FreeCaller(), Accelerator(GDK_KP_Subtract, (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("NaturalizePatch", FreeCaller(), Accelerator('N', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("PatchCylinder", FreeCaller()); + GlobalCommands_insert("PatchDenseCylinder", FreeCaller()); + GlobalCommands_insert("PatchVeryDenseCylinder", FreeCaller()); + GlobalCommands_insert("PatchSquareCylinder", FreeCaller()); + GlobalCommands_insert("PatchEndCap", FreeCaller()); + GlobalCommands_insert("PatchBevel", FreeCaller()); + GlobalCommands_insert("PatchSquareBevel", FreeCaller()); + GlobalCommands_insert("PatchSquareEndcap", FreeCaller()); + GlobalCommands_insert("PatchCone", FreeCaller()); + GlobalCommands_insert("PatchSphere", FreeCaller()); + GlobalCommands_insert("SimplePatchMesh", FreeCaller(), Accelerator('P', (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("PatchInsertInsertColumn", FreeCaller()); + GlobalCommands_insert("PatchInsertAddColumn", FreeCaller()); + GlobalCommands_insert("PatchInsertInsertRow", FreeCaller()); + GlobalCommands_insert("PatchInsertAddRow", FreeCaller()); + GlobalCommands_insert("PatchDeleteFirstColumn", FreeCaller()); + GlobalCommands_insert("PatchDeleteLastColumn", FreeCaller()); + GlobalCommands_insert("PatchDeleteFirstRow", FreeCaller()); + GlobalCommands_insert("PatchDeleteLastRow", FreeCaller()); + GlobalCommands_insert("InvertCurve", FreeCaller(), Accelerator('I', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("RedisperseRows", FreeCaller(), Accelerator('E', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("RedisperseCols", FreeCaller(), Accelerator('E', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("SmoothRows", FreeCaller(), Accelerator('W', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("SmoothCols", FreeCaller(), Accelerator('W', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("MatrixTranspose", FreeCaller(), Accelerator('M', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("CapCurrentCurve", FreeCaller(), Accelerator('C', (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("CycleCapTexturePatch", FreeCaller(), Accelerator('N', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("MakeOverlayPatch", FreeCaller(), Accelerator('Y')); + GlobalCommands_insert("ClearPatchOverlays", FreeCaller(), Accelerator('L', (GdkModifierType)GDK_CONTROL_MASK)); +} + +void Patch_constructToolbar(GtkToolbar* toolbar) +{ + toolbar_append_button(toolbar, "Put caps on the current patch (SHIFT + C)", "curve_cap.bmp", "CapCurrentCurve"); +} + +void Patch_constructMenu(GtkMenu* menu) +{ + create_menu_item_with_mnemonic(menu, "Cylinder", "PatchCylinder"); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "More Cylinders"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Dense Cylinder", "PatchDenseCylinder"); + create_menu_item_with_mnemonic(menu_in_menu, "Very Dense Cylinder", "PatchVeryDenseCylinder"); + create_menu_item_with_mnemonic(menu_in_menu, "Square Cylinder", "PatchSquareCylinder"); + } + menu_separator (menu); + create_menu_item_with_mnemonic(menu, "End cap", "PatchEndCap"); + create_menu_item_with_mnemonic(menu, "Bevel", "PatchBevel"); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "More End caps, Bevels"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Square Endcap", "PatchSquareBevel"); + create_menu_item_with_mnemonic(menu_in_menu, "Square Bevel", "PatchSquareEndcap"); + } + menu_separator (menu); + create_menu_item_with_mnemonic(menu, "Cone", "PatchCone"); + create_menu_item_with_mnemonic(menu, "Sphere", "PatchSphere"); + menu_separator (menu); + create_menu_item_with_mnemonic(menu, "Simple Patch Mesh...", "SimplePatchMesh"); + menu_separator (menu); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Insert"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Insert (2) Columns", "PatchInsertInsertColumn"); + create_menu_item_with_mnemonic(menu_in_menu, "Add (2) Columns", "PatchInsertAddColumn"); + menu_separator (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Insert (2) Rows", "PatchInsertInsertRow"); + create_menu_item_with_mnemonic(menu_in_menu, "Add (2) Rows", "PatchInsertAddRow"); + } + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Delete"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "First (2) Columns", "PatchDeleteFirstColumn"); + create_menu_item_with_mnemonic(menu_in_menu, "Last (2) Columns", "PatchDeleteLastColumn"); + menu_separator (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "First (2) Rows", "PatchDeleteFirstRow"); + create_menu_item_with_mnemonic(menu_in_menu, "Last (2) Rows", "PatchDeleteLastRow"); + } + menu_separator (menu); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Matrix"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Invert", "InvertCurve"); + GtkMenu* menu_3 = create_sub_menu_with_mnemonic (menu_in_menu, "Re-disperse"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_3); + create_menu_item_with_mnemonic(menu_3, "Rows", "RedisperseRows"); + create_menu_item_with_mnemonic(menu_3, "Columns", "RedisperseCols"); + GtkMenu* menu_4 = create_sub_menu_with_mnemonic (menu_in_menu, "Smooth"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_4); + create_menu_item_with_mnemonic(menu_4, "Rows", "SmoothRows"); + create_menu_item_with_mnemonic(menu_4, "Columns", "SmoothCols"); + create_menu_item_with_mnemonic(menu_in_menu, "Transpose", "MatrixTranspose"); + } + menu_separator (menu); + create_menu_item_with_mnemonic(menu, "Cap Selection", "CapCurrentCurve"); + create_menu_item_with_mnemonic(menu, "Cycle Cap Texture", "CycleCapTexturePatch"); + menu_separator (menu); + { + GtkMenu* menu_in_menu = create_sub_menu_with_mnemonic (menu, "Overlay"); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu_in_menu); + create_menu_item_with_mnemonic(menu_in_menu, "Set", "MakeOverlayPatch"); + create_menu_item_with_mnemonic(menu_in_menu, "Clear", "ClearPatchOverlays"); + } +} + + +#include +#include +#include +#include +#include +#include +#include "gtkutil/dialog.h" +#include "gtkutil/widget.h" + +void DoNewPatchDlg() +{ + ModalDialog dialog; + GtkComboBox* width; + GtkComboBox* height; + + GtkWindow* window = create_dialog_window(MainFrame_getWindow(), "Patch density", G_CALLBACK(dialog_delete_callback), &dialog); + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + { + GtkTable* table = create_dialog_table(2, 2, 4, 4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Width:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + { + GtkLabel* label = GTK_LABEL(gtk_label_new("Height:")); + gtk_widget_show(GTK_WIDGET(label)); + gtk_table_attach(table, GTK_WIDGET(label), 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_misc_set_alignment(GTK_MISC(label), 0, 0.5); + } + + { + GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); + gtk_combo_box_append_text(combo, "3"); + gtk_combo_box_append_text(combo, "5"); + gtk_combo_box_append_text(combo, "7"); + gtk_combo_box_append_text(combo, "9"); + gtk_combo_box_append_text(combo, "11"); + gtk_combo_box_append_text(combo, "13"); + gtk_combo_box_append_text(combo, "15"); + gtk_combo_box_append_text(combo, "17"); + gtk_combo_box_append_text(combo, "19"); + gtk_combo_box_append_text(combo, "21"); + gtk_combo_box_append_text(combo, "23"); + gtk_combo_box_append_text(combo, "25"); + gtk_combo_box_append_text(combo, "27"); + gtk_combo_box_append_text(combo, "29"); + gtk_combo_box_append_text(combo, "31"); // MAX_PATCH_SIZE is 32, so we should be able to do 31... + gtk_widget_show(GTK_WIDGET(combo)); + gtk_table_attach(table, GTK_WIDGET(combo), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + width = combo; + } + { + GtkComboBox* combo = GTK_COMBO_BOX(gtk_combo_box_new_text()); + gtk_combo_box_append_text(combo, "3"); + gtk_combo_box_append_text(combo, "5"); + gtk_combo_box_append_text(combo, "7"); + gtk_combo_box_append_text(combo, "9"); + gtk_combo_box_append_text(combo, "11"); + gtk_combo_box_append_text(combo, "13"); + gtk_combo_box_append_text(combo, "15"); + gtk_combo_box_append_text(combo, "17"); + gtk_combo_box_append_text(combo, "19"); + gtk_combo_box_append_text(combo, "21"); + gtk_combo_box_append_text(combo, "23"); + gtk_combo_box_append_text(combo, "25"); + gtk_combo_box_append_text(combo, "27"); + gtk_combo_box_append_text(combo, "29"); + gtk_combo_box_append_text(combo, "31"); // MAX_PATCH_SIZE is 32, so we should be able to do 31... + gtk_widget_show(GTK_WIDGET(combo)); + gtk_table_attach(table, GTK_WIDGET(combo), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + height = combo; + } + } + + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_grab_focus(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); + } + } + } + + // Initialize dialog + gtk_combo_box_set_active(width, 0); + gtk_combo_box_set_active(height, 0); + + if(modal_dialog_show(window, dialog) == eIDOK) + { + int w = gtk_combo_box_get_active(width) * 2 + 3; + int h = gtk_combo_box_get_active(height) * 2 + 3; + + Scene_PatchConstructPrefab(GlobalSceneGraph(), PatchCreator_getBounds(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()), ePlane, GlobalXYWnd_getCurrentViewType(), w, h); + } + + gtk_widget_destroy(GTK_WIDGET(window)); +} + + + + +EMessageBoxReturn DoCapDlg(ECapDialog* type) +{ + ModalDialog dialog; + ModalDialogButton ok_button(dialog, eIDOK); + ModalDialogButton cancel_button(dialog, eIDCANCEL); + GtkWidget* bevel; + GtkWidget* ibevel; + GtkWidget* endcap; + GtkWidget* iendcap; + GtkWidget* cylinder; + + GtkWindow* window = create_modal_dialog_window(MainFrame_getWindow(), "Cap", dialog); + + GtkAccelGroup *accel_group = gtk_accel_group_new(); + gtk_window_add_accel_group(window, accel_group); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(hbox)); + + { + // Gef: Added a vbox to contain the toggle buttons + GtkVBox* radio_vbox = create_dialog_vbox(4); + gtk_container_add(GTK_CONTAINER(hbox), GTK_WIDGET(radio_vbox)); + + { + GtkTable* table = GTK_TABLE(gtk_table_new(5, 2, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(radio_vbox), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings(table, 5); + gtk_table_set_col_spacings(table, 5); + + { + GtkImage* image = new_local_image("cap_bevel.bmp"); + gtk_widget_show(GTK_WIDGET(image)); + gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkImage* image = new_local_image("cap_endcap.bmp"); + gtk_widget_show(GTK_WIDGET(image)); + gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkImage* image = new_local_image("cap_ibevel.bmp"); + gtk_widget_show(GTK_WIDGET(image)); + gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkImage* image = new_local_image("cap_iendcap.bmp"); + gtk_widget_show(GTK_WIDGET(image)); + gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 3, 4, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkImage* image = new_local_image("cap_cylinder.bmp"); + gtk_widget_show(GTK_WIDGET(image)); + gtk_table_attach(table, GTK_WIDGET(image), 0, 1, 4, 5, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + + GSList* group = 0; + { + GtkWidget* button = gtk_radio_button_new_with_label (group, "Bevel"); + gtk_widget_show (button); + gtk_table_attach(table, button, 1, 2, 0, 1, + (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), + (GtkAttachOptions) (0), 0, 0); + group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); + + bevel = button; + } + { + GtkWidget* button = gtk_radio_button_new_with_label (group, "Endcap"); + gtk_widget_show (button); + gtk_table_attach(table, button, 1, 2, 1, 2, + (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), + (GtkAttachOptions) (0), 0, 0); + group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); + + endcap = button; + } + { + GtkWidget* button = gtk_radio_button_new_with_label (group, "Inverted Bevel"); + gtk_widget_show (button); + gtk_table_attach(table, button, 1, 2, 2, 3, + (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), + (GtkAttachOptions) (0), 0, 0); + group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); + + ibevel = button; + } + { + GtkWidget* button = gtk_radio_button_new_with_label (group, "Inverted Endcap"); + gtk_widget_show (button); + gtk_table_attach(table, button, 1, 2, 3, 4, + (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), + (GtkAttachOptions) (0), 0, 0); + group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); + + iendcap = button; + } + { + GtkWidget* button = gtk_radio_button_new_with_label (group, "Cylinder"); + gtk_widget_show (button); + gtk_table_attach(table, button, 1, 2, 4, 5, + (GtkAttachOptions) (GTK_FILL | GTK_EXPAND), + (GtkAttachOptions) (0), 0, 0); + group = gtk_radio_button_group (GTK_RADIO_BUTTON (button)); + + cylinder = button; + } + } + } + + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), FALSE, FALSE, 0); + { + GtkButton* button = create_modal_dialog_button("OK", ok_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Return, (GdkModifierType)0, GTK_ACCEL_VISIBLE); + } + { + GtkButton* button = create_modal_dialog_button("Cancel", cancel_button); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel_group, GDK_Escape, (GdkModifierType)0, GTK_ACCEL_VISIBLE); + } + } + } + + // Initialize dialog + gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (bevel), TRUE); + + EMessageBoxReturn ret = modal_dialog_show(window, dialog); + if (ret == eIDOK) + { + if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (bevel))) + *type = PATCHCAP_BEVEL; + else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(endcap))) + *type = PATCHCAP_ENDCAP; + else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(ibevel))) + *type = PATCHCAP_INVERTED_BEVEL; + else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(iendcap))) + *type = PATCHCAP_INVERTED_ENDCAP; + else if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cylinder))) + *type = PATCHCAP_CYLINDER; + } + + gtk_widget_destroy(GTK_WIDGET(window)); + + return ret; +} diff --git a/misc/mediasource/netradiant-src/radiant/patchmanip.h b/misc/mediasource/netradiant-src/radiant/patchmanip.h new file mode 100644 index 00000000..e4d372e1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patchmanip.h @@ -0,0 +1,57 @@ +/* +Copyright (C) 1999-2006 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 (INCLUDED_PATCHMANIP_H) +#define INCLUDED_PATCHMANIP_H + +#include "string/stringfwd.h" + +void Patch_registerCommands(); +typedef struct _GtkToolbar GtkToolbar; +typedef struct _GtkMenu GtkMenu; +void Patch_constructToolbar(GtkToolbar* toolbar); +void Patch_constructMenu(GtkMenu* menu); + +namespace scene +{ + class Graph; +} + +void Scene_PatchSetShader_Selected(scene::Graph& graph, const char* name); +void Scene_PatchGetShader_Selected(scene::Graph& graph, CopiedString& name); +void Scene_PatchSelectByShader(scene::Graph& graph, const char* name); +void Scene_PatchFindReplaceShader(scene::Graph& graph, const char* find, const char* replace); +void Scene_PatchFindReplaceShader_Selected(scene::Graph& graph, const char* find, const char* replace); + +void Scene_PatchCapTexture_Selected(scene::Graph& graph); +void Scene_PatchNaturalTexture_Selected(scene::Graph& graph); +void Scene_PatchTileTexture_Selected(scene::Graph& graph, float s, float t); + +void PatchFilters_construct(); + +void PatchPreferences_construct(); + +void Patch_registerPreferencesPage(); + +class PatchCreator; +extern PatchCreator* g_patchCreator; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/patchmodule.cpp b/misc/mediasource/netradiant-src/radiant/patchmodule.cpp new file mode 100644 index 00000000..d9296243 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patchmodule.cpp @@ -0,0 +1,251 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "patchmodule.h" + +#include "qerplugin.h" +#include "ipatch.h" + +#include "patch.h" +#include "patchmanip.h" + +namespace +{ + std::size_t g_patchModuleCount = 0; +} + +void Patch_Construct(EPatchType type) +{ + if(++g_patchModuleCount != 1) + { + return; + } + + PatchFilters_construct(); + + PatchPreferences_construct(); + + Patch_registerPreferencesPage(); + + Patch::constructStatic(type); + PatchInstance::constructStatic(); + + if(type == ePatchTypeDoom3) + { + MAX_PATCH_WIDTH = MAX_PATCH_HEIGHT = 99; + } + else + { + MAX_PATCH_WIDTH = MAX_PATCH_HEIGHT = 31; // matching q3map2 + } +} + +void Patch_Destroy() +{ + if(--g_patchModuleCount != 0) + { + return; + } + + Patch::destroyStatic(); + PatchInstance::destroyStatic(); +} + +class CommonPatchCreator : public PatchCreator +{ +public: + void Patch_undoSave(scene::Node& patch) const + { + Node_getPatch(patch)->undoSave(); + } + void Patch_resize(scene::Node& patch, std::size_t width, std::size_t height) const + { + Node_getPatch(patch)->setDims(width, height); + } + PatchControlMatrix Patch_getControlPoints(scene::Node& node) const + { + Patch& patch = *Node_getPatch(node); + return PatchControlMatrix(patch.getHeight(), patch.getWidth(), patch.getControlPoints().data()); + } + void Patch_controlPointsChanged(scene::Node& patch) const + { + return Node_getPatch(patch)->controlPointsChanged(); + } + const char* Patch_getShader(scene::Node& patch) const + { + return Node_getPatch(patch)->GetShader(); + } + void Patch_setShader(scene::Node& patch, const char* shader) const + { + Node_getPatch(patch)->SetShader(shader); + } +}; + +class Quake3PatchCreator : public CommonPatchCreator +{ +public: + scene::Node& createPatch() + { + return (new PatchNodeQuake3())->node(); + } +}; + +Quake3PatchCreator g_Quake3PatchCreator; + +PatchCreator& GetQuake3PatchCreator() +{ + return g_Quake3PatchCreator; +} + +class Doom3PatchCreator : public CommonPatchCreator +{ +public: + scene::Node& createPatch() + { + return (new PatchNodeDoom3(true))->node(); + } +}; + +Doom3PatchCreator g_Doom3PatchCreator; + +PatchCreator& GetDoom3PatchCreator() +{ + return g_Doom3PatchCreator; +} + +class Doom3PatchDef2Creator : public CommonPatchCreator +{ +public: + scene::Node& createPatch() + { + return (new PatchNodeDoom3())->node(); + } +}; + +Doom3PatchDef2Creator g_Doom3PatchDef2Creator; + +PatchCreator& GetDoom3PatchDef2Creator() +{ + return g_Doom3PatchDef2Creator; +} + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class PatchDependencies : + public GlobalRadiantModuleRef, + public GlobalSceneGraphModuleRef, + public GlobalShaderCacheModuleRef, + public GlobalSelectionModuleRef, + public GlobalOpenGLModuleRef, + public GlobalUndoModuleRef, + public GlobalFilterModuleRef +{ +}; + +class PatchQuake3API : public TypeSystemRef +{ + PatchCreator* m_patchquake3; +public: + typedef PatchCreator Type; + STRING_CONSTANT(Name, "quake3"); + + PatchQuake3API() + { + Patch_Construct(ePatchTypeQuake3); + + m_patchquake3 = &GetQuake3PatchCreator(); + g_patchCreator = m_patchquake3; + } + ~PatchQuake3API() + { + Patch_Destroy(); + } + PatchCreator* getTable() + { + return m_patchquake3; + } +}; + +typedef SingletonModule PatchQuake3Module; +typedef Static StaticPatchQuake3Module; +StaticRegisterModule staticRegisterPatchQuake3(StaticPatchQuake3Module::instance()); + + + +class PatchDoom3API : public TypeSystemRef +{ + PatchCreator* m_patchdoom3; +public: + typedef PatchCreator Type; + STRING_CONSTANT(Name, "doom3"); + + PatchDoom3API() + { + Patch_Construct(ePatchTypeDoom3); + + m_patchdoom3 = &GetDoom3PatchCreator(); + } + ~PatchDoom3API() + { + Patch_Destroy(); + } + PatchCreator* getTable() + { + return m_patchdoom3; + } +}; + +typedef SingletonModule PatchDoom3Module; +typedef Static StaticPatchDoom3Module; +StaticRegisterModule staticRegisterPatchDoom3(StaticPatchDoom3Module::instance()); + + +class PatchDef2Doom3API : public TypeSystemRef +{ + PatchCreator* m_patchdef2doom3; +public: + typedef PatchCreator Type; + STRING_CONSTANT(Name, "def2doom3"); + + PatchDef2Doom3API() + { + Patch_Construct(ePatchTypeDoom3); + + m_patchdef2doom3 = &GetDoom3PatchDef2Creator(); + g_patchCreator = m_patchdef2doom3; + } + ~PatchDef2Doom3API() + { + Patch_Destroy(); + } + PatchCreator* getTable() + { + return m_patchdef2doom3; + } +}; + +typedef SingletonModule PatchDef2Doom3Module; +typedef Static StaticPatchDef2Doom3Module; +StaticRegisterModule staticRegisterPatchDef2Doom3(StaticPatchDef2Doom3Module::instance()); + + + diff --git a/misc/mediasource/netradiant-src/radiant/patchmodule.h b/misc/mediasource/netradiant-src/radiant/patchmodule.h new file mode 100644 index 00000000..074d5947 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/patchmodule.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_PATCHMODULE_H) +#define INCLUDED_PATCHMODULE_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/plugin.cpp b/misc/mediasource/netradiant-src/radiant/plugin.cpp new file mode 100644 index 00000000..fad47ea2 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/plugin.cpp @@ -0,0 +1,358 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "plugin.h" + +#include "debugging/debugging.h" + +#include "qerplugin.h" +#include "ifilesystem.h" +#include "ishaders.h" +#include "ientity.h" +#include "ieclass.h" +#include "irender.h" +#include "iscenegraph.h" +#include "iselection.h" +#include "ifilter.h" +#include "iscriplib.h" +#include "igl.h" +#include "iundo.h" +#include "itextures.h" +#include "ireference.h" +#include "ifiletypes.h" +#include "preferencesystem.h" +#include "ibrush.h" +#include "ipatch.h" +#include "iimage.h" +#include "itoolbar.h" +#include "iplugin.h" +#include "imap.h" +#include "namespace.h" + +#include "gtkutil/messagebox.h" +#include "gtkutil/filechooser.h" +#include "maplib.h" + +#include "error.h" +#include "map.h" +#include "qe3.h" +#include "entityinspector.h" +#include "entitylist.h" +#include "points.h" +#include "gtkmisc.h" +#include "texwindow.h" +#include "mainframe.h" +#include "build.h" +#include "mru.h" +#include "multimon.h" +#include "surfacedialog.h" +#include "groupdialog.h" +#include "patchdialog.h" +#include "camwindow.h" +#include "watchbsp.h" +#include "xywindow.h" +#include "entity.h" +#include "select.h" +#include "preferences.h" +#include "autosave.h" +#include "plugintoolbar.h" +#include "findtexturedialog.h" +#include "nullmodel.h" +#include "grid.h" + +#include "modulesystem/modulesmap.h" +#include "modulesystem/singletonmodule.h" + +#include "generic/callback.h" + +const char* GameDescription_getKeyValue(const char* key) +{ + return g_pGameDescription->getKeyValue(key); +} + +const char* GameDescription_getRequiredKeyValue(const char* key) +{ + return g_pGameDescription->getRequiredKeyValue(key); +} + +const char* getMapName() +{ + return Map_Name(g_map); +} + +scene::Node& getMapWorldEntity() +{ + return Map_FindOrInsertWorldspawn(g_map); +} + +VIEWTYPE XYWindow_getViewType() +{ + return g_pParentWnd->GetXYWnd()->GetViewType(); +} + +Vector3 XYWindow_windowToWorld(const WindowVector& position) +{ + Vector3 result(0, 0, 0); + g_pParentWnd->GetXYWnd()->XY_ToPoint(static_cast(position.x()), static_cast(position.y()), result); + return result; +} + +const char* TextureBrowser_getSelectedShader() +{ + return TextureBrowser_GetSelectedShader(GlobalTextureBrowser()); +} + +class RadiantCoreAPI +{ + _QERFuncTable_1 m_radiantcore; +public: + typedef _QERFuncTable_1 Type; + STRING_CONSTANT(Name, "*"); + + RadiantCoreAPI() + { + m_radiantcore.getEnginePath = &EnginePath_get; + m_radiantcore.getLocalRcPath = &LocalRcPath_get; + m_radiantcore.getAppPath = &AppPath_get; + m_radiantcore.getGameToolsPath = &GameToolsPath_get; + m_radiantcore.getSettingsPath = &SettingsPath_get; + m_radiantcore.getMapsPath = &getMapsPath; + + m_radiantcore.getGameName = &gamename_get; + m_radiantcore.getGameMode = &gamemode_get; + + m_radiantcore.getMapName = &getMapName; + m_radiantcore.getMapWorldEntity = getMapWorldEntity; + m_radiantcore.getGridSize = GetGridSize; + + m_radiantcore.getGameDescriptionKeyValue = &GameDescription_getKeyValue; + m_radiantcore.getRequiredGameDescriptionKeyValue = &GameDescription_getRequiredKeyValue; + + m_radiantcore.attachGameToolsPathObserver = Radiant_attachGameToolsPathObserver; + m_radiantcore.detachGameToolsPathObserver = Radiant_detachGameToolsPathObserver; + m_radiantcore.attachEnginePathObserver = Radiant_attachEnginePathObserver; + m_radiantcore.detachEnginePathObserver = Radiant_detachEnginePathObserver; + m_radiantcore.attachGameNameObserver = Radiant_attachGameNameObserver; + m_radiantcore.detachGameNameObserver = Radiant_detachGameNameObserver; + m_radiantcore.attachGameModeObserver = Radiant_attachGameModeObserver; + m_radiantcore.detachGameModeObserver = Radiant_detachGameModeObserver; + + m_radiantcore.XYWindowDestroyed_connect = XYWindowDestroyed_connect; + m_radiantcore.XYWindowDestroyed_disconnect = XYWindowDestroyed_disconnect; + m_radiantcore.XYWindowMouseDown_connect = XYWindowMouseDown_connect; + m_radiantcore.XYWindowMouseDown_disconnect = XYWindowMouseDown_disconnect; + m_radiantcore.XYWindow_getViewType = XYWindow_getViewType; + m_radiantcore.XYWindow_windowToWorld = XYWindow_windowToWorld; + m_radiantcore.TextureBrowser_getSelectedShader = TextureBrowser_getSelectedShader; + + m_radiantcore.m_pfnMessageBox = >k_MessageBox; + m_radiantcore.m_pfnFileDialog = &file_dialog; + m_radiantcore.m_pfnColorDialog = &color_dialog; + m_radiantcore.m_pfnDirDialog = &dir_dialog; + m_radiantcore.m_pfnNewImage = &new_plugin_image; + } + _QERFuncTable_1* getTable() + { + return &m_radiantcore; + } +}; + +typedef SingletonModule RadiantCoreModule; +typedef Static StaticRadiantCoreModule; +StaticRegisterModule staticRegisterRadiantCore(StaticRadiantCoreModule::instance()); + + +class RadiantDependencies : + public GlobalRadiantModuleRef, + public GlobalFileSystemModuleRef, + public GlobalEntityModuleRef, + public GlobalShadersModuleRef, + public GlobalBrushModuleRef, + public GlobalSceneGraphModuleRef, + public GlobalShaderCacheModuleRef, + public GlobalFiletypesModuleRef, + public GlobalSelectionModuleRef, + public GlobalReferenceModuleRef, + public GlobalOpenGLModuleRef, + public GlobalEntityClassManagerModuleRef, + public GlobalUndoModuleRef, + public GlobalScripLibModuleRef, + public GlobalNamespaceModuleRef +{ + ImageModulesRef m_image_modules; + MapModulesRef m_map_modules; + ToolbarModulesRef m_toolbar_modules; + PluginModulesRef m_plugin_modules; + +public: + RadiantDependencies() : + GlobalEntityModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entities")), + GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")), + GlobalBrushModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("brushtypes")), + GlobalEntityClassManagerModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("entityclass")), + m_image_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("texturetypes")), + m_map_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("maptypes")), + m_toolbar_modules("*"), + m_plugin_modules("*") + { + } + + ImageModules& getImageModules() + { + return m_image_modules.get(); + } + MapModules& getMapModules() + { + return m_map_modules.get(); + } + ToolbarModules& getToolbarModules() + { + return m_toolbar_modules.get(); + } + PluginModules& getPluginModules() + { + return m_plugin_modules.get(); + } +}; + +class Radiant : public TypeSystemRef +{ +public: + Radiant() + { + Preferences_Init(); + + GlobalFiletypes().addType("sound", "wav", filetype_t("PCM sound files", "*.wav")); + + Selection_construct(); + HomePaths_Construct(); + VFS_Construct(); + Grid_construct(); + MultiMon_Construct(); + MRU_Construct(); + Pointfile_Construct(); + GLWindow_Construct(); + BuildMenu_Construct(); + Map_Construct(); + EntityList_Construct(); + MainFrame_Construct(); + GroupDialog_Construct(); + SurfaceInspector_Construct(); + PatchInspector_Construct(); + CamWnd_Construct(); + XYWindow_Construct(); + BuildMonitor_Construct(); + TextureBrowser_Construct(); + Entity_Construct(); + Autosave_Construct(); + EntityInspector_construct(); + FindTextureDialog_Construct(); + NullModel_construct(); + MapRoot_construct(); + + EnginePath_verify(); + EnginePath_Realise(); + } + ~Radiant() + { + EnginePath_Unrealise(); + + MapRoot_destroy(); + NullModel_destroy(); + FindTextureDialog_Destroy(); + EntityInspector_destroy(); + Autosave_Destroy(); + Entity_Destroy(); + TextureBrowser_Destroy(); + BuildMonitor_Destroy(); + XYWindow_Destroy(); + CamWnd_Destroy(); + PatchInspector_Destroy(); + SurfaceInspector_Destroy(); + GroupDialog_Destroy(); + MainFrame_Destroy(); + EntityList_Destroy(); + Map_Destroy(); + BuildMenu_Destroy(); + GLWindow_Destroy(); + Pointfile_Destroy(); + MRU_Destroy(); + MultiMon_Destroy(); + Grid_destroy(); + VFS_Destroy(); + HomePaths_Destroy(); + Selection_destroy(); + } +}; + +namespace +{ + bool g_RadiantInitialised = false; + RadiantDependencies* g_RadiantDependencies; + Radiant* g_Radiant; +} + + + +bool Radiant_Construct(ModuleServer& server) +{ + GlobalModuleServer::instance().set(server); + StaticModuleRegistryList().instance().registerModules(); + + g_RadiantDependencies = new RadiantDependencies(); + + g_RadiantInitialised = !server.getError(); + + if(g_RadiantInitialised) + { + g_Radiant = new Radiant; + } + + return g_RadiantInitialised; +} +void Radiant_Destroy() +{ + if(g_RadiantInitialised) + { + delete g_Radiant; + } + + delete g_RadiantDependencies; +} + +ImageModules& Radiant_getImageModules() +{ + return g_RadiantDependencies->getImageModules(); +} +MapModules& Radiant_getMapModules() +{ + return g_RadiantDependencies->getMapModules(); +} +ToolbarModules& Radiant_getToolbarModules() +{ + return g_RadiantDependencies->getToolbarModules(); +} +PluginModules& Radiant_getPluginModules() +{ + return g_RadiantDependencies->getPluginModules(); +} + + diff --git a/misc/mediasource/netradiant-src/radiant/plugin.h b/misc/mediasource/netradiant-src/radiant/plugin.h new file mode 100644 index 00000000..e4d2493d --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/plugin.h @@ -0,0 +1,47 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_PLUGIN_H) +#define INCLUDED_PLUGIN_H + +class ModuleServer; +bool Radiant_Construct(ModuleServer& server); +void Radiant_Destroy(); + + +template +class Modules; + +struct _QERPlugImageTable; +typedef Modules<_QERPlugImageTable> ImageModules; +ImageModules& Radiant_getImageModules(); +class MapFormat; +typedef Modules MapModules; +MapModules& Radiant_getMapModules(); +struct _QERPlugToolbarTable; +typedef Modules<_QERPlugToolbarTable> ToolbarModules; +ToolbarModules& Radiant_getToolbarModules(); +struct _QERPluginTable; +typedef Modules<_QERPluginTable> PluginModules; +PluginModules& Radiant_getPluginModules(); + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/pluginapi.cpp b/misc/mediasource/netradiant-src/radiant/pluginapi.cpp new file mode 100644 index 00000000..be91b9a6 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/pluginapi.cpp @@ -0,0 +1,92 @@ +/* +Copyright (C) 1999-2006 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 "pluginapi.h" + +#include "modulesystem.h" +#include "qerplugin.h" + +#include "generic/callback.h" +#include "math/vector.h" + +#include "gtkmisc.h" + +#include "camwindow.h" + +#include "mainframe.h" + + +// camera API +void QERApp_GetCamera( Vector3& origin, Vector3& angles ) +{ + CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); + origin = Camera_getOrigin(camwnd); + angles = Camera_getAngles(camwnd); +} + +void QERApp_SetCamera( const Vector3& origin, const Vector3& angles ) +{ + CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); + Camera_setOrigin(camwnd, origin); + Camera_setAngles(camwnd, angles); +} + +void QERApp_GetCamWindowExtents( int *x, int *y, int *width, int *height ) +{ +#if 0 + CamWnd* camwnd = g_pParentWnd->GetCamWnd(); + + gtk_window_get_position(GTK_WINDOW(camwnd->m_window), x, y); + + *width = camwnd->Camera()->width; + *height = camwnd->Camera()->height; +#endif +} + +#include "icamera.h" + +class CameraAPI +{ + _QERCameraTable m_camera; +public: + typedef _QERCameraTable Type; + STRING_CONSTANT(Name, "*"); + + CameraAPI() + { + m_camera.m_pfnGetCamera = &QERApp_GetCamera; + m_camera.m_pfnSetCamera = &QERApp_SetCamera; + m_camera.m_pfnGetCamWindowExtents = &QERApp_GetCamWindowExtents; + } + _QERCameraTable* getTable() + { + return &m_camera; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule CameraModule; +typedef Static StaticCameraModule; +StaticRegisterModule staticRegisterCamera(StaticCameraModule::instance()); + + diff --git a/misc/mediasource/netradiant-src/radiant/pluginapi.h b/misc/mediasource/netradiant-src/radiant/pluginapi.h new file mode 100644 index 00000000..267b0d7a --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/pluginapi.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_PLUGINAPI_H) +#define INCLUDED_PLUGINAPI_H + +template class BasicVector3; +typedef BasicVector3 Vector3; + +// camera API +void QERApp_GetCamera( Vector3& origin, Vector3& angles ); +void QERApp_SetCamera( const Vector3& origin, const Vector3& angles ); +void QERApp_GetCamWindowExtents( int *x, int *y, int *width, int *height ); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/pluginmanager.cpp b/misc/mediasource/netradiant-src/radiant/pluginmanager.cpp new file mode 100644 index 00000000..35933014 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/pluginmanager.cpp @@ -0,0 +1,253 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// PlugInManager.cpp: implementation of the CPlugInManager class. +// +////////////////////////////////////////////////////////////////////// + +#include "pluginmanager.h" + +#include "modulesystem.h" +#include "qerplugin.h" +#include "iplugin.h" + +#include "math/vector.h" +#include "string/string.h" + +#include "error.h" +#include "select.h" +#include "plugin.h" + +#include "modulesystem.h" + +#include + +/* plugin manager --------------------------------------- */ +class CPluginSlot : public IPlugIn +{ + CopiedString m_menu_name; + const _QERPluginTable *mpTable; + std::list m_CommandStrings; + std::list m_CommandTitleStrings; + std::list m_CommandIDs; + +public: + /*! + build directly from a SYN_PROVIDE interface + */ + CPluginSlot(GtkWidget* main_window, const char* name, const _QERPluginTable& table); + /*! + dispatching a command by name to the plugin + */ + void Dispatch(const char *p); + + // IPlugIn ------------------------------------------------------------ + const char* getMenuName(); + std::size_t getCommandCount(); + const char* getCommand(std::size_t n); + const char* getCommandTitle(std::size_t n); + void addMenuID(std::size_t n); + bool ownsCommandID(std::size_t n); + +}; + +CPluginSlot::CPluginSlot(GtkWidget* main_window, const char* name, const _QERPluginTable& table) +{ + mpTable = &table; + m_menu_name = name; + + const char* commands = mpTable->m_pfnQERPlug_GetCommandList(); + const char* titles = mpTable->m_pfnQERPlug_GetCommandTitleList(); + + StringTokeniser commandTokeniser(commands, ",;"); + StringTokeniser titleTokeniser(titles, ",;"); + + const char* cmdToken = commandTokeniser.getToken(); + const char *titleToken = titleTokeniser.getToken(); + while (!string_empty(cmdToken)) + { + if(string_empty(titleToken)) + { + m_CommandStrings.push_back(cmdToken); + m_CommandTitleStrings.push_back(cmdToken); + cmdToken = commandTokeniser.getToken(); + titleToken = ""; + } + else + { + m_CommandStrings.push_back(cmdToken); + m_CommandTitleStrings.push_back(titleToken); + cmdToken = commandTokeniser.getToken(); + titleToken = titleTokeniser.getToken(); + } + } + mpTable->m_pfnQERPlug_Init(0, (void*)main_window); +} + +const char* CPluginSlot::getMenuName() +{ + return m_menu_name.c_str(); +} + +std::size_t CPluginSlot::getCommandCount() +{ + return m_CommandStrings.size(); +} + +const char* CPluginSlot::getCommand(std::size_t n) +{ + std::list::iterator i = m_CommandStrings.begin(); + while(n-- != 0) + ++i; + return (*i).c_str(); +} + +const char* CPluginSlot::getCommandTitle(std::size_t n) +{ + std::list::iterator i = m_CommandTitleStrings.begin(); + while(n-- != 0) + ++i; + return (*i).c_str(); +} + +void CPluginSlot::addMenuID(std::size_t n) +{ + m_CommandIDs.push_back(n); +} + +bool CPluginSlot::ownsCommandID(std::size_t n) +{ + for(std::list::iterator i = m_CommandIDs.begin(); i != m_CommandIDs.end(); ++i) + { + if (*i == n) + return true; + } + return false; +} + +void CPluginSlot::Dispatch(const char *p) +{ + Vector3 vMin, vMax; + Select_GetBounds (vMin, vMax); + mpTable->m_pfnQERPlug_Dispatch(p, reinterpret_cast(&vMin), reinterpret_cast(&vMax), true);//QE_SingleBrush(true)); +} + + +class CPluginSlots +{ + std::list mSlots; +public: + virtual ~CPluginSlots(); + + void AddPluginSlot(GtkWidget* main_window, const char* name, const _QERPluginTable& table) + { + mSlots.push_back(new CPluginSlot(main_window, name, table)); + } + + void PopulateMenu(PluginsVisitor& menu); + bool Dispatch(std::size_t n, const char* p); +}; + +CPluginSlots::~CPluginSlots() +{ + std::list::iterator iSlot; + for(iSlot=mSlots.begin(); iSlot!=mSlots.end(); ++iSlot) + { + delete *iSlot; + *iSlot = 0; + } +} + +void CPluginSlots::PopulateMenu(PluginsVisitor& menu) +{ + std::list::iterator iPlug; + for(iPlug=mSlots.begin(); iPlug != mSlots.end(); ++iPlug) + { + menu.visit(*(*iPlug)); + } +} + +bool CPluginSlots::Dispatch(std::size_t n, const char* p) +{ + std::list::iterator iPlug; + for(iPlug=mSlots.begin(); iPlug!=mSlots.end(); ++iPlug) + { + CPluginSlot *pPlug = *iPlug; + if (pPlug->ownsCommandID(n)) + { + pPlug->Dispatch(p); + return true; + } + } + return false; +} + +CPluginSlots g_plugin_slots; + + +void FillPluginSlots(CPluginSlots& slots, GtkWidget* main_window) +{ + class AddPluginVisitor : public PluginModules::Visitor + { + CPluginSlots& m_slots; + GtkWidget* m_main_window; + public: + AddPluginVisitor(CPluginSlots& slots, GtkWidget* main_window) + : m_slots(slots), m_main_window(main_window) + { + } + void visit(const char* name, const _QERPluginTable& table) const + { + m_slots.AddPluginSlot(m_main_window, name, table); + } + } visitor(slots, main_window); + + Radiant_getPluginModules().foreachModule(visitor); +} + + +#include "pluginmanager.h" + +CPlugInManager g_PlugInMgr; + +CPlugInManager& GetPlugInMgr() +{ + return g_PlugInMgr; +} + +void CPlugInManager::Dispatch(std::size_t n, const char * p) +{ + g_plugin_slots.Dispatch(n, p); +} + +void CPlugInManager::Init(GtkWidget* main_window) +{ + FillPluginSlots(g_plugin_slots, main_window); +} + +void CPlugInManager::constructMenu(PluginsVisitor& menu) +{ + g_plugin_slots.PopulateMenu(menu); +} + +void CPlugInManager::Shutdown() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/pluginmanager.h b/misc/mediasource/netradiant-src/radiant/pluginmanager.h new file mode 100644 index 00000000..cf148bb5 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/pluginmanager.h @@ -0,0 +1,65 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_PLUGINMANAGER_H) +#define INCLUDED_PLUGINMANAGER_H + +#include + +typedef struct _GtkWidget GtkWidget; + +/*! +\class IPlugin +pure virtual interface for a plugin +temporary solution for migration from old plugin tech to synapse plugins +*/ +class IPlugIn +{ +public: + IPlugIn() { } + virtual ~IPlugIn() { } + + virtual const char* getMenuName() = 0; + virtual std::size_t getCommandCount() = 0; + virtual const char* getCommand(std::size_t) = 0; + virtual const char* getCommandTitle(std::size_t) = 0; + virtual void addMenuID(std::size_t) = 0; + virtual bool ownsCommandID(std::size_t n) = 0; +}; + +class PluginsVisitor +{ +public: + virtual void visit(IPlugIn& plugin) = 0; +}; + +class CPlugInManager +{ +public: + void Dispatch(std::size_t n, const char *p); + void Init(GtkWidget* main_window); + void constructMenu(PluginsVisitor& menu); + void Shutdown(); +}; + +CPlugInManager& GetPlugInMgr(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/pluginmenu.cpp b/misc/mediasource/netradiant-src/radiant/pluginmenu.cpp new file mode 100644 index 00000000..0fe758ed --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/pluginmenu.cpp @@ -0,0 +1,196 @@ +/* +Copyright (C) 1999-2006 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 "pluginmenu.h" + +#include "stream/textstream.h" + +#include +#include + +#include "gtkutil/pointer.h" +#include "gtkutil/menu.h" + +#include "pluginmanager.h" +#include "mainframe.h" +#include "preferences.h" + + +int m_nNextPlugInID = 0; + +void plugin_activated(GtkWidget* widget, gpointer data) +{ + const char* str = (const char*)g_object_get_data(G_OBJECT(widget),"command"); + GetPlugInMgr().Dispatch(gpointer_to_int(data), str); +} + +#include +typedef std::stack WidgetStack; + +void PlugInMenu_Add(GtkMenu* plugin_menu, IPlugIn* pPlugIn) +{ + GtkWidget *menu, *item, *parent, *subMenu; + const char *menuText, *menuCommand; + WidgetStack menuStack; + + parent = gtk_menu_item_new_with_label (pPlugIn->getMenuName()); + gtk_widget_show (parent); + gtk_container_add (GTK_CONTAINER (plugin_menu), parent); + + std::size_t nCount = pPlugIn->getCommandCount(); + if (nCount > 0) + { + menu = gtk_menu_new(); + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (GTK_MENU(menu)); + while (nCount > 0) + { + menuText = pPlugIn->getCommandTitle(--nCount); + menuCommand = pPlugIn->getCommand(nCount); + + if (menuText != 0 && strlen(menuText) > 0) + { + if (!strcmp(menuText, "-")) + { + item = gtk_menu_item_new(); + gtk_widget_set_sensitive (item, FALSE); + } + else if (!strcmp(menuText, ">")) + { + menuText = pPlugIn->getCommandTitle(--nCount); + menuCommand = pPlugIn->getCommand(nCount); + if (!strcmp(menuText, "-") || !strcmp(menuText, ">") || !strcmp(menuText, "<")) + { + globalErrorStream() << pPlugIn->getMenuName() << " Invalid title (" << menuText << ") for submenu.\n"; + continue; + } + + item = gtk_menu_item_new_with_label(menuText); + gtk_widget_show (item); + gtk_container_add (GTK_CONTAINER (menu), item); + + subMenu = gtk_menu_new(); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), subMenu); + menuStack.push(menu); + menu = subMenu; + continue; + } + else if (!strcmp(menuText, "<")) + { + if (!menuStack.empty()) + { + menu = menuStack.top(); + menuStack.pop(); + } + else + { + globalErrorStream() << pPlugIn->getMenuName() << ": Attempt to end non-existent submenu ignored.\n"; + } + continue; + } + else + { + item = gtk_menu_item_new_with_label (menuText); + g_object_set_data(G_OBJECT(item),"command", const_cast(static_cast(menuCommand))); + g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(plugin_activated), gint_to_pointer(m_nNextPlugInID)); + } + gtk_widget_show (item); + gtk_container_add (GTK_CONTAINER (menu), item); + pPlugIn->addMenuID(m_nNextPlugInID++); + } + } + if (!menuStack.empty()) + { + std::size_t size = menuStack.size(); + if (size != 0) + { + globalErrorStream() << pPlugIn->getMenuName() << " mismatched > <. " << Unsigned(size) << " submenu(s) not closed.\n"; + } + for (std::size_t i = 0; i < (size -1); i++) + { + menuStack.pop(); + } + menu = menuStack.top(); + menuStack.pop(); + } + gtk_menu_item_set_submenu (GTK_MENU_ITEM (parent), menu); + } +} + +GtkMenu* g_plugins_menu = 0; +GtkMenuItem* g_plugins_menu_separator = 0; + +void PluginsMenu_populate() +{ + class PluginsMenuConstructor : public PluginsVisitor + { + GtkMenu* m_menu; + public: + PluginsMenuConstructor(GtkMenu* menu) : m_menu(menu) + { + } + void visit(IPlugIn& plugin) + { + PlugInMenu_Add(m_menu, &plugin); + } + }; + + PluginsMenuConstructor constructor(g_plugins_menu); + GetPlugInMgr().constructMenu(constructor); +} + +void PluginsMenu_clear() +{ + m_nNextPlugInID = 0; + + GList* lst = g_list_find (gtk_container_children(GTK_CONTAINER(g_plugins_menu)), GTK_WIDGET(g_plugins_menu_separator)); + while (lst->next) + { + gtk_container_remove (GTK_CONTAINER(g_plugins_menu), GTK_WIDGET (lst->next->data)); + lst = g_list_find (gtk_container_children(GTK_CONTAINER(g_plugins_menu)), GTK_WIDGET(g_plugins_menu_separator)); + } +} + +GtkMenuItem* create_plugins_menu() +{ + // Plugins menu + GtkMenuItem* plugins_menu_item = new_sub_menu_item_with_mnemonic("_Plugins"); + GtkMenu* menu = GTK_MENU(gtk_menu_item_get_submenu(plugins_menu_item)); + if (g_Layout_enableDetachableMenus.m_value) + { + menu_tearoff(menu); + } + + g_plugins_menu = menu; + + //TODO: some modules/plugins do not yet support refresh +#if 0 + create_menu_item_with_mnemonic(menu, "Refresh", FreeCaller()); + + // NOTE: the seperator is used when doing a refresh of the list, everything past the seperator is removed + g_plugins_menu_separator = menu_separator(menu); +#endif + + PluginsMenu_populate(); + + return plugins_menu_item; +} + diff --git a/misc/mediasource/netradiant-src/radiant/pluginmenu.h b/misc/mediasource/netradiant-src/radiant/pluginmenu.h new file mode 100644 index 00000000..f843bcb4 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/pluginmenu.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_PLUGINMENU_H) +#define INCLUDED_PLUGINMENU_H + +typedef struct _GtkMenuItem GtkMenuItem; +GtkMenuItem* create_plugins_menu(); + +typedef struct _GtkMenu GtkMenu; +typedef struct _GtkMenuItem GtkMenuItem; +void PluginsMenu_populate(); +void PluginsMenu_clear(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/plugintoolbar.cpp b/misc/mediasource/netradiant-src/radiant/plugintoolbar.cpp new file mode 100644 index 00000000..4612fbd4 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/plugintoolbar.cpp @@ -0,0 +1,151 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "plugintoolbar.h" + + +#include "itoolbar.h" +#include "modulesystem.h" + +#include + +#include "stream/stringstream.h" +#include "gtkutil/image.h" +#include "gtkutil/container.h" + +#include "mainframe.h" +#include "plugin.h" + +GtkImage* new_plugin_image(const char* filename) +{ + { + StringOutputStream fullpath(256); + fullpath << GameToolsPath_get() << g_pluginsDir << "bitmaps/" << filename; + GtkImage* image = image_new_from_file_with_mask(fullpath.c_str()); + if(image != 0) + { + return image; + } + } + + { + StringOutputStream fullpath(256); + fullpath << AppPath_get() << g_pluginsDir << "bitmaps/" << filename; + GtkImage* image = image_new_from_file_with_mask(fullpath.c_str()); + if(image != 0) + { + return image; + } + } + + { + StringOutputStream fullpath(256); + fullpath << AppPath_get() << g_modulesDir << "bitmaps/" << filename; + GtkImage* image = image_new_from_file_with_mask(fullpath.c_str()); + if(image != 0) + { + return image; + } + } + + return image_new_missing(); +} + +inline GtkToolbarChildType gtktoolbarchildtype_for_toolbarbuttontype(IToolbarButton::EType type) +{ + switch(type) + { + case IToolbarButton::eSpace: + return GTK_TOOLBAR_CHILD_SPACE; + case IToolbarButton::eButton: + return GTK_TOOLBAR_CHILD_BUTTON; + case IToolbarButton::eToggleButton: + return GTK_TOOLBAR_CHILD_TOGGLEBUTTON; + case IToolbarButton::eRadioButton: + return GTK_TOOLBAR_CHILD_RADIOBUTTON; + } + ERROR_MESSAGE("invalid toolbar button type"); + return (GtkToolbarChildType)0; +} + +void toolbar_insert(GtkToolbar *toolbar, const char* icon, const char* text, const char* tooltip, IToolbarButton::EType type, GtkSignalFunc handler, gpointer data) +{ + gtk_toolbar_append_element(toolbar, gtktoolbarchildtype_for_toolbarbuttontype(type), 0, text, tooltip, "", GTK_WIDGET(new_plugin_image(icon)), handler, data); +} + +void ActivateToolbarButton(GtkWidget *widget, gpointer data) +{ + const_cast(reinterpret_cast(data))->activate(); +} + +void PlugInToolbar_AddButton(GtkToolbar* toolbar, const IToolbarButton* button) +{ + toolbar_insert(toolbar, button->getImage(), button->getText(), button->getTooltip(), button->getType(), GTK_SIGNAL_FUNC(ActivateToolbarButton), reinterpret_cast(const_cast(button))); +} + +GtkToolbar* g_plugin_toolbar = 0; + +void PluginToolbar_populate() +{ + class AddToolbarItemVisitor : public ToolbarModules::Visitor + { + GtkToolbar* m_toolbar; + public: + AddToolbarItemVisitor(GtkToolbar* toolbar) + : m_toolbar(toolbar) + { + } + void visit(const char* name, const _QERPlugToolbarTable& table) const + { + const std::size_t count = table.m_pfnToolbarButtonCount(); + for(std::size_t i=0;iGetCamWnd(); + Camera_setOrigin(camwnd, *i); + g_pParentWnd->GetXYWnd()->SetOrigin(*i); + { + Vector3 dir(vector3_normalised(vector3_subtracted(*(++i), Camera_getOrigin(camwnd)))); + Vector3 angles(Camera_getAngles(camwnd)); + angles[CAMERA_YAW] = static_cast(radians_to_degrees(atan2(dir[1], dir[0]))); + angles[CAMERA_PITCH] = static_cast(radians_to_degrees(asin(dir[2]))); + Camera_setAngles(camwnd, angles); + } +} + +// advance camera to previous point +void Pointfile_Prev (void) +{ + if(!s_pointfile.shown()) + return; + + if (s_check_point == s_pointfile.begin()) + { + globalOutputStream() << "Start of pointfile\n"; + return; + } + + CPointfile::const_iterator i = --s_check_point; + + CamWnd& camwnd = *g_pParentWnd->GetCamWnd(); + Camera_setOrigin(camwnd, *i); + g_pParentWnd->GetXYWnd()->SetOrigin(*i); + { + Vector3 dir(vector3_normalised(vector3_subtracted(*(++i), Camera_getOrigin(camwnd)))); + Vector3 angles(Camera_getAngles(camwnd)); + angles[CAMERA_YAW] = static_cast(radians_to_degrees(atan2(dir[1], dir[0]))); + angles[CAMERA_PITCH] = static_cast(radians_to_degrees(asin(dir[2]))); + Camera_setAngles(camwnd, angles); + } +} + +int LoadFile (const char *filename, void **bufferptr) +{ + FILE *f; + long len; + + f = fopen (filename, "rb"); + if (f == 0) + return -1; + + fseek (f, 0, SEEK_END); + len = ftell (f); + rewind (f); + + *bufferptr = malloc (len+1); + if (*bufferptr == 0) + return -1; + + fread (*bufferptr, 1, len, f); + fclose (f); + + // we need to end the buffer with a 0 + ((char*) (*bufferptr))[len] = 0; + + return len; +} + +void Pointfile_Parse(CPointfile& pointfile) +{ + int size; + char *data; + char *text; + int line = 1; + + const char* mapname = Map_Name(g_map); + StringOutputStream name(256); + name << StringRange(mapname, path_get_filename_base_end(mapname)) << ".lin"; + + size = LoadFile (name.c_str(), (void**)&data); + if (size == -1) + { + globalErrorStream() << "Pointfile " << name.c_str() << " not found\n"; + return; + } + + // store a pointer + text = data; + + globalOutputStream() << "Reading pointfile " << name.c_str() << "\n"; + + pointfile.Init(); + + while (*data) + { + Vector3 v; + if (sscanf(data,"%f %f %f", &v[0], &v[1], &v[2]) != 3) + { + globalOutputStream() << "Corrupt point file, line " << line << "\n"; + break; + } + + while (*data && *data != '\n') + { + if (*(data-1) == ' ' && *(data) == '-' && *(data+1) == ' ') + break; + data++; + } + // deal with zhlt style point files. + if (*data == '-') + { + if (sscanf(data,"- %f %f %f", &v[0], &v[1], &v[2]) != 3) + { + globalOutputStream() << "Corrupt point file, line " << line << "\n"; + break; + } + + while (*data && *data != '\n') + data++; + + } + while (*data == '\n') + { + data++; // skip the \n + line++; + } + pointfile.PushPoint (v); + } + + g_free(text); +} + +void Pointfile_Clear() +{ + s_pointfile.show(false); +} + +void Pointfile_Toggle() +{ + s_pointfile.show(!s_pointfile.shown()); + + s_check_point = s_pointfile.begin(); +} + +void Pointfile_Construct() +{ + CPointfile::constructStatic(); + + GlobalShaderCache().attachRenderable(s_pointfile); + + GlobalCommands_insert("TogglePointfile", FreeCaller()); + GlobalCommands_insert("NextLeakSpot", FreeCaller(), Accelerator('K', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalCommands_insert("PrevLeakSpot", FreeCaller(), Accelerator('L', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); +} + +void Pointfile_Destroy() +{ + GlobalShaderCache().detachRenderable(s_pointfile); + + CPointfile::destroyStatic(); +} + + + +// CPointfile implementation for SAX-specific stuff ------------------------------- +void CPointfile::saxStartElement (message_info_t *ctx, const xmlChar *name, const xmlChar **attrs) +{ + if(string_equal(reinterpret_cast(name), "polyline")) + { + Init(); + // there's a prefs setting to avoid stopping on leak + if (!g_WatchBSP_LeakStop) + ctx->stop_depth = 0; + } +} + +void CPointfile::saxEndElement (message_info_t *ctx, const xmlChar *name) +{ + if(string_equal(reinterpret_cast(name), "polyline")) + { + // we are done + GenerateDisplayList(); + SceneChangeNotify(); + s_check_point = begin(); + } + else if(string_equal(reinterpret_cast(name), "point")) + { + Vector3 v; + sscanf(m_characters.c_str(), "%f %f %f\n", &v[0], &v[1], &v[2]); + PushPoint(v); + m_characters.clear(); + } +} + +// only "point" is expected to have characters around here +void CPointfile::saxCharacters (message_info_t *ctx, const xmlChar *ch, int len) +{ + m_characters.write(reinterpret_cast(ch), len); +} + +const char* CPointfile::getName() +{ + return "Map leaked"; +} diff --git a/misc/mediasource/netradiant-src/radiant/points.h b/misc/mediasource/netradiant-src/radiant/points.h new file mode 100644 index 00000000..63665b78 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/points.h @@ -0,0 +1,40 @@ +/* +Copyright (C) 1999-2006 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: +// header for Pointfile stuff (adding a C++ class to wrap the pointfile thing in the SAX parser) +// + +#if !defined(INCLUDED_POINTS_H) +#define INCLUDED_POINTS_H + +void Pointfile_Clear(); +void Pointfile_Delete (void); + +void Pointfile_Construct(); +void Pointfile_Destroy(); + +class ISAXHandler; +extern ISAXHandler& g_pointfile; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/preferencedictionary.cpp b/misc/mediasource/netradiant-src/radiant/preferencedictionary.cpp new file mode 100644 index 00000000..598190eb --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/preferencedictionary.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "preferencedictionary.h" + diff --git a/misc/mediasource/netradiant-src/radiant/preferencedictionary.h b/misc/mediasource/netradiant-src/radiant/preferencedictionary.h new file mode 100644 index 00000000..45757d01 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/preferencedictionary.h @@ -0,0 +1,296 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_PREFERENCEDICTIONARY_H) +#define INCLUDED_PREFERENCEDICTIONARY_H + +#include "preferencesystem.h" +#include "xml/ixml.h" +#include "stream/stringstream.h" +#include "generic/callback.h" +#include "versionlib.h" +#include + +class PreferenceDictionary : public PreferenceSystem +{ + class PreferenceEntry + { + StringImportCallback m_importer; + StringExportCallback m_exporter; + public: + PreferenceEntry(const StringImportCallback& importer, const StringExportCallback& exporter) + : m_importer(importer), m_exporter(exporter) + { + } + void importString(const char* string) + { + m_importer(string); + } + void exportString(const StringImportCallback& importer) + { + m_exporter(importer); + } + }; + + typedef std::map PreferenceEntries; + PreferenceEntries m_preferences; + + typedef std::map PreferenceCache; + PreferenceCache m_cache; + +public: + typedef PreferenceEntries::iterator iterator; + + iterator begin() + { + return m_preferences.begin(); + } + iterator end() + { + return m_preferences.end(); + } + iterator find(const char* name) + { + return m_preferences.find(name); + } + + void registerPreference(const char* name, const StringImportCallback& importer, const StringExportCallback& exporter) + { + m_preferences.insert(PreferenceEntries::value_type(name, PreferenceEntry(importer, exporter))); + PreferenceCache::iterator i = m_cache.find(name); + if(i != m_cache.end()) + { + importer((*i).second.c_str()); + m_cache.erase(i); + } + } + + void importPref(const char* name, const char* value) + { + PreferenceEntries::iterator i = m_preferences.find(name); + if(i != m_preferences.end()) + { + (*i).second.importString(value); + } + else + { + m_cache.erase(name); + m_cache.insert(PreferenceCache::value_type(name, value)); + } + } +}; + +inline void XMLPreference_importString(XMLImporter& importer, const char* value) +{ + importer.write(value, string_length(value)); +} +typedef ReferenceCaller1 XMLPreferenceImportStringCaller; + +class XMLPreferenceDictionaryExporter : public XMLExporter +{ + class XMLQPrefElement : public XMLElement + { + const char* m_version; + public: + XMLQPrefElement(const char* version) : m_version(version) + { + } + const char* name() const + { + return "qpref"; + } + const char* attribute(const char* name) const + { + if(string_equal(name, "version")) + { + return m_version; + } + return ""; + } + void forEachAttribute(XMLAttrVisitor& visitor) const + { + visitor.visit("version", m_version); + } + }; + + class XMLPreferenceElement : public XMLElement + { + const char* m_name; + public: + XMLPreferenceElement(const char* name) + : m_name(name) + { + } + const char* name() const + { + return "epair"; + } + const char* attribute(const char* name) const + { + if(string_equal(name, "name")) + return m_name; + return ""; + } + void forEachAttribute(XMLAttrVisitor& visitor) const + { + visitor.visit("name", m_name); + } + }; + + typedef PreferenceDictionary PreferenceEntries; + PreferenceEntries& m_preferences; + const char* m_version; +public: + XMLPreferenceDictionaryExporter(PreferenceDictionary& preferences, const char* version) + : m_preferences(preferences), m_version(version) + { + } + + void exportXML(XMLImporter& importer) + { + importer.write("\n", 1); + + XMLQPrefElement qpref_element(m_version); + importer.pushElement(qpref_element); + importer.write("\n", 1); + + for(PreferenceEntries::iterator i = m_preferences.begin(); i != m_preferences.end(); ++i) + { + XMLPreferenceElement epair_element((*i).first.c_str()); + + importer.pushElement(epair_element); + + (*i).second.exportString(XMLPreferenceImportStringCaller(importer)); + + importer.popElement(epair_element.name()); + importer.write("\n", 1); + } + + importer.popElement(qpref_element.name()); + importer.write("\n", 1); + } +}; + +class XMLPreferenceDictionaryImporter : public XMLImporter +{ + struct xml_state_t + { + enum ETag + { + tag_qpref, + tag_qpref_ignore, + tag_epair, + tag_epair_ignore + }; + + xml_state_t(ETag tag) + : m_tag(tag) + { + } + + ETag m_tag; + CopiedString m_name; + StringOutputStream m_ostream; + }; + + typedef std::vector xml_stack_t; + xml_stack_t m_xml_stack; + + typedef PreferenceDictionary PreferenceEntries; + PreferenceEntries& m_preferences; + Version m_version; +public: + XMLPreferenceDictionaryImporter(PreferenceDictionary& preferences, const char* version) + : m_preferences(preferences), m_version(version_parse(version)) + { + } + + void pushElement(const XMLElement& element) + { + if(m_xml_stack.empty()) + { + if(string_equal(element.name(), "qpref")) + { + Version dataVersion(version_parse(element.attribute("version"))); + if(!version_compatible(m_version, dataVersion)) + { + globalOutputStream() << "qpref import: data version " << dataVersion << " is not compatible with code version " << m_version << "\n"; + m_xml_stack.push_back(xml_state_t::tag_qpref_ignore); + } + else + { + globalOutputStream() << "qpref import: data version " << dataVersion << " is compatible with code version " << m_version << "\n"; + m_xml_stack.push_back(xml_state_t::tag_qpref); + } + } + else + { + // not valid + } + } + else + { + switch(m_xml_stack.back().m_tag) + { + case xml_state_t::tag_qpref: + if(string_equal(element.name(), "epair")) + { + m_xml_stack.push_back(xml_state_t::tag_epair); + m_xml_stack.back().m_name = element.attribute("name"); + } + else + { + // not valid + } + break; + case xml_state_t::tag_qpref_ignore: + if(string_equal(element.name(), "epair")) + { + m_xml_stack.push_back(xml_state_t::tag_epair_ignore); + } + else + { + // not valid + } + break; + case xml_state_t::tag_epair: + case xml_state_t::tag_epair_ignore: + // not valid + break; + } + } + + } + void popElement(const char* name) + { + if(m_xml_stack.back().m_tag == xml_state_t::tag_epair) + { + m_preferences.importPref(m_xml_stack.back().m_name.c_str(), m_xml_stack.back().m_ostream.c_str()); + } + m_xml_stack.pop_back(); + } + std::size_t write(const char* buffer, std::size_t length) + { + return m_xml_stack.back().m_ostream.write(buffer, length); + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/preferences.cpp b/misc/mediasource/netradiant-src/radiant/preferences.cpp new file mode 100644 index 00000000..a691d812 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/preferences.cpp @@ -0,0 +1,1084 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// User preferences +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "preferences.h" +#include "environment.h" + +#include "debugging/debugging.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "generic/callback.h" +#include "math/vector.h" +#include "string/string.h" +#include "stream/stringstream.h" +#include "os/file.h" +#include "os/path.h" +#include "os/dir.h" +#include "gtkutil/filechooser.h" +#include "gtkutil/messagebox.h" +#include "cmdlib.h" + +#include "error.h" +#include "console.h" +#include "xywindow.h" +#include "mainframe.h" +#include "qe3.h" +#include "gtkdlgs.h" + + + +void Global_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox("Console", "Enable Logging", g_Console_enableLogging); +} + +void Interface_constructPreferences(PreferencesPage& page) +{ +#ifdef WIN32 + page.appendCheckBox("", "Default Text Editor", g_TextEditor_useWin32Editor); +#else + { + GtkWidget* use_custom = page.appendCheckBox("Text Editor", "Custom", g_TextEditor_useCustomEditor); + GtkWidget* custom_editor = page.appendPathEntry("Text Editor Command", g_TextEditor_editorCommand, true); + Widget_connectToggleDependency(custom_editor, use_custom); + } +#endif +} + +void Mouse_constructPreferences(PreferencesPage& page) +{ + { + const char* buttons[] = { "2 button", "3 button", }; + page.appendRadio("Mouse Type", g_glwindow_globals.m_nMouseType, STRING_ARRAY_RANGE(buttons)); + } + page.appendCheckBox("Right Button", "Activates Context Menu", g_xywindow_globals.m_bRightClick); +} +void Mouse_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Mouse", "Mouse Preferences")); + Mouse_constructPreferences(page); +} +void Mouse_registerPreferencesPage() +{ + PreferencesDialog_addInterfacePage(FreeCaller1()); +} + + +/*! +========================================================= +Games selection dialog +========================================================= +*/ + +#include + +inline const char* xmlAttr_getName(xmlAttrPtr attr) +{ + return reinterpret_cast(attr->name); +} + +inline const char* xmlAttr_getValue(xmlAttrPtr attr) +{ + return reinterpret_cast(attr->children->content); +} + +CGameDescription::CGameDescription(xmlDocPtr pDoc, const CopiedString& gameFile) +{ + // read the user-friendly game name + xmlNodePtr pNode = pDoc->children; + + while (strcmp((const char*)pNode->name, "game") && pNode != 0) + { + pNode=pNode->next; + } + if (!pNode) + { + Error("Didn't find 'game' node in the game description file '%s'\n", pDoc->URL); + } + + for(xmlAttrPtr attr = pNode->properties; attr != 0; attr = attr->next) + { + m_gameDescription.insert(GameDescription::value_type(xmlAttr_getName(attr), xmlAttr_getValue(attr))); + } + + { + StringOutputStream path(256); + path << AppPath_get() << gameFile.c_str() << "/"; + mGameToolsPath = path.c_str(); + } + + ASSERT_MESSAGE(file_exists(mGameToolsPath.c_str()), "game directory not found: " << makeQuoted(mGameToolsPath.c_str())); + + mGameFile = gameFile; + + { + GameDescription::iterator i = m_gameDescription.find("type"); + if(i == m_gameDescription.end()) + { + globalErrorStream() << "Warning, 'type' attribute not found in '" << reinterpret_cast(pDoc->URL) << "'\n"; + // default + mGameType = "q3"; + } + else + { + mGameType = (*i).second.c_str(); + } + } +} + +void CGameDescription::Dump() +{ + globalOutputStream() << "game description file: " << makeQuoted(mGameFile.c_str()) << "\n"; + for(GameDescription::iterator i = m_gameDescription.begin(); i != m_gameDescription.end(); ++i) + { + globalOutputStream() << (*i).first.c_str() << " = " << makeQuoted((*i).second.c_str()) << "\n"; + } +} + +CGameDescription *g_pGameDescription; ///< shortcut to g_GamesDialog.m_pCurrentDescription + + +#include "warnings.h" +#include "stream/textfilestream.h" +#include "container/array.h" +#include "xml/ixml.h" +#include "xml/xmlparser.h" +#include "xml/xmlwriter.h" + +#include "preferencedictionary.h" +#include "stringio.h" + +const char* const PREFERENCES_VERSION = "1.0"; + +bool Preferences_Load(PreferenceDictionary& preferences, const char* filename, const char *cmdline_prefix) +{ + bool ret = false; + TextFileInputStream file(filename); + if(!file.failed()) + { + XMLStreamParser parser(file); + XMLPreferenceDictionaryImporter importer(preferences, PREFERENCES_VERSION); + parser.exportXML(importer); + ret = true; + } + + int l = strlen(cmdline_prefix); + for(int i = 1; i < g_argc - 1; ++i) + { + if(g_argv[i][0] == '-') + { + if(!strncmp(g_argv[i]+1, cmdline_prefix, l)) + if(g_argv[i][l+1] == '-') + preferences.importPref(g_argv[i]+l+2, g_argv[i+1]); + ++i; + } + } + + return ret; +} + +bool Preferences_Save(PreferenceDictionary& preferences, const char* filename) +{ + TextFileOutputStream file(filename); + if(!file.failed()) + { + XMLStreamWriter writer(file); + XMLPreferenceDictionaryExporter exporter(preferences, PREFERENCES_VERSION); + exporter.exportXML(writer); + return true; + } + return false; +} + +bool Preferences_Save_Safe(PreferenceDictionary& preferences, const char* filename) +{ + Array tmpName(filename, filename + strlen(filename) + 1 + 3); + *(tmpName.end() - 4) = 'T'; + *(tmpName.end() - 3) = 'M'; + *(tmpName.end() - 2) = 'P'; + *(tmpName.end() - 1) = '\0'; + + return Preferences_Save(preferences, tmpName.data()) + && (!file_exists(filename) || file_remove(filename)) + && file_move(tmpName.data(), filename); +} + + + +void LogConsole_importString(const char* string) +{ + g_Console_enableLogging = string_equal(string, "true"); + Sys_LogFile(g_Console_enableLogging); +} +typedef FreeCaller1 LogConsoleImportStringCaller; + + +void RegisterGlobalPreferences(PreferenceSystem& preferences) +{ + preferences.registerPreference("gamefile", CopiedStringImportStringCaller(g_GamesDialog.m_sGameFile), CopiedStringExportStringCaller(g_GamesDialog.m_sGameFile)); + preferences.registerPreference("gamePrompt", BoolImportStringCaller(g_GamesDialog.m_bGamePrompt), BoolExportStringCaller(g_GamesDialog.m_bGamePrompt)); + preferences.registerPreference("log console", LogConsoleImportStringCaller(), BoolExportStringCaller(g_Console_enableLogging)); +} + + +PreferenceDictionary g_global_preferences; + +void GlobalPreferences_Init() +{ + RegisterGlobalPreferences(g_global_preferences); +} + +void CGameDialog::LoadPrefs() +{ + // load global .pref file + StringOutputStream strGlobalPref(256); + strGlobalPref << g_Preferences.m_global_rc_path->str << "global.pref"; + + globalOutputStream() << "loading global preferences from " << makeQuoted(strGlobalPref.c_str()) << "\n"; + + if(!Preferences_Load(g_global_preferences, strGlobalPref.c_str(), "global")) + { + globalOutputStream() << "failed to load global preferences from " << strGlobalPref.c_str() << "\n"; + } +} + +void CGameDialog::SavePrefs() +{ + StringOutputStream strGlobalPref(256); + strGlobalPref << g_Preferences.m_global_rc_path->str << "global.pref"; + + globalOutputStream() << "saving global preferences to " << strGlobalPref.c_str() << "\n"; + + if(!Preferences_Save_Safe(g_global_preferences, strGlobalPref.c_str())) + { + globalOutputStream() << "failed to save global preferences to " << strGlobalPref.c_str() << "\n"; + } +} + +void CGameDialog::DoGameDialog() +{ + // show the UI + DoModal(); + + // we save the prefs file + SavePrefs(); +} + +void CGameDialog::GameFileImport(int value) +{ + m_nComboSelect = value; + // use value to set m_sGameFile + std::list::iterator iGame = mGames.begin(); + int i; + for(i=0; imGameFile; +} + +void CGameDialog::GameFileExport(const IntImportCallback& importCallback) const +{ + // use m_sGameFile to set value + std::list::const_iterator iGame; + int i = 0; + for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) + { + if ((*iGame)->mGameFile == m_sGameFile) + { + m_nComboSelect = i; + break; + } + i++; + } + importCallback(m_nComboSelect); +} + +void CGameDialog_GameFileImport(CGameDialog& self, int value) +{ + self.GameFileImport(value); +} + +void CGameDialog_GameFileExport(CGameDialog& self, const IntImportCallback& importCallback) +{ + self.GameFileExport(importCallback); +} + +void CGameDialog::CreateGlobalFrame(PreferencesPage& page) +{ + std::vector games; + games.reserve(mGames.size()); + for(std::list::iterator i = mGames.begin(); i != mGames.end(); ++i) + { + games.push_back((*i)->getRequiredKeyValue("name")); + } + page.appendCombo( + "Select the game", + StringArrayRange(&(*games.begin()), &(*games.end())), + ReferenceCaller1(*this), + ReferenceCaller1(*this) + ); + page.appendCheckBox("Startup", "Show Global Preferences", m_bGamePrompt); +} + +GtkWindow* CGameDialog::BuildDialog() +{ + GtkFrame* frame = create_dialog_frame("Game settings", GTK_SHADOW_ETCHED_IN); + + GtkVBox* vbox2 = create_dialog_vbox(0, 4); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox2)); + + { + PreferencesPage preferencesPage(*this, GTK_WIDGET(vbox2)); + Global_constructPreferences(preferencesPage); + CreateGlobalFrame(preferencesPage); + } + + return create_simple_modal_dialog_window("Global Preferences", m_modal, GTK_WIDGET(frame)); +} + +class LoadGameFile +{ + std::list& mGames; + const char* mPath; +public: + LoadGameFile(std::list& games, const char* path) : mGames(games), mPath(path) + { + } + void operator()(const char* name) const + { + if(!extension_equal(path_get_extension(name), "game")) + { + return; + } + StringOutputStream strPath(256); + strPath << mPath << name; + globalOutputStream() << strPath.c_str() << '\n'; + + xmlDocPtr pDoc = xmlParseFile(strPath.c_str()); + if(pDoc) + { + mGames.push_front(new CGameDescription(pDoc, name)); + xmlFreeDoc(pDoc); + } + else + { + globalErrorStream() << "XML parser failed on '" << strPath.c_str() << "'\n"; + } + } +}; + +void CGameDialog::ScanForGames() +{ + StringOutputStream strGamesPath(256); + strGamesPath << AppPath_get() << "games/"; + const char *path = strGamesPath.c_str(); + + globalOutputStream() << "Scanning for game description files: " << path << '\n'; + + /*! + \todo FIXME LINUX: + do we put game description files below AppPath, or in ~/.radiant + i.e. read only or read/write? + my guess .. readonly cause it's an install + we will probably want to add ~/.radiant//games/ scanning on top of that for developers + (if that's really needed) + */ + + Directory_forEach(path, LoadGameFile(mGames, path)); +} + +CGameDescription* CGameDialog::GameDescriptionForComboItem() +{ + std::list::iterator iGame; + int i=0; + for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame,i++) + { + if (i == m_nComboSelect) + { + return (*iGame); + } + } + return 0; // not found +} + +void CGameDialog::InitGlobalPrefPath() +{ + g_Preferences.m_global_rc_path = g_string_new(SettingsPath_get()); +} + +void CGameDialog::Reset() +{ + if (!g_Preferences.m_global_rc_path) + InitGlobalPrefPath(); + StringOutputStream strGlobalPref(256); + strGlobalPref << g_Preferences.m_global_rc_path->str << "global.pref"; + file_remove(strGlobalPref.c_str()); +} + +void CGameDialog::Init() +{ + InitGlobalPrefPath(); + LoadPrefs(); + ScanForGames(); + if (mGames.empty()) + { + Error("Didn't find any valid game file descriptions, aborting\n"); + } + else + { + std::list::iterator iGame, iPrevGame; + for(iGame=mGames.begin(), iPrevGame = mGames.end(); iGame!=mGames.end(); iPrevGame = iGame, ++iGame) + { + if(iPrevGame != mGames.end()) + if(strcmp((*iGame)->getRequiredKeyValue("name"), (*iPrevGame)->getRequiredKeyValue("name")) < 0) + { + CGameDescription *h = *iGame; + *iGame = *iPrevGame; + *iPrevGame = h; + } + } + } + + CGameDescription* currentGameDescription = 0; + + if (!m_bGamePrompt) + { + // search by .game name + std::list::iterator iGame; + for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) + { + if ((*iGame)->mGameFile == m_sGameFile) + { + currentGameDescription = (*iGame); + break; + } + } + } + if (m_bGamePrompt || !currentGameDescription) + { + Create(); + DoGameDialog(); + // use m_nComboSelect to identify the game to run as and set the globals + currentGameDescription = GameDescriptionForComboItem(); + ASSERT_NOTNULL(currentGameDescription); + } + g_pGameDescription = currentGameDescription; + + g_pGameDescription->Dump(); +} + +CGameDialog::~CGameDialog() +{ + // free all the game descriptions + std::list::iterator iGame; + for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) + { + delete (*iGame); + *iGame = 0; + } + if(GetWidget() != 0) + { + Destroy(); + } +} + +inline const char* GameDescription_getIdentifier(const CGameDescription& gameDescription) +{ + const char* identifier = gameDescription.getKeyValue("index"); + if(string_empty(identifier)) + { + identifier = "1"; + } + return identifier; +} + +void CGameDialog::AddPacksURL(StringOutputStream &URL) +{ + // add the URLs for the list of game packs installed + // FIXME: this is kinda hardcoded for now.. + std::list::iterator iGame; + for(iGame=mGames.begin(); iGame!=mGames.end(); ++iGame) + { + URL << "&Games_dlup%5B%5D=" << GameDescription_getIdentifier(*(*iGame)); + } +} + +CGameDialog g_GamesDialog; + + +// ============================================================================= +// Widget callbacks for PrefsDlg + +static void OnButtonClean (GtkWidget *widget, gpointer data) +{ + // make sure this is what the user wants + if (gtk_MessageBox(GTK_WIDGET(g_Preferences.GetWidget()), "This will close Radiant and clean the corresponding registry entries.\n" + "Next time you start Radiant it will be good as new. Do you wish to continue?", + "Reset Registry", eMB_YESNO, eMB_ICONASTERISK) == eIDYES) + { + PrefsDlg *dlg = (PrefsDlg*)data; + dlg->EndModal (eIDCANCEL); + + g_preferences_globals.disable_ini = true; + Preferences_Reset(); + gtk_main_quit(); + } +} + +// ============================================================================= +// PrefsDlg class + +/* +======== + +very first prefs init deals with selecting the game and the game tools path +then we can load .ini stuff + +using prefs / ini settings: +those are per-game + +look in ~/.radiant//gamename +======== +*/ + +#define PREFS_LOCAL_FILENAME "local.pref" + +void PrefsDlg::Init() +{ + // m_global_rc_path has been set above + // m_rc_path is for game specific preferences + // takes the form: global-pref-path/gamename/prefs-file + + // this is common to win32 and Linux init now + m_rc_path = g_string_new (m_global_rc_path->str); + + // game sub-dir + g_string_append (m_rc_path, g_pGameDescription->mGameFile.c_str()); + g_string_append (m_rc_path, "/"); + Q_mkdir (m_rc_path->str); + + // then the ini file + m_inipath = g_string_new (m_rc_path->str); + g_string_append (m_inipath, PREFS_LOCAL_FILENAME); +} + +void notebook_set_page(GtkWidget* notebook, GtkWidget* page) +{ + int pagenum = gtk_notebook_page_num(GTK_NOTEBOOK(notebook), page); + if(gtk_notebook_get_current_page(GTK_NOTEBOOK(notebook)) != pagenum) + { + gtk_notebook_set_current_page(GTK_NOTEBOOK(notebook), pagenum); + } +} + +void PrefsDlg::showPrefPage(GtkWidget* prefpage) +{ + notebook_set_page(m_notebook, prefpage); + return; +} + +static void treeSelection(GtkTreeSelection* selection, gpointer data) +{ + PrefsDlg *dlg = (PrefsDlg*)data; + + GtkTreeModel* model; + GtkTreeIter selected; + if(gtk_tree_selection_get_selected(selection, &model, &selected)) + { + GtkWidget* prefpage; + gtk_tree_model_get(model, &selected, 1, (gpointer*)&prefpage, -1); + dlg->showPrefPage(prefpage); + } +} + +typedef std::list PreferenceGroupCallbacks; + +inline void PreferenceGroupCallbacks_constructGroup(const PreferenceGroupCallbacks& callbacks, PreferenceGroup& group) +{ + for(PreferenceGroupCallbacks::const_iterator i = callbacks.begin(); i != callbacks.end(); ++i) + { + (*i)(group); + } +} + + +inline void PreferenceGroupCallbacks_pushBack(PreferenceGroupCallbacks& callbacks, const PreferenceGroupCallback& callback) +{ + callbacks.push_back(callback); +} + +typedef std::list PreferencesPageCallbacks; + +inline void PreferencesPageCallbacks_constructPage(const PreferencesPageCallbacks& callbacks, PreferencesPage& page) +{ + for(PreferencesPageCallbacks::const_iterator i = callbacks.begin(); i != callbacks.end(); ++i) + { + (*i)(page); + } +} + +inline void PreferencesPageCallbacks_pushBack(PreferencesPageCallbacks& callbacks, const PreferencesPageCallback& callback) +{ + callbacks.push_back(callback); +} + +PreferencesPageCallbacks g_interfacePreferences; +void PreferencesDialog_addInterfacePreferences(const PreferencesPageCallback& callback) +{ + PreferencesPageCallbacks_pushBack(g_interfacePreferences, callback); +} +PreferenceGroupCallbacks g_interfaceCallbacks; +void PreferencesDialog_addInterfacePage(const PreferenceGroupCallback& callback) +{ + PreferenceGroupCallbacks_pushBack(g_interfaceCallbacks, callback); +} + +PreferencesPageCallbacks g_displayPreferences; +void PreferencesDialog_addDisplayPreferences(const PreferencesPageCallback& callback) +{ + PreferencesPageCallbacks_pushBack(g_displayPreferences, callback); +} +PreferenceGroupCallbacks g_displayCallbacks; +void PreferencesDialog_addDisplayPage(const PreferenceGroupCallback& callback) +{ + PreferenceGroupCallbacks_pushBack(g_displayCallbacks, callback); +} + +PreferencesPageCallbacks g_settingsPreferences; +void PreferencesDialog_addSettingsPreferences(const PreferencesPageCallback& callback) +{ + PreferencesPageCallbacks_pushBack(g_settingsPreferences, callback); +} +PreferenceGroupCallbacks g_settingsCallbacks; +void PreferencesDialog_addSettingsPage(const PreferenceGroupCallback& callback) +{ + PreferenceGroupCallbacks_pushBack(g_settingsCallbacks, callback); +} + +void Widget_updateDependency(GtkWidget* self, GtkWidget* toggleButton) +{ + gtk_widget_set_sensitive(self, gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(toggleButton)) && GTK_WIDGET_IS_SENSITIVE(toggleButton)); +} + +void ToggleButton_toggled_Widget_updateDependency(GtkWidget *toggleButton, GtkWidget* self) +{ + Widget_updateDependency(self, toggleButton); +} + +void ToggleButton_state_changed_Widget_updateDependency(GtkWidget* toggleButton, GtkStateType state, GtkWidget* self) +{ + if(state == GTK_STATE_INSENSITIVE) + { + Widget_updateDependency(self, toggleButton); + } +} + +void Widget_connectToggleDependency(GtkWidget* self, GtkWidget* toggleButton) +{ + g_signal_connect(G_OBJECT(toggleButton), "state_changed", G_CALLBACK(ToggleButton_state_changed_Widget_updateDependency), self); + g_signal_connect(G_OBJECT(toggleButton), "toggled", G_CALLBACK(ToggleButton_toggled_Widget_updateDependency), self); + Widget_updateDependency(self, toggleButton); +} + + +inline GtkWidget* getVBox(GtkWidget* page) +{ + return gtk_bin_get_child(GTK_BIN(page)); +} + +GtkTreeIter PreferenceTree_appendPage(GtkTreeStore* store, GtkTreeIter* parent, const char* name, GtkWidget* page) +{ + GtkTreeIter group; + gtk_tree_store_append(store, &group, parent); + gtk_tree_store_set(store, &group, 0, name, 1, page, -1); + return group; +} + +GtkWidget* PreferencePages_addPage(GtkWidget* notebook, const char* name) +{ + GtkWidget* preflabel = gtk_label_new(name); + gtk_widget_show(preflabel); + + GtkWidget* pageframe = gtk_frame_new(name); + gtk_container_set_border_width(GTK_CONTAINER(pageframe), 4); + gtk_widget_show(pageframe); + + GtkWidget* vbox = gtk_vbox_new(FALSE, 4); + gtk_widget_show(vbox); + gtk_container_set_border_width(GTK_CONTAINER(vbox), 4); + gtk_container_add(GTK_CONTAINER(pageframe), vbox); + + // Add the page to the notebook + gtk_notebook_append_page(GTK_NOTEBOOK(notebook), pageframe, preflabel); + + return pageframe; +} + +class PreferenceTreeGroup : public PreferenceGroup +{ + Dialog& m_dialog; + GtkWidget* m_notebook; + GtkTreeStore* m_store; + GtkTreeIter m_group; +public: + PreferenceTreeGroup(Dialog& dialog, GtkWidget* notebook, GtkTreeStore* store, GtkTreeIter group) : + m_dialog(dialog), + m_notebook(notebook), + m_store(store), + m_group(group) + { + } + PreferencesPage createPage(const char* treeName, const char* frameName) + { + GtkWidget* page = PreferencePages_addPage(m_notebook, frameName); + PreferenceTree_appendPage(m_store, &m_group, treeName, page); + return PreferencesPage(m_dialog, getVBox(page)); + } +}; + +GtkWindow* PrefsDlg::BuildDialog() +{ + PreferencesDialog_addInterfacePreferences(FreeCaller1()); + Mouse_registerPreferencesPage(); + + GtkWindow* dialog = create_floating_window("NetRadiant Preferences", m_parent); + + { + GtkWidget* mainvbox = gtk_vbox_new(FALSE, 5); + gtk_container_add(GTK_CONTAINER(dialog), mainvbox); + gtk_container_set_border_width(GTK_CONTAINER(mainvbox), 5); + gtk_widget_show(mainvbox); + + { + GtkWidget* hbox = gtk_hbox_new(FALSE, 5); + gtk_widget_show(hbox); + gtk_box_pack_end(GTK_BOX(mainvbox), hbox, FALSE, TRUE, 0); + + { + GtkButton* button = create_dialog_button("OK", G_CALLBACK(dialog_button_ok), &m_modal); + gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + { + GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(dialog_button_cancel), &m_modal); + gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + { + GtkButton* button = create_dialog_button("Clean", G_CALLBACK(OnButtonClean), this); + gtk_box_pack_end(GTK_BOX(hbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + } + + { + GtkWidget* hbox = gtk_hbox_new(FALSE, 5); + gtk_box_pack_start(GTK_BOX(mainvbox), hbox, TRUE, TRUE, 0); + gtk_widget_show(hbox); + + { + GtkWidget* sc_win = gtk_scrolled_window_new(0, 0); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sc_win), GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_box_pack_start(GTK_BOX(hbox), sc_win, FALSE, FALSE, 0); + gtk_widget_show(sc_win); + gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sc_win), GTK_SHADOW_IN); + + // prefs pages notebook + m_notebook = gtk_notebook_new(); + // hide the notebook tabs since its not supposed to look like a notebook + gtk_notebook_set_show_tabs(GTK_NOTEBOOK(m_notebook), FALSE); + gtk_box_pack_start(GTK_BOX(hbox), m_notebook, TRUE, TRUE, 0); + gtk_widget_show(m_notebook); + + + { + GtkTreeStore* store = gtk_tree_store_new(2, G_TYPE_STRING, G_TYPE_POINTER); + + GtkWidget* view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(store)); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(view), FALSE); + + { + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("Preferences", renderer, "text", 0, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW(view), column); + } + + { + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(view)); + g_signal_connect(G_OBJECT(selection), "changed", G_CALLBACK(treeSelection), this); + } + + gtk_widget_show(view); + + gtk_container_add(GTK_CONTAINER (sc_win), view); + + { + /********************************************************************/ + /* Add preference tree options */ + /********************************************************************/ + // Front page... + //GtkWidget* front = + PreferencePages_addPage(m_notebook, "Front Page"); + + { + GtkWidget* global = PreferencePages_addPage(m_notebook, "Global Preferences"); + { + PreferencesPage preferencesPage(*this, getVBox(global)); + Global_constructPreferences(preferencesPage); + } + GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Global", global); + { + GtkWidget* game = PreferencePages_addPage(m_notebook, "Game"); + PreferencesPage preferencesPage(*this, getVBox(game)); + g_GamesDialog.CreateGlobalFrame(preferencesPage); + + PreferenceTree_appendPage(store, &group, "Game", game); + } + } + + { + GtkWidget* interfacePage = PreferencePages_addPage(m_notebook, "Interface Preferences"); + { + PreferencesPage preferencesPage(*this, getVBox(interfacePage)); + PreferencesPageCallbacks_constructPage(g_interfacePreferences, preferencesPage); + } + + GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Interface", interfacePage); + PreferenceTreeGroup preferenceGroup(*this, m_notebook, store, group); + + PreferenceGroupCallbacks_constructGroup(g_interfaceCallbacks, preferenceGroup); + } + + { + GtkWidget* display = PreferencePages_addPage(m_notebook, "Display Preferences"); + { + PreferencesPage preferencesPage(*this, getVBox(display)); + PreferencesPageCallbacks_constructPage(g_displayPreferences, preferencesPage); + } + GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Display", display); + PreferenceTreeGroup preferenceGroup(*this, m_notebook, store, group); + + PreferenceGroupCallbacks_constructGroup(g_displayCallbacks, preferenceGroup); + } + + { + GtkWidget* settings = PreferencePages_addPage(m_notebook, "General Settings"); + { + PreferencesPage preferencesPage(*this, getVBox(settings)); + PreferencesPageCallbacks_constructPage(g_settingsPreferences, preferencesPage); + } + + GtkTreeIter group = PreferenceTree_appendPage(store, 0, "Settings", settings); + PreferenceTreeGroup preferenceGroup(*this, m_notebook, store, group); + + PreferenceGroupCallbacks_constructGroup(g_settingsCallbacks, preferenceGroup); + } + } + + gtk_tree_view_expand_all(GTK_TREE_VIEW(view)); + + g_object_unref(G_OBJECT(store)); + } + } + } + } + + gtk_notebook_set_page(GTK_NOTEBOOK(m_notebook), 0); + + return dialog; +} + +preferences_globals_t g_preferences_globals; + +PrefsDlg g_Preferences; // global prefs instance + + +void PreferencesDialog_constructWindow(GtkWindow* main_window) +{ + g_Preferences.m_parent = main_window; + g_Preferences.Create(); +} +void PreferencesDialog_destroyWindow() +{ + g_Preferences.Destroy(); +} + + +PreferenceDictionary g_preferences; + +PreferenceSystem& GetPreferenceSystem() +{ + return g_preferences; +} + +class PreferenceSystemAPI +{ + PreferenceSystem* m_preferencesystem; +public: + typedef PreferenceSystem Type; + STRING_CONSTANT(Name, "*"); + + PreferenceSystemAPI() + { + m_preferencesystem = &GetPreferenceSystem(); + } + PreferenceSystem* getTable() + { + return m_preferencesystem; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule PreferenceSystemModule; +typedef Static StaticPreferenceSystemModule; +StaticRegisterModule staticRegisterPreferenceSystem(StaticPreferenceSystemModule::instance()); + +void Preferences_Load() +{ + g_GamesDialog.LoadPrefs(); + + globalOutputStream() << "loading local preferences from " << g_Preferences.m_inipath->str << "\n"; + + if(!Preferences_Load(g_preferences, g_Preferences.m_inipath->str, g_GamesDialog.m_sGameFile.c_str())) + { + globalOutputStream() << "failed to load local preferences from " << g_Preferences.m_inipath->str << "\n"; + } +} + +void Preferences_Save() +{ + if (g_preferences_globals.disable_ini) + return; + + g_GamesDialog.SavePrefs(); + + globalOutputStream() << "saving local preferences to " << g_Preferences.m_inipath->str << "\n"; + + if(!Preferences_Save_Safe(g_preferences, g_Preferences.m_inipath->str)) + { + globalOutputStream() << "failed to save local preferences to " << g_Preferences.m_inipath->str << "\n"; + } +} + +void Preferences_Reset() +{ + file_remove(g_Preferences.m_inipath->str); +} + + +void PrefsDlg::PostModal (EMessageBoxReturn code) +{ + if (code == eIDOK) + { + Preferences_Save(); + UpdateAllWindows(); + } +} + +std::vector g_restart_required; + +void PreferencesDialog_restartRequired(const char* staticName) +{ + g_restart_required.push_back(staticName); +} + +void PreferencesDialog_showDialog() +{ + if(ConfirmModified("Edit Preferences") && g_Preferences.DoModal() == eIDOK) + { + if(!g_restart_required.empty()) + { + StringOutputStream message(256); + message << "Preference changes require a restart:\n"; + for(std::vector::iterator i = g_restart_required.begin(); i != g_restart_required.end(); ++i) + { + message << (*i) << '\n'; + } + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), message.c_str()); + g_restart_required.clear(); + } + } +} + + + + + +void GameName_importString(const char* value) +{ + gamename_set(value); +} +typedef FreeCaller1 GameNameImportStringCaller; +void GameName_exportString(const StringImportCallback& importer) +{ + importer(gamename_get()); +} +typedef FreeCaller1 GameNameExportStringCaller; + +void GameMode_importString(const char* value) +{ + gamemode_set(value); +} +typedef FreeCaller1 GameModeImportStringCaller; +void GameMode_exportString(const StringImportCallback& importer) +{ + importer(gamemode_get()); +} +typedef FreeCaller1 GameModeExportStringCaller; + + +void RegisterPreferences(PreferenceSystem& preferences) +{ +#ifdef WIN32 + preferences.registerPreference("UseCustomShaderEditor", BoolImportStringCaller(g_TextEditor_useWin32Editor), BoolExportStringCaller(g_TextEditor_useWin32Editor)); +#else + preferences.registerPreference("UseCustomShaderEditor", BoolImportStringCaller(g_TextEditor_useCustomEditor), BoolExportStringCaller(g_TextEditor_useCustomEditor)); + preferences.registerPreference("CustomShaderEditorCommand", CopiedStringImportStringCaller(g_TextEditor_editorCommand), CopiedStringExportStringCaller(g_TextEditor_editorCommand)); +#endif + + preferences.registerPreference("GameName", GameNameImportStringCaller(), GameNameExportStringCaller()); + preferences.registerPreference("GameMode", GameModeImportStringCaller(), GameModeExportStringCaller()); +} + +void Preferences_Init() +{ + RegisterPreferences(GetPreferenceSystem()); +} diff --git a/misc/mediasource/netradiant-src/radiant/preferences.h b/misc/mediasource/netradiant-src/radiant/preferences.h new file mode 100644 index 00000000..6375bec1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/preferences.h @@ -0,0 +1,434 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +/* +The following source code is licensed by Id Software and subject to the terms of +its LIMITED USE SOFTWARE LICENSE AGREEMENT, a copy of which is included with +GtkRadiant. If you did not receive a LIMITED USE SOFTWARE LICENSE AGREEMENT, +please contact Id Software immediately at info@idsoftware.com. +*/ + +#if !defined(INCLUDED_PREFERENCES_H) +#define INCLUDED_PREFERENCES_H + +#include "libxml/parser.h" +#include "dialog.h" +#include +#include + +void Widget_connectToggleDependency(GtkWidget* self, GtkWidget* toggleButton); + +class PreferencesPage +{ + Dialog& m_dialog; + GtkWidget* m_vbox; +public: + PreferencesPage(Dialog& dialog, GtkWidget* vbox) : m_dialog(dialog), m_vbox(vbox) + { + } + GtkWidget* appendCheckBox(const char* name, const char* flag, bool& data) + { + return m_dialog.addCheckBox(m_vbox, name, flag, data); + } + GtkWidget* appendCheckBox(const char* name, const char* flag, const BoolImportCallback& importCallback, const BoolExportCallback& exportCallback) + { + return m_dialog.addCheckBox(m_vbox, name, flag, importCallback, exportCallback); + } + void appendCombo(const char* name, StringArrayRange values, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) + { + m_dialog.addCombo(m_vbox, name, values, importCallback, exportCallback); + } + void appendCombo(const char* name, int& data, StringArrayRange values) + { + m_dialog.addCombo(m_vbox, name, data, values); + } + void appendSlider(const char* name, int& data, gboolean draw_value, const char* low, const char* high, double value, double lower, double upper, double step_increment, double page_increment) + { + m_dialog.addSlider(m_vbox, name, data, draw_value, low, high, value, lower, upper, step_increment, page_increment); + } + void appendRadio(const char* name, StringArrayRange names, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) + { + m_dialog.addRadio(m_vbox, name, names, importCallback, exportCallback); + } + void appendRadio(const char* name, int& data, StringArrayRange names) + { + m_dialog.addRadio(m_vbox, name, data, names); + } + void appendRadioIcons(const char* name, StringArrayRange icons, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) + { + m_dialog.addRadioIcons(m_vbox, name, icons, importCallback, exportCallback); + } + void appendRadioIcons(const char* name, int& data, StringArrayRange icons) + { + m_dialog.addRadioIcons(m_vbox, name, data, icons); + } + GtkWidget* appendEntry(const char* name, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) + { + return m_dialog.addIntEntry(m_vbox, name, importCallback, exportCallback); + } + GtkWidget* appendEntry(const char* name, int& data) + { + return m_dialog.addEntry(m_vbox, name, data); + } + GtkWidget* appendEntry(const char* name, const SizeImportCallback& importCallback, const SizeExportCallback& exportCallback) + { + return m_dialog.addSizeEntry(m_vbox, name, importCallback, exportCallback); + } + GtkWidget* appendEntry(const char* name, std::size_t& data) + { + return m_dialog.addEntry(m_vbox, name, data); + } + GtkWidget* appendEntry(const char* name, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback) + { + return m_dialog.addFloatEntry(m_vbox, name, importCallback, exportCallback); + } + GtkWidget* appendEntry(const char* name, float& data) + { + return m_dialog.addEntry(m_vbox, name, data); + } + GtkWidget* appendPathEntry(const char* name, bool browse_directory, const StringImportCallback& importCallback, const StringExportCallback& exportCallback) + { + return m_dialog.addPathEntry(m_vbox, name, browse_directory, importCallback, exportCallback); + } + GtkWidget* appendPathEntry(const char* name, CopiedString& data, bool directory) + { + return m_dialog.addPathEntry(m_vbox, name, data, directory); + } + GtkWidget* appendSpinner(const char* name, int& data, double value, double lower, double upper) + { + return m_dialog.addSpinner(m_vbox, name, data, value, lower, upper); + } + GtkWidget* appendSpinner(const char* name, double value, double lower, double upper, const IntImportCallback& importCallback, const IntExportCallback& exportCallback) + { + return m_dialog.addSpinner(m_vbox, name, value, lower, upper, importCallback, exportCallback); + } + GtkWidget* appendSpinner(const char* name, double value, double lower, double upper, const FloatImportCallback& importCallback, const FloatExportCallback& exportCallback) + { + return m_dialog.addSpinner(m_vbox, name, value, lower, upper, importCallback, exportCallback); + } +}; + +typedef Callback1 PreferencesPageCallback; + +class PreferenceGroup +{ +public: + virtual PreferencesPage createPage(const char* treeName, const char* frameName) = 0; +}; + +typedef Callback1 PreferenceGroupCallback; + +void PreferencesDialog_addInterfacePreferences(const PreferencesPageCallback& callback); +void PreferencesDialog_addInterfacePage(const PreferenceGroupCallback& callback); +void PreferencesDialog_addDisplayPreferences(const PreferencesPageCallback& callback); +void PreferencesDialog_addDisplayPage(const PreferenceGroupCallback& callback); +void PreferencesDialog_addSettingsPreferences(const PreferencesPageCallback& callback); +void PreferencesDialog_addSettingsPage(const PreferenceGroupCallback& callback); + +void PreferencesDialog_restartRequired(const char* staticName); + +template +class LatchedValue +{ +public: + Value m_value; + Value m_latched; + const char* m_description; + + LatchedValue(Value value, const char* description) : m_latched(value), m_description(description) + { + } + void useLatched() + { + m_value = m_latched; + } + void import(Value value) + { + m_latched = value; + if(m_latched != m_value) + { + PreferencesDialog_restartRequired(m_description); + } + } +}; + +typedef LatchedValue LatchedBool; +typedef MemberCaller1 LatchedBoolImportCaller; + +typedef LatchedValue LatchedInt; +typedef MemberCaller1 LatchedIntImportCaller; + +/*! +holds information for a given game +I'm a bit unclear on that still +it holds game specific configuration stuff +such as base names, engine names, some game specific features to activate in the various modules +it is not strictly a prefs thing since the user is not supposed to edit that (unless he is hacking +support for a new game) + +what we do now is fully generate the information for this during the setup. We might want to +generate a piece that just says "the game pack is there", but put the rest of the config somwhere +else (i.e. not generated, copied over during setup .. for instance in the game tools directory) +*/ +class CGameDescription +{ +typedef std::map GameDescription; + +public: + CopiedString mGameFile; ///< the .game file that describes this game + GameDescription m_gameDescription; + + CopiedString mGameToolsPath; ///< the explicit path to the game-dependent modules + CopiedString mGameType; ///< the type of the engine + + const char* getKeyValue(const char* key) const + { + GameDescription::const_iterator i = m_gameDescription.find(key); + if(i != m_gameDescription.end()) + { + return (*i).second.c_str(); + } + return ""; + } + const char* getRequiredKeyValue(const char* key) const + { + GameDescription::const_iterator i = m_gameDescription.find(key); + if(i != m_gameDescription.end()) + { + return (*i).second.c_str(); + } + ERROR_MESSAGE("game attribute " << makeQuoted(key) << " not found in " << makeQuoted(mGameFile.c_str())); + return ""; + } + + CGameDescription(xmlDocPtr pDoc, const CopiedString &GameFile); + + void Dump(); +}; + +extern CGameDescription *g_pGameDescription; + +typedef struct _GtkWidget GtkWidget; +class PrefsDlg; + +class PreferencesPage; + +class StringOutputStream; + +/*! +standalone dialog for games selection, and more generally global settings +*/ +class CGameDialog : public Dialog +{ +protected: + + mutable int m_nComboSelect; ///< intermediate int value for combo in dialog box + +public: + + /*! + those settings are saved in the global prefs file + I'm too lazy to wrap behind protected access, not sure this needs to be public + NOTE: those are preference settings. if you change them it is likely that you would + have to restart the editor for them to take effect + */ + /*@{*/ + /*! + what game has been selected + this is the name of the .game file + */ + CopiedString m_sGameFile; + /*! + prompt which game to load on startup + */ + bool m_bGamePrompt; + /*! + log console to radiant.log + m_bForceLogConsole is an obscure forced latching situation + */ + bool m_bForceLogConsole; + /*@}*/ + + /*! + the list of game descriptions we scanned from the game/ dir + */ + std::list mGames; + + CGameDialog() : + m_sGameFile(""), + m_bGamePrompt(true), + m_bForceLogConsole(false) + { + } + virtual ~CGameDialog(); + + void AddPacksURL(StringOutputStream &s); + + /*! + intialize the game dialog, called at CPrefsDlg::Init + will scan for games, load prefs, and do game selection dialog if needed + */ + void Init(); + + /*! + reset the global settings by removing the file + */ + void Reset(); + + /*! + run the dialog UI for the list of games + */ + void DoGameDialog(); + + /*! + Dialog API + this is only called when the dialog is built at startup for main engine select + */ + GtkWindow* BuildDialog(); + + void GameFileImport(int value); + void GameFileExport(const IntImportCallback& importCallback) const; + + /*! + construction of the dialog frame + this is the part to be re-used in prefs dialog + for the standalone dialog, we include this in a modal box + for prefs, we hook the frame in the main notebook + build the frame on-demand (only once) + */ + void CreateGlobalFrame(PreferencesPage& page); + + /*! + global preferences subsystem + XML-based this time, hopefully this will generalize to other prefs + LoadPrefs has hardcoded defaults + NOTE: it may not be strictly 'CGameDialog' to put the global prefs here + could have named the class differently I guess + */ + /*@{*/ + void LoadPrefs(); ///< load from file into variables + void SavePrefs(); ///< save pref variables to file + /*@}*/ + +private: + /*! + scan for .game files, load them + */ + void ScanForGames(); + + /*! + inits g_Preferences.m_global_rc_path + */ + void InitGlobalPrefPath(); + + /*! + uses m_nComboItem to find the right mGames + */ + CGameDescription *GameDescriptionForComboItem(); +}; + +/*! +this holds global level preferences +*/ +extern CGameDialog g_GamesDialog; + + +class texdef_t; + +class PrefsDlg : public Dialog +{ +public: +protected: + std::list mGames; + +public: + + GtkWidget *m_notebook; + + virtual ~PrefsDlg() + { + g_string_free (m_rc_path, true ); + g_string_free (m_inipath, true ); + } + + /*! + path for global settings + win32: AppPath + linux: ~/.radiant/[version]/ + */ + GString *m_global_rc_path; + + /*! + path to per-game settings + used for various game dependant storage + win32: GameToolsPath + linux: ~/.radiant/[version]/[gamename]/ + */ + GString *m_rc_path; + + /*! + holds per-game settings + m_rc_path+"local.pref" + \todo FIXME at some point this should become XML property bag code too + */ + GString *m_inipath; + + // initialize the above paths + void Init(); + + /*! Utility function for swapping notebook pages for tree list selections */ + void showPrefPage(GtkWidget* prefpage); + +protected: + + /*! Dialog API */ + GtkWindow* BuildDialog(); + void PostModal (EMessageBoxReturn code); +}; + +extern PrefsDlg g_Preferences; + +struct preferences_globals_t +{ + // disabled all INI / registry read write .. used when shutting down after registry cleanup + bool disable_ini; + preferences_globals_t() : disable_ini(false) + { + } +}; +extern preferences_globals_t g_preferences_globals; + +typedef struct _GtkWindow GtkWindow; +void PreferencesDialog_constructWindow(GtkWindow* main_window); +void PreferencesDialog_destroyWindow(); + +void PreferencesDialog_showDialog(); + +void GlobalPreferences_Init(); +void Preferences_Init(); + +void Preferences_Load(); +void Preferences_Save(); + +void Preferences_Reset(); + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/qe3.cpp b/misc/mediasource/netradiant-src/radiant/qe3.cpp new file mode 100644 index 00000000..67ffebec --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/qe3.cpp @@ -0,0 +1,386 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +/* +The following source code is licensed by Id Software and subject to the terms of +its LIMITED USE SOFTWARE LICENSE AGREEMENT, a copy of which is included with +GtkRadiant. If you did not receive a LIMITED USE SOFTWARE LICENSE AGREEMENT, +please contact Id Software immediately at info@idsoftware.com. +*/ + +// +// Linux stuff +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "qe3.h" + +#include "debugging/debugging.h" + +#include "ifilesystem.h" +//#include "imap.h" + +#include + +#include + +#include "stream/textfilestream.h" +#include "cmdlib.h" +#include "stream/stringstream.h" +#include "os/path.h" +#include "scenelib.h" + +#include "gtkutil/messagebox.h" +#include "error.h" +#include "map.h" +#include "build.h" +#include "points.h" +#include "camwindow.h" +#include "mainframe.h" +#include "preferences.h" +#include "watchbsp.h" +#include "autosave.h" +#include "convert.h" + +QEGlobals_t g_qeglobals; + + +#if defined(WIN32) +#define PATH_MAX 260 +#endif + + +void QE_InitVFS() +{ + // VFS initialization ----------------------- + // we will call GlobalFileSystem().initDirectory, giving the directories to look in (for files in pk3's and for standalone files) + // we need to call in order, the mod ones first, then the base ones .. they will be searched in this order + // *nix systems have a dual filesystem in ~/.q3a, which is searched first .. so we need to add that too + + const char* gamename = gamename_get(); + const char* basegame = basegame_get(); +#if defined(POSIX) + const char* userRoot = g_qeglobals.m_userEnginePath.c_str(); +#endif + const char* globalRoot = EnginePath_get(); + + // if we have a mod dir + if(!string_equal(gamename, basegame)) + { +#if defined(POSIX) + // ~/./ + { + StringOutputStream userGamePath(256); + userGamePath << userRoot << gamename << '/'; + GlobalFileSystem().initDirectory(userGamePath.c_str()); + } +#endif + + // / + { + StringOutputStream globalGamePath(256); + globalGamePath << globalRoot << gamename << '/'; + GlobalFileSystem().initDirectory(globalGamePath.c_str()); + } + } + +#if defined(POSIX) + // ~/./ + { + StringOutputStream userBasePath(256); + userBasePath << userRoot << basegame << '/'; + GlobalFileSystem().initDirectory(userBasePath.c_str()); + } +#endif + + // / + { + StringOutputStream globalBasePath(256); + globalBasePath << globalRoot << basegame << '/'; + GlobalFileSystem().initDirectory(globalBasePath.c_str()); + } +} + +int g_numbrushes = 0; +int g_numentities = 0; + +void QE_UpdateStatusBar() +{ + char buffer[128]; + sprintf(buffer, "Brushes: %d Entities: %d", g_numbrushes, g_numentities); + g_pParentWnd->SetStatusText(g_pParentWnd->m_brushcount_status, buffer); +} + +SimpleCounter g_brushCount; + +void QE_brushCountChanged() +{ + g_numbrushes = int(g_brushCount.get()); + QE_UpdateStatusBar(); +} + +SimpleCounter g_entityCount; + +void QE_entityCountChanged() +{ + g_numentities = int(g_entityCount.get()); + QE_UpdateStatusBar(); +} + +bool ConfirmModified(const char* title) +{ + if (!Map_Modified(g_map)) + return true; + + EMessageBoxReturn result = gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "The current map has changed since it was last saved.\nDo you want to save the current map before continuing?", title, eMB_YESNOCANCEL, eMB_ICONQUESTION); + if(result == eIDCANCEL) + { + return false; + } + if(result == eIDYES) + { + if(Map_Unnamed(g_map)) + { + return Map_SaveAs(); + } + else + { + return Map_Save(); + } + } + return true; +} + +void bsp_init() +{ + build_set_variable("RadiantPath", AppPath_get()); + build_set_variable("ExecutableType", RADIANT_EXECUTABLE); + build_set_variable("EnginePath", EnginePath_get()); + build_set_variable("MonitorAddress", (g_WatchBSP_Enabled) ? "127.0.0.1:39000" : ""); + build_set_variable("GameName", gamename_get()); + + const char* mapname = Map_Name(g_map); + StringOutputStream name(256); + name << StringRange(mapname, path_get_filename_base_end(mapname)) << ".bsp"; + + build_set_variable("MapFile", mapname); + build_set_variable("BspFile", name.c_str()); +} + +void bsp_shutdown() +{ + build_clear_variables(); +} + +class ArrayCommandListener : public CommandListener +{ + GPtrArray* m_array; +public: + ArrayCommandListener() + { + m_array = g_ptr_array_new(); + } + ~ArrayCommandListener() + { + g_ptr_array_free(m_array, TRUE); + } + + void execute(const char* command) + { + g_ptr_array_add(m_array, g_strdup(command)); + } + + GPtrArray* array() const + { + return m_array; + } +}; + +class BatchCommandListener : public CommandListener +{ + TextOutputStream& m_file; + std::size_t m_commandCount; + const char* m_outputRedirect; +public: + BatchCommandListener(TextOutputStream& file, const char* outputRedirect) : m_file(file), m_commandCount(0), m_outputRedirect(outputRedirect) + { + } + + void execute(const char* command) + { + m_file << command; + if (m_commandCount == 0) + { + m_file << " > "; + } + else + { + m_file << " >> "; + } + m_file << "\"" << m_outputRedirect << "\""; + m_file << "\n"; + ++m_commandCount; + } +}; + +bool Region_cameraValid() +{ + Vector3 vOrig(vector3_snapped(Camera_getOrigin(*g_pParentWnd->GetCamWnd()))); + + for (int i=0 ; i<3 ; i++) + { + if (vOrig[i] > region_maxs[i] || vOrig[i] < region_mins[i]) + { + return false; + } + } + return true; +} + + +void RunBSP(const char* name) +{ + // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=503 + // make sure we don't attempt to region compile a map with the camera outside the region + if (region_active && !Region_cameraValid()) + { + globalErrorStream() << "The camera must be in the region to start a region compile.\n"; + return; + } + + SaveMap(); + + if(Map_Unnamed(g_map)) + { + globalOutputStream() << "build cancelled\n"; + return; + } + + if (g_SnapShots_Enabled && !Map_Unnamed(g_map) && Map_Modified(g_map)) + { + Map_Snapshot(); + } + + if (region_active) + { + const char* mapname = Map_Name(g_map); + StringOutputStream name(256); + name << StringRange(mapname, path_get_filename_base_end(mapname)) << ".reg"; + Map_SaveRegion(name.c_str()); + } + + Pointfile_Delete(); + + bsp_init(); + + if (g_WatchBSP_Enabled) + { + ArrayCommandListener listener; + build_run(name, listener); + // grab the file name for engine running + const char* fullname = Map_Name(g_map); + StringOutputStream bspname(64); + bspname << StringRange(path_get_filename_start(fullname), path_get_filename_base_end(fullname)); + BuildMonitor_Run( listener.array(), bspname.c_str() ); + } + else + { + char junkpath[PATH_MAX]; + strcpy(junkpath, SettingsPath_get()); + strcat(junkpath, "junk.txt"); + + char batpath[PATH_MAX]; +#if defined(POSIX) + strcpy(batpath, SettingsPath_get()); + strcat(batpath, "qe3bsp.sh"); +#elif defined(WIN32) + strcpy(batpath, SettingsPath_get()); + strcat(batpath, "qe3bsp.bat"); +#else +#error "unsupported platform" +#endif + bool written = false; + { + TextFileOutputStream batchFile(batpath); + if(!batchFile.failed()) + { +#if defined (POSIX) + batchFile << "#!/bin/sh \n\n"; +#endif + BatchCommandListener listener(batchFile, junkpath); + build_run(name, listener); + written = true; + } + } + if(written) + { +#if defined (POSIX) + chmod (batpath, 0744); +#endif + globalOutputStream() << "Writing the compile script to '" << batpath << "'\n"; + globalOutputStream() << "The build output will be saved in '" << junkpath << "'\n"; + Q_Exec(batpath, NULL, NULL, true, false); + } + } + + bsp_shutdown(); +} + +// ============================================================================= +// Sys_ functions + +void Sys_SetTitle(const char *text, bool modified) +{ + StringOutputStream title; + title << text; + + if(modified) + { + title << " *"; + } + + gtk_window_set_title(MainFrame_getWindow(), title.c_str()); +} + +bool g_bWaitCursor = false; + +void Sys_BeginWait (void) +{ + ScreenUpdates_Disable("Processing...", "Please Wait"); + GdkCursor *cursor = gdk_cursor_new (GDK_WATCH); + gdk_window_set_cursor(GTK_WIDGET(MainFrame_getWindow())->window, cursor); + gdk_cursor_unref (cursor); + g_bWaitCursor = true; +} + +void Sys_EndWait (void) +{ + ScreenUpdates_Enable(); + gdk_window_set_cursor(GTK_WIDGET(MainFrame_getWindow())->window, 0); + g_bWaitCursor = false; +} + +void Sys_Beep (void) +{ + gdk_beep(); +} + diff --git a/misc/mediasource/netradiant-src/radiant/qe3.h b/misc/mediasource/netradiant-src/radiant/qe3.h new file mode 100644 index 00000000..b07223a0 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/qe3.h @@ -0,0 +1,66 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_QE3_H) +#define INCLUDED_QE3_H + +#include "string/string.h" + +// +// system functions +// +void Sys_SetTitle (const char *text, bool modified); + + +void RunBSP(const char* name); + + +void QE_InitVFS(); + +void QE_brushCountChanged(); +void QE_entityCountChanged(); + +bool ConfirmModified(const char* title); + + +// most of the QE globals are stored in this structure +typedef struct +{ + /*! + win32: engine full path. + unix: user home full path + engine dir. + */ + CopiedString m_userEnginePath; + /*! + cache for m_userEnginePath + mod subdirectory. + */ + CopiedString m_userGamePath; + +} QEGlobals_t; + +extern QEGlobals_t g_qeglobals; + +class SimpleCounter; +extern SimpleCounter g_brushCount; +extern SimpleCounter g_entityCount; + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/qgl.cpp b/misc/mediasource/netradiant-src/radiant/qgl.cpp new file mode 100644 index 00000000..335cb46b --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/qgl.cpp @@ -0,0 +1,1542 @@ +/* +Copyright (C) 1999-2006 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 "qgl.h" + +#include "debugging/debugging.h" + +#include +#include +#include + +#if defined(_WIN32) +#define WINGDIAPI __declspec(dllimport) +#define APIENTRY __stdcall +#endif + +#include + +#if defined(_WIN32) +#undef WINGDIAPI +#undef APIENTRY +#endif + +#include "igl.h" + + + + +#if defined(_WIN32) + +#include + +PROC ( WINAPI * qwglGetProcAddress)(LPCSTR); + +#elif defined (XWINDOWS) + +#include +#include +#include + +Bool (*qglXQueryExtension)( Display *dpy, int *errorb, int *event ); +void* (*qglXGetProcAddressARB) (const GLubyte *procName); +typedef void* (*glXGetProcAddressARBProc) (const GLubyte *procName); + +#else +#error "unsupported platform" +#endif + + +void QGL_Shutdown(OpenGLBinding& table) +{ + globalOutputStream() << "Shutting down OpenGL module..."; + +#if defined(WIN32) + qwglGetProcAddress = 0; +#elif defined(XWINDOWS) + qglXQueryExtension = glXQueryExtension; + qglXGetProcAddressARB = 0; +#else +#error "unsupported platform" +#endif + + globalOutputStream() << "Done.\n"; +} + + +typedef struct glu_error_struct +{ + GLenum errnum; + const char *errstr; +} GLU_ERROR_STRUCT; + +GLU_ERROR_STRUCT glu_errlist[] = { + {GL_NO_ERROR, "GL_NO_ERROR - no error"}, + {GL_INVALID_ENUM, "GL_INVALID_ENUM - An unacceptable value is specified for an enumerated argument."}, + {GL_INVALID_VALUE, "GL_INVALID_VALUE - A numeric argument is out of range."}, + {GL_INVALID_OPERATION, "GL_INVALID_OPERATION - The specified operation is not allowed in the current state."}, + {GL_STACK_OVERFLOW, "GL_STACK_OVERFLOW - Function would cause a stack overflow."}, + {GL_STACK_UNDERFLOW, "GL_STACK_UNDERFLOW - Function would cause a stack underflow."}, + {GL_OUT_OF_MEMORY, "GL_OUT_OF_MEMORY - There is not enough memory left to execute the function."}, + {0, 0} +}; + +const GLubyte* qgluErrorString(GLenum errCode ) +{ + int search = 0; + for (search = 0; glu_errlist[search].errstr; search++) + { + if (errCode == glu_errlist[search].errnum) + return (const GLubyte *)glu_errlist[search].errstr; + } //end for + return (const GLubyte *)"Unknown error"; +} + + +void glInvalidFunction() +{ + ERROR_MESSAGE("calling an invalid OpenGL function"); +} + +#define EXTENSIONS_ENABLED 1 + +bool QGL_ExtensionSupported(const char* extension) +{ +#if EXTENSIONS_ENABLED + const GLubyte *extensions = 0; + const GLubyte *start; + GLubyte *where, *terminator; + + // Extension names should not have spaces. + where = (GLubyte *) strchr (extension, ' '); + if (where || *extension == '\0') + return false; + + extensions = GlobalOpenGL().m_glGetString (GL_EXTENSIONS); +#ifndef __APPLE__ + if (!extensions) + return false; +#endif + + // It takes a bit of care to be fool-proof about parsing the + // OpenGL extensions string. Don't be fooled by sub-strings, etc. + for (start = extensions; ;) + { + where = (GLubyte *) strstr ((const char *) start, extension); + if (!where) + break; + + terminator = where + strlen (extension); + if (where == start || *(where - 1) == ' ') + if (*terminator == ' ' || *terminator == '\0') + return true; + + start = terminator; + } +#endif + + return false; +} + +typedef int (QGL_DLLEXPORT *QGLFunctionPointer)(); + +QGLFunctionPointer QGL_getExtensionFunc(const char* symbol) +{ +#if defined(XWINDOWS) + //ASSERT_NOTNULL(qglXGetProcAddressARB); + if (qglXGetProcAddressARB == 0) + { + return reinterpret_cast(glInvalidFunction); + } + else + { + return (QGLFunctionPointer)qglXGetProcAddressARB(reinterpret_cast(symbol)); + } +#elif defined(WIN32) + ASSERT_NOTNULL(qwglGetProcAddress); + return qwglGetProcAddress(symbol); +#else +#error "unsupported platform" +#endif +} + + +template +bool QGL_constructExtensionFunc(Func& func, const char* symbol) +{ + func = reinterpret_cast(QGL_getExtensionFunc(symbol)); + return func != 0; +} + +template +void QGL_invalidateExtensionFunc(Func& func) +{ + func = reinterpret_cast(glInvalidFunction); +} + +void QGL_clear(OpenGLBinding& table) +{ + QGL_invalidateExtensionFunc(table.m_glAccum); + QGL_invalidateExtensionFunc(table.m_glAlphaFunc); + QGL_invalidateExtensionFunc(table.m_glAreTexturesResident); + QGL_invalidateExtensionFunc(table.m_glArrayElement); + QGL_invalidateExtensionFunc(table.m_glBegin); + QGL_invalidateExtensionFunc(table.m_glBindTexture); + QGL_invalidateExtensionFunc(table.m_glBitmap); + QGL_invalidateExtensionFunc(table.m_glBlendFunc); + QGL_invalidateExtensionFunc(table.m_glCallList); + QGL_invalidateExtensionFunc(table.m_glCallLists); + QGL_invalidateExtensionFunc(table.m_glClear); + QGL_invalidateExtensionFunc(table.m_glClearAccum); + QGL_invalidateExtensionFunc(table.m_glClearColor); + QGL_invalidateExtensionFunc(table.m_glClearDepth); + QGL_invalidateExtensionFunc(table.m_glClearIndex); + QGL_invalidateExtensionFunc(table.m_glClearStencil); + QGL_invalidateExtensionFunc(table.m_glClipPlane); + QGL_invalidateExtensionFunc(table.m_glColor3b); + QGL_invalidateExtensionFunc(table.m_glColor3bv); + QGL_invalidateExtensionFunc(table.m_glColor3d); + QGL_invalidateExtensionFunc(table.m_glColor3dv); + QGL_invalidateExtensionFunc(table.m_glColor3f); + QGL_invalidateExtensionFunc(table.m_glColor3fv); + QGL_invalidateExtensionFunc(table.m_glColor3i); + QGL_invalidateExtensionFunc(table.m_glColor3iv); + QGL_invalidateExtensionFunc(table.m_glColor3s); + QGL_invalidateExtensionFunc(table.m_glColor3sv); + QGL_invalidateExtensionFunc(table.m_glColor3ub); + QGL_invalidateExtensionFunc(table.m_glColor3ubv); + QGL_invalidateExtensionFunc(table.m_glColor3ui); + QGL_invalidateExtensionFunc(table.m_glColor3uiv); + QGL_invalidateExtensionFunc(table.m_glColor3us); + QGL_invalidateExtensionFunc(table.m_glColor3usv); + QGL_invalidateExtensionFunc(table.m_glColor4b); + QGL_invalidateExtensionFunc(table.m_glColor4bv); + QGL_invalidateExtensionFunc(table.m_glColor4d); + QGL_invalidateExtensionFunc(table.m_glColor4dv); + QGL_invalidateExtensionFunc(table.m_glColor4f); + QGL_invalidateExtensionFunc(table.m_glColor4fv); + QGL_invalidateExtensionFunc(table.m_glColor4i); + QGL_invalidateExtensionFunc(table.m_glColor4iv); + QGL_invalidateExtensionFunc(table.m_glColor4s); + QGL_invalidateExtensionFunc(table.m_glColor4sv); + QGL_invalidateExtensionFunc(table.m_glColor4ub); + QGL_invalidateExtensionFunc(table.m_glColor4ubv); + QGL_invalidateExtensionFunc(table.m_glColor4ui); + QGL_invalidateExtensionFunc(table.m_glColor4uiv); + QGL_invalidateExtensionFunc(table.m_glColor4us); + QGL_invalidateExtensionFunc(table.m_glColor4usv); + QGL_invalidateExtensionFunc(table.m_glColorMask); + QGL_invalidateExtensionFunc(table.m_glColorMaterial); + QGL_invalidateExtensionFunc(table.m_glColorPointer); + QGL_invalidateExtensionFunc(table.m_glCopyPixels); + QGL_invalidateExtensionFunc(table.m_glCopyTexImage1D); + QGL_invalidateExtensionFunc(table.m_glCopyTexImage2D); + QGL_invalidateExtensionFunc(table.m_glCopyTexSubImage1D); + QGL_invalidateExtensionFunc(table.m_glCopyTexSubImage2D); + QGL_invalidateExtensionFunc(table.m_glCullFace); + QGL_invalidateExtensionFunc(table.m_glDeleteLists); + QGL_invalidateExtensionFunc(table.m_glDeleteTextures); + QGL_invalidateExtensionFunc(table.m_glDepthFunc); + QGL_invalidateExtensionFunc(table.m_glDepthMask); + QGL_invalidateExtensionFunc(table.m_glDepthRange); + QGL_invalidateExtensionFunc(table.m_glDisable); + QGL_invalidateExtensionFunc(table.m_glDisableClientState); + QGL_invalidateExtensionFunc(table.m_glDrawArrays); + QGL_invalidateExtensionFunc(table.m_glDrawBuffer); + QGL_invalidateExtensionFunc(table.m_glDrawElements); + QGL_invalidateExtensionFunc(table.m_glDrawPixels); + QGL_invalidateExtensionFunc(table.m_glEdgeFlag); + QGL_invalidateExtensionFunc(table.m_glEdgeFlagPointer); + QGL_invalidateExtensionFunc(table.m_glEdgeFlagv); + QGL_invalidateExtensionFunc(table.m_glEnable); + QGL_invalidateExtensionFunc(table.m_glEnableClientState); + QGL_invalidateExtensionFunc(table.m_glEnd); + QGL_invalidateExtensionFunc(table.m_glEndList); + QGL_invalidateExtensionFunc(table.m_glEvalCoord1d); + QGL_invalidateExtensionFunc(table.m_glEvalCoord1dv); + QGL_invalidateExtensionFunc(table.m_glEvalCoord1f); + QGL_invalidateExtensionFunc(table.m_glEvalCoord1fv); + QGL_invalidateExtensionFunc(table.m_glEvalCoord2d); + QGL_invalidateExtensionFunc(table.m_glEvalCoord2dv); + QGL_invalidateExtensionFunc(table.m_glEvalCoord2f); + QGL_invalidateExtensionFunc(table.m_glEvalCoord2fv); + QGL_invalidateExtensionFunc(table.m_glEvalMesh1); + QGL_invalidateExtensionFunc(table.m_glEvalMesh2); + QGL_invalidateExtensionFunc(table.m_glEvalPoint1); + QGL_invalidateExtensionFunc(table.m_glEvalPoint2); + QGL_invalidateExtensionFunc(table.m_glFeedbackBuffer); + QGL_invalidateExtensionFunc(table.m_glFinish); + QGL_invalidateExtensionFunc(table.m_glFlush); + QGL_invalidateExtensionFunc(table.m_glFogf); + QGL_invalidateExtensionFunc(table.m_glFogfv); + QGL_invalidateExtensionFunc(table.m_glFogi); + QGL_invalidateExtensionFunc(table.m_glFogiv); + QGL_invalidateExtensionFunc(table.m_glFrontFace); + QGL_invalidateExtensionFunc(table.m_glFrustum); + QGL_invalidateExtensionFunc(table.m_glGenLists); + QGL_invalidateExtensionFunc(table.m_glGenTextures); + QGL_invalidateExtensionFunc(table.m_glGetBooleanv); + QGL_invalidateExtensionFunc(table.m_glGetClipPlane); + QGL_invalidateExtensionFunc(table.m_glGetDoublev); + QGL_invalidateExtensionFunc(table.m_glGetError); + QGL_invalidateExtensionFunc(table.m_glGetFloatv); + QGL_invalidateExtensionFunc(table.m_glGetIntegerv); + QGL_invalidateExtensionFunc(table.m_glGetLightfv); + QGL_invalidateExtensionFunc(table.m_glGetLightiv); + QGL_invalidateExtensionFunc(table.m_glGetMapdv); + QGL_invalidateExtensionFunc(table.m_glGetMapfv); + QGL_invalidateExtensionFunc(table.m_glGetMapiv); + QGL_invalidateExtensionFunc(table.m_glGetMaterialfv); + QGL_invalidateExtensionFunc(table.m_glGetMaterialiv); + QGL_invalidateExtensionFunc(table.m_glGetPixelMapfv); + QGL_invalidateExtensionFunc(table.m_glGetPixelMapuiv); + QGL_invalidateExtensionFunc(table.m_glGetPixelMapusv); + QGL_invalidateExtensionFunc(table.m_glGetPointerv); + QGL_invalidateExtensionFunc(table.m_glGetPolygonStipple); + table.m_glGetString = glGetString; + QGL_invalidateExtensionFunc(table.m_glGetTexEnvfv); + QGL_invalidateExtensionFunc(table.m_glGetTexEnviv); + QGL_invalidateExtensionFunc(table.m_glGetTexGendv); + QGL_invalidateExtensionFunc(table.m_glGetTexGenfv); + QGL_invalidateExtensionFunc(table.m_glGetTexGeniv); + QGL_invalidateExtensionFunc(table.m_glGetTexImage); + QGL_invalidateExtensionFunc(table.m_glGetTexLevelParameterfv); + QGL_invalidateExtensionFunc(table.m_glGetTexLevelParameteriv); + QGL_invalidateExtensionFunc(table.m_glGetTexParameterfv); + QGL_invalidateExtensionFunc(table.m_glGetTexParameteriv); + QGL_invalidateExtensionFunc(table.m_glHint); + QGL_invalidateExtensionFunc(table.m_glIndexMask); + QGL_invalidateExtensionFunc(table.m_glIndexPointer); + QGL_invalidateExtensionFunc(table.m_glIndexd); + QGL_invalidateExtensionFunc(table.m_glIndexdv); + QGL_invalidateExtensionFunc(table.m_glIndexf); + QGL_invalidateExtensionFunc(table.m_glIndexfv); + QGL_invalidateExtensionFunc(table.m_glIndexi); + QGL_invalidateExtensionFunc(table.m_glIndexiv); + QGL_invalidateExtensionFunc(table.m_glIndexs); + QGL_invalidateExtensionFunc(table.m_glIndexsv); + QGL_invalidateExtensionFunc(table.m_glIndexub); + QGL_invalidateExtensionFunc(table.m_glIndexubv); + QGL_invalidateExtensionFunc(table.m_glInitNames); + QGL_invalidateExtensionFunc(table.m_glInterleavedArrays); + QGL_invalidateExtensionFunc(table.m_glIsEnabled); + QGL_invalidateExtensionFunc(table.m_glIsList); + QGL_invalidateExtensionFunc(table.m_glIsTexture); + QGL_invalidateExtensionFunc(table.m_glLightModelf); + QGL_invalidateExtensionFunc(table.m_glLightModelfv); + QGL_invalidateExtensionFunc(table.m_glLightModeli); + QGL_invalidateExtensionFunc(table.m_glLightModeliv); + QGL_invalidateExtensionFunc(table.m_glLightf); + QGL_invalidateExtensionFunc(table.m_glLightfv); + QGL_invalidateExtensionFunc(table.m_glLighti); + QGL_invalidateExtensionFunc(table.m_glLightiv); + QGL_invalidateExtensionFunc(table.m_glLineStipple); + QGL_invalidateExtensionFunc(table.m_glLineWidth); + QGL_invalidateExtensionFunc(table.m_glListBase); + QGL_invalidateExtensionFunc(table.m_glLoadIdentity); + QGL_invalidateExtensionFunc(table.m_glLoadMatrixd); + QGL_invalidateExtensionFunc(table.m_glLoadMatrixf); + QGL_invalidateExtensionFunc(table.m_glLoadName); + QGL_invalidateExtensionFunc(table.m_glLogicOp); + QGL_invalidateExtensionFunc(table.m_glMap1d); + QGL_invalidateExtensionFunc(table.m_glMap1f); + QGL_invalidateExtensionFunc(table.m_glMap2d); + QGL_invalidateExtensionFunc(table.m_glMap2f); + QGL_invalidateExtensionFunc(table.m_glMapGrid1d); + QGL_invalidateExtensionFunc(table.m_glMapGrid1f); + QGL_invalidateExtensionFunc(table.m_glMapGrid2d); + QGL_invalidateExtensionFunc(table.m_glMapGrid2f); + QGL_invalidateExtensionFunc(table.m_glMaterialf); + QGL_invalidateExtensionFunc(table.m_glMaterialfv); + QGL_invalidateExtensionFunc(table.m_glMateriali); + QGL_invalidateExtensionFunc(table.m_glMaterialiv); + QGL_invalidateExtensionFunc(table.m_glMatrixMode); + QGL_invalidateExtensionFunc(table.m_glMultMatrixd); + QGL_invalidateExtensionFunc(table.m_glMultMatrixf); + QGL_invalidateExtensionFunc(table.m_glNewList); + QGL_invalidateExtensionFunc(table.m_glNormal3b); + QGL_invalidateExtensionFunc(table.m_glNormal3bv); + QGL_invalidateExtensionFunc(table.m_glNormal3d); + QGL_invalidateExtensionFunc(table.m_glNormal3dv); + QGL_invalidateExtensionFunc(table.m_glNormal3f); + QGL_invalidateExtensionFunc(table.m_glNormal3fv); + QGL_invalidateExtensionFunc(table.m_glNormal3i); + QGL_invalidateExtensionFunc(table.m_glNormal3iv); + QGL_invalidateExtensionFunc(table.m_glNormal3s); + QGL_invalidateExtensionFunc(table.m_glNormal3sv); + QGL_invalidateExtensionFunc(table.m_glNormalPointer); + QGL_invalidateExtensionFunc(table.m_glOrtho); + QGL_invalidateExtensionFunc(table.m_glPassThrough); + QGL_invalidateExtensionFunc(table.m_glPixelMapfv); + QGL_invalidateExtensionFunc(table.m_glPixelMapuiv); + QGL_invalidateExtensionFunc(table.m_glPixelMapusv); + QGL_invalidateExtensionFunc(table.m_glPixelStoref); + QGL_invalidateExtensionFunc(table.m_glPixelStorei); + QGL_invalidateExtensionFunc(table.m_glPixelTransferf); + QGL_invalidateExtensionFunc(table.m_glPixelTransferi); + QGL_invalidateExtensionFunc(table.m_glPixelZoom); + QGL_invalidateExtensionFunc(table.m_glPointSize); + QGL_invalidateExtensionFunc(table.m_glPolygonMode); + QGL_invalidateExtensionFunc(table.m_glPolygonOffset); + QGL_invalidateExtensionFunc(table.m_glPolygonStipple); + QGL_invalidateExtensionFunc(table.m_glPopAttrib); + QGL_invalidateExtensionFunc(table.m_glPopClientAttrib); + QGL_invalidateExtensionFunc(table.m_glPopMatrix); + QGL_invalidateExtensionFunc(table.m_glPopName); + QGL_invalidateExtensionFunc(table.m_glPrioritizeTextures); + QGL_invalidateExtensionFunc(table.m_glPushAttrib); + QGL_invalidateExtensionFunc(table.m_glPushClientAttrib); + QGL_invalidateExtensionFunc(table.m_glPushMatrix); + QGL_invalidateExtensionFunc(table.m_glPushName); + QGL_invalidateExtensionFunc(table.m_glRasterPos2d); + QGL_invalidateExtensionFunc(table.m_glRasterPos2dv); + QGL_invalidateExtensionFunc(table.m_glRasterPos2f); + QGL_invalidateExtensionFunc(table.m_glRasterPos2fv); + QGL_invalidateExtensionFunc(table.m_glRasterPos2i); + QGL_invalidateExtensionFunc(table.m_glRasterPos2iv); + QGL_invalidateExtensionFunc(table.m_glRasterPos2s); + QGL_invalidateExtensionFunc(table.m_glRasterPos2sv); + QGL_invalidateExtensionFunc(table.m_glRasterPos3d); + QGL_invalidateExtensionFunc(table.m_glRasterPos3dv); + QGL_invalidateExtensionFunc(table.m_glRasterPos3f); + QGL_invalidateExtensionFunc(table.m_glRasterPos3fv); + QGL_invalidateExtensionFunc(table.m_glRasterPos3i); + QGL_invalidateExtensionFunc(table.m_glRasterPos3iv); + QGL_invalidateExtensionFunc(table.m_glRasterPos3s); + QGL_invalidateExtensionFunc(table.m_glRasterPos3sv); + QGL_invalidateExtensionFunc(table.m_glRasterPos4d); + QGL_invalidateExtensionFunc(table.m_glRasterPos4dv); + QGL_invalidateExtensionFunc(table.m_glRasterPos4f); + QGL_invalidateExtensionFunc(table.m_glRasterPos4fv); + QGL_invalidateExtensionFunc(table.m_glRasterPos4i); + QGL_invalidateExtensionFunc(table.m_glRasterPos4iv); + QGL_invalidateExtensionFunc(table.m_glRasterPos4s); + QGL_invalidateExtensionFunc(table.m_glRasterPos4sv); + QGL_invalidateExtensionFunc(table.m_glReadBuffer); + QGL_invalidateExtensionFunc(table.m_glReadPixels); + QGL_invalidateExtensionFunc(table.m_glRectd); + QGL_invalidateExtensionFunc(table.m_glRectdv); + QGL_invalidateExtensionFunc(table.m_glRectf); + QGL_invalidateExtensionFunc(table.m_glRectfv); + QGL_invalidateExtensionFunc(table.m_glRecti); + QGL_invalidateExtensionFunc(table.m_glRectiv); + QGL_invalidateExtensionFunc(table.m_glRects); + QGL_invalidateExtensionFunc(table.m_glRectsv); + QGL_invalidateExtensionFunc(table.m_glRenderMode); + QGL_invalidateExtensionFunc(table.m_glRotated); + QGL_invalidateExtensionFunc(table.m_glRotatef); + QGL_invalidateExtensionFunc(table.m_glScaled); + QGL_invalidateExtensionFunc(table.m_glScalef); + QGL_invalidateExtensionFunc(table.m_glScissor); + QGL_invalidateExtensionFunc(table.m_glSelectBuffer); + QGL_invalidateExtensionFunc(table.m_glShadeModel); + QGL_invalidateExtensionFunc(table.m_glStencilFunc); + QGL_invalidateExtensionFunc(table.m_glStencilMask); + QGL_invalidateExtensionFunc(table.m_glStencilOp); + QGL_invalidateExtensionFunc(table.m_glTexCoord1d); + QGL_invalidateExtensionFunc(table.m_glTexCoord1dv); + QGL_invalidateExtensionFunc(table.m_glTexCoord1f); + QGL_invalidateExtensionFunc(table.m_glTexCoord1fv); + QGL_invalidateExtensionFunc(table.m_glTexCoord1i); + QGL_invalidateExtensionFunc(table.m_glTexCoord1iv); + QGL_invalidateExtensionFunc(table.m_glTexCoord1s); + QGL_invalidateExtensionFunc(table.m_glTexCoord1sv); + QGL_invalidateExtensionFunc(table.m_glTexCoord2d); + QGL_invalidateExtensionFunc(table.m_glTexCoord2dv); + QGL_invalidateExtensionFunc(table.m_glTexCoord2f); + QGL_invalidateExtensionFunc(table.m_glTexCoord2fv); + QGL_invalidateExtensionFunc(table.m_glTexCoord2i); + QGL_invalidateExtensionFunc(table.m_glTexCoord2iv); + QGL_invalidateExtensionFunc(table.m_glTexCoord2s); + QGL_invalidateExtensionFunc(table.m_glTexCoord2sv); + QGL_invalidateExtensionFunc(table.m_glTexCoord3d); + QGL_invalidateExtensionFunc(table.m_glTexCoord3dv); + QGL_invalidateExtensionFunc(table.m_glTexCoord3f); + QGL_invalidateExtensionFunc(table.m_glTexCoord3fv); + QGL_invalidateExtensionFunc(table.m_glTexCoord3i); + QGL_invalidateExtensionFunc(table.m_glTexCoord3iv); + QGL_invalidateExtensionFunc(table.m_glTexCoord3s); + QGL_invalidateExtensionFunc(table.m_glTexCoord3sv); + QGL_invalidateExtensionFunc(table.m_glTexCoord4d); + QGL_invalidateExtensionFunc(table.m_glTexCoord4dv); + QGL_invalidateExtensionFunc(table.m_glTexCoord4f); + QGL_invalidateExtensionFunc(table.m_glTexCoord4fv); + QGL_invalidateExtensionFunc(table.m_glTexCoord4i); + QGL_invalidateExtensionFunc(table.m_glTexCoord4iv); + QGL_invalidateExtensionFunc(table.m_glTexCoord4s); + QGL_invalidateExtensionFunc(table.m_glTexCoord4sv); + QGL_invalidateExtensionFunc(table.m_glTexCoordPointer); + QGL_invalidateExtensionFunc(table.m_glTexEnvf); + QGL_invalidateExtensionFunc(table.m_glTexEnvfv); + QGL_invalidateExtensionFunc(table.m_glTexEnvi); + QGL_invalidateExtensionFunc(table.m_glTexEnviv); + QGL_invalidateExtensionFunc(table.m_glTexGend); + QGL_invalidateExtensionFunc(table.m_glTexGendv); + QGL_invalidateExtensionFunc(table.m_glTexGenf); + QGL_invalidateExtensionFunc(table.m_glTexGenfv); + QGL_invalidateExtensionFunc(table.m_glTexGeni); + QGL_invalidateExtensionFunc(table.m_glTexGeniv); + QGL_invalidateExtensionFunc(table.m_glTexImage1D); + QGL_invalidateExtensionFunc(table.m_glTexImage2D); + QGL_invalidateExtensionFunc(table.m_glTexParameterf); + QGL_invalidateExtensionFunc(table.m_glTexParameterfv); + QGL_invalidateExtensionFunc(table.m_glTexParameteri); + QGL_invalidateExtensionFunc(table.m_glTexParameteriv); + QGL_invalidateExtensionFunc(table.m_glTexSubImage1D); + QGL_invalidateExtensionFunc(table.m_glTexSubImage2D); + QGL_invalidateExtensionFunc(table.m_glTranslated); + QGL_invalidateExtensionFunc(table.m_glTranslatef); + QGL_invalidateExtensionFunc(table.m_glVertex2d); + QGL_invalidateExtensionFunc(table.m_glVertex2dv); + QGL_invalidateExtensionFunc(table.m_glVertex2f); + QGL_invalidateExtensionFunc(table.m_glVertex2fv); + QGL_invalidateExtensionFunc(table.m_glVertex2i); + QGL_invalidateExtensionFunc(table.m_glVertex2iv); + QGL_invalidateExtensionFunc(table.m_glVertex2s); + QGL_invalidateExtensionFunc(table.m_glVertex2sv); + QGL_invalidateExtensionFunc(table.m_glVertex3d); + QGL_invalidateExtensionFunc(table.m_glVertex3dv); + QGL_invalidateExtensionFunc(table.m_glVertex3f); + QGL_invalidateExtensionFunc(table.m_glVertex3fv); + QGL_invalidateExtensionFunc(table.m_glVertex3i); + QGL_invalidateExtensionFunc(table.m_glVertex3iv); + QGL_invalidateExtensionFunc(table.m_glVertex3s); + QGL_invalidateExtensionFunc(table.m_glVertex3sv); + QGL_invalidateExtensionFunc(table.m_glVertex4d); + QGL_invalidateExtensionFunc(table.m_glVertex4dv); + QGL_invalidateExtensionFunc(table.m_glVertex4f); + QGL_invalidateExtensionFunc(table.m_glVertex4fv); + QGL_invalidateExtensionFunc(table.m_glVertex4i); + QGL_invalidateExtensionFunc(table.m_glVertex4iv); + QGL_invalidateExtensionFunc(table.m_glVertex4s); + QGL_invalidateExtensionFunc(table.m_glVertex4sv); + QGL_invalidateExtensionFunc(table.m_glVertexPointer); + QGL_invalidateExtensionFunc(table.m_glViewport); +} + +int QGL_Init(OpenGLBinding& table) +{ + QGL_clear(table); + +#if defined(WIN32) + qwglGetProcAddress = wglGetProcAddress; +#elif defined(XWINDOWS) + qglXGetProcAddressARB = (glXGetProcAddressARBProc)dlsym(RTLD_DEFAULT, "glXGetProcAddressARB"); + if ((qglXQueryExtension == 0) || (qglXQueryExtension(GDK_DISPLAY(),0,0) != True)) + return 0; +#else +#error "unsupported platform" +#endif + + return 1; +} + +int g_qglMajorVersion = 0; +int g_qglMinorVersion = 0; + +// requires a valid gl context +void QGL_InitVersion() +{ +#if EXTENSIONS_ENABLED + const std::size_t versionSize = 256; + char version[versionSize]; + strncpy(version, reinterpret_cast(GlobalOpenGL().m_glGetString(GL_VERSION)), versionSize - 1); + version[versionSize - 1] = '\0'; + char* firstDot = strchr(version, '.'); + ASSERT_NOTNULL(firstDot); + *firstDot = '\0'; + g_qglMajorVersion = atoi(version); + char* secondDot = strchr(firstDot + 1, '.'); + if(secondDot != 0) + { + *secondDot = '\0'; + } + g_qglMinorVersion = atoi(firstDot + 1); +#else + g_qglMajorVersion = 1; + g_qglMinorVersion = 1; +#endif +} + + +inline void extension_not_implemented(const char* extension) +{ + globalErrorStream() << "WARNING: OpenGL driver reports support for " << extension << " but does not implement it\n"; +} + +float g_maxTextureAnisotropy; + +float QGL_maxTextureAnisotropy() +{ + return g_maxTextureAnisotropy; +} + +void QGL_sharedContextCreated(OpenGLBinding& table) +{ + QGL_InitVersion(); + + table.major_version = g_qglMajorVersion; + table.minor_version = g_qglMinorVersion; + + table.m_glAccum = glAccum; + table.m_glAlphaFunc = glAlphaFunc; + table.m_glAreTexturesResident = glAreTexturesResident; + table.m_glArrayElement = glArrayElement; + table.m_glBegin = glBegin; + table.m_glBindTexture = glBindTexture; + table.m_glBitmap = glBitmap; + table.m_glBlendFunc = glBlendFunc; + table.m_glCallList = glCallList; + table.m_glCallLists = glCallLists; + table.m_glClear = glClear; + table.m_glClearAccum = glClearAccum; + table.m_glClearColor = glClearColor; + table.m_glClearDepth = glClearDepth; + table.m_glClearIndex = glClearIndex; + table.m_glClearStencil = glClearStencil; + table.m_glClipPlane = glClipPlane; + table.m_glColor3b = glColor3b; + table.m_glColor3bv = glColor3bv; + table.m_glColor3d = glColor3d; + table.m_glColor3dv = glColor3dv; + table.m_glColor3f = glColor3f; + table.m_glColor3fv = glColor3fv; + table.m_glColor3i = glColor3i; + table.m_glColor3iv = glColor3iv; + table.m_glColor3s = glColor3s; + table.m_glColor3sv = glColor3sv; + table.m_glColor3ub = glColor3ub; + table.m_glColor3ubv = glColor3ubv; + table.m_glColor3ui = glColor3ui; + table.m_glColor3uiv = glColor3uiv; + table.m_glColor3us = glColor3us; + table.m_glColor3usv = glColor3usv; + table.m_glColor4b = glColor4b; + table.m_glColor4bv = glColor4bv; + table.m_glColor4d = glColor4d; + table.m_glColor4dv = glColor4dv; + table.m_glColor4f = glColor4f; + table.m_glColor4fv = glColor4fv; + table.m_glColor4i = glColor4i; + table.m_glColor4iv = glColor4iv; + table.m_glColor4s = glColor4s; + table.m_glColor4sv = glColor4sv; + table.m_glColor4ub = glColor4ub; + table.m_glColor4ubv = glColor4ubv; + table.m_glColor4ui = glColor4ui; + table.m_glColor4uiv = glColor4uiv; + table.m_glColor4us = glColor4us; + table.m_glColor4usv = glColor4usv; + table.m_glColorMask = glColorMask; + table.m_glColorMaterial = glColorMaterial; + table.m_glColorPointer = glColorPointer; + table.m_glCopyPixels = glCopyPixels; + table.m_glCopyTexImage1D = glCopyTexImage1D; + table.m_glCopyTexImage2D = glCopyTexImage2D; + table.m_glCopyTexSubImage1D = glCopyTexSubImage1D; + table.m_glCopyTexSubImage2D = glCopyTexSubImage2D; + table.m_glCullFace = glCullFace; + table.m_glDeleteLists = glDeleteLists; + table.m_glDeleteTextures = glDeleteTextures; + table.m_glDepthFunc = glDepthFunc; + table.m_glDepthMask = glDepthMask; + table.m_glDepthRange = glDepthRange; + table.m_glDisable = glDisable; + table.m_glDisableClientState = glDisableClientState; + table.m_glDrawArrays = glDrawArrays; + table.m_glDrawBuffer = glDrawBuffer; + table.m_glDrawElements = glDrawElements; + table.m_glDrawPixels = glDrawPixels; + table.m_glEdgeFlag = glEdgeFlag; + table.m_glEdgeFlagPointer = glEdgeFlagPointer; + table.m_glEdgeFlagv = glEdgeFlagv; + table.m_glEnable = glEnable; + table.m_glEnableClientState = glEnableClientState; + table.m_glEnd = glEnd; + table.m_glEndList = glEndList; + table.m_glEvalCoord1d = glEvalCoord1d; + table.m_glEvalCoord1dv = glEvalCoord1dv; + table.m_glEvalCoord1f = glEvalCoord1f; + table.m_glEvalCoord1fv = glEvalCoord1fv; + table.m_glEvalCoord2d = glEvalCoord2d; + table.m_glEvalCoord2dv = glEvalCoord2dv; + table.m_glEvalCoord2f = glEvalCoord2f; + table.m_glEvalCoord2fv = glEvalCoord2fv; + table.m_glEvalMesh1 = glEvalMesh1; + table.m_glEvalMesh2 = glEvalMesh2; + table.m_glEvalPoint1 = glEvalPoint1; + table.m_glEvalPoint2 = glEvalPoint2; + table.m_glFeedbackBuffer = glFeedbackBuffer; + table.m_glFinish = glFinish; + table.m_glFlush = glFlush; + table.m_glFogf = glFogf; + table.m_glFogfv = glFogfv; + table.m_glFogi = glFogi; + table.m_glFogiv = glFogiv; + table.m_glFrontFace = glFrontFace; + table.m_glFrustum = glFrustum; + table.m_glGenLists = glGenLists; + table.m_glGenTextures = glGenTextures; + table.m_glGetBooleanv = glGetBooleanv; + table.m_glGetClipPlane = glGetClipPlane; + table.m_glGetDoublev = glGetDoublev; + table.m_glGetError = glGetError; + table.m_glGetFloatv = glGetFloatv; + table.m_glGetIntegerv = glGetIntegerv; + table.m_glGetLightfv = glGetLightfv; + table.m_glGetLightiv = glGetLightiv; + table.m_glGetMapdv = glGetMapdv; + table.m_glGetMapfv = glGetMapfv; + table.m_glGetMapiv = glGetMapiv; + table.m_glGetMaterialfv = glGetMaterialfv; + table.m_glGetMaterialiv = glGetMaterialiv; + table.m_glGetPixelMapfv = glGetPixelMapfv; + table.m_glGetPixelMapuiv = glGetPixelMapuiv; + table.m_glGetPixelMapusv = glGetPixelMapusv; + table.m_glGetPointerv = glGetPointerv; + table.m_glGetPolygonStipple = glGetPolygonStipple; + table.m_glGetString = glGetString; + table.m_glGetTexEnvfv = glGetTexEnvfv; + table.m_glGetTexEnviv = glGetTexEnviv; + table.m_glGetTexGendv = glGetTexGendv; + table.m_glGetTexGenfv = glGetTexGenfv; + table.m_glGetTexGeniv = glGetTexGeniv; + table.m_glGetTexImage = glGetTexImage; + table.m_glGetTexLevelParameterfv = glGetTexLevelParameterfv; + table.m_glGetTexLevelParameteriv = glGetTexLevelParameteriv; + table.m_glGetTexParameterfv = glGetTexParameterfv; + table.m_glGetTexParameteriv = glGetTexParameteriv; + table.m_glHint = glHint; + table.m_glIndexMask = glIndexMask; + table.m_glIndexPointer = glIndexPointer; + table.m_glIndexd = glIndexd; + table.m_glIndexdv = glIndexdv; + table.m_glIndexf = glIndexf; + table.m_glIndexfv = glIndexfv; + table.m_glIndexi = glIndexi; + table.m_glIndexiv = glIndexiv; + table.m_glIndexs = glIndexs; + table.m_glIndexsv = glIndexsv; + table.m_glIndexub = glIndexub; + table.m_glIndexubv = glIndexubv; + table.m_glInitNames = glInitNames; + table.m_glInterleavedArrays = glInterleavedArrays; + table.m_glIsEnabled = glIsEnabled; + table.m_glIsList = glIsList; + table.m_glIsTexture = glIsTexture; + table.m_glLightModelf = glLightModelf; + table.m_glLightModelfv = glLightModelfv; + table.m_glLightModeli = glLightModeli; + table.m_glLightModeliv = glLightModeliv; + table.m_glLightf = glLightf; + table.m_glLightfv = glLightfv; + table.m_glLighti = glLighti; + table.m_glLightiv = glLightiv; + table.m_glLineStipple = glLineStipple; + table.m_glLineWidth = glLineWidth; + table.m_glListBase = glListBase; + table.m_glLoadIdentity = glLoadIdentity; + table.m_glLoadMatrixd = glLoadMatrixd; + table.m_glLoadMatrixf = glLoadMatrixf; + table.m_glLoadName = glLoadName; + table.m_glLogicOp = glLogicOp; + table.m_glMap1d = glMap1d; + table.m_glMap1f = glMap1f; + table.m_glMap2d = glMap2d; + table.m_glMap2f = glMap2f; + table.m_glMapGrid1d = glMapGrid1d; + table.m_glMapGrid1f = glMapGrid1f; + table.m_glMapGrid2d = glMapGrid2d; + table.m_glMapGrid2f = glMapGrid2f; + table.m_glMaterialf = glMaterialf; + table.m_glMaterialfv = glMaterialfv; + table.m_glMateriali = glMateriali; + table.m_glMaterialiv = glMaterialiv; + table.m_glMatrixMode = glMatrixMode; + table.m_glMultMatrixd = glMultMatrixd; + table.m_glMultMatrixf = glMultMatrixf; + table.m_glNewList = glNewList; + table.m_glNormal3b = glNormal3b; + table.m_glNormal3bv = glNormal3bv; + table.m_glNormal3d = glNormal3d; + table.m_glNormal3dv = glNormal3dv; + table.m_glNormal3f = glNormal3f; + table.m_glNormal3fv = glNormal3fv; + table.m_glNormal3i = glNormal3i; + table.m_glNormal3iv = glNormal3iv; + table.m_glNormal3s = glNormal3s; + table.m_glNormal3sv = glNormal3sv; + table.m_glNormalPointer = glNormalPointer; + table.m_glOrtho = glOrtho; + table.m_glPassThrough = glPassThrough; + table.m_glPixelMapfv = glPixelMapfv; + table.m_glPixelMapuiv = glPixelMapuiv; + table.m_glPixelMapusv = glPixelMapusv; + table.m_glPixelStoref = glPixelStoref; + table.m_glPixelStorei = glPixelStorei; + table.m_glPixelTransferf = glPixelTransferf; + table.m_glPixelTransferi = glPixelTransferi; + table.m_glPixelZoom = glPixelZoom; + table.m_glPointSize = glPointSize; + table.m_glPolygonMode = glPolygonMode; + table.m_glPolygonOffset = glPolygonOffset; + table.m_glPolygonStipple = glPolygonStipple; + table.m_glPopAttrib = glPopAttrib; + table.m_glPopClientAttrib = glPopClientAttrib; + table.m_glPopMatrix = glPopMatrix; + table.m_glPopName = glPopName; + table.m_glPrioritizeTextures = glPrioritizeTextures; + table.m_glPushAttrib = glPushAttrib; + table.m_glPushClientAttrib = glPushClientAttrib; + table.m_glPushMatrix = glPushMatrix; + table.m_glPushName = glPushName; + table.m_glRasterPos2d = glRasterPos2d; + table.m_glRasterPos2dv = glRasterPos2dv; + table.m_glRasterPos2f = glRasterPos2f; + table.m_glRasterPos2fv = glRasterPos2fv; + table.m_glRasterPos2i = glRasterPos2i; + table.m_glRasterPos2iv = glRasterPos2iv; + table.m_glRasterPos2s = glRasterPos2s; + table.m_glRasterPos2sv = glRasterPos2sv; + table.m_glRasterPos3d = glRasterPos3d; + table.m_glRasterPos3dv = glRasterPos3dv; + table.m_glRasterPos3f = glRasterPos3f; + table.m_glRasterPos3fv = glRasterPos3fv; + table.m_glRasterPos3i = glRasterPos3i; + table.m_glRasterPos3iv = glRasterPos3iv; + table.m_glRasterPos3s = glRasterPos3s; + table.m_glRasterPos3sv = glRasterPos3sv; + table.m_glRasterPos4d = glRasterPos4d; + table.m_glRasterPos4dv = glRasterPos4dv; + table.m_glRasterPos4f = glRasterPos4f; + table.m_glRasterPos4fv = glRasterPos4fv; + table.m_glRasterPos4i = glRasterPos4i; + table.m_glRasterPos4iv = glRasterPos4iv; + table.m_glRasterPos4s = glRasterPos4s; + table.m_glRasterPos4sv = glRasterPos4sv; + table.m_glReadBuffer = glReadBuffer; + table.m_glReadPixels = glReadPixels; + table.m_glRectd = glRectd; + table.m_glRectdv = glRectdv; + table.m_glRectf = glRectf; + table.m_glRectfv = glRectfv; + table.m_glRecti = glRecti; + table.m_glRectiv = glRectiv; + table.m_glRects = glRects; + table.m_glRectsv = glRectsv; + table.m_glRenderMode = glRenderMode; + table.m_glRotated = glRotated; + table.m_glRotatef = glRotatef; + table.m_glScaled = glScaled; + table.m_glScalef = glScalef; + table.m_glScissor = glScissor; + table.m_glSelectBuffer = glSelectBuffer; + table.m_glShadeModel = glShadeModel; + table.m_glStencilFunc = glStencilFunc; + table.m_glStencilMask = glStencilMask; + table.m_glStencilOp = glStencilOp; + table.m_glTexCoord1d = glTexCoord1d; + table.m_glTexCoord1dv = glTexCoord1dv; + table.m_glTexCoord1f = glTexCoord1f; + table.m_glTexCoord1fv = glTexCoord1fv; + table.m_glTexCoord1i = glTexCoord1i; + table.m_glTexCoord1iv = glTexCoord1iv; + table.m_glTexCoord1s = glTexCoord1s; + table.m_glTexCoord1sv = glTexCoord1sv; + table.m_glTexCoord2d = glTexCoord2d; + table.m_glTexCoord2dv = glTexCoord2dv; + table.m_glTexCoord2f = glTexCoord2f; + table.m_glTexCoord2fv = glTexCoord2fv; + table.m_glTexCoord2i = glTexCoord2i; + table.m_glTexCoord2iv = glTexCoord2iv; + table.m_glTexCoord2s = glTexCoord2s; + table.m_glTexCoord2sv = glTexCoord2sv; + table.m_glTexCoord3d = glTexCoord3d; + table.m_glTexCoord3dv = glTexCoord3dv; + table.m_glTexCoord3f = glTexCoord3f; + table.m_glTexCoord3fv = glTexCoord3fv; + table.m_glTexCoord3i = glTexCoord3i; + table.m_glTexCoord3iv = glTexCoord3iv; + table.m_glTexCoord3s = glTexCoord3s; + table.m_glTexCoord3sv = glTexCoord3sv; + table.m_glTexCoord4d = glTexCoord4d; + table.m_glTexCoord4dv = glTexCoord4dv; + table.m_glTexCoord4f = glTexCoord4f; + table.m_glTexCoord4fv = glTexCoord4fv; + table.m_glTexCoord4i = glTexCoord4i; + table.m_glTexCoord4iv = glTexCoord4iv; + table.m_glTexCoord4s = glTexCoord4s; + table.m_glTexCoord4sv = glTexCoord4sv; + table.m_glTexCoordPointer = glTexCoordPointer; + table.m_glTexEnvf = glTexEnvf; + table.m_glTexEnvfv = glTexEnvfv; + table.m_glTexEnvi = glTexEnvi; + table.m_glTexEnviv = glTexEnviv; + table.m_glTexGend = glTexGend; + table.m_glTexGendv = glTexGendv; + table.m_glTexGenf = glTexGenf; + table.m_glTexGenfv = glTexGenfv; + table.m_glTexGeni = glTexGeni; + table.m_glTexGeniv = glTexGeniv; + table.m_glTexImage1D = glTexImage1D; + table.m_glTexImage2D = glTexImage2D; + table.m_glTexParameterf = glTexParameterf; + table.m_glTexParameterfv = glTexParameterfv; + table.m_glTexParameteri = glTexParameteri; + table.m_glTexParameteriv = glTexParameteriv; + table.m_glTexSubImage1D = glTexSubImage1D; + table.m_glTexSubImage2D = glTexSubImage2D; + table.m_glTranslated = glTranslated; + table.m_glTranslatef = glTranslatef; + table.m_glVertex2d = glVertex2d; + table.m_glVertex2dv = glVertex2dv; + table.m_glVertex2f = glVertex2f; + table.m_glVertex2fv = glVertex2fv; + table.m_glVertex2i = glVertex2i; + table.m_glVertex2iv = glVertex2iv; + table.m_glVertex2s = glVertex2s; + table.m_glVertex2sv = glVertex2sv; + table.m_glVertex3d = glVertex3d; + table.m_glVertex3dv = glVertex3dv; + table.m_glVertex3f = glVertex3f; + table.m_glVertex3fv = glVertex3fv; + table.m_glVertex3i = glVertex3i; + table.m_glVertex3iv = glVertex3iv; + table.m_glVertex3s = glVertex3s; + table.m_glVertex3sv = glVertex3sv; + table.m_glVertex4d = glVertex4d; + table.m_glVertex4dv = glVertex4dv; + table.m_glVertex4f = glVertex4f; + table.m_glVertex4fv = glVertex4fv; + table.m_glVertex4i = glVertex4i; + table.m_glVertex4iv = glVertex4iv; + table.m_glVertex4s = glVertex4s; + table.m_glVertex4sv = glVertex4sv; + table.m_glVertexPointer = glVertexPointer; + table.m_glViewport = glViewport; + + if(QGL_ExtensionSupported("GL_ARB_multitexture")) + { + table.support_ARB_multitexture = + QGL_constructExtensionFunc(table.m_glActiveTextureARB, "glActiveTextureARB") + && QGL_constructExtensionFunc(table.m_glClientActiveTextureARB, "glClientActiveTextureARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1dARB, "glMultiTexCoord1dARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1dvARB, "glMultiTexCoord1dvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1fARB, "glMultiTexCoord1fARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1fvARB, "glMultiTexCoord1fvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1iARB, "glMultiTexCoord1iARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1ivARB, "glMultiTexCoord1ivARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1sARB, "glMultiTexCoord1sARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1svARB, "glMultiTexCoord1svARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2dARB, "glMultiTexCoord2dARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2dvARB, "glMultiTexCoord2dvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2fARB, "glMultiTexCoord2fARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2fvARB, "glMultiTexCoord2fvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2iARB, "glMultiTexCoord2iARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2ivARB, "glMultiTexCoord2ivARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2sARB, "glMultiTexCoord2sARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2svARB, "glMultiTexCoord2svARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3dARB, "glMultiTexCoord3dARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3dvARB, "glMultiTexCoord3dvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3fARB, "glMultiTexCoord3fARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3fvARB, "glMultiTexCoord3fvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3iARB, "glMultiTexCoord3iARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3ivARB, "glMultiTexCoord3ivARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3sARB, "glMultiTexCoord3sARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3svARB, "glMultiTexCoord3svARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4dARB, "glMultiTexCoord4dARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4dvARB, "glMultiTexCoord4dvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4fARB, "glMultiTexCoord4fARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4fvARB, "glMultiTexCoord4fvARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4iARB, "glMultiTexCoord4iARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4ivARB, "glMultiTexCoord4ivARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4sARB, "glMultiTexCoord4sARB") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4svARB, "glMultiTexCoord4svARB"); + + if(!table.support_ARB_multitexture) + { + extension_not_implemented("GL_ARB_multitexture"); + } + } + else + { + table.support_ARB_multitexture = false; + } + + if(QGL_ExtensionSupported("GL_ARB_texture_compression")) + { + table.support_ARB_texture_compression = + QGL_constructExtensionFunc(table.m_glCompressedTexImage3DARB, "glCompressedTexImage3DARB") + && QGL_constructExtensionFunc(table.m_glCompressedTexImage2DARB, "glCompressedTexImage2DARB") + && QGL_constructExtensionFunc(table.m_glCompressedTexImage1DARB, "glCompressedTexImage1DARB") + && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage3DARB, "glCompressedTexSubImage3DARB") + && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage2DARB, "glCompressedTexSubImage2DARB") + && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage1DARB, "glCompressedTexSubImage1DARB") + && QGL_constructExtensionFunc(table.m_glGetCompressedTexImageARB, "glGetCompressedTexImageARB"); + + if(!table.support_ARB_texture_compression) + { + extension_not_implemented("GL_ARB_texture_compression"); + } + } + else + { + table.support_ARB_texture_compression = false; + } + + table.support_EXT_texture_compression_s3tc = QGL_ExtensionSupported("GL_EXT_texture_compression_s3tc"); + + // GL 1.2 + if(table.major_version > 1 || table.minor_version >= 2) + { + table.support_GL_1_2 = + QGL_constructExtensionFunc(table.m_glCopyTexSubImage3D, "glCopyTexSubImage3D") + && QGL_constructExtensionFunc(table.m_glDrawRangeElements, "glDrawRangeElements") + && QGL_constructExtensionFunc(table.m_glTexImage3D, "glTexImage3D") + && QGL_constructExtensionFunc(table.m_glTexSubImage3D, "glTexSubImage3D"); + + if(!table.support_GL_1_2) + { + extension_not_implemented("GL_VERSION_1_2"); + } + } + else + { + table.support_GL_1_2 = false; + } + + // GL 1.3 + if(table.major_version > 1 || table.minor_version >= 3) + { + table.support_GL_1_3 = + QGL_constructExtensionFunc(table.m_glActiveTexture, "glActiveTexture") + && QGL_constructExtensionFunc(table.m_glClientActiveTexture, "glClientActiveTexture") + && QGL_constructExtensionFunc(table.m_glCompressedTexImage1D, "glCompressedTexImage1D") + && QGL_constructExtensionFunc(table.m_glCompressedTexImage2D, "glCompressedTexImage2D") + && QGL_constructExtensionFunc(table.m_glCompressedTexImage3D, "glCompressedTexImage3D") + && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage1D, "glCompressedTexSubImage1D") + && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage2D, "glCompressedTexSubImage2D") + && QGL_constructExtensionFunc(table.m_glCompressedTexSubImage3D, "glCompressedTexSubImage3D") + && QGL_constructExtensionFunc(table.m_glGetCompressedTexImage, "glGetCompressedTexImage") + && QGL_constructExtensionFunc(table.m_glLoadTransposeMatrixd, "glLoadTransposeMatrixd") + && QGL_constructExtensionFunc(table.m_glLoadTransposeMatrixf, "glLoadTransposeMatrixf") + && QGL_constructExtensionFunc(table.m_glMultTransposeMatrixd, "glMultTransposeMatrixd") + && QGL_constructExtensionFunc(table.m_glMultTransposeMatrixf, "glMultTransposeMatrixf") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1d, "glMultiTexCoord1d") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1dv, "glMultiTexCoord1dv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1f, "glMultiTexCoord1f") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1fv, "glMultiTexCoord1fv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1i, "glMultiTexCoord1i") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1iv, "glMultiTexCoord1iv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1s, "glMultiTexCoord1s") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord1sv, "glMultiTexCoord1sv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2d, "glMultiTexCoord2d") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2dv, "glMultiTexCoord2dv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2f, "glMultiTexCoord2f") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2fv, "glMultiTexCoord2fv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2i, "glMultiTexCoord2i") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2iv, "glMultiTexCoord2iv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2s, "glMultiTexCoord2s") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord2sv, "glMultiTexCoord2sv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3d, "glMultiTexCoord3d") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3dv, "glMultiTexCoord3dv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3f, "glMultiTexCoord3f") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3fv, "glMultiTexCoord3fv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3i, "glMultiTexCoord3i") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3iv, "glMultiTexCoord3iv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3s, "glMultiTexCoord3s") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord3sv, "glMultiTexCoord3sv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4d, "glMultiTexCoord4d") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4dv, "glMultiTexCoord4dv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4f, "glMultiTexCoord4f") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4fv, "glMultiTexCoord4fv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4i, "glMultiTexCoord4i") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4iv, "glMultiTexCoord4iv") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4s, "glMultiTexCoord4s") + && QGL_constructExtensionFunc(table.m_glMultiTexCoord4sv, "glMultiTexCoord4sv") + && QGL_constructExtensionFunc(table.m_glSampleCoverage, "glSampleCoverage"); + + if(!table.support_GL_1_3) + { + extension_not_implemented("GL_VERSION_1_3"); + } + } + else + { + table.support_GL_1_3 = false; + } + + // GL 1.4 + if(table.major_version > 1 || table.minor_version >= 4) + { + table.support_GL_1_4 = + QGL_constructExtensionFunc(table.m_glBlendColor, "glBlendColor") + && QGL_constructExtensionFunc(table.m_glBlendEquation, "glBlendEquation") + && QGL_constructExtensionFunc(table.m_glBlendFuncSeparate, "glBlendFuncSeparate") + && QGL_constructExtensionFunc(table.m_glFogCoordPointer, "glFogCoordPointer") + && QGL_constructExtensionFunc(table.m_glFogCoordd, "glFogCoordd") + && QGL_constructExtensionFunc(table.m_glFogCoorddv, "glFogCoorddv") + && QGL_constructExtensionFunc(table.m_glFogCoordf, "glFogCoordf") + && QGL_constructExtensionFunc(table.m_glFogCoordfv, "glFogCoordfv") + && QGL_constructExtensionFunc(table.m_glMultiDrawArrays, "glMultiDrawArrays") + && QGL_constructExtensionFunc(table.m_glMultiDrawElements, "glMultiDrawElements") + && QGL_constructExtensionFunc(table.m_glPointParameterf, "glPointParameterf") + && QGL_constructExtensionFunc(table.m_glPointParameterfv, "glPointParameterfv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3b, "glSecondaryColor3b") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3bv, "glSecondaryColor3bv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3d, "glSecondaryColor3d") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3dv, "glSecondaryColor3dv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3f, "glSecondaryColor3f") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3fv, "glSecondaryColor3fv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3i, "glSecondaryColor3i") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3iv, "glSecondaryColor3iv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3s, "glSecondaryColor3s") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3sv, "glSecondaryColor3sv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3ub, "glSecondaryColor3ub") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3ubv, "glSecondaryColor3ubv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3ui, "glSecondaryColor3ui") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3uiv, "glSecondaryColor3uiv") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3us, "glSecondaryColor3us") + && QGL_constructExtensionFunc(table.m_glSecondaryColor3usv, "glSecondaryColor3usv") + && QGL_constructExtensionFunc(table.m_glSecondaryColorPointer, "glSecondaryColorPointer") + && QGL_constructExtensionFunc(table.m_glWindowPos2d, "glWindowPos2d") + && QGL_constructExtensionFunc(table.m_glWindowPos2dv, "glWindowPos2dv") + && QGL_constructExtensionFunc(table.m_glWindowPos2f, "glWindowPos2f") + && QGL_constructExtensionFunc(table.m_glWindowPos2fv, "glWindowPos2fv") + && QGL_constructExtensionFunc(table.m_glWindowPos2i, "glWindowPos2i") + && QGL_constructExtensionFunc(table.m_glWindowPos2iv, "glWindowPos2iv") + && QGL_constructExtensionFunc(table.m_glWindowPos2s, "glWindowPos2s") + && QGL_constructExtensionFunc(table.m_glWindowPos2sv, "glWindowPos2sv") + && QGL_constructExtensionFunc(table.m_glWindowPos3d, "glWindowPos3d") + && QGL_constructExtensionFunc(table.m_glWindowPos3dv, "glWindowPos3dv") + && QGL_constructExtensionFunc(table.m_glWindowPos3f, "glWindowPos3f") + && QGL_constructExtensionFunc(table.m_glWindowPos3fv, "glWindowPos3fv") + && QGL_constructExtensionFunc(table.m_glWindowPos3i, "glWindowPos3i") + && QGL_constructExtensionFunc(table.m_glWindowPos3iv, "glWindowPos3iv") + && QGL_constructExtensionFunc(table.m_glWindowPos3s, "glWindowPos3s") + && QGL_constructExtensionFunc(table.m_glWindowPos3sv, "glWindowPos3sv"); + + if(!table.support_GL_1_4) + { + extension_not_implemented("GL_VERSION_1_4"); + } + } + else + { + table.support_GL_1_4 = false; + } + + // GL 1.5 + if(table.major_version > 1 || table.minor_version >= 5) + { + table.support_GL_1_5 = + QGL_constructExtensionFunc(table.m_glBeginQuery, "glBeginQuery") + && QGL_constructExtensionFunc(table.m_glBindBuffer, "glBindBuffer") + && QGL_constructExtensionFunc(table.m_glBufferData, "glBufferData") + && QGL_constructExtensionFunc(table.m_glBufferSubData, "glBufferSubData") + && QGL_constructExtensionFunc(table.m_glDeleteBuffers, "glDeleteBuffers") + && QGL_constructExtensionFunc(table.m_glDeleteQueries, "glDeleteQueries") + && QGL_constructExtensionFunc(table.m_glEndQuery, "glEndQuery") + && QGL_constructExtensionFunc(table.m_glGenBuffers, "glGenBuffers") + && QGL_constructExtensionFunc(table.m_glGenQueries, "glGenQueries") + && QGL_constructExtensionFunc(table.m_glGetBufferParameteriv, "glGetBufferParameteriv") + && QGL_constructExtensionFunc(table.m_glGetBufferPointerv, "glGetBufferPointerv") + && QGL_constructExtensionFunc(table.m_glGetBufferSubData, "glGetBufferSubData") + && QGL_constructExtensionFunc(table.m_glGetQueryObjectiv, "glGetQueryObjectiv") + && QGL_constructExtensionFunc(table.m_glGetQueryObjectuiv, "glGetQueryObjectuiv") + && QGL_constructExtensionFunc(table.m_glGetQueryiv, "glGetQueryiv") + && QGL_constructExtensionFunc(table.m_glIsBuffer, "glIsBuffer") + && QGL_constructExtensionFunc(table.m_glIsQuery, "glIsQuery") + && QGL_constructExtensionFunc(table.m_glMapBuffer, "glMapBuffer") + && QGL_constructExtensionFunc(table.m_glUnmapBuffer, "glUnmapBuffer"); + + if(!table.support_GL_1_5) + { + extension_not_implemented("GL_VERSION_1_5"); + } + } + else + { + table.support_GL_1_5 = false; + } + + + if(QGL_ExtensionSupported("GL_ARB_vertex_program")) + { + table.support_ARB_vertex_program = + QGL_constructExtensionFunc(table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB") + && QGL_constructExtensionFunc(table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB") + && QGL_constructExtensionFunc(table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB") + && QGL_constructExtensionFunc(table.m_glProgramStringARB, "glProgramStringARB") + && QGL_constructExtensionFunc(table.m_glBindProgramARB, "glBindProgramARB") + && QGL_constructExtensionFunc(table.m_glDeleteProgramsARB, "glDeleteProgramsARB") + && QGL_constructExtensionFunc(table.m_glGenProgramsARB, "glGenProgramsARB") + && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4dARB, "glProgramEnvParameter4dARB") + && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4dvARB, "glProgramEnvParameter4dvARB") + && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4fARB, "glProgramEnvParameter4fARB") + && QGL_constructExtensionFunc(table.m_glProgramEnvParameter4fvARB, "glProgramEnvParameter4fvARB") + && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4dARB, "glProgramLocalParameter4dARB") + && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4dvARB, "glProgramLocalParameter4dvARB") + && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4fARB, "glProgramLocalParameter4fARB") + && QGL_constructExtensionFunc(table.m_glProgramLocalParameter4fvARB, "glProgramLocalParameter4fvARB") + && QGL_constructExtensionFunc(table.m_glGetProgramEnvParameterdvARB, "glGetProgramEnvParameterdvARB") + && QGL_constructExtensionFunc(table.m_glGetProgramEnvParameterfvARB, "glGetProgramEnvParameterfvARB") + && QGL_constructExtensionFunc(table.m_glGetProgramLocalParameterdvARB, "glGetProgramLocalParameterdvARB") + && QGL_constructExtensionFunc(table.m_glGetProgramLocalParameterfvARB, "glGetProgramLocalParameterfvARB") + && QGL_constructExtensionFunc(table.m_glGetProgramivARB, "glGetProgramivARB") + && QGL_constructExtensionFunc(table.m_glGetProgramStringARB, "glGetProgramStringARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB") + && QGL_constructExtensionFunc(table.m_glIsProgramARB, "glIsProgramARB"); + + if(!table.support_ARB_vertex_program) + { + extension_not_implemented("GL_ARB_vertex_program"); + } + } + else + { + table.support_ARB_vertex_program = false; + } + + + table.support_ARB_fragment_program = QGL_ExtensionSupported("GL_ARB_fragment_program"); + + if(QGL_ExtensionSupported("GL_ARB_shader_objects")) + { + table.support_ARB_shader_objects = + QGL_constructExtensionFunc(table.m_glDeleteObjectARB, "glDeleteObjectARB") + && QGL_constructExtensionFunc(table.m_glGetHandleARB, "glGetHandleARB") + && QGL_constructExtensionFunc(table.m_glDetachObjectARB, "glDetachObjectARB") + && QGL_constructExtensionFunc(table.m_glCreateShaderObjectARB, "glCreateShaderObjectARB") + && QGL_constructExtensionFunc(table.m_glShaderSourceARB, "glShaderSourceARB") + && QGL_constructExtensionFunc(table.m_glCompileShaderARB, "glCompileShaderARB") + && QGL_constructExtensionFunc(table.m_glCreateProgramObjectARB, "glCreateProgramObjectARB") + && QGL_constructExtensionFunc(table.m_glAttachObjectARB, "glAttachObjectARB") + && QGL_constructExtensionFunc(table.m_glLinkProgramARB, "glLinkProgramARB") + && QGL_constructExtensionFunc(table.m_glUseProgramObjectARB, "glUseProgramObjectARB") + && QGL_constructExtensionFunc(table.m_glValidateProgramARB, "glValidateProgramARB") + && QGL_constructExtensionFunc(table.m_glUniform1fARB, "glUniform1fARB") + && QGL_constructExtensionFunc(table.m_glUniform2fARB, "glUniform2fARB") + && QGL_constructExtensionFunc(table.m_glUniform3fARB, "glUniform3fARB") + && QGL_constructExtensionFunc(table.m_glUniform4fARB, "glUniform4fARB") + && QGL_constructExtensionFunc(table.m_glUniform1iARB, "glUniform1iARB") + && QGL_constructExtensionFunc(table.m_glUniform2iARB, "glUniform2iARB") + && QGL_constructExtensionFunc(table.m_glUniform3iARB, "glUniform3iARB") + && QGL_constructExtensionFunc(table.m_glUniform4iARB, "glUniform4iARB") + && QGL_constructExtensionFunc(table.m_glUniform1fvARB, "glUniform1fvARB") + && QGL_constructExtensionFunc(table.m_glUniform2fvARB, "glUniform2fvARB") + && QGL_constructExtensionFunc(table.m_glUniform3fvARB, "glUniform3fvARB") + && QGL_constructExtensionFunc(table.m_glUniform4fvARB, "glUniform4fvARB") + && QGL_constructExtensionFunc(table.m_glUniform1ivARB, "glUniform1ivARB") + && QGL_constructExtensionFunc(table.m_glUniform2ivARB, "glUniform2ivARB") + && QGL_constructExtensionFunc(table.m_glUniform3ivARB, "glUniform3ivARB") + && QGL_constructExtensionFunc(table.m_glUniform4ivARB, "glUniform4ivARB") + && QGL_constructExtensionFunc(table.m_glUniformMatrix2fvARB, "glUniformMatrix2fvARB") + && QGL_constructExtensionFunc(table.m_glUniformMatrix3fvARB, "glUniformMatrix3fvARB") + && QGL_constructExtensionFunc(table.m_glUniformMatrix4fvARB, "glUniformMatrix4fvARB") + && QGL_constructExtensionFunc(table.m_glGetObjectParameterfvARB, "glGetObjectParameterfvARB") + && QGL_constructExtensionFunc(table.m_glGetObjectParameterivARB, "glGetObjectParameterivARB") + && QGL_constructExtensionFunc(table.m_glGetInfoLogARB, "glGetInfoLogARB") + && QGL_constructExtensionFunc(table.m_glGetAttachedObjectsARB, "glGetAttachedObjectsARB") + && QGL_constructExtensionFunc(table.m_glGetUniformLocationARB, "glGetUniformLocationARB") + && QGL_constructExtensionFunc(table.m_glGetActiveUniformARB, "glGetActiveUniformARB") + && QGL_constructExtensionFunc(table.m_glGetUniformfvARB, "glGetUniformfvARB") + && QGL_constructExtensionFunc(table.m_glGetUniformivARB, "glGetUniformivARB") + && QGL_constructExtensionFunc(table.m_glGetShaderSourceARB, "glGetShaderSourceARB"); + + if(!table.support_ARB_shader_objects) + { + extension_not_implemented("GL_ARB_shader_objects"); + } + } + else + { + table.support_ARB_shader_objects = false; + } + + if(QGL_ExtensionSupported("GL_ARB_vertex_shader")) + { + table.support_ARB_vertex_shader = + QGL_constructExtensionFunc(table.m_glVertexAttrib1fARB, "glVertexAttrib1fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1sARB, "glVertexAttrib1sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1dARB, "glVertexAttrib1dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2fARB, "glVertexAttrib2fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2sARB, "glVertexAttrib2sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2dARB, "glVertexAttrib2dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3fARB, "glVertexAttrib3fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3sARB, "glVertexAttrib3sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3dARB, "glVertexAttrib3dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4fARB, "glVertexAttrib4fARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4sARB, "glVertexAttrib4sARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4dARB, "glVertexAttrib4dARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubARB, "glVertexAttrib4NubARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1fvARB, "glVertexAttrib1fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1svARB, "glVertexAttrib1svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1dvARB, "glVertexAttrib1dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2fvARB, "glVertexAttrib2fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2svARB, "glVertexAttrib2svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2dvARB, "glVertexAttrib2dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3fvARB, "glVertexAttrib3fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3svARB, "glVertexAttrib3svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3dvARB, "glVertexAttrib3dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4fvARB, "glVertexAttrib4fvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4svARB, "glVertexAttrib4svARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4dvARB, "glVertexAttrib4dvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4ivARB, "glVertexAttrib4ivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4bvARB, "glVertexAttrib4bvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4ubvARB, "glVertexAttrib4ubvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4usvARB, "glVertexAttrib4usvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4uivARB, "glVertexAttrib4uivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NbvARB, "glVertexAttrib4NbvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NsvARB, "glVertexAttrib4NsvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NivARB, "glVertexAttrib4NivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NubvARB, "glVertexAttrib4NubvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NusvARB, "glVertexAttrib4NusvARB") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4NuivARB, "glVertexAttrib4NuivARB") + && QGL_constructExtensionFunc(table.m_glVertexAttribPointerARB, "glVertexAttribPointerARB") + && QGL_constructExtensionFunc(table.m_glEnableVertexAttribArrayARB, "glEnableVertexAttribArrayARB") + && QGL_constructExtensionFunc(table.m_glDisableVertexAttribArrayARB, "glDisableVertexAttribArrayARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribdvARB, "glGetVertexAttribdvARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribfvARB, "glGetVertexAttribfvARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribivARB, "glGetVertexAttribivARB") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribPointervARB, "glGetVertexAttribPointervARB") + && QGL_constructExtensionFunc(table.m_glBindAttribLocationARB, "glBindAttribLocationARB") + && QGL_constructExtensionFunc(table.m_glGetActiveAttribARB, "glGetActiveAttribARB") + && QGL_constructExtensionFunc(table.m_glGetAttribLocationARB, "glGetAttribLocationARB"); + + if(!table.support_ARB_vertex_shader) + { + extension_not_implemented("GL_ARB_vertex_shader"); + } + } + else + { + table.support_ARB_vertex_shader = false; + } + + if(QGL_ExtensionSupported("GL_NV_vertex_program2")) + { + table.support_NV_vertex_program2 = + QGL_constructExtensionFunc(table.m_glAreProgramsResidentNV, "glAreProgramsResidentNV") + && QGL_constructExtensionFunc(table.m_glBindProgramNV, "glBindProgramNV") + && QGL_constructExtensionFunc(table.m_glDeleteProgramsNV, "glDeleteProgramsNV") + && QGL_constructExtensionFunc(table.m_glExecuteProgramNV, "glExecuteProgramNV") + && QGL_constructExtensionFunc(table.m_glGenProgramsNV, "glGenProgramsNV") + && QGL_constructExtensionFunc(table.m_glGetProgramParameterdvNV, "glGetProgramParameterdvNV") + && QGL_constructExtensionFunc(table.m_glGetProgramParameterfvNV, "glGetProgramParameterfvNV") + && QGL_constructExtensionFunc(table.m_glGetProgramivNV, "glGetProgramivNV") + && QGL_constructExtensionFunc(table.m_glGetProgramStringNV, "glGetProgramStringNV") + && QGL_constructExtensionFunc(table.m_glGetTrackMatrixivNV, "glGetTrackMatrixivNV") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribdvNV, "glGetVertexAttribdvNV") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribfvNV, "glGetVertexAttribfvNV") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribivNV, "glGetVertexAttribivNV") + && QGL_constructExtensionFunc(table.m_glGetVertexAttribPointervNV, "glGetVertexAttribPointervNV") + && QGL_constructExtensionFunc(table.m_glIsProgramNV, "glIsProgramNV") + && QGL_constructExtensionFunc(table.m_glLoadProgramNV, "glLoadProgramNV") + && QGL_constructExtensionFunc(table.m_glProgramParameter4fNV, "glProgramParameter4fNV") + && QGL_constructExtensionFunc(table.m_glProgramParameter4fvNV, "glProgramParameter4fvNV") + && QGL_constructExtensionFunc(table.m_glProgramParameters4fvNV, "glProgramParameters4fvNV") + && QGL_constructExtensionFunc(table.m_glRequestResidentProgramsNV, "glRequestResidentProgramsNV") + && QGL_constructExtensionFunc(table.m_glTrackMatrixNV, "glTrackMatrixNV") + && QGL_constructExtensionFunc(table.m_glVertexAttribPointerNV, "glVertexAttribPointerNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1fNV, "glVertexAttrib1fNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib1fvNV, "glVertexAttrib1fvNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2fNV, "glVertexAttrib2fNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib2fvNV, "glVertexAttrib2fvNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3fNV, "glVertexAttrib3fNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib3fvNV, "glVertexAttrib3fvNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4fNV, "glVertexAttrib4fNV") + && QGL_constructExtensionFunc(table.m_glVertexAttrib4fvNV, "glVertexAttrib4fvNV") + && QGL_constructExtensionFunc(table.m_glVertexAttribs1fvNV, "glVertexAttribs1fvNV") + && QGL_constructExtensionFunc(table.m_glVertexAttribs2fvNV, "glVertexAttribs2fvNV") + && QGL_constructExtensionFunc(table.m_glVertexAttribs3fvNV, "glVertexAttribs3fvNV") + && QGL_constructExtensionFunc(table.m_glVertexAttribs4fvNV, "glVertexAttribs4fvNV"); + + if(!table.support_NV_vertex_program2) + { + extension_not_implemented("GL_NV_vertex_program2"); + } + } + else + { + table.support_NV_vertex_program2 = false; + QGL_invalidateExtensionFunc(table.m_glAreProgramsResidentNV); + QGL_invalidateExtensionFunc(table.m_glBindProgramNV); + QGL_invalidateExtensionFunc(table.m_glDeleteProgramsNV); + QGL_invalidateExtensionFunc(table.m_glExecuteProgramNV); + QGL_invalidateExtensionFunc(table.m_glGenProgramsNV); + QGL_invalidateExtensionFunc(table.m_glGetProgramParameterdvNV); + QGL_invalidateExtensionFunc(table.m_glGetProgramParameterfvNV); + QGL_invalidateExtensionFunc(table.m_glGetProgramivNV); + QGL_invalidateExtensionFunc(table.m_glGetProgramStringNV); + QGL_invalidateExtensionFunc(table.m_glGetTrackMatrixivNV); + QGL_invalidateExtensionFunc(table.m_glGetVertexAttribdvNV); + QGL_invalidateExtensionFunc(table.m_glGetVertexAttribfvNV); + QGL_invalidateExtensionFunc(table.m_glGetVertexAttribivNV); + QGL_invalidateExtensionFunc(table.m_glGetVertexAttribPointervNV); + QGL_invalidateExtensionFunc(table.m_glIsProgramNV); + QGL_invalidateExtensionFunc(table.m_glLoadProgramNV); + QGL_invalidateExtensionFunc(table.m_glProgramParameter4fNV); + QGL_invalidateExtensionFunc(table.m_glProgramParameter4fvNV); + QGL_invalidateExtensionFunc(table.m_glProgramParameters4fvNV); + QGL_invalidateExtensionFunc(table.m_glRequestResidentProgramsNV); + QGL_invalidateExtensionFunc(table.m_glTrackMatrixNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttribPointerNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib1fNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib1fvNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib2fNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib2fvNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib3fNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib3fvNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib4fNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttrib4fvNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttribs1fvNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttribs2fvNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttribs3fvNV); + QGL_invalidateExtensionFunc(table.m_glVertexAttribs4fvNV); + } + + if(QGL_ExtensionSupported("GL_NV_fragment_program")) + { + table.support_NV_fragment_program = + QGL_constructExtensionFunc(table.m_glProgramNamedParameter4fNV, "glProgramNamedParameter4fNV") + && QGL_constructExtensionFunc(table.m_glProgramNamedParameter4fvNV, "glProgramNamedParameter4fvNV") + && QGL_constructExtensionFunc(table.m_glGetProgramNamedParameterfvNV, "glGetProgramNamedParameterfvNV"); + + if(!table.support_NV_fragment_program) + { + extension_not_implemented("GL_NV_fragment_program"); + } + } + else + { + table.support_NV_fragment_program = false; + } + + table.support_ARB_fragment_shader = QGL_ExtensionSupported("GL_ARB_fragment_shader"); + table.support_ARB_shading_language_100 = QGL_ExtensionSupported("GL_ARB_shading_language_100"); + + if(QGL_ExtensionSupported("GL_EXT_texture_filter_anisotropic")) + { + glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &g_maxTextureAnisotropy); + globalOutputStream() << "Anisotropic filtering possible (max " << g_maxTextureAnisotropy << "x)\n"; + } + else + { + globalOutputStream() << "No Anisotropic filtering available\n"; + g_maxTextureAnisotropy = 0; + } +} + +void QGL_sharedContextDestroyed(OpenGLBinding& table) +{ + QGL_clear(table); +} + + +void QGL_assertNoErrors(const char *file, int line) +{ + GLenum error = GlobalOpenGL().m_glGetError(); + while (error != GL_NO_ERROR) + { + const char* errorString = reinterpret_cast(qgluErrorString(error)); + if (error == GL_OUT_OF_MEMORY) + { + ERROR_MESSAGE("OpenGL out of memory error at " << file << ":" << line << ": " << errorString); + } + else + { + ERROR_MESSAGE("OpenGL error at " << file << ":" << line << ": " << errorString); + } + error = GlobalOpenGL().m_glGetError(); + } +} + + +class QglAPI +{ + OpenGLBinding m_qgl; +public: + typedef OpenGLBinding Type; + STRING_CONSTANT(Name, "*"); + + QglAPI() + { + QGL_Init(m_qgl); + + m_qgl.assertNoErrors = &QGL_assertNoErrors; + } + ~QglAPI() + { + QGL_Shutdown(m_qgl); + } + OpenGLBinding* getTable() + { + return &m_qgl; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule QglModule; +typedef Static StaticQglModule; +StaticRegisterModule staticRegisterQgl(StaticQglModule::instance()); diff --git a/misc/mediasource/netradiant-src/radiant/qgl.h b/misc/mediasource/netradiant-src/radiant/qgl.h new file mode 100644 index 00000000..55d1570e --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/qgl.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_QGL_H) +#define INCLUDED_QGL_H + +struct OpenGLBinding; +void QGL_sharedContextCreated(OpenGLBinding& table); +void QGL_sharedContextDestroyed(OpenGLBinding& table); + +bool QGL_ExtensionSupported(const char* extension); + +float QGL_maxTextureAnisotropy(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/radiant.ico b/misc/mediasource/netradiant-src/radiant/radiant.ico new file mode 100644 index 00000000..45e8258e Binary files /dev/null and b/misc/mediasource/netradiant-src/radiant/radiant.ico differ diff --git a/misc/mediasource/netradiant-src/radiant/radiant.rc b/misc/mediasource/netradiant-src/radiant/radiant.rc new file mode 100644 index 00000000..51087c04 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/radiant.rc @@ -0,0 +1,72 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +//#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +//#ifdef _WIN32 +//LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +//#pragma code_page(1252) +//#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_RADIANT ICON DISCARDABLE "radiant.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "//#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/misc/mediasource/netradiant-src/radiant/radiant_old.ico b/misc/mediasource/netradiant-src/radiant/radiant_old.ico new file mode 100644 index 00000000..b45ef36a Binary files /dev/null and b/misc/mediasource/netradiant-src/radiant/radiant_old.ico differ diff --git a/misc/mediasource/netradiant-src/radiant/referencecache.cpp b/misc/mediasource/netradiant-src/radiant/referencecache.cpp new file mode 100644 index 00000000..d41b9344 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/referencecache.cpp @@ -0,0 +1,846 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "referencecache.h" + +#include "debugging/debugging.h" + +#include "iscenegraph.h" +#include "iselection.h" +#include "iundo.h" +#include "imap.h" +MapModules& ReferenceAPI_getMapModules(); +#include "imodel.h" +ModelModules& ReferenceAPI_getModelModules(); +#include "ifilesystem.h" +#include "iarchive.h" +#include "ifiletypes.h" +#include "ireference.h" +#include "ientity.h" +#include "qerplugin.h" + +#include + +#include "container/cache.h" +#include "container/hashfunc.h" +#include "os/path.h" +#include "stream/textfilestream.h" +#include "nullmodel.h" +#include "maplib.h" +#include "stream/stringstream.h" +#include "os/file.h" +#include "moduleobserver.h" +#include "moduleobservers.h" + +#include "mainframe.h" +#include "map.h" +#include "filetypes.h" + + +bool References_Saved(); + +void MapChanged() +{ + Map_SetModified(g_map, !References_Saved()); +} + + +EntityCreator* g_entityCreator = 0; + +bool MapResource_loadFile(const MapFormat& format, scene::Node& root, const char* filename) +{ + globalOutputStream() << "Open file " << filename << " for read..."; + TextFileInputStream file(filename); + if(!file.failed()) + { + globalOutputStream() << "success\n"; + ScopeDisableScreenUpdates disableScreenUpdates(path_get_filename_start(filename), "Loading Map"); + ASSERT_NOTNULL(g_entityCreator); + format.readGraph(root, file, *g_entityCreator); + return true; + } + else + { + globalErrorStream() << "failure\n"; + return false; + } +} + +NodeSmartReference MapResource_load(const MapFormat& format, const char* path, const char* name) +{ + NodeSmartReference root(NewMapRoot(name)); + + StringOutputStream fullpath(256); + fullpath << path << name; + + if(path_is_absolute(fullpath.c_str())) + { + MapResource_loadFile(format, root, fullpath.c_str()); + } + else + { + globalErrorStream() << "map path is not fully qualified: " << makeQuoted(fullpath.c_str()) << "\n"; + } + + return root; +} + +bool MapResource_saveFile(const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename) +{ + //ASSERT_MESSAGE(path_is_absolute(filename), "MapResource_saveFile: path is not absolute: " << makeQuoted(filename)); + globalOutputStream() << "Open file " << filename << " for write..."; + TextFileOutputStream file(filename); + if(!file.failed()) + { + globalOutputStream() << "success\n"; + ScopeDisableScreenUpdates disableScreenUpdates(path_get_filename_start(filename), "Saving Map"); + format.writeGraph(root, traverse, file); + return true; + } + + globalErrorStream() << "failure\n"; + return false; +} + +bool file_saveBackup(const char* path) +{ + if(file_writeable(path)) + { + StringOutputStream backup(256); + backup << StringRange(path, path_get_extension(path)) << "bak"; + + return (!file_exists(backup.c_str()) || file_remove(backup.c_str())) // remove backup + && file_move(path, backup.c_str()); // rename current to backup + } + + globalErrorStream() << "map path is not writeable: " << makeQuoted(path) << "\n"; + return false; +} + +bool MapResource_save(const MapFormat& format, scene::Node& root, const char* path, const char* name) +{ + StringOutputStream fullpath(256); + fullpath << path << name; + + if(path_is_absolute(fullpath.c_str())) + { + if(!file_exists(fullpath.c_str()) || file_saveBackup(fullpath.c_str())) + { + return MapResource_saveFile(format, root, Map_Traverse, fullpath.c_str()); + } + + globalErrorStream() << "failed to save a backup map file: " << makeQuoted(fullpath.c_str()) << "\n"; + return false; + } + + globalErrorStream() << "map path is not fully qualified: " << makeQuoted(fullpath.c_str()) << "\n"; + return false; +} + +namespace +{ + NodeSmartReference g_nullNode(NewNullNode()); + NodeSmartReference g_nullModel(g_nullNode); +} + +class NullModelLoader : public ModelLoader +{ +public: + scene::Node& loadModel(ArchiveFile& file) + { + return g_nullModel; + } +}; + +namespace +{ + NullModelLoader g_NullModelLoader; +} + + +/// \brief Returns the model loader for the model \p type or 0 if the model \p type has no loader module +ModelLoader* ModelLoader_forType(const char* type) +{ + const char* moduleName = findModuleName(&GlobalFiletypes(), ModelLoader::Name(), type); + if(string_not_empty(moduleName)) + { + ModelLoader* table = ReferenceAPI_getModelModules().findModule(moduleName); + if(table != 0) + { + return table; + } + else + { + globalErrorStream() << "ERROR: Model type incorrectly registered: \"" << moduleName << "\"\n"; + return &g_NullModelLoader; + } + } + return 0; +} + +NodeSmartReference ModelResource_load(ModelLoader* loader, const char* name) +{ + ScopeDisableScreenUpdates disableScreenUpdates(path_get_filename_start(name), "Loading Model"); + + NodeSmartReference model(g_nullModel); + + { + ArchiveFile* file = GlobalFileSystem().openFile(name); + + if(file != 0) + { + globalOutputStream() << "Loaded Model: \"" << name << "\"\n"; + model = loader->loadModel(*file); + file->release(); + } + else + { + globalErrorStream() << "Model load failed: \"" << name << "\"\n"; + } + } + + model.get().m_isRoot = true; + + return model; +} + + +inline hash_t path_hash(const char* path, hash_t previous = 0) +{ +#if defined(WIN32) + return string_hash_nocase(path, previous); +#else // UNIX + return string_hash(path, previous); +#endif +} + +struct PathEqual +{ + bool operator()(const CopiedString& path, const CopiedString& other) const + { + return path_equal(path.c_str(), other.c_str()); + } +}; + +struct PathHash +{ + typedef hash_t hash_type; + hash_type operator()(const CopiedString& path) const + { + return path_hash(path.c_str()); + } +}; + +typedef std::pair ModelKey; + +struct ModelKeyEqual +{ + bool operator()(const ModelKey& key, const ModelKey& other) const + { + return path_equal(key.first.c_str(), other.first.c_str()) && path_equal(key.second.c_str(), other.second.c_str()); + } +}; + +struct ModelKeyHash +{ + typedef hash_t hash_type; + hash_type operator()(const ModelKey& key) const + { + return hash_combine(path_hash(key.first.c_str()), path_hash(key.second.c_str())); + } +}; + +typedef HashTable ModelCache; +ModelCache g_modelCache; +bool g_modelCache_enabled = true; + +ModelCache::iterator ModelCache_find(const char* path, const char* name) +{ + if(g_modelCache_enabled) + { + return g_modelCache.find(ModelKey(path, name)); + } + return g_modelCache.end(); +} + +ModelCache::iterator ModelCache_insert(const char* path, const char* name, scene::Node& node) +{ + if(g_modelCache_enabled) + { + return g_modelCache.insert(ModelKey(path, name), NodeSmartReference(node)); + } + return g_modelCache.insert(ModelKey("", ""), g_nullModel); +} + +void ModelCache_flush(const char* path, const char* name) +{ + ModelCache::iterator i = g_modelCache.find(ModelKey(path, name)); + if(i != g_modelCache.end()) + { + //ASSERT_MESSAGE((*i).value.getCount() == 0, "resource flushed while still in use: " << (*i).key.first.c_str() << (*i).key.second.c_str()); + g_modelCache.erase(i); + } +} + +void ModelCache_clear() +{ + g_modelCache_enabled = false; + g_modelCache.clear(); + g_modelCache_enabled = true; +} + +NodeSmartReference Model_load(ModelLoader* loader, const char* path, const char* name, const char* type) +{ + if(loader != 0) + { + return ModelResource_load(loader, name); + } + else + { + const char* moduleName = findModuleName(&GlobalFiletypes(), MapFormat::Name(), type); + if(string_not_empty(moduleName)) + { + const MapFormat* format = ReferenceAPI_getMapModules().findModule(moduleName); + if(format != 0) + { + return MapResource_load(*format, path, name); + } + else + { + globalErrorStream() << "ERROR: Map type incorrectly registered: \"" << moduleName << "\"\n"; + return g_nullModel; + } + } + else + { + if(string_not_empty(type)) + { + globalErrorStream() << "Model type not supported: \"" << name << "\"\n"; + } + return g_nullModel; + } + } +} + +namespace +{ + bool g_realised = false; + + // name may be absolute or relative + const char* rootPath(const char* name) + { + return GlobalFileSystem().findRoot( + path_is_absolute(name) + ? name + : GlobalFileSystem().findFile(name) + ); + } +} + +struct ModelResource : public Resource +{ + NodeSmartReference m_model; + const CopiedString m_originalName; + CopiedString m_path; + CopiedString m_name; + CopiedString m_type; + ModelLoader* m_loader; + ModuleObservers m_observers; + std::time_t m_modified; + std::size_t m_unrealised; + + ModelResource(const CopiedString& name) : + m_model(g_nullModel), + m_originalName(name), + m_type(path_get_extension(name.c_str())), + m_loader(0), + m_modified(0), + m_unrealised(1) + { + m_loader = ModelLoader_forType(m_type.c_str()); + + if(g_realised) + { + realise(); + } + } + ~ModelResource() + { + if(realised()) + { + unrealise(); + } + ASSERT_MESSAGE(!realised(), "ModelResource::~ModelResource: resource reference still realised: " << makeQuoted(m_name.c_str())); + } + // NOT COPYABLE + ModelResource(const ModelResource&); + // NOT ASSIGNABLE + ModelResource& operator=(const ModelResource&); + + void setModel(const NodeSmartReference& model) + { + m_model = model; + } + void clearModel() + { + m_model = g_nullModel; + } + + void loadCached() + { + if(g_modelCache_enabled) + { + // cache lookup + ModelCache::iterator i = ModelCache_find(m_path.c_str(), m_name.c_str()); + if(i == g_modelCache.end()) + { + i = ModelCache_insert( + m_path.c_str(), + m_name.c_str(), + Model_load(m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str()) + ); + } + + setModel((*i).value); + } + else + { + setModel(Model_load(m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str())); + } + } + + void loadModel() + { + loadCached(); + connectMap(); + mapSave(); + } + + bool load() + { + ASSERT_MESSAGE(realised(), "resource not realised"); + if(m_model == g_nullModel) + { + loadModel(); + } + + return m_model != g_nullModel; + } + bool save() + { + if(!mapSaved()) + { + const char* moduleName = findModuleName(GetFileTypeRegistry(), MapFormat::Name(), m_type.c_str()); + if(string_not_empty(moduleName)) + { + const MapFormat* format = ReferenceAPI_getMapModules().findModule(moduleName); + if(format != 0 && MapResource_save(*format, m_model.get(), m_path.c_str(), m_name.c_str())) + { + mapSave(); + return true; + } + } + } + return false; + } + void flush() + { + if(realised()) + { + ModelCache_flush(m_path.c_str(), m_name.c_str()); + } + } + scene::Node* getNode() + { + //if(m_model != g_nullModel) + { + return m_model.get_pointer(); + } + //return 0; + } + void setNode(scene::Node* node) + { + ModelCache::iterator i = ModelCache_find(m_path.c_str(), m_name.c_str()); + if(i != g_modelCache.end()) + { + (*i).value = NodeSmartReference(*node); + } + setModel(NodeSmartReference(*node)); + + connectMap(); + } + void attach(ModuleObserver& observer) + { + if(realised()) + { + observer.realise(); + } + m_observers.attach(observer); + } + void detach(ModuleObserver& observer) + { + if(realised()) + { + observer.unrealise(); + } + m_observers.detach(observer); + } + bool realised() + { + return m_unrealised == 0; + } + void realise() + { + ASSERT_MESSAGE(m_unrealised != 0, "ModelResource::realise: already realised"); + if(--m_unrealised == 0) + { + m_path = rootPath(m_originalName.c_str()); + m_name = path_make_relative(m_originalName.c_str(), m_path.c_str()); + + //globalOutputStream() << "ModelResource::realise: " << m_path.c_str() << m_name.c_str() << "\n"; + + m_observers.realise(); + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + m_observers.unrealise(); + + //globalOutputStream() << "ModelResource::unrealise: " << m_path.c_str() << m_name.c_str() << "\n"; + clearModel(); + } + } + bool isMap() const + { + return Node_getMapFile(m_model) != 0; + } + void connectMap() + { + MapFile* map = Node_getMapFile(m_model); + if(map != 0) + { + map->setChangedCallback(FreeCaller()); + } + } + std::time_t modified() const + { + StringOutputStream fullpath(256); + fullpath << m_path.c_str() << m_name.c_str(); + return file_modified(fullpath.c_str()); + } + void mapSave() + { + m_modified = modified(); + MapFile* map = Node_getMapFile(m_model); + if(map != 0) + { + map->save(); + } + } + bool mapSaved() const + { + MapFile* map = Node_getMapFile(m_model); + if(map != 0) + { + return m_modified == modified() && map->saved(); + } + return true; + } + bool isModified() const + { + return ((!string_empty(m_path.c_str()) // had or has an absolute path + && m_modified != modified()) // AND disk timestamp changed + || !path_equal(rootPath(m_originalName.c_str()), m_path.c_str())); // OR absolute vfs-root changed + } + void refresh() + { + if(isModified()) + { + flush(); + unrealise(); + realise(); + } + } +}; + +class HashtableReferenceCache : public ReferenceCache, public ModuleObserver +{ + typedef HashedCache ModelReferences; + ModelReferences m_references; + std::size_t m_unrealised; + + class ModelReferencesSnapshot + { + ModelReferences& m_references; + typedef std::list Iterators; + Iterators m_iterators; + public: + typedef Iterators::iterator iterator; + ModelReferencesSnapshot(ModelReferences& references) : m_references(references) + { + for(ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i) + { + m_references.capture(i); + m_iterators.push_back(i); + } + } + ~ModelReferencesSnapshot() + { + for(Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i) + { + m_references.release(*i); + } + } + iterator begin() + { + return m_iterators.begin(); + } + iterator end() + { + return m_iterators.end(); + } + }; + +public: + + typedef ModelReferences::iterator iterator; + + HashtableReferenceCache() : m_unrealised(1) + { + } + + iterator begin() + { + return m_references.begin(); + } + iterator end() + { + return m_references.end(); + } + + void clear() + { + m_references.clear(); + } + + Resource* capture(const char* path) + { + //globalOutputStream() << "capture: \"" << path << "\"\n"; + return m_references.capture(CopiedString(path)).get(); + } + void release(const char* path) + { + m_references.release(CopiedString(path)); + //globalOutputStream() << "release: \"" << path << "\"\n"; + } + + void setEntityCreator(EntityCreator& entityCreator) + { + g_entityCreator = &entityCreator; + } + + bool realised() const + { + return m_unrealised == 0; + } + void realise() + { + ASSERT_MESSAGE(m_unrealised != 0, "HashtableReferenceCache::realise: already realised"); + if(--m_unrealised == 0) + { + g_realised = true; + + { + ModelReferencesSnapshot snapshot(m_references); + for(ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i) + { + ModelReferences::value_type& value = *(*i); + if(value.value.count() != 1) + { + value.value.get()->realise(); + } + } + } + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + g_realised = false; + + { + ModelReferencesSnapshot snapshot(m_references); + for(ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i) + { + ModelReferences::value_type& value = *(*i); + if(value.value.count() != 1) + { + value.value.get()->unrealise(); + } + } + } + + ModelCache_clear(); + } + } + void refresh() + { + ModelReferencesSnapshot snapshot(m_references); + for(ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i) + { + ModelResource* resource = (*(*i)).value.get(); + if(!resource->isMap()) + { + resource->refresh(); + } + } + } +}; + +namespace +{ + HashtableReferenceCache g_referenceCache; +} + +#if 0 +class ResourceVisitor +{ +public: + virtual void visit(const char* name, const char* path, const +}; +#endif + +void SaveReferences() +{ + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Saving Map"); + for(HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i) + { + (*i).value->save(); + } + MapChanged(); +} + +bool References_Saved() +{ + for(HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i) + { + scene::Node* node = (*i).value->getNode(); + if(node != 0) + { + MapFile* map = Node_getMapFile(*node); + if(map != 0 && !map->saved()) + { + return false; + } + } + } + return true; +} + +void RefreshReferences() +{ + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Refreshing Models"); + g_referenceCache.refresh(); +} + + +void FlushReferences() +{ + ModelCache_clear(); + + g_referenceCache.clear(); +} + +ReferenceCache& GetReferenceCache() +{ + return g_referenceCache; +} + + +#include "modulesystem/modulesmap.h" +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class ReferenceDependencies : + public GlobalRadiantModuleRef, + public GlobalFileSystemModuleRef, + public GlobalFiletypesModuleRef +{ + ModelModulesRef m_model_modules; + MapModulesRef m_map_modules; +public: + ReferenceDependencies() : + m_model_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("modeltypes")), + m_map_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("maptypes")) + { + } + ModelModules& getModelModules() + { + return m_model_modules.get(); + } + MapModules& getMapModules() + { + return m_map_modules.get(); + } +}; + +class ReferenceAPI : public TypeSystemRef +{ + ReferenceCache* m_reference; +public: + typedef ReferenceCache Type; + STRING_CONSTANT(Name, "*"); + + ReferenceAPI() + { + g_nullModel = NewNullModel(); + + GlobalFileSystem().attach(g_referenceCache); + + m_reference = &GetReferenceCache(); + } + ~ReferenceAPI() + { + GlobalFileSystem().detach(g_referenceCache); + + g_nullModel = g_nullNode; + } + ReferenceCache* getTable() + { + return m_reference; + } +}; + +typedef SingletonModule ReferenceModule; +typedef Static StaticReferenceModule; +StaticRegisterModule staticRegisterReference(StaticReferenceModule::instance()); + +ModelModules& ReferenceAPI_getModelModules() +{ + return StaticReferenceModule::instance().getDependencies().getModelModules(); +} +MapModules& ReferenceAPI_getMapModules() +{ + return StaticReferenceModule::instance().getDependencies().getMapModules(); +} diff --git a/misc/mediasource/netradiant-src/radiant/referencecache.h b/misc/mediasource/netradiant-src/radiant/referencecache.h new file mode 100644 index 00000000..32d121e7 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/referencecache.h @@ -0,0 +1,42 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (INCLUDED_REFERENCECACHE_H) +#define INCLUDED_REFERENCECACHE_H + +/// \brief Saves all open resource references if they differ from the version on disk. +void SaveReferences(); +/// \brief Flushes the cache of resource references. All resource references must be released before calling this. +void FlushReferences(); +/// \brief Reloads all resource references that differ from the version on disk. +void RefreshReferences(); + +#include "iscenegraph.h" +namespace scene +{ + class Node; +} +class MapFormat; +typedef void(*GraphTraversalFunc)(scene::Node& root, const scene::Traversable::Walker& walker); + +bool MapResource_saveFile(const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/renderer.cpp b/misc/mediasource/netradiant-src/radiant/renderer.cpp new file mode 100644 index 00000000..386653b9 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/renderer.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "renderer.h" + diff --git a/misc/mediasource/netradiant-src/radiant/renderer.h b/misc/mediasource/netradiant-src/radiant/renderer.h new file mode 100644 index 00000000..71865d62 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/renderer.h @@ -0,0 +1,199 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_RENDERER_H) +#define INCLUDED_RENDERER_H + +#include "irender.h" +#include "renderable.h" +#include "iselection.h" +#include "cullable.h" +#include "scenelib.h" +#include "math/frustum.h" +#include + +inline Cullable* Instance_getCullable(scene::Instance& instance) +{ + return InstanceTypeCast::cast(instance); +} + +inline Renderable* Instance_getRenderable(scene::Instance& instance) +{ + return InstanceTypeCast::cast(instance); +} + +inline VolumeIntersectionValue Cullable_testVisible(scene::Instance& instance, const VolumeTest& volume, VolumeIntersectionValue parentVisible) +{ + if(parentVisible == c_volumePartial) + { + Cullable* cullable = Instance_getCullable(instance); + if(cullable != 0) + { + return cullable->intersectVolume(volume, instance.localToWorld()); + } + } + return parentVisible; +} + +template +class CullingWalker +{ + const VolumeTest& m_volume; + const _Walker& m_walker; +public: + CullingWalker(const VolumeTest& volume, const _Walker& walker) + : m_volume(volume), m_walker(walker) + { + } + bool pre(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const + { + VolumeIntersectionValue visible = Cullable_testVisible(instance, m_volume, parentVisible); + if(visible != c_volumeOutside) + { + return m_walker.pre(path, instance); + } + return true; + } + void post(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const + { + return m_walker.post(path, instance); + } +}; + +template +class ForEachVisible : public scene::Graph::Walker +{ + const VolumeTest& m_volume; + const Walker_& m_walker; + mutable std::vector m_state; +public: + ForEachVisible(const VolumeTest& volume, const Walker_& walker) + : m_volume(volume), m_walker(walker) + { + m_state.push_back(c_volumePartial); + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + VolumeIntersectionValue visible = (path.top().get().visible()) ? m_state.back() : c_volumeOutside; + + if(visible == c_volumePartial) + { + visible = m_volume.TestAABB(instance.worldAABB()); + } + + m_state.push_back(visible); + + if(visible == c_volumeOutside) + { + return false; + } + else + { + return m_walker.pre(path, instance, m_state.back()); + } + } + void post(const scene::Path& path, scene::Instance& instance) const + { + if(m_state.back() != c_volumeOutside) + { + m_walker.post(path, instance, m_state.back()); + } + + m_state.pop_back(); + } +}; + +template +inline void Scene_forEachVisible(scene::Graph& graph, const VolumeTest& volume, const Functor& functor) +{ + graph.traverse(ForEachVisible< CullingWalker >(volume, CullingWalker(volume, functor))); +} + +class RenderHighlighted +{ + Renderer& m_renderer; + const VolumeTest& m_volume; +public: + RenderHighlighted(Renderer& renderer, const VolumeTest& volume) + : m_renderer(renderer), m_volume(volume) + { + } + void render(const Renderable& renderable) const + { + switch(m_renderer.getStyle()) + { + case Renderer::eFullMaterials: + renderable.renderSolid(m_renderer, m_volume); + break; + case Renderer::eWireframeOnly: + renderable.renderWireframe(m_renderer, m_volume); + break; + } + } + typedef ConstMemberCaller1 RenderCaller; + + bool pre(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const + { + m_renderer.PushState(); + + if(Cullable_testVisible(instance, m_volume, parentVisible) != c_volumeOutside) + { + Renderable* renderable = Instance_getRenderable(instance); + if(renderable) + { + renderable->viewChanged(); + } + + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 && selectable->isSelected()) + { + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + m_renderer.Highlight(Renderer::eFace); + } + else if(renderable) + { + renderable->renderComponents(m_renderer, m_volume); + } + m_renderer.Highlight(Renderer::ePrimitive); + } + + if(renderable) + { + render(*renderable); + } + } + + return true; + } + void post(const scene::Path& path, scene::Instance& instance, VolumeIntersectionValue parentVisible) const + { + m_renderer.PopState(); + } +}; + +inline void Scene_Render(Renderer& renderer, const VolumeTest& volume) +{ + GlobalSceneGraph().traverse(ForEachVisible(volume, RenderHighlighted(renderer, volume))); + GlobalShaderCache().forEachRenderable(RenderHighlighted::RenderCaller(RenderHighlighted(renderer, volume))); +} + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/renderstate.cpp b/misc/mediasource/netradiant-src/radiant/renderstate.cpp new file mode 100644 index 00000000..2f5596d1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/renderstate.cpp @@ -0,0 +1,2693 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "renderstate.h" + +#include "debugging/debugging.h" +#include "warnings.h" + +#include "ishaders.h" +#include "irender.h" +#include "itextures.h" +#include "igl.h" +#include "iglrender.h" +#include "renderable.h" +#include "qerplugin.h" + +#include +#include +#include +#include + +#include "math/matrix.h" +#include "math/aabb.h" +#include "generic/callback.h" +#include "texturelib.h" +#include "string/string.h" +#include "container/hashfunc.h" +#include "container/cache.h" +#include "generic/reference.h" +#include "moduleobservers.h" +#include "stream/filestream.h" +#include "stream/stringstream.h" +#include "os/file.h" +#include "preferences.h" + +#include "xywindow.h" + + + +#define DEBUG_RENDER 0 + +inline void debug_string(const char* string) +{ +#if(DEBUG_RENDER) + globalOutputStream() << string << "\n"; +#endif +} + +inline void debug_int(const char* comment, int i) +{ +#if(DEBUG_RENDER) + globalOutputStream() << comment << " " << i << "\n"; +#endif +} + +inline void debug_colour(const char* comment) +{ +#if(DEBUG_RENDER) + Vector4 v; + glGetFloatv(GL_CURRENT_COLOR, reinterpret_cast(&v)); + globalOutputStream() << comment << " colour: " + << v[0] << " " + << v[1] << " " + << v[2] << " " + << v[3]; + if(glIsEnabled(GL_COLOR_ARRAY)) + { + globalOutputStream() << " ARRAY"; + } + if(glIsEnabled(GL_COLOR_MATERIAL)) + { + globalOutputStream() << " MATERIAL"; + } + globalOutputStream() << "\n"; +#endif +} + +#include "timer.h" + +StringOutputStream g_renderer_stats; +std::size_t g_count_prims; +std::size_t g_count_states; +std::size_t g_count_transforms; +Timer g_timer; + +inline void count_prim() +{ + ++g_count_prims; +} + +inline void count_state() +{ + ++g_count_states; +} + +inline void count_transform() +{ + ++g_count_transforms; +} + +void Renderer_ResetStats() +{ + g_count_prims = 0; + g_count_states = 0; + g_count_transforms = 0; + g_timer.start(); +} + +const char* Renderer_GetStats() +{ + g_renderer_stats.clear(); + g_renderer_stats << "prims: " << Unsigned(g_count_prims) + << " | states: " << Unsigned(g_count_states) + << " | transforms: " << Unsigned(g_count_transforms) + << " | msec: " << g_timer.elapsed_msec(); + return g_renderer_stats.c_str(); +} + + +void printShaderLog(GLhandleARB object) +{ + GLint log_length = 0; + glGetObjectParameterivARB(object, GL_OBJECT_INFO_LOG_LENGTH_ARB, &log_length); + + Array log(log_length); + glGetInfoLogARB(object, log_length, &log_length, log.data()); + + globalErrorStream() << StringRange(log.begin(), log.begin() + log_length) << "\n"; +} + +void createShader(GLhandleARB program, const char* filename, GLenum type) +{ + GLhandleARB shader = glCreateShaderObjectARB(type); + GlobalOpenGL_debugAssertNoErrors(); + + // load shader + { + std::size_t size = file_size(filename); + FileInputStream file(filename); + ASSERT_MESSAGE(!file.failed(), "failed to open " << makeQuoted(filename)); + Array buffer(size); + size = file.read(reinterpret_cast(buffer.data()), size); + + const GLcharARB* string = buffer.data(); + GLint length = GLint(size); + glShaderSourceARB(shader, 1, &string, &length); + } + + // compile shader + { + glCompileShaderARB(shader); + + GLint compiled = 0; + glGetObjectParameterivARB(shader, GL_OBJECT_COMPILE_STATUS_ARB, &compiled); + + if(!compiled) + { + printShaderLog(shader); + } + + ASSERT_MESSAGE(compiled, "shader compile failed: " << makeQuoted(filename)); + } + + // attach shader + glAttachObjectARB(program, shader); + + glDeleteObjectARB(shader); + + GlobalOpenGL_debugAssertNoErrors(); +} + +void GLSLProgram_link(GLhandleARB program) +{ + glLinkProgramARB(program); + + GLint linked = false; + glGetObjectParameterivARB(program, GL_OBJECT_LINK_STATUS_ARB, &linked); + + if(!linked) + { + printShaderLog(program); + } + + ASSERT_MESSAGE(linked, "program link failed"); +} + +void GLSLProgram_validate(GLhandleARB program) +{ + glValidateProgramARB(program); + + GLint validated = false; + glGetObjectParameterivARB(program, GL_OBJECT_VALIDATE_STATUS_ARB, &validated); + + if(!validated) + { + printShaderLog(program); + } + + ASSERT_MESSAGE(validated, "program validation failed"); +} + +bool g_bumpGLSLPass_enabled = false; +bool g_depthfillPass_enabled = false; + +class GLSLBumpProgram : public GLProgram +{ +public: + GLhandleARB m_program; + qtexture_t* m_light_attenuation_xy; + qtexture_t* m_light_attenuation_z; + GLint u_view_origin; + GLint u_light_origin; + GLint u_light_color; + GLint u_bump_scale; + GLint u_specular_exponent; + + GLSLBumpProgram() : m_program(0), m_light_attenuation_xy(0), m_light_attenuation_z(0) + { + } + + void create() + { + // create program + m_program = glCreateProgramObjectARB(); + + // create shader + { + StringOutputStream filename(256); + filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_vp.glsl"; + createShader(m_program, filename.c_str(), GL_VERTEX_SHADER_ARB); + filename.clear(); + filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_fp.glsl"; + createShader(m_program, filename.c_str(), GL_FRAGMENT_SHADER_ARB); + } + + GLSLProgram_link(m_program); + GLSLProgram_validate(m_program); + + glUseProgramObjectARB(m_program); + + glBindAttribLocationARB(m_program, c_attr_TexCoord0, "attr_TexCoord0"); + glBindAttribLocationARB(m_program, c_attr_Tangent, "attr_Tangent"); + glBindAttribLocationARB(m_program, c_attr_Binormal, "attr_Binormal"); + + glUniform1iARB(glGetUniformLocationARB(m_program, "u_diffusemap"), 0); + glUniform1iARB(glGetUniformLocationARB(m_program, "u_bumpmap"), 1); + glUniform1iARB(glGetUniformLocationARB(m_program, "u_specularmap"), 2); + glUniform1iARB(glGetUniformLocationARB(m_program, "u_attenuationmap_xy"), 3); + glUniform1iARB(glGetUniformLocationARB(m_program, "u_attenuationmap_z"), 4); + + u_view_origin = glGetUniformLocationARB(m_program, "u_view_origin"); + u_light_origin = glGetUniformLocationARB(m_program, "u_light_origin"); + u_light_color = glGetUniformLocationARB(m_program, "u_light_color"); + u_bump_scale = glGetUniformLocationARB(m_program, "u_bump_scale"); + u_specular_exponent = glGetUniformLocationARB(m_program, "u_specular_exponent"); + + glUseProgramObjectARB(0); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void destroy() + { + glDeleteObjectARB(m_program); + m_program = 0; + } + + void enable() + { + glUseProgramObjectARB(m_program); + + glEnableVertexAttribArrayARB(c_attr_TexCoord0); + glEnableVertexAttribArrayARB(c_attr_Tangent); + glEnableVertexAttribArrayARB(c_attr_Binormal); + + GlobalOpenGL_debugAssertNoErrors(); + + debug_string("enable bump"); + g_bumpGLSLPass_enabled = true; + } + + void disable() + { + glUseProgramObjectARB(0); + + glDisableVertexAttribArrayARB(c_attr_TexCoord0); + glDisableVertexAttribArrayARB(c_attr_Tangent); + glDisableVertexAttribArrayARB(c_attr_Binormal); + + GlobalOpenGL_debugAssertNoErrors(); + + debug_string("disable bump"); + g_bumpGLSLPass_enabled = false; + } + + void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) + { + Matrix4 world2local(localToWorld); + matrix4_affine_invert(world2local); + + Vector3 localLight(origin); + matrix4_transform_point(world2local, localLight); + + Vector3 localViewer(viewer); + matrix4_transform_point(world2local, localViewer); + + Matrix4 local2light(world2light); + matrix4_multiply_by_matrix4(local2light, localToWorld); // local->world->light + + glUniform3fARB(u_view_origin, localViewer.x(), localViewer.y(), localViewer.z()); + glUniform3fARB(u_light_origin, localLight.x(), localLight.y(), localLight.z()); + glUniform3fARB(u_light_color, colour.x(), colour.y(), colour.z()); + glUniform1fARB(u_bump_scale, 1.0); + glUniform1fARB(u_specular_exponent, 32.0); + + glActiveTexture(GL_TEXTURE3); + glClientActiveTexture(GL_TEXTURE3); + + glMatrixMode(GL_TEXTURE); + glLoadMatrixf(reinterpret_cast(&local2light)); + glMatrixMode(GL_MODELVIEW); + + GlobalOpenGL_debugAssertNoErrors(); + } +}; + +GLSLBumpProgram g_bumpGLSL; + + +class GLSLDepthFillProgram : public GLProgram +{ +public: + GLhandleARB m_program; + + void create() + { + // create program + m_program = glCreateProgramObjectARB(); + + // create shader + { + StringOutputStream filename(256); + filename << GlobalRadiant().getAppPath() << "gl/zfill_vp.glsl"; + createShader(m_program, filename.c_str(), GL_VERTEX_SHADER_ARB); + filename.clear(); + filename << GlobalRadiant().getAppPath() << "gl/zfill_fp.glsl"; + createShader(m_program, filename.c_str(), GL_FRAGMENT_SHADER_ARB); + } + + GLSLProgram_link(m_program); + GLSLProgram_validate(m_program); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void destroy() + { + glDeleteObjectARB(m_program); + m_program = 0; + } + void enable() + { + glUseProgramObjectARB(m_program); + GlobalOpenGL_debugAssertNoErrors(); + debug_string("enable depthfill"); + g_depthfillPass_enabled = true; + } + void disable() + { + glUseProgramObjectARB(0); + GlobalOpenGL_debugAssertNoErrors(); + debug_string("disable depthfill"); + g_depthfillPass_enabled = false; + } + void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) + { + } +}; + +GLSLDepthFillProgram g_depthFillGLSL; + + +// ARB path + +void createProgram(const char* filename, GLenum type) +{ + std::size_t size = file_size(filename); + FileInputStream file(filename); + ASSERT_MESSAGE(!file.failed(), "failed to open " << makeQuoted(filename)); + Array buffer(size); + size = file.read(reinterpret_cast(buffer.data()), size); + + glProgramStringARB(type, GL_PROGRAM_FORMAT_ASCII_ARB, GLsizei(size), buffer.data()); + + if(GL_INVALID_OPERATION == glGetError()) + { + GLint errPos; + glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &errPos); + const GLubyte* errString = glGetString(GL_PROGRAM_ERROR_STRING_ARB); + + globalErrorStream() << reinterpret_cast(filename) << ":" << errPos << "\n" << reinterpret_cast(errString); + + ERROR_MESSAGE("error in gl program"); + } +} + +class ARBBumpProgram : public GLProgram +{ +public: + GLuint m_vertex_program; + GLuint m_fragment_program; + + void create() + { + glEnable(GL_VERTEX_PROGRAM_ARB); + glEnable(GL_FRAGMENT_PROGRAM_ARB); + + { + glGenProgramsARB(1, &m_vertex_program); + glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); + StringOutputStream filename(256); + filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_vp.glp"; + createProgram(filename.c_str(), GL_VERTEX_PROGRAM_ARB); + + glGenProgramsARB(1, &m_fragment_program); + glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); + filename.clear(); + filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_fp.glp"; + createProgram(filename.c_str(), GL_FRAGMENT_PROGRAM_ARB); + } + + glDisable(GL_VERTEX_PROGRAM_ARB); + glDisable(GL_FRAGMENT_PROGRAM_ARB); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void destroy() + { + glDeleteProgramsARB(1, &m_vertex_program); + glDeleteProgramsARB(1, &m_fragment_program); + GlobalOpenGL_debugAssertNoErrors(); + } + + void enable() + { + glEnable(GL_VERTEX_PROGRAM_ARB); + glEnable(GL_FRAGMENT_PROGRAM_ARB); + glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); + glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); + + glEnableVertexAttribArrayARB(8); + glEnableVertexAttribArrayARB(9); + glEnableVertexAttribArrayARB(10); + glEnableVertexAttribArrayARB(11); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void disable() + { + glDisable(GL_VERTEX_PROGRAM_ARB); + glDisable(GL_FRAGMENT_PROGRAM_ARB); + + glDisableVertexAttribArrayARB(8); + glDisableVertexAttribArrayARB(9); + glDisableVertexAttribArrayARB(10); + glDisableVertexAttribArrayARB(11); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) + { + Matrix4 world2local(localToWorld); + matrix4_affine_invert(world2local); + + Vector3 localLight(origin); + matrix4_transform_point(world2local, localLight); + + Vector3 localViewer(viewer); + matrix4_transform_point(world2local, localViewer); + + Matrix4 local2light(world2light); + matrix4_multiply_by_matrix4(local2light, localToWorld); // local->world->light + + // view origin + glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 4, localViewer.x(), localViewer.y(), localViewer.z(), 0); + + // light origin + glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 2, localLight.x(), localLight.y(), localLight.z(), 1); + + // light colour + glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 3, colour.x(), colour.y(), colour.z(), 0); + + // bump scale + glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, 1, 0, 0, 0); + + // specular exponent + glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 5, 32, 0, 0, 0); + + + glActiveTexture(GL_TEXTURE3); + glClientActiveTexture(GL_TEXTURE3); + + glMatrixMode(GL_TEXTURE); + glLoadMatrixf(reinterpret_cast(&local2light)); + glMatrixMode(GL_MODELVIEW); + + GlobalOpenGL_debugAssertNoErrors(); + } +}; + +class ARBDepthFillProgram : public GLProgram +{ +public: + GLuint m_vertex_program; + GLuint m_fragment_program; + + void create() + { + glEnable(GL_VERTEX_PROGRAM_ARB); + glEnable(GL_FRAGMENT_PROGRAM_ARB); + + { + glGenProgramsARB(1, &m_vertex_program); + glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); + StringOutputStream filename(256); + filename << GlobalRadiant().getAppPath() << "gl/zfill_vp.glp"; + createProgram(filename.c_str(), GL_VERTEX_PROGRAM_ARB); + + glGenProgramsARB(1, &m_fragment_program); + glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); + filename.clear(); + filename << GlobalRadiant().getAppPath() << "gl/zfill_fp.glp"; + createProgram(filename.c_str(), GL_FRAGMENT_PROGRAM_ARB); + } + + glDisable(GL_VERTEX_PROGRAM_ARB); + glDisable(GL_FRAGMENT_PROGRAM_ARB); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void destroy() + { + glDeleteProgramsARB(1, &m_vertex_program); + glDeleteProgramsARB(1, &m_fragment_program); + GlobalOpenGL_debugAssertNoErrors(); + } + + void enable() + { + glEnable(GL_VERTEX_PROGRAM_ARB); + glEnable(GL_FRAGMENT_PROGRAM_ARB); + glBindProgramARB(GL_VERTEX_PROGRAM_ARB, m_vertex_program); + glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, m_fragment_program); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void disable() + { + glDisable(GL_VERTEX_PROGRAM_ARB); + glDisable(GL_FRAGMENT_PROGRAM_ARB); + + GlobalOpenGL_debugAssertNoErrors(); + } + + void setParameters(const Vector3& viewer, const Matrix4& localToWorld, const Vector3& origin, const Vector3& colour, const Matrix4& world2light) + { + } +}; + +ARBBumpProgram g_bumpARB; +ARBDepthFillProgram g_depthFillARB; + + +#if 0 +// NV20 path (unfinished) + +void createProgram(GLint program, const char* filename, GLenum type) +{ + std::size_t size = file_size(filename); + FileInputStream file(filename); + ASSERT_MESSAGE(!file.failed(), "failed to open " << makeQuoted(filename)); + Array buffer(size); + size = file.read(reinterpret_cast(buffer.data()), size); + + glLoadProgramNV(type, program, GLsizei(size), buffer.data()); + + if(GL_INVALID_OPERATION == glGetError()) + { + GLint errPos; + glGetIntegerv(GL_PROGRAM_ERROR_POSITION_NV, &errPos); + const GLubyte* errString = glGetString(GL_PROGRAM_ERROR_STRING_NV); + + globalErrorStream() << filename << ":" << errPos << "\n" << errString; + + ERROR_MESSAGE("error in gl program"); + } +} + +GLuint m_vertex_program; +GLuint m_fragment_program; +qtexture_t* g_cube = 0; +qtexture_t* g_specular_lookup = 0; +qtexture_t* g_attenuation_xy = 0; +qtexture_t* g_attenuation_z = 0; + +void createVertexProgram() +{ + { + glGenProgramsNV(1, &m_vertex_program); + glBindProgramNV(GL_VERTEX_PROGRAM_NV, m_vertex_program); + StringOutputStream filename(256); + filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_vp.nv30"; + createProgram(m_vertex_program, filename.c_str(), GL_VERTEX_PROGRAM_NV); + + glGenProgramsNV(1, &m_fragment_program); + glBindProgramNV(GL_FRAGMENT_PROGRAM_NV, m_fragment_program); + filename.clear(); + filename << GlobalRadiant().getAppPath() << "gl/lighting_DBS_omni_fp.nv30"; + createProgram(m_fragment_program, filename.c_str(), GL_FRAGMENT_PROGRAM_NV); + } + + g_cube = GlobalTexturesCache().capture("generated/cube"); + g_specular_lookup = GlobalTexturesCache().capture("generated/specular"); + + g_attenuation_xy = GlobalTexturesCache().capture("lights/squarelight1"); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, g_attenuation_xy->texture_number); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); + + g_attenuation_z = GlobalTexturesCache().capture("lights/squarelight1a"); + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, g_attenuation_z->texture_number); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + GlobalOpenGL_debugAssertNoErrors(); +} + +void destroyVertexProgram() +{ + glDeleteProgramsNV(1, &m_vertex_program); + glDeleteProgramsNV(1, &m_fragment_program); + GlobalOpenGL_debugAssertNoErrors(); + + GlobalTexturesCache().release(g_cube); + GlobalTexturesCache().release(g_specular_lookup); + GlobalTexturesCache().release(g_attenuation_xy); + GlobalTexturesCache().release(g_attenuation_z); +} + +bool g_vertexProgram_enabled = false; + +void enableVertexProgram() +{ + //set up the register combiners + //two general combiners + glCombinerParameteriNV(GL_NUM_GENERAL_COMBINERS_NV, 2); + + //combiner 0 does tex0+tex1 -> spare0 + glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE0_ARB, + GL_UNSIGNED_IDENTITY_NV, GL_RGB); + glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_B_NV, GL_ZERO, + GL_UNSIGNED_INVERT_NV, GL_RGB); + glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_C_NV, GL_TEXTURE1_ARB, + GL_UNSIGNED_IDENTITY_NV, GL_RGB); + glCombinerInputNV(GL_COMBINER0_NV, GL_RGB, GL_VARIABLE_D_NV, GL_ZERO, + GL_UNSIGNED_INVERT_NV, GL_RGB); + glCombinerOutputNV(GL_COMBINER0_NV, GL_RGB, GL_DISCARD_NV, GL_DISCARD_NV, GL_SPARE0_NV, + GL_NONE, GL_NONE, GL_FALSE, GL_FALSE, GL_FALSE); + + //combiner 1 does tex2 dot tex3 -> spare1 + glCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_A_NV, GL_TEXTURE2_ARB, + GL_EXPAND_NORMAL_NV, GL_RGB); + glCombinerInputNV(GL_COMBINER1_NV, GL_RGB, GL_VARIABLE_B_NV, GL_TEXTURE3_ARB, + GL_EXPAND_NORMAL_NV, GL_RGB); + glCombinerOutputNV(GL_COMBINER1_NV, GL_RGB, GL_SPARE1_NV, GL_DISCARD_NV, GL_DISCARD_NV, + GL_NONE, GL_NONE, GL_TRUE, GL_FALSE, GL_FALSE); + + + + //final combiner outputs (1-spare0)*constant color 0*spare1 + //do constant color 0*spare1 in the EF multiplier + glFinalCombinerInputNV(GL_VARIABLE_E_NV, GL_SPARE1_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + glFinalCombinerInputNV(GL_VARIABLE_F_NV, GL_CONSTANT_COLOR0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + + //now do (1-spare0)*EF + glFinalCombinerInputNV(GL_VARIABLE_A_NV, GL_SPARE0_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + glFinalCombinerInputNV(GL_VARIABLE_B_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + glFinalCombinerInputNV(GL_VARIABLE_C_NV, GL_E_TIMES_F_NV, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + glFinalCombinerInputNV(GL_VARIABLE_D_NV, GL_ZERO, GL_UNSIGNED_IDENTITY_NV, GL_RGB); + + glEnable(GL_VERTEX_PROGRAM_NV); + glEnable(GL_REGISTER_COMBINERS_NV); + glBindProgramNV(GL_VERTEX_PROGRAM_NV, m_vertex_program); + glBindProgramNV(GL_FRAGMENT_PROGRAM_NV, m_fragment_program); + + glActiveTexture(GL_TEXTURE0); + glEnable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE1); + glEnable(GL_TEXTURE_1D); + glActiveTexture(GL_TEXTURE2); + glEnable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE3); + glEnable(GL_TEXTURE_2D); + + glEnableClientState(GL_VERTEX_ATTRIB_ARRAY8_NV); + glEnableClientState(GL_VERTEX_ATTRIB_ARRAY9_NV); + glEnableClientState(GL_VERTEX_ATTRIB_ARRAY10_NV); + glEnableClientState(GL_VERTEX_ATTRIB_ARRAY11_NV); + + GlobalOpenGL_debugAssertNoErrors(); + g_vertexProgram_enabled = true; +} + +void disableVertexProgram() +{ + glDisable(GL_VERTEX_PROGRAM_NV); + glDisable(GL_REGISTER_COMBINERS_NV); + + glActiveTexture(GL_TEXTURE0); + glDisable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE1); + glDisable(GL_TEXTURE_1D); + glActiveTexture(GL_TEXTURE2); + glDisable(GL_TEXTURE_2D); + glActiveTexture(GL_TEXTURE3); + glDisable(GL_TEXTURE_2D); + + glDisableClientState(GL_VERTEX_ATTRIB_ARRAY8_NV); + glDisableClientState(GL_VERTEX_ATTRIB_ARRAY9_NV); + glDisableClientState(GL_VERTEX_ATTRIB_ARRAY10_NV); + glDisableClientState(GL_VERTEX_ATTRIB_ARRAY11_NV); + + GlobalOpenGL_debugAssertNoErrors(); + g_vertexProgram_enabled = false; +} + +class GLstringNV +{ +public: + const GLubyte* m_string; + const GLint m_length; + GLstringNV(const char* string) : m_string(reinterpret_cast(string)), m_length(GLint(string_length(string))) + { + } +}; + +GLstringNV g_light_origin("light_origin"); +GLstringNV g_view_origin("view_origin"); +GLstringNV g_light_color("light_color"); +GLstringNV g_bumpGLSL_scale("bump_scale"); +GLstringNV g_specular_exponent("specular_exponent"); + +void setVertexProgramEnvironment(const Vector3& localViewer) +{ + Matrix4 local2light(g_matrix4_identity); + matrix4_translate_by_vec3(local2light, Vector3(0.5, 0.5, 0.5)); + matrix4_scale_by_vec3(local2light, Vector3(0.5, 0.5, 0.5)); + matrix4_scale_by_vec3(local2light, Vector3(1.0 / 512.0, 1.0 / 512.0, 1.0 / 512.0)); + matrix4_translate_by_vec3(local2light, vector3_negated(localViewer)); + + glActiveTexture(GL_TEXTURE3); + glClientActiveTexture(GL_TEXTURE3); + + glMatrixMode(GL_TEXTURE); + glLoadMatrixf(reinterpret_cast(&local2light)); + glMatrixMode(GL_MODELVIEW); + + glTrackMatrixNV(GL_VERTEX_PROGRAM_NV, 0, GL_MODELVIEW_PROJECTION_NV, GL_IDENTITY_NV); + glTrackMatrixNV(GL_VERTEX_PROGRAM_NV, 4, GL_TEXTURE0_ARB, GL_IDENTITY_NV); + + // view origin + //qglProgramNamedParameter4fNV(m_fragment_program, g_view_origin.m_length, g_view_origin.m_string, localViewer.x(), localViewer.y(), localViewer.z(), 0); + + // light origin + glProgramParameter4fNV(GL_VERTEX_PROGRAM_NV, 8, localViewer.x(), localViewer.y(), localViewer.z(), 1.0f); + + // light colour + glCombinerParameterfNV(GL_CONSTANT_COLOR0_NV, 1, 1, 1, 1) + + // bump scale + //qglProgramNamedParameter4fNV(m_fragment_program, g_bumpGLSL_scale.m_length, g_bumpGLSL_scale.m_string, 1, 0, 0, 0); + + // specular exponent + //qglProgramNamedParameter4fNV(m_fragment_program, g_specular_exponent.m_length, g_specular_exponent.m_string, 32, 0, 0, 0); + + GlobalOpenGL_debugAssertNoErrors(); +} + +#endif + + +bool g_vertexArray_enabled = false; +bool g_normalArray_enabled = false; +bool g_texcoordArray_enabled = false; +bool g_colorArray_enabled = false; + +inline bool OpenGLState_less(const OpenGLState& self, const OpenGLState& other) +{ + //! Sort by sort-order override. + if(self.m_sort != other.m_sort) + { + return self.m_sort < other.m_sort; + } + //! Sort by texture handle. + if(self.m_texture != other.m_texture) + { + return self.m_texture < other.m_texture; + } + if(self.m_texture1 != other.m_texture1) + { + return self.m_texture1 < other.m_texture1; + } + if(self.m_texture2 != other.m_texture2) + { + return self.m_texture2 < other.m_texture2; + } + if(self.m_texture3 != other.m_texture3) + { + return self.m_texture3 < other.m_texture3; + } + if(self.m_texture4 != other.m_texture4) + { + return self.m_texture4 < other.m_texture4; + } + if(self.m_texture5 != other.m_texture5) + { + return self.m_texture5 < other.m_texture5; + } + if(self.m_texture6 != other.m_texture6) + { + return self.m_texture6 < other.m_texture6; + } + if(self.m_texture7 != other.m_texture7) + { + return self.m_texture7 < other.m_texture7; + } + //! Sort by state bit-vector. + if(self.m_state != other.m_state) + { + return self.m_state < other.m_state; + } + //! Comparing address makes sure states are never equal. + return &self < &other; +} + +void OpenGLState_constructDefault(OpenGLState& state) +{ + state.m_state = RENDER_DEFAULT; + + state.m_texture = 0; + state.m_texture1 = 0; + state.m_texture2 = 0; + state.m_texture3 = 0; + state.m_texture4 = 0; + state.m_texture5 = 0; + state.m_texture6 = 0; + state.m_texture7 = 0; + + state.m_colour[0] = 1; + state.m_colour[1] = 1; + state.m_colour[2] = 1; + state.m_colour[3] = 1; + + state.m_depthfunc = GL_LESS; + + state.m_blend_src = GL_SRC_ALPHA; + state.m_blend_dst = GL_ONE_MINUS_SRC_ALPHA; + + state.m_alphafunc = GL_ALWAYS; + state.m_alpharef = 0; + + state.m_linewidth = 1; + state.m_pointsize = 1; + + state.m_linestipple_factor = 1; + state.m_linestipple_pattern = 0xaaaa; + + state.m_fog = OpenGLFogState(); +} + + + + +/// \brief A container of Renderable references. +/// May contain the same Renderable multiple times, with different transforms. +class OpenGLStateBucket +{ +public: + struct RenderTransform + { + const Matrix4* m_transform; + const OpenGLRenderable *m_renderable; + const RendererLight* m_light; + + RenderTransform(const OpenGLRenderable& renderable, const Matrix4& transform, const RendererLight* light) + : m_transform(&transform), m_renderable(&renderable), m_light(light) + { + } + }; + + typedef std::vector Renderables; + +private: + + OpenGLState m_state; + Renderables m_renderables; + +public: + OpenGLStateBucket() + { + } + void addRenderable(const OpenGLRenderable& renderable, const Matrix4& modelview, const RendererLight* light = 0) + { + m_renderables.push_back(RenderTransform(renderable, modelview, light)); + } + + OpenGLState& state() + { + return m_state; + } + + void render(OpenGLState& current, unsigned int globalstate, const Vector3& viewer); +}; + +#define LIGHT_SHADER_DEBUG 0 + +#if LIGHT_SHADER_DEBUG +typedef std::vector LightDebugShaders; +LightDebugShaders g_lightDebugShaders; +#endif + +class OpenGLStateLess +{ +public: + bool operator()(const OpenGLState& self, const OpenGLState& other) const + { + return OpenGLState_less(self, other); + } +}; + +typedef ConstReference OpenGLStateReference; +typedef std::map OpenGLStates; +OpenGLStates g_state_sorted; + +class OpenGLStateBucketAdd +{ + OpenGLStateBucket& m_bucket; + const OpenGLRenderable& m_renderable; + const Matrix4& m_modelview; +public: + typedef const RendererLight& first_argument_type; + + OpenGLStateBucketAdd(OpenGLStateBucket& bucket, const OpenGLRenderable& renderable, const Matrix4& modelview) : + m_bucket(bucket), m_renderable(renderable), m_modelview(modelview) + { + } + void operator()(const RendererLight& light) + { + m_bucket.addRenderable(m_renderable, m_modelview, &light); + } +}; + +class CountLights +{ + std::size_t m_count; +public: + typedef RendererLight& first_argument_type; + + CountLights() : m_count(0) + { + } + void operator()(const RendererLight& light) + { + ++m_count; + } + std::size_t count() const + { + return m_count; + } +}; + +class OpenGLShader : public Shader +{ + typedef std::list Passes; + Passes m_passes; + IShader* m_shader; + std::size_t m_used; + ModuleObservers m_observers; +public: + OpenGLShader() : m_shader(0), m_used(0) + { + } + ~OpenGLShader() + { + } + void construct(const char* name); + void destroy() + { + if(m_shader) + { + m_shader->DecRef(); + } + m_shader = 0; + + for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) + { + delete *i; + } + m_passes.clear(); + } + void addRenderable(const OpenGLRenderable& renderable, const Matrix4& modelview, const LightList* lights) + { + for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) + { +#if LIGHT_SHADER_DEBUG + if(((*i)->state().m_state & RENDER_BUMP) != 0) + { + if(lights != 0) + { + CountLights counter; + lights->forEachLight(makeCallback1(counter)); + globalOutputStream() << "count = " << counter.count() << "\n"; + for(std::size_t i = 0; i < counter.count(); ++i) + { + g_lightDebugShaders[counter.count()]->addRenderable(renderable, modelview); + } + } + } + else +#else + if(((*i)->state().m_state & RENDER_BUMP) != 0) + { + if(lights != 0) + { + OpenGLStateBucketAdd add(*(*i), renderable, modelview); + lights->forEachLight(makeCallback1(add)); + } + } + else +#endif + { + (*i)->addRenderable(renderable, modelview); + } + } + } + void incrementUsed() + { + if(++m_used == 1 && m_shader != 0) + { + m_shader->SetInUse(true); + } + } + void decrementUsed() + { + if(--m_used == 0 && m_shader != 0) + { + m_shader->SetInUse(false); + } + } + bool realised() const + { + return m_shader != 0; + } + void attach(ModuleObserver& observer) + { + if(realised()) + { + observer.realise(); + } + m_observers.attach(observer); + } + void detach(ModuleObserver& observer) + { + if(realised()) + { + observer.unrealise(); + } + m_observers.detach(observer); + } + void realise(const CopiedString& name) + { + construct(name.c_str()); + + if(m_used != 0 && m_shader != 0) + { + m_shader->SetInUse(true); + } + + for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) + { + g_state_sorted.insert(OpenGLStates::value_type(OpenGLStateReference((*i)->state()), *i)); + } + + m_observers.realise(); + } + void unrealise() + { + m_observers.unrealise(); + + for(Passes::iterator i = m_passes.begin(); i != m_passes.end(); ++i) + { + g_state_sorted.erase(OpenGLStateReference((*i)->state())); + } + + destroy(); + } + qtexture_t& getTexture() const + { + ASSERT_NOTNULL(m_shader); + return *m_shader->getTexture(); + } + unsigned int getFlags() const + { + ASSERT_NOTNULL(m_shader); + return m_shader->getFlags(); + } + IShader& getShader() const + { + ASSERT_NOTNULL(m_shader); + return *m_shader; + } + OpenGLState& appendDefaultPass() + { + m_passes.push_back(new OpenGLStateBucket); + OpenGLState& state = m_passes.back()->state(); + OpenGLState_constructDefault(state); + return state; + } +}; + + +inline bool lightEnabled(const RendererLight& light, const LightCullable& cullable) +{ + return cullable.testLight(light); +} + +typedef std::set RendererLights; + +#define DEBUG_LIGHT_SYNC 0 + +class LinearLightList : public LightList +{ + LightCullable& m_cullable; + RendererLights& m_allLights; + Callback m_evaluateChanged; + + typedef std::list Lights; + mutable Lights m_lights; + mutable bool m_lightsChanged; +public: + LinearLightList(LightCullable& cullable, RendererLights& lights, const Callback& evaluateChanged) : + m_cullable(cullable), m_allLights(lights), m_evaluateChanged(evaluateChanged) + { + m_lightsChanged = true; + } + void evaluateLights() const + { + m_evaluateChanged(); + if(m_lightsChanged) + { + m_lightsChanged = false; + + m_lights.clear(); + m_cullable.clearLights(); + for(RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i) + { + if(lightEnabled(*(*i), m_cullable)) + { + m_lights.push_back(*i); + m_cullable.insertLight(*(*i)); + } + } + } +#if(DEBUG_LIGHT_SYNC) + else + { + Lights lights; + for(RendererLights::const_iterator i = m_allLights.begin(); i != m_allLights.end(); ++i) + { + if(lightEnabled(*(*i), m_cullable)) + { + lights.push_back(*i); + } + } + ASSERT_MESSAGE( + !std::lexicographical_compare(lights.begin(), lights.end(), m_lights.begin(), m_lights.end()) + && !std::lexicographical_compare(m_lights.begin(), m_lights.end(), lights.begin(), lights.end()), + "lights out of sync" + ); + } +#endif + } + void forEachLight(const RendererLightCallback& callback) const + { + evaluateLights(); + + for(Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i) + { + callback(*(*i)); + } + } + void lightsChanged() const + { + m_lightsChanged = true; + } +}; + +inline void setFogState(const OpenGLFogState& state) +{ + glFogi(GL_FOG_MODE, state.mode); + glFogf(GL_FOG_DENSITY, state.density); + glFogf(GL_FOG_START, state.start); + glFogf(GL_FOG_END, state.end); + glFogi(GL_FOG_INDEX, state.index); + glFogfv(GL_FOG_COLOR, vector4_to_array(state.colour)); +} + +#define DEBUG_SHADERS 0 + +class OpenGLShaderCache : public ShaderCache, public TexturesCacheObserver, public ModuleObserver +{ + class CreateOpenGLShader + { + OpenGLShaderCache* m_cache; + public: + explicit CreateOpenGLShader(OpenGLShaderCache* cache = 0) + : m_cache(cache) + { + } + OpenGLShader* construct(const CopiedString& name) + { + OpenGLShader* shader = new OpenGLShader; + if(m_cache->realised()) + { + shader->realise(name); + } + return shader; + } + void destroy(OpenGLShader* shader) + { + if(m_cache->realised()) + { + shader->unrealise(); + } + delete shader; + } + }; + + typedef HashedCache, CreateOpenGLShader> Shaders; + Shaders m_shaders; + std::size_t m_unrealised; + + bool m_lightingEnabled; + bool m_lightingSupported; + bool m_useShaderLanguage; + +public: + OpenGLShaderCache() + : m_shaders(CreateOpenGLShader(this)), + m_unrealised(3), // wait until shaders, gl-context and textures are realised before creating any render-states + m_lightingEnabled(true), + m_lightingSupported(false), + m_useShaderLanguage(false), + m_lightsChanged(true), + m_traverseRenderablesMutex(false) + { + } + ~OpenGLShaderCache() + { + for(Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i) + { + globalOutputStream() << "leaked shader: " << makeQuoted((*i).key.c_str()) << "\n"; + } + } + Shader* capture(const char* name) + { + ASSERT_MESSAGE(name[0] == '$' + || *name == '[' + || *name == '<' + || *name == '(' + || strchr(name, '\\') == 0, "shader name contains invalid characters: \"" << name << "\""); +#if DEBUG_SHADERS + globalOutputStream() << "shaders capture: " << makeQuoted(name) << '\n'; +#endif + return m_shaders.capture(name).get(); + } + void release(const char *name) + { +#if DEBUG_SHADERS + globalOutputStream() << "shaders release: " << makeQuoted(name) << '\n'; +#endif + m_shaders.release(name); + } + void render(RenderStateFlags globalstate, const Matrix4& modelview, const Matrix4& projection, const Vector3& viewer) + { + glMatrixMode(GL_PROJECTION); + glLoadMatrixf(reinterpret_cast(&projection)); + #if 0 + //qglGetFloatv(GL_PROJECTION_MATRIX, reinterpret_cast(&projection)); + #endif + + glMatrixMode(GL_MODELVIEW); + glLoadMatrixf(reinterpret_cast(&modelview)); + #if 0 + //qglGetFloatv(GL_MODELVIEW_MATRIX, reinterpret_cast(&modelview)); + #endif + + ASSERT_MESSAGE(realised(), "render states are not realised"); + + // global settings that are not set in renderstates + glFrontFace(GL_CW); + glCullFace(GL_BACK); + glPolygonOffset(-1, 1); + { + const GLubyte pattern[132] = { + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55, + 0xAA, 0xAA, 0xAA, 0xAA, 0x55, 0x55, 0x55, 0x55 + }; + glPolygonStipple(pattern); + } + glEnableClientState(GL_VERTEX_ARRAY); + g_vertexArray_enabled = true; + glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); + + if(GlobalOpenGL().GL_1_3()) + { + glActiveTexture(GL_TEXTURE0); + glClientActiveTexture(GL_TEXTURE0); + } + + if(GlobalOpenGL().ARB_shader_objects()) + { + glUseProgramObjectARB(0); + glDisableVertexAttribArrayARB(c_attr_TexCoord0); + glDisableVertexAttribArrayARB(c_attr_Tangent); + glDisableVertexAttribArrayARB(c_attr_Binormal); + } + + if(globalstate & RENDER_TEXTURE) + { + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + } + + OpenGLState current; + OpenGLState_constructDefault(current); + current.m_sort = OpenGLState::eSortFirst; + + // default renderstate settings + glLineStipple(current.m_linestipple_factor, current.m_linestipple_pattern); + glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + g_texcoordArray_enabled = false; + glDisableClientState(GL_COLOR_ARRAY); + g_colorArray_enabled = false; + glDisableClientState(GL_NORMAL_ARRAY); + g_normalArray_enabled = false; + glDisable(GL_BLEND); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glDisable(GL_CULL_FACE); + glShadeModel(GL_FLAT); + glDisable(GL_DEPTH_TEST); + glDepthMask(GL_FALSE); + glDisable(GL_ALPHA_TEST); + glDisable(GL_LINE_STIPPLE); + glDisable(GL_POLYGON_STIPPLE); + glDisable(GL_POLYGON_OFFSET_LINE); + + glBindTexture(GL_TEXTURE_2D, 0); + glColor4f(1,1,1,1); + glDepthFunc(GL_LESS); + glAlphaFunc(GL_ALWAYS, 0); + glLineWidth(1); + glPointSize(1); + + glHint(GL_FOG_HINT, GL_NICEST); + glDisable(GL_FOG); + setFogState(OpenGLFogState()); + + GlobalOpenGL_debugAssertNoErrors(); + + debug_string("begin rendering"); + for(OpenGLStates::iterator i = g_state_sorted.begin(); i != g_state_sorted.end(); ++i) + { + (*i).second->render(current, globalstate, viewer); + } + debug_string("end rendering"); + } + void realise() + { + if(--m_unrealised == 0) + { + if(lightingSupported() && lightingEnabled()) + { + if(useShaderLanguage()) + { + g_bumpGLSL.create(); + g_depthFillGLSL.create(); + } + else + { + g_bumpARB.create(); + g_depthFillARB.create(); + } + } + + for(Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i) + { + if(!(*i).value.empty()) + { + (*i).value->realise(i->key); + } + } + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + for(Shaders::iterator i = m_shaders.begin(); i != m_shaders.end(); ++i) + { + if(!(*i).value.empty()) + { + (*i).value->unrealise(); + } + } + if(GlobalOpenGL().contextValid && lightingSupported() && lightingEnabled()) + { + if(useShaderLanguage()) + { + g_bumpGLSL.destroy(); + g_depthFillGLSL.destroy(); + } + else + { + g_bumpARB.destroy(); + g_depthFillARB.destroy(); + } + } + } + } + bool realised() + { + return m_unrealised == 0; + } + + + bool lightingEnabled() const + { + return m_lightingEnabled; + } + bool lightingSupported() const + { + return m_lightingSupported; + } + bool useShaderLanguage() const + { + return m_useShaderLanguage; + } + void setLighting(bool supported, bool enabled) + { + bool refresh = (m_lightingSupported && m_lightingEnabled) != (supported && enabled); + + if(refresh) + { + unrealise(); + GlobalShaderSystem().setLightingEnabled(supported && enabled); + } + + m_lightingSupported = supported; + m_lightingEnabled = enabled; + + if(refresh) + { + realise(); + } + } + void extensionsInitialised() + { + setLighting(GlobalOpenGL().GL_1_3() + && GlobalOpenGL().ARB_vertex_program() + && GlobalOpenGL().ARB_fragment_program() + && GlobalOpenGL().ARB_shader_objects() + && GlobalOpenGL().ARB_vertex_shader() + && GlobalOpenGL().ARB_fragment_shader() + && GlobalOpenGL().ARB_shading_language_100(), + m_lightingEnabled + ); + + if(!lightingSupported()) + { + globalOutputStream() << "Lighting mode requires OpenGL features not supported by your graphics drivers:\n"; + if(!GlobalOpenGL().GL_1_3()) + { + globalOutputStream() << " GL version 1.3 or better\n"; + } + if(!GlobalOpenGL().ARB_vertex_program()) + { + globalOutputStream() << " GL_ARB_vertex_program\n"; + } + if(!GlobalOpenGL().ARB_fragment_program()) + { + globalOutputStream() << " GL_ARB_fragment_program\n"; + } + if(!GlobalOpenGL().ARB_shader_objects()) + { + globalOutputStream() << " GL_ARB_shader_objects\n"; + } + if(!GlobalOpenGL().ARB_vertex_shader()) + { + globalOutputStream() << " GL_ARB_vertex_shader\n"; + } + if(!GlobalOpenGL().ARB_fragment_shader()) + { + globalOutputStream() << " GL_ARB_fragment_shader\n"; + } + if(!GlobalOpenGL().ARB_shading_language_100()) + { + globalOutputStream() << " GL_ARB_shading_language_100\n"; + } + } + } + void setLightingEnabled(bool enabled) + { + setLighting(m_lightingSupported, enabled); + } + + // light culling + + RendererLights m_lights; + bool m_lightsChanged; + typedef std::map LightLists; + LightLists m_lightLists; + + const LightList& attach(LightCullable& cullable) + { + return (*m_lightLists.insert(LightLists::value_type(&cullable, LinearLightList(cullable, m_lights, EvaluateChangedCaller(*this)))).first).second; + } + void detach(LightCullable& cullable) + { + m_lightLists.erase(&cullable); + } + void changed(LightCullable& cullable) + { + LightLists::iterator i = m_lightLists.find(&cullable); + ASSERT_MESSAGE(i != m_lightLists.end(), "cullable not attached"); + (*i).second.lightsChanged(); + } + void attach(RendererLight& light) + { + ASSERT_MESSAGE(m_lights.find(&light) == m_lights.end(), "light could not be attached"); + m_lights.insert(&light); + changed(light); + } + void detach(RendererLight& light) + { + ASSERT_MESSAGE(m_lights.find(&light) != m_lights.end(), "light could not be detached"); + m_lights.erase(&light); + changed(light); + } + void changed(RendererLight& light) + { + m_lightsChanged = true; + } + void evaluateChanged() + { + if(m_lightsChanged) + { + m_lightsChanged = false; + for(LightLists::iterator i = m_lightLists.begin(); i != m_lightLists.end(); ++i) + { + (*i).second.lightsChanged(); + } + } + } + typedef MemberCaller EvaluateChangedCaller; + + typedef std::set Renderables; + Renderables m_renderables; + mutable bool m_traverseRenderablesMutex; + + // renderables + void attachRenderable(const Renderable& renderable) + { + ASSERT_MESSAGE(!m_traverseRenderablesMutex, "attaching renderable during traversal"); + ASSERT_MESSAGE(m_renderables.find(&renderable) == m_renderables.end(), "renderable could not be attached"); + m_renderables.insert(&renderable); + } + void detachRenderable(const Renderable& renderable) + { + ASSERT_MESSAGE(!m_traverseRenderablesMutex, "detaching renderable during traversal"); + ASSERT_MESSAGE(m_renderables.find(&renderable) != m_renderables.end(), "renderable could not be detached"); + m_renderables.erase(&renderable); + } + void forEachRenderable(const RenderableCallback& callback) const + { + ASSERT_MESSAGE(!m_traverseRenderablesMutex, "for-each during traversal"); + m_traverseRenderablesMutex = true; + for(Renderables::const_iterator i = m_renderables.begin(); i != m_renderables.end(); ++i) + { + callback(*(*i)); + } + m_traverseRenderablesMutex = false; + } +}; + +static OpenGLShaderCache* g_ShaderCache; + +void ShaderCache_extensionsInitialised() +{ + g_ShaderCache->extensionsInitialised(); +} + +void ShaderCache_setBumpEnabled(bool enabled) +{ + g_ShaderCache->setLightingEnabled(enabled); +} + + +Vector3 g_DebugShaderColours[256]; +Shader* g_defaultPointLight = 0; + +void ShaderCache_Construct() +{ + g_ShaderCache = new OpenGLShaderCache; + GlobalTexturesCache().attach(*g_ShaderCache); + GlobalShaderSystem().attach(*g_ShaderCache); + + if(g_pGameDescription->mGameType == "doom3") + { + g_defaultPointLight = g_ShaderCache->capture("lights/defaultPointLight"); + //Shader* overbright = + g_ShaderCache->capture("$OVERBRIGHT"); + +#if LIGHT_SHADER_DEBUG + for(std::size_t i = 0; i < 256; ++i) + { + g_DebugShaderColours[i] = Vector3(i / 256.0, i / 256.0, i / 256.0); + } + + g_DebugShaderColours[0] = Vector3(1, 0, 0); + g_DebugShaderColours[1] = Vector3(1, 0.5, 0); + g_DebugShaderColours[2] = Vector3(1, 1, 0); + g_DebugShaderColours[3] = Vector3(0.5, 1, 0); + g_DebugShaderColours[4] = Vector3(0, 1, 0); + g_DebugShaderColours[5] = Vector3(0, 1, 0.5); + g_DebugShaderColours[6] = Vector3(0, 1, 1); + g_DebugShaderColours[7] = Vector3(0, 0.5, 1); + g_DebugShaderColours[8] = Vector3(0, 0, 1); + g_DebugShaderColours[9] = Vector3(0.5, 0, 1); + g_DebugShaderColours[10] = Vector3(1, 0, 1); + g_DebugShaderColours[11] = Vector3(1, 0, 0.5); + + g_lightDebugShaders.reserve(256); + StringOutputStream buffer(256); + for(std::size_t i = 0; i < 256; ++i) + { + buffer << "(" << g_DebugShaderColours[i].x() << " " << g_DebugShaderColours[i].y() << " " << g_DebugShaderColours[i].z() << ")"; + g_lightDebugShaders.push_back(g_ShaderCache->capture(buffer.c_str())); + buffer.clear(); + } +#endif + } +} + +void ShaderCache_Destroy() +{ + if(g_pGameDescription->mGameType == "doom3") + { + g_ShaderCache->release("lights/defaultPointLight"); + g_ShaderCache->release("$OVERBRIGHT"); + g_defaultPointLight = 0; + +#if LIGHT_SHADER_DEBUG + g_lightDebugShaders.clear(); + StringOutputStream buffer(256); + for(std::size_t i = 0; i < 256; ++i) + { + buffer << "(" << g_DebugShaderColours[i].x() << " " << g_DebugShaderColours[i].y() << " " << g_DebugShaderColours[i].z() << ")"; + g_ShaderCache->release(buffer.c_str()); + } +#endif + } + + GlobalShaderSystem().detach(*g_ShaderCache); + GlobalTexturesCache().detach(*g_ShaderCache); + delete g_ShaderCache; +} + +ShaderCache* GetShaderCache() +{ + return g_ShaderCache; +} + +inline void setTextureState(GLint& current, const GLint& texture, GLenum textureUnit) +{ + if(texture != current) + { + glActiveTexture(textureUnit); + glClientActiveTexture(textureUnit); + glBindTexture(GL_TEXTURE_2D, texture); + GlobalOpenGL_debugAssertNoErrors(); + current = texture; + } +} + +inline void setTextureState(GLint& current, const GLint& texture) +{ + if(texture != current) + { + glBindTexture(GL_TEXTURE_2D, texture); + GlobalOpenGL_debugAssertNoErrors(); + current = texture; + } +} + +inline void setState(unsigned int state, unsigned int delta, unsigned int flag, GLenum glflag) +{ + if(delta & state & flag) + { + glEnable(glflag); + GlobalOpenGL_debugAssertNoErrors(); + } + else if(delta & ~state & flag) + { + glDisable(glflag); + GlobalOpenGL_debugAssertNoErrors(); + } +} + +void OpenGLState_apply(const OpenGLState& self, OpenGLState& current, unsigned int globalstate) +{ + debug_int("sort", int(self.m_sort)); + debug_int("texture", self.m_texture); + debug_int("state", self.m_state); + debug_int("address", int(std::size_t(&self))); + + count_state(); + + if(self.m_state & RENDER_OVERRIDE) + { + globalstate |= RENDER_FILL | RENDER_DEPTHWRITE; + } + + const unsigned int state = self.m_state & globalstate; + const unsigned int delta = state ^ current.m_state; + + GlobalOpenGL_debugAssertNoErrors(); + + GLProgram* program = (state & RENDER_PROGRAM) != 0 ? self.m_program : 0; + + if(program != current.m_program) + { + if(current.m_program != 0) + { + current.m_program->disable(); + glColor4fv(vector4_to_array(current.m_colour)); + debug_colour("cleaning program"); + } + + current.m_program = program; + + if(current.m_program != 0) + { + current.m_program->enable(); + } + } + + if(delta & state & RENDER_FILL) + { + //qglPolygonMode (GL_BACK, GL_LINE); + //qglPolygonMode (GL_FRONT, GL_FILL); + glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); + GlobalOpenGL_debugAssertNoErrors(); + } + else if(delta & ~state & RENDER_FILL) + { + glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); + GlobalOpenGL_debugAssertNoErrors(); + } + + setState(state, delta, RENDER_OFFSETLINE, GL_POLYGON_OFFSET_LINE); + + if(delta & state & RENDER_LIGHTING) + { + glEnable(GL_LIGHTING); + glEnable(GL_COLOR_MATERIAL); + //qglEnable(GL_RESCALE_NORMAL); + glEnableClientState(GL_NORMAL_ARRAY); + GlobalOpenGL_debugAssertNoErrors(); + g_normalArray_enabled = true; + } + else if(delta & ~state & RENDER_LIGHTING) + { + glDisable(GL_LIGHTING); + glDisable(GL_COLOR_MATERIAL); + //qglDisable(GL_RESCALE_NORMAL); + glDisableClientState(GL_NORMAL_ARRAY); + GlobalOpenGL_debugAssertNoErrors(); + g_normalArray_enabled = false; + } + + if(delta & state & RENDER_TEXTURE) + { + GlobalOpenGL_debugAssertNoErrors(); + + if(GlobalOpenGL().GL_1_3()) + { + glActiveTexture(GL_TEXTURE0); + glClientActiveTexture(GL_TEXTURE0); + } + + glEnable(GL_TEXTURE_2D); + + glColor4f(1,1,1,self.m_colour[3]); + debug_colour("setting texture"); + + glEnableClientState(GL_TEXTURE_COORD_ARRAY); + GlobalOpenGL_debugAssertNoErrors(); + g_texcoordArray_enabled = true; + } + else if(delta & ~state & RENDER_TEXTURE) + { + if(GlobalOpenGL().GL_1_3()) + { + glActiveTexture(GL_TEXTURE0); + glClientActiveTexture(GL_TEXTURE0); + } + + glDisable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, 0); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + + GlobalOpenGL_debugAssertNoErrors(); + g_texcoordArray_enabled = false; + } + + if(delta & state & RENDER_BLEND) + { +// FIXME: some .TGA are buggy, have a completely empty alpha channel +// if such brushes are rendered in this loop they would be totally transparent with GL_MODULATE +// so I decided using GL_DECAL instead +// if an empty-alpha-channel or nearly-empty texture is used. It will be blank-transparent. +// this could get better if you can get glTexEnviv (GL_TEXTURE_ENV, to work .. patches are welcome + + glEnable(GL_BLEND); + if(GlobalOpenGL().GL_1_3()) + { + glActiveTexture(GL_TEXTURE0); + } + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); + GlobalOpenGL_debugAssertNoErrors(); + } + else if(delta & ~state & RENDER_BLEND) + { + glDisable(GL_BLEND); + if(GlobalOpenGL().GL_1_3()) + { + glActiveTexture(GL_TEXTURE0); + } + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + GlobalOpenGL_debugAssertNoErrors(); + } + + setState(state, delta, RENDER_CULLFACE, GL_CULL_FACE); + + if(delta & state & RENDER_SMOOTH) + { + glShadeModel(GL_SMOOTH); + GlobalOpenGL_debugAssertNoErrors(); + } + else if(delta & ~state & RENDER_SMOOTH) + { + glShadeModel(GL_FLAT); + GlobalOpenGL_debugAssertNoErrors(); + } + + setState(state, delta, RENDER_SCALED, GL_NORMALIZE); // not GL_RESCALE_NORMAL + + setState(state, delta, RENDER_DEPTHTEST, GL_DEPTH_TEST); + + if(delta & state & RENDER_DEPTHWRITE) + { + glDepthMask(GL_TRUE); + +#if DEBUG_RENDER + GLboolean depthEnabled; + glGetBooleanv(GL_DEPTH_WRITEMASK, &depthEnabled); + ASSERT_MESSAGE(depthEnabled, "failed to set depth buffer mask bit"); +#endif + debug_string("enabled depth-buffer writing"); + + GlobalOpenGL_debugAssertNoErrors(); + } + else if(delta & ~state & RENDER_DEPTHWRITE) + { + glDepthMask(GL_FALSE); + +#if DEBUG_RENDER + GLboolean depthEnabled; + glGetBooleanv(GL_DEPTH_WRITEMASK, &depthEnabled); + ASSERT_MESSAGE(!depthEnabled, "failed to set depth buffer mask bit"); +#endif + debug_string("disabled depth-buffer writing"); + + GlobalOpenGL_debugAssertNoErrors(); + } + + if(delta & state & RENDER_COLOURWRITE) + { + glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); + GlobalOpenGL_debugAssertNoErrors(); + } + else if(delta & ~state & RENDER_COLOURWRITE) + { + glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); + GlobalOpenGL_debugAssertNoErrors(); + } + + setState(state, delta, RENDER_ALPHATEST, GL_ALPHA_TEST); + + if(delta & state & RENDER_COLOURARRAY) + { + glEnableClientState(GL_COLOR_ARRAY); + GlobalOpenGL_debugAssertNoErrors(); + debug_colour("enabling color_array"); + g_colorArray_enabled = true; + } + else if(delta & ~state & RENDER_COLOURARRAY) + { + glDisableClientState(GL_COLOR_ARRAY); + glColor4fv(vector4_to_array(self.m_colour)); + debug_colour("cleaning color_array"); + GlobalOpenGL_debugAssertNoErrors(); + g_colorArray_enabled = false; + } + + if(delta & ~state & RENDER_COLOURCHANGE) + { + glColor4fv(vector4_to_array(self.m_colour)); + GlobalOpenGL_debugAssertNoErrors(); + } + + setState(state, delta, RENDER_LINESTIPPLE, GL_LINE_STIPPLE); + setState(state, delta, RENDER_LINESMOOTH, GL_LINE_SMOOTH); + + setState(state, delta, RENDER_POLYGONSTIPPLE, GL_POLYGON_STIPPLE); + setState(state, delta, RENDER_POLYGONSMOOTH, GL_POLYGON_SMOOTH); + + setState(state, delta, RENDER_FOG, GL_FOG); + + if((state & RENDER_FOG) != 0) + { + setFogState(self.m_fog); + GlobalOpenGL_debugAssertNoErrors(); + current.m_fog = self.m_fog; + } + + if(state & RENDER_DEPTHTEST && self.m_depthfunc != current.m_depthfunc) + { + glDepthFunc(self.m_depthfunc); + GlobalOpenGL_debugAssertNoErrors(); + current.m_depthfunc = self.m_depthfunc; + } + + if(state & RENDER_LINESTIPPLE + && (self.m_linestipple_factor != current.m_linestipple_factor + || self.m_linestipple_pattern != current.m_linestipple_pattern)) + { + glLineStipple(self.m_linestipple_factor, self.m_linestipple_pattern); + GlobalOpenGL_debugAssertNoErrors(); + current.m_linestipple_factor = self.m_linestipple_factor; + current.m_linestipple_pattern = self.m_linestipple_pattern; + } + + + if(state & RENDER_ALPHATEST + && ( self.m_alphafunc != current.m_alphafunc + || self.m_alpharef != current.m_alpharef ) ) + { + glAlphaFunc(self.m_alphafunc, self.m_alpharef); + GlobalOpenGL_debugAssertNoErrors(); + current.m_alphafunc = self.m_alphafunc; + current.m_alpharef = self.m_alpharef; + } + + { + GLint texture0 = 0; + GLint texture1 = 0; + GLint texture2 = 0; + GLint texture3 = 0; + GLint texture4 = 0; + GLint texture5 = 0; + GLint texture6 = 0; + GLint texture7 = 0; + //if(state & RENDER_TEXTURE) != 0) + { + texture0 = self.m_texture; + texture1 = self.m_texture1; + texture2 = self.m_texture2; + texture3 = self.m_texture3; + texture4 = self.m_texture4; + texture5 = self.m_texture5; + texture6 = self.m_texture6; + texture7 = self.m_texture7; + } + + if(GlobalOpenGL().GL_1_3()) + { + setTextureState(current.m_texture, texture0, GL_TEXTURE0); + setTextureState(current.m_texture1, texture1, GL_TEXTURE1); + setTextureState(current.m_texture2, texture2, GL_TEXTURE2); + setTextureState(current.m_texture3, texture3, GL_TEXTURE3); + setTextureState(current.m_texture4, texture4, GL_TEXTURE4); + setTextureState(current.m_texture5, texture5, GL_TEXTURE5); + setTextureState(current.m_texture6, texture6, GL_TEXTURE6); + setTextureState(current.m_texture7, texture7, GL_TEXTURE7); + } + else + { + setTextureState(current.m_texture, texture0); + } + } + + + if(state & RENDER_TEXTURE && self.m_colour[3] != current.m_colour[3]) + { + debug_colour("setting alpha"); + glColor4f(1,1,1,self.m_colour[3]); + GlobalOpenGL_debugAssertNoErrors(); + } + + if(!(state & RENDER_TEXTURE) + && (self.m_colour[0] != current.m_colour[0] + || self.m_colour[1] != current.m_colour[1] + || self.m_colour[2] != current.m_colour[2] + || self.m_colour[3] != current.m_colour[3])) + { + glColor4fv(vector4_to_array(self.m_colour)); + debug_colour("setting non-texture"); + GlobalOpenGL_debugAssertNoErrors(); + } + current.m_colour = self.m_colour; + + if(state & RENDER_BLEND + && (self.m_blend_src != current.m_blend_src || self.m_blend_dst != current.m_blend_dst)) + { + glBlendFunc(self.m_blend_src, self.m_blend_dst); + GlobalOpenGL_debugAssertNoErrors(); + current.m_blend_src = self.m_blend_src; + current.m_blend_dst = self.m_blend_dst; + } + + if(!(state & RENDER_FILL) + && self.m_linewidth != current.m_linewidth) + { + glLineWidth(self.m_linewidth); + GlobalOpenGL_debugAssertNoErrors(); + current.m_linewidth = self.m_linewidth; + } + + if(!(state & RENDER_FILL) + && self.m_pointsize != current.m_pointsize) + { + glPointSize(self.m_pointsize); + GlobalOpenGL_debugAssertNoErrors(); + current.m_pointsize = self.m_pointsize; + } + + current.m_state = state; + + GlobalOpenGL_debugAssertNoErrors(); +} + +void Renderables_flush(OpenGLStateBucket::Renderables& renderables, OpenGLState& current, unsigned int globalstate, const Vector3& viewer) +{ + const Matrix4* transform = 0; + glPushMatrix(); + for(OpenGLStateBucket::Renderables::const_iterator i = renderables.begin(); i != renderables.end(); ++i) + { + //qglLoadMatrixf(i->m_transform); + if(!transform || (transform != (*i).m_transform && !matrix4_affine_equal(*transform, *(*i).m_transform))) + { + count_transform(); + transform = (*i).m_transform; + glPopMatrix(); + glPushMatrix(); + glMultMatrixf(reinterpret_cast(transform)); + glFrontFace(((current.m_state & RENDER_CULLFACE) != 0 && matrix4_handedness(*transform) == MATRIX4_RIGHTHANDED) ? GL_CW : GL_CCW); + } + + count_prim(); + + if(current.m_program != 0 && (*i).m_light != 0) + { + const IShader& lightShader = static_cast((*i).m_light->getShader())->getShader(); + if(lightShader.firstLayer() != 0) + { + GLuint attenuation_xy = lightShader.firstLayer()->texture()->texture_number; + GLuint attenuation_z = lightShader.lightFalloffImage() != 0 + ? lightShader.lightFalloffImage()->texture_number + : static_cast(g_defaultPointLight)->getShader().lightFalloffImage()->texture_number; + + setTextureState(current.m_texture3, attenuation_xy, GL_TEXTURE3); + glActiveTexture(GL_TEXTURE3); + glBindTexture(GL_TEXTURE_2D, attenuation_xy); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); + + setTextureState(current.m_texture4, attenuation_z, GL_TEXTURE4); + glActiveTexture(GL_TEXTURE4); + glBindTexture(GL_TEXTURE_2D, attenuation_z); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + + AABB lightBounds((*i).m_light->aabb()); + + Matrix4 world2light(g_matrix4_identity); + + if((*i).m_light->isProjected()) + { + world2light = (*i).m_light->projection(); + matrix4_multiply_by_matrix4(world2light, matrix4_transposed((*i).m_light->rotation())); + matrix4_translate_by_vec3(world2light, vector3_negated(lightBounds.origin)); // world->lightBounds + } + if(!(*i).m_light->isProjected()) + { + matrix4_translate_by_vec3(world2light, Vector3(0.5f, 0.5f, 0.5f)); + matrix4_scale_by_vec3(world2light, Vector3(0.5f, 0.5f, 0.5f)); + matrix4_scale_by_vec3(world2light, Vector3(1.0f / lightBounds.extents.x(), 1.0f / lightBounds.extents.y(), 1.0f / lightBounds.extents.z())); + matrix4_multiply_by_matrix4(world2light, matrix4_transposed((*i).m_light->rotation())); + matrix4_translate_by_vec3(world2light, vector3_negated(lightBounds.origin)); // world->lightBounds + } + + current.m_program->setParameters(viewer, *(*i).m_transform, lightBounds.origin + (*i).m_light->offset(), (*i).m_light->colour(), world2light); + debug_string("set lightBounds parameters"); + } + } + + (*i).m_renderable->render(current.m_state); + } + glPopMatrix(); + renderables.clear(); +} + +void OpenGLStateBucket::render(OpenGLState& current, unsigned int globalstate, const Vector3& viewer) +{ + if((globalstate & m_state.m_state & RENDER_SCREEN) != 0) + { + OpenGLState_apply(m_state, current, globalstate); + debug_colour("screen fill"); + + glMatrixMode(GL_PROJECTION); + glPushMatrix(); + glLoadMatrixf(reinterpret_cast(&g_matrix4_identity)); + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadMatrixf(reinterpret_cast(&g_matrix4_identity)); + + glBegin(GL_QUADS); + glVertex3f(-1, -1, 0); + glVertex3f(1, -1, 0); + glVertex3f(1, 1, 0); + glVertex3f(-1, 1, 0); + glEnd(); + + glMatrixMode(GL_PROJECTION); + glPopMatrix(); + + glMatrixMode(GL_MODELVIEW); + glPopMatrix(); + } + else if(!m_renderables.empty()) + { + OpenGLState_apply(m_state, current, globalstate); + Renderables_flush(m_renderables, current, globalstate, viewer); + } +} + + +class OpenGLStateMap : public OpenGLStateLibrary +{ + typedef std::map States; + States m_states; +public: + ~OpenGLStateMap() + { + ASSERT_MESSAGE(m_states.empty(), "OpenGLStateMap::~OpenGLStateMap: not empty"); + } + + typedef States::iterator iterator; + iterator begin() + { + return m_states.begin(); + } + iterator end() + { + return m_states.end(); + } + + void getDefaultState(OpenGLState& state) const + { + OpenGLState_constructDefault(state); + } + + void insert(const char* name, const OpenGLState& state) + { + bool inserted = m_states.insert(States::value_type(name, state)).second; + ASSERT_MESSAGE(inserted, "OpenGLStateMap::insert: " << name << " already exists"); + } + void erase(const char* name) + { + std::size_t count = m_states.erase(name); + ASSERT_MESSAGE(count == 1, "OpenGLStateMap::erase: " << name << " does not exist"); + } + + iterator find(const char* name) + { + return m_states.find(name); + } +}; + +OpenGLStateMap* g_openglStates = 0; + +inline GLenum convertBlendFactor(BlendFactor factor) +{ + switch(factor) + { + case BLEND_ZERO: + return GL_ZERO; + case BLEND_ONE: + return GL_ONE; + case BLEND_SRC_COLOUR: + return GL_SRC_COLOR; + case BLEND_ONE_MINUS_SRC_COLOUR: + return GL_ONE_MINUS_SRC_COLOR; + case BLEND_SRC_ALPHA: + return GL_SRC_ALPHA; + case BLEND_ONE_MINUS_SRC_ALPHA: + return GL_ONE_MINUS_SRC_ALPHA; + case BLEND_DST_COLOUR: + return GL_DST_COLOR; + case BLEND_ONE_MINUS_DST_COLOUR: + return GL_ONE_MINUS_DST_COLOR; + case BLEND_DST_ALPHA: + return GL_DST_ALPHA; + case BLEND_ONE_MINUS_DST_ALPHA: + return GL_ONE_MINUS_DST_ALPHA; + case BLEND_SRC_ALPHA_SATURATE: + return GL_SRC_ALPHA_SATURATE; + } + return GL_ZERO; +} + +/// \todo Define special-case shaders in a data file. +void OpenGLShader::construct(const char* name) +{ + OpenGLState& state = appendDefaultPass(); + switch(name[0]) + { + case '(': + sscanf(name, "(%g %g %g)", &state.m_colour[0], &state.m_colour[1], &state.m_colour[2]); + state.m_colour[3] = 1.0f; + state.m_state = RENDER_FILL|RENDER_LIGHTING|RENDER_DEPTHTEST|RENDER_CULLFACE|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortFullbright; + break; + + case '[': + sscanf(name, "[%g %g %g]", &state.m_colour[0], &state.m_colour[1], &state.m_colour[2]); + state.m_colour[3] = 0.5f; + state.m_state = RENDER_FILL|RENDER_LIGHTING|RENDER_DEPTHTEST|RENDER_CULLFACE|RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_BLEND; + state.m_sort = OpenGLState::eSortTranslucent; + break; + + case '<': + sscanf(name, "<%g %g %g>", &state.m_colour[0], &state.m_colour[1], &state.m_colour[2]); + state.m_colour[3] = 1; + state.m_state = RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortFullbright; + state.m_depthfunc = GL_LESS; + state.m_linewidth = 1; + state.m_pointsize = 1; + break; + + case '$': + { + OpenGLStateMap::iterator i = g_openglStates->find(name); + if(i != g_openglStates->end()) + { + state = (*i).second; + break; + } + } + if(string_equal(name+1, "POINT")) + { + state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortControlFirst; + state.m_pointsize = 4; + } + else if(string_equal(name+1, "SELPOINT")) + { + state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortControlFirst + 1; + state.m_pointsize = 4; + } + else if(string_equal(name+1, "BIGPOINT")) + { + state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortControlFirst; + state.m_pointsize = 6; + } + else if(string_equal(name+1, "PIVOT")) + { + state.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHTEST|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortGUI1; + state.m_linewidth = 2; + state.m_depthfunc = GL_LEQUAL; + + OpenGLState& hiddenLine = appendDefaultPass(); + hiddenLine.m_state = RENDER_COLOURARRAY|RENDER_COLOURWRITE|RENDER_DEPTHTEST|RENDER_LINESTIPPLE; + hiddenLine.m_sort = OpenGLState::eSortGUI0; + hiddenLine.m_linewidth = 2; + hiddenLine.m_depthfunc = GL_GREATER; + } + else if(string_equal(name+1, "LATTICE")) + { + state.m_colour[0] = 1; + state.m_colour[1] = 0.5; + state.m_colour[2] = 0; + state.m_colour[3] = 1; + state.m_state = RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortControlFirst; + } + else if(string_equal(name+1, "WIREFRAME")) + { + state.m_state = RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortFullbright; + } + else if(string_equal(name+1, "CAM_HIGHLIGHT")) + { + state.m_colour[0] = 1; + state.m_colour[1] = 0; + state.m_colour[2] = 0; + state.m_colour[3] = 0.3f; + state.m_state = RENDER_FILL|RENDER_DEPTHTEST|RENDER_CULLFACE|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortHighlight; + state.m_depthfunc = GL_LEQUAL; + } + else if(string_equal(name+1, "CAM_OVERLAY")) + { +#if 0 + state.m_state = RENDER_CULLFACE|RENDER_COLOURWRITE|RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortOverlayFirst; +#else + state.m_state = RENDER_CULLFACE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_DEPTHWRITE|RENDER_OFFSETLINE; + state.m_sort = OpenGLState::eSortOverlayFirst + 1; + state.m_depthfunc = GL_LEQUAL; + + OpenGLState& hiddenLine = appendDefaultPass(); + hiddenLine.m_colour[0] = 0.75; + hiddenLine.m_colour[1] = 0.75; + hiddenLine.m_colour[2] = 0.75; + hiddenLine.m_colour[3] = 1; + hiddenLine.m_state = RENDER_CULLFACE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_OFFSETLINE|RENDER_LINESTIPPLE; + hiddenLine.m_sort = OpenGLState::eSortOverlayFirst; + hiddenLine.m_depthfunc = GL_GREATER; + hiddenLine.m_linestipple_factor = 2; +#endif + } + else if(string_equal(name+1, "XY_OVERLAY")) + { + state.m_colour[0] = g_xywindow_globals.color_selbrushes[0]; + state.m_colour[1] = g_xywindow_globals.color_selbrushes[1]; + state.m_colour[2] = g_xywindow_globals.color_selbrushes[2]; + state.m_colour[3] = 1; + state.m_state = RENDER_COLOURWRITE | RENDER_LINESTIPPLE; + state.m_sort = OpenGLState::eSortOverlayFirst; + state.m_linewidth = 2; + state.m_linestipple_factor = 3; + } + else if(string_equal(name+1, "DEBUG_CLIPPED")) + { + state.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortLast; + } + else if(string_equal(name+1, "POINTFILE")) + { + state.m_colour[0] = 1; + state.m_colour[1] = 0; + state.m_colour[2] = 0; + state.m_colour[3] = 1; + state.m_state = RENDER_DEPTHTEST | RENDER_COLOURWRITE | RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortFullbright; + state.m_linewidth = 4; + } + else if(string_equal(name+1, "LIGHT_SPHERE")) + { + state.m_colour[0] = .15f * .95f; + state.m_colour[1] = .15f * .95f; + state.m_colour[2] = .15f * .95f; + state.m_colour[3] = 1; + state.m_state = RENDER_CULLFACE | RENDER_DEPTHTEST | RENDER_BLEND | RENDER_FILL | RENDER_COLOURWRITE | RENDER_DEPTHWRITE; + state.m_blend_src = GL_ONE; + state.m_blend_dst = GL_ONE; + state.m_sort = OpenGLState::eSortTranslucent; + } + else if(string_equal(name+1, "Q3MAP2_LIGHT_SPHERE")) + { + state.m_colour[0] = .05f; + state.m_colour[1] = .05f; + state.m_colour[2] = .05f; + state.m_colour[3] = 1; + state.m_state = RENDER_CULLFACE | RENDER_DEPTHTEST | RENDER_BLEND | RENDER_FILL; + state.m_blend_src = GL_ONE; + state.m_blend_dst = GL_ONE; + state.m_sort = OpenGLState::eSortTranslucent; + } + else if(string_equal(name+1, "WIRE_OVERLAY")) + { +#if 0 + state.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE; + state.m_sort = OpenGLState::eSortOverlayFirst; +#else + state.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE; + state.m_sort = OpenGLState::eSortGUI1; + state.m_depthfunc = GL_LEQUAL; + + OpenGLState& hiddenLine = appendDefaultPass(); + hiddenLine.m_state = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE | RENDER_LINESTIPPLE; + hiddenLine.m_sort = OpenGLState::eSortGUI0; + hiddenLine.m_depthfunc = GL_GREATER; +#endif + } + else if(string_equal(name+1, "FLATSHADE_OVERLAY")) + { + state.m_state = RENDER_CULLFACE | RENDER_LIGHTING | RENDER_SMOOTH | RENDER_SCALED | RENDER_COLOURARRAY | RENDER_FILL | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE; + state.m_sort = OpenGLState::eSortGUI1; + state.m_depthfunc = GL_LEQUAL; + + OpenGLState& hiddenLine = appendDefaultPass(); + hiddenLine.m_state = RENDER_CULLFACE | RENDER_LIGHTING | RENDER_SMOOTH | RENDER_SCALED | RENDER_COLOURARRAY | RENDER_FILL | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_DEPTHTEST | RENDER_OVERRIDE | RENDER_POLYGONSTIPPLE; + hiddenLine.m_sort = OpenGLState::eSortGUI0; + hiddenLine.m_depthfunc = GL_GREATER; + } + else if(string_equal(name+1, "CLIPPER_OVERLAY")) + { + state.m_colour[0] = g_xywindow_globals.color_clipper[0]; + state.m_colour[1] = g_xywindow_globals.color_clipper[1]; + state.m_colour[2] = g_xywindow_globals.color_clipper[2]; + state.m_colour[3] = 1; + state.m_state = RENDER_CULLFACE | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_FILL | RENDER_POLYGONSTIPPLE; + state.m_sort = OpenGLState::eSortOverlayFirst; + } + else if(string_equal(name+1, "OVERBRIGHT")) + { + const float lightScale = 2; + state.m_colour[0] = lightScale * 0.5f; + state.m_colour[1] = lightScale * 0.5f; + state.m_colour[2] = lightScale * 0.5f; + state.m_colour[3] = 0.5; + state.m_state = RENDER_FILL|RENDER_BLEND|RENDER_COLOURWRITE|RENDER_SCREEN; + state.m_sort = OpenGLState::eSortOverbrighten; + state.m_blend_src = GL_DST_COLOR; + state.m_blend_dst = GL_SRC_COLOR; + } + else + { + // default to something recognisable.. =) + ERROR_MESSAGE("hardcoded renderstate not found"); + state.m_colour[0] = 1; + state.m_colour[1] = 0; + state.m_colour[2] = 1; + state.m_colour[3] = 1; + state.m_state = RENDER_COLOURWRITE | RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortFirst; + } + break; + default: + // construction from IShader + m_shader = QERApp_Shader_ForName(name); + + if(g_ShaderCache->lightingSupported() && g_ShaderCache->lightingEnabled() && m_shader->getBump() != 0 && m_shader->getBump()->texture_number != 0) // is a bump shader + { + state.m_state = RENDER_FILL | RENDER_CULLFACE | RENDER_TEXTURE | RENDER_DEPTHTEST | RENDER_DEPTHWRITE | RENDER_COLOURWRITE | RENDER_PROGRAM; + state.m_colour[0] = 0; + state.m_colour[1] = 0; + state.m_colour[2] = 0; + state.m_colour[3] = 1; + state.m_sort = OpenGLState::eSortOpaque; + + if(g_ShaderCache->useShaderLanguage()) + { + state.m_program = &g_depthFillGLSL; + } + else + { + state.m_program = &g_depthFillARB; + } + + OpenGLState& bumpPass = appendDefaultPass(); + bumpPass.m_texture = m_shader->getDiffuse()->texture_number; + bumpPass.m_texture1 = m_shader->getBump()->texture_number; + bumpPass.m_texture2 = m_shader->getSpecular()->texture_number; + + bumpPass.m_state = RENDER_BLEND|RENDER_FILL|RENDER_CULLFACE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_SMOOTH|RENDER_BUMP|RENDER_PROGRAM; + + if(g_ShaderCache->useShaderLanguage()) + { + bumpPass.m_state |= RENDER_LIGHTING; + bumpPass.m_program = &g_bumpGLSL; + } + else + { + bumpPass.m_program = &g_bumpARB; + } + + bumpPass.m_depthfunc = GL_LEQUAL; + bumpPass.m_sort = OpenGLState::eSortMultiFirst; + bumpPass.m_blend_src = GL_ONE; + bumpPass.m_blend_dst = GL_ONE; + } + else + { + state.m_texture = m_shader->getTexture()->texture_number; + + state.m_state = RENDER_FILL|RENDER_TEXTURE|RENDER_DEPTHTEST|RENDER_COLOURWRITE|RENDER_LIGHTING|RENDER_SMOOTH; + if((m_shader->getFlags() & QER_CULL) != 0) + { + if(m_shader->getCull() == IShader::eCullBack) + { + state.m_state |= RENDER_CULLFACE; + } + } + else + { + state.m_state |= RENDER_CULLFACE; + } + if((m_shader->getFlags() & QER_ALPHATEST) != 0) + { + state.m_state |= RENDER_ALPHATEST; + IShader::EAlphaFunc alphafunc; + m_shader->getAlphaFunc(&alphafunc, &state.m_alpharef); + switch(alphafunc) + { + case IShader::eAlways: + state.m_alphafunc = GL_ALWAYS; + case IShader::eEqual: + state.m_alphafunc = GL_EQUAL; + case IShader::eLess: + state.m_alphafunc = GL_LESS; + case IShader::eGreater: + state.m_alphafunc = GL_GREATER; + case IShader::eLEqual: + state.m_alphafunc = GL_LEQUAL; + case IShader::eGEqual: + state.m_alphafunc = GL_GEQUAL; + } + } + reinterpret_cast(state.m_colour) = m_shader->getTexture()->color; + state.m_colour[3] = 1.0f; + + if((m_shader->getFlags() & QER_TRANS) != 0) + { + state.m_state |= RENDER_BLEND; + state.m_colour[3] = m_shader->getTrans(); + state.m_sort = OpenGLState::eSortTranslucent; + BlendFunc blendFunc = m_shader->getBlendFunc(); + state.m_blend_src = convertBlendFactor(blendFunc.m_src); + state.m_blend_dst = convertBlendFactor(blendFunc.m_dst); + if(state.m_blend_src == GL_SRC_ALPHA || state.m_blend_dst == GL_SRC_ALPHA) + { + state.m_state |= RENDER_DEPTHWRITE; + } + } + else + { + state.m_state |= RENDER_DEPTHWRITE; + state.m_sort = OpenGLState::eSortFullbright; + } + } + } +} + + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class OpenGLStateLibraryAPI +{ + OpenGLStateMap m_stateMap; +public: + typedef OpenGLStateLibrary Type; + STRING_CONSTANT(Name, "*"); + + OpenGLStateLibraryAPI() + { + g_openglStates = &m_stateMap; + } + ~OpenGLStateLibraryAPI() + { + g_openglStates = 0; + } + OpenGLStateLibrary* getTable() + { + return &m_stateMap; + } +}; + +typedef SingletonModule OpenGLStateLibraryModule; +typedef Static StaticOpenGLStateLibraryModule; +StaticRegisterModule staticRegisterOpenGLStateLibrary(StaticOpenGLStateLibraryModule::instance()); + +class ShaderCacheDependencies : public GlobalShadersModuleRef, public GlobalTexturesModuleRef, public GlobalOpenGLStateLibraryModuleRef +{ +public: + ShaderCacheDependencies() : + GlobalShadersModuleRef(GlobalRadiant().getRequiredGameDescriptionKeyValue("shaders")) + { + } +}; + +class ShaderCacheAPI +{ + ShaderCache* m_shaderCache; +public: + typedef ShaderCache Type; + STRING_CONSTANT(Name, "*"); + + ShaderCacheAPI() + { + ShaderCache_Construct(); + + m_shaderCache = GetShaderCache(); + } + ~ShaderCacheAPI() + { + ShaderCache_Destroy(); + } + ShaderCache* getTable() + { + return m_shaderCache; + } +}; + +typedef SingletonModule ShaderCacheModule; +typedef Static StaticShaderCacheModule; +StaticRegisterModule staticRegisterShaderCache(StaticShaderCacheModule::instance()); + + diff --git a/misc/mediasource/netradiant-src/radiant/renderstate.h b/misc/mediasource/netradiant-src/radiant/renderstate.h new file mode 100644 index 00000000..9bbd2918 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/renderstate.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_RENDERSTATE_H) +#define INCLUDED_RENDERSTATE_H + +void ShaderCache_setBumpEnabled(bool enabled); +void ShaderCache_extensionsInitialised(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/resource.h b/misc/mediasource/netradiant-src/radiant/resource.h new file mode 100644 index 00000000..dc86a878 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/resource.h @@ -0,0 +1,18 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by radiant.rc +// +#define IDI_RADIANT 101 +#define IDR_MENU1 102 +#define IDD_DIALOG1 103 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 104 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/misc/mediasource/netradiant-src/radiant/scenegraph.cpp b/misc/mediasource/netradiant-src/radiant/scenegraph.cpp new file mode 100644 index 00000000..cb83691e --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/scenegraph.cpp @@ -0,0 +1,312 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "scenegraph.h" + +#include "debugging/debugging.h" + +#include +#include +#include + +#include "string/string.h" +#include "signal/signal.h" +#include "scenelib.h" +#include "instancelib.h" +#include "treemodel.h" + +class StringEqualPredicate +{ + const char* m_string; +public: + StringEqualPredicate(const char* string) : m_string(string) + { + } + bool operator()(const char* other) const + { + return string_equal(m_string, other); + } +}; + +template +class TypeIdMap +{ + typedef const char* TypeName; + typedef TypeName TypeNames[SIZE]; + TypeNames m_typeNames; + TypeName* m_typeNamesEnd; + +public: + TypeIdMap() : m_typeNamesEnd(m_typeNames) + { + } + TypeId getTypeId(const char* name) + { + TypeName* i = std::find_if(m_typeNames, m_typeNamesEnd, StringEqualPredicate(name)); + if(i == m_typeNamesEnd) + { + ASSERT_MESSAGE(m_typeNamesEnd != m_typeNames + SIZE, "reached maximum number of type names supported (" << Unsigned(SIZE) << ")"); + *m_typeNamesEnd++ = name; + } + return i - m_typeNames; + } +}; + +class CompiledGraph : public scene::Graph, public scene::Instantiable::Observer +{ + typedef std::map InstanceMap; + + InstanceMap m_instances; + scene::Instantiable::Observer* m_observer; + Signal0 m_boundsChanged; + scene::Path m_rootpath; + Signal0 m_sceneChangedCallbacks; + + TypeIdMap m_nodeTypeIds; + TypeIdMap m_instanceTypeIds; + +public: + + CompiledGraph(scene::Instantiable::Observer* observer) + : m_observer(observer) + { + } + + void addSceneChangedCallback(const SignalHandler& handler) + { + m_sceneChangedCallbacks.connectLast(handler); + } + void sceneChanged() + { + m_sceneChangedCallbacks(); + } + + scene::Node& root() + { + ASSERT_MESSAGE(!m_rootpath.empty(), "scenegraph root does not exist"); + return m_rootpath.top(); + } + void insert_root(scene::Node& root) + { + //globalOutputStream() << "insert_root\n"; + + ASSERT_MESSAGE(m_rootpath.empty(), "scenegraph root already exists"); + + root.IncRef(); + + Node_traverseSubgraph(root, InstanceSubgraphWalker(this, scene::Path(), 0)); + + m_rootpath.push(makeReference(root)); + } + void erase_root() + { + //globalOutputStream() << "erase_root\n"; + + ASSERT_MESSAGE(!m_rootpath.empty(), "scenegraph root does not exist"); + + scene::Node& root = m_rootpath.top(); + + m_rootpath.pop(); + + Node_traverseSubgraph(root, UninstanceSubgraphWalker(this, scene::Path())); + + root.DecRef(); + } + void boundsChanged() + { + m_boundsChanged(); + } + + void traverse(const Walker& walker) + { + traverse_subgraph(walker, m_instances.begin()); + } + + void traverse_subgraph(const Walker& walker, const scene::Path& start) + { + if(!m_instances.empty()) + { + traverse_subgraph(walker, m_instances.find(PathConstReference(start))); + } + } + + scene::Instance* find(const scene::Path& path) + { + InstanceMap::iterator i = m_instances.find(PathConstReference(path)); + if(i == m_instances.end()) + { + return 0; + } + return (*i).second; + } + + void insert(scene::Instance* instance) + { + m_instances.insert(InstanceMap::value_type(PathConstReference(instance->path()), instance)); + + m_observer->insert(instance); + } + void erase(scene::Instance* instance) + { + m_observer->erase(instance); + + m_instances.erase(PathConstReference(instance->path())); + } + + SignalHandlerId addBoundsChangedCallback(const SignalHandler& boundsChanged) + { + return m_boundsChanged.connectLast(boundsChanged); + } + void removeBoundsChangedCallback(SignalHandlerId id) + { + m_boundsChanged.disconnect(id); + } + + TypeId getNodeTypeId(const char* name) + { + return m_nodeTypeIds.getTypeId(name); + } + + TypeId getInstanceTypeId(const char* name) + { + return m_instanceTypeIds.getTypeId(name); + } + +private: + + bool pre(const Walker& walker, const InstanceMap::iterator& i) + { + return walker.pre(i->first, *i->second); + } + + void post(const Walker& walker, const InstanceMap::iterator& i) + { + walker.post(i->first, *i->second); + } + + void traverse_subgraph(const Walker& walker, InstanceMap::iterator i) + { + Stack stack; + if(i != m_instances.end()) + { + const std::size_t startSize = (*i).first.get().size(); + do + { + if(i != m_instances.end() + && stack.size() < ((*i).first.get().size() - startSize + 1)) + { + stack.push(i); + ++i; + if(!pre(walker, stack.top())) + { + // skip subgraph + while(i != m_instances.end() + && stack.size() < ((*i).first.get().size() - startSize + 1)) + { + ++i; + } + } + } + else + { + post(walker, stack.top()); + stack.pop(); + } + } + while(!stack.empty()); + } + } +}; + +namespace +{ + CompiledGraph* g_sceneGraph; + GraphTreeModel* g_tree_model; +} + +GraphTreeModel* scene_graph_get_tree_model() +{ + return g_tree_model; +} + + +class SceneGraphObserver : public scene::Instantiable::Observer +{ +public: + void insert(scene::Instance* instance) + { + g_sceneGraph->sceneChanged(); + graph_tree_model_insert(g_tree_model, *instance); + } + void erase(scene::Instance* instance) + { + g_sceneGraph->sceneChanged(); + graph_tree_model_erase(g_tree_model, *instance); + } +}; + +SceneGraphObserver g_SceneGraphObserver; + +void SceneGraph_Construct() +{ + g_tree_model = graph_tree_model_new(); + + g_sceneGraph = new CompiledGraph(&g_SceneGraphObserver); +} + +void SceneGraph_Destroy() +{ + delete g_sceneGraph; + + graph_tree_model_delete(g_tree_model); +} + + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class SceneGraphAPI +{ + scene::Graph* m_scenegraph; +public: + typedef scene::Graph Type; + STRING_CONSTANT(Name, "*"); + + SceneGraphAPI() + { + SceneGraph_Construct(); + + m_scenegraph = g_sceneGraph; + } + ~SceneGraphAPI() + { + SceneGraph_Destroy(); + } + scene::Graph* getTable() + { + return m_scenegraph; + } +}; + +typedef SingletonModule SceneGraphModule; +typedef Static StaticSceneGraphModule; +StaticRegisterModule staticRegisterSceneGraph(StaticSceneGraphModule::instance()); + diff --git a/misc/mediasource/netradiant-src/radiant/scenegraph.h b/misc/mediasource/netradiant-src/radiant/scenegraph.h new file mode 100644 index 00000000..d269f8b4 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/scenegraph.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDEDE_SCENEGRAPH_H) +#define INCLUDED_SCENEGRAPH_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/select.cpp b/misc/mediasource/netradiant-src/radiant/select.cpp new file mode 100644 index 00000000..5889fd5a --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/select.cpp @@ -0,0 +1,1273 @@ +/* +Copyright (C) 1999-2006 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 "select.h" + +#include "debugging/debugging.h" + +#include "ientity.h" +#include "iselection.h" +#include "iundo.h" + +#include + +#include "stream/stringstream.h" +#include "signal/isignal.h" +#include "shaderlib.h" +#include "scenelib.h" + +#include "gtkutil/idledraw.h" +#include "gtkutil/dialog.h" +#include "gtkutil/widget.h" +#include "brushmanip.h" +#include "brush.h" +#include "patchmanip.h" +#include "patchdialog.h" +#include "selection.h" +#include "texwindow.h" +#include "gtkmisc.h" +#include "mainframe.h" +#include "grid.h" +#include "map.h" + + + +select_workzone_t g_select_workzone; + + +/** + Loops over all selected brushes and stores their + world AABBs in the specified array. +*/ +class CollectSelectedBrushesBounds : public SelectionSystem::Visitor +{ + AABB* m_bounds; // array of AABBs + Unsigned m_max; // max AABB-elements in array + Unsigned& m_count;// count of valid AABBs stored in array + +public: + CollectSelectedBrushesBounds(AABB* bounds, Unsigned max, Unsigned& count) + : m_bounds(bounds), + m_max(max), + m_count(count) + { + m_count = 0; + } + + void visit(scene::Instance& instance) const + { + ASSERT_MESSAGE(m_count <= m_max, "Invalid m_count in CollectSelectedBrushesBounds"); + + // stop if the array is already full + if(m_count == m_max) + return; + + Selectable* selectable = Instance_getSelectable(instance); + if((selectable != 0) + && instance.isSelected()) + { + // brushes only + if(Instance_getBrush(instance) != 0) + { + m_bounds[m_count] = instance.worldAABB(); + ++m_count; + } + } + } +}; + +/** + Selects all objects that intersect one of the bounding AABBs. + The exact intersection-method is specified through TSelectionPolicy +*/ +template +class SelectByBounds : public scene::Graph::Walker +{ + AABB* m_aabbs; // selection aabbs + Unsigned m_count; // number of aabbs in m_aabbs + TSelectionPolicy policy; // type that contains a custom intersection method aabb<->aabb + +public: + SelectByBounds(AABB* aabbs, Unsigned count) + : m_aabbs(aabbs), + m_count(count) + { + } + + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + + // ignore worldspawn + Entity* entity = Node_getEntity(path.top()); + if(entity) + { + if(string_equal(entity->getKeyValue("classname"), "worldspawn")) + return true; + } + + if( (path.size() > 1) && + (!path.top().get().isRoot()) && + (selectable != 0) + ) + { + for(Unsigned i = 0; i < m_count; ++i) + { + if(policy.Evaluate(m_aabbs[i], instance)) + { + selectable->setSelected(true); + } + } + } + + return true; + } + + /** + Performs selection operation on the global scenegraph. + If delete_bounds_src is true, then the objects which were + used as source for the selection aabbs will be deleted. +*/ + static void DoSelection(bool delete_bounds_src = true) + { + if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) + { + // we may not need all AABBs since not all selected objects have to be brushes + const Unsigned max = (Unsigned)GlobalSelectionSystem().countSelected(); + AABB* aabbs = new AABB[max]; + + Unsigned count; + CollectSelectedBrushesBounds collector(aabbs, max, count); + GlobalSelectionSystem().foreachSelected(collector); + + // nothing usable in selection + if(!count) + { + delete[] aabbs; + return; + } + + // delete selected objects + if(delete_bounds_src)// see deleteSelection + { + UndoableCommand undo("deleteSelected"); + Select_Delete(); + } + + // select objects with bounds + GlobalSceneGraph().traverse(SelectByBounds(aabbs, count)); + + SceneChangeNotify(); + delete[] aabbs; + } + } +}; + +/** + SelectionPolicy for SelectByBounds + Returns true if box and the AABB of instance intersect +*/ +class SelectionPolicy_Touching +{ +public: + bool Evaluate(const AABB& box, scene::Instance& instance) const + { + const AABB& other(instance.worldAABB()); + for(Unsigned i = 0; i < 3; ++i) + { + if(fabsf(box.origin[i] - other.origin[i]) > (box.extents[i] + other.extents[i])) + return false; + } + return true; + } +}; + +/** + SelectionPolicy for SelectByBounds + Returns true if the AABB of instance is inside box +*/ +class SelectionPolicy_Inside +{ +public: + bool Evaluate(const AABB& box, scene::Instance& instance) const + { + const AABB& other(instance.worldAABB()); + for(Unsigned i = 0; i < 3; ++i) + { + if(fabsf(box.origin[i] - other.origin[i]) > (box.extents[i] - other.extents[i])) + return false; + } + return true; + } +}; + +class DeleteSelected : public scene::Graph::Walker +{ + mutable bool m_remove; + mutable bool m_removedChild; +public: + DeleteSelected() + : m_remove(false), m_removedChild(false) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + m_removedChild = false; + + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected() + && path.size() > 1 + && !path.top().get().isRoot()) + { + m_remove = true; + + return false;// dont traverse into child elements + } + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + + if(m_removedChild) + { + m_removedChild = false; + + // delete empty entities + Entity* entity = Node_getEntity(path.top()); + if(entity != 0 + && path.top().get_pointer() != Map_FindWorldspawn(g_map) + && Node_getTraversable(path.top())->empty()) + { + Path_deleteTop(path); + } + } + + // node should be removed + if(m_remove) + { + if(Node_isEntity(path.parent()) != 0) + { + m_removedChild = true; + } + + m_remove = false; + Path_deleteTop(path); + } + } +}; + +void Scene_DeleteSelected(scene::Graph& graph) +{ + graph.traverse(DeleteSelected()); + SceneChangeNotify(); +} + +void Select_Delete (void) +{ + Scene_DeleteSelected(GlobalSceneGraph()); +} + +class InvertSelectionWalker : public scene::Graph::Walker +{ + SelectionSystem::EMode m_mode; + mutable Selectable* m_selectable; +public: + InvertSelectionWalker(SelectionSystem::EMode mode) + : m_mode(mode), m_selectable(0) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable) + { + switch(m_mode) + { + case SelectionSystem::eEntity: + if(Node_isEntity(path.top()) != 0) + { + m_selectable = path.top().get().visible() ? selectable : 0; + } + break; + case SelectionSystem::ePrimitive: + m_selectable = path.top().get().visible() ? selectable : 0; + break; + case SelectionSystem::eComponent: + break; + } + } + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + if(m_selectable != 0) + { + m_selectable->setSelected(!m_selectable->isSelected()); + m_selectable = 0; + } + } +}; + +void Scene_Invert_Selection(scene::Graph& graph) +{ + graph.traverse(InvertSelectionWalker(GlobalSelectionSystem().Mode())); +} + +void Select_Invert() +{ + Scene_Invert_Selection(GlobalSceneGraph()); +} + +class ExpandSelectionToEntitiesWalker : public scene::Graph::Walker +{ + mutable std::size_t m_depth; + NodeSmartReference worldspawn; +public: + ExpandSelectionToEntitiesWalker() : m_depth(0), worldspawn(Map_FindOrInsertWorldspawn(g_map)) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + ++m_depth; + + // ignore worldspawn + NodeSmartReference me(path.top().get()); + if(me == worldspawn) + return false; + + if(m_depth == 2) // entity depth + { + // traverse and select children if any one is selected + if(instance.childSelected()) + Instance_setSelected(instance, true); + return Node_getEntity(path.top())->isContainer() && instance.isSelected(); + } + else if(m_depth == 3) // primitive depth + { + Instance_setSelected(instance, true); + return false; + } + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + --m_depth; + } +}; + +void Scene_ExpandSelectionToEntities() +{ + GlobalSceneGraph().traverse(ExpandSelectionToEntitiesWalker()); +} + + +namespace +{ + void Selection_UpdateWorkzone() + { + if(GlobalSelectionSystem().countSelected() != 0) + { + Select_GetBounds(g_select_workzone.d_work_min, g_select_workzone.d_work_max); + } + } + typedef FreeCaller SelectionUpdateWorkzoneCaller; + + IdleDraw g_idleWorkzone = IdleDraw(SelectionUpdateWorkzoneCaller()); +} + +const select_workzone_t& Select_getWorkZone() +{ + g_idleWorkzone.flush(); + return g_select_workzone; +} + +void UpdateWorkzone_ForSelection() +{ + g_idleWorkzone.queueDraw(); +} + +// update the workzone to the current selection +void UpdateWorkzone_ForSelectionChanged(const Selectable& selectable) +{ + if(selectable.isSelected()) + { + UpdateWorkzone_ForSelection(); + } +} + +void Select_SetShader(const char* shader) +{ + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushSetShader_Selected(GlobalSceneGraph(), shader); + Scene_PatchSetShader_Selected(GlobalSceneGraph(), shader); + } + Scene_BrushSetShader_Component_Selected(GlobalSceneGraph(), shader); +} + +void Select_SetTexdef(const TextureProjection& projection) +{ + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushSetTexdef_Selected(GlobalSceneGraph(), projection); + } + Scene_BrushSetTexdef_Component_Selected(GlobalSceneGraph(), projection); +} + +void Select_SetFlags(const ContentsFlagsValue& flags) +{ + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushSetFlags_Selected(GlobalSceneGraph(), flags); + } + Scene_BrushSetFlags_Component_Selected(GlobalSceneGraph(), flags); +} + +void Select_GetBounds (Vector3& mins, Vector3& maxs) +{ + AABB bounds; + Scene_BoundsSelected(GlobalSceneGraph(), bounds); + maxs = vector3_added(bounds.origin, bounds.extents); + mins = vector3_subtracted(bounds.origin, bounds.extents); +} + +void Select_GetMid (Vector3& mid) +{ + AABB bounds; + Scene_BoundsSelected(GlobalSceneGraph(), bounds); + mid = vector3_snapped(bounds.origin); +} + + +void Select_FlipAxis (int axis) +{ + Vector3 flip(1, 1, 1); + flip[axis] = -1; + GlobalSelectionSystem().scaleSelected(flip); +} + + +void Select_Scale(float x, float y, float z) +{ + GlobalSelectionSystem().scaleSelected(Vector3(x, y, z)); +} + +enum axis_t +{ + eAxisX = 0, + eAxisY = 1, + eAxisZ = 2, +}; + +enum sign_t +{ + eSignPositive = 1, + eSignNegative = -1, +}; + +inline Matrix4 matrix4_rotation_for_axis90(axis_t axis, sign_t sign) +{ + switch(axis) + { + case eAxisX: + if(sign == eSignPositive) + { + return matrix4_rotation_for_sincos_x(1, 0); + } + else + { + return matrix4_rotation_for_sincos_x(-1, 0); + } + case eAxisY: + if(sign == eSignPositive) + { + return matrix4_rotation_for_sincos_y(1, 0); + } + else + { + return matrix4_rotation_for_sincos_y(-1, 0); + } + default://case eAxisZ: + if(sign == eSignPositive) + { + return matrix4_rotation_for_sincos_z(1, 0); + } + else + { + return matrix4_rotation_for_sincos_z(-1, 0); + } + } +} + +inline void matrix4_rotate_by_axis90(Matrix4& matrix, axis_t axis, sign_t sign) +{ + matrix4_multiply_by_matrix4(matrix, matrix4_rotation_for_axis90(axis, sign)); +} + +inline void matrix4_pivoted_rotate_by_axis90(Matrix4& matrix, axis_t axis, sign_t sign, const Vector3& pivotpoint) +{ + matrix4_translate_by_vec3(matrix, pivotpoint); + matrix4_rotate_by_axis90(matrix, axis, sign); + matrix4_translate_by_vec3(matrix, vector3_negated(pivotpoint)); +} + +inline Quaternion quaternion_for_axis90(axis_t axis, sign_t sign) +{ +#if 1 + switch(axis) + { + case eAxisX: + if(sign == eSignPositive) + { + return Quaternion(c_half_sqrt2f, 0, 0, c_half_sqrt2f); + } + else + { + return Quaternion(-c_half_sqrt2f, 0, 0, -c_half_sqrt2f); + } + case eAxisY: + if(sign == eSignPositive) + { + return Quaternion(0, c_half_sqrt2f, 0, c_half_sqrt2f); + } + else + { + return Quaternion(0, -c_half_sqrt2f, 0, -c_half_sqrt2f); + } + default://case eAxisZ: + if(sign == eSignPositive) + { + return Quaternion(0, 0, c_half_sqrt2f, c_half_sqrt2f); + } + else + { + return Quaternion(0, 0, -c_half_sqrt2f, -c_half_sqrt2f); + } + } +#else + quaternion_for_matrix4_rotation(matrix4_rotation_for_axis90((axis_t)axis, (deg > 0) ? eSignPositive : eSignNegative)); +#endif +} + +void Select_RotateAxis (int axis, float deg) +{ + if(fabs(deg) == 90.f) + { + GlobalSelectionSystem().rotateSelected(quaternion_for_axis90((axis_t)axis, (deg > 0) ? eSignPositive : eSignNegative)); + } + else + { + switch(axis) + { + case 0: + GlobalSelectionSystem().rotateSelected(quaternion_for_matrix4_rotation(matrix4_rotation_for_x_degrees(deg))); + break; + case 1: + GlobalSelectionSystem().rotateSelected(quaternion_for_matrix4_rotation(matrix4_rotation_for_y_degrees(deg))); + break; + case 2: + GlobalSelectionSystem().rotateSelected(quaternion_for_matrix4_rotation(matrix4_rotation_for_z_degrees(deg))); + break; + } + } +} + + +void Select_ShiftTexture(float x, float y) +{ + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushShiftTexdef_Selected(GlobalSceneGraph(), x, y); + Scene_PatchTranslateTexture_Selected(GlobalSceneGraph(), x, y); + } + //globalOutputStream() << "shift selected face textures: s=" << x << " t=" << y << '\n'; + Scene_BrushShiftTexdef_Component_Selected(GlobalSceneGraph(), x, y); +} + +void Select_ScaleTexture(float x, float y) +{ + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushScaleTexdef_Selected(GlobalSceneGraph(), x, y); + Scene_PatchScaleTexture_Selected(GlobalSceneGraph(), x, y); + } + Scene_BrushScaleTexdef_Component_Selected(GlobalSceneGraph(), x, y); +} + +void Select_RotateTexture(float amt) +{ + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushRotateTexdef_Selected(GlobalSceneGraph(), amt); + Scene_PatchRotateTexture_Selected(GlobalSceneGraph(), amt); + } + Scene_BrushRotateTexdef_Component_Selected(GlobalSceneGraph(), amt); +} + +// TTimo modified to handle shader architecture: +// expects shader names at input, comparison relies on shader names .. texture names no longer relevant +void FindReplaceTextures(const char* pFind, const char* pReplace, bool bSelected) +{ + if(!texdef_name_valid(pFind)) + { + globalErrorStream() << "FindReplaceTextures: invalid texture name: '" << pFind << "', aborted\n"; + return; + } + if(!texdef_name_valid(pReplace)) + { + globalErrorStream() << "FindReplaceTextures: invalid texture name: '" << pReplace << "', aborted\n"; + return; + } + + StringOutputStream command; + command << "textureFindReplace -find " << pFind << " -replace " << pReplace; + UndoableCommand undo(command.c_str()); + + if(bSelected) + { + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushFindReplaceShader_Selected(GlobalSceneGraph(), pFind, pReplace); + Scene_PatchFindReplaceShader_Selected(GlobalSceneGraph(), pFind, pReplace); + } + Scene_BrushFindReplaceShader_Component_Selected(GlobalSceneGraph(), pFind, pReplace); + } + else + { + Scene_BrushFindReplaceShader(GlobalSceneGraph(), pFind, pReplace); + Scene_PatchFindReplaceShader(GlobalSceneGraph(), pFind, pReplace); + } +} + +typedef std::vector Classnames; + +bool classnames_match_entity(const Classnames& classnames, Entity* entity) +{ + for(Classnames::const_iterator i = classnames.begin(); i != classnames.end(); ++i) + { + if(string_equal(entity->getKeyValue("classname"), *i)) + { + return true; + } + } + return false; +} + +class EntityFindByClassnameWalker : public scene::Graph::Walker +{ + const Classnames& m_classnames; +public: + EntityFindByClassnameWalker(const Classnames& classnames) + : m_classnames(classnames) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Entity* entity = Node_getEntity(path.top()); + if(entity != 0 + && classnames_match_entity(m_classnames, entity)) + { + Instance_getSelectable(instance)->setSelected(true); + } + return true; + } +}; + +void Scene_EntitySelectByClassnames(scene::Graph& graph, const Classnames& classnames) +{ + graph.traverse(EntityFindByClassnameWalker(classnames)); +} + +class EntityGetSelectedClassnamesWalker : public scene::Graph::Walker +{ + Classnames& m_classnames; +public: + EntityGetSelectedClassnamesWalker(Classnames& classnames) + : m_classnames(classnames) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected()) + { + Entity* entity = Node_getEntity(path.top()); + if(entity != 0) + { + m_classnames.push_back(entity->getKeyValue("classname")); + } + } + return true; + } +}; + +void Scene_EntityGetClassnames(scene::Graph& graph, Classnames& classnames) +{ + graph.traverse(EntityGetSelectedClassnamesWalker(classnames)); +} + +void Select_AllOfType() +{ + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) + { + if(GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace) + { + GlobalSelectionSystem().setSelectedAllComponents(false); + Scene_BrushSelectByShader_Component(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); + } + } + else + { + Classnames classnames; + Scene_EntityGetClassnames(GlobalSceneGraph(), classnames); + GlobalSelectionSystem().setSelectedAll(false); + if(!classnames.empty()) + { + Scene_EntitySelectByClassnames(GlobalSceneGraph(), classnames); + } + else + { + Scene_BrushSelectByShader(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); + Scene_PatchSelectByShader(GlobalSceneGraph(), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); + } + } +} + +void Select_Inside(void) +{ + SelectByBounds::DoSelection(); +} + +void Select_Touching(void) +{ + SelectByBounds::DoSelection(false); +} + +void Select_FitTexture(float horizontal, float vertical) +{ + if(GlobalSelectionSystem().Mode() != SelectionSystem::eComponent) + { + Scene_BrushFitTexture_Selected(GlobalSceneGraph(), horizontal, vertical); + } + Scene_BrushFitTexture_Component_Selected(GlobalSceneGraph(), horizontal, vertical); + + SceneChangeNotify(); +} + +inline void hide_node(scene::Node& node, bool hide) +{ + hide + ? node.enable(scene::Node::eHidden) + : node.disable(scene::Node::eHidden); +} + +class HideSelectedWalker : public scene::Graph::Walker +{ + bool m_hide; +public: + HideSelectedWalker(bool hide) + : m_hide(hide) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected()) + { + hide_node(path.top(), m_hide); + } + return true; + } +}; + +void Scene_Hide_Selected(bool hide) +{ + GlobalSceneGraph().traverse(HideSelectedWalker(hide)); +} + +void Select_Hide() +{ + Scene_Hide_Selected(true); + SceneChangeNotify(); +} + +void HideSelected() +{ + Select_Hide(); + GlobalSelectionSystem().setSelectedAll(false); +} + + +class HideAllWalker : public scene::Graph::Walker +{ + bool m_hide; +public: + HideAllWalker(bool hide) + : m_hide(hide) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + hide_node(path.top(), m_hide); + return true; + } +}; + +void Scene_Hide_All(bool hide) +{ + GlobalSceneGraph().traverse(HideAllWalker(hide)); +} + +void Select_ShowAllHidden() +{ + Scene_Hide_All(false); + SceneChangeNotify(); +} + + + +void Selection_Flipx() +{ + UndoableCommand undo("mirrorSelected -axis x"); + Select_FlipAxis(0); +} + +void Selection_Flipy() +{ + UndoableCommand undo("mirrorSelected -axis y"); + Select_FlipAxis(1); +} + +void Selection_Flipz() +{ + UndoableCommand undo("mirrorSelected -axis z"); + Select_FlipAxis(2); +} + +void Selection_Rotatex() +{ + UndoableCommand undo("rotateSelected -axis x -angle -90"); + Select_RotateAxis(0,-90); +} + +void Selection_Rotatey() +{ + UndoableCommand undo("rotateSelected -axis y -angle 90"); + Select_RotateAxis(1, 90); +} + +void Selection_Rotatez() +{ + UndoableCommand undo("rotateSelected -axis z -angle -90"); + Select_RotateAxis(2,-90); +} + + + +void Nudge(int nDim, float fNudge) +{ + Vector3 translate(0, 0, 0); + translate[nDim] = fNudge; + + GlobalSelectionSystem().translateSelected(translate); +} + +void Selection_NudgeZ(float amount) +{ + StringOutputStream command; + command << "nudgeSelected -axis z -amount " << amount; + UndoableCommand undo(command.c_str()); + + Nudge(2, amount); +} + +void Selection_MoveDown() +{ + Selection_NudgeZ(-GetGridSize()); +} + +void Selection_MoveUp() +{ + Selection_NudgeZ(GetGridSize()); +} + +void SceneSelectionChange(const Selectable& selectable) +{ + SceneChangeNotify(); +} + +SignalHandlerId Selection_boundsChanged; + +void Selection_construct() +{ + typedef FreeCaller1 SceneSelectionChangeCaller; + GlobalSelectionSystem().addSelectionChangeCallback(SceneSelectionChangeCaller()); + typedef FreeCaller1 UpdateWorkzoneForSelectionChangedCaller; + GlobalSelectionSystem().addSelectionChangeCallback(UpdateWorkzoneForSelectionChangedCaller()); + typedef FreeCaller UpdateWorkzoneForSelectionCaller; + Selection_boundsChanged = GlobalSceneGraph().addBoundsChangedCallback(UpdateWorkzoneForSelectionCaller()); +} + +void Selection_destroy() +{ + GlobalSceneGraph().removeBoundsChangedCallback(Selection_boundsChanged); +} + + +#include "gtkdlgs.h" +#include +#include +#include +#include +#include + + +inline Quaternion quaternion_for_euler_xyz_degrees(const Vector3& eulerXYZ) +{ +#if 0 + return quaternion_for_matrix4_rotation(matrix4_rotation_for_euler_xyz_degrees(eulerXYZ)); +#elif 0 + return quaternion_multiplied_by_quaternion( + quaternion_multiplied_by_quaternion( + quaternion_for_z(degrees_to_radians(eulerXYZ[2])), + quaternion_for_y(degrees_to_radians(eulerXYZ[1])) + ), + quaternion_for_x(degrees_to_radians(eulerXYZ[0])) + ); +#elif 1 + double cx = cos(degrees_to_radians(eulerXYZ[0] * 0.5)); + double sx = sin(degrees_to_radians(eulerXYZ[0] * 0.5)); + double cy = cos(degrees_to_radians(eulerXYZ[1] * 0.5)); + double sy = sin(degrees_to_radians(eulerXYZ[1] * 0.5)); + double cz = cos(degrees_to_radians(eulerXYZ[2] * 0.5)); + double sz = sin(degrees_to_radians(eulerXYZ[2] * 0.5)); + + return Quaternion( + cz * cy * sx - sz * sy * cx, + cz * sy * cx + sz * cy * sx, + sz * cy * cx - cz * sy * sx, + cz * cy * cx + sz * sy * sx + ); +#endif +} + +struct RotateDialog +{ + GtkSpinButton* x; + GtkSpinButton* y; + GtkSpinButton* z; + GtkWindow *window; +}; + +static gboolean rotatedlg_apply (GtkWidget *widget, RotateDialog* rotateDialog) +{ + Vector3 eulerXYZ; + + eulerXYZ[0] = static_cast(gtk_spin_button_get_value(rotateDialog->x)); + eulerXYZ[1] = static_cast(gtk_spin_button_get_value(rotateDialog->y)); + eulerXYZ[2] = static_cast(gtk_spin_button_get_value(rotateDialog->z)); + + StringOutputStream command; + command << "rotateSelectedEulerXYZ -x " << eulerXYZ[0] << " -y " << eulerXYZ[1] << " -z " << eulerXYZ[2]; + UndoableCommand undo(command.c_str()); + + GlobalSelectionSystem().rotateSelected(quaternion_for_euler_xyz_degrees(eulerXYZ)); + return TRUE; +} + +static gboolean rotatedlg_cancel (GtkWidget *widget, RotateDialog* rotateDialog) +{ + gtk_widget_hide(GTK_WIDGET(rotateDialog->window)); + + gtk_spin_button_set_value(rotateDialog->x, 0.0f); // reset to 0 on close + gtk_spin_button_set_value(rotateDialog->y, 0.0f); + gtk_spin_button_set_value(rotateDialog->z, 0.0f); + + return TRUE; +} + +static gboolean rotatedlg_ok (GtkWidget *widget, RotateDialog* rotateDialog) +{ + rotatedlg_apply(widget, rotateDialog); + rotatedlg_cancel(widget, rotateDialog); + return TRUE; +} + +static gboolean rotatedlg_delete (GtkWidget *widget, GdkEventAny *event, RotateDialog* rotateDialog) +{ + rotatedlg_cancel(widget, rotateDialog); + return TRUE; +} + +RotateDialog g_rotate_dialog; +void DoRotateDlg() +{ + if(g_rotate_dialog.window == NULL) + { + g_rotate_dialog.window = create_dialog_window(MainFrame_getWindow(), "Arbitrary rotation", G_CALLBACK(rotatedlg_delete), &g_rotate_dialog); + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group(g_rotate_dialog.window, accel); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(g_rotate_dialog.window), GTK_WIDGET(hbox)); + { + GtkTable* table = create_dialog_table(3, 2, 4, 4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); + { + GtkWidget* label = gtk_label_new (" X "); + gtk_widget_show (label); + gtk_table_attach(table, label, 0, 1, 0, 1, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new (" Y "); + gtk_widget_show (label); + gtk_table_attach(table, label, 0, 1, 1, 2, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new (" Z "); + gtk_widget_show (label); + gtk_table_attach(table, label, 0, 1, 2, 3, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -359, 359, 1, 10, 0)); + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); + gtk_spin_button_set_wrap(spin, TRUE); + + gtk_widget_grab_focus(GTK_WIDGET(spin)); + + g_rotate_dialog.x = spin; + } + { + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -359, 359, 1, 10, 0)); + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); + gtk_spin_button_set_wrap(spin, TRUE); + + g_rotate_dialog.y = spin; + } + { + GtkAdjustment* adj = GTK_ADJUSTMENT(gtk_adjustment_new(0, -359, 359, 1, 10, 0)); + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(adj, 1, 0)); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(table, GTK_WIDGET(spin), 1, 2, 2, 3, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_size_request(GTK_WIDGET(spin), 64, -1); + gtk_spin_button_set_wrap(spin, TRUE); + + g_rotate_dialog.z = spin; + } + } + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + GtkButton* button = create_dialog_button("OK", G_CALLBACK(rotatedlg_ok), &g_rotate_dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(rotatedlg_cancel), &g_rotate_dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_dialog_button("Apply", G_CALLBACK(rotatedlg_apply), &g_rotate_dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + } + } + } + + gtk_widget_show(GTK_WIDGET(g_rotate_dialog.window)); +} + + + + + + + + + +struct ScaleDialog +{ + GtkWidget* x; + GtkWidget* y; + GtkWidget* z; + GtkWindow *window; +}; + +static gboolean scaledlg_apply (GtkWidget *widget, ScaleDialog* scaleDialog) +{ + float sx, sy, sz; + + sx = static_cast(atof(gtk_entry_get_text (GTK_ENTRY (scaleDialog->x)))); + sy = static_cast(atof(gtk_entry_get_text (GTK_ENTRY (scaleDialog->y)))); + sz = static_cast(atof(gtk_entry_get_text (GTK_ENTRY (scaleDialog->z)))); + + StringOutputStream command; + command << "scaleSelected -x " << sx << " -y " << sy << " -z " << sz; + UndoableCommand undo(command.c_str()); + + Select_Scale(sx, sy, sz); + + return TRUE; +} + +static gboolean scaledlg_cancel (GtkWidget *widget, ScaleDialog* scaleDialog) +{ + gtk_widget_hide(GTK_WIDGET(scaleDialog->window)); + + gtk_entry_set_text (GTK_ENTRY(scaleDialog->x), "1.0"); + gtk_entry_set_text (GTK_ENTRY(scaleDialog->y), "1.0"); + gtk_entry_set_text (GTK_ENTRY(scaleDialog->z), "1.0"); + + return TRUE; +} + +static gboolean scaledlg_ok (GtkWidget *widget, ScaleDialog* scaleDialog) +{ + scaledlg_apply(widget, scaleDialog); + scaledlg_cancel(widget, scaleDialog); + return TRUE; +} + +static gboolean scaledlg_delete (GtkWidget *widget, GdkEventAny *event, ScaleDialog* scaleDialog) +{ + scaledlg_cancel(widget, scaleDialog); + return TRUE; +} + +ScaleDialog g_scale_dialog; + +void DoScaleDlg() +{ + if(g_scale_dialog.window == NULL) + { + g_scale_dialog.window = create_dialog_window(MainFrame_getWindow(), "Arbitrary scale", G_CALLBACK(scaledlg_delete), &g_scale_dialog); + + GtkAccelGroup* accel = gtk_accel_group_new(); + gtk_window_add_accel_group(g_scale_dialog.window, accel); + + { + GtkHBox* hbox = create_dialog_hbox(4, 4); + gtk_container_add(GTK_CONTAINER(g_scale_dialog.window), GTK_WIDGET(hbox)); + { + GtkTable* table = create_dialog_table(3, 2, 4, 4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(table), TRUE, TRUE, 0); + { + GtkWidget* label = gtk_label_new (" X "); + gtk_widget_show (label); + gtk_table_attach(table, label, 0, 1, 0, 1, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new (" Y "); + gtk_widget_show (label); + gtk_table_attach(table, label, 0, 1, 1, 2, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new (" Z "); + gtk_widget_show (label); + gtk_table_attach(table, label, 0, 1, 2, 3, + (GtkAttachOptions) (0), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* entry = gtk_entry_new(); + gtk_entry_set_text (GTK_ENTRY(entry), "1.0"); + gtk_widget_show (entry); + gtk_table_attach(table, entry, 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + g_scale_dialog.x = entry; + } + { + GtkWidget* entry = gtk_entry_new(); + gtk_entry_set_text (GTK_ENTRY(entry), "1.0"); + gtk_widget_show (entry); + gtk_table_attach(table, entry, 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + g_scale_dialog.y = entry; + } + { + GtkWidget* entry = gtk_entry_new(); + gtk_entry_set_text (GTK_ENTRY(entry), "1.0"); + gtk_widget_show (entry); + gtk_table_attach(table, entry, 1, 2, 2, 3, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + + g_scale_dialog.z = entry; + } + } + { + GtkVBox* vbox = create_dialog_vbox(4); + gtk_box_pack_start(GTK_BOX(hbox), GTK_WIDGET(vbox), TRUE, TRUE, 0); + { + GtkButton* button = create_dialog_button("OK", G_CALLBACK(scaledlg_ok), &g_scale_dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + widget_make_default(GTK_WIDGET(button)); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_dialog_button("Cancel", G_CALLBACK(scaledlg_cancel), &g_scale_dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + gtk_widget_add_accelerator(GTK_WIDGET(button), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0); + } + { + GtkButton* button = create_dialog_button("Apply", G_CALLBACK(scaledlg_apply), &g_scale_dialog); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(button), FALSE, FALSE, 0); + } + } + } + } + + gtk_widget_show(GTK_WIDGET(g_scale_dialog.window)); +} diff --git a/misc/mediasource/netradiant-src/radiant/select.h b/misc/mediasource/netradiant-src/radiant/select.h new file mode 100644 index 00000000..5a019f7c --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/select.h @@ -0,0 +1,91 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_SELECT_H) +#define INCLUDED_SELECT_H + +#include "math/vector.h" + +void Select_GetBounds(Vector3& mins, Vector3& maxs); +void Select_GetMid(Vector3& mid); + +void Select_Delete(); +void Select_Invert(); +void Select_Inside(); +void Select_Touching(); +void Scene_ExpandSelectionToEntities(); + +void Selection_Flipx(); +void Selection_Flipy(); +void Selection_Flipz(); +void Selection_Rotatex(); +void Selection_Rotatey(); +void Selection_Rotatez(); + + +void Selection_MoveDown(); +void Selection_MoveUp(); + +void Select_AllOfType(); + +void DoRotateDlg(); +void DoScaleDlg(); + + +void Select_SetShader(const char* shader); + +class TextureProjection; +void Select_SetTexdef(const TextureProjection& projection); + +class ContentsFlagsValue; +void Select_SetFlags(const ContentsFlagsValue& flags); + +void Select_RotateTexture(float amt); +void Select_ScaleTexture(float x, float y); +void Select_ShiftTexture(float x, float y); +void Select_FitTexture(float horizontal = 1, float vertical = 1); +void FindReplaceTextures(const char* pFind, const char* pReplace, bool bSelected); + +void HideSelected(); +void Select_ShowAllHidden(); + +// updating workzone to a given brush (depends on current view) + +void Selection_construct(); +void Selection_destroy(); + + +struct select_workzone_t +{ + // defines the boundaries of the current work area + // is used to guess brushes and drop points third coordinate when creating from 2D view + Vector3 d_work_min, d_work_max; + + select_workzone_t() : + d_work_min(-64.0f,-64.0f,-64.0f), + d_work_max( 64.0f, 64.0f, 64.0f) + { + } +}; + +const select_workzone_t& Select_getWorkZone(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/selection.cpp b/misc/mediasource/netradiant-src/radiant/selection.cpp new file mode 100644 index 00000000..3b477990 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/selection.cpp @@ -0,0 +1,4179 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "selection.h" + +#include "debugging/debugging.h" + +#include +#include +#include + +#include "windowobserver.h" +#include "iundo.h" +#include "ientity.h" +#include "cullable.h" +#include "renderable.h" +#include "selectable.h" +#include "editable.h" + +#include "math/frustum.h" +#include "signal/signal.h" +#include "generic/object.h" +#include "selectionlib.h" +#include "render.h" +#include "view.h" +#include "renderer.h" +#include "stream/stringstream.h" +#include "eclasslib.h" +#include "generic/bitfield.h" +#include "generic/static.h" +#include "pivot.h" +#include "stringio.h" +#include "container/container.h" + +#include "grid.h" + +TextOutputStream& ostream_write(TextOutputStream& t, const Vector4& v) +{ + return t << "[ " << v.x() << " " << v.y() << " " << v.z() << " " << v.w() << " ]"; +} + +TextOutputStream& ostream_write(TextOutputStream& t, const Matrix4& m) +{ + return t << "[ " << m.x() << " " << m.y() << " " << m.z() << " " << m.t() << " ]"; +} + +struct Pivot2World +{ + Matrix4 m_worldSpace; + Matrix4 m_viewpointSpace; + Matrix4 m_viewplaneSpace; + Vector3 m_axis_screen; + + void update(const Matrix4& pivot2world, const Matrix4& modelview, const Matrix4& projection, const Matrix4& viewport) + { + Pivot2World_worldSpace(m_worldSpace, pivot2world, modelview, projection, viewport); + Pivot2World_viewpointSpace(m_viewpointSpace, m_axis_screen, pivot2world, modelview, projection, viewport); + Pivot2World_viewplaneSpace(m_viewplaneSpace, pivot2world, modelview, projection, viewport); + } +}; + + +void point_for_device_point(Vector3& point, const Matrix4& device2object, const float x, const float y, const float z) +{ + // transform from normalised device coords to object coords + point = vector4_projected(matrix4_transformed_vector4(device2object, Vector4(x, y, z, 1))); +} + +void ray_for_device_point(Ray& ray, const Matrix4& device2object, const float x, const float y) +{ + // point at x, y, zNear + point_for_device_point(ray.origin, device2object, x, y, -1); + + // point at x, y, zFar + point_for_device_point(ray.direction, device2object, x, y, 1); + + // construct ray + vector3_subtract(ray.direction, ray.origin); + vector3_normalise(ray.direction); +} + +bool sphere_intersect_ray(const Vector3& origin, float radius, const Ray& ray, Vector3& intersection) +{ + intersection = vector3_subtracted(origin, ray.origin); + const double a = vector3_dot(intersection, ray.direction); + const double d = radius * radius - (vector3_dot(intersection, intersection) - a * a); + + if(d > 0) + { + intersection = vector3_added(ray.origin, vector3_scaled(ray.direction, a - sqrt(d))); + return true; + } + else + { + intersection = vector3_added( ray.origin, vector3_scaled(ray.direction, a)); + return false; + } +} + +void ray_intersect_ray(const Ray& ray, const Ray& other, Vector3& intersection) +{ + intersection = vector3_subtracted(ray.origin, other.origin); + //float a = 1;//vector3_dot(ray.direction, ray.direction); // always >= 0 + double dot = vector3_dot(ray.direction, other.direction); + //float c = 1;//vector3_dot(other.direction, other.direction); // always >= 0 + double d = vector3_dot(ray.direction, intersection); + double e = vector3_dot(other.direction, intersection); + double D = 1 - dot*dot;//a*c - dot*dot; // always >= 0 + + if (D < 0.000001) + { + // the lines are almost parallel + intersection = vector3_added(other.origin, vector3_scaled(other.direction, e)); + } + else + { + intersection = vector3_added(other.origin, vector3_scaled(other.direction, (e - dot*d) / D)); + } +} + +const Vector3 g_origin(0, 0, 0); +const float g_radius = 64; + +void point_on_sphere(Vector3& point, const Matrix4& device2object, const float x, const float y) +{ + Ray ray; + ray_for_device_point(ray, device2object, x, y); + sphere_intersect_ray(g_origin, g_radius, ray, point); +} + +void point_on_axis(Vector3& point, const Vector3& axis, const Matrix4& device2object, const float x, const float y) +{ + Ray ray; + ray_for_device_point(ray, device2object, x, y); + ray_intersect_ray(ray, Ray(Vector3(0, 0, 0), axis), point); +} + +void point_on_plane(Vector3& point, const Matrix4& device2object, const float x, const float y) +{ + Matrix4 object2device(matrix4_full_inverse(device2object)); + point = vector4_projected(matrix4_transformed_vector4(device2object, Vector4(x, y, object2device[14] / object2device[15], 1))); +} + +//! a and b are unit vectors .. returns angle in radians +inline float angle_between(const Vector3& a, const Vector3& b) +{ + return static_cast(2.0 * atan2( + vector3_length(vector3_subtracted(a, b)), + vector3_length(vector3_added(a, b)) + )); +} + + +#if defined(_DEBUG) +class test_quat +{ +public: + test_quat(const Vector3& from, const Vector3& to) + { + Vector4 quaternion(quaternion_for_unit_vectors(from, to)); + Matrix4 matrix(matrix4_rotation_for_quaternion(quaternion_multiplied_by_quaternion(quaternion, c_quaternion_identity))); + } +private: +}; + +static test_quat bleh(g_vector3_axis_x, g_vector3_axis_y); +#endif + +//! axis is a unit vector +inline void constrain_to_axis(Vector3& vec, const Vector3& axis) +{ + vec = vector3_normalised(vector3_added(vec, vector3_scaled(axis, -vector3_dot(vec, axis)))); +} + +//! a and b are unit vectors .. a and b must be orthogonal to axis .. returns angle in radians +float angle_for_axis(const Vector3& a, const Vector3& b, const Vector3& axis) +{ + if(vector3_dot(axis, vector3_cross(a, b)) > 0.0) + return angle_between(a, b); + else + return -angle_between(a, b); +} + +float distance_for_axis(const Vector3& a, const Vector3& b, const Vector3& axis) +{ + return static_cast(vector3_dot(b, axis) - vector3_dot(a, axis)); +} + +class Manipulatable +{ +public: + virtual void Construct(const Matrix4& device2manip, const float x, const float y) = 0; + virtual void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) = 0; +}; + +void transform_local2object(Matrix4& object, const Matrix4& local, const Matrix4& local2object) +{ + object = matrix4_multiplied_by_matrix4( + matrix4_multiplied_by_matrix4(local2object, local), + matrix4_full_inverse(local2object) + ); +} + +class Rotatable +{ +public: + virtual void rotate(const Quaternion& rotation) = 0; +}; + +class RotateFree : public Manipulatable +{ + Vector3 m_start; + Rotatable& m_rotatable; +public: + RotateFree(Rotatable& rotatable) + : m_rotatable(rotatable) + { + } + void Construct(const Matrix4& device2manip, const float x, const float y) + { + point_on_sphere(m_start, device2manip, x, y); + vector3_normalise(m_start); + } + void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) + { + Vector3 current; + + point_on_sphere(current, device2manip, x, y); + vector3_normalise(current); + + m_rotatable.rotate(quaternion_for_unit_vectors(m_start, current)); + } +}; + +class RotateAxis : public Manipulatable +{ + Vector3 m_axis; + Vector3 m_start; + Rotatable& m_rotatable; +public: + RotateAxis(Rotatable& rotatable) + : m_rotatable(rotatable) + { + } + void Construct(const Matrix4& device2manip, const float x, const float y) + { + point_on_sphere(m_start, device2manip, x, y); + constrain_to_axis(m_start, m_axis); + } + /// \brief Converts current position to a normalised vector orthogonal to axis. + void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) + { + Vector3 current; + point_on_sphere(current, device2manip, x, y); + constrain_to_axis(current, m_axis); + + m_rotatable.rotate(quaternion_for_axisangle(m_axis, angle_for_axis(m_start, current, m_axis))); + } + + void SetAxis(const Vector3& axis) + { + m_axis = axis; + } +}; + +void translation_local2object(Vector3& object, const Vector3& local, const Matrix4& local2object) +{ + object = matrix4_get_translation_vec3( + matrix4_multiplied_by_matrix4( + matrix4_translated_by_vec3(local2object, local), + matrix4_full_inverse(local2object) + ) + ); +} + +class Translatable +{ +public: + virtual void translate(const Vector3& translation) = 0; +}; + +class TranslateAxis : public Manipulatable +{ + Vector3 m_start; + Vector3 m_axis; + Translatable& m_translatable; +public: + TranslateAxis(Translatable& translatable) + : m_translatable(translatable) + { + } + void Construct(const Matrix4& device2manip, const float x, const float y) + { + point_on_axis(m_start, m_axis, device2manip, x, y); + } + void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) + { + Vector3 current; + point_on_axis(current, m_axis, device2manip, x, y); + current = vector3_scaled(m_axis, distance_for_axis(m_start, current, m_axis)); + + translation_local2object(current, current, manip2object); + vector3_snap(current, GetSnapGridSize()); + + m_translatable.translate(current); + } + + void SetAxis(const Vector3& axis) + { + m_axis = axis; + } +}; + +class TranslateFree : public Manipulatable +{ +private: + Vector3 m_start; + Translatable& m_translatable; +public: + TranslateFree(Translatable& translatable) + : m_translatable(translatable) + { + } + void Construct(const Matrix4& device2manip, const float x, const float y) + { + point_on_plane(m_start, device2manip, x, y); + } + void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) + { + Vector3 current; + point_on_plane(current, device2manip, x, y); + current = vector3_subtracted(current, m_start); + + translation_local2object(current, current, manip2object); + vector3_snap(current, GetSnapGridSize()); + + m_translatable.translate(current); + } +}; + + +class Scalable +{ +public: + virtual void scale(const Vector3& scaling) = 0; +}; + + +class ScaleAxis : public Manipulatable +{ +private: + Vector3 m_start; + Vector3 m_axis; + Scalable& m_scalable; +public: + ScaleAxis(Scalable& scalable) + : m_scalable(scalable) + { + } + void Construct(const Matrix4& device2manip, const float x, const float y) + { + point_on_axis(m_start, m_axis, device2manip, x, y); + } + void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) + { + Vector3 current; + point_on_axis(current, m_axis, device2manip, x, y); + Vector3 delta = vector3_subtracted(current, m_start); + + translation_local2object(delta, delta, manip2object); + vector3_snap(delta, GetSnapGridSize()); + + Vector3 start(vector3_snapped(m_start, GetSnapGridSize())); + Vector3 scale( + start[0] == 0 ? 1 : 1 + delta[0] / start[0], + start[1] == 0 ? 1 : 1 + delta[1] / start[1], + start[2] == 0 ? 1 : 1 + delta[2] / start[2] + ); + m_scalable.scale(scale); + } + + void SetAxis(const Vector3& axis) + { + m_axis = axis; + } +}; + +class ScaleFree : public Manipulatable +{ +private: + Vector3 m_start; + Scalable& m_scalable; +public: + ScaleFree(Scalable& scalable) + : m_scalable(scalable) + { + } + void Construct(const Matrix4& device2manip, const float x, const float y) + { + point_on_plane(m_start, device2manip, x, y); + } + void Transform(const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y) + { + Vector3 current; + point_on_plane(current, device2manip, x, y); + Vector3 delta = vector3_subtracted(current, m_start); + + translation_local2object(delta, delta, manip2object); + vector3_snap(delta, GetSnapGridSize()); + + Vector3 start(vector3_snapped(m_start, GetSnapGridSize())); + Vector3 scale( + start[0] == 0 ? 1 : 1 + delta[0] / start[0], + start[1] == 0 ? 1 : 1 + delta[1] / start[1], + start[2] == 0 ? 1 : 1 + delta[2] / start[2] + ); + m_scalable.scale(scale); + } +}; + + + + + + + + + + +class RenderableClippedPrimitive : public OpenGLRenderable +{ + struct primitive_t + { + PointVertex m_points[9]; + std::size_t m_count; + }; + Matrix4 m_inverse; + std::vector m_primitives; +public: + Matrix4 m_world; + + void render(RenderStateFlags state) const + { + for(std::size_t i=0; i P[1])) // an upward crossing + || (((*prev)[1] > P[1]) && ((*cur)[1] <= P[1]))) + { // a downward crossing + // compute the actual edge-ray intersect x-coordinate + float vt = (float)(P[1] - (*prev)[1]) / ((*cur)[1] - (*prev)[1]); + if (P[0] < (*prev)[0] + vt * ((*cur)[0] - (*prev)[0])) // P[0] < intersect + { + ++crossings; // a valid crossing of y=P[1] right of P[0] + } + } + } + return (crossings & 0x1) != 0; // 0 if even (out), and 1 if odd (in) +} + +inline double triangle_signed_area_XY(const Vector3& p0, const Vector3& p1, const Vector3& p2) +{ + return ((p1[0] - p0[0]) * (p2[1] - p0[1])) - ((p2[0] - p0[0]) * (p1[1] - p0[1])); +} + +enum clipcull_t +{ + eClipCullNone, + eClipCullCW, + eClipCullCCW, +}; + + +inline SelectionIntersection select_point_from_clipped(Vector4& clipped) +{ + return SelectionIntersection(clipped[2] / clipped[3], static_cast(vector3_length_squared(Vector3(clipped[0] / clipped[3], clipped[1] / clipped[3], 0)))); +} + +void BestPoint(std::size_t count, Vector4 clipped[9], SelectionIntersection& best, clipcull_t cull) +{ + Vector3 normalised[9]; + + { + for(std::size_t i=0; i 2) + { + double signed_area = triangle_signed_area_XY(normalised[0], normalised[1], normalised[2]); + + if((cull == eClipCullCW && signed_area > 0) + || (cull == eClipCullCCW && signed_area < 0)) + return; + } + + if(count == 2) + { + Segment3D segment(normalised[0], normalised[1]); + Point3D point = segment_closest_point_to_point(segment, Vector3(0, 0, 0)); + assign_if_closer(best, SelectionIntersection(point.z(), 0)); + } + else if(count > 2 && !point_test_polygon_2d(Vector3(0, 0, 0), normalised, normalised + count)) + { + point_iterator_t end = normalised + count; + for(point_iterator_t previous = end-1, current = normalised; current != end; previous = current, ++current) + { + Segment3D segment(*previous, *current); + Point3D point = segment_closest_point_to_point(segment, Vector3(0, 0, 0)); + float depth = point.z(); + point.z() = 0; + float distance = static_cast(vector3_length_squared(point)); + + assign_if_closer(best, SelectionIntersection(depth, distance)); + } + } + else if(count > 2) + { + assign_if_closer( + best, + SelectionIntersection( + static_cast(ray_distance_to_plane( + Ray(Vector3(0, 0, 0), Vector3(0, 0, 1)), + plane3_for_points(normalised[0], normalised[1], normalised[2]) + )), + 0 + ) + ); + } + +#if defined(DEBUG_SELECTION) + if(count >= 2) + g_render_clipped.insert(clipped, count); +#endif +} + +void LineStrip_BestPoint(const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best) +{ + Vector4 clipped[2]; + for(std::size_t i = 0; (i + 1) < size; ++i) + { + const std::size_t count = matrix4_clip_line(local2view, vertex3f_to_vector3(vertices[i].vertex), vertex3f_to_vector3(vertices[i + 1].vertex), clipped); + BestPoint(count, clipped, best, eClipCullNone); + } +} + +void LineLoop_BestPoint(const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best) +{ + Vector4 clipped[2]; + for(std::size_t i = 0; i < size; ++i) + { + const std::size_t count = matrix4_clip_line(local2view, vertex3f_to_vector3(vertices[i].vertex), vertex3f_to_vector3(vertices[(i+1)%size].vertex), clipped); + BestPoint(count, clipped, best, eClipCullNone); + } +} + +void Line_BestPoint(const Matrix4& local2view, const PointVertex vertices[2], SelectionIntersection& best) +{ + Vector4 clipped[2]; + const std::size_t count = matrix4_clip_line(local2view, vertex3f_to_vector3(vertices[0].vertex), vertex3f_to_vector3(vertices[1].vertex), clipped); + BestPoint(count, clipped, best, eClipCullNone); +} + +void Circle_BestPoint(const Matrix4& local2view, clipcull_t cull, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best) +{ + Vector4 clipped[9]; + for(std::size_t i=0; i((*x).vertex), + reinterpret_cast((*y).vertex), + reinterpret_cast((*z).vertex), + clipped + ), + clipped, + best, + cull + ); + } +} + + +typedef std::multimap SelectableSortedSet; + +class SelectionPool : public Selector +{ + SelectableSortedSet m_pool; + SelectionIntersection m_intersection; + Selectable* m_selectable; + +public: + void pushSelectable(Selectable& selectable) + { + m_intersection = SelectionIntersection(); + m_selectable = &selectable; + } + void popSelectable() + { + addSelectable(m_intersection, m_selectable); + m_intersection = SelectionIntersection(); + } + void addIntersection(const SelectionIntersection& intersection) + { + assign_if_closer(m_intersection, intersection); + } + void addSelectable(const SelectionIntersection& intersection, Selectable* selectable) + { + if(intersection.valid()) + { + m_pool.insert(SelectableSortedSet::value_type(intersection, selectable)); + } + } + + typedef SelectableSortedSet::iterator iterator; + + iterator begin() + { + return m_pool.begin(); + } + iterator end() + { + return m_pool.end(); + } + + bool failed() + { + return m_pool.empty(); + } +}; + + +const Colour4b g_colour_sphere(0, 0, 0, 255); +const Colour4b g_colour_screen(0, 255, 255, 255); +const Colour4b g_colour_selected(255, 255, 0, 255); + +inline const Colour4b& colourSelected(const Colour4b& colour, bool selected) +{ + return (selected) ? g_colour_selected : colour; +} + +template +inline void draw_semicircle(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; + remap_policy::set(vertices[segments << 2].vertex, -radius, 0, 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); + +#if 0 + PointVertex* m = i + (segments << 2); + PointVertex* n = j + (segments << 2); + PointVertex* o = k + (segments << 2); + PointVertex* p = l + (segments << 2); +#endif + + remap_policy::set(i->vertex, x,-y, 0); + remap_policy::set(k->vertex,-y,-x, 0); +#if 0 + remap_policy::set(m->vertex,-x, y, 0); + remap_policy::set(o->vertex, y, x, 0); +#endif + + ++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); +#if 0 + remap_policy::set(n->vertex,-y, x, 0); + remap_policy::set(p->vertex, x, y, 0); +#endif + } +} + +class Manipulator +{ +public: + virtual Manipulatable* GetManipulatable() = 0; + virtual void testSelect(const View& view, const Matrix4& pivot2world) + { + } + virtual void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) + { + } + virtual void setSelected(bool select) = 0; + virtual bool isSelected() const = 0; +}; + + +inline Vector3 normalised_safe(const Vector3& self) +{ + if(vector3_equal(self, g_vector3_identity)) + { + return g_vector3_identity; + } + return vector3_normalised(self); +} + + +class RotateManipulator : public Manipulator +{ + struct RenderableCircle : public OpenGLRenderable + { + Array m_vertices; + + RenderableCircle(std::size_t size) : m_vertices(size) + { + } + void render(RenderStateFlags state) const + { + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices.data()->colour); + glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices.data()->vertex); + glDrawArrays(GL_LINE_LOOP, 0, GLsizei(m_vertices.size())); + } + void setColour(const Colour4b& colour) + { + for(Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i) + { + (*i).colour = colour; + } + } + }; + + struct RenderableSemiCircle : public OpenGLRenderable + { + Array m_vertices; + + RenderableSemiCircle(std::size_t size) : m_vertices(size) + { + } + void render(RenderStateFlags state) const + { + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices.data()->colour); + glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices.data()->vertex); + glDrawArrays(GL_LINE_STRIP, 0, GLsizei(m_vertices.size())); + } + void setColour(const Colour4b& colour) + { + for(Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i) + { + (*i).colour = colour; + } + } + }; + + RotateFree m_free; + RotateAxis m_axis; + Vector3 m_axis_screen; + RenderableSemiCircle m_circle_x; + RenderableSemiCircle m_circle_y; + RenderableSemiCircle m_circle_z; + RenderableCircle m_circle_screen; + RenderableCircle m_circle_sphere; + SelectableBool m_selectable_x; + SelectableBool m_selectable_y; + SelectableBool m_selectable_z; + SelectableBool m_selectable_screen; + SelectableBool m_selectable_sphere; + Pivot2World m_pivot; + Matrix4 m_local2world_x; + Matrix4 m_local2world_y; + Matrix4 m_local2world_z; + bool m_circle_x_visible; + bool m_circle_y_visible; + bool m_circle_z_visible; +public: + static Shader* m_state_outer; + + RotateManipulator(Rotatable& rotatable, std::size_t segments, float radius) : + m_free(rotatable), + m_axis(rotatable), + m_circle_x((segments << 2) + 1), + m_circle_y((segments << 2) + 1), + m_circle_z((segments << 2) + 1), + m_circle_screen(segments<<3), + m_circle_sphere(segments<<3) + { + draw_semicircle(segments, radius, m_circle_x.m_vertices.data(), RemapYZX()); + draw_semicircle(segments, radius, m_circle_y.m_vertices.data(), RemapZXY()); + draw_semicircle(segments, radius, m_circle_z.m_vertices.data(), RemapXYZ()); + + draw_circle(segments, radius * 1.15f, m_circle_screen.m_vertices.data(), RemapXYZ()); + draw_circle(segments, radius, m_circle_sphere.m_vertices.data(), RemapXYZ()); + } + + + void UpdateColours() + { + m_circle_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); + m_circle_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); + m_circle_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); + m_circle_screen.setColour(colourSelected(g_colour_screen, m_selectable_screen.isSelected())); + m_circle_sphere.setColour(colourSelected(g_colour_sphere, false)); + } + + void updateCircleTransforms() + { + Vector3 localViewpoint(matrix4_transformed_direction(matrix4_transposed(m_pivot.m_worldSpace), vector4_to_vector3(m_pivot.m_viewpointSpace.z()))); + + m_circle_x_visible = !vector3_equal_epsilon(g_vector3_axis_x, localViewpoint, 1e-6f); + if(m_circle_x_visible) + { + m_local2world_x = g_matrix4_identity; + vector4_to_vector3(m_local2world_x.y()) = normalised_safe( + vector3_cross(g_vector3_axis_x, localViewpoint) + ); + vector4_to_vector3(m_local2world_x.z()) = normalised_safe( + vector3_cross(vector4_to_vector3(m_local2world_x.x()), vector4_to_vector3(m_local2world_x.y())) + ); + matrix4_premultiply_by_matrix4(m_local2world_x, m_pivot.m_worldSpace); + } + + m_circle_y_visible = !vector3_equal_epsilon(g_vector3_axis_y, localViewpoint, 1e-6f); + if(m_circle_y_visible) + { + m_local2world_y = g_matrix4_identity; + vector4_to_vector3(m_local2world_y.z()) = normalised_safe( + vector3_cross(g_vector3_axis_y, localViewpoint) + ); + vector4_to_vector3(m_local2world_y.x()) = normalised_safe( + vector3_cross(vector4_to_vector3(m_local2world_y.y()), vector4_to_vector3(m_local2world_y.z())) + ); + matrix4_premultiply_by_matrix4(m_local2world_y, m_pivot.m_worldSpace); + } + + m_circle_z_visible = !vector3_equal_epsilon(g_vector3_axis_z, localViewpoint, 1e-6f); + if(m_circle_z_visible) + { + m_local2world_z = g_matrix4_identity; + vector4_to_vector3(m_local2world_z.x()) = normalised_safe( + vector3_cross(g_vector3_axis_z, localViewpoint) + ); + vector4_to_vector3(m_local2world_z.y()) = normalised_safe( + vector3_cross(vector4_to_vector3(m_local2world_z.z()), vector4_to_vector3(m_local2world_z.x())) + ); + matrix4_premultiply_by_matrix4(m_local2world_z, m_pivot.m_worldSpace); + } + } + + void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) + { + m_pivot.update(pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport()); + updateCircleTransforms(); + + // temp hack + UpdateColours(); + + renderer.SetState(m_state_outer, Renderer::eWireframeOnly); + renderer.SetState(m_state_outer, Renderer::eFullMaterials); + + renderer.addRenderable(m_circle_screen, m_pivot.m_viewpointSpace); + renderer.addRenderable(m_circle_sphere, m_pivot.m_viewpointSpace); + + if(m_circle_x_visible) + { + renderer.addRenderable(m_circle_x, m_local2world_x); + } + if(m_circle_y_visible) + { + renderer.addRenderable(m_circle_y, m_local2world_y); + } + if(m_circle_z_visible) + { + renderer.addRenderable(m_circle_z, m_local2world_z); + } + } + void testSelect(const View& view, const Matrix4& pivot2world) + { + m_pivot.update(pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport()); + updateCircleTransforms(); + + SelectionPool selector; + + { + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_local2world_x)); + +#if defined(DEBUG_SELECTION) + g_render_clipped.construct(view.GetViewMatrix()); +#endif + + SelectionIntersection best; + LineStrip_BestPoint(local2view, m_circle_x.m_vertices.data(), m_circle_x.m_vertices.size(), best); + selector.addSelectable(best, &m_selectable_x); + } + + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_local2world_y)); + +#if defined(DEBUG_SELECTION) + g_render_clipped.construct(view.GetViewMatrix()); +#endif + + SelectionIntersection best; + LineStrip_BestPoint(local2view, m_circle_y.m_vertices.data(), m_circle_y.m_vertices.size(), best); + selector.addSelectable(best, &m_selectable_y); + } + + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_local2world_z)); + +#if defined(DEBUG_SELECTION) + g_render_clipped.construct(view.GetViewMatrix()); +#endif + + SelectionIntersection best; + LineStrip_BestPoint(local2view, m_circle_z.m_vertices.data(), m_circle_z.m_vertices.size(), best); + selector.addSelectable(best, &m_selectable_z); + } + } + + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_viewpointSpace)); + + { + SelectionIntersection best; + LineLoop_BestPoint(local2view, m_circle_screen.m_vertices.data(), m_circle_screen.m_vertices.size(), best); + selector.addSelectable(best, &m_selectable_screen); + } + + { + SelectionIntersection best; + Circle_BestPoint(local2view, eClipCullCW, m_circle_sphere.m_vertices.data(), m_circle_sphere.m_vertices.size(), best); + selector.addSelectable(best, &m_selectable_sphere); + } + } + + m_axis_screen = m_pivot.m_axis_screen; + + if(!selector.failed()) + { + (*selector.begin()).second->setSelected(true); + } + } + + Manipulatable* GetManipulatable() + { + if(m_selectable_x.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_x); + return &m_axis; + } + else if(m_selectable_y.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_y); + return &m_axis; + } + else if(m_selectable_z.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_z); + return &m_axis; + } + else if(m_selectable_screen.isSelected()) + { + m_axis.SetAxis(m_axis_screen); + return &m_axis; + } + else + return &m_free; + } + + void setSelected(bool select) + { + m_selectable_x.setSelected(select); + m_selectable_y.setSelected(select); + m_selectable_z.setSelected(select); + m_selectable_screen.setSelected(select); + } + bool isSelected() const + { + return m_selectable_x.isSelected() + | m_selectable_y.isSelected() + | m_selectable_z.isSelected() + | m_selectable_screen.isSelected() + | m_selectable_sphere.isSelected(); + } +}; + +Shader* RotateManipulator::m_state_outer; + + +const float arrowhead_length = 16; +const float arrowhead_radius = 4; + +inline void draw_arrowline(const float length, PointVertex* line, const std::size_t axis) +{ + (*line++).vertex = vertex3f_identity; + (*line).vertex = vertex3f_identity; + vertex3f_to_array((*line).vertex)[axis] = length - arrowhead_length; +} + +template +inline void draw_arrowhead(const std::size_t segments, const float length, FlatShadedVertex* vertices, VertexRemap, NormalRemap) +{ + std::size_t head_tris = (segments << 3); + const double head_segment = c_2pi / head_tris; + for(std::size_t i = 0; i < head_tris; ++i) + { + { + FlatShadedVertex& point = vertices[i*6+0]; + VertexRemap::x(point.vertex) = length - arrowhead_length; + VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos(i * head_segment)); + VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin(i * head_segment)); + NormalRemap::x(point.normal) = arrowhead_radius / arrowhead_length; + NormalRemap::y(point.normal) = static_cast(cos(i * head_segment)); + NormalRemap::z(point.normal) = static_cast(sin(i * head_segment)); + } + { + FlatShadedVertex& point = vertices[i*6+1]; + VertexRemap::x(point.vertex) = length; + VertexRemap::y(point.vertex) = 0; + VertexRemap::z(point.vertex) = 0; + NormalRemap::x(point.normal) = arrowhead_radius / arrowhead_length; + NormalRemap::y(point.normal) = static_cast(cos((i + 0.5) * head_segment)); + NormalRemap::z(point.normal) = static_cast(sin((i + 0.5) * head_segment)); + } + { + FlatShadedVertex& point = vertices[i*6+2]; + VertexRemap::x(point.vertex) = length - arrowhead_length; + VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos((i+1) * head_segment)); + VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin((i+1) * head_segment)); + NormalRemap::x(point.normal) = arrowhead_radius / arrowhead_length; + NormalRemap::y(point.normal) = static_cast(cos((i+1) * head_segment)); + NormalRemap::z(point.normal) = static_cast(sin((i+1) * head_segment)); + } + + { + FlatShadedVertex& point = vertices[i*6+3]; + VertexRemap::x(point.vertex) = length - arrowhead_length; + VertexRemap::y(point.vertex) = 0; + VertexRemap::z(point.vertex) = 0; + NormalRemap::x(point.normal) = -1; + NormalRemap::y(point.normal) = 0; + NormalRemap::z(point.normal) = 0; + } + { + FlatShadedVertex& point = vertices[i*6+4]; + VertexRemap::x(point.vertex) = length - arrowhead_length; + VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos(i * head_segment)); + VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin(i * head_segment)); + NormalRemap::x(point.normal) = -1; + NormalRemap::y(point.normal) = 0; + NormalRemap::z(point.normal) = 0; + } + { + FlatShadedVertex& point = vertices[i*6+5]; + VertexRemap::x(point.vertex) = length - arrowhead_length; + VertexRemap::y(point.vertex) = arrowhead_radius * static_cast(cos((i+1) * head_segment)); + VertexRemap::z(point.vertex) = arrowhead_radius * static_cast(sin((i+1) * head_segment)); + NormalRemap::x(point.normal) = -1; + NormalRemap::y(point.normal) = 0; + NormalRemap::z(point.normal) = 0; + } + } +} + +template +class TripleRemapXYZ +{ +public: + static float& x(Triple& triple) + { + return triple.x(); + } + static float& y(Triple& triple) + { + return triple.y(); + } + static float& z(Triple& triple) + { + return triple.z(); + } +}; + +template +class TripleRemapYZX +{ +public: + static float& x(Triple& triple) + { + return triple.y(); + } + static float& y(Triple& triple) + { + return triple.z(); + } + static float& z(Triple& triple) + { + return triple.x(); + } +}; + +template +class TripleRemapZXY +{ +public: + static float& x(Triple& triple) + { + return triple.z(); + } + static float& y(Triple& triple) + { + return triple.x(); + } + static float& z(Triple& triple) + { + return triple.y(); + } +}; + +void vector3_print(const Vector3& v) +{ + globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )"; +} + +class TranslateManipulator : public Manipulator +{ + struct RenderableArrowLine : public OpenGLRenderable + { + PointVertex m_line[2]; + + RenderableArrowLine() + { + } + void render(RenderStateFlags state) const + { + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_line[0].colour); + glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_line[0].vertex); + glDrawArrays(GL_LINES, 0, 2); + } + void setColour(const Colour4b& colour) + { + m_line[0].colour = colour; + m_line[1].colour = colour; + } + }; + struct RenderableArrowHead : public OpenGLRenderable + { + Array m_vertices; + + RenderableArrowHead(std::size_t size) + : m_vertices(size) + { + } + void render(RenderStateFlags state) const + { + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(FlatShadedVertex), &m_vertices.data()->colour); + glVertexPointer(3, GL_FLOAT, sizeof(FlatShadedVertex), &m_vertices.data()->vertex); + glNormalPointer(GL_FLOAT, sizeof(FlatShadedVertex), &m_vertices.data()->normal); + glDrawArrays(GL_TRIANGLES, 0, GLsizei(m_vertices.size())); + } + void setColour(const Colour4b& colour) + { + for(Array::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i) + { + (*i).colour = colour; + } + } + }; + struct RenderableQuad : public OpenGLRenderable + { + PointVertex m_quad[4]; + void render(RenderStateFlags state) const + { + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_quad[0].colour); + glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_quad[0].vertex); + glDrawArrays(GL_LINE_LOOP, 0, 4); + } + void setColour(const Colour4b& colour) + { + m_quad[0].colour = colour; + m_quad[1].colour = colour; + m_quad[2].colour = colour; + m_quad[3].colour = colour; + } + }; + + TranslateFree m_free; + TranslateAxis m_axis; + RenderableArrowLine m_arrow_x; + RenderableArrowLine m_arrow_y; + RenderableArrowLine m_arrow_z; + RenderableArrowHead m_arrow_head_x; + RenderableArrowHead m_arrow_head_y; + RenderableArrowHead m_arrow_head_z; + RenderableQuad m_quad_screen; + SelectableBool m_selectable_x; + SelectableBool m_selectable_y; + SelectableBool m_selectable_z; + SelectableBool m_selectable_screen; + Pivot2World m_pivot; +public: + static Shader* m_state_wire; + static Shader* m_state_fill; + + TranslateManipulator(Translatable& translatable, std::size_t segments, float length) : + m_free(translatable), + m_axis(translatable), + m_arrow_head_x(3 * 2 * (segments << 3)), + m_arrow_head_y(3 * 2 * (segments << 3)), + m_arrow_head_z(3 * 2 * (segments << 3)) + { + draw_arrowline(length, m_arrow_x.m_line, 0); + draw_arrowhead(segments, length, m_arrow_head_x.m_vertices.data(), TripleRemapXYZ(), TripleRemapXYZ()); + draw_arrowline(length, m_arrow_y.m_line, 1); + draw_arrowhead(segments, length, m_arrow_head_y.m_vertices.data(), TripleRemapYZX(), TripleRemapYZX()); + draw_arrowline(length, m_arrow_z.m_line, 2); + draw_arrowhead(segments, length, m_arrow_head_z.m_vertices.data(), TripleRemapZXY(), TripleRemapZXY()); + + draw_quad(16, m_quad_screen.m_quad); + } + + void UpdateColours() + { + m_arrow_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); + m_arrow_head_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); + m_arrow_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); + m_arrow_head_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); + m_arrow_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); + m_arrow_head_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); + m_quad_screen.setColour(colourSelected(g_colour_screen, m_selectable_screen.isSelected())); + } + + bool manipulator_show_axis(const Pivot2World& pivot, const Vector3& axis) + { + return fabs(vector3_dot(pivot.m_axis_screen, axis)) < 0.95; + } + + void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) + { + m_pivot.update(pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport()); + + // temp hack + UpdateColours(); + + Vector3 x = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.x())); + bool show_x = manipulator_show_axis(m_pivot, x); + + Vector3 y = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.y())); + bool show_y = manipulator_show_axis(m_pivot, y); + + Vector3 z = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.z())); + bool show_z = manipulator_show_axis(m_pivot, z); + + renderer.SetState(m_state_wire, Renderer::eWireframeOnly); + renderer.SetState(m_state_wire, Renderer::eFullMaterials); + + if(show_x) + { + renderer.addRenderable(m_arrow_x, m_pivot.m_worldSpace); + } + if(show_y) + { + renderer.addRenderable(m_arrow_y, m_pivot.m_worldSpace); + } + if(show_z) + { + renderer.addRenderable(m_arrow_z, m_pivot.m_worldSpace); + } + + renderer.addRenderable(m_quad_screen, m_pivot.m_viewplaneSpace); + + renderer.SetState(m_state_fill, Renderer::eWireframeOnly); + renderer.SetState(m_state_fill, Renderer::eFullMaterials); + + if(show_x) + { + renderer.addRenderable(m_arrow_head_x, m_pivot.m_worldSpace); + } + if(show_y) + { + renderer.addRenderable(m_arrow_head_y, m_pivot.m_worldSpace); + } + if(show_z) + { + renderer.addRenderable(m_arrow_head_z, m_pivot.m_worldSpace); + } + } + void testSelect(const View& view, const Matrix4& pivot2world) + { + m_pivot.update(pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport()); + + SelectionPool selector; + + Vector3 x = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.x())); + bool show_x = manipulator_show_axis(m_pivot, x); + + Vector3 y = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.y())); + bool show_y = manipulator_show_axis(m_pivot, y); + + Vector3 z = vector3_normalised(vector4_to_vector3(m_pivot.m_worldSpace.z())); + bool show_z = manipulator_show_axis(m_pivot, z); + + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_viewpointSpace)); + + { + SelectionIntersection best; + Quad_BestPoint(local2view, eClipCullCW, m_quad_screen.m_quad, best); + if(best.valid()) + { + best = SelectionIntersection(0, 0); + selector.addSelectable(best, &m_selectable_screen); + } + } + } + + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_worldSpace)); + +#if defined(DEBUG_SELECTION) + g_render_clipped.construct(view.GetViewMatrix()); +#endif + + if(show_x) + { + SelectionIntersection best; + Line_BestPoint(local2view, m_arrow_x.m_line, best); + Triangles_BestPoint(local2view, eClipCullCW, m_arrow_head_x.m_vertices.begin(), m_arrow_head_x.m_vertices.end(), best); + selector.addSelectable(best, &m_selectable_x); + } + + if(show_y) + { + SelectionIntersection best; + Line_BestPoint(local2view, m_arrow_y.m_line, best); + Triangles_BestPoint(local2view, eClipCullCW, m_arrow_head_y.m_vertices.begin(), m_arrow_head_y.m_vertices.end(), best); + selector.addSelectable(best, &m_selectable_y); + } + + if(show_z) + { + SelectionIntersection best; + Line_BestPoint(local2view, m_arrow_z.m_line, best); + Triangles_BestPoint(local2view, eClipCullCW, m_arrow_head_z.m_vertices.begin(), m_arrow_head_z.m_vertices.end(), best); + selector.addSelectable(best, &m_selectable_z); + } + } + + if(!selector.failed()) + { + (*selector.begin()).second->setSelected(true); + } + } + + Manipulatable* GetManipulatable() + { + if(m_selectable_x.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_x); + return &m_axis; + } + else if(m_selectable_y.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_y); + return &m_axis; + } + else if(m_selectable_z.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_z); + return &m_axis; + } + else + { + return &m_free; + } + } + + void setSelected(bool select) + { + m_selectable_x.setSelected(select); + m_selectable_y.setSelected(select); + m_selectable_z.setSelected(select); + m_selectable_screen.setSelected(select); + } + bool isSelected() const + { + return m_selectable_x.isSelected() + | m_selectable_y.isSelected() + | m_selectable_z.isSelected() + | m_selectable_screen.isSelected(); + } +}; + +Shader* TranslateManipulator::m_state_wire; +Shader* TranslateManipulator::m_state_fill; + +class ScaleManipulator : public Manipulator +{ + struct RenderableArrow : public OpenGLRenderable + { + PointVertex m_line[2]; + + void render(RenderStateFlags state) const + { + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_line[0].colour); + glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_line[0].vertex); + glDrawArrays(GL_LINES, 0, 2); + } + void setColour(const Colour4b& colour) + { + m_line[0].colour = colour; + m_line[1].colour = colour; + } + }; + struct RenderableQuad : public OpenGLRenderable + { + PointVertex m_quad[4]; + void render(RenderStateFlags state) const + { + glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_quad[0].colour); + glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_quad[0].vertex); + glDrawArrays(GL_QUADS, 0, 4); + } + void setColour(const Colour4b& colour) + { + m_quad[0].colour = colour; + m_quad[1].colour = colour; + m_quad[2].colour = colour; + m_quad[3].colour = colour; + } + }; + + ScaleFree m_free; + ScaleAxis m_axis; + RenderableArrow m_arrow_x; + RenderableArrow m_arrow_y; + RenderableArrow m_arrow_z; + RenderableQuad m_quad_screen; + SelectableBool m_selectable_x; + SelectableBool m_selectable_y; + SelectableBool m_selectable_z; + SelectableBool m_selectable_screen; + Pivot2World m_pivot; +public: + ScaleManipulator(Scalable& scalable, std::size_t segments, float length) : + m_free(scalable), + m_axis(scalable) + { + draw_arrowline(length, m_arrow_x.m_line, 0); + draw_arrowline(length, m_arrow_y.m_line, 1); + draw_arrowline(length, m_arrow_z.m_line, 2); + + draw_quad(16, m_quad_screen.m_quad); + } + + Pivot2World& getPivot() + { + return m_pivot; + } + + void UpdateColours() + { + m_arrow_x.setColour(colourSelected(g_colour_x, m_selectable_x.isSelected())); + m_arrow_y.setColour(colourSelected(g_colour_y, m_selectable_y.isSelected())); + m_arrow_z.setColour(colourSelected(g_colour_z, m_selectable_z.isSelected())); + m_quad_screen.setColour(colourSelected(g_colour_screen, m_selectable_screen.isSelected())); + } + + void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world) + { + m_pivot.update(pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport()); + + // temp hack + UpdateColours(); + + renderer.addRenderable(m_arrow_x, m_pivot.m_worldSpace); + renderer.addRenderable(m_arrow_y, m_pivot.m_worldSpace); + renderer.addRenderable(m_arrow_z, m_pivot.m_worldSpace); + + renderer.addRenderable(m_quad_screen, m_pivot.m_viewpointSpace); + } + void testSelect(const View& view, const Matrix4& pivot2world) + { + m_pivot.update(pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport()); + + SelectionPool selector; + + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_worldSpace)); + +#if defined(DEBUG_SELECTION) + g_render_clipped.construct(view.GetViewMatrix()); +#endif + + { + SelectionIntersection best; + Line_BestPoint(local2view, m_arrow_x.m_line, best); + selector.addSelectable(best, &m_selectable_x); + } + + { + SelectionIntersection best; + Line_BestPoint(local2view, m_arrow_y.m_line, best); + selector.addSelectable(best, &m_selectable_y); + } + + { + SelectionIntersection best; + Line_BestPoint(local2view, m_arrow_z.m_line, best); + selector.addSelectable(best, &m_selectable_z); + } + } + + { + Matrix4 local2view(matrix4_multiplied_by_matrix4(view.GetViewMatrix(), m_pivot.m_viewpointSpace)); + + { + SelectionIntersection best; + Quad_BestPoint(local2view, eClipCullCW, m_quad_screen.m_quad, best); + selector.addSelectable(best, &m_selectable_screen); + } + } + + if(!selector.failed()) + { + (*selector.begin()).second->setSelected(true); + } + } + + Manipulatable* GetManipulatable() + { + if(m_selectable_x.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_x); + return &m_axis; + } + else if(m_selectable_y.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_y); + return &m_axis; + } + else if(m_selectable_z.isSelected()) + { + m_axis.SetAxis(g_vector3_axis_z); + return &m_axis; + } + else + return &m_free; + } + + void setSelected(bool select) + { + m_selectable_x.setSelected(select); + m_selectable_y.setSelected(select); + m_selectable_z.setSelected(select); + m_selectable_screen.setSelected(select); + } + bool isSelected() const + { + return m_selectable_x.isSelected() + | m_selectable_y.isSelected() + | m_selectable_z.isSelected() + | m_selectable_screen.isSelected(); + } +}; + + +inline PlaneSelectable* Instance_getPlaneSelectable(scene::Instance& instance) +{ + return InstanceTypeCast::cast(instance); +} + +class PlaneSelectableSelectPlanes : public scene::Graph::Walker +{ + Selector& m_selector; + SelectionTest& m_test; + PlaneCallback m_selectedPlaneCallback; +public: + PlaneSelectableSelectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) + : m_selector(selector), m_test(test), m_selectedPlaneCallback(selectedPlaneCallback) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 && selectable->isSelected()) + { + PlaneSelectable* planeSelectable = Instance_getPlaneSelectable(instance); + if(planeSelectable != 0) + { + planeSelectable->selectPlanes(m_selector, m_test, m_selectedPlaneCallback); + } + } + } + return true; + } +}; + +class PlaneSelectableSelectReversedPlanes : public scene::Graph::Walker +{ + Selector& m_selector; + const SelectedPlanes& m_selectedPlanes; +public: + PlaneSelectableSelectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes) + : m_selector(selector), m_selectedPlanes(selectedPlanes) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 && selectable->isSelected()) + { + PlaneSelectable* planeSelectable = Instance_getPlaneSelectable(instance); + if(planeSelectable != 0) + { + planeSelectable->selectReversedPlanes(m_selector, m_selectedPlanes); + } + } + } + return true; + } +}; + +void Scene_forEachPlaneSelectable_selectPlanes(scene::Graph& graph, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback) +{ + graph.traverse(PlaneSelectableSelectPlanes(selector, test, selectedPlaneCallback)); +} + +void Scene_forEachPlaneSelectable_selectReversedPlanes(scene::Graph& graph, Selector& selector, const SelectedPlanes& selectedPlanes) +{ + graph.traverse(PlaneSelectableSelectReversedPlanes(selector, selectedPlanes)); +} + + +class PlaneLess +{ +public: + bool operator()(const Plane3& plane, const Plane3& other) const + { + if(plane.a < other.a) + { + return true; + } + if(other.a < plane.a) + { + return false; + } + + if(plane.b < other.b) + { + return true; + } + if(other.b < plane.b) + { + return false; + } + + if(plane.c < other.c) + { + return true; + } + if(other.c < plane.c) + { + return false; + } + + if(plane.d < other.d) + { + return true; + } + if(other.d < plane.d) + { + return false; + } + + return false; + } +}; + +typedef std::set PlaneSet; + +inline void PlaneSet_insert(PlaneSet& self, const Plane3& plane) +{ + self.insert(plane); +} + +inline bool PlaneSet_contains(const PlaneSet& self, const Plane3& plane) +{ + return self.find(plane) != self.end(); +} + + +class SelectedPlaneSet : public SelectedPlanes +{ + PlaneSet m_selectedPlanes; +public: + bool empty() const + { + return m_selectedPlanes.empty(); + } + + void insert(const Plane3& plane) + { + PlaneSet_insert(m_selectedPlanes, plane); + } + bool contains(const Plane3& plane) const + { + return PlaneSet_contains(m_selectedPlanes, plane); + } + typedef MemberCaller1 InsertCaller; +}; + + +bool Scene_forEachPlaneSelectable_selectPlanes(scene::Graph& graph, Selector& selector, SelectionTest& test) +{ + SelectedPlaneSet selectedPlanes; + + Scene_forEachPlaneSelectable_selectPlanes(graph, selector, test, SelectedPlaneSet::InsertCaller(selectedPlanes)); + Scene_forEachPlaneSelectable_selectReversedPlanes(graph, selector, selectedPlanes); + + return !selectedPlanes.empty(); +} + +void Scene_Translate_Component_Selected(scene::Graph& graph, const Vector3& translation); +void Scene_Translate_Selected(scene::Graph& graph, const Vector3& translation); +void Scene_TestSelect_Primitive(Selector& selector, SelectionTest& test, const VolumeTest& volume); +void Scene_TestSelect_Component(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode); +void Scene_TestSelect_Component_Selected(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode); +void Scene_SelectAll_Component(bool select, SelectionSystem::EComponentMode componentMode); + +class ResizeTranslatable : public Translatable +{ + void translate(const Vector3& translation) + { + Scene_Translate_Component_Selected(GlobalSceneGraph(), translation); + } +}; + +class DragTranslatable : public Translatable +{ + void translate(const Vector3& translation) + { + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent) + { + Scene_Translate_Component_Selected(GlobalSceneGraph(), translation); + } + else + { + Scene_Translate_Selected(GlobalSceneGraph(), translation); + } + } +}; + +class SelectionVolume : public SelectionTest +{ + Matrix4 m_local2view; + const View& m_view; + clipcull_t m_cull; + Vector3 m_near; + Vector3 m_far; +public: + SelectionVolume(const View& view) + : m_view(view) + { + } + + const VolumeTest& getVolume() const + { + return m_view; + } + + const Vector3& getNear() const + { + return m_near; + } + const Vector3& getFar() const + { + return m_far; + } + + void BeginMesh(const Matrix4& localToWorld, bool twoSided) + { + m_local2view = matrix4_multiplied_by_matrix4(m_view.GetViewMatrix(), localToWorld); + + // Cull back-facing polygons based on winding being clockwise or counter-clockwise. + // Don't cull if the view is wireframe and the polygons are two-sided. + m_cull = twoSided && !m_view.fill() ? eClipCullNone : (matrix4_handedness(localToWorld) == MATRIX4_RIGHTHANDED) ? eClipCullCW : eClipCullCCW; + + { + Matrix4 screen2world(matrix4_full_inverse(m_local2view)); + + m_near = vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4(0, 0, -1, 1) + ) + ); + + m_far = vector4_projected( + matrix4_transformed_vector4( + screen2world, + Vector4(0, 0, 1, 1) + ) + ); + } + +#if defined(DEBUG_SELECTION) + g_render_clipped.construct(m_view.GetViewMatrix()); +#endif + } + void TestPoint(const Vector3& point, SelectionIntersection& best) + { + Vector4 clipped; + if(matrix4_clip_point(m_local2view, point, clipped) == c_CLIP_PASS) + { + best = select_point_from_clipped(clipped); + } + } + void TestPolygon(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) + { + Vector4 clipped[9]; + for(std::size_t i=0; i+2(vertices[0]), + reinterpret_cast(vertices[i+1]), + reinterpret_cast(vertices[i+2]), + clipped + ), + clipped, + best, + m_cull + ); + } + } + void TestLineLoop(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) + { + if(count == 0) + return; + Vector4 clipped[9]; + for(VertexPointer::iterator i = vertices.begin(), end = i + count, prev = i + (count-1); i != end; prev = i, ++i) + { + BestPoint( + matrix4_clip_line( + m_local2view, + reinterpret_cast((*prev)), + reinterpret_cast((*i)), + clipped + ), + clipped, + best, + m_cull + ); + } + } + void TestLineStrip(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) + { + if(count == 0) + return; + Vector4 clipped[9]; + for(VertexPointer::iterator i = vertices.begin(), end = i + count, next = i + 1; next != end; i = next, ++next) + { + BestPoint( + matrix4_clip_line( + m_local2view, + reinterpret_cast((*i)), + reinterpret_cast((*next)), + clipped + ), + clipped, + best, + m_cull + ); + } + } + void TestLines(const VertexPointer& vertices, std::size_t count, SelectionIntersection& best) + { + if(count == 0) + return; + Vector4 clipped[9]; + for(VertexPointer::iterator i = vertices.begin(), end = i + count; i != end; i += 2) + { + BestPoint( + matrix4_clip_line( + m_local2view, + reinterpret_cast((*i)), + reinterpret_cast((*(i+1))), + clipped + ), + clipped, + best, + m_cull + ); + } + } + void TestTriangles(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) + { + Vector4 clipped[9]; + for(IndexPointer::iterator i(indices.begin()); i != indices.end(); i += 3) + { + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast(vertices[*i]), + reinterpret_cast(vertices[*(i+1)]), + reinterpret_cast(vertices[*(i+2)]), + clipped + ), + clipped, + best, + m_cull + ); + } + } + void TestQuads(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) + { + Vector4 clipped[9]; + for(IndexPointer::iterator i(indices.begin()); i != indices.end(); i += 4) + { + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast(vertices[*i]), + reinterpret_cast(vertices[*(i+1)]), + reinterpret_cast(vertices[*(i+3)]), + clipped + ), + clipped, + best, + m_cull + ); + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast(vertices[*(i+1)]), + reinterpret_cast(vertices[*(i+2)]), + reinterpret_cast(vertices[*(i+3)]), + clipped + ), + clipped, + best, + m_cull + ); + } + } + void TestQuadStrip(const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best) + { + Vector4 clipped[9]; + for(IndexPointer::iterator i(indices.begin()); i+2 != indices.end(); i += 2) + { + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast(vertices[*i]), + reinterpret_cast(vertices[*(i+1)]), + reinterpret_cast(vertices[*(i+2)]), + clipped + ), + clipped, + best, + m_cull + ); + BestPoint( + matrix4_clip_triangle( + m_local2view, + reinterpret_cast(vertices[*(i+2)]), + reinterpret_cast(vertices[*(i+1)]), + reinterpret_cast(vertices[*(i+3)]), + clipped + ), + clipped, + best, + m_cull + ); + } + } +}; + +class SelectionCounter +{ +public: + typedef const Selectable& first_argument_type; + + SelectionCounter(const SelectionChangeCallback& onchanged) + : m_count(0), m_onchanged(onchanged) + { + } + void operator()(const Selectable& selectable) + { + if(selectable.isSelected()) + { + ++m_count; + } + else + { + ASSERT_MESSAGE(m_count != 0, "selection counter underflow"); + --m_count; + } + + m_onchanged(selectable); + } + bool empty() const + { + return m_count == 0; + } + std::size_t size() const + { + return m_count; + } +private: + std::size_t m_count; + SelectionChangeCallback m_onchanged; +}; + +inline void ConstructSelectionTest(View& view, const rect_t selection_box) +{ + view.EnableScissor(selection_box.min[0], selection_box.max[0], selection_box.min[1], selection_box.max[1]); +} + +inline const rect_t SelectionBoxForPoint(const float device_point[2], const float device_epsilon[2]) +{ + rect_t selection_box; + selection_box.min[0] = device_point[0] - device_epsilon[0]; + selection_box.min[1] = device_point[1] - device_epsilon[1]; + selection_box.max[0] = device_point[0] + device_epsilon[0]; + selection_box.max[1] = device_point[1] + device_epsilon[1]; + return selection_box; +} + +inline const rect_t SelectionBoxForArea(const float device_point[2], const float device_delta[2]) +{ + rect_t selection_box; + selection_box.min[0] = (device_delta[0] < 0) ? (device_point[0] + device_delta[0]) : (device_point[0]); + selection_box.min[1] = (device_delta[1] < 0) ? (device_point[1] + device_delta[1]) : (device_point[1]); + selection_box.max[0] = (device_delta[0] > 0) ? (device_point[0] + device_delta[0]) : (device_point[0]); + selection_box.max[1] = (device_delta[1] > 0) ? (device_point[1] + device_delta[1]) : (device_point[1]); + return selection_box; +} + +Quaternion construct_local_rotation(const Quaternion& world, const Quaternion& localToWorld) +{ + return quaternion_normalised(quaternion_multiplied_by_quaternion( + quaternion_normalised(quaternion_multiplied_by_quaternion( + quaternion_inverse(localToWorld), + world + )), + localToWorld + )); +} + +inline void matrix4_assign_rotation(Matrix4& matrix, const Matrix4& other) +{ + matrix[0] = other[0]; + matrix[1] = other[1]; + matrix[2] = other[2]; + matrix[4] = other[4]; + matrix[5] = other[5]; + matrix[6] = other[6]; + matrix[8] = other[8]; + matrix[9] = other[9]; + matrix[10] = other[10]; +} + +void matrix4_assign_rotation_for_pivot(Matrix4& matrix, scene::Instance& instance) +{ + Editable* editable = Node_getEditable(instance.path().top()); + if(editable != 0) + { + matrix4_assign_rotation(matrix, matrix4_multiplied_by_matrix4(instance.localToWorld(), editable->getLocalPivot())); + } + else + { + matrix4_assign_rotation(matrix, instance.localToWorld()); + } +} + +inline bool Instance_isSelectedComponents(scene::Instance& instance) +{ + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); + return componentSelectionTestable != 0 + && componentSelectionTestable->isSelectedComponents(); +} + +class TranslateSelected : public SelectionSystem::Visitor +{ + const Vector3& m_translate; +public: + TranslateSelected(const Vector3& translate) + : m_translate(translate) + { + } + void visit(scene::Instance& instance) const + { + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + transform->setType(TRANSFORM_PRIMITIVE); + transform->setTranslation(m_translate); + } + } +}; + +void Scene_Translate_Selected(scene::Graph& graph, const Vector3& translation) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + GlobalSelectionSystem().foreachSelected(TranslateSelected(translation)); + } +} + +Vector3 get_local_pivot(const Vector3& world_pivot, const Matrix4& localToWorld) +{ + return Vector3( + matrix4_transformed_point( + matrix4_full_inverse(localToWorld), + world_pivot + ) + ); +} + +void translation_for_pivoted_matrix_transform(Vector3& parent_translation, const Matrix4& local_transform, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent) +{ + // we need a translation inside the parent system to move the origin of this object to the right place + + // mathematically, it must fulfill: + // + // local_translation local_transform local_pivot = local_pivot + // local_translation = local_pivot - local_transform local_pivot + // + // or maybe? + // local_transform local_translation local_pivot = local_pivot + // local_translation local_pivot = local_transform^-1 local_pivot + // local_translation + local_pivot = local_transform^-1 local_pivot + // local_translation = local_transform^-1 local_pivot - local_pivot + + Vector3 local_pivot(get_local_pivot(world_pivot, localToWorld)); + + Vector3 local_translation( + vector3_subtracted( + local_pivot, + matrix4_transformed_point( + local_transform, + local_pivot + ) + /* + matrix4_transformed_point( + matrix4_full_inverse(local_transform), + local_pivot + ), + local_pivot + */ + ) + ); + + translation_local2object(parent_translation, local_translation, localToParent); + + /* + // verify it! + globalOutputStream() << "World pivot is at " << world_pivot << "\n"; + globalOutputStream() << "Local pivot is at " << local_pivot << "\n"; + globalOutputStream() << "Transformation " << local_transform << " moves it to: " << matrix4_transformed_point(local_transform, local_pivot) << "\n"; + globalOutputStream() << "Must move by " << local_translation << " in the local system" << "\n"; + globalOutputStream() << "Must move by " << parent_translation << " in the parent system" << "\n"; + */ +} + +void translation_for_pivoted_rotation(Vector3& parent_translation, const Quaternion& local_rotation, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent) +{ + translation_for_pivoted_matrix_transform(parent_translation, matrix4_rotation_for_quaternion_quantised(local_rotation), world_pivot, localToWorld, localToParent); +} + +void translation_for_pivoted_scale(Vector3& parent_translation, const Vector3& world_scale, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent) +{ + Matrix4 local_transform( + matrix4_multiplied_by_matrix4( + matrix4_full_inverse(localToWorld), + matrix4_multiplied_by_matrix4( + matrix4_scale_for_vec3(world_scale), + localToWorld + ) + ) + ); + local_transform.tx() = local_transform.ty() = local_transform.tz() = 0; // cancel translation parts + translation_for_pivoted_matrix_transform(parent_translation, local_transform, world_pivot, localToWorld, localToParent); +} + +class rotate_selected : public SelectionSystem::Visitor +{ + const Quaternion& m_rotate; + const Vector3& m_world_pivot; +public: + rotate_selected(const Quaternion& rotation, const Vector3& world_pivot) + : m_rotate(rotation), m_world_pivot(world_pivot) + { + } + void visit(scene::Instance& instance) const + { + TransformNode* transformNode = Node_getTransformNode(instance.path().top()); + if(transformNode != 0) + { + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + transform->setType(TRANSFORM_PRIMITIVE); + transform->setScale(c_scale_identity); + transform->setTranslation(c_translation_identity); + + transform->setType(TRANSFORM_PRIMITIVE); + transform->setRotation(m_rotate); + + { + Editable* editable = Node_getEditable(instance.path().top()); + const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; + + Vector3 parent_translation; + translation_for_pivoted_rotation( + parent_translation, + m_rotate, + m_world_pivot, + matrix4_multiplied_by_matrix4(instance.localToWorld(), localPivot), + matrix4_multiplied_by_matrix4(transformNode->localToParent(), localPivot) + ); + + transform->setTranslation(parent_translation); + } + } + } + } +}; + +void Scene_Rotate_Selected(scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + GlobalSelectionSystem().foreachSelected(rotate_selected(rotation, world_pivot)); + } +} + +class scale_selected : public SelectionSystem::Visitor +{ + const Vector3& m_scale; + const Vector3& m_world_pivot; +public: + scale_selected(const Vector3& scaling, const Vector3& world_pivot) + : m_scale(scaling), m_world_pivot(world_pivot) + { + } + void visit(scene::Instance& instance) const + { + TransformNode* transformNode = Node_getTransformNode(instance.path().top()); + if(transformNode != 0) + { + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + transform->setType(TRANSFORM_PRIMITIVE); + transform->setScale(c_scale_identity); + transform->setTranslation(c_translation_identity); + + transform->setType(TRANSFORM_PRIMITIVE); + transform->setScale(m_scale); + { + Editable* editable = Node_getEditable(instance.path().top()); + const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity; + + Vector3 parent_translation; + translation_for_pivoted_scale( + parent_translation, + m_scale, + m_world_pivot, + matrix4_multiplied_by_matrix4(instance.localToWorld(), localPivot), + matrix4_multiplied_by_matrix4(transformNode->localToParent(), localPivot) + ); + + transform->setTranslation(parent_translation); + } + } + } + } +}; + +void Scene_Scale_Selected(scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + GlobalSelectionSystem().foreachSelected(scale_selected(scaling, world_pivot)); + } +} + + +class translate_component_selected : public SelectionSystem::Visitor +{ + const Vector3& m_translate; +public: + translate_component_selected(const Vector3& translate) + : m_translate(translate) + { + } + void visit(scene::Instance& instance) const + { + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + transform->setType(TRANSFORM_COMPONENT); + transform->setTranslation(m_translate); + } + } +}; + +void Scene_Translate_Component_Selected(scene::Graph& graph, const Vector3& translation) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + GlobalSelectionSystem().foreachSelectedComponent(translate_component_selected(translation)); + } +} + +class rotate_component_selected : public SelectionSystem::Visitor +{ + const Quaternion& m_rotate; + const Vector3& m_world_pivot; +public: + rotate_component_selected(const Quaternion& rotation, const Vector3& world_pivot) + : m_rotate(rotation), m_world_pivot(world_pivot) + { + } + void visit(scene::Instance& instance) const + { + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + Vector3 parent_translation; + translation_for_pivoted_rotation(parent_translation, m_rotate, m_world_pivot, instance.localToWorld(), Node_getTransformNode(instance.path().top())->localToParent()); + + transform->setType(TRANSFORM_COMPONENT); + transform->setRotation(m_rotate); + transform->setTranslation(parent_translation); + } + } +}; + +void Scene_Rotate_Component_Selected(scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot) +{ + if(GlobalSelectionSystem().countSelectedComponents() != 0) + { + GlobalSelectionSystem().foreachSelectedComponent(rotate_component_selected(rotation, world_pivot)); + } +} + +class scale_component_selected : public SelectionSystem::Visitor +{ + const Vector3& m_scale; + const Vector3& m_world_pivot; +public: + scale_component_selected(const Vector3& scaling, const Vector3& world_pivot) + : m_scale(scaling), m_world_pivot(world_pivot) + { + } + void visit(scene::Instance& instance) const + { + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + Vector3 parent_translation; + translation_for_pivoted_scale(parent_translation, m_scale, m_world_pivot, instance.localToWorld(), Node_getTransformNode(instance.path().top())->localToParent()); + + transform->setType(TRANSFORM_COMPONENT); + transform->setScale(m_scale); + transform->setTranslation(parent_translation); + } + } +}; + +void Scene_Scale_Component_Selected(scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot) +{ + if(GlobalSelectionSystem().countSelectedComponents() != 0) + { + GlobalSelectionSystem().foreachSelectedComponent(scale_component_selected(scaling, world_pivot)); + } +} + + +class BooleanSelector : public Selector +{ + bool m_selected; + SelectionIntersection m_intersection; + Selectable* m_selectable; +public: + BooleanSelector() : m_selected(false) + { + } + + void pushSelectable(Selectable& selectable) + { + m_intersection = SelectionIntersection(); + m_selectable = &selectable; + } + void popSelectable() + { + if(m_intersection.valid()) + { + m_selected = true; + } + m_intersection = SelectionIntersection(); + } + void addIntersection(const SelectionIntersection& intersection) + { + if(m_selectable->isSelected()) + { + assign_if_closer(m_intersection, intersection); + } + } + + bool isSelected() + { + return m_selected; + } +}; + +class BestSelector : public Selector +{ + SelectionIntersection m_intersection; + Selectable* m_selectable; + SelectionIntersection m_bestIntersection; + std::list m_bestSelectable; +public: + BestSelector() : m_bestIntersection(SelectionIntersection()), m_bestSelectable(0) + { + } + + void pushSelectable(Selectable& selectable) + { + m_intersection = SelectionIntersection(); + m_selectable = &selectable; + } + void popSelectable() + { + if(m_intersection.equalEpsilon(m_bestIntersection, 0.25f, 0.001f)) + { + m_bestSelectable.push_back(m_selectable); + m_bestIntersection = m_intersection; + } + else if(m_intersection < m_bestIntersection) + { + m_bestSelectable.clear(); + m_bestSelectable.push_back(m_selectable); + m_bestIntersection = m_intersection; + } + m_intersection = SelectionIntersection(); + } + void addIntersection(const SelectionIntersection& intersection) + { + assign_if_closer(m_intersection, intersection); + } + + std::list& best() + { + return m_bestSelectable; + } +}; + +class DragManipulator : public Manipulator +{ + TranslateFree m_freeResize; + TranslateFree m_freeDrag; + ResizeTranslatable m_resize; + DragTranslatable m_drag; + SelectableBool m_dragSelectable; +public: + + bool m_selected; + + DragManipulator() : m_freeResize(m_resize), m_freeDrag(m_drag), m_selected(false) + { + } + + Manipulatable* GetManipulatable() + { + return m_dragSelectable.isSelected() ? &m_freeDrag : &m_freeResize; + } + + void testSelect(const View& view, const Matrix4& pivot2world) + { + SelectionPool selector; + + SelectionVolume test(view); + + if(GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive) + { + BooleanSelector booleanSelector; + + Scene_TestSelect_Primitive(booleanSelector, test, view); + + if(booleanSelector.isSelected()) + { + selector.addSelectable(SelectionIntersection(0, 0), &m_dragSelectable); + m_selected = false; + } + else + { + m_selected = Scene_forEachPlaneSelectable_selectPlanes(GlobalSceneGraph(), selector, test); + } + } + else + { + BestSelector bestSelector; + Scene_TestSelect_Component_Selected(bestSelector, test, view, GlobalSelectionSystem().ComponentMode()); + for(std::list::iterator i = bestSelector.best().begin(); i != bestSelector.best().end(); ++i) + { + if(!(*i)->isSelected()) + { + GlobalSelectionSystem().setSelectedAllComponents(false); + } + m_selected = false; + selector.addSelectable(SelectionIntersection(0, 0), (*i)); + m_dragSelectable.setSelected(true); + } + } + + for(SelectionPool::iterator i = selector.begin(); i != selector.end(); ++i) + { + (*i).second->setSelected(true); + } + } + + void setSelected(bool select) + { + m_selected = select; + m_dragSelectable.setSelected(select); + } + bool isSelected() const + { + return m_selected || m_dragSelectable.isSelected(); + } +}; + +class ClipManipulator : public Manipulator +{ +public: + + Manipulatable* GetManipulatable() + { + ERROR_MESSAGE("clipper is not manipulatable"); + return 0; + } + + void setSelected(bool select) + { + } + bool isSelected() const + { + return false; + } +}; + +class select_all : public scene::Graph::Walker +{ + bool m_select; +public: + select_all(bool select) + : m_select(select) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0) + { + selectable->setSelected(m_select); + } + return true; + } +}; + +class select_all_component : public scene::Graph::Walker +{ + bool m_select; + SelectionSystem::EComponentMode m_mode; +public: + select_all_component(bool select, SelectionSystem::EComponentMode mode) + : m_select(select), m_mode(mode) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); + if(componentSelectionTestable) + { + componentSelectionTestable->setSelectedComponents(m_select, m_mode); + } + return true; + } +}; + +void Scene_SelectAll_Component(bool select, SelectionSystem::EComponentMode componentMode) +{ + GlobalSceneGraph().traverse(select_all_component(select, componentMode)); +} + + +// RadiantSelectionSystem +class RadiantSelectionSystem : + public SelectionSystem, + public Translatable, + public Rotatable, + public Scalable, + public Renderable +{ + mutable Matrix4 m_pivot2world; + Matrix4 m_pivot2world_start; + Matrix4 m_manip2pivot_start; + Translation m_translation; + Rotation m_rotation; + Scale m_scale; +public: + static Shader* m_state; +private: + EManipulatorMode m_manipulator_mode; + Manipulator* m_manipulator; + + // state + bool m_undo_begun; + EMode m_mode; + EComponentMode m_componentmode; + + SelectionCounter m_count_primitive; + SelectionCounter m_count_component; + + TranslateManipulator m_translate_manipulator; + RotateManipulator m_rotate_manipulator; + ScaleManipulator m_scale_manipulator; + DragManipulator m_drag_manipulator; + ClipManipulator m_clip_manipulator; + + typedef SelectionList selection_t; + selection_t m_selection; + selection_t m_component_selection; + + Signal1 m_selectionChanged_callbacks; + + void ConstructPivot() const; + mutable bool m_pivotChanged; + bool m_pivot_moving; + + void Scene_TestSelect(Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode); + + bool nothingSelected() const + { + return (Mode() == eComponent && m_count_component.empty()) + || (Mode() == ePrimitive && m_count_primitive.empty()); + } + + +public: + enum EModifier + { + eManipulator, + eToggle, + eReplace, + eCycle, + }; + + RadiantSelectionSystem() : + m_undo_begun(false), + m_mode(ePrimitive), + m_componentmode(eDefault), + m_count_primitive(SelectionChangedCaller(*this)), + m_count_component(SelectionChangedCaller(*this)), + m_translate_manipulator(*this, 2, 64), + m_rotate_manipulator(*this, 8, 64), + m_scale_manipulator(*this, 0, 64), + m_pivotChanged(false), + m_pivot_moving(false) + { + SetManipulatorMode(eTranslate); + pivotChanged(); + addSelectionChangeCallback(PivotChangedSelectionCaller(*this)); + AddGridChangeCallback(PivotChangedCaller(*this)); + } + void pivotChanged() const + { + m_pivotChanged = true; + SceneChangeNotify(); + } + typedef ConstMemberCaller PivotChangedCaller; + void pivotChangedSelection(const Selectable& selectable) + { + pivotChanged(); + } + typedef MemberCaller1 PivotChangedSelectionCaller; + + void SetMode(EMode mode) + { + if(m_mode != mode) + { + m_mode = mode; + pivotChanged(); + } + } + EMode Mode() const + { + return m_mode; + } + void SetComponentMode(EComponentMode mode) + { + m_componentmode = mode; + } + EComponentMode ComponentMode() const + { + return m_componentmode; + } + void SetManipulatorMode(EManipulatorMode mode) + { + m_manipulator_mode = mode; + switch(m_manipulator_mode) + { + case eTranslate: m_manipulator = &m_translate_manipulator; break; + case eRotate: m_manipulator = &m_rotate_manipulator; break; + case eScale: m_manipulator = &m_scale_manipulator; break; + case eDrag: m_manipulator = &m_drag_manipulator; break; + case eClip: m_manipulator = &m_clip_manipulator; break; + } + pivotChanged(); + } + EManipulatorMode ManipulatorMode() const + { + return m_manipulator_mode; + } + + SelectionChangeCallback getObserver(EMode mode) + { + if(mode == ePrimitive) + { + return makeCallback1(m_count_primitive); + } + else + { + return makeCallback1(m_count_component); + } + } + std::size_t countSelected() const + { + return m_count_primitive.size(); + } + std::size_t countSelectedComponents() const + { + return m_count_component.size(); + } + void onSelectedChanged(scene::Instance& instance, const Selectable& selectable) + { + if(selectable.isSelected()) + { + m_selection.append(instance); + } + else + { + m_selection.erase(instance); + } + + ASSERT_MESSAGE(m_selection.size() == m_count_primitive.size(), "selection-tracking error"); + } + void onComponentSelection(scene::Instance& instance, const Selectable& selectable) + { + if(selectable.isSelected()) + { + m_component_selection.append(instance); + } + else + { + m_component_selection.erase(instance); + } + + ASSERT_MESSAGE(m_component_selection.size() == m_count_component.size(), "selection-tracking error"); + } + scene::Instance& ultimateSelected() const + { + ASSERT_MESSAGE(m_selection.size() > 0, "no instance selected"); + return m_selection.back(); + } + scene::Instance& penultimateSelected() const + { + ASSERT_MESSAGE(m_selection.size() > 1, "only one instance selected"); + return *(*(--(--m_selection.end()))); + } + void setSelectedAll(bool selected) + { + GlobalSceneGraph().traverse(select_all(selected)); + + m_manipulator->setSelected(selected); + } + void setSelectedAllComponents(bool selected) + { + Scene_SelectAll_Component(selected, SelectionSystem::eVertex); + Scene_SelectAll_Component(selected, SelectionSystem::eEdge); + Scene_SelectAll_Component(selected, SelectionSystem::eFace); + + m_manipulator->setSelected(selected); + } + + void foreachSelected(const Visitor& visitor) const + { + selection_t::const_iterator i = m_selection.begin(); + while(i != m_selection.end()) + { + visitor.visit(*(*(i++))); + } + } + void foreachSelectedComponent(const Visitor& visitor) const + { + selection_t::const_iterator i = m_component_selection.begin(); + while(i != m_component_selection.end()) + { + visitor.visit(*(*(i++))); + } + } + + void addSelectionChangeCallback(const SelectionChangeHandler& handler) + { + m_selectionChanged_callbacks.connectLast(handler); + } + void selectionChanged(const Selectable& selectable) + { + m_selectionChanged_callbacks(selectable); + } + typedef MemberCaller1 SelectionChangedCaller; + + + void startMove() + { + m_pivot2world_start = GetPivot2World(); + } + + bool SelectManipulator(const View& view, const float device_point[2], const float device_epsilon[2]) + { + if(!nothingSelected() || (ManipulatorMode() == eDrag && Mode() == eComponent)) + { +#if defined (DEBUG_SELECTION) + g_render_clipped.destroy(); +#endif + + m_manipulator->setSelected(false); + + if(!nothingSelected() || (ManipulatorMode() == eDrag && Mode() == eComponent)) + { + View scissored(view); + ConstructSelectionTest(scissored, SelectionBoxForPoint(device_point, device_epsilon)); + m_manipulator->testSelect(scissored, GetPivot2World()); + } + + startMove(); + + m_pivot_moving = m_manipulator->isSelected(); + + if(m_pivot_moving) + { + Pivot2World pivot; + pivot.update(GetPivot2World(), view.GetModelview(), view.GetProjection(), view.GetViewport()); + + m_manip2pivot_start = matrix4_multiplied_by_matrix4(matrix4_full_inverse(m_pivot2world_start), pivot.m_worldSpace); + + Matrix4 device2manip; + ConstructDevice2Manip(device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport()); + m_manipulator->GetManipulatable()->Construct(device2manip, device_point[0], device_point[1]); + + m_undo_begun = false; + } + + SceneChangeNotify(); + } + + return m_pivot_moving; + } + + void deselectAll() + { + if(Mode() == eComponent) + { + setSelectedAllComponents(false); + } + else + { + setSelectedAll(false); + } + } + + void SelectPoint(const View& view, const float device_point[2], const float device_epsilon[2], RadiantSelectionSystem::EModifier modifier, bool face) + { + ASSERT_MESSAGE(fabs(device_point[0]) <= 1.0f && fabs(device_point[1]) <= 1.0f, "point-selection error"); + if(modifier == eReplace) + { + if(face) + { + setSelectedAllComponents(false); + } + else + { + deselectAll(); + } + } + + #if defined (DEBUG_SELECTION) + g_render_clipped.destroy(); + #endif + + { + View scissored(view); + ConstructSelectionTest(scissored, SelectionBoxForPoint(device_point, device_epsilon)); + + SelectionVolume volume(scissored); + SelectionPool selector; + if(face) + { + Scene_TestSelect_Component(selector, volume, scissored, eFace); + } + else + { + Scene_TestSelect(selector, volume, scissored, Mode(), ComponentMode()); + } + + if(!selector.failed()) + { + switch(modifier) + { + case RadiantSelectionSystem::eToggle: + { + SelectableSortedSet::iterator best = selector.begin(); + // toggle selection of the object with least depth + if((*best).second->isSelected()) + (*best).second->setSelected(false); + else + (*best).second->setSelected(true); + } + break; + // if cycle mode not enabled, enable it + case RadiantSelectionSystem::eReplace: + { + // select closest + (*selector.begin()).second->setSelected(true); + } + break; + // select the next object in the list from the one already selected + case RadiantSelectionSystem::eCycle: + { + SelectionPool::iterator i = selector.begin(); + while(i != selector.end()) + { + if((*i).second->isSelected()) + { + (*i).second->setSelected(false); + ++i; + if(i != selector.end()) + { + i->second->setSelected(true); + } + else + { + selector.begin()->second->setSelected(true); + } + break; + } + ++i; + } + } + break; + default: + break; + } + } + } + } + + void SelectArea(const View& view, const float device_point[2], const float device_delta[2], RadiantSelectionSystem::EModifier modifier, bool face) + { + if(modifier == eReplace) + { + if(face) + { + setSelectedAllComponents(false); + } + else + { + deselectAll(); + } + } + + #if defined (DEBUG_SELECTION) + g_render_clipped.destroy(); + #endif + + { + View scissored(view); + ConstructSelectionTest(scissored, SelectionBoxForArea(device_point, device_delta)); + + SelectionVolume volume(scissored); + SelectionPool pool; + if(face) + { + Scene_TestSelect_Component(pool, volume, scissored, eFace); + } + else + { + Scene_TestSelect(pool, volume, scissored, Mode(), ComponentMode()); + } + + for(SelectionPool::iterator i = pool.begin(); i != pool.end(); ++i) + { + (*i).second->setSelected(!(modifier == RadiantSelectionSystem::eToggle && (*i).second->isSelected())); + } + } + } + + + void translate(const Vector3& translation) + { + if(!nothingSelected()) + { + //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); + + m_translation = translation; + + m_pivot2world = m_pivot2world_start; + matrix4_translate_by_vec3(m_pivot2world, translation); + + if(Mode() == eComponent) + { + Scene_Translate_Component_Selected(GlobalSceneGraph(), m_translation); + } + else + { + Scene_Translate_Selected(GlobalSceneGraph(), m_translation); + } + + SceneChangeNotify(); + } + } + void outputTranslation(TextOutputStream& ostream) + { + ostream << " -xyz " << m_translation.x() << " " << m_translation.y() << " " << m_translation.z(); + } + void rotate(const Quaternion& rotation) + { + if(!nothingSelected()) + { + //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid"); + + m_rotation = rotation; + + if(Mode() == eComponent) + { + Scene_Rotate_Component_Selected(GlobalSceneGraph(), m_rotation, vector4_to_vector3(m_pivot2world.t())); + + matrix4_assign_rotation_for_pivot(m_pivot2world, m_component_selection.back()); + } + else + { + Scene_Rotate_Selected(GlobalSceneGraph(), m_rotation, vector4_to_vector3(m_pivot2world.t())); + + matrix4_assign_rotation_for_pivot(m_pivot2world, m_selection.back()); + } + + SceneChangeNotify(); + } + } + void outputRotation(TextOutputStream& ostream) + { + ostream << " -eulerXYZ " << m_rotation.x() << " " << m_rotation.y() << " " << m_rotation.z(); + } + void scale(const Vector3& scaling) + { + if(!nothingSelected()) + { + m_scale = scaling; + + if(Mode() == eComponent) + { + Scene_Scale_Component_Selected(GlobalSceneGraph(), m_scale, vector4_to_vector3(m_pivot2world.t())); + } + else + { + Scene_Scale_Selected(GlobalSceneGraph(), m_scale, vector4_to_vector3(m_pivot2world.t())); + } + + SceneChangeNotify(); + } + } + void outputScale(TextOutputStream& ostream) + { + ostream << " -scale " << m_scale.x() << " " << m_scale.y() << " " << m_scale.z(); + } + + void rotateSelected(const Quaternion& rotation) + { + startMove(); + rotate(rotation); + freezeTransforms(); + } + void translateSelected(const Vector3& translation) + { + startMove(); + translate(translation); + freezeTransforms(); + } + void scaleSelected(const Vector3& scaling) + { + startMove(); + scale(scaling); + freezeTransforms(); + } + + void MoveSelected(const View& view, const float device_point[2]) + { + if(m_manipulator->isSelected()) + { + if(!m_undo_begun) + { + m_undo_begun = true; + GlobalUndoSystem().start(); + } + + Matrix4 device2manip; + ConstructDevice2Manip(device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport()); + m_manipulator->GetManipulatable()->Transform(m_manip2pivot_start, device2manip, device_point[0], device_point[1]); + } + } + + /// \todo Support view-dependent nudge. + void NudgeManipulator(const Vector3& nudge, const Vector3& view) + { + if(ManipulatorMode() == eTranslate || ManipulatorMode() == eDrag) + { + translateSelected(nudge); + } + } + + void endMove(); + void freezeTransforms(); + + void renderSolid(Renderer& renderer, const VolumeTest& volume) const; + void renderWireframe(Renderer& renderer, const VolumeTest& volume) const + { + renderSolid(renderer, volume); + } + + const Matrix4& GetPivot2World() const + { + ConstructPivot(); + return m_pivot2world; + } + + static void constructStatic() + { + m_state = GlobalShaderCache().capture("$POINT"); + #if defined(DEBUG_SELECTION) + g_state_clipped = GlobalShaderCache().capture("$DEBUG_CLIPPED"); + #endif + TranslateManipulator::m_state_wire = GlobalShaderCache().capture("$WIRE_OVERLAY"); + TranslateManipulator::m_state_fill = GlobalShaderCache().capture("$FLATSHADE_OVERLAY"); + RotateManipulator::m_state_outer = GlobalShaderCache().capture("$WIRE_OVERLAY"); + } + + static void destroyStatic() + { + #if defined(DEBUG_SELECTION) + GlobalShaderCache().release("$DEBUG_CLIPPED"); + #endif + GlobalShaderCache().release("$WIRE_OVERLAY"); + GlobalShaderCache().release("$FLATSHADE_OVERLAY"); + GlobalShaderCache().release("$WIRE_OVERLAY"); + GlobalShaderCache().release("$POINT"); + } +}; + +Shader* RadiantSelectionSystem::m_state = 0; + + +namespace +{ + RadiantSelectionSystem* g_RadiantSelectionSystem; + + inline RadiantSelectionSystem& getSelectionSystem() + { + return *g_RadiantSelectionSystem; + } +} + + + +class testselect_entity_visible : public scene::Graph::Walker +{ + Selector& m_selector; + SelectionTest& m_test; +public: + testselect_entity_visible(Selector& selector, SelectionTest& test) + : m_selector(selector), m_test(test) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && Node_isEntity(path.top())) + { + m_selector.pushSelectable(*selectable); + } + + SelectionTestable* selectionTestable = Instance_getSelectionTestable(instance); + if(selectionTestable) + { + selectionTestable->testSelect(m_selector, m_test); + } + + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && Node_isEntity(path.top())) + { + m_selector.popSelectable(); + } + } +}; + +class testselect_primitive_visible : public scene::Graph::Walker +{ + Selector& m_selector; + SelectionTest& m_test; +public: + testselect_primitive_visible(Selector& selector, SelectionTest& test) + : m_selector(selector), m_test(test) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0) + { + m_selector.pushSelectable(*selectable); + } + + SelectionTestable* selectionTestable = Instance_getSelectionTestable(instance); + if(selectionTestable) + { + selectionTestable->testSelect(m_selector, m_test); + } + + return true; + } + void post(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0) + { + m_selector.popSelectable(); + } + } +}; + +class testselect_component_visible : public scene::Graph::Walker +{ + Selector& m_selector; + SelectionTest& m_test; + SelectionSystem::EComponentMode m_mode; +public: + testselect_component_visible(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) + : m_selector(selector), m_test(test), m_mode(mode) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); + if(componentSelectionTestable) + { + componentSelectionTestable->testSelectComponents(m_selector, m_test, m_mode); + } + + return true; + } +}; + + +class testselect_component_visible_selected : public scene::Graph::Walker +{ + Selector& m_selector; + SelectionTest& m_test; + SelectionSystem::EComponentMode m_mode; +public: + testselect_component_visible_selected(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode) + : m_selector(selector), m_test(test), m_mode(mode) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 && selectable->isSelected()) + { + ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable(instance); + if(componentSelectionTestable) + { + componentSelectionTestable->testSelectComponents(m_selector, m_test, m_mode); + } + } + + return true; + } +}; + +void Scene_TestSelect_Primitive(Selector& selector, SelectionTest& test, const VolumeTest& volume) +{ + Scene_forEachVisible(GlobalSceneGraph(), volume, testselect_primitive_visible(selector, test)); +} + +void Scene_TestSelect_Component_Selected(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode) +{ + Scene_forEachVisible(GlobalSceneGraph(), volume, testselect_component_visible_selected(selector, test, componentMode)); +} + +void Scene_TestSelect_Component(Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode) +{ + Scene_forEachVisible(GlobalSceneGraph(), volume, testselect_component_visible(selector, test, componentMode)); +} + +void RadiantSelectionSystem::Scene_TestSelect(Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode) +{ + switch(mode) + { + case eEntity: + { + Scene_forEachVisible(GlobalSceneGraph(), view, testselect_entity_visible(selector, test)); + } + break; + case ePrimitive: + Scene_TestSelect_Primitive(selector, test, view); + break; + case eComponent: + Scene_TestSelect_Component_Selected(selector, test, view, componentMode); + break; + } +} + +class FreezeTransforms : public scene::Graph::Walker +{ +public: + bool pre(const scene::Path& path, scene::Instance& instance) const + { + TransformNode* transformNode = Node_getTransformNode(path.top()); + if(transformNode != 0) + { + Transformable* transform = Instance_getTransformable(instance); + if(transform != 0) + { + transform->freezeTransform(); + } + } + return true; + } +}; + +void RadiantSelectionSystem::freezeTransforms() +{ + GlobalSceneGraph().traverse(FreezeTransforms()); +} + + +void RadiantSelectionSystem::endMove() +{ + freezeTransforms(); + + if(Mode() == ePrimitive) + { + if(ManipulatorMode() == eDrag) + { + Scene_SelectAll_Component(false, SelectionSystem::eFace); + } + } + + m_pivot_moving = false; + pivotChanged(); + + SceneChangeNotify(); + + if(m_undo_begun) + { + StringOutputStream command; + + if(ManipulatorMode() == eTranslate) + { + command << "translateTool"; + outputTranslation(command); + } + else if(ManipulatorMode() == eRotate) + { + command << "rotateTool"; + outputRotation(command); + } + else if(ManipulatorMode() == eScale) + { + command << "scaleTool"; + outputScale(command); + } + else if(ManipulatorMode() == eDrag) + { + command << "dragTool"; + } + + GlobalUndoSystem().finish(command.c_str()); + } + +} + +inline AABB Instance_getPivotBounds(scene::Instance& instance) +{ + Entity* entity = Node_getEntity(instance.path().top()); + if(entity != 0 + && (entity->getEntityClass().fixedsize + || !node_is_group(instance.path().top()))) + { + Editable* editable = Node_getEditable(instance.path().top()); + if(editable != 0) + { + return AABB(vector4_to_vector3(matrix4_multiplied_by_matrix4(instance.localToWorld(), editable->getLocalPivot()).t()), Vector3(0, 0, 0)); + } + else + { + return AABB(vector4_to_vector3(instance.localToWorld().t()), Vector3(0, 0, 0)); + } + } + + return instance.worldAABB(); +} + +class bounds_selected : public scene::Graph::Walker +{ + AABB& m_bounds; +public: + bounds_selected(AABB& bounds) + : m_bounds(bounds) + { + m_bounds = AABB(); + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected()) + { + aabb_extend_by_aabb_safe(m_bounds, Instance_getPivotBounds(instance)); + } + return true; + } +}; + +class bounds_selected_component : public scene::Graph::Walker +{ + AABB& m_bounds; +public: + bounds_selected_component(AABB& bounds) + : m_bounds(bounds) + { + m_bounds = AABB(); + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + Selectable* selectable = Instance_getSelectable(instance); + if(selectable != 0 + && selectable->isSelected()) + { + ComponentEditable* componentEditable = Instance_getComponentEditable(instance); + if(componentEditable) + { + aabb_extend_by_aabb_safe(m_bounds, aabb_for_oriented_aabb_safe(componentEditable->getSelectedComponentsBounds(), instance.localToWorld())); + } + } + return true; + } +}; + +void Scene_BoundsSelected(scene::Graph& graph, AABB& bounds) +{ + graph.traverse(bounds_selected(bounds)); +} + +void Scene_BoundsSelectedComponent(scene::Graph& graph, AABB& bounds) +{ + graph.traverse(bounds_selected_component(bounds)); +} + +#if 0 +inline void pivot_for_node(Matrix4& pivot, scene::Node& node, scene::Instance& instance) +{ + ComponentEditable* componentEditable = Instance_getComponentEditable(instance); + if(GlobalSelectionSystem().Mode() == SelectionSystem::eComponent + && componentEditable != 0) + { + pivot = matrix4_translation_for_vec3(componentEditable->getSelectedComponentsBounds().origin); + } + else + { + Bounded* bounded = Instance_getBounded(instance); + if(bounded != 0) + { + pivot = matrix4_translation_for_vec3(bounded->localAABB().origin); + } + else + { + pivot = g_matrix4_identity; + } + } +} +#endif + +void RadiantSelectionSystem::ConstructPivot() const +{ + if(!m_pivotChanged || m_pivot_moving) + return; + m_pivotChanged = false; + + Vector3 m_object_pivot; + + if(!nothingSelected()) + { + { + AABB bounds; + if(Mode() == eComponent) + { + Scene_BoundsSelectedComponent(GlobalSceneGraph(), bounds); + } + else + { + Scene_BoundsSelected(GlobalSceneGraph(), bounds); + } + m_object_pivot = bounds.origin; + } + + vector3_snap(m_object_pivot, GetSnapGridSize()); + m_pivot2world = matrix4_translation_for_vec3(m_object_pivot); + + switch(m_manipulator_mode) + { + case eTranslate: + break; + case eRotate: + if(Mode() == eComponent) + { + matrix4_assign_rotation_for_pivot(m_pivot2world, m_component_selection.back()); + } + else + { + matrix4_assign_rotation_for_pivot(m_pivot2world, m_selection.back()); + } + break; + case eScale: + if(Mode() == eComponent) + { + matrix4_assign_rotation_for_pivot(m_pivot2world, m_component_selection.back()); + } + else + { + matrix4_assign_rotation_for_pivot(m_pivot2world, m_selection.back()); + } + break; + default: + break; + } + } +} + +void RadiantSelectionSystem::renderSolid(Renderer& renderer, const VolumeTest& volume) const +{ + //if(view->TestPoint(m_object_pivot)) + if(!nothingSelected()) + { + renderer.Highlight(Renderer::ePrimitive, false); + renderer.Highlight(Renderer::eFace, false); + + renderer.SetState(m_state, Renderer::eWireframeOnly); + renderer.SetState(m_state, Renderer::eFullMaterials); + + m_manipulator->render(renderer, volume, GetPivot2World()); + } + +#if defined(DEBUG_SELECTION) + renderer.SetState(g_state_clipped, Renderer::eWireframeOnly); + renderer.SetState(g_state_clipped, Renderer::eFullMaterials); + renderer.addRenderable(g_render_clipped, g_render_clipped.m_world); +#endif +} + + +void SelectionSystem_OnBoundsChanged() +{ + getSelectionSystem().pivotChanged(); +} + + +SignalHandlerId SelectionSystem_boundsChanged; + +void SelectionSystem_Construct() +{ + RadiantSelectionSystem::constructStatic(); + + g_RadiantSelectionSystem = new RadiantSelectionSystem; + + SelectionSystem_boundsChanged = GlobalSceneGraph().addBoundsChangedCallback(FreeCaller()); + + GlobalShaderCache().attachRenderable(getSelectionSystem()); +} + +void SelectionSystem_Destroy() +{ + GlobalShaderCache().detachRenderable(getSelectionSystem()); + + GlobalSceneGraph().removeBoundsChangedCallback(SelectionSystem_boundsChanged); + + delete g_RadiantSelectionSystem; + + RadiantSelectionSystem::destroyStatic(); +} + + + + +inline float screen_normalised(float pos, std::size_t size) +{ + return ((2.0f * pos) / size) - 1.0f; +} + +typedef Vector2 DeviceVector; + +inline DeviceVector window_to_normalised_device(WindowVector window, std::size_t width, std::size_t height) +{ + return DeviceVector(screen_normalised(window.x(), width), screen_normalised(height - 1 - window.y(), height)); +} + +inline float device_constrained(float pos) +{ + return std::min(1.0f, std::max(-1.0f, pos)); +} + +inline DeviceVector device_constrained(DeviceVector device) +{ + return DeviceVector(device_constrained(device.x()), device_constrained(device.y())); +} + +inline float window_constrained(float pos, std::size_t origin, std::size_t size) +{ + return std::min(static_cast(origin + size), std::max(static_cast(origin), pos)); +} + +inline WindowVector window_constrained(WindowVector window, std::size_t x, std::size_t y, std::size_t width, std::size_t height) +{ + return WindowVector(window_constrained(window.x(), x, width), window_constrained(window.y(), y, height)); +} + +typedef Callback1 MouseEventCallback; + +Single g_mouseMovedCallback; +Single g_mouseUpCallback; + +#if 1 +const ButtonIdentifier c_button_select = c_buttonLeft; +const ModifierFlags c_modifier_manipulator = c_modifierNone; +const ModifierFlags c_modifier_toggle = c_modifierShift; +const ModifierFlags c_modifier_replace = c_modifierShift | c_modifierAlt; +const ModifierFlags c_modifier_face = c_modifierControl; +#else +const ButtonIdentifier c_button_select = c_buttonLeft; +const ModifierFlags c_modifier_manipulator = c_modifierNone; +const ModifierFlags c_modifier_toggle = c_modifierControl; +const ModifierFlags c_modifier_replace = c_modifierNone; +const ModifierFlags c_modifier_face = c_modifierShift; +#endif +const ModifierFlags c_modifier_toggle_face = c_modifier_toggle | c_modifier_face; +const ModifierFlags c_modifier_replace_face = c_modifier_replace | c_modifier_face; + +const ButtonIdentifier c_button_texture = c_buttonMiddle; +const ModifierFlags c_modifier_apply_texture = c_modifierControl | c_modifierShift; +const ModifierFlags c_modifier_copy_texture = c_modifierNone; + +class Selector_ +{ + RadiantSelectionSystem::EModifier modifier_for_state(ModifierFlags state) + { + if(state == c_modifier_toggle || state == c_modifier_toggle_face) + { + return RadiantSelectionSystem::eToggle; + } + if(state == c_modifier_replace || state == c_modifier_replace_face) + { + return RadiantSelectionSystem::eReplace; + } + return RadiantSelectionSystem::eManipulator; + } + + rect_t getDeviceArea() const + { + DeviceVector delta(m_current - m_start); + if(selecting() && fabs(delta.x()) > m_epsilon.x() && fabs(delta.y()) > m_epsilon.y()) + { + return SelectionBoxForArea(&m_start[0], &delta[0]); + } + else + { + rect_t default_area = { { 0, 0, }, { 0, 0, }, }; + return default_area; + } + } + +public: + DeviceVector m_start; + DeviceVector m_current; + DeviceVector m_epsilon; + std::size_t m_unmoved_replaces; + ModifierFlags m_state; + const View* m_view; + RectangleCallback m_window_update; + + Selector_() : m_start(0.0f, 0.0f), m_current(0.0f, 0.0f), m_unmoved_replaces(0), m_state(c_modifierNone) + { + } + + void draw_area() + { + m_window_update(getDeviceArea()); + } + + void testSelect(DeviceVector position) + { + RadiantSelectionSystem::EModifier modifier = modifier_for_state(m_state); + if(modifier != RadiantSelectionSystem::eManipulator) + { + DeviceVector delta(position - m_start); + if(fabs(delta.x()) > m_epsilon.x() && fabs(delta.y()) > m_epsilon.y()) + { + DeviceVector delta(position - m_start); + getSelectionSystem().SelectArea(*m_view, &m_start[0], &delta[0], modifier, (m_state & c_modifier_face) != c_modifierNone); + } + else + { + if(modifier == RadiantSelectionSystem::eReplace && m_unmoved_replaces++ > 0) + { + modifier = RadiantSelectionSystem::eCycle; + } + getSelectionSystem().SelectPoint(*m_view, &position[0], &m_epsilon[0], modifier, (m_state & c_modifier_face) != c_modifierNone); + } + } + + m_start = m_current = DeviceVector(0.0f, 0.0f); + draw_area(); + } + + bool selecting() const + { + return m_state != c_modifier_manipulator; + } + + void setState(ModifierFlags state) + { + bool was_selecting = selecting(); + m_state = state; + if(was_selecting ^ selecting()) + { + draw_area(); + } + } + + ModifierFlags getState() const + { + return m_state; + } + + void modifierEnable(ModifierFlags type) + { + setState(bitfield_enable(getState(), type)); + } + void modifierDisable(ModifierFlags type) + { + setState(bitfield_disable(getState(), type)); + } + + void mouseDown(DeviceVector position) + { + m_start = m_current = device_constrained(position); + } + + void mouseMoved(DeviceVector position) + { + m_current = device_constrained(position); + draw_area(); + } + typedef MemberCaller1 MouseMovedCaller; + + void mouseUp(DeviceVector position) + { + testSelect(device_constrained(position)); + + g_mouseMovedCallback.clear(); + g_mouseUpCallback.clear(); + } + typedef MemberCaller1 MouseUpCaller; +}; + + +class Manipulator_ +{ +public: + DeviceVector m_epsilon; + const View* m_view; + + bool mouseDown(DeviceVector position) + { + return getSelectionSystem().SelectManipulator(*m_view, &position[0], &m_epsilon[0]); + } + + void mouseMoved(DeviceVector position) + { + getSelectionSystem().MoveSelected(*m_view, &position[0]); + } + typedef MemberCaller1 MouseMovedCaller; + + void mouseUp(DeviceVector position) + { + getSelectionSystem().endMove(); + g_mouseMovedCallback.clear(); + g_mouseUpCallback.clear(); + } + typedef MemberCaller1 MouseUpCaller; +}; + +void Scene_copyClosestTexture(SelectionTest& test); +void Scene_applyClosestTexture(SelectionTest& test); + +class RadiantWindowObserver : public SelectionSystemWindowObserver +{ + enum + { + SELECT_EPSILON = 8, + }; + + int m_width; + int m_height; + + bool m_mouse_down; + +public: + Selector_ m_selector; + Manipulator_ m_manipulator; + + RadiantWindowObserver() : m_mouse_down(false) + { + } + void release() + { + delete this; + } + void setView(const View& view) + { + m_selector.m_view = &view; + m_manipulator.m_view = &view; + } + void setRectangleDrawCallback(const RectangleCallback& callback) + { + m_selector.m_window_update = callback; + } + void onSizeChanged(int width, int height) + { + m_width = width; + m_height = height; + DeviceVector epsilon(SELECT_EPSILON / static_cast(m_width), SELECT_EPSILON / static_cast(m_height)); + m_selector.m_epsilon = m_manipulator.m_epsilon = epsilon; + } + void onMouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) + { + if(button == c_button_select) + { + m_mouse_down = true; + + DeviceVector devicePosition(window_to_normalised_device(position, m_width, m_height)); + if(modifiers == c_modifier_manipulator && m_manipulator.mouseDown(devicePosition)) + { + g_mouseMovedCallback.insert(MouseEventCallback(Manipulator_::MouseMovedCaller(m_manipulator))); + g_mouseUpCallback.insert(MouseEventCallback(Manipulator_::MouseUpCaller(m_manipulator))); + } + else + { + m_selector.mouseDown(devicePosition); + g_mouseMovedCallback.insert(MouseEventCallback(Selector_::MouseMovedCaller(m_selector))); + g_mouseUpCallback.insert(MouseEventCallback(Selector_::MouseUpCaller(m_selector))); + } + } + else if(button == c_button_texture) + { + DeviceVector devicePosition(device_constrained(window_to_normalised_device(position, m_width, m_height))); + + View scissored(*m_selector.m_view); + ConstructSelectionTest(scissored, SelectionBoxForPoint(&devicePosition[0], &m_selector.m_epsilon[0])); + SelectionVolume volume(scissored); + + if(modifiers == c_modifier_apply_texture) + { + Scene_applyClosestTexture(volume); + } + else if(modifiers == c_modifier_copy_texture) + { + Scene_copyClosestTexture(volume); + } + } + } + void onMouseMotion(const WindowVector& position, ModifierFlags modifiers) + { + m_selector.m_unmoved_replaces = 0; + + if(m_mouse_down && !g_mouseMovedCallback.empty()) + { + g_mouseMovedCallback.get()(window_to_normalised_device(position, m_width, m_height)); + } + } + void onMouseUp(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) + { + if(button == c_button_select && !g_mouseUpCallback.empty()) + { + m_mouse_down = false; + + g_mouseUpCallback.get()(window_to_normalised_device(position, m_width, m_height)); + } + } + void onModifierDown(ModifierFlags type) + { + m_selector.modifierEnable(type); + } + void onModifierUp(ModifierFlags type) + { + m_selector.modifierDisable(type); + } +}; + + + +SelectionSystemWindowObserver* NewWindowObserver() +{ + return new RadiantWindowObserver; +} + + + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class SelectionDependencies : + public GlobalSceneGraphModuleRef, + public GlobalShaderCacheModuleRef, + public GlobalOpenGLModuleRef +{ +}; + +class SelectionAPI : public TypeSystemRef +{ + SelectionSystem* m_selection; +public: + typedef SelectionSystem Type; + STRING_CONSTANT(Name, "*"); + + SelectionAPI() + { + SelectionSystem_Construct(); + + m_selection = &getSelectionSystem(); + } + ~SelectionAPI() + { + SelectionSystem_Destroy(); + } + SelectionSystem* getTable() + { + return m_selection; + } +}; + +typedef SingletonModule SelectionModule; +typedef Static StaticSelectionModule; +StaticRegisterModule staticRegisterSelection(StaticSelectionModule::instance()); diff --git a/misc/mediasource/netradiant-src/radiant/selection.h b/misc/mediasource/netradiant-src/radiant/selection.h new file mode 100644 index 00000000..8334ec63 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/selection.h @@ -0,0 +1,54 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_SELECTION_H) +#define INCLUDED_SELECTION_H + +#include "windowobserver.h" +#include "generic/callbackfwd.h" + +struct rect_t +{ + float min[2]; + float max[2]; +}; + +typedef Callback1 RectangleCallback; + +class View; + +class SelectionSystemWindowObserver : public WindowObserver +{ +public: + virtual void setView(const View& view) = 0; + virtual void setRectangleDrawCallback(const RectangleCallback& callback) = 0; +}; + +SelectionSystemWindowObserver* NewWindowObserver(); + +class AABB; +namespace scene +{ + class Graph; +} +void Scene_BoundsSelected(scene::Graph& graph, AABB& bounds); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/server.cpp b/misc/mediasource/netradiant-src/radiant/server.cpp new file mode 100644 index 00000000..e6b4dbb1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/server.cpp @@ -0,0 +1,291 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "server.h" + +#include "debugging/debugging.h" +#include "warnings.h" + +#include +#include +#include "os/path.h" + +#include "modulesystem.h" + +class RadiantModuleServer : public ModuleServer +{ + typedef std::pair ModuleType; + typedef std::pair ModuleKey; + typedef std::map Modules_; + Modules_ m_modules; + bool m_error; + +public: + RadiantModuleServer() : m_error(false) + { + } + + void setError(bool error) + { + m_error = error; + } + bool getError() const + { + return m_error; + } + + TextOutputStream& getOutputStream() + { + return globalOutputStream(); + } + TextOutputStream& getErrorStream() + { + return globalErrorStream(); + } + DebugMessageHandler& getDebugMessageHandler() + { + return globalDebugMessageHandler(); + } + + void registerModule(const char* type, int version, const char* name, Module& module) + { + ASSERT_NOTNULL(&module); + if(!m_modules.insert(Modules_::value_type(ModuleKey(ModuleType(type, version), name), &module)).second) + { + globalErrorStream() << "module already registered: type=" << makeQuoted(type) << " name=" << makeQuoted(name) << "\n"; + } + else + { + globalOutputStream() << "Module Registered: type=" << makeQuoted(type) << " version=" << makeQuoted(version) << " name=" << makeQuoted(name) << "\n"; + } + } + + Module* findModule(const char* type, int version, const char* name) const + { + Modules_::const_iterator i = m_modules.find(ModuleKey(ModuleType(type, version), name)); + if(i != m_modules.end()) + { + return (*i).second; + } + return 0; + } + + void foreachModule(const char* type, int version, const Visitor& visitor) + { + for(Modules_::const_iterator i = m_modules.begin(); i != m_modules.end(); ++i) + { + if(string_equal((*i).first.first.first.c_str(), type)) + { + visitor.visit((*i).first.second.c_str(), *(*i).second); + } + } + } +}; + + +#if defined(WIN32) + +#include + +#define FORMAT_BUFSIZE 2048 +const char* FormatGetLastError() +{ + static char buf[FORMAT_BUFSIZE]; + FormatMessage( + FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + buf, + FORMAT_BUFSIZE, + NULL + ); + return buf; +} + +class DynamicLibrary +{ + HMODULE m_library; +public: + typedef int (__stdcall* FunctionPointer)(); + + DynamicLibrary(const char* filename) + { + m_library = LoadLibrary(filename); + if(m_library == 0) + { + globalErrorStream() << "LoadLibrary failed: '" << filename << "'\n"; + globalErrorStream() << "GetLastError: " << FormatGetLastError(); + } + } + ~DynamicLibrary() + { + if(!failed()) + { + FreeLibrary(m_library); + } + } + bool failed() + { + return m_library == 0; + } + FunctionPointer findSymbol(const char* symbol) + { + FunctionPointer address = GetProcAddress(m_library, symbol); + if(address == 0) + { + globalErrorStream() << "GetProcAddress failed: '" << symbol << "'\n"; + globalErrorStream() << "GetLastError: " << FormatGetLastError(); + } + return address; + } +}; + +#elif defined(POSIX) + +#include + +class DynamicLibrary +{ + void* m_library; +public: + typedef int (* FunctionPointer)(); + + DynamicLibrary(const char* filename) + { + m_library = dlopen(filename, RTLD_NOW); + } + ~DynamicLibrary() + { + if(!failed()) + dlclose(m_library); + } + bool failed() + { + return m_library == 0; + } + FunctionPointer findSymbol(const char* symbol) + { + FunctionPointer p = (FunctionPointer)dlsym(m_library, symbol); + if(p == 0) + { + const char* error = reinterpret_cast(dlerror()); + if(error != 0) + { + globalErrorStream() << error; + } + } + return p; + } +}; + +#else +#error "unsupported platform" +#endif + +class DynamicLibraryModule +{ + typedef void (RADIANT_DLLIMPORT* RegisterModulesFunc)(ModuleServer& server); + DynamicLibrary m_library; + RegisterModulesFunc m_registerModule; +public: + DynamicLibraryModule(const char* filename) + : m_library(filename), m_registerModule(0) + { + if(!m_library.failed()) + { + m_registerModule = reinterpret_cast(m_library.findSymbol("Radiant_RegisterModules")); +#if 0 + if(!m_registerModule) + m_registerModule = reinterpret_cast(m_library.findSymbol("Radiant_RegisterModules@4")); +#endif + } + } + bool failed() + { + return m_registerModule == 0; + } + void registerModules(ModuleServer& server) + { + m_registerModule(server); + } +}; + + +class Libraries +{ + typedef std::vector libraries_t; + libraries_t m_libraries; + +public: + ~Libraries() + { + release(); + } + void registerLibrary(const char* filename, ModuleServer& server) + { + DynamicLibraryModule* library = new DynamicLibraryModule(filename); + + if(library->failed()) + { + delete library; + } + else + { + m_libraries.push_back(library); + library->registerModules(server); + } + } + void release() + { + for(libraries_t::iterator i = m_libraries.begin(); i != m_libraries.end(); ++i) + { + delete *i; + } + } + void clear() + { + m_libraries.clear(); + } +}; + + +Libraries g_libraries; +RadiantModuleServer g_server; + +ModuleServer& GlobalModuleServer_get() +{ + return g_server; +} + +void GlobalModuleServer_loadModule(const char* filename) +{ + g_libraries.registerLibrary(filename, g_server); +} + +void GlobalModuleServer_Initialise() +{ +} + +void GlobalModuleServer_Shutdown() +{ +} diff --git a/misc/mediasource/netradiant-src/radiant/server.h b/misc/mediasource/netradiant-src/radiant/server.h new file mode 100644 index 00000000..ded73098 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/server.h @@ -0,0 +1,31 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_SERVER_H) +#define INCLUDED_SERVER_H + +class ModuleServer; +ModuleServer& GlobalModuleServer_get(); +void GlobalModuleServer_loadModule(const char* filename); +void GlobalModuleServer_Initialise(); +void GlobalModuleServer_Shutdown(); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/shaders.cpp b/misc/mediasource/netradiant-src/radiant/shaders.cpp new file mode 100644 index 00000000..696ef5ba --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/shaders.cpp @@ -0,0 +1,73 @@ +/* +Copyright (C) 1999-2006 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 "shaders.h" + +#include "ifilesystem.h" + +#include "stream/stringstream.h" + +#include "gtkdlgs.h" + +void ViewShader(const char *pFile, const char *pName) +{ + char* pBuff = 0; + //int nSize = + vfsLoadFile(pFile, reinterpret_cast(&pBuff)); + if (pBuff == 0) + { + globalErrorStream() << "Failed to load shader file " << pFile << "\n"; + return; + } + // look for the shader declaration + StringOutputStream strFind(string_length(pName)); + strFind << LowerCase(pName); + StringOutputStream strLook(string_length(pBuff)); + strFind << LowerCase(pBuff); + // offset used when jumping over commented out definitions + std::size_t nOffset = 0; + while (true) + { + const char* substr = strstr(strFind.c_str() + nOffset, strFind.c_str()); + if (substr == 0) + break; + std::size_t nStart = substr - strLook.c_str(); + // we have found something, maybe it's a commented out shader name? + char *strCheck = new char[string_length(strLook.c_str())+1]; + strcpy( strCheck, strLook.c_str() ); + strCheck[nStart] = 0; + char *pCheck = strrchr( strCheck, '\n' ); + // if there's a commentary sign in-between we'll continue + if (pCheck && strstr( pCheck, "//" )) + { + delete[] strCheck; + nOffset = nStart + 1; + continue; + } + delete[] strCheck; + nOffset = nStart; + break; + } + // now close the file + vfsFreeFile(pBuff); + + DoTextEditor (pFile, static_cast(nOffset)); +} diff --git a/misc/mediasource/netradiant-src/radiant/shaders.h b/misc/mediasource/netradiant-src/radiant/shaders.h new file mode 100644 index 00000000..58b398cf --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/shaders.h @@ -0,0 +1,27 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_SHADERS_H) +#define INCLUDED_SHADERS_H + +void ViewShader(const char* file, const char* shader); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/sockets.cpp b/misc/mediasource/netradiant-src/radiant/sockets.cpp new file mode 100644 index 00000000..e08680be --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/sockets.cpp @@ -0,0 +1,47 @@ + +#include "sockets.h" + +#if defined(WIN32) +#include +#elif defined (POSIX) +#include +#define SOCKET_ERROR -1 +#else +#error "unsupported platform" +#endif + +#ifdef __APPLE__ +#include +#endif + +int Net_Wait(socket_t *sock, long sec, long usec) +{ +// used for select() +#ifdef WIN32 + TIMEVAL tout = { sec, usec }; +#endif +#if defined (POSIX) + timeval tout; + tout.tv_sec = sec; + tout.tv_usec = usec; +#endif + + // select() will identify if the socket needs an update + // if the socket is identified that means there's either a message or the connection has been closed/reset/terminated + fd_set readfds; + FD_ZERO(&readfds); + FD_SET(((unsigned int)sock->socket), &readfds); + // from select man page: + // n is the highest-numbered descriptor in any of the three sets, plus 1 + // (no use on windows) + switch( select( sock->socket + 1, &readfds, 0, 0, &tout ) ) + { + case SOCKET_ERROR: + return -1; + case 0: + return 0; + default: + return 1; + } +} + diff --git a/misc/mediasource/netradiant-src/radiant/sockets.h b/misc/mediasource/netradiant-src/radiant/sockets.h new file mode 100644 index 00000000..3bc2274d --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/sockets.h @@ -0,0 +1,14 @@ + +#if !defined(INCLUDED_SOCKETS_H) +#define INCLUDED_SOCKETS_H + +#include "l_net/l_net.h" + +// waits for a socket to become ready +// returns +// -1: error +// 0: timeout +// 1: ready +int Net_Wait(socket_t *sock, long sec, long usec); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/stacktrace.cpp b/misc/mediasource/netradiant-src/radiant/stacktrace.cpp new file mode 100644 index 00000000..18a70462 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/stacktrace.cpp @@ -0,0 +1,319 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "stacktrace.h" +#include "stream/textstream.h" + +#include "environment.h" + +#ifdef __linux__ +#include + +void write_stack_trace(TextOutputStream& outputStream) +{ + const unsigned int MAX_SYMBOLS = 256; + void* symbols[MAX_SYMBOLS]; + + // get return addresses + int symbol_count = backtrace(symbols, MAX_SYMBOLS); + + if(!symbol_count) + return; + + // resolve and print names + char** symbol_names = backtrace_symbols(symbols, symbol_count); + if(symbol_names) + { + for(int i = 0; (i < symbol_count); ++i) + outputStream << symbol_names[i] << "\n"; + + // not a memleak, see www.gnu.org/software/libc/manual (Debugging Support, Backtraces) + free(symbol_names); + } +} +#elif defined (WIN32) && defined (_MSC_VER) + +#include "windows.h" +#include "winnt.h" +#include "dbghelp.h" + +class Address +{ +public: + void* m_value; + Address(void* value) : m_value(value) + { + } +}; + +/// \brief Writes an address \p p to \p ostream in hexadecimal form. +template +inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const Address& p) +{ + const std::size_t bufferSize = (sizeof(void*) * 2) + 1; + char buf[bufferSize]; + ostream.write(buf, snprintf(buf, bufferSize, "%0p", p.m_value)); + return ostream; +} + +class Offset +{ +public: + void* m_value; + Offset(void* value) : m_value(value) + { + } +}; + +/// \brief Writes an address \p p to \p ostream in hexadecimal form. +template +inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const Offset& p) +{ + const std::size_t bufferSize = (sizeof(void*) * 2) + 1; + char buf[bufferSize]; + ostream.write(buf, snprintf(buf, bufferSize, "%X", p.m_value)); + return ostream; +} + +/// \brief Writes a WCHAR string \p s to \p ostream. +template +inline TextOutputStreamType& ostream_write(TextOutputStreamType& ostream, const WCHAR* s) +{ + const std::size_t bufferSize = 1024; + char buf[bufferSize]; + ostream.write(buf, snprintf(buf, bufferSize, "%ls", s)); + return ostream; +} + +struct EnumerateSymbolsContext +{ + STACKFRAME64& sf; + TextOutputStream& outputStream; + std::size_t count; + EnumerateSymbolsContext(STACKFRAME64& sf, TextOutputStream& outputStream) : sf(sf), outputStream(outputStream), count(0) + { + } +}; + +void write_symbol(PSYMBOL_INFO pSym, STACKFRAME64& sf, TextOutputStream& outputStream, std::size_t& count) +{ +#if 0 + if ( pSym->Flags & SYMFLAG_PARAMETER ) + { + + DWORD basicType; + if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, + TI_GET_BASETYPE, &basicType ) ) + { + int bleh = 0; + } + else + { + DWORD typeId; + if(SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, + TI_GET_TYPEID, &typeId )) + { + if ( SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, pSym->TypeIndex, + TI_GET_BASETYPE, &basicType ) ) + { + int bleh = 0; + } + else + { + const char* FormatGetLastError(); + const char* error = FormatGetLastError(); + int bleh = 0; + + WCHAR* name; + if(SymGetTypeInfo( GetCurrentProcess(), pSym->ModBase, typeId, + TI_GET_SYMNAME, &name )) + { + outputStream << name << " "; + LocalFree(name); + int bleh = 0; + } + else + { + const char* FormatGetLastError(); + const char* error = FormatGetLastError(); + int bleh = 0; + } + } + } + else + { + const char* FormatGetLastError(); + const char* error = FormatGetLastError(); + int bleh = 0; + } + } + if(count != 0) + { + outputStream << ", "; + } + outputStream << pSym->Name; + ++count; + } +#endif +} + +BOOL CALLBACK +EnumerateSymbolsCallback( + PSYMBOL_INFO pSymInfo, + ULONG SymbolSize, + PVOID UserContext ) +{ + write_symbol( pSymInfo, ((EnumerateSymbolsContext*)UserContext)->sf, ((EnumerateSymbolsContext*)UserContext)->outputStream, ((EnumerateSymbolsContext*)UserContext)->count); + + + return TRUE; +} + +void write_stack_trace(PCONTEXT pContext, TextOutputStream& outputStream) +{ + HANDLE m_hProcess = GetCurrentProcess(); + DWORD dwMachineType = 0; + + CONTEXT context = *pContext; + + // Could use SymSetOptions here to add the SYMOPT_DEFERRED_LOADS flag + if ( !SymInitialize( m_hProcess, (PSTR)environment_get_app_path(), TRUE ) ) + { + return; + } + + STACKFRAME64 sf; + memset( &sf, 0, sizeof(sf) ); + sf.AddrPC.Mode = AddrModeFlat; + sf.AddrStack.Mode = AddrModeFlat; + sf.AddrFrame.Mode = AddrModeFlat; + +#ifdef _M_IX86 + // Initialize the STACKFRAME structure for the first call. This is only + // necessary for Intel CPUs, and isn't mentioned in the documentation. + sf.AddrPC.Offset = context.Eip; + sf.AddrStack.Offset = context.Esp; + sf.AddrFrame.Offset = context.Ebp; + + dwMachineType = IMAGE_FILE_MACHINE_I386; +#elif _M_X64 + sf.AddrPC.Offset = context.Rip; + sf.AddrStack.Offset = context.Rsp; + + // MSDN: x64: The frame pointer is RBP or RDI. This value is not always used. + // very funny, we'll try Rdi for now + sf.AddrFrame.Offset = context.Rdi; + + dwMachineType = IMAGE_FILE_MACHINE_AMD64; +#endif + + const unsigned int max_sym_name = 1024;// should be enough + + while ( 1 ) + { + // Get the next stack frame + if ( ! StackWalk64( dwMachineType, + m_hProcess, + GetCurrentThread(), + &sf, + &context, + 0, + SymFunctionTableAccess64, + SymGetModuleBase64, + 0 ) ) + break; + + if ( 0 == sf.AddrFrame.Offset ) // Basic sanity check to make sure + break; // the frame is OK. Bail if not. + + // Get the name of the function for this stack frame entry + BYTE symbolBuffer[ sizeof(SYMBOL_INFO) + max_sym_name ]; + PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)symbolBuffer; + pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO); + pSymbol->MaxNameLen = max_sym_name; + + DWORD64 symDisplacement = 0; // Displacement of the input address, + // relative to the start of the symbol + + IMAGEHLP_MODULE64 module = { sizeof(IMAGEHLP_MODULE64) }; + if(SymGetModuleInfo64(m_hProcess, sf.AddrPC.Offset, &module)) + { + outputStream << module.ModuleName << "!"; + + if ( SymFromAddr(m_hProcess, sf.AddrPC.Offset, &symDisplacement, pSymbol)) + { + char undecoratedName[max_sym_name]; + UnDecorateSymbolName(pSymbol->Name, undecoratedName, max_sym_name, UNDNAME_COMPLETE); + + outputStream << undecoratedName; + + outputStream << "("; + // Use SymSetContext to get just the locals/params for this frame + IMAGEHLP_STACK_FRAME imagehlpStackFrame; + imagehlpStackFrame.InstructionOffset = sf.AddrPC.Offset; + SymSetContext( m_hProcess, &imagehlpStackFrame, 0 ); + + // Enumerate the locals/parameters + EnumerateSymbolsContext context(sf, outputStream); + SymEnumSymbols( m_hProcess, 0, 0, EnumerateSymbolsCallback, &context ); + outputStream << ")"; + + outputStream << " + " << Offset(reinterpret_cast(symDisplacement)); + + // Get the source line for this stack frame entry + IMAGEHLP_LINE64 lineInfo = { sizeof(IMAGEHLP_LINE64) }; + DWORD dwLineDisplacement; + if ( SymGetLineFromAddr64( m_hProcess, sf.AddrPC.Offset, + &dwLineDisplacement, &lineInfo ) ) + { + outputStream << " " << lineInfo.FileName << " line " << Unsigned(lineInfo.LineNumber); + } + } + else + { + outputStream << Address(reinterpret_cast(sf.AddrPC.Offset)); + } + } + + outputStream << "\n"; + } + + SymCleanup(m_hProcess); + + return; +} + +void write_stack_trace(TextOutputStream& outputStream) +{ + __try{ RaiseException(0,0,0,0); } __except(write_stack_trace((GetExceptionInformation())->ContextRecord, outputStream), EXCEPTION_CONTINUE_EXECUTION) {} +} + +#elif defined (WIN32) +void write_stack_trace(TextOutputStream& outputStream) +{ + outputStream << "\nStacktrace is disabled on this compiler\n"; +} +#else +void write_stack_trace(TextOutputStream& outputStream) +{ + outputStream << "\nStacktrace is disabled on this platform\n"; +} +#endif diff --git a/misc/mediasource/netradiant-src/radiant/stacktrace.h b/misc/mediasource/netradiant-src/radiant/stacktrace.h new file mode 100644 index 00000000..6f2ee0e5 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/stacktrace.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_STACKTRACE_H) +#define INCLUDED_STACKTRACE_H + +class TextOutputStream; +void write_stack_trace(TextOutputStream& outputStream); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/surfacedialog.cpp b/misc/mediasource/netradiant-src/radiant/surfacedialog.cpp new file mode 100644 index 00000000..b2067014 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/surfacedialog.cpp @@ -0,0 +1,2450 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Surface Dialog +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "surfacedialog.h" + +#include "debugging/debugging.h" +#include "warnings.h" + +#include "iscenegraph.h" +#include "itexdef.h" +#include "iundo.h" +#include "iselection.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include //Shamus: For Textool + +#include "signal/isignal.h" +#include "generic/object.h" +#include "math/vector.h" +#include "texturelib.h" +#include "shaderlib.h" +#include "stringio.h" + +#include "gtkutil/idledraw.h" +#include "gtkutil/dialog.h" +#include "gtkutil/entry.h" +#include "gtkutil/nonmodal.h" +#include "gtkutil/pointer.h" +#include "gtkutil/glwidget.h" //Shamus: For Textool +#include "gtkutil/button.h" +#include "map.h" +#include "select.h" +#include "patchmanip.h" +#include "brushmanip.h" +#include "patchdialog.h" +#include "preferences.h" +#include "brush_primit.h" +#include "xywindow.h" +#include "mainframe.h" +#include "gtkdlgs.h" +#include "dialog.h" +#include "brush.h" //Shamus: for Textool +#include "patch.h" +#include "commands.h" +#include "stream/stringstream.h" +#include "grid.h" +#include "textureentry.h" + +//NOTE: Proper functioning of Textool currently requires that the "#if 1" lines in +// brush_primit.h be changed to "#if 0". add/removeScale screws this up ATM. :-) +// Plus, Radiant seems to work just fine without that stuff. ;-) + +#define TEXTOOL_ENABLED 0 + +#if TEXTOOL_ENABLED + +namespace TexTool +{ + +//Shamus: Textool function prototypes +gboolean size_allocate(GtkWidget *, GtkAllocation *, gpointer); +gboolean expose(GtkWidget *, GdkEventExpose *, gpointer); +gboolean button_press(GtkWidget *, GdkEventButton *, gpointer); +gboolean button_release(GtkWidget *, GdkEventButton *, gpointer); +gboolean motion(GtkWidget *, GdkEventMotion *, gpointer); +void flipX(GtkToggleButton *, gpointer); +void flipY(GtkToggleButton *, gpointer); + +//End Textool function prototypes + +//Shamus: Textool globals +GtkWidget * g_textoolWin; +//End Textool globals + +void queueDraw() +{ + gtk_widget_queue_draw(g_textoolWin); +} + +} + +#endif + +inline void spin_button_set_step(GtkSpinButton* spin, gfloat step) +{ +#if 1 + gtk_spin_button_get_adjustment(spin)->step_increment = step; +#else + GValue gvalue = GValue_default(); + g_value_init(&gvalue, G_TYPE_DOUBLE); + g_value_set_double(&gvalue, step); + g_object_set(G_OBJECT(gtk_spin_button_get_adjustment(spin)), "step-increment", &gvalue, NULL); +#endif +} + +class Increment +{ + float& m_f; +public: + GtkSpinButton* m_spin; + GtkEntry* m_entry; + Increment(float& f) : m_f(f), m_spin(0), m_entry(0) + { + } + void cancel() + { + entry_set_float(m_entry, m_f); + } + typedef MemberCaller CancelCaller; + void apply() + { + m_f = static_cast(entry_get_float(m_entry)); + spin_button_set_step(m_spin, m_f); + } + typedef MemberCaller ApplyCaller; +}; + +void SurfaceInspector_GridChange(); + +class SurfaceInspector : public Dialog +{ + GtkWindow* BuildDialog(); + + NonModalEntry m_textureEntry; + NonModalSpinner m_hshiftSpinner; + NonModalEntry m_hshiftEntry; + NonModalSpinner m_vshiftSpinner; + NonModalEntry m_vshiftEntry; + NonModalSpinner m_hscaleSpinner; + NonModalEntry m_hscaleEntry; + NonModalSpinner m_vscaleSpinner; + NonModalEntry m_vscaleEntry; + NonModalSpinner m_rotateSpinner; + NonModalEntry m_rotateEntry; + + IdleDraw m_idleDraw; + + GtkCheckButton* m_surfaceFlags[32]; + GtkCheckButton* m_contentFlags[32]; + + NonModalEntry m_valueEntry; + GtkEntry* m_valueEntryWidget; +public: + WindowPositionTracker m_positionTracker; + WindowPositionTrackerImportStringCaller m_importPosition; + WindowPositionTrackerExportStringCaller m_exportPosition; + + // Dialog Data + float m_fitHorizontal; + float m_fitVertical; + + Increment m_hshiftIncrement; + Increment m_vshiftIncrement; + Increment m_hscaleIncrement; + Increment m_vscaleIncrement; + Increment m_rotateIncrement; + GtkEntry* m_texture; + + SurfaceInspector() : + m_textureEntry(ApplyShaderCaller(*this), UpdateCaller(*this)), + m_hshiftSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), + m_hshiftEntry(Increment::ApplyCaller(m_hshiftIncrement), Increment::CancelCaller(m_hshiftIncrement)), + m_vshiftSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), + m_vshiftEntry(Increment::ApplyCaller(m_vshiftIncrement), Increment::CancelCaller(m_vshiftIncrement)), + m_hscaleSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), + m_hscaleEntry(Increment::ApplyCaller(m_hscaleIncrement), Increment::CancelCaller(m_hscaleIncrement)), + m_vscaleSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), + m_vscaleEntry(Increment::ApplyCaller(m_vscaleIncrement), Increment::CancelCaller(m_vscaleIncrement)), + m_rotateSpinner(ApplyTexdefCaller(*this), UpdateCaller(*this)), + m_rotateEntry(Increment::ApplyCaller(m_rotateIncrement), Increment::CancelCaller(m_rotateIncrement)), + m_idleDraw(UpdateCaller(*this)), + m_valueEntry(ApplyFlagsCaller(*this), UpdateCaller(*this)), + m_importPosition(m_positionTracker), + m_exportPosition(m_positionTracker), + m_hshiftIncrement(g_si_globals.shift[0]), + m_vshiftIncrement(g_si_globals.shift[1]), + m_hscaleIncrement(g_si_globals.scale[0]), + m_vscaleIncrement(g_si_globals.scale[1]), + m_rotateIncrement(g_si_globals.rotate) + { + m_fitVertical = 1; + m_fitHorizontal = 1; + m_positionTracker.setPosition(c_default_window_pos); + } + + void constructWindow(GtkWindow* main_window) + { + m_parent = main_window; + Create(); + AddGridChangeCallback(FreeCaller()); + } + void destroyWindow() + { + Destroy(); + } + bool visible() const + { + return GTK_WIDGET_VISIBLE(const_cast(GetWidget())); + } + void queueDraw() + { + if(visible()) + { + m_idleDraw.queueDraw(); + } + } + + void Update(); + typedef MemberCaller UpdateCaller; + void ApplyShader(); + typedef MemberCaller ApplyShaderCaller; + void ApplyTexdef(); + typedef MemberCaller ApplyTexdefCaller; + void ApplyFlags(); + typedef MemberCaller ApplyFlagsCaller; +}; + +namespace +{ + SurfaceInspector* g_SurfaceInspector; + + inline SurfaceInspector& getSurfaceInspector() + { + ASSERT_NOTNULL(g_SurfaceInspector); + return *g_SurfaceInspector; + } +} + +void SurfaceInspector_constructWindow(GtkWindow* main_window) +{ + getSurfaceInspector().constructWindow(main_window); +} +void SurfaceInspector_destroyWindow() +{ + getSurfaceInspector().destroyWindow(); +} + +void SurfaceInspector_queueDraw() +{ + getSurfaceInspector().queueDraw(); +} + +namespace +{ + CopiedString g_selectedShader; + TextureProjection g_selectedTexdef; + ContentsFlagsValue g_selectedFlags; + size_t g_selectedShaderSize[2]; +} + +void SurfaceInspector_SetSelectedShader(const char* shader) +{ + g_selectedShader = shader; + SurfaceInspector_queueDraw(); +} + +void SurfaceInspector_SetSelectedTexdef(const TextureProjection& projection) +{ + g_selectedTexdef = projection; + SurfaceInspector_queueDraw(); +} + +void SurfaceInspector_SetSelectedFlags(const ContentsFlagsValue& flags) +{ + g_selectedFlags = flags; + SurfaceInspector_queueDraw(); +} + +static bool s_texture_selection_dirty = false; + +void SurfaceInspector_updateSelection() +{ + s_texture_selection_dirty = true; + SurfaceInspector_queueDraw(); + +#if TEXTOOL_ENABLED + if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + TexTool::queueDraw(); + //globalOutputStream() << "textool texture changed..\n"; + } +#endif +} + +void SurfaceInspector_SelectionChanged(const Selectable& selectable) +{ + SurfaceInspector_updateSelection(); +} + +void SurfaceInspector_SetCurrent_FromSelected() +{ + if(s_texture_selection_dirty == true) + { + s_texture_selection_dirty = false; + if(!g_SelectedFaceInstances.empty()) + { + TextureProjection projection; +//This *may* be the point before it fucks up... Let's see! +//Yep, there was a call to removeScale in there... + Scene_BrushGetTexdef_Component_Selected(GlobalSceneGraph(), projection); + + SurfaceInspector_SetSelectedTexdef(projection); + + Scene_BrushGetShaderSize_Component_Selected(GlobalSceneGraph(), g_selectedShaderSize[0], g_selectedShaderSize[1]); + g_selectedTexdef.m_brushprimit_texdef.coords[0][2] = float_mod(g_selectedTexdef.m_brushprimit_texdef.coords[0][2], (float)g_selectedShaderSize[0]); + g_selectedTexdef.m_brushprimit_texdef.coords[1][2] = float_mod(g_selectedTexdef.m_brushprimit_texdef.coords[1][2], (float)g_selectedShaderSize[1]); + + CopiedString name; + Scene_BrushGetShader_Component_Selected(GlobalSceneGraph(), name); + if(string_not_empty(name.c_str())) + { + SurfaceInspector_SetSelectedShader(name.c_str()); + } + + ContentsFlagsValue flags; + Scene_BrushGetFlags_Component_Selected(GlobalSceneGraph(), flags); + SurfaceInspector_SetSelectedFlags(flags); + } + else + { + TextureProjection projection; + Scene_BrushGetTexdef_Selected(GlobalSceneGraph(), projection); + SurfaceInspector_SetSelectedTexdef(projection); + + CopiedString name; + Scene_BrushGetShader_Selected(GlobalSceneGraph(), name); + if(string_empty(name.c_str())) + { + Scene_PatchGetShader_Selected(GlobalSceneGraph(), name); + } + if(string_not_empty(name.c_str())) + { + SurfaceInspector_SetSelectedShader(name.c_str()); + } + + ContentsFlagsValue flags(0, 0, 0, false); + Scene_BrushGetFlags_Selected(GlobalSceneGraph(), flags); + SurfaceInspector_SetSelectedFlags(flags); + } + } +} + +const char* SurfaceInspector_GetSelectedShader() +{ + SurfaceInspector_SetCurrent_FromSelected(); + return g_selectedShader.c_str(); +} + +const TextureProjection& SurfaceInspector_GetSelectedTexdef() +{ + SurfaceInspector_SetCurrent_FromSelected(); + return g_selectedTexdef; +} + +const ContentsFlagsValue& SurfaceInspector_GetSelectedFlags() +{ + SurfaceInspector_SetCurrent_FromSelected(); + return g_selectedFlags; +} + + + +/* +=================================================== + + SURFACE INSPECTOR + +=================================================== +*/ + +si_globals_t g_si_globals; + + +// make the shift increments match the grid settings +// the objective being that the shift+arrows shortcuts move the texture by the corresponding grid size +// this depends on a scale value if you have selected a particular texture on which you want it to work: +// we move the textures in pixels, not world units. (i.e. increment values are in pixel) +// depending on the texture scale it doesn't take the same amount of pixels to move of GetGridSize() +// increment * scale = gridsize +// hscale and vscale are optional parameters, if they are zero they will be set to the default scale +// NOTE: the default scale depends if you are using BP mode or regular. +// For regular it's 0.5f (128 pixels cover 64 world units), for BP it's simply 1.0f +// see fenris #2810 +void DoSnapTToGrid(float hscale, float vscale) +{ + g_si_globals.shift[0] = static_cast(float_to_integer(static_cast(GetGridSize()) / hscale)); + g_si_globals.shift[1] = static_cast(float_to_integer(static_cast(GetGridSize()) / vscale)); + getSurfaceInspector().queueDraw(); +} + +void SurfaceInspector_GridChange() +{ + if (g_si_globals.m_bSnapTToGrid) + DoSnapTToGrid(Texdef_getDefaultTextureScale(), Texdef_getDefaultTextureScale()); +} + +// make the shift increments match the grid settings +// the objective being that the shift+arrows shortcuts move the texture by the corresponding grid size +// this depends on the current texture scale used? +// we move the textures in pixels, not world units. (i.e. increment values are in pixel) +// depending on the texture scale it doesn't take the same amount of pixels to move of GetGridSize() +// increment * scale = gridsize +static void OnBtnMatchGrid(GtkWidget *widget, gpointer data) +{ + float hscale, vscale; + hscale = static_cast(gtk_spin_button_get_value_as_float(getSurfaceInspector().m_hscaleIncrement.m_spin)); + vscale = static_cast(gtk_spin_button_get_value_as_float(getSurfaceInspector().m_vscaleIncrement.m_spin)); + + if (hscale == 0.0f || vscale == 0.0f) + { + globalOutputStream() << "ERROR: unexpected scale == 0.0f\n"; + return; + } + + DoSnapTToGrid (hscale, vscale); +} + +// DoSurface will always try to show the surface inspector +// or update it because something new has been selected +// Shamus: It does get called when the SI is hidden, but not when you select something new. ;-) +void DoSurface (void) +{ + if(getSurfaceInspector().GetWidget() == 0) + { + getSurfaceInspector().Create(); + + } + getSurfaceInspector().Update(); + getSurfaceInspector().importData(); + getSurfaceInspector().ShowDlg(); +} + +void SurfaceInspector_toggleShown() +{ + if (getSurfaceInspector().visible()) + { + getSurfaceInspector().HideDlg(); + } + else + { + DoSurface(); + } +} + +void SurfaceInspector_FitTexture() +{ + UndoableCommand undo("textureAutoFit"); + Select_FitTexture(getSurfaceInspector().m_fitHorizontal, getSurfaceInspector().m_fitVertical); +} + +static void OnBtnPatchdetails(GtkWidget *widget, gpointer data) +{ + Scene_PatchCapTexture_Selected(GlobalSceneGraph()); +} + +static void OnBtnPatchnatural(GtkWidget *widget, gpointer data) +{ + Scene_PatchNaturalTexture_Selected(GlobalSceneGraph()); +} + +static void OnBtnPatchreset(GtkWidget *widget, gpointer data) +{ + float fx, fy; + + if (DoTextureLayout (&fx, &fy) == eIDOK) + { + Scene_PatchTileTexture_Selected(GlobalSceneGraph(), fx, fy); + } +} + +static void OnBtnPatchFit(GtkWidget *widget, gpointer data) +{ + Scene_PatchTileTexture_Selected(GlobalSceneGraph(), 1, 1); +} + +static void OnBtnAxial(GtkWidget *widget, gpointer data) +{ +//globalOutputStream() << "--> [OnBtnAxial]...\n"; + UndoableCommand undo("textureDefault"); + TextureProjection projection; +//globalOutputStream() << " TexDef_Construct_Default()...\n"; + TexDef_Construct_Default(projection); +//globalOutputStream() << " Select_SetTexdef()...\n"; + +#if TEXTOOL_ENABLED + + //Shamus: + if (g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) + { + // Scale up texture width/height if in BP mode... +//NOTE: This may not be correct any more! :-P + if (!g_SelectedFaceInstances.empty()) + { + Face & face = g_SelectedFaceInstances.last().getFace(); + float x = face.getShader().m_state->getTexture().width; + float y = face.getShader().m_state->getTexture().height; + projection.m_brushprimit_texdef.coords[0][0] /= x; + projection.m_brushprimit_texdef.coords[0][1] /= y; + projection.m_brushprimit_texdef.coords[1][0] /= x; + projection.m_brushprimit_texdef.coords[1][1] /= y; + } + } +#endif + + Select_SetTexdef(projection); +} + +static void OnBtnFaceFit(GtkWidget *widget, gpointer data) +{ + getSurfaceInspector().exportData(); + SurfaceInspector_FitTexture(); +} + +typedef const char* FlagName; + +const FlagName surfaceflagNamesDefault[32] = { + "surf1", + "surf2", + "surf3", + "surf4", + "surf5", + "surf6", + "surf7", + "surf8", + "surf9", + "surf10", + "surf11", + "surf12", + "surf13", + "surf14", + "surf15", + "surf16", + "surf17", + "surf18", + "surf19", + "surf20", + "surf21", + "surf22", + "surf23", + "surf24", + "surf25", + "surf26", + "surf27", + "surf28", + "surf29", + "surf30", + "surf31", + "surf32" +}; + +const FlagName contentflagNamesDefault[32] = { + "cont1", + "cont2", + "cont3", + "cont4", + "cont5", + "cont6", + "cont7", + "cont8", + "cont9", + "cont10", + "cont11", + "cont12", + "cont13", + "cont14", + "cont15", + "cont16", + "cont17", + "cont18", + "cont19", + "cont20", + "cont21", + "cont22", + "cont23", + "cont24", + "cont25", + "cont26", + "cont27", + "cont28", + "cont29", + "cont30", + "cont31", + "cont32" +}; + +const char* getSurfaceFlagName(std::size_t bit) +{ + const char* value = g_pGameDescription->getKeyValue(surfaceflagNamesDefault[bit]); + if(string_empty(value)) + { + return surfaceflagNamesDefault[bit]; + } + return value; +} + +const char* getContentFlagName(std::size_t bit) +{ + const char* value = g_pGameDescription->getKeyValue(contentflagNamesDefault[bit]); + if(string_empty(value)) + { + return contentflagNamesDefault[bit]; + } + return value; +} + + +// ============================================================================= +// SurfaceInspector class + +guint togglebutton_connect_toggled(GtkToggleButton* button, const Callback& callback) +{ + return g_signal_connect_swapped(G_OBJECT(button), "toggled", G_CALLBACK(callback.getThunk()), callback.getEnvironment()); +} + +GtkWindow* SurfaceInspector::BuildDialog() +{ + GtkWindow* window = create_floating_window("Surface Inspector", m_parent); + + m_positionTracker.connect(window); + + global_accel_connect_window(window); + + window_connect_focus_in_clear_focus_widget(window); + + + { + // replaced by only the vbox: + GtkWidget* vbox = gtk_vbox_new (FALSE, 5); + gtk_widget_show (vbox); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(vbox)); + gtk_container_set_border_width (GTK_CONTAINER (vbox), 5); + + { + GtkWidget* hbox2 = gtk_hbox_new (FALSE, 5); + gtk_widget_show (hbox2); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox2), FALSE, FALSE, 0); + + { + GtkWidget* label = gtk_label_new ("Texture"); + gtk_widget_show (label); + gtk_box_pack_start (GTK_BOX (hbox2), label, FALSE, TRUE, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_box_pack_start(GTK_BOX(hbox2), GTK_WIDGET(entry), TRUE, TRUE, 0); + m_texture = entry; + m_textureEntry.connect(entry); + GlobalTextureEntryCompletion::instance().connect(entry); + } + } + + + { + GtkWidget* table = gtk_table_new (6, 4, FALSE); + gtk_widget_show (table); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(table), FALSE, FALSE, 0); + gtk_table_set_row_spacings(GTK_TABLE(table), 5); + gtk_table_set_col_spacings(GTK_TABLE(table), 5); + { + GtkWidget* label = gtk_label_new ("Horizontal shift"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 2)); + m_hshiftIncrement.m_spin = spin; + m_hshiftSpinner.connect(spin); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach (GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); + } + { + GtkWidget* label = gtk_label_new ("Step"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 0, 1, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + m_hshiftIncrement.m_entry = entry; + m_hshiftEntry.connect(entry); + } + { + GtkWidget* label = gtk_label_new ("Vertical shift"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 2)); + m_vshiftIncrement.m_spin = spin; + m_vshiftSpinner.connect(spin); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); + } + { + GtkWidget* label = gtk_label_new ("Step"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 1, 2, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + m_vshiftIncrement.m_entry = entry; + m_vshiftEntry.connect(entry); + } + { + GtkWidget* label = gtk_label_new ("Horizontal stretch"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 5)); + m_hscaleIncrement.m_spin = spin; + m_hscaleSpinner.connect(spin); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); + } + { + GtkWidget* label = gtk_label_new ("Step"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 2, 3); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 2, 3); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + m_hscaleIncrement.m_entry = entry; + m_hscaleEntry.connect(entry); + } + { + GtkWidget* label = gtk_label_new ("Vertical stretch"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 3, 4, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 5)); + m_vscaleIncrement.m_spin = spin; + m_vscaleSpinner.connect(spin); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 3, 4, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); + } + { + GtkWidget* label = gtk_label_new ("Step"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 3, 4, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 3, 4, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + m_vscaleIncrement.m_entry = entry; + m_vscaleEntry.connect(entry); + } + { + GtkWidget* label = gtk_label_new ("Rotate"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 4, 5, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkSpinButton* spin = GTK_SPIN_BUTTON(gtk_spin_button_new(GTK_ADJUSTMENT(gtk_adjustment_new(0, -8192, 8192, 2, 8, 0)), 0, 2)); + m_rotateIncrement.m_spin = spin; + m_rotateSpinner.connect(spin); + gtk_widget_show(GTK_WIDGET(spin)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(spin), 1, 2, 4, 5, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(spin), 60, -2); + gtk_spin_button_set_wrap(spin, TRUE); + } + { + GtkWidget* label = gtk_label_new ("Step"); + gtk_widget_show (label); + gtk_misc_set_alignment (GTK_MISC (label), 0, 0); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 4, 5, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_table_attach(GTK_TABLE(table), GTK_WIDGET(entry), 3, 4, 4, 5, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize(GTK_WIDGET(entry), 50, -2); + m_rotateIncrement.m_entry = entry; + m_rotateEntry.connect(entry); + } + { + // match grid button + GtkWidget* button = gtk_button_new_with_label ("Match Grid"); + gtk_widget_show (button); + gtk_table_attach(GTK_TABLE(table), button, 2, 4, 5, 6, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(button), "clicked", G_CALLBACK(OnBtnMatchGrid), 0); + } + } + + { + GtkWidget* frame = gtk_frame_new ("Texturing"); + gtk_widget_show (frame); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), FALSE, FALSE, 0); + { + GtkWidget* table = gtk_table_new (4, 4, FALSE); + gtk_widget_show (table); + gtk_container_add (GTK_CONTAINER (frame), table); + gtk_table_set_row_spacings(GTK_TABLE(table), 5); + gtk_table_set_col_spacings(GTK_TABLE(table), 5); + gtk_container_set_border_width (GTK_CONTAINER (table), 5); + { + GtkWidget* label = gtk_label_new ("Brush"); + gtk_widget_show (label); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new ("Patch"); + gtk_widget_show (label); + gtk_table_attach(GTK_TABLE(table), label, 0, 1, 2, 3, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new ("Width"); + gtk_widget_show (label); + gtk_table_attach(GTK_TABLE(table), label, 2, 3, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* label = gtk_label_new ("Height"); + gtk_widget_show (label); + gtk_table_attach(GTK_TABLE(table), label, 3, 4, 0, 1, + (GtkAttachOptions) (GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + } + { + GtkWidget* button = gtk_button_new_with_label ("Axial"); + gtk_widget_show (button); + gtk_table_attach(GTK_TABLE(table), button, 0, 1, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnBtnAxial), 0); + gtk_widget_set_usize (button, 60, -2); + } + { + GtkWidget* button = gtk_button_new_with_label ("Fit"); + gtk_widget_show (button); + gtk_table_attach(GTK_TABLE(table), button, 1, 2, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnBtnFaceFit), 0); + gtk_widget_set_usize (button, 60, -2); + } + { + GtkWidget* button = gtk_button_new_with_label ("CAP"); + gtk_widget_show (button); + gtk_table_attach(GTK_TABLE(table), button, 0, 1, 3, 4, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnBtnPatchdetails), 0); + gtk_widget_set_usize (button, 60, -2); + } + { + GtkWidget* button = gtk_button_new_with_label ("Set..."); + gtk_widget_show (button); + gtk_table_attach(GTK_TABLE(table), button, 1, 2, 3, 4, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnBtnPatchreset), 0); + gtk_widget_set_usize (button, 60, -2); + } + { + GtkWidget* button = gtk_button_new_with_label ("Natural"); + gtk_widget_show (button); + gtk_table_attach(GTK_TABLE(table), button, 2, 3, 3, 4, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnBtnPatchnatural), 0); + gtk_widget_set_usize (button, 60, -2); + } + { + GtkWidget* button = gtk_button_new_with_label ("Fit"); + gtk_widget_show (button); + gtk_table_attach(GTK_TABLE(table), button, 3, 4, 3, 4, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + g_signal_connect(G_OBJECT(button), "clicked", + G_CALLBACK(OnBtnPatchFit), 0); + gtk_widget_set_usize (button, 60, -2); + } + { + GtkWidget* spin = gtk_spin_button_new (GTK_ADJUSTMENT (gtk_adjustment_new (1, 0, 1 << 16, 1, 10, 0)), 0, 6); + gtk_widget_show (spin); + gtk_table_attach(GTK_TABLE(table), spin, 2, 3, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize (spin, 60, -2); + AddDialogData(*GTK_SPIN_BUTTON(spin), m_fitHorizontal); + } + { + GtkWidget* spin = gtk_spin_button_new (GTK_ADJUSTMENT (gtk_adjustment_new (1, 0, 1 << 16, 1, 10, 0)), 0, 6); + gtk_widget_show (spin); + gtk_table_attach(GTK_TABLE(table), spin, 3, 4, 1, 2, + (GtkAttachOptions) (GTK_EXPAND | GTK_FILL), + (GtkAttachOptions) (0), 0, 0); + gtk_widget_set_usize (spin, 60, -2); + AddDialogData(*GTK_SPIN_BUTTON(spin), m_fitVertical); + } + } + } + if(!string_empty(g_pGameDescription->getKeyValue("si_flags"))) + { + { + GtkFrame* frame = GTK_FRAME(gtk_frame_new("Surface Flags")); + gtk_widget_show(GTK_WIDGET(frame)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); + { + GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 4)); + //gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); + gtk_widget_show(GTK_WIDGET(vbox3)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); + { + GtkTable* table = GTK_TABLE(gtk_table_new(8, 4, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings(table, 0); + gtk_table_set_col_spacings(table, 0); + + GtkCheckButton** p = m_surfaceFlags; + + for(int c = 0; c != 4; ++c) + { + for(int r = 0; r != 8; ++r) + { + GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new_with_label(getSurfaceFlagName(c * 8 + r))); + gtk_widget_show(GTK_WIDGET(check)); + gtk_table_attach(table, GTK_WIDGET(check), c, c+1, r, r+1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + *p++ = check; + guint handler_id = togglebutton_connect_toggled(GTK_TOGGLE_BUTTON(check), ApplyFlagsCaller(*this)); + g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler_id)); + } + } + } + } + } + { + GtkFrame* frame = GTK_FRAME(gtk_frame_new("Content Flags")); + gtk_widget_show(GTK_WIDGET(frame)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); + { + GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 4)); + //gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); + gtk_widget_show(GTK_WIDGET(vbox3)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); + { + + GtkTable* table = GTK_TABLE(gtk_table_new(8, 4, FALSE)); + gtk_widget_show(GTK_WIDGET(table)); + gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(table), TRUE, TRUE, 0); + gtk_table_set_row_spacings(table, 0); + gtk_table_set_col_spacings(table, 0); + + GtkCheckButton** p = m_contentFlags; + + for(int c = 0; c != 4; ++c) + { + for(int r = 0; r != 8; ++r) + { + GtkCheckButton* check = GTK_CHECK_BUTTON(gtk_check_button_new_with_label(getContentFlagName(c * 8 + r))); + gtk_widget_show(GTK_WIDGET(check)); + gtk_table_attach(table, GTK_WIDGET(check), c, c+1, r, r+1, + (GtkAttachOptions)(GTK_EXPAND | GTK_FILL), + (GtkAttachOptions)(0), 0, 0); + *p++ = check; + guint handler_id = togglebutton_connect_toggled(GTK_TOGGLE_BUTTON(check), ApplyFlagsCaller(*this)); + g_object_set_data(G_OBJECT(check), "handler", gint_to_pointer(handler_id)); + } + } + + // not allowed to modify detail flag using Surface Inspector + gtk_widget_set_sensitive(GTK_WIDGET(m_contentFlags[BRUSH_DETAIL_FLAG]), FALSE); + } + } + } + { + GtkFrame* frame = GTK_FRAME(gtk_frame_new("Value")); + gtk_widget_show(GTK_WIDGET(frame)); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), TRUE, TRUE, 0); + { + GtkVBox* vbox3 = GTK_VBOX(gtk_vbox_new(FALSE, 4)); + gtk_container_set_border_width(GTK_CONTAINER(vbox3), 4); + gtk_widget_show(GTK_WIDGET(vbox3)); + gtk_container_add(GTK_CONTAINER(frame), GTK_WIDGET(vbox3)); + + { + GtkEntry* entry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_show(GTK_WIDGET(entry)); + gtk_box_pack_start(GTK_BOX(vbox3), GTK_WIDGET(entry), TRUE, TRUE, 0); + m_valueEntryWidget = entry; + m_valueEntry.connect(entry); + } + } + } + } + +#if TEXTOOL_ENABLED + if(g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES) +// Shamus: Textool goodies... + { + GtkWidget * frame = gtk_frame_new("Textool"); + gtk_widget_show(frame); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(frame), FALSE, FALSE, 0); + { + //Prolly should make this a member or global var, so the SI can draw on it... + TexTool::g_textoolWin = glwidget_new(FALSE); + // --> Dunno, but this stuff may be necessary... (Looks like it!) + gtk_widget_ref(TexTool::g_textoolWin); + gtk_widget_set_events(TexTool::g_textoolWin, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK); + GTK_WIDGET_SET_FLAGS(TexTool::g_textoolWin, GTK_CAN_FOCUS); + // <-- end stuff... + gtk_widget_show(TexTool::g_textoolWin); + gtk_widget_set_usize(TexTool::g_textoolWin, -1, 240); //Yeah! + gtk_container_add(GTK_CONTAINER(frame), TexTool::g_textoolWin); + + g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "size_allocate", G_CALLBACK(TexTool::size_allocate), NULL); + g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "expose_event", G_CALLBACK(TexTool::expose), NULL); + g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "button_press_event", G_CALLBACK(TexTool::button_press), NULL); + g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "button_release_event", G_CALLBACK(TexTool::button_release), NULL); + g_signal_connect(G_OBJECT(TexTool::g_textoolWin), "motion_notify_event", G_CALLBACK(TexTool::motion), NULL); + } + { + GtkWidget * hbox = gtk_hbox_new(FALSE, 5); + gtk_widget_show(hbox); + gtk_box_pack_start(GTK_BOX(vbox), GTK_WIDGET(hbox), FALSE, FALSE, 0); + // Checkboxes go here... (Flip X/Y) + GtkWidget * flipX = gtk_check_button_new_with_label("Flip X axis"); + GtkWidget * flipY = gtk_check_button_new_with_label("Flip Y axis"); + gtk_widget_show(flipX); + gtk_widget_show(flipY); + gtk_box_pack_start(GTK_BOX(hbox), flipX, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(hbox), flipY, FALSE, FALSE, 0); + +//Instead of this, we probably need to create a vbox to put into the frame, then the +//window, then the hbox. !!! FIX !!! +// gtk_container_add(GTK_CONTAINER(frame), hbox); + +//Hmm. Do we really need g_object_set_data? Mebbe not... And we don't! :-) +// g_object_set_data(G_OBJECT(flipX), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(flipX), "toggled", G_CALLBACK(TexTool::flipX), 0))); +// g_object_set_data(G_OBJECT(flipY), "handler", gint_to_pointer(g_signal_connect(G_OBJECT(flipY), "toggled", G_CALLBACK(TexTool::flipY), 0))); +//Instead, just do: + g_signal_connect(G_OBJECT(flipX), "toggled", G_CALLBACK(TexTool::flipX), NULL); + g_signal_connect(G_OBJECT(flipY), "toggled", G_CALLBACK(TexTool::flipY), NULL); + } + } +#endif + } + + return window; +} + +/* +============== +Update + +Set the fields to the current texdef (i.e. map/texdef -> dialog widgets) +if faces selected (instead of brushes) -> will read this face texdef, else current texdef +if only patches selected, will read the patch texdef +=============== +*/ + +void spin_button_set_value_no_signal(GtkSpinButton* spin, gdouble value) +{ + guint handler_id = gpointer_to_int(g_object_get_data(G_OBJECT(spin), "handler")); + g_signal_handler_block(G_OBJECT(gtk_spin_button_get_adjustment(spin)), handler_id); + gtk_spin_button_set_value(spin, value); + g_signal_handler_unblock(G_OBJECT(gtk_spin_button_get_adjustment(spin)), handler_id); +} + +void spin_button_set_step_increment(GtkSpinButton* spin, gdouble value) +{ + GtkAdjustment* adjust = gtk_spin_button_get_adjustment(spin); + adjust->step_increment = value; +} + +void SurfaceInspector::Update() +{ + const char * name = SurfaceInspector_GetSelectedShader(); + + if(shader_is_texture(name)) + { + gtk_entry_set_text(m_texture, shader_get_textureName(name)); + } + else + { + gtk_entry_set_text(m_texture, ""); + } + + texdef_t shiftScaleRotate; +//Shamus: This is where we get into trouble--the BP code tries to convert to a "faked" +//shift, rotate & scale values from the brush face, which seems to screw up for some reason. +//!!! FIX !!! +/*globalOutputStream() << "--> SI::Update. About to do ShiftScaleRotate_fromFace()...\n"; +SurfaceInspector_GetSelectedBPTexdef(); +globalOutputStream() << "BP: (" << g_selectedBrushPrimitTexdef.coords[0][0] << ", " << g_selectedBrushPrimitTexdef.coords[0][1] << ")(" + << g_selectedBrushPrimitTexdef.coords[1][0] << ", " << g_selectedBrushPrimitTexdef.coords[1][1] << ")(" + << g_selectedBrushPrimitTexdef.coords[0][2] << ", " << g_selectedBrushPrimitTexdef.coords[1][2] << ") SurfaceInspector::Update\n";//*/ +//Ok, it's screwed up *before* we get here... + ShiftScaleRotate_fromFace(shiftScaleRotate, SurfaceInspector_GetSelectedTexdef()); + + // normalize again to hide the ridiculously high scale values that get created when using texlock + shiftScaleRotate.shift[0] = float_mod(shiftScaleRotate.shift[0], (float)g_selectedShaderSize[0]); + shiftScaleRotate.shift[1] = float_mod(shiftScaleRotate.shift[1], (float)g_selectedShaderSize[1]); + + { + spin_button_set_value_no_signal(m_hshiftIncrement.m_spin, shiftScaleRotate.shift[0]); + spin_button_set_step_increment(m_hshiftIncrement.m_spin, g_si_globals.shift[0]); + entry_set_float(m_hshiftIncrement.m_entry, g_si_globals.shift[0]); + } + + { + spin_button_set_value_no_signal(m_vshiftIncrement.m_spin, shiftScaleRotate.shift[1]); + spin_button_set_step_increment(m_vshiftIncrement.m_spin, g_si_globals.shift[1]); + entry_set_float(m_vshiftIncrement.m_entry, g_si_globals.shift[1]); + } + + { + spin_button_set_value_no_signal(m_hscaleIncrement.m_spin, shiftScaleRotate.scale[0]); + spin_button_set_step_increment(m_hscaleIncrement.m_spin, g_si_globals.scale[0]); + entry_set_float(m_hscaleIncrement.m_entry, g_si_globals.scale[0]); + } + + { + spin_button_set_value_no_signal(m_vscaleIncrement.m_spin, shiftScaleRotate.scale[1]); + spin_button_set_step_increment(m_vscaleIncrement.m_spin, g_si_globals.scale[1]); + entry_set_float(m_vscaleIncrement.m_entry, g_si_globals.scale[1]); + } + + { + spin_button_set_value_no_signal(m_rotateIncrement.m_spin, shiftScaleRotate.rotate); + spin_button_set_step_increment(m_rotateIncrement.m_spin, g_si_globals.rotate); + entry_set_float(m_rotateIncrement.m_entry, g_si_globals.rotate); + } + + if(!string_empty(g_pGameDescription->getKeyValue("si_flags"))) + { + ContentsFlagsValue flags(SurfaceInspector_GetSelectedFlags()); + + entry_set_int(m_valueEntryWidget, flags.m_value); + + for(GtkCheckButton** p = m_surfaceFlags; p != m_surfaceFlags + 32; ++p) + { + toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(*p), flags.m_surfaceFlags & (1 << (p - m_surfaceFlags))); + } + + for(GtkCheckButton** p = m_contentFlags; p != m_contentFlags + 32; ++p) + { + toggle_button_set_active_no_signal(GTK_TOGGLE_BUTTON(*p), flags.m_contentFlags & (1 << (p - m_contentFlags))); + } + } +} + +/* +============== +Apply + +Reads the fields to get the current texdef (i.e. widgets -> MAP) +in brush primitive mode, grab the fake shift scale rot and compute a new texture matrix +=============== +*/ +void SurfaceInspector::ApplyShader() +{ + StringOutputStream name(256); + name << GlobalTexturePrefix_get() << gtk_entry_get_text(m_texture); + + // TTimo: detect and refuse invalid texture names (at least the ones with spaces) + if(!texdef_name_valid(name.c_str())) + { + globalErrorStream() << "invalid texture name '" << name.c_str() << "'\n"; + SurfaceInspector_queueDraw(); + return; + } + + UndoableCommand undo("textureNameSetSelected"); + Select_SetShader(name.c_str()); +} + +void SurfaceInspector::ApplyTexdef() +{ + texdef_t shiftScaleRotate; + + shiftScaleRotate.shift[0] = static_cast(gtk_spin_button_get_value_as_float(m_hshiftIncrement.m_spin)); + shiftScaleRotate.shift[1] = static_cast(gtk_spin_button_get_value_as_float(m_vshiftIncrement.m_spin)); + shiftScaleRotate.scale[0] = static_cast(gtk_spin_button_get_value_as_float(m_hscaleIncrement.m_spin)); + shiftScaleRotate.scale[1] = static_cast(gtk_spin_button_get_value_as_float(m_vscaleIncrement.m_spin)); + shiftScaleRotate.rotate = static_cast(gtk_spin_button_get_value_as_float(m_rotateIncrement.m_spin)); + + TextureProjection projection; +//Shamus: This is the other place that screws up, it seems, since it doesn't seem to do the +//conversion from the face (I think) and so bogus values end up in the thing... !!! FIX !!! +//This is actually OK. :-P + ShiftScaleRotate_toFace(shiftScaleRotate, projection); + + UndoableCommand undo("textureProjectionSetSelected"); + Select_SetTexdef(projection); +} + +void SurfaceInspector::ApplyFlags() +{ + unsigned int surfaceflags = 0; + for(GtkCheckButton** p = m_surfaceFlags; p != m_surfaceFlags + 32; ++p) + { + if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(*p))) + { + surfaceflags |= (1 << (p - m_surfaceFlags)); + } + } + + unsigned int contentflags = 0; + for(GtkCheckButton** p = m_contentFlags; p != m_contentFlags + 32; ++p) + { + if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(*p))) + { + contentflags |= (1 << (p - m_contentFlags)); + } + } + + int value = entry_get_int(m_valueEntryWidget); + + UndoableCommand undo("flagsSetSelected"); + Select_SetFlags(ContentsFlagsValue(surfaceflags, contentflags, value, true)); +} + + +void Face_getTexture(Face& face, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags) +{ + shader = face.GetShader(); + face.GetTexdef(projection); + flags = face.getShader().m_flags; +} +typedef Function4 FaceGetTexture; + +void Face_setTexture(Face& face, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags) +{ + face.SetShader(shader); + face.SetTexdef(projection); + face.SetFlags(flags); +} +typedef Function4 FaceSetTexture; + + +void Patch_getTexture(Patch& patch, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags) +{ + shader = patch.GetShader(); + projection = TextureProjection(texdef_t(), brushprimit_texdef_t(), Vector3(0, 0, 0), Vector3(0, 0, 0)); + flags = ContentsFlagsValue(0, 0, 0, false); +} +typedef Function4 PatchGetTexture; + +void Patch_setTexture(Patch& patch, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags) +{ + patch.SetShader(shader); +} +typedef Function4 PatchSetTexture; + + +typedef Callback3 GetTextureCallback; +typedef Callback3 SetTextureCallback; + +struct Texturable +{ + GetTextureCallback getTexture; + SetTextureCallback setTexture; +}; + + +void Face_getClosest(Face& face, SelectionTest& test, SelectionIntersection& bestIntersection, Texturable& texturable) +{ + SelectionIntersection intersection; + face.testSelect(test, intersection); + if(intersection.valid() + && SelectionIntersection_closer(intersection, bestIntersection)) + { + bestIntersection = intersection; + texturable.setTexture = makeCallback3(FaceSetTexture(), face); + texturable.getTexture = makeCallback3(FaceGetTexture(), face); + } +} + + +class OccludeSelector : public Selector +{ + SelectionIntersection& m_bestIntersection; + bool& m_occluded; +public: + OccludeSelector(SelectionIntersection& bestIntersection, bool& occluded) : m_bestIntersection(bestIntersection), m_occluded(occluded) + { + m_occluded = false; + } + void pushSelectable(Selectable& selectable) + { + } + void popSelectable() + { + } + void addIntersection(const SelectionIntersection& intersection) + { + if(SelectionIntersection_closer(intersection, m_bestIntersection)) + { + m_bestIntersection = intersection; + m_occluded = true; + } + } +}; + +class BrushGetClosestFaceVisibleWalker : public scene::Graph::Walker +{ + SelectionTest& m_test; + Texturable& m_texturable; + mutable SelectionIntersection m_bestIntersection; +public: + BrushGetClosestFaceVisibleWalker(SelectionTest& test, Texturable& texturable) : m_test(test), m_texturable(texturable) + { + } + bool pre(const scene::Path& path, scene::Instance& instance) const + { + if(path.top().get().visible()) + { + BrushInstance* brush = Instance_getBrush(instance); + if(brush != 0) + { + m_test.BeginMesh(brush->localToWorld()); + + for(Brush::const_iterator i = brush->getBrush().begin(); i != brush->getBrush().end(); ++i) + { + Face_getClosest(*(*i), m_test, m_bestIntersection, m_texturable); + } + } + else + { + SelectionTestable* selectionTestable = Instance_getSelectionTestable(instance); + if(selectionTestable) + { + bool occluded; + OccludeSelector selector(m_bestIntersection, occluded); + selectionTestable->testSelect(selector, m_test); + if(occluded) + { + Patch* patch = Node_getPatch(path.top()); + if(patch != 0) + { + m_texturable.setTexture = makeCallback3(PatchSetTexture(), *patch); + m_texturable.getTexture = makeCallback3(PatchGetTexture(), *patch); + } + else + { + m_texturable = Texturable(); + } + } + } + } + } + return true; + } +}; + +Texturable Scene_getClosestTexturable(scene::Graph& graph, SelectionTest& test) +{ + Texturable texturable; + graph.traverse(BrushGetClosestFaceVisibleWalker(test, texturable)); + return texturable; +} + +bool Scene_getClosestTexture(scene::Graph& graph, SelectionTest& test, CopiedString& shader, TextureProjection& projection, ContentsFlagsValue& flags) +{ + Texturable texturable = Scene_getClosestTexturable(graph, test); + if(texturable.getTexture != GetTextureCallback()) + { + texturable.getTexture(shader, projection, flags); + return true; + } + return false; +} + +void Scene_setClosestTexture(scene::Graph& graph, SelectionTest& test, const char* shader, const TextureProjection& projection, const ContentsFlagsValue& flags) +{ + Texturable texturable = Scene_getClosestTexturable(graph, test); + if(texturable.setTexture != SetTextureCallback()) + { + texturable.setTexture(shader, projection, flags); + } +} + + +class FaceTexture +{ +public: + TextureProjection m_projection; + ContentsFlagsValue m_flags; +}; + +FaceTexture g_faceTextureClipboard; + +void FaceTextureClipboard_setDefault() +{ + g_faceTextureClipboard.m_flags = ContentsFlagsValue(0, 0, 0, false); + TexDef_Construct_Default(g_faceTextureClipboard.m_projection); +} + +void TextureClipboard_textureSelected(const char* shader) +{ + FaceTextureClipboard_setDefault(); +} + +class TextureBrowser; +extern TextureBrowser g_TextureBrowser; +void TextureBrowser_SetSelectedShader(TextureBrowser& textureBrowser, const char* shader); +const char* TextureBrowser_GetSelectedShader(TextureBrowser& textureBrowser); + +void Scene_copyClosestTexture(SelectionTest& test) +{ + CopiedString shader; + if(Scene_getClosestTexture(GlobalSceneGraph(), test, shader, g_faceTextureClipboard.m_projection, g_faceTextureClipboard.m_flags)) + { + TextureBrowser_SetSelectedShader(g_TextureBrowser, shader.c_str()); + } +} + +void Scene_applyClosestTexture(SelectionTest& test) +{ + UndoableCommand command("facePaintTexture"); + + Scene_setClosestTexture(GlobalSceneGraph(), test, TextureBrowser_GetSelectedShader(g_TextureBrowser), g_faceTextureClipboard.m_projection, g_faceTextureClipboard.m_flags); + + SceneChangeNotify(); +} + + + + + +void SelectedFaces_copyTexture() +{ + if(!g_SelectedFaceInstances.empty()) + { + Face& face = g_SelectedFaceInstances.last().getFace(); + face.GetTexdef(g_faceTextureClipboard.m_projection); + g_faceTextureClipboard.m_flags = face.getShader().m_flags; + + TextureBrowser_SetSelectedShader(g_TextureBrowser, face.getShader().getShader()); + } +} + +void FaceInstance_pasteTexture(FaceInstance& faceInstance) +{ + faceInstance.getFace().SetTexdef(g_faceTextureClipboard.m_projection); + faceInstance.getFace().SetShader(TextureBrowser_GetSelectedShader(g_TextureBrowser)); + faceInstance.getFace().SetFlags(g_faceTextureClipboard.m_flags); + SceneChangeNotify(); +} + +bool SelectedFaces_empty() +{ + return g_SelectedFaceInstances.empty(); +} + +void SelectedFaces_pasteTexture() +{ + UndoableCommand command("facePasteTexture"); + g_SelectedFaceInstances.foreach(FaceInstance_pasteTexture); +} + + + +void SurfaceInspector_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox("", "Surface Inspector Increments Match Grid", g_si_globals.m_bSnapTToGrid); +} +void SurfaceInspector_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Surface Inspector", "Surface Inspector Preferences")); + SurfaceInspector_constructPreferences(page); +} +void SurfaceInspector_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + +void SurfaceInspector_registerCommands() +{ + GlobalCommands_insert("FitTexture", FreeCaller(), Accelerator('B', (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("SurfaceInspector", FreeCaller(), Accelerator('S')); + + GlobalCommands_insert("FaceCopyTexture", FreeCaller()); + GlobalCommands_insert("FacePasteTexture", FreeCaller()); +} + + +#include "preferencesystem.h" + + +void SurfaceInspector_Construct() +{ + g_SurfaceInspector = new SurfaceInspector; + + SurfaceInspector_registerCommands(); + + FaceTextureClipboard_setDefault(); + + GlobalPreferenceSystem().registerPreference("SurfaceWnd", getSurfaceInspector().m_importPosition, getSurfaceInspector().m_exportPosition); + GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Scale1", FloatImportStringCaller(g_si_globals.scale[0]), FloatExportStringCaller(g_si_globals.scale[0])); + GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Scale2", FloatImportStringCaller(g_si_globals.scale[1]), FloatExportStringCaller(g_si_globals.scale[1])); + GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Shift1", FloatImportStringCaller(g_si_globals.shift[0]), FloatExportStringCaller(g_si_globals.shift[0])); + GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Shift2", FloatImportStringCaller(g_si_globals.shift[1]), FloatExportStringCaller(g_si_globals.shift[1])); + GlobalPreferenceSystem().registerPreference("SI_SurfaceTexdef_Rotate", FloatImportStringCaller(g_si_globals.rotate), FloatExportStringCaller(g_si_globals.rotate)); + GlobalPreferenceSystem().registerPreference("SnapTToGrid", BoolImportStringCaller(g_si_globals.m_bSnapTToGrid), BoolExportStringCaller(g_si_globals.m_bSnapTToGrid)); + + typedef FreeCaller1 SurfaceInspectorSelectionChangedCaller; + GlobalSelectionSystem().addSelectionChangeCallback(SurfaceInspectorSelectionChangedCaller()); + typedef FreeCaller SurfaceInspectorUpdateSelectionCaller; + Brush_addTextureChangedCallback(SurfaceInspectorUpdateSelectionCaller()); + Patch_addTextureChangedCallback(SurfaceInspectorUpdateSelectionCaller()); + + SurfaceInspector_registerPreferencesPage(); +} +void SurfaceInspector_Destroy() +{ + delete g_SurfaceInspector; +} + + + +#if TEXTOOL_ENABLED + +namespace TexTool { // namespace hides these symbols from other object-files +// +//Shamus: Textool functions, including GTK+ callbacks +// + +//NOTE: Black screen when TT first comes up is caused by an uninitialized Extent... !!! FIX !!! +// But... You can see down below that it *is* initialized! WTF? +struct Extent +{ + float minX, minY, maxX, maxY; + float width(void) { return fabs(maxX - minX); } + float height(void) { return fabs(maxY - minY); } +}; + +//This seems to control the texture scale... (Yep! ;-) +Extent extents = { -2.0f, -2.0f, +2.0f, +2.0f }; +brushprimit_texdef_t tm; // Texture transform matrix +Vector2 pts[c_brush_maxFaces]; +Vector2 center; +int numPts; +int textureNum; +Vector2 textureSize; +Vector2 windowSize; +#define VP_PADDING 1.2 +#define PI 3.14159265358979 +bool lButtonDown = false; +bool rButtonDown = false; +//int dragPoint; +//int anchorPoint; +bool haveAnchor = false; +brushprimit_texdef_t currentBP; +brushprimit_texdef_t origBP; // Original brush primitive (before we muck it up) +float controlRadius = 5.0f; +float rotationAngle = 0.0f; +float rotationAngle2 = 0.0f; +float oldRotationAngle; +Vector2 rotationPoint; +bool translatingX = false; // Widget state variables +bool translatingY = false; +bool scalingX = false; +bool scalingY = false; +bool rotating = false; +bool resizingX = false; // Not sure what this means... :-/ +bool resizingY = false; +float origAngle, origScaleX, origScaleY; +Vector2 oldCenter; + + +// Function prototypes (move up to top later...) + +void DrawCircularArc(Vector2 ctr, float startAngle, float endAngle, float radius); + + +void CopyPointsFromSelectedFace(void) +{ + // Make sure that there's a face and winding to get! + + if (g_SelectedFaceInstances.empty()) + { + numPts = 0; + return; + } + + Face & face = g_SelectedFaceInstances.last().getFace(); + textureNum = face.getShader().m_state->getTexture().texture_number; + textureSize.x() = face.getShader().m_state->getTexture().width; + textureSize.y() = face.getShader().m_state->getTexture().height; +//globalOutputStream() << "--> Texture #" << textureNum << ": " << textureSize.x() << " x " << textureSize.y() << "...\n"; + + currentBP = SurfaceInspector_GetSelectedTexdef().m_brushprimit_texdef; + + face.EmitTextureCoordinates(); + Winding & w = face.getWinding(); + int count = 0; + + for(Winding::const_iterator i=w.begin(); i!=w.end(); i++) + { + //globalOutputStream() << (*i).texcoord.x() << " " << (*i).texcoord.y() << ", "; + pts[count].x() = (*i).texcoord.x(); + pts[count].y() = (*i).texcoord.y(); + count++; + } + + numPts = count; + + //globalOutputStream() << " ..copied points\n"; +} + + brushprimit_texdef_t bp; +//This approach is probably wrongheaded and just not right anyway. So, !!! FIX !!! [DONE] +void CommitChanges(void) +{ + texdef_t t; // Throwaway, since this is BP only + + bp.coords[0][0] = tm.coords[0][0] * origBP.coords[0][0] + tm.coords[0][1] * origBP.coords[1][0]; + bp.coords[0][1] = tm.coords[0][0] * origBP.coords[0][1] + tm.coords[0][1] * origBP.coords[1][1]; + bp.coords[0][2] = tm.coords[0][0] * origBP.coords[0][2] + tm.coords[0][1] * origBP.coords[1][2] + tm.coords[0][2]; +//Ok, this works for translation... +// bp.coords[0][2] = tm.coords[0][0] * origBP.coords[0][2] + tm.coords[0][1] * origBP.coords[1][2] + tm.coords[0][2] * textureSize.x(); + bp.coords[1][0] = tm.coords[1][0] * origBP.coords[0][0] + tm.coords[1][1] * origBP.coords[1][0]; + bp.coords[1][1] = tm.coords[1][0] * origBP.coords[0][1] + tm.coords[1][1] * origBP.coords[1][1]; + bp.coords[1][2] = tm.coords[1][0] * origBP.coords[0][2] + tm.coords[1][1] * origBP.coords[1][2] + tm.coords[1][2]; +// bp.coords[1][2] = tm.coords[1][0] * origBP.coords[0][2] + tm.coords[1][1] * origBP.coords[1][2] + tm.coords[1][2] * textureSize.y(); + +//This doesn't work: g_brush_texture_changed(); +// Let's try this: +//Note: We should only set an undo *after* the button has been released... !!! FIX !!! +//Definitely *should* have an undo, though! +// UndoableCommand undo("textureProjectionSetSelected"); + Select_SetTexdef(TextureProjection(t, bp, Vector3(0, 0, 0), Vector3(0, 0, 0))); +//This is working, but for some reason the translate is causing the rest of the SI +//widgets to yield bad readings... !!! FIX !!! +//I.e., click on textool window, translate face wireframe, then controls go crazy. Dunno why. +//It's because there were some uncommented out add/removeScale functions in brush.h and a +//removeScale in brushmanip.cpp... :-/ +//Translate isn't working at all now... :-( +//It's because we need to multiply in some scaling factor (prolly the texture width/height) +//Yep. :-P +} + +void UpdateControlPoints(void) +{ + CommitChanges(); + + // Init texture transform matrix + + tm.coords[0][0] = 1.0f; tm.coords[0][1] = 0.0f; tm.coords[0][2] = 0.0f; + tm.coords[1][0] = 0.0f; tm.coords[1][1] = 1.0f; tm.coords[1][2] = 0.0f; +} + + +/* +For shifting we have: +*/ +/* +The code that should provide reasonable defaults, but doesn't for some reason: +It's scaling the BP by 128 for some reason, between the time it's created and the +time we get back to the SI widgets: + +static void OnBtnAxial(GtkWidget *widget, gpointer data) +{ + UndoableCommand undo("textureDefault"); + TextureProjection projection; + TexDef_Construct_Default(projection); + Select_SetTexdef(projection); +} + +Select_SetTexdef() calls Scene_BrushSetTexdef_Component_Selected(GlobalSceneGraph(), projection) +which is in brushmanip.h: This eventually calls +Texdef_Assign(m_texdef, texdef, m_brushprimit_texdef, brushprimit_texdef) in class Face... +which just copies from brushpr to m_brushpr... +*/ + +//Small problem with this thing: It's scaled to the texture which is all screwed up... !!! FIX !!! [DONE] +//Prolly should separate out the grid drawing so that we can draw it behind the polygon. +const float gridWidth = 1.3f;// Let's try an absolute height... WORKS!!! +// NOTE that 2.0 is the height of the viewport. Dunno why... Should make collision +// detection easier... +const float gridRadius = gridWidth * 0.5f; + +typedef const float WidgetColor[3]; +const WidgetColor widgetColor[10] = { + { 1.0000f, 0.2000f, 0.0000f }, // Red + { 0.9137f, 0.9765f, 0.4980f }, // Yellow + { 0.0000f, 0.6000f, 0.3216f }, // Green + { 0.6157f, 0.7726f, 0.8196f }, // Cyan + { 0.4980f, 0.5000f, 0.4716f }, // Grey + + // Highlight colors + { 1.0000f, 0.6000f, 0.4000f }, // Light Red + { 1.0000f, 1.0000f, 0.8980f }, // Light Yellow + { 0.4000f, 1.0000f, 0.7216f }, // Light Green + { 1.0000f, 1.0000f, 1.0000f }, // Light Cyan + { 0.8980f, 0.9000f, 0.8716f } // Light Grey +}; + +#define COLOR_RED 0 +#define COLOR_YELLOW 1 +#define COLOR_GREEN 2 +#define COLOR_CYAN 3 +#define COLOR_GREY 4 +#define COLOR_LT_RED 5 +#define COLOR_LT_YELLOW 6 +#define COLOR_LT_GREEN 7 +#define COLOR_LT_CYAN 8 +#define COLOR_LT_GREY 9 + +void DrawControlWidgets(void) +{ +//Note that the grid should go *behind* the face outline... !!! FIX !!! + // Grid + float xStart = center.x() - (gridWidth / 2.0f); + float yStart = center.y() - (gridWidth / 2.0f); + float xScale = (extents.height() / extents.width()) * (textureSize.y() / textureSize.x()); + + glPushMatrix(); +//Small problem with this approach: Changing the center point in the TX code doesn't seem to +//change anything here--prolly because we load a new identity matrix. A couple of ways to fix +//this would be to get rid of that code, or change the center to a new point by taking into +//account the transforms that we toss with the new identity matrix. Dunno which is better. + glLoadIdentity(); + glScalef(xScale, 1.0, 1.0); // Will that square it up? Yup. + glRotatef(static_cast(radians_to_degrees(atan2(-currentBP.coords[0][1], currentBP.coords[0][0]))), 0.0, 0.0, -1.0); + glTranslatef(-center.x(), -center.y(), 0.0); + + // Circle + glColor3fv(translatingX && translatingY ? widgetColor[COLOR_LT_YELLOW] : widgetColor[COLOR_YELLOW]); + glBegin(GL_LINE_LOOP); + DrawCircularArc(center, 0, 2.0f * PI, gridRadius * 0.16); + + glEnd(); + + // Axes + glBegin(GL_LINES); + glColor3fv(translatingY && !translatingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN]); + glVertex2f(center.x(), center.y() + (gridRadius * 0.16)); + glVertex2f(center.x(), center.y() + (gridRadius * 1.00)); + glColor3fv(translatingX && !translatingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED]); + glVertex2f(center.x() + (gridRadius * 0.16), center.y()); + glVertex2f(center.x() + (gridRadius * 1.00), center.y()); + glEnd(); + + // Arrowheads + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + glBegin(GL_TRIANGLES); + glColor3fv(translatingY && !translatingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN]); + glVertex2f(center.x(), center.y() + (gridRadius * 1.10)); + glVertex2f(center.x() + (gridRadius * 0.06), center.y() + (gridRadius * 0.94)); + glVertex2f(center.x() - (gridRadius * 0.06), center.y() + (gridRadius * 0.94)); + glColor3fv(translatingX && !translatingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED]); + glVertex2f(center.x() + (gridRadius * 1.10), center.y()); + glVertex2f(center.x() + (gridRadius * 0.94), center.y() + (gridRadius * 0.06)); + glVertex2f(center.x() + (gridRadius * 0.94), center.y() - (gridRadius * 0.06)); + glEnd(); + + // Arc + glBegin(GL_LINE_STRIP); + glColor3fv(rotating ? widgetColor[COLOR_LT_CYAN] : widgetColor[COLOR_CYAN]); + DrawCircularArc(center, 0.03f * PI, 0.47f * PI, gridRadius * 0.90); + glEnd(); + + // Boxes + glColor3fv(scalingY && !scalingX ? widgetColor[COLOR_LT_GREEN] : widgetColor[COLOR_GREEN]); + glBegin(GL_LINES); + glVertex2f(center.x() + (gridRadius * 0.20), center.y() + (gridRadius * 1.50)); + glVertex2f(center.x() - (gridRadius * 0.20), center.y() + (gridRadius * 1.50)); + glEnd(); + glBegin(GL_LINE_LOOP); + glVertex2f(center.x() + (gridRadius * 0.10), center.y() + (gridRadius * 1.40)); + glVertex2f(center.x() - (gridRadius * 0.10), center.y() + (gridRadius * 1.40)); + glVertex2f(center.x() - (gridRadius * 0.10), center.y() + (gridRadius * 1.20)); + glVertex2f(center.x() + (gridRadius * 0.10), center.y() + (gridRadius * 1.20)); + glEnd(); + + glColor3fv(scalingX && !scalingY ? widgetColor[COLOR_LT_RED] : widgetColor[COLOR_RED]); + glBegin(GL_LINES); + glVertex2f(center.x() + (gridRadius * 1.50), center.y() + (gridRadius * 0.20)); + glVertex2f(center.x() + (gridRadius * 1.50), center.y() - (gridRadius * 0.20)); + glEnd(); + glBegin(GL_LINE_LOOP); + glVertex2f(center.x() + (gridRadius * 1.40), center.y() + (gridRadius * 0.10)); + glVertex2f(center.x() + (gridRadius * 1.40), center.y() - (gridRadius * 0.10)); + glVertex2f(center.x() + (gridRadius * 1.20), center.y() - (gridRadius * 0.10)); + glVertex2f(center.x() + (gridRadius * 1.20), center.y() + (gridRadius * 0.10)); + glEnd(); + + glColor3fv(scalingX && scalingY ? widgetColor[COLOR_LT_CYAN] : widgetColor[COLOR_CYAN]); + glBegin(GL_LINE_STRIP); + glVertex2f(center.x() + (gridRadius * 1.50), center.y() + (gridRadius * 1.10)); + glVertex2f(center.x() + (gridRadius * 1.50), center.y() + (gridRadius * 1.50)); + glVertex2f(center.x() + (gridRadius * 1.10), center.y() + (gridRadius * 1.50)); + glEnd(); + glBegin(GL_LINE_LOOP); + glVertex2f(center.x() + (gridRadius * 1.40), center.y() + (gridRadius * 1.40)); + glVertex2f(center.x() + (gridRadius * 1.40), center.y() + (gridRadius * 1.20)); + glVertex2f(center.x() + (gridRadius * 1.20), center.y() + (gridRadius * 1.20)); + glVertex2f(center.x() + (gridRadius * 1.20), center.y() + (gridRadius * 1.40)); + glEnd(); + + glPopMatrix(); +} + +void DrawControlPoints(void) +{ + glColor3f(1, 1, 1); + glBegin(GL_LINE_LOOP); + + for(int i=0; i extents.maxX) + extents.maxX = pts[i].x(); + if (pts[i].y() < extents.minY) + extents.minY = pts[i].y(); + if (pts[i].y() > extents.maxY) + extents.maxY = pts[i].y(); + } + + // Do some viewport fitting stuff... + +//globalOutputStream() << "--> Center: " << center.x() << ", " << center.y() << "\n"; +//globalOutputStream() << "--> Extents (stage 1): " << extents.minX << ", " +// << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; + // TTimo: Apply a ratio to get the area we'll draw. + center.x() = 0.5f * (extents.minX + extents.maxX), + center.y() = 0.5f * (extents.minY + extents.maxY); + extents.minX = center.x() + VP_PADDING * (extents.minX - center.x()), + extents.minY = center.y() + VP_PADDING * (extents.minY - center.y()), + extents.maxX = center.x() + VP_PADDING * (extents.maxX - center.x()), + extents.maxY = center.y() + VP_PADDING * (extents.maxY - center.y()); +//globalOutputStream() << "--> Extents (stage 2): " << extents.minX << ", " +// << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; + + // TTimo: We want a texture with the same X / Y ratio. + // TTimo: Compute XY space / window size ratio. + float SSize = extents.width(), TSize = extents.height(); + float ratioX = textureSize.x() * extents.width() / windowSize.x(), + ratioY = textureSize.y() * extents.height() / windowSize.y(); +//globalOutputStream() << "--> Texture size: " << textureSize.x() << ", " << textureSize.y() << "\n"; +//globalOutputStream() << "--> Window size: " << windowSize.x() << ", " << windowSize.y() << "\n"; + + if (ratioX > ratioY) + { + TSize = (windowSize.y() * ratioX) / textureSize.y(); +// TSize = extents.width() * (windowSize.y() / windowSize.x()) * (textureSize.x() / textureSize.y()); + } + else + { + SSize = (windowSize.x() * ratioY) / textureSize.x(); +// SSize = extents.height() * (windowSize.x() / windowSize.y()) * (textureSize.y() / textureSize.x()); + } + + extents.minX = center.x() - 0.5f * SSize, extents.maxX = center.x() + 0.5f * SSize, + extents.minY = center.y() - 0.5f * TSize, extents.maxY = center.y() + 0.5f * TSize; +//globalOutputStream() << "--> Extents (stage 3): " << extents.minX << ", " +// << extents.maxX << ", " << extents.minY << ", " << extents.maxY << "\n"; +} + +gboolean size_allocate(GtkWidget * win, GtkAllocation * a, gpointer) +{ + windowSize.x() = a->width; + windowSize.y() = a->height; + queueDraw(); + return false; +} + +gboolean expose(GtkWidget * win, GdkEventExpose * e, gpointer) +{ +// globalOutputStream() << "--> Textool Window was exposed!\n"; +// globalOutputStream() << " (window width/height: " << cc << "/" << e->area.height << ")\n"; + +// windowSize.x() = e->area.width, windowSize.y() = e->area.height; +//This needs to go elsewhere... +// InitTextool(); + + if (glwidget_make_current(win) == FALSE) + { + globalOutputStream() << " FAILED to make current! Oh, the agony! :-(\n"; + return true; + } + + CopyPointsFromSelectedFace(); + + if(!lButtonDown) + { + focus(); + } + + // Probably should init button/anchor states here as well... +// rotationAngle = 0.0f; + glClearColor(0, 0, 0, 0); + glViewport(0, 0, e->area.width, e->area.height); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + +//??? + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + + glOrtho(extents.minX, extents.maxX, extents.maxY, extents.minY, -1, 1); + + glColor3f(1, 1, 1); + // draw the texture background + glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); + glBindTexture(GL_TEXTURE_2D, textureNum); + + glEnable(GL_TEXTURE_2D); + glBegin(GL_QUADS); + glTexCoord2f(extents.minX, extents.minY); + glVertex2f(extents.minX, extents.minY); + glTexCoord2f(extents.maxX, extents.minY); + glVertex2f(extents.maxX, extents.minY); + glTexCoord2f(extents.maxX, extents.maxY); + glVertex2f(extents.maxX, extents.maxY); + glTexCoord2f(extents.minX, extents.maxY); + glVertex2f(extents.minX, extents.maxY); + glEnd(); + glDisable(GL_TEXTURE_2D); + + // draw the texture-space grid + glColor3fv(widgetColor[COLOR_GREY]); + glBegin(GL_LINES); + + const int gridSubdivisions = 8; + const float gridExtents = 4.0f; + + for(int i = 0; i < gridSubdivisions + 1; ++i) + { + float y = i * (gridExtents / float(gridSubdivisions)); + float x = i * (gridExtents / float(gridSubdivisions)); + glVertex2f(0, y); + glVertex2f(gridExtents, y); + glVertex2f(x, 0); + glVertex2f(x, gridExtents); + } + + glEnd(); + + DrawControlPoints(); + DrawControlWidgets(); +//??? + // reset the current texture +// glBindTexture(GL_TEXTURE_2D, 0); +// glFinish(); + glwidget_swap_buffers(win); + + return false; +} + +/*int FindSelectedPoint(int x, int y) +{ + for(int i=0; i Textool button press...\n"; + + if (e->button == 1) + { + lButtonDown = true; + GlobalUndoSystem().start(); + + origBP = currentBP; + + //globalOutputStream() << "--> Original BP: [" << origBP.coords[0][0] << "][" << origBP.coords[0][1] << "][" << origBP.coords[0][2] << "]\n"; + //globalOutputStream() << " [" << origBP.coords[1][0] << "][" << origBP.coords[1][1] << "][" << origBP.coords[1][2] << "]\n"; + //float angle = atan2(origBP.coords[0][1], origBP.coords[0][0]) * 180.0f / 3.141592653589f; + origAngle = (origBP.coords[0][1] > 0 ? PI : -PI); // Could also be -PI... !!! FIX !!! [DONE] + + if (origBP.coords[0][0] != 0.0f) + origAngle = atan(origBP.coords[0][1] / origBP.coords[0][0]); + + origScaleX = origBP.coords[0][0] / cos(origAngle); + origScaleY = origBP.coords[1][1] / cos(origAngle); + rotationAngle = origAngle; + oldCenter[0] = oldCenter[1] = 0; + + //globalOutputStream() << "--> BP stats: ang=" << origAngle * RAD_TO_DEG << ", scale=" << origScaleX << "/" << origScaleY << "\n"; + //Should also set the Flip X/Y checkboxes here as well... !!! FIX !!! + //Also: should reverse texture left/right up/down instead of flipping the points... + +//disnowok +//float nx = windowSize.x() * (e->x - extents.minX) / (extents.maxX - extents.minX); +//float ny = windowSize.y() * (e->y - extents.minY) / (extents.maxY - extents.minY); +//disdoes... +//But I want it to scroll the texture window, not the points... !!! FIX !!! +//Actually, should scroll the texture window only when mouse is down on no widgets... + float nx = e->x / windowSize.x() * extents.width() + extents.minX; + float ny = e->y / windowSize.y() * extents.height() + extents.minY; + trans.x() = -tm.coords[0][0] * nx - tm.coords[0][1] * ny; + trans.y() = -tm.coords[1][0] * nx - tm.coords[1][1] * ny; + + dragPoint.x() = e->x, dragPoint.y() = e->y; + trans2.x() = nx, trans2.y() = ny; + oldRotationAngle = rotationAngle; +// oldTrans.x() = tm.coords[0][2] - nx * textureSize.x(); +// oldTrans.y() = tm.coords[1][2] - ny * textureSize.y(); + oldTrans.x() = tm.coords[0][2]; + oldTrans.y() = tm.coords[1][2]; + oldCenter.x() = center.x(); + oldCenter.y() = center.y(); + + queueDraw(); + + return true; + } +/* else if (e->button == 3) + { + rButtonDown = true; + }//*/ + +//globalOutputStream() << "(" << (haveAnchor ? "anchor" : "released") << ")\n"; + + return false; +} + +gboolean button_release(GtkWidget * win, GdkEventButton * e, gpointer) +{ +// globalOutputStream() << "--> Textool button release...\n"; + + if (e->button == 1) + { +/* float ptx = e->x / windowSize.x() * extents.width() + extents.minX; + float pty = e->y / windowSize.y() * extents.height() + extents.minY; + +//This prolly should go into the mouse move code... +//Doesn't work correctly anyway... + if (translatingX || translatingY) + center.x() = ptx, center.y() = pty;//*/ + + lButtonDown = false; + + if(translatingX || translatingY) + { + GlobalUndoSystem().finish("translateTexture"); + } + else if(rotating) + { + GlobalUndoSystem().finish("rotateTexture"); + } + else if(scalingX || scalingY) + { + GlobalUndoSystem().finish("scaleTexture"); + } + else if(resizingX || resizingY) + { + GlobalUndoSystem().finish("resizeTexture"); + } + else + { + GlobalUndoSystem().finish("textoolUnknown"); + } + + rotating = translatingX = translatingY = scalingX = scalingY + = resizingX = resizingY = false; + + queueDraw(); + } + else if (e->button == 3) + { + rButtonDown = false; + } + + return true; +} + +/* +void C2DView::GridForWindow( float c[2], int x, int y) +{ + SpaceForWindow( c, x, y ); + if ( !m_bDoGrid ) + return; + c[0] /= m_GridStep[0]; + c[1] /= m_GridStep[1]; + c[0] = (float)floor( c[0] + 0.5f ); + c[1] = (float)floor( c[1] + 0.5f ); + c[0] *= m_GridStep[0]; + c[1] *= m_GridStep[1]; +} +void C2DView::SpaceForWindow( float c[2], int x, int y) +{ + c[0] = ((float)(x))/((float)(m_rect.right-m_rect.left))*(m_Maxs[0]-m_Mins[0])+m_Mins[0]; + c[1] = ((float)(y))/((float)(m_rect.bottom-m_rect.top))*(m_Maxs[1]-m_Mins[1])+m_Mins[1]; +} +*/ +gboolean motion(GtkWidget * win, GdkEventMotion * e, gpointer) +{ +// globalOutputStream() << "--> Textool motion...\n"; + + if (lButtonDown) + { + if (translatingX || translatingY) + { + float ptx = e->x / windowSize.x() * extents.width() + extents.minX; + float pty = e->y / windowSize.y() * extents.height() + extents.minY; + +//Need to fix this to take the rotation angle into account, so that it moves along +//the rotated X/Y axis... + if (translatingX) + { +// tm.coords[0][2] = (trans.x() + ptx) * textureSize.x(); +//This works, but only when the angle is zero. !!! FIX !!! [DONE] +// tm.coords[0][2] = oldCenter.x() + (ptx * textureSize.x()); + tm.coords[0][2] = oldTrans.x() + (ptx - trans2.x()) * textureSize.x(); +// center.x() = oldCenter.x() + (ptx - trans2.x()); + } + + if (translatingY) + { +// tm.coords[1][2] = (trans.y() + pty) * textureSize.y(); +// tm.coords[1][2] = oldCenter.y() + (pty * textureSize.y()); + tm.coords[1][2] = oldTrans.y() + (pty - trans2.y()) * textureSize.y(); +// center.y() = oldCenter.y() + (pty - trans2.y()); + } + +//Need to update center.x/y() so that the widget translates as well. Also, oldCenter +//is badly named... Should be oldTrans or something like that... !!! FIX !!! +//Changing center.x/y() here doesn't seem to change anything... :-/ + UpdateControlPoints(); + } + else if (rotating) + { + // Shamus: New rotate code + int cx = (int)(windowSize.x() * (center.x() - extents.minX) / extents.width()); + int cy = (int)(windowSize.y() * (center.y() - extents.minY) / extents.height()); + Vector3 v1(dragPoint.x() - cx, dragPoint.y() - cy, 0), v2(e->x - cx, e->y - cy, 0); + + vector3_normalise(v1); + vector3_normalise(v2); + float c = vector3_dot(v1, v2); + Vector3 cross = vector3_cross(v1, v2); + float s = vector3_length(cross); + + if (cross[2] > 0) + s = -s; + +// Problem with this: arcsin/cos seems to only return -90 to 90 and 0 to 180... +// Can't derive angle from that! + +//rotationAngle = asin(s);// * 180.0f / 3.141592653589f; +rotationAngle = acos(c); +//rotationAngle2 = asin(s); +if (cross[2] < 0) + rotationAngle = -rotationAngle; + +//NO! DOESN'T WORK! rotationAngle -= 45.0f * DEG_TO_RAD; +//Let's try this: +//No wok. +/*c = cos(rotationAngle - oldRotationAngle); +s = sin(rotationAngle - oldRotationAngle); +rotationAngle += oldRotationAngle; +//c += cos(oldRotationAngle); +//s += sin(oldRotationAngle); +//rotationAngle += oldRotationAngle; +//c %= 2.0 * PI; +//s %= 2.0 * PI; +//rotationAngle %= 2.0 * PI;//*/ + +//This is wrong... Hmm... +//It seems to shear the texture instead of rotating it... !!! FIX !!! +// Now it rotates correctly. Seems TTimo was overcomplicating things here... ;-) + +// Seems like what needs to happen here is multiplying these rotations by tm... !!! FIX !!! + +// See brush_primit.cpp line 244 (Texdef_EmitTextureCoordinates()) for where texcoords come from... + + tm.coords[0][0] = c; + tm.coords[0][1] = s; + tm.coords[1][0] = -s; + tm.coords[1][1] = c; +//It doesn't work anymore... Dunno why... +//tm.coords[0][2] = -trans.x(); // This works!!! Yeah!!! +//tm.coords[1][2] = -trans.y(); +//nope. +//tm.coords[0][2] = rotationPoint.x(); // This works, but strangely... +//tm.coords[1][2] = rotationPoint.y(); +//tm.coords[0][2] = 0;// center.x() / 2.0f; +//tm.coords[1][2] = 0;// center.y() / 2.0f; +//No. +//tm.coords[0][2] = -(center.x() * textureSize.x()); +//tm.coords[1][2] = -(center.y() * textureSize.y()); +//Eh? No, but seems to be getting closer... +/*float ptx = e->x / windowSize.x() * extents.width() + extents.minX; +float pty = e->y / windowSize.y() * extents.height() + extents.minY; +tm.coords[0][2] = -c * center.x() - s * center.y() + ptx; +tm.coords[1][2] = s * center.x() - c * center.x() + pty;//*/ +//Kinda works, but center drifts around on non-square textures... +/*tm.coords[0][2] = (-c * center.x() - s * center.y()) * textureSize.x(); +tm.coords[1][2] = ( s * center.x() - c * center.y()) * textureSize.y();//*/ +//Rotates correctly, but not around the actual center of the face's points... +/*tm.coords[0][2] = -c * center.x() * textureSize.x() - s * center.y() * textureSize.y(); +tm.coords[1][2] = s * center.x() * textureSize.x() - c * center.y() * textureSize.y();//*/ +//Yes!!! + tm.coords[0][2] = (-c * center.x() * textureSize.x() - s * center.y() * textureSize.y()) + center.x() * textureSize.x(); + tm.coords[1][2] = ( s * center.x() * textureSize.x() - c * center.y() * textureSize.y()) + center.y() * textureSize.y();//*/ +//This doesn't work... +//And this is the wrong place for this anyway (I'm pretty sure). +/*tm.coords[0][2] += oldCenter.x(); +tm.coords[1][2] += oldCenter.y();//*/ + UpdateControlPoints(); // will cause a redraw + } + + return true; + } + else // Check for widget mouseovers + { + Vector2 tran; + float nx = e->x / windowSize.x() * extents.width() + extents.minX; + float ny = e->y / windowSize.y() * extents.height() + extents.minY; + // Translate nx/y to the "center" point... + nx -= center.x(); + ny -= center.y(); + ny = -ny; // Flip Y-axis so that increasing numbers move up + + tran.x() = tm.coords[0][0] * nx + tm.coords[0][1] * ny; + tran.y() = tm.coords[1][0] * nx + tm.coords[1][1] * ny; +//This doesn't seem to generate a valid distance from the center--for some reason it +//calculates a fixed number every time +//Look at nx/y above: they're getting fixed there! !!! FIX !!! [DONE] + float dist = sqrt((nx * nx) + (ny * ny)); + // Normalize to the 2.0 = height standard (for now) +//globalOutputStream() << "--> Distance before: " << dist; + dist = dist * 2.0f / extents.height(); +//globalOutputStream() << ". After: " << dist; + tran.x() = tran.x() * 2.0f / extents.height(); + tran.y() = tran.y() * 2.0f / extents.height(); +//globalOutputStream() << ". Trans: " << tran.x() << ", " << tran.y() << "\n"; + +//Let's try this instead... +//Interesting! It seems that e->x/y are rotated +//(no, they're not--the TM above is what's doing it...) +nx = ((e->x / windowSize.y()) * 2.0f) - (windowSize.x() / windowSize.y()); +ny = ((e->y / windowSize.y()) * 2.0f) - (windowSize.y() / windowSize.y()); +ny = -ny; +//Cool! It works! Now just need to do rotation... + + rotating = translatingX = translatingY = scalingX = scalingY + = resizingX = resizingY = false; + + if (dist < (gridRadius * 0.16f)) + { + translatingX = translatingY = true; + } + else if (dist > (gridRadius * 0.16f) && dist < (gridRadius * 1.10f) + && fabs(ny) < (gridRadius * 0.05f) && nx > 0) + { + translatingX = true; + } + else if (dist > (gridRadius * 0.16f) && dist < (gridRadius * 1.10f) + && fabs(nx) < (gridRadius * 0.05f) && ny > 0) + { + translatingY = true; + } + // Should tighten up the angle on this, or put this test after the axis tests... + else if (tran.x() > 0 && tran.y() > 0 + && (dist > (gridRadius * 0.82f) && dist < (gridRadius * 0.98f))) + { + rotating = true; + } + + queueDraw(); + + return true; + } + + return false; +} + +//It seems the fake tex coords conversion is screwing this stuff up... !!! FIX !!! +//This is still wrong... Prolly need to do something with the oldScaleX/Y stuff... +void flipX(GtkToggleButton *, gpointer) +{ +// globalOutputStream() << "--> Flip X...\n"; + //Shamus: +// SurfaceInspector_GetSelectedBPTexdef(); // Refresh g_selectedBrushPrimitTexdef... +// tm.coords[0][0] = -tm.coords[0][0]; +// tm.coords[1][0] = -tm.coords[1][0]; +// tm.coords[0][0] = -tm.coords[0][0]; // This should be correct now...Nope. +// tm.coords[1][1] = -tm.coords[1][1]; + tm.coords[0][0] = -tm.coords[0][0]; // This should be correct now... + tm.coords[1][0] = -tm.coords[1][0]; +// tm.coords[2][0] = -tm.coords[2][0];//wil wok? no. + UpdateControlPoints(); +} + +void flipY(GtkToggleButton *, gpointer) +{ +// globalOutputStream() << "--> Flip Y...\n"; +// tm.coords[0][1] = -tm.coords[0][1]; +// tm.coords[1][1] = -tm.coords[1][1]; +// tm.coords[0][1] = -tm.coords[0][1]; // This should be correct now...Nope. +// tm.coords[1][0] = -tm.coords[1][0]; + tm.coords[0][1] = -tm.coords[0][1]; // This should be correct now... + tm.coords[1][1] = -tm.coords[1][1]; +// tm.coords[2][1] = -tm.coords[2][1];//wil wok? no. + UpdateControlPoints(); +} + +} // end namespace TexTool + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/surfacedialog.h b/misc/mediasource/netradiant-src/radiant/surfacedialog.h new file mode 100644 index 00000000..034cf1d6 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/surfacedialog.h @@ -0,0 +1,60 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_SURFACEDIALOG_H) +#define INCLUDED_SURFACEDIALOG_H + + +void SurfaceInspector_Construct(); +void SurfaceInspector_Destroy(); + +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; +void SurfaceInspector_constructWindow(GtkWindow* widget); +void SurfaceInspector_destroyWindow(); + +bool SelectedFaces_empty(); +void SelectedFaces_copyTexture(); +void SelectedFaces_pasteTexture(); +void FaceTextureClipboard_setDefault(); + + +// the increment we are using for the surface inspector (this is saved in the prefs) +struct si_globals_t +{ + float shift[2]; + float scale[2]; + float rotate; + + bool m_bSnapTToGrid; + + si_globals_t() : m_bSnapTToGrid(false) + { + shift[0] = 8.0f; + shift[1] = 8.0f; + scale[0] = 0.5f; + scale[1] = 0.5f; + rotate = 45.0f; + } +}; +extern si_globals_t g_si_globals; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/texmanip.cpp b/misc/mediasource/netradiant-src/radiant/texmanip.cpp new file mode 100644 index 00000000..8fa88ca2 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/texmanip.cpp @@ -0,0 +1,388 @@ +/* +Copyright (c) 2002 Forest "LordHavoc" Hale + +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 Forest Hale nor the names of other 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. +*/ + +#include "texmanip.h" + +#include +#include "stream/textstream.h" + +static byte *row1 = NULL, *row2 = NULL; +static int rowsize = 0; + +void R_ResampleTextureLerpLine (const byte *in, byte *out, int inwidth, int outwidth, int bytesperpixel) +{ + int j, xi, oldx = 0, f, fstep, endx, lerp; +#define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i]) + + fstep = (int) (inwidth * 65536.0f / outwidth); + endx = (inwidth - 1); + if (bytesperpixel == 4) + { + for (j = 0,f = 0;j < outwidth;j++, f += fstep) + { + xi = f >> 16; + if (xi != oldx) + { + in += (xi - oldx) * 4; + oldx = xi; + } + + if (xi < endx) + { + lerp = f & 0xFFFF; + *out++ = (byte) ((((in[4] - in[0]) * lerp) >> 16) + in[0]); + *out++ = (byte) ((((in[5] - in[1]) * lerp) >> 16) + in[1]); + *out++ = (byte) ((((in[6] - in[2]) * lerp) >> 16) + in[2]); + *out++ = (byte) ((((in[7] - in[3]) * lerp) >> 16) + in[3]); + } + else // last pixel of the line has no pixel to lerp to + { + *out++ = in[0]; + *out++ = in[1]; + *out++ = in[2]; + *out++ = in[3]; + } + } + } + else if (bytesperpixel == 3) + { + for (j = 0, f = 0; j < outwidth; j++, f += fstep) + { + xi = f >> 16; + if (xi != oldx) + { + in += (xi - oldx) * 3; + oldx = xi; + } + + if (xi < endx) + { + lerp = f & 0xFFFF; + *out++ = (byte) ((((in[3] - in[0]) * lerp) >> 16) + in[0]); + *out++ = (byte) ((((in[4] - in[1]) * lerp) >> 16) + in[1]); + *out++ = (byte) ((((in[5] - in[2]) * lerp) >> 16) + in[2]); + } + else // last pixel of the line has no pixel to lerp to + { + *out++ = in[0]; + *out++ = in[1]; + *out++ = in[2]; + } + } + } + else + { + globalOutputStream() << "R_ResampleTextureLerpLine: unsupported bytesperpixel " << bytesperpixel << "\n"; + } +} + +/* +================ +R_ResampleTexture +================ +*/ +void R_ResampleTexture (const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight, int bytesperpixel) +{ + if (rowsize < outwidth * bytesperpixel) + { + if (row1) + free(row1); + if (row2) + free(row2); + + rowsize = outwidth * bytesperpixel; + row1 = (byte *)malloc(rowsize); + row2 = (byte *)malloc(rowsize); + } + + if (bytesperpixel == 4) + { + int i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth4 = inwidth*4, outwidth4 = outwidth*4; + byte *inrow, *out; + out = (byte *)outdata; + fstep = (int) (inheight * 65536.0f / outheight); +#define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i]) + + inrow = (byte *)indata; + oldy = 0; + R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); + R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel); + + for (i = 0, f = 0;i < outheight;i++,f += fstep) + { + yi = f >> 16; + if (yi < endy) + { + lerp = f & 0xFFFF; + if (yi != oldy) + { + inrow = (byte *)indata + inwidth4 * yi; + if (yi == oldy+1) + memcpy(row1, row2, outwidth4); + else + R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); + + R_ResampleTextureLerpLine (inrow + inwidth4, row2, inwidth, outwidth, bytesperpixel); + oldy = yi; + } + j = outwidth - 4; + while(j >= 0) + { + LERPBYTE( 0); + LERPBYTE( 1); + LERPBYTE( 2); + LERPBYTE( 3); + LERPBYTE( 4); + LERPBYTE( 5); + LERPBYTE( 6); + LERPBYTE( 7); + LERPBYTE( 8); + LERPBYTE( 9); + LERPBYTE(10); + LERPBYTE(11); + LERPBYTE(12); + LERPBYTE(13); + LERPBYTE(14); + LERPBYTE(15); + out += 16; + row1 += 16; + row2 += 16; + j -= 4; + } + if (j & 2) + { + LERPBYTE( 0); + LERPBYTE( 1); + LERPBYTE( 2); + LERPBYTE( 3); + LERPBYTE( 4); + LERPBYTE( 5); + LERPBYTE( 6); + LERPBYTE( 7); + out += 8; + row1 += 8; + row2 += 8; + } + if (j & 1) + { + LERPBYTE( 0); + LERPBYTE( 1); + LERPBYTE( 2); + LERPBYTE( 3); + out += 4; + row1 += 4; + row2 += 4; + } + row1 -= outwidth4; + row2 -= outwidth4; + } + else + { + if (yi != oldy) + { + inrow = (byte *)indata + inwidth4*yi; + if (yi == oldy+1) + memcpy(row1, row2, outwidth4); + else + R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); + + oldy = yi; + } + memcpy(out, row1, outwidth4); + } + } + } + else if (bytesperpixel == 3) + { + int i, j, yi, oldy, f, fstep, lerp, endy = (inheight-1), inwidth3 = inwidth * 3, outwidth3 = outwidth * 3; + byte *inrow, *out; + out = (byte *)outdata; + fstep = (int) (inheight*65536.0f/outheight); +#define LERPBYTE(i) out[i] = (byte) ((((row2[i] - row1[i]) * lerp) >> 16) + row1[i]) + + inrow = (byte *)indata; + oldy = 0; + R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); + R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel); + for (i = 0, f = 0;i < outheight;i++,f += fstep) + { + yi = f >> 16; + if (yi < endy) + { + lerp = f & 0xFFFF; + if (yi != oldy) + { + inrow = (byte *)indata + inwidth3*yi; + if (yi == oldy+1) + memcpy(row1, row2, outwidth3); + else + R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); + + R_ResampleTextureLerpLine (inrow + inwidth3, row2, inwidth, outwidth, bytesperpixel); + oldy = yi; + } + j = outwidth - 4; + while(j >= 0) + { + LERPBYTE( 0); + LERPBYTE( 1); + LERPBYTE( 2); + LERPBYTE( 3); + LERPBYTE( 4); + LERPBYTE( 5); + LERPBYTE( 6); + LERPBYTE( 7); + LERPBYTE( 8); + LERPBYTE( 9); + LERPBYTE(10); + LERPBYTE(11); + out += 12; + row1 += 12; + row2 += 12; + j -= 4; + } + if (j & 2) + { + LERPBYTE( 0); + LERPBYTE( 1); + LERPBYTE( 2); + LERPBYTE( 3); + LERPBYTE( 4); + LERPBYTE( 5); + out += 6; + row1 += 6; + row2 += 6; + } + if (j & 1) + { + LERPBYTE( 0); + LERPBYTE( 1); + LERPBYTE( 2); + out += 3; + row1 += 3; + row2 += 3; + } + row1 -= outwidth3; + row2 -= outwidth3; + } + else + { + if (yi != oldy) + { + inrow = (byte *)indata + inwidth3*yi; + if (yi == oldy+1) + memcpy(row1, row2, outwidth3); + else + R_ResampleTextureLerpLine (inrow, row1, inwidth, outwidth, bytesperpixel); + + oldy = yi; + } + memcpy(out, row1, outwidth3); + } + } + } + else + { + globalOutputStream() << "R_ResampleTexture: unsupported bytesperpixel " << bytesperpixel << "\n"; + } +} + +// in can be the same as out +void GL_MipReduce(byte *in, byte *out, int width, int height, int destwidth, int destheight) +{ + int x, y, width2, height2, nextrow; + if (width > destwidth) + { + if (height > destheight) + { + // reduce both + width2 = width >> 1; + height2 = height >> 1; + nextrow = width << 2; + for (y = 0;y < height2;y++) + { + for (x = 0;x < width2;x++) + { + out[0] = (byte) ((in[0] + in[4] + in[nextrow ] + in[nextrow+4]) >> 2); + out[1] = (byte) ((in[1] + in[5] + in[nextrow+1] + in[nextrow+5]) >> 2); + out[2] = (byte) ((in[2] + in[6] + in[nextrow+2] + in[nextrow+6]) >> 2); + out[3] = (byte) ((in[3] + in[7] + in[nextrow+3] + in[nextrow+7]) >> 2); + out += 4; + in += 8; + } + in += nextrow; // skip a line + } + } + else + { + // reduce width + width2 = width >> 1; + for (y = 0;y < height;y++) + { + for (x = 0;x < width2;x++) + { + out[0] = (byte) ((in[0] + in[4]) >> 1); + out[1] = (byte) ((in[1] + in[5]) >> 1); + out[2] = (byte) ((in[2] + in[6]) >> 1); + out[3] = (byte) ((in[3] + in[7]) >> 1); + out += 4; + in += 8; + } + } + } + } + else + { + if (height > destheight) + { + // reduce height + height2 = height >> 1; + nextrow = width << 2; + for (y = 0;y < height2;y++) + { + for (x = 0;x < width;x++) + { + out[0] = (byte) ((in[0] + in[nextrow ]) >> 1); + out[1] = (byte) ((in[1] + in[nextrow+1]) >> 1); + out[2] = (byte) ((in[2] + in[nextrow+2]) >> 1); + out[3] = (byte) ((in[3] + in[nextrow+3]) >> 1); + out += 4; + in += 4; + } + in += nextrow; // skip a line + } + } + else + { + globalOutputStream() << "GL_MipReduce: desired size already achieved\n"; + } + } +} diff --git a/misc/mediasource/netradiant-src/radiant/texmanip.h b/misc/mediasource/netradiant-src/radiant/texmanip.h new file mode 100644 index 00000000..3cca3ce2 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/texmanip.h @@ -0,0 +1,40 @@ +/* +Copyright (c) 2002 Forest "LordHavoc" Hale + +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 Forest Hale nor the names of other 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. +*/ + +#if !defined(INCLUDED_TEXMANIP_H) +#define INCLUDED_TEXMANIP_H + +typedef unsigned char byte; + +void R_ResampleTexture (const void *indata, int inwidth, int inheight, void *outdata, int outwidth, int outheight, int bytesperpixel); +void GL_MipReduce(byte *in, byte *out, int width, int height, int destwidth, int destheight); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/textureentry.cpp b/misc/mediasource/netradiant-src/radiant/textureentry.cpp new file mode 100644 index 00000000..615143c1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/textureentry.cpp @@ -0,0 +1,23 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "textureentry.h" + diff --git a/misc/mediasource/netradiant-src/radiant/textureentry.h b/misc/mediasource/netradiant-src/radiant/textureentry.h new file mode 100644 index 00000000..3965fe29 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/textureentry.h @@ -0,0 +1,129 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_TEXTUREENTRY_H) +#define INCLUDED_TEXTUREENTRY_H + + +#include +#include +#include "gtkutil/idledraw.h" + +#include "generic/static.h" +#include "signal/isignal.h" +#include "shaderlib.h" + +#include "texwindow.h" + +template +class EntryCompletion +{ + GtkListStore* m_store; + IdleDraw m_idleUpdate; +public: + EntryCompletion() : m_store(0), m_idleUpdate(UpdateCaller(*this)) + { + } + + void connect(GtkEntry* entry) + { + if(m_store == 0) + { + m_store = gtk_list_store_new(1, G_TYPE_STRING); + + fill(); + + StringList().connect(IdleDraw::QueueDrawCaller(m_idleUpdate)); + } + + GtkEntryCompletion* completion = gtk_entry_completion_new(); + gtk_entry_set_completion(entry, completion); + gtk_entry_completion_set_model(completion, GTK_TREE_MODEL(m_store)); + gtk_entry_completion_set_text_column(completion, 0); + } + + void append(const char* string) + { + GtkTreeIter iter; + gtk_list_store_append(m_store, &iter); + gtk_list_store_set(m_store, &iter, 0, string, -1); + } + typedef MemberCaller1 AppendCaller; + + void fill() + { + StringList().forEach(AppendCaller(*this)); + } + + void clear() + { + gtk_list_store_clear(m_store); + } + + void update() + { + clear(); + fill(); + } + typedef MemberCaller UpdateCaller; +}; + +class TextureNameList +{ +public: + void forEach(const ShaderNameCallback& callback) const + { + for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) + { + IShader *shader = QERApp_ActiveShaders_IteratorCurrent(); + + if(shader_equal_prefix(shader->getName(), "textures/")) + { + callback(shader->getName() + 9); + } + } + } + void connect(const SignalHandler& update) const + { + TextureBrowser_addActiveShadersChangedCallback(update); + } +}; + +typedef Static< EntryCompletion > GlobalTextureEntryCompletion; + + +class ShaderList +{ +public: + void forEach(const ShaderNameCallback& callback) const + { + GlobalShaderSystem().foreachShaderName(callback); + } + void connect(const SignalHandler& update) const + { + TextureBrowser_addShadersRealiseCallback(update); + } +}; + +typedef Static< EntryCompletion > GlobalShaderEntryCompletion; + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/textures.cpp b/misc/mediasource/netradiant-src/radiant/textures.cpp new file mode 100644 index 00000000..e7ff7e42 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/textures.cpp @@ -0,0 +1,912 @@ +/* +Copyright (C) 1999-2006 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 "textures.h" + +#include "debugging/debugging.h" +#include "warnings.h" + +#include "itextures.h" +#include "igl.h" +#include "preferencesystem.h" +#include "qgl.h" + +#include "texturelib.h" +#include "container/hashfunc.h" +#include "container/cache.h" +#include "generic/callback.h" +#include "stringio.h" + +#include "image.h" +#include "texmanip.h" +#include "preferences.h" + + + +enum ETexturesMode +{ + eTextures_NEAREST = 0, + eTextures_NEAREST_MIPMAP_NEAREST = 1, + eTextures_NEAREST_MIPMAP_LINEAR = 2, + eTextures_LINEAR = 3, + eTextures_LINEAR_MIPMAP_NEAREST = 4, + eTextures_LINEAR_MIPMAP_LINEAR = 5, + eTextures_MAX_ANISOTROPY = 6, +}; + +enum TextureCompressionFormat +{ + TEXTURECOMPRESSION_NONE = 0, + TEXTURECOMPRESSION_RGBA = 1, + TEXTURECOMPRESSION_RGBA_S3TC_DXT1 = 2, + TEXTURECOMPRESSION_RGBA_S3TC_DXT3 = 3, + TEXTURECOMPRESSION_RGBA_S3TC_DXT5 = 4, +}; + +struct texture_globals_t +{ + // RIANT + // texture compression format + TextureCompressionFormat m_nTextureCompressionFormat; + + float fGamma; + + bool bTextureCompressionSupported; // is texture compression supported by hardware? + GLint texture_components; + + // temporary values that should be initialised only once at run-time + bool m_bOpenGLCompressionSupported; + bool m_bS3CompressionSupported; + + texture_globals_t(GLint components) : + m_nTextureCompressionFormat(TEXTURECOMPRESSION_NONE), + fGamma(1.0f), + bTextureCompressionSupported(false), + texture_components(components), + m_bOpenGLCompressionSupported(false), + m_bS3CompressionSupported(false) + { + } +}; + +texture_globals_t g_texture_globals(GL_RGBA); + +void SetTexParameters(ETexturesMode mode) +{ + float maxAniso = QGL_maxTextureAnisotropy(); + if(maxAniso > 1) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); + else + if(mode == eTextures_MAX_ANISOTROPY) + mode = eTextures_LINEAR_MIPMAP_LINEAR; + + switch (mode) + { + case eTextures_NEAREST: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + break; + case eTextures_NEAREST_MIPMAP_NEAREST: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + break; + case eTextures_NEAREST_MIPMAP_LINEAR: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); + break; + case eTextures_LINEAR: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + break; + case eTextures_LINEAR_MIPMAP_NEAREST: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + break; + case eTextures_LINEAR_MIPMAP_LINEAR: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR ); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); + break; + case eTextures_MAX_ANISOTROPY: + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAniso); + break; + default: + globalOutputStream() << "invalid texture mode\n"; + } +} + +ETexturesMode g_texture_mode = eTextures_LINEAR_MIPMAP_LINEAR; + + + + +byte g_gammatable[256]; +void ResampleGamma(float fGamma) +{ + int i,inf; + if (fGamma == 1.0) + { + for (i = 0; i < 256; i++) + g_gammatable[i] = i; + } else + { + for (i = 0; i < 256; i++) + { + inf = (int)(255 * pow ( static_cast((i + 0.5) / 255.5) , static_cast(fGamma) ) + 0.5); + if (inf < 0) + inf = 0; + if (inf > 255) + inf = 255; + g_gammatable[i] = inf; + } + } +} + +inline const int& min_int(const int& left, const int& right) +{ + return std::min(left, right); +} + +int max_tex_size = 0; +const int max_texture_quality = 3; +LatchedInt g_Textures_textureQuality(3, "Texture Quality"); + +/// \brief This function does the actual processing of raw RGBA data into a GL texture. +/// It will also resample to power-of-two dimensions, generate the mipmaps and adjust gamma. +void LoadTextureRGBA(qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight) +{ + static float fGamma = -1; + float total[3]; + byte *outpixels = 0; + int nCount = nWidth * nHeight; + + if (fGamma != g_texture_globals.fGamma) + { + fGamma = g_texture_globals.fGamma; + ResampleGamma(fGamma); + } + + q->width = nWidth; + q->height = nHeight; + + total[0] = total[1] = total[2] = 0.0f; + + // resample texture gamma according to user settings + for (int i = 0; i < (nCount * 4); i += 4) + { + for (int j = 0; j < 3; j++) + { + total[j] += (pPixels + i)[j]; + byte b = (pPixels + i)[j]; + (pPixels + i)[j] = g_gammatable[b]; + } + } + + q->color[0] = total[0] / (nCount * 255); + q->color[1] = total[1] / (nCount * 255); + q->color[2] = total[2] / (nCount * 255); + + glGenTextures (1, &q->texture_number); + + glBindTexture( GL_TEXTURE_2D, q->texture_number ); + + SetTexParameters(g_texture_mode); + + int gl_width = 1; + while(gl_width < nWidth) + gl_width <<= 1; + + int gl_height = 1; + while(gl_height < nHeight) + gl_height <<= 1; + + bool resampled = false; + if (!(gl_width == nWidth && gl_height == nHeight)) + { + resampled = true; + outpixels = (byte *)malloc(gl_width * gl_height * 4); + R_ResampleTexture(pPixels, nWidth, nHeight, outpixels, gl_width, gl_height, 4); + } + else + { + outpixels = pPixels; + } + + int quality_reduction = max_texture_quality - g_Textures_textureQuality.m_value; + int target_width = min_int(gl_width >> quality_reduction, max_tex_size); + int target_height = min_int(gl_height >> quality_reduction, max_tex_size); + + while (gl_width > target_width || gl_height > target_height) + { + GL_MipReduce(outpixels, outpixels, gl_width, gl_height, target_width, target_height); + + if (gl_width > target_width) + gl_width >>= 1; + if (gl_height > target_height) + gl_height >>= 1; + } + + int mip = 0; + glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels); + while (gl_width > 1 || gl_height > 1) + { + GL_MipReduce(outpixels, outpixels, gl_width, gl_height, 1, 1); + + if (gl_width > 1) + gl_width >>= 1; + if (gl_height > 1) + gl_height >>= 1; + + glTexImage2D(GL_TEXTURE_2D, mip++, g_texture_globals.texture_components, gl_width, gl_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, outpixels); + } + + glBindTexture(GL_TEXTURE_2D, 0); + if (resampled) + free(outpixels); +} + +#if 0 +/* +============== +Texture_InitPalette +============== +*/ +void Texture_InitPalette (byte *pal) +{ + int r,g,b; + int i; + int inf; + byte gammatable[256]; + float gamma; + + gamma = g_texture_globals.fGamma; + + if (gamma == 1.0) + { + for (i=0 ; i<256 ; i++) + gammatable[i] = i; + } else + { + for (i=0 ; i<256 ; i++) + { + inf = (int)(255 * pow ( (i+0.5)/255.5 , gamma ) + 0.5); + if (inf < 0) + inf = 0; + if (inf > 255) + inf = 255; + gammatable[i] = inf; + } + } + + for (i=0 ; i<256 ; i++) + { + r = gammatable[pal[0]]; + g = gammatable[pal[1]]; + b = gammatable[pal[2]]; + pal += 3; + + //v = (r<<24) + (g<<16) + (b<<8) + 255; + //v = BigLong (v); + + //tex_palette[i] = v; + tex_palette[i*3+0] = r; + tex_palette[i*3+1] = g; + tex_palette[i*3+2] = b; + } +} +#endif + +#if 0 +class TestHashtable +{ +public: + TestHashtable() + { + HashTable strings; + strings["Monkey"] = "bleh"; + strings["MonkeY"] = "blah"; + } +}; + +const TestHashtable g_testhashtable; + +#endif + +typedef std::pair TextureKey; + +void qtexture_realise(qtexture_t& texture, const TextureKey& key) +{ + texture.texture_number = 0; + if(!string_empty(key.second.c_str())) + { + Image* image = key.first.loadImage(key.second.c_str()); + if(image != 0) + { + LoadTextureRGBA(&texture, image->getRGBAPixels(), image->getWidth(), image->getHeight()); + texture.surfaceFlags = image->getSurfaceFlags(); + texture.contentFlags = image->getContentFlags(); + texture.value = image->getValue(); + image->release(); + globalOutputStream() << "Loaded Texture: \"" << key.second.c_str() << "\"\n"; + GlobalOpenGL_debugAssertNoErrors(); + } + else + { + globalErrorStream() << "Texture load failed: \"" << key.second.c_str() << "\"\n"; + } + } +} + +void qtexture_unrealise(qtexture_t& texture) +{ + if(GlobalOpenGL().contextValid && texture.texture_number != 0) + { + glDeleteTextures(1, &texture.texture_number); + GlobalOpenGL_debugAssertNoErrors(); + } +} + +class TextureKeyEqualNoCase +{ +public: + bool operator()(const TextureKey& key, const TextureKey& other) const + { + return key.first == other.first && string_equal_nocase(key.second.c_str(), other.second.c_str()); + } +}; + +class TextureKeyHashNoCase +{ +public: + typedef hash_t hash_type; + hash_t operator()(const TextureKey& key) const + { + return hash_combine(string_hash_nocase(key.second.c_str()), pod_hash(key.first)); + } +}; + +#define DEBUG_TEXTURES 0 + +class TexturesMap : public TexturesCache +{ + class TextureConstructor + { + TexturesMap* m_cache; + public: + explicit TextureConstructor(TexturesMap* cache) + : m_cache(cache) + { + } + qtexture_t* construct(const TextureKey& key) + { + qtexture_t* texture = new qtexture_t(key.first, key.second.c_str()); + if(m_cache->realised()) + { + qtexture_realise(*texture, key); + } + return texture; + } + void destroy(qtexture_t* texture) + { + if(m_cache->realised()) + { + qtexture_unrealise(*texture); + } + delete texture; + } + }; + + typedef HashedCache qtextures_t; + qtextures_t m_qtextures; + TexturesCacheObserver* m_observer; + std::size_t m_unrealised; + +public: + TexturesMap() : m_qtextures(TextureConstructor(this)), m_observer(0), m_unrealised(1) + { + } + typedef qtextures_t::iterator iterator; + + iterator begin() + { + return m_qtextures.begin(); + } + iterator end() + { + return m_qtextures.end(); + } + + LoadImageCallback defaultLoader() const + { + return LoadImageCallback(0, QERApp_LoadImage); + } + Image* loadImage(const char* name) + { + return defaultLoader().loadImage(name); + } + qtexture_t* capture(const char* name) + { + return capture(defaultLoader(), name); + } + qtexture_t* capture(const LoadImageCallback& loader, const char* name) + { +#if DEBUG_TEXTURES + globalOutputStream() << "textures capture: " << makeQuoted(name) << '\n'; +#endif + return m_qtextures.capture(TextureKey(loader, name)).get(); + } + void release(qtexture_t* texture) + { +#if DEBUG_TEXTURES + globalOutputStream() << "textures release: " << makeQuoted(texture->name) << '\n'; +#endif + m_qtextures.release(TextureKey(texture->load, texture->name)); + } + void attach(TexturesCacheObserver& observer) + { + ASSERT_MESSAGE(m_observer == 0, "TexturesMap::attach: cannot attach observer"); + m_observer = &observer; + } + void detach(TexturesCacheObserver& observer) + { + ASSERT_MESSAGE(m_observer == &observer, "TexturesMap::detach: cannot detach observer"); + m_observer = 0; + } + void realise() + { + if(--m_unrealised == 0) + { + g_texture_globals.bTextureCompressionSupported = false; + + if(GlobalOpenGL().ARB_texture_compression()) + { + g_texture_globals.bTextureCompressionSupported = true; + g_texture_globals.m_bOpenGLCompressionSupported = true; + } + + if(GlobalOpenGL().EXT_texture_compression_s3tc()) + { + g_texture_globals.bTextureCompressionSupported = true; + g_texture_globals.m_bS3CompressionSupported = true; + } + + switch(g_texture_globals.texture_components) + { + case GL_RGBA: + break; + case GL_COMPRESSED_RGBA_ARB: + if (!g_texture_globals.m_bOpenGLCompressionSupported) + { + globalOutputStream() << "OpenGL extension GL_ARB_texture_compression not supported by current graphics drivers\n"; + g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; + g_texture_globals.texture_components = GL_RGBA; + } + break; + case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT: + case GL_COMPRESSED_RGBA_S3TC_DXT3_EXT: + case GL_COMPRESSED_RGBA_S3TC_DXT5_EXT: + if(!g_texture_globals.m_bS3CompressionSupported) + { + globalOutputStream() << "OpenGL extension GL_EXT_texture_compression_s3tc not supported by current graphics drivers\n"; + if(g_texture_globals.m_bOpenGLCompressionSupported) + { + g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_RGBA; + g_texture_globals.texture_components = GL_COMPRESSED_RGBA_ARB; + } + else + { + g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; + g_texture_globals.texture_components = GL_RGBA; + } + } + break; + default: + globalOutputStream() << "Unknown texture compression selected, reverting\n"; + g_texture_globals.m_nTextureCompressionFormat = TEXTURECOMPRESSION_NONE; + g_texture_globals.texture_components = GL_RGBA; + break; + } + + + glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max_tex_size); + if(max_tex_size == 0) + { + max_tex_size = 1024; + } + + for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i) + { + if(!(*i).value.empty()) + { + qtexture_realise(*(*i).value, (*i).key); + } + } + if(m_observer != 0) + { + m_observer->realise(); + } + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + if(m_observer != 0) + { + m_observer->unrealise(); + } + for(qtextures_t::iterator i = m_qtextures.begin(); i != m_qtextures.end(); ++i) + { + if(!(*i).value.empty()) + { + qtexture_unrealise(*(*i).value); + } + } + } + } + bool realised() + { + return m_unrealised == 0; + } +}; + +TexturesMap* g_texturesmap; + +TexturesCache& GetTexturesCache() +{ + return *g_texturesmap; +} + + +void Textures_Realise() +{ + g_texturesmap->realise(); +} + +void Textures_Unrealise() +{ + g_texturesmap->unrealise(); +} + + +Callback g_texturesModeChangedNotify; + +void Textures_setModeChangedNotify(const Callback& notify) +{ + g_texturesModeChangedNotify = notify; +} + +void Textures_ModeChanged() +{ + if(g_texturesmap->realised()) + { + SetTexParameters(g_texture_mode); + + for(TexturesMap::iterator i = g_texturesmap->begin(); i != g_texturesmap->end(); ++i) + { + glBindTexture (GL_TEXTURE_2D, (*i).value->texture_number); + SetTexParameters(g_texture_mode); + } + + glBindTexture( GL_TEXTURE_2D, 0 ); + } + g_texturesModeChangedNotify(); +} + +void Textures_SetMode(ETexturesMode mode) +{ + if(g_texture_mode != mode) + { + g_texture_mode = mode; + + Textures_ModeChanged(); + } +} + +void Textures_setTextureComponents(GLint texture_components) +{ + if(g_texture_globals.texture_components != texture_components) + { + Textures_Unrealise(); + g_texture_globals.texture_components = texture_components; + Textures_Realise(); + } +} + +void Textures_UpdateTextureCompressionFormat() +{ + GLint texture_components = GL_RGBA; + + switch (g_texture_globals.m_nTextureCompressionFormat) + { + case (TEXTURECOMPRESSION_NONE): + { + texture_components = GL_RGBA; + break; + } + case (TEXTURECOMPRESSION_RGBA): + { + texture_components = GL_COMPRESSED_RGBA_ARB; + break; + } + case (TEXTURECOMPRESSION_RGBA_S3TC_DXT1): + { + texture_components = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; + break; + } + case (TEXTURECOMPRESSION_RGBA_S3TC_DXT3): + { + texture_components = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; + break; + } + case (TEXTURECOMPRESSION_RGBA_S3TC_DXT5): + { + texture_components = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + break; + } + } + + Textures_setTextureComponents(texture_components); +} + +void TextureCompressionImport(TextureCompressionFormat& self, int value) +{ + if(!g_texture_globals.m_bOpenGLCompressionSupported + && g_texture_globals.m_bS3CompressionSupported + && value >= 1) + { + ++value; + } + switch(value) + { + case 0: + self = TEXTURECOMPRESSION_NONE; + break; + case 1: + self = TEXTURECOMPRESSION_RGBA; + break; + case 2: + self = TEXTURECOMPRESSION_RGBA_S3TC_DXT1; + break; + case 3: + self = TEXTURECOMPRESSION_RGBA_S3TC_DXT3; + break; + case 4: + self = TEXTURECOMPRESSION_RGBA_S3TC_DXT5; + break; + } + Textures_UpdateTextureCompressionFormat(); +} +typedef ReferenceCaller1 TextureCompressionImportCaller; + +void TextureGammaImport(float& self, float value) +{ + if(self != value) + { + Textures_Unrealise(); + self = value; + Textures_Realise(); + } +} +typedef ReferenceCaller1 TextureGammaImportCaller; + +void TextureModeImport(ETexturesMode& self, int value) +{ + switch(value) + { + case 0: + Textures_SetMode(eTextures_NEAREST); + break; + case 1: + Textures_SetMode(eTextures_NEAREST_MIPMAP_NEAREST); + break; + case 2: + Textures_SetMode(eTextures_LINEAR); + break; + case 3: + Textures_SetMode(eTextures_NEAREST_MIPMAP_LINEAR); + break; + case 4: + Textures_SetMode(eTextures_LINEAR_MIPMAP_NEAREST); + break; + case 5: + Textures_SetMode(eTextures_LINEAR_MIPMAP_LINEAR); + break; + case 6: + Textures_SetMode(eTextures_MAX_ANISOTROPY); + } +} +typedef ReferenceCaller1 TextureModeImportCaller; + +void TextureModeExport(ETexturesMode& self, const IntImportCallback& importer) +{ + switch(self) + { + case eTextures_NEAREST: + importer(0); + break; + case eTextures_NEAREST_MIPMAP_NEAREST: + importer(1); + break; + case eTextures_LINEAR: + importer(2); + break; + case eTextures_NEAREST_MIPMAP_LINEAR: + importer(3); + break; + case eTextures_LINEAR_MIPMAP_NEAREST: + importer(4); + break; + case eTextures_LINEAR_MIPMAP_LINEAR: + importer(5); + break; + case eTextures_MAX_ANISOTROPY: + importer(6); + break; + default: + importer(4); + } +} +typedef ReferenceCaller1 TextureModeExportCaller; + +void Textures_constructPreferences(PreferencesPage& page) +{ + { + const char* percentages[] = { "12.5%", "25%", "50%", "100%", }; + page.appendRadio( + "Texture Quality", + STRING_ARRAY_RANGE(percentages), + LatchedIntImportCaller(g_Textures_textureQuality), + IntExportCaller(g_Textures_textureQuality.m_latched) + ); + } + page.appendSpinner( + "Texture Gamma", + 1.0, + 0.0, + 1.0, + FloatImportCallback(TextureGammaImportCaller(g_texture_globals.fGamma)), + FloatExportCallback(FloatExportCaller(g_texture_globals.fGamma)) + ); + { + const char* texture_mode[] = { "Nearest", "Nearest Mipmap", "Linear", "Bilinear", "Bilinear Mipmap", "Trilinear", "Anisotropy" }; + page.appendCombo( + "Texture Render Mode", + STRING_ARRAY_RANGE(texture_mode), + IntImportCallback(TextureModeImportCaller(g_texture_mode)), + IntExportCallback(TextureModeExportCaller(g_texture_mode)) + ); + } + { + const char* compression_none[] = { "None" }; + const char* compression_opengl[] = { "None", "OpenGL ARB" }; + const char* compression_s3tc[] = { "None", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" }; + const char* compression_opengl_s3tc[] = { "None", "OpenGL ARB", "S3TC DXT1", "S3TC DXT3", "S3TC DXT5" }; + StringArrayRange compression( + (g_texture_globals.m_bOpenGLCompressionSupported) + ? (g_texture_globals.m_bS3CompressionSupported) + ? STRING_ARRAY_RANGE(compression_opengl_s3tc) + : STRING_ARRAY_RANGE(compression_opengl) + : (g_texture_globals.m_bS3CompressionSupported) + ? STRING_ARRAY_RANGE(compression_s3tc) + : STRING_ARRAY_RANGE(compression_none) + ); + page.appendCombo( + "Hardware Texture Compression", + compression, + TextureCompressionImportCaller(g_texture_globals.m_nTextureCompressionFormat), + IntExportCaller(reinterpret_cast(g_texture_globals.m_nTextureCompressionFormat)) + ); + } +} +void Textures_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Textures", "Texture Settings")); + Textures_constructPreferences(page); +} +void Textures_registerPreferencesPage() +{ + PreferencesDialog_addDisplayPage(FreeCaller1()); +} + +void TextureCompression_importString(const char* string) +{ + g_texture_globals.m_nTextureCompressionFormat = static_cast(atoi(string)); + Textures_UpdateTextureCompressionFormat(); +} +typedef FreeCaller1 TextureCompressionImportStringCaller; + + +void Textures_Construct() +{ + g_texturesmap = new TexturesMap; + + GlobalPreferenceSystem().registerPreference("TextureCompressionFormat", TextureCompressionImportStringCaller(), IntExportStringCaller(reinterpret_cast(g_texture_globals.m_nTextureCompressionFormat))); + GlobalPreferenceSystem().registerPreference("TextureFiltering", IntImportStringCaller(reinterpret_cast(g_texture_mode)), IntExportStringCaller(reinterpret_cast(g_texture_mode))); + GlobalPreferenceSystem().registerPreference("TextureQuality", IntImportStringCaller(g_Textures_textureQuality.m_latched), IntExportStringCaller(g_Textures_textureQuality.m_latched)); + GlobalPreferenceSystem().registerPreference("SI_Gamma", FloatImportStringCaller(g_texture_globals.fGamma), FloatExportStringCaller(g_texture_globals.fGamma)); + + g_Textures_textureQuality.useLatched(); + + Textures_registerPreferencesPage(); + + Textures_ModeChanged(); +} +void Textures_Destroy() +{ + delete g_texturesmap; +} + + +#include "modulesystem/modulesmap.h" +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +class TexturesDependencies : + public GlobalRadiantModuleRef, + public GlobalOpenGLModuleRef, + public GlobalPreferenceSystemModuleRef +{ + ImageModulesRef m_image_modules; +public: + TexturesDependencies() : + m_image_modules(GlobalRadiant().getRequiredGameDescriptionKeyValue("texturetypes")) + { + } + ImageModules& getImageModules() + { + return m_image_modules.get(); + } +}; + +class TexturesAPI +{ + TexturesCache* m_textures; +public: + typedef TexturesCache Type; + STRING_CONSTANT(Name, "*"); + + TexturesAPI() + { + Textures_Construct(); + + m_textures = &GetTexturesCache(); + } + ~TexturesAPI() + { + Textures_Destroy(); + } + TexturesCache* getTable() + { + return m_textures; + } +}; + +typedef SingletonModule TexturesModule; +typedef Static StaticTexturesModule; +StaticRegisterModule staticRegisterTextures(StaticTexturesModule::instance()); + +ImageModules& Textures_getImageModules() +{ + return StaticTexturesModule::instance().getDependencies().getImageModules(); +} + + + diff --git a/misc/mediasource/netradiant-src/radiant/textures.h b/misc/mediasource/netradiant-src/radiant/textures.h new file mode 100644 index 00000000..0a570b7d --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/textures.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 1999-2006 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 (INCLUDED_TEXTURES_H) +#define INCLUDED_TEXTURES_H + +#include "generic/callbackfwd.h" + +void Textures_Realise(); +void Textures_Unrealise(); +void Textures_sharedContextDestroyed(); + +void Textures_setModeChangedNotify(const Callback& notify); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/texwindow.cpp b/misc/mediasource/netradiant-src/radiant/texwindow.cpp new file mode 100644 index 00000000..95d490ab --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/texwindow.cpp @@ -0,0 +1,2723 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Texture Window +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "texwindow.h" + +#include "debugging/debugging.h" +#include "warnings.h" + +#include "ifilesystem.h" +#include "iundo.h" +#include "igl.h" +#include "iarchive.h" +#include "moduleobserver.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "signal/signal.h" +#include "math/vector.h" +#include "texturelib.h" +#include "string/string.h" +#include "shaderlib.h" +#include "os/file.h" +#include "os/path.h" +#include "stream/memstream.h" +#include "stream/textfilestream.h" +#include "stream/stringstream.h" +#include "cmdlib.h" +#include "texmanip.h" +#include "textures.h" +#include "convert.h" + +#include "gtkutil/menu.h" +#include "gtkutil/nonmodal.h" +#include "gtkutil/cursor.h" +#include "gtkutil/widget.h" +#include "gtkutil/glwidget.h" +#include "gtkutil/messagebox.h" + +#include "error.h" +#include "map.h" +#include "qgl.h" +#include "select.h" +#include "brush_primit.h" +#include "brushmanip.h" +#include "patchmanip.h" +#include "plugin.h" +#include "qe3.h" +#include "gtkdlgs.h" +#include "gtkmisc.h" +#include "mainframe.h" +#include "findtexturedialog.h" +#include "surfacedialog.h" +#include "patchdialog.h" +#include "groupdialog.h" +#include "preferences.h" +#include "shaders.h" +#include "commands.h" + +bool TextureBrowser_showWads() +{ + return !string_empty(g_pGameDescription->getKeyValue("show_wads")); +} + +void TextureBrowser_queueDraw(TextureBrowser& textureBrowser); + +bool string_equal_start(const char* string, StringRange start) +{ + return string_equal_n(string, start.first, start.last - start.first); +} + +typedef std::set TextureGroups; + +void TextureGroups_addWad(TextureGroups& groups, const char* archive) +{ + if(extension_equal(path_get_extension(archive), "wad")) + { +#if 1 + groups.insert(archive); +#else + CopiedString archiveBaseName(path_get_filename_start(archive), path_get_filename_base_end(archive)); + groups.insert(archiveBaseName); +#endif + } +} +typedef ReferenceCaller1 TextureGroupsAddWadCaller; + +void TextureGroups_addShader(TextureGroups& groups, const char* shaderName) +{ + const char* texture = path_make_relative(shaderName, "textures/"); + if(texture != shaderName) + { + const char* last = path_remove_directory(texture); + if(!string_empty(last)) + { + groups.insert(CopiedString(StringRange(texture, --last))); + } + } +} +typedef ReferenceCaller1 TextureGroupsAddShaderCaller; + +void TextureGroups_addDirectory(TextureGroups& groups, const char* directory) +{ + groups.insert(directory); +} +typedef ReferenceCaller1 TextureGroupsAddDirectoryCaller; + +namespace +{ + bool g_TextureBrowser_shaderlistOnly = false; + bool g_TextureBrowser_fixedSize = false; + bool g_TextureBrowser_filterNotex = false; +} + +class DeferredAdjustment +{ + gdouble m_value; + guint m_handler; + typedef void (*ValueChangedFunction)(void* data, gdouble value); + ValueChangedFunction m_function; + void* m_data; + + static gboolean deferred_value_changed(gpointer data) + { + reinterpret_cast(data)->m_function( + reinterpret_cast(data)->m_data, + reinterpret_cast(data)->m_value + ); + reinterpret_cast(data)->m_handler = 0; + reinterpret_cast(data)->m_value = 0; + return FALSE; + } +public: + DeferredAdjustment(ValueChangedFunction function, void* data) : m_value(0), m_handler(0), m_function(function), m_data(data) + { + } + void flush() + { + if(m_handler != 0) + { + g_source_remove(m_handler); + deferred_value_changed(this); + } + } + void value_changed(gdouble value) + { + m_value = value; + if(m_handler == 0) + { + m_handler = g_idle_add(deferred_value_changed, this); + } + } + static void adjustment_value_changed(GtkAdjustment *adjustment, DeferredAdjustment* self) + { + self->value_changed(adjustment->value); + } +}; + + + +class TextureBrowser; + +typedef ReferenceCaller TextureBrowserQueueDrawCaller; + +void TextureBrowser_scrollChanged(void* data, gdouble value); + + +enum StartupShaders +{ + STARTUPSHADERS_NONE = 0, + STARTUPSHADERS_COMMON, +}; + +void TextureBrowser_hideUnusedExport(const BoolImportCallback& importer); +typedef FreeCaller1 TextureBrowserHideUnusedExport; + +void TextureBrowser_showShadersExport(const BoolImportCallback& importer); +typedef FreeCaller1 TextureBrowserShowShadersExport; + +void TextureBrowser_showShaderlistOnly(const BoolImportCallback& importer); +typedef FreeCaller1 TextureBrowserShowShaderlistOnlyExport; + +void TextureBrowser_fixedSize(const BoolImportCallback& importer); +typedef FreeCaller1 TextureBrowserFixedSizeExport; + +void TextureBrowser_filterNotex(const BoolImportCallback& importer); +typedef FreeCaller1 TextureBrowserFilterNotexExport; + +class TextureBrowser +{ +public: + int width, height; + int originy; + int m_nTotalHeight; + + CopiedString shader; + + GtkWindow* m_parent; + GtkWidget* m_gl_widget; + GtkWidget* m_texture_scroll; + GtkWidget* m_treeViewTree; + GtkWidget* m_treeViewTags; + GtkWidget* m_tag_frame; + GtkListStore* m_assigned_store; + GtkListStore* m_available_store; + GtkWidget* m_assigned_tree; + GtkWidget* m_available_tree; + GtkWidget* m_scr_win_tree; + GtkWidget* m_scr_win_tags; + GtkWidget* m_tag_notebook; + GtkWidget* m_search_button; + GtkWidget* m_shader_info_item; + + std::set m_all_tags; + GtkListStore* m_all_tags_list; + std::vector m_copied_tags; + std::set m_found_shaders; + + ToggleItem m_hideunused_item; + ToggleItem m_showshaders_item; + ToggleItem m_showshaderlistonly_item; + ToggleItem m_fixedsize_item; + ToggleItem m_filternotex_item; + + guint m_sizeHandler; + guint m_exposeHandler; + + bool m_heightChanged; + bool m_originInvalid; + + DeferredAdjustment m_scrollAdjustment; + FreezePointer m_freezePointer; + + Vector3 color_textureback; + // the increment step we use against the wheel mouse + std::size_t m_mouseWheelScrollIncrement; + std::size_t m_textureScale; + // make the texture increments match the grid changes + bool m_showShaders; + bool m_showTextureScrollbar; + StartupShaders m_startupShaders; + // if true, the texture window will only display in-use shaders + // if false, all the shaders in memory are displayed + bool m_hideUnused; + bool m_rmbSelected; + bool m_searchedTags; + bool m_tags; + // The uniform size (in pixels) that textures are resized to when m_resizeTextures is true. + int m_uniformTextureSize; + // Return the display width of a texture in the texture browser + int getTextureWidth(qtexture_t* tex) + { + int width; + if (!g_TextureBrowser_fixedSize) + { + // Don't use uniform size + width = (int)(tex->width * ((float)m_textureScale / 100)); + } else if + (tex->width >= tex->height) + { + // Texture is square, or wider than it is tall + width = m_uniformTextureSize; + } else { + // Otherwise, preserve the texture's aspect ratio + width = (int)(m_uniformTextureSize * ((float)tex->width / tex->height)); + } + return width; + } + // Return the display height of a texture in the texture browser + int getTextureHeight(qtexture_t* tex) + { + int height; + if (!g_TextureBrowser_fixedSize) + { + // Don't use uniform size + height = (int)(tex->height * ((float)m_textureScale / 100)); + } else if (tex->height >= tex->width) + { + // Texture is square, or taller than it is wide + height = m_uniformTextureSize; + } else { + // Otherwise, preserve the texture's aspect ratio + height = (int)(m_uniformTextureSize * ((float)tex->height / tex->width)); + } + return height; + } + + TextureBrowser() : + m_texture_scroll(0), + m_hideunused_item(TextureBrowserHideUnusedExport()), + m_showshaders_item(TextureBrowserShowShadersExport()), + m_showshaderlistonly_item(TextureBrowserShowShaderlistOnlyExport()), + m_fixedsize_item(TextureBrowserFixedSizeExport()), + m_filternotex_item(TextureBrowserFilterNotexExport()), + m_heightChanged(true), + m_originInvalid(true), + m_scrollAdjustment(TextureBrowser_scrollChanged, this), + color_textureback(0.25f, 0.25f, 0.25f), + m_mouseWheelScrollIncrement(64), + m_textureScale(50), + m_showShaders(true), + m_showTextureScrollbar(true), + m_startupShaders(STARTUPSHADERS_NONE), + m_hideUnused(false), + m_rmbSelected(false), + m_searchedTags(false), + m_tags(false), + m_uniformTextureSize(128) + { + } +}; + +void(*TextureBrowser_textureSelected)(const char* shader); + + +void TextureBrowser_updateScroll(TextureBrowser& textureBrowser); + + +const char* TextureBrowser_getComonShadersName() +{ + const char* value = g_pGameDescription->getKeyValue("common_shaders_name"); + if(!string_empty(value)) + { + return value; + } + return "Common"; +} + +const char* TextureBrowser_getComonShadersDir() +{ + const char* value = g_pGameDescription->getKeyValue("common_shaders_dir"); + if(!string_empty(value)) + { + return value; + } + return "common/"; +} + +inline int TextureBrowser_fontHeight(TextureBrowser& textureBrowser) +{ + return GlobalOpenGL().m_font->getPixelHeight(); +} + +const char* TextureBrowser_GetSelectedShader(TextureBrowser& textureBrowser) +{ + return textureBrowser.shader.c_str(); +} + +void TextureBrowser_SetStatus(TextureBrowser& textureBrowser, const char* name) +{ + IShader* shader = QERApp_Shader_ForName( name); + qtexture_t* q = shader->getTexture(); + StringOutputStream strTex(256); + strTex << name << " W: " << Unsigned(q->width) << " H: " << Unsigned(q->height); + shader->DecRef(); + g_pParentWnd->SetStatusText(g_pParentWnd->m_texture_status, strTex.c_str()); +} + +void TextureBrowser_Focus(TextureBrowser& textureBrowser, const char* name); + +void TextureBrowser_SetSelectedShader(TextureBrowser& textureBrowser, const char* shader) +{ + textureBrowser.shader = shader; + TextureBrowser_SetStatus(textureBrowser, shader); + TextureBrowser_Focus(textureBrowser, shader); + + if(FindTextureDialog_isOpen()) + { + FindTextureDialog_selectTexture(shader); + } + + // disable the menu item "shader info" if no shader was selected + IShader* ishader = QERApp_Shader_ForName(shader); + CopiedString filename = ishader->getShaderFileName(); + + if(filename.empty()) + { + if(textureBrowser.m_shader_info_item != NULL) + { + gtk_widget_set_sensitive(textureBrowser.m_shader_info_item, FALSE); + } + } else { + gtk_widget_set_sensitive(textureBrowser.m_shader_info_item, TRUE); + } + + ishader->DecRef(); +} + + +CopiedString g_TextureBrowser_currentDirectory; + +/* +============================================================================ + +TEXTURE LAYOUT + +TTimo: now based on a rundown through all the shaders +NOTE: we expect the Active shaders count doesn't change during a Texture_StartPos .. Texture_NextPos cycle + otherwise we may need to rely on a list instead of an array storage +============================================================================ +*/ + +class TextureLayout +{ +public: + // texture layout functions + // TTimo: now based on shaders + int current_x, current_y, current_row; +}; + +void Texture_StartPos(TextureLayout& layout) +{ + layout.current_x = 8; + layout.current_y = -8; + layout.current_row = 0; +} + +void Texture_NextPos(TextureBrowser& textureBrowser, TextureLayout& layout, qtexture_t* current_texture, int *x, int *y) +{ + qtexture_t* q = current_texture; + + int nWidth = textureBrowser.getTextureWidth(q); + int nHeight = textureBrowser.getTextureHeight(q); + if (layout.current_x + nWidth > textureBrowser.width-8 && layout.current_row) + { // go to the next row unless the texture is the first on the row + layout.current_x = 8; + layout.current_y -= layout.current_row + TextureBrowser_fontHeight(textureBrowser) + 4; + layout.current_row = 0; + } + + *x = layout.current_x; + *y = layout.current_y; + + // Is our texture larger than the row? If so, grow the + // row height to match it + + if (layout.current_row < nHeight) + layout.current_row = nHeight; + + // never go less than 96, or the names get all crunched up + layout.current_x += nWidth < 96 ? 96 : nWidth; + layout.current_x += 8; +} + +bool TextureSearch_IsShown(const char* name) +{ + std::set::iterator iter; + + iter = GlobalTextureBrowser().m_found_shaders.find(name); + + if(iter == GlobalTextureBrowser().m_found_shaders.end()) + { + return false; + } else { + return true; + } +} + +CopiedString g_notex; +CopiedString g_shadernotex; + +// if texture_showinuse jump over non in-use textures +bool Texture_IsShown(IShader* shader, bool show_shaders, bool hideUnused) +{ + // filter notex / shadernotex images + if(g_TextureBrowser_filterNotex && (string_equal(g_notex.c_str(), shader->getTexture()->name) || string_equal(g_shadernotex.c_str(), shader->getTexture()->name))) + { + return false; + } + + if(g_TextureBrowser_currentDirectory == "Untagged") + { + std::set::iterator iter; + + iter = GlobalTextureBrowser().m_found_shaders.find(shader->getName()); + + if(iter == GlobalTextureBrowser().m_found_shaders.end()) + { + return false; + } else { + return true; + } + } + + if(!shader_equal_prefix(shader->getName(), "textures/")) + return false; + + if (!show_shaders && !shader->IsDefault()) + return false; + + if(hideUnused && !shader->IsInUse()) + return false; + + if(GlobalTextureBrowser().m_searchedTags) + { + if(!TextureSearch_IsShown(shader->getName())) + { + return false; + } else { + return true; + } + } else { + if(!shader_equal_prefix(shader_get_textureName(shader->getName()), g_TextureBrowser_currentDirectory.c_str())) + { + return false; + } + } + + return true; +} + +void TextureBrowser_heightChanged(TextureBrowser& textureBrowser) +{ + textureBrowser.m_heightChanged = true; + + TextureBrowser_updateScroll(textureBrowser); + TextureBrowser_queueDraw(textureBrowser); +} + +void TextureBrowser_evaluateHeight(TextureBrowser& textureBrowser) +{ + if(textureBrowser.m_heightChanged) + { + textureBrowser.m_heightChanged = false; + + textureBrowser.m_nTotalHeight = 0; + + TextureLayout layout; + Texture_StartPos(layout); + for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) + { + IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); + + if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) + continue; + + int x, y; + Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); + textureBrowser.m_nTotalHeight = std::max(textureBrowser.m_nTotalHeight, abs(layout.current_y) + TextureBrowser_fontHeight(textureBrowser) + textureBrowser.getTextureHeight(shader->getTexture()) + 4); + } + } +} + +int TextureBrowser_TotalHeight(TextureBrowser& textureBrowser) +{ + TextureBrowser_evaluateHeight(textureBrowser); + return textureBrowser.m_nTotalHeight; +} + +inline const int& min_int(const int& left, const int& right) +{ + return std::min(left, right); +} + +void TextureBrowser_clampOriginY(TextureBrowser& textureBrowser) +{ + if(textureBrowser.originy > 0) + { + textureBrowser.originy = 0; + } + int lower = min_int(textureBrowser.height - TextureBrowser_TotalHeight(textureBrowser), 0); + if(textureBrowser.originy < lower) + { + textureBrowser.originy = lower; + } +} + +int TextureBrowser_getOriginY(TextureBrowser& textureBrowser) +{ + if(textureBrowser.m_originInvalid) + { + textureBrowser.m_originInvalid = false; + TextureBrowser_clampOriginY(textureBrowser); + TextureBrowser_updateScroll(textureBrowser); + } + return textureBrowser.originy; +} + +void TextureBrowser_setOriginY(TextureBrowser& textureBrowser, int originy) +{ + textureBrowser.originy = originy; + TextureBrowser_clampOriginY(textureBrowser); + TextureBrowser_updateScroll(textureBrowser); + TextureBrowser_queueDraw(textureBrowser); +} + + +Signal0 g_activeShadersChangedCallbacks; + +void TextureBrowser_addActiveShadersChangedCallback(const SignalHandler& handler) +{ + g_activeShadersChangedCallbacks.connectLast(handler); +} + +class ShadersObserver : public ModuleObserver +{ + Signal0 m_realiseCallbacks; +public: + void realise() + { + m_realiseCallbacks(); + } + void unrealise() + { + } + void insert(const SignalHandler& handler) + { + m_realiseCallbacks.connectLast(handler); + } +}; + +namespace +{ + ShadersObserver g_ShadersObserver; +} + +void TextureBrowser_addShadersRealiseCallback(const SignalHandler& handler) +{ + g_ShadersObserver.insert(handler); +} + +void TextureBrowser_activeShadersChanged(TextureBrowser& textureBrowser) +{ + TextureBrowser_heightChanged(textureBrowser); + textureBrowser.m_originInvalid = true; + + g_activeShadersChangedCallbacks(); +} + +void TextureBrowser_importShowScrollbar(TextureBrowser& textureBrowser, bool value) +{ + textureBrowser.m_showTextureScrollbar = value; + if(textureBrowser.m_texture_scroll != 0) + { + widget_set_visible(textureBrowser.m_texture_scroll, textureBrowser.m_showTextureScrollbar); + TextureBrowser_updateScroll(textureBrowser); + } +} +typedef ReferenceCaller1 TextureBrowserImportShowScrollbarCaller; + + +/* +============== +TextureBrowser_ShowDirectory +relies on texture_directory global for the directory to use +1) Load the shaders for the given directory +2) Scan the remaining texture, load them and assign them a default shader (the "noshader" shader) +NOTE: when writing a texture plugin, or some texture extensions, this function may need to be overriden, and made + available through the IShaders interface +NOTE: for texture window layout: + all shaders are stored with alphabetical order after load + previously loaded and displayed stuff is hidden, only in-use and newly loaded is shown + ( the GL textures are not flushed though) +============== +*/ + +bool endswith(const char *haystack, const char *needle) +{ + size_t lh = strlen(haystack); + size_t ln = strlen(needle); + if(lh < ln) + return false; + return !memcmp(haystack + (lh - ln), needle, ln); +} + +bool texture_name_ignore(const char* name) +{ + StringOutputStream strTemp(string_length(name)); + strTemp << LowerCase(name); + + return + endswith(strTemp.c_str(), ".specular") || + endswith(strTemp.c_str(), ".glow") || + endswith(strTemp.c_str(), ".bump") || + endswith(strTemp.c_str(), ".diffuse") || + endswith(strTemp.c_str(), ".blend") || + endswith(strTemp.c_str(), ".alpha") || + endswith(strTemp.c_str(), "_norm") || + endswith(strTemp.c_str(), "_bump") || + endswith(strTemp.c_str(), "_glow") || + endswith(strTemp.c_str(), "_gloss") || + endswith(strTemp.c_str(), "_pants") || + endswith(strTemp.c_str(), "_shirt") || + endswith(strTemp.c_str(), "_reflect") || + endswith(strTemp.c_str(), "_alpha") || + 0; +} + +class LoadShaderVisitor : public Archive::Visitor +{ +public: + void visit(const char* name) + { + IShader* shader = QERApp_Shader_ForName(CopiedString(StringRange(name, path_get_filename_base_end(name))).c_str()); + shader->DecRef(); + } +}; + +void TextureBrowser_SetHideUnused(TextureBrowser& textureBrowser, bool hideUnused); + +GtkWidget* g_page_textures; + +void TextureBrowser_toggleShow() +{ + GroupDialog_showPage(g_page_textures); +} + + +void TextureBrowser_updateTitle() +{ + GroupDialog_updatePageTitle(g_page_textures); +} + + + +class TextureCategoryLoadShader +{ + const char* m_directory; + std::size_t& m_count; +public: + typedef const char* first_argument_type; + + TextureCategoryLoadShader(const char* directory, std::size_t& count) + : m_directory(directory), m_count(count) + { + m_count = 0; + } + void operator()(const char* name) const + { + if(shader_equal_prefix(name, "textures/") + && shader_equal_prefix(name + string_length("textures/"), m_directory)) + { + ++m_count; + // request the shader, this will load the texture if needed + // this Shader_ForName call is a kind of hack + IShader *pFoo = QERApp_Shader_ForName(name); + pFoo->DecRef(); + } + } +}; + +void TextureDirectory_loadTexture(const char* directory, const char* texture) +{ + StringOutputStream name(256); + name << directory << StringRange(texture, path_get_filename_base_end(texture)); + + if(texture_name_ignore(name.c_str())) + { + return; + } + + if (!shader_valid(name.c_str())) + { + globalOutputStream() << "Skipping invalid texture name: [" << name.c_str() << "]\n"; + return; + } + + // if a texture is already in use to represent a shader, ignore it + IShader* shader = QERApp_Shader_ForName(name.c_str()); + shader->DecRef(); +} +typedef ConstPointerCaller1 TextureDirectoryLoadTextureCaller; + +class LoadTexturesByTypeVisitor : public ImageModules::Visitor +{ + const char* m_dirstring; +public: + LoadTexturesByTypeVisitor(const char* dirstring) + : m_dirstring(dirstring) + { + } + void visit(const char* minor, const _QERPlugImageTable& table) const + { + GlobalFileSystem().forEachFile(m_dirstring, minor, TextureDirectoryLoadTextureCaller(m_dirstring)); + } +}; + +void TextureBrowser_ShowDirectory(TextureBrowser& textureBrowser, const char* directory) +{ + if(TextureBrowser_showWads()) + { + Archive* archive = GlobalFileSystem().getArchive(directory); + ASSERT_NOTNULL(archive); + LoadShaderVisitor visitor; + archive->forEachFile(Archive::VisitorFunc(visitor, Archive::eFiles, 0), "textures/"); + } + else + { + g_TextureBrowser_currentDirectory = directory; + TextureBrowser_heightChanged(textureBrowser); + + std::size_t shaders_count; + GlobalShaderSystem().foreachShaderName(makeCallback1(TextureCategoryLoadShader(directory, shaders_count))); + globalOutputStream() << "Showing " << Unsigned(shaders_count) << " shaders.\n"; + + if(g_pGameDescription->mGameType != "doom3") + { + // load remaining texture files + + StringOutputStream dirstring(64); + dirstring << "textures/" << directory; + + Radiant_getImageModules().foreachModule(LoadTexturesByTypeVisitor(dirstring.c_str())); + } + } + + // we'll display the newly loaded textures + all the ones already in use + TextureBrowser_SetHideUnused(textureBrowser, false); + + TextureBrowser_updateTitle(); +} + +void TextureBrowser_ShowTagSearchResult(TextureBrowser& textureBrowser, const char* directory) +{ + g_TextureBrowser_currentDirectory = directory; + TextureBrowser_heightChanged(textureBrowser); + + std::size_t shaders_count; + GlobalShaderSystem().foreachShaderName(makeCallback1(TextureCategoryLoadShader(directory, shaders_count))); + globalOutputStream() << "Showing " << Unsigned(shaders_count) << " shaders.\n"; + + if(g_pGameDescription->mGameType != "doom3") + { + // load remaining texture files + StringOutputStream dirstring(64); + dirstring << "textures/" << directory; + + { + LoadTexturesByTypeVisitor visitor(dirstring.c_str()); + Radiant_getImageModules().foreachModule(visitor); + } + } + + // we'll display the newly loaded textures + all the ones already in use + TextureBrowser_SetHideUnused(textureBrowser, false); +} + + +bool TextureBrowser_hideUnused(); + +void TextureBrowser_hideUnusedExport(const BoolImportCallback& importer) +{ + importer(TextureBrowser_hideUnused()); +} +typedef FreeCaller1 TextureBrowserHideUnusedExport; + +void TextureBrowser_showShadersExport(const BoolImportCallback& importer) +{ + importer(GlobalTextureBrowser().m_showShaders); +} +typedef FreeCaller1 TextureBrowserShowShadersExport; + +void TextureBrowser_showShaderlistOnly(const BoolImportCallback& importer) +{ + importer(g_TextureBrowser_shaderlistOnly); +} +typedef FreeCaller1 TextureBrowserShowShaderlistOnlyExport; + +void TextureBrowser_fixedSize(const BoolImportCallback& importer) +{ + importer(g_TextureBrowser_fixedSize); +} +typedef FreeCaller1 TextureBrowser_FixedSizeExport; + +void TextureBrowser_filterNotex(const BoolImportCallback& importer) +{ + importer(g_TextureBrowser_filterNotex); +} +typedef FreeCaller1 TextureBrowser_filterNotexExport; + +void TextureBrowser_SetHideUnused(TextureBrowser& textureBrowser, bool hideUnused) +{ + if(hideUnused) + { + textureBrowser.m_hideUnused = true; + } + else + { + textureBrowser.m_hideUnused = false; + } + + textureBrowser.m_hideunused_item.update(); + + TextureBrowser_heightChanged(textureBrowser); + textureBrowser.m_originInvalid = true; +} + +void TextureBrowser_ShowStartupShaders(TextureBrowser& textureBrowser) +{ + if(textureBrowser.m_startupShaders == STARTUPSHADERS_COMMON) + { + TextureBrowser_ShowDirectory(textureBrowser, TextureBrowser_getComonShadersDir()); + } +} + + +//++timo NOTE: this is a mix of Shader module stuff and texture explorer +// it might need to be split in parts or moved out .. dunno +// scroll origin so the specified texture is completely on screen +// if current texture is not displayed, nothing is changed +void TextureBrowser_Focus(TextureBrowser& textureBrowser, const char* name) +{ + TextureLayout layout; + // scroll origin so the texture is completely on screen + Texture_StartPos(layout); + + for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) + { + IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); + + if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) + continue; + + int x, y; + Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); + qtexture_t* q = shader->getTexture(); + if (!q) + break; + + // we have found when texdef->name and the shader name match + // NOTE: as everywhere else for our comparisons, we are not case sensitive + if (shader_equal(name, shader->getName())) + { + int textureHeight = (int)(q->height * ((float)textureBrowser.m_textureScale / 100)) + + 2 * TextureBrowser_fontHeight(textureBrowser); + + int originy = TextureBrowser_getOriginY(textureBrowser); + if (y > originy) + { + originy = y; + } + + if (y - textureHeight < originy - textureBrowser.height) + { + originy = (y - textureHeight) + textureBrowser.height; + } + + TextureBrowser_setOriginY(textureBrowser, originy); + return; + } + } +} + +IShader* Texture_At(TextureBrowser& textureBrowser, int mx, int my) +{ + my += TextureBrowser_getOriginY(textureBrowser) - textureBrowser.height; + + TextureLayout layout; + Texture_StartPos(layout); + for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) + { + IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); + + if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) + continue; + + int x, y; + Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); + qtexture_t *q = shader->getTexture(); + if (!q) + break; + + int nWidth = textureBrowser.getTextureWidth(q); + int nHeight = textureBrowser.getTextureHeight(q); + if (mx > x && mx - x < nWidth + && my < y && y - my < nHeight + TextureBrowser_fontHeight(textureBrowser)) + { + return shader; + } + } + + return 0; +} + +/* +============== +SelectTexture + + By mouse click +============== +*/ +void SelectTexture(TextureBrowser& textureBrowser, int mx, int my, bool bShift) +{ + IShader* shader = Texture_At(textureBrowser, mx, my); + if(shader != 0) + { + if (bShift) + { + if (shader->IsDefault()) + globalOutputStream() << "ERROR: " << shader->getName() << " is not a shader, it's a texture.\n"; + else + ViewShader( shader->getShaderFileName(), shader->getName() ); + } + else + { + TextureBrowser_SetSelectedShader(textureBrowser, shader->getName()); + TextureBrowser_textureSelected(shader->getName()); + + if (!FindTextureDialog_isOpen() && !textureBrowser.m_rmbSelected) + { + UndoableCommand undo("textureNameSetSelected"); + Select_SetShader(shader->getName()); + } + } + } +} + +/* +============================================================================ + + MOUSE ACTIONS + +============================================================================ +*/ + +void TextureBrowser_trackingDelta(int x, int y, unsigned int state, void* data) +{ + TextureBrowser& textureBrowser = *reinterpret_cast(data); + if(y != 0) + { + int scale = 1; + + if(state & GDK_SHIFT_MASK) + scale = 4; + + int originy = TextureBrowser_getOriginY(textureBrowser); + originy += y * scale; + TextureBrowser_setOriginY(textureBrowser, originy); + } +} + +void TextureBrowser_Tracking_MouseDown(TextureBrowser& textureBrowser) +{ + textureBrowser.m_freezePointer.freeze_pointer(textureBrowser.m_parent, TextureBrowser_trackingDelta, &textureBrowser); +} + +void TextureBrowser_Tracking_MouseUp(TextureBrowser& textureBrowser) +{ + textureBrowser.m_freezePointer.unfreeze_pointer(textureBrowser.m_parent); +} + +void TextureBrowser_Selection_MouseDown(TextureBrowser& textureBrowser, guint32 flags, int pointx, int pointy) +{ + SelectTexture(textureBrowser, pointx, textureBrowser.height - 1 - pointy, (flags & GDK_SHIFT_MASK) != 0); +} + +/* +============================================================================ + +DRAWING + +============================================================================ +*/ + +/* +============ +Texture_Draw +TTimo: relying on the shaders list to display the textures +we must query all qtexture_t* to manage and display through the IShaders interface +this allows a plugin to completely override the texture system +============ +*/ +void Texture_Draw(TextureBrowser& textureBrowser) +{ + int originy = TextureBrowser_getOriginY(textureBrowser); + + glClearColor(textureBrowser.color_textureback[0], + textureBrowser.color_textureback[1], + textureBrowser.color_textureback[2], + 0); + glViewport(0, 0, textureBrowser.width, textureBrowser.height); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + + glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glDisable (GL_DEPTH_TEST); + glDisable(GL_BLEND); + glOrtho (0, textureBrowser.width, originy-textureBrowser.height, originy, -100, 100); + glEnable (GL_TEXTURE_2D); + + glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); + + int last_y = 0, last_height = 0; + + TextureLayout layout; + Texture_StartPos(layout); + for(QERApp_ActiveShaders_IteratorBegin(); !QERApp_ActiveShaders_IteratorAtEnd(); QERApp_ActiveShaders_IteratorIncrement()) + { + IShader* shader = QERApp_ActiveShaders_IteratorCurrent(); + + if(!Texture_IsShown(shader, textureBrowser.m_showShaders, textureBrowser.m_hideUnused)) + continue; + + int x, y; + Texture_NextPos(textureBrowser, layout, shader->getTexture(), &x, &y); + qtexture_t *q = shader->getTexture(); + if (!q) + break; + + int nWidth = textureBrowser.getTextureWidth(q); + int nHeight = textureBrowser.getTextureHeight(q); + + if (y != last_y) + { + last_y = y; + last_height = 0; + } + last_height = std::max (nHeight, last_height); + + // Is this texture visible? + if ((y-nHeight-TextureBrowser_fontHeight(textureBrowser) < originy) + && (y > originy - textureBrowser.height)) + { + // borders rules: + // if it's the current texture, draw a thick red line, else: + // shaders have a white border, simple textures don't + // if !texture_showinuse: (some textures displayed may not be in use) + // draw an additional square around with 0.5 1 0.5 color + if (shader_equal(TextureBrowser_GetSelectedShader(textureBrowser), shader->getName())) + { + glLineWidth (3); + if(textureBrowser.m_rmbSelected) + { + glColor3f (0,0,1); + } else { + glColor3f (1,0,0); + } + glDisable (GL_TEXTURE_2D); + + glBegin (GL_LINE_LOOP); + glVertex2i (x-4,y-TextureBrowser_fontHeight(textureBrowser)+4); + glVertex2i (x-4,y-TextureBrowser_fontHeight(textureBrowser)-nHeight-4); + glVertex2i (x+4+nWidth,y-TextureBrowser_fontHeight(textureBrowser)-nHeight-4); + glVertex2i (x+4+nWidth,y-TextureBrowser_fontHeight(textureBrowser)+4); + glEnd(); + + glEnable (GL_TEXTURE_2D); + glLineWidth (1); + } + else + { + glLineWidth (1); + // shader border: + if (!shader->IsDefault()) + { + glColor3f (1,1,1); + glDisable (GL_TEXTURE_2D); + + glBegin (GL_LINE_LOOP); + glVertex2i (x-1,y+1-TextureBrowser_fontHeight(textureBrowser)); + glVertex2i (x-1,y-nHeight-1-TextureBrowser_fontHeight(textureBrowser)); + glVertex2i (x+1+nWidth,y-nHeight-1-TextureBrowser_fontHeight(textureBrowser)); + glVertex2i (x+1+nWidth,y+1-TextureBrowser_fontHeight(textureBrowser)); + glEnd(); + glEnable (GL_TEXTURE_2D); + } + + // highlight in-use textures + if (!textureBrowser.m_hideUnused && shader->IsInUse()) + { + glColor3f (0.5,1,0.5); + glDisable (GL_TEXTURE_2D); + glBegin (GL_LINE_LOOP); + glVertex2i (x-3,y+3-TextureBrowser_fontHeight(textureBrowser)); + glVertex2i (x-3,y-nHeight-3-TextureBrowser_fontHeight(textureBrowser)); + glVertex2i (x+3+nWidth,y-nHeight-3-TextureBrowser_fontHeight(textureBrowser)); + glVertex2i (x+3+nWidth,y+3-TextureBrowser_fontHeight(textureBrowser)); + glEnd(); + glEnable (GL_TEXTURE_2D); + } + } + + // Draw the texture + glBindTexture (GL_TEXTURE_2D, q->texture_number); + GlobalOpenGL_debugAssertNoErrors(); + glColor3f (1,1,1); + glBegin (GL_QUADS); + glTexCoord2i (0,0); + glVertex2i (x,y-TextureBrowser_fontHeight(textureBrowser)); + glTexCoord2i (1,0); + glVertex2i (x+nWidth,y-TextureBrowser_fontHeight(textureBrowser)); + glTexCoord2i (1,1); + glVertex2i (x+nWidth,y-TextureBrowser_fontHeight(textureBrowser)-nHeight); + glTexCoord2i (0,1); + glVertex2i (x,y-TextureBrowser_fontHeight(textureBrowser)-nHeight); + glEnd(); + + // draw the texture name + glDisable (GL_TEXTURE_2D); + glColor3f (1,1,1); + + glRasterPos2i (x, y-TextureBrowser_fontHeight(textureBrowser)+5); + + // don't draw the directory name + const char* name = shader->getName(); + name += strlen(name); + while(name != shader->getName() && *(name-1) != '/' && *(name-1) != '\\') + name--; + + GlobalOpenGL().drawString(name); + glEnable (GL_TEXTURE_2D); + } + + //int totalHeight = abs(y) + last_height + TextureBrowser_fontHeight(textureBrowser) + 4; + } + + + // reset the current texture + glBindTexture(GL_TEXTURE_2D, 0); + //qglFinish(); +} + +void TextureBrowser_queueDraw(TextureBrowser& textureBrowser) +{ + if(textureBrowser.m_gl_widget != 0) + { + gtk_widget_queue_draw(textureBrowser.m_gl_widget); + } +} + + +void TextureBrowser_setScale(TextureBrowser& textureBrowser, std::size_t scale) +{ + textureBrowser.m_textureScale = scale; + + TextureBrowser_queueDraw(textureBrowser); +} + + +void TextureBrowser_MouseWheel(TextureBrowser& textureBrowser, bool bUp) +{ + int originy = TextureBrowser_getOriginY(textureBrowser); + + if (bUp) + { + originy += int(textureBrowser.m_mouseWheelScrollIncrement); + } + else + { + originy -= int(textureBrowser.m_mouseWheelScrollIncrement); + } + + TextureBrowser_setOriginY(textureBrowser, originy); +} + +XmlTagBuilder TagBuilder; + +enum +{ + TAG_COLUMN, + N_COLUMNS +}; + +void BuildStoreAssignedTags(GtkListStore* store, const char* shader, TextureBrowser* textureBrowser) +{ + GtkTreeIter iter; + + gtk_list_store_clear(store); + + std::vector assigned_tags; + TagBuilder.GetShaderTags(shader, assigned_tags); + + for (size_t i = 0; i < assigned_tags.size(); i++) + { + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, TAG_COLUMN, assigned_tags[i].c_str(), -1); + } +} + +void BuildStoreAvailableTags( GtkListStore* storeAvailable, + GtkListStore* storeAssigned, + const std::set& allTags, + TextureBrowser* textureBrowser) +{ + GtkTreeIter iterAssigned; + GtkTreeIter iterAvailable; + std::set::const_iterator iterAll; + gchar* tag_assigned; + + gtk_list_store_clear(storeAvailable); + + bool row = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(storeAssigned), &iterAssigned) != 0; + + if(!row) // does the shader have tags assigned? + { + for (iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll) + { + gtk_list_store_append (storeAvailable, &iterAvailable); + gtk_list_store_set (storeAvailable, &iterAvailable, TAG_COLUMN, (*iterAll).c_str(), -1); + } + } + else + { + while(row) // available tags = all tags - assigned tags + { + gtk_tree_model_get(GTK_TREE_MODEL(storeAssigned), &iterAssigned, TAG_COLUMN, &tag_assigned, -1); + + for (iterAll = allTags.begin(); iterAll != allTags.end(); ++iterAll) + { + if(strcmp((char*)tag_assigned, (*iterAll).c_str()) != 0) + { + gtk_list_store_append (storeAvailable, &iterAvailable); + gtk_list_store_set (storeAvailable, &iterAvailable, TAG_COLUMN, (*iterAll).c_str(), -1); + } + else + { + row = gtk_tree_model_iter_next(GTK_TREE_MODEL(storeAssigned), &iterAssigned) != 0; + + if(row) + { + gtk_tree_model_get(GTK_TREE_MODEL(storeAssigned), &iterAssigned, TAG_COLUMN, &tag_assigned, -1); + } + } + } + } + } +} + +gboolean TextureBrowser_button_press(GtkWidget* widget, GdkEventButton* event, TextureBrowser* textureBrowser) +{ + if(event->type == GDK_BUTTON_PRESS) + { + if(event->button == 3) + { + if(GlobalTextureBrowser().m_tags) + { + textureBrowser->m_rmbSelected = true; + TextureBrowser_Selection_MouseDown (*textureBrowser, event->state, static_cast(event->x), static_cast(event->y)); + + BuildStoreAssignedTags(textureBrowser->m_assigned_store, textureBrowser->shader.c_str(), textureBrowser); + BuildStoreAvailableTags(textureBrowser->m_available_store, textureBrowser->m_assigned_store, textureBrowser->m_all_tags, textureBrowser); + textureBrowser->m_heightChanged = true; + gtk_widget_show(textureBrowser->m_tag_frame); + + process_gui(); + + TextureBrowser_Focus(*textureBrowser, textureBrowser->shader.c_str()); + } + else + { + TextureBrowser_Tracking_MouseDown(*textureBrowser); + } + } + else if(event->button == 1) + { + TextureBrowser_Selection_MouseDown(*textureBrowser, event->state, static_cast(event->x), static_cast(event->y)); + + if(GlobalTextureBrowser().m_tags) + { + textureBrowser->m_rmbSelected = false; + gtk_widget_hide(textureBrowser->m_tag_frame); + } + } + } + return FALSE; +} + +gboolean TextureBrowser_button_release(GtkWidget* widget, GdkEventButton* event, TextureBrowser* textureBrowser) +{ + if(event->type == GDK_BUTTON_RELEASE) + { + if(event->button == 3) + { + if(!GlobalTextureBrowser().m_tags) + { + TextureBrowser_Tracking_MouseUp(*textureBrowser); + } + } + } + return FALSE; +} + +gboolean TextureBrowser_motion(GtkWidget *widget, GdkEventMotion *event, TextureBrowser* textureBrowser) +{ + return FALSE; +} + +gboolean TextureBrowser_scroll(GtkWidget* widget, GdkEventScroll* event, TextureBrowser* textureBrowser) +{ + if(event->direction == GDK_SCROLL_UP) + { + TextureBrowser_MouseWheel(*textureBrowser, true); + } + else if(event->direction == GDK_SCROLL_DOWN) + { + TextureBrowser_MouseWheel(*textureBrowser, false); + } + return FALSE; +} + +void TextureBrowser_scrollChanged(void* data, gdouble value) +{ + //globalOutputStream() << "vertical scroll\n"; + TextureBrowser_setOriginY(*reinterpret_cast(data), -(int)value); +} + +static void TextureBrowser_verticalScroll(GtkAdjustment *adjustment, TextureBrowser* textureBrowser) +{ + textureBrowser->m_scrollAdjustment.value_changed(adjustment->value); +} + +void TextureBrowser_updateScroll(TextureBrowser& textureBrowser) +{ + if(textureBrowser.m_showTextureScrollbar) + { + int totalHeight = TextureBrowser_TotalHeight(textureBrowser); + + totalHeight = std::max(totalHeight, textureBrowser.height); + + GtkAdjustment *vadjustment = gtk_range_get_adjustment(GTK_RANGE(textureBrowser.m_texture_scroll)); + + vadjustment->value = -TextureBrowser_getOriginY(textureBrowser); + vadjustment->page_size = textureBrowser.height; + vadjustment->page_increment = textureBrowser.height/2; + vadjustment->step_increment = 20; + vadjustment->lower = 0; + vadjustment->upper = totalHeight; + + g_signal_emit_by_name(G_OBJECT (vadjustment), "changed"); + } +} + +gboolean TextureBrowser_size_allocate(GtkWidget* widget, GtkAllocation* allocation, TextureBrowser* textureBrowser) +{ + textureBrowser->width = allocation->width; + textureBrowser->height = allocation->height; + TextureBrowser_heightChanged(*textureBrowser); + textureBrowser->m_originInvalid = true; + TextureBrowser_queueDraw(*textureBrowser); + return FALSE; +} + +gboolean TextureBrowser_expose(GtkWidget* widget, GdkEventExpose* event, TextureBrowser* textureBrowser) +{ + if(glwidget_make_current(textureBrowser->m_gl_widget) != FALSE) + { + GlobalOpenGL_debugAssertNoErrors(); + TextureBrowser_evaluateHeight(*textureBrowser); + Texture_Draw(*textureBrowser); + GlobalOpenGL_debugAssertNoErrors(); + glwidget_swap_buffers(textureBrowser->m_gl_widget); + } + return FALSE; +} + + +TextureBrowser g_TextureBrowser; + +TextureBrowser& GlobalTextureBrowser() +{ + return g_TextureBrowser; +} + +bool TextureBrowser_hideUnused() +{ + return g_TextureBrowser.m_hideUnused; +} + +void TextureBrowser_ToggleHideUnused() +{ + if(g_TextureBrowser.m_hideUnused) + { + TextureBrowser_SetHideUnused(g_TextureBrowser, false); + } + else + { + TextureBrowser_SetHideUnused(g_TextureBrowser, true); + } +} + +void TextureGroups_constructTreeModel(TextureGroups groups, GtkTreeStore* store) +{ + // put the information from the old textures menu into a treeview + GtkTreeIter iter, child; + + TextureGroups::const_iterator i = groups.begin(); + while (i != groups.end()) + { + const char* dirName = (*i).c_str(); + const char* firstUnderscore = strchr(dirName, '_'); + StringRange dirRoot (dirName, (firstUnderscore == 0) ? dirName : firstUnderscore + 1); + + TextureGroups::const_iterator next = i; + ++next; + if(firstUnderscore != 0 + && next != groups.end() + && string_equal_start((*next).c_str(), dirRoot)) + { + gtk_tree_store_append(store, &iter, NULL); + gtk_tree_store_set (store, &iter, 0, CopiedString(StringRange(dirName, firstUnderscore)).c_str(), -1); + + // keep going... + while (i != groups.end() && string_equal_start((*i).c_str(), dirRoot)) + { + gtk_tree_store_append(store, &child, &iter); + gtk_tree_store_set (store, &child, 0, (*i).c_str(), -1); + ++i; + } + } + else + { + gtk_tree_store_append(store, &iter, NULL); + gtk_tree_store_set (store, &iter, 0, dirName, -1); + ++i; + } + } +} + +TextureGroups TextureGroups_constructTreeView() +{ + TextureGroups groups; + + if (TextureBrowser_showWads()) + { + GlobalFileSystem().forEachArchive (TextureGroupsAddWadCaller (groups)); + } + else + { + // scan texture dirs and pak files only if not restricting to shaderlist + if (g_pGameDescription->mGameType != "doom3" && !g_TextureBrowser_shaderlistOnly) + { + GlobalFileSystem().forEachDirectory ("textures/", TextureGroupsAddDirectoryCaller(groups)); + } + + GlobalShaderSystem().foreachShaderName(TextureGroupsAddShaderCaller(groups)); + } + + return groups; +} + +void TextureBrowser_constructTreeStore() +{ + TextureGroups groups = TextureGroups_constructTreeView(); + GtkTreeStore* store = gtk_tree_store_new(1, G_TYPE_STRING); + TextureGroups_constructTreeModel(groups, store); + std::set::iterator iter; + + GtkTreeModel* model = GTK_TREE_MODEL(store); + + gtk_tree_view_set_model(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), model); + + g_object_unref(G_OBJECT(store)); +} + +void TextureBrowser_constructTreeStoreTags() +{ + TextureGroups groups; + GtkTreeStore* store = gtk_tree_store_new(1, G_TYPE_STRING); + GtkTreeModel* model = GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list); + + gtk_tree_view_set_model(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), model); + + g_object_unref(G_OBJECT(store)); +} + +void TreeView_onRowActivated(GtkTreeView* treeview, GtkTreePath* path, GtkTreeViewColumn* col, gpointer userdata) +{ + GtkTreeIter iter; + + GtkTreeModel* model = gtk_tree_view_get_model(GTK_TREE_VIEW(treeview)); + + if (gtk_tree_model_get_iter (model, &iter, path)) + { + gchar dirName[1024]; + + gchar* buffer; + gtk_tree_model_get(model, &iter, 0, &buffer, -1); + strcpy(dirName, buffer); + g_free(buffer); + + g_TextureBrowser.m_searchedTags = false; + + if(!TextureBrowser_showWads()) + strcat(dirName, "/"); + + ScopeDisableScreenUpdates disableScreenUpdates(dirName, "Loading Textures"); + TextureBrowser_ShowDirectory(GlobalTextureBrowser (), dirName); + TextureBrowser_queueDraw(GlobalTextureBrowser ()); + } +} + +void TextureBrowser_createTreeViewTree() +{ + GtkCellRenderer* renderer; + g_TextureBrowser.m_treeViewTree = GTK_WIDGET(gtk_tree_view_new()); + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), FALSE); + + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), FALSE); + g_signal_connect(g_TextureBrowser.m_treeViewTree, "row-activated", (GCallback) TreeView_onRowActivated, NULL); + + renderer = gtk_cell_renderer_text_new(); + gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTree), -1, "", renderer, "text", 0, NULL); + + TextureBrowser_constructTreeStore(); +} + +void TextureBrowser_addTag(); +void TextureBrowser_renameTag(); +void TextureBrowser_deleteTag(); + +void TextureBrowser_createContextMenu(GtkWidget *treeview, GdkEventButton *event) +{ + GtkWidget* menu = gtk_menu_new(); + + GtkWidget* menuitem = gtk_menu_item_new_with_label("Add tag"); + g_signal_connect(menuitem, "activate", (GCallback)TextureBrowser_addTag, treeview); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem); + + menuitem = gtk_menu_item_new_with_label("Rename tag"); + g_signal_connect(menuitem, "activate", (GCallback)TextureBrowser_renameTag, treeview); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem); + + menuitem = gtk_menu_item_new_with_label("Delete tag"); + g_signal_connect(menuitem, "activate", (GCallback)TextureBrowser_deleteTag, treeview); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), menuitem); + + gtk_widget_show_all(menu); + + gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, + (event != NULL) ? event->button : 0, + gdk_event_get_time((GdkEvent*)event)); +} + +gboolean TreeViewTags_onButtonPressed(GtkWidget *treeview, GdkEventButton *event) +{ + if (event->type == GDK_BUTTON_PRESS && event->button == 3) + { + GtkTreePath *path; + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(treeview)); + + if(gtk_tree_view_get_path_at_pos(GTK_TREE_VIEW(treeview), event->x, event->y, &path, NULL, NULL, NULL)) + { + gtk_tree_selection_unselect_all(selection); + gtk_tree_selection_select_path(selection, path); + gtk_tree_path_free(path); + } + + TextureBrowser_createContextMenu(treeview, event); + return TRUE; + } + return FALSE; +} + +void TextureBrowser_createTreeViewTags() +{ + GtkCellRenderer* renderer; + g_TextureBrowser.m_treeViewTags = GTK_WIDGET(gtk_tree_view_new()); + gtk_tree_view_set_enable_search(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), FALSE); + + g_signal_connect(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), "button-press-event", (GCallback)TreeViewTags_onButtonPressed, NULL); + + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), FALSE); + + renderer = gtk_cell_renderer_text_new(); + gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags), -1, "", renderer, "text", 0, NULL); + + TextureBrowser_constructTreeStoreTags(); +} + +GtkMenuItem* TextureBrowser_constructViewMenu(GtkMenu* menu) +{ + GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic("_View"); + + if(g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + create_check_menu_item_with_mnemonic(menu, "Hide _Unused", "ShowInUse"); + if(string_empty(g_pGameDescription->getKeyValue("show_wads"))) + { + create_check_menu_item_with_mnemonic(menu, "Hide Image Missing", "FilterNotex"); + } + menu_separator(menu); + + create_menu_item_with_mnemonic(menu, "Show All", "ShowAllTextures"); + + // we always want to show shaders but don't want a "Show Shaders" menu for doom3 and .wad file games + if(g_pGameDescription->mGameType == "doom3" || !string_empty(g_pGameDescription->getKeyValue("show_wads"))) + { + g_TextureBrowser.m_showShaders = true; + } + else + { + create_check_menu_item_with_mnemonic(menu, "Show shaders", "ToggleShowShaders"); + } + + if(g_pGameDescription->mGameType != "doom3" && string_empty(g_pGameDescription->getKeyValue("show_wads"))) + { + create_check_menu_item_with_mnemonic (menu, "Shaders Only", "ToggleShowShaderlistOnly"); + } + if(g_TextureBrowser.m_tags) + { + create_menu_item_with_mnemonic(menu, "Show Untagged", "ShowUntagged"); + } + + create_check_menu_item_with_mnemonic(menu, "Fixed Size", "FixedSize"); + + if(string_empty(g_pGameDescription->getKeyValue("show_wads"))) + { + menu_separator(menu); + g_TextureBrowser.m_shader_info_item = GTK_WIDGET(create_menu_item_with_mnemonic(menu, "Shader Info", "ShaderInfo")); + gtk_widget_set_sensitive(g_TextureBrowser.m_shader_info_item, FALSE); + } + + return textures_menu_item; +} + +GtkMenuItem* TextureBrowser_constructToolsMenu(GtkMenu* menu) +{ + GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic("_Tools"); + + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + create_menu_item_with_mnemonic(menu, "Flush & Reload Shaders", "RefreshShaders"); + create_menu_item_with_mnemonic(menu, "Find / Replace...", "FindReplaceTextures"); + + return textures_menu_item; +} + +GtkMenuItem* TextureBrowser_constructTagsMenu(GtkMenu* menu) +{ + GtkMenuItem* textures_menu_item = new_sub_menu_item_with_mnemonic("T_ags"); + + if (g_Layout_enableDetachableMenus.m_value) + menu_tearoff (menu); + + create_menu_item_with_mnemonic(menu, "Add tag", "AddTag"); + create_menu_item_with_mnemonic(menu, "Rename tag", "RenameTag"); + create_menu_item_with_mnemonic(menu, "Delete tag", "DeleteTag"); + menu_separator(menu); + create_menu_item_with_mnemonic(menu, "Copy tags from selected", "CopyTag"); + create_menu_item_with_mnemonic(menu, "Paste tags to selected", "PasteTag"); + + return textures_menu_item; +} + +gboolean TextureBrowser_tagMoveHelper(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected) +{ + g_assert(selected != NULL); + + GtkTreeRowReference* rowref = gtk_tree_row_reference_new (model, path); + *selected = g_slist_append(*selected, rowref); + + return FALSE; +} + +void TextureBrowser_assignTags() +{ + GSList* selected = NULL; + GSList* node; + gchar* tag_assigned; + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_available_tree)); + + gtk_tree_selection_selected_foreach(selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected); + + if(selected != NULL) + { + for (node = selected; node != NULL; node = node->next) + { + GtkTreePath* path = gtk_tree_row_reference_get_path((GtkTreeRowReference*)node->data); + + if(path) + { + GtkTreeIter iter; + + if (gtk_tree_model_get_iter(GTK_TREE_MODEL(g_TextureBrowser.m_available_store), &iter, path)) + { + gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_available_store), &iter, TAG_COLUMN, &tag_assigned, -1); + if(!TagBuilder.CheckShaderTag(g_TextureBrowser.shader.c_str())) + { + // create a custom shader/texture entry + IShader* ishader = QERApp_Shader_ForName(g_TextureBrowser.shader.c_str()); + CopiedString filename = ishader->getShaderFileName(); + + if(filename.empty()) + { + // it's a texture + TagBuilder.AddShaderNode(g_TextureBrowser.shader.c_str(), CUSTOM, TEXTURE); + } else { + // it's a shader + TagBuilder.AddShaderNode(g_TextureBrowser.shader.c_str(), CUSTOM, SHADER); + } + ishader->DecRef(); + } + TagBuilder.AddShaderTag(g_TextureBrowser.shader.c_str(), (char*)tag_assigned, TAG); + + gtk_list_store_remove(g_TextureBrowser.m_available_store, &iter); + gtk_list_store_append (g_TextureBrowser.m_assigned_store, &iter); + gtk_list_store_set (g_TextureBrowser.m_assigned_store, &iter, TAG_COLUMN, (char*)tag_assigned, -1); + } + } + } + + g_slist_foreach(selected, (GFunc)gtk_tree_row_reference_free, NULL); + + // Save changes + TagBuilder.SaveXmlDoc(); + } + g_slist_free(selected); +} + +void TextureBrowser_removeTags() +{ + GSList* selected = NULL; + GSList* node; + gchar* tag; + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_assigned_tree)); + + gtk_tree_selection_selected_foreach(selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected); + + if(selected != NULL) + { + for (node = selected; node != NULL; node = node->next) + { + GtkTreePath* path = gtk_tree_row_reference_get_path((GtkTreeRowReference*)node->data); + + if (path) + { + GtkTreeIter iter; + + if (gtk_tree_model_get_iter(GTK_TREE_MODEL(g_TextureBrowser.m_assigned_store), &iter, path)) + { + gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_assigned_store), &iter, TAG_COLUMN, &tag, -1); + TagBuilder.DeleteShaderTag(g_TextureBrowser.shader.c_str(), tag); + gtk_list_store_remove(g_TextureBrowser.m_assigned_store, &iter); + } + } + } + + g_slist_foreach(selected, (GFunc)gtk_tree_row_reference_free, NULL); + + // Update the "available tags list" + BuildStoreAvailableTags(g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); + + // Save changes + TagBuilder.SaveXmlDoc(); + } + g_slist_free(selected); +} + +void TextureBrowser_buildTagList() +{ + GtkTreeIter treeIter; + gtk_list_store_clear(g_TextureBrowser.m_all_tags_list); + + std::set::iterator iter; + + for (iter = g_TextureBrowser.m_all_tags.begin(); iter != g_TextureBrowser.m_all_tags.end(); ++iter) + { + gtk_list_store_append(g_TextureBrowser.m_all_tags_list, &treeIter); + gtk_list_store_set(g_TextureBrowser.m_all_tags_list, &treeIter, TAG_COLUMN, (*iter).c_str(), -1); + } +} + +void TextureBrowser_searchTags() +{ + GSList* selected = NULL; + GSList* node; + gchar* tag; + char buffer[256]; + char tags_searched[256]; + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); + + gtk_tree_selection_selected_foreach(selection, (GtkTreeSelectionForeachFunc)TextureBrowser_tagMoveHelper, &selected); + + if(selected != NULL) + { + strcpy(buffer, "/root/*/*[tag='"); + strcpy(tags_searched, "[TAGS] "); + + for (node = selected; node != NULL; node = node->next) + { + GtkTreePath* path = gtk_tree_row_reference_get_path((GtkTreeRowReference*)node->data); + + if (path) + { + GtkTreeIter iter; + + if (gtk_tree_model_get_iter(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iter, path)) + { + gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iter, TAG_COLUMN, &tag, -1); + + strcat(buffer, tag); + strcat(tags_searched, tag); + if(node != g_slist_last(node)) + { + strcat(buffer, "' and tag='"); + strcat(tags_searched, ", "); + } + } + } + } + + strcat(buffer, "']"); + + g_slist_foreach(selected, (GFunc)gtk_tree_row_reference_free, NULL); + + g_TextureBrowser.m_found_shaders.clear(); // delete old list + TagBuilder.TagSearch(buffer, g_TextureBrowser.m_found_shaders); + + if(!g_TextureBrowser.m_found_shaders.empty()) // found something + { + size_t shaders_found = g_TextureBrowser.m_found_shaders.size(); + + globalOutputStream() << "Found " << (unsigned int)shaders_found << " textures and shaders with " << tags_searched << "\n"; + ScopeDisableScreenUpdates disableScreenUpdates("Searching...", "Loading Textures"); + + std::set::iterator iter; + + for(iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++) + { + std::string path = (*iter).c_str(); + size_t pos = path.find_last_of("/", path.size()); + std::string name = path.substr(pos + 1, path.size()); + path = path.substr(0, pos + 1); + TextureDirectory_loadTexture(path.c_str(), name.c_str()); + } + } + g_TextureBrowser.m_searchedTags = true; + g_TextureBrowser_currentDirectory = tags_searched; + + g_TextureBrowser.m_nTotalHeight = 0; + TextureBrowser_setOriginY(g_TextureBrowser, 0); + TextureBrowser_heightChanged(g_TextureBrowser); + TextureBrowser_updateTitle(); + } + g_slist_free(selected); +} + +void TextureBrowser_toggleSearchButton() +{ + gint page = gtk_notebook_get_current_page(GTK_NOTEBOOK(g_TextureBrowser.m_tag_notebook)); + + if(page == 0) // tag page + { + gtk_widget_show_all(g_TextureBrowser.m_search_button); + } else { + gtk_widget_hide_all(g_TextureBrowser.m_search_button); + } +} + +void TextureBrowser_constructTagNotebook() +{ + g_TextureBrowser.m_tag_notebook = gtk_notebook_new(); + GtkWidget* labelTags = gtk_label_new("Tags"); + GtkWidget* labelTextures = gtk_label_new("Textures"); + + gtk_notebook_append_page(GTK_NOTEBOOK(g_TextureBrowser.m_tag_notebook), g_TextureBrowser.m_scr_win_tree, labelTextures); + gtk_notebook_append_page(GTK_NOTEBOOK(g_TextureBrowser.m_tag_notebook), g_TextureBrowser.m_scr_win_tags, labelTags); + + g_signal_connect(G_OBJECT(g_TextureBrowser.m_tag_notebook), "switch-page", G_CALLBACK(TextureBrowser_toggleSearchButton), NULL); + + gtk_widget_show_all(g_TextureBrowser.m_tag_notebook); +} + +void TextureBrowser_constructSearchButton() +{ + GtkTooltips* tooltips = gtk_tooltips_new(); + + GtkWidget* image = gtk_image_new_from_stock(GTK_STOCK_FIND, GTK_ICON_SIZE_SMALL_TOOLBAR); + g_TextureBrowser.m_search_button = gtk_button_new(); + g_signal_connect(G_OBJECT(g_TextureBrowser.m_search_button), "clicked", G_CALLBACK(TextureBrowser_searchTags), NULL); + gtk_tooltips_set_tip(GTK_TOOLTIPS(tooltips), g_TextureBrowser.m_search_button, "Search with selected tags", "Search with selected tags"); + gtk_container_add(GTK_CONTAINER(g_TextureBrowser.m_search_button), image); +} + +void TextureBrowser_checkTagFile() +{ + const char SHADERTAG_FILE[] = "shadertags.xml"; + CopiedString default_filename, rc_filename; + StringOutputStream stream(256); + + stream << LocalRcPath_get(); + stream << SHADERTAG_FILE; + rc_filename = stream.c_str(); + + if(file_exists(rc_filename.c_str())) + { + g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc(rc_filename.c_str()); + + if(g_TextureBrowser.m_tags) + { + globalOutputStream() << "Loading tag file " << rc_filename.c_str() << ".\n"; + } + } + else + { + // load default tagfile + stream.clear(); + stream << g_pGameDescription->mGameToolsPath.c_str(); + stream << SHADERTAG_FILE; + default_filename = stream.c_str(); + + if(file_exists(default_filename.c_str())) + { + g_TextureBrowser.m_tags = TagBuilder.OpenXmlDoc(default_filename.c_str(), rc_filename.c_str()); + + if(g_TextureBrowser.m_tags) + { + globalOutputStream() << "Loading default tag file " << default_filename.c_str() << ".\n"; + } + } + else + { + globalErrorStream() << "Unable to find default tag file " << default_filename.c_str() << ". No tag support.\n"; + } + } +} + +void TextureBrowser_SetNotex() +{ + StringOutputStream name(256); + name << GlobalRadiant().getAppPath() << "bitmaps/notex.bmp"; + g_notex = name.c_str(); + + name = NULL; + name << GlobalRadiant().getAppPath() << "bitmaps/shadernotex.bmp"; + g_shadernotex = name.c_str(); +} + +GtkWidget* TextureBrowser_constructWindow(GtkWindow* toplevel) +{ + // The gl_widget and the tag assignment frame should be packed into a GtkVPaned with the slider + // position stored in local.pref. gtk_paned_get_position() and gtk_paned_set_position() don't + // seem to work in gtk 2.4 and the arrow buttons don't handle GTK_FILL, so here's another thing + // for the "once-the-gtk-libs-are-updated-TODO-list" :x + + TextureBrowser_checkTagFile(); + TextureBrowser_SetNotex(); + + GlobalShaderSystem().setActiveShadersChangedNotify(ReferenceCaller(g_TextureBrowser)); + + g_TextureBrowser.m_parent = toplevel; + + GtkWidget* table = gtk_table_new(3, 3, FALSE); + GtkWidget* frame_table = NULL; + GtkWidget* vbox = gtk_vbox_new(FALSE, 0); + gtk_table_attach(GTK_TABLE(table), vbox, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0); + gtk_widget_show(vbox); + + GtkWidget* menu_bar; + + { // menu bar + menu_bar = gtk_menu_bar_new(); + GtkWidget* menu_view = gtk_menu_new(); + GtkWidget* view_item = (GtkWidget*)TextureBrowser_constructViewMenu(GTK_MENU(menu_view)); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(view_item), menu_view); + gtk_menu_bar_append(GTK_MENU_BAR(menu_bar), view_item); + + GtkWidget* menu_tools = gtk_menu_new(); + GtkWidget* tools_item = (GtkWidget*)TextureBrowser_constructToolsMenu(GTK_MENU(menu_tools)); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(tools_item), menu_tools); + gtk_menu_bar_append(GTK_MENU_BAR(menu_bar), tools_item); + + gtk_table_attach(GTK_TABLE (table), menu_bar, 0, 3, 0, 1, GTK_FILL, GTK_SHRINK, 0, 0); + gtk_widget_show(menu_bar); + } + { // Texture TreeView + g_TextureBrowser.m_scr_win_tree = gtk_scrolled_window_new(NULL, NULL); + gtk_container_set_border_width(GTK_CONTAINER(g_TextureBrowser.m_scr_win_tree), 0); + + // vertical only scrolling for treeview + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(g_TextureBrowser.m_scr_win_tree), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); + + gtk_widget_show(g_TextureBrowser.m_scr_win_tree); + + TextureBrowser_createTreeViewTree(); + + gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(g_TextureBrowser.m_scr_win_tree), GTK_WIDGET(g_TextureBrowser.m_treeViewTree)); + gtk_widget_show(GTK_WIDGET(g_TextureBrowser.m_treeViewTree)); + } + { // gl_widget scrollbar + GtkWidget* w = gtk_vscrollbar_new(GTK_ADJUSTMENT(gtk_adjustment_new (0,0,0,1,1,0))); + gtk_table_attach(GTK_TABLE (table), w, 2, 3, 1, 2, GTK_SHRINK, GTK_FILL, 0, 0); + gtk_widget_show(w); + g_TextureBrowser.m_texture_scroll = w; + + GtkAdjustment *vadjustment = gtk_range_get_adjustment (GTK_RANGE (g_TextureBrowser.m_texture_scroll)); + g_signal_connect(G_OBJECT(vadjustment), "value_changed", G_CALLBACK(TextureBrowser_verticalScroll), &g_TextureBrowser); + + widget_set_visible(g_TextureBrowser.m_texture_scroll, g_TextureBrowser.m_showTextureScrollbar); + } + { // gl_widget + g_TextureBrowser.m_gl_widget = glwidget_new(FALSE); + gtk_widget_ref(g_TextureBrowser.m_gl_widget); + + gtk_widget_set_events(g_TextureBrowser.m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK); + GTK_WIDGET_SET_FLAGS(g_TextureBrowser.m_gl_widget, GTK_CAN_FOCUS); + + gtk_table_attach_defaults(GTK_TABLE(table), g_TextureBrowser.m_gl_widget, 1, 2, 1, 2); + gtk_widget_show(g_TextureBrowser.m_gl_widget); + + g_TextureBrowser.m_sizeHandler = g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "size_allocate", G_CALLBACK(TextureBrowser_size_allocate), &g_TextureBrowser); + g_TextureBrowser.m_exposeHandler = g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "expose_event", G_CALLBACK(TextureBrowser_expose), &g_TextureBrowser); + + g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "button_press_event", G_CALLBACK(TextureBrowser_button_press), &g_TextureBrowser); + g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "button_release_event", G_CALLBACK(TextureBrowser_button_release), &g_TextureBrowser); + g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "motion_notify_event", G_CALLBACK(TextureBrowser_motion), &g_TextureBrowser); + g_signal_connect(G_OBJECT(g_TextureBrowser.m_gl_widget), "scroll_event", G_CALLBACK(TextureBrowser_scroll), &g_TextureBrowser); + } + + // tag stuff + if(g_TextureBrowser.m_tags) + { + { // fill tag GtkListStore + g_TextureBrowser.m_all_tags_list = gtk_list_store_new(N_COLUMNS, G_TYPE_STRING); + GtkTreeSortable* sortable = GTK_TREE_SORTABLE(g_TextureBrowser.m_all_tags_list); + gtk_tree_sortable_set_sort_column_id(sortable, TAG_COLUMN, GTK_SORT_ASCENDING); + + TagBuilder.GetAllTags(g_TextureBrowser.m_all_tags); + TextureBrowser_buildTagList(); + } + { // tag menu bar + GtkWidget* menu_tags = gtk_menu_new(); + GtkWidget* tags_item = (GtkWidget*)TextureBrowser_constructTagsMenu(GTK_MENU(menu_tags)); + gtk_menu_item_set_submenu(GTK_MENU_ITEM(tags_item), menu_tags); + gtk_menu_bar_append(GTK_MENU_BAR(menu_bar), tags_item); + } + { // Tag TreeView + g_TextureBrowser.m_scr_win_tags = gtk_scrolled_window_new(NULL, NULL); + gtk_container_set_border_width(GTK_CONTAINER(g_TextureBrowser.m_scr_win_tags), 0); + + // vertical only scrolling for treeview + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(g_TextureBrowser.m_scr_win_tags), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); + + TextureBrowser_createTreeViewTags(); + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); + gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); + + gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW (g_TextureBrowser.m_scr_win_tags), GTK_WIDGET (g_TextureBrowser.m_treeViewTags)); + gtk_widget_show(GTK_WIDGET(g_TextureBrowser.m_treeViewTags)); + } + { // Texture/Tag notebook + TextureBrowser_constructTagNotebook(); + gtk_box_pack_start(GTK_BOX(vbox), g_TextureBrowser.m_tag_notebook, TRUE, TRUE, 0); + } + { // Tag search button + TextureBrowser_constructSearchButton(); + gtk_box_pack_end(GTK_BOX(vbox), g_TextureBrowser.m_search_button, FALSE, FALSE, 0); + } + { // Tag frame + frame_table = gtk_table_new(3, 3, FALSE); + + g_TextureBrowser.m_tag_frame = gtk_frame_new("Tag assignment"); + gtk_frame_set_label_align(GTK_FRAME(g_TextureBrowser.m_tag_frame), 0.5, 0.5); + gtk_frame_set_shadow_type(GTK_FRAME(g_TextureBrowser.m_tag_frame), GTK_SHADOW_NONE); + + gtk_table_attach(GTK_TABLE(table), g_TextureBrowser.m_tag_frame, 1, 3, 2, 3, GTK_FILL, GTK_SHRINK, 0, 0); + + gtk_widget_show(frame_table); + + gtk_container_add (GTK_CONTAINER(g_TextureBrowser.m_tag_frame), frame_table); + } + { // assigned tag list + GtkWidget* scrolled_win = gtk_scrolled_window_new(NULL, NULL); + gtk_container_set_border_width(GTK_CONTAINER (scrolled_win), 0); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW (scrolled_win), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); + + g_TextureBrowser.m_assigned_store = gtk_list_store_new(N_COLUMNS, G_TYPE_STRING); + + GtkTreeSortable* sortable = GTK_TREE_SORTABLE(g_TextureBrowser.m_assigned_store); + gtk_tree_sortable_set_sort_column_id(sortable, TAG_COLUMN, GTK_SORT_ASCENDING); + + GtkCellRenderer* renderer = gtk_cell_renderer_text_new(); + + g_TextureBrowser.m_assigned_tree = gtk_tree_view_new_with_model(GTK_TREE_MODEL (g_TextureBrowser.m_assigned_store)); + g_object_unref(G_OBJECT (g_TextureBrowser.m_assigned_store)); + g_signal_connect(g_TextureBrowser.m_assigned_tree, "row-activated", (GCallback) TextureBrowser_removeTags, NULL); + gtk_tree_view_set_headers_visible(GTK_TREE_VIEW (g_TextureBrowser.m_assigned_tree), FALSE); + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_assigned_tree)); + gtk_tree_selection_set_mode(selection, GTK_SELECTION_MULTIPLE); + + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes("", renderer, "text", TAG_COLUMN, NULL); + gtk_tree_view_append_column(GTK_TREE_VIEW (g_TextureBrowser.m_assigned_tree), column); + gtk_widget_show(g_TextureBrowser.m_assigned_tree); + + gtk_widget_show(scrolled_win); + gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW (scrolled_win), GTK_WIDGET (g_TextureBrowser.m_assigned_tree)); + + gtk_table_attach(GTK_TABLE(frame_table), scrolled_win, 0, 1, 1, 3, GTK_FILL, GTK_FILL, 0, 0); + } + { // available tag list + GtkWidget* scrolled_win = gtk_scrolled_window_new (NULL, NULL); + gtk_container_set_border_width (GTK_CONTAINER (scrolled_win), 0); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win), GTK_POLICY_NEVER, GTK_POLICY_ALWAYS); + + g_TextureBrowser.m_available_store = gtk_list_store_new (N_COLUMNS, G_TYPE_STRING); + GtkTreeSortable* sortable = GTK_TREE_SORTABLE(g_TextureBrowser.m_available_store); + gtk_tree_sortable_set_sort_column_id(sortable, TAG_COLUMN, GTK_SORT_ASCENDING); + + GtkCellRenderer* renderer = gtk_cell_renderer_text_new (); + + g_TextureBrowser.m_available_tree = gtk_tree_view_new_with_model (GTK_TREE_MODEL (g_TextureBrowser.m_available_store)); + g_object_unref (G_OBJECT (g_TextureBrowser.m_available_store)); + g_signal_connect(g_TextureBrowser.m_available_tree, "row-activated", (GCallback) TextureBrowser_assignTags, NULL); + gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (g_TextureBrowser.m_available_tree), FALSE); + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_available_tree)); + gtk_tree_selection_set_mode (selection, GTK_SELECTION_MULTIPLE); + + GtkTreeViewColumn* column = gtk_tree_view_column_new_with_attributes ("", renderer, "text", TAG_COLUMN, NULL); + gtk_tree_view_append_column (GTK_TREE_VIEW (g_TextureBrowser.m_available_tree), column); + gtk_widget_show (g_TextureBrowser.m_available_tree); + + gtk_widget_show (scrolled_win); + gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scrolled_win), GTK_WIDGET (g_TextureBrowser.m_available_tree)); + + gtk_table_attach (GTK_TABLE (frame_table), scrolled_win, 2, 3, 1, 3, GTK_FILL, GTK_FILL, 0, 0); + } + { // tag arrow buttons + GtkWidget* m_btn_left = gtk_button_new(); + GtkWidget* m_btn_right = gtk_button_new(); + GtkWidget* m_arrow_left = gtk_arrow_new(GTK_ARROW_LEFT, GTK_SHADOW_OUT); + GtkWidget* m_arrow_right = gtk_arrow_new(GTK_ARROW_RIGHT, GTK_SHADOW_OUT); + gtk_container_add(GTK_CONTAINER(m_btn_left), m_arrow_left); + gtk_container_add(GTK_CONTAINER(m_btn_right), m_arrow_right); + + // workaround. the size of the tag frame depends of the requested size of the arrow buttons. + gtk_widget_set_size_request(m_arrow_left, -1, 68); + gtk_widget_set_size_request(m_arrow_right, -1, 68); + + gtk_table_attach(GTK_TABLE(frame_table), m_btn_left, 1, 2, 1, 2, GTK_SHRINK, GTK_EXPAND, 0, 0); + gtk_table_attach(GTK_TABLE(frame_table), m_btn_right, 1, 2, 2, 3, GTK_SHRINK, GTK_EXPAND, 0, 0); + + g_signal_connect(G_OBJECT (m_btn_left), "clicked", G_CALLBACK(TextureBrowser_assignTags), NULL); + g_signal_connect(G_OBJECT (m_btn_right), "clicked", G_CALLBACK(TextureBrowser_removeTags), NULL); + + gtk_widget_show(m_btn_left); + gtk_widget_show(m_btn_right); + gtk_widget_show(m_arrow_left); + gtk_widget_show(m_arrow_right); + } + { // tag fram labels + GtkWidget* m_lbl_assigned = gtk_label_new ("Assigned"); + GtkWidget* m_lbl_unassigned = gtk_label_new ("Available"); + + gtk_table_attach (GTK_TABLE (frame_table), m_lbl_assigned, 0, 1, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0); + gtk_table_attach (GTK_TABLE (frame_table), m_lbl_unassigned, 2, 3, 0, 1, GTK_EXPAND, GTK_SHRINK, 0, 0); + + gtk_widget_show (m_lbl_assigned); + gtk_widget_show (m_lbl_unassigned); + } + } else { // no tag support, show the texture tree only + gtk_box_pack_start(GTK_BOX(vbox), g_TextureBrowser.m_scr_win_tree, TRUE, TRUE, 0); + } + + // TODO do we need this? + //gtk_container_set_focus_chain(GTK_CONTAINER(hbox_table), NULL); + + return table; +} + +void TextureBrowser_destroyWindow() +{ + GlobalShaderSystem().setActiveShadersChangedNotify(Callback()); + + g_signal_handler_disconnect(G_OBJECT(g_TextureBrowser.m_gl_widget), g_TextureBrowser.m_sizeHandler); + g_signal_handler_disconnect(G_OBJECT(g_TextureBrowser.m_gl_widget), g_TextureBrowser.m_exposeHandler); + + gtk_widget_unref(g_TextureBrowser.m_gl_widget); +} + +const Vector3& TextureBrowser_getBackgroundColour(TextureBrowser& textureBrowser) +{ + return textureBrowser.color_textureback; +} + +void TextureBrowser_setBackgroundColour(TextureBrowser& textureBrowser, const Vector3& colour) +{ + textureBrowser.color_textureback = colour; + TextureBrowser_queueDraw(textureBrowser); +} + +void TextureBrowser_selectionHelper(GtkTreeModel* model, GtkTreePath* path, GtkTreeIter* iter, GSList** selected) +{ + g_assert(selected != NULL); + + gchar* name; + gtk_tree_model_get(model, iter, TAG_COLUMN, &name, -1); + *selected = g_slist_append(*selected, name); +} + +void TextureBrowser_shaderInfo() +{ + const char* name = TextureBrowser_GetSelectedShader(g_TextureBrowser); + IShader* shader = QERApp_Shader_ForName(name); + + DoShaderInfoDlg(name, shader->getShaderFileName(), "Shader Info"); + + shader->DecRef(); +} + +void TextureBrowser_addTag() +{ + CopiedString tag; + + EMessageBoxReturn result = DoShaderTagDlg(&tag, "Add shader tag"); + + if (result == eIDOK && !tag.empty()) + { + GtkTreeIter iter, iter2; + g_TextureBrowser.m_all_tags.insert(tag.c_str()); + gtk_list_store_append(g_TextureBrowser.m_available_store, &iter); + gtk_list_store_set(g_TextureBrowser.m_available_store, &iter, TAG_COLUMN, tag.c_str(), -1); + + // Select the currently added tag in the available list + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_available_tree)); + gtk_tree_selection_select_iter(selection, &iter); + + gtk_list_store_append(g_TextureBrowser.m_all_tags_list, &iter2); + gtk_list_store_set(g_TextureBrowser.m_all_tags_list, &iter2, TAG_COLUMN, tag.c_str(), -1); + } +} + +void TextureBrowser_renameTag() +{ + /* WORKAROUND: The tag treeview is set to GTK_SELECTION_MULTIPLE. Because + gtk_tree_selection_get_selected() doesn't work with GTK_SELECTION_MULTIPLE, + we need to count the number of selected rows first and use + gtk_tree_selection_selected_foreach() then to go through the list of selected + rows (which always containins a single row). + */ + + GSList* selected = NULL; + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); + gtk_tree_selection_selected_foreach(selection, GtkTreeSelectionForeachFunc(TextureBrowser_selectionHelper), &selected); + + if(g_slist_length(selected) == 1) // we only rename a single tag + { + CopiedString newTag; + EMessageBoxReturn result = DoShaderTagDlg(&newTag, "Rename shader tag"); + + if (result == eIDOK && !newTag.empty()) + { + GtkTreeIter iterList; + gchar* rowTag; + gchar* oldTag = (char*)selected->data; + + bool row = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterList) != 0; + + while(row) + { + gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterList, TAG_COLUMN, &rowTag, -1); + + if(strcmp(rowTag, oldTag) == 0) + { + gtk_list_store_set(g_TextureBrowser.m_all_tags_list, &iterList, TAG_COLUMN, newTag.c_str(), -1); + } + row = gtk_tree_model_iter_next(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterList) != 0; + } + + TagBuilder.RenameShaderTag(oldTag, newTag.c_str()); + + g_TextureBrowser.m_all_tags.erase((CopiedString)oldTag); + g_TextureBrowser.m_all_tags.insert(newTag); + + BuildStoreAssignedTags(g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser); + BuildStoreAvailableTags(g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); + } + } + else + { + gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "Select a single tag for renaming."); + } +} + +void TextureBrowser_deleteTag() +{ + GSList* selected = NULL; + + GtkTreeSelection* selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(g_TextureBrowser.m_treeViewTags)); + gtk_tree_selection_selected_foreach(selection, GtkTreeSelectionForeachFunc(TextureBrowser_selectionHelper), &selected); + + if(g_slist_length(selected) == 1) // we only delete a single tag + { + EMessageBoxReturn result = gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "Are you sure you want to delete the selected tag?", "Delete Tag", eMB_YESNO, eMB_ICONQUESTION); + + if(result == eIDYES) + { + GtkTreeIter iterSelected; + gchar *rowTag; + + gchar* tagSelected = (char*)selected->data; + + bool row = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterSelected) != 0; + + while(row) + { + gtk_tree_model_get(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterSelected, TAG_COLUMN, &rowTag, -1); + + if(strcmp(rowTag, tagSelected) == 0) + { + gtk_list_store_remove(g_TextureBrowser.m_all_tags_list, &iterSelected); + break; + } + row = gtk_tree_model_iter_next(GTK_TREE_MODEL(g_TextureBrowser.m_all_tags_list), &iterSelected) != 0; + } + + TagBuilder.DeleteTag(tagSelected); + g_TextureBrowser.m_all_tags.erase((CopiedString)tagSelected); + + BuildStoreAssignedTags(g_TextureBrowser.m_assigned_store, g_TextureBrowser.shader.c_str(), &g_TextureBrowser); + BuildStoreAvailableTags(g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); + } + } else { + gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "Select a single tag for deletion."); + } +} + +void TextureBrowser_copyTag() +{ + g_TextureBrowser.m_copied_tags.clear(); + TagBuilder.GetShaderTags(g_TextureBrowser.shader.c_str(), g_TextureBrowser.m_copied_tags); +} + +void TextureBrowser_pasteTag() +{ + IShader* ishader = QERApp_Shader_ForName(g_TextureBrowser.shader.c_str()); + CopiedString shader = g_TextureBrowser.shader.c_str(); + + if(!TagBuilder.CheckShaderTag(shader.c_str())) + { + CopiedString shaderFile = ishader->getShaderFileName(); + if(shaderFile.empty()) + { + // it's a texture + TagBuilder.AddShaderNode(shader.c_str(), CUSTOM, TEXTURE); + } + else + { + // it's a shader + TagBuilder.AddShaderNode(shader.c_str(), CUSTOM, SHADER); + } + + for(size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i) + { + TagBuilder.AddShaderTag(shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG); + } + } + else + { + for(size_t i = 0; i < g_TextureBrowser.m_copied_tags.size(); ++i) + { + if(!TagBuilder.CheckShaderTag(shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str())) + { + // the tag doesn't exist - let's add it + TagBuilder.AddShaderTag(shader.c_str(), g_TextureBrowser.m_copied_tags[i].c_str(), TAG); + } + } + } + + ishader->DecRef(); + + TagBuilder.SaveXmlDoc(); + BuildStoreAssignedTags(g_TextureBrowser.m_assigned_store, shader.c_str(), &g_TextureBrowser); + BuildStoreAvailableTags (g_TextureBrowser.m_available_store, g_TextureBrowser.m_assigned_store, g_TextureBrowser.m_all_tags, &g_TextureBrowser); +} + +void RefreshShaders() +{ + ScopeDisableScreenUpdates disableScreenUpdates("Processing...", "Loading Shaders"); + GlobalShaderSystem().refresh(); + UpdateAllWindows(); +} + +void TextureBrowser_ToggleShowShaders() +{ + g_TextureBrowser.m_showShaders ^= 1; + g_TextureBrowser.m_showshaders_item.update(); + TextureBrowser_queueDraw(g_TextureBrowser); +} + +void TextureBrowser_ToggleShowShaderListOnly() +{ + g_TextureBrowser_shaderlistOnly ^= 1; + g_TextureBrowser.m_showshaderlistonly_item.update(); + + TextureBrowser_constructTreeStore(); +} + +void TextureBrowser_showAll() +{ + g_TextureBrowser_currentDirectory = ""; + g_TextureBrowser.m_searchedTags = false; + TextureBrowser_heightChanged(g_TextureBrowser); + TextureBrowser_updateTitle(); +} + +void TextureBrowser_showUntagged() +{ + EMessageBoxReturn result = gtk_MessageBox(GTK_WIDGET(g_TextureBrowser.m_parent), "WARNING! This function might need a lot of memory and time. Are you sure you want to use it?", "Show Untagged", eMB_YESNO, eMB_ICONWARNING); + + if(result == eIDYES) + { + g_TextureBrowser.m_found_shaders.clear(); + TagBuilder.GetUntagged(g_TextureBrowser.m_found_shaders); + std::set::iterator iter; + + ScopeDisableScreenUpdates disableScreenUpdates("Searching untagged textures...", "Loading Textures"); + + for(iter = g_TextureBrowser.m_found_shaders.begin(); iter != g_TextureBrowser.m_found_shaders.end(); iter++) + { + std::string path = (*iter).c_str(); + size_t pos = path.find_last_of("/", path.size()); + std::string name = path.substr(pos + 1, path.size()); + path = path.substr(0, pos + 1); + TextureDirectory_loadTexture(path.c_str(), name.c_str()); + globalErrorStream() << path.c_str() << name.c_str() << "\n"; + } + + g_TextureBrowser_currentDirectory = "Untagged"; + TextureBrowser_queueDraw(GlobalTextureBrowser()); + TextureBrowser_heightChanged(g_TextureBrowser); + TextureBrowser_updateTitle(); + } +} + +void TextureBrowser_FixedSize() +{ + g_TextureBrowser_fixedSize ^= 1; + GlobalTextureBrowser().m_fixedsize_item.update(); + TextureBrowser_activeShadersChanged(GlobalTextureBrowser()); +} + +void TextureBrowser_FilterNotex() +{ + g_TextureBrowser_filterNotex ^= 1; + GlobalTextureBrowser().m_filternotex_item.update(); + TextureBrowser_activeShadersChanged(GlobalTextureBrowser()); +} + +void TextureBrowser_exportTitle(const StringImportCallback& importer) +{ + StringOutputStream buffer(64); + buffer << "Textures: "; + if(!string_empty(g_TextureBrowser_currentDirectory.c_str())) + { + buffer << g_TextureBrowser_currentDirectory.c_str(); + } + else + { + buffer << "all"; + } + importer(buffer.c_str()); +} + + +void TextureScaleImport(TextureBrowser& textureBrowser, int value) +{ + switch(value) + { + case 0: + TextureBrowser_setScale(textureBrowser, 10); + break; + case 1: + TextureBrowser_setScale(textureBrowser, 25); + break; + case 2: + TextureBrowser_setScale(textureBrowser, 50); + break; + case 3: + TextureBrowser_setScale(textureBrowser, 100); + break; + case 4: + TextureBrowser_setScale(textureBrowser, 200); + break; + } +} +typedef ReferenceCaller1 TextureScaleImportCaller; + +void TextureScaleExport(TextureBrowser& textureBrowser, const IntImportCallback& importer) +{ + switch(textureBrowser.m_textureScale) + { + case 10: + importer(0); + break; + case 25: + importer(1); + break; + case 50: + importer(2); + break; + case 100: + importer(3); + break; + case 200: + importer(4); + break; + } +} +typedef ReferenceCaller1 TextureScaleExportCaller; + +void TextureBrowser_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox( + "", "Texture scrollbar", + TextureBrowserImportShowScrollbarCaller(GlobalTextureBrowser()), + BoolExportCaller(GlobalTextureBrowser().m_showTextureScrollbar) + ); + { + const char* texture_scale[] = { "10%", "25%", "50%", "100%", "200%" }; + page.appendCombo( + "Texture Thumbnail Scale", + STRING_ARRAY_RANGE(texture_scale), + IntImportCallback(TextureScaleImportCaller(GlobalTextureBrowser())), + IntExportCallback(TextureScaleExportCaller(GlobalTextureBrowser())) + ); + } + page.appendEntry("Mousewheel Increment", GlobalTextureBrowser().m_mouseWheelScrollIncrement); + { + const char* startup_shaders[] = { "None", TextureBrowser_getComonShadersName() }; + page.appendCombo("Load Shaders at Startup", reinterpret_cast(GlobalTextureBrowser().m_startupShaders), STRING_ARRAY_RANGE(startup_shaders)); + } +} +void TextureBrowser_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Texture Browser", "Texture Browser Preferences")); + TextureBrowser_constructPreferences(page); +} +void TextureBrowser_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + + +#include "preferencesystem.h" +#include "stringio.h" + +typedef ReferenceCaller1 TextureBrowserSetScaleCaller; + + + +void TextureClipboard_textureSelected(const char* shader); + +void TextureBrowser_Construct() +{ + GlobalCommands_insert("ShaderInfo", FreeCaller()); + GlobalCommands_insert("ShowUntagged", FreeCaller()); + GlobalCommands_insert("AddTag", FreeCaller()); + GlobalCommands_insert("RenameTag", FreeCaller()); + GlobalCommands_insert("DeleteTag", FreeCaller()); + GlobalCommands_insert("CopyTag", FreeCaller()); + GlobalCommands_insert("PasteTag", FreeCaller()); + GlobalCommands_insert("RefreshShaders", FreeCaller()); + GlobalToggles_insert("ShowInUse", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_hideunused_item), Accelerator('U')); + GlobalCommands_insert("ShowAllTextures", FreeCaller(), Accelerator('A', (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("ToggleTextures", FreeCaller(), Accelerator('T')); + GlobalToggles_insert("ToggleShowShaders", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_showshaders_item)); + GlobalToggles_insert("ToggleShowShaderlistOnly", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_showshaderlistonly_item)); + GlobalToggles_insert("FixedSize", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_fixedsize_item)); + GlobalToggles_insert("FilterNotex", FreeCaller(), ToggleItem::AddCallbackCaller(g_TextureBrowser.m_filternotex_item)); + + GlobalPreferenceSystem().registerPreference("TextureScale", + makeSizeStringImportCallback(TextureBrowserSetScaleCaller(g_TextureBrowser)), + SizeExportStringCaller(g_TextureBrowser.m_textureScale) + ); + GlobalPreferenceSystem().registerPreference("TextureScrollbar", + makeBoolStringImportCallback(TextureBrowserImportShowScrollbarCaller(g_TextureBrowser)), + BoolExportStringCaller(GlobalTextureBrowser().m_showTextureScrollbar) + ); + GlobalPreferenceSystem().registerPreference("ShowShaders", BoolImportStringCaller(GlobalTextureBrowser().m_showShaders), BoolExportStringCaller(GlobalTextureBrowser().m_showShaders)); + GlobalPreferenceSystem().registerPreference("ShowShaderlistOnly", BoolImportStringCaller(g_TextureBrowser_shaderlistOnly), BoolExportStringCaller(g_TextureBrowser_shaderlistOnly)); + GlobalPreferenceSystem().registerPreference("FixedSize", BoolImportStringCaller(g_TextureBrowser_fixedSize), BoolExportStringCaller(g_TextureBrowser_fixedSize)); + GlobalPreferenceSystem().registerPreference("FilterNotex", BoolImportStringCaller(g_TextureBrowser_filterNotex), BoolExportStringCaller(g_TextureBrowser_filterNotex)); + GlobalPreferenceSystem().registerPreference("LoadShaders", IntImportStringCaller(reinterpret_cast(GlobalTextureBrowser().m_startupShaders)), IntExportStringCaller(reinterpret_cast(GlobalTextureBrowser().m_startupShaders))); + GlobalPreferenceSystem().registerPreference("WheelMouseInc", SizeImportStringCaller(GlobalTextureBrowser().m_mouseWheelScrollIncrement), SizeExportStringCaller(GlobalTextureBrowser().m_mouseWheelScrollIncrement)); + GlobalPreferenceSystem().registerPreference("SI_Colors0", Vector3ImportStringCaller(GlobalTextureBrowser().color_textureback), Vector3ExportStringCaller(GlobalTextureBrowser().color_textureback)); + + g_TextureBrowser.shader = texdef_name_default(); + + Textures_setModeChangedNotify(ReferenceCaller(g_TextureBrowser)); + + TextureBrowser_registerPreferencesPage(); + + GlobalShaderSystem().attach(g_ShadersObserver); + + TextureBrowser_textureSelected = TextureClipboard_textureSelected; +} +void TextureBrowser_Destroy() +{ + GlobalShaderSystem().detach(g_ShadersObserver); + + Textures_setModeChangedNotify(Callback()); +} diff --git a/misc/mediasource/netradiant-src/radiant/texwindow.h b/misc/mediasource/netradiant-src/radiant/texwindow.h new file mode 100644 index 00000000..c5dbf33c --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/texwindow.h @@ -0,0 +1,62 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_TEXWINDOW_H) +#define INCLUDED_TEXWINDOW_H + +#include "math/vector.h" +#include "generic/callbackfwd.h" +#include "signal/signalfwd.h" +#include "xml/xmltextags.h" + +typedef struct _GtkWidget GtkWidget; + +class TextureBrowser; +TextureBrowser& GlobalTextureBrowser(); + +typedef struct _GtkWindow GtkWindow; +GtkWidget* TextureBrowser_constructWindow(GtkWindow* toplevel); +void TextureBrowser_destroyWindow(); + + +void TextureBrowser_ShowDirectory(TextureBrowser& textureBrowser, const char* name); +void TextureBrowser_ShowStartupShaders(TextureBrowser& textureBrowser); + +const char* TextureBrowser_GetSelectedShader(TextureBrowser& textureBrower); + +void TextureBrowser_Construct(); +void TextureBrowser_Destroy(); + +typedef Callback1 StringImportCallback; +template +class FreeCaller1; + +extern GtkWidget* g_page_textures; +void TextureBrowser_exportTitle(const StringImportCallback& importer); +typedef FreeCaller1 TextureBrowserExportTitleCaller; + +const Vector3& TextureBrowser_getBackgroundColour(TextureBrowser& textureBrowser); +void TextureBrowser_setBackgroundColour(TextureBrowser& textureBrowser, const Vector3& colour); + +void TextureBrowser_addActiveShadersChangedCallback(const SignalHandler& handler); +void TextureBrowser_addShadersRealiseCallback(const SignalHandler& handler); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/timer.cpp b/misc/mediasource/netradiant-src/radiant/timer.cpp new file mode 100644 index 00000000..617112e1 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/timer.cpp @@ -0,0 +1,109 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "timer.h" + + +#if defined(WIN32) + +#include + +MillisecondTime MillisecondTime::current() +{ + static class Cached + { + LONGLONG m_frequency; + LONGLONG m_base; + public: + Cached() + { + QueryPerformanceFrequency((LARGE_INTEGER *) &m_frequency); + QueryPerformanceCounter((LARGE_INTEGER *) &m_base); + } + LONGLONG frequency() + { + return m_frequency; + } + LONGLONG base() + { + return m_base; + } + } cached; + + if(cached.frequency() > 0) + { + LONGLONG count; + QueryPerformanceCounter((LARGE_INTEGER *) &count); + return time_from_ticks(count - cached.base(), cached.frequency()); + } + else + { +#if 1 + return MillisecondTime(); +#else + return time_from_ticks(timeGetTime(), 1000); +#endif + } +} + + + + +#elif defined(POSIX) + +#include +#include "sys/time.h" + +MillisecondTime MillisecondTime::current() +{ + static class Cached + { + time_t m_base; + public: + Cached() + { + time(&m_base); + } + time_t base() + { + return m_base; + } + } cached; + + timeval time; + gettimeofday(&time, 0); + return MillisecondTime((time.tv_sec - cached.base()) * 1000 + time.tv_usec / 1000); +} + + + +#else + +#include + +MillisecondTime MillisecondTime::current() +{ + return time_from_ticks(std::clock(), CLOCKS_PER_SEC); +} + + + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/timer.h b/misc/mediasource/netradiant-src/radiant/timer.h new file mode 100644 index 00000000..a8945200 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/timer.h @@ -0,0 +1,103 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 (INCLUDED_TIMER_H) +#define INCLUDED_TIMER_H + +#if 1 + +const int msec_per_sec = 1000; + +class MillisecondTime +{ + unsigned int m_milliseconds; +public: + MillisecondTime(unsigned int milliseconds) + : m_milliseconds(milliseconds) + { + } + MillisecondTime() + { + } + static MillisecondTime current(); + + unsigned int milliseconds_since(const MillisecondTime& other) const + { + return m_milliseconds - other.m_milliseconds; + } +}; + +template +inline MillisecondTime time_from_ticks(tick_type tick_count, tick_type ticks_per_sec) +{ + return MillisecondTime(static_cast(tick_count / static_cast(ticks_per_sec / msec_per_sec))); +} + +#else + +const unsigned int usec_per_sec = 1000000; + +class MillisecondTime +{ + unsigned int m_sec; + unsigned int m_usec; +public: + MillisecondTime(unsigned int sec, unsigned int usec) + : m_sec(sec), m_usec(usec) + { + } + MillisecondTime() + { + } + staticMillisecondTime current(); + + unsigned int milliseconds_since(const MillisecondTime& other) const + { + return static_cast((m_sec * static_cast(usec_per_sec) + m_usec) + - (other.m_sec * static_cast(usec_per_sec) + other.m_usec)) / 1000; + } +}; + +template +inline MillisecondTime time_from_ticks(tick_type tick_count, tick_type ticks_per_sec) +{ + return MillisecondTime(static_cast(tick_count / ticks_per_sec), + static_cast((tick_count % ticks_per_sec) * (usec_per_sec / static_cast(ticks_per_sec)))); +} + +#endif + +class Timer +{ + MillisecondTime m_start; + +public: + void start() + { + m_start = MillisecondTime::current(); + } + unsigned int elapsed_msec() + { + return MillisecondTime::current().milliseconds_since(m_start); + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/treemodel.cpp b/misc/mediasource/netradiant-src/radiant/treemodel.cpp new file mode 100644 index 00000000..cd13ecff --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/treemodel.cpp @@ -0,0 +1,1551 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "treemodel.h" + +#include "debugging/debugging.h" + +#include +#include +#include +#include + +#include "iscenegraph.h" +#include "nameable.h" + +#include "generic/callback.h" +#include "scenelib.h" +#include "string/string.h" +#include "generic/reference.h" + +inline Nameable* Node_getNameable(scene::Node& node) +{ + return NodeTypeCast::cast(node); +} + +#if 0 + +#include "gtkutil/gtktreestore.h" + +template +inline void gtk_tree_model_get_pointer(GtkTreeModel* model, GtkTreeIter* iter, gint column, value_type** pointer) +{ + GValue value = GValue_default(); + gtk_tree_model_get_value(model, iter, column, &value); + *pointer = (value_type*)g_value_get_pointer(&value); +} + + +typedef GtkTreeStore GraphTreeModel; + +GtkTreeStore* graph_tree_model_new(graph_type* graph) +{ + return gtk_tree_store_new(2, G_TYPE_POINTER, G_TYPE_POINTER); +} + +void graph_tree_model_delete(GraphTreeModel* model) +{ + g_object_unref(G_OBJECT(model)); +} + + +bool graph_tree_model_subtree_find_node(GraphTreeModel* model, GtkTreeIter* parent, const scene::Node& node, GtkTreeIter* iter) +{ + for(gboolean success = gtk_tree_model_iter_children(GTK_TREE_MODEL(model), iter, parent); + success != FALSE; + success = gtk_tree_model_iter_next(GTK_TREE_MODEL(model), iter)) + { + scene::Node* current; + gtk_tree_model_get_pointer(GTK_TREE_MODEL(model), iter, 0, ¤t); + if(current == node) + { + return true; + } + } + return false; +} + +typedef GtkTreeIter DoubleGtkTreeIter[2]; + +bool graph_tree_model_find_top(GraphTreeModel* model, const scene::Path& path, GtkTreeIter& iter) +{ + int swap = 0; + GtkTreeIter* parent_pointer = NULL; + GtkTreeIter parent; + for(scene::Path::const_iterator i = path.begin(); i != path.end(); ++i) + { + if(!graph_tree_model_subtree_find_node(model, parent_pointer, *i, &iter)) + { + return false; + } + parent = iter; + parent_pointer = &parent; + } + return true; +} + +bool graph_tree_model_find_parent(GraphTreeModel* model, const scene::Path& path, GtkTreeIter& iter) +{ + int swap = 0; + GtkTreeIter* parent_pointer = NULL; + ASSERT_MESSAGE(path.size() > 1, "path too short"); + for(scene::Path::const_iterator i = path.begin(); i != path.end()-1; ++i) + { + GtkTreeIter child; + if(!graph_tree_model_subtree_find_node(model, parent_pointer, *i, &child)) + { + return false; + } + iter = child; + parent_pointer = &iter; + } + return true; +} + +void node_attach_name_changed_callback(scene::Node& node, const Callback& callback) +{ + if(node != 0) + { + Nameable* nameable = Node_getNameable(node); + if(nameable != 0) + { + nameable->attach(callback); + } + } +} +void node_detach_name_changed_callback(scene::Node& node, const Callback& callback) +{ + if(node != 0) + { + Nameable* nameable = Node_getNameable(node); + if(nameable != 0) + { + nameable->detach(callback); + } + } +} + +GraphTreeModel* scene_graph_get_tree_model(); // temp hack + +void graph_tree_model_row_changed(const scene::Instance& instance) +{ + GraphTreeModel* model = scene_graph_get_tree_model(); + + GtkTreeIter child; + ASSERT_MESSAGE(graph_tree_model_find_top(model, instance.path(), child), "RUNTIME ERROR"); + + gtk_tree_store_set(GTK_TREE_STORE(model), &child, 0, instance.path().top(), -1); +} + +void graph_tree_model_row_inserted(GraphTreeModel* model, const scene::Instance& instance) +{ + GtkTreeIter parent; + GtkTreeIter* parent_pointer = NULL; + if(instance.path().size() != 1) + { + ASSERT_MESSAGE(graph_tree_model_find_parent(model, instance.path(), parent), "RUNTIME ERROR"); + parent_pointer = &parent; + } + + gpointer node = instance.path().top(); + gconstpointer selectable = Instance_getSelectable(instance); + + GtkTreeIter child; + gtk_tree_store_append(GTK_TREE_STORE(model), &child, parent_pointer); + gtk_tree_store_set(GTK_TREE_STORE(model), &child, 0, node, 1, selectable, -1); + + node_attach_name_changed_callback(instance.path().top(), ConstReferenceCaller(instance)); +} + +void graph_tree_model_row_deleted(GraphTreeModel* model, const scene::Instance& instance) +{ + GtkTreeIter child; + ASSERT_MESSAGE(graph_tree_model_find_top(model, instance.path(), child), "RUNTIME ERROR"); + + node_detach_name_changed_callback(instance.path().top(), ConstReferenceCaller(instance)); + + gtk_tree_store_remove(GTK_TREE_STORE(model), &child); +} + +#elif 0 + +const char* node_get_name(scene::Node& node); + +typedef scene::Node* NodePointer; + +class NodeNameLess +{ +public: + bool operator()(const NodePointer& self, const NodePointer& other) const + { + if(self == 0) + { + return true; + } + if(other == 0) + { + return false; + } + int result = string_compare(node_get_name(self), node_get_name(other)); + if(result == 0) + { + return self < other; + } + return result < 0; + } +}; + +class PathNameLess +{ +public: + bool operator()(const PathConstReference& self, const PathConstReference& other) const + { + return std::lexicographical_compare(self.get().begin(), self.get().end(), other.get().begin(), other.get().end(), NodeNameLess()); + } +}; + +typedef std::map graph_type; + +struct GraphTreeModel +{ + GObject parent; + + graph_type* graph; +}; + +struct GraphTreeModelClass +{ + GObjectClass parent_class; +}; + +#define GRAPH_TREE_MODEL(p) (reinterpret_cast(p)) + +static GtkTreeModelFlags graph_tree_model_get_flags (GtkTreeModel* tree_model) +{ + return GTK_TREE_MODEL_ITERS_PERSIST; +} + +static gint graph_tree_model_get_n_columns (GtkTreeModel* tree_model) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeModel* graph_tree_model = (GraphTreeModel*) tree_model; + + return 2; +} + +static const gint c_stamp = 0xabcdef; + +inline graph_type::iterator graph_iterator_read_tree_iter(GtkTreeIter* iter) +{ + ASSERT_MESSAGE(iter != 0, "tree model error"); + ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); + ASSERT_MESSAGE(iter->stamp == c_stamp, "tree model error"); + return *reinterpret_cast(&iter->user_data); +} + +inline void graph_iterator_write_tree_iter(graph_type::iterator i, GtkTreeIter* iter) +{ + ASSERT_MESSAGE(iter != 0, "tree model error"); + iter->stamp = c_stamp; + *reinterpret_cast(&iter->user_data) = i; + ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); +} + +static GType graph_tree_model_get_column_type (GtkTreeModel *tree_model, gint index) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeModel *graph_tree_model = (GraphTreeModel *) tree_model; + + return G_TYPE_POINTER; +} + +static gboolean graph_tree_model_get_iter(GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreePath* path) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + gint* indices = gtk_tree_path_get_indices (path); + gint depth = gtk_tree_path_get_depth (path); + + g_return_val_if_fail (depth > 0, FALSE); + + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + + if(graph.empty()) + return FALSE; + + GtkTreeIter tmp; + GtkTreeIter* parent = 0; + + for(gint i = 0; i < depth; i++) + { + if (! gtk_tree_model_iter_nth_child (tree_model, iter, parent, indices[i])) + return FALSE; + tmp = *iter; + parent = &tmp; + } + + return TRUE; +} + +static GtkTreePath* graph_tree_model_get_path(GtkTreeModel* tree_model, GtkTreeIter* iter) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + graph_type::iterator i = graph_iterator_read_tree_iter(iter); + + GtkTreePath* path = gtk_tree_path_new(); + + for(std::size_t depth = (*i).first.get().size(); depth != 0; --depth) + { + std::size_t index = 0; + + while(i != graph.begin() && (*i).first.get().size() >= depth) + { + --i; + if((*i).first.get().size() == depth) + ++index; + } + + gtk_tree_path_prepend_index(path, index); + } + + return path; +} + + +static void graph_tree_model_get_value (GtkTreeModel *tree_model, GtkTreeIter *iter, gint column, GValue *value) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + ASSERT_MESSAGE(column == 0 || column == 1, "tree model error"); + + graph_type::iterator i = graph_iterator_read_tree_iter(iter); + + g_value_init (value, G_TYPE_POINTER); + + if(column == 0) + g_value_set_pointer(value, reinterpret_cast((*i).first.get().top())); + else + g_value_set_pointer(value, reinterpret_cast(Instance_getSelectable(*(*i).second))); +} + +static gboolean graph_tree_model_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + graph_type::iterator i = graph_iterator_read_tree_iter(iter); + std::size_t depth = (*i).first.get().size(); + + ++i; + + while(i != graph.end() && (*i).first.get().size() > depth) + { + ++i; + } + + if(i == graph.end() || (*i).first.get().size() != depth) + { + return FALSE; + } + + graph_iterator_write_tree_iter(i, iter); + + return TRUE; +} + +static gboolean graph_tree_model_iter_children (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + graph_type::iterator i = (parent == 0) ? graph.begin() : graph_iterator_read_tree_iter(parent); + std::size_t depth = (parent == 0) ? 1 : (*i).first.get().size() + 1; + + if(parent != 0) + ++i; + + if(i != graph.end() && (*i).first.get().size() == depth) + { + graph_iterator_write_tree_iter(i, iter); + return TRUE; + } + + return FALSE; +} + +static gboolean graph_tree_model_iter_has_child (GtkTreeModel *tree_model, GtkTreeIter *iter) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + graph_type::iterator i = graph_iterator_read_tree_iter(iter); + std::size_t depth = (*i).first.get().size() + 1; + + return ++i != graph.end() && (*i).first.get().size() == depth; +} + +static gint graph_tree_model_iter_n_children (GtkTreeModel *tree_model, GtkTreeIter *parent) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + graph_type::iterator i = (parent == 0) ? graph.begin() : graph_iterator_read_tree_iter(parent); + std::size_t depth = (parent == 0) ? 1 : (*i).first.get().size() + 1; + + if(parent != 0) + ++i; + + gint count = 0; + while(i != graph.end() && (*i).first.get().size() >= depth) + { + ++count; + ++i; + } + + return count; +} + +static gboolean graph_tree_model_iter_nth_child (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent, gint n) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + graph_type::iterator i = (parent == 0) ? graph.begin() : graph_iterator_read_tree_iter(parent); + std::size_t depth = (parent == 0) ? 1 : (*i).first.get().size() + 1; + + if(parent != 0) + ++i; + + while(i != graph.end() && (*i).first.get().size() >= depth) + { + if((*i).first.get().size() == depth && n-- == 0) + { + graph_iterator_write_tree_iter(i, iter); + return TRUE; + } + ++i; + } + + return FALSE; +} + +static gboolean graph_tree_model_iter_parent(GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *child) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + graph_type& graph = *GRAPH_TREE_MODEL(tree_model)->graph; + graph_type::iterator i = graph_iterator_read_tree_iter(child); + std::size_t depth = (*i).first.get().size(); + if(depth == 1) + { + return FALSE; + } + else + { + do + { + --i; + } + while((*i).first.get().size() >= depth); + graph_iterator_write_tree_iter(i, iter); + return TRUE; + } +} + +static GObjectClass *g_parent_class = 0; + +static void graph_tree_model_init (GraphTreeModel *graph_tree_model) +{ + graph_tree_model->graph = 0; +} + +static void graph_tree_model_finalize(GObject* object) +{ + GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(object); + + /* must chain up */ + (* g_parent_class->finalize) (object); +} + +static void graph_tree_model_class_init (GraphTreeModelClass *class_) +{ + GObjectClass *object_class; + + g_parent_class = (GObjectClass*)g_type_class_peek_parent (class_); + object_class = (GObjectClass *) class_; + + object_class->finalize = graph_tree_model_finalize; +} + +static void graph_tree_model_tree_model_init (GtkTreeModelIface *iface) +{ + iface->get_flags = graph_tree_model_get_flags; + iface->get_n_columns = graph_tree_model_get_n_columns; + iface->get_column_type = graph_tree_model_get_column_type; + iface->get_iter = graph_tree_model_get_iter; + iface->get_path = graph_tree_model_get_path; + iface->get_value = graph_tree_model_get_value; + iface->iter_next = graph_tree_model_iter_next; + iface->iter_children = graph_tree_model_iter_children; + iface->iter_has_child = graph_tree_model_iter_has_child; + iface->iter_n_children = graph_tree_model_iter_n_children; + iface->iter_nth_child = graph_tree_model_iter_nth_child; + iface->iter_parent = graph_tree_model_iter_parent; +} + +static gboolean graph_tree_model_row_draggable(GtkTreeDragSource *drag_source, GtkTreePath *path) +{ +#ifdef _DEBUG + gint depth = gtk_tree_path_get_depth(path); +#endif + return gtk_tree_path_get_depth(path) > 1; +} + +static gboolean graph_tree_model_drag_data_delete(GtkTreeDragSource *drag_source, GtkTreePath *path) +{ + GtkTreeIter iter; + + if(gtk_tree_model_get_iter(GTK_TREE_MODEL(drag_source), &iter, path)) + { + graph_type::iterator i = graph_iterator_read_tree_iter(&iter); + Path_deleteTop((*i).first); + return TRUE; + } + else + { + return FALSE; + } +} + +static gboolean graph_tree_model_drag_data_get (GtkTreeDragSource *drag_source, GtkTreePath *path, GtkSelectionData *selection_data) +{ + if(gtk_tree_set_row_drag_data(selection_data, GTK_TREE_MODEL(drag_source), path)) + { + return TRUE; + } + else + { + /* FIXME handle text targets at least. */ + } + + return FALSE; +} + +static void graph_tree_model_drag_source_init (GtkTreeDragSourceIface *iface) +{ + iface->row_draggable = graph_tree_model_row_draggable; + iface->drag_data_delete = graph_tree_model_drag_data_delete; + iface->drag_data_get = graph_tree_model_drag_data_get; +} + +static gboolean graph_tree_model_drag_data_received (GtkTreeDragDest *drag_dest, GtkTreePath *dest, GtkSelectionData *selection_data) +{ + GtkTreeModel *tree_model = GTK_TREE_MODEL (drag_dest); + + GtkTreeModel *src_model = 0; + GtkTreePath *src_path = 0; + if(gtk_tree_get_row_drag_data(selection_data, &src_model, &src_path) + && src_model == tree_model) + { + /* Copy the given row to a new position */ + GtkTreeIter iter; + + if(gtk_tree_model_get_iter(src_model, &iter, src_path)) + { + int bleh = 0; + } + } + else + { + /* FIXME maybe add some data targets eventually, or handle text + * targets in the simple case. + */ + } + + return FALSE; +} + +static gboolean graph_tree_model_row_drop_possible(GtkTreeDragDest *drag_dest, GtkTreePath *dest_path, GtkSelectionData *selection_data) +{ + gboolean retval = FALSE; + + GtkTreeModel *src_model = 0; + GtkTreePath *src_path = 0; + if(gtk_tree_get_row_drag_data(selection_data, &src_model, &src_path) != FALSE) + { + /* can only drag to ourselves */ + if(src_model == GTK_TREE_MODEL(drag_dest)) + { + /* Can't drop into ourself. */ + if(!gtk_tree_path_is_ancestor(src_path, dest_path)) + { + /* Can't drop if dest_path's parent doesn't exist */ + if (gtk_tree_path_get_depth (dest_path) > 1) + { + GtkTreePath* tmp = gtk_tree_path_copy (dest_path); + gtk_tree_path_up (tmp); + + GtkTreeIter iter; + retval = gtk_tree_model_get_iter (GTK_TREE_MODEL (drag_dest), &iter, tmp); + + gtk_tree_path_free (tmp); + } + } + } + + gtk_tree_path_free (src_path); + } + + return retval; +} + +static void graph_tree_model_drag_dest_init (GtkTreeDragDestIface *iface) +{ + iface->drag_data_received = graph_tree_model_drag_data_received; + iface->row_drop_possible = graph_tree_model_row_drop_possible; +} + +GType graph_tree_model_get_type (void) +{ + static GType graph_tree_model_type = 0; + + if (!graph_tree_model_type) + { + static const GTypeInfo graph_tree_model_info = + { + sizeof (GraphTreeModelClass), + 0, /* base_init */ + 0, /* base_finalize */ + (GClassInitFunc) graph_tree_model_class_init, + 0, /* class_finalize */ + 0, /* class_data */ + sizeof (GraphTreeModel), + 0, /* n_preallocs */ + (GInstanceInitFunc) graph_tree_model_init + }; + + static const GInterfaceInfo tree_model_info = + { + (GInterfaceInitFunc) graph_tree_model_tree_model_init, + 0, + 0 + }; + + static const GInterfaceInfo drag_source_info = + { + (GInterfaceInitFunc) graph_tree_model_drag_source_init, + 0, + 0 + }; + + static const GInterfaceInfo drag_dest_info = + { + (GInterfaceInitFunc) graph_tree_model_drag_dest_init, + 0, + 0 + }; + + graph_tree_model_type = g_type_register_static (G_TYPE_OBJECT, "GraphTreeModel", + &graph_tree_model_info, (GTypeFlags)0); + + g_type_add_interface_static (graph_tree_model_type, + GTK_TYPE_TREE_MODEL, + &tree_model_info); + g_type_add_interface_static (graph_tree_model_type, + GTK_TYPE_TREE_DRAG_SOURCE, + &drag_source_info); + g_type_add_interface_static (graph_tree_model_type, + GTK_TYPE_TREE_DRAG_DEST, + &drag_dest_info); + } + + return graph_tree_model_type; +} + +GraphTreeModel* graph_tree_model_new() +{ + GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(g_object_new (graph_tree_model_get_type(), 0)); + + graph_tree_model->graph = new graph_type; + + return graph_tree_model; +} + +void graph_tree_model_delete(GraphTreeModel* model) +{ + delete model->graph; + g_object_unref(G_OBJECT(model)); +} + + +class TempNameable : public Nameable +{ + const char* m_name; +public: + TempNameable(const char* name) : m_name(name) + { + } + const char* name() const + { + return m_name; + } + void attach(const NameCallback& callback) + { + } + void detach(const NameCallback& callback) + { + } +}; + +void node_attach_name_changed_callback(scene::Node& node, const NameCallback& callback) +{ + if(&node != 0) + { + Nameable* nameable = Node_getNameable(node); + if(nameable != 0) + { + nameable->attach(callback); + } + } +} +void node_detach_name_changed_callback(scene::Node& node, const NameCallback& callback) +{ + if(&node != 0) + { + Nameable* nameable = Node_getNameable(node); + if(nameable != 0) + { + nameable->detach(callback); + } + } +} + +GraphTreeModel* scene_graph_get_tree_model(); // temp hack + +void graph_tree_model_row_inserted(GraphTreeModel* model, graph_type::iterator i) +{ + GtkTreeIter iter; + graph_iterator_write_tree_iter(i, &iter); + + GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); + + gint depth = gtk_tree_path_get_depth(tree_path); + gint* indices = gtk_tree_path_get_indices(tree_path); + + gtk_tree_model_row_inserted(GTK_TREE_MODEL(model), tree_path, &iter); + + gtk_tree_path_free(tree_path); +} + +void graph_tree_model_row_deleted(GraphTreeModel* model, graph_type::iterator i) +{ + GtkTreeIter iter; + graph_iterator_write_tree_iter(i, &iter); + + GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); + + gtk_tree_model_row_deleted(GTK_TREE_MODEL(model), tree_path); + + gtk_tree_path_free(tree_path); +} + +#include "generic/referencecounted.h" + +void graph_tree_model_set_name(const scene::Instance& instance, const char* name) +{ + GraphTreeModel* model = scene_graph_get_tree_model(); + + if(string_empty(name)) // hack! + { + graph_type::iterator i = model->graph->find(PathConstReference(instance.path())); + ASSERT_MESSAGE(i != model->graph->end(), "ERROR"); + + graph_tree_model_row_deleted(model, i); + + model->graph->erase(i); + } + else + { + graph_type::iterator i = model->graph->insert(graph_type::value_type(PathConstReference(instance.path()), &const_cast(instance))).first; + + graph_tree_model_row_inserted(model, i); + } +} + +void graph_tree_model_insert(GraphTreeModel* model, const scene::Instance& instance) +{ + graph_type::iterator i = model->graph->insert(graph_type::value_type(PathConstReference(instance.path()), &const_cast(instance))).first; + + graph_tree_model_row_inserted(model, i); + + node_attach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); +} + +void graph_tree_model_erase(GraphTreeModel* model, const scene::Instance& instance) +{ + node_detach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); + + graph_type::iterator i = model->graph->find(PathConstReference(instance.path())); + ASSERT_MESSAGE(i != model->graph->end(), "ERROR"); + + graph_tree_model_row_deleted(model, i); + + model->graph->erase(i); +} + +#elif 1 + +class GraphTreeNode; +void graph_tree_model_row_changed(GraphTreeNode& node); + +class GraphTreeNode +{ + typedef std::map, GraphTreeNode*> ChildNodes; + ChildNodes m_childnodes; +public: + Reference m_instance; + GraphTreeNode* m_parent; + + typedef ChildNodes::iterator iterator; + typedef ChildNodes::key_type key_type; + typedef ChildNodes::value_type value_type; + typedef ChildNodes::size_type size_type; + + GraphTreeNode(scene::Instance& instance) : m_instance(instance), m_parent(0) + { + m_instance.get().setChildSelectedChangedCallback(RowChangedCaller(*this)); + } + ~GraphTreeNode() + { + m_instance.get().setChildSelectedChangedCallback(Callback()); + ASSERT_MESSAGE(empty(), "GraphTreeNode::~GraphTreeNode: memory leak"); + } + + iterator begin() + { + return m_childnodes.begin(); + } + iterator end() + { + return m_childnodes.end(); + } + + size_type size() const + { + return m_childnodes.size(); + } + bool empty() const + { + return m_childnodes.empty(); + } + + iterator insert(const value_type& value) + { + iterator i = m_childnodes.insert(value).first; + (*i).second->m_parent = this; + return i; + } + void erase(iterator i) + { + m_childnodes.erase(i); + } + iterator find(const key_type& key) + { + return m_childnodes.find(key); + } + + void swap(GraphTreeNode& other) + { + std::swap(m_parent, other.m_parent); + std::swap(m_childnodes, other.m_childnodes); + std::swap(m_instance, other.m_instance); + } + + void rowChanged() + { + graph_tree_model_row_changed(*this); + } + typedef MemberCaller RowChangedCaller; +}; + +struct GraphTreeModel +{ + GObject parent; + + GraphTreeNode* m_graph; +}; + +struct GraphTreeModelClass +{ + GObjectClass parent_class; +}; + +#define GRAPH_TREE_MODEL(p) (reinterpret_cast(p)) + +static GtkTreeModelFlags graph_tree_model_get_flags (GtkTreeModel* tree_model) +{ + return GTK_TREE_MODEL_ITERS_PERSIST; +} + +static gint graph_tree_model_get_n_columns (GtkTreeModel* tree_model) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + //GraphTreeModel* graph_tree_model = (GraphTreeModel*) tree_model; + + return 2; +} + +static const gint c_stamp = 0xabcdef; + +inline GraphTreeNode::iterator graph_iterator_read_tree_iter(GtkTreeIter* iter) +{ + ASSERT_MESSAGE(iter != 0, "tree model error"); + ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); + ASSERT_MESSAGE(iter->stamp == c_stamp, "tree model error"); + return *reinterpret_cast(&iter->user_data); +} + +inline void graph_iterator_write_tree_iter(GraphTreeNode::iterator i, GtkTreeIter* iter) +{ + ASSERT_MESSAGE(iter != 0, "tree model error"); + iter->stamp = c_stamp; + *reinterpret_cast(&iter->user_data) = i; + ASSERT_MESSAGE(iter->user_data != 0, "tree model error"); +} + +static GType graph_tree_model_get_column_type (GtkTreeModel *tree_model, gint index) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + //GraphTreeModel *graph_tree_model = (GraphTreeModel *) tree_model; + + return G_TYPE_POINTER; +} + +static gboolean graph_tree_model_get_iter(GtkTreeModel* tree_model, GtkTreeIter* iter, GtkTreePath* path) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + gint* indices = gtk_tree_path_get_indices (path); + gint depth = gtk_tree_path_get_depth (path); + + g_return_val_if_fail (depth > 0, FALSE); + + GraphTreeNode* graph = GRAPH_TREE_MODEL(tree_model)->m_graph; + + if(graph->empty()) + return FALSE; + + GtkTreeIter tmp; + GtkTreeIter* parent = 0; + + for(gint i = 0; i < depth; i++) + { + if (! gtk_tree_model_iter_nth_child (tree_model, iter, parent, indices[i])) + return FALSE; + tmp = *iter; + parent = &tmp; + } + + return TRUE; +} + +static GtkTreePath* graph_tree_model_get_path(GtkTreeModel* tree_model, GtkTreeIter* iter) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeNode* graph = GRAPH_TREE_MODEL(tree_model)->m_graph; + + GtkTreePath* path = gtk_tree_path_new(); + + for(GraphTreeNode* node = (*graph_iterator_read_tree_iter(iter)).second; node != graph; node = node->m_parent) + { + std::size_t index = 0; + for(GraphTreeNode::iterator i = node->m_parent->begin(); i != node->m_parent->end(); ++i, ++index) + { + if((*i).second == node) + { + gtk_tree_path_prepend_index(path, gint(index)); + break; + } + } + ASSERT_MESSAGE(index != node->m_parent->size(), "error resolving tree path"); + } + + return path; +} + + +static void graph_tree_model_get_value (GtkTreeModel *tree_model, GtkTreeIter *iter, gint column, GValue *value) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + ASSERT_MESSAGE(column == 0 || column == 1, "tree model error"); + + GraphTreeNode::iterator i = graph_iterator_read_tree_iter(iter); + + g_value_init (value, G_TYPE_POINTER); + + if(column == 0) + { + g_value_set_pointer(value, reinterpret_cast((*i).first.second)); + } + else + { + g_value_set_pointer(value, reinterpret_cast(&(*i).second->m_instance.get())); + } +} + +static gboolean graph_tree_model_iter_next (GtkTreeModel *tree_model, GtkTreeIter *iter) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeNode::iterator i = graph_iterator_read_tree_iter(iter); + GraphTreeNode& parent = *(*i).second->m_parent; + + ASSERT_MESSAGE(i != parent.end(), "RUNTIME ERROR"); + + if(++i == parent.end()) + { + return FALSE; + } + + graph_iterator_write_tree_iter(i, iter); + + return TRUE; +} + +static gboolean graph_tree_model_iter_children (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeNode& node = (parent == 0) ? *GRAPH_TREE_MODEL(tree_model)->m_graph : *(*graph_iterator_read_tree_iter(parent)).second; + if(!node.empty()) + { + graph_iterator_write_tree_iter(node.begin(), iter); + return TRUE; + } + + return FALSE; +} + +static gboolean graph_tree_model_iter_has_child (GtkTreeModel *tree_model, GtkTreeIter *iter) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeNode& node = *(*graph_iterator_read_tree_iter(iter)).second; + return !node.empty(); +} + +static gint graph_tree_model_iter_n_children (GtkTreeModel *tree_model, GtkTreeIter *parent) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeNode& node = (parent == 0) ? *GRAPH_TREE_MODEL(tree_model)->m_graph : *(*graph_iterator_read_tree_iter(parent)).second; + return static_cast(node.size()); +} + +static gboolean graph_tree_model_iter_nth_child (GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *parent, gint n) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeNode& node = (parent == 0) ? *GRAPH_TREE_MODEL(tree_model)->m_graph : *(*graph_iterator_read_tree_iter(parent)).second; + if(static_cast(n) < node.size()) + { + GraphTreeNode::iterator i = node.begin(); + std::advance(i, n); + graph_iterator_write_tree_iter(i, iter); + return TRUE; + } + + return FALSE; +} + +static gboolean graph_tree_model_iter_parent(GtkTreeModel *tree_model, GtkTreeIter *iter, GtkTreeIter *child) +{ + ASSERT_MESSAGE(tree_model != 0, "RUNTIME ERROR"); + GraphTreeNode& node = *(*graph_iterator_read_tree_iter(child)).second; + if(node.m_parent != GRAPH_TREE_MODEL(tree_model)->m_graph) + { + GraphTreeNode& parentParent = *node.m_parent->m_parent; + for(GraphTreeNode::iterator i = parentParent.begin(); i != parentParent.end(); ++i) + { + if((*i).second == node.m_parent) + { + graph_iterator_write_tree_iter(i, iter); + return TRUE; + } + } + } + return FALSE; +} + +static GObjectClass *g_parent_class = 0; + +namespace +{ + scene::Node* g_null_node = 0; +} + +class NullInstance : public scene::Instance +{ +public: + NullInstance() : scene::Instance(scene::Path(makeReference(*g_null_node)), 0, 0, Static::instance()) + { + } +}; + +namespace +{ + NullInstance g_null_instance; +} + +static void graph_tree_model_init (GraphTreeModel *graph_tree_model) +{ + graph_tree_model->m_graph = new GraphTreeNode(g_null_instance); +} + +static void graph_tree_model_finalize(GObject* object) +{ + GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(object); + + delete graph_tree_model->m_graph; + + /* must chain up */ + (* g_parent_class->finalize) (object); +} + +static void graph_tree_model_class_init (GraphTreeModelClass *class_) +{ + GObjectClass *object_class; + + g_parent_class = (GObjectClass*)g_type_class_peek_parent (class_); + object_class = (GObjectClass *) class_; + + object_class->finalize = graph_tree_model_finalize; +} + +static void graph_tree_model_tree_model_init (GtkTreeModelIface *iface) +{ + iface->get_flags = graph_tree_model_get_flags; + iface->get_n_columns = graph_tree_model_get_n_columns; + iface->get_column_type = graph_tree_model_get_column_type; + iface->get_iter = graph_tree_model_get_iter; + iface->get_path = graph_tree_model_get_path; + iface->get_value = graph_tree_model_get_value; + iface->iter_next = graph_tree_model_iter_next; + iface->iter_children = graph_tree_model_iter_children; + iface->iter_has_child = graph_tree_model_iter_has_child; + iface->iter_n_children = graph_tree_model_iter_n_children; + iface->iter_nth_child = graph_tree_model_iter_nth_child; + iface->iter_parent = graph_tree_model_iter_parent; +} + +GType graph_tree_model_get_type (void) +{ + static GType graph_tree_model_type = 0; + + if (!graph_tree_model_type) + { + static const GTypeInfo graph_tree_model_info = + { + sizeof (GraphTreeModelClass), + 0, /* base_init */ + 0, /* base_finalize */ + (GClassInitFunc) graph_tree_model_class_init, + 0, /* class_finalize */ + 0, /* class_data */ + sizeof (GraphTreeModel), + 0, /* n_preallocs */ + (GInstanceInitFunc) graph_tree_model_init, + 0 + }; + + static const GInterfaceInfo tree_model_info = + { + (GInterfaceInitFunc) graph_tree_model_tree_model_init, + 0, + 0 + }; + + graph_tree_model_type = g_type_register_static (G_TYPE_OBJECT, "GraphTreeModel", + &graph_tree_model_info, (GTypeFlags)0); + + g_type_add_interface_static (graph_tree_model_type, + GTK_TYPE_TREE_MODEL, + &tree_model_info); + } + + return graph_tree_model_type; +} + +GraphTreeModel* graph_tree_model_new() +{ + GraphTreeModel* graph_tree_model = GRAPH_TREE_MODEL(g_object_new (graph_tree_model_get_type(), 0)); + + return graph_tree_model; +} + +void graph_tree_model_delete(GraphTreeModel* model) +{ + g_object_unref(G_OBJECT(model)); +} + +void graph_tree_model_row_changed(GraphTreeModel* model, GraphTreeNode::iterator i) +{ + GtkTreeIter iter; + graph_iterator_write_tree_iter(i, &iter); + + GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); + + gtk_tree_model_row_changed(GTK_TREE_MODEL(model), tree_path, &iter); + + gtk_tree_path_free(tree_path); +} + +void graph_tree_model_row_inserted(GraphTreeModel* model, GraphTreeNode::iterator i) +{ + GtkTreeIter iter; + graph_iterator_write_tree_iter(i, &iter); + + GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); + + gtk_tree_model_row_inserted(GTK_TREE_MODEL(model), tree_path, &iter); + + gtk_tree_path_free(tree_path); +} + +void graph_tree_model_row_deleted(GraphTreeModel* model, GraphTreeNode::iterator i) +{ + GtkTreeIter iter; + graph_iterator_write_tree_iter(i, &iter); + + GtkTreePath* tree_path = graph_tree_model_get_path(GTK_TREE_MODEL(model), &iter); + + gtk_tree_model_row_deleted(GTK_TREE_MODEL(model), tree_path); + + gtk_tree_path_free(tree_path); +} + +void graph_tree_model_row_inserted(GraphTreeModel& model, GraphTreeNode::iterator i) +{ + graph_tree_model_row_inserted(&model, i); +} + +void graph_tree_model_row_deleted(GraphTreeModel& model, GraphTreeNode::iterator i) +{ + graph_tree_model_row_deleted(&model, i); +} + +const char* node_get_name(scene::Node& node); + +const char* node_get_name_safe(scene::Node& node) +{ + if(&node == 0) + { + return ""; + } + return node_get_name(node); +} + +GraphTreeNode* graph_tree_model_find_parent(GraphTreeModel* model, const scene::Path& path) +{ + GraphTreeNode* parent = model->m_graph; + for(scene::Path::const_iterator i = path.begin(); i != path.end()-1; ++i) + { + GraphTreeNode::iterator child = parent->find(GraphTreeNode::key_type(node_get_name_safe((*i).get()), (*i).get_pointer())); + ASSERT_MESSAGE(child != parent->end(), "ERROR"); + parent = (*child).second; + } + return parent; +} + +void node_attach_name_changed_callback(scene::Node& node, const NameCallback& callback) +{ + if(&node != 0) + { + Nameable* nameable = Node_getNameable(node); + if(nameable != 0) + { + nameable->attach(callback); + } + } +} +void node_detach_name_changed_callback(scene::Node& node, const NameCallback& callback) +{ + if(&node != 0) + { + Nameable* nameable = Node_getNameable(node); + if(nameable != 0) + { + nameable->detach(callback); + } + } +} + +GraphTreeModel* scene_graph_get_tree_model(); // temp hack + +void graph_tree_node_foreach_pre(GraphTreeNode::iterator root, const Callback1& callback) +{ + callback(root); + for(GraphTreeNode::iterator i = (*root).second->begin(); i != (*root).second->end(); ++i) + { + graph_tree_node_foreach_pre(i, callback); + } +} + +void graph_tree_node_foreach_post(GraphTreeNode::iterator root, const Callback1& callback) +{ + for(GraphTreeNode::iterator i = (*root).second->begin(); i != (*root).second->end(); ++i) + { + graph_tree_node_foreach_post(i, callback); + } + callback(root); +} + +void graph_tree_model_row_changed(GraphTreeNode& node) +{ + GraphTreeModel* model = scene_graph_get_tree_model(); + const scene::Instance& instance = node.m_instance.get(); + + GraphTreeNode::iterator i = node.m_parent->find(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer())); + + graph_tree_model_row_changed(model, i); +} + +void graph_tree_model_set_name(const scene::Instance& instance, const char* name) +{ + GraphTreeModel* model = scene_graph_get_tree_model(); + GraphTreeNode* parent = graph_tree_model_find_parent(model, instance.path()); + + GraphTreeNode::iterator oldNode = parent->find(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer())); + graph_tree_node_foreach_post(oldNode, ReferenceCaller1(*model)); + GraphTreeNode* node((*oldNode).second); + parent->erase(oldNode); + + GraphTreeNode::iterator newNode = parent->insert(GraphTreeNode::value_type(GraphTreeNode::key_type(name, &instance.path().top().get()), node)); + graph_tree_node_foreach_pre(newNode, ReferenceCaller1(*model)); +} + +void graph_tree_model_insert(GraphTreeModel* model, const scene::Instance& instance) +{ + GraphTreeNode* parent = graph_tree_model_find_parent(model, instance.path()); + + GraphTreeNode::iterator i = parent->insert(GraphTreeNode::value_type(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer()), new GraphTreeNode(const_cast(instance)))); + + graph_tree_model_row_inserted(model, i); + + node_attach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); +} + +void graph_tree_model_erase(GraphTreeModel* model, const scene::Instance& instance) +{ + node_detach_name_changed_callback(instance.path().top(), ConstReferenceCaller1(instance)); + + GraphTreeNode* parent = graph_tree_model_find_parent(model, instance.path()); + + GraphTreeNode::iterator i = parent->find(GraphTreeNode::key_type(node_get_name_safe(instance.path().top().get()), instance.path().top().get_pointer())); + + graph_tree_model_row_deleted(model, i); + + GraphTreeNode* node((*i).second); + parent->erase(i); + delete node; +} + + + +#endif + + + + +#if 0 +class TestGraphTreeModel +{ +public: + TestGraphTreeModel() + { + gtk_init(0, 0); + + graph_type graph; + + scene::Node* root = *(scene::Node*)0xa0000000; + scene::Node* node1 = (scene::Node*)0xa0000001; + scene::Node* node2 = (scene::Node*)0xa0000002; + scene::Node* node3 = (scene::Node*)0xa0000003; + scene::Node* node4 = (scene::Node*)0xa0000004; + scene::Instance* instance = (scene::Instance*)0xaaaaaaaa; + + scene::Path rootpath(root); + + graph.insert(graph_type::value_type(rootpath, instance)); + + rootpath.push(node1); + graph.insert(graph_type::value_type(rootpath, instance)); + rootpath.pop(); + + rootpath.push(node2); + graph.insert(graph_type::value_type(rootpath, instance)); + rootpath.push(node3); + graph.insert(graph_type::value_type(rootpath, instance)); + rootpath.pop(); + rootpath.push(node4); + graph.insert(graph_type::value_type(rootpath, instance)); + rootpath.pop(); + rootpath.pop(); + + GtkTreeModel* model = GTK_TREE_MODEL(graph_tree_model_new(&graph)); + + { + gint n_columns = gtk_tree_model_get_n_columns(model); + ASSERT_MESSAGE(n_columns == 2, "test failed!"); + } + + { + GType type = gtk_tree_model_get_column_type(model, 0); + ASSERT_MESSAGE(type == G_TYPE_POINTER, "test failed!"); + } + + { + GType type = gtk_tree_model_get_column_type(model, 1); + ASSERT_MESSAGE(type == G_TYPE_POINTER, "test failed!"); + } + + + { + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); + + graph_type::iterator i = graph_iterator_read_tree_iter(&iter); + ASSERT_MESSAGE((*i).first.get().size() == 2 && (*i).first.get().top() == node1, "test failed!"); + } + + { + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); + + ASSERT_MESSAGE(gtk_tree_model_iter_has_child(model, &iter) == FALSE, "test failed!"); + + ASSERT_MESSAGE(gtk_tree_model_iter_n_children(model, &iter) == 0, "test failed!"); + + gtk_tree_model_iter_next(model, &iter); + + ASSERT_MESSAGE(gtk_tree_model_iter_has_child(model, &iter) != FALSE, "test failed!"); + + ASSERT_MESSAGE(gtk_tree_model_iter_n_children(model, &iter) == 2, "test failed!"); + + { + GtkTreeIter child; + gtk_tree_model_iter_nth_child(model, &child, &iter, 0); + + scene::Node* test; + gtk_tree_model_get_value(model, &child, 0, (GValue*)&test); + ASSERT_MESSAGE(test == node3, "test failed!"); + + { + GtkTreeIter parent; + gtk_tree_model_iter_parent(model, &parent, &child); + + scene::Node* test; + gtk_tree_model_get_value(model, &parent, 0, (GValue*)&test); + ASSERT_MESSAGE(test == node2, "test failed!"); + } + } + + { + GtkTreeIter child; + gtk_tree_model_iter_nth_child(model, &child, &iter, 1); + + scene::Node* test; + gtk_tree_model_get_value(model, &child, 0, (GValue*)&test); + ASSERT_MESSAGE(test == node4, "test failed!"); + } + } + + { + GtkTreeIter iter; + std::size_t count = 0; + for(gboolean good = gtk_tree_model_get_iter_first(model, &iter); good; good = gtk_tree_model_iter_next(model, &iter)) + { + scene::Node* test; + gtk_tree_model_get_value(model, &iter, 0, (GValue*)&test); + + ASSERT_MESSAGE((count == 0 && test == node1) || (count == 1 && test == node2), "test failed!"); + ++count; + } + + ASSERT_MESSAGE(count == 2, "test failed!"); + + } + + { + GtkTreeIter iter; + gtk_tree_model_get_iter_first(model, &iter); + + scene::Node* test; + gtk_tree_model_get_value(model, &iter, 0, (GValue*)&test); + ASSERT_MESSAGE(test == node1, "test failed!"); + } + + { + GtkTreeIter iter; + GtkTreePath* path = gtk_tree_path_new_from_string("0"); + gtk_tree_model_get_iter(model, &iter, path); + gtk_tree_path_free(path); + + graph_type::iterator i = graph_iterator_read_tree_iter(&iter); + ASSERT_MESSAGE((*i).first.get().size() == 2 && (*i).first.get().top() == node1, "test failed!"); + } + + { + GtkTreeIter iter; + GtkTreePath* path = gtk_tree_path_new_from_string("1"); + gtk_tree_model_get_iter(model, &iter, path); + gtk_tree_path_free(path); + + graph_type::iterator i = graph_iterator_read_tree_iter(&iter); + ASSERT_MESSAGE((*i).first.get().size() == 2 && (*i).first.get().top() == node2, "test failed!"); + } + + { + GtkTreeIter iter; + graph_type::iterator i = graph.begin(); + ++i; + graph_iterator_write_tree_iter(i, &iter); + + GtkTreePath* path = gtk_tree_model_get_path(model, &iter); + + gint depth = gtk_tree_path_get_depth(path); + gint* indices = gtk_tree_path_get_indices(path); + + ASSERT_MESSAGE(depth == 1 && indices[0] == 0, "test failed!"); + + gtk_tree_path_free(path); + } + + { + GtkTreeIter iter; + graph_type::iterator i = graph.begin(); + ++i; + ++i; + graph_iterator_write_tree_iter(i, &iter); + + GtkTreePath* path = gtk_tree_model_get_path(model, &iter); + + gint depth = gtk_tree_path_get_depth(path); + gint* indices = gtk_tree_path_get_indices(path); + + ASSERT_MESSAGE(depth == 1 && indices[0] == 1, "test failed!"); + + gtk_tree_path_free(path); + } + } +}; + + +TestGraphTreeModel g_TestGraphTreeModel; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/treemodel.h b/misc/mediasource/netradiant-src/radiant/treemodel.h new file mode 100644 index 00000000..7c33485b --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/treemodel.h @@ -0,0 +1,37 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_TREEMODEL_H) +#define INCLUDED_TREEMODEL_H + +struct GraphTreeModel; + +GraphTreeModel* graph_tree_model_new(); +void graph_tree_model_delete(GraphTreeModel* model); + +namespace scene +{ + class Instance; +} +void graph_tree_model_insert(GraphTreeModel* model, const scene::Instance& instance); +void graph_tree_model_erase(GraphTreeModel* model, const scene::Instance& instance); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/undo.cpp b/misc/mediasource/netradiant-src/radiant/undo.cpp new file mode 100644 index 00000000..aa75d950 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/undo.cpp @@ -0,0 +1,590 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "undo.h" + +#include "debugging/debugging.h" +#include "warnings.h" + +#include "iundo.h" +#include "preferencesystem.h" +#include "string/string.h" +#include "generic/callback.h" +#include "preferences.h" +#include "stringio.h" + +#include +#include +#include + +#include "timer.h" + +class DebugScopeTimer +{ + Timer m_timer; + const char* m_operation; +public: + DebugScopeTimer(const char* operation) + : m_operation(operation) + { + m_timer.start(); + } + ~DebugScopeTimer() + { + unsigned int elapsed = m_timer.elapsed_msec(); + if(elapsed > 0) + { + globalOutputStream() << m_operation << ": " << elapsed << " msec\n"; + } + } +}; + + +class RadiantUndoSystem : public UndoSystem +{ + INTEGER_CONSTANT(MAX_UNDO_LEVELS, 1024); + + class Snapshot + { + class StateApplicator + { + public: + Undoable* m_undoable; + private: + UndoMemento* m_data; + public: + + StateApplicator(Undoable* undoable, UndoMemento* data) + : m_undoable(undoable), m_data(data) + { + } + void restore() + { + m_undoable->importState(m_data); + } + void release() + { + m_data->release(); + } + }; + + typedef std::list states_t; + states_t m_states; + + public: + bool empty() const + { + return m_states.empty(); + } + std::size_t size() const + { + return m_states.size(); + } + void save(Undoable* undoable) + { + m_states.push_front(StateApplicator(undoable, undoable->exportState())); + } + void restore() + { + for(states_t::iterator i = m_states.begin(); i != m_states.end(); ++i) + { + (*i).restore(); + } + } + void release() + { + for(states_t::iterator i = m_states.begin(); i != m_states.end(); ++i) + { + (*i).release(); + } + } + }; + + struct Operation + { + Snapshot m_snapshot; + CopiedString m_command; + + Operation(const char* command) + : m_command(command) + { + } + ~Operation() + { + m_snapshot.release(); + } + }; + + + class UndoStack + { + //! Note: using std::list instead of vector/deque, to avoid copying of undos + typedef std::list Operations; + + Operations m_stack; + Operation* m_pending; + + public: + UndoStack() : m_pending(0) + { + } + ~UndoStack() + { + clear(); + } + bool empty() const + { + return m_stack.empty(); + } + std::size_t size() const + { + return m_stack.size(); + } + Operation* back() + { + return m_stack.back(); + } + const Operation* back() const + { + return m_stack.back(); + } + Operation* front() + { + return m_stack.front(); + } + const Operation* front() const + { + return m_stack.front(); + } + void pop_front() + { + delete m_stack.front(); + m_stack.pop_front(); + } + void pop_back() + { + delete m_stack.back(); + m_stack.pop_back(); + } + void clear() + { + if(!m_stack.empty()) + { + for(Operations::iterator i = m_stack.begin(); i != m_stack.end(); ++i) + { + delete *i; + } + m_stack.clear(); + } + } + void start(const char* command) + { + if(m_pending != 0) + { + delete m_pending; + } + m_pending = new Operation(command); + } + bool finish(const char* command) + { + if(m_pending != 0) + { + delete m_pending; + m_pending = 0; + return false; + } + else + { + ASSERT_MESSAGE(!m_stack.empty(), "undo stack empty"); + m_stack.back()->m_command = command; + return true; + } + } + void save(Undoable* undoable) + { + if(m_pending != 0) + { + m_stack.push_back(m_pending); + m_pending = 0; + } + back()->m_snapshot.save(undoable); + } + }; + + UndoStack m_undo_stack; + UndoStack m_redo_stack; + + class UndoStackFiller : public UndoObserver + { + UndoStack* m_stack; + public: + + UndoStackFiller() + : m_stack(0) + { + } + void save(Undoable* undoable) + { + ASSERT_NOTNULL(undoable); + + if(m_stack != 0) + { + m_stack->save(undoable); + m_stack = 0; + } + } + void setStack(UndoStack* stack) + { + m_stack = stack; + } + }; + + typedef std::map undoables_t; + undoables_t m_undoables; + + void mark_undoables(UndoStack* stack) + { + for(undoables_t::iterator i = m_undoables.begin(); i != m_undoables.end(); ++i) + { + (*i).second.setStack(stack); + } + } + + std::size_t m_undo_levels; + + typedef std::set Trackers; + Trackers m_trackers; +public: + RadiantUndoSystem() + : m_undo_levels(64) + { + } + ~RadiantUndoSystem() + { + clear(); + } + UndoObserver* observer(Undoable* undoable) + { + ASSERT_NOTNULL(undoable); + + return &m_undoables[undoable]; + } + void release(Undoable* undoable) + { + ASSERT_NOTNULL(undoable); + + m_undoables.erase(undoable); + } + void setLevels(std::size_t levels) + { + if(levels > MAX_UNDO_LEVELS()) + { + levels = MAX_UNDO_LEVELS(); + } + + while(m_undo_stack.size() > levels) + { + m_undo_stack.pop_front(); + } + m_undo_levels = levels; + } + std::size_t getLevels() const + { + return m_undo_levels; + } + std::size_t size() const + { + return m_undo_stack.size(); + } + void startUndo() + { + m_undo_stack.start("unnamedCommand"); + mark_undoables(&m_undo_stack); + } + bool finishUndo(const char* command) + { + bool changed = m_undo_stack.finish(command); + mark_undoables(0); + return changed; + } + void startRedo() + { + m_redo_stack.start("unnamedCommand"); + mark_undoables(&m_redo_stack); + } + bool finishRedo(const char* command) + { + bool changed = m_redo_stack.finish(command); + mark_undoables(0); + return changed; + } + void start() + { + m_redo_stack.clear(); + if(m_undo_stack.size() == m_undo_levels) + { + m_undo_stack.pop_front(); + } + startUndo(); + trackersBegin(); + } + void finish(const char* command) + { + if(finishUndo(command)) + { + globalOutputStream() << command << '\n'; + } + } + void undo() + { + if(m_undo_stack.empty()) + { + globalOutputStream() << "Undo: no undo available\n"; + } + else + { + Operation* operation = m_undo_stack.back(); + globalOutputStream() << "Undo: " << operation->m_command.c_str() << "\n"; + + startRedo(); + trackersUndo(); + operation->m_snapshot.restore(); + finishRedo(operation->m_command.c_str()); + m_undo_stack.pop_back(); + } + } + void redo() + { + if(m_redo_stack.empty()) + { + globalOutputStream() << "Redo: no redo available\n"; + } + else + { + Operation* operation = m_redo_stack.back(); + globalOutputStream() << "Redo: " << operation->m_command.c_str() << "\n"; + + startUndo(); + trackersRedo(); + operation->m_snapshot.restore(); + finishUndo(operation->m_command.c_str()); + m_redo_stack.pop_back(); + } + } + void clear() + { + mark_undoables(0); + m_undo_stack.clear(); + m_redo_stack.clear(); + trackersClear(); + } + void trackerAttach(UndoTracker& tracker) + { + ASSERT_MESSAGE(m_trackers.find(&tracker) == m_trackers.end(), "undo tracker already attached"); + m_trackers.insert(&tracker); + } + void trackerDetach(UndoTracker& tracker) + { + ASSERT_MESSAGE(m_trackers.find(&tracker) != m_trackers.end(), "undo tracker cannot be detached"); + m_trackers.erase(&tracker); + } + void trackersClear() const + { + for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) + { + (*i)->clear(); + } + } + void trackersBegin() const + { + for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) + { + (*i)->begin(); + } + } + void trackersUndo() const + { + for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) + { + (*i)->undo(); + } + } + void trackersRedo() const + { + for(Trackers::const_iterator i = m_trackers.begin(); i != m_trackers.end(); ++i) + { + (*i)->redo(); + } + } +}; + + + +void UndoLevels_importString(RadiantUndoSystem& undo, const char* value) +{ + int levels; + Int_importString(levels, value); + undo.setLevels(levels); +} +typedef ReferenceCaller1 UndoLevelsImportStringCaller; +void UndoLevels_exportString(const RadiantUndoSystem& undo, const StringImportCallback& importer) +{ + Int_exportString(static_cast(undo.getLevels()), importer); +} +typedef ConstReferenceCaller1 UndoLevelsExportStringCaller; + +#include "generic/callback.h" + +void UndoLevelsImport(RadiantUndoSystem& self, int value) +{ + self.setLevels(value); +} +typedef ReferenceCaller1 UndoLevelsImportCaller; +void UndoLevelsExport(const RadiantUndoSystem& self, const IntImportCallback& importCallback) +{ + importCallback(static_cast(self.getLevels())); +} +typedef ConstReferenceCaller1 UndoLevelsExportCaller; + + +void Undo_constructPreferences(RadiantUndoSystem& undo, PreferencesPage& page) +{ + page.appendSpinner("Undo Queue Size", 64, 0, 1024, IntImportCallback(UndoLevelsImportCaller(undo)), IntExportCallback(UndoLevelsExportCaller(undo))); +} +void Undo_constructPage(RadiantUndoSystem& undo, PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Undo", "Undo Queue Settings")); + Undo_constructPreferences(undo, page); +} +void Undo_registerPreferencesPage(RadiantUndoSystem& undo) +{ + PreferencesDialog_addSettingsPage(ReferenceCaller1(undo)); +} + +class UndoSystemDependencies : public GlobalPreferenceSystemModuleRef +{ +}; + +class UndoSystemAPI +{ + RadiantUndoSystem m_undosystem; +public: + typedef UndoSystem Type; + STRING_CONSTANT(Name, "*"); + + UndoSystemAPI() + { + GlobalPreferenceSystem().registerPreference("UndoLevels", makeIntStringImportCallback(UndoLevelsImportCaller(m_undosystem)), makeIntStringExportCallback(UndoLevelsExportCaller(m_undosystem))); + + Undo_registerPreferencesPage(m_undosystem); + } + UndoSystem* getTable() + { + return &m_undosystem; + } +}; + +#include "modulesystem/singletonmodule.h" +#include "modulesystem/moduleregistry.h" + +typedef SingletonModule UndoSystemModule; +typedef Static StaticUndoSystemModule; +StaticRegisterModule staticRegisterUndoSystem(StaticUndoSystemModule::instance()); + + + + + + + + + + +class undoable_test : public Undoable +{ + struct state_type : public UndoMemento + { + state_type() : test_data(0) + { + } + state_type(const state_type& other) : UndoMemento(other), test_data(other.test_data) + { + } + void release() + { + delete this; + } + + int test_data; + }; + state_type m_state; + UndoObserver* m_observer; +public: + undoable_test() + : m_observer(GlobalUndoSystem().observer(this)) + { + } + ~undoable_test() + { + GlobalUndoSystem().release(this); + } + UndoMemento* exportState() const + { + return new state_type(m_state); + } + void importState(const UndoMemento* state) + { + ASSERT_NOTNULL(state); + + m_observer->save(this); + m_state = *(static_cast(state)); + } + + void mutate(unsigned int data) + { + m_observer->save(this); + m_state.test_data = data; + } +}; + +#if 0 + +class TestUndo +{ +public: + TestUndo() + { + undoable_test test; + GlobalUndoSystem().begin("bleh"); + test.mutate(3); + GlobalUndoSystem().begin("blah"); + test.mutate(4); + GlobalUndoSystem().undo(); + GlobalUndoSystem().undo(); + GlobalUndoSystem().redo(); + GlobalUndoSystem().redo(); + } +}; + +TestUndo g_TestUndo; + +#endif + diff --git a/misc/mediasource/netradiant-src/radiant/undo.h b/misc/mediasource/netradiant-src/radiant/undo.h new file mode 100644 index 00000000..171af8cf --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/undo.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_UNDO_H) +#define INCLUDED_UNDO_H + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/url.cpp b/misc/mediasource/netradiant-src/radiant/url.cpp new file mode 100644 index 00000000..96f13a2e --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/url.cpp @@ -0,0 +1,66 @@ +/* +Copyright (C) 1999-2006 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 "url.h" + +#include "mainframe.h" +#include "gtkutil/messagebox.h" + +#ifdef WIN32 +#include +#include +bool open_url(const char* url) +{ + return ShellExecute( (HWND)GDK_WINDOW_HWND (GTK_WIDGET(MainFrame_getWindow())->window), "open", url, 0, 0, SW_SHOW ) > (HINSTANCE)32; +} +#endif + +#if defined(__linux__) || defined(__FreeBSD__) +#include +bool open_url(const char* url) +{ + // \todo FIXME: the way we open URLs on *nix should be improved. A script is good (see how I do on RTCW) + char command[2*PATH_MAX]; + snprintf (command, sizeof(command), + "firefox -remote \"openURL(%s,new-window)\" || firefox \"%s\" &", url, url); + return system(command) == 0; +} +#endif + +#ifdef __APPLE__ +#include +bool open_url(const char* url) +{ + char command[2*PATH_MAX]; + snprintf (command, sizeof(command), "open \"%s\" &", url); + return system(command) == 0; +} +#endif + +void OpenURL(const char *url) +{ + // let's put a little comment + globalOutputStream() << "OpenURL: " << url << "\n"; + if(!open_url(url)) + { + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "Failed to launch browser!"); + } +} diff --git a/misc/mediasource/netradiant-src/radiant/url.h b/misc/mediasource/netradiant-src/radiant/url.h new file mode 100644 index 00000000..38d50b51 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/url.h @@ -0,0 +1,27 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_URL_H) +#define INCLUDED_URL_H + +void OpenURL(const char *url); + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/view.cpp b/misc/mediasource/netradiant-src/radiant/view.cpp new file mode 100644 index 00000000..5282eb0f --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/view.cpp @@ -0,0 +1,57 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "view.h" + +#if defined(DEBUG_CULLING) + +#include + +char g_cull_stats[1024]; +int g_count_dots; +int g_count_planes; +int g_count_oriented_planes; +int g_count_bboxs; +int g_count_oriented_bboxs; + +#endif + +void Cull_ResetStats() +{ +#if defined(DEBUG_CULLING) + g_count_dots = 0; + g_count_planes = 0; + g_count_oriented_planes = 0; + g_count_bboxs = 0; + g_count_oriented_bboxs = 0; +#endif +} + + +const char* Cull_GetStats() +{ +#if defined(DEBUG_CULLING) + sprintf(g_cull_stats, "dots: %d | planes %d + %d | bboxs %d + %d", g_count_dots, g_count_planes, g_count_oriented_planes, g_count_bboxs, g_count_oriented_bboxs); + return g_cull_stats; +#else + return ""; +#endif +} diff --git a/misc/mediasource/netradiant-src/radiant/view.h b/misc/mediasource/netradiant-src/radiant/view.h new file mode 100644 index 00000000..b6dc414a --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/view.h @@ -0,0 +1,211 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_VIEW_H) +#define INCLUDED_VIEW_H + +#include "cullable.h" +#include "math/frustum.h" + + +#if defined(_DEBUG) +#define DEBUG_CULLING +#endif + + +#if defined(DEBUG_CULLING) + +extern int g_count_dots; +extern int g_count_planes; +extern int g_count_oriented_planes; +extern int g_count_bboxs; +extern int g_count_oriented_bboxs; + +#endif + +inline void debug_count_dot() +{ +#if defined(DEBUG_CULLING) + ++g_count_dots; +#endif +} + +inline void debug_count_plane() +{ +#if defined(DEBUG_CULLING) + ++g_count_planes; +#endif +} + +inline void debug_count_oriented_plane() +{ +#if defined(DEBUG_CULLING) + ++g_count_oriented_planes; +#endif +} + +inline void debug_count_bbox() +{ +#if defined(DEBUG_CULLING) + ++g_count_bboxs; +#endif +} + +inline void debug_count_oriented_bbox() +{ +#if defined(DEBUG_CULLING) + ++g_count_oriented_bboxs; +#endif +} + + + + +/// \brief View-volume culling and transformations. +class View : public VolumeTest +{ + /// modelview matrix + Matrix4 m_modelview; + /// projection matrix + Matrix4 m_projection; + /// device-to-screen transform + Matrix4 m_viewport; + + Matrix4 m_scissor; + + /// combined modelview and projection matrix + Matrix4 m_viewproj; + /// camera position in world space + Vector4 m_viewer; + /// view frustum in world space + Frustum m_frustum; + + bool m_fill; + + void construct() + { + m_viewproj = matrix4_multiplied_by_matrix4(matrix4_multiplied_by_matrix4(m_scissor, m_projection), m_modelview); + + m_frustum = frustum_from_viewproj(m_viewproj); + m_viewer = viewer_from_viewproj(m_viewproj); + } +public: + View(bool fill = false) : + m_modelview(g_matrix4_identity), + m_projection(g_matrix4_identity), + m_scissor(g_matrix4_identity), + m_fill(fill) + { + } + void Construct(const Matrix4& projection, const Matrix4& modelview, std::size_t width, std::size_t height) + { + // modelview + m_modelview = modelview; + + // projection + m_projection = projection; + + // viewport + m_viewport = g_matrix4_identity; + m_viewport[0] = float(width/2); + m_viewport[5] = float(height/2); + if(fabs(m_projection[11]) > 0.0000001) + m_viewport[10] = m_projection[0] * m_viewport[0]; + else + m_viewport[10] = 1 / m_projection[10]; + + construct(); + } + void EnableScissor(float min_x, float max_x, float min_y, float max_y) + { + m_scissor = g_matrix4_identity; + m_scissor[0] = static_cast((max_x - min_x) * 0.5); + m_scissor[5] = static_cast((max_y - min_y) * 0.5); + m_scissor[12] = static_cast((min_x + max_x) * 0.5); + m_scissor[13] = static_cast((min_y + max_y) * 0.5); + matrix4_full_invert(m_scissor); + + construct(); + } + void DisableScissor() + { + m_scissor = g_matrix4_identity; + + construct(); + } + + bool TestPoint(const Vector3& point) const + { + return viewproj_test_point(m_viewproj, point); + } + bool TestLine(const Segment& segment) const + { + return frustum_test_line(m_frustum, segment); + } + bool TestPlane(const Plane3& plane) const + { + debug_count_plane(); + return viewer_test_plane(m_viewer, plane); + } + bool TestPlane(const Plane3& plane, const Matrix4& localToWorld) const + { + debug_count_oriented_plane(); + return viewer_test_transformed_plane(m_viewer, plane, localToWorld); + } + VolumeIntersectionValue TestAABB(const AABB& aabb) const + { + debug_count_bbox(); + return frustum_test_aabb(m_frustum, aabb); + } + VolumeIntersectionValue TestAABB(const AABB& aabb, const Matrix4& localToWorld) const + { + debug_count_oriented_bbox(); + return frustum_intersects_transformed_aabb(m_frustum, aabb, localToWorld); + } + + const Matrix4& GetViewMatrix() const + { + return m_viewproj; + } + const Matrix4& GetViewport() const + { + return m_viewport; + }; + const Matrix4& GetModelview() const + { + return m_modelview; + } + const Matrix4& GetProjection() const + { + return m_projection; + } + + bool fill() const + { + return m_fill; + } + const Vector3& getViewer() const + { + return vector4_to_vector3(m_viewer); + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/watchbsp.cpp b/misc/mediasource/netradiant-src/radiant/watchbsp.cpp new file mode 100644 index 00000000..5c170b66 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/watchbsp.cpp @@ -0,0 +1,879 @@ +/* +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. +*/ + +//----------------------------------------------------------------------------- +// +// DESCRIPTION: +// monitoring window for running BSP processes (and possibly various other stuff) + +#include "watchbsp.h" + +#include +#include + +#include "cmdlib.h" +#include "convert.h" +#include "string/string.h" +#include "stream/stringstream.h" + +#include "gtkutil/messagebox.h" +#include "xmlstuff.h" +#include "console.h" +#include "preferences.h" +#include "points.h" +#include "feedback.h" +#include "mainframe.h" +#include "sockets.h" + +void message_flush(message_info_t* self) +{ + Sys_Print(self->msg_level, self->m_buffer, self->m_length); + self->m_length = 0; +} + +void message_print(message_info_t* self, const char* characters, std::size_t length) +{ + const char* end = characters + length; + while(characters != end) + { + std::size_t space = message_info_t::bufsize - 1 - self->m_length; + if(space == 0) + { + message_flush(self); + } + else + { + std::size_t size = std::min(space, std::size_t(end - characters)); + memcpy(self->m_buffer + self->m_length, characters, size); + self->m_length += size; + characters += size; + } + } +} + + +#include +#include +#include "xmlstuff.h" + +class CWatchBSP +{ +private: + // a flag we have set to true when using an external BSP plugin + // the resulting code with that is a bit dirty, cleaner solution would be to seperate the succession of commands from the listening loop + // (in two seperate classes probably) + bool m_bBSPPlugin; + + // EIdle: we are not listening + // DoMonitoringLoop will change state to EBeginStep + // EBeginStep: the socket is up for listening, we are expecting incoming connection + // incoming connection will change state to EWatching + // EWatching: we have a connection, monitor it + // connection closed will see if we start a new step (EBeginStep) or launch Quake3 and end (EIdle) + enum EWatchBSPState { EIdle, EBeginStep, EWatching } m_eState; + socket_t *m_pListenSocket; + socket_t *m_pInSocket; + netmessage_t msg; + GPtrArray *m_pCmd; + // used to timeout EBeginStep + GTimer *m_pTimer; + std::size_t m_iCurrentStep; + // name of the map so we can run the engine + char *m_sBSPName; + // buffer we use in push mode to receive data directly from the network + xmlParserInputBufferPtr m_xmlInputBuffer; + xmlParserInputPtr m_xmlInput; + xmlParserCtxtPtr m_xmlParserCtxt; + // call this to switch the set listening mode + bool SetupListening(); + // start a new EBeginStep + void DoEBeginStep(); + // the xml and sax parser state + char m_xmlBuf[MAX_NETMESSAGE]; + bool m_bNeedCtxtInit; + message_info_t m_message_info; + +public: + CWatchBSP() + { + m_pCmd = 0; + m_bBSPPlugin = false; + m_pListenSocket = NULL; + m_pInSocket = NULL; + m_eState = EIdle; + m_pTimer = g_timer_new(); + m_sBSPName = NULL; + m_xmlInputBuffer = NULL; + m_bNeedCtxtInit = true; + } + virtual ~CWatchBSP() + { + EndMonitoringLoop(); + Net_Shutdown(); + + g_timer_destroy(m_pTimer); + } + + bool HasBSPPlugin() const + { return m_bBSPPlugin; } + + // called regularly to keep listening + void RoutineProcessing(); + // start a monitoring loop with the following steps + void DoMonitoringLoop( GPtrArray *pCmd, const char *sBSPName ); + void EndMonitoringLoop() + { + Reset(); + if (m_sBSPName) + { + string_release(m_sBSPName, string_length(m_sBSPName)); + m_sBSPName = 0; + } + if(m_pCmd) + { + g_ptr_array_free(m_pCmd, TRUE); + m_pCmd = 0; + } + } + // close everything - may be called from the outside to abort the process + void Reset(); + // start a listening loop for an external process, possibly a BSP plugin + void ExternalListen(); +}; + +CWatchBSP* g_pWatchBSP; + + // watch the BSP process through network connections + // true: trigger the BSP steps one by one and monitor them through the network + // false: create a BAT / .sh file and execute it. don't bother monitoring it. +bool g_WatchBSP_Enabled = true; + // do we stop the compilation process if we come accross a leak? +bool g_WatchBSP_LeakStop = true; +bool g_WatchBSP_RunQuake = false; + // store prefs setting for automatic sleep mode activation +bool g_WatchBSP_DoSleep = true; + // timeout when beginning a step (in seconds) + // if we don't get a connection quick enough we assume something failed and go back to idling +int g_WatchBSP_Timeout = 10; + + +void Build_constructPreferences(PreferencesPage& page) +{ + GtkWidget* monitorbsp = page.appendCheckBox("", "Enable Build Process Monitoring", g_WatchBSP_Enabled); + GtkWidget* leakstop = page.appendCheckBox("", "Stop Compilation on Leak", g_WatchBSP_LeakStop); + GtkWidget* runengine = page.appendCheckBox("", "Run Engine After Compile", g_WatchBSP_RunQuake); + GtkWidget* sleep = page.appendCheckBox("", "Sleep When Running the Engine", g_WatchBSP_DoSleep); + Widget_connectToggleDependency(leakstop, monitorbsp); + Widget_connectToggleDependency(runengine, monitorbsp); + Widget_connectToggleDependency(sleep, runengine); +} +void Build_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Build", "Build Preferences")); + Build_constructPreferences(page); +} +void Build_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + +#include "preferencesystem.h" +#include "stringio.h" + +void BuildMonitor_Construct() +{ + g_pWatchBSP = new CWatchBSP(); + + g_WatchBSP_Enabled = !string_equal(g_pGameDescription->getKeyValue("no_bsp_monitor"), "1"); + + GlobalPreferenceSystem().registerPreference("WatchBSP", BoolImportStringCaller(g_WatchBSP_Enabled), BoolExportStringCaller(g_WatchBSP_Enabled)); + GlobalPreferenceSystem().registerPreference("RunQuake2Run", BoolImportStringCaller(g_WatchBSP_RunQuake), BoolExportStringCaller(g_WatchBSP_RunQuake)); + GlobalPreferenceSystem().registerPreference("LeakStop", BoolImportStringCaller(g_WatchBSP_LeakStop), BoolExportStringCaller(g_WatchBSP_LeakStop)); + GlobalPreferenceSystem().registerPreference("SleepMode", BoolImportStringCaller(g_WatchBSP_DoSleep), BoolExportStringCaller(g_WatchBSP_DoSleep)); + + Build_registerPreferencesPage(); +} + +void BuildMonitor_Destroy() +{ + delete g_pWatchBSP; +} + +CWatchBSP *GetWatchBSP() +{ + return g_pWatchBSP; +} + +void BuildMonitor_Run(GPtrArray* commands, const char* mapName) +{ + GetWatchBSP()->DoMonitoringLoop(commands, mapName); +} + + +// Static functions for the SAX callbacks ------------------------------------------------------- + +// utility for saxStartElement below +static void abortStream(message_info_t *data) +{ + GetWatchBSP()->EndMonitoringLoop(); + // tell there has been an error +#if 0 + if (GetWatchBSP()->HasBSPPlugin()) + g_BSPFrontendTable.m_pfnEndListen(2); +#endif + // yeah this doesn't look good.. but it's needed so that everything will be ignored until the stream goes out + data->ignore_depth = -1; + data->recurse++; +} + +#include "stream_version.h" + +static void saxStartElement(message_info_t *data, const xmlChar *name, const xmlChar **attrs) +{ +#if 0 + globalOutputStream() << "<" << name; + if(attrs != 0) + { + for(const xmlChar** p = attrs; *p != 0; p += 2) + { + globalOutputStream() << " " << p[0] << "=" << makeQuoted(p[1]); + } + } + globalOutputStream() << ">\n"; +#endif + + if (data->ignore_depth == 0) + { + if(data->pGeometry != 0) + // we have a handler + { + data->pGeometry->saxStartElement (data, name, attrs); + } + else + { + if (strcmp(reinterpret_cast(name), "q3map_feedback") == 0) + { + // check the correct version + // old q3map don't send a version attribute + // the ones we support .. send Q3MAP_STREAM_VERSION + if (!attrs[0] || !attrs[1] || (strcmp(reinterpret_cast(attrs[0]), "version") != 0)) + { + message_flush(data); + globalErrorStream() << "No stream version given in the feedback stream, this is an old q3map version.\n" + "Please turn off monitored compiling if you still wish to use this q3map executable\n"; + abortStream(data); + return; + } + else if (strcmp(reinterpret_cast(attrs[1]), Q3MAP_STREAM_VERSION) != 0) + { + message_flush(data); + globalErrorStream() << + "This version of Radiant reads version " Q3MAP_STREAM_VERSION " debug streams, I got an incoming connection with version " << reinterpret_cast(attrs[1]) << "\n" + "Please make sure your versions of Radiant and q3map are matching.\n"; + abortStream(data); + return; + } + } + // we don't treat locally + else if (strcmp(reinterpret_cast(name), "message") == 0) + { + int msg_level = atoi(reinterpret_cast(attrs[1])); + if(msg_level != data->msg_level) + { + message_flush(data); + data->msg_level = msg_level; + } + } + else if (strcmp(reinterpret_cast(name), "polyline") == 0) + // polyline has a particular status .. right now we only use it for leakfile .. + { + data->geometry_depth = data->recurse; + data->pGeometry = &g_pointfile; + data->pGeometry->saxStartElement (data, name, attrs); + } + else if (strcmp(reinterpret_cast(name), "select") == 0) + { + CSelectMsg *pSelect = new CSelectMsg(); + data->geometry_depth = data->recurse; + data->pGeometry = pSelect; + data->pGeometry->saxStartElement (data, name, attrs); + } + else if (strcmp(reinterpret_cast(name), "pointmsg") == 0) + { + CPointMsg *pPoint = new CPointMsg(); + data->geometry_depth = data->recurse; + data->pGeometry = pPoint; + data->pGeometry->saxStartElement (data, name, attrs); + } + else if (strcmp(reinterpret_cast(name), "windingmsg") == 0) + { + CWindingMsg *pWinding = new CWindingMsg(); + data->geometry_depth = data->recurse; + data->pGeometry = pWinding; + data->pGeometry->saxStartElement (data, name, attrs); + } + else + { + globalErrorStream() << "Warning: ignoring unrecognized node in XML stream (" << reinterpret_cast(name) << ")\n"; + // we don't recognize this node, jump over it + // (NOTE: the ignore mechanism is a bit screwed, only works when starting an ignore at the highest level) + data->ignore_depth = data->recurse; + } + } + } + data->recurse++; +} + +static void saxEndElement(message_info_t *data, const xmlChar *name) +{ +#if 0 + globalOutputStream() << "<" << name << "/>\n"; +#endif + + data->recurse--; + // we are out of an ignored chunk + if(data->recurse == data->ignore_depth) + { + data->ignore_depth = 0; + return; + } + if(data->pGeometry != 0) + { + data->pGeometry->saxEndElement (data, name); + // we add the object to the debug window + if(data->geometry_depth == data->recurse) + { + g_DbgDlg.Push(data->pGeometry); + data->pGeometry = 0; + } + } + if (data->recurse == data->stop_depth) + { + message_flush(data); +#ifdef _DEBUG + globalOutputStream() << "Received error msg .. shutting down..\n"; +#endif + GetWatchBSP()->EndMonitoringLoop(); + // tell there has been an error +#if 0 + if (GetWatchBSP()->HasBSPPlugin()) + g_BSPFrontendTable.m_pfnEndListen(2); +#endif + return; + } +} + +class MessageOutputStream : public TextOutputStream +{ + message_info_t* m_data; +public: + MessageOutputStream(message_info_t* data) : m_data(data) + { + } + std::size_t write(const char* buffer, std::size_t length) + { + if(m_data->pGeometry != 0) + { + m_data->pGeometry->saxCharacters(m_data, reinterpret_cast(buffer), int(length)); + } + else + { + if (m_data->ignore_depth == 0) + { + // output the message using the level + message_print(m_data, buffer, length); + // if this message has error level flag, we mark the depth to stop the compilation when we get out + // we don't set the msg level if we don't stop on leak + if (m_data->msg_level == 3) + { + m_data->stop_depth = m_data->recurse-1; + } + } + } + + return length; + } +}; + +template +inline MessageOutputStream& operator<<(MessageOutputStream& ostream, const T& t) +{ + return ostream_write(ostream, t); +} + +static void saxCharacters(message_info_t *data, const xmlChar *ch, int len) +{ + MessageOutputStream ostream(data); + ostream << StringRange(reinterpret_cast(ch), reinterpret_cast(ch + len)); +} + +static void saxComment(void *ctx, const xmlChar *msg) +{ + globalOutputStream() << "XML comment: " << reinterpret_cast(msg) << "\n"; +} + +static void saxWarning(void *ctx, const char *msg, ...) +{ + char saxMsgBuffer[4096]; + va_list args; + + va_start(args, msg); + vsprintf (saxMsgBuffer, msg, args); + va_end(args); + globalOutputStream() << "XML warning: " << saxMsgBuffer << "\n"; +} + +static void saxError(void *ctx, const char *msg, ...) +{ + char saxMsgBuffer[4096]; + va_list args; + + va_start(args, msg); + vsprintf (saxMsgBuffer, msg, args); + va_end(args); + globalErrorStream() << "XML error: " << saxMsgBuffer << "\n"; +} + +static void saxFatal(void *ctx, const char *msg, ...) +{ + char buffer[4096]; + + va_list args; + + va_start(args, msg); + vsprintf (buffer, msg, args); + va_end(args); + globalErrorStream() << "XML fatal error: " << buffer << "\n"; +} + +static xmlSAXHandler saxParser = { + 0, /* internalSubset */ + 0, /* isStandalone */ + 0, /* hasInternalSubset */ + 0, /* hasExternalSubset */ + 0, /* resolveEntity */ + 0, /* getEntity */ + 0, /* entityDecl */ + 0, /* notationDecl */ + 0, /* attributeDecl */ + 0, /* elementDecl */ + 0, /* unparsedEntityDecl */ + 0, /* setDocumentLocator */ + 0, /* startDocument */ + 0, /* endDocument */ + (startElementSAXFunc)saxStartElement, /* startElement */ + (endElementSAXFunc)saxEndElement, /* endElement */ + 0, /* reference */ + (charactersSAXFunc)saxCharacters, /* characters */ + 0, /* ignorableWhitespace */ + 0, /* processingInstruction */ + (commentSAXFunc)saxComment, /* comment */ + (warningSAXFunc)saxWarning, /* warning */ + (errorSAXFunc)saxError, /* error */ + (fatalErrorSAXFunc)saxFatal, /* fatalError */ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 +}; + +// ------------------------------------------------------------------------------------------------ + + +guint s_routine_id; +static gint watchbsp_routine(gpointer data) +{ + reinterpret_cast(data)->RoutineProcessing(); + return TRUE; +} + +void CWatchBSP::Reset() +{ + if (m_pInSocket) + { + Net_Disconnect(m_pInSocket); + m_pInSocket = NULL; + } + if (m_pListenSocket) + { + Net_Disconnect(m_pListenSocket); + m_pListenSocket = NULL; + } + if (m_xmlInputBuffer) + { + xmlFreeParserInputBuffer (m_xmlInputBuffer); + m_xmlInputBuffer = NULL; + } + m_eState = EIdle; + if (s_routine_id) + gtk_timeout_remove(s_routine_id); +} + +bool CWatchBSP::SetupListening() +{ +#ifdef _DEBUG + if (m_pListenSocket) + { + globalOutputStream() << "ERROR: m_pListenSocket != NULL in CWatchBSP::SetupListening\n"; + return false; + } +#endif + globalOutputStream() << "Setting up\n"; + Net_Setup(); + m_pListenSocket = Net_ListenSocket(39000); + if (m_pListenSocket == NULL) + return false; + globalOutputStream() << "Listening...\n"; + return true; +} + +void CWatchBSP::DoEBeginStep() +{ + Reset(); + if (SetupListening() == false) + { + const char* msg = "Failed to get a listening socket on port 39000.\nTry running with Build monitoring disabled if you can't fix this.\n"; + globalOutputStream() << msg; + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), msg, "Build monitoring", eMB_OK, eMB_ICONERROR); + return; + } + // set the timer for timeouts and step cancellation + g_timer_reset( m_pTimer ); + g_timer_start( m_pTimer ); + + if (!m_bBSPPlugin) + { + globalOutputStream() << "=== running build command ===\n" + << static_cast(g_ptr_array_index( m_pCmd, m_iCurrentStep )) << "\n"; + + if (!Q_Exec(NULL, (char *)g_ptr_array_index( m_pCmd, m_iCurrentStep ), NULL, true, false )) + { + StringOutputStream msg(256); + msg << "Failed to execute the following command: "; + msg << reinterpret_cast(g_ptr_array_index(m_pCmd, m_iCurrentStep)); + msg << "\nCheck that the file exists and that you don't run out of system resources.\n"; + globalOutputStream() << msg.c_str(); + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), msg.c_str(), "Build monitoring", eMB_OK, eMB_ICONERROR ); + return; + } + // re-initialise the debug window + if (m_iCurrentStep == 0) + g_DbgDlg.Init(); + } + m_eState = EBeginStep; + s_routine_id = gtk_timeout_add(25, watchbsp_routine, this); +} + + +#if defined(WIN32) +#define ENGINE_ATTRIBUTE "engine_win32" +#define MP_ENGINE_ATTRIBUTE "mp_engine_win32" +#elif defined(__linux__) || defined (__FreeBSD__) +#define ENGINE_ATTRIBUTE "engine_linux" +#define MP_ENGINE_ATTRIBUTE "mp_engine_linux" +#elif defined(__APPLE__) +#define ENGINE_ATTRIBUTE "engine_macos" +#define MP_ENGINE_ATTRIBUTE "mp_engine_macos" +#else +#error "unsupported platform" +#endif + +class RunEngineConfiguration +{ +public: + const char* executable; + const char* mp_executable; + bool do_sp_mp; + + RunEngineConfiguration() : + executable(g_pGameDescription->getRequiredKeyValue(ENGINE_ATTRIBUTE)), + mp_executable(g_pGameDescription->getKeyValue(MP_ENGINE_ATTRIBUTE)) + { + do_sp_mp = !string_empty(mp_executable); + } +}; + +inline void GlobalGameDescription_string_write_mapparameter(StringOutputStream& string, const char* mapname) +{ + if(g_pGameDescription->mGameType == "q2" + || g_pGameDescription->mGameType == "heretic2") + { + string << ". +exec radiant.cfg +map " << mapname; + } + else + { + string << "+set sv_pure 0 "; + // TTimo: a check for vm_* but that's all fine + //cmdline = "+set sv_pure 0 +set vm_ui 0 +set vm_cgame 0 +set vm_game 0 "; + const char* fs_game = gamename_get(); + if (!string_equal(fs_game, basegame_get())) + { + string << "+set fs_game " << fs_game << " "; + } + if(g_pGameDescription->mGameType == "wolf" + || g_pGameDescription->mGameType == "et") + { + if (string_equal(gamemode_get(), "mp")) + { + // MP + string << "+devmap " << mapname; + } + else + { + // SP + string << "+set nextmap \"spdevmap " << mapname << "\""; + } + } + else + { + string << "+devmap " << mapname; + } + } +} + + +void CWatchBSP::RoutineProcessing() +{ + switch (m_eState) + { + case EBeginStep: + // timeout: if we don't get an incoming connection fast enough, go back to idle + if ( g_timer_elapsed( m_pTimer, NULL ) > g_WatchBSP_Timeout ) + { + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "The connection timed out, assuming the build process failed\nMake sure you are using a networked version of Q3Map?\nOtherwise you need to disable BSP Monitoring in prefs.", "BSP process monitoring", eMB_OK ); + EndMonitoringLoop(); +#if 0 + if (m_bBSPPlugin) + { + // status == 1 : didn't get the connection + g_BSPFrontendTable.m_pfnEndListen(1); + } +#endif + return; + } +#ifdef _DEBUG + // some debug checks + if (!m_pListenSocket) + { + globalErrorStream() << "ERROR: m_pListenSocket == NULL in CWatchBSP::RoutineProcessing EBeginStep state\n"; + return; + } +#endif + // we are not connected yet, accept any incoming connection + m_pInSocket = Net_Accept(m_pListenSocket); + if (m_pInSocket) + { + globalOutputStream() << "Connected.\n"; + // prepare the message info struct for diving in + memset (&m_message_info, 0, sizeof(message_info_t)); + // a dumb flag to make sure we init the push parser context when first getting a msg + m_bNeedCtxtInit = true; + m_eState = EWatching; + } + break; + case EWatching: + { +#ifdef _DEBUG + // some debug checks + if (!m_pInSocket) + { + globalErrorStream() << "ERROR: m_pInSocket == NULL in CWatchBSP::RoutineProcessing EWatching state\n"; + return; + } +#endif + + int ret = Net_Wait(m_pInSocket, 0, 0); + if (ret == -1) + { + globalOutputStream() << "WARNING: SOCKET_ERROR in CWatchBSP::RoutineProcessing\n"; + globalOutputStream() << "Terminating the connection.\n"; + EndMonitoringLoop(); + return; + } + + if (ret == 1) + { + // the socket has been identified, there's something (message or disconnection) + // see if there's anything in input + ret = Net_Receive( m_pInSocket, &msg ); + if (ret > 0) + { + // unsigned int size = msg.size; //++timo just a check + strcpy (m_xmlBuf, NMSG_ReadString (&msg)); + if (m_bNeedCtxtInit) + { + m_xmlParserCtxt = NULL; + m_xmlParserCtxt = xmlCreatePushParserCtxt (&saxParser, &m_message_info, m_xmlBuf, static_cast(strlen(m_xmlBuf)), NULL); + + if (m_xmlParserCtxt == NULL) + { + globalErrorStream() << "Failed to create the XML parser (incoming stream began with: " << m_xmlBuf << ")\n"; + EndMonitoringLoop(); + } + m_bNeedCtxtInit = false; + } + else + { + xmlParseChunk(m_xmlParserCtxt, m_xmlBuf, static_cast(strlen(m_xmlBuf)), 0); + } + } + else + { + message_flush(&m_message_info); + // error or connection closed/reset + // NOTE: if we get an error down the XML stream we don't reach here + Net_Disconnect( m_pInSocket ); + m_pInSocket = NULL; + globalOutputStream() << "Connection closed.\n"; +#if 0 + if (m_bBSPPlugin) + { + EndMonitoringLoop(); + // let the BSP plugin know that the job is done + g_BSPFrontendTable.m_pfnEndListen(0); + return; + } +#endif + // move to next step or finish + m_iCurrentStep++; + if (m_iCurrentStep < m_pCmd->len ) + { + DoEBeginStep(); + } + else + { + // launch the engine .. OMG + if (g_WatchBSP_RunQuake) + { +#if 0 + // do we enter sleep mode before? + if (g_WatchBSP_DoSleep) + { + globalOutputStream() << "Going into sleep mode..\n"; + g_pParentWnd->OnSleep(); + } +#endif + globalOutputStream() << "Running engine...\n"; + StringOutputStream cmd(256); + // build the command line + cmd << EnginePath_get(); + // this is game dependant + + RunEngineConfiguration engineConfig; + + if(engineConfig.do_sp_mp) + { + if (string_equal(gamemode_get(), "mp")) + { + cmd << engineConfig.mp_executable; + } + else + { + cmd << engineConfig.executable; + } + } + else + { + cmd << engineConfig.executable; + } + + StringOutputStream cmdline; + + GlobalGameDescription_string_write_mapparameter(cmdline, m_sBSPName); + + globalOutputStream() << cmd.c_str() << " " << cmdline.c_str() << "\n"; + + // execute now + if (!Q_Exec(cmd.c_str(), (char *)cmdline.c_str(), EnginePath_get(), false, false)) + { + StringOutputStream msg; + msg << "Failed to execute the following command: " << cmd.c_str() << cmdline.c_str(); + globalOutputStream() << msg.c_str(); + gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), msg.c_str(), "Build monitoring", eMB_OK, eMB_ICONERROR ); + } + } + EndMonitoringLoop(); + } + } + } + } + break; + default: + break; + } +} + +GPtrArray* str_ptr_array_clone(GPtrArray* array) +{ + GPtrArray* cloned = g_ptr_array_sized_new(array->len); + for(guint i = 0; i < array->len; ++i) + { + g_ptr_array_add(cloned, g_strdup((char*)g_ptr_array_index(array, i))); + } + return cloned; +} + +void CWatchBSP::DoMonitoringLoop( GPtrArray *pCmd, const char *sBSPName ) +{ + m_sBSPName = string_clone(sBSPName); + if (m_eState != EIdle) + { + globalOutputStream() << "WatchBSP got a monitoring request while not idling...\n"; + // prompt the user, should we cancel the current process and go ahead? + if (gtk_MessageBox(GTK_WIDGET(MainFrame_getWindow()), "I am already monitoring a Build process.\nDo you want me to override and start a new compilation?", + "Build process monitoring", eMB_YESNO ) == eIDYES) + { + // disconnect and set EIdle state + Reset(); + } + } + m_pCmd = str_ptr_array_clone(pCmd); + m_iCurrentStep = 0; + DoEBeginStep(); +} + +void CWatchBSP::ExternalListen() +{ + m_bBSPPlugin = true; + DoEBeginStep(); +} + +// the part of the watchbsp interface we export to plugins +// NOTE: in the long run, the whole watchbsp.cpp interface needs to go out and be handled at the BSP plugin level +// for now we provide something really basic and limited, the essential is to have something that works fine and fast (for 1.1 final) +void QERApp_Listen() +{ + // open the listening socket + GetWatchBSP()->ExternalListen(); +} diff --git a/misc/mediasource/netradiant-src/radiant/watchbsp.h b/misc/mediasource/netradiant-src/radiant/watchbsp.h new file mode 100644 index 00000000..ac6a2b22 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/watchbsp.h @@ -0,0 +1,43 @@ +/* +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. +*/ + +#if !defined(INCLUDED_WATCHBSP_H) +#define INCLUDED_WATCHBSP_H + +void BuildMonitor_Construct(); +void BuildMonitor_Destroy(); + +typedef struct _GPtrArray GPtrArray; +void BuildMonitor_Run(GPtrArray* commands, const char* mapName); + +extern bool g_WatchBSP_Enabled; +extern bool g_WatchBSP_LeakStop; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/winding.cpp b/misc/mediasource/netradiant-src/radiant/winding.cpp new file mode 100644 index 00000000..bba89501 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/winding.cpp @@ -0,0 +1,346 @@ +/* +Copyright (C) 1999-2006 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 "winding.h" + +#include + +#include "math/line.h" + + +inline double plane3_distance_to_point(const Plane3& plane, const DoubleVector3& point) +{ + return vector3_dot(point, plane.normal()) - plane.dist(); +} + +inline double plane3_distance_to_point(const Plane3& plane, const Vector3& point) +{ + return vector3_dot(point, plane.normal()) - plane.dist(); +} + +/// \brief Returns the point at which \p line intersects \p plane, or an undefined value if there is no intersection. +inline DoubleVector3 line_intersect_plane(const DoubleLine& line, const Plane3& plane) +{ + return line.origin + vector3_scaled( + line.direction, + -plane3_distance_to_point(plane, line.origin) + / vector3_dot(line.direction, plane.normal()) + ); +} + +inline bool float_is_largest_absolute(double axis, double other) +{ + return fabs(axis) > fabs(other); +} + +/// \brief Returns the index of the component of \p v that has the largest absolute value. +inline int vector3_largest_absolute_component_index(const DoubleVector3& v) +{ + return (float_is_largest_absolute(v[1], v[0])) + ? (float_is_largest_absolute(v[1], v[2])) + ? 1 + : 2 + : (float_is_largest_absolute(v[0], v[2])) + ? 0 + : 2; +} + +/// \brief Returns the infinite line that is the intersection of \p plane and \p other. +inline DoubleLine plane3_intersect_plane3(const Plane3& plane, const Plane3& other) +{ + DoubleLine line; + line.direction = vector3_cross(plane.normal(), other.normal()); + switch(vector3_largest_absolute_component_index(line.direction)) + { + case 0: + line.origin.x() = 0; + line.origin.y() = (-other.dist() * plane.normal().z() - -plane.dist() * other.normal().z()) / line.direction.x(); + line.origin.z() = (-plane.dist() * other.normal().y() - -other.dist() * plane.normal().y()) / line.direction.x(); + break; + case 1: + line.origin.x() = (-plane.dist() * other.normal().z() - -other.dist() * plane.normal().z()) / line.direction.y(); + line.origin.y() = 0; + line.origin.z() = (-other.dist() * plane.normal().x() - -plane.dist() * other.normal().x()) / line.direction.y(); + break; + case 2: + line.origin.x() = (-other.dist() * plane.normal().y() - -plane.dist() * other.normal().y()) / line.direction.z(); + line.origin.y() = (-plane.dist() * other.normal().x() - -other.dist() * plane.normal().x()) / line.direction.z(); + line.origin.z() = 0; + break; + default: + break; + } + + return line; +} + + +/// \brief Keep the value of \p infinity as small as possible to improve precision in Winding_Clip. +void Winding_createInfinite(FixedWinding& winding, const Plane3& plane, double infinity) +{ + double max = -infinity; + int x = -1; + for (int i=0 ; i<3; i++) + { + double d = fabs(plane.normal()[i]); + if (d > max) + { + x = i; + max = d; + } + } + if(x == -1) + { + globalErrorStream() << "invalid plane\n"; + return; + } + + DoubleVector3 vup = g_vector3_identity; + switch (x) + { + case 0: + case 1: + vup[2] = 1; + break; + case 2: + vup[0] = 1; + break; + } + + + vector3_add(vup, vector3_scaled(plane.normal(), -vector3_dot(vup, plane.normal()))); + vector3_normalise(vup); + + DoubleVector3 org = vector3_scaled(plane.normal(), plane.dist()); + + DoubleVector3 vright = vector3_cross(vup, plane.normal()); + + vector3_scale(vup, infinity); + vector3_scale(vright, infinity); + + // project a really big axis aligned box onto the plane + + DoubleLine r1, r2, r3, r4; + r1.origin = vector3_added(vector3_subtracted(org, vright), vup); + r1.direction = vector3_normalised(vright); + winding.push_back(FixedWindingVertex(r1.origin, r1, c_brush_maxFaces)); + r2.origin = vector3_added(vector3_added(org, vright), vup); + r2.direction = vector3_normalised(vector3_negated(vup)); + winding.push_back(FixedWindingVertex(r2.origin, r2, c_brush_maxFaces)); + r3.origin = vector3_subtracted(vector3_added(org, vright), vup); + r3.direction = vector3_normalised(vector3_negated(vright)); + winding.push_back(FixedWindingVertex(r3.origin, r3, c_brush_maxFaces)); + r4.origin = vector3_subtracted(vector3_subtracted(org, vright), vup); + r4.direction = vector3_normalised(vup); + winding.push_back(FixedWindingVertex(r4.origin, r4, c_brush_maxFaces)); +} + + +inline PlaneClassification Winding_ClassifyDistance(const double distance, const double epsilon) +{ + if(distance > epsilon) + { + return ePlaneFront; + } + if(distance < -epsilon) + { + return ePlaneBack; + } + return ePlaneOn; +} + +/// \brief Returns true if +/// !flipped && winding is completely BACK or ON +/// or flipped && winding is completely FRONT or ON +bool Winding_TestPlane(const Winding& winding, const Plane3& plane, bool flipped) +{ + const int test = (flipped) ? ePlaneBack : ePlaneFront; + for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i) + { + if(test == Winding_ClassifyDistance(plane3_distance_to_point(plane, (*i).vertex), ON_EPSILON)) + { + return false; + } + } + return true; +} + +/// \brief Returns true if any point in \p w1 is in front of plane2, or any point in \p w2 is in front of plane1 +bool Winding_PlanesConcave(const Winding& w1, const Winding& w2, const Plane3& plane1, const Plane3& plane2) +{ + return !Winding_TestPlane(w1, plane2, false) || !Winding_TestPlane(w2, plane1, false); +} + +brushsplit_t Winding_ClassifyPlane(const Winding& winding, const Plane3& plane) +{ + brushsplit_t split; + for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i) + { + ++split.counts[Winding_ClassifyDistance(plane3_distance_to_point(plane, (*i).vertex), ON_EPSILON)]; + } + return split; +} + + +#define DEBUG_EPSILON ON_EPSILON +const double DEBUG_EPSILON_SQUARED = DEBUG_EPSILON * DEBUG_EPSILON; + +#define WINDING_DEBUG 0 + +/// \brief Clip \p winding which lies on \p plane by \p clipPlane, resulting in \p clipped. +/// If \p winding is completely in front of the plane, \p clipped will be identical to \p winding. +/// If \p winding is completely in back of the plane, \p clipped will be empty. +/// If \p winding intersects the plane, the edge of \p clipped which lies on \p clipPlane will store the value of \p adjacent. +void Winding_Clip(const FixedWinding& winding, const Plane3& plane, const Plane3& clipPlane, std::size_t adjacent, FixedWinding& clipped) +{ + PlaneClassification classification = Winding_ClassifyDistance(plane3_distance_to_point(clipPlane, winding.back().vertex), ON_EPSILON); + PlaneClassification nextClassification; + // for each edge + for(std::size_t next = 0, i = winding.size()-1; next != winding.size(); i = next, ++next, classification = nextClassification) + { + nextClassification = Winding_ClassifyDistance(plane3_distance_to_point(clipPlane, winding[next].vertex), ON_EPSILON); + const FixedWindingVertex& vertex = winding[i]; + + // if first vertex of edge is ON + if(classification == ePlaneOn) + { + // append first vertex to output winding + if(nextClassification == ePlaneBack) + { + // this edge lies on the clip plane + clipped.push_back(FixedWindingVertex(vertex.vertex, plane3_intersect_plane3(plane, clipPlane), adjacent)); + } + else + { + clipped.push_back(vertex); + } + continue; + } + + // if first vertex of edge is FRONT + if(classification == ePlaneFront) + { + // add first vertex to output winding + clipped.push_back(vertex); + } + // if second vertex of edge is ON + if(nextClassification == ePlaneOn) + { + continue; + } + // else if second vertex of edge is same as first + else if(nextClassification == classification) + { + continue; + } + // else if first vertex of edge is FRONT and there are only two edges + else if(classification == ePlaneFront && winding.size() == 2) + { + continue; + } + // else first vertex is FRONT and second is BACK or vice versa + else + { + // append intersection point of line and plane to output winding + DoubleVector3 mid(line_intersect_plane(vertex.edge, clipPlane)); + + if(classification == ePlaneFront) + { + // this edge lies on the clip plane + clipped.push_back(FixedWindingVertex(mid, plane3_intersect_plane3(plane, clipPlane), adjacent)); + } + else + { + clipped.push_back(FixedWindingVertex(mid, vertex.edge, vertex.adjacent)); + } + } + } +} + +std::size_t Winding_FindAdjacent(const Winding& winding, std::size_t face) +{ + for(std::size_t i=0; i dist_best) + { + dist_best = dist_squared; + index_best = i; + } + } + return index_best; +} + +std::size_t Winding_Opposite(const Winding& winding, const std::size_t index) +{ + return Winding_Opposite(winding, index, Winding_next(winding, index)); +} + +/// \brief Calculate the \p centroid of the polygon defined by \p winding which lies on plane \p plane. +void Winding_Centroid(const Winding& winding, const Plane3& plane, Vector3& centroid) +{ + double area2 = 0, x_sum = 0, y_sum = 0; + const ProjectionAxis axis = projectionaxis_for_normal(plane.normal()); + const indexremap_t remap = indexremap_for_projectionaxis(axis); + for(std::size_t i = winding.numpoints-1, j = 0; j < winding.numpoints; i = j, ++j) + { + const double ai = winding[i].vertex[remap.x] * winding[j].vertex[remap.y] - winding[j].vertex[remap.x] * winding[i].vertex[remap.y]; + area2 += ai; + x_sum += (winding[j].vertex[remap.x] + winding[i].vertex[remap.x]) * ai; + y_sum += (winding[j].vertex[remap.y] + winding[i].vertex[remap.y]) * ai; + } + + centroid[remap.x] = static_cast(x_sum / (3 * area2)); + centroid[remap.y] = static_cast(y_sum / (3 * area2)); + { + Ray ray(Vector3(0, 0, 0), Vector3(0, 0, 0)); + ray.origin[remap.x] = centroid[remap.x]; + ray.origin[remap.y] = centroid[remap.y]; + ray.direction[remap.z] = 1; + centroid[remap.z] = static_cast(ray_distance_to_plane(ray, plane)); + } +} diff --git a/misc/mediasource/netradiant-src/radiant/winding.h b/misc/mediasource/netradiant-src/radiant/winding.h new file mode 100644 index 00000000..233a9c82 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/winding.h @@ -0,0 +1,322 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_WINDING_H) +#define INCLUDED_WINDING_H + +#include "debugging/debugging.h" + +#include + +#include "math/vector.h" +#include "container/array.h" + +enum ProjectionAxis +{ + eProjectionAxisX = 0, + eProjectionAxisY = 1, + eProjectionAxisZ = 2, +}; + +const float ProjectionAxisEpsilon = static_cast(0.0001); + +inline bool projectionaxis_better(float axis, float other) +{ + return fabs(axis) > fabs(other) + ProjectionAxisEpsilon; +} + +/// \brief Texture axis precedence: Z > X > Y +inline ProjectionAxis projectionaxis_for_normal(const Vector3& normal) +{ + return (projectionaxis_better(normal[eProjectionAxisY], normal[eProjectionAxisX])) + ? (projectionaxis_better(normal[eProjectionAxisY], normal[eProjectionAxisZ])) + ? eProjectionAxisY + : eProjectionAxisZ + : (projectionaxis_better(normal[eProjectionAxisX], normal[eProjectionAxisZ])) + ? eProjectionAxisX + : eProjectionAxisZ; +} + + +struct indexremap_t +{ + indexremap_t(std::size_t _x, std::size_t _y, std::size_t _z) + : x(_x), y(_y), z(_z) + { + } + std::size_t x, y, z; +}; + +inline indexremap_t indexremap_for_projectionaxis(const ProjectionAxis axis) +{ + switch(axis) + { + case eProjectionAxisX: return indexremap_t(1, 2, 0); + case eProjectionAxisY: return indexremap_t(2, 0, 1); + default: return indexremap_t(0, 1, 2); + } +} + +enum PlaneClassification +{ + ePlaneFront = 0, + ePlaneBack = 1, + ePlaneOn = 2, +}; + +#define MAX_POINTS_ON_WINDING 64 +const std::size_t c_brush_maxFaces = 1024; + + +class WindingVertex +{ +public: + Vector3 vertex; + Vector2 texcoord; + Vector3 tangent; + Vector3 bitangent; + std::size_t adjacent; +}; + + + +struct Winding +{ + typedef Array container_type; + + std::size_t numpoints; + container_type points; + + typedef container_type::iterator iterator; + typedef container_type::const_iterator const_iterator; + + Winding() : numpoints(0) + { + } + Winding(std::size_t size) : numpoints(0), points(size) + { + } + void resize(std::size_t size) + { + points.resize(size); + numpoints = 0; + } + + iterator begin() + { + return points.begin(); + } + const_iterator begin() const + { + return points.begin(); + } + iterator end() + { + return points.begin() + numpoints; + } + const_iterator end() const + { + return points.begin() + numpoints; + } + + WindingVertex& operator[](std::size_t index) + { + ASSERT_MESSAGE(index < points.size(), "winding: index out of bounds"); + return points[index]; + } + const WindingVertex& operator[](std::size_t index) const + { + ASSERT_MESSAGE(index < points.size(), "winding: index out of bounds"); + return points[index]; + } + + void push_back(const WindingVertex& point) + { + points[numpoints] = point; + ++numpoints; + } + void erase(iterator point) + { + for(iterator i = point + 1; i != end(); point = i, ++i) + { + *point = *i; + } + --numpoints; + } +}; + +typedef BasicVector3 DoubleVector3; + +class DoubleLine +{ +public: + DoubleVector3 origin; + DoubleVector3 direction; +}; + +class FixedWindingVertex +{ +public: + DoubleVector3 vertex; + DoubleLine edge; + std::size_t adjacent; + + FixedWindingVertex(const DoubleVector3& vertex_, const DoubleLine& edge_, std::size_t adjacent_) + : vertex(vertex_), edge(edge_), adjacent(adjacent_) + { + } +}; + +struct FixedWinding +{ + typedef std::vector Points; + Points points; + + FixedWinding() + { + points.reserve(MAX_POINTS_ON_WINDING); + } + + FixedWindingVertex& front() + { + return points.front(); + } + const FixedWindingVertex& front() const + { + return points.front(); + } + FixedWindingVertex& back() + { + return points.back(); + } + const FixedWindingVertex& back() const + { + return points.back(); + } + + void clear() + { + points.clear(); + } + + void push_back(const FixedWindingVertex& point) + { + points.push_back(point); + } + std::size_t size() const + { + return points.size(); + } + + FixedWindingVertex& operator[](std::size_t index) + { + //ASSERT_MESSAGE(index < MAX_POINTS_ON_WINDING, "winding: index out of bounds"); + return points[index]; + } + const FixedWindingVertex& operator[](std::size_t index) const + { + //ASSERT_MESSAGE(index < MAX_POINTS_ON_WINDING, "winding: index out of bounds"); + return points[index]; + } + +}; + + +inline void Winding_forFixedWinding(Winding& winding, const FixedWinding& fixed) +{ + winding.resize(fixed.size()); + winding.numpoints = fixed.size(); + for(std::size_t i = 0; i < fixed.size(); ++i) + { + winding[i].vertex[0] = static_cast(fixed[i].vertex[0]); + winding[i].vertex[1] = static_cast(fixed[i].vertex[1]); + winding[i].vertex[2] = static_cast(fixed[i].vertex[2]); + winding[i].adjacent = fixed[i].adjacent; + } +} + +inline std::size_t Winding_wrap(const Winding& winding, std::size_t i) +{ + ASSERT_MESSAGE(winding.numpoints != 0, "Winding_wrap: empty winding"); + return i % winding.numpoints; +} + +inline std::size_t Winding_next(const Winding& winding, std::size_t i) +{ + return Winding_wrap(winding, ++i); +} + + +class Plane3; + +void Winding_createInfinite(FixedWinding& w, const Plane3& plane, double infinity); + +const double ON_EPSILON = 1.0 / (1 << 8); + +/// \brief Returns true if edge (\p x, \p y) is smaller than the epsilon used to classify winding points against a plane. +inline bool Edge_isDegenerate(const Vector3& x, const Vector3& y) +{ + return vector3_length_squared(y - x) < (ON_EPSILON * ON_EPSILON); +} + +void Winding_Clip(const FixedWinding& winding, const Plane3& plane, const Plane3& clipPlane, std::size_t adjacent, FixedWinding& clipped); + +struct brushsplit_t +{ + brushsplit_t() + { + counts[0] = 0; + counts[1] = 0; + counts[2] = 0; + } + brushsplit_t& operator+=(const brushsplit_t& other) + { + counts[0] += other.counts[0]; + counts[1] += other.counts[1]; + counts[2] += other.counts[2]; + return *this; + } + std::size_t counts[3]; +}; + +brushsplit_t Winding_ClassifyPlane(const Winding& w, const Plane3& plane); + +bool Winding_PlanesConcave(const Winding& w1, const Winding& w2, const Plane3& plane1, const Plane3& plane2); +bool Winding_TestPlane(const Winding& w, const Plane3& plane, bool flipped); + +std::size_t Winding_FindAdjacent(const Winding& w, std::size_t face); + +std::size_t Winding_Opposite(const Winding& w, const std::size_t index, const std::size_t other); +std::size_t Winding_Opposite(const Winding& w, std::size_t index); + +void Winding_Centroid(const Winding& w, const Plane3& plane, Vector3& centroid); + + +inline void Winding_printConnectivity(Winding& winding) +{ + for(Winding::iterator i = winding.begin(); i != winding.end(); ++i) + { + std::size_t vertexIndex = std::distance(winding.begin(), i); + globalOutputStream() << "vertex: " << Unsigned(vertexIndex) << " adjacent: " << Unsigned((*i).adjacent) << "\n"; + } +} + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/windowobservers.cpp b/misc/mediasource/netradiant-src/radiant/windowobservers.cpp new file mode 100644 index 00000000..481f6998 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/windowobservers.cpp @@ -0,0 +1,170 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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 "windowobservers.h" + +#include +#include +#include "generic/bitfield.h" + +namespace +{ + ModifierFlags g_modifier_state = c_modifierNone; +} + +typedef std::vector WindowObservers; + +inline void WindowObservers_OnModifierDown(WindowObservers& observers, ModifierFlags type) +{ + g_modifier_state = bitfield_enable(g_modifier_state, type); + for(WindowObservers::iterator i = observers.begin(); i != observers.end(); ++i) + { + (*i)->onModifierDown(type); + } +} + +inline void WindowObservers_OnModifierUp(WindowObservers& observers, ModifierFlags type) +{ + g_modifier_state = bitfield_disable(g_modifier_state, type); + for(WindowObservers::iterator i = observers.begin(); i != observers.end(); ++i) + { + (*i)->onModifierUp(type); + } +} + +#include + +gboolean selection_modifier_key_press(GtkWidget* widget, GdkEventKey* event, WindowObservers& observers) +{ + switch(event->keyval) + { + case GDK_Alt_L: + case GDK_Alt_R: + //globalOutputStream() << "Alt PRESSED\n"; + WindowObservers_OnModifierDown(observers, c_modifierAlt); + break; + case GDK_Shift_L: + case GDK_Shift_R: + //globalOutputStream() << "Shift PRESSED\n"; + WindowObservers_OnModifierDown(observers, c_modifierShift); + break; + case GDK_Control_L: + case GDK_Control_R: + //globalOutputStream() << "Control PRESSED\n"; + WindowObservers_OnModifierDown(observers, c_modifierControl); + break; + } + return FALSE; +} + +gboolean selection_modifier_key_release(GtkWidget* widget, GdkEventKey* event, WindowObservers& observers) +{ + switch(event->keyval) + { + case GDK_Alt_L: + case GDK_Alt_R: + //globalOutputStream() << "Alt RELEASED\n"; + WindowObservers_OnModifierUp(observers, c_modifierAlt); + break; + case GDK_Shift_L: + case GDK_Shift_R: + //globalOutputStream() << "Shift RELEASED\n"; + WindowObservers_OnModifierUp(observers, c_modifierShift); + break; + case GDK_Control_L: + case GDK_Control_R: + //globalOutputStream() << "Control RELEASED\n"; + WindowObservers_OnModifierUp(observers, c_modifierControl); + break; + } + return FALSE; +} + +void WindowObservers_UpdateModifier(WindowObservers& observers, ModifierFlags modifiers, ModifierFlags modifier) +{ + if(!bitfield_enabled(g_modifier_state, modifier) && bitfield_enabled(modifiers, modifier)) + { + WindowObservers_OnModifierDown(observers, modifier); + } + if(bitfield_enabled(g_modifier_state, modifier) && !bitfield_enabled(modifiers, modifier)) + { + WindowObservers_OnModifierUp(observers, modifier); + } +} + +void WindowObservers_UpdateModifiers(WindowObservers& observers, ModifierFlags modifiers) +{ + WindowObservers_UpdateModifier(observers, modifiers, c_modifierAlt); + WindowObservers_UpdateModifier(observers, modifiers, c_modifierShift); + WindowObservers_UpdateModifier(observers, modifiers, c_modifierControl); +} + +gboolean modifiers_button_press(GtkWidget* widget, GdkEventButton* event, WindowObservers* observers) +{ + if(event->type == GDK_BUTTON_PRESS) + { + WindowObservers_UpdateModifiers(*observers, modifiers_for_state(event->state)); + } + return FALSE; +} + +gboolean modifiers_button_release(GtkWidget* widget, GdkEventButton* event, WindowObservers* observers) +{ + if(event->type == GDK_BUTTON_RELEASE) + { + WindowObservers_UpdateModifiers(*observers, modifiers_for_state(event->state)); + } + return FALSE; +} + +gboolean modifiers_motion(GtkWidget *widget, GdkEventMotion *event, WindowObservers* observers) +{ + WindowObservers_UpdateModifiers(*observers, modifiers_for_state(event->state)); + return FALSE; +} + + +WindowObservers g_window_observers; + +void GlobalWindowObservers_updateModifiers(ModifierFlags modifiers) +{ + WindowObservers_UpdateModifiers(g_window_observers, modifiers); +} + +void GlobalWindowObservers_add(WindowObserver* observer) +{ + g_window_observers.push_back(observer); +} + +void GlobalWindowObservers_connectTopLevel(GtkWindow* window) +{ + g_signal_connect(G_OBJECT(window), "key_press_event", G_CALLBACK(selection_modifier_key_press), &g_window_observers); + g_signal_connect(G_OBJECT(window), "key_release_event", G_CALLBACK(selection_modifier_key_release), &g_window_observers); +} + +void GlobalWindowObservers_connectWidget(GtkWidget* widget) +{ + g_signal_connect(G_OBJECT(widget), "button_press_event", G_CALLBACK(modifiers_button_press), &g_window_observers); + g_signal_connect(G_OBJECT(widget), "button_release_event", G_CALLBACK(modifiers_button_release), &g_window_observers); + g_signal_connect(G_OBJECT(widget), "motion_notify_event", G_CALLBACK(modifiers_motion), &g_window_observers); +} + + diff --git a/misc/mediasource/netradiant-src/radiant/windowobservers.h b/misc/mediasource/netradiant-src/radiant/windowobservers.h new file mode 100644 index 00000000..7a47a936 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/windowobservers.h @@ -0,0 +1,69 @@ +/* +Copyright (C) 2001-2006, William Joseph. +All Rights Reserved. + +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(INCLUDED_WINDOWOBSERVERS_H) +#define INCLUDED_WINDOWOBSERVERS_H + +#include "windowobserver.h" + +#include + +#include "math/vector.h" + +class WindowObserver; +void GlobalWindowObservers_add(WindowObserver* observer); +typedef struct _GtkWidget GtkWidget; +typedef struct _GtkWindow GtkWindow; +void GlobalWindowObservers_connectWidget(GtkWidget* widget); +void GlobalWindowObservers_connectTopLevel(GtkWindow* window); + +inline ButtonIdentifier button_for_button(unsigned int button) +{ + switch(button) + { + case 1: + return c_buttonLeft; + case 2: + return c_buttonMiddle; + case 3: + return c_buttonRight; + } + return c_buttonInvalid; +} + +inline ModifierFlags modifiers_for_state(unsigned int state) +{ + ModifierFlags modifiers = c_modifierNone; + if(state & GDK_SHIFT_MASK) + modifiers |= c_modifierShift; + if(state & GDK_CONTROL_MASK) + modifiers |= c_modifierControl; + if(state & GDK_MOD1_MASK) + modifiers |= c_modifierAlt; + return modifiers; +} + +inline WindowVector WindowVector_forDouble(double x, double y) +{ + return WindowVector(static_cast(x), static_cast(y)); +} + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/xmlstuff.cpp b/misc/mediasource/netradiant-src/radiant/xmlstuff.cpp new file mode 100644 index 00000000..a92a1683 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/xmlstuff.cpp @@ -0,0 +1,32 @@ +/* +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. +*/ + +#include "xmlstuff.h" + diff --git a/misc/mediasource/netradiant-src/radiant/xmlstuff.h b/misc/mediasource/netradiant-src/radiant/xmlstuff.h new file mode 100644 index 00000000..0ffb8e2b --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/xmlstuff.h @@ -0,0 +1,90 @@ +/* +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. +*/ + +//----------------------------------------------------------------------------- +// +// DESCRIPTION: +// header for xml stuff used in radiant +// + +#ifndef __XMLSTUFF__ +#define __XMLSTUFF__ + +#include "libxml/parser.h" + +#include + +class ISAXHandler; + +// a 'user data' structure we pass along in the SAX callbacks to represent the current state +// the recurse value tracks the current depth in the tree +// message_info also stores information to exit the stream listening cleanly with an error: +// if msg_level == SYS_ERR, then we will reset the listening at the end of the current node +// the level for stopping the feed is stored in stop_depth +// unkown nodes are ignored, we use ignore_depth to track the level we start ignoring from +struct message_info_t +{ + int msg_level; // current message level (SYS_MSG, SYS_WRN, SYS_ERR) + int recurse; // current recursion depth (used to track various things) + int ignore_depth; // the ignore depth limit when we are jumping over unknown nodes (0 means we are not ignoring) + int stop_depth; // the depth we need to stop at the end + int geometry_depth; // are we parsing some geometry information (i.e. do we forward the SAX calls?) + ISAXHandler* pGeometry; // the handler + + enum unnamed0 { bufsize = 1024 }; + char m_buffer[bufsize]; + std::size_t m_length; +}; + +class IGL2DWindow; + +class ISAXHandler +{ +public: + virtual void Release() + { + } + virtual void saxStartElement(message_info_t* ctx, const xmlChar* name, const xmlChar** attrs) = 0; + virtual void saxEndElement(message_info_t* ctx, const xmlChar* name) = 0; + virtual void saxCharacters(message_info_t* ctx, const xmlChar* ch, int len) = 0; + virtual const char* getName() + { + return NULL; + } + virtual IGL2DWindow* Highlight() + { + return 0; + } + virtual void DropHighlight() + { + } +}; + +#endif diff --git a/misc/mediasource/netradiant-src/radiant/xywindow.cpp b/misc/mediasource/netradiant-src/radiant/xywindow.cpp new file mode 100644 index 00000000..7352b386 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/xywindow.cpp @@ -0,0 +1,3012 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// XY Window +// +// Leonardo Zide (leo@lokigames.com) +// + +#include "xywindow.h" + +#include "debugging/debugging.h" + +#include "ientity.h" +#include "igl.h" +#include "ibrush.h" +#include "iundo.h" +#include "iimage.h" +#include "ifilesystem.h" +#include "os/path.h" +#include "image.h" +#include "gtkutil/messagebox.h" + +#include +#include + +#include "generic/callback.h" +#include "string/string.h" +#include "stream/stringstream.h" + +#include "scenelib.h" +#include "eclasslib.h" +#include "renderer.h" +#include "moduleobserver.h" + +#include "gtkutil/menu.h" +#include "gtkutil/container.h" +#include "gtkutil/widget.h" +#include "gtkutil/glwidget.h" +#include "gtkutil/filechooser.h" +#include "gtkmisc.h" +#include "select.h" +#include "csg.h" +#include "brushmanip.h" +#include "selection.h" +#include "entity.h" +#include "camwindow.h" +#include "texwindow.h" +#include "mainframe.h" +#include "preferences.h" +#include "commands.h" +#include "feedback.h" +#include "grid.h" +#include "windowobservers.h" + +void LoadTextureRGBA(qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight); + +// d1223m +extern bool g_brush_always_caulk; + +//!\todo Rewrite. +class ClipPoint +{ +public: + Vector3 m_ptClip; // the 3d point + bool m_bSet; + + ClipPoint() + { + Reset(); + }; + void Reset() + { + m_ptClip[0] = m_ptClip[1] = m_ptClip[2] = 0.0; + m_bSet = false; + } + bool Set() + { + return m_bSet; + } + void Set(bool b) + { + m_bSet = b; + } + operator Vector3&() + { + return m_ptClip; + }; + + /*! Draw clip/path point with rasterized number label */ + void Draw(int num, float scale); + /*! Draw clip/path point with rasterized string label */ + void Draw(const char *label, float scale); +}; + +VIEWTYPE g_clip_viewtype; +bool g_bSwitch = true; +bool g_clip_useCaulk = false; +ClipPoint g_Clip1; +ClipPoint g_Clip2; +ClipPoint g_Clip3; +ClipPoint* g_pMovingClip = 0; + +/* Drawing clip points */ +void ClipPoint::Draw(int num, float scale) +{ + StringOutputStream label(4); + label << num; + Draw(label.c_str(), scale); +} + +void ClipPoint::Draw(const char *label, float scale) +{ + // draw point + glPointSize (4); + glColor3fv(vector3_to_array(g_xywindow_globals.color_clipper)); + glBegin (GL_POINTS); + glVertex3fv(vector3_to_array(m_ptClip)); + glEnd(); + glPointSize (1); + + float offset = 2.0f / scale; + + // draw label + glRasterPos3f (m_ptClip[0] + offset, m_ptClip[1] + offset, m_ptClip[2] + offset); + glCallLists (GLsizei(strlen(label)), GL_UNSIGNED_BYTE, label); +} + +float fDiff(float f1, float f2) +{ + if (f1 > f2) + return f1 - f2; + else + return f2 - f1; +} + +inline double ClipPoint_Intersect(const ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale) +{ + int nDim1 = (viewtype == YZ) ? 1 : 0; + int nDim2 = (viewtype == XY) ? 1 : 2; + double screenDistanceSquared(vector2_length_squared(Vector2(fDiff(clip.m_ptClip[nDim1], point[nDim1]) * scale, fDiff(clip.m_ptClip[nDim2], point[nDim2]) * scale))); + if(screenDistanceSquared < 8*8) + { + return screenDistanceSquared; + } + return FLT_MAX; +} + +inline void ClipPoint_testSelect(ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale, double& bestDistance, ClipPoint*& bestClip) +{ + if(clip.Set()) + { + double distance = ClipPoint_Intersect(clip, point, viewtype, scale); + if(distance < bestDistance) + { + bestDistance = distance; + bestClip = &clip; + } + } +} + +inline ClipPoint* GlobalClipPoints_Find(const Vector3& point, VIEWTYPE viewtype, float scale) +{ + double bestDistance = FLT_MAX; + ClipPoint* bestClip = 0; + ClipPoint_testSelect(g_Clip1, point, viewtype, scale, bestDistance, bestClip); + ClipPoint_testSelect(g_Clip2, point, viewtype, scale, bestDistance, bestClip); + ClipPoint_testSelect(g_Clip3, point, viewtype, scale, bestDistance, bestClip); + return bestClip; +} + +inline void GlobalClipPoints_Draw(float scale) +{ + // Draw clip points + if (g_Clip1.Set()) + g_Clip1.Draw(1, scale); + if (g_Clip2.Set()) + g_Clip2.Draw(2, scale); + if (g_Clip3.Set()) + g_Clip3.Draw(3, scale); +} + +inline bool GlobalClipPoints_valid() +{ + return g_Clip1.Set() && g_Clip2.Set(); +} + +void PlanePointsFromClipPoints(Vector3 planepts[3], const AABB& bounds, int viewtype) +{ + ASSERT_MESSAGE(GlobalClipPoints_valid(), "clipper points not initialised"); + planepts[0] = g_Clip1.m_ptClip; + planepts[1] = g_Clip2.m_ptClip; + planepts[2] = g_Clip3.m_ptClip; + Vector3 maxs(vector3_added(bounds.origin, bounds.extents)); + Vector3 mins(vector3_subtracted(bounds.origin, bounds.extents)); + if(!g_Clip3.Set()) + { + int n = (viewtype == XY) ? 2 : (viewtype == YZ) ? 0 : 1; + int x = (n == 0) ? 1 : 0; + int y = (n == 2) ? 1 : 2; + + if (n == 1) // on viewtype XZ, flip clip points + { + planepts[0][n] = maxs[n]; + planepts[1][n] = maxs[n]; + planepts[2][x] = g_Clip1.m_ptClip[x]; + planepts[2][y] = g_Clip1.m_ptClip[y]; + planepts[2][n] = mins[n]; + } + else + { + planepts[0][n] = mins[n]; + planepts[1][n] = mins[n]; + planepts[2][x] = g_Clip1.m_ptClip[x]; + planepts[2][y] = g_Clip1.m_ptClip[y]; + planepts[2][n] = maxs[n]; + } + } +} + +void Clip_Update() +{ + Vector3 planepts[3]; + if(!GlobalClipPoints_valid()) + { + planepts[0] = Vector3(0, 0, 0); + planepts[1] = Vector3(0, 0, 0); + planepts[2] = Vector3(0, 0, 0); + Scene_BrushSetClipPlane(GlobalSceneGraph(), Plane3(0, 0, 0, 0)); + } + else + { + AABB bounds(Vector3(0, 0, 0), Vector3(64, 64, 64)); + PlanePointsFromClipPoints(planepts, bounds, g_clip_viewtype); + if(g_bSwitch) + { + std::swap(planepts[0], planepts[1]); + } + Scene_BrushSetClipPlane(GlobalSceneGraph(), plane3_for_points(planepts[0], planepts[1], planepts[2])); + } + ClipperChangeNotify(); +} + +const char* Clip_getShader() +{ + return g_clip_useCaulk ? "textures/common/caulk" : TextureBrowser_GetSelectedShader(GlobalTextureBrowser()); +} + +void Clip() +{ + if (ClipMode() && GlobalClipPoints_valid()) + { + Vector3 planepts[3]; + AABB bounds(Vector3(0, 0, 0), Vector3(64, 64, 64)); + PlanePointsFromClipPoints(planepts, bounds, g_clip_viewtype); + Scene_BrushSplitByPlane(GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), (!g_bSwitch) ? eFront : eBack); + g_Clip1.Reset(); + g_Clip2.Reset(); + g_Clip3.Reset(); + Clip_Update(); + ClipperChangeNotify(); + } +} + +void SplitClip() +{ + if (ClipMode() && GlobalClipPoints_valid()) + { + Vector3 planepts[3]; + AABB bounds(Vector3(0, 0, 0), Vector3(64, 64, 64)); + PlanePointsFromClipPoints(planepts, bounds, g_clip_viewtype); + Scene_BrushSplitByPlane(GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), eFrontAndBack); + g_Clip1.Reset(); + g_Clip2.Reset(); + g_Clip3.Reset(); + Clip_Update(); + ClipperChangeNotify(); + } +} + +void FlipClip() +{ + g_bSwitch = !g_bSwitch; + Clip_Update(); + ClipperChangeNotify(); +} + +void OnClipMode(bool enabled) +{ + g_Clip1.Reset(); + g_Clip2.Reset(); + g_Clip3.Reset(); + + if(!enabled && g_pMovingClip) + { + g_pMovingClip = 0; + } + + Clip_Update(); + ClipperChangeNotify(); +} + +bool ClipMode() +{ + return GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip; +} + +void NewClipPoint(const Vector3& point) +{ + if (g_Clip1.Set() == false) + { + g_Clip1.m_ptClip = point; + g_Clip1.Set(true); + } + else if (g_Clip2.Set() == false) + { + g_Clip2.m_ptClip = point; + g_Clip2.Set(true); + } + else if (g_Clip3.Set() == false) + { + g_Clip3.m_ptClip = point; + g_Clip3.Set(true); + } + else + { + g_Clip1.Reset(); + g_Clip2.Reset(); + g_Clip3.Reset(); + g_Clip1.m_ptClip = point; + g_Clip1.Set(true); + } + + Clip_Update(); + ClipperChangeNotify(); +} + + + +struct xywindow_globals_private_t +{ + bool d_showgrid; + + // these are in the View > Show menu with Show coordinates + bool show_names; + bool show_coordinates; + bool show_angles; + bool show_outline; + bool show_axis; + + bool d_show_work; + + bool show_blocks; + int blockSize; + + bool m_bCamXYUpdate; + bool m_bChaseMouse; + bool m_bSizePaint; + + xywindow_globals_private_t() : + d_showgrid(true), + + show_names(false), + show_coordinates(true), + show_angles(true), + show_outline(false), + show_axis(true), + + d_show_work(false), + + show_blocks(false), + + m_bCamXYUpdate(true), + m_bChaseMouse(true), + m_bSizePaint(true) + { + } + +}; + +xywindow_globals_t g_xywindow_globals; +xywindow_globals_private_t g_xywindow_globals_private; + +const unsigned int RAD_NONE = 0x00; +const unsigned int RAD_SHIFT = 0x01; +const unsigned int RAD_ALT = 0x02; +const unsigned int RAD_CONTROL = 0x04; +const unsigned int RAD_PRESS = 0x08; +const unsigned int RAD_LBUTTON = 0x10; +const unsigned int RAD_MBUTTON = 0x20; +const unsigned int RAD_RBUTTON = 0x40; + +inline ButtonIdentifier button_for_flags(unsigned int flags) +{ + if(flags & RAD_LBUTTON) + return c_buttonLeft; + if(flags & RAD_RBUTTON) + return c_buttonRight; + if(flags & RAD_MBUTTON) + return c_buttonMiddle; + return c_buttonInvalid; +} + +inline ModifierFlags modifiers_for_flags(unsigned int flags) +{ + ModifierFlags modifiers = c_modifierNone; + if(flags & RAD_SHIFT) + modifiers |= c_modifierShift; + if(flags & RAD_CONTROL) + modifiers |= c_modifierControl; + if(flags & RAD_ALT) + modifiers |= c_modifierAlt; + return modifiers; +} + +inline unsigned int buttons_for_button_and_modifiers(ButtonIdentifier button, ModifierFlags flags) +{ + unsigned int buttons = 0; + + switch (button.get()) + { + case ButtonEnumeration::LEFT: buttons |= RAD_LBUTTON; break; + case ButtonEnumeration::MIDDLE: buttons |= RAD_MBUTTON; break; + case ButtonEnumeration::RIGHT: buttons |= RAD_RBUTTON; break; + } + + if(bitfield_enabled(flags, c_modifierControl)) + buttons |= RAD_CONTROL; + + if(bitfield_enabled(flags, c_modifierShift)) + buttons |= RAD_SHIFT; + + if(bitfield_enabled(flags, c_modifierAlt)) + buttons |= RAD_ALT; + + return buttons; +} + +inline unsigned int buttons_for_event_button(GdkEventButton* event) +{ + unsigned int flags = 0; + + switch (event->button) + { + case 1: flags |= RAD_LBUTTON; break; + case 2: flags |= RAD_MBUTTON; break; + case 3: flags |= RAD_RBUTTON; break; + } + + if ((event->state & GDK_CONTROL_MASK) != 0) + flags |= RAD_CONTROL; + + if ((event->state & GDK_SHIFT_MASK) != 0) + flags |= RAD_SHIFT; + + if((event->state & GDK_MOD1_MASK) != 0) + flags |= RAD_ALT; + + return flags; +} + +inline unsigned int buttons_for_state(guint state) +{ + unsigned int flags = 0; + + if ((state & GDK_BUTTON1_MASK) != 0) + flags |= RAD_LBUTTON; + + if ((state & GDK_BUTTON2_MASK) != 0) + flags |= RAD_MBUTTON; + + if ((state & GDK_BUTTON3_MASK) != 0) + flags |= RAD_RBUTTON; + + if ((state & GDK_CONTROL_MASK) != 0) + flags |= RAD_CONTROL; + + if ((state & GDK_SHIFT_MASK) != 0) + flags |= RAD_SHIFT; + + if ((state & GDK_MOD1_MASK) != 0) + flags |= RAD_ALT; + + return flags; +} + + +void XYWnd::SetScale(float f) +{ + m_fScale = f; + updateProjection(); + updateModelview(); + XYWnd_Update(*this); +} + +void XYWnd_ZoomIn(XYWnd* xy) +{ + float max_scale = 64; + float scale = xy->Scale() * 5.0f / 4.0f; + if(scale > max_scale) + { + if(xy->Scale() != max_scale) + { + xy->SetScale (max_scale); + } + } + else + { + xy->SetScale(scale); + } +} + + +// NOTE: the zoom out factor is 4/5, we could think about customizing it +// we don't go below a zoom factor corresponding to 10% of the max world size +// (this has to be computed against the window size) +void XYWnd_ZoomOut(XYWnd* xy) +{ + float min_scale = MIN(xy->Width(),xy->Height()) / ( 1.1f * (g_MaxWorldCoord-g_MinWorldCoord)); + float scale = xy->Scale() * 4.0f / 5.0f; + if(scale < min_scale) + { + if(xy->Scale() != min_scale) + { + xy->SetScale (min_scale); + } + } + else + { + xy->SetScale(scale); + } +} + +VIEWTYPE GlobalXYWnd_getCurrentViewType() +{ + ASSERT_NOTNULL(g_pParentWnd); + ASSERT_NOTNULL(g_pParentWnd->ActiveXY()); + return g_pParentWnd->ActiveXY()->GetViewType(); +} + +// ============================================================================= +// variables + +bool g_bCrossHairs = false; + +GtkMenu* XYWnd::m_mnuDrop = 0; + +// this is disabled, and broken +// http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394 +#if 0 +void WXY_Print() +{ + long width, height; + width = g_pParentWnd->ActiveXY()->Width(); + height = g_pParentWnd->ActiveXY()->Height(); + unsigned char* img; + const char* filename; + + filename = file_dialog(GTK_WIDGET(MainFrame_getWindow()), FALSE, "Save Image", 0, FILTER_BMP); + if (!filename) + return; + + g_pParentWnd->ActiveXY()->MakeCurrent(); + img = (unsigned char*)malloc (width*height*3); + glReadPixels (0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,img); + + FILE *fp; + fp = fopen(filename, "wb"); + if (fp) + { + unsigned short bits; + unsigned long cmap, bfSize; + + bits = 24; + cmap = 0; + bfSize = 54 + width*height*3; + + long byteswritten = 0; + long pixoff = 54 + cmap*4; + short res = 0; + char m1 ='B', m2 ='M'; + fwrite(&m1, 1, 1, fp); byteswritten++; // B + fwrite(&m2, 1, 1, fp); byteswritten++; // M + fwrite(&bfSize, 4, 1, fp); byteswritten+=4;// bfSize + fwrite(&res, 2, 1, fp); byteswritten+=2;// bfReserved1 + fwrite(&res, 2, 1, fp); byteswritten+=2;// bfReserved2 + fwrite(&pixoff, 4, 1, fp); byteswritten+=4;// bfOffBits + + unsigned long biSize = 40, compress = 0, size = 0; + long pixels = 0; + unsigned short planes = 1; + fwrite(&biSize, 4, 1, fp); byteswritten+=4;// biSize + fwrite(&width, 4, 1, fp); byteswritten+=4;// biWidth + fwrite(&height, 4, 1, fp); byteswritten+=4;// biHeight + fwrite(&planes, 2, 1, fp); byteswritten+=2;// biPlanes + fwrite(&bits, 2, 1, fp); byteswritten+=2;// biBitCount + fwrite(&compress, 4, 1, fp);byteswritten+=4;// biCompression + fwrite(&size, 4, 1, fp); byteswritten+=4;// biSizeImage + fwrite(&pixels, 4, 1, fp); byteswritten+=4;// biXPelsPerMeter + fwrite(&pixels, 4, 1, fp); byteswritten+=4;// biYPelsPerMeter + fwrite(&cmap, 4, 1, fp); byteswritten+=4;// biClrUsed + fwrite(&cmap, 4, 1, fp); byteswritten+=4;// biClrImportant + + unsigned long widthDW = (((width*24) + 31) / 32 * 4); + long row, row_size = width*3; + for (row = 0; row < height; row++) + { + unsigned char* buf = img+row*row_size; + + // write a row + int col; + for (col = 0; col < row_size; col += 3) + { + putc(buf[col+2], fp); + putc(buf[col+1], fp); + putc(buf[col], fp); + } + byteswritten += row_size; + + unsigned long count; + for (count = row_size; count < widthDW; count++) + { + putc(0, fp); // dummy + byteswritten++; + } + } + + fclose(fp); + } + + free (img); +} +#endif + + +#include "timer.h" + +Timer g_chasemouse_timer; + +void XYWnd::ChaseMouse() +{ + float multiplier = g_chasemouse_timer.elapsed_msec() / 10.0f; + Scroll(float_to_integer(multiplier * m_chasemouse_delta_x), float_to_integer(multiplier * -m_chasemouse_delta_y)); + + //globalOutputStream() << "chasemouse: multiplier=" << multiplier << " x=" << m_chasemouse_delta_x << " y=" << m_chasemouse_delta_y << '\n'; + + XY_MouseMoved(m_chasemouse_current_x, m_chasemouse_current_y , getButtonState()); + g_chasemouse_timer.start(); +} + +gboolean xywnd_chasemouse(gpointer data) +{ + reinterpret_cast(data)->ChaseMouse(); + return TRUE; +} + +inline const int& min_int(const int& left, const int& right) +{ + return std::min(left, right); +} + +bool XYWnd::chaseMouseMotion(int pointx, int pointy) +{ + m_chasemouse_delta_x = 0; + m_chasemouse_delta_y = 0; + + if (g_xywindow_globals_private.m_bChaseMouse && getButtonState() == RAD_LBUTTON) + { + const int epsilon = 16; + + if (pointx < epsilon) + { + m_chasemouse_delta_x = std::max(pointx, 0) - epsilon; + } + else if ((pointx - m_nWidth) > -epsilon) + { + m_chasemouse_delta_x = min_int((pointx - m_nWidth), 0) + epsilon; + } + + if (pointy < epsilon) + { + m_chasemouse_delta_y = std::max(pointy, 0) - epsilon; + } + else if ((pointy - m_nHeight) > -epsilon) + { + m_chasemouse_delta_y = min_int((pointy - m_nHeight), 0) + epsilon; + } + + if(m_chasemouse_delta_y != 0 || m_chasemouse_delta_x != 0) + { + //globalOutputStream() << "chasemouse motion: x=" << pointx << " y=" << pointy << "... "; + m_chasemouse_current_x = pointx; + m_chasemouse_current_y = pointy; + if(m_chasemouse_handler == 0) + { + //globalOutputStream() << "chasemouse timer start... "; + g_chasemouse_timer.start(); + m_chasemouse_handler = g_idle_add(xywnd_chasemouse, this); + } + return true; + } + else + { + if(m_chasemouse_handler != 0) + { + //globalOutputStream() << "chasemouse cancel\n"; + g_source_remove(m_chasemouse_handler); + m_chasemouse_handler = 0; + } + } + } + else + { + if(m_chasemouse_handler != 0) + { + //globalOutputStream() << "chasemouse cancel\n"; + g_source_remove(m_chasemouse_handler); + m_chasemouse_handler = 0; + } + } + return false; +} + +// ============================================================================= +// XYWnd class +Shader* XYWnd::m_state_selected = 0; + +void xy_update_xor_rectangle(XYWnd& self, rect_t area) +{ + if(GTK_WIDGET_VISIBLE(self.GetWidget())) + { + self.m_XORRectangle.set(rectangle_from_area(area.min, area.max, self.Width(), self.Height())); + } +} + +gboolean xywnd_button_press(GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd) +{ + if(event->type == GDK_BUTTON_PRESS) + { + g_pParentWnd->SetActiveXY(xywnd); + + xywnd->ButtonState_onMouseDown(buttons_for_event_button(event)); + + xywnd->onMouseDown(WindowVector(event->x, event->y), button_for_button(event->button), modifiers_for_state(event->state)); + } + return FALSE; +} + +gboolean xywnd_button_release(GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd) +{ + if(event->type == GDK_BUTTON_RELEASE) + { + xywnd->XY_MouseUp(static_cast(event->x), static_cast(event->y), buttons_for_event_button(event)); + + xywnd->ButtonState_onMouseUp(buttons_for_event_button(event)); + } + return FALSE; +} + +gboolean xywnd_focus_in(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd) +{ + if(event->type == GDK_FOCUS_CHANGE) + { + if(event->in) + g_pParentWnd->SetActiveXY(xywnd); + } + return FALSE; +} + +void xywnd_motion(gdouble x, gdouble y, guint state, void* data) +{ + if(reinterpret_cast(data)->chaseMouseMotion(static_cast(x), static_cast(y))) + { + return; + } + reinterpret_cast(data)->XY_MouseMoved(static_cast(x), static_cast(y), buttons_for_state(state)); +} + +gboolean xywnd_wheel_scroll(GtkWidget* widget, GdkEventScroll* event, XYWnd* xywnd) +{ + if(event->direction == GDK_SCROLL_UP) + { + XYWnd_ZoomIn(xywnd); + } + else if(event->direction == GDK_SCROLL_DOWN) + { + XYWnd_ZoomOut(xywnd); + } + return FALSE; +} + +gboolean xywnd_size_allocate(GtkWidget* widget, GtkAllocation* allocation, XYWnd* xywnd) +{ + xywnd->m_nWidth = allocation->width; + xywnd->m_nHeight = allocation->height; + xywnd->updateProjection(); + xywnd->m_window_observer->onSizeChanged(xywnd->Width(), xywnd->Height()); + return FALSE; +} + +gboolean xywnd_expose(GtkWidget* widget, GdkEventExpose* event, XYWnd* xywnd) +{ + if(glwidget_make_current(xywnd->GetWidget()) != FALSE) + { + if(Map_Valid(g_map) && ScreenUpdates_Enabled()) + { + GlobalOpenGL_debugAssertNoErrors(); + xywnd->XY_Draw(); + GlobalOpenGL_debugAssertNoErrors(); + + xywnd->m_XORRectangle.set(rectangle_t()); + } + glwidget_swap_buffers(xywnd->GetWidget()); + } + return FALSE; +} + + +void XYWnd_CameraMoved(XYWnd& xywnd) +{ + if(g_xywindow_globals_private.m_bCamXYUpdate) + { + XYWnd_Update(xywnd); + } +} + +XYWnd::XYWnd() : + m_gl_widget(glwidget_new(FALSE)), + m_deferredDraw(WidgetQueueDrawCaller(*m_gl_widget)), + m_deferred_motion(xywnd_motion, this), + m_parent(0), + m_window_observer(NewWindowObserver()), + m_XORRectangle(m_gl_widget), + m_chasemouse_handler(0) +{ + m_bActive = false; + m_buttonstate = 0; + + m_bNewBrushDrag = false; + m_move_started = false; + m_zoom_started = false; + + m_nWidth = 0; + m_nHeight = 0; + + m_vOrigin[0] = 0; + m_vOrigin[1] = 20; + m_vOrigin[2] = 46; + m_fScale = 1; + m_viewType = XY; + + m_backgroundActivated = false; + m_alpha = 1.0f; + m_xmin = 0.0f; + m_ymin = 0.0f; + m_xmax = 0.0f; + m_ymax = 0.0f; + + m_entityCreate = false; + + m_mnuDrop = 0; + + GlobalWindowObservers_add(m_window_observer); + GlobalWindowObservers_connectWidget(m_gl_widget); + + m_window_observer->setRectangleDrawCallback(ReferenceCaller1(*this)); + m_window_observer->setView(m_view); + + gtk_widget_ref(m_gl_widget); + + gtk_widget_set_events(m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK); + GTK_WIDGET_SET_FLAGS(m_gl_widget, GTK_CAN_FOCUS); + + m_sizeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "size_allocate", G_CALLBACK(xywnd_size_allocate), this); + m_exposeHandler = g_signal_connect(G_OBJECT(m_gl_widget), "expose_event", G_CALLBACK(xywnd_expose), this); + + g_signal_connect(G_OBJECT(m_gl_widget), "button_press_event", G_CALLBACK(xywnd_button_press), this); + g_signal_connect(G_OBJECT(m_gl_widget), "button_release_event", G_CALLBACK(xywnd_button_release), this); + g_signal_connect(G_OBJECT(m_gl_widget), "focus_in_event", G_CALLBACK(xywnd_focus_in), this); + g_signal_connect(G_OBJECT(m_gl_widget), "motion_notify_event", G_CALLBACK(DeferredMotion::gtk_motion), &m_deferred_motion); + + g_signal_connect(G_OBJECT(m_gl_widget), "scroll_event", G_CALLBACK(xywnd_wheel_scroll), this); + + Map_addValidCallback(g_map, DeferredDrawOnMapValidChangedCaller(m_deferredDraw)); + + updateProjection(); + updateModelview(); + + AddSceneChangeCallback(ReferenceCaller(*this)); + AddCameraMovedCallback(ReferenceCaller(*this)); + + PressedButtons_connect(g_pressedButtons, m_gl_widget); + + onMouseDown.connectLast(makeSignalHandler3(MouseDownCaller(), *this)); +} + +XYWnd::~XYWnd() +{ + onDestroyed(); + + if(m_mnuDrop != 0) + { + gtk_widget_destroy(GTK_WIDGET(m_mnuDrop)); + m_mnuDrop = 0; + } + + g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_sizeHandler); + g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_exposeHandler); + + gtk_widget_unref(m_gl_widget); + + m_window_observer->release(); +} + +void XYWnd::captureStates() +{ + m_state_selected = GlobalShaderCache().capture("$XY_OVERLAY"); +} + +void XYWnd::releaseStates() +{ + GlobalShaderCache().release("$XY_OVERLAY"); +} + +const Vector3& XYWnd::GetOrigin() +{ + return m_vOrigin; +} + +void XYWnd::SetOrigin(const Vector3& origin) +{ + m_vOrigin = origin; + updateModelview(); +} + +void XYWnd::Scroll(int x, int y) +{ + int nDim1 = (m_viewType == YZ) ? 1 : 0; + int nDim2 = (m_viewType == XY) ? 1 : 2; + m_vOrigin[nDim1] += x / m_fScale; + m_vOrigin[nDim2] += y / m_fScale; + updateModelview(); + queueDraw(); +} + +unsigned int Clipper_buttons() +{ + return RAD_LBUTTON; +} + +void XYWnd::DropClipPoint(int pointx, int pointy) +{ + Vector3 point; + + XY_ToPoint(pointx, pointy, point); + + Vector3 mid; + Select_GetMid(mid); + g_clip_viewtype = static_cast(GetViewType()); + const int nDim = (g_clip_viewtype == YZ ) ? 0 : ( (g_clip_viewtype == XZ) ? 1 : 2 ); + point[nDim] = mid[nDim]; + vector3_snap(point, GetSnapGridSize()); + NewClipPoint(point); +} + +void XYWnd::Clipper_OnLButtonDown(int x, int y) +{ + Vector3 mousePosition; + XY_ToPoint(x, y , mousePosition); + g_pMovingClip = GlobalClipPoints_Find(mousePosition, (VIEWTYPE)m_viewType, m_fScale); + if(!g_pMovingClip) + { + DropClipPoint(x, y); + } +} + +void XYWnd::Clipper_OnLButtonUp(int x, int y) +{ + if (g_pMovingClip) + { + g_pMovingClip = 0; + } +} + +void XYWnd::Clipper_OnMouseMoved(int x, int y) +{ + if (g_pMovingClip) + { + XY_ToPoint(x, y , g_pMovingClip->m_ptClip); + XY_SnapToGrid(g_pMovingClip->m_ptClip); + Clip_Update(); + ClipperChangeNotify(); + } +} + +void XYWnd::Clipper_Crosshair_OnMouseMoved(int x, int y) +{ + Vector3 mousePosition; + XY_ToPoint(x, y , mousePosition); + if(ClipMode() && GlobalClipPoints_Find(mousePosition, (VIEWTYPE)m_viewType, m_fScale) != 0) + { + GdkCursor *cursor; + cursor = gdk_cursor_new (GDK_CROSSHAIR); + gdk_window_set_cursor (m_gl_widget->window, cursor); + gdk_cursor_unref (cursor); + } + else + { + gdk_window_set_cursor (m_gl_widget->window, 0); + } +} + +unsigned int MoveCamera_buttons() +{ + return RAD_CONTROL | (g_glwindow_globals.m_nMouseType == ETwoButton ? RAD_RBUTTON : RAD_MBUTTON); +} + +void XYWnd_PositionCamera(XYWnd* xywnd, int x, int y, CamWnd& camwnd) +{ + Vector3 origin(Camera_getOrigin(camwnd)); + xywnd->XY_ToPoint(x, y, origin); + xywnd->XY_SnapToGrid(origin); + Camera_setOrigin(camwnd, origin); +} + +unsigned int OrientCamera_buttons() +{ + if(g_glwindow_globals.m_nMouseType == ETwoButton) + return RAD_RBUTTON | RAD_SHIFT | RAD_CONTROL; + return RAD_MBUTTON; +} + +void XYWnd_OrientCamera(XYWnd* xywnd, int x, int y, CamWnd& camwnd) +{ + Vector3 point = g_vector3_identity; + xywnd->XY_ToPoint(x, y, point); + xywnd->XY_SnapToGrid(point); + vector3_subtract(point, Camera_getOrigin(camwnd)); + + int n1 = (xywnd->GetViewType() == XY) ? 1 : 2; + int n2 = (xywnd->GetViewType() == YZ) ? 1 : 0; + int nAngle = (xywnd->GetViewType() == XY) ? CAMERA_YAW : CAMERA_PITCH; + if (point[n1] || point[n2]) + { + Vector3 angles(Camera_getAngles(camwnd)); + angles[nAngle] = static_cast(radians_to_degrees(atan2 (point[n1], point[n2]))); + Camera_setAngles(camwnd, angles); + } +} + +/* +============== +NewBrushDrag +============== +*/ +unsigned int NewBrushDrag_buttons() +{ + return RAD_LBUTTON; +} + +void XYWnd::NewBrushDrag_Begin(int x, int y) +{ + m_NewBrushDrag = 0; + m_nNewBrushPressx = x; + m_nNewBrushPressy = y; + + m_bNewBrushDrag = true; + GlobalUndoSystem().start(); +} + +void XYWnd::NewBrushDrag_End(int x, int y) +{ + if(m_NewBrushDrag != 0) + { + GlobalUndoSystem().finish("brushDragNew"); + } +} + +void XYWnd::NewBrushDrag(int x, int y) +{ + Vector3 mins, maxs; + XY_ToPoint(m_nNewBrushPressx, m_nNewBrushPressy, mins); + XY_SnapToGrid(mins); + XY_ToPoint(x, y, maxs); + XY_SnapToGrid(maxs); + + int nDim = (m_viewType == XY) ? 2 : (m_viewType == YZ) ? 0 : 1; + + mins[nDim] = float_snapped(Select_getWorkZone().d_work_min[nDim], GetSnapGridSize()); + maxs[nDim] = float_snapped(Select_getWorkZone().d_work_max[nDim], GetSnapGridSize()); + + if (maxs[nDim] <= mins[nDim]) + maxs[nDim] = mins[nDim] + GetGridSize(); + + for(int i=0 ; i<3 ; i++) + { + if (mins[i] == maxs[i]) + return; // don't create a degenerate brush + if (mins[i] > maxs[i]) + { + float temp = mins[i]; + mins[i] = maxs[i]; + maxs[i] = temp; + } + } + + if(m_NewBrushDrag == 0) + { + NodeSmartReference node(GlobalBrushCreator().createBrush()); + Node_getTraversable(Map_FindOrInsertWorldspawn(g_map))->insert(node); + + scene::Path brushpath(makeReference(GlobalSceneGraph().root())); + brushpath.push(makeReference(*Map_GetWorldspawn(g_map))); + brushpath.push(makeReference(node.get())); + selectPath(brushpath, true); + + m_NewBrushDrag = node.get_pointer(); + } + + // d1223m + //Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); + Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), + g_brush_always_caulk ? + "textures/common/caulk" : TextureBrowser_GetSelectedShader(GlobalTextureBrowser())); +} + +void entitycreate_activated(GtkWidget* item) +{ + scene::Node* world_node = Map_FindWorldspawn(g_map); + const char* entity_name = gtk_label_get_text(GTK_LABEL(GTK_BIN(item)->child)); + + if(!(world_node && string_equal(entity_name, "worldspawn"))) + { + g_pParentWnd->ActiveXY()->OnEntityCreate(entity_name); + } else { + GlobalRadiant().m_pfnMessageBox(GTK_WIDGET(MainFrame_getWindow()), "There's already a worldspawn in your map!" + "", + "Info", + eMB_OK, + eMB_ICONDEFAULT); + } +} + +void EntityClassMenu_addItem(GtkMenu* menu, const char* name) +{ + GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(name)); + g_signal_connect(G_OBJECT(item), "activate", G_CALLBACK(entitycreate_activated), item); + gtk_widget_show(GTK_WIDGET(item)); + menu_add_item(menu, item); +} + +class EntityClassMenuInserter : public EntityClassVisitor +{ + typedef std::pair MenuPair; + typedef std::vector MenuStack; + MenuStack m_stack; + CopiedString m_previous; +public: + EntityClassMenuInserter(GtkMenu* menu) + { + m_stack.reserve(2); + m_stack.push_back(MenuPair(menu, "")); + } + ~EntityClassMenuInserter() + { + if(!string_empty(m_previous.c_str())) + { + addItem(m_previous.c_str(), ""); + } + } + void visit(EntityClass* e) + { + ASSERT_MESSAGE(!string_empty(e->name()), "entity-class has no name"); + if(!string_empty(m_previous.c_str())) + { + addItem(m_previous.c_str(), e->name()); + } + m_previous = e->name(); + } + void pushMenu(const CopiedString& name) + { + GtkMenuItem* item = GTK_MENU_ITEM(gtk_menu_item_new_with_label(name.c_str())); + gtk_widget_show(GTK_WIDGET(item)); + container_add_widget(GTK_CONTAINER(m_stack.back().first), GTK_WIDGET(item)); + + GtkMenu* submenu = GTK_MENU(gtk_menu_new()); + gtk_menu_item_set_submenu(item, GTK_WIDGET(submenu)); + + m_stack.push_back(MenuPair(submenu, name)); + } + void popMenu() + { + m_stack.pop_back(); + } + void addItem(const char* name, const char* next) + { + const char* underscore = strchr(name, '_'); + + if(underscore != 0 && underscore != name) + { + bool nextEqual = string_equal_n(name, next, (underscore + 1) - name); + const char* parent = m_stack.back().second.c_str(); + + if(!string_empty(parent) + && string_length(parent) == std::size_t(underscore - name) + && string_equal_n(name, parent, underscore - name)) // this is a child + { + } + else if(nextEqual) + { + if(m_stack.size() == 2) + { + popMenu(); + } + pushMenu(CopiedString(StringRange(name, underscore))); + } + else if(m_stack.size() == 2) + { + popMenu(); + } + } + else if(m_stack.size() == 2) + { + popMenu(); + } + + EntityClassMenu_addItem(m_stack.back().first, name); + } +}; + +void XYWnd::OnContextMenu() +{ + if (g_xywindow_globals.m_bRightClick == false) + return; + + if (m_mnuDrop == 0) // first time, load it up + { + GtkMenu* menu = m_mnuDrop = GTK_MENU(gtk_menu_new()); + + EntityClassMenuInserter inserter(menu); + GlobalEntityClassManager().forEach(inserter); + } + + gtk_menu_popup(m_mnuDrop, 0, 0, 0, 0, 1, GDK_CURRENT_TIME); +} + +FreezePointer g_xywnd_freezePointer; + +unsigned int Move_buttons() +{ + return RAD_RBUTTON; +} + +void XYWnd_moveDelta(int x, int y, unsigned int state, void* data) +{ + reinterpret_cast(data)->EntityCreate_MouseMove(x, y); + reinterpret_cast(data)->Scroll(-x, y); +} + +gboolean XYWnd_Move_focusOut(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd) +{ + xywnd->Move_End(); + return FALSE; +} + +void XYWnd::Move_Begin() +{ + if(m_move_started) + { + Move_End(); + } + m_move_started = true; + g_xywnd_freezePointer.freeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow(), XYWnd_moveDelta, this); + m_move_focusOut = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(XYWnd_Move_focusOut), this); +} + +void XYWnd::Move_End() +{ + m_move_started = false; + g_xywnd_freezePointer.unfreeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow()); + g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_move_focusOut); +} + +unsigned int Zoom_buttons() +{ + return RAD_RBUTTON | RAD_SHIFT; +} + +int g_dragZoom = 0; + +void XYWnd_zoomDelta(int x, int y, unsigned int state, void* data) +{ + if(y != 0) + { + g_dragZoom += y; + + while(abs(g_dragZoom) > 8) + { + if(g_dragZoom > 0) + { + XYWnd_ZoomOut(reinterpret_cast(data)); + g_dragZoom -= 8; + } + else + { + XYWnd_ZoomIn(reinterpret_cast(data)); + g_dragZoom += 8; + } + } + } +} + +gboolean XYWnd_Zoom_focusOut(GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd) +{ + xywnd->Zoom_End(); + return FALSE; +} + +void XYWnd::Zoom_Begin() +{ + if(m_zoom_started) + { + Zoom_End(); + } + m_zoom_started = true; + g_dragZoom = 0; + g_xywnd_freezePointer.freeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow(), XYWnd_zoomDelta, this); + m_zoom_focusOut = g_signal_connect(G_OBJECT(m_gl_widget), "focus_out_event", G_CALLBACK(XYWnd_Zoom_focusOut), this); +} + +void XYWnd::Zoom_End() +{ + m_zoom_started = false; + g_xywnd_freezePointer.unfreeze_pointer(m_parent != 0 ? m_parent : MainFrame_getWindow()); + g_signal_handler_disconnect(G_OBJECT(m_gl_widget), m_zoom_focusOut); +} + +// makes sure the selected brush or camera is in view +void XYWnd::PositionView(const Vector3& position) +{ + int nDim1 = (m_viewType == YZ) ? 1 : 0; + int nDim2 = (m_viewType == XY) ? 1 : 2; + + m_vOrigin[nDim1] = position[nDim1]; + m_vOrigin[nDim2] = position[nDim2]; + + updateModelview(); + + XYWnd_Update(*this); +} + +void XYWnd::SetViewType(VIEWTYPE viewType) +{ + m_viewType = viewType; + updateModelview(); + + if(m_parent != 0) + { + gtk_window_set_title(m_parent, ViewType_getTitle(m_viewType)); + } +} + + +inline WindowVector WindowVector_forInteger(int x, int y) +{ + return WindowVector(static_cast(x), static_cast(y)); +} + +void XYWnd::mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers) +{ + XY_MouseDown(static_cast(position.x()), static_cast(position.y()), buttons_for_button_and_modifiers(button, modifiers)); +} +void XYWnd::XY_MouseDown (int x, int y, unsigned int buttons) +{ + if(buttons == Move_buttons()) + { + Move_Begin(); + EntityCreate_MouseDown(x, y); + } + else if(buttons == Zoom_buttons()) + { + Zoom_Begin(); + } + else if(ClipMode() && buttons == Clipper_buttons()) + { + Clipper_OnLButtonDown(x, y); + } + else if(buttons == NewBrushDrag_buttons() && GlobalSelectionSystem().countSelected() == 0) + { + NewBrushDrag_Begin(x, y); + } + // control mbutton = move camera + else if (buttons == MoveCamera_buttons()) + { + XYWnd_PositionCamera(this, x, y, *g_pParentWnd->GetCamWnd()); + } + // mbutton = angle camera + else if(buttons == OrientCamera_buttons()) + { + XYWnd_OrientCamera(this, x, y, *g_pParentWnd->GetCamWnd()); + } + else + { + m_window_observer->onMouseDown(WindowVector_forInteger(x, y), button_for_flags(buttons), modifiers_for_flags(buttons)); + } +} + +void XYWnd::XY_MouseUp(int x, int y, unsigned int buttons) +{ + if(m_move_started) + { + Move_End(); + EntityCreate_MouseUp(x, y); + } + else if(m_zoom_started) + { + Zoom_End(); + } + else if (ClipMode() && buttons == Clipper_buttons()) + { + Clipper_OnLButtonUp(x, y); + } + else if (m_bNewBrushDrag) + { + m_bNewBrushDrag = false; + NewBrushDrag_End(x, y); + } + else + { + m_window_observer->onMouseUp(WindowVector_forInteger(x, y), button_for_flags(buttons), modifiers_for_flags(buttons)); + } +} + +void XYWnd::XY_MouseMoved (int x, int y, unsigned int buttons) +{ + // rbutton = drag xy origin + if(m_move_started) + { + } + // zoom in/out + else if(m_zoom_started) + { + } + + else if (ClipMode() && g_pMovingClip != 0) + { + Clipper_OnMouseMoved(x, y); + } + // lbutton without selection = drag new brush + else if (m_bNewBrushDrag) + { + NewBrushDrag(x, y); + } + + // control mbutton = move camera + else if (getButtonState() == MoveCamera_buttons()) + { + XYWnd_PositionCamera(this, x, y, *g_pParentWnd->GetCamWnd()); + } + + // mbutton = angle camera + else if (getButtonState() == OrientCamera_buttons()) + { + XYWnd_OrientCamera(this, x, y, *g_pParentWnd->GetCamWnd()); + } + + else + { + m_window_observer->onMouseMotion(WindowVector_forInteger(x, y), modifiers_for_flags(buttons)); + + m_mousePosition[0] = m_mousePosition[1] = m_mousePosition[2] = 0.0; + XY_ToPoint(x, y , m_mousePosition); + XY_SnapToGrid(m_mousePosition); + + StringOutputStream status(64); + status << "x:: " << FloatFormat(m_mousePosition[0], 6, 1) + << " y:: " << FloatFormat(m_mousePosition[1], 6, 1) + << " z:: " << FloatFormat(m_mousePosition[2], 6, 1); + g_pParentWnd->SetStatusText(g_pParentWnd->m_position_status, status.c_str()); + + if (g_bCrossHairs) + { + XYWnd_Update(*this); + } + + Clipper_Crosshair_OnMouseMoved(x, y); + } +} + +void XYWnd::EntityCreate_MouseDown(int x, int y) +{ + m_entityCreate = true; + m_entityCreate_x = x; + m_entityCreate_y = y; +} + +void XYWnd::EntityCreate_MouseMove(int x, int y) +{ + if(m_entityCreate && (m_entityCreate_x != x || m_entityCreate_y != y)) + { + m_entityCreate = false; + } +} + +void XYWnd::EntityCreate_MouseUp(int x, int y) +{ + if(m_entityCreate) + { + m_entityCreate = false; + OnContextMenu(); + } +} + +inline float screen_normalised(int pos, unsigned int size) +{ + return ((2.0f * pos) / size) - 1.0f; +} + +inline float normalised_to_world(float normalised, float world_origin, float normalised2world_scale) +{ + return world_origin + normalised * normalised2world_scale; +} + + +// TTimo: watch it, this doesn't init one of the 3 coords +void XYWnd::XY_ToPoint (int x, int y, Vector3& point) +{ + float normalised2world_scale_x = m_nWidth / 2 / m_fScale; + float normalised2world_scale_y = m_nHeight / 2 / m_fScale; + if (m_viewType == XY) + { + point[0] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[0], normalised2world_scale_x); + point[1] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[1], normalised2world_scale_y); + } + else if (m_viewType == YZ) + { + point[1] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[1], normalised2world_scale_x); + point[2] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[2], normalised2world_scale_y); + } + else + { + point[0] = normalised_to_world(screen_normalised(x, m_nWidth), m_vOrigin[0], normalised2world_scale_x); + point[2] = normalised_to_world(-screen_normalised(y, m_nHeight), m_vOrigin[2], normalised2world_scale_y); + } +} + +void XYWnd::XY_SnapToGrid(Vector3& point) +{ + if (m_viewType == XY) + { + point[0] = float_snapped(point[0], GetSnapGridSize()); + point[1] = float_snapped(point[1], GetSnapGridSize()); + } + else if (m_viewType == YZ) + { + point[1] = float_snapped(point[1], GetSnapGridSize()); + point[2] = float_snapped(point[2], GetSnapGridSize()); + } + else + { + point[0] = float_snapped(point[0], GetSnapGridSize()); + point[2] = float_snapped(point[2], GetSnapGridSize()); + } +} + +void XYWnd::XY_LoadBackgroundImage(const char *name) +{ + const char* relative = path_make_relative(name, GlobalFileSystem().findRoot(name)); + if (relative == name) + globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n"; + + char fileNameWithoutExt[512]; + strncpy(fileNameWithoutExt, relative, sizeof(fileNameWithoutExt) - 1); + fileNameWithoutExt[512 - 1] = '\0'; + fileNameWithoutExt[strlen(fileNameWithoutExt) - 4] = '\0'; + + Image *image = QERApp_LoadImage(0, fileNameWithoutExt); + if (!image) { + globalOutputStream() << "Could not load texture " << fileNameWithoutExt << "\n"; + return; + } + g_pParentWnd->ActiveXY()->m_tex = (qtexture_t*)malloc(sizeof(qtexture_t)); + LoadTextureRGBA(g_pParentWnd->ActiveXY()->XYWnd::m_tex, image->getRGBAPixels(), image->getWidth(), image->getHeight()); + globalOutputStream() << "Loaded background texture " << relative << "\n"; + g_pParentWnd->ActiveXY()->m_backgroundActivated = true; + + int m_ix, m_iy; + switch(g_pParentWnd->ActiveXY()->m_viewType) + { + case XY: + m_ix = 0; + m_iy = 1; + break; + case XZ: + m_ix = 0; + m_iy = 2; + break; + case YZ: + m_ix = 1; + m_iy = 2; + break; + } + + Vector3 min, max; + Select_GetBounds(min, max); + g_pParentWnd->ActiveXY()->m_xmin = min[m_ix]; + g_pParentWnd->ActiveXY()->m_ymin = min[m_iy]; + g_pParentWnd->ActiveXY()->m_xmax = max[m_ix]; + g_pParentWnd->ActiveXY()->m_ymax = max[m_iy]; +} + +void XYWnd::XY_DisableBackground (void) +{ + g_pParentWnd->ActiveXY()->m_backgroundActivated = false; + if (g_pParentWnd->ActiveXY()->m_tex) + free(g_pParentWnd->ActiveXY()->m_tex); + g_pParentWnd->ActiveXY()->m_tex = NULL; +} + +void WXY_BackgroundSelect(void) +{ + bool brushesSelected = Scene_countSelectedBrushes(GlobalSceneGraph()) != 0; + if (!brushesSelected) { + gtk_MessageBox(0, "You have to select some brushes to get the bounding box for.\n", + "No selection", eMB_OK, eMB_ICONERROR); + return; + } + + const char *filename = file_dialog(GTK_WIDGET(MainFrame_getWindow()), TRUE, "Background Image", NULL, NULL); + g_pParentWnd->ActiveXY()->XY_DisableBackground(); + if (filename) + g_pParentWnd->ActiveXY()->XY_LoadBackgroundImage(filename); +} + +/* +============================================================================ + +DRAWING + +============================================================================ +*/ + +/* +============== +XY_DrawGrid +============== +*/ + +double two_to_the_power(int power) +{ + return pow(2.0f, power); +} + +void XYWnd::XY_DrawAxis(void) +{ + if ( g_xywindow_globals_private.show_axis) { + const char g_AxisName[3] = { 'X', 'Y', 'Z' }; + const int nDim1 = (m_viewType == YZ) ? 1 : 0; + const int nDim2 = (m_viewType == XY) ? 1 : 2; + const int w = (m_nWidth / 2 / m_fScale); + const int h = (m_nHeight / 2 / m_fScale); + + const Vector3& colourX = (m_viewType == YZ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorX; + const Vector3& colourY = (m_viewType == XY) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorZ; + + // draw two lines with corresponding axis colors to highlight current view + // horizontal line: nDim1 color + glLineWidth(2); + glBegin( GL_LINES ); + glColor3fv (vector3_to_array(colourX)); + glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale ); + glVertex2f( m_vOrigin[nDim1] - w + 65 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale ); + glVertex2f( 0, 0 ); + glVertex2f( 32 / m_fScale, 0 ); + glColor3fv (vector3_to_array(colourY)); + glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale ); + glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale ); + glVertex2f( 0, 0 ); + glVertex2f( 0, 32 / m_fScale ); + glEnd(); + glLineWidth(1); + // now print axis symbols + glColor3fv (vector3_to_array(colourX)); + glRasterPos2f ( m_vOrigin[nDim1] - w + 55 / m_fScale, m_vOrigin[nDim2] + h - 55 / m_fScale ); + GlobalOpenGL().drawChar(g_AxisName[nDim1]); + glRasterPos2f (28 / m_fScale, -10 / m_fScale ); + GlobalOpenGL().drawChar(g_AxisName[nDim1]); + glColor3fv (vector3_to_array(colourY)); + glRasterPos2f ( m_vOrigin[nDim1] - w + 25 / m_fScale, m_vOrigin[nDim2] + h - 30 / m_fScale ); + GlobalOpenGL().drawChar(g_AxisName[nDim2]); + glRasterPos2f ( -10 / m_fScale, 28 / m_fScale ); + GlobalOpenGL().drawChar(g_AxisName[nDim2]); + } +} + +void XYWnd::XY_DrawBackground(void) +{ + glPushAttrib(GL_ALL_ATTRIB_BITS); + + glEnable(GL_TEXTURE_2D); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); + + glPolygonMode(GL_FRONT, GL_FILL); + + glBindTexture(GL_TEXTURE_2D, m_tex->texture_number); + glBegin(GL_QUADS); + + glColor4f(1.0, 1.0, 1.0, m_alpha); + glTexCoord2f(0.0, 1.0); + glVertex2f(m_xmin, m_ymin); + + glTexCoord2f(1.0, 1.0); + glVertex2f(m_xmax, m_ymin); + + glTexCoord2f(1.0, 0.0); + glVertex2f(m_xmax, m_ymax); + + glTexCoord2f(0.0, 0.0); + glVertex2f(m_xmin, m_ymax); + + glEnd(); + glBindTexture(GL_TEXTURE_2D, 0); + + glPopAttrib(); +} + +void XYWnd::XY_DrawGrid(void) { + float x, y, xb, xe, yb, ye; + float w, h, a; + char text[32]; + float step, minor_step, stepx, stepy; + step = minor_step = stepx = stepy = GetGridSize(); + + int minor_power = Grid_getPower(); + int mask; + + while ((minor_step * m_fScale) <= 4.0f) { // make sure minor grid spacing is at least 4 pixels on the screen + ++minor_power; + minor_step *= 2; + } + int power = minor_power; + while ((power % 3) != 0 || (step * m_fScale) <= 32.0f) { // make sure major grid spacing is at least 32 pixels on the screen + ++power; + step = float(two_to_the_power(power)); + } + mask = (1 << (power - minor_power)) - 1; + while ((stepx * m_fScale) <= 32.0f) // text step x must be at least 32 + stepx *= 2; + while ((stepy * m_fScale) <= 32.0f) // text step y must be at least 32 + stepy *= 2; + + a = ((GetSnapGridSize() > 0.0f) ? 1.0f : 0.3f); + + glDisable(GL_TEXTURE_2D); + glDisable(GL_TEXTURE_1D); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + glLineWidth(1); + + w = (m_nWidth / 2 / m_fScale); + h = (m_nHeight / 2 / m_fScale); + + const int nDim1 = (m_viewType == YZ) ? 1 : 0; + const int nDim2 = (m_viewType == XY) ? 1 : 2; + + xb = m_vOrigin[nDim1] - w; + if (xb < region_mins[nDim1]) + xb = region_mins[nDim1]; + xb = step * floor (xb / step); + + xe = m_vOrigin[nDim1] + w; + if (xe > region_maxs[nDim1]) + xe = region_maxs[nDim1]; + xe = step * ceil (xe / step); + + yb = m_vOrigin[nDim2] - h; + if (yb < region_mins[nDim2]) + yb = region_mins[nDim2]; + yb = step * floor (yb / step); + + ye = m_vOrigin[nDim2] + h; + if (ye > region_maxs[nDim2]) + ye = region_maxs[nDim2]; + ye = step * ceil (ye / step); + +#define COLORS_DIFFER(a,b) \ + ((a)[0] != (b)[0] || \ + (a)[1] != (b)[1] || \ + (a)[2] != (b)[2]) + + // djbob + // draw minor blocks + if (g_xywindow_globals_private.d_showgrid || a < 1.0f) { + if(a < 1.0f) + glEnable(GL_BLEND); + + if (COLORS_DIFFER(g_xywindow_globals.color_gridminor, g_xywindow_globals.color_gridback)) { + glColor4fv(vector4_to_array(Vector4(g_xywindow_globals.color_gridminor, a))); + + glBegin (GL_LINES); + int i = 0; + for (x = xb ; x < xe ; x += minor_step, ++i) { + if ((i & mask) != 0) { + glVertex2f (x, yb); + glVertex2f (x, ye); + } + } + i = 0; + for (y = yb ; y < ye ; y += minor_step, ++i) { + if ((i & mask) != 0) { + glVertex2f (xb, y); + glVertex2f (xe, y); + } + } + glEnd(); + } + + // draw major blocks + if (COLORS_DIFFER(g_xywindow_globals.color_gridmajor, g_xywindow_globals.color_gridminor)) { + glColor4fv(vector4_to_array(Vector4(g_xywindow_globals.color_gridmajor, a))); + + glBegin (GL_LINES); + for (x = xb ; x <= xe ; x += step) { + glVertex2f (x, yb); + glVertex2f (x, ye); + } + for (y = yb ; y <= ye ; y += step) { + glVertex2f (xb, y); + glVertex2f (xe, y); + } + glEnd(); + } + + if(a < 1.0f) + glDisable(GL_BLEND); + } + + // draw coordinate text if needed + if ( g_xywindow_globals_private.show_coordinates) { + glColor4fv(vector4_to_array(Vector4(g_xywindow_globals.color_gridtext, 1.0f))); + float offx = m_vOrigin[nDim2] + h - (4 + GlobalOpenGL().m_font->getPixelAscent()) / m_fScale; + float offy = m_vOrigin[nDim1] - w + 4 / m_fScale; + for (x = xb - fmod(xb, stepx); x <= xe ; x += stepx) { + glRasterPos2f (x, offx); + sprintf (text, "%g", x); + GlobalOpenGL().drawString(text); + } + for (y = yb - fmod(yb, stepy); y <= ye ; y += stepy) { + glRasterPos2f (offy, y); + sprintf (text, "%g", y); + GlobalOpenGL().drawString(text); + } + + if (Active()) + glColor3fv(vector3_to_array(g_xywindow_globals.color_viewname)); + + // we do this part (the old way) only if show_axis is disabled + if (!g_xywindow_globals_private.show_axis) { + glRasterPos2f ( m_vOrigin[nDim1] - w + 35 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale ); + + GlobalOpenGL().drawString(ViewType_getTitle(m_viewType)); + } + } + + XYWnd::XY_DrawAxis(); + + // show current work zone? + // the work zone is used to place dropped points and brushes + if (g_xywindow_globals_private.d_show_work) { + glColor4f( 1.0f, 0.0f, 0.0f, 1.0f ); + glBegin( GL_LINES ); + glVertex2f( xb, Select_getWorkZone().d_work_min[nDim2] ); + glVertex2f( xe, Select_getWorkZone().d_work_min[nDim2] ); + glVertex2f( xb, Select_getWorkZone().d_work_max[nDim2] ); + glVertex2f( xe, Select_getWorkZone().d_work_max[nDim2] ); + glVertex2f( Select_getWorkZone().d_work_min[nDim1], yb ); + glVertex2f( Select_getWorkZone().d_work_min[nDim1], ye ); + glVertex2f( Select_getWorkZone().d_work_max[nDim1], yb ); + glVertex2f( Select_getWorkZone().d_work_max[nDim1], ye ); + glEnd(); + } +} + +/* +============== +XY_DrawBlockGrid +============== +*/ +void XYWnd::XY_DrawBlockGrid() +{ + if(Map_FindWorldspawn(g_map) == 0) + { + return; + } + const char *value = Node_getEntity(*Map_GetWorldspawn(g_map))->getKeyValue("_blocksize" ); + if (strlen(value)) + sscanf( value, "%i", &g_xywindow_globals_private.blockSize ); + + if (!g_xywindow_globals_private.blockSize || g_xywindow_globals_private.blockSize > 65536 || g_xywindow_globals_private.blockSize < 1024) + // don't use custom blocksize if it is less than the default, or greater than the maximum world coordinate + g_xywindow_globals_private.blockSize = 1024; + + float x, y, xb, xe, yb, ye; + float w, h; + char text[32]; + + glDisable(GL_TEXTURE_2D); + glDisable(GL_TEXTURE_1D); + glDisable(GL_DEPTH_TEST); + glDisable(GL_BLEND); + + w = (m_nWidth / 2 / m_fScale); + h = (m_nHeight / 2 / m_fScale); + + int nDim1 = (m_viewType == YZ) ? 1 : 0; + int nDim2 = (m_viewType == XY) ? 1 : 2; + + xb = m_vOrigin[nDim1] - w; + if (xb < region_mins[nDim1]) + xb = region_mins[nDim1]; + xb = static_cast(g_xywindow_globals_private.blockSize * floor (xb/g_xywindow_globals_private.blockSize)); + + xe = m_vOrigin[nDim1] + w; + if (xe > region_maxs[nDim1]) + xe = region_maxs[nDim1]; + xe = static_cast(g_xywindow_globals_private.blockSize * ceil (xe/g_xywindow_globals_private.blockSize)); + + yb = m_vOrigin[nDim2] - h; + if (yb < region_mins[nDim2]) + yb = region_mins[nDim2]; + yb = static_cast(g_xywindow_globals_private.blockSize * floor (yb/g_xywindow_globals_private.blockSize)); + + ye = m_vOrigin[nDim2] + h; + if (ye > region_maxs[nDim2]) + ye = region_maxs[nDim2]; + ye = static_cast(g_xywindow_globals_private.blockSize * ceil (ye/g_xywindow_globals_private.blockSize)); + + // draw major blocks + + glColor3fv(vector3_to_array(g_xywindow_globals.color_gridblock)); + glLineWidth (2); + + glBegin (GL_LINES); + + for (x=xb ; x<=xe ; x+=g_xywindow_globals_private.blockSize) + { + glVertex2f (x, yb); + glVertex2f (x, ye); + } + + if (m_viewType == XY) + { + for (y=yb ; y<=ye ; y+=g_xywindow_globals_private.blockSize) + { + glVertex2f (xb, y); + glVertex2f (xe, y); + } + } + + glEnd(); + glLineWidth (1); + + // draw coordinate text if needed + + if (m_viewType == XY && m_fScale > .1) + { + for (x=xb ; x(fov*cos(a+c_pi/4)), y + static_cast(fov*sin(a+c_pi/4)), 0); + glVertex3f (x, y, 0); + glVertex3f (x + static_cast(fov*cos(a-c_pi/4)), y + static_cast(fov*sin(a-c_pi/4)), 0); + glEnd(); + +} + + +float Betwixt(float f1, float f2) +{ + if (f1 > f2) + return f2 + ((f1 - f2) / 2); + else + return f1 + ((f2 - f1) / 2); +} + + +// can be greatly simplified but per usual i am in a hurry +// which is not an excuse, just a fact +void XYWnd::PaintSizeInfo(int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds) +{ + if(vector3_equal(vMinBounds, vMaxBounds)) + { + return; + } + const char* g_pDimStrings[] = {"x:", "y:", "z:"}; + typedef const char* OrgStrings[2]; + const OrgStrings g_pOrgStrings[] = { { "x:", "y:", }, { "x:", "z:", }, { "y:", "z:", } }; + + Vector3 vSize(vector3_subtracted(vMaxBounds, vMinBounds)); + + glColor3f(g_xywindow_globals.color_selbrushes[0] * .65f, + g_xywindow_globals.color_selbrushes[1] * .65f, + g_xywindow_globals.color_selbrushes[2] * .65f); + + StringOutputStream dimensions(16); + + if (m_viewType == XY) + { + glBegin (GL_LINES); + + glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale, 0.0f); + glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); + + glVertex3f(vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); + glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); + + glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale, 0.0f); + glVertex3f(vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f); + + + glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, vMinBounds[nDim2], 0.0f); + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2], 0.0f); + + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2], 0.0f); + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2], 0.0f); + + glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, vMaxBounds[nDim2], 0.0f); + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2], 0.0f); + + glEnd(); + + glRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), vMinBounds[nDim2] - 20.0f / m_fScale, 0.0f); + dimensions << g_pDimStrings[nDim1] << vSize[nDim1]; + GlobalOpenGL().drawString(dimensions.c_str()); + dimensions.clear(); + + glRasterPos3f (vMaxBounds[nDim1] + 16.0f / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2]), 0.0f); + dimensions << g_pDimStrings[nDim2] << vSize[nDim2]; + GlobalOpenGL().drawString(dimensions.c_str()); + dimensions.clear(); + + glRasterPos3f (vMinBounds[nDim1] + 4, vMaxBounds[nDim2] + 8 / m_fScale, 0.0f); + dimensions << "(" << g_pOrgStrings[0][0] << vMinBounds[nDim1] << " " << g_pOrgStrings[0][1] << vMaxBounds[nDim2] << ")"; + GlobalOpenGL().drawString(dimensions.c_str()); + } + else if (m_viewType == XZ) + { + glBegin (GL_LINES); + + glVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 6.0f / m_fScale); + glVertex3f(vMinBounds[nDim1], 0, vMinBounds[nDim2] - 10.0f / m_fScale); + + glVertex3f(vMinBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale); + glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale); + + glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 6.0f / m_fScale); + glVertex3f(vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale); + + + glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, 0,vMinBounds[nDim2]); + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMinBounds[nDim2]); + + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMinBounds[nDim2]); + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMaxBounds[nDim2]); + + glVertex3f(vMaxBounds[nDim1] + 6.0f / m_fScale, 0,vMaxBounds[nDim2]); + glVertex3f(vMaxBounds[nDim1] + 10.0f / m_fScale, 0,vMaxBounds[nDim2]); + + glEnd(); + + glRasterPos3f (Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), 0, vMinBounds[nDim2] - 20.0f / m_fScale); + dimensions << g_pDimStrings[nDim1] << vSize[nDim1]; + GlobalOpenGL().drawString(dimensions.c_str()); + dimensions.clear(); + + glRasterPos3f (vMaxBounds[nDim1] + 16.0f / m_fScale, 0, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2])); + dimensions << g_pDimStrings[nDim2] << vSize[nDim2]; + GlobalOpenGL().drawString(dimensions.c_str()); + dimensions.clear(); + + glRasterPos3f (vMinBounds[nDim1] + 4, 0, vMaxBounds[nDim2] + 8 / m_fScale); + dimensions << "(" << g_pOrgStrings[1][0] << vMinBounds[nDim1] << " " << g_pOrgStrings[1][1] << vMaxBounds[nDim2] << ")"; + GlobalOpenGL().drawString(dimensions.c_str()); + } + else + { + glBegin (GL_LINES); + + glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale); + glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); + + glVertex3f(0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); + glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); + + glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f / m_fScale); + glVertex3f(0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale); + + + glVertex3f(0, vMaxBounds[nDim1] + 6.0f / m_fScale, vMinBounds[nDim2]); + glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2]); + + glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMinBounds[nDim2]); + glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2]); + + glVertex3f(0, vMaxBounds[nDim1] + 6.0f / m_fScale, vMaxBounds[nDim2]); + glVertex3f(0, vMaxBounds[nDim1] + 10.0f / m_fScale, vMaxBounds[nDim2]); + + glEnd(); + + glRasterPos3f (0, Betwixt(vMinBounds[nDim1], vMaxBounds[nDim1]), vMinBounds[nDim2] - 20.0f / m_fScale); + dimensions << g_pDimStrings[nDim1] << vSize[nDim1]; + GlobalOpenGL().drawString(dimensions.c_str()); + dimensions.clear(); + + glRasterPos3f (0, vMaxBounds[nDim1] + 16.0f / m_fScale, Betwixt(vMinBounds[nDim2], vMaxBounds[nDim2])); + dimensions << g_pDimStrings[nDim2] << vSize[nDim2]; + GlobalOpenGL().drawString(dimensions.c_str()); + dimensions.clear(); + + glRasterPos3f (0, vMinBounds[nDim1] + 4.0f, vMaxBounds[nDim2] + 8 / m_fScale); + dimensions << "(" << g_pOrgStrings[2][0] << vMinBounds[nDim1] << " " << g_pOrgStrings[2][1] << vMaxBounds[nDim2] << ")"; + GlobalOpenGL().drawString(dimensions.c_str()); + } +} + +class XYRenderer: public Renderer +{ + struct state_type + { + state_type() : + m_highlight(0), + m_state(0) + { + } + unsigned int m_highlight; + Shader* m_state; + }; +public: + XYRenderer(RenderStateFlags globalstate, Shader* selected) : + m_globalstate(globalstate), + m_state_selected(selected) + { + ASSERT_NOTNULL(selected); + m_state_stack.push_back(state_type()); + } + + void SetState(Shader* state, EStyle style) + { + ASSERT_NOTNULL(state); + if(style == eWireframeOnly) + m_state_stack.back().m_state = state; + } + const EStyle getStyle() const + { + return eWireframeOnly; + } + void PushState() + { + m_state_stack.push_back(m_state_stack.back()); + } + void PopState() + { + ASSERT_MESSAGE(!m_state_stack.empty(), "popping empty stack"); + m_state_stack.pop_back(); + } + void Highlight(EHighlightMode mode, bool bEnable = true) + { + (bEnable) + ? m_state_stack.back().m_highlight |= mode + : m_state_stack.back().m_highlight &= ~mode; + } + void addRenderable(const OpenGLRenderable& renderable, const Matrix4& localToWorld) + { + if(m_state_stack.back().m_highlight & ePrimitive) + { + m_state_selected->addRenderable(renderable, localToWorld); + } + else + { + m_state_stack.back().m_state->addRenderable(renderable, localToWorld); + } + } + + void render(const Matrix4& modelview, const Matrix4& projection) + { + GlobalShaderCache().render(m_globalstate, modelview, projection); + } +private: + std::vector m_state_stack; + RenderStateFlags m_globalstate; + Shader* m_state_selected; +}; + +void XYWnd::updateProjection() +{ + m_projection[0] = 1.0f / static_cast(m_nWidth / 2); + m_projection[5] = 1.0f / static_cast(m_nHeight / 2); + m_projection[10] = 1.0f / (g_MaxWorldCoord * m_fScale); + + m_projection[12] = 0.0f; + m_projection[13] = 0.0f; + m_projection[14] = -1.0f; + + m_projection[1] = + m_projection[2] = + m_projection[3] = + + m_projection[4] = + m_projection[6] = + m_projection[7] = + + m_projection[8] = + m_projection[9] = + m_projection[11] = 0.0f; + + m_projection[15] = 1.0f; + + m_view.Construct(m_projection, m_modelview, m_nWidth, m_nHeight); +} + +// note: modelview matrix must have a uniform scale, otherwise strange things happen when rendering the rotation manipulator. +void XYWnd::updateModelview() +{ + int nDim1 = (m_viewType == YZ) ? 1 : 0; + int nDim2 = (m_viewType == XY) ? 1 : 2; + + // translation + m_modelview[12] = -m_vOrigin[nDim1] * m_fScale; + m_modelview[13] = -m_vOrigin[nDim2] * m_fScale; + m_modelview[14] = g_MaxWorldCoord * m_fScale; + + // axis base + switch(m_viewType) + { + case XY: + m_modelview[0] = m_fScale; + m_modelview[1] = 0; + m_modelview[2] = 0; + + m_modelview[4] = 0; + m_modelview[5] = m_fScale; + m_modelview[6] = 0; + + m_modelview[8] = 0; + m_modelview[9] = 0; + m_modelview[10] = -m_fScale; + break; + case XZ: + m_modelview[0] = m_fScale; + m_modelview[1] = 0; + m_modelview[2] = 0; + + m_modelview[4] = 0; + m_modelview[5] = 0; + m_modelview[6] = m_fScale; + + m_modelview[8] = 0; + m_modelview[9] = m_fScale; + m_modelview[10] = 0; + break; + case YZ: + m_modelview[0] = 0; + m_modelview[1] = 0; + m_modelview[2] = -m_fScale; + + m_modelview[4] = m_fScale; + m_modelview[5] = 0; + m_modelview[6] = 0; + + m_modelview[8] = 0; + m_modelview[9] = m_fScale; + m_modelview[10] = 0; + break; + } + + m_modelview[3] = m_modelview[7] = m_modelview[11] = 0; + m_modelview[15] = 1; + + m_view.Construct(m_projection, m_modelview, m_nWidth, m_nHeight); +} + +/* +============== +XY_Draw +============== +*/ + +//#define DBG_SCENEDUMP + +void XYWnd::XY_Draw() +{ + // + // clear + // + glViewport(0, 0, m_nWidth, m_nHeight); + glClearColor (g_xywindow_globals.color_gridback[0], + g_xywindow_globals.color_gridback[1], + g_xywindow_globals.color_gridback[2],0); + + glClear(GL_COLOR_BUFFER_BIT); + + // + // set up viewpoint + // + + glMatrixMode(GL_PROJECTION); + glLoadMatrixf(reinterpret_cast(&m_projection)); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glScalef(m_fScale, m_fScale, 1); + int nDim1 = (m_viewType == YZ) ? 1 : 0; + int nDim2 = (m_viewType == XY) ? 1 : 2; + glTranslatef(-m_vOrigin[nDim1], -m_vOrigin[nDim2], 0); + + glDisable (GL_LINE_STIPPLE); + glLineWidth(1); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_NORMAL_ARRAY); + glDisableClientState(GL_COLOR_ARRAY); + glDisable(GL_TEXTURE_2D); + glDisable(GL_LIGHTING); + glDisable(GL_COLOR_MATERIAL); + glDisable(GL_DEPTH_TEST); + + if (m_backgroundActivated) + XY_DrawBackground(); + XY_DrawGrid(); + + if ( g_xywindow_globals_private.show_blocks) + XY_DrawBlockGrid(); + + glLoadMatrixf(reinterpret_cast(&m_modelview)); + + unsigned int globalstate = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH; + if(!g_xywindow_globals.m_bNoStipple) + { + globalstate |= RENDER_LINESTIPPLE; + } + + { + XYRenderer renderer(globalstate, m_state_selected); + + Scene_Render(renderer, m_view); + + GlobalOpenGL_debugAssertNoErrors(); + renderer.render(m_modelview, m_projection); + GlobalOpenGL_debugAssertNoErrors(); + } + + glDepthMask(GL_FALSE); + + GlobalOpenGL_debugAssertNoErrors(); + + glLoadMatrixf(reinterpret_cast(&m_modelview)); + + GlobalOpenGL_debugAssertNoErrors(); + glDisable(GL_LINE_STIPPLE); + GlobalOpenGL_debugAssertNoErrors(); + glLineWidth(1); + GlobalOpenGL_debugAssertNoErrors(); + if(GlobalOpenGL().GL_1_3()) + { + glActiveTexture(GL_TEXTURE0); + glClientActiveTexture(GL_TEXTURE0); + } + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + GlobalOpenGL_debugAssertNoErrors(); + glDisableClientState(GL_NORMAL_ARRAY); + GlobalOpenGL_debugAssertNoErrors(); + glDisableClientState(GL_COLOR_ARRAY); + GlobalOpenGL_debugAssertNoErrors(); + glDisable(GL_TEXTURE_2D); + GlobalOpenGL_debugAssertNoErrors(); + glDisable(GL_LIGHTING); + GlobalOpenGL_debugAssertNoErrors(); + glDisable(GL_COLOR_MATERIAL); + GlobalOpenGL_debugAssertNoErrors(); + + GlobalOpenGL_debugAssertNoErrors(); + + + // size info + if(g_xywindow_globals_private.m_bSizePaint && GlobalSelectionSystem().countSelected() != 0) + { + Vector3 min, max; + Select_GetBounds(min, max); + PaintSizeInfo(nDim1, nDim2, min, max); + } + + if (g_bCrossHairs) + { + glColor4f(0.2f, 0.9f, 0.2f, 0.8f); + glBegin (GL_LINES); + if (m_viewType == XY) + { + glVertex2f(2.0f * g_MinWorldCoord, m_mousePosition[1]); + glVertex2f(2.0f * g_MaxWorldCoord, m_mousePosition[1]); + glVertex2f(m_mousePosition[0], 2.0f * g_MinWorldCoord); + glVertex2f(m_mousePosition[0], 2.0f * g_MaxWorldCoord); + } + else if (m_viewType == YZ) + { + glVertex3f(m_mousePosition[0], 2.0f * g_MinWorldCoord, m_mousePosition[2]); + glVertex3f(m_mousePosition[0], 2.0f * g_MaxWorldCoord, m_mousePosition[2]); + glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord); + glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord); + } + else + { + glVertex3f (2.0f * g_MinWorldCoord, m_mousePosition[1], m_mousePosition[2]); + glVertex3f (2.0f * g_MaxWorldCoord, m_mousePosition[1], m_mousePosition[2]); + glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord); + glVertex3f(m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord); + } + glEnd(); + } + + if (ClipMode()) + { + GlobalClipPoints_Draw(m_fScale); + } + + GlobalOpenGL_debugAssertNoErrors(); + + // reset modelview + glLoadIdentity(); + glScalef(m_fScale, m_fScale, 1); + glTranslatef(-m_vOrigin[nDim1], -m_vOrigin[nDim2], 0); + + DrawCameraIcon (Camera_getOrigin(*g_pParentWnd->GetCamWnd()), Camera_getAngles(*g_pParentWnd->GetCamWnd())); + + Feedback_draw2D( m_viewType ); + + if (g_xywindow_globals_private.show_outline) + { + if (Active()) + { + glMatrixMode (GL_PROJECTION); + glLoadIdentity(); + glOrtho (0, m_nWidth, 0, m_nHeight, 0, 1); + + glMatrixMode (GL_MODELVIEW); + glLoadIdentity(); + + // four view mode doesn't colorize + if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit) + glColor3fv(vector3_to_array(g_xywindow_globals.color_viewname)); + else + { + switch(m_viewType) + { + case YZ: + glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorX)); + break; + case XZ: + glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorY)); + break; + case XY: + glColor3fv(vector3_to_array(g_xywindow_globals.AxisColorZ)); + break; + } + } + glBegin (GL_LINE_LOOP); + glVertex2f (0.5, 0.5); + glVertex2f (m_nWidth-0.5, 1); + glVertex2f (m_nWidth-0.5, m_nHeight-0.5); + glVertex2f (0.5, m_nHeight-0.5); + glEnd(); + } + } + + GlobalOpenGL_debugAssertNoErrors(); + + glFinish(); +} + +void XYWnd_MouseToPoint(XYWnd* xywnd, int x, int y, Vector3& point) +{ + xywnd->XY_ToPoint(x, y, point); + xywnd->XY_SnapToGrid(point); + + int nDim = (xywnd->GetViewType() == XY) ? 2 : (xywnd->GetViewType() == YZ) ? 0 : 1; + float fWorkMid = float_mid(Select_getWorkZone().d_work_min[nDim], Select_getWorkZone().d_work_max[nDim]); + point[nDim] = float_snapped(fWorkMid, GetGridSize()); +} + +void XYWnd::OnEntityCreate (const char* item) +{ + StringOutputStream command; + command << "entityCreate -class " << item; + UndoableCommand undo(command.c_str()); + Vector3 point; + XYWnd_MouseToPoint(this, m_entityCreate_x, m_entityCreate_y, point); + Entity_createFromSelection(item, point); +} + + + +void GetFocusPosition(Vector3& position) +{ + if(GlobalSelectionSystem().countSelected() != 0) + { + Select_GetMid(position); + } + else + { + position = Camera_getOrigin(*g_pParentWnd->GetCamWnd()); + } +} + +void XYWnd_Focus(XYWnd* xywnd) +{ + Vector3 position; + GetFocusPosition(position); + xywnd->PositionView(position); +} + +void XY_Split_Focus() +{ + Vector3 position; + GetFocusPosition(position); + if(g_pParentWnd->GetXYWnd()) + g_pParentWnd->GetXYWnd()->PositionView(position); + if(g_pParentWnd->GetXZWnd()) + g_pParentWnd->GetXZWnd()->PositionView(position); + if(g_pParentWnd->GetYZWnd()) + g_pParentWnd->GetYZWnd()->PositionView(position); +} + +void XY_Focus() +{ + if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit) + { + // cannot do this in a split window + // do something else that the user may want here + XY_Split_Focus(); + return; + } + + XYWnd* xywnd = g_pParentWnd->GetXYWnd(); + XYWnd_Focus(xywnd); +} + +void XY_Top() +{ + if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) + { + // cannot do this in a split window + // do something else that the user may want here + XY_Split_Focus(); + return; + } + + XYWnd* xywnd = g_pParentWnd->GetXYWnd(); + xywnd->SetViewType(XY); + XYWnd_Focus(xywnd); +} + +void XY_Side() +{ + if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) + { + // cannot do this in a split window + // do something else that the user may want here + XY_Split_Focus(); + return; + } + + XYWnd* xywnd = g_pParentWnd->GetXYWnd(); + xywnd->SetViewType(XZ); + XYWnd_Focus(xywnd); +} + +void XY_Front() +{ + if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) + { + // cannot do this in a split window + // do something else that the user may want here + XY_Split_Focus(); + return; + } + + XYWnd* xywnd = g_pParentWnd->GetXYWnd(); + xywnd->SetViewType(YZ); + XYWnd_Focus(xywnd); +} + +void XY_Next() +{ + if (g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating) + { + // cannot do this in a split window + // do something else that the user may want here + XY_Split_Focus(); + return; + } + + XYWnd* xywnd = g_pParentWnd->GetXYWnd(); + if (xywnd->GetViewType() == XY) + xywnd->SetViewType(XZ); + else if (xywnd->GetViewType() == XZ) + xywnd->SetViewType(YZ); + else + xywnd->SetViewType(XY); + XYWnd_Focus(xywnd); +} + +void XY_Zoom100() +{ + if (g_pParentWnd->GetXYWnd()) + g_pParentWnd->GetXYWnd()->SetScale(1); + if (g_pParentWnd->GetXZWnd()) + g_pParentWnd->GetXZWnd()->SetScale(1); + if (g_pParentWnd->GetYZWnd()) + g_pParentWnd->GetYZWnd()->SetScale(1); +} + +void XY_ZoomIn() +{ + XYWnd_ZoomIn(g_pParentWnd->ActiveXY()); +} + +// NOTE: the zoom out factor is 4/5, we could think about customizing it +// we don't go below a zoom factor corresponding to 10% of the max world size +// (this has to be computed against the window size) +void XY_ZoomOut() +{ + XYWnd_ZoomOut(g_pParentWnd->ActiveXY()); +} + + + +void ToggleShowCrosshair() +{ + g_bCrossHairs ^= 1; + XY_UpdateAllWindows(); +} + +void ToggleShowSizeInfo() +{ + g_xywindow_globals_private.m_bSizePaint = !g_xywindow_globals_private.m_bSizePaint; + XY_UpdateAllWindows(); +} + +void ToggleShowGrid() +{ + g_xywindow_globals_private.d_showgrid = !g_xywindow_globals_private.d_showgrid; + XY_UpdateAllWindows(); +} + +ToggleShown g_xy_top_shown(true); + +void XY_Top_Shown_Construct(GtkWindow* parent) +{ + g_xy_top_shown.connect(GTK_WIDGET(parent)); +} + +ToggleShown g_yz_side_shown(false); + +void YZ_Side_Shown_Construct(GtkWindow* parent) +{ + g_yz_side_shown.connect(GTK_WIDGET(parent)); +} + +ToggleShown g_xz_front_shown(false); + +void XZ_Front_Shown_Construct(GtkWindow* parent) +{ + g_xz_front_shown.connect(GTK_WIDGET(parent)); +} + + +class EntityClassMenu : public ModuleObserver +{ + std::size_t m_unrealised; +public: + EntityClassMenu() : m_unrealised(1) + { + } + void realise() + { + if(--m_unrealised == 0) + { + } + } + void unrealise() + { + if(++m_unrealised == 1) + { + if(XYWnd::m_mnuDrop != 0) + { + gtk_widget_destroy(GTK_WIDGET(XYWnd::m_mnuDrop)); + XYWnd::m_mnuDrop = 0; + } + } + } +}; + +EntityClassMenu g_EntityClassMenu; + + + + +void ShowNamesToggle() +{ + GlobalEntityCreator().setShowNames(!GlobalEntityCreator().getShowNames()); + XY_UpdateAllWindows(); +} +typedef FreeCaller ShowNamesToggleCaller; +void ShowNamesExport(const BoolImportCallback& importer) +{ + importer(GlobalEntityCreator().getShowNames()); +} +typedef FreeCaller1 ShowNamesExportCaller; + +void ShowAnglesToggle() +{ + GlobalEntityCreator().setShowAngles(!GlobalEntityCreator().getShowAngles()); + XY_UpdateAllWindows(); +} +typedef FreeCaller ShowAnglesToggleCaller; +void ShowAnglesExport(const BoolImportCallback& importer) +{ + importer(GlobalEntityCreator().getShowAngles()); +} +typedef FreeCaller1 ShowAnglesExportCaller; + +void ShowBlocksToggle() +{ + g_xywindow_globals_private.show_blocks ^= 1; + XY_UpdateAllWindows(); +} +typedef FreeCaller ShowBlocksToggleCaller; +void ShowBlocksExport(const BoolImportCallback& importer) +{ + importer(g_xywindow_globals_private.show_blocks); +} +typedef FreeCaller1 ShowBlocksExportCaller; + +void ShowCoordinatesToggle() +{ + g_xywindow_globals_private.show_coordinates ^= 1; + XY_UpdateAllWindows(); +} +typedef FreeCaller ShowCoordinatesToggleCaller; +void ShowCoordinatesExport(const BoolImportCallback& importer) +{ + importer(g_xywindow_globals_private.show_coordinates); +} +typedef FreeCaller1 ShowCoordinatesExportCaller; + +void ShowOutlineToggle() +{ + g_xywindow_globals_private.show_outline ^= 1; + XY_UpdateAllWindows(); +} +typedef FreeCaller ShowOutlineToggleCaller; +void ShowOutlineExport(const BoolImportCallback& importer) +{ + importer(g_xywindow_globals_private.show_outline); +} +typedef FreeCaller1 ShowOutlineExportCaller; + +void ShowAxesToggle() +{ + g_xywindow_globals_private.show_axis ^= 1; + XY_UpdateAllWindows(); +} +typedef FreeCaller ShowAxesToggleCaller; +void ShowAxesExport(const BoolImportCallback& importer) +{ + importer(g_xywindow_globals_private.show_axis); +} +typedef FreeCaller1 ShowAxesExportCaller; + +void ShowWorkzoneToggle() +{ + g_xywindow_globals_private.d_show_work ^= 1; + XY_UpdateAllWindows(); +} +typedef FreeCaller ShowWorkzoneToggleCaller; +void ShowWorkzoneExport(const BoolImportCallback& importer) +{ + importer(g_xywindow_globals_private.d_show_work); +} +typedef FreeCaller1 ShowWorkzoneExportCaller; + +ShowNamesExportCaller g_show_names_caller; +BoolExportCallback g_show_names_callback(g_show_names_caller); +ToggleItem g_show_names(g_show_names_callback); + +ShowAnglesExportCaller g_show_angles_caller; +BoolExportCallback g_show_angles_callback(g_show_angles_caller); +ToggleItem g_show_angles(g_show_angles_callback); + +ShowBlocksExportCaller g_show_blocks_caller; +BoolExportCallback g_show_blocks_callback(g_show_blocks_caller); +ToggleItem g_show_blocks(g_show_blocks_callback); + +ShowCoordinatesExportCaller g_show_coordinates_caller; +BoolExportCallback g_show_coordinates_callback(g_show_coordinates_caller); +ToggleItem g_show_coordinates(g_show_coordinates_callback); + +ShowOutlineExportCaller g_show_outline_caller; +BoolExportCallback g_show_outline_callback(g_show_outline_caller); +ToggleItem g_show_outline(g_show_outline_callback); + +ShowAxesExportCaller g_show_axes_caller; +BoolExportCallback g_show_axes_callback(g_show_axes_caller); +ToggleItem g_show_axes(g_show_axes_callback); + +ShowWorkzoneExportCaller g_show_workzone_caller; +BoolExportCallback g_show_workzone_callback(g_show_workzone_caller); +ToggleItem g_show_workzone(g_show_workzone_callback); + +void XYShow_registerCommands() +{ + GlobalToggles_insert("ShowAngles", ShowAnglesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_angles)); + GlobalToggles_insert("ShowNames", ShowNamesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_names)); + GlobalToggles_insert("ShowBlocks", ShowBlocksToggleCaller(), ToggleItem::AddCallbackCaller(g_show_blocks)); + GlobalToggles_insert("ShowCoordinates", ShowCoordinatesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_coordinates)); + GlobalToggles_insert("ShowWindowOutline", ShowOutlineToggleCaller(), ToggleItem::AddCallbackCaller(g_show_outline)); + GlobalToggles_insert("ShowAxes", ShowAxesToggleCaller(), ToggleItem::AddCallbackCaller(g_show_axes)); + GlobalToggles_insert("ShowWorkzone", ShowWorkzoneToggleCaller(), ToggleItem::AddCallbackCaller(g_show_workzone)); +} + +void XYWnd_registerShortcuts() +{ + command_connect_accelerator("ToggleCrosshairs"); + command_connect_accelerator("ToggleSizePaint"); +} + + + +void Orthographic_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox("", "Solid selection boxes", g_xywindow_globals.m_bNoStipple); + page.appendCheckBox("", "Display size info", g_xywindow_globals_private.m_bSizePaint); + page.appendCheckBox("", "Chase mouse during drags", g_xywindow_globals_private.m_bChaseMouse); + page.appendCheckBox("", "Update views on camera move", g_xywindow_globals_private.m_bCamXYUpdate); +} +void Orthographic_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Orthographic", "Orthographic View Preferences")); + Orthographic_constructPreferences(page); +} +void Orthographic_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + +void Clipper_constructPreferences(PreferencesPage& page) +{ + page.appendCheckBox("", "Clipper tool uses caulk", g_clip_useCaulk); +} +void Clipper_constructPage(PreferenceGroup& group) +{ + PreferencesPage page(group.createPage("Clipper", "Clipper Tool Settings")); + Clipper_constructPreferences(page); +} +void Clipper_registerPreferencesPage() +{ + PreferencesDialog_addSettingsPage(FreeCaller1()); +} + + +#include "preferencesystem.h" +#include "stringio.h" + + + + +void ToggleShown_importBool(ToggleShown& self, bool value) +{ + self.set(value); +} +typedef ReferenceCaller1 ToggleShownImportBoolCaller; +void ToggleShown_exportBool(const ToggleShown& self, const BoolImportCallback& importer) +{ + importer(self.active()); +} +typedef ConstReferenceCaller1 ToggleShownExportBoolCaller; + + +void XYWindow_Construct() +{ + GlobalCommands_insert("ToggleCrosshairs", FreeCaller(), Accelerator('X', (GdkModifierType)GDK_SHIFT_MASK)); + GlobalCommands_insert("ToggleSizePaint", FreeCaller(), Accelerator('J')); + GlobalCommands_insert("ToggleGrid", FreeCaller(), Accelerator('0')); + + GlobalToggles_insert("ToggleView", ToggleShown::ToggleCaller(g_xy_top_shown), ToggleItem::AddCallbackCaller(g_xy_top_shown.m_item), Accelerator('V', (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + GlobalToggles_insert("ToggleSideView", ToggleShown::ToggleCaller(g_yz_side_shown), ToggleItem::AddCallbackCaller(g_yz_side_shown.m_item)); + GlobalToggles_insert("ToggleFrontView", ToggleShown::ToggleCaller(g_xz_front_shown), ToggleItem::AddCallbackCaller(g_xz_front_shown.m_item)); + GlobalCommands_insert("NextView", FreeCaller(), Accelerator(GDK_Tab, (GdkModifierType)GDK_CONTROL_MASK)); + GlobalCommands_insert("ZoomIn", FreeCaller(), Accelerator(GDK_Delete)); + GlobalCommands_insert("ZoomOut", FreeCaller(), Accelerator(GDK_Insert)); + GlobalCommands_insert("ViewTop", FreeCaller(), Accelerator(GDK_KP_Home)); + GlobalCommands_insert("ViewSide", FreeCaller(), Accelerator(GDK_KP_Page_Down)); + GlobalCommands_insert("ViewFront", FreeCaller(), Accelerator(GDK_KP_End)); + GlobalCommands_insert("Zoom100", FreeCaller()); + GlobalCommands_insert("CenterXYView", FreeCaller(), Accelerator(GDK_Tab, (GdkModifierType)(GDK_SHIFT_MASK|GDK_CONTROL_MASK))); + + GlobalPreferenceSystem().registerPreference("ClipCaulk", BoolImportStringCaller(g_clip_useCaulk), BoolExportStringCaller(g_clip_useCaulk)); + + GlobalPreferenceSystem().registerPreference("NewRightClick", BoolImportStringCaller(g_xywindow_globals.m_bRightClick), BoolExportStringCaller(g_xywindow_globals.m_bRightClick)); + GlobalPreferenceSystem().registerPreference("ChaseMouse", BoolImportStringCaller(g_xywindow_globals_private.m_bChaseMouse), BoolExportStringCaller(g_xywindow_globals_private.m_bChaseMouse)); + GlobalPreferenceSystem().registerPreference("SizePainting", BoolImportStringCaller(g_xywindow_globals_private.m_bSizePaint), BoolExportStringCaller(g_xywindow_globals_private.m_bSizePaint)); + GlobalPreferenceSystem().registerPreference("NoStipple", BoolImportStringCaller(g_xywindow_globals.m_bNoStipple), BoolExportStringCaller(g_xywindow_globals.m_bNoStipple)); + GlobalPreferenceSystem().registerPreference("SI_ShowCoords", BoolImportStringCaller(g_xywindow_globals_private.show_coordinates), BoolExportStringCaller(g_xywindow_globals_private.show_coordinates)); + GlobalPreferenceSystem().registerPreference("SI_ShowOutlines", BoolImportStringCaller(g_xywindow_globals_private.show_outline), BoolExportStringCaller(g_xywindow_globals_private.show_outline)); + GlobalPreferenceSystem().registerPreference("SI_ShowAxis", BoolImportStringCaller(g_xywindow_globals_private.show_axis), BoolExportStringCaller(g_xywindow_globals_private.show_axis)); + GlobalPreferenceSystem().registerPreference("CamXYUpdate", BoolImportStringCaller(g_xywindow_globals_private.m_bCamXYUpdate), BoolExportStringCaller(g_xywindow_globals_private.m_bCamXYUpdate)); + GlobalPreferenceSystem().registerPreference("ShowWorkzone", BoolImportStringCaller(g_xywindow_globals_private.d_show_work), BoolExportStringCaller(g_xywindow_globals_private.d_show_work)); + + GlobalPreferenceSystem().registerPreference("SI_AxisColors0", Vector3ImportStringCaller(g_xywindow_globals.AxisColorX), Vector3ExportStringCaller(g_xywindow_globals.AxisColorX)); + GlobalPreferenceSystem().registerPreference("SI_AxisColors1", Vector3ImportStringCaller(g_xywindow_globals.AxisColorY), Vector3ExportStringCaller(g_xywindow_globals.AxisColorY)); + GlobalPreferenceSystem().registerPreference("SI_AxisColors2", Vector3ImportStringCaller(g_xywindow_globals.AxisColorZ), Vector3ExportStringCaller(g_xywindow_globals.AxisColorZ)); + GlobalPreferenceSystem().registerPreference("SI_Colors1", Vector3ImportStringCaller(g_xywindow_globals.color_gridback), Vector3ExportStringCaller(g_xywindow_globals.color_gridback)); + GlobalPreferenceSystem().registerPreference("SI_Colors2", Vector3ImportStringCaller(g_xywindow_globals.color_gridminor), Vector3ExportStringCaller(g_xywindow_globals.color_gridminor)); + GlobalPreferenceSystem().registerPreference("SI_Colors3", Vector3ImportStringCaller(g_xywindow_globals.color_gridmajor), Vector3ExportStringCaller(g_xywindow_globals.color_gridmajor)); + GlobalPreferenceSystem().registerPreference("SI_Colors6", Vector3ImportStringCaller(g_xywindow_globals.color_gridblock), Vector3ExportStringCaller(g_xywindow_globals.color_gridblock)); + GlobalPreferenceSystem().registerPreference("SI_Colors7", Vector3ImportStringCaller(g_xywindow_globals.color_gridtext), Vector3ExportStringCaller(g_xywindow_globals.color_gridtext)); + GlobalPreferenceSystem().registerPreference("SI_Colors8", Vector3ImportStringCaller(g_xywindow_globals.color_brushes), Vector3ExportStringCaller(g_xywindow_globals.color_brushes)); + GlobalPreferenceSystem().registerPreference("SI_Colors14", Vector3ImportStringCaller(g_xywindow_globals.color_gridmajor_alt), Vector3ExportStringCaller(g_xywindow_globals.color_gridmajor_alt)); + + + GlobalPreferenceSystem().registerPreference("XZVIS", makeBoolStringImportCallback(ToggleShownImportBoolCaller(g_xz_front_shown)), makeBoolStringExportCallback(ToggleShownExportBoolCaller(g_xz_front_shown))); + GlobalPreferenceSystem().registerPreference("YZVIS", makeBoolStringImportCallback(ToggleShownImportBoolCaller(g_yz_side_shown)), makeBoolStringExportCallback(ToggleShownExportBoolCaller(g_yz_side_shown))); + + Orthographic_registerPreferencesPage(); + Clipper_registerPreferencesPage(); + + XYWnd::captureStates(); + GlobalEntityClassManager().attach(g_EntityClassMenu); +} + +void XYWindow_Destroy() +{ + GlobalEntityClassManager().detach(g_EntityClassMenu); + XYWnd::releaseStates(); +} diff --git a/misc/mediasource/netradiant-src/radiant/xywindow.h b/misc/mediasource/netradiant-src/radiant/xywindow.h new file mode 100644 index 00000000..fd795c45 --- /dev/null +++ b/misc/mediasource/netradiant-src/radiant/xywindow.h @@ -0,0 +1,315 @@ +/* +Copyright (C) 1999-2006 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(INCLUDED_XYWINDOW_H) +#define INCLUDED_XYWINDOW_H + +#include "math/matrix.h" +#include "signal/signal.h" + +#include "gtkutil/cursor.h" +#include "gtkutil/window.h" +#include "gtkutil/xorrectangle.h" +#include "view.h" +#include "map.h" +#include "texturelib.h" + +#include "qerplugin.h" + +class Shader; +class SelectionSystemWindowObserver; +namespace scene +{ + class Node; +} +typedef struct _GtkWindow GtkWindow; +typedef struct _GtkMenu GtkMenu; + + +void FlipClip(); +void SplitClip(); +void Clip(); +void OnClipMode(bool enabled); +bool ClipMode(); + +inline const char* ViewType_getTitle(VIEWTYPE viewtype) +{ + if(viewtype == XY) + { + return "XY Top"; + } + if(viewtype == XZ) + { + return "XZ Front"; + } + if(viewtype == YZ) + { + return "YZ Side"; + } + return ""; +} + +class XYWnd +{ + GtkWidget* m_gl_widget; + guint m_sizeHandler; + guint m_exposeHandler; + + DeferredDraw m_deferredDraw; + DeferredMotion m_deferred_motion; +public: + GtkWindow* m_parent; + XYWnd(); + ~XYWnd(); + + void queueDraw() + { + m_deferredDraw.draw(); + } + GtkWidget* GetWidget() + { + return m_gl_widget; + } + +public: + SelectionSystemWindowObserver* m_window_observer; + XORRectangle m_XORRectangle; + WindowPositionTracker m_positionTracker; + + static void captureStates(); + static void releaseStates(); + + void PositionView(const Vector3& position); + const Vector3& GetOrigin(); + void SetOrigin(const Vector3& origin); + void Scroll(int x, int y); + + void XY_Draw(); + void DrawCameraIcon(const Vector3& origin, const Vector3& angles); + void XY_DrawBlockGrid(); + void XY_DrawAxis(); + void XY_DrawGrid(); + void XY_DrawBackground(); + void XY_LoadBackgroundImage(const char *name); + void XY_DisableBackground(); + + void XY_MouseUp(int x, int y, unsigned int buttons); + void XY_MouseDown(int x, int y, unsigned int buttons); + void XY_MouseMoved(int x, int y, unsigned int buttons); + + void NewBrushDrag_Begin(int x, int y); + void NewBrushDrag(int x, int y); + void NewBrushDrag_End(int x, int y); + + void XY_ToPoint(int x, int y, Vector3& point); + void XY_SnapToGrid(Vector3& point); + + void Move_Begin(); + void Move_End(); + bool m_move_started; + guint m_move_focusOut; + + void Zoom_Begin(); + void Zoom_End(); + bool m_zoom_started; + guint m_zoom_focusOut; + + void SetActive(bool b) + { + m_bActive = b; + }; + bool Active() + { + return m_bActive; + }; + + void Clipper_OnLButtonDown(int x, int y); + void Clipper_OnLButtonUp(int x, int y); + void Clipper_OnMouseMoved(int x, int y); + void Clipper_Crosshair_OnMouseMoved(int x, int y); + void DropClipPoint(int pointx, int pointy); + + void SetViewType(VIEWTYPE n); + bool m_bActive; + + static GtkMenu* m_mnuDrop; + + int m_chasemouse_current_x, m_chasemouse_current_y; + int m_chasemouse_delta_x, m_chasemouse_delta_y; + + + guint m_chasemouse_handler; + void ChaseMouse(); + bool chaseMouseMotion(int pointx, int pointy); + + void updateModelview(); + void updateProjection(); + Matrix4 m_projection; + Matrix4 m_modelview; + + int m_nWidth; + int m_nHeight; + // background image stuff + qtexture_t *m_tex; + bool m_backgroundActivated; + float m_alpha; // vertex alpha + float m_xmin, m_ymin, m_xmax, m_ymax; +private: + float m_fScale; + Vector3 m_vOrigin; + + + View m_view; + static Shader* m_state_selected; + + int m_ptCursorX, m_ptCursorY; + + unsigned int m_buttonstate; + + int m_nNewBrushPressx; + int m_nNewBrushPressy; + scene::Node* m_NewBrushDrag; + bool m_bNewBrushDrag; + + Vector3 m_mousePosition; + + VIEWTYPE m_viewType; + + void OriginalButtonUp(guint32 nFlags, int point, int pointy); + void OriginalButtonDown(guint32 nFlags, int point, int pointy); + + void OnContextMenu(); + void PaintSizeInfo(int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds); + + int m_entityCreate_x, m_entityCreate_y; + bool m_entityCreate; + +public: + void ButtonState_onMouseDown(unsigned int buttons) + { + m_buttonstate |= buttons; + } + void ButtonState_onMouseUp(unsigned int buttons) + { + m_buttonstate &= ~buttons; + } + unsigned int getButtonState() const + { + return m_buttonstate; + } + void EntityCreate_MouseDown(int x, int y); + void EntityCreate_MouseMove(int x, int y); + void EntityCreate_MouseUp(int x, int y); + + void OnEntityCreate(const char* item); + VIEWTYPE GetViewType() + { + return m_viewType; + } + void SetScale(float f); + float Scale() + { + return m_fScale; + } + int Width() + { + return m_nWidth; + } + int Height() + { + return m_nHeight; + } + + Signal0 onDestroyed; + Signal3 onMouseDown; + void mouseDown(const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers); + typedef Member3 MouseDownCaller; +}; + +inline void XYWnd_Update(XYWnd& xywnd) +{ + xywnd.queueDraw(); +} + + +struct xywindow_globals_t +{ + Vector3 color_gridback; + Vector3 color_gridminor; + Vector3 color_gridmajor; + Vector3 color_gridblock; + Vector3 color_gridtext; + Vector3 color_brushes; + Vector3 color_selbrushes; + Vector3 color_clipper; + Vector3 color_viewname; + Vector3 color_gridminor_alt; + Vector3 color_gridmajor_alt; + Vector3 AxisColorX; + Vector3 AxisColorY; + Vector3 AxisColorZ; + + bool m_bRightClick; + bool m_bNoStipple; + + xywindow_globals_t() : + color_gridback(1.f, 1.f, 1.f), + color_gridminor(0.75f, 0.75f, 0.75f), + color_gridmajor(0.5f, 0.5f, 0.5f), + color_gridblock(0.f, 0.f, 1.f), + color_gridtext(0.f, 0.f, 0.f), + color_brushes(0.f, 0.f, 0.f), + color_selbrushes(1.f, 0.f, 0.f), + color_clipper(0.f, 0.f, 1.f), + color_viewname(0.5f, 0.f, 0.75f), + color_gridminor_alt(0.f, 0.f, 0.f), + color_gridmajor_alt(0.f, 0.f, 0.f), + + AxisColorX(1.f, 0.f, 0.f), + AxisColorY(0.f, 1.f, 0.f), + AxisColorZ(0.f, 0.f, 1.f), + m_bRightClick(true), + m_bNoStipple(false) + { + } + +}; + +extern xywindow_globals_t g_xywindow_globals; + + +VIEWTYPE GlobalXYWnd_getCurrentViewType(); + +typedef struct _GtkWindow GtkWindow; +void XY_Top_Shown_Construct(GtkWindow* parent); +void YZ_Side_Shown_Construct(GtkWindow* parent); +void XZ_Front_Shown_Construct(GtkWindow* parent); + +void XYWindow_Construct(); +void XYWindow_Destroy(); + +void WXY_Print(); +void WXY_BackgroundSelect(); + +void XYShow_registerCommands(); +void XYWnd_registerShortcuts(); + +#endif diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/README.txt new file mode 100644 index 00000000..599ec3d4 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/README.txt @@ -0,0 +1,8 @@ +DESCRIPTION OF PROBLEM: +======================= + +The provided map, maps/base_winding.map, serves as an example map to test +changes to BaseWindingForPlane(). This map has planes at many different +angles. Use the patch base_winding_logging.patch to log the computed +base windings, in order to compare before and after when making changes to +BaseWindingForPlane(). diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/base_winding_logging.patch b/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/base_winding_logging.patch new file mode 100644 index 00000000..20fbaee3 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/base_winding_logging.patch @@ -0,0 +1,27 @@ +Index: tools/quake3/q3map2/brush.c +=================================================================== +--- tools/quake3/q3map2/brush.c (revision 369) ++++ tools/quake3/q3map2/brush.c (working copy) +@@ -357,6 +357,8 @@ + side_t *side; + plane_t *plane; + ++ static int brushord = -1; ++ brushord++; + + /* walk the list of brush sides */ + for( i = 0; i < brush->numsides; i++ ) +@@ -367,6 +369,13 @@ + + /* make huge winding */ + w = BaseWindingForPlane( plane->normal, plane->dist ); ++ Sys_Printf(">>> BaseWindingForPlane() for brush %i, side %i is as follows:\n", brushord, i); ++ for (j = 0; j < w->numpoints; j++) { ++ Sys_Printf(">>> (%.1f %.1f %.1f) [rounded to nearest integer coordinates]\n", ++ Q_rint(w->p[j][0]), ++ Q_rint(w->p[j][1]), ++ Q_rint(w->p[j][2])); ++ } + + /* walk the list of brush sides */ + for( j = 0; j < brush->numsides && w != NULL; j++ ) diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/maps/base_winding.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/maps/base_winding.map new file mode 100644 index 00000000..237278a2 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/base_winding/maps/base_winding.map @@ -0,0 +1,1284 @@ +{ +"classname" "worldspawn" +{ +( 768 256 0 ) ( 768 115 -256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 768 256 0 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 768 115 -256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 512 0 0 ) ( 768 0 0 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 512 0 0 ) ( 428 115 -256 ) ( 443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 128 -443 ) ( 768 0 -443 ) ( 768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 768 128 -443 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 768 0 -443 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 768 115 -256 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 256 0 -443 ) ( 222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 128 -768 ) ( 768 0 -768 ) ( 768 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 768 128 -443 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -768 ) ( 768 128 -768 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -768 ) ( 768 0 -768 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 768 0 -443 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 256 0 -768 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 222 128 -768 ) ( 0 0 -768 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 222 128 -768 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 256 0 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 0 0 -512 ) ( 222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 314 -256 ) ( 768 115 -256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 768 314 -256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 768 115 -256 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 768 256 0 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 428 115 -256 ) ( 314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 314 -256 ) ( 768 128 -443 ) ( 768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 768 314 -256 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 768 128 -443 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 768 115 -256 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 222 128 -443 ) ( 314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 443 0 ) ( 768 314 -256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 768 443 0 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 768 314 -256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 768 256 0 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 314 314 -256 ) ( 256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 222 -443 ) ( 768 128 -443 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 768 222 -443 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 768 128 -443 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 768 314 -256 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 222 128 -443 ) ( 128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 222 -768 ) ( 768 128 -768 ) ( 768 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 768 222 -443 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -768 ) ( 768 222 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -768 ) ( 768 128 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 768 128 -443 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 222 128 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 128 222 -768 ) ( 0 0 -768 ) ( 222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 222 -768 ) ( 222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 222 128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 -443 ) ( 0 0 -512 ) ( 128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 115 768 -256 ) ( 314 768 -256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 115 768 -256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 314 768 -256 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 256 768 0 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 314 314 -256 ) ( 115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 768 -256 ) ( 768 768 0 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 314 768 -256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 314 -256 ) ( 768 768 -256 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 443 0 ) ( 768 768 0 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 256 768 0 ) ( 768 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 768 443 0 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 115 768 -256 ) ( 128 768 -443 ) ( 314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 115 768 -256 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 768 -443 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 314 768 -256 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 128 222 -443 ) ( 115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 768 -443 ) ( 768 768 -256 ) ( 314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 768 -443 ) ( 314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 222 -443 ) ( 768 768 -443 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 314 -256 ) ( 768 768 -256 ) ( 768 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 314 768 -256 ) ( 768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 -256 ) ( 768 314 -256 ) ( 768 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 768 768 -768 ) ( 128 768 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 222 -443 ) ( 768 222 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 768 -443 ) ( 768 768 -768 ) ( 768 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 768 -443 ) ( 128 768 -768 ) ( 768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 222 -768 ) ( 128 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 768 -443 ) ( 768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 768 0 ) ( 115 768 -256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 512 0 ) ( 0 768 0 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 115 768 -256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 256 768 0 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 115 428 -256 ) ( 0 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 0 768 -443 ) ( 128 768 -443 ) ( 115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -443 ) ( 0 768 -443 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 768 -443 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 115 768 -256 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 128 222 -443 ) ( 0 256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 0 768 -768 ) ( 128 768 -768 ) ( 128 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -443 ) ( 0 768 -443 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -768 ) ( 0 768 -768 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -768 ) ( 128 768 -768 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 768 -443 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 222 -768 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 256 -768 ) ( 0 0 -768 ) ( 128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -443 ) ( 0 256 -768 ) ( 128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 128 222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 -443 ) ( 0 0 -512 ) ( 0 256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -115 768 -256 ) ( 115 768 -256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 -256 ) ( -115 768 -256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 115 768 -256 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 512 0 ) ( 0 768 0 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 512 0 ) ( 115 428 -256 ) ( -115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -115 768 -256 ) ( 0 768 -443 ) ( 115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 -256 ) ( -115 768 -256 ) ( 115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -443 ) ( 0 768 -443 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 115 768 -256 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 -256 ) ( 0 256 -443 ) ( -115 428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 0 -512 0 ) ( 115 -428 -256 ) ( 256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 0 -512 0 ) ( 0 -768 0 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 -256 ) ( 115 -768 -256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 -443 0 ) ( 256 -768 0 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 -768 0 ) ( 115 -768 -256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 115 -428 -256 ) ( 0 -256 -443 ) ( 128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 115 -428 -256 ) ( 115 -768 -256 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -443 ) ( 0 -768 -443 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -443 ) ( 128 -768 -443 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -768 -443 ) ( 0 -768 -443 ) ( 115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 -256 -443 ) ( 0 -256 -768 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -443 ) ( 0 -768 -443 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -768 ) ( 0 -768 -768 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -768 ) ( 128 -768 -768 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -443 ) ( 128 -768 -443 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -768 -768 ) ( 0 -768 -768 ) ( 0 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 -256 -443 ) ( 0 0 -512 ) ( 128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 0 -256 -443 ) ( 0 -256 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -443 ) ( 128 -222 -768 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -768 ) ( 0 0 -768 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 -443 0 ) ( 115 -428 -256 ) ( 314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 256 -443 0 ) ( 256 -768 0 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 -256 ) ( 115 -768 -256 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 -256 ) ( 314 -768 -256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -768 -256 ) ( 115 -768 -256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 115 -428 -256 ) ( 128 -222 -443 ) ( 314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 115 -428 -256 ) ( 115 -768 -256 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -443 ) ( 128 -768 -443 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 -256 ) ( 314 -768 -256 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -768 -256 ) ( 128 -768 -443 ) ( 115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 -443 0 ) ( 314 -314 -256 ) ( 443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 256 -443 0 ) ( 256 -768 0 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 -256 ) ( 314 -768 -256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 -256 0 ) ( 443 -768 0 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 -768 0 ) ( 314 -768 -256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 314 -314 -256 ) ( 128 -222 -443 ) ( 222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 314 -314 -256 ) ( 314 -768 -256 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -443 ) ( 128 -768 -443 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 222 -768 -443 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -768 -443 ) ( 128 -768 -443 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 128 -222 -443 ) ( 128 -222 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -443 ) ( 128 -768 -443 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 -768 ) ( 128 -768 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -768 ) ( 222 -768 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 222 -768 -443 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -768 -768 ) ( 128 -768 -768 ) ( 128 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 128 -222 -443 ) ( 0 0 -512 ) ( 222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 128 -222 -443 ) ( 128 -222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 222 -128 -768 ) ( 128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -768 ) ( 0 0 -768 ) ( 128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 443 -256 0 ) ( 314 -314 -256 ) ( 428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 443 -256 0 ) ( 768 -256 0 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 -256 ) ( 768 -314 -256 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 -256 ) ( 768 -115 -256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -115 -256 ) ( 768 -314 -256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 443 -256 0 ) ( 443 -768 0 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 -256 0 ) ( 768 -256 0 ) ( 443 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 -768 0 ) ( 768 -768 0 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -768 -256 ) ( 768 -768 -256 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 -256 ) ( 768 -314 -256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 -256 ) ( 768 -768 0 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 314 -314 -256 ) ( 222 -128 -443 ) ( 428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 314 -314 -256 ) ( 768 -314 -256 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 768 -128 -443 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 -256 ) ( 768 -115 -256 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -115 -256 ) ( 768 -128 -443 ) ( 768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 314 -314 -256 ) ( 314 -768 -256 ) ( 222 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 -256 ) ( 768 -314 -256 ) ( 314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -768 -256 ) ( 768 -768 -256 ) ( 222 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -768 -443 ) ( 768 -768 -443 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 768 -128 -443 ) ( 314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 -443 ) ( 768 -768 -256 ) ( 768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 222 -128 -443 ) ( 768 -128 -443 ) ( 768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 222 -128 -768 ) ( 768 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -128 -443 ) ( 768 -128 -768 ) ( 768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 -443 ) ( 768 -768 -768 ) ( 222 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -768 -443 ) ( 222 -768 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 -768 ) ( 768 -128 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 443 -256 0 ) ( 428 -115 -256 ) ( 512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 443 -256 0 ) ( 768 -256 0 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 -256 ) ( 768 -115 -256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 512 0 0 ) ( 768 0 0 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 0 0 ) ( 768 -115 -256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 428 -115 -256 ) ( 222 -128 -443 ) ( 256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 428 -115 -256 ) ( 768 -115 -256 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 768 -128 -443 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 768 0 -443 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 0 -443 ) ( 768 -128 -443 ) ( 768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 222 -128 -443 ) ( 222 -128 -768 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -443 ) ( 768 -128 -443 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 -768 ) ( 768 -128 -768 ) ( 256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -768 ) ( 768 0 -768 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 768 0 -443 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 0 -768 ) ( 768 -128 -768 ) ( 768 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 222 -128 -443 ) ( 0 0 -512 ) ( 256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 222 -128 -443 ) ( 222 -128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 256 0 -768 ) ( 222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -768 ) ( 0 0 -768 ) ( 222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 512 0 0 ) ( 428 -115 -256 ) ( 428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 512 0 0 ) ( 768 0 0 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 -256 ) ( 768 -115 -256 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 768 115 -256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 115 -256 ) ( 768 -115 -256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 428 -115 -256 ) ( 256 0 -443 ) ( 428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 428 -115 -256 ) ( 768 -115 -256 ) ( 256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 -443 ) ( 768 0 -443 ) ( 428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 -256 ) ( 768 115 -256 ) ( 428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 115 -256 ) ( 768 0 -443 ) ( 768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -768 -256 0 ) ( -768 -115 -256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -768 -256 0 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -768 -115 -256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -512 0 0 ) ( -768 0 0 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -512 0 0 ) ( -428 -115 -256 ) ( -443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -128 -443 ) ( -768 0 -443 ) ( -768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -768 -128 -443 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -768 0 -443 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -768 -115 -256 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -256 0 -443 ) ( -222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -128 -768 ) ( -768 0 -768 ) ( -768 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -768 -128 -443 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -768 ) ( -768 -128 -768 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -768 ) ( -768 0 -768 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -768 0 -443 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -256 0 -768 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -222 -128 -768 ) ( 0 0 -768 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -222 -128 -768 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -256 0 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( 0 0 -512 ) ( -222 -128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -314 -256 ) ( -768 -115 -256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -768 -314 -256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -768 -115 -256 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -768 -256 0 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -428 -115 -256 ) ( -314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -314 -256 ) ( -768 -128 -443 ) ( -768 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -768 -314 -256 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -768 -128 -443 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -768 -115 -256 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -222 -128 -443 ) ( -314 -314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -443 0 ) ( -768 -314 -256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -768 -443 0 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -768 -314 -256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -768 -256 0 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -314 -314 -256 ) ( -256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -222 -443 ) ( -768 -128 -443 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -768 -222 -443 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -768 -128 -443 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -768 -314 -256 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -222 -128 -443 ) ( -128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -222 -768 ) ( -768 -128 -768 ) ( -768 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -768 -222 -443 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -768 ) ( -768 -222 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -768 ) ( -768 -128 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -768 -128 -443 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -222 -128 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -128 -222 -768 ) ( 0 0 -768 ) ( -222 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -222 -768 ) ( -222 -128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( -222 -128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 -443 ) ( 0 0 -512 ) ( -128 -222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -115 -768 -256 ) ( -314 -768 -256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( -115 -768 -256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -314 -768 -256 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -256 -768 0 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -314 -314 -256 ) ( -115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -768 -256 ) ( -768 -768 0 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -314 -768 -256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -314 -256 ) ( -768 -768 -256 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -443 0 ) ( -768 -768 0 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -256 -768 0 ) ( -768 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -768 -443 0 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -115 -768 -256 ) ( -128 -768 -443 ) ( -314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( -115 -768 -256 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -768 -443 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -314 -768 -256 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -128 -222 -443 ) ( -115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -768 -443 ) ( -768 -768 -256 ) ( -314 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -768 -443 ) ( -314 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -222 -443 ) ( -768 -768 -443 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -314 -256 ) ( -768 -768 -256 ) ( -768 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -314 -768 -256 ) ( -768 -314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 -256 ) ( -768 -314 -256 ) ( -768 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -768 -768 -768 ) ( -128 -768 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -222 -443 ) ( -768 -222 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -768 -443 ) ( -768 -768 -768 ) ( -768 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -768 -443 ) ( -128 -768 -768 ) ( -768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -222 -768 ) ( -128 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -768 -443 ) ( -768 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 -768 0 ) ( -115 -768 -256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -512 0 ) ( 0 -768 0 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( -115 -768 -256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -256 -768 0 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -115 -428 -256 ) ( 0 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 0 -768 -443 ) ( -128 -768 -443 ) ( -115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -443 ) ( 0 -768 -443 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -768 -443 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( -115 -768 -256 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( -128 -222 -443 ) ( 0 -256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 0 -768 -768 ) ( -128 -768 -768 ) ( -128 -768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -443 ) ( 0 -768 -443 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -768 ) ( 0 -768 -768 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -768 ) ( -128 -768 -768 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -768 -443 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -222 -768 ) ( 0 -256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 -256 -768 ) ( 0 0 -768 ) ( -128 -222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -443 ) ( 0 -256 -768 ) ( -128 -222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( -128 -222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 -443 ) ( 0 0 -512 ) ( 0 -256 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 115 -768 -256 ) ( -115 -768 -256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 -256 ) ( 115 -768 -256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( -115 -768 -256 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -512 0 ) ( 0 -768 0 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -512 0 ) ( -115 -428 -256 ) ( 115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 115 -768 -256 ) ( 0 -768 -443 ) ( -115 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 -256 ) ( 115 -768 -256 ) ( -115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 -443 ) ( 0 -768 -443 ) ( 115 -428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( -115 -768 -256 ) ( 0 -256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 -256 ) ( 0 -256 -443 ) ( 115 -428 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 0 512 0 ) ( -115 428 -256 ) ( -256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 0 512 0 ) ( 0 768 0 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 -256 ) ( -115 768 -256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 443 0 ) ( -256 768 0 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 768 0 ) ( -115 768 -256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -115 428 -256 ) ( 0 256 -443 ) ( -128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -115 428 -256 ) ( -115 768 -256 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -443 ) ( 0 768 -443 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -443 ) ( -128 768 -443 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 768 -443 ) ( 0 768 -443 ) ( -115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 256 -443 ) ( 0 256 -768 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -443 ) ( 0 768 -443 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 -768 ) ( 0 768 -768 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -768 ) ( -128 768 -768 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -443 ) ( -128 768 -443 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 768 -768 ) ( 0 768 -768 ) ( 0 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 256 -443 ) ( 0 0 -512 ) ( -128 222 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 0 256 -443 ) ( 0 256 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -443 ) ( -128 222 -768 ) ( 0 256 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -768 ) ( 0 0 -768 ) ( 0 256 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 443 0 ) ( -115 428 -256 ) ( -314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -256 443 0 ) ( -256 768 0 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 -256 ) ( -115 768 -256 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 -256 ) ( -314 768 -256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 768 -256 ) ( -115 768 -256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -115 428 -256 ) ( -128 222 -443 ) ( -314 314 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -115 428 -256 ) ( -115 768 -256 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -443 ) ( -128 768 -443 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 -256 ) ( -314 768 -256 ) ( -115 428 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 768 -256 ) ( -128 768 -443 ) ( -115 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 443 0 ) ( -314 314 -256 ) ( -443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -256 443 0 ) ( -256 768 0 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 -256 ) ( -314 768 -256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 256 0 ) ( -443 768 0 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 768 0 ) ( -314 768 -256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -314 314 -256 ) ( -128 222 -443 ) ( -222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -314 314 -256 ) ( -314 768 -256 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -443 ) ( -128 768 -443 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -222 768 -443 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 768 -443 ) ( -128 768 -443 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -128 222 -443 ) ( -128 222 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -443 ) ( -128 768 -443 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 -768 ) ( -128 768 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -768 ) ( -222 768 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -222 768 -443 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 768 -768 ) ( -128 768 -768 ) ( -128 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -128 222 -443 ) ( 0 0 -512 ) ( -222 128 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -128 222 -443 ) ( -128 222 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -222 128 -768 ) ( -128 222 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -768 ) ( 0 0 -768 ) ( -128 222 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -443 256 0 ) ( -314 314 -256 ) ( -428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -443 256 0 ) ( -768 256 0 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 -256 ) ( -768 314 -256 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 -256 ) ( -768 115 -256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 115 -256 ) ( -768 314 -256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -443 256 0 ) ( -443 768 0 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 256 0 ) ( -768 256 0 ) ( -443 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 768 0 ) ( -768 768 0 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 768 -256 ) ( -768 768 -256 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 -256 ) ( -768 314 -256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 -256 ) ( -768 768 0 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -314 314 -256 ) ( -222 128 -443 ) ( -428 115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -314 314 -256 ) ( -768 314 -256 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -768 128 -443 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 -256 ) ( -768 115 -256 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 115 -256 ) ( -768 128 -443 ) ( -768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -314 314 -256 ) ( -314 768 -256 ) ( -222 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 -256 ) ( -768 314 -256 ) ( -314 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 768 -256 ) ( -768 768 -256 ) ( -222 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 768 -443 ) ( -768 768 -443 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -768 128 -443 ) ( -314 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 -443 ) ( -768 768 -256 ) ( -768 314 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -222 128 -443 ) ( -768 128 -443 ) ( -768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -222 128 -768 ) ( -768 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 128 -443 ) ( -768 128 -768 ) ( -768 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 -443 ) ( -768 768 -768 ) ( -222 768 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 768 -443 ) ( -222 768 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 -768 ) ( -768 128 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -443 256 0 ) ( -428 115 -256 ) ( -512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -443 256 0 ) ( -768 256 0 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 -256 ) ( -768 115 -256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -512 0 0 ) ( -768 0 0 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 0 0 ) ( -768 115 -256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -428 115 -256 ) ( -222 128 -443 ) ( -256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -428 115 -256 ) ( -768 115 -256 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -768 128 -443 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -768 0 -443 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 0 -443 ) ( -768 128 -443 ) ( -768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -222 128 -443 ) ( -222 128 -768 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -443 ) ( -768 128 -443 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 -768 ) ( -768 128 -768 ) ( -256 0 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -768 ) ( -768 0 -768 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -768 0 -443 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 0 -768 ) ( -768 128 -768 ) ( -768 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -222 128 -443 ) ( 0 0 -512 ) ( -256 0 -443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -222 128 -443 ) ( -222 128 -768 ) ( 0 0 -512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 -512 ) ( 0 0 -768 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -256 0 -768 ) ( -222 128 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -768 ) ( 0 0 -768 ) ( -222 128 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -512 0 0 ) ( -428 115 -256 ) ( -428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -512 0 0 ) ( -768 0 0 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 -256 ) ( -768 115 -256 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -768 -115 -256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -115 -256 ) ( -768 115 -256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -428 115 -256 ) ( -256 0 -443 ) ( -428 -115 -256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -428 115 -256 ) ( -768 115 -256 ) ( -256 0 -443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 -443 ) ( -768 0 -443 ) ( -428 -115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 -256 ) ( -768 -115 -256 ) ( -428 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -115 -256 ) ( -768 0 -443 ) ( -768 115 -256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 512 0 0 ) ( 428 -115 256 ) ( 443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 512 0 0 ) ( 768 0 0 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 256 ) ( 768 -115 256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 -256 0 ) ( 768 -256 0 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -256 0 ) ( 768 -115 256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 428 -115 256 ) ( 256 0 443 ) ( 222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 428 -115 256 ) ( 768 -115 256 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 443 ) ( 768 0 443 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 443 ) ( 768 -128 443 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -128 443 ) ( 768 0 443 ) ( 768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 0 443 ) ( 256 0 768 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 443 ) ( 768 0 443 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 768 ) ( 768 0 768 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 768 ) ( 768 -128 768 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 443 ) ( 768 -128 443 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -128 768 ) ( 768 0 768 ) ( 768 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 0 443 ) ( 0 0 512 ) ( 222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 256 0 443 ) ( 256 0 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 443 ) ( 222 -128 768 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 768 ) ( 0 0 768 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 443 -256 0 ) ( 428 -115 256 ) ( 314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 443 -256 0 ) ( 768 -256 0 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 256 ) ( 768 -115 256 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 256 ) ( 768 -314 256 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -314 256 ) ( 768 -115 256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 428 -115 256 ) ( 222 -128 443 ) ( 314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 428 -115 256 ) ( 768 -115 256 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 443 ) ( 768 -128 443 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 256 ) ( 768 -314 256 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -314 256 ) ( 768 -128 443 ) ( 768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 443 -256 0 ) ( 314 -314 256 ) ( 256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 443 -256 0 ) ( 768 -256 0 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 256 ) ( 768 -314 256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 -443 0 ) ( 768 -443 0 ) ( 443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -443 0 ) ( 768 -314 256 ) ( 768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 314 -314 256 ) ( 222 -128 443 ) ( 128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 314 -314 256 ) ( 768 -314 256 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 443 ) ( 768 -128 443 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 768 -222 443 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -222 443 ) ( 768 -128 443 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 222 -128 443 ) ( 222 -128 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 443 ) ( 768 -128 443 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 -128 768 ) ( 768 -128 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 768 ) ( 768 -222 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 768 -222 443 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -222 768 ) ( 768 -128 768 ) ( 768 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 222 -128 443 ) ( 0 0 512 ) ( 128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 222 -128 443 ) ( 222 -128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 128 -222 768 ) ( 222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 768 ) ( 0 0 768 ) ( 222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 -443 0 ) ( 314 -314 256 ) ( 115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 256 -443 0 ) ( 256 -768 0 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 256 ) ( 314 -768 256 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 256 ) ( 115 -768 256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -768 256 ) ( 314 -768 256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 -443 0 ) ( 768 -443 0 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 -443 0 ) ( 256 -768 0 ) ( 768 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -443 0 ) ( 768 -768 0 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -314 256 ) ( 768 -768 256 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 256 ) ( 314 -768 256 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 256 ) ( 768 -768 0 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 314 -314 256 ) ( 128 -222 443 ) ( 115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 314 -314 256 ) ( 314 -768 256 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 128 -768 443 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 256 ) ( 115 -768 256 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -768 256 ) ( 128 -768 443 ) ( 314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 314 -314 256 ) ( 768 -314 256 ) ( 768 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 -314 256 ) ( 314 -768 256 ) ( 768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -314 256 ) ( 768 -768 256 ) ( 768 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -222 443 ) ( 768 -768 443 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 128 -768 443 ) ( 314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 443 ) ( 768 -768 256 ) ( 314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 128 -222 443 ) ( 128 -768 443 ) ( 768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 128 -222 768 ) ( 128 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -768 443 ) ( 128 -768 768 ) ( 768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 443 ) ( 768 -768 768 ) ( 768 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -222 443 ) ( 768 -222 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 -768 768 ) ( 128 -768 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 -443 0 ) ( 115 -428 256 ) ( 0 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 256 -443 0 ) ( 256 -768 0 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 256 ) ( 115 -768 256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -512 0 ) ( 0 -768 0 ) ( 256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -768 0 ) ( 115 -768 256 ) ( 256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 115 -428 256 ) ( 128 -222 443 ) ( 0 -256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 115 -428 256 ) ( 115 -768 256 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 128 -768 443 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -768 443 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -768 443 ) ( 128 -768 443 ) ( 115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 128 -222 443 ) ( 128 -222 768 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 443 ) ( 128 -768 443 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 -222 768 ) ( 128 -768 768 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 768 ) ( 0 -768 768 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -768 443 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -768 768 ) ( 128 -768 768 ) ( 128 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 128 -222 443 ) ( 0 0 512 ) ( 0 -256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 128 -222 443 ) ( 128 -222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -256 768 ) ( 128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 768 ) ( 0 0 768 ) ( 128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 -512 0 ) ( 115 -428 256 ) ( -115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 0 -512 0 ) ( 0 -768 0 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 -428 256 ) ( 115 -768 256 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( -115 -768 256 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -768 256 ) ( 115 -768 256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 115 -428 256 ) ( 0 -256 443 ) ( -115 -428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 115 -428 256 ) ( 115 -768 256 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -768 443 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( -115 -768 256 ) ( 115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -768 256 ) ( 0 -768 443 ) ( 115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 768 0 ) ( 115 768 256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 256 768 0 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 115 768 256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 512 0 ) ( 0 768 0 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 512 0 ) ( 115 428 256 ) ( 256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 128 768 443 ) ( 0 768 443 ) ( 115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 768 443 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 768 443 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 115 768 256 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 0 256 443 ) ( 128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 128 768 768 ) ( 0 768 768 ) ( 0 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 768 443 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 768 ) ( 128 768 768 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 768 ) ( 0 768 768 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 768 443 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 256 768 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 128 222 768 ) ( 0 0 768 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 222 768 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 256 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 0 512 ) ( 128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 314 768 256 ) ( 115 768 256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 314 768 256 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 115 768 256 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 256 768 0 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 115 428 256 ) ( 314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 314 768 256 ) ( 128 768 443 ) ( 115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 314 768 256 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 768 443 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 115 768 256 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 128 222 443 ) ( 314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 443 768 0 ) ( 314 768 256 ) ( 256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 443 768 0 ) ( 256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 314 768 256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 256 768 0 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 443 0 ) ( 314 314 256 ) ( 443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 222 768 443 ) ( 128 768 443 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 222 768 443 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 768 443 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 314 768 256 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 128 222 443 ) ( 222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 222 768 768 ) ( 128 768 768 ) ( 128 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 222 768 443 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 768 ) ( 222 768 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 768 ) ( 128 768 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 768 443 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 222 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 222 128 768 ) ( 0 0 768 ) ( 128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 222 128 768 ) ( 128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 128 222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 128 222 443 ) ( 0 0 512 ) ( 222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 115 256 ) ( 768 314 256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 768 115 256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 768 314 256 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 768 256 0 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 314 314 256 ) ( 428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 768 256 ) ( 768 768 0 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 768 314 256 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 768 256 ) ( 768 768 256 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 768 0 ) ( 768 768 0 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 768 256 0 ) ( 443 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 443 768 0 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 768 115 256 ) ( 768 128 443 ) ( 768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 768 115 256 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 768 128 443 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 768 314 256 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 222 128 443 ) ( 428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 768 443 ) ( 768 768 256 ) ( 768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 768 128 443 ) ( 314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 768 443 ) ( 768 768 443 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 768 256 ) ( 768 768 256 ) ( 222 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 768 314 256 ) ( 314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 314 314 256 ) ( 314 768 256 ) ( 222 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 768 768 768 ) ( 768 128 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 768 443 ) ( 222 768 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 768 443 ) ( 768 768 768 ) ( 222 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 768 128 443 ) ( 768 128 768 ) ( 768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 222 128 768 ) ( 768 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 768 128 443 ) ( 768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 768 0 0 ) ( 768 115 256 ) ( 768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 512 0 0 ) ( 768 0 0 ) ( 443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 768 115 256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 768 256 0 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 443 256 0 ) ( 428 115 256 ) ( 512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 0 443 ) ( 768 128 443 ) ( 768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 443 ) ( 768 0 443 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 768 128 443 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 768 115 256 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 222 128 443 ) ( 256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 0 768 ) ( 768 128 768 ) ( 768 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 443 ) ( 768 0 443 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 768 ) ( 768 0 768 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 768 ) ( 768 128 768 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 768 128 443 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 222 128 768 ) ( 256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 256 0 768 ) ( 0 0 768 ) ( 222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 443 ) ( 256 0 768 ) ( 222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 222 128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 222 128 443 ) ( 0 0 512 ) ( 256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 -115 256 ) ( 768 115 256 ) ( 768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 256 ) ( 768 -115 256 ) ( 512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 768 115 256 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 512 0 0 ) ( 768 0 0 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 512 0 0 ) ( 428 115 256 ) ( 428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 768 -115 256 ) ( 768 0 443 ) ( 768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 -115 256 ) ( 768 -115 256 ) ( 428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 256 0 443 ) ( 768 0 443 ) ( 428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 768 115 256 ) ( 256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 428 115 256 ) ( 256 0 443 ) ( 428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -512 0 0 ) ( -428 115 256 ) ( -443 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -512 0 0 ) ( -768 0 0 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 256 ) ( -768 115 256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 256 0 ) ( -768 256 0 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 256 0 ) ( -768 115 256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -428 115 256 ) ( -256 0 443 ) ( -222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -428 115 256 ) ( -768 115 256 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 443 ) ( -768 0 443 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 443 ) ( -768 128 443 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 128 443 ) ( -768 0 443 ) ( -768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 0 443 ) ( -256 0 768 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 443 ) ( -768 0 443 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 768 ) ( -768 0 768 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 768 ) ( -768 128 768 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 443 ) ( -768 128 443 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 128 768 ) ( -768 0 768 ) ( -768 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 0 443 ) ( 0 0 512 ) ( -222 128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -256 0 443 ) ( -256 0 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 443 ) ( -222 128 768 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 768 ) ( 0 0 768 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -443 256 0 ) ( -428 115 256 ) ( -314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -443 256 0 ) ( -768 256 0 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 256 ) ( -768 115 256 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 256 ) ( -768 314 256 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 314 256 ) ( -768 115 256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -428 115 256 ) ( -222 128 443 ) ( -314 314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -428 115 256 ) ( -768 115 256 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 443 ) ( -768 128 443 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 256 ) ( -768 314 256 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 314 256 ) ( -768 128 443 ) ( -768 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -443 256 0 ) ( -314 314 256 ) ( -256 443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -443 256 0 ) ( -768 256 0 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 256 ) ( -768 314 256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 443 0 ) ( -768 443 0 ) ( -443 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 443 0 ) ( -768 314 256 ) ( -768 256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -314 314 256 ) ( -222 128 443 ) ( -128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -314 314 256 ) ( -768 314 256 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 443 ) ( -768 128 443 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -768 222 443 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 222 443 ) ( -768 128 443 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -222 128 443 ) ( -222 128 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 443 ) ( -768 128 443 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 128 768 ) ( -768 128 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 768 ) ( -768 222 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -768 222 443 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 222 768 ) ( -768 128 768 ) ( -768 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -222 128 443 ) ( 0 0 512 ) ( -128 222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -222 128 443 ) ( -222 128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -128 222 768 ) ( -222 128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 768 ) ( 0 0 768 ) ( -222 128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 443 0 ) ( -314 314 256 ) ( -115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -256 443 0 ) ( -256 768 0 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 256 ) ( -314 768 256 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 256 ) ( -115 768 256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 768 256 ) ( -314 768 256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 443 0 ) ( -768 443 0 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 443 0 ) ( -256 768 0 ) ( -768 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 443 0 ) ( -768 768 0 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 314 256 ) ( -768 768 256 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 256 ) ( -314 768 256 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 256 ) ( -768 768 0 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -314 314 256 ) ( -128 222 443 ) ( -115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -314 314 256 ) ( -314 768 256 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -128 768 443 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 256 ) ( -115 768 256 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 768 256 ) ( -128 768 443 ) ( -314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -314 314 256 ) ( -768 314 256 ) ( -768 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 314 256 ) ( -314 768 256 ) ( -768 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 314 256 ) ( -768 768 256 ) ( -768 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 222 443 ) ( -768 768 443 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -128 768 443 ) ( -314 314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 443 ) ( -768 768 256 ) ( -314 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -128 222 443 ) ( -128 768 443 ) ( -768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -128 222 768 ) ( -128 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 768 443 ) ( -128 768 768 ) ( -768 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 443 ) ( -768 768 768 ) ( -768 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 222 443 ) ( -768 222 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 768 768 ) ( -128 768 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 443 0 ) ( -115 428 256 ) ( 0 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -256 443 0 ) ( -256 768 0 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 256 ) ( -115 768 256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 512 0 ) ( 0 768 0 ) ( -256 443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 768 0 ) ( -115 768 256 ) ( -256 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -115 428 256 ) ( -128 222 443 ) ( 0 256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -115 428 256 ) ( -115 768 256 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -128 768 443 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 768 443 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 768 443 ) ( -128 768 443 ) ( -115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -128 222 443 ) ( -128 222 768 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 443 ) ( -128 768 443 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 222 768 ) ( -128 768 768 ) ( 0 256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 768 ) ( 0 768 768 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 768 443 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 768 768 ) ( -128 768 768 ) ( -128 768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -128 222 443 ) ( 0 0 512 ) ( 0 256 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -128 222 443 ) ( -128 222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 256 768 ) ( -128 222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 768 ) ( 0 0 768 ) ( -128 222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 0 512 0 ) ( -115 428 256 ) ( 115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 0 512 0 ) ( 0 768 0 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 428 256 ) ( -115 768 256 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 115 768 256 ) ( 0 512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 768 256 ) ( -115 768 256 ) ( 0 768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -115 428 256 ) ( 0 256 443 ) ( 115 428 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( -115 428 256 ) ( -115 768 256 ) ( 0 256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 256 443 ) ( 0 768 443 ) ( 115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 428 256 ) ( 115 768 256 ) ( -115 428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 115 768 256 ) ( 0 768 443 ) ( -115 768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 -768 0 ) ( -115 -768 256 ) ( 0 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -256 -768 0 ) ( 0 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( -115 -768 256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -512 0 ) ( 0 -768 0 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -512 0 ) ( -115 -428 256 ) ( -256 -443 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -128 -768 443 ) ( 0 -768 443 ) ( -115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -768 443 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -768 443 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( -115 -768 256 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( 0 -256 443 ) ( -128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -128 -768 768 ) ( 0 -768 768 ) ( 0 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -768 443 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 768 ) ( -128 -768 768 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 768 ) ( 0 -768 768 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -768 443 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -256 768 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -128 -222 768 ) ( 0 0 768 ) ( 0 -256 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -222 768 ) ( 0 -256 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 -256 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 -256 443 ) ( 0 0 512 ) ( -128 -222 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -314 -768 256 ) ( -115 -768 256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -314 -768 256 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( -115 -768 256 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -256 -768 0 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -115 -428 256 ) ( -314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -314 -768 256 ) ( -128 -768 443 ) ( -115 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -314 -768 256 ) ( -115 -428 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -768 443 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( -115 -768 256 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -115 -428 256 ) ( -128 -222 443 ) ( -314 -314 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -443 -768 0 ) ( -314 -768 256 ) ( -256 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -443 -768 0 ) ( -256 -443 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -314 -768 256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -256 -768 0 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 -443 0 ) ( -314 -314 256 ) ( -443 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -222 -768 443 ) ( -128 -768 443 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -222 -768 443 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -768 443 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -314 -768 256 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -128 -222 443 ) ( -222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -222 -768 768 ) ( -128 -768 768 ) ( -128 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -222 -768 443 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 768 ) ( -222 -768 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 768 ) ( -128 -768 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -768 443 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -222 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -222 -128 768 ) ( 0 0 768 ) ( -128 -222 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -222 -128 768 ) ( -128 -222 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( -128 -222 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -128 -222 443 ) ( 0 0 512 ) ( -222 -128 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -115 256 ) ( -768 -314 256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -768 -115 256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -768 -314 256 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -768 -256 0 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -314 -314 256 ) ( -428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -768 256 ) ( -768 -768 0 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -768 -314 256 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -768 256 ) ( -768 -768 256 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -768 0 ) ( -768 -768 0 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -768 -256 0 ) ( -443 -768 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -443 -768 0 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -768 -115 256 ) ( -768 -128 443 ) ( -768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -768 -115 256 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -768 -128 443 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -768 -314 256 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -222 -128 443 ) ( -428 -115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 -768 443 ) ( -768 -768 256 ) ( -768 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -768 -128 443 ) ( -314 -314 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -768 443 ) ( -768 -768 443 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -768 256 ) ( -768 -768 256 ) ( -222 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -768 -314 256 ) ( -314 -768 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -314 -314 256 ) ( -314 -768 256 ) ( -222 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -768 -768 768 ) ( -768 -128 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -768 443 ) ( -222 -768 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -768 443 ) ( -768 -768 768 ) ( -222 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -768 -128 443 ) ( -768 -128 768 ) ( -768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -222 -128 768 ) ( -768 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -768 -128 443 ) ( -768 -768 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -768 0 0 ) ( -768 -115 256 ) ( -768 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -512 0 0 ) ( -768 0 0 ) ( -443 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -768 -115 256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -768 -256 0 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -443 -256 0 ) ( -428 -115 256 ) ( -512 0 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 0 443 ) ( -768 -128 443 ) ( -768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 443 ) ( -768 0 443 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -768 -128 443 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -768 -115 256 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -222 -128 443 ) ( -256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 0 768 ) ( -768 -128 768 ) ( -768 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 443 ) ( -768 0 443 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 768 ) ( -768 0 768 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 768 ) ( -768 -128 768 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -768 -128 443 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -222 -128 768 ) ( -256 0 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( -256 0 768 ) ( 0 0 768 ) ( -222 -128 768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 443 ) ( -256 0 768 ) ( -222 -128 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 0 0 512 ) ( 0 0 768 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( -222 -128 768 ) ( 0 0 512 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -222 -128 443 ) ( 0 0 512 ) ( -256 0 443 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 115 256 ) ( -768 -115 256 ) ( -768 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 256 ) ( -768 115 256 ) ( -512 0 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -768 -115 256 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -512 0 0 ) ( -768 0 0 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -512 0 0 ) ( -428 -115 256 ) ( -428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( -768 115 256 ) ( -768 0 443 ) ( -768 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 115 256 ) ( -768 115 256 ) ( -428 -115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -256 0 443 ) ( -768 0 443 ) ( -428 115 256 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -768 -115 256 ) ( -256 0 443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -428 -115 256 ) ( -256 0 443 ) ( -428 115 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 1024 768 -768 ) ( 768 768 -768 ) ( 768 -128 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 832 -128 768 ) ( 832 768 768 ) ( 1088 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 704 -768 0 ) ( 960 -768 0 ) ( 960 -768 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 776 -128 0 ) ( 776 768 0 ) ( 776 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 1024 768 0 ) ( 768 768 0 ) ( 768 768 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 768 0 ) ( 768 -128 0 ) ( 768 -128 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 768 -768 -768 ) ( -768 -768 -768 ) ( -768 -832 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 -832 768 ) ( -768 -768 768 ) ( 768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 -776 760 ) ( 768 -776 760 ) ( 768 -776 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 -832 768 ) ( 768 -768 768 ) ( 768 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 -768 768 ) ( -768 -768 768 ) ( -768 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 -768 768 ) ( -768 -832 768 ) ( -768 -832 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -768 768 -768 ) ( -1088 768 -768 ) ( -1088 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -1088 -768 768 ) ( -1088 768 768 ) ( -768 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -1088 -768 768 ) ( -768 -768 768 ) ( -768 -768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 -768 768 ) ( -768 768 768 ) ( -768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 768 768 ) ( -1088 768 768 ) ( -1088 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -776 704 768 ) ( -776 -832 768 ) ( -776 -832 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 768 1088 -768 ) ( -768 1088 -768 ) ( -768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 768 768 ) ( -768 1088 768 ) ( 768 1088 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 768 768 ) ( 768 768 768 ) ( 768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 768 768 ) ( 768 1088 768 ) ( 768 1088 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 832 776 768 ) ( -704 776 768 ) ( -704 776 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 1088 768 ) ( -768 768 768 ) ( -768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 768 768 768 ) ( -768 768 768 ) ( -768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -744 -704 776 ) ( -744 832 776 ) ( 792 832 776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 -768 1344 ) ( 768 -768 1344 ) ( 768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 -768 1344 ) ( 768 768 1344 ) ( 768 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 768 1344 ) ( -768 768 1344 ) ( -768 768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 768 1344 ) ( -768 -768 1344 ) ( -768 -768 768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 768 768 -776 ) ( -768 768 -776 ) ( -768 -768 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 -768 -768 ) ( -768 768 -768 ) ( 768 768 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 -768 -768 ) ( 768 -768 -768 ) ( 768 -768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 -768 -768 ) ( 768 768 -768 ) ( 768 768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 768 768 -768 ) ( -768 768 -768 ) ( -768 768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -768 768 -768 ) ( -768 -768 -768 ) ( -768 -768 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"origin" "-64 0 -384" +"classname" "info_player_deathmatch" +} +{ +"light" "1000" +"origin" "0 0 64" +"classname" "light" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/coarse_snap_normal/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/coarse_snap_normal/README.txt new file mode 100644 index 00000000..6525380d --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/coarse_snap_normal/README.txt @@ -0,0 +1,16 @@ +DESCRIPTION OF PROBLEM: +======================= + +Because of the coarse nature of SnapNormal(), planes that are 0.25 degrees +away from being axial are "snapped" to be axial. The "normal epsilon" +is a very small value by default, and cannot go much smaller (without +running into limits of floating point numbers). The problem with +SnapNormal() is that we compare the components of the normal that are near +1, instead of comaring the components that are near 0. This leads to a very +coarse and inaccurate SnapNormal(). + +If you open the example map in Radiant, you can see that the red brick should +touch the middle checkered brick at the edge. However, once this map is +compiled, the edges are a significant distance apart. This is due to the +coarse and inaccurate nature of SnapNormal(). Likewise, the green brick should +be flush with the center tiled brick, but it's not. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/coarse_snap_normal/maps/coarse_snap_normal.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/coarse_snap_normal/maps/coarse_snap_normal.map new file mode 100644 index 00000000..9be4523b --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/coarse_snap_normal/maps/coarse_snap_normal.map @@ -0,0 +1,84 @@ +{ +"classname" "worldspawn" +{ +( 544 312 -8 ) ( -584 312 -8 ) ( -584 -488 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -576 -488 0 ) ( -576 312 0 ) ( 552 312 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -584 -512 8 ) ( 544 -512 8 ) ( 544 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -488 8 ) ( 512 312 8 ) ( 512 312 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 528 512 8 ) ( -600 512 8 ) ( -600 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 312 8 ) ( -512 -488 8 ) ( -512 -488 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 720 512 0 ) ( 512 512 0 ) ( 512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 512 ) ( 512 512 512 ) ( 720 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 512 ) ( 720 -512 512 ) ( 720 -512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 520 -512 520 ) ( 520 512 520 ) ( 520 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 720 512 512 ) ( 512 512 512 ) ( 512 512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 512 512 ) ( 512 -512 512 ) ( 512 -512 -8 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -512 512 0 ) ( -592 512 0 ) ( -592 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -592 -512 512 ) ( -592 512 512 ) ( -512 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -592 -512 512 ) ( -512 -512 512 ) ( -512 -512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -512 512 ) ( -512 512 512 ) ( -512 512 -8 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -512 512 512 ) ( -592 512 512 ) ( -592 512 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -520 512 536 ) ( -520 -512 536 ) ( -520 -512 16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 512 512 512 ) ( -512 512 512 ) ( -512 -512 512 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -488 -512 520 ) ( -488 512 520 ) ( 536 512 520 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -512 664 ) ( 512 -512 664 ) ( 512 -512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 664 ) ( 512 512 664 ) ( 512 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 512 664 ) ( -512 512 664 ) ( -512 512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 512 664 ) ( -512 -512 664 ) ( -512 -512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 512 608 0 ) ( -512 608 0 ) ( -512 520 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 520 512 ) ( -512 608 512 ) ( 512 608 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 512 512 ) ( 512 512 512 ) ( 512 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 512 520 512 ) ( 512 608 512 ) ( 512 608 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 520 520 ) ( -512 520 520 ) ( -512 520 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 608 512 ) ( -512 520 512 ) ( -512 520 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 512 -512 0 ) ( -512 -512 0 ) ( -512 -600 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -600 512 ) ( -512 -512 512 ) ( 512 -512 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -520 520 ) ( 512 -520 520 ) ( 512 -520 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -600 512 ) ( 512 -512 512 ) ( 512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 512 ) ( -512 -512 512 ) ( -512 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -512 -512 512 ) ( -512 -600 512 ) ( -512 -600 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 512 72 64 ) ( -512 72 64 ) ( -512 -448 64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -128 448 260 ) ( 192 448 260 ) ( 192 -448 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -512 -448 256 ) ( 512 -448 256 ) ( 512 -448 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 192 -440 256 ) ( 192 80 256 ) ( 192 80 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 192 448 260 ) ( -128 448 260 ) ( -128 448 64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -128 56 256 ) ( -128 -464 256 ) ( -128 -464 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 192 -448 232 ) ( -128 -448 232 ) ( -128 -472 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -128 -472 256 ) ( -128 -448 256 ) ( 192 -448 256 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -128 -472 256 ) ( 192 -472 256 ) ( 192 -472 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 192 -472 256 ) ( 192 -448 256 ) ( 192 -448 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 192 -448 256 ) ( -128 -448 256 ) ( -128 -448 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -128 -448 256 ) ( -128 -472 256 ) ( -128 -472 232 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 192 472 260 ) ( -128 472 260 ) ( -128 448 260 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( -128 448 280 ) ( -128 472 280 ) ( 192 472 280 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( -128 448 280 ) ( 192 448 280 ) ( 192 448 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( 192 448 280 ) ( 192 472 280 ) ( 192 472 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( 192 472 280 ) ( -128 472 280 ) ( -128 472 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( -128 472 280 ) ( -128 448 280 ) ( -128 448 256 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +} +} +{ +"light" "3000" +"origin" "0 0 384" +"classname" "light" +} +{ +"origin" "0 -64 384" +"classname" "info_player_deathmatch" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/README.txt new file mode 100644 index 00000000..f9aa3d6d --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/README.txt @@ -0,0 +1,16 @@ +DESCRIPTION OF PROBLEM: +======================= + +The info_null in the map for the decal is not 100% below the center of the +decal itself, because to be totally below it would have to lie on half-units. +So, the info_null lies almost directly below the center of the decal. In +this particular case, all kinds of bad things happen to the decal. For one, +during compiling we get warnings like this: + + Bad texture matrix! (B) (50.512253, -49.515625) != (50.484375, -49.515625) + Bad texture matrix! (C) (48.723190, -49.522587) != (48.695312, -49.515625) + Bad texture matrix! (B) (48.723186, -49.522587) != (48.695312, -49.515625) + +If you look at where the decal (it's just a blue translucent tile texture) +meets the far wall, it's clearly not aligned correctly. The tile on the decal +and the tile on the wall should align perfectly, and it's quite a bit off. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/maps/decal_misalignment.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/maps/decal_misalignment.map new file mode 100644 index 00000000..b764bf20 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/maps/decal_misalignment.map @@ -0,0 +1,89 @@ +{ +"classname" "worldspawn" +{ +( 6472 6336 -960 ) ( 6288 6336 -960 ) ( 6288 6320 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6264 6320 -576 ) ( 6264 6336 -576 ) ( 6448 6336 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6280 6328 -832 ) ( 6464 6328 -832 ) ( 6464 6328 -848 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 6320 -832 ) ( 6464 6336 -832 ) ( 6464 6336 -848 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 6336 -832 ) ( 6280 6336 -832 ) ( 6280 6336 -848 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 6336 -832 ) ( 6144 6320 -832 ) ( 6144 6320 -848 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6552 6520 -960 ) ( 6464 6520 -960 ) ( 6464 6336 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 6336 -576 ) ( 6464 6520 -576 ) ( 6552 6520 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 6336 -576 ) ( 6552 6336 -576 ) ( 6552 6336 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6472 6344 -576 ) ( 6472 6528 -576 ) ( 6472 6528 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6528 7360 -576 ) ( 6440 7360 -576 ) ( 6440 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 6520 -576 ) ( 6464 6336 -576 ) ( 6464 6336 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 6464 7424 -960 ) ( 6144 7424 -960 ) ( 6144 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 7360 -576 ) ( 6144 7424 -576 ) ( 6464 7424 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 7360 -576 ) ( 6464 7360 -576 ) ( 6464 7360 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 6464 7360 -576 ) ( 6464 7424 -576 ) ( 6464 7424 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 7368 -576 ) ( 6144 7368 -576 ) ( 6144 7368 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 7424 -576 ) ( 6144 7360 -576 ) ( 6144 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6144 7360 -960 ) ( 5880 7360 -960 ) ( 5880 6808 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 5880 6808 -576 ) ( 5880 7360 -576 ) ( 6144 7360 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 5864 6336 -576 ) ( 6128 6336 -576 ) ( 6128 6336 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 6808 -576 ) ( 6144 7360 -576 ) ( 6144 7360 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 7360 -576 ) ( 5880 7360 -576 ) ( 5880 7360 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 7384 -576 ) ( 6136 6832 -576 ) ( 6136 6832 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6456 7360 -968 ) ( 6136 7360 -968 ) ( 6136 6336 -968 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 6336 -960 ) ( 6144 7360 -960 ) ( 6464 7360 -960 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 6336 -960 ) ( 6464 6336 -960 ) ( 6464 6336 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 6336 -960 ) ( 6464 7360 -960 ) ( 6464 7360 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 7360 -960 ) ( 6144 7360 -960 ) ( 6144 7360 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 7360 -960 ) ( 6144 6336 -960 ) ( 6144 6336 -1008 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6464 7360 -576 ) ( 6152 7360 -576 ) ( 6152 6336 -576 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 6176 6336 -568 ) ( 6176 7360 -568 ) ( 6488 7360 -568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6152 6336 -472 ) ( 6464 6336 -472 ) ( 6464 6336 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 6336 -472 ) ( 6464 7360 -472 ) ( 6464 7360 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6464 7360 -472 ) ( 6152 7360 -472 ) ( 6152 7360 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 7360 -472 ) ( 6144 6336 -472 ) ( 6144 6336 -576 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6200 7360 -896 ) ( 6200 6336 -896 ) ( 6592 6336 -896 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 +( 6360 6336 -832 ) ( 6360 7256 -832 ) ( 6464 7256 -832 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 +( 6208 6337 -832 ) ( 6400 6337 -832 ) ( 6400 6337 -896 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 +( 6463 6336 -816 ) ( 6463 7360 -816 ) ( 6463 7360 -880 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 +( 6232 7264 -896 ) ( 6232 7264 -832 ) ( 6232 6337 -896 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 +( 6232 7256 -832 ) ( 6232 7256 -896 ) ( 6463 7256 -832 ) radiant_regression_tests/glass 0 0 0 0.500000 0.500000 134217728 257 0 +} +} +{ +"target" "checker" +"classname" "_decal" +{ +patchDef2 +{ +radiant_regression_tests/tile_trans +( 3 3 0 0 0 ) +( +( ( 6462 7255 -832 50.484375 -56.679688 ) ( 6462 6796.500000 -832 50.484375 -53.097656 ) ( 6462 6338 -832 50.484375 -49.515625 ) ) +( ( 6347.500000 7255 -832 49.589844 -56.679688 ) ( 6347.500000 6796.500000 -832 49.589844 -53.097656 ) ( 6347.500000 6338 -832 49.589844 -49.515625 ) ) +( ( 6233 7255 -832 48.695312 -56.679688 ) ( 6233 6796.500000 -832 48.695312 -53.097656 ) ( 6233 6338 -832 48.695312 -49.515625 ) ) +) +} +} +} +{ +"targetname" "checker" +"origin" "6347 6796 -840" +"classname" "info_null" +} +{ +"origin" "6288 6704 -712" +"classname" "info_player_deathmatch" +} +{ +"light" "2000" +"origin" "6304 6792 -704" +"classname" "light" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/scripts/radiant_regression_tests.shader b/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/scripts/radiant_regression_tests.shader new file mode 100644 index 00000000..af31c07d --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/decal_misalignment/scripts/radiant_regression_tests.shader @@ -0,0 +1,29 @@ +textures/radiant_regression_tests/tile_trans +{ + qer_trans 0.9 + q3map_bounceScale 0.0 + surfaceparm trans + cull disable + polygonOffset + { + map textures/radiant_regression_tests/tile_trans.tga + blendFunc blend + alphaGen const 1 + } +} + +textures/radiant_regression_tests/glass +{ + qer_editorImage textures/radiant_regression_tests/qer_glass.tga + qer_trans 0.6 + q3map_bounceScale 0.0 + surfaceparm nolightmap + surfaceparm detail + surfaceparm trans + cull disable + { + map textures/radiant_regression_tests/glass.tga + blendFunc add + tcGen environment + } +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding/README.txt new file mode 100644 index 00000000..b060d083 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding/README.txt @@ -0,0 +1,4 @@ +DESCRIPTION OF PROBLEM: +======================= + +I'm testing when windings become degenerate. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding/maps/degenerate_winding.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding/maps/degenerate_winding.map new file mode 100644 index 00000000..808de186 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding/maps/degenerate_winding.map @@ -0,0 +1,68 @@ +{ +"classname" "worldspawn" +{ +( 256 256 -8 ) ( -256 256 -8 ) ( -256 -264 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -264 0 ) ( -256 256 0 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -256 -256 8 ) ( 256 -256 8 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -264 8 ) ( 256 256 8 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 256 8 ) ( -256 256 8 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 8 ) ( -256 -264 8 ) ( -256 -264 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 296 256 0 ) ( 256 256 0 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 280 -256 512 ) ( 280 256 512 ) ( 320 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 392 ) ( 296 -256 392 ) ( 296 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 264 -256 384 ) ( 264 256 384 ) ( 264 256 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 296 256 392 ) ( 256 256 392 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 256 392 ) ( 256 -256 392 ) ( 256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -256 256 0 ) ( -320 256 0 ) ( -320 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -320 -256 512 ) ( -320 256 512 ) ( -256 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -320 -256 504 ) ( -256 -256 504 ) ( -256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -256 504 ) ( -256 256 504 ) ( -256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -256 256 504 ) ( -320 256 504 ) ( -320 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -264 256 496 ) ( -264 -256 496 ) ( -264 -256 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 256 256 512 ) ( -256 256 512 ) ( -256 -256 512 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -224 -256 520 ) ( -224 256 520 ) ( 288 256 520 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -256 584 ) ( 256 -256 584 ) ( 256 -256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 584 ) ( 256 256 584 ) ( 256 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 256 584 ) ( -256 256 584 ) ( -256 256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 584 ) ( -256 -256 584 ) ( -256 -256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 256 328 0 ) ( -256 328 0 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 512 ) ( -256 328 512 ) ( 256 328 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 512 ) ( 256 256 512 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 256 256 512 ) ( 256 328 512 ) ( 256 328 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 264 536 ) ( -256 264 536 ) ( -256 264 24 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 328 512 ) ( -256 256 512 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 256 -256 0 ) ( -256 -256 0 ) ( -256 -304 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -304 512 ) ( -256 -256 512 ) ( 256 -256 512 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -264 520 ) ( 256 -264 520 ) ( 256 -264 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -304 512 ) ( 256 -256 512 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 512 ) ( -256 -256 512 ) ( -256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -256 -256 512 ) ( -256 -304 512 ) ( -256 -304 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 64 0 128 ) ( 8 0 128 ) ( 8 -8 128 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( 8 -8 464 ) ( 8 0 464 ) ( 64 0 464 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( -240 8 464 ) ( -240 0 464 ) ( -240 0 160 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( -240 24 128 ) ( 160 8 128 ) ( -240 24 464 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 160 8 128 ) ( -240 0 128 ) ( 160 8 464 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 159 11 128 ) ( 159 0 128 ) ( 159 11 464 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +} +} +{ +"light" "1000" +"origin" "-40 0 32" +"classname" "light" +} +{ +"origin" "-40 128 96" +"classname" "info_player_deathmatch" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding2/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding2/README.txt new file mode 100644 index 00000000..b36f2db3 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding2/README.txt @@ -0,0 +1,14 @@ +DESCRIPTION OF PROBLEM: +======================= + +The sample map contains a wedge brush. The tip (the sharp edge) of the wedge +is chopped off by 2 planes, leaving very narrow windings. Each of these 2 +narrow windings is less than 0.1 units tall. However, the wedge has height +exactly equal to 1/8 unit at the point where it is chopped. Therefore, +the two narrow sides caused by the chops are expected to be degenerate and the +top face of the wedge is expected to be unaffected. This should leave a +"hole" in the narrow part of the wedge. + +The hole isn't desirable but it's expected based on the logic in the code. +Still, if there is a hole in the brush, I consider this regression test to +be broken. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding2/maps/degenerate_winding2.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding2/maps/degenerate_winding2.map new file mode 100644 index 00000000..70abf7cc --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding2/maps/degenerate_winding2.map @@ -0,0 +1,69 @@ +{ +"classname" "worldspawn" +{ +( 7 0 0 ) ( 7 0 1 ) ( 7 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 7 0 0 ) ( 7 64 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 +( 7 0 1 ) ( 7 0 0 ) ( -1 0 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -1 64 0 ) ( 7 64 0 ) ( 7 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 7 0 1 ) ( -1 0 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 +( -1 0 2 ) ( 0 0 0 ) ( 0 64 0 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( 1 0 2 ) ( -7 0 -13 ) ( -7 64 -13 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 128 72 -72 ) ( -128 72 -72 ) ( -128 8 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 120 -64 ) ( -128 184 -64 ) ( 128 184 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -128 -128 -64 ) ( 128 -128 -64 ) ( 128 -128 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 0 -64 ) ( 192 64 -64 ) ( 192 64 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 128 192 -64 ) ( -128 192 -64 ) ( -128 192 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 64 -64 ) ( -192 0 -64 ) ( -192 0 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 256 192 -64 ) ( 192 192 -64 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 256 ) ( 192 192 256 ) ( 256 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 256 ) ( 256 -128 256 ) ( 256 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 200 -128 240 ) ( 200 192 240 ) ( 200 192 -80 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -192 192 -64 ) ( -280 192 -64 ) ( -280 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -280 -128 256 ) ( -280 192 256 ) ( -192 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -280 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -128 256 ) ( -192 192 256 ) ( -192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -192 192 256 ) ( -280 192 256 ) ( -280 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -200 192 256 ) ( -200 -128 256 ) ( -200 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 192 192 256 ) ( -192 192 256 ) ( -192 -128 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -176 -128 264 ) ( -176 192 264 ) ( 208 192 264 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -128 304 ) ( 192 -128 304 ) ( 192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 304 ) ( 192 192 304 ) ( 192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 192 304 ) ( -192 192 304 ) ( -192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 192 304 ) ( -192 -128 304 ) ( -192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 192 272 -64 ) ( -192 272 -64 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 192 256 ) ( -192 272 256 ) ( 192 272 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 192 192 256 ) ( 192 272 256 ) ( 192 272 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 200 256 ) ( -192 200 256 ) ( -192 200 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 272 256 ) ( -192 192 256 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 192 -128 -64 ) ( -192 -128 -64 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -192 256 ) ( -192 -128 256 ) ( 192 -128 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -136 280 ) ( 192 -136 280 ) ( 192 -136 -40 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -192 -128 256 ) ( -192 -192 256 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"light" "1000" +"origin" "-8 40 128" +"classname" "light" +} +{ +"origin" "-112 -40 40" +"classname" "info_player_deathmatch" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding3/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding3/README.txt new file mode 100644 index 00000000..3aa08fc9 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding3/README.txt @@ -0,0 +1,18 @@ +DESCRIPTION OF PROBLEM: +======================= + +The sample map contains a wedge brush. The tip (the sharp edge) of the wedge +is chopped off by the YZ plane (side 5, or the last side, of the brush). +The height of the wedge where it is chopped is about 0.9. This makes it +barely smaller than DEGENERATE_EPSILON. So the face resulting from the chop +is probably degenerate, and that winding will be removed. I'm now wondering +what happens to the rest of the brush. 0.9 rounded to the nearest 1/8 unit +is 1/8, so the top face of the brush should get a slight raise, making the +"hole" even bigger. The sides will have degenerate edges near the chop, so +they will become triangles, creating open slivers in the sides. + +Although this behavior is a tad nasty, it is expected based on the way the +code is written. I want to make sure nothing really nasty happens. + +I consider this regression test to be broken if there is a "hole" in the brush, +and I consider this test to be very broken if something more drastic happens. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding3/maps/degenerate_winding3.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding3/maps/degenerate_winding3.map new file mode 100644 index 00000000..1817265b --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/degenerate_winding3/maps/degenerate_winding3.map @@ -0,0 +1,68 @@ +{ +"classname" "worldspawn" +{ +( 10 0 0 ) ( 10 0 1 ) ( 10 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 10 0 0 ) ( 10 64 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 +( 10 0 1 ) ( 10 0 0 ) ( -1 0 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -1 64 0 ) ( 10 64 0 ) ( 10 64 1 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( 10 0 1 ) ( -1 0 0 ) ( -1 64 0 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 +( 0 0 1 ) ( 0 0 0 ) ( 0 64 0 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 128 72 -72 ) ( -128 72 -72 ) ( -128 8 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 120 -64 ) ( -128 184 -64 ) ( 128 184 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -128 -128 -64 ) ( 128 -128 -64 ) ( 128 -128 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 0 -64 ) ( 192 64 -64 ) ( 192 64 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 128 192 -64 ) ( -128 192 -64 ) ( -128 192 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 64 -64 ) ( -192 0 -64 ) ( -192 0 -72 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 256 192 -64 ) ( 192 192 -64 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 256 ) ( 192 192 256 ) ( 256 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 256 ) ( 256 -128 256 ) ( 256 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 200 -128 240 ) ( 200 192 240 ) ( 200 192 -80 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -192 192 -64 ) ( -280 192 -64 ) ( -280 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -280 -128 256 ) ( -280 192 256 ) ( -192 192 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -280 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -128 256 ) ( -192 192 256 ) ( -192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -192 192 256 ) ( -280 192 256 ) ( -280 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -200 192 256 ) ( -200 -128 256 ) ( -200 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 192 192 256 ) ( -192 192 256 ) ( -192 -128 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -176 -128 264 ) ( -176 192 264 ) ( 208 192 264 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -128 304 ) ( 192 -128 304 ) ( 192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 304 ) ( 192 192 304 ) ( 192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 192 304 ) ( -192 192 304 ) ( -192 192 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 192 304 ) ( -192 -128 304 ) ( -192 -128 248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 192 272 -64 ) ( -192 272 -64 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 192 256 ) ( -192 272 256 ) ( 192 272 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 192 256 ) ( 192 192 256 ) ( 192 192 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 192 192 256 ) ( 192 272 256 ) ( 192 272 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 200 256 ) ( -192 200 256 ) ( -192 200 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 272 256 ) ( -192 192 256 ) ( -192 192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 192 -128 -64 ) ( -192 -128 -64 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -192 256 ) ( -192 -128 256 ) ( 192 -128 256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -192 -136 280 ) ( 192 -136 280 ) ( 192 -136 -40 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -192 256 ) ( 192 -128 256 ) ( 192 -128 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 192 -128 256 ) ( -192 -128 256 ) ( -192 -128 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -192 -128 256 ) ( -192 -192 256 ) ( -192 -192 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"light" "1000" +"origin" "-8 40 128" +"classname" "light" +} +{ +"origin" "-112 -40 40" +"classname" "info_player_deathmatch" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/README.txt new file mode 100644 index 00000000..a65d9203 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/README.txt @@ -0,0 +1,183 @@ +DESCRIPTION OF PROBLEM: +======================= + +The example map, maps/disappearing_sliver.map, contains an example of this bug. +There are 6 walls in the map, and one tall thin triangular sliver brush in the +middle of the room (7 brushes total). Only one face of the sliver in the +middle of the room is a draw surface. The bug is that this sliver surface is +not rendered in the compiled BSP. Note that the sliver brush was hand-crafted +to demonstrate the bug. If you re-save the map, Radiant might adjust the +order in which the planes on the brush are defined, and this might, as a side +effect, get rid of the immediate bug. + +To trigger the bug, compile the map; you don't need -vis or -light. Only +-bsp (the first q3map2 stage) is necessary to trigger the bug. The only +entities in the map are 2 lights and a single info_player_deathmatch, so the +map will compile for any Q3 mod. + + +SOLUTION TO PROBLEM: +==================== + +Several days were spent studying this problem in great detail. + +The fix for this problem was to make the outcome of the VectorNormalize() +function libs/mathlib/mathlib.c more accurate. The previous code in this +function looks something like this: + + vec_t length, ilength; // vec_t is a typedef for 32 bit float. + + /* Compute length */ + + ilength = 1.0f/length; + out[0] = in[0]*ilength; + out[1] = in[1]*ilength; + out[2] = in[2]*ilength; + +As you can see, we are introducing a lot of extra error into our normalized +vector by multiplying by the reciprocal length instead of outright dividing +by the length. The new fixed code looks like this: + + out[0] = in[0]/length; + out[1] = in[1]/length; + out[2] = in[2]/length; + +And we get rid of the recpirocal length ilength altogether. Even the +slightest math errors are magnified in successive calls to linear algebra +functions. + +The change described above was commmitted to GtkRadiant trunk as revision 363. + + +POSSIBLE SIDE EFFECTS: +====================== + +The only negative side effect is that compilation of a map might take longer +due to an increased number of divide operations. (I'm actually not sure if +that is indeed the case.) Another side effect might be that if you're used +to a map being broken (missing triangles) or having "sparklies" between +brushes, those might be gone now. :-) + + +IN-DEPTH DISCUSSION: +==================== + +VectorNormalize() is used very frequently in Radiant and tools code. My goal +for this fix was to make the least amount of code change but still be able to +demonstrate a significant improvement in math accuracy (including a fix to +the test case). At the same time don't risk that any other bugs pop up as a +side effect of this change. + +Here is the sequence of calls (stack trace) that cause the example bug to +happen: + + main() in main.c --> + BSPMain() in bsp.c --> + LoadMapFile() in map.c --> + ParseMapEntity() in map.c --> + ParseBrush() in map.c --> + FinishBrush() in map.c --> + CreateBrushWindings() in brush.c --> + ChopWindingInPlace() in polylib.c + +What basically happens in this sequence of calls is that a brush is parsed +out of the map file, "infinite" planes are created for each brush face, and +then the planes are "intersected" to find the exact vertex topologies of each +brush face. The vertex topology of the visible face of the sliver (in the +example map) gets computed with a significant amount of math error. If we +did our math with infinite precision, the sliver face would have the following +vertices: + + (67 -1022 0) + (88 -892 -768) + (134 -1015 0) + +In fact, if you open the map file (disappearing_sliver.map), you can actually +see these exact points embedded in the third plane defined on brush 0. + +I managed to print out the actual computed vertices of the sliver face before +and after this bug fix. Basically this is printed out after all the +ChopWindingInPlace() calls in the above stack trace: + + (66.984695 -1021.998657 0.000000) + (87.989571 -891.969116 -768.174316) + (133.998917 -1014.997314 0.000000) + +(If you want to print this out for yourself, use winding_logging.patch.) + +The same vertices after the bugfix have the following coordinates: + + (67.000229 -1021.998657 0.000000) + (88.000175 -891.999146 -767.997437) + (133.999146 -1014.998779 0.000000) + +As you can see, the vertices after the fix are substantially more accurate, +and all it took was an improvement to VectorNormalize(). + +The problem before the fix was the Z coordinate of the second point, namely +-768.174316. There is a lot of "snap to nearest 1/8 unit" and "epsilon 0.1" +code used throughout q3map2. 0.174 is greater than the 0.1 epsilon, and that +is the problem. + + main() in main.c --> + BSPMain() in bsp.c --> + ProcessModels() in bsp.c --> + ProcessWorldModel() in bsp.c --> + ClipSidesIntoTree() in surface.c --> + ClipSideIntoTree_r() in surface.c --> + ClipWindingEpsilon() in polylib.c + +Now what ClipWindingEpsilon() does is, since -768.174316 reaches below the +plane z = -768 (and over the 0.1 epsilon), it clips the winding_t and creates +two points where there used to be only one. + + main() in main.c --> + BSPMain() in bsp.c --> + ProcessModels() in bsp.c --> + ProcessWorldModel() in bsp.c + FixTJunctions() in tjunction.c + FixBrokenSurface() in tjunction.c + +FixBrokenSurface() realizes that there are two points very close together +(in our case, since they were "snapped", the are coincident in fact). +Therefore it reports the surface to be broken. The drawable surface is +deleted as a result. + + +RELATED BUGS: +============= + +A lot of the math operations in the Radiant codebase cut corners like this +example demonstrates. There is a lot more code like this that can be +improved upon. In fact, it may make sense to use 64 bit floating points in +some important math operations (and then convert back to 32 bit for the return +values). Plans are to look at similar code and improve it. + +The following "issue" was discovered while doing research for this bug. +If FixBrokenSurface() sees two points very close together, it attempts to +partially fix the problem (the code is not complete) and then returns false, +which means that the surface is broken and should not be used. So in fact +it attempts to fix the problem partially but none of the fixes are used. +It seems that FixBrokenSurface() should be fixed to completely fix the case +where there are two close points, and should report the surface as fixed. +This might be a destabilizing change however, so if this is indeed fixed, it +may make sense to activate the fix only if a certain flag is set. + + +MORE NOTES: +=========== + +As stated above, the accuracy after revision 363 is: + + (67.000229 -1021.998657 0.000000) + (88.000175 -891.999146 -767.997437) + (133.999146 -1014.998779 0.000000) + +A further change was committed for a related problem in revision 377. After +this change: + + (66.99955750 -1022.00262451 0.00000000) + (87.99969482 -892.00170898 -768.00524902) + (133.99958801 -1015.00195312 0.00000000) + +The results look similar with respect to the amount of error present. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/maps/disappearing_sliver.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/maps/disappearing_sliver.map new file mode 100644 index 00000000..82528868 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/maps/disappearing_sliver.map @@ -0,0 +1,73 @@ +{ +"classname" "worldspawn" +{ +( -704 -1152 0 ) ( 4480 -1152 0 ) ( -704 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 67 -1022 0 ) ( 67 -4096 0 ) ( 88 -892 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 67 -1022 0 ) ( 88 -892 -768 ) ( 134 -1015 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 88 -892 -768 ) ( 88 -4096 -768 ) ( 134 -1015 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 134 -1015 0 ) ( 134 -4096 0 ) ( 67 -1022 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 584 -640 -768 ) ( 520 -640 -768 ) ( 520 -1160 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 528 -1160 320 ) ( 528 -640 320 ) ( 592 -640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 528 -1152 0 ) ( 592 -1152 0 ) ( 592 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 520 -1160 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 584 -640 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -640 0 ) ( 512 -1160 0 ) ( 512 -1160 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 512 -552 -768 ) ( -296 -552 -768 ) ( -296 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -296 -640 320 ) ( -296 -552 320 ) ( 512 -552 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -296 -640 320 ) ( 512 -640 320 ) ( 512 -640 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 512 -640 320 ) ( 512 -552 320 ) ( 512 -552 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 528 -632 320 ) ( -280 -632 320 ) ( -280 -632 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -536 320 ) ( -512 -624 320 ) ( -512 -624 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -512 -648 -768 ) ( -536 -648 -768 ) ( -536 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -536 -1152 320 ) ( -536 -648 320 ) ( -512 -648 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -536 -1152 320 ) ( -512 -1152 320 ) ( -512 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -1152 320 ) ( -512 -648 320 ) ( -512 -648 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -512 -640 320 ) ( -536 -640 320 ) ( -536 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -520 -648 320 ) ( -520 -1152 320 ) ( -520 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 512 -640 320 ) ( 24 -640 320 ) ( 24 -1152 320 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 48 -1152 328 ) ( 48 -640 328 ) ( 536 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 24 -1152 440 ) ( 512 -1152 440 ) ( 512 -1152 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -1152 440 ) ( 512 -640 440 ) ( 512 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -640 440 ) ( 24 -640 440 ) ( 24 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -640 464 ) ( -512 -1152 464 ) ( -512 -1152 352 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -328 -896 -776 ) ( -512 -896 -776 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -1152 -768 ) ( -512 -896 -768 ) ( -328 -896 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -512 -1152 -768 ) ( -328 -1152 -768 ) ( -328 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -896 -768 ) ( -512 -1152 -768 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -1152 -768 ) ( 512 -896 -768 ) ( 512 -896 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -368 -640 -824 ) ( -856 -640 -824 ) ( -856 -640 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -512 -1168 320 ) ( -512 -1584 320 ) ( -512 -1584 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 1152 -1152 320 ) ( 176 -1152 320 ) ( 176 -1152 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 512 -1576 320 ) ( 512 -1160 320 ) ( 512 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 208 -1160 320 ) ( 1184 -1160 320 ) ( 1184 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 176 -1568 320 ) ( 176 -1152 320 ) ( 1152 -1152 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -1152 -768 ) ( -520 -1152 -768 ) ( -520 -1192 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"light" "3000" +"origin" "0 -768 -480" +"classname" "light" +} +{ +"angle" "270" +"origin" "0 -712 -640" +"classname" "info_player_deathmatch" +} +{ +"classname" "light" +"origin" "0 -832 160" +"light" "3000" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/winding_logging.patch b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/winding_logging.patch new file mode 100644 index 00000000..a1babe91 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver/winding_logging.patch @@ -0,0 +1,105 @@ +Index: tools/quake3/q3map2/brush.c +=================================================================== +--- tools/quake3/q3map2/brush.c (revision 391) ++++ tools/quake3/q3map2/brush.c (working copy) +@@ -421,10 +421,16 @@ + side_t *side; + plane_t *plane; + +- ++ static int brushord = -1; ++ brushord++; ++ ++ Sys_Printf("In CreateBrushWindings() for brush %i\n", brushord); ++ + /* walk the list of brush sides */ + for( i = 0; i < brush->numsides; i++ ) + { ++ Sys_Printf(" Handling side %i on the brush\n", i); ++ + /* get side and plane */ + side = &brush->sides[ i ]; + plane = &mapplanes[ side->planenum ]; +@@ -435,7 +441,13 @@ + #else + w = BaseWindingForPlane( plane->normal, plane->dist ); + #endif +- ++ ++ Sys_Printf(" Before clipping we have:\n"); ++ int z; ++ for (z = 0; z < w->numpoints; z++) { ++ Sys_Printf(" (%.8f %.8f %.8f)\n", w->p[z][0], w->p[z][1], w->p[z][2]); ++ } ++ + /* walk the list of brush sides */ + for( j = 0; j < brush->numsides && w != NULL; j++ ) + { +@@ -451,7 +463,20 @@ + #else + ChopWindingInPlace( &w, plane->normal, plane->dist, 0 ); // CLIP_EPSILON ); + #endif +- ++ ++ Sys_Printf(" After clipping w/ side %i we have:\n", j); ++ if (w) ++ { ++ for (z = 0; z < w->numpoints; z++) ++ { ++ Sys_Printf(" (%.8f %.8f %.8f)\n", w->p[z][0], w->p[z][1], w->p[z][2]); ++ } ++ } ++ else ++ { ++ Sys_Printf(" winding is NULL\n"); ++ } ++ + /* ydnar: fix broken windings that would generate trifans */ + #if EXPERIMENTAL_HIGH_PRECISION_MATH_Q3MAP2_FIXES + FixWindingAccu(w); +Index: tools/quake3/q3map2/map.c +=================================================================== +--- tools/quake3/q3map2/map.c (revision 391) ++++ tools/quake3/q3map2/map.c (working copy) +@@ -803,7 +803,11 @@ + char shader[ MAX_QPATH ]; + int flags; + ++ static int brushord = -1; ++ brushord++; + ++ Sys_Printf("In ParseRawBrush() for brush %i\n", brushord); ++ + /* initial setup */ + buildBrush->numsides = 0; + buildBrush->detail = qfalse; +@@ -812,9 +816,12 @@ + if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) + MatchToken( "{" ); + ++ int sideord = -1; ++ + /* parse sides */ + while( 1 ) + { ++ sideord++; + if( !GetToken( qtrue ) ) + break; + if( !strcmp( token, "}" ) ) +@@ -917,7 +924,16 @@ + } + + /* find the plane number */ ++ Sys_Printf(" Side %i:\n", sideord); ++ Sys_Printf(" (%f %f %f)\n", planePoints[0][0], planePoints[0][1], planePoints[0][2]); ++ Sys_Printf(" (%f %f %f)\n", planePoints[1][0], planePoints[1][1], planePoints[1][2]); ++ Sys_Printf(" (%f %f %f)\n", planePoints[2][0], planePoints[2][1], planePoints[2][2]); + planenum = MapPlaneFromPoints( planePoints ); ++ Sys_Printf(" normal: (%.10f %.10f %.10f)\n", ++ mapplanes[planenum].normal[0], ++ mapplanes[planenum].normal[1], ++ mapplanes[planenum].normal[2]); ++ Sys_Printf(" dist: %.10f\n", mapplanes[planenum].dist); + side->planenum = planenum; + + /* bp: get the texture mapping for this texturedef / plane combination */ diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver2/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver2/README.txt new file mode 100644 index 00000000..ffa12be5 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver2/README.txt @@ -0,0 +1,93 @@ +DESCRIPTION OF PROBLEM: +======================= + +The example map, maps/disappearing_sliver2.map, contains an example of this +bug. The triangle sliver surface in the middle of the room is not rendered +in the final BSP. + +To trigger the bug, compile the map; you don't need -vis or -light. Only +-bsp (the first q3map2 stage) is necessary to trigger the bug. The only +entities in the map are a light and a info_player_deathmatch, so the map will +compile for any Q3 mod. + + +SOLUTION TO PROBLEM: +==================== + +It was discovered that BaseWindingForPlane() in polylib.c did some sloppy +mathematics with significant loss of precision. Those problems have been +addressed in commits to revisions 371 and 377. + + +POSSIBLE SIDE EFFECTS: +====================== + +Great care was taken to preserve the exact behavior of the original +BaseWindingForPlane() function except for the loss of precision. Therefore +no negative side effects should be seen. In fact performance may be +increased. + + +IN-DEPTH DISCUSSION: +==================== + +Turns out that the problem is very similar to the original disappearing_sliver +regression test. You should read that README.txt to familiarize yourself +with the situation. + +The thing we need to look at is side 0 of brush 0, if you applied +winding_logging.patch from disappearing_sliver regression test: + + In ParseRawBrush() for brush 0 + Side 0: + (6784.000000 16241.000000 -1722.000000) + (6144.000000 16083.000000 -1443.000000) + (6144.000000 16122.000000 -1424.000000) + +That is the exact plane defninition of our problem sliver, and in fact those +are also the correct points for the actual vertices of the triangle. + +Now the results of the winding for this surface after all the clipping takes +place: + + (6784.12500000 16241.02343750 -1722.06250000) + (6144.00000000 16082.99218750 -1443.00781250) + (6144.00000000 16122.00000000 -1424.00390625) + +As you can see, 6784.12500000 is more than epsilon distance (0.1) away from +the correct point. This is a big problem. + +After we apply the fix committed in revision 371, the result after clipping +is this: + + (6784.06250000 16241.01171875 -1722.03515625) + (6144.00000000 16082.99609375 -1443.00781250) + (6144.00000000 16122.00000000 -1424.00585938) + +As you can see, all points but one have an increase in accuracy. This is +still not accurate enough in my opinion, but is a step in the right direction. + +After the fix committed in revision 377, which is a further attempt to address +BaseWindingForPlane(), we get the following accuracy: + + (6784.00000000 16241.00000000 -1722.00000000) + (6144.00000000 16083.00000000 -1443.00000000) + (6144.00000000 16122.00000000 -1424.00000000) + +It's just a fluke for this particular case, but obviouly revision 377 looks +favorably upon this regression test, because there is zero percent error. + + +MORE NOTES: +=========== + +I attempted to improve upon revision 371 by streamlining the code in +BaseWindingForPlane() some more. Those attempts were committed as revision +375. After revision 375: + + (6784.09375000 16241.01757812 -1722.04687500) + (6144.00000000 16082.99414062 -1443.00390625) + (6144.00000000 16122.00000000 -1424.00097656) + +Revision 375 has since been reverted (undone) because of the loss in +accuracy. Revision 377 is a fix for those failed attempts. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver2/maps/disappearing_sliver2.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver2/maps/disappearing_sliver2.map new file mode 100644 index 00000000..53e18710 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver2/maps/disappearing_sliver2.map @@ -0,0 +1,69 @@ +{ +"message" "Icy Fantasy by Rambetter" +"classname" "worldspawn" +{ +( 6784 16241 -1722 ) ( 6144 16083 -1443 ) ( 6144 16122 -1424 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 6784 16241 -1722 ) ( 6784 16241 -2048 ) ( 6144 16083 -1443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 16083 -1443 ) ( 6144 16083 -2048 ) ( 6144 16122 -1424 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 16122 -1424 ) ( 6144 16122 -2048 ) ( 6784 16241 -1722 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 16122 -2048 ) ( 6144 16083 -2048 ) ( 6784 16241 -2048 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 6136 16424 168 ) ( 6136 15928 168 ) ( 6136 15928 -3544 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6112 16896 160 ) ( 6000 16896 160 ) ( 6000 16896 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 160 ) ( 6144 16432 160 ) ( 6144 16432 -3552 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6032 15936 160 ) ( 6144 15936 160 ) ( 6144 15936 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6128 15936 -896 ) ( 6128 16432 -896 ) ( 6240 16432 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6160 16432 -2048 ) ( 6048 16432 -2048 ) ( 6048 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6784 16672 -1296 ) ( 6784 16176 -1296 ) ( 6784 16176 -1776 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 16896 -1312 ) ( 6136 16896 -1312 ) ( 6136 16896 -1792 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6792 16160 -1296 ) ( 6792 16656 -1296 ) ( 6792 16656 -1776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 15936 -1280 ) ( 6144 15936 -1280 ) ( 6144 15936 -1760 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 16192 -896 ) ( 6136 16688 -896 ) ( 6144 16688 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16672 -2048 ) ( 6136 16672 -2048 ) ( 6136 16176 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6144 15936 -896 ) ( 6144 15880 -896 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15936 -896 ) ( 6144 15936 -896 ) ( 6144 15936 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6784 15880 -896 ) ( 6784 15936 -896 ) ( 6784 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15928 -896 ) ( 6784 15928 -896 ) ( 6784 15928 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15880 -896 ) ( 6144 15936 -896 ) ( 6784 15936 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15936 -2048 ) ( 6144 15936 -2048 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6144 16960 -896 ) ( 6144 16896 -896 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16904 -896 ) ( 6144 16904 -896 ) ( 6144 16904 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -896 ) ( 6784 16960 -896 ) ( 6784 16960 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -896 ) ( 6784 16896 -896 ) ( 6784 16896 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 16896 -896 ) ( 6144 16960 -896 ) ( 6784 16960 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16960 -2048 ) ( 6144 16960 -2048 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6144 16896 -784 ) ( 6144 16536 -784 ) ( 6144 16536 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -784 ) ( 6144 16896 -784 ) ( 6144 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16536 -784 ) ( 6784 16896 -784 ) ( 6784 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -744 ) ( 6784 15936 -744 ) ( 6784 15936 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16552 -888 ) ( 6144 16912 -888 ) ( 6784 16912 -888 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -896 ) ( 6144 16896 -896 ) ( 6144 16536 -896 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 6144 16544 -2048 ) ( 6144 15936 -2048 ) ( 6144 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -2048 ) ( 6144 16896 -2048 ) ( 6144 16896 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15936 -2048 ) ( 6784 16544 -2048 ) ( 6784 16544 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -2048 ) ( 6784 15936 -2048 ) ( 6784 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -2048 ) ( 6144 16544 -2048 ) ( 6784 16544 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6784 16584 -2056 ) ( 6144 16584 -2056 ) ( 6144 15976 -2056 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"classname" "info_player_deathmatch" +"origin" "6432 16168 -1472" +"angle" "180" +} +{ +"classname" "light" +"origin" "6440 16160 -1192" +"light" "1000" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/NOTES.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/NOTES.txt new file mode 100644 index 00000000..70bb752a --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/NOTES.txt @@ -0,0 +1,72 @@ +Random notes for Rambetter, don't expect to understand this: +============================================================ + +Brush 0 is the problem. + +Side 0 is the problem (under surf tri). +Side 1 is the +y 4-face. +Side 2 is the -x 4-face. +Side 3 is the -y 4-face. +side 4 is the +z tri. + +(6144, 16122) -> (6784, 16241) +x "climb" of side 1 is 6784 - 6144 = 640. +y "climb" of side 1 is 16241 - 16122 = 119. + +x/y "climb rate" of side 1 is 640 / 119 = 5.378151261. + +After clipping side 0 against side 1, we get +************ +**** (-262144, -33762.8125) -> (262144, 63722) +************ +The slope of that is (262144 + 262144) / (63722 + 33762.8125) = 5.378150571. + +(-262144, y) -> (6784, 16241) +So (6784 + 262144) / (16241 - y) = 640 / 119 +So y = 16241 - ((119 * (6784 + 262144)) / 640) = -33762.8 + +(6144, 16122) -> (262144, y) +So (262144 - 6144) / (y - 16122) = 640 / 119 +So y = 16122 + ((119 * (262144 - 6144)) / 640) = 63722 + +After clipping side 0 against side 1 should have +************ +**** (-262144, -33762.8) -> (262144, 63722) +************ + +Random notes for Rambetter, don't expect to understand this: +============================================================ + +Brush 0 is the problem. + +Side 0 is the problem (under surf tri). +Side 1 is the +y 4-face. +Side 2 is the -x 4-face. +Side 3 is the -y 4-face. +side 4 is the +z tri. + +(6144, 16122) -> (6784, 16241) +x "climb" of side 1 is 6784 - 6144 = 640. +y "climb" of side 1 is 16241 - 16122 = 119. + +x/y "climb rate" of side 1 is 640 / 119 = 5.378151261. + +After clipping side 0 against side 1, we get +************ +**** (-262144, -33762.8125) -> (262144, 63722) +************ +The slope of that is (262144 + 262144) / (63722 + 33762.8125) = 5.378150571. + +(-262144, y) -> (6784, 16241) +So (6784 + 262144) / (16241 - y) = 640 / 119 +So y = 16241 - ((119 * (6784 + 262144)) / 640) = -33762.8 + +(6144, 16122) -> (262144, y) +So (262144 - 6144) / (y - 16122) = 640 / 119 +So y = 16122 + ((119 * (262144 - 6144)) / 640) = 63722 + +After clipping side 0 against side 1 should have +************ +**** (-262144, -33762.8) -> (262144, 63722) +************ + diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/README.txt new file mode 100644 index 00000000..839bd692 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/README.txt @@ -0,0 +1,49 @@ +DESCRIPTION OF PROBLEM: +======================= + +The example map, maps/disappearing_sliver3.map, contains an example of this +bug. The triangle sliver surface in the middle of the room is not rendered +in the final BSP. + +To trigger the bug, compile the map; you don't need -vis or -light. Only +-bsp (the first q3map2 stage) is necessary to trigger the bug. The only +entities in the map are a light and a info_player_deathmatch, so the map will +compile for any Q3 mod. + + +SOLUTION TO PROBLEM: +==================== + +More work has been done to BaseWindingForPlane() to make it more accurate. +This function is in polylib.c. The changes to fix this regression test were +committed in revision 377; however, those changes are not "good enough". + + +IN-DEPTH DISCUSSION: +==================== + +This is the problem triangle: + + In ParseRawBrush() for brush 0 + Side 0: + (6144.000000 16122.000000 -2048.000000) + (6144.000000 16083.000000 -2048.000000) + (6784.000000 16241.000000 -2048.000000) + +Computed winding before fix: + + (6784.16406250 16241.04101562 -2048.00000000) + (6144.00000000 16122.00976562 -2048.00000000) + (6144.00000000 16083.00000000 -2048.00000000) + +Obviously the 6784.16406250 is beyond epsilon error. + +After revision 377: + + (6783.85937500 16240.96484375 -2048.00000000) + (6144.00000000 16121.99218750 -2048.00000000) + (6144.00000000 16083.00000000 -2048.00000000) + +Even though this fixes the regression test, the error in 6783.85937500 is +still greater than epsilon (but fortunately in the opposite direction). So +I don't consider this test case to be fixed quite yet. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/maps/disappearing_sliver3.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/maps/disappearing_sliver3.map new file mode 100644 index 00000000..a56c649d --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/disappearing_sliver3/maps/disappearing_sliver3.map @@ -0,0 +1,68 @@ +{ +"classname" "worldspawn" +{ +( 6144 16122 -2048 ) ( 6144 16083 -2048 ) ( 6784 16241 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 6144 16122 -1424 ) ( 6144 16122 -2048 ) ( 6784 16241 -1722 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 16083 -1443 ) ( 6144 16083 -2048 ) ( 6144 16122 -1424 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6784 16241 -1722 ) ( 6784 16241 -2048 ) ( 6144 16083 -1443 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6784 16241 -1722 ) ( 6144 16083 -1443 ) ( 6144 16122 -1424 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 6160 16432 -2240 ) ( 6048 16432 -2240 ) ( 6048 15936 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6128 15936 -1376 ) ( 6128 16432 -1376 ) ( 6240 16432 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6032 15936 160 ) ( 6144 15936 160 ) ( 6144 15936 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -512 ) ( 6144 16432 -512 ) ( 6144 16432 -4224 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6112 16896 160 ) ( 6000 16896 160 ) ( 6000 16896 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 16424 168 ) ( 6136 15928 168 ) ( 6136 15928 -3544 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6144 16672 -2240 ) ( 6136 16672 -2240 ) ( 6136 16176 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 16192 -1376 ) ( 6136 16688 -1376 ) ( 6144 16688 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 15936 -1280 ) ( 6144 15936 -1280 ) ( 6144 15936 -1760 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6792 16160 -1296 ) ( 6792 16656 -1296 ) ( 6792 16656 -1776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -1312 ) ( 6136 16896 -1312 ) ( 6136 16896 -1792 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16672 -1968 ) ( 6784 16176 -1968 ) ( 6784 16176 -2448 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 6784 15936 -2240 ) ( 6144 15936 -2240 ) ( 6144 15880 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15880 -1376 ) ( 6144 15936 -1376 ) ( 6784 15936 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15928 -896 ) ( 6784 15928 -896 ) ( 6784 15928 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15880 -1568 ) ( 6784 15936 -1568 ) ( 6784 15936 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15936 -896 ) ( 6144 15936 -896 ) ( 6144 15936 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 15936 -1568 ) ( 6144 15880 -1568 ) ( 6144 15880 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6784 16960 -2240 ) ( 6144 16960 -2240 ) ( 6144 16896 -2240 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -1376 ) ( 6144 16960 -1376 ) ( 6784 16960 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -896 ) ( 6784 16896 -896 ) ( 6784 16896 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6784 16896 -1568 ) ( 6784 16960 -1568 ) ( 6784 16960 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16904 -896 ) ( 6144 16904 -896 ) ( 6144 16904 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16960 -1568 ) ( 6144 16896 -1568 ) ( 6144 16896 -2720 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6784 16896 -1376 ) ( 6144 16896 -1376 ) ( 6144 16536 -1376 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 16552 -1368 ) ( 6144 16912 -1368 ) ( 6784 16912 -1368 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -1224 ) ( 6784 15936 -1224 ) ( 6784 15936 -1336 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16536 -1264 ) ( 6784 16896 -1264 ) ( 6784 16896 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -1264 ) ( 6144 16896 -1264 ) ( 6144 16896 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -1264 ) ( 6144 16536 -1264 ) ( 6144 16536 -1376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6784 16584 -2248 ) ( 6144 16584 -2248 ) ( 6144 15976 -2248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -2240 ) ( 6144 16544 -2240 ) ( 6784 16544 -2240 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 15936 -2240 ) ( 6784 15936 -2240 ) ( 6784 15936 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15936 -2240 ) ( 6784 16544 -2240 ) ( 6784 16544 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -2240 ) ( 6144 16896 -2240 ) ( 6144 16896 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16544 -2240 ) ( 6144 15936 -2240 ) ( 6144 15936 -2568 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"angle" "180" +"origin" "6432 16168 -2144" +"classname" "info_player_deathmatch" +} +{ +"light" "1000" +"origin" "6504 16160 -2152" +"classname" "light" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/duplicate_plane/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/duplicate_plane/README.txt new file mode 100644 index 00000000..8c2ef028 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/duplicate_plane/README.txt @@ -0,0 +1,13 @@ +DESCRIPTION OF PROBLEM: +======================= + +The 4-sided brush in the middle of the room (brush 0) has a duplicate plane. +The last side (side 4) is a duplicate of the third side (side 2) with the +vertexes re-arranged. + +I wanted to make sure that ChopWindingInPlaceAccu() is doing the right thing +by setting a winding to NULL when all its points lie on the plane that the +winding is being chopped with. This seems to be the case. My concern was +that both windings for that duplicate plane will be NULL'ed out. + +Seems that some other code might be fixing duplicate planes. That's OK. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/duplicate_plane/maps/duplicate_plane.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/duplicate_plane/maps/duplicate_plane.map new file mode 100644 index 00000000..d1913b42 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/duplicate_plane/maps/duplicate_plane.map @@ -0,0 +1,67 @@ +{ +"classname" "worldspawn" +{ +( 136 128 64 ) ( -128 128 64 ) ( -128 -192 64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 136 128 384 ) ( -128 128 384 ) ( -128 128 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 128 -192 0 ) ( -128 128 0 ) ( 128 -192 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -128 128 256 ) ( 128 128 64 ) ( -128 -192 256 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 128 -192 384 ) ( 128 -192 0 ) ( -128 128 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 256 256 -8 ) ( -256 256 -8 ) ( -256 -256 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -256 0 ) ( -256 256 0 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -256 -256 8 ) ( 256 -256 8 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 8 ) ( 256 256 8 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 256 8 ) ( -256 256 8 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 8 ) ( -256 -256 8 ) ( -256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -256 256 0 ) ( -280 256 0 ) ( -280 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -280 -256 384 ) ( -280 256 384 ) ( -256 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -280 -256 384 ) ( -256 -256 384 ) ( -256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -256 384 ) ( -256 256 384 ) ( -256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -256 256 384 ) ( -280 256 384 ) ( -280 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -264 256 392 ) ( -264 -256 392 ) ( -264 -256 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 280 256 0 ) ( 256 256 0 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 384 ) ( 256 256 384 ) ( 280 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 384 ) ( 280 -256 384 ) ( 280 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 264 -256 384 ) ( 264 256 384 ) ( 264 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 280 256 384 ) ( 256 256 384 ) ( 256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 256 384 ) ( 256 -256 384 ) ( 256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 256 256 384 ) ( -256 256 384 ) ( -256 -256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -248 -256 392 ) ( -248 256 392 ) ( 264 256 392 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -256 424 ) ( 256 -256 424 ) ( 256 -256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 424 ) ( 256 256 424 ) ( 256 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 256 424 ) ( -256 256 424 ) ( -256 256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 424 ) ( -256 -256 424 ) ( -256 -256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 256 296 0 ) ( -256 296 0 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 384 ) ( -256 296 384 ) ( 256 296 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 256 384 ) ( 256 256 384 ) ( 256 256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 256 256 384 ) ( 256 296 384 ) ( 256 296 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 264 392 ) ( -256 264 392 ) ( -256 264 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 296 384 ) ( -256 256 384 ) ( -256 256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 256 -256 0 ) ( -256 -256 0 ) ( -256 -296 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -296 384 ) ( -256 -256 384 ) ( 256 -256 384 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -256 -264 392 ) ( 256 -264 392 ) ( 256 -264 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -296 384 ) ( 256 -256 384 ) ( 256 -256 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 256 -256 384 ) ( -256 -256 384 ) ( -256 -256 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -256 -256 384 ) ( -256 -296 384 ) ( -256 -296 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"origin" "-8 16 256" +"classname" "info_player_deathmatch" +} +{ +"light" "1000" +"origin" "-32 -40 256" +"classname" "light" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/README.txt new file mode 100644 index 00000000..c3c2f88d --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/README.txt @@ -0,0 +1,7 @@ +DESCRIPTION OF PROBLEM: +======================= + +There are 3 model wedges in the map that are auto-clipped. The middle wedge +with the 45 degree slope is the problem. The slope face does not become solid; +therefore, there is a nonsolid "hole" on the wedge part. The other two wedges +are fine. 45 degrees seems to be a problem for model clipping. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/maps/model_clipping_45_degrees.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/maps/model_clipping_45_degrees.map new file mode 100644 index 00000000..f358dba6 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/maps/model_clipping_45_degrees.map @@ -0,0 +1,81 @@ +{ +"classname" "worldspawn" +{ +( 392 512 -8 ) ( 0 512 -8 ) ( 0 448 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 0 448 0 ) ( 0 512 0 ) ( 392 512 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 104 -192 0 ) ( 496 -192 0 ) ( 496 -192 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 448 0 ) ( 384 512 0 ) ( 384 512 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 400 640 0 ) ( 8 640 0 ) ( 8 640 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 528 0 ) ( -128 464 0 ) ( -128 464 -16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -128 688 320 ) ( -128 640 320 ) ( -128 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 648 320 ) ( -128 648 320 ) ( -128 648 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 640 320 ) ( 384 688 320 ) ( 384 688 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 640 320 ) ( 384 640 320 ) ( 384 640 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( -128 640 320 ) ( -128 688 320 ) ( 384 688 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 688 0 ) ( -128 688 0 ) ( -128 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -128 -184 328 ) ( -128 -240 328 ) ( -128 -240 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 -192 328 ) ( -128 -192 328 ) ( -128 -192 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 384 -240 328 ) ( 384 -184 328 ) ( 384 -184 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 -200 320 ) ( 384 -200 320 ) ( 384 -200 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 -240 320 ) ( -128 -184 320 ) ( 384 -184 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 -184 0 ) ( -128 -184 0 ) ( -128 -240 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -128 248 392 ) ( -128 -192 392 ) ( -128 -192 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 640 408 ) ( -128 640 408 ) ( -128 640 336 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 -192 392 ) ( 384 248 392 ) ( 384 248 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 -192 392 ) ( 384 -192 392 ) ( 384 -192 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 -176 328 ) ( -128 264 328 ) ( 384 264 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 248 320 ) ( -128 248 320 ) ( -128 -192 320 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 384 640 320 ) ( 384 -192 320 ) ( 384 -192 0 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( 432 640 320 ) ( 384 640 320 ) ( 384 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 392 -192 320 ) ( 392 640 320 ) ( 392 640 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 -192 320 ) ( 432 -192 320 ) ( 432 -192 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 384 -192 320 ) ( 384 640 320 ) ( 432 640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 432 640 0 ) ( 384 640 0 ) ( 384 -192 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -136 640 328 ) ( -136 -192 328 ) ( -136 -192 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 640 312 ) ( -224 640 312 ) ( -224 640 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 -192 312 ) ( -128 640 312 ) ( -128 640 -8 ) radiant_regression_tests/bigtile 0 0 0 0.500000 0.500000 0 0 0 +( -224 -192 312 ) ( -128 -192 312 ) ( -128 -192 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -224 -192 320 ) ( -224 640 320 ) ( -128 640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 640 0 ) ( -224 640 0 ) ( -224 -192 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"model" "models/mapobjects/wedges/wedge_shallow.ase" +"origin" "0 -96 0" +"classname" "misc_model" +} +{ +"model" "models/mapobjects/wedges/wedge_45.ase" +"origin" "0 160 0" +"classname" "misc_model" +} +{ +"model" "models/mapobjects/wedges/wedge_steep.ase" +"origin" "0 416 0" +"classname" "misc_model" +} +{ +"classname" "light" +"origin" "192 384 160" +"light" "800" +} +{ +"light" "800" +"origin" "192 64 160" +"classname" "light" +} +{ +"classname" "info_player_deathmatch" +"origin" "256 208 128" +"angle" "225" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_45.ase b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_45.ase new file mode 100644 index 00000000..dfb0d41d --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_45.ase @@ -0,0 +1,368 @@ +*3DSMAX_ASCIIEXPORT 200 +*COMMENT "Generated by Q3Map2 (ydnar) -convert -format ase" +*SCENE { + *SCENE_FILENAME "wedge_45.bsp" + *SCENE_FIRSTFRAME 0 + *SCENE_LASTFRAME 100 + *SCENE_FRAMESPEED 30 + *SCENE_TICKSPERFRAME 160 + *SCENE_BACKGROUND_STATIC 0.0000 0.0000 0.0000 + *SCENE_AMBIENT_STATIC 0.0000 0.0000 0.0000 +} +*MATERIAL_LIST { + *MATERIAL_COUNT 2 + *MATERIAL 0 { + *MATERIAL_NAME "textures/radiant_regression_tests/tile_model" + *MATERIAL_CLASS "Standard" + *MATERIAL_DIFFUSE 1.000000 1.000000 0.833333 + *MATERIAL_SHADING Phong + *MAP_DIFFUSE { + *MAP_NAME "textures/radiant_regression_tests/tile_model" + *MAP_CLASS "Bitmap" + *MAP_SUBNO 1 + *MAP_AMOUNT 1.0 + *MAP_TYPE Screen + *BITMAP "..\textures\radiant_regression_tests\tile_model.tga" + *BITMAP_FILTER Pyramidal + } + } + *MATERIAL 1 { + *MATERIAL_NAME "noshader" + *MATERIAL_CLASS "Standard" + *MATERIAL_DIFFUSE 1.000000 1.000000 1.000000 + *MATERIAL_SHADING Phong + *MAP_DIFFUSE { + *MAP_NAME "noshader" + *MAP_CLASS "Bitmap" + *MAP_SUBNO 1 + *MAP_AMOUNT 1.0 + *MAP_TYPE Screen + *BITMAP "..\noshader.tga" + *BITMAP_FILTER Pyramidal + } + } +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf0" + *NODE_TM { + *NODE_NAME "mat0model0surf0" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 128.000000 0.000000 0.000000 + *MESH_VERTEX 1 64.000000 0.000000 64.000000 + *MESH_VERTEX 2 128.000000 128.000000 0.000000 + *MESH_VERTEX 3 64.000000 128.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 + *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 0 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 1 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 2 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 3 0.707107 0.000000 0.707107 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 1.000000 -1.000000 1.000000 + *MESH_TVERT 1 -1.000000 -1.000000 1.000000 + *MESH_TVERT 2 1.000000 3.000000 1.000000 + *MESH_TVERT 3 -1.000000 3.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf1" + *NODE_TM { + *NODE_NAME "mat0model0surf1" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 128.000000 64.000000 + *MESH_VERTEX 1 0.000000 128.000000 0.000000 + *MESH_VERTEX 2 64.000000 128.000000 64.000000 + *MESH_VERTEX 3 128.000000 128.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 + *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 0 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 1 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 2 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 3 0.000000 1.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 2.000000 1.000000 + *MESH_TVERT 1 -2.000000 0.000000 1.000000 + *MESH_TVERT 2 0.000000 2.000000 1.000000 + *MESH_TVERT 3 2.000000 0.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf2" + *NODE_TM { + *NODE_NAME "mat0model0surf2" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 64.000000 0.000000 64.000000 + *MESH_VERTEX 1 0.000000 0.000000 64.000000 + *MESH_VERTEX 2 64.000000 128.000000 64.000000 + *MESH_VERTEX 3 0.000000 128.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 + *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 0 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 1 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 2 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 3 0.000000 0.000000 1.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 1.000000 -1.000000 1.000000 + *MESH_TVERT 1 -1.000000 -1.000000 1.000000 + *MESH_TVERT 2 1.000000 3.000000 1.000000 + *MESH_TVERT 3 -1.000000 3.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf3" + *NODE_TM { + *NODE_NAME "mat0model0surf3" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 0.000000 64.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 0.000000 128.000000 64.000000 + *MESH_VERTEX 3 0.000000 128.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 + *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 0 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 1 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 2 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 3 -1.000000 0.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 2.000000 1.000000 + *MESH_TVERT 1 -2.000000 0.000000 1.000000 + *MESH_TVERT 2 2.000000 2.000000 1.000000 + *MESH_TVERT 3 2.000000 0.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf4" + *NODE_TM { + *NODE_NAME "mat0model0surf4" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 128.000000 0.000000 0.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 64.000000 0.000000 64.000000 + *MESH_VERTEX 3 0.000000 0.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 + *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 0 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 1 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 2 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 3 0.000000 -1.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 2.000000 0.000000 1.000000 + *MESH_TVERT 1 -2.000000 0.000000 1.000000 + *MESH_TVERT 2 0.000000 2.000000 1.000000 + *MESH_TVERT 3 -2.000000 2.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf5" + *NODE_TM { + *NODE_NAME "mat0model0surf5" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 128.000000 0.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 128.000000 128.000000 0.000000 + *MESH_VERTEX 3 128.000000 0.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.707107 0.000000 0.707107 + *MESH_FACENORMAL 1 0.707107 0.000000 0.707107 + *MESH_VERTEXNORMAL 0 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 1 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 2 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 3 0.000000 0.000000 -1.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 3.000000 1.000000 + *MESH_TVERT 1 -2.000000 -1.000000 1.000000 + *MESH_TVERT 2 2.000000 3.000000 1.000000 + *MESH_TVERT 3 2.000000 -1.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_shallow.ase b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_shallow.ase new file mode 100644 index 00000000..4e23fd49 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_shallow.ase @@ -0,0 +1,368 @@ +*3DSMAX_ASCIIEXPORT 200 +*COMMENT "Generated by Q3Map2 (ydnar) -convert -format ase" +*SCENE { + *SCENE_FILENAME "wedge_shallow.bsp" + *SCENE_FIRSTFRAME 0 + *SCENE_LASTFRAME 100 + *SCENE_FRAMESPEED 30 + *SCENE_TICKSPERFRAME 160 + *SCENE_BACKGROUND_STATIC 0.0000 0.0000 0.0000 + *SCENE_AMBIENT_STATIC 0.0000 0.0000 0.0000 +} +*MATERIAL_LIST { + *MATERIAL_COUNT 2 + *MATERIAL 0 { + *MATERIAL_NAME "textures/radiant_regression_tests/tile_model" + *MATERIAL_CLASS "Standard" + *MATERIAL_DIFFUSE 1.000000 1.000000 0.833333 + *MATERIAL_SHADING Phong + *MAP_DIFFUSE { + *MAP_NAME "textures/radiant_regression_tests/tile_model" + *MAP_CLASS "Bitmap" + *MAP_SUBNO 1 + *MAP_AMOUNT 1.0 + *MAP_TYPE Screen + *BITMAP "..\textures\radiant_regression_tests\tile_model.tga" + *BITMAP_FILTER Pyramidal + } + } + *MATERIAL 1 { + *MATERIAL_NAME "noshader" + *MATERIAL_CLASS "Standard" + *MATERIAL_DIFFUSE 1.000000 1.000000 1.000000 + *MATERIAL_SHADING Phong + *MAP_DIFFUSE { + *MAP_NAME "noshader" + *MAP_CLASS "Bitmap" + *MAP_SUBNO 1 + *MAP_AMOUNT 1.0 + *MAP_TYPE Screen + *BITMAP "..\noshader.tga" + *BITMAP_FILTER Pyramidal + } + } +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf0" + *NODE_TM { + *NODE_NAME "mat0model0surf0" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 160.000000 0.000000 0.000000 + *MESH_VERTEX 1 64.000000 0.000000 64.000000 + *MESH_VERTEX 2 160.000000 128.000000 0.000000 + *MESH_VERTEX 3 64.000000 128.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 + *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 0 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 1 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 2 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 3 0.554700 0.000000 0.832050 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 2.000000 -1.000000 1.000000 + *MESH_TVERT 1 -1.000000 -1.000000 1.000000 + *MESH_TVERT 2 2.000000 3.000000 1.000000 + *MESH_TVERT 3 -1.000000 3.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf1" + *NODE_TM { + *NODE_NAME "mat0model0surf1" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 128.000000 64.000000 + *MESH_VERTEX 1 0.000000 128.000000 0.000000 + *MESH_VERTEX 2 64.000000 128.000000 64.000000 + *MESH_VERTEX 3 160.000000 128.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 + *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 0 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 1 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 2 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 3 0.000000 1.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 2.000000 1.000000 + *MESH_TVERT 1 -2.000000 0.000000 1.000000 + *MESH_TVERT 2 0.000000 2.000000 1.000000 + *MESH_TVERT 3 3.000000 0.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf2" + *NODE_TM { + *NODE_NAME "mat0model0surf2" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 64.000000 0.000000 64.000000 + *MESH_VERTEX 1 0.000000 0.000000 64.000000 + *MESH_VERTEX 2 64.000000 128.000000 64.000000 + *MESH_VERTEX 3 0.000000 128.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 + *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 0 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 1 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 2 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 3 0.000000 0.000000 1.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 1.000000 -1.000000 1.000000 + *MESH_TVERT 1 -1.000000 -1.000000 1.000000 + *MESH_TVERT 2 1.000000 3.000000 1.000000 + *MESH_TVERT 3 -1.000000 3.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf3" + *NODE_TM { + *NODE_NAME "mat0model0surf3" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 0.000000 64.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 0.000000 128.000000 64.000000 + *MESH_VERTEX 3 0.000000 128.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 + *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 0 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 1 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 2 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 3 -1.000000 0.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 2.000000 1.000000 + *MESH_TVERT 1 -2.000000 0.000000 1.000000 + *MESH_TVERT 2 2.000000 2.000000 1.000000 + *MESH_TVERT 3 2.000000 0.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf4" + *NODE_TM { + *NODE_NAME "mat0model0surf4" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 160.000000 0.000000 0.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 64.000000 0.000000 64.000000 + *MESH_VERTEX 3 0.000000 0.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 + *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 0 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 1 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 2 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 3 0.000000 -1.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 3.000000 0.000000 1.000000 + *MESH_TVERT 1 -2.000000 0.000000 1.000000 + *MESH_TVERT 2 0.000000 2.000000 1.000000 + *MESH_TVERT 3 -2.000000 2.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf5" + *NODE_TM { + *NODE_NAME "mat0model0surf5" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 128.000000 0.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 160.000000 128.000000 0.000000 + *MESH_VERTEX 3 160.000000 0.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.554700 0.000000 0.832050 + *MESH_FACENORMAL 1 0.554700 0.000000 0.832050 + *MESH_VERTEXNORMAL 0 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 1 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 2 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 3 0.000000 0.000000 -1.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 3.000000 1.000000 + *MESH_TVERT 1 -2.000000 -1.000000 1.000000 + *MESH_TVERT 2 3.000000 3.000000 1.000000 + *MESH_TVERT 3 3.000000 -1.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_steep.ase b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_steep.ase new file mode 100644 index 00000000..0e8727e0 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/models/mapobjects/wedges/wedge_steep.ase @@ -0,0 +1,368 @@ +*3DSMAX_ASCIIEXPORT 200 +*COMMENT "Generated by Q3Map2 (ydnar) -convert -format ase" +*SCENE { + *SCENE_FILENAME "wedge_steep.bsp" + *SCENE_FIRSTFRAME 0 + *SCENE_LASTFRAME 100 + *SCENE_FRAMESPEED 30 + *SCENE_TICKSPERFRAME 160 + *SCENE_BACKGROUND_STATIC 0.0000 0.0000 0.0000 + *SCENE_AMBIENT_STATIC 0.0000 0.0000 0.0000 +} +*MATERIAL_LIST { + *MATERIAL_COUNT 2 + *MATERIAL 0 { + *MATERIAL_NAME "textures/radiant_regression_tests/tile_model" + *MATERIAL_CLASS "Standard" + *MATERIAL_DIFFUSE 1.000000 1.000000 0.833333 + *MATERIAL_SHADING Phong + *MAP_DIFFUSE { + *MAP_NAME "textures/radiant_regression_tests/tile_model" + *MAP_CLASS "Bitmap" + *MAP_SUBNO 1 + *MAP_AMOUNT 1.0 + *MAP_TYPE Screen + *BITMAP "..\textures\radiant_regression_tests\tile_model.tga" + *BITMAP_FILTER Pyramidal + } + } + *MATERIAL 1 { + *MATERIAL_NAME "noshader" + *MATERIAL_CLASS "Standard" + *MATERIAL_DIFFUSE 1.000000 1.000000 1.000000 + *MATERIAL_SHADING Phong + *MAP_DIFFUSE { + *MAP_NAME "noshader" + *MAP_CLASS "Bitmap" + *MAP_SUBNO 1 + *MAP_AMOUNT 1.0 + *MAP_TYPE Screen + *BITMAP "..\noshader.tga" + *BITMAP_FILTER Pyramidal + } + } +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf0" + *NODE_TM { + *NODE_NAME "mat0model0surf0" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 112.000000 0.000000 0.000000 + *MESH_VERTEX 1 64.000000 0.000000 64.000000 + *MESH_VERTEX 2 112.000000 128.000000 0.000000 + *MESH_VERTEX 3 64.000000 128.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 + *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 0 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 1 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 2 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 3 0.800000 0.000000 0.600000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 0.000000 1.000000 + *MESH_TVERT 1 -2.000000 2.000000 1.000000 + *MESH_TVERT 2 2.000000 0.000000 1.000000 + *MESH_TVERT 3 2.000000 2.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf1" + *NODE_TM { + *NODE_NAME "mat0model0surf1" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 128.000000 64.000000 + *MESH_VERTEX 1 0.000000 128.000000 0.000000 + *MESH_VERTEX 2 64.000000 128.000000 64.000000 + *MESH_VERTEX 3 112.000000 128.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 + *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 0 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 1 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 2 0.000000 1.000000 0.000000 + *MESH_VERTEXNORMAL 3 0.000000 1.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -1.000000 2.000000 1.000000 + *MESH_TVERT 1 -1.000000 0.000000 1.000000 + *MESH_TVERT 2 1.000000 2.000000 1.000000 + *MESH_TVERT 3 2.500000 0.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf2" + *NODE_TM { + *NODE_NAME "mat0model0surf2" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 64.000000 0.000000 64.000000 + *MESH_VERTEX 1 0.000000 0.000000 64.000000 + *MESH_VERTEX 2 64.000000 128.000000 64.000000 + *MESH_VERTEX 3 0.000000 128.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 + *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 0 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 1 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 2 0.000000 0.000000 1.000000 + *MESH_VERTEXNORMAL 3 0.000000 0.000000 1.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 1.000000 -1.000000 1.000000 + *MESH_TVERT 1 -1.000000 -1.000000 1.000000 + *MESH_TVERT 2 1.000000 3.000000 1.000000 + *MESH_TVERT 3 -1.000000 3.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf3" + *NODE_TM { + *NODE_NAME "mat0model0surf3" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 0.000000 64.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 0.000000 128.000000 64.000000 + *MESH_VERTEX 3 0.000000 128.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 + *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 0 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 1 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 2 -1.000000 0.000000 0.000000 + *MESH_VERTEXNORMAL 3 -1.000000 0.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -2.000000 2.000000 1.000000 + *MESH_TVERT 1 -2.000000 0.000000 1.000000 + *MESH_TVERT 2 2.000000 2.000000 1.000000 + *MESH_TVERT 3 2.000000 0.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf4" + *NODE_TM { + *NODE_NAME "mat0model0surf4" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 112.000000 0.000000 0.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 64.000000 0.000000 64.000000 + *MESH_VERTEX 3 0.000000 0.000000 64.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 + *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 0 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 1 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 2 0.000000 -1.000000 0.000000 + *MESH_VERTEXNORMAL 3 0.000000 -1.000000 0.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 2.500000 0.000000 1.000000 + *MESH_TVERT 1 -1.000000 0.000000 1.000000 + *MESH_TVERT 2 1.000000 2.000000 1.000000 + *MESH_TVERT 3 -1.000000 2.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} +*GEOMOBJECT { + *NODE_NAME "mat0model0surf5" + *NODE_TM { + *NODE_NAME "mat0model0surf5" + *INHERIT_POS 0 0 0 + *INHERIT_ROT 0 0 0 + *INHERIT_SCL 0 0 0 + *TM_ROW0 1.0 0 0 + *TM_ROW1 0 1.0 0 + *TM_ROW2 0 0 1.0 + *TM_ROW3 0 0 0 + *TM_POS 0.000000 0.000000 0.000000 + } + *MESH { + *TIMEVALUE 0 + *MESH_NUMVERTEX 4 + *MESH_NUMFACES 2 + *COMMENT "SURFACETYPE MST_PLANAR" + *MESH_VERTEX_LIST { + *MESH_VERTEX 0 0.000000 128.000000 0.000000 + *MESH_VERTEX 1 0.000000 0.000000 0.000000 + *MESH_VERTEX 2 112.000000 128.000000 0.000000 + *MESH_VERTEX 3 112.000000 0.000000 0.000000 + } + *MESH_NORMALS { + *MESH_FACENORMAL 0 0.800000 0.000000 0.600000 + *MESH_FACENORMAL 1 0.800000 0.000000 0.600000 + *MESH_VERTEXNORMAL 0 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 1 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 2 0.000000 0.000000 -1.000000 + *MESH_VERTEXNORMAL 3 0.000000 0.000000 -1.000000 + } + *MESH_FACE_LIST { + *MESH_FACE 0 A: 0 B: 2 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + *MESH_FACE 1 A: 2 B: 3 C: 1 AB: 1 BC: 1 CA: 1 *MESH_SMOOTHING 0 *MESH_MTLID 0 + } + *MESH_NUMTVERTEX 4 + *MESH_TVERTLIST { + *MESH_TVERT 0 -1.000000 3.000000 1.000000 + *MESH_TVERT 1 -1.000000 -1.000000 1.000000 + *MESH_TVERT 2 2.500000 3.000000 1.000000 + *MESH_TVERT 3 2.500000 -1.000000 1.000000 + } + *MESH_NUMTVFACES 2 + *MESH_TFACELIST { + *MESH_TFACE 0 0 2 1 + *MESH_TFACE 1 2 3 1 + } + } + *PROP_MOTIONBLUR 0 + *PROP_CASTSHADOW 1 + *PROP_RECVSHADOW 1 + *MATERIAL_REF 0 +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/scripts/radiant_regression_tests.shader b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/scripts/radiant_regression_tests.shader new file mode 100644 index 00000000..a2c31ed6 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/model_clipping_45_degrees/scripts/radiant_regression_tests.shader @@ -0,0 +1,12 @@ +textures/radiant_regression_tests/tile_model +{ + q3map_clipModel + q3map_forceMeta + { + map $lightmap + } + { + map textures/radiant_regression_tests/tile_model.tga + blendFunc filter + } +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/piercing_triangle/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/piercing_triangle/README.txt new file mode 100644 index 00000000..b09e2c31 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/piercing_triangle/README.txt @@ -0,0 +1,14 @@ +DESCRIPTION OF PROBLEM: +======================= + +In the disappearing_triangle regression test I outlined a potential problem +in the tjunction.c code, having to do with 2 points being too close together +on a winding, and that winding becoming invalid (drawsurf disappearing). + +This example map is the same as disappearing_triangle.map, except that the +floor is raised by 1 unit. Therefore the floor intersects the sliver triangle. +The resulting chopped sliver has a very short edge that is "degenerate" and +causes that draw surf to go away due to problems in the tjunction.c code. + +This is speculation at this point. I will provide more info after the bug has +been fixed. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/piercing_triangle/maps/piercing_triangle.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/piercing_triangle/maps/piercing_triangle.map new file mode 100644 index 00000000..8dc3552f --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/piercing_triangle/maps/piercing_triangle.map @@ -0,0 +1,73 @@ +{ +"classname" "worldspawn" +{ +( 134 -1015 0 ) ( 134 -4096 0 ) ( 67 -1022 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 88 -892 -768 ) ( 88 -4096 -768 ) ( 134 -1015 0 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 67 -1022 0 ) ( 88 -892 -768 ) ( 134 -1015 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +( 67 -1022 0 ) ( 67 -4096 0 ) ( 88 -892 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( -704 -1152 0 ) ( 4480 -1152 0 ) ( -704 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +} +{ +( 512 -640 0 ) ( 512 -1160 0 ) ( 512 -1160 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 584 -640 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 520 -1160 0 ) ( 520 -640 0 ) ( 520 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 528 -1152 0 ) ( 592 -1152 0 ) ( 592 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 528 -1160 320 ) ( 528 -640 320 ) ( 592 -640 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 583 -640 -768 ) ( 519 -640 -768 ) ( 519 -1160 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -512 -536 320 ) ( -512 -624 320 ) ( -512 -624 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 528 -632 320 ) ( -280 -632 320 ) ( -280 -632 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -640 320 ) ( 512 -552 320 ) ( 512 -552 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -296 -640 320 ) ( 512 -640 320 ) ( 512 -640 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -296 -640 320 ) ( -296 -552 320 ) ( 512 -552 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 511 -552 -768 ) ( -297 -552 -768 ) ( -297 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -520 -648 320 ) ( -520 -1152 320 ) ( -520 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -640 320 ) ( -536 -640 320 ) ( -536 -640 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -1152 320 ) ( -512 -648 320 ) ( -512 -648 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -536 -1152 320 ) ( -512 -1152 320 ) ( -512 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -536 -1152 320 ) ( -536 -648 320 ) ( -512 -648 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -648 -768 ) ( -536 -648 -768 ) ( -536 -1152 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -512 -640 464 ) ( -512 -1152 464 ) ( -512 -1152 352 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -640 440 ) ( 24 -640 440 ) ( 24 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -1152 440 ) ( 512 -640 440 ) ( 512 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 24 -1152 440 ) ( 512 -1152 440 ) ( 512 -1152 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 48 -1152 328 ) ( 48 -640 328 ) ( 536 -640 328 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -640 320 ) ( 24 -640 320 ) ( 24 -1152 320 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -368 -640 -824 ) ( -856 -640 -824 ) ( -856 -640 -960 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -1152 -768 ) ( 512 -896 -768 ) ( 512 -896 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -896 -768 ) ( -512 -1152 -768 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -1152 -768 ) ( -328 -1152 -768 ) ( -328 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -511 -1152 -767 ) ( -511 -896 -767 ) ( -327 -896 -767 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -328 -896 -776 ) ( -512 -896 -776 ) ( -512 -1152 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -256 -1152 -768 ) ( -520 -1152 -768 ) ( -520 -1192 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 176 -1568 320 ) ( 176 -1152 320 ) ( 1152 -1152 320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 208 -1160 320 ) ( 1184 -1160 320 ) ( 1184 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -1576 320 ) ( 512 -1160 320 ) ( 512 -1160 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 1152 -1152 320 ) ( 176 -1152 320 ) ( 176 -1152 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -512 -1168 320 ) ( -512 -1584 320 ) ( -512 -1584 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"classname" "light" +"origin" "0 -768 -480" +"light" "3000" +} +{ +"classname" "info_player_deathmatch" +"origin" "0 -712 -640" +"angle" "270" +} +{ +"light" "3000" +"origin" "0 -832 160" +"classname" "light" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/plane_aliasing/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/plane_aliasing/README.txt new file mode 100644 index 00000000..c76d574f --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/plane_aliasing/README.txt @@ -0,0 +1,129 @@ +DESCRIPTION OF PROBLEM: +======================= + +This example map demonstrates what a relatively large value for plane distance +epsilon can do as far as destroying draw surfaces. The plane distance +epsilon was 0.01 at the time of this writing. This means that two planes +with the same normal and a distance 0.00999 apart are considered to be the +same plane. + +The recommended value of plane distance epsilon is more along the lines of +0.001; however, we can't currently change this epsilon to that value due to +lack of resolution in 32 bit floating point integers in the 2^16 number range. +The smallest epsilon in 32 bit float land that can be added to 2^16 that +results in a value greater than 2^16 is approximately 0.007, which is already +practically the current default plane distance epsilon (0.01). + +Brush 0 in the example map is a 6-sided brush with red top face. The red top +face is defined such in the .map file: + + ( -127 256 513 ) ( -127 384 513 ) ( 1 384 512 ) + +During the -bsp stage, + + In ParseRawBrush() for brush 0 + Side 4: + (-127.000000 256.000000 513.000000) + (-127.000000 384.000000 513.000000) + (1.000000 384.000000 512.000000) + normal: (0.0078122616 0.0000000000 0.9999694824) + dist: 511.9921875000 + +Now brush 1, the 4-sided brush with the red top face, has the following +defined as the red top face: + + ( -128 0 513 ) ( -128 128 513 ) ( 0 128 512 ) + +It's almost the same plane, only off by a distance of about 0.01. + +During compiling: + + In ParseRawBrush() for brush 1 + Side 1: + (-128.000000 0.000000 513.000000) + (-128.000000 128.000000 513.000000) + (0.000000 128.000000 512.000000) + normal: (0.0078122616 0.0000000000 0.9999694824) + dist: 511.9921875000 + +Note that the normal and dist are identical to the plane above, even though +the two are different. This leads to multiplying errors later on, when this +side is intersected with the bottom green face. In particular, the blue face +disappears from the map. The blue face: + + In CreateBrushWindings() for brush 1 + Handling side 2 on the brush + Before clipping we have: + (-262144.00000000 0.00000000 262144.00000000) + (262144.00000000 0.00000000 262144.00000000) + (262144.00000000 -0.00000000 -262144.00000000) + (-262144.00000000 0.00000000 -262144.00000000) + After clipping w/ side 0 we have: + (-262144.00000000 0.00000000 262144.00000000) + (262144.00000000 0.00000000 262144.00000000) + (262144.00000000 0.00000000 -19977.00073172) + (-262144.00000000 0.00000000 20983.00073758) + After clipping w/ side 1 we have: + (262144.00000000 0.00000000 -1535.99218726) + (262144.00000000 0.00000000 -19977.00073172) + (-128.11106773 0.00000000 513.00868046) + After clipping w/ side 3 we have: + (0.00000000 0.00000000 503.00000293) + (-128.11106773 0.00000000 513.00868046) + (-0.00000000 0.00000000 512.00781274) + +We see the error is greater than 0.1 in the X value -128.11106773. This +causes the draw surface to be discarded in processing later on. We must +not allow such a great error. An error greater than or equal to 0.1 is +considered to be very bad. + +This disappearing blue triangle can be fixed simply by deleting brush 0, +the 6-sided brush that causes the bad plane alias. I would suggest deleting +this brush by editing the .map file manually (and then renumbering the brushes +manually). + +After deleting this brush: + + In ParseRawBrush() for brush 0 + Side 1: + (-128.000000 0.000000 513.000000) + (-128.000000 128.000000 513.000000) + (0.000000 128.000000 512.000000) + normal: (0.0078122616 0.0000000000 0.9999694824) + dist: 511.9843750000 + + In CreateBrushWindings() for brush 0 + Handling side 1 on the brush + Before clipping we have: + (262132.00000000 262136.00000000 -1535.90625143) + (262132.00000000 -262136.00000000 -1535.90625143) + (-262124.00048828 -262136.00000000 2559.84375238) + (-262124.00048828 262136.00000000 2559.84375238) + After clipping w/ side 0 we have: + (262132.00000000 262136.00000000 -1535.90625143) + (262132.00000000 -262136.00000000 -1535.90625143) + (-127.99993289 -262136.00000000 512.99999805) + (-127.99993289 262136.00000000 512.99999805) + After clipping w/ side 2 we have: + (262132.00000000 262136.00000000 -1535.90625143) + (262132.00000000 -0.00000000 -1535.90625143) + (-127.99993289 -0.00000000 512.99999805) + (-127.99993289 262136.00000000 512.99999805) + After clipping w/ side 3 we have: + (0.00000000 0.00000000 511.99999857) + (-127.99993289 -0.00000000 512.99999805) + (-127.99993289 127.99993289 512.99999805) + +Note that we're way more accurate now, and we're nowhere near to approaching +the 0.1 error. All it took was the deletion of a seemintly unrelated brush. + + +SOLUTION TO PROBLEM: +==================== + +The suggested fix is to increase the resolution of plane distance from 32 bit +float to 64 bit float for the relevant brush processing operations. After that +is done, decrease the default plane distance epsilon from 0.01 to 0.001. Note +that even though plane distance epsilon can be specified on the command-line, +it will do no good (even if set to 0) if the plane distance is close to +2^16. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/plane_aliasing/maps/plane_aliasing.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/plane_aliasing/maps/plane_aliasing.map new file mode 100644 index 00000000..070d7ba9 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/plane_aliasing/maps/plane_aliasing.map @@ -0,0 +1,74 @@ +{ +"classname" "worldspawn" +{ +( -127 384 513 ) ( -127 256 513 ) ( -127 256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 1 384 512 ) ( -127 384 512 ) ( -127 384 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 1 256 512 ) ( 1 384 512 ) ( 1 384 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -127 256 512 ) ( 1 256 512 ) ( 1 256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -127 256 513 ) ( -127 384 513 ) ( 1 384 512 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( 1 384 384 ) ( -127 384 384 ) ( -127 256 384 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 0 128 503 ) ( -128 128 513 ) ( 0 0 503 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -128 0 513 ) ( -128 128 513 ) ( 0 128 512 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +( -128 0 512 ) ( 0 0 512 ) ( 0 0 384 ) radiant_regression_tests/blue 0 0 0 0.500000 0.500000 0 0 0 +( -128 128 503 ) ( 0 0 503 ) ( -128 128 513 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -128 472 8 ) ( -128 320 8 ) ( -128 320 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -232 512 8 ) ( -416 512 8 ) ( -416 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -304 8 ) ( 512 -152 8 ) ( 512 -152 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 48 -512 8 ) ( 232 -512 8 ) ( 232 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -432 232 0 ) ( -432 384 0 ) ( -248 384 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -256 384 -8 ) ( -440 384 -8 ) ( -440 232 -8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -136 512 1040 ) ( -136 -512 1040 ) ( -136 -512 8 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 512 1032 ) ( -520 512 1032 ) ( -520 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -128 -512 1032 ) ( -128 512 1032 ) ( -128 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -520 -512 1032 ) ( -512 -512 1032 ) ( -512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -520 -512 1024 ) ( -520 512 1024 ) ( -512 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 512 0 ) ( -520 512 0 ) ( -520 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 512 512 1024 ) ( 512 -512 1024 ) ( 512 -512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 592 512 1024 ) ( 512 512 1024 ) ( 512 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 520 -512 1000 ) ( 520 512 1000 ) ( 520 512 -24 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 1024 ) ( 592 -512 1024 ) ( 592 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 1024 ) ( 512 512 1024 ) ( 592 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 592 512 0 ) ( 512 512 0 ) ( 512 -512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -128 512 1200 ) ( -128 -512 1200 ) ( -128 -512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 512 1200 ) ( -512 512 1200 ) ( -512 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 1200 ) ( 512 512 1200 ) ( 512 512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -512 1200 ) ( 512 -512 1200 ) ( 512 -512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -456 -512 1032 ) ( -456 512 1032 ) ( 568 512 1032 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 512 1024 ) ( -512 512 1024 ) ( -512 -512 1024 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -128 712 1024 ) ( -128 512 1024 ) ( -128 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 520 1040 ) ( -512 520 1040 ) ( -512 520 16 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 512 1024 ) ( 512 712 1024 ) ( 512 712 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 512 1024 ) ( 512 512 1024 ) ( 512 512 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -512 512 1024 ) ( -512 712 1024 ) ( 512 712 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 712 0 ) ( -512 712 0 ) ( -512 512 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -128 -512 1024 ) ( -128 -624 1024 ) ( -128 -624 56 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -512 1024 ) ( -512 -512 1024 ) ( -512 -512 56 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 512 -624 1024 ) ( 512 -512 1024 ) ( 512 -512 56 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -520 1048 ) ( 512 -520 1048 ) ( 512 -520 80 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -512 -624 1024 ) ( -512 -512 1024 ) ( 512 -512 1024 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 512 -504 0 ) ( -512 -504 0 ) ( -512 -616 0 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"classname" "light" +"origin" "192 64 640" +"light" "3000" +} +{ +"classname" "info_player_deathmatch" +"origin" "-64 64 640" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/segmentation_fault/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/segmentation_fault/README.txt new file mode 100644 index 00000000..05f30d2f --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/segmentation_fault/README.txt @@ -0,0 +1,27 @@ +DESCRIPTION OF PROBLEM: +======================= + +The example map, maps/segmentation_fault.map, contains an example of this +bug. q3map2 might segfault while compiling this map. This sort of thing +might happen in certain intermediate versions of q3map2 while work is being +done on fixing the math accuracy. The bug may not have happened in older +version of q3map2, before the math accuracy issues were addressed. + +To trigger the bug, compile the map; you don't need -vis or -light. Only +-bsp (the first q3map2 stage) is necessary to trigger the bug. The only +entities in the map are a light and a info_player_deathmatch, so the map will +compile for any Q3 mod. + +Here is a description of the problem brush (brush #0): + + side 0: -z face + side 1: +z face + side 2: -y face + side 3: +x face + side 4: +y face + side 5: -x face + side 6: problem side "accidentally showed up" :-) + +Side 6 is actually a superfluous plane and will be NULL'ed out in the code. +If the code does not handle a NULL'ed out winding correctly, it will +segfault. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/segmentation_fault/maps/segmentation_fault.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/segmentation_fault/maps/segmentation_fault.map new file mode 100644 index 00000000..610e7850 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/segmentation_fault/maps/segmentation_fault.map @@ -0,0 +1,69 @@ +{ +"classname" "worldspawn" +{ +( 10296 17600 -592 ) ( 10240 17600 -592 ) ( 10240 17472 -592 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 +( 10280 17472 -576 ) ( 10280 17600 -576 ) ( 10336 17600 -576 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 +( 10280 17472 -576 ) ( 10336 17472 -576 ) ( 10336 17472 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 +( 10367 17472 -576 ) ( 10367 17600 -576 ) ( 10367 17600 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 +( 10328 17727 -576 ) ( 10272 17727 -576 ) ( 10272 17727 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 +( 10240 17608 -576 ) ( 10240 17480 -576 ) ( 10240 17480 -1600 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 +( 10240 17727 -576 ) ( 10240 17726 -621 ) ( 10335 17727 -576 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 257 0 +} +{ +( 10504 17800 -768 ) ( 10112 17800 -768 ) ( 10112 17792 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17792 -320 ) ( 10112 17800 -320 ) ( 10504 17800 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17792 -576 ) ( 10504 17792 -576 ) ( 10504 17792 -592 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 10496 17792 -576 ) ( 10496 17800 -576 ) ( 10496 17800 -592 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10504 17800 -576 ) ( 10112 17800 -576 ) ( 10112 17800 -592 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17800 -576 ) ( 10112 17792 -576 ) ( 10112 17792 -592 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 10496 17408 -768 ) ( 10112 17408 -768 ) ( 10112 17392 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17384 -320 ) ( 10112 17400 -320 ) ( 10496 17400 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17400 -544 ) ( 10496 17400 -544 ) ( 10496 17400 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17392 -544 ) ( 10496 17408 -544 ) ( 10496 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17408 -544 ) ( 10112 17408 -544 ) ( 10112 17408 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 10112 17408 -544 ) ( 10112 17392 -544 ) ( 10112 17392 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 10568 17784 -768 ) ( 10496 17784 -768 ) ( 10496 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17408 -320 ) ( 10496 17784 -320 ) ( 10568 17784 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17408 -320 ) ( 10568 17408 -320 ) ( 10568 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10504 17400 -320 ) ( 10504 17776 -320 ) ( 10504 17776 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10568 17792 -320 ) ( 10496 17792 -320 ) ( 10496 17792 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17784 -320 ) ( 10496 17408 -320 ) ( 10496 17408 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 10112 17792 -768 ) ( 10072 17792 -768 ) ( 10072 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10072 17408 -320 ) ( 10072 17792 -320 ) ( 10112 17792 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10072 17408 -320 ) ( 10112 17408 -320 ) ( 10112 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17408 -320 ) ( 10112 17792 -320 ) ( 10112 17792 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 10112 17792 -320 ) ( 10072 17792 -320 ) ( 10072 17792 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10104 17792 -320 ) ( 10104 17408 -320 ) ( 10104 17408 -768 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 10496 17792 -320 ) ( 10112 17792 -320 ) ( 10112 17408 -320 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 10112 17408 -312 ) ( 10112 17792 -312 ) ( 10496 17792 -312 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17408 -232 ) ( 10496 17408 -232 ) ( 10496 17408 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17408 -232 ) ( 10496 17792 -232 ) ( 10496 17792 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17792 -232 ) ( 10112 17792 -232 ) ( 10112 17792 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17792 -232 ) ( 10112 17408 -232 ) ( 10112 17408 -320 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 10496 17792 -776 ) ( 10112 17792 -776 ) ( 10112 17408 -776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17408 -768 ) ( 10112 17792 -768 ) ( 10496 17792 -768 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 10112 17408 -768 ) ( 10496 17408 -768 ) ( 10496 17408 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17408 -768 ) ( 10496 17792 -768 ) ( 10496 17792 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10496 17792 -768 ) ( 10112 17792 -768 ) ( 10112 17792 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 10112 17792 -768 ) ( 10112 17408 -768 ) ( 10112 17408 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"origin" "10312 17600 -480" +"classname" "info_player_deathmatch" +} +{ +"light" "1000" +"origin" "10240 17608 -464" +"classname" "light" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/snap_plane/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/snap_plane/README.txt new file mode 100644 index 00000000..d66196be --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/snap_plane/README.txt @@ -0,0 +1,45 @@ +DESCRIPTION OF PROBLEM: +======================= + +The example map, maps/snap_plane.map, contains an example of some bugs. +The green brush with the red face is transformed into something totally +unexpected. + +To trigger the bug, compile the map; you don't need -vis or -light. Only +-bsp (the first q3map2 stage) is necessary to trigger the bug. The only +entities in the map are a light and a info_player_deathmatch, so the map will +compile for any Q3 mod. + + +SOLUTION TO PROBLEM: +==================== + +I actually came up with this regression test after reading the code to +SnapPlane() and SnapNormal(). I decided to make this map as a test of +whether or not I understand how the code is broken. Sure enough, the map +is broken in the same way that I would expect it to be broken. + +The problem is that the red face of the green brush in the center of the room +is very close to being axially aligned, but not quite. This plane will +therefore be "snapped" to become axial. This is not the problem. The +problem is that after the snap, the plane will be shifted a great deal, +and the corner of the green brush will no longer come even close to meeting +the corner of the other cube brush next to it (the two corners of the two +brushes will drift apart a great deal). + +If you study the legacy SnapPlane() code, you will see that planes are +defined as a unit normal and distance from origin. Well, because +of the position of this brush on the side of the world extents (far from +the original), the snap will cause drastic effects on the points that the +plane was supposed to approximate. + +Another problem with SnapPlane() is that SnapNormal() snaps too liberally. +Once SnapNormal() is changed to only snap normals that are REALLY close +to axial (and not anything within 0.25 degrees), this bug will no longer +appear, but the SnapPlane() problem will still be present. So, this +regression test should be fixed BEFORE SnapNormal() is fixed, otherwise +create another regression test with a red face that is much much closer to +being axially aligned. We want to make sure that SnapPlane() is fixed when +things actually do get snapped. + +The code to address these issues is currently being worked on. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/snap_plane/maps/snap_plane.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/snap_plane/maps/snap_plane.map new file mode 100644 index 00000000..c2b490c5 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/snap_plane/maps/snap_plane.map @@ -0,0 +1,78 @@ +{ +"classname" "worldspawn" +{ +( -54784 5760 -64 ) ( -54976 5760 -64 ) ( -54976 5632 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -54976 5632 0 ) ( -54976 5760 0 ) ( -54784 5760 0 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -54976 5632 0 ) ( -54784 5632 0 ) ( -54784 5632 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -54784 5632 0 ) ( -54784 5760 0 ) ( -54784 5760 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -54784 5760 0 ) ( -54976 5760 0 ) ( -54976 5760 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -54976 5760 0 ) ( -54976 5632 0 ) ( -54976 5632 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -53808 5616 -64 ) ( -55064 5616 -64 ) ( -55064 4944 -64 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -55072 4944 0 ) ( -55072 5616 0 ) ( -53816 5616 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -55040 4096 8 ) ( -53784 4096 8 ) ( -53784 4096 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -54272 4936 8 ) ( -54272 5608 8 ) ( -54272 5608 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -53816 5632 8 ) ( -55072 5632 8 ) ( -55072 5632 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -54784 5592 8 ) ( -54784 4920 8 ) ( -54784 4920 0 ) radiant_regression_tests/green 0 0 0 0.500000 0.500000 0 0 0 +( -54528 5632 -64 ) ( -54272 5631 -64 ) ( -54528 5632 0 ) radiant_regression_tests/red 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -54200 5904 -128 ) ( -55032 5904 -128 ) ( -55032 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55024 5824 192 ) ( -55024 5904 192 ) ( -54192 5904 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55040 5824 0 ) ( -54208 5824 0 ) ( -54208 5824 -64 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -54208 5824 0 ) ( -54208 5904 0 ) ( -54208 5904 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54200 5832 0 ) ( -55032 5832 0 ) ( -55032 5832 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55040 5904 0 ) ( -55040 5824 0 ) ( -55040 5824 -64 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -54144 5824 -128 ) ( -54208 5824 -128 ) ( -54208 5424 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54208 5424 192 ) ( -54208 5824 192 ) ( -54144 5824 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54160 4032 192 ) ( -54096 4032 192 ) ( -54096 4032 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54200 5424 192 ) ( -54200 5824 192 ) ( -54200 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54144 5824 192 ) ( -54208 5824 192 ) ( -54208 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54208 5824 192 ) ( -54208 5424 192 ) ( -54208 5424 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( -54208 4032 -128 ) ( -54760 4032 -128 ) ( -54760 3944 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54760 3944 192 ) ( -54760 4032 192 ) ( -54208 4032 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54752 4024 192 ) ( -54200 4024 192 ) ( -54200 4024 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54208 3944 192 ) ( -54208 4032 192 ) ( -54208 4032 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54208 4032 192 ) ( -54760 4032 192 ) ( -54760 4032 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -55040 4016 192 ) ( -55040 3928 192 ) ( -55040 3928 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -55040 5824 -128 ) ( -55256 5824 -128 ) ( -55256 5256 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55256 5256 192 ) ( -55256 5824 192 ) ( -55040 5824 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55256 4032 192 ) ( -55040 4032 192 ) ( -55040 4032 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55040 5256 192 ) ( -55040 5824 192 ) ( -55040 5824 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -55040 5824 192 ) ( -55256 5824 192 ) ( -55256 5824 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55048 5808 192 ) ( -55048 5240 192 ) ( -55048 5240 -128 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -54208 4032 192 ) ( -55040 4032 192 ) ( -55040 4024 192 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -55016 4024 200 ) ( -55016 4032 200 ) ( -54184 4032 200 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55040 4032 296 ) ( -54208 4032 296 ) ( -54208 4032 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54208 4024 296 ) ( -54208 4032 296 ) ( -54208 4032 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54200 5824 296 ) ( -55032 5824 296 ) ( -55032 5824 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55040 4032 296 ) ( -55040 4024 296 ) ( -55040 4024 192 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( -54192 4560 -136 ) ( -55024 4560 -136 ) ( -55024 4552 -136 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55040 4024 -128 ) ( -55040 4032 -128 ) ( -54208 4032 -128 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( -55040 4032 -128 ) ( -54208 4032 -128 ) ( -54208 4032 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54208 4024 -128 ) ( -54208 4032 -128 ) ( -54208 4032 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -54208 5824 -120 ) ( -55040 5824 -120 ) ( -55040 5824 -248 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( -55040 4032 -128 ) ( -55040 4024 -128 ) ( -55040 4024 -256 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"light" "1000" +"origin" "-54664 5696 40" +"classname" "light" +} +{ +"angle" "360" +"origin" "-54840 5696 88" +"classname" "info_player_deathmatch" +} diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/sparkly_seam/README.txt b/misc/mediasource/netradiant-src/regression_tests/q3map2/sparkly_seam/README.txt new file mode 100644 index 00000000..3c54feb5 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/sparkly_seam/README.txt @@ -0,0 +1,21 @@ +DESCRIPTION OF PROBLEM: +======================= + +The example map, maps/sparkly_seam.map, contains two triangular brushes near +the side of the room. The seam between these two brushes "sparkles" even +though the endpoints of the edges are exactly the same. + +To trigger the bug, compile the map; you don't need -vis or -light. Only +-bsp (the first q3map2 stage) is necessary to trigger the bug. The only +entities in the map are a light and a info_player_deathmatch, so the map will +compile for any Q3 mod. + + +SOLUTION TO PROBLEM: +==================== + +None yet. The problem is likely caused by sloppy math operations (significant +loss of precision). This bug pops in and out of existence with every other +commit at the moment. The problem is likely caused by the operations in the +brush winding computation (where the planes are intersected with each other). +I have not gotten around to addressing that code yet. diff --git a/misc/mediasource/netradiant-src/regression_tests/q3map2/sparkly_seam/maps/sparkly_seam.map b/misc/mediasource/netradiant-src/regression_tests/q3map2/sparkly_seam/maps/sparkly_seam.map new file mode 100644 index 00000000..4b021372 --- /dev/null +++ b/misc/mediasource/netradiant-src/regression_tests/q3map2/sparkly_seam/maps/sparkly_seam.map @@ -0,0 +1,75 @@ +{ +"classname" "worldspawn" +{ +( 6784 16015 -2048 ) ( 6144 15958 -2048 ) ( 6784 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6784 16015 -1788 ) ( 6784 16015 -2048 ) ( 6784 15936 -1792 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 15958 -1471 ) ( 6144 15958 -2048 ) ( 6784 16015 -1788 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6784 15936 -1792 ) ( 6784 15936 -2048 ) ( 6144 15958 -1471 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6784 15936 -1792 ) ( 6144 15958 -1471 ) ( 6784 16015 -1788 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 6784 15936 -2048 ) ( 6144 15958 -2048 ) ( 6144 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6784 15936 -1792 ) ( 6144 15936 -2048 ) ( 6144 15936 -1472 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 15936 -1472 ) ( 6144 15958 -2048 ) ( 6144 15958 -1471 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 15958 -1471 ) ( 6784 15936 -2048 ) ( 6784 15936 -1792 ) common/caulk 0 0 0 0.500000 0.500000 134217728 4 0 +( 6144 15936 -1472 ) ( 6144 15958 -1471 ) ( 6784 15936 -1792 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 134217728 0 0 +} +{ +( 6160 16432 -2048 ) ( 6048 16432 -2048 ) ( 6048 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6128 15936 -896 ) ( 6128 16432 -896 ) ( 6240 16432 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6032 15936 160 ) ( 6144 15936 160 ) ( 6144 15936 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 160 ) ( 6144 16432 160 ) ( 6144 16432 -3552 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6112 16896 160 ) ( 6000 16896 160 ) ( 6000 16896 -3552 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 16424 168 ) ( 6136 15928 168 ) ( 6136 15928 -3544 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6144 16672 -2048 ) ( 6136 16672 -2048 ) ( 6136 16176 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 16192 -896 ) ( 6136 16688 -896 ) ( 6144 16688 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6136 15936 -1280 ) ( 6144 15936 -1280 ) ( 6144 15936 -1760 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6792 16160 -1296 ) ( 6792 16656 -1296 ) ( 6792 16656 -1776 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -1312 ) ( 6136 16896 -1312 ) ( 6136 16896 -1792 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16672 -1296 ) ( 6784 16176 -1296 ) ( 6784 16176 -1776 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +} +{ +( 6784 15936 -2048 ) ( 6144 15936 -2048 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15880 -896 ) ( 6144 15936 -896 ) ( 6784 15936 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15928 -896 ) ( 6784 15928 -896 ) ( 6784 15928 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15880 -896 ) ( 6784 15936 -896 ) ( 6784 15936 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15936 -896 ) ( 6144 15936 -896 ) ( 6144 15936 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 15936 -896 ) ( 6144 15880 -896 ) ( 6144 15880 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6784 16960 -2048 ) ( 6144 16960 -2048 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -896 ) ( 6144 16960 -896 ) ( 6784 16960 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -896 ) ( 6784 16896 -896 ) ( 6784 16896 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6784 16896 -896 ) ( 6784 16960 -896 ) ( 6784 16960 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16904 -896 ) ( 6144 16904 -896 ) ( 6144 16904 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16960 -896 ) ( 6144 16896 -896 ) ( 6144 16896 -2048 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6784 16896 -896 ) ( 6144 16896 -896 ) ( 6144 16536 -896 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 16552 -888 ) ( 6144 16912 -888 ) ( 6784 16912 -888 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -744 ) ( 6784 15936 -744 ) ( 6784 15936 -856 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16536 -784 ) ( 6784 16896 -784 ) ( 6784 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -784 ) ( 6144 16896 -784 ) ( 6144 16896 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16896 -784 ) ( 6144 16536 -784 ) ( 6144 16536 -896 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +{ +( 6784 16584 -2056 ) ( 6144 16584 -2056 ) ( 6144 15976 -2056 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 15936 -2048 ) ( 6144 16544 -2048 ) ( 6784 16544 -2048 ) radiant_regression_tests/tile 0 0 0 0.500000 0.500000 0 0 0 +( 6144 15936 -2048 ) ( 6784 15936 -2048 ) ( 6784 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 15936 -2048 ) ( 6784 16544 -2048 ) ( 6784 16544 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6784 16896 -2048 ) ( 6144 16896 -2048 ) ( 6144 16896 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +( 6144 16544 -2048 ) ( 6144 15936 -2048 ) ( 6144 15936 -2376 ) common/caulk 0 0 0 0.500000 0.500000 0 4 0 +} +} +{ +"angle" "180" +"origin" "6608 15968 -1608" +"classname" "info_player_deathmatch" +} +{ +"light" "1000" +"origin" "6440 16160 -1192" +"classname" "light" +} diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Info.plist b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Info.plist new file mode 100644 index 00000000..81e377d1 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Info.plist @@ -0,0 +1,18 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + netradiant.sh + CFBundleIconFile + NetRadiant + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 1.5.0 + + diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.conf b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.conf new file mode 100644 index 00000000..86dc8af2 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.conf @@ -0,0 +1,150 @@ + + + + + + + + + + /usr/share/fonts + /usr/X11/lib/X11/fonts /Library/Fonts /Network/Library/Fonts /System/Library/Fonts /opt/local/share/fonts + ~/.fonts + + + + + mono + + + monospace + + + + + + + sans serif + + + sans-serif + + + + + + + sans + + + sans-serif + + + + + conf.d + + + + ~/.fontconfig + + + + + 0x0020 + 0x00A0 + 0x00AD + 0x034F + 0x0600 + 0x0601 + 0x0602 + 0x0603 + 0x06DD + 0x070F + 0x115F + 0x1160 + 0x1680 + 0x17B4 + 0x17B5 + 0x180E + 0x2000 + 0x2001 + 0x2002 + 0x2003 + 0x2004 + 0x2005 + 0x2006 + 0x2007 + 0x2008 + 0x2009 + 0x200A + 0x200B + 0x200C + 0x200D + 0x200E + 0x200F + 0x2028 + 0x2029 + 0x202A + 0x202B + 0x202C + 0x202D + 0x202E + 0x202F + 0x205F + 0x2060 + 0x2061 + 0x2062 + 0x2063 + 0x206A + 0x206B + 0x206C + 0x206D + 0x206E + 0x206F + 0x2800 + 0x3000 + 0x3164 + 0xFEFF + 0xFFA0 + 0xFFF9 + 0xFFFA + 0xFFFB + + + + 30 + + + + diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.dtd b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.dtd new file mode 100644 index 00000000..cbdfdab3 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/fonts.dtd @@ -0,0 +1,224 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/gdk-pixbuf.loaders b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/gdk-pixbuf.loaders new file mode 100644 index 00000000..f8852a26 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/gdk-pixbuf.loaders @@ -0,0 +1,12 @@ +# GdkPixbuf Image Loader Modules file +# Automatically generated file, do not edit +# Created by gdk-pixbuf-query-loaders from gtk+-2.6.10 +# +# LoaderDir = /sw.haha/lib/gtk-2.0/2.4.0/loaders +# +"./libpixbufloader-bmp.so" +"bmp" 5 "gtk20" "The BMP image format" +"image/bmp" "image/x-bmp" "image/x-MS-bmp" "" +"bmp" "" +"BM" "" 100 + diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pango.modules b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pango.modules new file mode 100644 index 00000000..9eecea48 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pango.modules @@ -0,0 +1,7 @@ +# Pango Modules file +# Automatically generated file, do not edit +# +# ModulesPath = /sw.haha/lib/pango/1.4.0/modules +# +./pango-basic-fc.so BasicScriptEngineFc PangoEngineShape PangoRenderFc armenian:* bopomofo:* cherokee:* coptic:* cyrillic:* deseret:* ethiopic:* georgian:* gothic:* greek:* han:* hiragana:* katakana:* latin:* ogham:* old-italic:* runic:* canadian-aboriginal:* yi:* braille:* cypriot:* limbu:* osmanya:* shavian:* linear-b:* ugaritic:* common: +./pango-basic-x.so BasicScriptEngineX PangoEngineShape PangoRenderX common: diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangorc b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangorc new file mode 100644 index 00000000..282e977e --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangorc @@ -0,0 +1,5 @@ +[Pango] +ModuleFiles = ./pango.modules + +[PangoX] +AliasFiles = ./pangox.aliases diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangox.aliases b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangox.aliases new file mode 100644 index 00000000..9b41aa75 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/MacOS/install/pangox.aliases @@ -0,0 +1,220 @@ +# File defining aliases of PangoFontDescription to X font set +# +# family style variant weight stretch XLFD + +sans normal normal normal normal \ + "-*-helvetica-medium-r-normal--*-*-*-*-*-*-*-*,\ + -*-gulim-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +sans italic normal normal normal \ + "-*-helvetica-medium-o-normal--*-*-*-*-*-*-*-*,\ + -*-gulim-medium-o-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +sans normal normal bold normal \ + "-*-helvetica-bold-r-normal--*-*-*-*-*-*-*-*,\ + -*-gulim-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +sans italic normal bold normal \ + "-*-helvetica-bold-o-normal--*-*-*-*-*-*-*-*,\ + -*-gulim-bold-o-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + + +serif normal normal normal normal \ + "-*-times-medium-r-normal--*-*-*-*-*-*-*-*,\ + -*-batang-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +serif italic normal normal normal \ + "-*-times-medium-i-normal--*-*-*-*-*-*-*-*,\ + -*-batang-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +serif normal normal bold normal \ + "-*-times-bold-r-normal--*-*-*-*-*-*-*-*,\ + -*-batang-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +serif italic normal bold normal \ + "-*-times-bold-i-normal--*-*-*-*-*-*-*-*,\ + -*-batang-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +monospace normal normal normal normal \ + "-*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -*-dotum-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +monospace italic normal normal normal \ + "-*-fixed-medium-i-normal--*-*-*-*-*-*-*-*,\ + -*-dotum-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +monospace normal normal bold normal \ + "-*-fixed-bold-r-normal--*-*-*-*-*-*-*-*,\ + -*-dotum-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" + +monospace italic normal bold normal \ + "-*-fixed-bold-i-normal--*-*-*-*-*-*-*-*,\ + -*-dotum-bold-r-normal--*-*-*-*-*-*-ksc5601.1987-0,\ + -*-clearlyu-medium-r-normal--*-*-*-*-*-*-iso10646-1,\ + -*-fixed-medium-r-normal--*-*-*-*-*-*-*-*,\ + -kaist-iyagi-bold-r-normal--*-*-*-*-*-*-johab-1,\ + -*-song ti-medium-r-normal--*-*-*-*-*-*-*-*,\ + -freetype-unitamil-medium-r-normal--*-*-*-*-*-*-iso10646-tam,\ + -*-devanagari-medium-r-normal--*-*-*-*-*-*-iso10646-dev,\ + -*-gujarati-medium-r-normal--*-*-*-*-*-*-iso10646-guj,\ + -*-gurmukhi-medium-r-normal--*-*-*-*-*-*-iso10646-gur,\ + -*-bengali-medium-r-normal--*-*-*-*-*-*-iso10646-bng,\ + -*-kannada-medium-r-normal--*-*-*-*-*-*-iso10646-kan,\ + -*-burmese-medium-r-normal--*-*-*-*-*-*-iso10646-brm,\ + -*-buginese-medium-r-normal--*-*-*-*-*-*-iso10646-bgn,\ + -*-oriya-medium-r-normal--*-*-*-*-*-*-iso10646-ori,\ + -daewoo-mincho-medium-r-normal--*-*-*-*-*-*-ksc5601.1987-0" diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/PkgInfo b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/PkgInfo new file mode 100644 index 00000000..bd04210f --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/PkgInfo @@ -0,0 +1 @@ +APPL???? \ No newline at end of file diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/English.lproj/InfoPlist.strings b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/English.lproj/InfoPlist.strings new file mode 100644 index 00000000..4a182e50 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/English.lproj/InfoPlist.strings differ diff --git a/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/NetRadiant.icns b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/NetRadiant.icns new file mode 100644 index 00000000..339e718d Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/osx/NetRadiant.app/Contents/Resources/NetRadiant.icns differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools-src/splash.map b/misc/mediasource/netradiant-src/setup/data/tools-src/splash.map new file mode 100644 index 00000000..1594ee88 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools-src/splash.map @@ -0,0 +1,558 @@ +{ +"classname" "worldspawn" +{ +( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 1280 4096 ) ( 1280 -1280 4096 ) ( 1280 1280 4096 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +} +{ +( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 1280 4096 0 ) ( -1280 4096 512 ) ( 1280 4096 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +} +{ +( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 4096 -1280 512 ) ( 4096 1280 0 ) ( 4096 1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +} +{ +( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 1280 -4096 ) ( 1280 -1280 -4096 ) ( -1280 -1280 -4096 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +} +{ +( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 4352 1280 512 ) ( 4352 1280 0 ) ( 4352 -1280 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 1280 -4096 0 ) ( -1280 -4096 512 ) ( -1280 -4096 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +} +{ +( 1280 1280 4352 ) ( 1280 -1280 4352 ) ( -1280 1280 4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( 1280 4352 512 ) ( -1280 4352 512 ) ( 1280 4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -1280 -4352 ) ( 1280 -1280 -4352 ) ( -1280 1280 -4352 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -1280 -4352 0 ) ( -1280 -4352 512 ) ( 1280 -4352 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -4352 -1536 0 ) ( -4352 1024 0 ) ( -4352 -1536 512 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +( -4096 -1536 512 ) ( -4096 1024 0 ) ( -4096 -1536 0 ) common/caulk 0 0 0 0.5 0.5 0 0 0 +} +} +{ +"classname" "func_group" +{ +( -32 40 80 ) ( -40 40 72 ) ( -40 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 56 88 ) ( -40 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 32 68 ) ( -40 40 76 ) ( -40 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 52 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 40 32 ) ( -40 40 48 ) ( -40 104 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -104 40 32 ) ( -104 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 40 96 ) ( -48 40 80 ) ( -40 48 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -48 56 88 ) ( -48 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 68 ) ( -48 40 76 ) ( -48 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 48 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 32 80 ) ( -40 32 80 ) ( -40 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 32 68 ) ( -40 40 76 ) ( -40 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 40 32 ) ( -40 40 48 ) ( -40 104 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 40 96 ) ( -48 40 80 ) ( -40 48 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 80 ) ( -48 32 80 ) ( -48 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -48 72 88 ) ( -48 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 24 96 ) ( -104 24 96 ) ( -104 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 24 32 ) ( -40 24 48 ) ( -40 88 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 48 ) ( -40 52 32 ) ( -48 60 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 68 ) ( -48 40 76 ) ( -48 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 32 96 ) ( -32 40 80 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 32 80 ) ( -40 48 96 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 56 88 ) ( -40 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 40 32 ) ( -40 40 48 ) ( -40 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 80 ) ( -96 48 96 ) ( -96 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 76 ) ( -60 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -32 40 80 ) ( -40 40 80 ) ( -40 40 72 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 96 ) ( -32 40 80 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 32 80 ) ( -40 32 80 ) ( -40 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 40 32 ) ( -40 40 48 ) ( -40 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 76 ) ( -60 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -32 40 80 ) ( -40 40 80 ) ( -40 40 72 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 96 ) ( -32 40 80 ) ( -40 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 40 32 ) ( -40 40 48 ) ( -40 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 76 ) ( -60 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 96 ) ( -40 68 80 ) ( -32 60 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 96 64 ) ( -40 64 96 ) ( -40 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 64 96 ) ( -40 32 64 ) ( -40 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 24 32 ) ( -40 24 48 ) ( -40 88 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -56 60 80 ) ( -56 60 96 ) ( -96 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 48 ) ( -40 52 32 ) ( -48 60 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -48 32 64 ) ( -48 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -48 72 88 ) ( -48 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 68 48 ) ( -40 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 68 56 ) ( -60 60 76 ) ( -60 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 68 96 ) ( -40 68 80 ) ( -32 60 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 96 64 ) ( -40 96 64 ) ( -40 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 68 48 ) ( -40 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 68 56 ) ( -60 64 76 ) ( -60 64 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -32 32 80 ) ( -32 32 96 ) ( -32 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 96 ) ( -40 68 80 ) ( -32 60 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 92 48 ) ( -40 68 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 64 96 ) ( -40 64 96 ) ( -40 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 32 68 ) ( -40 32 68 ) ( -40 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 24 32 ) ( -40 24 48 ) ( -40 88 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -56 60 80 ) ( -56 60 96 ) ( -96 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 48 ) ( -40 52 32 ) ( -48 60 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -48 64 96 ) ( -48 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -48 72 88 ) ( -48 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 68 ) ( -48 32 68 ) ( -48 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 68 32 ) ( -40 68 48 ) ( -40 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 64 56 ) ( -60 60 76 ) ( -60 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 96 32 ) ( -40 120 32 ) ( -40 96 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 88 96 ) ( -40 96 96 ) ( -40 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 96 80 ) ( -40 80 96 ) ( -40 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 88 76 ) ( -40 88 68 ) ( -40 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -40 32 32 ) ( -40 32 48 ) ( -40 96 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 96 56 ) ( -60 88 76 ) ( -60 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -32 52 80 ) ( -32 52 96 ) ( -32 116 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 88 96 ) ( -32 80 80 ) ( -40 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 56 88 ) ( -40 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 88 76 ) ( -40 88 76 ) ( -40 88 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 96 68 ) ( -40 96 68 ) ( -40 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 88 80 ) ( -76 80 80 ) ( -64 80 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -32 52 80 ) ( -32 52 96 ) ( -32 116 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 88 96 ) ( -32 80 80 ) ( -40 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 96 80 ) ( -40 80 96 ) ( -40 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -32 72 88 ) ( -40 72 88 ) ( -40 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -88 40 48 ) ( -48 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 32 68 ) ( -96 40 76 ) ( -96 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 52 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 40 32 ) ( -88 40 48 ) ( -72 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 104 32 ) ( -88 104 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 48 96 ) ( -88 48 80 ) ( -80 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 72 88 ) ( -88 56 88 ) ( -88 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 68 ) ( -88 40 76 ) ( -88 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 48 80 ) ( -76 40 80 ) ( -64 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 52 48 ) ( -80 60 32 ) ( -88 52 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 60 32 ) ( -88 60 48 ) ( -88 -4 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -72 -4 96 ) ( -88 -4 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 68 ) ( -88 40 76 ) ( -88 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 32 68 ) ( -96 40 76 ) ( -96 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 104 32 ) ( -88 104 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 48 96 ) ( -88 48 80 ) ( -80 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 80 ) ( -88 32 80 ) ( -88 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 40 96 ) ( -88 32 80 ) ( -96 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 80 ) ( -96 48 96 ) ( -96 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 56 ) ( -68 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 40 96 ) ( -88 32 80 ) ( -96 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 56 ) ( -68 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 40 96 ) ( -88 32 80 ) ( -96 40 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 56 ) ( -68 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -88 68 96 ) ( -48 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 52 48 ) ( -80 60 32 ) ( -88 52 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 60 32 ) ( -88 60 48 ) ( -88 -4 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -72 60 80 ) ( -72 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 64 96 ) ( -88 32 64 ) ( -88 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 68 76 ) ( -68 60 56 ) ( -68 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 80 ) ( -48 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -88 68 96 ) ( -48 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 96 68 ) ( -96 88 76 ) ( -96 96 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 68 76 ) ( -68 64 56 ) ( -68 64 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 52 48 ) ( -80 60 32 ) ( -88 52 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 60 32 ) ( -88 60 48 ) ( -88 -4 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -72 60 80 ) ( -72 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 64 96 ) ( -88 64 96 ) ( -88 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 32 68 ) ( -88 32 68 ) ( -88 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 64 76 ) ( -68 60 56 ) ( -68 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 80 ) ( -48 60 96 ) ( -88 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 64 32 ) ( -88 40 48 ) ( -88 64 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 32 68 ) ( -96 32 68 ) ( -96 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 88 96 ) ( -96 88 80 ) ( -88 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 96 76 ) ( -68 88 56 ) ( -68 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 88 80 ) ( -48 88 96 ) ( -88 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 96 68 ) ( -96 96 68 ) ( -96 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 88 80 ) ( -76 76 80 ) ( -64 76 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -72 88 80 ) ( -72 88 96 ) ( -88 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 88 32 ) ( -88 88 48 ) ( -88 24 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 80 48 ) ( -80 88 32 ) ( -88 80 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 72 88 ) ( -88 56 88 ) ( -88 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 96 68 ) ( -88 96 68 ) ( -88 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 88 80 ) ( -76 80 80 ) ( -64 80 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 96 80 ) ( -96 96 96 ) ( -96 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 92 32 ) ( -88 68 48 ) ( -88 92 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 96 68 ) ( -96 96 68 ) ( -96 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 88 32 ) ( -88 88 48 ) ( -88 24 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 80 48 ) ( -80 88 32 ) ( -88 80 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 96 80 ) ( -88 80 96 ) ( -88 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 72 88 ) ( -88 72 88 ) ( -88 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 32 ) ( -96 32 32 ) ( -80 32 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 68 ) ( -96 40 76 ) ( -96 32 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 40 80 ) ( -64 32 80 ) ( -76 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 96 32 ) ( -96 32 32 ) ( -80 32 32 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -80 96 80 ) ( -80 96 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 96 80 ) ( -80 96 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 68 ) ( -96 88 76 ) ( -96 96 68 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 68 ) ( -96 32 68 ) ( -96 40 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 96 80 ) ( -80 96 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 68 ) ( -96 96 68 ) ( -96 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 96 80 ) ( -64 88 80 ) ( -76 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 80 ) ( -96 48 96 ) ( -96 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 56 88 ) ( -96 72 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 32 80 ) ( -96 32 80 ) ( -96 48 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 40 80 ) ( -76 32 80 ) ( -64 32 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -96 32 80 ) ( -96 32 96 ) ( -80 32 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 40 32 ) ( -48 40 48 ) ( -88 40 48 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 40 76 ) ( -68 32 76 ) ( -68 32 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 40 56 ) ( -60 32 56 ) ( -60 32 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 64 96 ) ( -96 96 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 32 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 72 88 ) ( -96 72 88 ) ( -96 56 88 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 68 76 ) ( -68 60 76 ) ( -68 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 68 56 ) ( -60 60 56 ) ( -60 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -88 68 80 ) ( -48 68 96 ) ( -88 68 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 64 ) ( -96 96 64 ) ( -96 64 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 68 76 ) ( -68 64 76 ) ( -68 64 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 68 56 ) ( -60 64 56 ) ( -60 64 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -80 32 96 ) ( -96 32 96 ) ( -96 96 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -48 60 80 ) ( -88 60 96 ) ( -48 60 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 64 96 ) ( -96 64 96 ) ( -96 32 64 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 64 76 ) ( -68 60 76 ) ( -68 60 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 64 56 ) ( -60 60 56 ) ( -60 60 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +{ +( -48 88 80 ) ( -88 88 96 ) ( -48 88 96 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -40 96 80 ) ( -96 80 96 ) ( -96 96 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -76 96 80 ) ( -76 88 80 ) ( -64 88 80 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -68 96 76 ) ( -68 88 76 ) ( -68 88 56 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +( -60 96 56 ) ( -60 88 56 ) ( -60 88 76 ) eX/eXmetalBase05Rust 0 0 0 0.25 0.25 0 0 0 +} +} +{ +"classname" "info_player_deathmatch" +"origin" "72 -68 -144" +"angle" "180" +} +{ +"classname" "light" +"origin" "0 0 -3000" +"light" "80000" +"_color" "0.5 0.5 1" +} +{ +"classname" "light" +"origin" "3000 0 0" +"light" "80000" +"_color" "0.5 1 0.5" +} +{ +"classname" "light" +"origin" "0 -3000 0" +"light" "80000" +"_color" "1 0.5 0.5" +} +{ +"classname" "func_group" +{ +( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -96 96 160 ) ( 96 -96 160 ) ( 96 96 160 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +} +{ +( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -112 80 -160 ) ( 80 -112 -160 ) ( -112 -112 -160 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +} +{ +( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( 96 -160 -32 ) ( -96 -160 32 ) ( -96 -160 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +} +{ +( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -160 -96 32 ) ( -160 96 -32 ) ( -160 -96 -32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +} +{ +( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( -168 -96 -32 ) ( -168 96 -32 ) ( -168 -96 32 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +( 96 160 -24 ) ( -96 160 40 ) ( 96 160 40 ) eX/eX_cretefloor_01 0 0 0 0.5 0.5 0 0 0 +} +{ +( 96 96 168 ) ( 96 -96 168 ) ( -96 96 168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( 96 168 40 ) ( -96 168 40 ) ( 96 168 -24 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( 168 104 32 ) ( 168 104 -32 ) ( 168 -88 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -112 -112 -168 ) ( 80 -112 -168 ) ( -112 80 -168 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( -96 -168 -32 ) ( -96 -168 32 ) ( 96 -168 -32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +( 160 -88 32 ) ( 160 104 -32 ) ( 160 104 32 ) eX/eX_cretebase_01 0 0 0 0.5 0.5 0 0 0 +} +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools-src/splash.xcf b/misc/mediasource/netradiant-src/setup/data/tools-src/splash.xcf new file mode 100644 index 00000000..8001037a Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools-src/splash.xcf differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/black.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/black.bmp new file mode 100644 index 00000000..8fc59ba1 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/black.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipx.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipx.bmp new file mode 100644 index 00000000..48ee0dbc Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipx.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipy.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipy.bmp new file mode 100644 index 00000000..d7408773 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipy.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipz.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipz.bmp new file mode 100644 index 00000000..017c33e9 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_flipz.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatex.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatex.bmp new file mode 100644 index 00000000..c7e55053 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatex.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatey.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatey.bmp new file mode 100644 index 00000000..e50e5d6d Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatey.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatez.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatez.bmp new file mode 100644 index 00000000..52ab554a Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/brush_rotatez.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_bevel.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_bevel.bmp new file mode 100644 index 00000000..3bb4186e Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_bevel.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_cylinder.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_cylinder.bmp new file mode 100644 index 00000000..21969267 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_cylinder.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_endcap.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_endcap.bmp new file mode 100644 index 00000000..e6cea655 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_endcap.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_ibevel.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_ibevel.bmp new file mode 100644 index 00000000..b1fa49b3 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_ibevel.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_iendcap.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_iendcap.bmp new file mode 100644 index 00000000..da1f5b66 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/cap_iendcap.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/console.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/console.bmp new file mode 100644 index 00000000..7fe64b0e Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/console.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/curve_cap.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/curve_cap.bmp new file mode 100644 index 00000000..574e7611 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/curve_cap.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/dontselectcurve.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/dontselectcurve.bmp new file mode 100644 index 00000000..a7b97954 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/dontselectcurve.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/dontselectmodel.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/dontselectmodel.bmp new file mode 100644 index 00000000..e81b1189 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/dontselectmodel.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/ellipsis.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/ellipsis.bmp new file mode 100644 index 00000000..a4360a9e Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/ellipsis.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/entities.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/entities.bmp new file mode 100644 index 00000000..ce3d8124 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/entities.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/file_open.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/file_open.bmp new file mode 100644 index 00000000..754f10fb Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/file_open.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/file_save.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/file_save.bmp new file mode 100644 index 00000000..651afb68 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/file_save.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/icon.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/icon.bmp new file mode 100644 index 00000000..01aec6ea Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/icon.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/lightinspector.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/lightinspector.bmp new file mode 100644 index 00000000..00b00a90 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/lightinspector.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/logo.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/logo.bmp new file mode 100644 index 00000000..ddbd3461 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/logo.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_edges.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_edges.bmp new file mode 100644 index 00000000..7b048f96 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_edges.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_faces.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_faces.bmp new file mode 100644 index 00000000..03d9f8c2 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_faces.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_vertices.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_vertices.bmp new file mode 100644 index 00000000..c434732e Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/modify_vertices.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/noFalloff.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/noFalloff.bmp new file mode 100644 index 00000000..e86d10c9 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/noFalloff.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/notex.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/notex.bmp new file mode 100644 index 00000000..b06664a7 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/notex.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_bend.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_bend.bmp new file mode 100644 index 00000000..af4fc94c Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_bend.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_drilldown.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_drilldown.bmp new file mode 100644 index 00000000..01ebcf39 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_drilldown.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_insdel.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_insdel.bmp new file mode 100644 index 00000000..b60b76b0 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_insdel.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_showboundingbox.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_showboundingbox.bmp new file mode 100644 index 00000000..357cfaf1 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_showboundingbox.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_weld.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_weld.bmp new file mode 100644 index 00000000..a0c99730 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_weld.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_wireframe.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_wireframe.bmp new file mode 100644 index 00000000..9804274f Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/patch_wireframe.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/popup_selection.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/popup_selection.bmp new file mode 100644 index 00000000..676c4d98 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/popup_selection.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/redo.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/redo.bmp new file mode 100644 index 00000000..32a373af Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/redo.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/refresh_models.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/refresh_models.bmp new file mode 100644 index 00000000..b6507f61 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/refresh_models.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelockx.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelockx.bmp new file mode 100644 index 00000000..61363da2 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelockx.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelocky.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelocky.bmp new file mode 100644 index 00000000..812394db Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelocky.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelockz.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelockz.bmp new file mode 100644 index 00000000..5692e4a7 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/scalelockz.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mouseresize.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mouseresize.bmp new file mode 100644 index 00000000..ca0c9ac3 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mouseresize.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mouserotate.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mouserotate.bmp new file mode 100644 index 00000000..7f18a561 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mouserotate.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mousescale.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mousescale.bmp new file mode 100644 index 00000000..d8f39024 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mousescale.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mousetranslate.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mousetranslate.bmp new file mode 100644 index 00000000..04962fde Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/select_mousetranslate.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_csgmerge.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_csgmerge.bmp new file mode 100644 index 00000000..fb5df4f9 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_csgmerge.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_csgsubtract.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_csgsubtract.bmp new file mode 100644 index 00000000..267d3749 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_csgsubtract.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_makehollow.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_makehollow.bmp new file mode 100644 index 00000000..8c5d60cd Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_makehollow.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall.bmp new file mode 100644 index 00000000..8d2c1043 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall_old.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall_old.bmp new file mode 100644 index 00000000..1f911e8c Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectcompletetall_old.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectinside.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectinside.bmp new file mode 100644 index 00000000..12b22afb Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectinside.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall.bmp new file mode 100644 index 00000000..d21ddc2c Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall_old.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall_old.bmp new file mode 100644 index 00000000..77b418be Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selectpartialtall_old.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selecttouching.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selecttouching.bmp new file mode 100644 index 00000000..e6d5c4b6 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/selection_selecttouching.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/shadernotex.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/shadernotex.bmp new file mode 100644 index 00000000..6be415e7 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/shadernotex.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/show_entities.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/show_entities.bmp new file mode 100644 index 00000000..9188bee6 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/show_entities.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/splash.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/splash.bmp new file mode 100644 index 00000000..a484997f Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/splash.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/texture_browser.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/texture_browser.bmp new file mode 100644 index 00000000..22f72506 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/texture_browser.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/texture_lock.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/texture_lock.bmp new file mode 100644 index 00000000..0a003bcf Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/texture_lock.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/textures_popup.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/textures_popup.bmp new file mode 100644 index 00000000..5333382f Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/textures_popup.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/undo.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/undo.bmp new file mode 100644 index 00000000..fd2b8392 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/undo.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cameratoggle.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cameratoggle.bmp new file mode 100644 index 00000000..4ec79ed6 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cameratoggle.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cameraupdate.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cameraupdate.bmp new file mode 100644 index 00000000..dbb11956 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cameraupdate.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_change.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_change.bmp new file mode 100644 index 00000000..977ee1e7 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_change.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_clipper.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_clipper.bmp new file mode 100644 index 00000000..606a2095 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_clipper.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cubicclipping.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cubicclipping.bmp new file mode 100644 index 00000000..16f7cb0e Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_cubicclipping.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_entity.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_entity.bmp new file mode 100644 index 00000000..851ec2c3 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/view_entity.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/white.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/white.bmp new file mode 100644 index 00000000..cbf038f7 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/white.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window1.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window1.bmp new file mode 100644 index 00000000..a8913c72 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window1.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window2.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window2.bmp new file mode 100644 index 00000000..6db9e565 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window2.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window3.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window3.bmp new file mode 100644 index 00000000..e81a299d Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window3.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window4.bmp b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window4.bmp new file mode 100644 index 00000000..d753945f Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/bitmaps/window4.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbfp1.cg b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbfp1.cg new file mode 100644 index 00000000..f535dbb2 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbfp1.cg @@ -0,0 +1,92 @@ +/// ============================================================================ +/* +Copyright (C) 2004 Robert Beckebans +Please see the file "AUTHORS" for a list of contributors + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + +#include "utils.cg" + +struct cg_vertex2fragment +{ + float4 position : TEXCOORD0; + float4 tex_diffuse_bump : TEXCOORD1; + float4 tex_specular : TEXCOORD2; + float4 tex_atten_xy_z : TEXCOORD3; + + float3 tangent : TEXCOORD4; + float3 binormal : TEXCOORD5; + float3 normal : TEXCOORD6; +}; + +struct cg_fragment2final +{ + float4 color : COLOR; +}; + + +cg_fragment2final main(cg_vertex2fragment IN, + uniform sampler2D diffusemap, + uniform sampler2D bumpmap, + uniform sampler2D specularmap, + uniform sampler2D attenuationmap_xy, + uniform sampler2D attenuationmap_z, + uniform float3 view_origin, + uniform float3 light_origin, + uniform float3 light_color, + uniform float bump_scale, + uniform float specular_exponent) +{ + cg_fragment2final OUT; + + // construct object-space-to-tangent-space 3x3 matrix + float3x3 rotation = float3x3(IN.tangent, IN.binormal, IN.normal); + + // compute view direction in tangent space + float3 V = normalize(mul(rotation, view_origin - IN.position.xyz)); + + // compute light direction in tangent space + float3 L = normalize(mul(rotation, (light_origin - IN.position.xyz))); + + // compute half angle in tangent space + float3 H = normalize(L + V); + + // compute normal in tangent space from bumpmap + float3 T = CG_Expand(tex2D(bumpmap, IN.tex_diffuse_bump.zw).xyz); + T.z *= bump_scale; + float3 N = normalize(T); + + // compute the diffuse term + float4 diffuse = tex2D(diffusemap, IN.tex_diffuse_bump.xy); + diffuse.rgb *= light_color * saturate(dot(N, L)); + + // compute the specular term + float3 specular = tex2D(specularmap, IN.tex_specular.xy).rgb * light_color * pow(saturate(dot(N, H)), specular_exponent); + + // compute attenuation + float3 attenuation_xy = tex2Dproj(attenuationmap_xy, float3(IN.tex_atten_xy_z.x, IN.tex_atten_xy_z.y, IN.tex_atten_xy_z.w)).rgb; + float3 attenuation_z = tex2D(attenuationmap_z, float2(IN.tex_atten_xy_z.z, 0)).rgb; + + // compute final color + OUT.color.rgba = diffuse; + OUT.color.rgb += specular; + OUT.color.rgb *= attenuation_xy; + OUT.color.rgb *= attenuation_z; + + return OUT; +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbvp1.cg b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbvp1.cg new file mode 100644 index 00000000..59a6fc73 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_XY_Z_arbvp1.cg @@ -0,0 +1,78 @@ +/// ============================================================================ +/* +Copyright (C) 2004 Robert Beckebans +Please see the file "AUTHORS" for a list of contributors + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + + +struct cg_app2vertex +{ + float4 position : POSITION; + float4 tex0 : ATTR8; + + float3 tangent : ATTR9; + float3 binormal : ATTR10; + float3 normal : ATTR11; +}; + +struct cg_vertex2fragment +{ + float4 hposition : POSITION; + + float4 position : TEXCOORD0; + float4 tex_diffuse_bump : TEXCOORD1; + float4 tex_specular : TEXCOORD2; + float4 tex_atten_xy_z : TEXCOORD3; + + float3 tangent : TEXCOORD4; + float3 binormal : TEXCOORD5; + float3 normal : TEXCOORD6; +}; + + + +cg_vertex2fragment main(cg_app2vertex IN) +{ + cg_vertex2fragment OUT; + + // transform vertex position into homogenous clip-space + OUT.hposition = mul(glstate.matrix.mvp, IN.position); + + // assign position in object space + OUT.position = IN.position; + + // transform texcoords + OUT.tex_diffuse_bump.xy = mul(glstate.matrix.texture[0], IN.tex0).xy; + + // transform texcoords + OUT.tex_diffuse_bump.zw = mul(glstate.matrix.texture[1], IN.tex0).xy; + + // transform texcoords + OUT.tex_specular = mul(glstate.matrix.texture[2], IN.tex0); + + // transform vertex position into light space + OUT.tex_atten_xy_z = mul(glstate.matrix.texture[3], IN.position); + + // assign tangent space vectors + OUT.tangent = IN.tangent; + OUT.binormal = IN.binormal; + OUT.normal = IN.normal; + + return OUT; +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glp b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glp new file mode 100644 index 00000000..88dab8d3 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glp @@ -0,0 +1,86 @@ +!!ARBfp1.0 +# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 +# command line args: -profile arbfp1 +# source file: ..\..\setup\data\tools\gl\lighting_DBS_XY_Z_arbfp1.cg +# source file: ..\..\setup\data\tools\gl/utils.cg +#vendor NVIDIA Corporation +#version 1.0.02 +#profile arbfp1 +#program main +#semantic main.diffusemap +#semantic main.bumpmap +#semantic main.specularmap +#semantic main.attenuationmap_xy +#semantic main.attenuationmap_z +#semantic main.view_origin +#semantic main.light_origin +#semantic main.light_color +#semantic main.bump_scale +#semantic main.specular_exponent +#var float4 IN.position : $vin.TEX0 : TEX0 : 0 : 1 +#var float4 IN.tex_diffuse_bump : $vin.TEX1 : TEX1 : 0 : 1 +#var float4 IN.tex_specular : $vin.TEX2 : TEX2 : 0 : 1 +#var float4 IN.tex_atten_xy_z : $vin.TEX3 : TEX3 : 0 : 1 +#var float3 IN.tangent : $vin.TEX4 : TEX4 : 0 : 1 +#var float3 IN.binormal : $vin.TEX5 : TEX5 : 0 : 1 +#var float3 IN.normal : $vin.TEX6 : TEX6 : 0 : 1 +#var sampler2D diffusemap : : texunit 0 : 1 : 1 +#var sampler2D bumpmap : : texunit 1 : 2 : 1 +#var sampler2D specularmap : : texunit 2 : 3 : 1 +#var sampler2D attenuationmap_xy : : texunit 3 : 4 : 1 +#var sampler2D attenuationmap_z : : texunit 4 : 5 : 1 +#var float3 view_origin : : c[4] : 6 : 1 +#var float3 light_origin : : c[2] : 7 : 1 +#var float3 light_color : : c[3] : 8 : 1 +#var float bump_scale : : c[1] : 9 : 1 +#var float specular_exponent : : c[5] : 10 : 1 +#var float4 main.color : $vout.COL : COL : -1 : 1 +#const c[0] = 0.5 2 0 +PARAM c[6] = { { 0.5, 2, 0 }, + program.local[1..5] }; +TEMP R0; +TEMP R1; +TEMP R2; +ADD R1.xyz, -fragment.texcoord[0], c[2]; +DP3 R0.z, fragment.texcoord[6], R1; +DP3 R0.x, fragment.texcoord[4], R1; +DP3 R0.y, fragment.texcoord[5], R1; +ADD R1.xyz, -fragment.texcoord[0], c[4]; +DP3 R0.w, R0, R0; +DP3 R2.z, fragment.texcoord[6], R1; +DP3 R2.x, fragment.texcoord[4], R1; +DP3 R2.y, fragment.texcoord[5], R1; +RSQ R0.w, R0.w; +MUL R1.xyz, R0.w, R0; +DP3 R1.w, R2, R2; +RSQ R0.w, R1.w; +MUL R2.xyz, R0.w, R2; +ADD R2.xyz, R1, R2; +DP3 R0.w, R2, R2; +RSQ R2.w, R0.w; +TEX R0.xyz, fragment.texcoord[1].zwzw, texture[1], 2D; +ADD R0.xyz, R0, -c[0].x; +MUL R0.xyz, R0, c[0].y; +MUL R0.z, R0, c[1].x; +DP3 R1.w, R0, R0; +RSQ R0.w, R1.w; +MUL R0.xyz, R0.w, R0; +MUL R2.xyz, R2.w, R2; +DP3_SAT R0.w, R0, R2; +DP3_SAT R0.x, R0, R1; +TEX R2.xyz, fragment.texcoord[2], texture[2], 2D; +MUL R1.xyz, R2, c[3]; +POW R0.w, R0.w, c[5].x; +MUL R2.xyz, R1, R0.w; +MUL R1.xyz, R0.x, c[3]; +TEX R0, fragment.texcoord[1], texture[0], 2D; +MAD R2.xyz, R0, R1, R2; +TXP R0.xyz, fragment.texcoord[3], texture[3], 2D; +MOV R1.y, c[0].z; +MOV R1.x, fragment.texcoord[3].z; +TEX R1.xyz, R1, texture[4], 2D; +MUL R0.xyz, R2, R0; +MUL result.color.xyz, R0, R1; +MOV result.color.w, R0; +END +# 41 instructions, 3 R-regs diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glsl b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glsl new file mode 100644 index 00000000..7f80fea2 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_fp.glsl @@ -0,0 +1,73 @@ +/// ============================================================================ +/* +Copyright (C) 2004 Robert Beckebans +Please see the file "CONTRIBUTORS" for a list of contributors + +This program 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 program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + +uniform sampler2D u_diffusemap; +uniform sampler2D u_bumpmap; +uniform sampler2D u_specularmap; +uniform sampler2D u_attenuationmap_xy; +uniform sampler2D u_attenuationmap_z; +uniform vec3 u_view_origin; +uniform vec3 u_light_origin; +uniform vec3 u_light_color; +uniform float u_bump_scale; +uniform float u_specular_exponent; + +varying vec3 var_vertex; +varying vec4 var_tex_diffuse_bump; +varying vec2 var_tex_specular; +varying vec4 var_tex_atten_xy_z; +varying mat3 var_mat_os2ts; + +void main() +{ + // compute view direction in tangent space + vec3 V = normalize(var_mat_os2ts * (u_view_origin - var_vertex)); + + // compute light direction in tangent space + vec3 L = normalize(var_mat_os2ts * (u_light_origin - var_vertex)); + + // compute half angle in tangent space + vec3 H = normalize(L + V); + + // compute normal in tangent space from bumpmap + vec3 N = 2.0 * (texture2D(u_bumpmap, var_tex_diffuse_bump.pq).xyz - 0.5); + N.z *= u_bump_scale; + N = normalize(N); + + // compute the diffuse term + vec4 diffuse = texture2D(u_diffusemap, var_tex_diffuse_bump.st); + diffuse.rgb *= u_light_color * clamp(dot(N, L), 0.0, 1.0); + + // compute the specular term + vec3 specular = texture2D(u_specularmap, var_tex_specular).rgb * u_light_color * pow(clamp(dot(N, H), 0.0, 1.0), u_specular_exponent); + + // compute attenuation + vec3 attenuation_xy = texture2DProj(u_attenuationmap_xy, vec3(var_tex_atten_xy_z.x, var_tex_atten_xy_z.y, var_tex_atten_xy_z.w)).rgb; + vec3 attenuation_z = texture2D(u_attenuationmap_z, vec2(var_tex_atten_xy_z.z, 0)).rgb; + + // compute final color + gl_FragColor.rgba = diffuse; + gl_FragColor.rgb += specular; + gl_FragColor.rgb *= attenuation_xy; + gl_FragColor.rgb *= attenuation_z; +} + diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glp b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glp new file mode 100644 index 00000000..b4472d70 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glp @@ -0,0 +1,410 @@ +!!ARBvp1.0 +# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 +# command line args: -profile arbvp1 +# source file: ..\..\setup\data\tools\gl\lighting_DBS_XY_Z_arbvp1.cg +#vendor NVIDIA Corporation +#version 1.0.02 +#profile arbvp1 +#program main +#semantic glstate : STATE +#var float4 glstate.material.ambient : STATE.MATERIAL.AMBIENT : : -1 : 0 +#var float4 glstate.material.diffuse : STATE.MATERIAL.DIFFUSE : : -1 : 0 +#var float4 glstate.material.specular : STATE.MATERIAL.SPECULAR : : -1 : 0 +#var float4 glstate.material.emission : STATE.MATERIAL.EMISSION : : -1 : 0 +#var float4 glstate.material.shininess : STATE.MATERIAL.SHININESS : : -1 : 0 +#var float4 glstate.material.front.ambient : STATE.MATERIAL.FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.material.front.diffuse : STATE.MATERIAL.FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.material.front.specular : STATE.MATERIAL.FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.material.front.emission : STATE.MATERIAL.FRONT.EMISSION : : -1 : 0 +#var float4 glstate.material.front.shininess : STATE.MATERIAL.FRONT.SHININESS : : -1 : 0 +#var float4 glstate.material.back.ambient : STATE.MATERIAL.BACK.AMBIENT : : -1 : 0 +#var float4 glstate.material.back.diffuse : STATE.MATERIAL.BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.material.back.specular : STATE.MATERIAL.BACK.SPECULAR : : -1 : 0 +#var float4 glstate.material.back.emission : STATE.MATERIAL.BACK.EMISSION : : -1 : 0 +#var float4 glstate.material.back.shininess : STATE.MATERIAL.BACK.SHININESS : : -1 : 0 +#var float4 glstate.light[0].ambient : STATE.LIGHT[0].AMBIENT : : -1 : 0 +#var float4 glstate.light[0].diffuse : STATE.LIGHT[0].DIFFUSE : : -1 : 0 +#var float4 glstate.light[0].specular : STATE.LIGHT[0].SPECULAR : : -1 : 0 +#var float4 glstate.light[0].position : STATE.LIGHT[0].POSITION : : -1 : 0 +#var float4 glstate.light[0].attenuation : STATE.LIGHT[0].ATTENUATION : : -1 : 0 +#var float4 glstate.light[0].spot.direction : STATE.LIGHT[0].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[0].half : STATE.LIGHT[0].HALF : : -1 : 0 +#var float4 glstate.light[1].ambient : STATE.LIGHT[1].AMBIENT : : -1 : 0 +#var float4 glstate.light[1].diffuse : STATE.LIGHT[1].DIFFUSE : : -1 : 0 +#var float4 glstate.light[1].specular : STATE.LIGHT[1].SPECULAR : : -1 : 0 +#var float4 glstate.light[1].position : STATE.LIGHT[1].POSITION : : -1 : 0 +#var float4 glstate.light[1].attenuation : STATE.LIGHT[1].ATTENUATION : : -1 : 0 +#var float4 glstate.light[1].spot.direction : STATE.LIGHT[1].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[1].half : STATE.LIGHT[1].HALF : : -1 : 0 +#var float4 glstate.light[2].ambient : STATE.LIGHT[2].AMBIENT : : -1 : 0 +#var float4 glstate.light[2].diffuse : STATE.LIGHT[2].DIFFUSE : : -1 : 0 +#var float4 glstate.light[2].specular : STATE.LIGHT[2].SPECULAR : : -1 : 0 +#var float4 glstate.light[2].position : STATE.LIGHT[2].POSITION : : -1 : 0 +#var float4 glstate.light[2].attenuation : STATE.LIGHT[2].ATTENUATION : : -1 : 0 +#var float4 glstate.light[2].spot.direction : STATE.LIGHT[2].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[2].half : STATE.LIGHT[2].HALF : : -1 : 0 +#var float4 glstate.light[3].ambient : STATE.LIGHT[3].AMBIENT : : -1 : 0 +#var float4 glstate.light[3].diffuse : STATE.LIGHT[3].DIFFUSE : : -1 : 0 +#var float4 glstate.light[3].specular : STATE.LIGHT[3].SPECULAR : : -1 : 0 +#var float4 glstate.light[3].position : STATE.LIGHT[3].POSITION : : -1 : 0 +#var float4 glstate.light[3].attenuation : STATE.LIGHT[3].ATTENUATION : : -1 : 0 +#var float4 glstate.light[3].spot.direction : STATE.LIGHT[3].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[3].half : STATE.LIGHT[3].HALF : : -1 : 0 +#var float4 glstate.light[4].ambient : STATE.LIGHT[4].AMBIENT : : -1 : 0 +#var float4 glstate.light[4].diffuse : STATE.LIGHT[4].DIFFUSE : : -1 : 0 +#var float4 glstate.light[4].specular : STATE.LIGHT[4].SPECULAR : : -1 : 0 +#var float4 glstate.light[4].position : STATE.LIGHT[4].POSITION : : -1 : 0 +#var float4 glstate.light[4].attenuation : STATE.LIGHT[4].ATTENUATION : : -1 : 0 +#var float4 glstate.light[4].spot.direction : STATE.LIGHT[4].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[4].half : STATE.LIGHT[4].HALF : : -1 : 0 +#var float4 glstate.light[5].ambient : STATE.LIGHT[5].AMBIENT : : -1 : 0 +#var float4 glstate.light[5].diffuse : STATE.LIGHT[5].DIFFUSE : : -1 : 0 +#var float4 glstate.light[5].specular : STATE.LIGHT[5].SPECULAR : : -1 : 0 +#var float4 glstate.light[5].position : STATE.LIGHT[5].POSITION : : -1 : 0 +#var float4 glstate.light[5].attenuation : STATE.LIGHT[5].ATTENUATION : : -1 : 0 +#var float4 glstate.light[5].spot.direction : STATE.LIGHT[5].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[5].half : STATE.LIGHT[5].HALF : : -1 : 0 +#var float4 glstate.light[6].ambient : STATE.LIGHT[6].AMBIENT : : -1 : 0 +#var float4 glstate.light[6].diffuse : STATE.LIGHT[6].DIFFUSE : : -1 : 0 +#var float4 glstate.light[6].specular : STATE.LIGHT[6].SPECULAR : : -1 : 0 +#var float4 glstate.light[6].position : STATE.LIGHT[6].POSITION : : -1 : 0 +#var float4 glstate.light[6].attenuation : STATE.LIGHT[6].ATTENUATION : : -1 : 0 +#var float4 glstate.light[6].spot.direction : STATE.LIGHT[6].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[6].half : STATE.LIGHT[6].HALF : : -1 : 0 +#var float4 glstate.light[7].ambient : STATE.LIGHT[7].AMBIENT : : -1 : 0 +#var float4 glstate.light[7].diffuse : STATE.LIGHT[7].DIFFUSE : : -1 : 0 +#var float4 glstate.light[7].specular : STATE.LIGHT[7].SPECULAR : : -1 : 0 +#var float4 glstate.light[7].position : STATE.LIGHT[7].POSITION : : -1 : 0 +#var float4 glstate.light[7].attenuation : STATE.LIGHT[7].ATTENUATION : : -1 : 0 +#var float4 glstate.light[7].spot.direction : STATE.LIGHT[7].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[7].half : STATE.LIGHT[7].HALF : : -1 : 0 +#var float4 glstate.lightmodel.ambient : STATE.LIGHTMODEL.AMBIENT : : -1 : 0 +#var float4 glstate.lightmodel.scenecolor : STATE.LIGHTMODEL.SCENECOLOR : : -1 : 0 +#var float4 glstate.lightmodel.front.scenecolor : STATE.LIGHTMODEL.FRONT.SCENECOLOR : : -1 : 0 +#var float4 glstate.lightmodel.back.scenecolor : STATE.LIGHTMODEL.BACK.SCENECOLOR : : -1 : 0 +#var float4 glstate.lightprod[0].ambient : STATE.LIGHTPROD[0].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[0].diffuse : STATE.LIGHTPROD[0].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[0].specular : STATE.LIGHTPROD[0].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[0].front.ambient : STATE.LIGHTPROD[0].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[0].front.diffuse : STATE.LIGHTPROD[0].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[0].front.specular : STATE.LIGHTPROD[0].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[0].back.ambient : STATE.LIGHTPROD[0].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[0].back.diffuse : STATE.LIGHTPROD[0].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[0].back.specular : STATE.LIGHTPROD[0].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[1].ambient : STATE.LIGHTPROD[1].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[1].diffuse : STATE.LIGHTPROD[1].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[1].specular : STATE.LIGHTPROD[1].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[1].front.ambient : STATE.LIGHTPROD[1].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[1].front.diffuse : STATE.LIGHTPROD[1].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[1].front.specular : STATE.LIGHTPROD[1].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[1].back.ambient : STATE.LIGHTPROD[1].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[1].back.diffuse : STATE.LIGHTPROD[1].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[1].back.specular : STATE.LIGHTPROD[1].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[2].ambient : STATE.LIGHTPROD[2].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[2].diffuse : STATE.LIGHTPROD[2].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[2].specular : STATE.LIGHTPROD[2].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[2].front.ambient : STATE.LIGHTPROD[2].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[2].front.diffuse : STATE.LIGHTPROD[2].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[2].front.specular : STATE.LIGHTPROD[2].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[2].back.ambient : STATE.LIGHTPROD[2].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[2].back.diffuse : STATE.LIGHTPROD[2].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[2].back.specular : STATE.LIGHTPROD[2].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[3].ambient : STATE.LIGHTPROD[3].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[3].diffuse : STATE.LIGHTPROD[3].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[3].specular : STATE.LIGHTPROD[3].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[3].front.ambient : STATE.LIGHTPROD[3].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[3].front.diffuse : STATE.LIGHTPROD[3].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[3].front.specular : STATE.LIGHTPROD[3].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[3].back.ambient : STATE.LIGHTPROD[3].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[3].back.diffuse : STATE.LIGHTPROD[3].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[3].back.specular : STATE.LIGHTPROD[3].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[4].ambient : STATE.LIGHTPROD[4].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[4].diffuse : STATE.LIGHTPROD[4].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[4].specular : STATE.LIGHTPROD[4].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[4].front.ambient : STATE.LIGHTPROD[4].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[4].front.diffuse : STATE.LIGHTPROD[4].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[4].front.specular : STATE.LIGHTPROD[4].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[4].back.ambient : STATE.LIGHTPROD[4].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[4].back.diffuse : STATE.LIGHTPROD[4].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[4].back.specular : STATE.LIGHTPROD[4].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[5].ambient : STATE.LIGHTPROD[5].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[5].diffuse : STATE.LIGHTPROD[5].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[5].specular : STATE.LIGHTPROD[5].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[5].front.ambient : STATE.LIGHTPROD[5].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[5].front.diffuse : STATE.LIGHTPROD[5].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[5].front.specular : STATE.LIGHTPROD[5].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[5].back.ambient : STATE.LIGHTPROD[5].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[5].back.diffuse : STATE.LIGHTPROD[5].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[5].back.specular : STATE.LIGHTPROD[5].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[6].ambient : STATE.LIGHTPROD[6].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[6].diffuse : STATE.LIGHTPROD[6].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[6].specular : STATE.LIGHTPROD[6].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[6].front.ambient : STATE.LIGHTPROD[6].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[6].front.diffuse : STATE.LIGHTPROD[6].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[6].front.specular : STATE.LIGHTPROD[6].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[6].back.ambient : STATE.LIGHTPROD[6].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[6].back.diffuse : STATE.LIGHTPROD[6].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[6].back.specular : STATE.LIGHTPROD[6].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[7].ambient : STATE.LIGHTPROD[7].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[7].diffuse : STATE.LIGHTPROD[7].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[7].specular : STATE.LIGHTPROD[7].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[7].front.ambient : STATE.LIGHTPROD[7].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[7].front.diffuse : STATE.LIGHTPROD[7].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[7].front.specular : STATE.LIGHTPROD[7].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[7].back.ambient : STATE.LIGHTPROD[7].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[7].back.diffuse : STATE.LIGHTPROD[7].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[7].back.specular : STATE.LIGHTPROD[7].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.texgen[0].eye.s : STATE.TEXGEN[0].EYE.S : : -1 : 0 +#var float4 glstate.texgen[0].eye.t : STATE.TEXGEN[0].EYE.T : : -1 : 0 +#var float4 glstate.texgen[0].eye.r : STATE.TEXGEN[0].EYE.R : : -1 : 0 +#var float4 glstate.texgen[0].eye.q : STATE.TEXGEN[0].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[0].object.s : STATE.TEXGEN[0].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[0].object.t : STATE.TEXGEN[0].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[0].object.r : STATE.TEXGEN[0].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[0].object.q : STATE.TEXGEN[0].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[1].eye.s : STATE.TEXGEN[1].EYE.S : : -1 : 0 +#var float4 glstate.texgen[1].eye.t : STATE.TEXGEN[1].EYE.T : : -1 : 0 +#var float4 glstate.texgen[1].eye.r : STATE.TEXGEN[1].EYE.R : : -1 : 0 +#var float4 glstate.texgen[1].eye.q : STATE.TEXGEN[1].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[1].object.s : STATE.TEXGEN[1].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[1].object.t : STATE.TEXGEN[1].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[1].object.r : STATE.TEXGEN[1].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[1].object.q : STATE.TEXGEN[1].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[2].eye.s : STATE.TEXGEN[2].EYE.S : : -1 : 0 +#var float4 glstate.texgen[2].eye.t : STATE.TEXGEN[2].EYE.T : : -1 : 0 +#var float4 glstate.texgen[2].eye.r : STATE.TEXGEN[2].EYE.R : : -1 : 0 +#var float4 glstate.texgen[2].eye.q : STATE.TEXGEN[2].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[2].object.s : STATE.TEXGEN[2].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[2].object.t : STATE.TEXGEN[2].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[2].object.r : STATE.TEXGEN[2].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[2].object.q : STATE.TEXGEN[2].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[3].eye.s : STATE.TEXGEN[3].EYE.S : : -1 : 0 +#var float4 glstate.texgen[3].eye.t : STATE.TEXGEN[3].EYE.T : : -1 : 0 +#var float4 glstate.texgen[3].eye.r : STATE.TEXGEN[3].EYE.R : : -1 : 0 +#var float4 glstate.texgen[3].eye.q : STATE.TEXGEN[3].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[3].object.s : STATE.TEXGEN[3].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[3].object.t : STATE.TEXGEN[3].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[3].object.r : STATE.TEXGEN[3].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[3].object.q : STATE.TEXGEN[3].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[4].eye.s : STATE.TEXGEN[4].EYE.S : : -1 : 0 +#var float4 glstate.texgen[4].eye.t : STATE.TEXGEN[4].EYE.T : : -1 : 0 +#var float4 glstate.texgen[4].eye.r : STATE.TEXGEN[4].EYE.R : : -1 : 0 +#var float4 glstate.texgen[4].eye.q : STATE.TEXGEN[4].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[4].object.s : STATE.TEXGEN[4].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[4].object.t : STATE.TEXGEN[4].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[4].object.r : STATE.TEXGEN[4].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[4].object.q : STATE.TEXGEN[4].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[5].eye.s : STATE.TEXGEN[5].EYE.S : : -1 : 0 +#var float4 glstate.texgen[5].eye.t : STATE.TEXGEN[5].EYE.T : : -1 : 0 +#var float4 glstate.texgen[5].eye.r : STATE.TEXGEN[5].EYE.R : : -1 : 0 +#var float4 glstate.texgen[5].eye.q : STATE.TEXGEN[5].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[5].object.s : STATE.TEXGEN[5].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[5].object.t : STATE.TEXGEN[5].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[5].object.r : STATE.TEXGEN[5].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[5].object.q : STATE.TEXGEN[5].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[6].eye.s : STATE.TEXGEN[6].EYE.S : : -1 : 0 +#var float4 glstate.texgen[6].eye.t : STATE.TEXGEN[6].EYE.T : : -1 : 0 +#var float4 glstate.texgen[6].eye.r : STATE.TEXGEN[6].EYE.R : : -1 : 0 +#var float4 glstate.texgen[6].eye.q : STATE.TEXGEN[6].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[6].object.s : STATE.TEXGEN[6].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[6].object.t : STATE.TEXGEN[6].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[6].object.r : STATE.TEXGEN[6].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[6].object.q : STATE.TEXGEN[6].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[7].eye.s : STATE.TEXGEN[7].EYE.S : : -1 : 0 +#var float4 glstate.texgen[7].eye.t : STATE.TEXGEN[7].EYE.T : : -1 : 0 +#var float4 glstate.texgen[7].eye.r : STATE.TEXGEN[7].EYE.R : : -1 : 0 +#var float4 glstate.texgen[7].eye.q : STATE.TEXGEN[7].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[7].object.s : STATE.TEXGEN[7].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[7].object.t : STATE.TEXGEN[7].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[7].object.r : STATE.TEXGEN[7].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[7].object.q : STATE.TEXGEN[7].OBJECT.Q : : -1 : 0 +#var float4 glstate.fog.color : STATE.FOG.COLOR : : -1 : 0 +#var float4 glstate.fog.params : STATE.FOG.PARAMS : : -1 : 0 +#var float4 glstate.clip[0].plane : STATE.CLIP[0].PLANE : : -1 : 0 +#var float4 glstate.clip[1].plane : STATE.CLIP[1].PLANE : : -1 : 0 +#var float4 glstate.clip[2].plane : STATE.CLIP[2].PLANE : : -1 : 0 +#var float4 glstate.clip[3].plane : STATE.CLIP[3].PLANE : : -1 : 0 +#var float4 glstate.clip[4].plane : STATE.CLIP[4].PLANE : : -1 : 0 +#var float4 glstate.clip[5].plane : STATE.CLIP[5].PLANE : : -1 : 0 +#var float4 glstate.clip[6].plane : STATE.CLIP[6].PLANE : : -1 : 0 +#var float4 glstate.clip[7].plane : STATE.CLIP[7].PLANE : : -1 : 0 +#var float glstate.point.size : STATE.POINT.SIZE : : -1 : 0 +#var float glstate.point.attenuation : STATE.POINT.ATTENUATION : : -1 : 0 +#var float4x4 glstate.matrix.modelview[0] : STATE.MATRIX.MODELVIEW[0] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[1] : STATE.MATRIX.MODELVIEW[1] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[2] : STATE.MATRIX.MODELVIEW[2] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[3] : STATE.MATRIX.MODELVIEW[3] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[4] : STATE.MATRIX.MODELVIEW[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[5] : STATE.MATRIX.MODELVIEW[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[6] : STATE.MATRIX.MODELVIEW[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[7] : STATE.MATRIX.MODELVIEW[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.projection : STATE.MATRIX.PROJECTION : , 4 : -1 : 0 +#var float4x4 glstate.matrix.mvp : STATE.MATRIX.MVP : c[0], 4 : -1 : 1 +#var float4x4 glstate.matrix.texture[0] : STATE.MATRIX.TEXTURE[0] : c[4], 4 : -1 : 1 +#var float4x4 glstate.matrix.texture[1] : STATE.MATRIX.TEXTURE[1] : c[8], 4 : -1 : 1 +#var float4x4 glstate.matrix.texture[2] : STATE.MATRIX.TEXTURE[2] : c[12], 4 : -1 : 1 +#var float4x4 glstate.matrix.texture[3] : STATE.MATRIX.TEXTURE[3] : c[16], 4 : -1 : 1 +#var float4x4 glstate.matrix.texture[4] : STATE.MATRIX.TEXTURE[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[5] : STATE.MATRIX.TEXTURE[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[6] : STATE.MATRIX.TEXTURE[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[7] : STATE.MATRIX.TEXTURE[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[0] : STATE.MATRIX.PALETTE[0] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[1] : STATE.MATRIX.PALETTE[1] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[2] : STATE.MATRIX.PALETTE[2] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[3] : STATE.MATRIX.PALETTE[3] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[4] : STATE.MATRIX.PALETTE[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[5] : STATE.MATRIX.PALETTE[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[6] : STATE.MATRIX.PALETTE[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[7] : STATE.MATRIX.PALETTE[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[0] : STATE.MATRIX.PROGRAM[0] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[1] : STATE.MATRIX.PROGRAM[1] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[2] : STATE.MATRIX.PROGRAM[2] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[3] : STATE.MATRIX.PROGRAM[3] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[4] : STATE.MATRIX.PROGRAM[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[5] : STATE.MATRIX.PROGRAM[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[6] : STATE.MATRIX.PROGRAM[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[7] : STATE.MATRIX.PROGRAM[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.projection : STATE.MATRIX.PROJECTION.INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.mvp : STATE.MATRIX.MVP.INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[0] : STATE.MATRIX.TEXTURE[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[1] : STATE.MATRIX.TEXTURE[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[2] : STATE.MATRIX.TEXTURE[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[3] : STATE.MATRIX.TEXTURE[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[4] : STATE.MATRIX.TEXTURE[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[5] : STATE.MATRIX.TEXTURE[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[6] : STATE.MATRIX.TEXTURE[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[7] : STATE.MATRIX.TEXTURE[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[0] : STATE.MATRIX.PALETTE[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[1] : STATE.MATRIX.PALETTE[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[2] : STATE.MATRIX.PALETTE[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[3] : STATE.MATRIX.PALETTE[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[4] : STATE.MATRIX.PALETTE[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[5] : STATE.MATRIX.PALETTE[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[6] : STATE.MATRIX.PALETTE[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[7] : STATE.MATRIX.PALETTE[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[0] : STATE.MATRIX.PROGRAM[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[1] : STATE.MATRIX.PROGRAM[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[2] : STATE.MATRIX.PROGRAM[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[3] : STATE.MATRIX.PROGRAM[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[4] : STATE.MATRIX.PROGRAM[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[5] : STATE.MATRIX.PROGRAM[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[6] : STATE.MATRIX.PROGRAM[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[7] : STATE.MATRIX.PROGRAM[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[0] : STATE.MATRIX.MODELVIEW[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[1] : STATE.MATRIX.MODELVIEW[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[2] : STATE.MATRIX.MODELVIEW[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[3] : STATE.MATRIX.MODELVIEW[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[4] : STATE.MATRIX.MODELVIEW[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[5] : STATE.MATRIX.MODELVIEW[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[6] : STATE.MATRIX.MODELVIEW[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[7] : STATE.MATRIX.MODELVIEW[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.projection : STATE.MATRIX.PROJECTION.TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.mvp : STATE.MATRIX.MVP.TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[0] : STATE.MATRIX.TEXTURE[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[1] : STATE.MATRIX.TEXTURE[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[2] : STATE.MATRIX.TEXTURE[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[3] : STATE.MATRIX.TEXTURE[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[4] : STATE.MATRIX.TEXTURE[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[5] : STATE.MATRIX.TEXTURE[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[6] : STATE.MATRIX.TEXTURE[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[7] : STATE.MATRIX.TEXTURE[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[0] : STATE.MATRIX.PALETTE[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[1] : STATE.MATRIX.PALETTE[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[2] : STATE.MATRIX.PALETTE[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[3] : STATE.MATRIX.PALETTE[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[4] : STATE.MATRIX.PALETTE[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[5] : STATE.MATRIX.PALETTE[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[6] : STATE.MATRIX.PALETTE[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[7] : STATE.MATRIX.PALETTE[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[0] : STATE.MATRIX.PROGRAM[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[1] : STATE.MATRIX.PROGRAM[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[2] : STATE.MATRIX.PROGRAM[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[3] : STATE.MATRIX.PROGRAM[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[4] : STATE.MATRIX.PROGRAM[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[5] : STATE.MATRIX.PROGRAM[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[6] : STATE.MATRIX.PROGRAM[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[7] : STATE.MATRIX.PROGRAM[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.projection : STATE.MATRIX.PROJECTION.INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.mvp : STATE.MATRIX.MVP.INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[0] : STATE.MATRIX.TEXTURE[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[1] : STATE.MATRIX.TEXTURE[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[2] : STATE.MATRIX.TEXTURE[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[3] : STATE.MATRIX.TEXTURE[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[4] : STATE.MATRIX.TEXTURE[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[5] : STATE.MATRIX.TEXTURE[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[6] : STATE.MATRIX.TEXTURE[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[7] : STATE.MATRIX.TEXTURE[7].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[0] : STATE.MATRIX.PALETTE[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[1] : STATE.MATRIX.PALETTE[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[2] : STATE.MATRIX.PALETTE[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[3] : STATE.MATRIX.PALETTE[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[4] : STATE.MATRIX.PALETTE[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[5] : STATE.MATRIX.PALETTE[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[6] : STATE.MATRIX.PALETTE[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[7] : STATE.MATRIX.PALETTE[7].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[0] : STATE.MATRIX.PROGRAM[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[1] : STATE.MATRIX.PROGRAM[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[2] : STATE.MATRIX.PROGRAM[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[3] : STATE.MATRIX.PROGRAM[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[4] : STATE.MATRIX.PROGRAM[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[5] : STATE.MATRIX.PROGRAM[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[6] : STATE.MATRIX.PROGRAM[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[7] : STATE.MATRIX.PROGRAM[7].INVTRANS : , 4 : -1 : 0 +#var float4 IN.position : $vin.POSITION : POSITION : 0 : 1 +#var float4 IN.tex0 : $vin.ATTR8 : ATTR8 : 0 : 1 +#var float3 IN.tangent : $vin.ATTR9 : ATTR9 : 0 : 1 +#var float3 IN.binormal : $vin.ATTR10 : ATTR10 : 0 : 1 +#var float3 IN.normal : $vin.ATTR11 : ATTR11 : 0 : 1 +#var float4 main.hposition : $vout.HPOS : HPOS : -1 : 1 +#var float4 main.position : $vout.TEX0 : TEX0 : -1 : 1 +#var float4 main.tex_diffuse_bump : $vout.TEX1 : TEX1 : -1 : 1 +#var float4 main.tex_specular : $vout.TEX2 : TEX2 : -1 : 1 +#var float4 main.tex_atten_xy_z : $vout.TEX3 : TEX3 : -1 : 1 +#var float3 main.tangent : $vout.TEX4 : TEX4 : -1 : 1 +#var float3 main.binormal : $vout.TEX5 : TEX5 : -1 : 1 +#var float3 main.normal : $vout.TEX6 : TEX6 : -1 : 1 +PARAM c[20] = { state.matrix.mvp, + state.matrix.texture[0], + state.matrix.texture[1], + state.matrix.texture[2], + state.matrix.texture[3] }; +TEMP R0; +DP4 result.position.w, vertex.position, c[3]; +DP4 result.position.z, vertex.position, c[2]; +DP4 result.position.y, vertex.position, c[1]; +DP4 result.position.x, vertex.position, c[0]; +DP4 R0.y, vertex.attrib[8], c[9]; +DP4 R0.x, vertex.attrib[8], c[8]; +MOV result.texcoord[0], vertex.position; +MOV result.texcoord[1].zw, R0.xyxy; +DP4 result.texcoord[1].y, vertex.attrib[8], c[5]; +DP4 result.texcoord[1].x, vertex.attrib[8], c[4]; +DP4 result.texcoord[2].w, vertex.attrib[8], c[15]; +DP4 result.texcoord[2].z, vertex.attrib[8], c[14]; +DP4 result.texcoord[2].y, vertex.attrib[8], c[13]; +DP4 result.texcoord[2].x, vertex.attrib[8], c[12]; +DP4 result.texcoord[3].w, vertex.position, c[19]; +DP4 result.texcoord[3].z, vertex.position, c[18]; +DP4 result.texcoord[3].y, vertex.position, c[17]; +DP4 result.texcoord[3].x, vertex.position, c[16]; +MOV result.texcoord[4].xyz, vertex.attrib[9]; +MOV result.texcoord[5].xyz, vertex.attrib[10]; +MOV result.texcoord[6].xyz, vertex.attrib[11]; +END +# 21 instructions, 1 R-regs diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glsl b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glsl new file mode 100644 index 00000000..6900b5af --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/lighting_DBS_omni_vp.glsl @@ -0,0 +1,58 @@ +/// ============================================================================ +/* +Copyright (C) 2004 Robert Beckebans +Please see the file "CONTRIBUTORS" for a list of contributors + +This program 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 program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + +attribute vec4 attr_TexCoord0; +attribute vec3 attr_Tangent; +attribute vec3 attr_Binormal; + +varying vec3 var_vertex; +varying vec4 var_tex_diffuse_bump; +varying vec2 var_tex_specular; +varying vec4 var_tex_atten_xy_z; +varying mat3 var_mat_os2ts; + +void main() +{ + // transform vertex position into homogenous clip-space + gl_Position = ftransform(); + + // assign position in object space + var_vertex = gl_Vertex.xyz; + + // transform texcoords into diffusemap texture space + var_tex_diffuse_bump.st = (gl_TextureMatrix[0] * attr_TexCoord0).st; + + // transform texcoords into bumpmap texture space + var_tex_diffuse_bump.pq = (gl_TextureMatrix[1] * attr_TexCoord0).st; + + // transform texcoords into specularmap texture space + var_tex_specular = (gl_TextureMatrix[2] * attr_TexCoord0).st; + + // calc light xy,z attenuation in light space + var_tex_atten_xy_z = gl_TextureMatrix[3] * gl_Vertex; + + + // construct object-space-to-tangent-space 3x3 matrix + var_mat_os2ts = mat3( attr_Tangent.x, attr_Binormal.x, gl_Normal.x, + attr_Tangent.y, attr_Binormal.y, gl_Normal.y, + attr_Tangent.z, attr_Binormal.z, gl_Normal.z ); +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/utils.cg b/misc/mediasource/netradiant-src/setup/data/tools/gl/utils.cg new file mode 100644 index 00000000..63bfcb6c --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/utils.cg @@ -0,0 +1,36 @@ +/// ============================================================================ +/* +Copyright (C) 2004 Robert Beckebans +Please see the file "AUTHORS" for a list of contributors + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + +// fresnel approximation +float fast_fresnel(float3 I, float3 N, float3 fresnel_values) +{ + float power = fresnel_values.x; + float scale = fresnel_values.y; + float bias = fresnel_values.z; + + return bias + pow(1.0 - dot(I, N), power) * scale; +} + +float3 CG_Expand(float3 v) +{ + return (v - 0.5) * 2; // expand a range-compressed vector +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_arbfp1.cg b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_arbfp1.cg new file mode 100644 index 00000000..c80189c2 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_arbfp1.cg @@ -0,0 +1,47 @@ +/// ============================================================================ +/* +Copyright (C) 2003 Robert Beckebans +Copyright (C) 2003, 2004 contributors of the XreaL project +Please see the file "AUTHORS" for a list of contributors + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + + +struct cg_vertex2fragment +{ + float4 position : POSITION; + float4 tex0 : TEXCOORD0; +}; + +struct cg_fragment2final +{ + float4 color : COLOR; +}; + + +cg_fragment2final main(in cg_vertex2fragment IN, + uniform sampler2D colormap) +{ + cg_fragment2final OUT; + + OUT.color.w = tex2D(colormap, IN.tex0.xy).a; + + OUT.color.xyz = 0; + + return OUT; +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_arbvp1.cg b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_arbvp1.cg new file mode 100644 index 00000000..4ffc6e27 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_arbvp1.cg @@ -0,0 +1,49 @@ +/// ============================================================================ +/* +Copyright (C) 2003 Robert Beckebans +Copyright (C) 2003, 2004 contributors of the XreaL project +Please see the file "AUTHORS" for a list of contributors + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +as published by the Free Software Foundation; either version 2 +of the License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + + +struct cg_app2vertex +{ + float4 position : ATTR0; + float4 texcoord0 : ATTR8; +}; + +struct cg_vertex2fragment +{ + float4 position : POSITION; + float4 tex0 : TEXCOORD0; +}; + + +cg_vertex2fragment main(cg_app2vertex IN) +{ + cg_vertex2fragment OUT; + + // transform vertex position into homogenous clip-space + OUT.position = mul(glstate.matrix.mvp, IN.position); + + // transform texcoords into 1st texture space + OUT.tex0 = mul(glstate.matrix.texture[0], IN.texcoord0); + + return OUT; +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_fp.glp b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_fp.glp new file mode 100644 index 00000000..5eb8b129 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_fp.glp @@ -0,0 +1,19 @@ +!!ARBfp1.0 +# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 +# command line args: -profile arbfp1 +# source file: ..\..\setup\data\tools\gl\zfill_arbfp1.cg +#vendor NVIDIA Corporation +#version 1.0.02 +#profile arbfp1 +#program main +#semantic main.colormap +#var float4 IN.position : : : 0 : 0 +#var float4 IN.tex0 : $vin.TEX0 : TEX0 : 0 : 1 +#var sampler2D colormap : : texunit 0 : 1 : 1 +#var float4 main.color : $vout.COL : COL : -1 : 1 +#const c[0] = 0 +PARAM c[1] = { { 0 } }; +MOV result.color.xyz, c[0].x; +TEX result.color.w, fragment.texcoord[0], texture[0], 2D; +END +# 2 instructions, 0 R-regs diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_fp.glsl b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_fp.glsl new file mode 100644 index 00000000..537db670 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_fp.glsl @@ -0,0 +1,29 @@ +/// ============================================================================ +/* +Copyright (C) 2004 Robert Beckebans +Please see the file "CONTRIBUTORS" for a list of contributors + +This program 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 program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + +uniform sampler2D u_colormap; + +void main() +{ + gl_FragColor.a = texture2D(u_colormap, gl_TexCoord[0].st).a; + gl_FragColor.rgb = vec3(0.0, 0.0, 0.0); +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_vp.glp b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_vp.glp new file mode 100644 index 00000000..f6eda0c0 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_vp.glp @@ -0,0 +1,384 @@ +!!ARBvp1.0 +# cgc version 1.3.0001, build date Aug 4 2004 10:01:10 +# command line args: -profile arbvp1 +# source file: ..\..\setup\data\tools\gl\zfill_arbvp1.cg +#vendor NVIDIA Corporation +#version 1.0.02 +#profile arbvp1 +#program main +#semantic glstate : STATE +#var float4 glstate.material.ambient : STATE.MATERIAL.AMBIENT : : -1 : 0 +#var float4 glstate.material.diffuse : STATE.MATERIAL.DIFFUSE : : -1 : 0 +#var float4 glstate.material.specular : STATE.MATERIAL.SPECULAR : : -1 : 0 +#var float4 glstate.material.emission : STATE.MATERIAL.EMISSION : : -1 : 0 +#var float4 glstate.material.shininess : STATE.MATERIAL.SHININESS : : -1 : 0 +#var float4 glstate.material.front.ambient : STATE.MATERIAL.FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.material.front.diffuse : STATE.MATERIAL.FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.material.front.specular : STATE.MATERIAL.FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.material.front.emission : STATE.MATERIAL.FRONT.EMISSION : : -1 : 0 +#var float4 glstate.material.front.shininess : STATE.MATERIAL.FRONT.SHININESS : : -1 : 0 +#var float4 glstate.material.back.ambient : STATE.MATERIAL.BACK.AMBIENT : : -1 : 0 +#var float4 glstate.material.back.diffuse : STATE.MATERIAL.BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.material.back.specular : STATE.MATERIAL.BACK.SPECULAR : : -1 : 0 +#var float4 glstate.material.back.emission : STATE.MATERIAL.BACK.EMISSION : : -1 : 0 +#var float4 glstate.material.back.shininess : STATE.MATERIAL.BACK.SHININESS : : -1 : 0 +#var float4 glstate.light[0].ambient : STATE.LIGHT[0].AMBIENT : : -1 : 0 +#var float4 glstate.light[0].diffuse : STATE.LIGHT[0].DIFFUSE : : -1 : 0 +#var float4 glstate.light[0].specular : STATE.LIGHT[0].SPECULAR : : -1 : 0 +#var float4 glstate.light[0].position : STATE.LIGHT[0].POSITION : : -1 : 0 +#var float4 glstate.light[0].attenuation : STATE.LIGHT[0].ATTENUATION : : -1 : 0 +#var float4 glstate.light[0].spot.direction : STATE.LIGHT[0].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[0].half : STATE.LIGHT[0].HALF : : -1 : 0 +#var float4 glstate.light[1].ambient : STATE.LIGHT[1].AMBIENT : : -1 : 0 +#var float4 glstate.light[1].diffuse : STATE.LIGHT[1].DIFFUSE : : -1 : 0 +#var float4 glstate.light[1].specular : STATE.LIGHT[1].SPECULAR : : -1 : 0 +#var float4 glstate.light[1].position : STATE.LIGHT[1].POSITION : : -1 : 0 +#var float4 glstate.light[1].attenuation : STATE.LIGHT[1].ATTENUATION : : -1 : 0 +#var float4 glstate.light[1].spot.direction : STATE.LIGHT[1].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[1].half : STATE.LIGHT[1].HALF : : -1 : 0 +#var float4 glstate.light[2].ambient : STATE.LIGHT[2].AMBIENT : : -1 : 0 +#var float4 glstate.light[2].diffuse : STATE.LIGHT[2].DIFFUSE : : -1 : 0 +#var float4 glstate.light[2].specular : STATE.LIGHT[2].SPECULAR : : -1 : 0 +#var float4 glstate.light[2].position : STATE.LIGHT[2].POSITION : : -1 : 0 +#var float4 glstate.light[2].attenuation : STATE.LIGHT[2].ATTENUATION : : -1 : 0 +#var float4 glstate.light[2].spot.direction : STATE.LIGHT[2].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[2].half : STATE.LIGHT[2].HALF : : -1 : 0 +#var float4 glstate.light[3].ambient : STATE.LIGHT[3].AMBIENT : : -1 : 0 +#var float4 glstate.light[3].diffuse : STATE.LIGHT[3].DIFFUSE : : -1 : 0 +#var float4 glstate.light[3].specular : STATE.LIGHT[3].SPECULAR : : -1 : 0 +#var float4 glstate.light[3].position : STATE.LIGHT[3].POSITION : : -1 : 0 +#var float4 glstate.light[3].attenuation : STATE.LIGHT[3].ATTENUATION : : -1 : 0 +#var float4 glstate.light[3].spot.direction : STATE.LIGHT[3].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[3].half : STATE.LIGHT[3].HALF : : -1 : 0 +#var float4 glstate.light[4].ambient : STATE.LIGHT[4].AMBIENT : : -1 : 0 +#var float4 glstate.light[4].diffuse : STATE.LIGHT[4].DIFFUSE : : -1 : 0 +#var float4 glstate.light[4].specular : STATE.LIGHT[4].SPECULAR : : -1 : 0 +#var float4 glstate.light[4].position : STATE.LIGHT[4].POSITION : : -1 : 0 +#var float4 glstate.light[4].attenuation : STATE.LIGHT[4].ATTENUATION : : -1 : 0 +#var float4 glstate.light[4].spot.direction : STATE.LIGHT[4].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[4].half : STATE.LIGHT[4].HALF : : -1 : 0 +#var float4 glstate.light[5].ambient : STATE.LIGHT[5].AMBIENT : : -1 : 0 +#var float4 glstate.light[5].diffuse : STATE.LIGHT[5].DIFFUSE : : -1 : 0 +#var float4 glstate.light[5].specular : STATE.LIGHT[5].SPECULAR : : -1 : 0 +#var float4 glstate.light[5].position : STATE.LIGHT[5].POSITION : : -1 : 0 +#var float4 glstate.light[5].attenuation : STATE.LIGHT[5].ATTENUATION : : -1 : 0 +#var float4 glstate.light[5].spot.direction : STATE.LIGHT[5].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[5].half : STATE.LIGHT[5].HALF : : -1 : 0 +#var float4 glstate.light[6].ambient : STATE.LIGHT[6].AMBIENT : : -1 : 0 +#var float4 glstate.light[6].diffuse : STATE.LIGHT[6].DIFFUSE : : -1 : 0 +#var float4 glstate.light[6].specular : STATE.LIGHT[6].SPECULAR : : -1 : 0 +#var float4 glstate.light[6].position : STATE.LIGHT[6].POSITION : : -1 : 0 +#var float4 glstate.light[6].attenuation : STATE.LIGHT[6].ATTENUATION : : -1 : 0 +#var float4 glstate.light[6].spot.direction : STATE.LIGHT[6].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[6].half : STATE.LIGHT[6].HALF : : -1 : 0 +#var float4 glstate.light[7].ambient : STATE.LIGHT[7].AMBIENT : : -1 : 0 +#var float4 glstate.light[7].diffuse : STATE.LIGHT[7].DIFFUSE : : -1 : 0 +#var float4 glstate.light[7].specular : STATE.LIGHT[7].SPECULAR : : -1 : 0 +#var float4 glstate.light[7].position : STATE.LIGHT[7].POSITION : : -1 : 0 +#var float4 glstate.light[7].attenuation : STATE.LIGHT[7].ATTENUATION : : -1 : 0 +#var float4 glstate.light[7].spot.direction : STATE.LIGHT[7].SPOT.DIRECTION : : -1 : 0 +#var float4 glstate.light[7].half : STATE.LIGHT[7].HALF : : -1 : 0 +#var float4 glstate.lightmodel.ambient : STATE.LIGHTMODEL.AMBIENT : : -1 : 0 +#var float4 glstate.lightmodel.scenecolor : STATE.LIGHTMODEL.SCENECOLOR : : -1 : 0 +#var float4 glstate.lightmodel.front.scenecolor : STATE.LIGHTMODEL.FRONT.SCENECOLOR : : -1 : 0 +#var float4 glstate.lightmodel.back.scenecolor : STATE.LIGHTMODEL.BACK.SCENECOLOR : : -1 : 0 +#var float4 glstate.lightprod[0].ambient : STATE.LIGHTPROD[0].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[0].diffuse : STATE.LIGHTPROD[0].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[0].specular : STATE.LIGHTPROD[0].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[0].front.ambient : STATE.LIGHTPROD[0].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[0].front.diffuse : STATE.LIGHTPROD[0].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[0].front.specular : STATE.LIGHTPROD[0].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[0].back.ambient : STATE.LIGHTPROD[0].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[0].back.diffuse : STATE.LIGHTPROD[0].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[0].back.specular : STATE.LIGHTPROD[0].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[1].ambient : STATE.LIGHTPROD[1].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[1].diffuse : STATE.LIGHTPROD[1].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[1].specular : STATE.LIGHTPROD[1].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[1].front.ambient : STATE.LIGHTPROD[1].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[1].front.diffuse : STATE.LIGHTPROD[1].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[1].front.specular : STATE.LIGHTPROD[1].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[1].back.ambient : STATE.LIGHTPROD[1].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[1].back.diffuse : STATE.LIGHTPROD[1].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[1].back.specular : STATE.LIGHTPROD[1].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[2].ambient : STATE.LIGHTPROD[2].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[2].diffuse : STATE.LIGHTPROD[2].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[2].specular : STATE.LIGHTPROD[2].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[2].front.ambient : STATE.LIGHTPROD[2].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[2].front.diffuse : STATE.LIGHTPROD[2].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[2].front.specular : STATE.LIGHTPROD[2].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[2].back.ambient : STATE.LIGHTPROD[2].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[2].back.diffuse : STATE.LIGHTPROD[2].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[2].back.specular : STATE.LIGHTPROD[2].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[3].ambient : STATE.LIGHTPROD[3].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[3].diffuse : STATE.LIGHTPROD[3].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[3].specular : STATE.LIGHTPROD[3].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[3].front.ambient : STATE.LIGHTPROD[3].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[3].front.diffuse : STATE.LIGHTPROD[3].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[3].front.specular : STATE.LIGHTPROD[3].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[3].back.ambient : STATE.LIGHTPROD[3].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[3].back.diffuse : STATE.LIGHTPROD[3].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[3].back.specular : STATE.LIGHTPROD[3].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[4].ambient : STATE.LIGHTPROD[4].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[4].diffuse : STATE.LIGHTPROD[4].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[4].specular : STATE.LIGHTPROD[4].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[4].front.ambient : STATE.LIGHTPROD[4].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[4].front.diffuse : STATE.LIGHTPROD[4].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[4].front.specular : STATE.LIGHTPROD[4].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[4].back.ambient : STATE.LIGHTPROD[4].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[4].back.diffuse : STATE.LIGHTPROD[4].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[4].back.specular : STATE.LIGHTPROD[4].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[5].ambient : STATE.LIGHTPROD[5].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[5].diffuse : STATE.LIGHTPROD[5].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[5].specular : STATE.LIGHTPROD[5].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[5].front.ambient : STATE.LIGHTPROD[5].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[5].front.diffuse : STATE.LIGHTPROD[5].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[5].front.specular : STATE.LIGHTPROD[5].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[5].back.ambient : STATE.LIGHTPROD[5].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[5].back.diffuse : STATE.LIGHTPROD[5].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[5].back.specular : STATE.LIGHTPROD[5].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[6].ambient : STATE.LIGHTPROD[6].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[6].diffuse : STATE.LIGHTPROD[6].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[6].specular : STATE.LIGHTPROD[6].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[6].front.ambient : STATE.LIGHTPROD[6].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[6].front.diffuse : STATE.LIGHTPROD[6].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[6].front.specular : STATE.LIGHTPROD[6].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[6].back.ambient : STATE.LIGHTPROD[6].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[6].back.diffuse : STATE.LIGHTPROD[6].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[6].back.specular : STATE.LIGHTPROD[6].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[7].ambient : STATE.LIGHTPROD[7].AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[7].diffuse : STATE.LIGHTPROD[7].DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[7].specular : STATE.LIGHTPROD[7].SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[7].front.ambient : STATE.LIGHTPROD[7].FRONT.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[7].front.diffuse : STATE.LIGHTPROD[7].FRONT.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[7].front.specular : STATE.LIGHTPROD[7].FRONT.SPECULAR : : -1 : 0 +#var float4 glstate.lightprod[7].back.ambient : STATE.LIGHTPROD[7].BACK.AMBIENT : : -1 : 0 +#var float4 glstate.lightprod[7].back.diffuse : STATE.LIGHTPROD[7].BACK.DIFFUSE : : -1 : 0 +#var float4 glstate.lightprod[7].back.specular : STATE.LIGHTPROD[7].BACK.SPECULAR : : -1 : 0 +#var float4 glstate.texgen[0].eye.s : STATE.TEXGEN[0].EYE.S : : -1 : 0 +#var float4 glstate.texgen[0].eye.t : STATE.TEXGEN[0].EYE.T : : -1 : 0 +#var float4 glstate.texgen[0].eye.r : STATE.TEXGEN[0].EYE.R : : -1 : 0 +#var float4 glstate.texgen[0].eye.q : STATE.TEXGEN[0].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[0].object.s : STATE.TEXGEN[0].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[0].object.t : STATE.TEXGEN[0].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[0].object.r : STATE.TEXGEN[0].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[0].object.q : STATE.TEXGEN[0].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[1].eye.s : STATE.TEXGEN[1].EYE.S : : -1 : 0 +#var float4 glstate.texgen[1].eye.t : STATE.TEXGEN[1].EYE.T : : -1 : 0 +#var float4 glstate.texgen[1].eye.r : STATE.TEXGEN[1].EYE.R : : -1 : 0 +#var float4 glstate.texgen[1].eye.q : STATE.TEXGEN[1].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[1].object.s : STATE.TEXGEN[1].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[1].object.t : STATE.TEXGEN[1].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[1].object.r : STATE.TEXGEN[1].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[1].object.q : STATE.TEXGEN[1].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[2].eye.s : STATE.TEXGEN[2].EYE.S : : -1 : 0 +#var float4 glstate.texgen[2].eye.t : STATE.TEXGEN[2].EYE.T : : -1 : 0 +#var float4 glstate.texgen[2].eye.r : STATE.TEXGEN[2].EYE.R : : -1 : 0 +#var float4 glstate.texgen[2].eye.q : STATE.TEXGEN[2].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[2].object.s : STATE.TEXGEN[2].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[2].object.t : STATE.TEXGEN[2].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[2].object.r : STATE.TEXGEN[2].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[2].object.q : STATE.TEXGEN[2].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[3].eye.s : STATE.TEXGEN[3].EYE.S : : -1 : 0 +#var float4 glstate.texgen[3].eye.t : STATE.TEXGEN[3].EYE.T : : -1 : 0 +#var float4 glstate.texgen[3].eye.r : STATE.TEXGEN[3].EYE.R : : -1 : 0 +#var float4 glstate.texgen[3].eye.q : STATE.TEXGEN[3].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[3].object.s : STATE.TEXGEN[3].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[3].object.t : STATE.TEXGEN[3].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[3].object.r : STATE.TEXGEN[3].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[3].object.q : STATE.TEXGEN[3].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[4].eye.s : STATE.TEXGEN[4].EYE.S : : -1 : 0 +#var float4 glstate.texgen[4].eye.t : STATE.TEXGEN[4].EYE.T : : -1 : 0 +#var float4 glstate.texgen[4].eye.r : STATE.TEXGEN[4].EYE.R : : -1 : 0 +#var float4 glstate.texgen[4].eye.q : STATE.TEXGEN[4].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[4].object.s : STATE.TEXGEN[4].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[4].object.t : STATE.TEXGEN[4].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[4].object.r : STATE.TEXGEN[4].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[4].object.q : STATE.TEXGEN[4].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[5].eye.s : STATE.TEXGEN[5].EYE.S : : -1 : 0 +#var float4 glstate.texgen[5].eye.t : STATE.TEXGEN[5].EYE.T : : -1 : 0 +#var float4 glstate.texgen[5].eye.r : STATE.TEXGEN[5].EYE.R : : -1 : 0 +#var float4 glstate.texgen[5].eye.q : STATE.TEXGEN[5].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[5].object.s : STATE.TEXGEN[5].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[5].object.t : STATE.TEXGEN[5].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[5].object.r : STATE.TEXGEN[5].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[5].object.q : STATE.TEXGEN[5].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[6].eye.s : STATE.TEXGEN[6].EYE.S : : -1 : 0 +#var float4 glstate.texgen[6].eye.t : STATE.TEXGEN[6].EYE.T : : -1 : 0 +#var float4 glstate.texgen[6].eye.r : STATE.TEXGEN[6].EYE.R : : -1 : 0 +#var float4 glstate.texgen[6].eye.q : STATE.TEXGEN[6].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[6].object.s : STATE.TEXGEN[6].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[6].object.t : STATE.TEXGEN[6].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[6].object.r : STATE.TEXGEN[6].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[6].object.q : STATE.TEXGEN[6].OBJECT.Q : : -1 : 0 +#var float4 glstate.texgen[7].eye.s : STATE.TEXGEN[7].EYE.S : : -1 : 0 +#var float4 glstate.texgen[7].eye.t : STATE.TEXGEN[7].EYE.T : : -1 : 0 +#var float4 glstate.texgen[7].eye.r : STATE.TEXGEN[7].EYE.R : : -1 : 0 +#var float4 glstate.texgen[7].eye.q : STATE.TEXGEN[7].EYE.Q : : -1 : 0 +#var float4 glstate.texgen[7].object.s : STATE.TEXGEN[7].OBJECT.S : : -1 : 0 +#var float4 glstate.texgen[7].object.t : STATE.TEXGEN[7].OBJECT.T : : -1 : 0 +#var float4 glstate.texgen[7].object.r : STATE.TEXGEN[7].OBJECT.R : : -1 : 0 +#var float4 glstate.texgen[7].object.q : STATE.TEXGEN[7].OBJECT.Q : : -1 : 0 +#var float4 glstate.fog.color : STATE.FOG.COLOR : : -1 : 0 +#var float4 glstate.fog.params : STATE.FOG.PARAMS : : -1 : 0 +#var float4 glstate.clip[0].plane : STATE.CLIP[0].PLANE : : -1 : 0 +#var float4 glstate.clip[1].plane : STATE.CLIP[1].PLANE : : -1 : 0 +#var float4 glstate.clip[2].plane : STATE.CLIP[2].PLANE : : -1 : 0 +#var float4 glstate.clip[3].plane : STATE.CLIP[3].PLANE : : -1 : 0 +#var float4 glstate.clip[4].plane : STATE.CLIP[4].PLANE : : -1 : 0 +#var float4 glstate.clip[5].plane : STATE.CLIP[5].PLANE : : -1 : 0 +#var float4 glstate.clip[6].plane : STATE.CLIP[6].PLANE : : -1 : 0 +#var float4 glstate.clip[7].plane : STATE.CLIP[7].PLANE : : -1 : 0 +#var float glstate.point.size : STATE.POINT.SIZE : : -1 : 0 +#var float glstate.point.attenuation : STATE.POINT.ATTENUATION : : -1 : 0 +#var float4x4 glstate.matrix.modelview[0] : STATE.MATRIX.MODELVIEW[0] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[1] : STATE.MATRIX.MODELVIEW[1] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[2] : STATE.MATRIX.MODELVIEW[2] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[3] : STATE.MATRIX.MODELVIEW[3] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[4] : STATE.MATRIX.MODELVIEW[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[5] : STATE.MATRIX.MODELVIEW[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[6] : STATE.MATRIX.MODELVIEW[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.modelview[7] : STATE.MATRIX.MODELVIEW[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.projection : STATE.MATRIX.PROJECTION : , 4 : -1 : 0 +#var float4x4 glstate.matrix.mvp : STATE.MATRIX.MVP : c[0], 4 : -1 : 1 +#var float4x4 glstate.matrix.texture[0] : STATE.MATRIX.TEXTURE[0] : c[4], 4 : -1 : 1 +#var float4x4 glstate.matrix.texture[1] : STATE.MATRIX.TEXTURE[1] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[2] : STATE.MATRIX.TEXTURE[2] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[3] : STATE.MATRIX.TEXTURE[3] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[4] : STATE.MATRIX.TEXTURE[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[5] : STATE.MATRIX.TEXTURE[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[6] : STATE.MATRIX.TEXTURE[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.texture[7] : STATE.MATRIX.TEXTURE[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[0] : STATE.MATRIX.PALETTE[0] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[1] : STATE.MATRIX.PALETTE[1] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[2] : STATE.MATRIX.PALETTE[2] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[3] : STATE.MATRIX.PALETTE[3] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[4] : STATE.MATRIX.PALETTE[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[5] : STATE.MATRIX.PALETTE[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[6] : STATE.MATRIX.PALETTE[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.palette[7] : STATE.MATRIX.PALETTE[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[0] : STATE.MATRIX.PROGRAM[0] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[1] : STATE.MATRIX.PROGRAM[1] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[2] : STATE.MATRIX.PROGRAM[2] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[3] : STATE.MATRIX.PROGRAM[3] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[4] : STATE.MATRIX.PROGRAM[4] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[5] : STATE.MATRIX.PROGRAM[5] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[6] : STATE.MATRIX.PROGRAM[6] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.program[7] : STATE.MATRIX.PROGRAM[7] : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.projection : STATE.MATRIX.PROJECTION.INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.mvp : STATE.MATRIX.MVP.INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[0] : STATE.MATRIX.TEXTURE[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[1] : STATE.MATRIX.TEXTURE[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[2] : STATE.MATRIX.TEXTURE[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[3] : STATE.MATRIX.TEXTURE[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[4] : STATE.MATRIX.TEXTURE[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[5] : STATE.MATRIX.TEXTURE[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[6] : STATE.MATRIX.TEXTURE[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.texture[7] : STATE.MATRIX.TEXTURE[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[0] : STATE.MATRIX.PALETTE[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[1] : STATE.MATRIX.PALETTE[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[2] : STATE.MATRIX.PALETTE[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[3] : STATE.MATRIX.PALETTE[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[4] : STATE.MATRIX.PALETTE[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[5] : STATE.MATRIX.PALETTE[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[6] : STATE.MATRIX.PALETTE[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.palette[7] : STATE.MATRIX.PALETTE[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[0] : STATE.MATRIX.PROGRAM[0].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[1] : STATE.MATRIX.PROGRAM[1].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[2] : STATE.MATRIX.PROGRAM[2].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[3] : STATE.MATRIX.PROGRAM[3].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[4] : STATE.MATRIX.PROGRAM[4].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[5] : STATE.MATRIX.PROGRAM[5].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[6] : STATE.MATRIX.PROGRAM[6].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.inverse.program[7] : STATE.MATRIX.PROGRAM[7].INVERSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[0] : STATE.MATRIX.MODELVIEW[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[1] : STATE.MATRIX.MODELVIEW[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[2] : STATE.MATRIX.MODELVIEW[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[3] : STATE.MATRIX.MODELVIEW[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[4] : STATE.MATRIX.MODELVIEW[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[5] : STATE.MATRIX.MODELVIEW[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[6] : STATE.MATRIX.MODELVIEW[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.modelview[7] : STATE.MATRIX.MODELVIEW[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.projection : STATE.MATRIX.PROJECTION.TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.mvp : STATE.MATRIX.MVP.TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[0] : STATE.MATRIX.TEXTURE[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[1] : STATE.MATRIX.TEXTURE[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[2] : STATE.MATRIX.TEXTURE[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[3] : STATE.MATRIX.TEXTURE[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[4] : STATE.MATRIX.TEXTURE[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[5] : STATE.MATRIX.TEXTURE[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[6] : STATE.MATRIX.TEXTURE[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.texture[7] : STATE.MATRIX.TEXTURE[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[0] : STATE.MATRIX.PALETTE[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[1] : STATE.MATRIX.PALETTE[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[2] : STATE.MATRIX.PALETTE[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[3] : STATE.MATRIX.PALETTE[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[4] : STATE.MATRIX.PALETTE[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[5] : STATE.MATRIX.PALETTE[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[6] : STATE.MATRIX.PALETTE[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.palette[7] : STATE.MATRIX.PALETTE[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[0] : STATE.MATRIX.PROGRAM[0].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[1] : STATE.MATRIX.PROGRAM[1].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[2] : STATE.MATRIX.PROGRAM[2].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[3] : STATE.MATRIX.PROGRAM[3].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[4] : STATE.MATRIX.PROGRAM[4].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[5] : STATE.MATRIX.PROGRAM[5].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[6] : STATE.MATRIX.PROGRAM[6].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.transpose.program[7] : STATE.MATRIX.PROGRAM[7].TRANSPOSE : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[0] : STATE.MATRIX.MODELVIEW[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[1] : STATE.MATRIX.MODELVIEW[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[2] : STATE.MATRIX.MODELVIEW[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[3] : STATE.MATRIX.MODELVIEW[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[4] : STATE.MATRIX.MODELVIEW[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[5] : STATE.MATRIX.MODELVIEW[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[6] : STATE.MATRIX.MODELVIEW[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.modelview[7] : STATE.MATRIX.MODELVIEW[7].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.projection : STATE.MATRIX.PROJECTION.INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.mvp : STATE.MATRIX.MVP.INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[0] : STATE.MATRIX.TEXTURE[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[1] : STATE.MATRIX.TEXTURE[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[2] : STATE.MATRIX.TEXTURE[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[3] : STATE.MATRIX.TEXTURE[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[4] : STATE.MATRIX.TEXTURE[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[5] : STATE.MATRIX.TEXTURE[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[6] : STATE.MATRIX.TEXTURE[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.texture[7] : STATE.MATRIX.TEXTURE[7].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[0] : STATE.MATRIX.PALETTE[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[1] : STATE.MATRIX.PALETTE[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[2] : STATE.MATRIX.PALETTE[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[3] : STATE.MATRIX.PALETTE[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[4] : STATE.MATRIX.PALETTE[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[5] : STATE.MATRIX.PALETTE[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[6] : STATE.MATRIX.PALETTE[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.palette[7] : STATE.MATRIX.PALETTE[7].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[0] : STATE.MATRIX.PROGRAM[0].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[1] : STATE.MATRIX.PROGRAM[1].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[2] : STATE.MATRIX.PROGRAM[2].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[3] : STATE.MATRIX.PROGRAM[3].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[4] : STATE.MATRIX.PROGRAM[4].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[5] : STATE.MATRIX.PROGRAM[5].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[6] : STATE.MATRIX.PROGRAM[6].INVTRANS : , 4 : -1 : 0 +#var float4x4 glstate.matrix.invtrans.program[7] : STATE.MATRIX.PROGRAM[7].INVTRANS : , 4 : -1 : 0 +#var float4 IN.position : $vin.ATTR0 : ATTR0 : 0 : 1 +#var float4 IN.texcoord0 : $vin.ATTR8 : ATTR8 : 0 : 1 +#var float4 main.position : $vout.HPOS : HPOS : -1 : 1 +#var float4 main.tex0 : $vout.TEX0 : TEX0 : -1 : 1 +PARAM c[8] = { state.matrix.mvp, + state.matrix.texture[0] }; +DP4 result.position.w, vertex.attrib[0], c[3]; +DP4 result.position.z, vertex.attrib[0], c[2]; +DP4 result.position.y, vertex.attrib[0], c[1]; +DP4 result.position.x, vertex.attrib[0], c[0]; +DP4 result.texcoord[0].w, vertex.attrib[8], c[7]; +DP4 result.texcoord[0].z, vertex.attrib[8], c[6]; +DP4 result.texcoord[0].y, vertex.attrib[8], c[5]; +DP4 result.texcoord[0].x, vertex.attrib[8], c[4]; +END +# 8 instructions, 0 R-regs diff --git a/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_vp.glsl b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_vp.glsl new file mode 100644 index 00000000..4c81280e --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/gl/zfill_vp.glsl @@ -0,0 +1,35 @@ +/// ============================================================================ +/* +Copyright (C) 2004 Robert Beckebans +Please see the file "CONTRIBUTORS" for a list of contributors + +This program 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 program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +*/ +/// ============================================================================ + +attribute vec4 attr_TexCoord0; + +void main() +{ + // transform vertex position into homogenous clip-space + gl_Position = ftransform(); + + // transform texcoords + gl_TexCoord[0] = gl_TextureMatrix[0] * gl_MultiTexCoord0; + + // assign color + gl_FrontColor = gl_Color; +} diff --git a/misc/mediasource/netradiant-src/setup/data/tools/global.xlink b/misc/mediasource/netradiant-src/setup/data/tools/global.xlink new file mode 100644 index 00000000..3ca47f1a --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/global.xlink @@ -0,0 +1,7 @@ + + + + + + + diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_caulk.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_caulk.bmp new file mode 100644 index 00000000..52239503 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_caulk.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_cleanup.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_cleanup.bmp new file mode 100644 index 00000000..8939d5d7 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_cleanup.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_dropent.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_dropent.bmp new file mode 100644 index 00000000..2fcdcba3 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_dropent.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_merge.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_merge.bmp new file mode 100644 index 00000000..2184f7a7 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_merge.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_poly.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_poly.bmp new file mode 100644 index 00000000..e714f3b9 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_poly.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_split.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_split.bmp new file mode 100644 index 00000000..7e1dc72f Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_split.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitcol.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitcol.bmp new file mode 100644 index 00000000..3d47fdcb Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitcol.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitrow.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitrow.bmp new file mode 100644 index 00000000..03b1ae3a Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_splitrow.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_trainpathplot.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_trainpathplot.bmp new file mode 100644 index 00000000..66537dc1 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_trainpathplot.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_treeplanter.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_treeplanter.bmp new file mode 100644 index 00000000..5c967ab2 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_treeplanter.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_turnedge.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_turnedge.bmp new file mode 100644 index 00000000..b72cb2aa Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/bobtoolz_turnedge.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_actorclip.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_actorclip.bmp new file mode 100644 index 00000000..4a2887c6 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_actorclip.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level1.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level1.bmp new file mode 100644 index 00000000..80a4b299 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level1.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level2.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level2.bmp new file mode 100644 index 00000000..e84e2544 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level2.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level3.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level3.bmp new file mode 100644 index 00000000..141c3245 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level3.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level4.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level4.bmp new file mode 100644 index 00000000..3783a803 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level4.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level5.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level5.bmp new file mode 100644 index 00000000..8f62851c Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level5.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level6.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level6.bmp new file mode 100644 index 00000000..418fdd28 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level6.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level7.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level7.bmp new file mode 100644 index 00000000..d82dab61 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level7.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level8.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level8.bmp new file mode 100644 index 00000000..c3809538 Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_level8.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_nodraw.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_nodraw.bmp new file mode 100644 index 00000000..3eaa529c Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_nodraw.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_stepon.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_stepon.bmp new file mode 100644 index 00000000..b73896fb Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_stepon.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_weaponclip.bmp b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_weaponclip.bmp new file mode 100644 index 00000000..799468ba Binary files /dev/null and b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bitmaps/ufoai_weaponclip.bmp differ diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/bt-el1.txt b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/bt-el1.txt new file mode 100644 index 00000000..f6485f94 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/bt-el1.txt @@ -0,0 +1,17 @@ +common/areaportal +common/clip +common/clusterportal +common/cushion +common/donotenter +common/full_clip +common/hint +common/missileclip +common/nodraw +common/nodrawnonsolid +common/nodrop +common/noimpact +common/origin +common/trigger +common/weapclip +liquid +fog \ No newline at end of file diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/bt-el2.txt b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/bt-el2.txt new file mode 100644 index 00000000..e69de29b diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/door-tex-trim.txt b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/door-tex-trim.txt new file mode 100644 index 00000000..d52ef76f --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/door-tex-trim.txt @@ -0,0 +1,5 @@ +base_support/support1rust +base_support/support1shiny +base_support/support2rust +base_support/wplat1_1 +base_support/plate2_5 \ No newline at end of file diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/door-tex.txt b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/door-tex.txt new file mode 100644 index 00000000..69629989 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/door-tex.txt @@ -0,0 +1,10 @@ +base_door/shinymetaldoor +base_door/shinymetaldoor_outside +gothic_door/door02_bred +gothic_door/door02_bred2_shiny +gothic_door/door02_eblue2_shiny +gothic_door/door02_i_ornate5_fin +gothic_door/door02_j +gothic_door/door02_j3 +gothic_door/door02_j4 +gothic_door/door02_k2b \ No newline at end of file diff --git a/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/tp_ent.txt b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/tp_ent.txt new file mode 100644 index 00000000..f0645b34 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/plugins/bt/tp_ent.txt @@ -0,0 +1,14 @@ +{ + "entity" "misc_model" + + "offset" "-16" + + "model" "models/mapobjects/trees_sd/tree_a.md3" + "model" "models/mapobjects/trees_sd/tree_b.md3" + "model" "models/mapobjects/trees_sd/tree_c.md3" + "model" "models/mapobjects/trees_sd/tree_d.md3" + + "pitch" "-5" "5" + "yaw" "0" "360" + "scale" "1" "1.3" +} \ No newline at end of file diff --git a/misc/mediasource/netradiant-src/setup/data/tools/q3data.qdt b/misc/mediasource/netradiant-src/setup/data/tools/q3data.qdt new file mode 100644 index 00000000..ba30ee12 --- /dev/null +++ b/misc/mediasource/netradiant-src/setup/data/tools/q3data.qdt @@ -0,0 +1,552 @@ +$aseconvert models/mapobjects/spotlamp/spotlamp_x.ase +$exit + + +$aseconvert models/weapons2/machinegun/machinegun.ase -weapon +$aseconvert models/weapons2/bfg/bfg.ase -weapon +$aseconvert models/weapons2/railgun/railgun.ase -weapon +$aseconvert models/weapons2/shotgun/shotgun.ase -weapon + +$aseconvert models/weapons2/meshes/chaingun.ase -weapon +$aseconvert models/weapons2/meshes/flamethrower.ase -weapon +$aseconvert models/weapons2/meshes/grapple.ase -weapon +$aseconvert models/weapons2/meshes/grenadel.ase -weapon +$aseconvert models/weapons2/meshes/lightning.ase -weapon +$aseconvert models/weapons2/meshes/plasma.ase -weapon +$aseconvert models/weapons2/meshes/railgun.ase -weapon +$aseconvert models/weapons2/meshes/ricochet.ase -weapon +$aseconvert models/weapons2/meshes/rocketl.ase -weapon +$aseconvert models/weapons2/meshes/shotgun.ase -weapon + + +$aseconvert models/mapobjects/chain1.ase +$aseconvert models/mapobjects/chain2.ase +$aseconvert models/mapobjects/chain3.ase +$aseconvert models/mapobjects/chain4.ase + +$exit + +$aseanimconvert models/players/light/bandolier/bandolier.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/brandon/4brandon.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/cash/4cash.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/doom/doom.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/shauna/shauna.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/tim/4tim.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/visor/4visor.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/xian/4xian.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/carmack/carmack.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/heavy/paulj/4paulj.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/heavy/brock/brock.ase -origin 0 0 24 -playerparms 75 138 140 1 + +$exit + +// note: playerparms are "skipStart skipEnd maxUpperFrames maxHeadFrames" +$aseanimconvert models/players/medium/visor/4visor.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/visor/4visor.ase -lod 1 0 -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/visor/4visor.ase -lod 2 0 -origin 0 0 24 -playerparms 75 138 140 1 + + + +$aseconvert models/powerups/ammo/backpack.ase + +$aseconvert models/weapons2/meshes/assault.ase -weapon +$aseconvert models/weapons2/meshes/chaingun.ase -weapon +$aseconvert models/weapons2/meshes/flamethrower.ase -weapon +$aseconvert models/weapons2/meshes/grapple.ase -weapon +$aseconvert models/weapons2/meshes/grenadel.ase -weapon +$aseconvert models/weapons2/meshes/lightning.ase -weapon +$aseconvert models/weapons2/meshes/plasma.ase -weapon +$aseconvert models/weapons2/meshes/railgun.ase -weapon +$aseconvert models/weapons2/meshes/ricochet.ase -weapon +$aseconvert models/weapons2/meshes/rocketl.ase -weapon +$aseconvert models/weapons2/meshes/shotgun.ase -weapon + +$aseconvert models/mapobjects/arenalogo.ase + +// +// talk sprite +// +$modelname sprites/balloon +$cd sprites +$spritebase -8 -8 16 16 +$spriteshader sprites/balloon3.tga + +// plasma ball sprite +$modelname sprites/plasma +$cd sprites +$spritebase -16 -16 32 32 +$spriteshader sprites/plasma1.tga +$spriteshader sprites/plasma2.tga + +// +// player models +// note: playerparms are "skipStart skipEnd maxUpperFrames maxHeadFrames" +// +$aseanimconvert models/players/light/bandolier/bandolier.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/brandon/4brandon.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/cash/4cash.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/doom/doom.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/light/shauna/shauna.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/tim/4tim.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/visor/4visor.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/xian/4xian.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/medium/carmack/carmack.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/heavy/paulj/4paulj.ase -origin 0 0 24 -playerparms 75 138 140 1 +$aseanimconvert models/players/heavy/brock/brock.ase -origin 0 0 24 -playerparms 75 138 140 1 + +// +// weaphits +// +$modelname models/weaphits/bullet +$cd models/weaphits +$base bullet01.3ds +$frame bullet01.3ds +$frame bullet02.3ds +$frame bullet03.3ds +$frame bullet04.3ds +$frame bullet05.3ds +$frame bullet06.3ds +$skin bullet01.3ds +$skin bullet03.3ds +$skin bullet05.3ds + +$modelname models/weaphits/ring01 +$cd models/weaphits +$base ring01_1.3ds +$frame ring01_1.3ds +$frame ring01_2.3ds +$frame ring01_3.3ds +$frame ring01_4.3ds +$frame ring01_5.3ds +$frame ring01_6.3ds +$skin ring01_1.3ds +$skin ring01_3.3ds +$skin ring01_5.3ds + +$modelname models/weaphits/ring02 +$cd models/weaphits +$base ring02_1.3ds +$frame ring02_1.3ds +$frame ring02_2.3ds +$frame ring02_3.3ds +$frame ring02_4.3ds +$frame ring02_5.3ds +$frame ring02_6.3ds +$skin ring02_1.3ds +$skin ring02_3.3ds +$skin ring02_5.3ds + +$modelname models/weaphits/boomgra +$cd models/weaphits +$base boomgra1.3ds +$frame boomgra1.3ds +$frame boomgra2.3ds +$frame boomgra3.3ds +$frame boomgra4.3ds +$frame boomgra5.3ds +$frame boomgra6.3ds +$skin boomgra1.3ds +$skin boomgra3.3ds +$skin boomgra5.3ds + +$modelname models/weaphits/boom01 +$cd models/weaphits +$base boom01_1.3ds +$frame boom01_1.3ds +$frame boom01_2.3ds +$frame boom01_3.3ds +$frame boom01_4.3ds +$frame boom01_5.3ds +$frame boom01_6.3ds +$skin boom01_1.3ds +$skin boom01_3.3ds +$skin boom01_5.3ds + +$modelname models/weaphits/boom02 +$cd models/weaphits +$base boom02_1.3ds +$frame boom02_1.3ds +$frame boom02_2.3ds +$frame boom02_3.3ds +$frame boom02_4.3ds +$frame boom02_5.3ds +$frame boom02_6.3ds +$skin boom02_1.3ds +$skin boom02_3.3ds +$skin boom02_5.3ds + +$modelname models/weaphits/boom03 +$cd models/weaphits +$base boom03_1.3ds +$frame boom03_1.3ds +$frame boom03_2.3ds +$frame boom03_3.3ds +$frame boom03_4.3ds +$frame boom03_5.3ds +$frame boom03_6.3ds +$skin boom03_1.3ds +$skin boom03_3.3ds +$skin boom03_5.3ds + +$modelname models/weaphits/boom04 +$cd models/weaphits +$base boom04_1.3ds +$frame boom04_1.3ds +$frame boom04_2.3ds +$frame boom04_3.3ds +$frame boom04_4.3ds +$frame boom04_5.3ds +$frame boom04_6.3ds +$skin boom04_1.3ds +$skin boom04_3.3ds +$skin boom04_5.3ds + +$modelname models/weaphits/boom05 +$cd models/weaphits +$base boom05_1.3ds +$frame boom05_1.3ds +$frame boom05_2.3ds +$frame boom05_3.3ds +$frame boom05_4.3ds +$frame boom05_5.3ds +$frame boom05_6.3ds +$skin boom05_1.3ds +$skin boom05_3.3ds +$skin boom05_5.3ds + +// +// point powerups +// +$aseconvert models/powerups/points/small.ase +$aseconvert models/powerups/points/medium.ase +$aseconvert models/powerups/points/large.ase + +// +// ammo +// +$aseconvert models\powerups\ammo\bfgam.ASE +$aseconvert models\powerups\ammo\bfgam_1.ASE +$aseconvert models\powerups\ammo\bouncyam.ASE +$aseconvert models\powerups\ammo\bouncyam_1.ASE +$aseconvert models\powerups\ammo\carbineam.ASE +$aseconvert models\powerups\ammo\carbineam_1.ASE +$aseconvert models\powerups\ammo\flameam.ASE +$aseconvert models\powerups\ammo\flameam_1.ASE +$aseconvert models\powerups\ammo\grenadeam.ASE +$aseconvert models\powerups\ammo\grenadeam_1.ASE +$aseconvert models\powerups\ammo\lightningam.ASE +$aseconvert models\powerups\ammo\lightningam_1.ASE +$aseconvert models\powerups\ammo\machinegunam.ASE +$aseconvert models\powerups\ammo\machinegunam_1.ASE +$aseconvert models\powerups\ammo\plasmaam.ASE +$aseconvert models\powerups\ammo\plasmaam_1.ASE +$aseconvert models\powerups\ammo\railgunam.ASE +$aseconvert models\powerups\ammo\railgunam_1.ASE +$aseconvert models\powerups\ammo\rocketam.ASE +$aseconvert models\powerups\ammo\rocketam_1.ASE +$aseconvert models\powerups\ammo\shotgunam.ASE +$aseconvert models\powerups\ammo\shotgunam_1.ASE + +$aseconvert models/powerups/ammo/backpack.ase + +// +// missiles +// +$modelname models/ammo/plasma/plasma +$cd models/ammo/plasma +$base plasma1.3ds +$frame plasma1.3ds +$skin plasma1.3ds + +$modelname models/ammo/laser/laser +$cd models/ammo/laser +$base laser1.3ds +$frame laser1.3ds +$skin laser1.3ds + +$modelname models/ammo/rocket/rocket +$cd models/ammo/rocket +$base rocket1.3ds +$frame rocket1.3ds +$skin rocket1.3ds +$skin rocket2.3ds + +$aseconvert models/ammo/grenade1.ase +$aseconvert models/explosions/smoke2.ase + +// +// map objects +// +$aseconvert models/mapobjects/ceilinglamp1.ase +$aseconvert models/mapobjects/ceilinglamp2.ase +$aseconvert models/mapobjects/chain1.ase +$aseconvert models/mapobjects/chain2.ase +$aseconvert models/mapobjects/chain3.ase +$aseconvert models/mapobjects/chain4.ase +$aseconvert models/mapobjects/crux.ase +$aseconvert models/mapobjects/floorlamp1.ase +$aseconvert models/mapobjects/floorlamp2.ase +$aseconvert models/mapobjects/hook.ase +$aseconvert models/mapobjects/impale.ase +$aseconvert models/mapobjects/standinglamp1.ase +$aseconvert models/mapobjects/standinglamp2.ase +$aseconvert models/mapobjects/standinglamp3.ase +$aseconvert models/mapobjects/walllamp1.ase +$aseconvert models/mapobjects/walllamp2.ase +$aseconvert models/mapobjects/walllamp3.ase + + +// +// objects +// +$aseconvert models/objects/dmspot.ase -origin 0 0 24 +$aseconvert models/objects/box01.ase + +// +// weapons +// +$aseconvert models/weapons2/meshes/assault.ase -weapon +$aseconvert models/weapons2/meshes/bfg.ase -weapon +$aseconvert models/weapons2/meshes/chaingun.ase -weapon +$aseconvert models/weapons2/meshes/flamethrower.ase -weapon +$aseconvert models/weapons2/meshes/grapple.ase -weapon +$aseconvert models/weapons2/meshes/grenadel.ase -weapon +$aseconvert models/weapons2/meshes/lightning.ase -weapon +$aseconvert models/weapons2/meshes/plasma.ase -weapon +$aseconvert models/weapons2/meshes/railgun.ase -weapon +$aseconvert models/weapons2/meshes/ricochet.ase -weapon +$aseconvert models/weapons2/meshes/rocketl.ase -weapon +$aseconvert models/weapons2/meshes/shotgun.ase -weapon + +// +// blood +// +$modelname models/weaphits/blood +$cd models/weaphits +$spritebase -16 -16 32 32 +$spriteshader models/weaphits/blood201.tga +$spriteshader models/weaphits/blood202.tga +$spriteshader models/weaphits/blood203.tga +$spriteshader models/weaphits/blood204.tga +$spriteshader models/weaphits/blood205.tga + + +// +// missiles +// +$modelname models/ammo/plasma/plasma +$cd models/ammo/plasma +$base plasma1.3ds +$frame plasma1.3ds +$skin plasma1.3ds + +$modelname models/ammo/laser/laser +$cd models/ammo/laser +$base laser1.3ds +$frame laser1.3ds +$skin laser1.3ds + + +$modelname models/ammo/rocket/rocket +$cd models/ammo/rocket +$base rocket1.3ds +$frame rocket1.3ds +$skin rocket1.3ds +$skin rocket2.3ds + + +// weaphits + +$modelname models/weaphits/bullet +$cd models/weaphits +$base bullet01.3ds +$frame bullet01.3ds +$frame bullet02.3ds +$frame bullet03.3ds +$frame bullet04.3ds +$frame bullet05.3ds +$frame bullet06.3ds +$skin bullet01.3ds +$skin bullet03.3ds +$skin bullet05.3ds + +$modelname models/weaphits/ring01 +$cd models/weaphits +$base ring01_1.3ds +$frame ring01_1.3ds +$frame ring01_2.3ds +$frame ring01_3.3ds +$frame ring01_4.3ds +$frame ring01_5.3ds +$frame ring01_6.3ds +$skin ring01_1.3ds +$skin ring01_3.3ds +$skin ring01_5.3ds + +$modelname models/weaphits/ring02 +$cd models/weaphits +$base ring02_1.3ds +$frame ring02_1.3ds +$frame ring02_2.3ds +$frame ring02_3.3ds +$frame ring02_4.3ds +$frame ring02_5.3ds +$frame ring02_6.3ds +$skin ring02_1.3ds +$skin ring02_3.3ds +$skin ring02_5.3ds + +$modelname models/weaphits/boomgra +$cd models/weaphits +$base boomgra1.3ds +$frame boomgra1.3ds +$frame boomgra2.3ds +$frame boomgra3.3ds +$frame boomgra4.3ds +$frame boomgra5.3ds +$frame boomgra6.3ds +$skin boomgra1.3ds +$skin boomgra3.3ds +$skin boomgra5.3ds + +$modelname models/weaphits/boom01 +$cd models/weaphits +$base boom01_1.3ds +$frame boom01_1.3ds +$frame boom01_2.3ds +$frame boom01_3.3ds +$frame boom01_4.3ds +$frame boom01_5.3ds +$frame boom01_6.3ds +$skin boom01_1.3ds +$skin boom01_3.3ds +$skin boom01_5.3ds + +$modelname models/weaphits/boom02 +$cd models/weaphits +$base boom02_1.3ds +$frame boom02_1.3ds +$frame boom02_2.3ds +$frame boom02_3.3ds +$frame boom02_4.3ds +$frame boom02_5.3ds +$frame boom02_6.3ds +$skin boom02_1.3ds +$skin boom02_3.3ds +$skin boom02_5.3ds + +$modelname models/weaphits/boom03 +$cd models/weaphits +$base boom03_1.3ds +$frame boom03_1.3ds +$frame boom03_2.3ds +$frame boom03_3.3ds +$frame boom03_4.3ds +$frame boom03_5.3ds +$frame boom03_6.3ds +$skin boom03_1.3ds +$skin boom03_3.3ds +$skin boom03_5.3ds + +$modelname models/weaphits/boom04 +$cd models/weaphits +$base boom04_1.3ds +$frame boom04_1.3ds +$frame boom04_2.3ds +$frame boom04_3.3ds +$frame boom04_4.3ds +$frame boom04_5.3ds +$frame boom04_6.3ds +$skin boom04_1.3ds +$skin boom04_3.3ds +$skin boom04_5.3ds + +$modelname models/weaphits/boom05 +$cd models/weaphits +$base boom05_1.3ds +$frame boom05_1.3ds +$frame boom05_2.3ds +$frame boom05_3.3ds +$frame boom05_4.3ds +$frame boom05_5.3ds +$frame boom05_6.3ds +$skin boom05_1.3ds +$skin boom05_3.3ds +$skin boom05_5.3ds + + +// +// armor +// +$aseconvert models/powerups/armor/armor_red.ase +$aseconvert models/powerups/armor/armor_yel.ase +$aseconvert models/powerups/armor/armor_grn.ase +$aseconvert models/powerups/armor/shard.ase +$aseconvert models/powerups/armor/shard_sphere.ase +$aseconvert models/powerups/armor/shard_sphere_1.ase + +// +// health +// +$aseconvert models/powerups/health/small.ase +$aseconvert models/powerups/health/small_1.ase +$aseconvert models/powerups/health/medium.ase +$aseconvert models/powerups/health/medium_1.ase +$aseconvert models/powerups/health/large.ase +$aseconvert models/powerups/health/large_1.ase +$aseconvert models/powerups/health/mega.ase +$aseconvert models/powerups/health/mega_1.ase + +// +// holdable powerups +// +$aseconvert models/powerups/holdable/ringodeth.ase +$aseconvert models/powerups/holdable/medkit.ase +$aseconvert models/powerups/holdable/teleporter.ase + +// +// instant powerups +// +$aseconvert models/powerups/instant/enviro.ase +$aseconvert models/powerups/instant/enviro_1.ase +$aseconvert models/powerups/instant/enviro_ring.ase +$aseconvert models/powerups/instant/enviro_ring_1.ase +$aseconvert models/powerups/instant/flight.ase +$aseconvert models/powerups/instant/flight_1.ase +$aseconvert models/powerups/instant/flight_ring.ase +$aseconvert models/powerups/instant/flight_ring_1.ase +$aseconvert models/powerups/instant/haste.ase +$aseconvert models/powerups/instant/haste_1.ase +$aseconvert models/powerups/instant/haste_ring.ase +$aseconvert models/powerups/instant/haste_ring_1.ase +$aseconvert models/powerups/instant/invis.ase +$aseconvert models/powerups/instant/invis_1.ase +$aseconvert models/powerups/instant/invis_ring.ase +$aseconvert models/powerups/instant/invis_ring_1.ase +$aseconvert models/powerups/instant/scan.ase +$aseconvert models/powerups/instant/scan_1.ase +$aseconvert models/powerups/instant/scan_ring.ase +$aseconvert models/powerups/instant/scan_ring_1.ase +$aseconvert models/powerups/instant/quad.ase +$aseconvert models/powerups/instant/quad_1.ase +$aseconvert models/powerups/instant/quad_ring.ase +$aseconvert models/powerups/instant/quad_ring_1.ase +$aseconvert models/powerups/instant/regen.ase +$aseconvert models/powerups/instant/regen_1.ase +$aseconvert models/powerups/instant/regen_ring.ase +$aseconvert models/powerups/instant/regen_ring_1.ase + +$exit + +// +// maps +// +$maps test_box test_items mirror mirror2 + + +// +// misc +// +$file q3default.cfg + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/bspfile.c b/misc/mediasource/netradiant-src/tools/quake2/common/bspfile.c new file mode 100644 index 00000000..05808c51 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/bspfile.c @@ -0,0 +1,789 @@ +/* +Copyright (C) 1999-2006 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 "bspfile.h" +#include "scriplib.h" +#include "inout.h" + +void GetLeafNums (void); + +//============================================================================= + +int nummodels; +dmodel_t dmodels[MAX_MAP_MODELS]; + +int visdatasize; +byte dvisdata[MAX_MAP_VISIBILITY]; +dvis_t *dvis = (dvis_t *)dvisdata; + +int lightdatasize; +byte dlightdata[MAX_MAP_LIGHTING]; + +int entdatasize; +char dentdata[MAX_MAP_ENTSTRING]; + +int numleafs; +dleaf_t dleafs[MAX_MAP_LEAFS]; + +int numplanes; +dplane_t dplanes[MAX_MAP_PLANES]; + +int numvertexes; +dvertex_t dvertexes[MAX_MAP_VERTS]; + +int numnodes; +dnode_t dnodes[MAX_MAP_NODES]; + +int numtexinfo; +texinfo_t texinfo[MAX_MAP_TEXINFO]; + +int numfaces; +dface_t dfaces[MAX_MAP_FACES]; + +int numedges; +dedge_t dedges[MAX_MAP_EDGES]; + +int numleaffaces; +unsigned short dleaffaces[MAX_MAP_LEAFFACES]; + +int numleafbrushes; +unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; + +int numsurfedges; +int dsurfedges[MAX_MAP_SURFEDGES]; + +int numbrushes; +dbrush_t dbrushes[MAX_MAP_BRUSHES]; + +int numbrushsides; +dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; + +int numareas; +darea_t dareas[MAX_MAP_AREAS]; + +int numareaportals; +dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; + +byte dpop[256]; + +/* +=============== +CompressVis + +=============== +*/ +int CompressVis (byte *vis, byte *dest) +{ + int j; + int rep; + int visrow; + byte *dest_p; + + dest_p = dest; +// visrow = (r_numvisleafs + 7)>>3; + visrow = (dvis->numclusters + 7)>>3; + + for (j=0 ; j>3; + row = (dvis->numclusters+7)>>3; + out = decompressed; + + do + { + if (*in) + { + *out++ = *in++; + continue; + } + + c = in[1]; + if (!c) + Error ("DecompressVis: 0 repeat"); + in += 2; + while (c) + { + *out++ = 0; + c--; + } + } while (out - decompressed < row); +} + +//============================================================================= + +/* +============= +SwapBSPFile + +Byte swaps all data in a bsp file. +============= +*/ +void SwapBSPFile (qboolean todisk) +{ + int i, j; + dmodel_t *d; + + +// models + for (i=0 ; ifirstface = LittleLong (d->firstface); + d->numfaces = LittleLong (d->numfaces); + d->headnode = LittleLong (d->headnode); + + for (j=0 ; j<3 ; j++) + { + d->mins[j] = LittleFloat(d->mins[j]); + d->maxs[j] = LittleFloat(d->maxs[j]); + d->origin[j] = LittleFloat(d->origin[j]); + } + } + +// +// vertexes +// + for (i=0 ; inumclusters; + else + j = LittleLong(dvis->numclusters); + dvis->numclusters = LittleLong (dvis->numclusters); + for (i=0 ; ibitofs[i][0] = LittleLong (dvis->bitofs[i][0]); + dvis->bitofs[i][1] = LittleLong (dvis->bitofs[i][1]); + } +} + + +dheader_t *header; + +int CopyLump (int lump, void *dest, int size) +{ + int length, ofs; + + length = header->lumps[lump].filelen; + ofs = header->lumps[lump].fileofs; + + if (length % size) + Error ("LoadBSPFile: odd lump size"); + + memcpy (dest, (byte *)header + ofs, length); + + return length / size; +} + +/* +============= +LoadBSPFile +============= +*/ +void LoadBSPFile (char *filename) +{ + int i; + +// +// load the file header +// + LoadFile (filename, (void **)&header); + +// swap the header + for (i=0 ; i< sizeof(dheader_t)/4 ; i++) + ((int *)header)[i] = LittleLong ( ((int *)header)[i]); + + if (header->ident != IDBSPHEADER) + Error ("%s is not a IBSP file", filename); + if (header->version != BSPVERSION) + Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); + + nummodels = CopyLump (LUMP_MODELS, dmodels, sizeof(dmodel_t)); + numvertexes = CopyLump (LUMP_VERTEXES, dvertexes, sizeof(dvertex_t)); + numplanes = CopyLump (LUMP_PLANES, dplanes, sizeof(dplane_t)); + numleafs = CopyLump (LUMP_LEAFS, dleafs, sizeof(dleaf_t)); + numnodes = CopyLump (LUMP_NODES, dnodes, sizeof(dnode_t)); + numtexinfo = CopyLump (LUMP_TEXINFO, texinfo, sizeof(texinfo_t)); + numfaces = CopyLump (LUMP_FACES, dfaces, sizeof(dface_t)); + numleaffaces = CopyLump (LUMP_LEAFFACES, dleaffaces, sizeof(dleaffaces[0])); + numleafbrushes = CopyLump (LUMP_LEAFBRUSHES, dleafbrushes, sizeof(dleafbrushes[0])); + numsurfedges = CopyLump (LUMP_SURFEDGES, dsurfedges, sizeof(dsurfedges[0])); + numedges = CopyLump (LUMP_EDGES, dedges, sizeof(dedge_t)); + numbrushes = CopyLump (LUMP_BRUSHES, dbrushes, sizeof(dbrush_t)); + numbrushsides = CopyLump (LUMP_BRUSHSIDES, dbrushsides, sizeof(dbrushside_t)); + numareas = CopyLump (LUMP_AREAS, dareas, sizeof(darea_t)); + numareaportals = CopyLump (LUMP_AREAPORTALS, dareaportals, sizeof(dareaportal_t)); + + visdatasize = CopyLump (LUMP_VISIBILITY, dvisdata, 1); + lightdatasize = CopyLump (LUMP_LIGHTING, dlightdata, 1); + entdatasize = CopyLump (LUMP_ENTITIES, dentdata, 1); + + CopyLump (LUMP_POP, dpop, 1); + + free (header); // everything has been copied out + +// +// swap everything +// + SwapBSPFile (false); +} + + +/* +============= +LoadBSPFileTexinfo + +Only loads the texinfo lump, so qdata can scan for textures +============= +*/ +void LoadBSPFileTexinfo (char *filename) +{ + int i; + FILE *f; + int length, ofs; + + header = malloc(sizeof(dheader_t)); + + f = fopen (filename, "rb"); + fread (header, sizeof(dheader_t), 1, f); + +// swap the header + for (i=0 ; i< sizeof(dheader_t)/4 ; i++) + ((int *)header)[i] = LittleLong ( ((int *)header)[i]); + + if (header->ident != IDBSPHEADER) + Error ("%s is not a IBSP file", filename); + if (header->version != BSPVERSION) + Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); + + + length = header->lumps[LUMP_TEXINFO].filelen; + ofs = header->lumps[LUMP_TEXINFO].fileofs; + + fseek (f, ofs, SEEK_SET); + fread (texinfo, length, 1, f); + fclose (f); + + numtexinfo = length / sizeof(texinfo_t); + + free (header); // everything has been copied out + + SwapBSPFile (false); +} + + +//============================================================================ + +FILE *wadfile; +dheader_t outheader; + +void AddLump (int lumpnum, void *data, int len) +{ + lump_t *lump; + + lump = &header->lumps[lumpnum]; + + lump->fileofs = LittleLong( ftell(wadfile) ); + lump->filelen = LittleLong(len); + SafeWrite (wadfile, data, (len+3)&~3); +} + +/* +============= +WriteBSPFile + +Swaps the bsp file in place, so it should not be referenced again +============= +*/ +void WriteBSPFile (char *filename) +{ + header = &outheader; + memset (header, 0, sizeof(dheader_t)); + + SwapBSPFile (true); + + header->ident = LittleLong (IDBSPHEADER); + header->version = LittleLong (BSPVERSION); + + wadfile = SafeOpenWrite (filename); + SafeWrite (wadfile, header, sizeof(dheader_t)); // overwritten later + + AddLump (LUMP_PLANES, dplanes, numplanes*sizeof(dplane_t)); + AddLump (LUMP_LEAFS, dleafs, numleafs*sizeof(dleaf_t)); + AddLump (LUMP_VERTEXES, dvertexes, numvertexes*sizeof(dvertex_t)); + AddLump (LUMP_NODES, dnodes, numnodes*sizeof(dnode_t)); + AddLump (LUMP_TEXINFO, texinfo, numtexinfo*sizeof(texinfo_t)); + AddLump (LUMP_FACES, dfaces, numfaces*sizeof(dface_t)); + AddLump (LUMP_BRUSHES, dbrushes, numbrushes*sizeof(dbrush_t)); + AddLump (LUMP_BRUSHSIDES, dbrushsides, numbrushsides*sizeof(dbrushside_t)); + AddLump (LUMP_LEAFFACES, dleaffaces, numleaffaces*sizeof(dleaffaces[0])); + AddLump (LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes*sizeof(dleafbrushes[0])); + AddLump (LUMP_SURFEDGES, dsurfedges, numsurfedges*sizeof(dsurfedges[0])); + AddLump (LUMP_EDGES, dedges, numedges*sizeof(dedge_t)); + AddLump (LUMP_MODELS, dmodels, nummodels*sizeof(dmodel_t)); + AddLump (LUMP_AREAS, dareas, numareas*sizeof(darea_t)); + AddLump (LUMP_AREAPORTALS, dareaportals, numareaportals*sizeof(dareaportal_t)); + + AddLump (LUMP_LIGHTING, dlightdata, lightdatasize); + AddLump (LUMP_VISIBILITY, dvisdata, visdatasize); + AddLump (LUMP_ENTITIES, dentdata, entdatasize); + AddLump (LUMP_POP, dpop, sizeof(dpop)); + + fseek (wadfile, 0, SEEK_SET); + SafeWrite (wadfile, header, sizeof(dheader_t)); + fclose (wadfile); +} + +//============================================================================ + +/* +============= +PrintBSPFileSizes + +Dumps info about current file +============= +*/ +void PrintBSPFileSizes (void) +{ + if (!num_entities) + ParseEntities (); + + printf ("%5i models %7i\n" + ,nummodels, (int)(nummodels*sizeof(dmodel_t))); + printf ("%5i brushes %7i\n" + ,numbrushes, (int)(numbrushes*sizeof(dbrush_t))); + printf ("%5i brushsides %7i\n" + ,numbrushsides, (int)(numbrushsides*sizeof(dbrushside_t))); + printf ("%5i planes %7i\n" + ,numplanes, (int)(numplanes*sizeof(dplane_t))); + printf ("%5i texinfo %7i\n" + ,numtexinfo, (int)(numtexinfo*sizeof(texinfo_t))); + printf ("%5i entdata %7i\n", num_entities, entdatasize); + + printf ("\n"); + + printf ("%5i vertexes %7i\n" + ,numvertexes, (int)(numvertexes*sizeof(dvertex_t))); + printf ("%5i nodes %7i\n" + ,numnodes, (int)(numnodes*sizeof(dnode_t))); + printf ("%5i faces %7i\n" + ,numfaces, (int)(numfaces*sizeof(dface_t))); + printf ("%5i leafs %7i\n" + ,numleafs, (int)(numleafs*sizeof(dleaf_t))); + printf ("%5i leaffaces %7i\n" + ,numleaffaces, (int)(numleaffaces*sizeof(dleaffaces[0]))); + printf ("%5i leafbrushes %7i\n" + ,numleafbrushes, (int)(numleafbrushes*sizeof(dleafbrushes[0]))); + printf ("%5i surfedges %7i\n" + ,numsurfedges, (int)(numsurfedges*sizeof(dsurfedges[0]))); + printf ("%5i edges %7i\n" + ,numedges, (int)(numedges*sizeof(dedge_t))); + printf (" lightdata %7i\n", lightdatasize); + printf (" visdata %7i\n", visdatasize); +} + + +//============================================ + +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 = 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 (false); + if (strlen(token) >= MAX_VALUE-1) + Error ("ParseEpar: token too long"); + e->value = copystring(token); + + // strip trailing spaces + StripTrailing (e->key); + StripTrailing (e->value); + + return e; +} + + +/* +================ +ParseEntity +================ +*/ +qboolean ParseEntity (void) +{ + epair_t *e; + entity_t *mapent; + + if (!GetToken (true)) + return false; + + 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 (true)) + Error ("ParseEntity: EOF without closing brace"); + if (!strcmp (token, "}") ) + break; + e = ParseEpair (); + e->next = mapent->epairs; + mapent->epairs = e; + } while (1); + + return true; +} + +/* +================ +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 +================ +*/ +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 ; inext) + { + 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 (entity_t *ent) +{ + epair_t *ep; + + printf ("------- entity %p -------\n", ent); + for (ep=ent->epairs ; ep ; ep=ep->next) + { + printf ("%s = %s\n", ep->key, ep->value); + } + +} + +void SetKeyValue (entity_t *ent, char *key, 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 = malloc (sizeof(*ep)); + ep->next = ent->epairs; + ent->epairs = ep; + ep->key = copystring(key); + ep->value = copystring(value); +} + +char *ValueForKey (entity_t *ent, 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 (entity_t *ent, char *key) +{ + char *k; + + k = ValueForKey (ent, key); + return atof(k); +} + +void GetVectorForKey (entity_t *ent, char *key, vec3_t vec) +{ + 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/misc/mediasource/netradiant-src/tools/quake2/common/bspfile.h b/misc/mediasource/netradiant-src/tools/quake2/common/bspfile.h new file mode 100644 index 00000000..e11ec208 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/bspfile.h @@ -0,0 +1,128 @@ +/* +Copyright (C) 1999-2006 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" + + +extern int nummodels; +extern dmodel_t dmodels[MAX_MAP_MODELS]; + +extern int visdatasize; +extern byte dvisdata[MAX_MAP_VISIBILITY]; +extern dvis_t *dvis; + +extern int lightdatasize; +extern byte dlightdata[MAX_MAP_LIGHTING]; + +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 numvertexes; +extern dvertex_t dvertexes[MAX_MAP_VERTS]; + +extern int numnodes; +extern dnode_t dnodes[MAX_MAP_NODES]; + +extern int numtexinfo; +extern texinfo_t texinfo[MAX_MAP_TEXINFO]; + +extern int numfaces; +extern dface_t dfaces[MAX_MAP_FACES]; + +extern int numedges; +extern dedge_t dedges[MAX_MAP_EDGES]; + +extern int numleaffaces; +extern unsigned short dleaffaces[MAX_MAP_LEAFFACES]; + +extern int numleafbrushes; +extern unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; + +extern int numsurfedges; +extern int dsurfedges[MAX_MAP_SURFEDGES]; + +extern int numareas; +extern darea_t dareas[MAX_MAP_AREAS]; + +extern int numareaportals; +extern dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; + +extern int numbrushes; +extern dbrush_t dbrushes[MAX_MAP_BRUSHES]; + +extern int numbrushsides; +extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; + +extern byte dpop[256]; + +void DecompressVis (byte *in, byte *decompressed); +int CompressVis (byte *vis, byte *dest); + +void LoadBSPFile (char *filename); +void LoadBSPFileTexinfo (char *filename); // just for qdata +void WriteBSPFile (char *filename); +void PrintBSPFileSizes (void); + +//=============== + + +typedef struct epair_s +{ + struct epair_s *next; + char *key; + char *value; +} epair_t; + +typedef struct +{ + vec3_t origin; + int firstbrush; + int numbrushes; + epair_t *epairs; + +// only valid for func_areaportals + int areaportalnum; + int portalareas[2]; +} entity_t; + +extern int num_entities; +extern entity_t entities[MAX_MAP_ENTITIES]; + +void ParseEntities (void); +void UnparseEntities (void); + +void SetKeyValue (entity_t *ent, char *key, char *value); +char *ValueForKey (entity_t *ent, char *key); +// will return "" if not present + +vec_t FloatForKey (entity_t *ent, char *key); +void GetVectorForKey (entity_t *ent, char *key, vec3_t vec); + +epair_t *ParseEpair (void); + +void PrintEntity (entity_t *ent); + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/cmdlib.c b/misc/mediasource/netradiant-src/tools/quake2/common/cmdlib.c new file mode 100644 index 00000000..e59bf215 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/cmdlib.c @@ -0,0 +1,1221 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// Nurail: Swiped from quake3/common + +#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 HERETIC2_BASEDIRNAME "h" +#define PATHSEPERATOR '/' + +// qboolean verbose = false; + +#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); + + memset(p, 0, 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); + + memset(p, 0, 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; + char basedirname[256]; + + if (!(path[0] == '/' || path[0] == '\\' || path[1] == ':')) + { // path is partial + Q_getwd (temp); + strcat (temp, path); + path = temp; + } + + // search for "quake2" in path + + if ( !strcmp( game, "heretic2" ) ) + strncpy(basedirname, HERETIC2_BASEDIRNAME, 256); + else + strncpy(basedirname, BASEDIRNAME, 256); + + 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_FPrintf( SYS_VRB, "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_FPrintf( SYS_VRB, "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 = true; + 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); +} + +int Q_strcasecmp (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 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); +} +/* +// all output ends up through here +void FPrintf (int flag, char *buf) +{ + printf(buf); + +} + +void Sys_FPrintf (int flag, const char *format, ...) +{ + char out_buffer[4096]; + va_list argptr; + + if ((flag == SYS_VRB) && (verbose == false)) + 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 ); + + exit (1); +} +*/ + + +/* +============================================================================ + + 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/misc/mediasource/netradiant-src/tools/quake2/common/cmdlib.h b/misc/mediasource/netradiant-src/tools/quake2/common/cmdlib.h new file mode 100644 index 00000000..5b08b81a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/cmdlib.h @@ -0,0 +1,174 @@ +/* +Copyright (C) 1999-2006 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 +#include +#include +#include +#include +#include +#include + +#ifdef WIN32 + #ifdef NDEBUG // Don't show in a Release build + #pragma warning(disable : 4305) // truncate from double to float + #pragma warning(disable : 4244) // conversion from double to float + #pragma warning(disable : 4018) // signed/unsigned mismatch + #endif +#endif + +#ifdef WIN32 + #pragma intrinsic( memset, memcpy ) +#endif + +#ifndef __BYTEBOOL__ + #define __BYTEBOOL__ + typedef enum {false, true} qboolean; + typedef unsigned char byte; +#endif + +#ifdef PATH_MAX +#define MAX_OS_PATH PATH_MAX +#else +#define MAX_OS_PATH 1024 +#endif +#define MEM_BLOCKSIZE 4096 + +/* +extern qboolean verbose; +#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 +*/ + +// 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_strcasecmp( const char *s1, const char *s2 ); +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 ); + +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); + +//void Sys_Printf (const char *text, ...); +//void Sys_FPrintf (int flag, const char *text, ...); +//void Error( const char *error, ... ); + +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 +{ + byte *data; + int count; +} cblock_t; + +extern char game[64]; + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/inout.c b/misc/mediasource/netradiant-src/tools/quake2/common/inout.c new file mode 100644 index 00000000..3cf66e7f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/inout.c @@ -0,0 +1,367 @@ +/* +Copyright (C) 1999-2006 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" + +#ifdef WIN32 +HWND hwndOut = NULL; +qboolean lookedForServer = false; +UINT wm_BroadcastCommand = -1; +#endif + +socket_t *brdcst_socket; +netmessage_t msg; + +qboolean verbose = false; + +// 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 = false; + 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 = true; + } + node = xmlNewNode (NULL, "message"); + xmlNodeSetContent (node, buf); + 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 == false)) + 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/misc/mediasource/netradiant-src/tools/quake2/common/inout.h b/misc/mediasource/netradiant-src/tools/quake2/common/inout.h new file mode 100644 index 00000000..75ef55ee --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/inout.h @@ -0,0 +1,63 @@ +/* +Copyright (C) 1999-2006 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" +#include "mathlib.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, ...); +void Error( const char *error, ...); + +#ifdef _DEBUG +#define DBG_XML 1 +#endif + +#ifdef DBG_XML +void DumpXML(); +#endif + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/l3dslib.c b/misc/mediasource/netradiant-src/tools/quake2/common/l3dslib.c new file mode 100644 index 00000000..f120bec2 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/l3dslib.c @@ -0,0 +1,300 @@ +/* +Copyright (C) 1999-2006 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 "inout.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 + +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 MAXVERTS) + Error ("Error: Too many vertices"); + + for (i=0 ; i MAXTRIANGLES) + Error ("Error: Too many triangles"); + + for (i=0 ; i 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 = 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/misc/mediasource/netradiant-src/tools/quake2/common/l3dslib.h b/misc/mediasource/netradiant-src/tools/quake2/common/l3dslib.h new file mode 100644 index 00000000..1d362ce9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/l3dslib.h @@ -0,0 +1,25 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake2/common/lbmlib.c b/misc/mediasource/netradiant-src/tools/quake2/common/lbmlib.c new file mode 100644 index 00000000..edc2c3e4 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/lbmlib.c @@ -0,0 +1,837 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// lbmlib.c + +#include "cmdlib.h" +#include "inout.h" +#include "lbmlib.h" + + + +/* +============================================================================ + + 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 (countbpwidth) + Error ("Decompression exceeded width!\n"); + + + return source; +} + + +/* +================= +LoadLBM +================= +*/ +void LoadLBM (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 = malloc (768); + memset (cmapbuffer, 0, 768); + memcpy (cmapbuffer, LBM_P, chunklength); + break; + + case BODYID: + body_p = LBM_P; + + pic_p = picbuffer = malloc (bmhd.w*bmhd.h); + if (formtype == PBMID) + { + // + // unpack PBM + // + for (y=0 ; ydata; + + 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 = 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 = malloc ( (pcx->ymax+1) * (pcx->xmax+1) ); + if (!out) + Error ("Skin_Cache: couldn't allocate"); + + *pic = out; + + pix = out; + + for (y=0 ; y<=pcx->ymax ; y++, pix += pcx->xmax+1) + { + for (x=0 ; x<=pcx->xmax ; ) + { + dataByte = *raw++; + + if((dataByte & 0xC0) == 0xC0) + { + runLength = dataByte & 0x3F; + dataByte = *raw++; + } + else + runLength = 1; + + while(runLength-- > 0) + pix[x++] = dataByte; + } + + } + + if ( raw - (byte *)pcx > len) + Error ("PCX file %s was malformed", filename); + + free (pcx); +} + +/* +============== +WritePCXfile +============== +*/ +void WritePCXfile (char *filename, byte *data, + int width, int height, byte *palette) +{ + int i, j, length; + pcx_t *pcx; + byte *pack; + + pcx = 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(2); // not a grey scale + + // pack the image + pack = &pcx->data; + + for (i=0 ; i=0; row--) { + pixbuf = targa_rgba + row*columns*4; + for(column=0; column=0; row--) { + pixbuf = targa_rgba + row*columns*4; + for(column=0; column0) + row--; + else + goto breakOut; + pixbuf = targa_rgba + row*columns*4; + } + } + } + else { // non run-length packet + for(j=0;j0) + 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; + } + } + } + + fclose(fin); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/lbmlib.h b/misc/mediasource/netradiant-src/tools/quake2/common/lbmlib.h new file mode 100644 index 00000000..40e6dce6 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/lbmlib.h @@ -0,0 +1,38 @@ +/* +Copyright (C) 1999-2006 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 (char *filename, byte **picture, byte **palette); +void WriteLBMfile (char *filename, byte *data, int width, int height + , byte *palette); +void LoadPCX (char *filename, byte **picture, byte **palette, int *width, int *height); +void WritePCXfile (char *filename, byte *data, int width, int height + , byte *palette); + +// loads / saves either lbm or pcx, depending on extension +void Load256Image (char *name, byte **pixels, byte **palette, + int *width, int *height); +void Save256Image (char *name, byte *pixels, byte *palette, + int width, int height); + + +void LoadTGA (char *filename, byte **pixels, int *width, int *height); diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/mathlib.c b/misc/mediasource/netradiant-src/tools/quake2/common/mathlib.c new file mode 100644 index 00000000..b912b450 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/mathlib.c @@ -0,0 +1,172 @@ +/* +Copyright (C) 1999-2006 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 "cmdlib.h" +#include "mathlib.h" + +vec3_t vec3_origin = {0,0,0}; + + +double VectorLength(vec3_t v) +{ + int i; + double length; + + length = 0; + for (i=0 ; i< 3 ; i++) + length += v[i]*v[i]; + length = sqrt (length); // FIXME + + return length; +} + +qboolean VectorCompare (vec3_t v1, vec3_t v2) +{ + int i; + + for (i=0 ; i<3 ; i++) + if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON) + return false; + + return true; +} + +vec_t Q_rint (vec_t in) +{ + return floor (in + 0.5); +} + +void VectorMA (vec3_t va, double scale, 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]; +} + +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; +} + +vec_t VectorNormalize (vec3_t in, vec3_t out) +{ + vec_t length, ilength; + + length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]); + if (length == 0) + { + VectorClear (out); + return 0; + } + + ilength = 1.0/length; + out[0] = in[0]*ilength; + out[1] = in[1]*ilength; + out[2] = in[2]*ilength; + + return length; +} + +vec_t ColorNormalize (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) + return 0; + + scale = 1.0 / 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 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; + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/mathlib.h b/misc/mediasource/netradiant-src/tools/quake2/common/mathlib.h new file mode 100644 index 00000000..eb10f0fc --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/mathlib.h @@ -0,0 +1,75 @@ +/* +Copyright (C) 1999-2006 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 DOUBLEVEC_T +typedef double vec_t; +#else +typedef float vec_t; +#endif +typedef vec_t vec3_t[3]; + +#define SIDE_FRONT 0 +#define SIDE_ON 2 +#define SIDE_BACK 1 +#define SIDE_CROSS -2 + +#define Q_PI 3.14159265358979323846 + +extern vec3_t vec3_origin; + +#define EQUAL_EPSILON 0.001 + +qboolean VectorCompare (vec3_t v1, vec3_t v2); + +#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 VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];} +#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];} +#define VectorClear(x) {x[0] = x[1] = x[2] = 0;} +#define VectorNegate(x) {x[0]=-x[0];x[1]=-x[1];x[2]=-x[2];} + +vec_t Q_rint (vec_t in); +vec_t _DotProduct (vec3_t v1, vec3_t v2); +void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out); +void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out); +void _VectorCopy (vec3_t in, vec3_t out); +void _VectorScale (vec3_t v, vec_t scale, vec3_t out); + +double VectorLength(vec3_t v); + +void VectorMA (vec3_t va, double scale, vec3_t vb, vec3_t vc); + +void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross); +vec_t VectorNormalize (vec3_t in, vec3_t out); +vec_t ColorNormalize (vec3_t in, vec3_t out); +void VectorInverse (vec3_t v); + +void ClearBounds (vec3_t mins, vec3_t maxs); +void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs); + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/md4.c b/misc/mediasource/netradiant-src/tools/quake2/common/md4.c new file mode 100644 index 00000000..7c2c9be4 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/md4.c @@ -0,0 +1,227 @@ +/* + mdfour.c + + An implementation of MD4 designed for use in the samba SMB + authentication protocol + + Copyright (C) 1997-1998 Andrew Tridgell + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA + + $Id: mdfour.c 7689 2007-11-12 14:28:40Z divverent $ +*/ + +#include /* XoXus: needed for memset call */ +#include "md4.h" + +/* NOTE: This code makes no attempt to be fast! + + It assumes that a int is at least 32 bits long +*/ + +static struct mdfour *m; + +#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)) +#ifdef LARGE_INT32 +#define lshift(x,s) ((((x)<<(s))&0xFFFFFFFF) | (((x)>>(32-(s)))&0xFFFFFFFF)) +#else +#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) +#endif + +#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) +#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) +#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) + +/* this applies md4 to 64 byte chunks */ +static void mdfour64(uint32 *M) +{ + int j; + uint32 AA, BB, CC, DD; + uint32 X[16]; + uint32 A,B,C,D; + + for (j=0;j<16;j++) + X[j] = M[j]; + + A = m->A; B = m->B; C = m->C; D = m->D; + AA = A; BB = B; CC = C; DD = D; + + ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); + ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); + ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); + ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); + ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); + ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); + ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); + ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); + + ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); + ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); + ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); + ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); + ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); + ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); + ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); + ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); + + ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); + ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); + ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); + ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); + ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); + ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); + ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); + ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); + + A += AA; B += BB; C += CC; D += DD; + +#ifdef LARGE_INT32 + A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; + C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; +#endif + + for (j=0;j<16;j++) + X[j] = 0; + + m->A = A; m->B = B; m->C = C; m->D = D; +} + +static void copy64(uint32 *M, unsigned char *in) +{ + int i; + + for (i=0;i<16;i++) + M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | + (in[i*4+1]<<8) | (in[i*4+0]<<0); +} + +static void copy4(unsigned char *out,uint32 x) +{ + out[0] = x&0xFF; + out[1] = (x>>8)&0xFF; + out[2] = (x>>16)&0xFF; + out[3] = (x>>24)&0xFF; +} + +void mdfour_begin(struct mdfour *md) +{ + md->A = 0x67452301; + md->B = 0xefcdab89; + md->C = 0x98badcfe; + md->D = 0x10325476; + md->totalN = 0; +} + + +static void mdfour_tail(unsigned char *in, int n) +{ + unsigned char buf[128]; + uint32 M[16]; + uint32 b; + + m->totalN += n; + + b = m->totalN * 8; + + memset(buf, 0, 128); + if (n) memcpy(buf, in, n); + buf[n] = 0x80; + + if (n <= 55) { + copy4(buf+56, b); + copy64(M, buf); + mdfour64(M); + } else { + copy4(buf+120, b); + copy64(M, buf); + mdfour64(M); + copy64(M, buf+64); + mdfour64(M); + } +} + +void mdfour_update(struct mdfour *md, unsigned char *in, int n) +{ + uint32 M[16]; + +// start of edit by Forest 'LordHavoc' Hale +// commented out to prevent crashing when length is 0 +// if (n == 0) mdfour_tail(in, n); +// end of edit by Forest 'LordHavoc' Hale + + m = md; + + while (n >= 64) { + copy64(M, in); + mdfour64(M); + in += 64; + n -= 64; + m->totalN += 64; + } + + mdfour_tail(in, n); +} + + +void mdfour_result(struct mdfour *md, unsigned char *out) +{ + m = md; + + copy4(out, m->A); + copy4(out+4, m->B); + copy4(out+8, m->C); + copy4(out+12, m->D); +} + + +void mdfour(unsigned char *out, unsigned char *in, int n) +{ + struct mdfour md; + mdfour_begin(&md); + mdfour_update(&md, in, n); + mdfour_result(&md, out); +} + +/////////////////////////////////////////////////////////////// +// MD4-based checksum utility functions +// +// Copyright (C) 2000 Jeff Teunissen +// +// Author: Jeff Teunissen +// Date: 01 Jan 2000 + +unsigned Com_BlockChecksum (void *buffer, int length) +{ + int digest[4]; + unsigned val; + + mdfour ( (unsigned char *) digest, (unsigned char *) buffer, length ); + + val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; + + return val; +} + +void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) +{ + mdfour ( outbuf, (unsigned char *) buffer, len ); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/md4.h b/misc/mediasource/netradiant-src/tools/quake2/common/md4.h new file mode 100644 index 00000000..4373c2c9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/md4.h @@ -0,0 +1,57 @@ +/* + mdfour.h + + an implementation of MD4 designed for use in the SMB authentication + protocol + + Copyright (C) Andrew Tridgell 1997-1998 + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA +*/ + +#ifndef _MDFOUR_H +#define _MDFOUR_H + +#ifndef int32 +#define int32 int +#endif + +#if SIZEOF_INT > 4 +#define LARGE_INT32 +#endif + +#ifndef uint32 +#define uint32 unsigned int32 +#endif + +struct mdfour { + uint32 A, B, C, D; + uint32 totalN; +}; + +void mdfour_begin(struct mdfour *md); // old: MD4Init +void mdfour_update(struct mdfour *md, unsigned char *in, int n); //old: MD4Update +void mdfour_result(struct mdfour *md, unsigned char *out); // old: MD4Final +void mdfour(unsigned char *out, unsigned char *in, int n); + +unsigned Com_BlockChecksum (void *buffer, int length); +void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf); + +#endif // _MDFOUR_H + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/path_init.c b/misc/mediasource/netradiant-src/tools/quake2/common/path_init.c new file mode 100644 index 00000000..d309e95c --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/path_init.c @@ -0,0 +1,404 @@ +/* ------------------------------------------------------------------------------- + +Copyright (C) 1999-2006 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 + +Nurail: Swiped from Q3Map2 + +*/ + + + +/* marker */ +#define PATH_INIT_C + +#if defined( __linux__ ) || defined( __APPLE__ ) + #define Q_UNIX +#endif + +#ifdef Q_UNIX + #include + #include + #include +#endif + + +/* dependencies */ +#include "cmdlib.h" +#include "inout.h" + + + +/* path support */ +#define MAX_BASE_PATHS 10 +#define MAX_GAME_PATHS 10 + +char *homePath; +char installPath[ MAX_OS_PATH ]; + +int numBasePaths; +char *basePaths[ MAX_BASE_PATHS ]; +int numGamePaths; +char *gamePaths[ MAX_GAME_PATHS ]; + +/* +some of this code is based off the original q3map port from loki +and finds various paths. moved here from bsp.c for clarity. +*/ + +/* +PathLokiGetHomeDir() +gets the user's home dir (for ~/.q3a) +*/ + +char *LokiGetHomeDir( void ) +{ + #ifndef Q_UNIX + return NULL; + #else + char *home; + uid_t id; + struct passwd *pwd; + + + /* get the home environment variable */ + home = getenv( "HOME" ); + if( home == NULL ) + { + /* do some more digging */ + id = getuid(); + setpwent(); + while( (pwd = getpwent()) != NULL ) + { + if( pwd->pw_uid == id ) + { + home = pwd->pw_dir; + break; + } + } + endpwent(); + } + + /* return it */ + return home; + #endif +} + + + +/* +PathLokiInitPaths() +initializes some paths on linux/os x +*/ + +void LokiInitPaths( char *argv0 ) +{ + #ifndef Q_UNIX + /* this is kinda crap, but hey */ + strcpy( installPath, "../" ); + #else + char temp[ MAX_OS_PATH ]; + char *home; + char *path; + char *last; + qboolean found; + + + /* get home dir */ + home = LokiGetHomeDir(); + if( home == NULL ) + home = "."; + + /* do some path divining */ + strcpy( temp, argv0 ); + if( strrchr( temp, '/' ) ) + argv0 = strrchr( argv0, '/' ) + 1; + else + { + /* get path environment variable */ + path = getenv( "PATH" ); + + /* minor setup */ + last[ 0 ] = path[ 0 ]; + last[ 1 ] = '\0'; + found = false; + + /* go through each : segment of path */ + while( last[ 0 ] != '\0' && found == false ) + { + /* null out temp */ + temp[ 0 ] = '\0'; + + /* find next chunk */ + last = strchr( path, ':' ); + if( last == NULL ) + last = path + strlen( path ); + + /* found home dir candidate */ + if( *path == '~' ) + { + strcpy( temp, home ); + path++; + } + + /* concatenate */ + if( last > (path + 1) ) + { + strncat( temp, path, (last - path) ); + strcat( temp, "/" ); + } + strcat( temp, "./" ); + strcat( temp, argv0 ); + + /* verify the path */ + if( access( temp, X_OK ) == 0 ) + found++; + path = last + 1; + } + } + + /* flake */ + if( realpath( temp, installPath ) ) + { + /* q3map is in "tools/" */ + *(strrchr( installPath, '/' )) = '\0'; + *(strrchr( installPath, '/' ) + 1) = '\0'; + } + + /* set home path */ + homePath = home; + #endif +} + + + +/* +CleanPath() - ydnar +cleans a dos path \ -> / +*/ + +void CleanPath( char *path ) +{ + while( *path ) + { + if( *path == '\\' ) + *path = '/'; + path++; + } +} + +/* +AddBasePath() - ydnar +adds a base path to the list +*/ + +void AddBasePath( char *path ) +{ + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' || numBasePaths >= MAX_BASE_PATHS ) + return; + + /* add it to the list */ + basePaths[ numBasePaths ] = safe_malloc( strlen( path ) + 1 ); + strcpy( basePaths[ numBasePaths ], path ); + CleanPath( basePaths[ numBasePaths ] ); + numBasePaths++; +} + + + +/* +AddHomeBasePath() - ydnar +adds a base path to the beginning of the list, prefixed by ~/ +*/ + +void AddHomeBasePath( char *path ) +{ + #ifdef Q_UNIX + int i; + char temp[ MAX_OS_PATH ]; + + + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' ) + return; + + /* make a hole */ + for( i = 0; i < (MAX_BASE_PATHS - 1); i++ ) + basePaths[ i + 1 ] = basePaths[ i ]; + + /* concatenate home dir and path */ + sprintf( temp, "%s/%s", homePath, path ); + + /* add it to the list */ + basePaths[ 0 ] = safe_malloc( strlen( temp ) + 1 ); + strcpy( basePaths[ 0 ], temp ); + CleanPath( basePaths[ 0 ] ); + numBasePaths++; + #endif +} + + + +/* +AddGamePath() - ydnar +adds a game path to the list +*/ + +void AddGamePath( char *path ) +{ + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' || numGamePaths >= MAX_GAME_PATHS ) + return; + + /* add it to the list */ + gamePaths[ numGamePaths ] = safe_malloc( strlen( path ) + 1 ); + strcpy( gamePaths[ numGamePaths ], path ); + CleanPath( gamePaths[ numGamePaths ] ); + numGamePaths++; +} + + + + +/* +InitPaths() - ydnar +cleaned up some of the path initialization code from bsp.c +will remove any arguments it uses +*/ + +void InitPaths( int *argc, char **argv ) +{ + int i, j, k, len, len2; + char temp[ MAX_OS_PATH ]; + char gamePath[MAX_OS_PATH], homeBasePath[MAX_OS_PATH], game_magic[10]; + + strcpy(gamePath, "baseq2"); + strcpy(game_magic, "quake"); + strcpy(homeBasePath, ".quake2"); + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- InitPaths ---\n" ); + + /* get the install path for backup */ + LokiInitPaths( argv[ 0 ] ); + + /* set game to default (q3a) */ + numBasePaths = 0; + numGamePaths = 0; + + /* parse through the arguments and extract those relevant to paths */ + for( i = 0; i < *argc; i++ ) + { + /* check for null */ + if( argv[ i ] == NULL ) + continue; + + /* -fs_basepath */ + if( strcmp( argv[ i ], "-fs_basepath" ) == 0 ) + { + if( ++i >= *argc ) + Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); + argv[ i - 1 ] = NULL; + AddBasePath( argv[ i ] ); + argv[ i ] = NULL; + } + + } + + /* remove processed arguments */ + for( i = 0, j = 0, k = 0; i < *argc && j < *argc; i++, j++ ) + { + for( j; j < *argc && argv[ j ] == NULL; j++ ); + argv[ i ] = argv[ j ]; + if( argv[ i ] != NULL ) + k++; + } + *argc = k; + + /* add standard game path */ + AddGamePath( gamePath ); + + /* if there is no base path set, figure it out */ + if( numBasePaths == 0 ) + { + /* this is another crappy replacement for SetQdirFromPath() */ + len2 = strlen( game_magic ); + for( i = 0; i < *argc && numBasePaths == 0; i++ ) + { + /* extract the arg */ + strcpy( temp, argv[ i ] ); + CleanPath( temp ); + len = strlen( temp ); + Sys_FPrintf( SYS_VRB, "Searching for \"%s\" in \"%s\" (%d)...\n", game_magic, temp, i ); + + /* this is slow, but only done once */ + for( j = 0; j < (len - len2); j++ ) + { + /* check for the game's magic word */ + if( Q_strncasecmp( &temp[ j ], game_magic, len2 ) == 0 ) + { + /* now find the next slash and nuke everything after it */ + while( temp[ ++j ] != '/' && temp[ j ] != '\0' ); + temp[ j ] = '\0'; + + /* add this as a base path */ + AddBasePath( temp ); + break; + } + } + } + + /* add install path */ + if( numBasePaths == 0 ) + AddBasePath( installPath ); + + /* check again */ + if( numBasePaths == 0 ) + Error( "Failed to find a valid base path." ); + } + + /* this only affects unix */ + AddHomeBasePath( homeBasePath ); + + /* initialize vfs paths */ + if( numBasePaths > MAX_BASE_PATHS ) + numBasePaths = MAX_BASE_PATHS; + if( numGamePaths > MAX_GAME_PATHS ) + numGamePaths = MAX_GAME_PATHS; + + /* walk the list of game paths */ + //for( j = 0; j < numGamePaths; j++ ) + //{ + /* walk the list of base paths */ + // for( i = 0; i < numBasePaths; i++ ) + // { + /* create a full path and initialize it */ + // sprintf( temp, "%s/%s/", basePaths[ i ], gamePaths[ j ] ); + // vfsInitDirectory( temp ); + // } + //} + + /* done */ + Sys_Printf( "\n" ); +} + + + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/polylib.c b/misc/mediasource/netradiant-src/tools/quake2/common/polylib.c new file mode 100644 index 00000000..e177d728 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/polylib.c @@ -0,0 +1,642 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#include "mathlib.h" +#include "polylib.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 8192 + +void pw(winding_t *w) +{ + int i; + for (i=0 ; inumpoints ; i++) + 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 (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 = 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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, 8192, vup); + VectorScale (vright, 8192, 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; i++) + { + p1 = w->p[i]; + + for (j=0 ; j<3 ; j++) + if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE) + Error ("CheckFace: BUGUS_RANGE: %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 ; jnumpoints ; 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 = false; + back = false; + for (i=0 ; inumpoints ; i++) + { + d = DotProduct (w->p[i], normal) - dist; + if (d < -ON_EPSILON) + { + if (front) + return SIDE_CROSS; + back = true; + continue; + } + if (d > ON_EPSILON) + { + if (back) + return SIDE_CROSS; + front = true; + continue; + } + } + + if (back) + return SIDE_BACK; + if (front) + return SIDE_FRONT; + return SIDE_ON; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/polylib.h b/misc/mediasource/netradiant-src/tools/quake2/common/polylib.h new file mode 100644 index 00000000..d89062d5 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/polylib.h @@ -0,0 +1,54 @@ +/* +Copyright (C) 1999-2006 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 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/misc/mediasource/netradiant-src/tools/quake2/common/q2_threads.h b/misc/mediasource/netradiant-src/tools/quake2/common/q2_threads.h new file mode 100644 index 00000000..b8fc2f53 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/q2_threads.h @@ -0,0 +1,34 @@ +/* +Copyright (C) 1999-2006 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 _THREADS_H + +#define _THREADS_H + +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); + +#endif // _THREADS_H diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/qfiles.h b/misc/mediasource/netradiant-src/tools/quake2/common/qfiles.h new file mode 100644 index 00000000..7c9cc864 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/qfiles.h @@ -0,0 +1,563 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// qfiles.h: quake file formats +// This file must be identical in the quake and utils directories +// + +/* +======================================================================== + +The .pak files are just a linear collapse of a directory tree + +======================================================================== +*/ + +#ifdef WIN32 + #ifdef NDEBUG // Don't show in a Release build + #pragma warning(disable : 4305) // truncate from double to float + #pragma warning(disable : 4244) // conversion from double to float + #pragma warning(disable : 4018) // signed/unsigned mismatch + #endif +#endif + +#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P') + +typedef struct +{ + char name[56]; + int filepos, filelen; +} dpackfile_t; + +typedef struct +{ + int ident; // == IDPAKHEADER + int dirofs; + int dirlen; +} dpackheader_t; + +#define MAX_FILES_IN_PACK 4096 + + +/* +======================================================================== + +PCX files are used for as many images as possible + +======================================================================== +*/ + +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; + + +/* +======================================================================== + +.MD2 triangle model file format + +======================================================================== +*/ + +#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I') +#define ALIAS_VERSION 8 + +#define MAX_TRIANGLES 4096 +#define MAX_VERTS 2048 +#define MAX_FRAMES 512 +#define MAX_MD2SKINS 32 +#define MAX_SKINNAME 64 + +typedef struct +{ + short s; + short t; +} dstvert_t; + +typedef struct +{ + short index_xyz[3]; + short index_st[3]; +} dtriangle_t; + +typedef struct +{ + byte v[3]; // scaled byte to fit in frame mins/maxs + byte lightnormalindex; +} dtrivertx_t; + +#define DTRIVERTX_V0 0 +#define DTRIVERTX_V1 1 +#define DTRIVERTX_V2 2 +#define DTRIVERTX_LNI 3 +#define DTRIVERTX_SIZE 4 + +typedef struct +{ + float scale[3]; // multiply byte verts by this + float translate[3]; // then add this + char name[16]; // frame name from grabbing + dtrivertx_t verts[1]; // variable sized +} daliasframe_t; + + +// the glcmd format: +// a positive integer starts a tristrip command, followed by that many +// vertex structures. +// a negative integer starts a trifan command, followed by -x vertexes +// a zero indicates the end of the command list. +// a vertex consists of a floating point s, a floating point t, +// and an integer vertex index. + + +typedef struct +{ + int ident; + int version; + + int skinwidth; + int skinheight; + int framesize; // byte size of each frame + + int num_skins; + int num_xyz; + int num_st; // greater than num_xyz for seams + int num_tris; + int num_glcmds; // dwords in strip/fan command list + int num_frames; + + int ofs_skins; // each skin is a MAX_SKINNAME string + int ofs_st; // byte offset from start for stverts + int ofs_tris; // offset for dtriangles + int ofs_frames; // offset for first frame + int ofs_glcmds; + int ofs_end; // end of file + +} dmdl_t; + +/* +======================================================================== + +.SP2 sprite file format + +======================================================================== +*/ + +#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I') + // little-endian "IDS2" +#define SPRITE_VERSION 2 + +typedef struct +{ + int width, height; + int origin_x, origin_y; // raster coordinates inside pic + char name[MAX_SKINNAME]; // name of pcx file +} dsprframe_t; + +typedef struct { + int ident; + int version; + int numframes; + dsprframe_t frames[1]; // variable sized +} dsprite_t; + +/* +============================================================================== + + .WAL texture file format + +============================================================================== +*/ + + +#define MIPLEVELS 4 +typedef struct miptex_s +{ + char name[32]; + unsigned width, height; + unsigned offsets[MIPLEVELS]; // four mip maps stored + char animname[32]; // next frame in animation chain + int flags; + int contents; + int value; +} miptex_t; + + /* + ============================================================================== + +- .WAL texture file format ++ .M8 texture file format + + ============================================================================== + */ + +typedef struct palette_s +{ + union + { + struct + { + byte r,g,b; + }; + }; +} palette_t; + +#define MIP_VERSION 2 +#define PAL_SIZE 256 +#define H2_MIPLEVELS 16 + + typedef struct miptex_m8_s + { + int version; + char name[32]; + unsigned width[H2_MIPLEVELS], height[H2_MIPLEVELS]; + unsigned offsets[H2_MIPLEVELS]; // four mip maps stored + char animname[32]; // next frame in animation chain + palette_t palette[PAL_SIZE]; + int flags; + int contents; + int value; + } miptex_m8_t; + + +#define MIP32_VERSION 4 + +#define MIP32_NOMIP_FLAG2 0x00000001 +#define MIP32_DETAILER_FLAG2 0x00000002 + +typedef struct miptex_m32_s +{ + int version; + char name[128]; + char altname[128]; // texture substitution + char animname[128]; // next frame in animation chain + char damagename[128]; // image that should be shown when damaged + unsigned width[H2_MIPLEVELS], height[H2_MIPLEVELS]; + unsigned offsets[H2_MIPLEVELS]; + int flags; + int contents; + int value; + float scale_x, scale_y; + int mip_scale; + + // detail texturing info + char dt_name[128]; // detailed texture name + float dt_scale_x, dt_scale_y; + float dt_u, dt_v; + float dt_alpha; + int dt_src_blend_mode, dt_dst_blend_mode; + + int flags2; + int unused[19]; // future expansion to maintain compatibility with h2 +} miptex_m32_t; + + + + +/* +============================================================================== + + .BSP file format + +============================================================================== +*/ + +#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') + // little-endian "IBSP" + +#define BSPVERSION 38 + + +// upper design bounds +// leaffaces, leafbrushes, planes, and verts are still bounded by +// 16 bit short limits +#define MAX_MAP_MODELS 1024 +#define MAX_MAP_BRUSHES 8192 +#define MAX_MAP_ENTITIES 2048 +#define MAX_MAP_ENTSTRING 0x40000 +#define MAX_MAP_TEXINFO 8192 + +#define MAX_MAP_AREAS 256 +#define MAX_MAP_AREAPORTALS 1024 +#define MAX_MAP_PLANES 65536 +#define MAX_MAP_NODES 65536 +#define MAX_MAP_BRUSHSIDES 65536 +#define MAX_MAP_LEAFS 65536 +#define MAX_MAP_VERTS 65536 +#define MAX_MAP_FACES 65536 +#define MAX_MAP_LEAFFACES 65536 +#define MAX_MAP_LEAFBRUSHES 65536 +#define MAX_MAP_PORTALS 65536 +#define MAX_MAP_EDGES 128000 +#define MAX_MAP_SURFEDGES 256000 +#define MAX_MAP_LIGHTING 0x200000 +#define MAX_MAP_VISIBILITY 0x100000 + +// key / value pair sizes + +#define MAX_KEY 32 +#define MAX_VALUE 1024 + +//============================================================================= + +typedef struct +{ + int fileofs, filelen; +} lump_t; + +#define LUMP_ENTITIES 0 +#define LUMP_PLANES 1 +#define LUMP_VERTEXES 2 +#define LUMP_VISIBILITY 3 +#define LUMP_NODES 4 +#define LUMP_TEXINFO 5 +#define LUMP_FACES 6 +#define LUMP_LIGHTING 7 +#define LUMP_LEAFS 8 +#define LUMP_LEAFFACES 9 +#define LUMP_LEAFBRUSHES 10 +#define LUMP_EDGES 11 +#define LUMP_SURFEDGES 12 +#define LUMP_MODELS 13 +#define LUMP_BRUSHES 14 +#define LUMP_BRUSHSIDES 15 +#define LUMP_POP 16 +#define LUMP_AREAS 17 +#define LUMP_AREAPORTALS 18 +#define HEADER_LUMPS 19 + +typedef struct +{ + int ident; + int version; + lump_t lumps[HEADER_LUMPS]; +} dheader_t; + +typedef struct +{ + float mins[3], maxs[3]; + float origin[3]; // for sounds or lights + int headnode; + int firstface, numfaces; // submodels just draw faces + // without walking the bsp tree +} dmodel_t; + + +typedef struct +{ + float point[3]; +} dvertex_t; + + +// 0-2 are axial planes +#define PLANE_X 0 +#define PLANE_Y 1 +#define PLANE_Z 2 + +// 3-5 are non-axial planes snapped to the nearest +#define PLANE_ANYX 3 +#define PLANE_ANYY 4 +#define PLANE_ANYZ 5 + +// planes (x&~1) and (x&~1)+1 are allways opposites + +typedef struct +{ + float normal[3]; + float dist; + int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate +} dplane_t; + + +// contents flags are seperate bits +// a given brush can contribute multiple content bits +// multiple brushes can be in a single leaf + +// these definitions also need to be in q_shared.h! + +// lower bits are stronger, and will eat weaker brushes completely +#define CONTENTS_SOLID 1 // an eye is never valid in a solid +#define CONTENTS_WINDOW 2 // translucent, but not watery +#define CONTENTS_AUX 4 +#define CONTENTS_LAVA 8 +#define CONTENTS_SLIME 16 +#define CONTENTS_WATER 32 +#define CONTENTS_MIST 64 +#define LAST_VISIBLE_CONTENTS 64 + +// remaining contents are non-visible, and don't eat brushes + +#define CONTENTS_AREAPORTAL 0x8000 + +#define CONTENTS_PLAYERCLIP 0x10000 +#define CONTENTS_MONSTERCLIP 0x20000 + +// currents can be added to any other contents, and may be mixed +#define CONTENTS_CURRENT_0 0x40000 +#define CONTENTS_CURRENT_90 0x80000 +#define CONTENTS_CURRENT_180 0x100000 +#define CONTENTS_CURRENT_270 0x200000 +#define CONTENTS_CURRENT_UP 0x400000 +#define CONTENTS_CURRENT_DOWN 0x800000 + +#define CONTENTS_ORIGIN 0x1000000 // removed before bsping an entity + +#define CONTENTS_MONSTER 0x2000000 // should never be on a brush, only in game +#define CONTENTS_DEADMONSTER 0x4000000 +#define CONTENTS_DETAIL 0x8000000 // brushes to be added after vis leafs +#define CONTENTS_TRANSLUCENT 0x10000000 // auto set if any surface has trans +#define CONTENTS_LADDER 0x20000000 + + + +#define SURF_LIGHT 0x1 // value will hold the light strength + +#define SURF_SLICK 0x2 // effects game physics + +#define SURF_SKY 0x4 // don't draw, but add to skybox +#define SURF_WARP 0x8 // turbulent water warp +#define SURF_TRANS33 0x10 +#define SURF_TRANS66 0x20 +#define SURF_FLOWING 0x40 // scroll towards angle +#define SURF_NODRAW 0x80 // don't bother referencing the texture + +#define SURF_HINT 0x100 // make a primary bsp splitter +#define SURF_SKIP 0x200 // completely ignore, allowing non-closed brushes + + + +typedef struct +{ + int planenum; + int children[2]; // negative numbers are -(leafs+1), not nodes + short mins[3]; // for frustom culling + short maxs[3]; + unsigned short firstface; + unsigned short numfaces; // counting both sides +} dnode_t; + + +typedef struct texinfo_s +{ + float vecs[2][4]; // [s/t][xyz offset] + int flags; // miptex flags + overrides + int value; // light emission, etc + char texture[32]; // texture name (textures/*.wal) + int nexttexinfo; // for animations, -1 = end of chain +} texinfo_t; + + +// note that edge 0 is never used, because negative edge nums are used for +// counterclockwise use of the edge in a face +typedef struct +{ + unsigned short v[2]; // vertex numbers +} dedge_t; + +#define MAXLIGHTMAPS 4 +typedef struct +{ + unsigned short planenum; + short side; + + int firstedge; // we must support > 64k edges + short numedges; + short texinfo; + +// lighting info + byte styles[MAXLIGHTMAPS]; + int lightofs; // start of [numstyles*surfsize] samples +} dface_t; + +typedef struct +{ + int contents; // OR of all brushes (not needed?) + + short cluster; + short area; + + short mins[3]; // for frustum culling + short maxs[3]; + + unsigned short firstleafface; + unsigned short numleaffaces; + + unsigned short firstleafbrush; + unsigned short numleafbrushes; +} dleaf_t; + +typedef struct +{ + unsigned short planenum; // facing out of the leaf + short texinfo; +} dbrushside_t; + +typedef struct +{ + int firstside; + int numsides; + int contents; +} dbrush_t; + +#define ANGLE_UP -1 +#define ANGLE_DOWN -2 + + +// the visibility lump consists of a header with a count, then +// byte offsets for the PVS and PHS of each cluster, then the raw +// compressed bit vectors +#define DVIS_PVS 0 +#define DVIS_PHS 1 +typedef struct +{ + int numclusters; + int bitofs[8][2]; // bitofs[numclusters][2] +} dvis_t; + +// each area has a list of portals that lead into other areas +// when portals are closed, other areas may not be visible or +// hearable even if the vis info says that it should be +typedef struct +{ + int portalnum; + int otherarea; +} dareaportal_t; + +typedef struct +{ + int numareaportals; + int firstareaportal; +} darea_t; diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/scriplib.c b/misc/mediasource/netradiant-src/tools/quake2/common/scriplib.c new file mode 100644 index 00000000..9cab6391 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/scriplib.c @@ -0,0 +1,296 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#include "scriplib.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 true if UnGetToken was just called + +/* +============== +AddScriptToStack +============== +*/ +void AddScriptToStack (char *filename) +{ + int size; + + script++; + if (script == &scriptstack[MAX_INCLUDES]) + Error ("script file exceeded MAX_INCLUDES"); + strcpy (script->filename, ExpandPath (filename) ); + + size = LoadFile (script->filename, (void **)&script->buffer); + + printf ("entering %s\n", script->filename); + + script->line = 1; + + script->script_p = script->buffer; + script->end_p = script->buffer + size; +} + + +/* +============== +LoadScriptFile +============== +*/ +void LoadScriptFile (char *filename) +{ + script = scriptstack; + AddScriptToStack (filename); + + endofscript = false; + tokenready = false; +} + + +/* +============== +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 = false; + tokenready = false; +} + + +/* +============== +UnGetToken + +Signals that the current token was not used, and should be reported +for the next GetToken. Note that + +GetToken (true); +UnGetToken (); +GetToken (false); + +could cross a line boundary. +============== +*/ +void UnGetToken (void) +{ + tokenready = true; +} + + +qboolean EndOfScript (qboolean crossline) +{ + if (!crossline) + Error ("Line %i is incomplete\n",scriptline); + + if (!strcmp (script->filename, "memory buffer")) + { + endofscript = true; + return false; + } + + free (script->buffer); + if (script == scriptstack+1) + { + endofscript = true; + return false; + } + script--; + scriptline = script->line; + printf ("returning to %s\n", script->filename); + return GetToken (crossline); +} + +/* +============== +GetToken +============== +*/ +qboolean GetToken (qboolean crossline) +{ + char *token_p; + + if (tokenready) // is a token allready waiting? + { + tokenready = false; + return true; + } + + if (script->script_p >= script->end_p) + 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); + 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); + 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] != '/') + { + 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 (false); + AddScriptToStack (token); + return GetToken (crossline); + } + + return true; +} + + +/* +============== +TokenAvailable + +Returns true if there is another token on the line +============== +*/ +qboolean TokenAvailable (void) +{ + char *search_p; + + search_p = script->script_p; + + if (search_p >= script->end_p) + return false; + + while ( *search_p <= 32) + { + if (*search_p == '\n') + return false; + search_p++; + if (search_p == script->end_p) + return false; + + } + + if (*search_p == ';') + return false; + + return true; +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/scriplib.h b/misc/mediasource/netradiant-src/tools/quake2/common/scriplib.h new file mode 100644 index 00000000..d07a9bb4 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/scriplib.h @@ -0,0 +1,43 @@ +/* +Copyright (C) 1999-2006 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 "cmdlib.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 (char *filename); +void ParseFromMemory (char *buffer, int size); + +qboolean GetToken (qboolean crossline); +void UnGetToken (void); +qboolean TokenAvailable (void); + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/threads.c b/misc/mediasource/netradiant-src/tools/quake2/common/threads.c new file mode 100644 index 00000000..9c123a5a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/threads.c @@ -0,0 +1,618 @@ +/* +Copyright (C) 1999-2006 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 "q2_threads.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_FPrintf( SYS_VRB,"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 + +// Setting default Threads to 1 +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 = true; + + // + // run threads in parallel + // + InitializeCriticalSection (&crit); + + if (numthreads == 1) + { // use same thread + func (0); + } + else + { + for (i=0 ; i + +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 = true; + + 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 +#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 = true; + + if (pacifier) + setbuf (stdout, NULL); + + init_lock (&lck); + + for (i=0 ; i 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 = true; + + if(pacifier) + setbuf(stdout, NULL); + + if(pthread_mutexattr_init(&mattrib) != 0) + Error("pthread_mutexattr_init failed"); + if (pthread_mutexattr_settype(&mattrib, PTHREAD_MUTEX_ERRORCHECK) != 0) + Error ("pthread_mutexattr_settype failed"); + recursive_mutex_init(mattrib); + + for (i=0 ; i +#include "cmdlib.h" +#include "inout.h" +#include "mathlib.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 + +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; + + +void ByteSwapTri (tf_triangle *tri) +{ + int i; + + for (i=0 ; iverts[j][k] = tri.pt[j].p.v[k]; + } + } + + ptri++; + + if ((ptri - *pptri) >= MAXTRIANGLES) + Error ("Error: too many triangles; increase MAXTRIANGLES\n"); + } + } + + *numtriangles = ptri - *pptri; + + fclose (input); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/common/trilib.h b/misc/mediasource/netradiant-src/tools/quake2/common/trilib.h new file mode 100644 index 00000000..5c32244a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/common/trilib.h @@ -0,0 +1,31 @@ +/* +Copyright (C) 1999-2006 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 +// +#define MAXTRIANGLES 2048 + +typedef struct { + vec3_t verts[3]; +} triangle_t; + +void LoadTriangleList (char *filename, triangle_t **pptri, int *numtriangles); + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/brushbsp.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/brushbsp.c new file mode 100644 index 00000000..53985b03 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/brushbsp.c @@ -0,0 +1,1329 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + + +int c_nodes; +int c_nonvis; +int c_active_brushes; + +// if a brush just barely pokes onto the other side, +// let it slide by without chopping +#define PLANESIDE_EPSILON 0.001 +//0.1 + +#define PSIDE_FRONT 1 +#define PSIDE_BACK 2 +#define PSIDE_BOTH (PSIDE_FRONT|PSIDE_BACK) +#define PSIDE_FACING 4 + + +void FindBrushInTree (node_t *node, int brushnum) +{ + bspbrush_t *b; + + if (node->planenum == PLANENUM_LEAF) + { + for (b=node->brushlist ; b ; b=b->next) + if (b->original->brushnum == brushnum) + Sys_Printf ("here\n"); + return; + } + FindBrushInTree (node->children[0], brushnum); + FindBrushInTree (node->children[1], brushnum); +} + +//================================================== + +/* +================ +DrawBrushList +================ +*/ +void DrawBrushList (bspbrush_t *brush, node_t *node) +{ + int i; + side_t *s; + + GLS_BeginScene (); + for ( ; brush ; brush=brush->next) + { + for (i=0 ; inumsides ; i++) + { + s = &brush->sides[i]; + if (!s->winding) + continue; + if (s->texinfo == TEXINFO_NODE) + GLS_Winding (s->winding, 1); + else if (!s->visible) + GLS_Winding (s->winding, 2); + else + GLS_Winding (s->winding, 0); + } + } + GLS_EndScene (); +} + +/* +================ +WriteBrushList +================ +*/ +void WriteBrushList (char *name, bspbrush_t *brush, qboolean onlyvis) +{ + int i; + side_t *s; + FILE *f; + + Sys_FPrintf( SYS_VRB, "writing %s\n", name); + f = SafeOpenWrite (name); + + for ( ; brush ; brush=brush->next) + { + for (i=0 ; inumsides ; i++) + { + s = &brush->sides[i]; + if (!s->winding) + continue; + if (onlyvis && !s->visible) + continue; + OutputWinding (brush->sides[i].winding, f); + } + } + + fclose (f); +} + +void PrintBrush (bspbrush_t *brush) +{ + int i; + + Sys_Printf ("brush: %p\n", brush); + for (i=0;inumsides ; i++) + { + pw(brush->sides[i].winding); + Sys_Printf ("\n"); + } +} + +/* +================== +BoundBrush + +Sets the mins/maxs based on the windings +================== +*/ +void BoundBrush (bspbrush_t *brush) +{ + int i, j; + winding_t *w; + + ClearBounds (brush->mins, brush->maxs); + for (i=0 ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (!w) + continue; + for (j=0 ; jnumpoints ; j++) + AddPointToBounds (w->p[j], brush->mins, brush->maxs); + } +} + +/* +================== +CreateBrushWindings + +================== +*/ +void CreateBrushWindings (bspbrush_t *brush) +{ + int i, j; + winding_t *w; + side_t *side; + plane_t *plane; + + for (i=0 ; inumsides ; i++) + { + side = &brush->sides[i]; + plane = &mapplanes[side->planenum]; + w = BaseWindingForPlane (plane->normal, plane->dist); + for (j=0 ; jnumsides && w; j++) + { + if (i == j) + continue; + if (brush->sides[j].bevel) + continue; + plane = &mapplanes[brush->sides[j].planenum^1]; + ChopWindingInPlace (&w, plane->normal, plane->dist, 0); //CLIP_EPSILON); + } + + side->winding = w; + } + + BoundBrush (brush); +} + +/* +================== +BrushFromBounds + +Creates a new axial brush +================== +*/ +bspbrush_t *BrushFromBounds (vec3_t mins, vec3_t maxs) +{ + bspbrush_t *b; + int i; + vec3_t normal; + vec_t dist; + + b = AllocBrush (6); + b->numsides = 6; + for (i=0 ; i<3 ; i++) + { + VectorClear (normal); + normal[i] = 1; + dist = maxs[i]; + b->sides[i].planenum = FindFloatPlane (normal, dist); + + normal[i] = -1; + dist = -mins[i]; + b->sides[3+i].planenum = FindFloatPlane (normal, dist); + } + + CreateBrushWindings (b); + + return b; +} + +/* +================== +BrushVolume + +================== +*/ +vec_t BrushVolume (bspbrush_t *brush) +{ + int i; + winding_t *w; + vec3_t corner; + vec_t d, area, volume; + plane_t *plane; + + if (!brush) + return 0; + + // grab the first valid point as the corner + + w = NULL; + for (i=0 ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (w) + break; + } + if (!w) + return 0; + VectorCopy (w->p[0], corner); + + // make tetrahedrons to all other faces + + volume = 0; + for ( ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (!w) + continue; + plane = &mapplanes[brush->sides[i].planenum]; + d = -(DotProduct (corner, plane->normal) - plane->dist); + area = WindingArea (w); + volume += d*area; + } + + volume /= 3; + return volume; +} + +/* +================ +CountBrushList +================ +*/ +int CountBrushList (bspbrush_t *brushes) +{ + int c; + + c = 0; + for ( ; brushes ; brushes = brushes->next) + c++; + return c; +} + +/* +================ +AllocTree +================ +*/ +tree_t *AllocTree (void) +{ + tree_t *tree; + + tree = malloc(sizeof(*tree)); + memset (tree, 0, sizeof(*tree)); + ClearBounds (tree->mins, tree->maxs); + + return tree; +} + +/* +================ +AllocNode +================ +*/ +node_t *AllocNode (void) +{ + node_t *node; + + node = malloc(sizeof(*node)); + memset (node, 0, sizeof(*node)); + + return node; +} + + +/* +================ +AllocBrush +================ +*/ +bspbrush_t *AllocBrush (int numsides) +{ + bspbrush_t *bb; + int c; + + c = (int)&(((bspbrush_t *)0)->sides[numsides]); + bb = malloc(c); + memset (bb, 0, c); + if (numthreads == 1) + c_active_brushes++; + return bb; +} + +/* +================ +FreeBrush +================ +*/ +void FreeBrush (bspbrush_t *brushes) +{ + int i; + + for (i=0 ; inumsides ; i++) + if (brushes->sides[i].winding) + FreeWinding(brushes->sides[i].winding); + free (brushes); + if (numthreads == 1) + c_active_brushes--; +} + + +/* +================ +FreeBrushList +================ +*/ +void FreeBrushList (bspbrush_t *brushes) +{ + bspbrush_t *next; + + for ( ; brushes ; brushes = next) + { + next = brushes->next; + + FreeBrush (brushes); + } +} + +/* +================== +CopyBrush + +Duplicates the brush, the sides, and the windings +================== +*/ +bspbrush_t *CopyBrush (bspbrush_t *brush) +{ + bspbrush_t *newbrush; + int size; + int i; + + size = (int)&(((bspbrush_t *)0)->sides[brush->numsides]); + + newbrush = AllocBrush (brush->numsides); + memcpy (newbrush, brush, size); + + for (i=0 ; inumsides ; i++) + { + if (brush->sides[i].winding) + newbrush->sides[i].winding = CopyWinding (brush->sides[i].winding); + } + + return newbrush; +} + + +/* +================== +PointInLeaf + +================== +*/ +node_t *PointInLeaf (node_t *node, vec3_t point) +{ + vec_t d; + plane_t *plane; + + while (node->planenum != PLANENUM_LEAF) + { + plane = &mapplanes[node->planenum]; + d = DotProduct (point, plane->normal) - plane->dist; + if (d > 0) + node = node->children[0]; + else + node = node->children[1]; + } + + return node; +} + +//======================================================== + +/* +============== +BoxOnPlaneSide + +Returns PSIDE_FRONT, PSIDE_BACK, or PSIDE_BOTH +============== +*/ +int BoxOnPlaneSide (vec3_t mins, vec3_t maxs, plane_t *plane) +{ + int side; + int i; + vec3_t corners[2]; + vec_t dist1, dist2; + + // axial planes are easy + if (plane->type < 3) + { + side = 0; + if (maxs[plane->type] > plane->dist+PLANESIDE_EPSILON) + side |= PSIDE_FRONT; + if (mins[plane->type] < plane->dist-PLANESIDE_EPSILON) + side |= PSIDE_BACK; + return side; + } + + // create the proper leading and trailing verts for the box + + for (i=0 ; i<3 ; i++) + { + if (plane->normal[i] < 0) + { + corners[0][i] = mins[i]; + corners[1][i] = maxs[i]; + } + else + { + corners[1][i] = mins[i]; + corners[0][i] = maxs[i]; + } + } + + dist1 = DotProduct (plane->normal, corners[0]) - plane->dist; + dist2 = DotProduct (plane->normal, corners[1]) - plane->dist; + side = 0; + if (dist1 >= PLANESIDE_EPSILON) + side = PSIDE_FRONT; + if (dist2 < PLANESIDE_EPSILON) + side |= PSIDE_BACK; + + return side; +} + +/* +============ +QuickTestBrushToPlanenum + +============ +*/ +int QuickTestBrushToPlanenum (bspbrush_t *brush, int planenum, int *numsplits) +{ + int i, num; + plane_t *plane; + int s; + + *numsplits = 0; + + // if the brush actually uses the planenum, + // we can tell the side for sure + for (i=0 ; inumsides ; i++) + { + num = brush->sides[i].planenum; + if (num >= 0x10000) + Error ("bad planenum"); + if (num == planenum) + return PSIDE_BACK|PSIDE_FACING; + if (num == (planenum ^ 1) ) + return PSIDE_FRONT|PSIDE_FACING; + } + + // box on plane side + plane = &mapplanes[planenum]; + s = BoxOnPlaneSide (brush->mins, brush->maxs, plane); + + // if both sides, count the visible faces split + if (s == PSIDE_BOTH) + { + *numsplits += 3; + } + + return s; +} + +/* +============ +TestBrushToPlanenum + +============ +*/ +int TestBrushToPlanenum (bspbrush_t *brush, int planenum, + int *numsplits, qboolean *hintsplit, int *epsilonbrush) +{ + int i, j, num; + plane_t *plane; + int s; + winding_t *w; + vec_t d, d_front, d_back; + int front, back; + + *numsplits = 0; + *hintsplit = false; + + // if the brush actually uses the planenum, + // we can tell the side for sure + for (i=0 ; inumsides ; i++) + { + num = brush->sides[i].planenum; + if (num >= 0x10000) + Error ("bad planenum"); + if (num == planenum) + return PSIDE_BACK|PSIDE_FACING; + if (num == (planenum ^ 1) ) + return PSIDE_FRONT|PSIDE_FACING; + } + + // box on plane side + plane = &mapplanes[planenum]; + s = BoxOnPlaneSide (brush->mins, brush->maxs, plane); + + if (s != PSIDE_BOTH) + return s; + +// if both sides, count the visible faces split + d_front = d_back = 0; + + for (i=0 ; inumsides ; i++) + { + if (brush->sides[i].texinfo == TEXINFO_NODE) + continue; // on node, don't worry about splits + if (!brush->sides[i].visible) + continue; // we don't care about non-visible + w = brush->sides[i].winding; + if (!w) + continue; + front = back = 0; + for (j=0 ; jnumpoints; j++) + { + d = DotProduct (w->p[j], plane->normal) - plane->dist; + if (d > d_front) + d_front = d; + if (d < d_back) + d_back = d; + + if (d > 0.1) // PLANESIDE_EPSILON) + front = 1; + if (d < -0.1) // PLANESIDE_EPSILON) + back = 1; + } + if (front && back) + { + if ( !(brush->sides[i].surf & SURF_SKIP) ) + { + (*numsplits)++; + if (brush->sides[i].surf & SURF_HINT) + *hintsplit = true; + } + } + } + + if ( (d_front > 0.0 && d_front < 1.0) + || (d_back < 0.0 && d_back > -1.0) ) + (*epsilonbrush)++; + +#if 0 + if (*numsplits == 0) + { // didn't really need to be split + if (front) + s = PSIDE_FRONT; + else if (back) + s = PSIDE_BACK; + else + s = 0; + } +#endif + + return s; +} + +//======================================================== + +/* +================ +WindingIsTiny + +Returns true if the winding would be crunched out of +existance by the vertex snapping. +================ +*/ +#define EDGE_LENGTH 0.2 +qboolean WindingIsTiny (winding_t *w) +{ +#if 0 + if (WindingArea (w) < 1) + return true; + return false; +#else + int i, j; + vec_t len; + vec3_t delta; + int edges; + + edges = 0; + for (i=0 ; inumpoints ; i++) + { + j = i == w->numpoints - 1 ? 0 : i+1; + VectorSubtract (w->p[j], w->p[i], delta); + len = (float) VectorLength (delta); + if (len > EDGE_LENGTH) + { + if (++edges == 3) + return false; + } + } + return true; +#endif +} + +/* +================ +WindingIsHuge + +Returns true if the winding still has one of the points +from basewinding for plane +================ +*/ +qboolean WindingIsHuge (winding_t *w) +{ + int i, j; + + for (i=0 ; inumpoints ; i++) + { + for (j=0 ; j<3 ; j++) + if (w->p[i][j] < -8000 || w->p[i][j] > 8000) + return true; + } + return false; +} + +//============================================================ + +/* +================ +Leafnode +================ +*/ +void LeafNode (node_t *node, bspbrush_t *brushes) +{ + bspbrush_t *b; + int i; + + node->planenum = PLANENUM_LEAF; + node->contents = 0; + + for (b=brushes ; b ; b=b->next) + { + // if the brush is solid and all of its sides are on nodes, + // it eats everything + if (b->original->contents & CONTENTS_SOLID) + { + for (i=0 ; inumsides ; i++) + if (b->sides[i].texinfo != TEXINFO_NODE) + break; + if (i == b->numsides) + { + node->contents = CONTENTS_SOLID; + break; + } + } + node->contents |= b->original->contents; + } + + node->brushlist = brushes; +} + + +//============================================================ + +void CheckPlaneAgainstParents (int pnum, node_t *node) +{ + node_t *p; + + for (p=node->parent ; p ; p=p->parent) + { + if (p->planenum == pnum) + Error ("Tried parent"); + } +} + +qboolean CheckPlaneAgainstVolume (int pnum, node_t *node) +{ + bspbrush_t *front, *back; + qboolean good; + + SplitBrush (node->volume, pnum, &front, &back); + + good = (front && back); + + if (front) + FreeBrush (front); + if (back) + FreeBrush (back); + + return good; +} + +/* +================ +SelectSplitSide + +Using a hueristic, choses one of the sides out of the brushlist +to partition the brushes with. +Returns NULL if there are no valid planes to split with.. +================ +*/ +side_t *SelectSplitSide (bspbrush_t *brushes, node_t *node) +{ + int value, bestvalue; + bspbrush_t *brush, *test; + side_t *side, *bestside; + int i, j, pass, numpasses; + int pnum; + int s; + int front, back, both, facing, splits; + int bsplits; + int bestsplits; + int epsilonbrush; + qboolean hintsplit; + + bestside = NULL; + bestvalue = -99999; + bestsplits = 0; + + // the search order goes: visible-structural, visible-detail, + // nonvisible-structural, nonvisible-detail. + // If any valid plane is available in a pass, no further + // passes will be tried. + numpasses = 4; + for (pass = 0 ; pass < numpasses ; pass++) + { + for (brush = brushes ; brush ; brush=brush->next) + { + if ( (pass & 1) && !(brush->original->contents & CONTENTS_DETAIL) ) + continue; + if ( !(pass & 1) && (brush->original->contents & CONTENTS_DETAIL) ) + continue; + for (i=0 ; inumsides ; i++) + { + side = brush->sides + i; + if (side->bevel) + continue; // never use a bevel as a spliter + if (!side->winding) + continue; // nothing visible, so it can't split + if (side->texinfo == TEXINFO_NODE) + continue; // allready a node splitter + if (side->tested) + continue; // we allready have metrics for this plane + if (side->surf & SURF_SKIP) + continue; // skip surfaces are never chosen + if ( side->visible ^ (pass<2) ) + continue; // only check visible faces on first pass + + pnum = side->planenum; + pnum &= ~1; // allways use positive facing plane + + CheckPlaneAgainstParents (pnum, node); + + if (!CheckPlaneAgainstVolume (pnum, node)) + continue; // would produce a tiny volume + + front = 0; + back = 0; + both = 0; + facing = 0; + splits = 0; + epsilonbrush = 0; + + for (test = brushes ; test ; test=test->next) + { + s = TestBrushToPlanenum (test, pnum, &bsplits, &hintsplit, &epsilonbrush); + + splits += bsplits; + if (bsplits && (s&PSIDE_FACING) ) + Error ("PSIDE_FACING with splits"); + + test->testside = s; + // if the brush shares this face, don't bother + // testing that facenum as a splitter again + if (s & PSIDE_FACING) + { + facing++; + for (j=0 ; jnumsides ; j++) + { + if ( (test->sides[j].planenum&~1) == pnum) + test->sides[j].tested = true; + } + } + if (s & PSIDE_FRONT) + front++; + if (s & PSIDE_BACK) + back++; + if (s == PSIDE_BOTH) + both++; + } + + // give a value estimate for using this plane + + value = 5*facing - 5*splits - abs(front-back); +// value = -5*splits; +// value = 5*facing - 5*splits; + if (mapplanes[pnum].type < 3) + value+=5; // axial is better + value -= epsilonbrush*1000; // avoid! + + // never split a hint side except with another hint + if (hintsplit && !(side->surf & SURF_HINT) ) + value = -9999999; + + // save off the side test so we don't need + // to recalculate it when we actually seperate + // the brushes + if (value > bestvalue) + { + bestvalue = value; + bestside = side; + bestsplits = splits; + for (test = brushes ; test ; test=test->next) + test->side = test->testside; + } + } + } + + // if we found a good plane, don't bother trying any + // other passes + if (bestside) + { + if (pass > 1) + { + if (numthreads == 1) + c_nonvis++; + } + if (pass > 0) + node->detail_seperator = true; // not needed for vis + break; + } + } + + // + // clear all the tested flags we set + // + for (brush = brushes ; brush ; brush=brush->next) + { + for (i=0 ; inumsides ; i++) + brush->sides[i].tested = false; + } + + return bestside; +} + + +/* +================== +BrushMostlyOnSide + +================== +*/ +int BrushMostlyOnSide (bspbrush_t *brush, plane_t *plane) +{ + int i, j; + winding_t *w; + vec_t d, max; + int side; + + max = 0; + side = PSIDE_FRONT; + for (i=0 ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (!w) + continue; + for (j=0 ; jnumpoints ; j++) + { + d = DotProduct (w->p[j], plane->normal) - plane->dist; + if (d > max) + { + max = d; + side = PSIDE_FRONT; + } + if (-d > max) + { + max = -d; + side = PSIDE_BACK; + } + } + } + return side; +} + +/* +================ +SplitBrush + +Generates two new brushes, leaving the original +unchanged +================ +*/ +void SplitBrush (bspbrush_t *brush, int planenum, + bspbrush_t **front, bspbrush_t **back) +{ + bspbrush_t *b[2]; + int i, j; + winding_t *w, *cw[2], *midwinding; + plane_t *plane, *plane2; + side_t *s, *cs; + float d, d_front, d_back; + + *front = *back = NULL; + plane = &mapplanes[planenum]; + + // check all points + d_front = d_back = 0; + for (i=0 ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (!w) + continue; + for (j=0 ; jnumpoints ; j++) + { + d = DotProduct (w->p[j], plane->normal) - plane->dist; + if (d > 0 && d > d_front) + d_front = d; + if (d < 0 && d < d_back) + d_back = d; + } + } + if (d_front < 0.1) // PLANESIDE_EPSILON) + { // only on back + *back = CopyBrush (brush); + return; + } + if (d_back > -0.1) // PLANESIDE_EPSILON) + { // only on front + *front = CopyBrush (brush); + return; + } + + // create a new winding from the split plane + + w = BaseWindingForPlane (plane->normal, plane->dist); + for (i=0 ; inumsides && w ; i++) + { + plane2 = &mapplanes[brush->sides[i].planenum ^ 1]; + ChopWindingInPlace (&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON); + } + + if (!w || WindingIsTiny (w) ) + { // the brush isn't really split + int side; + + side = BrushMostlyOnSide (brush, plane); + if (side == PSIDE_FRONT) + *front = CopyBrush (brush); + if (side == PSIDE_BACK) + *back = CopyBrush (brush); + return; + } + + if (WindingIsHuge (w)) + { + Sys_FPrintf( SYS_VRB, "WARNING: huge winding\n"); + } + + midwinding = w; + + // split it for real + + for (i=0 ; i<2 ; i++) + { + b[i] = AllocBrush (brush->numsides+1); + b[i]->original = brush->original; + } + + // split all the current windings + + for (i=0 ; inumsides ; i++) + { + s = &brush->sides[i]; + w = s->winding; + if (!w) + continue; + ClipWindingEpsilon (w, plane->normal, plane->dist, + 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]); + for (j=0 ; j<2 ; j++) + { + if (!cw[j]) + continue; +#if 0 + if (WindingIsTiny (cw[j])) + { + FreeWinding (cw[j]); + continue; + } +#endif + cs = &b[j]->sides[b[j]->numsides]; + b[j]->numsides++; + *cs = *s; +// cs->planenum = s->planenum; +// cs->texinfo = s->texinfo; +// cs->visible = s->visible; +// cs->original = s->original; + cs->winding = cw[j]; + cs->tested = false; + } + } + + + // see if we have valid polygons on both sides + + for (i=0 ; i<2 ; i++) + { + BoundBrush (b[i]); + for (j=0 ; j<3 ; j++) + { + if (b[i]->mins[j] < -4096 || b[i]->maxs[j] > 4096) + { + Sys_FPrintf( SYS_VRB, "bogus brush after clip\n"); + break; + } + } + + if (b[i]->numsides < 3 || j < 3) + { + FreeBrush (b[i]); + b[i] = NULL; + } + } + + if ( !(b[0] && b[1]) ) + { + if (!b[0] && !b[1]) + Sys_FPrintf( SYS_VRB, "split removed brush\n"); + else + Sys_FPrintf( SYS_VRB, "split not on both sides\n"); + if (b[0]) + { + FreeBrush (b[0]); + *front = CopyBrush (brush); + } + if (b[1]) + { + FreeBrush (b[1]); + *back = CopyBrush (brush); + } + return; + } + + // add the midwinding to both sides + for (i=0 ; i<2 ; i++) + { + cs = &b[i]->sides[b[i]->numsides]; + b[i]->numsides++; + + cs->planenum = planenum^i^1; + cs->texinfo = TEXINFO_NODE; + cs->visible = false; + cs->tested = false; + if (i==0) + cs->winding = CopyWinding (midwinding); + else + cs->winding = midwinding; + } + +{ + vec_t v1; + int i; + + for (i=0 ; i<2 ; i++) + { + v1 = BrushVolume (b[i]); + if (v1 < 1.0) + { + FreeBrush (b[i]); + b[i] = NULL; + Sys_FPrintf( SYS_VRB, "tiny volume after clip\n"); + } + } +} + + *front = b[0]; + *back = b[1]; +} + +/* +================ +SplitBrushList +================ +*/ +void SplitBrushList (bspbrush_t *brushes, + node_t *node, bspbrush_t **front, bspbrush_t **back) +{ + bspbrush_t *brush, *newbrush, *newbrush2; + side_t *side; + int sides; + int i; + + *front = *back = NULL; + + for (brush = brushes ; brush ; brush=brush->next) + { + sides = brush->side; + + if (sides == PSIDE_BOTH) + { // split into two brushes + SplitBrush (brush, node->planenum, &newbrush, &newbrush2); + if (newbrush) + { + newbrush->next = *front; + *front = newbrush; + } + if (newbrush2) + { + newbrush2->next = *back; + *back = newbrush2; + } + continue; + } + + newbrush = CopyBrush (brush); + + // if the planenum is actualy a part of the brush + // find the plane and flag it as used so it won't be tried + // as a splitter again + if (sides & PSIDE_FACING) + { + for (i=0 ; inumsides ; i++) + { + side = newbrush->sides + i; + if ( (side->planenum& ~1) == node->planenum) + side->texinfo = TEXINFO_NODE; + } + } + + + if (sides & PSIDE_FRONT) + { + newbrush->next = *front; + *front = newbrush; + continue; + } + if (sides & PSIDE_BACK) + { + newbrush->next = *back; + *back = newbrush; + continue; + } + } +} + + +/* +================ +BuildTree_r +================ +*/ +node_t *BuildTree_r (node_t *node, bspbrush_t *brushes) +{ + node_t *newnode; + side_t *bestside; + int i; + bspbrush_t *children[2]; + + if (numthreads == 1) + c_nodes++; + + if (drawflag) + DrawBrushList (brushes, node); + + // find the best plane to use as a splitter + bestside = SelectSplitSide (brushes, node); + if (!bestside) + { + // leaf node + node->side = NULL; + node->planenum = -1; + LeafNode (node, brushes); + return node; + } + + // this is a splitplane node + node->side = bestside; + node->planenum = bestside->planenum & ~1; // always use front facing + + SplitBrushList (brushes, node, &children[0], &children[1]); + FreeBrushList (brushes); + + // allocate children before recursing + for (i=0 ; i<2 ; i++) + { + newnode = AllocNode (); + newnode->parent = node; + node->children[i] = newnode; + } + + SplitBrush (node->volume, node->planenum, &node->children[0]->volume, + &node->children[1]->volume); + + // recursively process children + for (i=0 ; i<2 ; i++) + { + node->children[i] = BuildTree_r (node->children[i], children[i]); + } + + return node; +} + +//=========================================================== + +/* +================= +BrushBSP + +The incoming list will be freed before exiting +================= +*/ +tree_t *BrushBSP (bspbrush_t *brushlist, vec3_t mins, vec3_t maxs) +{ + node_t *node; + bspbrush_t *b; + int c_faces, c_nonvisfaces; + int c_brushes; + tree_t *tree; + int i; + vec_t volume; + + Sys_FPrintf( SYS_VRB, "--- BrushBSP ---\n"); + + tree = AllocTree (); + + c_faces = 0; + c_nonvisfaces = 0; + c_brushes = 0; + for (b=brushlist ; b ; b=b->next) + { + c_brushes++; + + volume = BrushVolume (b); + if (volume < microvolume) + { + Sys_Printf ("WARNING: entity %i, brush %i: microbrush\n", + b->original->entitynum, b->original->brushnum); + } + + for (i=0 ; inumsides ; i++) + { + if (b->sides[i].bevel) + continue; + if (!b->sides[i].winding) + continue; + if (b->sides[i].texinfo == TEXINFO_NODE) + continue; + if (b->sides[i].visible) + c_faces++; + else + c_nonvisfaces++; + } + + AddPointToBounds (b->mins, tree->mins, tree->maxs); + AddPointToBounds (b->maxs, tree->mins, tree->maxs); + } + + Sys_FPrintf( SYS_VRB, "%5i brushes\n", c_brushes); + Sys_FPrintf( SYS_VRB, "%5i visible faces\n", c_faces); + Sys_FPrintf( SYS_VRB, "%5i nonvisible faces\n", c_nonvisfaces); + + c_nodes = 0; + c_nonvis = 0; + node = AllocNode (); + + node->volume = BrushFromBounds (mins, maxs); + + tree->headnode = node; + + node = BuildTree_r (node, brushlist); + Sys_FPrintf( SYS_VRB, "%5i visible nodes\n", c_nodes/2 - c_nonvis); + Sys_FPrintf( SYS_VRB, "%5i nonvis nodes\n", c_nonvis); + Sys_FPrintf( SYS_VRB, "%5i leafs\n", (c_nodes+1)/2); +#if 0 +{ // debug code +static node_t *tnode; +vec3_t p; + +p[0] = -1469; +p[1] = -118; +p[2] = 119; +tnode = PointInLeaf (tree->headnode, p); +Sys_Printf ("contents: %i\n", tnode->contents); +p[0] = 0; +} +#endif + return tree; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/csg.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/csg.c new file mode 100644 index 00000000..2e058299 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/csg.c @@ -0,0 +1,634 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +/* + +tag all brushes with original contents +brushes may contain multiple contents +there will be no brush overlap after csg phase + + + + +each side has a count of the other sides it splits + +the best split will be the one that minimizes the total split counts +of all remaining sides + +precalc side on plane table + +evaluate split side +{ +cost = 0 +for all sides + for all sides + get + if side splits side and splitside is on same child + cost++; +} + + + */ + +void SplitBrush2 (bspbrush_t *brush, int planenum, + bspbrush_t **front, bspbrush_t **back) +{ + SplitBrush (brush, planenum, front, back); +#if 0 + if (*front && (*front)->sides[(*front)->numsides-1].texinfo == -1) + (*front)->sides[(*front)->numsides-1].texinfo = (*front)->sides[0].texinfo; // not -1 + if (*back && (*back)->sides[(*back)->numsides-1].texinfo == -1) + (*back)->sides[(*back)->numsides-1].texinfo = (*back)->sides[0].texinfo; // not -1 +#endif +} + +/* +=============== +SubtractBrush + +Returns a list of brushes that remain after B is subtracted from A. +May by empty if A is contained inside B. + +The originals are undisturbed. +=============== +*/ +bspbrush_t *SubtractBrush (bspbrush_t *a, bspbrush_t *b) +{ // a - b = out (list) + int i; + bspbrush_t *front, *back; + bspbrush_t *out, *in; + + in = a; + out = NULL; + for (i=0 ; inumsides && in ; i++) + { + SplitBrush2 (in, b->sides[i].planenum, &front, &back); + if (in != a) + FreeBrush (in); + if (front) + { // add to list + front->next = out; + out = front; + } + in = back; + } + if (in) + FreeBrush (in); + else + { // didn't really intersect + FreeBrushList (out); + return a; + } + return out; +} + +/* +=============== +IntersectBrush + +Returns a single brush made up by the intersection of the +two provided brushes, or NULL if they are disjoint. + +The originals are undisturbed. +=============== +*/ +bspbrush_t *IntersectBrush (bspbrush_t *a, bspbrush_t *b) +{ + int i; + bspbrush_t *front, *back; + bspbrush_t *in; + + in = a; + for (i=0 ; inumsides && in ; i++) + { + SplitBrush2 (in, b->sides[i].planenum, &front, &back); + if (in != a) + FreeBrush (in); + if (front) + FreeBrush (front); + in = back; + } + + if (in == a) + return NULL; + + in->next = NULL; + return in; +} + + +/* +=============== +BrushesDisjoint + +Returns true if the two brushes definately do not intersect. +There will be false negatives for some non-axial combinations. +=============== +*/ +qboolean BrushesDisjoint (bspbrush_t *a, bspbrush_t *b) +{ + int i, j; + + // check bounding boxes + for (i=0 ; i<3 ; i++) + if (a->mins[i] >= b->maxs[i] + || a->maxs[i] <= b->mins[i]) + return true; // bounding boxes don't overlap + + // check for opposing planes + for (i=0 ; inumsides ; i++) + { + for (j=0 ; jnumsides ; j++) + { + if (a->sides[i].planenum == + (b->sides[j].planenum^1) ) + return true; // opposite planes, so not touching + } + } + + return false; // might intersect +} + +/* +=============== +IntersectionContents + +Returns a content word for the intersection of two brushes. +Some combinations will generate a combination (water + clip), +but most will be the stronger of the two contents. +=============== +*/ +int IntersectionContents (int c1, int c2) +{ + int out; + + out = c1 | c2; + + if (out & CONTENTS_SOLID) + out = CONTENTS_SOLID; + + return out; +} + + +int minplanenums[3]; +int maxplanenums[3]; + +/* +=============== +ClipBrushToBox + +Any planes shared with the box edge will be set to no texinfo +=============== +*/ +bspbrush_t *ClipBrushToBox (bspbrush_t *brush, vec3_t clipmins, vec3_t clipmaxs) +{ + int i, j; + bspbrush_t *front, *back; + int p; + + for (j=0 ; j<2 ; j++) + { + if (brush->maxs[j] > clipmaxs[j]) + { + SplitBrush (brush, maxplanenums[j], &front, &back); + if (front) + FreeBrush (front); + brush = back; + if (!brush) + return NULL; + } + if (brush->mins[j] < clipmins[j]) + { + SplitBrush (brush, minplanenums[j], &front, &back); + if (back) + FreeBrush (back); + brush = front; + if (!brush) + return NULL; + } + } + + // remove any colinear faces + + for (i=0 ; inumsides ; i++) + { + p = brush->sides[i].planenum & ~1; + if (p == maxplanenums[0] || p == maxplanenums[1] + || p == minplanenums[0] || p == minplanenums[1]) + { + brush->sides[i].texinfo = TEXINFO_NODE; + brush->sides[i].visible = false; + } + } + return brush; +} + +/* +=============== +MakeBspBrushList +=============== +*/ +bspbrush_t *MakeBspBrushList (int startbrush, int endbrush, + vec3_t clipmins, vec3_t clipmaxs) +{ + mapbrush_t *mb; + bspbrush_t *brushlist, *newbrush; + int i, j; + int c_faces; + int c_brushes; + int numsides; + int vis; + vec3_t normal; + float dist; + + for (i=0 ; i<2 ; i++) + { + VectorClear (normal); + normal[i] = 1; + dist = clipmaxs[i]; + maxplanenums[i] = FindFloatPlane (normal, dist); + dist = clipmins[i]; + minplanenums[i] = FindFloatPlane (normal, dist); + } + + brushlist = NULL; + c_faces = 0; + c_brushes = 0; + + for (i=startbrush ; inumsides; + if (!numsides) + continue; + // make sure the brush has at least one face showing + vis = 0; + for (j=0 ; joriginal_sides[j].visible && mb->original_sides[j].winding) + vis++; +#if 0 + if (!vis) + continue; // no faces at all +#endif + // if the brush is outside the clip area, skip it + for (j=0 ; j<3 ; j++) + if (mb->mins[j] >= clipmaxs[j] + || mb->maxs[j] <= clipmins[j]) + break; + if (j != 3) + continue; + + // + // make a copy of the brush + // + newbrush = AllocBrush (mb->numsides); + newbrush->original = mb; + newbrush->numsides = mb->numsides; + memcpy (newbrush->sides, mb->original_sides, numsides*sizeof(side_t)); + for (j=0 ; jsides[j].winding) + newbrush->sides[j].winding = CopyWinding (newbrush->sides[j].winding); + if (newbrush->sides[j].surf & SURF_HINT) + newbrush->sides[j].visible = true; // hints are always visible + } + VectorCopy (mb->mins, newbrush->mins); + VectorCopy (mb->maxs, newbrush->maxs); + + // + // carve off anything outside the clip box + // + newbrush = ClipBrushToBox (newbrush, clipmins, clipmaxs); + if (!newbrush) + continue; + + c_faces += vis; + c_brushes++; + + newbrush->next = brushlist; + brushlist = newbrush; + } + + return brushlist; +} + +/* +=============== +AddBspBrushListToTail +=============== +*/ +bspbrush_t *AddBrushListToTail (bspbrush_t *list, bspbrush_t *tail) +{ + bspbrush_t *walk, *next; + + for (walk=list ; walk ; walk=next) + { // add to end of list + next = walk->next; + walk->next = NULL; + tail->next = walk; + tail = walk; + } + + return tail; +} + +/* +=========== +CullList + +Builds a new list that doesn't hold the given brush +=========== +*/ +bspbrush_t *CullList (bspbrush_t *list, bspbrush_t *skip1) +{ + bspbrush_t *newlist; + bspbrush_t *next; + + newlist = NULL; + + for ( ; list ; list = next) + { + next = list->next; + if (list == skip1) + { + FreeBrush (list); + continue; + } + list->next = newlist; + newlist = list; + } + return newlist; +} + + +/* +================== +WriteBrushMap +================== +*/ +void WriteBrushMap (char *name, bspbrush_t *list) +{ + FILE *f; + side_t *s; + int i; + winding_t *w; + + Sys_Printf ("writing %s\n", name); + f = fopen (name, "wb"); + if (!f) + Error ("Can't write %s\b", name); + + fprintf (f, "{\n\"classname\" \"worldspawn\"\n"); + + for ( ; list ; list=list->next ) + { + fprintf (f, "{\n"); + for (i=0,s=list->sides ; inumsides ; i++,s++) + { + w = BaseWindingForPlane (mapplanes[s->planenum].normal, mapplanes[s->planenum].dist); + + fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]); + fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]); + fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]); + + fprintf (f, "%s 0 0 0 1 1\n", texinfo[s->texinfo].texture); + FreeWinding (w); + } + fprintf (f, "}\n"); + } + fprintf (f, "}\n"); + + fclose (f); + +} + +/* +================== +BrushGE + +Returns true if b1 is allowed to bite b2 +================== +*/ +qboolean BrushGE (bspbrush_t *b1, bspbrush_t *b2) +{ + // detail brushes never bite structural brushes + if ( (b1->original->contents & CONTENTS_DETAIL) + && !(b2->original->contents & CONTENTS_DETAIL) ) + return false; + if (b1->original->contents & CONTENTS_SOLID) + return true; + return false; +} + +/* +================= +ChopBrushes + +Carves any intersecting solid brushes into the minimum number +of non-intersecting brushes. +================= +*/ +bspbrush_t *ChopBrushes (bspbrush_t *head) +{ + bspbrush_t *b1, *b2, *next; + bspbrush_t *tail; + bspbrush_t *keep; + bspbrush_t *sub, *sub2; + int c1, c2; + + Sys_FPrintf( SYS_VRB, "---- ChopBrushes ----\n"); + Sys_FPrintf( SYS_VRB, "original brushes: %i\n", CountBrushList (head)); + +#if 0 + if (startbrush == 0) + WriteBrushList ("before.gl", head, false); +#endif + keep = NULL; + +newlist: + // find tail + if (!head) + return NULL; + for (tail=head ; tail->next ; tail=tail->next) + ; + + for (b1=head ; b1 ; b1=next) + { + next = b1->next; + for (b2=b1->next ; b2 ; b2 = b2->next) + { + if (BrushesDisjoint (b1, b2)) + continue; + + sub = NULL; + sub2 = NULL; + c1 = 999999; + c2 = 999999; + + if ( BrushGE (b2, b1) ) + { + sub = SubtractBrush (b1, b2); + if (sub == b1) + continue; // didn't really intersect + if (!sub) + { // b1 is swallowed by b2 + head = CullList (b1, b1); + goto newlist; + } + c1 = CountBrushList (sub); + } + + if ( BrushGE (b1, b2) ) + { + sub2 = SubtractBrush (b2, b1); + if (sub2 == b2) + continue; // didn't really intersect + if (!sub2) + { // b2 is swallowed by b1 + FreeBrushList (sub); + head = CullList (b1, b2); + goto newlist; + } + c2 = CountBrushList (sub2); + } + + if (!sub && !sub2) + continue; // neither one can bite + + // only accept if it didn't fragment + // (commening this out allows full fragmentation) + if (c1 > 1 && c2 > 1) + { + if (sub2) + FreeBrushList (sub2); + if (sub) + FreeBrushList (sub); + continue; + } + + if (c1 < c2) + { + if (sub2) + FreeBrushList (sub2); + tail = AddBrushListToTail (sub, tail); + head = CullList (b1, b1); + goto newlist; + } + else + { + if (sub) + FreeBrushList (sub); + tail = AddBrushListToTail (sub2, tail); + head = CullList (b1, b2); + goto newlist; + } + } + + if (!b2) + { // b1 is no longer intersecting anything, so keep it + b1->next = keep; + keep = b1; + } + } + + Sys_FPrintf( SYS_VRB, "output brushes: %i\n", CountBrushList (keep)); +#if 0 + { + WriteBrushList ("after.gl", keep, false); + WriteBrushMap ("after.map", keep); + } +#endif + return keep; +} + + +/* +================= +InitialBrushList +================= +*/ +bspbrush_t *InitialBrushList (bspbrush_t *list) +{ + bspbrush_t *b; + bspbrush_t *out, *newb; + int i; + + // only return brushes that have visible faces + out = NULL; + for (b=list ; b ; b=b->next) + { +#if 0 + for (i=0 ; inumsides ; i++) + if (b->sides[i].visible) + break; + if (i == b->numsides) + continue; +#endif + newb = CopyBrush (b); + newb->next = out; + out = newb; + + // clear visible, so it must be set by MarkVisibleFaces_r + // to be used in the optimized list + for (i=0 ; inumsides ; i++) + { + newb->sides[i].original = &b->sides[i]; +// newb->sides[i].visible = true; + b->sides[i].visible = false; + } + } + + return out; +} + +/* +================= +OptimizedBrushList +================= +*/ +bspbrush_t *OptimizedBrushList (bspbrush_t *list) +{ + bspbrush_t *b; + bspbrush_t *out, *newb; + int i; + + // only return brushes that have visible faces + out = NULL; + for (b=list ; b ; b=b->next) + { + for (i=0 ; inumsides ; i++) + if (b->sides[i].visible) + break; + if (i == b->numsides) + continue; + newb = CopyBrush (b); + newb->next = out; + out = newb; + } + +// WriteBrushList ("vis.gl", out, true); + + return out; +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/faces.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/faces.c new file mode 100644 index 00000000..03d5b955 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/faces.c @@ -0,0 +1,1076 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// faces.c + +#include "qbsp.h" + +/* + + some faces will be removed before saving, but still form nodes: + + the insides of sky volumes + meeting planes of different water current volumes + +*/ + +// undefine for dumb linear searches +#define USE_HASHING + +#define INTEGRAL_EPSILON 0.01 +#define POINT_EPSILON 0.5 +#define OFF_EPSILON 0.5 + +int c_merge; +int c_subdivide; + +int c_totalverts; +int c_uniqueverts; +int c_degenerate; +int c_tjunctions; +int c_faceoverflows; +int c_facecollapse; +int c_badstartverts; + +#define MAX_SUPERVERTS 512 +int superverts[MAX_SUPERVERTS]; +int numsuperverts; + +face_t *edgefaces[MAX_MAP_EDGES][2]; +int firstmodeledge = 1; +int firstmodelface; + +int c_tryedges; + +vec3_t edge_dir; +vec3_t edge_start; +vec_t edge_len; + +int num_edge_verts; +int edge_verts[MAX_MAP_VERTS]; + + +float subdivide_size = 240; + + +face_t *NewFaceFromFace (face_t *f); + +//=========================================================================== + +typedef struct hashvert_s +{ + struct hashvert_s *next; + int num; +} hashvert_t; + + +#define HASH_SIZE 64 + + +int vertexchain[MAX_MAP_VERTS]; // the next vertex in a hash chain +int hashverts[HASH_SIZE*HASH_SIZE]; // a vertex number, or 0 for no verts + +face_t *edgefaces[MAX_MAP_EDGES][2]; + +//============================================================================ + + +unsigned HashVec (vec3_t vec) +{ + int x, y; + + x = (4096 + (int)(vec[0]+0.5)) >> 7; + y = (4096 + (int)(vec[1]+0.5)) >> 7; + + if ( x < 0 || x >= HASH_SIZE || y < 0 || y >= HASH_SIZE ) + Error ("HashVec: point outside valid range"); + + return y*HASH_SIZE + x; +} + +#ifdef USE_HASHING +/* +============= +GetVertex + +Uses hashing +============= +*/ +int GetVertexnum (vec3_t in) +{ + int h; + int i; + float *p; + vec3_t vert; + int vnum; + + c_totalverts++; + + for (i=0 ; i<3 ; i++) + { + if ( fabs(in[i] - Q_rint(in[i])) < INTEGRAL_EPSILON) + vert[i] = Q_rint(in[i]); + else + vert[i] = in[i]; + } + + h = HashVec (vert); + + for (vnum=hashverts[h] ; vnum ; vnum=vertexchain[vnum]) + { + p = dvertexes[vnum].point; + if ( fabs(p[0]-vert[0]) 4096) + Error ("GetVertexnum: outside +/- 4096"); + } + + // search for an existing vertex match + for (i=0, dv=dvertexes ; ipoint[j]; + if ( d > POINT_EPSILON || d < -POINT_EPSILON) + break; + } + if (j == 3) + return i; // a match + } + + // new point + if (numvertexes == MAX_MAP_VERTS) + Error ("MAX_MAP_VERTS"); + VectorCopy (v, dv->point); + numvertexes++; + c_uniqueverts++; + + return numvertexes-1; +} +#endif + + +/* +================== +FaceFromSuperverts + +The faces vertexes have beeb added to the superverts[] array, +and there may be more there than can be held in a face (MAXEDGES). + +If less, the faces vertexnums[] will be filled in, otherwise +face will reference a tree of split[] faces until all of the +vertexnums can be added. + +superverts[base] will become face->vertexnums[0], and the others +will be circularly filled in. +================== +*/ +void FaceFromSuperverts (node_t *node, face_t *f, int base) +{ + face_t *newf; + int remaining; + int i; + + remaining = numsuperverts; + while (remaining > MAXEDGES) + { // must split into two faces, because of vertex overload + c_faceoverflows++; + + newf = f->split[0] = NewFaceFromFace (f); + newf = f->split[0]; + newf->next = node->faces; + node->faces = newf; + + newf->numpoints = MAXEDGES; + for (i=0 ; ivertexnums[i] = superverts[(i+base)%numsuperverts]; + + f->split[1] = NewFaceFromFace (f); + f = f->split[1]; + f->next = node->faces; + node->faces = f; + + remaining -= (MAXEDGES-2); + base = (base+MAXEDGES-1)%numsuperverts; + } + + // copy the vertexes back to the face + f->numpoints = remaining; + for (i=0 ; ivertexnums[i] = superverts[(i+base)%numsuperverts]; +} + + +/* +================== +EmitFaceVertexes +================== +*/ +void EmitFaceVertexes (node_t *node, face_t *f) +{ + winding_t *w; + int i; + + if (f->merged || f->split[0] || f->split[1]) + return; + + w = f->w; + for (i=0 ; inumpoints ; i++) + { + if (noweld) + { // make every point unique + if (numvertexes == MAX_MAP_VERTS) + Error ("MAX_MAP_VERTS"); + superverts[i] = numvertexes; + VectorCopy (w->p[i], dvertexes[numvertexes].point); + numvertexes++; + c_uniqueverts++; + c_totalverts++; + } + else + superverts[i] = GetVertexnum (w->p[i]); + } + numsuperverts = w->numpoints; + + // this may fragment the face if > MAXEDGES + FaceFromSuperverts (node, f, 0); +} + +/* +================== +EmitVertexes_r +================== +*/ +void EmitVertexes_r (node_t *node) +{ + int i; + face_t *f; + + if (node->planenum == PLANENUM_LEAF) + return; + + for (f=node->faces ; f ; f=f->next) + { + EmitFaceVertexes (node, f); + } + + for (i=0 ; i<2 ; i++) + EmitVertexes_r (node->children[i]); +} + + +#ifdef USE_HASHING +/* +========== +FindEdgeVerts + +Uses the hash tables to cut down to a small number +========== +*/ +void FindEdgeVerts (vec3_t v1, vec3_t v2) +{ + int x1, x2, y1, y2, t; + int x, y; + int vnum; + +#if 0 +{ + int i; + num_edge_verts = numvertexes-1; + for (i=0 ; i> 7; + y1 = (4096 + (int)(v1[1]+0.5)) >> 7; + x2 = (4096 + (int)(v2[0]+0.5)) >> 7; + y2 = (4096 + (int)(v2[1]+0.5)) >> 7; + + if (x1 > x2) + { + t = x1; + x1 = x2; + x2 = t; + } + if (y1 > y2) + { + t = y1; + y1 = y2; + y2 = t; + } +#if 0 + x1--; + x2++; + y1--; + y2++; + if (x1 < 0) + x1 = 0; + if (x2 >= HASH_SIZE) + x2 = HASH_SIZE; + if (y1 < 0) + y1 = 0; + if (y2 >= HASH_SIZE) + y2 = HASH_SIZE; +#endif + num_edge_verts = 0; + for (x=x1 ; x <= x2 ; x++) + { + for (y=y1 ; y <= y2 ; y++) + { + for (vnum=hashverts[y*HASH_SIZE+x] ; vnum ; vnum=vertexchain[vnum]) + { + edge_verts[num_edge_verts++] = vnum; + } + } + } +} + +#else +/* +========== +FindEdgeVerts + +Forced a dumb check of everything +========== +*/ +void FindEdgeVerts (vec3_t v1, vec3_t v2) +{ + int i; + + num_edge_verts = numvertexes-1; + for (i=0 ; i= end) + continue; // off an end + VectorMA (edge_start, dist, edge_dir, exact); + VectorSubtract (p, exact, off); + error = VectorLength (off); + + if (fabs(error) > OFF_EPSILON) + continue; // not on the edge + + // break the edge + c_tjunctions++; + TestEdge (start, dist, p1, j, k+1); + TestEdge (dist, end, j, p2, k+1); + return; + } + + // the edge p1 to p2 is now free of tjunctions + if (numsuperverts >= MAX_SUPERVERTS) + Error ("MAX_SUPERVERTS"); + superverts[numsuperverts] = p1; + numsuperverts++; +} + +/* +================== +FixFaceEdges + +================== +*/ +void FixFaceEdges (node_t *node, face_t *f) +{ + int p1, p2; + int i; + vec3_t e2; + vec_t len; + int count[MAX_SUPERVERTS], start[MAX_SUPERVERTS]; + int base; + + if (f->merged || f->split[0] || f->split[1]) + return; + + numsuperverts = 0; + + for (i=0 ; inumpoints ; i++) + { + p1 = f->vertexnums[i]; + p2 = f->vertexnums[(i+1)%f->numpoints]; + + VectorCopy (dvertexes[p1].point, edge_start); + VectorCopy (dvertexes[p2].point, e2); + + FindEdgeVerts (edge_start, e2); + + VectorSubtract (e2, edge_start, edge_dir); + len = VectorNormalize (edge_dir, edge_dir); + + start[i] = numsuperverts; + TestEdge (0, len, p1, p2, 0); + + count[i] = numsuperverts - start[i]; + } + + if (numsuperverts < 3) + { // entire face collapsed + f->numpoints = 0; + c_facecollapse++; + return; + } + + // we want to pick a vertex that doesn't have tjunctions + // on either side, which can cause artifacts on trifans, + // especially underwater + for (i=0 ; inumpoints ; i++) + { + if (count[i] == 1 && count[(i+f->numpoints-1)%f->numpoints] == 1) + break; + } + if (i == f->numpoints) + { + f->badstartvert = true; + c_badstartverts++; + base = 0; + } + else + { // rotate the vertex order + base = start[i]; + } + + // this may fragment the face if > MAXEDGES + FaceFromSuperverts (node, f, base); +} + +/* +================== +FixEdges_r +================== +*/ +void FixEdges_r (node_t *node) +{ + int i; + face_t *f; + + if (node->planenum == PLANENUM_LEAF) + return; + + for (f=node->faces ; f ; f=f->next) + FixFaceEdges (node, f); + + for (i=0 ; i<2 ; i++) + FixEdges_r (node->children[i]); +} + +/* +=========== +FixTjuncs + +=========== +*/ +void FixTjuncs (node_t *headnode) +{ + // snap and merge all vertexes + Sys_FPrintf( SYS_VRB, "---- snap verts ----\n"); + memset (hashverts, 0, sizeof(hashverts)); + c_totalverts = 0; + c_uniqueverts = 0; + c_faceoverflows = 0; + EmitVertexes_r (headnode); + Sys_FPrintf( SYS_VRB, "%i unique from %i\n", c_uniqueverts, c_totalverts); + + // break edges on tjunctions + Sys_FPrintf( SYS_VRB, "---- tjunc ----\n"); + c_tryedges = 0; + c_degenerate = 0; + c_facecollapse = 0; + c_tjunctions = 0; + if (!notjunc) + FixEdges_r (headnode); + Sys_FPrintf( SYS_VRB, "%5i edges degenerated\n", c_degenerate); + Sys_FPrintf( SYS_VRB, "%5i faces degenerated\n", c_facecollapse); + Sys_FPrintf( SYS_VRB, "%5i edges added by tjunctions\n", c_tjunctions); + Sys_FPrintf( SYS_VRB, "%5i faces added by tjunctions\n", c_faceoverflows); + Sys_FPrintf( SYS_VRB, "%5i bad start verts\n", c_badstartverts); +} + + +//======================================================== + +int c_faces; + +face_t *AllocFace (void) +{ + face_t *f; + + f = malloc(sizeof(*f)); + memset (f, 0, sizeof(*f)); + c_faces++; + + return f; +} + +face_t *NewFaceFromFace (face_t *f) +{ + face_t *newf; + + newf = AllocFace (); + *newf = *f; + newf->merged = NULL; + newf->split[0] = newf->split[1] = NULL; + newf->w = NULL; + return newf; +} + +void FreeFace (face_t *f) +{ + if (f->w) + FreeWinding (f->w); + free (f); + c_faces--; +} + +//======================================================== + +/* +================== +GetEdge + +Called by writebsp. +Don't allow four way edges +================== +*/ +int GetEdge2 (int v1, int v2, face_t *f) +{ + dedge_t *edge; + int i; + + c_tryedges++; + + if (!noshare) + { + for (i=firstmodeledge ; i < numedges ; i++) + { + edge = &dedges[i]; + if (v1 == edge->v[1] && v2 == edge->v[0] + && edgefaces[i][0]->contents == f->contents) + { + if (edgefaces[i][1]) + // Sys_Printf ("WARNING: multiple backward edge\n"); + continue; + edgefaces[i][1] = f; + return -i; + } + #if 0 + if (v1 == edge->v[0] && v2 == edge->v[1]) + { + Sys_Printf ("WARNING: multiple forward edge\n"); + return i; + } + #endif + } + } + +// emit an edge + if (numedges >= MAX_MAP_EDGES) + Error ("numedges == MAX_MAP_EDGES"); + edge = &dedges[numedges]; + numedges++; + edge->v[0] = v1; + edge->v[1] = v2; + edgefaces[numedges-1][0] = f; + + return numedges-1; +} + +/* +=========================================================================== + +FACE MERGING + +=========================================================================== +*/ + +#define CONTINUOUS_EPSILON 0.001 + +/* +============= +TryMergeWinding + +If two polygons share a common edge and the edges that meet at the +common points are both inside the other polygons, merge them + +Returns NULL if the faces couldn't be merged, or the new face. +The originals will NOT be freed. +============= +*/ +winding_t *TryMergeWinding (winding_t *f1, winding_t *f2, vec3_t planenormal) +{ + vec_t *p1, *p2, *p3, *p4, *back; + winding_t *newf; + int i, j, k, l; + vec3_t normal, delta; + vec_t dot; + qboolean keep1, keep2; + + + // + // find a common edge + // + p1 = p2 = NULL; // stop compiler warning + j = 0; // + + for (i=0 ; inumpoints ; i++) + { + p1 = f1->p[i]; + p2 = f1->p[(i+1)%f1->numpoints]; + for (j=0 ; jnumpoints ; j++) + { + p3 = f2->p[j]; + p4 = f2->p[(j+1)%f2->numpoints]; + for (k=0 ; k<3 ; k++) + { + if (fabs(p1[k] - p4[k]) > EQUAL_EPSILON) + break; + if (fabs(p2[k] - p3[k]) > EQUAL_EPSILON) + break; + } + if (k==3) + break; + } + if (j < f2->numpoints) + break; + } + + if (i == f1->numpoints) + return NULL; // no matching edges + + // + // check slope of connected lines + // if the slopes are colinear, the point can be removed + // + back = f1->p[(i+f1->numpoints-1)%f1->numpoints]; + VectorSubtract (p1, back, delta); + CrossProduct (planenormal, delta, normal); + VectorNormalize (normal, normal); + + back = f2->p[(j+2)%f2->numpoints]; + VectorSubtract (back, p1, delta); + dot = DotProduct (delta, normal); + if (dot > CONTINUOUS_EPSILON) + return NULL; // not a convex polygon + keep1 = (qboolean)(dot < -CONTINUOUS_EPSILON); + + back = f1->p[(i+2)%f1->numpoints]; + VectorSubtract (back, p2, delta); + CrossProduct (planenormal, delta, normal); + VectorNormalize (normal, normal); + + back = f2->p[(j+f2->numpoints-1)%f2->numpoints]; + VectorSubtract (back, p2, delta); + dot = DotProduct (delta, normal); + if (dot > CONTINUOUS_EPSILON) + return NULL; // not a convex polygon + keep2 = (qboolean)(dot < -CONTINUOUS_EPSILON); + + // + // build the new polygon + // + newf = AllocWinding (f1->numpoints + f2->numpoints); + + // copy first polygon + for (k=(i+1)%f1->numpoints ; k != i ; k=(k+1)%f1->numpoints) + { + if (k==(i+1)%f1->numpoints && !keep2) + continue; + + VectorCopy (f1->p[k], newf->p[newf->numpoints]); + newf->numpoints++; + } + + // copy second polygon + for (l= (j+1)%f2->numpoints ; l != j ; l=(l+1)%f2->numpoints) + { + if (l==(j+1)%f2->numpoints && !keep1) + continue; + VectorCopy (f2->p[l], newf->p[newf->numpoints]); + newf->numpoints++; + } + + return newf; +} + +/* +============= +TryMerge + +If two polygons share a common edge and the edges that meet at the +common points are both inside the other polygons, merge them + +Returns NULL if the faces couldn't be merged, or the new face. +The originals will NOT be freed. +============= +*/ +face_t *TryMerge (face_t *f1, face_t *f2, vec3_t planenormal) +{ + face_t *newf; + winding_t *nw; + + if (!f1->w || !f2->w) + return NULL; + if (f1->texinfo != f2->texinfo) + return NULL; + if (f1->planenum != f2->planenum) // on front and back sides + return NULL; + if (f1->contents != f2->contents) + return NULL; + + + nw = TryMergeWinding (f1->w, f2->w, planenormal); + if (!nw) + return NULL; + + c_merge++; + newf = NewFaceFromFace (f1); + newf->w = nw; + + f1->merged = newf; + f2->merged = newf; + + return newf; +} + +/* +=============== +MergeNodeFaces +=============== +*/ +void MergeNodeFaces (node_t *node) +{ + face_t *f1, *f2, *end; + face_t *merged; + plane_t *plane; + + plane = &mapplanes[node->planenum]; + merged = NULL; + + for (f1 = node->faces ; f1 ; f1 = f1->next) + { + if (f1->merged || f1->split[0] || f1->split[1]) + continue; + for (f2 = node->faces ; f2 != f1 ; f2=f2->next) + { + if (f2->merged || f2->split[0] || f2->split[1]) + continue; + merged = TryMerge (f1, f2, plane->normal); + if (!merged) + continue; + + // add merged to the end of the node face list + // so it will be checked against all the faces again + for (end = node->faces ; end->next ; end = end->next) + ; + merged->next = NULL; + end->next = merged; + break; + } + } +} + +//===================================================================== + +/* +=============== +SubdivideFace + +Chop up faces that are larger than we want in the surface cache +=============== +*/ +void SubdivideFace (node_t *node, face_t *f) +{ + float mins, maxs; + vec_t v; + int axis, i; + texinfo_t *tex; + vec3_t temp; + vec_t dist; + winding_t *w, *frontw, *backw; + + if (f->merged) + return; + +// special (non-surface cached) faces don't need subdivision + tex = &texinfo[f->texinfo]; + + if ( tex->flags & (SURF_WARP|SURF_SKY) ) + { + return; + } + + for (axis = 0 ; axis < 2 ; axis++) + { + while (1) + { + mins = 999999; + maxs = -999999; + + VectorCopy (tex->vecs[axis], temp); + w = f->w; + for (i=0 ; inumpoints ; i++) + { + v = DotProduct (w->p[i], temp); + if (v < mins) + mins = v; + if (v > maxs) + maxs = v; + } +#if 0 + if (maxs - mins <= 0) + Error ("zero extents"); +#endif + if (axis == 2) + { // allow double high walls + if (maxs - mins <= subdivide_size/* *2 */) + break; + } + else if (maxs - mins <= subdivide_size) + break; + + // split it + c_subdivide++; + + v = VectorNormalize (temp, temp); + + dist = (mins + subdivide_size - 16)/v; + + ClipWindingEpsilon (w, temp, dist, ON_EPSILON, &frontw, &backw); + if (!frontw || !backw) + Error ("SubdivideFace: didn't split the polygon"); + + f->split[0] = NewFaceFromFace (f); + f->split[0]->w = frontw; + f->split[0]->next = node->faces; + node->faces = f->split[0]; + + f->split[1] = NewFaceFromFace (f); + f->split[1]->w = backw; + f->split[1]->next = node->faces; + node->faces = f->split[1]; + + SubdivideFace (node, f->split[0]); + SubdivideFace (node, f->split[1]); + return; + } + } +} + +void SubdivideNodeFaces (node_t *node) +{ + face_t *f; + + for (f = node->faces ; f ; f=f->next) + { + SubdivideFace (node, f); + } +} + +//=========================================================================== + +int c_nodefaces; + + +/* +============ +FaceFromPortal + +============ +*/ +face_t *FaceFromPortal (portal_t *p, int pside) +{ + face_t *f; + side_t *side; + + side = p->side; + if (!side) + return NULL; // portal does not bridge different visible contents + + f = AllocFace (); + + f->texinfo = side->texinfo; + f->planenum = (side->planenum & ~1) | pside; + f->portal = p; + + if ( (p->nodes[pside]->contents & CONTENTS_WINDOW) + && VisibleContents(p->nodes[!pside]->contents^p->nodes[pside]->contents) == CONTENTS_WINDOW ) + return NULL; // don't show insides of windows + + if (pside) + { + f->w = ReverseWinding(p->winding); + f->contents = p->nodes[1]->contents; + } + else + { + f->w = CopyWinding(p->winding); + f->contents = p->nodes[0]->contents; + } + return f; +} + + +/* +=============== +MakeFaces_r + +If a portal will make a visible face, +mark the side that originally created it + + solid / empty : solid + solid / water : solid + water / empty : water + water / water : none +=============== +*/ +void MakeFaces_r (node_t *node) +{ + portal_t *p; + int s; + + // recurse down to leafs + if (node->planenum != PLANENUM_LEAF) + { + MakeFaces_r (node->children[0]); + MakeFaces_r (node->children[1]); + + // merge together all visible faces on the node + if (!nomerge) + MergeNodeFaces (node); + if (!nosubdiv) + SubdivideNodeFaces (node); + + return; + } + + // solid leafs never have visible faces + if (node->contents & CONTENTS_SOLID) + return; + + // see which portals are valid + for (p=node->portals ; p ; p = p->next[s]) + { + s = (p->nodes[1] == node); + + p->face[s] = FaceFromPortal (p, s); + if (p->face[s]) + { + c_nodefaces++; + p->face[s]->next = p->onnode->faces; + p->onnode->faces = p->face[s]; + } + } +} + +/* +============ +MakeFaces +============ +*/ +void MakeFaces (node_t *node) +{ + Sys_FPrintf( SYS_VRB, "--- MakeFaces ---\n"); + c_merge = 0; + c_subdivide = 0; + c_nodefaces = 0; + + MakeFaces_r (node); + + Sys_FPrintf( SYS_VRB, "%5i makefaces\n", c_nodefaces); + Sys_FPrintf( SYS_VRB, "%5i merged\n", c_merge); + Sys_FPrintf( SYS_VRB, "%5i subdivided\n", c_subdivide); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/flow.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/flow.c new file mode 100644 index 00000000..8bd8022a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/flow.c @@ -0,0 +1,787 @@ +/* +Copyright (C) 1999-2006 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 "qvis.h" + +/* + + each portal will have a list of all possible to see from first portal + + if (!thread->portalmightsee[portalnum]) + + portal mightsee + + for p2 = all other portals in leaf + get sperating planes + for all portals that might be seen by p2 + mark as unseen if not present in seperating plane + flood fill a new mightsee + save as passagemightsee + + + void CalcMightSee (leaf_t *leaf, +*/ + +int CountBits (byte *bits, int numbits) +{ + int i; + int c; + + c = 0; + for (i=0 ; i>3] & (1<<(i&7)) ) + c++; + + return c; +} + +int c_fullskip; +int c_portalskip, c_leafskip; +int c_vistest, c_mighttest; + +int c_chop, c_nochop; + +int active; + +void CheckStack (leaf_t *leaf, threaddata_t *thread) +{ + pstack_t *p, *p2; + + for (p=thread->pstack_head.next ; p ; p=p->next) + { +// printf ("="); + if (p->leaf == leaf) + Error ("CheckStack: leaf recursion"); + for (p2=thread->pstack_head.next ; p2 != p ; p2=p2->next) + if (p2->leaf == p->leaf) + Error ("CheckStack: late leaf recursion"); + } +// printf ("\n"); +} + + +winding_t *AllocStackWinding (pstack_t *stack) +{ + int i; + + for (i=0 ; i<3 ; i++) + { + if (stack->freewindings[i]) + { + stack->freewindings[i] = 0; + return &stack->windings[i]; + } + } + + Error ("AllocStackWinding: failed"); + + return NULL; +} + +void FreeStackWinding (winding_t *w, pstack_t *stack) +{ + int i; + + i = w - stack->windings; + + if (i<0 || i>2) + return; // not from local + + if (stack->freewindings[i]) + Error ("FreeStackWinding: allready free"); + stack->freewindings[i] = 1; +} + +/* +============== +Vis_ChopWinding + +============== +*/ +winding_t *Vis_ChopWinding (winding_t *in, pstack_t *stack, plane_t *split) +{ + vec_t dists[128]; + int sides[128]; + int counts[3]; + vec_t dot; + int i, j; + vec_t *p1, *p2; + vec3_t mid; + winding_t *neww; + + counts[0] = counts[1] = counts[2] = 0; + +// determine sides for each point + for (i=0 ; inumpoints ; i++) + { + dot = DotProduct (in->points[i], split->normal); + dot -= split->dist; + dists[i] = dot; + if (dot > ON_EPSILON) + sides[i] = SIDE_FRONT; + else if (dot < -ON_EPSILON) + sides[i] = SIDE_BACK; + else + { + sides[i] = SIDE_ON; + } + counts[sides[i]]++; + } + + if (!counts[1]) + return in; // completely on front side + + if (!counts[0]) + { + FreeStackWinding (in, stack); + return NULL; + } + + sides[i] = sides[0]; + dists[i] = dists[0]; + + neww = AllocStackWinding (stack); + + neww->numpoints = 0; + + for (i=0 ; inumpoints ; i++) + { + p1 = in->points[i]; + + if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING) + { + FreeStackWinding (neww, stack); + return in; // can't chop -- fall back to original + } + + if (sides[i] == SIDE_ON) + { + VectorCopy (p1, neww->points[neww->numpoints]); + neww->numpoints++; + continue; + } + + if (sides[i] == SIDE_FRONT) + { + VectorCopy (p1, neww->points[neww->numpoints]); + neww->numpoints++; + } + + if (sides[i+1] == SIDE_ON || sides[i+1] == sides[i]) + continue; + + if (neww->numpoints == MAX_POINTS_ON_FIXED_WINDING) + { + FreeStackWinding (neww, stack); + return in; // can't chop -- fall back to original + } + + // generate a split point + p2 = in->points[(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 (split->normal[j] == 1) + mid[j] = split->dist; + else if (split->normal[j] == -1) + mid[j] = -split->dist; + else + mid[j] = p1[j] + dot*(p2[j]-p1[j]); + } + + VectorCopy (mid, neww->points[neww->numpoints]); + neww->numpoints++; + } + +// free the original winding + FreeStackWinding (in, stack); + + return neww; +} + + +/* +============== +ClipToSeperators + +Source, pass, and target are an ordering of portals. + +Generates seperating planes canidates by taking two points from source and one +point from pass, and clips target by them. + +If target is totally clipped away, that portal can not be seen through. + +Normal clip keeps target on the same side as pass, which is correct if the +order goes source, pass, target. If the order goes pass, source, target then +flipclip should be set. +============== +*/ +winding_t *ClipToSeperators (winding_t *source, winding_t *pass, winding_t *target, qboolean flipclip, pstack_t *stack) +{ + int i, j, k, l; + plane_t plane; + vec3_t v1, v2; + float d; + vec_t length; + int counts[3]; + qboolean fliptest; + +// check all combinations + for (i=0 ; inumpoints ; i++) + { + l = (i+1)%source->numpoints; + VectorSubtract (source->points[l] , source->points[i], v1); + + // fing a vertex of pass that makes a plane that puts all of the + // vertexes of pass on the front side and all of the vertexes of + // source on the back side + for (j=0 ; jnumpoints ; j++) + { + VectorSubtract (pass->points[j], source->points[i], v2); + + plane.normal[0] = v1[1]*v2[2] - v1[2]*v2[1]; + plane.normal[1] = v1[2]*v2[0] - v1[0]*v2[2]; + plane.normal[2] = v1[0]*v2[1] - v1[1]*v2[0]; + + // if points don't make a valid plane, skip it + + length = plane.normal[0] * plane.normal[0] + + plane.normal[1] * plane.normal[1] + + plane.normal[2] * plane.normal[2]; + + if (length < ON_EPSILON) + continue; + + length = 1/sqrt(length); + + plane.normal[0] *= length; + plane.normal[1] *= length; + plane.normal[2] *= length; + + plane.dist = DotProduct (pass->points[j], plane.normal); + + // + // find out which side of the generated seperating plane has the + // source portal + // +#if 1 + fliptest = false; + for (k=0 ; knumpoints ; k++) + { + if (k == i || k == l) + continue; + d = DotProduct (source->points[k], plane.normal) - plane.dist; + if (d < -ON_EPSILON) + { // source is on the negative side, so we want all + // pass and target on the positive side + fliptest = false; + break; + } + else if (d > ON_EPSILON) + { // source is on the positive side, so we want all + // pass and target on the negative side + fliptest = true; + break; + } + } + if (k == source->numpoints) + continue; // planar with source portal +#else + fliptest = flipclip; +#endif + // + // flip the normal if the source portal is backwards + // + if (fliptest) + { + VectorSubtract (vec3_origin, plane.normal, plane.normal); + plane.dist = -plane.dist; + } +#if 1 + // + // if all of the pass portal points are now on the positive side, + // this is the seperating plane + // + counts[0] = counts[1] = counts[2] = 0; + for (k=0 ; knumpoints ; k++) + { + if (k==j) + continue; + d = DotProduct (pass->points[k], plane.normal) - plane.dist; + if (d < -ON_EPSILON) + break; + else if (d > ON_EPSILON) + counts[0]++; + else + counts[2]++; + } + if (k != pass->numpoints) + continue; // points on negative side, not a seperating plane + + if (!counts[0]) + continue; // planar with seperating plane +#else + k = (j+1)%pass->numpoints; + d = DotProduct (pass->points[k], plane.normal) - plane.dist; + if (d < -ON_EPSILON) + continue; + k = (j+pass->numpoints-1)%pass->numpoints; + d = DotProduct (pass->points[k], plane.normal) - plane.dist; + if (d < -ON_EPSILON) + continue; +#endif + // + // flip the normal if we want the back side + // + if (flipclip) + { + VectorSubtract (vec3_origin, plane.normal, plane.normal); + plane.dist = -plane.dist; + } + + // + // clip target by the seperating plane + // + target = Vis_ChopWinding (target, stack, &plane); + if (!target) + return NULL; // target is not visible + } + } + + return target; +} + + + +/* +================== +RecursiveLeafFlow + +Flood fill through the leafs +If src_portal is NULL, this is the originating leaf +================== +*/ +void RecursiveLeafFlow (int leafnum, threaddata_t *thread, pstack_t *prevstack) +{ + pstack_t stack; + portal_t *p; + plane_t backplane; + leaf_t *leaf; + int i, j; + long *test, *might, *vis, more; + int pnum; + + thread->c_chains++; + + leaf = &leafs[leafnum]; +// CheckStack (leaf, thread); + + prevstack->next = &stack; + + stack.next = NULL; + stack.leaf = leaf; + stack.portal = NULL; + + might = (long *)stack.mightsee; + vis = (long *)thread->base->portalvis; + +// check all portals for flowing into other leafs + for (i=0 ; inumportals ; i++) + { + p = leaf->portals[i]; + pnum = p - portals; + + if ( ! (prevstack->mightsee[pnum >> 3] & (1<<(pnum&7)) ) ) + { + continue; // can't possibly see it + } + + // if the portal can't see anything we haven't allready seen, skip it + if (p->status == stat_done) + { + test = (long *)p->portalvis; + } + else + { + test = (long *)p->portalflood; + } + + more = 0; + for (j=0 ; jmightsee)[j] & test[j]; + more |= (might[j] & ~vis[j]); + } + + if (!more && + (thread->base->portalvis[pnum>>3] & (1<<(pnum&7))) ) + { // can't see anything new + continue; + } + + // get plane of portal, point normal into the neighbor leaf + stack.portalplane = p->plane; + VectorSubtract (vec3_origin, p->plane.normal, backplane.normal); + backplane.dist = -p->plane.dist; + +// c_portalcheck++; + + stack.portal = p; + stack.next = NULL; + stack.freewindings[0] = 1; + stack.freewindings[1] = 1; + stack.freewindings[2] = 1; + +#if 1 +{ +float d; + + d = DotProduct (p->origin, thread->pstack_head.portalplane.normal); + d -= thread->pstack_head.portalplane.dist; + if (d < -p->radius) + { + continue; + } + else if (d > p->radius) + { + stack.pass = p->winding; + } + else + { + stack.pass = Vis_ChopWinding (p->winding, &stack, &thread->pstack_head.portalplane); + if (!stack.pass) + continue; + } +} +#else + stack.pass = Vis_ChopWinding (p->winding, &stack, &thread->pstack_head.portalplane); + if (!stack.pass) + continue; +#endif + + +#if 1 +{ +float d; + + d = DotProduct (thread->base->origin, p->plane.normal); + d -= p->plane.dist; + if (d > p->radius) + { + continue; + } + else if (d < -p->radius) + { + stack.source = prevstack->source; + } + else + { + stack.source = Vis_ChopWinding (prevstack->source, &stack, &backplane); + if (!stack.source) + continue; + } +} +#else + stack.source = Vis_ChopWinding (prevstack->source, &stack, &backplane); + if (!stack.source) + continue; +#endif + + if (!prevstack->pass) + { // the second leaf can only be blocked if coplanar + + // mark the portal as visible + thread->base->portalvis[pnum>>3] |= (1<<(pnum&7)); + + RecursiveLeafFlow (p->leaf, thread, &stack); + continue; + } + + stack.pass = ClipToSeperators (stack.source, prevstack->pass, stack.pass, false, &stack); + if (!stack.pass) + continue; + + stack.pass = ClipToSeperators (prevstack->pass, stack.source, stack.pass, true, &stack); + if (!stack.pass) + continue; + + // mark the portal as visible + thread->base->portalvis[pnum>>3] |= (1<<(pnum&7)); + + // flow through it for real + RecursiveLeafFlow (p->leaf, thread, &stack); + } +} + + +/* +=============== +PortalFlow + +generates the portalvis bit vector +=============== +*/ +void PortalFlow (int portalnum) +{ + threaddata_t data; + int i; + portal_t *p; + int c_might, c_can; + + p = sorted_portals[portalnum]; + p->status = stat_working; + + c_might = CountBits (p->portalflood, numportals*2); + + memset (&data, 0, sizeof(data)); + data.base = p; + + data.pstack_head.portal = p; + data.pstack_head.source = p->winding; + data.pstack_head.portalplane = p->plane; + for (i=0 ; iportalflood)[i]; + RecursiveLeafFlow (p->leaf, &data, &data.pstack_head); + + p->status = stat_done; + + c_can = CountBits (p->portalvis, numportals*2); + + Sys_FPrintf ( SYS_VRB, "portal:%4i mightsee:%4i cansee:%4i (%i chains)\n", + (int)(p - portals), c_might, c_can, data.c_chains); +} + + +/* +=============================================================================== + +This is a rough first-order aproximation that is used to trivially reject some +of the final calculations. + + +Calculates portalfront and portalflood bit vectors + +thinking about: + +typedef struct passage_s +{ + struct passage_s *next; + struct portal_s *to; + stryct sep_s *seperators; + byte *mightsee; +} passage_t; + +typedef struct portal_s +{ + struct passage_s *passages; + int leaf; // leaf portal faces into +} portal_s; + +leaf = portal->leaf +clear +for all portals + + +calc portal visibility + clear bit vector + for all passages + passage visibility + + +for a portal to be visible to a passage, it must be on the front of +all seperating planes, and both portals must be behind the mew portal + +=============================================================================== +*/ + +int c_flood, c_vis; + + +/* +================== +SimpleFlood + +================== +*/ +void SimpleFlood (portal_t *srcportal, int leafnum) +{ + int i; + leaf_t *leaf; + portal_t *p; + int pnum; + + leaf = &leafs[leafnum]; + + for (i=0 ; inumportals ; i++) + { + p = leaf->portals[i]; + pnum = p - portals; + if ( ! (srcportal->portalfront[pnum>>3] & (1<<(pnum&7)) ) ) + continue; + + if (srcportal->portalflood[pnum>>3] & (1<<(pnum&7)) ) + continue; + + srcportal->portalflood[pnum>>3] |= (1<<(pnum&7)); + + SimpleFlood (srcportal, p->leaf); + } +} + +/* +============== +BasePortalVis +============== +*/ +void BasePortalVis (int portalnum) +{ + int j, k; + portal_t *tp, *p; + float d; + winding_t *w; + + p = portals+portalnum; + + p->portalfront = malloc (portalbytes); + memset (p->portalfront, 0, portalbytes); + + p->portalflood = malloc (portalbytes); + memset (p->portalflood, 0, portalbytes); + + p->portalvis = malloc (portalbytes); + memset (p->portalvis, 0, portalbytes); + + for (j=0, tp = portals ; jwinding; + for (k=0 ; knumpoints ; k++) + { + d = DotProduct (w->points[k], p->plane.normal) + - p->plane.dist; + if (d > ON_EPSILON) + break; + } + if (k == w->numpoints) + continue; // no points on front + + w = p->winding; + for (k=0 ; knumpoints ; k++) + { + d = DotProduct (w->points[k], tp->plane.normal) + - tp->plane.dist; + if (d < -ON_EPSILON) + break; + } + if (k == w->numpoints) + continue; // no points on front + + p->portalfront[j>>3] |= (1<<(j&7)); + } + + SimpleFlood (p, p->leaf); + + p->nummightsee = CountBits (p->portalflood, numportals*2); +// printf ("portal %i: %i mightsee\n", portalnum, p->nummightsee); + c_flood += p->nummightsee; +} + + + + + +/* +=============================================================================== + +This is a second order aproximation + +Calculates portalvis bit vector + +WAAAAAAY too slow. + +=============================================================================== +*/ + +/* +================== +RecursiveLeafBitFlow + +================== +*/ +void RecursiveLeafBitFlow (int leafnum, byte *mightsee, byte *cansee) +{ + portal_t *p; + leaf_t *leaf; + int i, j; + long more; + int pnum; + byte newmight[MAX_PORTALS/8]; + + leaf = &leafs[leafnum]; + +// check all portals for flowing into other leafs + for (i=0 ; inumportals ; i++) + { + p = leaf->portals[i]; + pnum = p - portals; + + // if some previous portal can't see it, skip + if (! (mightsee[pnum>>3] & (1<<(pnum&7)) ) ) + continue; + + // if this portal can see some portals we mightsee, recurse + more = 0; + for (j=0 ; jportalflood)[j]; + more |= ((long *)newmight)[j] & ~((long *)cansee)[j]; + } + + if (!more) + continue; // can't see anything new + + cansee[pnum>>3] |= (1<<(pnum&7)); + + RecursiveLeafBitFlow (p->leaf, newmight, cansee); + } +} + +/* +============== +BetterPortalVis +============== +*/ +void BetterPortalVis (int portalnum) +{ + portal_t *p; + + p = portals+portalnum; + + RecursiveLeafBitFlow (p->leaf, p->portalflood, p->portalvis); + + // build leaf vis information + p->nummightsee = CountBits (p->portalvis, numportals*2); + c_vis += p->nummightsee; +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/gldraw.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/gldraw.c new file mode 100644 index 00000000..6e249c31 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/gldraw.c @@ -0,0 +1,231 @@ +/* +Copyright (C) 1999-2006 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 +#include +#include + +#include "qbsp.h" + +// can't use the glvertex3fv functions, because the vec3_t fields +// could be either floats or doubles, depending on DOUBLEVEC_T + +qboolean drawflag; +vec3_t draw_mins, draw_maxs; + + +#define WIN_SIZE 512 + +void InitWindow (void) +{ + auxInitDisplayMode (AUX_SINGLE | AUX_RGB); + auxInitPosition (0, 0, WIN_SIZE, WIN_SIZE); + auxInitWindow ("qcsg"); +} + +void Draw_ClearWindow (void) +{ + static int init; + int w, h, g; + vec_t mx, my; + + if (!drawflag) + return; + + if (!init) + { + init = true; + InitWindow (); + } + + glClearColor (1,0.8,0.8,0); + glClear (GL_COLOR_BUFFER_BIT); + + w = (draw_maxs[0] - draw_mins[0]); + h = (draw_maxs[1] - draw_mins[1]); + + mx = draw_mins[0] + w/2; + my = draw_mins[1] + h/2; + + g = w > h ? w : h; + + glLoadIdentity (); + gluPerspective (90, 1, 2, 16384); + gluLookAt (mx, my, draw_maxs[2] + g/2, mx , my, draw_maxs[2], 0, 1, 0); + + glColor3f (0,0,0); +// glPolygonMode (GL_FRONT_AND_BACK, GL_LINE); + glPolygonMode (GL_FRONT_AND_BACK, GL_FILL); + glDisable (GL_DEPTH_TEST); + glEnable (GL_BLEND); + glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + +#if 0 + glColor4f (1,0,0,0.5); + glBegin (GL_POLYGON); + + glVertex3f (0, 500, 0); + glVertex3f (0, 900, 0); + glVertex3f (0, 900, 100); + glVertex3f (0, 500, 100); + + glEnd (); +#endif + + glFlush (); + +} + +void Draw_SetRed (void) +{ + if (!drawflag) + return; + + glColor3f (1,0,0); +} + +void Draw_SetGrey (void) +{ + if (!drawflag) + return; + + glColor3f (0.5,0.5,0.5); +} + +void Draw_SetBlack (void) +{ + if (!drawflag) + return; + + glColor3f (0,0,0); +} + +void DrawWinding (winding_t *w) +{ + int i; + + if (!drawflag) + return; + + glColor4f (0,0,0,0.5); + glBegin (GL_LINE_LOOP); + for (i=0 ; inumpoints ; i++) + glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); + glEnd (); + + glColor4f (0,1,0,0.3); + glBegin (GL_POLYGON); + for (i=0 ; inumpoints ; i++) + glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); + glEnd (); + + glFlush (); +} + +void DrawAuxWinding (winding_t *w) +{ + int i; + + if (!drawflag) + return; + + glColor4f (0,0,0,0.5); + glBegin (GL_LINE_LOOP); + for (i=0 ; inumpoints ; i++) + glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); + glEnd (); + + glColor4f (1,0,0,0.3); + glBegin (GL_POLYGON); + for (i=0 ; inumpoints ; i++) + glVertex3f (w->p[i][0],w->p[i][1],w->p[i][2] ); + glEnd (); + + glFlush (); +} + +//============================================================ + +#define GLSERV_PORT 25001 + +qboolean wins_init; +int draw_socket; + +void GLS_BeginScene (void) +{ + WSADATA winsockdata; + WORD wVersionRequested; + struct sockaddr_in address; + int r; + + if (!wins_init) + { + wins_init = true; + + wVersionRequested = MAKEWORD(1, 1); + + r = WSAStartup (MAKEWORD(1, 1), &winsockdata); + + if (r) + Error ("Winsock initialization failed."); + + } + + // connect a socket to the server + + draw_socket = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP); + if (draw_socket == -1) + Error ("draw_socket failed"); + + address.sin_family = AF_INET; + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + address.sin_port = GLSERV_PORT; + r = connect (draw_socket, (struct sockaddr *)&address, sizeof(address)); + if (r == -1) + { + closesocket (draw_socket); + draw_socket = 0; + } +} + +void GLS_Winding (winding_t *w, int code) +{ + byte buf[1024]; + int i, j; + + if (!draw_socket) + return; + + ((int *)buf)[0] = w->numpoints; + ((int *)buf)[1] = code; + for (i=0 ; inumpoints ; i++) + for (j=0 ; j<3 ; j++) + ((float *)buf)[2+i*3+j] = w->p[i][j]; + + send (draw_socket, buf, w->numpoints*12+8, 0); +} + +void GLS_EndScene (void) +{ + closesocket (draw_socket); + draw_socket = 0; +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/glfile.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/glfile.c new file mode 100644 index 00000000..6e98bd0f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/glfile.c @@ -0,0 +1,148 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +int c_glfaces; + +int PortalVisibleSides (portal_t *p) +{ + int fcon, bcon; + + if (!p->onnode) + return 0; // outside + + fcon = p->nodes[0]->contents; + bcon = p->nodes[1]->contents; + + // same contents never create a face + if (fcon == bcon) + return 0; + + // FIXME: is this correct now? + if (!fcon) + return 1; + if (!bcon) + return 2; + return 0; +} + +void OutputWinding (winding_t *w, FILE *glview) +{ + static int level = 128; + vec_t light; + int i; + + fprintf (glview, "%i\n", w->numpoints); + level+=28; + light = (level&255)/255.0; + for (i=0 ; inumpoints ; i++) + { + fprintf (glview, "%6.3f %6.3f %6.3f %6.3f %6.3f %6.3f\n", + w->p[i][0], + w->p[i][1], + w->p[i][2], + light, + light, + light); + } + fprintf (glview, "\n"); +} + +/* +============= +OutputPortal +============= +*/ +void OutputPortal (portal_t *p, FILE *glview) +{ + winding_t *w; + int sides; + + sides = PortalVisibleSides (p); + if (!sides) + return; + + c_glfaces++; + + w = p->winding; + + if (sides == 2) // back side + w = ReverseWinding (w); + + OutputWinding (w, glview); + + if (sides == 2) + FreeWinding(w); +} + +/* +============= +WriteGLView_r +============= +*/ +void WriteGLView_r (node_t *node, FILE *glview) +{ + portal_t *p, *nextp; + + if (node->planenum != PLANENUM_LEAF) + { + WriteGLView_r (node->children[0], glview); + WriteGLView_r (node->children[1], glview); + return; + } + + // write all the portals + for (p=node->portals ; p ; p=nextp) + { + if (p->nodes[0] == node) + { + OutputPortal (p, glview); + nextp = p->next[0]; + } + else + nextp = p->next[1]; + } +} + +/* +============= +WriteGLView +============= +*/ +void WriteGLView (tree_t *tree, char *source) +{ + char name[1024]; + FILE *glview; + + c_glfaces = 0; + sprintf (name, "%s%s.gl",outbase, source); + Sys_Printf ("Writing %s\n", name); + + glview = fopen (name, "w"); + if (!glview) + Error ("Couldn't open %s", name); + WriteGLView_r (tree->headnode, glview); + fclose (glview); + + Sys_Printf ("%5i c_glfaces\n", c_glfaces); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/leakfile.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/leakfile.c new file mode 100644 index 00000000..8753eec5 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/leakfile.c @@ -0,0 +1,180 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +/* +============================================================================== + +LEAF FILE GENERATION + +Save out name.line for qe3 to read +============================================================================== +*/ + + +/* +============= +LeakFile + +Finds the shortest possible chain of portals +that leads from the outside leaf to a specifically +occupied leaf +============= +*/ + +/* +void LeakFile (tree_t *tree) +{ + vec3_t mid; + FILE *linefile; + char filename[1024]; + node_t *node; + int count; + + if (!tree->outside_node.occupied) + return; + + Sys_Printf ("--- LeakFile ---\n"); + + // + // write the points to the file + // + sprintf (filename, "%s.lin", source); + linefile = fopen (filename, "w"); + if (!linefile) + Error ("Couldn't open %s\n", filename); + + count = 0; + node = &tree->outside_node; + while (node->occupied > 1) + { + int next; + portal_t *p, *nextportal; + node_t *nextnode; + int s; + + // find the best portal exit + next = node->occupied; + for (p=node->portals ; p ; p = p->next[!s]) + { + s = (p->nodes[0] == node); + if (p->nodes[s]->occupied + && p->nodes[s]->occupied < next) + { + nextportal = p; + nextnode = p->nodes[s]; + next = nextnode->occupied; + } + } + node = nextnode; + WindingCenter (nextportal->winding, mid); + fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); + count++; + } + // add the occupant center + GetVectorForKey (node->occupant, "origin", mid); + + fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); + Sys_Printf ("%5i point linefile\n", count+1); + + fclose (linefile); +} +*/ + +/* +============= +LeakFile + +Finds the shortest possible chain of portals +that leads from the outside leaf to a specifically +occupied leaf + +TTimo: builds a polyline xml node +============= +*/ +xmlNodePtr LeakFile (tree_t *tree) +{ + vec3_t mid; + FILE *linefile; + char filename[1024]; + node_t *node; + int count; + xmlNodePtr xml_node, point; + + if (!tree->outside_node.occupied) + return NULL; + + Sys_FPrintf (SYS_VRB,"--- LeakFile ---\n"); + + // + // write the points to the file + // + sprintf (filename, "%s.lin", source); + linefile = fopen (filename, "w"); + if (!linefile) + Error ("Couldn't open %s\n", filename); + + xml_node = xmlNewNode (NULL, "polyline"); + + count = 0; + node = &tree->outside_node; + while (node->occupied > 1) + { + int next; + portal_t *p, *nextportal; + node_t *nextnode; + int s; + + // find the best portal exit + next = node->occupied; + for (p=node->portals ; p ; p = p->next[!s]) + { + s = (p->nodes[0] == node); + if (p->nodes[s]->occupied + && p->nodes[s]->occupied < next) + { + nextportal = p; + nextnode = p->nodes[s]; + next = nextnode->occupied; + } + } + node = nextnode; + WindingCenter (nextportal->winding, mid); + fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); + point = xml_NodeForVec(mid); + xmlAddChild(xml_node, point); + count++; + } + // add the occupant center + GetVectorForKey (node->occupant, "origin", mid); + + fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); + point = xml_NodeForVec(mid); + xmlAddChild(xml_node, point); + Sys_FPrintf( SYS_VRB, "%9d point linefile\n", count+1); + + fclose (linefile); + + return xml_node; +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/lightmap.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/lightmap.c new file mode 100644 index 00000000..8a9580b7 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/lightmap.c @@ -0,0 +1,1315 @@ +/* +Copyright (C) 1999-2006 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 "qrad.h" + +#define MAX_LSTYLES 256 + +typedef struct +{ + dface_t *faces[2]; + qboolean coplanar; +} edgeshare_t; + +edgeshare_t edgeshare[MAX_MAP_EDGES]; + +int facelinks[MAX_MAP_FACES]; +int planelinks[2][MAX_MAP_PLANES]; + +/* +============ +LinkPlaneFaces +============ +*/ +void LinkPlaneFaces (void) +{ + int i; + dface_t *f; + + f = dfaces; + for (i=0 ; iside][f->planenum]; + planelinks[f->side][f->planenum] = i; + } +} + +/* +============ +PairEdges +============ +*/ +void PairEdges (void) +{ + int i, j, k; + dface_t *f; + edgeshare_t *e; + + f = dfaces; + for (i=0 ; inumedges ; j++) + { + k = dsurfedges[f->firstedge + j]; + if (k < 0) + { + e = &edgeshare[-k]; + e->faces[1] = f; + } + else + { + e = &edgeshare[k]; + e->faces[0] = f; + } + + if (e->faces[0] && e->faces[1]) + { + // determine if coplanar + if (e->faces[0]->planenum == e->faces[1]->planenum) + e->coplanar = true; + } + } + } +} + +/* +================================================================= + + POINT TRIANGULATION + +================================================================= +*/ + +typedef struct triedge_s +{ + int p0, p1; + vec3_t normal; + vec_t dist; + struct triangle_s *tri; +} triedge_t; + +typedef struct triangle_s +{ + triedge_t *edges[3]; +} triangle_t; + +#define MAX_TRI_POINTS 1024 +#define MAX_TRI_EDGES (MAX_TRI_POINTS*6) +#define MAX_TRI_TRIS (MAX_TRI_POINTS*2) + +typedef struct +{ + int numpoints; + int numedges; + int numtris; + dplane_t *plane; + triedge_t *edgematrix[MAX_TRI_POINTS][MAX_TRI_POINTS]; + patch_t *points[MAX_TRI_POINTS]; + triedge_t edges[MAX_TRI_EDGES]; + triangle_t tris[MAX_TRI_TRIS]; +} triangulation_t; + +/* +=============== +AllocTriangulation +=============== +*/ +triangulation_t *AllocTriangulation (dplane_t *plane) +{ + triangulation_t *t; + + t = malloc(sizeof(triangulation_t)); + t->numpoints = 0; + t->numedges = 0; + t->numtris = 0; + + t->plane = plane; + +// memset (t->edgematrix, 0, sizeof(t->edgematrix)); + + return t; +} + +/* +=============== +FreeTriangulation +=============== +*/ +void FreeTriangulation (triangulation_t *tr) +{ + free (tr); +} + + +triedge_t *FindEdge (triangulation_t *trian, int p0, int p1) +{ + triedge_t *e, *be; + vec3_t v1; + vec3_t normal; + vec_t dist; + + if (trian->edgematrix[p0][p1]) + return trian->edgematrix[p0][p1]; + + if (trian->numedges > MAX_TRI_EDGES-2) + Error ("trian->numedges > MAX_TRI_EDGES-2"); + + VectorSubtract (trian->points[p1]->origin, trian->points[p0]->origin, v1); + VectorNormalize (v1, v1); + CrossProduct (v1, trian->plane->normal, normal); + dist = DotProduct (trian->points[p0]->origin, normal); + + e = &trian->edges[trian->numedges]; + e->p0 = p0; + e->p1 = p1; + e->tri = NULL; + VectorCopy (normal, e->normal); + e->dist = dist; + trian->numedges++; + trian->edgematrix[p0][p1] = e; + + be = &trian->edges[trian->numedges]; + be->p0 = p1; + be->p1 = p0; + be->tri = NULL; + VectorSubtract (vec3_origin, normal, be->normal); + be->dist = -dist; + trian->numedges++; + trian->edgematrix[p1][p0] = be; + + return e; +} + +triangle_t *AllocTriangle (triangulation_t *trian) +{ + triangle_t *t; + + if (trian->numtris >= MAX_TRI_TRIS) + Error ("trian->numtris >= MAX_TRI_TRIS"); + + t = &trian->tris[trian->numtris]; + trian->numtris++; + + return t; +} + +/* +============ +TriEdge_r +============ +*/ +void TriEdge_r (triangulation_t *trian, triedge_t *e) +{ + int i, bestp; + vec3_t v1, v2; + vec_t *p0, *p1, *p; + vec_t best, ang; + triangle_t *nt; + + if (e->tri) + return; // allready connected by someone + + // find the point with the best angle + p0 = trian->points[e->p0]->origin; + p1 = trian->points[e->p1]->origin; + best = 1.1; + for (i=0 ; i< trian->numpoints ; i++) + { + p = trian->points[i]->origin; + // a 0 dist will form a degenerate triangle + if (DotProduct(p, e->normal) - e->dist < 0) + continue; // behind edge + VectorSubtract (p0, p, v1); + VectorSubtract (p1, p, v2); + if (!VectorNormalize (v1,v1)) + continue; + if (!VectorNormalize (v2,v2)) + continue; + ang = DotProduct (v1, v2); + if (ang < best) + { + best = ang; + bestp = i; + } + } + if (best >= 1) + return; // edge doesn't match anything + + // make a new triangle + nt = AllocTriangle (trian); + nt->edges[0] = e; + nt->edges[1] = FindEdge (trian, e->p1, bestp); + nt->edges[2] = FindEdge (trian, bestp, e->p0); + for (i=0 ; i<3 ; i++) + nt->edges[i]->tri = nt; + TriEdge_r (trian, FindEdge (trian, bestp, e->p1)); + TriEdge_r (trian, FindEdge (trian, e->p0, bestp)); +} + +/* +============ +TriangulatePoints +============ +*/ +void TriangulatePoints (triangulation_t *trian) +{ + vec_t d, bestd; + vec3_t v1; + int bp1, bp2, i, j; + vec_t *p1, *p2; + triedge_t *e, *e2; + + if (trian->numpoints < 2) + return; + + // find the two closest points + bestd = 9999; + for (i=0 ; inumpoints ; i++) + { + p1 = trian->points[i]->origin; + for (j=i+1 ; jnumpoints ; j++) + { + p2 = trian->points[j]->origin; + VectorSubtract (p2, p1, v1); + d = VectorLength (v1); + if (d < bestd) + { + bestd = d; + bp1 = i; + bp2 = j; + } + } + } + + e = FindEdge (trian, bp1, bp2); + e2 = FindEdge (trian, bp2, bp1); + TriEdge_r (trian, e); + TriEdge_r (trian, e2); +} + +/* +=============== +AddPointToTriangulation +=============== +*/ +void AddPointToTriangulation (patch_t *patch, triangulation_t *trian) +{ + int pnum; + + pnum = trian->numpoints; + if (pnum == MAX_TRI_POINTS) + Error ("trian->numpoints == MAX_TRI_POINTS"); + trian->points[pnum] = patch; + trian->numpoints++; +} + +/* +=============== +LerpTriangle +=============== +*/ +void LerpTriangle (triangulation_t *trian, triangle_t *t, vec3_t point, vec3_t color) +{ + patch_t *p1, *p2, *p3; + vec3_t base, d1, d2; + float x, y, x1, y1, x2, y2; + + p1 = trian->points[t->edges[0]->p0]; + p2 = trian->points[t->edges[1]->p0]; + p3 = trian->points[t->edges[2]->p0]; + + VectorCopy (p1->totallight, base); + VectorSubtract (p2->totallight, base, d1); + VectorSubtract (p3->totallight, base, d2); + + x = DotProduct (point, t->edges[0]->normal) - t->edges[0]->dist; + y = DotProduct (point, t->edges[2]->normal) - t->edges[2]->dist; + + x1 = 0; + y1 = DotProduct (p2->origin, t->edges[2]->normal) - t->edges[2]->dist; + + x2 = DotProduct (p3->origin, t->edges[0]->normal) - t->edges[0]->dist; + y2 = 0; + + if (fabs(y1)edges[i]; + d = DotProduct (e->normal, point) - e->dist; + if (d < 0) + return false; // not inside + } + + return true; +} + +/* +=============== +SampleTriangulation +=============== +*/ +void SampleTriangulation (vec3_t point, triangulation_t *trian, vec3_t color) +{ + triangle_t *t; + triedge_t *e; + vec_t d, best; + patch_t *p0, *p1; + vec3_t v1, v2; + int i, j; + + if (trian->numpoints == 0) + { + VectorClear (color); + return; + } + if (trian->numpoints == 1) + { + VectorCopy (trian->points[0]->totallight, color); + return; + } + + // search for triangles + for (t = trian->tris, j=0 ; j < trian->numtris ; t++, j++) + { + if (!PointInTriangle (point, t)) + continue; + + // this is it + LerpTriangle (trian, t, point, color); + return; + } + + // search for exterior edge + for (e=trian->edges, j=0 ; j< trian->numedges ; e++, j++) + { + if (e->tri) + continue; // not an exterior edge + + d = DotProduct (point, e->normal) - e->dist; + if (d < 0) + continue; // not in front of edge + + p0 = trian->points[e->p0]; + p1 = trian->points[e->p1]; + + VectorSubtract (p1->origin, p0->origin, v1); + VectorNormalize (v1, v1); + VectorSubtract (point, p0->origin, v2); + d = DotProduct (v2, v1); + if (d < 0) + continue; + if (d > 1) + continue; + for (i=0 ; i<3 ; i++) + color[i] = p0->totallight[i] + d * (p1->totallight[i] - p0->totallight[i]); + return; + } + + // search for nearest point + best = 99999; + p1 = NULL; + for (j=0 ; jnumpoints ; j++) + { + p0 = trian->points[j]; + VectorSubtract (point, p0->origin, v1); + d = VectorLength (v1); + if (d < best) + { + best = d; + p1 = p0; + } + } + + if (!p1) + Error ("SampleTriangulation: no points"); + + VectorCopy (p1->totallight, color); +} + +/* +================================================================= + + LIGHTMAP SAMPLE GENERATION + +================================================================= +*/ + + +#define SINGLEMAP (64*64*4) + +typedef struct +{ + vec_t facedist; + vec3_t facenormal; + + int numsurfpt; + vec3_t surfpt[SINGLEMAP]; + + vec3_t modelorg; // for origined bmodels + + vec3_t texorg; + vec3_t worldtotex[2]; // s = (world - texorg) . worldtotex[0] + vec3_t textoworld[2]; // world = texorg + s * textoworld[0] + + vec_t exactmins[2], exactmaxs[2]; + + int texmins[2], texsize[2]; + int surfnum; + dface_t *face; +} lightinfo_t; + + +/* +================ +CalcFaceExtents + +Fills in s->texmins[] and s->texsize[] +also sets exactmins[] and exactmaxs[] +================ +*/ +void CalcFaceExtents (lightinfo_t *l) +{ + dface_t *s; + vec_t mins[2], maxs[2], val; + int i,j, e; + dvertex_t *v; + texinfo_t *tex; + vec3_t vt; + + s = l->face; + + mins[0] = mins[1] = 999999; + maxs[0] = maxs[1] = -99999; + + tex = &texinfo[s->texinfo]; + + for (i=0 ; inumedges ; i++) + { + e = dsurfedges[s->firstedge+i]; + if (e >= 0) + v = dvertexes + dedges[e].v[0]; + else + v = dvertexes + dedges[-e].v[1]; + +// VectorAdd (v->point, l->modelorg, vt); + VectorCopy (v->point, vt); + + for (j=0 ; j<2 ; j++) + { + val = DotProduct (vt, tex->vecs[j]) + tex->vecs[j][3]; + if (val < mins[j]) + mins[j] = val; + if (val > maxs[j]) + maxs[j] = val; + } + } + + for (i=0 ; i<2 ; i++) + { + l->exactmins[i] = mins[i]; + l->exactmaxs[i] = maxs[i]; + + mins[i] = floor(mins[i]/16); + maxs[i] = ceil(maxs[i]/16); + + l->texmins[i] = mins[i]; + l->texsize[i] = maxs[i] - mins[i]; + if (l->texsize[0] * l->texsize[1] > SINGLEMAP/4) // div 4 for extrasamples + Error ("Surface to large to map"); + } +} + +/* +================ +CalcFaceVectors + +Fills in texorg, worldtotex. and textoworld +================ +*/ +void CalcFaceVectors (lightinfo_t *l) +{ + texinfo_t *tex; + int i, j; + vec3_t texnormal; + vec_t distscale; + vec_t dist, len; + int w, h; + + tex = &texinfo[l->face->texinfo]; + +// convert from float to double + for (i=0 ; i<2 ; i++) + for (j=0 ; j<3 ; j++) + l->worldtotex[i][j] = tex->vecs[i][j]; + +// calculate a normal to the texture axis. points can be moved along this +// without changing their S/T + texnormal[0] = tex->vecs[1][1]*tex->vecs[0][2] + - tex->vecs[1][2]*tex->vecs[0][1]; + texnormal[1] = tex->vecs[1][2]*tex->vecs[0][0] + - tex->vecs[1][0]*tex->vecs[0][2]; + texnormal[2] = tex->vecs[1][0]*tex->vecs[0][1] + - tex->vecs[1][1]*tex->vecs[0][0]; + VectorNormalize (texnormal, texnormal); + +// flip it towards plane normal + distscale = DotProduct (texnormal, l->facenormal); + if (!distscale) + { + Sys_FPrintf( SYS_VRB, "WARNING: Texture axis perpendicular to face\n"); + distscale = 1; + } + if (distscale < 0) + { + distscale = -distscale; + VectorSubtract (vec3_origin, texnormal, texnormal); + } + +// distscale is the ratio of the distance along the texture normal to +// the distance along the plane normal + distscale = 1/distscale; + + for (i=0 ; i<2 ; i++) + { + len = VectorLength (l->worldtotex[i]); + dist = DotProduct (l->worldtotex[i], l->facenormal); + dist *= distscale; + VectorMA (l->worldtotex[i], -dist, texnormal, l->textoworld[i]); + VectorScale (l->textoworld[i], (1/len)*(1/len), l->textoworld[i]); + } + + +// calculate texorg on the texture plane + for (i=0 ; i<3 ; i++) + l->texorg[i] = -tex->vecs[0][3]* l->textoworld[0][i] - tex->vecs[1][3] * l->textoworld[1][i]; + +// project back to the face plane + dist = DotProduct (l->texorg, l->facenormal) - l->facedist - 1; + dist *= distscale; + VectorMA (l->texorg, -dist, texnormal, l->texorg); + + // compensate for org'd bmodels + VectorAdd (l->texorg, l->modelorg, l->texorg); + + // total sample count + h = l->texsize[1]+1; + w = l->texsize[0]+1; + l->numsurfpt = w * h; +} + +/* +================= +CalcPoints + +For each texture aligned grid point, back project onto the plane +to get the world xyz value of the sample point +================= +*/ +void CalcPoints (lightinfo_t *l, float sofs, float tofs) +{ + int i; + int s, t, j; + int w, h, step; + vec_t starts, startt, us, ut; + vec_t *surf; + vec_t mids, midt; + vec3_t facemid; + dleaf_t *leaf; + + surf = l->surfpt[0]; + mids = (l->exactmaxs[0] + l->exactmins[0])/2; + midt = (l->exactmaxs[1] + l->exactmins[1])/2; + + for (j=0 ; j<3 ; j++) + facemid[j] = l->texorg[j] + l->textoworld[0][j]*mids + l->textoworld[1][j]*midt; + + h = l->texsize[1]+1; + w = l->texsize[0]+1; + l->numsurfpt = w * h; + + starts = l->texmins[0]*16; + startt = l->texmins[1]*16; + step = 16; + + + for (t=0 ; ttexorg[j] + l->textoworld[0][j]*us + + l->textoworld[1][j]*ut; + + leaf = Rad_PointInLeaf (surf); + if (leaf->contents != CONTENTS_SOLID) + { + if (!TestLine_r (0, facemid, surf)) + break; // got it + } + + // nudge it + if (i & 1) + { + if (us > mids) + { + us -= 8; + if (us < mids) + us = mids; + } + else + { + us += 8; + if (us > mids) + us = mids; + } + } + else + { + if (ut > midt) + { + ut -= 8; + if (ut < midt) + ut = midt; + } + else + { + ut += 8; + if (ut > midt) + ut = midt; + } + } + } + } + } + +} + + +//============================================================== + + + +#define MAX_STYLES 32 +typedef struct +{ + int numsamples; + float *origins; + int numstyles; + int stylenums[MAX_STYLES]; + float *samples[MAX_STYLES]; +} facelight_t; + +directlight_t *directlights[MAX_MAP_LEAFS]; +facelight_t facelight[MAX_MAP_FACES]; +int numdlights; + +/* +================== +FindTargetEntity +================== +*/ +entity_t *FindTargetEntity (char *target) +{ + int i; + char *n; + + for (i=0 ; itotallight[0] < DIRECT_LIGHT + && p->totallight[1] < DIRECT_LIGHT + && p->totallight[2] < DIRECT_LIGHT) + continue; + + numdlights++; + dl = malloc(sizeof(directlight_t)); + memset (dl, 0, sizeof(*dl)); + + VectorCopy (p->origin, dl->origin); + + leaf = Rad_PointInLeaf (dl->origin); + cluster = leaf->cluster; + dl->next = directlights[cluster]; + directlights[cluster] = dl; + + dl->type = emit_surface; + VectorCopy (p->plane->normal, dl->normal); + + dl->intensity = ColorNormalize (p->totallight, dl->color); + dl->intensity *= p->area * direct_scale; + VectorClear (p->totallight); // all sent now + } + + // + // entities + // + for (i=0 ; iorigin); + dl->style = FloatForKey (e, "_style"); + if (!dl->style) + dl->style = FloatForKey (e, "style"); + if (dl->style < 0 || dl->style >= MAX_LSTYLES) + dl->style = 0; + + leaf = Rad_PointInLeaf (dl->origin); + cluster = leaf->cluster; + + dl->next = directlights[cluster]; + directlights[cluster] = dl; + + intensity = FloatForKey (e, "light"); + if (!intensity) + intensity = FloatForKey (e, "_light"); + if (!intensity) + intensity = 300; + _color = ValueForKey (e, "_color"); + if (_color && _color[0]) + { + sscanf (_color, "%f %f %f", &dl->color[0],&dl->color[1],&dl->color[2]); + ColorNormalize (dl->color, dl->color); + } + else + dl->color[0] = dl->color[1] = dl->color[2] = 1.0; + dl->intensity = intensity*entity_scale; + dl->type = emit_point; + + target = ValueForKey (e, "target"); + + if (!strcmp (name, "light_spot") || target[0]) + { + dl->type = emit_spotlight; + dl->stopdot = FloatForKey (e, "_cone"); + if (!dl->stopdot) + dl->stopdot = 10; + dl->stopdot = cos(dl->stopdot/180*3.14159); + if (target[0]) + { // point towards target + e2 = FindTargetEntity (target); + if (!e2) + Sys_Printf ("WARNING: light at (%i %i %i) has missing target\n", + (int)dl->origin[0], (int)dl->origin[1], (int)dl->origin[2]); + else + { + GetVectorForKey (e2, "origin", dest); + VectorSubtract (dest, dl->origin, dl->normal); + VectorNormalize (dl->normal, dl->normal); + } + } + else + { // point down angle + angle = FloatForKey (e, "angle"); + if (angle == ANGLE_UP) + { + dl->normal[0] = dl->normal[1] = 0; + dl->normal[2] = 1; + } + else if (angle == ANGLE_DOWN) + { + dl->normal[0] = dl->normal[1] = 0; + dl->normal[2] = -1; + } + else + { + dl->normal[2] = 0; + dl->normal[0] = cos (angle/180*3.14159); + dl->normal[1] = sin (angle/180*3.14159); + } + } + } + } + + Sys_FPrintf( SYS_VRB, "%i direct lights\n", numdlights); +} + +/* +============= +GatherSampleLight + +Lightscale is the normalizer for multisampling +============= +*/ +void GatherSampleLight (vec3_t pos, vec3_t normal, + float **styletable, int offset, int mapsize, float lightscale) +{ + int i; + directlight_t *l; + byte pvs[(MAX_MAP_LEAFS+7)/8]; + vec3_t delta; + float dot, dot2; + float dist; + float scale; + float *dest; + + // get the PVS for the pos to limit the number of checks + if (!PvsForOrigin (pos, pvs)) + { + return; + } + + for (i = 0 ; inumclusters ; i++) + { + if ( ! (pvs[ i>>3] & (1<<(i&7))) ) + continue; + + for (l=directlights[i] ; l ; l=l->next) + { + VectorSubtract (l->origin, pos, delta); + dist = VectorNormalize (delta, delta); + dot = DotProduct (delta, normal); + if (dot <= 0.001) + continue; // behind sample surface + + switch (l->type) + { + case emit_point: + // linear falloff + scale = (l->intensity - dist) * dot; + break; + + case emit_surface: + dot2 = -DotProduct (delta, l->normal); + if (dot2 <= 0.001) + goto skipadd; // behind light surface + scale = (l->intensity / (dist*dist) ) * dot * dot2; + break; + + case emit_spotlight: + // linear falloff + dot2 = -DotProduct (delta, l->normal); + if (dot2 <= l->stopdot) + goto skipadd; // outside light cone + scale = (l->intensity - dist) * dot; + break; + default: + Error ("Bad l->type"); + } + + if (TestLine_r (0, pos, l->origin)) + continue; // occluded + + if (scale <= 0) + continue; + + // if this style doesn't have a table yet, allocate one + if (!styletable[l->style]) + { + styletable[l->style] = malloc (mapsize); + memset (styletable[l->style], 0, mapsize); + } + + dest = styletable[l->style] + offset; + // add some light to it + VectorMA (dest, scale*lightscale, l->color, dest); + +skipadd: ; + } + } + +} + +/* +============= +AddSampleToPatch + +Take the sample's collected light and +add it back into the apropriate patch +for the radiosity pass. + +The sample is added to all patches that might include +any part of it. They are counted and averaged, so it +doesn't generate extra light. +============= +*/ +void AddSampleToPatch (vec3_t pos, vec3_t color, int facenum) +{ + patch_t *patch; + vec3_t mins, maxs; + int i; + + if (numbounce == 0) + return; + if (color[0] + color[1] + color[2] < 3) + return; + + for (patch = face_patches[facenum] ; patch ; patch=patch->next) + { + // see if the point is in this patch (roughly) + WindingBounds (patch->winding, mins, maxs); + for (i=0 ; i<3 ; i++) + { + if (mins[i] > pos[i] + 16) + goto nextpatch; + if (maxs[i] < pos[i] - 16) + goto nextpatch; + } + + // add the sample to the patch + patch->samples++; + VectorAdd (patch->samplelight, color, patch->samplelight); +nextpatch:; + } + +} + + +/* +============= +BuildFacelights +============= +*/ +float sampleofs[5][2] = +{ {0,0}, {-0.25, -0.25}, {0.25, -0.25}, {0.25, 0.25}, {-0.25, 0.25} }; + + +void BuildFacelights (int facenum) +{ + dface_t *f; + lightinfo_t l[5]; + float *styletable[MAX_LSTYLES]; + int i, j; + float *spot; + patch_t *patch; + int numsamples; + int tablesize; + facelight_t *fl; + + f = &dfaces[facenum]; + + if ( texinfo[f->texinfo].flags & (SURF_WARP|SURF_SKY) ) + return; // non-lit texture + + memset (styletable,0, sizeof(styletable)); + + if (extrasamples) + numsamples = 5; + else + numsamples = 1; + for (i=0 ; iplanenum].normal, l[i].facenormal); + l[i].facedist = dplanes[f->planenum].dist; + if (f->side) + { + VectorSubtract (vec3_origin, l[i].facenormal, l[i].facenormal); + l[i].facedist = -l[i].facedist; + } + + // get the origin offset for rotating bmodels + VectorCopy (face_offset[facenum], l[i].modelorg); + + CalcFaceVectors (&l[i]); + CalcFaceExtents (&l[i]); + CalcPoints (&l[i], sampleofs[i][0], sampleofs[i][1]); + } + + tablesize = l[0].numsurfpt * sizeof(vec3_t); + styletable[0] = malloc(tablesize); + memset (styletable[0], 0, tablesize); + + fl = &facelight[facenum]; + fl->numsamples = l[0].numsurfpt; + fl->origins = malloc (tablesize); + memcpy (fl->origins, l[0].surfpt, tablesize); + + for (i=0 ; inext) + { + if (patch->samples) + { + VectorScale (patch->samplelight, 1.0/patch->samples, patch->samplelight); + } + else + { +// printf ("patch with no samples\n"); + } + } + + for (i=0 ; inumstyles == MAX_STYLES) + break; + fl->samples[fl->numstyles] = styletable[i]; + fl->stylenums[fl->numstyles] = i; + fl->numstyles++; + } + + // the light from DIRECT_LIGHTS is sent out, but the + // texture itself should still be full bright + + if (face_patches[facenum]->baselight[0] >= DIRECT_LIGHT || + face_patches[facenum]->baselight[1] >= DIRECT_LIGHT || + face_patches[facenum]->baselight[2] >= DIRECT_LIGHT + ) + { + spot = fl->samples[0]; + for (i=0 ; ibaselight, spot); + } + } +} + + +/* +============= +FinalLightFace + +Add the indirect lighting on top of the direct +lighting and save into final map format +============= +*/ +void FinalLightFace (int facenum) +{ + dface_t *f; + int i, j, k, st; + vec3_t lb; + patch_t *patch; + triangulation_t *trian; + facelight_t *fl; + float minlight; + float max, newmax; + byte *dest; + int pfacenum; + vec3_t facemins, facemaxs; + + f = &dfaces[facenum]; + fl = &facelight[facenum]; + + if ( texinfo[f->texinfo].flags & (SURF_WARP|SURF_SKY) ) + return; // non-lit texture + + ThreadLock (); + f->lightofs = lightdatasize; + lightdatasize += fl->numstyles*(fl->numsamples*3); + +// add green sentinals between lightmaps +#if 0 +lightdatasize += 64*3; +for (i=0 ; i<64 ; i++) +dlightdata[lightdatasize-(i+1)*3 + 1] = 255; +#endif + + if (lightdatasize > MAX_MAP_LIGHTING) + Error ("MAX_MAP_LIGHTING"); + ThreadUnlock (); + + f->styles[0] = 0; + f->styles[1] = f->styles[2] = f->styles[3] = 0xff; + + // + // set up the triangulation + // + if (numbounce > 0) + { + ClearBounds (facemins, facemaxs); + for (i=0 ; inumedges ; i++) + { + int ednum; + + ednum = dsurfedges[f->firstedge+i]; + if (ednum >= 0) + AddPointToBounds (dvertexes[dedges[ednum].v[0]].point, + facemins, facemaxs); + else + AddPointToBounds (dvertexes[dedges[-ednum].v[1]].point, + facemins, facemaxs); + } + + trian = AllocTriangulation (&dplanes[f->planenum]); + + // for all faces on the plane, add the nearby patches + // to the triangulation + for (pfacenum = planelinks[f->side][f->planenum] + ; pfacenum ; pfacenum = facelinks[pfacenum]) + { + for (patch = face_patches[pfacenum] ; patch ; patch=patch->next) + { + for (i=0 ; i < 3 ; i++) + { + if (facemins[i] - patch->origin[i] > subdiv*2) + break; + if (patch->origin[i] - facemaxs[i] > subdiv*2) + break; + } + if (i != 3) + continue; // not needed for this face + AddPointToTriangulation (patch, trian); + } + } + for (i=0 ; inumpoints ; i++) + memset (trian->edgematrix[i], 0, trian->numpoints*sizeof(trian->edgematrix[0][0]) ); + TriangulatePoints (trian); + } + + // + // sample the triangulation + // + + // _minlight allows models that have faces that would not be + // illuminated to receive a mottled light pattern instead of + // black + minlight = FloatForKey (face_entity[facenum], "_minlight") * 128; + + dest = &dlightdata[f->lightofs]; + + if (fl->numstyles > MAXLIGHTMAPS) + { + fl->numstyles = MAXLIGHTMAPS; + Sys_Printf ("face with too many lightstyles: (%f %f %f)\n", + face_patches[facenum]->origin[0], + face_patches[facenum]->origin[1], + face_patches[facenum]->origin[2] + ); + } + + for (st=0 ; stnumstyles ; st++) + { + f->styles[st] = fl->stylenums[st]; + for (j=0 ; jnumsamples ; j++) + { + VectorCopy ( (fl->samples[st]+j*3), lb); + if (numbounce > 0 && st == 0) + { + vec3_t add; + + SampleTriangulation (fl->origins + j*3, trian, add); + VectorAdd (lb, add, lb); + } + // add an ambient term if desired + lb[0] += ambient; + lb[1] += ambient; + lb[2] += ambient; + + VectorScale (lb, lightscale, lb); + + // we need to clamp without allowing hue to change + for (k=0 ; k<3 ; k++) + if (lb[k] < 1) + lb[k] = 1; + max = lb[0]; + if (lb[1] > max) + max = lb[1]; + if (lb[2] > max) + max = lb[2]; + newmax = max; + if (newmax < 0) + newmax = 0; // roundoff problems + if (newmax < minlight) + { + newmax = minlight + (rand()%48); + } + if (newmax > maxlight) + newmax = maxlight; + + for (k=0 ; k<3 ; k++) + { + *dest++ = lb[k]*newmax/max; + } + } + } + + if (numbounce > 0) + FreeTriangulation (trian); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/main.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/main.c new file mode 100644 index 00000000..5ed8daca --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/main.c @@ -0,0 +1,721 @@ +/* +Copyright (C) 1999-2006 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 +*/ + + +/* marker */ +#define MAIN_C + + + +/* dependencies */ +#include "q2map.h" + +#define qtrue true +#define qfalse false + +char *mapname; +char game[64]; +extern qboolean verbose; + +/// BSP +extern qboolean drawflag; +extern qboolean noprune; +extern qboolean glview; +extern qboolean nodetail; +extern qboolean fulldetail; +extern qboolean onlyents; +extern qboolean nomerge; +extern qboolean nowater; +extern qboolean nofill; +extern qboolean nocsg; +extern qboolean noweld; +extern qboolean noshare; +extern qboolean nosubdiv; +extern qboolean notjunc; +extern qboolean noopt; +extern qboolean leaktest; +extern qboolean verboseentities; +extern char outbase[32]; +extern int block_xl, block_xh, block_yl, block_yh; +extern vec_t microvolume; +extern float subdivide_size; + +// VIS +extern char inbase[32]; +extern qboolean fastvis; +extern qboolean nosort; +extern int testlevel; + +// RAD +extern qboolean dumppatches; +extern int numbounce; +extern qboolean extrasamples; +extern float subdiv; +extern float lightscale; +extern float direct_scale; +extern float entity_scale; +extern qboolean nopvs; +extern float ambient; +extern float maxlight; + + +void InitPaths( int *argc, char **argv ); + +/* +Random() +returns a pseudorandom number between 0 and 1 +*/ +/* +vec_t Random( void ) +{ + return (vec_t) rand() / RAND_MAX; +} +*/ + + +/* +ExitQ2Map() +cleanup routine +*/ +/* +static void ExitQ2Map( void ) +{ + BSPFilesCleanup(); + if( mapDrawSurfs != NULL ) + free( mapDrawSurfs ); +} +*/ + + +/* +BSPInfo() +emits statistics about the bsp file +*/ + +int BSPInfo() +{ + char source[ 1024 ], ext[ 64 ]; + int size; + FILE *f; + + Sys_Printf ("\n----- INFO ----\n\n"); + + /* dummy check */ + if( mapname == NULL ) + { + Sys_Printf( "No files to dump info for.\n"); + return -1; + } + + /* enable info mode */ + //infoMode = qtrue; + + + /* mangle filename and get size */ + strcpy( source, mapname ); + ExtractFileExtension( source, ext ); + if( !Q_stricmp( ext, "map" ) ) + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + f = fopen( source, "rb" ); + if( f ) + { + size = Q_filelength (f); + fclose( f ); + } + else + size = 0; + + /* load the bsp file and print lump sizes */ + Sys_Printf( "Map: %s\n\n", source ); + + Sys_Printf( "-----------------------------------------------------\n" ); + + LoadBSPFile( source ); + PrintBSPFileSizes(); + + Sys_Printf( "-----------------------------------------------------\n" ); + + /* print sizes */ + Sys_Printf( "Total: %d B = %.3f kB = %.3f MB\n", size, size / 1024.0, size / (1024.0 * 1024.0) ); + + Sys_Printf( "-----------------------------------------------------\n" ); + + /* return count */ + return 0; +} + + + +/* +ScaleBSPMain() +amaze and confuse your enemies with wierd scaled maps! +*/ +/* +int ScaleBSPMain( int argc, char **argv ) +{ + int i; + float f, scale; + vec3_t vec; + char str[ 1024 ]; + + + // arg checking + if( argc < 2 ) + { + Sys_Printf( "Usage: q3map -scale [-v] \n" ); + return 0; + } + + // get scale + scale = atof( argv[ argc - 2 ] ); + if( scale == 0.0f ) + { + Sys_Printf( "Usage: q3map -scale [-v] \n" ); + Sys_Printf( "Non-zero scale value required.\n" ); + return 0; + } + + // do some path mangling + strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + + // load the bsp + Sys_Printf( "Loading %s\n", source ); + LoadBSPFile( source ); + ParseEntities(); + + // note it + Sys_Printf( "--- ScaleBSP ---\n" ); + Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities ); + + // scale entity keys + for( i = 0; i < numBSPEntities && i < numEntities; i++ ) + { + // scale origin + GetVectorForKey( &entities[ i ], "origin", vec ); + if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) ) + { + VectorScale( vec, scale, vec ); + sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); + SetKeyValue( &entities[ i ], "origin", str ); + } + + // scale door lip + f = FloatForKey( &entities[ i ], "lip" ); + if( f ) + { + f *= scale; + sprintf( str, "%f", f ); + SetKeyValue( &entities[ i ], "lip", str ); + } + } + + // scale models + for( i = 0; i < numBSPModels; i++ ) + { + VectorScale( bspModels[ i ].mins, scale, bspModels[ i ].mins ); + VectorScale( bspModels[ i ].maxs, scale, bspModels[ i ].maxs ); + } + + // scale nodes + for( i = 0; i < numBSPNodes; i++ ) + { + VectorScale( bspNodes[ i ].mins, scale, bspNodes[ i ].mins ); + VectorScale( bspNodes[ i ].maxs, scale, bspNodes[ i ].maxs ); + } + + // scale leafs + for( i = 0; i < numBSPLeafs; i++ ) + { + VectorScale( bspLeafs[ i ].mins, scale, bspLeafs[ i ].mins ); + VectorScale( bspLeafs[ i ].maxs, scale, bspLeafs[ i ].maxs ); + } + + // scale drawverts + for( i = 0; i < numBSPDrawVerts; i++ ) + VectorScale( bspDrawVerts[ i ].xyz, scale, bspDrawVerts[ i ].xyz ); + + // scale planes + for( i = 0; i < numBSPPlanes; i++ ) + bspPlanes[ i ].dist *= scale; + + // scale gridsize + GetVectorForKey( &entities[ 0 ], "gridsize", vec ); + if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f ) + VectorCopy( gridSize, vec ); + VectorScale( vec, scale, vec ); + sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); + SetKeyValue( &entities[ 0 ], "gridsize", str ); + + // write the bsp + UnparseEntities(); + StripExtension( source ); + DefaultExtension( source, "_s.bsp" ); + Sys_Printf( "Writing %s\n", source ); + WriteBSPFile( source ); + + // return to sender + return 0; +} +*/ + + +/* +ConvertBSPMain() +main argument processing function for bsp conversion +*/ +/* +int ConvertBSPMain( int argc, char **argv ) +{ + int i; + int (*convertFunc)( char * ); + + + // set default + convertFunc = ConvertBSPToASE; + + // arg checking + if( argc < 1 ) + { + Sys_Printf( "Usage: q3map -scale [-v] \n" ); + return 0; + } + + // process arguments + for( i = 1; i < (argc - 1); i++ ) + { + // -format map|ase|... + if( !strcmp( argv[ i ], "-format" ) ) + { + i++; + if( !Q_stricmp( argv[ i ], "ase" ) ) + convertFunc = ConvertBSPToASE; + else if( !Q_stricmp( argv[ i ], "map" ) ) + convertFunc = ConvertBSPToMap; + else + Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] ); + } + } + + // clean up map name + strcpy( source, ExpandArg( argv[ i ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + + LoadShaderInfo(); + + Sys_Printf( "Loading %s\n", source ); + + // ydnar: load surface file + //% LoadSurfaceExtraFile( source ); + + LoadBSPFile( source ); + + // parse bsp entities + ParseEntities(); + + // convert + return convertFunc( source ); +} +*/ + +int Check_BSP_Options( int argc, char **argv ) +{ + int i; + + for (i=1 ; i 59 ) + Sys_Printf("%d Minutes ", total_time/60 ); + Sys_Printf( "%d Seconds\n", total_time%60 ); + + /* shut down connection */ + Broadcast_Shutdown(); + + /* return any error code */ + return r; +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/map.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/map.c new file mode 100644 index 00000000..818f2a1d --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/map.c @@ -0,0 +1,1017 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// map.c + +#include "qbsp.h" + +extern qboolean onlyents; + +int nummapbrushes; +mapbrush_t mapbrushes[MAX_MAP_BRUSHES]; + +int nummapbrushsides; +side_t brushsides[MAX_MAP_SIDES]; +brush_texture_t side_brushtextures[MAX_MAP_SIDES]; + +int nummapplanes; +plane_t mapplanes[MAX_MAP_PLANES]; + +#define PLANE_HASHES 1024 +plane_t *planehash[PLANE_HASHES]; + +vec3_t map_mins, map_maxs; + +// undefine to make plane finding use linear sort +#define USE_HASHING + +void TestExpandBrushes (void); + +int c_boxbevels; +int c_edgebevels; + +int c_areaportals; + +int c_clipbrushes; + +/* +============================================================================= + +PLANE FINDING + +============================================================================= +*/ + + +/* +================= +PlaneTypeForNormal +================= +*/ +int PlaneTypeForNormal (vec3_t normal) +{ + vec_t ax, ay, az; + +// NOTE: should these have an epsilon around 1.0? + 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; + + ax = fabs(normal[0]); + ay = fabs(normal[1]); + az = fabs(normal[2]); + + if (ax >= ay && ax >= az) + return PLANE_ANYX; + if (ay >= ax && ay >= az) + return PLANE_ANYY; + return PLANE_ANYZ; +} + +/* +================ +PlaneEqual +================ +*/ +#define NORMAL_EPSILON 0.00001 +#define DIST_EPSILON 0.01 +qboolean PlaneEqual (plane_t *p, vec3_t normal, vec_t dist) +{ +#if 1 + if ( + fabs(p->normal[0] - normal[0]) < NORMAL_EPSILON + && fabs(p->normal[1] - normal[1]) < NORMAL_EPSILON + && fabs(p->normal[2] - normal[2]) < NORMAL_EPSILON + && fabs(p->dist - dist) < DIST_EPSILON ) + return true; +#else + if (p->normal[0] == normal[0] + && p->normal[1] == normal[1] + && p->normal[2] == normal[2] + && p->dist == dist) + return true; +#endif + return false; +} + +/* +================ +AddPlaneToHash +================ +*/ +void AddPlaneToHash (plane_t *p) +{ + int hash; + + hash = (int)fabs(p->dist) / 8; + hash &= (PLANE_HASHES-1); + + p->hash_chain = planehash[hash]; + planehash[hash] = p; +} + +/* +================ +CreateNewFloatPlane +================ +*/ +int CreateNewFloatPlane (vec3_t normal, vec_t dist) +{ + plane_t *p, temp; + + if (VectorLength(normal) < 0.5) + Error ("FloatPlane: bad normal"); + // create a new plane + if (nummapplanes+2 > MAX_MAP_PLANES) + Error ("MAX_MAP_PLANES"); + + p = &mapplanes[nummapplanes]; + VectorCopy (normal, p->normal); + p->dist = dist; + p->type = (p+1)->type = PlaneTypeForNormal (p->normal); + + VectorSubtract (vec3_origin, normal, (p+1)->normal); + (p+1)->dist = -dist; + + nummapplanes += 2; + + // allways put axial planes facing positive first + if (p->type < 3) + { + if (p->normal[0] < 0 || p->normal[1] < 0 || p->normal[2] < 0) + { + // flip order + temp = *p; + *p = *(p+1); + *(p+1) = temp; + + AddPlaneToHash (p); + AddPlaneToHash (p+1); + return nummapplanes - 1; + } + } + + AddPlaneToHash (p); + AddPlaneToHash (p+1); + return nummapplanes - 2; +} + +/* +============== +SnapVector +============== +*/ +void SnapVector (vec3_t normal) +{ + int i; + + for (i=0 ; i<3 ; i++) + { + if ( fabs(normal[i] - 1) < NORMAL_EPSILON ) + { + VectorClear (normal); + normal[i] = 1; + break; + } + if ( fabs(normal[i] - -1) < NORMAL_EPSILON ) + { + VectorClear (normal); + normal[i] = -1; + break; + } + } +} + +/* +============== +SnapPlane +============== +*/ +void SnapPlane (vec3_t normal, vec_t *dist) +{ + SnapVector (normal); + + if (fabs(*dist-Q_rint(*dist)) < DIST_EPSILON) + *dist = Q_rint(*dist); +} + +/* +============= +FindFloatPlane + +============= +*/ +#ifndef USE_HASHING +int FindFloatPlane (vec3_t normal, vec_t dist) +{ + int i; + plane_t *p; + + SnapPlane (normal, &dist); + for (i=0, p=mapplanes ; ihash_chain) + { + if (PlaneEqual (p, normal, dist)) + return p-mapplanes; + } + } + + return CreateNewFloatPlane (normal, dist); +} +#endif + +/* +================ +PlaneFromPoints +================ +*/ +int PlaneFromPoints (int *p0, int *p1, int *p2) +{ + vec3_t t1, t2, normal; + vec_t dist; + + VectorSubtract (p0, p1, t1); + VectorSubtract (p2, p1, t2); + CrossProduct (t1, t2, normal); + VectorNormalize (normal, normal); + + dist = DotProduct (p0, normal); + + return FindFloatPlane (normal, dist); +} + + +//==================================================================== + + +/* +=========== +BrushContents +=========== +*/ +int BrushContents (mapbrush_t *b) +{ + int contents; + side_t *s; + int i; + int trans; + + s = &b->original_sides[0]; + contents = s->contents; + trans = texinfo[s->texinfo].flags; + for (i=1 ; inumsides ; i++, s++) + { + s = &b->original_sides[i]; + trans |= texinfo[s->texinfo].flags; + if (s->contents != contents) + { + Sys_Printf ("Entity %i, Brush %i: mixed face contents\n" + , b->entitynum, b->brushnum); + break; + } + } + + // if any side is translucent, mark the contents + // and change solid to window + if ( trans & (SURF_TRANS33|SURF_TRANS66) ) + { + contents |= CONTENTS_TRANSLUCENT; + if (contents & CONTENTS_SOLID) + { + contents &= ~CONTENTS_SOLID; + contents |= CONTENTS_WINDOW; + } + } + + return contents; +} + + +//============================================================================ + +/* +================= +AddBrushBevels + +Adds any additional planes necessary to allow the brush to be expanded +against axial bounding boxes +================= +*/ +void AddBrushBevels (mapbrush_t *b) +{ + int axis, dir; + int i, j, k, l, order; + side_t sidetemp; + brush_texture_t tdtemp; + side_t *s, *s2; + vec3_t normal; + float dist; + winding_t *w, *w2; + vec3_t vec, vec2; + float d; + + // + // add the axial planes + // + order = 0; + for (axis=0 ; axis <3 ; axis++) + { + for (dir=-1 ; dir <= 1 ; dir+=2, order++) + { + // see if the plane is allready present + for (i=0, s=b->original_sides ; inumsides ; i++,s++) + { + if (mapplanes[s->planenum].normal[axis] == dir) + break; + } + + if (i == b->numsides) + { // add a new side + if (nummapbrushsides == MAX_MAP_BRUSHSIDES) + Error ("MAX_MAP_BRUSHSIDES"); + nummapbrushsides++; + b->numsides++; + VectorClear (normal); + normal[axis] = dir; + if (dir == 1) + dist = b->maxs[axis]; + else + dist = -b->mins[axis]; + s->planenum = FindFloatPlane (normal, dist); + s->texinfo = b->original_sides[0].texinfo; + s->contents = b->original_sides[0].contents; + s->bevel = true; + c_boxbevels++; + } + + // if the plane is not in it canonical order, swap it + if (i != order) + { + sidetemp = b->original_sides[order]; + b->original_sides[order] = b->original_sides[i]; + b->original_sides[i] = sidetemp; + + j = b->original_sides - brushsides; + tdtemp = side_brushtextures[j+order]; + side_brushtextures[j+order] = side_brushtextures[j+i]; + side_brushtextures[j+i] = tdtemp; + } + } + } + + // + // add the edge bevels + // + if (b->numsides == 6) + return; // pure axial + + // test the non-axial plane edges + for (i=6 ; inumsides ; i++) + { + s = b->original_sides + i; + w = s->winding; + if (!w) + continue; + for (j=0 ; jnumpoints ; j++) + { + k = (j+1)%w->numpoints; + VectorSubtract (w->p[j], w->p[k], vec); + if (VectorNormalize (vec, vec) < 0.5) + continue; + SnapVector (vec); + for (k=0 ; k<3 ; k++) + if ( vec[k] == -1 || vec[k] == 1) + break; // axial + if (k != 3) + continue; // only test non-axial edges + + // try the six possible slanted axials from this edge + for (axis=0 ; axis <3 ; axis++) + { + for (dir=-1 ; dir <= 1 ; dir+=2) + { + // construct a plane + VectorClear (vec2); + vec2[axis] = dir; + CrossProduct (vec, vec2, normal); + if (VectorNormalize (normal, normal) < 0.5) + continue; + dist = DotProduct (w->p[j], normal); + + // if all the points on all the sides are + // behind this plane, it is a proper edge bevel + for (k=0 ; knumsides ; k++) + { + // if this plane has allready been used, skip it + if (PlaneEqual (&mapplanes[b->original_sides[k].planenum] + , normal, dist) ) + break; + + w2 = b->original_sides[k].winding; + if (!w2) + continue; + for (l=0 ; lnumpoints ; l++) + { + d = DotProduct (w2->p[l], normal) - dist; + if (d > 0.1) + break; // point in front + } + if (l != w2->numpoints) + break; + } + + if (k != b->numsides) + continue; // wasn't part of the outer hull + // add this plane + if (nummapbrushsides == MAX_MAP_BRUSHSIDES) + Error ("MAX_MAP_BRUSHSIDES"); + nummapbrushsides++; + s2 = &b->original_sides[b->numsides]; + s2->planenum = FindFloatPlane (normal, dist); + s2->texinfo = b->original_sides[0].texinfo; + s2->contents = b->original_sides[0].contents; + s2->bevel = true; + c_edgebevels++; + b->numsides++; + } + } + } + } +} + + +/* +================ +MakeBrushWindings + +makes basewindigs for sides and mins / maxs for the brush +================ +*/ +qboolean MakeBrushWindings (mapbrush_t *ob) +{ + int i, j; + winding_t *w; + side_t *side; + plane_t *plane; + + ClearBounds (ob->mins, ob->maxs); + + for (i=0 ; inumsides ; i++) + { + plane = &mapplanes[ob->original_sides[i].planenum]; + w = BaseWindingForPlane (plane->normal, plane->dist); + for (j=0 ; jnumsides && w; j++) + { + if (i == j) + continue; + if (ob->original_sides[j].bevel) + continue; + plane = &mapplanes[ob->original_sides[j].planenum^1]; + ChopWindingInPlace (&w, plane->normal, plane->dist, 0); //CLIP_EPSILON); + } + + side = &ob->original_sides[i]; + side->winding = w; + if (w) + { + side->visible = true; + for (j=0 ; jnumpoints ; j++) + AddPointToBounds (w->p[j], ob->mins, ob->maxs); + } + } + + for (i=0 ; i<3 ; i++) + { + if (ob->mins[0] < -4096 || ob->maxs[0] > 4096) + Sys_Printf ("entity %i, brush %i: bounds out of range\n", ob->entitynum, ob->brushnum); + if (ob->mins[0] > 4096 || ob->maxs[0] < -4096) + Sys_Printf ("entity %i, brush %i: no visible sides on brush\n", ob->entitynum, ob->brushnum); + } + + return true; +} + + +/* +================= +ParseBrush +================= +*/ +void ParseBrush (entity_t *mapent) +{ + mapbrush_t *b; + int i,j, k; + int mt; + side_t *side, *s2; + int planenum; + brush_texture_t td; + int planepts[3][3]; + + if (nummapbrushes == MAX_MAP_BRUSHES) + Error ("nummapbrushes == MAX_MAP_BRUSHES"); + + b = &mapbrushes[nummapbrushes]; + b->original_sides = &brushsides[nummapbrushsides]; + b->entitynum = num_entities-1; + b->brushnum = nummapbrushes - mapent->firstbrush; + + do + { + if (!GetToken (true)) + break; + if (!strcmp (token, "}") ) + break; + + if (nummapbrushsides == MAX_MAP_BRUSHSIDES) + Error ("MAX_MAP_BRUSHSIDES"); + side = &brushsides[nummapbrushsides]; + + // read the three point plane definition + for (i=0 ; i<3 ; i++) + { + if (i != 0) + GetToken (true); + if (strcmp (token, "(") ) + Error ("parsing brush"); + + for (j=0 ; j<3 ; j++) + { + GetToken (false); + planepts[i][j] = atoi(token); + } + + GetToken (false); + if (strcmp (token, ")") ) + Error ("parsing brush"); + + } + + + // + // read the texturedef + // + GetToken (false); + strcpy (td.name, token); + + GetToken (false); + td.shift[0] = atoi(token); + GetToken (false); + td.shift[1] = atoi(token); + GetToken (false); + td.rotate = atoi(token); + GetToken (false); + td.scale[0] = atof(token); + GetToken (false); + td.scale[1] = atof(token); + + // find default flags and values + mt = FindMiptex (td.name); + td.flags = textureref[mt].flags; + td.value = textureref[mt].value; + side->contents = textureref[mt].contents; + side->surf = td.flags = textureref[mt].flags; + + if (TokenAvailable()) + { + GetToken (false); + side->contents = atoi(token); + GetToken (false); + side->surf = td.flags = atoi(token); + GetToken (false); + td.value = atoi(token); + } + + // translucent objects are automatically classified as detail + if (side->surf & (SURF_TRANS33|SURF_TRANS66) ) + side->contents |= CONTENTS_DETAIL; + if (side->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) ) + side->contents |= CONTENTS_DETAIL; + if (fulldetail) + side->contents &= ~CONTENTS_DETAIL; + if (!(side->contents & ((LAST_VISIBLE_CONTENTS-1) + | CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP|CONTENTS_MIST) ) ) + side->contents |= CONTENTS_SOLID; + + // hints and skips are never detail, and have no content + if (side->surf & (SURF_HINT|SURF_SKIP) ) + { + side->contents = 0; + side->surf &= ~CONTENTS_DETAIL; + } + + + // + // find the plane number + // + planenum = PlaneFromPoints (planepts[0], planepts[1], planepts[2]); + if (planenum == -1) + { + Sys_Printf ("Entity %i, Brush %i: plane with no normal\n" + , b->entitynum, b->brushnum); + continue; + } + + // + // see if the plane has been used already + // + for (k=0 ; knumsides ; k++) + { + s2 = b->original_sides + k; + if (s2->planenum == planenum) + { + Sys_Printf ("Entity %i, Brush %i: duplicate plane\n" + , b->entitynum, b->brushnum); + break; + } + if ( s2->planenum == (planenum^1) ) + { + Sys_Printf ("Entity %i, Brush %i: mirrored plane\n" + , b->entitynum, b->brushnum); + break; + } + } + if (k != b->numsides) + continue; // duplicated + + // + // keep this side + // + + side = b->original_sides + b->numsides; + side->planenum = planenum; + side->texinfo = TexinfoForBrushTexture (&mapplanes[planenum], + &td, vec3_origin); + + // save the td off in case there is an origin brush and we + // have to recalculate the texinfo + side_brushtextures[nummapbrushsides] = td; + + nummapbrushsides++; + b->numsides++; + } while (1); + + // get the content for the entire brush + b->contents = BrushContents (b); + + // allow detail brushes to be removed + if (nodetail && (b->contents & CONTENTS_DETAIL) ) + { + b->numsides = 0; + return; + } + + // allow water brushes to be removed + if (nowater && (b->contents & (CONTENTS_LAVA | CONTENTS_SLIME | CONTENTS_WATER)) ) + { + b->numsides = 0; + return; + } + + // create windings for sides and bounds for brush + MakeBrushWindings (b); + + // brushes that will not be visible at all will never be + // used as bsp splitters + if (b->contents & (CONTENTS_PLAYERCLIP|CONTENTS_MONSTERCLIP) ) + { + c_clipbrushes++; + for (i=0 ; inumsides ; i++) + b->original_sides[i].texinfo = TEXINFO_NODE; + } + + // + // origin brushes are removed, but they set + // the rotation origin for the rest of the brushes + // in the entity. After the entire entity is parsed, + // the planenums and texinfos will be adjusted for + // the origin brush + // + if (b->contents & CONTENTS_ORIGIN) + { + char string[32]; + vec3_t origin; + + if (num_entities == 1) + { + Error ("Entity %i, Brush %i: origin brushes not allowed in world" + , b->entitynum, b->brushnum); + return; + } + + VectorAdd (b->mins, b->maxs, origin); + VectorScale (origin, 0.5, origin); + + sprintf (string, "%i %i %i", (int)origin[0], (int)origin[1], (int)origin[2]); + SetKeyValue (&entities[b->entitynum], "origin", string); + + VectorCopy (origin, entities[b->entitynum].origin); + + // don't keep this brush + b->numsides = 0; + + return; + } + + AddBrushBevels (b); + + nummapbrushes++; + mapent->numbrushes++; +} + +/* +================ +MoveBrushesToWorld + +Takes all of the brushes from the current entity and +adds them to the world's brush list. + +Used by func_group and func_areaportal +================ +*/ +void MoveBrushesToWorld (entity_t *mapent) +{ + int newbrushes; + int worldbrushes; + mapbrush_t *temp; + int i; + + // this is pretty gross, because the brushes are expected to be + // in linear order for each entity + + newbrushes = mapent->numbrushes; + worldbrushes = entities[0].numbrushes; + + temp = malloc(newbrushes*sizeof(mapbrush_t)); + memcpy (temp, mapbrushes + mapent->firstbrush, newbrushes*sizeof(mapbrush_t)); + +#if 0 // let them keep their original brush numbers + for (i=0 ; inumbrushes = 0; +} + +/* +================ +ParseMapEntity +================ +*/ +qboolean ParseMapEntity (void) +{ + entity_t *mapent; + epair_t *e; + side_t *s; + int i, j; + int startbrush, startsides; + vec_t newdist; + mapbrush_t *b; + + if (!GetToken (true)) + return false; + + if (strcmp (token, "{") ) + Error ("ParseEntity: { not found"); + + if (num_entities == MAX_MAP_ENTITIES) + Error ("num_entities == MAX_MAP_ENTITIES"); + + startbrush = nummapbrushes; + startsides = nummapbrushsides; + + mapent = &entities[num_entities]; + num_entities++; + memset (mapent, 0, sizeof(*mapent)); + mapent->firstbrush = nummapbrushes; + mapent->numbrushes = 0; +// mapent->portalareas[0] = -1; +// mapent->portalareas[1] = -1; + + do + { + if (!GetToken (true)) + Error ("ParseEntity: EOF without closing brace"); + if (!strcmp (token, "}") ) + break; + if (!strcmp (token, "{") ) + ParseBrush (mapent); + else + { + e = ParseEpair (); + e->next = mapent->epairs; + mapent->epairs = e; + } + } while (1); + + GetVectorForKey (mapent, "origin", mapent->origin); + + // + // if there was an origin brush, offset all of the planes and texinfo + // + if (mapent->origin[0] || mapent->origin[1] || mapent->origin[2]) + { + for (i=0 ; inumbrushes ; i++) + { + b = &mapbrushes[mapent->firstbrush + i]; + for (j=0 ; jnumsides ; j++) + { + s = &b->original_sides[j]; + newdist = mapplanes[s->planenum].dist - + DotProduct (mapplanes[s->planenum].normal, mapent->origin); + s->planenum = FindFloatPlane (mapplanes[s->planenum].normal, newdist); + s->texinfo = TexinfoForBrushTexture (&mapplanes[s->planenum], + &side_brushtextures[s-brushsides], mapent->origin); + } + MakeBrushWindings (b); + } + } + + // group entities are just for editor convenience + // toss all brushes into the world entity + if (!strcmp ("func_group", ValueForKey (mapent, "classname"))) + { + MoveBrushesToWorld (mapent); + mapent->numbrushes = 0; + return true; + } + + // areaportal entities move their brushes, but don't eliminate + // the entity + if (!strcmp ("func_areaportal", ValueForKey (mapent, "classname"))) + { + char str[128]; + + if (mapent->numbrushes != 1) + Error ("Entity %i: func_areaportal can only be a single brush", num_entities-1); + + b = &mapbrushes[nummapbrushes-1]; + b->contents = CONTENTS_AREAPORTAL; + c_areaportals++; + mapent->areaportalnum = c_areaportals; + // set the portal number as "style" + sprintf (str, "%i", c_areaportals); + SetKeyValue (mapent, "style", str); + MoveBrushesToWorld (mapent); + return true; + } + + return true; +} + +//=================================================================== + +/* +================ +LoadMapFile +================ +*/ +void LoadMapFile (char *filename) +{ + int i; + + Sys_FPrintf( SYS_VRB, "--- LoadMapFile ---\n"); + + LoadScriptFile (filename); + + nummapbrushsides = 0; + num_entities = 0; + + while (ParseMapEntity ()) + { + } + + ClearBounds (map_mins, map_maxs); + for (i=0 ; i 4096) + continue; // no valid points + AddPointToBounds (mapbrushes[i].mins, map_mins, map_maxs); + AddPointToBounds (mapbrushes[i].maxs, map_mins, map_maxs); + } + + Sys_FPrintf( SYS_VRB, "%5i brushes\n", nummapbrushes); + Sys_FPrintf( SYS_VRB, "%5i clipbrushes\n", c_clipbrushes); + Sys_FPrintf( SYS_VRB, "%5i total sides\n", nummapbrushsides); + Sys_FPrintf( SYS_VRB, "%5i boxbevels\n", c_boxbevels); + Sys_FPrintf( SYS_VRB, "%5i edgebevels\n", c_edgebevels); + Sys_FPrintf( SYS_VRB, "%5i entities\n", num_entities); + Sys_FPrintf( SYS_VRB, "%5i planes\n", nummapplanes); + Sys_FPrintf( SYS_VRB, "%5i areaportals\n", c_areaportals); + Sys_FPrintf( SYS_VRB, "size: %5.0f,%5.0f,%5.0f to %5.0f,%5.0f,%5.0f\n", map_mins[0],map_mins[1],map_mins[2], + map_maxs[0],map_maxs[1],map_maxs[2]); + +// TestExpandBrushes (); +} + + +//==================================================================== + + +/* +================ +TestExpandBrushes + +Expands all the brush planes and saves a new map out +================ +*/ +void TestExpandBrushes (void) +{ + FILE *f; + side_t *s; + int i, j, bn; + winding_t *w; + char *name = "expanded.map"; + mapbrush_t *brush; + vec_t dist; + + Sys_Printf ("writing %s\n", name); + f = fopen (name, "wb"); + if (!f) + Error ("Can't write %s\b", name); + + fprintf (f, "{\n\"classname\" \"worldspawn\"\n"); + + for (bn=0 ; bnnumsides ; i++) + { + s = brush->original_sides + i; + dist = mapplanes[s->planenum].dist; + for (j=0 ; j<3 ; j++) + dist += fabs( 16 * mapplanes[s->planenum].normal[j] ); + + w = BaseWindingForPlane (mapplanes[s->planenum].normal, dist); + + fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]); + fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]); + fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]); + + fprintf (f, "%s 0 0 0 1 1\n", texinfo[s->texinfo].texture); + FreeWinding (w); + } + fprintf (f, "}\n"); + } + fprintf (f, "}\n"); + + fclose (f); + + Error ("can't proceed after expanding brushes"); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/nodraw.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/nodraw.c new file mode 100644 index 00000000..888b2570 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/nodraw.c @@ -0,0 +1,46 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +vec3_t draw_mins, draw_maxs; +qboolean drawflag; + +void Draw_ClearWindow (void) +{ +} + +//============================================================ + +#define GLSERV_PORT 25001 + + +void GLS_BeginScene (void) +{ +} + +void GLS_Winding (winding_t *w, int code) +{ +} + +void GLS_EndScene (void) +{ +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/patches.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/patches.c new file mode 100644 index 00000000..2ff82315 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/patches.c @@ -0,0 +1,603 @@ +/* +Copyright (C) 1999-2006 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 "qrad.h" + +vec3_t texture_reflectivity[MAX_MAP_TEXINFO]; + +/* +=================================================================== + + TEXTURE LIGHT VALUES + +=================================================================== +*/ + +/* +====================== +CalcTextureReflectivity_Quake2 +====================== +*/ +void CalcTextureReflectivity_Quake2 (void) +{ + int i; + int j, k, texels; + int color[3]; + int texel; + byte *palette; + char path[1024]; + float r, scale; + miptex_t *mt; + + sprintf (path, "%spics/colormap.pcx", gamedir); + + // get the game palette + Load256Image (path, NULL, &palette, NULL, NULL); + + // allways set index 0 even if no textures + texture_reflectivity[0][0] = 0.5; + texture_reflectivity[0][1] = 0.5; + texture_reflectivity[0][2] = 0.5; + + for (i=0 ; iwidth)*LittleLong(mt->height); + color[0] = color[1] = color[2] = 0; + + for (j=0 ; joffsets[0]) + j]; + for (k=0 ; k<3 ; k++) + color[k] += palette[texel*3+k]; + } + + for (j=0 ; j<3 ; j++) + { + r = color[j]/texels/255.0; + texture_reflectivity[i][j] = r; + } + // scale the reflectivity up, because the textures are + // so dim + scale = ColorNormalize (texture_reflectivity[i], + texture_reflectivity[i]); + if (scale < 0.5) + { + scale *= 2; + VectorScale (texture_reflectivity[i], scale, texture_reflectivity[i]); + } +#if 0 +texture_reflectivity[i][0] = 0.5; +texture_reflectivity[i][1] = 0.5; +texture_reflectivity[i][2] = 0.5; +#endif + } +} + +/* +====================== +CalcTextureReflectivity_Heretic2 +====================== +*/ +void CalcTextureReflectivity_Heretic2 (void) +{ + int i; + int j, texels; + int color[3]; + int texel; + char path[1024]; + float r; + miptex_m8_t *mt; + miptex_m32_t *mt32; + byte *pos; + + + // allways set index 0 even if no textures + texture_reflectivity[0][0] = 0.5; + texture_reflectivity[0][1] = 0.5; + texture_reflectivity[0][2] = 0.5; + + for (i=0 ; iwidth[0])*LittleLong(mt->height[0]); + color[0] = color[1] = color[2] = 0; + + for (j=0 ; joffsets[0]) + j]; + color[0] += mt->palette[texel].r; + color[1] += mt->palette[texel].g; + color[2] += mt->palette[texel].b; + } + + free(mt); + } + else + { + texels = LittleLong(mt32->width[0])*LittleLong(mt32->height[0]); + color[0] = color[1] = color[2] = 0; + + for (j=0 ; joffsets[0] + (j<<2); + color[0] += *pos++; // r + color[1] += *pos++; // g + color[2] += *pos++; // b + } + + free(mt32); + } + + + for (j=0 ; j<3 ; j++) + { + r = color[j]/((float) texels*255.0); + texture_reflectivity[i][j] = r; + } + } +} + +/* +======================================================================= + +MAKE FACES + +======================================================================= +*/ + +/* +============= +WindingFromFace +============= +*/ +winding_t *WindingFromFace (dface_t *f) +{ + int i; + int se; + dvertex_t *dv; + int v; + winding_t *w; + + w = AllocWinding (f->numedges); + w->numpoints = f->numedges; + + for (i=0 ; inumedges ; i++) + { + se = dsurfedges[f->firstedge + i]; + if (se < 0) + v = dedges[-se].v[1]; + else + v = dedges[se].v[0]; + + dv = &dvertexes[v]; + VectorCopy (dv->point, w->p[i]); + } + + RemoveColinearPoints (w); + + return w; +} + +/* +============= +BaseLightForFace +============= +*/ +void BaseLightForFace (dface_t *f, vec3_t color) +{ + texinfo_t *tx; + + // + // check for light emited by texture + // + tx = &texinfo[f->texinfo]; + if (!(tx->flags & SURF_LIGHT) || tx->value == 0) + { + VectorClear (color); + return; + } + + VectorScale (texture_reflectivity[f->texinfo], tx->value, color); +} + +qboolean IsSky (dface_t *f) +{ + texinfo_t *tx; + + tx = &texinfo[f->texinfo]; + if (tx->flags & SURF_SKY) + return true; + return false; +} + +/* +============= +MakePatchForFace +============= +*/ +float totalarea; +void MakePatchForFace (int fn, winding_t *w) +{ + dface_t *f; + float area; + patch_t *patch; + dplane_t *pl; + int i; + vec3_t color; + dleaf_t *leaf; + + f = &dfaces[fn]; + + area = WindingArea (w); + totalarea += area; + + patch = &patches[num_patches]; + if (num_patches == MAX_PATCHES) + Error ("num_patches == MAX_PATCHES"); + patch->next = face_patches[fn]; + face_patches[fn] = patch; + + patch->winding = w; + + if (f->side) + patch->plane = &backplanes[f->planenum]; + else + patch->plane = &dplanes[f->planenum]; + if (face_offset[fn][0] || face_offset[fn][1] || face_offset[fn][2] ) + { // origin offset faces must create new planes + if (numplanes + fakeplanes >= MAX_MAP_PLANES) + Error ("numplanes + fakeplanes >= MAX_MAP_PLANES"); + pl = &dplanes[numplanes + fakeplanes]; + fakeplanes++; + + *pl = *(patch->plane); + pl->dist += DotProduct (face_offset[fn], pl->normal); + patch->plane = pl; + } + + WindingCenter (w, patch->origin); + VectorAdd (patch->origin, patch->plane->normal, patch->origin); + leaf = Rad_PointInLeaf(patch->origin); + patch->cluster = leaf->cluster; + if (patch->cluster == -1) + Sys_FPrintf( SYS_VRB, "patch->cluster == -1\n"); + + patch->area = area; + if (patch->area <= 1) + patch->area = 1; + patch->sky = IsSky (f); + + VectorCopy (texture_reflectivity[f->texinfo], patch->reflectivity); + + // non-bmodel patches can emit light + if (fn < dmodels[0].numfaces) + { + BaseLightForFace (f, patch->baselight); + + ColorNormalize (patch->reflectivity, color); + + for (i=0 ; i<3 ; i++) + patch->baselight[i] *= color[i]; + + VectorCopy (patch->baselight, patch->totallight); + } + num_patches++; +} + + +entity_t *EntityForModel (int modnum) +{ + int i; + char *s; + char name[16]; + + sprintf (name, "*%i", modnum); + // search the entities for one using modnum + for (i=0 ; inumfaces ; j++) + { + fn = mod->firstface + j; + face_entity[fn] = ent; + VectorCopy (origin, face_offset[fn]); + f = &dfaces[fn]; + w = WindingFromFace (f); + for (k=0 ; knumpoints ; k++) + { + VectorAdd (w->p[k], origin, w->p[k]); + } + MakePatchForFace (fn, w); + } + } + + Sys_FPrintf( SYS_VRB, "%i sqaure feet\n", (int)(totalarea/64)); +} + +/* +======================================================================= + +SUBDIVIDE + +======================================================================= +*/ + +void FinishSplit (patch_t *patch, patch_t *newp) +{ + dleaf_t *leaf; + + VectorCopy (patch->baselight, newp->baselight); + VectorCopy (patch->totallight, newp->totallight); + VectorCopy (patch->reflectivity, newp->reflectivity); + newp->plane = patch->plane; + newp->sky = patch->sky; + + patch->area = WindingArea (patch->winding); + newp->area = WindingArea (newp->winding); + + if (patch->area <= 1) + patch->area = 1; + if (newp->area <= 1) + newp->area = 1; + + WindingCenter (patch->winding, patch->origin); + VectorAdd (patch->origin, patch->plane->normal, patch->origin); + leaf = Rad_PointInLeaf(patch->origin); + patch->cluster = leaf->cluster; + if (patch->cluster == -1) + Sys_FPrintf( SYS_VRB, "patch->cluster == -1\n"); + + WindingCenter (newp->winding, newp->origin); + VectorAdd (newp->origin, newp->plane->normal, newp->origin); + leaf = Rad_PointInLeaf(newp->origin); + newp->cluster = leaf->cluster; + if (newp->cluster == -1) + Sys_FPrintf( SYS_VRB, "patch->cluster == -1\n"); +} + +/* +============= +SubdividePatch + +Chops the patch only if its local bounds exceed the max size +============= +*/ +void SubdividePatch (patch_t *patch) +{ + winding_t *w, *o1, *o2; + vec3_t mins, maxs, total; + vec3_t split; + vec_t dist; + int i, j; + vec_t v; + patch_t *newp; + + w = patch->winding; + mins[0] = mins[1] = mins[2] = 99999; + maxs[0] = maxs[1] = maxs[2] = -99999; + for (i=0 ; inumpoints ; 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; + } + } + VectorSubtract (maxs, mins, total); + for (i=0 ; i<3 ; i++) + if (total[i] > (subdiv+1) ) + break; + if (i == 3) + { + // no splitting needed + return; + } + + // + // split the winding + // + VectorCopy (vec3_origin, split); + split[i] = 1; + dist = (mins[i] + maxs[i])*0.5; + ClipWindingEpsilon (w, split, dist, ON_EPSILON, &o1, &o2); + + // + // create a new patch + // + if (num_patches == MAX_PATCHES) + Error ("MAX_PATCHES"); + newp = &patches[num_patches]; + num_patches++; + + newp->next = patch->next; + patch->next = newp; + + patch->winding = o1; + newp->winding = o2; + + FinishSplit (patch, newp); + + SubdividePatch (patch); + SubdividePatch (newp); +} + + +/* +============= +DicePatch + +Chops the patch by a global grid +============= +*/ +void DicePatch (patch_t *patch) +{ + winding_t *w, *o1, *o2; + vec3_t mins, maxs; + vec3_t split; + vec_t dist; + int i; + patch_t *newp; + + w = patch->winding; + WindingBounds (w, mins, maxs); + for (i=0 ; i<3 ; i++) + if (floor((mins[i]+1)/subdiv) < floor((maxs[i]-1)/subdiv)) + break; + if (i == 3) + { + // no splitting needed + return; + } + + // + // split the winding + // + VectorCopy (vec3_origin, split); + split[i] = 1; + dist = subdiv*(1+floor((mins[i]+1)/subdiv)); + ClipWindingEpsilon (w, split, dist, ON_EPSILON, &o1, &o2); + + // + // create a new patch + // + if (num_patches == MAX_PATCHES) + Error ("MAX_PATCHES"); + newp = &patches[num_patches]; + num_patches++; + + newp->next = patch->next; + patch->next = newp; + + patch->winding = o1; + newp->winding = o2; + + FinishSplit (patch, newp); + + DicePatch (patch); + DicePatch (newp); +} + + +/* +============= +SubdividePatches +============= +*/ +void SubdividePatches (void) +{ + int i, num; + + if (subdiv < 1) + return; + + num = num_patches; // because the list will grow + for (i=0 ; i c_peak_portals) + c_peak_portals = c_active_portals; + + p = malloc (sizeof(portal_t)); + memset (p, 0, sizeof(portal_t)); + + return p; +} + +void FreePortal (portal_t *p) +{ + if (p->winding) + FreeWinding (p->winding); + if (numthreads == 1) + c_active_portals--; + free (p); +} + +//============================================================== + +/* +============== +VisibleContents + +Returns the single content bit of the +strongest visible content present +============== +*/ +int VisibleContents (int contents) +{ + int i; + + for (i=1 ; i<=LAST_VISIBLE_CONTENTS ; i<<=1) + if (contents & i ) + return i; + + return 0; +} + + +/* +=============== +ClusterContents +=============== +*/ +int ClusterContents (node_t *node) +{ + int c1, c2, c; + + if (node->planenum == PLANENUM_LEAF) + return node->contents; + + c1 = ClusterContents(node->children[0]); + c2 = ClusterContents(node->children[1]); + c = c1|c2; + + // a cluster may include some solid detail areas, but + // still be seen into + if ( ! (c1&CONTENTS_SOLID) || ! (c2&CONTENTS_SOLID) ) + c &= ~CONTENTS_SOLID; + return c; +} + +/* +============= +Portal_VisFlood + +Returns true if the portal is empty or translucent, allowing +the PVS calculation to see through it. +The nodes on either side of the portal may actually be clusters, +not leafs, so all contents should be ored together +============= +*/ +qboolean Portal_VisFlood (portal_t *p) +{ + int c1, c2; + + if (!p->onnode) + return false; // to global outsideleaf + + c1 = ClusterContents(p->nodes[0]); + c2 = ClusterContents(p->nodes[1]); + + if (!VisibleContents (c1^c2)) + return true; + + if (c1 & (CONTENTS_TRANSLUCENT|CONTENTS_DETAIL)) + c1 = 0; + if (c2 & (CONTENTS_TRANSLUCENT|CONTENTS_DETAIL)) + c2 = 0; + + if ( (c1|c2) & CONTENTS_SOLID ) + return false; // can't see through solid + + if (! (c1 ^ c2)) + return true; // identical on both sides + + if (!VisibleContents (c1^c2)) + return true; + return false; +} + + +/* +=============== +Portal_EntityFlood + +The entity flood determines which areas are +"outside" on the map, which are then filled in. +Flowing from side s to side !s +=============== +*/ +qboolean Portal_EntityFlood (portal_t *p, int s) +{ + if (p->nodes[0]->planenum != PLANENUM_LEAF + || p->nodes[1]->planenum != PLANENUM_LEAF) + Error ("Portal_EntityFlood: not a leaf"); + + // can never cross to a solid + if ( (p->nodes[0]->contents & CONTENTS_SOLID) + || (p->nodes[1]->contents & CONTENTS_SOLID) ) + return false; + + // can flood through everything else + return true; +} + + +//============================================================================= + +int c_tinyportals; + +/* +============= +AddPortalToNodes +============= +*/ +void AddPortalToNodes (portal_t *p, node_t *front, node_t *back) +{ + if (p->nodes[0] || p->nodes[1]) + Error ("AddPortalToNode: allready included"); + + p->nodes[0] = front; + p->next[0] = front->portals; + front->portals = p; + + p->nodes[1] = back; + p->next[1] = back->portals; + back->portals = p; +} + + +/* +============= +RemovePortalFromNode +============= +*/ +void RemovePortalFromNode (portal_t *portal, node_t *l) +{ + portal_t **pp, *t; + +// remove reference to the current portal + pp = &l->portals; + while (1) + { + t = *pp; + if (!t) + Error ("RemovePortalFromNode: portal not in leaf"); + + if ( t == portal ) + break; + + if (t->nodes[0] == l) + pp = &t->next[0]; + else if (t->nodes[1] == l) + pp = &t->next[1]; + else + Error ("RemovePortalFromNode: portal not bounding leaf"); + } + + if (portal->nodes[0] == l) + { + *pp = portal->next[0]; + portal->nodes[0] = NULL; + } + else if (portal->nodes[1] == l) + { + *pp = portal->next[1]; + portal->nodes[1] = NULL; + } +} + +//============================================================================ + +void PrintPortal (portal_t *p) +{ + int i; + winding_t *w; + + w = p->winding; + for (i=0 ; inumpoints ; i++) + Sys_Printf ("(%5.0f,%5.0f,%5.0f)\n",w->p[i][0] + , w->p[i][1], w->p[i][2]); +} + +/* +================ +MakeHeadnodePortals + +The created portals will face the global outside_node +================ +*/ +#define SIDESPACE 8 +void MakeHeadnodePortals (tree_t *tree) +{ + vec3_t bounds[2]; + int i, j, n; + portal_t *p, *portals[6]; + plane_t bplanes[6], *pl; + node_t *node; + + node = tree->headnode; + +// pad with some space so there will never be null volume leafs + for (i=0 ; i<3 ; i++) + { + bounds[0][i] = tree->mins[i] - SIDESPACE; + bounds[1][i] = tree->maxs[i] + SIDESPACE; + } + + tree->outside_node.planenum = PLANENUM_LEAF; + tree->outside_node.brushlist = NULL; + tree->outside_node.portals = NULL; + tree->outside_node.contents = 0; + + for (i=0 ; i<3 ; i++) + for (j=0 ; j<2 ; j++) + { + n = j*3 + i; + + p = AllocPortal (); + portals[n] = p; + + pl = &bplanes[n]; + memset (pl, 0, sizeof(*pl)); + if (j) + { + pl->normal[i] = -1; + pl->dist = -bounds[j][i]; + } + else + { + pl->normal[i] = 1; + pl->dist = bounds[j][i]; + } + p->plane = *pl; + p->winding = BaseWindingForPlane (pl->normal, pl->dist); + AddPortalToNodes (p, node, &tree->outside_node); + } + +// clip the basewindings by all the other planes + for (i=0 ; i<6 ; i++) + { + for (j=0 ; j<6 ; j++) + { + if (j == i) + continue; + ChopWindingInPlace (&portals[i]->winding, bplanes[j].normal, bplanes[j].dist, ON_EPSILON); + } + } +} + +//=================================================== + + +/* +================ +BaseWindingForNode +================ +*/ +#define BASE_WINDING_EPSILON 0.001 +#define SPLIT_WINDING_EPSILON 0.001 + +winding_t *BaseWindingForNode (node_t *node) +{ + winding_t *w; + node_t *n; + plane_t *plane; + vec3_t normal; + vec_t dist; + + w = BaseWindingForPlane (mapplanes[node->planenum].normal + , mapplanes[node->planenum].dist); + + // clip by all the parents + for (n=node->parent ; n && w ; ) + { + plane = &mapplanes[n->planenum]; + + if (n->children[0] == node) + { // take front + ChopWindingInPlace (&w, plane->normal, plane->dist, BASE_WINDING_EPSILON); + } + else + { // take back + VectorSubtract (vec3_origin, plane->normal, normal); + dist = -plane->dist; + ChopWindingInPlace (&w, normal, dist, BASE_WINDING_EPSILON); + } + node = n; + n = n->parent; + } + + return w; +} + +//============================================================ + +qboolean WindingIsTiny (winding_t *w); + +/* +================== +MakeNodePortal + +create the new portal by taking the full plane winding for the cutting plane +and clipping it by all of parents of this node +================== +*/ +void MakeNodePortal (node_t *node) +{ + portal_t *new_portal, *p; + winding_t *w; + vec3_t normal; + float dist; + int side; + + w = BaseWindingForNode (node); + + // clip the portal by all the other portals in the node + for (p = node->portals ; p && w; p = p->next[side]) + { + if (p->nodes[0] == node) + { + side = 0; + VectorCopy (p->plane.normal, normal); + dist = p->plane.dist; + } + else if (p->nodes[1] == node) + { + side = 1; + VectorSubtract (vec3_origin, p->plane.normal, normal); + dist = -p->plane.dist; + } + else + Error ("CutNodePortals_r: mislinked portal"); + + ChopWindingInPlace (&w, normal, dist, 0.1); + } + + if (!w) + { + return; + } + + if (WindingIsTiny (w)) + { + c_tinyportals++; + FreeWinding (w); + return; + } + + + new_portal = AllocPortal (); + new_portal->plane = mapplanes[node->planenum]; + new_portal->onnode = node; + new_portal->winding = w; + AddPortalToNodes (new_portal, node->children[0], node->children[1]); +} + + +/* +============== +SplitNodePortals + +Move or split the portals that bound node so that the node's +children have portals instead of node. +============== +*/ +void SplitNodePortals (node_t *node) +{ + portal_t *p, *next_portal, *new_portal; + node_t *f, *b, *other_node; + int side; + plane_t *plane; + winding_t *frontwinding, *backwinding; + + plane = &mapplanes[node->planenum]; + f = node->children[0]; + b = node->children[1]; + + for (p = node->portals ; p ; p = next_portal) + { + if (p->nodes[0] == node) + side = 0; + else if (p->nodes[1] == node) + side = 1; + else + Error ("CutNodePortals_r: mislinked portal"); + next_portal = p->next[side]; + + other_node = p->nodes[!side]; + RemovePortalFromNode (p, p->nodes[0]); + RemovePortalFromNode (p, p->nodes[1]); + +// +// cut the portal into two portals, one on each side of the cut plane +// + ClipWindingEpsilon (p->winding, plane->normal, plane->dist, + SPLIT_WINDING_EPSILON, &frontwinding, &backwinding); + + if (frontwinding && WindingIsTiny(frontwinding)) + { + FreeWinding (frontwinding); + frontwinding = NULL; + c_tinyportals++; + } + + if (backwinding && WindingIsTiny(backwinding)) + { + FreeWinding (backwinding); + backwinding = NULL; + c_tinyportals++; + } + + if (!frontwinding && !backwinding) + { // tiny windings on both sides + continue; + } + + if (!frontwinding) + { + FreeWinding (backwinding); + if (side == 0) + AddPortalToNodes (p, b, other_node); + else + AddPortalToNodes (p, other_node, b); + continue; + } + if (!backwinding) + { + FreeWinding (frontwinding); + if (side == 0) + AddPortalToNodes (p, f, other_node); + else + AddPortalToNodes (p, other_node, f); + continue; + } + + // the winding is split + new_portal = AllocPortal (); + *new_portal = *p; + new_portal->winding = backwinding; + FreeWinding (p->winding); + p->winding = frontwinding; + + if (side == 0) + { + AddPortalToNodes (p, f, other_node); + AddPortalToNodes (new_portal, b, other_node); + } + else + { + AddPortalToNodes (p, other_node, f); + AddPortalToNodes (new_portal, other_node, b); + } + } + + node->portals = NULL; +} + + +/* +================ +CalcNodeBounds +================ +*/ +void CalcNodeBounds (node_t *node) +{ + portal_t *p; + int s; + int i; + + // calc mins/maxs for both leafs and nodes + ClearBounds (node->mins, node->maxs); + for (p = node->portals ; p ; p = p->next[s]) + { + s = (p->nodes[1] == node); + for (i=0 ; iwinding->numpoints ; i++) + AddPointToBounds (p->winding->p[i], node->mins, node->maxs); + } +} + + +/* +================== +MakeTreePortals_r +================== +*/ +void MakeTreePortals_r (node_t *node) +{ + int i; + + CalcNodeBounds (node); + if (node->mins[0] >= node->maxs[0]) + { + Sys_Printf ("WARNING: node without a volume\n"); + } + + for (i=0 ; i<3 ; i++) + { + if (node->mins[i] < -8000 || node->maxs[i] > 8000) + { + Sys_Printf ("WARNING: node with unbounded volume\n"); + break; + } + } + if (node->planenum == PLANENUM_LEAF) + return; + + MakeNodePortal (node); + SplitNodePortals (node); + + MakeTreePortals_r (node->children[0]); + MakeTreePortals_r (node->children[1]); +} + +/* +================== +MakeTreePortals +================== +*/ +void MakeTreePortals (tree_t *tree) +{ + MakeHeadnodePortals (tree); + MakeTreePortals_r (tree->headnode); +} + +/* +========================================================= + +FLOOD ENTITIES + +========================================================= +*/ + +/* +============= +FloodPortals_r +============= +*/ +void FloodPortals_r (node_t *node, int dist) +{ + portal_t *p; + int s; + + node->occupied = dist; + + for (p=node->portals ; p ; p = p->next[s]) + { + s = (p->nodes[1] == node); + + if (p->nodes[!s]->occupied) + continue; + + if (!Portal_EntityFlood (p, s)) + continue; + + FloodPortals_r (p->nodes[!s], dist+1); + } +} + +/* +============= +PlaceOccupant +============= +*/ +qboolean PlaceOccupant (node_t *headnode, vec3_t origin, entity_t *occupant) +{ + node_t *node; + vec_t d; + plane_t *plane; + + // find the leaf to start in + node = headnode; + while (node->planenum != PLANENUM_LEAF) + { + plane = &mapplanes[node->planenum]; + d = DotProduct (origin, plane->normal) - plane->dist; + if (d >= 0) + node = node->children[0]; + else + node = node->children[1]; + } + + if (node->contents == CONTENTS_SOLID) + return false; + node->occupant = occupant; + + FloodPortals_r (node, 1); + + return true; +} + +/* +============= +FloodEntities + +Marks all nodes that can be reached by entites +============= +*/ +qboolean FloodEntities (tree_t *tree) +{ + int i; + vec3_t origin; + char *cl; + qboolean inside; + node_t *headnode; + + headnode = tree->headnode; + Sys_FPrintf( SYS_VRB, "--- FloodEntities ---\n"); + inside = false; + tree->outside_node.occupied = 0; + + for (i=1 ; ioutside_node.occupied) + { + Sys_FPrintf( SYS_VRB, "entity reached from outside -- no filling\n"); + } + + return (qboolean)(inside && !tree->outside_node.occupied); +} + +/* +========================================================= + +FLOOD AREAS + +========================================================= +*/ + +int c_areas; + +/* +============= +FloodAreas_r +============= +*/ +void FloodAreas_r (node_t *node) +{ + portal_t *p; + int s; + bspbrush_t *b; + entity_t *e; + + if (node->contents == CONTENTS_AREAPORTAL) + { + // this node is part of an area portal + b = node->brushlist; + e = &entities[b->original->entitynum]; + + // if the current area has allready touched this + // portal, we are done + if (e->portalareas[0] == c_areas || e->portalareas[1] == c_areas) + return; + + // note the current area as bounding the portal + if (e->portalareas[1]) + { + Sys_Printf ("WARNING: areaportal entity %i touches > 2 areas\n", b->original->entitynum); + return; + } + if (e->portalareas[0]) + e->portalareas[1] = c_areas; + else + e->portalareas[0] = c_areas; + + return; + } + + if (node->area) + return; // allready got it + node->area = c_areas; + + for (p=node->portals ; p ; p = p->next[s]) + { + s = (p->nodes[1] == node); +#if 0 + if (p->nodes[!s]->occupied) + continue; +#endif + if (!Portal_EntityFlood (p, s)) + continue; + + FloodAreas_r (p->nodes[!s]); + } +} + +/* +============= +FindAreas_r + +Just decend the tree, and for each node that hasn't had an +area set, flood fill out from there +============= +*/ +void FindAreas_r (node_t *node) +{ + if (node->planenum != PLANENUM_LEAF) + { + FindAreas_r (node->children[0]); + FindAreas_r (node->children[1]); + return; + } + + if (node->area) + return; // allready got it + + if (node->contents & CONTENTS_SOLID) + return; + + if (!node->occupied) + return; // not reachable by entities + + // area portals are allways only flooded into, never + // out of + if (node->contents == CONTENTS_AREAPORTAL) + return; + + c_areas++; + FloodAreas_r (node); +} + +/* +============= +SetAreaPortalAreas_r + +Just decend the tree, and for each node that hasn't had an +area set, flood fill out from there +============= +*/ +void SetAreaPortalAreas_r (node_t *node) +{ + bspbrush_t *b; + entity_t *e; + + if (node->planenum != PLANENUM_LEAF) + { + SetAreaPortalAreas_r (node->children[0]); + SetAreaPortalAreas_r (node->children[1]); + return; + } + + if (node->contents == CONTENTS_AREAPORTAL) + { + if (node->area) + return; // allready set + + b = node->brushlist; + e = &entities[b->original->entitynum]; + node->area = e->portalareas[0]; + if (!e->portalareas[1]) + { + Sys_Printf ("WARNING: areaportal entity %i doesn't touch two areas\n", b->original->entitynum); + return; + } + } +} + +/* +============= +EmitAreaPortals + +============= +*/ +void EmitAreaPortals (node_t *headnode) +{ + int i, j; + entity_t *e; + dareaportal_t *dp; + + if (c_areas > MAX_MAP_AREAS) + Error ("MAX_MAP_AREAS"); + numareas = c_areas+1; + numareaportals = 1; // leave 0 as an error + + for (i=1 ; i<=c_areas ; i++) + { + dareas[i].firstareaportal = numareaportals; + for (j=0 ; jareaportalnum) + continue; + dp = &dareaportals[numareaportals]; + if (e->portalareas[0] == i) + { + dp->portalnum = e->areaportalnum; + dp->otherarea = e->portalareas[1]; + numareaportals++; + } + else if (e->portalareas[1] == i) + { + dp->portalnum = e->areaportalnum; + dp->otherarea = e->portalareas[0]; + numareaportals++; + } + } + dareas[i].numareaportals = numareaportals - dareas[i].firstareaportal; + } + + Sys_FPrintf( SYS_VRB, "%5i numareas\n", numareas); + Sys_FPrintf( SYS_VRB, "%5i numareaportals\n", numareaportals); +} + +/* +============= +FloodAreas + +Mark each leaf with an area, bounded by CONTENTS_AREAPORTAL +============= +*/ +void FloodAreas (tree_t *tree) +{ + Sys_FPrintf( SYS_VRB, "--- FloodAreas ---\n"); + FindAreas_r (tree->headnode); + SetAreaPortalAreas_r (tree->headnode); + Sys_FPrintf( SYS_VRB, "%5i areas\n", c_areas); +} + +//====================================================== + +int c_outside; +int c_inside; +int c_solid; + +void FillOutside_r (node_t *node) +{ + if (node->planenum != PLANENUM_LEAF) + { + FillOutside_r (node->children[0]); + FillOutside_r (node->children[1]); + return; + } + + // anything not reachable by an entity + // can be filled away + if (!node->occupied) + { + if (node->contents != CONTENTS_SOLID) + { + c_outside++; + node->contents = CONTENTS_SOLID; + } + else + c_solid++; + } + else + c_inside++; + +} + +/* +============= +FillOutside + +Fill all nodes that can't be reached by entities +============= +*/ +void FillOutside (node_t *headnode) +{ + c_outside = 0; + c_inside = 0; + c_solid = 0; + Sys_FPrintf( SYS_VRB, "--- FillOutside ---\n"); + FillOutside_r (headnode); + Sys_FPrintf( SYS_VRB, "%5i solid leafs\n", c_solid); + Sys_FPrintf( SYS_VRB, "%5i leafs filled\n", c_outside); + Sys_FPrintf( SYS_VRB, "%5i inside leafs\n", c_inside); +} + + +//============================================================== + +/* +============ +FindPortalSide + +Finds a brush side to use for texturing the given portal +============ +*/ +void FindPortalSide (portal_t *p) +{ + int viscontents; + bspbrush_t *bb; + mapbrush_t *brush; + node_t *n; + int i,j; + int planenum; + side_t *side, *bestside; + float dot, bestdot; + plane_t *p1, *p2; + + // decide which content change is strongest + // solid > lava > water, etc + viscontents = VisibleContents (p->nodes[0]->contents ^ p->nodes[1]->contents); + if (!viscontents) + return; + + planenum = p->onnode->planenum; + bestside = NULL; + bestdot = 0; + + for (j=0 ; j<2 ; j++) + { + n = p->nodes[j]; + p1 = &mapplanes[p->onnode->planenum]; + for (bb=n->brushlist ; bb ; bb=bb->next) + { + brush = bb->original; + if ( !(brush->contents & viscontents) ) + continue; + for (i=0 ; inumsides ; i++) + { + side = &brush->original_sides[i]; + if (side->bevel) + continue; + if (side->texinfo == TEXINFO_NODE) + continue; // non-visible + if ((side->planenum&~1) == planenum) + { // exact match + bestside = &brush->original_sides[i]; + goto gotit; + } + // see how close the match is + p2 = &mapplanes[side->planenum&~1]; + dot = DotProduct (p1->normal, p2->normal); + if (dot > bestdot) + { + bestdot = dot; + bestside = side; + } + } + } + } + +gotit: + if (!bestside) + Sys_FPrintf( SYS_VRB, "WARNING: side not found for portal\n"); + + p->sidefound = true; + p->side = bestside; +} + + +/* +=============== +MarkVisibleSides_r + +=============== +*/ +void MarkVisibleSides_r (node_t *node) +{ + portal_t *p; + int s; + + if (node->planenum != PLANENUM_LEAF) + { + MarkVisibleSides_r (node->children[0]); + MarkVisibleSides_r (node->children[1]); + return; + } + + // empty leafs are never boundary leafs + if (!node->contents) + return; + + // see if there is a visible face + for (p=node->portals ; p ; p = p->next[!s]) + { + s = (p->nodes[0] == node); + if (!p->onnode) + continue; // edge of world + if (!p->sidefound) + FindPortalSide (p); + if (p->side) + p->side->visible = true; + } + +} + +/* +============= +MarkVisibleSides + +============= +*/ +void MarkVisibleSides (tree_t *tree, int startbrush, int endbrush) +{ + int i, j; + mapbrush_t *mb; + int numsides; + + Sys_FPrintf( SYS_VRB, "--- MarkVisibleSides ---\n"); + + // clear all the visible flags + for (i=startbrush ; inumsides; + for (j=0 ; joriginal_sides[j].visible = false; + } + + // set visible flags on the sides that are used by portals + MarkVisibleSides_r (tree->headnode); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/prtfile.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/prtfile.c new file mode 100644 index 00000000..790db065 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/prtfile.c @@ -0,0 +1,286 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +/* +============================================================================== + +PORTAL FILE GENERATION + +Save out name.prt for qvis to read +============================================================================== +*/ + + +#define PORTALFILE "PRT1" + +FILE *pf; +int num_visclusters; // clusters the player can be in +int num_visportals; + +void WriteFloat (FILE *f, vec_t v) +{ + if ( fabs(v - Q_rint(v)) < 0.001 ) + fprintf (f,"%i ",(int)Q_rint(v)); + else + fprintf (f,"%f ",v); +} + +/* +================= +WritePortalFile_r +================= +*/ +void WritePortalFile_r (node_t *node) +{ + int i, s; + portal_t *p; + winding_t *w; + vec3_t normal; + vec_t dist; + + // decision node + if (node->planenum != PLANENUM_LEAF && !node->detail_seperator) + { + WritePortalFile_r (node->children[0]); + WritePortalFile_r (node->children[1]); + return; + } + + if (node->contents & CONTENTS_SOLID) + return; + + for (p = node->portals ; p ; p=p->next[s]) + { + w = p->winding; + s = (p->nodes[1] == node); + if (w && p->nodes[0] == node) + { + if (!Portal_VisFlood (p)) + continue; + // write out to the file + + // sometimes planes get turned around when they are very near + // the changeover point between different axis. interpret the + // plane the same way vis will, and flip the side orders if needed + // FIXME: is this still relevent? + WindingPlane (w, normal, &dist); + if ( DotProduct (p->plane.normal, normal) < 0.99 ) + { // backwards... + fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[1]->cluster, p->nodes[0]->cluster); + } + else + fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[0]->cluster, p->nodes[1]->cluster); + for (i=0 ; inumpoints ; i++) + { + fprintf (pf,"("); + WriteFloat (pf, w->p[i][0]); + WriteFloat (pf, w->p[i][1]); + WriteFloat (pf, w->p[i][2]); + fprintf (pf,") "); + } + fprintf (pf,"\n"); + } + } + +} + +/* +================ +FillLeafNumbers_r + +All of the leafs under node will have the same cluster +================ +*/ +void FillLeafNumbers_r (node_t *node, int num) +{ + if (node->planenum == PLANENUM_LEAF) + { + if (node->contents & CONTENTS_SOLID) + node->cluster = -1; + else + node->cluster = num; + return; + } + node->cluster = num; + FillLeafNumbers_r (node->children[0], num); + FillLeafNumbers_r (node->children[1], num); +} + +/* +================ +NumberLeafs_r +================ +*/ +void NumberLeafs_r (node_t *node) +{ + portal_t *p; + + if (node->planenum != PLANENUM_LEAF && !node->detail_seperator) + { // decision node + node->cluster = -99; + NumberLeafs_r (node->children[0]); + NumberLeafs_r (node->children[1]); + return; + } + + // either a leaf or a detail cluster + + if ( node->contents & CONTENTS_SOLID ) + { // solid block, viewpoint never inside + node->cluster = -1; + return; + } + + FillLeafNumbers_r (node, num_visclusters); + num_visclusters++; + + // count the portals + for (p = node->portals ; p ; ) + { + if (p->nodes[0] == node) // only write out from first leaf + { + if (Portal_VisFlood (p)) + num_visportals++; + p = p->next[0]; + } + else + p = p->next[1]; + } + +} + + +/* +================ +CreateVisPortals_r +================ +*/ +void CreateVisPortals_r (node_t *node) +{ + // stop as soon as we get to a detail_seperator, which + // means that everything below is in a single cluster + if (node->planenum == PLANENUM_LEAF || node->detail_seperator ) + return; + + MakeNodePortal (node); + SplitNodePortals (node); + + CreateVisPortals_r (node->children[0]); + CreateVisPortals_r (node->children[1]); +} + +/* +================ +FinishVisPortals_r +================ +*/ +void FinishVisPortals2_r (node_t *node) +{ + if (node->planenum == PLANENUM_LEAF) + return; + + MakeNodePortal (node); + SplitNodePortals (node); + + FinishVisPortals2_r (node->children[0]); + FinishVisPortals2_r (node->children[1]); +} + +void FinishVisPortals_r (node_t *node) +{ + if (node->planenum == PLANENUM_LEAF) + return; + + if (node->detail_seperator) + { + FinishVisPortals2_r (node); + return; + } + + FinishVisPortals_r (node->children[0]); + FinishVisPortals_r (node->children[1]); +} + + +int clusterleaf; +void SaveClusters_r (node_t *node) +{ + if (node->planenum == PLANENUM_LEAF) + { + dleafs[clusterleaf++].cluster = node->cluster; + return; + } + SaveClusters_r (node->children[0]); + SaveClusters_r (node->children[1]); +} + +/* +================ +WritePortalFile +================ +*/ +void WritePortalFile (tree_t *tree) +{ + char filename[1024]; + node_t *headnode; + + Sys_FPrintf( SYS_VRB, "--- WritePortalFile ---\n"); + + headnode = tree->headnode; + num_visclusters = 0; + num_visportals = 0; + + FreeTreePortals_r (headnode); + + MakeHeadnodePortals (tree); + + CreateVisPortals_r (headnode); + +// set the cluster field in every leaf and count the total number of portals + + NumberLeafs_r (headnode); + +// write the file + sprintf (filename, "%s.prt", source); + Sys_Printf ("writing %s\n", filename); + pf = fopen (filename, "w"); + if (!pf) + Error ("Error opening %s", filename); + + fprintf (pf, "%s\n", PORTALFILE); + fprintf (pf, "%i\n", num_visclusters); + fprintf (pf, "%i\n", num_visportals); + + Sys_FPrintf( SYS_VRB, "%5i visclusters\n", num_visclusters); + Sys_FPrintf( SYS_VRB, "%5i visportals\n", num_visportals); + + WritePortalFile_r (headnode); + + fclose (pf); + + // we need to store the clusters out now because ordering + // issues made us do this after writebsp... + clusterleaf = 1; + SaveClusters_r (headnode); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/q2map.h b/misc/mediasource/netradiant-src/tools/quake2/q2map/q2map.h new file mode 100644 index 00000000..331b35df --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/q2map.h @@ -0,0 +1,50 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// q2map.h + +/* platform-specific */ +#if defined( __linux__ ) || defined( __APPLE__ ) + #define Q_UNIX +#endif + +#ifdef Q_UNIX + #include + #include + #include +#endif + +#ifdef WIN32 + #include +#endif + +#include + +#include "cmdlib.h" +#include "mathlib.h" +#include "scriplib.h" +#include "polylib.h" +#include "q2_threads.h" +#include "bspfile.h" +#include "inout.h" + +int BSP_Main (); +int VIS_Main (); +int RAD_Main (); diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/qbsp.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/qbsp.c new file mode 100644 index 00000000..2809390c --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/qbsp.c @@ -0,0 +1,426 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// csg4.c + +#include "qbsp.h" + +extern float subdivide_size; + +char source[1024]; +char name[1024]; + +vec_t microvolume = 1.0; +qboolean noprune; +qboolean glview; +qboolean nodetail; +qboolean fulldetail; +qboolean onlyents; +qboolean nomerge; +qboolean nowater; +qboolean nofill; +qboolean nocsg; +qboolean noweld; +qboolean noshare; +qboolean nosubdiv; +qboolean notjunc; +qboolean noopt; +qboolean leaktest; +qboolean verboseentities; + +char outbase[32]; + +int block_xl = -8, block_xh = 7, block_yl = -8, block_yh = 7; + +int entity_num; + + +node_t *block_nodes[10][10]; + + +/* +============ +BlockTree + +============ +*/ +node_t *BlockTree (int xl, int yl, int xh, int yh) +{ + node_t *node; + vec3_t normal; + float dist; + int mid; + + if (xl == xh && yl == yh) + { + node = block_nodes[xl+5][yl+5]; + if (!node) + { // return an empty leaf + node = AllocNode (); + node->planenum = PLANENUM_LEAF; + node->contents = 0; //CONTENTS_SOLID; + return node; + } + return node; + } + + // create a seperator along the largest axis + node = AllocNode (); + + if (xh - xl > yh - yl) + { // split x axis + mid = xl + (xh-xl)/2 + 1; + normal[0] = 1; + normal[1] = 0; + normal[2] = 0; + dist = mid*1024; + node->planenum = FindFloatPlane (normal, dist); + node->children[0] = BlockTree ( mid, yl, xh, yh); + node->children[1] = BlockTree ( xl, yl, mid-1, yh); + } + else + { + mid = yl + (yh-yl)/2 + 1; + normal[0] = 0; + normal[1] = 1; + normal[2] = 0; + dist = mid*1024; + node->planenum = FindFloatPlane (normal, dist); + node->children[0] = BlockTree ( xl, mid, xh, yh); + node->children[1] = BlockTree ( xl, yl, xh, mid-1); + } + + return node; +} + +/* +============ +ProcessBlock_Thread + +============ +*/ +int brush_start, brush_end; +void ProcessBlock_Thread (int blocknum) +{ + int xblock, yblock; + vec3_t mins, maxs; + bspbrush_t *brushes; + tree_t *tree; + node_t *node; + + yblock = block_yl + blocknum / (block_xh-block_xl+1); + xblock = block_xl + blocknum % (block_xh-block_xl+1); + + Sys_FPrintf( SYS_VRB, "############### block %2i,%2i ###############\n", xblock, yblock); + + mins[0] = xblock*1024; + mins[1] = yblock*1024; + mins[2] = -4096; + maxs[0] = (xblock+1)*1024; + maxs[1] = (yblock+1)*1024; + maxs[2] = 4096; + + // the makelist and chopbrushes could be cached between the passes... + brushes = MakeBspBrushList (brush_start, brush_end, mins, maxs); + if (!brushes) + { + node = AllocNode (); + node->planenum = PLANENUM_LEAF; + node->contents = CONTENTS_SOLID; + block_nodes[xblock+5][yblock+5] = node; + return; + } + + if (!nocsg) + brushes = ChopBrushes (brushes); + + tree = BrushBSP (brushes, mins, maxs); + + block_nodes[xblock+5][yblock+5] = tree->headnode; +} + +/* +============ +ProcessWorldModel + +============ +*/ +void ProcessWorldModel (void) +{ + entity_t *e; + tree_t *tree; + qboolean leaked; + qboolean optimize; + xmlNodePtr polyline, leaknode; + char level[ 2 ]; + + e = &entities[entity_num]; + + brush_start = e->firstbrush; + brush_end = brush_start + e->numbrushes; + leaked = false; + + // + // perform per-block operations + // + if (block_xh * 1024 > map_maxs[0]) + block_xh = floor(map_maxs[0]/1024.0); + if ( (block_xl+1) * 1024 < map_mins[0]) + block_xl = floor(map_mins[0]/1024.0); + if (block_yh * 1024 > map_maxs[1]) + block_yh = floor(map_maxs[1]/1024.0); + if ( (block_yl+1) * 1024 < map_mins[1]) + block_yl = floor(map_mins[1]/1024.0); + + if (block_xl <-4) + block_xl = -4; + if (block_yl <-4) + block_yl = -4; + if (block_xh > 3) + block_xh = 3; + if (block_yh > 3) + block_yh = 3; + + for (optimize = false ; optimize <= true ; optimize++) + { + Sys_FPrintf( SYS_VRB, "--------------------------------------------\n"); + + RunThreadsOnIndividual ((block_xh-block_xl+1)*(block_yh-block_yl+1), + !verbose, ProcessBlock_Thread); + + // + // build the division tree + // oversizing the blocks guarantees that all the boundaries + // will also get nodes. + // + + Sys_FPrintf( SYS_VRB, "--------------------------------------------\n"); + + tree = AllocTree (); + tree->headnode = BlockTree (block_xl-1, block_yl-1, block_xh+1, block_yh+1); + + tree->mins[0] = (block_xl)*1024; + tree->mins[1] = (block_yl)*1024; + tree->mins[2] = map_mins[2] - 8; + + tree->maxs[0] = (block_xh+1)*1024; + tree->maxs[1] = (block_yh+1)*1024; + tree->maxs[2] = map_maxs[2] + 8; + + // + // perform the global operations + // + MakeTreePortals (tree); + + if (FloodEntities (tree)) + FillOutside (tree->headnode); + else + { + + Sys_FPrintf( SYS_NOXML, "**********************\n" ); + Sys_FPrintf( SYS_NOXML, "******* leaked *******\n" ); + Sys_FPrintf( SYS_NOXML, "**********************\n" ); + polyline = LeakFile( tree ); + leaknode = xmlNewNode( NULL, "message" ); + xmlNodeSetContent( leaknode, "MAP LEAKED\n" ); + xmlAddChild( leaknode, polyline ); + level[0] = (int) '0' + SYS_ERR; + level[1] = 0; + xmlSetProp( leaknode, "level", (char*) &level ); + xml_SendNode( leaknode ); + if( leaktest ) + { + Sys_Printf ("--- MAP LEAKED, ABORTING LEAKTEST ---\n"); + exit( 0 ); + } + leaked = true; +/* + Sys_Printf ("**** leaked ****\n"); + leaked = true; + LeakFile (tree); + if (leaktest) + { + Sys_Printf ("--- MAP LEAKED ---\n"); + exit (0); + } */ + } + + MarkVisibleSides (tree, brush_start, brush_end); + if (noopt || leaked) + break; + if (!optimize) + { + FreeTree (tree); + } + } + + FloodAreas (tree); + if (glview) + WriteGLView (tree, source); + MakeFaces (tree->headnode); + FixTjuncs (tree->headnode); + + if (!noprune) + PruneNodes (tree->headnode); + + WriteBSP (tree->headnode); + + if (!leaked) + WritePortalFile (tree); + + FreeTree (tree); +} + +/* +============ +ProcessSubModel + +============ +*/ +void ProcessSubModel (void) +{ + entity_t *e; + int start, end; + tree_t *tree; + bspbrush_t *list; + vec3_t mins, maxs; + + e = &entities[entity_num]; + + start = e->firstbrush; + end = start + e->numbrushes; + + mins[0] = mins[1] = mins[2] = -4096; + maxs[0] = maxs[1] = maxs[2] = 4096; + list = MakeBspBrushList (start, end, mins, maxs); + if (!nocsg) + list = ChopBrushes (list); + tree = BrushBSP (list, mins, maxs); + MakeTreePortals (tree); + MarkVisibleSides (tree, start, end); + MakeFaces (tree->headnode); + FixTjuncs (tree->headnode); + WriteBSP (tree->headnode); + FreeTree (tree); +} + +/* +============ +ProcessModels +============ +*/ +void ProcessModels (void) +{ + BeginBSPFile (); + + for (entity_num=0 ; entity_num< num_entities ; entity_num++) + { + if (!entities[entity_num].numbrushes) + continue; + + Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", nummodels); + BeginModel (); + if (entity_num == 0) + ProcessWorldModel (); + else + ProcessSubModel (); + EndModel (); + + //if (!verboseentities) + // verbose = false; // don't bother printing submodels + } + + EndBSPFile (); +} + + +/* +============ +main +============ +*/ +int BSP_Main () +{ + double start, end; + char path[1024]; + int total_bsp_time; + + Sys_Printf ("\n----- BSP ----\n\n"); + + + start = I_FloatTime (); + + ThreadSetDefault (); + SetQdirFromPath (mapname); + + strcpy (source, ExpandArg (mapname)); + StripExtension (source); + + // delete portal and line files + sprintf (path, "%s.prt", source); + remove (path); + sprintf (path, "%s.lin", source); + remove (path); + + strcpy (name, ExpandArg (mapname)); + DefaultExtension (name, ".map"); // might be .reg + + // + // if onlyents, just grab the entites and resave + // + if (onlyents) + { + char out[1024]; + + sprintf (out, "%s.bsp", source); + LoadBSPFile (out); + num_entities = 0; + + LoadMapFile (name); + SetModelNumbers (); + SetLightStyles (); + + UnparseEntities (); + + WriteBSPFile (out); + } + else + { + // + // start from scratch + // + LoadMapFile (name); + SetModelNumbers (); + SetLightStyles (); + + ProcessModels (); + } + + end = I_FloatTime (); + total_bsp_time = (int) (end-start); + Sys_Printf("\nBSP Time: "); + if ( total_bsp_time > 59 ) + Sys_Printf("%d Minutes ", total_bsp_time/60 ); + Sys_Printf( "%d Seconds\n", total_bsp_time%60 ); + + + return 0; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/qbsp.h b/misc/mediasource/netradiant-src/tools/quake2/q2map/qbsp.h new file mode 100644 index 00000000..cc5c822a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/qbsp.h @@ -0,0 +1,390 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +/* Files: + +brushbsp.c +csg.c +faces.c +gldraw.c +glfile.c +leakfile.c +map.c +nodraw.c +portals.c +prtfile.c +qbsp3.c +textures.c +tree.c +writebsp.c + +*/ + +#include "cmdlib.h" +#include "mathlib.h" +#include "scriplib.h" +#include "polylib.h" +#include "q2_threads.h" +#include "bspfile.h" +#include "inout.h" + +#ifdef WIN32 + #ifdef NDEBUG // Don't show in a Release build + #pragma warning(disable : 4305) // truncate from double to float + #pragma warning(disable : 4244) // conversion from double to float + #pragma warning(disable : 4018) // signed/unsigned mismatch + #endif +#endif + +#define MAX_BRUSH_SIDES 128 +#define CLIP_EPSILON 0.1 + +#define BOGUS_RANGE 8192 + +#define TEXINFO_NODE -1 // side is allready on a node + +typedef struct plane_s +{ + vec3_t normal; + vec_t dist; + int type; + struct plane_s *hash_chain; +} plane_t; + +typedef struct +{ + vec_t shift[2]; + vec_t rotate; + vec_t scale[2]; + char name[32]; + int flags; + int value; +} brush_texture_t; + +typedef struct side_s +{ + int planenum; + int texinfo; + winding_t *winding; + struct side_s *original; // bspbrush_t sides will reference the mapbrush_t sides + int contents; // from miptex + int surf; // from miptex + qboolean visible; // choose visble planes first + qboolean tested; // this plane allready checked as a split + qboolean bevel; // don't ever use for bsp splitting +} side_t; + +typedef struct brush_s +{ + int entitynum; + int brushnum; + + int contents; + + vec3_t mins, maxs; + + int numsides; + side_t *original_sides; +} mapbrush_t; + +#define PLANENUM_LEAF -1 + +#define MAXEDGES 20 + +typedef struct face_s +{ + struct face_s *next; // on node + + // the chain of faces off of a node can be merged or split, + // but each face_t along the way will remain in the chain + // until the entire tree is freed + struct face_s *merged; // if set, this face isn't valid anymore + struct face_s *split[2]; // if set, this face isn't valid anymore + + struct portal_s *portal; + int texinfo; + int planenum; + int contents; // faces in different contents can't merge + int outputnumber; + winding_t *w; + int numpoints; + qboolean badstartvert; // tjunctions cannot be fixed without a midpoint vertex + int vertexnums[MAXEDGES]; +} face_t; + + + +typedef struct bspbrush_s +{ + struct bspbrush_s *next; + vec3_t mins, maxs; + int side, testside; // side of node during construction + mapbrush_t *original; + int numsides; + side_t sides[6]; // variably sized +} bspbrush_t; + + + +#define MAX_NODE_BRUSHES 8 +typedef struct node_s +{ + // both leafs and nodes + int planenum; // -1 = leaf node + struct node_s *parent; + vec3_t mins, maxs; // valid after portalization + bspbrush_t *volume; // one for each leaf/node + + // nodes only + qboolean detail_seperator; // a detail brush caused the split + side_t *side; // the side that created the node + struct node_s *children[2]; + face_t *faces; + + // leafs only + bspbrush_t *brushlist; // fragments of all brushes in this leaf + int contents; // OR of all brush contents + int occupied; // 1 or greater can reach entity + entity_t *occupant; // for leak file testing + int cluster; // for portalfile writing + int area; // for areaportals + struct portal_s *portals; // also on nodes during construction +} node_t; + +typedef struct portal_s +{ + plane_t plane; + node_t *onnode; // NULL = outside box + node_t *nodes[2]; // [0] = front side of plane + struct portal_s *next[2]; + winding_t *winding; + + qboolean sidefound; // false if ->side hasn't been checked + side_t *side; // NULL = non-visible + face_t *face[2]; // output face in bsp file +} portal_t; + +typedef struct +{ + node_t *headnode; + node_t outside_node; + vec3_t mins, maxs; +} tree_t; + +extern int entity_num; + +extern plane_t mapplanes[MAX_MAP_PLANES]; +extern int nummapplanes; + +extern int nummapbrushes; +extern mapbrush_t mapbrushes[MAX_MAP_BRUSHES]; + +extern vec3_t map_mins, map_maxs; + +#define MAX_MAP_SIDES (MAX_MAP_BRUSHES*6) + +extern int nummapbrushsides; +extern side_t brushsides[MAX_MAP_SIDES]; + +extern qboolean noprune; +extern qboolean nodetail; +extern qboolean fulldetail; +extern qboolean nomerge; +extern qboolean nosubdiv; +extern qboolean nowater; +extern qboolean noweld; +extern qboolean noshare; +extern qboolean notjunc; + +extern vec_t microvolume; + +extern char outbase[32]; + +extern char source[1024]; + +void LoadMapFile (char *filename); +int FindFloatPlane (vec3_t normal, vec_t dist); + +//============================================================================= + +// textures.c + +typedef struct +{ + char name[64]; + int flags; + int value; + int contents; + char animname[64]; +} textureref_t; + +#define MAX_MAP_TEXTURES 1024 + +extern textureref_t textureref[MAX_MAP_TEXTURES]; + +int FindMiptex (char *name); + +int TexinfoForBrushTexture (plane_t *plane, brush_texture_t *bt, vec3_t origin); + +//============================================================================= + +void FindGCD (int *v); + +mapbrush_t *Brush_LoadEntity (entity_t *ent); +int PlaneTypeForNormal (vec3_t normal); +qboolean MakeBrushPlanes (mapbrush_t *b); +int FindIntPlane (int *inormal, int *iorigin); +void CreateBrush (int brushnum); + + +//============================================================================= + +// draw.c + +extern vec3_t draw_mins, draw_maxs; +extern qboolean drawflag; + +void Draw_ClearWindow (void); +void DrawWinding (winding_t *w); + +void GLS_BeginScene (void); +void GLS_Winding (winding_t *w, int code); +void GLS_EndScene (void); + +//============================================================================= + +// csg + +bspbrush_t *MakeBspBrushList (int startbrush, int endbrush, + vec3_t clipmins, vec3_t clipmaxs); +bspbrush_t *ChopBrushes (bspbrush_t *head); +bspbrush_t *InitialBrushList (bspbrush_t *list); +bspbrush_t *OptimizedBrushList (bspbrush_t *list); + +void WriteBrushMap (char *name, bspbrush_t *list); + +//============================================================================= + +// brushbsp + +void WriteBrushList (char *name, bspbrush_t *brush, qboolean onlyvis); + +bspbrush_t *CopyBrush (bspbrush_t *brush); + +void SplitBrush (bspbrush_t *brush, int planenum, + bspbrush_t **front, bspbrush_t **back); + +tree_t *AllocTree (void); +node_t *AllocNode (void); +bspbrush_t *AllocBrush (int numsides); +int CountBrushList (bspbrush_t *brushes); +void FreeBrush (bspbrush_t *brushes); +vec_t BrushVolume (bspbrush_t *brush); + +void BoundBrush (bspbrush_t *brush); +void FreeBrushList (bspbrush_t *brushes); + +tree_t *BrushBSP (bspbrush_t *brushlist, vec3_t mins, vec3_t maxs); + +//============================================================================= + +// portals.c + +int VisibleContents (int contents); + +void MakeHeadnodePortals (tree_t *tree); +void MakeNodePortal (node_t *node); +void SplitNodePortals (node_t *node); + +qboolean Portal_VisFlood (portal_t *p); + +qboolean FloodEntities (tree_t *tree); +void FillOutside (node_t *headnode); +void FloodAreas (tree_t *tree); +void MarkVisibleSides (tree_t *tree, int start, int end); +void FreePortal (portal_t *p); +void EmitAreaPortals (node_t *headnode); + +void MakeTreePortals (tree_t *tree); + +//============================================================================= + +// glfile.c + +void OutputWinding (winding_t *w, FILE *glview); +void WriteGLView (tree_t *tree, char *source); + +//============================================================================= + +// leakfile.c + +//void LeakFile (tree_t *tree); +xmlNodePtr LeakFile (tree_t *tree); + +//============================================================================= + +// prtfile.c + +void WritePortalFile (tree_t *tree); + +//============================================================================= + +// writebsp.c + +void SetModelNumbers (void); +void SetLightStyles (void); + +void BeginBSPFile (void); +void WriteBSP (node_t *headnode); +void EndBSPFile (void); +void BeginModel (void); +void EndModel (void); + +//============================================================================= + +// faces.c + +void MakeFaces (node_t *headnode); +void FixTjuncs (node_t *headnode); +int GetEdge2 (int v1, int v2, face_t *f); + +face_t *AllocFace (void); +void FreeFace (face_t *f); + +void MergeNodeFaces (node_t *node); + +//============================================================================= + +// tree.c + +void FreeTree (tree_t *tree); +void FreeTree_r (node_t *node); +void PrintTree_r (node_t *node, int depth); +void FreeTreePortals_r (node_t *node); +void PruneNodes_r (node_t *node); +void PruneNodes (node_t *node); + +//============================================================================= + +// externs + +extern char *mapname; +extern char game[64]; diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/qrad.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/qrad.c new file mode 100644 index 00000000..e1744cdd --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/qrad.c @@ -0,0 +1,647 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// qrad.c + +#include "qrad.h" + + + +/* + +NOTES +----- + +every surface must be divided into at least two patches each axis + +*/ + +patch_t *face_patches[MAX_MAP_FACES]; +entity_t *face_entity[MAX_MAP_FACES]; +patch_t patches[MAX_PATCHES]; +unsigned num_patches; + +vec3_t radiosity[MAX_PATCHES]; // light leaving a patch +vec3_t illumination[MAX_PATCHES]; // light arriving at a patch + +vec3_t face_offset[MAX_MAP_FACES]; // for rotating bmodels +dplane_t backplanes[MAX_MAP_PLANES]; + +char inbase[32], outbase[32]; + +int fakeplanes; // created planes for origin offset + +int numbounce = 8; +qboolean extrasamples; + +float subdiv = 64; +qboolean dumppatches; + +void BuildLightmaps (void); +int TestLine (vec3_t start, vec3_t stop); + +int junk; + +float ambient = 0; +float maxlight = 196; + +float lightscale = 1.0; + +qboolean glview; + +qboolean nopvs; + +char source[1024]; + +float direct_scale = 0.4; +float entity_scale = 1.0; + +/* +=================================================================== + +MISC + +=================================================================== +*/ + + +/* +============= +MakeBackplanes +============= +*/ +void MakeBackplanes (void) +{ + int i; + + for (i=0 ; ichildren[i]; + if (j < 0) + leafparents[-j - 1] = nodenum; + else + MakeParents (j, nodenum); + } +} + + +/* +=================================================================== + +TRANSFER SCALES + +=================================================================== +*/ + +int PointInLeafnum (vec3_t point) +{ + int nodenum; + vec_t dist; + dnode_t *node; + dplane_t *plane; + + nodenum = 0; + while (nodenum >= 0) + { + node = &dnodes[nodenum]; + plane = &dplanes[node->planenum]; + dist = DotProduct (point, plane->normal) - plane->dist; + if (dist > 0) + nodenum = node->children[0]; + else + nodenum = node->children[1]; + } + + return -nodenum - 1; +} + + +dleaf_t *Rad_PointInLeaf (vec3_t point) +{ + int num; + + num = PointInLeafnum (point); + return &dleafs[num]; +} + + +qboolean PvsForOrigin (vec3_t org, byte *pvs) +{ + dleaf_t *leaf; + + if (!visdatasize) + { + memset (pvs, 255, (numleafs+7)/8 ); + return true; + } + + leaf = Rad_PointInLeaf (org); + if (leaf->cluster == -1) + return false; // in solid leaf + + DecompressVis (dvisdata + dvis->bitofs[leaf->cluster][DVIS_PVS], pvs); + return true; +} + + +/* +============= +MakeTransfers + +============= +*/ +int total_transfer; + +void MakeTransfers (int i) +{ + int j; + vec3_t delta; + vec_t dist, scale; + float trans; + int itrans; + patch_t *patch, *patch2; + float total; + dplane_t plane; + vec3_t origin; + float transfers[MAX_PATCHES], *all_transfers; + int s; + int itotal; + byte pvs[(MAX_MAP_LEAFS+7)/8]; + int cluster; + + patch = patches + i; + total = 0; + + VectorCopy (patch->origin, origin); + plane = *patch->plane; + + if (!PvsForOrigin (patch->origin, pvs)) + return; + + // find out which patch2s will collect light + // from patch + + all_transfers = transfers; + patch->numtransfers = 0; + for (j=0, patch2 = patches ; jcluster; + if (cluster == -1) + continue; + if ( ! ( pvs[cluster>>3] & (1<<(cluster&7)) ) ) + continue; // not in pvs + } + + // calculate vector + VectorSubtract (patch2->origin, origin, delta); + dist = VectorNormalize (delta, delta); + if (!dist) + continue; // should never happen + + // reletive angles + scale = DotProduct (delta, plane.normal); + scale *= -DotProduct (delta, patch2->plane->normal); + if (scale <= 0) + continue; + + // check exact tramsfer + if (TestLine_r (0, patch->origin, patch2->origin) ) + continue; + + trans = scale * patch2->area / (dist*dist); + + if (trans < 0) + trans = 0; // rounding errors... + + transfers[j] = trans; + if (trans > 0) + { + total += trans; + patch->numtransfers++; + } + } + + // copy the transfers out and normalize + // total should be somewhere near PI if everything went right + // because partial occlusion isn't accounted for, and nearby + // patches have underestimated form factors, it will usually + // be higher than PI + if (patch->numtransfers) + { + transfer_t *t; + + if (patch->numtransfers < 0 || patch->numtransfers > MAX_PATCHES) + Error ("Weird numtransfers"); + s = patch->numtransfers * sizeof(transfer_t); + patch->transfers = malloc (s); + if (!patch->transfers) + Error ("Memory allocation failure"); + + // + // normalize all transfers so all of the light + // is transfered to the surroundings + // + t = patch->transfers; + itotal = 0; + for (j=0 ; jtransfer = itrans; + t->patch = j; + t++; + } + } + + // don't bother locking around this. not that important. + total_transfer += patch->numtransfers; +} + + +/* +============= +FreeTransfers +============= +*/ +void FreeTransfers (void) +{ + int i; + + for (i=0 ; iwinding; + fprintf (out, "%i\n", w->numpoints); + for (i=0 ; inumpoints ; i++) + { + fprintf (out, "%5.2f %5.2f %5.2f %5.3f %5.3f %5.3f\n", + w->p[i][0], + w->p[i][1], + w->p[i][2], + patch->totallight[0], + patch->totallight[1], + patch->totallight[2]); + } + fprintf (out, "\n"); + } + + fclose (out); +} + +/* +============= +WriteGlView +============= +*/ +void WriteGlView (void) +{ + char name[1024]; + FILE *f; + int i, j; + patch_t *p; + winding_t *w; + + strcpy (name, source); + StripExtension (name); + strcat (name, ".glr"); + + f = fopen (name, "w"); + if (!f) + Error ("Couldn't open %s", f); + + for (j=0 ; jwinding; + fprintf (f, "%i\n", w->numpoints); + for (i=0 ; inumpoints ; i++) + { + fprintf (f, "%5.2f %5.2f %5.2f %5.3f %5.3f %5.3f\n", + w->p[i][0], + w->p[i][1], + w->p[i][2], + p->totallight[0]/128, + p->totallight[1]/128, + p->totallight[2]/128); + } + fprintf (f, "\n"); + } + + fclose (f); +} + + +//============================================================== + +/* +============= +CollectLight +============= +*/ +float CollectLight (void) +{ + int i, j; + patch_t *patch; + vec_t total; + + total = 0; + + for (i=0, patch=patches ; isky) + { + VectorClear (radiosity[i]); + VectorClear (illumination[i]); + continue; + } + + for (j=0 ; j<3 ; j++) + { + patch->totallight[j] += illumination[i][j] / patch->area; + radiosity[i][j] = illumination[i][j] * patch->reflectivity[j]; + } + + total += radiosity[i][0] + radiosity[i][1] + radiosity[i][2]; + VectorClear (illumination[i]); + } + + return total; +} + + +/* +============= +ShootLight + +Send light out to other patches + Run multi-threaded +============= +*/ +void ShootLight (int patchnum) +{ + int k, l; + transfer_t *trans; + int num; + patch_t *patch; + vec3_t send; + + // this is the amount of light we are distributing + // prescale it so that multiplying by the 16 bit + // transfer values gives a proper output value + for (k=0 ; k<3 ; k++) + send[k] = radiosity[patchnum][k] / 0x10000; + patch = &patches[patchnum]; + + trans = patch->transfers; + num = patch->numtransfers; + + for (k=0 ; kpatch][l] += send[l]*trans->transfer; + } +} + +/* +============= +BounceLight +============= +*/ +void BounceLight (void) +{ + int i, j; + float added; + char name[64]; + patch_t *p; + + for (i=0 ; itotallight[j] = p->samplelight[j]; + radiosity[i][j] = p->samplelight[j] * p->reflectivity[j] * p->area; + } + } + + for (i=0 ; itotallight[0] < 0 || patch->totallight[1] < 0 || patch->totallight[2] < 0) + Error ("negative patch totallight\n"); + } +} + +/* +============= +RadWorld +============= +*/ +void RadWorld (void) +{ + if (numnodes == 0 || numfaces == 0) + Error ("Empty map"); + MakeBackplanes (); + MakeParents (0, -1); + MakeTnodes (&dmodels[0]); + + // turn each face into a single patch + MakePatches (); + + // subdivide patches to a maximum dimension + SubdividePatches (); + + // create directlights out of patches and lights + CreateDirectLights (); + + // build initial facelights + RunThreadsOnIndividual (numfaces, true, BuildFacelights); + + if (numbounce > 0) + { + // build transfer lists + RunThreadsOnIndividual (num_patches, true, MakeTransfers); + Sys_FPrintf( SYS_VRB, "transfer lists: %5.1f megs\n" + , (float)total_transfer * sizeof(transfer_t) / (1024*1024)); + + // spread light around + BounceLight (); + + FreeTransfers (); + + CheckPatches (); + } + + if (glview) + WriteGlView (); + + // blend bounced light into direct light and save + PairEdges (); + LinkPlaneFaces (); + + lightdatasize = 0; + RunThreadsOnIndividual (numfaces, true, FinalLightFace); +} + + +/* +======== +main + +light modelfile +======== +*/ +int RAD_Main () +{ + double start, end; + char name[1024]; + int total_rad_time; + + Sys_Printf ("\n----- RAD ----\n\n"); + + if (maxlight > 255) + maxlight = 255; + + start = I_FloatTime (); + + if ( !strcmp( game, "heretic2" ) ) + CalcTextureReflectivity = &CalcTextureReflectivity_Heretic2; + else + CalcTextureReflectivity = &CalcTextureReflectivity_Quake2; + + SetQdirFromPath (mapname); + strcpy (source, ExpandArg(mapname)); + StripExtension (source); + DefaultExtension (source, ".bsp"); + +// ReadLightFile (); + + sprintf (name, "%s%s", inbase, source); + Sys_Printf ("reading %s\n", name); + LoadBSPFile (name); + ParseEntities (); + (*CalcTextureReflectivity) (); + + if (!visdatasize) + { + Sys_Printf ("No vis information, direct lighting only.\n"); + numbounce = 0; + ambient = 0.1; + } + + RadWorld (); + + sprintf (name, "%s%s", outbase, source); + Sys_Printf ("writing %s\n", name); + WriteBSPFile (name); + + end = I_FloatTime (); + total_rad_time = (int) (end-start); + Sys_Printf("\nRAD Time: "); + if ( total_rad_time > 59 ) + Sys_Printf("%d Minutes ", total_rad_time/60 ); + Sys_Printf( "%d Seconds\n", total_rad_time%60 ); + + + return 0; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/qrad.h b/misc/mediasource/netradiant-src/tools/quake2/q2map/qrad.h new file mode 100644 index 00000000..eda18919 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/qrad.h @@ -0,0 +1,184 @@ +/* +Copyright (C) 1999-2006 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 +*/ +/* Files: + +lightmap.c +patches.c +qrad.c +trace.c + +*/ + + +#include "cmdlib.h" +#include "mathlib.h" +#include "bspfile.h" +#include "polylib.h" +#include "q2_threads.h" +#include "lbmlib.h" +#include "inout.h" + +#ifdef WIN32 +#include +#endif + +#ifdef WIN32 + #ifdef NDEBUG // Don't show in a Release build + #pragma warning(disable : 4305) // truncate from double to float + #pragma warning(disable : 4244) // conversion from double to float + #pragma warning(disable : 4018) // signed/unsigned mismatch + #endif +#endif + +typedef enum +{ + emit_surface, + emit_point, + emit_spotlight +} emittype_t; + + + +typedef struct directlight_s +{ + struct directlight_s *next; + emittype_t type; + + float intensity; + int style; + vec3_t origin; + vec3_t color; + vec3_t normal; // for surfaces and spotlights + float stopdot; // for spotlights +} directlight_t; + + +// the sum of all tranfer->transfer values for a given patch +// should equal exactly 0x10000, showing that all radiance +// reaches other patches +typedef struct +{ + unsigned short patch; + unsigned short transfer; +} transfer_t; + + +#define MAX_PATCHES 65000 // larger will cause 32 bit overflows + +typedef struct patch_s +{ + winding_t *winding; + struct patch_s *next; // next in face + int numtransfers; + transfer_t *transfers; + + int cluster; // for pvs checking + vec3_t origin; + dplane_t *plane; + + qboolean sky; + + vec3_t totallight; // accumulated by radiosity + // does NOT include light + // accounted for by direct lighting + float area; + + // illuminance * reflectivity = radiosity + vec3_t reflectivity; + vec3_t baselight; // emissivity only + + // each style 0 lightmap sample in the patch will be + // added up to get the average illuminance of the entire patch + vec3_t samplelight; + int samples; // for averaging direct light +} patch_t; + +extern patch_t *face_patches[MAX_MAP_FACES]; +extern entity_t *face_entity[MAX_MAP_FACES]; +extern vec3_t face_offset[MAX_MAP_FACES]; // for rotating bmodels +extern patch_t patches[MAX_PATCHES]; +extern unsigned num_patches; + +extern int leafparents[MAX_MAP_LEAFS]; +extern int nodeparents[MAX_MAP_NODES]; + +extern float lightscale; + + +void MakeShadowSplits (void); + +//============================================== + + +void BuildVisMatrix (void); +qboolean CheckVisBit (unsigned p1, unsigned p2); + +//============================================== + +extern float ambient, maxlight; + +void LinkPlaneFaces (void); + +extern qboolean extrasamples; +extern int numbounce; + +extern directlight_t *directlights[MAX_MAP_LEAFS]; + +extern byte nodehit[MAX_MAP_NODES]; + +void BuildLightmaps (void); + +void BuildFacelights (int facenum); + +void FinalLightFace (int facenum); + +qboolean PvsForOrigin (vec3_t org, byte *pvs); + +int TestLine_r (int node, vec3_t start, vec3_t stop); + +void CreateDirectLights (void); + +dleaf_t *Rad_PointInLeaf (vec3_t point); + + +extern dplane_t backplanes[MAX_MAP_PLANES]; +extern int fakeplanes; // created planes for origin offset + +extern float subdiv; + +extern float direct_scale; +extern float entity_scale; + +int PointInLeafnum (vec3_t point); +void MakeTnodes (dmodel_t *bm); +void MakePatches (void); +void SubdividePatches (void); +void PairEdges (void); +void (*CalcTextureReflectivity) (void); +void CalcTextureReflectivity_Quake2(void); +void CalcTextureReflectivity_Heretic2(void); + +//============================================================================= + +// externs + +extern char *mapname; +extern char game[64]; diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/qvis.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/qvis.c new file mode 100644 index 00000000..7785ebe5 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/qvis.c @@ -0,0 +1,581 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// qvis.c + +#include "qvis.h" +#include "q2_threads.h" +#include "stdlib.h" + +int numportals; +int portalclusters; + +char inbase[32]; +char outbase[32]; + +portal_t *portals; +leaf_t *leafs; + +int c_portaltest, c_portalpass, c_portalcheck; + +byte *uncompressedvis; + +byte *vismap, *vismap_p, *vismap_end; // past visfile +int originalvismapsize; + +int leafbytes; // (portalclusters+63)>>3 +int leaflongs; + +int portalbytes, portallongs; + +qboolean fastvis; +qboolean nosort; + +int testlevel = 2; + +int totalvis; + +portal_t *sorted_portals[MAX_MAP_PORTALS*2]; + + +//============================================================================= + +void PlaneFromWinding (winding_t *w, plane_t *plane) +{ + vec3_t v1, v2; + +// calc plane + VectorSubtract (w->points[2], w->points[1], v1); + VectorSubtract (w->points[0], w->points[1], v2); + CrossProduct (v2, v1, plane->normal); + VectorNormalize (plane->normal, plane->normal); + plane->dist = DotProduct (w->points[0], plane->normal); +} + + +/* +================== +NewWinding +================== +*/ +winding_t *NewWinding (int points) +{ + winding_t *w; + int size; + + if (points > MAX_POINTS_ON_WINDING) + Error ("NewWinding: %i points", points); + + size = (int)((winding_t *)0)->points[points]; + w = malloc (size); + memset (w, 0, size); + + return w; +} + + +/* +void pw(winding_t *w) +{ + int i; + for (i=0 ; inumpoints ; i++) + Sys_Printf ("(%5.1f, %5.1f, %5.1f)\n",w->points[i][0], w->points[i][1],w->points[i][2]); +} +*/ +void prl(leaf_t *l) +{ + int i; + portal_t *p; + plane_t pl; + + for (i=0 ; inumportals ; i++) + { + p = l->portals[i]; + pl = p->plane; + Sys_Printf ("portal %4i to leaf %4i : %7.1f : (%4.1f, %4.1f, %4.1f)\n",(int)(p-portals),p->leaf,pl.dist, pl.normal[0], pl.normal[1], pl.normal[2]); + } +} + + +//============================================================================= + +/* +============= +SortPortals + +Sorts the portals from the least complex, so the later ones can reuse +the earlier information. +============= +*/ +int PComp (const void *a, const void *b) +{ + if ( (*(portal_t **)a)->nummightsee == (*(portal_t **)b)->nummightsee) + return 0; + if ( (*(portal_t **)a)->nummightsee < (*(portal_t **)b)->nummightsee) + return -1; + return 1; +} +void SortPortals (void) +{ + int i; + + for (i=0 ; i>3] & (1<<(i&7)) ) + { + p = portals+i; + leafbits[p->leaf>>3] |= (1<<(p->leaf&7)); + } + } + + c_leafs = CountBits (leafbits, portalclusters); + + return c_leafs; +} + + +/* +=============== +ClusterMerge + +Merges the portal visibility for a leaf +=============== +*/ +void ClusterMerge (int leafnum) +{ + leaf_t *leaf; + byte portalvector[MAX_PORTALS/8]; + byte uncompressed[MAX_MAP_LEAFS/8]; + byte compressed[MAX_MAP_LEAFS/8]; + int i, j; + int numvis; + byte *dest; + portal_t *p; + int pnum; + + // OR together all the portalvis bits + + memset (portalvector, 0, portalbytes); + leaf = &leafs[leafnum]; + for (i=0 ; inumportals ; i++) + { + p = leaf->portals[i]; + if (p->status != stat_done) + Error ("portal not done"); + for (j=0 ; jportalvis)[j]; + pnum = p - portals; + portalvector[pnum>>3] |= 1<<(pnum&7); + } + + // convert portal bits to leaf bits + numvis = LeafVectorFromPortalVector (portalvector, uncompressed); + + if (uncompressed[leafnum>>3] & (1<<(leafnum&7))) + Sys_Printf ("WARNING: Leaf portals saw into leaf\n"); + + uncompressed[leafnum>>3] |= (1<<(leafnum&7)); + numvis++; // count the leaf itself + + // save uncompressed for PHS calculation + memcpy (uncompressedvis + leafnum*leafbytes, uncompressed, leafbytes); + +// +// compress the bit string +// + Sys_FPrintf( SYS_VRB, "cluster %4i : %4i visible\n", leafnum, numvis); + totalvis += numvis; + + i = CompressVis (uncompressed, compressed); + + dest = vismap_p; + vismap_p += i; + + if (vismap_p > vismap_end) + Error ("Vismap expansion overflow"); + + dvis->bitofs[leafnum][DVIS_PVS] = dest-vismap; + + memcpy (dest, compressed, i); +} + + +/* +================== +CalcPortalVis +================== +*/ +void CalcPortalVis (void) +{ + int i; + +// fastvis just uses mightsee for a very loose bound + if (fastvis) + { + for (i=0 ; iwinding; + VectorCopy (vec3_origin, total); + for (i=0 ; inumpoints ; i++) + { + VectorAdd (total, w->points[i], total); + } + + for (i=0 ; i<3 ; i++) + total[i] /= w->numpoints; + + bestr = 0; + for (i=0 ; inumpoints ; i++) + { + VectorSubtract (w->points[i], total, dist); + r = VectorLength (dist); + if (r > bestr) + bestr = r; + } + VectorCopy (total, p->origin); + p->radius = bestr; +} + +/* +============ +LoadPortals +============ +*/ +void LoadPortals (char *name) +{ + int i, j; + portal_t *p; + leaf_t *l; + char magic[80]; + FILE *f; + int numpoints; + winding_t *w; + int leafnums[2]; + plane_t plane; + + if (!strcmp(name,"-")) + f = stdin; + else + { + f = fopen(name, "r"); + if (!f) + Error ("LoadPortals: couldn't read %s\n",name); + } + + if (fscanf (f,"%79s\n%i\n%i\n",magic, &portalclusters, &numportals) != 3) + Error ("LoadPortals: failed to read header"); + if (strcmp(magic,PORTALFILE)) + Error ("LoadPortals: not a portal file"); + + Sys_Printf ("%4i portalclusters\n", portalclusters); + Sys_Printf ("%4i numportals\n", numportals); + + // these counts should take advantage of 64 bit systems automatically + leafbytes = ((portalclusters+63)&~63)>>3; + leaflongs = leafbytes/sizeof(long); + + portalbytes = ((numportals*2+63)&~63)>>3; + portallongs = portalbytes/sizeof(long); + +// each file portal is split into two memory portals + portals = malloc(2*numportals*sizeof(portal_t)); + memset (portals, 0, 2*numportals*sizeof(portal_t)); + + leafs = malloc(portalclusters*sizeof(leaf_t)); + memset (leafs, 0, portalclusters*sizeof(leaf_t)); + + originalvismapsize = portalclusters*leafbytes; + uncompressedvis = malloc(originalvismapsize); + + vismap = vismap_p = dvisdata; + dvis->numclusters = portalclusters; + vismap_p = (byte *)&dvis->bitofs[portalclusters]; + + vismap_end = vismap + MAX_MAP_VISIBILITY; + + for (i=0, p=portals ; i MAX_POINTS_ON_WINDING) + Error ("LoadPortals: portal %i has too many points", i); + if ( (unsigned)leafnums[0] > portalclusters + || (unsigned)leafnums[1] > portalclusters) + Error ("LoadPortals: reading portal %i", i); + + w = p->winding = NewWinding (numpoints); + w->original = true; + w->numpoints = numpoints; + + for (j=0 ; jpoints[j][k] = v[k]; + } + fscanf (f, "\n"); + + // calc plane + PlaneFromWinding (w, &plane); + + // create forward portal + l = &leafs[leafnums[0]]; + if (l->numportals == MAX_PORTALS_ON_LEAF) + Error ("Leaf with too many portals"); + l->portals[l->numportals] = p; + l->numportals++; + + p->winding = w; + VectorSubtract (vec3_origin, plane.normal, p->plane.normal); + p->plane.dist = -plane.dist; + p->leaf = leafnums[1]; + SetPortalSphere (p); + p++; + + // create backwards portal + l = &leafs[leafnums[1]]; + if (l->numportals == MAX_PORTALS_ON_LEAF) + Error ("Leaf with too many portals"); + l->portals[l->numportals] = p; + l->numportals++; + + p->winding = NewWinding(w->numpoints); + p->winding->numpoints = w->numpoints; + for (j=0 ; jnumpoints ; j++) + { + VectorCopy (w->points[w->numpoints-1-j], p->winding->points[j]); + } + + p->plane = plane; + p->leaf = leafnums[0]; + SetPortalSphere (p); + p++; + + } + + fclose (f); +} + + +/* +================ +CalcPHS + +Calculate the PHS (Potentially Hearable Set) +by ORing together all the PVS visible from a leaf +================ +*/ +void CalcPHS (void) +{ + int i, j, k, l, index; + int bitbyte; + long *dest, *src; + byte *scan; + int count; + byte uncompressed[MAX_MAP_LEAFS/8]; + byte compressed[MAX_MAP_LEAFS/8]; + + Sys_Printf ("Building PHS...\n"); + + count = 0; + for (i=0 ; i= portalclusters) + Error ("Bad bit in PVS"); // pad bits should be 0 + src = (long *)(uncompressedvis + index*leafbytes); + dest = (long *)uncompressed; + for (l=0 ; l>3] & (1<<(j&7)) ) + count++; + + // + // compress the bit string + // + j = CompressVis (uncompressed, compressed); + + dest = (long *)vismap_p; + vismap_p += j; + + if (vismap_p > vismap_end) + Error ("Vismap expansion overflow"); + + dvis->bitofs[i][DVIS_PHS] = (byte *)dest-vismap; + + memcpy (dest, compressed, j); + } + + Sys_Printf ("Average clusters hearable: %i\n", count/portalclusters); +} + +/* +=========== +main +=========== +*/ +int VIS_Main () +{ + char portalfile[1024]; + char source[1024]; + char name[1024]; + double start, end; + int total_vis_time; + + Sys_Printf ("\n----- VIS ----\n\n"); + + //if (i != argc - 1) + // Error ("usage: vis [-threads #] [-level 0-4] [-fast] [-v] bspfile"); + + start = I_FloatTime (); + + ThreadSetDefault (); + + SetQdirFromPath (mapname); + strcpy (source, ExpandArg(mapname)); + StripExtension (source); + DefaultExtension (source, ".bsp"); + + sprintf (name, "%s%s", inbase, source); + Sys_Printf ("reading %s\n", name); + LoadBSPFile (name); + if (numnodes == 0 || numfaces == 0) + Error ("Empty map"); + + sprintf (portalfile, "%s%s", inbase, ExpandArg(mapname)); + StripExtension (portalfile); + strcat (portalfile, ".prt"); + + Sys_Printf ("reading %s\n", portalfile); + LoadPortals (portalfile); + + CalcVis (); + + CalcPHS (); + + visdatasize = vismap_p - dvisdata; + Sys_Printf ("visdatasize:%i compressed from %i\n", visdatasize, originalvismapsize*2); + + sprintf (name, "%s%s", outbase, source); + Sys_Printf ("writing %s\n", name); + WriteBSPFile (name); + + end = I_FloatTime (); + total_vis_time = (int) (end-start); + Sys_Printf("\nVIS Time: "); + if ( total_vis_time > 59 ) + Sys_Printf("%d Minutes ", total_vis_time/60 ); + Sys_Printf( "%d Seconds\n", total_vis_time%60 ); + + + return 0; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/qvis.h b/misc/mediasource/netradiant-src/tools/quake2/q2map/qvis.h new file mode 100644 index 00000000..3f2306fb --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/qvis.h @@ -0,0 +1,169 @@ +/* +Copyright (C) 1999-2006 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 +*/ +/* Files: + +flow.c +qvis3.c + +*/ + +#include "cmdlib.h" +#include "mathlib.h" +#include "bspfile.h" +#include "inout.h" + +#ifdef WIN32 + #ifdef NDEBUG // Don't show in a Release build + #pragma warning(disable : 4305) // truncate from double to float + #pragma warning(disable : 4244) // conversion from double to float + #pragma warning(disable : 4018) // signed/unsigned mismatch + #endif +#endif + +#define MAX_PORTALS 32768 + +#define PORTALFILE "PRT1" + +#define ON_EPSILON 0.1 + +typedef struct +{ + vec3_t normal; + float dist; +} plane_t; + +#define MAX_POINTS_ON_WINDING 64 +#define MAX_POINTS_ON_FIXED_WINDING 12 + +typedef struct +{ + qboolean original; // don't free, it's part of the portal + int numpoints; + vec3_t points[MAX_POINTS_ON_FIXED_WINDING]; // variable sized +} winding_t; + +winding_t *NewWinding (int points); +void FreeWinding (winding_t *w); +winding_t *CopyWinding (winding_t *w); + + +typedef enum {stat_none, stat_working, stat_done} vstatus_t; +typedef struct +{ + plane_t plane; // normal pointing into neighbor + int leaf; // neighbor + + vec3_t origin; // for fast clip testing + float radius; + + winding_t *winding; + vstatus_t status; + byte *portalfront; // [portals], preliminary + byte *portalflood; // [portals], intermediate + byte *portalvis; // [portals], final + + int nummightsee; // bit count on portalflood for sort +} portal_t; + +typedef struct seperating_plane_s +{ + struct seperating_plane_s *next; + plane_t plane; // from portal is on positive side +} sep_t; + + +typedef struct passage_s +{ + struct passage_s *next; + int from, to; // leaf numbers + sep_t *planes; +} passage_t; + +#define MAX_PORTALS_ON_LEAF 128 +typedef struct leaf_s +{ + int numportals; + passage_t *passages; + portal_t *portals[MAX_PORTALS_ON_LEAF]; +} leaf_t; + + +typedef struct pstack_s +{ + byte mightsee[MAX_PORTALS/8]; // bit string + struct pstack_s *next; + leaf_t *leaf; + portal_t *portal; // portal exiting + winding_t *source; + winding_t *pass; + + winding_t windings[3]; // source, pass, temp in any order + int freewindings[3]; + + plane_t portalplane; +} pstack_t; + +typedef struct +{ + portal_t *base; + int c_chains; + pstack_t pstack_head; +} threaddata_t; + + + +extern int numportals; +extern int portalclusters; + +extern portal_t *portals; +extern leaf_t *leafs; + +extern int c_portaltest, c_portalpass, c_portalcheck; +extern int c_portalskip, c_leafskip; +extern int c_vistest, c_mighttest; +extern int c_chains; + +extern byte *vismap, *vismap_p, *vismap_end; // past visfile + +extern int testlevel; + +extern byte *uncompressed; + +extern int leafbytes, leaflongs; +extern int portalbytes, portallongs; + + +void LeafFlow (int leafnum); + + +void BasePortalVis (int portalnum); +void BetterPortalVis (int portalnum); +void PortalFlow (int portalnum); + +extern portal_t *sorted_portals[MAX_MAP_PORTALS*2]; + +int CountBits (byte *bits, int numbits); + +//============================================================================= + +// externs + +extern char *mapname; diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/textures.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/textures.c new file mode 100644 index 00000000..503d7a4d --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/textures.c @@ -0,0 +1,249 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +int nummiptex; +textureref_t textureref[MAX_MAP_TEXTURES]; + +//========================================================================== + + +int FindMiptex (char *name) +{ + int i; + char path[1024]; + miptex_t *mt; + miptex_m8_t *mt_m8; + miptex_m32_t *mt_m32; + + for (i=0 ; ivalue); + textureref[i].flags = LittleLong (mt_m32->flags); + textureref[i].contents = LittleLong (mt_m32->contents); + strcpy (textureref[i].animname, mt_m32->animname); + free (mt_m32); + } + else + sprintf (path, "%stextures/%s.m8", gamedir, name); + + if (TryLoadFile (path, (void **)&mt_m8) != -1) + { + textureref[i].value = LittleLong (mt_m8->value); + textureref[i].flags = LittleLong (mt_m8->flags); + textureref[i].contents = LittleLong (mt_m8->contents); + strcpy (textureref[i].animname, mt_m8->animname); + free (mt_m8); + } + } + else + { + sprintf (path, "%stextures/%s.wal", gamedir, name); + if (TryLoadFile (path, (void **)&mt) != -1) + { + textureref[i].value = LittleLong (mt->value); + textureref[i].flags = LittleLong (mt->flags); + textureref[i].contents = LittleLong (mt->contents); + strcpy (textureref[i].animname, mt->animname); + free (mt); + } + } + + nummiptex++; + + if (textureref[i].animname[0]) + FindMiptex (textureref[i].animname); + + return i; +} + + +/* +================== +textureAxisFromPlane +================== +*/ +vec3_t baseaxis[18] = +{ +{0,0,1}, {1,0,0}, {0,-1,0}, // floor +{0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling +{1,0,0}, {0,1,0}, {0,0,-1}, // west wall +{-1,0,0}, {0,1,0}, {0,0,-1}, // east wall +{0,1,0}, {1,0,0}, {0,0,-1}, // south wall +{0,-1,0}, {1,0,0}, {0,0,-1} // north wall +}; + +void TextureAxisFromPlane(plane_t *pln, vec3_t xv, vec3_t yv) +{ + int bestaxis; + vec_t dot,best; + int i; + + best = 0; + bestaxis = 0; + + for (i=0 ; i<6 ; i++) + { + dot = DotProduct (pln->normal, baseaxis[i*3]); + if (dot > best) + { + best = dot; + bestaxis = i; + } + } + + VectorCopy (baseaxis[bestaxis*3+1], xv); + VectorCopy (baseaxis[bestaxis*3+2], yv); +} + + + + +int TexinfoForBrushTexture (plane_t *plane, brush_texture_t *bt, vec3_t origin) +{ + vec3_t vecs[2]; + int sv, tv; + vec_t ang, sinv, cosv; + vec_t ns, nt; + texinfo_t tx, *tc; + int i, j, k; + float shift[2]; + brush_texture_t anim; + int mt; + + if (!bt->name[0]) + return 0; + + memset (&tx, 0, sizeof(tx)); + strcpy (tx.texture, bt->name); + + TextureAxisFromPlane(plane, vecs[0], vecs[1]); + + shift[0] = DotProduct (origin, vecs[0]); + shift[1] = DotProduct (origin, vecs[1]); + + if (!bt->scale[0]) + bt->scale[0] = 1; + if (!bt->scale[1]) + bt->scale[1] = 1; + + +// rotate axis + if (bt->rotate == 0) + { sinv = 0 ; cosv = 1; } + else if (bt->rotate == 90) + { sinv = 1 ; cosv = 0; } + else if (bt->rotate == 180) + { sinv = 0 ; cosv = -1; } + else if (bt->rotate == 270) + { sinv = -1 ; cosv = 0; } + else + { + ang = bt->rotate / 180 * Q_PI; + sinv = sin(ang); + cosv = cos(ang); + } + + if (vecs[0][0]) + sv = 0; + else if (vecs[0][1]) + sv = 1; + else + sv = 2; + + if (vecs[1][0]) + tv = 0; + else if (vecs[1][1]) + tv = 1; + else + tv = 2; + + for (i=0 ; i<2 ; i++) + { + ns = cosv * vecs[i][sv] - sinv * vecs[i][tv]; + nt = sinv * vecs[i][sv] + cosv * vecs[i][tv]; + vecs[i][sv] = ns; + vecs[i][tv] = nt; + } + + for (i=0 ; i<2 ; i++) + for (j=0 ; j<3 ; j++) + tx.vecs[i][j] = vecs[i][j] / bt->scale[i]; + + tx.vecs[0][3] = bt->shift[0] + shift[0]; + tx.vecs[1][3] = bt->shift[1] + shift[1]; + tx.flags = bt->flags; + tx.value = bt->value; + + // + // find the texinfo + // + tc = texinfo; + for (i=0 ; iflags != tx.flags) + continue; + if (tc->value != tx.value) + continue; + for (j=0 ; j<2 ; j++) + { + if (strcmp (tc->texture, tx.texture)) + goto skip; + for (k=0 ; k<4 ; k++) + { + if (tc->vecs[j][k] != tx.vecs[j][k]) + goto skip; + } + } + return i; +skip:; + } + *tc = tx; + numtexinfo++; + + // load the next animation + mt = FindMiptex (bt->name); + if (textureref[mt].animname[0]) + { + anim = *bt; + strcpy (anim.name, textureref[mt].animname); + tc->nexttexinfo = TexinfoForBrushTexture (plane, &anim, origin); + } + else + tc->nexttexinfo = -1; + + + return i; +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/trace.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/trace.c new file mode 100644 index 00000000..b9392b17 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/trace.c @@ -0,0 +1,298 @@ +/* +Copyright (C) 1999-2006 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 +*/ +// trace.c +/* +#include "cmdlib.h" +#include "mathlib.h" +#include "bspfile.h" +*/ + +#include "qrad.h" + +#define ON_EPSILON 0.1 + +typedef struct tnode_s +{ + int type; + vec3_t normal; + float dist; + int children[2]; + int pad; +} tnode_t; + +tnode_t *tnodes, *tnode_p; + +/* +============== +MakeTnode + +Converts the disk node structure into the efficient tracing structure +============== +*/ +void MakeTnode (int nodenum) +{ + tnode_t *t; + dplane_t *plane; + int i; + dnode_t *node; + + t = tnode_p++; + + node = dnodes + nodenum; + plane = dplanes + node->planenum; + + t->type = plane->type; + VectorCopy (plane->normal, t->normal); + t->dist = plane->dist; + + for (i=0 ; i<2 ; i++) + { + if (node->children[i] < 0) + t->children[i] = (dleafs[-node->children[i] - 1].contents & CONTENTS_SOLID) | (1<<31); + else + { + t->children[i] = tnode_p - tnodes; + MakeTnode (node->children[i]); + } + } + +} + + +/* +============= +MakeTnodes + +Loads the node structure out of a .bsp file to be used for light occlusion +============= +*/ +void MakeTnodes (dmodel_t *bm) +{ + // 32 byte align the structs + tnodes = malloc( (numnodes+1) * sizeof(tnode_t)); + tnodes = (tnode_t *)(((int)tnodes + 31)&~31); + tnode_p = tnodes; + + MakeTnode (0); +} + + +//========================================================== + + +int TestLine_r (int node, vec3_t start, vec3_t stop) +{ + tnode_t *tnode; + float front, back; + vec3_t mid; + float frac; + int side; + int r; + + if (node & (1<<31)) + return node & ~(1<<31); // leaf node + + tnode = &tnodes[node]; + switch (tnode->type) + { + case PLANE_X: + front = start[0] - tnode->dist; + back = stop[0] - tnode->dist; + break; + case PLANE_Y: + front = start[1] - tnode->dist; + back = stop[1] - tnode->dist; + break; + case PLANE_Z: + front = start[2] - tnode->dist; + back = stop[2] - tnode->dist; + break; + default: + front = (start[0]*tnode->normal[0] + start[1]*tnode->normal[1] + start[2]*tnode->normal[2]) - tnode->dist; + back = (stop[0]*tnode->normal[0] + stop[1]*tnode->normal[1] + stop[2]*tnode->normal[2]) - tnode->dist; + break; + } + + if (front >= -ON_EPSILON && back >= -ON_EPSILON) + return TestLine_r (tnode->children[0], start, stop); + + if (front < ON_EPSILON && back < ON_EPSILON) + return TestLine_r (tnode->children[1], start, stop); + + side = front < 0; + + frac = front / (front-back); + + mid[0] = start[0] + (stop[0] - start[0])*frac; + mid[1] = start[1] + (stop[1] - start[1])*frac; + mid[2] = start[2] + (stop[2] - start[2])*frac; + + r = TestLine_r (tnode->children[side], start, mid); + if (r) + return r; + return TestLine_r (tnode->children[!side], mid, stop); +} + +int TestLine (vec3_t start, vec3_t stop) +{ + return TestLine_r (0, start, stop); +} + +/* +============================================================================== + +LINE TRACING + +The major lighting operation is a point to point visibility test, performed +by recursive subdivision of the line by the BSP tree. + +============================================================================== +*/ + +typedef struct +{ + vec3_t backpt; + int side; + int node; +} tracestack_t; + + +/* +============== +TestLine +============== +*/ +qboolean _TestLine (vec3_t start, vec3_t stop) +{ + int node; + float front, back; + tracestack_t *tstack_p; + int side; + float frontx,fronty, frontz, backx, backy, backz; + tracestack_t tracestack[64]; + tnode_t *tnode; + + frontx = start[0]; + fronty = start[1]; + frontz = start[2]; + backx = stop[0]; + backy = stop[1]; + backz = stop[2]; + + tstack_p = tracestack; + node = 0; + + while (1) + { + if (node == CONTENTS_SOLID) + { +#if 0 + float d1, d2, d3; + + d1 = backx - frontx; + d2 = backy - fronty; + d3 = backz - frontz; + + if (d1*d1 + d2*d2 + d3*d3 > 1) +#endif + return false; // DONE! + } + + while (node < 0) + { + // pop up the stack for a back side + tstack_p--; + if (tstack_p < tracestack) + return true; + node = tstack_p->node; + + // set the hit point for this plane + + frontx = backx; + fronty = backy; + frontz = backz; + + // go down the back side + + backx = tstack_p->backpt[0]; + backy = tstack_p->backpt[1]; + backz = tstack_p->backpt[2]; + + node = tnodes[tstack_p->node].children[!tstack_p->side]; + } + + tnode = &tnodes[node]; + + switch (tnode->type) + { + case PLANE_X: + front = frontx - tnode->dist; + back = backx - tnode->dist; + break; + case PLANE_Y: + front = fronty - tnode->dist; + back = backy - tnode->dist; + break; + case PLANE_Z: + front = frontz - tnode->dist; + back = backz - tnode->dist; + break; + default: + front = (frontx*tnode->normal[0] + fronty*tnode->normal[1] + frontz*tnode->normal[2]) - tnode->dist; + back = (backx*tnode->normal[0] + backy*tnode->normal[1] + backz*tnode->normal[2]) - tnode->dist; + break; + } + + if (front > -ON_EPSILON && back > -ON_EPSILON) +// if (front > 0 && back > 0) + { + node = tnode->children[0]; + continue; + } + + if (front < ON_EPSILON && back < ON_EPSILON) +// if (front <= 0 && back <= 0) + { + node = tnode->children[1]; + continue; + } + + side = front < 0; + + front = front / (front-back); + + tstack_p->node = node; + tstack_p->side = side; + tstack_p->backpt[0] = backx; + tstack_p->backpt[1] = backy; + tstack_p->backpt[2] = backz; + + tstack_p++; + + backx = frontx + front*(backx-frontx); + backy = fronty + front*(backy-fronty); + backz = frontz + front*(backz-frontz); + + node = tnode->children[side]; + } +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/tree.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/tree.c new file mode 100644 index 00000000..52d78fa8 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/tree.c @@ -0,0 +1,218 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +extern int c_nodes; + +void RemovePortalFromNode (portal_t *portal, node_t *l); + +node_t *NodeForPoint (node_t *node, vec3_t origin) +{ + plane_t *plane; + vec_t d; + + while (node->planenum != PLANENUM_LEAF) + { + plane = &mapplanes[node->planenum]; + d = DotProduct (origin, plane->normal) - plane->dist; + if (d >= 0) + node = node->children[0]; + else + node = node->children[1]; + } + + return node; +} + + + +/* +============= +FreeTreePortals_r +============= +*/ +void FreeTreePortals_r (node_t *node) +{ + portal_t *p, *nextp; + int s; + + // free children + if (node->planenum != PLANENUM_LEAF) + { + FreeTreePortals_r (node->children[0]); + FreeTreePortals_r (node->children[1]); + } + + // free portals + for (p=node->portals ; p ; p=nextp) + { + s = (p->nodes[1] == node); + nextp = p->next[s]; + + RemovePortalFromNode (p, p->nodes[!s]); + FreePortal (p); + } + node->portals = NULL; +} + +/* +============= +FreeTree_r +============= +*/ +void FreeTree_r (node_t *node) +{ + face_t *f, *nextf; + + // free children + if (node->planenum != PLANENUM_LEAF) + { + FreeTree_r (node->children[0]); + FreeTree_r (node->children[1]); + } + + // free bspbrushes + FreeBrushList (node->brushlist); + + // free faces + for (f=node->faces ; f ; f=nextf) + { + nextf = f->next; + FreeFace (f); + } + + // free the node + if (node->volume) + FreeBrush (node->volume); + + if (numthreads == 1) + c_nodes--; + free (node); +} + + +/* +============= +FreeTree +============= +*/ +void FreeTree (tree_t *tree) +{ + FreeTreePortals_r (tree->headnode); + FreeTree_r (tree->headnode); + free (tree); +} + +//=============================================================== + +void PrintTree_r (node_t *node, int depth) +{ + int i; + plane_t *plane; + bspbrush_t *bb; + + for (i=0 ; iplanenum == PLANENUM_LEAF) + { + if (!node->brushlist) + Sys_Printf ("NULL\n"); + else + { + for (bb=node->brushlist ; bb ; bb=bb->next) + Sys_Printf ("%i ", bb->original->brushnum); + Sys_Printf ("\n"); + } + return; + } + + plane = &mapplanes[node->planenum]; + Sys_Printf ("#%i (%5.2f %5.2f %5.2f):%5.2f\n", node->planenum, + plane->normal[0], plane->normal[1], plane->normal[2], + plane->dist); + PrintTree_r (node->children[0], depth+1); + PrintTree_r (node->children[1], depth+1); +} + +/* +========================================================= + +NODES THAT DON'T SEPERATE DIFFERENT CONTENTS CAN BE PRUNED + +========================================================= +*/ + +int c_pruned; + +/* +============ +PruneNodes_r +============ +*/ +void PruneNodes_r (node_t *node) +{ + bspbrush_t *b, *next; + + if (node->planenum == PLANENUM_LEAF) + return; + PruneNodes_r (node->children[0]); + PruneNodes_r (node->children[1]); + + if ( (node->children[0]->contents & CONTENTS_SOLID) + && (node->children[1]->contents & CONTENTS_SOLID) ) + { + if (node->faces) + Error ("node->faces seperating CONTENTS_SOLID"); + if (node->children[0]->faces || node->children[1]->faces) + Error ("!node->faces with children"); + + // FIXME: free stuff + node->planenum = PLANENUM_LEAF; + node->contents = CONTENTS_SOLID; + node->detail_seperator = false; + + if (node->brushlist) + Error ("PruneNodes: node->brushlist"); + + // combine brush lists + node->brushlist = node->children[1]->brushlist; + + for (b=node->children[0]->brushlist ; b ; b=next) + { + next = b->next; + b->next = node->brushlist; + node->brushlist = b; + } + + c_pruned++; + } +} + + +void PruneNodes (node_t *node) +{ + Sys_FPrintf( SYS_VRB, "--- PruneNodes ---\n"); + c_pruned = 0; + PruneNodes_r (node); + Sys_FPrintf( SYS_VRB, "%5i pruned nodes\n", c_pruned); +} + +//=========================================================== diff --git a/misc/mediasource/netradiant-src/tools/quake2/q2map/writebsp.c b/misc/mediasource/netradiant-src/tools/quake2/q2map/writebsp.c new file mode 100644 index 00000000..722f6ab9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/q2map/writebsp.c @@ -0,0 +1,591 @@ +/* +Copyright (C) 1999-2006 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 "qbsp.h" + +int c_nofaces; +int c_facenodes; + + +/* +========================================================= + +ONLY SAVE OUT PLANES THAT ARE ACTUALLY USED AS NODES + +========================================================= +*/ + +int planeused[MAX_MAP_PLANES]; + +/* +============ +EmitPlanes + +There is no oportunity to discard planes, because all of the original +brushes will be saved in the map. +============ +*/ +void EmitPlanes (void) +{ + int i; + dplane_t *dp; + plane_t *mp; + int planetranslate[MAX_MAP_PLANES]; + + mp = mapplanes; + for (i=0 ; inormal, dp->normal); + dp->dist = mp->dist; + dp->type = mp->type; + numplanes++; + } +} + + +//======================================================== + +void EmitMarkFace (dleaf_t *leaf_p, face_t *f) +{ + int i; + int facenum; + + while (f->merged) + f = f->merged; + + if (f->split[0]) + { + EmitMarkFace (leaf_p, f->split[0]); + EmitMarkFace (leaf_p, f->split[1]); + return; + } + + facenum = f->outputnumber; + if (facenum == -1) + return; // degenerate face + + if (facenum < 0 || facenum >= numfaces) + Error ("Bad leafface"); + for (i=leaf_p->firstleafface ; i= MAX_MAP_LEAFFACES) + Error ("MAX_MAP_LEAFFACES"); + + dleaffaces[numleaffaces] = facenum; + numleaffaces++; + } + +} + + +/* +================== +EmitLeaf +================== +*/ +void EmitLeaf (node_t *node) +{ + dleaf_t *leaf_p; + portal_t *p; + int s; + face_t *f; + bspbrush_t *b; + int i; + int brushnum; + + // emit a leaf + if (numleafs >= MAX_MAP_LEAFS) + Error ("MAX_MAP_LEAFS"); + + leaf_p = &dleafs[numleafs]; + numleafs++; + + leaf_p->contents = node->contents; + leaf_p->cluster = node->cluster; + leaf_p->area = node->area; + + // + // write bounding box info + // + VectorCopy ((short) node->mins, leaf_p->mins); + VectorCopy ((short) node->maxs, leaf_p->maxs); + + // + // write the leafbrushes + // + leaf_p->firstleafbrush = numleafbrushes; + for (b=node->brushlist ; b ; b=b->next) + { + if (numleafbrushes >= MAX_MAP_LEAFBRUSHES) + Error ("MAX_MAP_LEAFBRUSHES"); + + brushnum = b->original - mapbrushes; + for (i=leaf_p->firstleafbrush ; inumleafbrushes = numleafbrushes - leaf_p->firstleafbrush; + + // + // write the leaffaces + // + if (leaf_p->contents & CONTENTS_SOLID) + return; // no leaffaces in solids + + leaf_p->firstleafface = numleaffaces; + + for (p = node->portals ; p ; p = p->next[s]) + { + s = (p->nodes[1] == node); + f = p->face[s]; + if (!f) + continue; // not a visible portal + + EmitMarkFace (leaf_p, f); + } + + leaf_p->numleaffaces = numleaffaces - leaf_p->firstleafface; +} + + +/* +================== +EmitFace +================== +*/ +void EmitFace (face_t *f) +{ + dface_t *df; + int i; + int e; + + f->outputnumber = -1; + + if (f->numpoints < 3) + { + return; // degenerated + } + if (f->merged || f->split[0] || f->split[1]) + { + return; // not a final face + } + + // save output number so leaffaces can use + f->outputnumber = numfaces; + + if (numfaces >= MAX_MAP_FACES) + Error ("numfaces == MAX_MAP_FACES"); + df = &dfaces[numfaces]; + numfaces++; + + // planenum is used by qlight, but not quake + df->planenum = f->planenum & (~1); + df->side = f->planenum & 1; + + df->firstedge = numsurfedges; + df->numedges = f->numpoints; + df->texinfo = f->texinfo; + for (i=0 ; inumpoints ; i++) + { +// e = GetEdge (f->pts[i], f->pts[(i+1)%f->numpoints], f); + e = GetEdge2 (f->vertexnums[i], f->vertexnums[(i+1)%f->numpoints], f); + if (numsurfedges >= MAX_MAP_SURFEDGES) + Error ("numsurfedges == MAX_MAP_SURFEDGES"); + dsurfedges[numsurfedges] = e; + numsurfedges++; + } +} + +/* +============ +EmitDrawingNode_r +============ +*/ +int EmitDrawNode_r (node_t *node) +{ + dnode_t *n; + face_t *f; + int i; + + if (node->planenum == PLANENUM_LEAF) + { + EmitLeaf (node); + return -numleafs; + } + + // emit a node + if (numnodes == MAX_MAP_NODES) + Error ("MAX_MAP_NODES"); + n = &dnodes[numnodes]; + numnodes++; + + VectorCopy ((short) node->mins, n->mins); + VectorCopy ((short) node->maxs, n->maxs); + + planeused[node->planenum]++; + planeused[node->planenum^1]++; + + if (node->planenum & 1) + Error ("WriteDrawNodes_r: odd planenum"); + n->planenum = node->planenum; + n->firstface = numfaces; + + if (!node->faces) + c_nofaces++; + else + c_facenodes++; + + for (f=node->faces ; f ; f=f->next) + EmitFace (f); + + n->numfaces = numfaces - n->firstface; + + + // + // recursively output the other nodes + // + for (i=0 ; i<2 ; i++) + { + if (node->children[i]->planenum == PLANENUM_LEAF) + { + n->children[i] = -(numleafs + 1); + EmitLeaf (node->children[i]); + } + else + { + n->children[i] = numnodes; + EmitDrawNode_r (node->children[i]); + } + } + + return n - dnodes; +} + +//========================================================= + + +/* +============ +WriteBSP +============ +*/ +void WriteBSP (node_t *headnode) +{ + int oldfaces; + + c_nofaces = 0; + c_facenodes = 0; + + Sys_FPrintf( SYS_VRB, "--- WriteBSP ---\n"); + + oldfaces = numfaces; + dmodels[nummodels].headnode = EmitDrawNode_r (headnode); + EmitAreaPortals (headnode); + + Sys_FPrintf( SYS_VRB, "%5i nodes with faces\n", c_facenodes); + Sys_FPrintf( SYS_VRB, "%5i nodes without faces\n", c_nofaces); + Sys_FPrintf( SYS_VRB, "%5i faces\n", numfaces-oldfaces); +} + +//=========================================================== + +/* +============ +SetModelNumbers +============ +*/ +void SetModelNumbers (void) +{ + int i; + int models; + char value[10]; + + models = 1; + for (i=1 ; icontents = b->contents; + db->firstside = numbrushsides; + db->numsides = b->numsides; + for (j=0 ; jnumsides ; j++) + { + if (numbrushsides == MAX_MAP_BRUSHSIDES) + Error ("MAX_MAP_BRUSHSIDES"); + cp = &dbrushsides[numbrushsides]; + numbrushsides++; + cp->planenum = b->original_sides[j].planenum; + cp->texinfo = b->original_sides[j].texinfo; + } + + // add any axis planes not contained in the brush to bevel off corners + for (x=0 ; x<3 ; x++) + for (s=-1 ; s<=1 ; s+=2) + { + // add the plane + VectorCopy (vec3_origin, normal); + normal[x] = (float) s; + if (s == -1) + dist = -b->mins[x]; + else + dist = b->maxs[x]; + planenum = FindFloatPlane (normal, dist); + for (i=0 ; inumsides ; i++) + if (b->original_sides[i].planenum == planenum) + break; + if (i == b->numsides) + { + if (numbrushsides >= MAX_MAP_BRUSHSIDES) + Error ("MAX_MAP_BRUSHSIDES"); + + dbrushsides[numbrushsides].planenum = planenum; + dbrushsides[numbrushsides].texinfo = + dbrushsides[numbrushsides-1].texinfo; + numbrushsides++; + db->numsides++; + } + } + + } + +} + +//=========================================================== + +/* +================== +BeginBSPFile +================== +*/ +void BeginBSPFile (void) +{ + // these values may actually be initialized + // if the file existed when loaded, so clear them explicitly + nummodels = 0; + numfaces = 0; + numnodes = 0; + numbrushsides = 0; + numvertexes = 0; + numleaffaces = 0; + numleafbrushes = 0; + numsurfedges = 0; + + // edge 0 is not used, because 0 can't be negated + numedges = 1; + + // leave vertex 0 as an error + numvertexes = 1; + + // leave leaf 0 as an error + numleafs = 1; + dleafs[0].contents = CONTENTS_SOLID; +} + + +/* +============ +EndBSPFile +============ +*/ +void EndBSPFile (void) +{ + char path[1024]; + +#if 0 + int len; + byte *buf; +#endif + + EmitBrushes (); + EmitPlanes (); + UnparseEntities (); + + // load the pop +#if 0 + sprintf (path, "%s/pics/pop.lmp", gamedir); + len = LoadFile (path, &buf); + memcpy (dpop, buf, sizeof(dpop)); + free (buf); +#endif + + // write the map + sprintf (path, "%s.bsp", source); + Sys_Printf ("Writing %s\n", path); + WriteBSPFile (path); +} + + +/* +================== +BeginModel +================== +*/ +int firstmodleaf; +extern int firstmodeledge; +extern int firstmodelface; +void BeginModel (void) +{ + dmodel_t *mod; + int start, end; + mapbrush_t *b; + int j; + entity_t *e; + vec3_t mins, maxs; + + if (nummodels == MAX_MAP_MODELS) + Error ("MAX_MAP_MODELS"); + mod = &dmodels[nummodels]; + + mod->firstface = numfaces; + + firstmodleaf = numleafs; + firstmodeledge = numedges; + firstmodelface = numfaces; + + // + // bound the brushes + // + e = &entities[entity_num]; + + start = e->firstbrush; + end = start + e->numbrushes; + ClearBounds (mins, maxs); + + for (j=start ; jnumsides) + continue; // not a real brush (origin brush) + AddPointToBounds (b->mins, mins, maxs); + AddPointToBounds (b->maxs, mins, maxs); + } + + VectorCopy (mins, mod->mins); + VectorCopy (maxs, mod->maxs); +} + + +/* +================== +EndModel +================== +*/ +void EndModel (void) +{ + dmodel_t *mod; + + mod = &dmodels[nummodels]; + + mod->numfaces = numfaces - mod->firstface; + + nummodels++; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata/anorms.h b/misc/mediasource/netradiant-src/tools/quake2/qdata/anorms.h new file mode 100644 index 00000000..65170ad9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata/anorms.h @@ -0,0 +1,162 @@ + { -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 }, diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata/images.c b/misc/mediasource/netradiant-src/tools/quake2/qdata/images.c new file mode 100644 index 00000000..ec4e99f3 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata/images.c @@ -0,0 +1,763 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" +#include "inout.h" + +char mip_prefix[1024]; // directory to dump the textures in + +qboolean colormap_issued; +byte colormap_palette[768]; + +/* +============== +RemapZero + +Replaces all 0 bytes in an image with the closest palette entry. +This is because NT won't let us change index 0, so any palette +animation leaves those pixels untouched. +============== +*/ +void RemapZero (byte *pixels, byte *palette, int width, int height) +{ + int i, c; + int alt_zero; + int value, best; + + alt_zero = 0; + best = 9999999; + for (i=1 ; i<255 ; i++) + { + value = palette[i*3+0]+palette[i*3+1]+palette[i*3+2]; + if (value < best) + { + best = value; + alt_zero = i; + } + } + + c = width*height; + for (i=0 ; ibyteimagewidth || 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 ; ybyteimagewidth || 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 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 = true; + + 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 +must be multiples of sixteen +SURF_WINDOW +============== +*/ +void Cmd_Mip (void) +{ + int x,y,xl,yl,xh,yh,w,h; + byte *screen_p, *source; + int linedelta; + miptex_t *qtex; + int miplevel, mipstep; + int xx, yy, pix; + int count; + int flags, value, contents; + mipparm_t *mp; + char lumpname[64]; + byte *lump_p; + char filename[1024]; + char animname[64]; + + GetToken (false); + strcpy (lumpname, token); + + GetToken (false); + xl = atoi (token); + GetToken (false); + yl = atoi (token); + GetToken (false); + w = atoi (token); + GetToken (false); + h = atoi (token); + + if ( (w & 15) || (h & 15) ) + Error ("line %i: miptex sizes must be multiples of 16", scriptline); + + flags = 0; + contents = 0; + value = 0; + + animname[0] = 0; + + // get optional flags and values + while (TokenAvailable ()) + { + GetToken (false); + + for (mp=mipparms ; mp->name ; mp++) + { + if (!strcmp(mp->name, token)) + { + switch (mp->type) + { + case pt_animvalue: + GetToken (false); // specify the next animation frame + strcpy (animname, token); + break; + case pt_flags: + flags |= mp->flags; + break; + case pt_contents: + contents |= mp->flags; + break; + case pt_flagvalue: + flags |= mp->flags; + GetToken (false); // specify the light value + value = atoi(token); + break; + } + break; + } + } + if (!mp->name) + Error ("line %i: unknown parm %s", scriptline, token); + } + + sprintf (filename, "%stextures/%s/%s.wal", gamedir, mip_prefix, lumpname); + if (g_release) + return; // textures are only released by $maps + + xh = xl+w; + yh = yl+h; + + qtex = malloc (sizeof(miptex_t) + w*h*2); + memset (qtex, 0, sizeof(miptex_t)); + + qtex->width = LittleLong(w); + qtex->height = LittleLong(h); + qtex->flags = LittleLong(flags); + qtex->contents = LittleLong(contents); + qtex->value = LittleLong(value); + sprintf (qtex->name, "%s/%s", mip_prefix, lumpname); + if (animname[0]) + sprintf (qtex->animname, "%s/%s", mip_prefix, animname); + + lump_p = (byte *)(&qtex->value+1); + + screen_p = byteimage + yl*byteimagewidth + xl; + linedelta = byteimagewidth - w; + + source = lump_p; + qtex->offsets[0] = LittleLong(lump_p - (byte *)qtex); + + for (y=yl ; yoffsets[miplevel] = LittleLong(lump_p - (byte *)qtex); + + mipstep = 1< /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/models.o : models.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/sprites.o : sprites.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/images.o : images.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/tables.o : tables.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i + +$(ODIR)/cmdlib.o : ../common/cmdlib.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/scriplib.o : ../common/scriplib.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/lbmlib.o : ../common/lbmlib.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/mathlib.o : ../common/mathlib.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/trilib.o : ../common/trilib.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/l3dslib.o : ../common/l3dslib.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i +$(ODIR)/threads.o : ../common/threads.c + cc $(CFLAGS) -E $? | tr -d '\015' > /tmp/temp.i + cc $(CFLAGS) -o $@ /tmp/temp.i diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata/models.c b/misc/mediasource/netradiant-src/tools/quake2/qdata/models.c new file mode 100644 index 00000000..2316b0f6 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata/models.c @@ -0,0 +1,1152 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" +#include "inout.h" + +//================================================================= + +typedef struct +{ + int numnormals; + vec3_t normalsum; +} vertexnormals_t; + +typedef struct +{ + vec3_t v; + int lightnormalindex; +} trivert_t; + +typedef struct +{ + vec3_t mins, maxs; + char name[16]; + trivert_t v[MAX_VERTS]; +} frame_t; + +//================================================================ + +frame_t g_frames[MAX_FRAMES]; + +dmdl_t model; + + +float scale_up; // set by $scale +vec3_t adjust; // set by $origin +int g_fixedwidth, g_fixedheight; // set by $skinsize + + +// +// base frame info +// +vec3_t base_xyz[MAX_VERTS]; +dstvert_t base_st[MAX_VERTS]; +dtriangle_t triangles[MAX_TRIANGLES]; + +int triangle_st[MAX_TRIANGLES][3][2]; + +// the command list holds counts, s/t values, and xyz indexes +// that are valid for every frame +int commands[16384]; +int numcommands; +int numglverts; +int used[MAX_TRIANGLES]; + +char g_skins[MAX_MD2SKINS][64]; + +char cdarchive[1024]; +char cdpartial[1024]; +char cddir[1024]; + +char modelname[64]; // empty unless $modelname issued (players) + +#define NUMVERTEXNORMALS 162 + +float avertexnormals[NUMVERTEXNORMALS][3] = { +#include "anorms.h" +}; + +FILE *headerouthandle = NULL; + +//============================================================== + +/* +=============== +ClearModel +=============== +*/ +void ClearModel (void) +{ + memset (&model, 0, sizeof(model)); + + modelname[0] = 0; + scale_up = 1.0; + VectorCopy (vec3_origin, adjust); + g_fixedwidth = g_fixedheight = 0; + g_skipmodel = false; +} + + +void H_printf(char *fmt, ...) +{ + va_list argptr; + char name[1024]; + + if (!headerouthandle) + { + sprintf (name, "%s/tris.h", cddir); + headerouthandle = SafeOpenWrite (name); + fprintf(headerouthandle, "// %s\n\n", cddir); + fprintf(headerouthandle, "// This file generated by qdata - Do NOT Modify\n\n"); + } + + va_start (argptr, fmt); + vfprintf (headerouthandle, fmt, argptr); + va_end (argptr); +} + + +/* +============ +WriteModelFile +============ +*/ +void WriteModelFile (FILE *modelouthandle) +{ + int i; + dmdl_t modeltemp; + int j, k; + frame_t *in; + daliasframe_t *out; + byte buffer[MAX_VERTS*4+128]; + float v; + int c_on, c_off; + + model.ident = IDALIASHEADER; + model.version = ALIAS_VERSION; + model.framesize = (int)&((daliasframe_t *)0)->verts[model.num_xyz]; + model.num_glcmds = numcommands; + model.ofs_skins = sizeof(dmdl_t); + model.ofs_st = model.ofs_skins + model.num_skins * MAX_SKINNAME; + model.ofs_tris = model.ofs_st + model.num_st*sizeof(dstvert_t); + model.ofs_frames = model.ofs_tris + model.num_tris*sizeof(dtriangle_t); + model.ofs_glcmds = model.ofs_frames + model.num_frames*model.framesize; + model.ofs_end = model.ofs_glcmds + model.num_glcmds*4; + + // + // write out the model header + // + for (i=0 ; iname, in->name); + for (j=0 ; j<3 ; j++) + { + out->scale[j] = (in->maxs[j] - in->mins[j])/255; + out->translate[j] = in->mins[j]; + } + + for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; + + for (k=0 ; k<3 ; k++) + { + // scale to byte values & min/max check + v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); + + // clamp, so rounding doesn't wrap from 255.6 to 0 + if (v > 255.0) + v = 255.0; + if (v < 0) + v = 0; + out->verts[j].v[k] = v; + } + } + + for (j=0 ; j<3 ; j++) + { + out->scale[j] = LittleFloat (out->scale[j]); + out->translate[j] = LittleFloat (out->translate[j]); + } + + SafeWrite (modelouthandle, out, model.framesize); + } + + // + // write out glcmds + // + SafeWrite (modelouthandle, commands, numcommands*4); +} + + +/* +=============== +FinishModel +=============== +*/ +void FinishModel (void) +{ + FILE *modelouthandle; + int i; + char name[1024]; + + if (!model.num_frames) + return; + +// +// copy to release directory tree if doing a release build +// + if (g_release) + { + if (modelname[0]) + sprintf (name, "%s", modelname); + else + sprintf (name, "%s/tris.md2", cdpartial); + ReleaseFile (name); + + for (i=0 ; iindex_xyz[(startv)%3]; + strip_xyz[1] = last->index_xyz[(startv+1)%3]; + strip_xyz[2] = last->index_xyz[(startv+2)%3]; + strip_st[0] = last->index_st[(startv)%3]; + strip_st[1] = last->index_st[(startv+1)%3]; + strip_st[2] = last->index_st[(startv+2)%3]; + + strip_tris[0] = starttri; + stripcount = 1; + + m1 = last->index_xyz[(startv+2)%3]; + st1 = last->index_st[(startv+2)%3]; + m2 = last->index_xyz[(startv+1)%3]; + st2 = last->index_st[(startv+1)%3]; + + // look for a matching triangle +nexttri: + for (j=starttri+1, check=&triangles[starttri+1] + ; jindex_xyz[k] != m1) + continue; + if (check->index_st[k] != st1) + continue; + if (check->index_xyz[ (k+1)%3 ] != m2) + continue; + if (check->index_st[ (k+1)%3 ] != st2) + continue; + + // this is the next part of the fan + + // if we can't use this triangle, this tristrip is done + if (used[j]) + goto done; + + // the new edge + if (stripcount & 1) + { + m2 = check->index_xyz[ (k+2)%3 ]; + st2 = check->index_st[ (k+2)%3 ]; + } + else + { + m1 = check->index_xyz[ (k+2)%3 ]; + st1 = check->index_st[ (k+2)%3 ]; + } + + strip_xyz[stripcount+2] = check->index_xyz[ (k+2)%3 ]; + strip_st[stripcount+2] = check->index_st[ (k+2)%3 ]; + strip_tris[stripcount] = j; + stripcount++; + + used[j] = 2; + goto nexttri; + } + } +done: + + // clear the temp used flags + for (j=starttri+1 ; jindex_xyz[(startv)%3]; + strip_xyz[1] = last->index_xyz[(startv+1)%3]; + strip_xyz[2] = last->index_xyz[(startv+2)%3]; + strip_st[0] = last->index_st[(startv)%3]; + strip_st[1] = last->index_st[(startv+1)%3]; + strip_st[2] = last->index_st[(startv+2)%3]; + + strip_tris[0] = starttri; + stripcount = 1; + + m1 = last->index_xyz[(startv+0)%3]; + st1 = last->index_st[(startv+0)%3]; + m2 = last->index_xyz[(startv+2)%3]; + st2 = last->index_st[(startv+2)%3]; + + + // look for a matching triangle +nexttri: + for (j=starttri+1, check=&triangles[starttri+1] + ; jindex_xyz[k] != m1) + continue; + if (check->index_st[k] != st1) + continue; + if (check->index_xyz[ (k+1)%3 ] != m2) + continue; + if (check->index_st[ (k+1)%3 ] != st2) + continue; + + // this is the next part of the fan + + // if we can't use this triangle, this tristrip is done + if (used[j]) + goto done; + + // the new edge + m2 = check->index_xyz[ (k+2)%3 ]; + st2 = check->index_st[ (k+2)%3 ]; + + strip_xyz[stripcount+2] = m2; + strip_st[stripcount+2] = st2; + strip_tris[stripcount] = j; + stripcount++; + + used[j] = 2; + goto nexttri; + } + } +done: + + // clear the temp used flags + for (j=starttri+1 ; j bestlen) + { + besttype = type; + bestlen = len; + for (j=0 ; j= 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_fixedwidth / 2; + iheight = g_fixedheight; + + s_scale = (float)(iwidth-4) / width; + t_scale = (float)(iheight-4) / height; + } + +// +// determine which side of each triangle to map the texture to +// + for (i=0 ; i 0) + { + basex = iwidth + 2; + } + else + { + basex = 2; + } + basey = 2; + + for (j=0 ; j<3 ; j++) + { + pbasevert = ptri[i].verts[j]; + + triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); + triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); + } + } + +// make the width a multiple of 4; some hardware requires this, and it ensures +// dword alignment for each scan + swidth = iwidth*2; + model.skinwidth = (swidth + 3) & ~3; + model.skinheight = iheight; +} + + +/* +================= +Cmd_Base +================= +*/ +void Cmd_Base (void) +{ + triangle_t *ptri; + int i, j, k; + int time1; + char file1[1024]; + + GetToken (false); + + if (g_skipmodel || g_release || g_archive) + return; + + printf ("---------------------\n"); + sprintf (file1, "%s/%s.%s", cdarchive, token, trifileext); + printf ("%s\n", file1); + + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s.%s", cddir, token, trifileext); + + time1 = FileTime (file1); + if (time1 == -1) + Error ("%s doesn't exist", file1); + +// +// load the base triangles +// + if (do3ds) + Load3DSTriangleList (file1, &ptri, &model.num_tris); + else + LoadTriangleList (file1, &ptri, &model.num_tris); + +// +// get the ST values +// + BuildST (ptri, model.num_tris); + +// +// run through all the base triangles, storing each unique vertex in the +// base vertex list and setting the indirect triangles to point to the base +// vertices +// + for (i=0 ; i= '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.%s",cddir, base, suffix, trifileext); + time1 = FileTime (file1); + if (time1 != -1) + { + sprintf (retname, "%s%s.%s", base, suffix, trifileext); + return retname; + } + + // check for 'run.1' + sprintf (file1, "%s/%s.%s",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; +} + +/* +=============== +GrabFrame +=============== +*/ +void GrabFrame (char *frame) +{ + triangle_t *ptri; + int i, j; + trivert_t *ptrivert; + int num_tris; + char file1[1024]; + frame_t *fr; + vertexnormals_t vnorms[MAX_VERTS]; + int index_xyz; + char *framefile; + + // the frame 'run1' will be looked for as either + // run.1 or run1.tri, so the new alias sequence save + // feature an be used + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + + printf ("grabbing %s\n", file1); + + if (model.num_frames >= MAX_FRAMES) + Error ("model.num_frames >= MAX_FRAMES"); + fr = &g_frames[model.num_frames]; + model.num_frames++; + + strcpy (fr->name, frame); + +// +// load the frame +// + if (do3ds) + Load3DSTriangleList (file1, &ptri, &num_tris); + else + LoadTriangleList (file1, &ptri, &num_tris); + + if (num_tris != model.num_tris) + Error ("%s: number of triangles doesn't match base frame\n", file1); + +// +// allocate storage for the frame's vertices +// + ptrivert = fr->v; + + for (i=0 ; imins, fr->maxs); + +// +// 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 ; imins, fr->maxs); + + VectorAdd (vnorms[index_xyz].normalsum, normal, vnorms[index_xyz].normalsum); + vnorms[index_xyz].numnormals++; + } + } + +// +// calculate the vertex normals, match them to the template list, and store the +// index of the best match +// + for (i=0 ; i maxdot) + { + maxdot = dot; + maxdotindex = j; + } + } + + ptrivert[i].lightnormalindex = maxdotindex; + } + + free (ptri); +} + +/* +=============== +Cmd_Frame +=============== +*/ +void Cmd_Frame (void) +{ + while (TokenAvailable()) + { + GetToken (false); + if (g_skipmodel) + continue; + if (g_release || g_archive) + { + model.num_frames = 1; // don't skip the writeout + continue; + } + + H_printf("#define FRAME_%-16s\t%i\n", token, model.num_frames); + + GrabFrame (token); + } +} + + +/* +=============== +Cmd_Skin + +Skins aren't actually stored in the file, only a reference +is saved out to the header file. +=============== +*/ +void Cmd_Skin (void) +{ + byte *palette; + byte *pixels; + int width, height; + byte *cropped; + int y; + char name[1024], savename[1024]; + + GetToken (false); + + if (model.num_skins == MAX_MD2SKINS) + Error ("model.num_skins == MAX_MD2SKINS"); + + if (g_skipmodel) + return; + + sprintf (name, "%s/%s.lbm", cdarchive, token); + strcpy (name, ExpandPathAndArchive( name ) ); +// sprintf (name, "%s/%s.lbm", cddir, token); + + if (TokenAvailable()) + { + GetToken (false); + sprintf (g_skins[model.num_skins], "%s.pcx", token); + sprintf (savename, "%s%s.pcx", gamedir, g_skins[model.num_skins]); + } + else + { + sprintf (savename, "%s/%s.pcx", cddir, token); + sprintf (g_skins[model.num_skins], "%s/%s.pcx", cdpartial, token); + } + + model.num_skins++; + + if (g_skipmodel || g_release || g_archive) + return; + + // load the image + printf ("loading %s\n", name); + Load256Image (name, &pixels, &palette, &width, &height); + RemapZero (pixels, palette, width, height); + + // crop it to the proper size + cropped = malloc (model.skinwidth*model.skinheight); + for (y=0 ; y= sizeof(pf->name)) + Error ("Filename too long for pak: %s", filename); + + len = LoadFile (source, (void **)&buf); + + if (g_compress_pak && len < 4096*1024 ) + { + cblock_t in, out; + cblock_t Huffman (cblock_t in); + + in.count = len; + in.data = buf; + + out = Huffman (in); + + if (out.count < in.count) + { + printf (" compressed from %i to %i\n", in.count, out.count); + free (in.data); + buf = out.data; + len = out.count; + } + else + free (out.data); + } + + strcpy (pf->name, filename); + pf->filepos = LittleLong(ftell(pakfile)); + pf->filelen = LittleLong(len); + pf++; + + SafeWrite (pakfile, buf, len); + + free (buf); +} + + +/* +============== +FinishPak +============== +*/ +void FinishPak (void) +{ + int dirlen; + int d; + int i; + unsigned checksum; + + if (!g_pak) + return; + + pakheader.id[0] = 'P'; + pakheader.id[1] = 'A'; + pakheader.id[2] = 'C'; + pakheader.id[3] = 'K'; + dirlen = (byte *)pf - (byte *)pfiles; + pakheader.dirofs = LittleLong(ftell(pakfile)); + pakheader.dirlen = LittleLong(dirlen); + + checksum = Com_BlockChecksum ( (void *)pfiles, dirlen ); + + SafeWrite (pakfile, pfiles, dirlen); + + i = ftell (pakfile); + + fseek (pakfile, 0, SEEK_SET); + SafeWrite (pakfile, &pakheader, sizeof(pakheader)); + fclose (pakfile); + + d = pf - pfiles; + printf ("%i files packed in %i bytes\n",d, i); + printf ("checksum: 0x%x\n", checksum); +} + + +/* +=============== +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 (false); + 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 +#include + +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 ; id_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 (false); + 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= argc) + Error ("usage: %s [-archive ] [-release ] [-only ] [-3ds] file.qgr", argv[ 0 ] ); + + if (do3ds) + trifileext = ext_3ds; + else + trifileext = ext_tri; + + for ( ; i +#include +#include +#include +#include + +#include "cmdlib.h" +#include "scriplib.h" +#include "mathlib.h" +#include "trilib.h" +#include "lbmlib.h" +#include "q2_threads.h" +#include "l3dslib.h" +#include "bspfile.h" + +#ifdef WIN32 + #ifdef NDEBUG // Don't show in a Release build + #pragma warning(disable : 4305) // truncate from double to float + #pragma warning(disable : 4244) // conversion from double to float + #pragma warning(disable : 4018) // signed/unsigned mismatch + #endif +#endif + +void Cmd_Modelname (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_Skin (void); +void Cmd_Skinsize (void); +void FinishModel (void); + +void Cmd_Inverse16Table( void ); + +void Cmd_SpriteName (void); +void Cmd_Load (void); +void Cmd_SpriteFrame (void); +void FinishSprite (void); + +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_Alphalight (void); + +void Cmd_Video (void); + +void RemapZero (byte *pixels, byte *palette, int width, int height); + +void ReleaseFile (char *filename); + +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 char *trifileext; diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata/sprites.c b/misc/mediasource/netradiant-src/tools/quake2/qdata/sprites.c new file mode 100644 index 00000000..a70f0074 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata/sprites.c @@ -0,0 +1,228 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" +#include "inout.h" + +#define MAX_SPRFRAMES MAX_MD2SKINS + +dsprite_t sprite; +dsprframe_t frames[MAX_SPRFRAMES]; + +byte *byteimage, *lbmpalette; +int byteimagewidth, byteimageheight; + +char spritename[1024]; + + +void FinishSprite (void); +void Cmd_Spritename (void); + + + +/* +============== +FinishSprite +============== +*/ +void FinishSprite (void) +{ + FILE *spriteouthandle; + int i, curframe; + dsprite_t spritetemp; + char savename[1024]; + + if (sprite.numframes == 0) + return; + + if (!strlen(spritename)) + Error ("Didn't name sprite file"); + + sprintf (savename, "%s%s.sp2", gamedir, spritename); + + if (g_release) + { + char name[1024]; + + sprintf (name, "%s.sp2", spritename); + ReleaseFile (name); + spritename[0] = 0; // clear for a new sprite + sprite.numframes = 0; + return; + } + + + printf ("saving in %s\n", savename); + CreatePath (savename); + spriteouthandle = SafeOpenWrite (savename); + + +// +// write out the sprite header +// + spritetemp.ident = LittleLong (IDSPRITEHEADER); + spritetemp.version = LittleLong (SPRITE_VERSION); + spritetemp.numframes = LittleLong (sprite.numframes); + + SafeWrite (spriteouthandle, &spritetemp, 12); + +// +// write out the frames +// + curframe = 0; + + for (i=0 ; i 256) || (h > 256)) + Error ("Sprite has a dimension longer than 256"); + + xh = xl+w; + yh = yl+h; + + if (sprite.numframes >= MAX_SPRFRAMES) + Error ("Too many frames; increase MAX_SPRFRAMES\n"); + + pframe = &frames[sprite.numframes]; + pframe->width = w; + pframe->height = h; + pframe->origin_x = ox; + pframe->origin_y = oy; + sprintf (pframe->name, "%s_%i.pcx", spritename, sprite.numframes); + sprintf (savename, "%s%s_%i.pcx", gamedir, spritename, sprite.numframes); + sprite.numframes++; + + if (g_release) + { + ReleaseFile (pframe->name); + return; + } + + // crop it to the proper size + cropped = malloc (w*h); + for (y=0 ; y> 5 ) & 63 ) << 2; + b[0] = ( ( color >> 11 ) & 31 ) << 3; + + for ( i = 0; i < 256; i++ ) + { + r[1] = ( d_8to24table[i] >> 0 ) & 0xFF; + g[1] = ( d_8to24table[i] >> 8 ) & 0xFF; + b[1] = ( d_8to24table[i] >> 16 ) & 0xFF; + + d = ( r[1] - r[0] ) * ( r[1] - r[0] ) + + ( g[1] - g[0] ) * ( g[1] - g[0] ) + + ( b[1] - b[0] ) * ( b[1] - b[0] ); + + if ( d < closest_distance_so_far ) + { + closest_distance_so_far = d; + closest_so_far = i; + } + } + + return closest_so_far; +} +*/ + +extern byte BestColor( int, int, int, int, int ); + +void Inverse16_BuildTable( void ) +{ + int i; + + /* + ** create the 16-to-8 table + */ + for ( i = 0; i < 65536; i++ ) + { + int r = i & 31; + int g = ( i >> 5 ) & 63; + int b = ( i >> 11 ) & 31; + + r <<= 3; + g <<= 2; + b <<= 3; + + inverse16to8table[i] = BestColor( r, g, b, 0, 255 ); + } +} + +void Alphalight_Thread (int i) +{ + int j; + float r, g, b; + float mr, mg, mb, ma; + float distortion, bestdistortion; + float v; + + r = (i>>10) * (1.0/16); + g = ((i>>5)&31) * (1.0/16); + b = (i&31) * (1.0/16); + + bestdistortion = 999999; + for (j=0 ; j<16*16*16*16 ; j++) + { + mr = (j>>12) * (1.0/16); + mg = ((j>>8)&15) * (1.0/16); + mb = ((j>>4)&15) * (1.0/16); + ma = (j&15) * (1.0/16); + + v = r * 0.5 - (mr*ma + 0.5*(1.0-ma)); + distortion = v*v; + v = g * 0.5 - (mg*ma + 0.5*(1.0-ma)); + distortion += v*v; + v = b * 0.5 - (mb*ma + 0.5*(1.0-ma)); + distortion += v*v; + + distortion *= 1.0 + ma*4; + + if (distortion < bestdistortion) + { + bestdistortion = distortion; + alphamap[i] = j; + } + } +} + +void Cmd_Alphalight (void) +{ + char savename[1024]; + + GetToken (false); + + if (g_release) + { + ReleaseFile (token); + return; + } + + sprintf (savename, "%s%s", gamedir, token); + printf ("Building alphalight table...\n"); + + RunThreadsOnIndividual (32*32*32, true, Alphalight_Thread); + + SaveFile (savename, (byte *)alphamap, sizeof(alphamap)); +} + + +void Cmd_Inverse16Table( void ) +{ + char savename[1024]; + + if ( g_release ) + { + sprintf (savename, "pics/16to8.dat"); + ReleaseFile( savename ); + return; + } + + sprintf (savename, "%spics/16to8.dat", gamedir); + printf ("Building inverse 16-to-8 table...\n"); + + Inverse16_BuildTable(); + + SaveFile( savename, (byte *) inverse16to8table, sizeof( inverse16to8table ) ); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata/video.c b/misc/mediasource/netradiant-src/tools/quake2/qdata/video.c new file mode 100644 index 00000000..c4027171 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata/video.c @@ -0,0 +1,1259 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" +#include "inout.h" + +byte *soundtrack; +char 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; + + +int samplecounts[0x10000]; + +wavinfo_t 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; + + soundtrack = NULL; + sprintf (name, "%svideo/%s/%s.wav", gamedir, base, base); + printf ("%s\n", name); + f = fopen (name, "rb"); + if (!f) + { + printf ("no soundtrack for %s\n", base); + return; + } + len = Q_filelength(f); + soundtrack = malloc(len); + fread (soundtrack, 1, len, f); + fclose (f); + + wavinfo = GetWavinfo (name, soundtrack, len); + + // count samples for compression + memset (samplecounts, 0, sizeof(samplecounts)); + + j = wavinfo.samples/2; + for (i=0 ; i wavinfo.samples || !soundtrack) + fwrite (&empty, 1, width, output); + else + fwrite (soundtrack + wavinfo.dataofs + sample*width, 1, width,output); + } +} + +//========================================================================== + +/* +================== +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 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>8)&255; + *out_p++ = (in.count>>16)&255; + *out_p++ = (in.count>>24)&255; + + // write head index + for (i=0 ; i>8)&255; + *out_p++ = (i>>16)&255; + *out_p++ = (i>>24)&255; + + // write the L column + for (i=0 ; i 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 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>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 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) + max = in.count - i; + + start = lzss_head[val]; + while (start != -1 && start >= i-BACK_WINDOW) + { + // count match length + for (j=0 ; 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 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<>3] |= 1<<(outbits&7); + } + else + { // output a phrase + outbits++; // leave a 0 bit to mark phrase + for (j=0 ; j>3] |= 1<<(outbits&7); + for (j=0 ; j>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 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 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 max) + max = hnodes1[i][j].count; + } + if (max == 0) + max = 1; + total = 0; + for (j=0 ; j 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>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<>3] |= 1<<(outbits&7); + outbits++; + } + i += rept-1; + } +#endif + } + + out_p += (outbits+7)>>3; + + out.count = out_p - out.data; + + return out; +} + +//========================================================================== + + +/* +=================== +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.pcx", gamedir, base, base, ten3, ten2, ten1, ten0); + else + sprintf (name, "%svideo/%s/%s%i%i%i.pcx", gamedir, base, base, ten2, ten1, ten0); + + f = fopen(name, "rb"); + if (!f) + { + in.data = NULL; + return in; + } + fclose (f); + + printf ("%s\n", name); + Load256Image (name, &in.data, palette, &width, &height); + in.count = width*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) +{ + char savename[1024]; + char name[1024]; + FILE *output; + int startframe, frame; + byte *palette; + int width, height; + byte current_palette[768]; + int command; + int i; + int digits; + cblock_t in, huffman; + int swap; + + + GetToken (false); + strcpy (base, token); + if (g_release) + { +// sprintf (savename, "video/%s.cin", token); +// ReleaseFile (savename); + return; + } + + GetToken (false); + digits = atoi(token); + + // optionally skip frames + if (TokenAvailable ()) + { + GetToken (false); + startframe = atoi(token); + } + else + startframe=0; + + sprintf (savename, "%svideo/%s.cin", gamedir, base); + + + // clear stuff + memset (charbits1, 0, sizeof(charbits1)); + memset (charbitscount1, 0, sizeof(charbitscount1)); + memset (hnodes1, 0, sizeof(hnodes1)); + memset (numhnodes1, 0, sizeof(numhnodes1)); + memset (order0counts, 0, sizeof(order0counts)); + + + // load the entire sound wav file if present + LoadSoundtrack (); + + if (digits == 4) + sprintf (name, "%svideo/%s/%s0000.pcx", gamedir, base, base); + else + sprintf (name, "%svideo/%s/%s000.pcx", gamedir, base, base); + + printf ("%s\n", name); + Load256Image (name, NULL, &palette, &width, &height); + + output = fopen (savename, "wb"); + if (!output) + Error ("Can't open %s", savename); + + // write header info + i = LittleLong (width); + fwrite (&i, 4, 1, output); + i = LittleLong (height); + fwrite (&i, 4, 1, output); + i = LittleLong (wavinfo.rate); + fwrite (&i, 4, 1, output); + i = LittleLong (wavinfo.width); + fwrite (&i, 4, 1, output); + i = LittleLong (wavinfo.channels); + fwrite (&i, 4, 1, output); + + // build the dictionary + for ( frame=startframe ; ; frame++) + { + printf ("counting ", frame); + in = LoadFrame (base, frame, digits, &palette); + if (!in.data) + break; + Huffman1_Count (in); + free (in.data); + } + printf ("\n"); + + // build nodes and write counts + Huffman1_Build (output); + + + memset (current_palette, 0, sizeof(current_palette)); + + // compress it with the dictionary + for (frame=startframe ; ; frame++) + { + printf ("packing ", frame); + in = LoadFrame (base, frame, digits, &palette); + if (!in.data) + break; + + // see if the palette has changed + for (i=0 ; i<768 ; i++) + if (palette[i] != current_palette[i]) + { + // write a palette change + memcpy (current_palette, palette, sizeof(current_palette)); + command = LittleLong(1); + fwrite (&command, 1, 4, output); + fwrite (current_palette, 1, sizeof(current_palette), output); + break; + } + if (i == 768) + { + command = 0; // no palette change + fwrite (&command, 1, 4, output); + } + + // save the image + huffman = Huffman1 (in); + printf ("%5i bytes after huffman1\n", huffman.count); + + swap = LittleLong (huffman.count); + fwrite (&swap, 1, sizeof(swap), output); + + fwrite (huffman.data, 1, huffman.count, output); + + // save some sound samples + WriteSound (output, frame); + + free (palette); + free (in.data); + free (huffman.data); + } + printf ("\n"); + + // write end-of-file command + command = 2; + fwrite (&command, 1, 4, output); + + printf ("Total size: %i\n", ftell (output)); + + fclose (output); + + if (soundtrack) + free (soundtrack); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/adpcm.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/adpcm.h new file mode 100644 index 00000000..e70f9664 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/adpcm.h @@ -0,0 +1,49 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +/* +** adpcm.h - include file for adpcm coder. +** +** Version 1.0, 7-Jul-92. +** +** Modded 10/3/98 +** John Scott +*/ + +typedef struct adpcm_state_s +{ + short in_valprev; // Previous output value + short in_index; // Index into stepsize table + short out_valprev; // Previous output value + short out_index; // Index into stepsize table + int count; // Number of sample counts +} adpcm_state_t; + +typedef struct adpcm_s +{ + adpcm_state_t state; + char adpcm[0x10000]; +} adpcm_t; + +void adpcm_coder(short [], adpcm_t *); +void adpcm_decoder(adpcm_t *, short []); + +// end diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/animcomp.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/animcomp.c new file mode 100644 index 00000000..6af022f6 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/animcomp.c @@ -0,0 +1,351 @@ +/* +Copyright (C) 1999-2006 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 +#include +#include +#include "animcomp.h" + + +void *SafeMalloc(size_t n, char *desc); + + + +float *matrix; +float *delta; +float *best; +float *comp; +float *tcomp; +float *bestcomp; +float *frames; +float *base; + +int MatWidth; +int MatHeight; +int CFrameSize; +int nFrames; + + +void AnimCompressInit(int nframes,int nVerts,int CompressedFrameSize) +{ + nFrames=nframes; + MatWidth=nVerts*3; + MatHeight=CompressedFrameSize; + CFrameSize=CompressedFrameSize; + matrix=(float *)SafeMalloc(MatWidth*MatHeight*sizeof(float), "AnimCompressInit"); + best=(float *)SafeMalloc(MatWidth*MatHeight*sizeof(float), "AnimCompressInit"); + delta=(float *)SafeMalloc(MatWidth*MatHeight*sizeof(float), "AnimCompressInit"); + comp=(float *)SafeMalloc(CFrameSize*nFrames*sizeof(float), "AnimCompressInit"); + tcomp=(float *)SafeMalloc(CFrameSize*nFrames*sizeof(float), "AnimCompressInit"); + bestcomp=(float *)SafeMalloc(CFrameSize*nFrames*sizeof(float), "AnimCompressInit"); + base=(float *)SafeMalloc(MatWidth*sizeof(float), "AnimCompressInit"); + frames=(float *)SafeMalloc(MatWidth*nFrames*sizeof(float), "AnimCompressInit"); +} + +void AnimSetFrame(int frame,int index,float x,float y,float z) +{ + frames[frame*MatWidth+index*3]=x; + frames[frame*MatWidth+index*3+1]=y; + frames[frame*MatWidth+index*3+2]=z; +} + +typedef struct +{ + int index; + float val; +} SORTP; + + +#define F_RANDOM (((float)rand())/(float)RAND_MAX) + +extern void DOsvd(float *a,float *res,float *comp,float *values,int nframes,int framesize,int compressedsize); + +void AnimCompressDoit() +{ + float compression; + float *rescale; + float *ans; + float maxdev; + float avedev; + float tmp; + int j,k,l,numave; + + for (k=0;kmaxdev) + maxdev=tmp; + avedev+=tmp; + numave++; + } + } + avedev/=(float)numave; +printf("%f Max Deviation (inches) %f Ave Dev. (inches)\n",maxdev,avedev); +printf("%d bytes original size\n",MatWidth*nFrames); +printf("%d bytes of overhead\n",MatWidth*MatHeight); +printf("%d bytes/frame * %d frames = %d bytes\n",CFrameSize,nFrames,CFrameSize*nFrames); + compression=(float)(MatWidth*MatHeight+CFrameSize*nFrames+MatWidth); + compression/=(float)(MatWidth*nFrames); +printf("Overall compression = %f %%\n",100.0f-100.0f*compression); + compression=(float)(CFrameSize); + compression/=(float)(MatWidth); +printf("frame size compression = %f %%\n",100.0f-100.0f*compression); + free(rescale); + free(ans); +} + +void AnimCompressToBytes(float *trans,float *scale,char *mat,char *ccomp,unsigned char *cbase,float *cscale,float *coffset,float *bmin,float *bmax) +{ + int k,l,nv,j; + float maxdev; + float avedev; + float tmp; + int numave; + float t,mx; + float *ans; + + + nv=MatWidth/3; + + trans[0]=1E30f; + scale[0]=-1E30f; + trans[1]=1E30f; + scale[1]=-1E30f; + trans[2]=1E30f; + scale[2]=-1E30f; + for (k=0;kscale[0]) + scale[0]=base[k]; + if (base[k]scale[1]) + scale[1]=base[k+1]; + if (base[k+1]scale[2]) + scale[2]=base[k+2]; + if (base[k+2]255.0f) + t=255.0f; + cbase[k]=(unsigned char)t; + + t=(base[k+1]-trans[1])/scale[1]; + if (t<0.0f) + t=0.0f; + if (t>255.0f) + t=255.0f; + cbase[k+1]=(unsigned char)t; + + t=(base[k+2]-trans[2])/scale[2]; + if (t<0.0f) + t=0.0f; + if (t>255.0f) + t=255.0f; + cbase[k+2]=(unsigned char)t; + } + for (l=0;lmx) + mx=(float)fabs(best[l*MatWidth+k]); + } + if (mx>1E-8) + { + mx/=127.0f; + coffset[l]=1E30f; + cscale[l]=-1E30f; + for (j=0;jcscale[l]) + cscale[l]=bestcomp[j*MatHeight+l]; + if (bestcomp[j*MatHeight+l]1E-10) + { + for (j=0;j127.0f) + tmp=127.0f; + if (tmp<-127.0f) + tmp=-127.0f; + ccomp[j*MatHeight+l]=(char)floor(tmp+0.5); + } + coffset[l]+=cscale[l]*127.0f/254.0f; + cscale[l]/=254.0f; + } + else + { + cscale[l]=1.0f; + coffset[l]=0.0f; + for (j=0;j127.0f) + tmp=127.0f; + if (tmp<-127.0f) + tmp=-127.0f; + mat[k*MatHeight+l]=(char)floor(tmp+0.5); + } + } + else + { + cscale[l]=1.0f; + coffset[l]=0.0f; + for (j=0;jmaxdev) + maxdev=tmp; + avedev+=tmp; + numave++; + + if (bmin[k%3]>ans[k]) + bmin[k%3]=ans[k]; + if (bmax[k%3]version = MIP_VERSION; + + for(i=j=0;i<256;i++,j+=3) + { + mp->palette[i].r = palette[j]; + mp->palette[i].g = palette[j+1]; + mp->palette[i].b = palette[j+2]; + } + pos = (byte *)(mp + 1); + + mp->width[0] = w; + mp->height[0] = h; + mp->offsets[0] = sizeof(*mp); + memcpy(pos, buffer, w * h); + + *FinalSize = size; + return(mp); +} + +miptex32_t *CreateBook32(long *buffer, int w, int h, int *FinalSize) +{ + miptex32_t *mp; + byte *pos; + int size; + + size = sizeof(*mp) + (w * h * 4); + mp = (miptex32_t *)SafeMalloc(size, "CreateBook32"); + memset(mp, 0, size); + + mp->version = MIP32_VERSION; + + pos = (byte *)(mp + 1); + + mp->width[0] = w; + mp->height[0] = h; + mp->offsets[0] = sizeof(*mp); + memcpy(pos, buffer, w * h * 4); + + *FinalSize = size; + return(mp); +} + + +// Routines to chop a random sized image into gl texture friendly chunks + +typedef struct rect_s +{ + int x, y; + int w, h; + char name[4]; +} rect_t; + +int GetCoords(int x, int store[MAX_MD2SKINS]) +{ + int index, start, delta; + + index = 0; + start = 0; + delta = 256; + + store[index++] = start; + while(x) + { + if(x >= delta) + { + start += delta; + store[index++] = start; + x -= delta; + } + else + { + delta >>= 1; + } + } + return(index); +} + +int ChopImage(int w, int h, rect_t coords[MAX_MD2SKINS]) +{ + int xs[MAX_MD2SKINS], ys[MAX_MD2SKINS]; + int xcount, ycount, x, y, index; + + index = 0; + xcount = GetCoords(w, xs) - 1; + ycount = GetCoords(h, ys) - 1; + + for(y = 0; y < ycount; y++) + { + for(x = 0; x < xcount; x++, index++) + { + coords[index].x = xs[x]; + coords[index].y = ys[y]; + coords[index].w = xs[x + 1] - xs[x]; + coords[index].h = ys[y + 1] - ys[y]; + coords[index].name[0] = x + '0'; + coords[index].name[1] = y + '0'; + coords[index].name[2] = 0; + } + } + return(index); +} + +/* +=============== +Cmd_Pic +=============== +*/ + +void Cmd_Book() +{ + int xl,yl,xh,yh,w,h; + byte *dest, *source; + int flags, value, contents; + char lumpname[64]; + char filename[1024]; + unsigned long *destl, *sourcel; + int linedelta, x, y; + int size; + miptex_t *qtex; + miptex32_t *qtex32; + float scale_x, scale_y; + int numrects, i; + rect_t coords[MAX_MD2SKINS]; + bookframe_t bframes[MAX_MD2SKINS]; + bookframe_t *bf; + book_t book; + + GetScriptToken (false); + strcpy (lumpname, token); + + GetScriptToken (false); + xl = atoi (token); + GetScriptToken (false); + yl = atoi (token); + GetScriptToken (false); + w = atoi (token); + GetScriptToken (false); + h = atoi (token); + + total_x += w; + total_y += h; + total_textures++; + + if ( (w & 7) || (h & 7) ) + Error ("line %i: miptex sizes must be multiples of 8", scriptline); + + flags = 0; + contents = 0; + value = 0; + + scale_x = scale_y = 0.5; + + if (g_release) + return; + + if(TrueColorImage) + { + xh = xl + w; + yh = yl + h; + + if (xl >= longimagewidth || xh > longimagewidth || + yl >= longimageheight || yh > longimageheight) + { + Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,longimagewidth,longimageheight); + } + + sourcel = (unsigned long *) longimage + (yl * longimagewidth) + xl; + destl = (unsigned long *) longimage; + linedelta = (longimagewidth - w); + + for(y = yl; y < yh; y++) + { + for(x = xl; x < xh; x++) + { + *destl++ = *sourcel++; // RGBA + } + sourcel += linedelta; + } + + // Get rectangles to chop into + numrects = ChopImage(w, h, coords); + + bf = bframes; + for(i = 0; i < numrects; i++, bf++) + { + // Copy section of image to buffer + sourcel = (unsigned long *) longimage + (coords[i].y * w) + coords[i].x; + destl = bufferl; + linedelta = w - coords[i].w; + + for(y = 0; y < coords[i].h; y++) + { + for(x = 0; x < coords[i].w; x++) + { + *destl++ = *sourcel++; + } + sourcel += linedelta; + } + + qtex32 = CreateBook32(bufferl, coords[i].w, coords[i].h, &size); + + qtex32->flags = flags; + qtex32->contents = contents; + qtex32->value = value; + qtex32->scale_x = scale_x; + qtex32->scale_y = scale_y; + + sprintf (filename, "%sbook/%s/%s_%s.m32", gamedir, book_prefix, lumpname, coords[i].name); + sprintf (qtex32->name, "%s/%s_%s.m32", book_prefix, lumpname, coords[i].name); + + strcpy(bf->name, qtex32->name); + bf->x = coords[i].x; + bf->y = coords[i].y; + bf->w = coords[i].w; + bf->h = coords[i].h; + // + // write it out + // + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex32, size); + + free (qtex32); + } + } + else + { + xh = xl + w; + yh = yl + h; + + if (xl >= byteimagewidth || xh > byteimagewidth || + yl >= byteimageheight || yh > byteimageheight) + { + Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); + } + + // Copy image to top left + source = byteimage + yl*byteimagewidth + xl; + dest = byteimage; + linedelta = byteimagewidth - w; + + for(y = yl; y < yh; y++) + { + for(x = xl; x < xh; x++) + { + *dest++ = *source++; + } + source += linedelta; + } + + // Get rectangles to chop into + numrects = ChopImage(w, h, coords); + + bf = bframes; + for(i = 0; i < numrects; i++, bf++) + { + // Copy section of image to buffer + source = byteimage + (coords[i].y * w) + coords[i].x; + dest = buffer; + linedelta = w - coords[i].w; + + for(y = 0; y < coords[i].h; y++) + { + for(x = 0; x < coords[i].w; x++) + { + *dest++ = *source++; + } + source += linedelta; + } + + qtex = CreateBook8(buffer, coords[i].w, coords[i].h, lbmpalette, &size); + + qtex->flags = flags; + qtex->contents = contents; + qtex->value = value; + + sprintf (filename, "%sbook/%s/%s_%s.m8", gamedir, book_prefix, lumpname, coords[i].name); + sprintf (qtex->name, "%s/%s_%s.m8", book_prefix, lumpname, coords[i].name); + + strcpy(bf->name, qtex->name); + bf->x = coords[i].x; + bf->y = coords[i].y; + bf->w = coords[i].w; + bf->h = coords[i].h; + // + // write it out + // + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex, size); + + free (qtex); + } + } + // Set up descriptor + size = sizeof(bookframe_t) * numrects; + + book.bheader.ident = IDBOOKHEADER; + book.bheader.version = BOOK_VERSION; + book.bheader.num_segments = numrects; + book.bheader.total_w = w; + book.bheader.total_h = h; + memcpy(book.bframes, bframes, size); + + // Save out segment descriptor + sprintf (filename, "%sBook/%s/%s.bk", gamedir, book_prefix, lumpname); + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)&book, size + sizeof(bookheader_t)); +} + +/* +=============== +Cmd_picdir +=============== +*/ +void Cmd_Bookdir (void) +{ + char filename[1024]; + + GetScriptToken (false); + strcpy (book_prefix, token); + // create the directory if needed + sprintf (filename, "%sBook", gamedir); + Q_mkdir (filename); + sprintf (filename, "%sBook/%s", gamedir, book_prefix); + Q_mkdir (filename); +} + +// end diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.c new file mode 100644 index 00000000..146e03f3 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.c @@ -0,0 +1,793 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#include "mathlib.h" +#include "bspfile.h" +#include "scriplib.h" + +void GetLeafNums (void); + +//============================================================================= + +int nummodels; +dmodel_t dmodels[MAX_MAP_MODELS]; + +int visdatasize; +byte dvisdata[MAX_MAP_VISIBILITY]; +dvis_t *dvis = (dvis_t *)dvisdata; + +int lightdatasize; +byte dlightdata[MAX_MAP_LIGHTING]; + +int entdatasize; +char dentdata[MAX_MAP_ENTSTRING]; + +int numleafs; +dleaf_t dleafs[MAX_MAP_LEAFS]; + +int numplanes; +dplane_t dplanes[MAX_MAP_PLANES]; + +int numvertexes; +dvertex_t dvertexes[MAX_MAP_VERTS]; + +int numnodes; +dnode_t dnodes[MAX_MAP_NODES]; + +int numtexinfo; +texinfo_t texinfo[MAX_MAP_TEXINFO]; + +int numfaces; +dface_t dfaces[MAX_MAP_FACES]; + +int numedges; +dedge_t dedges[MAX_MAP_EDGES]; + +int numleaffaces; +unsigned short dleaffaces[MAX_MAP_LEAFFACES]; + +int numleafbrushes; +unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; + +int numsurfedges; +int dsurfedges[MAX_MAP_SURFEDGES]; + +int numbrushes; +dbrush_t dbrushes[MAX_MAP_BRUSHES]; + +int numbrushsides; +dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; + +int numareas; +darea_t dareas[MAX_MAP_AREAS]; + +int numareaportals; +dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; + +byte dpop[256]; + +/* +=============== +CompressVis + +=============== +*/ +int CompressVis (byte *vis, byte *dest) +{ + int j; + int rep; + int visrow; + byte *dest_p; + + dest_p = dest; +// visrow = (r_numvisleafs + 7)>>3; + visrow = (dvis->numclusters + 7)>>3; + + for (j=0 ; j>3; + row = (dvis->numclusters+7)>>3; + out = decompressed; + + do + { + if (*in) + { + *out++ = *in++; + continue; + } + + c = in[1]; + if (!c) + Error ("DecompressVis: 0 repeat"); + in += 2; + while (c) + { + *out++ = 0; + c--; + } + } while (out - decompressed < row); +} + +//============================================================================= + +/* +============= +SwapBSPFile + +Byte swaps all data in a bsp file. +============= +*/ +void SwapBSPFile (qboolean todisk) +{ + int i, j; + dmodel_t *d; + + +// models + for (i=0 ; ifirstface = LittleLong (d->firstface); + d->numfaces = LittleLong (d->numfaces); + d->headnode = LittleLong (d->headnode); + + for (j=0 ; j<3 ; j++) + { + d->mins[j] = LittleFloat(d->mins[j]); + d->maxs[j] = LittleFloat(d->maxs[j]); + d->origin[j] = LittleFloat(d->origin[j]); + } + } + +// +// vertexes +// + for (i=0 ; inumclusters; + else + j = LittleLong(dvis->numclusters); + dvis->numclusters = LittleLong (dvis->numclusters); + for (i=0 ; ibitofs[i][0] = LittleLong (dvis->bitofs[i][0]); + dvis->bitofs[i][1] = LittleLong (dvis->bitofs[i][1]); + } +} + + +dheader_t *header; + +int CopyLump (int lump, void *dest, int size) +{ + int length, ofs; + + length = header->lumps[lump].filelen; + ofs = header->lumps[lump].fileofs; + + if (length % size) + Error ("LoadBSPFile: odd lump size"); + + memcpy (dest, (byte *)header + ofs, length); + + return length / size; +} + +/* +============= +LoadBSPFile +============= +*/ +void LoadBSPFile (char *filename) +{ + int i; + +// +// load the file header +// + LoadFile (filename, (void **)&header); + +// swap the header + for (i=0 ; i< sizeof(dheader_t)/4 ; i++) + ((int *)header)[i] = LittleLong ( ((int *)header)[i]); + + if (header->ident != IDBSPHEADER) + Error ("%s is not a IBSP file", filename); + if (header->version != BSPVERSION) + Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); + + nummodels = CopyLump (LUMP_MODELS, dmodels, sizeof(dmodel_t)); + numvertexes = CopyLump (LUMP_VERTEXES, dvertexes, sizeof(dvertex_t)); + numplanes = CopyLump (LUMP_PLANES, dplanes, sizeof(dplane_t)); + numleafs = CopyLump (LUMP_LEAFS, dleafs, sizeof(dleaf_t)); + numnodes = CopyLump (LUMP_NODES, dnodes, sizeof(dnode_t)); + numtexinfo = CopyLump (LUMP_TEXINFO, texinfo, sizeof(texinfo_t)); + numfaces = CopyLump (LUMP_FACES, dfaces, sizeof(dface_t)); + numleaffaces = CopyLump (LUMP_LEAFFACES, dleaffaces, sizeof(dleaffaces[0])); + numleafbrushes = CopyLump (LUMP_LEAFBRUSHES, dleafbrushes, sizeof(dleafbrushes[0])); + numsurfedges = CopyLump (LUMP_SURFEDGES, dsurfedges, sizeof(dsurfedges[0])); + numedges = CopyLump (LUMP_EDGES, dedges, sizeof(dedge_t)); + numbrushes = CopyLump (LUMP_BRUSHES, dbrushes, sizeof(dbrush_t)); + numbrushsides = CopyLump (LUMP_BRUSHSIDES, dbrushsides, sizeof(dbrushside_t)); + numareas = CopyLump (LUMP_AREAS, dareas, sizeof(darea_t)); + numareaportals = CopyLump (LUMP_AREAPORTALS, dareaportals, sizeof(dareaportal_t)); + + visdatasize = CopyLump (LUMP_VISIBILITY, dvisdata, 1); + lightdatasize = CopyLump (LUMP_LIGHTING, dlightdata, 1); + entdatasize = CopyLump (LUMP_ENTITIES, dentdata, 1); + + CopyLump (LUMP_POP, dpop, 1); + + free (header); // everything has been copied out + +// +// swap everything +// + SwapBSPFile (false); +} + + +/* +============= +LoadBSPFileTexinfo + +Only loads the texinfo lump, so qdata can scan for textures +============= +*/ +void LoadBSPFileTexinfo (char *filename) +{ + int i; + FILE *f; + int length, ofs; + + header = malloc(sizeof(dheader_t)); + + f = fopen (filename, "rb"); + fread (header, sizeof(dheader_t), 1, f); + +// swap the header + for (i=0 ; i< sizeof(dheader_t)/4 ; i++) + ((int *)header)[i] = LittleLong ( ((int *)header)[i]); + + if (header->ident != IDBSPHEADER) + Error ("%s is not a IBSP file", filename); + if (header->version != BSPVERSION) + Error ("%s is version %i, not %i", filename, header->version, BSPVERSION); + + + length = header->lumps[LUMP_TEXINFO].filelen; + ofs = header->lumps[LUMP_TEXINFO].fileofs; + + fseek (f, ofs, SEEK_SET); + fread (texinfo, length, 1, f); + fclose (f); + + numtexinfo = length / sizeof(texinfo_t); + + free (header); // everything has been copied out + + SwapBSPFile (false); +} + + +//============================================================================ + +FILE *wadfile; +dheader_t outheader; + +void AddLump (int lumpnum, void *data, int len) +{ + lump_t *lump; + + lump = &header->lumps[lumpnum]; + + lump->fileofs = LittleLong( ftell(wadfile) ); + lump->filelen = LittleLong(len); + SafeWrite (wadfile, data, (len+3)&~3); +} + +/* +============= +WriteBSPFile + +Swaps the bsp file in place, so it should not be referenced again +============= +*/ +void WriteBSPFile (char *filename) +{ + header = &outheader; + memset (header, 0, sizeof(dheader_t)); + + SwapBSPFile (true); + + header->ident = LittleLong (IDBSPHEADER); + header->version = LittleLong (BSPVERSION); + + wadfile = SafeOpenWrite (filename); + SafeWrite (wadfile, header, sizeof(dheader_t)); // overwritten later + + AddLump (LUMP_PLANES, dplanes, numplanes*sizeof(dplane_t)); + AddLump (LUMP_LEAFS, dleafs, numleafs*sizeof(dleaf_t)); + AddLump (LUMP_VERTEXES, dvertexes, numvertexes*sizeof(dvertex_t)); + AddLump (LUMP_NODES, dnodes, numnodes*sizeof(dnode_t)); + AddLump (LUMP_TEXINFO, texinfo, numtexinfo*sizeof(texinfo_t)); + AddLump (LUMP_FACES, dfaces, numfaces*sizeof(dface_t)); + AddLump (LUMP_BRUSHES, dbrushes, numbrushes*sizeof(dbrush_t)); + AddLump (LUMP_BRUSHSIDES, dbrushsides, numbrushsides*sizeof(dbrushside_t)); + AddLump (LUMP_LEAFFACES, dleaffaces, numleaffaces*sizeof(dleaffaces[0])); + AddLump (LUMP_LEAFBRUSHES, dleafbrushes, numleafbrushes*sizeof(dleafbrushes[0])); + AddLump (LUMP_SURFEDGES, dsurfedges, numsurfedges*sizeof(dsurfedges[0])); + AddLump (LUMP_EDGES, dedges, numedges*sizeof(dedge_t)); + AddLump (LUMP_MODELS, dmodels, nummodels*sizeof(dmodel_t)); + AddLump (LUMP_AREAS, dareas, numareas*sizeof(darea_t)); + AddLump (LUMP_AREAPORTALS, dareaportals, numareaportals*sizeof(dareaportal_t)); + + AddLump (LUMP_LIGHTING, dlightdata, lightdatasize); + AddLump (LUMP_VISIBILITY, dvisdata, visdatasize); + AddLump (LUMP_ENTITIES, dentdata, entdatasize); + AddLump (LUMP_POP, dpop, sizeof(dpop)); + + fseek (wadfile, 0, SEEK_SET); + SafeWrite (wadfile, header, sizeof(dheader_t)); + fclose (wadfile); +} + +//============================================================================ + +/* +============= +PrintBSPFileSizes + +Dumps info about current file +============= +*/ +void PrintBSPFileSizes (void) +{ + if (!num_entities) + ParseEntities (); + + printf ("%5i models %7i\n" + ,nummodels, (int)(nummodels*sizeof(dmodel_t))); + printf ("%5i brushes %7i\n" + ,numbrushes, (int)(numbrushes*sizeof(dbrush_t))); + printf ("%5i brushsides %7i\n" + ,numbrushsides, (int)(numbrushsides*sizeof(dbrushside_t))); + printf ("%5i planes %7i\n" + ,numplanes, (int)(numplanes*sizeof(dplane_t))); + printf ("%5i texinfo %7i\n" + ,numtexinfo, (int)(numtexinfo*sizeof(texinfo_t))); + printf ("%5i entdata %7i\n", num_entities, entdatasize); + + printf ("\n"); + + printf ("%5i vertexes %7i\n" + ,numvertexes, (int)(numvertexes*sizeof(dvertex_t))); + printf ("%5i nodes %7i\n" + ,numnodes, (int)(numnodes*sizeof(dnode_t))); + printf ("%5i faces %7i\n" + ,numfaces, (int)(numfaces*sizeof(dface_t))); + printf ("%5i leafs %7i\n" + ,numleafs, (int)(numleafs*sizeof(dleaf_t))); + printf ("%5i leaffaces %7i\n" + ,numleaffaces, (int)(numleaffaces*sizeof(dleaffaces[0]))); + printf ("%5i leafbrushes %7i\n" + ,numleafbrushes, (int)(numleafbrushes*sizeof(dleafbrushes[0]))); + printf ("%5i surfedges %7i\n" + ,numsurfedges, (int)(numsurfedges*sizeof(dsurfedges[0]))); + printf ("%5i edges %7i\n" + ,numedges, (int)(numedges*sizeof(dedge_t))); + printf (" lightdata %7i\n", lightdatasize); + printf (" visdata %7i\n", visdatasize); +} + + +//============================================ + +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 = 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); + GetScriptToken (false); + if (strlen(token) >= MAX_VALUE-1) + Error ("ParseEpar: token too long"); + e->value = copystring(token); + + // strip trailing spaces + StripTrailing (e->key); + StripTrailing (e->value); + + return e; +} + + +/* +================ +ParseEntity +================ +*/ +qboolean ParseEntity (void) +{ + epair_t *e; + entity_t *mapent; + + if (!GetScriptToken (true)) + return false; + + 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 (!GetScriptToken (true)) + Error ("ParseEntity: EOF without closing brace"); + if (!strcmp (token, "}") ) + break; + e = ParseEpair (); + e->next = mapent->epairs; + mapent->epairs = e; + } while (1); + + return true; +} + +/* +================ +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 +================ +*/ +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 ; inext) + { + 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 (entity_t *ent) +{ + epair_t *ep; + + printf ("------- entity %p -------\n", ent); + for (ep=ent->epairs ; ep ; ep=ep->next) + { + printf ("%s = %s\n", ep->key, ep->value); + } + +} + +void SetKeyValue (entity_t *ent, char *key, 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 = malloc (sizeof(*ep)); + if (!ep) + Error("SetKeyValue MALLOC failed! Could not allocate %s bytes.", sizeof(*ep)); + ep->next = ent->epairs; + ent->epairs = ep; + ep->key = copystring(key); + ep->value = copystring(value); +} + +char *ValueForKey (entity_t *ent, 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 (entity_t *ent, char *key) +{ + char *k; + + k = ValueForKey (ent, key); + return atof(k); +} + +void GetVectorForKey (entity_t *ent, char *key, vec3_t vec) +{ + 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/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.h new file mode 100644 index 00000000..1597a3df --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/bspfile.h @@ -0,0 +1,133 @@ +/* +Copyright (C) 1999-2006 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 _QBSP3_H +#define _QBSP3_H + + +#include "qfiles.h" + + +extern int nummodels; +extern dmodel_t dmodels[MAX_MAP_MODELS]; + +extern int visdatasize; +extern byte dvisdata[MAX_MAP_VISIBILITY]; +extern dvis_t *dvis; + +extern int lightdatasize; +extern byte dlightdata[MAX_MAP_LIGHTING]; + +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 numvertexes; +extern dvertex_t dvertexes[MAX_MAP_VERTS]; + +extern int numnodes; +extern dnode_t dnodes[MAX_MAP_NODES]; + +extern int numtexinfo; +extern texinfo_t texinfo[MAX_MAP_TEXINFO]; + +extern int numfaces; +extern dface_t dfaces[MAX_MAP_FACES]; + +extern int numedges; +extern dedge_t dedges[MAX_MAP_EDGES]; + +extern int numleaffaces; +extern unsigned short dleaffaces[MAX_MAP_LEAFFACES]; + +extern int numleafbrushes; +extern unsigned short dleafbrushes[MAX_MAP_LEAFBRUSHES]; + +extern int numsurfedges; +extern int dsurfedges[MAX_MAP_SURFEDGES]; + +extern int numareas; +extern darea_t dareas[MAX_MAP_AREAS]; + +extern int numareaportals; +extern dareaportal_t dareaportals[MAX_MAP_AREAPORTALS]; + +extern int numbrushes; +extern dbrush_t dbrushes[MAX_MAP_BRUSHES]; + +extern int numbrushsides; +extern dbrushside_t dbrushsides[MAX_MAP_BRUSHSIDES]; + +extern byte dpop[256]; + +void DecompressVis (byte *in, byte *decompressed); +int CompressVis (byte *vis, byte *dest); + +void LoadBSPFile (char *filename); +void LoadBSPFileTexinfo (char *filename); // just for qdata +void WriteBSPFile (char *filename); +void PrintBSPFileSizes (void); + +//=============== + + +typedef struct epair_s +{ + struct epair_s *next; + char *key; + char *value; +} epair_t; + +typedef struct +{ + vec3_t origin; + int firstbrush; + int numbrushes; + epair_t *epairs; + +// only valid for func_areaportals + int areaportalnum; + int portalareas[2]; +} entity_t; + +extern int num_entities; +extern entity_t entities[MAX_MAP_ENTITIES]; + +void ParseEntities (void); +void UnparseEntities (void); + +void SetKeyValue (entity_t *ent, char *key, char *value); +char *ValueForKey (entity_t *ent, char *key); +// will return "" if not present + +vec_t FloatForKey (entity_t *ent, char *key); +void GetVectorForKey (entity_t *ent, char *key, vec3_t vec); + +epair_t *ParseEpair (void); + +void PrintEntity (entity_t *ent); + +#endif //_QBSP3_H diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.c new file mode 100644 index 00000000..f3115d29 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.c @@ -0,0 +1,1238 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// Nurail: Swiped from quake3/common + +#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 "h" +#define PATHSEPERATOR '/' + +extern qboolean verbose; + +qboolean g_dokeypress = false; + +qboolean g_nomkdir = false; + + +#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 + +void *SafeMalloc(size_t n, char *desc) +{ + void *p; + + if((p = malloc(n)) == NULL) + { + Error("Failed to allocate %d bytes for '%s'.\n", n, desc); + } + memset(p, 0, n); + return p; +} + +#if defined (__linux__) || defined (__APPLE__) +void strlwr(char *conv_str) +{ + int i; + + for(i=0; i32); + + 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); +} + +int Q_strcasecmp (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 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); +} +/* +// all output ends up through here +void FPrintf (int flag, char *buf) +{ + printf(buf); + +} + +void Sys_FPrintf (int flag, const char *format, ...) +{ + char out_buffer[4096]; + va_list argptr; + + if ((flag == SYS_VRB) && (verbose == false)) + 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 ); + + exit (1); +} + +*/ + +/* +============================================================================ + + 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/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.h new file mode 100644 index 00000000..a6cb14e9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/cmdlib.h @@ -0,0 +1,181 @@ +/* +Copyright (C) 1999-2006 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__ + +#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 + +#ifndef __BYTEBOOL__ + #define __BYTEBOOL__ + //typedef enum {false, true} qboolean; + //typedef unsigned char byte; + #include "q_typedef.h" +#endif + +#ifdef PATH_MAX +#define MAX_OS_PATH PATH_MAX +#else +#define MAX_OS_PATH 1024 +#endif +#define MEM_BLOCKSIZE 4096 +/* +extern qboolean verbose; +#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 +*/ +// 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 ); +int Q_strcasecmp( 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 ); + +int CheckParm( const char *check ); + +void *SafeMalloc(size_t n, char *desc); +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); +/* +void Sys_Printf (const char *text, ...); +void Sys_FPrintf (int flag, const char *text, ...); +void Error( const char *error, ... ); +*/ +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]; + +extern qboolean g_dokeypress; + +// sleep for the given amount of milliseconds +void Sys_Sleep(int n); + +// for compression routines +typedef struct +{ + byte *data; + int count; +} cblock_t; + + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/her2_threads.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/her2_threads.h new file mode 100644 index 00000000..339b0c86 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/her2_threads.h @@ -0,0 +1,35 @@ +/* +Copyright (C) 1999-2006 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 _THREADS_H + +#define _THREADS_H + + +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); + +#endif //_THREADS_H diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/inout.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/inout.c new file mode 100644 index 00000000..3cf66e7f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/inout.c @@ -0,0 +1,367 @@ +/* +Copyright (C) 1999-2006 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" + +#ifdef WIN32 +HWND hwndOut = NULL; +qboolean lookedForServer = false; +UINT wm_BroadcastCommand = -1; +#endif + +socket_t *brdcst_socket; +netmessage_t msg; + +qboolean verbose = false; + +// 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 = false; + 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 = true; + } + node = xmlNewNode (NULL, "message"); + xmlNodeSetContent (node, buf); + 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 == false)) + 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/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/inout.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/inout.h new file mode 100644 index 00000000..75ef55ee --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/inout.h @@ -0,0 +1,63 @@ +/* +Copyright (C) 1999-2006 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" +#include "mathlib.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, ...); +void Error( const char *error, ...); + +#ifdef _DEBUG +#define DBG_XML 1 +#endif + +#ifdef DBG_XML +void DumpXML(); +#endif + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.c new file mode 100644 index 00000000..853ff1ca --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.c @@ -0,0 +1,476 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#include "mathlib.h" +#include "trilib.h" +#include "l3dslib.h" +#include "token.h" +#include "fmodel.h" +#include "bspfile.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 + +typedef struct { + int v[4]; +} tri; + +float fverts[MAXVERTS][3]; +tri tris[MAXTRIANGLES]; + +int bytesread, level, numtris, totaltris; +int vertsfound, trisfound; + +triangle_t *ptri; + + + +void DefaultNodesList(mesh_node_t **nodesList, int *num_mesh_nodes, int *numtriangles) +{ + int pos, bit, i; + + if (nodesList) + { + *num_mesh_nodes = 1; + memset(&(*nodesList)[0], 0, sizeof(mesh_node_t)); + strcpy((*nodesList)[0].name, "default"); + + // set all of the tris to be used for the top node + for(i = 0; i < (*numtriangles); i++) + { + pos = (i) >> 3; + bit = 1 << ((i) & 7 ); + + (*nodesList)[0].tris[pos] |= bit; + } + } +} + + +// 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 MAXVERTS) + Error ("Error: Too many vertices"); + + for (i=0 ; i MAXTRIANGLES) + Error ("Error: Too many triangles"); + + for (i=0 ; i 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, mesh_node_t **nodesList, int *num_mesh_nodes) +{ + FILE *input; + short int tshort; + + if (nodesList) + { + *num_mesh_nodes = 0; + *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); + } + + 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 = 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); + + DefaultNodesList(nodesList,num_mesh_nodes,numtriangles); +} + +//========================================================================== +// +// LoadASC +// +//========================================================================== + +void LoadASC(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) +{ + int i, j; + int vertexCount; + struct + { + float v[3]; + } *vList; + int triCount; + triangle_t *tList; + float x, y, z; +// float x2, y2, z2; +// float rx, ry, rz; + qboolean goodObject; + + if (nodesList) + { + *num_mesh_nodes = 0; + *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); + } + + TK_OpenSource(fileName); + + goodObject = false; + while(goodObject == false) + { + TK_Beyond(TK_C_NAMED); + TK_Beyond(TK_OBJECT); + TK_Beyond(TK_C_TRI); + TK_Beyond(TK_MESH); + TK_BeyondRequire(TK_C_VERTICES, TK_COLON); + TK_FetchRequire(TK_INTNUMBER); + vertexCount = tk_IntNumber; + if(vertexCount > 0) + { + goodObject = true; + } + } + TK_BeyondRequire(TK_C_FACES, TK_COLON); + TK_FetchRequire(TK_INTNUMBER); + triCount = tk_IntNumber; + if(triCount >= MAXTRIANGLES) + { + Error("Too many triangles in file %s\n", fileName); + } + *triangleCount = triCount; + tList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); + *triList = tList; + + memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); + TK_BeyondRequire(TK_C_VERTEX, TK_LIST); + +/* rx = ((rotation[0]+90.0)/360.0)*2.0*M_PI; + //rx = (rotation[0]/360.0)*2.0*M_PI; + ry = (rotation[1]/360.0)*2.0*M_PI; + rz = (rotation[2]/360.0)*2.0*M_PI; +*/ + vList = (void *) SafeMalloc(vertexCount*sizeof vList[0], "Vertex list"); + for(i = 0; i < vertexCount; i++) + { + TK_BeyondRequire(TK_C_VERTEX, TK_INTNUMBER); + if(tk_IntNumber != i) + { + Error("File '%s', line %d:\nVertex index mismatch.\n", + tk_SourceName, tk_Line); + } + TK_FetchRequireFetch(TK_COLON); + + TK_BeyondRequire(TK_COLON, TK_FLOATNUMBER); + x = tk_FloatNumber; + TK_BeyondRequire(TK_COLON, TK_FLOATNUMBER); + y = tk_FloatNumber; + TK_BeyondRequire(TK_COLON, TK_FLOATNUMBER); + z = tk_FloatNumber; + +/* x2 = x*cos(rz)+y*sin(rz); + y2 = -x*sin(rz)+y*cos(rz); + x = x2; + y = y2; + y2 = y*cos(rx)+z*sin(rx); + z2 = -y*sin(rx)+z*cos(rx); + y = y2; + z = z2; + x2 = x*cos(ry)-z*sin(ry); + z2 = x*sin(ry)+z*cos(ry); + x = x2; + z = z2; +*/ + vList[i].v[0] = x; + vList[i].v[1] = y; + vList[i].v[2] = z; + } + TK_BeyondRequire(TK_C_FACE, TK_LIST); + for(i = 0; i < triCount; i++) + { + TK_BeyondRequire(TK_C_FACE, TK_INTNUMBER); + if(tk_IntNumber != i) + { + Error("File '%s', line %d:\nTriangle index mismatch.\n", + tk_SourceName, tk_Line); + } + for(j = 0; j < 3; j++) + { + TK_BeyondRequire(TK_IDENTIFIER, TK_COLON); + TK_FetchRequire(TK_INTNUMBER); + if(tk_IntNumber >= vertexCount) + { + Error("File '%s', line %d:\nVertex number" + " > vertexCount: %d\n", tk_SourceName, tk_Line, + tk_IntNumber); + } + tList[i].verts[2-j][0] = vList[tk_IntNumber].v[0]; + tList[i].verts[2-j][1] = vList[tk_IntNumber].v[1]; + tList[i].verts[2-j][2] = vList[tk_IntNumber].v[2]; +#ifdef _QDATA + tList[i].indicies[2-j] = tk_IntNumber; +#endif + } + +/* printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" + " v2: %f, %f, %f\n", i, + tList[i].verts[0][0], + tList[i].verts[0][1], + tList[i].verts[0][2], + tList[i].verts[1][0], + tList[i].verts[1][1], + tList[i].verts[1][2], + tList[i].verts[2][0], + tList[i].verts[2][1], + tList[i].verts[2][2]); +*/ + } + + DefaultNodesList(nodesList,num_mesh_nodes,triangleCount); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.h new file mode 100644 index 00000000..b20391c6 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/l3dslib.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 1999-2006 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 DefaultNodesList(mesh_node_t **nodesList, int *num_mesh_nodes, int *numtriangles); + +void Load3DSTriangleList (char *filename, triangle_t **pptri, int *numtriangles, mesh_node_t **ppmnodes, int *num_mesh_nodes); +void LoadASC(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **ppmnodes, int *num_mesh_nodes); diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.c new file mode 100644 index 00000000..5ea39bd9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.c @@ -0,0 +1,1052 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// lbmlib.c + +#include "cmdlib.h" +#include "inout.h" +#include "lbmlib.h" + +// Ups the palette values so no pixels except 0 appear transparent +// Need a value of 8 to cater for 16bit renderers + +typedef struct +{ + byte r; + byte g; + byte b; +} paletteRGB_t; + + +void CorrectPalette(byte *pal) +{ + paletteRGB_t *p; + + p = (paletteRGB_t *)pal; + // Color 0 always transparent + p->r = 0; + p->g = 0; + p->b = 0; +} + +/* +============================================================================ + + 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 (countbpwidth) + Error ("Decompression exceeded width!\n"); + + + return source; +} + + +/* +================= +LoadLBM +================= +*/ +void LoadLBM (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 = malloc (768); + memset (cmapbuffer, 0, 768); + memcpy (cmapbuffer, LBM_P, chunklength); + CorrectPalette(cmapbuffer); + break; + + case BODYID: + body_p = LBM_P; + + pic_p = picbuffer = malloc (bmhd.w*bmhd.h); + if (formtype == PBMID) + { + // + // unpack PBM + // + for (y=0 ; ydata; + + 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 = malloc(768); + memcpy (*palette, (byte *)pcx + len - 768, 768); + CorrectPalette(*palette); + } + + if (width) + *width = pcx->xmax+1; + if (height) + *height = pcx->ymax+1; + + if (!pic) + return; + + out = malloc ( (pcx->ymax+1) * (pcx->xmax+1) ); + if (!out) + Error ("Skin_Cache: couldn't allocate"); + + *pic = out; + + pix = out; + + for (y=0 ; y<=pcx->ymax ; y++, pix += pcx->xmax+1) + { + for (x=0 ; x<=pcx->xmax ; ) + { + dataByte = *raw++; + + if((dataByte & 0xC0) == 0xC0) + { + runLength = dataByte & 0x3F; + dataByte = *raw++; + } + else + runLength = 1; + + while(runLength-- > 0) + pix[x++] = dataByte; + } + + } + + if ( raw - (byte *)pcx > len) + Error ("PCX file %s was malformed", filename); + + free (pcx); +} + +/* +============== +WritePCXfile +============== +*/ + +void StuffPackedByte(int curRepCount, byte curByte, byte** packPtr) +{ + byte* pack; + + pack = *packPtr; + + while(curRepCount > 0) + { + if (curRepCount == 1) + { + if ((curByte & 0xc0) != 0xc0) + { + *pack++ = curByte; + } + else + { + *pack++ = 0xc1; + *pack++ = curByte; + } + break; + } + if (curRepCount < 0x0040) + { + *pack++ = (0x00c0 | curRepCount); + curRepCount = 0; + } + else + { + *pack++ = 0xff; + curRepCount -= 0x003f; + } + *pack++ = curByte; + } + *packPtr = pack; +} + +void WritePCXfile (char *filename, byte *data, + int width, int height, byte *palette) +{ + int i, j, length; + pcx_t *pcx; + byte *pack; + byte curByte; + int curRepCount; + + pcx = malloc (width*height*2+1000); + memset (pcx, 0, sizeof(*pcx)); + + pcx->manufacturer = 0x0a; // PCX id + pcx->version = 5; // 256 color + pcx->encoding = 1; // RLE + 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= rows) + goto breakOut; + pixbuf += rowOffset; + rowBuf = pixbuf; + } + } + } + else + { // non run-length packet + for(j = 0; j < packetSize; j++) + { + switch (targa_header.pixel_size) + { + case 24: + blue = getc(fin); + green = getc(fin); + red = getc(fin); + rowBuf[0] = red; + rowBuf[1] = green; + rowBuf[2] = blue; + rowBuf[3] = 255; + rowBuf += pixDirection; + break; + case 32: + blue = getc(fin); + green = getc(fin); + red = getc(fin); + alphabyte = getc(fin); + rowBuf[0] = red; + rowBuf[1] = green; + rowBuf[2] = blue; + rowBuf[3] = alphabyte; + rowBuf += pixDirection; + break; + } + column++; + if (column == columns) + { // pixel packet run spans across rows + column = 0; + row++; + if (row >= rows) + goto breakOut; + pixbuf += rowOffset; + rowBuf = pixbuf; + } + } + } + } + breakOut:; + pixbuf += rowOffset; + } + } + fclose(fin); +} + +void MergeAlpha(byte *pix, byte *alpha, byte *pal, byte **out, int width, int height) +{ + int size, i; + byte *data, *src, *srca; + + size = width * height; + data = malloc(size * 4); + if(!data) + Error("Could not allocate memory for true color image"); + + *out = data; + src = pix; + srca = alpha; + + for(i = 0; i < size; i++, src++, srca++) + { + *data++ = pal[*src * 3 + 0]; // r + *data++ = pal[*src * 3 + 1]; // g + *data++ = pal[*src * 3 + 2]; // b + *data++ = *srca; // a + } + free(pix); + free(alpha); + free(pal); +} + +/* +============== +LoadAnyImage + +Return Value: + false: paletted texture + true: true color RGBA image (no palette) +============== +*/ +qboolean LoadAnyImage (char *name, byte **pixels, byte **palette, int *width, int *height) +{ + char ext[128]; + int len; + int alpha_width, alpha_height; + char alpha_name[128]; + byte *alpha_pixels; + + ExtractFileExtension (name, ext); + + if(palette) + { + *palette = NULL; + } + + if (!Q_strcasecmp (ext, "lbm")) + { + LoadLBM (name, pixels, palette); + if (width) + *width = bmhd.w; + if (height) + *height = bmhd.h; + return false; + } + else if (!Q_strcasecmp (ext, "pcx")) + { + len = strlen(name); + strcpy(alpha_name, name); + strcpy(&alpha_name[len - 4], "_a.pcx"); // Alpha map name (may not exist) + + if(FileExists(alpha_name)) + { + LoadPCX (name, pixels, palette, width, height); // Load in image + LoadPCX (alpha_name, &alpha_pixels, NULL, &alpha_width, &alpha_height); // Load in alpha map + if((*width != alpha_width) || (*height != alpha_height)) + { + Error("Alpha image dimensions not equal to graphic image dimensions"); + } + MergeAlpha(*pixels, alpha_pixels, *palette, pixels, *width, *height); + *palette = NULL;//Merge Frees pal + return true; + } + else + { + LoadPCX (name, pixels, palette, width, height); // Load in image + return false; + } + } + else if (!Q_strcasecmp (ext, "tga")) + { + LoadTGA(name, pixels, width, height); + if (palette) + { + *palette = NULL; + } + + return true; + } + else + Error ("%s doesn't have a known image extension", name); + + return false; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.h new file mode 100644 index 00000000..5a5f46f2 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/lbmlib.h @@ -0,0 +1,41 @@ +/* +Copyright (C) 1999-2006 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 (char *filename, byte **picture, byte **palette); +void WriteLBMfile (char *filename, byte *data, int width, int height + , byte *palette); +void LoadPCX (char *filename, byte **picture, byte **palette, int *width, int *height); +void WritePCXfile (char *filename, byte *data, int width, int height + , byte *palette); + +// loads / saves either lbm or pcx, depending on extension +void Load256Image (char *name, byte **pixels, byte **palette, + int *width, int *height); +void Save256Image (char *name, byte *pixels, byte *palette, + int width, int height); + + +void LoadTGA (char *filename, byte **pixels, int *width, int *height); + +qboolean LoadAnyImage (char *name, byte **pixels, byte **palette, int *width, int *height); diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.c new file mode 100644 index 00000000..aa53c44a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.c @@ -0,0 +1,176 @@ +/* +Copyright (C) 1999-2006 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 "cmdlib.h" +#include "mathlib.h" + +vec3_t vec3_origin = {0,0,0}; + + +double VectorLength(vec3_t v) +{ + int i; + double length; + + length = 0; + for (i=0 ; i< 3 ; i++) + length += v[i]*v[i]; + length = sqrt (length); // FIXME + + return length; +} + +qboolean VectorCompare (vec3_t v1, vec3_t v2) +{ + int i; + + for (i=0 ; i<3 ; i++) + if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON) + return false; + + return true; +} + +vec_t Q_rint (vec_t in) +{ + return floor (in + 0.5); +} + +void VectorMA (vec3_t va, double scale, 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]; +} + +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; +} + +#pragma optimize("g", off) // went back to turning optimization off, + // the bug_fix thing stopped working + +vec_t VectorNormalize (vec3_t in, vec3_t out) +{ + vec_t length, ilength; + + length = sqrt (in[0]*in[0] + in[1]*in[1] + in[2]*in[2]); + if (length == 0) + { + VectorClear (out); + return 0; + } + + ilength = 1.0/length; + out[0] = in[0]*ilength; + out[1] = in[1]*ilength; + out[2] = in[2]*ilength; + + return length; +} + +vec_t ColorNormalize (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) + return 0; + + scale = 1.0 / max; + + VectorScale (in, scale, out); + + return max; +} + +#pragma optimize("", on) + +void VectorInverse (vec3_t v) +{ + v[0] = -v[0]; + v[1] = -v[1]; + v[2] = -v[2]; +} + +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; + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.h new file mode 100644 index 00000000..76dfda32 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/mathlib.h @@ -0,0 +1,76 @@ +/* +Copyright (C) 1999-2006 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 DOUBLEVEC_T +typedef double vec_t; +#else +typedef float vec_t; +#endif +typedef vec_t vec3_t[3]; +*/ +#define SIDE_FRONT 0 +#define SIDE_ON 2 +#define SIDE_BACK 1 +#define SIDE_CROSS -2 + +#define Q_PI 3.14159265358979323846 + +extern vec3_t vec3_origin; + +#define EQUAL_EPSILON 0.001 + +qboolean VectorCompare (vec3_t v1, vec3_t v2); + +#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 VectorCopy(a,b) {b[0]=a[0];b[1]=a[1];b[2]=a[2];} +#define VectorScale(a,b,c) {c[0]=b*a[0];c[1]=b*a[1];c[2]=b*a[2];} +#define VectorClear(x) {x[0] = x[1] = x[2] = 0;} +#define VectorNegate(x) {x[0]=-x[0];x[1]=-x[1];x[2]=-x[2];} + +vec_t Q_rint (vec_t in); +vec_t _DotProduct (vec3_t v1, vec3_t v2); +void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out); +void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out); +void _VectorCopy (vec3_t in, vec3_t out); +void _VectorScale (vec3_t v, vec_t scale, vec3_t out); + +double VectorLength(vec3_t v); + +void VectorMA (vec3_t va, double scale, vec3_t vb, vec3_t vc); + +void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross); +vec_t VectorNormalize (vec3_t in, vec3_t out); +vec_t ColorNormalize (vec3_t in, vec3_t out); +void VectorInverse (vec3_t v); + +void ClearBounds (vec3_t mins, vec3_t maxs); +void AddPointToBounds (vec3_t v, vec3_t mins, vec3_t maxs); + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/md4.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/md4.c new file mode 100644 index 00000000..7c2c9be4 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/md4.c @@ -0,0 +1,227 @@ +/* + mdfour.c + + An implementation of MD4 designed for use in the samba SMB + authentication protocol + + Copyright (C) 1997-1998 Andrew Tridgell + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA + + $Id: mdfour.c 7689 2007-11-12 14:28:40Z divverent $ +*/ + +#include /* XoXus: needed for memset call */ +#include "md4.h" + +/* NOTE: This code makes no attempt to be fast! + + It assumes that a int is at least 32 bits long +*/ + +static struct mdfour *m; + +#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)) +#ifdef LARGE_INT32 +#define lshift(x,s) ((((x)<<(s))&0xFFFFFFFF) | (((x)>>(32-(s)))&0xFFFFFFFF)) +#else +#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) +#endif + +#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) +#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) +#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) + +/* this applies md4 to 64 byte chunks */ +static void mdfour64(uint32 *M) +{ + int j; + uint32 AA, BB, CC, DD; + uint32 X[16]; + uint32 A,B,C,D; + + for (j=0;j<16;j++) + X[j] = M[j]; + + A = m->A; B = m->B; C = m->C; D = m->D; + AA = A; BB = B; CC = C; DD = D; + + ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); + ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); + ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); + ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); + ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); + ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); + ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); + ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); + + ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); + ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); + ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); + ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); + ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); + ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); + ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); + ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); + + ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); + ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); + ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); + ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); + ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); + ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); + ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); + ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); + + A += AA; B += BB; C += CC; D += DD; + +#ifdef LARGE_INT32 + A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; + C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; +#endif + + for (j=0;j<16;j++) + X[j] = 0; + + m->A = A; m->B = B; m->C = C; m->D = D; +} + +static void copy64(uint32 *M, unsigned char *in) +{ + int i; + + for (i=0;i<16;i++) + M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | + (in[i*4+1]<<8) | (in[i*4+0]<<0); +} + +static void copy4(unsigned char *out,uint32 x) +{ + out[0] = x&0xFF; + out[1] = (x>>8)&0xFF; + out[2] = (x>>16)&0xFF; + out[3] = (x>>24)&0xFF; +} + +void mdfour_begin(struct mdfour *md) +{ + md->A = 0x67452301; + md->B = 0xefcdab89; + md->C = 0x98badcfe; + md->D = 0x10325476; + md->totalN = 0; +} + + +static void mdfour_tail(unsigned char *in, int n) +{ + unsigned char buf[128]; + uint32 M[16]; + uint32 b; + + m->totalN += n; + + b = m->totalN * 8; + + memset(buf, 0, 128); + if (n) memcpy(buf, in, n); + buf[n] = 0x80; + + if (n <= 55) { + copy4(buf+56, b); + copy64(M, buf); + mdfour64(M); + } else { + copy4(buf+120, b); + copy64(M, buf); + mdfour64(M); + copy64(M, buf+64); + mdfour64(M); + } +} + +void mdfour_update(struct mdfour *md, unsigned char *in, int n) +{ + uint32 M[16]; + +// start of edit by Forest 'LordHavoc' Hale +// commented out to prevent crashing when length is 0 +// if (n == 0) mdfour_tail(in, n); +// end of edit by Forest 'LordHavoc' Hale + + m = md; + + while (n >= 64) { + copy64(M, in); + mdfour64(M); + in += 64; + n -= 64; + m->totalN += 64; + } + + mdfour_tail(in, n); +} + + +void mdfour_result(struct mdfour *md, unsigned char *out) +{ + m = md; + + copy4(out, m->A); + copy4(out+4, m->B); + copy4(out+8, m->C); + copy4(out+12, m->D); +} + + +void mdfour(unsigned char *out, unsigned char *in, int n) +{ + struct mdfour md; + mdfour_begin(&md); + mdfour_update(&md, in, n); + mdfour_result(&md, out); +} + +/////////////////////////////////////////////////////////////// +// MD4-based checksum utility functions +// +// Copyright (C) 2000 Jeff Teunissen +// +// Author: Jeff Teunissen +// Date: 01 Jan 2000 + +unsigned Com_BlockChecksum (void *buffer, int length) +{ + int digest[4]; + unsigned val; + + mdfour ( (unsigned char *) digest, (unsigned char *) buffer, length ); + + val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; + + return val; +} + +void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) +{ + mdfour ( outbuf, (unsigned char *) buffer, len ); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/md4.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/md4.h new file mode 100644 index 00000000..4373c2c9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/md4.h @@ -0,0 +1,57 @@ +/* + mdfour.h + + an implementation of MD4 designed for use in the SMB authentication + protocol + + Copyright (C) Andrew Tridgell 1997-1998 + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA +*/ + +#ifndef _MDFOUR_H +#define _MDFOUR_H + +#ifndef int32 +#define int32 int +#endif + +#if SIZEOF_INT > 4 +#define LARGE_INT32 +#endif + +#ifndef uint32 +#define uint32 unsigned int32 +#endif + +struct mdfour { + uint32 A, B, C, D; + uint32 totalN; +}; + +void mdfour_begin(struct mdfour *md); // old: MD4Init +void mdfour_update(struct mdfour *md, unsigned char *in, int n); //old: MD4Update +void mdfour_result(struct mdfour *md, unsigned char *out); // old: MD4Final +void mdfour(unsigned char *out, unsigned char *in, int n); + +unsigned Com_BlockChecksum (void *buffer, int length); +void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf); + +#endif // _MDFOUR_H + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/path_init.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/path_init.c new file mode 100644 index 00000000..8947de84 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/path_init.c @@ -0,0 +1,405 @@ +/* ------------------------------------------------------------------------------- + +Copyright (C) 1999-2006 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 +*/ + +/* +Nurail: Swiped from Q3Map2 +*/ + + + +/* marker */ +#define PATH_INIT_C + +#if defined( __linux__ ) || defined( __APPLE__ ) + #define Q_UNIX +#endif + +#ifdef Q_UNIX + #include + #include + #include +#endif + + +/* dependencies */ +#include "cmdlib.h" +#include "inout.h" + + + +/* path support */ +#define MAX_BASE_PATHS 10 +#define MAX_GAME_PATHS 10 + +char *homePath; +char installPath[ MAX_OS_PATH ]; + +int numBasePaths; +char *basePaths[ MAX_BASE_PATHS ]; +int numGamePaths; +char *gamePaths[ MAX_GAME_PATHS ]; + +/* +some of this code is based off the original q3map port from loki +and finds various paths. moved here from bsp.c for clarity. +*/ + +/* +PathLokiGetHomeDir() +gets the user's home dir (for ~/.q3a) +*/ + +char *LokiGetHomeDir( void ) +{ + #ifndef Q_UNIX + return NULL; + #else + char *home; + uid_t id; + struct passwd *pwd; + + + /* get the home environment variable */ + home = getenv( "HOME" ); + if( home == NULL ) + { + /* do some more digging */ + id = getuid(); + setpwent(); + while( (pwd = getpwent()) != NULL ) + { + if( pwd->pw_uid == id ) + { + home = pwd->pw_dir; + break; + } + } + endpwent(); + } + + /* return it */ + return home; + #endif +} + + + +/* +PathLokiInitPaths() +initializes some paths on linux/os x +*/ + +void LokiInitPaths( char *argv0 ) +{ + #ifndef Q_UNIX + /* this is kinda crap, but hey */ + strcpy( installPath, "../" ); + #else + char temp[ MAX_OS_PATH ]; + char *home; + char *path; + char *last; + qboolean found; + + + /* get home dir */ + home = LokiGetHomeDir(); + if( home == NULL ) + home = "."; + + /* do some path divining */ + strcpy( temp, argv0 ); + if( strrchr( temp, '/' ) ) + argv0 = strrchr( argv0, '/' ) + 1; + else + { + /* get path environment variable */ + path = getenv( "PATH" ); + + /* minor setup */ + last[ 0 ] = path[ 0 ]; + last[ 1 ] = '\0'; + found = false; + + /* go through each : segment of path */ + while( last[ 0 ] != '\0' && found == false ) + { + /* null out temp */ + temp[ 0 ] = '\0'; + + /* find next chunk */ + last = strchr( path, ':' ); + if( last == NULL ) + last = path + strlen( path ); + + /* found home dir candidate */ + if( *path == '~' ) + { + strcpy( temp, home ); + path++; + } + + /* concatenate */ + if( last > (path + 1) ) + { + strncat( temp, path, (last - path) ); + strcat( temp, "/" ); + } + strcat( temp, "./" ); + strcat( temp, argv0 ); + + /* verify the path */ + if( access( temp, X_OK ) == 0 ) + found++; + path = last + 1; + } + } + + /* flake */ + if( realpath( temp, installPath ) ) + { + /* q3map is in "tools/" */ + *(strrchr( installPath, '/' )) = '\0'; + *(strrchr( installPath, '/' ) + 1) = '\0'; + } + + /* set home path */ + homePath = home; + #endif +} + + + +/* +CleanPath() - ydnar +cleans a dos path \ -> / +*/ + +void CleanPath( char *path ) +{ + while( *path ) + { + if( *path == '\\' ) + *path = '/'; + path++; + } +} + +/* +AddBasePath() - ydnar +adds a base path to the list +*/ + +void AddBasePath( char *path ) +{ + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' || numBasePaths >= MAX_BASE_PATHS ) + return; + + /* add it to the list */ + basePaths[ numBasePaths ] = safe_malloc( strlen( path ) + 1 ); + strcpy( basePaths[ numBasePaths ], path ); + CleanPath( basePaths[ numBasePaths ] ); + numBasePaths++; +} + + + +/* +AddHomeBasePath() - ydnar +adds a base path to the beginning of the list, prefixed by ~/ +*/ + +void AddHomeBasePath( char *path ) +{ + #ifdef Q_UNIX + int i; + char temp[ MAX_OS_PATH ]; + + + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' ) + return; + + /* make a hole */ + for( i = 0; i < (MAX_BASE_PATHS - 1); i++ ) + basePaths[ i + 1 ] = basePaths[ i ]; + + /* concatenate home dir and path */ + sprintf( temp, "%s/%s", homePath, path ); + + /* add it to the list */ + basePaths[ 0 ] = safe_malloc( strlen( temp ) + 1 ); + strcpy( basePaths[ 0 ], temp ); + CleanPath( basePaths[ 0 ] ); + numBasePaths++; + #endif +} + + + +/* +AddGamePath() - ydnar +adds a game path to the list +*/ + +void AddGamePath( char *path ) +{ + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' || numGamePaths >= MAX_GAME_PATHS ) + return; + + /* add it to the list */ + gamePaths[ numGamePaths ] = safe_malloc( strlen( path ) + 1 ); + strcpy( gamePaths[ numGamePaths ], path ); + CleanPath( gamePaths[ numGamePaths ] ); + numGamePaths++; +} + + + + +/* +InitPaths() - ydnar +cleaned up some of the path initialization code from bsp.c +will remove any arguments it uses +*/ + +void InitPaths( int *argc, char **argv ) +{ + int i, j, k, len, len2; + char temp[ MAX_OS_PATH ]; + char gamePath[MAX_OS_PATH], homeBasePath[MAX_OS_PATH], game_magic[10]; + + strcpy(gamePath, "base"); + strcpy(game_magic, "h"); + strcpy(homeBasePath, ".heretic2"); + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- InitPaths ---\n" ); + + /* get the install path for backup */ + LokiInitPaths( argv[ 0 ] ); + + /* set game to default (q3a) */ + numBasePaths = 0; + numGamePaths = 0; + + /* parse through the arguments and extract those relevant to paths */ + for( i = 0; i < *argc; i++ ) + { + /* check for null */ + if( argv[ i ] == NULL ) + continue; + + /* -fs_basepath */ + if( strcmp( argv[ i ], "-fs_basepath" ) == 0 ) + { + if( ++i >= *argc ) + Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); + argv[ i - 1 ] = NULL; + AddBasePath( argv[ i ] ); + argv[ i ] = NULL; + } + + } + + /* remove processed arguments */ + for( i = 0, j = 0, k = 0; i < *argc && j < *argc; i++, j++ ) + { + for( j; j < *argc && argv[ j ] == NULL; j++ ); + argv[ i ] = argv[ j ]; + if( argv[ i ] != NULL ) + k++; + } + *argc = k; + + /* add standard game path */ + AddGamePath( gamePath ); + + /* if there is no base path set, figure it out */ + if( numBasePaths == 0 ) + { + /* this is another crappy replacement for SetQdirFromPath() */ + len2 = strlen( game_magic ); + for( i = 0; i < *argc && numBasePaths == 0; i++ ) + { + /* extract the arg */ + strcpy( temp, argv[ i ] ); + CleanPath( temp ); + len = strlen( temp ); + Sys_FPrintf( SYS_VRB, "Searching for \"%s\" in \"%s\" (%d)...\n", game_magic, temp, i ); + + /* this is slow, but only done once */ + for( j = 0; j < (len - len2); j++ ) + { + /* check for the game's magic word */ + if( Q_strncasecmp( &temp[ j ], game_magic, len2 ) == 0 ) + { + /* now find the next slash and nuke everything after it */ + while( temp[ ++j ] != '/' && temp[ j ] != '\0' ); + temp[ j ] = '\0'; + + /* add this as a base path */ + AddBasePath( temp ); + break; + } + } + } + + /* add install path */ + if( numBasePaths == 0 ) + AddBasePath( installPath ); + + /* check again */ + if( numBasePaths == 0 ) + Error( "Failed to find a valid base path." ); + } + + /* this only affects unix */ + AddHomeBasePath( homeBasePath ); + + /* initialize vfs paths */ + if( numBasePaths > MAX_BASE_PATHS ) + numBasePaths = MAX_BASE_PATHS; + if( numGamePaths > MAX_GAME_PATHS ) + numGamePaths = MAX_GAME_PATHS; + + /* walk the list of game paths */ + //for( j = 0; j < numGamePaths; j++ ) + //{ + /* walk the list of base paths */ + // for( i = 0; i < numBasePaths; i++ ) + // { + /* create a full path and initialize it */ + // sprintf( temp, "%s/%s/", basePaths[ i ], gamePaths[ j ] ); + // vfsInitDirectory( temp ); + // } + //} + + /* done */ + Sys_Printf( "\n" ); +} + + + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.c new file mode 100644 index 00000000..ce1a909a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.c @@ -0,0 +1,656 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#include "mathlib.h" +#include "polylib.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 8192 + +void pw(winding_t *w) +{ + int i; + for (i=0 ; inumpoints ; i++) + 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 (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 = malloc (s); + if (!w) + Error("AllocWinding MALLOC failed! Could not allocate %s bytes.", 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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, 8192, vup); + VectorScale (vright, 8192, 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 ; inumpoints ; 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]; + 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; + + if (in->numpoints >= MAX_POINTS_ON_WINDING-4) + Error ("ClipWinding: MAX_POINTS_ON_WINDING"); + + counts[0] = counts[1] = counts[2] = 0; + +// determine sides for each point + for (i=0 ; inumpoints ; 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 ; inumpoints ; 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]; + 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; + + if (!in) + { + printf ("Warning: NULL passed to ChopWindingInPlace\n"); + return; + } + if (in->numpoints >= MAX_POINTS_ON_WINDING-4) + Error ("ChopWinding: MAX_POINTS_ON_WINDING"); + +// determine sides for each point + for (i=0 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; i++) + { + p1 = w->p[i]; + + for (j=0 ; j<3 ; j++) + if (p1[j] > BOGUS_RANGE || p1[j] < -BOGUS_RANGE) + Error ("CheckFace: BUGUS_RANGE: %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 ; jnumpoints ; 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 = false; + back = false; + for (i=0 ; inumpoints ; i++) + { + d = DotProduct (w->p[i], normal) - dist; + if (d < -ON_EPSILON) + { + if (front) + return SIDE_CROSS; + back = true; + continue; + } + if (d > ON_EPSILON) + { + if (back) + return SIDE_CROSS; + front = true; + continue; + } + } + + if (back) + return SIDE_BACK; + if (front) + return SIDE_FRONT; + return SIDE_ON; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.h new file mode 100644 index 00000000..fec80e06 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/polylib.h @@ -0,0 +1,55 @@ +/* +Copyright (C) 1999-2006 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 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/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.c new file mode 100644 index 00000000..25600a25 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.c @@ -0,0 +1,82 @@ +/* +Copyright (C) 1999-2006 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 "scriplib.h" +//#include + +materialtype_t defaultmaterialtypes[] = +{ + {"gravel", MATERIAL_GRAVEL}, + {"metal", MATERIAL_METAL}, + {"stone", MATERIAL_STONE}, + {"wood", MATERIAL_WOOD}, + {NULL, 0} +}; + +materialtype_t *materialtypes; + +void QFile_ReadMaterialTypes(char* filename) +{ + int i; + FILE *f; + + f = fopen (filename, "rb"); + if (!f) + { + materialtypes = defaultmaterialtypes; + return; + } + fclose (f); + + free(materialtypes); + materialtypes = (materialtype_t*)malloc(256 * sizeof(materialtype_t)); + + LoadScriptFile(filename); + i = 0; + + while (i < 255) + { + GetScriptToken (true); + if (endofscript) + { + break; + } + if (strcmp(token, "material") != 0) + { + while (ScriptTokenAvailable()) + { + GetScriptToken(false); + } + } + else + { + GetScriptToken(false); + materialtypes[i].name = (char*)malloc(strlen(token) + 1); + strcpy(materialtypes[i].name, token); + GetScriptToken (false); + materialtypes[i].value = atoi(token); + } + i++; + } + materialtypes[i].name = NULL; + materialtypes[i].value = 0; +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.h new file mode 100644 index 00000000..3492136e --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/qfiles.h @@ -0,0 +1,619 @@ +/* +Copyright (C) 1999-2006 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 + +#include "q_typedef.h" + +// +// qfiles.h: quake file formats +// This file must be identical in the quake and utils directories +// + +/* +======================================================================== + +The .pak files are just a linear collapse of a directory tree + +======================================================================== +*/ + +#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P') + +typedef struct +{ + char name[56]; + int filepos, filelen; +} dpackfile_t; + +typedef struct +{ + int ident; // == IDPAKHEADER + int dirofs; + int dirlen; +} dpackheader_t; + +#define MAX_FILES_IN_PACK 4096 + + +/* +======================================================================== + +PCX files are used for as many images as possible + +======================================================================== +*/ + +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; + + +/* +======================================================================== + +.MD2 compressed triangle model file format + +======================================================================== +*/ +#define IDJOINTEDALIASHEADER (('2'<<24)+('J'<<16)+('D'<<8)+'I') + +/* +======================================================================== + +.MD2 triangle model file format + +======================================================================== +*/ + +#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I') +#define ALIAS_VERSION 8 + +#define MAX_TRIANGLES 2048 +#define MAX_VERTS 2048 +#define MAX_FRAMES 512 +#define MAX_MD2SKINS 64 +#define MAX_SKINNAME 64 + +typedef struct +{ + short s; + short t; +} dstvert_t; + +typedef struct +{ + short index_xyz[3]; + short index_st[3]; +} dtriangle_t; + +typedef struct +{ + byte v[3]; // scaled byte to fit in frame mins/maxs + byte lightnormalindex; +} dtrivertx_t; + +#define DTRIVERTX_V0 0 +#define DTRIVERTX_V1 1 +#define DTRIVERTX_V2 2 +#define DTRIVERTX_LNI 3 +#define DTRIVERTX_SIZE 4 + +typedef struct +{ + float scale[3]; // multiply byte verts by this + float translate[3]; // then add this + char name[16]; // frame name from grabbing + dtrivertx_t verts[1]; // variable sized +} daliasframe_t; + + +// the glcmd format: +// a positive integer starts a tristrip command, followed by that many +// vertex structures. +// a negative integer starts a trifan command, followed by -x vertexes +// a zero indicates the end of the command list. +// a vertex consists of a floating point s, a floating point t, +// and an integer vertex index. + + +typedef struct +{ + int ident; + int version; + + int skinwidth; + int skinheight; + int framesize; // byte size of each frame + + int num_skins; + int num_xyz; + int num_st; // greater than num_xyz for seams + int num_tris; + int num_glcmds; // dwords in strip/fan command list + int num_frames; + + int ofs_skins; // each skin is a MAX_SKINNAME string + int ofs_st; // byte offset from start for stverts + int ofs_tris; // offset for dtriangles + int ofs_frames; // offset for first frame + int ofs_glcmds; + int ofs_end; // end of file + +} dmdl_t; + +/* +======================================================================== + +.BK file format + +======================================================================== +*/ + +#define IDBOOKHEADER (('K'<<24)+('O'<<16)+('O'<<8)+'B') +#define BOOK_VERSION 2 + +typedef struct bookframe_s +{ + int x; + int y; + int w; + int h; + char name[MAX_SKINNAME]; // name of gfx file +} bookframe_t; + +typedef struct bookheader_s +{ + unsigned int ident; + unsigned int version; + int num_segments; + int total_w; + int total_h; +} bookheader_t; + +typedef struct book_s +{ + bookheader_t bheader; + bookframe_t bframes[MAX_MD2SKINS]; +} book_t; + +/* +======================================================================== + +.SP2 sprite file format + +======================================================================== +*/ + +#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I') + // little-endian "IDS2" +#define SPRITE_VERSION 2 + +typedef struct +{ + int width, height; + int origin_x, origin_y; // raster coordinates inside pic + char name[MAX_SKINNAME]; // name of pcx file +} dsprframe_t; + +typedef struct { + int ident; + int version; + int numframes; + dsprframe_t frames[1]; // variable sized +} dsprite_t; + +/* +============================================================================== + + .M8 texture file format + +============================================================================== +*/ + +typedef struct palette_s +{ + union + { + struct + { + byte r,g,b; + }; + }; +} palette_t; + +#define MIP_VERSION 2 +#define PAL_SIZE 256 +#define MIPLEVELS 16 + +typedef struct miptex_s +{ + int version; + char name[32]; + unsigned width[MIPLEVELS], height[MIPLEVELS]; + unsigned offsets[MIPLEVELS]; // four mip maps stored + char animname[32]; // next frame in animation chain + palette_t palette[PAL_SIZE]; + int flags; + int contents; + int value; +} miptex_t; + + +#define MIP32_VERSION 4 + +#define MIP32_NOMIP_FLAG2 0x00000001 +#define MIP32_DETAILER_FLAG2 0x00000002 + +typedef struct miptex32_s +{ + int version; + char name[128]; + char altname[128]; // texture substitution + char animname[128]; // next frame in animation chain + char damagename[128]; // image that should be shown when damaged + unsigned width[MIPLEVELS], height[MIPLEVELS]; + unsigned offsets[MIPLEVELS]; + int flags; + int contents; + int value; + float scale_x, scale_y; + int mip_scale; + + // detail texturing info + char dt_name[128]; // detailed texture name + float dt_scale_x, dt_scale_y; + float dt_u, dt_v; + float dt_alpha; + int dt_src_blend_mode, dt_dst_blend_mode; + + int flags2; + int unused[19]; // future expansion to maintain compatibility with h2 +} miptex32_t; + + + +/* +============================================================================== + + .BSP file format + +============================================================================== +*/ + +#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') + // little-endian "IBSP" + +#define BSPVERSION 38 + + +// upper design bounds +// leaffaces, leafbrushes, planes, and verts are still bounded by +// 16 bit short limits +#define MAX_MAP_MODELS 1024 +#define MAX_MAP_BRUSHES 8192 +#define MAX_MAP_ENTITIES 2048 +#define MAX_MAP_ENTSTRING 0x40000 +#define MAX_MAP_TEXINFO 8192 + +#define MAX_MAP_AREAS 256 +#define MAX_MAP_AREAPORTALS 1024 +#define MAX_MAP_PLANES 65536 +#define MAX_MAP_NODES 65536 +#define MAX_MAP_BRUSHSIDES 65536 +#define MAX_MAP_LEAFS 65536 +#define MAX_MAP_VERTS 65536 +#define MAX_MAP_FACES 65536 +#define MAX_MAP_LEAFFACES 65536 +#define MAX_MAP_LEAFBRUSHES 65536 +#define MAX_MAP_PORTALS 65536 +#define MAX_MAP_EDGES 128000 +#define MAX_MAP_SURFEDGES 256000 +#define MAX_MAP_LIGHTING 0x200000 +#define MAX_MAP_VISIBILITY 0x180000 + +// key / value pair sizes + +#define MAX_KEY 32 +#define MAX_VALUE 1024 + +//============================================================================= + +typedef struct +{ + int fileofs, filelen; +} lump_t; + +#define LUMP_ENTITIES 0 +#define LUMP_PLANES 1 +#define LUMP_VERTEXES 2 +#define LUMP_VISIBILITY 3 +#define LUMP_NODES 4 +#define LUMP_TEXINFO 5 +#define LUMP_FACES 6 +#define LUMP_LIGHTING 7 +#define LUMP_LEAFS 8 +#define LUMP_LEAFFACES 9 +#define LUMP_LEAFBRUSHES 10 +#define LUMP_EDGES 11 +#define LUMP_SURFEDGES 12 +#define LUMP_MODELS 13 +#define LUMP_BRUSHES 14 +#define LUMP_BRUSHSIDES 15 +#define LUMP_POP 16 +#define LUMP_AREAS 17 +#define LUMP_AREAPORTALS 18 +#define HEADER_LUMPS 19 + +typedef struct +{ + int ident; + int version; + lump_t lumps[HEADER_LUMPS]; +} dheader_t; + +typedef struct +{ + float mins[3], maxs[3]; + float origin[3]; // for sounds or lights + int headnode; + int firstface, numfaces; // submodels just draw faces + // without walking the bsp tree +} dmodel_t; + + +typedef struct +{ + float point[3]; +} dvertex_t; + + +// 0-2 are axial planes +#define PLANE_X 0 +#define PLANE_Y 1 +#define PLANE_Z 2 + +// 3-5 are non-axial planes snapped to the nearest +#define PLANE_ANYX 3 +#define PLANE_ANYY 4 +#define PLANE_ANYZ 5 + +// planes (x&~1) and (x&~1)+1 are allways opposites + +typedef struct +{ + float normal[3]; + float dist; + int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate +} dplane_t; + + +// contents flags are seperate bits +// a given brush can contribute multiple content bits +// multiple brushes can be in a single leaf + +// these definitions also need to be in q_shared.h! + +// lower bits are stronger, and will eat weaker brushes completely +#define CONTENTS_SOLID 0x00000001 // an eye is never valid in a solid +#define CONTENTS_WINDOW 0x00000002 // translucent, but not watery +#define CONTENTS_PUSHPULL 0x00000004 +#define CONTENTS_LAVA 0x00000008 +#define CONTENTS_SLIME 0x00000010 +#define CONTENTS_WATER 0x00000020 +#define CONTENTS_MIST 0x00000040 // 64 +#define LAST_VISIBLE_CONTENTS 64 // this one worries me a bit JKH + +// remaining contents are non-visible, and don't eat brushes + +#define CONTENTS_AREAPORTAL 0x00008000 + +#define CONTENTS_PLAYERCLIP 0x00010000 +#define CONTENTS_MONSTERCLIP 0x00020000 + +// currents can be added to any other contents, and may be mixed +#define CONTENTS_CURRENT_0 0x00040000 +#define CONTENTS_CURRENT_90 0x00080000 +#define CONTENTS_CURRENT_180 0x00100000 +#define CONTENTS_CURRENT_270 0x00200000 +#define CONTENTS_CURRENT_UP 0x00400000 +#define CONTENTS_CURRENT_DOWN 0x00800000 + +#define CONTENTS_ORIGIN 0x01000000 // removed before bsping an entity + +#define CONTENTS_MONSTER 0x02000000 // should never be on a brush, only in game +#define CONTENTS_DEADMONSTER 0x04000000 +#define CONTENTS_DETAIL 0x08000000 // brushes to be added after vis leafs +#define CONTENTS_TRANSLUCENT 0x10000000 // auto set if any surface has trans +#define CONTENTS_LADDER 0x20000000 + + + +#define SURF_LIGHT 0x00000001 // value will hold the light strength + +#define SURF_SLICK 0x00000002 // effects game physics + +#define SURF_SKY 0x00000004 // don't draw, but add to skybox +#define SURF_WARP 0x00000008 // turbulent water warp +#define SURF_TRANS33 0x00000010 +#define SURF_TRANS66 0x00000020 +#define SURF_FLOWING 0x00000040 // scroll towards angle +#define SURF_NODRAW 0x00000080 // don't bother referencing the texture + +#define SURF_HINT 0x00000100 // make a primary bsp splitter +#define SURF_SKIP 0x00000200 // completely ignore, allowing non-closed brushes +#define SURF_TALL_WALL 0x00000400 // face doesn't get broken up as normal + +#define SURF_ALPHA_TEXTURE 0x00000800 // texture has alpha in it, and should show through in bsp process +#define SURF_ANIMSPEED 0x00001000 // value will hold the anim speed in fps + +#define SURF_UNDULATE 0x00002000 // rock surface up and down... +#define SURF_SKYREFLECT 0x00004000 // liquid will somewhat reflect the sky - not quite finished.... + +#define SURF_TYPE_GRAVEL 0x00000000 +#define SURF_TYPE_METAL 0x01000000 +#define SURF_TYPE_STONE 0x02000000 +#define SURF_TYPE_WOOD 0x03000000 +#define SURF_MATERIAL 0xFF000000 + + + +typedef struct +{ + int planenum; + int children[2]; // negative numbers are -(leafs+1), not nodes + short mins[3]; // for frustom culling + short maxs[3]; + unsigned short firstface; + unsigned short numfaces; // counting both sides +} dnode_t; + + +typedef struct texinfo_s +{ + float vecs[2][4]; // [s/t][xyz offset] + int flags; // miptex flags + overrides + int value; // light emission, etc + char texture[32]; // texture name (textures/*.wal) + int nexttexinfo; // for animations, -1 = end of chain +} texinfo_t; + + +// note that edge 0 is never used, because negative edge nums are used for +// counterclockwise use of the edge in a face +typedef struct +{ + unsigned short v[2]; // vertex numbers +} dedge_t; + +#define MAXLIGHTMAPS 4 +typedef struct +{ + unsigned short planenum; + short side; + + int firstedge; // we must support > 64k edges + short numedges; + short texinfo; + +// lighting info + union { + byte styles[MAXLIGHTMAPS]; + paletteRGBA_t lighting; + }; + int lightofs; // start of [numstyles*surfsize] samples +} dface_t; + +typedef struct +{ + int contents; // OR of all brushes (not needed?) + + short cluster; + short area; + + short mins[3]; // for frustum culling + short maxs[3]; + + unsigned short firstleafface; + unsigned short numleaffaces; + + unsigned short firstleafbrush; + unsigned short numleafbrushes; +} dleaf_t; + +typedef struct +{ + unsigned short planenum; // facing out of the leaf + short texinfo; +} dbrushside_t; + +typedef struct +{ + int firstside; + int numsides; + int contents; +} dbrush_t; + +#define ANGLE_UP -1 +#define ANGLE_DOWN -2 + + +// the visibility lump consists of a header with a count, then +// byte offsets for the PVS and PHS of each cluster, then the raw +// compressed bit vectors +#define DVIS_PVS 0 +#define DVIS_PHS 1 +typedef struct +{ + int numclusters; + int bitofs[8][2]; // bitofs[numclusters][2] +} dvis_t; + +// each area has a list of portals that lead into other areas +// when portals are closed, other areas may not be visible or +// hearable even if the vis info says that it should be +typedef struct +{ + int portalnum; + int otherarea; +} dareaportal_t; + + +typedef struct +{ + int numareaportals; + int firstareaportal; +} darea_t; + +typedef struct +{ + char *name; + int value; +} materialtype_t; + +enum +{ + MATERIAL_GRAVEL, + MATERIAL_METAL, + MATERIAL_STONE, + MATERIAL_WOOD, +}; + +materialtype_t *materialtypes; + +void QFile_ReadMaterialTypes(char* filename); + + +#endif //_QFILES_H diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.c new file mode 100644 index 00000000..c9001795 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.c @@ -0,0 +1,297 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#include "scriplib.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 true if UnGetScriptToken was just called + +/* +============== +AddScriptToStack +============== +*/ +void AddScriptToStack (char *filename) +{ + int size; + + script++; + if (script == &scriptstack[MAX_INCLUDES]) + Error ("script file exceeded MAX_INCLUDES"); + strcpy (script->filename, ExpandPath (filename) ); + + size = LoadFile (script->filename, (void **)&script->buffer); + + printf ("entering %s\n", script->filename); + + script->line = 1; + + script->script_p = script->buffer; + script->end_p = script->buffer + size; +} + + +/* +============== +LoadScriptFile +============== +*/ +void LoadScriptFile (char *filename) +{ + script = scriptstack; + AddScriptToStack (filename); + + endofscript = false; + tokenready = false; +} + + +/* +============== +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 = false; + tokenready = false; +} + + +/* +============== +UnGetScriptToken + +Signals that the current token was not used, and should be reported +for the next GetScriptToken. Note that + +GetScriptToken (true); +UnGetScriptToken (); +GetScriptToken (false); + +could cross a line boundary. +============== +*/ +void UnGetScriptToken (void) +{ + tokenready = true; +} + + +qboolean EndOfScript (qboolean crossline) +{ + if (!crossline) + Error ("Line %i is incomplete\n",scriptline); + + if (!strcmp (script->filename, "memory buffer")) + { + endofscript = true; + return false; + } + + free (script->buffer); + if (script == scriptstack+1) + { + endofscript = true; + return false; + } + script--; + scriptline = script->line; + printf ("returning to %s\n", script->filename); + return GetScriptToken (crossline); +} + +/* +============== +GetScriptToken +============== +*/ +qboolean GetScriptToken (qboolean crossline) +{ + char *token_p; + + if (tokenready) // is a token allready waiting? + { + tokenready = false; + return true; + } + + if (script->script_p >= script->end_p) + 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); + 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); + 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] != '/') + { + 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")) + { + GetScriptToken (false); + AddScriptToStack (token); + return GetScriptToken (crossline); + } + + return true; +} + + +/* +============== +ScriptTokenAvailable + +Returns true if there is another token on the line +============== +*/ +qboolean ScriptTokenAvailable (void) +{ + char *search_p; + + search_p = script->script_p; + + if (search_p >= script->end_p) + return false; + + while ( *search_p <= 32) + { + if (*search_p == '\n') + return false; + search_p++; + if (search_p == script->end_p) + return false; + + } + + if (*search_p == ';') + return false; + + return true; +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.h new file mode 100644 index 00000000..4a87d582 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/scriplib.h @@ -0,0 +1,44 @@ +/* +Copyright (C) 1999-2006 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 "cmdlib.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 (char *filename); +void ParseFromMemory (char *buffer, int size); + +qboolean GetScriptToken (qboolean crossline); +void UnGetScriptToken (void); +qboolean ScriptTokenAvailable (void); + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/threads.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/threads.c new file mode 100644 index 00000000..bf37b9f7 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/threads.c @@ -0,0 +1,620 @@ +/* +Copyright (C) 1999-2006 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 "her2_threads.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 = true; + + // + // run threads in parallel + // + InitializeCriticalSection (&crit); + + if (numthreads == 1) + { // use same thread + func (0); + } + else + { + for (i=0 ; i + +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 = true; + + 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 +#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 = true; + + if (pacifier) + setbuf (stdout, NULL); + + init_lock (&lck); + + for (i=0 ; i 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 = true; + + 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", + "", + "", + "", + "", + "", + "", + "(", + ")", + "{", + "}", + "[", + "]", + ":", + "mesh", + "model", + "nodes", + "rotation", + "scaling", + "translation", + "polygons", + "position", + "vertex", + "vertices", + "HRCH", + "Softimage" +}; + +// CODE -------------------------------------------------------------------- + +//========================================================================== +// +// TK_Init +// +//========================================================================== + +void TK_Init(void) +{ + int i; + + for(i = 0; i < 256; i++) + { + ASCIIToChrCode[i] = CHR_SPECIAL; + } + for(i = '0'; i <= '9'; i++) + { + ASCIIToChrCode[i] = CHR_NUMBER; + } + for(i = 'A'; i <= 'Z'; i++) + { + ASCIIToChrCode[i] = CHR_LETTER; + } + for(i = 'a'; i <= 'z'; i++) + { + ASCIIToChrCode[i] = CHR_LETTER; + } + ASCIIToChrCode[ASCII_QUOTE] = CHR_QUOTE; + ASCIIToChrCode[ASCII_UNDERSCORE] = CHR_LETTER; + ASCIIToChrCode[EOF_CHARACTER] = CHR_EOF; + tk_String = TokenStringBuffer; + IncLineNumber = FALSE; + SourceOpen = FALSE; +} + +//========================================================================== +// +// TK_OpenSource +// +//========================================================================== + +void TK_OpenSource(char *fileName) +{ + int size; + + TK_CloseSource(); + size = LoadFile(fileName, (void **)&FileStart); + strcpy(tk_SourceName, fileName); + SourceOpen = TRUE; + FileEnd = FileStart+size; + FilePtr = FileStart; + tk_Line = 1; + tk_Token = TK_NONE; + NextChr(); +} + +//========================================================================== +// +// TK_CloseSource +// +//========================================================================== + +void TK_CloseSource(void) +{ + if(SourceOpen) + { + free(FileStart); + SourceOpen = FALSE; + } +} + +//========================================================================== +// +// TK_Fetch +// +//========================================================================== + +tokenType_t TK_Fetch(void) +{ + while(Chr == ASCII_SPACE) + { + NextChr(); + } + if(Chr == '-') + { + ProcessNumberToken(); + } + else switch(ASCIIToChrCode[(byte)Chr]) + { + case CHR_EOF: + tk_Token = TK_EOF; + break; + case CHR_LETTER: + ProcessLetterToken(); + break; + case CHR_NUMBER: + ProcessNumberToken(); + break; + case CHR_QUOTE: + ProcessQuoteToken(); + break; + default: + ProcessSpecialToken(); + break; + } + return tk_Token; +} + +//========================================================================== +// +// TK_Require +// +//========================================================================== + +void TK_Require(tokenType_t tokType) +{ + if(tokType == TK_FLOATNUMBER && tk_Token == TK_INTNUMBER) + { + tk_FloatNumber = (float)tk_IntNumber; + tk_Token = TK_FLOATNUMBER; + return; + } + if(tk_Token != tokType) + { + Error("File '%s', line %d:\nExpected '%s', found '%s'.\n", + tk_SourceName, tk_Line, TokenNames[tokType], + TokenNames[tk_Token]); + } +} + +void TK_FetchRequire(tokenType_t tokType) +{ + TK_Fetch(); + TK_Require(tokType); +} + +tokenType_t TK_RequireFetch(tokenType_t tokType) +{ + TK_Require(tokType); + return TK_Fetch(); +} + +tokenType_t TK_FetchRequireFetch(tokenType_t tokType) +{ + TK_Fetch(); + TK_Require(tokType); + return TK_Fetch(); +} + +tokenType_t TK_Beyond(tokenType_t tokType) +{ + while(tk_Token != tokType) + { + if(TK_Fetch() == TK_EOF) + { + Error("File '%s':\nCould not find token '%s'.\n", // FIXME: TokenNames table not big enuff + tk_SourceName, TokenNames[tokType]); + } + } + return TK_Fetch(); +} + +void TK_BeyondRequire(tokenType_t bTok, tokenType_t rTok) +{ + TK_Beyond(bTok); + TK_Require(rTok); +} + +tokenType_t TK_Search(tokenType_t tokType) +{ + while(tk_Token != tokType) + { + if(TK_Fetch() == TK_EOF) + { + return TK_EOF; + } + } + return TK_Fetch(); +} + +tokenType_t TK_Get(tokenType_t tokType) +{ + while(tk_Token != tokType) + { + if(TK_Fetch() == TK_EOF) + { + Error("File '%s':\nCould not find token '%s'.\n", + tk_SourceName, TokenNames[tokType]); + } + } + return tk_Token; +} + +//========================================================================== +// +// ProcessLetterToken +// +//========================================================================== + +static void ProcessLetterToken(void) +{ + int i; + char *text; + + i = 0; + text = TokenStringBuffer; + while(ASCIIToChrCode[(byte)Chr] == CHR_LETTER + || ASCIIToChrCode[(byte)Chr] == CHR_NUMBER) + { + if(++i == MAX_IDENTIFIER_LENGTH) + { + Error("File '%s', line %d:\nIdentifier too long.\n", + tk_SourceName, tk_Line); + } + *text++ = Chr; + NextChr(); + } + *text = 0; + if(CheckForKeyword() == FALSE) + { + tk_Token = TK_IDENTIFIER; + } +} + +//========================================================================== +// +// CheckForKeyword +// +//========================================================================== + +static qboolean CheckForKeyword(void) +{ + int i; + + for(i = 0; Keywords[i].name != NULL; i++) + { + if(strcmp(tk_String, Keywords[i].name) == 0) + { + tk_Token = Keywords[i].token; + return TRUE; + } + } + return FALSE; +} + +//========================================================================== +// +// ProcessNumberToken +// +//========================================================================== + +static void ProcessNumberToken(void) +{ + char *buffer; + + buffer = TempBuffer; + *buffer++ = Chr; + NextChr(); + while(ASCIIToChrCode[(byte)Chr] == CHR_NUMBER) + { + *buffer++ = Chr; + NextChr(); + } + if(Chr == '.') + { // Float + *buffer++ = Chr; + NextChr(); // Skip period + while(ASCIIToChrCode[(byte)Chr] == CHR_NUMBER) + { + *buffer++ = Chr; + NextChr(); + } + *buffer = 0; + tk_FloatNumber = (float)atof(TempBuffer); + tk_Token = TK_FLOATNUMBER; + return; + } + + // Integer + *buffer = 0; + tk_IntNumber = atoi(TempBuffer); + tk_Token = TK_INTNUMBER; +} + +//========================================================================== +// +// ProcessQuoteToken +// +//========================================================================== + +static void ProcessQuoteToken(void) +{ + int i; + char *text; + + i = 0; + text = TokenStringBuffer; + NextChr(); + while(Chr != ASCII_QUOTE) + { + if(Chr == EOF_CHARACTER) + { + Error("File '%s', line %d:\n inside string.\n", + tk_SourceName, tk_Line); + } + if(++i > MAX_QUOTED_LENGTH-1) + { + Error("File '%s', line %d:\nString literal too long.\n", + tk_SourceName, tk_Line); + } + *text++ = Chr; + NextChr(); + } + *text = 0; + NextChr(); + tk_Token = TK_STRING; +} + +//========================================================================== +// +// ProcessSpecialToken +// +//========================================================================== + +static void ProcessSpecialToken(void) +{ + char c; + + c = Chr; + NextChr(); + switch(c) + { + case '(': + tk_Token = TK_LPAREN; + break; + case ')': + tk_Token = TK_RPAREN; + break; + case '{': + tk_Token = TK_LBRACE; + break; + case '}': + tk_Token = TK_RBRACE; + break; + case '[': + tk_Token = TK_LBRACKET; + break; + case ']': + tk_Token = TK_RBRACKET; + break; + case ':': + tk_Token = TK_COLON; + break; + default: + tk_Token = TK_UNKNOWNCHAR; + break; + } +} + +//========================================================================== +// +// NextChr +// +//========================================================================== + +static void NextChr(void) +{ + if(FilePtr >= FileEnd) + { + Chr = EOF_CHARACTER; + return; + } + if(IncLineNumber == TRUE) + { + tk_Line++; + IncLineNumber = FALSE; + } + Chr = *FilePtr++; + if(Chr < ASCII_SPACE) + { + if(Chr == '\n') + { + IncLineNumber = TRUE; + } + Chr = ASCII_SPACE; + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/token.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/token.h new file mode 100644 index 00000000..1e2fd27e --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/token.h @@ -0,0 +1,132 @@ +/* +Copyright (C) 1999-2006 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 +*/ + + +//************************************************************************** +//** +//** token.h +//** +//************************************************************************** + +#ifndef __TOKEN_H__ +#define __TOKEN_H__ + +#include "cmdlib.h" + +#ifndef TRUE +#define TRUE 1 +#endif +#ifndef FALSE +#define FALSE 0 +#endif +#ifndef YES +#define YES 1 +#endif +#ifndef NO +#define NO 0 +#endif +#define ASCII_SPACE 32 +#define ASCII_QUOTE 34 +#define ASCII_UNDERSCORE 95 +#define EOF_CHARACTER 127 +#define MAX_IDENTIFIER_LENGTH 64 +#define MAX_QUOTED_LENGTH 1024 +#define MAX_FILE_NAME_LENGTH 1024 + +typedef enum +{ + TK_NONE, + TK_UNKNOWNCHAR, + TK_EOF, + TK_IDENTIFIER, // VALUE: (char *) tk_String + TK_STRING, // VALUE: (char *) tk_String + TK_INTNUMBER, // VALUE: (int) tk_IntNumber + TK_FLOATNUMBER, // VALUE: (float) tk_FloatNumber + TK_LPAREN, + TK_RPAREN, + TK_LBRACE, + TK_RBRACE, // 10 + TK_LBRACKET, + TK_RBRACKET, + TK_COLON, + TK_MESH, + TK_MODEL, // 15 + TK_NODES, + TK_ROTATION, + TK_SCALING, + TK_TRANSLATION, + TK_POLYGONS, // 20 + TK_POSITION, + TK_VERTEX, + TK_VERTICES, + TK_EDGES, + TK_HRCH, // 25 + TK_SOFTIMAGE, + TK_MATERIAL, + TK_SPLINE, // 28 + + TK_C_NAMED, + TK_OBJECT, // 30 + TK_C_TRI, + TK_C_VERTICES, + TK_C_FACES, + TK_C_VERTEX, + TK_LIST, // 35 + TK_C_FACE, + + TK_C_HEXEN, + TK_C_TRIANGLES, + TK_C_VERSION, + TK_FACES, // 40 + TK_FACE, + TK_ORIGIN, + + TK_CLUSTERS, + TK_NUM_CLUSTER_VERTICES, + TK_NAME, // 45 + TK_CLUSTER_NAME, + TK_CLUSTER_STATE, + + TK_ACTOR_DATA, + TK_UVTEXTURE, +} tokenType_t; + +void TK_Init(void); +void TK_OpenSource(char *fileName); +void TK_CloseSource(void); +tokenType_t TK_Fetch(void); +void TK_Require(tokenType_t tokType); +void TK_FetchRequire(tokenType_t tokType); +tokenType_t TK_RequireFetch(tokenType_t tokType); +tokenType_t TK_FetchRequireFetch(tokenType_t tokType); +tokenType_t TK_Beyond(tokenType_t tokType); +void TK_BeyondRequire(tokenType_t bTok, tokenType_t rTok); +tokenType_t TK_Search(tokenType_t tokType); +tokenType_t TK_Get(tokenType_t tokType); + +extern tokenType_t tk_Token; +extern int tk_Line; +extern int tk_IntNumber; +extern float tk_FloatNumber; +extern char *tk_String; +extern char tk_SourceName[MAX_FILE_NAME_LENGTH]; + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.c new file mode 100644 index 00000000..e7583447 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.c @@ -0,0 +1,1077 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#include "mathlib.h" +#include "trilib.h" +#include "token.h" +#include "l3dslib.h" +#include "fmodel.h" +#if 1 +#include "qd_skeletons.h" +#endif + +// on disk representation of a face +#define FLOAT_START 99999.0 +#define FLOAT_END -FLOAT_START +#define MAGIC 123322 +#ifndef M_PI + #define M_PI 3.14159265 +#endif + +float FixHTRRotateX = 0.0; +float FixHTRRotateY = 0.0; +float FixHTRRotateZ = 0.0; +float FixHTRTranslateX = 0.0; +float FixHTRTranslateY = 0.0; +float FixHTRTranslateZ = 0.0; + +//#define NOISY 1 + +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; + + +void ByteSwapTri (tf_triangle *tri) +{ + int i; + + for (i=0 ; iverts[j][k] = tri.pt[j].p.v[k]; + } + } + + ptri++; + + if ((ptri - *pptri) >= MAXTRIANGLES) + Error ("Error: too many triangles; increase MAXTRIANGLES\n"); + } + } + + *numtriangles = ptri - *pptri; + + fclose (input); + + DefaultNodesList(nodesList,num_mesh_nodes,numtriangles); +} + + +//========================================================================== +// +// LoadHRC +// +//========================================================================== + +float scaling[3]; +float rotation[3]; +float translation[3]; +static char *hrc_name; + +struct +{ + float v[3]; +} vList[8192]; + +void HandleHRCModel(triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes, + int ActiveNode, int Depth, int numVerts) +{ + void ReadHRCClusterList(mesh_node_t *meshNode, int baseIndex); + + int i, j; + int vertexCount; + int triCount; + triangle_t *tList; + mesh_node_t *meshNode; + float x, y, z; + float x2, y2, z2; + float rx, ry, rz; + tokenType_t nextToken; + float orig_scaling[3]; + float orig_rotation[3]; + float orig_translation[3]; + int start_tri; + int pos,bit; + int vertIndexBase; + + // Update Node Info + if (nodesList) + { + TK_BeyondRequire(TK_NAME, TK_STRING); + + if (Depth == 0 || tk_String[0] == '_') + { // Root + ActiveNode = *num_mesh_nodes; + (*num_mesh_nodes)++; + if ((*num_mesh_nodes) > MAX_FM_MESH_NODES) + { + Error("Too many mesh nodes in file %s\n", hrc_name); + } + meshNode = &(*nodesList)[ActiveNode]; + +// memset(meshNode, 0, sizeof(mesh_node_t)); + strcpy(meshNode->name, tk_String); + + memset(meshNode->tris, 0, sizeof(meshNode->tris)); + memset(meshNode->verts, 0, sizeof(meshNode->verts)); + + meshNode->start_glcmds = 0; + meshNode->num_glcmds = 0; + vertIndexBase = 0; + } + else + { // Childs under the children + meshNode = &(*nodesList)[ActiveNode]; + vertIndexBase = numVerts; + } + } + else + { + meshNode = NULL; + } + + + // Get the scaling, rotation, and translation values + TK_Beyond(TK_SCALING); + for(i = 0; i < 3; i++) + { + orig_scaling[i] = scaling[i]; + + TK_Require(TK_FLOATNUMBER); + scaling[i] *= tk_FloatNumber; + + TK_Fetch(); + } + TK_Beyond(TK_ROTATION); + for(i = 0; i < 3; i++) + { + orig_rotation[i] = rotation[i]; + + TK_Require(TK_FLOATNUMBER); + rotation[i] = tk_FloatNumber; + + TK_Fetch(); + } + TK_Beyond(TK_TRANSLATION); + for(i = 0; i < 3; i++) + { + orig_translation[i] = translation[i]; + + TK_Require(TK_FLOATNUMBER); + translation[i] += tk_FloatNumber; + + TK_Fetch(); + } + + rx = ((rotation[0]-90.0)/360.0)*2.0*M_PI; + ry = (rotation[2]/360.0)*2.0*M_PI; + rz = (rotation[1]/360.0)*2.0*M_PI; + + // rjr - might not work if there an item doesn't have a mesh + nextToken = tk_Token; + if (nextToken == TK_ACTOR_DATA) + { + while (nextToken != TK_MODEL && nextToken != TK_RBRACE) + { + nextToken = TK_Fetch(); + } + } + + while (nextToken == TK_SPLINE) + { // spline node has two right braces + nextToken = TK_Beyond(TK_RBRACE); + nextToken = TK_Beyond(TK_RBRACE); + } + + while (nextToken == TK_MATERIAL) + { + nextToken = TK_Beyond(TK_RBRACE); + } + + while(nextToken == TK_MODEL) + { + HandleHRCModel(triList,triangleCount,nodesList,num_mesh_nodes,ActiveNode, Depth+1, 0); + + nextToken = TK_Fetch(); + } + + if (nextToken == TK_MESH) + { + // Get all the tri and vertex info + TK_BeyondRequire(TK_VERTICES, TK_INTNUMBER); + vertexCount = tk_IntNumber; + for(i = 0; i < vertexCount; i++) + { + TK_BeyondRequire(TK_LBRACKET, TK_INTNUMBER); + if(tk_IntNumber != i) + { + Error("File '%s', line %d:\nVertex index mismatch.\n", + tk_SourceName, tk_Line); + } + TK_Beyond(TK_POSITION); + // Apply the scaling, rotation, and translation in the order + // specified in the HRC file. This could be wrong. + TK_Require(TK_FLOATNUMBER); + x = tk_FloatNumber*scaling[0]; + TK_FetchRequire(TK_FLOATNUMBER); + y = tk_FloatNumber*scaling[1]; + TK_FetchRequire(TK_FLOATNUMBER); + z = tk_FloatNumber*scaling[2]; + + y2 = y*cos(rx)+z*sin(rx); + z2 = -y*sin(rx)+z*cos(rx); + y = y2; + z = z2; + + x2 = x*cos(ry)-z*sin(ry); + z2 = x*sin(ry)+z*cos(ry); + x = x2; + z = z2; + + x2 = x*cos(rz)+y*sin(rz); + y2 = -x*sin(rz)+y*cos(rz); + x = x2; + y = y2; + + vList[i].v[0] = x+translation[0]; + vList[i].v[1] = y-translation[2]; + vList[i].v[2] = z+translation[1]; + } + TK_BeyondRequire(TK_POLYGONS, TK_INTNUMBER); + triCount = tk_IntNumber; + if(triCount >= MAXTRIANGLES) + { + Error("Too many triangles in file %s\n", hrc_name); + } + + start_tri = *triangleCount; + *triangleCount += triCount; + + tList = *triList; + + for(i = 0; i < triCount; i++) + { + if (meshNode) + { // Update the node + pos = (i + start_tri) >> 3; + bit = 1 << ((i + start_tri) & 7 ); + meshNode->tris[pos] |= bit; + } + + TK_BeyondRequire(TK_LBRACKET, TK_INTNUMBER); + if(tk_IntNumber != i) + { + Error("File '%s', line %d:\nTriangle index mismatch.\n", + tk_SourceName, tk_Line); + } + TK_BeyondRequire(TK_NODES, TK_INTNUMBER); + if(tk_IntNumber != 3) + { + Error("File '%s', line %d:\nBad polygon vertex count: %d.", + tk_SourceName, tk_Line, tk_IntNumber); + } + tList[i+start_tri].HasUV = true; + for(j = 0; j < 3; j++) + { + TK_BeyondRequire(TK_LBRACKET, TK_INTNUMBER); + if(tk_IntNumber != j) + { + Error("File '%s', line %d:\nTriangle vertex index" + " mismatch. %d should be %d\n", tk_SourceName, tk_Line, + tk_IntNumber, j); + } + TK_BeyondRequire(TK_VERTEX, TK_INTNUMBER); + + tList[i+start_tri].verts[2-j][0] = vList[tk_IntNumber].v[0]; + tList[i+start_tri].verts[2-j][1] = vList[tk_IntNumber].v[1]; + tList[i+start_tri].verts[2-j][2] = vList[tk_IntNumber].v[2]; +#if 1 + tList[i+start_tri].indicies[2-j] = tk_IntNumber+vertIndexBase; +#endif + TK_BeyondRequire(TK_UVTEXTURE, TK_FLOATNUMBER); + tList[i+start_tri].uv[2-j][0] = tk_FloatNumber; + TK_Fetch(); + TK_Require(TK_FLOATNUMBER); + tList[i+start_tri].uv[2-j][1] = tk_FloatNumber; + } + + /* printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" + " v2: %f, %f, %f\n", i, + tList[i].verts[0][0], + tList[i].verts[0][1], + tList[i].verts[0][2], + tList[i].verts[1][0], + tList[i].verts[1][1], + tList[i].verts[1][2], + tList[i].verts[2][0], + tList[i].verts[2][1], + tList[i].verts[2][2]); + */ + } + + TK_Beyond(TK_RBRACE); + TK_Beyond(TK_RBRACE); + + if (tk_Token == TK_EDGES) + { + // TK_Beyond(TK_EDGES); + TK_Beyond(TK_RBRACE); + } + + scaling[0] = scaling[1] = scaling[2] = 1.0; + // rotation[0] = rotation[1] = rotation[2] = 0.0; + // translation[0] = translation[1] = translation[2] = 0.0; + + // See if there are any other models belonging to this node + +#if 1 + TK_Fetch(); + + nextToken = tk_Token; + if(nextToken == TK_CLUSTERS) + { + if(g_skelModel.clustered == -1) + { + ReadHRCClusterList(meshNode, vertIndexBase); + } + else + { + nextToken = TK_Get(TK_CLUSTER_NAME); + + while (nextToken == TK_CLUSTER_NAME) + { + TK_BeyondRequire(TK_CLUSTER_STATE, TK_INTNUMBER); + nextToken = TK_Fetch(); + } + } + + // one right brace follow the list of clusters + nextToken = TK_Beyond(TK_RBRACE); + } + else + { + if(g_skelModel.clustered == -1 && !vertIndexBase) + { + meshNode->clustered = false; + } + } +#endif + + nextToken = tk_Token; + if(nextToken == TK_SPLINE) + { + while (nextToken == TK_SPLINE) + { // spline node has two right braces + nextToken = TK_Beyond(TK_RBRACE); + nextToken = TK_Beyond(TK_RBRACE); + } + + nextToken = TK_Beyond(TK_RBRACE); + } + + while (nextToken == TK_MATERIAL) + { + nextToken = TK_Beyond(TK_RBRACE); + } + + while(nextToken == TK_MODEL) + { + HandleHRCModel(triList,triangleCount,nodesList, num_mesh_nodes, ActiveNode, Depth+1, vertexCount+vertIndexBase); + + nextToken = TK_Fetch(); + } + } + + for(i=0;i<3;i++) + { + scaling[i] = orig_scaling[i]; + rotation[i] = orig_rotation[i]; + translation[i] = orig_translation[i]; + } +} + +static void LoadHRC(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) +{ + if (nodesList) + { + *num_mesh_nodes = 0; + + if(!*nodesList) + { + *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); + } + } + + hrc_name = fileName; + + scaling[0] = scaling[1] = scaling[2] = 1.0; + rotation[0] = rotation[1] = rotation[2] = 0.0; + translation[0] = translation[1] = translation[2] = 0.0; + + *triangleCount = 0; + *triList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); + memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + + // prime it + TK_Beyond(TK_MODEL); + + HandleHRCModel(triList, triangleCount, nodesList, num_mesh_nodes, 0, 0, 0); + TK_CloseSource(); +} + +//========================================================================== +// +// LoadHTR +// +//========================================================================== +/* +static int Version2; + +void HandleHTRModel(triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes, + int ActiveNode, int Depth, int numVerts) +{ + int i, j; + int vertexCount; + int vertexNum; + int triCount; + float origin[3]; + triangle_t *tList; + float x, y, z; + float x2, y2, z2; + float rx, ry, rz; + mesh_node_t *meshNode; + int pos,bit; + int vertIndexBase; + int start_tri; + + if (nodesList) + { + TK_BeyondRequire(TK_NAME, TK_STRING); + + if (Depth == 0 || tk_String[0] == '_') + { // Root + ActiveNode = *num_mesh_nodes; + (*num_mesh_nodes)++; + if ((*num_mesh_nodes) > MAX_FM_MESH_NODES) + { + Error("Too many mesh nodes in file %s\n", hrc_name); + } + meshNode = &(*nodesList)[ActiveNode]; + +// memset(meshNode, 0, sizeof(mesh_node_t)); + strcpy(meshNode->name, tk_String); + + memset(meshNode->tris, 0, sizeof(meshNode->tris)); + memset(meshNode->verts, 0, sizeof(meshNode->verts)); + + meshNode->start_glcmds = 0; + meshNode->num_glcmds = 0; + vertIndexBase = 0; + } + else + { // Childs under the children + meshNode = &(*nodesList)[ActiveNode]; + vertIndexBase = numVerts; + } + } + else + { + meshNode = NULL; + } + + // Get vertex count + TK_BeyondRequire(TK_VERTICES, TK_INTNUMBER); + vertexCount = tk_IntNumber; + + // Get triangle count + TK_BeyondRequire(TK_FACES, TK_INTNUMBER); + triCount = tk_IntNumber; + if(triCount >= MAXTRIANGLES) + { + Error("Too many triangles in file %s\n", hrc_name); + } + + // Get origin + TK_Beyond(TK_ORIGIN); + TK_Require(TK_FLOATNUMBER); + origin[0] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + origin[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + origin[2] = tk_FloatNumber; + + //rx = 90.0/360.0*2.0*M_PI; + rx = FixHTRRotateX/360.0*2.0*M_PI; + ry = FixHTRRotateY/360.0*2.0*M_PI; + rz = FixHTRRotateZ/360.0*2.0*M_PI; + + // Get vertex list + for(i = 0; i < vertexCount; i++) + { + TK_FetchRequire(TK_VERTEX); + TK_FetchRequire(TK_FLOATNUMBER); + x = tk_FloatNumber-origin[0]; + TK_FetchRequire(TK_FLOATNUMBER); + y = tk_FloatNumber-origin[1]; + TK_FetchRequire(TK_FLOATNUMBER); + z = tk_FloatNumber-origin[2]; + + x += FixHTRTranslateX; + y += FixHTRTranslateY; + z += FixHTRTranslateZ; + + y2 = y*cos(rx)-z*sin(rx); + z2 = y*sin(rx)+z*cos(rx); + y = y2; + z = z2; + x2 = x*cos(ry)+z*sin(ry); + z2 = -x*sin(ry)+z*cos(ry); + x = x2; + z = z2; + x2 = x*cos(rz)-y*sin(rz); + y2 = x*sin(rz)+y*cos(rz); + x = x2; + y = y2; + + vList[i].v[0] = x; + vList[i].v[1] = y; + vList[i].v[2] = z; + } + + start_tri = *triangleCount; + *triangleCount += triCount; + + tList = *triList; + + // Get face list + for(i = 0; i < triCount; i++) + { + if (meshNode) + { // Update the node + pos = (i + start_tri) >> 3; + bit = 1 << ((i + start_tri) & 7 ); + meshNode->tris[pos] |= bit; + } + + TK_FetchRequire(TK_FACE); + TK_FetchRequire(TK_LPAREN); + for(j = 0; j < 3; j++) + { + TK_FetchRequire(TK_INTNUMBER); + vertexNum = tk_IntNumber-1; + if(vertexNum >= vertexCount) + { + Error("File '%s', line %d:\nVertex number" + " >= vertexCount: %d\n", tk_SourceName, tk_Line, + tk_IntNumber); + } + tList[i+start_tri].verts[2-j][0] = vList[vertexNum].v[0]; + tList[i+start_tri].verts[2-j][1] = vList[vertexNum].v[1]; + tList[i+start_tri].verts[2-j][2] = vList[vertexNum].v[2]; + } + TK_FetchRequire(TK_RPAREN); +#ifdef _QDATA + if (Version2) + { + TK_FetchRequire(TK_FLOATNUMBER); + tList[i+start_tri].uv[0][0]=tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + tList[i+start_tri].uv[0][1]=tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + tList[i+start_tri].uv[1][0]=tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + tList[i+start_tri].uv[1][1]=tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + tList[i+start_tri].uv[2][0]=tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + tList[i+start_tri].uv[2][1]=tk_FloatNumber; + tList[i+start_tri].HasUV=1; + } + else + tList[i+start_tri].HasUV=0; +#endif +// printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" +// " v2: %f, %f, %f\n", i, +// tList[i].verts[0][0], +// tList[i].verts[0][1], +// tList[i].verts[0][2], +// tList[i].verts[1][0], +// tList[i].verts[1][1], +// tList[i].verts[1][2], +// tList[i].verts[2][0], +// tList[i].verts[2][1], +// tList[i].verts[2][2]); + + } + + TK_Fetch(); + + if (tk_Token == TK_VERTICES) + { + HandleHTRModel(triList,triangleCount,nodesList, num_mesh_nodes, ActiveNode, Depth+1, vertexCount+vertIndexBase); + } +} + +static void LoadHTR(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) +{ + if (nodesList) + { + *num_mesh_nodes = 0; + + if(!*nodesList) + { + *nodesList = SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); + } + } + + hrc_name = fileName; + + scaling[0] = scaling[1] = scaling[2] = 1.0; + rotation[0] = rotation[1] = rotation[2] = 0.0; + translation[0] = translation[1] = translation[2] = 0.0; + + *triangleCount = 0; + *triList = SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); + memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); + + TK_OpenSource(fileName); + + TK_Beyond(TK_C_HEXEN); + TK_Beyond(TK_C_TRIANGLES); + TK_BeyondRequire(TK_C_VERSION, TK_INTNUMBER); + if(tk_IntNumber != 1&&tk_IntNumber != 2) + { + Error("Unsupported version (%d) in file %s\n", tk_IntNumber, + fileName); + } + Version2=(tk_IntNumber==2); + + + HandleHTRModel(triList, triangleCount, nodesList, num_mesh_nodes, 0, 0, 0); +} + +*/ + +static void LoadHTR(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **nodesList, int *num_mesh_nodes) +{ + int Version2=0; + int i, j; + int vertexCount; + int vertexNum; + struct + { + float v[3]; + } *vList; + int triCount; + float origin[3]; + triangle_t *tList; + float x, y, z; + float x2, y2, z2; + float rx, ry, rz; + + if (nodesList) + { + *num_mesh_nodes = 0; + *nodesList = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); + } + + TK_OpenSource(fileName); + + TK_Beyond(TK_C_HEXEN); + TK_Beyond(TK_C_TRIANGLES); + TK_BeyondRequire(TK_C_VERSION, TK_INTNUMBER); + if(tk_IntNumber != 1&&tk_IntNumber != 2) + { + Error("Unsupported version (%d) in file %s\n", tk_IntNumber, + fileName); + } + Version2=(tk_IntNumber==2); + + + // Get vertex count + TK_BeyondRequire(TK_VERTICES, TK_INTNUMBER); + vertexCount = tk_IntNumber; + vList = (void *) SafeMalloc(vertexCount*sizeof vList[0], "Vertex list"); + + // Get triangle count + TK_BeyondRequire(TK_FACES, TK_INTNUMBER); + triCount = tk_IntNumber; + if(triCount >= MAXTRIANGLES) + { + Error("Too many triangles in file %s\n", fileName); + } + *triangleCount = triCount; + tList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); + *triList = tList; + memset(*triList,0,MAXTRIANGLES*sizeof(triangle_t)); + + // Get origin + TK_Beyond(TK_ORIGIN); + TK_Require(TK_FLOATNUMBER); + origin[0] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + origin[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + origin[2] = tk_FloatNumber; + + //rx = 90.0/360.0*2.0*M_PI; + rx = FixHTRRotateX/360.0*2.0*M_PI; + ry = FixHTRRotateY/360.0*2.0*M_PI; + rz = FixHTRRotateZ/360.0*2.0*M_PI; + + // Get vertex list + for(i = 0; i < vertexCount; i++) + { + TK_FetchRequire(TK_VERTEX); + TK_FetchRequire(TK_FLOATNUMBER); + x = tk_FloatNumber-origin[0]; + TK_FetchRequire(TK_FLOATNUMBER); + y = tk_FloatNumber-origin[1]; + TK_FetchRequire(TK_FLOATNUMBER); + z = tk_FloatNumber-origin[2]; + + x += FixHTRTranslateX; + y += FixHTRTranslateY; + z += FixHTRTranslateZ; + + y2 = y*cos(rx)-z*sin(rx); + z2 = y*sin(rx)+z*cos(rx); + y = y2; + z = z2; + x2 = x*cos(ry)+z*sin(ry); + z2 = -x*sin(ry)+z*cos(ry); + x = x2; + z = z2; + x2 = x*cos(rz)-y*sin(rz); + y2 = x*sin(rz)+y*cos(rz); + x = x2; + y = y2; + + vList[i].v[0] = x; + vList[i].v[1] = y; + vList[i].v[2] = z; + } + + // Get face list + for(i = 0; i < triCount; i++) + { + TK_FetchRequire(TK_FACE); + TK_FetchRequire(TK_LPAREN); + for(j = 0; j < 3; j++) + { + TK_FetchRequire(TK_INTNUMBER); + vertexNum = tk_IntNumber-1; + if(vertexNum >= vertexCount) + { + Error("File '%s', line %d:\nVertex number" + " >= vertexCount: %d\n", tk_SourceName, tk_Line, + tk_IntNumber); + } + tList[i].verts[2-j][0] = vList[vertexNum].v[0]; + tList[i].verts[2-j][1] = vList[vertexNum].v[1]; + tList[i].verts[2-j][2] = vList[vertexNum].v[2]; + } + TK_FetchRequire(TK_RPAREN); +#if 1 + if (Version2) + { + TK_FetchRequire(TK_FLOATNUMBER); + tList[i].uv[2][0]= fmod(1000+tk_FloatNumber,1); + TK_FetchRequire(TK_FLOATNUMBER); + tList[i].uv[2][1]=fmod(1000+tk_FloatNumber,1); + TK_FetchRequire(TK_FLOATNUMBER); + tList[i].uv[1][0]=fmod(1000+tk_FloatNumber,1); + TK_FetchRequire(TK_FLOATNUMBER); + tList[i].uv[1][1]=fmod(1000+tk_FloatNumber,1); + TK_FetchRequire(TK_FLOATNUMBER); + tList[i].uv[0][0]=fmod(1000+tk_FloatNumber,1); + TK_FetchRequire(TK_FLOATNUMBER); + tList[i].uv[0][1]=fmod(1000+tk_FloatNumber,1); + tList[i].HasUV=1; + } + else + tList[i].HasUV=0; +#endif +/* printf("Face %i:\n v0: %f, %f, %f\n v1: %f, %f, %f\n" + " v2: %f, %f, %f\n", i, + tList[i].verts[0][0], + tList[i].verts[0][1], + tList[i].verts[0][2], + tList[i].verts[1][0], + tList[i].verts[1][1], + tList[i].verts[1][2], + tList[i].verts[2][0], + tList[i].verts[2][1], + tList[i].verts[2][2]); +*/ + } + + free(vList); + TK_CloseSource(); + DefaultNodesList(nodesList,num_mesh_nodes,triangleCount); +} + +//========================================================================== +// +// LoadTriangleList +// +//========================================================================== + +void LoadTriangleList(char *fileName, triangle_t **triList, int *triangleCount, mesh_node_t **ppmnodes, int *num_mesh_nodes) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + LoadHRC(InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + printf(" - assuming .HRC\n"); + return; + } + + strcpy(InputFileName, fileName); + strcat(InputFileName, ".asc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + LoadASC(InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + printf(" - assuming .ASC\n"); + return; + } + + strcpy(InputFileName, fileName); + strcat(InputFileName, ".tri"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + LoadTRI(InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + printf(" - assuming .TRI\n"); + return; + } + + strcpy(InputFileName, fileName); + strcat(InputFileName, ".3ds"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + Load3DSTriangleList (InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + printf(" - assuming .3DS\n"); + return; + } + + strcpy(InputFileName, fileName); + strcat(InputFileName, ".htr"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + LoadHTR (InputFileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + printf(" - assuming .HTR\n"); + return; + } + Error("\n Could not open file '%s':\n" + "No HRC, ASC, 3DS, HTR, or TRI match.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { + printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRC(fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + } + else if (strcmp(dotstart,".asc") == 0 || strcmp(dotstart,".ASC") == 0) + { + LoadASC(fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + } + else if (strcmp(dotstart,".tri") == 0 || strcmp(dotstart,".TRI") == 0) + { + LoadTRI(fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + } + else if (strcmp(dotstart,".3ds") == 0 || strcmp(dotstart,".3DS") == 0) + { + Load3DSTriangleList (fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + } + else if (strcmp(dotstart,".htr") == 0 || strcmp(dotstart,".HTR") == 0) + { + LoadHTR (fileName, triList, triangleCount, ppmnodes, num_mesh_nodes); + } + else + { + Error("Could not open file '%s':\n",fileName); + return; + } + } + else //failed to load file + { + Error("Could not open file '%s':\n",fileName); + } + + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.h new file mode 100644 index 00000000..94263e0b --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/common/trilib.h @@ -0,0 +1,56 @@ +/* +Copyright (C) 1999-2006 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 +// + +#include "fmodel.h" + +#define MAXTRIANGLES MAX_FM_TRIANGLES + +typedef struct +{ + vec3_t verts[3]; +#if 1 + int indicies[3]; + float uv[3][2]; + qboolean HasUV; +#endif +} triangle_t; + +#define NUM_CLUSTERS 8 + +typedef struct +{ + char name[64]; + byte tris[MAXTRIANGLES>>3]; + byte verts[MAX_FM_VERTS>>3]; + int start_glcmds, num_glcmds; + + int *clusters[NUM_CLUSTERS]; + struct IntListNode_s *vertLists[NUM_CLUSTERS]; + int num_verts[NUM_CLUSTERS + 1]; + int new_num_verts[NUM_CLUSTERS + 1]; + qboolean clustered; +} mesh_node_t; + +void LoadTriangleList (char *filename, triangle_t **pptri, int *numtriangles, mesh_node_t **ppmnodes, int *num_mesh_nodes); diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/fmodels.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/fmodels.c new file mode 100644 index 00000000..7570240a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/fmodels.c @@ -0,0 +1,3404 @@ +/* +Copyright (C) 1999-2006 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 "qd_fmodel.h" +#include "animcomp.h" +#include "qd_skeletons.h" +#include "skeletons.h" +#include "qdata.h" +#include "flex.h" +#include "reference.h" + +#include + +/* +======================================================================== + +.FM triangle flexible model file format + +======================================================================== +*/ + +//================================================================= + +#define NUMVERTEXNORMALS 162 + +extern float avertexnormals[NUMVERTEXNORMALS][3]; + +#define MAX_GROUPS 128 + +typedef struct +{ + triangle_t triangle; + int group; +} trigroup_t; + +#define TRIVERT_DIST .1 + +typedef struct +{ + int start_frame; + int num_frames; + int degrees; + char *mat; + char *ccomp; + char *cbase; + float *cscale; + float *coffset; + float trans[3]; + float scale[3]; + float bmin[3]; + float bmax[3]; +} fmgroup_t; + +//================================================================ + +// Initial +fmheader_t fmheader; + +// Skin +extern char g_skins[MAX_FM_SKINS][64]; + +// ST Coord +extern fmstvert_t base_st[MAX_FM_VERTS]; + +// Triangles +extern fmtriangle_t triangles[MAX_FM_TRIANGLES]; + +// Frames +fmframe_t g_frames[MAX_FM_FRAMES]; +//fmframe_t *g_FMframes; + +// GL Commands +extern int commands[16384]; +extern int numcommands; + + +// +// varibles set by commands +// +extern float scale_up; // set by $scale +extern vec3_t adjust; // set by $origin +extern int g_fixedwidth, g_fixedheight; // set by $skinsize +extern char modelname[64]; // set by $modelname + + +extern char *g_outputDir; + + +// Mesh Nodes +mesh_node_t *pmnodes = NULL; +fmmeshnode_t mesh_nodes[MAX_FM_MESH_NODES]; + +fmgroup_t groups[MAX_GROUPS]; +int num_groups; +int frame_to_group[MAX_FM_FRAMES]; + +// +// variables set by command line arguments +// +qboolean g_no_opimizations = false; + + +// +// base frame info +// +static int triangle_st[MAX_FM_TRIANGLES][3][2]; + + +// number of gl vertices +extern int numglverts; +// indicates if a triangle has already been used in a glcmd +extern int used[MAX_FM_TRIANGLES]; +// indicates if a triangle has translucency in it or not +static qboolean translucent[MAX_FM_TRIANGLES]; + +// main output file handle +extern FILE *headerouthandle; +// output sizes of buildst() +static int skin_width, skin_height; + + +// statistics +static int total_skin_pixels; +static int skin_pixels_used; + +int ShareVertex( trigroup_t trione, trigroup_t tritwo); +float DistBetween(vec3_t point1, vec3_t point2); +int GetNumTris( trigroup_t *tris, int group); +void GetOneGroup(trigroup_t *tris, int grp, triangle_t* triangles); +void ScaleTris( vec3_t min, vec3_t max, int Width, int Height, float* u, float* v, int verts); +void NewDrawLine(int x1, int y1, int x2, int y2, unsigned char* picture, int width, int height); + +#ifndef _WIN32 + +void strupr(char *string) +{ + int i; + + for (i=0 ; iverts[fmheader.num_xyz]; + + WriteHeader(modelouthandle, FM_HEADER_NAME, FM_HEADER_VER, sizeof(fmheader), &fmheader); + + // + // write out the skin names + // + + WriteHeader(modelouthandle, FM_SKIN_NAME, FM_SKIN_VER, fmheader.num_skins * MAX_FM_SKINNAME, g_skins); + + // + // write out the texture coordinates + // + c_on = c_off = 0; + for (i=0 ; iname, in->name); + for (j=0 ; j<3 ; j++) + { + out->scale[j] = (in->maxs[j] - in->mins[j])/255; + out->translate[j] = in->mins[j]; + + outFrames[i].scale[j] = out->scale[j]; + outFrames[i].translate[j] = out->translate[j]; + } + + for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; + + for (k=0 ; k<3 ; k++) + { + // scale to byte values & min/max check + v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); + + // clamp, so rounding doesn't wrap from 255.6 to 0 + if (v > 255.0) + v = 255.0; + if (v < 0) + v = 0; + out->verts[j].v[k] = v; + } + } + + for (j=0 ; j<3 ; j++) + { + out->scale[j] = LittleFloat (out->scale[j]); + out->translate[j] = LittleFloat (out->translate[j]); + } + + SafeWrite (modelouthandle, out, fmheader.framesize); + } + + // Go back and finish the header + // WriteHeader(modelouthandle, FM_FRAME_NAME, FM_FRAME_VER, -1, NULL); + } + else + { + WriteHeader(modelouthandle, FM_SHORT_FRAME_NAME, FM_SHORT_FRAME_VER,FRAME_NAME_LEN*fmheader.num_frames, NULL); + for (i=0 ; iname,FRAME_NAME_LEN); + } + WriteHeader(modelouthandle, FM_NORMAL_NAME, FM_NORMAL_VER,fmheader.num_xyz, NULL); + in = &g_frames[0]; + for (j=0 ; jv[j].lightnormalindex,1); + } + + // + // write out glcmds + // + WriteHeader(modelouthandle, FM_GLCMDS_NAME, FM_GLCMDS_VER, numcommands*4, commands); + + // + // write out mesh nodes + // + for(i=0;idegrees*sizeof(char) + char *ccomp; g->num_frames*g->degrees*sizeof(char) + char *cbase; fmheader.num_xyz*3*sizeof(unsigned char) + float *cscale; g->degrees*sizeof(float) + float *coffset; g->degrees*sizeof(float) + float trans[3]; 3*sizeof(float) + float scale[3]; 3*sizeof(float) +} fmgroup_t; +*/ + int tmp,k; + fmgroup_t *g; + size=sizeof(int)+fmheader.num_frames*sizeof(int); + for (k=0;kdegrees*sizeof(char); + size+=g->num_frames*g->degrees*sizeof(char); + size+=fmheader.num_xyz*3*sizeof(unsigned char); + size+=g->degrees*sizeof(float); + size+=g->degrees*sizeof(float); + size+=12*sizeof(float); + } + WriteHeader(modelouthandle, FM_COMP_NAME, FM_COMP_VER,size, NULL); + SafeWrite (modelouthandle,&num_groups,sizeof(int)); + SafeWrite (modelouthandle,frame_to_group,sizeof(int)*fmheader.num_frames); + + for (k=0;kstart_frame); + SafeWrite (modelouthandle,&tmp,sizeof(int)); + tmp=LittleLong(g->num_frames); + SafeWrite (modelouthandle,&tmp,sizeof(int)); + tmp=LittleLong(g->degrees); + SafeWrite (modelouthandle,&tmp,sizeof(int)); + + SafeWrite (modelouthandle,g->mat,fmheader.num_xyz*3*g->degrees*sizeof(char)); + SafeWrite (modelouthandle,g->ccomp,g->num_frames*g->degrees*sizeof(char)); + SafeWrite (modelouthandle,g->cbase,fmheader.num_xyz*3*sizeof(unsigned char)); + SafeWrite (modelouthandle,g->cscale,g->degrees*sizeof(float)); + SafeWrite (modelouthandle,g->coffset,g->degrees*sizeof(float)); + SafeWrite (modelouthandle,g->trans,3*sizeof(float)); + SafeWrite (modelouthandle,g->scale,3*sizeof(float)); + SafeWrite (modelouthandle,g->bmin,3*sizeof(float)); + SafeWrite (modelouthandle,g->bmax,3*sizeof(float)); + free(g->mat); + free(g->ccomp); + free(g->cbase); + free(g->cscale); + free(g->coffset); + } + } + + // write the skeletal info + if(g_skelModel.type != SKEL_NULL) + { + size = 0; + + temp = sizeof(int); // change this to a byte + memcpy(data + size, &g_skelModel.type, temp); + size += temp; + + // number of joints + temp = sizeof(int); // change this to a byte + memcpy(data + size, &numJointsInSkeleton[g_skelModel.type], temp); + size += temp; + + // number of verts in each joint cluster + temp = sizeof(int)*numJointsInSkeleton[g_skelModel.type]; // change this to shorts + memcpy(data + size, &g_skelModel.new_num_verts[1], temp); + size += temp; + + // cluster verts + for(i = 0; i < numJointsInSkeleton[g_skelModel.type]; ++i) + { + current = g_skelModel.vertLists[i]; + while(current) + { + temp = sizeof(int); // change this to a short + memcpy(data + size, ¤t->data, temp); + size += temp; + toFree = current; + current = current->next; + free(toFree); // freeing of memory allocated in ReplaceClusterIndex called in Cmd_Base + } + } + + if(!num_groups) // joints are stored with regular verts for compressed models + { + framesWritten = true; + + temp = sizeof(int); // change this to a byte + memcpy(data + size, &framesWritten, temp); + size += temp; + + for (i = 0; i < fmheader.num_frames; ++i) + { + in = &g_frames[i]; + + for (j = 0 ; j < numJointsInSkeleton[g_skelModel.type]; ++j) + { + for (k=0 ; k<3 ; k++) + { + // scale to byte values & min/max check + v = Q_rint ( (in->joints[j].placement.origin[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // write out origin as a float since they arn't clamped + temp = sizeof(float); // change this to a short + assert(size+temp < DATA_SIZE); + memcpy(data + size, &v, temp); + size += temp; + } + + for (k=0 ; k<3 ; k++) + { + v = Q_rint ( (in->joints[j].placement.direction[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // write out origin as a float since they arn't clamped + temp = sizeof(float); // change this to a short + assert(size+temp < DATA_SIZE); + memcpy(data + size, &v, temp); + size += temp; + } + + for (k=0 ; k<3 ; k++) + { + v = Q_rint ( (in->joints[j].placement.up[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // write out origin as a float since they arn't clamped + temp = sizeof(float); // change this to a short + assert(size+temp < DATA_SIZE); + memcpy(data + size, &v, temp); + size += temp; + } + } + } + + } + else + { + temp = sizeof(int); // change this to a byte + memcpy(data + size, &framesWritten, temp); + size += temp; + } + + WriteHeader(modelouthandle, FM_SKELETON_NAME, FM_SKELETON_VER, size, data); + } + + if(g_skelModel.references != REF_NULL) + { + int refnum; + + size = 0; + if (RefPointNum <= 0) + { // Hard-coded labels + refnum = numReferences[g_skelModel.references]; + } + else + { // Labels indicated in QDT + refnum = RefPointNum; + } + + temp = sizeof(int); // change this to a byte + memcpy(data2 + size, &g_skelModel.references, temp); + size += temp; + + if(!num_groups) + { + framesWritten = true; + + temp = sizeof(int); // change this to a byte + memcpy(data2 + size, &framesWritten, temp); + size += temp; + + for (i = 0; i < fmheader.num_frames; ++i) + { + in = &g_frames[i]; + + for (j = 0 ; j < refnum; ++j) + { + for (k=0 ; k<3 ; k++) + { + // scale to byte values & min/max check + v = Q_rint ( (in->references[j].placement.origin[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // write out origin as a float since they arn't clamped + temp = sizeof(float); // change this to a short + assert(size+temp < DATA_SIZE); + memcpy(data2 + size, &v, temp); + size += temp; + } + + for (k=0 ; k<3 ; k++) + { + v = Q_rint ( (in->references[j].placement.direction[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // write out origin as a float since they arn't clamped + temp = sizeof(float); // change this to a short + assert(size+temp < DATA_SIZE); + memcpy(data2 + size, &v, temp); + size += temp; + } + + for (k=0 ; k<3 ; k++) + { + v = Q_rint ( (in->references[j].placement.up[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // write out origin as a float since they arn't clamped + temp = sizeof(float); // change this to a short + assert(size+temp < DATA_SIZE); + memcpy(data2 + size, &v, temp); + size += temp; + } + } + } + } + else // FINISH ME: references need to be stored with regular verts for compressed models + { + framesWritten = false; + + temp = sizeof(int); // change this to a byte + memcpy(data2 + size, &framesWritten, temp); + size += temp; + } + + WriteHeader(modelouthandle, FM_REFERENCES_NAME, FM_REFERENCES_VER, size, data2); + } +} + +static void CompressFrames() +{ + fmgroup_t *g; + int i,j,k; + fmframe_t *in; + + j=0; + for (i=0;i=groups[j].start_frame+groups[j].num_frames&&jnum_frames,fmheader.num_xyz,g->degrees); + for (i=0;inum_frames;i++) + { + in = &g_frames[i+g->start_frame]; + for (j=0;jv[j].v[0],in->v[j].v[1],in->v[j].v[2]); + } + AnimCompressDoit(); + g->mat= (char *) SafeMalloc(fmheader.num_xyz*3*g->degrees*sizeof(char), "CompressFrames"); + g->ccomp=(char *) SafeMalloc(g->num_frames*g->degrees*sizeof(char), "CompressFrames"); + g->cbase=(char *) SafeMalloc(fmheader.num_xyz*3*sizeof(unsigned char), "CompressFrames"); + g->cscale=(float *) SafeMalloc(g->degrees*sizeof(float), "CompressFrames"); + g->coffset=(float *) SafeMalloc(g->degrees*sizeof(float), "CompressFrames"); + AnimCompressToBytes(g->trans,g->scale,g->mat,g->ccomp,g->cbase,g->cscale,g->coffset,g->bmin,g->bmax); + AnimCompressEnd(); + } +} + +static void OptimizeVertices(void) +{ + qboolean vert_used[MAX_FM_VERTS]; + short vert_replacement[MAX_FM_VERTS]; + int i,j,k,l,pos,bit,set_pos,set_bit; + fmframe_t *in; + qboolean Found; + int num_unique; + static IntListNode_t *newVertLists[NUM_CLUSTERS]; + static int newNum_verts[NUM_CLUSTERS]; + IntListNode_t *current, *next; + + printf("Optimizing vertices..."); + + memset(vert_used, 0, sizeof(vert_used)); + + if(g_skelModel.clustered == true) + { + memset(newNum_verts, 0, sizeof(newNum_verts)); + memset(newVertLists, 0, sizeof(newVertLists)); + } + + num_unique = 0; + + // search for common points among all the frames + for (i=0 ; iv[j].v[0] == in->v[k].v[0] && + in->v[j].v[1] == in->v[k].v[1] && + in->v[j].v[2] == in->v[k].v[2]) + { + Found = true; + vert_replacement[j] = k; + break; + } + + } + + if (!Found) + { + if (!vert_used[j]) + { + num_unique++; + } + vert_used[j] = true; + } + } + } + + // recompute the light normals + for (i=0 ; iv[j].vnorm.normalsum, in->v[k].vnorm.normalsum, in->v[k].vnorm.normalsum); + in->v[k].vnorm.numnormals += in->v[j].vnorm.numnormals++; + } + } + + for (j=0 ; jv[j].vnorm.numnormals; + if (!c) + Error ("Vertex with no triangles attached"); + + VectorScale (in->v[j].vnorm.normalsum, 1.0/c, v); + VectorNormalize (v, v); + + maxdot = -999999.0; + maxdotindex = -1; + + for (k=0 ; k maxdot) + { + maxdot = dot; + maxdotindex = k; + } + } + + in->v[j].lightnormalindex = maxdotindex; + } + } + + // create substitution list + num_unique = 0; + for(i=0;inext) + { + if(current->data == i) + { + IntListNode_t *current2; + int m; + qboolean added = false; + + for(m = 0, current2 = newVertLists[k]; m < newNum_verts[k+1]; + ++m, current2 = current2->next) + { + if(current2->data == vert_replacement[i]) + { + added = true; + break; + } + } + + if(!added) + { + ++newNum_verts[k+1]; + + next = newVertLists[k]; + + newVertLists[k] = (IntListNode_t *) SafeMalloc(sizeof(IntListNode_t), "OptimizeVertices"); + // freed after model write out + + newVertLists[k]->data = vert_replacement[i]; + newVertLists[k]->next = next; + } + break; + } + } + } + } + } + + // substitute + for (i=0 ; iv[vert_replacement[j]] = in->v[j]; + } + + } + + for(i = 0; i < numJointsInSkeleton[g_skelModel.type]; ++i) + { + IntListNode_t *toFree; + current = g_skelModel.vertLists[i]; + + while(current) + { + toFree = current; + current = current->next; + free(toFree); // freeing of memory allocated in ReplaceClusterIndex called in Cmd_Base + } + + g_skelModel.vertLists[i] = newVertLists[i]; + g_skelModel.new_num_verts[i+1] = newNum_verts[i+1]; + } + +#ifndef NDEBUG + for(k = 0; k < numJointsInSkeleton[g_skelModel.type]; ++k) + { + for(l = 0, current = g_skelModel.vertLists[k]; + l < g_skelModel.new_num_verts[k+1]; ++l, current = current->next) + { + IntListNode_t *current2; + int m; + + for(m = l+1, current2 = current->next; m < newNum_verts[k+1]; + ++m, current2 = current2->next) + { + if(current->data == current2->data) + { + printf("Warning duplicate vertex: %d\n", current->data); + break; + } + } + } + } +#endif + + for(i=0;i> 3; + bit = 1 << (i & 7 ); + + for (j=0 ; j<3 ; j++) + { + set_bit = set_pos = triangles[i].index_xyz[j] = vert_replacement[triangles[i].index_xyz[j]]; + + set_pos >>= 3; + set_bit = 1 << (set_bit & 7); + + for(k=0;kreferences[j].placement.origin, in->v[index].v); + index++; + + VectorCopy(in->references[j].placement.direction, in->v[index].v); + index++; + + VectorCopy(in->references[j].placement.up, in->v[index].v); + index++; + } + } + + fmheader.num_xyz += refnum*3; + } + + // tack on the skeletal joint verts to the regular verts + if(g_skelModel.type != SKEL_NULL) + { + fmframe_t *in; + int index; + + for (i = 0; i < fmheader.num_frames; ++i) + { + in = &g_frames[i]; + index = fmheader.num_xyz; + + for (j = 0 ; j < numJointsInSkeleton[g_skelModel.type]; ++j) + { + VectorCopy(in->joints[j].placement.origin, in->v[index].v); + index++; + + VectorCopy(in->joints[j].placement.direction, in->v[index].v); + index++; + + VectorCopy(in->joints[j].placement.up, in->v[index].v); + index++; + } + } + + fmheader.num_xyz += numJointsInSkeleton[g_skelModel.type]*3; + } + + CompressFrames(); + } +} + + +/* +=============== +FinishModel +=============== +*/ +void FMFinishModel (void) +{ + FILE *modelouthandle; + int i,j,length,tris,verts,bit,pos,total_tris,total_verts; + char name[1024]; + int trans_count; + + if (!fmheader.num_frames) + return; + +// +// copy to release directory tree if doing a release build +// + if (g_release) + { + if (modelname[0]) + sprintf (name, "%s", modelname); + else + sprintf (name, "%s/tris.fm", cdpartial); + ReleaseFile (name); + + for (i=0 ; i> 3; + bit = 1 << ((j) & 7 ); + if (pmnodes[i].tris[pos] & bit) + { + tris++; + } + } + for(j=0;j> 3; + bit = 1 << ((j) & 7 ); + if (pmnodes[i].verts[pos] & bit) + { + verts++; + } + } + + printf("%-33s %4d %5d\n",pmnodes[i].name,tris,verts); + + total_tris += tris; + total_verts += verts; + } + printf("--------------------------------- ---- -----\n"); + printf("%-33s %4d %5d\n","TOTALS",total_tris,total_verts); + } + } + fclose (modelouthandle); + + // finish writing header file + H_printf("\n"); + + // scale_up is usefull to allow step distances to be adjusted + H_printf("#define MODEL_SCALE\t\t%f\n", scale_up); + + // mesh nodes + if (fmheader.num_mesh_nodes) + { + H_printf("\n"); + H_printf("#define NUM_MESH_NODES\t\t%d\n\n",fmheader.num_mesh_nodes); + for(i=0;iindex_xyz[(startv)%3]; + strip_xyz[1] = last->index_xyz[(startv+1)%3]; + strip_xyz[2] = last->index_xyz[(startv+2)%3]; + strip_st[0] = last->index_st[(startv)%3]; + strip_st[1] = last->index_st[(startv+1)%3]; + strip_st[2] = last->index_st[(startv+2)%3]; + + strip_tris[0] = starttri; + stripcount = 1; + + m1 = last->index_xyz[(startv+2)%3]; + st1 = last->index_st[(startv+2)%3]; + m2 = last->index_xyz[(startv+1)%3]; + st2 = last->index_st[(startv+1)%3]; + + // look for a matching triangle +nexttri: + for (j=starttri+1, check=&triangles[starttri+1] + ; j> 3; + bit = 1 << (j & 7 ); + if (!(pmnodes[node].tris[pos] & bit)) + { + continue; + } + for (k=0 ; k<3 ; k++) + { + if (check->index_xyz[k] != m1) + continue; + if (check->index_st[k] != st1) + continue; + if (check->index_xyz[ (k+1)%3 ] != m2) + continue; + if (check->index_st[ (k+1)%3 ] != st2) + continue; + + // this is the next part of the fan + + // if we can't use this triangle, this tristrip is done + if (used[j] || translucent[j] != translucent[starttri]) + goto done; + + // the new edge + if (stripcount & 1) + { + m2 = check->index_xyz[ (k+2)%3 ]; + st2 = check->index_st[ (k+2)%3 ]; + } + else + { + m1 = check->index_xyz[ (k+2)%3 ]; + st1 = check->index_st[ (k+2)%3 ]; + } + + strip_xyz[stripcount+2] = check->index_xyz[ (k+2)%3 ]; + strip_st[stripcount+2] = check->index_st[ (k+2)%3 ]; + strip_tris[stripcount] = j; + stripcount++; + + used[j] = 2; + goto nexttri; + } + } +done: + + // clear the temp used flags + for (j=starttri+1 ; jindex_xyz[(startv)%3]; + strip_xyz[1] = last->index_xyz[(startv+1)%3]; + strip_xyz[2] = last->index_xyz[(startv+2)%3]; + strip_st[0] = last->index_st[(startv)%3]; + strip_st[1] = last->index_st[(startv+1)%3]; + strip_st[2] = last->index_st[(startv+2)%3]; + + strip_tris[0] = starttri; + stripcount = 1; + + m1 = last->index_xyz[(startv+0)%3]; + st1 = last->index_st[(startv+0)%3]; + m2 = last->index_xyz[(startv+2)%3]; + st2 = last->index_st[(startv+2)%3]; + + + // look for a matching triangle +nexttri: + for (j=starttri+1, check=&triangles[starttri+1] + ; j> 3; + bit = 1 << (j & 7 ); + if (!(pmnodes[node].tris[pos] & bit)) + { + continue; + } + for (k=0 ; k<3 ; k++) + { + if (check->index_xyz[k] != m1) + continue; + if (check->index_st[k] != st1) + continue; + if (check->index_xyz[ (k+1)%3 ] != m2) + continue; + if (check->index_st[ (k+1)%3 ] != st2) + continue; + + // this is the next part of the fan + + // if we can't use this triangle, this tristrip is done + if (used[j] || translucent[j] != translucent[starttri]) + goto done; + + // the new edge + m2 = check->index_xyz[ (k+2)%3 ]; + st2 = check->index_st[ (k+2)%3 ]; + + strip_xyz[stripcount+2] = m2; + strip_st[stripcount+2] = st2; + strip_tris[stripcount] = j; + stripcount++; + + used[j] = 2; + goto nexttri; + } + } +done: + + // clear the temp used flags + for (j=starttri+1 ; j> 3; + bit = 1 << (i & 7 ); + if (!(pmnodes[l].tris[pos] & bit)) + { + continue; + } + + // pick an unused triangle and start the trifan + if (used[i] || trans_check != translucent[i]) + { + continue; + } + + bestlen = 0; + for (type = 0 ; type < 2 ; type++) + // type = 1; + { + for (startv =0 ; startv < 3 ; startv++) + { + if (type == 1) + len = StripLength (i, startv, fmheader.num_tris, l); + else + len = FanLength (i, startv, fmheader.num_tris, l); + if (len > bestlen) + { + besttype = type; + bestlen = len; + for (j=0 ; j + "-------------------------", // ? + "-------------------------", // @ + "-***-*---*******---**---*", // A + "****-*---*****-*---*****-", + "-*****----*----*-----****", + "****-*---**---**---*****-", + "******----****-*----*****", + "******----****-*----*----", + "-*****----*--***---*-****", + "*---**---*******---**---*", + "-***---*----*----*---***-", + "----*----*----**---*-***-", + "-*--*-*-*--**---*-*--*--*", + "-*----*----*----*----****", + "*---***-***-*-**---**---*", + "*---***--**-*-**--***---*", + "-***-*---**---**---*-***-", + "****-*---*****-*----*----", + "-***-*---**---*-***----**", + "****-*---*****-*-*--*--**", + "-*****-----***-----*****-", + "*****--*----*----*----*--", + "*---**---**---**---******", + "*---**---**---*-*-*---*--", + "*---**---**-*-***-***---*", + "*---*-*-*---*---*-*-*---*", + "*---**---*-*-*---*----*--", + "*****---*---*---*---*****" // Z +}; + +void DrawLine(int x1, int y1, int x2, int y2) +{ + int dx, dy; + int adx, ady; + int count; + float xfrac, yfrac, xstep, ystep; + unsigned sx, sy; + float u, v; + + dx = x2 - x1; + dy = y2 - y1; + adx = abs(dx); + ady = abs(dy); + + count = adx > ady ? adx : ady; + count++; + + if(count > 300) + { + printf("Bad count\n"); + return; // don't ever hang up on bad data + } + + xfrac = x1; + yfrac = y1; + + xstep = (float)dx/count; + ystep = (float)dy/count; + + switch(LineType) + { + case LINE_NORMAL: + do + { + if(xfrac < SKINPAGE_WIDTH && yfrac < SKINPAGE_HEIGHT) + { + pic[(int)yfrac*SKINPAGE_WIDTH+(int)xfrac] = LineColor; + } + xfrac += xstep; + yfrac += ystep; + count--; + } while (count > 0); + break; + case LINE_FAT: + do + { + for (u=-0.1 ; u<=0.9 ; u+=0.999) + { + for (v=-0.1 ; v<=0.9 ; v+=0.999) + { + sx = xfrac+u; + sy = yfrac+v; + if(sx < SKINPAGE_WIDTH && sy < SKINPAGE_HEIGHT) + { + pic[sy*SKINPAGE_WIDTH+sx] = LineColor; + } + } + } + xfrac += xstep; + yfrac += ystep; + count--; + } while (count > 0); + break; + case LINE_DOTTED: + do + { + if(count&1 && xfrac < SKINPAGE_WIDTH && + yfrac < SKINPAGE_HEIGHT) + { + pic[(int)yfrac*SKINPAGE_WIDTH+(int)xfrac] = LineColor; + } + xfrac += xstep; + yfrac += ystep; + count--; + } while (count > 0); + break; + default: + Error("Unknown %d.\n", LineType); + } +} + +//========================================================================== +// +// DrawCharacter +// +//========================================================================== + +static void DrawCharacter(int x, int y, int character) +{ + int r, c; + char *def; + + character = toupper(character); + if(character < ASCII_SPACE || character > 'Z') + { + character = ASCII_SPACE; + } + character -= ASCII_SPACE; + for(def = CharDefs[character], r = 0; r < 5; r++) + { + for(c = 0; c < 5; c++) + { + pic[(y+r)*SKINPAGE_WIDTH+x+c] = *def++ == '*' ? 255 : 0; + } + } +} + +//========================================================================== +// +// DrawTextChar +// +//========================================================================== + +void DrawTextChar(int x, int y, char *text) +{ + int c; + + while((c = *text++) != '\0') + { + DrawCharacter(x, y, c); + x += 6; + } +} + + +extern void DrawScreen(float s_scale, float t_scale, float iwidth, float iheight); + +//========================================================================== +// ExtractDigit + +static int ExtractDigit(byte *pic, int x, int y) +{ + int i; + int r, c; + char digString[32]; + char *buffer; + byte backColor; + char **DigitDefs; + + backColor = pic[(SKINPAGE_HEIGHT - 1) * SKINPAGE_WIDTH]; + DigitDefs = &CharDefs['0' - ASCII_SPACE]; + + buffer = digString; + for(r = 0; r < 5; r++) + { + for(c = 0; c < 5; c++) + { + *buffer++ = (pic[(y + r) * SKINPAGE_WIDTH + x + c] == backColor) ? ' ' : '*'; + } + } + *buffer = '\0'; + for(i = 0; i < 10; i++) + { + if(strcmp(DigitDefs[i], digString) == 0) + { + return i; + } + } + + Error("Unable to extract scaling info from skin PCX."); + return 0; +} + +//========================================================================== +// ExtractNumber + +int ExtractNumber(byte *pic, int x, int y) +{ + return ExtractDigit(pic, x, y) * 100 + ExtractDigit(pic, x + 6, y) * 10 + ExtractDigit(pic, x + 12, y); +} + + + + + +/* +============ +BuildST + +Builds the triangle_st array for the base frame and +fmheader.skinwidth / fmheader.skinheight + + FIXME: allow this to be loaded from a file for + arbitrary mappings +============ +*/ +static void BuildST (triangle_t *ptri, int numtri, qboolean DrawSkin) +{ + int backface_flag; + int i, j; + int width, height, iwidth, iheight, swidth; + float basex, basey; + float scale; + vec3_t mins, maxs; + float *pbasevert; + vec3_t vtemp1, vtemp2, normal; + float s_scale, t_scale; + float scWidth; + float scHeight; + int skinwidth; + int skinheight; + + // + // find bounds of all the verts on the base frame + // + ClearBounds (mins, maxs); + backface_flag = false; + + if (ptri[0].HasUV) // if we have the uv already, we don't want to double up or scale + { + iwidth = ScaleWidth; + iheight = ScaleHeight; + + t_scale = s_scale = 1.0; + } + else + { + for (i=0 ; i 0) + { + backface_flag = true; + break; + } + } + scWidth = ScaleWidth*SCALE_ADJUST_FACTOR; + if (backface_flag) //we are doubling + scWidth /= 2; + + scHeight = ScaleHeight*SCALE_ADJUST_FACTOR; + + scale = scWidth/width; + + if(height*scale >= scHeight) + { + scale = scHeight/height; + } + + iwidth = ceil(width*scale)+4; + iheight = ceil(height*scale)+4; + + s_scale = (float)(iwidth-4) / width; + t_scale = (float)(iheight-4) / height; + t_scale = s_scale; + } + if (DrawSkin) + { + if(backface_flag) + DrawScreen(s_scale, t_scale, iwidth*2, iheight); + else + DrawScreen(s_scale, t_scale, iwidth, iheight); + } + if (backface_flag) + skinwidth=iwidth*2; + else + skinwidth=iwidth; + skinheight=iheight; + + +/* if (!g_fixedwidth) + { // old style + scale = 8; + if (width*scale >= 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_fixedwidth / 2; + iheight = g_fixedheight; + + s_scale = (float)(iwidth-4) / width; + t_scale = (float)(iheight-4) / height; + }*/ + +// +// determine which side of each triangle to map the texture to +// + basey = 2; + for (i=0 ; i 0) + { + basex = iwidth + 2; + } + else + { + basex = 2; + } + + for (j=0 ; j<3 ; j++) + { + pbasevert = ptri[i].verts[j]; + + triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); + triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); + } + } + + if (DrawSkin) + { + DrawLine(triangle_st[i][0][0], triangle_st[i][0][1], + triangle_st[i][1][0], triangle_st[i][1][1]); + DrawLine(triangle_st[i][1][0], triangle_st[i][1][1], + triangle_st[i][2][0], triangle_st[i][2][1]); + DrawLine(triangle_st[i][2][0], triangle_st[i][2][1], + triangle_st[i][0][0], triangle_st[i][0][1]); + } + } + +// make the width a multiple of 4; some hardware requires this, and it ensures +// dword alignment for each scan + + swidth = iwidth; + if(backface_flag) + swidth *= 2; + fmheader.skinwidth = (swidth + 3) & ~3; + fmheader.skinheight = iheight; + + skin_width = iwidth; + skin_height = iheight; +} + + +static void BuildNewST (triangle_t *ptri, int numtri, qboolean DrawSkin) +{ + int i, j; + + for (i=0 ; i 1) + goto split; + d = lp2[1] - lp1[1]; + if (d < -1 || d > 1) + goto split; + + d = lp3[0] - lp2[0]; + if (d < -1 || d > 1) + goto split2; + d = lp3[1] - lp2[1]; + if (d < -1 || d > 1) + goto split2; + + d = lp1[0] - lp3[0]; + if (d < -1 || d > 1) + goto split3; + d = lp1[1] - lp3[1]; + if (d < -1 || d > 1) + { +split3: + temp = lp1; + lp1 = lp3; + lp3 = lp2; + lp2 = temp; + + goto split; + } + + return 0; // entire tri is filled + +split2: + temp = lp1; + lp1 = lp2; + lp2 = lp3; + lp3 = temp; + +split: +// split this edge + new[0] = (lp1[0] + lp2[0]) >> 1; + new[1] = (lp1[1] + lp2[1]) >> 1; + +// draw the point if splitting a leading edge + if (lp2[1] > lp1[1]) + goto nodraw; + if ((lp2[1] == lp1[1]) && (lp2[0] < lp1[0])) + goto nodraw; + + if (SetPixel) + { + assert ((new[1]*BaseWidth) + new[0] < BaseWidth*BaseHeight); + + if (BaseTrueColor) + { + BasePixels[((new[1]*BaseWidth) + new[0]) * 4] = 1; + } + else + { + BasePixels[(new[1]*BaseWidth) + new[0]] = 1; + } + } + else + { + if (TransPixels) + { + if (TransPixels[(new[1]*TransWidth) + new[0]] != 255) + return 1; + } + else if (BaseTrueColor) + { + if (BasePixels[(((new[1]*BaseWidth) + new[0]) * 4) + 3] != 255) + return 1; + } + else + { +// pixel = BasePixels[(new[1]*BaseWidth) + new[0]]; + } + } + +nodraw: +// recursively continue + if (CheckTransRecursiveTri(lp3, lp1, new)) + return 1; + + return CheckTransRecursiveTri(lp3, new, lp2); +} + +static void ReplaceClusterIndex(int newIndex, int oldindex, int **clusters, + IntListNode_t **vertLists, int *num_verts, int *new_num_verts) +{ + int i, j; + IntListNode_t *next; + + for(j = 0; j < numJointsInSkeleton[g_skelModel.type]; ++j) + { + if(!clusters[j]) + { + continue; + } + + for(i = 0; i < num_verts[j+1]; ++i) + { + if(clusters[j][i] == oldindex) + { + ++new_num_verts[j+1]; + + next = vertLists[j]; + + vertLists[j] = (IntListNode_t *) SafeMalloc(sizeof(IntListNode_t), "ReplaceClusterIndex"); + // Currently freed in WriteJointedModelFile only + + vertLists[j]->data = newIndex; + vertLists[j]->next = next; + } + } + } +} + +#define FUDGE_EPSILON 0.002 + +qboolean VectorFudgeCompare (vec3_t v1, vec3_t v2) +{ + int i; + + for (i=0 ; i<3 ; i++) + if (fabs(v1[i]-v2[i]) > FUDGE_EPSILON) + return false; + + return true; +} + +/* +================= +Cmd_Base +================= +*/ +void Cmd_FMBase (qboolean GetST) +{ + triangle_t *ptri, *st_tri; + int num_st_tris; + int i, j, k, l; + int x,y,z; +// int time1; + char file1[1024],file2[1024],trans_file[1024], stfile[1024], extension[256]; + vec3_t base_xyz[MAX_FM_VERTS]; + FILE *FH; + int pos,bit; + qboolean NewSkin; + + GetScriptToken (false); + + if (g_skipmodel || g_release || g_archive) + return; + + printf ("---------------------\n"); + sprintf (file1, "%s/%s.%s", cdarchive, token, trifileext); + printf ("%s ", file1); + + ExpandPathAndArchive (file1); + + // Use the input filepath for this one. + sprintf (file1, "%s/%s", cddir, token); + +// time1 = FileTime (file1); +// if (time1 == -1) +// Error ("%s doesn't exist", file1); + +// +// load the base triangles +// + if (do3ds) + Load3DSTriangleList (file1, &ptri, &fmheader.num_tris, &pmnodes, &fmheader.num_mesh_nodes); + else + LoadTriangleList (file1, &ptri, &fmheader.num_tris, &pmnodes, &fmheader.num_mesh_nodes); + + if (g_ignoreTriUV) + { + for (i=0;i> 3; + bit = 1 << (i & 7 ); + if (!(pmnodes[l].tris[pos] & bit)) + { + continue; + } + + for (j=0 ; j<3 ; j++) + { + // get the xyz index + for (k=0 ; k> 3; + bit = 1 << (k & 7); + pmnodes[l].verts[pos] |= bit; + + triangles[i].index_xyz[j] = k; + + // get the st index + for (k=0 ; k= fmheader.num_mesh_nodes) + { + Error("Node '%s' not in base list!\n", token); + } + } + + free(pmnodes); + pmnodes = newnodes; +} + +//=============================================================== + +extern char *FindFrameFile (char *frame); + + +/* +=============== +GrabFrame +=============== +*/ +void GrabFrame (char *frame) +{ + triangle_t *ptri; + int i, j; + fmtrivert_t *ptrivert; + int num_tris; + char file1[1024]; + fmframe_t *fr; + int index_xyz; + char *framefile; + + // the frame 'run1' will be looked for as either + // run.1 or run1.tri, so the new alias sequence save + // feature an be used + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + + printf ("grabbing %s ", file1); + + if (fmheader.num_frames >= MAX_FM_FRAMES) + Error ("fmheader.num_frames >= MAX_FM_FRAMES"); + fr = &g_frames[fmheader.num_frames]; + fmheader.num_frames++; + + strcpy (fr->name, frame); + +// +// load the frame +// + if (do3ds) + Load3DSTriangleList (file1, &ptri, &num_tris, NULL, NULL); + else + LoadTriangleList (file1, &ptri, &num_tris, NULL, NULL); + + if (num_tris != fmheader.num_tris) + Error ("%s: number of triangles (%d) doesn't match base frame (%d)\n", file1, num_tris, fmheader.num_tris); + +// +// allocate storage for the frame's vertices +// + ptrivert = fr->v; + + for (i=0 ; imins, fr->maxs); + +// +// 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 ; imins, fr->maxs); + + VectorAdd (ptrivert[index_xyz].vnorm.normalsum, normal, ptrivert[index_xyz].vnorm.normalsum); + ptrivert[index_xyz].vnorm.numnormals++; + } + } + +// +// calculate the vertex normals, match them to the template list, and store the +// index of the best match +// + for (i=0 ; i maxdot) + { + maxdot = dot; + maxdotindex = j; + } + } + + ptrivert[i].lightnormalindex = maxdotindex; + } + + free (ptri); +} + +/* +=============== +Cmd_Frame +=============== +*/ +void Cmd_FMFrame (void) +{ + while (ScriptTokenAvailable()) + { + GetScriptToken (false); + if (g_skipmodel) + continue; + if (g_release || g_archive) + { + fmheader.num_frames = 1; // don't skip the writeout + continue; + } + + H_printf("#define FRAME_%-16s\t%i\n", token, fmheader.num_frames); + + if((g_skelModel.type != SKEL_NULL) || (g_skelModel.references != REF_NULL)) + { + GrabModelTransform(token); + } + + GrabFrame (token); + + if(g_skelModel.type != SKEL_NULL) + { + GrabSkeletalFrame(token); + } + + if(g_skelModel.references != REF_NULL) + { + GrabReferencedFrame(token); + } + + // need to add the up and dir points to the frame bounds here + // using AddPointToBounds (ptrivert[index_xyz].v, fr->mins, fr->maxs); + // then remove fudge in determining scale on frame write out + } +} + +/* +=============== +Cmd_Skin + +Skins aren't actually stored in the file, only a reference +is saved out to the header file. +=============== +*/ +void Cmd_FMSkin (void) +{ + byte *palette; + byte *pixels; + int width, height; + byte *cropped; + int y; + char name[1024], savename[1024], transname[1024], extension[256]; + miptex32_t *qtex32; + int size; + FILE *FH; + qboolean TrueColor; + + GetScriptToken (false); + + if (fmheader.num_skins == MAX_FM_SKINS) + Error ("fmheader.num_skins == MAX_FM_SKINS"); + + if (g_skipmodel) + return; + + sprintf (name, "%s/%s", cdarchive, token); + strcpy (name, ExpandPathAndArchive( name ) ); +// sprintf (name, "%s/%s.lbm", cddir, token); + + if (ScriptTokenAvailable()) + { + GetScriptToken (false); + sprintf (g_skins[fmheader.num_skins], "!%s", token); + sprintf (savename, "%s!%s", g_outputDir, token); + sprintf (transname, "%s!%s_a.pcx", gamedir, token); + } + else + { + sprintf (g_skins[fmheader.num_skins], "%s/!%s", cdpartial, token); + sprintf (savename, "%s/!%s", g_outputDir, token); + sprintf (transname, "%s/!%s_a.pcx", cddir, token); + } + + fmheader.num_skins++; + + if (g_skipmodel || g_release || g_archive) + return; + + // load the image + printf ("loading %s\n", name); + ExtractFileExtension (name, extension); + if (extension[0] == 0) + { + strcat(name, ".pcx"); + } + + + TrueColor = LoadAnyImage (name, &pixels, &palette, &width, &height); +// RemapZero (pixels, palette, width, height); + + // crop it to the proper size + + if (!TrueColor) + { + cropped = (byte *) SafeMalloc (fmheader.skinwidth*fmheader.skinheight, "Cmd_FMSkin"); + for (y=0 ; y= 3); +// figure out the best plane projections + DOsvdPlane ((float*)vertices, num, (float *)&n, (float *)&base); + + if (DotProduct(aveNorm,n) < 0.0f) + { + VectorScale(n, -1.0f, n); + } + VectorNormalize(n,n); + if (fabs(n[2]) < .57) + { + CrossProduct( zaxis, n, crossvect); + VectorCopy(crossvect, u); + } + else + { + CrossProduct( yaxis, n, crossvect); + VectorCopy(crossvect, u); + } + VectorNormalize(u,u); + CrossProduct( n, u, crossvect); + VectorCopy(crossvect, v); + VectorNormalize(v,v); + + num = 0; + + for ( j = 0; j < 3; j++) + { + groupMin[j] = 1e30f; + groupMax[j] = -1e30f; + } + + for ( j = 0; j < numtris; j++) + { + for ( k = 0; k < 3; k++) + { + VectorCopy(grouptris[j].verts[k],v0); + VectorSubtract(v0, base, v0); + uvw[0] = DotProduct(v0, u); + uvw[1] = DotProduct(v0, v); + uvw[2] = DotProduct(v0, n); + VectorCopy(uvw,uvs[num]); + num++; + for ( l = 0; l < 3; l++) + { + if (uvw[l] < groupMin[l]) + { + groupMin[l] = uvw[l]; + } + if (uvw[l] > groupMax[l]) + { + groupMax[l] = uvw[l]; + } + } + } + } + + xwidth = ceil(0 - groupMin[0]) + 2; // move right of origin and avoid overlap + ywidth = ceil(0 - groupMin[1]) + 2; // move "above" origin + + for ( j=0; j < numverts; j++) + { + uFinal[finalcount] = uvs[j][0] + xwidth + xbase; + vFinal[finalcount] = uvs[j][1] + ywidth; + if (uFinal[finalcount] < uvwMin[0]) + { + uvwMin[0] = uFinal[finalcount]; + } + if (uFinal[finalcount] > uvwMax[0]) + { + uvwMax[0] = uFinal[finalcount]; + } + if (vFinal[finalcount] < uvwMin[1]) + { + uvwMin[1] = vFinal[finalcount]; + } + if (vFinal[finalcount] > uvwMax[1]) + { + uvwMax[1] = vFinal[finalcount]; + } + finalcount++; + } + + fprintf(grpfile,"svdPlaned Group min: ( %f , %f )\n",groupMin[0] + xwidth + xbase, groupMin[1] + ywidth); + fprintf(grpfile,"svdPlaned Group max: ( %f , %f )\n",groupMax[0] + xwidth + xbase, groupMax[1] + ywidth); + + finalcount = finalstart; + + for ( count = 0; count < numverts; count++) + { + fprintf(grpfile,"Vertex %d: ( %f , %f , %f )\n",count,vertices[count][0],vertices[count][1],vertices[count][2]); + fprintf(grpfile,"svdPlaned: ( %f , %f )\n",uFinal[finalcount],vFinal[finalcount++]); + } + + finalstart = finalcount; + + fprintf(grpfile,"\n"); + + free(vertices); + free(uvs); + free(grouptris); + + xbase += ceil(groupMax[0] - groupMin[0]) + 2; + + } + + fprintf(grpfile,"Global Min ( %f , %f )\n",uvwMin[0],uvwMin[1]); + fprintf(grpfile,"Global Max ( %f , %f )\n",uvwMax[0],uvwMax[1]); + + + ScaleTris(uvwMin, uvwMax, width, height, uFinal, vFinal, finalcount); + + for (k = 0; k < finalcount; k++) + { + fprintf(grpfile, "scaled vertex %d: ( %f , %f )\n",k,uFinal[k],vFinal[k]); + } + + // i've got the array of vertices in uFinal and vFinal. Now I need to write them and draw lines + + datasize = width * height*sizeof(unsigned char); + newpic = (unsigned char*)SafeMalloc(datasize, "NewGen"); + memset(newpic,0,datasize); + memset(pic_palette,0,sizeof(pic_palette)); + pic_palette[767] = pic_palette[766] = pic_palette[765] = 255; + + k = 0; + while (k < finalcount) + { + NewDrawLine(uFinal[k], vFinal[k], uFinal[k+1], vFinal[k+1], newpic, width, height); + k++; + NewDrawLine(uFinal[k], vFinal[k], uFinal[k+1], vFinal[k+1], newpic, width, height); + k++; + NewDrawLine(uFinal[k], vFinal[k], uFinal[k-2], vFinal[k-2], newpic, width, height); + k++; + fprintf(grpfile, "output tri with verts %d, %d, %d", k-2, k-1, k); + } + + WritePCXfile (OutputName, newpic, width, height, pic_palette); + + fclose(grpfile); + + free(todo); + free(done); + free(triangles); + free(newpic); + return; +} +void NewDrawLine(int x1, int y1, int x2, int y2, unsigned char* picture, int width, int height) +{ + long dx, dy; + long adx, ady; + long count; + float xfrac, yfrac, xstep, ystep; + unsigned long sx, sy; + float u, v; + + dx = x2 - x1; + dy = y2 - y1; + adx = abs(dx); + ady = abs(dy); + + count = adx > ady ? adx : ady; + count++; + + if(count > 300) + { + printf("Bad count\n"); + return; // don't ever hang up on bad data + } + + xfrac = x1; + yfrac = y1; + + xstep = (float)dx/count; + ystep = (float)dy/count; + + switch(LineType) + { + case LINE_NORMAL: + do + { + if(xfrac < width && yfrac < height) + { + picture[(long)yfrac*width+(long)xfrac] = LineColor; + } + xfrac += xstep; + yfrac += ystep; + count--; + } while (count > 0); + break; + case LINE_FAT: + do + { + for (u=-0.1 ; u<=0.9 ; u+=0.999) + { + for (v=-0.1 ; v<=0.9 ; v+=0.999) + { + sx = xfrac+u; + sy = yfrac+v; + if(sx < width && sy < height) + { + picture[sy*width+sx] = LineColor; + } + } + } + xfrac += xstep; + yfrac += ystep; + count--; + } while (count > 0); + break; + case LINE_DOTTED: + do + { + if(count&1 && xfrac < width && + yfrac < height) + { + picture[(long)yfrac*width+(long)xfrac] = LineColor; + } + xfrac += xstep; + yfrac += ystep; + count--; + } while (count > 0); + break; + default: + Error("Unknown %d.\n", LineType); + } +} +*/ +void ScaleTris( vec3_t min, vec3_t max, int Width, int Height, float* u, float* v, int verts) +{ + + int i; + float hscale, vscale; + float scale; + + hscale = max[0]; + vscale = max[1]; + + hscale = (Width-2) / max[0]; + vscale = (Height-2) / max[1]; + + scale = hscale; + if (scale > vscale) + { + scale = vscale; + } + for ( i = 0; i 32) + { + Error ("Degrees of freedom out of range: %d",groups[num_groups].degrees); + } +} + +void Cmd_FMEndGroup (void) +{ + groups[num_groups].num_frames = fmheader.num_frames - groups[num_groups].start_frame; + + if(num_groups < MAX_GROUPS - 1) + { + num_groups++; + } + else + { + Error("Number of compression groups exceded: %i\n", MAX_GROUPS); + } +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/icon1.ico b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/icon1.ico new file mode 100644 index 00000000..8f441941 Binary files /dev/null and b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/icon1.ico differ diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/images.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/images.c new file mode 100644 index 00000000..49f5cd27 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/images.c @@ -0,0 +1,1397 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" + +#ifdef _WIN32 + #include +#endif + +#include + +#if 1 + extern char *g_outputDir; +#endif // _QDATA + +char mip_prefix[1024]; // directory to dump the textures in + +qboolean colormap_issued; +byte colormap_palette[768]; + +unsigned total_x = 0; +unsigned total_y = 0; +unsigned total_textures = 0; + +#define MAX_IMAGE_SIZE 512 + +#if 0 +/* +============== +RemapZero + +Replaces all 0 bytes in an image with the closest palette entry. +This is because NT won't let us change index 0, so any palette +animation leaves those pixels untouched. +============== +*/ +void RemapZero (byte *pixels, byte *palette, int width, int height) +{ + int i, c; + int alt_zero; + int value, best; + + alt_zero = 0; + best = 9999999; + for (i=1 ; i<255 ; i++) + { + value = palette[i*3+0]+palette[i*3+1]+palette[i*3+2]; + if (value < best) + { + best = value; + alt_zero = i; + } + } + + c = width*height; + for (i=0 ; i> 16; + palette_g[i] = (palette[i] & 0x0000ff00) >> 8; + palette_b[i] = (palette[i] & 0x000000ff); + } + + for(i=0;i biggest_delta) + continue; + dg = abs(palette_g[i] - g); + if (dg > biggest_delta) + continue; + db = abs(palette_b[i] - b); + if (db > biggest_delta) + continue; + + dist = dr * dr + dg * dg + db * db; + if (dist < min_dist) + { + min_dist = dist; + min_index = i; + if (min_dist == 0) break; + + dist = dr; + if (dg > dist) dist = dg; + if (db > dist) dist = db; + if (dist < biggest_delta) + biggest_delta = dist; + } + } + + last_place++; + if (last_place >= MAX_LAST) + last_place = 0; + + last_r[last_place] = r; + last_g[last_place] = g; + last_b[last_place] = b; + last_i[last_place] = min_index; + + return min_index; +} + + +void GL_ResampleTexture8P (byte *in, int inwidth, int inheight, byte *out, + int outwidth, int outheight, palette_t *palette) +{ + int i, j; + byte *inrow, *inrow2; + unsigned frac, fracstep; + unsigned p1[1024], p2[1024], *p1p, *p2p; + palette_t *c1,*c2,*c3,*c4; + unsigned r,g,b; + + fracstep = inwidth*0x10000/outwidth; + + frac = fracstep>>2; + for (i=0 ; i>16; + frac += fracstep; + } + frac = 3*(fracstep>>2); + for (i=0 ; i>16; + frac += fracstep; + } + + cached = 0; + + for (i=0 ; ir + (unsigned)c2->r + (unsigned)c3->r + (unsigned)c4->r)>>2; + g = ((unsigned)c1->g + (unsigned)c2->g + (unsigned)c3->g + (unsigned)c4->g)>>2; + b = ((unsigned)c1->b + (unsigned)c2->b + (unsigned)c3->b + (unsigned)c4->b)>>2; + + *out++ = ConvertTrueColorToPal(r,g,b); + } + } +} + +void GL_MipMap8P(byte *out, byte *in, int width, int height, palette_t *palette) +{ + int i, j; + palette_t *c1,*c2,*c3,*c4; + unsigned r,g,b; + + cached = 0; + memset(out, 0, 256 * 256); + width <<= 1; + height <<= 1; + + for (i = 0; i < height; i += 2, in += width) + { + for (j = 0; j < width; j += 2) + { + c1 = &palette[in[0]]; + c3 = &palette[in[width]]; + in++; + c2 = &palette[in[0]]; + c4 = &palette[in[width]]; + in++; + + r = ((unsigned)c1->r + (unsigned)c2->r + (unsigned)c3->r + (unsigned)c4->r) >> 2; + g = ((unsigned)c1->g + (unsigned)c2->g + (unsigned)c3->g + (unsigned)c4->g) >> 2; + b = ((unsigned)c1->b + (unsigned)c2->b + (unsigned)c3->b + (unsigned)c4->b) >> 2; + + *out++ = ConvertTrueColorToPal(r, g, b); + } + } +} + + +miptex_t *CreateMip(byte *data, unsigned width, unsigned height, byte *palette, int *FinalSize, qboolean mip) +{ + int scaled_width, scaled_height; + int i,j,r,g,b; + byte intensitytable[256]; + byte scaled[256*256]; + byte out[256*256]; + int miplevel; + miptex_t *mp; + byte *pos; + int size; + + for (i=0 ; i<256 ; i++) + { + j = i * intensity_value; + if (j > 255) + j = 255; + intensitytable[i] = j; + } + + for (scaled_width = 1 ; scaled_width < width ; scaled_width<<=1) + ; + if (1 && scaled_width > width && 1) + scaled_width >>= 1; + for (scaled_height = 1 ; scaled_height < height ; scaled_height<<=1) + ; + if (1 && scaled_height > height && 1) + scaled_height >>= 1; + + // don't ever bother with >256 textures + if (scaled_width > 256) + scaled_width = 256; + if (scaled_height > 256) + scaled_height = 256; + + if (scaled_width < 1) + scaled_width = 1; + if (scaled_height < 1) + scaled_height = 1; + + size = sizeof(*mp) + (scaled_width*scaled_height*3); + mp = (miptex_t *)SafeMalloc(size, "CreateMip"); + memset(mp,0,size); + + mp->version = MIP_VERSION; + + for(i=j=0;i<256;i++,j+=3) + { + mp->palette[i].r = r = intensitytable[palette[j]]; + mp->palette[i].g = g = intensitytable[palette[j+1]]; + mp->palette[i].b = b = intensitytable[palette[j+2]]; + image_pal[i] = 0xff000000 | (r<<16) | (g<<8) | (b); + } + + PrepareConvert(image_pal); + + if (scaled_width == width && scaled_height == height) + { + memcpy (scaled, data, width*height); + } + else + GL_ResampleTexture8P (data, width, height, scaled, scaled_width, scaled_height, mp->palette); + + pos = (byte *)(mp + 1); + miplevel = 0; + + while ((scaled_width >= 1 || scaled_height >= 1) && (miplevel <= MIPLEVELS-1) && (!miplevel || mip)) + { + if (scaled_width < 1) + scaled_width = 1; + if (scaled_height < 1) + scaled_height = 1; + + if(miplevel > 0) + GL_MipMap8P(out, (byte *)scaled, scaled_width, scaled_height, mp->palette); + else + memcpy(out, scaled, 256 * 256); + + mp->width[miplevel] = scaled_width; + mp->height[miplevel] = scaled_height; + mp->offsets[miplevel] = pos - ((byte *)(mp)); + memcpy(pos, out, scaled_width * scaled_height); + memcpy(scaled, out, 256 * 256); + pos += scaled_width * scaled_height; + + scaled_width >>= 1; + scaled_height >>= 1; + + miplevel++; + } + + *FinalSize = pos - ((byte *)(mp)); + + return mp; +} + + +void GL_ResampleTexture (unsigned *in, int inwidth, int inheight, unsigned *out, int outwidth, int outheight) +{ + int i, j; + unsigned *inrow, *inrow2; + unsigned frac, fracstep; + unsigned p1[1024], p2[1024]; + byte *pix1, *pix2, *pix3, *pix4; + + fracstep = inwidth*0x10000/outwidth; + + frac = fracstep>>2; + for (i=0 ; i>16); + frac += fracstep; + } + frac = 3*(fracstep>>2); + for (i=0 ; i>16); + frac += fracstep; + } + + for (i=0 ; i> 1; + for (j=0 ; j>2; + ((byte *)(out+j))[1] = (pix1[1] + pix2[1] + pix3[1] + pix4[1])>>2; + ((byte *)(out+j))[2] = (pix1[2] + pix2[2] + pix3[2] + pix4[2])>>2; + ((byte *)(out+j))[3] = (pix1[3] + pix2[3] + pix3[3] + pix4[3])>>2; + } + } +} + +void GL_MipMap (byte *out, byte *in, int width, int height) +{ + int i, j; + + width <<=3; + height <<= 1; + for (i=0 ; i>2; + out[1] = (in[1] + in[5] + in[width+1] + in[width+5])>>2; + out[2] = (in[2] + in[6] + in[width+2] + in[width+6])>>2; + out[3] = (in[3] + in[7] + in[width+3] + in[width+7])>>2; + } + } +} + +miptex32_t *CreateMip32(unsigned *data, unsigned width, unsigned height, int *FinalSize, qboolean mip) +{ + int scaled_width, scaled_height; + unsigned scaled[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; + unsigned out[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; + int miplevel; + miptex32_t *mp; + byte *pos; + int size; + paletteRGBA_t *test; + + for (scaled_width = 1 ; scaled_width < width ; scaled_width<<=1) + ; + if (1 && scaled_width > width && 1) + scaled_width >>= 1; + for (scaled_height = 1 ; scaled_height < height ; scaled_height<<=1) + ; + if (1 && scaled_height > height && 1) + scaled_height >>= 1; + + // don't ever bother with >256 textures + if (scaled_width > MAX_IMAGE_SIZE) + scaled_width = MAX_IMAGE_SIZE; + if (scaled_height > MAX_IMAGE_SIZE) + scaled_height = MAX_IMAGE_SIZE; + + if (scaled_width < 1) + scaled_width = 1; + if (scaled_height < 1) + scaled_height = 1; + + size = sizeof(*mp) + (scaled_width*scaled_height*3*4); + mp = (miptex32_t *)SafeMalloc(size, "CreateMip"); + memset(mp,0,size); + + mp->version = MIP32_VERSION; + + size = width*height; + test = (paletteRGBA_t *)data; + while(size) + { + if (test->a != 255) + { + mp->flags |= LittleLong(SURF_ALPHA_TEXTURE); + break; + } + + size--; + test++; + } + + if (scaled_width == width && scaled_height == height) + { + memcpy (scaled, data, width*height*4); + } + else + GL_ResampleTexture (data, width, height, scaled, scaled_width, scaled_height); + + pos = (byte *)(mp + 1); + miplevel = 0; + + while ((scaled_width >= 1 || scaled_height >= 1) && (miplevel <= MIPLEVELS-1) && (!miplevel || mip)) + { + if (scaled_width < 1) + scaled_width = 1; + if (scaled_height < 1) + scaled_height = 1; + + if (miplevel > 0) + { + GL_MipMap((byte *)out, (byte *)scaled, scaled_width, scaled_height); + } + else + { + memcpy(out, scaled, MAX_IMAGE_SIZE * MAX_IMAGE_SIZE * 4); + } + + mp->width[miplevel] = scaled_width; + mp->height[miplevel] = scaled_height; + mp->offsets[miplevel] = pos - ((byte *)(mp)); + memcpy(pos, out, scaled_width * scaled_height * 4); + memcpy(scaled, out, MAX_IMAGE_SIZE * MAX_IMAGE_SIZE * 4); + pos += scaled_width * scaled_height * 4; + + scaled_width >>= 1; + scaled_height >>= 1; + + miplevel++; + } + + *FinalSize = pos - ((byte *)(mp)); + + return mp; +} + +/* +============== +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]; + + GetScriptToken (false); + + if (token[0] == '/' || token[0] == '\\') + sprintf (savename, "%s%s.pcx", gamedir, token+1); + else + sprintf (savename, "%spics/%s.pcx", gamedir, 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; + } + + GetScriptToken (false); + xl = atoi (token); + GetScriptToken (false); + yl = atoi (token); + GetScriptToken (false); + w = atoi (token); + GetScriptToken (false); + 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 = (byte *) SafeMalloc (w*h, "Cmd_Grab"); + for (y=0 ; ybyteimagewidth || yl+h>byteimageheight) + Error ("GrabPic: Bad size: %i, %i, %i, %i",xl,yl,w,h); + + // crop it to the proper size + cropped = (byte *) SafeMalloc (w*h, "Cmd_Raw"); + for (y=0 ; y 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 = true; + + 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 +must be multiples of sixteen +SURF_WINDOW +============== +*/ + +void Cmd_Mip (void) +{ + int xl,yl,xh,yh,w,h; + byte *dest, *source; + int flags, value, contents; + mipparm_t *mp; + char lumpname[128]; + char altname[128]; + char animname[128]; + char damagename[128]; + byte buffer[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; + unsigned bufferl[MAX_IMAGE_SIZE*MAX_IMAGE_SIZE]; + materialtype_t *mat; + char filename[1024]; + unsigned *destl, *sourcel; + int linedelta, x, y; + int size; + miptex_t *qtex; + miptex32_t *qtex32; + float scale_x, scale_y; + int mip_scale; + // detail texturing + char dt_name[128]; + float dt_scale_x, dt_scale_y; + float dt_u, dt_v; + float dt_alpha; + int dt_src_blend_mode, dt_dst_blend_mode; + int flags2; + + + GetScriptToken (false); + strcpy (lumpname, token); + + GetScriptToken (false); + xl = atoi (token); + GetScriptToken (false); + yl = atoi (token); + GetScriptToken (false); + w = atoi (token); + GetScriptToken (false); + h = atoi (token); + + total_x += w; + total_y += h; + total_textures++; + + if ( (w & 15) || (h & 15) ) + Error ("line %i: miptex sizes must be multiples of 16", scriptline); + + flags = 0; + flags2 = 0; + contents = 0; + value = 0; + mip_scale = 0; + + altname[0] = animname[0] = damagename[0] = 0; + + scale_x = scale_y = 0.5; + + // detail texturing + dt_name[0] = 0; + dt_scale_x = dt_scale_y = 0.0; + dt_u = dt_v = 0.0; + dt_alpha = 0.0; + dt_src_blend_mode = dt_dst_blend_mode = 0; + + // get optional flags and values + while (ScriptTokenAvailable ()) + { + GetScriptToken (false); + + for (mp=mipparms ; mp->name ; mp++) + { + if (!strcmp(mp->name, token)) + { + switch (mp->type) + { + case pt_animvalue: + GetScriptToken (false); // specify the next animation frame + strcpy (animname, token); + break; + case pt_altnamevalue: + GetScriptToken (false); // specify the alternate texture + strcpy (altname, token); + break; + case pt_damagenamevalue: + GetScriptToken (false); // specify the damage texture + strcpy (damagename, token); + break; + case pt_flags: + flags |= mp->flags; + break; + case pt_contents: + contents |= mp->flags; + break; + case pt_flagvalue: + flags |= mp->flags; + GetScriptToken (false); // specify the light value + value = atoi(token); + break; + case pt_materialvalue: + GetScriptToken(false); + for (mat=materialtypes ; mat->name ; mat++) + { + if (!strcmp(mat->name, token)) + { + // assumes SURF_MATERIAL is in top 8 bits + flags = (flags & 0x0FFFFFF) | (mat->value << 24); + break; + } + } + break; + case pt_scale: + GetScriptToken (false); // specify the x scale + scale_x = atof(token); + GetScriptToken (false); // specify the y scale + scale_y = atof(token); + break; + + case pt_mip: + mip_scale = 1; + break; + + case pt_detailer: + flags2 |= MIP32_DETAILER_FLAG2; + break; + + case pt_nomip: + flags2 |= MIP32_NOMIP_FLAG2; + break; + + case pt_detail: + GetScriptToken(false); + strcpy(dt_name, token); + GetScriptToken(false); + dt_scale_x = atof(token); + GetScriptToken(false); + dt_scale_y = atof(token); + GetScriptToken(false); + dt_u = atof(token); + GetScriptToken(false); + dt_v = atof(token); + GetScriptToken(false); + dt_alpha = atof(token); + GetScriptToken(false); + for (mp=mipparms ; mp->name ; mp++) + { + if (!strcmp(mp->name, token)) + { + if (mp->type == pt_gl) + { + dt_src_blend_mode = mp->flags; + break; + } + } + } + if (!mp->name) + { + Error ("line %i: invalid gl blend mode %s", scriptline, token); + } + GetScriptToken (false); + for (mp=mipparms ; mp->name ; mp++) + { + if (!strcmp(mp->name, token)) + { + if (mp->type == pt_gl) + { + dt_dst_blend_mode = mp->flags; + break; + } + } + } + if (!mp->name) + { + Error ("line %i: invalid gl blend mode %s", scriptline, token); + } + break; + } + break; + } + } + if (!mp->name) + Error ("line %i: unknown parm %s", scriptline, token); + } + + if (g_release) + return; // textures are only released by $maps + + xh = xl+w; + yh = yl+h; + if (xh*yh > MAX_IMAGE_SIZE*MAX_IMAGE_SIZE) + { + Error("line %i image %s: image is too big!", scriptline, lumpname); + } + + if (TrueColorImage) + { + if (xl >= longimagewidth || xh > longimagewidth || + yl >= longimageheight || yh > longimageheight) + { + Error ("line %i image %s: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, lumpname, xl,yl,w,h,longimagewidth,longimageheight); + } + + sourcel = longimage + (yl*longimagewidth) + xl; + destl = bufferl; + linedelta = (longimagewidth - w); + + for (y=yl ; yflags |= LittleLong(flags); + qtex32->flags2 |= LittleLong(flags2); + qtex32->contents = LittleLong(contents); + qtex32->value = LittleLong(value); + qtex32->scale_x = scale_x; + qtex32->scale_y = scale_y; + qtex32->mip_scale = mip_scale; + sprintf (qtex32->name, "%s/%s", mip_prefix, lumpname); + if (animname[0]) + { + sprintf (qtex32->animname, "%s/%s", mip_prefix, animname); + } + if (altname[0]) + { + sprintf (qtex32->altname, "%s/%s", mip_prefix, altname); + } + if (damagename[0]) + { + sprintf (qtex32->damagename, "%s/%s", mip_prefix, damagename); + } + if (dt_name[0] & ((flags2 & MIP32_DETAILER_FLAG2) == 0)) + { + sprintf (qtex32->dt_name, "%s/%s", mip_prefix, dt_name); + qtex32->dt_scale_x = dt_scale_x; + qtex32->dt_scale_y = dt_scale_y; + qtex32->dt_u = dt_u; + qtex32->dt_v = dt_v; + qtex32->dt_alpha = dt_alpha; + qtex32->dt_src_blend_mode = dt_src_blend_mode; + qtex32->dt_dst_blend_mode = dt_dst_blend_mode; + } + + // + // write it out + // + sprintf (filename, "%stextures/%s/%s.m32", g_outputDir, mip_prefix, lumpname); + if(qtex32->flags & (SURF_ALPHA_TEXTURE)) + printf ("writing %s with ALPHA\n", filename); + else + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex32, size); + + free (qtex32); + } + else + { + if (xl >= byteimagewidth || xh > byteimagewidth || + yl >= byteimageheight || yh > byteimageheight) + { + Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); + } + + source = byteimage + yl*byteimagewidth + xl; + dest = buffer; + linedelta = byteimagewidth - w; + + for (y=yl ; yflags = LittleLong(flags); + qtex->contents = LittleLong(contents); + qtex->value = LittleLong(value); + sprintf (qtex->name, "%s/%s", mip_prefix, lumpname); + if (animname[0]) + sprintf (qtex->animname, "%s/%s", mip_prefix, animname); + + // + // write it out + // + sprintf (filename, "%stextures/%s/%s.m8", g_outputDir, mip_prefix, lumpname); + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex, size); + + free (qtex); + } +} + +/* +=============== +Cmd_Mippal +=============== +*/ +void Cmd_Mippal (void) +{ + colormap_issued = true; + if (g_release) + return; + + memcpy (colormap_palette, lbmpalette, 768); + + BuildPalmap(); +} + + +/* +=============== +Cmd_Mipdir +=============== +*/ +void Cmd_Mipdir (void) +{ + char filename[1024]; + + GetScriptToken (false); + strcpy (mip_prefix, token); + // create the directory if needed + sprintf (filename, "%stextures", g_outputDir); + Q_mkdir (filename); + sprintf (filename, "%stextures/%s", g_outputDir, mip_prefix); + Q_mkdir (filename); +} + + +/* +============================================================================= + +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; + + GetScriptToken (false); + + 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", gamedir, 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/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/jointed.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/jointed.c new file mode 100644 index 00000000..4d78a792 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/jointed.c @@ -0,0 +1,572 @@ +/* +Copyright (C) 1999-2006 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 +#include "token.h" +#include "joints.h" +#include "angles.h" +#include "inout.h" + +char *SKEL_ROOT_NAMES[] = +{ + "RAVEN_SPINE" +}; + +char *SKEL_NAMES[] = +{ + "RAVEN_WAIST1", + "RAVEN_WAIST2", + "RAVEN_NECK" +}; + +int NAME_OFFSETS[] = +{ + 0 +}; + +int numJointsForSkeleton[] = +{ + NUM_JOINTS_RAVEN, + NUM_JOINTS_BOX +}; + +float g_scaling[3]; +float g_rotation[3]; +float g_translation[3]; + +//========================================================================== +// +// LoadHRCClustered +// +//========================================================================== + +static void LoadHRCClustered(char *fileName, int **clusterList, int *num_verts, int skelType) +{ + int i, j; + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + + TK_Beyond(TK_CLUSTERS); + + while(TK_Search(TK_CLUSTER_NAME) != TK_EOF) + { + TK_Require(TK_STRING); + + for( i = 0; i < numJointsForSkeleton[skelType]; ++i) + { + if(stricmp(tk_String, SKEL_NAMES[NAME_OFFSETS[skelType]+i]) == 0) + { + i = -i + numJointsForSkeleton[skelType] - 1; + + TK_BeyondRequire(TK_NUM_CLUSTER_VERTICES, TK_INTNUMBER); + + num_verts[i+1] = tk_IntNumber; + + clusterList[i] = (int *) SafeMalloc(num_verts[i+1]*sizeof(int), "LoadHRCClustered"); + assert(clusterList[i]); + // currently this function is only called by LoadTriangleListClustered, which in turn is only + // called by Cmd_Base in qdata. This is where the only call to free for this memory is being made. + + TK_Beyond(TK_LBRACE); + + for(j = 0; j < num_verts[i+1]; ++j) + { + TK_Require(TK_INTNUMBER); + clusterList[i][j] = tk_IntNumber; + TK_Fetch(); + } + + break; + } + } + } + + num_verts[0] = numJointsForSkeleton[skelType]; +} + +static void LoadHRCGlobals(char *fileName) +{ + int i; + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + TK_Beyond(TK_MODEL); + + TK_Beyond(TK_SCALING); + for(i = 0; i < 3; i++) + { + TK_Require(TK_FLOATNUMBER); + g_scaling[i] = tk_FloatNumber; + TK_Fetch(); + } + + TK_Beyond(TK_ROTATION); + for(i = 0; i < 3; i++) + { + TK_Require(TK_FLOATNUMBER); + g_rotation[i] = tk_FloatNumber; + TK_Fetch(); + } + + TK_Beyond(TK_TRANSLATION); + for(i = 0; i < 3; i++) + { + TK_Require(TK_FLOATNUMBER); + g_translation[i] = tk_FloatNumber; + TK_Fetch(); + } +} + +static void ParseVec3(vec3_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void ParseRotation3(vec3_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = -tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void ParseTranslation3(vec3_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void LoadHRCJointList(char *fileName, QDataJoint_t *jointList, int skelType) +{ +#define MAX_STACK 64 + int i, j; + vec3_t curTranslation[MAX_STACK], curRotation[MAX_STACK], curScale[MAX_STACK]; + int curCorrespondingJoint[MAX_STACK]; + int currentStack = 0, stackSize; + int baseJoint; + float cx, sx, cy, sy, cz, sz; + float rx, ry, rz; + float x2, y2, z2; + + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + + TK_Beyond(TK_MODEL); + TK_Beyond(TK_MODEL); + +/* while(1) + { + TK_Beyond(TK_MODEL); + TK_BeyondRequire(TK_NAME, TK_STRING); + + if(_stricmp(tk_String, SKEL_ROOT_NAMES[skelType]) == 0) + break; + }*/ + + TK_Beyond(TK_SCALING); + + ParseVec3(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3(curRotation[currentStack]); + + TK_Beyond(TK_TRANSLATION); + + ParseVec3(curTranslation[currentStack]); + + // account for global model translation + curTranslation[currentStack][1] += g_translation[0]; + curTranslation[currentStack][2] += g_translation[1]; + curTranslation[currentStack][0] += g_translation[2]; + + ++currentStack; + + for(i = 0; i < NUM_JOINTS_RAVEN; ++i) + { + while(1) + { + TK_Beyond(TK_MODEL); + +// TK_BeyondRequire(TK_NAME, TK_STRING); + +// if(_stricmp(tk_String, SKEL_NAMES[NAME_OFFSETS[skelType]+i]) == 0) + break; + + TK_Beyond(TK_SCALING); + + ParseVec3(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3(curRotation[currentStack]); + + TK_Beyond(TK_TRANSLATION); + + ParseVec3(curTranslation[currentStack]); + + curCorrespondingJoint[currentStack] = -1; + + ++currentStack; + } + + TK_Beyond(TK_SCALING); + + ParseVec3(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3(curRotation[currentStack]); + + jointList[i].rotation[1] = curRotation[currentStack][1]; + jointList[i].rotation[2] = curRotation[currentStack][2]; + jointList[i].rotation[0] = curRotation[currentStack][0]; + + TK_Beyond(TK_TRANSLATION); + + ParseVec3(curTranslation[currentStack]); + + jointList[i].placement.origin[1] = curTranslation[currentStack][1]; + jointList[i].placement.origin[2] = curTranslation[currentStack][2]; + jointList[i].placement.origin[0] = curTranslation[currentStack][0]; + + jointList[i].placement.direction[1] = 7.5; + jointList[i].placement.direction[2] = 0.0; + jointList[i].placement.direction[0] = 0.0; + + jointList[i].placement.up[1] = 0.0; + jointList[i].placement.up[2] = 7.5; + jointList[i].placement.up[0] = 0.0; + + curCorrespondingJoint[currentStack] = i; + + ++currentStack; + } + + stackSize = currentStack; + + for(i = 0; i < NUM_JOINTS_RAVEN; ++i) + { + rx = jointList[i].rotation[0]*ANGLE_TO_RAD; + ry = jointList[i].rotation[1]*ANGLE_TO_RAD; + rz = jointList[i].rotation[2]*ANGLE_TO_RAD; + + cx = cos(rx); + sx = sin(rx); + + cy = cos(ry); + sy = sin(ry); + + cz = cos(rz); + sz = sin(rz); + + // y-axis rotation for direction + x2 = jointList[i].placement.direction[0]*cy+jointList[i].placement.direction[2]*sy; + z2 = -jointList[i].placement.direction[0]*sy+jointList[i].placement.direction[2]*cy; + jointList[i].placement.direction[0] = x2; + jointList[i].placement.direction[2] = z2; + + // y-axis rotation for up + x2 = jointList[i].placement.up[0]*cy+jointList[i].placement.up[2]*sy; + z2 = -jointList[i].placement.up[0]*sy+jointList[i].placement.up[2]*cy; + jointList[i].placement.up[0] = x2; + jointList[i].placement.up[2] = z2; + + // z-axis rotation for direction + x2 = jointList[i].placement.direction[0]*cz-jointList[i].placement.direction[1]*sz; + y2 = jointList[i].placement.direction[0]*sz+jointList[i].placement.direction[1]*cz; + jointList[i].placement.direction[0] = x2; + jointList[i].placement.direction[1] = y2; + + // z-axis rotation for up + x2 = jointList[i].placement.up[0]*cz-jointList[i].placement.up[1]*sz; + y2 = jointList[i].placement.up[0]*sz+jointList[i].placement.up[1]*cz; + jointList[i].placement.up[0] = x2; + jointList[i].placement.up[1] = y2; + + // x-axis rotation for direction vector + y2 = jointList[i].placement.direction[1]*cx-jointList[i].placement.direction[2]*sx; + z2 = jointList[i].placement.direction[1]*sx+jointList[i].placement.direction[2]*cx; + jointList[i].placement.direction[1] = y2; + jointList[i].placement.direction[2] = z2; + + // x-axis rotation for up vector + y2 = jointList[i].placement.up[1]*cx-jointList[i].placement.up[2]*sx; + z2 = jointList[i].placement.up[1]*sx+jointList[i].placement.up[2]*cx; + jointList[i].placement.up[1] = y2; + jointList[i].placement.up[2] = z2; + + // translate to position in model + jointList[i].placement.direction[0] += jointList[i].placement.origin[0]; + jointList[i].placement.direction[1] += jointList[i].placement.origin[1]; + jointList[i].placement.direction[2] += jointList[i].placement.origin[2]; + + // translate to position in model + jointList[i].placement.up[0] += jointList[i].placement.origin[0]; + jointList[i].placement.up[1] += jointList[i].placement.origin[1]; + jointList[i].placement.up[2] += jointList[i].placement.origin[2]; + } + + baseJoint = NUM_JOINTS_RAVEN; + + for(i = stackSize/*NUM_JOINTS_RAVEN*/ - 1; i > 0; --i) + { + + rx = curRotation[i-1][0]*ANGLE_TO_RAD; + ry = curRotation[i-1][1]*ANGLE_TO_RAD; + rz = curRotation[i-1][2]*ANGLE_TO_RAD; + + cx = cos(rx); + sx = sin(rx); + + cy = cos(ry); + sy = sin(ry); + + cz = cos(rz); + sz = sin(rz); + + for(j = i-1; j < stackSize-1; ++j) + { + // y-axis rotation for origin + x2 = jointList[j].placement.origin[0]*cy+jointList[j].placement.origin[2]*sy; + z2 = -jointList[j].placement.origin[0]*sy+jointList[j].placement.origin[2]*cy; + jointList[j].placement.origin[0] = x2; + jointList[j].placement.origin[2] = z2; + + // y-axis rotation for direction + x2 = jointList[j].placement.direction[0]*cy+jointList[j].placement.direction[2]*sy; + z2 = -jointList[j].placement.direction[0]*sy+jointList[j].placement.direction[2]*cy; + jointList[j].placement.direction[0] = x2; + jointList[j].placement.direction[2] = z2; + + // y-axis rotation for up + x2 = jointList[j].placement.up[0]*cy+jointList[j].placement.up[2]*sy; + z2 = -jointList[j].placement.up[0]*sy+jointList[j].placement.up[2]*cy; + jointList[j].placement.up[0] = x2; + jointList[j].placement.up[2] = z2; + + // z-axis rotation for origin + x2 = jointList[j].placement.origin[0]*cz-jointList[j].placement.origin[1]*sz; + y2 = jointList[j].placement.origin[0]*sz+jointList[j].placement.origin[1]*cz; + jointList[j].placement.origin[0] = x2; + jointList[j].placement.origin[1] = y2; + + // z-axis rotation for direction + x2 = jointList[j].placement.direction[0]*cz-jointList[j].placement.direction[1]*sz; + y2 = jointList[j].placement.direction[0]*sz+jointList[j].placement.direction[1]*cz; + jointList[j].placement.direction[0] = x2; + jointList[j].placement.direction[1] = y2; + + // z-axis rotation for up + x2 = jointList[j].placement.up[0]*cz-jointList[j].placement.up[1]*sz; + y2 = jointList[j].placement.up[0]*sz+jointList[j].placement.up[1]*cz; + jointList[j].placement.up[0] = x2; + jointList[j].placement.up[1] = y2; + + // x-axis rotation for origin + y2 = jointList[j].placement.origin[1]*cx-jointList[j].placement.origin[2]*sx; + z2 = jointList[j].placement.origin[1]*sx+jointList[j].placement.origin[2]*cx; + jointList[j].placement.origin[1] = y2; + jointList[j].placement.origin[2] = z2; + + // x-axis rotation for direction vector + y2 = jointList[j].placement.direction[1]*cx-jointList[j].placement.direction[2]*sx; + z2 = jointList[j].placement.direction[1]*sx+jointList[j].placement.direction[2]*cx; + jointList[j].placement.direction[1] = y2; + jointList[j].placement.direction[2] = z2; + + // x-axis rotation for up vector + y2 = jointList[j].placement.up[1]*cx-jointList[j].placement.up[2]*sx; + z2 = jointList[j].placement.up[1]*sx+jointList[j].placement.up[2]*cx; + jointList[j].placement.up[1] = y2; + jointList[j].placement.up[2] = z2; + + if(curCorrespondingJoint[j+1] != -1) + { + // translate origin + jointList[j].placement.origin[0] += curTranslation[i-1][0]; + jointList[j].placement.origin[1] += curTranslation[i-1][1]; + jointList[j].placement.origin[2] += curTranslation[i-1][2]; + + // translate back to local coord + jointList[j].placement.direction[0] += curTranslation[i-1][0]; + jointList[j].placement.direction[1] += curTranslation[i-1][1]; + jointList[j].placement.direction[2] += curTranslation[i-1][2]; + + // translate back to local coord + jointList[j].placement.up[0] += curTranslation[i-1][0]; + jointList[j].placement.up[1] += curTranslation[i-1][1]; + jointList[j].placement.up[2] += curTranslation[i-1][2]; + } + } + } +} + +void LoadGlobals(char *fileName) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + + LoadHRCGlobals(InputFileName); + + printf(" - assuming .HRC\n"); + return; + } + + Error("\n Could not open file '%s':\n" + "No HRC match.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { + printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRCGlobals(fileName); + return; + } + } + + Error("Could not open file '%s':\n",fileName); + } +} + +void LoadClusters(char *fileName, int **clusterList, int *num_verts, int skelType) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + + LoadHRCClustered(InputFileName, clusterList, num_verts, skelType); + + printf(" - assuming .HRC\n"); + return; + } + + Error("\n Could not open file '%s':\n" + "No HRC match.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { + printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRCClustered(fileName, clusterList, num_verts, skelType); + return; + } + } + + Error("Could not open file '%s':\n",fileName); + } +} + +void LoadJointList(char *fileName, QDataJoint_t *jointList, int skelType) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + + LoadHRCJointList(InputFileName, jointList, skelType); + + printf(" - assuming .HRC\n"); + return; + } + + Error("\n Could not open file '%s':\n" + "No HRC.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { + printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRCJointList(fileName, jointList, skelType); + + return; + } + } + + Error("Could not open file '%s':\n",fileName); + } +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/jointed.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/jointed.h new file mode 100644 index 00000000..d0736c1f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/jointed.h @@ -0,0 +1,35 @@ +/* +Copyright (C) 1999-2006 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 _JOINTED_H +#define _JOINTED_H + +#include "joints.h" + +void LoadGlobals(char *fileName); +void LoadClusters(char *fileName, int **clusterList, int *num_verts, int skel_type); +void LoadJointList(char *fileName, struct QDataJoint_s *jointList, int num_verts); + +#define NUM_CLUSTERS 8 + +#define NOT_JOINTED -1 + +#endif //_JOINTED_H diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/joints.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/joints.h new file mode 100644 index 00000000..c08dee10 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/joints.h @@ -0,0 +1,144 @@ +/* +Copyright (C) 1999-2006 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 JOINTS_H +#define JOINTS_H + +#ifdef _HERETIC2_ +#include "angles.h" +#endif + +//typedef float vec3_t[3]; +//typedef unsigned char byte; + +#ifndef _WIN32 +#define stricmp strcasecmp +#define strcmpi strcasecmp +#endif + +typedef struct Placement_s +{ + vec3_t origin; + vec3_t direction; + vec3_t up; +} Placement_t; + +#if 1 +typedef struct QDataJoint_s +{ + Placement_t placement; + vec3_t rotation; +} QDataJoint_t; +#endif + +typedef struct ArrayedListNode_s +{ + int data; + int next; + int inUse; +} ArrayedListNode_t; + +#define ARRAYEDLISTNODE_NULL -1 + +typedef struct JointAngles_s +{ + float angles[3]; + int children; + int created; +} JointAngles_t; + +typedef struct JointAngles2_s +{ + float angles[3]; + int children; + int changed[3]; + int inUse; +} JointAngles2_t; + +#define MAX_MODELJOINTS 256 +#define MAX_MODELJOINTNODES 255 + +extern JointAngles_t jointAngles[MAX_MODELJOINTS]; +extern JointAngles2_t jointAngles2[MAX_MODELJOINTS]; + +extern ArrayedListNode_t jointAngleNodes[MAX_MODELJOINTNODES]; + +// Skeletal structures enums +enum { + SKEL_RAVEN = 0, + SKEL_BOX, + NUM_SKELETONS +}; + +// Raven Skeletal structures enums +enum { + RAVEN_WAIST1 = 0, + RAVEN_WAIST2 = 1, + RAVEN_HEAD = 2, + NUM_JOINTS_RAVEN +}; + +// Box Skeletal structures enums +enum { + BOX_CENTER = 0, + NUM_JOINTS_BOX +}; + +extern int numJointsForSkeleton[]; +extern char *RAVEN_SKEL_NAMES[]; + +#define J_NEW_SKELETON 0x00001000 +#define J_YAW_CHANGED 0x00002000 +#define J_PITCH_CHANGED 0x00004000 +#define J_ROLL_CHANGED 0x00008000 +#define MAX_JOINTS 0x00000fff +/* +inline int GetFreeNode(ArrayedListNode_t *nodeArray, int max) +{ // yeah, I know this is a sucky, inefficient way to do this, but I didn't feel like taking the time to write a real resource manager in C + int i; + + for(i = 0; i < max; ++i) + { + if(!nodeArray[i].inUse) + { + nodeArray[i].inUse = 1; + return i; + } + } + + assert(0); + return -1; +} + +inline void FreeNode(ArrayedListNode_t *nodeArray, int index) +{ + nodeArray[index].inUse = 0; +} +*/ +int CreateSkeleton(int structure); +void CreateSkeletonAtIndex(int structure, int index); +void FreeSkeleton(int structure, int index); +void SetJointAngle(int jointIndex, int angleIndex, float angle); +float ModifyJointAngle(int jointIndex, int angleIndex, float deltaAngle); +int ZeroJointAngle(int jointIndex, int angleIndex, float angVel); +int ApplyAngVelToJoint(int jointIndex, int angleIndex, float angVel, float destAng); + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/models.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/models.c new file mode 100644 index 00000000..27145b70 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/models.c @@ -0,0 +1,2050 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" +#include +#include "jointed.h" +#include "fmodel.h" + +//================================================================= + +typedef struct +{ + int numnormals; + vec3_t normalsum; +} vertexnormals_t; + +typedef struct +{ + vec3_t v; + int lightnormalindex; +} trivert_t; + +typedef struct +{ + vec3_t mins, maxs; + char name[16]; + trivert_t v[MAX_VERTS]; + QDataJoint_t joints[NUM_CLUSTERS]; // ,this +} frame_t; + +// ,and all of this should get out of here, need to use new stuff in fmodels instead + +typedef struct IntListNode_s +{ + int data; + struct IntListNode_s *next; +} IntListNode_t; // gaak + +typedef struct +{ + float scale[3]; // multiply byte verts by this + float translate[3]; // then add this +} PartialAliasFrame_t; + +int jointed; +int clustered; + +int *clusters[NUM_CLUSTERS]; +IntListNode_t *vertLists[NUM_CLUSTERS]; +int num_verts[NUM_CLUSTERS + 1]; +int new_num_verts[NUM_CLUSTERS + 1]; + +// end that + +//================================================================ + +frame_t g_frames[MAX_FRAMES]; +//frame_t *g_frames; + +static dmdl_t model; + + +float scale_up; // set by $scale +vec3_t adjust; // set by $origin +int g_fixedwidth, g_fixedheight; // set by $skinsize + + +// +// base frame info +// +dstvert_t base_st[MAX_VERTS]; +dtriangle_t triangles[MAX_TRIANGLES]; + +static int triangle_st[MAX_TRIANGLES][3][2]; + +// the command list holds counts, s/t values, and xyz indexes +// that are valid for every frame +int commands[16384]; +int numcommands; +int numglverts; +int used[MAX_TRIANGLES]; + +char g_skins[MAX_MD2SKINS][64]; + +char cdarchive[1024]; +char cdpartial[1024]; +char cddir[1024]; + +char modelname[64]; // empty unless $modelname issued (players) + +extern char *g_outputDir; + +#define NUMVERTEXNORMALS 162 + +float avertexnormals[NUMVERTEXNORMALS][3] = +{ + #include "anorms.h" +}; + +unsigned char pic[SKINPAGE_HEIGHT*SKINPAGE_WIDTH], pic_palette[768]; + +FILE *headerouthandle = NULL; + +//============================================================== + +/* +=============== +ClearModel +=============== +*/ +static void ClearModel (void) +{ + memset (&model, 0, sizeof(model)); + + modelname[0] = 0; + jointed = NOT_JOINTED; + clustered = 0; + scale_up = 1.0; + VectorCopy (vec3_origin, adjust); + g_fixedwidth = g_fixedheight = 0; + g_skipmodel = false; +} + + +void H_printf(char *fmt, ...) +{ + va_list argptr; + char name[1024]; + + if (!headerouthandle) + { + sprintf (name, "%s/tris.h", cddir); + headerouthandle = SafeOpenWrite (name); + fprintf(headerouthandle, "// %s\n\n", cddir); + fprintf(headerouthandle, "// This file generated by qdata - Do NOT Modify\n\n"); + } + + va_start (argptr, fmt); + vfprintf (headerouthandle, fmt, argptr); + va_end (argptr); +} + +#if 1 +/* +============ +WriteModelFile +============ +*/ +void WriteCommonModelFile (FILE *modelouthandle, PartialAliasFrame_t *outFrames) +{ + int i; + dmdl_t modeltemp; + int j, k; + frame_t *in; + daliasframe_t *out; + byte buffer[MAX_VERTS*4+128]; + float v; + int c_on, c_off; + + model.version = ALIAS_VERSION; + model.framesize = (int)&((daliasframe_t *)0)->verts[model.num_xyz]; + model.num_glcmds = numcommands; + model.ofs_skins = sizeof(dmdl_t); + model.ofs_st = model.ofs_skins + model.num_skins * MAX_SKINNAME; + model.ofs_tris = model.ofs_st + model.num_st*sizeof(dstvert_t); + model.ofs_frames = model.ofs_tris + model.num_tris*sizeof(dtriangle_t); + model.ofs_glcmds = model.ofs_frames + model.num_frames*model.framesize; + model.ofs_end = model.ofs_glcmds + model.num_glcmds*sizeof(int); + // + // write out the model header + // + for (i=0 ; iname, in->name); + for (j=0 ; j<3 ; j++) + { + out->scale[j] = (in->maxs[j] - in->mins[j])/255; + out->translate[j] = in->mins[j]; + + if(outFrames) + { + outFrames[i].scale[j] = out->scale[j]; + outFrames[i].translate[j] = out->translate[j]; + } + } + + for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; + + for (k=0 ; k<3 ; k++) + { + // scale to byte values & min/max check + v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); + + // clamp, so rounding doesn't wrap from 255.6 to 0 + if (v > 255.0) + v = 255.0; + if (v < 0) + v = 0; + out->verts[j].v[k] = v; + } + } + + for (j=0 ; j<3 ; j++) + { + out->scale[j] = LittleFloat (out->scale[j]); + out->translate[j] = LittleFloat (out->translate[j]); + } + + SafeWrite (modelouthandle, out, model.framesize); + } + + // + // write out glcmds + // + SafeWrite (modelouthandle, commands, numcommands*4); +} + +/* +============ +WriteModelFile +============ +*/ +void WriteModelFile (FILE *modelouthandle) +{ + model.ident = IDALIASHEADER; + + WriteCommonModelFile(modelouthandle, NULL); +} + +/* +============ +WriteJointedModelFile +============ +*/ +void WriteJointedModelFile (FILE *modelouthandle) +{ + int i; + int j, k; + frame_t *in; + float v; + IntListNode_t *current, *toFree; + PartialAliasFrame_t outFrames[MAX_FRAMES]; + + model.ident = IDJOINTEDALIASHEADER; + + WriteCommonModelFile(modelouthandle, outFrames); + + // Skeletal Type + SafeWrite(modelouthandle, &jointed, sizeof(int)); + + // number of joints + SafeWrite(modelouthandle, &numJointsForSkeleton[jointed], sizeof(int)); + + // number of verts in each cluster + SafeWrite(modelouthandle, &new_num_verts[1], sizeof(int)*numJointsForSkeleton[jointed]); + + // cluster verts + for(i = 0; i < new_num_verts[0]; ++i) + { + current = vertLists[i]; + while(current) + { + SafeWrite (modelouthandle, ¤t->data, sizeof(int)); + toFree = current; + current = current->next; + free(toFree); // freeing of memory allocated in ReplaceClusterIndex called in Cmd_Base + } + } + + for (i=0 ; ijoints[j].placement.origin[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // clamp, so rounding doesn't wrap from 255.6 to 0 + if (v > 255.0) + { + v = 255.0; + } + + if (v < 0) + { + v = 0; + } + + // write out origin as a float (there's only a few per model, so it's not really + // a size issue) + SafeWrite (modelouthandle, &v, sizeof(float)); + } + + for (k=0 ; k<3 ; k++) + { + v = Q_rint ( (in->joints[j].placement.direction[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // clamp, so rounding doesn't wrap from 255.6 to 0 + if (v > 255.0) + { + v = 255.0; + } + + if (v < 0) + { + v = 0; + } + + // write out origin as a float (there's only a few per model, so it's not really + // a size issue) + SafeWrite (modelouthandle, &v, sizeof(float)); + } + + for (k=0 ; k<3 ; k++) + { + v = Q_rint ( (in->joints[j].placement.up[k] - outFrames[i].translate[k]) / outFrames[i].scale[k] ); + + // clamp, so rounding doesn't wrap from 255.6 to 0 + if (v > 255.0) + { + v = 255.0; + } + + if (v < 0) + { + v = 0; + } + + // write out origin as a float (there's only a few per model, so it's not really + // a size issue) + SafeWrite (modelouthandle, &v, sizeof(float)); + } + } + } +} +#else +/* +============ +WriteModelFile +============ +*/ +static void WriteModelFile (FILE *modelouthandle) +{ + int i; + dmdl_t modeltemp; + int j, k; + frame_t *in; + daliasframe_t *out; + byte buffer[MAX_VERTS*4+128]; + float v; + int c_on, c_off; + + model.ident = IDALIASHEADER; + model.version = ALIAS_VERSION; + model.framesize = (int)&((daliasframe_t *)0)->verts[model.num_xyz]; + model.num_glcmds = numcommands; + model.ofs_skins = sizeof(dmdl_t); + model.ofs_st = model.ofs_skins + model.num_skins * MAX_SKINNAME; + model.ofs_tris = model.ofs_st + model.num_st*sizeof(dstvert_t); + model.ofs_frames = model.ofs_tris + model.num_tris*sizeof(dtriangle_t); + model.ofs_glcmds = model.ofs_frames + model.num_frames*model.framesize; + model.ofs_end = model.ofs_glcmds + model.num_glcmds*4; + + // + // write out the model header + // + for (i=0 ; iname, in->name); + for (j=0 ; j<3 ; j++) + { + out->scale[j] = (in->maxs[j] - in->mins[j])/255; + out->translate[j] = in->mins[j]; + } + + for (j=0 ; jverts[j].lightnormalindex = in->v[j].lightnormalindex; + + for (k=0 ; k<3 ; k++) + { + // scale to byte values & min/max check + v = Q_rint ( (in->v[j].v[k] - out->translate[k]) / out->scale[k] ); + + // clamp, so rounding doesn't wrap from 255.6 to 0 + if (v > 255.0) + v = 255.0; + if (v < 0) + v = 0; + out->verts[j].v[k] = v; + } + } + + for (j=0 ; j<3 ; j++) + { + out->scale[j] = LittleFloat (out->scale[j]); + out->translate[j] = LittleFloat (out->translate[j]); + } + + SafeWrite (modelouthandle, out, model.framesize); + } + + // + // write out glcmds + // + SafeWrite (modelouthandle, commands, numcommands*4); +} +#endif + +/* +=============== +FinishModel +=============== +*/ +void FinishModel (void) +{ + FILE *modelouthandle; + int i; + char name[1024]; + + if (!model.num_frames) + return; + +// +// copy to release directory tree if doing a release build +// + if (g_release) + { + if (modelname[0]) + sprintf (name, "%s", modelname); + else + sprintf (name, "%s/tris.md2", cdpartial); + ReleaseFile (name); + + for (i=0 ; iindex_xyz[(startv)%3]; + strip_xyz[1] = last->index_xyz[(startv+1)%3]; + strip_xyz[2] = last->index_xyz[(startv+2)%3]; + strip_st[0] = last->index_st[(startv)%3]; + strip_st[1] = last->index_st[(startv+1)%3]; + strip_st[2] = last->index_st[(startv+2)%3]; + + strip_tris[0] = starttri; + stripcount = 1; + + m1 = last->index_xyz[(startv+2)%3]; + st1 = last->index_st[(startv+2)%3]; + m2 = last->index_xyz[(startv+1)%3]; + st2 = last->index_st[(startv+1)%3]; + + // look for a matching triangle +nexttri: + for (j=starttri+1, check=&triangles[starttri+1] + ; jindex_xyz[k] != m1) + continue; + if (check->index_st[k] != st1) + continue; + if (check->index_xyz[ (k+1)%3 ] != m2) + continue; + if (check->index_st[ (k+1)%3 ] != st2) + continue; + + // this is the next part of the fan + + // if we can't use this triangle, this tristrip is done + if (used[j]) + goto done; + + // the new edge + if (stripcount & 1) + { + m2 = check->index_xyz[ (k+2)%3 ]; + st2 = check->index_st[ (k+2)%3 ]; + } + else + { + m1 = check->index_xyz[ (k+2)%3 ]; + st1 = check->index_st[ (k+2)%3 ]; + } + + strip_xyz[stripcount+2] = check->index_xyz[ (k+2)%3 ]; + strip_st[stripcount+2] = check->index_st[ (k+2)%3 ]; + strip_tris[stripcount] = j; + stripcount++; + + used[j] = 2; + goto nexttri; + } + } +done: + + // clear the temp used flags + for (j=starttri+1 ; jindex_xyz[(startv)%3]; + strip_xyz[1] = last->index_xyz[(startv+1)%3]; + strip_xyz[2] = last->index_xyz[(startv+2)%3]; + strip_st[0] = last->index_st[(startv)%3]; + strip_st[1] = last->index_st[(startv+1)%3]; + strip_st[2] = last->index_st[(startv+2)%3]; + + strip_tris[0] = starttri; + stripcount = 1; + + m1 = last->index_xyz[(startv+0)%3]; + st1 = last->index_st[(startv+0)%3]; + m2 = last->index_xyz[(startv+2)%3]; + st2 = last->index_st[(startv+2)%3]; + + + // look for a matching triangle +nexttri: + for (j=starttri+1, check=&triangles[starttri+1] + ; jindex_xyz[k] != m1) + continue; + if (check->index_st[k] != st1) + continue; + if (check->index_xyz[ (k+1)%3 ] != m2) + continue; + if (check->index_st[ (k+1)%3 ] != st2) + continue; + + // this is the next part of the fan + + // if we can't use this triangle, this tristrip is done + if (used[j]) + goto done; + + // the new edge + m2 = check->index_xyz[ (k+2)%3 ]; + st2 = check->index_st[ (k+2)%3 ]; + + strip_xyz[stripcount+2] = m2; + strip_st[stripcount+2] = st2; + strip_tris[stripcount] = j; + stripcount++; + + used[j] = 2; + goto nexttri; + } + } +done: + + // clear the temp used flags + for (j=starttri+1 ; j bestlen) + { + besttype = type; + bestlen = len; + for (j=0 ; j= 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_fixedwidth / 2; + iheight = g_fixedheight; + + s_scale = (float)(iwidth-4) / width; + t_scale = (float)(iheight-4) / height; + } + +// +// determine which side of each triangle to map the texture to +// + for (i=0 ; i 0) + { + basex = iwidth + 2; + } + else + { + basex = 2; + } + basey = 2; + + for (j=0 ; j<3 ; j++) + { + pbasevert = ptri[i].verts[j]; + + triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); + triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); + } + } + +// make the width a multiple of 4; some hardware requires this, and it ensures +// dword alignment for each scan + swidth = iwidth*2; + model.skinwidth = (swidth + 3) & ~3; + model.skinheight = iheight; +} +#endif + +//========================================================================== +// +// DrawScreen +// +//========================================================================== + +void DrawScreen(float s_scale, float t_scale, float iwidth, float iheight) +{ + int i; + byte *scrpos; + char buffer[256]; + + // Divider + scrpos = &pic[(INFO_Y-2)*SKINPAGE_WIDTH]; + for(i = 0; i < SKINPAGE_WIDTH; i++) + { + *scrpos++ = 255; + } + + sprintf(buffer, "GENSKIN: "); + DrawTextChar(16, INFO_Y, buffer); + + sprintf(buffer, "( %03d * %03d ) SCALE %f %f, SKINWIDTH %d," + " SKINHEIGHT %d", (int)ScaleWidth, (int)ScaleHeight, s_scale, t_scale, (int)iwidth*2, (int)iheight); + DrawTextChar(80, INFO_Y, buffer); +} + +/* +============ +BuildST + +Builds the triangle_st array for the base frame and +model.skinwidth / model.skinheight + + FIXME: allow this to be loaded from a file for + arbitrary mappings +============ +*/ +void BuildST (triangle_t *ptri, int numtri, qboolean DrawSkin) +{ + int i, j; + int width, height, iwidth, iheight, swidth; + float basex, basey; + float scale; + vec3_t mins, maxs; + float *pbasevert; + vec3_t vtemp1, vtemp2, normal; + float s_scale, t_scale; + float scWidth; + float scHeight; + + // + // find bounds of all the verts on the base frame + // + ClearBounds (mins, maxs); + + for (i=0 ; i= scHeight) + { + scale = scHeight/height; + } + + iwidth = ceil(width*scale)+4; + iheight = ceil(height*scale)+4; + + s_scale = (float)(iwidth-4) / width; + t_scale = (float)(iheight-4) / height; + t_scale = s_scale; + + if (DrawSkin) + DrawScreen(s_scale, t_scale, iwidth, iheight); + + +/* if (!g_fixedwidth) + { // old style + scale = 8; + if (width*scale >= 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_fixedwidth / 2; + iheight = g_fixedheight; + + s_scale = (float)(iwidth-4) / width; + t_scale = (float)(iheight-4) / height; + }*/ + +// +// determine which side of each triangle to map the texture to +// + for (i=0 ; i 0) + { + basex = iwidth + 2; + } + else + { + basex = 2; + } + basey = 2; + + for (j=0 ; j<3 ; j++) + { + pbasevert = ptri[i].verts[j]; + + triangle_st[i][j][0] = Q_rint((pbasevert[0] - mins[0]) * s_scale + basex); + triangle_st[i][j][1] = Q_rint((maxs[2] - pbasevert[2]) * t_scale + basey); + } + } + + DrawLine(triangle_st[i][0][0], triangle_st[i][0][1], + triangle_st[i][1][0], triangle_st[i][1][1]); + DrawLine(triangle_st[i][1][0], triangle_st[i][1][1], + triangle_st[i][2][0], triangle_st[i][2][1]); + DrawLine(triangle_st[i][2][0], triangle_st[i][2][1], + triangle_st[i][0][0], triangle_st[i][0][1]); + } + +// make the width a multiple of 4; some hardware requires this, and it ensures +// dword alignment for each scan + + swidth = iwidth*2; + model.skinwidth = (swidth + 3) & ~3; + model.skinheight = iheight; +} + + +static void ReplaceClusterIndex(int newIndex, int oldindex, int **clusters, + IntListNode_t **vertLists, int *num_verts, int *new_num_verts) +{ + int i, j; + IntListNode_t *next; + + for(j = 0; j < num_verts[0]; ++j) + { + for(i = 0; i < num_verts[j+1]; ++i) + { + if(clusters[j][i] == oldindex) + { + ++new_num_verts[j+1]; + + next = vertLists[j]; + + vertLists[j] = (IntListNode_t *) SafeMalloc(sizeof(IntListNode_t), "ReplaceClusterIndex"); + // Currently freed in WriteJointedModelFile only + + vertLists[j]->data = newIndex; + vertLists[j]->next = next; + } + } + } +} + +/* +================= +Cmd_Base +================= +*/ +void Cmd_Base (void) +{ + vec3_t base_xyz[MAX_VERTS]; + triangle_t *ptri; + int i, j, k; +#if 1 +#else + int time1; +#endif + char file1[1024]; + char file2[1024]; + + GetScriptToken (false); + + if (g_skipmodel || g_release || g_archive) + return; + + printf ("---------------------\n"); +#if 1 + sprintf (file1, "%s/%s", cdpartial, token); + printf ("%s ", file1); + + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s", cddir, token); +#else + sprintf (file1, "%s/%s.%s", cdarchive, token, trifileext); + printf ("%s\n", file1); + + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s.%s", cddir, token, trifileext); + + time1 = FileTime (file1); + if (time1 == -1) + Error ("%s doesn't exist", file1); +#endif +// +// load the base triangles +// + if (do3ds) + Load3DSTriangleList (file1, &ptri, &model.num_tris, NULL, NULL); + else + LoadTriangleList (file1, &ptri, &model.num_tris, NULL, NULL); + + + GetScriptToken (false); + sprintf (file2, "%s/%s.pcx", cddir, token); +// sprintf (trans_file, "%s/!%s_a.pcx", cddir, token); + + printf ("skin: %s\n", file2); + Load256Image (file2, &BasePixels, &BasePalette, &BaseWidth, &BaseHeight); + + if (BaseWidth != SKINPAGE_WIDTH || BaseHeight != SKINPAGE_HEIGHT) + { + if (g_allow_newskin) + { + ScaleWidth = BaseWidth; + ScaleHeight = BaseHeight; + } + else + { + Error("Invalid skin page size: (%d,%d) should be (%d,%d)", + BaseWidth,BaseHeight,SKINPAGE_WIDTH,SKINPAGE_HEIGHT); + } + } + else + { + ScaleWidth = (float)ExtractNumber(BasePixels, ENCODED_WIDTH_X, + ENCODED_WIDTH_Y); + ScaleHeight = (float)ExtractNumber(BasePixels, ENCODED_HEIGHT_X, + ENCODED_HEIGHT_Y); + } + +// +// get the ST values +// + BuildST (ptri, model.num_tris,false); + +// +// run through all the base triangles, storing each unique vertex in the +// base vertex list and setting the indirect triangles to point to the base +// vertices +// + for (i=0 ; i= '0' && *s <= '9') + s--; + + strcpy (suffix, s+1); + strcpy (base, frame); + base[s-frame+1] = 0; + + sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "hrc"); + time1 = FileTime (file1); + if (time1 != -1) + { + sprintf (retname, "%s%s.%s", base, suffix, "hrc"); + return retname; + } + + sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "asc"); + time1 = FileTime (file1); + if (time1 != -1) + { + sprintf (retname, "%s%s.%s", base, suffix, "asc"); + return retname; + } + + sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "tri"); + time1 = FileTime (file1); + if (time1 != -1) + { + sprintf (retname, "%s%s.%s", base, suffix, "tri"); + return retname; + } + + sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "3ds"); + time1 = FileTime (file1); + if (time1 != -1) + { + sprintf (retname, "%s%s.%s", base, suffix, "3ds"); + return retname; + } + + sprintf (file1, "%s/%s%s.%s",cddir, base, suffix, "htr"); + time1 = FileTime (file1); + if (time1 != -1) + { + sprintf (retname, "%s%s.%s", base, suffix, "htr"); + return retname; + } + + // check for 'run.1' + sprintf (file1, "%s/%s.%s",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; +} + +/* +=============== +GrabFrame +=============== +*/ +static void GrabFrame (char *frame) +{ + triangle_t *ptri; + int i, j; + trivert_t *ptrivert; + int num_tris; + char file1[1024]; + frame_t *fr; + vertexnormals_t vnorms[MAX_VERTS]; + int index_xyz; + char *framefile; + + // the frame 'run1' will be looked for as either + // run.1 or run1.tri, so the new alias sequence save + // feature an be used + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + + printf ("grabbing %s ", file1); + + if (model.num_frames >= MAX_FRAMES) + Error ("model.num_frames >= MAX_FRAMES"); + fr = &g_frames[model.num_frames]; + model.num_frames++; + + strcpy (fr->name, frame); + +// +// load the frame +// + if (do3ds) + Load3DSTriangleList (file1, &ptri, &num_tris, NULL, NULL); + else + LoadTriangleList (file1, &ptri, &num_tris, NULL, NULL); + + if (num_tris != model.num_tris) + Error ("%s: number of triangles doesn't match base frame\n", file1); + +// +// allocate storage for the frame's vertices +// + ptrivert = fr->v; + + for (i=0 ; imins, fr->maxs); + +// +// 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 ; imins, fr->maxs); + + VectorAdd (vnorms[index_xyz].normalsum, normal, vnorms[index_xyz].normalsum); + vnorms[index_xyz].numnormals++; + } + } + +// +// calculate the vertex normals, match them to the template list, and store the +// index of the best match +// + for (i=0 ; i maxdot) + { + maxdot = dot; + maxdotindex = j; + } + } + + ptrivert[i].lightnormalindex = maxdotindex; + } + + free (ptri); +} + +/* +=============== +GrabJointedFrame +=============== +*/ +void GrabJointedFrame(char *frame) +{ + char file1[1024]; + char *framefile; + frame_t *fr; + + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + + printf ("grabbing %s\n", file1); + + fr = &g_frames[model.num_frames - 1]; // last frame read in + + LoadJointList(file1, fr->joints, jointed); +} + +/* +=============== +GrabGlobals +=============== +*/ +void GrabGlobals(char *frame) +{ + char file1[1024]; + char *framefile; + frame_t *fr; + + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + + printf ("grabbing %s\n", file1); + + fr = &g_frames[model.num_frames - 1]; // last frame read in + + LoadGlobals(file1); +} + +/* +=============== +Cmd_Frame +=============== +*/ +void Cmd_Frame (void) +{ + while (ScriptTokenAvailable()) + { + GetScriptToken (false); + if (g_skipmodel) + continue; + if (g_release || g_archive) + { + model.num_frames = 1; // don't skip the writeout + continue; + } + + H_printf("#define FRAME_%-16s\t%i\n", token, model.num_frames); + + GrabFrame (token); + } +} + +/* +=============== +Cmd_Skin + +Skins aren't actually stored in the file, only a reference +is saved out to the header file. +=============== +*/ +void Cmd_Skin (void) +{ + byte *palette; + byte *pixels; + int width, height; + byte *cropped; + int y; + char name[1024], savename[1024]; + + GetScriptToken (false); + + if (model.num_skins == MAX_MD2SKINS) + Error ("model.num_skins == MAX_MD2SKINS"); + + if (g_skipmodel) + return; + +#if 1 + sprintf (name, "%s/%s.pcx", cddir, token); + sprintf (savename, "%s/!%s.pcx", g_outputDir, token); + sprintf (g_skins[model.num_skins], "%s/!%s.pcx", cdpartial, token); +#else + sprintf (name, "%s/%s.lbm", cdarchive, token); + strcpy (name, ExpandPathAndArchive( name ) ); +// sprintf (name, "%s/%s.lbm", cddir, token); + + if (ScriptTokenAvailable()) + { + GetScriptToken (false); + sprintf (g_skins[model.num_skins], "%s.pcx", token); + sprintf (savename, "%s%s.pcx", g_outputDir, g_skins[model.num_skins]); + } + else + { + sprintf (savename, "%s/%s.pcx", g_outputDir, token); + sprintf (g_skins[model.num_skins], "%s/%s.pcx", cdpartial, token); + } +#endif + + model.num_skins++; + + if (g_skipmodel || g_release || g_archive) + return; + + // load the image + printf ("loading %s\n", name); + Load256Image (name, &pixels, &palette, &width, &height); +// RemapZero (pixels, palette, width, height); + + // crop it to the proper size + cropped = (byte *) SafeMalloc (model.skinwidth*model.skinheight, "Cmd_Skin"); + for (y=0 ; y= longimagewidth || xh > longimagewidth || + yl >= longimageheight || yh > longimageheight) + { + Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,longimagewidth,longimageheight); + } + + sourcel = longimage + (yl*longimagewidth) + xl; + destl = bufferl; + linedelta = (longimagewidth - w); + + for (y=yl ; yflags |= LittleLong(flags); + qtex32->contents = contents; + qtex32->value = value; + qtex32->scale_x = scale_x; + qtex32->scale_y = scale_y; + sprintf (qtex32->name, "%s/%s", pic_prefix, lumpname); + if (animname[0]) + sprintf (qtex32->animname, "%s/%s", pic_prefix, animname); + + // + // write it out + // + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex32, size); + + free (qtex32); + } + else + { + sprintf (filename, "%spics/%s/%s.m8", g_outputDir, pic_prefix, lumpname); + if (g_release) + return; // textures are only released by $maps + + xh = xl+w; + yh = yl+h; + + if (xl >= byteimagewidth || xh > byteimagewidth || + yl >= byteimageheight || yh > byteimageheight) + { + Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); + } + + source = byteimage + yl*byteimagewidth + xl; + dest = buffer; + linedelta = byteimagewidth - w; + + for (y=yl ; yflags = flags; + qtex->contents = contents; + qtex->value = value; + sprintf (qtex->name, "%s/%s", pic_prefix, lumpname); + if (animname[0]) + sprintf (qtex->animname, "%s/%s", pic_prefix, animname); + + // + // write it out + // + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex, size); + + free (qtex); + } +} + + +/* +=============== +Cmd_picdir +=============== +*/ +void Cmd_Picdir (void) +{ + char filename[1024]; + + GetScriptToken (false); + strcpy (pic_prefix, token); + // create the directory if needed + sprintf (filename, "%sPics", g_outputDir); + Q_mkdir (filename); + sprintf (filename, "%sPics/%s", g_outputDir, pic_prefix); + Q_mkdir (filename); +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/angles.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/angles.h new file mode 100644 index 00000000..1a722dab --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/angles.h @@ -0,0 +1,76 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// Angles in radians + +#define ANGLE_0 0.0F +#define ANGLE_1 0.017453292F +#define ANGLE_5 0.087266462F +#define ANGLE_10 0.174532925F +#define ANGLE_15 0.261799387F +#define ANGLE_20 0.392699081F +#define ANGLE_30 0.523598775F +#define ANGLE_45 0.785398163F +#define ANGLE_60 1.047197551F +#define ANGLE_72 1.256637061F +#define ANGLE_90 1.570796327F +#define ANGLE_120 2.094395102F +#define ANGLE_135 2.35619449F +#define ANGLE_144 2.513274123F +#define ANGLE_180 3.141592653F +#define ANGLE_225 3.926990817F +#define ANGLE_270 4.71238898F +#define ANGLE_315 5.497787144F +#define ANGLE_360 6.283185307F + +// Angles in degrees + +#define DEGREE_0 0.0F +#define DEGREE_180 180.0F +#define DEGREE_45 (DEGREE_180 / 4.0F) +#define DEGREE_90 (DEGREE_180 / 2.0F) +#define DEGREE_135 (DEGREE_90 + DEGREE_45) +#define DEGREE_270 (DEGREE_180 + DEGREE_90) +#define DEGREE_360 (DEGREE_180 * 2.0F) + +#define DEGREE_225 (DEGREE_180 + DEGREE_45) +#define DEGREE_315 (DEGREE_270 + DEGREE_45) + +#define DEGREE_30 (DEGREE_180 / 6.0F) +#define DEGREE_60 (DEGREE_180 / 3.0F) +#define DEGREE_120 (DEGREE_360 / 3.0F) + +#define DEGREE_1 (DEGREE_180 / 180.0F) +#define DEGREE_5 (DEGREE_180 / 36.0F) +#define DEGREE_10 (DEGREE_180 / 18.0F) +#define DEGREE_15 (DEGREE_180 / 12.0F) +#define DEGREE_20 (DEGREE_180 / 8.0F) + +// Conversion routines + +#define ANGLE_TO_RAD ANGLE_1 +#define RAD_TO_ANGLE (180.0F / ANGLE_180) + +#define SHORT_TO_ANGLE (360.0/65536) + + +#pragma warning(disable : 4305) // 'initializing' : truncation from 'const double ' to 'float ' + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/arrayedlist.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/arrayedlist.h new file mode 100644 index 00000000..c04d669f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/arrayedlist.h @@ -0,0 +1,71 @@ +/* +Copyright (C) 1999-2006 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 _ARRAYEDLIST_H +#define _ARRAYEDLIST_H + +#include + +typedef struct ArrayedListNode_s +{ + int data; + int next; + int inUse; +} ArrayedListNode_t; + +#define ARRAYEDLISTNODE_NULL -1 + +static +#ifdef _WIN32 + _inline +#else + inline +#endif + int GetFreeNode(ArrayedListNode_t *nodeArray, int max) +{ + int i; + + for(i = 0; i < max; ++i) + { + if(!nodeArray[i].inUse) + { + nodeArray[i].inUse = 1; + return i; + } + } + + assert(0); + return -1; +} + +static +#ifdef _WIN32 + _inline +#else + inline +#endif +void FreeNode(ArrayedListNode_t *nodeArray, int index) +{ + nodeArray[index].inUse = 0; +} + +#endif //_ARRAYEDLIST_H + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/flex.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/flex.h new file mode 100644 index 00000000..0b231cbf --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/flex.h @@ -0,0 +1,33 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// Generic flexible format + +typedef struct +{ + char ident[32]; + int version; + int size; +} header_t; + +void WriteHeader(FILE *, char *, int, int, void *); + +// end diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/fmodel.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/fmodel.h new file mode 100644 index 00000000..ee198fff --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/fmodel.h @@ -0,0 +1,202 @@ +/* +Copyright (C) 1999-2006 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 +*/ + + +/* +======================================================================== + +.FM triangle flexible model file format + +======================================================================== +*/ + +#ifndef __FMODEL_HEADER +#define __FMODEL_HEADER + +#include "bspfile.h" + +//typedef unsigned char byte; +//typedef int qboolean; +//typedef float vec3_t[3]; + +#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 // also defined in game/qshared.h + + +#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) + +extern byte *BasePalette; +extern byte *BasePixels,*TransPixels; +extern int BaseWidth, BaseHeight, TransWidth, TransHeight; +extern int ScaleWidth, ScaleHeight; + +int ExtractNumber(byte *pic, int x, int y); +void DrawTextChar(int x, int y, char *text); +void DrawLine(int x1, int y1, int x2, int y2); + +// the glcmd format: +// a positive integer starts a tristrip command, followed by that many +// vertex structures. +// a negative integer starts a trifan command, followed by -x vertexes +// a zero indicates the end of the command list. +// a vertex consists of a floating point s, a floating point t, +// and an integer vertex index. + + +// Initial Header +#define FM_HEADER_NAME "header" +#define FM_HEADER_VER 2 + +typedef struct +{ + int skinwidth; + int skinheight; + int framesize; // byte size of each frame + + int num_skins; + int num_xyz; + int num_st; // greater than num_xyz for seams + int num_tris; + int num_glcmds; // dwords in strip/fan command list + int num_frames; + int num_mesh_nodes; +} fmheader_t; + + +// Skin Header +#define FM_SKIN_NAME "skin" +#define FM_SKIN_VER 1 + + +// ST Coord Header +#define FM_ST_NAME "st coord" +#define FM_ST_VER 1 + +typedef struct +{ + short s; + short t; +} fmstvert_t; + + +// Tri Header +#define FM_TRI_NAME "tris" +#define FM_TRI_VER 1 + +typedef struct +{ + short index_xyz[3]; + short index_st[3]; +} fmtriangle_t; + + +// Frame Header +#define FM_FRAME_NAME "frames" +#define FM_FRAME_VER 1 + +// Frame for compression, just the names +#define FM_SHORT_FRAME_NAME "short frames" +#define FM_SHORT_FRAME_VER 1 + +// Normals for compressed frames +#define FM_NORMAL_NAME "normals" +#define FM_NORMAL_VER 1 + +// Compressed Frame Data +#define FM_COMP_NAME "comp data" +#define FM_COMP_VER 1 + +// GL Cmds Header +#define FM_GLCMDS_NAME "glcmds" +#define FM_GLCMDS_VER 1 + + +// Mesh Nodes Header +#define FM_MESH_NAME "mesh nodes" +#define FM_MESH_VER 3 + +// Skeleton Header +#define FM_SKELETON_NAME "skeleton" +#define FM_SKELETON_VER 1 + +// References Header +#define FM_REFERENCES_NAME "references" +#define FM_REFERENCES_VER 1 + +typedef struct +{ + + union + { + + byte tris[MAX_FM_TRIANGLES>>3]; + + struct { + short *triIndicies; + int num_tris; + }; + + }; + + byte verts[MAX_FM_VERTS>>3]; + short start_glcmds, num_glcmds; +} fmmeshnode_t; + +//================================================================= + +// Frame info +typedef struct +{ + byte v[3]; // scaled byte to fit in frame mins/maxs + byte lightnormalindex; +} fmtrivertx_t; + +typedef struct +{ + float scale[3]; // multiply byte verts by this + float translate[3]; // then add this + char name[16]; // frame name from grabbing + fmtrivertx_t verts[1]; // variable sized +} fmaliasframe_t; + + +#endif // #define __FMODEL_HEADER diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/h2common.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/h2common.h new file mode 100644 index 00000000..a7f6587d --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/h2common.h @@ -0,0 +1,26 @@ +/* +Copyright (C) 1999-2006 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 H2COMMON_H +#define H2COMMON_H + #define H2COMMON_API +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/placement.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/placement.h new file mode 100644 index 00000000..4db2c55b --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/placement.h @@ -0,0 +1,38 @@ +/* +Copyright (C) 1999-2006 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 PLACEMENT_H +#define PLACEMENT_H + +#include "q_typedef.h" + +//typedef float vec3_t[3]; + +typedef struct Placement_s +{ + vec3_t origin; + vec3_t direction; + vec3_t up; +} Placement_t; + +#endif + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/q_typedef.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/q_typedef.h new file mode 100644 index 00000000..02f9a459 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/q_typedef.h @@ -0,0 +1,63 @@ +/* +Copyright (C) 1999-2006 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_TYPEDEF_H +#define Q_TYPEDEF_H + +typedef float vec_t; +typedef vec_t vec2_t[2]; +typedef vec_t vec3_t[3]; +typedef double vec3d_t[3]; +typedef vec_t vec5_t[5]; + +typedef float matrix3_t[3][3]; +typedef float matrix3d_t[3][3]; + +typedef int fixed4_t; +typedef int fixed8_t; +typedef int fixed16_t; + +typedef unsigned char byte; + +#ifndef __cplusplus +typedef enum {false, true} qboolean; +#else +typedef int qboolean; +#endif + +typedef struct edict_s edict_t; + +typedef struct paletteRGBA_s +{ + union + { + struct + { + byte r,g,b,a; + }; + unsigned c; + byte c_array[4]; + }; +} paletteRGBA_t; + +#endif + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/qfiles.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/qfiles.h new file mode 100644 index 00000000..d71eaf2b --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/qfiles.h @@ -0,0 +1,604 @@ +/* +Copyright (C) 1999-2006 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 +*/ + + +// +// qfiles.h: quake file formats +// This file must be identical in the quake and utils directories +// + +/* +======================================================================== + +The .pak files are just a linear collapse of a directory tree + +======================================================================== +*/ + +#define IDPAKHEADER (('K'<<24)+('C'<<16)+('A'<<8)+'P') + +typedef struct +{ + char name[56]; + int filepos, filelen; +} dpackfile_t; + +typedef struct +{ + int ident; // == IDPAKHEADER + int dirofs; + int dirlen; +} dpackheader_t; + +#define MAX_FILES_IN_PACK 6144 + + +/* +======================================================================== + +PCX files are used for as many images as possible + +======================================================================== +*/ + +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; + +/* +======================================================================== + +.MD2 compressed triangle model file format + +======================================================================== +*/ +#define IDCOMPRESSEDALIASHEADER (('2'<<24)+('C'<<16)+('D'<<8)+'I') + +/* +======================================================================== + +.MD2 compressed triangle model file format + +======================================================================== +*/ +#define IDJOINTEDALIASHEADER (('2'<<24)+('J'<<16)+('D'<<8)+'I') + +/* +======================================================================== + +.MD2 triangle model file format + +======================================================================== +*/ + +#define IDALIASHEADER (('2'<<24)+('P'<<16)+('D'<<8)+'I') +#define ALIAS_VERSION 8 + +#define MAX_TRIANGLES 4096 +#define MAX_VERTS 2048 +#define MAX_FRAMES 512 +#define MAX_MD2SKINS 64 +#define MAX_SKINNAME 64 + +typedef struct +{ + short s; + short t; +} dstvert_t; + +typedef struct +{ + short index_xyz[3]; + short index_st[3]; +} dtriangle_t; + +typedef struct +{ + union + { + struct + { + byte v[3]; // scaled byte to fit in frame mins/maxs + byte lightnormalindex; + }; + + int vert; + }; +} dtrivertx_t; + +#define DTRIVERTX_V0 0 +#define DTRIVERTX_V1 1 +#define DTRIVERTX_V2 2 +#define DTRIVERTX_LNI 3 +#define DTRIVERTX_SIZE 4 + +typedef struct +{ + float scale[3]; // multiply byte verts by this + float translate[3]; // then add this + char name[16]; // frame name from grabbing + dtrivertx_t verts[1]; // variable sized +} daliasframe_t; + + +// the glcmd format: +// a positive integer starts a tristrip command, followed by that many +// vertex structures. +// a negative integer starts a trifan command, followed by -x vertexes +// a zero indicates the end of the command list. +// a vertex consists of a floating point s, a floating point t, +// and an integer vertex index. + + +typedef struct +{ + int ident; + int version; + + int skinwidth; + int skinheight; + int framesize; // byte size of each frame + + int num_skins; + int num_xyz; + int num_st; // greater than num_xyz for seams + int num_tris; + int num_glcmds; // dwords in strip/fan command list + int num_frames; + + int ofs_skins; // each skin is a MAX_SKINNAME string + int ofs_st; // byte offset from start for stverts + int ofs_tris; // offset for dtriangles + int ofs_frames; // offset for first frame + int ofs_glcmds; + int ofs_end; // end of file + +} dmdl_t; + +// compressed model +typedef struct dcompmdl_s +{ + dmdl_t header; + short CompressedFrameSize; + short UniqueVerts; + short *remap; + float *translate; // then add this + float *scale; // multiply byte verts by this + char *mat; + char *frames; + char *base; + float *ctranslate; + float *cscale; + char data[1]; +} dcompmdl_t; + +typedef struct +{ + dcompmdl_t compModInfo; + int rootCluster; + int skeletalType; + struct ModelSkeleton_s *skeletons; +} JointedModel_t; + +/* +======================================================================== + +.BK file format + +======================================================================== +*/ + +#define IDBOOKHEADER (('K'<<24)+('O'<<16)+('O'<<8)+'B') +#define BOOK_VERSION 2 + +typedef struct bookframe_s +{ + int x; + int y; + int w; + int h; + char name[MAX_SKINNAME]; // name of gfx file +} bookframe_t; + +typedef struct bookheader_s +{ + unsigned int ident; + unsigned int version; + int num_segments; + int total_w; + int total_h; +} bookheader_t; + +typedef struct book_s +{ + bookheader_t bheader; + bookframe_t bframes[MAX_MD2SKINS]; +} book_t; + +/* +======================================================================== + +.SP2 sprite file format + +======================================================================== +*/ + +#define IDSPRITEHEADER (('2'<<24)+('S'<<16)+('D'<<8)+'I') + // little-endian "IDS2" +#define SPRITE_VERSION 2 + +typedef struct +{ + int width, height; + int origin_x, origin_y; // raster coordinates inside pic + char name[MAX_SKINNAME]; // name of pcx file +} dsprframe_t; + +typedef struct { + int ident; + int version; + int numframes; + dsprframe_t frames[1]; // variable sized +} dsprite_t; + +/* +============================================================================== + + .M8 texture file format + +============================================================================== +*/ + +typedef struct palette_s +{ + union + { + struct + { + byte r,g,b; + }; + }; +} palette_t; + +#define MIP_VERSION 2 +#define PAL_SIZE 256 +#define MIPLEVELS 16 + +typedef struct miptex_s +{ + int version; + char name[32]; + unsigned width[MIPLEVELS], height[MIPLEVELS]; + unsigned offsets[MIPLEVELS]; // four mip maps stored + char animname[32]; // next frame in animation chain + palette_t palette[PAL_SIZE]; + int flags; + int contents; + int value; +} miptex_t; + + + +#define MIP32_VERSION 4 + +typedef struct miptex32_s +{ + int version; + char name[128]; + char altname[128]; // texture substitution + char animname[128]; // next frame in animation chain + char damagename[128]; // image that should be shown when damaged + unsigned width[MIPLEVELS], height[MIPLEVELS]; + unsigned offsets[MIPLEVELS]; + int flags; + int contents; + int value; + float scale_x, scale_y; + int mip_scale; + + // detail texturing info + char dt_name[128]; // detailed texture name + float dt_scale_x, dt_scale_y; + float dt_u, dt_v; + float dt_alpha; + int dt_src_blend_mode, dt_dst_blend_mode; + + int unused[20]; // future expansion to maintain compatibility with h2 +} miptex32_t; + + +/* +============================================================================== + + .BSP file format + +============================================================================== +*/ + +#define IDBSPHEADER (('P'<<24)+('S'<<16)+('B'<<8)+'I') + // little-endian "IBSP" + +#define BSPVERSION 38 + + +// upper design bounds +// leaffaces, leafbrushes, planes, and verts are still bounded by +// 16 bit short limits +#define MAX_MAP_MODELS 1024 +//#define MAX_MAP_BRUSHES 8192 // Quake 2 original +#define MAX_MAP_BRUSHES 10240 +#define MAX_MAP_ENTITIES 2048 +#define MAX_MAP_ENTSTRING 0x40000 +#define MAX_MAP_TEXINFO 8192 + +#define MAX_MAP_AREAS 256 +#define MAX_MAP_AREAPORTALS 1024 +#define MAX_MAP_PLANES 65536 +#define MAX_MAP_NODES 65536 +#define MAX_MAP_BRUSHSIDES 65536 +#define MAX_MAP_LEAFS 65536 +#define MAX_MAP_VERTS 65536 +#define MAX_MAP_FACES 65536 +#define MAX_MAP_LEAFFACES 65536 +#define MAX_MAP_LEAFBRUSHES 65536 +#define MAX_MAP_PORTALS 65536 +#define MAX_MAP_EDGES 128000 +#define MAX_MAP_SURFEDGES 256000 +#define MAX_MAP_LIGHTING 0x200000 +#define MAX_MAP_VISIBILITY 0x180000 + +// key / value pair sizes + +#define MAX_KEY 32 +#define MAX_VALUE 1024 + +//============================================================================= + +typedef struct +{ + int fileofs, filelen; +} lump_t; + +#define LUMP_ENTITIES 0 +#define LUMP_PLANES 1 +#define LUMP_VERTEXES 2 +#define LUMP_VISIBILITY 3 +#define LUMP_NODES 4 +#define LUMP_TEXINFO 5 +#define LUMP_FACES 6 +#define LUMP_LIGHTING 7 +#define LUMP_LEAFS 8 +#define LUMP_LEAFFACES 9 +#define LUMP_LEAFBRUSHES 10 +#define LUMP_EDGES 11 +#define LUMP_SURFEDGES 12 +#define LUMP_MODELS 13 +#define LUMP_BRUSHES 14 +#define LUMP_BRUSHSIDES 15 +#define LUMP_POP 16 +#define LUMP_AREAS 17 +#define LUMP_AREAPORTALS 18 +#define HEADER_LUMPS 19 + +typedef struct +{ + int ident; + int version; + lump_t lumps[HEADER_LUMPS]; +} dheader_t; + +typedef struct +{ + float mins[3], maxs[3]; + float origin[3]; // for sounds or lights + int headnode; + int firstface, numfaces; // submodels just draw faces + // without walking the bsp tree +} dmodel_t; + + +typedef struct +{ + float point[3]; +} dvertex_t; + + +// 0-2 are axial planes +#define PLANE_X 0 +#define PLANE_Y 1 +#define PLANE_Z 2 + +// 3-5 are non-axial planes snapped to the nearest +#define PLANE_ANYX 3 +#define PLANE_ANYY 4 +#define PLANE_ANYZ 5 + +// planes (x&~1) and (x&~1)+1 are allways opposites + +typedef struct +{ + float normal[3]; + float dist; + int type; // PLANE_X - PLANE_ANYZ ?remove? trivial to regenerate +} dplane_t; + + +// contents flags are seperate bits +// a given brush can contribute multiple content bits +// multiple brushes can be in a single leaf + +// These definitions also need to be in q_shared.h! + +// ************************************************************************************************ +// CONTENTS_XXX +// ------------ +// Contents flags. +// ************************************************************************************************ + +// Lower bits are stronger, and will eat weaker brushes completely. + +#define CONTENTS_SOLID 0x00000001 // An eye is never valid in a solid. +#define CONTENTS_WINDOW 0x00000002 // Translucent, but not watery. +#define CONTENTS_AUX 0x00000004 +#define CONTENTS_LAVA 0x00000008 +#define CONTENTS_SLIME 0x00000010 +#define CONTENTS_WATER 0x00000020 +#define CONTENTS_MIST 0x00000040 +#define LAST_VISIBLE_CONTENTS CONTENTS_MIST + +// Remaining contents are non-visible, and don't eat brushes. + +#define CONTENTS_AREAPORTAL 0x00008000 +#define CONTENTS_PLAYERCLIP 0x00010000 +#define CONTENTS_MONSTERCLIP 0x00020000 + +// Currents can be added to any other contents, and may be mixed. + +#define CONTENTS_CURRENT_0 0x00040000 +#define CONTENTS_CURRENT_90 0x00080000 +#define CONTENTS_CURRENT_180 0x00100000 +#define CONTENTS_CURRENT_270 0x00200000 +#define CONTENTS_CURRENT_UP 0x00400000 +#define CONTENTS_CURRENT_DOWN 0x00800000 +#define CONTENTS_ORIGIN 0x01000000 // Removed before bsping an entity. +#define CONTENTS_MONSTER 0x02000000 // Should never be on a brush, only in game. +#define CONTENTS_DEADMONSTER 0x04000000 +#define CONTENTS_DETAIL 0x08000000 // Brushes to be added after vis leaves. +#define CONTENTS_TRANSLUCENT 0x10000000 // Auto set if any surface has transparency. +#define CONTENTS_LADDER 0x20000000 +#define CONTENTS_CAMERANOBLOCK 0x40000000 // Camera LOS ignores any brushes with this flag. + +typedef struct +{ + int planenum; + int children[2]; // negative numbers are -(leafs+1), not nodes + short mins[3]; // for frustom culling + short maxs[3]; + unsigned short firstface; + unsigned short numfaces; // counting both sides +} dnode_t; + + +typedef struct texinfo_s +{ + float vecs[2][4]; // [s/t][xyz offset] + int flags; // miptex flags + overrides + int value; // light emission, etc + char texture[32]; // texture name (textures/*.wal) + int nexttexinfo; // for animations, -1 = end of chain +} texinfo_t; + + +// note that edge 0 is never used, because negative edge nums are used for +// counterclockwise use of the edge in a face +typedef struct +{ + unsigned short v[2]; // vertex numbers +} dedge_t; + +#define MAXLIGHTMAPS 4 +typedef struct +{ + unsigned short planenum; + short side; + + int firstedge; // we must support > 64k edges + short numedges; + short texinfo; + +// lighting info + byte styles[MAXLIGHTMAPS]; + int lightofs; // start of [numstyles*surfsize] samples +} dface_t; + +typedef struct +{ + int contents; // OR of all brushes (not needed?) + + short cluster; + short area; + + short mins[3]; // for frustum culling + short maxs[3]; + + unsigned short firstleafface; + unsigned short numleaffaces; + + unsigned short firstleafbrush; + unsigned short numleafbrushes; +} dleaf_t; + +typedef struct +{ + unsigned short planenum; // facing out of the leaf + short texinfo; +} dbrushside_t; + +typedef struct +{ + int firstside; + int numsides; + int contents; +} dbrush_t; + +#define ANGLE_UP -1 +#define ANGLE_DOWN -2 + + +// the visibility lump consists of a header with a count, then +// byte offsets for the PVS and PHS of each cluster, then the raw +// compressed bit vectors +#define DVIS_PVS 0 +#define DVIS_PHS 1 +typedef struct +{ + int numclusters; + int bitofs[8][2]; // bitofs[numclusters][2] +} dvis_t; + +// each area has a list of portals that lead into other areas +// when portals are closed, other areas may not be visible or +// hearable even if the vis info says that it should be +typedef struct +{ + int portalnum; + int otherarea; +} dareaportal_t; + +typedef struct +{ + int numareaportals; + int firstareaportal; +} darea_t; + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.c new file mode 100644 index 00000000..ddad0fe4 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.c @@ -0,0 +1,124 @@ +/* +Copyright (C) 1999-2006 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 "reference.h" +#include "arrayedlist.h" +#include "resourcemanager.h" +#include "skeletons.h" + +char *referenceRootNames[] = +{ + "elf_Lhandroot",//0 + "elf_Rhandroot", + "elf_Rfootroot", + "elf_Lfootroot", + "elf_Bstaffroot", + "elf_bladeroot", + "elf_hellroot", + "StaffBone",//7 + "SwordBone", + "SpearBone", + "RFootBone", + "LFootBone", + "hp_backroot",//12 + "hp_staffroot", + "hp_lhandroot", + "hp_rhandroot", + "hp_rfootroot", + "hp_lfootroot", + "staffroot",//18 + "rfootroot", + "lfootroot", + "rhandroot", + "lhandroot", + "leyeroot", + "reyeroot" +}; + +int referenceRootNameOffsets[NUM_REFERENCED] = +{ + 0, // CORVUS + 7, // INSECT + 12, // HIGH PRIESTESS + 18, // MORCALAVIN +}; + +int numReferences[NUM_REFERENCED] = +{ + NUM_REFERENCES_CORVUS, + NUM_REFERENCES_INSECT, + NUM_REFERENCES_PRIESTESS, + NUM_REFERENCES_MORK, +}; + +int corvusJointIDs[NUM_REFERENCES_CORVUS] = +{ + CORVUS_UPPERBACK, + CORVUS_UPPERBACK, + -1, + -1, + CORVUS_UPPERBACK, + CORVUS_UPPERBACK, + CORVUS_UPPERBACK, +}; + +int *jointIDs[NUM_REFERENCED] = +{ + corvusJointIDs, +}; + +static ResourceManager_t ReferenceMngr; + +void InitReferenceMngr() +{ +#define REFERENCE_BLOCK_SIZE 8 + char *dummystr = NULL; + + ResMngr_Con(&ReferenceMngr, sizeof(LERPedReferences_t), REFERENCE_BLOCK_SIZE, dummystr); +} + +void ReleaseReferenceMngr() +{ + ResMngr_Des(&ReferenceMngr); +} + +LERPedReferences_t *LERPedReferences_new(int init_refType) +{ + LERPedReferences_t *newRefs; + + newRefs = ResMngr_AllocateResource(&ReferenceMngr, sizeof(*newRefs)); + newRefs->refType = init_refType; + newRefs->jointIDs = jointIDs[init_refType]; + newRefs->lastUpdate = -(REF_MINCULLTIME*2.0); + + memset(newRefs->references, 0, MAX_REFPOINTS*sizeof(Reference_t)); + memset(newRefs->oldReferences, 0, MAX_REFPOINTS*sizeof(Reference_t)); + + return newRefs; +} + +void LERPedReferences_delete(LERPedReferences_t *toDelete) +{ + ResMngr_DeallocateResource(&ReferenceMngr, toDelete, sizeof(*toDelete)); +} + +// end diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.h new file mode 100644 index 00000000..ace3678b --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/reference.h @@ -0,0 +1,126 @@ +/* +Copyright (C) 1999-2006 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 REFERENCE_H +#define REFERENCE_H + +#include "placement.h" + +#define MAX_REFPOINTS 16 +#define REF_MINCULLTIME 1.0 + +typedef struct Reference_s +{ + int activecount; + Placement_t placement; +} Reference_t; + +typedef struct LERPedReferences_s +{ + int refType; + int *jointIDs; + float lastUpdate; + Reference_t references[MAX_REFPOINTS]; + Reference_t oldReferences[MAX_REFPOINTS]; +} LERPedReferences_t; + +// Reference Types +enum { + REF_NULL = -1, + REF_CORVUS,//0 + REF_INSECT,//1 + REF_PRIESTESS,//2 + REF_MORK,//3 + NUM_REFERENCED//4 +}; + +// Corvus Reference Points +enum { + CORVUS_LEFTHAND,//0 + CORVUS_RIGHTHAND, + CORVUS_LEFTFOOT, + CORVUS_RIGHTFOOT, + CORVUS_STAFF, + CORVUS_BLADE, + CORVUS_HELL_HEAD, + NUM_REFERENCES_CORVUS//7 +}; + +// Tchekrik Reference Points +enum { + INSECT_STAFF,//0 + INSECT_SWORD, + INSECT_SPEAR, + INSECT_RIGHTFOOT, + INSECT_LEFTFOOT, + NUM_REFERENCES_INSECT//5 +}; + +// High Priestess Reference Points +enum { + PRIESTESS_BACK,//0 + PRIESTESS_STAFF, + PRIESTESS_LHAND, + PRIESTESS_RHAND, + PRIESTESS_RFOOT, + PRIESTESS_LFOOT, + NUM_REFERENCES_PRIESTESS//6 +}; + +// Morcalavin Reference Points +enum +{ + MORK_STAFFREF,//0 + MORK_RFOOTREF,//1 + MORK_LFOOTREF,//2 + MORK_RHANDREF,//3 + MORK_LHANDREF,//4 + MORK_LEYEREF,//5 + MORK_REYEREF,//6 + NUM_REFERENCES_MORK//7 +}; + +#define CORVUS_LIMBS_MASK ((1 << CORVUS_LEFTHAND) | (1 << CORVUS_RIGHTHAND) | (1 << CORVUS_LEFTFOOT) | (1 << CORVUS_RIGHTFOOT)) +#define CORVUS_WEAPON_MASK ((1 << CORVUS_STAFF) | (1 << CORVUS_BLADE) | (1 << CORVUS_HELL_HEAD)) +#define CORVUS_MASK (CORVUS_LIMBS_MASK | CORVUS_WEAPON_MASK) + +#define INSECT_MASK ((1 << INSECT_STAFF) | (1 << INSECT_SWORD) | (1 << INSECT_SPEAR) | (1 << INSECT_RIGHTFOOT) | (1 << INSECT_LEFTFOOT)) + +#define PRIESTESS_MASK ((1 << PRIESTESS_BACK) | (1 << PRIESTESS_STAFF) | (1 << PRIESTESS_LHAND) | (1 << PRIESTESS_RHAND) | (1 << PRIESTESS_RFOOT) | (1 << PRIESTESS_LFOOT)) + +#define MORK_MASK ((1 << MORK_STAFFREF) | (1 << MORK_RFOOTREF) | (1 << MORK_LFOOTREF) | (1 << MORK_RHANDREF) | (1 << MORK_LHANDREF) | (1 << MORK_LEYEREF) | (1 << MORK_REYEREF)) + +extern char *referenceRootNames[]; +extern int referenceRootNameOffsets[]; +extern int numReferences[]; + +void EnableRefPoints(LERPedReferences_t *refInfo, int mask); +void DisableRefPoints(LERPedReferences_t *refInfo, int mask); + +void InitReferenceMngr(); +void ReleaseReferenceMngr(); + +LERPedReferences_t *LERPedReferences_new(int init_refType); +void LERPedReferences_delete(LERPedReferences_t *toDelete); + +#endif + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.c new file mode 100644 index 00000000..ef5613df --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.c @@ -0,0 +1,159 @@ +/* +Copyright (C) 1999-2006 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 +*/ + + +// +// ResourceManager.c +// + +#include +#include "resourcemanager.h" +#include + +typedef struct ResMngr_Block_s +{ + char *start; + unsigned int size; + struct ResMngr_Block_s *next; +} ResMngr_Block_t; + +static void ResMngr_CreateBlock(ResourceManager_t *resource) +{ + unsigned int _blockSize; + char *block; + char **current; + ResMngr_Block_t *temp; + unsigned int i; + + _blockSize = resource->nodeSize * resource->resPerBlock; + + block = malloc(_blockSize); + + assert(block); + + temp = malloc(sizeof(*temp)); + + temp->start = block; + temp->size = _blockSize; + temp->next = resource->blockList; + + resource->blockList = temp; + + resource->free = (char **)(block); + + current = resource->free; + + for(i = 1; i < resource->resPerBlock; ++i) + { + // set current->next to point to next node + *current = (char *)(current) + resource->nodeSize; + + // set current node to current->next + current = (char **)(*current); + } + + *current = NULL; +} + +H2COMMON_API void ResMngr_Con(ResourceManager_t *resource, size_t init_resSize, unsigned int init_resPerBlock, char *resman_name) +{ + resource->resSize = init_resSize; + + resource->resPerBlock = init_resPerBlock; + + resource->nodeSize = resource->resSize + sizeof(*resource->free); + + resource->blockList = NULL; + + resource->numResourcesAllocated = 0; + + ResMngr_CreateBlock(resource); +} + +H2COMMON_API void ResMngr_Des(ResourceManager_t *resource) +{ + ResMngr_Block_t *toDelete; + +#if 0 + if (resource->numResourcesAllocated) + { + char mess[100]; + sprintf(mess,"Potential memory leak %d bytes unfreed\n",resource->resSize*resource->numResourcesAllocated); + OutputDebugString(mess); + } +#endif + + while(resource->blockList) + { + toDelete = resource->blockList; + resource->blockList = resource->blockList->next; + free(toDelete->start); + free(toDelete); + } +} + +H2COMMON_API void *ResMngr_AllocateResource(ResourceManager_t *resource, size_t size) +{ + char **toPop; + + assert(size == resource->resSize); + + ++resource->numResourcesAllocated; + + assert(resource->free); // constructor not called; possibly due to a static object + // containing a static ResourceManagerFastLarge member being + // constructed before its own static members + + toPop = resource->free; + + // set unallocated to the next node and check for NULL (end of list) + if(!(resource->free = (char **)(*resource->free))) + { // if at end create new block + ResMngr_CreateBlock(resource); + } + + // set next to NULL + *toPop = NULL; + + // return the resource for the node + return (void *)(toPop + 1); +} + +H2COMMON_API void ResMngr_DeallocateResource(ResourceManager_t *resource, void *toDeallocate, size_t size) +{ + char **toPush; + + assert(size == resource->resSize); + + --resource->numResourcesAllocated; + + toPush = (char **)(toDeallocate) - 1; + + assert(resource->free); // see same assert at top of AllocateResource + + // set toPop->next to current unallocated front + *toPush = (char *)(resource->free); + + // set unallocated to the node removed from allocated + resource->free = toPush; +} + +// end diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.h new file mode 100644 index 00000000..e267ecd5 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/resourcemanager.h @@ -0,0 +1,47 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// ResourceManager.h +// + +#include "h2common.h" +#include // needed here for size_t + +typedef struct ResourceManager_s +{ + size_t resSize; + unsigned int resPerBlock; + unsigned int nodeSize; + struct ResMngr_Block_s *blockList; + char **free; + char *ResMan_Name; + + unsigned numResourcesAllocated; + +} ResourceManager_t; + +extern H2COMMON_API void ResMngr_Con(ResourceManager_t *resource, size_t init_resSize, unsigned int init_resPerBlock, char *resman_name); +extern H2COMMON_API void ResMngr_Des(ResourceManager_t *resource); +extern H2COMMON_API void *ResMngr_AllocateResource(ResourceManager_t *resource, size_t size); +extern H2COMMON_API void ResMngr_DeallocateResource(ResourceManager_t *resource, void *toDeallocate, size_t size); + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.c new file mode 100644 index 00000000..1da0b4f1 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.c @@ -0,0 +1,232 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// +// Skeletons.c +// + +#include "skeletons.h" + +char *skeletonRootNames[] = +{ + "RAVEN_ROOT", + "BOX_ROOT", + "BEETLE_ROOT", + "ELFLORD_ROOT", + "PLAGUELF_ROOT", + "ELF_BACKROOT", +}; + +int skeletonRNameOffsets[] = +{ + 0, // RAVEN + 1, // BOX + 2, // BEETLE + 3, // ELFLORD + 4, // PLAGUE ELF + 5, // CORVUS +}; + +char *skeletonJointNames[] = +{ + "RAVEN_LOWERBACK", // 0 + "RAVEN_UPPERBACK", + "RAVEN_NECK", + "BOX_CENTER", // 3 + "BEETLE_NECK", // 4 + "BEETLE_HEAD", + "PLAGUELF_BACKB", // 6 + "PLAGUELF_BACKC", + "PLAGUELF_NECK", + "ELF_BACKB", // 9 + "ELF_BACKC", + "ELF_NECKB", +}; + +int skeletonNameOffsets[] = +{ + 0, // RAVEN + 3, // BOX + 4, // BEETLE + -1, // ELFLORD + 6, // PLAGUE ELF + 9, // CORVUS +}; + +char *skeletonEffectorNames[] = +{ + "BEETLE_EYES", // 0 + "CORVUS_EYES", // 1 +}; + +int skeletonENameOffsets[] = +{ + -1, // RAVEN + -1, // BOX + 0, // BEETLE + -1, // ELFLORD + 1, // PLAGUE ELF +}; + +int numJointsInSkeleton[] = +{ + NUM_JOINTS_RAVEN, + NUM_JOINTS_BOX, + NUM_JOINTS_BEETLE, + NUM_JOINTS_ELFLORD, + NUM_JOINTS_PLAGUE_ELF, + NUM_JOINTS_CORVUS, +}; + +int numNodesInSkeleton[] = +{ + 2, // RAVEN + 0, // BOX + 1, // BEETLE + -1, // ELFLORD + 2, // PLAGUE ELF + 2, // CORVUS +}; + +void CreateRavenSkel(void *g_skeletalJoints, size_t jointSize, struct ArrayedListNode_s *g_jointNodes, int root); +void CreateBoxSkel(void *g_skeletalJoints, size_t jointSize, struct ArrayedListNode_s *g_jointNodes, int root); +void CreateBeetleSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex); +void CreateElfLordSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex); +void CreatePlagueElfSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex); + +CreateSkeleton_t SkeletonCreators[NUM_SKELETONS] = +{ + CreateRavenSkel, + CreateBoxSkel, + CreateBeetleSkel, + CreateElfLordSkel, + CreatePlagueElfSkel, + CreatePlagueElfSkel, // Corvus has the same structure as the Plague Elf +}; + +void CreateRavenSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) +{ + char *root; + int *children; + int nodeIndex; + + root = (char *)g_skeletalJoints + rootIndex * jointSize; + + children = (int *)(root + RAVEN_HEAD * jointSize); + *children = ARRAYEDLISTNODE_NULL; + + nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); + + children = (int *)(root + RAVEN_UPPERBACK * jointSize); + *children = nodeIndex; + + g_jointNodes[nodeIndex].data = rootIndex + RAVEN_HEAD; + g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; + + nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); + + children = (int *)(root + RAVEN_LOWERBACK * jointSize); + *children = nodeIndex; + + g_jointNodes[nodeIndex].data = rootIndex + RAVEN_UPPERBACK; + g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; +} + +void CreateBoxSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) +{ + char *root; + int *children; + + root = (char *)g_skeletalJoints + rootIndex * jointSize; + + children = (int *)(root + RAVEN_HEAD * jointSize); + *children = ARRAYEDLISTNODE_NULL; +} + +void CreateBeetleSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) +{ + char *root; + int *children; + int nodeIndex; + + root = (char *)g_skeletalJoints + rootIndex * jointSize; + + children = (int *)(root + BEETLE_HEAD * jointSize); + *children = ARRAYEDLISTNODE_NULL; + + nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); + + children = (int *)(root + BEETLE_NECK * jointSize); + *children = nodeIndex; + + g_jointNodes[nodeIndex].data = rootIndex + BEETLE_HEAD; + g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; +} + +void CreateElfLordSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) +{ + char *root; + int *children; + int nodeIndex; + + root = (char *)g_skeletalJoints + rootIndex * jointSize; + + children = (int *)(root + BEETLE_HEAD * jointSize); + *children = ARRAYEDLISTNODE_NULL; + + nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); + + children = (int *)(root + BEETLE_NECK * jointSize); + *children = nodeIndex; + + g_jointNodes[nodeIndex].data = rootIndex + BEETLE_HEAD; + g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; +} + +void CreatePlagueElfSkel(void *g_skeletalJoints, size_t jointSize, ArrayedListNode_t *g_jointNodes, int rootIndex) +{ + char *root; + int *children; + int nodeIndex; + + root = (char *)g_skeletalJoints + rootIndex * jointSize; + + children = (int *)(root + PLAGUE_ELF_HEAD * jointSize); + *children = ARRAYEDLISTNODE_NULL; + + nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); + + children = (int *)(root + PLAGUE_ELF_UPPERBACK * jointSize); + *children = nodeIndex; + + g_jointNodes[nodeIndex].data = rootIndex + PLAGUE_ELF_HEAD; + g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; + + nodeIndex = GetFreeNode(g_jointNodes, MAX_ARRAYED_JOINT_NODES); + + children = (int *)(root + PLAGUE_ELF_LOWERBACK * jointSize); + *children = nodeIndex; + + g_jointNodes[nodeIndex].data = rootIndex + PLAGUE_ELF_UPPERBACK; + g_jointNodes[nodeIndex].next = ARRAYEDLISTNODE_NULL; +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.h new file mode 100644 index 00000000..b36c12ed --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qcommon/skeletons.h @@ -0,0 +1,107 @@ +/* +Copyright (C) 1999-2006 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 // for size_t +#include "arrayedlist.h" + +#define JN_YAW_CHANGED 0x00000001 +#define JN_PITCH_CHANGED 0x00000002 +#define JN_ROLL_CHANGED 0x00000004 + +// Skeleton types +enum { + SKEL_NULL = -1, + SKEL_RAVEN = 0, + SKEL_BOX, + SKEL_BEETLE, + SKEL_ELFLORD, + SKEL_PLAGUE_ELF, + SKEL_CORVUS, + NUM_SKELETONS +}; + +// Raven Skeletal joints +enum { + RAVEN_LOWERBACK = 0, + RAVEN_UPPERBACK, + RAVEN_HEAD, + NUM_JOINTS_RAVEN +}; + +// Box Skeletal joints +enum { + BOX_CENTER = 0, + NUM_JOINTS_BOX +}; + +// Beetle Skeletal joints +enum { + BEETLE_NECK = 0, + BEETLE_HEAD, + NUM_JOINTS_BEETLE +}; + +// Elflord Skeletal joints +enum { + ELFLORD_, + ELFLORD__, + NUM_JOINTS_ELFLORD +}; + +// Plague Elf Skeletal joints +enum { + PLAGUE_ELF_LOWERBACK, + PLAGUE_ELF_UPPERBACK, + PLAGUE_ELF_HEAD, + NUM_JOINTS_PLAGUE_ELF +}; + +// Corvus Skeletal joints +enum { + CORVUS_LOWERBACK, + CORVUS_UPPERBACK, + CORVUS_HEAD, + NUM_JOINTS_CORVUS +}; + +#define NO_SWAP_FRAME -1 +#define NULL_ROOT_JOINT -1 + +#define MAX_ARRAYED_SKELETAL_JOINTS 255 // has max of 65,535 (if this remains at 255, net code can be changed to reflect) +#define MAX_ARRAYED_JOINT_NODES (MAX_ARRAYED_SKELETAL_JOINTS - 1) + +#define MAX_JOINTS_PER_SKELETON 8 // arbitrary small number +#define MAX_JOINT_NODES_PER_SKELETON (MAX_JOINTS_PER_SKELETON - 1) + +extern char *skeletonRootNames[]; +extern int skeletonRNameOffsets[]; +extern char *skeletonJointNames[]; +extern int skeletonNameOffsets[]; +extern int numJointsInSkeleton[]; +extern char *skeletonEffectorNames[]; +extern int skeletonENameOffsets[]; +extern int numNodesInSkeleton[]; + +typedef void (*CreateSkeleton_t)(void *skeletalJoints, size_t jointSize, struct ArrayedListNode_s *jointNodes, int rootIndex); + +extern CreateSkeleton_t SkeletonCreators[NUM_SKELETONS]; + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_fmodel.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_fmodel.h new file mode 100644 index 00000000..7ec6570c --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_fmodel.h @@ -0,0 +1,61 @@ +/* +Copyright (C) 1999-2006 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 FMODEL_H +#define FMODEL_H +#include "fmodel.h" +#endif +#include "qd_skeletons.h" + +typedef struct +{ + int numnormals; + vec3_t normalsum; +} fmvertexnormals_t; + +typedef struct +{ + vec3_t v; + int lightnormalindex; + fmvertexnormals_t vnorm; +} fmtrivert_t; + +#define FRAME_NAME_LEN (16) + +typedef struct +{ + vec3_t mins, maxs; + char name[FRAME_NAME_LEN]; + fmtrivert_t v[MAX_FM_VERTS]; + struct QD_SkeletalJoint_s joints[NUM_CLUSTERS]; + struct QD_SkeletalJoint_s references[NUM_REFERENCES]; +} fmframe_t; + +extern fmframe_t g_frames[MAX_FM_FRAMES]; + +extern fmheader_t fmheader; +extern char cdarchive[1024]; // set by $fmcd +extern char cdpartial[1024]; // set by $fmcd +extern char cddir[1024]; // set by $fmcd + +void GrabFrame (char *frame); +void H_printf(char *fmt, ...); +char *FindFrameFile (char *frame); diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.c new file mode 100644 index 00000000..43395c8c --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.c @@ -0,0 +1,1291 @@ +/* +Copyright (C) 1999-2006 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 "qd_skeletons.h" +#include "skeletons.h" +#include "qd_fmodel.h" +#include "angles.h" +#include "token.h" +#include "qdata.h" +#include "reference.h" + +#include +#include +#include + + +// We're assuming no more than 16 reference points, with no more than 32 characters in the name +char RefPointNameList[REF_MAX_POINTS][REF_MAX_STRLEN]; +int RefPointNum = 0; + +Skeletalfmheader_t g_skelModel; + +void ClearSkeletalModel() +{ + g_skelModel.type = SKEL_NULL; + g_skelModel.clustered = false; + g_skelModel.references = REF_NULL; +} + +//========================================================================== +// +// LoadHRCClustered +// +//========================================================================== + +// Places the null terminated src string into the dest string less any trailing digits or underscores +void StripTrailingDigits(char *src, char *dest) +{ +#ifndef NDEBUG + int max = SKELETAL_NAME_MAX; // should be sufficient for inteded use on names from hrc files +#endif + int i = 0; + + while(src[i] != '\0') + { + ++i; +#ifndef NDEBUG + assert(i < max); +#endif + } + + while((src[--i] >= '0' && src[i] <= '9') || src[i] == '_') + { + + } + + memcpy(dest, src, ++i); + + dest[i] = '\0'; +} + +static void LoadHRCClustered(char *fileName, int **clusterList, int *num_verts, int skelType) +{ + extern void HandleHRCModel(triangle_t **triList, int *triangleCount, + mesh_node_t **nodesList, int *num_mesh_nodes, int ActiveNode, int Depth); + + extern mesh_node_t *pmnodes; + + triangle_t *triList; +// mesh_node_t *nodesList; + int num_mesh_nodes = 0, triangleCount = 0; + +#if 0 + int i; + int j, numVerts; + char stripped[SKELETAL_NAME_MAX]; + + for( i = 1; i < numJointsInSkeleton[skelType] + 1; ++i) + { + num_verts[i] = 0; + } + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + + TK_Beyond(TK_CLUSTERS); + + while(TK_Search(TK_CLUSTER_NAME) != TK_EOF) + { + TK_Require(TK_STRING); + + StripTrailingDigits(tk_String, stripped); + + for( i = 0; i < numJointsInSkeleton[skelType]; ++i) + { + if(stricmp(stripped, skeletonJointNames[skeletonNameOffsets[skelType]+i]) == 0) + { + i = -i + numJointsInSkeleton[skelType] - 1; + + TK_BeyondRequire(TK_NUM_CLUSTER_VERTICES, TK_INTNUMBER); + + numVerts = tk_IntNumber; + + if(!num_verts[i+1]) // first set of verts for cluster + { + clusterList[i] = SafeMalloc(numVerts*sizeof(int), "LoadHRCClustered"); + assert(clusterList[i]); + } + else // any later sets of verts need to copy current + { + int *temp; + + temp = SafeMalloc((num_verts[i+1]+numVerts)*sizeof(int), "LoadHRCClustered"); + assert(temp); + + memcpy(temp + numVerts, clusterList[i], num_verts[i+1]*sizeof(int)); + + free(clusterList[i]); + + clusterList[i] = temp; + } + + // currently this function is only called by LoadModelClusters. + // Apparently the matching free has disappeared, + // should probably be free at the end of FMCmd_Base + + TK_Beyond(TK_LBRACE); + + for(j = 0; j < numVerts; ++j) + { + TK_Require(TK_INTNUMBER); + clusterList[i][j] = tk_IntNumber; + TK_Fetch(); + } + + num_verts[i+1] += numVerts; + + break; + } + } + } + + num_verts[0] = numJointsInSkeleton[skelType]; +#endif + +#if 1 // get the index number localized to the root +// for( i = 1; i < numJointsInSkeleton[skelType] + 1; ++i) +// { +// g_skelModel.num_verts[i] = 0; +// } + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + + // prime it + TK_Beyond(TK_MODEL); + + triList = (triangle_t *) SafeMalloc(MAXTRIANGLES*sizeof(triangle_t), "Triangle list"); + memset(triList,0,MAXTRIANGLES*sizeof(triangle_t)); +// nodesList = SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); + pmnodes = (mesh_node_t *) SafeMalloc(MAX_FM_MESH_NODES * sizeof(mesh_node_t), "Mesh Node List"); + + memset(pmnodes, 0, MAX_FM_MESH_NODES * sizeof(mesh_node_t)); + + // this should eventually use a stripped down version of this + HandleHRCModel(&triList, &triangleCount, &pmnodes, &num_mesh_nodes, 0, 0); + +// free(nodesList); + free(triList); + + num_verts[0] = numJointsInSkeleton[skelType]; +#endif +} + +void ReadHRCClusterList(mesh_node_t *meshNode, int baseIndex) +{ + int i, j, numVerts; + tokenType_t nextToken; + char stripped[SKELETAL_NAME_MAX]; + + meshNode->clustered = true; + + nextToken = TK_Get(TK_CLUSTER_NAME); + + while (nextToken == TK_CLUSTER_NAME) + { + TK_FetchRequire(TK_STRING); + + StripTrailingDigits(tk_String, stripped); + + for( i = 0; i < numJointsInSkeleton[g_skelModel.type]; ++i) + { + if(stricmp(stripped, skeletonJointNames[skeletonNameOffsets[g_skelModel.type]+i]) == 0) + { + i = -i + numJointsInSkeleton[g_skelModel.type] - 1; + + TK_BeyondRequire(TK_NUM_CLUSTER_VERTICES, TK_INTNUMBER); + + numVerts = tk_IntNumber; + + if(!baseIndex) + { + meshNode->clusters[i] = (int *) SafeMalloc(numVerts*sizeof(int), "ReadHRCClusterList"); + assert(meshNode->clusters[i]); + } + else + { + int *temp; + + temp = meshNode->clusters[i]; + meshNode->clusters[i] = (int *) SafeMalloc((meshNode->num_verts[i+1]+numVerts)*sizeof(int), "ReadHRCClusterList"); + assert(meshNode->clusters[i]); + + memcpy(meshNode->clusters[i], temp, meshNode->num_verts[i+1]*sizeof(int)); + free(temp); + } + + // currently this function is only called by LoadModelClusters. + // Apparently the matching free has disappeared, + // should probably be free at the end of FMCmd_Base + + TK_Beyond(TK_LBRACE); + + for(j = 0; j < numVerts; ++j) + { + TK_Require(TK_INTNUMBER); + meshNode->clusters[i][baseIndex+j] = tk_IntNumber+baseIndex; + TK_Fetch(); + } + + if(baseIndex) + { + meshNode->num_verts[i+1] += numVerts; + } + else + { + meshNode->num_verts[i+1] = numVerts; + } + + break; + } + } + + TK_BeyondRequire(TK_CLUSTER_STATE, TK_INTNUMBER); + nextToken = TK_Fetch(); + } +} + +static void LoadHRCGlobals(char *fileName) +{ + int i; + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + TK_Beyond(TK_MODEL); + + TK_Beyond(TK_SCALING); + for(i = 0; i < 3; i++) + { + TK_Require(TK_FLOATNUMBER); + g_skelModel.scaling[i] = tk_FloatNumber; + TK_Fetch(); + } + + TK_Beyond(TK_ROTATION); + for(i = 0; i < 3; i++) + { + TK_Require(TK_FLOATNUMBER); + g_skelModel.rotation[i] = tk_FloatNumber; + TK_Fetch(); + } + + TK_Beyond(TK_TRANSLATION); + for(i = 0; i < 3; i++) + { + TK_Require(TK_FLOATNUMBER); + g_skelModel.translation[i] = tk_FloatNumber; + TK_Fetch(); + } +} + +static void ParseVec3(vec3_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void ParseVec3d(vec3d_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void ParseRotation3(vec3_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void ParseRotation3d(vec3d_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void ParseTranslation3(vec3_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void ParseTranslation3d(vec3d_t in) +{ + TK_Require(TK_FLOATNUMBER); + in[1] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[2] = tk_FloatNumber; + TK_FetchRequire(TK_FLOATNUMBER); + in[0] = tk_FloatNumber; +} + +static void LoadHRCJointList(char *fileName, QD_SkeletalJoint_t *jointList, int skelType) +{ +#define MAX_STACK 64 + int i, j; + vec3d_t curTranslation[MAX_STACK], curRotation[MAX_STACK], curScale[MAX_STACK]; + int curCorrespondingJoint[MAX_STACK]; + int currentStack = 0, stackSize; + double cx, sx, cy, sy, cz, sz; + double rx, ry, rz; + double x2, y2, z2; + char stripped[SKELETAL_NAME_MAX]; + Placement_d_t *placement; + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + + TK_Beyond(TK_MODEL); + + while(TK_Search(TK_NAME) != TK_EOF) + { + TK_Require(TK_STRING); + + StripTrailingDigits(tk_String, stripped); + + if(stricmp(stripped, skeletonRootNames[skeletonRNameOffsets[skelType]]) == 0) + { + break; + } + } + + if(tk_Token == TK_EOF) + { + Error("Bone Chain Root: %s not found\n", skeletonRootNames[skeletonRNameOffsets[skelType]]); + return; + } + + TK_Beyond(TK_SCALING); + + ParseVec3d(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3d(curRotation[currentStack]); + + TK_Beyond(TK_TRANSLATION); + + ParseVec3d(curTranslation[currentStack]); + + // account for global model translation + curTranslation[currentStack][1] += g_skelModel.translation[0]; + curTranslation[currentStack][2] += g_skelModel.translation[1]; + curTranslation[currentStack][0] += g_skelModel.translation[2]; + + curCorrespondingJoint[currentStack] = -1; + + ++currentStack; + + for(i = 0; i < numJointsInSkeleton[skelType]; ++i) + { + while(1) + { + TK_Beyond(TK_MODEL); + + TK_BeyondRequire(TK_NAME, TK_STRING); + + StripTrailingDigits(tk_String, stripped); + + if(stricmp(stripped, skeletonJointNames[skeletonNameOffsets[skelType]+i]) == 0) + break; + + TK_Beyond(TK_SCALING); + + ParseVec3d(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3d(curRotation[currentStack]); + + TK_Beyond(TK_TRANSLATION); + + ParseVec3d(curTranslation[currentStack]); + + curCorrespondingJoint[currentStack] = -1; + + ++currentStack; + } + + TK_Beyond(TK_SCALING); + + ParseVec3d(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3d(curRotation[currentStack]); + + jointList[i].rotation[1] = curRotation[currentStack][1]; + jointList[i].rotation[2] = curRotation[currentStack][2]; + jointList[i].rotation[0] = curRotation[currentStack][0]; + + TK_Beyond(TK_TRANSLATION); + + ParseVec3d(curTranslation[currentStack]); + +// jointList[i].placement.origin[1] = curTranslation[currentStack][1]; +// jointList[i].placement.origin[2] = curTranslation[currentStack][2]; +// jointList[i].placement.origin[0] = curTranslation[currentStack][0]; + + jointList[i].placement.origin[1] = 0.0; + jointList[i].placement.origin[2] = 0.0; + jointList[i].placement.origin[0] = 0.0; + + jointList[i].placement.direction[1] = 20.0; + jointList[i].placement.direction[2] = 0.0; + jointList[i].placement.direction[0] = 0.0; + + jointList[i].placement.up[1] = 0.0; + jointList[i].placement.up[2] = 20.0; + jointList[i].placement.up[0] = 0.0; + + curCorrespondingJoint[currentStack] = i; + + ++currentStack; + } + + stackSize = currentStack; + +#if 0 + // rotate the direction and up vectors to correspond to the rotation + for(i = 0; i < numJointsInSkeleton[skelType]; ++i) + { + rx = jointList[i].rotation[0]*ANGLE_TO_RAD; + ry = jointList[i].rotation[1]*ANGLE_TO_RAD; + rz = jointList[i].rotation[2]*ANGLE_TO_RAD; + + cx = cos(rx); + sx = sin(rx); + + cy = cos(ry); + sy = sin(ry); + + cz = cos(rz); + sz = sin(rz); + + // y-axis rotation for direction + x2 = jointList[i].placement.direction[0]*cy+jointList[i].placement.direction[2]*sy; + z2 = -jointList[i].placement.direction[0]*sy+jointList[i].placement.direction[2]*cy; + jointList[i].placement.direction[0] = x2; + jointList[i].placement.direction[2] = z2; + + // y-axis rotation for up + x2 = jointList[i].placement.up[0]*cy+jointList[i].placement.up[2]*sy; + z2 = -jointList[i].placement.up[0]*sy+jointList[i].placement.up[2]*cy; + jointList[i].placement.up[0] = x2; + jointList[i].placement.up[2] = z2; + + // z-axis rotation for direction + x2 = jointList[i].placement.direction[0]*cz-jointList[i].placement.direction[1]*sz; + y2 = jointList[i].placement.direction[0]*sz+jointList[i].placement.direction[1]*cz; + jointList[i].placement.direction[0] = x2; + jointList[i].placement.direction[1] = y2; + + // z-axis rotation for up + x2 = jointList[i].placement.up[0]*cz-jointList[i].placement.up[1]*sz; + y2 = jointList[i].placement.up[0]*sz+jointList[i].placement.up[1]*cz; + jointList[i].placement.up[0] = x2; + jointList[i].placement.up[1] = y2; + + // x-axis rotation for direction vector + y2 = jointList[i].placement.direction[1]*cx-jointList[i].placement.direction[2]*sx; + z2 = jointList[i].placement.direction[1]*sx+jointList[i].placement.direction[2]*cx; + jointList[i].placement.direction[1] = y2; + jointList[i].placement.direction[2] = z2; + + // x-axis rotation for up vector + y2 = jointList[i].placement.up[1]*cx-jointList[i].placement.up[2]*sx; + z2 = jointList[i].placement.up[1]*sx+jointList[i].placement.up[2]*cx; + jointList[i].placement.up[1] = y2; + jointList[i].placement.up[2] = z2; + + // translate direction to a point in the model + jointList[i].placement.direction[0] += jointList[i].placement.origin[0]; + jointList[i].placement.direction[1] += jointList[i].placement.origin[1]; + jointList[i].placement.direction[2] += jointList[i].placement.origin[2]; + + // translate up to a point in the model + jointList[i].placement.up[0] += jointList[i].placement.origin[0]; + jointList[i].placement.up[1] += jointList[i].placement.origin[1]; + jointList[i].placement.up[2] += jointList[i].placement.origin[2]; + } +#endif + + for(i = stackSize - 1; i >= 0; --i) + { + rx = curRotation[i][0]*ANGLE_TO_RAD; + ry = curRotation[i][1]*ANGLE_TO_RAD; + rz = curRotation[i][2]*ANGLE_TO_RAD; + + cx = cos(rx); + sx = sin(rx); + + cy = cos(ry); + sy = sin(ry); + + cz = cos(rz); + sz = sin(rz); + +#if 1 + for(j = i; j < stackSize; ++j) + { + if(curCorrespondingJoint[j] != -1) + { + placement = &jointList[curCorrespondingJoint[j]].placement; + + // y-axis rotation for origin + x2 = placement->origin[0]*cy+placement->origin[2]*sy; + z2 = -placement->origin[0]*sy+placement->origin[2]*cy; + placement->origin[0] = x2; + placement->origin[2] = z2; + + // y-axis rotation for direction + x2 = placement->direction[0]*cy+placement->direction[2]*sy; + z2 = -placement->direction[0]*sy+placement->direction[2]*cy; + placement->direction[0] = x2; + placement->direction[2] = z2; + + // y-axis rotation for up + x2 = placement->up[0]*cy+placement->up[2]*sy; + z2 = -placement->up[0]*sy+placement->up[2]*cy; + placement->up[0] = x2; + placement->up[2] = z2; + + // z-axis rotation for origin + x2 = placement->origin[0]*cz-placement->origin[1]*sz; + y2 = placement->origin[0]*sz+placement->origin[1]*cz; + placement->origin[0] = x2; + placement->origin[1] = y2; + + // z-axis rotation for direction + x2 = placement->direction[0]*cz-placement->direction[1]*sz; + y2 = placement->direction[0]*sz+placement->direction[1]*cz; + placement->direction[0] = x2; + placement->direction[1] = y2; + + // z-axis rotation for up + x2 = placement->up[0]*cz-placement->up[1]*sz; + y2 = placement->up[0]*sz+placement->up[1]*cz; + placement->up[0] = x2; + placement->up[1] = y2; + + // x-axis rotation for origin + y2 = placement->origin[1]*cx-placement->origin[2]*sx; + z2 = placement->origin[1]*sx+placement->origin[2]*cx; + placement->origin[1] = y2; + placement->origin[2] = z2; + + // x-axis rotation for direction vector + y2 = placement->direction[1]*cx-placement->direction[2]*sx; + z2 = placement->direction[1]*sx+placement->direction[2]*cx; + placement->direction[1] = y2; + placement->direction[2] = z2; + + // x-axis rotation for up vector + y2 = placement->up[1]*cx-placement->up[2]*sx; + z2 = placement->up[1]*sx+placement->up[2]*cx; + placement->up[1] = y2; + placement->up[2] = z2; + + // translate origin + placement->origin[0] += curTranslation[i][0]; + placement->origin[1] += curTranslation[i][1]; + placement->origin[2] += curTranslation[i][2]; + + // translate back to local coord + placement->direction[0] += curTranslation[i][0]; + placement->direction[1] += curTranslation[i][1]; + placement->direction[2] += curTranslation[i][2]; + + // translate back to local coord + placement->up[0] += curTranslation[i][0]; + placement->up[1] += curTranslation[i][1]; + placement->up[2] += curTranslation[i][2]; + } + } +#else + // This screwed up and needs to be sorted out!!! + // The stack info needs to be written too instead of the jointList for j > numJoints for Skeleton + for(j = i-1; j < stackSize-1; ++j) + { + // y-axis rotation for origin + x2 = jointList[j].placement.origin[0]*cy+jointList[j].placement.origin[2]*sy; + z2 = -jointList[j].placement.origin[0]*sy+jointList[j].placement.origin[2]*cy; + jointList[j].placement.origin[0] = x2; + jointList[j].placement.origin[2] = z2; + + // y-axis rotation for direction + x2 = jointList[j].placement.direction[0]*cy+jointList[j].placement.direction[2]*sy; + z2 = -jointList[j].placement.direction[0]*sy+jointList[j].placement.direction[2]*cy; + jointList[j].placement.direction[0] = x2; + jointList[j].placement.direction[2] = z2; + + // y-axis rotation for up + x2 = jointList[j].placement.up[0]*cy+jointList[j].placement.up[2]*sy; + z2 = -jointList[j].placement.up[0]*sy+jointList[j].placement.up[2]*cy; + jointList[j].placement.up[0] = x2; + jointList[j].placement.up[2] = z2; + + // z-axis rotation for origin + x2 = jointList[j].placement.origin[0]*cz-jointList[j].placement.origin[1]*sz; + y2 = jointList[j].placement.origin[0]*sz+jointList[j].placement.origin[1]*cz; + jointList[j].placement.origin[0] = x2; + jointList[j].placement.origin[1] = y2; + + // z-axis rotation for direction + x2 = jointList[j].placement.direction[0]*cz-jointList[j].placement.direction[1]*sz; + y2 = jointList[j].placement.direction[0]*sz+jointList[j].placement.direction[1]*cz; + jointList[j].placement.direction[0] = x2; + jointList[j].placement.direction[1] = y2; + + // z-axis rotation for up + x2 = jointList[j].placement.up[0]*cz-jointList[j].placement.up[1]*sz; + y2 = jointList[j].placement.up[0]*sz+jointList[j].placement.up[1]*cz; + jointList[j].placement.up[0] = x2; + jointList[j].placement.up[1] = y2; + + // x-axis rotation for origin + y2 = jointList[j].placement.origin[1]*cx-jointList[j].placement.origin[2]*sx; + z2 = jointList[j].placement.origin[1]*sx+jointList[j].placement.origin[2]*cx; + jointList[j].placement.origin[1] = y2; + jointList[j].placement.origin[2] = z2; + + // x-axis rotation for direction vector + y2 = jointList[j].placement.direction[1]*cx-jointList[j].placement.direction[2]*sx; + z2 = jointList[j].placement.direction[1]*sx+jointList[j].placement.direction[2]*cx; + jointList[j].placement.direction[1] = y2; + jointList[j].placement.direction[2] = z2; + + // x-axis rotation for up vector + y2 = jointList[j].placement.up[1]*cx-jointList[j].placement.up[2]*sx; + z2 = jointList[j].placement.up[1]*sx+jointList[j].placement.up[2]*cx; + jointList[j].placement.up[1] = y2; + jointList[j].placement.up[2] = z2; + + if(curCorrespondingJoint[j+1] != -1) + { + // translate origin + jointList[j].placement.origin[0] += curTranslation[i-1][0]; + jointList[j].placement.origin[1] += curTranslation[i-1][1]; + jointList[j].placement.origin[2] += curTranslation[i-1][2]; + + // translate back to local coord + jointList[j].placement.direction[0] += curTranslation[i-1][0]; + jointList[j].placement.direction[1] += curTranslation[i-1][1]; + jointList[j].placement.direction[2] += curTranslation[i-1][2]; + + // translate back to local coord + jointList[j].placement.up[0] += curTranslation[i-1][0]; + jointList[j].placement.up[1] += curTranslation[i-1][1]; + jointList[j].placement.up[2] += curTranslation[i-1][2]; + } + } +#endif + } +} + +void LoadModelTransform(char *fileName) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + + LoadHRCGlobals(InputFileName); + + printf(" - assuming .HRC\n"); + return; + } + + Error("\n Could not open file '%s':\n" + "No HRC match.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { +// printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRCGlobals(fileName); + return; + } + } + + Error("Could not open file '%s':\n",fileName); + } +} + +void LoadModelClusters(char *fileName, int **clusterList, int *num_verts, int skelType) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + + LoadHRCClustered(InputFileName, clusterList, num_verts, skelType); + + printf(" - assuming .HRC\n"); + return; + } + + Error("\n Could not open file '%s':\n" + "No HRC match.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { +// printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRCClustered(fileName, clusterList, num_verts, skelType); + return; + } + } + + Error("Could not open file '%s':\n",fileName); + } +} + +void LoadSkeleton(char *fileName, QD_SkeletalJoint_t *jointList, int skelType) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + + LoadHRCJointList(InputFileName, jointList, skelType); + + printf(" - assuming .HRC\n"); + return; + } + + Error("\n Could not open file '%s':\n" + "No HRC.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { +// printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRCJointList(fileName, jointList, skelType); + + return; + } + } + + Error("Could not open file '%s':\n",fileName); + } +} + +/* +=============== +GrabSkeletalFrame +=============== +*/ +void GrabSkeletalFrame(char *frame) +{ + char file1[1024]; + char *framefile; + fmframe_t *fr; + + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + + printf ("Grabbing Skeletal Frame %s\n", file1); + + fr = &g_frames[fmheader.num_frames - 1]; // last frame read in + + LoadSkeleton(file1, fr->joints, g_skelModel.type); +} + +/* +=============== +GrabModelTransform +=============== +*/ +void GrabModelTransform(char *frame) +{ + char file1[1024]; + char *framefile; + fmframe_t *fr; + + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + +// printf ("grabbing %s\n", file1); + + fr = &g_frames[fmheader.num_frames - 1]; // last frame read in + + LoadModelTransform(file1); +} + +void Cmd_FMCluster() +{ + char file1[1024]; + + GetScriptToken (false); + + printf ("---------------------\n"); + sprintf (file1, "%s/%s", cdpartial, token); + printf ("%s\n", file1); + + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s", cddir, token); + + g_skelModel.clustered = -1; + + LoadModelClusters(file1, (int **)&g_skelModel.clusters, (int *)&g_skelModel.num_verts, g_skelModel.type); + + g_skelModel.new_num_verts[0] = g_skelModel.num_verts[0]; + + g_skelModel.clustered = true; +} + +void Cmd_FMSkeleton() +{ + GetScriptToken (false); + g_skelModel.type = atoi(token); +} + +void Cmd_FMSkeletalFrame() +{ + while (ScriptTokenAvailable()) + { + GetScriptToken (false); + if (g_skipmodel) + { + GetScriptToken (false); + continue; + } + if (g_release || g_archive) + { + fmheader.num_frames = 1; // don't skip the writeout + GetScriptToken (false); + continue; + } + + H_printf("#define FRAME_%-16s\t%i\n", token, fmheader.num_frames); + + GrabModelTransform (token); + GrabFrame (token); + GrabSkeletalFrame (token); + + // need to add the up and dir points to the frame bounds here + // using AddPointToBounds (ptrivert[index_xyz].v, fr->mins, fr->maxs); + // then remove fudge in determining scale on frame write out + } +} + +static void LoadHRCReferences(char *fileName, fmframe_t *fr) +{ +#define MAX_STACK 64 + int i, j, k; + vec3d_t curTranslation[MAX_STACK], curRotation[MAX_STACK]; + int curCorrespondingJoint[MAX_STACK]; + int currentStack, stackSize; + double cx, sx, cy, sy, cz, sz; + double rx, ry, rz; + double x2, y2, z2; + char stripped[SKELETAL_NAME_MAX]; + Placement_d_t *placement; + int refnum; + + TK_OpenSource(fileName); + TK_FetchRequire(TK_HRCH); + TK_FetchRequire(TK_COLON); + TK_FetchRequire(TK_SOFTIMAGE); + + if (RefPointNum <= 0) + { // There were no labels indicated in the QDT, so use the hard-coded stuff. + refnum = numReferences[g_skelModel.references]; + } + else + { + refnum = RefPointNum; + } + + for(k = 0; k < refnum; ++k) + { + currentStack = 0; + + // Load the root to get translation and initial rotation +// TK_Beyond(TK_MODEL); + + while(TK_Search(TK_NAME) != TK_EOF) + { + TK_Require(TK_STRING); + + StripTrailingDigits(tk_String, stripped); + + if (RefPointNum == 0) + { // Hard coded refpoint labels + if(stricmp(stripped, + referenceRootNames[referenceRootNameOffsets[g_skelModel.references]+k]) == 0) + { + break; + } + } + else + { // labels indicated by the QDT + if(stricmp(stripped, RefPointNameList[k]) == 0) + { + break; + } + } + } + + if(tk_Token == TK_EOF) + { + if (RefPointNum == 0) + { // Hard coded refpoint labels + Error("Bone Chain Root: %s not found\n", referenceRootNames[referenceRootNameOffsets[g_skelModel.references]]); + } + else + { // labels indicated by the QDT + Error("Bone Chain Root: %s not found\n", RefPointNameList[k]); + } + return; + } + +// TK_Beyond(TK_SCALING); + +// ParseVec3d(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3d(curRotation[currentStack]); + + TK_Beyond(TK_TRANSLATION); + + ParseVec3d(curTranslation[currentStack]); + + // account for global model translation + curTranslation[currentStack][1] += g_skelModel.translation[0]; + curTranslation[currentStack][2] += g_skelModel.translation[1]; + curTranslation[currentStack][0] += g_skelModel.translation[2]; + + curCorrespondingJoint[currentStack] = -1; + +// rjr - this one not needed, as there is also a stack increment 20 lines below??? +// ++currentStack; + + // Load the joint to get orientation + TK_Beyond(TK_MODEL); + +// TK_Beyond(TK_SCALING); + +// ParseVec3d(curScale[currentStack]); + + TK_Beyond(TK_ROTATION); + + ParseRotation3d(curRotation[currentStack]); + +// TK_Beyond(TK_TRANSLATION); + +// ParseVec3d(curTranslation[currentStack]); + + fr->references[k].placement.origin[1] = 0.0; + fr->references[k].placement.origin[2] = 0.0; + fr->references[k].placement.origin[0] = 0.0; + + fr->references[k].placement.direction[1] = 20.0; + fr->references[k].placement.direction[2] = 0.0; + fr->references[k].placement.direction[0] = 0.0; + + fr->references[k].placement.up[1] = 0.0; + fr->references[k].placement.up[2] = 20.0; + fr->references[k].placement.up[0] = 0.0; + + curCorrespondingJoint[currentStack] = k; + + ++currentStack; + + stackSize = currentStack; + + for(i = stackSize - 1; i >= 0; --i) + { + rx = curRotation[i][0]*ANGLE_TO_RAD; + ry = curRotation[i][1]*ANGLE_TO_RAD; + rz = curRotation[i][2]*ANGLE_TO_RAD; + + cx = cos(rx); + sx = sin(rx); + + cy = cos(ry); + sy = sin(ry); + + cz = cos(rz); + sz = sin(rz); + + for(j = i; j < stackSize; ++j) + { + if(curCorrespondingJoint[j] != -1) + { + placement = &fr->references[curCorrespondingJoint[j]].placement; + + // y-axis rotation for origin + x2 = placement->origin[0]*cy+placement->origin[2]*sy; + z2 = -placement->origin[0]*sy+placement->origin[2]*cy; + placement->origin[0] = x2; + placement->origin[2] = z2; + + // y-axis rotation for direction + x2 = placement->direction[0]*cy+placement->direction[2]*sy; + z2 = -placement->direction[0]*sy+placement->direction[2]*cy; + placement->direction[0] = x2; + placement->direction[2] = z2; + + // y-axis rotation for up + x2 = placement->up[0]*cy+placement->up[2]*sy; + z2 = -placement->up[0]*sy+placement->up[2]*cy; + placement->up[0] = x2; + placement->up[2] = z2; + + // z-axis rotation for origin + x2 = placement->origin[0]*cz-placement->origin[1]*sz; + y2 = placement->origin[0]*sz+placement->origin[1]*cz; + placement->origin[0] = x2; + placement->origin[1] = y2; + + // z-axis rotation for direction + x2 = placement->direction[0]*cz-placement->direction[1]*sz; + y2 = placement->direction[0]*sz+placement->direction[1]*cz; + placement->direction[0] = x2; + placement->direction[1] = y2; + + // z-axis rotation for up + x2 = placement->up[0]*cz-placement->up[1]*sz; + y2 = placement->up[0]*sz+placement->up[1]*cz; + placement->up[0] = x2; + placement->up[1] = y2; + + // x-axis rotation for origin + y2 = placement->origin[1]*cx-placement->origin[2]*sx; + z2 = placement->origin[1]*sx+placement->origin[2]*cx; + placement->origin[1] = y2; + placement->origin[2] = z2; + + // x-axis rotation for direction vector + y2 = placement->direction[1]*cx-placement->direction[2]*sx; + z2 = placement->direction[1]*sx+placement->direction[2]*cx; + placement->direction[1] = y2; + placement->direction[2] = z2; + + // x-axis rotation for up vector + y2 = placement->up[1]*cx-placement->up[2]*sx; + z2 = placement->up[1]*sx+placement->up[2]*cx; + placement->up[1] = y2; + placement->up[2] = z2; + + // translate origin + placement->origin[0] += curTranslation[i][0]; + placement->origin[1] += curTranslation[i][1]; + placement->origin[2] += curTranslation[i][2]; + + // translate back to local coord + placement->direction[0] += curTranslation[i][0]; + placement->direction[1] += curTranslation[i][1]; + placement->direction[2] += curTranslation[i][2]; + + // translate back to local coord + placement->up[0] += curTranslation[i][0]; + placement->up[1] += curTranslation[i][1]; + placement->up[2] += curTranslation[i][2]; + + } + } + } + printf("%f, %f, %f\n", placement->origin[0], placement->origin[1], placement->origin[2]); + } + printf("\n"); +} + +void Cmd_FMReferenced() +{ + int i; + + GetScriptToken (false); + g_skelModel.references = atoi(token); + + // Guess what? Now, we now want a list of strings to look for here instead of a hard-coded list + for (i=0; i 0) + { + printf("Searching for %d different reference points.\n", RefPointNum); + } + else + { + printf("Using built-in reference points.\n"); + } + +} + +void LoadReferences(char *fileName, fmframe_t *fr) +{ + FILE *file1; + int dot = '.'; + char *dotstart; + char InputFileName[256]; + + dotstart = strrchr(fileName,dot); // Does it already have an extension on the file name? + + if (!dotstart) + { + strcpy(InputFileName, fileName); + strcat(InputFileName, ".hrc"); + if((file1 = fopen(InputFileName, "rb")) != NULL) + { + fclose(file1); + + LoadHRCReferences(InputFileName, fr); + + printf(" - assuming .HRC\n"); + return; + } + + Error("\n Could not open file '%s':\n" + "No HRC.\n", fileName); + } + else + { + if((file1 = fopen(fileName, "rb")) != NULL) + { + printf("\n"); + fclose(file1); + if (strcmp(dotstart,".hrc") == 0 || strcmp(dotstart,".HRC") == 0) + { + LoadHRCReferences(fileName, fr); + + return; + } + } + + Error("Could not open file '%s':\n",fileName); + } +} + +void GrabReferencedFrame(char *frame) +{ + char file1[1024]; + char *framefile; + fmframe_t *fr; + + framefile = FindFrameFile (frame); + + sprintf (file1, "%s/%s", cdarchive, framefile); + ExpandPathAndArchive (file1); + + sprintf (file1, "%s/%s",cddir, framefile); + + printf ("Grabbing Referenced %s\n", file1); + + fr = &g_frames[fmheader.num_frames - 1]; // last frame read in + + LoadReferences(file1, fr); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.h new file mode 100644 index 00000000..b6ff7bcd --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qd_skeletons.h @@ -0,0 +1,84 @@ +/* +Copyright (C) 1999-2006 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 QD_SKELETONS_H +#define QD_SKELETONS_H + +#include "placement.h" + + +typedef struct Placement_d_s +{ + vec3d_t origin; + vec3d_t direction; + vec3d_t up; +} Placement_d_t; + +typedef struct QD_SkeletalJoint_s +{ + Placement_d_t placement; + vec3d_t rotation; +} QD_SkeletalJoint_t; + +#define NUM_CLUSTERS 8 + +typedef struct IntListNode_s +{ + int data; + struct IntListNode_s *next; +} IntListNode_t; // gaak + +typedef struct Skeletalfmheader_s +{ + int type; + int clustered; + int references; + + int *clusters[NUM_CLUSTERS]; + IntListNode_t *vertLists[NUM_CLUSTERS]; + int num_verts[NUM_CLUSTERS + 1]; + int new_num_verts[NUM_CLUSTERS + 1]; + + float scaling[3]; + float rotation[3]; + float translation[3]; +} Skeletalfmheader_t; + +#define SKELETAL_NAME_MAX 32 + +extern Skeletalfmheader_t g_skelModel; + +void ClearSkeletalModel(); +void GrabModelTransform(char *frame); +void GrabSkeletalFrame(char *frame); +void GrabReferencedFrame(char *frame); + +// Reference Stuff +#define NUM_REFERENCES 8 + +#define REF_MAX_POINTS 16 +#define REF_MAX_STRLEN 32 + +// We're assuming no more than 16 reference points, with no more than 32 characters in the name +extern char RefPointNameList[REF_MAX_POINTS][REF_MAX_STRLEN]; +extern int RefPointNum; + +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qdata.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qdata.c new file mode 100644 index 00000000..0a939b16 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/qdata.c @@ -0,0 +1,735 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" +#include "md4.h" + +void TK_Init(); + +qboolean g_compress_pak; +qboolean g_release; // don't grab, copy output data to new tree +qboolean g_pak; // if true, copy to pak instead of release +char g_releasedir[1024]; // c:\quake2\baseq2, etc +qboolean g_archive; // don't grab, copy source data to new tree +qboolean do3ds; +char g_only[256]; // if set, only grab this cd +qboolean g_skipmodel; // set true when a cd is not g_only +int g_forcemodel = MODEL_AUTO; +qboolean g_verbose = false; +qboolean g_allow_newskin = true; +qboolean g_ignoreTriUV = false; +qboolean g_publishOutput = false; + +char *ext_3ds = "3ds"; +char *ext_tri= "tri"; +char *trifileext; + +char g_materialFile[256] = "none"; // default for Heretic2 +char *g_outputDir; +extern char *g_publishDir; + +extern qboolean g_nomkdir; + +/* +======================================================= + + PAK FILES + +======================================================= +*/ + +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; + + + +/* +============== +BeginPak +============== +*/ +void BeginPak (char *outname) +{ + if (!g_pak) + return; + + pakfile = SafeOpenWrite (outname); + + // leave space for header + SafeWrite (pakfile, &pakheader, sizeof(pakheader)); + + pf = pfiles; +} + + +/* +============== +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) +{ + int len; + byte *buf; + char source[1024]; + char dest[1024]; + + if (!g_release) + return; + + sprintf (source, "%s%s", gamedir, filename); + + if (!g_pak) + { // copy it + sprintf (dest, "%s/%s", g_releasedir, filename); + printf ("copying to %s\n", dest); + QCopyFile (source, dest); + return; + } + + // pak it + printf ("paking %s\n", filename); + if (strlen(filename) >= sizeof(pf->name)) + Error ("Filename too long for pak: %s", filename); + + len = LoadFile (source, (void **)&buf); + + // segment moved to old.c + + strcpy (pf->name, filename); + pf->filepos = LittleLong(ftell(pakfile)); + pf->filelen = LittleLong(len); + pf++; + + SafeWrite (pakfile, buf, len); + + free (buf); +} + + +/* +============== +FinishPak +============== +*/ +void FinishPak (void) +{ + int dirlen; + int d; + int i; + unsigned checksum; + + if (!g_pak) + return; + + pakheader.id[0] = 'P'; + pakheader.id[1] = 'A'; + pakheader.id[2] = 'C'; + pakheader.id[3] = 'K'; + dirlen = (byte *)pf - (byte *)pfiles; + pakheader.dirofs = LittleLong(ftell(pakfile)); + pakheader.dirlen = LittleLong(dirlen); + + checksum = Com_BlockChecksum ( (void *)pfiles, dirlen ); + + SafeWrite (pakfile, pfiles, dirlen); + + i = ftell (pakfile); + + fseek (pakfile, 0, SEEK_SET); + SafeWrite (pakfile, &pakheader, sizeof(pakheader)); + fclose (pakfile); + + d = pf - pfiles; + printf ("%i files packed in %i bytes\n",d, i); + printf ("checksum: 0x%x\n", checksum); +} + + +/* +=============== +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) +{ + GetScriptToken (false); + 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 +#ifdef NeXT +#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 ; id_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) +{ + GetScriptToken (false); + 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 width height\n"); + } + return 0; + } +*/ else if (!strcmpi(argv[i], "-genskin")) + { + i++; + if (i < argc-3) + { + GenSkin(argv[i],argv[i+1],atol(argv[i+2]),atol(argv[i+3])); + } + else + { + printf("qdata -genskin \n"); + } + return 0; + + } + else if (!strcmpi(argv[i], "-noopts")) + { + g_no_opimizations = true; + printf("not performing optimizations\n"); + } + else if (!strcmpi(argv[i], "-md2")) + { + g_forcemodel = MODEL_MD2; + } + else if (!strcmpi(argv[i], "-fm")) + { + g_forcemodel = MODEL_FM; + } + else if (!strcmpi(argv[i], "-verbose")) + { + g_verbose = true; + } + else if (!strcmpi(argv[i], "-oldskin")) + { + g_allow_newskin = false; + } + else if (!strcmpi(argv[i], "-ignoreUV")) + { + g_ignoreTriUV = true; + } + else if (!strcmpi(argv[i], "-publish")) + { + g_publishOutput = true; + } + else if (!strcmpi(argv[i], "-nomkdir")) + { + g_nomkdir = true; + } + else if (argv[i][0] == '-') + Error ("Unknown option \"%s\"", argv[i]); + else + break; + } + + if (i >= argc) + { + Error ("usage: qdata [-archive ]\n" + " [-release ]\n" + " [-base ]\n" + " [-compress]\n" + " [-pak ]\n" + " [-only ]\n" + " [-keypress]\n" + " [-3ds]\n" + " [-materialfile ]\n" + " [-noopts]\n" + " [-md2]\n" + " [-fm]\n" + " [-verbose]\n" + " [-ignoreUV]\n" + " [-oldskin]\n" + " [-publish]\n" + " [-nomkdir]\n" + " file.qdt\n" + "or\n" + " qdata -genskin "); + } + + if (do3ds) + trifileext = ext_3ds; + else + trifileext = ext_tri; + + for ( ; i +#include +#include +#include +#include + +#include "cmdlib.h" +#include "inout.h" +#include "scriplib.h" +#include "mathlib.h" +#include "trilib.h" +#include "lbmlib.h" +#include "her2_threads.h" +#include "l3dslib.h" +#include "bspfile.h" + +#ifndef _WIN32 +#define stricmp strcasecmp +#define strcmpi strcasecmp +#endif + + +#define MODEL_AUTO 0 +#define MODEL_MD2 1 +#define MODEL_FM 2 + +// Model cover functions (to allow the forcing of a model type) +void MODELCMD_Modelname (int modeltype); +void MODELCMD_Cd (int modeltype); +void MODELCMD_Origin (int modeltype); +void MODELCMD_Jointed (int modeltype); +void MODELCMD_Cluster (int modeltype); +void MODELCMD_Base (int modeltype); +void MODELCMD_BaseST (int modeltype); +void MODELCMD_ScaleUp (int modeltype); +void MODELCMD_Frame (int modeltype); +void MODELCMD_Skin (int modeltype); +void MODELCMD_Skinsize (int modeltype); +void MODELCMD_Skeleton (int modeltype); +void MODELCMD_SkeletalFrame (int modeltype); +void MODELCMD_BeginGroup(int modeltype); +void MODELCMD_EndGroup(int modeltype); +void MODELCMD_Referenced(int modeltype); +void MODELCMD_NodeOrder(int modeltype); + +void Cmd_Modelname (void); +void Cmd_Base (void); +void Cmd_Cd (void); +void Cmd_Origin (void); +void Cmd_ScaleUp (void); +void Cmd_Frame (void); +void Cmd_Skin (void); +void Cmd_Skinsize (void); +void FinishModel (void); +void Cmd_Cluster (void); + +// Flexible Models +//void Cmd_FMModelname (void); +void Cmd_FMBase (qboolean GetST); +void Cmd_FMCd (void); +//void Cmd_FMOrigin (void); +void Cmd_FMCluster(); +void Cmd_FMSkeleton(); +//void Cmd_FMScaleUp (void); +void Cmd_FMFrame (void); +void Cmd_FMSkeletalFrame(); +void Cmd_FMSkin (void); +//void Cmd_FMSkinsize (void); +void Cmd_FMBeginGroup(void); +void Cmd_FMEndGroup(void); +void Cmd_FMReferenced(); +void Cmd_FMNodeOrder(void); +void FMFinishModel (void); +void GenSkin(char *ModelFile, char *OutputName, int Width, int Height); +void NewGen (char *ModelFile, char *OutputName, int width, int height); + + +void Cmd_Inverse16Table( void ); + +void Cmd_SpriteName (void); +void Cmd_Load (void); +void Cmd_SpriteFrame (void); +void Cmd_Sprdir (void); +void FinishSprite (void); + +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_Alphalight (void); + +void Cmd_Picdir (void); +void Cmd_Pic (void); + +void Cmd_Bookdir (void); +void Cmd_Book (void); + +void Cmd_TextureMix (void); + +void Cmd_Video (void); + +//void RemapZero (byte *pixels, byte *palette, int width, int height); + +void ReleaseFile (char *filename); + +extern byte *byteimage, *lbmpalette; +extern int byteimagewidth, byteimageheight; +extern qboolean TrueColorImage; +extern unsigned *longimage; +extern int longimagewidth, longimageheight; + +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_no_opimizations; +extern int g_forcemodel; +extern qboolean g_verbose; +extern qboolean g_allow_newskin; +extern qboolean g_ignoreTriUV; //from qdata.c +extern qboolean g_dokeypress; + +extern char *trifileext; + +extern char g_materialFile[256]; + +extern unsigned total_x; +extern unsigned total_y; +extern unsigned total_textures; + +miptex_t *CreateMip(byte *data, unsigned width, unsigned height, byte *palette, int *FinalSize, qboolean mip); +miptex32_t *CreateMip32(unsigned *data, unsigned width, unsigned height, int *FinalSize, qboolean mip); diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/resource.h b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/resource.h new file mode 100644 index 00000000..14e2fb5b --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/resource.h @@ -0,0 +1,18 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Developer Studio generated include file. +// Used by Script1.rc +// +#define IDI_ICON1 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NO_MFC 1 +#define _APS_3D_CONTROLS 1 +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1000 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/script1.aps b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/script1.aps new file mode 100644 index 00000000..6650b67c Binary files /dev/null and b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/script1.aps differ diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/script1.rc b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/script1.rc new file mode 100644 index 00000000..7d053745 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/script1.rc @@ -0,0 +1,115 @@ +//Microsoft Developer Studio generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "afxres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (U.S.) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +#ifdef _WIN32 +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US +#pragma code_page(1252) +#endif //_WIN32 + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_ICON1 ICON DISCARDABLE "icon1.ico" + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE DISCARDABLE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE DISCARDABLE +BEGIN + "#include ""afxres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE DISCARDABLE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +#ifndef _MAC +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +VS_VERSION_INFO VERSIONINFO + FILEVERSION 1,0,0,1 + PRODUCTVERSION 1,0,0,1 + FILEFLAGSMASK 0x3fL +#ifdef _DEBUG + FILEFLAGS 0x1L +#else + FILEFLAGS 0x0L +#endif + FILEOS 0x40004L + FILETYPE 0x1L + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904b0" + BEGIN + VALUE "Comments", "Heavily modified from original ID tool\0" + VALUE "CompanyName", "Raven Software\0" + VALUE "FileDescription", "qdata\0" + VALUE "FileVersion", "2.0\0" + VALUE "InternalName", "qdata\0" + VALUE "LegalCopyright", "Copyright © 1998\0" + VALUE "OriginalFilename", "qdata.exe\0" + VALUE "ProductName", "Raven Software qdata\0" + VALUE "ProductVersion", "2.0\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1200 + END +END + +#endif // !_MAC + +#endif // English (U.S.) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/sprites.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/sprites.c new file mode 100644 index 00000000..bd9d8bf2 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/sprites.c @@ -0,0 +1,349 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" + +#define MAX_SPRFRAMES MAX_MD2SKINS + +dsprite_t sprite; +dsprframe_t frames[MAX_SPRFRAMES]; + +byte *byteimage, *lbmpalette; +int byteimagewidth, byteimageheight; + +qboolean TrueColorImage; +unsigned *longimage; +int longimagewidth, longimageheight; + +char spritename[1024]; + + +void FinishSprite (void); +void Cmd_Spritename (void); + +char spr_prefix[1024]; +char pic_prefix[1024]; + +extern char *g_outputDir; + + +/* +============== +FinishSprite +============== +*/ +void FinishSprite (void) +{ + FILE *spriteouthandle; + int i, curframe; + dsprite_t spritetemp; + char savename[1024]; + + if (sprite.numframes == 0) + return; + + if (!strlen(spritename)) + Error ("Didn't name sprite file"); + + sprintf (savename, "%sSprites/%s/%s.sp2", g_outputDir, spr_prefix, spritename); + + if (g_release) + { + char name[1024]; + + sprintf (name, "%s.sp2", spritename); + ReleaseFile (name); + spritename[0] = 0; // clear for a new sprite + sprite.numframes = 0; + return; + } + + + printf ("saving in %s\n", savename); + CreatePath (savename); + spriteouthandle = SafeOpenWrite (savename); + + +// +// write out the sprite header +// + spritetemp.ident = LittleLong (IDSPRITEHEADER); + spritetemp.version = LittleLong (SPRITE_VERSION); + spritetemp.numframes = LittleLong (sprite.numframes); + + SafeWrite (spriteouthandle, &spritetemp, 12); + +// +// write out the frames +// + curframe = 0; + + for (i=0 ; i 256) || (h > 256)) + Error ("Sprite has a dimension longer than 256"); + + xh = xl+w; + yh = yl+h; + + if (sprite.numframes >= MAX_SPRFRAMES) + Error ("Too many frames; increase MAX_SPRFRAMES\n"); + + pframe = &frames[sprite.numframes]; + pframe->width = w; + pframe->height = h; + pframe->origin_x = ox; + pframe->origin_y = oy; + + if (g_release) + { + ReleaseFile (pframe->name); + return; + } + + if (TrueColorImage) + { + sprintf (filename, "%ssprites/%s/%s_%i.m32", g_outputDir, spr_prefix, spritename, sprite.numframes); + sprintf (pframe->name, "%s/%s_%i.m32", spr_prefix, spritename, sprite.numframes); + + if (g_release) + return; // textures are only released by $maps + + xh = xl+w; + yh = yl+h; + + if (xl >= longimagewidth || xh > longimagewidth || + yl >= longimageheight || yh > longimageheight) + { + Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,longimagewidth,longimageheight); + } + + sourcel = longimage + (yl*longimagewidth) + xl; + destl = bufferl; + linedelta = (longimagewidth - w); + + for (y=yl ; ycontents = 0; + qtex32->value = 0; + strcpy(qtex32->name, pframe->name); + // + // write it out + // + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex32, size); + + free (qtex32); + } + else + { + sprintf (filename, "%ssprites/%s/%s_%i.m8", g_outputDir, spr_prefix, spritename, sprite.numframes); + sprintf (pframe->name, "%s/%s_%i.m8", spr_prefix, spritename, sprite.numframes); + + if (g_release) + return; // textures are only released by $maps + + xh = xl+w; + yh = yl+h; + + if (xl >= byteimagewidth || xh > byteimagewidth || + yl >= byteimageheight || yh > byteimageheight) + { + Error ("line %i: bad clip dimmensions (%d,%d) (%d,%d) > image (%d,%d)", scriptline, xl,yl,w,h,byteimagewidth,byteimageheight); + } + + source = byteimage + yl*byteimagewidth + xl; + dest = buffer; + linedelta = byteimagewidth - w; + + for (y=yl ; yflags = 0; + qtex->contents = 0; + qtex->value = 0; + strcpy(qtex->name, pframe->name); + // + // write it out + // + printf ("writing %s\n", filename); + SaveFile (filename, (byte *)qtex, size); + + free (qtex); + } + + sprite.numframes++; +} + + +/* +============== +Cmd_SpriteName +============== +*/ +void Cmd_SpriteName (void) +{ + if (sprite.numframes) + FinishSprite (); + + GetScriptToken (false); + strcpy (spritename, token); + memset (&sprite, 0, sizeof(sprite)); + memset (&frames, 0, sizeof(frames)); +} + + +/* +=============== +Cmd_Sprdir +=============== +*/ +void Cmd_Sprdir (void) +{ + char filename[1024]; + + GetScriptToken (false); + strcpy (spr_prefix, token); + // create the directory if needed + sprintf (filename, "%sSprites", g_outputDir); + Q_mkdir (filename); + sprintf (filename, "%sSprites/%s", g_outputDir, spr_prefix); + Q_mkdir (filename); +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/svdcmp.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/svdcmp.c new file mode 100644 index 00000000..04ac7230 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/svdcmp.c @@ -0,0 +1,490 @@ +/* +Copyright (C) 1999-2006 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 +#include +#include +#include + +static double at,bt,ct; +#define PYTHAG(a,b) ((at=fabs(a)) > (bt=fabs(b)) ? \ + (ct=bt/at,at*sqrt(1.0+ct*ct)) : (bt ? (ct=at/bt,bt*sqrt(1.0+ct*ct)): 0.0)) + + static double maxarg1,maxarg2; +#define MAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1) > (maxarg2) ?\ + (maxarg1) : (maxarg2)) +#define SIGN(a,b) ((b) >= 0.0 ? fabs(a) : -fabs(a)) + +void ntrerror(char *s) +{ + printf("%s\n",s); + exit(1); +} + +double *allocVect(int sz) +{ + double *ret; + + ret = calloc(sizeof(double), (size_t)sz); + return ret; +} + +void freeVect(double *ret) +{ + free(ret); +} + +double **allocMatrix(int r,int c) +{ + double **ret; + + ret = calloc(sizeof(double), (size_t)(r*c)); + return ret; +} + +void freeMatrix(double **ret,int r) +{ + free(ret); +} + +void svdcmp(double** a, int m, int n, double* w, double** v) +{ + int flag,i,its,j,jj,k,l,nm; + double c,f,h,s,x,y,z; + double anorm=0.0,g=0.0,scale=0.0; + double *rv1; + void nrerror(); + + if (m < n) ntrerror("SVDCMP: You must augment A with extra zero rows"); + rv1=allocVect(n); + for (i=1;i<=n;i++) { + l=i+1; + rv1[i]=scale*g; + g=s=scale=0.0; + if (i <= m) { + for (k=i;k<=m;k++) scale += fabs(a[k][i]); + if (scale) { + for (k=i;k<=m;k++) { + a[k][i] /= scale; + s += a[k][i]*a[k][i]; + } + f=a[i][i]; + g = -SIGN(sqrt(s),f); + h=f*g-s; + a[i][i]=f-g; + if (i != n) { + for (j=l;j<=n;j++) { + for (s=0.0,k=i;k<=m;k++) s += a[k][i]*a[k][j]; + f=s/h; + for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; + } + } + for (k=i;k<=m;k++) a[k][i] *= scale; + } + } + w[i]=scale*g; + g=s=scale=0.0; + if (i <= m && i != n) { + for (k=l;k<=n;k++) scale += fabs(a[i][k]); + if (scale) { + for (k=l;k<=n;k++) { + a[i][k] /= scale; + s += a[i][k]*a[i][k]; + } + f=a[i][l]; + g = -SIGN(sqrt(s),f); + h=f*g-s; + a[i][l]=f-g; + for (k=l;k<=n;k++) rv1[k]=a[i][k]/h; + if (i != m) { + for (j=l;j<=m;j++) { + for (s=0.0,k=l;k<=n;k++) s += a[j][k]*a[i][k]; + for (k=l;k<=n;k++) a[j][k] += s*rv1[k]; + } + } + for (k=l;k<=n;k++) a[i][k] *= scale; + } + } + anorm=MAX(anorm,(fabs(w[i])+fabs(rv1[i]))); + } + for (i=n;i>=1;i--) { + if (i < n) { + if (g) { + for (j=l;j<=n;j++) + v[j][i]=(a[i][j]/a[i][l])/g; + for (j=l;j<=n;j++) { + for (s=0.0,k=l;k<=n;k++) s += a[i][k]*v[k][j]; + for (k=l;k<=n;k++) v[k][j] += s*v[k][i]; + } + } + for (j=l;j<=n;j++) v[i][j]=v[j][i]=0.0; + } + v[i][i]=1.0; + g=rv1[i]; + l=i; + } + for (i=n;i>=1;i--) { + l=i+1; + g=w[i]; + if (i < n) + for (j=l;j<=n;j++) a[i][j]=0.0; + if (g) { + g=1.0/g; + if (i != n) { + for (j=l;j<=n;j++) { + for (s=0.0,k=l;k<=m;k++) s += a[k][i]*a[k][j]; + f=(s/a[i][i])*g; + for (k=i;k<=m;k++) a[k][j] += f*a[k][i]; + } + } + for (j=i;j<=m;j++) a[j][i] *= g; + } else { + for (j=i;j<=m;j++) a[j][i]=0.0; + } + ++a[i][i]; + } + for (k=n;k>=1;k--) { + for (its=1;its<=30;its++) { + flag=1; + for (l=k;l>=1;l--) { + nm=l-1; + if (fabs(rv1[l])+anorm == anorm) { + flag=0; + break; + } + if (fabs(w[nm])+anorm == anorm) break; + } + if (flag) { + c=0.0; + s=1.0; + for (i=l;i<=k;i++) { + f=s*rv1[i]; + if (fabs(f)+anorm != anorm) { + g=w[i]; + h=PYTHAG(f,g); + w[i]=h; + h=1.0/h; + c=g*h; + s=(-f*h); + for (j=1;j<=m;j++) { + y=a[j][nm]; + z=a[j][i]; + a[j][nm]=y*c+z*s; + a[j][i]=z*c-y*s; + } + } + } + } + z=w[k]; + if (l == k) { + if (z < 0.0) { + w[k] = -z; + for (j=1;j<=n;j++) v[j][k]=(-v[j][k]); + } + break; + } + if (its == 30) ntrerror("No convergence in 30 SVDCMP iterations"); + x=w[l]; + nm=k-1; + y=w[nm]; + g=rv1[nm]; + h=rv1[k]; + f=((y-z)*(y+z)+(g-h)*(g+h))/(2.0*h*y); + g=PYTHAG(f,1.0); + f=((x-z)*(x+z)+h*((y/(f+SIGN(g,f)))-h))/x; + c=s=1.0; + for (j=l;j<=nm;j++) { + i=j+1; + g=rv1[i]; + y=w[i]; + h=s*g; + g=c*g; + z=PYTHAG(f,h); + rv1[j]=z; + c=f/z; + s=h/z; + f=x*c+g*s; + g=g*c-x*s; + h=y*s; + y=y*c; + for (jj=1;jj<=n;jj++) { + x=v[jj][j]; + z=v[jj][i]; + v[jj][j]=x*c+z*s; + v[jj][i]=z*c-x*s; + } + z=PYTHAG(f,h); + w[j]=z; + if (z) { + z=1.0/z; + c=f*z; + s=h*z; + } + f=(c*g)+(s*y); + x=(c*y)-(s*g); + for (jj=1;jj<=m;jj++) { + y=a[jj][j]; + z=a[jj][i]; + a[jj][j]=y*c+z*s; + a[jj][i]=z*c-y*s; + } + } + rv1[l]=0.0; + rv1[k]=f; + w[k]=x; + } + } + freeVect(rv1); +} + + + +void svbksb(double** u, double* w, double** v,int m, int n, double* b, double* x) +{ + int jj,j,i; + double s,*tmp; + tmp=allocVect(n); + for (j=1;j<=n;j++) + { + s=0.0; + if (w[j]) + { + for (i=1;i<=m;i++) + s += u[i][j]*b[i]; + s /= w[j]; + } + tmp[j]=s; + } + for (j=1;j<=n;j++) + { + s=0.0; + for (jj=1;jj<=n;jj++) + s += v[j][jj]*tmp[jj]; + x[j]=s; + } + freeVect(tmp); +} + +#undef SIGN +#undef MAX +#undef PYTHAG + + +#if 1 +void DOsvd(float *a,float *res,float *comp,float *values,int nframes,int framesize,int compressedsize) +{ + int usedfs; + int *remap; + int i,j; + double **da; + double **v; + double *w; + int DOFerr; + float mx; + int bestat; + + if (nframes>framesize) + usedfs=nframes; + else + usedfs=framesize; + + da=allocMatrix(usedfs,nframes); + v=allocMatrix(nframes,nframes); + w=allocVect(nframes); + + DOFerr = 0; //false + for (i=0;imx) + { + mx=(float) fabs(w[i+1]); + bestat=i; + } + } + + if(mx>0) + { + remap[bestat]=j; + } + else + { + DOFerr = 1; //true + } + } + + if(DOFerr) + { + printf("Warning: To many degrees of freedom! File size may increase\n"); + + for (i=0;imx) + { + mx=fabs(w[i+1]); + bestat=i; + } + } + assert(mx>-.5f); + remap[bestat]=j; + } + // josh **DO NOT** put your dof>nframes mod here + for (i=0;i=3); + base[0]=pnts[0]; + base[1]=pnts[1]; + base[2]=pnts[2]; + for (i=1;i> 5 ) & 63 ) << 2; + b[0] = ( ( color >> 11 ) & 31 ) << 3; + + for ( i = 0; i < 256; i++ ) + { + r[1] = ( d_8to24table[i] >> 0 ) & 0xFF; + g[1] = ( d_8to24table[i] >> 8 ) & 0xFF; + b[1] = ( d_8to24table[i] >> 16 ) & 0xFF; + + d = ( r[1] - r[0] ) * ( r[1] - r[0] ) + + ( g[1] - g[0] ) * ( g[1] - g[0] ) + + ( b[1] - b[0] ) * ( b[1] - b[0] ); + + if ( d < closest_distance_so_far ) + { + closest_distance_so_far = d; + closest_so_far = i; + } + } + + return closest_so_far; +} +*/ + +extern byte BestColor( int, int, int, int, int ); + +void Inverse16_BuildTable( void ) +{ + int i; + + /* + ** create the 16-to-8 table + */ + for ( i = 0; i < 65536; i++ ) + { + int r = i & 31; + int g = ( i >> 5 ) & 63; + int b = ( i >> 11 ) & 31; + + r <<= 3; + g <<= 2; + b <<= 3; + + inverse16to8table[i] = BestColor( r, g, b, 0, 255 ); + } +} + +void Alphalight_Thread (int i) +{ + int j; + float r, g, b; + float mr, mg, mb, ma; + float distortion, bestdistortion; + float v; + + r = (i>>10) * (1.0/16); + g = ((i>>5)&31) * (1.0/16); + b = (i&31) * (1.0/16); + + bestdistortion = 999999; + for (j=0 ; j<16*16*16*16 ; j++) + { + mr = (j>>12) * (1.0/16); + mg = ((j>>8)&15) * (1.0/16); + mb = ((j>>4)&15) * (1.0/16); + ma = (j&15) * (1.0/16); + + v = r * 0.5 - (mr*ma + 0.5*(1.0-ma)); + distortion = v*v; + v = g * 0.5 - (mg*ma + 0.5*(1.0-ma)); + distortion += v*v; + v = b * 0.5 - (mb*ma + 0.5*(1.0-ma)); + distortion += v*v; + + distortion *= 1.0 + ma*4; + + if (distortion < bestdistortion) + { + bestdistortion = distortion; + alphamap[i] = j; + } + } +} + +void Cmd_Alphalight (void) +{ + char savename[1024]; + + GetScriptToken (false); + + if (g_release) + { + ReleaseFile (token); + return; + } + + sprintf (savename, "%s%s", gamedir, token); + printf ("Building alphalight table...\n"); + + RunThreadsOnIndividual (32*32*32, true, Alphalight_Thread); + + SaveFile (savename, (byte *)alphamap, sizeof(alphamap)); +} + + +void Cmd_Inverse16Table( void ) +{ + char savename[1024]; + + if ( g_release ) + { + sprintf (savename, "pics/16to8.dat"); + ReleaseFile( savename ); + return; + } + + sprintf (savename, "%spics/16to8.dat", gamedir); + printf ("Building inverse 16-to-8 table...\n"); + + Inverse16_BuildTable(); + + SaveFile( savename, (byte *) inverse16to8table, sizeof( inverse16to8table ) ); +} diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/tmix.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/tmix.c new file mode 100644 index 00000000..ac1b2f30 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/tmix.c @@ -0,0 +1,698 @@ +/* +Copyright (C) 1999-2006 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 "qdata.h" +#include "flex.h" + +#define MAXFILES 2048 + +typedef struct +{ + int x; + int y; + int w; + int h; + int cw; + int ch; + int rw; + int index; + int depth; + int col; + int baseline; + char name[128]; +} Coords; + +int filenum; +int valid; +Coords in[MAXFILES]; +Coords out; +char outscript[256]; +char sourcedir[256]; +char outusage[256]; +char root[32]; + +int destsize = 0; +byte *pixels = NULL; // Buffer to load image +long *outpixels = NULL; // Buffer to store combined textures +long *usagemap = NULL; // Buffer of usage map +void *bmptemp = NULL; // Buffer of usage map +byte *map = NULL; + +int xcharsize; +int ycharsize; +int dosort = 0; +int missed = 0; +int overlap = 0; +int nobaseline = 0; +int percent; + +////////////////////////////////////////////////// +// Setting the char based usage map // +////////////////////////////////////////////////// + +byte TryPlace(Coords *coord) +{ + int x, y; + byte entry = 0; + byte *mapitem; + + mapitem = map + (coord->x / xcharsize) + ((coord->y / ycharsize) * out.cw); + + for (y = 0; y < coord->ch; y++, mapitem += out.cw - coord->cw) + { + for (x = 0; x < coord->cw; x++) + { + if (entry |= *mapitem++ & 8) + { + return(entry); + } + } + } + return(entry); +} + +void SetMap(Coords *coord) +{ + int x, y; + byte *mapitem; + + mapitem = map + (coord->x / xcharsize) + ((coord->y / ycharsize) * out.cw); + + for (y = 0; y < coord->ch; y++, mapitem += out.cw - coord->cw) + for (x = 0; x < coord->cw; x++) + *mapitem++ |= 8; +} + +////////////////////////////////////////////////// +// Setting the pixel based usage map // +////////////////////////////////////////////////// + +void CheckOverlap(Coords *coord) +{ + int x; + int y; + long *dest; + + x = coord->x; + y = coord->y; + + dest = (long *)(usagemap + x + (y * out.w)); + + for (y = 0; y < coord->h; y++, dest += out.w - coord->w) + { + for (x = 0; x < coord->w; x++) + { + if (*dest++) + { + overlap++; + return; + } + } + } +} + +void SetUsageMap(Coords *coord) +{ + int x; + int y; + long *dest; + + x = coord->x; + y = coord->y; + + dest = (long *)(usagemap + x + (y * out.w)); + + for (y = 0; y < coord->h; y++, dest += out.w - coord->w) + { + for (x = 0; x < coord->w; x++) + { + *dest++ = coord->col; + } + } +} + +////////////////////////////////////////////////// +// Flips the BMP image to the correct way up // +////////////////////////////////////////////////// + +void CopyLine(byte *dest, byte *src, int size) +{ + int x; + + for (x = 0; x < size; x++) + *dest++ = *src++; +} + +/****************************************************/ +/* Printing headers etc */ +/****************************************************/ + +void RemoveLeading(char *name) +{ + int i; + char temp[128]; + + for(i = strlen(name) - 1; i > 0; i--) + { + if((name[i] == '\\') || (name[i] == '/')) + { + strcpy(temp, name + i + 1); + strcpy(name, temp); + return; + } + } +} + +void RemoveExt(char *name) +{ + while ((*name != '.') && *name) + name++; + *name = 0; +} + +/****************************************************/ +/* Misc calcualtions */ +/****************************************************/ + +int TotalArea() +{ + int i; + int total = 0; + + for (i = 0; i < (filenum + 2); i++) + total += in[i].w * in[i].h; + + return(total); +} + +/****************************************************/ +/* Setup and checking of all info */ +/****************************************************/ + +void InitVars() +{ + filenum = 0; + valid = 0; + dosort = 0; + missed = 0; + overlap = 0; + nobaseline = 0; + + memset(outscript, 0, sizeof(outscript)); + memset(outscript, 0, sizeof(sourcedir)); + memset(outscript, 0, sizeof(outusage)); + memset(outscript, 0, sizeof(root)); + + memset(in, 0, sizeof(in)); + memset(&out, 0, sizeof(out)); +} +void Cleanup() +{ + if (pixels) + free(pixels); + if (usagemap) + free(usagemap); + if (outpixels) + free(outpixels); + if (bmptemp) + free(bmptemp); + if (map) + free(map); +} + +typedef struct glxy_s +{ + float xl, yt, xr, yb; + int w, h, baseline; +} glxy_t; + +int SaveScript(char *name) +{ + FILE *fp; + int i, j; + glxy_t buff; + + if(fp = fopen(name, "wb")) + { + for (j = 0; j < filenum; j++) + { + for (i = 0; i < filenum; i++) + { + if (in[i].index == j) + { + if (in[i].depth) + { + buff.xl = (float)in[i].x / (float)out.w; + buff.yt = (float)in[i].y / (float)out.h; + buff.xr = ((float)in[i].w + (float)in[i].x) / (float)out.w; + buff.yb = ((float)in[i].h + (float)in[i].y) / (float)out.h; + buff.w = in[i].w; + buff.h = in[i].h; + buff.baseline = in[i].baseline; + } + else + { + memset(&buff, 0, sizeof(glxy_t)); + } + fwrite(&buff, 1, sizeof(glxy_t), fp); + i = filenum; + } + } + } + fclose(fp); + return(true); + } + else + return(false); +} + +int GetScriptInfo(char *name) +{ + FILE *fp; + char buffer[256]; + char tempbuff[256]; + char delims[] = {" \t,\n"}; + + printf("Opening script file %s.\n", name); + + if (fp = fopen(name, "r")) + { + while(fgets(buffer, 256, fp)) + { + if (strncmp(buffer, "//", 2) && strncmp(buffer, "\n", 1)) + { + strupr(buffer); + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "OUTPUT") == 0) + { + strcpy(out.name, strtok(NULL, delims)); + strlwr(out.name); + } + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "SOURCEDIR") == 0) + { + strcpy(tempbuff, strtok(NULL, delims)); + strcpy(sourcedir, ExpandPathAndArchive(tempbuff)); + } + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "DOSORT") == 0) + dosort = 1; + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "XCHARSIZE") == 0) + xcharsize = strtol(strtok(NULL, delims), NULL, 0); + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "YCHARSIZE") == 0) + ycharsize = strtol(strtok(NULL, delims), NULL, 0); + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "OUTSCRIPT") == 0) + { + strcpy(outscript, strtok(NULL, delims)); + strlwr(outscript); + } + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "OUTUSAGE") == 0) + strcpy(outusage, strtok(NULL, delims)); + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "POS") == 0) + { + out.w = strtol(strtok(NULL, delims), NULL, 0); + out.h = strtol(strtok(NULL, delims), NULL, 0); + } + + strcpy(tempbuff, buffer); + if (strcmp(strtok(tempbuff, delims), "FILE") == 0) + { + strcpy(in[filenum].name, strtok(NULL, delims)); + in[filenum].x = strtol(strtok(NULL, delims), NULL, 0); + in[filenum].y = strtol(strtok(NULL, delims), NULL, 0); + in[filenum].col = strtol(strtok(NULL, delims), NULL, 0); + filenum++; + } + } + } + fclose(fp); + return(true); + } + else + { + printf("ERROR : Could not open script file.\n"); + return(false); + } +} + +int CheckVars() +{ + int i; + + if (out.name[0] == 0) + { + printf("ERROR : No output name specified.\n"); + return(false); + } + if ((out.w <= 0) || (out.h <= 0)) + { + printf("ERROR : Invalid VRAM coordinates.\n"); + return(false); + } + if (filenum == 0) + { + printf("ERROR : No input files specified.\n"); + return(false); + } + for (i = 0; i < filenum; i++) + if (in[i].name[0] == 0) + { + printf("ERROR : Input filename invalid.\n"); + return(false); + } + return(true); +} + +// Makes sure texture is totally within the output area + +int CheckCoords(Coords *coord) +{ + if ((coord->x + coord->w) > out.w) + return(false); + if ((coord->y + coord->h) > out.h) + return(false); + + return(true); +} +// Gets the width, height, palette width and palette height of each BMP file + +int GetFileDimensions() +{ + int i; + int width, height; + char name[128]; + + for (i = 0; i < filenum; i++) + { + in[i].index = i; + + strcpy(name, sourcedir); + strcat(name, in[i].name); + printf("Getting file dimensions, file : %s \r", in[i].name); + if(FileExists(name)) + { + LoadAnyImage(name, NULL, NULL, &width, &height); + in[i].depth = 32; + in[i].rw = width; + in[i].w = width; // makes it width in + in[i].h = height; + in[i].cw = (in[i].w + (xcharsize - 1)) / xcharsize; + in[i].ch = (in[i].h + (ycharsize - 1)) / ycharsize; + + if (!CheckCoords(&in[i]) && (in[i].x >= 0)) + { + printf("Error : texture %s out of bounds.\n", in[i].name); + return(false); + } + valid++; + } + else + { + in[i].depth = 0; + in[i].x = -1; + in[i].y = -1; + in[i].w = 0; + in[i].h = 0; + } + } + printf("\n\n"); + return(true); +} + +// Sorts files into order for optimal space finding +// Fixed position ones first, followed by the others in descending size +// The theory being that it is easier to find space for smaller textures. +// size = (width + height) +// For space finding it is easier to place a 32x32 than a 128x2 + +#define WEIGHT 0x8000 + +void Swap(Coords *a, Coords *b) +{ + Coords c; + + c = *a; + *a = *b; + *b = c; +} + +void SortInNames() +{ + int i, j; + int largest, largcount; + int size; + + printf("Sorting filenames by size.\n\n"); + + for (j = 0; j < filenum; j++) + { + largest = -1; + largcount = -1; + + for (i = j; i < filenum; i++) + { + if (in[i].depth) + { + size = in[i].w + in[i].h; + + if ((in[i].x < 0) && (size > largest)) + { + largcount = i; + largest = size; + } + } + } + if ((largcount >= 0) && (largcount != j)) + Swap(&in[j], &in[largcount]); + } +} + +int SetVars(char *name) +{ + if (!GetScriptInfo(name)) + return(false); + + if (!CheckVars()) + return(false); + + destsize = out.w * out.h; + + out.cw = out.w / xcharsize; + out.ch = out.h / ycharsize; + + if ((usagemap = (long *)SafeMalloc(destsize * 4, "")) == NULL) + return(false); + if ((outpixels = (long *)SafeMalloc(destsize * 4, "")) == NULL) + return(false); + if ((bmptemp = (void *)SafeMalloc(destsize * 4, "")) == NULL) + return(false); + if ((map = (byte *)SafeMalloc(destsize / (xcharsize * ycharsize), "")) == NULL) + return(false); + + if (GetFileDimensions() == false) + return(false); + + if (dosort) + SortInNames(); + + return(true); +} +/****************************************************/ +/* Actual copying routines */ +/****************************************************/ + +int FindCoords(Coords *coord) +{ + int tx, ty; + + if (coord->x >= 0) + { + SetMap(coord); + return(true); + } + else + { + for (ty = 0; ty < out.ch; ty++) + { + for (tx = 0; tx < out.cw; tx++) + { + coord->x = (tx * xcharsize); + coord->y = (ty * ycharsize); + + if (CheckCoords(coord) && !TryPlace(coord)) + { + SetMap(coord); + return(true); + } + } + } + } + coord->x = -1; + coord->y = -1; + + return(false); +} + +void CheckBaseline(int i) +{ + int y; + long *pix; + + in[i].baseline = -1; + pix = (long *)pixels; + + for(y = 0; y < in[i].h; y++, pix += in[i].w) + { + if((*pix & 0x00ffffff) == 0x00ff00ff) + { + in[i].baseline = y; + break; + } + } + pix = (long *)pixels; + for(y = 0; y < in[i].w * in[i].h; y++, pix++) + { + if((*pix & 0x00ffffff) == 0x00ff00ff) + { + *pix = 0; + } + } + + if(in[i].baseline == -1) + { + printf("\nERROR : %s has no baseline\n", in[i].name); + nobaseline++; + } +} + +void CopyToMain32(Coords *coord) +{ + int x; + int y; + long *source; + long *dest; + + x = coord->x; + y = coord->y; + + source = (long *)pixels; + dest = (long *)(outpixels + x + (y * out.w)); + + for (y = 0; y < coord->h; y++, dest += out.w - coord->w) + { + for (x = 0; x < coord->w; x++) + { + *dest++ = *source++; + } + } +} + +void CreateMain() +{ + int i, count; + int width, height; + char name[128]; + + for (i = 0, count = 0; i < filenum; i++) + { + if (in[i].depth) + { + printf("\rProcessing %d of %d (%d missed, %d overlapping, %d nobase)\r", count + 1, valid, missed, overlap, nobaseline); + count++; + if (!FindCoords(&in[i])) + missed++; + else + { + strcpy(name, sourcedir); + strcat(name, in[i].name); + LoadAnyImage(name, &pixels, NULL, &width, &height); + CheckBaseline(i); + CheckOverlap(&in[i]); + CopyToMain32(&in[i]); + SetUsageMap(&in[i]); + } + } + } +} + +void Cmd_TextureMix() +{ + miptex32_t *qtex32; + char filename[1024]; + int size; + + InitVars(); + + GetScriptToken (false); + + strcpy(root, token); + RemoveExt(root); + RemoveLeading(root); + + strcpy(filename, ExpandPathAndArchive(token)); + if (SetVars(filename)) + { + // Create combined texture + percent = ((TotalArea() * 100) / (out.w * out.h)); + printf("Total area consumed : %d%%\n", percent); + printf("Texture resolution : %dx%d pixels.\n", xcharsize, ycharsize); + CreateMain(); + + // Save image as m32 + sprintf (filename, "%spics/misc/%s.m32", gamedir, out.name); + qtex32 = CreateMip32((unsigned *)outpixels, out.w, out.h, &size, false); + + qtex32->contents = 0; + qtex32->value = 0; + qtex32->scale_x = 1.0; + qtex32->scale_y = 1.0; + sprintf (qtex32->name, "misc/%s", out.name); + + printf ("\n\nwriting %s\n", filename); + SaveFile (filename, (byte *)qtex32, size); + free (qtex32); + + // Save out script file + sprintf (filename, "%spics/misc/%s.fnt", gamedir, outscript); + printf("Writing %s as script file\n", filename); + if (!SaveScript(filename)) + { + printf("Unable to save output script.\n"); + } + } + printf("Everythings groovy.\n"); + Cleanup(); +} + +// end + diff --git a/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/video.c b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/video.c new file mode 100644 index 00000000..181a9735 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake2/qdata_heretic2/video.c @@ -0,0 +1,1149 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +// To do + +// Sound error handling (when sound too short) +// rle b4 huffing +// adpcm encoding of sound + +#if 0 +#include "qdata.h" +#include "flex.h" +#include "fc.h" +#include "adpcm.h" + +#define MIN_REPT 15 +#define MAX_REPT 0 +#define HUF_TOKENS (256 + MAX_REPT) + +#define BLOCKSIZE 8 + +#define M_PI 3.14159265358979323846 // matches value in gcc v2 math.h +#define SQRT2 1.414213562 + +typedef struct hnode_s +{ + int count; + qboolean used; + int children[2]; +} hnode_t; + +typedef struct +{ + int rate; + int width; + int channels; + int loopstart; + int samples; + int dataofs; // chunk starts this many bytes from file start +} wavinfo_t; + +// These weren`t picked out my ass.... +// They were defined at http://www.rahul.net/jfm/dct.html +// However, I think he plucked them out of his ass..... + +float Quantise[BLOCKSIZE * BLOCKSIZE]; + +float LUT_Quantise[BLOCKSIZE * BLOCKSIZE] = +{ + 16.0F/16.0F, 11.0F/16.0F, 10.0F/16.0F, 16.0F/16.0F, 24.0F/16.0F, 40.0F/16.0F, 51.0F/16.0F, 61.0F/16.0F, + 12.0F/16.0F, 13.0F/16.0F, 14.0F/16.0F, 19.0F/16.0F, 26.0F/16.0F, 58.0F/16.0F, 60.0F/16.0F, 55.0F/16.0F, + 14.0F/16.0F, 13.0F/16.0F, 16.0F/16.0F, 24.0F/16.0F, 40.0F/16.0F, 57.0F/16.0F, 69.0F/16.0F, 56.0F/16.0F, + 14.0F/16.0F, 17.0F/16.0F, 22.0F/16.0F, 29.0F/16.0F, 51.0F/16.0F, 87.0F/16.0F, 80.0F/16.0F, 62.0F/16.0F, + 18.0F/16.0F, 22.0F/16.0F, 37.0F/16.0F, 56.0F/16.0F, 68.0F/16.0F,109.0F/16.0F,103.0F/16.0F, 77.0F/16.0F, + 24.0F/16.0F, 35.0F/16.0F, 55.0F/16.0F, 64.0F/16.0F, 81.0F/16.0F,104.0F/16.0F,113.0F/16.0F, 92.0F/16.0F, + 49.0F/16.0F, 64.0F/16.0F, 78.0F/16.0F, 87.0F/16.0F,103.0F/16.0F,121.0F/16.0F,120.0F/16.0F,101.0F/16.0F, + 72.0F/16.0F, 92.0F/16.0F, 95.0F/16.0F, 98.0F/16.0F,112.0F/16.0F,100.0F/16.0F,103.0F/16.0F, 99.0F/16.0F +}; + +int LUT_ZZ[BLOCKSIZE * BLOCKSIZE] = +{ + 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 +}; + +char base[32]; + +byte *soundtrack; + +byte scaled[256][HUF_TOKENS]; +unsigned int charbits1[256][HUF_TOKENS]; +int charbitscount1[256][HUF_TOKENS]; +hnode_t hnodes1[256][HUF_TOKENS * 2]; +int numhnodes1[256]; +int order0counts[256]; +int numhnodes; +hnode_t hnodes[512]; +unsigned charbits[256]; +int charbitscount[256]; + +CineHead_t cinehead; + +byte *data_p; +byte *iff_end; +byte *last_chunk; +byte *iff_data; +int iff_chunk_len; + +float dctbase[BLOCKSIZE][BLOCKSIZE]; +float red[BLOCKSIZE * BLOCKSIZE]; +float green[BLOCKSIZE * BLOCKSIZE]; +float blue[BLOCKSIZE * BLOCKSIZE]; +float temp[BLOCKSIZE * BLOCKSIZE]; + +wavinfo_t wavinfo; +adpcm_t adpcm; + +/* +=============================================================================== + +WAV loading + +=============================================================================== +*/ + +/* Intel ADPCM step variation table */ +static int indexTable[16] = +{ + -1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8, +}; + +static int stepsizeTable[89] = +{ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, + 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, + 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, + 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, + 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, + 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, + 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, + 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 +}; + +#if 0 +static void adpcm_decoder(char *indata, short *outdata, int len, adpcm_state_t *state) +{ + signed char *inp; /* Input buffer pointer */ + short *outp; /* output buffer pointer */ + int sign; /* Current adpcm sign bit */ + int delta; /* Current adpcm output value */ + int step; /* Stepsize */ + int valpred; /* Predicted value */ + int vpdiff; /* Current change to valpred */ + int index; /* Current step change index */ + int inputbuffer; /* place to keep next 4-bit value */ + int bufferstep; /* toggle between inputbuffer/input */ + + outp = outdata; + inp = (signed char *)indata; + + valpred = state->valprev; + index = state->index; + step = stepsizeTable[index]; + + bufferstep = 0; + + for(; len > 0; len--) + { + /* Step 1 - get the delta value */ + if (bufferstep) + delta = inputbuffer & 0xf; + else + { + inputbuffer = *inp++; + delta = (inputbuffer >> 4) & 0xf; + } + bufferstep = !bufferstep; + + /* Step 2 - Find new index value (for later) */ + index += indexTable[delta]; + if(index < 0) + index = 0; + if(index > 88) + index = 88; + + /* Step 3 - Separate sign and magnitude */ + sign = delta & 8; + delta = delta & 7; + + /* Step 4 - Compute difference and new predicted value */ + /* + ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment + ** in adpcm_coder. + */ + vpdiff = step >> 3; + if(delta & 4) + vpdiff += step; + if(delta & 2) + vpdiff += step>>1; + if(delta & 1) + vpdiff += step>>2; + + if (sign) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 5 - clamp output value */ + if (valpred > 32767) + valpred = 32767; + else if (valpred < -32768) + valpred = -32768; + + /* Step 6 - Update step value */ + step = stepsizeTable[index]; + + /* Step 7 - Output value */ + *outp++ = valpred; + } + + state->valprev = valpred; + state->index = index; +} +#endif + +void adpcm_coder(short *inp, adpcm_t *adpcm) +{ + int val; /* Current input sample value */ + int sign; /* Current adpcm sign bit */ + int delta; /* Current adpcm output value */ + int diff; /* Difference between val and valprev */ + int step; /* Stepsize */ + int valpred; /* Predicted output value */ + int vpdiff; /* Current change to valpred */ + int index; /* Current step change index */ + int outputbuffer; /* place to keep previous 4-bit value */ + int bufferstep; /* toggle between outputbuffer/output */ + adpcm_state_t *state; + char *outp; + int len; + + state = &adpcm->state; + len = state->count; + outp = adpcm->adpcm; + + valpred = state->in_valprev; + index = state->in_index; + step = stepsizeTable[index]; + + bufferstep = 1; + while(len--) + { + val = *inp++; + + /* Step 1 - compute difference with previous value */ + diff = val - valpred; + sign = (diff < 0) ? 8 : 0; + if (sign) + diff = -diff; + + /* Step 2 - Divide and clamp */ + /* Note: + ** This code *approximately* computes: + ** delta = diff*4/step; + ** vpdiff = (delta+0.5)*step/4; + ** but in shift step bits are dropped. The net result of this is + ** that even if you have fast mul/div hardware you cannot put it to + ** good use since the fixup would be too expensive. + */ + delta = 0; + vpdiff = (step >> 3); + + if (diff >= step) + { + delta = 4; + diff -= step; + vpdiff += step; + } + step >>= 1; + if (diff >= step) + { + delta |= 2; + diff -= step; + vpdiff += step; + } + step >>= 1; + if (diff >= step) + { + delta |= 1; + vpdiff += step; + } + + /* Step 3 - Update previous value */ + if (sign) + valpred -= vpdiff; + else + valpred += vpdiff; + + /* Step 4 - Clamp previous value to 16 bits */ + if (valpred > 32767) + valpred = 32767; + else if (valpred < -32768) + valpred = -32768; + + /* Step 5 - Assemble value, update index and step values */ + delta |= sign; + + index += indexTable[delta]; + if (index < 0) + index = 0; + if (index > 88) + index = 88; + step = stepsizeTable[index]; + + /* Step 6 - Output value */ + if (bufferstep) + outputbuffer = (delta << 4) & 0xf0; + else + *outp++ = (delta & 0x0f) | outputbuffer; + + bufferstep = !bufferstep; + } + + /* Output last step, if needed */ + if(!bufferstep) + *outp++ = outputbuffer; + + state->out_valprev = valpred; + state->out_index = index; +} + +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 = *(long *)data_p; + data_p += 4; + if(iff_chunk_len < 0) + { + data_p = NULL; + return; + } + + 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 = *(long *)data_p; + data_p += 4; + 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; + + FindChunk("fmt "); + if(!data_p) + { + printf("Missing fmt chunk\n"); + return(info); + } + data_p += 8; + format = *(short *)data_p; + data_p += 2; + if (format != 1) + { + printf("Microsoft PCM format only\n"); + return(info); + } + + info.channels = *(short *)data_p; + data_p += 2; + info.rate = *(long *)data_p; + data_p += 4; + data_p += 6; + info.width = *(short *)data_p / 8; + data_p += 2; + +// get cue chunk + FindChunk("cue "); + if(data_p) + { + data_p += 32; + info.loopstart = *(long *)data_p; + data_p += 4; + +// if the next chunk is a LIST chunk, look for a cue length marker + FindNextChunk ("LIST"); + if(data_p) + { +// this is not a proper parse, but it works with cooledit... + if (!strncmp (data_p + 28, "mark", 4)) + { + data_p += 24; + i = *(long *)data_p; // samples in loop + data_p += 4; + 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 = *(long *)data_p; + data_p += 4; + + 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() +{ + char name[1024]; + FILE *f; + int len; + + soundtrack = NULL; + sprintf (name, "%svideo/%s/%s.wav", gamedir, base, base); + printf ("\nLoading sound : %s\n", name); + f = fopen (name, "rb"); + if (!f) + { + printf ("\nNo soundtrack for %s\n", base); + return; + } + len = Q_filelength(f); + soundtrack = SafeMalloc(len, "LoadSoundtrack"); + fread(soundtrack, 1, len, f); + fclose(f); + + wavinfo = GetWavinfo(name, soundtrack, len); + adpcm.state.out_valprev = 0; + adpcm.state.out_index = 0; +} + +// ================== +// WriteSound +// ================== + +int WriteSound(FILE *output, int frame, int numframes) +{ + int start, end; + int count; + int empty = 0; + int width; + char *work; + + width = wavinfo.width * wavinfo.channels; + start = ((frame * wavinfo.rate / 14) + 31) & 0xffffffe0; // start sample + end = (((frame + numframes) * wavinfo.rate / 14) + 31) & 0xffffffe0; // end sample + count = end - start; + + work = soundtrack + wavinfo.dataofs + (start * width); + adpcm.state.count = count * wavinfo.channels; // Number of samples + adpcm.state.in_valprev = adpcm.state.out_valprev; + adpcm.state.in_index = adpcm.state.out_index; + adpcm_coder((short *)work, &adpcm); + WriteHeader(output, FC_SOUND_22KMADPCM, FC_ADPCM_VERSION, (adpcm.state.count / 2) + sizeof(adpcm_state_t), (char *)&adpcm); + return(count / 2); +} +// ============================== +// Basic run length encoder +// ============================== + +char *RLEZZ(char *in, char *out) +{ + int srun; + char count; + int idx = 0; + + while(idx < 64) + { + srun = idx; // Start of run + + while(idx < 63) + { + if(in[LUT_ZZ[idx]] != in[LUT_ZZ[idx + 1]]) + break; + idx++; + } + count = (char)(idx - srun); // count of repeated bytes + + if(!count) + { + while(idx < 63) + { + if(in[LUT_ZZ[idx]] == in[LUT_ZZ[idx + 1]]) + break; + idx++; + } + if(idx == 63) + idx++; + + count = (char)(idx - srun); // count of unique bytes + *out++ = count; + while(count--) + *out++ = in[LUT_ZZ[srun++]]; + } + else + { + *out++ = -(count + 1); + *out++ = in[LUT_ZZ[idx]]; + idx++; + } + } + return(out); +} + +// ============================== +// Discrete Cosine Transformation +// ============================== + +void init_base(float quant) +{ + int y, x; + + for(y = 0; y < BLOCKSIZE; y++) + for(x = 0; x < BLOCKSIZE; x++) + { + if(y == 0) + dctbase[y][x] = 1; + else + dctbase[y][x] = SQRT2 * cos(((x * 2 + 1) * y * M_PI) / (BLOCKSIZE * 2)); + } + + for(y = 0; y < BLOCKSIZE * BLOCKSIZE; y++) + Quantise[y] = LUT_Quantise[y] / quant; +} + +void SplitComponents(byte *src, int width, int height) +{ + int i, j; + float *tr = red; + float *tg = green; + float *tb = blue; + + for(i = 0; i < BLOCKSIZE; i++, src += (width - BLOCKSIZE) * 4) + for(j = 0; j < BLOCKSIZE; j++) + { + *tr++ = ((float)*src++) - 128.0F; + *tg++ = ((float)*src++) - 128.0F; + *tb++ = ((float)*src++) - 128.0F; + src++; + } +} + +void transferH(float *src, float *dst) +{ + int y, dx, dy; + float sum; + float *work; + + for(y = 0; y < BLOCKSIZE; y++, src += BLOCKSIZE) + { + for(dy = 0; dy < BLOCKSIZE; dy++) + { + sum = 0; + work = src; + for(dx = 0; dx < BLOCKSIZE; dx++, work++) + sum += dctbase[dy][dx] * *work; + + *dst++ = sum / BLOCKSIZE; + } + } +} + +void transferV(float *src, float *dst) +{ + int x, dy, fy; + float sum; + float *work; + + for(x = 0; x < BLOCKSIZE; x++, src++, dst++) + { + for(fy = 0; fy < BLOCKSIZE; fy++) + { + sum = 0; + work = src; + for(dy = 0; dy < BLOCKSIZE; dy++, work += BLOCKSIZE) + sum += dctbase[fy][dy] * *work; + + dst[fy * BLOCKSIZE] = sum / BLOCKSIZE; + } + } +} + +char *Combine(byte *dst, float *p, float *q) +{ + int i, j; + byte rlesrc[BLOCKSIZE * BLOCKSIZE]; + int c; + byte *work; + + work = rlesrc; + for(j = 0; j < BLOCKSIZE; j++) + for(i = 0; i < BLOCKSIZE; i++) + { + c = (int)((*p++ / *q++) + 128.5F); + c -= 128; + + if(c < -128) + c = -128; + if(c > 127) + c = 127; + + *work++ = (char)c; + } + + dst = RLEZZ(rlesrc, dst); + return(dst); +} + +char *CombineComponents(char *dst, int width, int height) +{ + dst = Combine(dst, red, Quantise); + dst = Combine(dst, green, Quantise); + dst = Combine(dst, blue, Quantise); + return(dst); +} + +void DCT(cblock_t *out, cblock_t in, int width, int height) +{ + int x, y; + char *cursrc; + char *curdst; + + curdst = out->data; + for(y = 0; y < height; y += BLOCKSIZE) + for(x = 0; x < width; x += BLOCKSIZE) + { + cursrc = in.data + ((y * width) + x) * 4; + SplitComponents(cursrc, width, height); + transferH(red, temp); + transferV(temp, red); + transferH(green, temp); + transferV(temp, green); + transferH(blue, temp); + transferV(temp, blue); + curdst = CombineComponents(curdst, width, height); + } + out->count = curdst - out->data; +} + +// ================== +// 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); +} + +// ================== +// 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); +} + +// ================== +// 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; + + 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; + } + } +} + +// ================== +// Huffman1_Build +// ================== + +void Huffman1_Build() +{ + 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; +// easy to overflow 32 bits here! + for(j = 0; j < HUF_TOKENS; j++) + { + 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); + } +} + +// ================== +// 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 = SafeMalloc((in.count * 2) + 1024 + 4, "Huffman"); + memset(out_p, 0, (in.count * 2) + 1024 + 4); + + // leave space for compressed count + out_p += 4; + // write count + *(long *)out_p = in.count; + out_p += 4; + + // 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; + // 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; + } + } + out_p += (outbits + 7) >> 3; + out.count = out_p - out.data; + + out_p = out.data; + *(long *)out_p = out.count; + return(out); +} +// =================== +// LoadFrame +// =================== + +void LoadFrame(cblock_t *out, char *base, int frame) +{ + cblock_t in; + int width, height; + char name[1024]; + FILE *f; + + in.data = NULL; + in.count = -1; + sprintf (name, "%svideo/%s/%s%04i.tga", gamedir, base, base, frame); + + f = fopen(name, "rb"); + if (!f) + { + out->data = NULL; + return; + } + fclose (f); + + LoadTGA(name, &in.data, &width, &height); + if((width != cinehead.Width) || (height != cinehead.Height)) + { + free(in.data); + printf("Invalid picture size\n"); + out->data = NULL; + return; + } + out->data = SafeMalloc(width * height * 3, "LoadFrame"); // rle could possibly expand file so this not 100% safe (however DCT should force a lot of compression) + DCT(out, in, width, height); + free(in.data); +} + +// ================================== +// Cmd_Video +// +// video +// ================================== + +void Cmd_Video() +{ + char savename[256]; + char name[256]; + FILE *output; + int frame; + int width, height; + cblock_t in, huffman; + int size; + float dctconst; + int maxsize, ssize; + int min_rle_size, warnings; + int ave_image, ave_sound; + + GetScriptToken(false); + strcpy(base, token); + if (g_release) + return; + + GetScriptToken(false); + dctconst = atof(token); + GetScriptToken(false); + maxsize = atoi(token); + + sprintf (savename, "%svideo/%s.cin", gamedir, base); + + // clear stuff + memset(charbits1, 0, sizeof(charbits1)); + memset(charbitscount1, 0, sizeof(charbitscount1)); + memset(hnodes1, 0, sizeof(hnodes1)); + memset(numhnodes1, 0, sizeof(numhnodes1)); + memset(order0counts, 0, sizeof(order0counts)); + + // load the entire sound wav file if present + LoadSoundtrack(); + + cinehead.SndRate = wavinfo.rate; + cinehead.SndWidth = wavinfo.width; + cinehead.SndChannels = wavinfo.channels; + + sprintf(name, "%svideo/%s/%s0000.tga", gamedir, base, base); + printf("Loading sequence : %s\n", name); + printf("DCT constant : %f\n", dctconst); + + LoadTGA (name, NULL, &width, &height); + + output = fopen (savename, "wb"); + if (!output) + Error ("Can't open %s", savename); + + if((width % BLOCKSIZE) || (height % BLOCKSIZE)) + Error("Width and height must be a multiple of %d", BLOCKSIZE); + + cinehead.Width = width; + cinehead.Height = height; + init_base(dctconst); + + // build the dictionary + printf("Counting : "); + min_rle_size = 0; + for (frame = 0; ; frame++) + { + printf("."); + LoadFrame(&in, base, frame); + if(!in.data) + break; + Huffman1_Count(in); + if(in.count > min_rle_size) + min_rle_size = in.count; + free(in.data); + } + printf ("\n"); + cinehead.NumFrames = frame; + printf("Num Frames : %d\n", frame); + cinehead.MaxRleSize = (min_rle_size + 0x1f) & 0xfffffe0; + cinehead.MaxSndSize = ((4 * wavinfo.rate * wavinfo.channels / 14) + 0x1f) & 0xffffffe0; + + WriteHeader(output, FC_HEADER_NAME, FC_HEADER_VERSION, sizeof(CineHead_t), &cinehead); + + // build nodes and write counts + Huffman1_Build(); + WriteHeader(output, FC_HUFFBITS_NAME, FC_HUFFBITS_VERSION, sizeof(scaled), scaled); + WriteHeader(output, FC_QUANT_NAME, FC_QUANT_VERSION, sizeof(Quantise), Quantise); + + ave_image = 0; + ave_sound = 0; + warnings = 0; + // compress it with the dictionary + if(soundtrack) + { + ssize = WriteSound(output, frame, 4); + ave_sound += ssize; + } + + for (frame = 0; frame < cinehead.NumFrames; frame++) + { + // save some sound samples + printf ("Packing : ", frame); + LoadFrame(&in, base, frame); + + // save the image + huffman = Huffman1(in); + printf ("%d bytes rle, %d bytes huffman", in.count, huffman.count); + size = (huffman.count + 3) & 0xfffffffc; // round up to longwords + if(size > maxsize) + { + printf(" ** WARNING **"); + warnings++; + } + printf("\n"); + ave_image += huffman.count; + + WriteHeader(output, FC_IMAGE_NAME, FC_IMAGE_VERSION, size, huffman.data); + if(soundtrack) + { + ssize = WriteSound(output, frame + 4, 1); + ave_sound += ssize; + } + + free (in.data); + free (huffman.data); + } + printf("\nTotal size: %d (headers + %d image + %d sound)\n", ftell(output), ave_image, ave_sound); + printf("Data rate : %d bytes per sec (image and sound)\n", (ave_image + ave_sound) / cinehead.NumFrames); + printf("Cin created ok with %d warnings.\n", warnings); + fclose (output); + + if (soundtrack) + free (soundtrack); +} +#endif + +void Cmd_Video() +{ +} + +// end + diff --git a/misc/mediasource/netradiant-src/tools/quake3/common/aselib.c b/misc/mediasource/netradiant-src/tools/quake3/common/aselib.c new file mode 100644 index 00000000..980e7266 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/aselib.c @@ -0,0 +1,965 @@ +/* +Copyright (C) 1999-2006 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", token ); + } +} + +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/misc/mediasource/netradiant-src/tools/quake3/common/aselib.h b/misc/mediasource/netradiant-src/tools/quake3/common/aselib.h new file mode 100644 index 00000000..299e6053 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/aselib.h @@ -0,0 +1,31 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/bspfile.c b/misc/mediasource/netradiant-src/tools/quake3/common/bspfile.c new file mode 100644 index 00000000..828d0938 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/bspfile.c @@ -0,0 +1,706 @@ +/* +Copyright (C) 1999-2006 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 ; inext ) { + 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/misc/mediasource/netradiant-src/tools/quake3/common/bspfile.h b/misc/mediasource/netradiant-src/tools/quake3/common/bspfile.h new file mode 100644 index 00000000..ad70bae5 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/bspfile.h @@ -0,0 +1,121 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/cmdlib.c b/misc/mediasource/netradiant-src/tools/quake3/common/cmdlib.c new file mode 100644 index 00000000..5168d233 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/cmdlib.c @@ -0,0 +1,1179 @@ +/* +Copyright (C) 1999-2006 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 < (int) 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 < (int) 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 || 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 (!*gamedir) + Error ("ExpandGamePath called without gamedir 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 + if(!getcwd (out, 256)) *out = 0; + strcat (out, "/"); +#endif + while ( out[i] != 0 ) + { + if ( out[i] == '\\' ) + out[i] = '/'; + i++; + } +} + + +void Q_mkdir (const char *path) +{ + char parentbuf[256]; + const char *p = NULL; + int retry = 2; + while(retry--) + { +#ifdef WIN32 + const char *q = NULL; + if (_mkdir (path) != -1) + return; + if(errno == ENOENT) + { + p = strrchr(path, '/'); + q = strrchr(path, '\\'); + if(q && (!p || q < p)) + p = q; + } +#else + if (mkdir (path, 0777) != -1) + return; + if(errno == ENOENT) + p = strrchr(path, '/'); +#endif + if(p) + { + strncpy(parentbuf, path, sizeof(parentbuf)); + if((int) (p - path) < (int) sizeof(parentbuf)) + { + parentbuf[p - path] = 0; + Sys_Printf ("mkdir: %s: creating parent %s first\n", path, parentbuf); + Q_mkdir(parentbuf); + continue; + } + } + break; + } + 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 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/misc/mediasource/netradiant-src/tools/quake3/common/cmdlib.h b/misc/mediasource/netradiant-src/tools/quake3/common/cmdlib.h new file mode 100644 index 00000000..37890b46 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/cmdlib.h @@ -0,0 +1,168 @@ +/* +Copyright (C) 1999-2006 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 + + +#ifdef PATH_MAX +#define MAX_OS_PATH PATH_MAX +#else +#define MAX_OS_PATH 1024 +#endif +#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, ... ) +#ifdef __GNUC__ +__attribute__((noreturn)) +#endif +; +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/misc/mediasource/netradiant-src/tools/quake3/common/imagelib.c b/misc/mediasource/netradiant-src/tools/quake3/common/imagelib.c new file mode 100644 index 00000000..31e31850 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/imagelib.c @@ -0,0 +1,1249 @@ +/* +Copyright (C) 1999-2006 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 "inout.h" +#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 (countbpwidth) + 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 ; ydata; + + 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 */ + runLength = 0; + 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 ; iid_length, t->colormap_type, t->image_type, t->colormap_index, t->colormap_length, t->colormap_size, t->x_origin, t->y_origin, t->width, t->height, t->pixel_size, t->attributes); +} + +/* +============= +LoadTGABuffer +============= +*/ +void LoadTGABuffer (const byte *f, const byte *enddata, byte **pic, int *width, int *height) +{ + int x, y, row_inc, compressed, readpixelcount, red, green, blue, alpha, runlen, pindex, alphabits, image_width, image_height; + byte *pixbuf, *image_rgba; + const byte *fin; + unsigned char *p; + TargaHeader targa_header; + unsigned char palette[256*4]; + + *pic = NULL; + + // abort if it is too small to parse + if (enddata - f < 19) + return; + + targa_header.id_length = f[0]; + targa_header.colormap_type = f[1]; + targa_header.image_type = f[2]; + + targa_header.colormap_index = f[3] + f[4] * 256; + targa_header.colormap_length = f[5] + f[6] * 256; + targa_header.colormap_size = f[7]; + targa_header.x_origin = f[8] + f[9] * 256; + targa_header.y_origin = f[10] + f[11] * 256; + targa_header.width = image_width = f[12] + f[13] * 256; + targa_header.height = image_height = f[14] + f[15] * 256; + + targa_header.pixel_size = f[16]; + targa_header.attributes = f[17]; + + // advance to end of header + fin = f + 18; + + // skip TARGA image comment (usually 0 bytes) + fin += targa_header.id_length; + + // read/skip the colormap if present (note: according to the TARGA spec it + // can be present even on truecolor or greyscale images, just not used by + // the image data) + if (targa_header.colormap_type) + { + if (targa_header.colormap_length > 256) + { + TargaError(&targa_header, "LoadTGA: only up to 256 colormap_length supported\n"); + return; + } + if (targa_header.colormap_index) + { + TargaError(&targa_header, "LoadTGA: colormap_index not supported\n"); + return; + } + if (targa_header.colormap_size == 24) + { + for (x = 0;x < targa_header.colormap_length;x++) + { + palette[x*4+2] = *fin++; + palette[x*4+1] = *fin++; + palette[x*4+0] = *fin++; + palette[x*4+3] = 255; + } + } + else if (targa_header.colormap_size == 32) + { + for (x = 0;x < targa_header.colormap_length;x++) + { + palette[x*4+2] = *fin++; + palette[x*4+1] = *fin++; + palette[x*4+0] = *fin++; + palette[x*4+3] = *fin++; + } + } + else + { + TargaError(&targa_header, "LoadTGA: Only 32 and 24 bit colormap_size supported\n"); + return; + } + } + + // check our pixel_size restrictions according to image_type + if (targa_header.image_type == 2 || targa_header.image_type == 10) + { + if (targa_header.pixel_size != 24 && targa_header.pixel_size != 32) + { + TargaError(&targa_header, "LoadTGA: only 24bit and 32bit pixel sizes supported for type 2 and type 10 images\n"); + return; + } + } + else if (targa_header.image_type == 1 || targa_header.image_type == 9) + { + if (targa_header.pixel_size != 8) + { + TargaError(&targa_header, "LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n"); + return; + } + } + else if (targa_header.image_type == 3 || targa_header.image_type == 11) + { + if (targa_header.pixel_size != 8) + { + TargaError(&targa_header, "LoadTGA: only 8bit pixel size for type 1, 3, 9, and 11 images supported\n"); + return; + } + } + else + { + TargaError(&targa_header, "LoadTGA: Only type 1, 2, 3, 9, 10, and 11 targa RGB images supported"); + return; + } + + if (targa_header.attributes & 0x10) + { + TargaError(&targa_header, "LoadTGA: origin must be in top left or bottom left, top right and bottom right are not supported\n"); + return; + } + + // number of attribute bits per pixel, we only support 0 or 8 + alphabits = targa_header.attributes & 0x0F; + if (alphabits != 8 && alphabits != 0) + { + TargaError(&targa_header, "LoadTGA: only 0 or 8 attribute (alpha) bits supported\n"); + return; + } + + image_rgba = safe_malloc(image_width * image_height * 4); + if (!image_rgba) + { + Sys_Printf("LoadTGA: not enough memory for %i by %i image\n", image_width, image_height); + return; + } + + // If bit 5 of attributes isn't set, the image has been stored from bottom to top + if ((targa_header.attributes & 0x20) == 0) + { + pixbuf = image_rgba + (image_height - 1)*image_width*4; + row_inc = -image_width*4*2; + } + else + { + pixbuf = image_rgba; + row_inc = 0; + } + + compressed = targa_header.image_type == 9 || targa_header.image_type == 10 || targa_header.image_type == 11; + x = 0; + y = 0; + red = green = blue = alpha = 255; + while (y < image_height) + { + // decoder is mostly the same whether it's compressed or not + readpixelcount = 1000000; + runlen = 1000000; + if (compressed && fin < enddata) + { + runlen = *fin++; + // high bit indicates this is an RLE compressed run + if (runlen & 0x80) + readpixelcount = 1; + runlen = 1 + (runlen & 0x7f); + } + + while((runlen--) && y < image_height) + { + if (readpixelcount > 0) + { + readpixelcount--; + red = green = blue = alpha = 255; + if (fin < enddata) + { + switch(targa_header.image_type) + { + case 1: + case 9: + // colormapped + pindex = *fin++; + if (pindex >= targa_header.colormap_length) + pindex = 0; // error + p = palette + pindex * 4; + red = p[0]; + green = p[1]; + blue = p[2]; + alpha = p[3]; + break; + case 2: + case 10: + // BGR or BGRA + blue = *fin++; + if (fin < enddata) + green = *fin++; + if (fin < enddata) + red = *fin++; + if (targa_header.pixel_size == 32 && fin < enddata) + alpha = *fin++; + break; + case 3: + case 11: + // greyscale + red = green = blue = *fin++; + break; + } + if (!alphabits) + alpha = 255; + } + } + *pixbuf++ = red; + *pixbuf++ = green; + *pixbuf++ = blue; + *pixbuf++ = alpha; + x++; + if (x == image_width) + { + // end of line, advance to next + x = 0; + y++; + pixbuf += row_inc; + } + } + } + + *pic = image_rgba; + if (width) + *width = image_width; + if (height) + *height = image_height; +} + + +/* +============= +LoadTGA +============= +*/ +void LoadTGA (const char *name, byte **pixels, int *width, int *height) +{ + byte *buffer; + int nLen; + // + // load the file + // + nLen = vfsLoadFile ( name, (void **)&buffer, 0); + if (nLen == -1) + { + Error ("Couldn't read %s", name); + } + + LoadTGABuffer(buffer, buffer + nLen, 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>8; + buffer[14] = height&255; + buffer[15] = height>>8; + buffer[16] = 8; // pixel size + + f = fopen (filename, "wb"); + fwrite (buffer, 1, 18, f); + fwrite (data, 1, width * height, f); + fclose (f); +} + +/* +============================================================================ + +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/misc/mediasource/netradiant-src/tools/quake3/common/imagelib.h b/misc/mediasource/netradiant-src/tools/quake3/common/imagelib.h new file mode 100644 index 00000000..2371b48a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/imagelib.h @@ -0,0 +1,45 @@ +/* +Copyright (C) 1999-2006 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 ( const byte *buffer, const byte* enddata, byte **pic, int *width, int *height); +void WriteTGA (const char *filename, byte *data, int width, int height); +void WriteTGAGray (const char *filename, byte *data, int width, int height); + +void Load32BitImage (const char *name, unsigned **pixels, int *width, int *height); + diff --git a/misc/mediasource/netradiant-src/tools/quake3/common/inout.c b/misc/mediasource/netradiant-src/tools/quake3/common/inout.c new file mode 100644 index 00000000..9f7005ad --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/inout.c @@ -0,0 +1,375 @@ +/* +Copyright (C) 1999-2006 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, (xmlChar*)"point"); + xmlNodeSetContent (ret, (xmlChar*)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 < (int)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, (xmlChar*)"select"); + xmlNodeSetContent (node, (xmlChar*)buf); + level[0] = (int)'0' + (bError ? SYS_ERR : SYS_WRN) ; + level[1] = 0; + xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&level); + // a 'select' information + sprintf (buf, "%i %i", entitynum, brushnum); + select = xmlNewNode (NULL, (xmlChar*)"brush"); + xmlNodeSetContent (select, (xmlChar*)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, (xmlChar*)"pointmsg"); + xmlNodeSetContent (node, (xmlChar*)msg); + level[0] = (int)'0' + SYS_ERR; + level[1] = 0; + xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&level); + // a 'point' node + sprintf (buf, "%g %g %g", pt[0], pt[1], pt[2]); + point = xmlNewNode (NULL, (xmlChar*)"point"); + xmlNodeSetContent (point, (xmlChar*)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, (xmlChar*)"windingmsg"); + xmlNodeSetContent (node, (xmlChar*)msg); + level[0] = (int)'0' + SYS_ERR; + level[1] = 0; + xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&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, (xmlChar*)"winding"); + xmlNodeSetContent (winding, (xmlChar*)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(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("%s", 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((xmlChar*)"1.0"); + doc->children = xmlNewDocRawNode(doc, NULL, (xmlChar*)"q3map_feedback", NULL); + bGotXML = qtrue; + } + node = xmlNewNode (NULL, (xmlChar*)"message"); + { + gchar* utf8 = g_locale_to_utf8(buf, -1, NULL, NULL, NULL); + xmlNodeSetContent(node, (xmlChar*)utf8); + g_free(utf8); + } + level[0] = (int)'0' + flag; + level[1] = 0; + xmlSetProp (node, (xmlChar*)"level", (xmlChar *)&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/misc/mediasource/netradiant-src/tools/quake3/common/inout.h b/misc/mediasource/netradiant-src/tools/quake3/common/inout.h new file mode 100644 index 00000000..c60b0b85 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/inout.h @@ -0,0 +1,62 @@ +/* +Copyright (C) 1999-2006 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" +#include "mathlib.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/misc/mediasource/netradiant-src/tools/quake3/common/l3dslib.c b/misc/mediasource/netradiant-src/tools/quake3/common/l3dslib.c new file mode 100644 index 00000000..3030b0bf --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/l3dslib.c @@ -0,0 +1,301 @@ +/* +Copyright (C) 1999-2006 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 MAXVERTS) + Error ("Error: Too many vertices"); + + for (i=0 ; i MAXTRIANGLES) + Error ("Error: Too many triangles"); + + for (i=0 ; i 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/misc/mediasource/netradiant-src/tools/quake3/common/l3dslib.h b/misc/mediasource/netradiant-src/tools/quake3/common/l3dslib.h new file mode 100644 index 00000000..bac2433b --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/l3dslib.h @@ -0,0 +1,26 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/md4.c b/misc/mediasource/netradiant-src/tools/quake3/common/md4.c new file mode 100644 index 00000000..7c2c9be4 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/md4.c @@ -0,0 +1,227 @@ +/* + mdfour.c + + An implementation of MD4 designed for use in the samba SMB + authentication protocol + + Copyright (C) 1997-1998 Andrew Tridgell + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA + + $Id: mdfour.c 7689 2007-11-12 14:28:40Z divverent $ +*/ + +#include /* XoXus: needed for memset call */ +#include "md4.h" + +/* NOTE: This code makes no attempt to be fast! + + It assumes that a int is at least 32 bits long +*/ + +static struct mdfour *m; + +#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)) +#ifdef LARGE_INT32 +#define lshift(x,s) ((((x)<<(s))&0xFFFFFFFF) | (((x)>>(32-(s)))&0xFFFFFFFF)) +#else +#define lshift(x,s) (((x)<<(s)) | ((x)>>(32-(s)))) +#endif + +#define ROUND1(a,b,c,d,k,s) a = lshift(a + F(b,c,d) + X[k], s) +#define ROUND2(a,b,c,d,k,s) a = lshift(a + G(b,c,d) + X[k] + 0x5A827999,s) +#define ROUND3(a,b,c,d,k,s) a = lshift(a + H(b,c,d) + X[k] + 0x6ED9EBA1,s) + +/* this applies md4 to 64 byte chunks */ +static void mdfour64(uint32 *M) +{ + int j; + uint32 AA, BB, CC, DD; + uint32 X[16]; + uint32 A,B,C,D; + + for (j=0;j<16;j++) + X[j] = M[j]; + + A = m->A; B = m->B; C = m->C; D = m->D; + AA = A; BB = B; CC = C; DD = D; + + ROUND1(A,B,C,D, 0, 3); ROUND1(D,A,B,C, 1, 7); + ROUND1(C,D,A,B, 2, 11); ROUND1(B,C,D,A, 3, 19); + ROUND1(A,B,C,D, 4, 3); ROUND1(D,A,B,C, 5, 7); + ROUND1(C,D,A,B, 6, 11); ROUND1(B,C,D,A, 7, 19); + ROUND1(A,B,C,D, 8, 3); ROUND1(D,A,B,C, 9, 7); + ROUND1(C,D,A,B, 10, 11); ROUND1(B,C,D,A, 11, 19); + ROUND1(A,B,C,D, 12, 3); ROUND1(D,A,B,C, 13, 7); + ROUND1(C,D,A,B, 14, 11); ROUND1(B,C,D,A, 15, 19); + + ROUND2(A,B,C,D, 0, 3); ROUND2(D,A,B,C, 4, 5); + ROUND2(C,D,A,B, 8, 9); ROUND2(B,C,D,A, 12, 13); + ROUND2(A,B,C,D, 1, 3); ROUND2(D,A,B,C, 5, 5); + ROUND2(C,D,A,B, 9, 9); ROUND2(B,C,D,A, 13, 13); + ROUND2(A,B,C,D, 2, 3); ROUND2(D,A,B,C, 6, 5); + ROUND2(C,D,A,B, 10, 9); ROUND2(B,C,D,A, 14, 13); + ROUND2(A,B,C,D, 3, 3); ROUND2(D,A,B,C, 7, 5); + ROUND2(C,D,A,B, 11, 9); ROUND2(B,C,D,A, 15, 13); + + ROUND3(A,B,C,D, 0, 3); ROUND3(D,A,B,C, 8, 9); + ROUND3(C,D,A,B, 4, 11); ROUND3(B,C,D,A, 12, 15); + ROUND3(A,B,C,D, 2, 3); ROUND3(D,A,B,C, 10, 9); + ROUND3(C,D,A,B, 6, 11); ROUND3(B,C,D,A, 14, 15); + ROUND3(A,B,C,D, 1, 3); ROUND3(D,A,B,C, 9, 9); + ROUND3(C,D,A,B, 5, 11); ROUND3(B,C,D,A, 13, 15); + ROUND3(A,B,C,D, 3, 3); ROUND3(D,A,B,C, 11, 9); + ROUND3(C,D,A,B, 7, 11); ROUND3(B,C,D,A, 15, 15); + + A += AA; B += BB; C += CC; D += DD; + +#ifdef LARGE_INT32 + A &= 0xFFFFFFFF; B &= 0xFFFFFFFF; + C &= 0xFFFFFFFF; D &= 0xFFFFFFFF; +#endif + + for (j=0;j<16;j++) + X[j] = 0; + + m->A = A; m->B = B; m->C = C; m->D = D; +} + +static void copy64(uint32 *M, unsigned char *in) +{ + int i; + + for (i=0;i<16;i++) + M[i] = (in[i*4+3]<<24) | (in[i*4+2]<<16) | + (in[i*4+1]<<8) | (in[i*4+0]<<0); +} + +static void copy4(unsigned char *out,uint32 x) +{ + out[0] = x&0xFF; + out[1] = (x>>8)&0xFF; + out[2] = (x>>16)&0xFF; + out[3] = (x>>24)&0xFF; +} + +void mdfour_begin(struct mdfour *md) +{ + md->A = 0x67452301; + md->B = 0xefcdab89; + md->C = 0x98badcfe; + md->D = 0x10325476; + md->totalN = 0; +} + + +static void mdfour_tail(unsigned char *in, int n) +{ + unsigned char buf[128]; + uint32 M[16]; + uint32 b; + + m->totalN += n; + + b = m->totalN * 8; + + memset(buf, 0, 128); + if (n) memcpy(buf, in, n); + buf[n] = 0x80; + + if (n <= 55) { + copy4(buf+56, b); + copy64(M, buf); + mdfour64(M); + } else { + copy4(buf+120, b); + copy64(M, buf); + mdfour64(M); + copy64(M, buf+64); + mdfour64(M); + } +} + +void mdfour_update(struct mdfour *md, unsigned char *in, int n) +{ + uint32 M[16]; + +// start of edit by Forest 'LordHavoc' Hale +// commented out to prevent crashing when length is 0 +// if (n == 0) mdfour_tail(in, n); +// end of edit by Forest 'LordHavoc' Hale + + m = md; + + while (n >= 64) { + copy64(M, in); + mdfour64(M); + in += 64; + n -= 64; + m->totalN += 64; + } + + mdfour_tail(in, n); +} + + +void mdfour_result(struct mdfour *md, unsigned char *out) +{ + m = md; + + copy4(out, m->A); + copy4(out+4, m->B); + copy4(out+8, m->C); + copy4(out+12, m->D); +} + + +void mdfour(unsigned char *out, unsigned char *in, int n) +{ + struct mdfour md; + mdfour_begin(&md); + mdfour_update(&md, in, n); + mdfour_result(&md, out); +} + +/////////////////////////////////////////////////////////////// +// MD4-based checksum utility functions +// +// Copyright (C) 2000 Jeff Teunissen +// +// Author: Jeff Teunissen +// Date: 01 Jan 2000 + +unsigned Com_BlockChecksum (void *buffer, int length) +{ + int digest[4]; + unsigned val; + + mdfour ( (unsigned char *) digest, (unsigned char *) buffer, length ); + + val = digest[0] ^ digest[1] ^ digest[2] ^ digest[3]; + + return val; +} + +void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf) +{ + mdfour ( outbuf, (unsigned char *) buffer, len ); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/common/md4.h b/misc/mediasource/netradiant-src/tools/quake3/common/md4.h new file mode 100644 index 00000000..4373c2c9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/md4.h @@ -0,0 +1,57 @@ +/* + mdfour.h + + an implementation of MD4 designed for use in the SMB authentication + protocol + + Copyright (C) Andrew Tridgell 1997-1998 + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + See the GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA +*/ + +#ifndef _MDFOUR_H +#define _MDFOUR_H + +#ifndef int32 +#define int32 int +#endif + +#if SIZEOF_INT > 4 +#define LARGE_INT32 +#endif + +#ifndef uint32 +#define uint32 unsigned int32 +#endif + +struct mdfour { + uint32 A, B, C, D; + uint32 totalN; +}; + +void mdfour_begin(struct mdfour *md); // old: MD4Init +void mdfour_update(struct mdfour *md, unsigned char *in, int n); //old: MD4Update +void mdfour_result(struct mdfour *md, unsigned char *out); // old: MD4Final +void mdfour(unsigned char *out, unsigned char *in, int n); + +unsigned Com_BlockChecksum (void *buffer, int length); +void Com_BlockFullChecksum (void *buffer, int len, unsigned char *outbuf); + +#endif // _MDFOUR_H + diff --git a/misc/mediasource/netradiant-src/tools/quake3/common/mutex.c b/misc/mediasource/netradiant-src/tools/quake3/common/mutex.c new file mode 100644 index 00000000..38a383d6 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/mutex.c @@ -0,0 +1,197 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/mutex.h b/misc/mediasource/netradiant-src/tools/quake3/common/mutex.h new file mode 100644 index 00000000..aa929923 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/mutex.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/polylib.c b/misc/mediasource/netradiant-src/tools/quake3/common/polylib.c new file mode 100644 index 00000000..34dd173e --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/polylib.c @@ -0,0 +1,1109 @@ +/* +Copyright (C) 1999-2006 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 ; inumpoints ; 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; +} + +/* +============= +AllocWindingAccu +============= +*/ +winding_accu_t *AllocWindingAccu(int points) +{ + winding_accu_t *w; + int s; + + if (points >= MAX_POINTS_ON_WINDING) + Error("AllocWindingAccu failed: MAX_POINTS_ON_WINDING exceeded"); + + if (numthreads == 1) + { + // At the time of this writing, these statistics were not used in any way. + 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_accu_t) * 3 * points + sizeof(int); + w = safe_malloc(s); + memset(w, 0, s); + return w; +} + +/* +============= +FreeWinding +============= +*/ +void FreeWinding (winding_t *w) +{ + if (!w) Error("FreeWinding: winding is NULL"); + + if (*(unsigned *)w == 0xdeaddead) + Error ("FreeWinding: freed a freed winding"); + *(unsigned *)w = 0xdeaddead; + + if (numthreads == 1) + c_active_windings--; + free (w); +} + +/* +============= +FreeWindingAccu +============= +*/ +void FreeWindingAccu(winding_accu_t *w) +{ + if (!w) Error("FreeWindingAccu: winding is NULL"); + + if (*((unsigned *) w) == 0xdeaddead) + Error("FreeWindingAccu: 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; i++) + VectorAdd (w->p[i], center, center); + + scale = 1.0/w->numpoints; + VectorScale (center, scale, center); +} + +/* +================= +BaseWindingForPlaneAccu +================= +*/ +winding_accu_t *BaseWindingForPlaneAccu(vec3_t normal, vec_t dist) +{ + // The goal in this function is to replicate the behavior of the original BaseWindingForPlane() + // function (see below) but at the same time increasing accuracy substantially. + + // The original code gave a preference for the vup vector to start out as (0, 0, 1), unless the + // normal had a dominant Z value, in which case vup started out as (1, 0, 0). After that, vup + // was "bent" [along the plane defined by normal and vup] to become perpendicular to normal. + // After that the vright vector was computed as the cross product of vup and normal. + + // I'm constructing the winding polygon points in a fashion similar to the method used in the + // original function. Orientation is the same. The size of the winding polygon, however, is + // variable in this function (depending on the angle of normal), and is larger (by about a factor + // of 2) than the winding polygon in the original function. + + int x, i; + vec_t max, v; + vec3_accu_t vright, vup, org, normalAccu; + winding_accu_t *w; + + // One of the components of normal must have a magnitiude greater than this value, + // otherwise normal is not a unit vector. This is a little bit of inexpensive + // partial error checking we can do. + max = 0.56; // 1 / sqrt(1^2 + 1^2 + 1^2) = 0.577350269 + + x = -1; + for (i = 0; i < 3; i++) { + v = (vec_t) fabs(normal[i]); + if (v > max) { + x = i; + max = v; + } + } + if (x == -1) Error("BaseWindingForPlaneAccu: no dominant axis found because normal is too short"); + + switch (x) { + case 0: // Fall through to next case. + case 1: + vright[0] = (vec_accu_t) -normal[1]; + vright[1] = (vec_accu_t) normal[0]; + vright[2] = 0; + break; + case 2: + vright[0] = 0; + vright[1] = (vec_accu_t) -normal[2]; + vright[2] = (vec_accu_t) normal[1]; + break; + } + + // vright and normal are now perpendicular; you can prove this by taking their + // dot product and seeing that it's always exactly 0 (with no error). + + // NOTE: vright is NOT a unit vector at this point. vright will have length + // not exceeding 1.0. The minimum length that vright can achieve happens when, + // for example, the Z and X components of the normal input vector are equal, + // and when normal's Y component is zero. In that case Z and X of the normal + // vector are both approximately 0.70711. The resulting vright vector in this + // case will have a length of 0.70711. + + // We're relying on the fact that MAX_WORLD_COORD is a power of 2 to keep + // our calculation precise and relatively free of floating point error. + // [However, the code will still work fine if that's not the case.] + VectorScaleAccu(vright, ((vec_accu_t) MAX_WORLD_COORD) * 4.0, vright); + + // At time time of this writing, MAX_WORLD_COORD was 65536 (2^16). Therefore + // the length of vright at this point is at least 185364. In comparison, a + // corner of the world at location (65536, 65536, 65536) is distance 113512 + // away from the origin. + + VectorCopyRegularToAccu(normal, normalAccu); + CrossProductAccu(normalAccu, vright, vup); + + // vup now has length equal to that of vright. + + VectorScaleAccu(normalAccu, (vec_accu_t) dist, org); + + // org is now a point on the plane defined by normal and dist. Furthermore, + // org, vright, and vup are pairwise perpendicular. Now, the 4 vectors + // { (+-)vright + (+-)vup } have length that is at least sqrt(185364^2 + 185364^2), + // which is about 262144. That length lies outside the world, since the furthest + // point in the world has distance 113512 from the origin as mentioned above. + // Also, these 4 vectors are perpendicular to the org vector. So adding them + // to org will only increase their length. Therefore the 4 points defined below + // all lie outside of the world. Furthermore, it can be easily seen that the + // edges connecting these 4 points (in the winding_accu_t below) lie completely + // outside the world. sqrt(262144^2 + 262144^2)/2 = 185363, which is greater than + // 113512. + + w = AllocWindingAccu(4); + + VectorSubtractAccu(org, vright, w->p[0]); + VectorAddAccu(w->p[0], vup, w->p[0]); + + VectorAddAccu(org, vright, w->p[1]); + VectorAddAccu(w->p[1], vup, w->p[1]); + + VectorAddAccu(org, vright, w->p[2]); + VectorSubtractAccu(w->p[2], vup, w->p[2]); + + VectorSubtractAccu(org, vright, w->p[3]); + VectorSubtractAccu(w->p[3], vup, w->p[3]); + + w->numpoints = 4; + + return w; +} + +/* +================= +BaseWindingForPlane + +Original BaseWindingForPlane() function that has serious accuracy problems. Here is why. +The base winding is computed as a rectangle with very large coordinates. These coordinates +are in the range 2^17 or 2^18. "Epsilon" (meaning the distance between two adjacent numbers) +at these magnitudes in 32 bit floating point world is about 0.02. So for example, if things +go badly (by bad luck), then the whole plane could be shifted by 0.02 units (its distance could +be off by that much). Then if we were to compute the winding of this plane and another of +the brush's planes met this winding at a very acute angle, that error could multiply to around +0.1 or more when computing the final vertex coordinates of the winding. 0.1 is a very large +error, and can lead to all sorts of disappearing triangle problems. +================= +*/ +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); + + // LordHavoc: this has to use *2 because otherwise some created points may + // be inside the world (think of a diagonal case), and any brush with such + // points should be removed, failure to detect such cases is disasterous + VectorScale (vup, MAX_WORLD_COORD*2, vup); + VectorScale (vright, MAX_WORLD_COORD*2, 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) +{ + size_t size; + winding_t *c; + + if (!w) Error("CopyWinding: winding is NULL"); + + c = AllocWinding (w->numpoints); + size = (size_t)((winding_t *)NULL)->p[w->numpoints]; + memcpy (c, w, size); + return c; +} + +/* +================== +CopyWindingAccuIncreaseSizeAndFreeOld +================== +*/ +winding_accu_t *CopyWindingAccuIncreaseSizeAndFreeOld(winding_accu_t *w) +{ + int i; + winding_accu_t *c; + + if (!w) Error("CopyWindingAccuIncreaseSizeAndFreeOld: winding is NULL"); + + c = AllocWindingAccu(w->numpoints + 1); + c->numpoints = w->numpoints; + for (i = 0; i < c->numpoints; i++) + { + VectorCopyAccu(w->p[i], c->p[i]); + } + FreeWindingAccu(w); + return c; +} + +/* +================== +CopyWindingAccuToRegular +================== +*/ +winding_t *CopyWindingAccuToRegular(winding_accu_t *w) +{ + int i; + winding_t *c; + + if (!w) Error("CopyWindingAccuToRegular: winding is NULL"); + + c = AllocWinding(w->numpoints); + c->numpoints = w->numpoints; + for (i = 0; i < c->numpoints; i++) + { + VectorCopyAccuToRegular(w->p[i], c->p[i]); + } + return c; +} + +/* +================== +ReverseWinding +================== +*/ +winding_t *ReverseWinding (winding_t *w) +{ + int i; + winding_t *c; + + c = AllocWinding (w->numpoints); + for (i=0 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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"); +} + + +/* +============= +ChopWindingInPlaceAccu +============= +*/ +void ChopWindingInPlaceAccu(winding_accu_t **inout, vec3_t normal, vec_t dist, vec_t crudeEpsilon) +{ + vec_accu_t fineEpsilon; + winding_accu_t *in; + int counts[3]; + int i, j; + vec_accu_t dists[MAX_POINTS_ON_WINDING + 1]; + int sides[MAX_POINTS_ON_WINDING + 1]; + int maxpts; + winding_accu_t *f; + vec_accu_t *p1, *p2; + vec_accu_t w; + vec3_accu_t mid, normalAccu; + + // We require at least a very small epsilon. It's a good idea for several reasons. + // First, we will be dividing by a potentially very small distance below. We don't + // want that distance to be too small; otherwise, things "blow up" with little accuracy + // due to the division. (After a second look, the value w below is in range (0,1), but + // graininess problem remains.) Second, Having minimum epsilon also prevents the following + // situation. Say for example we have a perfect octagon defined by the input winding. + // Say our chopping plane (defined by normal and dist) is essentially the same plane + // that the octagon is sitting on. Well, due to rounding errors, it may be that point + // 1 of the octagon might be in front, point 2 might be in back, point 3 might be in + // front, point 4 might be in back, and so on. So we could end up with a very ugly- + // looking chopped winding, and this might be undesirable, and would at least lead to + // a possible exhaustion of MAX_POINTS_ON_WINDING. It's better to assume that points + // very very close to the plane are on the plane, using an infinitesimal epsilon amount. + + // Now, the original ChopWindingInPlace() function used a vec_t-based winding_t. + // So this minimum epsilon is quite similar to casting the higher resolution numbers to + // the lower resolution and comparing them in the lower resolution mode. We explicitly + // choose the minimum epsilon as something around the vec_t epsilon of one because we + // want the resolution of vec_accu_t to have a large resolution around the epsilon. + // Some of that leftover resolution even goes away after we scale to points far away. + + // Here is a further discussion regarding the choice of smallestEpsilonAllowed. + // In the 32 float world (we can assume vec_t is that), the "epsilon around 1.0" is + // 0.00000011921. In the 64 bit float world (we can assume vec_accu_t is that), the + // "epsilon around 1.0" is 0.00000000000000022204. (By the way these two epsilons + // are defined as VEC_SMALLEST_EPSILON_AROUND_ONE VEC_ACCU_SMALLEST_EPSILON_AROUND_ONE + // respectively.) If you divide the first by the second, you get approximately + // 536,885,246. Dividing that number by 200,000 (a typical base winding coordinate) + // gives 2684. So in other words, if our smallestEpsilonAllowed was chosen as exactly + // VEC_SMALLEST_EPSILON_AROUND_ONE, you would be guaranteed at least 2000 "ticks" in + // 64-bit land inside of the epsilon for all numbers we're dealing with. + + static const vec_accu_t smallestEpsilonAllowed = ((vec_accu_t) VEC_SMALLEST_EPSILON_AROUND_ONE) * 0.5; + if (crudeEpsilon < smallestEpsilonAllowed) fineEpsilon = smallestEpsilonAllowed; + else fineEpsilon = (vec_accu_t) crudeEpsilon; + + in = *inout; + counts[0] = counts[1] = counts[2] = 0; + VectorCopyRegularToAccu(normal, normalAccu); + + for (i = 0; i < in->numpoints; i++) + { + dists[i] = DotProductAccu(in->p[i], normalAccu) - dist; + if (dists[i] > fineEpsilon) sides[i] = SIDE_FRONT; + else if (dists[i] < -fineEpsilon) sides[i] = SIDE_BACK; + else sides[i] = SIDE_ON; + counts[sides[i]]++; + } + sides[i] = sides[0]; + dists[i] = dists[0]; + + // I'm wondering if whatever code that handles duplicate planes is robust enough + // that we never get a case where two nearly equal planes result in 2 NULL windings + // due to the 'if' statement below. TODO: Investigate this. + if (!counts[SIDE_FRONT]) { + FreeWindingAccu(in); + *inout = NULL; + return; + } + if (!counts[SIDE_BACK]) { + return; // Winding is unmodified. + } + + // NOTE: The least number of points that a winding can have at this point is 2. + // In that case, one point is SIDE_FRONT and the other is SIDE_BACK. + + maxpts = counts[SIDE_FRONT] + 2; // We dynamically expand if this is too small. + f = AllocWindingAccu(maxpts); + + for (i = 0; i < in->numpoints; i++) + { + p1 = in->p[i]; + + if (sides[i] == SIDE_ON || sides[i] == SIDE_FRONT) + { + if (f->numpoints >= MAX_POINTS_ON_WINDING) + Error("ChopWindingInPlaceAccu: MAX_POINTS_ON_WINDING"); + if (f->numpoints >= maxpts) // This will probably never happen. + { + Sys_FPrintf(SYS_VRB, "WARNING: estimate on chopped winding size incorrect (no problem)\n"); + f = CopyWindingAccuIncreaseSizeAndFreeOld(f); + maxpts++; + } + VectorCopyAccu(p1, f->p[f->numpoints]); + f->numpoints++; + if (sides[i] == SIDE_ON) continue; + } + if (sides[i + 1] == SIDE_ON || sides[i + 1] == sides[i]) + { + continue; + } + + // Generate a split point. + p2 = in->p[((i + 1) == in->numpoints) ? 0 : (i + 1)]; + + // The divisor's absolute value is greater than the dividend's absolute value. + // w is in the range (0,1). + w = dists[i] / (dists[i] - dists[i + 1]); + + for (j = 0; j < 3; j++) + { + // Avoid round-off error when possible. Check axis-aligned normal. + if (normal[j] == 1) mid[j] = dist; + else if (normal[j] == -1) mid[j] = -dist; + else mid[j] = p1[j] + (w * (p2[j] - p1[j])); + } + if (f->numpoints >= MAX_POINTS_ON_WINDING) + Error("ChopWindingInPlaceAccu: MAX_POINTS_ON_WINDING"); + if (f->numpoints >= maxpts) // This will probably never happen. + { + Sys_FPrintf(SYS_VRB, "WARNING: estimate on chopped winding size incorrect (no problem)\n"); + f = CopyWindingAccuIncreaseSizeAndFreeOld(f); + maxpts++; + } + VectorCopyAccu(mid, f->p[f->numpoints]); + f->numpoints++; + } + + FreeWindingAccu(in); + *inout = f; +} + +/* +============= +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 ; inumpoints ; 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 ; inumpoints ; 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 ; inumpoints ; 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 ; jnumpoints ; 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 ; inumpoints ; 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/misc/mediasource/netradiant-src/tools/quake3/common/polylib.h b/misc/mediasource/netradiant-src/tools/quake3/common/polylib.h new file mode 100644 index 00000000..1f4495d9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/polylib.h @@ -0,0 +1,74 @@ +/* +Copyright (C) 1999-2006 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 512 + +// 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); + + +/////////////////////////////////////////////////////////////////////////////////////// +// Below is double-precision stuff. This was initially needed by the base winding code +// in q3map2 brush processing. +/////////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int numpoints; + vec3_accu_t p[4]; // variable sized +} winding_accu_t; + +winding_accu_t *BaseWindingForPlaneAccu(vec3_t normal, vec_t dist); +void ChopWindingInPlaceAccu(winding_accu_t **w, vec3_t normal, vec_t dist, vec_t epsilon); +winding_t *CopyWindingAccuToRegular(winding_accu_t *w); +void FreeWindingAccu(winding_accu_t *w); diff --git a/misc/mediasource/netradiant-src/tools/quake3/common/polyset.h b/misc/mediasource/netradiant-src/tools/quake3/common/polyset.h new file mode 100644 index 00000000..12993999 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/polyset.h @@ -0,0 +1,51 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/qfiles.h b/misc/mediasource/netradiant-src/tools/quake3/common/qfiles.h new file mode 100644 index 00000000..29e94978 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/qfiles.h @@ -0,0 +1,489 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/qthreads.h b/misc/mediasource/netradiant-src/tools/quake3/common/qthreads.h new file mode 100644 index 00000000..ab806030 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/qthreads.h @@ -0,0 +1,31 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/scriplib.c b/misc/mediasource/netradiant-src/tools/quake3/common/scriplib.c new file mode 100644 index 00000000..47196e53 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/scriplib.c @@ -0,0 +1,409 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/scriplib.h b/misc/mediasource/netradiant-src/tools/quake3/common/scriplib.h new file mode 100644 index 00000000..1e3f2c31 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/scriplib.h @@ -0,0 +1,55 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/surfaceflags.h b/misc/mediasource/netradiant-src/tools/quake3/common/surfaceflags.h new file mode 100644 index 00000000..d7ab2ba7 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/surfaceflags.h @@ -0,0 +1,114 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/threads.c b/misc/mediasource/netradiant-src/tools/quake3/common/threads.c new file mode 100644 index 00000000..7f404a4f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/threads.c @@ -0,0 +1,634 @@ +/* +Copyright (C) 1999-2006 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 = 40*dispatch / workcount; + if(f < oldf) + { + Sys_Printf("warning: progress went backwards (should never happen)\n"); + oldf = f; + } + while(f > oldf) + { + ++oldf; + if (pacifier) + { + if(oldf % 4 == 0) + Sys_Printf("%i", f / 4); + else + Sys_Printf ("."); + 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 + +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 +#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 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_attr_t attr; + pthread_t work_threads[MAX_THREADS]; + size_t stacksize; + + int start, end; + int i=0, status=0; + + start = I_FloatTime (); + pacifier = showpacifier; + + dispatch = 0; + oldf = -1; + workcount = workcnt; + + pthread_attr_init(&attr); + if(pthread_attr_setstacksize(&attr, 8388608) != 0) + { + stacksize = 0; + pthread_attr_getstacksize(&attr, &stacksize); + Sys_Printf("Could not set a per-thread stack size of 8 MB, using only %.2f MB\n", stacksize / 1048576.0); + } + + 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 (pthread_mutexattr_settype(&mattrib, PTHREAD_MUTEX_ERRORCHECK) != 0) + Error ("pthread_mutexattr_settype failed"); + recursive_mutex_init(mattrib); + + for (i=0 ; i +#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 ; iverts[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/misc/mediasource/netradiant-src/tools/quake3/common/trilib.h b/misc/mediasource/netradiant-src/tools/quake3/common/trilib.h new file mode 100644 index 00000000..89dcf764 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/trilib.h @@ -0,0 +1,26 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/unzip.c b/misc/mediasource/netradiant-src/tools/quake3/common/unzip.c new file mode 100644 index 00000000..1e2be2be --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/unzip.c @@ -0,0 +1,4609 @@ +/* +Copyright (C) 1999-2006 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; + + if(fread( &v, sizeof(v), 1, fin ) != 1) + return UNZ_EOF; + + *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; + + if(fread( &v, sizeof(v), 1, fin ) != 1) + return UNZ_EOF; + + *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 ? (uInt)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 */ + r.base = 0; + } + 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/misc/mediasource/netradiant-src/tools/quake3/common/unzip.h b/misc/mediasource/netradiant-src/tools/quake3/common/unzip.h new file mode 100644 index 00000000..5cbfce93 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/unzip.h @@ -0,0 +1,321 @@ +/* +Copyright (C) 1999-2006 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/misc/mediasource/netradiant-src/tools/quake3/common/vfs.c b/misc/mediasource/netradiant-src/tools/quake3/common/vfs.c new file mode 100644 index 00000000..86a749c7 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/vfs.c @@ -0,0 +1,396 @@ +/* +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 +#include +#include + +#include "cmdlib.h" +#include "mathlib.h" +#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+1]; +static int g_numDirs; +char g_strForbiddenDirs[VFS_MAXDIRS][PATH_MAX+1]; +int g_numForbiddenDirs = 0; +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; + int j; + + for(j = 0; j < g_numForbiddenDirs; ++j) + { + if(!Q_stricmp(path, g_strForbiddenDirs[j]) + || (strlen(path) > strlen(g_strForbiddenDirs[j]) && path[strlen(path) - strlen(g_strForbiddenDirs[j]) - 1] == '/' && !Q_stricmp(path + strlen(path) - strlen(g_strForbiddenDirs[j]), g_strForbiddenDirs[j]))) + break; + } + if(j < g_numForbiddenDirs) + return; + + if (g_numDirs == VFS_MAXDIRS) + return; + + Sys_Printf ("VFS Init: %s\n", path); + + strncpy (g_strDirs[g_numDirs], path, PATH_MAX); + g_strDirs[g_numDirs][PATH_MAX] = 0; + 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; + + for(j = 0; j < g_numForbiddenDirs; ++j) + if(!Q_stricmp(name, g_strForbiddenDirs[j])) + break; + if(j < g_numForbiddenDirs) + continue; + + dirlist = g_strdup(name); + + { + char *ext = strrchr (dirlist, '.'); + + if(ext && !Q_stricmp(ext, ".pk3dir")) + { + if (g_numDirs == VFS_MAXDIRS) + continue; + snprintf(g_strDirs[g_numDirs], PATH_MAX, "%s/%s", path, name); + g_strDirs[g_numDirs][PATH_MAX] = '\0'; + vfsFixDOSName (g_strDirs[g_numDirs]); + vfsAddSlash (g_strDirs[g_numDirs]); + ++g_numDirs; + } + + 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) + { + fclose(f); + return -1; + } + + if(fread (*bufferptr, 1, len, f) != (size_t) len) + { + fclose(f); + return -1; + } + 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) + { + fclose(f); + return -1; + } + + if(fread (*bufferptr, 1, len, f) != (size_t) len) + { + fclose(f); + return -1; + } + 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/misc/mediasource/netradiant-src/tools/quake3/common/vfs.h b/misc/mediasource/netradiant-src/tools/quake3/common/vfs.h new file mode 100644 index 00000000..93731a1e --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/common/vfs.h @@ -0,0 +1,58 @@ +/* +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_ + +// to get PATH_MAX +#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 + +#define VFS_MAXDIRS 64 + +void vfsInitDirectory (const char *path); +void vfsShutdown (); +int vfsGetFileCount (const char *filename); +int vfsLoadFile (const char *filename, void **buffer, int index); + +extern char g_strForbiddenDirs[VFS_MAXDIRS][PATH_MAX+1]; +extern int g_numForbiddenDirs; + +#endif // _VFS_H_ diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3data/.cvswrappers b/misc/mediasource/netradiant-src/tools/quake3/q3data/.cvswrappers new file mode 100644 index 00000000..2ea7d171 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/.cvswrappers @@ -0,0 +1,2 @@ +*.dsp -m 'COPY' -k 'b' +*.dsw -m 'COPY' -k 'b' diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3data/3dslib.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/3dslib.c new file mode 100644 index 00000000..e2012c70 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/3dslib.c @@ -0,0 +1,651 @@ +/* +Copyright (C) 1999-2006 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 "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/misc/mediasource/netradiant-src/tools/quake3/q3data/3dslib.h b/misc/mediasource/netradiant-src/tools/quake3/q3data/3dslib.h new file mode 100644 index 00000000..406fe2d7 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/3dslib.h @@ -0,0 +1,139 @@ +/* +Copyright (C) 1999-2006 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 +{ + 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/misc/mediasource/netradiant-src/tools/quake3/q3data/compress.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/compress.c new file mode 100644 index 00000000..fdf9043a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/compress.c @@ -0,0 +1,771 @@ +/* +Copyright (C) 1999-2006 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 "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 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>8)&255; + *out_p++ = (in.count>>16)&255; + *out_p++ = (in.count>>24)&255; + + // write head index + for (i=0 ; i>8)&255; + *out_p++ = (i>>16)&255; + *out_p++ = (i>>24)&255; + + // write the L column + for (i=0 ; i 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 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>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 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) + max = in.count - i; + + start = lzss_head[val]; + while (start != -1 && start >= i-BACK_WINDOW) + { + // count match length + for (j=0 ; 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 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<>3] |= 1<<(outbits&7); + } + else + { // output a phrase + outbits++; // leave a 0 bit to mark phrase + for (j=0 ; j>3] |= 1<<(outbits&7); + for (j=0 ; j>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 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 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 max) + max = hnodes1[i][j].count; + } + if (max == 0) + max = 1; + total = 0; + for (j=0 ; j 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>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<>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/misc/mediasource/netradiant-src/tools/quake3/q3data/images.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/images.c new file mode 100644 index 00000000..5009ae38 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/images.c @@ -0,0 +1,486 @@ +/* +Copyright (C) 1999-2006 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 "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 ; ybyteimagewidth || 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 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 +#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/misc/mediasource/netradiant-src/tools/quake3/q3data/md3lib.h b/misc/mediasource/netradiant-src/tools/quake3/q3data/md3lib.h new file mode 100644 index 00000000..fbf48b57 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/md3lib.h @@ -0,0 +1,28 @@ +/* +Copyright (C) 1999-2006 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 "../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/misc/mediasource/netradiant-src/tools/quake3/q3data/models.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/models.c new file mode 100644 index 00000000..b87dc625 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/models.c @@ -0,0 +1,2155 @@ +/* +Copyright (C) 1999-2006 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 "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 ; fshaders[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; iverts[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/misc/mediasource/netradiant-src/tools/quake3/q3data/oldstuff.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/oldstuff.c new file mode 100644 index 00000000..045c67e7 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/oldstuff.c @@ -0,0 +1,151 @@ +/* +Copyright (C) 1999-2006 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 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/misc/mediasource/netradiant-src/tools/quake3/q3data/p3dlib.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/p3dlib.c new file mode 100644 index 00000000..3ccdfbe1 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/p3dlib.c @@ -0,0 +1,345 @@ +/* +Copyright (C) 1999-2006 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 "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/misc/mediasource/netradiant-src/tools/quake3/q3data/p3dlib.h b/misc/mediasource/netradiant-src/tools/quake3/q3data/p3dlib.h new file mode 100644 index 00000000..1bd63078 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/p3dlib.h @@ -0,0 +1,29 @@ +/* +Copyright (C) 1999-2006 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 +*/ + + +#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/misc/mediasource/netradiant-src/tools/quake3/q3data/polyset.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/polyset.c new file mode 100644 index 00000000..cdb0cda7 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/polyset.c @@ -0,0 +1,273 @@ +/* +Copyright (C) 1999-2006 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 "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/misc/mediasource/netradiant-src/tools/quake3/q3data/q3data.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/q3data.c new file mode 100644 index 00000000..81f4ae61 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/q3data.c @@ -0,0 +1,666 @@ +/* +Copyright (C) 1999-2006 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 +*/ + +#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 ; id_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] [-dump ] [-release ] [-only ] [-3dsconvert ] [-verbose] [file.qdt]"); + + for ( ; i +#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/misc/mediasource/netradiant-src/tools/quake3/q3data/stripper.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/stripper.c new file mode 100644 index 00000000..76fc96b3 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/stripper.c @@ -0,0 +1,303 @@ +/* +Copyright (C) 1999-2006 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 +#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/misc/mediasource/netradiant-src/tools/quake3/q3data/video.c b/misc/mediasource/netradiant-src/tools/quake3/q3data/video.c new file mode 100644 index 00000000..afabdeb9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3data/video.c @@ -0,0 +1,1153 @@ +/* +Copyright (C) 1999-2006 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 "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 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/misc/mediasource/netradiant-src/tools/quake3/q3map2/.patchsets b/misc/mediasource/netradiant-src/tools/quake3/q3map2/.patchsets new file mode 100644 index 00000000..70846872 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/.patchsets @@ -0,0 +1,3 @@ +master = https://zerowing.idsoftware.com/svn/radiant/GtkRadiant/trunk/tools/quake3/q3map2 +revisions_applied = 1-321 + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/branch-manager b/misc/mediasource/netradiant-src/tools/quake3/q3map2/branch-manager new file mode 100644 index 00000000..2fd5a8fd --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/branch-manager @@ -0,0 +1,344 @@ +#!/usr/bin/perl + +use strict; +use warnings; + +sub OutputOf($@) +{ + my ($cmd, @args) = @_; + $cmd =~ s/#(\d)/"\$ARG$1"/g; + $ENV{"ARG$_"} = $args[$_-1] + for 1..@args; + + open my $fh, '-|', $cmd + or die "popen $cmd: $!"; + + $ENV{"ARG$_"} = '' + for 1..@args; + + undef local $/; + my $ret = <$fh>; + close $fh; + + return $ret; +} + +my %conf = +( + master => '', + revisions_applied => '' +); +my @revisions_applied = (); # array of [first, last] ranges + +sub LoadSettings() +{ + open my $fh, '<', ".patchsets" + or return; + while(<$fh>) + { + chomp; + /^([^=]*?)\s*=\s*(.*?)$/s + or next; + die "Invalid config item: $1 (allowed: @{[sort keys %conf]})" + if not exists $conf{$1}; + $conf{$1} = $2; + } + + @revisions_applied = map { /^(\d+)-(\d+)$/s or die "Invalid revision spec $_"; [$1, $2]; } split /,/, $conf{revisions_applied}; +} + +sub WriteSettings() +{ + $conf{revisions_applied} = join ',', map { "$_->[0]-$_->[1]" } @revisions_applied; + + open my $fh, '>', ".patchsets" + or die "writing settings: $!"; + for(sort keys %conf) + { + print $fh "$_ = $conf{$_}\n"; + } +} + +sub AddPatch($$) +{ + my ($first, $last) = @_; + die "Invalid range" if $first > $last; + + my @rev = sort { $a->[0] <=> $b->[0] } (@revisions_applied, [$first, $last]); + + my $i = 0; + while($i < @rev - 1) + { + my $a = $rev[$i][0]; + my $b = $rev[$i][1]; + my $c = $rev[$i+1][0]; + my $d = $rev[$i+1][1]; + + if($b >= $c) + { + die "overlapping patch: $a-$b overlaps $c-$d"; + } + if($b == $c - 1) + { + splice @rev, $i, 2, [$a, $d]; + next; + } + ++$i; + } + + @revisions_applied = @rev; +} + +sub RemovePatch($$) +{ + my ($first, $last) = @_; + die "Invalid range" if $first > $last; + + my @rev = sort { $a->[0] <=> $b->[0] } (@revisions_applied); + + my $i = 0; + while($i < @rev) + { + my $a = $rev[$i][0]; + my $b = $rev[$i][1]; + + if($first >= $a && $last <= $b) + { + # this is the range + my @replacement; + + if($first == $a && $last == $b) + { + @replacement = (); + } + elsif($first == $a) + { + @replacement = ([$last + 1, $b]); + } + elsif($last == $b) + { + @replacement = ([$a, $first - 1]); + } + else + { + @replacement = ([$a, $first - 1], [$last + 1, $b]); + } + splice @rev, $i, 1, @replacement; + @revisions_applied = @rev; + return; + } + } + + die "could not remove range: not in set"; +} + +sub GetUnappliedRanges($) +{ + my ($lastrev) = @_; + my @unapplied = (); + + my $cur = 0; + for(@revisions_applied) + { + my ($a, $b) = @$_; + if($a - 1 >= $cur + 1) + { + push @unapplied, [$cur + 1, $a - 1]; + } + $cur = $b; + } + if($lastrev >= $cur + 1) + { + push @unapplied, [$cur + 1, $lastrev]; + } + return @unapplied; +} + +sub GetMasterRev() +{ + my $svninfo = OutputOf 'svn info #1', $conf{master}; + $svninfo =~ /^Last Changed Rev: (\d+)$/m + or die "could not get svn info"; + return $1; +} + +sub GetLog($$) +{ + my ($first, $last) = @_; + my $log = OutputOf 'svn log -r#1:#2 #3', $first, $last, $conf{master}; + $log =~ s/^-*$//gm; + $log =~ s/\n+/\n/gs; + $log =~ s/^\n//s; + $log =~ s/\n$//s; + return $log; +} + +sub GetDiff($$) +{ + my ($first, $last) = @_; + return OutputOf 'svn diff -r#1:#2 #3', $first-1, $last, $conf{master}; +} + +my ($cmd, @args) = @ARGV; +$cmd = 'help' if not defined $cmd; + +if($cmd eq 'info') +{ + LoadSettings(); + for(@revisions_applied) + { + my ($a, $b) = @$_; + print "Applied: $a to $b\n"; + } + for(GetUnappliedRanges(GetMasterRev())) + { + my ($a, $b) = @$_; + print "Unapplied: $a to $b\n"; + } +} +elsif($cmd eq 'unmerged-diff') +{ + LoadSettings(); + my @autoadd = (); + for(GetUnappliedRanges(GetMasterRev())) + { + my ($a, $b) = @$_; + my $log = GetLog $a, $b; + if($log eq '') + { + push @autoadd, [$a, $b]; + next; + } + $log =~ s/^/ /gm; + print "Unapplied: $a to $b\n"; + print "$log\n"; + print GetDiff $a, $b; + print "\n"; + } + for(@autoadd) + { + my ($a, $b) = @$_; + print "Autofilled revision hole $a to $b\n"; + AddPatch $a, $b; + } + WriteSettings() if @autoadd; +} +elsif($cmd eq 'unmerged') +{ + LoadSettings(); + my @autoadd = (); + for(GetUnappliedRanges(GetMasterRev())) + { + my ($a, $b) = @$_; + my $log = GetLog $a, $b; + if($log eq '') + { + push @autoadd, [$a, $b]; + next; + } + $log =~ s/^/ /gm; + print "Unapplied: $a to $b\n"; + print "$log\n\n"; + } + for(@autoadd) + { + my ($a, $b) = @$_; + print "Autofilled revision hole $a to $b\n"; + AddPatch $a, $b; + } + WriteSettings() if @autoadd; +} +elsif($cmd eq 'merge') +{ + my ($first, $last, $force) = @args; + die "Usage: $0 merge first last [--force]" + if not defined $first; + $last = $first if not defined $last; + + die "Usage: $0 merge first last" + if "$first$last" =~ /[^0-9]/; + + die "There is an uncommitted merge" + if -f '.commitmsg' and $force ne '--force'; + + LoadSettings(); + AddPatch $first, $last; + + print OutputOf 'svn merge -r#1:#2 #3', ($first - 1), $last, $conf{master}; + print "You may also want to run $0 unmerged to fill possible revision holes\n"; + print "Make sure there are no conflicts, then run $0 commit\n"; + print "To abort, use $0 revert\n"; + + open my $fh, '>>', '.commitmsg' + or die "open .commitmsg"; + print $fh GetLog $first, $last; + print $fh "\n"; + close $fh; + + WriteSettings(); +} +elsif($cmd eq 'undo') +{ + my ($first, $last, $force) = @args; + die "Usage: $0 undo first last" + if not defined $first; + $last = $first if not defined $last; + + die "Usage: $0 merge first last" + if "$first$last" =~ /[^0-9]/; + + die "There is an uncommitted merge" + if -f '.commitmsg' and $force ne '--force'; + + LoadSettings(); + RemovePatch $first, $last; + + print OutputOf 'svn merge -r#2:#1 #3', ($first - 1), $last, $conf{master}; + print "Make sure there are no conflicts, then run $0 commit\n"; + print "To abort, use $0 revert\n"; + + open my $fh, '>>', '.commitmsg' + or die "open .commitmsg"; + print $fh "undo the following merge:\n", GetLog $first, $last; + close $fh; + + WriteSettings(); +} +elsif($cmd eq 'commit') +{ + system 'vim .commitmsg'; + print "Hit Enter if OK to commit, Ctrl-C otherwise...\n"; + my $ok = ; + if(!system 'svn commit -F .commitmsg') + { + unlink '.commitmsg'; + } +} +elsif($cmd eq 'revert') +{ + if(!system 'svn revert -R .') + { + unlink '.commitmsg'; + } +} +elsif($cmd eq 'init') +{ + my ($master, $rev) = @args; + $conf{master} = $master; + @revisions_applied = [1, $rev]; + WriteSettings(); +} +else +{ + print <side = side; + sideRef->next = next; + return sideRef; +} + + + +/* +CountBrushList() +counts the number of brushes in a brush linked list +*/ + +int CountBrushList( brush_t *brushes ) +{ + int c = 0; + + + /* count brushes */ + for( ; brushes != NULL; brushes = brushes->next ) + c++; + return c; +} + + + +/* +AllocBrush() +allocates a new brush +*/ + +brush_t *AllocBrush( int numSides ) +{ + brush_t *bb; + size_t c; + + + /* allocate and clear */ + if( numSides <= 0 ) + Error( "AllocBrush called with numsides = %d", numSides ); + c = (size_t)&(((brush_t*) 0)->sides[ numSides ]); + bb = safe_malloc( c ); + memset( bb, 0, c ); + if( numthreads == 1 ) + numActiveBrushes++; + + /* return it */ + return bb; +} + + + +/* +FreeBrush() +frees a single brush and all sides/windings +*/ + +void FreeBrush( brush_t *b ) +{ + int i; + + + /* error check */ + if( *((unsigned int*) b) == 0xFEFEFEFE ) + { + Sys_FPrintf( SYS_VRB, "WARNING: Attempt to free an already freed brush!\n" ); + return; + } + + /* free brush sides */ + for( i = 0; i < b->numsides; i++ ) + if( b->sides[i].winding != NULL ) + FreeWinding( b->sides[ i ].winding ); + + /* ydnar: overwrite it */ + memset( b, 0xFE, (size_t)&(((brush_t*) 0)->sides[ b->numsides ]) ); + *((unsigned int*) b) = 0xFEFEFEFE; + + /* free it */ + free( b ); + if( numthreads == 1 ) + numActiveBrushes--; +} + + + +/* +FreeBrushList() +frees a linked list of brushes +*/ + +void FreeBrushList( brush_t *brushes ) +{ + brush_t *next; + + + /* walk brush list */ + for( ; brushes != NULL; brushes = next ) + { + next = brushes->next; + FreeBrush( brushes ); + } +} + + + +/* +CopyBrush() +duplicates the brush, sides, and windings +*/ + +brush_t *CopyBrush( brush_t *brush ) +{ + brush_t *newBrush; + size_t size; + int i; + + + /* copy brush */ + size = (size_t)&(((brush_t*) 0)->sides[ brush->numsides ]); + newBrush = AllocBrush( brush->numsides ); + memcpy( newBrush, brush, size ); + + /* ydnar: nuke linked list */ + newBrush->next = NULL; + + /* copy sides */ + for( i = 0; i < brush->numsides; i++ ) + { + if( brush->sides[ i ].winding != NULL ) + newBrush->sides[ i ].winding = CopyWinding( brush->sides[ i ].winding ); + } + + /* return it */ + return newBrush; +} + + + + +/* +BoundBrush() +sets the mins/maxs based on the windings +returns false if the brush doesn't enclose a valid volume +*/ + +qboolean BoundBrush( brush_t *brush ) +{ + int i, j; + winding_t *w; + + + ClearBounds( brush->mins, brush->maxs ); + for( i = 0; i < brush->numsides; i++ ) + { + w = brush->sides[ i ].winding; + if( w == NULL ) + continue; + for( j = 0; j < w->numpoints; j++ ) + AddPointToBounds( w->p[ j ], brush->mins, brush->maxs ); + } + + for( i = 0; i < 3; i++ ) + { + if( brush->mins[ i ] < MIN_WORLD_COORD || brush->maxs[ i ] > MAX_WORLD_COORD || brush->mins[i] >= brush->maxs[ i ] ) + return qfalse; + } + + return qtrue; +} + + + + +/* +SnapWeldVector() - ydnar +welds two vec3_t's into a third, taking into account nearest-to-integer +instead of averaging +*/ + +#define SNAP_EPSILON 0.01 + +void SnapWeldVector( vec3_t a, vec3_t b, vec3_t out ) +{ + int i; + vec_t ai, bi, outi; + + + /* dummy check */ + if( a == NULL || b == NULL || out == NULL ) + return; + + /* do each element */ + for( i = 0; i < 3; i++ ) + { + /* round to integer */ + ai = Q_rint( a[ i ] ); + bi = Q_rint( a[ i ] ); + + /* prefer exact integer */ + if( ai == a[ i ] ) + out[ i ] = a[ i ]; + else if( bi == b[ i ] ) + out[ i ] = b[ i ]; + + /* use nearest */ + else if( fabs( ai - a[ i ] ) < fabs( bi < b[ i ] ) ) + out[ i ] = a[ i ]; + else + out[ i ] = b[ i ]; + + /* snap */ + outi = Q_rint( out[ i ] ); + if( fabs( outi - out[ i ] ) <= SNAP_EPSILON ) + out[ i ] = outi; + } +} + +/* +================== +SnapWeldVectorAccu + +Welds two vectors into a third, taking into account nearest-to-integer +instead of averaging. +================== +*/ +void SnapWeldVectorAccu(vec3_accu_t a, vec3_accu_t b, vec3_accu_t out) +{ + // I'm just preserving what I think was the intended logic of the original + // SnapWeldVector(). I'm not actually sure where this function should even + // be used. I'd like to know which kinds of problems this function addresses. + + // TODO: I thought we're snapping all coordinates to nearest 1/8 unit? + // So what is natural about snapping to the nearest integer? Maybe we should + // be snapping to the nearest 1/8 unit instead? + + int i; + vec_accu_t ai, bi, ad, bd; + + if (a == NULL || b == NULL || out == NULL) + Error("SnapWeldVectorAccu: NULL argument"); + + for (i = 0; i < 3; i++) + { + ai = Q_rintAccu(a[i]); + bi = Q_rintAccu(b[i]); + ad = fabs(ai - a[i]); + bd = fabs(bi - b[i]); + + if (ad < bd) + { + if (ad < SNAP_EPSILON) out[i] = ai; + else out[i] = a[i]; + } + else + { + if (bd < SNAP_EPSILON) out[i] = bi; + else out[i] = b[i]; + } + } +} + +/* +FixWinding() - ydnar +removes degenerate edges from a winding +returns qtrue if the winding is valid +*/ + +#define DEGENERATE_EPSILON 0.1 + +qboolean FixWinding( winding_t *w ) +{ + qboolean valid = qtrue; + int i, j, k; + vec3_t vec; + float dist; + + + /* dummy check */ + if( !w ) + return qfalse; + + /* check all verts */ + for( i = 0; i < w->numpoints; i++ ) + { + /* don't remove points if winding is a triangle */ + if( w->numpoints == 3 ) + return valid; + + /* get second point index */ + j = (i + 1) % w->numpoints; + + /* degenerate edge? */ + VectorSubtract( w->p[ i ], w->p[ j ], vec ); + dist = VectorLength( vec ); + if( dist < DEGENERATE_EPSILON ) + { + valid = qfalse; + //Sys_FPrintf( SYS_VRB, "WARNING: Degenerate winding edge found, fixing...\n" ); + + /* create an average point (ydnar 2002-01-26: using nearest-integer weld preference) */ + SnapWeldVector( w->p[ i ], w->p[ j ], vec ); + VectorCopy( vec, w->p[ i ] ); + //VectorAdd( w->p[ i ], w->p[ j ], vec ); + //VectorScale( vec, 0.5, w->p[ i ] ); + + /* move the remaining verts */ + for( k = i + 2; k < w->numpoints; k++ ) + { + VectorCopy( w->p[ k ], w->p[ k - 1 ] ); + } + w->numpoints--; + } + } + + /* one last check and return */ + if( w->numpoints < 3 ) + valid = qfalse; + return valid; +} + +/* +================== +FixWindingAccu + +Removes degenerate edges (edges that are too short) from a winding. +Returns qtrue if the winding has been altered by this function. +Returns qfalse if the winding is untouched by this function. + +It's advised that you check the winding after this function exits to make +sure it still has at least 3 points. If that is not the case, the winding +cannot be considered valid. The winding may degenerate to one or two points +if the some of the winding's points are close together. +================== +*/ +qboolean FixWindingAccu(winding_accu_t *w) +{ + int i, j, k; + vec3_accu_t vec; + vec_accu_t dist; + qboolean done, altered; + + if (w == NULL) Error("FixWindingAccu: NULL argument"); + + altered = qfalse; + + while (qtrue) + { + if (w->numpoints < 2) break; // Don't remove the only remaining point. + done = qtrue; + for (i = 0; i < w->numpoints; i++) + { + j = (((i + 1) == w->numpoints) ? 0 : (i + 1)); + + VectorSubtractAccu(w->p[i], w->p[j], vec); + dist = VectorLengthAccu(vec); + if (dist < DEGENERATE_EPSILON) + { + // TODO: I think the "snap weld vector" was written before + // some of the math precision fixes, and its purpose was + // probably to address math accuracy issues. We can think + // about changing the logic here. Maybe once plane distance + // gets 64 bits, we can look at it then. + SnapWeldVectorAccu(w->p[i], w->p[j], vec); + VectorCopyAccu(vec, w->p[i]); + for (k = j + 1; k < w->numpoints; k++) + { + VectorCopyAccu(w->p[k], w->p[k - 1]); + } + w->numpoints--; + altered = qtrue; + // The only way to finish off fixing the winding consistently and + // accurately is by fixing the winding all over again. For example, + // the point at index i and the point at index i-1 could now be + // less than the epsilon distance apart. There are too many special + // case problems we'd need to handle if we didn't start from the + // beginning. + done = qfalse; + break; // This will cause us to return to the "while" loop. + } + } + if (done) break; + } + + return altered; +} + + +/* +CreateBrushWindings() +makes basewindigs for sides and mins/maxs for the brush +returns false if the brush doesn't enclose a valid volume +*/ + +qboolean CreateBrushWindings( brush_t *brush ) +{ + int i, j; +#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES + winding_accu_t *w; +#else + winding_t *w; +#endif + side_t *side; + plane_t *plane; + + + /* walk the list of brush sides */ + for( i = 0; i < brush->numsides; i++ ) + { + /* get side and plane */ + side = &brush->sides[ i ]; + plane = &mapplanes[ side->planenum ]; + + /* make huge winding */ +#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES + w = BaseWindingForPlaneAccu(plane->normal, plane->dist); +#else + w = BaseWindingForPlane( plane->normal, plane->dist ); +#endif + + /* walk the list of brush sides */ + for( j = 0; j < brush->numsides && w != NULL; j++ ) + { + if( i == j ) + continue; + if( brush->sides[ j ].planenum == (brush->sides[ i ].planenum ^ 1) ) + continue; /* back side clipaway */ + if( brush->sides[ j ].bevel ) + continue; + plane = &mapplanes[ brush->sides[ j ].planenum ^ 1 ]; +#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES + ChopWindingInPlaceAccu(&w, plane->normal, plane->dist, 0); +#else + ChopWindingInPlace( &w, plane->normal, plane->dist, 0 ); // CLIP_EPSILON ); +#endif + + /* ydnar: fix broken windings that would generate trifans */ +#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES + // I think it's better to FixWindingAccu() once after we chop with all planes + // so that error isn't multiplied. There is nothing natural about welding + // the points unless they are the final endpoints. ChopWindingInPlaceAccu() + // is able to handle all kinds of degenerate windings. +#else + FixWinding( w ); +#endif + } + + /* set side winding */ +#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES + if (w != NULL) + { + FixWindingAccu(w); + if (w->numpoints < 3) + { + FreeWindingAccu(w); + w = NULL; + } + } + side->winding = (w ? CopyWindingAccuToRegular(w) : NULL); + if (w) FreeWindingAccu(w); +#else + side->winding = w; +#endif + } + + /* find brush bounds */ + return BoundBrush( brush ); +} + + + + +/* +================== +BrushFromBounds + +Creates a new axial brush +================== +*/ +brush_t *BrushFromBounds (vec3_t mins, vec3_t maxs) +{ + brush_t *b; + int i; + vec3_t normal; + vec_t dist; + + b = AllocBrush (6); + b->numsides = 6; + for (i=0 ; i<3 ; i++) + { + VectorClear (normal); + normal[i] = 1; + dist = maxs[i]; + b->sides[i].planenum = FindFloatPlane (normal, dist, 1, (vec3_t*) &maxs ); + + normal[i] = -1; + dist = -mins[i]; + b->sides[3+i].planenum = FindFloatPlane (normal, dist, 1, (vec3_t*) &mins ); + } + + CreateBrushWindings (b); + + return b; +} + +/* +================== +BrushVolume + +================== +*/ +vec_t BrushVolume (brush_t *brush) +{ + int i; + winding_t *w; + vec3_t corner; + vec_t d, area, volume; + plane_t *plane; + + if (!brush) + return 0; + + // grab the first valid point as the corner + + w = NULL; + for (i=0 ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (w) + break; + } + if (!w) + return 0; + VectorCopy (w->p[0], corner); + + // make tetrahedrons to all other faces + + volume = 0; + for ( ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (!w) + continue; + plane = &mapplanes[brush->sides[i].planenum]; + d = -(DotProduct (corner, plane->normal) - plane->dist); + area = WindingArea (w); + volume += d*area; + } + + volume /= 3; + return volume; +} + + + +/* +WriteBSPBrushMap() +writes a map with the split bsp brushes +*/ + +void WriteBSPBrushMap( char *name, brush_t *list ) +{ + FILE *f; + side_t *s; + int i; + winding_t *w; + + + /* note it */ + Sys_Printf( "Writing %s\n", name ); + + /* open the map file */ + f = fopen( name, "wb" ); + if( f == NULL ) + Error( "Can't write %s\b", name ); + + fprintf (f, "{\n\"classname\" \"worldspawn\"\n"); + + for ( ; list ; list=list->next ) + { + fprintf (f, "{\n"); + for (i=0,s=list->sides ; inumsides ; i++,s++) + { + // TODO: See if we can use a smaller winding to prevent resolution loss. + // Is WriteBSPBrushMap() used only to decompile maps? + w = BaseWindingForPlane (mapplanes[s->planenum].normal, mapplanes[s->planenum].dist); + + fprintf (f,"( %i %i %i ) ", (int)w->p[0][0], (int)w->p[0][1], (int)w->p[0][2]); + fprintf (f,"( %i %i %i ) ", (int)w->p[1][0], (int)w->p[1][1], (int)w->p[1][2]); + fprintf (f,"( %i %i %i ) ", (int)w->p[2][0], (int)w->p[2][1], (int)w->p[2][2]); + + fprintf (f, "notexture 0 0 0 1 1\n" ); + FreeWinding (w); + } + fprintf (f, "}\n"); + } + fprintf (f, "}\n"); + + fclose (f); + +} + + + +/* +FilterBrushIntoTree_r() +adds brush reference to any intersecting bsp leafnode +*/ + +int FilterBrushIntoTree_r( brush_t *b, node_t *node ) +{ + brush_t *front, *back; + int c; + + + /* dummy check */ + if( b == NULL ) + return 0; + + /* add it to the leaf list */ + if( node->planenum == PLANENUM_LEAF ) + { + /* something somewhere is hammering brushlist */ + b->next = node->brushlist; + node->brushlist = b; + + /* classify the leaf by the structural brush */ + if( !b->detail ) + { + if( b->opaque ) + { + node->opaque = qtrue; + node->areaportal = qfalse; + } + else if( b->compileFlags & C_AREAPORTAL ) + { + if( !node->opaque ) + node->areaportal = qtrue; + } + } + + return 1; + } + + /* split it by the node plane */ + c = b->numsides; + SplitBrush( b, node->planenum, &front, &back ); + FreeBrush( b ); + + c = 0; + c += FilterBrushIntoTree_r( front, node->children[ 0 ] ); + c += FilterBrushIntoTree_r( back, node->children[ 1 ] ); + + return c; +} + + + +/* +FilterDetailBrushesIntoTree +fragment all the detail brushes into the structural leafs +*/ + +void FilterDetailBrushesIntoTree( entity_t *e, tree_t *tree ) +{ + brush_t *b, *newb; + int r; + int c_unique, c_clusters; + int i; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- FilterDetailBrushesIntoTree ---\n" ); + + /* walk the list of brushes */ + c_unique = 0; + c_clusters = 0; + for( b = e->brushes; b; b = b->next ) + { + if( !b->detail ) + continue; + c_unique++; + newb = CopyBrush( b ); + r = FilterBrushIntoTree_r( newb, tree->headnode ); + c_clusters += r; + + /* mark all sides as visible so drawsurfs are created */ + if( r ) + { + for( i = 0; i < b->numsides; i++ ) + { + if( b->sides[ i ].winding ) + b->sides[ i ].visible = qtrue; + } + } + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d detail brushes\n", c_unique ); + Sys_FPrintf( SYS_VRB, "%9d cluster references\n", c_clusters ); +} + +/* +===================== +FilterStructuralBrushesIntoTree + +Mark the leafs as opaque and areaportals +===================== +*/ +void FilterStructuralBrushesIntoTree( entity_t *e, tree_t *tree ) { + brush_t *b, *newb; + int r; + int c_unique, c_clusters; + int i; + + Sys_FPrintf (SYS_VRB, "--- FilterStructuralBrushesIntoTree ---\n"); + + c_unique = 0; + c_clusters = 0; + for ( b = e->brushes ; b ; b = b->next ) { + if ( b->detail ) { + continue; + } + c_unique++; + newb = CopyBrush( b ); + r = FilterBrushIntoTree_r( newb, tree->headnode ); + c_clusters += r; + + // mark all sides as visible so drawsurfs are created + if ( r ) { + for ( i = 0 ; i < b->numsides ; i++ ) { + if ( b->sides[i].winding ) { + b->sides[i].visible = qtrue; + } + } + } + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d structural brushes\n", c_unique ); + Sys_FPrintf( SYS_VRB, "%9d cluster references\n", c_clusters ); +} + + + +/* +================ +AllocTree +================ +*/ +tree_t *AllocTree (void) +{ + tree_t *tree; + + tree = safe_malloc(sizeof(*tree)); + memset (tree, 0, sizeof(*tree)); + ClearBounds (tree->mins, tree->maxs); + + return tree; +} + +/* +================ +AllocNode +================ +*/ +node_t *AllocNode (void) +{ + node_t *node; + + node = safe_malloc(sizeof(*node)); + memset (node, 0, sizeof(*node)); + + return node; +} + + +/* +================ +WindingIsTiny + +Returns true if the winding would be crunched out of +existance by the vertex snapping. +================ +*/ +#define EDGE_LENGTH 0.2 +qboolean WindingIsTiny (winding_t *w) +{ +/* + if (WindingArea (w) < 1) + return qtrue; + return qfalse; +*/ + int i, j; + vec_t len; + vec3_t delta; + int edges; + + edges = 0; + for (i=0 ; inumpoints ; i++) + { + j = i == w->numpoints - 1 ? 0 : i+1; + VectorSubtract (w->p[j], w->p[i], delta); + len = VectorLength (delta); + if (len > EDGE_LENGTH) + { + if (++edges == 3) + return qfalse; + } + } + return qtrue; +} + +/* +================ +WindingIsHuge + +Returns true if the winding still has one of the points +from basewinding for plane +================ +*/ +qboolean WindingIsHuge (winding_t *w) +{ + int i, j; + + for (i=0 ; inumpoints ; i++) + { + for (j=0 ; j<3 ; j++) + if (w->p[i][j] <= MIN_WORLD_COORD || w->p[i][j] >= MAX_WORLD_COORD) + return qtrue; + } + return qfalse; +} + +//============================================================ + +/* +================== +BrushMostlyOnSide + +================== +*/ +int BrushMostlyOnSide (brush_t *brush, plane_t *plane) +{ + int i, j; + winding_t *w; + vec_t d, max; + int side; + + max = 0; + side = PSIDE_FRONT; + for (i=0 ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (!w) + continue; + for (j=0 ; jnumpoints ; j++) + { + d = DotProduct (w->p[j], plane->normal) - plane->dist; + if (d > max) + { + max = d; + side = PSIDE_FRONT; + } + if (-d > max) + { + max = -d; + side = PSIDE_BACK; + } + } + } + return side; +} + + + +/* +SplitBrush() +generates two new brushes, leaving the original unchanged +*/ + +void SplitBrush( brush_t *brush, int planenum, brush_t **front, brush_t **back ) +{ + brush_t *b[2]; + int i, j; + winding_t *w, *cw[2], *midwinding; + plane_t *plane, *plane2; + side_t *s, *cs; + float d, d_front, d_back; + + + *front = NULL; + *back = NULL; + plane = &mapplanes[planenum]; + + // check all points + d_front = d_back = 0; + for (i=0 ; inumsides ; i++) + { + w = brush->sides[i].winding; + if (!w) + continue; + for (j=0 ; jnumpoints ; j++) + { + d = DotProduct (w->p[j], plane->normal) - plane->dist; + if (d > 0 && d > d_front) + d_front = d; + if (d < 0 && d < d_back) + d_back = d; + } + } + + if (d_front < 0.1) // PLANESIDE_EPSILON) + { // only on back + *back = CopyBrush( brush ); + return; + } + + if (d_back > -0.1) // PLANESIDE_EPSILON) + { // only on front + *front = CopyBrush( brush ); + return; + } + + // create a new winding from the split plane + w = BaseWindingForPlane (plane->normal, plane->dist); + for (i=0 ; inumsides && w ; i++) + { + plane2 = &mapplanes[brush->sides[i].planenum ^ 1]; + ChopWindingInPlace (&w, plane2->normal, plane2->dist, 0); // PLANESIDE_EPSILON); + } + + if (!w || WindingIsTiny (w) ) + { // the brush isn't really split + int side; + + side = BrushMostlyOnSide (brush, plane); + if (side == PSIDE_FRONT) + *front = CopyBrush (brush); + if (side == PSIDE_BACK) + *back = CopyBrush (brush); + return; + } + + if( WindingIsHuge( w ) ) + Sys_FPrintf( SYS_VRB,"WARNING: huge winding\n" ); + + midwinding = w; + + // split it for real + + for (i=0 ; i<2 ; i++) + { + b[i] = AllocBrush (brush->numsides+1); + memcpy( b[i], brush, sizeof( brush_t ) - sizeof( brush->sides ) ); + b[i]->numsides = 0; + b[i]->next = NULL; + b[i]->original = brush->original; + } + + // split all the current windings + + for (i=0 ; inumsides ; i++) + { + s = &brush->sides[i]; + w = s->winding; + if (!w) + continue; + ClipWindingEpsilon (w, plane->normal, plane->dist, + 0 /*PLANESIDE_EPSILON*/, &cw[0], &cw[1]); + for (j=0 ; j<2 ; j++) + { + if (!cw[j]) + continue; + cs = &b[j]->sides[b[j]->numsides]; + b[j]->numsides++; + *cs = *s; + cs->winding = cw[j]; + } + } + + + // see if we have valid polygons on both sides + for (i=0 ; i<2 ; i++) + { + if (b[i]->numsides < 3 || !BoundBrush (b[i])) + { + if (b[i]->numsides >= 3) + Sys_FPrintf (SYS_VRB,"bogus brush after clip\n"); + FreeBrush (b[i]); + b[i] = NULL; + } + } + + if ( !(b[0] && b[1]) ) + { + if (!b[0] && !b[1]) + Sys_FPrintf (SYS_VRB,"split removed brush\n"); + else + Sys_FPrintf (SYS_VRB,"split not on both sides\n"); + if (b[0]) + { + FreeBrush (b[0]); + *front = CopyBrush (brush); + } + if (b[1]) + { + FreeBrush (b[1]); + *back = CopyBrush (brush); + } + return; + } + + // add the midwinding to both sides + for (i=0 ; i<2 ; i++) + { + cs = &b[i]->sides[b[i]->numsides]; + b[i]->numsides++; + + cs->planenum = planenum^i^1; + cs->shaderInfo = NULL; + if (i==0) + cs->winding = CopyWinding (midwinding); + else + cs->winding = midwinding; + } + + { + vec_t v1; + int i; + + + for (i=0 ; i<2 ; i++) + { + v1 = BrushVolume (b[i]); + if (v1 < 1.0) + { + FreeBrush (b[i]); + b[i] = NULL; + // Sys_FPrintf (SYS_VRB,"tiny volume after clip\n"); + } + } + } + + *front = b[0]; + *back = b[1]; +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/brush_primit.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/brush_primit.c new file mode 100644 index 00000000..4a0d2520 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/brush_primit.c @@ -0,0 +1,81 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define BRUSH_PRIMIT_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* ------------------------------------------------------------------------------- + +functions + +------------------------------------------------------------------------------- */ + +/* +ComputeAxisBase() +computes the base texture axis for brush primitive texturing +note: ComputeAxisBase here and in editor code must always BE THE SAME! +warning: special case behaviour of atan2( y, x ) <-> atan( y / x ) might not be the same everywhere when x == 0 +rotation by (0,RotY,RotZ) assigns X to normal +*/ + +void ComputeAxisBase( vec3_t normal, vec3_t texX, vec3_t texY ) +{ + vec_t RotY, RotZ; + + + /* do some cleaning */ + if( fabs( normal[ 0 ] ) < 1e-6 ) + normal[ 0 ]= 0.0f; + if( fabs( normal[ 1 ] ) < 1e-6 ) + normal[ 1 ]=0.0f; + if( fabs( normal[ 2 ] ) < 1e-6 ) + normal[ 2 ] = 0.0f; + + /* compute the two rotations around y and z to rotate x to normal */ + RotY = -atan2( normal[ 2 ], sqrt( normal[ 1 ] * normal[ 1 ] + normal[ 0 ] * normal[ 0 ]) ); + RotZ = atan2( normal[ 1 ], normal[ 0 ] ); + + /* rotate (0,1,0) and (0,0,1) to compute texX and texY */ + texX[ 0 ] = -sin( RotZ ); + texX[ 1 ] = cos( RotZ ); + texX[ 2 ] = 0; + + /* the texY vector is along -z (t texture coorinates axis) */ + texY[ 0 ] = -sin( RotY ) * cos( RotZ ); + texY[ 1 ] = -sin( RotY ) * sin( RotZ ); + texY[ 2 ] = -cos( RotY ); +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/bsp.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bsp.c new file mode 100644 index 00000000..79019792 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bsp.c @@ -0,0 +1,990 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define BSP_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* ------------------------------------------------------------------------------- + +functions + +------------------------------------------------------------------------------- */ + +/* +ProcessAdvertisements() +copies advertisement info into the BSP structures +*/ + +static void ProcessAdvertisements( void ) { + int i; + const char* className; + const char* modelKey; + int modelNum; + bspModel_t* adModel; + bspDrawSurface_t* adSurface; + + Sys_FPrintf( SYS_VRB, "--- ProcessAdvertisements ---\n" ); + + for( i = 0; i < numEntities; i++ ) { + + /* is an advertisement? */ + className = ValueForKey( &entities[ i ], "classname" ); + + if( !Q_stricmp( "advertisement", className ) ) { + + modelKey = ValueForKey( &entities[ i ], "model" ); + + if( strlen( modelKey ) > MAX_QPATH - 1 ) { + Error( "Model Key for entity exceeds ad struct string length." ); + } else { + if( numBSPAds < MAX_MAP_ADVERTISEMENTS ) { + bspAds[numBSPAds].cellId = IntForKey( &entities[ i ], "cellId" ); + strncpy( bspAds[numBSPAds].model, modelKey, sizeof( bspAds[numBSPAds].model ) ); + + modelKey++; + modelNum = atoi( modelKey ); + adModel = &bspModels[modelNum]; + + if( adModel->numBSPSurfaces != 1 ) { + Error( "Ad cell id %d has more than one surface.", bspAds[numBSPAds].cellId ); + } + + adSurface = &bspDrawSurfaces[adModel->firstBSPSurface]; + + // store the normal for use at run time.. all ad verts are assumed to + // have identical normals (because they should be a simple rectangle) + // so just use the first vert's normal + VectorCopy( bspDrawVerts[adSurface->firstVert].normal, bspAds[numBSPAds].normal ); + + // store the ad quad for quick use at run time + if( adSurface->surfaceType == MST_PATCH ) { + int v0 = adSurface->firstVert + adSurface->patchHeight - 1; + int v1 = adSurface->firstVert + adSurface->numVerts - 1; + int v2 = adSurface->firstVert + adSurface->numVerts - adSurface->patchWidth; + int v3 = adSurface->firstVert; + VectorCopy( bspDrawVerts[v0].xyz, bspAds[numBSPAds].rect[0] ); + VectorCopy( bspDrawVerts[v1].xyz, bspAds[numBSPAds].rect[1] ); + VectorCopy( bspDrawVerts[v2].xyz, bspAds[numBSPAds].rect[2] ); + VectorCopy( bspDrawVerts[v3].xyz, bspAds[numBSPAds].rect[3] ); + } else { + Error( "Ad cell %d has an unsupported Ad Surface type.", bspAds[numBSPAds].cellId ); + } + + numBSPAds++; + } else { + Error( "Maximum number of map advertisements exceeded." ); + } + } + } + } + + Sys_FPrintf( SYS_VRB, "%9d in-game advertisements\n", numBSPAds ); +} + +/* +SetCloneModelNumbers() - ydnar +sets the model numbers for brush entities +*/ + +static void SetCloneModelNumbers( void ) +{ + int i, j; + int models; + char modelValue[ 10 ]; + const char *value, *value2, *value3; + + + /* start with 1 (worldspawn is model 0) */ + models = 1; + for( i = 1; i < numEntities; i++ ) + { + /* only entities with brushes or patches get a model number */ + if( entities[ i ].brushes == NULL && entities[ i ].patches == NULL ) + continue; + + /* is this a clone? */ + value = ValueForKey( &entities[ i ], "_ins" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ i ], "_instance" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ i ], "_clone" ); + if( value[ 0 ] != '\0' ) + continue; + + /* add the model key */ + sprintf( modelValue, "*%d", models ); + SetKeyValue( &entities[ i ], "model", modelValue ); + + /* increment model count */ + models++; + } + + /* fix up clones */ + for( i = 1; i < numEntities; i++ ) + { + /* only entities with brushes or patches get a model number */ + if( entities[ i ].brushes == NULL && entities[ i ].patches == NULL ) + continue; + + /* is this a clone? */ + value = ValueForKey( &entities[ i ], "_ins" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ i ], "_instance" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ i ], "_clone" ); + if( value[ 0 ] == '\0' ) + continue; + + /* find an entity with matching clone name */ + for( j = 0; j < numEntities; j++ ) + { + /* is this a clone parent? */ + value2 = ValueForKey( &entities[ j ], "_clonename" ); + if( value2[ 0 ] == '\0' ) + continue; + + /* do they match? */ + if( strcmp( value, value2 ) == 0 ) + { + /* get the model num */ + value3 = ValueForKey( &entities[ j ], "model" ); + if( value3[ 0 ] == '\0' ) + { + Sys_Printf( "WARNING: Cloned entity %s referenced entity without model\n", value2 ); + continue; + } + models = atoi( &value2[ 1 ] ); + + /* add the model key */ + sprintf( modelValue, "*%d", models ); + SetKeyValue( &entities[ i ], "model", modelValue ); + + /* nuke the brushes/patches for this entity (fixme: leak!) */ + entities[ i ].brushes = NULL; + entities[ i ].patches = NULL; + } + } + } +} + + + +/* +FixBrushSides() - ydnar +matches brushsides back to their appropriate drawsurface and shader +*/ + +static void FixBrushSides( entity_t *e ) +{ + int i; + mapDrawSurface_t *ds; + sideRef_t *sideRef; + bspBrushSide_t *side; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- FixBrushSides ---\n" ); + + /* walk list of drawsurfaces */ + for( i = e->firstDrawSurf; i < numMapDrawSurfs; i++ ) + { + /* get surface and try to early out */ + ds = &mapDrawSurfs[ i ]; + if( ds->outputNum < 0 ) + continue; + + /* walk sideref list */ + for( sideRef = ds->sideRef; sideRef != NULL; sideRef = sideRef->next ) + { + /* get bsp brush side */ + if( sideRef->side == NULL || sideRef->side->outputNum < 0 ) + continue; + side = &bspBrushSides[ sideRef->side->outputNum ]; + + /* set drawsurface */ + side->surfaceNum = ds->outputNum; + //% Sys_FPrintf( SYS_VRB, "DS: %7d Side: %7d ", ds->outputNum, sideRef->side->outputNum ); + + /* set shader */ + if( strcmp( bspShaders[ side->shaderNum ].shader, ds->shaderInfo->shader ) ) + { + //% Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", bspShaders[ side->shaderNum ].shader, ds->shaderInfo->shader ); + side->shaderNum = EmitShader( ds->shaderInfo->shader, &ds->shaderInfo->contentFlags, &ds->shaderInfo->surfaceFlags ); + } + } + } +} + + + +/* +ProcessWorldModel() +creates a full bsp + surfaces for the worldspawn entity +*/ + +void ProcessWorldModel( void ) +{ + int i, s; + entity_t *e; + tree_t *tree; + face_t *faces; + qboolean ignoreLeaks, leaked; + xmlNodePtr polyline, leaknode; + char level[ 2 ], shader[ 1024 ]; + const char *value; + + /* sets integer blockSize from worldspawn "_blocksize" key if it exists */ + value = ValueForKey( &entities[ 0 ], "_blocksize" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ 0 ], "blocksize" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ 0 ], "chopsize" ); /* sof2 */ + if( value[ 0 ] != '\0' ) + { + /* scan 3 numbers */ + s = sscanf( value, "%d %d %d", &blockSize[ 0 ], &blockSize[ 1 ], &blockSize[ 2 ] ); + + /* handle legacy case */ + if( s == 1 ) + { + blockSize[ 1 ] = blockSize[ 0 ]; + blockSize[ 2 ] = blockSize[ 0 ]; + } + } + Sys_Printf( "block size = { %d %d %d }\n", blockSize[ 0 ], blockSize[ 1 ], blockSize[ 2 ] ); + + /* sof2: ignore leaks? */ + value = ValueForKey( &entities[ 0 ], "_ignoreleaks" ); /* ydnar */ + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ 0 ], "ignoreleaks" ); + if( value[ 0 ] == '1' ) + ignoreLeaks = qtrue; + else + ignoreLeaks = qfalse; + + /* begin worldspawn model */ + BeginModel(); + e = &entities[ 0 ]; + e->firstDrawSurf = 0; + + /* ydnar: gs mods */ + ClearMetaTriangles(); + + /* check for patches with adjacent edges that need to lod together */ + PatchMapDrawSurfs( e ); + + /* build an initial bsp tree using all of the sides of all of the structural brushes */ + faces = MakeStructuralBSPFaceList( entities[ 0 ].brushes ); + tree = FaceBSP( faces ); + MakeTreePortals( tree ); + FilterStructuralBrushesIntoTree( e, tree ); + + /* see if the bsp is completely enclosed */ + if( FloodEntities( tree ) || ignoreLeaks ) + { + /* rebuild a better bsp tree using only the sides that are visible from the inside */ + FillOutside( tree->headnode ); + + /* chop the sides to the convex hull of their visible fragments, giving us the smallest polygons */ + ClipSidesIntoTree( e, tree ); + + /* build a visible face tree */ + faces = MakeVisibleBSPFaceList( entities[ 0 ].brushes ); + FreeTree( tree ); + tree = FaceBSP( faces ); + MakeTreePortals( tree ); + FilterStructuralBrushesIntoTree( e, tree ); + leaked = qfalse; + + /* ydnar: flood again for skybox */ + if( skyboxPresent ) + FloodEntities( tree ); + } + else + { + Sys_FPrintf( SYS_NOXML, "**********************\n" ); + Sys_FPrintf( SYS_NOXML, "******* leaked *******\n" ); + Sys_FPrintf( SYS_NOXML, "**********************\n" ); + polyline = LeakFile( tree ); + leaknode = xmlNewNode( NULL, (xmlChar*)"message" ); + xmlNodeSetContent( leaknode, (xmlChar*)"MAP LEAKED\n" ); + xmlAddChild( leaknode, polyline ); + level[0] = (int) '0' + SYS_ERR; + level[1] = 0; + xmlSetProp( leaknode, (xmlChar*)"level", (xmlChar*) &level ); + xml_SendNode( leaknode ); + if( leaktest ) + { + Sys_Printf ("--- MAP LEAKED, ABORTING LEAKTEST ---\n"); + exit( 0 ); + } + leaked = qtrue; + + /* chop the sides to the convex hull of their visible fragments, giving us the smallest polygons */ + ClipSidesIntoTree( e, tree ); + } + + /* save out information for visibility processing */ + NumberClusters( tree ); + if( !leaked ) + WritePortalFile( tree ); + + /* flood from entities */ + FloodAreas( tree ); + + /* create drawsurfs for triangle models */ + AddTriangleModels( e ); + + /* create drawsurfs for surface models */ + AddEntitySurfaceModels( e ); + + /* generate bsp brushes from map brushes */ + EmitBrushes( e->brushes, &e->firstBrush, &e->numBrushes ); + + /* add references to the detail brushes */ + FilterDetailBrushesIntoTree( e, tree ); + + /* drawsurfs that cross fog boundaries will need to be split along the fog boundary */ + if( !nofog ) + FogDrawSurfaces( e ); + + /* subdivide each drawsurf as required by shader tesselation */ + if( !nosubdivide ) + SubdivideFaceSurfaces( e, tree ); + + /* add in any vertexes required to fix t-junctions */ + if( !notjunc ) + FixTJunctions( e ); + + /* ydnar: classify the surfaces */ + ClassifyEntitySurfaces( e ); + + /* ydnar: project decals */ + MakeEntityDecals( e ); + + /* ydnar: meta surfaces */ + MakeEntityMetaTriangles( e ); + SmoothMetaTriangles(); + FixMetaTJunctions(); + MergeMetaTriangles(); + + /* ydnar: debug portals */ + if( debugPortals ) + MakeDebugPortalSurfs( tree ); + + /* ydnar: fog hull */ + value = ValueForKey( &entities[ 0 ], "_foghull" ); + if( value[ 0 ] != '\0' ) + { + sprintf( shader, "textures/%s", value ); + MakeFogHullSurfs( e, tree, shader ); + } + + /* ydnar: bug 645: do flares for lights */ + for( i = 0; i < numEntities && emitFlares; i++ ) + { + entity_t *light, *target; + const char *value, *flareShader; + vec3_t origin, targetOrigin, normal, color; + int lightStyle; + + + /* get light */ + light = &entities[ i ]; + value = ValueForKey( light, "classname" ); + if( !strcmp( value, "light" ) ) + { + /* get flare shader */ + flareShader = ValueForKey( light, "_flareshader" ); + value = ValueForKey( light, "_flare" ); + if( flareShader[ 0 ] != '\0' || value[ 0 ] != '\0' ) + { + /* get specifics */ + GetVectorForKey( light, "origin", origin ); + GetVectorForKey( light, "_color", color ); + lightStyle = IntForKey( light, "_style" ); + if( lightStyle == 0 ) + lightStyle = IntForKey( light, "style" ); + + /* handle directional spotlights */ + value = ValueForKey( light, "target" ); + if( value[ 0 ] != '\0' ) + { + /* get target light */ + target = FindTargetEntity( value ); + if( target != NULL ) + { + GetVectorForKey( target, "origin", targetOrigin ); + VectorSubtract( targetOrigin, origin, normal ); + VectorNormalize( normal, normal ); + } + } + else + //% VectorClear( normal ); + VectorSet( normal, 0, 0, -1 ); + + /* create the flare surface (note shader defaults automatically) */ + DrawSurfaceForFlare( mapEntityNum, origin, normal, color, flareShader, lightStyle ); + } + } + } + + /* add references to the final drawsurfs in the apropriate clusters */ + FilterDrawsurfsIntoTree( e, tree ); + + /* match drawsurfaces back to original brushsides (sof2) */ + FixBrushSides( e ); + + /* finish */ + EndModel( e, tree->headnode ); + FreeTree( tree ); +} + + + +/* +ProcessSubModel() +creates bsp + surfaces for other brush models +*/ + +void ProcessSubModel( void ) +{ + entity_t *e; + tree_t *tree; + brush_t *b, *bc; + node_t *node; + + + /* start a brush model */ + BeginModel(); + e = &entities[ mapEntityNum ]; + e->firstDrawSurf = numMapDrawSurfs; + + /* ydnar: gs mods */ + ClearMetaTriangles(); + + /* check for patches with adjacent edges that need to lod together */ + PatchMapDrawSurfs( e ); + + /* allocate a tree */ + node = AllocNode(); + node->planenum = PLANENUM_LEAF; + tree = AllocTree(); + tree->headnode = node; + + /* add the sides to the tree */ + ClipSidesIntoTree( e, tree ); + + /* ydnar: create drawsurfs for triangle models */ + AddTriangleModels( e ); + + /* create drawsurfs for surface models */ + AddEntitySurfaceModels( e ); + + /* generate bsp brushes from map brushes */ + EmitBrushes( e->brushes, &e->firstBrush, &e->numBrushes ); + + /* just put all the brushes in headnode */ + for( b = e->brushes; b; b = b->next ) + { + bc = CopyBrush( b ); + bc->next = node->brushlist; + node->brushlist = bc; + } + + /* subdivide each drawsurf as required by shader tesselation */ + if( !nosubdivide ) + SubdivideFaceSurfaces( e, tree ); + + /* add in any vertexes required to fix t-junctions */ + if( !notjunc ) + FixTJunctions( e ); + + /* ydnar: classify the surfaces and project lightmaps */ + ClassifyEntitySurfaces( e ); + + /* ydnar: project decals */ + MakeEntityDecals( e ); + + /* ydnar: meta surfaces */ + MakeEntityMetaTriangles( e ); + SmoothMetaTriangles(); + FixMetaTJunctions(); + MergeMetaTriangles(); + + /* add references to the final drawsurfs in the apropriate clusters */ + FilterDrawsurfsIntoTree( e, tree ); + + /* match drawsurfaces back to original brushsides (sof2) */ + FixBrushSides( e ); + + /* finish */ + EndModel( e, node ); + FreeTree( tree ); +} + + + +/* +ProcessModels() +process world + other models into the bsp +*/ + +void ProcessModels( void ) +{ + qboolean oldVerbose; + entity_t *entity; + + + /* preserve -v setting */ + oldVerbose = verbose; + + /* start a new bsp */ + BeginBSPFile(); + + /* create map fogs */ + CreateMapFogs(); + + /* walk entity list */ + for( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ ) + { + /* get entity */ + entity = &entities[ mapEntityNum ]; + if( entity->brushes == NULL && entity->patches == NULL ) + continue; + + /* process the model */ + Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels ); + if( mapEntityNum == 0 ) + ProcessWorldModel(); + else + ProcessSubModel(); + + /* potentially turn off the deluge of text */ + verbose = verboseEntities; + } + + /* restore -v setting */ + verbose = oldVerbose; + + /* write fogs */ + EmitFogs(); + + /* vortex: emit meta stats */ + EmitMetaStats(); +} + + + +/* +OnlyEnts() +this is probably broken unless teamed with a radiant version that preserves entity order +*/ + +void OnlyEnts( void ) +{ + char out[ 1024 ]; + + char save_cmdline[1024], save_version[1024]; + const char *p; + + /* note it */ + Sys_Printf( "--- OnlyEnts ---\n" ); + + sprintf( out, "%s.bsp", source ); + LoadBSPFile( out ); + + ParseEntities(); + p = ValueForKey(&entities[0], "_q3map2_cmdline"); + strncpy(save_cmdline, p, sizeof(save_cmdline)); + save_cmdline[sizeof(save_cmdline)-1] = 0; + p = ValueForKey(&entities[0], "_q3map2_version"); + strncpy(save_version, p, sizeof(save_version)); + save_version[sizeof(save_version)-1] = 0; + + numEntities = 0; + + LoadShaderInfo(); + LoadMapFile( name, qfalse, qfalse ); + SetModelNumbers(); + SetLightStyles(); + + if(*save_cmdline) + SetKeyValue(&entities[0], "_q3map2_cmdline", save_cmdline); + if(*save_version) + SetKeyValue(&entities[0], "_q3map2_version", save_version); + + numBSPEntities = numEntities; + UnparseEntities(); + + WriteBSPFile( out ); +} + + + +/* +BSPMain() - ydnar +handles creation of a bsp from a map file +*/ + +int BSPMain( int argc, char **argv ) +{ + int i; + char path[ 1024 ], tempSource[ 1024 ]; + qboolean onlyents = qfalse; + + + /* note it */ + Sys_Printf( "--- BSP ---\n" ); + + SetDrawSurfacesBuffer(); + mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); + memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); + numMapDrawSurfs = 0; + + tempSource[ 0 ] = '\0'; + globalCelShader[0] = 0; + + /* set standard game flags */ + maxSurfaceVerts = game->maxSurfaceVerts; + maxSurfaceIndexes = game->maxSurfaceIndexes; + emitFlares = game->emitFlares; + + /* process arguments */ + for( i = 1; i < (argc - 1); i++ ) + { + if( !strcmp( argv[ i ], "-onlyents" ) ) + { + Sys_Printf( "Running entity-only compile\n" ); + onlyents = qtrue; + } + else if( !strcmp( argv[ i ], "-tempname" ) ) + strcpy( tempSource, argv[ ++i ] ); + else if( !strcmp( argv[ i ], "-tmpout" ) ) + strcpy( outbase, "/tmp" ); + else if( !strcmp( argv[ i ], "-nowater" ) ) + { + Sys_Printf( "Disabling water\n" ); + nowater = qtrue; + } + else if( !strcmp( argv[ i ], "-nodetail" ) ) + { + Sys_Printf( "Ignoring detail brushes\n") ; + nodetail = qtrue; + } + else if( !strcmp( argv[ i ], "-fulldetail" ) ) + { + Sys_Printf( "Turning detail brushes into structural brushes\n" ); + fulldetail = qtrue; + } + else if( !strcmp( argv[ i ], "-nofog" ) ) + { + Sys_Printf( "Fog volumes disabled\n" ); + nofog = qtrue; + } + else if( !strcmp( argv[ i ], "-nosubdivide" ) ) + { + Sys_Printf( "Disabling brush face subdivision\n" ); + nosubdivide = qtrue; + } + else if( !strcmp( argv[ i ], "-leaktest" ) ) + { + Sys_Printf( "Leaktest enabled\n" ); + leaktest = qtrue; + } + else if( !strcmp( argv[ i ], "-verboseentities" ) ) + { + Sys_Printf( "Verbose entities enabled\n" ); + verboseEntities = qtrue; + } + else if( !strcmp( argv[ i ], "-nocurves" ) ) + { + Sys_Printf( "Ignoring curved surfaces (patches)\n" ); + noCurveBrushes = qtrue; + } + else if( !strcmp( argv[ i ], "-notjunc" ) ) + { + Sys_Printf( "T-junction fixing disabled\n" ); + notjunc = qtrue; + } + else if( !strcmp( argv[ i ], "-fakemap" ) ) + { + Sys_Printf( "Generating fakemap.map\n" ); + fakemap = qtrue; + } + else if( !strcmp( argv[ i ], "-samplesize" ) ) + { + sampleSize = atoi( argv[ i + 1 ] ); + if( sampleSize < 1 ) + sampleSize = 1; + i++; + Sys_Printf( "Lightmap sample size set to %dx%d units\n", sampleSize, sampleSize ); + } + else if( !strcmp( argv[ i ], "-minsamplesize" ) ) + { + minSampleSize = atoi( argv[ i + 1 ] ); + if( minSampleSize < 1 ) + minSampleSize = 1; + i++; + Sys_Printf( "Minimum lightmap sample size set to %dx%d units\n", minSampleSize, minSampleSize ); + } + else if( !strcmp( argv[ i ], "-custinfoparms") ) + { + Sys_Printf( "Custom info parms enabled\n" ); + useCustomInfoParms = qtrue; + } + + /* sof2 args */ + else if( !strcmp( argv[ i ], "-rename" ) ) + { + Sys_Printf( "Appending _bsp suffix to misc_model shaders (SOF2)\n" ); + renameModelShaders = qtrue; + } + + /* ydnar args */ + else if( !strcmp( argv[ i ], "-ne" ) ) + { + normalEpsilon = atof( argv[ i + 1 ] ); + i++; + Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon ); + } + else if( !strcmp( argv[ i ], "-de" ) ) + { + distanceEpsilon = atof( argv[ i + 1 ] ); + i++; + Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon ); + } + else if( !strcmp( argv[ i ], "-mv" ) ) + { + maxLMSurfaceVerts = atoi( argv[ i + 1 ] ); + if( maxLMSurfaceVerts < 3 ) + maxLMSurfaceVerts = 3; + if( maxLMSurfaceVerts > maxSurfaceVerts ) + maxSurfaceVerts = maxLMSurfaceVerts; + i++; + Sys_Printf( "Maximum lightmapped surface vertex count set to %d\n", maxLMSurfaceVerts ); + } + else if( !strcmp( argv[ i ], "-mi" ) ) + { + maxSurfaceIndexes = atoi( argv[ i + 1 ] ); + if( maxSurfaceIndexes < 3 ) + maxSurfaceIndexes = 3; + i++; + Sys_Printf( "Maximum per-surface index count set to %d\n", maxSurfaceIndexes ); + } + else if( !strcmp( argv[ i ], "-np" ) ) + { + npDegrees = atof( argv[ i + 1 ] ); + if( npDegrees < 0.0f ) + shadeAngleDegrees = 0.0f; + else if( npDegrees > 0.0f ) + Sys_Printf( "Forcing nonplanar surfaces with a breaking angle of %f degrees\n", npDegrees ); + i++; + } + else if( !strcmp( argv[ i ], "-snap" ) ) + { + bevelSnap = atoi( argv[ i + 1 ]); + if( bevelSnap < 0 ) + bevelSnap = 0; + i++; + if( bevelSnap > 0 ) + Sys_Printf( "Snapping brush bevel planes to %d units\n", bevelSnap ); + } + else if( !strcmp( argv[ i ], "-texrange" ) ) + { + texRange = atoi( argv[ i + 1 ]); + if( texRange < 0 ) + texRange = 0; + i++; + Sys_Printf( "Limiting per-surface texture range to %d texels\n", texRange ); + } + else if( !strcmp( argv[ i ], "-nohint" ) ) + { + Sys_Printf( "Hint brushes disabled\n" ); + noHint = qtrue; + } + else if( !strcmp( argv[ i ], "-flat" ) ) + { + Sys_Printf( "Flatshading enabled\n" ); + flat = qtrue; + } + else if( !strcmp( argv[ i ], "-celshader" ) ) + { + ++i; + if(argv[i][0]) + sprintf( globalCelShader, "textures/%s", argv[ i ] ); + else + *globalCelShader = 0; + Sys_Printf( "Global cel shader set to \"%s\"\n", globalCelShader ); + } + else if( !strcmp( argv[ i ], "-meta" ) ) + { + Sys_Printf( "Creating meta surfaces from brush faces\n" ); + meta = qtrue; + } + else if( !strcmp( argv[ i ], "-patchmeta" ) ) + { + Sys_Printf( "Creating meta surfaces from patches\n" ); + patchMeta = qtrue; + } + else if( !strcmp( argv[ i ], "-flares" ) ) + { + Sys_Printf( "Flare surfaces enabled\n" ); + emitFlares = qtrue; + } + else if( !strcmp( argv[ i ], "-noflares" ) ) + { + Sys_Printf( "Flare surfaces disabled\n" ); + emitFlares = qfalse; + } + else if( !strcmp( argv[ i ], "-skyfix" ) ) + { + Sys_Printf( "GL_CLAMP sky fix/hack/workaround enabled\n" ); + skyFixHack = qtrue; + } + else if( !strcmp( argv[ i ], "-debugsurfaces" ) ) + { + Sys_Printf( "emitting debug surfaces\n" ); + debugSurfaces = qtrue; + } + else if( !strcmp( argv[ i ], "-debuginset" ) ) + { + Sys_Printf( "Debug surface triangle insetting enabled\n" ); + debugInset = qtrue; + } + else if( !strcmp( argv[ i ], "-debugportals" ) ) + { + Sys_Printf( "Debug portal surfaces enabled\n" ); + debugPortals = qtrue; + } + else if( !strcmp( argv[ i ], "-altsplit" ) ) + { + Sys_Printf( "Alternate BSP splitting (by 27) enabled\n" ); + bspAlternateSplitWeights = qtrue; + } + else if( !strcmp( argv[ i ], "-deep" ) ) + { + Sys_Printf( "Deep BSP tree generation enabled\n" ); + deepBSP = qtrue; + } + else if( !strcmp( argv[ i ], "-maxarea" ) ) + { + Sys_Printf( "Max Area face surface generation enabled\n" ); + maxAreaFaceSurface = qtrue; + } + else if( !strcmp( argv[ i ], "-bsp" ) ) + Sys_Printf( "-bsp argument unnecessary\n" ); + else + { + Sys_Printf( "WARNING: Unknown option \"%s\"\n", argv[ i ] ); + } + } + + /* fixme: print more useful usage here */ + if( i != (argc - 1) ) + Error( "usage: q3map [options] mapfile" ); + + /* copy source name */ + strcpy( source, ExpandArg( argv[ i ] ) ); + StripExtension( source ); + + /* ydnar: set default sample size */ + SetDefaultSampleSize( sampleSize ); + + /* delete portal, line and surface files */ + sprintf( path, "%s.prt", source ); + remove( path ); + sprintf( path, "%s.lin", source ); + remove( path ); + //% sprintf( path, "%s.srf", source ); /* ydnar */ + //% remove( path ); + + /* expand mapname */ + strcpy( name, ExpandArg( argv[ i ] ) ); + if( strcmp( name + strlen( name ) - 4, ".reg" ) ) + { + /* if we are doing a full map, delete the last saved region map */ + sprintf( path, "%s.reg", source ); + remove( path ); + DefaultExtension( name, ".map" ); /* might be .reg */ + } + + /* if onlyents, just grab the entites and resave */ + if( onlyents ) + { + OnlyEnts(); + return 0; + } + + /* load shaders */ + LoadShaderInfo(); + + /* load original file from temp spot in case it was renamed by the editor on the way in */ + if( strlen( tempSource ) > 0 ) + LoadMapFile( tempSource, qfalse, qfalse ); + else + LoadMapFile( name, qfalse, qfalse ); + + /* div0: inject command line parameters */ + InjectCommandLine(argv, 1, argc - 1); + + /* ydnar: decal setup */ + ProcessDecals(); + + /* ydnar: cloned brush model entities */ + SetCloneModelNumbers(); + + /* process world and submodels */ + ProcessModels(); + + /* set light styles from targetted light entities */ + SetLightStyles(); + + /* process in game advertisements */ + ProcessAdvertisements(); + + /* finish and write bsp */ + EndBSPFile(qtrue); + + /* remove temp map source file if appropriate */ + if( strlen( tempSource ) > 0) + remove( tempSource ); + + /* return to sender */ + return 0; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_abstract.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_abstract.c new file mode 100644 index 00000000..ef78160f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_abstract.c @@ -0,0 +1,934 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define BSPFILE_ABSTRACT_C + + + +/* dependencies */ +#include "q3map2.h" + + + + +/* ------------------------------------------------------------------------------- + +this file was copied out of the common directory in order to not break +compatibility with the q3map 1.x tree. it was moved out in order to support +the raven bsp format (RBSP) used in soldier of fortune 2 and jedi knight 2. + +since each game has its own set of particular features, the data structures +below no longer directly correspond to the binary format of a particular game. + +the translation will be done at bsp load/save time to keep any sort of +special-case code messiness out of the rest of the program. + +------------------------------------------------------------------------------- */ + + + +/* FIXME: remove the functions below that handle memory management of bsp file chunks */ + +int numBSPDrawVertsBuffer = 0; +void IncDrawVerts() +{ + numBSPDrawVerts++; + + if(bspDrawVerts == 0) + { + numBSPDrawVertsBuffer = 1024; + + bspDrawVerts = safe_malloc_info(sizeof(bspDrawVert_t) * numBSPDrawVertsBuffer, "IncDrawVerts"); + + } + else if(numBSPDrawVerts > numBSPDrawVertsBuffer) + { + numBSPDrawVertsBuffer *= 3; // multiply by 1.5 + numBSPDrawVertsBuffer /= 2; + + bspDrawVerts = realloc(bspDrawVerts, sizeof(bspDrawVert_t) * numBSPDrawVertsBuffer); + + if(!bspDrawVerts) + Error( "realloc() failed (IncDrawVerts)"); + } + + memset(bspDrawVerts + (numBSPDrawVerts - 1), 0, sizeof(bspDrawVert_t)); +} + +void SetDrawVerts(int n) +{ + if(bspDrawVerts != 0) + free(bspDrawVerts); + + numBSPDrawVerts = n; + numBSPDrawVertsBuffer = numBSPDrawVerts; + + bspDrawVerts = safe_malloc_info(sizeof(bspDrawVert_t) * numBSPDrawVertsBuffer, "IncDrawVerts"); + + memset(bspDrawVerts, 0, n * sizeof(bspDrawVert_t)); +} + +int numBSPDrawSurfacesBuffer = 0; +void SetDrawSurfacesBuffer() +{ + if(bspDrawSurfaces != 0) + free(bspDrawSurfaces); + + numBSPDrawSurfacesBuffer = MAX_MAP_DRAW_SURFS; + + bspDrawSurfaces = safe_malloc_info(sizeof(bspDrawSurface_t) * numBSPDrawSurfacesBuffer, "IncDrawSurfaces"); + + memset(bspDrawSurfaces, 0, MAX_MAP_DRAW_SURFS * sizeof(bspDrawVert_t)); +} + +void SetDrawSurfaces(int n) +{ + if(bspDrawSurfaces != 0) + free(bspDrawSurfaces); + + numBSPDrawSurfaces = n; + numBSPDrawSurfacesBuffer = numBSPDrawSurfaces; + + bspDrawSurfaces = safe_malloc_info(sizeof(bspDrawSurface_t) * numBSPDrawSurfacesBuffer, "IncDrawSurfaces"); + + memset(bspDrawSurfaces, 0, n * sizeof(bspDrawVert_t)); +} + +void BSPFilesCleanup() +{ + if(bspDrawVerts != 0) + free(bspDrawVerts); + if(bspDrawSurfaces != 0) + free(bspDrawSurfaces); + if(bspLightBytes != 0) + free(bspLightBytes); + if(bspGridPoints != 0) + free(bspGridPoints); +} + + + + + + +/* +SwapBlock() +if all values are 32 bits, this can be used to swap everything +*/ + +void SwapBlock( int *block, int size ) +{ + int i; + + + /* dummy check */ + if( block == NULL ) + return; + + /* swap */ + size >>= 2; + for( i = 0; i < size; i++ ) + block[ i ] = LittleLong( block[ i ] ); +} + + + +/* +SwapBSPFile() +byte swaps all data in the abstract bsp +*/ + +void SwapBSPFile( void ) +{ + int i, j; + + + /* models */ + SwapBlock( (int*) bspModels, numBSPModels * sizeof( bspModels[ 0 ] ) ); + + /* shaders (don't swap the name) */ + for( i = 0; i < numBSPShaders ; i++ ) + { + bspShaders[ i ].contentFlags = LittleLong( bspShaders[ i ].contentFlags ); + bspShaders[ i ].surfaceFlags = LittleLong( bspShaders[ i ].surfaceFlags ); + } + + /* planes */ + SwapBlock( (int*) bspPlanes, numBSPPlanes * sizeof( bspPlanes[ 0 ] ) ); + + /* nodes */ + SwapBlock( (int*) bspNodes, numBSPNodes * sizeof( bspNodes[ 0 ] ) ); + + /* leafs */ + SwapBlock( (int*) bspLeafs, numBSPLeafs * sizeof( bspLeafs[ 0 ] ) ); + + /* leaffaces */ + SwapBlock( (int*) bspLeafSurfaces, numBSPLeafSurfaces * sizeof( bspLeafSurfaces[ 0 ] ) ); + + /* leafbrushes */ + SwapBlock( (int*) bspLeafBrushes, numBSPLeafBrushes * sizeof( bspLeafBrushes[ 0 ] ) ); + + // brushes + SwapBlock( (int*) bspBrushes, numBSPBrushes * sizeof( bspBrushes[ 0 ] ) ); + + // brushsides + SwapBlock( (int*) bspBrushSides, numBSPBrushSides * sizeof( bspBrushSides[ 0 ] ) ); + + // vis + ((int*) &bspVisBytes)[ 0 ] = LittleLong( ((int*) &bspVisBytes)[ 0 ] ); + ((int*) &bspVisBytes)[ 1 ] = LittleLong( ((int*) &bspVisBytes)[ 1 ] ); + + /* drawverts (don't swap colors) */ + for( i = 0; i < numBSPDrawVerts; i++ ) + { + bspDrawVerts[ i ].xyz[ 0 ] = LittleFloat( bspDrawVerts[ i ].xyz[ 0 ] ); + bspDrawVerts[ i ].xyz[ 1 ] = LittleFloat( bspDrawVerts[ i ].xyz[ 1 ] ); + bspDrawVerts[ i ].xyz[ 2 ] = LittleFloat( bspDrawVerts[ i ].xyz[ 2 ] ); + bspDrawVerts[ i ].normal[ 0 ] = LittleFloat( bspDrawVerts[ i ].normal[ 0 ] ); + bspDrawVerts[ i ].normal[ 1 ] = LittleFloat( bspDrawVerts[ i ].normal[ 1 ] ); + bspDrawVerts[ i ].normal[ 2 ] = LittleFloat( bspDrawVerts[ i ].normal[ 2 ] ); + bspDrawVerts[ i ].st[ 0 ] = LittleFloat( bspDrawVerts[ i ].st[ 0 ] ); + bspDrawVerts[ i ].st[ 1 ] = LittleFloat( bspDrawVerts[ i ].st[ 1 ] ); + for( j = 0; j < MAX_LIGHTMAPS; j++ ) + { + bspDrawVerts[ i ].lightmap[ j ][ 0 ] = LittleFloat( bspDrawVerts[ i ].lightmap[ j ][ 0 ] ); + bspDrawVerts[ i ].lightmap[ j ][ 1 ] = LittleFloat( bspDrawVerts[ i ].lightmap[ j ][ 1 ] ); + } + } + + /* drawindexes */ + SwapBlock( (int*) bspDrawIndexes, numBSPDrawIndexes * sizeof( bspDrawIndexes[0] ) ); + + /* drawsurfs */ + /* note: rbsp files (and hence q3map2 abstract bsp) have byte lightstyles index arrays, this follows sof2map convention */ + SwapBlock( (int*) bspDrawSurfaces, numBSPDrawSurfaces * sizeof( bspDrawSurfaces[ 0 ] ) ); + + /* fogs */ + for( i = 0; i < numBSPFogs; i++ ) + { + bspFogs[ i ].brushNum = LittleLong( bspFogs[ i ].brushNum ); + bspFogs[ i ].visibleSide = LittleLong( bspFogs[ i ].visibleSide ); + } + + /* advertisements */ + for( i = 0; i < numBSPAds; i++ ) + { + bspAds[ i ].cellId = LittleLong( bspAds[ i ].cellId ); + bspAds[ i ].normal[ 0 ] = LittleFloat( bspAds[ i ].normal[ 0 ] ); + bspAds[ i ].normal[ 1 ] = LittleFloat( bspAds[ i ].normal[ 1 ] ); + bspAds[ i ].normal[ 2 ] = LittleFloat( bspAds[ i ].normal[ 2 ] ); + + for( j = 0; j < 4; j++ ) + { + bspAds[ i ].rect[j][ 0 ] = LittleFloat( bspAds[ i ].rect[j][ 0 ] ); + bspAds[ i ].rect[j][ 1 ] = LittleFloat( bspAds[ i ].rect[j][ 1 ] ); + bspAds[ i ].rect[j][ 2 ] = LittleFloat( bspAds[ i ].rect[j][ 2 ] ); + } + + //bspAds[ i ].model[ MAX_QPATH ]; + } +} + + + +/* +GetLumpElements() +gets the number of elements in a bsp lump +*/ + +int GetLumpElements( bspHeader_t *header, int lump, int size ) +{ + /* check for odd size */ + if( header->lumps[ lump ].length % size ) + { + if( force ) + { + Sys_Printf( "WARNING: GetLumpElements: odd lump size (%d) in lump %d\n", header->lumps[ lump ].length, lump ); + return 0; + } + else + Error( "GetLumpElements: odd lump size (%d) in lump %d", header->lumps[ lump ].length, lump ); + } + + /* return element count */ + return header->lumps[ lump ].length / size; +} + + + +/* +GetLump() +returns a pointer to the specified lump +*/ + +void *GetLump( bspHeader_t *header, int lump ) +{ + return (void*)( (byte*) header + header->lumps[ lump ].offset); +} + + + +/* +CopyLump() +copies a bsp file lump into a destination buffer +*/ + +int CopyLump( bspHeader_t *header, int lump, void *dest, int size ) +{ + int length, offset; + + + /* get lump length and offset */ + length = header->lumps[ lump ].length; + offset = header->lumps[ lump ].offset; + + /* handle erroneous cases */ + if( length == 0 ) + return 0; + if( length % size ) + { + if( force ) + { + Sys_Printf( "WARNING: CopyLump: odd lump size (%d) in lump %d\n", length, lump ); + return 0; + } + else + Error( "CopyLump: odd lump size (%d) in lump %d", length, lump ); + } + + /* copy block of memory and return */ + memcpy( dest, (byte*) header + offset, length ); + return length / size; +} + +int CopyLump_Allocate( bspHeader_t *header, int lump, void **dest, int size, int *allocationVariable ) +{ + /* get lump length and offset */ + *allocationVariable = header->lumps[ lump ].length / size; + *dest = realloc(*dest, size * *allocationVariable); + return CopyLump(header, lump, *dest, size); +} + + +/* +AddLump() +adds a lump to an outgoing bsp file +*/ + +void AddLump( FILE *file, bspHeader_t *header, int lumpNum, const void *data, int length ) +{ + bspLump_t *lump; + + + /* add lump to bsp file header */ + lump = &header->lumps[ lumpNum ]; + lump->offset = LittleLong( ftell( file ) ); + lump->length = LittleLong( length ); + + /* write lump to file */ + SafeWrite( file, data, (length + 3) & ~3 ); +} + + + +/* +LoadBSPFile() +loads a bsp file into memory +*/ + +void LoadBSPFile( const char *filename ) +{ + /* dummy check */ + if( game == NULL || game->load == NULL ) + Error( "LoadBSPFile: unsupported BSP file format" ); + + /* load it, then byte swap the in-memory version */ + game->load( filename ); + SwapBSPFile(); +} + + + +/* +WriteBSPFile() +writes a bsp file +*/ + +void WriteBSPFile( const char *filename ) +{ + char tempname[ 1024 ]; + time_t tm; + + + /* dummy check */ + if( game == NULL || game->write == NULL ) + Error( "WriteBSPFile: unsupported BSP file format" ); + + /* make fake temp name so existing bsp file isn't damaged in case write process fails */ + time( &tm ); + sprintf( tempname, "%s.%08X", filename, (int) tm ); + + /* byteswap, write the bsp, then swap back so it can be manipulated further */ + SwapBSPFile(); + game->write( tempname ); + SwapBSPFile(); + + /* replace existing bsp file */ + remove( filename ); + rename( tempname, filename ); +} + + + +/* +PrintBSPFileSizes() +dumps info about current file +*/ + +void PrintBSPFileSizes( void ) +{ + /* parse entities first */ + if( numEntities <= 0 ) + ParseEntities(); + + /* note that this is abstracted */ + Sys_Printf( "Abstracted BSP file components (*actual sizes may differ)\n" ); + + /* print various and sundry bits */ + Sys_Printf( "%9d models %9d\n", + numBSPModels, (int) (numBSPModels * sizeof( bspModel_t )) ); + Sys_Printf( "%9d shaders %9d\n", + numBSPShaders, (int) (numBSPShaders * sizeof( bspShader_t )) ); + Sys_Printf( "%9d brushes %9d\n", + numBSPBrushes, (int) (numBSPBrushes * sizeof( bspBrush_t )) ); + Sys_Printf( "%9d brushsides %9d *\n", + numBSPBrushSides, (int) (numBSPBrushSides * sizeof( bspBrushSide_t )) ); + Sys_Printf( "%9d fogs %9d\n", + numBSPFogs, (int) (numBSPFogs * sizeof( bspFog_t ) ) ); + Sys_Printf( "%9d planes %9d\n", + numBSPPlanes, (int) (numBSPPlanes * sizeof( bspPlane_t )) ); + Sys_Printf( "%9d entdata %9d\n", + numEntities, bspEntDataSize ); + Sys_Printf( "\n"); + + Sys_Printf( "%9d nodes %9d\n", + numBSPNodes, (int) (numBSPNodes * sizeof( bspNode_t)) ); + Sys_Printf( "%9d leafs %9d\n", + numBSPLeafs, (int) (numBSPLeafs * sizeof( bspLeaf_t )) ); + Sys_Printf( "%9d leafsurfaces %9d\n", + numBSPLeafSurfaces, (int) (numBSPLeafSurfaces * sizeof( *bspLeafSurfaces )) ); + Sys_Printf( "%9d leafbrushes %9d\n", + numBSPLeafBrushes, (int) (numBSPLeafBrushes * sizeof( *bspLeafBrushes )) ); + Sys_Printf( "\n"); + + Sys_Printf( "%9d drawsurfaces %9d *\n", + numBSPDrawSurfaces, (int) (numBSPDrawSurfaces * sizeof( *bspDrawSurfaces )) ); + Sys_Printf( "%9d drawverts %9d *\n", + numBSPDrawVerts, (int) (numBSPDrawVerts * sizeof( *bspDrawVerts )) ); + Sys_Printf( "%9d drawindexes %9d\n", + numBSPDrawIndexes, (int) (numBSPDrawIndexes * sizeof( *bspDrawIndexes )) ); + Sys_Printf( "\n"); + + Sys_Printf( "%9d lightmaps %9d\n", + numBSPLightBytes / (game->lightmapSize * game->lightmapSize * 3), numBSPLightBytes ); + Sys_Printf( "%9d lightgrid %9d *\n", + numBSPGridPoints, (int) (numBSPGridPoints * sizeof( *bspGridPoints )) ); + Sys_Printf( " visibility %9d\n", + numBSPVisBytes ); +} + + + +/* ------------------------------------------------------------------------------- + +entity data handling + +------------------------------------------------------------------------------- */ + + +/* +StripTrailing() +strips low byte chars off the end of a string +*/ + +void StripTrailing( char *e ) +{ + char *s; + + + s = e + strlen( e ) - 1; + while( s >= e && *s <= 32 ) + { + *s = 0; + s--; + } +} + + + +/* +ParseEpair() +parses a single quoted "key" "value" pair into an epair struct +*/ + +epair_t *ParseEPair( void ) +{ + epair_t *e; + + + /* allocate and clear new epair */ + e = safe_malloc( sizeof( epair_t ) ); + memset( e, 0, sizeof( epair_t ) ); + + /* handle key */ + if( strlen( token ) >= (MAX_KEY - 1) ) + Error( "ParseEPair: token too long" ); + + e->key = copystring( token ); + GetToken( qfalse ); + + /* handle value */ + 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 it */ + return e; +} + + + +/* +ParseEntity() +parses an entity's epairs +*/ + +qboolean ParseEntity( void ) +{ + epair_t *e; + + + /* dummy check */ + if( !GetToken( qtrue ) ) + return qfalse; + if( strcmp( token, "{" ) ) + Error( "ParseEntity: { not found" ); + if( numEntities == MAX_MAP_ENTITIES ) + Error( "numEntities == MAX_MAP_ENTITIES" ); + + /* create new entity */ + mapEnt = &entities[ numEntities ]; + numEntities++; + + /* parse */ + while( 1 ) + { + if( !GetToken( qtrue ) ) + Error( "ParseEntity: EOF without closing brace" ); + if( !EPAIR_STRCMP( token, "}" ) ) + break; + e = ParseEPair(); + e->next = mapEnt->epairs; + mapEnt->epairs = e; + } + + /* return to sender */ + return qtrue; +} + + + +/* +ParseEntities() +parses the bsp entity data string into entities +*/ + +void ParseEntities( void ) +{ + numEntities = 0; + ParseFromMemory( bspEntData, bspEntDataSize ); + while( ParseEntity() ); + + /* ydnar: set number of bsp entities in case a map is loaded on top */ + numBSPEntities = numEntities; +} + +/* + * must be called before UnparseEntities + */ +void InjectCommandLine(char **argv, int beginArgs, int endArgs) +{ + const char *previousCommandLine; + char newCommandLine[1024]; + const char *inpos; + char *outpos = newCommandLine; + char *sentinel = newCommandLine + sizeof(newCommandLine) - 1; + int i; + + previousCommandLine = ValueForKey(&entities[0], "_q3map2_cmdline"); + if(previousCommandLine && *previousCommandLine) + { + inpos = previousCommandLine; + while(outpos != sentinel && *inpos) + *outpos++ = *inpos++; + if(outpos != sentinel) + *outpos++ = ';'; + if(outpos != sentinel) + *outpos++ = ' '; + } + + for(i = beginArgs; i < endArgs; ++i) + { + if(outpos != sentinel && i != beginArgs) + *outpos++ = ' '; + inpos = argv[i]; + while(outpos != sentinel && *inpos) + if(*inpos != '\\' && *inpos != '"' && *inpos != ';' && (unsigned char) *inpos >= ' ') + *outpos++ = *inpos++; + } + + *outpos = 0; + SetKeyValue(&entities[0], "_q3map2_cmdline", newCommandLine); + SetKeyValue(&entities[0], "_q3map2_version", Q3MAP_VERSION); +} + +/* +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 ) +{ + int i; + char *buf, *end; + epair_t *ep; + char line[ 2048 ]; + char key[ 1024 ], value[ 1024 ]; + const char *value2; + + + /* setup */ + AUTOEXPAND_BY_REALLOC(bspEntData, 0, allocatedBSPEntData, 1024); + buf = bspEntData; + end = buf; + *end = 0; + + + /* run through entity list */ + for( i = 0; i < numBSPEntities && i < numEntities; i++ ) + { + { + int sz = end - buf; + AUTOEXPAND_BY_REALLOC(bspEntData, sz + 65536, allocatedBSPEntData, 1024); + buf = bspEntData; + end = buf + sz; + } + + /* get epair */ + ep = entities[ i ].epairs; + if( ep == NULL ) + continue; /* ent got removed */ + + /* ydnar: certain entities get stripped from bsp file */ + value2 = ValueForKey( &entities[ i ], "classname" ); + if( !Q_stricmp( value2, "misc_model" ) || + !Q_stricmp( value2, "_decal" ) || + !Q_stricmp( value2, "_skybox" ) ) + continue; + + /* add beginning brace */ + strcat( end, "{\n" ); + end += 2; + + /* walk epair list */ + for( ep = entities[ i ].epairs; ep != NULL; ep = ep->next ) + { + /* copy and clean */ + strcpy( key, ep->key ); + StripTrailing( key ); + strcpy( value, ep->value ); + StripTrailing( value ); + + /* add to buffer */ + sprintf( line, "\"%s\" \"%s\"\n", key, value ); + strcat( end, line ); + end += strlen( line ); + } + + /* add trailing brace */ + strcat( end,"}\n" ); + end += 2; + + /* check for overflow */ + if( end > buf + allocatedBSPEntData ) + Error( "Entity text too long" ); + } + + /* set size */ + bspEntDataSize = end - buf + 1; +} + + + +/* +PrintEntity() +prints an entity's epairs to the console +*/ + +void PrintEntity( const entity_t *ent ) +{ + epair_t *ep; + + + Sys_Printf( "------- entity %p -------\n", ent ); + for( ep = ent->epairs; ep != NULL; ep = ep->next ) + Sys_Printf( "%s = %s\n", ep->key, ep->value ); + +} + + + +/* +SetKeyValue() +sets an epair in an entity +*/ + +void SetKeyValue( entity_t *ent, const char *key, const char *value ) +{ + epair_t *ep; + + + /* check for existing epair */ + for( ep = ent->epairs; ep != NULL; ep = ep->next ) + { + if( !EPAIR_STRCMP( ep->key, key ) ) + { + free( ep->value ); + ep->value = copystring( value ); + return; + } + } + + /* create new epair */ + ep = safe_malloc( sizeof( *ep ) ); + ep->next = ent->epairs; + ent->epairs = ep; + ep->key = copystring( key ); + ep->value = copystring( value ); +} + +/* +KeyExists() +returns true if entity has this key +*/ + +qboolean KeyExists( const entity_t *ent, const char *key ) +{ + epair_t *ep; + + /* walk epair list */ + for( ep = ent->epairs; ep != NULL; ep = ep->next ) + { + if( !EPAIR_STRCMP( ep->key, key ) ) + return qtrue; + } + + /* no match */ + return qfalse; +} + +/* +ValueForKey() +gets the value for an entity key +*/ + +const char *ValueForKey( const entity_t *ent, const char *key ) +{ + epair_t *ep; + + + /* dummy check */ + if( ent == NULL ) + return ""; + + /* walk epair list */ + for( ep = ent->epairs; ep != NULL; ep = ep->next ) + { + if( !EPAIR_STRCMP( ep->key, key ) ) + return ep->value; + } + + /* if no match, return empty string */ + return ""; +} + + + +/* +IntForKey() +gets the integer point value for an entity key +*/ + +int IntForKey( const entity_t *ent, const char *key ) +{ + const char *k; + + + k = ValueForKey( ent, key ); + return atoi( k ); +} + + + +/* +FloatForKey() +gets the floating point value for an entity key +*/ + +vec_t FloatForKey( const entity_t *ent, const char *key ) +{ + const char *k; + + + k = ValueForKey( ent, key ); + return atof( k ); +} + + + +/* +GetVectorForKey() +gets a 3-element vector value for an entity key +*/ + +void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ) +{ + const char *k; + double v1, v2, v3; + + + /* get value */ + k = ValueForKey( ent, key ); + + /* scanf into doubles, then assign, so it is vec_t size independent */ + v1 = v2 = v3 = 0.0; + sscanf( k, "%lf %lf %lf", &v1, &v2, &v3 ); + vec[ 0 ] = v1; + vec[ 1 ] = v2; + vec[ 2 ] = v3; +} + + + +/* +FindTargetEntity() +finds an entity target +*/ + +entity_t *FindTargetEntity( const char *target ) +{ + int i; + const char *n; + + + /* walk entity list */ + for( i = 0; i < numEntities; i++ ) + { + n = ValueForKey( &entities[ i ], "targetname" ); + if ( !strcmp( n, target ) ) + return &entities[ i ]; + } + + /* nada */ + return NULL; +} + + + +/* +GetEntityShadowFlags() - ydnar +gets an entity's shadow flags +note: does not set them to defaults if the keys are not found! +*/ + +void GetEntityShadowFlags( const entity_t *ent, const entity_t *ent2, int *castShadows, int *recvShadows ) +{ + const char *value; + + /* get cast shadows */ + if( castShadows != NULL ) + { + value = ValueForKey( ent, "_castShadows" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( ent, "_cs" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( ent2, "_castShadows" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( ent2, "_cs" ); + if( value[ 0 ] != '\0' ) + *castShadows = atoi( value ); + } + + /* receive */ + if( recvShadows != NULL ) + { + value = ValueForKey( ent, "_receiveShadows" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( ent, "_rs" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( ent2, "_receiveShadows" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( ent2, "_rs" ); + if( value[ 0 ] != '\0' ) + *recvShadows = atoi( value ); + } + + /* vortex: game-specific default eneity keys */ + value = ValueForKey( ent, "classname" ); + if (!Q_stricmp( game->magic, "dq" ) || !Q_stricmp( game->magic, "prophecy" ) ) + { + /* vortex: deluxe quake default shadow flags */ + if (!Q_stricmp( value, "func_wall" ) ) + { + if( recvShadows != NULL ) + *recvShadows = 1; + if( castShadows != NULL ) + *castShadows = 1; + } + } +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_ibsp.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_ibsp.c new file mode 100644 index 00000000..77ffd704 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_ibsp.c @@ -0,0 +1,593 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define BSPFILE_IBSP_C + + + +/* dependencies */ +#include "q3map2.h" + + + + +/* ------------------------------------------------------------------------------- + +this file handles translating the bsp file format used by quake 3, rtcw, and ef +into the abstracted bsp file used by q3map2. + +------------------------------------------------------------------------------- */ + +/* constants */ +#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 LUMP_ADVERTISEMENTS 17 +#define HEADER_LUMPS 18 + + +/* types */ +typedef struct +{ + char ident[ 4 ]; + int version; + + bspLump_t lumps[ HEADER_LUMPS ]; +} +ibspHeader_t; + + + +/* brush sides */ +typedef struct +{ + int planeNum; + int shaderNum; +} +ibspBrushSide_t; + + +static void CopyBrushSidesLump( ibspHeader_t *header ) +{ + int i; + ibspBrushSide_t *in; + bspBrushSide_t *out; + + + /* get count */ + numBSPBrushSides = GetLumpElements( (bspHeader_t*) header, LUMP_BRUSHSIDES, sizeof( *in ) ); + + /* copy */ + in = GetLump( (bspHeader_t*) header, LUMP_BRUSHSIDES ); + for( i = 0; i < numBSPBrushSides; i++ ) + { + AUTOEXPAND_BY_REALLOC(bspBrushSides, i, allocatedBSPBrushSides, 1024); + out = &bspBrushSides[i]; + out->planeNum = in->planeNum; + out->shaderNum = in->shaderNum; + out->surfaceNum = -1; + in++; + } +} + + +static void AddBrushSidesLump( FILE *file, ibspHeader_t *header ) +{ + int i, size; + bspBrushSide_t *in; + ibspBrushSide_t *buffer, *out; + + + /* allocate output buffer */ + size = numBSPBrushSides * sizeof( *buffer ); + buffer = safe_malloc( size ); + memset( buffer, 0, size ); + + /* convert */ + in = bspBrushSides; + out = buffer; + for( i = 0; i < numBSPBrushSides; i++ ) + { + out->planeNum = in->planeNum; + out->shaderNum = in->shaderNum; + in++; + out++; + } + + /* write lump */ + AddLump( file, (bspHeader_t*) header, LUMP_BRUSHSIDES, buffer, size ); + + /* free buffer */ + free( buffer ); +} + + + +/* drawsurfaces */ +typedef struct ibspDrawSurface_s +{ + 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 ]; + + int patchWidth; + int patchHeight; +} +ibspDrawSurface_t; + + +static void CopyDrawSurfacesLump( ibspHeader_t *header ) +{ + int i, j; + ibspDrawSurface_t *in; + bspDrawSurface_t *out; + + + /* get count */ + numBSPDrawSurfaces = GetLumpElements( (bspHeader_t*) header, LUMP_SURFACES, sizeof( *in ) ); + SetDrawSurfaces( numBSPDrawSurfaces ); + + /* copy */ + in = GetLump( (bspHeader_t*) header, LUMP_SURFACES ); + out = bspDrawSurfaces; + for( i = 0; i < numBSPDrawSurfaces; i++ ) + { + out->shaderNum = in->shaderNum; + out->fogNum = in->fogNum; + out->surfaceType = in->surfaceType; + out->firstVert = in->firstVert; + out->numVerts = in->numVerts; + out->firstIndex = in->firstIndex; + out->numIndexes = in->numIndexes; + + out->lightmapStyles[ 0 ] = LS_NORMAL; + out->vertexStyles[ 0 ] = LS_NORMAL; + out->lightmapNum[ 0 ] = in->lightmapNum; + out->lightmapX[ 0 ] = in->lightmapX; + out->lightmapY[ 0 ] = in->lightmapY; + + for( j = 1; j < MAX_LIGHTMAPS; j++ ) + { + out->lightmapStyles[ j ] = LS_NONE; + out->vertexStyles[ j ] = LS_NONE; + out->lightmapNum[ j ] = -3; + out->lightmapX[ j ] = 0; + out->lightmapY[ j ] = 0; + } + + out->lightmapWidth = in->lightmapWidth; + out->lightmapHeight = in->lightmapHeight; + + VectorCopy( in->lightmapOrigin, out->lightmapOrigin ); + VectorCopy( in->lightmapVecs[ 0 ], out->lightmapVecs[ 0 ] ); + VectorCopy( in->lightmapVecs[ 1 ], out->lightmapVecs[ 1 ] ); + VectorCopy( in->lightmapVecs[ 2 ], out->lightmapVecs[ 2 ] ); + + out->patchWidth = in->patchWidth; + out->patchHeight = in->patchHeight; + + in++; + out++; + } +} + + +static void AddDrawSurfacesLump( FILE *file, ibspHeader_t *header ) +{ + int i, size; + bspDrawSurface_t *in; + ibspDrawSurface_t *buffer, *out; + + + /* allocate output buffer */ + size = numBSPDrawSurfaces * sizeof( *buffer ); + buffer = safe_malloc( size ); + memset( buffer, 0, size ); + + /* convert */ + in = bspDrawSurfaces; + out = buffer; + for( i = 0; i < numBSPDrawSurfaces; i++ ) + { + out->shaderNum = in->shaderNum; + out->fogNum = in->fogNum; + out->surfaceType = in->surfaceType; + out->firstVert = in->firstVert; + out->numVerts = in->numVerts; + out->firstIndex = in->firstIndex; + out->numIndexes = in->numIndexes; + + out->lightmapNum = in->lightmapNum[ 0 ]; + out->lightmapX = in->lightmapX[ 0 ]; + out->lightmapY = in->lightmapY[ 0 ]; + out->lightmapWidth = in->lightmapWidth; + out->lightmapHeight = in->lightmapHeight; + + VectorCopy( in->lightmapOrigin, out->lightmapOrigin ); + VectorCopy( in->lightmapVecs[ 0 ], out->lightmapVecs[ 0 ] ); + VectorCopy( in->lightmapVecs[ 1 ], out->lightmapVecs[ 1 ] ); + VectorCopy( in->lightmapVecs[ 2 ], out->lightmapVecs[ 2 ] ); + + out->patchWidth = in->patchWidth; + out->patchHeight = in->patchHeight; + + in++; + out++; + } + + /* write lump */ + AddLump( file, (bspHeader_t*) header, LUMP_SURFACES, buffer, size ); + + /* free buffer */ + free( buffer ); +} + + + +/* drawverts */ +typedef struct +{ + vec3_t xyz; + float st[ 2 ]; + float lightmap[ 2 ]; + vec3_t normal; + byte color[ 4 ]; +} +ibspDrawVert_t; + + +static void CopyDrawVertsLump( ibspHeader_t *header ) +{ + int i; + ibspDrawVert_t *in; + bspDrawVert_t *out; + + + /* get count */ + numBSPDrawVerts = GetLumpElements( (bspHeader_t*) header, LUMP_DRAWVERTS, sizeof( *in ) ); + SetDrawVerts( numBSPDrawVerts ); + + /* copy */ + in = GetLump( (bspHeader_t*) header, LUMP_DRAWVERTS ); + out = bspDrawVerts; + for( i = 0; i < numBSPDrawVerts; i++ ) + { + VectorCopy( in->xyz, out->xyz ); + out->st[ 0 ] = in->st[ 0 ]; + out->st[ 1 ] = in->st[ 1 ]; + + out->lightmap[ 0 ][ 0 ] = in->lightmap[ 0 ]; + out->lightmap[ 0 ][ 1 ] = in->lightmap[ 1 ]; + + VectorCopy( in->normal, out->normal ); + + out->color[ 0 ][ 0 ] = in->color[ 0 ]; + out->color[ 0 ][ 1 ] = in->color[ 1 ]; + out->color[ 0 ][ 2 ] = in->color[ 2 ]; + out->color[ 0 ][ 3 ] = in->color[ 3 ]; + + in++; + out++; + } +} + + +static void AddDrawVertsLump( FILE *file, ibspHeader_t *header ) +{ + int i, size; + bspDrawVert_t *in; + ibspDrawVert_t *buffer, *out; + + + /* allocate output buffer */ + size = numBSPDrawVerts * sizeof( *buffer ); + buffer = safe_malloc( size ); + memset( buffer, 0, size ); + + /* convert */ + in = bspDrawVerts; + out = buffer; + for( i = 0; i < numBSPDrawVerts; i++ ) + { + VectorCopy( in->xyz, out->xyz ); + out->st[ 0 ] = in->st[ 0 ]; + out->st[ 1 ] = in->st[ 1 ]; + + out->lightmap[ 0 ] = in->lightmap[ 0 ][ 0 ]; + out->lightmap[ 1 ] = in->lightmap[ 0 ][ 1 ]; + + VectorCopy( in->normal, out->normal ); + + out->color[ 0 ] = in->color[ 0 ][ 0 ]; + out->color[ 1 ] = in->color[ 0 ][ 1 ]; + out->color[ 2 ] = in->color[ 0 ][ 2 ]; + out->color[ 3 ] = in->color[ 0 ][ 3 ]; + + in++; + out++; + } + + /* write lump */ + AddLump( file, (bspHeader_t*) header, LUMP_DRAWVERTS, buffer, size ); + + /* free buffer */ + free( buffer ); +} + + + +/* light grid */ +typedef struct +{ + byte ambient[ 3 ]; + byte directed[ 3 ]; + byte latLong[ 2 ]; +} +ibspGridPoint_t; + + +static void CopyLightGridLumps( ibspHeader_t *header ) +{ + int i, j; + ibspGridPoint_t *in; + bspGridPoint_t *out; + + + /* get count */ + numBSPGridPoints = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTGRID, sizeof( *in ) ); + + /* allocate buffer */ + bspGridPoints = safe_malloc( numBSPGridPoints * sizeof( *bspGridPoints ) ); + memset( bspGridPoints, 0, numBSPGridPoints * sizeof( *bspGridPoints ) ); + + /* copy */ + in = GetLump( (bspHeader_t*) header, LUMP_LIGHTGRID ); + out = bspGridPoints; + for( i = 0; i < numBSPGridPoints; i++ ) + { + for( j = 0; j < MAX_LIGHTMAPS; j++ ) + { + VectorCopy( in->ambient, out->ambient[ j ] ); + VectorCopy( in->directed, out->directed[ j ] ); + out->styles[ j ] = LS_NONE; + } + + out->styles[ 0 ] = LS_NORMAL; + + out->latLong[ 0 ] = in->latLong[ 0 ]; + out->latLong[ 1 ] = in->latLong[ 1 ]; + + in++; + out++; + } +} + + +static void AddLightGridLumps( FILE *file, ibspHeader_t *header ) +{ + int i; + bspGridPoint_t *in; + ibspGridPoint_t *buffer, *out; + + + /* dummy check */ + if( bspGridPoints == NULL ) + return; + + /* allocate temporary buffer */ + buffer = safe_malloc( numBSPGridPoints * sizeof( *out ) ); + + /* convert */ + in = bspGridPoints; + out = buffer; + for( i = 0; i < numBSPGridPoints; i++ ) + { + VectorCopy( in->ambient[ 0 ], out->ambient ); + VectorCopy( in->directed[ 0 ], out->directed ); + + out->latLong[ 0 ] = in->latLong[ 0 ]; + out->latLong[ 1 ] = in->latLong[ 1 ]; + + in++; + out++; + } + + /* write lumps */ + AddLump( file, (bspHeader_t*) header, LUMP_LIGHTGRID, buffer, (numBSPGridPoints * sizeof( *out )) ); + + /* free buffer (ydnar 2002-10-22: [bug 641] thanks Rap70r! */ + free( buffer ); +} + +/* +LoadIBSPFile() +loads a quake 3 bsp file into memory +*/ + +void LoadIBSPFile( const char *filename ) +{ + ibspHeader_t *header; + + + /* load the file header */ + LoadFile( filename, (void**) &header ); + + /* swap the header (except the first 4 bytes) */ + SwapBlock( (int*) ((byte*) header + sizeof( int )), sizeof( *header ) - sizeof( int ) ); + + /* make sure it matches the format we're trying to load */ + if( force == qfalse && *((int*) header->ident) != *((int*) game->bspIdent) ) + Error( "%s is not a %s file", filename, game->bspIdent ); + if( force == qfalse && header->version != game->bspVersion ) + Error( "%s is version %d, not %d", filename, header->version, game->bspVersion ); + + /* load/convert lumps */ + numBSPShaders = CopyLump_Allocate( (bspHeader_t*) header, LUMP_SHADERS, (void **) &bspShaders, sizeof( bspShader_t ), &allocatedBSPShaders ); + + numBSPModels = CopyLump_Allocate( (bspHeader_t*) header, LUMP_MODELS, (void **) &bspModels, sizeof( bspModel_t ), &allocatedBSPModels ); + + numBSPPlanes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_PLANES, (void **) &bspPlanes, sizeof( bspPlane_t ), &allocatedBSPPlanes ); + + numBSPLeafs = CopyLump( (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, sizeof( bspLeaf_t ) ); // TODO fix overflow + + numBSPNodes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_NODES, (void **) &bspNodes, sizeof( bspNode_t ), &allocatedBSPNodes ); + + numBSPLeafSurfaces = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFSURFACES, (void **) &bspLeafSurfaces, sizeof( bspLeafSurfaces[ 0 ] ), &allocatedBSPLeafSurfaces ); + + numBSPLeafBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFBRUSHES, (void **) &bspLeafBrushes, sizeof( bspLeafBrushes[ 0 ] ), &allocatedBSPLeafBrushes ); + + numBSPBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_BRUSHES, (void **) &bspBrushes, sizeof( bspBrush_t ), &allocatedBSPLeafBrushes ); + + CopyBrushSidesLump( header ); + + CopyDrawVertsLump( header ); + + CopyDrawSurfacesLump( header ); + + numBSPFogs = CopyLump( (bspHeader_t*) header, LUMP_FOGS, bspFogs, sizeof( bspFog_t ) ); // TODO fix overflow + + numBSPDrawIndexes = CopyLump( (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, sizeof( bspDrawIndexes[ 0 ] ) ); + + numBSPVisBytes = CopyLump( (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, 1 ); // TODO fix overflow + + numBSPLightBytes = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTMAPS, 1 ); // TODO change to CopyLump_Allocate + bspLightBytes = safe_malloc( numBSPLightBytes ); + CopyLump( (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, 1 ); + + bspEntDataSize = CopyLump_Allocate( (bspHeader_t*) header, LUMP_ENTITIES, (void **) &bspEntData, 1, &allocatedBSPEntData); + + CopyLightGridLumps( header ); + + /* advertisements */ + if(header->version == 47) // quake live's bsp version + numBSPAds = CopyLump( (bspHeader_t*) header, LUMP_ADVERTISEMENTS, bspAds, sizeof( bspAdvertisement_t ) ); + else + numBSPAds = 0; + + /* free the file buffer */ + free( header ); +} + + + +/* +WriteIBSPFile() +writes an id bsp file +*/ + +void WriteIBSPFile( const char *filename ) +{ + ibspHeader_t outheader, *header; + FILE *file; + time_t t; + char marker[ 1024 ]; + int size; + + + /* set header */ + header = &outheader; + memset( header, 0, sizeof( *header ) ); + + //% Swapfile(); + + /* set up header */ + *((int*) (bspHeader_t*) header->ident) = *((int*) game->bspIdent); + header->version = LittleLong( game->bspVersion ); + + /* write initial header */ + file = SafeOpenWrite( filename ); + SafeWrite( file, (bspHeader_t*) header, sizeof( *header ) ); /* overwritten later */ + + /* add marker lump */ + time( &t ); + sprintf( marker, "I LOVE MY Q3MAP2 %s on %s)", Q3MAP_VERSION, asctime( localtime( &t ) ) ); + AddLump( file, (bspHeader_t*) header, 0, marker, strlen( marker ) + 1 ); + + /* add lumps */ + AddLump( file, (bspHeader_t*) header, LUMP_SHADERS, bspShaders, numBSPShaders * sizeof( bspShader_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_PLANES, bspPlanes, numBSPPlanes * sizeof( bspPlane_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, numBSPLeafs * sizeof( bspLeaf_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_NODES, bspNodes, numBSPNodes * sizeof( bspNode_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_BRUSHES, bspBrushes, numBSPBrushes*sizeof( bspBrush_t ) ); + AddBrushSidesLump( file, header ); + AddLump( file, (bspHeader_t*) header, LUMP_LEAFSURFACES, bspLeafSurfaces, numBSPLeafSurfaces * sizeof( bspLeafSurfaces[ 0 ] ) ); + AddLump( file, (bspHeader_t*) header, LUMP_LEAFBRUSHES, bspLeafBrushes, numBSPLeafBrushes * sizeof( bspLeafBrushes[ 0 ] ) ); + AddLump( file, (bspHeader_t*) header, LUMP_MODELS, bspModels, numBSPModels * sizeof( bspModel_t ) ); + AddDrawVertsLump( file, header ); + AddDrawSurfacesLump( file, header ); + AddLump( file, (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, numBSPVisBytes ); + AddLump( file, (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, numBSPLightBytes ); + AddLightGridLumps( file, header ); + AddLump( file, (bspHeader_t*) header, LUMP_ENTITIES, bspEntData, bspEntDataSize ); + AddLump( file, (bspHeader_t*) header, LUMP_FOGS, bspFogs, numBSPFogs * sizeof( bspFog_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, numBSPDrawIndexes * sizeof( bspDrawIndexes[ 0 ] ) ); + + /* advertisements */ + AddLump( file, (bspHeader_t*) header, LUMP_ADVERTISEMENTS, bspAds, numBSPAds * sizeof( bspAdvertisement_t ) ); + + /* emit bsp size */ + size = ftell( file ); + Sys_Printf( "Wrote %.1f MB (%d bytes)\n", (float) size / (1024 * 1024), size ); + + /* write the completed header */ + fseek( file, 0, SEEK_SET ); + SafeWrite( file, header, sizeof( *header ) ); + + /* close the file */ + fclose( file ); +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_rbsp.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_rbsp.c new file mode 100644 index 00000000..79f177ea --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/bspfile_rbsp.c @@ -0,0 +1,340 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define BSPFILE_RBSP_C + + + +/* dependencies */ +#include "q3map2.h" + + + + +/* ------------------------------------------------------------------------------- + +this file handles translating the bsp file format used by quake 3, rtcw, and ef +into the abstracted bsp file used by q3map2. + +------------------------------------------------------------------------------- */ + +/* constants */ +#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 LUMP_LIGHTARRAY 17 +#define HEADER_LUMPS 18 + + +/* types */ +typedef struct +{ + char ident[ 4 ]; + int version; + + bspLump_t lumps[ HEADER_LUMPS ]; +} +rbspHeader_t; + + + +/* light grid */ +#define MAX_MAP_GRID 0xffff +#define MAX_MAP_GRIDARRAY 0x100000 +#define LG_EPSILON 4 + + +static void CopyLightGridLumps( rbspHeader_t *header ) +{ + int i; + unsigned short *inArray; + bspGridPoint_t *in, *out; + + + /* get count */ + numBSPGridPoints = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTARRAY, sizeof( *inArray ) ); + + /* allocate buffer */ + bspGridPoints = safe_malloc( numBSPGridPoints * sizeof( *bspGridPoints ) ); + memset( bspGridPoints, 0, numBSPGridPoints * sizeof( *bspGridPoints ) ); + + /* copy */ + inArray = GetLump( (bspHeader_t*) header, LUMP_LIGHTARRAY ); + in = GetLump( (bspHeader_t*) header, LUMP_LIGHTGRID ); + out = bspGridPoints; + for( i = 0; i < numBSPGridPoints; i++ ) + { + memcpy( out, &in[ *inArray ], sizeof( *in ) ); + inArray++; + out++; + } +} + + +static void AddLightGridLumps( FILE *file, rbspHeader_t *header ) +{ + int i, j, k, c, d; + int numGridPoints, maxGridPoints; + bspGridPoint_t *gridPoints, *in, *out; + int numGridArray; + unsigned short *gridArray; + qboolean bad; + + + /* allocate temporary buffers */ + maxGridPoints = (numBSPGridPoints < MAX_MAP_GRID) ? numBSPGridPoints : MAX_MAP_GRID; + gridPoints = safe_malloc( maxGridPoints * sizeof( *gridPoints ) ); + gridArray = safe_malloc( numBSPGridPoints * sizeof( *gridArray ) ); + + /* zero out */ + numGridPoints = 0; + numGridArray = numBSPGridPoints; + + /* for each bsp grid point, find an approximate twin */ + Sys_Printf( "Storing lightgrid: %d points\n", numBSPGridPoints ); + for( i = 0; i < numGridArray; i++ ) + { + /* get points */ + in = &bspGridPoints[ i ]; + + /* walk existing list */ + for( j = 0; j < numGridPoints; j++ ) + { + /* get point */ + out = &gridPoints[ j ]; + + /* compare styles */ + if( *((unsigned int*) in->styles) != *((unsigned int*) out->styles) ) + continue; + + /* compare direction */ + d = abs( in->latLong[ 0 ] - out->latLong[ 0 ] ); + if( d < (255 - LG_EPSILON) && d > LG_EPSILON ) + continue; + d = abs( in->latLong[ 1 ] - out->latLong[ 1 ] ); + if( d < 255 - LG_EPSILON && d > LG_EPSILON ) + continue; + + /* compare light */ + bad = qfalse; + for( k = 0; (k < MAX_LIGHTMAPS && bad == qfalse); k++ ) + { + for( c = 0; c < 3; c++ ) + { + if( abs( (int) in->ambient[ k ][ c ] - (int) out->ambient[ k ][ c ]) > LG_EPSILON || + abs( (int) in->directed[ k ][ c ] - (int) out->directed[ k ][ c ]) > LG_EPSILON ) + { + bad = qtrue; + break; + } + } + } + + /* failure */ + if( bad ) + continue; + + /* this sample is ok */ + break; + } + + /* set sample index */ + gridArray[ i ] = (unsigned short) j; + + /* if no sample found, add a new one */ + if( j >= numGridPoints && numGridPoints < maxGridPoints ) + { + out = &gridPoints[ numGridPoints++ ]; + memcpy( out, in, sizeof( *in ) ); + } + } + + /* swap array */ + for( i = 0; i < numGridArray; i++ ) + gridArray[ i ] = LittleShort( gridArray[ i ] ); + + /* write lumps */ + AddLump( file, (bspHeader_t*) header, LUMP_LIGHTGRID, gridPoints, (numGridPoints * sizeof( *gridPoints )) ); + AddLump( file, (bspHeader_t*) header, LUMP_LIGHTARRAY, gridArray, (numGridArray * sizeof( *gridArray )) ); + + /* free buffers */ + free( gridPoints ); + free( gridArray ); +} + + + +/* +LoadRBSPFile() +loads a raven bsp file into memory +*/ + +void LoadRBSPFile( const char *filename ) +{ + rbspHeader_t *header; + + + /* load the file header */ + LoadFile( filename, (void**) &header ); + + /* swap the header (except the first 4 bytes) */ + SwapBlock( (int*) ((byte*) header + sizeof( int )), sizeof( *header ) - sizeof( int ) ); + + /* make sure it matches the format we're trying to load */ + if( force == qfalse && *((int*) header->ident) != *((int*) game->bspIdent) ) + Error( "%s is not a %s file", filename, game->bspIdent ); + if( force == qfalse && header->version != game->bspVersion ) + Error( "%s is version %d, not %d", filename, header->version, game->bspVersion ); + + /* load/convert lumps */ + numBSPShaders = CopyLump_Allocate( (bspHeader_t*) header, LUMP_SHADERS, (void **) &bspShaders, sizeof( bspShader_t ), &allocatedBSPShaders ); + + numBSPModels = CopyLump_Allocate( (bspHeader_t*) header, LUMP_MODELS, (void **) &bspModels, sizeof( bspModel_t ), &allocatedBSPModels ); + + numBSPPlanes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_PLANES, (void **) &bspPlanes, sizeof( bspPlane_t ), &allocatedBSPPlanes ); + + numBSPLeafs = CopyLump( (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, sizeof( bspLeaf_t ) ); + + numBSPNodes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_NODES, (void **) &bspNodes, sizeof( bspNode_t ), &allocatedBSPNodes ); + + numBSPLeafSurfaces = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFSURFACES, (void **) &bspLeafSurfaces, sizeof( bspLeafSurfaces[ 0 ] ), &allocatedBSPLeafSurfaces ); + + numBSPLeafBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_LEAFBRUSHES, (void **) &bspLeafBrushes, sizeof( bspLeafBrushes[ 0 ] ), &allocatedBSPLeafBrushes ); + + numBSPBrushes = CopyLump_Allocate( (bspHeader_t*) header, LUMP_BRUSHES, (void **) &bspBrushes, sizeof( bspBrush_t ), &allocatedBSPLeafBrushes ); + + numBSPBrushSides = CopyLump_Allocate( (bspHeader_t*) header, LUMP_BRUSHSIDES, (void **) &bspBrushSides, sizeof( bspBrushSide_t ), &allocatedBSPBrushSides ); + + numBSPDrawVerts = GetLumpElements( (bspHeader_t*) header, LUMP_DRAWVERTS, sizeof( bspDrawVerts[ 0 ] ) ); + SetDrawVerts( numBSPDrawVerts ); + CopyLump( (bspHeader_t*) header, LUMP_DRAWVERTS, bspDrawVerts, sizeof( bspDrawVerts[ 0 ] ) ); + + numBSPDrawSurfaces = GetLumpElements( (bspHeader_t*) header, LUMP_SURFACES, sizeof( bspDrawSurfaces[ 0 ] ) ); + SetDrawSurfaces( numBSPDrawSurfaces ); + CopyLump( (bspHeader_t*) header, LUMP_SURFACES, bspDrawSurfaces, sizeof( bspDrawSurfaces[ 0 ] ) ); + + numBSPFogs = CopyLump( (bspHeader_t*) header, LUMP_FOGS, bspFogs, sizeof( bspFogs[ 0 ] ) ); + + numBSPDrawIndexes = CopyLump( (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, sizeof( bspDrawIndexes[ 0 ] ) ); + + numBSPVisBytes = CopyLump( (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, 1 ); + + numBSPLightBytes = GetLumpElements( (bspHeader_t*) header, LUMP_LIGHTMAPS, 1 ); + bspLightBytes = safe_malloc( numBSPLightBytes ); + CopyLump( (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, 1 ); + + bspEntDataSize = CopyLump_Allocate( (bspHeader_t*) header, LUMP_ENTITIES, (void **) &bspEntData, 1, &allocatedBSPEntData); + + CopyLightGridLumps( header ); + + /* free the file buffer */ + free( header ); +} + + + +/* +WriteRBSPFile() +writes a raven bsp file +*/ + +void WriteRBSPFile( const char *filename ) +{ + rbspHeader_t outheader, *header; + FILE *file; + time_t t; + char marker[ 1024 ]; + int size; + + + /* set header */ + header = &outheader; + memset( header, 0, sizeof( *header ) ); + + //% Swapfile(); + + /* set up header */ + *((int*) (bspHeader_t*) header->ident) = *((int*) game->bspIdent); + header->version = LittleLong( game->bspVersion ); + + /* write initial header */ + file = SafeOpenWrite( filename ); + SafeWrite( file, (bspHeader_t*) header, sizeof( *header ) ); /* overwritten later */ + + /* add marker lump */ + time( &t ); + sprintf( marker, "I LOVE MY Q3MAP2 %s on %s)", Q3MAP_VERSION, asctime( localtime( &t ) ) ); + AddLump( file, (bspHeader_t*) header, 0, marker, strlen( marker ) + 1 ); + + /* add lumps */ + AddLump( file, (bspHeader_t*) header, LUMP_SHADERS, bspShaders, numBSPShaders * sizeof( bspShader_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_PLANES, bspPlanes, numBSPPlanes * sizeof( bspPlane_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_LEAFS, bspLeafs, numBSPLeafs * sizeof( bspLeaf_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_NODES, bspNodes, numBSPNodes * sizeof( bspNode_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_BRUSHES, bspBrushes, numBSPBrushes*sizeof( bspBrush_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_BRUSHSIDES, bspBrushSides, numBSPBrushSides * sizeof( bspBrushSides[ 0 ] ) ); + AddLump( file, (bspHeader_t*) header, LUMP_LEAFSURFACES, bspLeafSurfaces, numBSPLeafSurfaces * sizeof( bspLeafSurfaces[ 0 ] ) ); + AddLump( file, (bspHeader_t*) header, LUMP_LEAFBRUSHES, bspLeafBrushes, numBSPLeafBrushes * sizeof( bspLeafBrushes[ 0 ] ) ); + AddLump( file, (bspHeader_t*) header, LUMP_MODELS, bspModels, numBSPModels * sizeof( bspModel_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_DRAWVERTS, bspDrawVerts, numBSPDrawVerts * sizeof( bspDrawVerts[ 0 ] ) ); + AddLump( file, (bspHeader_t*) header, LUMP_SURFACES, bspDrawSurfaces, numBSPDrawSurfaces * sizeof( bspDrawSurfaces[ 0 ] ) ); + AddLump( file, (bspHeader_t*) header, LUMP_VISIBILITY, bspVisBytes, numBSPVisBytes ); + AddLump( file, (bspHeader_t*) header, LUMP_LIGHTMAPS, bspLightBytes, numBSPLightBytes ); + AddLightGridLumps( file, header ); + AddLump( file, (bspHeader_t*) header, LUMP_ENTITIES, bspEntData, bspEntDataSize ); + AddLump( file, (bspHeader_t*) header, LUMP_FOGS, bspFogs, numBSPFogs * sizeof( bspFog_t ) ); + AddLump( file, (bspHeader_t*) header, LUMP_DRAWINDEXES, bspDrawIndexes, numBSPDrawIndexes * sizeof( bspDrawIndexes[ 0 ] ) ); + + /* emit bsp size */ + size = ftell( file ); + Sys_Printf( "Wrote %.1f MB (%d bytes)\n", (float) size / (1024 * 1024), size ); + + /* write the completed header */ + fseek( file, 0, SEEK_SET ); + SafeWrite( file, header, sizeof( *header ) ); + + /* close the file */ + fclose( file ); +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/changelog.q3map1 b/misc/mediasource/netradiant-src/tools/quake3/q3map2/changelog.q3map1 new file mode 100644 index 00000000..21b0cb99 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/changelog.q3map1 @@ -0,0 +1,371 @@ +Old Q3Map 1.x and Early Q3Map2 Changelog (Chronological Order) + +- FILE IS STATIC. IF YOU MAKE CHANGES, UPDATE CHANGELOG.Q3MAP2 - + + +Date Version Notes +---------------------------------------------------------------- +2001-12-03 1.2 (ydnar) Alpha Initial version (win32) + +2001-12-03 1.2 (ydnar 2) Alpha Tolerance expanded + (more brush faces caught) + +2001-12-04 1.2 (ydnar 3) Alpha Detail faces inside other + detail brushes now culled, + Small against large detail + faces also culled. + +2001-12-04 1.2 (ydnar 4) Alpha djbob found a bug where + coincident caulk faces + were causing textured + faces to be caulked. Fixed. + +2001-12-04 1.2 (ydnar 7) Alpha 5 and 6 were internal test + versions. This version + takes into account extra + surface info, so coplanar + clip brushes no longer + cull away textured sides. + +2001-12-22 1.2 (ydnar 8) Alpha Optimized light. Lighting + for most maps should now + be measurable in minutes + as opposed to hours. + +2001-12-24 1.2 (ydnar 9) Alpha Fixed light. It is still + faster, but to enable + "blinding fast" mode, + you must supply the -fast + switch on the commandline + after -light. Fast mode + should be approximately + 2x as fast as build 8. + +2001-12-24 1.2 (ydnar 10) Alpha Grid lighting is now + optimized. Not as much + as I would like, but + a distance^2 cull before + traces on EVERY SINGLE + SURFACE LIGHT IN THE MAP + certainly speeds things + the fuck up. -fast not + necessary to see this + optimization. Also added + the -cheap switch to + limit light contributions + to a point when it exceeds + 255 in R, G, and B. This + *may* cause artifacts. + Test away... + +2001-12-24 1.2 (ydnar 11) Alpha Now using PVS data (vis). + Well constructed and + hinted maps should now + see a bit of a speedup. + Lights in the void are + also now removed as a + byproduct. + +2001-12-24 1.2 (ydnar 12) Alpha Fixed bug that caused + vlight to crash. + +2001-12-27 1.2 (ydnar 13) Alpha - Fixed broken PVS check. + - Cheap now supresses sun + Sun trace skipped if + sample is "cheapened." + - Experimental -smooth + option for subsampling + shadow edges. + - Experimental radiosity + code. Will probably crash. + - Other minor optimizations. + +2001-12-27 1.2 (ydnar 14) Alpha Build 13 always subsampled, + making it slower. Fixed. + +2001-12-28 1.2 (ydnar 15) Alpha Bad windings from edge- or + vertex- manipulated brushes + no longer created. Vertex + lighting on func_* with + an origin now works. + Radiosity should be more + stable (but not fully + correct yet). Light + envelopes now properly + calculated for entities + with origins. + +2001-12-28 1.2 (ydnar 16) Alpha Un-vised maps will now light. + +2001-12-30 1.2 (ydnar 17) Alpha Radiosity. Use q3map_bounce + in shaders to specify + amount of light to reflect. + Use -bounce N after -light + to enable radiosity. Use + -dump to emit radiosity + lights as a prefab. + +2001-12-31 1.2 (ydnar 18) Alpha Normalization release. New + features include -fastgrid, + -cheapgrid, and -fastbounce. + Running with -fastgrid and + -cheapgrid will produce + results identical to normal + q3map (with the lightgrid + being a little darker). + Also added q3map_nofast to + shaders to override -fast + switch for a surface light. + +2002-01-01 1.2 (ydnar 19) Alpha Fixed an odd vertex lighting + bug (thanks Quakin) that was + causing sun to leak to brush + faces when using r_vertexlight + ingame. Changed a little bit + of the default behavior, so + test with vertex lighting + and with terrain. Minor + shader changes might be + necessary to get some maps to + look as before. + +2002-01-01 1.2 (ydnar 20) Alpha Colored alpha shadows. Some + minor optimizations in + shadow tracing. Should be + slightly faster than 19. + +2002-01-02 1.2 (ydnar 21) Alpha Set up colored shadows + properly to use + surfaceparm lightfilter. + Shaders must use this parm + to have colored shadows. + Can be used with alphashadow + as well. + +2002-01-04 1.2.1-y1 (nightly) This version is all new, + based off the official + GtkRadiant tree, which has + all the previous enhancements. + New features include colored + lightgrid tracing through + lightfilter shaders, and + surfaceparm lightgrid, for + large/space maps with large + volumes. Also fixed are + potential broken brush + winding radiosity crashes. + Maybe. + +2002-01-05 1.2.1-y2 (nightly) Merged latest CVS. Removed + bug where ambient was getting + calculated into the radiosity + solution for every pass, + leading to overbright maps + in a hurry. Also removed + the bad PTPFF reporting, + as it only caused problems + with radiosity in a big way. + Sue me. + +2002-01-05 1.2.1-y3 (nightly) I really suck. Sample color + now properly cleared to 0 + when bouncing. + +2002-01-07 1.2.1-y4 (nightly) Particle Studio generated + brush faces should no longer + be culled. I no longer cull + faces that are autosprite. + Added -bouncegrid to have + radiosity add to lightgrid. + +2002-01-08 1.2.1-y5 (nightly) Same as y4, but compiled with + full optimizations. Should + be 10-25% faster in all, + including BSP and vis + stages. + +2002-01-09 1.2.1-y6 (nightly) Brushfaces with polygonoffset + in their shader will no longer + be faceculled. + +2002-01-11 1.2.1-y7 (nightly) Increased stack size for threads + to 4MB on Win32 to (hopefully) + elminate stack overflow + crash with radiosity. Also + made subdivision use the heap + to lessen the stack load. Fixed + bug where q3map_bounce was not + being used in shader parsing. + Redid some of the divide math + to work in 0-255 instead of + 0-256. + +2002-01-11 1.2.1-y8 (nightly) More Win32 threading + crutches. Eat me, Bill. + +2002-01-15 1.2.1-y9 RR2DO2 noticed a stupid bug + in my PVS code. Fixed it, + so the PVS light opts work as + they should. Lighting is + faster. Also got rid of some + redundant square roots from + the raytracing, speeding up + lighting another ~25%. + +2002-01-20 1.2.1-y10 Fixed a potential crash bug + with maps with 0 lights. Also + changed how lightmaps are + projected onto patches that + lie in a single plane (bevel + endcaps, floors, etc). Shadows + now work properly on them. + +2002-01-22 1.2.1-y11 Fixed a divide-by-zero crash + with maps with no lights or + no tracing. Also added + code to make brush/patch + vertex lighting more closely + resemble lightmap, even on + less-than-perfect maps. And + -light is faster, too...about + 25% on q3dm17. 34->25 seconds. + +2002-01-24 1.2.1-y12 Completely rewrote the path + argument handling. Should find + the Quake 3 dir and other + dirs properly now. Needs to + be tested on Linux though. + Also made lights linear by + default when run with -game + wolf. This is to match the + Gray Matter q3map and + entity definition. + +2002-01-28 1.2.4-y1 Merged from 1.2.4-nightly CVS + sources. Fog sparklies gone. + -nopatchfix so vlight works + properly again. Cleaned up + paths processing some more, + including Linux stuff. Added + _lightmapscale entity key. + Brought -game wolf lighting + to parity with GM tools. + RR2DO2's PCX loading fix. A + bunch of other useful fun shit. + +2002-01-29 1.2.4-y2 Fixed a bug in RR2DO2's PCX fix. + Fixed a stupid bug in lightmap + dimension bounds checking (thanks + Laerth). + +2002-01-29 1.2.4-y3 Now will detect (and report to + GtkRadiant) all degenerate patches + like those created by capping a + cone. + +2002-02-23 2.0.0-a1 thru a3 Rewrote about 30% of the code. + Lots of cool new shit. + +2002-02-24 2.0.0-a4 thru a8 Terrain fix (thx Pointy), patches + are no longer circus colored, more + terrain texturing fixes. + +2002-02-26 2.0.0-a10 thru a11 Adjacent coplanar surfaces now + will share lightmaps. This prevents + most wierd edge cases with filter + and speeds things up a bit. Patches + too. + +2002-02-27 2.0.0-a12 More lightmap fixes for non-planar + surfaces. Bugfixes in allocation/ + compression of lightmaps as well. + +2002-03-02 2.0.0-a13 Fixed some surface light bugs, + adjusted the occluded-luxel finding + code, and amped the radiosity. Other + fixes to RTCW lighting code (better + angle attenuation on linear lights). + +2002-03-04 2.0.0-a14 Vertex light should now be near- + perfect on clean (and mostly on not- + so-clean) maps. Unlit maps will no + longer have tri-fanned brush faces + with random vertex colors. VLight is + now totally gone (reverts to -light). + +2002-03-06 2.0.0-a15 Relaxed the planar check, should now + classify all slightly-off plane brush + face metasurfaces as planar. Triangle + checking much more stringent as well. + +2002-03-11 2.0.0-a16 Vis crash gone. Lightmap allocation + now sorted by shader to minimize + shader count (and lessen chance for + RTCW shader substitution bug). Hit + big quarter-century also. + +2002-03-12 2.0.0-a17 Dammit. + +2002-03-12 2.0.0-a18 Hunting phantom lights... + +2002-03-16 2.0.0-a19 Fogclip and _celshader. Check the + extras folder... + +2002-03-18 2.0.0-b1-rc1 Beta release candidate. Fixed the + stupid phantom light bug finally. + Tricked out the sun tracing a wee + bit as well, should be a little + faster + more accurate. Other little + bits fixed up as well. Thanks to K, + {wf}ShadowSpawn and RR2DO2 for their + help tracking these last bugs down. + +2002-03-19 2.0.0-b1-rc2 Increased some maximums, and got + rid of some cruft. + +2002-03-22 2.0.0-b1-rc3 Some minor optimizations. + +2002-03-30 2.0.0-b1-rc5 Now with fur (see extras/fur.shader). + +2002-04-01 2.0.0-b1-rc6 Enhanced with baby seal technology. + +2002-05-01 2.0.1 OK, better late than never. Fixed the + alphashadow = 255 = transparent bug. + +2002-06-24 2.1.0-b1 Added _foghull functionality. Works + like terrain "_shader" where + you don't need "textures/" prefix. + Also added q3map_normalmap. See + NVIDIA's website for Photoshop filter + to generate normalmaps from grayscale + heightmaps. This makes lightmaps + look bumpmapped. Currently 50% broken. + +2002-07-06 2.2.0-b1 Empty epairs now stripped from map, + fixing Wolfenstein crash bug. Func_* + entities are now fogged properly. + Sort of. This will be enhanced later. + Added the .srf file to store all the + extra crap I was hiding in the BSP. + It's an editable text file that + -light uses, so you can change the + samplesize w/o recompiling the map + (just -light'ing it). Changed color + normalization to clamping, because + it looks better. Other stuff got + fixed as well. + +2002-07-08 2.2.0-b2 thru b11 Test versions. Thanks jer and jet! + +2002-07-09 2.2.0-b12 Larger-than-life lightmaps are now + supported, up to 1024x1024. Add + q3map_lightmapSize H W to a shader + to use. Lightmaps are stored in + maps/{mapname}/_lm_NNN.tga and a + shader script q3map_{mapname}.shader + is generated. Also added + q3map_lightmapGamma N.N. Use a + value of 2.0 to simulate + r_overBrightBits 1 and + r_mapOverBrightBits 2 on external + lightmap images. diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/changelog.q3map2.txt b/misc/mediasource/netradiant-src/tools/quake3/q3map2/changelog.q3map2.txt new file mode 100644 index 00000000..d58c0242 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/changelog.q3map2.txt @@ -0,0 +1,709 @@ +Q3Map2 Version History + Changelog (Reverse Chronological Order) + +2.5.16 (2004-10-18) + +- New: -fixaas mode to reassociate an AAS file with a changed BSP +- New: -nostyles switch on light phase disabling lightstyles +- Using libmhash cryptographic hashing library instead of md5lib + + +2.5.15 (2004-07-08) + +- New: q3map_rgbGen, q3map_rgbMod or q3map_colorGen, q3map_colorMod +- New: q3map_alphaGen const (like q3map_alphaMod set) +- New: q3map_noVertexLight to suppress overwriting of vertex rgb +- q3map_backShader now works again, can be used instead of + q3map_cloneShader + q3map_invert on the target shader +- q3map_alphaMod volume brushes in func_group entities will now only + affect that entity's surfaces +- q3map_clipModel now works on trans/nonsolid shaders, allowing + simplified clipping surfaces in models +- Fixed bug in alphaMod code where only the first vertex was being + modded (thanks Ratty) +- Vis exits instead of crashing with divide-by-zero when there are + no portals on simple box maps +- All of a surface's lightmaps must be solid or not solid, fixing + ST coord problem with non-Raven games using lightstyles +- Reverted a change in the meta code which was causing lightmap coord + overflows and ugly self-shadowing errors on surface boundaries +- Any use of lightstyles automatically sets -nocollapse to reduce + total shader counts +- Tenebrae lightmap size changed to 512x512 + + +2.5.14 (2004-04-09) + +- New: -dirty mode courtesy of RaP7oR (dirtmapping/ambient occlusion) +- New: q3map_skyLight code using more uniform angular distribution about + the sky hemisphere +- New: q3map_alphaMod set N.N +- New: q3map_alphaMod scale N.N +- New: q3map_alphaMod volume - applies all other q3map_alphaMod directives + to each vertex inside a brush textured with this shader, allowing large + faded scrolling fire shaders, waterfalls, marquees, explicit dotProduct + terrain blending control, etc. +- Fixed a bug in alphaMod code where the type of the first alphaMod was + being used for all subsequent alphaMods +- Lowered vertex-lit surface limits to 999 verts, 1000 was breaking Quake 3 +- Tightened up solid lightmap tolerances +- Fixed bug in solid lightmap code where lightmap SD coords were being + incorrectly set + + +2.5.13 (2004-03-03) + +- New: -convert -format to convert between different BSP formats. + Example, to convert a Jedi Academy map to Enemy Territory: + -game ja -convert -format et +- New: -game etut support for Urban Terror on Enemy Territory +- New: -analyze mode for reverse engineering a BSP format +- New: -compensate N.N (default 1.0) for descaling lightmap/vertex/grid + data to compensate for ingame overbrighting. 4.0 is a good value for + Quake 3 if used in combination with -gamma 2.2 +- New: compensate/gamma per-game setting +- New: -light -cpma argument for "classic" (sic) vertex lighting +- Replaced malloc() with stack allocation in IlluminateRawLightmap for + most small/medium lightmap calculations +- Misc cleanups in q3map2.h +- Support for non-128x128 lightmaps +- The -meta process will now generate surfaces with more than 64 + verts that have non-lightmapped shaders +- Extended lightmap size tolerance to 2x for merging meta triangles in + maps with aggressive lightmapscale. Sorry kids! +- Moved surface finish pass (celshading, cloning) to final surface pass. + This should fix a bug involving fog/tesselation/celshading/cloning +- Solid-color lightmaps (within 1/255 in RGB) are detected and replaced + with a single pixel lightmap, saving space + + +2.5.12 (2004-01-18) + +- New: -dark option for dark lightmap/brush seams in -light (Unreal 1-ish) +- New: spawnflags 4 on misc_model entities makes them forcemeta/lightmapped + unless explicitly set as vertex lit in their shader(s). This can be + combined with spawnflags 2 (solid) as spawnflags 6 +- New: -gamma N.N switch sets lightmap/vertex gamma value for more + realistic lighting, instead of using high ambient/minlight. Default + is 1.0 (linear ramp), good values are between 1.5 and 2.2 +- Changed q3map_lightmapGamma N.N to q3map_lightmapBrightness N.N, to + better match its intended function +- Ported to VS.NET 2003 and GtkRadiant 1.5 (spog_branch) +- Fixed bug in _skybox maps where sunlight was leaking through brushes. + Thanks pjw! +- Fixed bug in ASE loader where models without submodels/submaterials + would not load properly. +- Fixed bug where q3map_tcGen was not being applied to models +- Optimized MergeMetaTriangles a bit +- Added KOR's fix to raytracer +- -bouncegrid no longer affects the lightgrid dir +- Added feature to PicoModel where spaces in material names in 3DS, ASE + and LWO models will mark the end of the shader name, so you can have + "textures/foo/bar 1" and "textures/foo/bar 2" in Lightwave, and both + surfaces will map to "textures/foo/bar" + + +2.5.11 (2003-12-01) + +- New: added support for _skybox entities to generate "portal sky" + surfaces in games w/o native support (Quake 3). _skybox entities have + 3 keys: _scale (default 64), and angle/angles (for rotation of the + skybox relative to the map) +- New: added -skyfix switch to BSP phase as a workaround hack for + the black GL_CLAMP border on skybox edges on ATI (and newer nvidia) + video cards. Note: unnecessary in ET or JA +- New: Added _anglescale to light entities for scaling angle attenuation. + Use a small value (< 1.0) to lessen the angle attenuation, and a high + value (> 1.0) for sharper, more faceted lighting +- New: Added _lightmapscale support to misc_model entities +- Custom shaders (external lightmaps, styles) will not be generated + if the find/replace text cannot be found +- Tightened up light culling epsilon from 1.0 to 0.125 to stop certain + surface lights from being incorrectly culled (thanks RasputiN!) +- Fixed bug where small 3 and 4 sided brush faces were getting fanned, + adding triangle/vertex counts +- Moved to Visual Studio .NET, with aggressive optimizations enabled +- Cleaned up missing image warnings +- Parsing images out of shader stages if not found explicit/implicitly +- Loads Enemy Territory implicitMap images if editor/light image not found + + +2.5.10 (2003-10-22) + +- New: Lightwave model support (beta) courtesy of RR2DO2 +- New: Heretic 2 FM model support courtesy of Nurail +- Re-enabled vertex cache friendly triangle reordering with fix +- Disabled triangle reordering on certain surfaces, including autosprite + shaders due to visual errors +- Fixed bug in radiosity where sorting of lights by style took forever. + Thanks ReBoOT! +- Fixed bug in sun lighting code where maps too far off the origin would + not be properly it by sun or sky light. Thanks MindLink! +- Entity causing a leak will be printed and selected in Radiant if BSP + monitoring is enabled. Requested by heeen +- Fixed odd bug causing 10x slowdown in lighting in some maps. Should + be back to 2.5.7 performance. Also fixed a couple old bugs related to + autosprite shader (point) lights and backsplash lights not being styled + or setup correctly + + +2.5.9 (2003-10-12) + +- Disabled triangle reordering for now (crashing on some maps) + + +2.5.8 (2003-10-02) + +- New: Added two new sun parameters: angular deviation (width of the sun in + degrees) and sampling count (jitters). This allows for decent approximation + of penumbra "half-shadow" effects from sunlight with 16+ samples. These + parameters are accessible for entity lights (including spots and suns) via + these entity keys: _deviance and _samples. To use in shaders, use the new + q3map_sunExt +- New: q3map_lightmapFilterRadius for light-emitting shaders. + Put *after* any q3map_sun directives or else your sun will be filtered. This + is good for eliminating the "stadium lighting" effect from q3map_skyLight. + Also usable as an entity key: _filterradius or _filter +- New: Quake 2 MD2 model support in PicoModel for misc_model entities + (thanks to Nurail!) +- Re-enabled vertex-cache-aware triangle reordering. Will probably have a + negligible effect on rendering performance, but can't hurt +- Added short-circuit to raytracer: any empty nodes (including children) are + ignored on sun traces +- Added BSP file size printout +- Filtering of any kind now disables adaptive supersampling on a per-light, + per-ightmap basis +- Fixed another _minlight <-> styled light interaction bug (thanks pjw!) + + +2.5.7 (2003-08-31) + +- New: Jedi Academy support via -game ja +- New: DDS (DXT1/3/5) texture support for future games +- Re-enabled q3map_surfaceModel support, and the 'oriented' flag works as well +- Re-enabled (fixed, really) large external lightmap support +- Fixed a bug in the model code that would cause a crash if an uninvertable + matrix was created +- Fixed a bug in Mathlib m4x4_t code where the tolerance for a singular matrix + was too low and crapping out on small (scaled down) matrices +- Fixed bug in divide-by-zero on lightmap efficiency calculation +- Added -force switch, allows unsupported BSP formats to (try) to be loaded + + +2.5.6 (2003-08-15) + +- New: can convert BSP files to MAP files via -convert -format map. Note: not + perfect by any means, as certain pieces of data are irretrievably lost, such + as func_group entities (including terrain specifics), brush face texturing + info, and light/misc_model entities with Q3Map2-generated BSPs + + +2.5.5 + +- New: -scale N.N mode to scale the BSP +- New: -light -lomem switch to supress trace BSP optimization. This + feature trades lighting performance for decreased memory usage +- New: Added negative light support (note: will not darken below _minlight value) + might screw up radiosity, haven't tested much. Should work with entity + lights, shader lights, sun/sky lights and radiosity. Lightfilter shadows + tint negative lights too, so the end effect is subtraction of the color +- New: Lightstyle support for non-Raven (JK2/SOF2) games, including Quake 3, + RTCW, ET, EF. Only works with lightmapped surfaces, use with care +- Fixed long standing terrain texturing bug, should produce exact desired + results all of the time now. May require fixing alphamaps that were + kludged together to accomodate this bug on existing maps +- Fixed bug (huh, wtf) causing misc_model surfaces to not be fogged +- Fixed bug where fog brushes wouldn't fog surfaces if a global map fog + shader was present +- Fixed bug where -patchmeta surfaces were being ignored for raytracing +- Fixed long-standing bug where twosided surfaces were not correctly + bouncing light. You can now have a foggy glass window that re-emits + bright light with q3map_bounce 3.0 or so +- Fixed really stupid bug in radiosity with bouncing styled lights +- Stripping .map and appending .bsp in -info mode +- Fixed bug where tesselated brush face surfaces were not being fogged +- Twosided surfaces (using cull disable/twosided/none) are now lit twosided +- Added tighter tolerance for alphashadow/lightfilter shadowing to raytracer + which fixed problem with double shadows from tracing near triangle seams +- Brush entities should now be properly fogged. Really. +- Styled lightmaps are no longer affected by _minlight (doh) + + +2.5.4 (2003-04-01) + +- New: q3map_tessSize support for JK2/SOF2 +- New: -lightmapsize N argument +- Fixed bug where switched styled lights weren't working correctly in SOF2/JK2 +- Fixed bug where external lightmaps with generated shaders were referencing + the wrong lightmap +- Fixed bug causing lightgrid brushes to be ignored +- Added variable sphere around trace sample points to inhibit occluder geometry + + +2.5.3 (2003-03-06) + +- New: SOF2/JK2 light styles now supported +- New: q3map_lightStyle N to set shader lightstyles +- New: Tenebrae 2 support via -game tenebrae +- New: -light -deluxe and -debugdeluxe for Tenebrae "deluxemap" static + lighting algorithm +- Light envelopes now properly clipped to the PVS +- q3map_vertexScale re-enabled (scales vertex lighting per-shader) +- Minor bug in brush bevel code corrected +- Brushes from func_group entities are correctly sorted on insertion +- Fixed a couple misc warnings to print "percent" instead of "%" +- Added -custinfoparms support to -light mode to suppress warnings +- _minlight, _minvertexlight and _mingridlight order independent, and now + allow for values of 0 + + +2.5.2 (2003-02-17) + +- Fixed crash bugs with global map fog +- Model loading really only warns once now + + +2.5.1 (2003-02-17) (Splash Damage internal release) + +- Added more Hella-Fast juice to light code. Overall should be 35% faster +- Refactored surface portion of raytracer code for less memory usage +- Changed UVW epsilon in raytracer to catch more edge cases +- Removed bounds check on occluded luxel finding, was causing more problems + than it was solving +- Adaptive antialiasing code now ignores unmapped luxels for better shadow + edges and higher performance +- Brushes in the BSP are now sorted opaque first +- Fixed Really Stupid bug causing MapRawLightmap to take about 4x as long +- Added optimization to make MapRawLightmap 2x as fast +- New non-sucky quadrilateral subdivision of patches for MapRawLightmap +- Patches with < 90 degrees of curvature are now box-lightmapped +- Patch vertex normals now correctly stored, fixing bug in 2.5.0 +- Prints warning if map with < 10% detail brushes is detected + + +2.5.0 (2003-02-14) (Splash Damage internal release) + +RAYTRACING AND SHADOW CALCULATION +- New raytracing code. Rewrote the raytracer to maximize efficiency on modern + "caulk-hull" maps. Uses triangle intercept code written by SPoG, based on code + by Tomas Moller and Ben Trumbore (Journal of Graphics Tools, 2(1):21-28, 1997) + and a biased octree leaf subdivision scheme by Y.T. +- Shadows (casting and receiving) are now controllable per-entity + New entity keys: "_castShadows" or "_cs" and "_receiveShadows" or "_rc" + Values: 0 = no shadows, 1 = worldspawn shadows, > 1 explicit shadow group, + negative values imply no worldspawn shadow interation. + *Entities, including model2 and RTCW misc_gamemodels can now cast shadows* + +RADIOSITY +- Bumped up default and smallest radiosity patch size. Performance should be + approximately 4x with a small quality tradeoff +- Radiosity patches now trace to centroid of triangle, and not bounds center +- Radiosity and surface lights are now nudged around a bit if in solid +- Radiosity light generation code is now thread-safe +- Radiosity -dump files now .map instead of .pfb +- Poorly worded "q3map_bounce" renamed to "q3map_bounceScale" (old still works) +- New -bounceonly switch to store only bounced light in the BSP (for Tenebrae) + +MISC LIGHTING +- Optimized case where light and sample are coplanar +- Forcing nudged luxels to stay within lightmap surfaces' bounds + +CURVED SURFACES +- New -subdivisions N argument, works with -patchmeta and -light for setting + patch level-of-detail. Default value is 8, use 4 to simulate default Q3 +- All patch tesselation code changed to create x-patterned tesselation for + better lighting +- Storing patch LOD info in the .srf file for better patch light/shadows + +FOG +- Reworked fog code to fix bad interation with fog and clipped models + +MODELS +- Entities with attached MD3/ASE misc_models now have their bounds correctly set +- Attached misc_models now support q3map_clipModel for solidity +- Missing models will only warn once, rather than spew errors + +MISC +- Metasurface merging no longer folds nonplanar triangles into planar surfaces + and vice-versa * +- Fixed Really Stupid Bug where entity numbering was not loaded by lighting code + resulting in lightmaps merging across entity boundaries * + +* Might result in slightly larger BSP. For maximum efficiency, ungroup + func_group entities before doing a final compile + +TODO ++ Document new shadow stuff ++ Merge adjacent light-casting triangles into convex windings + + +2.3.38 (2003-02-07) + +- New lighting code, return of Smoove-B. Intelligently antialises shadow edges + when you use the new -samples N switch. Get -extra quality in 1/3 the time +- New lightmap filtering code. Now using a proper 0.25/0.5/1.0 filter kernel. + Also operates on individual lightsources, so per-lightsource filter/kernel + settings are now possible +- New -patchmeta fixes, now does stitching and adaptive subdivision. + Thanks Sock! +- Nonsolid patches will no longer be in the BSP when run with -patchmeta +- Misc fog fixes, including q3map_noFog support in maps with global _fog + support (SOF2/JK2) +- Now stripping misc_model entities from the BSP +- Fixed disappearing face bug that's been present since 2.3.36. + Thanks Shadowspawn! + + +2.3.37 (2003-01-24) + +- Building from GtkRadiant CVS trunk +- Added new brush bevel code by MrElusive to fix lingering aas problems (sweet!) +- Added -snap N arg to BSP phase for axial bevel plane snapping to reduce + clipped model plane count (note: will muck with above, use with care) +- Patches in terrain entities should now have proper vertex alpha set +- Fixed bug in fur code where fur was being limited to 2 layers (thanks pazur) +- Reduced vertexlight search area to a reasonable size to keep vertex lighting + times down + + +2.3.36 (2003-01-15) + +- Plane hashing re-enabled (I suck) +- Plane hashing optimized (faster parsing of larger maps) +- Plane finding accuracy code enabled +- New ASE clipping code + + With above should be 10-50% faster + + Should generate 33% fewer planes + + Generates mostly-axial 5-sided polyhedra instead of pyramids, + for tighter 2-sided clipping +- New -light args: + + -scale N -- scales all lightsources (area, radiosity, point, sky) + + -sky[scale] N -- scales sky lights (q3map_skylight, q3map_sunlight) +- Changed fur code to scale fur offset based on original vertex alpha + + +2.3.35 (2003-01-14) + +- PicoModel now inverts ASE T coordinate +- BSP to ASE converter now inverts T coordinate +- Disabling 2.3.34 triangle optimization code until I find out why it crashes +- Fixed Conscript-q3map2 to use stack_size ld flags directly on Darwin/OS X +- Added Conscript-q3map2 to q3map2.dsp for easier Win32 edit, *nix target + + +2.3.34 (2003-01-08) + +- Building from merged GtkRadiant 1.2 -> 1.3 merged codebase +- IMPORTANT NEW CHANGE: Light entities are now STRIPPED from the BSP file. + They are re-read in by -light from the MAP file. This has two consequences: + + It is no longer necessary to re-BSP & re-vis a map in order to change + lighting. You can just change lights in the map file and run -light. + + Slightly smaller BSP file, due to fewer entities + + Faster loading time, as the game code doesn't have to deal with them +- Added new -ne (normal epsilon) and -de (distance epsilon) for tuning precision + of plane snapping to correct potential AAS/BSP issues +- Using latest PicoModel, with support for RTCW MDC models +- Surfaces per raw lightmap are now sorted by shader name, which should give + slightly better lightmap efficiency and lower in-game shader counts +- Adjusted model code to use correct m4x4_t code & angles key +- Minor bugfix in patch color gradient calculation code +- Silenced erroneous areaportal warning spew +- q3map_tcGen now works on model surfaces +- Using default radiosity subdivide of 256 again (should make radiosity faster) +- Enabled byte-swapping code so Q3Map2 can be compiled/run on little-endian + architectures (Mac OS X) + + +2.3.33 (2002-12-08) + +- Added new -bouncescale argument for radiosity scaling +- Added -pointscale and -areascale for consistent naming +- Radiosity patch subdivision code enhanced +- Hint portals split the BSP first (higher priority) +- Antiportal and areaportal faces split the BSP last, to minimize errors +- Areaportals work internally like hint and antiportals, so they no longer need + to be full brushes (the other sides can be skip) +- External lightmaps are now named "lm_NNNN.tga" in the maps/mapname dir +- Cleaned up some of -light argument processing +- Planar surfaces w/o lightmaps will no longer be tagged as MST_TRIANGLE_SOUP + (this fixes problems with Particle Studio particles dropping out of view) + + +2.3.32 (2002-11-30) + +- GtkRadiant (1.2.11) integration +- Added epsilon to texture plane choose code to eliminate numerical + inconsistencies on brush faces slanted at 45 degree angles (bug 637) +- Fixed bug in lightmap export after lighting when map contains 0 BSP lightmaps +- Adjusted some light tracing constants to fix certain brush/patch seam shadows +- Tinkered with skylight code again +- Fixed bug where lightgrid would be black if level was compiled with -nogrid +- Fixed -approx code to work in floating-point space, using _minlight +- Fixed bug where vertex light code was using invalid pvs data to create + light list for surface, leading to incorrect vertex lighting +- Fixed related bug in anti-light-leak code that was causing brush faces to go + black (bug 694) +- New: _minlight sets _minvertexlight and (new) _mingridlight automatically +- New: _mingridlight key to set minimum grid lighting + + +2.3.31 (2002-11-21) + +- Stitching the edges of lightmaps on patches that wrap around (cyls and cones) + so the seam is no longer visible +- The -patchmeta switch works better now, the patches are still stored in the + BSP for collision, but are pre-tesselated into nonplanar meta surfaces for + more efficient rendering +- Better, more uniform lightmap sample position finding on patch meshes +- Moved q3map_tcMod and q3map_alphaMod processing to the final phase +- New: q3map_skylight AMOUNT ITERATIONS to replace surfacelight on sky surfaces + for much faster and more uniform sky illumination + + +2.3.30 (Splash Damage internal release) + +- Fixed bug in PicoModel ASE material parsing code +- Fixed a few seam/lightmap precision/projection errors +- Increased MAX_SHADER FILES to 1024 and fixed overrun error when more than that + number of shaders was listed in shaderlist.txt +- Increased a few compiler maximums for larger maps +- New: -np N switch on BSP phase, works like -shadeangle, in that it forces all + planar shaders to be nonplanar with the shading angle specified +- New: -nohint switch on BSP phase, omits hint brushes from compile for testing +- New: -debugaxis switch on light mode. Colors lightmaps based on their lightmap + axis (which direction the lightmap was projected on) +- New: -debugorigin switch on light mode. Colors lightmaps based on the luxel + origin relative to the raw lightmap's bounding box +- New: -debugcluster switch on light mode. Colors lightmaps based on the pvs + cluster the luxel falls into +- New: -convert switch to convert BSP to ASE file (experimental) +- New: q3map_lightmapmergable directive to allow terrain to be mapped onto a + single lightmap page for seamless terrain shadows + + +2.3.29 (2002-11-03) + +- Merged with latest CVS, fixed minor issues with matrix order +- Fixed minor Sys_FPrintf/Sys_Printf substitution typo in Q3Map2 +- Expanded debug colors to 12 for debugging surface meshes +- PicoModel: fixed ASE loader to support > 1 texture coordinate per-vertex, + so more models supported correctly, also loading vertex normals +- PicoModel: md3 shader names are now cleaned. Suffixes (such as .tga or .jpg) + are stripped, and \ path separators are changed to / +- New: Add :q3map to the end of any shader name, and it will be interpreted as + the named shader minus :q3map. Example: + textures/shaderlab/concrete:q3map -> textures/shaderlab/concrete + One potential use is the -approx feature to collapse lightmapped surfaces + into vertexlit surfaces, saving lightmap space/memory +- New: q3map_clipModel -- does what you think it does, sort of. This code ix + really experimental, and should *only* be used on large models such as terrain + (not small decorative models). This code will be evolving. Note: the shader's + surfaceparms are inherited by the magic clip brush, so if you have nonsolid + in your model's shader that uses q3map_clipModel, then the brush will also + be nonsolid + + +2.3.28 (2002-11-01) + +- Bug 654 (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=654): + Fixed problem where brush faces, drawsurfaces, and surfaceparms weren't living + together in perfect harmony (terrain surfaceparms now inherited by brushes) +- Nodraw fog works now, albeit when you're underneath, surfaces above don't get + fogged properly. Could be good for foggy water where you want the above-water + portions to only be occluded by the water surface +- Bug 656 (http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=656): + Number of lightgrid points displayed (byte size is currently out of proportion + due to internal storage format) when Q3Map is called with the -info switch +- Fixed wack surface merging bug where code would attempt to merge triangles not + adjacent to the current set, causing bad lightmap projections on nonplanar + surfaces +- Fixed tiny 1-character bug in 2d lightmap texture allocator where adjacent + luxels were being checked for occlusion rather than the actual source luxel + + +2.3.27 (2002-10-31) Happy Halloween! + +- Fixed minor bug in scriplib bugfix where the last character in a file wasn't + being read. +- Fixed bug where 0-area or bogus triangles were causing crash in MapRawLightmap + if they used a shader with a normalmap (thanks ShadowSpawn) +- Fixed bug where lightmaps were getting hosed levelwide on a prerelease version + of 2.3.27 +- Fixed bug where lightmaps were getting knackered on models and certain patches +- Merged latest PicoModel version from seaw0lf, adding support for ASE and WF OBJ + models (preliminary) +- Increased MAX_MAP_PLANES to 0x40000 (~256k) + +Known issues: +- Lightmap projection and surface merging on large ASE models sometimes flakes +- Surface to brush surfaceparm propogation doesn't work properly with large + metasurfaces: http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=654 + + +2.3.26 (2002-10-27) + +- Now using GtkRadiant's libpng and zlib config (linked as DLLs) +- Fixed bug in script parser where repeat calls to GetToken() were causing + memory corruption +- Fixed SOF2 -rename bug +- When using -game sof2 or -game jk2, the -flares argument is implied +- Added -noflares argument to disable the above behavior +- Added support for flares on entities. Use one of the following keys: + "_flare" "1" -- use default flare (different for each game) + "_flareshader" "path/to/flareshader" -- use a specific flare shader + Note: This only matters in SOF2/JK2 now. Make a light targetted (a spotlight) + to get it to aim the correct direction, otherwise it defaults to pointing + downward. You cannot have omnidirectional flares +- Lightgrid size is automatically increased to accomodate large maps. The + MAX_MAP_LIGHTGRID error will never happen again + + +2.3.25 (2002-10-22) + +- Go Giants! +- Fixed bug where Q3Map would crash on writing the BSP after the light stage. + Thanks to Rap7or (#q3map) and loon8 (Q3W forums) [bug 641] +- Fixed bug where surface lights were not affecting the light grid properly. + Thanks to Shadowspawn and djbob [bug 642] +- NEW: Added -faster support to lightgrid calculations while fixing previous bug +- NEW: Changed it so the BSP file is written to a temp file first, then renamed. + This should prevent BSP file corruption on crashes during writes + + +2.3.24 (2002-10-20) + +- Fixed numerous outstanding bugs and issues. +- Normal interpolation is now improved. It's slightly slower, but more 'correct' + in cases where you have 10 triangles in one plane and 1 triangle in another + meeting up and the 10 triangles were over-affecting the average. Only new + identical normals are averaged now. This change affects phong shading, meta + surfaces, and PicoModel +- PicoModel up to version 0.7.6, BSD license, better 3DS model support +- PicoModel library now fixes broken normals on MD3 and 3DS models +- Bumpmapping code is improved. The correct tangent vectors per-triangle are + now calculated so the bumpmaps are consistent with regards to light direction +- Metasurface merging code optimized. Should be about 100x as fast on complex + maps or maps using models with high triangle counts +- Vertexlight code tweaked a bit +- Triangle/winding orders now more consistent. Tesselated surfaces will have + a uniform triangle ordering (thanks RR2DO2) +- NEW: "vertexDeform move" now parsed and surfaces are merged into the + appropriate BSP leaves they may enter into (thanks to Bart Vrijkorte) +- NEW: shader command: q3map_alphaMod. Currently takes a single form: + q3map_alphaMod dotproduct ( NX NY NZ ) + where NX NY NZ are a unit normal (length of 1.0) specifying direction. + An example use would be snow in a shader's 2nd pass, using alphaFunc or + blendFunc: + q3map_alphaMod dotproduct ( 0 0 1 ) // surfaces facing upwards have snow + (idea contributed by RR2DO2) + + +2.3.23 (2002-10-18) + +- In my haste to release the previous version, I neglected to give credit where + it was due. Seaw0lf had as much (probably more) to do with the new model + loading library (PicoModel). Because of his efforts, you can load 3DS models + and use them in misc_model entities. +- PicoModel model library up to version 0.7. Improved 3DS support, more stable. +- Surface models still not reenabled. Soon. :) +- You can now remap a misc_model's shaders like this: + Key "_remapNN" "the/model/shader;the/real/shader" + This works just like TA terrain vertexRemapShader key. You can also supply a + * glob for the source shader if you want all your model's shaders to use the + specified shader: + "_remap" "*;models/mapobjects/tree/bark" + + +2.3.22 (2002-10-16) + +- Moving to sensible Linux-style versioning. +- The misc_model code has been completely rewritten, breaking surface models. + Surface models will reappear in the next release, once the new model API has + stablized. +- New: MD3 and 3D Studio 3DS models now natively supported. +- The misc_model "angles" key now supported. Values: "pitch yaw roll" in keeping + with standard Quake 3 angles order. +- Models scaled with "modelscale_vec" now have proper normal scaling/rotation + (thanks SPOG). +- Models can now be lightmapped. +- Models can now have > 1000 vertexes per surface. +- For best results for above, add the following to models' shaders: + q3map_splotchfix + q3map_nonplanar +- 3DS models' MATERIAL NAMES ARE THE FINAL Q3 SHADER NAMES. YOU HAVE BEEN WARNED. +- Models are generally 13373R. :) + + +2.3.0-a21 (2002-10-02) + +- Fixed a stack of really stupid bugs in the lightgrid code. Should be faster + and more predictable now. +- SOF2/JK2 lightgrid now compiled. This is the first version of Q3Map2 that can + compile full, release-worthy SOF2 and JK2 maps. +- SOF2/JK2 damageshader and damagable brush faces should work correctly now. + + +2.3.0-a20 (2002-09-26) + +- SOF2/JK2 worldspawn "fog" (and "_fog") shader key support for levelwide fog +- SOF2/JK2 light "scale" key to scale light brightness +- SOF2/JK2 -rename function for _bsp and _rmg_bsp shader renaming + + +2.3.0-a19 (2002-09-24) + +- Shaders can now be subclassed (Q3Map relavant portions only, such as + surfaceparms, lighting, texture projection, etc). To subclass an existing + shader, add "q3map_baseshader X" where X is the name of the base shader. +- Preliminary auto-model distribution over surfaces. You can now have things + like grass and tree models automatically distributed across your terrain + or other surfaces. To wit: + + q3map_surfacemodel models/mapobjects/tree2/tree2.md3 64 0.001 0.5 4.0 0 360 1 + + q3map_surfacemodel + + + The last flag is 1 or 0, and sets whether the model gets fitted to the + orientation of the surface. Not functional yet. See screenshots page for + shots of this in action. + + +2.3.0-a18 (2002-09-21) + +- misc_models can now be attached to any brush model entity. Just target the + brush entity with the misc_model (select model, then entity, hit Ctrl+K) +- q3map_tcMod translate (or shift or offset) +- q3map_tcMod rotate (rotates around origin, not center) +- q3map_tcMod scale +- Metasurface merging now much, much better. Merges into roughly rectangular or + square areas wherever possible +- q3map_terrain no longer sets Z-axis lightmap projection. It must be set in + the terrain layer shaders if you want previous behavior +- Worlspawn _blocksize key now supports 3 elements for setting X Y and Z splits + independently of each other (use a value of 0 for no splits on that axis) +- Misc bugfixes + + +2.3.0-a1 through 2.3.0-a17 (2002-07 through 2002-09-20) + +- Elite Force support (via -game ef) +- SOF2 and JK2 support (via -game sof2 or -game jk2) +- All new image handling with PNG support +- q3map_lightimage specifies image for radiosity and lighting +- External lightmaps, set using q3map_lightmapsize . Up to + 1024 x 1024 supported. +- q3map_lightmapGamma sets the brightness scale of a lightmap +- q3map_lightmapsampleoffset to fix glitches in lightmapped terrain +- Tons more features and bugfixes. See the forum threads for details/screenshots +- Two new surfaceparms, "antiportal" and "skip," and associated shaders, for + allowing the mapper to more cleanly set up visibility data +- Lightmaps will always have square texels now (no more stretching) +- Vertex light improvements +- Light grid improvements +- q3map_lightrgb support for RTCW + + + + + + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_ase.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_ase.c new file mode 100644 index 00000000..56262311 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_ase.c @@ -0,0 +1,437 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define CONVERT_ASE_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +ConvertSurface() +converts a bsp drawsurface to an ase chunk +*/ + +int numLightmapsASE = 0; +static void ConvertSurface( FILE *f, bspModel_t *model, int modelNum, bspDrawSurface_t *ds, int surfaceNum, vec3_t origin ) +{ + int i, v, face, a, b, c; + bspDrawVert_t *dv; + vec3_t normal; + char name[ 1024 ]; + + + /* ignore patches for now */ + if( ds->surfaceType != MST_PLANAR && ds->surfaceType != MST_TRIANGLE_SOUP ) + return; + + /* print object header for each dsurf */ + sprintf( name, "mat%dmodel%dsurf%d", ds->shaderNum, modelNum, surfaceNum ); + fprintf( f, "*GEOMOBJECT\t{\r\n" ); + fprintf( f, "\t*NODE_NAME\t\"%s\"\r\n", name ); + fprintf( f, "\t*NODE_TM\t{\r\n" ); + fprintf( f, "\t\t*NODE_NAME\t\"%s\"\r\n", name ); + fprintf( f, "\t\t*INHERIT_POS\t0\t0\t0\r\n" ); + fprintf( f, "\t\t*INHERIT_ROT\t0\t0\t0\r\n" ); + fprintf( f, "\t\t*INHERIT_SCL\t0\t0\t0\r\n" ); + fprintf( f, "\t\t*TM_ROW0\t1.0\t0\t0\r\n" ); + fprintf( f, "\t\t*TM_ROW1\t0\t1.0\t0\r\n" ); + fprintf( f, "\t\t*TM_ROW2\t0\t0\t1.0\r\n" ); + fprintf( f, "\t\t*TM_ROW3\t0\t0\t0\r\n" ); + fprintf( f, "\t\t*TM_POS\t%f\t%f\t%f\r\n", origin[ 0 ], origin[ 1 ], origin[ 2 ] ); + fprintf( f, "\t}\r\n" ); + + /* print mesh header */ + fprintf( f, "\t*MESH\t{\r\n" ); + fprintf( f, "\t\t*TIMEVALUE\t0\r\n" ); + fprintf( f, "\t\t*MESH_NUMVERTEX\t%d\r\n", ds->numVerts ); + fprintf( f, "\t\t*MESH_NUMFACES\t%d\r\n", ds->numIndexes / 3 ); + switch( ds->surfaceType ) + { + case MST_PLANAR: + fprintf( f, "\t\t*COMMENT\t\"SURFACETYPE\tMST_PLANAR\"\r\n" ); + break; + case MST_TRIANGLE_SOUP: + fprintf( f, "\t\t*COMMENT\t\"SURFACETYPE\tMST_TRIANGLE_SOUP\"\r\n" ); + break; + } + + /* export vertex xyz */ + fprintf( f, "\t\t*MESH_VERTEX_LIST\t{\r\n" ); + for( i = 0; i < ds->numVerts; i++ ) + { + v = i + ds->firstVert; + dv = &bspDrawVerts[ v ]; + fprintf( f, "\t\t\t*MESH_VERTEX\t%d\t%f\t%f\t%f\r\n", i, dv->xyz[ 0 ], dv->xyz[ 1 ], dv->xyz[ 2 ] ); + } + fprintf( f, "\t\t}\r\n" ); + + /* export vertex normals */ + fprintf( f, "\t\t*MESH_NORMALS\t{\r\n" ); + for( i = 0; i < ds->numIndexes; i += 3 ) + { + face = (i / 3); + a = bspDrawIndexes[ i + ds->firstIndex ]; + b = bspDrawIndexes[ i + ds->firstIndex + 1 ]; + c = bspDrawIndexes[ i + ds->firstIndex + 2 ]; + VectorCopy( bspDrawVerts[ a ].normal, normal ); + VectorAdd( normal, bspDrawVerts[ b ].normal, normal ); + VectorAdd( normal, bspDrawVerts[ c ].normal, normal ); + if( VectorNormalize( normal, normal ) ) + fprintf( f, "\t\t\t*MESH_FACENORMAL\t%d\t%f\t%f\t%f\r\n", face, normal[ 0 ], normal[ 1 ], normal[ 2 ] ); + } + for( i = 0; i < ds->numVerts; i++ ) + { + v = i + ds->firstVert; + dv = &bspDrawVerts[ v ]; + fprintf( f, "\t\t\t*MESH_VERTEXNORMAL\t%d\t%f\t%f\t%f\r\n", i, dv->normal[ 0 ], dv->normal[ 1 ], dv->normal[ 2 ] ); + } + fprintf( f, "\t\t}\r\n" ); + + /* export faces */ + fprintf( f, "\t\t*MESH_FACE_LIST\t{\r\n" ); + for( i = 0; i < ds->numIndexes; i += 3 ) + { + face = (i / 3); + a = bspDrawIndexes[ i + ds->firstIndex ]; + c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; + b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; + fprintf( f, "\t\t\t*MESH_FACE\t%d\tA:\t%d\tB:\t%d\tC:\t%d\tAB:\t1\tBC:\t1\tCA:\t1\t*MESH_SMOOTHING\t0\t*MESH_MTLID\t0\r\n", + face, a, b, c ); + } + fprintf( f, "\t\t}\r\n" ); + + /* export vertex st */ + fprintf( f, "\t\t*MESH_NUMTVERTEX\t%d\r\n", ds->numVerts ); + fprintf( f, "\t\t*MESH_TVERTLIST\t{\r\n" ); + for( i = 0; i < ds->numVerts; i++ ) + { + v = i + ds->firstVert; + dv = &bspDrawVerts[ v ]; + fprintf( f, "\t\t\t*MESH_TVERT\t%d\t%f\t%f\t%f\r\n", i, dv->st[ 0 ], (1.0 - dv->st[ 1 ]), 1.0f ); + } + fprintf( f, "\t\t}\r\n" ); + + /* export texture faces */ + fprintf( f, "\t\t*MESH_NUMTVFACES\t%d\r\n", ds->numIndexes / 3 ); + fprintf( f, "\t\t*MESH_TFACELIST\t{\r\n" ); + for( i = 0; i < ds->numIndexes; i += 3 ) + { + face = (i / 3); + a = bspDrawIndexes[ i + ds->firstIndex ]; + c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; + b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; + fprintf( f, "\t\t\t*MESH_TFACE\t%d\t%d\t%d\t%d\r\n", face, a, b, c ); + } + fprintf( f, "\t\t}\r\n" ); + + /* print mesh footer */ + fprintf( f, "\t}\r\n" ); + + /* print object footer */ + fprintf( f, "\t*PROP_MOTIONBLUR\t0\r\n" ); + fprintf( f, "\t*PROP_CASTSHADOW\t1\r\n" ); + fprintf( f, "\t*PROP_RECVSHADOW\t1\r\n" ); + if(lightmapsAsTexcoord) + { + if(ds->lightmapNum[0] >= 0 && ds->lightmapNum[0] + deluxemap < numLightmapsASE) + fprintf( f, "\t*MATERIAL_REF\t%d\r\n", ds->lightmapNum[0] + deluxemap ); + else + Sys_Printf( "WARNING: lightmap %d out of range, not exporting\n", ds->lightmapNum[0] + deluxemap ); + } + else + fprintf( f, "\t*MATERIAL_REF\t%d\r\n", ds->shaderNum ); + fprintf( f, "}\r\n" ); +} + + + +/* +ConvertModel() +exports a bsp model to an ase chunk +*/ + +static void ConvertModel( FILE *f, bspModel_t *model, int modelNum, vec3_t origin ) +{ + int i, s; + bspDrawSurface_t *ds; + + + /* go through each drawsurf in the model */ + for( i = 0; i < model->numBSPSurfaces; i++ ) + { + s = i + model->firstBSPSurface; + ds = &bspDrawSurfaces[ s ]; + ConvertSurface( f, model, modelNum, ds, s, origin ); + } +} + + + +/* +ConvertShader() +exports a bsp shader to an ase chunk +*/ + +/* + *MATERIAL 0 { + *MATERIAL_NAME "models/test/rock16l" + *MATERIAL_CLASS "Standard" + *MATERIAL_AMBIENT 0.5882 0.5882 0.5882 + *MATERIAL_DIFFUSE 0.5882 0.5882 0.5882 + *MATERIAL_SPECULAR 0.5882 0.5882 0.5882 + *MATERIAL_SHINE 0.0000 + *MATERIAL_SHINESTRENGTH 0.0000 + *MATERIAL_TRANSPARENCY 0.0000 + *MATERIAL_WIRESIZE 1.0000 + *MATERIAL_SHADING Phong + *MATERIAL_XP_FALLOFF 0.0000 + *MATERIAL_SELFILLUM 0.0000 + *MATERIAL_FALLOFF In + *MATERIAL_XP_TYPE Filter + *MAP_DIFFUSE { + *MAP_NAME "Map #2" + *MAP_CLASS "Bitmap" + *MAP_SUBNO 1 + *MAP_AMOUNT 1.0000 + *BITMAP "models/test/rock16l" + *MAP_TYPE Screen + *UVW_U_OFFSET 0.0000 + *UVW_V_OFFSET 0.0000 + *UVW_U_TILING 1.0000 + *UVW_V_TILING 1.0000 + *UVW_ANGLE 0.0000 + *UVW_BLUR 1.0000 + *UVW_BLUR_OFFSET 0.0000 + *UVW_NOUSE_AMT 1.0000 + *UVW_NOISE_SIZE 1.0000 + *UVW_NOISE_LEVEL 1 + *UVW_NOISE_PHASE 0.0000 + *BITMAP_FILTER Pyramidal + } + } +*/ + +static void ConvertShader( FILE *f, bspShader_t *shader, int shaderNum ) +{ + shaderInfo_t *si; + char *c, filename[ 1024 ]; + + + /* get shader */ + si = ShaderInfoForShader( shader->shader ); + if( si == NULL ) + { + Sys_Printf( "WARNING: NULL shader in BSP\n" ); + return; + } + + /* set bitmap filename */ + if( si->shaderImage->filename[ 0 ] != '*' ) + strcpy( filename, si->shaderImage->filename ); + else + sprintf( filename, "%s.tga", si->shader ); + for( c = filename; *c != '\0'; c++ ) + if( *c == '/' ) + *c = '\\'; + + /* print shader info */ + fprintf( f, "\t*MATERIAL\t%d\t{\r\n", shaderNum ); + fprintf( f, "\t\t*MATERIAL_NAME\t\"%s\"\r\n", shader->shader ); + fprintf( f, "\t\t*MATERIAL_CLASS\t\"Standard\"\r\n" ); + fprintf( f, "\t\t*MATERIAL_DIFFUSE\t%f\t%f\t%f\r\n", si->color[ 0 ], si->color[ 1 ], si->color[ 2 ] ); + fprintf( f, "\t\t*MATERIAL_SHADING Phong\r\n" ); + + /* print map info */ + fprintf( f, "\t\t*MAP_DIFFUSE\t{\r\n" ); + fprintf( f, "\t\t\t*MAP_NAME\t\"%s\"\r\n", shader->shader ); + fprintf( f, "\t\t\t*MAP_CLASS\t\"Bitmap\"\r\n"); + fprintf( f, "\t\t\t*MAP_SUBNO\t1\r\n" ); + fprintf( f, "\t\t\t*MAP_AMOUNT\t1.0\r\n" ); + fprintf( f, "\t\t\t*MAP_TYPE\tScreen\r\n" ); + if(shadersAsBitmap) + fprintf( f, "\t\t\t*BITMAP\t\"%s\"\r\n", shader->shader ); + else + fprintf( f, "\t\t\t*BITMAP\t\"..\\%s\"\r\n", filename ); + fprintf( f, "\t\t\t*BITMAP_FILTER\tPyramidal\r\n" ); + fprintf( f, "\t\t}\r\n" ); + + fprintf( f, "\t}\r\n" ); +} +static void ConvertLightmap( FILE *f, const char *base, int lightmapNum ) +{ + /* print shader info */ + fprintf( f, "\t*MATERIAL\t%d\t{\r\n", lightmapNum ); + fprintf( f, "\t\t*MATERIAL_NAME\t\"lm_%04d\"\r\n", lightmapNum ); + fprintf( f, "\t\t*MATERIAL_CLASS\t\"Standard\"\r\n" ); + fprintf( f, "\t\t*MATERIAL_DIFFUSE\t1\t1\t1\r\n"); + fprintf( f, "\t\t*MATERIAL_SHADING Phong\r\n" ); + + /* print map info */ + if(lightmapNum >= 0) + { + fprintf( f, "\t\t*MAP_DIFFUSE\t{\r\n" ); + fprintf( f, "\t\t\t*MAP_NAME\t\"lm_%04d\"\r\n", lightmapNum ); + fprintf( f, "\t\t\t*MAP_CLASS\t\"Bitmap\"\r\n"); + fprintf( f, "\t\t\t*MAP_SUBNO\t1\r\n" ); + fprintf( f, "\t\t\t*MAP_AMOUNT\t1.0\r\n" ); + fprintf( f, "\t\t\t*MAP_TYPE\tScreen\r\n" ); + fprintf( f, "\t\t\t*BITMAP\t\"%s\\lm_%04d.tga\"\r\n", base, lightmapNum ); + fprintf( f, "\t\t\t*BITMAP_FILTER\tPyramidal\r\n" ); + fprintf( f, "\t\t}\r\n" ); + } + + fprintf( f, "\t}\r\n" ); +} + + + +/* +ConvertBSPToASE() +exports an 3d studio ase file from the bsp +*/ + +int ConvertBSPToASE( char *bspName ) +{ + int i, modelNum; + FILE *f; + bspShader_t *shader; + bspModel_t *model; + entity_t *e; + vec3_t origin; + const char *key; + char name[ 1024 ], base[ 1024 ], dirname[ 1024 ]; + + + /* note it */ + Sys_Printf( "--- Convert BSP to ASE ---\n" ); + + /* create the ase filename from the bsp name */ + strcpy( dirname, bspName ); + StripExtension( dirname ); + strcpy( name, bspName ); + StripExtension( name ); + strcat( name, ".ase" ); + Sys_Printf( "writing %s\n", name ); + + ExtractFileBase( bspName, base ); + + /* open it */ + f = fopen( name, "wb" ); + if( f == NULL ) + Error( "Open failed on %s\n", name ); + + /* print header */ + fprintf( f, "*3DSMAX_ASCIIEXPORT\t200\r\n" ); + fprintf( f, "*COMMENT\t\"Generated by Q3Map2 (ydnar) -convert -format ase\"\r\n" ); + fprintf( f, "*SCENE\t{\r\n" ); + fprintf( f, "\t*SCENE_FILENAME\t\"%s.bsp\"\r\n", base ); + fprintf( f, "\t*SCENE_FIRSTFRAME\t0\r\n" ); + fprintf( f, "\t*SCENE_LASTFRAME\t100\r\n" ); + fprintf( f, "\t*SCENE_FRAMESPEED\t30\r\n" ); + fprintf( f, "\t*SCENE_TICKSPERFRAME\t160\r\n" ); + fprintf( f, "\t*SCENE_BACKGROUND_STATIC\t0.0000\t0.0000\t0.0000\r\n" ); + fprintf( f, "\t*SCENE_AMBIENT_STATIC\t0.0000\t0.0000\t0.0000\r\n" ); + fprintf( f, "}\r\n" ); + + /* print materials */ + fprintf( f, "*MATERIAL_LIST\t{\r\n" ); + if(lightmapsAsTexcoord) + { + int lightmapCount; + for( lightmapCount = 0; lightmapCount < numBSPLightmaps; lightmapCount++ ) + ; + for( ; ; lightmapCount++ ) + { + char buf[1024]; + FILE *tmp; + snprintf(buf, sizeof(buf), "%s/lm_%04d.tga", dirname, lightmapCount); + buf[sizeof(buf) - 1] = 0; + tmp = fopen(buf, "rb"); + if(!tmp) + break; + fclose(tmp); + } + fprintf( f, "\t*MATERIAL_COUNT\t%d\r\n", lightmapCount ); + for( i = 0; i < lightmapCount; i++ ) + ConvertLightmap( f, base, i ); + numLightmapsASE = lightmapCount; + } + else + { + fprintf( f, "\t*MATERIAL_COUNT\t%d\r\n", numBSPShaders ); + for( i = 0; i < numBSPShaders; i++ ) + { + shader = &bspShaders[ i ]; + ConvertShader( f, shader, i ); + } + } + fprintf( f, "}\r\n" ); + + /* walk entity list */ + for( i = 0; i < numEntities; i++ ) + { + /* get entity and model */ + e = &entities[ i ]; + if( i == 0 ) + modelNum = 0; + else + { + key = ValueForKey( e, "model" ); + if( key[ 0 ] != '*' ) + continue; + modelNum = atoi( key + 1 ); + } + model = &bspModels[ modelNum ]; + + /* get entity origin */ + key = ValueForKey( e, "origin" ); + if( key[ 0 ] == '\0' ) + VectorClear( origin ); + else + GetVectorForKey( e, "origin", origin ); + + /* convert model */ + ConvertModel( f, model, modelNum, origin ); + } + + /* close the file and return */ + fclose( f ); + + /* return to sender */ + return 0; +} + + + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_map.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_map.c new file mode 100644 index 00000000..0f37665d --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_map.c @@ -0,0 +1,860 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define CONVERT_MAP_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +ConvertBrush() +exports a map brush +*/ + +#define SNAP_FLOAT_TO_INT 4 +#define SNAP_INT_TO_FLOAT (1.0 / SNAP_FLOAT_TO_INT) + +typedef vec_t vec2_t[2]; + +static vec_t Det3x3(vec_t a00, vec_t a01, vec_t a02, + vec_t a10, vec_t a11, vec_t a12, + vec_t a20, vec_t a21, vec_t a22) +{ + return + a00 * (a11 * a22 - a12 * a21) + - a01 * (a10 * a22 - a12 * a20) + + a02 * (a10 * a21 - a11 * a20); +} + +void GetBestSurfaceTriangleMatchForBrushside(side_t *buildSide, bspDrawVert_t *bestVert[3]) +{ + bspDrawSurface_t *s; + int i; + int t; + vec_t best = 0; + vec_t thisarea; + vec3_t normdiff; + vec3_t v1v0, v2v0, norm; + bspDrawVert_t *vert[3]; + winding_t *polygon; + plane_t *buildPlane = &mapplanes[buildSide->planenum]; + int matches = 0; + + // first, start out with NULLs + bestVert[0] = bestVert[1] = bestVert[2] = NULL; + + // brute force through all surfaces + for(s = bspDrawSurfaces; s != bspDrawSurfaces + numBSPDrawSurfaces; ++s) + { + if(s->surfaceType != MST_PLANAR && s->surfaceType != MST_TRIANGLE_SOUP) + continue; + if(strcmp(buildSide->shaderInfo->shader, bspShaders[s->shaderNum].shader)) + continue; + for(t = 0; t + 3 <= s->numIndexes; t += 3) + { + vert[0] = &bspDrawVerts[s->firstVert + bspDrawIndexes[s->firstIndex + t + 0]]; + vert[1] = &bspDrawVerts[s->firstVert + bspDrawIndexes[s->firstIndex + t + 1]]; + vert[2] = &bspDrawVerts[s->firstVert + bspDrawIndexes[s->firstIndex + t + 2]]; + if(s->surfaceType == MST_PLANAR && VectorCompare(vert[0]->normal, vert[1]->normal) && VectorCompare(vert[1]->normal, vert[2]->normal)) + { + VectorSubtract(vert[0]->normal, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; + VectorSubtract(vert[1]->normal, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; + VectorSubtract(vert[2]->normal, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; + } + else + { + // this is more prone to roundoff errors, but with embedded + // models, there is no better way + VectorSubtract(vert[1]->xyz, vert[0]->xyz, v1v0); + VectorSubtract(vert[2]->xyz, vert[0]->xyz, v2v0); + CrossProduct(v2v0, v1v0, norm); + VectorNormalize(norm, norm); + VectorSubtract(norm, buildPlane->normal, normdiff); if(VectorLength(normdiff) >= normalEpsilon) continue; + } + if(abs(DotProduct(vert[0]->xyz, buildPlane->normal) - buildPlane->dist) >= distanceEpsilon) continue; + if(abs(DotProduct(vert[1]->xyz, buildPlane->normal) - buildPlane->dist) >= distanceEpsilon) continue; + if(abs(DotProduct(vert[2]->xyz, buildPlane->normal) - buildPlane->dist) >= distanceEpsilon) continue; + // Okay. Correct surface type, correct shader, correct plane. Let's start with the business... + polygon = CopyWinding(buildSide->winding); + for(i = 0; i < 3; ++i) + { + // 0: 1, 2 + // 1: 2, 0 + // 2; 0, 1 + vec3_t *v1 = &vert[(i+1)%3]->xyz; + vec3_t *v2 = &vert[(i+2)%3]->xyz; + vec3_t triNormal; + vec_t triDist; + vec3_t sideDirection; + // we now need to generate triNormal and triDist so that they represent the plane spanned by normal and (v2 - v1). + VectorSubtract(*v2, *v1, sideDirection); + CrossProduct(sideDirection, buildPlane->normal, triNormal); + triDist = DotProduct(*v1, triNormal); + ChopWindingInPlace(&polygon, triNormal, triDist, distanceEpsilon); + if(!polygon) + goto exwinding; + } + thisarea = WindingArea(polygon); + if(thisarea > 0) + ++matches; + if(thisarea > best) + { + best = thisarea; + bestVert[0] = vert[0]; + bestVert[1] = vert[1]; + bestVert[2] = vert[2]; + } + FreeWinding(polygon); +exwinding: + ; + } + } + //if(strncmp(buildSide->shaderInfo->shader, "textures/common/", 16)) + // fprintf(stderr, "brushside with %s: %d matches (%f area)\n", buildSide->shaderInfo->shader, matches, best); +} + +#define FRAC(x) ((x) - floor(x)) +static void ConvertOriginBrush( FILE *f, int num, vec3_t origin, qboolean brushPrimitives ) +{ + int originSize = 256; + + char pattern[6][7][3] = { + { "+++", "+-+", "-++", "- ", " + ", " - ", "- " }, + { "+++", "-++", "++-", "- ", " +", "+ ", " +" }, + { "+++", "++-", "+-+", " - ", " +", " - ", " +" }, + { "---", "+--", "-+-", "- ", " + ", " - ", "+ " }, + { "---", "--+", "+--", "- ", " +", "- ", " +" }, + { "---", "-+-", "--+", " - ", " +", " + ", " +" } + }; + int i; +#define S(a,b,c) (pattern[a][b][c] == '+' ? +1 : pattern[a][b][c] == '-' ? -1 : 0) + + /* start brush */ + fprintf( f, "\t// brush %d\n", num ); + fprintf( f, "\t{\n" ); + if(brushPrimitives) + { + fprintf( f, "\tbrushDef\n" ); + fprintf( f, "\t{\n" ); + } + /* print brush side */ + /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ + + for(i = 0; i < 6; ++i) + { + if(brushPrimitives) + { + fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", + origin[0] + 8 * S(i,0,0), origin[1] + 8 * S(i,0,1), origin[2] + 8 * S(i,0,2), + origin[0] + 8 * S(i,1,0), origin[1] + 8 * S(i,1,1), origin[2] + 8 * S(i,1,2), + origin[0] + 8 * S(i,2,0), origin[1] + 8 * S(i,2,1), origin[2] + 8 * S(i,2,2), + 1.0f/16.0f, 0.0f, FRAC((S(i,5,0) * origin[0] + S(i,5,1) * origin[1] + S(i,5,2) * origin[2]) / 16.0 + 0.5), + 0.0f, 1.0f/16.0f, FRAC((S(i,6,0) * origin[0] + S(i,6,1) * origin[1] + S(i,6,2) * origin[2]) / 16.0 + 0.5), + "common/origin", + 0 + ); + } + else + { + fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", + origin[0] + 8 * S(i,0,0), origin[1] + 8 * S(i,0,1), origin[2] + 8 * S(i,0,2), + origin[0] + 8 * S(i,1,0), origin[1] + 8 * S(i,1,1), origin[2] + 8 * S(i,1,2), + origin[0] + 8 * S(i,2,0), origin[1] + 8 * S(i,2,1), origin[2] + 8 * S(i,2,2), + "common/origin", + FRAC((S(i,3,0) * origin[0] + S(i,3,1) * origin[1] + S(i,3,2) * origin[2]) / 16.0 + 0.5) * originSize, + FRAC((S(i,4,0) * origin[0] + S(i,4,1) * origin[1] + S(i,4,2) * origin[2]) / 16.0 + 0.5) * originSize, + 0.0f, 16.0 / originSize, 16.0 / originSize, + 0 + ); + } + } +#undef S + + /* end brush */ + if(brushPrimitives) + fprintf( f, "\t}\n" ); + fprintf( f, "\t}\n\n" ); +} + +static void ConvertBrush( FILE *f, int num, bspBrush_t *brush, vec3_t origin, qboolean brushPrimitives ) +{ + int i, j; + bspBrushSide_t *side; + side_t *buildSide; + bspShader_t *shader; + char *texture; + bspPlane_t *plane; + plane_t *buildPlane; + vec3_t pts[ 3 ]; + bspDrawVert_t *vert[3]; + int valid; + + + /* start brush */ + fprintf( f, "\t// brush %d\n", num ); + fprintf( f, "\t{\n" ); + if(brushPrimitives) + { + fprintf( f, "\tbrushDef\n" ); + fprintf( f, "\t{\n" ); + } + + /* clear out build brush */ + for( i = 0; i < buildBrush->numsides; i++ ) + { + buildSide = &buildBrush->sides[ i ]; + if( buildSide->winding != NULL ) + { + FreeWinding( buildSide->winding ); + buildSide->winding = NULL; + } + } + buildBrush->numsides = 0; + + /* iterate through bsp brush sides */ + for( i = 0; i < brush->numSides; i++ ) + { + /* get side */ + side = &bspBrushSides[ brush->firstSide + i ]; + + /* get shader */ + if( side->shaderNum < 0 || side->shaderNum >= numBSPShaders ) + continue; + shader = &bspShaders[ side->shaderNum ]; + //if( !Q_stricmp( shader->shader, "default" ) || !Q_stricmp( shader->shader, "noshader" ) ) + // continue; + + /* get plane */ + plane = &bspPlanes[ side->planeNum ]; + + /* add build side */ + buildSide = &buildBrush->sides[ buildBrush->numsides ]; + buildBrush->numsides++; + + /* tag it */ + buildSide->shaderInfo = ShaderInfoForShader( shader->shader ); + buildSide->planenum = side->planeNum; + buildSide->winding = NULL; + } + + /* make brush windings */ + if( !CreateBrushWindings( buildBrush ) ) + { + Sys_Printf( "CreateBrushWindings failed\n" ); + return; + } + + /* iterate through build brush sides */ + for( i = 0; i < buildBrush->numsides; i++ ) + { + /* get build side */ + buildSide = &buildBrush->sides[ i ]; + + /* get plane */ + buildPlane = &mapplanes[ buildSide->planenum ]; + + /* dummy check */ + if( buildSide->shaderInfo == NULL || buildSide->winding == NULL ) + continue; + + // st-texcoords -> texMat block + // start out with dummy + VectorSet(buildSide->texMat[0], 1/32.0, 0, 0); + VectorSet(buildSide->texMat[1], 0, 1/32.0, 0); + + // find surface for this side (by brute force) + // surface format: + // - meshverts point in pairs of three into verts + // - (triangles) + // - find the triangle that has most in common with our side + GetBestSurfaceTriangleMatchForBrushside(buildSide, vert); + valid = 0; + + /* get texture name */ + if( !Q_strncasecmp( buildSide->shaderInfo->shader, "textures/", 9 ) ) + texture = buildSide->shaderInfo->shader + 9; + else + texture = buildSide->shaderInfo->shader; + + /* get plane points and offset by origin */ + for( j = 0; j < 3; j++ ) + { + VectorAdd( buildSide->winding->p[ j ], origin, pts[ j ] ); + //% pts[ j ][ 0 ] = SNAP_INT_TO_FLOAT * floor( pts[ j ][ 0 ] * SNAP_FLOAT_TO_INT + 0.5f ); + //% pts[ j ][ 1 ] = SNAP_INT_TO_FLOAT * floor( pts[ j ][ 1 ] * SNAP_FLOAT_TO_INT + 0.5f ); + //% pts[ j ][ 2 ] = SNAP_INT_TO_FLOAT * floor( pts[ j ][ 2 ] * SNAP_FLOAT_TO_INT + 0.5f ); + } + + if(vert[0] && vert[1] && vert[2]) + { + if(brushPrimitives) + { + int i; + vec3_t texX, texY; + vec2_t xyI, xyJ, xyK; + vec2_t stI, stJ, stK; + vec_t D, D0, D1, D2; + + ComputeAxisBase(buildPlane->normal, texX, texY); + + xyI[0] = DotProduct(vert[0]->xyz, texX); + xyI[1] = DotProduct(vert[0]->xyz, texY); + xyJ[0] = DotProduct(vert[1]->xyz, texX); + xyJ[1] = DotProduct(vert[1]->xyz, texY); + xyK[0] = DotProduct(vert[2]->xyz, texX); + xyK[1] = DotProduct(vert[2]->xyz, texY); + stI[0] = vert[0]->st[0]; stI[1] = vert[0]->st[1]; + stJ[0] = vert[1]->st[0]; stJ[1] = vert[1]->st[1]; + stK[0] = vert[2]->st[0]; stK[1] = vert[2]->st[1]; + + // - solve linear equations: + // - (x, y) := xyz . (texX, texY) + // - st[i] = texMat[i][0]*x + texMat[i][1]*y + texMat[i][2] + // (for three vertices) + D = Det3x3( + xyI[0], xyI[1], 1, + xyJ[0], xyJ[1], 1, + xyK[0], xyK[1], 1 + ); + if(D != 0) + { + for(i = 0; i < 2; ++i) + { + D0 = Det3x3( + stI[i], xyI[1], 1, + stJ[i], xyJ[1], 1, + stK[i], xyK[1], 1 + ); + D1 = Det3x3( + xyI[0], stI[i], 1, + xyJ[0], stJ[i], 1, + xyK[0], stK[i], 1 + ); + D2 = Det3x3( + xyI[0], xyI[1], stI[i], + xyJ[0], xyJ[1], stJ[i], + xyK[0], xyK[1], stK[i] + ); + VectorSet(buildSide->texMat[i], D0 / D, D1 / D, D2 / D); + } + valid = 1; + } + else + fprintf(stderr, "degenerate triangle found when solving texMat equations for\n(%f %f %f) (%f %f %f) (%f %f %f)\n( %f %f %f )\n( %f %f %f ) -> ( %f %f )\n( %f %f %f ) -> ( %f %f )\n( %f %f %f ) -> ( %f %f )\n", + buildPlane->normal[0], buildPlane->normal[1], buildPlane->normal[2], + vert[0]->normal[0], vert[0]->normal[1], vert[0]->normal[2], + texX[0], texX[1], texX[2], texY[0], texY[1], texY[2], + vert[0]->xyz[0], vert[0]->xyz[1], vert[0]->xyz[2], xyI[0], xyI[1], + vert[1]->xyz[0], vert[1]->xyz[1], vert[1]->xyz[2], xyJ[0], xyJ[1], + vert[2]->xyz[0], vert[2]->xyz[1], vert[2]->xyz[2], xyK[0], xyK[1] + ); + + /* print brush side */ + /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ + fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + buildSide->texMat[0][0], buildSide->texMat[0][1], FRAC(buildSide->texMat[0][2]), + buildSide->texMat[1][0], buildSide->texMat[1][1], FRAC(buildSide->texMat[1][2]), + texture, + // DEBUG: valid ? 0 : C_DETAIL + 0 + ); + } + else + { + // invert QuakeTextureVecs + int i; + vec3_t vecs[2]; + int sv, tv; + vec2_t stI, stJ, stK; + vec3_t sts[2]; + vec2_t shift, scale; + vec_t rotate; + vec_t D, D0, D1, D2; + + TextureAxisFromPlane(buildPlane, vecs[0], vecs[1]); + if (vecs[0][0]) + sv = 0; + else if (vecs[0][1]) + sv = 1; + else + sv = 2; + if (vecs[1][0]) + tv = 0; + else if (vecs[1][1]) + tv = 1; + else + tv = 2; + + stI[0] = vert[0]->st[0] * buildSide->shaderInfo->shaderWidth; stI[1] = vert[0]->st[1] * buildSide->shaderInfo->shaderHeight; + stJ[0] = vert[1]->st[0] * buildSide->shaderInfo->shaderWidth; stJ[1] = vert[1]->st[1] * buildSide->shaderInfo->shaderHeight; + stK[0] = vert[2]->st[0] * buildSide->shaderInfo->shaderWidth; stK[1] = vert[2]->st[1] * buildSide->shaderInfo->shaderHeight; + + D = Det3x3( + vert[0]->xyz[sv], vert[0]->xyz[tv], 1, + vert[1]->xyz[sv], vert[1]->xyz[tv], 1, + vert[2]->xyz[sv], vert[2]->xyz[tv], 1 + ); + if(D != 0) + { + for(i = 0; i < 2; ++i) + { + D0 = Det3x3( + stI[i], vert[0]->xyz[tv], 1, + stJ[i], vert[1]->xyz[tv], 1, + stK[i], vert[2]->xyz[tv], 1 + ); + D1 = Det3x3( + vert[0]->xyz[sv], stI[i], 1, + vert[1]->xyz[sv], stJ[i], 1, + vert[2]->xyz[sv], stK[i], 1 + ); + D2 = Det3x3( + vert[0]->xyz[sv], vert[0]->xyz[tv], stI[i], + vert[1]->xyz[sv], vert[1]->xyz[tv], stJ[i], + vert[2]->xyz[sv], vert[2]->xyz[tv], stK[i] + ); + VectorSet(sts[i], D0 / D, D1 / D, D2 / D); + } + valid = 1; + } + else + fprintf(stderr, "degenerate triangle found when solving texDef equations\n"); // FIXME add stuff here + + // now we must solve: + // // now we must invert: + // ang = rotate / 180 * Q_PI; + // sinv = sin(ang); + // cosv = cos(ang); + // ns = cosv * vecs[0][sv]; + // nt = sinv * vecs[0][sv]; + // vecsrotscaled[0][sv] = ns / scale[0]; + // vecsrotscaled[0][tv] = nt / scale[0]; + // ns = -sinv * vecs[1][tv]; + // nt = cosv * vecs[1][tv]; + // vecsrotscaled[1][sv] = ns / scale[1]; + // vecsrotscaled[1][tv] = nt / scale[1]; + scale[0] = 1.0/sqrt(sts[0][0] * sts[0][0] + sts[0][1] * sts[0][1]); + scale[1] = 1.0/sqrt(sts[1][0] * sts[1][0] + sts[1][1] * sts[1][1]); + rotate = atan2(sts[0][1] * vecs[0][sv] - sts[1][0] * vecs[1][tv], sts[0][0] * vecs[0][sv] + sts[1][1] * vecs[1][tv]) * (180.0f / Q_PI); + shift[0] = buildSide->shaderInfo->shaderWidth * FRAC(sts[0][2] / buildSide->shaderInfo->shaderWidth); + shift[1] = buildSide->shaderInfo->shaderHeight * FRAC(sts[1][2] / buildSide->shaderInfo->shaderHeight); + + /* print brush side */ + /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ + fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + texture, + shift[0], shift[1], rotate, scale[0], scale[1], + // DEBUG: valid ? 0 : C_DETAIL + 0 + ); + } + } + else + { + vec3_t vecs[ 2 ]; + if(strncmp(buildSide->shaderInfo->shader, "textures/common/", 16)) + if(strcmp(buildSide->shaderInfo->shader, "noshader")) + if(strcmp(buildSide->shaderInfo->shader, "default")) + { + fprintf(stderr, "no matching triangle for brushside using %s (hopefully nobody can see this side anyway)\n", buildSide->shaderInfo->shader); + texture = "common/WTF"; + } + + MakeNormalVectors( buildPlane->normal, vecs[ 0 ], vecs[ 1 ] ); + VectorMA( vec3_origin, buildPlane->dist, buildPlane->normal, pts[ 0 ] ); + VectorMA( pts[ 0 ], 256.0f, vecs[ 0 ], pts[ 1 ] ); + VectorMA( pts[ 0 ], 256.0f, vecs[ 1 ], pts[ 2 ] ); + if(brushPrimitives) + { + fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( ( %.8f %.8f %.8f ) ( %.8f %.8f %.8f ) ) %s %d 0 0\n", + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + 1.0f/16.0f, 0.0f, 0.0f, + 0.0f, 1.0f/16.0f, 0.0f, + texture, + // DEBUG: valid ? 0 : C_DETAIL + 0 + ); + } + else + { + fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s %.8f %.8f %.8f %.8f %.8f %d 0 0\n", + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + texture, + 0.0f, 0.0f, 0.0f, 0.25f, 0.25f, + // DEBUG: valid ? 0 : C_DETAIL + 0 + ); + } + } + } + + /* end brush */ + if(brushPrimitives) + { + fprintf( f, "\t}\n" ); + } + fprintf( f, "\t}\n\n" ); +} +#undef FRAC + +#if 0 + /* iterate through the brush sides (ignore the first 6 bevel planes) */ + for( i = 0; i < brush->numSides; i++ ) + { + /* get side */ + side = &bspBrushSides[ brush->firstSide + i ]; + + /* get shader */ + if( side->shaderNum < 0 || side->shaderNum >= numBSPShaders ) + continue; + shader = &bspShaders[ side->shaderNum ]; + if( !Q_stricmp( shader->shader, "default" ) || !Q_stricmp( shader->shader, "noshader" ) ) + continue; + + /* get texture name */ + if( !Q_strncasecmp( shader->shader, "textures/", 9 ) ) + texture = shader->shader + 9; + else + texture = shader->shader; + + /* get plane */ + plane = &bspPlanes[ side->planeNum ]; + + /* make plane points */ + { + vec3_t vecs[ 2 ]; + + + MakeNormalVectors( plane->normal, vecs[ 0 ], vecs[ 1 ] ); + VectorMA( vec3_origin, plane->dist, plane->normal, pts[ 0 ] ); + VectorMA( pts[ 0 ], 256.0f, vecs[ 0 ], pts[ 1 ] ); + VectorMA( pts[ 0 ], 256.0f, vecs[ 1 ], pts[ 2 ] ); + } + + /* offset by origin */ + for( j = 0; j < 3; j++ ) + VectorAdd( pts[ j ], origin, pts[ j ] ); + + /* print brush side */ + /* ( 640 24 -224 ) ( 448 24 -224 ) ( 448 -232 -224 ) common/caulk 0 48 0 0.500000 0.500000 0 0 0 */ + fprintf( f, "\t\t( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) ( %.3f %.3f %.3f ) %s 0 0 0 0.5 0.5 0 0 0\n", + pts[ 0 ][ 0 ], pts[ 0 ][ 1 ], pts[ 0 ][ 2 ], + pts[ 1 ][ 0 ], pts[ 1 ][ 1 ], pts[ 1 ][ 2 ], + pts[ 2 ][ 0 ], pts[ 2 ][ 1 ], pts[ 2 ][ 2 ], + texture ); + } +#endif + + + +/* +ConvertPatch() +converts a bsp patch to a map patch + + { + patchDef2 + { + base_wall/concrete + ( 9 3 0 0 0 ) + ( + ( ( 168 168 -192 0 2 ) ( 168 168 -64 0 1 ) ( 168 168 64 0 0 ) ... ) + ... + ) + } + } + +*/ + +static void ConvertPatch( FILE *f, int num, bspDrawSurface_t *ds, vec3_t origin ) +{ + int x, y; + bspShader_t *shader; + char *texture; + bspDrawVert_t *dv; + vec3_t xyz; + + + /* only patches */ + if( ds->surfaceType != MST_PATCH ) + return; + + /* get shader */ + if( ds->shaderNum < 0 || ds->shaderNum >= numBSPShaders ) + return; + shader = &bspShaders[ ds->shaderNum ]; + + /* get texture name */ + if( !Q_strncasecmp( shader->shader, "textures/", 9 ) ) + texture = shader->shader + 9; + else + texture = shader->shader; + + /* start patch */ + fprintf( f, "\t// patch %d\n", num ); + fprintf( f, "\t{\n" ); + fprintf( f, "\t\tpatchDef2\n" ); + fprintf( f, "\t\t{\n" ); + fprintf( f, "\t\t\t%s\n", texture ); + fprintf( f, "\t\t\t( %d %d 0 0 0 )\n", ds->patchWidth, ds->patchHeight ); + fprintf( f, "\t\t\t(\n" ); + + /* iterate through the verts */ + for( x = 0; x < ds->patchWidth; x++ ) + { + /* start row */ + fprintf( f, "\t\t\t\t(" ); + + /* iterate through the row */ + for( y = 0; y < ds->patchHeight; y++ ) + { + /* get vert */ + dv = &bspDrawVerts[ ds->firstVert + (y * ds->patchWidth) + x ]; + + /* offset it */ + VectorAdd( origin, dv->xyz, xyz ); + + /* print vertex */ + fprintf( f, " ( %f %f %f %f %f )", xyz[ 0 ], xyz[ 1 ], xyz[ 2 ], dv->st[ 0 ], dv->st[ 1 ] ); + } + + /* end row */ + fprintf( f, " )\n" ); + } + + /* end patch */ + fprintf( f, "\t\t\t)\n" ); + fprintf( f, "\t\t}\n" ); + fprintf( f, "\t}\n\n" ); +} + + + +/* +ConvertModel() +exports a bsp model to a map file +*/ + +static void ConvertModel( FILE *f, bspModel_t *model, int modelNum, vec3_t origin, qboolean brushPrimitives ) +{ + int i, num; + bspBrush_t *brush; + bspDrawSurface_t *ds; + + + /* convert bsp planes to map planes */ + nummapplanes = numBSPPlanes; + AUTOEXPAND_BY_REALLOC(mapplanes, nummapplanes, allocatedmapplanes, 1024); + for( i = 0; i < numBSPPlanes; i++ ) + { + VectorCopy( bspPlanes[ i ].normal, mapplanes[ i ].normal ); + mapplanes[ i ].dist = bspPlanes[ i ].dist; + mapplanes[ i ].type = PlaneTypeForNormal( mapplanes[ i ].normal ); + mapplanes[ i ].hash_chain = 0; + } + + /* allocate a build brush */ + buildBrush = AllocBrush( 512 ); + buildBrush->entityNum = 0; + buildBrush->original = buildBrush; + + if(origin[0] != 0 || origin[1] != 0 || origin[2] != 0) + ConvertOriginBrush(f, -1, origin, brushPrimitives); + + /* go through each brush in the model */ + for( i = 0; i < model->numBSPBrushes; i++ ) + { + num = i + model->firstBSPBrush; + brush = &bspBrushes[ num ]; + ConvertBrush( f, num, brush, origin, brushPrimitives ); + } + + /* free the build brush */ + free( buildBrush ); + + /* go through each drawsurf in the model */ + for( i = 0; i < model->numBSPSurfaces; i++ ) + { + num = i + model->firstBSPSurface; + ds = &bspDrawSurfaces[ num ]; + + /* we only love patches */ + if( ds->surfaceType == MST_PATCH ) + ConvertPatch( f, num, ds, origin ); + } +} + + + +/* +ConvertEPairs() +exports entity key/value pairs to a map file +*/ + +static void ConvertEPairs( FILE *f, entity_t *e, qboolean skip_origin ) +{ + epair_t *ep; + + + /* walk epairs */ + for( ep = e->epairs; ep != NULL; ep = ep->next ) + { + /* ignore empty keys/values */ + if( ep->key[ 0 ] == '\0' || ep->value[ 0 ] == '\0' ) + continue; + + /* ignore model keys with * prefixed values */ + if( !Q_stricmp( ep->key, "model" ) && ep->value[ 0 ] == '*' ) + continue; + + /* ignore origin keys if skip_origin is set */ + if( skip_origin && !Q_stricmp( ep->key, "origin" ) ) + continue; + + /* emit the epair */ + fprintf( f, "\t\"%s\" \"%s\"\n", ep->key, ep->value ); + } +} + + + +/* +ConvertBSPToMap() +exports an quake map file from the bsp +*/ + +int ConvertBSPToMap_Ext( char *bspName, qboolean brushPrimitives ) +{ + int i, modelNum; + FILE *f; + bspModel_t *model; + entity_t *e; + vec3_t origin; + const char *value; + char name[ 1024 ], base[ 1024 ]; + + + /* note it */ + Sys_Printf( "--- Convert BSP to MAP ---\n" ); + + /* create the bsp filename from the bsp name */ + strcpy( name, bspName ); + StripExtension( name ); + strcat( name, "_converted.map" ); + Sys_Printf( "writing %s\n", name ); + + ExtractFileBase( bspName, base ); + strcat( base, ".bsp" ); + + /* open it */ + f = fopen( name, "wb" ); + if( f == NULL ) + Error( "Open failed on %s\n", name ); + + /* print header */ + fprintf( f, "// Generated by Q3Map2 (ydnar) -convert -format map\n" ); + + /* walk entity list */ + for( i = 0; i < numEntities; i++ ) + { + /* get entity */ + e = &entities[ i ]; + + /* start entity */ + fprintf( f, "// entity %d\n", i ); + fprintf( f, "{\n" ); + + /* get model num */ + if( i == 0 ) + modelNum = 0; + else + { + value = ValueForKey( e, "model" ); + if( value[ 0 ] == '*' ) + modelNum = atoi( value + 1 ); + else + modelNum = -1; + } + + /* export keys */ + ConvertEPairs( f, e, modelNum >= 0 ); + fprintf( f, "\n" ); + + /* only handle bsp models */ + if( modelNum >= 0 ) + { + /* get model */ + model = &bspModels[ modelNum ]; + + /* get entity origin */ + value = ValueForKey( e, "origin" ); + if( value[ 0 ] == '\0' ) + VectorClear( origin ); + else + GetVectorForKey( e, "origin", origin ); + + /* convert model */ + ConvertModel( f, model, modelNum, origin, brushPrimitives ); + } + + /* end entity */ + fprintf( f, "}\n\n" ); + } + + /* close the file and return */ + fclose( f ); + + /* return to sender */ + return 0; +} + +int ConvertBSPToMap( char *bspName ) +{ + return ConvertBSPToMap_Ext(bspName, qfalse); +} + +int ConvertBSPToMap_BP( char *bspName ) +{ + return ConvertBSPToMap_Ext(bspName, qtrue); +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_obj.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_obj.c new file mode 100644 index 00000000..08e75e11 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/convert_obj.c @@ -0,0 +1,328 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define CONVERT_ASE_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +ConvertSurface() +converts a bsp drawsurface to an obj chunk +*/ + +int firstLightmap = 0; +int lastLightmap = -1; +static void ConvertLightmapToMTL( FILE *f, const char *base, int lightmapNum ); + +int objVertexCount = 0; +int objLastShaderNum = -1; +static void ConvertSurfaceToOBJ( FILE *f, bspModel_t *model, int modelNum, bspDrawSurface_t *ds, int surfaceNum, vec3_t origin ) +{ + int i, v, face, a, b, c; + bspDrawVert_t *dv; + + /* ignore patches for now */ + if( ds->surfaceType != MST_PLANAR && ds->surfaceType != MST_TRIANGLE_SOUP ) + return; + + fprintf(f, "g mat%dmodel%dsurf%d\r\n", ds->shaderNum, modelNum, surfaceNum); + switch( ds->surfaceType ) + { + case MST_PLANAR: + fprintf( f, "# SURFACETYPE MST_PLANAR\r\n" ); + break; + case MST_TRIANGLE_SOUP: + fprintf( f, "# SURFACETYPE MST_TRIANGLE_SOUP\r\n" ); + break; + } + + /* export shader */ + if(lightmapsAsTexcoord) + { + if(objLastShaderNum != ds->lightmapNum[0]) + { + fprintf(f, "usemtl lm_%04d\r\n", ds->lightmapNum[0] + deluxemap); + objLastShaderNum = ds->lightmapNum[0] + deluxemap; + } + if(ds->lightmapNum[0] + deluxemap < firstLightmap) + { + Sys_Printf( "WARNING: lightmap %d out of range (exporting anyway)\n", ds->lightmapNum[0] + deluxemap ); + firstLightmap = ds->lightmapNum[0] + deluxemap; + } + if(ds->lightmapNum[0] > lastLightmap) + { + Sys_Printf( "WARNING: lightmap %d out of range (exporting anyway)\n", ds->lightmapNum[0] + deluxemap ); + lastLightmap = ds->lightmapNum[0] + deluxemap; + } + } + else + { + if(objLastShaderNum != ds->shaderNum) + { + fprintf(f, "usemtl %s\r\n", bspShaders[ds->shaderNum].shader); + objLastShaderNum = ds->shaderNum; + } + } + + /* export vertex */ + for( i = 0; i < ds->numVerts; i++ ) + { + v = i + ds->firstVert; + dv = &bspDrawVerts[ v ]; + fprintf(f, "# vertex %d\r\n", i + objVertexCount + 1); + fprintf(f, "v %f %f %f\r\n", dv->xyz[ 0 ], dv->xyz[ 1 ], dv->xyz[ 2 ]); + fprintf(f, "vn %f %f %f\r\n", dv->normal[ 0 ], dv->normal[ 1 ], dv->normal[ 2 ]); + if(lightmapsAsTexcoord) + fprintf(f, "vt %f %f\r\n", dv->lightmap[0][0], 1.0 - dv->lightmap[0][1]); + else + fprintf(f, "vt %f %f\r\n", dv->st[ 0 ], 1.0 - dv->st[ 1 ]); + } + + /* export faces */ + for( i = 0; i < ds->numIndexes; i += 3 ) + { + face = (i / 3); + a = bspDrawIndexes[ i + ds->firstIndex ]; + c = bspDrawIndexes[ i + ds->firstIndex + 1 ]; + b = bspDrawIndexes[ i + ds->firstIndex + 2 ]; + fprintf(f, "f %d/%d/%d %d/%d/%d %d/%d/%d\r\n", + a + objVertexCount + 1, a + objVertexCount + 1, a + objVertexCount + 1, + b + objVertexCount + 1, b + objVertexCount + 1, b + objVertexCount + 1, + c + objVertexCount + 1, c + objVertexCount + 1, c + objVertexCount + 1 + ); + } + + objVertexCount += ds->numVerts; +} + + + +/* +ConvertModel() +exports a bsp model to an ase chunk +*/ + +static void ConvertModelToOBJ( FILE *f, bspModel_t *model, int modelNum, vec3_t origin ) +{ + int i, s; + bspDrawSurface_t *ds; + + + /* go through each drawsurf in the model */ + for( i = 0; i < model->numBSPSurfaces; i++ ) + { + s = i + model->firstBSPSurface; + ds = &bspDrawSurfaces[ s ]; + ConvertSurfaceToOBJ( f, model, modelNum, ds, s, origin ); + } +} + + + +/* +ConvertShader() +exports a bsp shader to an ase chunk +*/ + +static void ConvertShaderToMTL( FILE *f, bspShader_t *shader, int shaderNum ) +{ + shaderInfo_t *si; + char *c, filename[ 1024 ]; + + + /* get shader */ + si = ShaderInfoForShader( shader->shader ); + if( si == NULL ) + { + Sys_Printf( "WARNING: NULL shader in BSP\n" ); + return; + } + + /* set bitmap filename */ + if( si->shaderImage->filename[ 0 ] != '*' ) + strcpy( filename, si->shaderImage->filename ); + else + sprintf( filename, "%s.tga", si->shader ); + + /* blender hates this, so let's not do it + for( c = filename; *c != '\0'; c++ ) + if( *c == '/' ) + *c = '\\'; + */ + + /* print shader info */ + fprintf( f, "newmtl %s\r\n", shader->shader ); + fprintf( f, "Kd %f %f %f\r\n", si->color[ 0 ], si->color[ 1 ], si->color[ 2 ] ); + if(shadersAsBitmap) + fprintf( f, "map_Kd %s\r\n", shader->shader ); + else + /* blender hates this, so let's not do it + fprintf( f, "map_Kd ..\\%s\r\n", filename ); + */ + fprintf( f, "map_Kd ../%s\r\n", filename ); +} + +static void ConvertLightmapToMTL( FILE *f, const char *base, int lightmapNum ) +{ + /* print shader info */ + fprintf( f, "newmtl lm_%04d\r\n", lightmapNum ); + if(lightmapNum >= 0) + /* blender hates this, so let's not do it + fprintf( f, "map_Kd %s\\lm_%04d.tga\r\n", base, lightmapNum ); + */ + fprintf( f, "map_Kd %s/lm_%04d.tga\r\n", base, lightmapNum ); +} + + + +/* +ConvertBSPToASE() +exports an 3d studio ase file from the bsp +*/ + +int ConvertBSPToOBJ( char *bspName ) +{ + int i, modelNum; + FILE *f, *fmtl; + bspShader_t *shader; + bspModel_t *model; + entity_t *e; + vec3_t origin; + const char *key; + char name[ 1024 ], base[ 1024 ], mtlname[ 1024 ], dirname[ 1024 ]; + + + /* note it */ + Sys_Printf( "--- Convert BSP to OBJ ---\n" ); + + /* create the ase filename from the bsp name */ + strcpy( dirname, bspName ); + StripExtension( dirname ); + strcpy( name, bspName ); + StripExtension( name ); + strcat( name, ".obj" ); + Sys_Printf( "writing %s\n", name ); + strcpy( mtlname, bspName ); + StripExtension( mtlname ); + strcat( mtlname, ".mtl" ); + Sys_Printf( "writing %s\n", mtlname ); + + ExtractFileBase( bspName, base ); + + /* open it */ + f = fopen( name, "wb" ); + if( f == NULL ) + Error( "Open failed on %s\n", name ); + fmtl = fopen( mtlname, "wb" ); + if( fmtl == NULL ) + Error( "Open failed on %s\n", mtlname ); + + /* print header */ + fprintf( f, "o %s\r\n", base ); + fprintf( f, "# Generated by Q3Map2 (ydnar) -convert -format obj\r\n" ); + fprintf( f, "mtllib %s.mtl\r\n", base ); + + fprintf( fmtl, "# Generated by Q3Map2 (ydnar) -convert -format obj\r\n" ); + if(lightmapsAsTexcoord) + { + int lightmapCount; + for( lightmapCount = 0; lightmapCount < numBSPLightmaps; lightmapCount++ ) + ; + for( ; ; lightmapCount++ ) + { + char buf[1024]; + FILE *tmp; + snprintf(buf, sizeof(buf), "%s/lm_%04d.tga", dirname, lightmapCount); + buf[sizeof(buf) - 1] = 0; + tmp = fopen(buf, "rb"); + if(!tmp) + break; + fclose(tmp); + } + lastLightmap = lightmapCount - 1; + } + else + { + for( i = 0; i < numBSPShaders; i++ ) + { + shader = &bspShaders[ i ]; + ConvertShaderToMTL( fmtl, shader, i ); + } + } + + /* walk entity list */ + for( i = 0; i < numEntities; i++ ) + { + /* get entity and model */ + e = &entities[ i ]; + if( i == 0 ) + modelNum = 0; + else + { + key = ValueForKey( e, "model" ); + if( key[ 0 ] != '*' ) + continue; + modelNum = atoi( key + 1 ); + } + model = &bspModels[ modelNum ]; + + /* get entity origin */ + key = ValueForKey( e, "origin" ); + if( key[ 0 ] == '\0' ) + VectorClear( origin ); + else + GetVectorForKey( e, "origin", origin ); + + /* convert model */ + ConvertModelToOBJ( f, model, modelNum, origin ); + } + + if(lightmapsAsTexcoord) + { + for( i = firstLightmap; i <= lastLightmap; i++ ) + ConvertLightmapToMTL( fmtl, base, i ); + } + + /* close the file and return */ + fclose( f ); + fclose( fmtl ); + + /* return to sender */ + return 0; +} + + + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/decals.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/decals.c new file mode 100644 index 00000000..a130334f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/decals.c @@ -0,0 +1,906 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define DECALS_C + + + +/* dependencies */ +#include "q3map2.h" + + + +#define MAX_PROJECTORS 1024 + +typedef struct decalProjector_s +{ + shaderInfo_t *si; + vec3_t mins, maxs; + vec3_t center; + float radius, radius2; + int numPlanes; /* either 5 or 6, for quad or triangle projectors */ + vec4_t planes[ 6 ]; + vec4_t texMat[ 2 ]; +} +decalProjector_t; + +static int numProjectors = 0; +static decalProjector_t projectors[ MAX_PROJECTORS ]; + +static int numDecalSurfaces = 0; + +static vec3_t entityOrigin; + + + +/* +DVectorNormalize() +normalizes a vector, returns the length, operates using doubles +*/ + +typedef double dvec_t; +typedef dvec_t dvec3_t[ 3 ]; + +dvec_t DVectorNormalize( dvec3_t in, dvec3_t out ) +{ + dvec_t len, ilen; + + + len = (dvec_t) sqrt( in[ 0 ] * in[ 0 ] + in[ 1 ] * in[ 1 ] + in[ 2 ] * in[ 2 ] ); + if( len == 0.0 ) + { + VectorClear( out ); + return 0.0; + } + + ilen = 1.0 / len; + out[ 0 ] = in[ 0 ] * ilen; + out[ 1 ] = in[ 1 ] * ilen; + out[ 2 ] = in[ 2 ] * ilen; + + return len; +} + + + +/* +MakeTextureMatrix() +generates a texture projection matrix for a triangle +returns qfalse if a texture matrix cannot be created +*/ + +#define Vector2Subtract(a,b,c) ((c)[ 0 ] = (a)[ 0 ] - (b)[ 0 ], (c)[ 1 ] = (a)[ 1 ] - (b)[ 1 ]) + +static qboolean MakeTextureMatrix( decalProjector_t *dp, vec4_t projection, bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *c ) +{ + int i, j; + double bb, s, t, d; + dvec3_t pa, pb, pc; + dvec3_t bary, xyz; + dvec3_t vecs[ 3 ], axis[ 3 ], lengths; + + + /* project triangle onto plane of projection */ + d = DotProduct( a->xyz, projection ) - projection[ 3 ]; + VectorMA( a->xyz, -d, projection, pa ); + d = DotProduct( b->xyz, projection ) - projection[ 3 ]; + VectorMA( b->xyz, -d, projection, pb ); + d = DotProduct( c->xyz, projection ) - projection[ 3 ]; + VectorMA( c->xyz, -d, projection, pc ); + + /* two methods */ + #if 1 + { + /* old code */ + + /* calculate barycentric basis for the triangle */ + bb = (b->st[ 0 ] - a->st[ 0 ]) * (c->st[ 1 ] - a->st[ 1 ]) - (c->st[ 0 ] - a->st[ 0 ]) * (b->st[ 1 ] - a->st[ 1 ]); + if( fabs( bb ) < 0.00000001 ) + return qfalse; + + /* calculate texture origin */ + #if 0 + s = 0.0; + t = 0.0; + bary[ 0 ] = ((b->st[ 0 ] - s) * (c->st[ 1 ] - t) - (c->st[ 0 ] - s) * (b->st[ 1 ] - t)) / bb; + bary[ 1 ] = ((c->st[ 0 ] - s) * (a->st[ 1 ] - t) - (a->st[ 0 ] - s) * (c->st[ 1 ] - t)) / bb; + bary[ 2 ] = ((a->st[ 0 ] - s) * (b->st[ 1 ] - t) - (b->st[ 0 ] - s) * (a->st[ 1 ] - t)) / bb; + + origin[ 0 ] = bary[ 0 ] * pa[ 0 ] + bary[ 1 ] * pb[ 0 ] + bary[ 2 ] * pc[ 0 ]; + origin[ 1 ] = bary[ 0 ] * pa[ 1 ] + bary[ 1 ] * pb[ 1 ] + bary[ 2 ] * pc[ 1 ]; + origin[ 2 ] = bary[ 0 ] * pa[ 2 ] + bary[ 1 ] * pb[ 2 ] + bary[ 2 ] * pc[ 2 ]; + #endif + + /* calculate s vector */ + s = a->st[ 0 ] + 1.0; + t = a->st[ 1 ] + 0.0; + bary[ 0 ] = ((b->st[ 0 ] - s) * (c->st[ 1 ] - t) - (c->st[ 0 ] - s) * (b->st[ 1 ] - t)) / bb; + bary[ 1 ] = ((c->st[ 0 ] - s) * (a->st[ 1 ] - t) - (a->st[ 0 ] - s) * (c->st[ 1 ] - t)) / bb; + bary[ 2 ] = ((a->st[ 0 ] - s) * (b->st[ 1 ] - t) - (b->st[ 0 ] - s) * (a->st[ 1 ] - t)) / bb; + + xyz[ 0 ] = bary[ 0 ] * pa[ 0 ] + bary[ 1 ] * pb[ 0 ] + bary[ 2 ] * pc[ 0 ]; + xyz[ 1 ] = bary[ 0 ] * pa[ 1 ] + bary[ 1 ] * pb[ 1 ] + bary[ 2 ] * pc[ 1 ]; + xyz[ 2 ] = bary[ 0 ] * pa[ 2 ] + bary[ 1 ] * pb[ 2 ] + bary[ 2 ] * pc[ 2 ]; + + //% VectorSubtract( xyz, origin, vecs[ 0 ] ); + VectorSubtract( xyz, pa, vecs[ 0 ] ); + + /* calculate t vector */ + s = a->st[ 0 ] + 0.0; + t = a->st[ 1 ] + 1.0; + bary[ 0 ] = ((b->st[ 0 ] - s) * (c->st[ 1 ] - t) - (c->st[ 0 ] - s) * (b->st[ 1 ] - t)) / bb; + bary[ 1 ] = ((c->st[ 0 ] - s) * (a->st[ 1 ] - t) - (a->st[ 0 ] - s) * (c->st[ 1 ] - t)) / bb; + bary[ 2 ] = ((a->st[ 0 ] - s) * (b->st[ 1 ] - t) - (b->st[ 0 ] - s) * (a->st[ 1 ] - t)) / bb; + + xyz[ 0 ] = bary[ 0 ] * pa[ 0 ] + bary[ 1 ] * pb[ 0 ] + bary[ 2 ] * pc[ 0 ]; + xyz[ 1 ] = bary[ 0 ] * pa[ 1 ] + bary[ 1 ] * pb[ 1 ] + bary[ 2 ] * pc[ 1 ]; + xyz[ 2 ] = bary[ 0 ] * pa[ 2 ] + bary[ 1 ] * pb[ 2 ] + bary[ 2 ] * pc[ 2 ]; + + //% VectorSubtract( xyz, origin, vecs[ 1 ] ); + VectorSubtract( xyz, pa, vecs[ 1 ] ); + + /* calcuate r vector */ + VectorScale( projection, -1.0, vecs[ 2 ] ); + + /* calculate transform axis */ + for( i = 0; i < 3; i++ ) + lengths[ i ] = DVectorNormalize( vecs[ i ], axis[ i ] ); + for( i = 0; i < 2; i++ ) + for( j = 0; j < 3; j++ ) + dp->texMat[ i ][ j ] = lengths[ i ] > 0.0 ? (axis[ i ][ j ] / lengths[ i ]) : 0.0; + //% dp->texMat[ i ][ j ] = fabs( vecs[ i ][ j ] ) > 0.0 ? (1.0 / vecs[ i ][ j ]) : 0.0; + //% dp->texMat[ i ][ j ] = axis[ i ][ j ] > 0.0 ? (1.0 / axis[ i ][ j ]) : 0.0; + + /* calculalate translation component */ + dp->texMat[ 0 ][ 3 ] = a->st[ 0 ] - DotProduct( a->xyz, dp->texMat[ 0 ] ); + dp->texMat[ 1 ][ 3 ] = a->st[ 1 ] - DotProduct( a->xyz, dp->texMat[ 1 ] ); + } + #else + { + int k; + dvec3_t origin, deltas[ 3 ]; + double texDeltas[ 3 ][ 2 ]; + double delta, texDelta; + + + /* new code */ + + /* calculate deltas */ + VectorSubtract( pa, pb, deltas[ 0 ] ); + VectorSubtract( pa, pc, deltas[ 1 ] ); + VectorSubtract( pb, pc, deltas[ 2 ] ); + Vector2Subtract( a->st, b->st, texDeltas[ 0 ] ); + Vector2Subtract( a->st, c->st, texDeltas[ 1 ] ); + Vector2Subtract( b->st, c->st, texDeltas[ 2 ] ); + + /* walk st */ + for( i = 0; i < 2; i++ ) + { + /* walk xyz */ + for( j = 0; j < 3; j++ ) + { + /* clear deltas */ + delta = 0.0; + texDelta = 0.0; + + /* walk deltas */ + for( k = 0; k < 3; k++ ) + { + if( fabs( deltas[ k ][ j ] ) > delta && + fabs( texDeltas[ k ][ i ] ) > texDelta ) + { + delta = deltas[ k ][ j ]; + texDelta = texDeltas[ k ][ i ]; + } + } + + /* set texture matrix component */ + if( fabs( delta ) > 0.0 ) + dp->texMat[ i ][ j ] = texDelta / delta; + else + dp->texMat[ i ][ j ] = 0.0; + } + + /* set translation component */ + dp->texMat[ i ][ 3 ] = a->st[ i ] - DotProduct( pa, dp->texMat[ i ] ); + } + } + #endif + + /* debug code */ + #if 1 + Sys_Printf( "Mat: [ %f %f %f %f ] [ %f %f %f %f ] Theta: %f (%f)\n", + dp->texMat[ 0 ][ 0 ], dp->texMat[ 0 ][ 1 ], dp->texMat[ 0 ][ 2 ], dp->texMat[ 0 ][ 3 ], + dp->texMat[ 1 ][ 0 ], dp->texMat[ 1 ][ 1 ], dp->texMat[ 1 ][ 2 ], dp->texMat[ 1 ][ 3 ], + RAD2DEG( acos( DotProduct( dp->texMat[ 0 ], dp->texMat[ 1 ] ) ) ), + RAD2DEG( acos( DotProduct( axis[ 0 ], axis[ 1 ] ) ) ) ); + + Sys_Printf( "XYZ: %f %f %f ST: %f %f ST(t): %f %f\n", + a->xyz[ 0 ], a->xyz[ 1 ], a->xyz[ 2 ], + a->st[ 0 ], a->st[ 1 ], + DotProduct( a->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ], DotProduct( a->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ] ); + #endif + + /* test texture matrix */ + s = DotProduct( a->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; + t = DotProduct( a->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; + if( fabs( s - a->st[ 0 ] ) > 0.01 || fabs( t - a->st[ 1 ] ) > 0.01 ) + { + Sys_Printf( "Bad texture matrix! (A) (%f, %f) != (%f, %f)\n", + s, t, a->st[ 0 ], a->st[ 1 ] ); + //% return qfalse; + } + s = DotProduct( b->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; + t = DotProduct( b->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; + if( fabs( s - b->st[ 0 ] ) > 0.01 || fabs( t - b->st[ 1 ] ) > 0.01 ) + { + Sys_Printf( "Bad texture matrix! (B) (%f, %f) != (%f, %f)\n", + s, t, b->st[ 0 ], b->st[ 1 ] ); + //% return qfalse; + } + s = DotProduct( c->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; + t = DotProduct( c->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; + if( fabs( s - c->st[ 0 ] ) > 0.01 || fabs( t - c->st[ 1 ] ) > 0.01 ) + { + Sys_Printf( "Bad texture matrix! (C) (%f, %f) != (%f, %f)\n", + s, t, c->st[ 0 ], c->st[ 1 ] ); + //% return qfalse; + } + + /* disco */ + return qtrue; +} + + + +/* +TransformDecalProjector() +transforms a decal projector +note: non-normalized axes will screw up the plane transform +*/ + +static void TransformDecalProjector( decalProjector_t *in, vec3_t axis[ 3 ], vec3_t origin, decalProjector_t *out ) +{ + int i; + + + /* copy misc stuff */ + out->si = in->si; + out->numPlanes = in->numPlanes; + + /* translate bounding box and sphere (note: rotated projector bounding box will be invalid!) */ + VectorSubtract( in->mins, origin, out->mins ); + VectorSubtract( in->maxs, origin, out->maxs ); + VectorSubtract( in->center, origin, out->center ); + out->radius = in->radius; + out->radius2 = in->radius2; + + /* translate planes */ + for( i = 0; i < in->numPlanes; i++ ) + { + out->planes[ i ][ 0 ] = DotProduct( in->planes[ i ], axis[ 0 ] ); + out->planes[ i ][ 1 ] = DotProduct( in->planes[ i ], axis[ 1 ] ); + out->planes[ i ][ 2 ] = DotProduct( in->planes[ i ], axis[ 2 ] ); + out->planes[ i ][ 3 ] = in->planes[ i ][ 3 ] - DotProduct( out->planes[ i ], origin ); + } + + /* translate texture matrix */ + for( i = 0; i < 2; i++ ) + { + out->texMat[ i ][ 0 ] = DotProduct( in->texMat[ i ], axis[ 0 ] ); + out->texMat[ i ][ 1 ] = DotProduct( in->texMat[ i ], axis[ 1 ] ); + out->texMat[ i ][ 2 ] = DotProduct( in->texMat[ i ], axis[ 2 ] ); + out->texMat[ i ][ 3 ] = in->texMat[ i ][ 3 ] + DotProduct( out->texMat[ i ], origin ); + } +} + + + +/* +MakeDecalProjector() +creates a new decal projector from a triangle +*/ + +static int MakeDecalProjector( shaderInfo_t *si, vec4_t projection, float distance, int numVerts, bspDrawVert_t **dv ) +{ + int i, j; + decalProjector_t *dp; + vec3_t xyz; + + + /* dummy check */ + if( numVerts != 3 && numVerts != 4 ) + return -1; + + /* limit check */ + if( numProjectors >= MAX_PROJECTORS ) + { + Sys_Printf( "WARNING: MAX_PROJECTORS (%d) exceeded, no more decal projectors available.\n", MAX_PROJECTORS ); + return -2; + } + + /* create a new projector */ + dp = &projectors[ numProjectors ]; + memset( dp, 0, sizeof( *dp ) ); + + /* basic setup */ + dp->si = si; + dp->numPlanes = numVerts + 2; + + /* make texture matrix */ + if( !MakeTextureMatrix( dp, projection, dv[ 0 ], dv[ 1 ], dv[ 2 ] ) ) + return -1; + + /* bound the projector */ + ClearBounds( dp->mins, dp->maxs ); + for( i = 0; i < numVerts; i++ ) + { + AddPointToBounds( dv[ i ]->xyz, dp->mins, dp->maxs ); + VectorMA( dv[ i ]->xyz, distance, projection, xyz ); + AddPointToBounds( xyz, dp->mins, dp->maxs ); + } + + /* make bouding sphere */ + VectorAdd( dp->mins, dp->maxs, dp->center ); + VectorScale( dp->center, 0.5f, dp->center ); + VectorSubtract( dp->maxs, dp->center, xyz ); + dp->radius = VectorLength( xyz ); + dp->radius2 = dp->radius * dp->radius; + + /* make the front plane */ + if( !PlaneFromPoints( dp->planes[ 0 ], dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) ) + return -1; + + /* make the back plane */ + VectorSubtract( vec3_origin, dp->planes[ 0 ], dp->planes[ 1 ] ); + VectorMA( dv[ 0 ]->xyz, distance, projection, xyz ); + dp->planes[ 1 ][ 3 ] = DotProduct( xyz, dp->planes[ 1 ] ); + + /* make the side planes */ + for( i = 0; i < numVerts; i++ ) + { + j = (i + 1) % numVerts; + VectorMA( dv[ i ]->xyz, distance, projection, xyz ); + if( !PlaneFromPoints( dp->planes[ i + 2 ], dv[ j ]->xyz, dv[ i ]->xyz, xyz ) ) + return -1; + } + + /* return ok */ + numProjectors++; + return numProjectors - 1; +} + + + +/* +ProcessDecals() +finds all decal entities and creates decal projectors +*/ + +#define PLANAR_EPSILON 0.5f + +void ProcessDecals( void ) +{ + int i, j, x, y, pw[ 5 ], r, iterations; + float distance; + vec4_t projection, plane; + vec3_t origin, target, delta; + entity_t *e, *e2; + parseMesh_t *p; + mesh_t *mesh, *subdivided; + bspDrawVert_t *dv[ 4 ]; + const char *value; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- ProcessDecals ---\n" ); + + /* walk entity list */ + for( i = 0; i < numEntities; i++ ) + { + /* get entity */ + e = &entities[ i ]; + value = ValueForKey( e, "classname" ); + if( Q_stricmp( value, "_decal" ) ) + continue; + + /* any patches? */ + if( e->patches == NULL ) + { + Sys_Printf( "WARNING: Decal entity without any patch meshes, ignoring.\n" ); + e->epairs = NULL; /* fixme: leak! */ + continue; + } + + /* find target */ + value = ValueForKey( e, "target" ); + e2 = FindTargetEntity( value ); + + /* no target? */ + if( e2 == NULL ) + { + Sys_Printf( "WARNING: Decal entity without a valid target, ignoring.\n" ); + continue; + } + + /* walk entity patches */ + for( p = e->patches; p != NULL; p = e->patches ) + { + /* setup projector */ + if( VectorCompare( e->origin, vec3_origin ) ) + { + VectorAdd( p->eMins, p->eMaxs, origin ); + VectorScale( origin, 0.5f, origin ); + } + else + VectorCopy( e->origin, origin ); + + VectorCopy( e2->origin, target ); + VectorSubtract( target, origin, delta ); + + /* setup projection plane */ + distance = VectorNormalize( delta, projection ); + projection[ 3 ] = DotProduct( origin, projection ); + + /* create projectors */ + if( distance > 0.125f ) + { + /* tesselate the patch */ + iterations = IterationsForCurve( p->longestCurve, patchSubdivisions ); + subdivided = SubdivideMesh2( p->mesh, iterations ); + + /* fit it to the curve and remove colinear verts on rows/columns */ + PutMeshOnCurve( *subdivided ); + mesh = RemoveLinearMeshColumnsRows( subdivided ); + FreeMesh( subdivided ); + + /* offset by projector origin */ + for( j = 0; j < (mesh->width * mesh->height); j++ ) + VectorAdd( mesh->verts[ j ].xyz, e->origin, mesh->verts[ j ].xyz ); + + /* iterate through the mesh quads */ + for( y = 0; y < (mesh->height - 1); y++ ) + { + for( x = 0; x < (mesh->width - 1); x++ ) + { + /* set indexes */ + pw[ 0 ] = x + (y * mesh->width); + pw[ 1 ] = x + ((y + 1) * mesh->width); + pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); + pw[ 3 ] = x + 1 + (y * mesh->width); + pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ + + /* set radix */ + r = (x + y) & 1; + + /* get drawverts */ + dv[ 0 ] = &mesh->verts[ pw[ r + 0 ] ]; + dv[ 1 ] = &mesh->verts[ pw[ r + 1 ] ]; + dv[ 2 ] = &mesh->verts[ pw[ r + 2 ] ]; + dv[ 3 ] = &mesh->verts[ pw[ r + 3 ] ]; + + /* planar? (nuking this optimization as it doesn't work on non-rectangular quads) */ + plane[ 0 ] = 0.0f; /* stupid msvc */ + if( 0 && PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) && + fabs( DotProduct( dv[ 1 ]->xyz, plane ) - plane[ 3 ] ) <= PLANAR_EPSILON ) + { + /* make a quad projector */ + MakeDecalProjector( p->shaderInfo, projection, distance, 4, dv ); + } + else + { + /* make first triangle */ + MakeDecalProjector( p->shaderInfo, projection, distance, 3, dv ); + + /* make second triangle */ + dv[ 1 ] = dv[ 2 ]; + dv[ 2 ] = dv[ 3 ]; + MakeDecalProjector( p->shaderInfo, projection, distance, 3, dv ); + } + } + } + + /* clean up */ + free( mesh ); + } + + /* remove patch from entity (fixme: leak!) */ + e->patches = p->next; + + /* push patch to worldspawn (enable this to debug projectors) */ + #if 0 + p->next = entities[ 0 ].patches; + entities[ 0 ].patches = p; + #endif + } + } + + /* emit some stats */ + Sys_FPrintf( SYS_VRB, "%9d decal projectors\n", numProjectors ); +} + + + +/* +ProjectDecalOntoWinding() +projects a decal onto a winding +*/ + +static void ProjectDecalOntoWinding( decalProjector_t *dp, mapDrawSurface_t *ds, winding_t *w ) +{ + int i, j; + float d, d2, alpha; + winding_t *front, *back; + mapDrawSurface_t *ds2; + bspDrawVert_t *dv; + vec4_t plane; + + + /* dummy check */ + if( w->numpoints < 3 ) + { + FreeWinding( w ); + return; + } + + /* offset by entity origin */ + for( i = 0; i < w->numpoints; i++ ) + VectorAdd( w->p[ i ], entityOrigin, w->p[ i ] ); + + /* make a plane from the winding */ + if( !PlaneFromPoints( plane, w->p[ 0 ], w->p[ 1 ], w->p[ 2 ] ) ) + { + FreeWinding( w ); + return; + } + + /* backface check */ + d = DotProduct( dp->planes[ 0 ], plane ); + if( d < -0.0001f ) + { + FreeWinding( w ); + return; + } + + /* walk list of planes */ + for( i = 0; i < dp->numPlanes; i++ ) + { + /* chop winding by the plane */ + ClipWindingEpsilon( w, dp->planes[ i ], dp->planes[ i ][ 3 ], 0.0625f, &front, &back ); + FreeWinding( w ); + + /* lose the front fragment */ + if( front != NULL ) + FreeWinding( front ); + + /* if nothing left in back, then bail */ + if( back == NULL ) + return; + + /* reset winding */ + w = back; + } + + /* nothing left? */ + if( w == NULL || w->numpoints < 3 ) + return; + + /* add to counts */ + numDecalSurfaces++; + + /* make a new surface */ + ds2 = AllocDrawSurface( SURFACE_DECAL ); + + /* set it up */ + ds2->entityNum = ds->entityNum; + ds2->castShadows = ds->castShadows; + ds2->recvShadows = ds->recvShadows; + ds2->shaderInfo = dp->si; + ds2->fogNum = ds->fogNum; /* why was this -1? */ + ds2->lightmapScale = ds->lightmapScale; + ds2->shadeAngleDegrees = ds->shadeAngleDegrees; + ds2->numVerts = w->numpoints; + ds2->verts = safe_malloc( ds2->numVerts * sizeof( *ds2->verts ) ); + memset( ds2->verts, 0, ds2->numVerts * sizeof( *ds2->verts ) ); + + /* set vertexes */ + for( i = 0; i < ds2->numVerts; i++ ) + { + /* get vertex */ + dv = &ds2->verts[ i ]; + + /* set alpha */ + d = DotProduct( w->p[ i ], dp->planes[ 0 ] ) - dp->planes[ 0 ][ 3 ]; + d2 = DotProduct( w->p[ i ], dp->planes[ 1 ] ) - dp->planes[ 1 ][ 3 ]; + alpha = 255.0f * d2 / (d + d2); + if( alpha > 255 ) + alpha = 255; + else if( alpha < 0 ) + alpha = 0; + + /* set misc */ + VectorSubtract( w->p[ i ], entityOrigin, dv->xyz ); + VectorCopy( plane, dv->normal ); + dv->st[ 0 ] = DotProduct( dv->xyz, dp->texMat[ 0 ] ) + dp->texMat[ 0 ][ 3 ]; + dv->st[ 1 ] = DotProduct( dv->xyz, dp->texMat[ 1 ] ) + dp->texMat[ 1 ][ 3 ]; + + /* set color */ + for( j = 0; j < MAX_LIGHTMAPS; j++ ) + { + dv->color[ j ][ 0 ] = 255; + dv->color[ j ][ 1 ] = 255; + dv->color[ j ][ 2 ] = 255; + dv->color[ j ][ 3 ] = alpha; + } + } +} + + + +/* +ProjectDecalOntoFace() +projects a decal onto a brushface surface +*/ + +static void ProjectDecalOntoFace( decalProjector_t *dp, mapDrawSurface_t *ds ) +{ + vec4_t plane; + float d; + winding_t *w; + + + /* dummy check */ + if( ds->sideRef == NULL || ds->sideRef->side == NULL ) + return; + + /* backface check */ + if( ds->planar ) + { + VectorCopy( mapplanes[ ds->planeNum ].normal, plane ); + plane[ 3 ] = mapplanes[ ds->planeNum ].dist + DotProduct( plane, entityOrigin ); + d = DotProduct( dp->planes[ 0 ], plane ); + if( d < -0.0001f ) + return; + } + + /* generate decal */ + w = WindingFromDrawSurf( ds ); + ProjectDecalOntoWinding( dp, ds, w ); +} + + + +/* +ProjectDecalOntoPatch() +projects a decal onto a patch surface +*/ + +static void ProjectDecalOntoPatch( decalProjector_t *dp, mapDrawSurface_t *ds ) +{ + int x, y, pw[ 5 ], r, iterations; + vec4_t plane; + float d; + mesh_t src, *mesh, *subdivided; + winding_t *w; + + + /* backface check */ + if( ds->planar ) + { + VectorCopy( mapplanes[ ds->planeNum ].normal, plane ); + plane[ 3 ] = mapplanes[ ds->planeNum ].dist + DotProduct( plane, entityOrigin ); + d = DotProduct( dp->planes[ 0 ], plane ); + if( d < -0.0001f ) + return; + } + + /* tesselate the patch */ + src.width = ds->patchWidth; + src.height = ds->patchHeight; + src.verts = ds->verts; + iterations = IterationsForCurve( ds->longestCurve, patchSubdivisions ); + subdivided = SubdivideMesh2( src, iterations ); + + /* fit it to the curve and remove colinear verts on rows/columns */ + PutMeshOnCurve( *subdivided ); + mesh = RemoveLinearMeshColumnsRows( subdivided ); + FreeMesh( subdivided ); + + /* iterate through the mesh quads */ + for( y = 0; y < (mesh->height - 1); y++ ) + { + for( x = 0; x < (mesh->width - 1); x++ ) + { + /* set indexes */ + pw[ 0 ] = x + (y * mesh->width); + pw[ 1 ] = x + ((y + 1) * mesh->width); + pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); + pw[ 3 ] = x + 1 + (y * mesh->width); + pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ + + /* set radix */ + r = (x + y) & 1; + + /* generate decal for first triangle */ + w = AllocWinding( 3 ); + w->numpoints = 3; + VectorCopy( mesh->verts[ pw[ r + 0 ] ].xyz, w->p[ 0 ] ); + VectorCopy( mesh->verts[ pw[ r + 1 ] ].xyz, w->p[ 1 ] ); + VectorCopy( mesh->verts[ pw[ r + 2 ] ].xyz, w->p[ 2 ] ); + ProjectDecalOntoWinding( dp, ds, w ); + + /* generate decal for second triangle */ + w = AllocWinding( 3 ); + w->numpoints = 3; + VectorCopy( mesh->verts[ pw[ r + 0 ] ].xyz, w->p[ 0 ] ); + VectorCopy( mesh->verts[ pw[ r + 2 ] ].xyz, w->p[ 1 ] ); + VectorCopy( mesh->verts[ pw[ r + 3 ] ].xyz, w->p[ 2 ] ); + ProjectDecalOntoWinding( dp, ds, w ); + } + } + + /* clean up */ + free( mesh ); +} + + + +/* +ProjectDecalOntoTriangles() +projects a decal onto a triangle surface +*/ + +static void ProjectDecalOntoTriangles( decalProjector_t *dp, mapDrawSurface_t *ds ) +{ + int i; + vec4_t plane; + float d; + winding_t *w; + + + /* triangle surfaces without shaders don't get marks by default */ + if( ds->type == SURFACE_TRIANGLES && ds->shaderInfo->shaderText == NULL ) + return; + + /* backface check */ + if( ds->planar ) + { + VectorCopy( mapplanes[ ds->planeNum ].normal, plane ); + plane[ 3 ] = mapplanes[ ds->planeNum ].dist + DotProduct( plane, entityOrigin ); + d = DotProduct( dp->planes[ 0 ], plane ); + if( d < -0.0001f ) + return; + } + + /* iterate through triangles */ + for( i = 0; i < ds->numIndexes; i += 3 ) + { + /* generate decal */ + w = AllocWinding( 3 ); + w->numpoints = 3; + VectorCopy( ds->verts[ ds->indexes[ i ] ].xyz, w->p[ 0 ] ); + VectorCopy( ds->verts[ ds->indexes[ i + 1 ] ].xyz, w->p[ 1 ] ); + VectorCopy( ds->verts[ ds->indexes[ i + 2 ] ].xyz, w->p[ 2 ] ); + ProjectDecalOntoWinding( dp, ds, w ); + } +} + + + +/* +MakeEntityDecals() +projects decals onto world surfaces +*/ + +void MakeEntityDecals( entity_t *e ) +{ + int i, j, k, f, fOld, start; + decalProjector_t dp; + mapDrawSurface_t *ds; + vec3_t identityAxis[ 3 ] = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } }; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- MakeEntityDecals ---\n" ); + + /* set entity origin */ + VectorCopy( e->origin, entityOrigin ); + + /* transform projector instead of geometry */ + VectorClear( entityOrigin ); + + /* init pacifier */ + fOld = -1; + start = I_FloatTime(); + + /* walk the list of decal projectors */ + for( i = 0; i < numProjectors; i++ ) + { + /* print pacifier */ + f = 10 * i / numProjectors; + if( f != fOld ) + { + fOld = f; + Sys_FPrintf( SYS_VRB, "%d...", f ); + } + + /* get projector */ + TransformDecalProjector( &projectors[ i ], identityAxis, e->origin, &dp ); + + /* walk the list of surfaces in the entity */ + for( j = e->firstDrawSurf; j < numMapDrawSurfs; j++ ) + { + /* get surface */ + ds = &mapDrawSurfs[ j ]; + if( ds->numVerts <= 0 ) + continue; + + /* ignore autosprite or nomarks */ + if( ds->shaderInfo->autosprite || (ds->shaderInfo->compileFlags & C_NOMARKS) ) + continue; + + /* bounds check */ + for( k = 0; k < 3; k++ ) + if( ds->mins[ k ] >= (dp.center[ k ] + dp.radius) || + ds->maxs[ k ] <= (dp.center[ k ] - dp.radius) ) + break; + if( k < 3 ) + continue; + + /* switch on type */ + switch( ds->type ) + { + case SURFACE_FACE: + ProjectDecalOntoFace( &dp, ds ); + break; + + case SURFACE_PATCH: + ProjectDecalOntoPatch( &dp, ds ); + break; + + case SURFACE_TRIANGLES: + case SURFACE_FORCED_META: + case SURFACE_META: + ProjectDecalOntoTriangles( &dp, ds ); + break; + + default: + break; + } + } + } + + /* print time */ + Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) ); + + /* emit some stats */ + Sys_FPrintf( SYS_VRB, "%9d decal surfaces\n", numDecalSurfaces ); +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/facebsp.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/facebsp.c new file mode 100644 index 00000000..9291f564 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/facebsp.c @@ -0,0 +1,528 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define FACEBSP_C + + + +/* dependencies */ +#include "q3map2.h" + + + +int c_faceLeafs; + + +/* +================ +AllocBspFace +================ +*/ +face_t *AllocBspFace( void ) { + face_t *f; + + f = safe_malloc(sizeof(*f)); + memset( f, 0, sizeof(*f) ); + + return f; +} + + + +/* +================ +FreeBspFace +================ +*/ +void FreeBspFace( face_t *f ) { + if ( f->w ) { + FreeWinding( f->w ); + } + free( f ); +} + + + +/* +SelectSplitPlaneNum() +finds the best split plane for this node +*/ + +static void SelectSplitPlaneNum( node_t *node, face_t *list, int *splitPlaneNum, int *compileFlags ) +{ + face_t *split; + face_t *check; + face_t *bestSplit; + int splits, facing, front, back; + int side; + plane_t *plane; + int value, bestValue; + int i; + vec3_t normal; + float dist; + int planenum; + float sizeBias; + + //int frontC,backC,splitsC,facingC; + + + /* ydnar: set some defaults */ + *splitPlaneNum = -1; /* leaf */ + *compileFlags = 0; + + /* ydnar 2002-06-24: changed this to split on z-axis as well */ + /* ydnar 2002-09-21: changed blocksize to be a vector, so mappers can specify a 3 element value */ + + /* if it is crossing a block boundary, force a split */ + for( i = 0; i < 3; i++ ) + { + if( blockSize[ i ] <= 0 ) + continue; + dist = blockSize[ i ] * (floor( node->mins[ i ] / blockSize[ i ] ) + 1); + if( node->maxs[ i ] > dist ) + { + VectorClear( normal ); + normal[ i ] = 1; + planenum = FindFloatPlane( normal, dist, 0, NULL ); + *splitPlaneNum = planenum; + return; + } + } + + /* pick one of the face planes */ + bestValue = -99999; + bestSplit = list; + + + // div0: this check causes detail/structural mixes + //for( split = list; split; split = split->next ) + // split->checked = qfalse; + + for( split = list; split; split = split->next ) + { + //if ( split->checked ) + // continue; + + plane = &mapplanes[ split->planenum ]; + splits = 0; + facing = 0; + front = 0; + back = 0; + for ( check = list ; check ; check = check->next ) { + if ( check->planenum == split->planenum ) { + facing++; + //check->checked = qtrue; // won't need to test this plane again + continue; + } + side = WindingOnPlaneSide( check->w, plane->normal, plane->dist ); + if ( side == SIDE_CROSS ) { + splits++; + } else if ( side == SIDE_FRONT ) { + front++; + } else if ( side == SIDE_BACK ) { + back++; + } + } + + if(bspAlternateSplitWeights) + { + // from 27 + + //Bigger is better + sizeBias=WindingArea(split->w); + + //Base score = 20000 perfectly balanced + value = 20000-(abs(front-back)); + value -= plane->counter;// If we've already used this plane sometime in the past try not to use it again + value -= facing ; // if we're going to have alot of other surfs use this plane, we want to get it in quickly. + value -= splits*5; //more splits = bad + value += sizeBias*10; //We want a huge score bias based on plane size + } + else + { + value = 5*facing - 5*splits; // - abs(front-back); + if ( plane->type < 3 ) { + value+=5; // axial is better + } + } + + value += split->priority; // prioritize hints higher + + if ( value > bestValue ) { + bestValue = value; + bestSplit = split; + //frontC=front; + //backC=back; + //splitsC=splits; + //facingC=facing; + } + } + + /* nothing, we have a leaf */ + if( bestValue == -99999 ) + return; + + //Sys_FPrintf (SYS_VRB, "F: %d B:%d S:%d FA:%ds\n",frontC,backC,splitsC,facingC ); + + /* set best split data */ + *splitPlaneNum = bestSplit->planenum; + *compileFlags = bestSplit->compileFlags; + +#if 0 + if(bestSplit->compileFlags & C_DETAIL) + for( split = list; split; split = split->next ) + if(!(split->compileFlags & C_DETAIL)) + Sys_FPrintf(SYS_ERR, "DON'T DO SUCH SPLITS (1)\n"); + if((node->compileFlags & C_DETAIL) && !(bestSplit->compileFlags & C_DETAIL)) + Sys_FPrintf(SYS_ERR, "DON'T DO SUCH SPLITS (2)\n"); +#endif + + if (*splitPlaneNum>-1) mapplanes[ *splitPlaneNum ].counter++; +} + + + +/* +CountFaceList() +counts bsp faces in the linked list +*/ + +int CountFaceList( face_t *list ) +{ + int c; + + + c = 0; + for( ; list != NULL; list = list->next ) + c++; + return c; +} + + + +/* +BuildFaceTree_r() +recursively builds the bsp, splitting on face planes +*/ + +void BuildFaceTree_r( node_t *node, face_t *list ) +{ + face_t *split; + face_t *next; + int side; + plane_t *plane; + face_t *newFace; + face_t *childLists[2]; + winding_t *frontWinding, *backWinding; + int i; + int splitPlaneNum, compileFlags; + qboolean isstruct = qfalse; + + + /* count faces left */ + i = CountFaceList( list ); + + /* select the best split plane */ + SelectSplitPlaneNum( node, list, &splitPlaneNum, &compileFlags ); + + /* if we don't have any more faces, this is a node */ + if ( splitPlaneNum == -1 ) + { + node->planenum = PLANENUM_LEAF; + node->has_structural_children = qfalse; + c_faceLeafs++; + return; + } + + /* partition the list */ + node->planenum = splitPlaneNum; + node->compileFlags = compileFlags; + node->has_structural_children = !(compileFlags & C_DETAIL) && !node->opaque; + plane = &mapplanes[ splitPlaneNum ]; + childLists[0] = NULL; + childLists[1] = NULL; + + for( split = list; split; split = next ) + { + /* set next */ + next = split->next; + + /* don't split by identical plane */ + if( split->planenum == node->planenum ) + { + FreeBspFace( split ); + continue; + } + + if(!(split->compileFlags & C_DETAIL)) + isstruct = 1; + + /* determine which side the face falls on */ + side = WindingOnPlaneSide( split->w, plane->normal, plane->dist ); + + /* switch on side */ + if( side == SIDE_CROSS ) + { + ClipWindingEpsilon( split->w, plane->normal, plane->dist, CLIP_EPSILON * 2, + &frontWinding, &backWinding ); + if( frontWinding ) { + newFace = AllocBspFace(); + newFace->w = frontWinding; + newFace->next = childLists[0]; + newFace->planenum = split->planenum; + newFace->priority = split->priority; + newFace->compileFlags = split->compileFlags; + childLists[0] = newFace; + } + if( backWinding ) { + newFace = AllocBspFace(); + newFace->w = backWinding; + newFace->next = childLists[1]; + newFace->planenum = split->planenum; + newFace->priority = split->priority; + newFace->compileFlags = split->compileFlags; + childLists[1] = newFace; + } + FreeBspFace( split ); + } else if ( side == SIDE_FRONT ) { + split->next = childLists[0]; + childLists[0] = split; + } else if ( side == SIDE_BACK ) { + split->next = childLists[1]; + childLists[1] = split; + } + } + + + // recursively process children + for ( i = 0 ; i < 2 ; i++ ) { + node->children[i] = AllocNode(); + node->children[i]->parent = node; + VectorCopy( node->mins, node->children[i]->mins ); + VectorCopy( node->maxs, node->children[i]->maxs ); + } + + for ( i = 0 ; i < 3 ; i++ ) { + if ( plane->normal[i] == 1 ) { + node->children[0]->mins[i] = plane->dist; + node->children[1]->maxs[i] = plane->dist; + break; + } + } + +#if 0 + if((node->compileFlags & C_DETAIL) && isstruct) + Sys_FPrintf(SYS_ERR, "I am detail, my child is structural, this is a wtf1\n", node->has_structural_children); +#endif + + for ( i = 0 ; i < 2 ; i++ ) { + BuildFaceTree_r ( node->children[i], childLists[i]); + node->has_structural_children |= node->children[i]->has_structural_children; + } + +#if 0 + if((node->compileFlags & C_DETAIL) && !(node->children[0]->compileFlags & C_DETAIL) && node->children[0]->planenum != PLANENUM_LEAF) + Sys_FPrintf(SYS_ERR, "I am detail, my child is structural\n", node->has_structural_children); + if((node->compileFlags & C_DETAIL) && isstruct) + Sys_FPrintf(SYS_ERR, "I am detail, my child is structural, this is a wtf2\n", node->has_structural_children); +#endif +} + + +/* +================ +FaceBSP + +List will be freed before returning +================ +*/ +tree_t *FaceBSP( face_t *list ) { + tree_t *tree; + face_t *face; + int i; + int count; + + Sys_FPrintf (SYS_VRB, "--- FaceBSP ---\n" ); + + tree = AllocTree (); + + count = 0; + for( face = list; face != NULL; face = face->next ) + { + count++; + for( i = 0; i < face->w->numpoints; i++ ) + { + AddPointToBounds( face->w->p[ i ], tree->mins, tree->maxs ); + } + } + Sys_FPrintf( SYS_VRB, "%9d faces\n", count ); + + for( i = 0; i < nummapplanes; i++) + { + mapplanes[ i ].counter=0; + } + + tree->headnode = AllocNode(); + VectorCopy( tree->mins, tree->headnode->mins ); + VectorCopy( tree->maxs, tree->headnode->maxs ); + c_faceLeafs = 0; + + BuildFaceTree_r ( tree->headnode, list ); + + Sys_FPrintf( SYS_VRB, "%9d leafs\n", c_faceLeafs ); + + return tree; +} + + + +/* +MakeStructuralBSPFaceList() +get structural brush faces +*/ + +face_t *MakeStructuralBSPFaceList( brush_t *list ) +{ + brush_t *b; + int i; + side_t *s; + winding_t *w; + face_t *f, *flist; + + + flist = NULL; + for( b = list; b != NULL; b = b->next ) + { + if( !deepBSP && b->detail ) + continue; + + for( i = 0; i < b->numsides; i++ ) + { + /* get side and winding */ + s = &b->sides[ i ]; + w = s->winding; + if( w == NULL ) + continue; + + /* ydnar: skip certain faces */ + if( s->compileFlags & C_SKIP ) + continue; + + /* allocate a face */ + f = AllocBspFace(); + f->w = CopyWinding( w ); + f->planenum = s->planenum & ~1; + f->compileFlags = s->compileFlags; /* ydnar */ + if(b->detail) + f->compileFlags |= C_DETAIL; + + /* ydnar: set priority */ + f->priority = 0; + if( f->compileFlags & C_HINT ) + f->priority += HINT_PRIORITY; + if( f->compileFlags & C_ANTIPORTAL ) + f->priority += ANTIPORTAL_PRIORITY; + if( f->compileFlags & C_AREAPORTAL ) + f->priority += AREAPORTAL_PRIORITY; + if( f->compileFlags & C_DETAIL ) + f->priority += DETAIL_PRIORITY; + + /* get next face */ + f->next = flist; + flist = f; + } + } + + return flist; +} + + + +/* +MakeVisibleBSPFaceList() +get visible brush faces +*/ + +face_t *MakeVisibleBSPFaceList( brush_t *list ) +{ + brush_t *b; + int i; + side_t *s; + winding_t *w; + face_t *f, *flist; + + + flist = NULL; + for( b = list; b != NULL; b = b->next ) + { + if( !deepBSP && b->detail ) + continue; + + for( i = 0; i < b->numsides; i++ ) + { + /* get side and winding */ + s = &b->sides[ i ]; + w = s->visibleHull; + if( w == NULL ) + continue; + + /* ydnar: skip certain faces */ + if( s->compileFlags & C_SKIP ) + continue; + + /* allocate a face */ + f = AllocBspFace(); + f->w = CopyWinding( w ); + f->planenum = s->planenum & ~1; + f->compileFlags = s->compileFlags; /* ydnar */ + if(b->detail) + f->compileFlags |= C_DETAIL; + + /* ydnar: set priority */ + f->priority = 0; + if( f->compileFlags & C_HINT ) + f->priority += HINT_PRIORITY; + if( f->compileFlags & C_ANTIPORTAL ) + f->priority += ANTIPORTAL_PRIORITY; + if( f->compileFlags & C_AREAPORTAL ) + f->priority += AREAPORTAL_PRIORITY; + if( f->compileFlags & C_DETAIL ) + f->priority += DETAIL_PRIORITY; + + /* get next face */ + f->next = flist; + flist = f; + } + } + + return flist; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/fog.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/fog.c new file mode 100644 index 00000000..c9ee6e25 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/fog.c @@ -0,0 +1,803 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define FOG_C + + + +/* dependencies */ +#include "q3map2.h" + + + +int numFogFragments; +int numFogPatchFragments; + + + +/* +DrawSurfToMesh() +converts a patch drawsurface to a mesh_t +*/ + +mesh_t *DrawSurfToMesh( mapDrawSurface_t *ds ) +{ + mesh_t *m; + + + m = safe_malloc( sizeof( *m ) ); + m->width = ds->patchWidth; + m->height = ds->patchHeight; + m->verts = safe_malloc( sizeof(m->verts[ 0 ]) * m->width * m->height ); + memcpy( m->verts, ds->verts, sizeof(m->verts[ 0 ]) * m->width * m->height ); + + return m; +} + + + +/* +SplitMeshByPlane() +chops a mesh by a plane +*/ + +void SplitMeshByPlane( mesh_t *in, vec3_t normal, float dist, mesh_t **front, mesh_t **back ) +{ + int w, h, split; + float d[MAX_PATCH_SIZE][MAX_PATCH_SIZE]; + bspDrawVert_t *dv, *v1, *v2; + int c_front, c_back, c_on; + mesh_t *f, *b; + int i; + float frac; + int frontAprox, backAprox; + + for ( i = 0 ; i < 2 ; i++ ) { + dv = in->verts; + c_front = 0; + c_back = 0; + c_on = 0; + for ( h = 0 ; h < in->height ; h++ ) { + for ( w = 0 ; w < in->width ; w++, dv++ ) { + d[h][w] = DotProduct( dv->xyz, normal ) - dist; + if ( d[h][w] > ON_EPSILON ) { + c_front++; + } else if ( d[h][w] < -ON_EPSILON ) { + c_back++; + } else { + c_on++; + } + } + } + + *front = NULL; + *back = NULL; + + if ( !c_front ) { + *back = in; + return; + } + if ( !c_back ) { + *front = in; + return; + } + + // find a split point + split = -1; + for ( w = 0 ; w < in->width -1 ; w++ ) { + if ( ( d[0][w] < 0 ) != ( d[0][w+1] < 0 ) ) { + if ( split == -1 ) { + split = w; + break; + } + } + } + + if ( split == -1 ) { + if ( i == 1 ) { + Sys_FPrintf (SYS_VRB, "No crossing points in patch\n"); + *front = in; + return; + } + + in = TransposeMesh( in ); + InvertMesh( in ); + continue; + } + + // make sure the split point stays the same for all other rows + for ( h = 1 ; h < in->height ; h++ ) { + for ( w = 0 ; w < in->width -1 ; w++ ) { + if ( ( d[h][w] < 0 ) != ( d[h][w+1] < 0 ) ) { + if ( w != split ) { + Sys_Printf( "multiple crossing points for patch -- can't clip\n"); + *front = in; + return; + } + } + } + if ( ( d[h][split] < 0 ) == ( d[h][split+1] < 0 ) ) { + Sys_Printf( "differing crossing points for patch -- can't clip\n"); + *front = in; + return; + } + } + + break; + } + + + // create two new meshes + f = safe_malloc( sizeof( *f ) ); + f->width = split + 2; + if ( ! (f->width & 1) ) { + f->width++; + frontAprox = 1; + } else { + frontAprox = 0; + } + if ( f->width > MAX_PATCH_SIZE ) { + Error( "MAX_PATCH_SIZE after split"); + } + f->height = in->height; + f->verts = safe_malloc( sizeof(f->verts[0]) * f->width * f->height ); + + b = safe_malloc( sizeof( *b ) ); + b->width = in->width - split; + if ( ! (b->width & 1) ) { + b->width++; + backAprox = 1; + } else { + backAprox = 0; + } + if ( b->width > MAX_PATCH_SIZE ) { + Error( "MAX_PATCH_SIZE after split"); + } + b->height = in->height; + b->verts = safe_malloc( sizeof(b->verts[0]) * b->width * b->height ); + + if ( d[0][0] > 0 ) { + *front = f; + *back = b; + } else { + *front = b; + *back = f; + } + + // distribute the points + for ( w = 0 ; w < in->width ; w++ ) { + for ( h = 0 ; h < in->height ; h++ ) { + if ( w <= split ) { + f->verts[ h * f->width + w ] = in->verts[ h * in->width + w ]; + } else { + b->verts[ h * b->width + w - split + backAprox ] = in->verts[ h * in->width + w ]; + } + } + } + + // clip the crossing line + for ( h = 0; h < in->height; h++ ) + { + dv = &f->verts[ h * f->width + split + 1 ]; + v1 = &in->verts[ h * in->width + split ]; + v2 = &in->verts[ h * in->width + split + 1 ]; + + frac = d[h][split] / ( d[h][split] - d[h][split+1] ); + + /* interpolate */ + //% for( i = 0; i < 10; i++ ) + //% dv->xyz[ i ] = v1->xyz[ i ] + frac * (v2->xyz[ i ] - v1->xyz[ i ]); + //% dv->xyz[10] = 0; // set all 4 colors to 0 + LerpDrawVertAmount( v1, v2, frac, dv ); + + if ( frontAprox ) { + f->verts[ h * f->width + split + 2 ] = *dv; + } + b->verts[ h * b->width ] = *dv; + if ( backAprox ) { + b->verts[ h * b->width + 1 ] = *dv; + } + } + + /* +PrintMesh( in ); +Sys_Printf("\n"); +PrintMesh( f ); +Sys_Printf("\n"); +PrintMesh( b ); +Sys_Printf("\n"); + */ + + FreeMesh( in ); +} + + +/* +ChopPatchSurfaceByBrush() +chops a patch up by a fog brush +*/ + +qboolean ChopPatchSurfaceByBrush( entity_t *e, mapDrawSurface_t *ds, brush_t *b ) +{ + int i, j; + side_t *s; + plane_t *plane; + mesh_t *outside[MAX_BRUSH_SIDES]; + int numOutside; + mesh_t *m, *front, *back; + mapDrawSurface_t *newds; + + m = DrawSurfToMesh( ds ); + numOutside = 0; + + // only split by the top and bottom planes to avoid + // some messy patch clipping issues + + for ( i = 4 ; i <= 5 ; i++ ) { + s = &b->sides[ i ]; + plane = &mapplanes[ s->planenum ]; + + SplitMeshByPlane( m, plane->normal, plane->dist, &front, &back ); + + if ( !back ) { + // nothing actually contained inside + for ( j = 0 ; j < numOutside ; j++ ) { + FreeMesh( outside[j] ); + } + return qfalse; + } + m = back; + + if ( front ) { + if ( numOutside == MAX_BRUSH_SIDES ) { + Error( "MAX_BRUSH_SIDES" ); + } + outside[ numOutside ] = front; + numOutside++; + } + } + + /* all of outside fragments become seperate drawsurfs */ + numFogPatchFragments += numOutside; + for( i = 0; i < numOutside; i++ ) + { + /* transpose and invert the chopped patch (fixes potential crash. fixme: why?) */ + outside[ i ] = TransposeMesh( outside[ i ] ); + InvertMesh( outside[ i ] ); + + /* ydnar: do this the hacky right way */ + newds = AllocDrawSurface( SURFACE_PATCH ); + memcpy( newds, ds, sizeof( *ds ) ); + newds->patchWidth = outside[ i ]->width; + newds->patchHeight = outside[ i ]->height; + newds->numVerts = outside[ i ]->width * outside[ i ]->height; + newds->verts = safe_malloc( newds->numVerts * sizeof( *newds->verts ) ); + memcpy( newds->verts, outside[ i ]->verts, newds->numVerts * sizeof( *newds->verts ) ); + + /* free the source mesh */ + FreeMesh( outside[ i ] ); + } + + /* only rejigger this patch if it was chopped */ + //% Sys_Printf( "Inside: %d x %d\n", m->width, m->height ); + if( numOutside > 0 ) + { + /* transpose and invert the chopped patch (fixes potential crash. fixme: why?) */ + m = TransposeMesh( m ); + InvertMesh( m ); + + /* replace ds with m */ + ds->patchWidth = m->width; + ds->patchHeight = m->height; + ds->numVerts = m->width * m->height; + free( ds->verts ); + ds->verts = safe_malloc( ds->numVerts * sizeof( *ds->verts ) ); + memcpy( ds->verts, m->verts, ds->numVerts * sizeof( *ds->verts ) ); + } + + /* free the source mesh and return */ + FreeMesh( m ); + return qtrue; +} + + + +/* +WindingFromDrawSurf() +creates a winding from a surface's verts +*/ + +winding_t *WindingFromDrawSurf( mapDrawSurface_t *ds ) +{ + winding_t *w; + int i; + + // we use the first point of the surface, maybe something more clever would be useful + // (actually send the whole draw surface would be cool?) + if( ds->numVerts >= MAX_POINTS_ON_WINDING ) + { + int max = ds->numVerts; + vec3_t p[256]; + + if(max > 256) + max = 256; + + for ( i = 0 ; i < max ; i++ ) { + VectorCopy( ds->verts[i].xyz, p[i] ); + } + + xml_Winding( "WindingFromDrawSurf failed: MAX_POINTS_ON_WINDING exceeded", p, max, qtrue ); + } + + w = AllocWinding( ds->numVerts ); + w->numpoints = ds->numVerts; + for ( i = 0 ; i < ds->numVerts ; i++ ) { + VectorCopy( ds->verts[i].xyz, w->p[i] ); + } + return w; +} + + + +/* +ChopFaceSurfaceByBrush() +chops up a face drawsurface by a fog brush, with a potential fragment left inside +*/ + +qboolean ChopFaceSurfaceByBrush( entity_t *e, mapDrawSurface_t *ds, brush_t *b ) +{ + int i, j; + side_t *s; + plane_t *plane; + winding_t *w; + winding_t *front, *back; + winding_t *outside[ MAX_BRUSH_SIDES ]; + int numOutside; + mapDrawSurface_t *newds; + + + /* dummy check */ + if( ds->sideRef == NULL || ds->sideRef->side == NULL ) + return qfalse; + + /* initial setup */ + w = WindingFromDrawSurf( ds ); + numOutside = 0; + + /* chop by each brush side */ + for( i = 0; i < b->numsides; i++ ) + { + /* get brush side and plane */ + s = &b->sides[ i ]; + plane = &mapplanes[ s->planenum ]; + + /* handle coplanar outfacing (don't fog) */ + if( ds->sideRef->side->planenum == s->planenum ) + return qfalse; + + /* handle coplanar infacing (keep inside) */ + if( (ds->sideRef->side->planenum ^ 1) == s->planenum ) + continue; + + /* general case */ + ClipWindingEpsilon( w, plane->normal, plane->dist, ON_EPSILON, &front, &back ); + FreeWinding( w ); + + if( back == NULL ) + { + /* nothing actually contained inside */ + for( j = 0; j < numOutside; j++ ) + FreeWinding( outside[ j ] ); + return qfalse; + } + + if( front != NULL ) + { + if( numOutside == MAX_BRUSH_SIDES ) + Error( "MAX_BRUSH_SIDES" ); + outside[ numOutside ] = front; + numOutside++; + } + + w = back; + } + + /* fixme: celshaded surface fragment errata */ + + /* all of outside fragments become seperate drawsurfs */ + numFogFragments += numOutside; + s = ds->sideRef->side; + for( i = 0; i < numOutside; i++ ) + { + newds = DrawSurfaceForSide( e, ds->mapBrush, s, outside[ i ] ); + newds->fogNum = ds->fogNum; + FreeWinding( outside[ i ] ); + } + + /* ydnar: the old code neglected to snap to 0.125 for the fragment + inside the fog brush, leading to sparklies. this new code does + the right thing and uses the original surface's brush side */ + + /* build a drawsurf for it */ + newds = DrawSurfaceForSide( e, ds->mapBrush, s, w ); + if( newds == NULL ) + return qfalse; + + /* copy new to original */ + ClearSurface( ds ); + memcpy( ds, newds, sizeof( mapDrawSurface_t ) ); + + /* didn't really add a new drawsurface... :) */ + numMapDrawSurfs--; + + /* return ok */ + return qtrue; +} + + + +/* +FogDrawSurfaces() +call after the surface list has been pruned, before tjunction fixing +*/ + +void FogDrawSurfaces( entity_t *e ) +{ + int i, j, k, fogNum; + fog_t *fog; + mapDrawSurface_t *ds; + vec3_t mins, maxs; + int fogged, numFogged; + int numBaseDrawSurfs; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "----- FogDrawSurfs -----\n" ); + + /* reset counters */ + numFogged = 0; + numFogFragments = 0; + + /* walk fog list */ + for( fogNum = 0; fogNum < numMapFogs; fogNum++ ) + { + /* get fog */ + fog = &mapFogs[ fogNum ]; + + /* clip each surface into this, but don't clip any of the resulting fragments to the same brush */ + numBaseDrawSurfs = numMapDrawSurfs; + for( i = 0; i < numBaseDrawSurfs; i++ ) + { + /* get the drawsurface */ + ds = &mapDrawSurfs[ i ]; + + /* no fog? */ + if( ds->shaderInfo->noFog ) + continue; + + /* global fog doesn't have a brush */ + if( fog->brush == NULL ) + { + /* don't re-fog already fogged surfaces */ + if( ds->fogNum >= 0 ) + continue; + fogged = 1; + } + else + { + /* find drawsurface bounds */ + ClearBounds( mins, maxs ); + for( j = 0; j < ds->numVerts; j++ ) + AddPointToBounds( ds->verts[ j ].xyz, mins, maxs ); + + /* check against the fog brush */ + for( k = 0; k < 3; k++ ) + { + if( mins[ k ] > fog->brush->maxs[ k ] ) + break; + if( maxs[ k ] < fog->brush->mins[ k ] ) + break; + } + + /* no intersection? */ + if( k < 3 ) + continue; + + /* ydnar: gs mods: handle the various types of surfaces */ + switch( ds->type ) + { + /* handle brush faces */ + case SURFACE_FACE: + fogged = ChopFaceSurfaceByBrush( e, ds, fog->brush ); + break; + + /* handle patches */ + case SURFACE_PATCH: + fogged = ChopPatchSurfaceByBrush( e, ds, fog->brush ); + break; + + /* handle triangle surfaces (fixme: split triangle surfaces) */ + case SURFACE_TRIANGLES: + case SURFACE_FORCED_META: + case SURFACE_META: + fogged = 1; + break; + + /* no fogging */ + default: + fogged = 0; + break; + } + } + + /* is this surface fogged? */ + if( fogged ) + { + numFogged += fogged; + ds->fogNum = fogNum; + } + } + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d fog polygon fragments\n", numFogFragments ); + Sys_FPrintf( SYS_VRB, "%9d fog patch fragments\n", numFogPatchFragments ); + Sys_FPrintf( SYS_VRB, "%9d fogged drawsurfs\n", numFogged ); +} + + + +/* +FogForPoint() - ydnar +gets the fog number for a point in space +*/ + +int FogForPoint( vec3_t point, float epsilon ) +{ + int fogNum, i, j; + float dot; + qboolean inside; + brush_t *brush; + plane_t *plane; + + + /* start with bogus fog num */ + fogNum = defaultFogNum; + + /* walk the list of fog volumes */ + for( i = 0; i < numMapFogs; i++ ) + { + /* sof2: global fog doesn't reference a brush */ + if( mapFogs[ i ].brush == NULL ) + { + fogNum = i; + continue; + } + + /* get fog brush */ + brush = mapFogs[ i ].brush; + + /* check point against all planes */ + inside = qtrue; + for( j = 0; j < brush->numsides && inside; j++ ) + { + plane = &mapplanes[ brush->sides[ j ].planenum ]; /* note usage of map planes here */ + dot = DotProduct( point, plane->normal ); + dot -= plane->dist; + if( dot > epsilon ) + inside = qfalse; + } + + /* if inside, return the fog num */ + if( inside ) + { + //% Sys_Printf( "FogForPoint: %f, %f, %f in fog %d\n", point[ 0 ], point[ 1 ], point[ 2 ], i ); + return i; + } + } + + /* if the point made it this far, it's not inside any fog volumes (or inside global fog) */ + return fogNum; +} + + + +/* +FogForBounds() - ydnar +gets the fog number for a bounding box +*/ + +int FogForBounds( vec3_t mins, vec3_t maxs, float epsilon ) +{ + int fogNum, i, j; + float highMin, lowMax, volume, bestVolume; + vec3_t fogMins, fogMaxs, overlap; + brush_t *brush; + + + /* start with bogus fog num */ + fogNum = defaultFogNum; + + /* init */ + bestVolume = 0.0f; + + /* walk the list of fog volumes */ + for( i = 0; i < numMapFogs; i++ ) + { + /* sof2: global fog doesn't reference a brush */ + if( mapFogs[ i ].brush == NULL ) + { + fogNum = i; + continue; + } + + /* get fog brush */ + brush = mapFogs[ i ].brush; + + /* get bounds */ + fogMins[ 0 ] = brush->mins[ 0 ] - epsilon; + fogMins[ 1 ] = brush->mins[ 1 ] - epsilon; + fogMins[ 2 ] = brush->mins[ 2 ] - epsilon; + fogMaxs[ 0 ] = brush->maxs[ 0 ] + epsilon; + fogMaxs[ 1 ] = brush->maxs[ 1 ] + epsilon; + fogMaxs[ 2 ] = brush->maxs[ 2 ] + epsilon; + + /* check against bounds */ + for( j = 0; j < 3; j++ ) + { + if( mins[ j ] > fogMaxs[ j ] || maxs[ j ] < fogMins[ j ] ) + break; + highMin = mins[ j ] > fogMins[ j ] ? mins[ j ] : fogMins[ j ]; + lowMax = maxs[ j ] < fogMaxs[ j ] ? maxs[ j ] : fogMaxs[ j ]; + overlap[ j ] = lowMax - highMin; + if( overlap[ j ] < 1.0f ) + overlap[ j ] = 1.0f; + } + + /* no overlap */ + if( j < 3 ) + continue; + + /* get volume */ + volume = overlap[ 0 ] * overlap[ 1 ] * overlap[ 2 ]; + + /* test against best volume */ + if( volume > bestVolume ) + { + bestVolume = volume; + fogNum = i; + } + } + + /* if the point made it this far, it's not inside any fog volumes (or inside global fog) */ + return fogNum; +} + + + +/* +CreateMapFogs() - ydnar +generates a list of map fogs +*/ + +void CreateMapFogs( void ) +{ + int i; + entity_t *entity; + brush_t *brush; + fog_t *fog; + vec3_t invFogDir; + const char *globalFog; + + + /* skip? */ + if( nofog ) + return; + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- CreateMapFogs ---\n" ); + + /* walk entities */ + for( i = 0; i < numEntities; i++ ) + { + /* get entity */ + entity = &entities[ i ]; + + /* walk entity brushes */ + for( brush = entity->brushes; brush != NULL; brush = brush->next ) + { + /* ignore non-fog brushes */ + if( brush->contentShader->fogParms == qfalse ) + continue; + + /* test limit */ + if( numMapFogs >= MAX_MAP_FOGS ) + Error( "Exceeded MAX_MAP_FOGS (%d)", MAX_MAP_FOGS ); + + /* set up fog */ + fog = &mapFogs[ numMapFogs++ ]; + fog->si = brush->contentShader; + fog->brush = brush; + fog->visibleSide = -1; + + /* if shader specifies an explicit direction, then find a matching brush side with an opposed normal */ + if( VectorLength( fog->si->fogDir ) ) + { + /* flip it */ + VectorScale( fog->si->fogDir, -1.0f, invFogDir ); + + /* find the brush side */ + for( i = 0; i < brush->numsides; i++ ) + { + if( VectorCompare( invFogDir, mapplanes[ brush->sides[ i ].planenum ].normal ) ) + { + fog->visibleSide = i; + //% Sys_Printf( "Brush num: %d Side num: %d\n", fog->brushNum, fog->visibleSide ); + break; + } + } + } + } + } + + /* ydnar: global fog */ + globalFog = ValueForKey( &entities[ 0 ], "_fog" ); + if( globalFog[ 0 ] == '\0' ) + globalFog = ValueForKey( &entities[ 0 ], "fog" ); + if( globalFog[ 0 ] != '\0' ) + { + /* test limit */ + if( numMapFogs >= MAX_MAP_FOGS ) + Error( "Exceeded MAX_MAP_FOGS (%d) trying to add global fog", MAX_MAP_FOGS ); + + /* note it */ + Sys_FPrintf( SYS_VRB, "Map has global fog shader %s\n", globalFog ); + + /* set up fog */ + fog = &mapFogs[ numMapFogs++ ]; + fog->si = ShaderInfoForShader( globalFog ); + if( fog->si == NULL ) + Error( "Invalid shader \"%s\" referenced trying to add global fog", globalFog ); + fog->brush = NULL; + fog->visibleSide = -1; + + /* set as default fog */ + defaultFogNum = numMapFogs - 1; + + /* mark all worldspawn brushes as fogged */ + for( brush = entities[ 0 ].brushes; brush != NULL; brush = brush->next ) + ApplySurfaceParm( "fog", &brush->contentFlags, NULL, &brush->compileFlags ); + } + + /* emit some stats */ + Sys_FPrintf( SYS_VRB, "%9d fogs\n", numMapFogs ); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game__null.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game__null.h new file mode 100644 index 00000000..c2f24849 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game__null.h @@ -0,0 +1,98 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME__NULL_H +#define GAME__NULL_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags +are in game_quake3.h + +------------------------------------------------------------------------------- */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + NULL, /* -game x */ + NULL, /* default base game data dir */ + NULL, /* unix home sub-dir */ + NULL, /* magic path word */ + NULL, /* shader directory */ + 0, /* max lightmapped surface verts */ + 0, /* max surface verts */ + 0, /* max surface indexes */ + qfalse, /* flares */ + NULL, /* default flare shader */ + qfalse, /* wolf lighting model? */ + 0, /* lightmap width/height */ + 0, /* lightmap gamma */ + 0, /* lightmap exposure */ + 0, /* lightmap compensate */ + 0, /* lightgrid scale */ + 0, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 0, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 0, /* minimap size */ + 0, /* minimap sharpener */ + 0, /* minimap border */ + qfalse, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + NULL, /* minimap name format */ + NULL, /* bsp file prefix */ + 0, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + NULL, /* bsp load function */ + NULL, /* bsp write function */ + + { + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_darkplaces.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_darkplaces.h new file mode 100644 index 00000000..e91fdb76 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_darkplaces.h @@ -0,0 +1,150 @@ +/* ------------------------------------------------------------------------------- + +Copyright (C) 1999-2006 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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_DARKPLACES_H +#define GAME_DARKPLACES_H + +/* content and surface flags get form quake3 */ + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "darkplaces", /* -game x */ + "id1", /* default base game data dir */ + ".darkplaces ", /* unix home sub-dir */ + "darkplaces", /* magic path word */ + "scripts", /* shader directory */ + 999, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 200.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 0.3f, /* lightgrid scale */ + 0.6f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qtrue, /* disable shader lightstyles hack */ + qtrue, /* keep light entities on bsp */ + 4, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_dq.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_dq.h new file mode 100644 index 00000000..97d2d6d5 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_dq.h @@ -0,0 +1,150 @@ +/* ------------------------------------------------------------------------------- + +Copyright (C) 1999-2006 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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_DQ_H +#define GAME_DQ_H + +/* content and surface flags get form quake3 */ + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "dq", /* -game x */ + "basedq", /* default base game data dir */ + ".dq", /* unix home sub-dir */ + "dq", /* magic path word */ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.2f, /* lightmap gamma */ + 200.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 0.3f, /* lightgrid scale */ + 0.6f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qtrue, /* disable shader lightstyles hack */ + qtrue, /* keep light entities on bsp */ + 4, /* default patchMeta subdivisions tolerance */ + qtrue, /* patch casting enabled */ + qtrue, /* compile deluxemaps */ + 1, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_ef.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_ef.h new file mode 100644 index 00000000..84ea664c --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_ef.h @@ -0,0 +1,210 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_EF_H +#define GAME_EF_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* game flags */ +#define E_CONT_SOLID 1 /* an eye is never valid in a solid */ +#define E_CONT_LAVA 8 +#define E_CONT_SLIME 16 +#define E_CONT_WATER 32 +#define E_CONT_FOG 64 +#define E_CONT_LADDER 128 /* elite force ladder contents */ + +#define E_CONT_AREAPORTAL 0x8000 + +#define E_CONT_PLAYERCLIP 0x10000 +#define E_CONT_MONSTERCLIP 0x20000 +#define E_CONT_SHOTCLIP 0x40000 /* elite force shot clip */ +#define E_CONT_ITEM 0x80000 +#define E_CONT_CLUSTERPORTAL 0x100000 +#define E_CONT_DONOTENTER 0x200000 +#define E_CONT_BOTCLIP 0x400000 + +#define E_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ + +#define E_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ +#define E_CONT_CORPSE 0x4000000 +#define E_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ +#define E_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ +#define E_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ +#define E_CONT_TRIGGER 0x40000000 +#define E_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ + +#define E_SURF_NODAMAGE 0x1 /* never give falling damage */ +#define E_SURF_SLICK 0x2 /* effects game physics */ +#define E_SURF_SKY 0x4 /* lighting from environment map */ +#define E_SURF_LADDER 0x8 +#define E_SURF_NOIMPACT 0x10 /* don't make missile explosions */ +#define E_SURF_NOMARKS 0x20 /* don't leave missile marks */ +#define E_SURF_FLESH 0x40 /* make flesh sounds and effects */ +#define E_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ +#define E_SURF_HINT 0x100 /* make a primary bsp splitter */ +#define E_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ +#define E_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ +#define E_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ +#define E_SURF_METALSTEPS 0x1000 /* clanking footsteps */ +#define E_SURF_NOSTEPS 0x2000 /* no footstep sounds */ +#define E_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ +#define E_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ +#define E_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ +#define E_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ +#define E_SURF_FORCEFIELD 0x40000 /* elite force forcefield brushes */ + +/* ydnar flags */ +#define E_SURF_VERTEXLIT (E_SURF_POINTLIGHT | E_SURF_NOLIGHTMAP) + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "ef", /* -game x */ + "baseef", /* default base game data dir */ + ".ef", /* unix home sub-dir */ + "elite", /* magic path word */ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", E_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", E_CONT_ORIGIN, E_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", E_CONT_AREAPORTAL, E_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", E_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", E_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", E_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, E_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, E_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, E_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, E_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, E_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, E_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, E_CONT_SOLID, E_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", E_CONT_TRIGGER, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", E_CONT_WATER, E_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", E_CONT_SLIME, E_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", E_CONT_LAVA, E_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", E_CONT_PLAYERCLIP, E_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", E_CONT_MONSTERCLIP, E_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "shotclip", E_CONT_SHOTCLIP, E_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", E_CONT_NODROP, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", E_CONT_CLUSTERPORTAL, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", E_CONT_DONOTENTER, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", E_CONT_BOTCLIP, E_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", E_CONT_FOG, E_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, E_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, E_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, E_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, E_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", E_CONT_LADDER, E_CONT_SOLID, E_SURF_LADDER, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodamage", 0, 0, E_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, E_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, E_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, E_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, E_SURF_NODLIGHT, 0, 0, 0 }, + { "forcefield", 0, 0, E_SURF_FORCEFIELD, 0, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_etut.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_etut.h new file mode 100644 index 00000000..8add5bbe --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_etut.h @@ -0,0 +1,280 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_ETUT_H +#define GAME_ETUT_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* game flags */ +#define U_CONT_SOLID 1 /* an eye is never valid in a solid */ +#define U_CONT_LAVA 8 +#define U_CONT_SLIME 16 +#define U_CONT_WATER 32 +#define U_CONT_FOG 64 + +#define U_CONT_AREAPORTAL 0x8000 + +#define U_CONT_PLAYERCLIP 0x10000 +#define U_CONT_MONSTERCLIP 0x20000 +#define U_CONT_TELEPORTER 0x40000 +#define U_CONT_JUMPPAD 0x80000 +#define U_CONT_CLUSTERPORTAL 0x100000 +#define U_CONT_DONOTENTER 0x200000 +#define U_CONT_BOTCLIP 0x400000 + +#define U_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ + +#define U_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ +#define U_CONT_CORPSE 0x4000000 +#define U_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ +#define U_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ +#define U_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ +#define U_CONT_TRIGGER 0x40000000 +#define U_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ + +#define U_SURF_NODAMAGE 0x1 /* never give falling damage */ +#define U_SURF_SLICK 0x2 /* effects game physics */ +#define U_SURF_SKY 0x4 /* lighting from environment map */ +#define U_SURF_LADDER 0x8 +#define U_SURF_NOIMPACT 0x10 /* don't make missile explosions */ +#define U_SURF_NOMARKS 0x20 /* don't leave missile marks */ +#define U_SURF_FLESH 0x40 /* make flesh sounds and effects */ +#define U_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ +#define U_SURF_HINT 0x100 /* make a primary bsp splitter */ +#define U_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ +#define U_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ +#define U_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ +#define U_SURF_METALSTEPS 0x1000 /* clanking footsteps */ +#define U_SURF_NOSTEPS 0x2000 /* no footstep sounds */ +#define U_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ +#define U_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ +#define U_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ +#define U_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ +#define U_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ + +/* ydnar flags */ +#define U_SURF_VERTEXLIT (U_SURF_POINTLIGHT | U_SURF_NOLIGHTMAP) + +/* materials */ +#define U_MAT_MASK 0xFFF00000 /* mask to get the material type */ + +#define U_MAT_NONE 0x00000000 +#define U_MAT_TIN 0x00100000 +#define U_MAT_ALUMINUM 0x00200000 +#define U_MAT_IRON 0x00300000 +#define U_MAT_TITANIUM 0x00400000 +#define U_MAT_STEEL 0x00500000 +#define U_MAT_BRASS 0x00600000 +#define U_MAT_COPPER 0x00700000 +#define U_MAT_CEMENT 0x00800000 +#define U_MAT_ROCK 0x00900000 +#define U_MAT_GRAVEL 0x00A00000 +#define U_MAT_PAVEMENT 0x00B00000 +#define U_MAT_BRICK 0x00C00000 +#define U_MAT_CLAY 0x00D00000 +#define U_MAT_GRASS 0x00E00000 +#define U_MAT_DIRT 0x00F00000 +#define U_MAT_MUD 0x01000000 +#define U_MAT_SNOW 0x01100000 +#define U_MAT_ICE 0x01200000 +#define U_MAT_SAND 0x01300000 +#define U_MAT_CERAMICTILE 0x01400000 +#define U_MAT_LINOLEUM 0x01500000 +#define U_MAT_RUG 0x01600000 +#define U_MAT_PLASTER 0x01700000 +#define U_MAT_PLASTIC 0x01800000 +#define U_MAT_CARDBOARD 0x01900000 +#define U_MAT_HARDWOOD 0x01A00000 +#define U_MAT_SOFTWOOD 0x01B00000 +#define U_MAT_PLANK 0x01C00000 +#define U_MAT_GLASS 0x01D00000 +#define U_MAT_WATER 0x01E00000 +#define U_MAT_STUCCO 0x01F00000 + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "etut", /* -game x */ + "etut", /* default base game data dir */ + ".etwolf", /* unix home sub-dir */ + "et", /* magic path word */ + "scripts", /* shader directory */ + 1024, /* max lightmapped surface verts */ + 1024, /* max surface verts */ + 6144, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 2.2f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 47, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", U_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", U_CONT_ORIGIN, U_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", U_CONT_AREAPORTAL, U_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", U_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", U_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", U_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, U_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, U_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, U_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, U_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, U_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, U_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, U_CONT_SOLID, U_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", U_CONT_TRIGGER, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", U_CONT_WATER, U_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", U_CONT_SLIME, U_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", U_CONT_LAVA, U_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", U_CONT_PLAYERCLIP, U_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", U_CONT_MONSTERCLIP, U_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", U_CONT_NODROP, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", U_CONT_CLUSTERPORTAL, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", U_CONT_DONOTENTER, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", U_CONT_BOTCLIP, U_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", U_CONT_FOG, U_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, U_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, U_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, U_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, U_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, U_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, U_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, U_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, U_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, U_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, U_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, U_SURF_DUST, 0, 0, 0 }, + + + /* materials */ + { "*mat_none", 0, 0, U_MAT_NONE, U_MAT_MASK, 0, 0 }, + { "*mat_tin", 0, 0, U_MAT_TIN, U_MAT_MASK, 0, 0 }, + { "*mat_aluminum", 0, 0, U_MAT_ALUMINUM, U_MAT_MASK, 0, 0 }, + { "*mat_iron", 0, 0, U_MAT_IRON, U_MAT_MASK, 0, 0 }, + { "*mat_titanium", 0, 0, U_MAT_TITANIUM, U_MAT_MASK, 0, 0 }, + { "*mat_steel", 0, 0, U_MAT_STEEL, U_MAT_MASK, 0, 0 }, + { "*mat_brass", 0, 0, U_MAT_BRASS, U_MAT_MASK, 0, 0 }, + { "*mat_copper", 0, 0, U_MAT_COPPER, U_MAT_MASK, 0, 0 }, + { "*mat_cement", 0, 0, U_MAT_CEMENT, U_MAT_MASK, 0, 0 }, + { "*mat_rock", 0, 0, U_MAT_ROCK, U_MAT_MASK, 0, 0 }, + { "*mat_gravel", 0, 0, U_MAT_GRAVEL, U_MAT_MASK, 0, 0 }, + { "*mat_pavement", 0, 0, U_MAT_PAVEMENT, U_MAT_MASK, 0, 0 }, + { "*mat_brick", 0, 0, U_MAT_BRICK, U_MAT_MASK, 0, 0 }, + { "*mat_clay", 0, 0, U_MAT_CLAY, U_MAT_MASK, 0, 0 }, + { "*mat_grass", 0, 0, U_MAT_GRASS, U_MAT_MASK, 0, 0 }, + { "*mat_dirt", 0, 0, U_MAT_DIRT, U_MAT_MASK, 0, 0 }, + { "*mat_mud", 0, 0, U_MAT_MUD, U_MAT_MASK, 0, 0 }, + { "*mat_snow", 0, 0, U_MAT_SNOW, U_MAT_MASK, 0, 0 }, + { "*mat_ice", 0, 0, U_MAT_ICE, U_MAT_MASK, 0, 0 }, + { "*mat_sand", 0, 0, U_MAT_SAND, U_MAT_MASK, 0, 0 }, + { "*mat_ceramic", 0, 0, U_MAT_CERAMICTILE, U_MAT_MASK, 0, 0 }, + { "*mat_ceramictile", 0, 0, U_MAT_CERAMICTILE, U_MAT_MASK, 0, 0 }, + { "*mat_linoleum", 0, 0, U_MAT_LINOLEUM, U_MAT_MASK, 0, 0 }, + { "*mat_rug", 0, 0, U_MAT_RUG, U_MAT_MASK, 0, 0 }, + { "*mat_plaster", 0, 0, U_MAT_PLASTER, U_MAT_MASK, 0, 0 }, + { "*mat_plastic", 0, 0, U_MAT_PLASTIC, U_MAT_MASK, 0, 0 }, + { "*mat_cardboard", 0, 0, U_MAT_CARDBOARD, U_MAT_MASK, 0, 0 }, + { "*mat_hardwood", 0, 0, U_MAT_HARDWOOD, U_MAT_MASK, 0, 0 }, + { "*mat_softwood", 0, 0, U_MAT_SOFTWOOD, U_MAT_MASK, 0, 0 }, + { "*mat_plank", 0, 0, U_MAT_PLANK, U_MAT_MASK, 0, 0 }, + { "*mat_glass", 0, 0, U_MAT_GLASS, U_MAT_MASK, 0, 0 }, + { "*mat_water", 0, 0, U_MAT_WATER, U_MAT_MASK, 0, 0 }, + { "*mat_stucco", 0, 0, U_MAT_STUCCO, U_MAT_MASK, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_ja.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_ja.h new file mode 100644 index 00000000..3d25129e --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_ja.h @@ -0,0 +1,204 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_JA_H +#define GAME_JA_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* this file must be included *after* game_sof2.h and game_jk2.h because they share defines! */ + +#define JA_CONT_INSIDE 0x10000000 /* jedi academy 'inside' */ +#define JA_SURF_FORCESIGHT 0x02000000 /* jedi academy 'forcesight' */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "ja", /* -game x */ + "base", /* default base game data dir */ + ".ja", /* unix home sub-dir */ + "GameData", /* magic path word */ + "shaders", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qtrue, /* flares */ + "gfx/misc/flare", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "RBSP", /* bsp file prefix */ + 1, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadRBSPFile, /* bsp load function */ + WriteRBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", S_CONT_SOLID | S_CONT_OPAQUE, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", 0, S_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", S_CONT_TRANSLUCENT, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", S_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", S_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", 0, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, 0, 0, C_HINT, 0 }, + { "nodraw", 0, 0, S_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, 0, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, 0, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, 0, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, 0, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, S_CONT_SOLID, 0, 0, 0, C_SOLID }, + { "nonopaque", 0, S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, 0 }, /* setting trans ok? */ + + { "trigger", S_CONT_TRIGGER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", S_CONT_WATER, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", S_CONT_SLIME, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", S_CONT_LAVA, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "shotclip", S_CONT_SHOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* setting trans/detail ok? */ + { "playerclip", S_CONT_PLAYERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", S_CONT_MONSTERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", S_CONT_NODROP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "terrain", S_CONT_TERRAIN, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "ladder", S_CONT_LADDER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "abseil", S_CONT_ABSEIL, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "outside", S_CONT_OUTSIDE, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "botclip", S_CONT_BOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "fog", S_CONT_FOG, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_FOG | C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* nonopaque? */ + { "sky", 0, 0, S_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, S_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, S_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, S_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "nodamage", 0, 0, S_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, S_SURF_METALSTEPS, 0, 0, 0 }, + { "nosteps", 0, 0, S_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, S_SURF_NODLIGHT, 0, 0, 0 }, + { "nomiscents", 0, 0, S_SURF_NOMISCENTS, 0, 0, 0 }, + { "forcefield", 0, 0, S_SURF_FORCEFIELD, 0, 0, 0 }, + + /* jedi academy */ + { "inside", JA_CONT_INSIDE, 0, 0, 0, 0, 0 }, + { "forcesight", 0, 0, JA_SURF_FORCESIGHT, 0, 0, 0 }, + + /* materials */ + { "*mat_none", 0, 0, S_MAT_NONE, S_MAT_MASK, 0, 0 }, + { "*mat_solidwood", 0, 0, S_MAT_SOLIDWOOD, S_MAT_MASK, 0, 0 }, + { "*mat_hollowwood", 0, 0, S_MAT_HOLLOWWOOD, S_MAT_MASK, 0, 0 }, + { "*mat_solidmetal", 0, 0, S_MAT_SOLIDMETAL, S_MAT_MASK, 0, 0 }, + { "*mat_hollowmetal", 0, 0, S_MAT_HOLLOWMETAL, S_MAT_MASK, 0, 0 }, + { "*mat_shortgrass", 0, 0, S_MAT_SHORTGRASS, S_MAT_MASK, 0, 0 }, + { "*mat_longgrass", 0, 0, S_MAT_LONGGRASS, S_MAT_MASK, 0, 0 }, + { "*mat_dirt", 0, 0, S_MAT_DIRT, S_MAT_MASK, 0, 0 }, + { "*mat_sand", 0, 0, S_MAT_SAND, S_MAT_MASK, 0, 0 }, + { "*mat_gravel", 0, 0, S_MAT_GRAVEL, S_MAT_MASK, 0, 0 }, + { "*mat_glass", 0, 0, S_MAT_GLASS, S_MAT_MASK, 0, 0 }, + { "*mat_concrete", 0, 0, S_MAT_CONCRETE, S_MAT_MASK, 0, 0 }, + { "*mat_marble", 0, 0, S_MAT_MARBLE, S_MAT_MASK, 0, 0 }, + { "*mat_water", 0, 0, S_MAT_WATER, S_MAT_MASK, 0, 0 }, + { "*mat_snow", 0, 0, S_MAT_SNOW, S_MAT_MASK, 0, 0 }, + { "*mat_ice", 0, 0, S_MAT_ICE, S_MAT_MASK, 0, 0 }, + { "*mat_flesh", 0, 0, S_MAT_FLESH, S_MAT_MASK, 0, 0 }, + { "*mat_mud", 0, 0, S_MAT_MUD, S_MAT_MASK, 0, 0 }, + { "*mat_bpglass", 0, 0, S_MAT_BPGLASS, S_MAT_MASK, 0, 0 }, + { "*mat_dryleaves", 0, 0, S_MAT_DRYLEAVES, S_MAT_MASK, 0, 0 }, + { "*mat_greenleaves", 0, 0, S_MAT_GREENLEAVES, S_MAT_MASK, 0, 0 }, + { "*mat_fabric", 0, 0, S_MAT_FABRIC, S_MAT_MASK, 0, 0 }, + { "*mat_canvas", 0, 0, S_MAT_CANVAS, S_MAT_MASK, 0, 0 }, + { "*mat_rock", 0, 0, S_MAT_ROCK, S_MAT_MASK, 0, 0 }, + { "*mat_rubber", 0, 0, S_MAT_RUBBER, S_MAT_MASK, 0, 0 }, + { "*mat_plastic", 0, 0, S_MAT_PLASTIC, S_MAT_MASK, 0, 0 }, + { "*mat_tiles", 0, 0, S_MAT_TILES, S_MAT_MASK, 0, 0 }, + { "*mat_carpet", 0, 0, S_MAT_CARPET, S_MAT_MASK, 0, 0 }, + { "*mat_plaster", 0, 0, S_MAT_PLASTER, S_MAT_MASK, 0, 0 }, + { "*mat_shatterglass", 0, 0, S_MAT_SHATTERGLASS, S_MAT_MASK, 0, 0 }, + { "*mat_armor", 0, 0, S_MAT_ARMOR, S_MAT_MASK, 0, 0 }, + { "*mat_computer", 0, 0, S_MAT_COMPUTER, S_MAT_MASK, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_jk2.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_jk2.h new file mode 100644 index 00000000..056baf01 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_jk2.h @@ -0,0 +1,198 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_JK2_H +#define GAME_JK2_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* this file must be included *after* game_sof2.h because it shares defines! */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "jk2", /* -game x */ + "base", /* default base game data dir */ + ".jk2", /* unix home sub-dir */ + "GameData", /* magic path word */ + "shaders", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qtrue, /* flares */ + "gfx/misc/flare", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "RBSP", /* bsp file prefix */ + 1, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadRBSPFile, /* bsp load function */ + WriteRBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", S_CONT_SOLID | S_CONT_OPAQUE, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", 0, S_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", S_CONT_TRANSLUCENT, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", S_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", S_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", 0, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, 0, 0, C_HINT, 0 }, + { "nodraw", 0, 0, S_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, 0, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, 0, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, 0, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, 0, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, S_CONT_SOLID, 0, 0, 0, C_SOLID }, + { "nonopaque", 0, S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, 0 }, /* setting trans ok? */ + + { "trigger", S_CONT_TRIGGER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", S_CONT_WATER, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", S_CONT_SLIME, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", S_CONT_LAVA, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "shotclip", S_CONT_SHOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* setting trans/detail ok? */ + { "playerclip", S_CONT_PLAYERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", S_CONT_MONSTERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", S_CONT_NODROP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "terrain", S_CONT_TERRAIN, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "ladder", S_CONT_LADDER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "abseil", S_CONT_ABSEIL, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "outside", S_CONT_OUTSIDE, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "botclip", S_CONT_BOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "fog", S_CONT_FOG, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_FOG | C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* nonopaque? */ + { "sky", 0, 0, S_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, S_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, S_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, S_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "nodamage", 0, 0, S_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, S_SURF_METALSTEPS, 0, 0, 0 }, + { "nosteps", 0, 0, S_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, S_SURF_NODLIGHT, 0, 0, 0 }, + { "nomiscents", 0, 0, S_SURF_NOMISCENTS, 0, 0, 0 }, + { "forcefield", 0, 0, S_SURF_FORCEFIELD, 0, 0, 0 }, + + + /* materials */ + { "*mat_none", 0, 0, S_MAT_NONE, S_MAT_MASK, 0, 0 }, + { "*mat_solidwood", 0, 0, S_MAT_SOLIDWOOD, S_MAT_MASK, 0, 0 }, + { "*mat_hollowwood", 0, 0, S_MAT_HOLLOWWOOD, S_MAT_MASK, 0, 0 }, + { "*mat_solidmetal", 0, 0, S_MAT_SOLIDMETAL, S_MAT_MASK, 0, 0 }, + { "*mat_hollowmetal", 0, 0, S_MAT_HOLLOWMETAL, S_MAT_MASK, 0, 0 }, + { "*mat_shortgrass", 0, 0, S_MAT_SHORTGRASS, S_MAT_MASK, 0, 0 }, + { "*mat_longgrass", 0, 0, S_MAT_LONGGRASS, S_MAT_MASK, 0, 0 }, + { "*mat_dirt", 0, 0, S_MAT_DIRT, S_MAT_MASK, 0, 0 }, + { "*mat_sand", 0, 0, S_MAT_SAND, S_MAT_MASK, 0, 0 }, + { "*mat_gravel", 0, 0, S_MAT_GRAVEL, S_MAT_MASK, 0, 0 }, + { "*mat_glass", 0, 0, S_MAT_GLASS, S_MAT_MASK, 0, 0 }, + { "*mat_concrete", 0, 0, S_MAT_CONCRETE, S_MAT_MASK, 0, 0 }, + { "*mat_marble", 0, 0, S_MAT_MARBLE, S_MAT_MASK, 0, 0 }, + { "*mat_water", 0, 0, S_MAT_WATER, S_MAT_MASK, 0, 0 }, + { "*mat_snow", 0, 0, S_MAT_SNOW, S_MAT_MASK, 0, 0 }, + { "*mat_ice", 0, 0, S_MAT_ICE, S_MAT_MASK, 0, 0 }, + { "*mat_flesh", 0, 0, S_MAT_FLESH, S_MAT_MASK, 0, 0 }, + { "*mat_mud", 0, 0, S_MAT_MUD, S_MAT_MASK, 0, 0 }, + { "*mat_bpglass", 0, 0, S_MAT_BPGLASS, S_MAT_MASK, 0, 0 }, + { "*mat_dryleaves", 0, 0, S_MAT_DRYLEAVES, S_MAT_MASK, 0, 0 }, + { "*mat_greenleaves", 0, 0, S_MAT_GREENLEAVES, S_MAT_MASK, 0, 0 }, + { "*mat_fabric", 0, 0, S_MAT_FABRIC, S_MAT_MASK, 0, 0 }, + { "*mat_canvas", 0, 0, S_MAT_CANVAS, S_MAT_MASK, 0, 0 }, + { "*mat_rock", 0, 0, S_MAT_ROCK, S_MAT_MASK, 0, 0 }, + { "*mat_rubber", 0, 0, S_MAT_RUBBER, S_MAT_MASK, 0, 0 }, + { "*mat_plastic", 0, 0, S_MAT_PLASTIC, S_MAT_MASK, 0, 0 }, + { "*mat_tiles", 0, 0, S_MAT_TILES, S_MAT_MASK, 0, 0 }, + { "*mat_carpet", 0, 0, S_MAT_CARPET, S_MAT_MASK, 0, 0 }, + { "*mat_plaster", 0, 0, S_MAT_PLASTER, S_MAT_MASK, 0, 0 }, + { "*mat_shatterglass", 0, 0, S_MAT_SHATTERGLASS, S_MAT_MASK, 0, 0 }, + { "*mat_armor", 0, 0, S_MAT_ARMOR, S_MAT_MASK, 0, 0 }, + { "*mat_computer", 0, 0, S_MAT_COMPUTER, S_MAT_MASK, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_nexuiz.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_nexuiz.h new file mode 100644 index 00000000..4d496c33 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_nexuiz.h @@ -0,0 +1,159 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_NEXUIZ_H +#define GAME_NEXUIZ_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags +are in game_quake3.h + +------------------------------------------------------------------------------- */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "nexuiz", /* -game x */ + "data", /* default base game data dir */ + ".nexuiz", /* unix home sub-dir */ + "nexuiz", /* magic path word */ + "scripts", /* shader directory */ + 999, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qtrue, /* disable shader lightstyles hack */ + qtrue, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 1.0f/66.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "../gfx/%s_mini.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_prophecy.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_prophecy.h new file mode 100644 index 00000000..60e299d3 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_prophecy.h @@ -0,0 +1,150 @@ +/* ------------------------------------------------------------------------------- + +Copyright (C) 1999-2006 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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_PROPHECY_H +#define GAME_PROPHECY_H + +/* content and surface flags get form quake3 */ + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "prophecy", /* -game x */ + "base", /* default base game data dir */ + ".prophecy", /* unix home sub-dir */ + "prophecy", /* magic path word */ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 200.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 0.4f, /* lightgrid scale */ + 0.6f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qtrue, /* disable shader lightstyles hack */ + qtrue, /* keep light entities on bsp */ + 4, /* default patchMeta subdivisions tolerance */ + qtrue, /* patch casting enabled */ + qtrue, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_qfusion.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_qfusion.h new file mode 100644 index 00000000..7645ad0a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_qfusion.h @@ -0,0 +1,211 @@ +/* ------------------------------------------------------------------------------- + +This code is based on source provided under the terms of the Id Software +LIMITED USE SOFTWARE LICENSE AGREEMENT, a copy of which is included with the +GtkRadiant sources (see LICENSE_ID). If you did not receive a copy of +LICENSE_ID, please contact Id Software immediately at info@idsoftware.com. + +All changes and additions to the original source which have been developed by +other contributors (see CONTRIBUTORS) are provided under the terms of the +license the contributors choose (see LICENSE), to the extent permitted by the +LICENSE_ID. If you did not receive a copy of the contributor license, +please contact the GtkRadiant maintainers at info@gtkradiant.com immediately. + +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. + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_QFUSION_H +#define GAME_QFUSION_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* game flags */ +#define F_CONT_SOLID 1 /* an eye is never valid in a solid */ +#define F_CONT_LAVA 8 +#define F_CONT_SLIME 16 +#define F_CONT_WATER 32 +#define F_CONT_FOG 64 + +#define F_CONT_AREAPORTAL 0x8000 + +#define F_CONT_PLAYERCLIP 0x10000 +#define F_CONT_MONSTERCLIP 0x20000 +#define F_CONT_TELEPORTER 0x40000 +#define F_CONT_JUMPPAD 0x80000 +#define F_CONT_CLUSTERPORTAL 0x100000 +#define F_CONT_DONOTENTER 0x200000 +#define F_CONT_BOTCLIP 0x400000 + +#define F_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ + +#define F_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ +#define F_CONT_CORPSE 0x4000000 +#define F_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ +#define F_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ +#define F_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ +#define F_CONT_TRIGGER 0x40000000 +#define F_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ + +#define F_SURF_NODAMAGE 0x1 /* never give falling damage */ +#define F_SURF_SLICK 0x2 /* effects game physics */ +#define F_SURF_SKY 0x4 /* lighting from environment map */ +#define F_SURF_LADDER 0x8 +#define F_SURF_NOIMPACT 0x10 /* don't make missile explosions */ +#define F_SURF_NOMARKS 0x20 /* don't leave missile marks */ +#define F_SURF_FLESH 0x40 /* make flesh sounds and effects */ +#define F_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ +#define F_SURF_HINT 0x100 /* make a primary bsp splitter */ +#define F_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ +#define F_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ +#define F_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ +#define F_SURF_METALSTEPS 0x1000 /* clanking footsteps */ +#define F_SURF_NOSTEPS 0x2000 /* no footstep sounds */ +#define F_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ +#define F_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ +#define F_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ +#define F_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ +#define F_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ + +/* ydnar flags */ +#define F_SURF_VERTEXLIT (F_SURF_POINTLIGHT | F_SURF_NOLIGHTMAP) + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "qfusion", /* -game x */ + "baseq3", /* default base game data dir */ + ".q3a", /* unix home sub-dir */ + "quake", /* magic path word */ + "scripts", /* shader directory */ + 2048, /* max lightmapped surface verts */ + 2048, /* max surface verts */ + 12288, /* max surface indexes */ + qtrue, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 512, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qtrue, /* light angle attenuation uses half-lambert curve */ + qtrue, /* disable shader lightstyles hack */ + qtrue, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qtrue, /* patch casting enabled */ + qtrue, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 256, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_WHITE, /* minimap mode */ + "../minimaps/%s.tga", /* minimap name format */ + "FBSP", /* bsp file prefix */ + 1, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadRBSPFile, /* bsp load function */ + WriteRBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", F_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", F_CONT_ORIGIN, F_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", F_CONT_AREAPORTAL, F_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", F_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", F_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", F_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, F_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, F_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, F_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, F_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, F_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, F_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, F_CONT_SOLID, F_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", F_CONT_TRIGGER, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", F_CONT_WATER, F_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", F_CONT_SLIME, F_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", F_CONT_LAVA, F_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", F_CONT_PLAYERCLIP, F_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", F_CONT_MONSTERCLIP, F_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", F_CONT_NODROP, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", F_CONT_CLUSTERPORTAL, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", F_CONT_DONOTENTER, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", F_CONT_BOTCLIP, F_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", F_CONT_FOG, F_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, F_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, F_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, F_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, F_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, F_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, F_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, F_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, F_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, F_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, F_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, F_SURF_DUST, 0, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_quake3.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_quake3.h new file mode 100644 index 00000000..98d4c4b8 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_quake3.h @@ -0,0 +1,207 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_QUAKE3_H +#define GAME_QUAKE3_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* game flags */ +#define Q_CONT_SOLID 1 /* an eye is never valid in a solid */ +#define Q_CONT_LAVA 8 +#define Q_CONT_SLIME 16 +#define Q_CONT_WATER 32 +#define Q_CONT_FOG 64 + +#define Q_CONT_AREAPORTAL 0x8000 + +#define Q_CONT_PLAYERCLIP 0x10000 +#define Q_CONT_MONSTERCLIP 0x20000 +#define Q_CONT_TELEPORTER 0x40000 +#define Q_CONT_JUMPPAD 0x80000 +#define Q_CONT_CLUSTERPORTAL 0x100000 +#define Q_CONT_DONOTENTER 0x200000 +#define Q_CONT_BOTCLIP 0x400000 + +#define Q_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ + +#define Q_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ +#define Q_CONT_CORPSE 0x4000000 +#define Q_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ +#define Q_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ +#define Q_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ +#define Q_CONT_TRIGGER 0x40000000 +#define Q_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ + +#define Q_SURF_NODAMAGE 0x1 /* never give falling damage */ +#define Q_SURF_SLICK 0x2 /* effects game physics */ +#define Q_SURF_SKY 0x4 /* lighting from environment map */ +#define Q_SURF_LADDER 0x8 +#define Q_SURF_NOIMPACT 0x10 /* don't make missile explosions */ +#define Q_SURF_NOMARKS 0x20 /* don't leave missile marks */ +#define Q_SURF_FLESH 0x40 /* make flesh sounds and effects */ +#define Q_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ +#define Q_SURF_HINT 0x100 /* make a primary bsp splitter */ +#define Q_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ +#define Q_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ +#define Q_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ +#define Q_SURF_METALSTEPS 0x1000 /* clanking footsteps */ +#define Q_SURF_NOSTEPS 0x2000 /* no footstep sounds */ +#define Q_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ +#define Q_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ +#define Q_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ +#define Q_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ +#define Q_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ + +/* ydnar flags */ +#define Q_SURF_VERTEXLIT (Q_SURF_POINTLIGHT | Q_SURF_NOLIGHTMAP) + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "quake3", /* -game x */ + "baseq3", /* default base game data dir */ + ".q3a", /* unix home sub-dir */ + "quake", /* magic path word */ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_quakelive.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_quakelive.h new file mode 100644 index 00000000..1a509272 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_quakelive.h @@ -0,0 +1,159 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_QUAKELIVE_H +#define GAME_QUAKELIVE_H + + + +/* ------------------------------------------------------------------------------- + +no content and surface flags here +they are the same as Quake 3's +(this file must be included AFTER game_quake3.h) + +------------------------------------------------------------------------------- */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "quakelive", /* -game x */ + "baseq3", /* default base game data dir (FIXME what does quake live really use?) */ + ".q3a", /* unix home sub-dir (FIXME what does quake live really use?) */ + "quake", /* magic path word (FIXME where does quake live install to?) */ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 47, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_reaction.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_reaction.h new file mode 100644 index 00000000..c81e7245 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_reaction.h @@ -0,0 +1,194 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_REACTION_H +#define GAME_REACTION_H + + + +/* ------------------------------------------------------------------------------- + +inherit content and surface flags from game_quake3.h +(this file must be included AFTER game_quake3.h) + +Additional surface flags follow. These were given to me (Rambetter) by TTI from the Reaction team. +Note that some of these values have more than one bit set. I'm not sure how Reaction is using these +bits, but this is what I got from TTI. + +------------------------------------------------------------------------------- */ + +#define REACTION_SURF_GRAVEL 0x80000 +#define REACTION_SURF_WOOD 0x81000 +#define REACTION_SURF_CARPET 0x100000 +#define REACTION_SURF_METAL2 0x101000 +#define REACTION_SURF_GLASS 0x180000 +#define REACTION_SURF_GRASS 0x181000 +#define REACTION_SURF_SNOW 0x200000 +#define REACTION_SURF_MUD 0x201000 +#define REACTION_SURF_WOOD2 0x280000 +#define REACTION_SURF_HARDMETAL 0x281000 +#define REACTION_SURF_LEAVES 0x300000 +#define REACTION_SURF_CEMENT 0x301000 +#define REACTION_SURF_MARBLE 0x380000 +#define REACTION_SURF_SNOW2 0x381000 +#define REACTION_SURF_HARDSTEPS 0x400000 +#define REACTION_SURF_SAND 0x401000 + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "reaction", /* -game x */ + "Boomstick", /* default base game data dir */ + ".Reaction", /* unix home sub-dir */ + "reaction", /* magic path word */ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + { "rq3_gravel", 0, 0, REACTION_SURF_GRAVEL, 0, 0, 0 }, + { "rq3_wood", 0, 0, REACTION_SURF_WOOD, 0, 0, 0 }, + { "rq3_carpet", 0, 0, REACTION_SURF_CARPET, 0, 0, 0 }, + { "rq3_metal2", 0, 0, REACTION_SURF_METAL2, 0, 0, 0 }, + { "rq3_glass", 0, 0, REACTION_SURF_GLASS, 0, 0, 0 }, + { "rq3_grass", 0, 0, REACTION_SURF_GRASS, 0, 0, 0 }, + { "rq3_snow", 0, 0, REACTION_SURF_SNOW, 0, 0, 0 }, + { "rq3_mud", 0, 0, REACTION_SURF_MUD, 0, 0, 0 }, + { "rq3_wood2", 0, 0, REACTION_SURF_WOOD2, 0, 0, 0 }, + { "rq3_hardmetal", 0, 0, REACTION_SURF_HARDMETAL, 0, 0, 0 }, + { "rq3_leaves", 0, 0, REACTION_SURF_LEAVES, 0, 0, 0 }, + { "rq3_cement", 0, 0, REACTION_SURF_CEMENT, 0, 0, 0 }, + { "rq3_marble", 0, 0, REACTION_SURF_MARBLE, 0, 0, 0 }, + { "rq3_snow2", 0, 0, REACTION_SURF_SNOW2, 0, 0, 0 }, + { "rq3_hardsteps", 0, 0, REACTION_SURF_HARDSTEPS, 0, 0, 0 }, + { "rq3_sand", 0, 0, REACTION_SURF_SAND, 0, 0, 0 }, + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_sof2.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_sof2.h new file mode 100644 index 00000000..931ec69c --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_sof2.h @@ -0,0 +1,273 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_SOF2_H +#define GAME_SOF2_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* thanks to the gracious fellows at raven */ +#define S_CONT_SOLID 0x00000001 /* Default setting. An eye is never valid in a solid */ +#define S_CONT_LAVA 0x00000002 +#define S_CONT_WATER 0x00000004 +#define S_CONT_FOG 0x00000008 +#define S_CONT_PLAYERCLIP 0x00000010 +#define S_CONT_MONSTERCLIP 0x00000020 +#define S_CONT_BOTCLIP 0x00000040 +#define S_CONT_SHOTCLIP 0x00000080 +#define S_CONT_BODY 0x00000100 /* should never be on a brush, only in game */ +#define S_CONT_CORPSE 0x00000200 /* should never be on a brush, only in game */ +#define S_CONT_TRIGGER 0x00000400 +#define S_CONT_NODROP 0x00000800 /* don't leave bodies or items (death fog, lava) */ +#define S_CONT_TERRAIN 0x00001000 /* volume contains terrain data */ +#define S_CONT_LADDER 0x00002000 +#define S_CONT_ABSEIL 0x00004000 /* used like ladder to define where an NPC can abseil */ +#define S_CONT_OPAQUE 0x00008000 /* defaults to on, when off, solid can be seen through */ +#define S_CONT_OUTSIDE 0x00010000 /* volume is considered to be in the outside (i.e. not indoors) */ +#define S_CONT_SLIME 0x00020000 /* don't be fooled. it may SAY "slime" but it really means "projectileclip" */ +#define S_CONT_LIGHTSABER 0x00040000 +#define S_CONT_TELEPORTER 0x00080000 +#define S_CONT_ITEM 0x00100000 +#define S_CONT_DETAIL 0x08000000 /* brushes not used for the bsp */ +#define S_CONT_TRANSLUCENT 0x80000000 /* don't consume surface fragments inside */ + +#define S_SURF_SKY 0x00002000 /* lighting from environment map */ +#define S_SURF_SLICK 0x00004000 /* affects game physics */ +#define S_SURF_METALSTEPS 0x00008000 /* chc needs this since we use same tools */ +#define S_SURF_FORCEFIELD 0x00010000 /* chc */ +#define S_SURF_NODAMAGE 0x00040000 /* never give falling damage */ +#define S_SURF_NOIMPACT 0x00080000 /* don't make missile explosions */ +#define S_SURF_NOMARKS 0x00100000 /* don't leave missile marks */ +#define S_SURF_NODRAW 0x00200000 /* don't generate a drawsurface at all */ +#define S_SURF_NOSTEPS 0x00400000 /* no footstep sounds */ +#define S_SURF_NODLIGHT 0x00800000 /* don't dlight even if solid (solid lava, skies) */ +#define S_SURF_NOMISCENTS 0x01000000 /* no client models allowed on this surface */ + +#define S_SURF_PATCH 0x80000000 /* mark this face as a patch(editor only) */ + +/* materials */ +#define S_MAT_BITS 5 +#define S_MAT_MASK 0x1f /* mask to get the material type */ + +#define S_MAT_NONE 0 /* for when the artist hasn't set anything up =) */ +#define S_MAT_SOLIDWOOD 1 /* freshly cut timber */ +#define S_MAT_HOLLOWWOOD 2 /* termite infested creaky wood */ +#define S_MAT_SOLIDMETAL 3 /* solid girders */ +#define S_MAT_HOLLOWMETAL 4 /* hollow metal machines */ +#define S_MAT_SHORTGRASS 5 /* manicured lawn */ +#define S_MAT_LONGGRASS 6 /* long jungle grass */ +#define S_MAT_DIRT 7 /* hard mud */ +#define S_MAT_SAND 8 /* sandy beach */ +#define S_MAT_GRAVEL 9 /* lots of small stones */ +#define S_MAT_GLASS 10 +#define S_MAT_CONCRETE 11 /* hardened concrete pavement */ +#define S_MAT_MARBLE 12 /* marble floors */ +#define S_MAT_WATER 13 /* light covering of water on a surface */ +#define S_MAT_SNOW 14 /* freshly laid snow */ +#define S_MAT_ICE 15 /* packed snow/solid ice */ +#define S_MAT_FLESH 16 /* hung meat, corpses in the world */ +#define S_MAT_MUD 17 /* wet soil */ +#define S_MAT_BPGLASS 18 /* bulletproof glass */ +#define S_MAT_DRYLEAVES 19 /* dried up leaves on the floor */ +#define S_MAT_GREENLEAVES 20 /* fresh leaves still on a tree */ +#define S_MAT_FABRIC 21 /* Cotton sheets */ +#define S_MAT_CANVAS 22 /* tent material */ +#define S_MAT_ROCK 23 +#define S_MAT_RUBBER 24 /* hard tire like rubber */ +#define S_MAT_PLASTIC 25 +#define S_MAT_TILES 26 /* tiled floor */ +#define S_MAT_CARPET 27 /* lush carpet */ +#define S_MAT_PLASTER 28 /* drywall style plaster */ +#define S_MAT_SHATTERGLASS 29 /* glass with the Crisis Zone style shattering */ +#define S_MAT_ARMOR 30 /* body armor */ +#define S_MAT_COMPUTER 31 /* computers/electronic equipment */ +#define S_MAT_LAST 32 /* number of materials */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "sof2", /* -game x */ + "base", /* default base game data dir */ + ".sof2", /* unix home sub-dir */ + "soldier", /* magic path word */ + "shaders", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qtrue, /* flares */ + "gfx/misc/lens_flare", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "RBSP", /* bsp file prefix */ + 1, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadRBSPFile, /* bsp load function */ + WriteRBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", S_CONT_SOLID | S_CONT_OPAQUE, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", 0, S_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", S_CONT_TRANSLUCENT, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", S_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", S_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", 0, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, 0, 0, C_HINT, 0 }, + { "nodraw", 0, 0, S_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, 0, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, 0, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, 0, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, 0, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, S_CONT_SOLID, 0, 0, 0, C_SOLID }, + { "nonopaque", 0, S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, 0 }, /* setting trans ok? */ + + { "trigger", S_CONT_TRIGGER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", S_CONT_WATER, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", S_CONT_SLIME, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", S_CONT_LAVA, S_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "shotclip", S_CONT_SHOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* setting trans/detail ok? */ + { "playerclip", S_CONT_PLAYERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", S_CONT_MONSTERCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", S_CONT_NODROP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "terrain", S_CONT_TERRAIN, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "ladder", S_CONT_LADDER, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "abseil", S_CONT_ABSEIL, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "outside", S_CONT_OUTSIDE, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "botclip", S_CONT_BOTCLIP, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + + { "fog", S_CONT_FOG, S_CONT_SOLID | S_CONT_OPAQUE, 0, 0, C_FOG | C_DETAIL | C_TRANSLUCENT, C_SOLID }, /* nonopaque? */ + { "sky", 0, 0, S_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, S_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, S_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, S_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "nodamage", 0, 0, S_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, S_SURF_METALSTEPS, 0, 0, 0 }, + { "nosteps", 0, 0, S_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, S_SURF_NODLIGHT, 0, 0, 0 }, + { "nomiscents", 0, 0, S_SURF_NOMISCENTS, 0, 0, 0 }, + { "forcefield", 0, 0, S_SURF_FORCEFIELD, 0, 0, 0 }, + + + /* materials */ + { "*mat_none", 0, 0, S_MAT_NONE, S_MAT_MASK, 0, 0 }, + { "*mat_solidwood", 0, 0, S_MAT_SOLIDWOOD, S_MAT_MASK, 0, 0 }, + { "*mat_hollowwood", 0, 0, S_MAT_HOLLOWWOOD, S_MAT_MASK, 0, 0 }, + { "*mat_solidmetal", 0, 0, S_MAT_SOLIDMETAL, S_MAT_MASK, 0, 0 }, + { "*mat_hollowmetal", 0, 0, S_MAT_HOLLOWMETAL, S_MAT_MASK, 0, 0 }, + { "*mat_shortgrass", 0, 0, S_MAT_SHORTGRASS, S_MAT_MASK, 0, 0 }, + { "*mat_longgrass", 0, 0, S_MAT_LONGGRASS, S_MAT_MASK, 0, 0 }, + { "*mat_dirt", 0, 0, S_MAT_DIRT, S_MAT_MASK, 0, 0 }, + { "*mat_sand", 0, 0, S_MAT_SAND, S_MAT_MASK, 0, 0 }, + { "*mat_gravel", 0, 0, S_MAT_GRAVEL, S_MAT_MASK, 0, 0 }, + { "*mat_glass", 0, 0, S_MAT_GLASS, S_MAT_MASK, 0, 0 }, + { "*mat_concrete", 0, 0, S_MAT_CONCRETE, S_MAT_MASK, 0, 0 }, + { "*mat_marble", 0, 0, S_MAT_MARBLE, S_MAT_MASK, 0, 0 }, + { "*mat_water", 0, 0, S_MAT_WATER, S_MAT_MASK, 0, 0 }, + { "*mat_snow", 0, 0, S_MAT_SNOW, S_MAT_MASK, 0, 0 }, + { "*mat_ice", 0, 0, S_MAT_ICE, S_MAT_MASK, 0, 0 }, + { "*mat_flesh", 0, 0, S_MAT_FLESH, S_MAT_MASK, 0, 0 }, + { "*mat_mud", 0, 0, S_MAT_MUD, S_MAT_MASK, 0, 0 }, + { "*mat_bpglass", 0, 0, S_MAT_BPGLASS, S_MAT_MASK, 0, 0 }, + { "*mat_dryleaves", 0, 0, S_MAT_DRYLEAVES, S_MAT_MASK, 0, 0 }, + { "*mat_greenleaves", 0, 0, S_MAT_GREENLEAVES, S_MAT_MASK, 0, 0 }, + { "*mat_fabric", 0, 0, S_MAT_FABRIC, S_MAT_MASK, 0, 0 }, + { "*mat_canvas", 0, 0, S_MAT_CANVAS, S_MAT_MASK, 0, 0 }, + { "*mat_rock", 0, 0, S_MAT_ROCK, S_MAT_MASK, 0, 0 }, + { "*mat_rubber", 0, 0, S_MAT_RUBBER, S_MAT_MASK, 0, 0 }, + { "*mat_plastic", 0, 0, S_MAT_PLASTIC, S_MAT_MASK, 0, 0 }, + { "*mat_tiles", 0, 0, S_MAT_TILES, S_MAT_MASK, 0, 0 }, + { "*mat_carpet", 0, 0, S_MAT_CARPET, S_MAT_MASK, 0, 0 }, + { "*mat_plaster", 0, 0, S_MAT_PLASTER, S_MAT_MASK, 0, 0 }, + { "*mat_shatterglass", 0, 0, S_MAT_SHATTERGLASS, S_MAT_MASK, 0, 0 }, + { "*mat_armor", 0, 0, S_MAT_ARMOR, S_MAT_MASK, 0, 0 }, + { "*mat_computer", 0, 0, S_MAT_COMPUTER, S_MAT_MASK, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_t.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_t.h new file mode 100644 index 00000000..5eec9063 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_t.h @@ -0,0 +1,34 @@ + +/* +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 +*/ + +/* ydnar: for -game support */ +typedef struct game_s +{ + char *arg; /* -game matches this */ + char *gamePath; /* main game data dir */ + char *homeBasePath; /* home sub-dir on unix */ + char *magic; /* magic word for figuring out base path */ + qboolean wolfLight; /* when true, lights work like wolf q3map */ + int bspVersion; /* BSP version to use */ +} +game_t; + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_tenebrae.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_tenebrae.h new file mode 100644 index 00000000..ab312158 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_tenebrae.h @@ -0,0 +1,208 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_TENEBRAE_H +#define GAME_TENEBRAE_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* game flags */ +#define T_CONT_SOLID 1 /* an eye is never valid in a solid */ +#define T_CONT_LAVA 8 +#define T_CONT_SLIME 16 +#define T_CONT_WATER 32 +#define T_CONT_FOG 64 + +#define T_CONT_AREAPORTAL 0x8000 + +#define T_CONT_PLAYERCLIP 0x10000 +#define T_CONT_MONSTERCLIP 0x20000 +#define T_CONT_TELEPORTER 0x40000 +#define T_CONT_JUMPPAD 0x80000 +#define T_CONT_CLUSTERPORTAL 0x100000 +#define T_CONT_DONOTENTER 0x200000 +#define T_CONT_BOTCLIP 0x400000 + +#define T_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ + +#define T_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ +#define T_CONT_CORPSE 0x4000000 +#define T_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ +#define T_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ +#define T_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ +#define T_CONT_TRIGGER 0x40000000 +#define T_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ + +#define T_SURF_NODAMAGE 0x1 /* never give falling damage */ +#define T_SURF_SLICK 0x2 /* effects game physics */ +#define T_SURF_SKY 0x4 /* lighting from environment map */ +#define T_SURF_LADDER 0x8 +#define T_SURF_NOIMPACT 0x10 /* don't make missile explosions */ +#define T_SURF_NOMARKS 0x20 /* don't leave missile marks */ +#define T_SURF_FLESH 0x40 /* make flesh sounds and effects */ +#define T_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ +#define T_SURF_HINT 0x100 /* make a primary bsp splitter */ +#define T_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ +#define T_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ +#define T_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ +#define T_SURF_METALSTEPS 0x1000 /* clanking footsteps */ +#define T_SURF_NOSTEPS 0x2000 /* no footstep sounds */ +#define T_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ +#define T_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ +#define T_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ +#define T_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ +#define T_SURF_DUST 0x40000 /* leave a dust trail when walking on this surface */ + +/* ydnar flags */ +#define T_SURF_VERTEXLIT (T_SURF_POINTLIGHT | T_SURF_NOLIGHTMAP) + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "tenebrae", /* -game x */ + "base", /* default base game data dir */ + ".tenebrae", /* unix home sub-dir */ + "tenebrae", /* magic path word */ + "scripts", /* shader directory */ + 1024, /* max lightmapped surface verts */ + 1024, /* max surface verts */ + 6144, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 512, /* lightmap width/height */ + 2.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qtrue, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qtrue, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", T_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", T_CONT_ORIGIN, T_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", T_CONT_AREAPORTAL, T_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", T_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", T_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", T_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, T_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, T_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, T_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, T_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, T_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, T_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, T_CONT_SOLID, T_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", T_CONT_TRIGGER, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", T_CONT_WATER, T_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", T_CONT_SLIME, T_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", T_CONT_LAVA, T_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", T_CONT_PLAYERCLIP, T_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", T_CONT_MONSTERCLIP, T_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", T_CONT_NODROP, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", T_CONT_CLUSTERPORTAL, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", T_CONT_DONOTENTER, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", T_CONT_BOTCLIP, T_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", T_CONT_FOG, T_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, T_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, T_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, T_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, T_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, T_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, T_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, T_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, T_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, T_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, T_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, T_SURF_DUST, 0, 0, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_tremulous.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_tremulous.h new file mode 100644 index 00000000..5d422629 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_tremulous.h @@ -0,0 +1,176 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + +/* Tremulous support, by LinuxManMikeC */ + + +/* marker */ +#ifndef GAME_TREMULOUS_H +#define GAME_TREMULOUS_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags - also uses defines from game_quake3.h + +------------------------------------------------------------------------------- */ +#define TREM_CONT_NOALIENBUILD 0x1000 +#define TREM_CONT_NOHUMANBUILD 0x2000 +#define TREM_CONT_NOBUILD 0x4000 + +#define TREM_SURF_NOALIENBUILDSURFACE 0x80000 +#define TREM_SURF_NOHUMANBUILDSURFACE 0x100000 +#define TREM_SURF_NOBUILDSURFACE 0x200000 + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "tremulous", /* -game x */ + "base", /* default base game data dir */ + ".tremulous", /* unix home sub-dir */ + "tremulous", /* magic path word - think this is right for trem*/ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + + /* tremulous */ + {"noalienbuild", TREM_CONT_NOALIENBUILD,0,0,0,0,0}, + {"nohumanbuild", TREM_CONT_NOHUMANBUILD,0,0,0,0,0}, + {"nobuild", TREM_CONT_NOBUILD,0,0,0,0,0}, + + {"noalienbuildsurface", 0,0,TREM_SURF_NOALIENBUILDSURFACE,0,0,0}, + {"nohumanbuildsurface", 0,0,TREM_SURF_NOHUMANBUILDSURFACE,0,0,0}, + {"nobuildsurface", 0,0,TREM_SURF_NOBUILDSURFACE,0,0,0}, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_wolf.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_wolf.h new file mode 100644 index 00000000..157bfe3a --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_wolf.h @@ -0,0 +1,254 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_WOLF_H +#define GAME_WOLF_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* game flags */ +#define W_CONT_SOLID 1 /* an eye is never valid in a solid */ +#define W_CONT_LAVA 8 +#define W_CONT_SLIME 16 +#define W_CONT_WATER 32 +#define W_CONT_FOG 64 + +#define W_CONT_MISSILECLIP 0x80 /* wolf ranged missile blocking */ +#define W_CONT_ITEM 0x100 /* wolf item contents */ +#define W_CONT_AI_NOSIGHT 0x1000 /* wolf ai sight blocking */ +#define W_CONT_CLIPSHOT 0x2000 /* wolf shot clip */ +#define W_CONT_AREAPORTAL 0x8000 + +#define W_CONT_PLAYERCLIP 0x10000 +#define W_CONT_MONSTERCLIP 0x20000 +#define W_CONT_TELEPORTER 0x40000 +#define W_CONT_JUMPPAD 0x80000 +#define W_CONT_CLUSTERPORTAL 0x100000 +#define W_CONT_DONOTENTER 0x200000 +#define W_CONT_DONOTENTER_LARGE 0x400000 /* wolf dne */ + +#define W_CONT_ORIGIN 0x1000000 /* removed before bsping an entity */ + +#define W_CONT_BODY 0x2000000 /* should never be on a brush, only in game */ +#define W_CONT_CORPSE 0x4000000 +#define W_CONT_DETAIL 0x8000000 /* brushes not used for the bsp */ +#define W_CONT_STRUCTURAL 0x10000000 /* brushes used for the bsp */ +#define W_CONT_TRANSLUCENT 0x20000000 /* don't consume surface fragments inside */ +#define W_CONT_TRIGGER 0x40000000 +#define W_CONT_NODROP 0x80000000 /* don't leave bodies or items (death fog, lava) */ + +#define W_SURF_NODAMAGE 0x1 /* never give falling damage */ +#define W_SURF_SLICK 0x2 /* effects game physics */ +#define W_SURF_SKY 0x4 /* lighting from environment map */ +#define W_SURF_LADDER 0x8 +#define W_SURF_NOIMPACT 0x10 /* don't make missile explosions */ +#define W_SURF_NOMARKS 0x20 /* don't leave missile marks */ +#define W_SURF_CERAMIC 0x40 /* wolf ceramic material */ +#define W_SURF_NODRAW 0x80 /* don't generate a drawsurface at all */ +#define W_SURF_HINT 0x100 /* make a primary bsp splitter */ +#define W_SURF_SKIP 0x200 /* completely ignore, allowing non-closed brushes */ +#define W_SURF_NOLIGHTMAP 0x400 /* surface doesn't need a lightmap */ +#define W_SURF_POINTLIGHT 0x800 /* generate lighting info at vertexes */ +#define W_SURF_METAL 0x1000 /* wolf metal material */ +#define W_SURF_NOSTEPS 0x2000 /* no footstep sounds */ +#define W_SURF_NONSOLID 0x4000 /* don't collide against curves with this set */ +#define W_SURF_LIGHTFILTER 0x8000 /* act as a light filter during q3map -light */ +#define W_SURF_ALPHASHADOW 0x10000 /* do per-pixel light shadow casting in q3map */ +#define W_SURF_NODLIGHT 0x20000 /* don't dlight even if solid (solid lava, skies) */ +#define W_SURF_WOOD 0x40000 /* wolf wood material */ +#define W_SURF_GRASS 0x80000 /* wolf grass material */ +#define W_SURF_GRAVEL 0x100000 /* wolf gravel material */ +#define W_SURF_GLASS 0x200000 /* wolf glass material */ +#define W_SURF_SNOW 0x400000 /* wolf snow material */ +#define W_SURF_ROOF 0x800000 /* wolf roof material */ +#define W_SURF_RUBBLE 0x1000000 /* wolf rubble material */ +#define W_SURF_CARPET 0x2000000 /* wolf carpet material */ + +#define W_SURF_MONSTERSLICK 0x4000000 /* wolf npc slick surface */ +#define W_SURF_MONSLICK_W 0x8000000 /* wolf slide bodies west */ +#define W_SURF_MONSLICK_N 0x10000000 /* wolf slide bodies north */ +#define W_SURF_MONSLICK_E 0x20000000 /* wolf slide bodies east */ +#define W_SURF_MONSLICK_S 0x40000000 /* wolf slide bodies south */ + +/* ydnar flags */ +#define W_SURF_VERTEXLIT (W_SURF_POINTLIGHT | W_SURF_NOLIGHTMAP) + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "wolf", /* -game x */ + "main", /* default base game data dir */ + ".wolf", /* unix home sub-dir */ + "wolf", /* magic path word */ + "scripts", /* shader directory */ + 64, /* max lightmapped surface verts */ + 999, /* max surface verts */ + 6000, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qtrue, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 47, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", W_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", W_CONT_ORIGIN, W_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", W_CONT_AREAPORTAL, W_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", W_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", W_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", W_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, W_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, W_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, W_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, W_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, W_CONT_SOLID, W_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", W_CONT_TRIGGER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", W_CONT_WATER, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slag", W_CONT_SLIME, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", W_CONT_LAVA, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", W_CONT_PLAYERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", W_CONT_MONSTERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "clipmissile", W_CONT_MISSILECLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "clipshot", W_CONT_CLIPSHOT, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", W_CONT_NODROP, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", W_CONT_CLUSTERPORTAL, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "nonotenterlarge",W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", W_CONT_FOG, W_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, W_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, W_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, W_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, W_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, W_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, W_SURF_NODAMAGE, 0, 0, 0 }, + { "nosteps", 0, 0, W_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, W_SURF_NODLIGHT, 0, 0, 0 }, + + + /* materials */ + { "metal", 0, 0, W_SURF_METAL, 0, 0, 0 }, + { "metalsteps", 0, 0, W_SURF_METAL, 0, 0, 0 }, + { "glass", 0, 0, W_SURF_GLASS, 0, 0, 0 }, + { "ceramic", 0, 0, W_SURF_CERAMIC, 0, 0, 0 }, + { "woodsteps", 0, 0, W_SURF_WOOD, 0, 0, 0 }, + { "grasssteps", 0, 0, W_SURF_GRASS, 0, 0, 0 }, + { "gravelsteps", 0, 0, W_SURF_GRAVEL, 0, 0, 0 }, + { "rubble", 0, 0, W_SURF_RUBBLE, 0, 0, 0 }, + { "carpetsteps", 0, 0, W_SURF_CARPET, 0, 0, 0 }, + { "snowsteps", 0, 0, W_SURF_SNOW, 0, 0, 0 }, + { "roofsteps", 0, 0, W_SURF_ROOF, 0, 0, 0 }, + + + /* ai */ + { "ai_nosight", W_CONT_AI_NOSIGHT, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + /* ydnar: experimental until bits are confirmed! */ + { "ai_nopass", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "ai_nopasslarge", W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + + /* sliding bodies */ + { "monsterslick", 0, 0, W_SURF_MONSTERSLICK, 0, C_TRANSLUCENT, 0 }, + { "monsterslicknorth", 0, 0, W_SURF_MONSLICK_N, 0, C_TRANSLUCENT, 0 }, + { "monsterslickeast", 0, 0, W_SURF_MONSLICK_E, 0, C_TRANSLUCENT, 0 }, + { "monsterslicksouth", 0, 0, W_SURF_MONSLICK_S, 0, C_TRANSLUCENT, 0 }, + { "monsterslickwest", 0, 0, W_SURF_MONSLICK_W, 0, C_TRANSLUCENT, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_wolfet.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_wolfet.h new file mode 100644 index 00000000..3495f0dc --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_wolfet.h @@ -0,0 +1,193 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +Support for Wolfenstein: Enemy Territory by ydnar@splashdamage.com + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_WOLFET_H +#define GAME_WOLFET_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags + +------------------------------------------------------------------------------- */ + +/* this file must be included *after* game_wolf.h because it shares defines! */ + +#define W_SURF_SPLASH 0x00000040 /* enemy territory water splash surface */ +#define W_SURF_LANDMINE 0x80000000 /* enemy territory 'landminable' surface */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "et", /* -game x */ + "etmain", /* default base game data dir */ + ".etwolf", /* unix home sub-dir */ + "et", /* magic path word */ + "scripts", /* shader directory */ + 1024, /* max lightmapped surface verts */ + 1024, /* max surface verts */ + 6144, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qtrue, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qfalse, /* disable shader lightstyles hack */ + qfalse, /* keep light entities on bsp */ + 8, /* default patchMeta subdivisions tolerance */ + qfalse, /* patch casting enabled */ + qfalse, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 0.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "%s.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 47, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", W_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + + /* compiler */ + { "origin", W_CONT_ORIGIN, W_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", W_CONT_AREAPORTAL, W_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", W_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", W_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", W_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, W_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, W_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, W_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, W_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, W_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + + /* game */ + { "nonsolid", 0, W_CONT_SOLID, W_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", W_CONT_TRIGGER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", W_CONT_WATER, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slag", W_CONT_SLIME, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", W_CONT_LAVA, W_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", W_CONT_PLAYERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", W_CONT_MONSTERCLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "clipmissile", W_CONT_MISSILECLIP, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "clipshot", W_CONT_CLIPSHOT, W_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", W_CONT_NODROP, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", W_CONT_CLUSTERPORTAL, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "nonotenterlarge",W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", W_CONT_FOG, W_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, W_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, W_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, W_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, W_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, W_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, W_SURF_NODAMAGE, 0, 0, 0 }, + { "nosteps", 0, 0, W_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, W_SURF_NODLIGHT, 0, 0, 0 }, + + /* wolf et landmine-able surface */ + { "landmine", 0, 0, W_SURF_LANDMINE, 0, 0, 0 }, + + /* materials */ + { "metal", 0, 0, W_SURF_METAL, 0, 0, 0 }, + { "metalsteps", 0, 0, W_SURF_METAL, 0, 0, 0 }, + { "glass", 0, 0, W_SURF_GLASS, 0, 0, 0 }, + { "splash", 0, 0, W_SURF_SPLASH, 0, 0, 0 }, + { "woodsteps", 0, 0, W_SURF_WOOD, 0, 0, 0 }, + { "grasssteps", 0, 0, W_SURF_GRASS, 0, 0, 0 }, + { "gravelsteps", 0, 0, W_SURF_GRAVEL, 0, 0, 0 }, + { "rubble", 0, 0, W_SURF_RUBBLE, 0, 0, 0 }, + { "carpetsteps", 0, 0, W_SURF_CARPET, 0, 0, 0 }, + { "snowsteps", 0, 0, W_SURF_SNOW, 0, 0, 0 }, + { "roofsteps", 0, 0, W_SURF_ROOF, 0, 0, 0 }, + + + /* ai */ + { "ai_nosight", W_CONT_AI_NOSIGHT, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + /* ydnar: experimental until bits are confirmed! */ + { "ai_nopass", W_CONT_DONOTENTER, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "ai_nopasslarge", W_CONT_DONOTENTER_LARGE, W_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + + /* sliding bodies */ + { "monsterslick", 0, 0, W_SURF_MONSTERSLICK, 0, C_TRANSLUCENT, 0 }, + { "monsterslicknorth", 0, 0, W_SURF_MONSLICK_N, 0, C_TRANSLUCENT, 0 }, + { "monsterslickeast", 0, 0, W_SURF_MONSLICK_E, 0, C_TRANSLUCENT, 0 }, + { "monsterslicksouth", 0, 0, W_SURF_MONSLICK_S, 0, C_TRANSLUCENT, 0 }, + { "monsterslickwest", 0, 0, W_SURF_MONSLICK_W, 0, C_TRANSLUCENT, 0 }, + + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_xonotic.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_xonotic.h new file mode 100644 index 00000000..568c263e --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/game_xonotic.h @@ -0,0 +1,155 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef GAME_XONOTIC_H +#define GAME_XONOTIC_H + + + +/* ------------------------------------------------------------------------------- + +content and surface flags +are in game_quake3.h + +------------------------------------------------------------------------------- */ + + + +/* ------------------------------------------------------------------------------- + +game_t struct + +------------------------------------------------------------------------------- */ + +{ + "xonotic", /* -game x */ + "data", /* default base game data dir */ + ".xonotic", /* unix home sub-dir */ + "xonotic", /* magic path word */ + "scripts", /* shader directory */ + 1048575, /* max lightmapped surface verts */ + 1048575, /* max surface verts */ + 1048575, /* max surface indexes */ + qfalse, /* flares */ + "flareshader", /* default flare shader */ + qfalse, /* wolf lighting model? */ + 128, /* lightmap width/height */ + 1.0f, /* lightmap gamma */ + 1.0f, /* lightmap exposure */ + 1.0f, /* lightmap compensate */ + 1.0f, /* lightgrid scale */ + 1.0f, /* lightgrid ambient scale */ + qfalse, /* light angle attenuation uses half-lambert curve */ + qtrue, /* disable shader lightstyles hack */ + qtrue, /* keep light entities on bsp */ + 4, /* default patchMeta subdivisions tolerance */ + qtrue, /* patch casting enabled */ + qtrue, /* compile deluxemaps */ + 0, /* deluxemaps default mode */ + 512, /* minimap size */ + 1.0f, /* minimap sharpener */ + 1.0f/66.0f, /* minimap border */ + qtrue, /* minimap keep aspect */ + MINIMAP_MODE_GRAY, /* minimap mode */ + "../gfx/%s_mini.tga", /* minimap name format */ + "IBSP", /* bsp file prefix */ + 46, /* bsp file version */ + qfalse, /* cod-style lump len/ofs order */ + LoadIBSPFile, /* bsp load function */ + WriteIBSPFile, /* bsp write function */ + + { + /* name contentFlags contentFlagsClear surfaceFlags surfaceFlagsClear compileFlags compileFlagsClear */ + + /* default */ + { "default", Q_CONT_SOLID, -1, 0, -1, C_SOLID, -1 }, + + /* ydnar */ + { "lightgrid", 0, 0, 0, 0, C_LIGHTGRID, 0 }, + { "antiportal", 0, 0, 0, 0, C_ANTIPORTAL, 0 }, + { "skip", 0, 0, 0, 0, C_SKIP, 0 }, + + /* compiler */ + { "origin", Q_CONT_ORIGIN, Q_CONT_SOLID, 0, 0, C_ORIGIN | C_TRANSLUCENT, C_SOLID }, + { "areaportal", Q_CONT_AREAPORTAL, Q_CONT_SOLID, 0, 0, C_AREAPORTAL | C_TRANSLUCENT, C_SOLID }, + { "trans", Q_CONT_TRANSLUCENT, 0, 0, 0, C_TRANSLUCENT, 0 }, + { "detail", Q_CONT_DETAIL, 0, 0, 0, C_DETAIL, 0 }, + { "structural", Q_CONT_STRUCTURAL, 0, 0, 0, C_STRUCTURAL, 0 }, + { "hint", 0, 0, Q_SURF_HINT, 0, C_HINT, 0 }, + { "nodraw", 0, 0, Q_SURF_NODRAW, 0, C_NODRAW, 0 }, + + { "alphashadow", 0, 0, Q_SURF_ALPHASHADOW, 0, C_ALPHASHADOW | C_TRANSLUCENT, 0 }, + { "lightfilter", 0, 0, Q_SURF_LIGHTFILTER, 0, C_LIGHTFILTER | C_TRANSLUCENT, 0 }, + { "nolightmap", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + { "pointlight", 0, 0, Q_SURF_VERTEXLIT, 0, C_VERTEXLIT, 0 }, + + /* game */ + { "nonsolid", 0, Q_CONT_SOLID, Q_SURF_NONSOLID, 0, 0, C_SOLID }, + + { "trigger", Q_CONT_TRIGGER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "water", Q_CONT_WATER, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "slime", Q_CONT_SLIME, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + { "lava", Q_CONT_LAVA, Q_CONT_SOLID, 0, 0, C_LIQUID | C_TRANSLUCENT, C_SOLID }, + + { "playerclip", Q_CONT_PLAYERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "monsterclip", Q_CONT_MONSTERCLIP, Q_CONT_SOLID, 0, 0, C_DETAIL | C_TRANSLUCENT, C_SOLID }, + { "nodrop", Q_CONT_NODROP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "clusterportal", Q_CONT_CLUSTERPORTAL, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "donotenter", Q_CONT_DONOTENTER, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + { "botclip", Q_CONT_BOTCLIP, Q_CONT_SOLID, 0, 0, C_TRANSLUCENT, C_SOLID }, + + { "fog", Q_CONT_FOG, Q_CONT_SOLID, 0, 0, C_FOG, C_SOLID }, + { "sky", 0, 0, Q_SURF_SKY, 0, C_SKY, 0 }, + + { "slick", 0, 0, Q_SURF_SLICK, 0, 0, 0 }, + + { "noimpact", 0, 0, Q_SURF_NOIMPACT, 0, 0, 0 }, + { "nomarks", 0, 0, Q_SURF_NOMARKS, 0, C_NOMARKS, 0 }, + { "ladder", 0, 0, Q_SURF_LADDER, 0, 0, 0 }, + { "nodamage", 0, 0, Q_SURF_NODAMAGE, 0, 0, 0 }, + { "metalsteps", 0, 0, Q_SURF_METALSTEPS, 0, 0, 0 }, + { "flesh", 0, 0, Q_SURF_FLESH, 0, 0, 0 }, + { "nosteps", 0, 0, Q_SURF_NOSTEPS, 0, 0, 0 }, + { "nodlight", 0, 0, Q_SURF_NODLIGHT, 0, 0, 0 }, + { "dust", 0, 0, Q_SURF_DUST, 0, 0, 0 }, + + /* null */ + { NULL, 0, 0, 0, 0, 0, 0 } + } +} + + + +/* end marker */ +#endif + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/image.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/image.c new file mode 100644 index 00000000..929b15d9 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/image.c @@ -0,0 +1,492 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define IMAGE_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* ------------------------------------------------------------------------------- + +this file contains image pool management with reference counting. note: it isn't +reentrant, so only call it from init/shutdown code or wrap calls in a mutex + +------------------------------------------------------------------------------- */ + +/* +LoadDDSBuffer() +loads a dxtc (1, 3, 5) dds buffer into a valid rgba image +*/ + +static void LoadDDSBuffer( byte *buffer, int size, byte **pixels, int *width, int *height ) +{ + int w, h; + ddsPF_t pf; + + + /* dummy check */ + if( buffer == NULL || size <= 0 || pixels == NULL || width == NULL || height == NULL ) + return; + + /* null out */ + *pixels = 0; + *width = 0; + *height = 0; + + /* get dds info */ + if( DDSGetInfo( (ddsBuffer_t*) buffer, &w, &h, &pf ) ) + { + Sys_Printf( "WARNING: Invalid DDS texture\n" ); + return; + } + + /* only certain types of dds textures are supported */ + if( pf != DDS_PF_ARGB8888 && pf != DDS_PF_DXT1 && pf != DDS_PF_DXT3 && pf != DDS_PF_DXT5 ) + { + Sys_Printf( "WARNING: Only DDS texture formats ARGB8888, DXT1, DXT3, and DXT5 are supported (%d)\n", pf ); + return; + } + + /* create image pixel buffer */ + *width = w; + *height = h; + *pixels = safe_malloc( w * h * 4 ); + + /* decompress the dds texture */ + DDSDecompress( (ddsBuffer_t*) buffer, *pixels ); +} + + + +/* +PNGReadData() +callback function for libpng to read from a memory buffer +note: this function is a total hack, as it reads/writes the png struct directly! +*/ + +typedef struct pngBuffer_s +{ + byte *buffer; + png_size_t size, offset; +} +pngBuffer_t; + +void PNGReadData( png_struct *png, png_byte *buffer, png_size_t size ) +{ + pngBuffer_t *pb = (pngBuffer_t*) png_get_io_ptr( png ); + + + if( (pb->offset + size) > pb->size ) + size = (pb->size - pb->offset); + memcpy( buffer, &pb->buffer[ pb->offset ], size ); + pb->offset += size; + //% Sys_Printf( "Copying %d bytes from 0x%08X to 0x%08X (offset: %d of %d)\n", size, &pb->buffer[ pb->offset ], buffer, pb->offset, pb->size ); +} + + + +/* +LoadPNGBuffer() +loads a png file buffer into a valid rgba image +*/ + +static void LoadPNGBuffer( byte *buffer, int size, byte **pixels, int *width, int *height ) +{ + png_struct *png; + png_info *info, *end; + pngBuffer_t pb; + int bitDepth, colorType, channels; + png_uint_32 w, h, i; + byte **rowPointers; + + + /* dummy check */ + if( buffer == NULL || size <= 0 || pixels == NULL || width == NULL || height == NULL ) + return; + + /* null out */ + *pixels = 0; + *width = 0; + *height = 0; + + /* determine if this is a png file */ + if( png_sig_cmp( buffer, 0, 8 ) != 0 ) + { + Sys_Printf( "WARNING: Invalid PNG file\n" ); + return; + } + + /* create png structs */ + png = png_create_read_struct( PNG_LIBPNG_VER_STRING, NULL, NULL, NULL ); + if( png == NULL ) + { + Sys_Printf( "WARNING: Unable to create PNG read struct\n" ); + return; + } + + info = png_create_info_struct( png ); + if( info == NULL ) + { + Sys_Printf( "WARNING: Unable to create PNG info struct\n" ); + png_destroy_read_struct( &png, NULL, NULL ); + return; + } + + end = png_create_info_struct( png ); + if( end == NULL ) + { + Sys_Printf( "WARNING: Unable to create PNG end info struct\n" ); + png_destroy_read_struct( &png, &info, NULL ); + return; + } + + /* set read callback */ + pb.buffer = buffer; + pb.size = size; + pb.offset = 0; + png_set_read_fn( png, &pb, PNGReadData ); + png->io_ptr = &pb; /* hack! */ + + /* set error longjmp */ + if( setjmp( png->jmpbuf ) ) + { + Sys_Printf( "WARNING: An error occurred reading PNG image\n" ); + png_destroy_read_struct( &png, &info, &end ); + return; + } + + /* fixme: add proper i/o stuff here */ + + /* read png info */ + png_read_info( png, info ); + + /* read image header chunk */ + png_get_IHDR( png, info, + &w, &h, &bitDepth, &colorType, NULL, NULL, NULL ); + + /* read number of channels */ + channels = png_get_channels( png, info ); + + /* the following will probably bork on certain types of png images, but hey... */ + + /* force indexed/gray/trans chunk to rgb */ + if( (colorType == PNG_COLOR_TYPE_PALETTE && bitDepth <= 8) || + (colorType == PNG_COLOR_TYPE_GRAY && bitDepth <= 8) || + png_get_valid( png, info, PNG_INFO_tRNS ) ) + png_set_expand( png ); + + /* strip 16bpc -> 8bpc */ + if( bitDepth == 16 ) + png_set_strip_16( png ); + + /* pad rgb to rgba */ + if( bitDepth == 8 && colorType == PNG_COLOR_TYPE_RGB) + png_set_filler( png, 255, PNG_FILLER_AFTER ); + + /* create image pixel buffer */ + *width = w; + *height = h; + *pixels = safe_malloc( w * h * 4 ); + + /* create row pointers */ + rowPointers = safe_malloc( h * sizeof( byte* ) ); + for( i = 0; i < h; i++ ) + rowPointers[ i ] = *pixels + (i * w * 4); + + /* read the png */ + png_read_image( png, rowPointers ); + + /* clean up */ + free( rowPointers ); + png_destroy_read_struct( &png, &info, &end ); + +} + + + +/* +ImageInit() +implicitly called by every function to set up image list +*/ + +static void ImageInit( void ) +{ + int i; + + + if( numImages <= 0 ) + { + /* clear images (fixme: this could theoretically leak) */ + memset( images, 0, sizeof( images ) ); + + /* generate *bogus image */ + images[ 0 ].name = safe_malloc( strlen( DEFAULT_IMAGE ) + 1 ); + strcpy( images[ 0 ].name, DEFAULT_IMAGE ); + images[ 0 ].filename = safe_malloc( strlen( DEFAULT_IMAGE ) + 1 ); + strcpy( images[ 0 ].filename, DEFAULT_IMAGE ); + images[ 0 ].width = 64; + images[ 0 ].height = 64; + images[ 0 ].refCount = 1; + images[ 0 ].pixels = safe_malloc( 64 * 64 * 4 ); + for( i = 0; i < (64 * 64 * 4); i++ ) + images[ 0 ].pixels[ i ] = 255; + } +} + + + +/* +ImageFree() +frees an rgba image +*/ + +void ImageFree( image_t *image ) +{ + /* dummy check */ + if( image == NULL ) + return; + + /* decrement refcount */ + image->refCount--; + + /* free? */ + if( image->refCount <= 0 ) + { + if( image->name != NULL ) + free( image->name ); + image->name = NULL; + if( image->filename != NULL ) + free( image->filename ); + image->filename = NULL; + free( image->pixels ); + image->width = 0; + image->height = 0; + numImages--; + } +} + + + +/* +ImageFind() +finds an existing rgba image and returns a pointer to the image_t struct or NULL if not found +*/ + +image_t *ImageFind( const char *filename ) +{ + int i; + char name[ 1024 ]; + + + /* init */ + ImageInit(); + + /* dummy check */ + if( filename == NULL || filename[ 0 ] == '\0' ) + return NULL; + + /* strip file extension off name */ + strcpy( name, filename ); + StripExtension( name ); + + /* search list */ + for( i = 0; i < MAX_IMAGES; i++ ) + { + if( images[ i ].name != NULL && !strcmp( name, images[ i ].name ) ) + return &images[ i ]; + } + + /* no matching image found */ + return NULL; +} + + + +/* +ImageLoad() +loads an rgba image and returns a pointer to the image_t struct or NULL if not found +*/ + +image_t *ImageLoad( const char *filename ) +{ + int i; + image_t *image; + char name[ 1024 ]; + int size; + byte *buffer = NULL; + qboolean alphaHack = qfalse; + + + /* init */ + ImageInit(); + + /* dummy check */ + if( filename == NULL || filename[ 0 ] == '\0' ) + return NULL; + + /* strip file extension off name */ + strcpy( name, filename ); + StripExtension( name ); + + /* try to find existing image */ + image = ImageFind( name ); + if( image != NULL ) + { + image->refCount++; + return image; + } + + /* none found, so find first non-null image */ + image = NULL; + for( i = 0; i < MAX_IMAGES; i++ ) + { + if( images[ i ].name == NULL ) + { + image = &images[ i ]; + break; + } + } + + /* too many images? */ + if( image == NULL ) + Error( "MAX_IMAGES (%d) exceeded, there are too many image files referenced by the map.", MAX_IMAGES ); + + /* set it up */ + image->name = safe_malloc( strlen( name ) + 1 ); + strcpy( image->name, name ); + + /* attempt to load tga */ + StripExtension( name ); + strcat( name, ".tga" ); + size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); + if( size > 0 ) + LoadTGABuffer( buffer, buffer + size, &image->pixels, &image->width, &image->height ); + else + { + /* attempt to load png */ + StripExtension( name ); + strcat( name, ".png" ); + size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); + if( size > 0 ) + LoadPNGBuffer( buffer, size, &image->pixels, &image->width, &image->height ); + else + { + /* attempt to load jpg */ + StripExtension( name ); + strcat( name, ".jpg" ); + size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); + if( size > 0 ) + { + if( LoadJPGBuff( buffer, size, &image->pixels, &image->width, &image->height ) == -1 && image->pixels != NULL ) + Sys_Printf( "WARNING: LoadJPGBuff: %s\n", (unsigned char*) image->pixels ); + alphaHack = qtrue; + } + else + { + /* attempt to load dds */ + StripExtension( name ); + strcat( name, ".dds" ); + size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); + if( size > 0 ) + { + LoadDDSBuffer( buffer, size, &image->pixels, &image->width, &image->height ); + + /* debug code */ + #if 1 + { + ddsPF_t pf; + DDSGetInfo( (ddsBuffer_t*) buffer, NULL, NULL, &pf ); + Sys_Printf( "pf = %d\n", pf ); + if( image->width > 0 ) + { + StripExtension( name ); + strcat( name, "_converted.tga" ); + WriteTGA( "C:\\games\\quake3\\baseq3\\textures\\rad\\dds_converted.tga", image->pixels, image->width, image->height ); + } + } + #endif + } + } + } + } + + /* free file buffer */ + free( buffer ); + + /* make sure everything's kosher */ + if( size <= 0 || image->width <= 0 || image->height <= 0 || image->pixels == NULL ) + { + //% Sys_Printf( "size = %d width = %d height = %d pixels = 0x%08x (%s)\n", + //% size, image->width, image->height, image->pixels, name ); + free( image->name ); + image->name = NULL; + return NULL; + } + + /* set filename */ + image->filename = safe_malloc( strlen( name ) + 1 ); + strcpy( image->filename, name ); + + /* set count */ + image->refCount = 1; + numImages++; + + if(alphaHack) + { + StripExtension( name ); + strcat( name, "_alpha.jpg" ); + size = vfsLoadFile( (const char*) name, (void**) &buffer, 0 ); + if( size > 0 ) + { + unsigned char *pixels; + int width, height; + if( LoadJPGBuff( buffer, size, &pixels, &width, &height ) == -1 && pixels != NULL ) + Sys_Printf( "WARNING: LoadJPGBuff: %s\n", (unsigned char*) image->pixels ); + if(pixels && width == image->width && height == image->height) + { + int i; + for(i = 0; i < width*height; ++i) + image->pixels[4*i+3] = pixels[4*i+2]; // copy alpha from blue channel + } + free(pixels); + free(buffer); + } + } + + /* return the image */ + return image; +} + + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/leakfile.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/leakfile.c new file mode 100644 index 00000000..fc5a3191 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/leakfile.c @@ -0,0 +1,127 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define LEAKFILE_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +============================================================================== + +LEAK FILE GENERATION + +Save out name.line for qe3 to read +============================================================================== +*/ + + +/* +============= +LeakFile + +Finds the shortest possible chain of portals +that leads from the outside leaf to a specifically +occupied leaf + +TTimo: builds a polyline xml node +============= +*/ +xmlNodePtr LeakFile (tree_t *tree) +{ + vec3_t mid; + FILE *linefile; + char filename[1024]; + node_t *node; + int count; + xmlNodePtr xml_node, point; + + if (!tree->outside_node.occupied) + return NULL; + + Sys_FPrintf (SYS_VRB,"--- LeakFile ---\n"); + + // + // write the points to the file + // + sprintf (filename, "%s.lin", source); + linefile = fopen (filename, "w"); + if (!linefile) + Error ("Couldn't open %s\n", filename); + + xml_node = xmlNewNode (NULL, (xmlChar*)"polyline"); + + count = 0; + node = &tree->outside_node; + while (node->occupied > 1) + { + int next; + portal_t *p, *nextportal = NULL; + node_t *nextnode = NULL; + int s; + + // find the best portal exit + next = node->occupied; + for (p=node->portals ; p ; p = p->next[!s]) + { + s = (p->nodes[0] == node); + if (p->nodes[s]->occupied + && p->nodes[s]->occupied < next) + { + nextportal = p; + nextnode = p->nodes[s]; + next = nextnode->occupied; + } + } + node = nextnode; + WindingCenter (nextportal->winding, mid); + fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); + point = xml_NodeForVec(mid); + xmlAddChild(xml_node, point); + count++; + } + // add the occupant center + GetVectorForKey (node->occupant, "origin", mid); + + fprintf (linefile, "%f %f %f\n", mid[0], mid[1], mid[2]); + point = xml_NodeForVec(mid); + xmlAddChild(xml_node, point); + Sys_FPrintf( SYS_VRB, "%9d point linefile\n", count+1); + + fclose (linefile); + + return xml_node; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/light.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light.c new file mode 100644 index 00000000..9323b8c8 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light.c @@ -0,0 +1,2877 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define LIGHT_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +CreateSunLight() - ydnar +this creates a sun light +*/ + +static void CreateSunLight( sun_t *sun ) +{ + int i; + float photons, d, angle, elevation, da, de; + vec3_t direction; + light_t *light; + + + /* dummy check */ + if( sun == NULL ) + return; + + /* fixup */ + if( sun->numSamples < 1 ) + sun->numSamples = 1; + + /* set photons */ + photons = sun->photons / sun->numSamples; + + /* create the right number of suns */ + for( i = 0; i < sun->numSamples; i++ ) + { + /* calculate sun direction */ + if( i == 0 ) + VectorCopy( sun->direction, direction ); + else + { + /* + sun->direction[ 0 ] = cos( angle ) * cos( elevation ); + sun->direction[ 1 ] = sin( angle ) * cos( elevation ); + sun->direction[ 2 ] = sin( elevation ); + + xz_dist = sqrt( x*x + z*z ) + latitude = atan2( xz_dist, y ) * RADIANS + longitude = atan2( x, z ) * RADIANS + */ + + d = sqrt( sun->direction[ 0 ] * sun->direction[ 0 ] + sun->direction[ 1 ] * sun->direction[ 1 ] ); + angle = atan2( sun->direction[ 1 ], sun->direction[ 0 ] ); + elevation = atan2( sun->direction[ 2 ], d ); + + /* jitter the angles (loop to keep random sample within sun->deviance steridians) */ + do + { + da = (Random() * 2.0f - 1.0f) * sun->deviance; + de = (Random() * 2.0f - 1.0f) * sun->deviance; + } + while( (da * da + de * de) > (sun->deviance * sun->deviance) ); + angle += da; + elevation += de; + + /* debug code */ + //% Sys_Printf( "%d: Angle: %3.4f Elevation: %3.3f\n", sun->numSamples, (angle / Q_PI * 180.0f), (elevation / Q_PI * 180.0f) ); + + /* create new vector */ + direction[ 0 ] = cos( angle ) * cos( elevation ); + direction[ 1 ] = sin( angle ) * cos( elevation ); + direction[ 2 ] = sin( elevation ); + } + + /* create a light */ + numSunLights++; + light = safe_malloc( sizeof( *light ) ); + memset( light, 0, sizeof( *light ) ); + light->next = lights; + lights = light; + + /* initialize the light */ + light->flags = LIGHT_SUN_DEFAULT; + light->type = EMIT_SUN; + light->fade = 1.0f; + light->falloffTolerance = falloffTolerance; + light->filterRadius = sun->filterRadius / sun->numSamples; + light->style = noStyles ? LS_NORMAL : sun->style; + + /* set the light's position out to infinity */ + VectorMA( vec3_origin, (MAX_WORLD_COORD * 8.0f), direction, light->origin ); /* MAX_WORLD_COORD * 2.0f */ + + /* set the facing to be the inverse of the sun direction */ + VectorScale( direction, -1.0, light->normal ); + light->dist = DotProduct( light->origin, light->normal ); + + /* set color and photons */ + VectorCopy( sun->color, light->color ); + light->photons = photons * skyScale; + } + + /* another sun? */ + if( sun->next != NULL ) + CreateSunLight( sun->next ); +} + + + +/* +CreateSkyLights() - ydnar +simulates sky light with multiple suns +*/ + +static void CreateSkyLights( vec3_t color, float value, int iterations, float filterRadius, int style ) +{ + int i, j, numSuns; + int angleSteps, elevationSteps; + float angle, elevation; + float angleStep, elevationStep; + float step, start; + sun_t sun; + + + /* dummy check */ + if( value <= 0.0f || iterations < 2 ) + return; + + /* calculate some stuff */ + step = 2.0f / (iterations - 1); + start = -1.0f; + + /* basic sun setup */ + VectorCopy( color, sun.color ); + sun.deviance = 0.0f; + sun.filterRadius = filterRadius; + sun.numSamples = 1; + sun.style = noStyles ? LS_NORMAL : style; + sun.next = NULL; + + /* setup */ + elevationSteps = iterations - 1; + angleSteps = elevationSteps * 4; + angle = 0.0f; + elevationStep = DEG2RAD( 90.0f / iterations ); /* skip elevation 0 */ + angleStep = DEG2RAD( 360.0f / angleSteps ); + + /* calc individual sun brightness */ + numSuns = angleSteps * elevationSteps + 1; + sun.photons = value / numSuns; + + /* iterate elevation */ + elevation = elevationStep * 0.5f; + angle = 0.0f; + for( i = 0, elevation = elevationStep * 0.5f; i < elevationSteps; i++ ) + { + /* iterate angle */ + for( j = 0; j < angleSteps; j++ ) + { + /* create sun */ + sun.direction[ 0 ] = cos( angle ) * cos( elevation ); + sun.direction[ 1 ] = sin( angle ) * cos( elevation ); + sun.direction[ 2 ] = sin( elevation ); + CreateSunLight( &sun ); + + /* move */ + angle += angleStep; + } + + /* move */ + elevation += elevationStep; + angle += angleStep / elevationSteps; + } + + /* create vertical sun */ + VectorSet( sun.direction, 0.0f, 0.0f, 1.0f ); + CreateSunLight( &sun ); + + /* short circuit */ + return; +} + + + +/* +CreateEntityLights() +creates lights from light entities +*/ + +void CreateEntityLights( void ) +{ + int i, j; + light_t *light, *light2; + entity_t *e, *e2; + const char *name; + const char *target; + vec3_t dest; + const char *_color; + float intensity, scale, deviance, filterRadius; + int spawnflags, flags, numSamples; + qboolean junior; + + + /* go throught entity list and find lights */ + for( i = 0; i < numEntities; i++ ) + { + /* get entity */ + e = &entities[ i ]; + name = ValueForKey( e, "classname" ); + + /* ydnar: check for lightJunior */ + if( Q_strncasecmp( name, "lightJunior", 11 ) == 0 ) + junior = qtrue; + else if( Q_strncasecmp( name, "light", 5 ) == 0 ) + junior = qfalse; + else + continue; + + /* lights with target names (and therefore styles) are only parsed from BSP */ + target = ValueForKey( e, "targetname" ); + if( target[ 0 ] != '\0' && i >= numBSPEntities ) + continue; + + /* create a light */ + numPointLights++; + light = safe_malloc( sizeof( *light ) ); + memset( light, 0, sizeof( *light ) ); + light->next = lights; + lights = light; + + /* handle spawnflags */ + spawnflags = IntForKey( e, "spawnflags" ); + + /* ydnar: quake 3+ light behavior */ + if( wolfLight == qfalse ) + { + /* set default flags */ + flags = LIGHT_Q3A_DEFAULT; + + /* linear attenuation? */ + if( spawnflags & 1 ) + { + flags |= LIGHT_ATTEN_LINEAR; + flags &= ~LIGHT_ATTEN_ANGLE; + } + + /* no angle attenuate? */ + if( spawnflags & 2 ) + flags &= ~LIGHT_ATTEN_ANGLE; + } + + /* ydnar: wolf light behavior */ + else + { + /* set default flags */ + flags = LIGHT_WOLF_DEFAULT; + + /* inverse distance squared attenuation? */ + if( spawnflags & 1 ) + { + flags &= ~LIGHT_ATTEN_LINEAR; + flags |= LIGHT_ATTEN_ANGLE; + } + + /* angle attenuate? */ + if( spawnflags & 2 ) + flags |= LIGHT_ATTEN_ANGLE; + } + + /* other flags (borrowed from wolf) */ + + /* wolf dark light? */ + if( (spawnflags & 4) || (spawnflags & 8) ) + flags |= LIGHT_DARK; + + /* nogrid? */ + if( spawnflags & 16 ) + flags &= ~LIGHT_GRID; + + /* junior? */ + if( junior ) + { + flags |= LIGHT_GRID; + flags &= ~LIGHT_SURFACES; + } + + /* vortex: unnormalized? */ + if (spawnflags & 32) + flags |= LIGHT_UNNORMALIZED; + + /* vortex: distance atten? */ + if (spawnflags & 64) + flags |= LIGHT_ATTEN_DISTANCE; + + /* store the flags */ + light->flags = flags; + + /* ydnar: set fade key (from wolf) */ + light->fade = 1.0f; + if( light->flags & LIGHT_ATTEN_LINEAR ) + { + light->fade = FloatForKey( e, "fade" ); + if( light->fade == 0.0f ) + light->fade = 1.0f; + } + + /* ydnar: set angle scaling (from vlight) */ + light->angleScale = FloatForKey( e, "_anglescale" ); + if( light->angleScale != 0.0f ) + light->flags |= LIGHT_ATTEN_ANGLE; + + /* set origin */ + GetVectorForKey( e, "origin", light->origin); + light->style = IntForKey( e, "_style" ); + if( light->style == LS_NORMAL ) + light->style = IntForKey( e, "style" ); + if( light->style < LS_NORMAL || light->style >= LS_NONE ) + Error( "Invalid lightstyle (%d) on entity %d", light->style, i ); + + if( light->style != LS_NORMAL ) { + Sys_FPrintf (SYS_WRN, "WARNING: Styled light found targeting %s\n **", target ); + } + + /* set light intensity */ + intensity = FloatForKey( e, "_light" ); + if( intensity == 0.0f ) + intensity = FloatForKey( e, "light" ); + if( intensity == 0.0f) + intensity = 300.0f; + + /* ydnar: set light scale (sof2) */ + scale = FloatForKey( e, "scale" ); + if( scale == 0.0f ) + scale = 1.0f; + intensity *= scale; + + /* ydnar: get deviance and samples */ + deviance = FloatForKey( e, "_deviance" ); + if( deviance == 0.0f ) + deviance = FloatForKey( e, "_deviation" ); + if( deviance == 0.0f ) + deviance = FloatForKey( e, "_jitter" ); + numSamples = IntForKey( e, "_samples" ); + if( deviance < 0.0f || numSamples < 1 ) + { + deviance = 0.0f; + numSamples = 1; + } + intensity /= numSamples; + + /* ydnar: get filter radius */ + filterRadius = FloatForKey( e, "_filterradius" ); + if( filterRadius == 0.0f ) + filterRadius = FloatForKey( e, "_filteradius" ); + if( filterRadius == 0.0f ) + filterRadius = FloatForKey( e, "_filter" ); + if( filterRadius < 0.0f ) + filterRadius = 0.0f; + light->filterRadius = filterRadius; + + /* set light color */ + _color = ValueForKey( e, "_color" ); + if( _color && _color[ 0 ] ) + { + sscanf( _color, "%f %f %f", &light->color[ 0 ], &light->color[ 1 ], &light->color[ 2 ] ); + if (!(light->flags & LIGHT_UNNORMALIZED)) + { + ColorNormalize( light->color, light->color ); + } + } + else + light->color[ 0 ] = light->color[ 1 ] = light->color[ 2 ] = 1.0f; + + light->extraDist = FloatForKey( e, "_extradist" ); + if(light->extraDist == 0.0f) + light->extraDist = extraDist; + + intensity = intensity * pointScale; + light->photons = intensity; + + light->type = EMIT_POINT; + + /* set falloff threshold */ + light->falloffTolerance = falloffTolerance / numSamples; + + /* lights with a target will be spotlights */ + target = ValueForKey( e, "target" ); + if( target[ 0 ] ) + { + float radius; + float dist; + sun_t sun; + const char *_sun; + + + /* get target */ + e2 = FindTargetEntity( target ); + if( e2 == NULL ) + { + Sys_Printf( "WARNING: light at (%i %i %i) has missing target\n", + (int) light->origin[ 0 ], (int) light->origin[ 1 ], (int) light->origin[ 2 ] ); + } + else + { + /* not a point light */ + numPointLights--; + numSpotLights++; + + /* make a spotlight */ + GetVectorForKey( e2, "origin", dest ); + VectorSubtract( dest, light->origin, light->normal ); + dist = VectorNormalize( light->normal, light->normal ); + radius = FloatForKey( e, "radius" ); + if( !radius ) + radius = 64; + if( !dist ) + dist = 64; + light->radiusByDist = (radius + 16) / dist; + light->type = EMIT_SPOT; + + /* ydnar: wolf mods: spotlights always use nonlinear + angle attenuation */ + light->flags &= ~LIGHT_ATTEN_LINEAR; + light->flags |= LIGHT_ATTEN_ANGLE; + light->fade = 1.0f; + + /* ydnar: is this a sun? */ + _sun = ValueForKey( e, "_sun" ); + if( _sun[ 0 ] == '1' ) + { + /* not a spot light */ + numSpotLights--; + + /* unlink this light */ + lights = light->next; + + /* make a sun */ + VectorScale( light->normal, -1.0f, sun.direction ); + VectorCopy( light->color, sun.color ); + sun.photons = (intensity / pointScale); + sun.deviance = deviance / 180.0f * Q_PI; + sun.numSamples = numSamples; + sun.style = noStyles ? LS_NORMAL : light->style; + sun.next = NULL; + + /* make a sun light */ + CreateSunLight( &sun ); + + /* free original light */ + free( light ); + light = NULL; + + /* skip the rest of this love story */ + continue; + } + } + } + + /* jitter the light */ + for( j = 1; j < numSamples; j++ ) + { + /* create a light */ + light2 = safe_malloc( sizeof( *light ) ); + memcpy( light2, light, sizeof( *light ) ); + light2->next = lights; + lights = light2; + + /* add to counts */ + if( light->type == EMIT_SPOT ) + numSpotLights++; + else + numPointLights++; + + /* jitter it */ + light2->origin[ 0 ] = light->origin[ 0 ] + (Random() * 2.0f - 1.0f) * deviance; + light2->origin[ 1 ] = light->origin[ 1 ] + (Random() * 2.0f - 1.0f) * deviance; + light2->origin[ 2 ] = light->origin[ 2 ] + (Random() * 2.0f - 1.0f) * deviance; + } + } +} + + + +/* +CreateSurfaceLights() - ydnar +this hijacks the radiosity code to generate surface lights for first pass +*/ + +#define APPROX_BOUNCE 1.0f + +void CreateSurfaceLights( void ) +{ + int i; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + shaderInfo_t *si; + light_t *light; + float subdivide; + vec3_t origin; + clipWork_t cw; + const char *nss; + + + /* get sun shader supressor */ + nss = ValueForKey( &entities[ 0 ], "_noshadersun" ); + + /* walk the list of surfaces */ + for( i = 0; i < numBSPDrawSurfaces; i++ ) + { + /* get surface and other bits */ + ds = &bspDrawSurfaces[ i ]; + info = &surfaceInfos[ i ]; + si = info->si; + + /* sunlight? */ + if( si->sun != NULL && nss[ 0 ] != '1' ) + { + Sys_FPrintf( SYS_VRB, "Sun: %s\n", si->shader ); + CreateSunLight( si->sun ); + si->sun = NULL; /* FIXME: leak! */ + } + + /* sky light? */ + if( si->skyLightValue > 0.0f ) + { + Sys_FPrintf( SYS_VRB, "Sky: %s\n", si->shader ); + CreateSkyLights( si->color, si->skyLightValue, si->skyLightIterations, si->lightFilterRadius, si->lightStyle ); + si->skyLightValue = 0.0f; /* FIXME: hack! */ + } + + /* try to early out */ + if( si->value <= 0 ) + continue; + + /* autosprite shaders become point lights */ + if( si->autosprite ) + { + /* create an average xyz */ + VectorAdd( info->mins, info->maxs, origin ); + VectorScale( origin, 0.5f, origin ); + + /* create a light */ + light = safe_malloc( sizeof( *light ) ); + memset( light, 0, sizeof( *light ) ); + light->next = lights; + lights = light; + + /* set it up */ + light->flags = LIGHT_Q3A_DEFAULT; + light->type = EMIT_POINT; + light->photons = si->value * pointScale; + light->fade = 1.0f; + light->si = si; + VectorCopy( origin, light->origin ); + VectorCopy( si->color, light->color ); + light->falloffTolerance = falloffTolerance; + light->style = si->lightStyle; + + /* add to point light count and continue */ + numPointLights++; + continue; + } + + /* get subdivision amount */ + if( si->lightSubdivide > 0 ) + subdivide = si->lightSubdivide; + else + subdivide = defaultLightSubdivide; + + /* switch on type */ + switch( ds->surfaceType ) + { + case MST_PLANAR: + case MST_TRIANGLE_SOUP: + RadLightForTriangles( i, 0, info->lm, si, APPROX_BOUNCE, subdivide, &cw ); + break; + + case MST_PATCH: + RadLightForPatch( i, 0, info->lm, si, APPROX_BOUNCE, subdivide, &cw ); + break; + + default: + break; + } + } +} + + + +/* +SetEntityOrigins() +find the offset values for inline models +*/ + +void SetEntityOrigins( void ) +{ + int i, j, k, f; + entity_t *e; + vec3_t origin; + const char *key; + int modelnum; + bspModel_t *dm; + bspDrawSurface_t *ds; + + + /* ydnar: copy drawverts into private storage for nefarious purposes */ + yDrawVerts = safe_malloc( numBSPDrawVerts * sizeof( bspDrawVert_t ) ); + memcpy( yDrawVerts, bspDrawVerts, numBSPDrawVerts * sizeof( bspDrawVert_t ) ); + + /* set the entity origins */ + for( i = 0; i < numEntities; i++ ) + { + /* get entity and model */ + e = &entities[ i ]; + key = ValueForKey( e, "model" ); + if( key[ 0 ] != '*' ) + continue; + modelnum = atoi( key + 1 ); + dm = &bspModels[ modelnum ]; + + /* get entity origin */ + key = ValueForKey( e, "origin" ); + if( key[ 0 ] == '\0' ) + continue; + GetVectorForKey( e, "origin", origin ); + + /* set origin for all surfaces for this model */ + for( j = 0; j < dm->numBSPSurfaces; j++ ) + { + /* get drawsurf */ + ds = &bspDrawSurfaces[ dm->firstBSPSurface + j ]; + + /* set its verts */ + for( k = 0; k < ds->numVerts; k++ ) + { + f = ds->firstVert + k; + VectorAdd( origin, bspDrawVerts[ f ].xyz, yDrawVerts[ f ].xyz ); + } + } + } +} + + + +/* +PointToPolygonFormFactor() +calculates the area over a point/normal hemisphere a winding covers +ydnar: fixme: there has to be a faster way to calculate this +without the expensive per-vert sqrts and transcendental functions +ydnar 2002-09-30: added -faster switch because only 19% deviance > 10% +between this and the approximation +*/ + +#define ONE_OVER_2PI 0.159154942f //% (1.0f / (2.0f * 3.141592657f)) + +float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w ) +{ + vec3_t triVector, triNormal; + int i, j; + vec3_t dirs[ MAX_POINTS_ON_WINDING ]; + float total; + float dot, angle, facing; + + + /* this is expensive */ + for( i = 0; i < w->numpoints; i++ ) + { + VectorSubtract( w->p[ i ], point, dirs[ i ] ); + VectorNormalize( dirs[ i ], dirs[ i ] ); + } + + /* duplicate first vertex to avoid mod operation */ + VectorCopy( dirs[ 0 ], dirs[ i ] ); + + /* calculcate relative area */ + total = 0.0f; + for( i = 0; i < w->numpoints; i++ ) + { + /* get a triangle */ + j = i + 1; + dot = DotProduct( dirs[ i ], dirs[ j ] ); + + /* roundoff can cause slight creep, which gives an IND from acos */ + if( dot > 1.0f ) + dot = 1.0f; + else if( dot < -1.0f ) + dot = -1.0f; + + /* get the angle */ + angle = acos( dot ); + + CrossProduct( dirs[ i ], dirs[ j ], triVector ); + if( VectorNormalize( triVector, triNormal ) < 0.0001f ) + continue; + + facing = DotProduct( normal, triNormal ); + total += facing * angle; + + /* ydnar: this was throwing too many errors with radiosity + crappy maps. ignoring it. */ + if( total > 6.3f || total < -6.3f ) + return 0.0f; + } + + /* now in the range of 0 to 1 over the entire incoming hemisphere */ + //% total /= (2.0f * 3.141592657f); + total *= ONE_OVER_2PI; + return total; +} + + + +/* +LightContributionTosample() +determines the amount of light reaching a sample (luxel or vertex) from a given light +*/ + +int LightContributionToSample( trace_t *trace ) +{ + light_t *light; + float angle; + float add; + float dist; + float addDeluxe = 0.0f, addDeluxeBounceScale = 0.25f; + qboolean angledDeluxe = qtrue; + float colorBrightness; + qboolean doAddDeluxe = qtrue; + + /* get light */ + light = trace->light; + + /* clear color */ + trace->forceSubsampling = 0.0f; /* to make sure */ + VectorClear( trace->color ); + VectorClear( trace->colorNoShadow ); + VectorClear( trace->directionContribution ); + + colorBrightness = RGBTOGRAY( light->color ) * ( 1.0f/255.0f ); + + /* ydnar: early out */ + if( !(light->flags & LIGHT_SURFACES) || light->envelope <= 0.0f ) + return 0; + + /* do some culling checks */ + if( light->type != EMIT_SUN ) + { + /* MrE: if the light is behind the surface */ + if( trace->twoSided == qfalse ) + if( DotProduct( light->origin, trace->normal ) - DotProduct( trace->origin, trace->normal ) < 0.0f ) + return 0; + + /* ydnar: test pvs */ + if( !ClusterVisible( trace->cluster, light->cluster ) ) + return 0; + } + + /* exact point to polygon form factor */ + if( light->type == EMIT_AREA ) + { + float factor; + float d; + vec3_t pushedOrigin; + + /* project sample point into light plane */ + d = DotProduct( trace->origin, light->normal ) - light->dist; + if( d < 3.0f ) + { + /* sample point behind plane? */ + if( !(light->flags & LIGHT_TWOSIDED) && d < -1.0f ) + return 0; + + /* sample plane coincident? */ + if( d > -3.0f && DotProduct( trace->normal, light->normal ) > 0.9f ) + return 0; + } + + /* nudge the point so that it is clearly forward of the light */ + /* so that surfaces meeting a light emitter don't get black edges */ + if( d > -8.0f && d < 8.0f ) + VectorMA( trace->origin, (8.0f - d), light->normal, pushedOrigin ); + else + VectorCopy( trace->origin, pushedOrigin ); + + /* get direction and distance */ + VectorCopy( light->origin, trace->end ); + dist = SetupTrace( trace ); + if( dist >= light->envelope ) + return 0; + + /* ptpff approximation */ + if( faster ) + { + /* angle attenuation */ + angle = DotProduct( trace->normal, trace->direction ); + + /* twosided lighting */ + if( trace->twoSided && angle < 0 ) + { + angle = -angle; + + /* no deluxemap contribution from "other side" light */ + doAddDeluxe = qfalse; + } + + /* attenuate */ + angle *= -DotProduct( light->normal, trace->direction ); + if( angle == 0.0f ) + return 0; + else if( angle < 0.0f && + (trace->twoSided || (light->flags & LIGHT_TWOSIDED)) ) + { + angle = -angle; + + /* no deluxemap contribution from "other side" light */ + doAddDeluxe = qfalse; + } + + /* clamp the distance to prevent super hot spots */ + dist = sqrt(dist * dist + light->extraDist * light->extraDist); + if( dist < 16.0f ) + dist = 16.0f; + + add = light->photons / (dist * dist) * angle; + + if( deluxemap ) + { + if( angledDeluxe ) + addDeluxe = light->photons / (dist * dist) * angle; + else + addDeluxe = light->photons / (dist * dist); + } + } + else + { + /* calculate the contribution */ + factor = PointToPolygonFormFactor( pushedOrigin, trace->normal, light->w ); + if( factor == 0.0f ) + return 0; + else if( factor < 0.0f ) + { + /* twosided lighting */ + if( trace->twoSided || (light->flags & LIGHT_TWOSIDED) ) + { + factor = -factor; + + /* push light origin to other side of the plane */ + VectorMA( light->origin, -2.0f, light->normal, trace->end ); + dist = SetupTrace( trace ); + if( dist >= light->envelope ) + return 0; + + /* no deluxemap contribution from "other side" light */ + doAddDeluxe = qfalse; + } + else + return 0; + } + + /* also don't deluxe if the direction is on the wrong side */ + if(DotProduct(trace->normal, trace->direction) < 0) + { + /* no deluxemap contribution from "other side" light */ + doAddDeluxe = qfalse; + } + + /* ydnar: moved to here */ + add = factor * light->add; + + if( deluxemap ) + addDeluxe = add; + } + } + + /* point/spot lights */ + else if( light->type == EMIT_POINT || light->type == EMIT_SPOT ) + { + /* get direction and distance */ + VectorCopy( light->origin, trace->end ); + dist = SetupTrace( trace ); + if( dist >= light->envelope ) + return 0; + + /* clamp the distance to prevent super hot spots */ + dist = sqrt(dist * dist + light->extraDist * light->extraDist); + if( dist < 16.0f ) + dist = 16.0f; + + /* angle attenuation */ + if( light->flags & LIGHT_ATTEN_ANGLE ) + { + /* standard Lambert attenuation */ + float dot = DotProduct( trace->normal, trace->direction ); + + /* twosided lighting */ + if( trace->twoSided && dot < 0 ) + { + dot = -dot; + + /* no deluxemap contribution from "other side" light */ + doAddDeluxe = qfalse; + } + + /* jal: optional half Lambert attenuation (http://developer.valvesoftware.com/wiki/Half_Lambert) */ + if( lightAngleHL ) + { + if( dot > 0.001f ) // skip coplanar + { + if( dot > 1.0f ) dot = 1.0f; + dot = ( dot * 0.5f ) + 0.5f; + dot *= dot; + } + else + dot = 0; + } + + angle = dot; + } + else + angle = 1.0f; + + if( light->angleScale != 0.0f ) + { + angle /= light->angleScale; + if( angle > 1.0f ) + angle = 1.0f; + } + + /* attenuate */ + if( light->flags & LIGHT_ATTEN_LINEAR ) + { + add = angle * light->photons * linearScale - (dist * light->fade); + if( add < 0.0f ) + add = 0.0f; + + if( deluxemap ) + { + if( angledDeluxe ) + addDeluxe = angle * light->photons * linearScale - (dist * light->fade); + else + addDeluxe = light->photons * linearScale - (dist * light->fade); + + if( addDeluxe < 0.0f ) + addDeluxe = 0.0f; + } + } + else + { + add = (light->photons / (dist * dist)) * angle; + if( add < 0.0f ) + add = 0.0f; + + if( deluxemap ) + { + if( angledDeluxe ) + addDeluxe = (light->photons / (dist * dist)) * angle; + else + addDeluxe = (light->photons / (dist * dist)); + } + + if( addDeluxe < 0.0f ) + addDeluxe = 0.0f; + } + + /* handle spotlights */ + if( light->type == EMIT_SPOT ) + { + float distByNormal, radiusAtDist, sampleRadius; + vec3_t pointAtDist, distToSample; + + /* do cone calculation */ + distByNormal = -DotProduct( trace->displacement, light->normal ); + if( distByNormal < 0.0f ) + return 0; + VectorMA( light->origin, distByNormal, light->normal, pointAtDist ); + radiusAtDist = light->radiusByDist * distByNormal; + VectorSubtract( trace->origin, pointAtDist, distToSample ); + sampleRadius = VectorLength( distToSample ); + + /* outside the cone */ + if( sampleRadius >= radiusAtDist ) + return 0; + + /* attenuate */ + if( sampleRadius > (radiusAtDist - 32.0f) ) + { + add *= ((radiusAtDist - sampleRadius) / 32.0f); + if( add < 0.0f ) + add = 0.0f; + + addDeluxe *= ((radiusAtDist - sampleRadius) / 32.0f); + + if( addDeluxe < 0.0f ) + addDeluxe = 0.0f; + } + } + } + + /* ydnar: sunlight */ + else if( light->type == EMIT_SUN ) + { + /* get origin and direction */ + VectorAdd( trace->origin, light->origin, trace->end ); + dist = SetupTrace( trace ); + + /* angle attenuation */ + if( light->flags & LIGHT_ATTEN_ANGLE ) + { + /* standard Lambert attenuation */ + float dot = DotProduct( trace->normal, trace->direction ); + + /* twosided lighting */ + if( trace->twoSided && dot < 0 ) + { + dot = -dot; + + /* no deluxemap contribution from "other side" light */ + doAddDeluxe = qfalse; + } + + /* jal: optional half Lambert attenuation (http://developer.valvesoftware.com/wiki/Half_Lambert) */ + if( lightAngleHL ) + { + if( dot > 0.001f ) // skip coplanar + { + if( dot > 1.0f ) dot = 1.0f; + dot = ( dot * 0.5f ) + 0.5f; + dot *= dot; + } + else + dot = 0; + } + + angle = dot; + } + else + angle = 1.0f; + + /* attenuate */ + add = light->photons * angle; + + if( deluxemap ) + { + if( angledDeluxe ) + addDeluxe = light->photons * angle; + else + addDeluxe = light->photons; + + if( addDeluxe < 0.0f ) + addDeluxe = 0.0f; + } + + if( add <= 0.0f ) + return 0; + + /* VorteX: set noShadow color */ + VectorScale(light->color, add, trace->colorNoShadow); + + addDeluxe *= colorBrightness; + + if( bouncing ) + { + addDeluxe *= addDeluxeBounceScale; + if( addDeluxe < 0.00390625f ) + addDeluxe = 0.00390625f; + } + + VectorScale( trace->direction, addDeluxe, trace->directionContribution ); + + /* setup trace */ + trace->testAll = qtrue; + VectorScale( light->color, add, trace->color ); + + /* trace to point */ + if( trace->testOcclusion && !trace->forceSunlight ) + { + /* trace */ + TraceLine( trace ); + trace->forceSubsampling *= add; + if( !(trace->compileFlags & C_SKY) || trace->opaque ) + { + VectorClear( trace->color ); + VectorClear( trace->directionContribution ); + + return -1; + } + } + + /* return to sender */ + return 1; + } + else + Error("Light of undefined type!"); + + /* VorteX: set noShadow color */ + VectorScale(light->color, add, trace->colorNoShadow); + + /* ydnar: changed to a variable number */ + if( add <= 0.0f || (add <= light->falloffTolerance && (light->flags & LIGHT_FAST_ACTUAL)) ) + return 0; + + addDeluxe *= colorBrightness; + + /* hack land: scale down the radiosity contribution to light directionality. + Deluxemaps fusion many light directions into one. In a rtl process all lights + would contribute individually to the bump map, so several light sources together + would make it more directional (example: a yellow and red lights received from + opposing sides would light one side in red and the other in blue, adding + the effect of 2 directions applied. In the deluxemapping case, this 2 lights would + neutralize each other making it look like having no direction. + Same thing happens with radiosity. In deluxemapping case the radiosity contribution + is modifying the direction applied from directional lights, making it go closer and closer + to the surface normal the bigger is the amount of radiosity received. + So, for preserving the directional lights contributions, we scale down the radiosity + contribution. It's a hack, but there's a reason behind it */ + if( bouncing ) + { + addDeluxe *= addDeluxeBounceScale; + /* better NOT increase it beyond the original value + if( addDeluxe < 0.00390625f ) + addDeluxe = 0.00390625f; + */ + } + + if(doAddDeluxe) + { + VectorScale( trace->direction, addDeluxe, trace->directionContribution ); + } + + /* setup trace */ + trace->testAll = qfalse; + VectorScale( light->color, add, trace->color ); + + /* raytrace */ + TraceLine( trace ); + trace->forceSubsampling *= add; + if( trace->passSolid || trace->opaque ) + { + VectorClear( trace->color ); + VectorClear( trace->directionContribution ); + + return -1; + } + + /* return to sender */ + return 1; +} + + + +/* +LightingAtSample() +determines the amount of light reaching a sample (luxel or vertex) +*/ + +void LightingAtSample( trace_t *trace, byte styles[ MAX_LIGHTMAPS ], vec3_t colors[ MAX_LIGHTMAPS ] ) +{ + int i, lightmapNum; + + + /* clear colors */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + VectorClear( colors[ lightmapNum ] ); + + /* ydnar: normalmap */ + if( normalmap ) + { + colors[ 0 ][ 0 ] = (trace->normal[ 0 ] + 1.0f) * 127.5f; + colors[ 0 ][ 1 ] = (trace->normal[ 1 ] + 1.0f) * 127.5f; + colors[ 0 ][ 2 ] = (trace->normal[ 2 ] + 1.0f) * 127.5f; + return; + } + + /* ydnar: don't bounce ambient all the time */ + if( !bouncing ) + VectorCopy( ambientColor, colors[ 0 ] ); + + /* ydnar: trace to all the list of lights pre-stored in tw */ + for( i = 0; i < trace->numLights && trace->lights[ i ] != NULL; i++ ) + { + /* set light */ + trace->light = trace->lights[ i ]; + + /* style check */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + if( styles[ lightmapNum ] == trace->light->style || + styles[ lightmapNum ] == LS_NONE ) + break; + } + + /* max of MAX_LIGHTMAPS (4) styles allowed to hit a sample */ + if( lightmapNum >= MAX_LIGHTMAPS ) + continue; + + /* sample light */ + LightContributionToSample( trace ); + if( trace->color[ 0 ] == 0.0f && trace->color[ 1 ] == 0.0f && trace->color[ 2 ] == 0.0f ) + continue; + + /* handle negative light */ + if( trace->light->flags & LIGHT_NEGATIVE ) + VectorScale( trace->color, -1.0f, trace->color ); + + /* set style */ + styles[ lightmapNum ] = trace->light->style; + + /* add it */ + VectorAdd( colors[ lightmapNum ], trace->color, colors[ lightmapNum ] ); + + /* cheap mode */ + if( cheap && + colors[ 0 ][ 0 ] >= 255.0f && + colors[ 0 ][ 1 ] >= 255.0f && + colors[ 0 ][ 2 ] >= 255.0f ) + break; + } +} + + + +/* +LightContributionToPoint() +for a given light, how much light/color reaches a given point in space (with no facing) +note: this is similar to LightContributionToSample() but optimized for omnidirectional sampling +*/ + +int LightContributionToPoint( trace_t *trace ) +{ + light_t *light; + float add, dist; + + + /* get light */ + light = trace->light; + + /* clear color */ + VectorClear( trace->color ); + + /* ydnar: early out */ + if( !(light->flags & LIGHT_GRID) || light->envelope <= 0.0f ) + return qfalse; + + /* is this a sun? */ + if( light->type != EMIT_SUN ) + { + /* sun only? */ + if( sunOnly ) + return qfalse; + + /* test pvs */ + if( !ClusterVisible( trace->cluster, light->cluster ) ) + return qfalse; + } + + /* ydnar: check origin against light's pvs envelope */ + if( trace->origin[ 0 ] > light->maxs[ 0 ] || trace->origin[ 0 ] < light->mins[ 0 ] || + trace->origin[ 1 ] > light->maxs[ 1 ] || trace->origin[ 1 ] < light->mins[ 1 ] || + trace->origin[ 2 ] > light->maxs[ 2 ] || trace->origin[ 2 ] < light->mins[ 2 ] ) + { + gridBoundsCulled++; + return qfalse; + } + + /* set light origin */ + if( light->type == EMIT_SUN ) + VectorAdd( trace->origin, light->origin, trace->end ); + else + VectorCopy( light->origin, trace->end ); + + /* set direction */ + dist = SetupTrace( trace ); + + /* test envelope */ + if( dist > light->envelope ) + { + gridEnvelopeCulled++; + return qfalse; + } + + /* ptpff approximation */ + if( light->type == EMIT_AREA && faster ) + { + /* clamp the distance to prevent super hot spots */ + dist = sqrt(dist * dist + light->extraDist * light->extraDist); + if( dist < 16.0f ) + dist = 16.0f; + + /* attenuate */ + add = light->photons / (dist * dist); + } + + /* exact point to polygon form factor */ + else if( light->type == EMIT_AREA ) + { + float factor, d; + vec3_t pushedOrigin; + + + /* see if the point is behind the light */ + d = DotProduct( trace->origin, light->normal ) - light->dist; + if( !(light->flags & LIGHT_TWOSIDED) && d < -1.0f ) + return qfalse; + + /* nudge the point so that it is clearly forward of the light */ + /* so that surfaces meeting a light emiter don't get black edges */ + if( d > -8.0f && d < 8.0f ) + VectorMA( trace->origin, (8.0f - d), light->normal, pushedOrigin ); + else + VectorCopy( trace->origin, pushedOrigin ); + + /* calculate the contribution (ydnar 2002-10-21: [bug 642] bad normal calc) */ + factor = PointToPolygonFormFactor( pushedOrigin, trace->direction, light->w ); + if( factor == 0.0f ) + return qfalse; + else if( factor < 0.0f ) + { + if( light->flags & LIGHT_TWOSIDED ) + factor = -factor; + else + return qfalse; + } + + /* ydnar: moved to here */ + add = factor * light->add; + } + + /* point/spot lights */ + else if( light->type == EMIT_POINT || light->type == EMIT_SPOT ) + { + /* clamp the distance to prevent super hot spots */ + dist = sqrt(dist * dist + light->extraDist * light->extraDist); + if( dist < 16.0f ) + dist = 16.0f; + + /* attenuate */ + if( light->flags & LIGHT_ATTEN_LINEAR ) + { + add = light->photons * linearScale - (dist * light->fade); + if( add < 0.0f ) + add = 0.0f; + } + else + add = light->photons / (dist * dist); + + /* handle spotlights */ + if( light->type == EMIT_SPOT ) + { + float distByNormal, radiusAtDist, sampleRadius; + vec3_t pointAtDist, distToSample; + + + /* do cone calculation */ + distByNormal = -DotProduct( trace->displacement, light->normal ); + if( distByNormal < 0.0f ) + return qfalse; + VectorMA( light->origin, distByNormal, light->normal, pointAtDist ); + radiusAtDist = light->radiusByDist * distByNormal; + VectorSubtract( trace->origin, pointAtDist, distToSample ); + sampleRadius = VectorLength( distToSample ); + + /* outside the cone */ + if( sampleRadius >= radiusAtDist ) + return qfalse; + + /* attenuate */ + if( sampleRadius > (radiusAtDist - 32.0f) ) + add *= ((radiusAtDist - sampleRadius) / 32.0f); + } + } + + /* ydnar: sunlight */ + else if( light->type == EMIT_SUN ) + { + /* attenuate */ + add = light->photons; + if( add <= 0.0f ) + return qfalse; + + /* setup trace */ + trace->testAll = qtrue; + VectorScale( light->color, add, trace->color ); + + /* trace to point */ + if( trace->testOcclusion && !trace->forceSunlight ) + { + /* trace */ + TraceLine( trace ); + if( !(trace->compileFlags & C_SKY) || trace->opaque ) + { + VectorClear( trace->color ); + return -1; + } + } + + /* return to sender */ + return qtrue; + } + + /* unknown light type */ + else + return qfalse; + + /* ydnar: changed to a variable number */ + if( add <= 0.0f || (add <= light->falloffTolerance && (light->flags & LIGHT_FAST_ACTUAL)) ) + return qfalse; + + /* setup trace */ + trace->testAll = qfalse; + VectorScale( light->color, add, trace->color ); + + /* trace */ + TraceLine( trace ); + if( trace->passSolid ) + { + VectorClear( trace->color ); + return qfalse; + } + + /* we have a valid sample */ + return qtrue; +} + + + +/* +TraceGrid() +grid samples are for quickly determining the lighting +of dynamically placed entities in the world +*/ + +#define MAX_CONTRIBUTIONS 32768 + +typedef struct +{ + vec3_t dir; + vec3_t color; + vec3_t ambient; + int style; +} +contribution_t; + +void TraceGrid( int num ) +{ + int i, j, x, y, z, mod, numCon, numStyles; + float d, step; + vec3_t baseOrigin, cheapColor, color, thisdir; + rawGridPoint_t *gp; + bspGridPoint_t *bgp; + contribution_t contributions[ MAX_CONTRIBUTIONS ]; + trace_t trace; + + /* get grid points */ + gp = &rawGridPoints[ num ]; + bgp = &bspGridPoints[ num ]; + + /* get grid origin */ + mod = num; + z = mod / (gridBounds[ 0 ] * gridBounds[ 1 ]); + mod -= z * (gridBounds[ 0 ] * gridBounds[ 1 ]); + y = mod / gridBounds[ 0 ]; + mod -= y * gridBounds[ 0 ]; + x = mod; + + trace.origin[ 0 ] = gridMins[ 0 ] + x * gridSize[ 0 ]; + trace.origin[ 1 ] = gridMins[ 1 ] + y * gridSize[ 1 ]; + trace.origin[ 2 ] = gridMins[ 2 ] + z * gridSize[ 2 ]; + + /* set inhibit sphere */ + if( gridSize[ 0 ] > gridSize[ 1 ] && gridSize[ 0 ] > gridSize[ 2 ] ) + trace.inhibitRadius = gridSize[ 0 ] * 0.5f; + else if( gridSize[ 1 ] > gridSize[ 0 ] && gridSize[ 1 ] > gridSize[ 2 ] ) + trace.inhibitRadius = gridSize[ 1 ] * 0.5f; + else + trace.inhibitRadius = gridSize[ 2 ] * 0.5f; + + /* find point cluster */ + trace.cluster = ClusterForPointExt( trace.origin, GRID_EPSILON ); + if( trace.cluster < 0 ) + { + /* try to nudge the origin around to find a valid point */ + VectorCopy( trace.origin, baseOrigin ); + for( step = 0; (step += 0.005) <= 1.0; ) + { + VectorCopy( baseOrigin, trace.origin ); + trace.origin[ 0 ] += step * (Random() - 0.5) * gridSize[0]; + trace.origin[ 1 ] += step * (Random() - 0.5) * gridSize[1]; + trace.origin[ 2 ] += step * (Random() - 0.5) * gridSize[2]; + + /* ydnar: changed to find cluster num */ + trace.cluster = ClusterForPointExt( trace.origin, VERTEX_EPSILON ); + if( trace.cluster >= 0 ) + break; + } + + /* can't find a valid point at all */ + if( step > 1.0 ) + return; + } + + /* setup trace */ + trace.testOcclusion = !noTrace; + trace.forceSunlight = qfalse; + trace.recvShadows = WORLDSPAWN_RECV_SHADOWS; + trace.numSurfaces = 0; + trace.surfaces = NULL; + trace.numLights = 0; + trace.lights = NULL; + + /* clear */ + numCon = 0; + VectorClear( cheapColor ); + + /* trace to all the lights, find the major light direction, and divide the + total light between that along the direction and the remaining in the ambient */ + for( trace.light = lights; trace.light != NULL; trace.light = trace.light->next ) + { + float addSize; + + + /* sample light */ + if( !LightContributionToPoint( &trace ) ) + continue; + + /* handle negative light */ + if( trace.light->flags & LIGHT_NEGATIVE ) + VectorScale( trace.color, -1.0f, trace.color ); + + /* add a contribution */ + VectorCopy( trace.color, contributions[ numCon ].color ); + VectorCopy( trace.direction, contributions[ numCon ].dir ); + VectorClear( contributions[ numCon ].ambient ); + contributions[ numCon ].style = trace.light->style; + numCon++; + + /* push average direction around */ + addSize = VectorLength( trace.color ); + VectorMA( gp->dir, addSize, trace.direction, gp->dir ); + + /* stop after a while */ + if( numCon >= (MAX_CONTRIBUTIONS - 1) ) + break; + + /* ydnar: cheap mode */ + VectorAdd( cheapColor, trace.color, cheapColor ); + if( cheapgrid && cheapColor[ 0 ] >= 255.0f && cheapColor[ 1 ] >= 255.0f && cheapColor[ 2 ] >= 255.0f ) + break; + } + + /////// Floodlighting for point ////////////////// + //do our floodlight ambient occlusion loop, and add a single contribution based on the brightest dir + if( floodlighty ) + { + int k; + float addSize, f; + vec3_t dir = { 0, 0, 1 }; + float ambientFrac = 0.25f; + + trace.testOcclusion = qtrue; + trace.forceSunlight = qfalse; + trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; + trace.testAll = qtrue; + + for( k = 0; k < 2; k++ ) + { + if( k == 0 ) // upper hemisphere + { + trace.normal[0] = 0; + trace.normal[1] = 0; + trace.normal[2] = 1; + } + else //lower hemisphere + { + trace.normal[0] = 0; + trace.normal[1] = 0; + trace.normal[2] = -1; + } + + f = FloodLightForSample( &trace, floodlightDistance, floodlight_lowquality ); + + /* add a fraction as pure ambient, half as top-down direction */ + contributions[ numCon ].color[0]= floodlightRGB[0] * floodlightIntensity * f * ( 1.0f - ambientFrac ); + contributions[ numCon ].color[1]= floodlightRGB[1] * floodlightIntensity * f * ( 1.0f - ambientFrac ); + contributions[ numCon ].color[2]= floodlightRGB[2] * floodlightIntensity * f * ( 1.0f - ambientFrac ); + + contributions[ numCon ].ambient[0]= floodlightRGB[0] * floodlightIntensity * f * ambientFrac; + contributions[ numCon ].ambient[1]= floodlightRGB[1] * floodlightIntensity * f * ambientFrac; + contributions[ numCon ].ambient[2]= floodlightRGB[2] * floodlightIntensity * f * ambientFrac; + + contributions[ numCon ].dir[0] = dir[0]; + contributions[ numCon ].dir[1] = dir[1]; + contributions[ numCon ].dir[2] = dir[2]; + + contributions[ numCon ].style = 0; + + /* push average direction around */ + addSize = VectorLength( contributions[ numCon ].color ); + VectorMA( gp->dir, addSize, dir, gp->dir ); + + numCon++; + } + } + ///////////////////// + + /* normalize to get primary light direction */ + VectorNormalize( gp->dir, thisdir ); + + /* now that we have identified the primary light direction, + go back and separate all the light into directed and ambient */ + + numStyles = 1; + for( i = 0; i < numCon; i++ ) + { + /* get relative directed strength */ + d = DotProduct( contributions[ i ].dir, thisdir ); + /* we map 1 to gridDirectionality, and 0 to gridAmbientDirectionality */ + d = gridAmbientDirectionality + d * (gridDirectionality - gridAmbientDirectionality); + if( d < 0.0f ) + d = 0.0f; + + /* find appropriate style */ + for( j = 0; j < numStyles; j++ ) + { + if( gp->styles[ j ] == contributions[ i ].style ) + break; + } + + /* style not found? */ + if( j >= numStyles ) + { + /* add a new style */ + if( numStyles < MAX_LIGHTMAPS ) + { + gp->styles[ numStyles ] = contributions[ i ].style; + bgp->styles[ numStyles ] = contributions[ i ].style; + numStyles++; + //% Sys_Printf( "(%d, %d) ", num, contributions[ i ].style ); + } + + /* fallback */ + else + j = 0; + } + + /* add the directed color */ + VectorMA( gp->directed[ j ], d, contributions[ i ].color, gp->directed[ j ] ); + + /* ambient light will be at 1/4 the value of directed light */ + /* (ydnar: nuke this in favor of more dramatic lighting?) */ + /* (PM: how about actually making it work? d=1 when it got here for single lights/sun :P */ +// d = 0.25f; + /* (Hobbes: always setting it to .25 is hardly any better) */ + d = 0.25f * (1.0f - d); + VectorMA( gp->ambient[ j ], d, contributions[ i ].color, gp->ambient[ j ] ); + + VectorAdd( gp->ambient[ j ], contributions[ i ].ambient, gp->ambient[ j ] ); + +/* + * div0: + * the total light average = ambient value + 0.25 * sum of all directional values + * we can also get the total light average as 0.25 * the sum of all contributions + * + * 0.25 * sum(contribution_i) == ambient + 0.25 * sum(d_i contribution_i) + * + * THIS YIELDS: + * ambient == 0.25 * sum((1 - d_i) contribution_i) + * + * So, 0.25f * (1.0f - d) IS RIGHT. If you want to tune it, tune d BEFORE. + */ + } + + + /* store off sample */ + for( i = 0; i < MAX_LIGHTMAPS; i++ ) + { +#if 0 + /* do some fudging to keep the ambient from being too low (2003-07-05: 0.25 -> 0.125) */ + if( !bouncing ) + VectorMA( gp->ambient[ i ], 0.125f, gp->directed[ i ], gp->ambient[ i ] ); +#endif + + /* set minimum light and copy off to bytes */ + VectorCopy( gp->ambient[ i ], color ); + for( j = 0; j < 3; j++ ) + if( color[ j ] < minGridLight[ j ] ) + color[ j ] = minGridLight[ j ]; + + /* vortex: apply gridscale and gridambientscale here */ + ColorToBytes( color, bgp->ambient[ i ], gridScale*gridAmbientScale ); + ColorToBytes( gp->directed[ i ], bgp->directed[ i ], gridScale ); + } + + /* debug code */ + #if 0 + //% Sys_FPrintf( SYS_VRB, "%10d %10d %10d ", &gp->ambient[ 0 ][ 0 ], &gp->ambient[ 0 ][ 1 ], &gp->ambient[ 0 ][ 2 ] ); + Sys_FPrintf( SYS_VRB, "%9d Amb: (%03.1f %03.1f %03.1f) Dir: (%03.1f %03.1f %03.1f)\n", + num, + gp->ambient[ 0 ][ 0 ], gp->ambient[ 0 ][ 1 ], gp->ambient[ 0 ][ 2 ], + gp->directed[ 0 ][ 0 ], gp->directed[ 0 ][ 1 ], gp->directed[ 0 ][ 2 ] ); + #endif + + /* store direction */ + NormalToLatLong( thisdir, bgp->latLong ); +} + + + +/* +SetupGrid() +calculates the size of the lightgrid and allocates memory +*/ + +void SetupGrid( void ) +{ + int i, j; + vec3_t maxs, oldGridSize; + const char *value; + char temp[ 64 ]; + + + /* don't do this if not grid lighting */ + if( noGridLighting ) + return; + + /* ydnar: set grid size */ + value = ValueForKey( &entities[ 0 ], "gridsize" ); + if( value[ 0 ] != '\0' ) + sscanf( value, "%f %f %f", &gridSize[ 0 ], &gridSize[ 1 ], &gridSize[ 2 ] ); + + /* quantize it */ + VectorCopy( gridSize, oldGridSize ); + for( i = 0; i < 3; i++ ) + gridSize[ i ] = gridSize[ i ] >= 8.0f ? floor( gridSize[ i ] ) : 8.0f; + + /* ydnar: increase gridSize until grid count is smaller than max allowed */ + numRawGridPoints = MAX_MAP_LIGHTGRID + 1; + j = 0; + while( numRawGridPoints > MAX_MAP_LIGHTGRID ) + { + /* get world bounds */ + for( i = 0; i < 3; i++ ) + { + gridMins[ i ] = gridSize[ i ] * ceil( bspModels[ 0 ].mins[ i ] / gridSize[ i ] ); + maxs[ i ] = gridSize[ i ] * floor( bspModels[ 0 ].maxs[ i ] / gridSize[ i ] ); + gridBounds[ i ] = (maxs[ i ] - gridMins[ i ]) / gridSize[ i ] + 1; + } + + /* set grid size */ + numRawGridPoints = gridBounds[ 0 ] * gridBounds[ 1 ] * gridBounds[ 2 ]; + + /* increase grid size a bit */ + if( numRawGridPoints > MAX_MAP_LIGHTGRID ) + gridSize[ j++ % 3 ] += 16.0f; + } + + /* print it */ + Sys_Printf( "Grid size = { %1.0f, %1.0f, %1.0f }\n", gridSize[ 0 ], gridSize[ 1 ], gridSize[ 2 ] ); + + /* different? */ + if( !VectorCompare( gridSize, oldGridSize ) ) + { + sprintf( temp, "%.0f %.0f %.0f", gridSize[ 0 ], gridSize[ 1 ], gridSize[ 2 ] ); + SetKeyValue( &entities[ 0 ], "gridsize", (const char*) temp ); + Sys_FPrintf( SYS_VRB, "Storing adjusted grid size\n" ); + } + + /* 2nd variable. fixme: is this silly? */ + numBSPGridPoints = numRawGridPoints; + + /* allocate lightgrid */ + rawGridPoints = safe_malloc( numRawGridPoints * sizeof( *rawGridPoints ) ); + memset( rawGridPoints, 0, numRawGridPoints * sizeof( *rawGridPoints ) ); + + if( bspGridPoints != NULL ) + free( bspGridPoints ); + bspGridPoints = safe_malloc( numBSPGridPoints * sizeof( *bspGridPoints ) ); + memset( bspGridPoints, 0, numBSPGridPoints * sizeof( *bspGridPoints ) ); + + /* clear lightgrid */ + for( i = 0; i < numRawGridPoints; i++ ) + { + VectorCopy( ambientColor, rawGridPoints[ i ].ambient[ j ] ); + rawGridPoints[ i ].styles[ 0 ] = LS_NORMAL; + bspGridPoints[ i ].styles[ 0 ] = LS_NORMAL; + for( j = 1; j < MAX_LIGHTMAPS; j++ ) + { + rawGridPoints[ i ].styles[ j ] = LS_NONE; + bspGridPoints[ i ].styles[ j ] = LS_NONE; + } + } + + /* note it */ + Sys_Printf( "%9d grid points\n", numRawGridPoints ); +} + + + +/* +LightWorld() +does what it says... +*/ + +void LightWorld( void ) +{ + vec3_t color; + float f; + int b, bt; + qboolean minVertex, minGrid; + const char *value; + + + /* ydnar: smooth normals */ + if( shade ) + { + Sys_Printf( "--- SmoothNormals ---\n" ); + SmoothNormals(); + } + + /* determine the number of grid points */ + Sys_Printf( "--- SetupGrid ---\n" ); + SetupGrid(); + + /* find the optional minimum lighting values */ + GetVectorForKey( &entities[ 0 ], "_color", color ); + if( VectorLength( color ) == 0.0f ) + VectorSet( color, 1.0, 1.0, 1.0 ); + + /* ambient */ + f = FloatForKey( &entities[ 0 ], "_ambient" ); + if( f == 0.0f ) + f = FloatForKey( &entities[ 0 ], "ambient" ); + VectorScale( color, f, ambientColor ); + + /* minvertexlight */ + minVertex = qfalse; + value = ValueForKey( &entities[ 0 ], "_minvertexlight" ); + if( value[ 0 ] != '\0' ) + { + minVertex = qtrue; + f = atof( value ); + VectorScale( color, f, minVertexLight ); + } + + /* mingridlight */ + minGrid = qfalse; + value = ValueForKey( &entities[ 0 ], "_mingridlight" ); + if( value[ 0 ] != '\0' ) + { + minGrid = qtrue; + f = atof( value ); + VectorScale( color, f, minGridLight ); + } + + /* minlight */ + value = ValueForKey( &entities[ 0 ], "_minlight" ); + if( value[ 0 ] != '\0' ) + { + f = atof( value ); + VectorScale( color, f, minLight ); + if( minVertex == qfalse ) + VectorScale( color, f, minVertexLight ); + if( minGrid == qfalse ) + VectorScale( color, f, minGridLight ); + } + + /* create world lights */ + Sys_FPrintf( SYS_VRB, "--- CreateLights ---\n" ); + CreateEntityLights(); + CreateSurfaceLights(); + Sys_Printf( "%9d point lights\n", numPointLights ); + Sys_Printf( "%9d spotlights\n", numSpotLights ); + Sys_Printf( "%9d diffuse (area) lights\n", numDiffuseLights ); + Sys_Printf( "%9d sun/sky lights\n", numSunLights ); + + /* calculate lightgrid */ + if( !noGridLighting ) + { + /* ydnar: set up light envelopes */ + SetupEnvelopes( qtrue, fastgrid ); + + Sys_Printf( "--- TraceGrid ---\n" ); + inGrid = qtrue; + RunThreadsOnIndividual( numRawGridPoints, qtrue, TraceGrid ); + inGrid = qfalse; + Sys_Printf( "%d x %d x %d = %d grid\n", + gridBounds[ 0 ], gridBounds[ 1 ], gridBounds[ 2 ], numBSPGridPoints ); + + /* ydnar: emit statistics on light culling */ + Sys_FPrintf( SYS_VRB, "%9d grid points envelope culled\n", gridEnvelopeCulled ); + Sys_FPrintf( SYS_VRB, "%9d grid points bounds culled\n", gridBoundsCulled ); + } + + /* slight optimization to remove a sqrt */ + subdivideThreshold *= subdivideThreshold; + + /* map the world luxels */ + Sys_Printf( "--- MapRawLightmap ---\n" ); + RunThreadsOnIndividual( numRawLightmaps, qtrue, MapRawLightmap ); + Sys_Printf( "%9d luxels\n", numLuxels ); + Sys_Printf( "%9d luxels mapped\n", numLuxelsMapped ); + Sys_Printf( "%9d luxels occluded\n", numLuxelsOccluded ); + + /* dirty them up */ + if( dirty ) + { + Sys_Printf( "--- DirtyRawLightmap ---\n" ); + RunThreadsOnIndividual( numRawLightmaps, qtrue, DirtyRawLightmap ); + } + + /* floodlight pass */ + FloodlightRawLightmaps(); + + /* ydnar: set up light envelopes */ + SetupEnvelopes( qfalse, fast ); + + /* light up my world */ + lightsPlaneCulled = 0; + lightsEnvelopeCulled = 0; + lightsBoundsCulled = 0; + lightsClusterCulled = 0; + + Sys_Printf( "--- IlluminateRawLightmap ---\n" ); + RunThreadsOnIndividual( numRawLightmaps, qtrue, IlluminateRawLightmap ); + Sys_Printf( "%9d luxels illuminated\n", numLuxelsIlluminated ); + + StitchSurfaceLightmaps(); + + Sys_Printf( "--- IlluminateVertexes ---\n" ); + RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, IlluminateVertexes ); + Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated ); + + /* ydnar: emit statistics on light culling */ + Sys_FPrintf( SYS_VRB, "%9d lights plane culled\n", lightsPlaneCulled ); + Sys_FPrintf( SYS_VRB, "%9d lights envelope culled\n", lightsEnvelopeCulled ); + Sys_FPrintf( SYS_VRB, "%9d lights bounds culled\n", lightsBoundsCulled ); + Sys_FPrintf( SYS_VRB, "%9d lights cluster culled\n", lightsClusterCulled ); + + /* radiosity */ + b = 1; + bt = bounce; + while( bounce > 0 ) + { + /* store off the bsp between bounces */ + StoreSurfaceLightmaps(); + UnparseEntities(); + Sys_Printf( "Writing %s\n", source ); + WriteBSPFile( source ); + + /* note it */ + Sys_Printf( "\n--- Radiosity (bounce %d of %d) ---\n", b, bt ); + + /* flag bouncing */ + bouncing = qtrue; + VectorClear( ambientColor ); + floodlighty = qfalse; + + /* generate diffuse lights */ + RadFreeLights(); + RadCreateDiffuseLights(); + + /* setup light envelopes */ + SetupEnvelopes( qfalse, fastbounce ); + if( numLights == 0 ) + { + Sys_Printf( "No diffuse light to calculate, ending radiosity.\n" ); + break; + } + + /* add to lightgrid */ + if( bouncegrid ) + { + gridEnvelopeCulled = 0; + gridBoundsCulled = 0; + + Sys_Printf( "--- BounceGrid ---\n" ); + inGrid = qtrue; + RunThreadsOnIndividual( numRawGridPoints, qtrue, TraceGrid ); + inGrid = qfalse; + Sys_FPrintf( SYS_VRB, "%9d grid points envelope culled\n", gridEnvelopeCulled ); + Sys_FPrintf( SYS_VRB, "%9d grid points bounds culled\n", gridBoundsCulled ); + } + + /* light up my world */ + lightsPlaneCulled = 0; + lightsEnvelopeCulled = 0; + lightsBoundsCulled = 0; + lightsClusterCulled = 0; + + Sys_Printf( "--- IlluminateRawLightmap ---\n" ); + RunThreadsOnIndividual( numRawLightmaps, qtrue, IlluminateRawLightmap ); + Sys_Printf( "%9d luxels illuminated\n", numLuxelsIlluminated ); + Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated ); + + StitchSurfaceLightmaps(); + + Sys_Printf( "--- IlluminateVertexes ---\n" ); + RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, IlluminateVertexes ); + Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated ); + + /* ydnar: emit statistics on light culling */ + Sys_FPrintf( SYS_VRB, "%9d lights plane culled\n", lightsPlaneCulled ); + Sys_FPrintf( SYS_VRB, "%9d lights envelope culled\n", lightsEnvelopeCulled ); + Sys_FPrintf( SYS_VRB, "%9d lights bounds culled\n", lightsBoundsCulled ); + Sys_FPrintf( SYS_VRB, "%9d lights cluster culled\n", lightsClusterCulled ); + + /* interate */ + bounce--; + b++; + } +} + + + +/* +LightMain() +main routine for light processing +*/ + +int LightMain( int argc, char **argv ) +{ + int i; + float f; + char mapSource[ 1024 ]; + const char *value; + int lightmapMergeSize = 0; + qboolean lightSamplesInsist = qfalse; + + + /* note it */ + Sys_Printf( "--- Light ---\n" ); + Sys_Printf( "--- ProcessGameSpecific ---\n" ); + + /* set standard game flags */ + wolfLight = game->wolfLight; + if (wolfLight == qtrue) + Sys_Printf( " lightning model: wolf\n" ); + else + Sys_Printf( " lightning model: quake3\n" ); + + lmCustomSize = game->lightmapSize; + Sys_Printf( " lightmap size: %d x %d pixels\n", lmCustomSize, lmCustomSize ); + + lightmapGamma = game->lightmapGamma; + Sys_Printf( " lightning gamma: %f\n", lightmapGamma ); + + lightmapCompensate = game->lightmapCompensate; + Sys_Printf( " lightning compensation: %f\n", lightmapCompensate ); + + lightmapExposure = game->lightmapExposure; + Sys_Printf( " lightning exposure: %f\n", lightmapExposure ); + + gridScale = game->gridScale; + Sys_Printf( " lightgrid scale: %f\n", gridScale ); + + gridAmbientScale = game->gridAmbientScale; + Sys_Printf( " lightgrid ambient scale: %f\n", gridAmbientScale ); + + lightAngleHL = game->lightAngleHL; + if( lightAngleHL ) + Sys_Printf( " half lambert light angle attenuation enabled \n" ); + + noStyles = game->noStyles; + if (noStyles == qtrue) + Sys_Printf( " shader lightstyles hack: disabled\n" ); + else + Sys_Printf( " shader lightstyles hack: enabled\n" ); + + keepLights = game->keepLights; + if (keepLights == qtrue) + Sys_Printf( " keep lights: enabled\n" ); + else + Sys_Printf( " keep lights: disabled\n" ); + + patchShadows = game->patchShadows; + if (patchShadows == qtrue) + Sys_Printf( " patch shadows: enabled\n" ); + else + Sys_Printf( " patch shadows: disabled\n" ); + + deluxemap = game->deluxeMap; + deluxemode = game->deluxeMode; + if (deluxemap == qtrue) + { + if (deluxemode) + Sys_Printf( " deluxemapping: enabled with tangentspace deluxemaps\n" ); + else + Sys_Printf( " deluxemapping: enabled with modelspace deluxemaps\n" ); + } + else + Sys_Printf( " deluxemapping: disabled\n" ); + + Sys_Printf( "--- ProcessCommandLine ---\n" ); + + /* process commandline arguments */ + for( i = 1; i < (argc - 1); i++ ) + { + /* lightsource scaling */ + if( !strcmp( argv[ i ], "-point" ) || !strcmp( argv[ i ], "-pointscale" ) ) + { + f = atof( argv[ i + 1 ] ); + pointScale *= f; + Sys_Printf( "Point (entity) light scaled by %f to %f\n", f, pointScale ); + i++; + } + + else if( !strcmp( argv[ i ], "-area" ) || !strcmp( argv[ i ], "-areascale" ) ) + { + f = atof( argv[ i + 1 ] ); + areaScale *= f; + Sys_Printf( "Area (shader) light scaled by %f to %f\n", f, areaScale ); + i++; + } + + else if( !strcmp( argv[ i ], "-sky" ) || !strcmp( argv[ i ], "-skyscale" ) ) + { + f = atof( argv[ i + 1 ] ); + skyScale *= f; + Sys_Printf( "Sky/sun light scaled by %f to %f\n", f, skyScale ); + i++; + } + + else if( !strcmp( argv[ i ], "-bouncescale" ) ) + { + f = atof( argv[ i + 1 ] ); + bounceScale *= f; + Sys_Printf( "Bounce (radiosity) light scaled by %f to %f\n", f, bounceScale ); + i++; + } + + else if( !strcmp( argv[ i ], "-scale" ) ) + { + f = atof( argv[ i + 1 ] ); + pointScale *= f; + areaScale *= f; + skyScale *= f; + bounceScale *= f; + Sys_Printf( "All light scaled by %f\n", f ); + i++; + } + + else if( !strcmp( argv[ i ], "-gridscale" ) ) + { + f = atof( argv[ i + 1 ] ); + Sys_Printf( "Grid lightning scaled by %f\n", f ); + gridScale *= f; + i++; + } + + else if( !strcmp( argv[ i ], "-gridambientscale" ) ) + { + f = atof( argv[ i + 1 ] ); + Sys_Printf( "Grid ambient lightning scaled by %f\n", f ); + gridAmbientScale *= f; + i++; + } + + else if( !strcmp( argv[ i ], "-griddirectionality" ) ) + { + f = atof( argv[ i + 1 ] ); + if(f > 1) f = 1; + if(f < gridAmbientDirectionality) gridAmbientDirectionality = f; + Sys_Printf( "Grid directionality is %f\n", f ); + gridDirectionality = f; + i++; + } + + else if( !strcmp( argv[ i ], "-gridambientdirectionality" ) ) + { + f = atof( argv[ i + 1 ] ); + if(f < -1) f = -1; + if(f > gridDirectionality) gridDirectionality = f; + Sys_Printf( "Grid ambient directionality is %f\n", f ); + gridAmbientDirectionality = f; + i++; + } + + else if( !strcmp( argv[ i ], "-gamma" ) ) + { + f = atof( argv[ i + 1 ] ); + lightmapGamma = f; + Sys_Printf( "Lighting gamma set to %f\n", lightmapGamma ); + i++; + } + + else if( !strcmp( argv[ i ], "-exposure" ) ) + { + f = atof( argv[ i + 1 ] ); + lightmapExposure = f; + Sys_Printf( "Lighting exposure set to %f\n", lightmapExposure ); + i++; + } + + else if( !strcmp( argv[ i ], "-compensate" ) ) + { + f = atof( argv[ i + 1 ] ); + if( f <= 0.0f ) + f = 1.0f; + lightmapCompensate = f; + Sys_Printf( "Lighting compensation set to 1/%f\n", lightmapCompensate ); + i++; + } + + /* ydnar switches */ + else if( !strcmp( argv[ i ], "-bounce" ) ) + { + bounce = atoi( argv[ i + 1 ] ); + if( bounce < 0 ) + bounce = 0; + else if( bounce > 0 ) + Sys_Printf( "Radiosity enabled with %d bounce(s)\n", bounce ); + i++; + } + + else if( !strcmp( argv[ i ], "-supersample" ) || !strcmp( argv[ i ], "-super" ) ) + { + superSample = atoi( argv[ i + 1 ] ); + if( superSample < 1 ) + superSample = 1; + else if( superSample > 1 ) + Sys_Printf( "Ordered-grid supersampling enabled with %d sample(s) per lightmap texel\n", (superSample * superSample) ); + i++; + } + + else if( !strcmp( argv[ i ], "-randomsamples" ) ) + { + lightRandomSamples = qtrue; + Sys_Printf( "Random sampling enabled\n", lightRandomSamples ); + } + + else if( !strcmp( argv[ i ], "-samples" ) ) + { + if(*argv[i+1] == '+') + lightSamplesInsist = qtrue; + else + lightSamplesInsist = qfalse; + lightSamples = atoi( argv[ i + 1 ] ); + if( lightSamples < 1 ) + lightSamples = 1; + else if( lightSamples > 1 ) + Sys_Printf( "Adaptive supersampling enabled with %d sample(s) per lightmap texel\n", lightSamples ); + i++; + } + + else if( !strcmp( argv[ i ], "-samplessearchboxsize" ) ) + { + lightSamplesSearchBoxSize = atoi( argv[ i + 1 ] ); + if( lightSamplesSearchBoxSize <= 0 ) + lightSamplesSearchBoxSize = 1; + if( lightSamplesSearchBoxSize > 4 ) + lightSamplesSearchBoxSize = 4; /* more makes no sense */ + else if( lightSamplesSearchBoxSize != 1 ) + Sys_Printf( "Adaptive supersampling uses %f times the normal search box size\n", lightSamplesSearchBoxSize ); + i++; + } + + else if( !strcmp( argv[ i ], "-filter" ) ) + { + filter = qtrue; + Sys_Printf( "Lightmap filtering enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-dark" ) ) + { + dark = qtrue; + Sys_Printf( "Dark lightmap seams enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-shadeangle" ) ) + { + shadeAngleDegrees = atof( argv[ i + 1 ] ); + if( shadeAngleDegrees < 0.0f ) + shadeAngleDegrees = 0.0f; + else if( shadeAngleDegrees > 0.0f ) + { + shade = qtrue; + Sys_Printf( "Phong shading enabled with a breaking angle of %f degrees\n", shadeAngleDegrees ); + } + i++; + } + + else if( !strcmp( argv[ i ], "-thresh" ) ) + { + subdivideThreshold = atof( argv[ i + 1 ] ); + if( subdivideThreshold < 0 ) + subdivideThreshold = DEFAULT_SUBDIVIDE_THRESHOLD; + else + Sys_Printf( "Subdivision threshold set at %.3f\n", subdivideThreshold ); + i++; + } + + else if( !strcmp( argv[ i ], "-approx" ) ) + { + approximateTolerance = atoi( argv[ i + 1 ] ); + if( approximateTolerance < 0 ) + approximateTolerance = 0; + else if( approximateTolerance > 0 ) + Sys_Printf( "Approximating lightmaps within a byte tolerance of %d\n", approximateTolerance ); + i++; + } + else if( !strcmp( argv[ i ], "-deluxe" ) || !strcmp( argv[ i ], "-deluxemap" ) ) + { + deluxemap = qtrue; + Sys_Printf( "Generating deluxemaps for average light direction\n" ); + } + else if( !strcmp( argv[ i ], "-deluxemode" )) + { + deluxemode = atoi( argv[ i + 1 ] ); + if (deluxemode == 0 || deluxemode > 1 || deluxemode < 0) + { + Sys_Printf( "Generating modelspace deluxemaps\n" ); + deluxemode = 0; + } + else + Sys_Printf( "Generating tangentspace deluxemaps\n" ); + i++; + } + else if( !strcmp( argv[ i ], "-nodeluxe" ) || !strcmp( argv[ i ], "-nodeluxemap" ) ) + { + deluxemap = qfalse; + Sys_Printf( "Disabling generating of deluxemaps for average light direction\n" ); + } + else if( !strcmp( argv[ i ], "-external" ) ) + { + externalLightmaps = qtrue; + Sys_Printf( "Storing all lightmaps externally\n" ); + } + + else if( !strcmp( argv[ i ], "-lightmapsize" ) ) + { + lmCustomSize = atoi( argv[ i + 1 ] ); + + /* must be a power of 2 and greater than 2 */ + if( ((lmCustomSize - 1) & lmCustomSize) || lmCustomSize < 2 ) + { + Sys_Printf( "WARNING: Lightmap size must be a power of 2, greater or equal to 2 pixels.\n" ); + lmCustomSize = game->lightmapSize; + } + i++; + Sys_Printf( "Default lightmap size set to %d x %d pixels\n", lmCustomSize, lmCustomSize ); + + /* enable external lightmaps */ + if( lmCustomSize != game->lightmapSize ) + { + externalLightmaps = qtrue; + Sys_Printf( "Storing all lightmaps externally\n" ); + } + } + + else if( !strcmp( argv[ i ], "-rawlightmapsizelimit" ) ) + { + lmLimitSize = atoi( argv[ i + 1 ] ); + + i++; + Sys_Printf( "Raw lightmap size limit set to %d x %d pixels\n", lmLimitSize, lmLimitSize ); + } + + else if( !strcmp( argv[ i ], "-lightmapdir" ) ) + { + lmCustomDir = argv[i + 1]; + i++; + Sys_Printf( "Lightmap directory set to %s\n", lmCustomDir ); + externalLightmaps = qtrue; + Sys_Printf( "Storing all lightmaps externally\n" ); + } + + /* ydnar: add this to suppress warnings */ + else if( !strcmp( argv[ i ], "-custinfoparms") ) + { + Sys_Printf( "Custom info parms enabled\n" ); + useCustomInfoParms = qtrue; + } + + else if( !strcmp( argv[ i ], "-wolf" ) ) + { + /* -game should already be set */ + wolfLight = qtrue; + Sys_Printf( "Enabling Wolf lighting model (linear default)\n" ); + } + + else if( !strcmp( argv[ i ], "-q3" ) ) + { + /* -game should already be set */ + wolfLight = qfalse; + Sys_Printf( "Enabling Quake 3 lighting model (nonlinear default)\n" ); + } + + else if( !strcmp( argv[ i ], "-extradist" ) ) + { + extraDist = atof( argv[ i + 1 ] ); + if( extraDist < 0 ) + extraDist = 0; + i++; + Sys_Printf( "Default extra radius set to %f units\n", extraDist ); + } + + else if( !strcmp( argv[ i ], "-sunonly" ) ) + { + sunOnly = qtrue; + Sys_Printf( "Only computing sunlight\n" ); + } + + else if( !strcmp( argv[ i ], "-bounceonly" ) ) + { + bounceOnly = qtrue; + Sys_Printf( "Storing bounced light (radiosity) only\n" ); + } + + else if( !strcmp( argv[ i ], "-nocollapse" ) ) + { + noCollapse = qtrue; + Sys_Printf( "Identical lightmap collapsing disabled\n" ); + } + + else if( !strcmp( argv[ i ], "-nolightmapsearch" ) ) + { + lightmapSearchBlockSize = 1; + Sys_Printf( "No lightmap searching - all lightmaps will be sequential\n" ); + } + + else if( !strcmp( argv[ i ], "-lightmapsearchpower" ) ) + { + lightmapMergeSize = (game->lightmapSize << atoi(argv[i+1])); + ++i; + Sys_Printf( "Restricted lightmap searching enabled - optimize for lightmap merge power %d (size %d)\n", atoi(argv[i]), lightmapMergeSize ); + } + + else if( !strcmp( argv[ i ], "-lightmapsearchblocksize" ) ) + { + lightmapSearchBlockSize = atoi(argv[i+1]); + ++i; + Sys_Printf( "Restricted lightmap searching enabled - block size set to %d\n", lightmapSearchBlockSize ); + } + + else if( !strcmp( argv[ i ], "-shade" ) ) + { + shade = qtrue; + Sys_Printf( "Phong shading enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-bouncegrid") ) + { + bouncegrid = qtrue; + if( bounce > 0 ) + Sys_Printf( "Grid lighting with radiosity enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-smooth" ) ) + { + lightSamples = EXTRA_SCALE; + Sys_Printf( "The -smooth argument is deprecated, use \"-samples 2\" instead\n" ); + } + + else if( !strcmp( argv[ i ], "-fast" ) ) + { + fast = qtrue; + fastgrid = qtrue; + fastbounce = qtrue; + Sys_Printf( "Fast mode enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-faster" ) ) + { + faster = qtrue; + fast = qtrue; + fastgrid = qtrue; + fastbounce = qtrue; + Sys_Printf( "Faster mode enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-fastgrid" ) ) + { + fastgrid = qtrue; + Sys_Printf( "Fast grid lighting enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-fastbounce" ) ) + { + fastbounce = qtrue; + Sys_Printf( "Fast bounce mode enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-cheap" ) ) + { + cheap = qtrue; + cheapgrid = qtrue; + Sys_Printf( "Cheap mode enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-cheapgrid" ) ) + { + cheapgrid = qtrue; + Sys_Printf( "Cheap grid mode enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-normalmap" ) ) + { + normalmap = qtrue; + Sys_Printf( "Storing normal map instead of lightmap\n" ); + } + + else if( !strcmp( argv[ i ], "-trisoup" ) ) + { + trisoup = qtrue; + Sys_Printf( "Converting brush faces to triangle soup\n" ); + } + + else if( !strcmp( argv[ i ], "-debug" ) ) + { + debug = qtrue; + Sys_Printf( "Lightmap debugging enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-debugsurfaces" ) || !strcmp( argv[ i ], "-debugsurface" ) ) + { + debugSurfaces = qtrue; + Sys_Printf( "Lightmap surface debugging enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-debugunused" ) ) + { + debugUnused = qtrue; + Sys_Printf( "Unused luxel debugging enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-debugaxis" ) ) + { + debugAxis = qtrue; + Sys_Printf( "Lightmap axis debugging enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-debugcluster" ) ) + { + debugCluster = qtrue; + Sys_Printf( "Luxel cluster debugging enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-debugorigin" ) ) + { + debugOrigin = qtrue; + Sys_Printf( "Luxel origin debugging enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-debugdeluxe" ) ) + { + deluxemap = qtrue; + debugDeluxemap = qtrue; + Sys_Printf( "Deluxemap debugging enabled\n" ); + } + + else if( !strcmp( argv[ i ], "-export" ) ) + { + exportLightmaps = qtrue; + Sys_Printf( "Exporting lightmaps\n" ); + } + + else if( !strcmp(argv[ i ], "-notrace" )) + { + noTrace = qtrue; + Sys_Printf( "Shadow occlusion disabled\n" ); + } + else if( !strcmp(argv[ i ], "-patchshadows" ) ) + { + patchShadows = qtrue; + Sys_Printf( "Patch shadow casting enabled\n" ); + } + else if( !strcmp( argv[ i ], "-extra" ) ) + { + superSample = EXTRA_SCALE; /* ydnar */ + Sys_Printf( "The -extra argument is deprecated, use \"-super 2\" instead\n" ); + } + else if( !strcmp( argv[ i ], "-extrawide" ) ) + { + superSample = EXTRAWIDE_SCALE; /* ydnar */ + filter = qtrue; /* ydnar */ + Sys_Printf( "The -extrawide argument is deprecated, use \"-filter [-super 2]\" instead\n"); + } + else if( !strcmp( argv[ i ], "-samplesize" ) ) + { + sampleSize = atoi( argv[ i + 1 ] ); + if( sampleSize < 1 ) + sampleSize = 1; + i++; + Sys_Printf( "Default lightmap sample size set to %dx%d units\n", sampleSize, sampleSize ); + } + else if( !strcmp( argv[ i ], "-minsamplesize" ) ) + { + minSampleSize = atoi( argv[ i + 1 ] ); + if( minSampleSize < 1 ) + minSampleSize = 1; + i++; + Sys_Printf( "Minimum lightmap sample size set to %dx%d units\n", minSampleSize, minSampleSize ); + } + else if( !strcmp( argv[ i ], "-samplescale" ) ) + { + sampleScale = atoi( argv[ i + 1 ] ); + i++; + Sys_Printf( "Lightmaps sample scale set to %d\n", sampleScale); + } + else if( !strcmp( argv[ i ], "-novertex" ) ) + { + noVertexLighting = qtrue; + Sys_Printf( "Disabling vertex lighting\n" ); + } + else if( !strcmp( argv[ i ], "-nogrid" ) ) + { + noGridLighting = qtrue; + Sys_Printf( "Disabling grid lighting\n" ); + } + else if( !strcmp( argv[ i ], "-border" ) ) + { + lightmapBorder = qtrue; + Sys_Printf( "Adding debug border to lightmaps\n" ); + } + else if( !strcmp( argv[ i ], "-nosurf" ) ) + { + noSurfaces = qtrue; + Sys_Printf( "Not tracing against surfaces\n" ); + } + else if( !strcmp( argv[ i ], "-dump" ) ) + { + dump = qtrue; + Sys_Printf( "Dumping radiosity lights into numbered prefabs\n" ); + } + else if( !strcmp( argv[ i ], "-lomem" ) ) + { + loMem = qtrue; + Sys_Printf( "Enabling low-memory (potentially slower) lighting mode\n" ); + } + else if( !strcmp( argv[ i ], "-lightanglehl" ) ) + { + if( ( atoi( argv[ i + 1 ] ) != 0 ) != lightAngleHL ) + { + lightAngleHL = ( atoi( argv[ i + 1 ] ) != 0 ); + if( lightAngleHL ) + Sys_Printf( "Enabling half lambert light angle attenuation\n" ); + else + Sys_Printf( "Disabling half lambert light angle attenuation\n" ); + } + } + else if( !strcmp( argv[ i ], "-nostyle" ) || !strcmp( argv[ i ], "-nostyles" ) ) + { + noStyles = qtrue; + Sys_Printf( "Disabling lightstyles\n" ); + } + else if( !strcmp( argv[ i ], "-style" ) || !strcmp( argv[ i ], "-styles" ) ) + { + noStyles = qfalse; + Sys_Printf( "Enabling lightstyles\n" ); + } + else if( !strcmp( argv[ i ], "-keeplights" )) + { + keepLights = qtrue; + Sys_Printf( "Leaving light entities on map after compile\n" ); + } + else if( !strcmp( argv[ i ], "-cpma" ) ) + { + cpmaHack = qtrue; + Sys_Printf( "Enabling Challenge Pro Mode Asstacular Vertex Lighting Mode (tm)\n" ); + } + else if( !strcmp( argv[ i ], "-floodlight" ) ) + { + floodlighty = qtrue; + Sys_Printf( "FloodLighting enabled\n" ); + } + else if( !strcmp( argv[ i ], "-debugnormals" ) ) + { + debugnormals = qtrue; + Sys_Printf( "DebugNormals enabled\n" ); + } + else if( !strcmp( argv[ i ], "-lowquality" ) ) + { + floodlight_lowquality = qtrue; + Sys_Printf( "Low Quality FloodLighting enabled\n" ); + } + + /* r7: dirtmapping */ + else if( !strcmp( argv[ i ], "-dirty" ) ) + { + dirty = qtrue; + Sys_Printf( "Dirtmapping enabled\n" ); + } + else if( !strcmp( argv[ i ], "-dirtdebug" ) || !strcmp( argv[ i ], "-debugdirt" ) ) + { + dirtDebug = qtrue; + Sys_Printf( "Dirtmap debugging enabled\n" ); + } + else if( !strcmp( argv[ i ], "-dirtmode" ) ) + { + dirtMode = atoi( argv[ i + 1 ] ); + if( dirtMode != 0 && dirtMode != 1 ) + dirtMode = 0; + if( dirtMode == 1 ) + Sys_Printf( "Enabling randomized dirtmapping\n" ); + else + Sys_Printf( "Enabling ordered dir mapping\n" ); + i++; + } + else if( !strcmp( argv[ i ], "-dirtdepth" ) ) + { + dirtDepth = atof( argv[ i + 1 ] ); + if( dirtDepth <= 0.0f ) + dirtDepth = 128.0f; + Sys_Printf( "Dirtmapping depth set to %.1f\n", dirtDepth ); + i++; + } + else if( !strcmp( argv[ i ], "-dirtscale" ) ) + { + dirtScale = atof( argv[ i + 1 ] ); + if( dirtScale <= 0.0f ) + dirtScale = 1.0f; + Sys_Printf( "Dirtmapping scale set to %.1f\n", dirtScale ); + i++; + } + else if( !strcmp( argv[ i ], "-dirtgain" ) ) + { + dirtGain = atof( argv[ i + 1 ] ); + if( dirtGain <= 0.0f ) + dirtGain = 1.0f; + Sys_Printf( "Dirtmapping gain set to %.1f\n", dirtGain ); + i++; + } + else if( !strcmp( argv[ i ], "-trianglecheck" ) ) + { + lightmapTriangleCheck = qtrue; + } + else if( !strcmp( argv[ i ], "-extravisnudge" ) ) + { + lightmapExtraVisClusterNudge = qtrue; + } + else if( !strcmp( argv[ i ], "-fill" ) ) + { + lightmapFill = qtrue; + Sys_Printf( "Filling lightmap colors from surrounding pixels to improve JPEG compression\n" ); + } + /* unhandled args */ + else + { + Sys_Printf( "WARNING: Unknown argument \"%s\"\n", argv[ i ] ); + } + + } + + /* fix up samples count */ + if(lightRandomSamples) + { + if(!lightSamplesInsist) + { + /* approximately match -samples in quality */ + switch(lightSamples) + { + /* somewhat okay */ + case 1: + case 2: + lightSamples = 16; + Sys_Printf( "Adaptive supersampling preset enabled with %d random sample(s) per lightmap texel\n", lightSamples ); + break; + + /* good */ + case 3: + lightSamples = 64; + Sys_Printf( "Adaptive supersampling preset enabled with %d random sample(s) per lightmap texel\n", lightSamples ); + break; + + /* perfect */ + case 4: + lightSamples = 256; + Sys_Printf( "Adaptive supersampling preset enabled with %d random sample(s) per lightmap texel\n", lightSamples ); + break; + + default: break; + } + } + } + + /* fix up lightmap search power */ + if(lightmapMergeSize) + { + lightmapSearchBlockSize = (lightmapMergeSize / lmCustomSize) * (lightmapMergeSize / lmCustomSize); + if(lightmapSearchBlockSize < 1) + lightmapSearchBlockSize = 1; + + Sys_Printf( "Restricted lightmap searching enabled - block size adjusted to %d\n", lightmapSearchBlockSize ); + } + + /* clean up map name */ + strcpy( source, ExpandArg( argv[ i ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + strcpy( mapSource, ExpandArg( argv[ i ] ) ); + StripExtension( mapSource ); + DefaultExtension( mapSource, ".map" ); + + /* ydnar: set default sample size */ + SetDefaultSampleSize( sampleSize ); + + /* ydnar: handle shaders */ + BeginMapShaderFile( source ); + LoadShaderInfo(); + + /* note loading */ + Sys_Printf( "Loading %s\n", source ); + + /* ydnar: load surface file */ + LoadSurfaceExtraFile( source ); + + /* load bsp file */ + LoadBSPFile( source ); + + /* parse bsp entities */ + ParseEntities(); + + /* inject command line parameters */ + InjectCommandLine(argv, 0, argc - 1); + + /* load map file */ + value = ValueForKey( &entities[ 0 ], "_keepLights" ); + if( value[ 0 ] != '1' ) + LoadMapFile( mapSource, qtrue, qfalse ); + + /* set the entity/model origins and init yDrawVerts */ + SetEntityOrigins(); + + /* ydnar: set up optimization */ + SetupBrushes(); + SetupDirt(); + SetupFloodLight(); + SetupSurfaceLightmaps(); + + /* initialize the surface facet tracing */ + SetupTraceNodes(); + + /* light the world */ + LightWorld(); + + /* ydnar: store off lightmaps */ + StoreSurfaceLightmaps(); + + /* write out the bsp */ + UnparseEntities(); + Sys_Printf( "Writing %s\n", source ); + WriteBSPFile( source ); + + /* ydnar: export lightmaps */ + if( exportLightmaps && !externalLightmaps ) + ExportLightmaps(); + + /* return to sender */ + return 0; +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_bounce.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_bounce.c new file mode 100644 index 00000000..7db00613 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_bounce.c @@ -0,0 +1,959 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define LIGHT_BOUNCE_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* functions */ + +/* +RadFreeLights() +deletes any existing lights, freeing up memory for the next bounce +*/ + +void RadFreeLights( void ) +{ + light_t *light, *next; + + + /* delete lights */ + for( light = lights; light; light = next ) + { + next = light->next; + if( light->w != NULL ) + FreeWinding( light->w ); + free( light ); + } + numLights = 0; + lights = NULL; +} + + + +/* +RadClipWindingEpsilon() +clips a rad winding by a plane +based off the regular clip winding code +*/ + +static void RadClipWindingEpsilon( radWinding_t *in, vec3_t normal, vec_t dist, + vec_t epsilon, radWinding_t *front, radWinding_t *back, clipWork_t *cw ) +{ + vec_t *dists; + int *sides; + int counts[ 3 ]; + vec_t dot; /* ydnar: changed from static b/c of threading */ /* VC 4.2 optimizer bug if not static? */ + int i, j, k; + radVert_t *v1, *v2, mid; + int maxPoints; + + + /* crutch */ + dists = cw->dists; + sides = cw->sides; + + /* clear counts */ + counts[ 0 ] = counts[ 1 ] = counts[ 2 ] = 0; + + /* determine sides for each point */ + for( i = 0; i < in->numVerts; i++ ) + { + dot = DotProduct( in->verts[ i ].xyz, 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 ]; + + /* clear front and back */ + front->numVerts = back->numVerts = 0; + + /* handle all on one side cases */ + if( counts[ 0 ] == 0 ) + { + memcpy( back, in, sizeof( radWinding_t ) ); + return; + } + if( counts[ 1 ] == 0 ) + { + memcpy( front, in, sizeof( radWinding_t ) ); + return; + } + + /* setup windings */ + maxPoints = in->numVerts + 4; + + /* do individual verts */ + for( i = 0; i < in->numVerts; i++ ) + { + /* do simple vertex copies first */ + v1 = &in->verts[ i ]; + + if( sides[ i ] == SIDE_ON ) + { + memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) ); + memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) ); + continue; + } + + if( sides[ i ] == SIDE_FRONT ) + memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) ); + + if( sides[ i ] == SIDE_BACK ) + memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) ); + + if( sides[ i + 1 ] == SIDE_ON || sides[ i + 1 ] == sides[ i ] ) + continue; + + /* generate a split vertex */ + v2 = &in->verts[ (i + 1) % in->numVerts ]; + + dot = dists[ i ] / (dists[ i ] - dists[ i + 1 ]); + + /* average vertex values */ + for( j = 0; j < 4; j++ ) + { + /* color */ + if( j < 4 ) + { + for( k = 0; k < MAX_LIGHTMAPS; k++ ) + mid.color[ k ][ j ] = v1->color[ k ][ j ] + dot * (v2->color[ k ][ j ] - v1->color[ k ][ j ]); + } + + /* xyz, normal */ + if( j < 3 ) + { + mid.xyz[ j ] = v1->xyz[ j ] + dot * (v2->xyz[ j ] - v1->xyz[ j ]); + mid.normal[ j ] = v1->normal[ j ] + dot * (v2->normal[ j ] - v1->normal[ j ]); + } + + /* st, lightmap */ + if( j < 2 ) + { + mid.st[ j ] = v1->st[ j ] + dot * (v2->st[ j ] - v1->st[ j ]); + for( k = 0; k < MAX_LIGHTMAPS; k++ ) + mid.lightmap[ k ][ j ] = v1->lightmap[ k ][ j ] + dot * (v2->lightmap[ k ][ j ] - v1->lightmap[ k ][ j ]); + } + } + + /* normalize the averaged normal */ + VectorNormalize( mid.normal, mid.normal ); + + /* copy the midpoint to both windings */ + memcpy( &front->verts[ front->numVerts++ ], &mid, sizeof( radVert_t ) ); + memcpy( &back->verts[ back->numVerts++ ], &mid, sizeof( radVert_t ) ); + } + + /* error check */ + if( front->numVerts > maxPoints || front->numVerts > maxPoints ) + Error( "RadClipWindingEpsilon: points exceeded estimate" ); + if( front->numVerts > MAX_POINTS_ON_WINDING || front->numVerts > MAX_POINTS_ON_WINDING ) + Error( "RadClipWindingEpsilon: MAX_POINTS_ON_WINDING" ); +} + + + + + +/* +RadSampleImage() +samples a texture image for a given color +returns qfalse if pixels are bad +*/ + +qboolean RadSampleImage( byte *pixels, int width, int height, float st[ 2 ], float color[ 4 ] ) +{ + float sto[ 2 ]; + int x, y; + + + /* clear color first */ + color[ 0 ] = color[ 1 ] = color[ 2 ] = color[ 3 ] = 255; + + /* dummy check */ + if( pixels == NULL || width < 1 || height < 1 ) + return qfalse; + + /* bias st */ + sto[ 0 ] = st[ 0 ]; + while( sto[ 0 ] < 0.0f ) + sto[ 0 ] += 1.0f; + sto[ 1 ] = st[ 1 ]; + while( sto[ 1 ] < 0.0f ) + sto[ 1 ] += 1.0f; + + /* get offsets */ + x = ((float) width * sto[ 0 ]) + 0.5f; + x %= width; + y = ((float) height * sto[ 1 ]) + 0.5f; + y %= height; + + /* get pixel */ + pixels += (y * width * 4) + (x * 4); + VectorCopy( pixels, color ); + color[ 3 ] = pixels[ 3 ]; + return qtrue; +} + + + +/* +RadSample() +samples a fragment's lightmap or vertex color and returns an +average color and a color gradient for the sample +*/ + +#define MAX_SAMPLES 150 +#define SAMPLE_GRANULARITY 6 + +static void RadSample( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si, radWinding_t *rw, vec3_t average, vec3_t gradient, int *style ) +{ + int i, j, k, l, v, x, y, samples; + vec3_t color, mins, maxs; + vec4_t textureColor; + float alpha, alphaI, bf; + vec3_t blend; + float st[ 2 ], lightmap[ 2 ], *radLuxel; + radVert_t *rv[ 3 ]; + + + /* initial setup */ + ClearBounds( mins, maxs ); + VectorClear( average ); + VectorClear( gradient ); + alpha = 0; + + /* dummy check */ + if( rw == NULL || rw->numVerts < 3 ) + return; + + /* start sampling */ + samples = 0; + + /* sample vertex colors if no lightmap or this is the initial pass */ + if( lm == NULL || lm->radLuxels[ lightmapNum ] == NULL || bouncing == qfalse ) + { + for( samples = 0; samples < rw->numVerts; samples++ ) + { + /* multiply by texture color */ + if( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, rw->verts[ samples ].st, textureColor ) ) + { + VectorCopy( si->averageColor, textureColor ); + textureColor[ 4 ] = 255.0f; + } + for( i = 0; i < 3; i++ ) + color[ i ] = (textureColor[ i ] / 255) * (rw->verts[ samples ].color[ lightmapNum ][ i ] / 255.0f); + + AddPointToBounds( color, mins, maxs ); + VectorAdd( average, color, average ); + + /* get alpha */ + alpha += (textureColor[ 3 ] / 255.0f) * (rw->verts[ samples ].color[ lightmapNum ][ 3 ] / 255.0f); + } + + /* set style */ + *style = ds->vertexStyles[ lightmapNum ]; + } + + /* sample lightmap */ + else + { + /* fracture the winding into a fan (including degenerate tris) */ + for( v = 1; v < (rw->numVerts - 1) && samples < MAX_SAMPLES; v++ ) + { + /* get a triangle */ + rv[ 0 ] = &rw->verts[ 0 ]; + rv[ 1 ] = &rw->verts[ v ]; + rv[ 2 ] = &rw->verts[ v + 1 ]; + + /* this code is embarassing (really should just rasterize the triangle) */ + for( i = 1; i < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; i++ ) + { + for( j = 1; j < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; j++ ) + { + for( k = 1; k < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; k++ ) + { + /* create a blend vector (barycentric coordinates) */ + blend[ 0 ] = i; + blend[ 1 ] = j; + blend[ 2 ] = k; + bf = (1.0 / (blend[ 0 ] + blend[ 1 ] + blend[ 2 ])); + VectorScale( blend, bf, blend ); + + /* create a blended sample */ + st[ 0 ] = st[ 1 ] = 0.0f; + lightmap[ 0 ] = lightmap[ 1 ] = 0.0f; + alphaI = 0.0f; + for( l = 0; l < 3; l++ ) + { + st[ 0 ] += (rv[ l ]->st[ 0 ] * blend[ l ]); + st[ 1 ] += (rv[ l ]->st[ 1 ] * blend[ l ]); + lightmap[ 0 ] += (rv[ l ]->lightmap[ lightmapNum ][ 0 ] * blend[ l ]); + lightmap[ 1 ] += (rv[ l ]->lightmap[ lightmapNum ][ 1 ] * blend[ l ]); + alphaI += (rv[ l ]->color[ lightmapNum ][ 3 ] * blend[ l ]); + } + + /* get lightmap xy coords */ + x = lightmap[ 0 ] / (float) superSample; + y = lightmap[ 1 ] / (float) superSample; + if( x < 0 ) + x = 0; + else if ( x >= lm->w ) + x = lm->w - 1; + if( y < 0 ) + y = 0; + else if ( y >= lm->h ) + y = lm->h - 1; + + /* get radiosity luxel */ + radLuxel = RAD_LUXEL( lightmapNum, x, y ); + + /* ignore unlit/unused luxels */ + if( radLuxel[ 0 ] < 0.0f ) + continue; + + /* inc samples */ + samples++; + + /* multiply by texture color */ + if( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, st, textureColor ) ) + { + VectorCopy( si->averageColor, textureColor ); + textureColor[ 4 ] = 255; + } + for( i = 0; i < 3; i++ ) + color[ i ] = (textureColor[ i ] / 255) * (radLuxel[ i ] / 255); + + AddPointToBounds( color, mins, maxs ); + VectorAdd( average, color, average ); + + /* get alpha */ + alpha += (textureColor[ 3 ] / 255) * (alphaI / 255); + } + } + } + } + + /* set style */ + *style = ds->lightmapStyles[ lightmapNum ]; + } + + /* any samples? */ + if( samples <= 0 ) + return; + + /* average the color */ + VectorScale( average, (1.0 / samples), average ); + + /* create the color gradient */ + //% VectorSubtract( maxs, mins, delta ); + + /* new: color gradient will always be 0-1.0, expressed as the range of light relative to overall light */ + //% gradient[ 0 ] = maxs[ 0 ] > 0.0f ? (maxs[ 0 ] - mins[ 0 ]) / maxs[ 0 ] : 0.0f; + //% gradient[ 1 ] = maxs[ 1 ] > 0.0f ? (maxs[ 1 ] - mins[ 1 ]) / maxs[ 1 ] : 0.0f; + //% gradient[ 2 ] = maxs[ 2 ] > 0.0f ? (maxs[ 2 ] - mins[ 2 ]) / maxs[ 2 ] : 0.0f; + + /* newer: another contrast function */ + for( i = 0; i < 3; i++ ) + gradient[ i ] = (maxs[ i ] - mins[ i ]) * maxs[ i ]; +} + + + +/* +RadSubdivideDiffuseLight() +subdivides a radiosity winding until it is smaller than subdivide, then generates an area light +*/ + +#define RADIOSITY_MAX_GRADIENT 0.75f //% 0.25f +#define RADIOSITY_VALUE 500.0f +#define RADIOSITY_MIN 0.0001f +#define RADIOSITY_CLIP_EPSILON 0.125f + +static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si, + float scale, float subdivide, qboolean original, radWinding_t *rw, clipWork_t *cw ) +{ + int i, style = 0; + float dist, area, value; + vec3_t mins, maxs, normal, d1, d2, cross, color, gradient; + light_t *light, *splash; + winding_t *w; + + + /* dummy check */ + if( rw == NULL || rw->numVerts < 3 ) + return; + + /* get bounds for winding */ + ClearBounds( mins, maxs ); + for( i = 0; i < rw->numVerts; i++ ) + AddPointToBounds( rw->verts[ i ].xyz, mins, maxs ); + + /* subdivide if necessary */ + for( i = 0; i < 3; i++ ) + { + if( maxs[ i ] - mins[ i ] > subdivide ) + { + radWinding_t front, back; + + + /* make axial plane */ + VectorClear( normal ); + normal[ i ] = 1; + dist = (maxs[ i ] + mins[ i ]) * 0.5f; + + /* clip the winding */ + RadClipWindingEpsilon( rw, normal, dist, RADIOSITY_CLIP_EPSILON, &front, &back, cw ); + + /* recurse */ + RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qfalse, &front, cw ); + RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qfalse, &back, cw ); + return; + } + } + + /* check area */ + area = 0.0f; + for( i = 2; i < rw->numVerts; i++ ) + { + VectorSubtract( rw->verts[ i - 1 ].xyz, rw->verts[ 0 ].xyz, d1 ); + VectorSubtract( rw->verts[ i ].xyz, rw->verts[ 0 ].xyz, d2 ); + CrossProduct( d1, d2, cross ); + area += 0.5f * VectorLength( cross ); + } + if( area < 1.0f || area > 20000000.0f ) + return; + + /* more subdivision may be necessary */ + if( bouncing ) + { + /* get color sample for the surface fragment */ + RadSample( lightmapNum, ds, lm, si, rw, color, gradient, &style ); + + /* if color gradient is too high, subdivide again */ + if( subdivide > minDiffuseSubdivide && + (gradient[ 0 ] > RADIOSITY_MAX_GRADIENT || gradient[ 1 ] > RADIOSITY_MAX_GRADIENT || gradient[ 2 ] > RADIOSITY_MAX_GRADIENT) ) + { + RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, (subdivide / 2.0f), qfalse, rw, cw ); + return; + } + } + + /* create a regular winding and an average normal */ + w = AllocWinding( rw->numVerts ); + w->numpoints = rw->numVerts; + VectorClear( normal ); + for( i = 0; i < rw->numVerts; i++ ) + { + VectorCopy( rw->verts[ i ].xyz, w->p[ i ] ); + VectorAdd( normal, rw->verts[ i ].normal, normal ); + } + VectorScale( normal, (1.0f / rw->numVerts), normal ); + if( VectorNormalize( normal, normal ) == 0.0f ) + return; + + /* early out? */ + if( bouncing && VectorLength( color ) < RADIOSITY_MIN ) + return; + + /* debug code */ + //% Sys_Printf( "Size: %d %d %d\n", (int) (maxs[ 0 ] - mins[ 0 ]), (int) (maxs[ 1 ] - mins[ 1 ]), (int) (maxs[ 2 ] - mins[ 2 ]) ); + //% Sys_Printf( "Grad: %f %f %f\n", gradient[ 0 ], gradient[ 1 ], gradient[ 2 ] ); + + /* increment counts */ + numDiffuseLights++; + switch( ds->surfaceType ) + { + case MST_PLANAR: + numBrushDiffuseLights++; + break; + + case MST_TRIANGLE_SOUP: + numTriangleDiffuseLights++; + break; + + case MST_PATCH: + numPatchDiffuseLights++; + break; + } + + /* create a light */ + light = safe_malloc( sizeof( *light ) ); + memset( light, 0, sizeof( *light ) ); + + /* attach it */ + ThreadLock(); + light->next = lights; + lights = light; + ThreadUnlock(); + + /* initialize the light */ + light->flags = LIGHT_AREA_DEFAULT; + light->type = EMIT_AREA; + light->si = si; + light->fade = 1.0f; + light->w = w; + + /* set falloff threshold */ + light->falloffTolerance = falloffTolerance; + + /* bouncing light? */ + if( !bouncing ) + { + /* handle first-pass lights in normal q3a style */ + value = si->value; + light->photons = value * area * areaScale; + light->add = value * formFactorValueScale * areaScale; + VectorCopy( si->color, light->color ); + VectorScale( light->color, light->add, light->emitColor ); + light->style = noStyles ? LS_NORMAL : si->lightStyle; + if( light->style < LS_NORMAL || light->style >= LS_NONE ) + light->style = LS_NORMAL; + + /* set origin */ + VectorAdd( mins, maxs, light->origin ); + VectorScale( light->origin, 0.5f, light->origin ); + + /* nudge it off the plane a bit */ + VectorCopy( normal, light->normal ); + VectorMA( light->origin, 1.0f, light->normal, light->origin ); + light->dist = DotProduct( light->origin, normal ); + + /* optionally create a point splashsplash light for first pass */ + if( original && si->backsplashFraction > 0 ) + { + /* allocate a new point light */ + splash = safe_malloc( sizeof( *splash ) ); + memset( splash, 0, sizeof( *splash ) ); + splash->next = lights; + lights = splash; + + /* set it up */ + splash->flags = LIGHT_Q3A_DEFAULT; + splash->type = EMIT_POINT; + splash->photons = light->photons * si->backsplashFraction; + splash->fade = 1.0f; + splash->si = si; + VectorMA( light->origin, si->backsplashDistance, normal, splash->origin ); + VectorCopy( si->color, splash->color ); + splash->falloffTolerance = falloffTolerance; + splash->style = noStyles ? LS_NORMAL : light->style; + + /* add to counts */ + numPointLights++; + } + } + else + { + /* handle bounced light (radiosity) a little differently */ + value = RADIOSITY_VALUE * si->bounceScale * 0.375f; + light->photons = value * area * bounceScale; + light->add = value * formFactorValueScale * bounceScale; + VectorCopy( color, light->color ); + VectorScale( light->color, light->add, light->emitColor ); + light->style = noStyles ? LS_NORMAL : style; + if( light->style < LS_NORMAL || light->style >= LS_NONE ) + light->style = LS_NORMAL; + + /* set origin */ + WindingCenter( w, light->origin ); + + /* nudge it off the plane a bit */ + VectorCopy( normal, light->normal ); + VectorMA( light->origin, 1.0f, light->normal, light->origin ); + light->dist = DotProduct( light->origin, normal ); + } + + /* emit light from both sides? */ + if( si->compileFlags & C_FOG || si->twoSided ) + light->flags |= LIGHT_TWOSIDED; + + //% Sys_Printf( "\nAL: C: (%6f, %6f, %6f) [%6f] N: (%6f, %6f, %6f) %s\n", + //% light->color[ 0 ], light->color[ 1 ], light->color[ 2 ], light->add, + //% light->normal[ 0 ], light->normal[ 1 ], light->normal[ 2 ], + //% light->si->shader ); +} + + + +/* +RadLightForTriangles() +creates unbounced diffuse lights for triangle soup (misc_models, etc) +*/ + +void RadLightForTriangles( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ) +{ + int i, j, k, v; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + float *radVertexLuxel; + radWinding_t rw; + + + /* get surface */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* each triangle is a potential emitter */ + rw.numVerts = 3; + for( i = 0; i < ds->numIndexes; i += 3 ) + { + /* copy each vert */ + for( j = 0; j < 3; j++ ) + { + /* get vertex index and rad vertex luxel */ + v = ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ]; + + /* get most everything */ + memcpy( &rw.verts[ j ], &yDrawVerts[ v ], sizeof( bspDrawVert_t ) ); + + /* fix colors */ + for( k = 0; k < MAX_LIGHTMAPS; k++ ) + { + radVertexLuxel = RAD_VERTEX_LUXEL( k, ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ] ); + VectorCopy( radVertexLuxel, rw.verts[ j ].color[ k ] ); + rw.verts[ j ].color[ k ][ 3 ] = yDrawVerts[ v ].color[ k ][ 3 ]; + } + } + + /* subdivide into area lights */ + RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw ); + } +} + + + +/* +RadLightForPatch() +creates unbounced diffuse lights for patches +*/ + +#define PLANAR_EPSILON 0.1f + +void RadLightForPatch( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ) +{ + int i, x, y, v, t, pw[ 5 ], r; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + bspDrawVert_t *bogus; + bspDrawVert_t *dv[ 4 ]; + mesh_t src, *subdivided, *mesh; + float *radVertexLuxel; + float dist; + vec4_t plane; + qboolean planar; + radWinding_t rw; + + + /* get surface */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* construct a bogus vert list with color index stuffed into color[ 0 ] */ + bogus = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) ); + memcpy( bogus, &yDrawVerts[ ds->firstVert ], ds->numVerts * sizeof( bspDrawVert_t ) ); + for( i = 0; i < ds->numVerts; i++ ) + bogus[ i ].color[ 0 ][ 0 ] = i; + + /* build a subdivided mesh identical to shadow facets for this patch */ + /* this MUST MATCH FacetsForPatch() identically! */ + src.width = ds->patchWidth; + src.height = ds->patchHeight; + src.verts = bogus; + //% subdivided = SubdivideMesh( src, 8, 512 ); + subdivided = SubdivideMesh2( src, info->patchIterations ); + PutMeshOnCurve( *subdivided ); + //% MakeMeshNormals( *subdivided ); + mesh = RemoveLinearMeshColumnsRows( subdivided ); + FreeMesh( subdivided ); + free( bogus ); + + /* FIXME: build interpolation table into color[ 1 ] */ + + /* fix up color indexes */ + for( i = 0; i < (mesh->width * mesh->height); i++ ) + { + dv[ 0 ] = &mesh->verts[ i ]; + if( dv[ 0 ]->color[ 0 ][ 0 ] >= ds->numVerts ) + dv[ 0 ]->color[ 0 ][ 0 ] = ds->numVerts - 1; + } + + /* iterate through the mesh quads */ + for( y = 0; y < (mesh->height - 1); y++ ) + { + for( x = 0; x < (mesh->width - 1); x++ ) + { + /* set indexes */ + pw[ 0 ] = x + (y * mesh->width); + pw[ 1 ] = x + ((y + 1) * mesh->width); + pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); + pw[ 3 ] = x + 1 + (y * mesh->width); + pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ + + /* set radix */ + r = (x + y) & 1; + + /* get drawverts */ + dv[ 0 ] = &mesh->verts[ pw[ r + 0 ] ]; + dv[ 1 ] = &mesh->verts[ pw[ r + 1 ] ]; + dv[ 2 ] = &mesh->verts[ pw[ r + 2 ] ]; + dv[ 3 ] = &mesh->verts[ pw[ r + 3 ] ]; + + /* planar? */ + planar = PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ); + if( planar ) + { + dist = DotProduct( dv[ 1 ]->xyz, plane ) - plane[ 3 ]; + if( fabs( dist ) > PLANAR_EPSILON ) + planar = qfalse; + } + + /* generate a quad */ + if( planar ) + { + rw.numVerts = 4; + for( v = 0; v < 4; v++ ) + { + /* get most everything */ + memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) ); + + /* fix colors */ + for( i = 0; i < MAX_LIGHTMAPS; i++ ) + { + radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] ); + VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] ); + rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ]; + } + } + + /* subdivide into area lights */ + RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw ); + } + + /* generate 2 tris */ + else + { + rw.numVerts = 3; + for( t = 0; t < 2; t++ ) + { + for( v = 0; v < 3 + t; v++ ) + { + /* get "other" triangle (stupid hacky logic, but whatevah) */ + if( v == 1 && t == 1 ) + v++; + + /* get most everything */ + memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) ); + + /* fix colors */ + for( i = 0; i < MAX_LIGHTMAPS; i++ ) + { + radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] ); + VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] ); + rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ]; + } + } + + /* subdivide into area lights */ + RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw ); + } + } + } + } + + /* free the mesh */ + FreeMesh( mesh ); +} + + + + +/* +RadLight() +creates unbounced diffuse lights for a given surface +*/ + +void RadLight( int num ) +{ + int lightmapNum; + float scale, subdivide; + int contentFlags, surfaceFlags, compileFlags; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + rawLightmap_t *lm; + shaderInfo_t *si; + clipWork_t cw; + + + /* get drawsurface, lightmap, and shader info */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + lm = info->lm; + si = info->si; + scale = si->bounceScale; + + /* find nodraw bit */ + contentFlags = surfaceFlags = compileFlags = 0; + ApplySurfaceParm( "nodraw", &contentFlags, &surfaceFlags, &compileFlags ); + + // jal : avoid bouncing on trans surfaces + ApplySurfaceParm( "trans", &contentFlags, &surfaceFlags, &compileFlags ); + + /* early outs? */ + if( scale <= 0.0f || (si->compileFlags & C_SKY) || si->autosprite || + (bspShaders[ ds->shaderNum ].contentFlags & contentFlags) || (bspShaders[ ds->shaderNum ].surfaceFlags & surfaceFlags) || + (si->compileFlags & compileFlags) ) + return; + + /* determine how much we need to chop up the surface */ + if( si->lightSubdivide ) + subdivide = si->lightSubdivide; + else + subdivide = diffuseSubdivide; + + /* inc counts */ + numDiffuseSurfaces++; + + /* iterate through styles (this could be more efficient, yes) */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* switch on type */ + if( ds->lightmapStyles[ lightmapNum ] != LS_NONE && ds->lightmapStyles[ lightmapNum ] != LS_UNUSED ) + { + switch( ds->surfaceType ) + { + case MST_PLANAR: + case MST_TRIANGLE_SOUP: + RadLightForTriangles( num, lightmapNum, lm, si, scale, subdivide, &cw ); + break; + + case MST_PATCH: + RadLightForPatch( num, lightmapNum, lm, si, scale, subdivide, &cw ); + break; + + default: + break; + } + } + } +} + + + +/* +RadCreateDiffuseLights() +creates lights for unbounced light on surfaces in the bsp +*/ + +int iterations = 0; + +void RadCreateDiffuseLights( void ) +{ + /* startup */ + Sys_FPrintf( SYS_VRB, "--- RadCreateDiffuseLights ---\n" ); + numDiffuseSurfaces = 0; + numDiffuseLights = 0; + numBrushDiffuseLights = 0; + numTriangleDiffuseLights = 0; + numPatchDiffuseLights = 0; + numAreaLights = 0; + + /* hit every surface (threaded) */ + RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, RadLight ); + + /* dump the lights generated to a file */ + if( dump ) + { + char dumpName[ 1024 ], ext[ 64 ]; + FILE *file; + light_t *light; + + strcpy( dumpName, source ); + StripExtension( dumpName ); + sprintf( ext, "_bounce_%03d.map", iterations ); + strcat( dumpName, ext ); + file = fopen( dumpName, "wb" ); + Sys_Printf( "Writing %s...\n", dumpName ); + if( file ) + { + for( light = lights; light; light = light->next ) + { + fprintf( file, + "{\n" + "\"classname\" \"light\"\n" + "\"light\" \"%d\"\n" + "\"origin\" \"%.0f %.0f %.0f\"\n" + "\"_color\" \"%.3f %.3f %.3f\"\n" + "}\n", + + (int) light->add, + + light->origin[ 0 ], + light->origin[ 1 ], + light->origin[ 2 ], + + light->color[ 0 ], + light->color[ 1 ], + light->color[ 2 ] ); + } + fclose( file ); + } + } + + /* increment */ + iterations++; + + /* print counts */ + Sys_Printf( "%8d diffuse surfaces\n", numDiffuseSurfaces ); + Sys_FPrintf( SYS_VRB, "%8d total diffuse lights\n", numDiffuseLights ); + Sys_FPrintf( SYS_VRB, "%8d brush diffuse lights\n", numBrushDiffuseLights ); + Sys_FPrintf( SYS_VRB, "%8d patch diffuse lights\n", numPatchDiffuseLights ); + Sys_FPrintf( SYS_VRB, "%8d triangle diffuse lights\n", numTriangleDiffuseLights ); +} + + + + + + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_shadows.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_shadows.c new file mode 100644 index 00000000..d482bbca --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_shadows.c @@ -0,0 +1,124 @@ +/* +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 +*/ + +#define LIGHT_SHADOWS_C + +#include "light.h" +#include "inout.h" + + + +/* ------------------------------------------------------------------------------- + +ydnar: this code deals with shadow volume bsps + +------------------------------------------------------------------------------- */ + +typedef struct shadowNode_s +{ + vec4_t plane; + int children[ 2 ]; +} +shadowNode_t; + +int numShadowNodes; +shadowNode_t *shadowNodes; + + + +/* +AddShadow() +adds a shadow, returning the index into the shadow list +*/ + + + +/* +MakeShadowFromPoints() +creates a shadow volume from 4 points (the first being the light origin) +*/ + + + +/* +SetupShadows() +sets up the shadow volumes for all lights in the world +*/ + +void SetupShadows( void ) +{ + int i, j, s; + light_t *light; + dleaf_t *leaf; + dsurface_t *ds; + surfaceInfo_t *info; + shaderInfo_t *si; + byte *tested; + + + /* early out for weird cases where there are no lights */ + if( lights == NULL ) + return; + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- SetupShadows ---\n" ); + + /* allocate a surface test list */ + tested = safe_malloc( numDrawSurfaces / 8 + 1 ); + + /* walk the list of lights */ + for( light = lights; light != NULL; light = light->next ) + { + /* do some early out testing */ + if( light->cluster < 0 ) + continue; + + /* clear surfacetest list */ + memset( tested, 0, numDrawSurfaces / 8 + 1 ); + + /* walk the bsp leaves */ + for( i = 0, leaf = dleafs; i < numleafs; i++, leaf++ ) + { + /* in pvs? */ + if( ClusterVisible( light->cluster, leaf->cluster ) == qfalse ) + continue; + + /* walk the surface list for this leaf */ + for( j = 0; j < leaf->numLeafSurfaces; j++ ) + { + /* don't filter a surface more than once */ + s = dleafsurfaces[ leaf->firstLeafSurface + j ]; + if( tested[ s >> 3 ] & (1 << (s & 7)) ) + continue; + tested[ s >> 3 ] |= (1 << (s & 7)); + + /* get surface and info */ + ds = &drawSurfaces[ s ]; + info = &surfaceInfos[ s ]; + si = info->si; + + /* don't create shadow volumes from translucent surfaces */ + if( si->contents & CONTENTS_TRANSLUCENT ) + continue; + } + } + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_trace.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_trace.c new file mode 100644 index 00000000..8e79244e --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_trace.c @@ -0,0 +1,1752 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define LIGHT_TRACE_C + + + +/* dependencies */ +#include "q3map2.h" + + +/* dependencies */ +#include "q3map2.h" + + + +#define Vector2Copy( a, b ) ((b)[ 0 ] = (a)[ 0 ], (b)[ 1 ] = (a)[ 1 ]) +#define Vector4Copy( a, b ) ((b)[ 0 ] = (a)[ 0 ], (b)[ 1 ] = (a)[ 1 ], (b)[ 2 ] = (a)[ 2 ], (b)[ 3 ] = (a)[ 3 ]) + +#define MAX_NODE_ITEMS 5 +#define MAX_NODE_TRIANGLES 5 +#define MAX_TRACE_DEPTH 32 +#define MIN_NODE_SIZE 32.0f + +#define GROW_TRACE_INFOS 32768 //% 4096 +#define GROW_TRACE_WINDINGS 65536 //% 32768 +#define GROW_TRACE_TRIANGLES 131072 //% 32768 +#define GROW_TRACE_NODES 16384 //% 16384 +#define GROW_NODE_ITEMS 16 //% 256 + +#define MAX_TW_VERTS 24 // vortex: increased from 12 to 24 for ability co compile some insane maps with large curve count + +#define TRACE_ON_EPSILON 0.1f + +#define TRACE_LEAF -1 +#define TRACE_LEAF_SOLID -2 + +typedef struct traceVert_s +{ + vec3_t xyz; + float st[ 2 ]; +} +traceVert_t; + +typedef struct traceInfo_s +{ + shaderInfo_t *si; + int surfaceNum, castShadows, skipGrid; +} +traceInfo_t; + +typedef struct traceWinding_s +{ + vec4_t plane; + int infoNum, numVerts; + traceVert_t v[ MAX_TW_VERTS ]; +} +traceWinding_t; + +typedef struct traceTriangle_s +{ + vec3_t edge1, edge2; + int infoNum; + traceVert_t v[ 3 ]; +} +traceTriangle_t; + +typedef struct traceNode_s +{ + int type; + vec4_t plane; + vec3_t mins, maxs; + int children[ 2 ]; + int numItems, maxItems; + int *items; +} +traceNode_t; + + +int noDrawContentFlags, noDrawSurfaceFlags, noDrawCompileFlags; + +int numTraceInfos = 0, maxTraceInfos = 0, firstTraceInfo = 0; +traceInfo_t *traceInfos = NULL; + +int numTraceWindings = 0, maxTraceWindings = 0, deadWinding = -1; +traceWinding_t *traceWindings = NULL; + +int numTraceTriangles = 0, maxTraceTriangles = 0, deadTriangle = -1; +traceTriangle_t *traceTriangles = NULL; + +int headNodeNum = 0, skyboxNodeNum = 0, maxTraceDepth = 0, numTraceLeafNodes = 0; +int numTraceNodes = 0, maxTraceNodes = 0; +traceNode_t *traceNodes = NULL; + + + +/* ------------------------------------------------------------------------------- + +allocation and list management + +------------------------------------------------------------------------------- */ + +/* +AddTraceInfo() - ydnar +adds a trace info structure to the pool +*/ + +static int AddTraceInfo( traceInfo_t *ti ) +{ + int num; + void *temp; + + + /* find an existing info */ + for( num = firstTraceInfo; num < numTraceInfos; num++ ) + { + if( traceInfos[ num ].si == ti->si && + traceInfos[ num ].surfaceNum == ti->surfaceNum && + traceInfos[ num ].castShadows == ti->castShadows && + traceInfos[ num ].skipGrid == ti->skipGrid ) + return num; + } + + /* enough space? */ + if( numTraceInfos >= maxTraceInfos ) + { + /* allocate more room */ + maxTraceInfos += GROW_TRACE_INFOS; + temp = safe_malloc( maxTraceInfos * sizeof( *traceInfos ) ); + if( traceInfos != NULL ) + { + memcpy( temp, traceInfos, numTraceInfos * sizeof( *traceInfos ) ); + free( traceInfos ); + } + traceInfos = (traceInfo_t*) temp; + } + + /* add the info */ + memcpy( &traceInfos[ num ], ti, sizeof( *traceInfos ) ); + if( num == numTraceInfos ) + numTraceInfos++; + + /* return the ti number */ + return num; +} + + + +/* +AllocTraceNode() - ydnar +allocates a new trace node +*/ + +static int AllocTraceNode( void ) +{ + traceNode_t *temp; + + + /* enough space? */ + if( numTraceNodes >= maxTraceNodes ) + { + /* reallocate more room */ + maxTraceNodes += GROW_TRACE_NODES; + temp = safe_malloc( maxTraceNodes * sizeof( traceNode_t ) ); + if( traceNodes != NULL ) + { + memcpy( temp, traceNodes, numTraceNodes * sizeof( traceNode_t ) ); + free( traceNodes ); + } + traceNodes = temp; + } + + /* add the node */ + memset( &traceNodes[ numTraceNodes ], 0, sizeof( traceNode_t ) ); + traceNodes[ numTraceNodes ].type = TRACE_LEAF; + ClearBounds( traceNodes[ numTraceNodes ].mins, traceNodes[ numTraceNodes ].maxs ); + + /* Sys_Printf("alloc node %d\n", numTraceNodes); */ + + numTraceNodes++; + + /* return the count */ + return (numTraceNodes - 1); +} + + + +/* +AddTraceWinding() - ydnar +adds a winding to the raytracing pool +*/ + +static int AddTraceWinding( traceWinding_t *tw ) +{ + int num; + void *temp; + + + /* check for a dead winding */ + if( deadWinding >= 0 && deadWinding < numTraceWindings ) + num = deadWinding; + else + { + /* put winding at the end of the list */ + num = numTraceWindings; + + /* enough space? */ + if( numTraceWindings >= maxTraceWindings ) + { + /* allocate more room */ + maxTraceWindings += GROW_TRACE_WINDINGS; + temp = safe_malloc( maxTraceWindings * sizeof( *traceWindings ) ); + if( traceWindings != NULL ) + { + memcpy( temp, traceWindings, numTraceWindings * sizeof( *traceWindings ) ); + free( traceWindings ); + } + traceWindings = (traceWinding_t*) temp; + } + } + + /* add the winding */ + memcpy( &traceWindings[ num ], tw, sizeof( *traceWindings ) ); + if( num == numTraceWindings ) + numTraceWindings++; + deadWinding = -1; + + /* return the winding number */ + return num; +} + + + +/* +AddTraceTriangle() - ydnar +adds a triangle to the raytracing pool +*/ + +static int AddTraceTriangle( traceTriangle_t *tt ) +{ + int num; + void *temp; + + + /* check for a dead triangle */ + if( deadTriangle >= 0 && deadTriangle < numTraceTriangles ) + num = deadTriangle; + else + { + /* put triangle at the end of the list */ + num = numTraceTriangles; + + /* enough space? */ + if( numTraceTriangles >= maxTraceTriangles ) + { + /* allocate more room */ + maxTraceTriangles += GROW_TRACE_TRIANGLES; + temp = safe_malloc( maxTraceTriangles * sizeof( *traceTriangles ) ); + if( traceTriangles != NULL ) + { + memcpy( temp, traceTriangles, numTraceTriangles * sizeof( *traceTriangles ) ); + free( traceTriangles ); + } + traceTriangles = (traceTriangle_t*) temp; + } + } + + /* find vectors for two edges sharing the first vert */ + VectorSubtract( tt->v[ 1 ].xyz, tt->v[ 0 ].xyz, tt->edge1 ); + VectorSubtract( tt->v[ 2 ].xyz, tt->v[ 0 ].xyz, tt->edge2 ); + + /* add the triangle */ + memcpy( &traceTriangles[ num ], tt, sizeof( *traceTriangles ) ); + if( num == numTraceTriangles ) + numTraceTriangles++; + deadTriangle = -1; + + /* return the triangle number */ + return num; +} + + + +/* +AddItemToTraceNode() - ydnar +adds an item reference (winding or triangle) to a trace node +*/ + +static int AddItemToTraceNode( traceNode_t *node, int num ) +{ + void *temp; + + + /* dummy check */ + if( num < 0 ) + return -1; + + /* enough space? */ + if( node->numItems >= node->maxItems ) + { + /* allocate more room */ + if( node == traceNodes ) + node->maxItems *= 2; + else + node->maxItems += GROW_NODE_ITEMS; + if( node->maxItems <= 0 ) + node->maxItems = GROW_NODE_ITEMS; + temp = safe_malloc( node->maxItems * sizeof( *node->items ) ); + if( node->items != NULL ) + { + memcpy( temp, node->items, node->numItems * sizeof( *node->items ) ); + free( node->items ); + } + node->items = (int*) temp; + } + + /* add the poly */ + node->items[ node->numItems ] = num; + node->numItems++; + + /* return the count */ + return (node->numItems - 1); +} + + + + +/* ------------------------------------------------------------------------------- + +trace node setup + +------------------------------------------------------------------------------- */ + +/* +SetupTraceNodes_r() - ydnar +recursively create the initial trace node structure from the bsp tree +*/ + +static int SetupTraceNodes_r( int bspNodeNum ) +{ + int i, nodeNum, bspLeafNum, newNode; + bspPlane_t *plane; + bspNode_t *bspNode; + + + /* get bsp node and plane */ + bspNode = &bspNodes[ bspNodeNum ]; + plane = &bspPlanes[ bspNode->planeNum ]; + + /* allocate a new trace node */ + nodeNum = AllocTraceNode(); + + /* setup trace node */ + traceNodes[ nodeNum ].type = PlaneTypeForNormal( plane->normal ); + VectorCopy( plane->normal, traceNodes[ nodeNum ].plane ); + traceNodes[ nodeNum ].plane[ 3 ] = plane->dist; + + /* setup children */ + for( i = 0; i < 2; i++ ) + { + /* leafnode */ + if( bspNode->children[ i ] < 0 ) + { + bspLeafNum = -bspNode->children[ i ] - 1; + + /* new code */ + newNode = AllocTraceNode(); + traceNodes[ nodeNum ].children[ i ] = newNode; + /* have to do this separately, as gcc first executes LHS, then RHS, and if a realloc took place, this fails */ + + if( bspLeafs[ bspLeafNum ].cluster == -1 ) + traceNodes[ traceNodes[ nodeNum ].children[ i ] ].type = TRACE_LEAF_SOLID; + } + + /* normal node */ + else + { + newNode = SetupTraceNodes_r( bspNode->children[ i ] ); + traceNodes[ nodeNum ].children[ i ] = newNode; + } + + if(traceNodes[ nodeNum ].children[ i ] == 0) + Error( "Invalid tracenode allocated" ); + } + + /* Sys_Printf("node %d children: %d %d\n", nodeNum, traceNodes[ nodeNum ].children[0], traceNodes[ nodeNum ].children[1]); */ + + /* return node number */ + return nodeNum; +} + + + +/* +ClipTraceWinding() - ydnar +clips a trace winding against a plane into one or two parts +*/ + +#define TW_ON_EPSILON 0.25f + +void ClipTraceWinding( traceWinding_t *tw, vec4_t plane, traceWinding_t *front, traceWinding_t *back ) +{ + int i, j, k; + int sides[ MAX_TW_VERTS ], counts[ 3 ] = { 0, 0, 0 }; + float dists[ MAX_TW_VERTS ]; + float frac; + traceVert_t *a, *b, mid; + + + /* clear front and back */ + front->numVerts = 0; + back->numVerts = 0; + + /* classify points */ + for( i = 0; i < tw->numVerts; i++ ) + { + dists[ i ] = DotProduct( tw->v[ i ].xyz, plane ) - plane[ 3 ]; + if( dists[ i ] < -TW_ON_EPSILON ) + sides[ i ] = SIDE_BACK; + else if( dists[ i ] > TW_ON_EPSILON ) + sides[ i ] = SIDE_FRONT; + else + sides[ i ] = SIDE_ON; + counts[ sides[ i ] ]++; + } + + /* entirely on front? */ + if( counts[ SIDE_BACK ] == 0 ) + memcpy( front, tw, sizeof( *front ) ); + + /* entirely on back? */ + else if( counts[ SIDE_FRONT ] == 0 ) + memcpy( back, tw, sizeof( *back ) ); + + /* straddles the plane */ + else + { + /* setup front and back */ + memcpy( front, tw, sizeof( *front ) ); + front->numVerts = 0; + memcpy( back, tw, sizeof( *back ) ); + back->numVerts = 0; + + /* split the winding */ + for( i = 0; i < tw->numVerts; i++ ) + { + /* radix */ + j = (i + 1) % tw->numVerts; + + /* get verts */ + a = &tw->v[ i ]; + b = &tw->v[ j ]; + + /* handle points on the splitting plane */ + switch( sides[ i ] ) + { + case SIDE_FRONT: + if( front->numVerts >= MAX_TW_VERTS ) + Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); + front->v[ front->numVerts++ ] = *a; + break; + + case SIDE_BACK: + if( back->numVerts >= MAX_TW_VERTS ) + Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); + back->v[ back->numVerts++ ] = *a; + break; + + case SIDE_ON: + if( front->numVerts >= MAX_TW_VERTS || back->numVerts >= MAX_TW_VERTS ) + Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); + front->v[ front->numVerts++ ] = *a; + back->v[ back->numVerts++ ] = *a; + continue; + } + + /* check next point to see if we need to split the edge */ + if( sides[ j ] == SIDE_ON || sides[ j ] == sides[ i ] ) + continue; + + /* check limit */ + if( front->numVerts >= MAX_TW_VERTS || back->numVerts >= MAX_TW_VERTS ) + Error( "MAX_TW_VERTS (%d) exceeded", MAX_TW_VERTS ); + + /* generate a split point */ + frac = dists[ i ] / (dists[ i ] - dists[ j ]); + for( k = 0; k < 3; k++ ) + { + /* minimize fp precision errors */ + if( plane[ k ] == 1.0f ) + mid.xyz[ k ] = plane[ 3 ]; + else if( plane[ k ] == -1.0f ) + mid.xyz[ k ] = -plane[ 3 ]; + else + mid.xyz[ k ] = a->xyz[ k ] + frac * (b->xyz[ k ] - a->xyz[ k ]); + } + /* set texture coordinates */ + mid.st[ 0 ] = a->st[ 0 ] + frac * (b->st[ 0 ] - a->st[ 0 ]); + mid.st[ 1 ] = a->st[ 1 ] + frac * (b->st[ 1 ] - a->st[ 1 ]); + + /* copy midpoint to front and back polygons */ + front->v[ front->numVerts++ ] = mid; + back->v[ back->numVerts++ ] = mid; + } + } +} + + + +/* +FilterTraceWindingIntoNodes_r() - ydnar +filters a trace winding into the raytracing tree +*/ + +static void FilterTraceWindingIntoNodes_r( traceWinding_t *tw, int nodeNum ) +{ + int num; + vec4_t plane1, plane2, reverse; + traceNode_t *node; + traceWinding_t front, back; + + + /* don't filter if passed a bogus node (solid, etc) */ + if( nodeNum < 0 || nodeNum >= numTraceNodes ) + return; + + /* get node */ + node = &traceNodes[ nodeNum ]; + + /* is this a decision node? */ + if( node->type >= 0 ) + { + /* create winding plane if necessary, filtering out bogus windings as well */ + if( nodeNum == headNodeNum ) + { + if( !PlaneFromPoints( tw->plane, tw->v[ 0 ].xyz, tw->v[ 1 ].xyz, tw->v[ 2 ].xyz ) ) + return; + } + + /* validate the node */ + if( node->children[ 0 ] == 0 || node->children[ 1 ] == 0 ) + Error( "Invalid tracenode: %d", nodeNum ); + + /* get node plane */ + Vector4Copy( node->plane, plane1 ); + + /* get winding plane */ + Vector4Copy( tw->plane, plane2 ); + + /* invert surface plane */ + VectorSubtract( vec3_origin, plane2, reverse ); + reverse[ 3 ] = -plane2[ 3 ]; + + /* front only */ + if( DotProduct( plane1, plane2 ) > 0.999f && fabs( plane1[ 3 ] - plane2[ 3 ] ) < 0.001f ) + { + FilterTraceWindingIntoNodes_r( tw, node->children[ 0 ] ); + return; + } + + /* back only */ + if( DotProduct( plane1, reverse ) > 0.999f && fabs( plane1[ 3 ] - reverse[ 3 ] ) < 0.001f ) + { + FilterTraceWindingIntoNodes_r( tw, node->children[ 1 ] ); + return; + } + + /* clip the winding by node plane */ + ClipTraceWinding( tw, plane1, &front, &back ); + + /* filter by node plane */ + if( front.numVerts >= 3 ) + FilterTraceWindingIntoNodes_r( &front, node->children[ 0 ] ); + if( back.numVerts >= 3 ) + FilterTraceWindingIntoNodes_r( &back, node->children[ 1 ] ); + + /* return to caller */ + return; + } + + /* add winding to leaf node */ + num = AddTraceWinding( tw ); + AddItemToTraceNode( node, num ); +} + + + +/* +SubdivideTraceNode_r() - ydnar +recursively subdivides a tracing node until it meets certain size and complexity criteria +*/ + +static void SubdivideTraceNode_r( int nodeNum, int depth ) +{ + int i, j, count, num, frontNum, backNum, type; + vec3_t size; + float dist; + double average[ 3 ]; + traceNode_t *node, *frontNode, *backNode; + traceWinding_t *tw, front, back; + + + /* dummy check */ + if( nodeNum < 0 || nodeNum >= numTraceNodes ) + return; + + /* get node */ + node = &traceNodes[ nodeNum ]; + + /* runaway recursion check */ + if( depth >= MAX_TRACE_DEPTH ) + { + //% Sys_Printf( "Depth: (%d items)\n", node->numItems ); + numTraceLeafNodes++; + return; + } + depth++; + + /* is this a decision node? */ + if( node->type >= 0 ) + { + /* subdivide children */ + frontNum = node->children[ 0 ]; + backNum = node->children[ 1 ]; + SubdivideTraceNode_r( frontNum, depth ); + SubdivideTraceNode_r( backNum, depth ); + return; + } + + /* bound the node */ + ClearBounds( node->mins, node->maxs ); + VectorClear( average ); + count = 0; + for( i = 0; i < node->numItems; i++ ) + { + /* get winding */ + tw = &traceWindings[ node->items[ i ] ]; + + /* walk its verts */ + for( j = 0; j < tw->numVerts; j++ ) + { + AddPointToBounds( tw->v[ j ].xyz, node->mins, node->maxs ); + average[ 0 ] += tw->v[ j ].xyz[ 0 ]; + average[ 1 ] += tw->v[ j ].xyz[ 1 ]; + average[ 2 ] += tw->v[ j ].xyz[ 2 ]; + count++; + } + } + + /* check triangle limit */ + //% if( node->numItems <= MAX_NODE_ITEMS ) + if( (count - (node->numItems * 2)) < MAX_NODE_TRIANGLES ) + { + //% Sys_Printf( "Limit: (%d triangles)\n", (count - (node->numItems * 2)) ); + numTraceLeafNodes++; + return; + } + + /* the largest dimension of the bounding box will be the split axis */ + VectorSubtract( node->maxs, node->mins, size ); + if( size[ 0 ] >= size[ 1 ] && size[ 0 ] >= size[ 2 ] ) + type = PLANE_X; + else if( size[ 1 ] >= size[ 0 ] && size[ 1 ] >= size[ 2 ] ) + type = PLANE_Y; + else + type = PLANE_Z; + + /* don't split small nodes */ + if( size[ type ] <= MIN_NODE_SIZE ) + { + //% Sys_Printf( "Limit: %f %f %f (%d items)\n", size[ 0 ], size[ 1 ], size[ 2 ], node->numItems ); + numTraceLeafNodes++; + return; + } + + /* set max trace depth */ + if( depth > maxTraceDepth ) + maxTraceDepth = depth; + + /* snap the average */ + dist = floor( average[ type ] / count ); + + /* dummy check it */ + if( dist <= node->mins[ type ] || dist >= node->maxs[ type ] ) + dist = floor( 0.5f * (node->mins[ type ] + node->maxs[ type ]) ); + + /* allocate child nodes */ + frontNum = AllocTraceNode(); + backNum = AllocTraceNode(); + + /* reset pointers */ + node = &traceNodes[ nodeNum ]; + frontNode = &traceNodes[ frontNum ]; + backNode = &traceNodes[ backNum ]; + + /* attach children */ + node->type = type; + node->plane[ type ] = 1.0f; + node->plane[ 3 ] = dist; + node->children[ 0 ] = frontNum; + node->children[ 1 ] = backNum; + + /* setup front node */ + frontNode->maxItems = (node->maxItems >> 1); + frontNode->items = safe_malloc( frontNode->maxItems * sizeof( *frontNode->items ) ); + + /* setup back node */ + backNode->maxItems = (node->maxItems >> 1); + backNode->items = safe_malloc( backNode->maxItems * sizeof( *backNode->items ) ); + + /* filter windings into child nodes */ + for( i = 0; i < node->numItems; i++ ) + { + /* get winding */ + tw = &traceWindings[ node->items[ i ] ]; + + /* clip the winding by the new split plane */ + ClipTraceWinding( tw, node->plane, &front, &back ); + + /* kill the existing winding */ + if( front.numVerts >= 3 || back.numVerts >= 3 ) + deadWinding = node->items[ i ]; + + /* add front winding */ + if( front.numVerts >= 3 ) + { + num = AddTraceWinding( &front ); + AddItemToTraceNode( frontNode, num ); + } + + /* add back winding */ + if( back.numVerts >= 3 ) + { + num = AddTraceWinding( &back ); + AddItemToTraceNode( backNode, num ); + } + } + + /* free original node winding list */ + node->numItems = 0; + node->maxItems = 0; + free( node->items ); + node->items = NULL; + + /* check children */ + if( frontNode->numItems <= 0 ) + { + frontNode->maxItems = 0; + free( frontNode->items ); + frontNode->items = NULL; + } + + if( backNode->numItems <= 0 ) + { + backNode->maxItems = 0; + free( backNode->items ); + backNode->items = NULL; + } + + /* subdivide children */ + SubdivideTraceNode_r( frontNum, depth ); + SubdivideTraceNode_r( backNum, depth ); +} + + + +/* +TriangulateTraceNode_r() +optimizes the tracing data by changing trace windings into triangles +*/ + +static int TriangulateTraceNode_r( int nodeNum ) +{ + int i, j, num, frontNum, backNum, numWindings, *windings; + traceNode_t *node; + traceWinding_t *tw; + traceTriangle_t tt; + + + /* dummy check */ + if( nodeNum < 0 || nodeNum >= numTraceNodes ) + return 0; + + /* get node */ + node = &traceNodes[ nodeNum ]; + + /* is this a decision node? */ + if( node->type >= 0 ) + { + /* triangulate children */ + frontNum = node->children[ 0 ]; + backNum = node->children[ 1 ]; + node->numItems = TriangulateTraceNode_r( frontNum ); + node->numItems += TriangulateTraceNode_r( backNum ); + return node->numItems; + } + + /* empty node? */ + if( node->numItems == 0 ) + { + node->maxItems = 0; + if( node->items != NULL ) + free( node->items ); + return node->numItems; + } + + /* store off winding data */ + numWindings = node->numItems; + windings = node->items; + + /* clear it */ + node->numItems = 0; + node->maxItems = numWindings * 2; + node->items = safe_malloc( node->maxItems * sizeof( tt ) ); + + /* walk winding list */ + for( i = 0; i < numWindings; i++ ) + { + /* get winding */ + tw = &traceWindings[ windings[ i ] ]; + + /* initial setup */ + tt.infoNum = tw->infoNum; + tt.v[ 0 ] = tw->v[ 0 ]; + + /* walk vertex list */ + for( j = 1; j + 1 < tw->numVerts; j++ ) + { + /* set verts */ + tt.v[ 1 ] = tw->v[ j ]; + tt.v[ 2 ] = tw->v[ j + 1 ]; + + /* find vectors for two edges sharing the first vert */ + VectorSubtract( tt.v[ 1 ].xyz, tt.v[ 0 ].xyz, tt.edge1 ); + VectorSubtract( tt.v[ 2 ].xyz, tt.v[ 0 ].xyz, tt.edge2 ); + + /* add it to the node */ + num = AddTraceTriangle( &tt ); + AddItemToTraceNode( node, num ); + } + } + + /* free windings */ + if( windings != NULL ) + free( windings ); + + /* return item count */ + return node->numItems; +} + + + +/* ------------------------------------------------------------------------------- + +shadow casting item setup (triangles, patches, entities) + +------------------------------------------------------------------------------- */ + +/* +PopulateWithBSPModel() - ydnar +filters a bsp model's surfaces into the raytracing tree +*/ + +static void PopulateWithBSPModel( bspModel_t *model, m4x4_t transform ) +{ + int i, j, x, y, pw[ 5 ], r, nodeNum; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + bspDrawVert_t *verts; + int *indexes; + mesh_t srcMesh, *mesh, *subdivided; + traceInfo_t ti; + traceWinding_t tw; + + + /* dummy check */ + if( model == NULL || transform == NULL ) + return; + + /* walk the list of surfaces in this model and fill out the info structs */ + for( i = 0; i < model->numBSPSurfaces; i++ ) + { + /* get surface and info */ + ds = &bspDrawSurfaces[ model->firstBSPSurface + i ]; + info = &surfaceInfos[ model->firstBSPSurface + i ]; + if( info->si == NULL ) + continue; + + /* no shadows */ + if( !info->castShadows ) + continue; + + /* patchshadows? */ + if( ds->surfaceType == MST_PATCH && patchShadows == qfalse ) + continue; + + /* some surfaces in the bsp might have been tagged as nodraw, with a bogus shader */ + if( (bspShaders[ ds->shaderNum ].contentFlags & noDrawContentFlags) || + (bspShaders[ ds->shaderNum ].surfaceFlags & noDrawSurfaceFlags) ) + continue; + + /* translucent surfaces that are neither alphashadow or lightfilter don't cast shadows */ + if( (info->si->compileFlags & C_NODRAW) ) + continue; + if( (info->si->compileFlags & C_TRANSLUCENT) && + !(info->si->compileFlags & C_ALPHASHADOW) && + !(info->si->compileFlags & C_LIGHTFILTER) ) + continue; + + /* setup trace info */ + ti.si = info->si; + ti.castShadows = info->castShadows; + ti.surfaceNum = model->firstBSPBrush + i; + ti.skipGrid = (ds->surfaceType == MST_PATCH); + + /* choose which node (normal or skybox) */ + if( info->parentSurfaceNum >= 0 ) + { + nodeNum = skyboxNodeNum; + + /* sky surfaces in portal skies are ignored */ + if( info->si->compileFlags & C_SKY ) + continue; + } + else + nodeNum = headNodeNum; + + /* setup trace winding */ + memset( &tw, 0, sizeof( tw ) ); + tw.infoNum = AddTraceInfo( &ti ); + tw.numVerts = 3; + + /* switch on type */ + switch( ds->surfaceType ) + { + /* handle patches */ + case MST_PATCH: + /* subdivide the surface */ + srcMesh.width = ds->patchWidth; + srcMesh.height = ds->patchHeight; + srcMesh.verts = &bspDrawVerts[ ds->firstVert ]; + //% subdivided = SubdivideMesh( srcMesh, 8, 512 ); + subdivided = SubdivideMesh2( srcMesh, info->patchIterations ); + + /* fit it to the curve and remove colinear verts on rows/columns */ + PutMeshOnCurve( *subdivided ); + mesh = RemoveLinearMeshColumnsRows( subdivided ); + FreeMesh( subdivided ); + + /* set verts */ + verts = mesh->verts; + + /* subdivide each quad to place the models */ + for( y = 0; y < (mesh->height - 1); y++ ) + { + for( x = 0; x < (mesh->width - 1); x++ ) + { + /* set indexes */ + pw[ 0 ] = x + (y * mesh->width); + pw[ 1 ] = x + ((y + 1) * mesh->width); + pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); + pw[ 3 ] = x + 1 + (y * mesh->width); + pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ + + /* set radix */ + r = (x + y) & 1; + + /* make first triangle */ + VectorCopy( verts[ pw[ r + 0 ] ].xyz, tw.v[ 0 ].xyz ); + Vector2Copy( verts[ pw[ r + 0 ] ].st, tw.v[ 0 ].st ); + VectorCopy( verts[ pw[ r + 1 ] ].xyz, tw.v[ 1 ].xyz ); + Vector2Copy( verts[ pw[ r + 1 ] ].st, tw.v[ 1 ].st ); + VectorCopy( verts[ pw[ r + 2 ] ].xyz, tw.v[ 2 ].xyz ); + Vector2Copy( verts[ pw[ r + 2 ] ].st, tw.v[ 2 ].st ); + m4x4_transform_point( transform, tw.v[ 0 ].xyz ); + m4x4_transform_point( transform, tw.v[ 1 ].xyz ); + m4x4_transform_point( transform, tw.v[ 2 ].xyz ); + FilterTraceWindingIntoNodes_r( &tw, nodeNum ); + + /* make second triangle */ + VectorCopy( verts[ pw[ r + 0 ] ].xyz, tw.v[ 0 ].xyz ); + Vector2Copy( verts[ pw[ r + 0 ] ].st, tw.v[ 0 ].st ); + VectorCopy( verts[ pw[ r + 2 ] ].xyz, tw.v[ 1 ].xyz ); + Vector2Copy( verts[ pw[ r + 2 ] ].st, tw.v[ 1 ].st ); + VectorCopy( verts[ pw[ r + 3 ] ].xyz, tw.v[ 2 ].xyz ); + Vector2Copy( verts[ pw[ r + 3 ] ].st, tw.v[ 2 ].st ); + m4x4_transform_point( transform, tw.v[ 0 ].xyz ); + m4x4_transform_point( transform, tw.v[ 1 ].xyz ); + m4x4_transform_point( transform, tw.v[ 2 ].xyz ); + FilterTraceWindingIntoNodes_r( &tw, nodeNum ); + } + } + + /* free the subdivided mesh */ + FreeMesh( mesh ); + break; + + /* handle triangle surfaces */ + case MST_TRIANGLE_SOUP: + case MST_PLANAR: + /* set verts and indexes */ + verts = &bspDrawVerts[ ds->firstVert ]; + indexes = &bspDrawIndexes[ ds->firstIndex ]; + + /* walk the triangle list */ + for( j = 0; j < ds->numIndexes; j += 3 ) + { + VectorCopy( verts[ indexes[ j ] ].xyz, tw.v[ 0 ].xyz ); + Vector2Copy( verts[ indexes[ j ] ].st, tw.v[ 0 ].st ); + VectorCopy( verts[ indexes[ j + 1 ] ].xyz, tw.v[ 1 ].xyz ); + Vector2Copy( verts[ indexes[ j + 1 ] ].st, tw.v[ 1 ].st ); + VectorCopy( verts[ indexes[ j + 2 ] ].xyz, tw.v[ 2 ].xyz ); + Vector2Copy( verts[ indexes[ j + 2 ] ].st, tw.v[ 2 ].st ); + m4x4_transform_point( transform, tw.v[ 0 ].xyz ); + m4x4_transform_point( transform, tw.v[ 1 ].xyz ); + m4x4_transform_point( transform, tw.v[ 2 ].xyz ); + FilterTraceWindingIntoNodes_r( &tw, nodeNum ); + } + break; + + /* other surface types do not cast shadows */ + default: + break; + } + } +} + + + +/* +PopulateWithPicoModel() - ydnar +filters a picomodel's surfaces into the raytracing tree +*/ + +static void PopulateWithPicoModel( int castShadows, picoModel_t *model, m4x4_t transform ) +{ + int i, j, k, numSurfaces, numIndexes; + picoSurface_t *surface; + picoShader_t *shader; + picoVec_t *xyz, *st; + picoIndex_t *indexes; + traceInfo_t ti; + traceWinding_t tw; + + + /* dummy check */ + if( model == NULL || transform == NULL ) + return; + + /* get info */ + numSurfaces = PicoGetModelNumSurfaces( model ); + + /* walk the list of surfaces in this model and fill out the info structs */ + for( i = 0; i < numSurfaces; i++ ) + { + /* get surface */ + surface = PicoGetModelSurface( model, i ); + if( surface == NULL ) + continue; + + /* only handle triangle surfaces initially (fixme: support patches) */ + if( PicoGetSurfaceType( surface ) != PICO_TRIANGLES ) + continue; + + /* get shader (fixme: support shader remapping) */ + shader = PicoGetSurfaceShader( surface ); + if( shader == NULL ) + continue; + ti.si = ShaderInfoForShader( PicoGetShaderName( shader ) ); + if( ti.si == NULL ) + continue; + + /* translucent surfaces that are neither alphashadow or lightfilter don't cast shadows */ + if( (ti.si->compileFlags & C_NODRAW) ) + continue; + if( (ti.si->compileFlags & C_TRANSLUCENT) && + !(ti.si->compileFlags & C_ALPHASHADOW) && + !(ti.si->compileFlags & C_LIGHTFILTER) ) + continue; + + /* setup trace info */ + ti.castShadows = castShadows; + ti.surfaceNum = -1; + ti.skipGrid = qtrue; // also ignore picomodels when skipping patches + + /* setup trace winding */ + memset( &tw, 0, sizeof( tw ) ); + tw.infoNum = AddTraceInfo( &ti ); + tw.numVerts = 3; + + /* get info */ + numIndexes = PicoGetSurfaceNumIndexes( surface ); + indexes = PicoGetSurfaceIndexes( surface, 0 ); + + /* walk the triangle list */ + for( j = 0; j < numIndexes; j += 3, indexes += 3 ) + { + for( k = 0; k < 3; k++ ) + { + xyz = PicoGetSurfaceXYZ( surface, indexes[ k ] ); + st = PicoGetSurfaceST( surface, 0, indexes[ k ] ); + VectorCopy( xyz, tw.v[ k ].xyz ); + Vector2Copy( st, tw.v[ k ].st ); + m4x4_transform_point( transform, tw.v[ k ].xyz ); + } + FilterTraceWindingIntoNodes_r( &tw, headNodeNum ); + } + } +} + + + +/* +PopulateTraceNodes() - ydnar +fills the raytracing tree with world and entity occluders +*/ + +static void PopulateTraceNodes( void ) +{ + int i, m, frame, castShadows; + float temp; + entity_t *e; + const char *value; + picoModel_t *model; + vec3_t origin, scale, angles; + m4x4_t transform; + + + /* add worldspawn triangles */ + m4x4_identity( transform ); + PopulateWithBSPModel( &bspModels[ 0 ], transform ); + + /* walk each entity list */ + for( i = 1; i < numEntities; i++ ) + { + /* get entity */ + e = &entities[ i ]; + + /* get shadow flags */ + castShadows = ENTITY_CAST_SHADOWS; + GetEntityShadowFlags( e, NULL, &castShadows, NULL ); + + /* early out? */ + if( !castShadows ) + continue; + + /* get entity origin */ + GetVectorForKey( e, "origin", origin ); + + /* get scale */ + scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = 1.0f; + temp = FloatForKey( e, "modelscale" ); + if( temp != 0.0f ) + scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp; + value = ValueForKey( e, "modelscale_vec" ); + if( value[ 0 ] != '\0' ) + sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] ); + + /* get "angle" (yaw) or "angles" (pitch yaw roll) */ + angles[ 0 ] = angles[ 1 ] = angles[ 2 ] = 0.0f; + angles[ 2 ] = FloatForKey( e, "angle" ); + value = ValueForKey( e, "angles" ); + if( value[ 0 ] != '\0' ) + sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ); + + /* set transform matrix (thanks spog) */ + m4x4_identity( transform ); + m4x4_pivoted_transform_by_vec3( transform, origin, angles, eXYZ, scale, vec3_origin ); + + /* hack: Stable-1_2 and trunk have differing row/column major matrix order + this transpose is necessary with Stable-1_2 + uncomment the following line with old m4x4_t (non 1.3/spog_branch) code */ + //% m4x4_transpose( transform ); + + /* get model */ + value = ValueForKey( e, "model" ); + + /* switch on model type */ + switch( value[ 0 ] ) + { + /* no model */ + case '\0': + break; + + /* bsp model */ + case '*': + m = atoi( &value[ 1 ] ); + if( m <= 0 || m >= numBSPModels ) + continue; + PopulateWithBSPModel( &bspModels[ m ], transform ); + break; + + /* external model */ + default: + frame = IntForKey( e, "_frame" ); + model = LoadModel( value, frame ); + if( model == NULL ) + continue; + PopulateWithPicoModel( castShadows, model, transform ); + continue; + } + + /* get model2 */ + value = ValueForKey( e, "model2" ); + + /* switch on model type */ + switch( value[ 0 ] ) + { + /* no model */ + case '\0': + break; + + /* bsp model */ + case '*': + m = atoi( &value[ 1 ] ); + if( m <= 0 || m >= numBSPModels ) + continue; + PopulateWithBSPModel( &bspModels[ m ], transform ); + break; + + /* external model */ + default: + frame = IntForKey( e, "_frame2" ); + model = LoadModel( value, frame ); + if( model == NULL ) + continue; + PopulateWithPicoModel( castShadows, model, transform ); + continue; + } + } +} + + + + +/* ------------------------------------------------------------------------------- + +trace initialization + +------------------------------------------------------------------------------- */ + +/* +SetupTraceNodes() - ydnar +creates a balanced bsp with axis-aligned splits for efficient raytracing +*/ + +void SetupTraceNodes( void ) +{ + /* note it */ + Sys_FPrintf( SYS_VRB, "--- SetupTraceNodes ---\n" ); + + /* find nodraw bit */ + noDrawContentFlags = noDrawSurfaceFlags = noDrawCompileFlags = 0; + ApplySurfaceParm( "nodraw", &noDrawContentFlags, &noDrawSurfaceFlags, &noDrawCompileFlags ); + + /* create the baseline raytracing tree from the bsp tree */ + headNodeNum = SetupTraceNodes_r( 0 ); + + /* create outside node for skybox surfaces */ + skyboxNodeNum = AllocTraceNode(); + + /* populate the tree with triangles from the world and shadow casting entities */ + PopulateTraceNodes(); + + /* create the raytracing bsp */ + if( loMem == qfalse ) + { + SubdivideTraceNode_r( headNodeNum, 0 ); + SubdivideTraceNode_r( skyboxNodeNum, 0 ); + } + + /* create triangles from the trace windings */ + TriangulateTraceNode_r( headNodeNum ); + TriangulateTraceNode_r( skyboxNodeNum ); + + /* emit some stats */ + //% Sys_FPrintf( SYS_VRB, "%9d original triangles\n", numOriginalTriangles ); + Sys_FPrintf( SYS_VRB, "%9d trace windings (%.2fMB)\n", numTraceWindings, (float) (numTraceWindings * sizeof( *traceWindings )) / (1024.0f * 1024.0f) ); + Sys_FPrintf( SYS_VRB, "%9d trace triangles (%.2fMB)\n", numTraceTriangles, (float) (numTraceTriangles * sizeof( *traceTriangles )) / (1024.0f * 1024.0f) ); + Sys_FPrintf( SYS_VRB, "%9d trace nodes (%.2fMB)\n", numTraceNodes, (float) (numTraceNodes * sizeof( *traceNodes )) / (1024.0f * 1024.0f) ); + Sys_FPrintf( SYS_VRB, "%9d leaf nodes (%.2fMB)\n", numTraceLeafNodes, (float) (numTraceLeafNodes * sizeof( *traceNodes )) / (1024.0f * 1024.0f) ); + //% Sys_FPrintf( SYS_VRB, "%9d average triangles per leaf node\n", numTraceTriangles / numTraceLeafNodes ); + Sys_FPrintf( SYS_VRB, "%9d average windings per leaf node\n", numTraceWindings / (numTraceLeafNodes + 1) ); + Sys_FPrintf( SYS_VRB, "%9d max trace depth\n", maxTraceDepth ); + + /* free trace windings */ + free( traceWindings ); + numTraceWindings = 0; + maxTraceWindings = 0; + deadWinding = -1; + + /* debug code: write out trace triangles to an alias obj file */ + #if 0 + { + int i, j; + FILE *file; + char filename[ 1024 ]; + traceWinding_t *tw; + + + /* open the file */ + strcpy( filename, source ); + StripExtension( filename ); + strcat( filename, ".lin" ); + Sys_Printf( "Opening light trace file %s...\n", filename ); + file = fopen( filename, "w" ); + if( file == NULL ) + Error( "Error opening %s for writing", filename ); + + /* walk node list */ + for( i = 0; i < numTraceWindings; i++ ) + { + tw = &traceWindings[ i ]; + for( j = 0; j < tw->numVerts + 1; j++ ) + fprintf( file, "%f %f %f\n", + tw->v[ j % tw->numVerts ].xyz[ 0 ], tw->v[ j % tw->numVerts ].xyz[ 1 ], tw->v[ j % tw->numVerts ].xyz[ 2 ] ); + } + + /* close it */ + fclose( file ); + } + #endif +} + + + +/* ------------------------------------------------------------------------------- + +raytracer + +------------------------------------------------------------------------------- */ + +/* +TraceTriangle() +based on code written by william 'spog' joseph +based on code originally written by tomas moller and ben trumbore, journal of graphics tools, 2(1):21-28, 1997 +*/ + +#define BARY_EPSILON 0.01f +#define ASLF_EPSILON 0.0001f /* so to not get double shadows */ +#define COPLANAR_EPSILON 0.25f //% 0.000001f +#define NEAR_SHADOW_EPSILON 1.5f //% 1.25f +#define SELF_SHADOW_EPSILON 0.5f + +qboolean TraceTriangle( traceInfo_t *ti, traceTriangle_t *tt, trace_t *trace ) +{ + int i; + float tvec[ 3 ], pvec[ 3 ], qvec[ 3 ]; + float det, invDet, depth; + float u, v, w, s, t; + int is, it; + byte *pixel; + float shadow; + shaderInfo_t *si; + + + /* don't double-trace against sky */ + si = ti->si; + if( trace->compileFlags & si->compileFlags & C_SKY ) + return qfalse; + + /* receive shadows from worldspawn group only */ + if( trace->recvShadows == 1 ) + { + if( ti->castShadows != 1 ) + return qfalse; + } + + /* receive shadows from same group and worldspawn group */ + else if( trace->recvShadows > 1 ) + { + if( ti->castShadows != 1 && abs( ti->castShadows ) != abs( trace->recvShadows ) ) + return qfalse; + //% Sys_Printf( "%d:%d ", tt->castShadows, trace->recvShadows ); + } + + /* receive shadows from the same group only (< 0) */ + else + { + if( abs( ti->castShadows ) != abs( trace->recvShadows ) ) + return qfalse; + } + + /* skip patches when doing the grid (FIXME this is an ugly hack) */ + if( inGrid ) + { + if (ti->skipGrid) + return qfalse; + } + + /* begin calculating determinant - also used to calculate u parameter */ + CrossProduct( trace->direction, tt->edge2, pvec ); + + /* if determinant is near zero, trace lies in plane of triangle */ + det = DotProduct( tt->edge1, pvec ); + + /* the non-culling branch */ + if( fabs( det ) < COPLANAR_EPSILON ) + return qfalse; + invDet = 1.0f / det; + + /* calculate distance from first vertex to ray origin */ + VectorSubtract( trace->origin, tt->v[ 0 ].xyz, tvec ); + + /* calculate u parameter and test bounds */ + u = DotProduct( tvec, pvec ) * invDet; + if( u < -BARY_EPSILON || u > (1.0f + BARY_EPSILON) ) + return qfalse; + + /* prepare to test v parameter */ + CrossProduct( tvec, tt->edge1, qvec ); + + /* calculate v parameter and test bounds */ + v = DotProduct( trace->direction, qvec ) * invDet; + if( v < -BARY_EPSILON || (u + v) > (1.0f + BARY_EPSILON) ) + return qfalse; + + /* calculate t (depth) */ + depth = DotProduct( tt->edge2, qvec ) * invDet; + if( depth <= trace->inhibitRadius || depth >= trace->distance ) + return qfalse; + + /* if hitpoint is really close to trace origin (sample point), then check for self-shadowing */ + if( depth <= SELF_SHADOW_EPSILON ) + { + /* don't self-shadow */ + for( i = 0; i < trace->numSurfaces; i++ ) + { + if( ti->surfaceNum == trace->surfaces[ i ] ) + return qfalse; + } + } + + /* stack compile flags */ + trace->compileFlags |= si->compileFlags; + + /* don't trace against sky */ + if( si->compileFlags & C_SKY ) + return qfalse; + + /* most surfaces are completely opaque */ + if( !(si->compileFlags & (C_ALPHASHADOW | C_LIGHTFILTER)) || + si->lightImage == NULL || si->lightImage->pixels == NULL ) + { + VectorMA( trace->origin, depth, trace->direction, trace->hit ); + VectorClear( trace->color ); + trace->opaque = qtrue; + return qtrue; + } + + /* force subsampling because the lighting is texture dependent */ + trace->forceSubsampling = 1.0; + + /* try to avoid double shadows near triangle seams */ + if( u < -ASLF_EPSILON || u > (1.0f + ASLF_EPSILON) || + v < -ASLF_EPSILON || (u + v) > (1.0f + ASLF_EPSILON) ) + return qfalse; + + /* calculate w parameter */ + w = 1.0f - (u + v); + + /* calculate st from uvw (barycentric) coordinates */ + s = w * tt->v[ 0 ].st[ 0 ] + u * tt->v[ 1 ].st[ 0 ] + v * tt->v[ 2 ].st[ 0 ]; + t = w * tt->v[ 0 ].st[ 1 ] + u * tt->v[ 1 ].st[ 1 ] + v * tt->v[ 2 ].st[ 1 ]; + s = s - floor( s ); + t = t - floor( t ); + is = s * si->lightImage->width; + it = t * si->lightImage->height; + + /* get pixel */ + pixel = si->lightImage->pixels + 4 * (it * si->lightImage->width + is); + + /* ydnar: color filter */ + if( si->compileFlags & C_LIGHTFILTER ) + { + /* filter by texture color */ + trace->color[ 0 ] *= ((1.0f / 255.0f) * pixel[ 0 ]); + trace->color[ 1 ] *= ((1.0f / 255.0f) * pixel[ 1 ]); + trace->color[ 2 ] *= ((1.0f / 255.0f) * pixel[ 2 ]); + } + + /* ydnar: alpha filter */ + if( si->compileFlags & C_ALPHASHADOW ) + { + /* filter by inverse texture alpha */ + shadow = (1.0f / 255.0f) * (255 - pixel[ 3 ]); + trace->color[ 0 ] *= shadow; + trace->color[ 1 ] *= shadow; + trace->color[ 2 ] *= shadow; + } + + /* check filter for opaque */ + if( trace->color[ 0 ] <= 0.001f && trace->color[ 1 ] <= 0.001f && trace->color[ 2 ] <= 0.001f ) + { + VectorClear( trace->color ); + VectorMA( trace->origin, depth, trace->direction, trace->hit ); + trace->opaque = qtrue; + return qtrue; + } + + /* continue tracing */ + return qfalse; +} + + + +/* +TraceWinding() - ydnar +temporary hack +*/ + +qboolean TraceWinding( traceWinding_t *tw, trace_t *trace ) +{ + int i; + traceTriangle_t tt; + + + /* initial setup */ + tt.infoNum = tw->infoNum; + tt.v[ 0 ] = tw->v[ 0 ]; + + /* walk vertex list */ + for( i = 1; i + 1 < tw->numVerts; i++ ) + { + /* set verts */ + tt.v[ 1 ] = tw->v[ i ]; + tt.v[ 2 ] = tw->v[ i + 1 ]; + + /* find vectors for two edges sharing the first vert */ + VectorSubtract( tt.v[ 1 ].xyz, tt.v[ 0 ].xyz, tt.edge1 ); + VectorSubtract( tt.v[ 2 ].xyz, tt.v[ 0 ].xyz, tt.edge2 ); + + /* trace it */ + if( TraceTriangle( &traceInfos[ tt.infoNum ], &tt, trace ) ) + return qtrue; + } + + /* done */ + return qfalse; +} + + + + +/* +TraceLine_r() +returns qtrue if something is hit and tracing can stop +*/ + +static qboolean TraceLine_r( int nodeNum, vec3_t origin, vec3_t end, trace_t *trace ) +{ + traceNode_t *node; + int side; + float front, back, frac; + vec3_t mid; + qboolean r; + + + /* bogus node number means solid, end tracing unless testing all */ + if( nodeNum < 0 ) + { + VectorCopy( origin, trace->hit ); + trace->passSolid = qtrue; + return qtrue; + } + + /* get node */ + node = &traceNodes[ nodeNum ]; + + /* solid? */ + if( node->type == TRACE_LEAF_SOLID ) + { + VectorCopy( origin, trace->hit ); + trace->passSolid = qtrue; + return qtrue; + } + + /* leafnode? */ + if( node->type < 0 ) + { + /* note leaf and return */ + if( node->numItems > 0 && trace->numTestNodes < MAX_TRACE_TEST_NODES ) + trace->testNodes[ trace->numTestNodes++ ] = nodeNum; + return qfalse; + } + + /* ydnar 2003-09-07: don't test branches of the bsp with nothing in them when testall is enabled */ + if( trace->testAll && node->numItems == 0 ) + return qfalse; + + /* classify beginning and end points */ + switch( node->type ) + { + case PLANE_X: + front = origin[ 0 ] - node->plane[ 3 ]; + back = end[ 0 ] - node->plane[ 3 ]; + break; + + case PLANE_Y: + front = origin[ 1 ] - node->plane[ 3 ]; + back = end[ 1 ] - node->plane[ 3 ]; + break; + + case PLANE_Z: + front = origin[ 2 ] - node->plane[ 3 ]; + back = end[ 2 ] - node->plane[ 3 ]; + break; + + default: + front = DotProduct( origin, node->plane ) - node->plane[ 3 ]; + back = DotProduct( end, node->plane ) - node->plane[ 3 ]; + break; + } + + /* entirely in front side? */ + if( front >= -TRACE_ON_EPSILON && back >= -TRACE_ON_EPSILON ) + return TraceLine_r( node->children[ 0 ], origin, end, trace ); + + /* entirely on back side? */ + if( front < TRACE_ON_EPSILON && back < TRACE_ON_EPSILON ) + return TraceLine_r( node->children[ 1 ], origin, end, trace ); + + /* select side */ + side = front < 0; + + /* calculate intercept point */ + frac = front / (front - back); + mid[ 0 ] = origin[ 0 ] + (end[ 0 ] - origin[ 0 ]) * frac; + mid[ 1 ] = origin[ 1 ] + (end[ 1 ] - origin[ 1 ]) * frac; + mid[ 2 ] = origin[ 2 ] + (end[ 2 ] - origin[ 2 ]) * frac; + + /* fixme: check inhibit radius, then solid nodes and ignore */ + + /* set trace hit here */ + //% VectorCopy( mid, trace->hit ); + + /* trace first side */ + r = TraceLine_r( node->children[ side ], origin, mid, trace ); + if( r ) + return r; + + /* trace other side */ + return TraceLine_r( node->children[ !side ], mid, end, trace ); +} + + + +/* +TraceLine() - ydnar +rewrote this function a bit :) +*/ + +void TraceLine( trace_t *trace ) +{ + int i, j; + traceNode_t *node; + traceTriangle_t *tt; + traceInfo_t *ti; + + + /* setup output (note: this code assumes the input data is completely filled out) */ + trace->passSolid = qfalse; + trace->opaque = qfalse; + trace->compileFlags = 0; + trace->numTestNodes = 0; + + /* early outs */ + if( !trace->recvShadows || !trace->testOcclusion || trace->distance <= 0.00001f ) + return; + + /* trace through nodes */ + TraceLine_r( headNodeNum, trace->origin, trace->end, trace ); + if( trace->passSolid && !trace->testAll ) + { + trace->opaque = qtrue; + return; + } + + /* skip surfaces? */ + if( noSurfaces ) + return; + + /* testall means trace through sky */ + if( trace->testAll && trace->numTestNodes < MAX_TRACE_TEST_NODES && + trace->compileFlags & C_SKY && + (trace->numSurfaces == 0 || surfaceInfos[ trace->surfaces[ 0 ] ].childSurfaceNum < 0) ) + { + //% trace->testNodes[ trace->numTestNodes++ ] = skyboxNodeNum; + TraceLine_r( skyboxNodeNum, trace->origin, trace->end, trace ); + } + + /* walk node list */ + for( i = 0; i < trace->numTestNodes; i++ ) + { + /* get node */ + node = &traceNodes[ trace->testNodes[ i ] ]; + + /* walk node item list */ + for( j = 0; j < node->numItems; j++ ) + { + tt = &traceTriangles[ node->items[ j ] ]; + ti = &traceInfos[ tt->infoNum ]; + if( TraceTriangle( ti, tt, trace ) ) + return; + //% if( TraceWinding( &traceWindings[ node->items[ j ] ], trace ) ) + //% return; + } + } +} + + + +/* +SetupTrace() - ydnar +sets up certain trace values +*/ + +float SetupTrace( trace_t *trace ) +{ + VectorSubtract( trace->end, trace->origin, trace->displacement ); + trace->distance = VectorNormalize( trace->displacement, trace->direction ); + VectorCopy( trace->origin, trace->hit ); + return trace->distance; +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_ydnar.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_ydnar.c new file mode 100644 index 00000000..f60e6645 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/light_ydnar.c @@ -0,0 +1,4434 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define LIGHT_YDNAR_C + + + +/* dependencies */ +#include "q3map2.h" + + + + +/* +ColorToBytes() +ydnar: moved to here 2001-02-04 +*/ + +void ColorToBytes( const float *color, byte *colorBytes, float scale ) +{ + int i; + float max, gamma; + vec3_t sample; + float inv, dif; + + + /* ydnar: scaling necessary for simulating r_overbrightBits on external lightmaps */ + if( scale <= 0.0f ) + scale = 1.0f; + + /* make a local copy */ + VectorScale( color, scale, sample ); + + /* muck with it */ + gamma = 1.0f / lightmapGamma; + for( i = 0; i < 3; i++ ) + { + /* handle negative light */ + if( sample[ i ] < 0.0f ) + { + sample[ i ] = 0.0f; + continue; + } + + /* gamma */ + sample[ i ] = pow( sample[ i ] / 255.0f, gamma ) * 255.0f; + } + + if (lightmapExposure == 1) + { + /* clamp with color normalization */ + max = sample[ 0 ]; + if( sample[ 1 ] > max ) + max = sample[ 1 ]; + if( sample[ 2 ] > max ) + max = sample[ 2 ]; + if( max > 255.0f ) + VectorScale( sample, (255.0f / max), sample ); + } + else + { + if (lightmapExposure==0) + { + lightmapExposure=1.0f; + } + inv=1.f/lightmapExposure; + //Exposure + + max = sample[ 0 ]; + if( sample[ 1 ] > max ) + max = sample[ 1 ]; + if( sample[ 2 ] > max ) + max = sample[ 2 ]; + + dif = (1- exp(-max * inv) ) * 255; + + if (max >0) + { + dif = dif / max; + } + else + { + dif = 0; + } + + for (i=0;i<3;i++) + { + sample[i]*=dif; + } + } + + + /* compensate for ingame overbrighting/bitshifting */ + VectorScale( sample, (1.0f / lightmapCompensate), sample ); + + /* store it off */ + colorBytes[ 0 ] = sample[ 0 ]; + colorBytes[ 1 ] = sample[ 1 ]; + colorBytes[ 2 ] = sample[ 2 ]; +} + + + +/* ------------------------------------------------------------------------------- + +this section deals with phong shading (normal interpolation across brush faces) + +------------------------------------------------------------------------------- */ + +/* +SmoothNormals() +smooths together coincident vertex normals across the bsp +*/ + +#define MAX_SAMPLES 256 +#define THETA_EPSILON 0.000001 +#define EQUAL_NORMAL_EPSILON 0.01 + +void SmoothNormals( void ) +{ + int i, j, k, f, cs, numVerts, numVotes, fOld, start; + float shadeAngle, defaultShadeAngle, maxShadeAngle, dot, testAngle; + bspDrawSurface_t *ds; + shaderInfo_t *si; + float *shadeAngles; + byte *smoothed; + vec3_t average, diff; + int indexes[ MAX_SAMPLES ]; + vec3_t votes[ MAX_SAMPLES ]; + + + /* allocate shade angle table */ + shadeAngles = safe_malloc( numBSPDrawVerts * sizeof( float ) ); + memset( shadeAngles, 0, numBSPDrawVerts * sizeof( float ) ); + + /* allocate smoothed table */ + cs = (numBSPDrawVerts / 8) + 1; + smoothed = safe_malloc( cs ); + memset( smoothed, 0, cs ); + + /* set default shade angle */ + defaultShadeAngle = DEG2RAD( shadeAngleDegrees ); + maxShadeAngle = 0; + + /* run through every surface and flag verts belonging to non-lightmapped surfaces + and set per-vertex smoothing angle */ + for( i = 0; i < numBSPDrawSurfaces; i++ ) + { + /* get drawsurf */ + ds = &bspDrawSurfaces[ i ]; + + /* get shader for shade angle */ + si = surfaceInfos[ i ].si; + if( si->shadeAngleDegrees ) + shadeAngle = DEG2RAD( si->shadeAngleDegrees ); + else + shadeAngle = defaultShadeAngle; + if( shadeAngle > maxShadeAngle ) + maxShadeAngle = shadeAngle; + + /* flag its verts */ + for( j = 0; j < ds->numVerts; j++ ) + { + f = ds->firstVert + j; + shadeAngles[ f ] = shadeAngle; + if( ds->surfaceType == MST_TRIANGLE_SOUP ) + smoothed[ f >> 3 ] |= (1 << (f & 7)); + } + + /* ydnar: optional force-to-trisoup */ + if( trisoup && ds->surfaceType == MST_PLANAR ) + { + ds->surfaceType = MST_TRIANGLE_SOUP; + ds->lightmapNum[ 0 ] = -3; + } + } + + /* bail if no surfaces have a shade angle */ + if( maxShadeAngle == 0 ) + { + free( shadeAngles ); + free( smoothed ); + return; + } + + /* init pacifier */ + fOld = -1; + start = I_FloatTime(); + + /* go through the list of vertexes */ + for( i = 0; i < numBSPDrawVerts; i++ ) + { + /* print pacifier */ + f = 10 * i / numBSPDrawVerts; + if( f != fOld ) + { + fOld = f; + Sys_Printf( "%i...", f ); + } + + /* already smoothed? */ + if( smoothed[ i >> 3 ] & (1 << (i & 7)) ) + continue; + + /* clear */ + VectorClear( average ); + numVerts = 0; + numVotes = 0; + + /* build a table of coincident vertexes */ + for( j = i; j < numBSPDrawVerts && numVerts < MAX_SAMPLES; j++ ) + { + /* already smoothed? */ + if( smoothed[ j >> 3 ] & (1 << (j & 7)) ) + continue; + + /* test vertexes */ + if( VectorCompare( yDrawVerts[ i ].xyz, yDrawVerts[ j ].xyz ) == qfalse ) + continue; + + /* use smallest shade angle */ + shadeAngle = (shadeAngles[ i ] < shadeAngles[ j ] ? shadeAngles[ i ] : shadeAngles[ j ]); + + /* check shade angle */ + dot = DotProduct( bspDrawVerts[ i ].normal, bspDrawVerts[ j ].normal ); + if( dot > 1.0 ) + dot = 1.0; + else if( dot < -1.0 ) + dot = -1.0; + testAngle = acos( dot ) + THETA_EPSILON; + if( testAngle >= shadeAngle ) + { + //Sys_Printf( "F(%3.3f >= %3.3f) ", RAD2DEG( testAngle ), RAD2DEG( shadeAngle ) ); + continue; + } + //Sys_Printf( "P(%3.3f < %3.3f) ", RAD2DEG( testAngle ), RAD2DEG( shadeAngle ) ); + + /* add to the list */ + indexes[ numVerts++ ] = j; + + /* flag vertex */ + smoothed[ j >> 3 ] |= (1 << (j & 7)); + + /* see if this normal has already been voted */ + for( k = 0; k < numVotes; k++ ) + { + VectorSubtract( bspDrawVerts[ j ].normal, votes[ k ], diff ); + if( fabs( diff[ 0 ] ) < EQUAL_NORMAL_EPSILON && + fabs( diff[ 1 ] ) < EQUAL_NORMAL_EPSILON && + fabs( diff[ 2 ] ) < EQUAL_NORMAL_EPSILON ) + break; + } + + /* add a new vote? */ + if( k == numVotes && numVotes < MAX_SAMPLES ) + { + VectorAdd( average, bspDrawVerts[ j ].normal, average ); + VectorCopy( bspDrawVerts[ j ].normal, votes[ numVotes ] ); + numVotes++; + } + } + + /* don't average for less than 2 verts */ + if( numVerts < 2 ) + continue; + + /* average normal */ + if( VectorNormalize( average, average ) > 0 ) + { + /* smooth */ + for( j = 0; j < numVerts; j++ ) + VectorCopy( average, yDrawVerts[ indexes[ j ] ].normal ); + } + } + + /* free the tables */ + free( shadeAngles ); + free( smoothed ); + + /* print time */ + Sys_Printf( " (%i)\n", (int) (I_FloatTime() - start) ); +} + + + +/* ------------------------------------------------------------------------------- + +this section deals with phong shaded lightmap tracing + +------------------------------------------------------------------------------- */ + +/* 9th rewrite (recursive subdivision of a lightmap triangle) */ + +/* +CalcTangentVectors() +calculates the st tangent vectors for normalmapping +*/ + +static qboolean CalcTangentVectors( int numVerts, bspDrawVert_t **dv, vec3_t *stv, vec3_t *ttv ) +{ + int i; + float bb, s, t; + vec3_t bary; + + + /* calculate barycentric basis for the triangle */ + bb = (dv[ 1 ]->st[ 0 ] - dv[ 0 ]->st[ 0 ]) * (dv[ 2 ]->st[ 1 ] - dv[ 0 ]->st[ 1 ]) - (dv[ 2 ]->st[ 0 ] - dv[ 0 ]->st[ 0 ]) * (dv[ 1 ]->st[ 1 ] - dv[ 0 ]->st[ 1 ]); + if( fabs( bb ) < 0.00000001f ) + return qfalse; + + /* do each vertex */ + for( i = 0; i < numVerts; i++ ) + { + /* calculate s tangent vector */ + s = dv[ i ]->st[ 0 ] + 10.0f; + t = dv[ i ]->st[ 1 ]; + bary[ 0 ] = ((dv[ 1 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t) - (dv[ 2 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t)) / bb; + bary[ 1 ] = ((dv[ 2 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t) - (dv[ 0 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t)) / bb; + bary[ 2 ] = ((dv[ 0 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t) - (dv[ 1 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t)) / bb; + + stv[ i ][ 0 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 0 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 0 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 0 ]; + stv[ i ][ 1 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 1 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 1 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 1 ]; + stv[ i ][ 2 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 2 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 2 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 2 ]; + + VectorSubtract( stv[ i ], dv[ i ]->xyz, stv[ i ] ); + VectorNormalize( stv[ i ], stv[ i ] ); + + /* calculate t tangent vector */ + s = dv[ i ]->st[ 0 ]; + t = dv[ i ]->st[ 1 ] + 10.0f; + bary[ 0 ] = ((dv[ 1 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t) - (dv[ 2 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t)) / bb; + bary[ 1 ] = ((dv[ 2 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t) - (dv[ 0 ]->st[ 0 ] - s) * (dv[ 2 ]->st[ 1 ] - t)) / bb; + bary[ 2 ] = ((dv[ 0 ]->st[ 0 ] - s) * (dv[ 1 ]->st[ 1 ] - t) - (dv[ 1 ]->st[ 0 ] - s) * (dv[ 0 ]->st[ 1 ] - t)) / bb; + + ttv[ i ][ 0 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 0 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 0 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 0 ]; + ttv[ i ][ 1 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 1 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 1 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 1 ]; + ttv[ i ][ 2 ] = bary[ 0 ] * dv[ 0 ]->xyz[ 2 ] + bary[ 1 ] * dv[ 1 ]->xyz[ 2 ] + bary[ 2 ] * dv[ 2 ]->xyz[ 2 ]; + + VectorSubtract( ttv[ i ], dv[ i ]->xyz, ttv[ i ] ); + VectorNormalize( ttv[ i ], ttv[ i ] ); + + /* debug code */ + //% Sys_FPrintf( SYS_VRB, "%d S: (%f %f %f) T: (%f %f %f)\n", i, + //% stv[ i ][ 0 ], stv[ i ][ 1 ], stv[ i ][ 2 ], ttv[ i ][ 0 ], ttv[ i ][ 1 ], ttv[ i ][ 2 ] ); + } + + /* return to caller */ + return qtrue; +} + + + + +/* +PerturbNormal() +perterbs the normal by the shader's normalmap in tangent space +*/ + +static void PerturbNormal( bspDrawVert_t *dv, shaderInfo_t *si, vec3_t pNormal, vec3_t stv[ 3 ], vec3_t ttv[ 3 ] ) +{ + int i; + vec4_t bump; + + + /* passthrough */ + VectorCopy( dv->normal, pNormal ); + + /* sample normalmap */ + if( RadSampleImage( si->normalImage->pixels, si->normalImage->width, si->normalImage->height, dv->st, bump ) == qfalse ) + return; + + /* remap sampled normal from [0,255] to [-1,-1] */ + for( i = 0; i < 3; i++ ) + bump[ i ] = (bump[ i ] - 127.0f) * (1.0f / 127.5f); + + /* scale tangent vectors and add to original normal */ + VectorMA( dv->normal, bump[ 0 ], stv[ 0 ], pNormal ); + VectorMA( pNormal, bump[ 1 ], ttv[ 0 ], pNormal ); + VectorMA( pNormal, bump[ 2 ], dv->normal, pNormal ); + + /* renormalize and return */ + VectorNormalize( pNormal, pNormal ); +} + + + +/* +MapSingleLuxel() +maps a luxel for triangle bv at +*/ + +#define NUDGE 0.5f +#define BOGUS_NUDGE -99999.0f + +static int MapSingleLuxel( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv, vec4_t plane, float pass, vec3_t stv[ 3 ], vec3_t ttv[ 3 ], vec3_t worldverts[ 3 ] ) +{ + int i, x, y, numClusters, *clusters, pointCluster, *cluster; + float *luxel, *origin, *normal, d, lightmapSampleOffset; + shaderInfo_t *si; + vec3_t pNormal; + vec3_t vecs[ 3 ]; + vec3_t nudged; + vec3_t cverts[ 3 ]; + vec3_t temp; + vec4_t sideplane, hostplane; + vec3_t origintwo; + int j, next; + float e; + float *nudge; + static float nudges[][ 2 ] = + { + //%{ 0, 0 }, /* try center first */ + { -NUDGE, 0 }, /* left */ + { NUDGE, 0 }, /* right */ + { 0, NUDGE }, /* up */ + { 0, -NUDGE }, /* down */ + { -NUDGE, NUDGE }, /* left/up */ + { NUDGE, -NUDGE }, /* right/down */ + { NUDGE, NUDGE }, /* right/up */ + { -NUDGE, -NUDGE }, /* left/down */ + { BOGUS_NUDGE, BOGUS_NUDGE } + }; + + + /* find luxel xy coords (fixme: subtract 0.5?) */ + x = dv->lightmap[ 0 ][ 0 ]; + y = dv->lightmap[ 0 ][ 1 ]; + if( x < 0 ) + x = 0; + else if( x >= lm->sw ) + x = lm->sw - 1; + if( y < 0 ) + y = 0; + else if( y >= lm->sh ) + y = lm->sh - 1; + + /* set shader and cluster list */ + if( info != NULL ) + { + si = info->si; + numClusters = info->numSurfaceClusters; + clusters = &surfaceClusters[ info->firstSurfaceCluster ]; + } + else + { + si = NULL; + numClusters = 0; + clusters = NULL; + } + + /* get luxel, origin, cluster, and normal */ + luxel = SUPER_LUXEL( 0, x, y ); + origin = SUPER_ORIGIN( x, y ); + normal = SUPER_NORMAL( x, y ); + cluster = SUPER_CLUSTER( x, y ); + + /* don't attempt to remap occluded luxels for planar surfaces */ + if( (*cluster) == CLUSTER_OCCLUDED && lm->plane != NULL ) + return (*cluster); + + /* only average the normal for premapped luxels */ + else if( (*cluster) >= 0 ) + { + /* do bumpmap calculations */ + if( stv != NULL ) + PerturbNormal( dv, si, pNormal, stv, ttv ); + else + VectorCopy( dv->normal, pNormal ); + + /* add the additional normal data */ + VectorAdd( normal, pNormal, normal ); + luxel[ 3 ] += 1.0f; + return (*cluster); + } + + /* otherwise, unmapped luxels (*cluster == CLUSTER_UNMAPPED) will have their full attributes calculated */ + + /* get origin */ + + /* axial lightmap projection */ + if( lm->vecs != NULL ) + { + /* calculate an origin for the sample from the lightmap vectors */ + VectorCopy( lm->origin, origin ); + for( i = 0; i < 3; i++ ) + { + /* add unless it's the axis, which is taken care of later */ + if( i == lm->axisNum ) + continue; + origin[ i ] += (x * lm->vecs[ 0 ][ i ]) + (y * lm->vecs[ 1 ][ i ]); + } + + /* project the origin onto the plane */ + d = DotProduct( origin, plane ) - plane[ 3 ]; + d /= plane[ lm->axisNum ]; + origin[ lm->axisNum ] -= d; + } + + /* non axial lightmap projection (explicit xyz) */ + else + VectorCopy( dv->xyz, origin ); + + ////////////////////// + //27's test to make sure samples stay within the triangle boundaries + //1) Test the sample origin to see if it lays on the wrong side of any edge (x/y) + //2) if it does, nudge it onto the correct side. + + if (worldverts!=NULL && lightmapTriangleCheck) + { + for (j=0;j<3;j++) + { + VectorCopy(worldverts[j],cverts[j]); + } + PlaneFromPoints(hostplane,cverts[0],cverts[1],cverts[2]); + + for (j=0;j<3;j++) + { + for (i=0;i<3;i++) + { + //build plane using 2 edges and a normal + next=(i+1)%3; + + VectorCopy(cverts[next],temp); + VectorAdd(temp,hostplane,temp); + PlaneFromPoints(sideplane,cverts[i],cverts[ next ], temp); + + //planetest sample point + e=DotProduct(origin,sideplane); + e=e-sideplane[3]; + if (e>0) + { + //we're bad. + //VectorClear(origin); + //Move the sample point back inside triangle bounds + origin[0]-=sideplane[0]*(e+1); + origin[1]-=sideplane[1]*(e+1); + origin[2]-=sideplane[2]*(e+1); +#ifdef DEBUG_27_1 + VectorClear(origin); +#endif + } + } + } + } + + //////////////////////// + + /* planar surfaces have precalculated lightmap vectors for nudging */ + if( lm->plane != NULL ) + { + VectorCopy( lm->vecs[ 0 ], vecs[ 0 ] ); + VectorCopy( lm->vecs[ 1 ], vecs[ 1 ] ); + VectorCopy( lm->plane, vecs[ 2 ] ); + } + + /* non-planar surfaces must calculate them */ + else + { + if( plane != NULL ) + VectorCopy( plane, vecs[ 2 ] ); + else + VectorCopy( dv->normal, vecs[ 2 ] ); + MakeNormalVectors( vecs[ 2 ], vecs[ 0 ], vecs[ 1 ] ); + } + + /* push the origin off the surface a bit */ + if( si != NULL ) + lightmapSampleOffset = si->lightmapSampleOffset; + else + lightmapSampleOffset = DEFAULT_LIGHTMAP_SAMPLE_OFFSET; + if( lm->axisNum < 0 ) + VectorMA( origin, lightmapSampleOffset, vecs[ 2 ], origin ); + else if( vecs[ 2 ][ lm->axisNum ] < 0.0f ) + origin[ lm->axisNum ] -= lightmapSampleOffset; + else + origin[ lm->axisNum ] += lightmapSampleOffset; + + VectorCopy(origin,origintwo); + if(lightmapExtraVisClusterNudge) + { + origintwo[0]+=vecs[2][0]; + origintwo[1]+=vecs[2][1]; + origintwo[2]+=vecs[2][2]; + } + + /* get cluster */ + pointCluster = ClusterForPointExtFilter( origintwo, LUXEL_EPSILON, numClusters, clusters ); + + /* another retarded hack, storing nudge count in luxel[ 1 ] */ + luxel[ 1 ] = 0.0f; + + /* point in solid? (except in dark mode) */ + if( pointCluster < 0 && dark == qfalse ) + { + /* nudge the the location around */ + nudge = nudges[ 0 ]; + while( nudge[ 0 ] > BOGUS_NUDGE && pointCluster < 0 ) + { + /* nudge the vector around a bit */ + for( i = 0; i < 3; i++ ) + { + /* set nudged point*/ + nudged[ i ] = origintwo[ i ] + (nudge[ 0 ] * vecs[ 0 ][ i ]) + (nudge[ 1 ] * vecs[ 1 ][ i ]); + } + nudge += 2; + + /* get pvs cluster */ + pointCluster = ClusterForPointExtFilter( nudged, LUXEL_EPSILON, numClusters, clusters ); //% + 0.625 ); + if( pointCluster >= 0 ) + VectorCopy( nudged, origin ); + luxel[ 1 ] += 1.0f; + } + } + + /* as a last resort, if still in solid, try drawvert origin offset by normal (except in dark mode) */ + if( pointCluster < 0 && si != NULL && dark == qfalse ) + { + VectorMA( dv->xyz, lightmapSampleOffset, dv->normal, nudged ); + pointCluster = ClusterForPointExtFilter( nudged, LUXEL_EPSILON, numClusters, clusters ); + if( pointCluster >= 0 ) + VectorCopy( nudged, origin ); + luxel[ 1 ] += 1.0f; + } + + /* valid? */ + if( pointCluster < 0 ) + { + (*cluster) = CLUSTER_OCCLUDED; + VectorClear( origin ); + VectorClear( normal ); + numLuxelsOccluded++; + return (*cluster); + } + + /* debug code */ + //% Sys_Printf( "%f %f %f\n", origin[ 0 ], origin[ 1 ], origin[ 2 ] ); + + /* do bumpmap calculations */ + if( stv ) + PerturbNormal( dv, si, pNormal, stv, ttv ); + else + VectorCopy( dv->normal, pNormal ); + + /* store the cluster and normal */ + (*cluster) = pointCluster; + VectorCopy( pNormal, normal ); + + /* store explicit mapping pass and implicit mapping pass */ + luxel[ 0 ] = pass; + luxel[ 3 ] = 1.0f; + + /* add to count */ + numLuxelsMapped++; + + /* return ok */ + return (*cluster); +} + + + +/* +MapTriangle_r() +recursively subdivides a triangle until its edges are shorter +than the distance between two luxels (thanks jc :) +*/ + +static void MapTriangle_r( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 3 ], vec4_t plane, vec3_t stv[ 3 ], vec3_t ttv[ 3 ], vec3_t worldverts[ 3 ] ) +{ + bspDrawVert_t mid, *dv2[ 3 ]; + int max; + + + /* map the vertexes */ + #if 0 + MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv ); + MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv ); + MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv ); + #endif + + /* subdivide calc */ + { + int i; + float *a, *b, dx, dy, dist, maxDist; + + + /* find the longest edge and split it */ + max = -1; + maxDist = 0; + for( i = 0; i < 3; i++ ) + { + /* get verts */ + a = dv[ i ]->lightmap[ 0 ]; + b = dv[ (i + 1) % 3 ]->lightmap[ 0 ]; + + /* get dists */ + dx = a[ 0 ] - b[ 0 ]; + dy = a[ 1 ] - b[ 1 ]; + dist = (dx * dx) + (dy * dy); //% sqrt( (dx * dx) + (dy * dy) ); + + /* longer? */ + if( dist > maxDist ) + { + maxDist = dist; + max = i; + } + } + + /* try to early out */ + if( max < 0 || maxDist <= subdivideThreshold ) /* ydnar: was i < 0 instead of max < 0 (?) */ + return; + } + + /* split the longest edge and map it */ + LerpDrawVert( dv[ max ], dv[ (max + 1) % 3 ], &mid ); + MapSingleLuxel( lm, info, &mid, plane, 1, stv, ttv, worldverts ); + + /* push the point up a little bit to account for fp creep (fixme: revisit this) */ + //% VectorMA( mid.xyz, 2.0f, mid.normal, mid.xyz ); + + /* recurse to first triangle */ + VectorCopy( dv, dv2 ); + dv2[ max ] = ∣ + MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts ); + + /* recurse to second triangle */ + VectorCopy( dv, dv2 ); + dv2[ (max + 1) % 3 ] = ∣ + MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts ); +} + + + +/* +MapTriangle() +seed function for MapTriangle_r() +requires a cw ordered triangle +*/ + +static qboolean MapTriangle( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 3 ], qboolean mapNonAxial ) +{ + int i; + vec4_t plane; + vec3_t *stv, *ttv, stvStatic[ 3 ], ttvStatic[ 3 ]; + vec3_t worldverts[ 3 ]; + + + /* get plane if possible */ + if( lm->plane != NULL ) + { + VectorCopy( lm->plane, plane ); + plane[ 3 ] = lm->plane[ 3 ]; + } + + /* otherwise make one from the points */ + else if( PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) == qfalse ) + return qfalse; + + /* check to see if we need to calculate texture->world tangent vectors */ + if( info->si->normalImage != NULL && CalcTangentVectors( 3, dv, stvStatic, ttvStatic ) ) + { + stv = stvStatic; + ttv = ttvStatic; + } + else + { + stv = NULL; + ttv = NULL; + } + + VectorCopy( dv[ 0 ]->xyz, worldverts[ 0 ] ); + VectorCopy( dv[ 1 ]->xyz, worldverts[ 1 ] ); + VectorCopy( dv[ 2 ]->xyz, worldverts[ 2 ] ); + + /* map the vertexes */ + MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv, worldverts ); + MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv, worldverts ); + MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv, worldverts ); + + /* 2002-11-20: prefer axial triangle edges */ + if( mapNonAxial ) + { + /* subdivide the triangle */ + MapTriangle_r( lm, info, dv, plane, stv, ttv, worldverts ); + return qtrue; + } + + for( i = 0; i < 3; i++ ) + { + float *a, *b; + bspDrawVert_t *dv2[ 3 ]; + + + /* get verts */ + a = dv[ i ]->lightmap[ 0 ]; + b = dv[ (i + 1) % 3 ]->lightmap[ 0 ]; + + /* make degenerate triangles for mapping edges */ + if( fabs( a[ 0 ] - b[ 0 ] ) < 0.01f || fabs( a[ 1 ] - b[ 1 ] ) < 0.01f ) + { + dv2[ 0 ] = dv[ i ]; + dv2[ 1 ] = dv[ (i + 1) % 3 ]; + dv2[ 2 ] = dv[ (i + 1) % 3 ]; + + /* map the degenerate triangle */ + MapTriangle_r( lm, info, dv2, plane, stv, ttv, worldverts ); + } + } + + return qtrue; +} + + + +/* +MapQuad_r() +recursively subdivides a quad until its edges are shorter +than the distance between two luxels +*/ + +static void MapQuad_r( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 4 ], vec4_t plane, vec3_t stv[ 4 ], vec3_t ttv[ 4 ] ) +{ + bspDrawVert_t mid[ 2 ], *dv2[ 4 ]; + int max; + + + /* subdivide calc */ + { + int i; + float *a, *b, dx, dy, dist, maxDist; + + + /* find the longest edge and split it */ + max = -1; + maxDist = 0; + for( i = 0; i < 4; i++ ) + { + /* get verts */ + a = dv[ i ]->lightmap[ 0 ]; + b = dv[ (i + 1) % 4 ]->lightmap[ 0 ]; + + /* get dists */ + dx = a[ 0 ] - b[ 0 ]; + dy = a[ 1 ] - b[ 1 ]; + dist = (dx * dx) + (dy * dy); //% sqrt( (dx * dx) + (dy * dy) ); + + /* longer? */ + if( dist > maxDist ) + { + maxDist = dist; + max = i; + } + } + + /* try to early out */ + if( max < 0 || maxDist <= subdivideThreshold ) + return; + } + + /* we only care about even/odd edges */ + max &= 1; + + /* split the longest edges */ + LerpDrawVert( dv[ max ], dv[ (max + 1) % 4 ], &mid[ 0 ] ); + LerpDrawVert( dv[ max + 2 ], dv[ (max + 3) % 4 ], &mid[ 1 ] ); + + /* map the vertexes */ + MapSingleLuxel( lm, info, &mid[ 0 ], plane, 1, stv, ttv, NULL ); + MapSingleLuxel( lm, info, &mid[ 1 ], plane, 1, stv, ttv, NULL ); + + /* 0 and 2 */ + if( max == 0 ) + { + /* recurse to first quad */ + dv2[ 0 ] = dv[ 0 ]; + dv2[ 1 ] = &mid[ 0 ]; + dv2[ 2 ] = &mid[ 1 ]; + dv2[ 3 ] = dv[ 3 ]; + MapQuad_r( lm, info, dv2, plane, stv, ttv ); + + /* recurse to second quad */ + dv2[ 0 ] = &mid[ 0 ]; + dv2[ 1 ] = dv[ 1 ]; + dv2[ 2 ] = dv[ 2 ]; + dv2[ 3 ] = &mid[ 1 ]; + MapQuad_r( lm, info, dv2, plane, stv, ttv ); + } + + /* 1 and 3 */ + else + { + /* recurse to first quad */ + dv2[ 0 ] = dv[ 0 ]; + dv2[ 1 ] = dv[ 1 ]; + dv2[ 2 ] = &mid[ 0 ]; + dv2[ 3 ] = &mid[ 1 ]; + MapQuad_r( lm, info, dv2, plane, stv, ttv ); + + /* recurse to second quad */ + dv2[ 0 ] = &mid[ 1 ]; + dv2[ 1 ] = &mid[ 0 ]; + dv2[ 2 ] = dv[ 2 ]; + dv2[ 3 ] = dv[ 3 ]; + MapQuad_r( lm, info, dv2, plane, stv, ttv ); + } +} + + + +/* +MapQuad() +seed function for MapQuad_r() +requires a cw ordered triangle quad +*/ + +#define QUAD_PLANAR_EPSILON 0.5f + +static qboolean MapQuad( rawLightmap_t *lm, surfaceInfo_t *info, bspDrawVert_t *dv[ 4 ] ) +{ + float dist; + vec4_t plane; + vec3_t *stv, *ttv, stvStatic[ 4 ], ttvStatic[ 4 ]; + + + /* get plane if possible */ + if( lm->plane != NULL ) + { + VectorCopy( lm->plane, plane ); + plane[ 3 ] = lm->plane[ 3 ]; + } + + /* otherwise make one from the points */ + else if( PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz ) == qfalse ) + return qfalse; + + /* 4th point must fall on the plane */ + dist = DotProduct( plane, dv[ 3 ]->xyz ) - plane[ 3 ]; + if( fabs( dist ) > QUAD_PLANAR_EPSILON ) + return qfalse; + + /* check to see if we need to calculate texture->world tangent vectors */ + if( info->si->normalImage != NULL && CalcTangentVectors( 4, dv, stvStatic, ttvStatic ) ) + { + stv = stvStatic; + ttv = ttvStatic; + } + else + { + stv = NULL; + ttv = NULL; + } + + /* map the vertexes */ + MapSingleLuxel( lm, info, dv[ 0 ], plane, 1, stv, ttv, NULL ); + MapSingleLuxel( lm, info, dv[ 1 ], plane, 1, stv, ttv, NULL ); + MapSingleLuxel( lm, info, dv[ 2 ], plane, 1, stv, ttv, NULL ); + MapSingleLuxel( lm, info, dv[ 3 ], plane, 1, stv, ttv, NULL ); + + /* subdivide the quad */ + MapQuad_r( lm, info, dv, plane, stv, ttv ); + return qtrue; +} + + + +/* +MapRawLightmap() +maps the locations, normals, and pvs clusters for a raw lightmap +*/ + +#define VectorDivide( in, d, out ) VectorScale( in, (1.0f / (d)), out ) //% (out)[ 0 ] = (in)[ 0 ] / (d), (out)[ 1 ] = (in)[ 1 ] / (d), (out)[ 2 ] = (in)[ 2 ] / (d) + +void MapRawLightmap( int rawLightmapNum ) +{ + int n, num, i, x, y, sx, sy, pw[ 5 ], r, *cluster, mapNonAxial; + float *luxel, *origin, *normal, samples, radius, pass; + rawLightmap_t *lm; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + mesh_t src, *subdivided, *mesh; + bspDrawVert_t *verts, *dv[ 4 ], fake; + + + /* bail if this number exceeds the number of raw lightmaps */ + if( rawLightmapNum >= numRawLightmaps ) + return; + + /* get lightmap */ + lm = &rawLightmaps[ rawLightmapNum ]; + + /* ----------------------------------------------------------------- + map referenced surfaces onto the raw lightmap + ----------------------------------------------------------------- */ + + /* walk the list of surfaces on this raw lightmap */ + for( n = 0; n < lm->numLightSurfaces; n++ ) + { + /* with > 1 surface per raw lightmap, clear occluded */ + if( n > 0 ) + { + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + if( *cluster < 0 ) + *cluster = CLUSTER_UNMAPPED; + } + } + } + + /* get surface */ + num = lightSurfaces[ lm->firstLightSurface + n ]; + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* bail if no lightmap to calculate */ + if( info->lm != lm ) + { + Sys_Printf( "!" ); + continue; + } + + /* map the surface onto the lightmap origin/cluster/normal buffers */ + switch( ds->surfaceType ) + { + case MST_PLANAR: + /* get verts */ + verts = yDrawVerts + ds->firstVert; + + /* map the triangles */ + for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ ) + { + for( i = 0; i < ds->numIndexes; i += 3 ) + { + dv[ 0 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i ] ]; + dv[ 1 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 1 ] ]; + dv[ 2 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 2 ] ]; + MapTriangle( lm, info, dv, mapNonAxial ); + } + } + break; + + case MST_PATCH: + /* make a mesh from the drawsurf */ + src.width = ds->patchWidth; + src.height = ds->patchHeight; + src.verts = &yDrawVerts[ ds->firstVert ]; + //% subdivided = SubdivideMesh( src, 8, 512 ); + subdivided = SubdivideMesh2( src, info->patchIterations ); + + /* fit it to the curve and remove colinear verts on rows/columns */ + PutMeshOnCurve( *subdivided ); + mesh = RemoveLinearMeshColumnsRows( subdivided ); + FreeMesh( subdivided ); + + /* get verts */ + verts = mesh->verts; + + /* debug code */ + #if 0 + if( lm->plane ) + { + Sys_Printf( "Planar patch: [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f] [%1.3f %1.3f %1.3f]\n", + lm->plane[ 0 ], lm->plane[ 1 ], lm->plane[ 2 ], + lm->vecs[ 0 ][ 0 ], lm->vecs[ 0 ][ 1 ], lm->vecs[ 0 ][ 2 ], + lm->vecs[ 1 ][ 0 ], lm->vecs[ 1 ][ 1 ], lm->vecs[ 1 ][ 2 ] ); + } + #endif + + /* map the mesh quads */ + #if 0 + + for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ ) + { + for( y = 0; y < (mesh->height - 1); y++ ) + { + for( x = 0; x < (mesh->width - 1); x++ ) + { + /* set indexes */ + pw[ 0 ] = x + (y * mesh->width); + pw[ 1 ] = x + ((y + 1) * mesh->width); + pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); + pw[ 3 ] = x + 1 + (y * mesh->width); + pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ + + /* set radix */ + r = (x + y) & 1; + + /* get drawverts and map first triangle */ + dv[ 0 ] = &verts[ pw[ r + 0 ] ]; + dv[ 1 ] = &verts[ pw[ r + 1 ] ]; + dv[ 2 ] = &verts[ pw[ r + 2 ] ]; + MapTriangle( lm, info, dv, mapNonAxial ); + + /* get drawverts and map second triangle */ + dv[ 0 ] = &verts[ pw[ r + 0 ] ]; + dv[ 1 ] = &verts[ pw[ r + 2 ] ]; + dv[ 2 ] = &verts[ pw[ r + 3 ] ]; + MapTriangle( lm, info, dv, mapNonAxial ); + } + } + } + + #else + + for( y = 0; y < (mesh->height - 1); y++ ) + { + for( x = 0; x < (mesh->width - 1); x++ ) + { + /* set indexes */ + pw[ 0 ] = x + (y * mesh->width); + pw[ 1 ] = x + ((y + 1) * mesh->width); + pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); + pw[ 3 ] = x + 1 + (y * mesh->width); + pw[ 4 ] = pw[ 0 ]; + + /* set radix */ + r = (x + y) & 1; + + /* attempt to map quad first */ + dv[ 0 ] = &verts[ pw[ r + 0 ] ]; + dv[ 1 ] = &verts[ pw[ r + 1 ] ]; + dv[ 2 ] = &verts[ pw[ r + 2 ] ]; + dv[ 3 ] = &verts[ pw[ r + 3 ] ]; + if( MapQuad( lm, info, dv ) ) + continue; + + for( mapNonAxial = 0; mapNonAxial < 2; mapNonAxial++ ) + { + /* get drawverts and map first triangle */ + dv[ 1 ] = &verts[ pw[ r + 1 ] ]; + dv[ 2 ] = &verts[ pw[ r + 2 ] ]; + MapTriangle( lm, info, dv, mapNonAxial ); + + /* get drawverts and map second triangle */ + dv[ 1 ] = &verts[ pw[ r + 2 ] ]; + dv[ 2 ] = &verts[ pw[ r + 3 ] ]; + MapTriangle( lm, info, dv, mapNonAxial ); + } + } + } + + #endif + + /* free the mesh */ + FreeMesh( mesh ); + break; + + default: + break; + } + } + + /* ----------------------------------------------------------------- + average and clean up luxel normals + ----------------------------------------------------------------- */ + + /* walk the luxels */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + luxel = SUPER_LUXEL( 0, x, y ); + normal = SUPER_NORMAL( x, y ); + cluster = SUPER_CLUSTER( x, y ); + + /* only look at mapped luxels */ + if( *cluster < 0 ) + continue; + + /* the normal data could be the sum of multiple samples */ + if( luxel[ 3 ] > 1.0f ) + VectorNormalize( normal, normal ); + + /* mark this luxel as having only one normal */ + luxel[ 3 ] = 1.0f; + } + } + + /* non-planar surfaces stop here */ + if( lm->plane == NULL ) + return; + + /* ----------------------------------------------------------------- + map occluded or unuxed luxels + ----------------------------------------------------------------- */ + + /* walk the luxels */ + radius = floor( superSample / 2 ); + radius = radius > 0 ? radius : 1.0f; + radius += 1.0f; + for( pass = 2.0f; pass <= radius; pass += 1.0f ) + { + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + luxel = SUPER_LUXEL( 0, x, y ); + normal = SUPER_NORMAL( x, y ); + cluster = SUPER_CLUSTER( x, y ); + + /* only look at unmapped luxels */ + if( *cluster != CLUSTER_UNMAPPED ) + continue; + + /* divine a normal and origin from neighboring luxels */ + VectorClear( fake.xyz ); + VectorClear( fake.normal ); + fake.lightmap[ 0 ][ 0 ] = x; //% 0.0001 + x; + fake.lightmap[ 0 ][ 1 ] = y; //% 0.0001 + y; + samples = 0.0f; + for( sy = (y - 1); sy <= (y + 1); sy++ ) + { + if( sy < 0 || sy >= lm->sh ) + continue; + + for( sx = (x - 1); sx <= (x + 1); sx++ ) + { + if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) + continue; + + /* get neighboring luxel */ + luxel = SUPER_LUXEL( 0, sx, sy ); + origin = SUPER_ORIGIN( sx, sy ); + normal = SUPER_NORMAL( sx, sy ); + cluster = SUPER_CLUSTER( sx, sy ); + + /* only consider luxels mapped in previous passes */ + if( *cluster < 0 || luxel[ 0 ] >= pass ) + continue; + + /* add its distinctiveness to our own */ + VectorAdd( fake.xyz, origin, fake.xyz ); + VectorAdd( fake.normal, normal, fake.normal ); + samples += luxel[ 3 ]; + } + } + + /* any samples? */ + if( samples == 0.0f ) + continue; + + /* average */ + VectorDivide( fake.xyz, samples, fake.xyz ); + //% VectorDivide( fake.normal, samples, fake.normal ); + if( VectorNormalize( fake.normal, fake.normal ) == 0.0f ) + continue; + + /* map the fake vert */ + MapSingleLuxel( lm, NULL, &fake, lm->plane, pass, NULL, NULL, NULL ); + } + } + } + + /* ----------------------------------------------------------------- + average and clean up luxel normals + ----------------------------------------------------------------- */ + + /* walk the luxels */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + luxel = SUPER_LUXEL( 0, x, y ); + normal = SUPER_NORMAL( x, y ); + cluster = SUPER_CLUSTER( x, y ); + + /* only look at mapped luxels */ + if( *cluster < 0 ) + continue; + + /* the normal data could be the sum of multiple samples */ + if( luxel[ 3 ] > 1.0f ) + VectorNormalize( normal, normal ); + + /* mark this luxel as having only one normal */ + luxel[ 3 ] = 1.0f; + } + } + + /* debug code */ + #if 0 + Sys_Printf( "\n" ); + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + vec3_t mins, maxs; + + + cluster = SUPER_CLUSTER( x, y ); + origin = SUPER_ORIGIN( x, y ); + normal = SUPER_NORMAL( x, y ); + luxel = SUPER_LUXEL( x, y ); + + if( *cluster < 0 ) + continue; + + /* check if within the bounding boxes of all surfaces referenced */ + ClearBounds( mins, maxs ); + for( n = 0; n < lm->numLightSurfaces; n++ ) + { + int TOL; + info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + n ] ]; + TOL = info->sampleSize + 2; + AddPointToBounds( info->mins, mins, maxs ); + AddPointToBounds( info->maxs, mins, maxs ); + if( origin[ 0 ] > (info->mins[ 0 ] - TOL) && origin[ 0 ] < (info->maxs[ 0 ] + TOL) && + origin[ 1 ] > (info->mins[ 1 ] - TOL) && origin[ 1 ] < (info->maxs[ 1 ] + TOL) && + origin[ 2 ] > (info->mins[ 2 ] - TOL) && origin[ 2 ] < (info->maxs[ 2 ] + TOL) ) + break; + } + + /* inside? */ + if( n < lm->numLightSurfaces ) + continue; + + /* report bogus origin */ + Sys_Printf( "%6d [%2d,%2d] (%4d): XYZ(%+4.1f %+4.1f %+4.1f) LO(%+4.1f %+4.1f %+4.1f) HI(%+4.1f %+4.1f %+4.1f) <%3.0f>\n", + rawLightmapNum, x, y, *cluster, + origin[ 0 ], origin[ 1 ], origin[ 2 ], + mins[ 0 ], mins[ 1 ], mins[ 2 ], + maxs[ 0 ], maxs[ 1 ], maxs[ 2 ], + luxel[ 3 ] ); + } + } + #endif +} + + + +/* +SetupDirt() +sets up dirtmap (ambient occlusion) +*/ + +#define DIRT_CONE_ANGLE 88 /* degrees */ +#define DIRT_NUM_ANGLE_STEPS 16 +#define DIRT_NUM_ELEVATION_STEPS 3 +#define DIRT_NUM_VECTORS (DIRT_NUM_ANGLE_STEPS * DIRT_NUM_ELEVATION_STEPS) + +static vec3_t dirtVectors[ DIRT_NUM_VECTORS ]; +static int numDirtVectors = 0; + +void SetupDirt( void ) +{ + int i, j; + float angle, elevation, angleStep, elevationStep; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- SetupDirt ---\n" ); + + /* calculate angular steps */ + angleStep = DEG2RAD( 360.0f / DIRT_NUM_ANGLE_STEPS ); + elevationStep = DEG2RAD( DIRT_CONE_ANGLE / DIRT_NUM_ELEVATION_STEPS ); + + /* iterate angle */ + angle = 0.0f; + for( i = 0, angle = 0.0f; i < DIRT_NUM_ANGLE_STEPS; i++, angle += angleStep ) + { + /* iterate elevation */ + for( j = 0, elevation = elevationStep * 0.5f; j < DIRT_NUM_ELEVATION_STEPS; j++, elevation += elevationStep ) + { + dirtVectors[ numDirtVectors ][ 0 ] = sin( elevation ) * cos( angle ); + dirtVectors[ numDirtVectors ][ 1 ] = sin( elevation ) * sin( angle ); + dirtVectors[ numDirtVectors ][ 2 ] = cos( elevation ); + numDirtVectors++; + } + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d dirtmap vectors\n", numDirtVectors ); +} + + +/* +DirtForSample() +calculates dirt value for a given sample +*/ + +float DirtForSample( trace_t *trace ) +{ + int i; + float gatherDirt, outDirt, angle, elevation, ooDepth; + vec3_t normal, worldUp, myUp, myRt, temp, direction, displacement; + + + /* dummy check */ + if( !dirty ) + return 1.0f; + if( trace == NULL || trace->cluster < 0 ) + return 0.0f; + + /* setup */ + gatherDirt = 0.0f; + ooDepth = 1.0f / dirtDepth; + VectorCopy( trace->normal, normal ); + + /* check if the normal is aligned to the world-up */ + if( normal[ 0 ] == 0.0f && normal[ 1 ] == 0.0f && ( normal[ 2 ] == 1.0f || normal[ 2 ] == -1.0f ) ) + { + if( normal[ 2 ] == 1.0f ) + { + VectorSet( myRt, 1.0f, 0.0f, 0.0f ); + VectorSet( myUp, 0.0f, 1.0f, 0.0f ); + } + else if( normal[ 2 ] == -1.0f ) + { + VectorSet( myRt, -1.0f, 0.0f, 0.0f ); + VectorSet( myUp, 0.0f, 1.0f, 0.0f ); + } + } + else + { + VectorSet( worldUp, 0.0f, 0.0f, 1.0f ); + CrossProduct( normal, worldUp, myRt ); + VectorNormalize( myRt, myRt ); + CrossProduct( myRt, normal, myUp ); + VectorNormalize( myUp, myUp ); + } + + /* 1 = random mode, 0 (well everything else) = non-random mode */ + if( dirtMode == 1 ) + { + /* iterate */ + for( i = 0; i < numDirtVectors; i++ ) + { + /* get random vector */ + angle = Random() * DEG2RAD( 360.0f ); + elevation = Random() * DEG2RAD( DIRT_CONE_ANGLE ); + temp[ 0 ] = cos( angle ) * sin( elevation ); + temp[ 1 ] = sin( angle ) * sin( elevation ); + temp[ 2 ] = cos( elevation ); + + /* transform into tangent space */ + direction[ 0 ] = myRt[ 0 ] * temp[ 0 ] + myUp[ 0 ] * temp[ 1 ] + normal[ 0 ] * temp[ 2 ]; + direction[ 1 ] = myRt[ 1 ] * temp[ 0 ] + myUp[ 1 ] * temp[ 1 ] + normal[ 1 ] * temp[ 2 ]; + direction[ 2 ] = myRt[ 2 ] * temp[ 0 ] + myUp[ 2 ] * temp[ 1 ] + normal[ 2 ] * temp[ 2 ]; + + /* set endpoint */ + VectorMA( trace->origin, dirtDepth, direction, trace->end ); + SetupTrace( trace ); + + /* trace */ + TraceLine( trace ); + if( trace->opaque && !(trace->compileFlags & C_SKY) ) + { + VectorSubtract( trace->hit, trace->origin, displacement ); + gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); + } + } + } + else + { + /* iterate through ordered vectors */ + for( i = 0; i < numDirtVectors; i++ ) + { + /* transform vector into tangent space */ + direction[ 0 ] = myRt[ 0 ] * dirtVectors[ i ][ 0 ] + myUp[ 0 ] * dirtVectors[ i ][ 1 ] + normal[ 0 ] * dirtVectors[ i ][ 2 ]; + direction[ 1 ] = myRt[ 1 ] * dirtVectors[ i ][ 0 ] + myUp[ 1 ] * dirtVectors[ i ][ 1 ] + normal[ 1 ] * dirtVectors[ i ][ 2 ]; + direction[ 2 ] = myRt[ 2 ] * dirtVectors[ i ][ 0 ] + myUp[ 2 ] * dirtVectors[ i ][ 1 ] + normal[ 2 ] * dirtVectors[ i ][ 2 ]; + + /* set endpoint */ + VectorMA( trace->origin, dirtDepth, direction, trace->end ); + SetupTrace( trace ); + + /* trace */ + TraceLine( trace ); + if( trace->opaque ) + { + VectorSubtract( trace->hit, trace->origin, displacement ); + gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); + } + } + } + + /* direct ray */ + VectorMA( trace->origin, dirtDepth, normal, trace->end ); + SetupTrace( trace ); + + /* trace */ + TraceLine( trace ); + if( trace->opaque ) + { + VectorSubtract( trace->hit, trace->origin, displacement ); + gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); + } + + /* early out */ + if( gatherDirt <= 0.0f ) + return 1.0f; + + /* apply gain (does this even do much? heh) */ + outDirt = pow( gatherDirt / (numDirtVectors + 1), dirtGain ); + if( outDirt > 1.0f ) + outDirt = 1.0f; + + /* apply scale */ + outDirt *= dirtScale; + if( outDirt > 1.0f ) + outDirt = 1.0f; + + /* return to sender */ + return 1.0f - outDirt; +} + + + +/* +DirtyRawLightmap() +calculates dirty fraction for each luxel +*/ + +void DirtyRawLightmap( int rawLightmapNum ) +{ + int i, x, y, sx, sy, *cluster; + float *origin, *normal, *dirt, *dirt2, average, samples; + rawLightmap_t *lm; + surfaceInfo_t *info; + trace_t trace; + qboolean noDirty; + + + /* bail if this number exceeds the number of raw lightmaps */ + if( rawLightmapNum >= numRawLightmaps ) + return; + + /* get lightmap */ + lm = &rawLightmaps[ rawLightmapNum ]; + + /* setup trace */ + trace.testOcclusion = qtrue; + trace.forceSunlight = qfalse; + trace.recvShadows = lm->recvShadows; + trace.numSurfaces = lm->numLightSurfaces; + trace.surfaces = &lightSurfaces[ lm->firstLightSurface ]; + trace.inhibitRadius = 0.0f; + trace.testAll = qfalse; + + /* twosided lighting (may or may not be a good idea for lightmapped stuff) */ + trace.twoSided = qfalse; + for( i = 0; i < trace.numSurfaces; i++ ) + { + /* get surface */ + info = &surfaceInfos[ trace.surfaces[ i ] ]; + + /* check twosidedness */ + if( info->si->twoSided ) + { + trace.twoSided = qtrue; + break; + } + } + + noDirty = qfalse; + for( i = 0; i < trace.numSurfaces; i++ ) + { + /* get surface */ + info = &surfaceInfos[ trace.surfaces[ i ] ]; + + /* check twosidedness */ + if( info->si->noDirty ) + { + noDirty = qtrue; + break; + } + } + + /* gather dirt */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + cluster = SUPER_CLUSTER( x, y ); + origin = SUPER_ORIGIN( x, y ); + normal = SUPER_NORMAL( x, y ); + dirt = SUPER_DIRT( x, y ); + + /* set default dirt */ + *dirt = 0.0f; + + /* only look at mapped luxels */ + if( *cluster < 0 ) + continue; + + /* don't apply dirty on this surface */ + if( noDirty ) + { + *dirt = 1.0f; + continue; + } + + /* copy to trace */ + trace.cluster = *cluster; + VectorCopy( origin, trace.origin ); + VectorCopy( normal, trace.normal ); + + /* get dirt */ + *dirt = DirtForSample( &trace ); + } + } + + /* testing no filtering */ + //% return; + + /* filter dirt */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + cluster = SUPER_CLUSTER( x, y ); + dirt = SUPER_DIRT( x, y ); + + /* filter dirt by adjacency to unmapped luxels */ + average = *dirt; + samples = 1.0f; + for( sy = (y - 1); sy <= (y + 1); sy++ ) + { + if( sy < 0 || sy >= lm->sh ) + continue; + + for( sx = (x - 1); sx <= (x + 1); sx++ ) + { + if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) + continue; + + /* get neighboring luxel */ + cluster = SUPER_CLUSTER( sx, sy ); + dirt2 = SUPER_DIRT( sx, sy ); + if( *cluster < 0 || *dirt2 <= 0.0f ) + continue; + + /* add it */ + average += *dirt2; + samples += 1.0f; + } + + /* bail */ + if( samples <= 0.0f ) + break; + } + + /* bail */ + if( samples <= 0.0f ) + continue; + + /* scale dirt */ + *dirt = average / samples; + } + } +} + + + +/* +SubmapRawLuxel() +calculates the pvs cluster, origin, normal of a sub-luxel +*/ + +static qboolean SubmapRawLuxel( rawLightmap_t *lm, int x, int y, float bx, float by, int *sampleCluster, vec3_t sampleOrigin, vec3_t sampleNormal ) +{ + int i, *cluster, *cluster2; + float *origin, *origin2, *normal; //% , *normal2; + vec3_t originVecs[ 2 ]; //% , normalVecs[ 2 ]; + + + /* calulate x vector */ + if( (x < (lm->sw - 1) && bx >= 0.0f) || (x == 0 && bx <= 0.0f) ) + { + cluster = SUPER_CLUSTER( x, y ); + origin = SUPER_ORIGIN( x, y ); + //% normal = SUPER_NORMAL( x, y ); + cluster2 = SUPER_CLUSTER( x + 1, y ); + origin2 = *cluster2 < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x + 1, y ); + //% normal2 = *cluster2 < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x + 1, y ); + } + else if( (x > 0 && bx <= 0.0f) || (x == (lm->sw - 1) && bx >= 0.0f) ) + { + cluster = SUPER_CLUSTER( x - 1, y ); + origin = *cluster < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x - 1, y ); + //% normal = *cluster < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x - 1, y ); + cluster2 = SUPER_CLUSTER( x, y ); + origin2 = SUPER_ORIGIN( x, y ); + //% normal2 = SUPER_NORMAL( x, y ); + } + else + { + Error( "Spurious lightmap S vector\n" ); + } + + VectorSubtract( origin2, origin, originVecs[ 0 ] ); + //% VectorSubtract( normal2, normal, normalVecs[ 0 ] ); + + /* calulate y vector */ + if( (y < (lm->sh - 1) && bx >= 0.0f) || (y == 0 && bx <= 0.0f) ) + { + cluster = SUPER_CLUSTER( x, y ); + origin = SUPER_ORIGIN( x, y ); + //% normal = SUPER_NORMAL( x, y ); + cluster2 = SUPER_CLUSTER( x, y + 1 ); + origin2 = *cluster2 < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x, y + 1 ); + //% normal2 = *cluster2 < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x, y + 1 ); + } + else if( (y > 0 && bx <= 0.0f) || (y == (lm->sh - 1) && bx >= 0.0f) ) + { + cluster = SUPER_CLUSTER( x, y - 1 ); + origin = *cluster < 0 ? SUPER_ORIGIN( x, y ) : SUPER_ORIGIN( x, y - 1 ); + //% normal = *cluster < 0 ? SUPER_NORMAL( x, y ) : SUPER_NORMAL( x, y - 1 ); + cluster2 = SUPER_CLUSTER( x, y ); + origin2 = SUPER_ORIGIN( x, y ); + //% normal2 = SUPER_NORMAL( x, y ); + } + else + Sys_Printf( "WARNING: Spurious lightmap T vector\n" ); + + VectorSubtract( origin2, origin, originVecs[ 1 ] ); + //% VectorSubtract( normal2, normal, normalVecs[ 1 ] ); + + /* calculate new origin */ + //% VectorMA( origin, bx, originVecs[ 0 ], sampleOrigin ); + //% VectorMA( sampleOrigin, by, originVecs[ 1 ], sampleOrigin ); + for( i = 0; i < 3; i++ ) + sampleOrigin[ i ] = sampleOrigin[ i ] + (bx * originVecs[ 0 ][ i ]) + (by * originVecs[ 1 ][ i ]); + + /* get cluster */ + *sampleCluster = ClusterForPointExtFilter( sampleOrigin, (LUXEL_EPSILON * 2), lm->numLightClusters, lm->lightClusters ); + if( *sampleCluster < 0 ) + return qfalse; + + /* calculate new normal */ + //% VectorMA( normal, bx, normalVecs[ 0 ], sampleNormal ); + //% VectorMA( sampleNormal, by, normalVecs[ 1 ], sampleNormal ); + //% if( VectorNormalize( sampleNormal, sampleNormal ) <= 0.0f ) + //% return qfalse; + normal = SUPER_NORMAL( x, y ); + VectorCopy( normal, sampleNormal ); + + /* return ok */ + return qtrue; +} + + +/* +SubsampleRawLuxel_r() +recursively subsamples a luxel until its color gradient is low enough or subsampling limit is reached +*/ + +static void SubsampleRawLuxel_r( rawLightmap_t *lm, trace_t *trace, vec3_t sampleOrigin, int x, int y, float bias, float *lightLuxel, float *lightDeluxel ) +{ + int b, samples, mapped, lighted; + int cluster[ 4 ]; + vec4_t luxel[ 4 ]; + vec3_t deluxel[ 3 ]; + vec3_t origin[ 4 ], normal[ 4 ]; + float biasDirs[ 4 ][ 2 ] = { { -1.0f, -1.0f }, { 1.0f, -1.0f }, { -1.0f, 1.0f }, { 1.0f, 1.0f } }; + vec3_t color, direction, total; + + + /* limit check */ + if( lightLuxel[ 3 ] >= lightSamples ) + return; + + /* setup */ + VectorClear( total ); + mapped = 0; + lighted = 0; + + /* make 2x2 subsample stamp */ + for( b = 0; b < 4; b++ ) + { + /* set origin */ + VectorCopy( sampleOrigin, origin[ b ] ); + + /* calculate position */ + if( !SubmapRawLuxel( lm, x, y, (bias * biasDirs[ b ][ 0 ]), (bias * biasDirs[ b ][ 1 ]), &cluster[ b ], origin[ b ], normal[ b ] ) ) + { + cluster[ b ] = -1; + continue; + } + mapped++; + + /* increment sample count */ + luxel[ b ][ 3 ] = lightLuxel[ 3 ] + 1.0f; + + /* setup trace */ + trace->cluster = *cluster; + VectorCopy( origin[ b ], trace->origin ); + VectorCopy( normal[ b ], trace->normal ); + + /* sample light */ + + LightContributionToSample( trace ); + if(trace->forceSubsampling > 1.0f) + { + /* alphashadow: we subsample as deep as we can */ + ++lighted; + ++mapped; + ++mapped; + } + + /* add to totals (fixme: make contrast function) */ + VectorCopy( trace->color, luxel[ b ] ); + if(lightDeluxel) + { + VectorCopy( trace->directionContribution, deluxel[ b ] ); + } + VectorAdd( total, trace->color, total ); + if( (luxel[ b ][ 0 ] + luxel[ b ][ 1 ] + luxel[ b ][ 2 ]) > 0.0f ) + lighted++; + } + + /* subsample further? */ + if( (lightLuxel[ 3 ] + 1.0f) < lightSamples && + (total[ 0 ] > 4.0f || total[ 1 ] > 4.0f || total[ 2 ] > 4.0f) && + lighted != 0 && lighted != mapped ) + { + for( b = 0; b < 4; b++ ) + { + if( cluster[ b ] < 0 ) + continue; + SubsampleRawLuxel_r( lm, trace, origin[ b ], x, y, (bias * 0.5f), luxel[ b ], lightDeluxel ? deluxel[ b ] : NULL ); + } + } + + /* average */ + //% VectorClear( color ); + //% samples = 0; + VectorCopy( lightLuxel, color ); + if(lightDeluxel) + { + VectorCopy( lightDeluxel, direction ); + } + samples = 1; + for( b = 0; b < 4; b++ ) + { + if( cluster[ b ] < 0 ) + continue; + VectorAdd( color, luxel[ b ], color ); + if(lightDeluxel) + { + VectorAdd( direction, deluxel[ b ], direction ); + } + samples++; + } + + /* add to luxel */ + if( samples > 0 ) + { + /* average */ + color[ 0 ] /= samples; + color[ 1 ] /= samples; + color[ 2 ] /= samples; + + /* add to color */ + VectorCopy( color, lightLuxel ); + lightLuxel[ 3 ] += 1.0f; + + if(lightDeluxel) + { + direction[ 0 ] /= samples; + direction[ 1 ] /= samples; + direction[ 2 ] /= samples; + VectorCopy( direction, lightDeluxel ); + } + } +} + +/* A mostly Gaussian-like bounded random distribution (sigma is expected standard deviation) */ +static void GaussLikeRandom(float sigma, float *x, float *y) +{ + float r; + r = Random() * 2 * Q_PI; + *x = sigma * 2.73861278752581783822 * cos(r); + *y = sigma * 2.73861278752581783822 * sin(r); + r = Random(); + r = 1 - sqrt(r); + r = 1 - sqrt(r); + *x *= r; + *y *= r; +} +static void RandomSubsampleRawLuxel( rawLightmap_t *lm, trace_t *trace, vec3_t sampleOrigin, int x, int y, float bias, float *lightLuxel, float *lightDeluxel ) +{ + int b, mapped; + int cluster; + vec3_t origin, normal; + vec3_t total, totaldirection; + float dx, dy; + + VectorClear( total ); + VectorClear( totaldirection ); + mapped = 0; + for(b = 0; b < lightSamples; ++b) + { + /* set origin */ + VectorCopy( sampleOrigin, origin ); + GaussLikeRandom(bias, &dx, &dy); + + /* calculate position */ + if( !SubmapRawLuxel( lm, x, y, dx, dy, &cluster, origin, normal ) ) + { + cluster = -1; + continue; + } + mapped++; + + trace->cluster = cluster; + VectorCopy( origin, trace->origin ); + VectorCopy( normal, trace->normal ); + + LightContributionToSample( trace ); + VectorAdd( total, trace->color, total ); + if(lightDeluxel) + { + VectorAdd( totaldirection, trace->directionContribution, totaldirection ); + } + } + + /* add to luxel */ + if( mapped > 0 ) + { + /* average */ + lightLuxel[ 0 ] = total[ 0 ] / mapped; + lightLuxel[ 1 ] = total[ 1 ] / mapped; + lightLuxel[ 2 ] = total[ 2 ] / mapped; + + if(lightDeluxel) + { + lightDeluxel[ 0 ] = totaldirection[ 0 ] / mapped; + lightDeluxel[ 1 ] = totaldirection[ 1 ] / mapped; + lightDeluxel[ 2 ] = totaldirection[ 2 ] / mapped; + } + } +} + + + +/* +IlluminateRawLightmap() +illuminates the luxels +*/ + +#define STACK_LL_SIZE (SUPER_LUXEL_SIZE * 64 * 64) +#define LIGHT_LUXEL( x, y ) (lightLuxels + ((((y) * lm->sw) + (x)) * SUPER_LUXEL_SIZE)) +#define LIGHT_DELUXEL( x, y ) (lightDeluxels + ((((y) * lm->sw) + (x)) * SUPER_DELUXEL_SIZE)) + +void IlluminateRawLightmap( int rawLightmapNum ) +{ + int i, t, x, y, sx, sy, size, luxelFilterRadius, lightmapNum; + int *cluster, *cluster2, mapped, lighted, totalLighted; + size_t llSize, ldSize; + rawLightmap_t *lm; + surfaceInfo_t *info; + qboolean filterColor, filterDir; + float brightness; + float *origin, *normal, *dirt, *luxel, *luxel2, *deluxel, *deluxel2; + unsigned char *flag; + float *lightLuxels, *lightDeluxels, *lightLuxel, *lightDeluxel, samples, filterRadius, weight; + vec3_t color, direction, averageColor, averageDir, total, temp, temp2; + float tests[ 4 ][ 2 ] = { { 0.0f, 0 }, { 1, 0 }, { 0, 1 }, { 1, 1 } }; + trace_t trace; + float stackLightLuxels[ STACK_LL_SIZE ]; + + + /* bail if this number exceeds the number of raw lightmaps */ + if( rawLightmapNum >= numRawLightmaps ) + return; + + /* get lightmap */ + lm = &rawLightmaps[ rawLightmapNum ]; + + /* setup trace */ + trace.testOcclusion = !noTrace; + trace.forceSunlight = qfalse; + trace.recvShadows = lm->recvShadows; + trace.numSurfaces = lm->numLightSurfaces; + trace.surfaces = &lightSurfaces[ lm->firstLightSurface ]; + trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; + + /* twosided lighting (may or may not be a good idea for lightmapped stuff) */ + trace.twoSided = qfalse; + for( i = 0; i < trace.numSurfaces; i++ ) + { + /* get surface */ + info = &surfaceInfos[ trace.surfaces[ i ] ]; + + /* check twosidedness */ + if( info->si->twoSided ) + { + trace.twoSided = qtrue; + break; + } + } + + /* create a culled light list for this raw lightmap */ + CreateTraceLightsForBounds( lm->mins, lm->maxs, lm->plane, lm->numLightClusters, lm->lightClusters, LIGHT_SURFACES, &trace ); + + /* ----------------------------------------------------------------- + fill pass + ----------------------------------------------------------------- */ + + /* set counts */ + numLuxelsIlluminated += (lm->sw * lm->sh); + + /* test debugging state */ + if( debugSurfaces || debugAxis || debugCluster || debugOrigin || dirtDebug || normalmap ) + { + /* debug fill the luxels */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + + /* only fill mapped luxels */ + if( *cluster < 0 ) + continue; + + /* get particulars */ + luxel = SUPER_LUXEL( 0, x, y ); + origin = SUPER_ORIGIN( x, y ); + normal = SUPER_NORMAL( x, y ); + + /* color the luxel with raw lightmap num? */ + if( debugSurfaces ) + VectorCopy( debugColors[ rawLightmapNum % 12 ], luxel ); + + /* color the luxel with lightmap axis? */ + else if( debugAxis ) + { + luxel[ 0 ] = (lm->axis[ 0 ] + 1.0f) * 127.5f; + luxel[ 1 ] = (lm->axis[ 1 ] + 1.0f) * 127.5f; + luxel[ 2 ] = (lm->axis[ 2 ] + 1.0f) * 127.5f; + } + + /* color the luxel with luxel cluster? */ + else if( debugCluster ) + VectorCopy( debugColors[ *cluster % 12 ], luxel ); + + /* color the luxel with luxel origin? */ + else if( debugOrigin ) + { + VectorSubtract( lm->maxs, lm->mins, temp ); + VectorScale( temp, (1.0f / 255.0f), temp ); + VectorSubtract( origin, lm->mins, temp2 ); + luxel[ 0 ] = lm->mins[ 0 ] + (temp[ 0 ] * temp2[ 0 ]); + luxel[ 1 ] = lm->mins[ 1 ] + (temp[ 1 ] * temp2[ 1 ]); + luxel[ 2 ] = lm->mins[ 2 ] + (temp[ 2 ] * temp2[ 2 ]); + } + + /* color the luxel with the normal */ + else if( normalmap ) + { + luxel[ 0 ] = (normal[ 0 ] + 1.0f) * 127.5f; + luxel[ 1 ] = (normal[ 1 ] + 1.0f) * 127.5f; + luxel[ 2 ] = (normal[ 2 ] + 1.0f) * 127.5f; + } + + /* otherwise clear it */ + else + VectorClear( luxel ); + + /* add to counts */ + luxel[ 3 ] = 1.0f; + } + } + } + else + { + /* allocate temporary per-light luxel storage */ + llSize = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); + ldSize = lm->sw * lm->sh * SUPER_DELUXEL_SIZE * sizeof( float ); + if( llSize <= (STACK_LL_SIZE * sizeof( float )) ) + lightLuxels = stackLightLuxels; + else + lightLuxels = safe_malloc( llSize ); + if(deluxemap) + lightDeluxels = safe_malloc( ldSize ); + else + lightDeluxels = NULL; + + /* clear luxels */ + //% memset( lm->superLuxels[ 0 ], 0, llSize ); + + /* set ambient color */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + luxel = SUPER_LUXEL( 0, x, y ); + normal = SUPER_NORMAL( x, y ); + deluxel = SUPER_DELUXEL( x, y ); + + /* blacken unmapped clusters */ + if( *cluster < 0 ) + VectorClear( luxel ); + + /* set ambient */ + else + { + VectorCopy( ambientColor, luxel ); + if( deluxemap ) + { + brightness = RGBTOGRAY( ambientColor ) * ( 1.0f/255.0f ); + + // use AT LEAST this amount of contribution from ambient for the deluxemap, fixes points that receive ZERO light + if(brightness < 0.00390625f) + brightness = 0.00390625f; + + VectorScale( normal, brightness, deluxel ); + } + luxel[ 3 ] = 1.0f; + } + } + } + + /* clear styled lightmaps */ + size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); + for( lightmapNum = 1; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + if( lm->superLuxels[ lightmapNum ] != NULL ) + memset( lm->superLuxels[ lightmapNum ], 0, size ); + } + + /* debugging code */ + //% if( trace.numLights <= 0 ) + //% Sys_Printf( "Lightmap %9d: 0 lights, axis: %.2f, %.2f, %.2f\n", rawLightmapNum, lm->axis[ 0 ], lm->axis[ 1 ], lm->axis[ 2 ] ); + + /* walk light list */ + for( i = 0; i < trace.numLights; i++ ) + { + /* setup trace */ + trace.light = trace.lights[ i ]; + + /* style check */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + if( lm->styles[ lightmapNum ] == trace.light->style || + lm->styles[ lightmapNum ] == LS_NONE ) + break; + } + + /* max of MAX_LIGHTMAPS (4) styles allowed to hit a surface/lightmap */ + if( lightmapNum >= MAX_LIGHTMAPS ) + { + Sys_Printf( "WARNING: Hit per-surface style limit (%d)\n", MAX_LIGHTMAPS ); + continue; + } + + /* setup */ + memset( lightLuxels, 0, llSize ); + if(deluxemap) + memset( lightDeluxels, 0, ldSize ); + totalLighted = 0; + + /* determine filter radius */ + filterRadius = lm->filterRadius > trace.light->filterRadius + ? lm->filterRadius + : trace.light->filterRadius; + if( filterRadius < 0.0f ) + filterRadius = 0.0f; + + /* set luxel filter radius */ + luxelFilterRadius = superSample * filterRadius / lm->sampleSize; + if( luxelFilterRadius == 0 && (filterRadius > 0.0f || filter) ) + luxelFilterRadius = 1; + + /* allocate sampling flags storage */ + if((lightSamples > 1 || lightRandomSamples) && luxelFilterRadius == 0) + { + size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( unsigned char ); + if(lm->superFlags == NULL) + lm->superFlags = safe_malloc( size ); + memset( (void *) lm->superFlags, 0, size ); + } + + /* initial pass, one sample per luxel */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + if( *cluster < 0 ) + continue; + + /* get particulars */ + lightLuxel = LIGHT_LUXEL( x, y ); + lightDeluxel = LIGHT_DELUXEL( x, y ); + origin = SUPER_ORIGIN( x, y ); + normal = SUPER_NORMAL( x, y ); + flag = SUPER_FLAG( x, y ); + +#if 0 + ////////// 27's temp hack for testing edge clipping //// + if( origin[0]==0 && origin[1]==0 && origin[2]==0 ) + { + lightLuxel[ 1 ] = 255; + lightLuxel[ 3 ] = 1.0f; + totalLighted++; + } + else +#endif + { + /* set contribution count */ + lightLuxel[ 3 ] = 1.0f; + + /* setup trace */ + trace.cluster = *cluster; + VectorCopy( origin, trace.origin ); + VectorCopy( normal, trace.normal ); + + /* get light for this sample */ + LightContributionToSample( &trace ); + VectorCopy( trace.color, lightLuxel ); + + /* add the contribution to the deluxemap */ + if( deluxemap ) + { + VectorCopy( trace.directionContribution, lightDeluxel ); + } + + /* check for evilness */ + if(trace.forceSubsampling > 1.0f && (lightSamples > 1 || lightRandomSamples) && luxelFilterRadius == 0) + { + totalLighted++; + *flag |= FLAG_FORCE_SUBSAMPLING; /* force */ + } + /* add to count */ + else if( trace.color[ 0 ] || trace.color[ 1 ] || trace.color[ 2 ] ) + totalLighted++; + } + } + } + + /* don't even bother with everything else if nothing was lit */ + if( totalLighted == 0 ) + continue; + + /* secondary pass, adaptive supersampling (fixme: use a contrast function to determine if subsampling is necessary) */ + /* 2003-09-27: changed it so filtering disamples supersampling, as it would waste time */ + if( (lightSamples > 1 || lightRandomSamples) && luxelFilterRadius == 0 ) + { + /* walk luxels */ + for( y = 0; y < (lm->sh - 1); y++ ) + { + for( x = 0; x < (lm->sw - 1); x++ ) + { + /* setup */ + mapped = 0; + lighted = 0; + VectorClear( total ); + + /* test 2x2 stamp */ + for( t = 0; t < 4; t++ ) + { + /* set sample coords */ + sx = x + tests[ t ][ 0 ]; + sy = y + tests[ t ][ 1 ]; + + /* get cluster */ + cluster = SUPER_CLUSTER( sx, sy ); + if( *cluster < 0 ) + continue; + mapped++; + + /* get luxel */ + flag = SUPER_FLAG( sx, sy ); + if(*flag & FLAG_FORCE_SUBSAMPLING) + { + /* force a lighted/mapped discrepancy so we subsample */ + ++lighted; + ++mapped; + ++mapped; + } + lightLuxel = LIGHT_LUXEL( sx, sy ); + VectorAdd( total, lightLuxel, total ); + if( (lightLuxel[ 0 ] + lightLuxel[ 1 ] + lightLuxel[ 2 ]) > 0.0f ) + lighted++; + } + + /* if total color is under a certain amount, then don't bother subsampling */ + if( total[ 0 ] <= 4.0f && total[ 1 ] <= 4.0f && total[ 2 ] <= 4.0f ) + continue; + + /* if all 4 pixels are either in shadow or light, then don't subsample */ + if( lighted != 0 && lighted != mapped ) + { + for( t = 0; t < 4; t++ ) + { + /* set sample coords */ + sx = x + tests[ t ][ 0 ]; + sy = y + tests[ t ][ 1 ]; + + /* get luxel */ + cluster = SUPER_CLUSTER( sx, sy ); + if( *cluster < 0 ) + continue; + flag = SUPER_FLAG( sx, sy ); + if(*flag & FLAG_ALREADY_SUBSAMPLED) // already subsampled + continue; + lightLuxel = LIGHT_LUXEL( sx, sy ); + lightDeluxel = LIGHT_DELUXEL( sx, sy ); + origin = SUPER_ORIGIN( sx, sy ); + + /* only subsample shadowed luxels */ + //% if( (lightLuxel[ 0 ] + lightLuxel[ 1 ] + lightLuxel[ 2 ]) <= 0.0f ) + //% continue; + + /* subsample it */ + if(lightRandomSamples) + RandomSubsampleRawLuxel( lm, &trace, origin, sx, sy, 0.5f * lightSamplesSearchBoxSize, lightLuxel, deluxemap ? lightDeluxel : NULL ); + else + SubsampleRawLuxel_r( lm, &trace, origin, sx, sy, 0.25f * lightSamplesSearchBoxSize, lightLuxel, deluxemap ? lightDeluxel : NULL ); + + *flag |= FLAG_ALREADY_SUBSAMPLED; + + /* debug code to colorize subsampled areas to yellow */ + //% luxel = SUPER_LUXEL( lightmapNum, sx, sy ); + //% VectorSet( luxel, 255, 204, 0 ); + } + } + } + } + } + + /* tertiary pass, apply dirt map (ambient occlusion) */ + if( 0 && dirty ) + { + /* walk luxels */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + if( *cluster < 0 ) + continue; + + /* get particulars */ + lightLuxel = LIGHT_LUXEL( x, y ); + dirt = SUPER_DIRT( x, y ); + + /* scale light value */ + VectorScale( lightLuxel, *dirt, lightLuxel ); + } + } + } + + /* allocate sampling lightmap storage */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + { + /* allocate sampling lightmap storage */ + size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); + lm->superLuxels[ lightmapNum ] = safe_malloc( size ); + memset( lm->superLuxels[ lightmapNum ], 0, size ); + } + + /* set style */ + if( lightmapNum > 0 ) + { + lm->styles[ lightmapNum ] = trace.light->style; + //% Sys_Printf( "Surface %6d has lightstyle %d\n", rawLightmapNum, trace.light->style ); + } + + /* copy to permanent luxels */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster and origin */ + cluster = SUPER_CLUSTER( x, y ); + if( *cluster < 0 ) + continue; + origin = SUPER_ORIGIN( x, y ); + + /* filter? */ + if( luxelFilterRadius ) + { + /* setup */ + VectorClear( averageColor ); + VectorClear( averageDir ); + samples = 0.0f; + + /* cheaper distance-based filtering */ + for( sy = (y - luxelFilterRadius); sy <= (y + luxelFilterRadius); sy++ ) + { + if( sy < 0 || sy >= lm->sh ) + continue; + + for( sx = (x - luxelFilterRadius); sx <= (x + luxelFilterRadius); sx++ ) + { + if( sx < 0 || sx >= lm->sw ) + continue; + + /* get particulars */ + cluster = SUPER_CLUSTER( sx, sy ); + if( *cluster < 0 ) + continue; + lightLuxel = LIGHT_LUXEL( sx, sy ); + lightDeluxel = LIGHT_DELUXEL( sx, sy ); + + /* create weight */ + weight = (abs( sx - x ) == luxelFilterRadius ? 0.5f : 1.0f); + weight *= (abs( sy - y ) == luxelFilterRadius ? 0.5f : 1.0f); + + /* scale luxel by filter weight */ + VectorScale( lightLuxel, weight, color ); + VectorAdd( averageColor, color, averageColor ); + if(deluxemap) + { + VectorScale( lightDeluxel, weight, direction ); + VectorAdd( averageDir, direction, averageDir ); + } + samples += weight; + } + } + + /* any samples? */ + if( samples <= 0.0f ) + continue; + + /* scale into luxel */ + luxel = SUPER_LUXEL( lightmapNum, x, y ); + luxel[ 3 ] = 1.0f; + + /* handle negative light */ + if( trace.light->flags & LIGHT_NEGATIVE ) + { + luxel[ 0 ] -= averageColor[ 0 ] / samples; + luxel[ 1 ] -= averageColor[ 1 ] / samples; + luxel[ 2 ] -= averageColor[ 2 ] / samples; + } + + /* handle normal light */ + else + { + luxel[ 0 ] += averageColor[ 0 ] / samples; + luxel[ 1 ] += averageColor[ 1 ] / samples; + luxel[ 2 ] += averageColor[ 2 ] / samples; + } + + if(deluxemap) + { + /* scale into luxel */ + deluxel = SUPER_DELUXEL( x, y ); + deluxel[ 0 ] += averageDir[ 0 ] / samples; + deluxel[ 1 ] += averageDir[ 1 ] / samples; + deluxel[ 2 ] += averageDir[ 2 ] / samples; + } + } + + /* single sample */ + else + { + /* get particulars */ + lightLuxel = LIGHT_LUXEL( x, y ); + lightDeluxel = LIGHT_DELUXEL( x, y ); + luxel = SUPER_LUXEL( lightmapNum, x, y ); + deluxel = SUPER_DELUXEL( x, y ); + + /* handle negative light */ + if( trace.light->flags & LIGHT_NEGATIVE ) + VectorScale( averageColor, -1.0f, averageColor ); + + /* add color */ + luxel[ 3 ] = 1.0f; + + /* handle negative light */ + if( trace.light->flags & LIGHT_NEGATIVE ) + VectorSubtract( luxel, lightLuxel, luxel ); + + /* handle normal light */ + else + VectorAdd( luxel, lightLuxel, luxel ); + + if(deluxemap) + { + VectorAdd( deluxel, lightDeluxel, deluxel ); + } + } + } + } + } + + /* free temporary luxels */ + if( lightLuxels != stackLightLuxels ) + free( lightLuxels ); + + if(deluxemap) + free( lightDeluxels ); + } + + /* free light list */ + FreeTraceLights( &trace ); + + /* floodlight pass */ + if( floodlighty ) + FloodlightIlluminateLightmap(lm); + + if (debugnormals) + { + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + //% if( *cluster < 0 ) + //% continue; + + /* get particulars */ + luxel = SUPER_LUXEL( lightmapNum, x, y ); + normal = SUPER_NORMAL ( x, y ); + + luxel[0]=(normal[0]*127)+127; + luxel[1]=(normal[1]*127)+127; + luxel[2]=(normal[2]*127)+127; + } + } + } + } + + /* ----------------------------------------------------------------- + dirt pass + ----------------------------------------------------------------- */ + + if( dirty ) + { + /* walk lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + + /* apply dirt to each luxel */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + //% if( *cluster < 0 ) // TODO why not do this check? These pixels should be zero anyway + //% continue; + + /* get particulars */ + luxel = SUPER_LUXEL( lightmapNum, x, y ); + dirt = SUPER_DIRT( x, y ); + + /* apply dirt */ + VectorScale( luxel, *dirt, luxel ); + + /* debugging */ + if( dirtDebug ) + VectorSet( luxel, *dirt * 255.0f, *dirt * 255.0f, *dirt * 255.0f ); + } + } + } + } + + /* ----------------------------------------------------------------- + filter pass + ----------------------------------------------------------------- */ + + /* walk lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + + /* average occluded luxels from neighbors */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get particulars */ + cluster = SUPER_CLUSTER( x, y ); + luxel = SUPER_LUXEL( lightmapNum, x, y ); + deluxel = SUPER_DELUXEL( x, y ); + normal = SUPER_NORMAL( x, y ); + + /* determine if filtering is necessary */ + filterColor = qfalse; + filterDir = qfalse; + if( *cluster < 0 || + (lm->splotchFix && (luxel[ 0 ] <= ambientColor[ 0 ] || luxel[ 1 ] <= ambientColor[ 1 ] || luxel[ 2 ] <= ambientColor[ 2 ])) ) + filterColor = qtrue; + + if( deluxemap && lightmapNum == 0 && (*cluster < 0 || filter) ) + filterDir = qtrue; + + if( !filterColor && !filterDir ) + continue; + + /* choose seed amount */ + VectorClear( averageColor ); + VectorClear( averageDir ); + samples = 0.0f; + + /* walk 3x3 matrix */ + for( sy = (y - 1); sy <= (y + 1); sy++ ) + { + if( sy < 0 || sy >= lm->sh ) + continue; + + for( sx = (x - 1); sx <= (x + 1); sx++ ) + { + if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) + continue; + + /* get neighbor's particulars */ + cluster2 = SUPER_CLUSTER( sx, sy ); + luxel2 = SUPER_LUXEL( lightmapNum, sx, sy ); + deluxel2 = SUPER_DELUXEL( sx, sy ); + + /* ignore unmapped/unlit luxels */ + if( *cluster2 < 0 || luxel2[ 3 ] == 0.0f || + (lm->splotchFix && VectorCompare( luxel2, ambientColor )) ) + continue; + + /* add its distinctiveness to our own */ + VectorAdd( averageColor, luxel2, averageColor ); + samples += luxel2[ 3 ]; + if( filterDir ) + VectorAdd( averageDir, deluxel2, averageDir ); + } + } + + /* fall through */ + if( samples <= 0.0f ) + continue; + + /* dark lightmap seams */ + if( dark ) + { + if( lightmapNum == 0 ) + VectorMA( averageColor, 2.0f, ambientColor, averageColor ); + samples += 2.0f; + } + + /* average it */ + if( filterColor ) + { + VectorDivide( averageColor, samples, luxel ); + luxel[ 3 ] = 1.0f; + } + if( filterDir ) + VectorDivide( averageDir, samples, deluxel ); + + /* set cluster to -3 */ + if( *cluster < 0 ) + *cluster = CLUSTER_FLOODED; + } + } + } + + +#if 0 + // audit pass + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + for( y = 0; y < lm->sh; y++ ) + for( x = 0; x < lm->sw; x++ ) + { + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + luxel = SUPER_LUXEL( lightmapNum, x, y ); + deluxel = SUPER_DELUXEL( x, y ); + if(!luxel || !deluxel || !cluster) + { + Sys_FPrintf(SYS_VRB, "WARNING: I got NULL'd.\n"); + continue; + } + else if(*cluster < 0) + { + // unmapped pixel + // should have neither deluxemap nor lightmap + if(deluxel[3]) + Sys_FPrintf(SYS_VRB, "WARNING: I have written deluxe to an unmapped luxel. Sorry.\n"); + } + else + { + // mapped pixel + // should have both deluxemap and lightmap + if(deluxel[3]) + Sys_FPrintf(SYS_VRB, "WARNING: I forgot to write deluxe to a mapped luxel. Sorry.\n"); + } + } + } +#endif +} + + + +/* +IlluminateVertexes() +light the surface vertexes +*/ + +#define VERTEX_NUDGE 4.0f + +void IlluminateVertexes( int num ) +{ + int i, x, y, z, x1, y1, z1, sx, sy, radius, maxRadius, *cluster; + int lightmapNum, numAvg; + float samples, *vertLuxel, *radVertLuxel, *luxel, dirt; + vec3_t origin, temp, temp2, colors[ MAX_LIGHTMAPS ], avgColors[ MAX_LIGHTMAPS ]; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + rawLightmap_t *lm; + bspDrawVert_t *verts; + trace_t trace; + float floodLightAmount; + vec3_t floodColor; + + + /* get surface, info, and raw lightmap */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + lm = info->lm; + + /* ----------------------------------------------------------------- + illuminate the vertexes + ----------------------------------------------------------------- */ + + /* calculate vertex lighting for surfaces without lightmaps */ + if( lm == NULL || cpmaHack ) + { + /* setup trace */ + trace.testOcclusion = (cpmaHack && lm != NULL) ? qfalse : !noTrace; + trace.forceSunlight = info->si->forceSunlight; + trace.recvShadows = info->recvShadows; + trace.numSurfaces = 1; + trace.surfaces = # + trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; + + /* twosided lighting */ + trace.twoSided = info->si->twoSided; + + /* make light list for this surface */ + CreateTraceLightsForSurface( num, &trace ); + + /* setup */ + verts = yDrawVerts + ds->firstVert; + numAvg = 0; + memset( avgColors, 0, sizeof( avgColors ) ); + + /* walk the surface verts */ + for( i = 0; i < ds->numVerts; i++ ) + { + /* get vertex luxel */ + radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); + + /* color the luxel with raw lightmap num? */ + if( debugSurfaces ) + VectorCopy( debugColors[ num % 12 ], radVertLuxel ); + + /* color the luxel with luxel origin? */ + else if( debugOrigin ) + { + VectorSubtract( info->maxs, info->mins, temp ); + VectorScale( temp, (1.0f / 255.0f), temp ); + VectorSubtract( origin, lm->mins, temp2 ); + radVertLuxel[ 0 ] = info->mins[ 0 ] + (temp[ 0 ] * temp2[ 0 ]); + radVertLuxel[ 1 ] = info->mins[ 1 ] + (temp[ 1 ] * temp2[ 1 ]); + radVertLuxel[ 2 ] = info->mins[ 2 ] + (temp[ 2 ] * temp2[ 2 ]); + } + + /* color the luxel with the normal */ + else if( normalmap ) + { + radVertLuxel[ 0 ] = (verts[ i ].normal[ 0 ] + 1.0f) * 127.5f; + radVertLuxel[ 1 ] = (verts[ i ].normal[ 1 ] + 1.0f) * 127.5f; + radVertLuxel[ 2 ] = (verts[ i ].normal[ 2 ] + 1.0f) * 127.5f; + } + + /* illuminate the vertex */ + else + { + /* clear vertex luxel */ + VectorSet( radVertLuxel, -1.0f, -1.0f, -1.0f ); + + /* try at initial origin */ + trace.cluster = ClusterForPointExtFilter( verts[ i ].xyz, VERTEX_EPSILON, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ] ); + if( trace.cluster >= 0 ) + { + /* setup trace */ + VectorCopy( verts[ i ].xyz, trace.origin ); + VectorCopy( verts[ i ].normal, trace.normal ); + + /* r7 dirt */ + if( dirty && !bouncing ) + dirt = DirtForSample( &trace ); + else + dirt = 1.0f; + + /* jal: floodlight */ + floodLightAmount = 0.0f; + VectorClear( floodColor ); + if( floodlighty && !bouncing ) + { + floodLightAmount = floodlightIntensity * FloodLightForSample( &trace, floodlightDistance, floodlight_lowquality ); + VectorScale( floodlightRGB, floodLightAmount, floodColor ); + } + + /* trace */ + LightingAtSample( &trace, ds->vertexStyles, colors ); + + /* store */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* r7 dirt */ + VectorScale( colors[ lightmapNum ], dirt, colors[ lightmapNum ] ); + + /* jal: floodlight */ + VectorAdd( colors[ lightmapNum ], floodColor, colors[ lightmapNum ] ); + + /* store */ + radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + VectorCopy( colors[ lightmapNum ], radVertLuxel ); + VectorAdd( avgColors[ lightmapNum ], colors[ lightmapNum ], colors[ lightmapNum ] ); + } + } + + /* is this sample bright enough? */ + radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); + if( radVertLuxel[ 0 ] <= ambientColor[ 0 ] && + radVertLuxel[ 1 ] <= ambientColor[ 1 ] && + radVertLuxel[ 2 ] <= ambientColor[ 2 ] ) + { + /* nudge the sample point around a bit */ + for( x = 0; x < 5; x++ ) + { + /* two's complement 0, 1, -1, 2, -2, etc */ + x1 = ((x >> 1) ^ (x & 1 ? -1 : 0)) + (x & 1); + + for( y = 0; y < 5; y++ ) + { + y1 = ((y >> 1) ^ (y & 1 ? -1 : 0)) + (y & 1); + + for( z = 0; z < 5; z++ ) + { + z1 = ((z >> 1) ^ (z & 1 ? -1 : 0)) + (z & 1); + + /* nudge origin */ + trace.origin[ 0 ] = verts[ i ].xyz[ 0 ] + (VERTEX_NUDGE * x1); + trace.origin[ 1 ] = verts[ i ].xyz[ 1 ] + (VERTEX_NUDGE * y1); + trace.origin[ 2 ] = verts[ i ].xyz[ 2 ] + (VERTEX_NUDGE * z1); + + /* try at nudged origin */ + trace.cluster = ClusterForPointExtFilter( origin, VERTEX_EPSILON, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ] ); + if( trace.cluster < 0 ) + continue; + + /* r7 dirt */ + if( dirty && !bouncing ) + dirt = DirtForSample( &trace ); + else + dirt = 1.0f; + + /* jal: floodlight */ + floodLightAmount = 0.0f; + VectorClear( floodColor ); + if( floodlighty && !bouncing ) + { + floodLightAmount = floodlightIntensity * FloodLightForSample( &trace, floodlightDistance, floodlight_lowquality ); + VectorScale( floodlightRGB, floodLightAmount, floodColor ); + } + + /* trace */ + LightingAtSample( &trace, ds->vertexStyles, colors ); + + /* store */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* r7 dirt */ + VectorScale( colors[ lightmapNum ], dirt, colors[ lightmapNum ] ); + + /* jal: floodlight */ + VectorAdd( colors[ lightmapNum ], floodColor, colors[ lightmapNum ] ); + + /* store */ + radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + VectorCopy( colors[ lightmapNum ], radVertLuxel ); + } + + /* bright enough? */ + radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); + if( radVertLuxel[ 0 ] > ambientColor[ 0 ] || + radVertLuxel[ 1 ] > ambientColor[ 1 ] || + radVertLuxel[ 2 ] > ambientColor[ 2 ] ) + x = y = z = 1000; + } + } + } + } + + /* add to average? */ + radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); + if( radVertLuxel[ 0 ] > ambientColor[ 0 ] || + radVertLuxel[ 1 ] > ambientColor[ 1 ] || + radVertLuxel[ 2 ] > ambientColor[ 2 ] ) + { + numAvg++; + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + VectorAdd( avgColors[ lightmapNum ], radVertLuxel, avgColors[ lightmapNum ] ); + } + } + } + + /* another happy customer */ + numVertsIlluminated++; + } + + /* set average color */ + if( numAvg > 0 ) + { + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + VectorScale( avgColors[ lightmapNum ], (1.0f / numAvg), avgColors[ lightmapNum ] ); + } + else + { + VectorCopy( ambientColor, avgColors[ 0 ] ); + } + + /* clean up and store vertex color */ + for( i = 0; i < ds->numVerts; i++ ) + { + /* get vertex luxel */ + radVertLuxel = RAD_VERTEX_LUXEL( 0, ds->firstVert + i ); + + /* store average in occluded vertexes */ + if( radVertLuxel[ 0 ] < 0.0f ) + { + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + VectorCopy( avgColors[ lightmapNum ], radVertLuxel ); + + /* debug code */ + //% VectorSet( radVertLuxel, 255.0f, 0.0f, 0.0f ); + } + } + + /* store it */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* get luxels */ + vertLuxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + + /* store */ + if( bouncing || bounce == 0 || !bounceOnly ) + VectorAdd( vertLuxel, radVertLuxel, vertLuxel ); + if( !info->si->noVertexLight ) + ColorToBytes( vertLuxel, verts[ i ].color[ lightmapNum ], info->si->vertexScale ); + } + } + + /* free light list */ + FreeTraceLights( &trace ); + + /* return to sender */ + return; + } + + /* ----------------------------------------------------------------- + reconstitute vertex lighting from the luxels + ----------------------------------------------------------------- */ + + /* set styles from lightmap */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + ds->vertexStyles[ lightmapNum ] = lm->styles[ lightmapNum ]; + + /* get max search radius */ + maxRadius = lm->sw; + maxRadius = maxRadius > lm->sh ? maxRadius : lm->sh; + + /* walk the surface verts */ + verts = yDrawVerts + ds->firstVert; + for( i = 0; i < ds->numVerts; i++ ) + { + /* do each lightmap */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + + /* get luxel coords */ + x = verts[ i ].lightmap[ lightmapNum ][ 0 ]; + y = verts[ i ].lightmap[ lightmapNum ][ 1 ]; + if( x < 0 ) + x = 0; + else if( x >= lm->sw ) + x = lm->sw - 1; + if( y < 0 ) + y = 0; + else if( y >= lm->sh ) + y = lm->sh - 1; + + /* get vertex luxels */ + vertLuxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + radVertLuxel = RAD_VERTEX_LUXEL( lightmapNum, ds->firstVert + i ); + + /* color the luxel with the normal? */ + if( normalmap ) + { + radVertLuxel[ 0 ] = (verts[ i ].normal[ 0 ] + 1.0f) * 127.5f; + radVertLuxel[ 1 ] = (verts[ i ].normal[ 1 ] + 1.0f) * 127.5f; + radVertLuxel[ 2 ] = (verts[ i ].normal[ 2 ] + 1.0f) * 127.5f; + } + + /* color the luxel with surface num? */ + else if( debugSurfaces ) + VectorCopy( debugColors[ num % 12 ], radVertLuxel ); + + /* divine color from the superluxels */ + else + { + /* increasing radius */ + VectorClear( radVertLuxel ); + samples = 0.0f; + for( radius = 0; radius < maxRadius && samples <= 0.0f; radius++ ) + { + /* sample within radius */ + for( sy = (y - radius); sy <= (y + radius); sy++ ) + { + if( sy < 0 || sy >= lm->sh ) + continue; + + for( sx = (x - radius); sx <= (x + radius); sx++ ) + { + if( sx < 0 || sx >= lm->sw ) + continue; + + /* get luxel particulars */ + luxel = SUPER_LUXEL( lightmapNum, sx, sy ); + cluster = SUPER_CLUSTER( sx, sy ); + if( *cluster < 0 ) + continue; + + /* testing: must be brigher than ambient color */ + //% if( luxel[ 0 ] <= ambientColor[ 0 ] || luxel[ 1 ] <= ambientColor[ 1 ] || luxel[ 2 ] <= ambientColor[ 2 ] ) + //% continue; + + /* add its distinctiveness to our own */ + VectorAdd( radVertLuxel, luxel, radVertLuxel ); + samples += luxel[ 3 ]; + } + } + } + + /* any color? */ + if( samples > 0.0f ) + VectorDivide( radVertLuxel, samples, radVertLuxel ); + else + VectorCopy( ambientColor, radVertLuxel ); + } + + /* store into floating point storage */ + VectorAdd( vertLuxel, radVertLuxel, vertLuxel ); + numVertsIlluminated++; + + /* store into bytes (for vertex approximation) */ + if( !info->si->noVertexLight ) + ColorToBytes( vertLuxel, verts[ i ].color[ lightmapNum ], 1.0f ); + } + } +} + + + +/* ------------------------------------------------------------------------------- + +light optimization (-fast) + +creates a list of lights that will affect a surface and stores it in tw +this is to optimize surface lighting by culling out as many of the +lights in the world as possible from further calculation + +------------------------------------------------------------------------------- */ + +/* +SetupBrushes() +determines opaque brushes in the world and find sky shaders for sunlight calculations +*/ + +void SetupBrushes( void ) +{ + int i, j, b, compileFlags; + qboolean inside; + bspBrush_t *brush; + bspBrushSide_t *side; + bspShader_t *shader; + shaderInfo_t *si; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- SetupBrushes ---\n" ); + + /* allocate */ + if( opaqueBrushes == NULL ) + opaqueBrushes = safe_malloc( numBSPBrushes / 8 + 1 ); + + /* clear */ + memset( opaqueBrushes, 0, numBSPBrushes / 8 + 1 ); + numOpaqueBrushes = 0; + + /* walk the list of worldspawn brushes */ + for( i = 0; i < bspModels[ 0 ].numBSPBrushes; i++ ) + { + /* get brush */ + b = bspModels[ 0 ].firstBSPBrush + i; + brush = &bspBrushes[ b ]; + + /* check all sides */ + inside = qtrue; + compileFlags = 0; + for( j = 0; j < brush->numSides && inside; j++ ) + { + /* do bsp shader calculations */ + side = &bspBrushSides[ brush->firstSide + j ]; + shader = &bspShaders[ side->shaderNum ]; + + /* get shader info */ + si = ShaderInfoForShader( shader->shader ); + if( si == NULL ) + continue; + + /* or together compile flags */ + compileFlags |= si->compileFlags; + } + + /* determine if this brush is opaque to light */ + if( !(compileFlags & C_TRANSLUCENT) ) + { + opaqueBrushes[ b >> 3 ] |= (1 << (b & 7)); + numOpaqueBrushes++; + maxOpaqueBrush = i; + } + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d opaque brushes\n", numOpaqueBrushes ); +} + + + +/* +ClusterVisible() +determines if two clusters are visible to each other using the PVS +*/ + +qboolean ClusterVisible( int a, int b ) +{ + int portalClusters, leafBytes; + byte *pvs; + + + /* dummy check */ + if( a < 0 || b < 0 ) + return qfalse; + + /* early out */ + if( a == b ) + return qtrue; + + /* not vised? */ + if( numBSPVisBytes <=8 ) + return qtrue; + + /* get pvs data */ + portalClusters = ((int *) bspVisBytes)[ 0 ]; + leafBytes = ((int*) bspVisBytes)[ 1 ]; + pvs = bspVisBytes + VIS_HEADER_SIZE + (a * leafBytes); + + /* check */ + if( (pvs[ b >> 3 ] & (1 << (b & 7))) ) + return qtrue; + return qfalse; +} + + + +/* +PointInLeafNum_r() +borrowed from vlight.c +*/ + +int PointInLeafNum_r( vec3_t point, int nodenum ) +{ + int leafnum; + vec_t dist; + bspNode_t *node; + bspPlane_t *plane; + + + while( nodenum >= 0 ) + { + node = &bspNodes[ nodenum ]; + plane = &bspPlanes[ node->planeNum ]; + dist = DotProduct( point, plane->normal ) - plane->dist; + if( dist > 0.1 ) + nodenum = node->children[ 0 ]; + else if( dist < -0.1 ) + nodenum = node->children[ 1 ]; + else + { + leafnum = PointInLeafNum_r( point, node->children[ 0 ] ); + if( bspLeafs[ leafnum ].cluster != -1 ) + return leafnum; + nodenum = node->children[ 1 ]; + } + } + + leafnum = -nodenum - 1; + return leafnum; +} + + + +/* +PointInLeafnum() +borrowed from vlight.c +*/ + +int PointInLeafNum( vec3_t point ) +{ + return PointInLeafNum_r( point, 0 ); +} + + + +/* +ClusterVisibleToPoint() - ydnar +returns qtrue if point can "see" cluster +*/ + +qboolean ClusterVisibleToPoint( vec3_t point, int cluster ) +{ + int pointCluster; + + + /* get leafNum for point */ + pointCluster = ClusterForPoint( point ); + if( pointCluster < 0 ) + return qfalse; + + /* check pvs */ + return ClusterVisible( pointCluster, cluster ); +} + + + +/* +ClusterForPoint() - ydnar +returns the pvs cluster for point +*/ + +int ClusterForPoint( vec3_t point ) +{ + int leafNum; + + + /* get leafNum for point */ + leafNum = PointInLeafNum( point ); + if( leafNum < 0 ) + return -1; + + /* return the cluster */ + return bspLeafs[ leafNum ].cluster; +} + + + +/* +ClusterForPointExt() - ydnar +also takes brushes into account for occlusion testing +*/ + +int ClusterForPointExt( vec3_t point, float epsilon ) +{ + int i, j, b, leafNum, cluster; + float dot; + qboolean inside; + int *brushes, numBSPBrushes; + bspLeaf_t *leaf; + bspBrush_t *brush; + bspPlane_t *plane; + + + /* get leaf for point */ + leafNum = PointInLeafNum( point ); + if( leafNum < 0 ) + return -1; + leaf = &bspLeafs[ leafNum ]; + + /* get the cluster */ + cluster = leaf->cluster; + if( cluster < 0 ) + return -1; + + /* transparent leaf, so check point against all brushes in the leaf */ + brushes = &bspLeafBrushes[ leaf->firstBSPLeafBrush ]; + numBSPBrushes = leaf->numBSPLeafBrushes; + for( i = 0; i < numBSPBrushes; i++ ) + { + /* get parts */ + b = brushes[ i ]; + if( b > maxOpaqueBrush ) + continue; + brush = &bspBrushes[ b ]; + if( !(opaqueBrushes[ b >> 3 ] & (1 << (b & 7))) ) + continue; + + /* check point against all planes */ + inside = qtrue; + for( j = 0; j < brush->numSides && inside; j++ ) + { + plane = &bspPlanes[ bspBrushSides[ brush->firstSide + j ].planeNum ]; + dot = DotProduct( point, plane->normal ); + dot -= plane->dist; + if( dot > epsilon ) + inside = qfalse; + } + + /* if inside, return bogus cluster */ + if( inside ) + return -1 - b; + } + + /* if the point made it this far, it's not inside any opaque brushes */ + return cluster; +} + + + +/* +ClusterForPointExtFilter() - ydnar +adds cluster checking against a list of known valid clusters +*/ + +int ClusterForPointExtFilter( vec3_t point, float epsilon, int numClusters, int *clusters ) +{ + int i, cluster; + + + /* get cluster for point */ + cluster = ClusterForPointExt( point, epsilon ); + + /* check if filtering is necessary */ + if( cluster < 0 || numClusters <= 0 || clusters == NULL ) + return cluster; + + /* filter */ + for( i = 0; i < numClusters; i++ ) + { + if( cluster == clusters[ i ] || ClusterVisible( cluster, clusters[ i ] ) ) + return cluster; + } + + /* failed */ + return -1; +} + + + +/* +ShaderForPointInLeaf() - ydnar +checks a point against all brushes in a leaf, returning the shader of the brush +also sets the cumulative surface and content flags for the brush hit +*/ + +int ShaderForPointInLeaf( vec3_t point, int leafNum, float epsilon, int wantContentFlags, int wantSurfaceFlags, int *contentFlags, int *surfaceFlags ) +{ + int i, j; + float dot; + qboolean inside; + int *brushes, numBSPBrushes; + bspLeaf_t *leaf; + bspBrush_t *brush; + bspBrushSide_t *side; + bspPlane_t *plane; + bspShader_t *shader; + int allSurfaceFlags, allContentFlags; + + + /* clear things out first */ + *surfaceFlags = 0; + *contentFlags = 0; + + /* get leaf */ + if( leafNum < 0 ) + return -1; + leaf = &bspLeafs[ leafNum ]; + + /* transparent leaf, so check point against all brushes in the leaf */ + brushes = &bspLeafBrushes[ leaf->firstBSPLeafBrush ]; + numBSPBrushes = leaf->numBSPLeafBrushes; + for( i = 0; i < numBSPBrushes; i++ ) + { + /* get parts */ + brush = &bspBrushes[ brushes[ i ] ]; + + /* check point against all planes */ + inside = qtrue; + allSurfaceFlags = 0; + allContentFlags = 0; + for( j = 0; j < brush->numSides && inside; j++ ) + { + side = &bspBrushSides[ brush->firstSide + j ]; + plane = &bspPlanes[ side->planeNum ]; + dot = DotProduct( point, plane->normal ); + dot -= plane->dist; + if( dot > epsilon ) + inside = qfalse; + else + { + shader = &bspShaders[ side->shaderNum ]; + allSurfaceFlags |= shader->surfaceFlags; + allContentFlags |= shader->contentFlags; + } + } + + /* handle if inside */ + if( inside ) + { + /* if there are desired flags, check for same and continue if they aren't matched */ + if( wantContentFlags && !(wantContentFlags & allContentFlags) ) + continue; + if( wantSurfaceFlags && !(wantSurfaceFlags & allSurfaceFlags) ) + continue; + + /* store the cumulative flags and return the brush shader (which is mostly useless) */ + *surfaceFlags = allSurfaceFlags; + *contentFlags = allContentFlags; + return brush->shaderNum; + } + } + + /* if the point made it this far, it's not inside any brushes */ + return -1; +} + + + +/* +ChopBounds() +chops a bounding box by the plane defined by origin and normal +returns qfalse if the bounds is entirely clipped away + +this is not exactly the fastest way to do this... +*/ + +qboolean ChopBounds( vec3_t mins, vec3_t maxs, vec3_t origin, vec3_t normal ) +{ + /* FIXME: rewrite this so it doesn't use bloody brushes */ + return qtrue; +} + + + +/* +SetupEnvelopes() +calculates each light's effective envelope, +taking into account brightness, type, and pvs. +*/ + +#define LIGHT_EPSILON 0.125f +#define LIGHT_NUDGE 2.0f + +void SetupEnvelopes( qboolean forGrid, qboolean fastFlag ) +{ + int i, x, y, z, x1, y1, z1; + light_t *light, *light2, **owner; + bspLeaf_t *leaf; + vec3_t origin, dir, mins, maxs; + float radius, intensity; + light_t *buckets[ 256 ]; + + + /* early out for weird cases where there are no lights */ + if( lights == NULL ) + return; + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- SetupEnvelopes%s ---\n", fastFlag ? " (fast)" : "" ); + + /* count lights */ + numLights = 0; + numCulledLights = 0; + owner = &lights; + while( *owner != NULL ) + { + /* get light */ + light = *owner; + + /* handle negative lights */ + if( light->photons < 0.0f || light->add < 0.0f ) + { + light->photons *= -1.0f; + light->add *= -1.0f; + light->flags |= LIGHT_NEGATIVE; + } + + /* sunlight? */ + if( light->type == EMIT_SUN ) + { + /* special cased */ + light->cluster = 0; + light->envelope = MAX_WORLD_COORD * 8.0f; + VectorSet( light->mins, MIN_WORLD_COORD * 8.0f, MIN_WORLD_COORD * 8.0f, MIN_WORLD_COORD * 8.0f ); + VectorSet( light->maxs, MAX_WORLD_COORD * 8.0f, MAX_WORLD_COORD * 8.0f, MAX_WORLD_COORD * 8.0f ); + } + + /* everything else */ + else + { + /* get pvs cluster for light */ + light->cluster = ClusterForPointExt( light->origin, LIGHT_EPSILON ); + + /* invalid cluster? */ + if( light->cluster < 0 ) + { + /* nudge the sample point around a bit */ + for( x = 0; x < 4; x++ ) + { + /* two's complement 0, 1, -1, 2, -2, etc */ + x1 = ((x >> 1) ^ (x & 1 ? -1 : 0)) + (x & 1); + + for( y = 0; y < 4; y++ ) + { + y1 = ((y >> 1) ^ (y & 1 ? -1 : 0)) + (y & 1); + + for( z = 0; z < 4; z++ ) + { + z1 = ((z >> 1) ^ (z & 1 ? -1 : 0)) + (z & 1); + + /* nudge origin */ + origin[ 0 ] = light->origin[ 0 ] + (LIGHT_NUDGE * x1); + origin[ 1 ] = light->origin[ 1 ] + (LIGHT_NUDGE * y1); + origin[ 2 ] = light->origin[ 2 ] + (LIGHT_NUDGE * z1); + + /* try at nudged origin */ + light->cluster = ClusterForPointExt( origin, LIGHT_EPSILON ); + if( light->cluster < 0 ) + continue; + + /* set origin */ + VectorCopy( origin, light->origin ); + } + } + } + } + + /* only calculate for lights in pvs and outside of opaque brushes */ + if( light->cluster >= 0 ) + { + /* set light fast flag */ + if( fastFlag ) + light->flags |= LIGHT_FAST_TEMP; + else + light->flags &= ~LIGHT_FAST_TEMP; + if( light->si && light->si->noFast ) + light->flags &= ~(LIGHT_FAST | LIGHT_FAST_TEMP); + + /* clear light envelope */ + light->envelope = 0; + + /* handle area lights */ + if( exactPointToPolygon && light->type == EMIT_AREA && light->w != NULL ) + { + /* ugly hack to calculate extent for area lights, but only done once */ + VectorScale( light->normal, -1.0f, dir ); + for( radius = 100.0f; radius < 130000.0f && light->envelope == 0; radius += 10.0f ) + { + float factor; + + VectorMA( light->origin, radius, light->normal, origin ); + factor = PointToPolygonFormFactor( origin, dir, light->w ); + if( factor < 0.0f ) + factor *= -1.0f; + if( (factor * light->add) <= light->falloffTolerance ) + light->envelope = radius; + } + + /* check for fast mode */ + if( !(light->flags & LIGHT_FAST) && !(light->flags & LIGHT_FAST_TEMP) ) + light->envelope = MAX_WORLD_COORD * 8.0f; + intensity = light->photons; /* hopefully not used */ + } + else + { + radius = 0.0f; + intensity = light->photons; + } + + /* other calcs */ + if( light->envelope <= 0.0f ) + { + /* solve distance for non-distance lights */ + if( !(light->flags & LIGHT_ATTEN_DISTANCE) ) + light->envelope = MAX_WORLD_COORD * 8.0f; + + /* solve distance for linear lights */ + else if( (light->flags & LIGHT_ATTEN_LINEAR ) ) + //% light->envelope = ((intensity / light->falloffTolerance) * linearScale - 1 + radius) / light->fade; + light->envelope = ((intensity * linearScale) - light->falloffTolerance) / light->fade; + + /* + add = angle * light->photons * linearScale - (dist * light->fade); + T = (light->photons * linearScale) - (dist * light->fade); + T + (dist * light->fade) = (light->photons * linearScale); + dist * light->fade = (light->photons * linearScale) - T; + dist = ((light->photons * linearScale) - T) / light->fade; + */ + + /* solve for inverse square falloff */ + else + light->envelope = sqrt( intensity / light->falloffTolerance ) + radius; + + /* + add = light->photons / (dist * dist); + T = light->photons / (dist * dist); + T * (dist * dist) = light->photons; + dist = sqrt( light->photons / T ); + */ + } + + /* chop radius against pvs */ + { + /* clear bounds */ + ClearBounds( mins, maxs ); + + /* check all leaves */ + for( i = 0; i < numBSPLeafs; i++ ) + { + /* get test leaf */ + leaf = &bspLeafs[ i ]; + + /* in pvs? */ + if( leaf->cluster < 0 ) + continue; + if( ClusterVisible( light->cluster, leaf->cluster ) == qfalse ) /* ydnar: thanks Arnout for exposing my stupid error (this never failed before) */ + continue; + + /* add this leafs bbox to the bounds */ + VectorCopy( leaf->mins, origin ); + AddPointToBounds( origin, mins, maxs ); + VectorCopy( leaf->maxs, origin ); + AddPointToBounds( origin, mins, maxs ); + } + + /* test to see if bounds encompass light */ + for( i = 0; i < 3; i++ ) + { + if( mins[ i ] > light->origin[ i ] || maxs[ i ] < light->origin[ i ] ) + { + //% Sys_Printf( "WARNING: Light PVS bounds (%.0f, %.0f, %.0f) -> (%.0f, %.0f, %.0f)\ndo not encompass light %d (%f, %f, %f)\n", + //% mins[ 0 ], mins[ 1 ], mins[ 2 ], + //% maxs[ 0 ], maxs[ 1 ], maxs[ 2 ], + //% numLights, light->origin[ 0 ], light->origin[ 1 ], light->origin[ 2 ] ); + AddPointToBounds( light->origin, mins, maxs ); + } + } + + /* chop the bounds by a plane for area lights and spotlights */ + if( light->type == EMIT_AREA || light->type == EMIT_SPOT ) + ChopBounds( mins, maxs, light->origin, light->normal ); + + /* copy bounds */ + VectorCopy( mins, light->mins ); + VectorCopy( maxs, light->maxs ); + + /* reflect bounds around light origin */ + //% VectorMA( light->origin, -1.0f, origin, origin ); + VectorScale( light->origin, 2, origin ); + VectorSubtract( origin, maxs, origin ); + AddPointToBounds( origin, mins, maxs ); + //% VectorMA( light->origin, -1.0f, mins, origin ); + VectorScale( light->origin, 2, origin ); + VectorSubtract( origin, mins, origin ); + AddPointToBounds( origin, mins, maxs ); + + /* calculate spherical bounds */ + VectorSubtract( maxs, light->origin, dir ); + radius = (float) VectorLength( dir ); + + /* if this radius is smaller than the envelope, then set the envelope to it */ + if( radius < light->envelope ) + { + light->envelope = radius; + //% Sys_FPrintf( SYS_VRB, "PVS Cull (%d): culled\n", numLights ); + } + //% else + //% Sys_FPrintf( SYS_VRB, "PVS Cull (%d): failed (%8.0f > %8.0f)\n", numLights, radius, light->envelope ); + } + + /* add grid/surface only check */ + if( forGrid ) + { + if( !(light->flags & LIGHT_GRID) ) + light->envelope = 0.0f; + } + else + { + if( !(light->flags & LIGHT_SURFACES) ) + light->envelope = 0.0f; + } + } + + /* culled? */ + if( light->cluster < 0 || light->envelope <= 0.0f ) + { + /* debug code */ + //% Sys_Printf( "Culling light: Cluster: %d Envelope: %f\n", light->cluster, light->envelope ); + + /* delete the light */ + numCulledLights++; + *owner = light->next; + if( light->w != NULL ) + free( light->w ); + free( light ); + continue; + } + } + + /* square envelope */ + light->envelope2 = (light->envelope * light->envelope); + + /* increment light count */ + numLights++; + + /* set next light */ + owner = &((**owner).next); + } + + /* bucket sort lights by style */ + memset( buckets, 0, sizeof( buckets ) ); + light2 = NULL; + for( light = lights; light != NULL; light = light2 ) + { + /* get next light */ + light2 = light->next; + + /* filter into correct bucket */ + light->next = buckets[ light->style ]; + buckets[ light->style ] = light; + + /* if any styled light is present, automatically set nocollapse */ + if( light->style != LS_NORMAL ) + noCollapse = qtrue; + } + + /* filter back into light list */ + lights = NULL; + for( i = 255; i >= 0; i-- ) + { + light2 = NULL; + for( light = buckets[ i ]; light != NULL; light = light2 ) + { + light2 = light->next; + light->next = lights; + lights = light; + } + } + + /* emit some statistics */ + Sys_Printf( "%9d total lights\n", numLights ); + Sys_Printf( "%9d culled lights\n", numCulledLights ); +} + + + +/* +CreateTraceLightsForBounds() +creates a list of lights that affect the given bounding box and pvs clusters (bsp leaves) +*/ + +void CreateTraceLightsForBounds( vec3_t mins, vec3_t maxs, vec3_t normal, int numClusters, int *clusters, int flags, trace_t *trace ) +{ + int i; + light_t *light; + vec3_t origin, dir, nullVector = { 0.0f, 0.0f, 0.0f }; + float radius, dist, length; + + + /* potential pre-setup */ + if( numLights == 0 ) + SetupEnvelopes( qfalse, fast ); + + /* debug code */ + //% Sys_Printf( "CTWLFB: (%4.1f %4.1f %4.1f) (%4.1f %4.1f %4.1f)\n", mins[ 0 ], mins[ 1 ], mins[ 2 ], maxs[ 0 ], maxs[ 1 ], maxs[ 2 ] ); + + /* allocate the light list */ + trace->lights = safe_malloc( sizeof( light_t* ) * (numLights + 1) ); + trace->numLights = 0; + + /* calculate spherical bounds */ + VectorAdd( mins, maxs, origin ); + VectorScale( origin, 0.5f, origin ); + VectorSubtract( maxs, origin, dir ); + radius = (float) VectorLength( dir ); + + /* get length of normal vector */ + if( normal != NULL ) + length = VectorLength( normal ); + else + { + normal = nullVector; + length = 0; + } + + /* test each light and see if it reaches the sphere */ + /* note: the attenuation code MUST match LightingAtSample() */ + for( light = lights; light; light = light->next ) + { + /* check zero sized envelope */ + if( light->envelope <= 0 ) + { + lightsEnvelopeCulled++; + continue; + } + + /* check flags */ + if( !(light->flags & flags) ) + continue; + + /* sunlight skips all this nonsense */ + if( light->type != EMIT_SUN ) + { + /* sun only? */ + if( sunOnly ) + continue; + + /* check against pvs cluster */ + if( numClusters > 0 && clusters != NULL ) + { + for( i = 0; i < numClusters; i++ ) + { + if( ClusterVisible( light->cluster, clusters[ i ] ) ) + break; + } + + /* fixme! */ + if( i == numClusters ) + { + lightsClusterCulled++; + continue; + } + } + + /* if the light's bounding sphere intersects with the bounding sphere then this light needs to be tested */ + VectorSubtract( light->origin, origin, dir ); + dist = VectorLength( dir ); + dist -= light->envelope; + dist -= radius; + if( dist > 0 ) + { + lightsEnvelopeCulled++; + continue; + } + + /* check bounding box against light's pvs envelope (note: this code never eliminated any lights, so disabling it) */ + #if 0 + skip = qfalse; + for( i = 0; i < 3; i++ ) + { + if( mins[ i ] > light->maxs[ i ] || maxs[ i ] < light->mins[ i ] ) + skip = qtrue; + } + if( skip ) + { + lightsBoundsCulled++; + continue; + } + #endif + } + + /* planar surfaces (except twosided surfaces) have a couple more checks */ + if( length > 0.0f && trace->twoSided == qfalse ) + { + /* lights coplanar with a surface won't light it */ + if( !(light->flags & LIGHT_TWOSIDED) && DotProduct( light->normal, normal ) > 0.999f ) + { + lightsPlaneCulled++; + continue; + } + + /* check to see if light is behind the plane */ + if( DotProduct( light->origin, normal ) - DotProduct( origin, normal ) < -1.0f ) + { + lightsPlaneCulled++; + continue; + } + } + + /* add this light */ + trace->lights[ trace->numLights++ ] = light; + } + + /* make last night null */ + trace->lights[ trace->numLights ] = NULL; +} + + + +void FreeTraceLights( trace_t *trace ) +{ + if( trace->lights != NULL ) + free( trace->lights ); +} + + + +/* +CreateTraceLightsForSurface() +creates a list of lights that can potentially affect a drawsurface +*/ + +void CreateTraceLightsForSurface( int num, trace_t *trace ) +{ + int i; + vec3_t mins, maxs, normal; + bspDrawVert_t *dv; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + + + /* dummy check */ + if( num < 0 ) + return; + + /* get drawsurface and info */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* get the mins/maxs for the dsurf */ + ClearBounds( mins, maxs ); + VectorCopy( bspDrawVerts[ ds->firstVert ].normal, normal ); + for( i = 0; i < ds->numVerts; i++ ) + { + dv = &yDrawVerts[ ds->firstVert + i ]; + AddPointToBounds( dv->xyz, mins, maxs ); + if( !VectorCompare( dv->normal, normal ) ) + VectorClear( normal ); + } + + /* create the lights for the bounding box */ + CreateTraceLightsForBounds( mins, maxs, normal, info->numSurfaceClusters, &surfaceClusters[ info->firstSurfaceCluster ], LIGHT_SURFACES, trace ); +} + +///////////////////////////////////////////////////////////// + +#define FLOODLIGHT_CONE_ANGLE 88 /* degrees */ +#define FLOODLIGHT_NUM_ANGLE_STEPS 16 +#define FLOODLIGHT_NUM_ELEVATION_STEPS 4 +#define FLOODLIGHT_NUM_VECTORS (FLOODLIGHT_NUM_ANGLE_STEPS * FLOODLIGHT_NUM_ELEVATION_STEPS) + +static vec3_t floodVectors[ FLOODLIGHT_NUM_VECTORS ]; +static int numFloodVectors = 0; + +void SetupFloodLight( void ) +{ + int i, j; + float angle, elevation, angleStep, elevationStep; + const char *value; + double v1,v2,v3,v4,v5,v6; + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- SetupFloodLight ---\n" ); + + /* calculate angular steps */ + angleStep = DEG2RAD( 360.0f / FLOODLIGHT_NUM_ANGLE_STEPS ); + elevationStep = DEG2RAD( FLOODLIGHT_CONE_ANGLE / FLOODLIGHT_NUM_ELEVATION_STEPS ); + + /* iterate angle */ + angle = 0.0f; + for( i = 0, angle = 0.0f; i < FLOODLIGHT_NUM_ANGLE_STEPS; i++, angle += angleStep ) + { + /* iterate elevation */ + for( j = 0, elevation = elevationStep * 0.5f; j < FLOODLIGHT_NUM_ELEVATION_STEPS; j++, elevation += elevationStep ) + { + floodVectors[ numFloodVectors ][ 0 ] = sin( elevation ) * cos( angle ); + floodVectors[ numFloodVectors ][ 1 ] = sin( elevation ) * sin( angle ); + floodVectors[ numFloodVectors ][ 2 ] = cos( elevation ); + numFloodVectors++; + } + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d numFloodVectors\n", numFloodVectors ); + + /* floodlight */ + value = ValueForKey( &entities[ 0 ], "_floodlight" ); + + if( value[ 0 ] != '\0' ) + { + v1=v2=v3=0; + v4=floodlightDistance; + v5=floodlightIntensity; + v6=floodlightDirectionScale; + + sscanf( value, "%lf %lf %lf %lf %lf %lf", &v1, &v2, &v3, &v4, &v5); + + floodlightRGB[0]=v1; + floodlightRGB[1]=v2; + floodlightRGB[2]=v3; + + if (VectorLength(floodlightRGB)==0) + { + VectorSet(floodlightRGB,240,240,255); + } + + if (v4<1) v4=1024; + if (v5<1) v5=128; + if (v6<0) v6=1; + + floodlightDistance=v4; + floodlightIntensity=v5; + floodlightDirectionScale=v6; + + floodlighty = qtrue; + Sys_Printf( "FloodLighting enabled via worldspawn _floodlight key.\n" ); + } + else + { + VectorSet(floodlightRGB,240,240,255); + //floodlighty = qtrue; + //Sys_Printf( "FloodLighting enabled via worldspawn _floodlight key.\n" ); + } + VectorNormalize(floodlightRGB,floodlightRGB); +} + +/* +FloodLightForSample() +calculates floodlight value for a given sample +once again, kudos to the dirtmapping coder +*/ + +float FloodLightForSample( trace_t *trace , float floodLightDistance, qboolean floodLightLowQuality) +{ + int i; + float d; + float contribution; + int sub = 0; + float gatherLight, outLight; + vec3_t normal, worldUp, myUp, myRt, direction, displacement; + float dd; + int vecs = 0; + + gatherLight=0; + /* dummy check */ + //if( !dirty ) + // return 1.0f; + if( trace == NULL || trace->cluster < 0 ) + return 0.0f; + + + /* setup */ + dd = floodLightDistance; + VectorCopy( trace->normal, normal ); + + /* check if the normal is aligned to the world-up */ + if( normal[ 0 ] == 0.0f && normal[ 1 ] == 0.0f && ( normal[ 2 ] == 1.0f || normal[ 2 ] == -1.0f ) ) + { + if( normal[ 2 ] == 1.0f ) + { + VectorSet( myRt, 1.0f, 0.0f, 0.0f ); + VectorSet( myUp, 0.0f, 1.0f, 0.0f ); + } + else if( normal[ 2 ] == -1.0f ) + { + VectorSet( myRt, -1.0f, 0.0f, 0.0f ); + VectorSet( myUp, 0.0f, 1.0f, 0.0f ); + } + } + else + { + VectorSet( worldUp, 0.0f, 0.0f, 1.0f ); + CrossProduct( normal, worldUp, myRt ); + VectorNormalize( myRt, myRt ); + CrossProduct( myRt, normal, myUp ); + VectorNormalize( myUp, myUp ); + } + + /* vortex: optimise floodLightLowQuality a bit */ + if ( floodLightLowQuality == qtrue ) + { + /* iterate through ordered vectors */ + for( i = 0; i < numFloodVectors; i++ ) + if (rand()%10 != 0 ) continue; + } + else + { + /* iterate through ordered vectors */ + for( i = 0; i < numFloodVectors; i++ ) + { + vecs++; + + /* transform vector into tangent space */ + direction[ 0 ] = myRt[ 0 ] * floodVectors[ i ][ 0 ] + myUp[ 0 ] * floodVectors[ i ][ 1 ] + normal[ 0 ] * floodVectors[ i ][ 2 ]; + direction[ 1 ] = myRt[ 1 ] * floodVectors[ i ][ 0 ] + myUp[ 1 ] * floodVectors[ i ][ 1 ] + normal[ 1 ] * floodVectors[ i ][ 2 ]; + direction[ 2 ] = myRt[ 2 ] * floodVectors[ i ][ 0 ] + myUp[ 2 ] * floodVectors[ i ][ 1 ] + normal[ 2 ] * floodVectors[ i ][ 2 ]; + + /* set endpoint */ + VectorMA( trace->origin, dd, direction, trace->end ); + + //VectorMA( trace->origin, 1, direction, trace->origin ); + + SetupTrace( trace ); + /* trace */ + TraceLine( trace ); + contribution=1; + + if ( trace->compileFlags & C_SKY || trace->compileFlags & C_TRANSLUCENT ) + { + contribution=1.0f; + } + else if ( trace->opaque ) + { + VectorSubtract( trace->hit, trace->origin, displacement ); + d=VectorLength( displacement ); + + // d=trace->distance; + //if (d>256) gatherDirt+=1; + contribution=d/dd; + if (contribution>1) contribution=1.0f; + + //gatherDirt += 1.0f - ooDepth * VectorLength( displacement ); + } + + gatherLight+=contribution; + } + } + + /* early out */ + if( gatherLight <= 0.0f ) + return 0.0f; + + sub=vecs; + + if (sub<1) sub=1; + gatherLight/=(sub); + + outLight=gatherLight; + if( outLight > 1.0f ) + outLight = 1.0f; + + /* return to sender */ + return outLight; +} + +/* +FloodLightRawLightmap +lighttracer style ambient occlusion light hack. +Kudos to the dirtmapping author for most of this source. +VorteX: modified to floodlight up custom surfaces (q3map_floodLight) +VorteX: fixed problems with deluxemapping +*/ + +// floodlight pass on a lightmap +void FloodLightRawLightmapPass( rawLightmap_t *lm , vec3_t lmFloodLightRGB, float lmFloodLightIntensity, float lmFloodLightDistance, qboolean lmFloodLightLowQuality, float floodlightDirectionScale) +{ + int i, x, y, *cluster; + float *origin, *normal, *floodlight, floodLightAmount; + surfaceInfo_t *info; + trace_t trace; + // int sx, sy; + // float samples, average, *floodlight2; + + memset(&trace,0,sizeof(trace_t)); + + /* setup trace */ + trace.testOcclusion = qtrue; + trace.forceSunlight = qfalse; + trace.twoSided = qtrue; + trace.recvShadows = lm->recvShadows; + trace.numSurfaces = lm->numLightSurfaces; + trace.surfaces = &lightSurfaces[ lm->firstLightSurface ]; + trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS; + trace.testAll = qfalse; + trace.distance = 1024; + + /* twosided lighting (may or may not be a good idea for lightmapped stuff) */ + //trace.twoSided = qfalse; + for( i = 0; i < trace.numSurfaces; i++ ) + { + /* get surface */ + info = &surfaceInfos[ trace.surfaces[ i ] ]; + + /* check twosidedness */ + if( info->si->twoSided ) + { + trace.twoSided = qtrue; + break; + } + } + + /* gather floodlight */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + cluster = SUPER_CLUSTER( x, y ); + origin = SUPER_ORIGIN( x, y ); + normal = SUPER_NORMAL( x, y ); + floodlight = SUPER_FLOODLIGHT( x, y ); + + /* set default dirt */ + *floodlight = 0.0f; + + /* only look at mapped luxels */ + if( *cluster < 0 ) + continue; + + /* copy to trace */ + trace.cluster = *cluster; + VectorCopy( origin, trace.origin ); + VectorCopy( normal, trace.normal ); + + /* get floodlight */ + floodLightAmount = FloodLightForSample( &trace , lmFloodLightDistance, lmFloodLightLowQuality)*lmFloodLightIntensity; + + /* add floodlight */ + floodlight[0] += lmFloodLightRGB[0]*floodLightAmount; + floodlight[1] += lmFloodLightRGB[1]*floodLightAmount; + floodlight[2] += lmFloodLightRGB[2]*floodLightAmount; + floodlight[3] += floodlightDirectionScale; + } + } + + /* testing no filtering */ + return; + +#if 0 + + /* filter "dirt" */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + cluster = SUPER_CLUSTER( x, y ); + floodlight = SUPER_FLOODLIGHT(x, y ); + + /* filter dirt by adjacency to unmapped luxels */ + average = *floodlight; + samples = 1.0f; + for( sy = (y - 1); sy <= (y + 1); sy++ ) + { + if( sy < 0 || sy >= lm->sh ) + continue; + + for( sx = (x - 1); sx <= (x + 1); sx++ ) + { + if( sx < 0 || sx >= lm->sw || (sx == x && sy == y) ) + continue; + + /* get neighboring luxel */ + cluster = SUPER_CLUSTER( sx, sy ); + floodlight2 = SUPER_FLOODLIGHT( sx, sy ); + if( *cluster < 0 || *floodlight2 <= 0.0f ) + continue; + + /* add it */ + average += *floodlight2; + samples += 1.0f; + } + + /* bail */ + if( samples <= 0.0f ) + break; + } + + /* bail */ + if( samples <= 0.0f ) + continue; + + /* scale dirt */ + *floodlight = average / samples; + } + } +#endif +} + +void FloodLightRawLightmap( int rawLightmapNum ) +{ + rawLightmap_t *lm; + + /* bail if this number exceeds the number of raw lightmaps */ + if( rawLightmapNum >= numRawLightmaps ) + return; + /* get lightmap */ + lm = &rawLightmaps[ rawLightmapNum ]; + + /* global pass */ + if (floodlighty && floodlightIntensity) + FloodLightRawLightmapPass(lm, floodlightRGB, floodlightIntensity, floodlightDistance, floodlight_lowquality, floodlightDirectionScale); + + /* custom pass */ + if (lm->floodlightIntensity) + { + FloodLightRawLightmapPass(lm, lm->floodlightRGB, lm->floodlightIntensity, lm->floodlightDistance, qfalse, lm->floodlightDirectionScale); + numSurfacesFloodlighten += 1; + } +} + +void FloodlightRawLightmaps() +{ + Sys_Printf( "--- FloodlightRawLightmap ---\n" ); + numSurfacesFloodlighten = 0; + RunThreadsOnIndividual( numRawLightmaps, qtrue, FloodLightRawLightmap ); + Sys_Printf( "%9d custom lightmaps floodlighted\n", numSurfacesFloodlighten ); +} + +/* +FloodLightIlluminate() +illuminate floodlight into lightmap luxels +*/ + +void FloodlightIlluminateLightmap( rawLightmap_t *lm ) +{ + float *luxel, *floodlight, *deluxel, *normal; + int *cluster; + float brightness; + int x, y, lightmapNum; + + /* walk lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + + /* apply floodlight to each luxel */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get floodlight */ + floodlight = SUPER_FLOODLIGHT( x, y ); + if (!floodlight[0] && !floodlight[1] && !floodlight[2]) + continue; + + /* get cluster */ + cluster = SUPER_CLUSTER( x, y ); + + /* only process mapped luxels */ + if( *cluster < 0 ) + continue; + + /* get particulars */ + luxel = SUPER_LUXEL( lightmapNum, x, y ); + deluxel = SUPER_DELUXEL( x, y ); + + /* add to lightmap */ + luxel[0]+=floodlight[0]; + luxel[1]+=floodlight[1]; + luxel[2]+=floodlight[2]; + + if (luxel[3]==0) luxel[3]=1; + + /* add to deluxemap */ + if (deluxemap && floodlight[3] > 0) + { + vec3_t lightvector; + + normal = SUPER_NORMAL( x, y ); + brightness = RGBTOGRAY( floodlight ) * ( 1.0f/255.0f ) * floodlight[3]; + + // use AT LEAST this amount of contribution from ambient for the deluxemap, fixes points that receive ZERO light + if(brightness < 0.00390625f) + brightness = 0.00390625f; + + VectorScale( normal, brightness, lightvector ); + VectorAdd( deluxel, lightvector, deluxel ); + } + } + } + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/lightmaps.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/lightmaps.c new file mode 100644 index 00000000..13f5c533 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/lightmaps.c @@ -0,0 +1,119 @@ +/* +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 "qbsp.h" + + +/* + + Lightmap allocation has to be done after all flood filling and + visible surface determination. + +*/ + +int numSortShaders; +mapDrawSurface_t **surfsOnShader; +int allocatedSurfsOnShader; + + +int allocated[ LIGHTMAP_WIDTH ]; + +int numLightmaps = 1; +int c_exactLightmap = 0; +int c_planarPatch = 0; +int c_nonplanarLightmap = 0; + + +void PrepareNewLightmap( void ) { + memset( allocated, 0, sizeof( allocated ) ); + numLightmaps++; +} + +/* +=============== +AllocLMBlock + +returns a texture number and the position inside it +=============== +*/ +qboolean AllocLMBlock (int w, int h, int *x, int *y) +{ + int i, j; + int best, best2; + + best = LIGHTMAP_HEIGHT; + + for ( i=0 ; i <= LIGHTMAP_WIDTH-w ; i++ ) { + best2 = 0; + + for (j=0 ; j= best) { + break; + } + if (allocated[i+j] > best2) { + best2 = allocated[i+j]; + } + } + if (j == w) { // this is a valid spot + *x = i; + *y = best = best2; + } + } + + if (best + h > LIGHTMAP_HEIGHT) { + return qfalse; + } + + for (i=0 ; i> 8; + buffer[ 14 ] = height & 255; + buffer[ 15 ] = height >> 8; + buffer[ 16 ] = 24; + + /* swap rgb to bgr */ + c = (width * height * 3) + 18; + for( i = 18; i < c; i += 3 ) + { + buffer[ i ] = data[ i - 18 + 2 ]; /* blue */ + buffer[ i + 1 ] = data[ i - 18 + 1 ]; /* green */ + buffer[ i + 2 ] = data[ i - 18 + 0 ]; /* red */ + } + + /* write it and free the buffer */ + file = fopen( filename, "wb" ); + if( file == NULL ) + Error( "Unable to open %s for writing", filename ); + + /* flip vertically? */ + if( flip ) + { + fwrite( buffer, 1, 18, file ); + for( in = buffer + ((height - 1) * width * 3) + 18; in >= buffer; in -= (width * 3) ) + fwrite( in, 1, (width * 3), file ); + } + else + fwrite( buffer, 1, c, file ); + + /* close the file */ + fclose( file ); + free( buffer ); +} + + + +/* +ExportLightmaps() +exports the lightmaps as a list of numbered tga images +*/ + +void ExportLightmaps( void ) +{ + int i; + char dirname[ 1024 ], filename[ 1024 ]; + byte *lightmap; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- ExportLightmaps ---\n"); + + /* do some path mangling */ + strcpy( dirname, source ); + StripExtension( dirname ); + + /* sanity check */ + if( bspLightBytes == NULL ) + { + Sys_Printf( "WARNING: No BSP lightmap data\n" ); + return; + } + + /* make a directory for the lightmaps */ + Q_mkdir( dirname ); + + /* iterate through the lightmaps */ + for( i = 0, lightmap = bspLightBytes; lightmap < (bspLightBytes + numBSPLightBytes); i++, lightmap += (game->lightmapSize * game->lightmapSize * 3) ) + { + /* write a tga image out */ + sprintf( filename, "%s/lightmap_%04d.tga", dirname, i ); + Sys_Printf( "Writing %s\n", filename ); + WriteTGA24( filename, lightmap, game->lightmapSize, game->lightmapSize, qfalse ); + } +} + + + +/* +ExportLightmapsMain() +exports the lightmaps as a list of numbered tga images +*/ + +int ExportLightmapsMain( int argc, char **argv ) +{ + /* arg checking */ + if( argc < 1 ) + { + Sys_Printf( "Usage: q3map -export [-v] \n" ); + return 0; + } + + /* do some path mangling */ + strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + + /* load the bsp */ + Sys_Printf( "Loading %s\n", source ); + LoadBSPFile( source ); + + /* export the lightmaps */ + ExportLightmaps(); + + /* return to sender */ + return 0; +} + + + +/* +ImportLightmapsMain() +imports the lightmaps from a list of numbered tga images +*/ + +int ImportLightmapsMain( int argc, char **argv ) +{ + int i, x, y, len, width, height; + char dirname[ 1024 ], filename[ 1024 ]; + byte *lightmap, *buffer, *pixels, *in, *out; + + + /* arg checking */ + if( argc < 1 ) + { + Sys_Printf( "Usage: q3map -import [-v] \n" ); + return 0; + } + + /* do some path mangling */ + strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + + /* load the bsp */ + Sys_Printf( "Loading %s\n", source ); + LoadBSPFile( source ); + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- ImportLightmaps ---\n"); + + /* do some path mangling */ + strcpy( dirname, source ); + StripExtension( dirname ); + + /* sanity check */ + if( bspLightBytes == NULL ) + Error( "No lightmap data" ); + + /* make a directory for the lightmaps */ + Q_mkdir( dirname ); + + /* iterate through the lightmaps */ + for( i = 0, lightmap = bspLightBytes; lightmap < (bspLightBytes + numBSPLightBytes); i++, lightmap += (game->lightmapSize * game->lightmapSize * 3) ) + { + /* read a tga image */ + sprintf( filename, "%s/lightmap_%04d.tga", dirname, i ); + Sys_Printf( "Loading %s\n", filename ); + buffer = NULL; + len = vfsLoadFile( filename, (void*) &buffer, -1 ); + if( len < 0 ) + { + Sys_Printf( "WARNING: Unable to load image %s\n", filename ); + continue; + } + + /* parse file into an image */ + pixels = NULL; + LoadTGABuffer( buffer, buffer + len, &pixels, &width, &height ); + free( buffer ); + + /* sanity check it */ + if( pixels == NULL ) + { + Sys_Printf( "WARNING: Unable to load image %s\n", filename ); + continue; + } + if( width != game->lightmapSize || height != game->lightmapSize ) + Sys_Printf( "WARNING: Image %s is not the right size (%d, %d) != (%d, %d)\n", + filename, width, height, game->lightmapSize, game->lightmapSize ); + + /* copy the pixels */ + in = pixels; + for( y = 1; y <= game->lightmapSize; y++ ) + { + out = lightmap + ((game->lightmapSize - y) * game->lightmapSize * 3); + for( x = 0; x < game->lightmapSize; x++, in += 4, out += 3 ) + VectorCopy( in, out ); + } + + /* free the image */ + free( pixels ); + } + + /* write the bsp */ + Sys_Printf( "writing %s\n", source ); + WriteBSPFile( source ); + + /* return to sender */ + return 0; +} + + + +/* ------------------------------------------------------------------------------- + +this section deals with projecting a lightmap onto a raw drawsurface + +------------------------------------------------------------------------------- */ + +/* +CompareLightSurface() +compare function for qsort() +*/ + +static int CompareLightSurface( const void *a, const void *b ) +{ + shaderInfo_t *asi, *bsi; + + + /* get shaders */ + asi = surfaceInfos[ *((const int*) a) ].si; + bsi = surfaceInfos[ *((const int*) b) ].si; + + /* dummy check */ + if( asi == NULL ) + return -1; + if( bsi == NULL ) + return 1; + + /* compare shader names */ + return strcmp( asi->shader, bsi->shader ); +} + + + +/* +FinishRawLightmap() +allocates a raw lightmap's necessary buffers +*/ + +void FinishRawLightmap( rawLightmap_t *lm ) +{ + int i, j, c, size, *sc; + float is; + surfaceInfo_t *info; + + + /* sort light surfaces by shader name */ + qsort( &lightSurfaces[ lm->firstLightSurface ], lm->numLightSurfaces, sizeof( int ), CompareLightSurface ); + + /* count clusters */ + lm->numLightClusters = 0; + for( i = 0; i < lm->numLightSurfaces; i++ ) + { + /* get surface info */ + info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + i ] ]; + + /* add surface clusters */ + lm->numLightClusters += info->numSurfaceClusters; + } + + /* allocate buffer for clusters and copy */ + lm->lightClusters = safe_malloc( lm->numLightClusters * sizeof( *lm->lightClusters ) ); + c = 0; + for( i = 0; i < lm->numLightSurfaces; i++ ) + { + /* get surface info */ + info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + i ] ]; + + /* add surface clusters */ + for( j = 0; j < info->numSurfaceClusters; j++ ) + lm->lightClusters[ c++ ] = surfaceClusters[ info->firstSurfaceCluster + j ]; + } + + /* set styles */ + lm->styles[ 0 ] = LS_NORMAL; + for( i = 1; i < MAX_LIGHTMAPS; i++ ) + lm->styles[ i ] = LS_NONE; + + /* set supersampling size */ + lm->sw = lm->w * superSample; + lm->sh = lm->h * superSample; + + /* add to super luxel count */ + numRawSuperLuxels += (lm->sw * lm->sh); + + /* manipulate origin/vecs for supersampling */ + if( superSample > 1 && lm->vecs != NULL ) + { + /* calc inverse supersample */ + is = 1.0f / superSample; + + /* scale the vectors and shift the origin */ + #if 1 + /* new code that works for arbitrary supersampling values */ + VectorMA( lm->origin, -0.5, lm->vecs[ 0 ], lm->origin ); + VectorMA( lm->origin, -0.5, lm->vecs[ 1 ], lm->origin ); + VectorScale( lm->vecs[ 0 ], is, lm->vecs[ 0 ] ); + VectorScale( lm->vecs[ 1 ], is, lm->vecs[ 1 ] ); + VectorMA( lm->origin, is, lm->vecs[ 0 ], lm->origin ); + VectorMA( lm->origin, is, lm->vecs[ 1 ], lm->origin ); + #else + /* old code that only worked with a value of 2 */ + VectorScale( lm->vecs[ 0 ], is, lm->vecs[ 0 ] ); + VectorScale( lm->vecs[ 1 ], is, lm->vecs[ 1 ] ); + VectorMA( lm->origin, -is, lm->vecs[ 0 ], lm->origin ); + VectorMA( lm->origin, -is, lm->vecs[ 1 ], lm->origin ); + #endif + } + + /* allocate bsp lightmap storage */ + size = lm->w * lm->h * BSP_LUXEL_SIZE * sizeof( float ); + if( lm->bspLuxels[ 0 ] == NULL ) + lm->bspLuxels[ 0 ] = safe_malloc( size ); + memset( lm->bspLuxels[ 0 ], 0, size ); + + /* allocate radiosity lightmap storage */ + if( bounce ) + { + size = lm->w * lm->h * RAD_LUXEL_SIZE * sizeof( float ); + if( lm->radLuxels[ 0 ] == NULL ) + lm->radLuxels[ 0 ] = safe_malloc( size ); + memset( lm->radLuxels[ 0 ], 0, size ); + } + + /* allocate sampling lightmap storage */ + size = lm->sw * lm->sh * SUPER_LUXEL_SIZE * sizeof( float ); + if( lm->superLuxels[ 0 ] == NULL ) + lm->superLuxels[ 0 ] = safe_malloc( size ); + memset( lm->superLuxels[ 0 ], 0, size ); + + /* allocate origin map storage */ + size = lm->sw * lm->sh * SUPER_ORIGIN_SIZE * sizeof( float ); + if( lm->superOrigins == NULL ) + lm->superOrigins = safe_malloc( size ); + memset( lm->superOrigins, 0, size ); + + /* allocate normal map storage */ + size = lm->sw * lm->sh * SUPER_NORMAL_SIZE * sizeof( float ); + if( lm->superNormals == NULL ) + lm->superNormals = safe_malloc( size ); + memset( lm->superNormals, 0, size ); + + /* allocate floodlight map storage */ + size = lm->sw * lm->sh * SUPER_FLOODLIGHT_SIZE * sizeof( float ); + if( lm->superFloodLight == NULL ) + lm->superFloodLight = safe_malloc( size ); + memset( lm->superFloodLight, 0, size ); + + /* allocate cluster map storage */ + size = lm->sw * lm->sh * sizeof( int ); + if( lm->superClusters == NULL ) + lm->superClusters = safe_malloc( size ); + size = lm->sw * lm->sh; + sc = lm->superClusters; + for( i = 0; i < size; i++ ) + (*sc++) = CLUSTER_UNMAPPED; + + /* deluxemap allocation */ + if( deluxemap ) + { + /* allocate sampling deluxel storage */ + size = lm->sw * lm->sh * SUPER_DELUXEL_SIZE * sizeof( float ); + if( lm->superDeluxels == NULL ) + lm->superDeluxels = safe_malloc( size ); + memset( lm->superDeluxels, 0, size ); + + /* allocate bsp deluxel storage */ + size = lm->w * lm->h * BSP_DELUXEL_SIZE * sizeof( float ); + if( lm->bspDeluxels == NULL ) + lm->bspDeluxels = safe_malloc( size ); + memset( lm->bspDeluxels, 0, size ); + } + + /* add to count */ + numLuxels += (lm->sw * lm->sh); +} + + + +/* +AddPatchToRawLightmap() +projects a lightmap for a patch surface +since lightmap calculation for surfaces is now handled in a general way (light_ydnar.c), +it is no longer necessary for patch verts to fall exactly on a lightmap sample +based on AllocateLightmapForPatch() +*/ + +qboolean AddPatchToRawLightmap( int num, rawLightmap_t *lm ) +{ + bspDrawSurface_t *ds; + surfaceInfo_t *info; + int x, y; + bspDrawVert_t *verts, *a, *b; + vec3_t delta; + mesh_t src, *subdivided, *mesh; + float sBasis, tBasis, s, t; + float length, widthTable[ MAX_EXPANDED_AXIS ], heightTable[ MAX_EXPANDED_AXIS ]; + + + /* patches finish a raw lightmap */ + lm->finished = qtrue; + + /* get surface and info */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* make a temporary mesh from the drawsurf */ + src.width = ds->patchWidth; + src.height = ds->patchHeight; + src.verts = &yDrawVerts[ ds->firstVert ]; + //% subdivided = SubdivideMesh( src, 8, 512 ); + subdivided = SubdivideMesh2( src, info->patchIterations ); + + /* fit it to the curve and remove colinear verts on rows/columns */ + PutMeshOnCurve( *subdivided ); + mesh = RemoveLinearMeshColumnsRows( subdivided ); + FreeMesh( subdivided ); + + /* find the longest distance on each row/column */ + verts = mesh->verts; + memset( widthTable, 0, sizeof( widthTable ) ); + memset( heightTable, 0, sizeof( heightTable ) ); + for( y = 0; y < mesh->height; y++ ) + { + for( x = 0; x < mesh->width; x++ ) + { + /* get width */ + if( x + 1 < mesh->width ) + { + a = &verts[ (y * mesh->width) + x ]; + b = &verts[ (y * mesh->width) + x + 1 ]; + VectorSubtract( a->xyz, b->xyz, delta ); + length = VectorLength( delta ); + if( length > widthTable[ x ] ) + widthTable[ x ] = length; + } + + /* get height */ + if( y + 1 < mesh->height ) + { + a = &verts[ (y * mesh->width) + x ]; + b = &verts[ ((y + 1) * mesh->width) + x ]; + VectorSubtract( a->xyz, b->xyz, delta ); + length = VectorLength( delta ); + if( length > heightTable[ y ] ) + heightTable[ y ] = length; + } + } + } + + /* determine lightmap width */ + length = 0; + for( x = 0; x < (mesh->width - 1); x++ ) + length += widthTable[ x ]; + lm->w = ceil( length / lm->sampleSize ) + 1; + if( lm->w < ds->patchWidth ) + lm->w = ds->patchWidth; + if( lm->w > lm->customWidth ) + lm->w = lm->customWidth; + sBasis = (float) (lm->w - 1) / (float) (ds->patchWidth - 1); + + /* determine lightmap height */ + length = 0; + for( y = 0; y < (mesh->height - 1); y++ ) + length += heightTable[ y ]; + lm->h = ceil( length / lm->sampleSize ) + 1; + if( lm->h < ds->patchHeight ) + lm->h = ds->patchHeight; + if( lm->h > lm->customHeight ) + lm->h = lm->customHeight; + tBasis = (float) (lm->h - 1) / (float) (ds->patchHeight - 1); + + /* free the temporary mesh */ + FreeMesh( mesh ); + + /* set the lightmap texture coordinates in yDrawVerts */ + lm->wrap[ 0 ] = qtrue; + lm->wrap[ 1 ] = qtrue; + verts = &yDrawVerts[ ds->firstVert ]; + for( y = 0; y < ds->patchHeight; y++ ) + { + t = (tBasis * y) + 0.5f; + for( x = 0; x < ds->patchWidth; x++ ) + { + s = (sBasis * x) + 0.5f; + verts[ (y * ds->patchWidth) + x ].lightmap[ 0 ][ 0 ] = s * superSample; + verts[ (y * ds->patchWidth) + x ].lightmap[ 0 ][ 1 ] = t * superSample; + + if( y == 0 && !VectorCompare( verts[ x ].xyz, verts[ ((ds->patchHeight - 1) * ds->patchWidth) + x ].xyz ) ) + lm->wrap[ 1 ] = qfalse; + } + + if( !VectorCompare( verts[ (y * ds->patchWidth) ].xyz, verts[ (y * ds->patchWidth) + (ds->patchWidth - 1) ].xyz ) ) + lm->wrap[ 0 ] = qfalse; + } + + /* debug code: */ + //% Sys_Printf( "wrap S: %d wrap T: %d\n", lm->wrap[ 0 ], lm->wrap[ 1 ] ); + //% if( lm->w > (ds->lightmapWidth & 0xFF) || lm->h > (ds->lightmapHeight & 0xFF) ) + //% Sys_Printf( "Patch lightmap: (%3d %3d) > (%3d, %3d)\n", lm->w, lm->h, ds->lightmapWidth & 0xFF, ds->lightmapHeight & 0xFF ); + //% ds->lightmapWidth = lm->w | (ds->lightmapWidth & 0xFFFF0000); + //% ds->lightmapHeight = lm->h | (ds->lightmapHeight & 0xFFFF0000); + + /* add to counts */ + numPatchesLightmapped++; + + /* return */ + return qtrue; +} + + + +/* +AddSurfaceToRawLightmap() +projects a lightmap for a surface +based on AllocateLightmapForSurface() +*/ + +qboolean AddSurfaceToRawLightmap( int num, rawLightmap_t *lm ) +{ + bspDrawSurface_t *ds, *ds2; + surfaceInfo_t *info, *info2; + int num2, n, i, axisNum; + float s, t, d, len, sampleSize; + vec3_t mins, maxs, origin, faxis, size, exactSize, delta, normalized, vecs[ 2 ]; + vec4_t plane; + bspDrawVert_t *verts; + + + /* get surface and info */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* add the surface to the raw lightmap */ + lightSurfaces[ numLightSurfaces++ ] = num; + lm->numLightSurfaces++; + + /* does this raw lightmap already have any surfaces? */ + if( lm->numLightSurfaces > 1 ) + { + /* surface and raw lightmap must have the same lightmap projection axis */ + if( VectorCompare( info->axis, lm->axis ) == qfalse ) + return qfalse; + + /* match identical attributes */ + if( info->sampleSize != lm->sampleSize || + info->entityNum != lm->entityNum || + info->recvShadows != lm->recvShadows || + info->si->lmCustomWidth != lm->customWidth || + info->si->lmCustomHeight != lm->customHeight || + info->si->lmBrightness != lm->brightness || + info->si->lmFilterRadius != lm->filterRadius || + info->si->splotchFix != lm->splotchFix ) + return qfalse; + + /* surface bounds must intersect with raw lightmap bounds */ + for( i = 0; i < 3; i++ ) + { + if( info->mins[ i ] > lm->maxs[ i ] ) + return qfalse; + if( info->maxs[ i ] < lm->mins[ i ] ) + return qfalse; + } + + /* plane check (fixme: allow merging of nonplanars) */ + if( info->si->lmMergable == qfalse ) + { + if( info->plane == NULL || lm->plane == NULL ) + return qfalse; + + /* compare planes */ + for( i = 0; i < 4; i++ ) + if( fabs( info->plane[ i ] - lm->plane[ i ] ) > EQUAL_EPSILON ) + return qfalse; + } + + /* debug code hacking */ + //% if( lm->numLightSurfaces > 1 ) + //% return qfalse; + } + + /* set plane */ + if( info->plane == NULL ) + lm->plane = NULL; + + /* add surface to lightmap bounds */ + AddPointToBounds( info->mins, lm->mins, lm->maxs ); + AddPointToBounds( info->maxs, lm->mins, lm->maxs ); + + /* check to see if this is a non-planar patch */ + if( ds->surfaceType == MST_PATCH && + lm->axis[ 0 ] == 0.0f && lm->axis[ 1 ] == 0.0f && lm->axis[ 2 ] == 0.0f ) + return AddPatchToRawLightmap( num, lm ); + + /* start with initially requested sample size */ + sampleSize = lm->sampleSize; + + /* round to the lightmap resolution */ + for( i = 0; i < 3; i++ ) + { + exactSize[ i ] = lm->maxs[ i ] - lm->mins[ i ]; + mins[ i ] = sampleSize * floor( lm->mins[ i ] / sampleSize ); + maxs[ i ] = sampleSize * ceil( lm->maxs[ i ] / sampleSize ); + size[ i ] = (maxs[ i ] - mins[ i ]) / sampleSize + 1.0f; + + /* hack (god this sucks) */ + if( size[ i ] > lm->customWidth || size[ i ] > lm->customHeight || (lmLimitSize && size[i] > lmLimitSize)) + { + i = -1; + sampleSize += 1.0f; + } + } + + if(sampleSize != lm->sampleSize && lmLimitSize == 0) + { + Sys_FPrintf(SYS_VRB,"WARNING: surface at (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) too large for desired samplesize/lightmapsize/lightmapscale combination, increased samplesize from %d to %d\n", + info->mins[0], + info->mins[1], + info->mins[2], + info->maxs[0], + info->maxs[1], + info->maxs[2], + lm->sampleSize, + (int) sampleSize); + } + + /* set actual sample size */ + lm->actualSampleSize = sampleSize; + + /* fixme: copy rounded mins/maxes to lightmap record? */ + if( lm->plane == NULL ) + { + VectorCopy( mins, lm->mins ); + VectorCopy( maxs, lm->maxs ); + VectorCopy( mins, origin ); + } + + /* set lightmap origin */ + VectorCopy( lm->mins, origin ); + + /* make absolute axis */ + faxis[ 0 ] = fabs( lm->axis[ 0 ] ); + faxis[ 1 ] = fabs( lm->axis[ 1 ] ); + faxis[ 2 ] = fabs( lm->axis[ 2 ] ); + + /* clear out lightmap vectors */ + memset( vecs, 0, sizeof( vecs ) ); + + /* classify the plane (x y or z major) (ydnar: biased to z axis projection) */ + if( faxis[ 2 ] >= faxis[ 0 ] && faxis[ 2 ] >= faxis[ 1 ] ) + { + axisNum = 2; + lm->w = size[ 0 ]; + lm->h = size[ 1 ]; + vecs[ 0 ][ 0 ] = 1.0f / sampleSize; + vecs[ 1 ][ 1 ] = 1.0f / sampleSize; + } + else if( faxis[ 0 ] >= faxis[ 1 ] && faxis[ 0 ] >= faxis[ 2 ] ) + { + axisNum = 0; + lm->w = size[ 1 ]; + lm->h = size[ 2 ]; + vecs[ 0 ][ 1 ] = 1.0f / sampleSize; + vecs[ 1 ][ 2 ] = 1.0f / sampleSize; + } + else + { + axisNum = 1; + lm->w = size[ 0 ]; + lm->h = size[ 2 ]; + vecs[ 0 ][ 0 ] = 1.0f / sampleSize; + vecs[ 1 ][ 2 ] = 1.0f / sampleSize; + } + + /* check for bogus axis */ + if( faxis[ axisNum ] == 0.0f ) + { + Sys_Printf( "WARNING: ProjectSurfaceLightmap: Chose a 0 valued axis\n" ); + lm->w = lm->h = 0; + return qfalse; + } + + /* store the axis number in the lightmap */ + lm->axisNum = axisNum; + + /* walk the list of surfaces on this raw lightmap */ + for( n = 0; n < lm->numLightSurfaces; n++ ) + { + /* get surface */ + num2 = lightSurfaces[ lm->firstLightSurface + n ]; + ds2 = &bspDrawSurfaces[ num2 ]; + info2 = &surfaceInfos[ num2 ]; + verts = &yDrawVerts[ ds2->firstVert ]; + + /* set the lightmap texture coordinates in yDrawVerts in [0, superSample * lm->customWidth] space */ + for( i = 0; i < ds2->numVerts; i++ ) + { + VectorSubtract( verts[ i ].xyz, origin, delta ); + s = DotProduct( delta, vecs[ 0 ] ) + 0.5f; + t = DotProduct( delta, vecs[ 1 ] ) + 0.5f; + verts[ i ].lightmap[ 0 ][ 0 ] = s * superSample; + verts[ i ].lightmap[ 0 ][ 1 ] = t * superSample; + + if( s > (float) lm->w || t > (float) lm->h ) + { + Sys_FPrintf( SYS_VRB, "WARNING: Lightmap texture coords out of range: S %1.4f > %3d || T %1.4f > %3d\n", + s, lm->w, t, lm->h ); + } + } + } + + /* get first drawsurface */ + num2 = lightSurfaces[ lm->firstLightSurface ]; + ds2 = &bspDrawSurfaces[ num2 ]; + info2 = &surfaceInfos[ num2 ]; + verts = &yDrawVerts[ ds2->firstVert ]; + + /* calculate lightmap origin */ + if( VectorLength( ds2->lightmapVecs[ 2 ] ) ) + VectorCopy( ds2->lightmapVecs[ 2 ], plane ); + else + VectorCopy( lm->axis, plane ); + plane[ 3 ] = DotProduct( verts[ 0 ].xyz, plane ); + + VectorCopy( origin, lm->origin ); + d = DotProduct( lm->origin, plane ) - plane[ 3 ]; + d /= plane[ axisNum ]; + lm->origin[ axisNum ] -= d; + + /* legacy support */ + VectorCopy( lm->origin, ds->lightmapOrigin ); + + /* for planar surfaces, create lightmap vectors for st->xyz conversion */ + if( VectorLength( ds->lightmapVecs[ 2 ] ) || 1 ) /* ydnar: can't remember what exactly i was thinking here... */ + { + /* allocate space for the vectors */ + lm->vecs = safe_malloc( 3 * sizeof( vec3_t ) ); + memset( lm->vecs, 0, 3 * sizeof( vec3_t ) ); + VectorCopy( ds->lightmapVecs[ 2 ], lm->vecs[ 2 ] ); + + /* project stepped lightmap blocks and subtract to get planevecs */ + for( i = 0; i < 2; i++ ) + { + len = VectorNormalize( vecs[ i ], normalized ); + VectorScale( normalized, (1.0 / len), lm->vecs[ i ] ); + d = DotProduct( lm->vecs[ i ], plane ); + d /= plane[ axisNum ]; + lm->vecs[ i ][ axisNum ] -= d; + } + } + else + { + /* lightmap vectors are useless on a non-planar surface */ + lm->vecs = NULL; + } + + /* add to counts */ + if( ds->surfaceType == MST_PATCH ) + { + numPatchesLightmapped++; + if( lm->plane != NULL ) + numPlanarPatchesLightmapped++; + } + else + { + if( lm->plane != NULL ) + numPlanarsLightmapped++; + else + numNonPlanarsLightmapped++; + } + + /* return */ + return qtrue; +} + + + +/* +CompareSurfaceInfo() +compare function for qsort() +*/ + +static int CompareSurfaceInfo( const void *a, const void *b ) +{ + surfaceInfo_t *aInfo, *bInfo; + int i; + + + /* get surface info */ + aInfo = &surfaceInfos[ *((const int*) a) ]; + bInfo = &surfaceInfos[ *((const int*) b) ]; + + /* model first */ + if( aInfo->modelindex < bInfo->modelindex ) + return 1; + else if( aInfo->modelindex > bInfo->modelindex ) + return -1; + + /* then lightmap status */ + if( aInfo->hasLightmap < bInfo->hasLightmap ) + return 1; + else if( aInfo->hasLightmap > bInfo->hasLightmap ) + return -1; + + /* 27: then shader! */ + if (aInfo->si < bInfo->si) + return 1; + else if (aInfo->si > bInfo->si) + return -1; + + + /* then lightmap sample size */ + if( aInfo->sampleSize < bInfo->sampleSize ) + return 1; + else if( aInfo->sampleSize > bInfo->sampleSize ) + return -1; + + /* then lightmap axis */ + for( i = 0; i < 3; i++ ) + { + if( aInfo->axis[ i ] < bInfo->axis[ i ] ) + return 1; + else if( aInfo->axis[ i ] > bInfo->axis[ i ] ) + return -1; + } + + /* then plane */ + if( aInfo->plane == NULL && bInfo->plane != NULL ) + return 1; + else if( aInfo->plane != NULL && bInfo->plane == NULL ) + return -1; + else if( aInfo->plane != NULL && bInfo->plane != NULL ) + { + for( i = 0; i < 4; i++ ) + { + if( aInfo->plane[ i ] < bInfo->plane[ i ] ) + return 1; + else if( aInfo->plane[ i ] > bInfo->plane[ i ] ) + return -1; + } + } + + /* then position in world */ + for( i = 0; i < 3; i++ ) + { + if( aInfo->mins[ i ] < bInfo->mins[ i ] ) + return 1; + else if( aInfo->mins[ i ] > bInfo->mins[ i ] ) + return -1; + } + + /* these are functionally identical (this should almost never happen) */ + return 0; +} + + + +/* +SetupSurfaceLightmaps() +allocates lightmaps for every surface in the bsp that needs one +this depends on yDrawVerts being allocated +*/ + +void SetupSurfaceLightmaps( void ) +{ + int i, j, k, s,num, num2; + bspModel_t *model; + bspLeaf_t *leaf; + bspDrawSurface_t *ds, *ds2; + surfaceInfo_t *info, *info2; + rawLightmap_t *lm; + qboolean added; + vec3_t mapSize, entityOrigin; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- SetupSurfaceLightmaps ---\n"); + + /* determine supersample amount */ + if( superSample < 1 ) + superSample = 1; + else if( superSample > 8 ) + { + Sys_Printf( "WARNING: Insane supersampling amount (%d) detected.\n", superSample ); + superSample = 8; + } + + /* clear map bounds */ + ClearBounds( mapMins, mapMaxs ); + + /* allocate a list of surface clusters */ + numSurfaceClusters = 0; + maxSurfaceClusters = numBSPLeafSurfaces; + surfaceClusters = safe_malloc( maxSurfaceClusters * sizeof( *surfaceClusters ) ); + memset( surfaceClusters, 0, maxSurfaceClusters * sizeof( *surfaceClusters ) ); + + /* allocate a list for per-surface info */ + surfaceInfos = safe_malloc( numBSPDrawSurfaces * sizeof( *surfaceInfos ) ); + memset( surfaceInfos, 0, numBSPDrawSurfaces * sizeof( *surfaceInfos ) ); + for( i = 0; i < numBSPDrawSurfaces; i++ ) + surfaceInfos[ i ].childSurfaceNum = -1; + + /* allocate a list of surface indexes to be sorted */ + sortSurfaces = safe_malloc( numBSPDrawSurfaces * sizeof( int ) ); + memset( sortSurfaces, 0, numBSPDrawSurfaces * sizeof( int ) ); + + /* walk each model in the bsp */ + for( i = 0; i < numBSPModels; i++ ) + { + /* get model */ + model = &bspModels[ i ]; + + /* walk the list of surfaces in this model and fill out the info structs */ + for( j = 0; j < model->numBSPSurfaces; j++ ) + { + /* make surface index */ + num = model->firstBSPSurface + j; + + /* copy index to sort list */ + sortSurfaces[ num ] = num; + + /* get surface and info */ + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* set entity origin */ + if( ds->numVerts > 0 ) + VectorSubtract( yDrawVerts[ ds->firstVert ].xyz, bspDrawVerts[ ds->firstVert ].xyz, entityOrigin ); + else + VectorClear( entityOrigin ); + + /* basic setup */ + info->modelindex = i; + info->lm = NULL; + info->plane = NULL; + info->firstSurfaceCluster = numSurfaceClusters; + + /* get extra data */ + info->si = GetSurfaceExtraShaderInfo( num ); + if( info->si == NULL ) + info->si = ShaderInfoForShader( bspShaders[ ds->shaderNum ].shader ); + info->parentSurfaceNum = GetSurfaceExtraParentSurfaceNum( num ); + info->entityNum = GetSurfaceExtraEntityNum( num ); + info->castShadows = GetSurfaceExtraCastShadows( num ); + info->recvShadows = GetSurfaceExtraRecvShadows( num ); + info->sampleSize = GetSurfaceExtraSampleSize( num ); + info->longestCurve = GetSurfaceExtraLongestCurve( num ); + info->patchIterations = IterationsForCurve( info->longestCurve, patchSubdivisions ); + GetSurfaceExtraLightmapAxis( num, info->axis ); + + /* mark parent */ + if( info->parentSurfaceNum >= 0 ) + surfaceInfos[ info->parentSurfaceNum ].childSurfaceNum = j; + + /* determine surface bounds */ + ClearBounds( info->mins, info->maxs ); + for( k = 0; k < ds->numVerts; k++ ) + { + AddPointToBounds( yDrawVerts[ ds->firstVert + k ].xyz, mapMins, mapMaxs ); + AddPointToBounds( yDrawVerts[ ds->firstVert + k ].xyz, info->mins, info->maxs ); + } + + /* find all the bsp clusters the surface falls into */ + for( k = 0; k < numBSPLeafs; k++ ) + { + /* get leaf */ + leaf = &bspLeafs[ k ]; + + /* test bbox */ + if( leaf->mins[ 0 ] > info->maxs[ 0 ] || leaf->maxs[ 0 ] < info->mins[ 0 ] || + leaf->mins[ 1 ] > info->maxs[ 1 ] || leaf->maxs[ 1 ] < info->mins[ 1 ] || + leaf->mins[ 2 ] > info->maxs[ 2 ] || leaf->maxs[ 2 ] < info->mins[ 2 ] ) + continue; + + /* test leaf surfaces */ + for( s = 0; s < leaf->numBSPLeafSurfaces; s++ ) + { + if( bspLeafSurfaces[ leaf->firstBSPLeafSurface + s ] == num ) + { + if( numSurfaceClusters >= maxSurfaceClusters ) + Error( "maxSurfaceClusters exceeded" ); + surfaceClusters[ numSurfaceClusters ] = leaf->cluster; + numSurfaceClusters++; + info->numSurfaceClusters++; + } + } + } + + /* determine if surface is planar */ + if( VectorLength( ds->lightmapVecs[ 2 ] ) > 0.0f ) + { + /* make a plane */ + info->plane = safe_malloc( 4 * sizeof( float ) ); + VectorCopy( ds->lightmapVecs[ 2 ], info->plane ); + info->plane[ 3 ] = DotProduct( yDrawVerts[ ds->firstVert ].xyz, info->plane ); + } + + /* determine if surface requires a lightmap */ + if( ds->surfaceType == MST_TRIANGLE_SOUP || + ds->surfaceType == MST_FOLIAGE || + (info->si->compileFlags & C_VERTEXLIT) ) + numSurfsVertexLit++; + else + { + numSurfsLightmapped++; + info->hasLightmap = qtrue; + } + } + } + + /* find longest map distance */ + VectorSubtract( mapMaxs, mapMins, mapSize ); + maxMapDistance = VectorLength( mapSize ); + + /* sort the surfaces info list */ + qsort( sortSurfaces, numBSPDrawSurfaces, sizeof( int ), CompareSurfaceInfo ); + + /* allocate a list of surfaces that would go into raw lightmaps */ + numLightSurfaces = 0; + lightSurfaces = safe_malloc( numSurfsLightmapped * sizeof( int ) ); + memset( lightSurfaces, 0, numSurfsLightmapped * sizeof( int ) ); + + /* allocate a list of raw lightmaps */ + numRawSuperLuxels = 0; + numRawLightmaps = 0; + rawLightmaps = safe_malloc( numSurfsLightmapped * sizeof( *rawLightmaps ) ); + memset( rawLightmaps, 0, numSurfsLightmapped * sizeof( *rawLightmaps ) ); + + /* walk the list of sorted surfaces */ + for( i = 0; i < numBSPDrawSurfaces; i++ ) + { + /* get info and attempt early out */ + num = sortSurfaces[ i ]; + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + if( info->hasLightmap == qfalse || info->lm != NULL || info->parentSurfaceNum >= 0 ) + continue; + + /* allocate a new raw lightmap */ + lm = &rawLightmaps[ numRawLightmaps ]; + numRawLightmaps++; + + /* set it up */ + lm->splotchFix = info->si->splotchFix; + lm->firstLightSurface = numLightSurfaces; + lm->numLightSurfaces = 0; + /* vortex: multiply lightmap sample size by -samplescale */ + if (sampleScale > 0) + lm->sampleSize = info->sampleSize*sampleScale; + else + lm->sampleSize = info->sampleSize; + lm->actualSampleSize = lm->sampleSize; + lm->entityNum = info->entityNum; + lm->recvShadows = info->recvShadows; + lm->brightness = info->si->lmBrightness; + lm->filterRadius = info->si->lmFilterRadius; + VectorCopy(info->si->floodlightRGB, lm->floodlightRGB); + lm->floodlightDistance = info->si->floodlightDistance; + lm->floodlightIntensity = info->si->floodlightIntensity; + lm->floodlightDirectionScale = info->si->floodlightDirectionScale; + VectorCopy( info->axis, lm->axis ); + lm->plane = info->plane; + VectorCopy( info->mins, lm->mins ); + VectorCopy( info->maxs, lm->maxs ); + + lm->customWidth = info->si->lmCustomWidth; + lm->customHeight = info->si->lmCustomHeight; + + /* add the surface to the raw lightmap */ + AddSurfaceToRawLightmap( num, lm ); + info->lm = lm; + + /* do an exhaustive merge */ + added = qtrue; + while( added ) + { + /* walk the list of surfaces again */ + added = qfalse; + for( j = i + 1; j < numBSPDrawSurfaces && lm->finished == qfalse; j++ ) + { + /* get info and attempt early out */ + num2 = sortSurfaces[ j ]; + ds2 = &bspDrawSurfaces[ num2 ]; + info2 = &surfaceInfos[ num2 ]; + if( info2->hasLightmap == qfalse || info2->lm != NULL ) + continue; + + /* add the surface to the raw lightmap */ + if( AddSurfaceToRawLightmap( num2, lm ) ) + { + info2->lm = lm; + added = qtrue; + } + else + { + /* back up one */ + lm->numLightSurfaces--; + numLightSurfaces--; + } + } + } + + /* finish the lightmap and allocate the various buffers */ + FinishRawLightmap( lm ); + } + + /* allocate vertex luxel storage */ + for( k = 0; k < MAX_LIGHTMAPS; k++ ) + { + vertexLuxels[ k ] = safe_malloc( numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); + memset( vertexLuxels[ k ], 0, numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); + radVertexLuxels[ k ] = safe_malloc( numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); + memset( radVertexLuxels[ k ], 0, numBSPDrawVerts * VERTEX_LUXEL_SIZE * sizeof( float ) ); + } + + /* emit some stats */ + Sys_FPrintf( SYS_VRB, "%9d surfaces\n", numBSPDrawSurfaces ); + Sys_FPrintf( SYS_VRB, "%9d raw lightmaps\n", numRawLightmaps ); + Sys_FPrintf( SYS_VRB, "%9d surfaces vertex lit\n", numSurfsVertexLit ); + Sys_FPrintf( SYS_VRB, "%9d surfaces lightmapped\n", numSurfsLightmapped ); + Sys_FPrintf( SYS_VRB, "%9d planar surfaces lightmapped\n", numPlanarsLightmapped ); + Sys_FPrintf( SYS_VRB, "%9d non-planar surfaces lightmapped\n", numNonPlanarsLightmapped ); + Sys_FPrintf( SYS_VRB, "%9d patches lightmapped\n", numPatchesLightmapped ); + Sys_FPrintf( SYS_VRB, "%9d planar patches lightmapped\n", numPlanarPatchesLightmapped ); +} + + + +/* +StitchSurfaceLightmaps() +stitches lightmap edges +2002-11-20 update: use this func only for stitching nonplanar patch lightmap seams +*/ + +#define MAX_STITCH_CANDIDATES 32 +#define MAX_STITCH_LUXELS 64 + +void StitchSurfaceLightmaps( void ) +{ + int i, j, x, y, x2, y2, *cluster, *cluster2, + numStitched, numCandidates, numLuxels, f, fOld, start; + rawLightmap_t *lm, *a, *b, *c[ MAX_STITCH_CANDIDATES ]; + float *luxel, *luxel2, *origin, *origin2, *normal, *normal2, + sampleSize, average[ 3 ], totalColor, ootc, *luxels[ MAX_STITCH_LUXELS ]; + + + /* disabled for now */ + return; + + /* note it */ + Sys_Printf( "--- StitchSurfaceLightmaps ---\n"); + + /* init pacifier */ + fOld = -1; + start = I_FloatTime(); + + /* walk the list of raw lightmaps */ + numStitched = 0; + for( i = 0; i < numRawLightmaps; i++ ) + { + /* print pacifier */ + f = 10 * i / numRawLightmaps; + if( f != fOld ) + { + fOld = f; + Sys_Printf( "%i...", f ); + } + + /* get lightmap a */ + a = &rawLightmaps[ i ]; + + /* walk rest of lightmaps */ + numCandidates = 0; + for( j = i + 1; j < numRawLightmaps && numCandidates < MAX_STITCH_CANDIDATES; j++ ) + { + /* get lightmap b */ + b = &rawLightmaps[ j ]; + + /* test bounding box */ + if( a->mins[ 0 ] > b->maxs[ 0 ] || a->maxs[ 0 ] < b->mins[ 0 ] || + a->mins[ 1 ] > b->maxs[ 1 ] || a->maxs[ 1 ] < b->mins[ 1 ] || + a->mins[ 2 ] > b->maxs[ 2 ] || a->maxs[ 2 ] < b->mins[ 2 ] ) + continue; + + /* add candidate */ + c[ numCandidates++ ] = b; + } + + /* walk luxels */ + for( y = 0; y < a->sh; y++ ) + { + for( x = 0; x < a->sw; x++ ) + { + /* ignore unmapped/unlit luxels */ + lm = a; + cluster = SUPER_CLUSTER( x, y ); + if( *cluster == CLUSTER_UNMAPPED ) + continue; + luxel = SUPER_LUXEL( 0, x, y ); + if( luxel[ 3 ] <= 0.0f ) + continue; + + /* get particulars */ + origin = SUPER_ORIGIN( x, y ); + normal = SUPER_NORMAL( x, y ); + + /* walk candidate list */ + for( j = 0; j < numCandidates; j++ ) + { + /* get candidate */ + b = c[ j ]; + lm = b; + + /* set samplesize to the smaller of the pair */ + sampleSize = 0.5f * (a->actualSampleSize < b->actualSampleSize ? a->actualSampleSize : b->actualSampleSize); + + /* test bounding box */ + if( origin[ 0 ] < (b->mins[ 0 ] - sampleSize) || (origin[ 0 ] > b->maxs[ 0 ] + sampleSize) || + origin[ 1 ] < (b->mins[ 1 ] - sampleSize) || (origin[ 1 ] > b->maxs[ 1 ] + sampleSize) || + origin[ 2 ] < (b->mins[ 2 ] - sampleSize) || (origin[ 2 ] > b->maxs[ 2 ] + sampleSize) ) + continue; + + /* walk candidate luxels */ + VectorClear( average ); + numLuxels = 0; + totalColor = 0.0f; + for( y2 = 0; y2 < b->sh && numLuxels < MAX_STITCH_LUXELS; y2++ ) + { + for( x2 = 0; x2 < b->sw && numLuxels < MAX_STITCH_LUXELS; x2++ ) + { + /* ignore same luxels */ + if( a == b && abs( x - x2 ) <= 1 && abs( y - y2 ) <= 1 ) + continue; + + /* ignore unmapped/unlit luxels */ + cluster2 = SUPER_CLUSTER( x2, y2 ); + if( *cluster2 == CLUSTER_UNMAPPED ) + continue; + luxel2 = SUPER_LUXEL( 0, x2, y2 ); + if( luxel2[ 3 ] <= 0.0f ) + continue; + + /* get particulars */ + origin2 = SUPER_ORIGIN( x2, y2 ); + normal2 = SUPER_NORMAL( x2, y2 ); + + /* test normal */ + if( DotProduct( normal, normal2 ) < 0.5f ) + continue; + + /* test bounds */ + if( fabs( origin[ 0 ] - origin2[ 0 ] ) > sampleSize || + fabs( origin[ 1 ] - origin2[ 1 ] ) > sampleSize || + fabs( origin[ 2 ] - origin2[ 2 ] ) > sampleSize ) + continue; + + /* add luxel */ + //% VectorSet( luxel2, 255, 0, 255 ); + luxels[ numLuxels++ ] = luxel2; + VectorAdd( average, luxel2, average ); + totalColor += luxel2[ 3 ]; + } + } + + /* early out */ + if( numLuxels == 0 ) + continue; + + /* scale average */ + ootc = 1.0f / totalColor; + VectorScale( average, ootc, luxel ); + luxel[ 3 ] = 1.0f; + numStitched++; + } + } + } + } + + /* emit statistics */ + Sys_Printf( " (%i)\n", (int) (I_FloatTime() - start) ); + Sys_FPrintf( SYS_VRB, "%9d luxels stitched\n", numStitched ); +} + + + +/* +CompareBSPLuxels() +compares two surface lightmaps' bsp luxels, ignoring occluded luxels +*/ + +#define SOLID_EPSILON 0.0625 +#define LUXEL_TOLERANCE 0.0025 +#define LUXEL_COLOR_FRAC 0.001302083 /* 1 / 3 / 256 */ + +static qboolean CompareBSPLuxels( rawLightmap_t *a, int aNum, rawLightmap_t *b, int bNum ) +{ + rawLightmap_t *lm; + int x, y; + double delta, total, rd, gd, bd; + float *aLuxel, *bLuxel; + + + /* styled lightmaps will never be collapsed to non-styled lightmaps when there is _minlight */ + if( (minLight[ 0 ] || minLight[ 1 ] || minLight[ 2 ]) && + ((aNum == 0 && bNum != 0) || (aNum != 0 && bNum == 0)) ) + return qfalse; + + /* basic tests */ + if( a->customWidth != b->customWidth || a->customHeight != b->customHeight || + a->brightness != b->brightness || + a->solid[ aNum ] != b->solid[ bNum ] || + a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) + return qfalse; + + /* compare solid color lightmaps */ + if( a->solid[ aNum ] && b->solid[ bNum ] ) + { + /* get deltas */ + rd = fabs( a->solidColor[ aNum ][ 0 ] - b->solidColor[ bNum ][ 0 ] ); + gd = fabs( a->solidColor[ aNum ][ 1 ] - b->solidColor[ bNum ][ 1 ] ); + bd = fabs( a->solidColor[ aNum ][ 2 ] - b->solidColor[ bNum ][ 2 ] ); + + /* compare color */ + if( rd > SOLID_EPSILON || gd > SOLID_EPSILON|| bd > SOLID_EPSILON ) + return qfalse; + + /* okay */ + return qtrue; + } + + /* compare nonsolid lightmaps */ + if( a->w != b->w || a->h != b->h ) + return qfalse; + + /* compare luxels */ + delta = 0.0; + total = 0.0; + for( y = 0; y < a->h; y++ ) + { + for( x = 0; x < a->w; x++ ) + { + /* increment total */ + total += 1.0; + + /* get luxels */ + lm = a; aLuxel = BSP_LUXEL( aNum, x, y ); + lm = b; bLuxel = BSP_LUXEL( bNum, x, y ); + + /* ignore unused luxels */ + if( aLuxel[ 0 ] < 0 || bLuxel[ 0 ] < 0 ) + continue; + + /* get deltas */ + rd = fabs( aLuxel[ 0 ] - bLuxel[ 0 ] ); + gd = fabs( aLuxel[ 1 ] - bLuxel[ 1 ] ); + bd = fabs( aLuxel[ 2 ] - bLuxel[ 2 ] ); + + /* 2003-09-27: compare individual luxels */ + if( rd > 3.0 || gd > 3.0 || bd > 3.0 ) + return qfalse; + + /* compare (fixme: take into account perceptual differences) */ + delta += rd * LUXEL_COLOR_FRAC; + delta += gd * LUXEL_COLOR_FRAC; + delta += bd * LUXEL_COLOR_FRAC; + + /* is the change too high? */ + if( total > 0.0 && ((delta / total) > LUXEL_TOLERANCE) ) + return qfalse; + } + } + + /* made it this far, they must be identical (or close enough) */ + return qtrue; +} + + + +/* +MergeBSPLuxels() +merges two surface lightmaps' bsp luxels, overwriting occluded luxels +*/ + +static qboolean MergeBSPLuxels( rawLightmap_t *a, int aNum, rawLightmap_t *b, int bNum ) +{ + rawLightmap_t *lm; + int x, y; + float luxel[ 3 ], *aLuxel, *bLuxel; + + + /* basic tests */ + if( a->customWidth != b->customWidth || a->customHeight != b->customHeight || + a->brightness != b->brightness || + a->solid[ aNum ] != b->solid[ bNum ] || + a->bspLuxels[ aNum ] == NULL || b->bspLuxels[ bNum ] == NULL ) + return qfalse; + + /* compare solid lightmaps */ + if( a->solid[ aNum ] && b->solid[ bNum ] ) + { + /* average */ + VectorAdd( a->solidColor[ aNum ], b->solidColor[ bNum ], luxel ); + VectorScale( luxel, 0.5f, luxel ); + + /* copy to both */ + VectorCopy( luxel, a->solidColor[ aNum ] ); + VectorCopy( luxel, b->solidColor[ bNum ] ); + + /* return to sender */ + return qtrue; + } + + /* compare nonsolid lightmaps */ + if( a->w != b->w || a->h != b->h ) + return qfalse; + + /* merge luxels */ + for( y = 0; y < a->h; y++ ) + { + for( x = 0; x < a->w; x++ ) + { + /* get luxels */ + lm = a; aLuxel = BSP_LUXEL( aNum, x, y ); + lm = b; bLuxel = BSP_LUXEL( bNum, x, y ); + + /* handle occlusion mismatch */ + if( aLuxel[ 0 ] < 0.0f ) + VectorCopy( bLuxel, aLuxel ); + else if( bLuxel[ 0 ] < 0.0f ) + VectorCopy( aLuxel, bLuxel ); + else + { + /* average */ + VectorAdd( aLuxel, bLuxel, luxel ); + VectorScale( luxel, 0.5f, luxel ); + + /* debugging code */ + //% luxel[ 2 ] += 64.0f; + + /* copy to both */ + VectorCopy( luxel, aLuxel ); + VectorCopy( luxel, bLuxel ); + } + } + } + + /* done */ + return qtrue; +} + + + +/* +ApproximateLuxel() +determines if a single luxel is can be approximated with the interpolated vertex rgba +*/ + +static qboolean ApproximateLuxel( rawLightmap_t *lm, bspDrawVert_t *dv ) +{ + int i, x, y, d, lightmapNum; + float *luxel; + vec3_t color, vertexColor; + byte cb[ 4 ], vcb[ 4 ]; + + + /* find luxel xy coords */ + x = dv->lightmap[ 0 ][ 0 ] / superSample; + y = dv->lightmap[ 0 ][ 1 ] / superSample; + if( x < 0 ) + x = 0; + else if( x >= lm->w ) + x = lm->w - 1; + if( y < 0 ) + y = 0; + else if( y >= lm->h ) + y = lm->h - 1; + + /* walk list */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->styles[ lightmapNum ] == LS_NONE ) + continue; + + /* get luxel */ + luxel = BSP_LUXEL( lightmapNum, x, y ); + + /* ignore occluded luxels */ + if( luxel[ 0 ] < 0.0f || luxel[ 1 ] < 0.0f || luxel[ 2 ] < 0.0f ) + return qtrue; + + /* copy, set min color and compare */ + VectorCopy( luxel, color ); + VectorCopy( dv->color[ 0 ], vertexColor ); + + /* styles are not affected by minlight */ + if( lightmapNum == 0 ) + { + for( i = 0; i < 3; i++ ) + { + /* set min color */ + if( color[ i ] < minLight[ i ] ) + color[ i ] = minLight[ i ]; + if( vertexColor[ i ] < minLight[ i ] ) /* note NOT minVertexLight */ + vertexColor[ i ] = minLight[ i ]; + } + } + + /* set to bytes */ + ColorToBytes( color, cb, 1.0f ); + ColorToBytes( vertexColor, vcb, 1.0f ); + + /* compare */ + for( i = 0; i < 3; i++ ) + { + d = cb[ i ] - vcb[ i ]; + if( d < 0 ) + d *= -1; + if( d > approximateTolerance ) + return qfalse; + } + } + + /* close enough for the girls i date */ + return qtrue; +} + + + +/* +ApproximateTriangle() +determines if a single triangle can be approximated with vertex rgba +*/ + +static qboolean ApproximateTriangle_r( rawLightmap_t *lm, bspDrawVert_t *dv[ 3 ] ) +{ + bspDrawVert_t mid, *dv2[ 3 ]; + int max; + + + /* approximate the vertexes */ + if( ApproximateLuxel( lm, dv[ 0 ] ) == qfalse ) + return qfalse; + if( ApproximateLuxel( lm, dv[ 1 ] ) == qfalse ) + return qfalse; + if( ApproximateLuxel( lm, dv[ 2 ] ) == qfalse ) + return qfalse; + + /* subdivide calc */ + { + int i; + float dx, dy, dist, maxDist; + + + /* find the longest edge and split it */ + max = -1; + maxDist = 0; + for( i = 0; i < 3; i++ ) + { + dx = dv[ i ]->lightmap[ 0 ][ 0 ] - dv[ (i + 1) % 3 ]->lightmap[ 0 ][ 0 ]; + dy = dv[ i ]->lightmap[ 0 ][ 1 ] - dv[ (i + 1) % 3 ]->lightmap[ 0 ][ 1 ]; + dist = sqrt( (dx * dx) + (dy * dy) ); + if( dist > maxDist ) + { + maxDist = dist; + max = i; + } + } + + /* try to early out */ + if( i < 0 || maxDist < subdivideThreshold ) + return qtrue; + } + + /* split the longest edge and map it */ + LerpDrawVert( dv[ max ], dv[ (max + 1) % 3 ], &mid ); + if( ApproximateLuxel( lm, &mid ) == qfalse ) + return qfalse; + + /* recurse to first triangle */ + VectorCopy( dv, dv2 ); + dv2[ max ] = ∣ + if( ApproximateTriangle_r( lm, dv2 ) == qfalse ) + return qfalse; + + /* recurse to second triangle */ + VectorCopy( dv, dv2 ); + dv2[ (max + 1) % 3 ] = ∣ + return ApproximateTriangle_r( lm, dv2 ); +} + + + +/* +ApproximateLightmap() +determines if a raw lightmap can be approximated sufficiently with vertex colors +*/ + +static qboolean ApproximateLightmap( rawLightmap_t *lm ) +{ + int n, num, i, x, y, pw[ 5 ], r; + bspDrawSurface_t *ds; + surfaceInfo_t *info; + mesh_t src, *subdivided, *mesh; + bspDrawVert_t *verts, *dv[ 3 ]; + qboolean approximated; + + + /* approximating? */ + if( approximateTolerance <= 0 ) + return qfalse; + + /* test for jmonroe */ + #if 0 + /* don't approx lightmaps with styled twins */ + if( lm->numStyledTwins > 0 ) + return qfalse; + + /* don't approx lightmaps with styles */ + for( i = 1; i < MAX_LIGHTMAPS; i++ ) + { + if( lm->styles[ i ] != LS_NONE ) + return qfalse; + } + #endif + + /* assume reduced until shadow detail is found */ + approximated = qtrue; + + /* walk the list of surfaces on this raw lightmap */ + for( n = 0; n < lm->numLightSurfaces; n++ ) + { + /* get surface */ + num = lightSurfaces[ lm->firstLightSurface + n ]; + ds = &bspDrawSurfaces[ num ]; + info = &surfaceInfos[ num ]; + + /* assume not-reduced initially */ + info->approximated = qfalse; + + /* bail if lightmap doesn't match up */ + if( info->lm != lm ) + continue; + + /* bail if not vertex lit */ + if( info->si->noVertexLight ) + continue; + + /* assume that surfaces whose bounding boxes is smaller than 2x samplesize will be forced to vertex */ + if( (info->maxs[ 0 ] - info->mins[ 0 ]) <= (2.0f * info->sampleSize) && + (info->maxs[ 1 ] - info->mins[ 1 ]) <= (2.0f * info->sampleSize) && + (info->maxs[ 2 ] - info->mins[ 2 ]) <= (2.0f * info->sampleSize) ) + { + info->approximated = qtrue; + numSurfsVertexForced++; + continue; + } + + /* handle the triangles */ + switch( ds->surfaceType ) + { + case MST_PLANAR: + /* get verts */ + verts = yDrawVerts + ds->firstVert; + + /* map the triangles */ + info->approximated = qtrue; + for( i = 0; i < ds->numIndexes && info->approximated; i += 3 ) + { + dv[ 0 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i ] ]; + dv[ 1 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 1 ] ]; + dv[ 2 ] = &verts[ bspDrawIndexes[ ds->firstIndex + i + 2 ] ]; + info->approximated = ApproximateTriangle_r( lm, dv ); + } + break; + + case MST_PATCH: + /* make a mesh from the drawsurf */ + src.width = ds->patchWidth; + src.height = ds->patchHeight; + src.verts = &yDrawVerts[ ds->firstVert ]; + //% subdivided = SubdivideMesh( src, 8, 512 ); + subdivided = SubdivideMesh2( src, info->patchIterations ); + + /* fit it to the curve and remove colinear verts on rows/columns */ + PutMeshOnCurve( *subdivided ); + mesh = RemoveLinearMeshColumnsRows( subdivided ); + FreeMesh( subdivided ); + + /* get verts */ + verts = mesh->verts; + + /* map the mesh quads */ + info->approximated = qtrue; + for( y = 0; y < (mesh->height - 1) && info->approximated; y++ ) + { + for( x = 0; x < (mesh->width - 1) && info->approximated; x++ ) + { + /* set indexes */ + pw[ 0 ] = x + (y * mesh->width); + pw[ 1 ] = x + ((y + 1) * mesh->width); + pw[ 2 ] = x + 1 + ((y + 1) * mesh->width); + pw[ 3 ] = x + 1 + (y * mesh->width); + pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */ + + /* set radix */ + r = (x + y) & 1; + + /* get drawverts and map first triangle */ + dv[ 0 ] = &verts[ pw[ r + 0 ] ]; + dv[ 1 ] = &verts[ pw[ r + 1 ] ]; + dv[ 2 ] = &verts[ pw[ r + 2 ] ]; + info->approximated = ApproximateTriangle_r( lm, dv ); + + /* get drawverts and map second triangle */ + dv[ 0 ] = &verts[ pw[ r + 0 ] ]; + dv[ 1 ] = &verts[ pw[ r + 2 ] ]; + dv[ 2 ] = &verts[ pw[ r + 3 ] ]; + if( info->approximated ) + info->approximated = ApproximateTriangle_r( lm, dv ); + } + } + + /* free the mesh */ + FreeMesh( mesh ); + break; + + default: + break; + } + + /* reduced? */ + if( info->approximated == qfalse ) + approximated = qfalse; + else + numSurfsVertexApproximated++; + } + + /* return */ + return approximated; +} + + + +/* +TestOutLightmapStamp() +tests a stamp on a given lightmap for validity +*/ + +static qboolean TestOutLightmapStamp( rawLightmap_t *lm, int lightmapNum, outLightmap_t *olm, int x, int y ) +{ + int sx, sy, ox, oy, offset; + float *luxel; + + + /* bounds check */ + if( x < 0 || y < 0 || (x + lm->w) > olm->customWidth || (y + lm->h) > olm->customHeight ) + return qfalse; + + /* solid lightmaps test a 1x1 stamp */ + if( lm->solid[ lightmapNum ] ) + { + offset = (y * olm->customWidth) + x; + if( olm->lightBits[ offset >> 3 ] & (1 << (offset & 7)) ) + return qfalse; + return qtrue; + } + + /* test the stamp */ + for( sy = 0; sy < lm->h; sy++ ) + { + for( sx = 0; sx < lm->w; sx++ ) + { + /* get luxel */ + luxel = BSP_LUXEL( lightmapNum, sx, sy ); + if( luxel[ 0 ] < 0.0f ) + continue; + + /* get bsp lightmap coords and test */ + ox = x + sx; + oy = y + sy; + offset = (oy * olm->customWidth) + ox; + if( olm->lightBits[ offset >> 3 ] & (1 << (offset & 7)) ) + return qfalse; + } + } + + /* stamp is empty */ + return qtrue; +} + + + +/* +SetupOutLightmap() +sets up an output lightmap +*/ + +static void SetupOutLightmap( rawLightmap_t *lm, outLightmap_t *olm ) +{ + /* dummy check */ + if( lm == NULL || olm == NULL ) + return; + + /* is this a "normal" bsp-stored lightmap? */ + if( (lm->customWidth == game->lightmapSize && lm->customHeight == game->lightmapSize) || externalLightmaps ) + { + olm->lightmapNum = numBSPLightmaps; + numBSPLightmaps++; + + /* lightmaps are interleaved with light direction maps */ + if( deluxemap ) + numBSPLightmaps++; + } + else + olm->lightmapNum = -3; + + /* set external lightmap number */ + olm->extLightmapNum = -1; + + /* set it up */ + olm->numLightmaps = 0; + olm->customWidth = lm->customWidth; + olm->customHeight = lm->customHeight; + olm->freeLuxels = olm->customWidth * olm->customHeight; + olm->numShaders = 0; + + /* allocate buffers */ + olm->lightBits = safe_malloc( (olm->customWidth * olm->customHeight / 8) + 8 ); + memset( olm->lightBits, 0, (olm->customWidth * olm->customHeight / 8) + 8 ); + olm->bspLightBytes = safe_malloc( olm->customWidth * olm->customHeight * 3 ); + memset( olm->bspLightBytes, 0, olm->customWidth * olm->customHeight * 3 ); + if( deluxemap ) + { + olm->bspDirBytes = safe_malloc( olm->customWidth * olm->customHeight * 3 ); + memset( olm->bspDirBytes, 0, olm->customWidth * olm->customHeight * 3 ); + } +} + + + +/* +FindOutLightmaps() +for a given surface lightmap, find output lightmap pages and positions for it +*/ + +#define LIGHTMAP_RESERVE_COUNT 1 +static void FindOutLightmaps( rawLightmap_t *lm ) +{ + int i, j, k, lightmapNum, xMax, yMax, x, y, sx, sy, ox, oy, offset; + outLightmap_t *olm; + surfaceInfo_t *info; + float *luxel, *deluxel; + vec3_t color, direction; + byte *pixel; + qboolean ok; + + + /* set default lightmap number (-3 = LIGHTMAP_BY_VERTEX) */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + lm->outLightmapNums[ lightmapNum ] = -3; + + /* can this lightmap be approximated with vertex color? */ + if( ApproximateLightmap( lm ) ) + return; + + /* walk list */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + if( lm->styles[ lightmapNum ] == LS_NONE ) + continue; + + /* don't store twinned lightmaps */ + if( lm->twins[ lightmapNum ] != NULL ) + continue; + + /* if this is a styled lightmap, try some normalized locations first */ + ok = qfalse; + if( lightmapNum > 0 && outLightmaps != NULL ) + { + /* loop twice */ + for( j = 0; j < 2; j++ ) + { + /* try identical position */ + for( i = 0; i < numOutLightmaps; i++ ) + { + /* get the output lightmap */ + olm = &outLightmaps[ i ]; + + /* simple early out test */ + if( olm->freeLuxels < lm->used ) + continue; + + /* don't store non-custom raw lightmaps on custom bsp lightmaps */ + if( olm->customWidth != lm->customWidth || + olm->customHeight != lm->customHeight ) + continue; + + /* try identical */ + if( j == 0 ) + { + x = lm->lightmapX[ 0 ]; + y = lm->lightmapY[ 0 ]; + ok = TestOutLightmapStamp( lm, lightmapNum, olm, x, y ); + } + + /* try shifting */ + else + { + for( sy = -1; sy <= 1; sy++ ) + { + for( sx = -1; sx <= 1; sx++ ) + { + x = lm->lightmapX[ 0 ] + sx * (olm->customWidth >> 1); //% lm->w; + y = lm->lightmapY[ 0 ] + sy * (olm->customHeight >> 1); //% lm->h; + ok = TestOutLightmapStamp( lm, lightmapNum, olm, x, y ); + + if( ok ) + break; + } + + if( ok ) + break; + } + } + + if( ok ) + break; + } + + if( ok ) + break; + } + } + + /* try normal placement algorithm */ + if( ok == qfalse ) + { + /* reset origin */ + x = 0; + y = 0; + + /* walk the list of lightmap pages */ + if(lightmapSearchBlockSize <= 0 || numOutLightmaps < LIGHTMAP_RESERVE_COUNT) + i = 0; + else + i = ((numOutLightmaps - LIGHTMAP_RESERVE_COUNT) / lightmapSearchBlockSize) * lightmapSearchBlockSize; + for( ; i < numOutLightmaps; i++ ) + { + /* get the output lightmap */ + olm = &outLightmaps[ i ]; + + /* simple early out test */ + if( olm->freeLuxels < lm->used ) + continue; + + /* don't store non-custom raw lightmaps on custom bsp lightmaps */ + if( olm->customWidth != lm->customWidth || + olm->customHeight != lm->customHeight ) + continue; + + /* set maxs */ + if( lm->solid[ lightmapNum ] ) + { + xMax = olm->customWidth; + yMax = olm->customHeight; + } + else + { + xMax = (olm->customWidth - lm->w) + 1; + yMax = (olm->customHeight - lm->h) + 1; + } + + /* walk the origin around the lightmap */ + for( y = 0; y < yMax; y++ ) + { + for( x = 0; x < xMax; x++ ) + { + /* find a fine tract of lauhnd */ + ok = TestOutLightmapStamp( lm, lightmapNum, olm, x, y ); + + if( ok ) + break; + } + + if( ok ) + break; + } + + if( ok ) + break; + + /* reset x and y */ + x = 0; + y = 0; + } + } + + /* no match? */ + if( ok == qfalse ) + { + /* allocate LIGHTMAP_RESERVE_COUNT new output lightmaps */ + numOutLightmaps += LIGHTMAP_RESERVE_COUNT; + olm = safe_malloc( numOutLightmaps * sizeof( outLightmap_t ) ); + if( outLightmaps != NULL && numOutLightmaps > LIGHTMAP_RESERVE_COUNT ) + { + memcpy( olm, outLightmaps, (numOutLightmaps - LIGHTMAP_RESERVE_COUNT) * sizeof( outLightmap_t ) ); + free( outLightmaps ); + } + outLightmaps = olm; + + /* initialize both out lightmaps */ + for(k = numOutLightmaps - LIGHTMAP_RESERVE_COUNT; k < numOutLightmaps; ++k) + SetupOutLightmap( lm, &outLightmaps[ k ] ); + + /* set out lightmap */ + i = numOutLightmaps - LIGHTMAP_RESERVE_COUNT; + olm = &outLightmaps[ i ]; + + /* set stamp xy origin to the first surface lightmap */ + if( lightmapNum > 0 ) + { + x = lm->lightmapX[ 0 ]; + y = lm->lightmapY[ 0 ]; + } + } + + /* if this is a style-using lightmap, it must be exported */ + if( lightmapNum > 0 && game->load != LoadRBSPFile ) + olm->extLightmapNum = 0; + + /* add the surface lightmap to the bsp lightmap */ + lm->outLightmapNums[ lightmapNum ] = i; + lm->lightmapX[ lightmapNum ] = x; + lm->lightmapY[ lightmapNum ] = y; + olm->numLightmaps++; + + /* add shaders */ + for( i = 0; i < lm->numLightSurfaces; i++ ) + { + /* get surface info */ + info = &surfaceInfos[ lightSurfaces[ lm->firstLightSurface + i ] ]; + + /* test for shader */ + for( j = 0; j < olm->numShaders; j++ ) + { + if( olm->shaders[ j ] == info->si ) + break; + } + + /* if it doesn't exist, add it */ + if( j >= olm->numShaders && olm->numShaders < MAX_LIGHTMAP_SHADERS ) + { + olm->shaders[ olm->numShaders ] = info->si; + olm->numShaders++; + numLightmapShaders++; + } + } + + /* set maxs */ + if( lm->solid[ lightmapNum ] ) + { + xMax = 1; + yMax = 1; + } + else + { + xMax = lm->w; + yMax = lm->h; + } + + /* mark the bits used */ + for( y = 0; y < yMax; y++ ) + { + for( x = 0; x < xMax; x++ ) + { + /* get luxel */ + luxel = BSP_LUXEL( lightmapNum, x, y ); + deluxel = BSP_DELUXEL( x, y ); + if( luxel[ 0 ] < 0.0f && !lm->solid[ lightmapNum ]) + continue; + + /* set minimum light */ + if( lm->solid[ lightmapNum ] ) + { + if( debug ) + VectorSet( color, 255.0f, 0.0f, 0.0f ); + else + VectorCopy( lm->solidColor[ lightmapNum ], color ); + } + else + VectorCopy( luxel, color ); + + /* styles are not affected by minlight */ + if( lightmapNum == 0 ) + { + for( i = 0; i < 3; i++ ) + { + if( color[ i ] < minLight[ i ] ) + color[ i ] = minLight[ i ]; + } + } + + /* get bsp lightmap coords */ + ox = x + lm->lightmapX[ lightmapNum ]; + oy = y + lm->lightmapY[ lightmapNum ]; + offset = (oy * olm->customWidth) + ox; + + /* flag pixel as used */ + olm->lightBits[ offset >> 3 ] |= (1 << (offset & 7)); + olm->freeLuxels--; + + /* store color */ + pixel = olm->bspLightBytes + (((oy * olm->customWidth) + ox) * 3); + ColorToBytes( color, pixel, lm->brightness ); + + /* store direction */ + if( deluxemap ) + { + /* normalize average light direction */ + pixel = olm->bspDirBytes + (((oy * olm->customWidth) + ox) * 3); + VectorScale( deluxel, 1000.0f, direction ); + VectorNormalize( direction, direction ); + VectorScale( direction, 127.5f, direction ); + for( i = 0; i < 3; i++ ) + pixel[ i ] = (byte)( 127.5f + direction[ i ] ); + } + } + } + } +} + + + +/* +CompareRawLightmap() +compare function for qsort() +*/ + +static int CompareRawLightmap( const void *a, const void *b ) +{ + rawLightmap_t *alm, *blm; + surfaceInfo_t *aInfo, *bInfo; + int i, min, diff; + + + /* get lightmaps */ + alm = &rawLightmaps[ *((const int*) a) ]; + blm = &rawLightmaps[ *((const int*) b) ]; + + /* get min number of surfaces */ + min = (alm->numLightSurfaces < blm->numLightSurfaces ? alm->numLightSurfaces : blm->numLightSurfaces); + + /* iterate */ + for( i = 0; i < min; i++ ) + { + /* get surface info */ + aInfo = &surfaceInfos[ lightSurfaces[ alm->firstLightSurface + i ] ]; + bInfo = &surfaceInfos[ lightSurfaces[ blm->firstLightSurface + i ] ]; + + /* compare shader names */ + diff = strcmp( aInfo->si->shader, bInfo->si->shader ); + if( diff != 0 ) + return diff; + } + + /* test style count */ + diff = 0; + for( i = 0; i < MAX_LIGHTMAPS; i++ ) + diff += blm->styles[ i ] - alm->styles[ i ]; + if( diff ) + return diff; + + /* compare size */ + diff = (blm->w * blm->h) - (alm->w * alm->h); + if( diff != 0 ) + return diff; + + /* must be equivalent */ + return 0; +} + +void FillOutLightmap(outLightmap_t *olm) +{ + int x, y; + int ofs; + vec3_t dir_sum, light_sum; + int cnt, filled; + byte *lightBitsNew = NULL; + byte *lightBytesNew = NULL; + byte *dirBytesNew = NULL; + + lightBitsNew = safe_malloc((olm->customWidth * olm->customHeight + 8) / 8); + lightBytesNew = safe_malloc(olm->customWidth * olm->customHeight * 3); + if(deluxemap) + dirBytesNew = safe_malloc(olm->customWidth * olm->customHeight * 3); + + /* + memset(olm->lightBits, 0, (olm->customWidth * olm->customHeight + 8) / 8); + olm->lightBits[0] |= 1; + olm->lightBits[(10 * olm->customWidth + 30) >> 3] |= 1 << ((10 * olm->customWidth + 30) & 7); + memset(olm->bspLightBytes, 0, olm->customWidth * olm->customHeight * 3); + olm->bspLightBytes[0] = 255; + olm->bspLightBytes[(10 * olm->customWidth + 30) * 3 + 2] = 255; + */ + + memcpy(lightBitsNew, olm->lightBits, (olm->customWidth * olm->customHeight + 8) / 8); + memcpy(lightBytesNew, olm->bspLightBytes, olm->customWidth * olm->customHeight * 3); + if(deluxemap) + memcpy(dirBytesNew, olm->bspDirBytes, olm->customWidth * olm->customHeight * 3); + + for(;;) + { + filled = 0; + for(y = 0; y < olm->customHeight; ++y) + { + for(x = 0; x < olm->customWidth; ++x) + { + ofs = y * olm->customWidth + x; + if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ + continue; + cnt = 0; + VectorClear(dir_sum); + VectorClear(light_sum); + + /* try all four neighbors */ + ofs = ((y + olm->customHeight - 1) % olm->customHeight) * olm->customWidth + x; + if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ + { + ++cnt; + VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); + if(deluxemap) + VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); + } + + ofs = ((y + 1) % olm->customHeight) * olm->customWidth + x; + if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ + { + ++cnt; + VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); + if(deluxemap) + VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); + } + + ofs = y * olm->customWidth + (x + olm->customWidth - 1) % olm->customWidth; + if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ + { + ++cnt; + VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); + if(deluxemap) + VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); + } + + ofs = y * olm->customWidth + (x + 1) % olm->customWidth; + if(olm->lightBits[ofs >> 3] & (1 << (ofs & 7))) /* already filled */ + { + ++cnt; + VectorAdd(light_sum, olm->bspLightBytes + ofs * 3, light_sum); + if(deluxemap) + VectorAdd(dir_sum, olm->bspDirBytes + ofs * 3, dir_sum); + } + + if(cnt) + { + ++filled; + ofs = y * olm->customWidth + x; + lightBitsNew[ofs >> 3] |= (1 << (ofs & 7)); + VectorScale(light_sum, 1.0/cnt, lightBytesNew + ofs * 3); + if(deluxemap) + VectorScale(dir_sum, 1.0/cnt, dirBytesNew + ofs * 3); + } + } + } + + if(!filled) + break; + + memcpy(olm->lightBits, lightBitsNew, (olm->customWidth * olm->customHeight + 8) / 8); + memcpy(olm->bspLightBytes, lightBytesNew, olm->customWidth * olm->customHeight * 3); + if(deluxemap) + memcpy(olm->bspDirBytes, dirBytesNew, olm->customWidth * olm->customHeight * 3); + } + + free(lightBitsNew); + free(lightBytesNew); + if(deluxemap) + free(dirBytesNew); +} + +/* +StoreSurfaceLightmaps() +stores the surface lightmaps into the bsp as byte rgb triplets +*/ + +void StoreSurfaceLightmaps( void ) +{ + int i, j, k, x, y, lx, ly, sx, sy, *cluster, mappedSamples; + int style, size, lightmapNum, lightmapNum2; + float *normal, *luxel, *bspLuxel, *bspLuxel2, *radLuxel, samples, occludedSamples; + vec3_t sample, occludedSample, dirSample, colorMins, colorMaxs; + float *deluxel, *bspDeluxel, *bspDeluxel2; + byte *lb; + int numUsed, numTwins, numTwinLuxels, numStored; + float lmx, lmy, efficiency; + vec3_t color; + bspDrawSurface_t *ds, *parent, dsTemp; + surfaceInfo_t *info; + rawLightmap_t *lm, *lm2; + outLightmap_t *olm; + bspDrawVert_t *dv, *ydv, *dvParent; + char dirname[ 1024 ], filename[ 1024 ]; + shaderInfo_t *csi; + char lightmapName[ 128 ]; + const char *rgbGenValues[ 256 ]; + const char *alphaGenValues[ 256 ]; + + + /* note it */ + Sys_Printf( "--- StoreSurfaceLightmaps ---\n"); + + /* setup */ + if(lmCustomDir) + { + strcpy( dirname, lmCustomDir ); + } + else + { + strcpy( dirname, source ); + StripExtension( dirname ); + } + memset( rgbGenValues, 0, sizeof( rgbGenValues ) ); + memset( alphaGenValues, 0, sizeof( alphaGenValues ) ); + + /* ----------------------------------------------------------------- + average the sampled luxels into the bsp luxels + ----------------------------------------------------------------- */ + + /* note it */ + Sys_Printf( "Subsampling..." ); + + /* walk the list of raw lightmaps */ + numUsed = 0; + numTwins = 0; + numTwinLuxels = 0; + numSolidLightmaps = 0; + for( i = 0; i < numRawLightmaps; i++ ) + { + /* get lightmap */ + lm = &rawLightmaps[ i ]; + + /* walk individual lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early outs */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + + /* allocate bsp luxel storage */ + if( lm->bspLuxels[ lightmapNum ] == NULL ) + { + size = lm->w * lm->h * BSP_LUXEL_SIZE * sizeof( float ); + lm->bspLuxels[ lightmapNum ] = safe_malloc( size ); + memset( lm->bspLuxels[ lightmapNum ], 0, size ); + } + + /* allocate radiosity lightmap storage */ + if( bounce ) + { + size = lm->w * lm->h * RAD_LUXEL_SIZE * sizeof( float ); + if( lm->radLuxels[ lightmapNum ] == NULL ) + lm->radLuxels[ lightmapNum ] = safe_malloc( size ); + memset( lm->radLuxels[ lightmapNum ], 0, size ); + } + + /* average supersampled luxels */ + for( y = 0; y < lm->h; y++ ) + { + for( x = 0; x < lm->w; x++ ) + { + /* subsample */ + samples = 0.0f; + occludedSamples = 0.0f; + mappedSamples = 0; + VectorClear( sample ); + VectorClear( occludedSample ); + VectorClear( dirSample ); + for( ly = 0; ly < superSample; ly++ ) + { + for( lx = 0; lx < superSample; lx++ ) + { + /* sample luxel */ + sx = x * superSample + lx; + sy = y * superSample + ly; + luxel = SUPER_LUXEL( lightmapNum, sx, sy ); + deluxel = SUPER_DELUXEL( sx, sy ); + normal = SUPER_NORMAL( sx, sy ); + cluster = SUPER_CLUSTER( sx, sy ); + + /* sample deluxemap */ + if( deluxemap && lightmapNum == 0 ) + VectorAdd( dirSample, deluxel, dirSample ); + + /* keep track of used/occluded samples */ + if( *cluster != CLUSTER_UNMAPPED ) + mappedSamples++; + + /* handle lightmap border? */ + if( lightmapBorder && (sx == 0 || sx == (lm->sw - 1) || sy == 0 || sy == (lm->sh - 1) ) && luxel[ 3 ] > 0.0f ) + { + VectorSet( sample, 255.0f, 0.0f, 0.0f ); + samples += 1.0f; + } + + /* handle debug */ + else if( debug && *cluster < 0 ) + { + if( *cluster == CLUSTER_UNMAPPED ) + VectorSet( luxel, 255, 204, 0 ); + else if( *cluster == CLUSTER_OCCLUDED ) + VectorSet( luxel, 255, 0, 255 ); + else if( *cluster == CLUSTER_FLOODED ) + VectorSet( luxel, 0, 32, 255 ); + VectorAdd( occludedSample, luxel, occludedSample ); + occludedSamples += 1.0f; + } + + /* normal luxel handling */ + else if( luxel[ 3 ] > 0.0f ) + { + /* handle lit or flooded luxels */ + if( *cluster > 0 || *cluster == CLUSTER_FLOODED ) + { + VectorAdd( sample, luxel, sample ); + samples += luxel[ 3 ]; + } + + /* handle occluded or unmapped luxels */ + else + { + VectorAdd( occludedSample, luxel, occludedSample ); + occludedSamples += luxel[ 3 ]; + } + + /* handle style debugging */ + if( debug && lightmapNum > 0 && x < 2 && y < 2 ) + { + VectorCopy( debugColors[ 0 ], sample ); + samples = 1; + } + } + } + } + + /* only use occluded samples if necessary */ + if( samples <= 0.0f ) + { + VectorCopy( occludedSample, sample ); + samples = occludedSamples; + } + + /* get luxels */ + luxel = SUPER_LUXEL( lightmapNum, x, y ); + deluxel = SUPER_DELUXEL( x, y ); + + /* store light direction */ + if( deluxemap && lightmapNum == 0 ) + VectorCopy( dirSample, deluxel ); + + /* store the sample back in super luxels */ + if( samples > 0.01f ) + { + VectorScale( sample, (1.0f / samples), luxel ); + luxel[ 3 ] = 1.0f; + } + + /* if any samples were mapped in any way, store ambient color */ + else if( mappedSamples > 0 ) + { + if( lightmapNum == 0 ) + VectorCopy( ambientColor, luxel ); + else + VectorClear( luxel ); + luxel[ 3 ] = 1.0f; + } + + /* store a bogus value to be fixed later */ + else + { + VectorClear( luxel ); + luxel[ 3 ] = -1.0f; + } + } + } + + /* setup */ + lm->used = 0; + ClearBounds( colorMins, colorMaxs ); + + /* clean up and store into bsp luxels */ + for( y = 0; y < lm->h; y++ ) + { + for( x = 0; x < lm->w; x++ ) + { + /* get luxels */ + luxel = SUPER_LUXEL( lightmapNum, x, y ); + deluxel = SUPER_DELUXEL( x, y ); + + /* copy light direction */ + if( deluxemap && lightmapNum == 0 ) + VectorCopy( deluxel, dirSample ); + + /* is this a valid sample? */ + if( luxel[ 3 ] > 0.0f ) + { + VectorCopy( luxel, sample ); + samples = luxel[ 3 ]; + numUsed++; + lm->used++; + + /* fix negative samples */ + for( j = 0; j < 3; j++ ) + { + if( sample[ j ] < 0.0f ) + sample[ j ] = 0.0f; + } + } + else + { + /* nick an average value from the neighbors */ + VectorClear( sample ); + VectorClear( dirSample ); + samples = 0.0f; + + /* fixme: why is this disabled?? */ + for( sy = (y - 1); sy <= (y + 1); sy++ ) + { + if( sy < 0 || sy >= lm->h ) + continue; + + for( sx = (x - 1); sx <= (x + 1); sx++ ) + { + if( sx < 0 || sx >= lm->w || (sx == x && sy == y) ) + continue; + + /* get neighbor's particulars */ + luxel = SUPER_LUXEL( lightmapNum, sx, sy ); + if( luxel[ 3 ] < 0.0f ) + continue; + VectorAdd( sample, luxel, sample ); + samples += luxel[ 3 ]; + } + } + + /* no samples? */ + if( samples == 0.0f ) + { + VectorSet( sample, -1.0f, -1.0f, -1.0f ); + samples = 1.0f; + } + else + { + numUsed++; + lm->used++; + + /* fix negative samples */ + for( j = 0; j < 3; j++ ) + { + if( sample[ j ] < 0.0f ) + sample[ j ] = 0.0f; + } + } + } + + /* scale the sample */ + VectorScale( sample, (1.0f / samples), sample ); + + /* store the sample in the radiosity luxels */ + if( bounce > 0 ) + { + radLuxel = RAD_LUXEL( lightmapNum, x, y ); + VectorCopy( sample, radLuxel ); + + /* if only storing bounced light, early out here */ + if( bounceOnly && !bouncing ) + continue; + } + + /* store the sample in the bsp luxels */ + bspLuxel = BSP_LUXEL( lightmapNum, x, y ); + bspDeluxel = BSP_DELUXEL( x, y ); + + VectorAdd( bspLuxel, sample, bspLuxel ); + if( deluxemap && lightmapNum == 0 ) + VectorAdd( bspDeluxel, dirSample, bspDeluxel ); + + /* add color to bounds for solid checking */ + if( samples > 0.0f ) + AddPointToBounds( bspLuxel, colorMins, colorMaxs ); + } + } + + /* set solid color */ + lm->solid[ lightmapNum ] = qfalse; + VectorAdd( colorMins, colorMaxs, lm->solidColor[ lightmapNum ] ); + VectorScale( lm->solidColor[ lightmapNum ], 0.5f, lm->solidColor[ lightmapNum ] ); + + /* nocollapse prevents solid lightmaps */ + if( noCollapse == qfalse ) + { + /* check solid color */ + VectorSubtract( colorMaxs, colorMins, sample ); + if( (sample[ 0 ] <= SOLID_EPSILON && sample[ 1 ] <= SOLID_EPSILON && sample[ 2 ] <= SOLID_EPSILON) || + (lm->w <= 2 && lm->h <= 2) ) /* small lightmaps get forced to solid color */ + { + /* set to solid */ + VectorCopy( colorMins, lm->solidColor[ lightmapNum ] ); + lm->solid[ lightmapNum ] = qtrue; + numSolidLightmaps++; + } + + /* if all lightmaps aren't solid, then none of them are solid */ + if( lm->solid[ lightmapNum ] != lm->solid[ 0 ] ) + { + for( y = 0; y < MAX_LIGHTMAPS; y++ ) + { + if( lm->solid[ y ] ) + numSolidLightmaps--; + lm->solid[ y ] = qfalse; + } + } + } + + /* wrap bsp luxels if necessary */ + if( lm->wrap[ 0 ] ) + { + for( y = 0; y < lm->h; y++ ) + { + bspLuxel = BSP_LUXEL( lightmapNum, 0, y ); + bspLuxel2 = BSP_LUXEL( lightmapNum, lm->w - 1, y ); + VectorAdd( bspLuxel, bspLuxel2, bspLuxel ); + VectorScale( bspLuxel, 0.5f, bspLuxel ); + VectorCopy( bspLuxel, bspLuxel2 ); + if( deluxemap && lightmapNum == 0 ) + { + bspDeluxel = BSP_DELUXEL( 0, y ); + bspDeluxel2 = BSP_DELUXEL( lm->w - 1, y ); + VectorAdd( bspDeluxel, bspDeluxel2, bspDeluxel ); + VectorScale( bspDeluxel, 0.5f, bspDeluxel ); + VectorCopy( bspDeluxel, bspDeluxel2 ); + } + } + } + if( lm->wrap[ 1 ] ) + { + for( x = 0; x < lm->w; x++ ) + { + bspLuxel = BSP_LUXEL( lightmapNum, x, 0 ); + bspLuxel2 = BSP_LUXEL( lightmapNum, x, lm->h - 1 ); + VectorAdd( bspLuxel, bspLuxel2, bspLuxel ); + VectorScale( bspLuxel, 0.5f, bspLuxel ); + VectorCopy( bspLuxel, bspLuxel2 ); + if( deluxemap && lightmapNum == 0 ) + { + bspDeluxel = BSP_DELUXEL( x, 0 ); + bspDeluxel2 = BSP_DELUXEL( x, lm->h - 1 ); + VectorAdd( bspDeluxel, bspDeluxel2, bspDeluxel ); + VectorScale( bspDeluxel, 0.5f, bspDeluxel ); + VectorCopy( bspDeluxel, bspDeluxel2 ); + } + } + } + } + } + + /* ----------------------------------------------------------------- + convert modelspace deluxemaps to tangentspace + ----------------------------------------------------------------- */ + /* note it */ + if( !bouncing ) + { + if( deluxemap && deluxemode == 1) + { + vec3_t worldUp, myNormal, myTangent, myBinormal; + float dist; + + Sys_Printf( "converting..." ); + + for( i = 0; i < numRawLightmaps; i++ ) + { + /* get lightmap */ + lm = &rawLightmaps[ i ]; + + /* walk lightmap samples */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get normal and deluxel */ + normal = SUPER_NORMAL(x, y); + cluster = SUPER_CLUSTER(x, y); + bspDeluxel = BSP_DELUXEL( x, y ); + deluxel = SUPER_DELUXEL( x, y ); + + /* get normal */ + VectorSet( myNormal, normal[0], normal[1], normal[2] ); + + /* get tangent vectors */ + if( myNormal[ 0 ] == 0.0f && myNormal[ 1 ] == 0.0f ) + { + if( myNormal[ 2 ] == 1.0f ) + { + VectorSet( myTangent, 1.0f, 0.0f, 0.0f ); + VectorSet( myBinormal, 0.0f, 1.0f, 0.0f ); + } + else if( myNormal[ 2 ] == -1.0f ) + { + VectorSet( myTangent, -1.0f, 0.0f, 0.0f ); + VectorSet( myBinormal, 0.0f, 1.0f, 0.0f ); + } + } + else + { + VectorSet( worldUp, 0.0f, 0.0f, 1.0f ); + CrossProduct( myNormal, worldUp, myTangent ); + VectorNormalize( myTangent, myTangent ); + CrossProduct( myTangent, myNormal, myBinormal ); + VectorNormalize( myBinormal, myBinormal ); + } + + /* project onto plane */ + dist = -DotProduct(myTangent, myNormal); + VectorMA(myTangent, dist, myNormal, myTangent); + dist = -DotProduct(myBinormal, myNormal); + VectorMA(myBinormal, dist, myNormal, myBinormal); + + /* renormalize */ + VectorNormalize( myTangent, myTangent ); + VectorNormalize( myBinormal, myBinormal ); + + /* convert modelspace deluxel to tangentspace */ + dirSample[0] = bspDeluxel[0]; + dirSample[1] = bspDeluxel[1]; + dirSample[2] = bspDeluxel[2]; + VectorNormalize(dirSample, dirSample); + + /* fix tangents to world matrix */ + if (myNormal[0] > 0 || myNormal[1] < 0 || myNormal[2] < 0) + VectorNegate(myTangent, myTangent); + + /* build tangentspace vectors */ + bspDeluxel[0] = DotProduct(dirSample, myTangent); + bspDeluxel[1] = DotProduct(dirSample, myBinormal); + bspDeluxel[2] = DotProduct(dirSample, myNormal); + } + } + } + } + } + + /* ----------------------------------------------------------------- + blend lightmaps + ----------------------------------------------------------------- */ + +#ifdef sdfsdfwq312323 + /* note it */ + Sys_Printf( "blending..." ); + + for( i = 0; i < numRawLightmaps; i++ ) + { + vec3_t myColor; + float myBrightness; + + /* get lightmap */ + lm = &rawLightmaps[ i ]; + + /* walk individual lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early outs */ + if( lm->superLuxels[ lightmapNum ] == NULL ) + continue; + + /* walk lightmap samples */ + for( y = 0; y < lm->sh; y++ ) + { + for( x = 0; x < lm->sw; x++ ) + { + /* get luxel */ + bspLuxel = BSP_LUXEL( lightmapNum, x, y ); + + /* get color */ + VectorNormalize(bspLuxel, myColor); + myBrightness = VectorLength(bspLuxel); + myBrightness *= (1 / 127.0f); + myBrightness = myBrightness*myBrightness; + myBrightness *= 127.0f; + VectorScale(myColor, myBrightness, bspLuxel); + } + } + } + } +#endif + + /* ----------------------------------------------------------------- + collapse non-unique lightmaps + ----------------------------------------------------------------- */ + + if( noCollapse == qfalse && deluxemap == qfalse ) + { + /* note it */ + Sys_Printf( "collapsing..." ); + + /* set all twin refs to null */ + for( i = 0; i < numRawLightmaps; i++ ) + { + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + rawLightmaps[ i ].twins[ lightmapNum ] = NULL; + rawLightmaps[ i ].twinNums[ lightmapNum ] = -1; + rawLightmaps[ i ].numStyledTwins = 0; + } + } + + /* walk the list of raw lightmaps */ + for( i = 0; i < numRawLightmaps; i++ ) + { + /* get lightmap */ + lm = &rawLightmaps[ i ]; + + /* walk lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early outs */ + if( lm->bspLuxels[ lightmapNum ] == NULL || + lm->twins[ lightmapNum ] != NULL ) + continue; + + /* find all lightmaps that are virtually identical to this one */ + for( j = i + 1; j < numRawLightmaps; j++ ) + { + /* get lightmap */ + lm2 = &rawLightmaps[ j ]; + + /* walk lightmaps */ + for( lightmapNum2 = 0; lightmapNum2 < MAX_LIGHTMAPS; lightmapNum2++ ) + { + /* early outs */ + if( lm2->bspLuxels[ lightmapNum2 ] == NULL || + lm2->twins[ lightmapNum2 ] != NULL ) + continue; + + /* compare them */ + if( CompareBSPLuxels( lm, lightmapNum, lm2, lightmapNum2 ) ) + { + /* merge and set twin */ + if( MergeBSPLuxels( lm, lightmapNum, lm2, lightmapNum2 ) ) + { + lm2->twins[ lightmapNum2 ] = lm; + lm2->twinNums[ lightmapNum2 ] = lightmapNum; + numTwins++; + numTwinLuxels += (lm->w * lm->h); + + /* count styled twins */ + if( lightmapNum > 0 ) + lm->numStyledTwins++; + } + } + } + } + } + } + } + + /* ----------------------------------------------------------------- + sort raw lightmaps by shader + ----------------------------------------------------------------- */ + + /* note it */ + Sys_Printf( "sorting..." ); + + /* allocate a new sorted list */ + if( sortLightmaps == NULL ) + sortLightmaps = safe_malloc( numRawLightmaps * sizeof( int ) ); + + /* fill it out and sort it */ + for( i = 0; i < numRawLightmaps; i++ ) + sortLightmaps[ i ] = i; + qsort( sortLightmaps, numRawLightmaps, sizeof( int ), CompareRawLightmap ); + + /* ----------------------------------------------------------------- + allocate output lightmaps + ----------------------------------------------------------------- */ + + /* note it */ + Sys_Printf( "allocating..." ); + + /* kill all existing output lightmaps */ + if( outLightmaps != NULL ) + { + for( i = 0; i < numOutLightmaps; i++ ) + { + free( outLightmaps[ i ].lightBits ); + free( outLightmaps[ i ].bspLightBytes ); + } + free( outLightmaps ); + outLightmaps = NULL; + } + + numLightmapShaders = 0; + numOutLightmaps = 0; + numBSPLightmaps = 0; + numExtLightmaps = 0; + + /* find output lightmap */ + for( i = 0; i < numRawLightmaps; i++ ) + { + lm = &rawLightmaps[ sortLightmaps[ i ] ]; + FindOutLightmaps( lm ); + } + + /* set output numbers in twinned lightmaps */ + for( i = 0; i < numRawLightmaps; i++ ) + { + /* get lightmap */ + lm = &rawLightmaps[ sortLightmaps[ i ] ]; + + /* walk lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* get twin */ + lm2 = lm->twins[ lightmapNum ]; + if( lm2 == NULL ) + continue; + lightmapNum2 = lm->twinNums[ lightmapNum ]; + + /* find output lightmap from twin */ + lm->outLightmapNums[ lightmapNum ] = lm2->outLightmapNums[ lightmapNum2 ]; + lm->lightmapX[ lightmapNum ] = lm2->lightmapX[ lightmapNum2 ]; + lm->lightmapY[ lightmapNum ] = lm2->lightmapY[ lightmapNum2 ]; + } + } + + /* ----------------------------------------------------------------- + store output lightmaps + ----------------------------------------------------------------- */ + + /* note it */ + Sys_Printf( "storing..." ); + + /* count the bsp lightmaps and allocate space */ + if( bspLightBytes != NULL ) + free( bspLightBytes ); + if( numBSPLightmaps == 0 || externalLightmaps ) + { + numBSPLightBytes = 0; + bspLightBytes = NULL; + } + else + { + numBSPLightBytes = (numBSPLightmaps * game->lightmapSize * game->lightmapSize * 3); + bspLightBytes = safe_malloc( numBSPLightBytes ); + memset( bspLightBytes, 0, numBSPLightBytes ); + } + + /* walk the list of output lightmaps */ + for( i = 0; i < numOutLightmaps; i++ ) + { + /* get output lightmap */ + olm = &outLightmaps[ i ]; + + /* fill output lightmap */ + if(lightmapFill) + FillOutLightmap(olm); + + /* is this a valid bsp lightmap? */ + if( olm->lightmapNum >= 0 && !externalLightmaps ) + { + /* copy lighting data */ + lb = bspLightBytes + (olm->lightmapNum * game->lightmapSize * game->lightmapSize * 3); + memcpy( lb, olm->bspLightBytes, game->lightmapSize * game->lightmapSize * 3 ); + + /* copy direction data */ + if( deluxemap ) + { + lb = bspLightBytes + ((olm->lightmapNum + 1) * game->lightmapSize * game->lightmapSize * 3); + memcpy( lb, olm->bspDirBytes, game->lightmapSize * game->lightmapSize * 3 ); + } + } + + /* external lightmap? */ + if( olm->lightmapNum < 0 || olm->extLightmapNum >= 0 || externalLightmaps ) + { + /* make a directory for the lightmaps */ + Q_mkdir( dirname ); + + /* set external lightmap number */ + olm->extLightmapNum = numExtLightmaps; + + /* write lightmap */ + sprintf( filename, "%s/" EXTERNAL_LIGHTMAP, dirname, numExtLightmaps ); + Sys_FPrintf( SYS_VRB, "\nwriting %s", filename ); + WriteTGA24( filename, olm->bspLightBytes, olm->customWidth, olm->customHeight, qtrue ); + numExtLightmaps++; + + /* write deluxemap */ + if( deluxemap ) + { + sprintf( filename, "%s/" EXTERNAL_LIGHTMAP, dirname, numExtLightmaps ); + Sys_FPrintf( SYS_VRB, "\nwriting %s", filename ); + WriteTGA24( filename, olm->bspDirBytes, olm->customWidth, olm->customHeight, qtrue ); + numExtLightmaps++; + + if( debugDeluxemap ) + olm->extLightmapNum++; + } + } + } + + if( numExtLightmaps > 0 ) + Sys_Printf( "\n" ); + + /* delete unused external lightmaps */ + for( i = numExtLightmaps; i; i++ ) + { + /* determine if file exists */ + sprintf( filename, "%s/" EXTERNAL_LIGHTMAP, dirname, i ); + if( !FileExists( filename ) ) + break; + + /* delete it */ + remove( filename ); + } + + /* ----------------------------------------------------------------- + project the lightmaps onto the bsp surfaces + ----------------------------------------------------------------- */ + + /* note it */ + Sys_Printf( "projecting..." ); + + /* walk the list of surfaces */ + for( i = 0; i < numBSPDrawSurfaces; i++ ) + { + /* get the surface and info */ + ds = &bspDrawSurfaces[ i ]; + info = &surfaceInfos[ i ]; + lm = info->lm; + olm = NULL; + + /* handle surfaces with identical parent */ + if( info->parentSurfaceNum >= 0 ) + { + /* preserve original data and get parent */ + parent = &bspDrawSurfaces[ info->parentSurfaceNum ]; + memcpy( &dsTemp, ds, sizeof( *ds ) ); + + /* overwrite child with parent data */ + memcpy( ds, parent, sizeof( *ds ) ); + + /* restore key parts */ + ds->fogNum = dsTemp.fogNum; + ds->firstVert = dsTemp.firstVert; + ds->firstIndex = dsTemp.firstIndex; + memcpy( ds->lightmapVecs, dsTemp.lightmapVecs, sizeof( dsTemp.lightmapVecs ) ); + + /* set vertex data */ + dv = &bspDrawVerts[ ds->firstVert ]; + dvParent = &bspDrawVerts[ parent->firstVert ]; + for( j = 0; j < ds->numVerts; j++ ) + { + memcpy( dv[ j ].lightmap, dvParent[ j ].lightmap, sizeof( dv[ j ].lightmap ) ); + memcpy( dv[ j ].color, dvParent[ j ].color, sizeof( dv[ j ].color ) ); + } + + /* skip the rest */ + continue; + } + + /* handle vertex lit or approximated surfaces */ + else if( lm == NULL || lm->outLightmapNums[ 0 ] < 0 ) + { + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + ds->lightmapNum[ lightmapNum ] = -3; + ds->lightmapStyles[ lightmapNum ] = ds->vertexStyles[ lightmapNum ]; + } + } + + /* handle lightmapped surfaces */ + else + { + /* walk lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* set style */ + ds->lightmapStyles[ lightmapNum ] = lm->styles[ lightmapNum ]; + + /* handle unused style */ + if( lm->styles[ lightmapNum ] == LS_NONE || lm->outLightmapNums[ lightmapNum ] < 0 ) + { + ds->lightmapNum[ lightmapNum ] = -3; + continue; + } + + /* get output lightmap */ + olm = &outLightmaps[ lm->outLightmapNums[ lightmapNum ] ]; + + /* set bsp lightmap number */ + ds->lightmapNum[ lightmapNum ] = olm->lightmapNum; + + /* deluxemap debugging makes the deluxemap visible */ + if( deluxemap && debugDeluxemap && lightmapNum == 0 ) + ds->lightmapNum[ lightmapNum ]++; + + /* calc lightmap origin in texture space */ + lmx = (float) lm->lightmapX[ lightmapNum ] / (float) olm->customWidth; + lmy = (float) lm->lightmapY[ lightmapNum ] / (float) olm->customHeight; + + /* calc lightmap st coords */ + dv = &bspDrawVerts[ ds->firstVert ]; + ydv = &yDrawVerts[ ds->firstVert ]; + for( j = 0; j < ds->numVerts; j++ ) + { + if( lm->solid[ lightmapNum ] ) + { + dv[ j ].lightmap[ lightmapNum ][ 0 ] = lmx + (0.5f / (float) olm->customWidth); + dv[ j ].lightmap[ lightmapNum ][ 1 ] = lmy + (0.5f / (float) olm->customWidth); + } + else + { + dv[ j ].lightmap[ lightmapNum ][ 0 ] = lmx + (ydv[ j ].lightmap[ 0 ][ 0 ] / (superSample * olm->customWidth)); + dv[ j ].lightmap[ lightmapNum ][ 1 ] = lmy + (ydv[ j ].lightmap[ 0 ][ 1 ] / (superSample * olm->customHeight)); + } + } + } + } + + /* store vertex colors */ + dv = &bspDrawVerts[ ds->firstVert ]; + for( j = 0; j < ds->numVerts; j++ ) + { + /* walk lightmaps */ + for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* handle unused style */ + if( ds->vertexStyles[ lightmapNum ] == LS_NONE ) + VectorClear( color ); + else + { + /* get vertex color */ + luxel = VERTEX_LUXEL( lightmapNum, ds->firstVert + j ); + VectorCopy( luxel, color ); + + /* set minimum light */ + if( lightmapNum == 0 ) + { + for( k = 0; k < 3; k++ ) + if( color[ k ] < minVertexLight[ k ] ) + color[ k ] = minVertexLight[ k ]; + } + } + + /* store to bytes */ + if( !info->si->noVertexLight ) + ColorToBytes( color, dv[ j ].color[ lightmapNum ], info->si->vertexScale ); + } + } + + /* surfaces with styled lightmaps and a style marker get a custom generated shader (fixme: make this work with external lightmaps) */ + if( olm != NULL && lm != NULL && lm->styles[ 1 ] != LS_NONE && game->load != LoadRBSPFile ) //% info->si->styleMarker > 0 ) + { + qboolean dfEqual; + char key[ 32 ], styleStage[ 512 ], styleStages[ 4096 ], rgbGen[ 128 ], alphaGen[ 128 ]; + + + /* setup */ + sprintf( styleStages, "\n\t// Q3Map2 custom lightstyle stage(s)\n" ); + dv = &bspDrawVerts[ ds->firstVert ]; + + /* depthFunc equal? */ + if( info->si->styleMarker == 2 || info->si->implicitMap == IM_MASKED ) + dfEqual = qtrue; + else + dfEqual = qfalse; + + /* generate stages for styled lightmaps */ + for( lightmapNum = 1; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ ) + { + /* early out */ + style = lm->styles[ lightmapNum ]; + if( style == LS_NONE || lm->outLightmapNums[ lightmapNum ] < 0 ) + continue; + + /* get output lightmap */ + olm = &outLightmaps[ lm->outLightmapNums[ lightmapNum ] ]; + + /* lightmap name */ + if( lm->outLightmapNums[ lightmapNum ] == lm->outLightmapNums[ 0 ] ) + strcpy( lightmapName, "$lightmap" ); + else + sprintf( lightmapName, "maps/%s/" EXTERNAL_LIGHTMAP, mapName, olm->extLightmapNum ); + + /* get rgbgen string */ + if( rgbGenValues[ style ] == NULL ) + { + sprintf( key, "_style%drgbgen", style ); + rgbGenValues[ style ] = ValueForKey( &entities[ 0 ], key ); + if( rgbGenValues[ style ][ 0 ] == '\0' ) + rgbGenValues[ style ] = "wave noise 0.5 1 0 5.37"; + } + rgbGen[ 0 ] = '\0'; + if( rgbGenValues[ style ][ 0 ] != '\0' ) + sprintf( rgbGen, "\t\trgbGen %s // style %d\n", rgbGenValues[ style ], style ); + else + rgbGen[ 0 ] = '\0'; + + /* get alphagen string */ + if( alphaGenValues[ style ] == NULL ) + { + sprintf( key, "_style%dalphagen", style ); + alphaGenValues[ style ] = ValueForKey( &entities[ 0 ], key ); + } + if( alphaGenValues[ style ][ 0 ] != '\0' ) + sprintf( alphaGen, "\t\talphaGen %s // style %d\n", alphaGenValues[ style ], style ); + else + alphaGen[ 0 ] = '\0'; + + /* calculate st offset */ + lmx = dv[ 0 ].lightmap[ lightmapNum ][ 0 ] - dv[ 0 ].lightmap[ 0 ][ 0 ]; + lmy = dv[ 0 ].lightmap[ lightmapNum ][ 1 ] - dv[ 0 ].lightmap[ 0 ][ 1 ]; + + /* create additional stage */ + if( lmx == 0.0f && lmy == 0.0f ) + { + sprintf( styleStage, "\t{\n" + "\t\tmap %s\n" /* lightmap */ + "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" + "%s" /* depthFunc equal */ + "%s" /* rgbGen */ + "%s" /* alphaGen */ + "\t\ttcGen lightmap\n" + "\t}\n", + lightmapName, + (dfEqual ? "\t\tdepthFunc equal\n" : ""), + rgbGen, + alphaGen ); + } + else + { + sprintf( styleStage, "\t{\n" + "\t\tmap %s\n" /* lightmap */ + "\t\tblendFunc GL_SRC_ALPHA GL_ONE\n" + "%s" /* depthFunc equal */ + "%s" /* rgbGen */ + "%s" /* alphaGen */ + "\t\ttcGen lightmap\n" + "\t\ttcMod transform 1 0 0 1 %1.5f %1.5f\n" /* st offset */ + "\t}\n", + lightmapName, + (dfEqual ? "\t\tdepthFunc equal\n" : ""), + rgbGen, + alphaGen, + lmx, lmy ); + + } + + /* concatenate */ + strcat( styleStages, styleStage ); + } + + /* create custom shader */ + if( info->si->styleMarker == 2 ) + csi = CustomShader( info->si, "q3map_styleMarker2", styleStages ); + else + csi = CustomShader( info->si, "q3map_styleMarker", styleStages ); + + /* emit remap command */ + //% EmitVertexRemapShader( csi->shader, info->si->shader ); + + /* store it */ + //% Sys_Printf( "Emitting: %s (%d", csi->shader, strlen( csi->shader ) ); + ds->shaderNum = EmitShader( csi->shader, &bspShaders[ ds->shaderNum ].contentFlags, &bspShaders[ ds->shaderNum ].surfaceFlags ); + //% Sys_Printf( ")\n" ); + } + + /* devise a custom shader for this surface (fixme: make this work with light styles) */ + else if( olm != NULL && lm != NULL && !externalLightmaps && + (olm->customWidth != game->lightmapSize || olm->customHeight != game->lightmapSize) ) + { + /* get output lightmap */ + olm = &outLightmaps[ lm->outLightmapNums[ 0 ] ]; + + /* do some name mangling */ + sprintf( lightmapName, "maps/%s/" EXTERNAL_LIGHTMAP, mapName, olm->extLightmapNum ); + + /* create custom shader */ + csi = CustomShader( info->si, "$lightmap", lightmapName ); + + /* store it */ + //% Sys_Printf( "Emitting: %s (%d", csi->shader, strlen( csi->shader ) ); + ds->shaderNum = EmitShader( csi->shader, &bspShaders[ ds->shaderNum ].contentFlags, &bspShaders[ ds->shaderNum ].surfaceFlags ); + //% Sys_Printf( ")\n" ); + } + + /* use the normal plain-jane shader */ + else + ds->shaderNum = EmitShader( info->si->shader, &bspShaders[ ds->shaderNum ].contentFlags, &bspShaders[ ds->shaderNum ].surfaceFlags ); + } + + /* finish */ + Sys_Printf( "done.\n" ); + + /* calc num stored */ + numStored = numBSPLightBytes / 3; + efficiency = (numStored <= 0) + ? 0 + : (float) numUsed / (float) numStored; + + /* print stats */ + Sys_Printf( "%9d luxels used\n", numUsed ); + Sys_Printf( "%9d luxels stored (%3.2f percent efficiency)\n", numStored, efficiency * 100.0f ); + Sys_Printf( "%9d solid surface lightmaps\n", numSolidLightmaps ); + Sys_Printf( "%9d identical surface lightmaps, using %d luxels\n", numTwins, numTwinLuxels ); + Sys_Printf( "%9d vertex forced surfaces\n", numSurfsVertexForced ); + Sys_Printf( "%9d vertex approximated surfaces\n", numSurfsVertexApproximated ); + Sys_Printf( "%9d BSP lightmaps\n", numBSPLightmaps ); + Sys_Printf( "%9d total lightmaps\n", numOutLightmaps ); + Sys_Printf( "%9d unique lightmap/shader combinations\n", numLightmapShaders ); + + /* write map shader file */ + WriteMapShaderFile(); +} + + + + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/listen.pl b/misc/mediasource/netradiant-src/tools/quake3/q3map2/listen.pl new file mode 100644 index 00000000..6101a767 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/listen.pl @@ -0,0 +1,46 @@ +#!/usr/bin/perl -w + +use IO::Socket; +use Net::hostent; + +my $port = shift || 13131; + +my $server = IO::Socket::INET->new( + Proto => 'tcp', + LocalPort => $port, + Listen => SOMAXCONN, + Reuse => 1 ) + || die "can't setup server"; +print "[Q3Map2 listener $0 is now active on port $port]\n"; + +while( $client = $server->accept() ) +{ + + $client->autoflush( 1 ); + + $hostinfo = gethostbyaddr( $client->peeraddr ); + printf "[Connect from %s]\n\n", $hostinfo ? $hostinfo->name : $client->peerhost; + + #ask the client for a command + print $client "[server]\$"; + my $text = ""; + while( <$client> ) + { + $text .= $_; + while( $text =~ s|]*>([^<]+)|| ) + { + my $msg = $1; + + # fix xml ents + $msg =~ s|<|<|g; + $msg =~ s|>|>|g; + $msg =~ s|"|"|g;#" + $msg =~ s|'|'|g;#' + + print $msg; + } + } + + printf "\n[Disconnected: %s]\n\n", $hostinfo ? $hostinfo->name : $client->peerhost; + close $client; +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/main.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/main.c new file mode 100644 index 00000000..074a4a43 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/main.c @@ -0,0 +1,1847 @@ +/* -------------------------------------------------------------------------------; + +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 + +------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define MAIN_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +Random() +returns a pseudorandom number between 0 and 1 +*/ + +vec_t Random( void ) +{ + return (vec_t) rand() / RAND_MAX; +} + + + +/* +ExitQ3Map() +cleanup routine +*/ + +static void ExitQ3Map( void ) +{ + BSPFilesCleanup(); + if( mapDrawSurfs != NULL ) + free( mapDrawSurfs ); +} + + + +/* minimap stuff */ + +typedef struct minimap_s +{ + bspModel_t *model; + int width; + int height; + int samples; + float *sample_offsets; + float sharpen_boxmult; + float sharpen_centermult; + float boost; + float *data1f; + float *sharpendata1f; + vec3_t mins, size; +} +minimap_t; +static minimap_t minimap; + +qboolean BrushIntersectionWithLine(bspBrush_t *brush, vec3_t start, vec3_t dir, float *t_in, float *t_out) +{ + int i; + qboolean in = qfalse, out = qfalse; + bspBrushSide_t *sides = &bspBrushSides[brush->firstSide]; + + for(i = 0; i < brush->numSides; ++i) + { + bspPlane_t *p = &bspPlanes[sides[i].planeNum]; + float sn = DotProduct(start, p->normal); + float dn = DotProduct(dir, p->normal); + if(dn == 0) + { + if(sn > p->dist) + return qfalse; // outside! + } + else + { + float t = (p->dist - sn) / dn; + if(dn < 0) + { + if(!in || t > *t_in) + { + *t_in = t; + in = qtrue; + // as t_in can only increase, and t_out can only decrease, early out + if(out && *t_in >= *t_out) + return qfalse; + } + } + else + { + if(!out || t < *t_out) + { + *t_out = t; + out = qtrue; + // as t_in can only increase, and t_out can only decrease, early out + if(in && *t_in >= *t_out) + return qfalse; + } + } + } + } + return in && out; +} + +static float MiniMapSample(float x, float y) +{ + vec3_t org, dir; + int i, bi; + float t0, t1; + float samp; + bspBrush_t *b; + bspBrushSide_t *s; + int cnt; + + org[0] = x; + org[1] = y; + org[2] = 0; + dir[0] = 0; + dir[1] = 0; + dir[2] = 1; + + cnt = 0; + samp = 0; + for(i = 0; i < minimap.model->numBSPBrushes; ++i) + { + bi = minimap.model->firstBSPBrush + i; + if(opaqueBrushes[bi >> 3] & (1 << (bi & 7))) + { + b = &bspBrushes[bi]; + + // sort out mins/maxs of the brush + s = &bspBrushSides[b->firstSide]; + if(x < -bspPlanes[s[0].planeNum].dist) + continue; + if(x > +bspPlanes[s[1].planeNum].dist) + continue; + if(y < -bspPlanes[s[2].planeNum].dist) + continue; + if(y > +bspPlanes[s[3].planeNum].dist) + continue; + + if(BrushIntersectionWithLine(b, org, dir, &t0, &t1)) + { + samp += t1 - t0; + ++cnt; + } + } + } + + return samp; +} + +void RandomVector2f(float v[2]) +{ + do + { + v[0] = 2 * Random() - 1; + v[1] = 2 * Random() - 1; + } + while(v[0] * v[0] + v[1] * v[1] > 1); +} + +static void MiniMapRandomlySupersampled(int y) +{ + int x, i; + float *p = &minimap.data1f[y * minimap.width]; + float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height); + float dx = minimap.size[0] / (float) minimap.width; + float dy = minimap.size[1] / (float) minimap.height; + float uv[2]; + float thisval; + + for(x = 0; x < minimap.width; ++x) + { + float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width); + float val = 0; + + for(i = 0; i < minimap.samples; ++i) + { + RandomVector2f(uv); + thisval = MiniMapSample( + xmin + (uv[0] + 0.5) * dx, /* exaggerated random pattern for better results */ + ymin + (uv[1] + 0.5) * dy /* exaggerated random pattern for better results */ + ); + val += thisval; + } + val /= minimap.samples * minimap.size[2]; + *p++ = val; + } +} + +static void MiniMapSupersampled(int y) +{ + int x, i; + float *p = &minimap.data1f[y * minimap.width]; + float ymin = minimap.mins[1] + minimap.size[1] * (y / (float) minimap.height); + float dx = minimap.size[0] / (float) minimap.width; + float dy = minimap.size[1] / (float) minimap.height; + + for(x = 0; x < minimap.width; ++x) + { + float xmin = minimap.mins[0] + minimap.size[0] * (x / (float) minimap.width); + float val = 0; + + for(i = 0; i < minimap.samples; ++i) + { + float thisval = MiniMapSample( + xmin + minimap.sample_offsets[2*i+0] * dx, + ymin + minimap.sample_offsets[2*i+1] * dy + ); + val += thisval; + } + val /= minimap.samples * minimap.size[2]; + *p++ = val; + } +} + +static void MiniMapNoSupersampling(int y) +{ + int x; + float *p = &minimap.data1f[y * minimap.width]; + float ymin = minimap.mins[1] + minimap.size[1] * ((y + 0.5) / (float) minimap.height); + + for(x = 0; x < minimap.width; ++x) + { + float xmin = minimap.mins[0] + minimap.size[0] * ((x + 0.5) / (float) minimap.width); + *p++ = MiniMapSample(xmin, ymin) / minimap.size[2]; + } +} + +static void MiniMapSharpen(int y) +{ + int x; + qboolean up = (y > 0); + qboolean down = (y < minimap.height - 1); + float *p = &minimap.data1f[y * minimap.width]; + float *q = &minimap.sharpendata1f[y * minimap.width]; + + for(x = 0; x < minimap.width; ++x) + { + qboolean left = (x > 0); + qboolean right = (x < minimap.width - 1); + float val = p[0] * minimap.sharpen_centermult; + + if(left && up) + val += p[-1 -minimap.width] * minimap.sharpen_boxmult; + if(left && down) + val += p[-1 +minimap.width] * minimap.sharpen_boxmult; + if(right && up) + val += p[+1 -minimap.width] * minimap.sharpen_boxmult; + if(right && down) + val += p[+1 +minimap.width] * minimap.sharpen_boxmult; + + if(left) + val += p[-1] * minimap.sharpen_boxmult; + if(right) + val += p[+1] * minimap.sharpen_boxmult; + if(up) + val += p[-minimap.width] * minimap.sharpen_boxmult; + if(down) + val += p[+minimap.width] * minimap.sharpen_boxmult; + + ++p; + *q++ = val; + } +} + +static void MiniMapContrastBoost(int y) +{ + int x; + float *q = &minimap.data1f[y * minimap.width]; + for(x = 0; x < minimap.width; ++x) + { + *q = *q * minimap.boost / ((minimap.boost - 1) * *q + 1); + ++q; + } +} + +void MiniMapMakeMinsMaxs(vec3_t mins_in, vec3_t maxs_in, float border, qboolean keepaspect) +{ + vec3_t mins, maxs, extend; + VectorCopy(mins_in, mins); + VectorCopy(maxs_in, maxs); + + // line compatible to nexuiz mapinfo + Sys_Printf("size %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]); + + if(keepaspect) + { + VectorSubtract(maxs, mins, extend); + if(extend[1] > extend[0]) + { + mins[0] -= (extend[1] - extend[0]) * 0.5; + maxs[0] += (extend[1] - extend[0]) * 0.5; + } + else + { + mins[1] -= (extend[0] - extend[1]) * 0.5; + maxs[1] += (extend[0] - extend[1]) * 0.5; + } + } + + /* border: amount of black area around the image */ + /* input: border, 1-2*border, border but we need border/(1-2*border) */ + + VectorSubtract(maxs, mins, extend); + VectorScale(extend, border / (1 - 2 * border), extend); + + VectorSubtract(mins, extend, mins); + VectorAdd(maxs, extend, maxs); + + VectorCopy(mins, minimap.mins); + VectorSubtract(maxs, mins, minimap.size); + + // line compatible to nexuiz mapinfo + Sys_Printf("size_texcoords %f %f %f %f %f %f\n", mins[0], mins[1], mins[2], maxs[0], maxs[1], maxs[2]); +} + +/* +MiniMapSetupBrushes() +determines solid non-sky brushes in the world +*/ + +void MiniMapSetupBrushes( void ) +{ + int i, b, compileFlags; + bspBrush_t *brush; + bspShader_t *shader; + shaderInfo_t *si; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- MiniMapSetupBrushes ---\n" ); + + /* allocate */ + if( opaqueBrushes == NULL ) + opaqueBrushes = safe_malloc( numBSPBrushes / 8 + 1 ); + + /* clear */ + memset( opaqueBrushes, 0, numBSPBrushes / 8 + 1 ); + numOpaqueBrushes = 0; + + /* walk the list of worldspawn brushes */ + for( i = 0; i < minimap.model->numBSPBrushes; i++ ) + { + /* get brush */ + b = minimap.model->firstBSPBrush + i; + brush = &bspBrushes[ b ]; + +#if 0 + /* check all sides */ + compileFlags = 0; + for( j = 0; j < brush->numSides; j++ ) + { + /* do bsp shader calculations */ + side = &bspBrushSides[ brush->firstSide + j ]; + shader = &bspShaders[ side->shaderNum ]; + + /* get shader info */ + si = ShaderInfoForShader( shader->shader ); + if( si == NULL ) + continue; + + /* or together compile flags */ + compileFlags |= si->compileFlags; + } +#else + shader = &bspShaders[ brush->shaderNum ]; + si = ShaderInfoForShader( shader->shader ); + if( si == NULL ) + compileFlags = 0; + else + compileFlags = si->compileFlags; +#endif + + /* determine if this brush is solid */ + if( (compileFlags & (C_SOLID | C_SKY)) == C_SOLID ) + { + opaqueBrushes[ b >> 3 ] |= (1 << (b & 7)); + numOpaqueBrushes++; + maxOpaqueBrush = i; + } + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d solid brushes\n", numOpaqueBrushes ); +} + +qboolean MiniMapEvaluateSampleOffsets(int *bestj, int *bestk, float *bestval) +{ + float val, dx, dy; + int j, k; + + *bestj = *bestk = -1; + *bestval = 3; /* max possible val is 2 */ + + for(j = 0; j < minimap.samples; ++j) + for(k = j + 1; k < minimap.samples; ++k) + { + dx = minimap.sample_offsets[2*j+0] - minimap.sample_offsets[2*k+0]; + dy = minimap.sample_offsets[2*j+1] - minimap.sample_offsets[2*k+1]; + if(dx > +0.5) dx -= 1; + if(dx < -0.5) dx += 1; + if(dy > +0.5) dy -= 1; + if(dy < -0.5) dy += 1; + val = dx * dx + dy * dy; + if(val < *bestval) + { + *bestj = j; + *bestk = k; + *bestval = val; + } + } + + return *bestval < 3; +} + +void MiniMapMakeSampleOffsets() +{ + int i, j, k, jj, kk; + float val, valj, valk, sx, sy, rx, ry; + + Sys_Printf( "Generating good sample offsets (this may take a while)...\n" ); + + /* start with entirely random samples */ + for(i = 0; i < minimap.samples; ++i) + { + minimap.sample_offsets[2*i+0] = Random(); + minimap.sample_offsets[2*i+1] = Random(); + } + + for(i = 0; i < 1000; ++i) + { + if(MiniMapEvaluateSampleOffsets(&j, &k, &val)) + { + sx = minimap.sample_offsets[2*j+0]; + sy = minimap.sample_offsets[2*j+1]; + minimap.sample_offsets[2*j+0] = rx = Random(); + minimap.sample_offsets[2*j+1] = ry = Random(); + if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valj)) + valj = -1; + minimap.sample_offsets[2*j+0] = sx; + minimap.sample_offsets[2*j+1] = sy; + + sx = minimap.sample_offsets[2*k+0]; + sy = minimap.sample_offsets[2*k+1]; + minimap.sample_offsets[2*k+0] = rx; + minimap.sample_offsets[2*k+1] = ry; + if(!MiniMapEvaluateSampleOffsets(&jj, &kk, &valk)) + valk = -1; + minimap.sample_offsets[2*k+0] = sx; + minimap.sample_offsets[2*k+1] = sy; + + if(valj > valk) + { + if(valj > val) + { + /* valj is the greatest */ + minimap.sample_offsets[2*j+0] = rx; + minimap.sample_offsets[2*j+1] = ry; + i = -1; + } + else + { + /* valj is the greater and it is useless - forget it */ + } + } + else + { + if(valk > val) + { + /* valk is the greatest */ + minimap.sample_offsets[2*k+0] = rx; + minimap.sample_offsets[2*k+1] = ry; + i = -1; + } + else + { + /* valk is the greater and it is useless - forget it */ + } + } + } + else + break; + } +} + +void MergeRelativePath(char *out, const char *absolute, const char *relative) +{ + const char *endpos = absolute + strlen(absolute); + while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\')) + --endpos; + while(relative[0] == '.' && relative[1] == '.' && (relative[2] == '/' || relative[2] == '\\')) + { + relative += 3; + while(endpos != absolute) + { + --endpos; + if(*endpos == '/' || *endpos == '\\') + break; + } + while(endpos != absolute && (endpos[-1] == '/' || endpos[-1] == '\\')) + --endpos; + } + memcpy(out, absolute, endpos - absolute); + out[endpos - absolute] = '/'; + strcpy(out + (endpos - absolute + 1), relative); +} + +int MiniMapBSPMain( int argc, char **argv ) +{ + char minimapFilename[1024]; + char basename[1024]; + char path[1024]; + char relativeMinimapFilename[1024]; + float minimapSharpen; + float border; + byte *data4b, *p; + float *q; + int x, y; + int i; + miniMapMode_t mode; + vec3_t mins, maxs; + qboolean keepaspect; + + /* arg checking */ + if( argc < 2 ) + { + Sys_Printf( "Usage: q3map [-v] -minimap [-size n] [-sharpen f] [-samples n | -random n] [-o filename.tga] [-minmax Xmin Ymin Zmin Xmax Ymax Zmax] \n" ); + return 0; + } + + /* load the BSP first */ + strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + Sys_Printf( "Loading %s\n", source ); + BeginMapShaderFile( source ); + LoadShaderInfo(); + LoadBSPFile( source ); + + minimap.model = &bspModels[0]; + VectorCopy(minimap.model->mins, mins); + VectorCopy(minimap.model->maxs, maxs); + + *minimapFilename = 0; + minimapSharpen = game->miniMapSharpen; + minimap.width = minimap.height = game->miniMapSize; + border = game->miniMapBorder; + keepaspect = game->miniMapKeepAspect; + mode = game->miniMapMode; + + minimap.samples = 1; + minimap.sample_offsets = NULL; + minimap.boost = 1.0; + + /* process arguments */ + for( i = 1; i < (argc - 1); i++ ) + { + if( !strcmp( argv[ i ], "-size" ) ) + { + minimap.width = minimap.height = atoi(argv[i + 1]); + i++; + Sys_Printf( "Image size set to %i\n", minimap.width ); + } + else if( !strcmp( argv[ i ], "-sharpen" ) ) + { + minimapSharpen = atof(argv[i + 1]); + i++; + Sys_Printf( "Sharpening coefficient set to %f\n", minimapSharpen ); + } + else if( !strcmp( argv[ i ], "-samples" ) ) + { + minimap.samples = atoi(argv[i + 1]); + i++; + Sys_Printf( "Samples set to %i\n", minimap.samples ); + if(minimap.sample_offsets) + free(minimap.sample_offsets); + minimap.sample_offsets = malloc(2 * sizeof(*minimap.sample_offsets) * minimap.samples); + MiniMapMakeSampleOffsets(); + } + else if( !strcmp( argv[ i ], "-random" ) ) + { + minimap.samples = atoi(argv[i + 1]); + i++; + Sys_Printf( "Random samples set to %i\n", minimap.samples ); + if(minimap.sample_offsets) + free(minimap.sample_offsets); + minimap.sample_offsets = NULL; + } + else if( !strcmp( argv[ i ], "-border" ) ) + { + border = atof(argv[i + 1]); + i++; + Sys_Printf( "Border set to %f\n", border ); + } + else if( !strcmp( argv[ i ], "-keepaspect" ) ) + { + keepaspect = qtrue; + Sys_Printf( "Keeping aspect ratio by letterboxing\n", border ); + } + else if( !strcmp( argv[ i ], "-nokeepaspect" ) ) + { + keepaspect = qfalse; + Sys_Printf( "Not keeping aspect ratio\n", border ); + } + else if( !strcmp( argv[ i ], "-o" ) ) + { + strcpy(minimapFilename, argv[i + 1]); + i++; + Sys_Printf( "Output file name set to %s\n", minimapFilename ); + } + else if( !strcmp( argv[ i ], "-minmax" ) && i < (argc - 7) ) + { + mins[0] = atof(argv[i + 1]); + mins[1] = atof(argv[i + 2]); + mins[2] = atof(argv[i + 3]); + maxs[0] = atof(argv[i + 4]); + maxs[1] = atof(argv[i + 5]); + maxs[2] = atof(argv[i + 6]); + i += 6; + Sys_Printf( "Map mins/maxs overridden\n" ); + } + else if( !strcmp( argv[ i ], "-gray" ) ) + { + mode = MINIMAP_MODE_GRAY; + Sys_Printf( "Writing as white-on-black image\n" ); + } + else if( !strcmp( argv[ i ], "-black" ) ) + { + mode = MINIMAP_MODE_BLACK; + Sys_Printf( "Writing as black alpha image\n" ); + } + else if( !strcmp( argv[ i ], "-white" ) ) + { + mode = MINIMAP_MODE_WHITE; + Sys_Printf( "Writing as white alpha image\n" ); + } + else if( !strcmp( argv[ i ], "-boost" ) ) + { + minimap.boost = atof(argv[i + 1]); + i++; + Sys_Printf( "Contrast boost set to %f\n", minimap.boost ); + } + } + + MiniMapMakeMinsMaxs(mins, maxs, border, keepaspect); + + if(!*minimapFilename) + { + ExtractFileBase(source, basename); + ExtractFilePath(source, path); + sprintf(relativeMinimapFilename, game->miniMapNameFormat, basename); + MergeRelativePath(minimapFilename, path, relativeMinimapFilename); + Sys_Printf("Output file name automatically set to %s\n", minimapFilename); + } + ExtractFilePath(minimapFilename, path); + Q_mkdir(path); + + if(minimapSharpen >= 0) + { + minimap.sharpen_centermult = 8 * minimapSharpen + 1; + minimap.sharpen_boxmult = -minimapSharpen; + } + + minimap.data1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f)); + data4b = safe_malloc(minimap.width * minimap.height * 4); + if(minimapSharpen >= 0) + minimap.sharpendata1f = safe_malloc(minimap.width * minimap.height * sizeof(*minimap.data1f)); + + MiniMapSetupBrushes(); + + if(minimap.samples <= 1) + { + Sys_Printf( "\n--- MiniMapNoSupersampling (%d) ---\n", minimap.height ); + RunThreadsOnIndividual(minimap.height, qtrue, MiniMapNoSupersampling); + } + else + { + if(minimap.sample_offsets) + { + Sys_Printf( "\n--- MiniMapSupersampled (%d) ---\n", minimap.height ); + RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSupersampled); + } + else + { + Sys_Printf( "\n--- MiniMapRandomlySupersampled (%d) ---\n", minimap.height ); + RunThreadsOnIndividual(minimap.height, qtrue, MiniMapRandomlySupersampled); + } + } + + if(minimap.boost != 1.0) + { + Sys_Printf( "\n--- MiniMapContrastBoost (%d) ---\n", minimap.height ); + RunThreadsOnIndividual(minimap.height, qtrue, MiniMapContrastBoost); + } + + if(minimap.sharpendata1f) + { + Sys_Printf( "\n--- MiniMapSharpen (%d) ---\n", minimap.height ); + RunThreadsOnIndividual(minimap.height, qtrue, MiniMapSharpen); + q = minimap.sharpendata1f; + } + else + { + q = minimap.data1f; + } + + Sys_Printf( "\nConverting..."); + + switch(mode) + { + case MINIMAP_MODE_GRAY: + p = data4b; + for(y = 0; y < minimap.height; ++y) + for(x = 0; x < minimap.width; ++x) + { + byte b; + float v = *q++; + if(v < 0) v = 0; + if(v > 255.0/256.0) v = 255.0/256.0; + b = v * 256; + *p++ = b; + } + Sys_Printf( " writing to %s...", minimapFilename ); + WriteTGAGray(minimapFilename, data4b, minimap.width, minimap.height); + break; + case MINIMAP_MODE_BLACK: + p = data4b; + for(y = 0; y < minimap.height; ++y) + for(x = 0; x < minimap.width; ++x) + { + byte b; + float v = *q++; + if(v < 0) v = 0; + if(v > 255.0/256.0) v = 255.0/256.0; + b = v * 256; + *p++ = 0; + *p++ = 0; + *p++ = 0; + *p++ = b; + } + Sys_Printf( " writing to %s...", minimapFilename ); + WriteTGA(minimapFilename, data4b, minimap.width, minimap.height); + break; + case MINIMAP_MODE_WHITE: + p = data4b; + for(y = 0; y < minimap.height; ++y) + for(x = 0; x < minimap.width; ++x) + { + byte b; + float v = *q++; + if(v < 0) v = 0; + if(v > 255.0/256.0) v = 255.0/256.0; + b = v * 256; + *p++ = 255; + *p++ = 255; + *p++ = 255; + *p++ = b; + } + Sys_Printf( " writing to %s...", minimapFilename ); + WriteTGA(minimapFilename, data4b, minimap.width, minimap.height); + break; + } + + Sys_Printf( " done.\n" ); + + /* return to sender */ + return 0; +} + + + + + +/* +MD4BlockChecksum() +calculates an md4 checksum for a block of data +*/ + +static int MD4BlockChecksum( void *buffer, int length ) +{ + return Com_BlockChecksum(buffer, length); +} + +/* +FixAAS() +resets an aas checksum to match the given BSP +*/ + +int FixAAS( int argc, char **argv ) +{ + int length, checksum; + void *buffer; + FILE *file; + char aas[ 1024 ], **ext; + char *exts[] = + { + ".aas", + "_b0.aas", + "_b1.aas", + NULL + }; + + + /* arg checking */ + if( argc < 2 ) + { + Sys_Printf( "Usage: q3map -fixaas [-v] \n" ); + return 0; + } + + /* do some path mangling */ + strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + + /* note it */ + Sys_Printf( "--- FixAAS ---\n" ); + + /* load the bsp */ + Sys_Printf( "Loading %s\n", source ); + length = LoadFile( source, &buffer ); + + /* create bsp checksum */ + Sys_Printf( "Creating checksum...\n" ); + checksum = LittleLong( MD4BlockChecksum( buffer, length ) ); + + /* write checksum to aas */ + ext = exts; + while( *ext ) + { + /* mangle name */ + strcpy( aas, source ); + StripExtension( aas ); + strcat( aas, *ext ); + Sys_Printf( "Trying %s\n", aas ); + ext++; + + /* fix it */ + file = fopen( aas, "r+b" ); + if( !file ) + continue; + if( fwrite( &checksum, 4, 1, file ) != 1 ) + Error( "Error writing checksum to %s", aas ); + fclose( file ); + } + + /* return to sender */ + return 0; +} + + + +/* +AnalyzeBSP() - ydnar +analyzes a Quake engine BSP file +*/ + +typedef struct abspHeader_s +{ + char ident[ 4 ]; + int version; + + bspLump_t lumps[ 1 ]; /* unknown size */ +} +abspHeader_t; + +typedef struct abspLumpTest_s +{ + int radix, minCount; + char *name; +} +abspLumpTest_t; + +int AnalyzeBSP( int argc, char **argv ) +{ + abspHeader_t *header; + int size, i, version, offset, length, lumpInt, count; + char ident[ 5 ]; + void *lump; + float lumpFloat; + char lumpString[ 1024 ], source[ 1024 ]; + qboolean lumpSwap = qfalse; + abspLumpTest_t *lumpTest; + static abspLumpTest_t lumpTests[] = + { + { sizeof( bspPlane_t ), 6, "IBSP LUMP_PLANES" }, + { sizeof( bspBrush_t ), 1, "IBSP LUMP_BRUSHES" }, + { 8, 6, "IBSP LUMP_BRUSHSIDES" }, + { sizeof( bspBrushSide_t ), 6, "RBSP LUMP_BRUSHSIDES" }, + { sizeof( bspModel_t ), 1, "IBSP LUMP_MODELS" }, + { sizeof( bspNode_t ), 2, "IBSP LUMP_NODES" }, + { sizeof( bspLeaf_t ), 1, "IBSP LUMP_LEAFS" }, + { 104, 3, "IBSP LUMP_DRAWSURFS" }, + { 44, 3, "IBSP LUMP_DRAWVERTS" }, + { 4, 6, "IBSP LUMP_DRAWINDEXES" }, + { 128 * 128 * 3, 1, "IBSP LUMP_LIGHTMAPS" }, + { 256 * 256 * 3, 1, "IBSP LUMP_LIGHTMAPS (256 x 256)" }, + { 512 * 512 * 3, 1, "IBSP LUMP_LIGHTMAPS (512 x 512)" }, + { 0, 0, NULL } + }; + + + /* arg checking */ + if( argc < 1 ) + { + Sys_Printf( "Usage: q3map -analyze [-lumpswap] [-v] \n" ); + return 0; + } + + /* process arguments */ + for( i = 1; i < (argc - 1); i++ ) + { + /* -format map|ase|... */ + if( !strcmp( argv[ i ], "-lumpswap" ) ) + { + Sys_Printf( "Swapped lump structs enabled\n" ); + lumpSwap = qtrue; + } + } + + /* clean up map name */ + strcpy( source, ExpandArg( argv[ i ] ) ); + Sys_Printf( "Loading %s\n", source ); + + /* load the file */ + size = LoadFile( source, (void**) &header ); + if( size == 0 || header == NULL ) + { + Sys_Printf( "Unable to load %s.\n", source ); + return -1; + } + + /* analyze ident/version */ + memcpy( ident, header->ident, 4 ); + ident[ 4 ] = '\0'; + version = LittleLong( header->version ); + + Sys_Printf( "Identity: %s\n", ident ); + Sys_Printf( "Version: %d\n", version ); + Sys_Printf( "---------------------------------------\n" ); + + /* analyze each lump */ + for( i = 0; i < 100; i++ ) + { + /* call of duty swapped lump pairs */ + if( lumpSwap ) + { + offset = LittleLong( header->lumps[ i ].length ); + length = LittleLong( header->lumps[ i ].offset ); + } + + /* standard lump pairs */ + else + { + offset = LittleLong( header->lumps[ i ].offset ); + length = LittleLong( header->lumps[ i ].length ); + } + + /* extract data */ + lump = (byte*) header + offset; + lumpInt = LittleLong( (int) *((int*) lump) ); + lumpFloat = LittleFloat( (float) *((float*) lump) ); + memcpy( lumpString, (char*) lump, (length < sizeof(lumpString) ? length : sizeof(lumpString)-1) ); + lumpString[ sizeof(lumpString)-1 ] = '\0'; + + /* print basic lump info */ + Sys_Printf( "Lump: %d\n", i ); + Sys_Printf( "Offset: %d bytes\n", offset ); + Sys_Printf( "Length: %d bytes\n", length ); + + /* only operate on valid lumps */ + if( length > 0 ) + { + /* print data in 4 formats */ + Sys_Printf( "As hex: %08X\n", lumpInt ); + Sys_Printf( "As int: %d\n", lumpInt ); + Sys_Printf( "As float: %f\n", lumpFloat ); + Sys_Printf( "As string: %s\n", lumpString ); + + /* guess lump type */ + if( lumpString[ 0 ] == '{' && lumpString[ 2 ] == '"' ) + Sys_Printf( "Type guess: IBSP LUMP_ENTITIES\n" ); + else if( strstr( lumpString, "textures/" ) ) + Sys_Printf( "Type guess: IBSP LUMP_SHADERS\n" ); + else + { + /* guess based on size/count */ + for( lumpTest = lumpTests; lumpTest->radix > 0; lumpTest++ ) + { + if( (length % lumpTest->radix) != 0 ) + continue; + count = length / lumpTest->radix; + if( count < lumpTest->minCount ) + continue; + Sys_Printf( "Type guess: %s (%d x %d)\n", lumpTest->name, count, lumpTest->radix ); + } + } + } + + Sys_Printf( "---------------------------------------\n" ); + + /* end of file */ + if( offset + length >= size ) + break; + } + + /* last stats */ + Sys_Printf( "Lump count: %d\n", i + 1 ); + Sys_Printf( "File size: %d bytes\n", size ); + + /* return to caller */ + return 0; +} + + + +/* +BSPInfo() +emits statistics about the bsp file +*/ + +int BSPInfo( int count, char **fileNames ) +{ + int i; + char source[ 1024 ], ext[ 64 ]; + int size; + FILE *f; + + + /* dummy check */ + if( count < 1 ) + { + Sys_Printf( "No files to dump info for.\n"); + return -1; + } + + /* enable info mode */ + infoMode = qtrue; + + /* walk file list */ + for( i = 0; i < count; i++ ) + { + Sys_Printf( "---------------------------------\n" ); + + /* mangle filename and get size */ + strcpy( source, fileNames[ i ] ); + ExtractFileExtension( source, ext ); + if( !Q_stricmp( ext, "map" ) ) + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + f = fopen( source, "rb" ); + if( f ) + { + size = Q_filelength (f); + fclose( f ); + } + else + size = 0; + + /* load the bsp file and print lump sizes */ + Sys_Printf( "%s\n", source ); + LoadBSPFile( source ); + PrintBSPFileSizes(); + + /* print sizes */ + Sys_Printf( "\n" ); + Sys_Printf( " total %9d\n", size ); + Sys_Printf( " %9d KB\n", size / 1024 ); + Sys_Printf( " %9d MB\n", size / (1024 * 1024) ); + + Sys_Printf( "---------------------------------\n" ); + } + + /* return count */ + return i; +} + + +static void ExtrapolateTexcoords(const float *axyz, const float *ast, const float *bxyz, const float *bst, const float *cxyz, const float *cst, const float *axyz_new, float *ast_out, const float *bxyz_new, float *bst_out, const float *cxyz_new, float *cst_out) +{ + vec4_t scoeffs, tcoeffs; + float md; + m4x4_t solvematrix; + + vec3_t norm; + vec3_t dab, dac; + VectorSubtract(bxyz, axyz, dab); + VectorSubtract(cxyz, axyz, dac); + CrossProduct(dab, dac, norm); + + // assume: + // s = f(x, y, z) + // s(v + norm) = s(v) when n ortho xyz + + // s(v) = DotProduct(v, scoeffs) + scoeffs[3] + + // solve: + // scoeffs * (axyz, 1) == ast[0] + // scoeffs * (bxyz, 1) == bst[0] + // scoeffs * (cxyz, 1) == cst[0] + // scoeffs * (norm, 0) == 0 + // scoeffs * [axyz, 1 | bxyz, 1 | cxyz, 1 | norm, 0] = [ast[0], bst[0], cst[0], 0] + solvematrix[0] = axyz[0]; + solvematrix[4] = axyz[1]; + solvematrix[8] = axyz[2]; + solvematrix[12] = 1; + solvematrix[1] = bxyz[0]; + solvematrix[5] = bxyz[1]; + solvematrix[9] = bxyz[2]; + solvematrix[13] = 1; + solvematrix[2] = cxyz[0]; + solvematrix[6] = cxyz[1]; + solvematrix[10] = cxyz[2]; + solvematrix[14] = 1; + solvematrix[3] = norm[0]; + solvematrix[7] = norm[1]; + solvematrix[11] = norm[2]; + solvematrix[15] = 0; + + md = m4_det(solvematrix); + if(md*md < 1e-10) + { + Sys_Printf("Cannot invert some matrix, some texcoords aren't extrapolated!"); + return; + } + + m4x4_invert(solvematrix); + + scoeffs[0] = ast[0]; + scoeffs[1] = bst[0]; + scoeffs[2] = cst[0]; + scoeffs[3] = 0; + m4x4_transform_vec4(solvematrix, scoeffs); + tcoeffs[0] = ast[1]; + tcoeffs[1] = bst[1]; + tcoeffs[2] = cst[1]; + tcoeffs[3] = 0; + m4x4_transform_vec4(solvematrix, tcoeffs); + + ast_out[0] = scoeffs[0] * axyz_new[0] + scoeffs[1] * axyz_new[1] + scoeffs[2] * axyz_new[2] + scoeffs[3]; + ast_out[1] = tcoeffs[0] * axyz_new[0] + tcoeffs[1] * axyz_new[1] + tcoeffs[2] * axyz_new[2] + tcoeffs[3]; + bst_out[0] = scoeffs[0] * bxyz_new[0] + scoeffs[1] * bxyz_new[1] + scoeffs[2] * bxyz_new[2] + scoeffs[3]; + bst_out[1] = tcoeffs[0] * bxyz_new[0] + tcoeffs[1] * bxyz_new[1] + tcoeffs[2] * bxyz_new[2] + tcoeffs[3]; + cst_out[0] = scoeffs[0] * cxyz_new[0] + scoeffs[1] * cxyz_new[1] + scoeffs[2] * cxyz_new[2] + scoeffs[3]; + cst_out[1] = tcoeffs[0] * cxyz_new[0] + tcoeffs[1] * cxyz_new[1] + tcoeffs[2] * cxyz_new[2] + tcoeffs[3]; +} + +/* +ScaleBSPMain() +amaze and confuse your enemies with wierd scaled maps! +*/ + +int ScaleBSPMain( int argc, char **argv ) +{ + int i, j; + float f, a; + vec3_t scale; + vec3_t vec; + char str[ 1024 ]; + int uniform, axis; + qboolean texscale; + float *old_xyzst = NULL; + float spawn_ref = 0; + + + /* arg checking */ + if( argc < 3 ) + { + Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref ] \n" ); + return 0; + } + + texscale = qfalse; + for(i = 1; i < argc-2; ++i) + { + if(!strcmp(argv[i], "-tex")) + { + texscale = qtrue; + } + else if(!strcmp(argv[i], "-spawn_ref")) + { + spawn_ref = atof(argv[i+1]); + ++i; + } + else + break; + } + + /* get scale */ + // if(argc-2 >= i) // always true + scale[2] = scale[1] = scale[0] = atof( argv[ argc - 2 ] ); + if(argc-3 >= i) + scale[1] = scale[0] = atof( argv[ argc - 3 ] ); + if(argc-4 >= i) + scale[0] = atof( argv[ argc - 4 ] ); + + uniform = ((scale[0] == scale[1]) && (scale[1] == scale[2])); + + if( scale[0] == 0.0f || scale[1] == 0.0f || scale[2] == 0.0f ) + { + Sys_Printf( "Usage: q3map [-v] -scale [-tex] [-spawn_ref ] \n" ); + Sys_Printf( "Non-zero scale value required.\n" ); + return 0; + } + + /* do some path mangling */ + strcpy( source, ExpandArg( argv[ argc - 1 ] ) ); + StripExtension( source ); + DefaultExtension( source, ".bsp" ); + + /* load the bsp */ + Sys_Printf( "Loading %s\n", source ); + LoadBSPFile( source ); + ParseEntities(); + + /* note it */ + Sys_Printf( "--- ScaleBSP ---\n" ); + Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities ); + + /* scale entity keys */ + for( i = 0; i < numBSPEntities && i < numEntities; i++ ) + { + /* scale origin */ + GetVectorForKey( &entities[ i ], "origin", vec ); + if( (vec[ 0 ] || vec[ 1 ] || vec[ 2 ]) ) + { + if(!strncmp(ValueForKey(&entities[i], "classname"), "info_player_", 12)) + vec[2] += spawn_ref; + vec[0] *= scale[0]; + vec[1] *= scale[1]; + vec[2] *= scale[2]; + if(!strncmp(ValueForKey(&entities[i], "classname"), "info_player_", 12)) + vec[2] -= spawn_ref; + sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); + SetKeyValue( &entities[ i ], "origin", str ); + } + + a = FloatForKey( &entities[ i ], "angle" ); + if(a == -1 || a == -2) // z scale + axis = 2; + else if(fabs(sin(DEG2RAD(a))) < 0.707) + axis = 0; + else + axis = 1; + + /* scale door lip */ + f = FloatForKey( &entities[ i ], "lip" ); + if( f ) + { + f *= scale[axis]; + sprintf( str, "%f", f ); + SetKeyValue( &entities[ i ], "lip", str ); + } + + /* scale plat height */ + f = FloatForKey( &entities[ i ], "height" ); + if( f ) + { + f *= scale[2]; + sprintf( str, "%f", f ); + SetKeyValue( &entities[ i ], "height", str ); + } + + // TODO maybe allow a definition file for entities to specify which values are scaled how? + } + + /* scale models */ + for( i = 0; i < numBSPModels; i++ ) + { + bspModels[ i ].mins[0] *= scale[0]; + bspModels[ i ].mins[1] *= scale[1]; + bspModels[ i ].mins[2] *= scale[2]; + bspModels[ i ].maxs[0] *= scale[0]; + bspModels[ i ].maxs[1] *= scale[1]; + bspModels[ i ].maxs[2] *= scale[2]; + } + + /* scale nodes */ + for( i = 0; i < numBSPNodes; i++ ) + { + bspNodes[ i ].mins[0] *= scale[0]; + bspNodes[ i ].mins[1] *= scale[1]; + bspNodes[ i ].mins[2] *= scale[2]; + bspNodes[ i ].maxs[0] *= scale[0]; + bspNodes[ i ].maxs[1] *= scale[1]; + bspNodes[ i ].maxs[2] *= scale[2]; + } + + /* scale leafs */ + for( i = 0; i < numBSPLeafs; i++ ) + { + bspLeafs[ i ].mins[0] *= scale[0]; + bspLeafs[ i ].mins[1] *= scale[1]; + bspLeafs[ i ].mins[2] *= scale[2]; + bspLeafs[ i ].maxs[0] *= scale[0]; + bspLeafs[ i ].maxs[1] *= scale[1]; + bspLeafs[ i ].maxs[2] *= scale[2]; + } + + if(texscale) + { + Sys_Printf("Using texture unlocking (and probably breaking texture alignment a lot)\n"); + old_xyzst = safe_malloc(sizeof(*old_xyzst) * numBSPDrawVerts * 5); + for(i = 0; i < numBSPDrawVerts; i++) + { + old_xyzst[5*i+0] = bspDrawVerts[i].xyz[0]; + old_xyzst[5*i+1] = bspDrawVerts[i].xyz[1]; + old_xyzst[5*i+2] = bspDrawVerts[i].xyz[2]; + old_xyzst[5*i+3] = bspDrawVerts[i].st[0]; + old_xyzst[5*i+4] = bspDrawVerts[i].st[1]; + } + } + + /* scale drawverts */ + for( i = 0; i < numBSPDrawVerts; i++ ) + { + bspDrawVerts[i].xyz[0] *= scale[0]; + bspDrawVerts[i].xyz[1] *= scale[1]; + bspDrawVerts[i].xyz[2] *= scale[2]; + bspDrawVerts[i].normal[0] /= scale[0]; + bspDrawVerts[i].normal[1] /= scale[1]; + bspDrawVerts[i].normal[2] /= scale[2]; + VectorNormalize(bspDrawVerts[i].normal, bspDrawVerts[i].normal); + } + + if(texscale) + { + for(i = 0; i < numBSPDrawSurfaces; i++) + { + switch(bspDrawSurfaces[i].surfaceType) + { + case SURFACE_FACE: + case SURFACE_META: + if(bspDrawSurfaces[i].numIndexes % 3) + Error("Not a triangulation!"); + for(j = bspDrawSurfaces[i].firstIndex; j < bspDrawSurfaces[i].firstIndex + bspDrawSurfaces[i].numIndexes; j += 3) + { + int ia = bspDrawIndexes[j] + bspDrawSurfaces[i].firstVert, ib = bspDrawIndexes[j+1] + bspDrawSurfaces[i].firstVert, ic = bspDrawIndexes[j+2] + bspDrawSurfaces[i].firstVert; + bspDrawVert_t *a = &bspDrawVerts[ia], *b = &bspDrawVerts[ib], *c = &bspDrawVerts[ic]; + float *oa = &old_xyzst[ia*5], *ob = &old_xyzst[ib*5], *oc = &old_xyzst[ic*5]; + // extrapolate: + // a->xyz -> oa + // b->xyz -> ob + // c->xyz -> oc + ExtrapolateTexcoords( + &oa[0], &oa[3], + &ob[0], &ob[3], + &oc[0], &oc[3], + a->xyz, a->st, + b->xyz, b->st, + c->xyz, c->st); + } + break; + } + } + } + + /* scale planes */ + if(uniform) + { + for( i = 0; i < numBSPPlanes; i++ ) + { + bspPlanes[ i ].dist *= scale[0]; + } + } + else + { + for( i = 0; i < numBSPPlanes; i++ ) + { + bspPlanes[ i ].normal[0] /= scale[0]; + bspPlanes[ i ].normal[1] /= scale[1]; + bspPlanes[ i ].normal[2] /= scale[2]; + f = 1/VectorLength(bspPlanes[i].normal); + VectorScale(bspPlanes[i].normal, f, bspPlanes[i].normal); + bspPlanes[ i ].dist *= f; + } + } + + /* scale gridsize */ + GetVectorForKey( &entities[ 0 ], "gridsize", vec ); + if( (vec[ 0 ] + vec[ 1 ] + vec[ 2 ]) == 0.0f ) + VectorCopy( gridSize, vec ); + vec[0] *= scale[0]; + vec[1] *= scale[1]; + vec[2] *= scale[2]; + sprintf( str, "%f %f %f", vec[ 0 ], vec[ 1 ], vec[ 2 ] ); + SetKeyValue( &entities[ 0 ], "gridsize", str ); + + /* inject command line parameters */ + InjectCommandLine(argv, 0, argc - 1); + + /* write the bsp */ + UnparseEntities(); + StripExtension( source ); + DefaultExtension( source, "_s.bsp" ); + Sys_Printf( "Writing %s\n", source ); + WriteBSPFile( source ); + + /* return to sender */ + return 0; +} + + +/* +PseudoCompileBSP() +a stripped down ProcessModels +*/ +void PseudoCompileBSP(qboolean need_tree) +{ + int models; + char modelValue[10]; + entity_t *entity; + face_t *faces; + tree_t *tree; + node_t *node; + brush_t *brush; + side_t *side; + int i; + + SetDrawSurfacesBuffer(); + mapDrawSurfs = safe_malloc( sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); + memset( mapDrawSurfs, 0, sizeof( mapDrawSurface_t ) * MAX_MAP_DRAW_SURFS ); + numMapDrawSurfs = 0; + + BeginBSPFile(); + models = 1; + for( mapEntityNum = 0; mapEntityNum < numEntities; mapEntityNum++ ) + { + /* get entity */ + entity = &entities[ mapEntityNum ]; + if( entity->brushes == NULL && entity->patches == NULL ) + continue; + + if(mapEntityNum != 0) + { + sprintf( modelValue, "*%d", models++); + SetKeyValue(entity, "model", modelValue); + } + + /* process the model */ + Sys_FPrintf( SYS_VRB, "############### model %i ###############\n", numBSPModels ); + BeginModel(); + + entity->firstDrawSurf = numMapDrawSurfs; + + ClearMetaTriangles(); + PatchMapDrawSurfs(entity); + + if(mapEntityNum == 0 && need_tree) + { + faces = MakeStructuralBSPFaceList(entities[0].brushes); + tree = FaceBSP(faces); + node = tree->headnode; + } + else + { + node = AllocNode(); + node->planenum = PLANENUM_LEAF; + tree = AllocTree(); + tree->headnode = node; + } + + /* a minimized ClipSidesIntoTree */ + for( brush = entity->brushes; brush; brush = brush->next ) + { + /* walk the brush sides */ + for( i = 0; i < brush->numsides; i++ ) + { + /* get side */ + side = &brush->sides[ i ]; + if( side->winding == NULL ) + continue; + /* shader? */ + if( side->shaderInfo == NULL ) + continue; + /* save this winding as a visible surface */ + DrawSurfaceForSide(entity, brush, side, side->winding); + } + } + + if(meta) + { + ClassifyEntitySurfaces(entity); + MakeEntityDecals(entity); + MakeEntityMetaTriangles(entity); + SmoothMetaTriangles(); + MergeMetaTriangles(); + } + FilterDrawsurfsIntoTree(entity, tree); + + FilterStructuralBrushesIntoTree(entity, tree); + FilterDetailBrushesIntoTree(entity, tree); + + EmitBrushes(entity->brushes, &entity->firstBrush, &entity->numBrushes ); + EndModel(entity, node); + } + EndBSPFile(qfalse); +} + +/* +ConvertBSPMain() +main argument processing function for bsp conversion +*/ + +int ConvertBSPMain( int argc, char **argv ) +{ + int i; + int (*convertFunc)( char * ); + game_t *convertGame; + char ext[1024]; + qboolean map_allowed, force_bsp, force_map; + + + /* set default */ + convertFunc = ConvertBSPToASE; + convertGame = NULL; + map_allowed = qfalse; + force_bsp = qfalse; + force_map = qfalse; + + /* arg checking */ + if( argc < 1 ) + { + Sys_Printf( "Usage: q3map -convert -format [-shadesasbitmap|-lightmapsastexcoord|-deluxemapsastexcoord] [-readbsp|-readmap [-meta|-patchmeta]] \n" ); + return 0; + } + + /* process arguments */ + for( i = 1; i < (argc - 1); i++ ) + { + /* -format map|ase|... */ + if( !strcmp( argv[ i ], "-format" ) ) + { + i++; + if( !Q_stricmp( argv[ i ], "ase" ) ) + { + convertFunc = ConvertBSPToASE; + map_allowed = qfalse; + } + else if( !Q_stricmp( argv[ i ], "obj" ) ) + { + convertFunc = ConvertBSPToOBJ; + map_allowed = qfalse; + } + else if( !Q_stricmp( argv[ i ], "map_bp" ) ) + { + convertFunc = ConvertBSPToMap_BP; + map_allowed = qtrue; + } + else if( !Q_stricmp( argv[ i ], "map" ) ) + { + convertFunc = ConvertBSPToMap; + map_allowed = qtrue; + } + else + { + convertGame = GetGame( argv[ i ] ); + map_allowed = qfalse; + if( convertGame == NULL ) + Sys_Printf( "Unknown conversion format \"%s\". Defaulting to ASE.\n", argv[ i ] ); + } + } + else if( !strcmp( argv[ i ], "-ne" ) ) + { + normalEpsilon = atof( argv[ i + 1 ] ); + i++; + Sys_Printf( "Normal epsilon set to %f\n", normalEpsilon ); + } + else if( !strcmp( argv[ i ], "-de" ) ) + { + distanceEpsilon = atof( argv[ i + 1 ] ); + i++; + Sys_Printf( "Distance epsilon set to %f\n", distanceEpsilon ); + } + else if( !strcmp( argv[ i ], "-shadersasbitmap" ) ) + shadersAsBitmap = qtrue; + else if( !strcmp( argv[ i ], "-lightmapsastexcoord" ) ) + lightmapsAsTexcoord = qtrue; + else if( !strcmp( argv[ i ], "-deluxemapsastexcoord" ) ) + { + lightmapsAsTexcoord = qtrue; + deluxemap = qtrue; + } + else if( !strcmp( argv[ i ], "-readbsp" ) ) + force_bsp = qtrue; + else if( !strcmp( argv[ i ], "-readmap" ) ) + force_map = qtrue; + else if( !strcmp( argv[ i ], "-meta" ) ) + meta = qtrue; + else if( !strcmp( argv[ i ], "-patchmeta" ) ) + { + meta = qtrue; + patchMeta = qtrue; + } + } + + LoadShaderInfo(); + + /* clean up map name */ + strcpy(source, ExpandArg(argv[i])); + ExtractFileExtension(source, ext); + + if(!map_allowed && !force_map) + force_bsp = qtrue; + + if(force_map || (!force_bsp && !Q_stricmp(ext, "map") && map_allowed)) + { + if(!map_allowed) + Sys_Printf("WARNING: the requested conversion should not be done from .map files. Compile a .bsp first.\n"); + StripExtension(source); + DefaultExtension(source, ".map"); + Sys_Printf("Loading %s\n", source); + LoadMapFile(source, qfalse, convertGame == NULL); + PseudoCompileBSP(convertGame != NULL); + } + else + { + StripExtension(source); + DefaultExtension(source, ".bsp"); + Sys_Printf("Loading %s\n", source); + LoadBSPFile(source); + ParseEntities(); + } + + /* bsp format convert? */ + if( convertGame != NULL ) + { + /* set global game */ + game = convertGame; + + /* write bsp */ + StripExtension( source ); + DefaultExtension( source, "_c.bsp" ); + Sys_Printf( "Writing %s\n", source ); + WriteBSPFile( source ); + + /* return to sender */ + return 0; + } + + /* normal convert */ + return convertFunc( source ); +} + + + +/* +main() +q3map mojo... +*/ + +int main( int argc, char **argv ) +{ + int i, r; + double start, end; + + + /* we want consistent 'randomness' */ + srand( 0 ); + + /* start timer */ + start = I_FloatTime(); + + /* this was changed to emit version number over the network */ + printf( Q3MAP_VERSION "\n" ); + + /* set exit call */ + atexit( ExitQ3Map ); + + /* read general options first */ + for( i = 1; i < argc; i++ ) + { + /* -connect */ + if( !strcmp( argv[ i ], "-connect" ) ) + { + argv[ i ] = NULL; + i++; + Broadcast_Setup( argv[ i ] ); + argv[ i ] = NULL; + } + + /* verbose */ + else if( !strcmp( argv[ i ], "-v" ) ) + { + if(!verbose) + { + verbose = qtrue; + argv[ i ] = NULL; + } + } + + /* force */ + else if( !strcmp( argv[ i ], "-force" ) ) + { + force = qtrue; + argv[ i ] = NULL; + } + + /* patch subdivisions */ + else if( !strcmp( argv[ i ], "-subdivisions" ) ) + { + argv[ i ] = NULL; + i++; + patchSubdivisions = atoi( argv[ i ] ); + argv[ i ] = NULL; + if( patchSubdivisions <= 0 ) + patchSubdivisions = 1; + } + + /* threads */ + else if( !strcmp( argv[ i ], "-threads" ) ) + { + argv[ i ] = NULL; + i++; + numthreads = atoi( argv[ i ] ); + argv[ i ] = NULL; + } + } + + /* init model library */ + PicoInit(); + PicoSetMallocFunc( safe_malloc ); + PicoSetFreeFunc( free ); + PicoSetPrintFunc( PicoPrintFunc ); + PicoSetLoadFileFunc( PicoLoadFileFunc ); + PicoSetFreeFileFunc( free ); + + /* set number of threads */ + ThreadSetDefault(); + + /* generate sinusoid jitter table */ + for( i = 0; i < MAX_JITTERS; i++ ) + { + jitters[ i ] = sin( i * 139.54152147 ); + //% Sys_Printf( "Jitter %4d: %f\n", i, jitters[ i ] ); + } + + /* we print out two versions, q3map's main version (since it evolves a bit out of GtkRadiant) + and we put the GtkRadiant version to make it easy to track with what version of Radiant it was built with */ + + Sys_Printf( "Q3Map - v1.0r (c) 1999 Id Software Inc.\n" ); + Sys_Printf( "Q3Map (ydnar) - v" Q3MAP_VERSION "\n" ); + Sys_Printf( "NetRadiant - v" RADIANT_VERSION " " __DATE__ " " __TIME__ "\n" ); + Sys_Printf( "%s\n", Q3MAP_MOTD ); + + /* ydnar: new path initialization */ + InitPaths( &argc, argv ); + + /* set game options */ + if (!patchSubdivisions) + patchSubdivisions = game->patchSubdivisions; + + /* check if we have enough options left to attempt something */ + if( argc < 2 ) + Error( "Usage: %s [general options] [options] mapfile", argv[ 0 ] ); + + /* fixaas */ + if( !strcmp( argv[ 1 ], "-fixaas" ) ) + r = FixAAS( argc - 1, argv + 1 ); + + /* analyze */ + else if( !strcmp( argv[ 1 ], "-analyze" ) ) + r = AnalyzeBSP( argc - 1, argv + 1 ); + + /* info */ + else if( !strcmp( argv[ 1 ], "-info" ) ) + r = BSPInfo( argc - 2, argv + 2 ); + + /* vis */ + else if( !strcmp( argv[ 1 ], "-vis" ) ) + r = VisMain( argc - 1, argv + 1 ); + + /* light */ + else if( !strcmp( argv[ 1 ], "-light" ) ) + r = LightMain( argc - 1, argv + 1 ); + + /* vlight */ + else if( !strcmp( argv[ 1 ], "-vlight" ) ) + { + Sys_Printf( "WARNING: VLight is no longer supported, defaulting to -light -fast instead\n\n" ); + argv[ 1 ] = "-fast"; /* eek a hack */ + r = LightMain( argc, argv ); + } + + /* ydnar: lightmap export */ + else if( !strcmp( argv[ 1 ], "-export" ) ) + r = ExportLightmapsMain( argc - 1, argv + 1 ); + + /* ydnar: lightmap import */ + else if( !strcmp( argv[ 1 ], "-import" ) ) + r = ImportLightmapsMain( argc - 1, argv + 1 ); + + /* ydnar: bsp scaling */ + else if( !strcmp( argv[ 1 ], "-scale" ) ) + r = ScaleBSPMain( argc - 1, argv + 1 ); + + /* ydnar: bsp conversion */ + else if( !strcmp( argv[ 1 ], "-convert" ) ) + r = ConvertBSPMain( argc - 1, argv + 1 ); + + /* div0: minimap */ + else if( !strcmp( argv[ 1 ], "-minimap" ) ) + r = MiniMapBSPMain(argc - 1, argv + 1); + + /* ydnar: otherwise create a bsp */ + else + r = BSPMain( argc, argv ); + + /* emit time */ + end = I_FloatTime(); + Sys_Printf( "%9.0f seconds elapsed\n", end - start ); + + /* shut down connection */ + Broadcast_Shutdown(); + + /* return any error code */ + return r; +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/map.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/map.c new file mode 100644 index 00000000..95bb3d1f --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/map.c @@ -0,0 +1,1925 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define MAP_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* FIXME: remove these vars */ + +/* undefine to make plane finding use linear sort (note: really slow) */ +#define USE_HASHING +#define PLANE_HASHES 8192 + +int planehash[ PLANE_HASHES ]; + +int c_boxbevels; +int c_edgebevels; +int c_areaportals; +int c_detail; +int c_structural; + + + +/* +PlaneEqual() +ydnar: replaced with variable epsilon for djbob +*/ + +qboolean PlaneEqual( plane_t *p, vec3_t normal, vec_t dist ) +{ + float ne, de; + + + /* get local copies */ + ne = normalEpsilon; + de = distanceEpsilon; + + /* compare */ + // We check equality of each component since we're using '<', not '<=' + // (the epsilons may be zero). We want to use '<' intead of '<=' to be + // consistent with the true meaning of "epsilon", and also because other + // parts of the code uses this inequality. + if ((p->dist == dist || fabs(p->dist - dist) < de) && + (p->normal[0] == normal[0] || fabs(p->normal[0] - normal[0]) < ne) && + (p->normal[1] == normal[1] || fabs(p->normal[1] - normal[1]) < ne) && + (p->normal[2] == normal[2] || fabs(p->normal[2] - normal[2]) < ne)) + return qtrue; + + /* different */ + return qfalse; +} + + + +/* +AddPlaneToHash() +*/ + +void AddPlaneToHash( plane_t *p ) +{ + int hash; + + + hash = (PLANE_HASHES - 1) & (int) fabs( p->dist ); + + p->hash_chain = planehash[hash]; + planehash[hash] = p - mapplanes + 1; +} + +/* +================ +CreateNewFloatPlane +================ +*/ +int CreateNewFloatPlane (vec3_t normal, vec_t dist) +{ + plane_t *p, temp; + + if (VectorLength(normal) < 0.5) + { + Sys_Printf( "FloatPlane: bad normal\n"); + return -1; + } + + // create a new plane + AUTOEXPAND_BY_REALLOC(mapplanes, nummapplanes+1, allocatedmapplanes, 1024); + + p = &mapplanes[nummapplanes]; + VectorCopy (normal, p->normal); + p->dist = dist; + p->type = (p+1)->type = PlaneTypeForNormal (p->normal); + + VectorSubtract (vec3_origin, normal, (p+1)->normal); + (p+1)->dist = -dist; + + nummapplanes += 2; + + // allways put axial planes facing positive first + if (p->type < 3) + { + if (p->normal[0] < 0 || p->normal[1] < 0 || p->normal[2] < 0) + { + // flip order + temp = *p; + *p = *(p+1); + *(p+1) = temp; + + AddPlaneToHash (p); + AddPlaneToHash (p+1); + return nummapplanes - 1; + } + } + + AddPlaneToHash (p); + AddPlaneToHash (p+1); + return nummapplanes - 2; +} + + + +/* +SnapNormal() +Snaps a near-axial normal vector. +Returns qtrue if and only if the normal was adjusted. +*/ + +qboolean SnapNormal( vec3_t normal ) +{ +#if Q3MAP2_EXPERIMENTAL_SNAP_NORMAL_FIX + int i; + qboolean adjusted = qfalse; + + // A change from the original SnapNormal() is that we snap each + // component that's close to 0. So for example if a normal is + // (0.707, 0.707, 0.0000001), it will get snapped to lie perfectly in the + // XY plane (its Z component will be set to 0 and its length will be + // normalized). The original SnapNormal() didn't snap such vectors - it + // only snapped vectors that were near a perfect axis. + + for (i = 0; i < 3; i++) + { + if (normal[i] != 0.0 && -normalEpsilon < normal[i] && normal[i] < normalEpsilon) + { + normal[i] = 0.0; + adjusted = qtrue; + } + } + + if (adjusted) + { + VectorNormalize(normal, normal); + return qtrue; + } + return qfalse; +#else + int i; + + // I would suggest that you uncomment the following code and look at the + // results: + + /* + Sys_Printf("normalEpsilon is %f\n", normalEpsilon); + for (i = 0;; i++) + { + normal[0] = 1.0; + normal[1] = 0.0; + normal[2] = i * 0.000001; + VectorNormalize(normal, normal); + if (1.0 - normal[0] >= normalEpsilon) { + Sys_Printf("(%f %f %f)\n", normal[0], normal[1], normal[2]); + Error("SnapNormal: test completed"); + } + } + */ + + // When the normalEpsilon is 0.00001, the loop will break out when normal is + // (0.999990 0.000000 0.004469). In other words, this is the vector closest + // to axial that will NOT be snapped. Anything closer will be snaped. Now, + // 0.004469 is close to 1/225. The length of a circular quarter-arc of radius + // 1 is PI/2, or about 1.57. And 0.004469/1.57 is about 0.0028, or about + // 1/350. Expressed a different way, 1/350 is also about 0.26/90. + // This means is that a normal with an angle that is within 1/4 of a degree + // from axial will be "snapped". My belief is that the person who wrote the + // code below did not intend it this way. I think the person intended that + // the epsilon be measured against the vector components close to 0, not 1.0. + // I think the logic should be: if 2 of the normal components are within + // epsilon of 0, then the vector can be snapped to be perfectly axial. + // We may consider adjusting the epsilon to a larger value when we make this + // code fix. + + for( i = 0; i < 3; i++ ) + { + if( fabs( normal[ i ] - 1 ) < normalEpsilon ) + { + VectorClear( normal ); + normal[ i ] = 1; + return qtrue; + } + if( fabs( normal[ i ] - -1 ) < normalEpsilon ) + { + VectorClear( normal ); + normal[ i ] = -1; + return qtrue; + } + } + return qfalse; +#endif +} + + + +/* +SnapPlane() +snaps a plane to normal/distance epsilons +*/ + +void SnapPlane( vec3_t normal, vec_t *dist, vec3_t center ) +{ +// SnapPlane disabled by LordHavoc because it often messes up collision +// brushes made from triangles of embedded models, and it has little effect +// on anything else (axial planes are usually derived from snapped points) +/* + SnapPlane reenabled by namespace because of multiple reports of + q3map2-crashes which were triggered by this patch. +*/ + SnapNormal( normal ); + + // TODO: Rambetter has some serious comments here as well. First off, + // in the case where a normal is non-axial, there is nothing special + // about integer distances. I would think that snapping a distance might + // make sense for axial normals, but I'm not so sure about snapping + // non-axial normals. A shift by 0.01 in a plane, multiplied by a clipping + // against another plane that is 5 degrees off, and we introduce 0.1 error + // easily. A 0.1 error in a vertex is where problems start to happen, such + // as disappearing triangles. + + // Second, assuming we have snapped the normal above, let's say that the + // plane we just snapped was defined for some points that are actually + // quite far away from normal * dist. Well, snapping the normal in this + // case means that we've just moved those points by potentially many units! + // Therefore, if we are going to snap the normal, we need to know the + // points we're snapping for so that the plane snaps with those points in + // mind (points remain close to the plane). + + // I would like to know exactly which problems SnapPlane() is trying to + // solve so that we can better engineer it (I'm not saying that SnapPlane() + // should be removed altogether). Fix all this snapping code at some point! + + if( fabs( *dist - Q_rint( *dist ) ) < distanceEpsilon ) + *dist = Q_rint( *dist ); +} + +/* +SnapPlaneImproved() +snaps a plane to normal/distance epsilons, improved code +*/ +void SnapPlaneImproved(vec3_t normal, vec_t *dist, int numPoints, const vec3_t *points) +{ + int i; + vec3_t center; + vec_t distNearestInt; + + if (SnapNormal(normal)) + { + if (numPoints > 0) + { + // Adjust the dist so that the provided points don't drift away. + VectorClear(center); + for (i = 0; i < numPoints; i++) + { + VectorAdd(center, points[i], center); + } + for (i = 0; i < 3; i++) { center[i] = center[i] / numPoints; } + *dist = DotProduct(normal, center); + } + } + + if (VectorIsOnAxis(normal)) + { + // Only snap distance if the normal is an axis. Otherwise there + // is nothing "natural" about snapping the distance to an integer. + distNearestInt = Q_rint(*dist); + if (-distanceEpsilon < *dist - distNearestInt && *dist - distNearestInt < distanceEpsilon) + { + *dist = distNearestInt; + } + } +} + + + +/* +FindFloatPlane() +ydnar: changed to allow a number of test points to be supplied that +must be within an epsilon distance of the plane +*/ + +int FindFloatPlane( vec3_t innormal, vec_t dist, int numPoints, vec3_t *points ) // NOTE: this has a side effect on the normal. Good or bad? + +#ifdef USE_HASHING + +{ + int i, j, hash, h; + int pidx; + plane_t *p; + vec_t d; + vec3_t normal; + + VectorCopy(innormal, normal); +#if Q3MAP2_EXPERIMENTAL_SNAP_PLANE_FIX + SnapPlaneImproved(normal, &dist, numPoints, (const vec3_t *) points); +#else + SnapPlane( normal, &dist ); +#endif + /* hash the plane */ + hash = (PLANE_HASHES - 1) & (int) fabs( dist ); + + /* search the border bins as well */ + for( i = -1; i <= 1; i++ ) + { + h = (hash + i) & (PLANE_HASHES - 1); + for( pidx = planehash[ h ] - 1; pidx != -1; pidx = mapplanes[pidx].hash_chain - 1 ) + { + p = &mapplanes[pidx]; + + /* do standard plane compare */ + if( !PlaneEqual( p, normal, dist ) ) + continue; + + /* ydnar: uncomment the following line for old-style plane finding */ + //% return p - mapplanes; + + /* ydnar: test supplied points against this plane */ + for( j = 0; j < numPoints; j++ ) + { + // NOTE: When dist approaches 2^16, the resolution of 32 bit floating + // point number is greatly decreased. The distanceEpsilon cannot be + // very small when world coordinates extend to 2^16. Making the + // dot product here in 64 bit land will not really help the situation + // because the error will already be carried in dist. + d = DotProduct( points[ j ], p->normal ) - p->dist; + d = fabs(d); + if (d != 0.0 && d >= distanceEpsilon) + break; // Point is too far from plane. + } + + /* found a matching plane */ + if( j >= numPoints ) + return p - mapplanes; + } + } + + /* none found, so create a new one */ + return CreateNewFloatPlane( normal, dist ); +} + +#else + +{ + int i; + plane_t *p; + vec3_t normal; + + VectorCopy(innormal, normal); +#if Q3MAP2_EXPERIMENTAL_SNAP_PLANE_FIX + SnapPlaneImproved(normal, &dist, numPoints, (const vec3_t *) points); +#else + SnapPlane( normal, &dist ); +#endif + for( i = 0, p = mapplanes; i < nummapplanes; i++, p++ ) + { + if( !PlaneEqual( p, normal, dist ) ) + continue; + + /* ydnar: uncomment the following line for old-style plane finding */ + //% return i; + + /* ydnar: test supplied points against this plane */ + for( j = 0; j < numPoints; j++ ) + { + d = DotProduct( points[ j ], p->normal ) - p->dist; + if( fabs( d ) > distanceEpsilon ) + break; + } + + /* found a matching plane */ + if( j >= numPoints ) + return i; + // TODO: Note that the non-USE_HASHING code does not compute epsilons + // for the provided points. It should do that. I think this code + // is unmaintained because nobody sets USE_HASHING to off. + } + + return CreateNewFloatPlane( normal, dist ); +} + +#endif + + + +/* +MapPlaneFromPoints() +takes 3 points and finds the plane they lie in +*/ + +int MapPlaneFromPoints( vec3_t *p ) +{ +#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES + vec3_accu_t paccu[3]; + vec3_accu_t t1, t2, normalAccu; + vec3_t normal; + vec_t dist; + + VectorCopyRegularToAccu(p[0], paccu[0]); + VectorCopyRegularToAccu(p[1], paccu[1]); + VectorCopyRegularToAccu(p[2], paccu[2]); + + VectorSubtractAccu(paccu[0], paccu[1], t1); + VectorSubtractAccu(paccu[2], paccu[1], t2); + CrossProductAccu(t1, t2, normalAccu); + VectorNormalizeAccu(normalAccu, normalAccu); + // TODO: A 32 bit float for the plane distance isn't enough resolution + // if the plane is 2^16 units away from the origin (the "epsilon" approaches + // 0.01 in that case). + dist = (vec_t) DotProductAccu(paccu[0], normalAccu); + VectorCopyAccuToRegular(normalAccu, normal); + + return FindFloatPlane(normal, dist, 3, p); +#else + vec3_t t1, t2, normal; + vec_t dist; + + + /* calc plane normal */ + VectorSubtract( p[ 0 ], p[ 1 ], t1 ); + VectorSubtract( p[ 2 ], p[ 1 ], t2 ); + CrossProduct( t1, t2, normal ); + VectorNormalize( normal, normal ); + + /* calc plane distance */ + dist = DotProduct( p[ 0 ], normal ); + + /* store the plane */ + return FindFloatPlane( normal, dist, 3, p ); +#endif +} + + + +/* +SetBrushContents() +the content flags and compile flags on all sides of a brush should be the same +*/ + +void SetBrushContents( brush_t *b ) +{ + int contentFlags, compileFlags; + side_t *s; + int i; + qboolean mixed; + + + /* get initial compile flags from first side */ + s = &b->sides[ 0 ]; + contentFlags = s->contentFlags; + compileFlags = s->compileFlags; + b->contentShader = s->shaderInfo; + mixed = qfalse; + + /* get the content/compile flags for every side in the brush */ + for( i = 1; i < b->numsides; i++, s++ ) + { + s = &b->sides[ i ]; + if( s->shaderInfo == NULL ) + continue; + if( s->contentFlags != contentFlags || s->compileFlags != compileFlags ) + mixed = qtrue; + + contentFlags |= s->contentFlags; + compileFlags |= s->compileFlags; + } + + /* ydnar: getting rid of this stupid warning */ + //% if( mixed ) + //% Sys_FPrintf( SYS_VRB,"Entity %i, Brush %i: mixed face contentFlags\n", b->entitynum, b->brushnum ); + + /* check for detail & structural */ + if( (compileFlags & C_DETAIL) && (compileFlags & C_STRUCTURAL) ) + { + xml_Select( "Mixed detail and structural (defaulting to structural)", mapEnt->mapEntityNum, entitySourceBrushes, qfalse ); + compileFlags &= ~C_DETAIL; + } + + /* the fulldetail flag will cause detail brushes to be treated like normal brushes */ + if( fulldetail ) + compileFlags &= ~C_DETAIL; + + /* all translucent brushes that aren't specifically made structural will be detail */ + if( (compileFlags & C_TRANSLUCENT) && !(compileFlags & C_STRUCTURAL) ) + compileFlags |= C_DETAIL; + + /* detail? */ + if( compileFlags & C_DETAIL ) + { + c_detail++; + b->detail = qtrue; + } + else + { + c_structural++; + b->detail = qfalse; + } + + /* opaque? */ + if( compileFlags & C_TRANSLUCENT ) + b->opaque = qfalse; + else + b->opaque = qtrue; + + /* areaportal? */ + if( compileFlags & C_AREAPORTAL ) + c_areaportals++; + + /* set brush flags */ + b->contentFlags = contentFlags; + b->compileFlags = compileFlags; +} + + + +/* +AddBrushBevels() +adds any additional planes necessary to allow the brush being +built to be expanded against axial bounding boxes +ydnar 2003-01-20: added mrelusive fixes +*/ + +void AddBrushBevels( void ) +{ + int axis, dir; + int i, j, k, l, order; + side_t sidetemp; + side_t *s, *s2; + winding_t *w, *w2; + vec3_t normal; + float dist; + vec3_t vec, vec2; + float d, minBack; + + // + // add the axial planes + // + order = 0; + for ( axis = 0; axis < 3; axis++ ) { + for ( dir = -1; dir <= 1; dir += 2, order++ ) { + // see if the plane is allready present + for ( i = 0, s = buildBrush->sides; i < buildBrush->numsides; i++, s++ ) + { + /* ydnar: testing disabling of mre code */ + #if 0 + if ( dir > 0 ) { + if ( mapplanes[s->planenum].normal[axis] >= 0.9999f ) { + break; + } + } + else { + if ( mapplanes[s->planenum].normal[axis] <= -0.9999f ) { + break; + } + } + #else + if( (dir > 0 && mapplanes[ s->planenum ].normal[ axis ] == 1.0f ) || + (dir < 0 && mapplanes[ s->planenum ].normal[ axis ] == -1.0f) ) + break; + #endif + } + + if ( i == buildBrush->numsides ) { + // add a new side + if ( buildBrush->numsides == MAX_BUILD_SIDES ) { + xml_Select( "MAX_BUILD_SIDES", buildBrush->entityNum, buildBrush->brushNum, qtrue); + } + memset( s, 0, sizeof( *s ) ); + buildBrush->numsides++; + VectorClear (normal); + normal[axis] = dir; + + if( dir == 1 ) + { + /* ydnar: adding bevel plane snapping for fewer bsp planes */ + if( bevelSnap > 0 ) + dist = floor( buildBrush->maxs[ axis ] / bevelSnap ) * bevelSnap; + else + dist = buildBrush->maxs[ axis ]; + } + else + { + /* ydnar: adding bevel plane snapping for fewer bsp planes */ + if( bevelSnap > 0 ) + dist = -ceil( buildBrush->mins[ axis ] / bevelSnap ) * bevelSnap; + else + dist = -buildBrush->mins[ axis ]; + } + + s->planenum = FindFloatPlane( normal, dist, 0, NULL ); + s->contentFlags = buildBrush->sides[ 0 ].contentFlags; + s->bevel = qtrue; + c_boxbevels++; + } + + // if the plane is not in it canonical order, swap it + if ( i != order ) { + sidetemp = buildBrush->sides[order]; + buildBrush->sides[order] = buildBrush->sides[i]; + buildBrush->sides[i] = sidetemp; + } + } + } + + // + // add the edge bevels + // + if ( buildBrush->numsides == 6 ) { + return; // pure axial + } + + // test the non-axial plane edges + for ( i = 6; i < buildBrush->numsides; i++ ) { + s = buildBrush->sides + i; + w = s->winding; + if ( !w ) { + continue; + } + for ( j = 0; j < w->numpoints; j++) { + k = (j+1)%w->numpoints; + VectorSubtract( w->p[j], w->p[k], vec ); + if ( VectorNormalize( vec, vec ) < 0.5f ) { + continue; + } + SnapNormal( vec ); + for ( k = 0; k < 3; k++ ) { + if ( vec[k] == -1.0f || vec[k] == 1.0f || (vec[k] == 0.0f && vec[(k+1)%3] == 0.0f) ) { + break; // axial + } + } + if ( k != 3 ) { + continue; // only test non-axial edges + } + + /* debug code */ + //% Sys_Printf( "-------------\n" ); + + // try the six possible slanted axials from this edge + for ( axis = 0; axis < 3; axis++ ) { + for ( dir = -1; dir <= 1; dir += 2 ) { + // construct a plane + VectorClear( vec2 ); + vec2[axis] = dir; + CrossProduct( vec, vec2, normal ); + if ( VectorNormalize( normal, normal ) < 0.5f ) { + continue; + } + dist = DotProduct( w->p[j], normal ); + + // if all the points on all the sides are + // behind this plane, it is a proper edge bevel + for ( k = 0; k < buildBrush->numsides; k++ ) { + + // if this plane has allready been used, skip it + if ( PlaneEqual( &mapplanes[buildBrush->sides[k].planenum], normal, dist ) ) { + break; + } + + w2 = buildBrush->sides[k].winding; + if ( !w2 ) { + continue; + } + minBack = 0.0f; + for ( l = 0; l < w2->numpoints; l++ ) { + d = DotProduct( w2->p[l], normal ) - dist; + if ( d > 0.1f ) { + break; // point in front + } + if ( d < minBack ) { + minBack = d; + } + } + // if some point was at the front + if ( l != w2->numpoints ) { + break; + } + + // if no points at the back then the winding is on the bevel plane + if ( minBack > -0.1f ) { + //% Sys_Printf( "On bevel plane\n" ); + break; + } + } + + if ( k != buildBrush->numsides ) { + continue; // wasn't part of the outer hull + } + + /* debug code */ + //% Sys_Printf( "n = %f %f %f\n", normal[ 0 ], normal[ 1 ], normal[ 2 ] ); + + // add this plane + if( buildBrush->numsides == MAX_BUILD_SIDES ) { + xml_Select( "MAX_BUILD_SIDES", buildBrush->entityNum, buildBrush->brushNum, qtrue); + } + s2 = &buildBrush->sides[buildBrush->numsides]; + buildBrush->numsides++; + memset( s2, 0, sizeof( *s2 ) ); + + s2->planenum = FindFloatPlane( normal, dist, 1, &w->p[ j ] ); + s2->contentFlags = buildBrush->sides[0].contentFlags; + s2->bevel = qtrue; + c_edgebevels++; + } + } + } + } +} + + + +/* +FinishBrush() +produces a final brush based on the buildBrush->sides array +and links it to the current entity +*/ + +static void MergeOrigin(entity_t *ent, vec3_t origin) +{ + vec3_t adjustment; + char string[128]; + + /* we have not parsed the brush completely yet... */ + GetVectorForKey( ent, "origin", ent->origin ); + + VectorMA(origin, -1, ent->originbrush_origin, adjustment); + VectorAdd(adjustment, ent->origin, ent->origin); + VectorCopy(origin, ent->originbrush_origin); + + sprintf(string, "%f %f %f", ent->origin[0], ent->origin[1], ent->origin[2]); + SetKeyValue(ent, "origin", string); +} + +brush_t *FinishBrush( qboolean noCollapseGroups ) +{ + brush_t *b; + + + /* create windings for sides and bounds for brush */ + if ( !CreateBrushWindings( buildBrush ) ) + return NULL; + + /* origin brushes are removed, but they set the rotation origin for the rest of the brushes in the entity. + after the entire entity is parsed, the planenums and texinfos will be adjusted for the origin brush */ + if( buildBrush->compileFlags & C_ORIGIN ) + { + vec3_t origin; + + Sys_Printf( "Entity %i, Brush %i: origin brush detected\n", + mapEnt->mapEntityNum, entitySourceBrushes ); + + if( numEntities == 1 ) + { + Sys_Printf( "Entity %i, Brush %i: origin brushes not allowed in world\n", + mapEnt->mapEntityNum, entitySourceBrushes ); + return NULL; + } + + VectorAdd (buildBrush->mins, buildBrush->maxs, origin); + VectorScale (origin, 0.5, origin); + + MergeOrigin(&entities[ numEntities - 1 ], origin); + + /* don't keep this brush */ + return NULL; + } + + /* determine if the brush is an area portal */ + if( buildBrush->compileFlags & C_AREAPORTAL ) + { + if( numEntities != 1 ) + { + Sys_Printf ("Entity %i, Brush %i: areaportals only allowed in world\n", numEntities - 1, entitySourceBrushes ); + return NULL; + } + } + + /* add bevel planes */ + if(!noCollapseGroups) + AddBrushBevels(); + + /* keep it */ + b = CopyBrush( buildBrush ); + + /* set map entity and brush numbering */ + b->entityNum = mapEnt->mapEntityNum; + b->brushNum = entitySourceBrushes; + + /* set original */ + b->original = b; + + /* link opaque brushes to head of list, translucent brushes to end */ + if( b->opaque || mapEnt->lastBrush == NULL ) + { + b->next = mapEnt->brushes; + mapEnt->brushes = b; + if( mapEnt->lastBrush == NULL ) + mapEnt->lastBrush = b; + } + else + { + b->next = NULL; + mapEnt->lastBrush->next = b; + mapEnt->lastBrush = b; + } + + /* link colorMod volume brushes to the entity directly */ + if( b->contentShader != NULL && + b->contentShader->colorMod != NULL && + b->contentShader->colorMod->type == CM_VOLUME ) + { + b->nextColorModBrush = mapEnt->colorModBrushes; + mapEnt->colorModBrushes = b; + } + + /* return to sender */ + return b; +} + + + +/* +TextureAxisFromPlane() +determines best orthagonal axis to project a texture onto a wall +(must be identical in radiant!) +*/ + +vec3_t baseaxis[18] = +{ + {0,0,1}, {1,0,0}, {0,-1,0}, // floor + {0,0,-1}, {1,0,0}, {0,-1,0}, // ceiling + {1,0,0}, {0,1,0}, {0,0,-1}, // west wall + {-1,0,0}, {0,1,0}, {0,0,-1}, // east wall + {0,1,0}, {1,0,0}, {0,0,-1}, // south wall + {0,-1,0}, {1,0,0}, {0,0,-1} // north wall +}; + +void TextureAxisFromPlane( plane_t *pln, vec3_t xv, vec3_t yv ) +{ + int bestaxis; + vec_t dot,best; + int i; + + best = 0; + bestaxis = 0; + + for (i=0 ; i<6 ; i++) + { + dot = DotProduct (pln->normal, baseaxis[i*3]); + if( dot > best + 0.0001f ) /* ydnar: bug 637 fix, suggested by jmonroe */ + { + best = dot; + bestaxis = i; + } + } + + VectorCopy (baseaxis[bestaxis*3+1], xv); + VectorCopy (baseaxis[bestaxis*3+2], yv); +} + + + +/* +QuakeTextureVecs() +creates world-to-texture mapping vecs for crappy quake plane arrangements +*/ + +void QuakeTextureVecs( plane_t *plane, vec_t shift[ 2 ], vec_t rotate, vec_t scale[ 2 ], vec_t mappingVecs[ 2 ][ 4 ] ) +{ + vec3_t vecs[2]; + int sv, tv; + vec_t ang, sinv, cosv; + vec_t ns, nt; + int i, j; + + + TextureAxisFromPlane(plane, vecs[0], vecs[1]); + + if (!scale[0]) + scale[0] = 1; + if (!scale[1]) + scale[1] = 1; + + // rotate axis + if (rotate == 0) + { sinv = 0 ; cosv = 1; } + else if (rotate == 90) + { sinv = 1 ; cosv = 0; } + else if (rotate == 180) + { sinv = 0 ; cosv = -1; } + else if (rotate == 270) + { sinv = -1 ; cosv = 0; } + else + { + ang = rotate / 180 * Q_PI; + sinv = sin(ang); + cosv = cos(ang); + } + + if (vecs[0][0]) + sv = 0; + else if (vecs[0][1]) + sv = 1; + else + sv = 2; + + if (vecs[1][0]) + tv = 0; + else if (vecs[1][1]) + tv = 1; + else + tv = 2; + + for (i=0 ; i<2 ; i++) { + ns = cosv * vecs[i][sv] - sinv * vecs[i][tv]; + nt = sinv * vecs[i][sv] + cosv * vecs[i][tv]; + vecs[i][sv] = ns; + vecs[i][tv] = nt; + } + + for (i=0 ; i<2 ; i++) + for (j=0 ; j<3 ; j++) + mappingVecs[i][j] = vecs[i][j] / scale[i]; + + mappingVecs[0][3] = shift[0]; + mappingVecs[1][3] = shift[1]; +} + + + +/* +ParseRawBrush() +parses the sides into buildBrush->sides[], nothing else. +no validation, back plane removal, etc. + +Timo - 08/26/99 +added brush epairs parsing ( ignoring actually ) +Timo - 08/04/99 +added exclusive brush primitive parsing +Timo - 08/08/99 +support for old brush format back in +NOTE: it would be "cleaner" to have seperate functions to parse between old and new brushes +*/ + +static void ParseRawBrush( qboolean onlyLights ) +{ + side_t *side; + vec3_t planePoints[ 3 ]; + int planenum; + shaderInfo_t *si; + vec_t shift[ 2 ]; + vec_t rotate = 0; + vec_t scale[ 2 ]; + char name[ MAX_QPATH ]; + char shader[ MAX_QPATH ]; + int flags; + + + /* initial setup */ + buildBrush->numsides = 0; + buildBrush->detail = qfalse; + + /* bp */ + if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) + MatchToken( "{" ); + + /* parse sides */ + while( 1 ) + { + if( !GetToken( qtrue ) ) + break; + if( !strcmp( token, "}" ) ) + break; + + /* ttimo : bp: here we may have to jump over brush epairs (only used in editor) */ + if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) + { + while( 1 ) + { + if( strcmp( token, "(" ) ) + GetToken( qfalse ); + else + break; + GetToken( qtrue ); + } + } + UnGetToken(); + + /* test side count */ + if( buildBrush->numsides >= MAX_BUILD_SIDES ) + xml_Select( "MAX_BUILD_SIDES", buildBrush->entityNum, buildBrush->brushNum, qtrue ); + + /* add side */ + side = &buildBrush->sides[ buildBrush->numsides ]; + memset( side, 0, sizeof( *side ) ); + buildBrush->numsides++; + + /* read the three point plane definition */ + Parse1DMatrix( 3, planePoints[ 0 ] ); + Parse1DMatrix( 3, planePoints[ 1 ] ); + Parse1DMatrix( 3, planePoints[ 2 ] ); + + /* bp: read the texture matrix */ + if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) + Parse2DMatrix( 2, 3, (float*) side->texMat ); + + /* read shader name */ + GetToken( qfalse ); + strcpy( name, token ); + + /* bp */ + if( g_bBrushPrimit == BPRIMIT_OLDBRUSHES ) + { + GetToken( qfalse ); + shift[ 0 ] = atof( token ); + GetToken( qfalse ); + shift[ 1 ] = atof( token ); + GetToken( qfalse ); + rotate = atof( token ); + GetToken( qfalse ); + scale[ 0 ] = atof( token ); + GetToken( qfalse ); + scale[ 1 ] = atof( token ); + } + + /* set default flags and values */ + sprintf( shader, "textures/%s", name ); + if( onlyLights ) + si = &shaderInfo[ 0 ]; + else + si = ShaderInfoForShader( shader ); + side->shaderInfo = si; + side->surfaceFlags = si->surfaceFlags; + side->contentFlags = si->contentFlags; + side->compileFlags = si->compileFlags; + side->value = si->value; + + /* ydnar: gs mods: bias texture shift */ + if( si->globalTexture == qfalse ) + { + shift[ 0 ] -= (floor( shift[ 0 ] / si->shaderWidth ) * si->shaderWidth); + shift[ 1 ] -= (floor( shift[ 1 ] / si->shaderHeight ) * si->shaderHeight); + } + + /* + historically, there are 3 integer values at the end of a brushside line in a .map file. + in quake 3, the only thing that mattered was the first of these three values, which + was previously the content flags. and only then did a single bit matter, the detail + bit. because every game has its own special flags for specifying detail, the + traditionally game-specified CONTENTS_DETAIL flag was overridden for Q3Map 2.3.0 + by C_DETAIL, defined in q3map2.h. the value is exactly as it was before, but + is stored in compileFlags, as opposed to contentFlags, for multiple-game + portability. :sigh: + */ + + if( TokenAvailable() ) + { + /* get detail bit from map content flags */ + GetToken( qfalse ); + flags = atoi( token ); + if( flags & C_DETAIL ) + side->compileFlags |= C_DETAIL; + + /* historical */ + GetToken( qfalse ); + //% td.flags = atoi( token ); + GetToken( qfalse ); + //% td.value = atoi( token ); + } + + /* find the plane number */ + planenum = MapPlaneFromPoints( planePoints ); + side->planenum = planenum; + + /* bp: get the texture mapping for this texturedef / plane combination */ + if( g_bBrushPrimit == BPRIMIT_OLDBRUSHES ) + QuakeTextureVecs( &mapplanes[ planenum ], shift, rotate, scale, side->vecs ); + } + + /* bp */ + if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) + { + UnGetToken(); + MatchToken( "}" ); + MatchToken( "}" ); + } +} + + + +/* +RemoveDuplicateBrushPlanes +returns false if the brush has a mirrored set of planes, +meaning it encloses no volume. +also removes planes without any normal +*/ + +qboolean RemoveDuplicateBrushPlanes( brush_t *b ) +{ + int i, j, k; + side_t *sides; + + sides = b->sides; + + for ( i = 1 ; i < b->numsides ; i++ ) { + + // check for a degenerate plane + if ( sides[i].planenum == -1) { + xml_Select( "degenerate plane", b->entityNum, b->brushNum, qfalse ); + // remove it + for ( k = i + 1 ; k < b->numsides ; k++ ) { + sides[k-1] = sides[k]; + } + b->numsides--; + i--; + continue; + } + + // check for duplication and mirroring + for ( j = 0 ; j < i ; j++ ) { + if ( sides[i].planenum == sides[j].planenum ) { + xml_Select( "duplicate plane", b->entityNum, b->brushNum, qfalse ); + // remove the second duplicate + for ( k = i + 1 ; k < b->numsides ; k++ ) { + sides[k-1] = sides[k]; + } + b->numsides--; + i--; + break; + } + + if ( sides[i].planenum == (sides[j].planenum ^ 1) ) { + // mirror plane, brush is invalid + xml_Select( "mirrored plane", b->entityNum, b->brushNum, qfalse ); + return qfalse; + } + } + } + return qtrue; +} + + + +/* +ParseBrush() +parses a brush out of a map file and sets it up +*/ + +static void ParseBrush( qboolean onlyLights, qboolean noCollapseGroups ) +{ + brush_t *b; + + + /* parse the brush out of the map */ + ParseRawBrush( onlyLights ); + + /* only go this far? */ + if( onlyLights ) + return; + + /* set some defaults */ + buildBrush->portalareas[ 0 ] = -1; + buildBrush->portalareas[ 1 ] = -1; + buildBrush->entityNum = numMapEntities - 1; + buildBrush->brushNum = entitySourceBrushes; + + /* if there are mirrored planes, the entire brush is invalid */ + if( !RemoveDuplicateBrushPlanes( buildBrush ) ) + return; + + /* get the content for the entire brush */ + SetBrushContents( buildBrush ); + + /* allow detail brushes to be removed */ + if( nodetail && (buildBrush->compileFlags & C_DETAIL) ) + { + //% FreeBrush( buildBrush ); + return; + } + + /* allow liquid brushes to be removed */ + if( nowater && (buildBrush->compileFlags & C_LIQUID ) ) + { + //% FreeBrush( buildBrush ); + return; + } + + /* ydnar: allow hint brushes to be removed */ + if( noHint && (buildBrush->compileFlags & C_HINT) ) + { + //% FreeBrush( buildBrush ); + return; + } + + /* finish the brush */ + b = FinishBrush(noCollapseGroups); +} + + + +/* +MoveBrushesToWorld() +takes all of the brushes from the current entity and +adds them to the world's brush list +(used by func_group) +*/ + +void AdjustBrushesForOrigin( entity_t *ent ); +void MoveBrushesToWorld( entity_t *ent ) +{ + brush_t *b, *next; + parseMesh_t *pm; + + /* we need to undo the common/origin adjustment, and instead shift them by the entity key origin */ + VectorScale(ent->origin, -1, ent->originbrush_origin); + AdjustBrushesForOrigin(ent); + VectorClear(ent->originbrush_origin); + + /* move brushes */ + for( b = ent->brushes; b != NULL; b = next ) + { + /* get next brush */ + next = b->next; + + /* link opaque brushes to head of list, translucent brushes to end */ + if( b->opaque || entities[ 0 ].lastBrush == NULL ) + { + b->next = entities[ 0 ].brushes; + entities[ 0 ].brushes = b; + if( entities[ 0 ].lastBrush == NULL ) + entities[ 0 ].lastBrush = b; + } + else + { + b->next = NULL; + entities[ 0 ].lastBrush->next = b; + entities[ 0 ].lastBrush = b; + } + } + ent->brushes = NULL; + + /* ydnar: move colormod brushes */ + if( ent->colorModBrushes != NULL ) + { + for( b = ent->colorModBrushes; b->nextColorModBrush != NULL; b = b->nextColorModBrush ); + + b->nextColorModBrush = entities[ 0 ].colorModBrushes; + entities[ 0 ].colorModBrushes = ent->colorModBrushes; + + ent->colorModBrushes = NULL; + } + + /* move patches */ + if( ent->patches != NULL ) + { + for( pm = ent->patches; pm->next != NULL; pm = pm->next ); + + pm->next = entities[ 0 ].patches; + entities[ 0 ].patches = ent->patches; + + ent->patches = NULL; + } +} + + + +/* +AdjustBrushesForOrigin() +*/ + +void AdjustBrushesForOrigin( entity_t *ent ) +{ + + int i; + side_t *s; + vec_t newdist; + brush_t *b; + parseMesh_t *p; + + /* walk brush list */ + for( b = ent->brushes; b != NULL; b = b->next ) + { + /* offset brush planes */ + for( i = 0; i < b->numsides; i++) + { + /* get brush side */ + s = &b->sides[ i ]; + + /* offset side plane */ + newdist = mapplanes[ s->planenum ].dist - DotProduct( mapplanes[ s->planenum ].normal, ent->originbrush_origin ); + + /* find a new plane */ + s->planenum = FindFloatPlane( mapplanes[ s->planenum ].normal, newdist, 0, NULL ); + } + + /* rebuild brush windings (ydnar: just offsetting the winding above should be fine) */ + CreateBrushWindings( b ); + } + + /* walk patch list */ + for( p = ent->patches; p != NULL; p = p->next ) + { + for( i = 0; i < (p->mesh.width * p->mesh.height); i++ ) + VectorSubtract( p->mesh.verts[ i ].xyz, ent->originbrush_origin, p->mesh.verts[ i ].xyz ); + } +} + + + +/* +SetEntityBounds() - ydnar +finds the bounds of an entity's brushes (necessary for terrain-style generic metashaders) +*/ + +void SetEntityBounds( entity_t *e ) +{ + int i; + brush_t *b; + parseMesh_t *p; + vec3_t mins, maxs; + const char *value; + + + + + /* walk the entity's brushes/patches and determine bounds */ + ClearBounds( mins, maxs ); + for( b = e->brushes; b; b = b->next ) + { + AddPointToBounds( b->mins, mins, maxs ); + AddPointToBounds( b->maxs, mins, maxs ); + } + for( p = e->patches; p; p = p->next ) + { + for( i = 0; i < (p->mesh.width * p->mesh.height); i++ ) + AddPointToBounds( p->mesh.verts[ i ].xyz, mins, maxs ); + } + + /* try to find explicit min/max key */ + value = ValueForKey( e, "min" ); + if( value[ 0 ] != '\0' ) + GetVectorForKey( e, "min", mins ); + value = ValueForKey( e, "max" ); + if( value[ 0 ] != '\0' ) + GetVectorForKey( e, "max", maxs ); + + /* store the bounds */ + for( b = e->brushes; b; b = b->next ) + { + VectorCopy( mins, b->eMins ); + VectorCopy( maxs, b->eMaxs ); + } + for( p = e->patches; p; p = p->next ) + { + VectorCopy( mins, p->eMins ); + VectorCopy( maxs, p->eMaxs ); + } +} + + + +/* +LoadEntityIndexMap() - ydnar +based on LoadAlphaMap() from terrain.c, a little more generic +*/ + +void LoadEntityIndexMap( entity_t *e ) +{ + int i, size, numLayers, w, h; + const char *value, *indexMapFilename, *shader; + char ext[ MAX_QPATH ], offset[ 4096 ], *search, *space; + byte *pixels; + unsigned int *pixels32; + indexMap_t *im; + brush_t *b; + parseMesh_t *p; + + + /* this only works with bmodel ents */ + if( e->brushes == NULL && e->patches == NULL ) + return; + + /* determine if there is an index map (support legacy "alphamap" key as well) */ + value = ValueForKey( e, "_indexmap" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( e, "alphamap" ); + if( value[ 0 ] == '\0' ) + return; + indexMapFilename = value; + + /* get number of layers (support legacy "layers" key as well) */ + value = ValueForKey( e, "_layers" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( e, "layers" ); + if( value[ 0 ] == '\0' ) + { + Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" has missing \"_layers\" or \"layers\" key\n", indexMapFilename ); + Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); + return; + } + numLayers = atoi( value ); + if( numLayers < 1 ) + { + Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" has < 1 layer (%d)\n", indexMapFilename, numLayers ); + Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); + return; + } + + /* get base shader name (support legacy "shader" key as well) */ + value = ValueForKey( mapEnt, "_shader" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( e, "shader" ); + if( value[ 0 ] == '\0' ) + { + Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" has missing \"_shader\" or \"shader\" key\n", indexMapFilename ); + Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); + return; + } + shader = value; + + /* note it */ + Sys_FPrintf( SYS_VRB, "Entity %d (%s) has shader index map \"%s\"\n", mapEnt->mapEntityNum, ValueForKey( e, "classname" ), indexMapFilename ); + + /* get index map file extension */ + ExtractFileExtension( indexMapFilename, ext ); + + /* handle tga image */ + if( !Q_stricmp( ext, "tga" ) ) + { + /* load it */ + Load32BitImage( indexMapFilename, &pixels32, &w, &h ); + + /* convert to bytes */ + size = w * h; + pixels = safe_malloc( size ); + for( i = 0; i < size; i++ ) + { + pixels[ i ] = ((pixels32[ i ] & 0xFF) * numLayers) / 256; + if( pixels[ i ] >= numLayers ) + pixels[ i ] = numLayers - 1; + } + + /* free the 32 bit image */ + free( pixels32 ); + } + else + { + /* load it */ + Load256Image( indexMapFilename, &pixels, NULL, &w, &h ); + + /* debug code */ + //% Sys_Printf( "-------------------------------" ); + + /* fix up out-of-range values */ + size = w * h; + for( i = 0; i < size; i++ ) + { + if( pixels[ i ] >= numLayers ) + pixels[ i ] = numLayers - 1; + + /* debug code */ + //% if( (i % w) == 0 ) + //% Sys_Printf( "\n" ); + //% Sys_Printf( "%c", pixels[ i ] + '0' ); + } + + /* debug code */ + //% Sys_Printf( "\n-------------------------------\n" ); + } + + /* the index map must be at least 2x2 pixels */ + if( w < 2 || h < 2 ) + { + Sys_Printf( "WARNING: Entity with index/alpha map \"%s\" is smaller than 2x2 pixels\n", indexMapFilename ); + Sys_Printf( "Entity will not be textured properly. Check your keys/values.\n" ); + free( pixels ); + return; + } + + /* create a new index map */ + im = safe_malloc( sizeof( *im ) ); + memset( im, 0, sizeof( *im ) ); + + /* set it up */ + im->w = w; + im->h = h; + im->numLayers = numLayers; + strcpy( im->name, indexMapFilename ); + strcpy( im->shader, shader ); + im->pixels = pixels; + + /* get height offsets */ + value = ValueForKey( mapEnt, "_offsets" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( e, "offsets" ); + if( value[ 0 ] != '\0' ) + { + /* value is a space-seperated set of numbers */ + strcpy( offset, value ); + search = offset; + + /* get each value */ + for( i = 0; i < 256 && *search != '\0'; i++ ) + { + space = strstr( search, " " ); + if( space != NULL ) + *space = '\0'; + im->offsets[ i ] = atof( search ); + if( space == NULL ) + break; + search = space + 1; + } + } + + /* store the index map in every brush/patch in the entity */ + for( b = e->brushes; b != NULL; b = b->next ) + b->im = im; + for( p = e->patches; p != NULL; p = p->next ) + p->im = im; +} + + + + + + + +/* +ParseMapEntity() +parses a single entity out of a map file +*/ + +static qboolean ParseMapEntity( qboolean onlyLights, qboolean noCollapseGroups ) +{ + epair_t *ep; + const char *classname, *value; + float lightmapScale, shadeAngle; + int lightmapSampleSize; + char shader[ MAX_QPATH ]; + shaderInfo_t *celShader = NULL; + brush_t *brush; + parseMesh_t *patch; + qboolean funcGroup; + int castShadows, recvShadows; + + + /* eof check */ + if( !GetToken( qtrue ) ) + return qfalse; + + /* conformance check */ + if( strcmp( token, "{" ) ) + { + Sys_Printf( "WARNING: ParseEntity: { not found, found %s on line %d - last entity was at: <%4.2f, %4.2f, %4.2f>...\n" + "Continuing to process map, but resulting BSP may be invalid.\n", + token, scriptline, entities[ numEntities ].origin[ 0 ], entities[ numEntities ].origin[ 1 ], entities[ numEntities ].origin[ 2 ] ); + return qfalse; + } + + /* range check */ + if( numEntities >= MAX_MAP_ENTITIES ) + Error( "numEntities == MAX_MAP_ENTITIES" ); + + /* setup */ + entitySourceBrushes = 0; + mapEnt = &entities[ numEntities ]; + numEntities++; + memset( mapEnt, 0, sizeof( *mapEnt ) ); + + /* ydnar: true entity numbering */ + mapEnt->mapEntityNum = numMapEntities; + numMapEntities++; + + /* loop */ + while( 1 ) + { + /* get initial token */ + if( !GetToken( qtrue ) ) + { + Sys_Printf( "WARNING: ParseEntity: EOF without closing brace\n" + "Continuing to process map, but resulting BSP may be invalid.\n" ); + return qfalse; + } + + if( !strcmp( token, "}" ) ) + break; + + if( !strcmp( token, "{" ) ) + { + /* parse a brush or patch */ + if( !GetToken( qtrue ) ) + break; + + /* check */ + if( !strcmp( token, "patchDef2" ) ) + { + numMapPatches++; + ParsePatch( onlyLights ); + } + else if( !strcmp( token, "terrainDef" ) ) + { + //% ParseTerrain(); + Sys_Printf( "WARNING: Terrain entity parsing not supported in this build.\n" ); /* ydnar */ + } + else if( !strcmp( token, "brushDef" ) ) + { + if( g_bBrushPrimit == BPRIMIT_OLDBRUSHES ) + Error( "Old brush format not allowed in new brush format map" ); + g_bBrushPrimit = BPRIMIT_NEWBRUSHES; + + /* parse brush primitive */ + ParseBrush( onlyLights, noCollapseGroups ); + } + else + { + if( g_bBrushPrimit == BPRIMIT_NEWBRUSHES ) + Error( "New brush format not allowed in old brush format map" ); + g_bBrushPrimit = BPRIMIT_OLDBRUSHES; + + /* parse old brush format */ + UnGetToken(); + ParseBrush( onlyLights, noCollapseGroups ); + } + entitySourceBrushes++; + } + else + { + /* parse a key / value pair */ + ep = ParseEPair(); + + /* ydnar: 2002-07-06 fixed wolf bug with empty epairs */ + if( ep->key[ 0 ] != '\0' && ep->value[ 0 ] != '\0' ) + { + ep->next = mapEnt->epairs; + mapEnt->epairs = ep; + } + } + } + + /* ydnar: get classname */ + classname = ValueForKey( mapEnt, "classname" ); + + /* ydnar: only lights? */ + if( onlyLights && Q_strncasecmp( classname, "light", 5 ) ) + { + numEntities--; + return qtrue; + } + + /* ydnar: determine if this is a func_group */ + if( !Q_stricmp( "func_group", classname ) ) + funcGroup = qtrue; + else + funcGroup = qfalse; + + /* worldspawn (and func_groups) default to cast/recv shadows in worldspawn group */ + if( funcGroup || mapEnt->mapEntityNum == 0 ) + { + //% Sys_Printf( "World: %d\n", mapEnt->mapEntityNum ); + castShadows = WORLDSPAWN_CAST_SHADOWS; + recvShadows = WORLDSPAWN_RECV_SHADOWS; + } + + /* other entities don't cast any shadows, but recv worldspawn shadows */ + else + { + //% Sys_Printf( "Entity: %d\n", mapEnt->mapEntityNum ); + castShadows = ENTITY_CAST_SHADOWS; + recvShadows = ENTITY_RECV_SHADOWS; + } + + /* get explicit shadow flags */ + GetEntityShadowFlags( mapEnt, NULL, &castShadows, &recvShadows ); + + /* vortex: added _ls key (short name of lightmapscale) */ + /* ydnar: get lightmap scaling value for this entity */ + lightmapScale = 0.0f; + if( strcmp( "", ValueForKey( mapEnt, "lightmapscale" ) ) || + strcmp( "", ValueForKey( mapEnt, "_lightmapscale" ) ) || + strcmp( "", ValueForKey( mapEnt, "_ls" ) ) ) + { + /* get lightmap scale from entity */ + lightmapScale = FloatForKey( mapEnt, "lightmapscale" ); + if( lightmapScale <= 0.0f ) + lightmapScale = FloatForKey( mapEnt, "_lightmapscale" ); + if( lightmapScale <= 0.0f ) + lightmapScale = FloatForKey( mapEnt, "_ls" ); + if( lightmapScale < 0.0f ) + lightmapScale = 0.0f; + if( lightmapScale > 0.0f ) + Sys_Printf( "Entity %d (%s) has lightmap scale of %.4f\n", mapEnt->mapEntityNum, classname, lightmapScale ); + } + + /* ydnar: get cel shader :) for this entity */ + value = ValueForKey( mapEnt, "_celshader" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ 0 ], "_celshader" ); + if( value[ 0 ] != '\0' ) + { + if(strcmp(value, "none")) + { + sprintf( shader, "textures/%s", value ); + celShader = ShaderInfoForShader( shader ); + Sys_Printf( "Entity %d (%s) has cel shader %s\n", mapEnt->mapEntityNum, classname, celShader->shader ); + } + else + { + celShader = NULL; + } + } + else + celShader = (*globalCelShader ? ShaderInfoForShader(globalCelShader) : NULL); + + /* jal : entity based _shadeangle */ + shadeAngle = 0.0f; + if ( strcmp( "", ValueForKey( mapEnt, "_shadeangle" ) ) ) + shadeAngle = FloatForKey( mapEnt, "_shadeangle" ); + /* vortex' aliases */ + else if ( strcmp( "", ValueForKey( mapEnt, "_smoothnormals" ) ) ) + shadeAngle = FloatForKey( mapEnt, "_smoothnormals" ); + else if ( strcmp( "", ValueForKey( mapEnt, "_sn" ) ) ) + shadeAngle = FloatForKey( mapEnt, "_sn" ); + else if ( strcmp( "", ValueForKey( mapEnt, "_smooth" ) ) ) + shadeAngle = FloatForKey( mapEnt, "_smooth" ); + + if( shadeAngle < 0.0f ) + shadeAngle = 0.0f; + + if( shadeAngle > 0.0f ) + Sys_Printf( "Entity %d (%s) has shading angle of %.4f\n", mapEnt->mapEntityNum, classname, shadeAngle ); + + /* jal : entity based _samplesize */ + lightmapSampleSize = 0; + if ( strcmp( "", ValueForKey( mapEnt, "_lightmapsamplesize" ) ) ) + lightmapSampleSize = IntForKey( mapEnt, "_lightmapsamplesize" ); + else if ( strcmp( "", ValueForKey( mapEnt, "_samplesize" ) ) ) + lightmapSampleSize = IntForKey( mapEnt, "_samplesize" ); + + if( lightmapSampleSize < 0 ) + lightmapSampleSize = 0; + + if( lightmapSampleSize > 0 ) + Sys_Printf( "Entity %d (%s) has lightmap sample size of %d\n", mapEnt->mapEntityNum, classname, lightmapSampleSize ); + + /* attach stuff to everything in the entity */ + for( brush = mapEnt->brushes; brush != NULL; brush = brush->next ) + { + brush->entityNum = mapEnt->mapEntityNum; + brush->castShadows = castShadows; + brush->recvShadows = recvShadows; + brush->lightmapSampleSize = lightmapSampleSize; + brush->lightmapScale = lightmapScale; + brush->celShader = celShader; + brush->shadeAngleDegrees = shadeAngle; + } + + for( patch = mapEnt->patches; patch != NULL; patch = patch->next ) + { + patch->entityNum = mapEnt->mapEntityNum; + patch->castShadows = castShadows; + patch->recvShadows = recvShadows; + patch->lightmapSampleSize = lightmapSampleSize; + patch->lightmapScale = lightmapScale; + patch->celShader = celShader; + } + + /* ydnar: gs mods: set entity bounds */ + SetEntityBounds( mapEnt ); + + /* ydnar: gs mods: load shader index map (equivalent to old terrain alphamap) */ + LoadEntityIndexMap( mapEnt ); + + /* get entity origin and adjust brushes */ + GetVectorForKey( mapEnt, "origin", mapEnt->origin ); + if( mapEnt->originbrush_origin[ 0 ] || mapEnt->originbrush_origin[ 1 ] || mapEnt->originbrush_origin[ 2 ] ) + AdjustBrushesForOrigin( mapEnt ); + + /* group_info entities are just for editor grouping (fixme: leak!) */ + if( !noCollapseGroups && !Q_stricmp( "group_info", classname ) ) + { + numEntities--; + return qtrue; + } + + /* group entities are just for editor convenience, toss all brushes into worldspawn */ + if( !noCollapseGroups && funcGroup ) + { + MoveBrushesToWorld( mapEnt ); + numEntities--; + return qtrue; + } + + /* done */ + return qtrue; +} + + + +/* +LoadMapFile() +loads a map file into a list of entities +*/ + +void LoadMapFile( char *filename, qboolean onlyLights, qboolean noCollapseGroups ) +{ + FILE *file; + brush_t *b; + int oldNumEntities = 0, numMapBrushes; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- LoadMapFile ---\n" ); + Sys_Printf( "Loading %s\n", filename ); + + /* hack */ + file = SafeOpenRead( filename ); + fclose( file ); + + /* load the map file */ + LoadScriptFile( filename, -1 ); + + /* setup */ + if( onlyLights ) + oldNumEntities = numEntities; + else + numEntities = 0; + + /* initial setup */ + numMapDrawSurfs = 0; + c_detail = 0; + g_bBrushPrimit = BPRIMIT_UNDEFINED; + + /* allocate a very large temporary brush for building the brushes as they are loaded */ + buildBrush = AllocBrush( MAX_BUILD_SIDES ); + + /* parse the map file */ + while( ParseMapEntity( onlyLights, noCollapseGroups ) ); + + /* light loading */ + if( onlyLights ) + { + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d light entities\n", numEntities - oldNumEntities ); + } + else + { + /* set map bounds */ + ClearBounds( mapMins, mapMaxs ); + for( b = entities[ 0 ].brushes; b; b = b->next ) + { + AddPointToBounds( b->mins, mapMins, mapMaxs ); + AddPointToBounds( b->maxs, mapMins, mapMaxs ); + } + + /* get brush counts */ + numMapBrushes = CountBrushList( entities[ 0 ].brushes ); + if( (float) c_detail / (float) numMapBrushes < 0.10f && numMapBrushes > 500 ) + Sys_Printf( "WARNING: Over 90 percent structural map detected. Compile time may be adversely affected.\n" ); + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d total world brushes\n", numMapBrushes ); + Sys_FPrintf( SYS_VRB, "%9d detail brushes\n", c_detail ); + Sys_FPrintf( SYS_VRB, "%9d patches\n", numMapPatches); + Sys_FPrintf( SYS_VRB, "%9d boxbevels\n", c_boxbevels); + Sys_FPrintf( SYS_VRB, "%9d edgebevels\n", c_edgebevels); + Sys_FPrintf( SYS_VRB, "%9d entities\n", numEntities ); + Sys_FPrintf( SYS_VRB, "%9d planes\n", nummapplanes); + Sys_Printf( "%9d areaportals\n", c_areaportals); + Sys_Printf( "Size: %5.0f, %5.0f, %5.0f to %5.0f, %5.0f, %5.0f\n", + mapMins[ 0 ], mapMins[ 1 ], mapMins[ 2 ], + mapMaxs[ 0 ], mapMaxs[ 1 ], mapMaxs[ 2 ]); + + /* write bogus map */ + if( fakemap ) + WriteBSPBrushMap( "fakemap.map", entities[ 0 ].brushes ); + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/mesh.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/mesh.c new file mode 100644 index 00000000..288525cf --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/mesh.c @@ -0,0 +1,826 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define MESH_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +LerpDrawVert() +returns an 50/50 interpolated vert +*/ + +void LerpDrawVert( bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *out ) +{ + int k; + + + out->xyz[ 0 ] = 0.5 * (a->xyz[ 0 ] + b->xyz[ 0 ]); + out->xyz[ 1 ] = 0.5 * (a->xyz[ 1 ] + b->xyz[ 1 ]); + out->xyz[ 2 ] = 0.5 * (a->xyz[ 2 ] + b->xyz[ 2 ]); + + out->st[ 0 ] = 0.5 * (a->st[ 0 ] + b->st[ 0 ]); + out->st[ 1 ] = 0.5 * (a->st[ 1 ] + b->st[ 1 ]); + + for( k = 0; k < MAX_LIGHTMAPS; k++ ) + { + out->lightmap[ k ][ 0 ] = 0.5f * (a->lightmap[ k ][ 0 ] + b->lightmap[ k ][ 0 ]); + out->lightmap[ k ][ 1 ] = 0.5f * (a->lightmap[ k ][ 1 ] + b->lightmap[ k ][ 1 ]); + out->color[ k ][ 0 ] = (a->color[ k ][ 0 ] + b->color[ k ][ 0 ]) >> 1; + out->color[ k ][ 1 ] = (a->color[ k ][ 1 ] + b->color[ k ][ 1 ]) >> 1; + out->color[ k ][ 2 ] = (a->color[ k ][ 2 ] + b->color[ k ][ 2 ]) >> 1; + out->color[ k ][ 3 ] = (a->color[ k ][ 3 ] + b->color[ k ][ 3 ]) >> 1; + } + + /* ydnar: added normal interpolation */ + out->normal[ 0 ] = 0.5f * (a->normal[ 0 ] + b->normal[ 0 ]); + out->normal[ 1 ] = 0.5f * (a->normal[ 1 ] + b->normal[ 1 ]); + out->normal[ 2 ] = 0.5f * (a->normal[ 2 ] + b->normal[ 2 ]); + + /* if the interpolant created a bogus normal, just copy the normal from a */ + if( VectorNormalize( out->normal, out->normal ) == 0 ) + VectorCopy( a->normal, out->normal ); +} + + + +/* +LerpDrawVertAmount() +returns a biased interpolated vert +*/ + +void LerpDrawVertAmount( bspDrawVert_t *a, bspDrawVert_t *b, float amount, bspDrawVert_t *out ) +{ + int k; + + + out->xyz[ 0 ] = a->xyz[ 0 ] + amount * (b->xyz[ 0 ] - a->xyz[ 0 ]); + out->xyz[ 1 ] = a->xyz[ 1 ] + amount * (b->xyz[ 1 ] - a->xyz[ 1 ]); + out->xyz[ 2 ] = a->xyz[ 2 ] + amount * (b->xyz[ 2 ] - a->xyz[ 2 ]); + + out->st[ 0 ] = a->st[ 0 ] + amount * (b->st[ 0 ] - a->st[ 0 ]); + out->st[ 1 ] = a->st[ 1 ] + amount * (b->st[ 1 ] - a->st[ 1 ]); + + for( k = 0; k < MAX_LIGHTMAPS; k++ ) + { + out->lightmap[ k ][ 0 ] = a->lightmap[ k ][ 0 ] + amount * (b->lightmap[ k ][ 0 ] - a->lightmap[ k ][ 0 ]); + out->lightmap[ k ][ 1 ] = a->lightmap[ k ][ 1 ] + amount * (b->lightmap[ k ][ 1 ] - a->lightmap[ k ][ 1 ]); + out->color[ k ][ 0 ] = a->color[ k ][ 0 ] + amount * (b->color[ k ][ 0 ] - a->color[ k ][ 0 ]); + out->color[ k ][ 1 ] = a->color[ k ][ 1 ] + amount * (b->color[ k ][ 1 ] - a->color[ k ][ 1 ]); + out->color[ k ][ 2 ] = a->color[ k ][ 2 ] + amount * (b->color[ k ][ 2 ] - a->color[ k ][ 2 ]); + out->color[ k ][ 3 ] = a->color[ k ][ 3 ] + amount * (b->color[ k ][ 3 ] - a->color[ k ][ 3 ]); + } + + out->normal[ 0 ] = a->normal[ 0 ] + amount * (b->normal[ 0 ] - a->normal[ 0 ]); + out->normal[ 1 ] = a->normal[ 1 ] + amount * (b->normal[ 1 ] - a->normal[ 1 ]); + out->normal[ 2 ] = a->normal[ 2 ] + amount * (b->normal[ 2 ] - a->normal[ 2 ]); + + /* if the interpolant created a bogus normal, just copy the normal from a */ + if( VectorNormalize( out->normal, out->normal ) == 0 ) + VectorCopy( a->normal, out->normal ); +} + + +void FreeMesh( mesh_t *m ) { + free( m->verts ); + free( m ); +} + +void PrintMesh( mesh_t *m ) { + int i, j; + + for ( i = 0 ; i < m->height ; i++ ) { + for ( j = 0 ; j < m->width ; j++ ) { + Sys_Printf("(%5.2f %5.2f %5.2f) " + , m->verts[i*m->width+j].xyz[0] + , m->verts[i*m->width+j].xyz[1] + , m->verts[i*m->width+j].xyz[2] ); + } + Sys_Printf("\n"); + } +} + + +mesh_t *CopyMesh( mesh_t *mesh ) { + mesh_t *out; + int size; + + out = safe_malloc( sizeof( *out ) ); + out->width = mesh->width; + out->height = mesh->height; + + size = out->width * out->height * sizeof( *out->verts ); + out->verts = safe_malloc( size ); + memcpy( out->verts, mesh->verts, size ); + + return out; +} + + +/* +TransposeMesh() +returns a transposed copy of the mesh, freeing the original +*/ + +mesh_t *TransposeMesh( mesh_t *in ) { + int w, h; + mesh_t *out; + + out = safe_malloc( sizeof( *out ) ); + out->width = in->height; + out->height = in->width; + out->verts = safe_malloc( out->width * out->height * sizeof( bspDrawVert_t ) ); + + for ( h = 0 ; h < in->height ; h++ ) { + for ( w = 0 ; w < in->width ; w++ ) { + out->verts[ w * in->height + h ] = in->verts[ h * in->width + w ]; + } + } + + FreeMesh( in ); + + return out; +} + +void InvertMesh( mesh_t *in ) { + int w, h; + bspDrawVert_t temp; + + for ( h = 0 ; h < in->height ; h++ ) { + for ( w = 0 ; w < in->width / 2 ; w++ ) { + temp = in->verts[ h * in->width + w ]; + in->verts[ h * in->width + w ] = in->verts[ h * in->width + in->width - 1 - w ]; + in->verts[ h * in->width + in->width - 1 - w ] = temp; + } + } +} + +/* +================= +MakeMeshNormals + +================= +*/ +void MakeMeshNormals( mesh_t in ) +{ + int i, j, k, dist; + vec3_t normal; + vec3_t sum; + int count; + vec3_t base; + vec3_t delta; + int x, y; + bspDrawVert_t *dv; + vec3_t around[8], temp; + qboolean good[8]; + qboolean wrapWidth, wrapHeight; + float len; + int neighbors[8][2] = + { + {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1}, {-1,-1}, {-1,0}, {-1,1} + }; + + + wrapWidth = qfalse; + for ( i = 0 ; i < in.height ; i++ ) { + VectorSubtract( in.verts[i*in.width].xyz, + in.verts[i*in.width+in.width-1].xyz, delta ); + len = VectorLength( delta ); + if ( len > 1.0 ) { + break; + } + } + if ( i == in.height ) { + wrapWidth = qtrue; + } + + wrapHeight = qfalse; + for ( i = 0 ; i < in.width ; i++ ) { + VectorSubtract( in.verts[i].xyz, + in.verts[i + (in.height-1)*in.width].xyz, delta ); + len = VectorLength( delta ); + if ( len > 1.0 ) { + break; + } + } + if ( i == in.width) { + wrapHeight = qtrue; + } + + + for ( i = 0 ; i < in.width ; i++ ) { + for ( j = 0 ; j < in.height ; j++ ) { + count = 0; + dv = &in.verts[j*in.width+i]; + VectorCopy( dv->xyz, base ); + for ( k = 0 ; k < 8 ; k++ ) { + VectorClear( around[k] ); + good[k] = qfalse; + + for ( dist = 1 ; dist <= 3 ; dist++ ) { + x = i + neighbors[k][0] * dist; + y = j + neighbors[k][1] * dist; + if ( wrapWidth ) { + if ( x < 0 ) { + x = in.width - 1 + x; + } else if ( x >= in.width ) { + x = 1 + x - in.width; + } + } + if ( wrapHeight ) { + if ( y < 0 ) { + y = in.height - 1 + y; + } else if ( y >= in.height ) { + y = 1 + y - in.height; + } + } + + if ( x < 0 || x >= in.width || y < 0 || y >= in.height ) { + break; // edge of patch + } + VectorSubtract( in.verts[y*in.width+x].xyz, base, temp ); + if ( VectorNormalize( temp, temp ) == 0 ) { + continue; // degenerate edge, get more dist + } else { + good[k] = qtrue; + VectorCopy( temp, around[k] ); + break; // good edge + } + } + } + + VectorClear( sum ); + for ( k = 0 ; k < 8 ; k++ ) { + if ( !good[k] || !good[(k+1)&7] ) { + continue; // didn't get two points + } + CrossProduct( around[(k+1)&7], around[k], normal ); + if ( VectorNormalize( normal, normal ) == 0 ) { + continue; + } + VectorAdd( normal, sum, sum ); + count++; + } + if ( count == 0 ) { +//Sys_Printf("bad normal\n"); + count = 1; + } + VectorNormalize( sum, dv->normal ); + } + } +} + +/* +PutMeshOnCurve() +drops the aproximating points onto the curve +ydnar: fixme: make this use LerpDrawVert() rather than this complicated mess +*/ + +void PutMeshOnCurve( mesh_t in ) { + int i, j, l, m; + float prev, next; + + + // put all the aproximating points on the curve + for ( i = 0 ; i < in.width ; i++ ) { + for ( j = 1 ; j < in.height ; j += 2 ) { + for ( l = 0 ; l < 3 ; l++ ) { + prev = ( in.verts[j*in.width+i].xyz[l] + in.verts[(j+1)*in.width+i].xyz[l] ) * 0.5; + next = ( in.verts[j*in.width+i].xyz[l] + in.verts[(j-1)*in.width+i].xyz[l] ) * 0.5; + in.verts[j*in.width+i].xyz[l] = ( prev + next ) * 0.5; + + /* ydnar: interpolating st coords */ + if( l < 2 ) + { + prev = ( in.verts[j*in.width+i].st[l] + in.verts[(j+1)*in.width+i].st[l] ) * 0.5; + next = ( in.verts[j*in.width+i].st[l] + in.verts[(j-1)*in.width+i].st[l] ) * 0.5; + in.verts[j*in.width+i].st[l] = ( prev + next ) * 0.5; + + for( m = 0; m < MAX_LIGHTMAPS; m++ ) + { + prev = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[(j+1)*in.width+i].lightmap[ m ][l] ) * 0.5; + next = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[(j-1)*in.width+i].lightmap[ m ][l] ) * 0.5; + in.verts[j*in.width+i].lightmap[ m ][l] = ( prev + next ) * 0.5; + } + } + } + } + } + + for ( j = 0 ; j < in.height ; j++ ) { + for ( i = 1 ; i < in.width ; i += 2 ) { + for ( l = 0 ; l < 3 ; l++ ) { + prev = ( in.verts[j*in.width+i].xyz[l] + in.verts[j*in.width+i+1].xyz[l] ) * 0.5; + next = ( in.verts[j*in.width+i].xyz[l] + in.verts[j*in.width+i-1].xyz[l] ) * 0.5; + in.verts[j*in.width+i].xyz[l] = ( prev + next ) * 0.5; + + /* ydnar: interpolating st coords */ + if( l < 2 ) + { + prev = ( in.verts[j*in.width+i].st[l] + in.verts[j*in.width+i+1].st[l] ) * 0.5; + next = ( in.verts[j*in.width+i].st[l] + in.verts[j*in.width+i-1].st[l] ) * 0.5; + in.verts[j*in.width+i].st[l] = ( prev + next ) * 0.5; + + for( m = 0; m < MAX_LIGHTMAPS; m++ ) + { + prev = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[j*in.width+i+1].lightmap[ m ][l] ) * 0.5; + next = ( in.verts[j*in.width+i].lightmap[ m ][l] + in.verts[j*in.width+i-1].lightmap[ m ][l] ) * 0.5; + in.verts[j*in.width+i].lightmap[ m ][l] = ( prev + next ) * 0.5; + } + } + } + } + } +} + + +/* +================= +SubdivideMesh + +================= +*/ +mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ) +{ + int i, j, k, l; + bspDrawVert_t prev, next, mid; + vec3_t prevxyz, nextxyz, midxyz; + vec3_t delta; + float len; + mesh_t out; + + /* ydnar: static for os x */ + MAC_STATIC bspDrawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS]; + + + out.width = in.width; + out.height = in.height; + + for ( i = 0 ; i < in.width ; i++ ) { + for ( j = 0 ; j < in.height ; j++ ) { + expand[j][i] = in.verts[j*in.width+i]; + } + } + + // horizontal subdivisions + for ( j = 0 ; j + 2 < out.width ; j += 2 ) { + // check subdivided midpoints against control points + for ( i = 0 ; i < out.height ; i++ ) { + for ( l = 0 ; l < 3 ; l++ ) { + prevxyz[l] = expand[i][j+1].xyz[l] - expand[i][j].xyz[l]; + nextxyz[l] = expand[i][j+2].xyz[l] - expand[i][j+1].xyz[l]; + midxyz[l] = (expand[i][j].xyz[l] + expand[i][j+1].xyz[l] * 2 + + expand[i][j+2].xyz[l] ) * 0.25; + } + + // if the span length is too long, force a subdivision + if ( VectorLength( prevxyz ) > minLength + || VectorLength( nextxyz ) > minLength ) { + break; + } + + // see if this midpoint is off far enough to subdivide + VectorSubtract( expand[i][j+1].xyz, midxyz, delta ); + len = VectorLength( delta ); + if ( len > maxError ) { + break; + } + } + + if ( out.width + 2 >= MAX_EXPANDED_AXIS ) { + break; // can't subdivide any more + } + + if ( i == out.height ) { + continue; // didn't need subdivision + } + + // insert two columns and replace the peak + out.width += 2; + + for ( i = 0 ; i < out.height ; i++ ) { + LerpDrawVert( &expand[i][j], &expand[i][j+1], &prev ); + LerpDrawVert( &expand[i][j+1], &expand[i][j+2], &next ); + LerpDrawVert( &prev, &next, &mid ); + + for ( k = out.width - 1 ; k > j + 3 ; k-- ) { + expand[i][k] = expand[i][k-2]; + } + expand[i][j + 1] = prev; + expand[i][j + 2] = mid; + expand[i][j + 3] = next; + } + + // back up and recheck this set again, it may need more subdivision + j -= 2; + + } + + // vertical subdivisions + for ( j = 0 ; j + 2 < out.height ; j += 2 ) { + // check subdivided midpoints against control points + for ( i = 0 ; i < out.width ; i++ ) { + for ( l = 0 ; l < 3 ; l++ ) { + prevxyz[l] = expand[j+1][i].xyz[l] - expand[j][i].xyz[l]; + nextxyz[l] = expand[j+2][i].xyz[l] - expand[j+1][i].xyz[l]; + midxyz[l] = (expand[j][i].xyz[l] + expand[j+1][i].xyz[l] * 2 + + expand[j+2][i].xyz[l] ) * 0.25; + } + + // if the span length is too long, force a subdivision + if ( VectorLength( prevxyz ) > minLength + || VectorLength( nextxyz ) > minLength ) { + break; + } + // see if this midpoint is off far enough to subdivide + VectorSubtract( expand[j+1][i].xyz, midxyz, delta ); + len = VectorLength( delta ); + if ( len > maxError ) { + break; + } + } + + if ( out.height + 2 >= MAX_EXPANDED_AXIS ) { + break; // can't subdivide any more + } + + if ( i == out.width ) { + continue; // didn't need subdivision + } + + // insert two columns and replace the peak + out.height += 2; + + for ( i = 0 ; i < out.width ; i++ ) { + LerpDrawVert( &expand[j][i], &expand[j+1][i], &prev ); + LerpDrawVert( &expand[j+1][i], &expand[j+2][i], &next ); + LerpDrawVert( &prev, &next, &mid ); + + for ( k = out.height - 1 ; k > j + 3 ; k-- ) { + expand[k][i] = expand[k-2][i]; + } + expand[j+1][i] = prev; + expand[j+2][i] = mid; + expand[j+3][i] = next; + } + + // back up and recheck this set again, it may need more subdivision + j -= 2; + + } + + // collapse the verts + + out.verts = &expand[0][0]; + for ( i = 1 ; i < out.height ; i++ ) { + memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(bspDrawVert_t) ); + } + + return CopyMesh(&out); +} + + + +/* +IterationsForCurve() - ydnar +given a curve of a certain length, return the number of subdivision iterations +note: this is affected by subdivision amount +*/ + +int IterationsForCurve( float len, int subdivisions ) +{ + int iterations, facets; + + + /* calculate the number of subdivisions */ + for( iterations = 0; iterations < 3; iterations++ ) + { + facets = subdivisions * 16 * pow( 2, iterations ); + if( facets >= len ) + break; + } + + /* return to caller */ + return iterations; +} + + +/* +SubdivideMesh2() - ydnar +subdivides each mesh quad a specified number of times +*/ + +mesh_t *SubdivideMesh2( mesh_t in, int iterations ) +{ + int i, j, k; + bspDrawVert_t prev, next, mid; + mesh_t out; + + /* ydnar: static for os x */ + MAC_STATIC bspDrawVert_t expand[ MAX_EXPANDED_AXIS ][ MAX_EXPANDED_AXIS ]; + + + /* initial setup */ + out.width = in.width; + out.height = in.height; + for( i = 0; i < in.width; i++ ) + { + for( j = 0; j < in.height; j++ ) + expand[ j ][ i ] = in.verts[ j * in.width + i ]; + } + + /* keep chopping */ + for( ; iterations > 0; iterations-- ) + { + /* horizontal subdivisions */ + for( j = 0; j + 2 < out.width; j += 4 ) + { + /* check size limit */ + if( out.width + 2 >= MAX_EXPANDED_AXIS ) + break; + + /* insert two columns and replace the peak */ + out.width += 2; + for( i = 0; i < out.height; i++ ) + { + LerpDrawVert( &expand[ i ][ j ], &expand[ i ][ j + 1 ], &prev ); + LerpDrawVert( &expand[ i ][ j + 1 ], &expand[ i ][ j + 2 ], &next ); + LerpDrawVert( &prev, &next, &mid ); + + for ( k = out.width - 1 ; k > j + 3; k-- ) + expand [ i ][ k ] = expand[ i ][ k - 2 ]; + expand[ i ][ j + 1 ] = prev; + expand[ i ][ j + 2 ] = mid; + expand[ i ][ j + 3 ] = next; + } + + } + + /* vertical subdivisions */ + for ( j = 0; j + 2 < out.height; j += 4 ) + { + /* check size limit */ + if( out.height + 2 >= MAX_EXPANDED_AXIS ) + break; + + /* insert two columns and replace the peak */ + out.height += 2; + for( i = 0; i < out.width; i++ ) + { + LerpDrawVert( &expand[ j ][ i ], &expand[ j + 1 ][ i ], &prev ); + LerpDrawVert( &expand[ j + 1 ][ i ], &expand[ j + 2 ][ i ], &next ); + LerpDrawVert( &prev, &next, &mid ); + + for( k = out.height - 1; k > j + 3; k-- ) + expand[ k ][ i ] = expand[ k - 2 ][ i ]; + expand[ j + 1 ][ i ] = prev; + expand[ j + 2 ][ i ] = mid; + expand[ j + 3 ][ i ] = next; + } + } + } + + /* collapse the verts */ + out.verts = &expand[ 0 ][ 0 ]; + for( i = 1; i < out.height; i++ ) + memmove( &out.verts[ i * out.width ], expand[ i ], out.width * sizeof( bspDrawVert_t ) ); + + /* return to sender */ + return CopyMesh( &out ); +} + + + + + + + +/* +================ +ProjectPointOntoVector +================ +*/ +void ProjectPointOntoVector( vec3_t point, vec3_t vStart, vec3_t vEnd, vec3_t vProj ) +{ + vec3_t pVec, vec; + + VectorSubtract( point, vStart, pVec ); + VectorSubtract( vEnd, vStart, vec ); + VectorNormalize( vec, vec ); + // project onto the directional vector for this segment + VectorMA( vStart, DotProduct( pVec, vec ), vec, vProj ); +} + +/* +================ +RemoveLinearMeshColumsRows +================ +*/ +mesh_t *RemoveLinearMeshColumnsRows( mesh_t *in ) { + int i, j, k; + float len, maxLength; + vec3_t proj, dir; + mesh_t out; + + /* ydnar: static for os x */ + MAC_STATIC bspDrawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS]; + + + out.width = in->width; + out.height = in->height; + + for ( i = 0 ; i < in->width ; i++ ) { + for ( j = 0 ; j < in->height ; j++ ) { + expand[j][i] = in->verts[j*in->width+i]; + } + } + + for ( j = 1 ; j < out.width - 1; j++ ) { + maxLength = 0; + for ( i = 0 ; i < out.height ; i++ ) { + ProjectPointOntoVector(expand[i][j].xyz, expand[i][j-1].xyz, expand[i][j+1].xyz, proj); + VectorSubtract(expand[i][j].xyz, proj, dir); + len = VectorLength(dir); + if (len > maxLength) { + maxLength = len; + } + } + if (maxLength < 0.1) + { + out.width--; + for ( i = 0 ; i < out.height ; i++ ) { + for (k = j; k < out.width; k++) { + expand[i][k] = expand[i][k+1]; + } + } + j--; + } + } + for ( j = 1 ; j < out.height - 1; j++ ) { + maxLength = 0; + for ( i = 0 ; i < out.width ; i++ ) { + ProjectPointOntoVector(expand[j][i].xyz, expand[j-1][i].xyz, expand[j+1][i].xyz, proj); + VectorSubtract(expand[j][i].xyz, proj, dir); + len = VectorLength(dir); + if (len > maxLength) { + maxLength = len; + } + } + if (maxLength < 0.1) + { + out.height--; + for ( i = 0 ; i < out.width ; i++ ) { + for (k = j; k < out.height; k++) { + expand[k][i] = expand[k+1][i]; + } + } + j--; + } + } + // collapse the verts + out.verts = &expand[0][0]; + for ( i = 1 ; i < out.height ; i++ ) { + memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(bspDrawVert_t) ); + } + + return CopyMesh(&out); +} + + + +/* +================= +SubdivideMeshQuads +================= +*/ +mesh_t *SubdivideMeshQuads( mesh_t *in, float minLength, int maxsize, int *widthtable, int *heighttable ) +{ + int i, j, k, w, h, maxsubdivisions, subdivisions; + vec3_t dir; + float length, maxLength, amount; + mesh_t out; + bspDrawVert_t expand[MAX_EXPANDED_AXIS][MAX_EXPANDED_AXIS]; + + out.width = in->width; + out.height = in->height; + + for ( i = 0 ; i < in->width ; i++ ) { + for ( j = 0 ; j < in->height ; j++ ) { + expand[j][i] = in->verts[j*in->width+i]; + } + } + + if (maxsize > MAX_EXPANDED_AXIS) + Error("SubdivideMeshQuads: maxsize > MAX_EXPANDED_AXIS"); + + // horizontal subdivisions + + maxsubdivisions = (maxsize - in->width) / (in->width - 1); + + for ( w = 0, j = 0 ; w < in->width - 1; w++, j += subdivisions + 1) { + maxLength = 0; + for ( i = 0 ; i < out.height ; i++ ) { + VectorSubtract(expand[i][j+1].xyz, expand[i][j].xyz, dir); + length = VectorLength( dir ); + if (length > maxLength) { + maxLength = length; + } + } + + subdivisions = (int) (maxLength / minLength); + if (subdivisions > maxsubdivisions) + subdivisions = maxsubdivisions; + + widthtable[w] = subdivisions + 1; + if (subdivisions <= 0) + continue; + + out.width += subdivisions; + + for ( i = 0 ; i < out.height ; i++ ) { + for ( k = out.width - 1 ; k > j + subdivisions; k-- ) { + expand[i][k] = expand[i][k-subdivisions]; + } + for (k = 1; k <= subdivisions; k++) + { + amount = (float) k / (subdivisions + 1); + LerpDrawVertAmount(&expand[i][j], &expand[i][j+subdivisions+1], amount, &expand[i][j+k]); + } + } + } + + maxsubdivisions = (maxsize - in->height) / (in->height - 1); + + for ( h = 0, j = 0 ; h < in->height - 1; h++, j += subdivisions + 1) { + maxLength = 0; + for ( i = 0 ; i < out.width ; i++ ) { + VectorSubtract(expand[j+1][i].xyz, expand[j][i].xyz, dir); + length = VectorLength( dir ); + if (length > maxLength) { + maxLength = length; + } + } + + subdivisions = (int) (maxLength / minLength); + if (subdivisions > maxsubdivisions) + subdivisions = maxsubdivisions; + + heighttable[h] = subdivisions + 1; + if (subdivisions <= 0) + continue; + + out.height += subdivisions; + + for ( i = 0 ; i < out.width ; i++ ) { + for ( k = out.height - 1 ; k > j + subdivisions; k-- ) { + expand[k][i] = expand[k-subdivisions][i]; + } + for (k = 1; k <= subdivisions; k++) + { + amount = (float) k / (subdivisions + 1); + LerpDrawVertAmount(&expand[j][i], &expand[j+subdivisions+1][i], amount, &expand[j+k][i]); + } + } + } + + // collapse the verts + out.verts = &expand[0][0]; + for ( i = 1 ; i < out.height ; i++ ) { + memmove( &out.verts[i*out.width], expand[i], out.width * sizeof(bspDrawVert_t) ); + } + + return CopyMesh(&out); +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/model.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/model.c new file mode 100644 index 00000000..a56134c8 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/model.c @@ -0,0 +1,904 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define MODEL_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +PicoPrintFunc() +callback for picomodel.lib +*/ + +void PicoPrintFunc( int level, const char *str ) +{ + if( str == NULL ) + return; + switch( level ) + { + case PICO_NORMAL: + Sys_Printf( "%s\n", str ); + break; + + case PICO_VERBOSE: + Sys_FPrintf( SYS_VRB, "%s\n", str ); + break; + + case PICO_WARNING: + Sys_Printf( "WARNING: %s\n", str ); + break; + + case PICO_ERROR: + Sys_Printf( "ERROR: %s\n", str ); + break; + + case PICO_FATAL: + Error( "ERROR: %s\n", str ); + break; + } +} + + + +/* +PicoLoadFileFunc() +callback for picomodel.lib +*/ + +void PicoLoadFileFunc( const char *name, byte **buffer, int *bufSize ) +{ + *bufSize = vfsLoadFile( name, (void**) buffer, 0 ); +} + + + +/* +FindModel() - ydnar +finds an existing picoModel and returns a pointer to the picoModel_t struct or NULL if not found +*/ + +picoModel_t *FindModel( const char *name, int frame ) +{ + int i; + + + /* init */ + if( numPicoModels <= 0 ) + memset( picoModels, 0, sizeof( picoModels ) ); + + /* dummy check */ + if( name == NULL || name[ 0 ] == '\0' ) + return NULL; + + /* search list */ + for( i = 0; i < MAX_MODELS; i++ ) + { + if( picoModels[ i ] != NULL && + !strcmp( PicoGetModelName( picoModels[ i ] ), name ) && + PicoGetModelFrameNum( picoModels[ i ] ) == frame ) + return picoModels[ i ]; + } + + /* no matching picoModel found */ + return NULL; +} + + + +/* +LoadModel() - ydnar +loads a picoModel and returns a pointer to the picoModel_t struct or NULL if not found +*/ + +picoModel_t *LoadModel( const char *name, int frame ) +{ + int i; + picoModel_t *model, **pm; + + + /* init */ + if( numPicoModels <= 0 ) + memset( picoModels, 0, sizeof( picoModels ) ); + + /* dummy check */ + if( name == NULL || name[ 0 ] == '\0' ) + return NULL; + + /* try to find existing picoModel */ + model = FindModel( name, frame ); + if( model != NULL ) + return model; + + /* none found, so find first non-null picoModel */ + pm = NULL; + for( i = 0; i < MAX_MODELS; i++ ) + { + if( picoModels[ i ] == NULL ) + { + pm = &picoModels[ i ]; + break; + } + } + + /* too many picoModels? */ + if( pm == NULL ) + Error( "MAX_MODELS (%d) exceeded, there are too many model files referenced by the map.", MAX_MODELS ); + + /* attempt to parse model */ + *pm = PicoLoadModel( name, frame ); + + /* if loading failed, make a bogus model to silence the rest of the warnings */ + if( *pm == NULL ) + { + /* allocate a new model */ + *pm = PicoNewModel(); + if( *pm == NULL ) + return NULL; + + /* set data */ + PicoSetModelName( *pm, name ); + PicoSetModelFrameNum( *pm, frame ); + } + + /* debug code */ + #if 0 + { + int numSurfaces, numVertexes; + picoSurface_t *ps; + + + Sys_Printf( "Model %s\n", name ); + numSurfaces = PicoGetModelNumSurfaces( *pm ); + for( i = 0; i < numSurfaces; i++ ) + { + ps = PicoGetModelSurface( *pm, i ); + numVertexes = PicoGetSurfaceNumVertexes( ps ); + Sys_Printf( "Surface %d has %d vertexes\n", i, numVertexes ); + } + } + #endif + + /* set count */ + if( *pm != NULL ) + numPicoModels++; + + /* return the picoModel */ + return *pm; +} + + + +/* +InsertModel() - ydnar +adds a picomodel into the bsp +*/ + +void InsertModel( const char *name, int skin, int frame, m4x4_t transform, remap_t *remap, shaderInfo_t *celShader, int eNum, int castShadows, int recvShadows, int spawnFlags, float lightmapScale, int lightmapSampleSize, float shadeAngle ) +{ + int i, j, k, s, numSurfaces; + m4x4_t identity, nTransform; + picoModel_t *model; + picoShader_t *shader; + picoSurface_t *surface; + shaderInfo_t *si; + mapDrawSurface_t *ds; + bspDrawVert_t *dv; + char *picoShaderName; + char shaderName[ MAX_QPATH ]; + picoVec_t *xyz, *normal, *st; + byte *color; + picoIndex_t *indexes; + remap_t *rm, *glob; + skinfile_t *sf, *sf2; + double normalEpsilon_save; + double distanceEpsilon_save; + char skinfilename[ MAX_QPATH ]; + char *skinfilecontent; + int skinfilesize; + char *skinfileptr, *skinfilenextptr; + + + /* get model */ + model = LoadModel( name, frame ); + if( model == NULL ) + return; + + /* load skin file */ + snprintf(skinfilename, sizeof(skinfilename), "%s_%d.skin", name, skin); + skinfilename[sizeof(skinfilename)-1] = 0; + skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0); + if(skinfilesize < 0 && skin != 0) + { + /* fallback to skin 0 if invalid */ + snprintf(skinfilename, sizeof(skinfilename), "%s_0.skin", name); + skinfilename[sizeof(skinfilename)-1] = 0; + skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0); + if(skinfilesize >= 0) + Sys_Printf( "Skin %d of %s does not exist, using 0 instead\n", skin, name ); + } + sf = NULL; + if(skinfilesize >= 0) + { + Sys_Printf( "Using skin %d of %s\n", skin, name ); + int pos; + for(skinfileptr = skinfilecontent; *skinfileptr; skinfileptr = skinfilenextptr) + { + // for fscanf + char format[64]; + + skinfilenextptr = strchr(skinfileptr, '\r'); + if(skinfilenextptr) + { + *skinfilenextptr++ = 0; + } + else + { + skinfilenextptr = strchr(skinfileptr, '\n'); + if(skinfilenextptr) + *skinfilenextptr++ = 0; + else + skinfilenextptr = skinfileptr + strlen(skinfileptr); + } + + /* create new item */ + sf2 = sf; + sf = safe_malloc( sizeof( *sf ) ); + sf->next = sf2; + + sprintf(format, "replace %%%ds %%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1); + if(sscanf(skinfileptr, format, sf->name, sf->to) == 2) + continue; + sprintf(format, " %%%d[^, ] ,%%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1); + if((pos = sscanf(skinfileptr, format, sf->name, sf->to)) == 2) + continue; + + /* invalid input line -> discard sf struct */ + Sys_Printf( "Discarding skin directive in %s: %s\n", skinfilename, skinfileptr ); + free(sf); + sf = sf2; + } + free(skinfilecontent); + } + + /* handle null matrix */ + if( transform == NULL ) + { + m4x4_identity( identity ); + transform = identity; + } + + /* hack: Stable-1_2 and trunk have differing row/column major matrix order + this transpose is necessary with Stable-1_2 + uncomment the following line with old m4x4_t (non 1.3/spog_branch) code */ + //% m4x4_transpose( transform ); + + /* create transform matrix for normals */ + memcpy( nTransform, transform, sizeof( m4x4_t ) ); + if( m4x4_invert( nTransform ) ) + Sys_FPrintf( SYS_VRB, "WARNING: Can't invert model transform matrix, using transpose instead\n" ); + m4x4_transpose( nTransform ); + + /* fix bogus lightmap scale */ + if( lightmapScale <= 0.0f ) + lightmapScale = 1.0f; + + /* fix bogus shade angle */ + if( shadeAngle <= 0.0f ) + shadeAngle = 0.0f; + + /* each surface on the model will become a new map drawsurface */ + numSurfaces = PicoGetModelNumSurfaces( model ); + //% Sys_FPrintf( SYS_VRB, "Model %s has %d surfaces\n", name, numSurfaces ); + for( s = 0; s < numSurfaces; s++ ) + { + /* get surface */ + surface = PicoGetModelSurface( model, s ); + if( surface == NULL ) + continue; + + /* only handle triangle surfaces initially (fixme: support patches) */ + if( PicoGetSurfaceType( surface ) != PICO_TRIANGLES ) + continue; + + /* allocate a surface (ydnar: gs mods) */ + ds = AllocDrawSurface( SURFACE_TRIANGLES ); + ds->entityNum = eNum; + ds->castShadows = castShadows; + ds->recvShadows = recvShadows; + + /* get shader name */ + shader = PicoGetSurfaceShader( surface ); + if( shader == NULL ) + picoShaderName = ""; + else + picoShaderName = PicoGetShaderName( shader ); + + /* handle .skin file */ + if(sf) + { + picoShaderName = NULL; + for(sf2 = sf; sf2 != NULL; sf2 = sf2->next) + { + if( !Q_stricmp( surface->name, sf2->name ) ) + { + Sys_FPrintf( SYS_VRB, "Skin file: mapping %s to %s\n", surface->name, sf2->to ); + picoShaderName = sf2->to; + break; + } + } + if(!picoShaderName) + { + Sys_FPrintf( SYS_VRB, "Skin file: not mapping %s\n", surface->name ); + continue; + } + } + + /* handle shader remapping */ + glob = NULL; + for( rm = remap; rm != NULL; rm = rm->next ) + { + if( rm->from[ 0 ] == '*' && rm->from[ 1 ] == '\0' ) + glob = rm; + else if( !Q_stricmp( picoShaderName, rm->from ) ) + { + Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", picoShaderName, rm->to ); + picoShaderName = rm->to; + glob = NULL; + break; + } + } + + if( glob != NULL ) + { + Sys_FPrintf( SYS_VRB, "Globbing %s to %s\n", picoShaderName, glob->to ); + picoShaderName = glob->to; + } + + /* shader renaming for sof2 */ + if( renameModelShaders ) + { + strcpy( shaderName, picoShaderName ); + StripExtension( shaderName ); + if( spawnFlags & 1 ) + strcat( shaderName, "_RMG_BSP" ); + else + strcat( shaderName, "_BSP" ); + si = ShaderInfoForShader( shaderName ); + } + else + si = ShaderInfoForShader( picoShaderName ); + + /* set shader */ + ds->shaderInfo = si; + + /* force to meta? */ + if( (si != NULL && si->forceMeta) || (spawnFlags & 4) ) /* 3rd bit */ + ds->type = SURFACE_FORCED_META; + + /* fix the surface's normals (jal: conditioned by shader info) */ + if( !(spawnFlags & 64) && ( shadeAngle == 0.0f || ds->type != SURFACE_FORCED_META ) ) + PicoFixSurfaceNormals( surface ); + + /* set sample size */ + if( lightmapSampleSize > 0.0f ) + ds->sampleSize = lightmapSampleSize; + + /* set lightmap scale */ + if( lightmapScale > 0.0f ) + ds->lightmapScale = lightmapScale; + + /* set shading angle */ + if( shadeAngle > 0.0f ) + ds->shadeAngleDegrees = shadeAngle; + + /* set particulars */ + ds->numVerts = PicoGetSurfaceNumVertexes( surface ); + ds->verts = safe_malloc( ds->numVerts * sizeof( ds->verts[ 0 ] ) ); + memset( ds->verts, 0, ds->numVerts * sizeof( ds->verts[ 0 ] ) ); + + ds->numIndexes = PicoGetSurfaceNumIndexes( surface ); + ds->indexes = safe_malloc( ds->numIndexes * sizeof( ds->indexes[ 0 ] ) ); + memset( ds->indexes, 0, ds->numIndexes * sizeof( ds->indexes[ 0 ] ) ); + + /* copy vertexes */ + for( i = 0; i < ds->numVerts; i++ ) + { + /* get vertex */ + dv = &ds->verts[ i ]; + + /* xyz and normal */ + xyz = PicoGetSurfaceXYZ( surface, i ); + VectorCopy( xyz, dv->xyz ); + m4x4_transform_point( transform, dv->xyz ); + + normal = PicoGetSurfaceNormal( surface, i ); + VectorCopy( normal, dv->normal ); + m4x4_transform_normal( nTransform, dv->normal ); + VectorNormalize( dv->normal, dv->normal ); + + /* ydnar: tek-fu celshading support for flat shaded shit */ + if( flat ) + { + dv->st[ 0 ] = si->stFlat[ 0 ]; + dv->st[ 1 ] = si->stFlat[ 1 ]; + } + + /* ydnar: gs mods: added support for explicit shader texcoord generation */ + else if( si->tcGen ) + { + /* project the texture */ + dv->st[ 0 ] = DotProduct( si->vecs[ 0 ], dv->xyz ); + dv->st[ 1 ] = DotProduct( si->vecs[ 1 ], dv->xyz ); + } + + /* normal texture coordinates */ + else + { + st = PicoGetSurfaceST( surface, 0, i ); + dv->st[ 0 ] = st[ 0 ]; + dv->st[ 1 ] = st[ 1 ]; + } + + /* set lightmap/color bits */ + color = PicoGetSurfaceColor( surface, 0, i ); + for( j = 0; j < MAX_LIGHTMAPS; j++ ) + { + dv->lightmap[ j ][ 0 ] = 0.0f; + dv->lightmap[ j ][ 1 ] = 0.0f; + if(spawnFlags & 32) // spawnflag 32: model color -> alpha hack + { + dv->color[ j ][ 0 ] = 255.0f; + dv->color[ j ][ 1 ] = 255.0f; + dv->color[ j ][ 2 ] = 255.0f; + dv->color[ j ][ 3 ] = RGBTOGRAY( color ); + } + else + { + dv->color[ j ][ 0 ] = color[ 0 ]; + dv->color[ j ][ 1 ] = color[ 1 ]; + dv->color[ j ][ 2 ] = color[ 2 ]; + dv->color[ j ][ 3 ] = color[ 3 ]; + } + } + } + + /* copy indexes */ + indexes = PicoGetSurfaceIndexes( surface, 0 ); + for( i = 0; i < ds->numIndexes; i++ ) + ds->indexes[ i ] = indexes[ i ]; + + /* set cel shader */ + ds->celShader = celShader; + + /* ydnar: giant hack land: generate clipping brushes for model triangles */ + if( si->clipModel || (spawnFlags & 2) ) /* 2nd bit */ + { + vec3_t points[ 4 ], backs[ 3 ]; + vec4_t plane, reverse, pa, pb, pc; + + + /* temp hack */ + if( !si->clipModel && !(si->compileFlags & C_SOLID) ) + continue; + + /* walk triangle list */ + for( i = 0; i < ds->numIndexes; i += 3 ) + { + /* overflow hack */ + AUTOEXPAND_BY_REALLOC(mapplanes, (nummapplanes+64) << 1, allocatedmapplanes, 1024); + + /* make points and back points */ + for( j = 0; j < 3; j++ ) + { + /* get vertex */ + dv = &ds->verts[ ds->indexes[ i + j ] ]; + + /* copy xyz */ + VectorCopy( dv->xyz, points[ j ] ); + } + + VectorCopy( points[0], points[3] ); // for cyclic usage + + /* make plane for triangle */ + // div0: add some extra spawnflags: + // 0: snap normals to axial planes for extrusion + // 8: extrude with the original normals + // 16: extrude only with up/down normals (ideal for terrain) + // 24: extrude by distance zero (may need engine changes) + if( PlaneFromPoints( plane, points[ 0 ], points[ 1 ], points[ 2 ] ) ) + { + vec3_t bestNormal; + float backPlaneDistance = 2; + + if(spawnFlags & 8) // use a DOWN normal + { + if(spawnFlags & 16) + { + // 24: normal as is, and zero width (broken) + VectorCopy(plane, bestNormal); + } + else + { + // 8: normal as is + VectorCopy(plane, bestNormal); + } + } + else + { + if(spawnFlags & 16) + { + // 16: UP/DOWN normal + VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1)); + } + else + { + // 0: axial normal + if(fabs(plane[0]) > fabs(plane[1])) // x>y + if(fabs(plane[1]) > fabs(plane[2])) // x>y, y>z + VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0); + else // x>y, z>=y + if(fabs(plane[0]) > fabs(plane[2])) // x>z, z>=y + VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0); + else // z>=x, x>y + VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1)); + else // y>=x + if(fabs(plane[1]) > fabs(plane[2])) // y>z, y>=x + VectorSet(bestNormal, 0, (plane[1] >= 0 ? 1 : -1), 0); + else // z>=y, y>=x + VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1)); + } + } + + /* build a brush */ + buildBrush = AllocBrush( 48 ); + buildBrush->entityNum = mapEntityNum; + buildBrush->original = buildBrush; + buildBrush->contentShader = si; + buildBrush->compileFlags = si->compileFlags; + buildBrush->contentFlags = si->contentFlags; + normalEpsilon_save = normalEpsilon; + distanceEpsilon_save = distanceEpsilon; + if(si->compileFlags & C_STRUCTURAL) // allow forced structural brushes here + { + buildBrush->detail = qfalse; + + // only allow EXACT matches when snapping for these (this is mostly for caulk brushes inside a model) + if(normalEpsilon > 0) + normalEpsilon = 0; + if(distanceEpsilon > 0) + distanceEpsilon = 0; + } + else + buildBrush->detail = qtrue; + + /* regenerate back points */ + for( j = 0; j < 3; j++ ) + { + /* get vertex */ + dv = &ds->verts[ ds->indexes[ i + j ] ]; + + // shift by some units + VectorMA(dv->xyz, -64.0f, bestNormal, backs[j]); // 64 prevents roundoff errors a bit + } + + /* make back plane */ + VectorScale( plane, -1.0f, reverse ); + reverse[ 3 ] = -plane[ 3 ]; + if((spawnFlags & 24) != 24) + reverse[3] += DotProduct(bestNormal, plane) * backPlaneDistance; + // that's at least sqrt(1/3) backPlaneDistance, unless in DOWN mode; in DOWN mode, we are screwed anyway if we encounter a plane that's perpendicular to the xy plane) + + if( PlaneFromPoints( pa, points[ 2 ], points[ 1 ], backs[ 1 ] ) && + PlaneFromPoints( pb, points[ 1 ], points[ 0 ], backs[ 0 ] ) && + PlaneFromPoints( pc, points[ 0 ], points[ 2 ], backs[ 2 ] ) ) + { + /* set up brush sides */ + buildBrush->numsides = 5; + buildBrush->sides[ 0 ].shaderInfo = si; + for( j = 1; j < buildBrush->numsides; j++ ) + buildBrush->sides[ j ].shaderInfo = NULL; // don't emit these faces as draw surfaces, should make smaller BSPs; hope this works + + buildBrush->sides[ 0 ].planenum = FindFloatPlane( plane, plane[ 3 ], 3, points ); + buildBrush->sides[ 1 ].planenum = FindFloatPlane( pa, pa[ 3 ], 2, &points[ 1 ] ); // pa contains points[1] and points[2] + buildBrush->sides[ 2 ].planenum = FindFloatPlane( pb, pb[ 3 ], 2, &points[ 0 ] ); // pb contains points[0] and points[1] + buildBrush->sides[ 3 ].planenum = FindFloatPlane( pc, pc[ 3 ], 2, &points[ 2 ] ); // pc contains points[2] and points[0] (copied to points[3] + buildBrush->sides[ 4 ].planenum = FindFloatPlane( reverse, reverse[ 3 ], 3, backs ); + } + else + { + free(buildBrush); + continue; + } + + normalEpsilon = normalEpsilon_save; + distanceEpsilon = distanceEpsilon_save; + + /* add to entity */ + if( CreateBrushWindings( buildBrush ) ) + { + AddBrushBevels(); + //% EmitBrushes( buildBrush, NULL, NULL ); + buildBrush->next = entities[ mapEntityNum ].brushes; + entities[ mapEntityNum ].brushes = buildBrush; + entities[ mapEntityNum ].numBrushes++; + } + else + free( buildBrush ); + } + } + } + } +} + + + +/* +AddTriangleModels() +adds misc_model surfaces to the bsp +*/ + +void AddTriangleModels( entity_t *e ) +{ + int num, frame, skin, castShadows, recvShadows, spawnFlags; + entity_t *e2; + const char *targetName; + const char *target, *model, *value; + char shader[ MAX_QPATH ]; + shaderInfo_t *celShader; + float temp, baseLightmapScale, lightmapScale; + float shadeAngle; + int lightmapSampleSize; + vec3_t origin, scale, angles; + m4x4_t transform; + epair_t *ep; + remap_t *remap, *remap2; + char *split; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- AddTriangleModels ---\n" ); + + /* get current brush entity targetname */ + if( e == entities ) + targetName = ""; + else + { + targetName = ValueForKey( e, "targetname" ); + + /* misc_model entities target non-worldspawn brush model entities */ + if( targetName[ 0 ] == '\0' ) + return; + } + + /* get lightmap scale */ + /* vortex: added _ls key (short name of lightmapscale) */ + baseLightmapScale = 0.0f; + if( strcmp( "", ValueForKey( e, "lightmapscale" ) ) || + strcmp( "", ValueForKey( e, "_lightmapscale" ) ) || + strcmp( "", ValueForKey( e, "_ls" ) ) ) + { + baseLightmapScale = FloatForKey( e, "lightmapscale" ); + if( baseLightmapScale <= 0.0f ) + baseLightmapScale = FloatForKey( e, "_lightmapscale" ); + if( baseLightmapScale <= 0.0f ) + baseLightmapScale = FloatForKey( e, "_ls" ); + if( baseLightmapScale < 0.0f ) + baseLightmapScale = 0.0f; + if( baseLightmapScale > 0.0f ) + Sys_Printf( "World Entity has lightmap scale of %.4f\n", baseLightmapScale ); + } + + + /* walk the entity list */ + for( num = 1; num < numEntities; num++ ) + { + /* get e2 */ + e2 = &entities[ num ]; + + /* convert misc_models into raw geometry */ + if( Q_stricmp( "misc_model", ValueForKey( e2, "classname" ) ) ) + continue; + + /* ydnar: added support for md3 models on non-worldspawn models */ + target = ValueForKey( e2, "target" ); + if( strcmp( target, targetName ) ) + continue; + + /* get model name */ + model = ValueForKey( e2, "model" ); + if( model[ 0 ] == '\0' ) + { + Sys_Printf( "WARNING: misc_model at %i %i %i without a model key\n", + (int) origin[ 0 ], (int) origin[ 1 ], (int) origin[ 2 ] ); + continue; + } + + /* get model frame */ + frame = IntForKey( e2, "_frame" ); + + /* worldspawn (and func_groups) default to cast/recv shadows in worldspawn group */ + if( e == entities ) + { + castShadows = WORLDSPAWN_CAST_SHADOWS; + recvShadows = WORLDSPAWN_RECV_SHADOWS; + } + + /* other entities don't cast any shadows, but recv worldspawn shadows */ + else + { + castShadows = ENTITY_CAST_SHADOWS; + recvShadows = ENTITY_RECV_SHADOWS; + } + + /* get explicit shadow flags */ + GetEntityShadowFlags( e2, e, &castShadows, &recvShadows ); + + /* get spawnflags */ + spawnFlags = IntForKey( e2, "spawnflags" ); + + /* get origin */ + GetVectorForKey( e2, "origin", origin ); + VectorSubtract( origin, e->origin, origin ); /* offset by parent */ + + /* get scale */ + scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = 1.0f; + temp = FloatForKey( e2, "modelscale" ); + if( temp != 0.0f ) + scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp; + value = ValueForKey( e2, "modelscale_vec" ); + if( value[ 0 ] != '\0' ) + sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] ); + + /* get "angle" (yaw) or "angles" (pitch yaw roll) */ + angles[ 0 ] = angles[ 1 ] = angles[ 2 ] = 0.0f; + angles[ 2 ] = FloatForKey( e2, "angle" ); + value = ValueForKey( e2, "angles" ); + if( value[ 0 ] != '\0' ) + sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ); + + /* set transform matrix (thanks spog) */ + m4x4_identity( transform ); + m4x4_pivoted_transform_by_vec3( transform, origin, angles, eXYZ, scale, vec3_origin ); + + /* get shader remappings */ + remap = NULL; + for( ep = e2->epairs; ep != NULL; ep = ep->next ) + { + /* look for keys prefixed with "_remap" */ + if( ep->key != NULL && ep->value != NULL && + ep->key[ 0 ] != '\0' && ep->value[ 0 ] != '\0' && + !Q_strncasecmp( ep->key, "_remap", 6 ) ) + { + /* create new remapping */ + remap2 = remap; + remap = safe_malloc( sizeof( *remap ) ); + remap->next = remap2; + strcpy( remap->from, ep->value ); + + /* split the string */ + split = strchr( remap->from, ';' ); + if( split == NULL ) + { + Sys_Printf( "WARNING: Shader _remap key found in misc_model without a ; character\n" ); + free( remap ); + remap = remap2; + continue; + } + + /* store the split */ + *split = '\0'; + strcpy( remap->to, (split + 1) ); + + /* note it */ + //% Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", remap->from, remap->to ); + } + } + + /* ydnar: cel shader support */ + value = ValueForKey( e2, "_celshader" ); + if( value[ 0 ] == '\0' ) + value = ValueForKey( &entities[ 0 ], "_celshader" ); + if( value[ 0 ] != '\0' ) + { + sprintf( shader, "textures/%s", value ); + celShader = ShaderInfoForShader( shader ); + } + else + celShader = *globalCelShader ? ShaderInfoForShader(globalCelShader) : NULL; + + /* jal : entity based _samplesize */ + lightmapSampleSize = 0; + if ( strcmp( "", ValueForKey( e2, "_lightmapsamplesize" ) ) ) + lightmapSampleSize = IntForKey( e2, "_lightmapsamplesize" ); + else if ( strcmp( "", ValueForKey( e2, "_samplesize" ) ) ) + lightmapSampleSize = IntForKey( e2, "_samplesize" ); + + if( lightmapSampleSize < 0 ) + lightmapSampleSize = 0; + + if( lightmapSampleSize > 0.0f ) + Sys_Printf( "misc_model has lightmap sample size of %.d\n", lightmapSampleSize ); + + /* get lightmap scale */ + /* vortex: added _ls key (short name of lightmapscale) */ + lightmapScale = 0.0f; + if( strcmp( "", ValueForKey( e2, "lightmapscale" ) ) || + strcmp( "", ValueForKey( e2, "_lightmapscale" ) ) || + strcmp( "", ValueForKey( e2, "_ls" ) ) ) + { + lightmapScale = FloatForKey( e2, "lightmapscale" ); + if( lightmapScale <= 0.0f ) + lightmapScale = FloatForKey( e2, "_lightmapscale" ); + if( lightmapScale <= 0.0f ) + lightmapScale = FloatForKey( e2, "_ls" ); + if( lightmapScale < 0.0f ) + lightmapScale = 0.0f; + if( lightmapScale > 0.0f ) + Sys_Printf( "misc_model has lightmap scale of %.4f\n", lightmapScale ); + } + + /* jal : entity based _shadeangle */ + shadeAngle = 0.0f; + if ( strcmp( "", ValueForKey( e2, "_shadeangle" ) ) ) + shadeAngle = FloatForKey( e2, "_shadeangle" ); + /* vortex' aliases */ + else if ( strcmp( "", ValueForKey( e2, "_smoothnormals" ) ) ) + shadeAngle = FloatForKey( e2, "_smoothnormals" ); + else if ( strcmp( "", ValueForKey( e2, "_sn" ) ) ) + shadeAngle = FloatForKey( e2, "_sn" ); + else if ( strcmp( "", ValueForKey( e2, "_smooth" ) ) ) + shadeAngle = FloatForKey( e2, "_smooth" ); + + if( shadeAngle < 0.0f ) + shadeAngle = 0.0f; + + if( shadeAngle > 0.0f ) + Sys_Printf( "misc_model has shading angle of %.4f\n", shadeAngle ); + + skin = IntForKey(e2, "skin"); + + /* insert the model */ + InsertModel( model, skin, frame, transform, remap, celShader, mapEntityNum, castShadows, recvShadows, spawnFlags, lightmapScale, lightmapSampleSize, shadeAngle ); + + /* free shader remappings */ + while( remap != NULL ) + { + remap2 = remap->next; + free( remap ); + remap = remap2; + } + } +} diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/patch.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/patch.c new file mode 100644 index 00000000..9cd707e2 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/patch.c @@ -0,0 +1,524 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define PATCH_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +ExpandLongestCurve() - ydnar +finds length of quadratic curve specified and determines if length is longer than the supplied max +*/ + +#define APPROX_SUBDIVISION 8 + +static void ExpandLongestCurve( float *longestCurve, vec3_t a, vec3_t b, vec3_t c ) +{ + int i; + float t, len; + vec3_t ab, bc, ac, pt, last, delta; + + + /* calc vectors */ + VectorSubtract( b, a, ab ); + if( VectorNormalize( ab, ab ) < 0.125f ) + return; + VectorSubtract( c, b, bc ); + if( VectorNormalize( bc, bc ) < 0.125f ) + return; + VectorSubtract( c, a, ac ); + if( VectorNormalize( ac, ac ) < 0.125f ) + return; + + /* if all 3 vectors are the same direction, then this edge is linear, so we ignore it */ + if( DotProduct( ab, bc ) > 0.99f && DotProduct( ab, ac ) > 0.99f ) + return; + + /* recalculate vectors */ + VectorSubtract( b, a, ab ); + VectorSubtract( c, b, bc ); + + /* determine length */ + VectorCopy( a, last ); + for( i = 0, len = 0.0f, t = 0.0f; i < APPROX_SUBDIVISION; i++, t += (1.0f / APPROX_SUBDIVISION) ) + { + /* calculate delta */ + delta[ 0 ] = ((1.0f - t) * ab[ 0 ]) + (t * bc[ 0 ]); + delta[ 1 ] = ((1.0f - t) * ab[ 1 ]) + (t * bc[ 1 ]); + delta[ 2 ] = ((1.0f - t) * ab[ 2 ]) + (t * bc[ 2 ]); + + /* add to first point and calculate pt-pt delta */ + VectorAdd( a, delta, pt ); + VectorSubtract( pt, last, delta ); + + /* add it to length and store last point */ + len += VectorLength( delta ); + VectorCopy( pt, last ); + } + + /* longer? */ + if( len > *longestCurve ) + *longestCurve = len; +} + + + +/* +ExpandMaxIterations() - ydnar +determines how many iterations a quadratic curve needs to be subdivided with to fit the specified error +*/ + +static void ExpandMaxIterations( int *maxIterations, int maxError, vec3_t a, vec3_t b, vec3_t c ) +{ + int i, j; + vec3_t prev, next, mid, delta, delta2; + float len, len2; + int numPoints, iterations; + vec3_t points[ MAX_EXPANDED_AXIS ]; + + + /* initial setup */ + numPoints = 3; + VectorCopy( a, points[ 0 ] ); + VectorCopy( b, points[ 1 ] ); + VectorCopy( c, points[ 2 ] ); + + /* subdivide */ + for( i = 0; i + 2 < numPoints; i += 2 ) + { + /* check subdivision limit */ + if( numPoints + 2 >= MAX_EXPANDED_AXIS ) + break; + + /* calculate new curve deltas */ + for( j = 0; j < 3; j++ ) + { + prev[ j ] = points[ i + 1 ][ j ] - points[ i ][ j ]; + next[ j ] = points[ i + 2 ][ j ] - points[ i + 1 ][ j ]; + mid[ j ] = (points[ i ][ j ] + points[ i + 1 ][ j ] * 2.0f + points[ i + 2 ][ j ]) * 0.25f; + } + + /* see if this midpoint is off far enough to subdivide */ + VectorSubtract( points[ i + 1 ], mid, delta ); + len = VectorLength( delta ); + if( len < maxError ) + continue; + + /* subdivide */ + numPoints += 2; + + /* create new points */ + for( j = 0; j < 3; j++ ) + { + prev[ j ] = 0.5f * (points[ i ][ j ] + points[ i + 1 ][ j ]); + next[ j ] = 0.5f * (points[ i + 1 ][ j ] + points[ i + 2 ][ j ]); + mid[ j ] = 0.5f * (prev[ j ] + next[ j ]); + } + + /* push points out */ + for( j = numPoints - 1; j > i + 3; j-- ) + VectorCopy( points[ j - 2 ], points[ j ] ); + + /* insert new points */ + VectorCopy( prev, points[ i + 1 ] ); + VectorCopy( mid, points[ i + 2 ] ); + VectorCopy( next, points[ i + 3 ] ); + + /* back up and recheck this set again, it may need more subdivision */ + i -= 2; + } + + /* put the line on the curve */ + for( i = 1; i < numPoints; i += 2 ) + { + for( j = 0; j < 3; j++ ) + { + prev[ j ] = 0.5f * (points[ i ][ j ] + points[ i + 1 ][ j ] ); + next[ j ] = 0.5f * (points[ i ][ j ] + points[ i - 1 ][ j ] ); + points[ i ][ j ] = 0.5f * (prev[ j ] + next[ j ]); + } + } + + /* eliminate linear sections */ + for( i = 0; i + 2 < numPoints; i++ ) + { + /* create vectors */ + VectorSubtract( points[ i + 1 ], points[ i ], delta ); + len = VectorNormalize( delta, delta ); + VectorSubtract( points[ i + 2 ], points[ i + 1 ], delta2 ); + len2 = VectorNormalize( delta2, delta2 ); + + /* if either edge is degenerate, then eliminate it */ + if( len < 0.0625f || len2 < 0.0625f || DotProduct( delta, delta2 ) >= 1.0f ) + { + for( j = i + 1; j + 1 < numPoints; j++ ) + VectorCopy( points[ j + 1 ], points[ j ] ); + numPoints--; + continue; + } + } + + /* the number of iterations is 2^(points - 1) - 1 */ + numPoints >>= 1; + iterations = 0; + while( numPoints > 1 ) + { + numPoints >>= 1; + iterations++; + } + + /* more? */ + if( iterations > *maxIterations ) + *maxIterations = iterations; +} + + + +/* +ParsePatch() +creates a mapDrawSurface_t from the patch text +*/ + +void ParsePatch( qboolean onlyLights ) +{ + vec_t info[ 5 ]; + int i, j, k; + parseMesh_t *pm; + char texture[ MAX_QPATH ]; + char shader[ MAX_QPATH ]; + mesh_t m; + bspDrawVert_t *verts; + epair_t *ep; + vec4_t delta, delta2, delta3; + qboolean degenerate; + float longestCurve; + int maxIterations; + + MatchToken( "{" ); + + /* get texture */ + GetToken( qtrue ); + strcpy( texture, token ); + + Parse1DMatrix( 5, info ); + m.width = info[0]; + m.height = info[1]; + m.verts = verts = safe_malloc( m.width * m.height * sizeof( m.verts[0] ) ); + + if( m.width < 0 || m.width > MAX_PATCH_SIZE || m.height < 0 || m.height > MAX_PATCH_SIZE ) + Error( "ParsePatch: bad size" ); + + MatchToken( "(" ); + for( j = 0; j < m.width ; j++ ) + { + MatchToken( "(" ); + for( i = 0; i < m.height ; i++ ) + { + Parse1DMatrix( 5, verts[ i * m.width + j ].xyz ); + + /* ydnar: fix colors */ + for( k = 0; k < MAX_LIGHTMAPS; k++ ) + { + verts[ i * m.width + j ].color[ k ][ 0 ] = 255; + verts[ i * m.width + j ].color[ k ][ 1 ] = 255; + verts[ i * m.width + j ].color[ k ][ 2 ] = 255; + verts[ i * m.width + j ].color[ k ][ 3 ] = 255; + } + } + MatchToken( ")" ); + } + MatchToken( ")" ); + + // if brush primitives format, we may have some epairs to ignore here + GetToken(qtrue); + if (g_bBrushPrimit!=BPRIMIT_OLDBRUSHES && strcmp(token,"}")) + { + // NOTE: we leak that! + ep = ParseEPair(); + } + else + UnGetToken(); + + MatchToken( "}" ); + MatchToken( "}" ); + + /* short circuit */ + if( noCurveBrushes || onlyLights ) + return; + + + /* ydnar: delete and warn about degenerate patches */ + j = (m.width * m.height); + VectorClear( delta ); + delta[ 3 ] = 0; + degenerate = qtrue; + + /* find first valid vector */ + for( i = 1; i < j && delta[ 3 ] == 0; i++ ) + { + VectorSubtract( m.verts[ 0 ].xyz, m.verts[ i ].xyz, delta ); + delta[ 3 ] = VectorNormalize( delta, delta ); + } + + /* secondary degenerate test */ + if( delta[ 3 ] == 0 ) + degenerate = qtrue; + else + { + /* if all vectors match this or are zero, then this is a degenerate patch */ + for( i = 1; i < j && degenerate == qtrue; i++ ) + { + VectorSubtract( m.verts[ 0 ].xyz, m.verts[ i ].xyz, delta2 ); + delta2[ 3 ] = VectorNormalize( delta2, delta2 ); + if( delta2[ 3 ] != 0 ) + { + /* create inverse vector */ + VectorCopy( delta2, delta3 ); + delta3[ 3 ] = delta2[ 3 ]; + VectorInverse( delta3 ); + + /* compare */ + if( VectorCompare( delta, delta2 ) == qfalse && VectorCompare( delta, delta3 ) == qfalse ) + degenerate = qfalse; + } + } + } + + /* warn and select degenerate patch */ + if( degenerate ) + { + xml_Select( "degenerate patch", mapEnt->mapEntityNum, entitySourceBrushes, qfalse ); + free( m.verts ); + return; + } + + /* find longest curve on the mesh */ + longestCurve = 0.0f; + maxIterations = 0; + for( j = 0; j + 2 < m.width; j += 2 ) + { + for( i = 0; i + 2 < m.height; i += 2 ) + { + ExpandLongestCurve( &longestCurve, verts[ i * m.width + j ].xyz, verts[ i * m.width + (j + 1) ].xyz, verts[ i * m.width + (j + 2) ].xyz ); /* row */ + ExpandLongestCurve( &longestCurve, verts[ i * m.width + j ].xyz, verts[ (i + 1) * m.width + j ].xyz, verts[ (i + 2) * m.width + j ].xyz ); /* col */ + ExpandMaxIterations( &maxIterations, patchSubdivisions, verts[ i * m.width + j ].xyz, verts[ i * m.width + (j + 1) ].xyz, verts[ i * m.width + (j + 2) ].xyz ); /* row */ + ExpandMaxIterations( &maxIterations, patchSubdivisions, verts[ i * m.width + j ].xyz, verts[ (i + 1) * m.width + j ].xyz, verts[ (i + 2) * m.width + j ].xyz ); /* col */ + } + } + + /* allocate patch mesh */ + pm = safe_malloc( sizeof( *pm ) ); + memset( pm, 0, sizeof( *pm ) ); + + /* ydnar: add entity/brush numbering */ + pm->entityNum = mapEnt->mapEntityNum; + pm->brushNum = entitySourceBrushes; + + /* set shader */ + sprintf( shader, "textures/%s", texture ); + pm->shaderInfo = ShaderInfoForShader( shader ); + + /* set mesh */ + pm->mesh = m; + + /* set longest curve */ + pm->longestCurve = longestCurve; + pm->maxIterations = maxIterations; + + /* link to the entity */ + pm->next = mapEnt->patches; + mapEnt->patches = pm; +} + + + +/* +GrowGroup_r() +recursively adds patches to a lod group +*/ + +static void GrowGroup_r( parseMesh_t *pm, int patchNum, int patchCount, parseMesh_t **meshes, byte *bordering, byte *group ) +{ + int i; + const byte *row; + + + /* early out check */ + if( group[ patchNum ] ) + return; + + + /* set it */ + group[ patchNum ] = 1; + row = bordering + patchNum * patchCount; + + /* check maximums */ + if( meshes[ patchNum ]->longestCurve > pm->longestCurve ) + pm->longestCurve = meshes[ patchNum ]->longestCurve; + if( meshes[ patchNum ]->maxIterations > pm->maxIterations ) + pm->maxIterations = meshes[ patchNum ]->maxIterations; + + /* walk other patches */ + for( i = 0; i < patchCount; i++ ) + { + if( row[ i ] ) + GrowGroup_r( pm, i, patchCount, meshes, bordering, group ); + } +} + + +/* +PatchMapDrawSurfs() +any patches that share an edge need to choose their +level of detail as a unit, otherwise the edges would +pull apart. +*/ + +void PatchMapDrawSurfs( entity_t *e ) +{ + int i, j, k, l, c1, c2; + parseMesh_t *pm; + parseMesh_t *check, *scan; + mapDrawSurface_t *ds; + int patchCount, groupCount; + bspDrawVert_t *v1, *v2; + vec3_t bounds[ 2 ]; + byte *bordering; + + /* ydnar: mac os x fails with these if not static */ + MAC_STATIC parseMesh_t *meshes[ MAX_MAP_DRAW_SURFS ]; + MAC_STATIC qb_t grouped[ MAX_MAP_DRAW_SURFS ]; + MAC_STATIC byte group[ MAX_MAP_DRAW_SURFS ]; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- PatchMapDrawSurfs ---\n" ); + + patchCount = 0; + for ( pm = e->patches ; pm ; pm = pm->next ) { + meshes[patchCount] = pm; + patchCount++; + } + + if ( !patchCount ) { + return; + } + bordering = safe_malloc( patchCount * patchCount ); + memset( bordering, 0, patchCount * patchCount ); + + // build the bordering matrix + for ( k = 0 ; k < patchCount ; k++ ) { + bordering[k*patchCount+k] = 1; + + for ( l = k+1 ; l < patchCount ; l++ ) { + check = meshes[k]; + scan = meshes[l]; + c1 = scan->mesh.width * scan->mesh.height; + v1 = scan->mesh.verts; + + for ( i = 0 ; i < c1 ; i++, v1++ ) { + c2 = check->mesh.width * check->mesh.height; + v2 = check->mesh.verts; + for ( j = 0 ; j < c2 ; j++, v2++ ) { + if ( fabs( v1->xyz[0] - v2->xyz[0] ) < 1.0 + && fabs( v1->xyz[1] - v2->xyz[1] ) < 1.0 + && fabs( v1->xyz[2] - v2->xyz[2] ) < 1.0 ) { + break; + } + } + if ( j != c2 ) { + break; + } + } + if ( i != c1 ) { + // we have a connection + bordering[k*patchCount+l] = + bordering[l*patchCount+k] = 1; + } else { + // no connection + bordering[k*patchCount+l] = + bordering[l*patchCount+k] = 0; + } + + } + } + + /* build groups */ + memset( grouped, 0, patchCount ); + groupCount = 0; + for ( i = 0; i < patchCount; i++ ) + { + /* get patch */ + scan = meshes[ i ]; + + /* start a new group */ + if( !grouped[ i ] ) + groupCount++; + + /* recursively find all patches that belong in the same group */ + memset( group, 0, patchCount ); + GrowGroup_r( scan, i, patchCount, meshes, bordering, group ); + + /* bound them */ + ClearBounds( bounds[ 0 ], bounds[ 1 ] ); + for( j = 0; j < patchCount; j++ ) + { + if ( group[ j ] ) + { + grouped[ j ] = qtrue; + check = meshes[ j ]; + c1 = check->mesh.width * check->mesh.height; + v1 = check->mesh.verts; + for( k = 0; k < c1; k++, v1++ ) + AddPointToBounds( v1->xyz, bounds[ 0 ], bounds[ 1 ] ); + } + } + + /* debug code */ + //% Sys_Printf( "Longest curve: %f Iterations: %d\n", scan->longestCurve, scan->maxIterations ); + + /* create drawsurf */ + scan->grouped = qtrue; + ds = DrawSurfaceForMesh( e, scan, NULL ); /* ydnar */ + VectorCopy( bounds[ 0 ], ds->bounds[ 0 ] ); + VectorCopy( bounds[ 1 ], ds->bounds[ 1 ] ); + } + + /* emit some statistics */ + Sys_FPrintf( SYS_VRB, "%9d patches\n", patchCount ); + Sys_FPrintf( SYS_VRB, "%9d patch LOD groups\n", groupCount ); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/path_init.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/path_init.c new file mode 100644 index 00000000..83383e22 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/path_init.c @@ -0,0 +1,507 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define PATH_INIT_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* path support */ +#define MAX_BASE_PATHS 10 +#define MAX_GAME_PATHS 10 + +char *homePath; +char installPath[ MAX_OS_PATH ]; + +int numBasePaths; +char *basePaths[ MAX_BASE_PATHS ]; +int numGamePaths; +char *gamePaths[ MAX_GAME_PATHS ]; +char *homeBasePath = NULL; + + +/* +some of this code is based off the original q3map port from loki +and finds various paths. moved here from bsp.c for clarity. +*/ + +/* +PathLokiGetHomeDir() +gets the user's home dir (for ~/.q3a) +*/ + +char *LokiGetHomeDir( void ) +{ + #ifndef Q_UNIX + return NULL; + #else + char *home; + uid_t id; + struct passwd *pwd; + + + /* get the home environment variable */ + home = getenv( "HOME" ); + if( home == NULL ) + { + /* do some more digging */ + id = getuid(); + setpwent(); + while( (pwd = getpwent()) != NULL ) + { + if( pwd->pw_uid == id ) + { + home = pwd->pw_dir; + break; + } + } + endpwent(); + } + + /* return it */ + return home; + #endif +} + + + +/* +PathLokiInitPaths() +initializes some paths on linux/os x +*/ + +void LokiInitPaths( char *argv0 ) +{ + #ifndef Q_UNIX + /* this is kinda crap, but hey */ + strcpy( installPath, "../" ); + #else + char temp[ MAX_OS_PATH ]; + char last0[ 2 ]; + char *home; + char *path; + char *last; + qboolean found; + + + /* get home dir */ + home = LokiGetHomeDir(); + if( home == NULL ) + home = "."; + + /* do some path divining */ + strcpy( temp, argv0 ); + if( strrchr( argv0, '/' ) ) + argv0 = strrchr( argv0, '/' ) + 1; + else + { + /* get path environment variable */ + path = getenv( "PATH" ); + + /* minor setup */ + last = last0; + last[ 0 ] = path[ 0 ]; + last[ 1 ] = '\0'; + found = qfalse; + + /* go through each : segment of path */ + while( last[ 0 ] != '\0' && found == qfalse ) + { + /* null out temp */ + temp[ 0 ] = '\0'; + + /* find next chunk */ + last = strchr( path, ':' ); + if( last == NULL ) + last = path + strlen( path ); + + /* found home dir candidate */ + if( *path == '~' ) + { + strcpy( temp, home ); + path++; + } + + /* concatenate */ + if( last > (path + 1) ) + { + strncat( temp, path, (last - path) ); + strcat( temp, "/" ); + } + strcat( temp, "./" ); + strcat( temp, argv0 ); + + /* verify the path */ + if( access( temp, X_OK ) == 0 ) + found++; + path = last + 1; + } + } + + /* flake */ + if( realpath( temp, installPath ) ) + { + /* q3map is in "tools/" */ + *(strrchr( installPath, '/' )) = '\0'; + *(strrchr( installPath, '/' ) + 1) = '\0'; + } + + /* set home path */ + homePath = home; + #endif +} + + + +/* +CleanPath() - ydnar +cleans a dos path \ -> / +*/ + +void CleanPath( char *path ) +{ + while( *path ) + { + if( *path == '\\' ) + *path = '/'; + path++; + } +} + + + +/* +GetGame() - ydnar +gets the game_t based on a -game argument +returns NULL if no match found +*/ + +game_t *GetGame( char *arg ) +{ + int i; + + + /* dummy check */ + if( arg == NULL || arg[ 0 ] == '\0' ) + return NULL; + + /* joke */ + if( !Q_stricmp( arg, "quake1" ) || + !Q_stricmp( arg, "quake2" ) || + !Q_stricmp( arg, "unreal" ) || + !Q_stricmp( arg, "ut2k3" ) || + !Q_stricmp( arg, "dn3d" ) || + !Q_stricmp( arg, "dnf" ) || + !Q_stricmp( arg, "hl" ) ) + { + Sys_Printf( "April fools, silly rabbit!\n" ); + exit( 0 ); + } + + /* test it */ + i = 0; + while( games[ i ].arg != NULL ) + { + if( Q_stricmp( arg, games[ i ].arg ) == 0 ) + return &games[ i ]; + i++; + } + + /* no matching game */ + return NULL; +} + + + +/* +AddBasePath() - ydnar +adds a base path to the list +*/ + +void AddBasePath( char *path ) +{ + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' || numBasePaths >= MAX_BASE_PATHS ) + return; + + /* add it to the list */ + basePaths[ numBasePaths ] = safe_malloc( strlen( path ) + 1 ); + strcpy( basePaths[ numBasePaths ], path ); + CleanPath( basePaths[ numBasePaths ] ); + numBasePaths++; +} + + + +/* +AddHomeBasePath() - ydnar +adds a base path to the beginning of the list, prefixed by ~/ +*/ + +void AddHomeBasePath( char *path ) +{ + #ifdef Q_UNIX + int i; + char temp[ MAX_OS_PATH ]; + + + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' ) + return; + + /* make a hole */ + for( i = (MAX_BASE_PATHS - 2); i >= 0; i-- ) + basePaths[ i + 1 ] = basePaths[ i ]; + + /* concatenate home dir and path */ + sprintf( temp, "%s/%s", homePath, path ); + + /* add it to the list */ + basePaths[ 0 ] = safe_malloc( strlen( temp ) + 1 ); + strcpy( basePaths[ 0 ], temp ); + CleanPath( basePaths[ 0 ] ); + numBasePaths++; + #endif +} + + + +/* +AddGamePath() - ydnar +adds a game path to the list +*/ + +void AddGamePath( char *path ) +{ + int i; + + /* dummy check */ + if( path == NULL || path[ 0 ] == '\0' || numGamePaths >= MAX_GAME_PATHS ) + return; + + /* add it to the list */ + gamePaths[ numGamePaths ] = safe_malloc( strlen( path ) + 1 ); + strcpy( gamePaths[ numGamePaths ], path ); + CleanPath( gamePaths[ numGamePaths ] ); + numGamePaths++; + + /* don't add it if it's already there */ + for (i = 0; i < numGamePaths - 1; i++) + { + if (strcmp(gamePaths[i], gamePaths[numGamePaths - 1]) == 0) + { + free(gamePaths[numGamePaths - 1]); + gamePaths[numGamePaths - 1] = NULL; + numGamePaths--; + break; + } + } + +} + + + + +/* +InitPaths() - ydnar +cleaned up some of the path initialization code from bsp.c +will remove any arguments it uses +*/ + +void InitPaths( int *argc, char **argv ) +{ + int i, j, k, len, len2; + char temp[ MAX_OS_PATH ]; + + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- InitPaths ---\n" ); + + /* get the install path for backup */ + LokiInitPaths( argv[ 0 ] ); + + /* set game to default (q3a) */ + game = &games[ 0 ]; + numBasePaths = 0; + numGamePaths = 0; + + /* parse through the arguments and extract those relevant to paths */ + for( i = 0; i < *argc; i++ ) + { + /* check for null */ + if( argv[ i ] == NULL ) + continue; + + /* -game */ + if( strcmp( argv[ i ], "-game" ) == 0 ) + { + if( ++i >= *argc ) + Error( "Out of arguments: No game specified after %s", argv[ i - 1 ] ); + argv[ i - 1 ] = NULL; + game = GetGame( argv[ i ] ); + if( game == NULL ) + game = &games[ 0 ]; + argv[ i ] = NULL; + } + + /* -fs_forbiddenpath */ + else if( strcmp( argv[ i ], "-fs_forbiddenpath" ) == 0 ) + { + if( ++i >= *argc ) + Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); + argv[ i - 1 ] = NULL; + if(g_numForbiddenDirs < VFS_MAXDIRS) + { + strncpy(g_strForbiddenDirs[g_numForbiddenDirs], argv[i], PATH_MAX); + g_strForbiddenDirs[g_numForbiddenDirs][PATH_MAX] = 0; + ++g_numForbiddenDirs; + } + argv[ i ] = NULL; + } + + /* -fs_basepath */ + else if( strcmp( argv[ i ], "-fs_basepath" ) == 0 ) + { + if( ++i >= *argc ) + Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); + argv[ i - 1 ] = NULL; + AddBasePath( argv[ i ] ); + argv[ i ] = NULL; + } + + /* -fs_game */ + else if( strcmp( argv[ i ], "-fs_game" ) == 0 ) + { + if( ++i >= *argc ) + Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); + argv[ i - 1 ] = NULL; + AddGamePath( argv[ i ] ); + argv[ i ] = NULL; + } + + /* -fs_nohomebase */ + else if( strcmp( argv[ i ], "-fs_homebase" ) == 0 ) + { + if( ++i >= *argc ) + Error( "Out of arguments: No path specified after %s.", argv[ i - 1 ] ); + argv[ i - 1 ] = NULL; + homeBasePath = argv[i]; + argv[ i ] = NULL; + } + } + + /* remove processed arguments */ + for( i = 0, j = 0, k = 0; i < *argc && j < *argc; i++, j++ ) + { + for( ; j < *argc && argv[ j ] == NULL; j++ ); + argv[ i ] = argv[ j ]; + if( argv[ i ] != NULL ) + k++; + } + *argc = k; + + /* add standard game path */ + AddGamePath( game->gamePath ); + + /* if there is no base path set, figure it out */ + if( numBasePaths == 0 ) + { + /* this is another crappy replacement for SetQdirFromPath() */ + len2 = strlen( game->magic ); + for( i = 0; i < *argc && numBasePaths == 0; i++ ) + { + /* extract the arg */ + strcpy( temp, argv[ i ] ); + CleanPath( temp ); + len = strlen( temp ); + Sys_FPrintf( SYS_VRB, "Searching for \"%s\" in \"%s\" (%d)...\n", game->magic, temp, i ); + + /* this is slow, but only done once */ + for( j = 0; j < (len - len2); j++ ) + { + /* check for the game's magic word */ + if( Q_strncasecmp( &temp[ j ], game->magic, len2 ) == 0 ) + { + /* now find the next slash and nuke everything after it */ + while( temp[ ++j ] != '/' && temp[ j ] != '\0' ); + temp[ j ] = '\0'; + + /* add this as a base path */ + AddBasePath( temp ); + break; + } + } + } + + /* add install path */ + if( numBasePaths == 0 ) + AddBasePath( installPath ); + + /* check again */ + if( numBasePaths == 0 ) + Error( "Failed to find a valid base path." ); + } + + /* this only affects unix */ + if(homeBasePath) + AddHomeBasePath( homeBasePath ); + else + AddHomeBasePath( game->homeBasePath ); + + /* initialize vfs paths */ + if( numBasePaths > MAX_BASE_PATHS ) + numBasePaths = MAX_BASE_PATHS; + if( numGamePaths > MAX_GAME_PATHS ) + numGamePaths = MAX_GAME_PATHS; + + /* walk the list of game paths */ + for( j = 0; j < numGamePaths; j++ ) + { + /* walk the list of base paths */ + for( i = 0; i < numBasePaths; i++ ) + { + /* create a full path and initialize it */ + sprintf( temp, "%s/%s/", basePaths[ i ], gamePaths[ j ] ); + vfsInitDirectory( temp ); + } + } + + /* done */ + Sys_Printf( "\n" ); +} + + + + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/portals.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/portals.c new file mode 100644 index 00000000..2efc1db4 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/portals.c @@ -0,0 +1,981 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define PORTALS_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* ydnar: to fix broken portal windings */ +extern qboolean FixWinding( winding_t *w ); + + +int c_active_portals; +int c_peak_portals; +int c_boundary; +int c_boundary_sides; + +/* +=========== +AllocPortal +=========== +*/ +portal_t *AllocPortal (void) +{ + portal_t *p; + + if (numthreads == 1) + c_active_portals++; + if (c_active_portals > c_peak_portals) + c_peak_portals = c_active_portals; + + p = safe_malloc (sizeof(portal_t)); + memset (p, 0, sizeof(portal_t)); + + return p; +} + +void FreePortal (portal_t *p) +{ + if (p->winding) + FreeWinding (p->winding); + if (numthreads == 1) + c_active_portals--; + free (p); +} + + + +/* +PortalPassable +returns true if the portal has non-opaque leafs on both sides +*/ + +qboolean PortalPassable( portal_t *p ) +{ + /* is this to global outside leaf? */ + if( !p->onnode ) + return qfalse; + + /* this should never happen */ + if( p->nodes[ 0 ]->planenum != PLANENUM_LEAF || + p->nodes[ 1 ]->planenum != PLANENUM_LEAF ) + Error( "Portal_EntityFlood: not a leaf" ); + + /* ydnar: added antiportal to supress portal generation for visibility blocking */ + if( p->compileFlags & C_ANTIPORTAL ) + return qfalse; + + /* both leaves on either side of the portal must be passable */ + if( p->nodes[ 0 ]->opaque == qfalse && p->nodes[ 1 ]->opaque == qfalse ) + return qtrue; + + /* otherwise this isn't a passable portal */ + return qfalse; +} + + + + +int c_tinyportals; +int c_badportals; /* ydnar */ + +/* +============= +AddPortalToNodes +============= +*/ +void AddPortalToNodes (portal_t *p, node_t *front, node_t *back) +{ + if (p->nodes[0] || p->nodes[1]) + Error ("AddPortalToNode: allready included"); + + p->nodes[0] = front; + p->next[0] = front->portals; + front->portals = p; + + p->nodes[1] = back; + p->next[1] = back->portals; + back->portals = p; +} + + +/* +============= +RemovePortalFromNode +============= +*/ +void RemovePortalFromNode (portal_t *portal, node_t *l) +{ + portal_t **pp, *t; + +// remove reference to the current portal + pp = &l->portals; + while (1) + { + t = *pp; + if (!t) + Error ("RemovePortalFromNode: portal not in leaf"); + + if ( t == portal ) + break; + + if (t->nodes[0] == l) + pp = &t->next[0]; + else if (t->nodes[1] == l) + pp = &t->next[1]; + else + Error ("RemovePortalFromNode: portal not bounding leaf"); + } + + if (portal->nodes[0] == l) + { + *pp = portal->next[0]; + portal->nodes[0] = NULL; + } + else if (portal->nodes[1] == l) + { + *pp = portal->next[1]; + portal->nodes[1] = NULL; + } +} + +//============================================================================ + +void PrintPortal (portal_t *p) +{ + int i; + winding_t *w; + + w = p->winding; + for (i=0 ; inumpoints ; i++) + Sys_Printf ("(%5.0f,%5.0f,%5.0f)\n",w->p[i][0] + , w->p[i][1], w->p[i][2]); +} + +/* +================ +MakeHeadnodePortals + +The created portals will face the global outside_node +================ +*/ +#define SIDESPACE 8 +void MakeHeadnodePortals (tree_t *tree) +{ + vec3_t bounds[2]; + int i, j, n; + portal_t *p, *portals[6]; + plane_t bplanes[6], *pl; + node_t *node; + + node = tree->headnode; + +// pad with some space so there will never be null volume leafs + for (i=0 ; i<3 ; i++) + { + bounds[0][i] = tree->mins[i] - SIDESPACE; + bounds[1][i] = tree->maxs[i] + SIDESPACE; + if ( bounds[0][i] >= bounds[1][i] ) { + Error( "Backwards tree volume" ); + } + } + + tree->outside_node.planenum = PLANENUM_LEAF; + tree->outside_node.brushlist = NULL; + tree->outside_node.portals = NULL; + tree->outside_node.opaque = qfalse; + + for (i=0 ; i<3 ; i++) + for (j=0 ; j<2 ; j++) + { + n = j*3 + i; + + p = AllocPortal (); + portals[n] = p; + + pl = &bplanes[n]; + memset (pl, 0, sizeof(*pl)); + if (j) + { + pl->normal[i] = -1; + pl->dist = -bounds[j][i]; + } + else + { + pl->normal[i] = 1; + pl->dist = bounds[j][i]; + } + p->plane = *pl; + p->winding = BaseWindingForPlane (pl->normal, pl->dist); + AddPortalToNodes (p, node, &tree->outside_node); + } + +// clip the basewindings by all the other planes + for (i=0 ; i<6 ; i++) + { + for (j=0 ; j<6 ; j++) + { + if (j == i) + continue; + ChopWindingInPlace (&portals[i]->winding, bplanes[j].normal, bplanes[j].dist, ON_EPSILON); + } + } +} + +//=================================================== + + +/* +================ +BaseWindingForNode +================ +*/ +#define BASE_WINDING_EPSILON 0.001 +#define SPLIT_WINDING_EPSILON 0.001 + +winding_t *BaseWindingForNode (node_t *node) +{ + winding_t *w; + node_t *n; + plane_t *plane; + vec3_t normal; + vec_t dist; + + w = BaseWindingForPlane (mapplanes[node->planenum].normal + , mapplanes[node->planenum].dist); + + // clip by all the parents + for (n=node->parent ; n && w ; ) + { + plane = &mapplanes[n->planenum]; + + if (n->children[0] == node) + { // take front + ChopWindingInPlace (&w, plane->normal, plane->dist, BASE_WINDING_EPSILON); + } + else + { // take back + VectorSubtract (vec3_origin, plane->normal, normal); + dist = -plane->dist; + ChopWindingInPlace (&w, normal, dist, BASE_WINDING_EPSILON); + } + node = n; + n = n->parent; + } + + return w; +} + +//============================================================ + +/* +================== +MakeNodePortal + +create the new portal by taking the full plane winding for the cutting plane +and clipping it by all of parents of this node +================== +*/ +void MakeNodePortal (node_t *node) +{ + portal_t *new_portal, *p; + winding_t *w; + vec3_t normal; + float dist; + int side; + + w = BaseWindingForNode (node); + + // clip the portal by all the other portals in the node + for (p = node->portals ; p && w; p = p->next[side]) + { + if (p->nodes[0] == node) + { + side = 0; + VectorCopy (p->plane.normal, normal); + dist = p->plane.dist; + } + else if (p->nodes[1] == node) + { + side = 1; + VectorSubtract (vec3_origin, p->plane.normal, normal); + dist = -p->plane.dist; + } + else + Error ("CutNodePortals_r: mislinked portal"); + + ChopWindingInPlace (&w, normal, dist, CLIP_EPSILON); + } + + if (!w) + { + return; + } + + + /* ydnar: adding this here to fix degenerate windings */ + #if 0 + if( FixWinding( w ) == qfalse ) + { + c_badportals++; + FreeWinding( w ); + return; + } + #endif + + if (WindingIsTiny (w)) + { + c_tinyportals++; + FreeWinding (w); + return; + } + + new_portal = AllocPortal (); + new_portal->plane = mapplanes[node->planenum]; + new_portal->onnode = node; + new_portal->winding = w; + new_portal->compileFlags = node->compileFlags; + AddPortalToNodes (new_portal, node->children[0], node->children[1]); +} + + +/* +============== +SplitNodePortals + +Move or split the portals that bound node so that the node's +children have portals instead of node. +============== +*/ +void SplitNodePortals (node_t *node) +{ + portal_t *p, *next_portal, *new_portal; + node_t *f, *b, *other_node; + int side; + plane_t *plane; + winding_t *frontwinding, *backwinding; + + plane = &mapplanes[node->planenum]; + f = node->children[0]; + b = node->children[1]; + + for (p = node->portals ; p ; p = next_portal) + { + if (p->nodes[0] == node) + side = 0; + else if (p->nodes[1] == node) + side = 1; + else + Error ("SplitNodePortals: mislinked portal"); + next_portal = p->next[side]; + + other_node = p->nodes[!side]; + RemovePortalFromNode (p, p->nodes[0]); + RemovePortalFromNode (p, p->nodes[1]); + +// +// cut the portal into two portals, one on each side of the cut plane +// + ClipWindingEpsilon (p->winding, plane->normal, plane->dist, + SPLIT_WINDING_EPSILON, &frontwinding, &backwinding); + + if (frontwinding && WindingIsTiny(frontwinding)) + { + if (!f->tinyportals) + VectorCopy(frontwinding->p[0], f->referencepoint); + f->tinyportals++; + if (!other_node->tinyportals) + VectorCopy(frontwinding->p[0], other_node->referencepoint); + other_node->tinyportals++; + + FreeWinding (frontwinding); + frontwinding = NULL; + c_tinyportals++; + } + + if (backwinding && WindingIsTiny(backwinding)) + { + if (!b->tinyportals) + VectorCopy(backwinding->p[0], b->referencepoint); + b->tinyportals++; + if (!other_node->tinyportals) + VectorCopy(backwinding->p[0], other_node->referencepoint); + other_node->tinyportals++; + + FreeWinding (backwinding); + backwinding = NULL; + c_tinyportals++; + } + + if (!frontwinding && !backwinding) + { // tiny windings on both sides + continue; + } + + if (!frontwinding) + { + FreeWinding (backwinding); + if (side == 0) + AddPortalToNodes (p, b, other_node); + else + AddPortalToNodes (p, other_node, b); + continue; + } + if (!backwinding) + { + FreeWinding (frontwinding); + if (side == 0) + AddPortalToNodes (p, f, other_node); + else + AddPortalToNodes (p, other_node, f); + continue; + } + + // the winding is split + new_portal = AllocPortal (); + *new_portal = *p; + new_portal->winding = backwinding; + FreeWinding (p->winding); + p->winding = frontwinding; + + if (side == 0) + { + AddPortalToNodes (p, f, other_node); + AddPortalToNodes (new_portal, b, other_node); + } + else + { + AddPortalToNodes (p, other_node, f); + AddPortalToNodes (new_portal, other_node, b); + } + } + + node->portals = NULL; +} + + +/* +================ +CalcNodeBounds +================ +*/ +void CalcNodeBounds (node_t *node) +{ + portal_t *p; + int s; + int i; + + // calc mins/maxs for both leafs and nodes + ClearBounds (node->mins, node->maxs); + for (p = node->portals ; p ; p = p->next[s]) + { + s = (p->nodes[1] == node); + for (i=0 ; iwinding->numpoints ; i++) + AddPointToBounds (p->winding->p[i], node->mins, node->maxs); + } +} + +/* +================== +MakeTreePortals_r +================== +*/ +void MakeTreePortals_r (node_t *node) +{ + int i; + + CalcNodeBounds (node); + if (node->mins[0] >= node->maxs[0]) + { + Sys_Printf ("WARNING: node without a volume\n"); + Sys_Printf("node has %d tiny portals\n", node->tinyportals); + Sys_Printf("node reference point %1.2f %1.2f %1.2f\n", node->referencepoint[0], + node->referencepoint[1], + node->referencepoint[2]); + } + + for (i=0 ; i<3 ; i++) + { + if (node->mins[i] < MIN_WORLD_COORD || node->maxs[i] > MAX_WORLD_COORD) + { + if(node->portals && node->portals->winding) + xml_Winding("WARNING: Node With Unbounded Volume", node->portals->winding->p, node->portals->winding->numpoints, qfalse); + + break; + } + } + if (node->planenum == PLANENUM_LEAF) + return; + + MakeNodePortal (node); + SplitNodePortals (node); + + MakeTreePortals_r (node->children[0]); + MakeTreePortals_r (node->children[1]); +} + +/* +================== +MakeTreePortals +================== +*/ +void MakeTreePortals (tree_t *tree) +{ + Sys_FPrintf (SYS_VRB, "--- MakeTreePortals ---\n"); + MakeHeadnodePortals (tree); + MakeTreePortals_r (tree->headnode); + Sys_FPrintf( SYS_VRB, "%9d tiny portals\n", c_tinyportals ); + Sys_FPrintf( SYS_VRB, "%9d bad portals\n", c_badportals ); /* ydnar */ +} + +/* +========================================================= + +FLOOD ENTITIES + +========================================================= +*/ + +int c_floodedleafs; + +/* +============= +FloodPortals_r +============= +*/ + +void FloodPortals_r( node_t *node, int dist, qboolean skybox ) +{ + int s; + portal_t *p; + + + if( skybox ) + node->skybox = skybox; + + if( node->occupied || node->opaque ) + return; + + c_floodedleafs++; + node->occupied = dist; + + for( p = node->portals; p; p = p->next[ s ] ) + { + s = (p->nodes[ 1 ] == node); + FloodPortals_r( p->nodes[ !s ], dist + 1, skybox ); + } +} + + + +/* +============= +PlaceOccupant +============= +*/ + +qboolean PlaceOccupant( node_t *headnode, vec3_t origin, entity_t *occupant, qboolean skybox ) +{ + vec_t d; + node_t *node; + plane_t *plane; + + + // find the leaf to start in + node = headnode; + while( node->planenum != PLANENUM_LEAF ) + { + plane = &mapplanes[ node->planenum ]; + d = DotProduct( origin, plane->normal ) - plane->dist; + if( d >= 0 ) + node = node->children[ 0 ]; + else + node = node->children[ 1 ]; + } + + if( node->opaque ) + return qfalse; + node->occupant = occupant; + node->skybox = skybox; + + FloodPortals_r( node, 1, skybox ); + + return qtrue; +} + +/* +============= +FloodEntities + +Marks all nodes that can be reached by entites +============= +*/ + +qboolean FloodEntities( tree_t *tree ) +{ + int i, s; + vec3_t origin, offset, scale, angles; + qboolean r, inside, tripped, skybox; + node_t *headnode; + entity_t *e; + const char *value; + + + headnode = tree->headnode; + Sys_FPrintf( SYS_VRB,"--- FloodEntities ---\n" ); + inside = qfalse; + tree->outside_node.occupied = 0; + + tripped = qfalse; + c_floodedleafs = 0; + for( i = 1; i < numEntities; i++ ) + { + /* get entity */ + e = &entities[ i ]; + + /* get origin */ + GetVectorForKey( e, "origin", origin ); + + /* as a special case, allow origin-less entities */ + if( VectorCompare( origin, vec3_origin ) ) + continue; + + /* also allow bmodel entities outside, as they could be on a moving path that will go into the map */ + if( e->brushes != NULL || e->patches != NULL ) + continue; + + /* handle skybox entities */ + value = ValueForKey( e, "classname" ); + if( !Q_stricmp( value, "_skybox" ) ) + { + skybox = qtrue; + skyboxPresent = qtrue; + + /* invert origin */ + VectorScale( origin, -1.0f, offset ); + + /* get scale */ + VectorSet( scale, 64.0f, 64.0f, 64.0f ); + value = ValueForKey( e, "_scale" ); + if( value[ 0 ] != '\0' ) + { + s = sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] ); + if( s == 1 ) + { + scale[ 1 ] = scale[ 0 ]; + scale[ 2 ] = scale[ 0 ]; + } + } + + /* get "angle" (yaw) or "angles" (pitch yaw roll) */ + VectorClear( angles ); + angles[ 2 ] = FloatForKey( e, "angle" ); + value = ValueForKey( e, "angles" ); + if( value[ 0 ] != '\0' ) + sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] ); + + /* set transform matrix (thanks spog) */ + m4x4_identity( skyboxTransform ); + m4x4_pivoted_transform_by_vec3( skyboxTransform, offset, angles, eXYZ, scale, origin ); + } + else + skybox = qfalse; + + /* nudge off floor */ + origin[ 2 ] += 1; + + /* debugging code */ + //% if( i == 1 ) + //% origin[ 2 ] += 4096; + + /* find leaf */ + r = PlaceOccupant( headnode, origin, e, skybox ); + if( r ) + inside = qtrue; + if( !r ) + { + Sys_Printf( "Entity %i, Brush %i: Entity in solid\n", e->mapEntityNum, 0); + } + else if( tree->outside_node.occupied && !tripped ) + { + xml_Select( "Entity leaked", e->mapEntityNum, 0, qfalse ); + tripped = qtrue; + } + } + + Sys_FPrintf( SYS_VRB, "%9d flooded leafs\n", c_floodedleafs ); + + if( !inside ) + Sys_FPrintf( SYS_VRB, "no entities in open -- no filling\n" ); + else if( tree->outside_node.occupied ) + Sys_FPrintf( SYS_VRB, "entity reached from outside -- no filling\n" ); + + return (qboolean) (inside && !tree->outside_node.occupied); +} + +/* +========================================================= + +FLOOD AREAS + +========================================================= +*/ + +int c_areas; + + + +/* +FloodAreas_r() +floods through leaf portals to tag leafs with an area +*/ + +void FloodAreas_r( node_t *node ) +{ + int s; + portal_t *p; + brush_t *b; + + + if( node->areaportal ) + { + if( node->area == -1 ) + node->area = c_areas; + + /* this node is part of an area portal brush */ + b = node->brushlist->original; + + /* if the current area has already touched this portal, we are done */ + if( b->portalareas[ 0 ] == c_areas || b->portalareas[ 1 ] == c_areas ) + return; + + // note the current area as bounding the portal + if( b->portalareas[ 1 ] != -1 ) + { + Sys_Printf( "WARNING: areaportal brush %i touches > 2 areas\n", b->brushNum ); + return; + } + if( b->portalareas[ 0 ] != -1 ) + b->portalareas[ 1 ] = c_areas; + else + b->portalareas[ 0 ] = c_areas; + + return; + } + + if( node->area != -1 ) + return; + if( node->cluster == -1 ) + return; + + node->area = c_areas; + + /* ydnar: skybox nodes set the skybox area */ + if( node->skybox ) + skyboxArea = c_areas; + + for( p = node->portals; p; p = p->next[ s ] ) + { + s = (p->nodes[1] == node); + + /* ydnar: allow areaportal portals to block area flow */ + if( p->compileFlags & C_AREAPORTAL ) + continue; + + if( !PortalPassable( p ) ) + continue; + + FloodAreas_r( p->nodes[ !s ] ); + } +} + +/* +============= +FindAreas_r + +Just decend the tree, and for each node that hasn't had an +area set, flood fill out from there +============= +*/ +void FindAreas_r( node_t *node ) +{ + if( node->planenum != PLANENUM_LEAF ) + { + FindAreas_r( node->children[ 0 ] ); + FindAreas_r( node->children[ 1 ] ); + return; + } + + if( node->opaque || node->areaportal || node->area != -1 ) + return; + + FloodAreas_r( node ); + c_areas++; +} + +/* +============= +CheckAreas_r +============= +*/ +void CheckAreas_r (node_t *node) +{ + brush_t *b; + + if (node->planenum != PLANENUM_LEAF) + { + CheckAreas_r (node->children[0]); + CheckAreas_r (node->children[1]); + return; + } + + if (node->opaque) + return; + + if (node->cluster != -1) + if (node->area == -1) + Sys_Printf("WARNING: cluster %d has area set to -1\n", node->cluster); + if (node->areaportal) + { + b = node->brushlist->original; + + // check if the areaportal touches two areas + if (b->portalareas[0] == -1 || b->portalareas[1] == -1) + Sys_Printf ("WARNING: areaportal brush %i doesn't touch two areas\n", b->brushNum); + } +} + + + +/* +FloodSkyboxArea_r() - ydnar +sets all nodes with the skybox area to skybox +*/ + +void FloodSkyboxArea_r( node_t *node ) +{ + if( skyboxArea < 0 ) + return; + + if( node->planenum != PLANENUM_LEAF ) + { + FloodSkyboxArea_r( node->children[ 0 ] ); + FloodSkyboxArea_r( node->children[ 1 ] ); + return; + } + + if( node->opaque || node->area != skyboxArea ) + return; + + node->skybox = qtrue; +} + + + +/* +FloodAreas() +mark each leaf with an area, bounded by C_AREAPORTAL +*/ + +void FloodAreas( tree_t *tree ) +{ + Sys_FPrintf( SYS_VRB,"--- FloodAreas ---\n" ); + FindAreas_r( tree->headnode ); + + /* ydnar: flood all skybox nodes */ + FloodSkyboxArea_r( tree->headnode ); + + /* check for areaportal brushes that don't touch two areas */ + /* ydnar: fix this rather than just silence the warnings */ + //% CheckAreas_r( tree->headnode ); + + Sys_FPrintf( SYS_VRB, "%9d areas\n", c_areas ); +} + + + +//====================================================== + +int c_outside; +int c_inside; +int c_solid; + +void FillOutside_r (node_t *node) +{ + if (node->planenum != PLANENUM_LEAF) + { + FillOutside_r (node->children[0]); + FillOutside_r (node->children[1]); + return; + } + + // anything not reachable by an entity + // can be filled away + if (!node->occupied) { + if ( !node->opaque ) { + c_outside++; + node->opaque = qtrue; + } else { + c_solid++; + } + } else { + c_inside++; + } + +} + +/* +============= +FillOutside + +Fill all nodes that can't be reached by entities +============= +*/ +void FillOutside (node_t *headnode) +{ + c_outside = 0; + c_inside = 0; + c_solid = 0; + Sys_FPrintf( SYS_VRB,"--- FillOutside ---\n" ); + FillOutside_r( headnode ); + Sys_FPrintf( SYS_VRB,"%9d solid leafs\n", c_solid ); + Sys_Printf( "%9d leafs filled\n", c_outside ); + Sys_FPrintf( SYS_VRB, "%9d inside leafs\n", c_inside ); +} + + +//============================================================== + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/prtfile.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/prtfile.c new file mode 100644 index 00000000..2f10c7c0 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/prtfile.c @@ -0,0 +1,386 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define PRTFILE_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +============================================================================== + +PORTAL FILE GENERATION + +Save out name.prt for qvis to read +============================================================================== +*/ + + +#define PORTALFILE "PRT1" + +FILE *pf; +int num_visclusters; // clusters the player can be in +int num_visportals; +int num_solidfaces; + +void WriteFloat (FILE *f, vec_t v) +{ + if ( fabs(v - Q_rint(v)) < 0.001 ) + fprintf (f,"%i ",(int)Q_rint(v)); + else + fprintf (f,"%f ",v); +} + +void CountVisportals_r(node_t *node) +{ + int s; + portal_t *p; + winding_t *w; + + // decision node + if (node->planenum != PLANENUM_LEAF) { + CountVisportals_r (node->children[0]); + CountVisportals_r (node->children[1]); + return; + } + + if (node->opaque) { + return; + } + + for (p = node->portals ; p ; p=p->next[s]) + { + w = p->winding; + s = (p->nodes[1] == node); + if (w && p->nodes[0] == node) + { + if (!PortalPassable(p)) + continue; + if(p->nodes[0]->cluster == p->nodes[1]->cluster) + continue; + ++num_visportals; + } + } +} + +/* +================= +WritePortalFile_r +================= +*/ +void WritePortalFile_r (node_t *node) +{ + int i, s; + portal_t *p; + winding_t *w; + vec3_t normal; + vec_t dist; + + // decision node + if (node->planenum != PLANENUM_LEAF) { + WritePortalFile_r (node->children[0]); + WritePortalFile_r (node->children[1]); + return; + } + + if (node->opaque) { + return; + } + + for (p = node->portals ; p ; p=p->next[s]) + { + w = p->winding; + s = (p->nodes[1] == node); + if (w && p->nodes[0] == node) + { + if (!PortalPassable(p)) + continue; + if(p->nodes[0]->cluster == p->nodes[1]->cluster) + continue; + --num_visportals; + // write out to the file + + // sometimes planes get turned around when they are very near + // the changeover point between different axis. interpret the + // plane the same way vis will, and flip the side orders if needed + // FIXME: is this still relevent? + WindingPlane (w, normal, &dist); + + if ( DotProduct (p->plane.normal, normal) < 0.99 ) + { // backwards... + fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[1]->cluster, p->nodes[0]->cluster); + } + else + fprintf (pf,"%i %i %i ",w->numpoints, p->nodes[0]->cluster, p->nodes[1]->cluster); + + /* ydnar: added this change to make antiportals work */ + if( p->compileFlags & C_HINT ) + fprintf( pf, "1 " ); + else + fprintf( pf, "0 " ); + + /* write the winding */ + for (i=0 ; inumpoints ; i++) + { + fprintf (pf,"("); + WriteFloat (pf, w->p[i][0]); + WriteFloat (pf, w->p[i][1]); + WriteFloat (pf, w->p[i][2]); + fprintf (pf,") "); + } + fprintf (pf,"\n"); + } + } + +} + +void CountSolidFaces_r (node_t *node) +{ + int s; + portal_t *p; + winding_t *w; + + // decision node + if (node->planenum != PLANENUM_LEAF) { + CountSolidFaces_r (node->children[0]); + CountSolidFaces_r (node->children[1]); + return; + } + + if (node->opaque) { + return; + } + + for (p = node->portals ; p ; p=p->next[s]) + { + w = p->winding; + s = (p->nodes[1] == node); + if (w) + { + if (PortalPassable(p)) + continue; + if(p->nodes[0]->cluster == p->nodes[1]->cluster) + continue; + // write out to the file + + ++num_solidfaces; + } + } +} + +/* +================= +WriteFaceFile_r +================= +*/ +void WriteFaceFile_r (node_t *node) +{ + int i, s; + portal_t *p; + winding_t *w; + + // decision node + if (node->planenum != PLANENUM_LEAF) { + WriteFaceFile_r (node->children[0]); + WriteFaceFile_r (node->children[1]); + return; + } + + if (node->opaque) { + return; + } + + for (p = node->portals ; p ; p=p->next[s]) + { + w = p->winding; + s = (p->nodes[1] == node); + if (w) + { + if (PortalPassable(p)) + continue; + if(p->nodes[0]->cluster == p->nodes[1]->cluster) + continue; + // write out to the file + + if (p->nodes[0] == node) + { + fprintf (pf,"%i %i ",w->numpoints, p->nodes[0]->cluster); + for (i=0 ; inumpoints ; i++) + { + fprintf (pf,"("); + WriteFloat (pf, w->p[i][0]); + WriteFloat (pf, w->p[i][1]); + WriteFloat (pf, w->p[i][2]); + fprintf (pf,") "); + } + fprintf (pf,"\n"); + } + else + { + fprintf (pf,"%i %i ",w->numpoints, p->nodes[1]->cluster); + for (i = w->numpoints-1; i >= 0; i--) + { + fprintf (pf,"("); + WriteFloat (pf, w->p[i][0]); + WriteFloat (pf, w->p[i][1]); + WriteFloat (pf, w->p[i][2]); + fprintf (pf,") "); + } + fprintf (pf,"\n"); + } + } + } +} + +/* +================ +NumberLeafs_r +================ +*/ +void NumberLeafs_r (node_t *node, int c) +{ +#if 0 + portal_t *p; +#endif + if ( node->planenum != PLANENUM_LEAF ) { + // decision node + node->cluster = -99; + + if(node->has_structural_children) + { +#if 0 + if(c >= 0) + Sys_FPrintf (SYS_ERR,"THIS CANNOT HAPPEN\n"); +#endif + NumberLeafs_r (node->children[0], c); + NumberLeafs_r (node->children[1], c); + } + else + { + if(c < 0) + c = num_visclusters++; + NumberLeafs_r (node->children[0], c); + NumberLeafs_r (node->children[1], c); + } + return; + } + + node->area = -1; + + if ( node->opaque ) { + // solid block, viewpoint never inside + node->cluster = -1; + return; + } + + if(c < 0) + c = num_visclusters++; + + node->cluster = c; + +#if 0 + // count the portals + for (p = node->portals ; p ; ) + { + if (p->nodes[0] == node) // only write out from first leaf + { + if (PortalPassable(p)) + num_visportals++; + else + num_solidfaces++; + p = p->next[0]; + } + else + { + if (!PortalPassable(p)) + num_solidfaces++; + p = p->next[1]; + } + } +#endif +} + + +/* +================ +NumberClusters +================ +*/ +void NumberClusters(tree_t *tree) { + num_visclusters = 0; + num_visportals = 0; + num_solidfaces = 0; + + Sys_FPrintf (SYS_VRB,"--- NumberClusters ---\n"); + + // set the cluster field in every leaf and count the total number of portals + NumberLeafs_r (tree->headnode, -1); + CountVisportals_r (tree->headnode); + CountSolidFaces_r (tree->headnode); + + Sys_FPrintf( SYS_VRB, "%9d visclusters\n", num_visclusters ); + Sys_FPrintf( SYS_VRB, "%9d visportals\n", num_visportals ); + Sys_FPrintf( SYS_VRB, "%9d solidfaces\n", num_solidfaces ); +} + +/* +================ +WritePortalFile +================ +*/ +void WritePortalFile (tree_t *tree) +{ + char filename[1024]; + + Sys_FPrintf (SYS_VRB,"--- WritePortalFile ---\n"); + + // write the file + sprintf (filename, "%s.prt", source); + Sys_Printf ("writing %s\n", filename); + pf = fopen (filename, "w"); + if (!pf) + Error ("Error opening %s", filename); + + fprintf (pf, "%s\n", PORTALFILE); + fprintf (pf, "%i\n", num_visclusters); + fprintf (pf, "%i\n", num_visportals); + fprintf (pf, "%i\n", num_solidfaces); + + WritePortalFile_r(tree->headnode); + WriteFaceFile_r(tree->headnode); + + fclose (pf); +} + diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.h b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.h new file mode 100644 index 00000000..e912d15b --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.h @@ -0,0 +1,2540 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#ifndef Q3MAP2_H +#define Q3MAP2_H + + + +/* version */ +#ifndef Q3MAP_VERSION +#error no Q3MAP_VERSION defined +#endif +#define Q3MAP_MOTD "Your map saw the pretty lights from q3map2's BFG" + + + + +/* ------------------------------------------------------------------------------- + +dependencies + +------------------------------------------------------------------------------- */ + +/* platform-specific */ +#if defined( __linux__ ) || defined( __APPLE__ ) + #define Q_UNIX +#endif + +#ifdef Q_UNIX + #include + #include + #include +#endif + +#ifdef WIN32 + #include +#endif + + +/* general */ +#include "version.h" /* ttimo: might want to guard that if built outside of the GtkRadiant tree */ + +#include "cmdlib.h" +#include "mathlib.h" +#include "md5lib.h" +#include "ddslib.h" + +#include "picomodel.h" + +#include "scriplib.h" +#include "polylib.h" +#include "imagelib.h" +#include "qthreads.h" +#include "inout.h" +#include "vfs.h" +#include "png.h" +#include "md4.h" +#include "radiant_jpeglib.h" +#include + + + +/* ------------------------------------------------------------------------------- + +port-related hacks + +------------------------------------------------------------------------------- */ + +#define MAC_STATIC_HACK 0 +#if defined( __APPLE__ ) && MAC_STATIC_HACK + #define MAC_STATIC static +#else + #define MAC_STATIC +#endif + +#if 1 + #ifdef WIN32 + #define Q_stricmp stricmp + #define Q_strncasecmp strnicmp + #else + #define Q_stricmp strcasecmp + #define Q_strncasecmp strncasecmp + #endif +#endif + +/* macro version */ +#define VectorMA( a, s, b, c ) ((c)[ 0 ] = (a)[ 0 ] + (s) * (b)[ 0 ], (c)[ 1 ] = (a)[ 1 ] + (s) * (b)[ 1 ], (c)[ 2 ] = (a)[ 2 ] + (s) * (b)[ 2 ]) + + + +/* ------------------------------------------------------------------------------- + +constants + +------------------------------------------------------------------------------- */ + +/* temporary hacks and tests (please keep off in SVN to prevent anyone's legacy map from screwing up) */ +/* 2011-01-10 TTimo says we should turn these on in SVN, so turning on now */ +#define Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES 1 +#define Q3MAP2_EXPERIMENTAL_SNAP_NORMAL_FIX 1 +#define Q3MAP2_EXPERIMENTAL_SNAP_PLANE_FIX 1 + +/* general */ +#define MAX_QPATH 64 + +#define MAX_IMAGES 512 +#define DEFAULT_IMAGE "*default" + +#define MAX_MODELS 512 + +#define DEF_BACKSPLASH_FRACTION 0.05f /* 5% backsplash by default */ +#define DEF_BACKSPLASH_DISTANCE 23 + +#define DEF_RADIOSITY_BOUNCE 1.0f /* ydnar: default to 100% re-emitted light */ + +#define MAX_SHADER_INFO 8192 +#define MAX_CUST_SURFACEPARMS 64 + +#define SHADER_MAX_VERTEXES 1000 +#define SHADER_MAX_INDEXES (6 * SHADER_MAX_VERTEXES) + +#define MAX_JITTERS 256 + + +/* epair parsing (note case-sensitivity directive) */ +#define CASE_INSENSITIVE_EPAIRS 1 + +#if CASE_INSENSITIVE_EPAIRS + #define EPAIR_STRCMP Q_stricmp +#else + #define EPAIR_STRCMP strcmp +#endif + + +/* ydnar: compiler flags, because games have widely varying content/surface flags */ +#define C_SOLID 0x00000001 +#define C_TRANSLUCENT 0x00000002 +#define C_STRUCTURAL 0x00000004 +#define C_HINT 0x00000008 +#define C_NODRAW 0x00000010 +#define C_LIGHTGRID 0x00000020 +#define C_ALPHASHADOW 0x00000040 +#define C_LIGHTFILTER 0x00000080 +#define C_VERTEXLIT 0x00000100 +#define C_LIQUID 0x00000200 +#define C_FOG 0x00000400 +#define C_SKY 0x00000800 +#define C_ORIGIN 0x00001000 +#define C_AREAPORTAL 0x00002000 +#define C_ANTIPORTAL 0x00004000 /* like hint, but doesn't generate portals */ +#define C_SKIP 0x00008000 /* like hint, but skips this face (doesn't split bsp) */ +#define C_NOMARKS 0x00010000 /* no decals */ +#define C_DETAIL 0x08000000 /* THIS MUST BE THE SAME AS IN RADIANT! */ + + +/* shadow flags */ +#define WORLDSPAWN_CAST_SHADOWS 1 +#define WORLDSPAWN_RECV_SHADOWS 1 +#define ENTITY_CAST_SHADOWS 0 +#define ENTITY_RECV_SHADOWS 1 + + +/* bsp */ +#define MAX_PATCH_SIZE 32 +#define MAX_BRUSH_SIDES 1024 +#define MAX_BUILD_SIDES 1024 + +#define MAX_EXPANDED_AXIS 128 + +#define CLIP_EPSILON 0.1f +#define PLANESIDE_EPSILON 0.001f +#define PLANENUM_LEAF -1 + +#define HINT_PRIORITY 1000 /* ydnar: force hint splits first and antiportal/areaportal splits last */ +#define ANTIPORTAL_PRIORITY -1000 +#define AREAPORTAL_PRIORITY -1000 +#define DETAIL_PRIORITY -3000 + +#define PSIDE_FRONT 1 +#define PSIDE_BACK 2 +#define PSIDE_BOTH (PSIDE_FRONT | PSIDE_BACK) +#define PSIDE_FACING 4 + +#define BPRIMIT_UNDEFINED 0 +#define BPRIMIT_OLDBRUSHES 1 +#define BPRIMIT_NEWBRUSHES 2 + + +/* vis */ +#define VIS_HEADER_SIZE 8 + +#define SEPERATORCACHE /* seperator caching helps a bit */ + +#define PORTALFILE "PRT1" + +#define MAX_PORTALS 0x20000 /* same as MAX_MAP_PORTALS */ +#define MAX_SEPERATORS MAX_POINTS_ON_WINDING +#define MAX_POINTS_ON_FIXED_WINDING 24 /* ydnar: increased this from 12 at the expense of more memory */ +#define MAX_PORTALS_ON_LEAF 1024 + + +/* light */ +#define EMIT_POINT 0 +#define EMIT_AREA 1 +#define EMIT_SPOT 2 +#define EMIT_SUN 3 + +#define LIGHT_ATTEN_LINEAR 1 +#define LIGHT_ATTEN_ANGLE 2 +#define LIGHT_ATTEN_DISTANCE 4 +#define LIGHT_TWOSIDED 8 +#define LIGHT_GRID 16 +#define LIGHT_SURFACES 32 +#define LIGHT_DARK 64 /* probably never use this */ +#define LIGHT_FAST 256 +#define LIGHT_FAST_TEMP 512 +#define LIGHT_FAST_ACTUAL (LIGHT_FAST | LIGHT_FAST_TEMP) +#define LIGHT_NEGATIVE 1024 +#define LIGHT_UNNORMALIZED 2048 /* vortex: do not normalize _color */ + +#define LIGHT_SUN_DEFAULT (LIGHT_ATTEN_ANGLE | LIGHT_GRID | LIGHT_SURFACES) +#define LIGHT_AREA_DEFAULT (LIGHT_ATTEN_ANGLE | LIGHT_ATTEN_DISTANCE | LIGHT_GRID | LIGHT_SURFACES) /* q3a and wolf are the same */ +#define LIGHT_Q3A_DEFAULT (LIGHT_ATTEN_ANGLE | LIGHT_ATTEN_DISTANCE | LIGHT_GRID | LIGHT_SURFACES | LIGHT_FAST) +#define LIGHT_WOLF_DEFAULT (LIGHT_ATTEN_LINEAR | LIGHT_ATTEN_DISTANCE | LIGHT_GRID | LIGHT_SURFACES | LIGHT_FAST) + +#define MAX_TRACE_TEST_NODES 256 +#define DEFAULT_INHIBIT_RADIUS 1.5f + +#define LUXEL_EPSILON 0.125f +#define VERTEX_EPSILON -0.125f +#define GRID_EPSILON 0.0f + +#define DEFAULT_LIGHTMAP_SAMPLE_SIZE 16 +#define DEFAULT_LIGHTMAP_MIN_SAMPLE_SIZE 0 +#define DEFAULT_LIGHTMAP_SAMPLE_OFFSET 1.0f +#define DEFAULT_SUBDIVIDE_THRESHOLD 1.0f + +#define EXTRA_SCALE 2 /* -extrawide = -super 2 */ +#define EXTRAWIDE_SCALE 2 /* -extrawide = -super 2 -filter */ + +#define CLUSTER_UNMAPPED -1 +#define CLUSTER_OCCLUDED -2 +#define CLUSTER_FLOODED -3 + +#define VERTEX_LUXEL_SIZE 3 +#define BSP_LUXEL_SIZE 3 +#define RAD_LUXEL_SIZE 3 +#define SUPER_LUXEL_SIZE 4 +#define SUPER_FLAG_SIZE 4 +#define FLAG_FORCE_SUBSAMPLING 1 +#define FLAG_ALREADY_SUBSAMPLED 2 +#define SUPER_ORIGIN_SIZE 3 +#define SUPER_NORMAL_SIZE 4 +#define SUPER_DELUXEL_SIZE 3 +#define BSP_DELUXEL_SIZE 3 +#define SUPER_FLOODLIGHT_SIZE 4 + +#define VERTEX_LUXEL( s, v ) (vertexLuxels[ s ] + ((v) * VERTEX_LUXEL_SIZE)) +#define RAD_VERTEX_LUXEL( s, v )(radVertexLuxels[ s ] + ((v) * VERTEX_LUXEL_SIZE)) +#define BSP_LUXEL( s, x, y ) (lm->bspLuxels[ s ] + ((((y) * lm->w) + (x)) * BSP_LUXEL_SIZE)) +#define RAD_LUXEL( s, x, y ) (lm->radLuxels[ s ] + ((((y) * lm->w) + (x)) * RAD_LUXEL_SIZE)) +#define SUPER_LUXEL( s, x, y ) (lm->superLuxels[ s ] + ((((y) * lm->sw) + (x)) * SUPER_LUXEL_SIZE)) +#define SUPER_FLAG( x, y ) (lm->superFlags + ((((y) * lm->sw) + (x)) * SUPER_FLAG_SIZE)) +#define SUPER_DELUXEL( x, y ) (lm->superDeluxels + ((((y) * lm->sw) + (x)) * SUPER_DELUXEL_SIZE)) +#define BSP_DELUXEL( x, y ) (lm->bspDeluxels + ((((y) * lm->w) + (x)) * BSP_DELUXEL_SIZE)) +#define SUPER_CLUSTER( x, y ) (lm->superClusters + (((y) * lm->sw) + (x))) +#define SUPER_ORIGIN( x, y ) (lm->superOrigins + ((((y) * lm->sw) + (x)) * SUPER_ORIGIN_SIZE)) +#define SUPER_NORMAL( x, y ) (lm->superNormals + ((((y) * lm->sw) + (x)) * SUPER_NORMAL_SIZE)) +#define SUPER_DIRT( x, y ) (lm->superNormals + ((((y) * lm->sw) + (x)) * SUPER_NORMAL_SIZE) + 3) /* stash dirtyness in normal[ 3 ] */ +#define SUPER_FLOODLIGHT( x, y ) (lm->superFloodLight + ((((y) * lm->sw) + (x)) * SUPER_FLOODLIGHT_SIZE) ) + + + +/* ------------------------------------------------------------------------------- + +abstracted bsp file + +------------------------------------------------------------------------------- */ + +#define EXTERNAL_LIGHTMAP "lm_%04d.tga" + +#define MAX_LIGHTMAPS 4 /* RBSP */ +#define MAX_LIGHT_STYLES 64 +#define MAX_SWITCHED_LIGHTS 32 +#define LS_NORMAL 0x00 +#define LS_UNUSED 0xFE +#define LS_NONE 0xFF + +#define MAX_LIGHTMAP_SHADERS 256 + +/* ok to increase these at the expense of more memory */ +#define MAX_MAP_ENTITIES 0x1000 //% 0x800 /* ydnar */ +#define MAX_MAP_ENTSTRING 0x80000 //% 0x40000 /* ydnar */ + +#define MAX_MAP_AREAS 0x100 /* MAX_MAP_AREA_BYTES in q_shared must match! */ +#define MAX_MAP_FOGS 30 //& 0x100 /* RBSP (32 - world fog - goggles) */ +#define MAX_MAP_LEAFS 0x20000 +#define MAX_MAP_PORTALS 0x20000 +#define MAX_MAP_LIGHTING 0x800000 +#define MAX_MAP_LIGHTGRID 0x100000 //% 0x800000 /* ydnar: set to points, not bytes */ +#define MAX_MAP_VISCLUSTERS 0x4000 // <= MAX_MAP_LEAFS +#define MAX_MAP_VISIBILITY (VIS_HEADER_SIZE + MAX_MAP_VISCLUSTERS * (((MAX_MAP_VISCLUSTERS + 63) & ~63) >> 3)) + +#define MAX_MAP_DRAW_SURFS 0x20000 +#define MAX_MAP_DRAW_INDEXES 0x80000 + +#define MAX_MAP_ADVERTISEMENTS 30 + +/* 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 void (*bspFunc)( const char * ); + + +typedef struct +{ + int offset, length; +} +bspLump_t; + + +typedef struct +{ + char ident[ 4 ]; + int version; + + bspLump_t lumps[ 100 ]; /* theoretical maximum # of bsp lumps */ +} +bspHeader_t; + + +typedef struct +{ + float mins[ 3 ], maxs[ 3 ]; + int firstBSPSurface, numBSPSurfaces; + int firstBSPBrush, numBSPBrushes; +} +bspModel_t; + + +typedef struct +{ + char shader[ MAX_QPATH ]; + int surfaceFlags; + int contentFlags; +} +bspShader_t; + + +/* planes x^1 is allways the opposite of plane x */ + +typedef struct +{ + float normal[ 3 ]; + float dist; +} +bspPlane_t; + + +typedef struct +{ + int planeNum; + int children[ 2 ]; /* negative numbers are -(leafs+1), not nodes */ + int mins[ 3 ]; /* for frustom culling */ + int maxs[ 3 ]; +} +bspNode_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 firstBSPLeafSurface; + int numBSPLeafSurfaces; + + int firstBSPLeafBrush; + int numBSPLeafBrushes; +} +bspLeaf_t; + + +typedef struct +{ + int planeNum; /* positive plane side faces out of the leaf */ + int shaderNum; + int surfaceNum; /* RBSP */ +} +bspBrushSide_t; + + +typedef struct +{ + int firstSide; + int numSides; + int shaderNum; /* the shader that determines the content flags */ +} +bspBrush_t; + + +typedef struct +{ + char shader[ MAX_QPATH ]; + int brushNum; + int visibleSide; /* the brush side that ray tests need to clip against (-1 == none) */ +} +bspFog_t; + + +typedef struct +{ + vec3_t xyz; + float st[ 2 ]; + float lightmap[ MAX_LIGHTMAPS ][ 2 ]; /* RBSP */ + vec3_t normal; + byte color[ MAX_LIGHTMAPS ][ 4 ]; /* RBSP */ +} +bspDrawVert_t; + + +typedef enum +{ + MST_BAD, + MST_PLANAR, + MST_PATCH, + MST_TRIANGLE_SOUP, + MST_FLARE, + MST_FOLIAGE +} +bspSurfaceType_t; + + +typedef struct bspGridPoint_s +{ + byte ambient[ MAX_LIGHTMAPS ][ 3 ]; + byte directed[ MAX_LIGHTMAPS ][ 3 ]; + byte styles[ MAX_LIGHTMAPS ]; + byte latLong[ 2 ]; +} +bspGridPoint_t; + + +typedef struct +{ + int shaderNum; + int fogNum; + int surfaceType; + + int firstVert; + int numVerts; + + int firstIndex; + int numIndexes; + + byte lightmapStyles[ MAX_LIGHTMAPS ]; /* RBSP */ + byte vertexStyles[ MAX_LIGHTMAPS ]; /* RBSP */ + int lightmapNum[ MAX_LIGHTMAPS ]; /* RBSP */ + int lightmapX[ MAX_LIGHTMAPS ], lightmapY[ MAX_LIGHTMAPS ]; /* RBSP */ + int lightmapWidth, lightmapHeight; + + vec3_t lightmapOrigin; + vec3_t lightmapVecs[ 3 ]; /* on patches, [ 0 ] and [ 1 ] are lodbounds */ + + int patchWidth; + int patchHeight; +} +bspDrawSurface_t; + + +/* advertisements */ +typedef struct { + int cellId; + vec3_t normal; + vec3_t rect[4]; + char model[ MAX_QPATH ]; +} bspAdvertisement_t; + + +/* ------------------------------------------------------------------------------- + +general types + +------------------------------------------------------------------------------- */ + +/* ydnar: for smaller structs */ +typedef unsigned char qb_t; + + +/* ydnar: for q3map_tcMod */ +typedef float tcMod_t[ 3 ][ 3 ]; + + +/* ydnar: for multiple game support */ +typedef struct surfaceParm_s +{ + char *name; + int contentFlags, contentFlagsClear; + int surfaceFlags, surfaceFlagsClear; + int compileFlags, compileFlagsClear; +} +surfaceParm_t; + +typedef enum +{ + MINIMAP_MODE_GRAY, + MINIMAP_MODE_BLACK, + MINIMAP_MODE_WHITE +} +miniMapMode_t; + +typedef struct game_s +{ + char *arg; /* -game matches this */ + char *gamePath; /* main game data dir */ + char *homeBasePath; /* home sub-dir on unix */ + char *magic; /* magic word for figuring out base path */ + char *shaderPath; /* shader directory */ + int maxLMSurfaceVerts; /* default maximum meta surface verts */ + int maxSurfaceVerts; /* default maximum surface verts */ + int maxSurfaceIndexes; /* default maximum surface indexes (tris * 3) */ + qboolean emitFlares; /* when true, emit flare surfaces */ + char *flareShader; /* default flare shader (MUST BE SET) */ + qboolean wolfLight; /* when true, lights work like wolf q3map */ + int lightmapSize; /* bsp lightmap width/height */ + float lightmapGamma; /* default lightmap gamma */ + float lightmapExposure; /* default lightmap exposure */ + float lightmapCompensate; /* default lightmap compensate value */ + float gridScale; /* vortex: default lightgrid scale (affects both directional and ambient spectres) */ + float gridAmbientScale; /* vortex: default lightgrid ambient spectre scale */ + qboolean lightAngleHL; /* jal: use half-lambert curve for light angle attenuation */ + qboolean noStyles; /* use lightstyles hack or not */ + qboolean keepLights; /* keep light entities on bsp */ + int patchSubdivisions; /* default patch subdivisions tolerance */ + qboolean patchShadows; /* patch casting enabled */ + qboolean deluxeMap; /* compile deluxemaps */ + int deluxeMode; /* deluxemap mode (0 - modelspace, 1 - tangentspace with renormalization, 2 - tangentspace without renormalization) */ + int miniMapSize; /* minimap size */ + float miniMapSharpen; /* minimap sharpening coefficient */ + float miniMapBorder; /* minimap border amount */ + qboolean miniMapKeepAspect; /* minimap keep aspect ratio by letterboxing */ + miniMapMode_t miniMapMode; /* minimap mode */ + char *miniMapNameFormat; /* minimap name format */ + char *bspIdent; /* 4-letter bsp file prefix */ + int bspVersion; /* bsp version to use */ + qboolean lumpSwap; /* cod-style len/ofs order */ + bspFunc load, write; /* load/write function pointers */ + surfaceParm_t surfaceParms[ 128 ]; /* surfaceparm array */ +} +game_t; + + +typedef struct image_s +{ + char *name, *filename; + int refCount; + int width, height; + byte *pixels; +} +image_t; + + +typedef struct sun_s +{ + struct sun_s *next; + vec3_t direction, color; + float photons, deviance, filterRadius; + int numSamples, style; +} +sun_t; + + +typedef struct surfaceModel_s +{ + struct surfaceModel_s *next; + char model[ MAX_QPATH ]; + float density, odds; + float minScale, maxScale; + float minAngle, maxAngle; + qboolean oriented; +} +surfaceModel_t; + + +/* ydnar/sd: foliage stuff for wolf et (engine-supported optimization of the above) */ +typedef struct foliage_s +{ + struct foliage_s *next; + char model[ MAX_QPATH ]; + float scale, density, odds; + qboolean inverseAlpha; +} +foliage_t; + +typedef struct foliageInstance_s +{ + vec3_t xyz, normal; +} +foliageInstance_t; + + +typedef struct remap_s +{ + struct remap_s *next; + char from[ 1024 ]; + char to[ MAX_QPATH ]; +} +remap_t; + +typedef struct skinfile_s +{ + struct skinfile_s *next; + char name[ 1024 ]; + char to[ MAX_QPATH ]; +} +skinfile_t; + + +/* wingdi.h hack, it's the same: 0 */ +#undef CM_NONE + +typedef enum +{ + CM_NONE, + CM_VOLUME, + CM_COLOR_SET, + CM_ALPHA_SET, + CM_COLOR_SCALE, + CM_ALPHA_SCALE, + CM_COLOR_DOT_PRODUCT, + CM_ALPHA_DOT_PRODUCT, + CM_COLOR_DOT_PRODUCT_SCALE, + CM_ALPHA_DOT_PRODUCT_SCALE, + CM_COLOR_DOT_PRODUCT_2, + CM_ALPHA_DOT_PRODUCT_2, + CM_COLOR_DOT_PRODUCT_2_SCALE, + CM_ALPHA_DOT_PRODUCT_2_SCALE +} +colorModType_t; + + +typedef struct colorMod_s +{ + struct colorMod_s *next; + colorModType_t type; + vec_t data[ 16 ]; +} +colorMod_t; + + +typedef enum +{ + IM_NONE, + IM_OPAQUE, + IM_MASKED, + IM_BLEND +} +implicitMap_t; + + +typedef struct shaderInfo_s +{ + char shader[ MAX_QPATH ]; + int surfaceFlags; + int contentFlags; + int compileFlags; + float value; /* light value */ + + char *flareShader; /* for light flares */ + char *damageShader; /* ydnar: sof2 damage shader name */ + char *backShader; /* for surfaces that generate different front and back passes */ + char *cloneShader; /* ydnar: for cloning of a surface */ + char *remapShader; /* ydnar: remap a shader in final stage */ + char *deprecateShader; /* vortex: shader is deprecated and replaced by this on use */ + + surfaceModel_t *surfaceModel; /* ydnar: for distribution of models */ + foliage_t *foliage; /* ydnar/splash damage: wolf et foliage */ + + float subdivisions; /* from a "tesssize xxx" */ + float backsplashFraction; /* floating point value, usually 0.05 */ + float backsplashDistance; /* default 16 */ + float lightSubdivide; /* default 999 */ + float lightFilterRadius; /* ydnar: lightmap filtering/blurring radius for lights created by this shader (default: 0) */ + + int lightmapSampleSize; /* lightmap sample size */ + float lightmapSampleOffset; /* ydnar: lightmap sample offset (default: 1.0) */ + + float bounceScale; /* ydnar: radiosity re-emission [0,1.0+] */ + float offset; /* ydnar: offset in units */ + float shadeAngleDegrees; /* ydnar: breaking angle for smooth shading (degrees) */ + + vec3_t mins, maxs; /* ydnar: for particle studio vertexDeform move support */ + + qb_t legacyTerrain; /* ydnar: enable legacy terrain crutches */ + qb_t indexed; /* ydnar: attempt to use indexmap (terrain alphamap style) */ + qb_t forceMeta; /* ydnar: force metasurface path */ + qb_t noClip; /* ydnar: don't clip into bsp, preserve original face winding */ + qb_t noFast; /* ydnar: supress fast lighting for surfaces with this shader */ + qb_t invert; /* ydnar: reverse facing */ + qb_t nonplanar; /* ydnar: for nonplanar meta surface merging */ + qb_t tcGen; /* ydnar: has explicit texcoord generation */ + vec3_t vecs[ 2 ]; /* ydnar: explicit texture vectors for [0,1] texture space */ + tcMod_t mod; /* ydnar: q3map_tcMod matrix for djbob :) */ + vec3_t lightmapAxis; /* ydnar: explicit lightmap axis projection */ + colorMod_t *colorMod; /* ydnar: q3map_rgb/color/alpha/Set/Mod support */ + + int furNumLayers; /* ydnar: number of fur layers */ + float furOffset; /* ydnar: offset of each layer */ + float furFade; /* ydnar: alpha fade amount per layer */ + + qb_t splotchFix; /* ydnar: filter splotches on lightmaps */ + + qb_t hasPasses; /* false if the shader doesn't define any rendering passes */ + qb_t globalTexture; /* don't normalize texture repeats */ + qb_t twoSided; /* cull none */ + qb_t autosprite; /* autosprite shaders will become point lights instead of area lights */ + qb_t polygonOffset; /* ydnar: don't face cull this or against this */ + qb_t patchShadows; /* have patches casting shadows when using -light for this surface */ + qb_t vertexShadows; /* shadows will be casted at this surface even when vertex lit */ + qb_t forceSunlight; /* force sun light at this surface even tho we might not calculate shadows in vertex lighting */ + qb_t notjunc; /* don't use this surface for tjunction fixing */ + qb_t fogParms; /* ydnar: has fogparms */ + qb_t noFog; /* ydnar: supress fogging */ + qb_t clipModel; /* ydnar: solid model hack */ + qb_t noVertexLight; /* ydnar: leave vertex color alone */ + qb_t noDirty; /* jal: do not apply the dirty pass to this surface */ + + byte styleMarker; /* ydnar: light styles hack */ + + float vertexScale; /* vertex light scale */ + + char skyParmsImageBase[ MAX_QPATH ]; /* ydnar: for skies */ + + char editorImagePath[ MAX_QPATH ]; /* use this image to generate texture coordinates */ + char lightImagePath[ MAX_QPATH ]; /* use this image to generate color / averageColor */ + char normalImagePath[ MAX_QPATH ]; /* ydnar: normalmap image for bumpmapping */ + + implicitMap_t implicitMap; /* ydnar: enemy territory implicit shaders */ + char implicitImagePath[ MAX_QPATH ]; + + image_t *shaderImage; + image_t *lightImage; + image_t *normalImage; + + float skyLightValue; /* ydnar */ + int skyLightIterations; /* ydnar */ + sun_t *sun; /* ydnar */ + + vec3_t color; /* normalized color */ + vec3_t averageColor; + byte lightStyle; + + /* vortex: per-surface floodlight */ + float floodlightDirectionScale; + vec3_t floodlightRGB; + float floodlightIntensity; + float floodlightDistance; + + qb_t lmMergable; /* ydnar */ + int lmCustomWidth, lmCustomHeight; /* ydnar */ + float lmBrightness; /* ydnar */ + float lmFilterRadius; /* ydnar: lightmap filtering/blurring radius for this shader (default: 0) */ + + int shaderWidth, shaderHeight; /* ydnar */ + float stFlat[ 2 ]; + + vec3_t fogDir; /* ydnar */ + + char *shaderText; /* ydnar */ + qb_t custom; + qb_t finished; +} +shaderInfo_t; + + + +/* ------------------------------------------------------------------------------- + +bsp structures + +------------------------------------------------------------------------------- */ + +typedef struct face_s +{ + struct face_s *next; + int planenum; + int priority; + //qboolean checked; + int compileFlags; + winding_t *w; +} +face_t; + + +typedef struct plane_s +{ + vec3_t normal; + vec_t dist; + int type; + int counter; + int hash_chain; +} +plane_t; + + +typedef struct side_s +{ + int planenum; + + int outputNum; /* set when the side is written to the file list */ + + float texMat[ 2 ][ 3 ]; /* brush primitive texture matrix */ + float vecs[ 2 ][ 4 ]; /* old-style texture coordinate mapping */ + + winding_t *winding; + winding_t *visibleHull; /* convex hull of all visible fragments */ + + shaderInfo_t *shaderInfo; + + int contentFlags; /* from shaderInfo */ + int surfaceFlags; /* from shaderInfo */ + int compileFlags; /* from shaderInfo */ + int value; /* from shaderInfo */ + + qboolean visible; /* choose visble planes first */ + qboolean bevel; /* don't ever use for bsp splitting, and don't bother making windings for it */ + qboolean culled; /* ydnar: face culling */ +} +side_t; + + +typedef struct sideRef_s +{ + struct sideRef_s *next; + side_t *side; +} +sideRef_t; + + +/* ydnar: generic index mapping for entities (natural extension of terrain texturing) */ +typedef struct indexMap_s +{ + int w, h, numLayers; + char name[ MAX_QPATH ], shader[ MAX_QPATH ]; + float offsets[ 256 ]; + byte *pixels; +} +indexMap_t; + + +typedef struct brush_s +{ + struct brush_s *next; + struct brush_s *nextColorModBrush; /* ydnar: colorMod volume brushes go here */ + struct brush_s *original; /* chopped up brushes will reference the originals */ + + int entityNum, brushNum;/* editor numbering */ + int outputNum; /* set when the brush is written to the file list */ + + /* ydnar: for shadowcasting entities */ + int castShadows; + int recvShadows; + + shaderInfo_t *contentShader; + shaderInfo_t *celShader; /* :) */ + + /* ydnar: gs mods */ + int lightmapSampleSize; /* jal : entity based _lightmapsamplesize */ + float lightmapScale; + float shadeAngleDegrees; /* jal : entity based _shadeangle */ + vec3_t eMins, eMaxs; + indexMap_t *im; + + int contentFlags; + int compileFlags; /* ydnar */ + qboolean detail; + qboolean opaque; + + int portalareas[ 2 ]; + + vec3_t mins, maxs; + int numsides; + + side_t sides[ 6 ]; /* variably sized */ +} +brush_t; + + +typedef struct fog_s +{ + shaderInfo_t *si; + brush_t *brush; + int visibleSide; /* the brush side that ray tests need to clip against (-1 == none) */ +} +fog_t; + + +typedef struct +{ + int width, height; + bspDrawVert_t *verts; +} +mesh_t; + + +typedef struct parseMesh_s +{ + struct parseMesh_s *next; + + int entityNum, brushNum; /* ydnar: editor numbering */ + + /* ydnar: for shadowcasting entities */ + int castShadows; + int recvShadows; + + mesh_t mesh; + shaderInfo_t *shaderInfo; + shaderInfo_t *celShader; /* :) */ + + /* ydnar: gs mods */ + int lightmapSampleSize; /* jal : entity based _lightmapsamplesize */ + float lightmapScale; + vec3_t eMins, eMaxs; + indexMap_t *im; + + /* grouping */ + qboolean grouped; + float longestCurve; + int maxIterations; +} +parseMesh_t; + + +/* + ydnar: the drawsurf struct was extended to allow for: + - non-convex planar surfaces + - non-planar brushface surfaces + - lightmapped terrain + - planar patches +*/ + +typedef enum +{ + /* ydnar: these match up exactly with bspSurfaceType_t */ + SURFACE_BAD, + SURFACE_FACE, + SURFACE_PATCH, + SURFACE_TRIANGLES, + SURFACE_FLARE, + SURFACE_FOLIAGE, /* wolf et */ + + /* ydnar: compiler-relevant surface types */ + SURFACE_FORCED_META, + SURFACE_META, + SURFACE_FOGHULL, + SURFACE_DECAL, + SURFACE_SHADER, + + NUM_SURFACE_TYPES +} +surfaceType_t; + +char *surfaceTypes[ NUM_SURFACE_TYPES ] +#ifndef MAIN_C + ; +#else + = + { + "SURFACE_BAD", + "SURFACE_FACE", + "SURFACE_PATCH", + "SURFACE_TRIANGLES", + "SURFACE_FLARE", + "SURFACE_FOLIAGE", + "SURFACE_FORCED_META", + "SURFACE_META", + "SURFACE_FOGHULL", + "SURFACE_DECAL", + "SURFACE_SHADER" + }; +#endif + + +/* ydnar: this struct needs an overhaul (again, heh) */ +typedef struct mapDrawSurface_s +{ + surfaceType_t type; + qboolean planar; + int outputNum; /* ydnar: to match this sort of thing up */ + + qboolean fur; /* ydnar: this is kind of a hack, but hey... */ + qboolean skybox; /* ydnar: yet another fun hack */ + qboolean backSide; /* ydnar: q3map_backShader support */ + + struct mapDrawSurface_s *parent; /* ydnar: for cloned (skybox) surfaces to share lighting data */ + struct mapDrawSurface_s *clone; /* ydnar: for cloned surfaces */ + struct mapDrawSurface_s *cel; /* ydnar: for cloned cel surfaces */ + + shaderInfo_t *shaderInfo; + shaderInfo_t *celShader; + brush_t *mapBrush; + parseMesh_t *mapMesh; + sideRef_t *sideRef; + + int fogNum; + + int numVerts; /* vertexes and triangles */ + bspDrawVert_t *verts; + int numIndexes; + int *indexes; + + int planeNum; + vec3_t lightmapOrigin; /* also used for flares */ + vec3_t lightmapVecs[ 3 ]; /* also used for flares */ + int lightStyle; /* used for flares */ + + /* ydnar: per-surface (per-entity, actually) lightmap sample size scaling */ + float lightmapScale; + + /* jal: per-surface (per-entity, actually) shadeangle */ + float shadeAngleDegrees; + + /* ydnar: surface classification */ + vec3_t mins, maxs; + vec3_t lightmapAxis; + int sampleSize; + + /* ydnar: shadow group support */ + int castShadows, recvShadows; + + /* ydnar: texture coordinate range monitoring for hardware with limited texcoord precision (in texel space) */ + float bias[ 2 ]; + int texMins[ 2 ], texMaxs[ 2 ], texRange[ 2 ]; + + /* ydnar: for patches */ + float longestCurve; + int maxIterations; + int patchWidth, patchHeight; + vec3_t bounds[ 2 ]; + + /* ydnar/sd: for foliage */ + int numFoliageInstances; + + /* ydnar: editor/useful numbering */ + int entityNum; + int surfaceNum; +} +mapDrawSurface_t; + + +typedef struct drawSurfRef_s +{ + struct drawSurfRef_s *nextRef; + int outputNum; +} +drawSurfRef_t; + + +/* ydnar: metasurfaces are constructed from lists of metatriangles so they can be merged in the best way */ +typedef struct metaTriangle_s +{ + shaderInfo_t *si; + side_t *side; + int entityNum, surfaceNum, planeNum, fogNum, sampleSize, castShadows, recvShadows; + float shadeAngleDegrees; + vec4_t plane; + vec3_t lightmapAxis; + int indexes[ 3 ]; +} +metaTriangle_t; + + +typedef struct epair_s +{ + struct epair_s *next; + char *key, *value; +} +epair_t; + + +typedef struct +{ + vec3_t origin; + brush_t *brushes, *lastBrush, *colorModBrushes; + parseMesh_t *patches; + int mapEntityNum, firstDrawSurf; + int firstBrush, numBrushes; /* only valid during BSP compile */ + epair_t *epairs; + vec3_t originbrush_origin; +} +entity_t; + + +typedef struct node_s +{ + /* both leafs and nodes */ + int planenum; /* -1 = leaf node */ + struct node_s *parent; + vec3_t mins, maxs; /* valid after portalization */ + brush_t *volume; /* one for each leaf/node */ + + /* nodes only */ + side_t *side; /* the side that created the node */ + struct node_s *children[ 2 ]; + int compileFlags; /* ydnar: hint, antiportal */ + int tinyportals; + vec3_t referencepoint; + + /* leafs only */ + qboolean opaque; /* view can never be inside */ + qboolean areaportal; + qboolean skybox; /* ydnar: a skybox leaf */ + qboolean sky; /* ydnar: a sky leaf */ + int cluster; /* for portalfile writing */ + int area; /* for areaportals */ + brush_t *brushlist; /* fragments of all brushes in this leaf */ + drawSurfRef_t *drawSurfReferences; + + int occupied; /* 1 or greater can reach entity */ + entity_t *occupant; /* for leak file testing */ + + struct portal_s *portals; /* also on nodes during construction */ + + qboolean has_structural_children; +} +node_t; + + +typedef struct portal_s +{ + plane_t plane; + node_t *onnode; /* NULL = outside box */ + node_t *nodes[ 2 ]; /* [ 0 ] = front side of plane */ + struct portal_s *next[ 2 ]; + winding_t *winding; + + qboolean sidefound; /* false if ->side hasn't been checked */ + int compileFlags; /* from original face that caused the split */ + side_t *side; /* NULL = non-visible */ +} +portal_t; + + +typedef struct +{ + node_t *headnode; + node_t outside_node; + vec3_t mins, maxs; +} +tree_t; + + + +/* ------------------------------------------------------------------------------- + +vis structures + +------------------------------------------------------------------------------- */ + +typedef struct +{ + vec3_t normal; + float dist; +} +visPlane_t; + + +typedef struct +{ + int numpoints; + vec3_t points[ MAX_POINTS_ON_FIXED_WINDING ]; /* variable sized */ +} +fixedWinding_t; + + +typedef struct passage_s +{ + struct passage_s *next; + byte cansee[ 1 ]; /* all portals that can be seen through this passage */ +} passage_t; + + +typedef enum +{ + stat_none, + stat_working, + stat_done +} +vstatus_t; + + +typedef struct +{ + int num; + qboolean hint; /* true if this portal was created from a hint splitter */ + qboolean removed; + visPlane_t plane; /* normal pointing into neighbor */ + int leaf; /* neighbor */ + + vec3_t origin; /* for fast clip testing */ + float radius; + + fixedWinding_t *winding; + vstatus_t status; + byte *portalfront; /* [portals], preliminary */ + byte *portalflood; /* [portals], intermediate */ + byte *portalvis; /* [portals], final */ + + int nummightsee; /* bit count on portalflood for sort */ + passage_t *passages; /* there are just as many passages as there */ + /* are portals in the leaf this portal leads */ +} +vportal_t; + + +typedef struct leaf_s +{ + int numportals; + int merged; + vportal_t *portals[MAX_PORTALS_ON_LEAF]; +} +leaf_t; + + +typedef struct pstack_s +{ + byte mightsee[ MAX_PORTALS / 8 ]; + struct pstack_s *next; + leaf_t *leaf; + vportal_t *portal; /* portal exiting */ + fixedWinding_t *source; + fixedWinding_t *pass; + + fixedWinding_t windings[ 3 ]; /* source, pass, temp in any order */ + int freewindings[ 3 ]; + + visPlane_t portalplane; + int depth; +#ifdef SEPERATORCACHE + visPlane_t seperators[ 2 ][ MAX_SEPERATORS ]; + int numseperators[ 2 ]; +#endif +} +pstack_t; + + +typedef struct +{ + vportal_t *base; + int c_chains; + pstack_t pstack_head; +} +threaddata_t; + + + +/* ------------------------------------------------------------------------------- + +light structures + +------------------------------------------------------------------------------- */ + +/* ydnar: new light struct with flags */ +typedef struct light_s +{ + struct light_s *next; + + int type; + int flags; /* ydnar: condensed all the booleans into one flags int */ + shaderInfo_t *si; + + vec3_t origin; + vec3_t normal; /* for surfaces, spotlights, and suns */ + float dist; /* plane location along normal */ + + float photons; + int style; + vec3_t color; + float radiusByDist; /* for spotlights */ + float fade; /* ydnar: from wolf, for linear lights */ + float angleScale; /* ydnar: stolen from vlight for K */ + float extraDist; /* "extra dimension" distance of the light, to kill hot spots */ + + float add; /* ydnar: used for area lights */ + float envelope; /* ydnar: units until falloff < tolerance */ + float envelope2; /* ydnar: envelope squared (tiny optimization) */ + vec3_t mins, maxs; /* ydnar: pvs envelope */ + int cluster; /* ydnar: cluster light falls into */ + + winding_t *w; + vec3_t emitColor; /* full out-of-gamut value */ + + float falloffTolerance; /* ydnar: minimum attenuation threshold */ + float filterRadius; /* ydnar: lightmap filter radius in world units, 0 == default */ +} +light_t; + + +typedef struct +{ + /* constant input */ + qboolean testOcclusion, forceSunlight, testAll; + int recvShadows; + + int numSurfaces; + int *surfaces; + + int numLights; + light_t **lights; + + qboolean twoSided; + + /* per-sample input */ + int cluster; + vec3_t origin, normal; + vec_t inhibitRadius; /* sphere in which occluding geometry is ignored */ + + /* per-light input */ + light_t *light; + vec3_t end; + + /* calculated input */ + vec3_t displacement, direction; + vec_t distance; + + /* input and output */ + vec3_t color; /* starts out at full color, may be reduced if transparent surfaces are crossed */ + vec3_t colorNoShadow; /* result color with no shadow casting */ + vec3_t directionContribution; /* result contribution to the deluxe map */ + + /* output */ + vec3_t hit; + int compileFlags; /* for determining surface compile flags traced through */ + qboolean passSolid; + qboolean opaque; + vec_t forceSubsampling; /* needs subsampling (alphashadow), value = max color contribution possible from it */ + + /* working data */ + int numTestNodes; + int testNodes[ MAX_TRACE_TEST_NODES ]; +} +trace_t; + + + +/* must be identical to bspDrawVert_t except for float color! */ +typedef struct +{ + vec3_t xyz; + float st[ 2 ]; + float lightmap[ MAX_LIGHTMAPS ][ 2 ]; + vec3_t normal; + float color[ MAX_LIGHTMAPS ][ 4 ]; +} +radVert_t; + + +typedef struct +{ + int numVerts; + radVert_t verts[ MAX_POINTS_ON_WINDING ]; +} +radWinding_t; + + +/* crutch for poor local allocations in win32 smp */ +typedef struct +{ + vec_t dists[ MAX_POINTS_ON_WINDING + 4 ]; + int sides[ MAX_POINTS_ON_WINDING + 4 ]; +} +clipWork_t; + + +/* ydnar: new lightmap handling code */ +typedef struct outLightmap_s +{ + int lightmapNum, extLightmapNum; + int customWidth, customHeight; + int numLightmaps; + int freeLuxels; + int numShaders; + shaderInfo_t *shaders[ MAX_LIGHTMAP_SHADERS ]; + byte *lightBits; + byte *bspLightBytes; + byte *bspDirBytes; +} +outLightmap_t; + + +typedef struct rawLightmap_s +{ + qboolean finished, splotchFix, wrap[ 2 ]; + int customWidth, customHeight; + float brightness; + float filterRadius; + + int firstLightSurface, numLightSurfaces; /* index into lightSurfaces */ + int numLightClusters, *lightClusters; + + int sampleSize, actualSampleSize, axisNum; + + /* vortex: per-surface floodlight */ + float floodlightDirectionScale; + vec3_t floodlightRGB; + float floodlightIntensity; + float floodlightDistance; + + int entityNum; + int recvShadows; + vec3_t mins, maxs, axis, origin, *vecs; + float *plane; + int w, h, sw, sh, used; + + qboolean solid[ MAX_LIGHTMAPS ]; + vec3_t solidColor[ MAX_LIGHTMAPS ]; + + int numStyledTwins; + struct rawLightmap_s *twins[ MAX_LIGHTMAPS ]; + + int outLightmapNums[ MAX_LIGHTMAPS ]; + int twinNums[ MAX_LIGHTMAPS ]; + int lightmapX[ MAX_LIGHTMAPS ], lightmapY[ MAX_LIGHTMAPS ]; + byte styles[ MAX_LIGHTMAPS ]; + float *bspLuxels[ MAX_LIGHTMAPS ]; + float *radLuxels[ MAX_LIGHTMAPS ]; + float *superLuxels[ MAX_LIGHTMAPS ]; + unsigned char *superFlags; + float *superOrigins; + float *superNormals; + int *superClusters; + + float *superDeluxels; /* average light direction */ + float *bspDeluxels; + float *superFloodLight; +} +rawLightmap_t; + + +typedef struct rawGridPoint_s +{ + vec3_t ambient[ MAX_LIGHTMAPS ]; + vec3_t directed[ MAX_LIGHTMAPS ]; + vec3_t dir; + byte styles[ MAX_LIGHTMAPS ]; +} +rawGridPoint_t; + + +typedef struct surfaceInfo_s +{ + int modelindex; + shaderInfo_t *si; + rawLightmap_t *lm; + int parentSurfaceNum, childSurfaceNum; + int entityNum, castShadows, recvShadows, sampleSize, patchIterations; + float longestCurve; + float *plane; + vec3_t axis, mins, maxs; + qboolean hasLightmap, approximated; + int firstSurfaceCluster, numSurfaceClusters; +} +surfaceInfo_t; + +/* ------------------------------------------------------------------------------- + +prototypes + +------------------------------------------------------------------------------- */ + +/* main.c */ +vec_t Random( void ); +int BSPInfo( int count, char **fileNames ); +int ScaleBSPMain( int argc, char **argv ); +int ConvertMain( int argc, char **argv ); + + +/* path_init.c */ +game_t *GetGame( char *arg ); +void InitPaths( int *argc, char **argv ); + + +/* bsp.c */ +int BSPMain( int argc, char **argv ); + + +/* convert_map.c */ +int ConvertBSPToMap( char *bspName ); +int ConvertBSPToMap_BP( char *bspName ); + + +/* convert_ase.c */ +int ConvertBSPToASE( char *bspName ); + +/* convert_obj.c */ +int ConvertBSPToOBJ( char *bspName ); + + +/* brush.c */ +sideRef_t *AllocSideRef( side_t *side, sideRef_t *next ); +int CountBrushList( brush_t *brushes ); +brush_t *AllocBrush( int numsides ); +void FreeBrush( brush_t *brushes ); +void FreeBrushList( brush_t *brushes ); +brush_t *CopyBrush( brush_t *brush ); +qboolean BoundBrush( brush_t *brush ); +qboolean CreateBrushWindings( brush_t *brush ); +brush_t *BrushFromBounds( vec3_t mins, vec3_t maxs ); +vec_t BrushVolume( brush_t *brush ); +void WriteBSPBrushMap( char *name, brush_t *list ); + +void FilterDetailBrushesIntoTree( entity_t *e, tree_t *tree ); +void FilterStructuralBrushesIntoTree( entity_t *e, tree_t *tree ); + +int BoxOnPlaneSide( vec3_t mins, vec3_t maxs, plane_t *plane ); +qboolean WindingIsTiny( winding_t *w ); + +void SplitBrush( brush_t *brush, int planenum, brush_t **front, brush_t **back); + +tree_t *AllocTree( void ); +node_t *AllocNode( void ); + + +/* mesh.c */ +void LerpDrawVert( bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *out ); +void LerpDrawVertAmount( bspDrawVert_t *a, bspDrawVert_t *b, float amount, bspDrawVert_t *out ); +void FreeMesh( mesh_t *m ); +mesh_t *CopyMesh( mesh_t *mesh ); +void PrintMesh( mesh_t *m ); +mesh_t *TransposeMesh( mesh_t *in ); +void InvertMesh( mesh_t *m ); +mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ); +int IterationsForCurve( float len, int subdivisions ); +mesh_t *SubdivideMesh2( mesh_t in, int iterations ); +mesh_t *SubdivideMeshQuads( mesh_t *in, float minLength, int maxsize, int *widthtable, int *heighttable ); +mesh_t *RemoveLinearMeshColumnsRows( mesh_t *in ); +void MakeMeshNormals( mesh_t in ); +void PutMeshOnCurve( mesh_t in ); + +void MakeNormalVectors( vec3_t forward, vec3_t right, vec3_t up ); + + +/* map.c */ +void LoadMapFile( char *filename, qboolean onlyLights, qboolean noCollapseGroups ); +int FindFloatPlane( vec3_t normal, vec_t dist, int numPoints, vec3_t *points ); +int PlaneTypeForNormal( vec3_t normal ); +void AddBrushBevels( void ); +brush_t *FinishBrush(qboolean noCollapseGroups); + + +/* portals.c */ +void MakeHeadnodePortals( tree_t *tree ); +void MakeNodePortal( node_t *node ); +void SplitNodePortals( node_t *node ); + +qboolean PortalPassable( portal_t *p ); + +qboolean FloodEntities( tree_t *tree ); +void FillOutside( node_t *headnode); +void FloodAreas( tree_t *tree); +face_t *VisibleFaces( entity_t *e, tree_t *tree ); +void FreePortal( portal_t *p ); + +void MakeTreePortals( tree_t *tree ); + + +/* leakfile.c */ +xmlNodePtr LeakFile( tree_t *tree ); + + +/* prtfile.c */ +void NumberClusters( tree_t *tree ); +void WritePortalFile( tree_t *tree ); + + +/* writebsp.c */ +void SetModelNumbers( void ); +void SetLightStyles( void ); + +int EmitShader( const char *shader, int *contentFlags, int *surfaceFlags ); + +void BeginBSPFile( void ); +void EndBSPFile( qboolean do_write ); +void EmitBrushes( brush_t *brushes, int *firstBrush, int *numBrushes ); +void EmitFogs( void ); + +void BeginModel( void ); +void EndModel( entity_t *e, node_t *headnode ); + + +/* tree.c */ +void FreeTree( tree_t *tree ); +void FreeTree_r( node_t *node ); +void PrintTree_r( node_t *node, int depth ); +void FreeTreePortals_r( node_t *node ); + + +/* patch.c */ +void ParsePatch( qboolean onlyLights ); +mesh_t *SubdivideMesh( mesh_t in, float maxError, float minLength ); +void PatchMapDrawSurfs( entity_t *e ); +void TriangulatePatchSurface( entity_t *e , mapDrawSurface_t *ds ); + + +/* tjunction.c */ +void FixTJunctions( entity_t *e ); + + +/* fog.c */ +winding_t *WindingFromDrawSurf( mapDrawSurface_t *ds ); +void FogDrawSurfaces( entity_t *e ); +int FogForPoint( vec3_t point, float epsilon ); +int FogForBounds( vec3_t mins, vec3_t maxs, float epsilon ); +void CreateMapFogs( void ); + + +/* facebsp.c */ +face_t *MakeStructuralBSPFaceList( brush_t *list ); +face_t *MakeVisibleBSPFaceList( brush_t *list ); +tree_t *FaceBSP( face_t *list ); + + +/* model.c */ +void PicoPrintFunc( int level, const char *str ); +void PicoLoadFileFunc( const char *name, byte **buffer, int *bufSize ); +picoModel_t *FindModel( const char *name, int frame ); +picoModel_t *LoadModel( const char *name, int frame ); +void InsertModel( const char *name, int skin, int frame, m4x4_t transform, remap_t *remap, shaderInfo_t *celShader, int eNum, int castShadows, int recvShadows, int spawnFlags, float lightmapScale, int lightmapSampleSize, float shadeAngle ); +void AddTriangleModels( entity_t *e ); + + +/* surface.c */ +mapDrawSurface_t *AllocDrawSurface( surfaceType_t type ); +void FinishSurface( mapDrawSurface_t *ds ); +void StripFaceSurface( mapDrawSurface_t *ds ); +void MaxAreaFaceSurface( mapDrawSurface_t *ds ); +qboolean CalcSurfaceTextureRange( mapDrawSurface_t *ds ); +qboolean CalcLightmapAxis( vec3_t normal, vec3_t axis ); +void ClassifySurfaces( int numSurfs, mapDrawSurface_t *ds ); +void ClassifyEntitySurfaces( entity_t *e ); +void TidyEntitySurfaces( entity_t *e ); +mapDrawSurface_t *CloneSurface( mapDrawSurface_t *src, shaderInfo_t *si ); +mapDrawSurface_t *MakeCelSurface( mapDrawSurface_t *src, shaderInfo_t *si ); +qboolean IsTriangleDegenerate( bspDrawVert_t *points, int a, int b, int c ); +void ClearSurface( mapDrawSurface_t *ds ); +void AddEntitySurfaceModels( entity_t *e ); +mapDrawSurface_t *DrawSurfaceForSide( entity_t *e, brush_t *b, side_t *s, winding_t *w ); +mapDrawSurface_t *DrawSurfaceForMesh( entity_t *e, parseMesh_t *p, mesh_t *mesh ); +mapDrawSurface_t *DrawSurfaceForFlare( int entNum, vec3_t origin, vec3_t normal, vec3_t color, const char *flareShader, int lightStyle ); +mapDrawSurface_t *DrawSurfaceForShader( char *shader ); +void ClipSidesIntoTree( entity_t *e, tree_t *tree ); +void MakeDebugPortalSurfs( tree_t *tree ); +void MakeFogHullSurfs( entity_t *e, tree_t *tree, char *shader ); +void SubdivideFaceSurfaces( entity_t *e, tree_t *tree ); +void AddEntitySurfaceModels( entity_t *e ); +int AddSurfaceModels( mapDrawSurface_t *ds ); +void FilterDrawsurfsIntoTree( entity_t *e, tree_t *tree ); +void EmitPatchSurface( entity_t *e, mapDrawSurface_t *ds ); +void EmitTriangleSurface( mapDrawSurface_t *ds ); + + +/* surface_fur.c */ +void Fur( mapDrawSurface_t *src ); + + +/* surface_foliage.c */ +void Foliage( mapDrawSurface_t *src ); + + +/* ydnar: surface_meta.c */ +void ClearMetaTriangles( void ); +int FindMetaTriangle( metaTriangle_t *src, bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *c, int planeNum ); +void MakeEntityMetaTriangles( entity_t *e ); +void FixMetaTJunctions( void ); +void SmoothMetaTriangles( void ); +void MergeMetaTriangles( void ); +void EmitMetaStats(); // vortex: print meta statistics even in no-verbose mode + + +/* surface_extra.c */ +void SetDefaultSampleSize( int sampleSize ); + +void SetSurfaceExtra( mapDrawSurface_t *ds, int num ); + +shaderInfo_t *GetSurfaceExtraShaderInfo( int num ); +int GetSurfaceExtraParentSurfaceNum( int num ); +int GetSurfaceExtraEntityNum( int num ); +int GetSurfaceExtraCastShadows( int num ); +int GetSurfaceExtraRecvShadows( int num ); +int GetSurfaceExtraSampleSize( int num ); +int GetSurfaceExtraMinSampleSize( int num ); +float GetSurfaceExtraLongestCurve( int num ); +void GetSurfaceExtraLightmapAxis( int num, vec3_t lightmapAxis ); + +void WriteSurfaceExtraFile( const char *path ); +void LoadSurfaceExtraFile( const char *path ); + + +/* decals.c */ +void ProcessDecals( void ); +void MakeEntityDecals( entity_t *e ); + +/* map.c */ +void TextureAxisFromPlane( plane_t *pln, vec3_t xv, vec3_t yv ); + +/* brush_primit.c */ +void ComputeAxisBase( vec3_t normal, vec3_t texX, vec3_t texY); + + +/* vis.c */ +fixedWinding_t *NewFixedWinding( int points ); +int VisMain( int argc, char **argv ); + +/* visflow.c */ +int CountBits( byte *bits, int numbits ); +void PassageFlow( int portalnum ); +void CreatePassages( int portalnum ); +void PassageMemory( void ); +void BasePortalVis( int portalnum ); +void BetterPortalVis( int portalnum ); +void PortalFlow( int portalnum ); +void PassagePortalFlow( int portalnum ); + + + +/* light.c */ +float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w ); +int LightContributionToSample( trace_t *trace ); +void LightingAtSample( trace_t *trace, byte styles[ MAX_LIGHTMAPS ], vec3_t colors[ MAX_LIGHTMAPS ] ); +int LightContributionToPoint( trace_t *trace ); +int LightMain( int argc, char **argv ); + + +/* light_trace.c */ +void SetupTraceNodes( void ); +void TraceLine( trace_t *trace ); +float SetupTrace( trace_t *trace ); + + +/* light_bounce.c */ +qboolean RadSampleImage( byte *pixels, int width, int height, float st[ 2 ], float color[ 4 ] ); +void RadLightForTriangles( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ); +void RadLightForPatch( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw ); +void RadCreateDiffuseLights( void ); +void RadFreeLights(); + + +/* light_ydnar.c */ +void ColorToBytes( const float *color, byte *colorBytes, float scale ); +void SmoothNormals( void ); + +void MapRawLightmap( int num ); + +void SetupDirt(); +float DirtForSample( trace_t *trace ); +void DirtyRawLightmap( int num ); + +void SetupFloodLight(); +void FloodlightRawLightmaps(); +void FloodlightIlluminateLightmap( rawLightmap_t *lm ); +float FloodLightForSample( trace_t *trace , float floodLightDistance, qboolean floodLightLowQuality); +void FloodLightRawLightmap( int num ); + +void IlluminateRawLightmap( int num ); +void IlluminateVertexes( int num ); + +void SetupBrushes( void ); +void SetupClusters( void ); +qboolean ClusterVisible( int a, int b ); +qboolean ClusterVisibleToPoint( vec3_t point, int cluster ); +int ClusterForPoint( vec3_t point ); +int ClusterForPointExt( vec3_t point, float epsilon ); +int ClusterForPointExtFilter( vec3_t point, float epsilon, int numClusters, int *clusters ); +int ShaderForPointInLeaf( vec3_t point, int leafNum, float epsilon, int wantContentFlags, int wantSurfaceFlags, int *contentFlags, int *surfaceFlags ); +void SetupEnvelopes( qboolean forGrid, qboolean fastFlag ); +void FreeTraceLights( trace_t *trace ); +void CreateTraceLightsForBounds( vec3_t mins, vec3_t maxs, vec3_t normal, int numClusters, int *clusters, int flags, trace_t *trace ); +void CreateTraceLightsForSurface( int num, trace_t *trace ); + + +/* lightmaps_ydnar.c */ +void ExportLightmaps( void ); + +int ExportLightmapsMain( int argc, char **argv ); +int ImportLightmapsMain( int argc, char **argv ); + +void SetupSurfaceLightmaps( void ); +void StitchSurfaceLightmaps( void ); +void StoreSurfaceLightmaps( void ); + + +/* image.c */ +void ImageFree( image_t *image ); +image_t *ImageFind( const char *filename ); +image_t *ImageLoad( const char *filename ); + + +/* shaders.c */ +void ColorMod( colorMod_t *am, int numVerts, bspDrawVert_t *drawVerts ); + +void TCMod( tcMod_t mod, float st[ 2 ] ); +void TCModIdentity( tcMod_t mod ); +void TCModMultiply( tcMod_t a, tcMod_t b, tcMod_t out ); +void TCModTranslate( tcMod_t mod, float s, float t ); +void TCModScale( tcMod_t mod, float s, float t ); +void TCModRotate( tcMod_t mod, float euler ); + +qboolean ApplySurfaceParm( char *name, int *contentFlags, int *surfaceFlags, int *compileFlags ); + +void BeginMapShaderFile( const char *mapFile ); +void WriteMapShaderFile( void ); +shaderInfo_t *CustomShader( shaderInfo_t *si, char *find, char *replace ); +void EmitVertexRemapShader( char *from, char *to ); + +void LoadShaderInfo( void ); +shaderInfo_t *ShaderInfoForShader( const char *shader ); + + +/* bspfile_abstract.c */ +void SetGridPoints( int n ); +void SetDrawVerts( int n ); +void IncDrawVerts(); +void SetDrawSurfaces(int n); +void SetDrawSurfacesBuffer(); +void BSPFilesCleanup(); + +void SwapBlock( int *block, int size ); + +int GetLumpElements( bspHeader_t *header, int lump, int size ); +void *GetLump( bspHeader_t *header, int lump ); +int CopyLump( bspHeader_t *header, int lump, void *dest, int size ); +int CopyLump_Allocate( bspHeader_t *header, int lump, void **dest, int size, int *allocationVariable ); +void AddLump( FILE *file, bspHeader_t *header, int lumpNum, const void *data, int length ); + +void LoadBSPFile( const char *filename ); +void WriteBSPFile( const char *filename ); +void PrintBSPFileSizes( void ); + +epair_t *ParseEPair( void ); +void ParseEntities( void ); +void UnparseEntities( void ); +void PrintEntity( const entity_t *ent ); +void SetKeyValue( entity_t *ent, const char *key, const char *value ); +qboolean KeyExists( const entity_t *ent, const char *key ); /* VorteX: check if key exists */ +const char *ValueForKey( const entity_t *ent, const char *key ); +int IntForKey( const entity_t *ent, const char *key ); +vec_t FloatForKey( const entity_t *ent, const char *key ); +void GetVectorForKey( const entity_t *ent, const char *key, vec3_t vec ); +entity_t *FindTargetEntity( const char *target ); +void GetEntityShadowFlags( const entity_t *ent, const entity_t *ent2, int *castShadows, int *recvShadows ); +void InjectCommandLine(char **argv, int beginArgs, int endArgs); + + + +/* bspfile_ibsp.c */ +void LoadIBSPFile( const char *filename ); +void WriteIBSPFile( const char *filename ); + + +/* bspfile_rbsp.c */ +void LoadRBSPFile( const char *filename ); +void WriteRBSPFile( const char *filename ); + + + +/* ------------------------------------------------------------------------------- + +bsp/general global variables + +------------------------------------------------------------------------------- */ + +#ifdef MAIN_C + #define Q_EXTERN + #define Q_ASSIGN( a ) = a +#else + #define Q_EXTERN extern + #define Q_ASSIGN( a ) +#endif + +/* game support */ +Q_EXTERN game_t games[] +#ifndef MAIN_C + ; +#else + = + { + #include "game_quake3.h" + , + #include "game_quakelive.h"/* most be after game_quake3.h as they share defines! */ + , + #include "game_nexuiz.h"/* most be after game_quake3.h as they share defines! */ + , + #include "game_xonotic.h"/* most be after game_quake3.h as they share defines! */ + , + #include "game_tremulous.h" /*LinuxManMikeC: must be after game_quake3.h, depends on #define's set in it */ + , + #include "game_tenebrae.h" + , + #include "game_wolf.h" + , + #include "game_wolfet.h"/* most be after game_wolf.h as they share defines! */ + , + #include "game_etut.h" + , + #include "game_ef.h" + , + #include "game_sof2.h" + , + #include "game_jk2.h" /* most be after game_sof2.h as they share defines! */ + , + #include "game_ja.h" /* most be after game_jk2.h as they share defines! */ + , + #include "game_qfusion.h" /* qfusion game */ + , + #include "game_reaction.h" /* must be after game_quake3.h */ + , + #include "game_darkplaces.h" /* vortex: darkplaces q1 engine */ + , + #include "game_dq.h" /* vortex: deluxe quake game ( darkplaces q1 engine) */ + , + #include "game_prophecy.h" /* vortex: prophecy game ( darkplaces q1 engine) */ + , + #include "game__null.h" /* null game (must be last item) */ + }; +#endif +Q_EXTERN game_t *game Q_ASSIGN( &games[ 0 ] ); + + +/* general */ +Q_EXTERN int numImages Q_ASSIGN( 0 ); +Q_EXTERN image_t images[ MAX_IMAGES ]; + +Q_EXTERN int numPicoModels Q_ASSIGN( 0 ); +Q_EXTERN picoModel_t *picoModels[ MAX_MODELS ]; + +Q_EXTERN shaderInfo_t *shaderInfo Q_ASSIGN( NULL ); +Q_EXTERN int numShaderInfo Q_ASSIGN( 0 ); +Q_EXTERN int numVertexRemaps Q_ASSIGN( 0 ); + +Q_EXTERN surfaceParm_t custSurfaceParms[ MAX_CUST_SURFACEPARMS ]; +Q_EXTERN int numCustSurfaceParms Q_ASSIGN( 0 ); + +Q_EXTERN char mapName[ MAX_QPATH ]; /* ydnar: per-map custom shaders for larger lightmaps */ +Q_EXTERN char mapShaderFile[ 1024 ]; +Q_EXTERN qboolean warnImage Q_ASSIGN( qtrue ); + +/* ydnar: sinusoid samples */ +Q_EXTERN float jitters[ MAX_JITTERS ]; + + +/* commandline arguments */ +Q_EXTERN qboolean verbose; +Q_EXTERN qboolean verboseEntities Q_ASSIGN( qfalse ); +Q_EXTERN qboolean force Q_ASSIGN( qfalse ); +Q_EXTERN qboolean infoMode Q_ASSIGN( qfalse ); +Q_EXTERN qboolean useCustomInfoParms Q_ASSIGN( qfalse ); +Q_EXTERN qboolean noprune Q_ASSIGN( qfalse ); +Q_EXTERN qboolean leaktest Q_ASSIGN( qfalse ); +Q_EXTERN qboolean nodetail Q_ASSIGN( qfalse ); +Q_EXTERN qboolean nosubdivide Q_ASSIGN( qfalse ); +Q_EXTERN qboolean notjunc Q_ASSIGN( qfalse ); +Q_EXTERN qboolean fulldetail Q_ASSIGN( qfalse ); +Q_EXTERN qboolean nowater Q_ASSIGN( qfalse ); +Q_EXTERN qboolean noCurveBrushes Q_ASSIGN( qfalse ); +Q_EXTERN qboolean fakemap Q_ASSIGN( qfalse ); +Q_EXTERN qboolean coplanar Q_ASSIGN( qfalse ); +Q_EXTERN qboolean nofog Q_ASSIGN( qfalse ); +Q_EXTERN qboolean noHint Q_ASSIGN( qfalse ); /* ydnar */ +Q_EXTERN qboolean renameModelShaders Q_ASSIGN( qfalse ); /* ydnar */ +Q_EXTERN qboolean skyFixHack Q_ASSIGN( qfalse ); /* ydnar */ +Q_EXTERN qboolean bspAlternateSplitWeights Q_ASSIGN( qfalse ); /* 27 */ +Q_EXTERN qboolean deepBSP Q_ASSIGN( qfalse ); /* div0 */ +Q_EXTERN qboolean maxAreaFaceSurface Q_ASSIGN( qfalse ); /* divVerent */ + +Q_EXTERN int patchSubdivisions Q_ASSIGN( 8 ); /* ydnar: -patchmeta subdivisions */ + +Q_EXTERN int maxLMSurfaceVerts Q_ASSIGN( 64 ); /* ydnar */ +Q_EXTERN int maxSurfaceVerts Q_ASSIGN( 999 ); /* ydnar */ +Q_EXTERN int maxSurfaceIndexes Q_ASSIGN( 6000 ); /* ydnar */ +Q_EXTERN float npDegrees Q_ASSIGN( 0.0f ); /* ydnar: nonplanar degrees */ +Q_EXTERN int bevelSnap Q_ASSIGN( 0 ); /* ydnar: bevel plane snap */ +Q_EXTERN int texRange Q_ASSIGN( 0 ); +Q_EXTERN qboolean flat Q_ASSIGN( qfalse ); +Q_EXTERN qboolean meta Q_ASSIGN( qfalse ); +Q_EXTERN qboolean patchMeta Q_ASSIGN( qfalse ); +Q_EXTERN qboolean emitFlares Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugSurfaces Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugInset Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugPortals Q_ASSIGN( qfalse ); +Q_EXTERN qboolean lightmapTriangleCheck Q_ASSIGN(qfalse); +Q_EXTERN qboolean lightmapExtraVisClusterNudge Q_ASSIGN(qfalse); +Q_EXTERN qboolean lightmapFill Q_ASSIGN(qfalse); + +#if Q3MAP2_EXPERIMENTAL_SNAP_NORMAL_FIX +// Increasing the normalEpsilon to compensate for new logic in SnapNormal(), where +// this epsilon is now used to compare against 0 components instead of the 1 or -1 +// components. Unfortunately, normalEpsilon is also used in PlaneEqual(). So changing +// this will affect anything that calls PlaneEqual() as well (which are, at the time +// of this writing, FindFloatPlane() and AddBrushBevels()). +Q_EXTERN double normalEpsilon Q_ASSIGN(0.00005); +#else +Q_EXTERN double normalEpsilon Q_ASSIGN( 0.00001 ); +#endif + +#if Q3MAP2_EXPERIMENTAL_HIGH_PRECISION_MATH_FIXES +// NOTE: This distanceEpsilon is too small if parts of the map are at maximum world +// extents (in the range of plus or minus 2^16). The smallest epsilon at values +// close to 2^16 is about 0.007, which is greater than distanceEpsilon. Therefore, +// maps should be constrained to about 2^15, otherwise slightly undesirable effects +// may result. The 0.01 distanceEpsilon used previously is just too coarse in my +// opinion. The real fix for this problem is to have 64 bit distances and then make +// this epsilon even smaller, or to constrain world coordinates to plus minus 2^15 +// (or even 2^14). +Q_EXTERN double distanceEpsilon Q_ASSIGN(0.005); +#else +Q_EXTERN double distanceEpsilon Q_ASSIGN( 0.01 ); +#endif + + +/* bsp */ +Q_EXTERN int numMapEntities Q_ASSIGN( 0 ); + +Q_EXTERN int blockSize[ 3 ] /* should be the same as in radiant */ +#ifndef MAIN_C + ; +#else + = { 1024, 1024, 1024 }; +#endif + +Q_EXTERN char name[ 1024 ]; +Q_EXTERN char source[ 1024 ]; +Q_EXTERN char outbase[ 32 ]; + +Q_EXTERN int sampleSize; /* lightmap sample size in units */ +Q_EXTERN int minSampleSize; /* minimum sample size to use at all */ +Q_EXTERN int sampleScale; /* vortex: lightmap sample scale (ie quality)*/ + +Q_EXTERN int mapEntityNum Q_ASSIGN( 0 ); + +Q_EXTERN int entitySourceBrushes; + +Q_EXTERN plane_t *mapplanes Q_ASSIGN(NULL); /* mapplanes[ num ^ 1 ] will always be the mirror or mapplanes[ num ] */ +Q_EXTERN int nummapplanes Q_ASSIGN(0); /* nummapplanes will always be even */ +Q_EXTERN int allocatedmapplanes Q_ASSIGN(0); +Q_EXTERN int numMapPatches; +Q_EXTERN vec3_t mapMins, mapMaxs; + +Q_EXTERN int defaultFogNum Q_ASSIGN( -1 ); /* ydnar: cleaner fog handling */ +Q_EXTERN int numMapFogs Q_ASSIGN( 0 ); +Q_EXTERN fog_t mapFogs[ MAX_MAP_FOGS ]; + +Q_EXTERN entity_t *mapEnt; +Q_EXTERN brush_t *buildBrush; +Q_EXTERN int numActiveBrushes; +Q_EXTERN int g_bBrushPrimit; + +Q_EXTERN int numStrippedLights Q_ASSIGN( 0 ); + + +/* surface stuff */ +Q_EXTERN mapDrawSurface_t *mapDrawSurfs Q_ASSIGN( NULL ); +Q_EXTERN int numMapDrawSurfs; + +Q_EXTERN int numSurfacesByType[ NUM_SURFACE_TYPES ]; +Q_EXTERN int numClearedSurfaces; +Q_EXTERN int numStripSurfaces; +Q_EXTERN int numMaxAreaSurfaces; +Q_EXTERN int numFanSurfaces; +Q_EXTERN int numMergedSurfaces; +Q_EXTERN int numMergedVerts; + +Q_EXTERN int numRedundantIndexes; + +Q_EXTERN int numSurfaceModels Q_ASSIGN( 0 ); + +Q_EXTERN byte debugColors[ 12 ][ 3 ] +#ifndef MAIN_C + ; +#else + = + { + { 255, 0, 0 }, + { 192, 128, 128 }, + { 255, 255, 0 }, + { 192, 192, 128 }, + { 0, 255, 255 }, + { 128, 192, 192 }, + { 0, 0, 255 }, + { 128, 128, 192 }, + { 255, 0, 255 }, + { 192, 128, 192 }, + { 0, 255, 0 }, + { 128, 192, 128 } + }; +#endif + +Q_EXTERN qboolean skyboxPresent Q_ASSIGN( qfalse ); +Q_EXTERN int skyboxArea Q_ASSIGN( -1 ); +Q_EXTERN m4x4_t skyboxTransform; + + + +/* ------------------------------------------------------------------------------- + +vis global variables + +------------------------------------------------------------------------------- */ + +/* commandline arguments */ +Q_EXTERN qboolean fastvis; +Q_EXTERN qboolean noPassageVis; +Q_EXTERN qboolean passageVisOnly; +Q_EXTERN qboolean mergevis; +Q_EXTERN qboolean mergevisportals; +Q_EXTERN qboolean nosort; +Q_EXTERN qboolean saveprt; +Q_EXTERN qboolean hint; /* ydnar */ +Q_EXTERN char inbase[ MAX_QPATH ]; +Q_EXTERN char globalCelShader[ MAX_QPATH ]; + +Q_EXTERN float farPlaneDist; /* rr2do2, rf, mre, ydnar all contributed to this one... */ + +Q_EXTERN int numportals; +Q_EXTERN int portalclusters; + +Q_EXTERN vportal_t *portals; +Q_EXTERN leaf_t *leafs; + +Q_EXTERN vportal_t *faces; +Q_EXTERN leaf_t *faceleafs; + +Q_EXTERN int numfaces; + +Q_EXTERN int c_portaltest, c_portalpass, c_portalcheck; +Q_EXTERN int c_portalskip, c_leafskip; +Q_EXTERN int c_vistest, c_mighttest; +Q_EXTERN int c_chains; + +Q_EXTERN byte *vismap, *vismap_p, *vismap_end; + +Q_EXTERN int testlevel; + +Q_EXTERN byte *uncompressed; + +Q_EXTERN int leafbytes, leaflongs; +Q_EXTERN int portalbytes, portallongs; + +Q_EXTERN vportal_t *sorted_portals[ MAX_MAP_PORTALS * 2 ]; + + + +/* ------------------------------------------------------------------------------- + +light global variables + +------------------------------------------------------------------------------- */ + +/* commandline arguments */ +Q_EXTERN qboolean wolfLight Q_ASSIGN( qfalse ); +Q_EXTERN float extraDist Q_ASSIGN( 0.0f ); +Q_EXTERN qboolean loMem Q_ASSIGN( qfalse ); +Q_EXTERN qboolean noStyles Q_ASSIGN( qfalse ); +Q_EXTERN qboolean keepLights Q_ASSIGN( qfalse ); + +Q_EXTERN int sampleSize Q_ASSIGN( DEFAULT_LIGHTMAP_SAMPLE_SIZE ); +Q_EXTERN int minSampleSize Q_ASSIGN( DEFAULT_LIGHTMAP_MIN_SAMPLE_SIZE ); +Q_EXTERN qboolean noVertexLighting Q_ASSIGN( qfalse ); +Q_EXTERN qboolean noGridLighting Q_ASSIGN( qfalse ); + +Q_EXTERN qboolean noTrace Q_ASSIGN( qfalse ); +Q_EXTERN qboolean noSurfaces Q_ASSIGN( qfalse ); +Q_EXTERN qboolean patchShadows Q_ASSIGN( qfalse ); +Q_EXTERN qboolean cpmaHack Q_ASSIGN( qfalse ); + +Q_EXTERN qboolean deluxemap Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugDeluxemap Q_ASSIGN( qfalse ); +Q_EXTERN int deluxemode Q_ASSIGN( 0 ); /* deluxemap format (0 - modelspace, 1 - tangentspace with renormalization, 2 - tangentspace without renormalization) */ + +Q_EXTERN qboolean fast Q_ASSIGN( qfalse ); +Q_EXTERN qboolean faster Q_ASSIGN( qfalse ); +Q_EXTERN qboolean fastgrid Q_ASSIGN( qfalse ); +Q_EXTERN qboolean fastbounce Q_ASSIGN( qfalse ); +Q_EXTERN qboolean cheap Q_ASSIGN( qfalse ); +Q_EXTERN qboolean cheapgrid Q_ASSIGN( qfalse ); +Q_EXTERN int bounce Q_ASSIGN( 0 ); +Q_EXTERN qboolean bounceOnly Q_ASSIGN( qfalse ); +Q_EXTERN qboolean bouncing Q_ASSIGN( qfalse ); +Q_EXTERN qboolean bouncegrid Q_ASSIGN( qfalse ); +Q_EXTERN qboolean normalmap Q_ASSIGN( qfalse ); +Q_EXTERN qboolean trisoup Q_ASSIGN( qfalse ); +Q_EXTERN qboolean shade Q_ASSIGN( qfalse ); +Q_EXTERN float shadeAngleDegrees Q_ASSIGN( 0.0f ); +Q_EXTERN int superSample Q_ASSIGN( 0 ); +Q_EXTERN int lightSamples Q_ASSIGN( 1 ); +Q_EXTERN qboolean lightRandomSamples Q_ASSIGN( qfalse ); +Q_EXTERN int lightSamplesSearchBoxSize Q_ASSIGN( 1 ); +Q_EXTERN qboolean filter Q_ASSIGN( qfalse ); +Q_EXTERN qboolean dark Q_ASSIGN( qfalse ); +Q_EXTERN qboolean sunOnly Q_ASSIGN( qfalse ); +Q_EXTERN int approximateTolerance Q_ASSIGN( 0 ); +Q_EXTERN qboolean noCollapse Q_ASSIGN( qfalse ); +Q_EXTERN int lightmapSearchBlockSize Q_ASSIGN( 0 ); +Q_EXTERN qboolean exportLightmaps Q_ASSIGN( qfalse ); +Q_EXTERN qboolean externalLightmaps Q_ASSIGN( qfalse ); +Q_EXTERN int lmCustomSize Q_ASSIGN( LIGHTMAP_WIDTH ); +Q_EXTERN char * lmCustomDir Q_ASSIGN( NULL ); +Q_EXTERN int lmLimitSize Q_ASSIGN( 0 ); + +Q_EXTERN qboolean dirty Q_ASSIGN( qfalse ); +Q_EXTERN qboolean dirtDebug Q_ASSIGN( qfalse ); +Q_EXTERN int dirtMode Q_ASSIGN( 0 ); +Q_EXTERN float dirtDepth Q_ASSIGN( 128.0f ); +Q_EXTERN float dirtScale Q_ASSIGN( 1.0f ); +Q_EXTERN float dirtGain Q_ASSIGN( 1.0f ); + +/* 27: floodlighting */ +Q_EXTERN qboolean debugnormals Q_ASSIGN( qfalse ); +Q_EXTERN qboolean floodlighty Q_ASSIGN( qfalse ); +Q_EXTERN qboolean floodlight_lowquality Q_ASSIGN( qfalse ); +Q_EXTERN vec3_t floodlightRGB; +Q_EXTERN float floodlightIntensity Q_ASSIGN( 512.0f ); +Q_EXTERN float floodlightDistance Q_ASSIGN( 1024.0f ); +Q_EXTERN float floodlightDirectionScale Q_ASSIGN( 1.0f ); + +Q_EXTERN qboolean dump Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debug Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugUnused Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugAxis Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugCluster Q_ASSIGN( qfalse ); +Q_EXTERN qboolean debugOrigin Q_ASSIGN( qfalse ); +Q_EXTERN qboolean lightmapBorder Q_ASSIGN( qfalse ); + +/* longest distance across the map */ +Q_EXTERN float maxMapDistance Q_ASSIGN( 0 ); + +/* for run time tweaking of light sources */ +Q_EXTERN float pointScale Q_ASSIGN( 7500.0f ); +Q_EXTERN float areaScale Q_ASSIGN( 0.25f ); +Q_EXTERN float skyScale Q_ASSIGN( 1.0f ); +Q_EXTERN float bounceScale Q_ASSIGN( 0.25f ); + +/* jal: alternative angle attenuation curve */ +Q_EXTERN qboolean lightAngleHL Q_ASSIGN( qfalse ); + +/* vortex: gridscale and gridambientscale */ +Q_EXTERN float gridScale Q_ASSIGN( 1.0f ); +Q_EXTERN float gridAmbientScale Q_ASSIGN( 1.0f ); +Q_EXTERN float gridDirectionality Q_ASSIGN( 1.0f ); +Q_EXTERN float gridAmbientDirectionality Q_ASSIGN( 0.0f ); +Q_EXTERN qboolean inGrid Q_ASSIGN(0); + +/* ydnar: lightmap gamma/compensation */ +Q_EXTERN float lightmapGamma Q_ASSIGN( 1.0f ); +Q_EXTERN float lightmapExposure Q_ASSIGN( 1.0f ); +Q_EXTERN float lightmapCompensate Q_ASSIGN( 1.0f ); + +/* ydnar: for runtime tweaking of falloff tolerance */ +Q_EXTERN float falloffTolerance Q_ASSIGN( 1.0f ); +Q_EXTERN qboolean exactPointToPolygon Q_ASSIGN( qtrue ); +Q_EXTERN float formFactorValueScale Q_ASSIGN( 3.0f ); +Q_EXTERN float linearScale Q_ASSIGN( 1.0f / 8000.0f ); + +// for .ase conversion +Q_EXTERN qboolean shadersAsBitmap Q_ASSIGN( qfalse ); +Q_EXTERN qboolean lightmapsAsTexcoord Q_ASSIGN( qfalse ); + +Q_EXTERN light_t *lights; +Q_EXTERN int numPointLights; +Q_EXTERN int numSpotLights; +Q_EXTERN int numSunLights; +Q_EXTERN int numAreaLights; + +/* ydnar: for luxel placement */ +Q_EXTERN int numSurfaceClusters, maxSurfaceClusters; +Q_EXTERN int *surfaceClusters; + +/* ydnar: for radiosity */ +Q_EXTERN int numDiffuseLights; +Q_EXTERN int numBrushDiffuseLights; +Q_EXTERN int numTriangleDiffuseLights; +Q_EXTERN int numPatchDiffuseLights; + +/* ydnar: general purpose extra copy of drawvert list */ +Q_EXTERN bspDrawVert_t *yDrawVerts; + +/* ydnar: for tracing statistics */ +Q_EXTERN int minSurfacesTested; +Q_EXTERN int maxSurfacesTested; +Q_EXTERN int totalSurfacesTested; +Q_EXTERN int totalTraces; + +Q_EXTERN FILE *dumpFile; + +Q_EXTERN int c_visible, c_occluded; +Q_EXTERN int c_subsampled; /* ydnar */ + +Q_EXTERN int defaultLightSubdivide Q_ASSIGN( 999 ); + +Q_EXTERN vec3_t ambientColor; +Q_EXTERN vec3_t minLight, minVertexLight, minGridLight; + +Q_EXTERN int *entitySurface; +Q_EXTERN vec3_t *surfaceOrigin; + +Q_EXTERN vec3_t sunDirection; +Q_EXTERN vec3_t sunLight; + +/* tracing */ +Q_EXTERN int c_totalTrace; +Q_EXTERN int c_cullTrace, c_testTrace; +Q_EXTERN int c_testFacets; + +/* ydnar: light optimization */ +Q_EXTERN float subdivideThreshold Q_ASSIGN( DEFAULT_SUBDIVIDE_THRESHOLD ); + +Q_EXTERN int numOpaqueBrushes, maxOpaqueBrush; +Q_EXTERN byte *opaqueBrushes; + +Q_EXTERN int numLights; +Q_EXTERN int numCulledLights; + +Q_EXTERN int gridBoundsCulled; +Q_EXTERN int gridEnvelopeCulled; + +Q_EXTERN int lightsBoundsCulled; +Q_EXTERN int lightsEnvelopeCulled; +Q_EXTERN int lightsPlaneCulled; +Q_EXTERN int lightsClusterCulled; + +/* ydnar: radiosity */ +Q_EXTERN float diffuseSubdivide Q_ASSIGN( 256.0f ); +Q_EXTERN float minDiffuseSubdivide Q_ASSIGN( 64.0f ); +Q_EXTERN int numDiffuseSurfaces Q_ASSIGN( 0 ); + +/* ydnar: list of surface information necessary for lightmap calculation */ +Q_EXTERN surfaceInfo_t *surfaceInfos Q_ASSIGN( NULL ); + +/* ydnar: sorted list of surfaces */ +Q_EXTERN int *sortSurfaces Q_ASSIGN( NULL ); + +/* clumps of surfaces that share a raw lightmap */ +Q_EXTERN int numLightSurfaces Q_ASSIGN( 0 ); +Q_EXTERN int *lightSurfaces Q_ASSIGN( NULL ); + +/* raw lightmaps */ +Q_EXTERN int numRawSuperLuxels Q_ASSIGN( 0 ); +Q_EXTERN int numRawLightmaps Q_ASSIGN( 0 ); +Q_EXTERN rawLightmap_t *rawLightmaps Q_ASSIGN( NULL ); +Q_EXTERN int *sortLightmaps Q_ASSIGN( NULL ); + +/* vertex luxels */ +Q_EXTERN float *vertexLuxels[ MAX_LIGHTMAPS ]; +Q_EXTERN float *radVertexLuxels[ MAX_LIGHTMAPS ]; + +/* bsp lightmaps */ +Q_EXTERN int numLightmapShaders Q_ASSIGN( 0 ); +Q_EXTERN int numSolidLightmaps Q_ASSIGN( 0 ); +Q_EXTERN int numOutLightmaps Q_ASSIGN( 0 ); +Q_EXTERN int numBSPLightmaps Q_ASSIGN( 0 ); +Q_EXTERN int numExtLightmaps Q_ASSIGN( 0 ); +Q_EXTERN outLightmap_t *outLightmaps Q_ASSIGN( NULL ); + +/* vortex: per surface floodlight statictics */ +Q_EXTERN int numSurfacesFloodlighten Q_ASSIGN( 0 ); + +/* grid points */ +Q_EXTERN int numRawGridPoints Q_ASSIGN( 0 ); +Q_EXTERN rawGridPoint_t *rawGridPoints Q_ASSIGN( NULL ); + +Q_EXTERN int numSurfsVertexLit Q_ASSIGN( 0 ); +Q_EXTERN int numSurfsVertexForced Q_ASSIGN( 0 ); +Q_EXTERN int numSurfsVertexApproximated Q_ASSIGN( 0 ); +Q_EXTERN int numSurfsLightmapped Q_ASSIGN( 0 ); +Q_EXTERN int numPlanarsLightmapped Q_ASSIGN( 0 ); +Q_EXTERN int numNonPlanarsLightmapped Q_ASSIGN( 0 ); +Q_EXTERN int numPatchesLightmapped Q_ASSIGN( 0 ); +Q_EXTERN int numPlanarPatchesLightmapped Q_ASSIGN( 0 ); + +Q_EXTERN int numLuxels Q_ASSIGN( 0 ); +Q_EXTERN int numLuxelsMapped Q_ASSIGN( 0 ); +Q_EXTERN int numLuxelsOccluded Q_ASSIGN( 0 ); +Q_EXTERN int numLuxelsIlluminated Q_ASSIGN( 0 ); +Q_EXTERN int numVertsIlluminated Q_ASSIGN( 0 ); + +/* lightgrid */ +Q_EXTERN vec3_t gridMins; +Q_EXTERN int gridBounds[ 3 ]; +Q_EXTERN vec3_t gridSize +#ifndef MAIN_C + ; +#else + = { 64, 64, 128 }; +#endif + + + +/* ------------------------------------------------------------------------------- + +abstracted bsp globals + +------------------------------------------------------------------------------- */ + +Q_EXTERN int numEntities Q_ASSIGN( 0 ); +Q_EXTERN int numBSPEntities Q_ASSIGN( 0 ); +Q_EXTERN entity_t entities[ MAX_MAP_ENTITIES ]; + +Q_EXTERN int numBSPModels Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPModels Q_ASSIGN( 0 ); +Q_EXTERN bspModel_t* bspModels Q_ASSIGN(NULL); + +Q_EXTERN int numBSPShaders Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPShaders Q_ASSIGN( 0 ); +Q_EXTERN bspShader_t* bspShaders Q_ASSIGN(0); + +Q_EXTERN int bspEntDataSize Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPEntData Q_ASSIGN( 0 ); +Q_EXTERN char *bspEntData Q_ASSIGN(0); + +Q_EXTERN int numBSPLeafs Q_ASSIGN( 0 ); +Q_EXTERN bspLeaf_t bspLeafs[ MAX_MAP_LEAFS ]; + +Q_EXTERN int numBSPPlanes Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPPlanes Q_ASSIGN(0); +Q_EXTERN bspPlane_t *bspPlanes; + +Q_EXTERN int numBSPNodes Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPNodes Q_ASSIGN( 0 ); +Q_EXTERN bspNode_t* bspNodes Q_ASSIGN(NULL); + +Q_EXTERN int numBSPLeafSurfaces Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPLeafSurfaces Q_ASSIGN( 0 ); +Q_EXTERN int* bspLeafSurfaces Q_ASSIGN(NULL); + +Q_EXTERN int numBSPLeafBrushes Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPLeafBrushes Q_ASSIGN( 0 ); +Q_EXTERN int* bspLeafBrushes Q_ASSIGN(NULL); + +Q_EXTERN int numBSPBrushes Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPBrushes Q_ASSIGN( 0 ); +Q_EXTERN bspBrush_t* bspBrushes Q_ASSIGN(NULL); + +Q_EXTERN int numBSPBrushSides Q_ASSIGN( 0 ); +Q_EXTERN int allocatedBSPBrushSides Q_ASSIGN( 0 ); +Q_EXTERN bspBrushSide_t* bspBrushSides Q_ASSIGN(NULL); + +Q_EXTERN int numBSPLightBytes Q_ASSIGN( 0 ); +Q_EXTERN byte *bspLightBytes Q_ASSIGN( NULL ); + +//% Q_EXTERN int numBSPGridPoints Q_ASSIGN( 0 ); +//% Q_EXTERN byte *bspGridPoints Q_ASSIGN( NULL ); + +Q_EXTERN int numBSPGridPoints Q_ASSIGN( 0 ); +Q_EXTERN bspGridPoint_t *bspGridPoints Q_ASSIGN( NULL ); + +Q_EXTERN int numBSPVisBytes Q_ASSIGN( 0 ); +Q_EXTERN byte bspVisBytes[ MAX_MAP_VISIBILITY ]; + +Q_EXTERN int numBSPDrawVerts Q_ASSIGN( 0 ); +Q_EXTERN bspDrawVert_t *bspDrawVerts Q_ASSIGN( NULL ); + +Q_EXTERN int numBSPDrawIndexes Q_ASSIGN( 0 ); +Q_EXTERN int bspDrawIndexes[ MAX_MAP_DRAW_INDEXES ]; + +Q_EXTERN int numBSPDrawSurfaces Q_ASSIGN( 0 ); +Q_EXTERN bspDrawSurface_t *bspDrawSurfaces Q_ASSIGN( NULL ); + +Q_EXTERN int numBSPFogs Q_ASSIGN( 0 ); +Q_EXTERN bspFog_t bspFogs[ MAX_MAP_FOGS ]; + +Q_EXTERN int numBSPAds Q_ASSIGN( 0 ); +Q_EXTERN bspAdvertisement_t bspAds[ MAX_MAP_ADVERTISEMENTS ]; + +#define AUTOEXPAND_BY_REALLOC(ptr, reqitem, allocated, def) \ + do \ + { \ + if(reqitem >= allocated) \ + { \ + if(allocated == 0) \ + allocated = def; \ + while(reqitem >= allocated && allocated) \ + allocated *= 2; \ + if(!allocated || allocated > 2147483647 / (int)sizeof(*ptr)) \ + { \ + Error(#ptr " over 2 GB"); \ + } \ + ptr = realloc(ptr, sizeof(*ptr) * allocated); \ + if(!ptr) \ + Error(#ptr " out of memory"); \ + } \ + } \ + while(0) + +#define AUTOEXPAND_BY_REALLOC_BSP(suffix, def) AUTOEXPAND_BY_REALLOC(bsp##suffix, numBSP##suffix, allocatedBSP##suffix, def) + +/* end marker */ +#endif diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.ico b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.ico new file mode 100644 index 00000000..4fe56fa6 Binary files /dev/null and b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.ico differ diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.rc b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.rc new file mode 100644 index 00000000..bc120375 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2.rc @@ -0,0 +1 @@ +101 ICON DISCARDABLE "q3map2.ico" diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2_fsr_newfiles/q3map2_fsr_svn158.patch b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2_fsr_newfiles/q3map2_fsr_svn158.patch new file mode 100644 index 00000000..0df87e49 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/q3map2_fsr_newfiles/q3map2_fsr_svn158.patch @@ -0,0 +1,19 @@ +Index: light.c +=================================================================== +--- light.c (revision 158) ++++ light.c (working copy) +@@ -357,12 +365,13 @@ + intensity *= scale; + + /* ydnar: get deviance and samples */ ++ /* VorteX: now set start value for _samples when _deviance is found */ + deviance = FloatForKey( e, "_deviance" ); + if( deviance == 0.0f ) + deviance = FloatForKey( e, "_deviation" ); + if( deviance == 0.0f ) + deviance = FloatForKey( e, "_jitter" ); +- numSamples = IntForKey( e, "_samples" ); ++ numSamples = max(IntForKey( e, "_samples" ), deviance); + if( deviance < 0.0f || numSamples < 1 ) + { + deviance = 0.0f; diff --git a/misc/mediasource/netradiant-src/tools/quake3/q3map2/shaders.c b/misc/mediasource/netradiant-src/tools/quake3/q3map2/shaders.c new file mode 100644 index 00000000..3bf6cbe1 --- /dev/null +++ b/misc/mediasource/netradiant-src/tools/quake3/q3map2/shaders.c @@ -0,0 +1,2153 @@ +/* ------------------------------------------------------------------------------- + +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 + +---------------------------------------------------------------------------------- + +This code has been altered significantly from its original form, to support +several games based on the Quake III Arena engine, in the form of "Q3Map2." + +------------------------------------------------------------------------------- */ + + + +/* marker */ +#define SHADERS_C + + + +/* dependencies */ +#include "q3map2.h" + + + +/* +ColorMod() +routines for dealing with vertex color/alpha modification +*/ + +void ColorMod( colorMod_t *cm, int numVerts, bspDrawVert_t *drawVerts ) +{ + int i, j, k; + float c; + vec4_t mult, add; + bspDrawVert_t *dv; + colorMod_t *cm2; + + + /* dummy check */ + if( cm == NULL || numVerts < 1 || drawVerts == NULL ) + return; + + + /* walk vertex list */ + for( i = 0; i < numVerts; i++ ) + { + /* get vertex */ + dv = &drawVerts[ i ]; + + /* walk colorMod list */ + for( cm2 = cm; cm2 != NULL; cm2 = cm2->next ) + { + /* default */ + VectorSet( mult, 1.0f, 1.0f, 1.0f ); + mult[ 3 ] = 1.0f; + VectorSet( add, 0.0f, 0.0f, 0.0f ); + mult[ 3 ] = 0.0f; + + /* switch on type */ + switch( cm2->type ) + { + case CM_COLOR_SET: + VectorClear( mult ); + VectorScale( cm2->data, 255.0f, add ); + break; + + case CM_ALPHA_SET: + mult[ 3 ] = 0.0f; + add[ 3 ] = cm2->data[ 0 ] * 255.0f; + break; + + case CM_COLOR_SCALE: + VectorCopy( cm2->data, mult ); + break; + + case CM_ALPHA_SCALE: + mult[ 3 ] = cm2->data[ 0 ]; + break; + + case CM_COLOR_DOT_PRODUCT: + c = DotProduct( dv->normal, cm2->data ); + VectorSet( mult, c, c, c ); + break; + + case CM_COLOR_DOT_PRODUCT_SCALE: + c = DotProduct( dv->normal, cm2->data ); + c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); + VectorSet( mult, c, c, c ); + break; + + case CM_ALPHA_DOT_PRODUCT: + mult[ 3 ] = DotProduct( dv->normal, cm2->data ); + break; + + case CM_ALPHA_DOT_PRODUCT_SCALE: + c = DotProduct( dv->normal, cm2->data ); + c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); + mult[ 3 ] = c; + break; + + case CM_COLOR_DOT_PRODUCT_2: + c = DotProduct( dv->normal, cm2->data ); + c *= c; + VectorSet( mult, c, c, c ); + break; + + case CM_COLOR_DOT_PRODUCT_2_SCALE: + c = DotProduct( dv->normal, cm2->data ); + c *= c; + c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); + VectorSet( mult, c, c, c ); + break; + + case CM_ALPHA_DOT_PRODUCT_2: + mult[ 3 ] = DotProduct( dv->normal, cm2->data ); + mult[ 3 ] *= mult[ 3 ]; + break; + + case CM_ALPHA_DOT_PRODUCT_2_SCALE: + c = DotProduct( dv->normal, cm2->data ); + c *= c; + c = (c - cm2->data[3]) / (cm2->data[4] - cm2->data[3]); + mult[ 3 ] = c; + break; + + default: + break; + } + + /* apply mod */ + for( j = 0; j < MAX_LIGHTMAPS; j++ ) + { + for( k = 0; k < 4; k++ ) + { + c = (mult[ k ] * dv->color[ j ][ k ]) + add[ k ]; + if( c < 0 ) + c = 0; + else if( c > 255 ) + c = 255; + dv->color[ j ][ k ] = c; + } + } + } + } +} + + + +/* +TCMod*() +routines for dealing with a 3x3 texture mod matrix +*/ + +void TCMod( tcMod_t mod, float st[ 2 ] ) +{ + float old[ 2 ]; + + + old[ 0 ] = st[ 0 ]; + old[ 1 ] = st[ 1 ]; + st[ 0 ] = (mod[ 0 ][ 0 ] * old[ 0 ]) + (mod[ 0 ][ 1 ] * old[ 1 ]) + mod[ 0 ][ 2 ]; + st[ 1 ] = (mod[ 1 ][ 0 ] * old[ 0 ]) + (mod[ 1 ][ 1 ] * old[ 1 ]) + mod[ 1 ][ 2 ]; +} + + +void TCModIdentity( tcMod_t mod ) +{ + mod[ 0 ][ 0 ] = 1.0f; mod[ 0 ][ 1 ] = 0.0f; mod[ 0 ][ 2 ] = 0.0f; + mod[ 1 ][ 0 ] = 0.0f; mod[ 1 ][ 1 ] = 1.0f; mod[ 1 ][ 2 ] = 0.0f; + mod[ 2 ][ 0 ] = 0.0f; mod[ 2 ][ 1 ] = 0.0f; mod[ 2 ][ 2 ] = 1.0f; /* this row is only used for multiples, not transformation */ +} + + +void TCModMultiply( tcMod_t a, tcMod_t b, tcMod_t out ) +{ + int i; + + + for( i = 0; i < 3; i++ ) + { + out[ i ][ 0 ] = (a[ i ][ 0 ] * b[ 0 ][ 0 ]) + (a[ i ][ 1 ] * b[ 1 ][ 0 ]) + (a[ i ][ 2 ] * b[ 2 ][ 0 ]); + out[ i ][ 1 ] = (a[ i ][ 0 ] * b[ 0 ][ 1 ]) + (a[ i ][ 1 ] * b[ 1 ][ 1 ]) + (a[ i ][ 2 ] * b[ 2 ][ 1 ]); + out[ i ][ 2 ] = (a[ i ][ 0 ] * b[ 0 ][ 2 ]) + (a[ i ][ 1 ] * b[ 1 ][ 2 ]) + (a[ i ][ 2 ] * b[ 2 ][ 2 ]); + } +} + + +void TCModTranslate( tcMod_t mod, float s, float t ) +{ + mod[ 0 ][ 2 ] += s; + mod[ 1 ][ 2 ] += t; +} + + +void TCModScale( tcMod_t mod, float s, float t ) +{ + mod[ 0 ][ 0 ] *= s; + mod[ 1 ][ 1 ] *= t; +} + + +void TCModRotate( tcMod_t mod, float euler ) +{ + tcMod_t old, temp; + float radians, sinv, cosv; + + + memcpy( old, mod, sizeof( tcMod_t ) ); + TCModIdentity( temp ); + + radians = euler / 180 * Q_PI; + sinv = sin( radians ); + cosv = cos( radians ); + + temp[ 0 ][ 0 ] = cosv; temp[ 0 ][ 1 ] = -sinv; + temp[ 1 ][ 0 ] = sinv; temp[ 1 ][ 1 ] = cosv; + + TCModMultiply( old, temp, mod ); +} + + + +/* +ApplySurfaceParm() - ydnar +applies a named surfaceparm to the supplied flags +*/ + +qboolean ApplySurfaceParm( char *name, int *contentFlags, int *surfaceFlags, int *compileFlags ) +{ + int i, fake; + surfaceParm_t *sp; + + + /* dummy check */ + if( name == NULL ) + name = ""; + if( contentFlags == NULL ) + contentFlags = &fake; + if( surfaceFlags == NULL ) + surfaceFlags = &fake; + if( compileFlags == NULL ) + compileFlags = &fake; + + /* walk the current game's surfaceparms */ + sp = game->surfaceParms; + while( sp->name != NULL ) + { + /* match? */ + if( !Q_stricmp( name, sp->name ) ) + { + /* clear and set flags */ + *contentFlags &= ~(sp->contentFlagsClear); + *contentFlags |= sp->contentFlags; + *surfaceFlags &= ~(sp->surfaceFlagsClear); + *surfaceFlags |= sp->surfaceFlags; + *compileFlags &= ~(sp->compileFlagsClear); + *compileFlags |= sp->compileFlags; + + /* return ok */ + return qtrue; + } + + /* next */ + sp++; + } + + /* check custom info parms */ + for( i = 0; i < numCustSurfaceParms; i++ ) + { + /* get surfaceparm */ + sp = &custSurfaceParms[ i ]; + + /* match? */ + if( !Q_stricmp( name, sp->name ) ) + { + /* clear and set flags */ + *contentFlags &= ~(sp->contentFlagsClear); + *contentFlags |= sp->contentFlags; + *surfaceFlags &= ~(sp->surfaceFlagsClear); + *surfaceFlags |= sp->surfaceFlags; + *compileFlags &= ~(sp->compileFlagsClear); + *compileFlags |= sp->compileFlags; + + /* return ok */ + return qtrue; + } + } + + /* no matching surfaceparm found */ + return qfalse; +} + + + +/* +BeginMapShaderFile() - ydnar +erases and starts a new map shader script +*/ + +void BeginMapShaderFile( const char *mapFile ) +{ + char base[ 1024 ]; + int len; + + + /* dummy check */ + mapName[ 0 ] = '\0'; + mapShaderFile[ 0 ] = '\0'; + if( mapFile == NULL || mapFile[ 0 ] == '\0' ) + return; + + /* copy map name */ + strcpy( base, mapFile ); + StripExtension( base ); + + /* extract map name */ + len = strlen( base ) - 1; + while( len > 0 && base[ len ] != '/' && base[ len ] != '\\' ) + len--; + strcpy( mapName, &base[ len + 1 ] ); + base[ len ] = '\0'; + if( len <= 0 ) + return; + + /* append ../scripts/q3map2_.shader */ + sprintf( mapShaderFile, "%s/../%s/q3map2_%s.shader", base, game->shaderPath, mapName ); + Sys_FPrintf( SYS_VRB, "Map has shader script %s\n", mapShaderFile ); + + /* remove it */ + remove( mapShaderFile ); + + /* stop making warnings about missing images */ + warnImage = qfalse; +} + + + +/* +WriteMapShaderFile() - ydnar +writes a shader to the map shader script +*/ + +void WriteMapShaderFile( void ) +{ + FILE *file; + shaderInfo_t *si; + int i, num; + + + /* dummy check */ + if( mapShaderFile[ 0 ] == '\0' ) + return; + + /* are there any custom shaders? */ + for( i = 0, num = 0; i < numShaderInfo; i++ ) + { + if( shaderInfo[ i ].custom ) + break; + } + if( i == numShaderInfo ) + return; + + /* note it */ + Sys_FPrintf( SYS_VRB, "--- WriteMapShaderFile ---\n"); + Sys_FPrintf( SYS_VRB, "Writing %s", mapShaderFile ); + + /* open shader file */ + file = fopen( mapShaderFile, "w" ); + if( file == NULL ) + { + Sys_Printf( "WARNING: Unable to open map shader file %s for writing\n", mapShaderFile ); + return; + } + + /* print header */ + fprintf( file, + "// Custom shader file for %s.bsp\n" + "// Generated by Q3Map2 (ydnar)\n" + "// Do not edit! This file is overwritten on recompiles.\n\n", + mapName ); + + /* walk the shader list */ + for( i = 0, num = 0; i < numShaderInfo; i++ ) + { + /* get the shader and print it */ + si = &shaderInfo[ i ]; + if( si->custom == qfalse || si->shaderText == NULL || si->shaderText[ 0 ] == '\0' ) + continue; + num++; + + /* print it to the file */ + fprintf( file, "%s%s\n", si->shader, si->shaderText ); + //Sys_Printf( "%s%s\n", si->shader, si->shaderText ); /* FIXME: remove debugging code */ + + Sys_FPrintf( SYS_VRB, "." ); + } + + /* close the shader */ + fflush( file ); + fclose( file ); + + Sys_FPrintf( SYS_VRB, "\n" ); + + /* print some stats */ + Sys_Printf( "%9d custom shaders emitted\n", num ); +} + + + +/* +CustomShader() - ydnar +sets up a custom map shader +*/ + +shaderInfo_t *CustomShader( shaderInfo_t *si, char *find, char *replace ) +{ + shaderInfo_t *csi; + char shader[ MAX_QPATH ]; + char *s; + int loc; + byte digest[ 16 ]; + char *srcShaderText, temp[ 8192 ], shaderText[ 8192 ]; /* ydnar: fixme (make this bigger?) */ + + + /* dummy check */ + if( si == NULL ) + return ShaderInfoForShader( "default" ); + + /* default shader text source */ + srcShaderText = si->shaderText; + + /* et: implicitMap */ + if( si->implicitMap == IM_OPAQUE ) + { + srcShaderText = temp; + sprintf( temp, "\n" + "{ // Q3Map2 defaulted (implicitMap)\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t}\n" + "\tq3map_styleMarker\n" + "\t{\n" + "\t\tmap %s\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t\trgbGen identity\n" + "\t}\n" + "}\n", + si->implicitImagePath ); + } + + /* et: implicitMask */ + else if( si->implicitMap == IM_MASKED ) + { + srcShaderText = temp; + sprintf( temp, "\n" + "{ // Q3Map2 defaulted (implicitMask)\n" + "\tcull none\n" + "\t{\n" + "\t\tmap %s\n" + "\t\talphaFunc GE128\n" + "\t\tdepthWrite\n" + "\t}\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t\tdepthFunc equal\n" + "\t}\n" + "\tq3map_styleMarker\n" + "\t{\n" + "\t\tmap %s\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t\tdepthFunc equal\n" + "\t\trgbGen identity\n" + "\t}\n" + "}\n", + si->implicitImagePath, + si->implicitImagePath ); + } + + /* et: implicitBlend */ + else if( si->implicitMap == IM_BLEND ) + { + srcShaderText = temp; + sprintf( temp, "\n" + "{ // Q3Map2 defaulted (implicitBlend)\n" + "\tcull none\n" + "\t{\n" + "\t\tmap %s\n" + "\t\tblendFunc GL_SRC_ALPHA GL_ONE_MINUS_SRC_ALPHA\n" + "\t}\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t}\n" + "\tq3map_styleMarker\n" + "}\n", + si->implicitImagePath ); + } + + /* default shader text */ + else if( srcShaderText == NULL ) + { + srcShaderText = temp; + sprintf( temp, "\n" + "{ // Q3Map2 defaulted\n" + "\t{\n" + "\t\tmap $lightmap\n" + "\t\trgbGen identity\n" + "\t}\n" + "\tq3map_styleMarker\n" + "\t{\n" + "\t\tmap %s.tga\n" + "\t\tblendFunc GL_DST_COLOR GL_ZERO\n" + "\t\trgbGen identity\n" + "\t}\n" + "}\n", + si->shader ); + } + + /* error check */ + if( (strlen( mapName ) + 1 + 32) > MAX_QPATH ) + Error( "Custom shader name length (%d) exceeded. Shorten your map name.\n", MAX_QPATH ); + + /* do some bad find-replace */ + s = strstr( srcShaderText, find ); + if( s == NULL ) + //% strcpy( shaderText, srcShaderText ); + return si; /* testing just using the existing shader if this fails */ + else + { + /* substitute 'find' with 'replace' */ + loc = s - srcShaderText; + strcpy( shaderText, srcShaderText ); + shaderText[ loc ] = '\0'; + strcat( shaderText, replace ); + strcat( shaderText, &srcShaderText[ loc + strlen( find ) ] ); + } + + /* make md4 hash of the shader text */ + Com_BlockFullChecksum(shaderText, strlen(shaderText), digest); + + /* mangle hash into a shader name */ + sprintf( shader, "%s/%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", mapName, + digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], + digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ], digest[ 15 ] ); + + /* get shader */ + csi = ShaderInfoForShader( shader ); + + /* might be a preexisting shader */ + if( csi->custom ) + return csi; + + /* clone the existing shader and rename */ + memcpy( csi, si, sizeof( shaderInfo_t ) ); + strcpy( csi->shader, shader ); + csi->custom = qtrue; + + /* store new shader text */ + csi->shaderText = safe_malloc( strlen( shaderText ) + 1 ); + strcpy( csi->shaderText, shaderText ); /* LEAK! */ + + /* return it */ + return csi; +} + + + +/* +EmitVertexRemapShader() +adds a vertexremapshader key/value pair to worldspawn +*/ + +void EmitVertexRemapShader( char *from, char *to ) +{ + byte digest[ 16 ]; + char key[ 64 ], value[ 256 ]; + + + /* dummy check */ + if( from == NULL || from[ 0 ] == '\0' || + to == NULL || to[ 0 ] == '\0' ) + return; + + /* build value */ + sprintf( value, "%s;%s", from, to ); + + /* make md4 hash */ + Com_BlockFullChecksum(value, strlen(value), digest); + + /* make key (this is annoying, as vertexremapshader is precisely 17 characters, + which is one too long, so we leave off the last byte of the md5 digest) */ + sprintf( key, "vertexremapshader%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", + digest[ 0 ], digest[ 1 ], digest[ 2 ], digest[ 3 ], digest[ 4 ], digest[ 5 ], digest[ 6 ], digest[ 7 ], + digest[ 8 ], digest[ 9 ], digest[ 10 ], digest[ 11 ], digest[ 12 ], digest[ 13 ], digest[ 14 ] ); /* no: digest[ 15 ] */ + + /* add key/value pair to worldspawn */ + SetKeyValue( &entities[ 0 ], key, value ); +} + + + +/* +AllocShaderInfo() +allocates and initializes a new shader +*/ + +static shaderInfo_t *AllocShaderInfo( void ) +{ + shaderInfo_t *si; + + + /* allocate? */ + if( shaderInfo == NULL ) + { + shaderInfo = safe_malloc( sizeof( shaderInfo_t ) * MAX_SHADER_INFO ); + numShaderInfo = 0; + } + + /* bounds check */ + if( numShaderInfo == MAX_SHADER_INFO ) + Error( "MAX_SHADER_INFO exceeded. Remove some PK3 files or shader scripts from shaderlist.txt and try again." ); + si = &shaderInfo[ numShaderInfo ]; + numShaderInfo++; + + /* ydnar: clear to 0 first */ + memset( si, 0, sizeof( shaderInfo_t ) ); + + /* set defaults */ + ApplySurfaceParm( "default", &si->contentFlags, &si->surfaceFlags, &si->compileFlags ); + + si->backsplashFraction = DEF_BACKSPLASH_FRACTION; + si->backsplashDistance = DEF_BACKSPLASH_DISTANCE; + + si->bounceScale = DEF_RADIOSITY_BOUNCE; + + si->lightStyle = LS_NORMAL; + + si->polygonOffset = qfalse; + + si->shadeAngleDegrees = 0.0f; + si->lightmapSampleSize = 0; + si->lightmapSampleOffset = DEFAULT_LIGHTMAP_SAMPLE_OFFSET; + si->patchShadows = qfalse; + si->vertexShadows = qtrue; /* ydnar: changed default behavior */ + si->forceSunlight = qfalse; + si->vertexScale = 1.0; + si->notjunc = qfalse; + + /* ydnar: set texture coordinate transform matrix to identity */ + TCModIdentity( si->mod ); + + /* ydnar: lightmaps can now be > 128x128 in certain games or an externally generated tga */ + si->lmCustomWidth = lmCustomSize; + si->lmCustomHeight = lmCustomSize; + + /* return to sender */ + return si; +} + + + +/* +FinishShader() - ydnar +sets a shader's width and height among other things +*/ + +void FinishShader( shaderInfo_t *si ) +{ + int x, y; + float st[ 2 ], o[ 2 ], dist, bestDist; + vec4_t color, bestColor, delta; + + + /* don't double-dip */ + if( si->finished ) + return; + + /* if they're explicitly set, copy from image size */ + if( si->shaderWidth == 0 && si->shaderHeight == 0 ) + { + si->shaderWidth = si->shaderImage->width; + si->shaderHeight = si->shaderImage->height; + } + + /* legacy terrain has explicit image-sized texture projection */ + if( si->legacyTerrain && si->tcGen == qfalse ) + { + /* set xy texture projection */ + si->tcGen = qtrue; + VectorSet( si->vecs[ 0 ], (1.0f / (si->shaderWidth * 0.5f)), 0, 0 ); + VectorSet( si->vecs[ 1 ], 0, (1.0f / (si->shaderHeight * 0.5f)), 0 ); + } + + /* find pixel coordinates best matching the average color of the image */ + bestDist = 99999999; + o[ 0 ] = 1.0f / si->shaderImage->width; + o[ 1 ] = 1.0f / si->shaderImage->height; + for( y = 0, st[ 1 ] = 0.0f; y < si->shaderImage->height; y++, st[ 1 ] += o[ 1 ] ) + { + for( x = 0, st[ 0 ] = 0.0f; x < si->shaderImage->width; x++, st[ 0 ] += o[ 0 ] ) + { + /* sample the shader image */ + RadSampleImage( si->shaderImage->pixels, si->shaderImage->width, si->shaderImage->height, st, color ); + + /* determine error squared */ + VectorSubtract( color, si->averageColor, delta ); + delta[ 3 ] = color[ 3 ] - si->averageColor[ 3 ]; + dist = delta[ 0 ] * delta[ 0 ] + delta[ 1 ] * delta[ 1 ] + delta[ 2 ] * delta[ 2 ] + delta[ 3 ] * delta[ 3 ]; + if( dist < bestDist ) + { + VectorCopy( color, bestColor ); + bestColor[ 3 ] = color[ 3 ]; + si->stFlat[ 0 ] = st[ 0 ]; + si->stFlat[ 1 ] = st[ 1 ]; + } + } + } + + /* set to finished */ + si->finished = qtrue; +} + + + +/* +LoadShaderImages() +loads a shader's images +ydnar: image.c made this a bit simpler +*/ + +static void LoadShaderImages( shaderInfo_t *si ) +{ + int i, count; + float color[ 4 ]; + + + /* nodraw shaders don't need images */ + if( si->compileFlags & C_NODRAW ) + si->shaderImage = ImageLoad( DEFAULT_IMAGE ); + else + { + /* try to load editor image first */ + si->shaderImage = ImageLoad( si->editorImagePath ); + + /* then try shadername */ + if( si->shaderImage == NULL ) + si->shaderImage = ImageLoad( si->shader ); + + /* then try implicit image path (note: new behavior!) */ + if( si->shaderImage == NULL ) + si->shaderImage = ImageLoad( si->implicitImagePath ); + + /* then try lightimage (note: new behavior!) */ + if( si->shaderImage == NULL ) + si->shaderImage = ImageLoad( si->lightImagePath ); + + /* otherwise, use default image */ + if( si->shaderImage == NULL ) + { + si->shaderImage = ImageLoad( DEFAULT_IMAGE ); + if( warnImage && strcmp( si->shader, "noshader" ) ) + Sys_Printf( "WARNING: Couldn't find image for shader %s\n", si->shader ); + } + + /* load light image */ + si->lightImage = ImageLoad( si->lightImagePath ); + + /* load normalmap image (ok if this is NULL) */ + si->normalImage = ImageLoad( si->normalImagePath ); + if( si->normalImage != NULL ) + { + Sys_FPrintf( SYS_VRB, "Shader %s has\n" + " NM %s\n", si->shader, si->normalImagePath ); + } + } + + /* if no light image, use shader image */ + if( si->lightImage == NULL ) + si->lightImage = ImageLoad( si->shaderImage->name ); + + /* create default and average colors */ + count = si->lightImage->width * si->lightImage->height; + VectorClear( color ); + color[ 3 ] = 0.0f; + for( i = 0; i < count; i++ ) + { + color[ 0 ] += si->lightImage->pixels[ i * 4 + 0 ]; + color[ 1 ] += si->lightImage->pixels[ i * 4 + 1 ]; + color[ 2 ] += si->lightImage->pixels[ i * 4 + 2 ]; + color[ 3 ] += si->lightImage->pixels[ i * 4 + 3 ]; + } + + if( VectorLength( si->color ) <= 0.0f ) + { + ColorNormalize( color, si->color ); + VectorScale( color, (1.0f / count), si->averageColor ); + } + else + { + VectorCopy( si->color, si->averageColor ); + } +} + + + +/* +ShaderInfoForShader() +finds a shaderinfo for a named shader +*/ + +#define MAX_SHADER_DEPRECATION_DEPTH 16 + +shaderInfo_t *ShaderInfoForShader( const char *shaderName ) +{ + int i; + int deprecationDepth; + shaderInfo_t *si; + char shader[ MAX_QPATH ]; + + /* dummy check */ + if( shaderName == NULL || shaderName[ 0 ] == '\0' ) + { + Sys_Printf( "WARNING: Null or empty shader name\n" ); + shaderName = "missing"; + } + + /* strip off extension */ + strcpy( shader, shaderName ); + StripExtension( shader ); + + /* search for it */ + deprecationDepth = 0; + for( i = 0; i < numShaderInfo; i++ ) + { + si = &shaderInfo[ i ]; + if( !Q_stricmp( shader, si->shader ) ) + { + /* check if shader is deprecated */ + if (deprecationDepth < MAX_SHADER_DEPRECATION_DEPTH && si->deprecateShader && si->deprecateShader[ 0 ] ) + { + /* override name */ + strcpy( shader, si->deprecateShader ); + StripExtension( shader ); + /* increase deprecation depth */ + deprecationDepth++; + if (deprecationDepth == MAX_SHADER_DEPRECATION_DEPTH) + Sys_Printf("WARNING: Max deprecation depth of %i is reached on shader '%s'\n", MAX_SHADER_DEPRECATION_DEPTH, shader); + /* search again from beginning */ + i = -1; + continue; + } + + /* load image if necessary */ + if( si->finished == qfalse ) + { + LoadShaderImages( si ); + FinishShader( si ); + } + + /* return it */ + return si; + } + } + + /* allocate a default shader */ + si = AllocShaderInfo(); + strcpy( si->shader, shader ); + LoadShaderImages( si ); + FinishShader( si ); + + /* return it */ + return si; +} + + + +/* +GetTokenAppend() - ydnar +gets a token and appends its text to the specified buffer +*/ + +static int oldScriptLine = 0; +static int tabDepth = 0; + +qboolean GetTokenAppend( char *buffer, qboolean crossline ) +{ + qboolean r; + int i; + + + /* get the token */ + r = GetToken( crossline ); + if( r == qfalse || buffer == NULL || token[ 0 ] == '\0' ) + return r; + + /* pre-tabstops */ + if( token[ 0 ] == '}' ) + tabDepth--; + + /* append? */ + if( oldScriptLine != scriptline ) + { + strcat( buffer, "\n" ); + for( i = 0; i < tabDepth; i++ ) + strcat( buffer, "\t" ); + } + else + strcat( buffer, " " ); + oldScriptLine = scriptline; + strcat( buffer, token ); + + /* post-tabstops */ + if( token[ 0 ] == '{' ) + tabDepth++; + + /* return */ + return r; +} + + +void Parse1DMatrixAppend( char *buffer, int x, vec_t *m ) +{ + int i; + + + if( !GetTokenAppend( buffer, qtrue ) || strcmp( token, "(" ) ) + Error( "Parse1DMatrixAppend(): line %d: ( not found!", scriptline ); + for( i = 0; i < x; i++ ) + { + if( !GetTokenAppend( buffer, qfalse ) ) + Error( "Parse1DMatrixAppend(): line %d: Number not found!", scriptline ); + m[ i ] = atof( token ); + } + if( !GetTokenAppend( buffer, qtrue ) || strcmp( token, ")" ) ) + Error( "Parse1DMatrixAppend(): line %d: ) not found!", scriptline ); +} + + + + +/* +ParseShaderFile() +parses a shader file into discrete shaderInfo_t +*/ + +static void ParseShaderFile( const char *filename ) +{ + int i, val; + shaderInfo_t *si; + char *suffix, temp[ 1024 ]; + char shaderText[ 8192 ]; /* ydnar: fixme (make this bigger?) */ + + + /* init */ + si = NULL; + shaderText[ 0 ] = '\0'; + + /* load the shader */ + LoadScriptFile( filename, 0 ); + + /* tokenize it */ + while( 1 ) + { + /* copy shader text to the shaderinfo */ + if( si != NULL && shaderText[ 0 ] != '\0' ) + { + strcat( shaderText, "\n" ); + si->shaderText = safe_malloc( strlen( shaderText ) + 1 ); + strcpy( si->shaderText, shaderText ); + //% if( VectorLength( si->vecs[ 0 ] ) ) + //% Sys_Printf( "%s\n", shaderText ); + } + + /* ydnar: clear shader text buffer */ + shaderText[ 0 ] = '\0'; + + /* test for end of file */ + if( !GetToken( qtrue ) ) + break; + + /* shader name is initial token */ + si = AllocShaderInfo(); + strcpy( si->shader, token ); + + /* ignore ":q3map" suffix */ + suffix = strstr( si->shader, ":q3map" ); + if( suffix != NULL ) + *suffix = '\0'; + + /* handle { } section */ + if( !GetTokenAppend( shaderText, qtrue ) ) + break; + if( strcmp( token, "{" ) ) + { + if( si != NULL ) + Error( "ParseShaderFile(): %s, line %d: { not found!\nFound instead: %s\nLast known shader: %s", + filename, scriptline, token, si->shader ); + else + Error( "ParseShaderFile(): %s, line %d: { not found!\nFound instead: %s", + filename, scriptline, token ); + } + + while( 1 ) + { + /* get the next token */ + if( !GetTokenAppend( shaderText, qtrue ) ) + break; + if( !strcmp( token, "}" ) ) + break; + + + /* ----------------------------------------------------------------- + shader stages (passes) + ----------------------------------------------------------------- */ + + /* parse stage directives */ + if( !strcmp( token, "{" ) ) + { + si->hasPasses = qtrue; + while( 1 ) + { + if( !GetTokenAppend( shaderText, qtrue ) ) + break; + if( !strcmp( token, "}" ) ) + break; + + /* only care about images if we don't have a editor/light image */ + if( si->editorImagePath[ 0 ] == '\0' && si->lightImagePath[ 0 ] == '\0' && si->implicitImagePath[ 0 ] == '\0' ) + { + /* digest any images */ + if( !Q_stricmp( token, "map" ) || + !Q_stricmp( token, "clampMap" ) || + !Q_stricmp( token, "animMap" ) || + !Q_stricmp( token, "clampAnimMap" ) || + !Q_stricmp( token, "clampMap" ) || + !Q_stricmp( token, "mapComp" ) || + !Q_stricmp( token, "mapNoComp" ) ) + { + /* skip one token for animated stages */ + if( !Q_stricmp( token, "animMap" ) || !Q_stricmp( token, "clampAnimMap" ) ) + GetTokenAppend( shaderText, qfalse ); + + /* get an image */ + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] != '*' && token[ 0 ] != '$' ) + { + strcpy( si->lightImagePath, token ); + DefaultExtension( si->lightImagePath, ".tga" ); + + /* debug code */ + //% Sys_FPrintf( SYS_VRB, "Deduced shader image: %s\n", si->lightImagePath ); + } + } + } + } + } + + + /* ----------------------------------------------------------------- + surfaceparm * directives + ----------------------------------------------------------------- */ + + /* match surfaceparm */ + else if( !Q_stricmp( token, "surfaceparm" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( ApplySurfaceParm( token, &si->contentFlags, &si->surfaceFlags, &si->compileFlags ) == qfalse ) + Sys_Printf( "WARNING: Unknown surfaceparm: \"%s\"\n", token ); + } + + + /* ----------------------------------------------------------------- + game-related shader directives + ----------------------------------------------------------------- */ + + /* ydnar: fogparms (for determining fog volumes) */ + else if( !Q_stricmp( token, "fogparms" ) ) + si->fogParms = qtrue; + + /* ydnar: polygonoffset (for no culling) */ + else if( !Q_stricmp( token, "polygonoffset" ) ) + si->polygonOffset = qtrue; + + /* tesssize is used to force liquid surfaces to subdivide */ + else if( !Q_stricmp( token, "tessSize" ) || !Q_stricmp( token, "q3map_tessSize" ) /* sof2 */ ) + { + GetTokenAppend( shaderText, qfalse ); + si->subdivisions = atof( token ); + } + + /* cull none will set twoSided (ydnar: added disable too) */ + else if ( !Q_stricmp( token, "cull" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( !Q_stricmp( token, "none" ) || !Q_stricmp( token, "disable" ) || !Q_stricmp( token, "twosided" ) ) + si->twoSided = qtrue; + } + + /* deformVertexes autosprite[ 2 ] + we catch this so autosprited surfaces become point + lights instead of area lights */ + else if( !Q_stricmp( token, "deformVertexes" ) ) + { + GetTokenAppend( shaderText, qfalse ); + + /* deformVertexes autosprite(2) */ + if( !Q_strncasecmp( token, "autosprite", 10 ) ) + { + /* set it as autosprite and detail */ + si->autosprite = qtrue; + ApplySurfaceParm( "detail", &si->contentFlags, &si->surfaceFlags, &si->compileFlags ); + + /* ydnar: gs mods: added these useful things */ + si->noClip = qtrue; + si->notjunc = qtrue; + } + + /* deformVertexes move (ydnar: for particle studio support) */ + if( !Q_stricmp( token, "move") ) + { + vec3_t amt, mins, maxs; + float base, amp; + + + /* get move amount */ + GetTokenAppend( shaderText, qfalse ); amt[ 0 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); amt[ 1 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); amt[ 2 ] = atof( token ); + + /* skip func */ + GetTokenAppend( shaderText, qfalse ); + + /* get base and amplitude */ + GetTokenAppend( shaderText, qfalse ); base = atof( token ); + GetTokenAppend( shaderText, qfalse ); amp = atof( token ); + + /* calculate */ + VectorScale( amt, base, mins ); + VectorMA( mins, amp, amt, maxs ); + VectorAdd( si->mins, mins, si->mins ); + VectorAdd( si->maxs, maxs, si->maxs ); + } + } + + /* light (old-style flare specification) */ + else if( !Q_stricmp( token, "light" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->flareShader = game->flareShader; + } + + /* ydnar: damageShader (sof2 mods) */ + else if( !Q_stricmp( token, "damageShader" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] != '\0' ) + { + si->damageShader = safe_malloc( strlen( token ) + 1 ); + strcpy( si->damageShader, token ); + } + GetTokenAppend( shaderText, qfalse ); /* don't do anything with health */ + } + + /* ydnar: enemy territory implicit shaders */ + else if( !Q_stricmp( token, "implicitMap" ) ) + { + si->implicitMap = IM_OPAQUE; + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] == '-' && token[ 1 ] == '\0' ) + sprintf( si->implicitImagePath, "%s.tga", si->shader ); + else + strcpy( si->implicitImagePath, token ); + } + + else if( !Q_stricmp( token, "implicitMask" ) ) + { + si->implicitMap = IM_MASKED; + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] == '-' && token[ 1 ] == '\0' ) + sprintf( si->implicitImagePath, "%s.tga", si->shader ); + else + strcpy( si->implicitImagePath, token ); + } + + else if( !Q_stricmp( token, "implicitBlend" ) ) + { + si->implicitMap = IM_MASKED; + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] == '-' && token[ 1 ] == '\0' ) + sprintf( si->implicitImagePath, "%s.tga", si->shader ); + else + strcpy( si->implicitImagePath, token ); + } + + + /* ----------------------------------------------------------------- + image directives + ----------------------------------------------------------------- */ + + /* qer_editorimage */ + else if( !Q_stricmp( token, "qer_editorImage" ) ) + { + GetTokenAppend( shaderText, qfalse ); + strcpy( si->editorImagePath, token ); + DefaultExtension( si->editorImagePath, ".tga" ); + } + + /* ydnar: q3map_normalimage (bumpmapping normal map) */ + else if( !Q_stricmp( token, "q3map_normalImage" ) ) + { + GetTokenAppend( shaderText, qfalse ); + strcpy( si->normalImagePath, token ); + DefaultExtension( si->normalImagePath, ".tga" ); + } + + /* q3map_lightimage */ + else if( !Q_stricmp( token, "q3map_lightImage" ) ) + { + GetTokenAppend( shaderText, qfalse ); + strcpy( si->lightImagePath, token ); + DefaultExtension( si->lightImagePath, ".tga" ); + } + + /* ydnar: skyparms */ + else if( !Q_stricmp( token, "skyParms" ) ) + { + /* get image base */ + GetTokenAppend( shaderText, qfalse ); + + /* ignore bogus paths */ + if( Q_stricmp( token, "-" ) && Q_stricmp( token, "full" ) ) + { + strcpy( si->skyParmsImageBase, token ); + + /* use top image as sky light image */ + if( si->lightImagePath[ 0 ] == '\0' ) + sprintf( si->lightImagePath, "%s_up.tga", si->skyParmsImageBase ); + } + + /* skip rest of line */ + GetTokenAppend( shaderText, qfalse ); + GetTokenAppend( shaderText, qfalse ); + } + + /* ----------------------------------------------------------------- + q3map_* directives + ----------------------------------------------------------------- */ + + /* q3map_sun + color will be normalized, so it doesn't matter what range you use + intensity falls off with angle but not distance 100 is a fairly bright sun + degree of 0 = from the east, 90 = north, etc. altitude of 0 = sunrise/set, 90 = noon + ydnar: sof2map has bareword 'sun' token, so we support that as well */ + else if( !Q_stricmp( token, "sun" ) /* sof2 */ || !Q_stricmp( token, "q3map_sun" ) || !Q_stricmp( token, "q3map_sunExt" ) ) + { + float a, b; + sun_t *sun; + qboolean ext; + + + /* ydnar: extended sun directive? */ + if( !Q_stricmp( token, "q3map_sunext" ) ) + ext = qtrue; + + /* allocate sun */ + sun = safe_malloc( sizeof( *sun ) ); + memset( sun, 0, sizeof( *sun ) ); + + /* set style */ + sun->style = si->lightStyle; + + /* get color */ + GetTokenAppend( shaderText, qfalse ); + sun->color[ 0 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); + sun->color[ 1 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); + sun->color[ 2 ] = atof( token ); + + /* normalize it */ + VectorNormalize( sun->color, sun->color ); + + /* scale color by brightness */ + GetTokenAppend( shaderText, qfalse ); + sun->photons = atof( token ); + + /* get sun angle/elevation */ + GetTokenAppend( shaderText, qfalse ); + a = atof( token ); + a = a / 180.0f * Q_PI; + + GetTokenAppend( shaderText, qfalse ); + b = atof( token ); + b = b / 180.0f * Q_PI; + + sun->direction[ 0 ] = cos( a ) * cos( b ); + sun->direction[ 1 ] = sin( a ) * cos( b ); + sun->direction[ 2 ] = sin( b ); + + /* get filter radius from shader */ + sun->filterRadius = si->lightFilterRadius; + + /* ydnar: get sun angular deviance/samples */ + if( ext && TokenAvailable() ) + { + GetTokenAppend( shaderText, qfalse ); + sun->deviance = atof( token ); + sun->deviance = sun->deviance / 180.0f * Q_PI; + + GetTokenAppend( shaderText, qfalse ); + sun->numSamples = atoi( token ); + } + + /* store sun */ + sun->next = si->sun; + si->sun = sun; + + /* apply sky surfaceparm */ + ApplySurfaceParm( "sky", &si->contentFlags, &si->surfaceFlags, &si->compileFlags ); + + /* don't process any more tokens on this line */ + continue; + } + + /* match q3map_ */ + else if( !Q_strncasecmp( token, "q3map_", 6 ) ) + { + /* ydnar: q3map_baseShader (inherit this shader's parameters) */ + if( !Q_stricmp( token, "q3map_baseShader" ) ) + { + shaderInfo_t *si2; + qboolean oldWarnImage; + + + /* get shader */ + GetTokenAppend( shaderText, qfalse ); + //% Sys_FPrintf( SYS_VRB, "Shader %s has base shader %s\n", si->shader, token ); + oldWarnImage = warnImage; + warnImage = qfalse; + si2 = ShaderInfoForShader( token ); + warnImage = oldWarnImage; + + /* subclass it */ + if( si2 != NULL ) + { + /* preserve name */ + strcpy( temp, si->shader ); + + /* copy shader */ + memcpy( si, si2, sizeof( *si ) ); + + /* restore name and set to unfinished */ + strcpy( si->shader, temp ); + si->shaderWidth = 0; + si->shaderHeight = 0; + si->finished = qfalse; + } + } + + /* ydnar: q3map_surfacemodel */ + else if( !Q_stricmp( token, "q3map_surfacemodel" ) ) + { + surfaceModel_t *model; + + /* allocate new model and attach it */ + model = safe_malloc( sizeof( *model ) ); + memset( model, 0, sizeof( *model ) ); + model->next = si->surfaceModel; + si->surfaceModel = model; + + /* get parameters */ + GetTokenAppend( shaderText, qfalse ); + strcpy( model->model, token ); + + GetTokenAppend( shaderText, qfalse ); + model->density = atof( token ); + GetTokenAppend( shaderText, qfalse ); + model->odds = atof( token ); + + GetTokenAppend( shaderText, qfalse ); + model->minScale = atof( token ); + GetTokenAppend( shaderText, qfalse ); + model->maxScale = atof( token ); + + GetTokenAppend( shaderText, qfalse ); + model->minAngle = atof( token ); + GetTokenAppend( shaderText, qfalse ); + model->maxAngle = atof( token ); + + GetTokenAppend( shaderText, qfalse ); + model->oriented = (token[ 0 ] == '1' ? qtrue : qfalse); + } + + /* ydnar/sd: q3map_foliage */ + else if( !Q_stricmp( token, "q3map_foliage" ) ) + { + foliage_t *foliage; + + + /* allocate new foliage struct and attach it */ + foliage = safe_malloc( sizeof( *foliage ) ); + memset( foliage, 0, sizeof( *foliage ) ); + foliage->next = si->foliage; + si->foliage = foliage; + + /* get parameters */ + GetTokenAppend( shaderText, qfalse ); + strcpy( foliage->model, token ); + + GetTokenAppend( shaderText, qfalse ); + foliage->scale = atof( token ); + GetTokenAppend( shaderText, qfalse ); + foliage->density = atof( token ); + GetTokenAppend( shaderText, qfalse ); + foliage->odds = atof( token ); + GetTokenAppend( shaderText, qfalse ); + foliage->inverseAlpha = atoi( token ); + } + + /* ydnar: q3map_bounce (fraction of light to re-emit during radiosity passes) */ + else if( !Q_stricmp( token, "q3map_bounce" ) || !Q_stricmp( token, "q3map_bounceScale" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->bounceScale = atof( token ); + } + + /* ydnar/splashdamage: q3map_skyLight */ + else if( !Q_stricmp( token, "q3map_skyLight" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->skyLightValue = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->skyLightIterations = atoi( token ); + + /* clamp */ + if( si->skyLightValue < 0.0f ) + si->skyLightValue = 0.0f; + if( si->skyLightIterations < 2 ) + si->skyLightIterations = 2; + } + + /* q3map_surfacelight */ + else if( !Q_stricmp( token, "q3map_surfacelight" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->value = atof( token ); + } + + /* q3map_lightStyle (sof2/jk2 lightstyle) */ + else if( !Q_stricmp( token, "q3map_lightStyle" ) ) + { + GetTokenAppend( shaderText, qfalse ); + val = atoi( token ); + if( val < 0 ) + val = 0; + else if( val > LS_NONE ) + val = LS_NONE; + si->lightStyle = val; + } + + /* wolf: q3map_lightRGB */ + else if( !Q_stricmp( token, "q3map_lightRGB" ) ) + { + VectorClear( si->color ); + GetTokenAppend( shaderText, qfalse ); + si->color[ 0 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->color[ 1 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->color[ 2 ] = atof( token ); + ColorNormalize( si->color, si->color ); + } + + /* q3map_lightSubdivide */ + else if( !Q_stricmp( token, "q3map_lightSubdivide" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->lightSubdivide = atoi( token ); + } + + /* q3map_backsplash */ + else if( !Q_stricmp( token, "q3map_backsplash" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->backsplashFraction = atof( token ) * 0.01f; + GetTokenAppend( shaderText, qfalse ); + si->backsplashDistance = atof( token ); + } + + /* q3map_floodLight */ + else if( !Q_stricmp( token, "q3map_floodLight" ) ) + { + /* get color */ + GetTokenAppend( shaderText, qfalse ); + si->floodlightRGB[ 0 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->floodlightRGB[ 1 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->floodlightRGB[ 2 ] = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->floodlightDistance = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->floodlightIntensity = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->floodlightDirectionScale = atof( token ); + } + + /* jal: q3map_nodirty : skip dirty */ + else if( !Q_stricmp( token, "q3map_nodirty" ) ) + { + si->noDirty = qtrue; + } + + /* q3map_lightmapSampleSize */ + else if( !Q_stricmp( token, "q3map_lightmapSampleSize" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->lightmapSampleSize = atoi( token ); + } + + /* q3map_lightmapSampleOffset */ + else if( !Q_stricmp( token, "q3map_lightmapSampleOffset" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->lightmapSampleOffset = atof( token ); + } + + /* ydnar: q3map_lightmapFilterRadius */ + else if( !Q_stricmp( token, "q3map_lightmapFilterRadius" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->lmFilterRadius = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->lightFilterRadius = atof( token ); + } + + /* ydnar: q3map_lightmapAxis [xyz] */ + else if( !Q_stricmp( token, "q3map_lightmapAxis" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( !Q_stricmp( token, "x" ) ) + VectorSet( si->lightmapAxis, 1, 0, 0 ); + else if( !Q_stricmp( token, "y" ) ) + VectorSet( si->lightmapAxis, 0, 1, 0 ); + else if( !Q_stricmp( token, "z" ) ) + VectorSet( si->lightmapAxis, 0, 0, 1 ); + else + { + Sys_Printf( "WARNING: Unknown value for lightmap axis: %s\n", token ); + VectorClear( si->lightmapAxis ); + } + } + + /* ydnar: q3map_lightmapSize (for autogenerated shaders + external tga lightmaps) */ + else if( !Q_stricmp( token, "q3map_lightmapSize" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->lmCustomWidth = atoi( token ); + GetTokenAppend( shaderText, qfalse ); + si->lmCustomHeight = atoi( token ); + + /* must be a power of 2 */ + if( ((si->lmCustomWidth - 1) & si->lmCustomWidth) || + ((si->lmCustomHeight - 1) & si->lmCustomHeight) ) + { + Sys_Printf( "WARNING: Non power-of-two lightmap size specified (%d, %d)\n", + si->lmCustomWidth, si->lmCustomHeight ); + si->lmCustomWidth = lmCustomSize; + si->lmCustomHeight = lmCustomSize; + } + } + + /* ydnar: q3map_lightmapBrightness N (for autogenerated shaders + external tga lightmaps) */ + else if( !Q_stricmp( token, "q3map_lightmapBrightness" ) || !Q_stricmp( token, "q3map_lightmapGamma" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->lmBrightness = atof( token ); + if( si->lmBrightness < 0 ) + si->lmBrightness = 1.0; + } + + /* q3map_vertexScale (scale vertex lighting by this fraction) */ + else if( !Q_stricmp( token, "q3map_vertexScale" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->vertexScale = atof( token ); + } + + /* q3map_noVertexLight */ + else if( !Q_stricmp( token, "q3map_noVertexLight" ) ) + { + si->noVertexLight = qtrue; + } + + /* q3map_flare[Shader] */ + else if( !Q_stricmp( token, "q3map_flare" ) || !Q_stricmp( token, "q3map_flareShader" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] != '\0' ) + { + si->flareShader = safe_malloc( strlen( token ) + 1 ); + strcpy( si->flareShader, token ); + } + } + + /* q3map_backShader */ + else if( !Q_stricmp( token, "q3map_backShader" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] != '\0' ) + { + si->backShader = safe_malloc( strlen( token ) + 1 ); + strcpy( si->backShader, token ); + } + } + + /* ydnar: q3map_cloneShader */ + else if ( !Q_stricmp( token, "q3map_cloneShader" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] != '\0' ) + { + si->cloneShader = safe_malloc( strlen( token ) + 1 ); + strcpy( si->cloneShader, token ); + } + } + + /* q3map_remapShader */ + else if( !Q_stricmp( token, "q3map_remapShader" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] != '\0' ) + { + si->remapShader = safe_malloc( strlen( token ) + 1 ); + strcpy( si->remapShader, token ); + } + } + + /* q3map_deprecateShader */ + else if( !Q_stricmp( token, "q3map_deprecateShader" ) ) + { + GetTokenAppend( shaderText, qfalse ); + if( token[ 0 ] != '\0' ) + { + + si->deprecateShader = safe_malloc( strlen( token ) + 1 ); + strcpy( si->deprecateShader, token ); + } + } + + /* ydnar: q3map_offset */ + else if( !Q_stricmp( token, "q3map_offset" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->offset = atof( token ); + } + + /* ydnar: q3map_fur */ + else if( !Q_stricmp( token, "q3map_fur" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->furNumLayers = atoi( token ); + GetTokenAppend( shaderText, qfalse ); + si->furOffset = atof( token ); + GetTokenAppend( shaderText, qfalse ); + si->furFade = atof( token ); + } + + /* ydnar: gs mods: legacy support for terrain/terrain2 shaders */ + else if( !Q_stricmp( token, "q3map_terrain" ) ) + { + /* team arena terrain is assumed to be nonplanar, with full normal averaging, + passed through the metatriangle surface pipeline, with a lightmap axis on z */ + si->legacyTerrain = qtrue; + si->noClip = qtrue; + si->notjunc = qtrue; + si->indexed = qtrue; + si->nonplanar = qtrue; + si->forceMeta = qtrue; + si->shadeAngleDegrees = 179.0f; + //% VectorSet( si->lightmapAxis, 0, 0, 1 ); /* ydnar 2002-09-21: turning this off for better lightmapping of cliff faces */ + } + + /* ydnar: picomodel: q3map_forceMeta (forces brush faces and/or triangle models to go through the metasurface pipeline) */ + else if( !Q_stricmp( token, "q3map_forceMeta" ) ) + { + si->forceMeta = qtrue; + } + + /* ydnar: gs mods: q3map_shadeAngle */ + else if( !Q_stricmp( token, "q3map_shadeAngle" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->shadeAngleDegrees = atof( token ); + } + + /* ydnar: q3map_textureSize (substitute for q3map_lightimage derivation for terrain) */ + else if( !Q_stricmp( token, "q3map_textureSize" ) ) + { + GetTokenAppend( shaderText, qfalse ); + si->shaderWidth = atoi( token ); + GetTokenAppend( shaderText, qfalse ); + si->shaderHeight = atoi( token ); + } + + /* ydnar: gs mods: q3map_tcGen